code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
import qualified Data.Sequence as Seq import LogicGrowsOnTrees (exploreTree) import LogicGrowsOnTrees.Examples.Queens (nqueensUsingBitsSolutions) main = print . exploreTree . fmap Seq.singleton . nqueensUsingBitsSolutions $ 5
gcross/LogicGrowsOnTrees
LogicGrowsOnTrees/tutorial/tutorial-2.hs
Haskell
bsd-2-clause
226
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-| All RPC calls are run within this monad. It encapsulates: * IO operations, * failures, * working with the daemon state. Code that is specific either to the configuration or the lock management, should go into their corresponding dedicated modules. -} {- Copyright (C) 2014 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.WConfd.Monad ( DaemonHandle , dhConfigPath , mkDaemonHandle , WConfdMonadInt , runWConfdMonadInt , WConfdMonad , daemonHandle , modifyConfigState , modifyConfigStateWithImmediate , forceConfigStateDistribution , readConfigState , modifyConfigDataErr_ , modifyLockWaiting , modifyLockWaiting_ , readLockWaiting , readLockAllocation , modifyTempResState , modifyTempResStateErr , readTempResState ) where import Control.Applicative import Control.Arrow ((&&&), second) import Control.Monad import Control.Monad.Base import Control.Monad.Error import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans.Control import Data.Functor.Identity import Data.IORef.Lifted import Data.Monoid (Any(..)) import qualified Data.Set as S import Data.Tuple (swap) import System.Time (getClockTime) import qualified Text.JSON as J import Ganeti.BasicTypes import Ganeti.Errors import Ganeti.JQueue (notifyJob) import Ganeti.Lens import Ganeti.Locking.Allocation (LockAllocation) import Ganeti.Locking.Locks import Ganeti.Locking.Waiting (getAllocation) import Ganeti.Logging import Ganeti.Logging.WriterLog import Ganeti.Objects (ConfigData) import Ganeti.Utils.AsyncWorker import Ganeti.Utils.IORef import Ganeti.WConfd.ConfigState import Ganeti.WConfd.TempRes -- * Pure data types used in the monad -- | The state of the daemon, capturing both the configuration state and the -- locking state. data DaemonState = DaemonState { dsConfigState :: ConfigState , dsLockWaiting :: GanetiLockWaiting , dsTempRes :: TempResState } $(makeCustomLenses ''DaemonState) data DaemonHandle = DaemonHandle { dhDaemonState :: IORef DaemonState -- ^ The current state of the daemon , dhConfigPath :: FilePath -- ^ The configuration file path -- all static information that doesn't change during the life-time of the -- daemon should go here; -- all IDs of threads that do asynchronous work should probably also go here , dhSaveConfigWorker :: AsyncWorker Any () , dhSaveLocksWorker :: AsyncWorker () () , dhSaveTempResWorker :: AsyncWorker () () } mkDaemonHandle :: FilePath -> ConfigState -> GanetiLockWaiting -> TempResState -> (IO ConfigState -> [AsyncWorker () ()] -> ResultG (AsyncWorker Any ())) -- ^ A function that creates a worker that asynchronously -- saves the configuration to the master file. -> (IO ConfigState -> ResultG (AsyncWorker () ())) -- ^ A function that creates a worker that asynchronously -- distributes the configuration to master candidates -> (IO ConfigState -> ResultG (AsyncWorker () ())) -- ^ A function that creates a worker that asynchronously -- distributes SSConf to nodes -> (IO GanetiLockWaiting -> ResultG (AsyncWorker () ())) -- ^ A function that creates a worker that asynchronously -- saves the lock allocation state. -> (IO TempResState -> ResultG (AsyncWorker () ())) -- ^ A function that creates a worker that asynchronously -- saves the temporary reservations state. -> ResultG DaemonHandle mkDaemonHandle cpath cstat lstat trstat saveWorkerFn distMCsWorkerFn distSSConfWorkerFn saveLockWorkerFn saveTempResWorkerFn = do ds <- newIORef $ DaemonState cstat lstat trstat let readConfigIO = dsConfigState `liftM` readIORef ds :: IO ConfigState ssconfWorker <- distSSConfWorkerFn readConfigIO distMCsWorker <- distMCsWorkerFn readConfigIO saveWorker <- saveWorkerFn readConfigIO [ distMCsWorker , ssconfWorker ] saveLockWorker <- saveLockWorkerFn $ dsLockWaiting `liftM` readIORef ds saveTempResWorker <- saveTempResWorkerFn $ dsTempRes `liftM` readIORef ds return $ DaemonHandle ds cpath saveWorker saveLockWorker saveTempResWorker -- * The monad and its instances -- | A type alias for easier referring to the actual content of the monad -- when implementing its instances. type WConfdMonadIntType = ReaderT DaemonHandle IO -- | The internal part of the monad without error handling. newtype WConfdMonadInt a = WConfdMonadInt { getWConfdMonadInt :: WConfdMonadIntType a } deriving (Functor, Applicative, Monad, MonadIO, MonadBase IO, MonadLog) instance MonadBaseControl IO WConfdMonadInt where newtype StM WConfdMonadInt b = StMWConfdMonadInt { runStMWConfdMonadInt :: StM WConfdMonadIntType b } liftBaseWith f = WConfdMonadInt . liftBaseWith $ \r -> f (liftM StMWConfdMonadInt . r . getWConfdMonadInt) restoreM = WConfdMonadInt . restoreM . runStMWConfdMonadInt -- | Runs the internal part of the WConfdMonad monad on a given daemon -- handle. runWConfdMonadInt :: WConfdMonadInt a -> DaemonHandle -> IO a runWConfdMonadInt (WConfdMonadInt k) = runReaderT k -- | The complete monad with error handling. type WConfdMonad = ResultT GanetiException WConfdMonadInt -- | A pure monad that logs and reports errors used for atomic modifications. type AtomicModifyMonad a = ResultT GanetiException WriterLog a -- * Basic functions in the monad -- | Returns the daemon handle. daemonHandle :: WConfdMonad DaemonHandle daemonHandle = lift . WConfdMonadInt $ ask -- | Returns the current configuration, given a handle readConfigState :: WConfdMonad ConfigState readConfigState = liftM dsConfigState . readIORef . dhDaemonState =<< daemonHandle -- | Atomically modifies the configuration state in the WConfdMonad -- with a computation that can possibly fail; immediately afterwards, -- while config write is still going on, do the followup action. Return -- only after replication is finished. modifyConfigStateErrWithImmediate :: (TempResState -> ConfigState -> AtomicModifyMonad (a, ConfigState)) -> WConfdMonad () -> WConfdMonad a modifyConfigStateErrWithImmediate f immediateFollowup = do dh <- daemonHandle now <- liftIO getClockTime -- If the configuration is modified, we also bump its serial number. -- In order to determine if we need to save, we report if it's modified -- as well as if it needs to be distributed synchronously. let unpackResult cs (r, cs') | cs /= cs' = ( (r, True, needsFullDist cs cs') , over csConfigDataL (bumpSerial now) cs' ) | otherwise = ((r, False, False), cs') let modCS ds@(DaemonState { dsTempRes = tr }) = mapMOf2 dsConfigStateL (\cs -> liftM (unpackResult cs) (f tr cs)) ds (r, modified, distSync) <- atomicModifyIORefErrLog (dhDaemonState dh) (liftM swap . modCS) if modified then if distSync then do logDebug "Triggering config write\ \ together with full synchronous distribution" res <- liftBase . triggerWithResult (Any True) $ dhSaveConfigWorker dh immediateFollowup wait res logDebug "Config write and distribution finished" else do -- trigger the config. saving worker and wait for it logDebug "Triggering config write\ \ and asynchronous distribution" res <- liftBase . triggerWithResult (Any False) $ dhSaveConfigWorker dh immediateFollowup wait res logDebug "Config writer finished with local task" else immediateFollowup return r -- | Atomically modifies the configuration state in the WConfdMonad -- with a computation that can possibly fail. modifyConfigStateErr :: (TempResState -> ConfigState -> AtomicModifyMonad (a, ConfigState)) -> WConfdMonad a modifyConfigStateErr = flip modifyConfigStateErrWithImmediate (return ()) -- | Atomically modifies the configuration state in the WConfdMonad -- with a computation that can possibly fail. modifyConfigStateErr_ :: (TempResState -> ConfigState -> AtomicModifyMonad ConfigState) -> WConfdMonad () modifyConfigStateErr_ f = modifyConfigStateErr ((liftM ((,) ()) .) . f) -- | Atomically modifies the configuration state in the WConfdMonad. modifyConfigState :: (ConfigState -> (a, ConfigState)) -> WConfdMonad a modifyConfigState f = modifyConfigStateErr ((return .) . const f) -- | Atomically modifies the configuration state in WConfdMonad; immediately -- afterwards (while the config write-out is not necessarily finished) do -- another acation. modifyConfigStateWithImmediate :: (ConfigState -> (a, ConfigState)) -> WConfdMonad () -> WConfdMonad a modifyConfigStateWithImmediate f = modifyConfigStateErrWithImmediate ((return .) . const f) -- | Force the distribution of configuration without actually modifying it. -- -- We need a separate call for this operation, because 'modifyConfigState' only -- triggers the distribution when the configuration changes. forceConfigStateDistribution :: WConfdMonad () forceConfigStateDistribution = do logDebug "Forcing synchronous config write together with full distribution" dh <- daemonHandle liftBase . triggerAndWait (Any True) . dhSaveConfigWorker $ dh logDebug "Forced config write and distribution finished" -- | Atomically modifies the configuration data in the WConfdMonad -- with a computation that can possibly fail. modifyConfigDataErr_ :: (TempResState -> ConfigData -> AtomicModifyMonad ConfigData) -> WConfdMonad () modifyConfigDataErr_ f = modifyConfigStateErr_ (traverseOf csConfigDataL . f) -- | Atomically modifies the state of temporary reservations in -- WConfdMonad in the presence of possible errors. modifyTempResStateErr :: (ConfigData -> StateT TempResState ErrorResult a) -> WConfdMonad a modifyTempResStateErr f = do -- we use Compose to traverse the composition of applicative functors -- @ErrorResult@ and @(,) a@ let f' ds = traverseOf2 dsTempResL (runStateT (f (csConfigData . dsConfigState $ ds))) ds dh <- daemonHandle r <- toErrorBase $ atomicModifyIORefErr (dhDaemonState dh) (liftM swap . f') -- logDebug $ "Current temporary reservations: " ++ J.encode tr logDebug "Triggering temporary reservations write" liftBase . triggerAndWait_ . dhSaveTempResWorker $ dh logDebug "Temporary reservations write finished" return r -- | Atomically modifies the state of temporary reservations in -- WConfdMonad. modifyTempResState :: (ConfigData -> State TempResState a) -> WConfdMonad a modifyTempResState f = modifyTempResStateErr (mapStateT (return . runIdentity) . f) -- | Reads the state of of the configuration and temporary reservations -- in WConfdMonad. readTempResState :: WConfdMonad (ConfigData, TempResState) readTempResState = liftM (csConfigData . dsConfigState &&& dsTempRes) . readIORef . dhDaemonState =<< daemonHandle -- | Atomically modifies the lock waiting state in WConfdMonad. modifyLockWaiting :: (GanetiLockWaiting -> ( GanetiLockWaiting , (a, S.Set ClientId) )) -> WConfdMonad a modifyLockWaiting f = do dh <- lift . WConfdMonadInt $ ask let f' = (id &&& fst) . f (lockAlloc, (r, nfy)) <- atomicModifyWithLens (dhDaemonState dh) dsLockWaitingL f' logDebug $ "Current lock status: " ++ J.encode lockAlloc logDebug "Triggering lock state write" liftBase . triggerAndWait_ . dhSaveLocksWorker $ dh logDebug "Lock write finished" unless (S.null nfy) $ do logDebug . (++) "Locks became available for " . show $ S.toList nfy liftIO . mapM_ (notifyJob . ciPid) $ S.toList nfy logDebug "Finished notifying processes" return r -- | Atomically modifies the lock allocation state in WConfdMonad, not -- producing any result modifyLockWaiting_ :: (GanetiLockWaiting -> (GanetiLockWaiting, S.Set ClientId)) -> WConfdMonad () modifyLockWaiting_ = modifyLockWaiting . ((second $ (,) ()) .) -- | Read the lock waiting state in WConfdMonad. readLockWaiting :: WConfdMonad GanetiLockWaiting readLockWaiting = liftM dsLockWaiting . readIORef . dhDaemonState =<< daemonHandle -- | Read the underlying lock allocation. readLockAllocation :: WConfdMonad (LockAllocation GanetiLocks ClientId) readLockAllocation = liftM getAllocation readLockWaiting
ganeti-github-testing/ganeti-test-1
src/Ganeti/WConfd/Monad.hs
Haskell
bsd-2-clause
14,252
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE TemplateHaskell #-} module Bones.Skeletons.BranchAndBound.HdpH.Types where import Control.Parallel.HdpH (Closure, Par, StaticDecl, declare, mkClosure, static) import GHC.Generics (Generic) -- Functions required to specify a B&B computation type BBNode a b s = (a, b, s) bound :: BBNode a b s -> b bound (_, b, _) = b solution :: BBNode a b s -> a solution (s, _ , _ )= s candidates :: BBNode a b s -> s candidates (_, _, s) = s data BAndBFunctions g a b s = BAndBFunctions { orderedGenerator :: g -> BBNode a b s -> Par [Par (BBNode a b s)] , pruningHeuristic :: g -> BBNode a b s -> Par b , compareB :: b -> b -> Ordering } deriving (Generic) data ToCFns a b s = ToCFns { toCa :: a -> Closure a , toCb :: b -> Closure b , toCs :: s -> Closure s , toCnode :: (a, b, s) -> Closure (a, b, s) } deriving (Generic) data PruneType = NoPrune | Prune | PruneLevel toClosureUnit :: Closure () toClosureUnit = $(mkClosure [| unit |]) unit :: () unit = () -- Static Information $(return []) -- TH Workaround declareStatic :: StaticDecl declareStatic = mconcat [ declare $(static 'unit) ]
BlairArchibald/bones
lib/src/Bones/Skeletons/BranchAndBound/HdpH/Types.hs
Haskell
bsd-3-clause
1,295
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Ordinal.ET.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.Ordinal.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale ET Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = examples (OrdinalData 4) [ "4." , "neljas" , "Neljas" ]
facebookincubator/duckling
Duckling/Ordinal/ET/Corpus.hs
Haskell
bsd-3-clause
681
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Language.Haskell.GHC.ExactPrint.Types ( -- * Core Types Anns , emptyAnns , Annotation(..) , annNone , KeywordId(..) , Comment(..) -- * Positions , Pos , DeltaPos(..) , deltaRow, deltaColumn -- * AnnKey , AnnKey(..) , mkAnnKey , AnnConName(..) , annGetConstr -- * Other , Rigidity(..) -- * Internal Types , LayoutStartCol(..) , declFun ) where import Data.Data (Data, Typeable, toConstr,cast) import qualified DynFlags as GHC import qualified GHC import qualified Outputable as GHC import qualified Data.Map as Map -- --------------------------------------------------------------------- -- | A Haskell comment. The @AnnKeywordId@ is present if it has been converted -- from an @AnnKeywordId@ because the annotation must be interleaved into the -- stream and does not have a well-defined position data Comment = Comment { commentContents :: !String -- ^ The contents of the comment including separators , commentIdentifier :: !GHC.SrcSpan -- ^ Needed to uniquely identify two comments with the same contents , commentOrigin :: !(Maybe GHC.AnnKeywordId) -- ^ We sometimes turn syntax into comments in order to process them properly. } deriving (Eq,Typeable,Data,Ord) instance Show Comment where show (Comment cs ss o) = "(Comment " ++ show cs ++ " " ++ showGhc ss ++ " " ++ show o ++ ")" instance GHC.Outputable Comment where ppr x = GHC.text (show x) type Pos = (Int,Int) -- | A relative positions, row then column newtype DeltaPos = DP (Int,Int) deriving (Show,Eq,Ord,Typeable,Data) deltaRow, deltaColumn :: DeltaPos -> Int deltaRow (DP (r, _)) = r deltaColumn (DP (_, c)) = c -- | Marks the start column of a layout block. newtype LayoutStartCol = LayoutStartCol { getLayoutStartCol :: Int } deriving (Eq, Num) instance Show LayoutStartCol where show (LayoutStartCol sc) = "(LayoutStartCol " ++ show sc ++ ")" annNone :: Annotation annNone = Ann (DP (0,0)) [] [] [] Nothing Nothing data Annotation = Ann { -- The first three fields relate to interfacing up into the AST annEntryDelta :: !DeltaPos -- ^ Offset used to get to the start of the SrcSpan, from whatever the prior -- output was, including all annPriorComments (field below). , annPriorComments :: ![(Comment, DeltaPos)] -- ^ Comments coming after the last non-comment output of the preceding -- element but before the SrcSpan being annotated by this Annotation. If -- these are changed then annEntryDelta (field above) must also change to -- match. , annFollowingComments :: ![(Comment, DeltaPos)] -- ^ Comments coming after the last output for the element subject to this -- Annotation. These will only be added by AST transformations, and care -- must be taken not to disturb layout of following elements. -- The next three fields relate to interacing down into the AST , annsDP :: ![(KeywordId, DeltaPos)] -- ^ Annotations associated with this element. , annSortKey :: !(Maybe [GHC.SrcSpan]) -- ^ Captures the sort order of sub elements. This is needed when the -- sub-elements have been split (as in a HsLocalBind which holds separate -- binds and sigs) or for infix patterns where the order has been -- re-arranged. It is captured explicitly so that after the Delta phase a -- SrcSpan is used purely as an index into the annotations, allowing -- transformations of the AST including the introduction of new Located -- items or re-arranging existing ones. , annCapturedSpan :: !(Maybe AnnKey) -- ^ Occasionally we must calculate a SrcSpan for an unlocated list of -- elements which we must remember for the Print phase. e.g. the statements -- in a HsLet or HsDo. These must be managed as a group because they all -- need eo be vertically aligned for the Haskell layout rules, and this -- guarantees this property in the presence of AST edits. } deriving (Typeable,Eq) instance Show Annotation where show (Ann dp comments fcomments ans sk csp) = "(Ann (" ++ show dp ++ ") " ++ show comments ++ " " ++ show fcomments ++ " " ++ show ans ++ " " ++ showGhc sk ++ " " ++ showGhc csp ++ ")" -- | This structure holds a complete set of annotations for an AST type Anns = Map.Map AnnKey Annotation emptyAnns :: Anns emptyAnns = Map.empty -- | For every @Located a@, use the @SrcSpan@ and constructor name of -- a as the key, to store the standard annotation. -- These are used to maintain context in the AP and EP monads data AnnKey = AnnKey GHC.SrcSpan AnnConName deriving (Eq, Ord) -- More compact Show instance instance Show AnnKey where show (AnnKey ss cn) = "AnnKey " ++ showGhc ss ++ " " ++ show cn mkAnnKeyPrim :: (Data a) => GHC.Located a -> AnnKey mkAnnKeyPrim (GHC.L l a) = AnnKey l (annGetConstr a) -- |Make an unwrapped @AnnKey@ for the @LHsDecl@ case, a normal one otherwise. mkAnnKey :: (Data a) => GHC.Located a -> AnnKey mkAnnKey ld = case cast ld :: Maybe (GHC.LHsDecl GHC.RdrName) of Just d -> declFun mkAnnKeyPrim d Nothing -> mkAnnKeyPrim ld -- Holds the name of a constructor data AnnConName = CN { unConName :: String } deriving (Eq,Ord) -- More compact show instance instance Show AnnConName where show (CN s) = "CN " ++ show s annGetConstr :: (Data a) => a -> AnnConName annGetConstr a = CN (show $ toConstr a) -- | The different syntactic elements which are not represented in the -- AST. data KeywordId = G GHC.AnnKeywordId -- ^ A normal keyword | AnnSemiSep -- ^ A seperating comma | AnnComment Comment | AnnString String -- ^ Used to pass information from -- Delta to Print when we have to work -- out details from the original -- SrcSpan. #if __GLASGOW_HASKELL__ <= 710 | AnnUnicode GHC.AnnKeywordId -- ^ Used to indicate that we should print using unicode syntax if possible. #endif deriving (Eq,Ord) instance Show KeywordId where show (G gc) = "(G " ++ show gc ++ ")" show AnnSemiSep = "AnnSemiSep" show (AnnComment dc) = "(AnnComment " ++ show dc ++ ")" show (AnnString s) = "(AnnString " ++ s ++ ")" #if __GLASGOW_HASKELL__ <= 710 show (AnnUnicode gc) = "(AnnUnicode " ++ show gc ++ ")" #endif -- --------------------------------------------------------------------- instance GHC.Outputable KeywordId where ppr k = GHC.text (show k) instance GHC.Outputable (AnnConName) where ppr tr = GHC.text (show tr) instance GHC.Outputable Annotation where ppr a = GHC.text (show a) instance GHC.Outputable AnnKey where ppr a = GHC.text (show a) instance GHC.Outputable DeltaPos where ppr a = GHC.text (show a) -- --------------------------------------------------------------------- -- -- Flag used to control whether we use rigid or normal layout rules. data Rigidity = NormalLayout | RigidLayout deriving (Eq, Ord, Show) declFun :: (forall a . Data a => GHC.Located a -> b) -> GHC.LHsDecl GHC.RdrName -> b declFun f (GHC.L l de) = case de of GHC.TyClD d -> f (GHC.L l d) GHC.InstD d -> f (GHC.L l d) GHC.DerivD d -> f (GHC.L l d) GHC.ValD d -> f (GHC.L l d) GHC.SigD d -> f (GHC.L l d) GHC.DefD d -> f (GHC.L l d) GHC.ForD d -> f (GHC.L l d) GHC.WarningD d -> f (GHC.L l d) GHC.AnnD d -> f (GHC.L l d) GHC.RuleD d -> f (GHC.L l d) GHC.VectD d -> f (GHC.L l d) GHC.SpliceD d -> f (GHC.L l d) GHC.DocD d -> f (GHC.L l d) GHC.RoleAnnotD d -> f (GHC.L l d) #if __GLASGOW_HASKELL__ < 711 GHC.QuasiQuoteD d -> f (GHC.L l d) #endif -- --------------------------------------------------------------------- -- Duplicated here so it can be used in show instances showGhc :: (GHC.Outputable a) => a -> String showGhc = GHC.showPpr GHC.unsafeGlobalDynFlags -- ---------------------------------------------------------------------
mpickering/ghc-exactprint
src/Language/Haskell/GHC/ExactPrint/Types.hs
Haskell
bsd-3-clause
8,397
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE NoImplicitPrelude #-} module Language.Fay.JQuery.Cookie where import Language.Fay.Prelude import Language.Fay.FFI data Cookie a = Cookie { cookieName :: String , cookieValue :: a , cookieExpires :: Maybe Double , cookiePath :: Maybe String } -- | Set a session cookie. setSessionCookie :: String -> String -> Fay () setSessionCookie = ffi "jQuery['cookie'](%1,JSON.stringify(%2))" -- | Delete a cookie. deleteCookie :: String -> Fay () deleteCookie = ffi "jQuery['removeCookie'](%1)" -- | Get cookie value. getCookie :: String -> Fay (Maybe String) getCookie key = do exists <- cookieExists key if exists then do value <- _cookieValue key return (Just value) else return Nothing -- | Check a cookie exists. cookieExists :: String -> Fay Bool cookieExists = ffi "jQuery['cookie'](%1) !== null" -- | Get a cookie's value. _cookieValue :: String -> Fay String _cookieValue = ffi "jQuery['cookie'](%1)"
faylang/fay-server
modules/library/Language/Fay/JQuery/Cookie.hs
Haskell
bsd-3-clause
997
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} module HVX.Internal.DCP ( Vex(..) , GetVex(getVex) , Mon(..) , GetMon(getMon) , ValidVex(validVex) , FlipVex , FlipMon , ApplyVex , ApplyMon , AddVex , AddMon ) where class GetVex (v :: Vex) where getVex :: e (v :: Vex) (m :: Mon) -> String -- | convexity data Vex = Affine | Convex | Concave | Nonvex instance GetVex 'Affine where getVex _ = "Affine" instance GetVex 'Convex where getVex _ = "Convex" instance GetVex 'Concave where getVex _ = "Concave" instance GetVex 'Nonvex where getVex _ = "Nonvex" class ValidVex (v :: Vex) where validVex :: e (v :: Vex) (m :: Mon) -> e v m validVex = id instance ValidVex 'Affine instance ValidVex 'Convex instance ValidVex 'Concave class GetMon (m :: Mon) where getMon :: e (v :: Vex) (m :: Mon) -> String -- | monotonicity data Mon = Const | Nondec | Noninc | Nonmon instance GetMon 'Const where getMon _ = "Const" instance GetMon 'Nondec where getMon _ = "Nondec" instance GetMon 'Noninc where getMon _ = "Noninc" instance GetMon 'Nonmon where getMon _ = "Nonmon" -- | invert convexities type family FlipVex v where FlipVex 'Convex = 'Concave FlipVex 'Concave = 'Convex FlipVex 'Affine = 'Affine FlipVex 'Nonvex = 'Nonvex -- | invert monotonicities type family FlipMon m where FlipMon 'Const = 'Const FlipMon 'Nondec = 'Noninc FlipMon 'Noninc = 'Nondec FlipMon 'Nonmon = 'Nonmon -- determines the convexity of a function applied to an expression -- "newexpr = apply f expr" type family ApplyVex vf mf ve me where ApplyVex vf 'Const ve me = 'Affine ApplyVex vf mf ve 'Const = 'Affine ApplyVex vf mf 'Affine me = vf ApplyVex 'Affine 'Nondec ve me = ve ApplyVex 'Affine 'Noninc ve me = FlipVex ve ApplyVex v 'Nondec v me = v ApplyVex 'Convex 'Noninc 'Concave me = 'Convex ApplyVex 'Concave 'Noninc 'Convex me = 'Concave ApplyVex vf mf ve me = 'Nonvex -- determines the monotonicity of a function applied to an expression -- "newexpr = apply f expr" type family ApplyMon mf me where ApplyMon 'Const me = 'Const ApplyMon mf 'Const = 'Const ApplyMon 'Nondec me = me ApplyMon 'Noninc me = FlipMon me ApplyMon 'Nonmon me = 'Nonmon -- determines the convexity of the sum of two expressions -- "newexpr = e1 +~ e2" type family AddVex v1 v2 where AddVex 'Affine v2 = v2 AddVex v1 'Affine = v1 AddVex v v = v AddVex v1 v2 = 'Nonvex -- determines the monotonicity of the sum of two expressions -- "newexpr = e1 +~ e2" type family AddMon m1 m2 where AddMon m1 'Const = m1 AddMon 'Const m2 = m2 AddMon m m = m AddMon m1 m2 = 'Nonmon
chrisnc/hvx
src/HVX/Internal/DCP.hs
Haskell
bsd-3-clause
2,838
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Handler.Download where import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Yesod import Foundation getDownloadR :: Int -> Handler TypedContent getDownloadR ident = do StoredFile filename contentType bytes <- getById ident addHeader "Content-Disposition" $ Text.concat ["attachmeth: filename=\"", filename, "\""] sendResponse (Text.encodeUtf8 contentType, toContent bytes)
grauwoelfchen/cowberry
Handler/Download.hs
Haskell
bsd-3-clause
536
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} module Language.Lambda.Syntax.Named.Exp ( Exp (Var,App,Lam,Let) -- , bound -- , free , uname , name , fold , gFold , (#) , (!) ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative import Data.Foldable import Data.Traversable #endif import Bound.Unwrap (Fresh, Unwrap, unwrap, runUnwrap) import Test.QuickCheck.Arbitrary import Test.QuickCheck.Gen import qualified Language.Lambda.Syntax.Nameless.Exp as NL data Exp a = Var a | App (Exp a) (Exp a) | Lam a (Exp a) | Let (a, Exp a) (Exp a) deriving (Read, Show, Functor, Foldable, Traversable) fold :: (a -> n a) -> (n a -> n a -> n a) -> (a -> n a -> n a) -> ((a, n a) -> n a -> n a) -> Exp a -> n a fold v _ _ _ (Var n) = v n fold v a l lt (fun `App` arg) = a (fold v a l lt fun) (fold v a l lt arg) fold v a l lt (Lam n body) = l n (fold v a l lt body) fold v a l lt (Let def term) = lt (fmap g def) (g term) where g = fold v a l lt gFold :: (m a -> n b) -> (n b -> n b -> n b) -> (m a -> n b -> n b) -> ((m a, n b) -> n b -> n b) -> Exp (m a) -> n b gFold v _ _ _ (Var n) = v n gFold v a l lt (fun `App` arg) = a (gFold v a l lt fun) (gFold v a l lt arg) gFold v a l lt (Lam n body) = l n (gFold v a l lt body) gFold v a l lt (Let defs expr) = lt (fmap g defs) (g expr) where g = gFold v a l lt infixl 9 # (#) :: Exp a -> Exp a -> Exp a (#) = App infixr 6 ! (!) :: a -> Exp a -> Exp a (!) = Lam instance Eq a => Eq (Exp a) where l1 == l2 = uname l1 == uname l2 uname :: Eq a => Exp a -> NL.Exp a a uname = fold NL.Var NL.App NL.lam_ NL.let_ name :: Eq a => NL.Exp (Fresh a) (Fresh a) -> Exp (Fresh a) name = runUnwrap . go where go :: NL.Exp (Fresh a) (Fresh a) -> Unwrap (Exp (Fresh a)) go (NL.Var n) = return (Var n) go (fun `NL.App` arg) = App <$> go fun <*> go arg go (NL.Lam (NL.Alpha n) scope) = do (n', e) <- unwrap n scope Lam n' <$> go e go (NL.Let (NL.Alpha n) d scope) = do d' <- go d (n', e) <- unwrap n scope Let (n', d') <$> go e genExpr :: Arbitrary a => Int -> Gen (Exp a) genExpr depth | depth <= 1 = Var <$> arbitrary | otherwise = do depth1 <- genDepth depth2 <- genDepth oneof [ genExpr 1 , App <$> genExpr depth1 <*> genExpr depth2 , Lam <$> arbitrary <*> genExpr depth1 ] where genDepth = elements [1 .. pred depth] instance Arbitrary a => Arbitrary (Exp a) where arbitrary = sized genExpr
julmue/UntypedLambda
src/Language/Lambda/Syntax/Named/Exp.hs
Haskell
bsd-3-clause
2,682
{-# LANGUAGE FlexibleContexts, Rank2Types #-} module Rede.SpdyProtocol.Session( -- trivialSession basicSession -- ,showHeadersIfPresent ) where import Control.Concurrent (forkIO) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Reader import Control.Exception(throwIO) import Data.Conduit -- import Data.IORef import qualified Data.Streaming.Zlib as Z -- import Data.Conduit.Lift (distribute) -- import qualified Data.Conduit.List as CL import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as LB import Data.ByteString.Char8 (pack) import Data.Default (def) import Control.Concurrent.MVar import qualified Data.Map as MA import Data.Binary.Put (runPut) import qualified Data.Binary as Bi import Data.Binary.Get (runGet) import qualified Data.HashTable.IO as H import qualified Data.Dequeue as D import Rede.SpdyProtocol.Framing.AnyFrame import Rede.SpdyProtocol.Framing.Frame import Rede.SpdyProtocol.Framing.Ping import Rede.SpdyProtocol.Framing.DataFrame import Rede.SpdyProtocol.Framing.RstStream import Rede.SpdyProtocol.Framing.WindowUpdate import Rede.MainLoop.StreamPlug import Rede.SpdyProtocol.Framing.KeyValueBlock import qualified Rede.SpdyProtocol.Framing.Settings as SeF import Rede.SpdyProtocol.Streams.State import Rede.MainLoop.Tokens -- TODO: Move to constants? initialSettings :: SeF.SettingsFrame initialSettings = SeF.SettingsFrame { SeF.prologue = def ,SeF.persistSettings = [ (SeF.InitialWindowSize_S, 65536, SeF.None_PS) ] } -- goAwayMsg :: GoA.GoAwayFrame -- goAwayMsg = GoA.GoAwayFrame { -- GoA.prologue = def -- ,GoA.statusCode = GoA.OK_GAR -- ,GoA.lastGoodStream = 0 -- } type WaitList = D.BankersDequeue AnyFrame -- A table from stream id to windows reamining list and waiting -- list type StreamWindowInfo = MVar (Int, WaitList) type StreamWaits = H.BasicHashTable Int StreamWindowInfo data SimpleSessionStateRecord = SimpleSessionStateRecord { streamInputs :: MVar (MA.Map Int (MVar AnyFrame)) -- ,streamsOutput :: MVar (Maybe AnyFrame) ,sendZLib :: MVar Z.Deflate ,recvZLib :: MVar Z.Inflate ,streamInit :: Int -> IO () -> StreamStateT IO () -> IO () -- Need also a way to do frame-flow control ,streamWaits :: StreamWaits ,initialWindowSize :: MVar Int ,sessionWindow :: MVar Int } type SessionM = ReaderT SimpleSessionStateRecord -- | Super-simple session manager without flow control and such.... -- but using StreamWorkers already.... -- TODO: without proper flow control, we are in troubles.... basicSession :: (StreamWorkerClass serviceParams servicePocket sessionPocket) => servicePocket -> IO ( (Sink AnyFrame IO () ), (Source IO AnyFrame ) ) basicSession worker_service_pocket = do -- Create the input record.... stream_inputs <- newMVar $ MA.empty -- Whatever is put here makes it to the socket, so this -- should go after flow control session_gate <- (newEmptyMVar :: IO (MVar AnyFrame) ) send_zlib <- Z.initDeflateWithDictionary 2 zLibInitDict Z.defaultWindowBits send_zlib_mvar <- newMVar send_zlib recv_zlib <- Z.initInflateWithDictionary Z.defaultWindowBits zLibInitDict recv_zlib_mvar <- newMVar recv_zlib worker_session_pocket <- initSession worker_service_pocket -- Preserve the IO wrapper make_worker <- return $ initStream worker_service_pocket worker_session_pocket next_stream_id <- newMVar 2 -- Stream ids pushed from the server start at two stream_waits <- H.new -- TODO: Fix this initial_window_size <- newMVar 65536 session_window <- newMVar 65536 session_record <- return $ SimpleSessionStateRecord { streamInputs = stream_inputs ,sendZLib = send_zlib_mvar ,recvZLib = recv_zlib_mvar ,streamInit = \ stream_id fin -> initStreamState stream_id fin next_stream_id ,streamWaits = stream_waits ,initialWindowSize = initial_window_size ,sessionWindow = session_window } -- hoister <- return $ (\ x -> runReaderT x session_record :: SessionM IO a -> IO a) flow_control_gate <- liftIO $ newEmptyMVar -- This is the end of the pipeline which is closest to the TCP socket in the input direction -- The "flow_control_gate" variable here is given to newly created streams, it is also used -- directly by the sink to process WindowUpdate frames... packet_sink <- return $ transPipe ( \ x -> runReaderT x session_record) (statefulSink make_worker flow_control_gate) -- We will need to run flow control liftIO $ forkIO $ runReaderT (flowControl flow_control_gate session_gate) session_record -- This is the end of the pipeline that is closest to the TCP socket in the output direction packet_source <- return $ transPipe (\ x -> runReaderT x session_record) (createTrivialSource session_gate) return (packet_sink, packet_source) takesInput :: MVar AnyFrame -> Source (StreamStateT IO) AnyFrame takesInput input_mvar = do frame <- liftIO $ takeMVar input_mvar -- liftIO $ putStrLn "Got something" yield frame takesInput input_mvar plugStream :: IO StreamWorker -> MVar AnyFrame -> MVar (Either AnyFrame (Int,Int) ) -> IO ( StreamStateT IO () ) plugStream workerStart input_mvar drop_output_here_mvar = do worker <- workerStart return (( (takesInput input_mvar) $= inputPlug =$= (transPipe liftIO (worker::StreamWorker)) =$= (outputPlug :: Conduit StreamOutputAction (StreamStateT IO) AnyFrame) -- ATTENTION: potential session race-condition here. $$ (streamOutput drop_output_here_mvar) )) -- | Takes output from the stream conduit and puts it on the output mvar. This runs in -- the stream thread. -- ATTENTION: When a stream finishes, the conduit closes and yields a Nothing to -- signal that streamOutput :: MVar (Either AnyFrame (Int,Int) ) -> Sink AnyFrame (StreamStateT IO) () streamOutput output_mvar = do any_frame_maybe <- await case any_frame_maybe of -- The stream is alive Just anyframe -> do liftIO $ putMVar output_mvar $ Left anyframe streamOutput output_mvar --The stream wishes to finish, in this case, --don't put anything in the output MVar, but --call a provided finalizer Nothing -> do lift streamFinalize -- Now let natural finalization of the conduit to take -- place... -- IMPLEMENT: iDropThisFrame (Ping_CFT) iDropThisFrame :: AnyControlFrame -> Bool -- iDropThisFrame (SettingsFrame_ACF _ ) = True -- iDropThisFrame (WindowUpdateFrame_ACF _ ) = True iDropThisFrame _ = False -- | Takes a stream worker constructor and properly sets its connections so that -- it can take and place data in the multi-threaded pipeline. statefulSink :: IO StreamWorker -- ^ When needed, create a new stream worker here. -> MVar (Either AnyFrame (Int,Int) ) -- ^ All outputs of this session should be placed here -- (This should go to ) -> Sink AnyFrame (SessionM IO) () statefulSink init_worker flow_control_gate = do anyframe_maybe <- await session_record <- lift $ ask stream_init <- return $ streamInit session_record -- session_window <- return $ sessionWindow session_record case anyframe_maybe of Just anyframe -> do headers_uncompressed <- lift $ uncompressFrameHeaders anyframe case headers_uncompressed of (AnyControl_AF control_frame) | iDropThisFrame control_frame -> do liftIO $ putStrLn $ "Frame dropped: " ++ (show control_frame) continue -- ## (AnyControl_AF (WindowUpdateFrame_ACF winupdate) ) -> do stream_id <- return $ streamIdFromFrame winupdate delta_bytes <- return $ deltaWindowSize winupdate -- liftIO $ putStrLn $ "Window update stream=" ++ (show stream_id) ++ " delta=" ++ (show delta_bytes) liftIO $ putMVar flow_control_gate $ Right (stream_id, delta_bytes) continue -- We started here: sending ping requests.... often we also -- need to answer to them... (AnyControl_AF (PingFrame_ACF ping_frame)) -> do case handlePingFrame ping_frame of Just answer -> liftIO $ putMVar flow_control_gate $ Left $ wrapCF answer Nothing -> return () continue -- ## frame@(AnyControl_AF (SynStream_ACF syn_stream)) -> let stream_id = streamIdFromFrame syn_stream inputs = streamInputs session_record fin = do stream_inputs <- takeMVar inputs putMVar inputs $ MA.delete stream_id stream_inputs stream_create = do putStrLn $ "Opening stream " ++ (show stream_id) stream_inputs <- takeMVar inputs input_place <- newEmptyMVar stream_worker <- plugStream init_worker input_place flow_control_gate putMVar inputs $ MA.insert stream_id input_place stream_inputs forkIO $ stream_init stream_id fin $ stream_worker putMVar input_place frame in do liftIO stream_create continue -- ## ( AnyControl_AF (RstStreamFrame_ACF rst_stream) ) -> do stream_id <- return $ streamIdFromFrame rst_stream liftIO $ putStrLn $ "Reset stream " ++ (show stream_id) ++ " because: "++ (show $ getFrameResetReason rst_stream) lift $ deleteStream stream_id continue -- ## (AnyControl_AF (GoAwayFrame_ACF goaway)) -> do -- To test: the socket should be closed here liftIO $ putStrLn $ "GOAWAY (closing this sink) " ++ (show goaway) -- Don't continue here (AnyControl_AF (SettingsFrame_ACF settings)) -> do case SeF.getDefaultWindowSize settings of Just sz -> do liftIO $ putStrLn $ "Settings window size: " ++ (show sz) liftIO $ modifyMVar_ (initialWindowSize session_record) (\ _ -> return sz) Nothing -> return () continue -- ## frame -> do liftIO $ putStrLn $ "Dont't know how to handle ... " ++ (show frame) continue -- ## -- Come and recurse... Nothing -> return () -- So must one finish here... where continue = statefulSink init_worker flow_control_gate handlePingFrame :: PingFrame -> Maybe PingFrame handlePingFrame p@(PingFrame _ frame_id) | odd frame_id = Just p handlePingFrame _ = Nothing addBytesToStream :: Int -> Int -> SessionM IO () addBytesToStream stream_id bytecount = do stream_waits <- asks streamWaits if stream_id > 0 then do stream_window_info_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_window_info_maybe of Nothing -> do -- The stream was possibly deleted before, do nothing... return () Just mvar -> do -- Modify it liftIO $ modifyMVar_ mvar $ \ (bytes, deq) -> return (bytes+bytecount, deq) else do -- Surely this refers to the entire thing session_window_mvar <- asks sessionWindow liftIO $ modifyMVar_ session_window_mvar (\ current_value -> return (current_value + bytecount)) initFlowControlOnStream :: Int -> SessionM IO () initFlowControlOnStream stream_id = do stream_waits <- asks streamWaits (window_bytes, queue) <- createStreamWindowInfo stream_id mvar <- liftIO $ newMVar (window_bytes , queue) liftIO $ H.insert stream_waits stream_id mvar createStreamWindowInfo :: Int -> SessionM IO (Int, WaitList) createStreamWindowInfo stream_id = do if odd stream_id then do initial_size_ioref <- asks initialWindowSize sz <- liftIO $ readMVar initial_size_ioref return (sz, D.empty) else do -- Working around bug on Firefox return (10000000, D.empty) flowControlAllowsFrame :: Int -> AnyFrame -> SessionM IO Bool flowControlAllowsFrame stream_id anyframe = do stream_waits <- asks streamWaits stream_info_mvar_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_info_mvar_maybe of Just stream_info_mvar -> do (bytes_remaining, dq) <- liftIO $ takeMVar stream_info_mvar size_to_send <- return $ associatedLength anyframe available_in_session_mv <- asks sessionWindow available_in_session <- liftIO $ takeMVar available_in_session_mv -- liftIO $ putStrLn $ "Bytes remaining stream id " ++ (show stream_id ) ++ " " ++ (show bytes_remaining) case ( ((D.length dq) == 0), ((bytes_remaining >= size_to_send) && (size_to_send <= available_in_session) ) ) of (True, True) -> do -- Empty dequeue, enough bytes liftIO $ do putMVar stream_info_mvar (bytes_remaining-size_to_send, dq) putMVar available_in_session_mv (available_in_session - size_to_send) return True _ -> do liftIO $ do putStrLn $ "FRAME of stream " ++ (show stream_id) ++ " DELAYED rem bytes: " ++ (show bytes_remaining) ++ " size_to_send: " ++ (show size_to_send) putMVar stream_info_mvar (bytes_remaining, (D.pushBack dq anyframe)) putMVar available_in_session_mv available_in_session return False Nothing -> -- Stream has been deleted return False flowControlCanPopFrame :: Int -> SessionM IO (Maybe AnyFrame) flowControlCanPopFrame stream_id = do session_record <- ask stream_waits <- asks streamWaits if stream_id > 0 then do stream_info_mvar_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_info_mvar_maybe of Just stream_info_mvar -> do (bytes_remaining, dq) <- liftIO $ takeMVar stream_info_mvar (anyframe_maybe, newqueue) <- return $ D.popFront dq available_in_session_mv <- asks sessionWindow available_in_session <- liftIO $ takeMVar available_in_session_mv (result, newbytes, dq', new_available_in_session) <- case anyframe_maybe of Just anyframe -> if (sz <= bytes_remaining) && (sz <= available_in_session) then do liftIO $ putStrLn $ "Frame of " ++ (show stream_id) ++ " popped!" return ( (Just anyframe), bytes_remaining - sz, newqueue, available_in_session - sz) else do liftIO $ putStrLn $ "Impossible: stream_id= " ++ (show stream_id) ++ " stream bytes avail: " ++ (show bytes_remaining) ++ " session avail: " ++ (show available_in_session) return ( Nothing, bytes_remaining, dq, available_in_session) where sz = associatedLength anyframe Nothing -> return (Nothing, bytes_remaining, dq, available_in_session) liftIO $ do putMVar stream_info_mvar (newbytes, dq') putMVar available_in_session_mv new_available_in_session return result Nothing -> do return Nothing else do -- More complicated case of the session window, go through all the active streams liftIO $ H.foldM (\ p (stream_id', _) -> runReaderT (innerFold p stream_id') session_record) Nothing stream_waits where innerFold p stream_id' = do -- liftIO $ putStrLn $ "iter: " ++ (show stream_id') case p of Just _ -> return p Nothing -> do anyframe_maybe <- flowControlCanPopFrame stream_id' case anyframe_maybe of Just _ -> do return anyframe_maybe Nothing -> do return Nothing -- This one sits on the output stream, checking to see if frames are allowed to leave flowControl :: MVar (Either AnyFrame (Int,Int) ) -- Input frames and window's -- updates come this way -> MVar AnyFrame -- Can output frames go this way -> SessionM IO () flowControl input output = do event <- liftIO $ takeMVar input case event of Left anyframe -> if frameIsFlowControlled anyframe then do stream_id <- return $ streamIdFromAnyFrame anyframe can_send <- flowControlAllowsFrame stream_id anyframe if can_send then do -- No need to wait liftIO $ putMVar output anyframe else do return () else do -- Not flow-controlled, this is most likely headers and synreplies -- generated here in the server, don't obstruct them liftIO $ putMVar output anyframe -- Some of the non-flow controlled frames create send windows when -- they go out, let's take care of that case anyframe of (AnyControl_AF (SynStream_ACF frame) ) -> initFlowControlOnStream $ streamIdFromFrame frame (AnyControl_AF (SynReplyFrame_ACF frame)) -> initFlowControlOnStream $ streamIdFromFrame frame _ -> return () Right (stream_id, window_delta_size) -> do -- liftIO $ putStrLn $ "Add to stream: " ++ (show stream_id) -- So, I got some more room to send frames -- Notice that this may happen before this fragment ever observes -- a frame on that stream, so we need to be sure it exists... addBytesToStream stream_id window_delta_size sendFramesForStream stream_id output -- Tail-recursively invoke flowControl input output where sendFramesForStream stream_id output' = do popped_frame_maybe <- flowControlCanPopFrame stream_id case popped_frame_maybe of Just anyframe -> do liftIO $ putMVar output' anyframe sendFramesForStream stream_id output' Nothing -> return () associatedLength :: AnyFrame -> Int associatedLength (DataFrame_AF dataframe ) = B.length $ payload dataframe -- Here is where frames pop-up coming from the individual stream -- threads. So, the frames are serialized at this point and any -- incoming Key-value block compressed. This runs on the output -- thread. The parameter output_mvar is a gate that flow control -- uses to put frames which are ready for delivery... createTrivialSource :: MVar AnyFrame -> Source (SessionM IO) AnyFrame createTrivialSource output_mvar = do yield $ wrapCF initialSettings createTrivialSourceLoop :: Source (SessionM IO) AnyFrame where createTrivialSourceLoop = do anyframe_headerscompressed <- lift $ do anyframe <- liftIO $ takeMVar output_mvar compressFrameHeaders anyframe -- This is a good place to remove the entry from the table if -- this frame is the last one in the stream case frameEndsStream anyframe_headerscompressed of Just which_stream -> do liftIO $ putStrLn $ "Stream " ++ (show which_stream) ++ " closed naturally" lift $ deleteStream which_stream Nothing -> return () liftIO $ putStrLn $ "SENDING of: " ++ (show $ streamIdFromAnyFrame anyframe_headerscompressed) yield anyframe_headerscompressed createTrivialSourceLoop deleteStream :: Int -> SessionM IO () deleteStream stream_id = do stream_waits <- asks streamWaits liftIO $ H.delete stream_waits stream_id -- | Use to purge old streams from tables.... frameEndsStream :: AnyFrame -> Maybe Int frameEndsStream (DataFrame_AF dataframe) = if has_fin_flag then Just (streamIdFromFrame dataframe) else Nothing where has_fin_flag = getFrameFlag dataframe Fin_F frameEndsStream _ = Nothing frameIsFlowControlled :: AnyFrame -> Bool frameIsFlowControlled (DataFrame_AF _) = True frameIsFlowControlled _ = False compressFrameHeaders :: AnyFrame -> (SessionM IO) AnyFrame compressFrameHeaders ( AnyControl_AF (SynStream_ACF f)) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders ( AnyControl_AF (SynReplyFrame_ACF f )) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders ( AnyControl_AF (HeadersFrame_ACF f)) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders frame_without_headers = return frame_without_headers uncompressFrameHeaders :: AnyFrame -> (SessionM IO) AnyFrame uncompressFrameHeaders ( AnyControl_AF (SynStream_ACF f)) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders ( AnyControl_AF (SynReplyFrame_ACF f )) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders ( AnyControl_AF (HeadersFrame_ACF f)) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders frame_without_headers = return frame_without_headers justCompress :: CompressedHeadersOnFrame f => f -> SessionM IO f justCompress frame = do send_zlib_mvar <- asks sendZLib case present_headers of UncompressedKeyValueBlock uncompressed_uvl -> do uncompressed_bytes <- return $ LB.toStrict $ runPut $ Bi.put $ uncompressed_uvl new_value <- liftIO $ do withMVar send_zlib_mvar $ \ send_zlib -> do popper <- Z.feedDeflate send_zlib uncompressed_bytes list_piece_1 <- exhaustPopper popper latest_piece <- exhaustPopper $ Z.flushDeflate send_zlib return $ CompressedKeyValueBlock $ B.concat (list_piece_1 ++ latest_piece) return $ setCompressedHeaders frame new_value CompressedKeyValueBlock _ -> error "This was not expected" where present_headers = getCompressedHeaders frame justDecompress :: CompressedHeadersOnFrame f => f -> SessionM IO f justDecompress frame = do recv_zlib_mvar <- asks recvZLib case present_headers of CompressedKeyValueBlock bscmp -> do -- uncompressed_bytes <- return $ LB.toStrict $ runPut $ Bi.put $ uncompressed_uvl new_value <- liftIO $ do withMVar recv_zlib_mvar $ \ recv_zlib -> do popper <- Z.feedInflate recv_zlib bscmp list_piece_1 <- exhaustPopper popper latest <- Z.flushInflate recv_zlib uncompressed_bytes <- return $ B.concat (list_piece_1 ++ [latest]) return $ UncompressedKeyValueBlock $ runGet Bi.get $ LB.fromChunks [uncompressed_bytes] return $ setCompressedHeaders frame new_value UncompressedKeyValueBlock _ -> error "This was not expected" where present_headers = getCompressedHeaders frame exhaustPopper :: Z.Popper -> IO [B.ByteString] exhaustPopper popper = do x <- popper case x of Z.PRDone -> return [] Z.PRNext bytestring -> do more <- exhaustPopper popper return $ (bytestring:more) Z.PRError e -> do -- When this happens, the only sensible -- thing to do is throw an exception, and trash the entire -- stream.... throwIO e zLibInitDict :: B.ByteString zLibInitDict = pack $ map toEnum [ 0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68, 0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70, 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05, 0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00, 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00, 0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00, 0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d, 0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00, 0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00, 0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72, 0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72, 0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00, 0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79, 0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00, 0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77, 0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00, 0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72, 0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73, 0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65, 0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32, 0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35, 0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30, 0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33, 0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37, 0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30, 0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34, 0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31, 0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31, 0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34, 0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34, 0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e, 0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d, 0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34, 0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30, 0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30, 0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64, 0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46, 0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41, 0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a, 0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41, 0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20, 0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57, 0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61, 0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20, 0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67, 0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, 0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65, 0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64, 0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69, 0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d, 0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a, 0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e ]
loadimpact/http2-test
hs-src/Rede/SpdyProtocol/Session.hs
Haskell
bsd-3-clause
36,820
instance Pointed Point where point = Point instance MonadStep Point where type SS Point = Point step f xs = xs >>= f
davdar/quals
writeup-old/sections/04MonadicAAM/02RecoveringConcrete/03PointMonadStep.hs
Haskell
bsd-3-clause
123
{-# LANGUAGE FlexibleContexts, FlexibleInstances #-} module Instances where import Prelude as P import Control.Applicative import Test.QuickCheck import Test.QuickCheck.Arbitrary import Data.SparseVector import qualified Data.Vector as V import Data.Vector (Vector) instance Arbitrary a => Arbitrary (Vector a) where arbitrary = fmap V.fromList arbitrary -- The mod is to prevent it from generating huge ranges that slow down our tests when we're converting to flat vectors instance Arbitrary a => Arbitrary (SparseVector a) where arbitrary = liftA2 (fromList . (`mod` 10000) . abs) arbitrary arbitrary {- newtype NonOverlappingRange v a = NonOverlappingRange [(Index, v a)] deriving (Show) nonOverlapping :: (v a -> Int) -> [(NonNegative Index, v a)] -> [(NonNegative Index, v a)] nonOverlapping _ [] = [] nonOverlapping len xs = scanl1 (\(NonNegative x, y) (NonNegative a, b) -> (NonNegative $ x + a + len y, b)) xs deNonNegative :: [(NonNegative a, b)] -> [(a, b)] deNonNegative = map (\(NonNegative i, xs) -> (i, xs)) instance Arbitrary a => Arbitrary (NonOverlappingRange Vector a) where arbitrary = do base <- arbitrary return $ NonOverlappingRange (deNonNegative (nonOverlapping V.length base)) instance Arbitrary a => Arbitrary (NonOverlappingRange [] a) where arbitrary = do base <- arbitrary return $ NonOverlappingRange (deNonNegative (nonOverlapping P.length base)) -}
copumpkin/vector-sparse
tests/Instances.hs
Haskell
bsd-3-clause
1,439
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Hasmin.Parser.Internal -- Copyright : (c) 2017 Cristian Adrián Ontivero -- License : BSD3 -- Stability : experimental -- Portability : unknown -- ----------------------------------------------------------------------------- module Hasmin.Parser.Internal ( stylesheet , atRule , atMedia , styleRule , rule , rules , declaration , declarations , selector , supportsCondition ) where import Control.Applicative ((<|>), many, some, optional) import Data.Functor (($>)) import Data.Attoparsec.Combinator (lookAhead, endOfInput) import Data.Attoparsec.Text (asciiCI, char, manyTill, Parser, satisfy) import Data.List.NonEmpty (NonEmpty) import Data.Monoid ((<>)) import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.Attoparsec.Text as A import qualified Data.Char as C import qualified Data.Text as T import Hasmin.Parser.Utils import Hasmin.Parser.Value import Hasmin.Parser.Selector import Hasmin.Types.Stylesheet import Hasmin.Types.Declaration -- | Parser for a declaration, starting by the property name. declaration :: Parser Declaration declaration = do p <- property <* colon v <- valuesFor p <|> valuesFallback i <- important ie <- lexeme iehack pure $ Declaration p v i ie -- | Parser for property names. Usually, 'ident' would be enough, but this -- parser adds support for IE hacks (e.g. *width), which deviate from the CSS -- grammar. property :: Parser Text property = mappend <$> opt ie7orLessHack <*> ident where ie7orLessHack = T.singleton <$> satisfy (`Set.member` ie7orLessHacks) ie7orLessHacks = Set.fromList ("!$&*()=%+@,./`[]#~?:<>|" :: String) -- | Used to parse the "!important" at the end of declarations, ignoring spaces -- and comments after the '!'. important :: Parser Bool important = A.option False (char '!' *> skipComments *> asciiCI "important" $> True) iehack :: Parser Bool iehack = A.option False (A.string "\\9" $> True) -- Note: The handleSemicolons outside is needed to handle parsing "h1 { ; }". -- -- | Parser for a list of declarations, ignoring spaces, comments, and empty -- declarations (e.g. ; ;) declarations :: Parser [Declaration] declarations = many (declaration <* handleSemicolons) <* handleSemicolons where handleSemicolons = many (A.char ';' *> skipComments) -- | Parser for CSS at-rules (e.g. \@keyframes, \@media) atRule :: Parser Rule atRule = do _ <- char '@' ruleType <- ident fromMaybe (atBlock ruleType) (Map.lookup ruleType m) where m = Map.fromList [("charset", atCharset) ,("import", atImport) ,("namespace", atNamespace) ,("media", atMedia) ,("supports", atSupports) -- ,("document", atDocument) -- ,("page", atPage) ,("font-face", skipComments *> atBlock "font-face") ,("keyframes", atKeyframe mempty ) ,("-webkit-keyframes", atKeyframe "-webkit-") ,("-moz-keyframes", atKeyframe "-moz-") ,("-o-keyframes", atKeyframe "-o-") -- ,("viewport", atViewport) -- ,("counter-style", atCounterStyle) -- ,("font-feature-value", atFontFeatureValue) ] -- @import [ <string> | <url> ] [<media-query-list>]?; atImport :: Parser Rule atImport = do esu <- skipComments *> stringOrUrl mql <- A.option [] mediaQueryList _ <- skipComments <* char ';' pure $ AtImport esu mql atCharset :: Parser Rule atCharset = AtCharset <$> (lexeme stringtype <* char ';') -- @namespace <namespace-prefix>? [ <string> | <uri> ]; -- where -- <namespace-prefix> = IDENT atNamespace :: Parser Rule atNamespace = do i <- skipComments *> A.option mempty ident ret <- if T.null i then AtNamespace i . Left <$> stringtype else decideBasedOn i _ <- skipComments <* char ';' pure ret where decideBasedOn x | T.toCaseFold x == "url" = do c <- A.peekChar case c of Just '(' -> AtNamespace mempty <$> (char '(' *> (Right <$> url)) _ -> AtNamespace x <$> (skipComments *> stringOrUrl) | otherwise = AtNamespace x <$> (skipComments *> stringOrUrl) atKeyframe :: Text -> Parser Rule atKeyframe t = do name <- lexeme ident <* char '{' bs <- many (keyframeBlock <* skipComments) _ <- char '}' pure $ AtKeyframes t name bs keyframeBlock :: Parser KeyframeBlock keyframeBlock = do sel <- lexeme kfsList ds <- char '{' *> skipComments *> declarations <* char '}' pure $ KeyframeBlock sel ds where from = asciiCI "from" $> From to = asciiCI "to" $> To keyframeSelector = from <|> to <|> (KFPercentage <$> percentage) kfsList = (:) <$> keyframeSelector <*> many (comma *> keyframeSelector) atMedia :: Parser Rule atMedia = do m <- satisfy C.isSpace *> mediaQueryList _ <- char '{' <* skipComments r <- manyTill (rule <* skipComments) (lookAhead (char '}')) _ <- char '}' pure $ AtMedia m r atSupports :: Parser Rule atSupports = do sc <- satisfy C.isSpace *> supportsCondition _ <- lexeme (char '{') r <- manyTill (rule <* skipComments) (lookAhead (char '}')) _ <- char '}' pure $ AtSupports sc r -- | Parser for a <https://drafts.csswg.org/css-conditional-3/#supports_condition supports_condition>, -- needed by @\@supports@ rules. supportsCondition :: Parser SupportsCondition supportsCondition = asciiCI "not" *> skipComments *> (Not <$> supportsCondInParens) <|> supportsConjunction <|> supportsDisjunction <|> (Parens <$> supportsCondInParens) where supportsDisjunction :: Parser SupportsCondition supportsDisjunction = supportsHelper Or "or" supportsConjunction :: Parser SupportsCondition supportsConjunction = supportsHelper And "and" supportsCondInParens :: Parser SupportsCondInParens supportsCondInParens = do _ <- char '(' x <- lexeme $ (ParensCond <$> supportsCondition) <|> (ParensDec <$> atSupportsDeclaration) _ <- char ')' pure x atSupportsDeclaration :: Parser Declaration atSupportsDeclaration = do p <- property <* colon v <- valuesFor p <|> valuesInParens pure $ Declaration p v False False -- customPropertyIdent :: Parser Text -- customPropertyIdent = (<>) <$> string "-" <*> ident supportsHelper :: (SupportsCondInParens -> NonEmpty SupportsCondInParens -> SupportsCondition) -> Text -> Parser SupportsCondition supportsHelper c t = do x <- supportsCondInParens <* skipComments xs <- some (asciiCI t *> lexeme supportsCondInParens) pure $ c x (NE.fromList xs) -- TODO clean code -- the "manyTill .. lookAhead" was added because if we only used "rules", it -- doesn't know when to stop, and breaks the parser atBlock :: Text -> Parser Rule atBlock i = do t <- mappend i <$> A.takeWhile (/= '{') <* char '{' r <- skipComments *> ((AtBlockWithDec t <$> declarations) <|> (AtBlockWithRules t <$> manyTill (rule <* skipComments) (lookAhead (char '}')))) _ <- char '}' pure r -- | Parses a CSS style rule, e.g. @body { padding: 0; }@ styleRule :: Parser Rule styleRule = do sels <- selectors <* char '{' <* skipComments decs <- declarations <* char '}' pure $ StyleRule sels decs -- | Parser for a CSS rule, which can be either an at-rule (e.g. \@charset), or a style -- rule. rule :: Parser Rule rule = atRule <|> styleRule -- | Parser for CSS rules (both style rules, and at-rules), which can be -- separated by whitespace or comments. rules :: Parser [Rule] rules = manyTill (rule <* skipComments) endOfInput -- | Parse a stylesheet, starting by the \@charset, \@import and \@namespace -- rules, followed by the list of rules, and ignoring any unneeded whitespace -- and comments. stylesheet :: Parser [Rule] stylesheet = do charset <- A.option [] ((:[]) <$> atCharset <* skipComments) imports <- many (atImport <* skipComments) namespaces <- many (atNamespace <* skipComments) _ <- skipComments -- if there is no charset, import, or namespace at rule we need this here. rest <- rules pure $ charset <> imports <> namespaces <> rest -- | Media Feature values. Per the -- <https://www.w3.org/TR/css3-mediaqueries/#values original spec (6.1)>, -- \<resolution\> only accepts dpi and dpcm units, dppx was added later. -- However, the w3c validator considers it valid, so we make no exceptions. {- data MediaFeatureValue = MFV_Length Length | MFV_Ratio Ratio | MFV_Number Number | MFV_Resolution Resolution | MFV_Other Text -} -- | Specs: -- -- https://drafts.csswg.org/mediaqueries-3/#syntax -- https://www.w3.org/TR/css3-mediaqueries/ -- https://www.w3.org/TR/CSS21/grammar.html -- -- Implementation based on mozilla's pseudo BNF: -- https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries mediaQueryList :: Parser [MediaQuery] mediaQueryList = lexeme ((:) <$> mediaQuery <*> many (char ',' *> skipComments *> mediaQuery)) mediaQuery :: Parser MediaQuery mediaQuery = mediaQuery1 <|> mediaQuery2 where mediaQuery1 = MediaQuery1 <$> optionalNotOrOnly <*> mediaType <*> andExpressions mediaQuery2 = MediaQuery2 <$> ((:) <$> expression <*> andExpressions) mediaType = lexeme ident andExpressions = many (h *> expression) h = lexeme (asciiCI "and" *> satisfy C.isSpace) optionalNotOrOnly = A.option mempty (asciiCI "not" <|> asciiCI "only") -- https://www.w3.org/TR/mediaqueries-4/#typedef-media-condition-without-or expression :: Parser Expression expression = char '(' *> skipComments *> (expr <|> expFallback) where expr = do e <- ident <* skipComments v <- optional (char ':' *> lexeme value) _ <- char ')' -- Needed here for expFallback to trigger pure $ Expression e v expFallback = InvalidExpression <$> A.takeWhile (/= ')') <* char ')' -- TODO implement the whole spec 4, or at least 3. -- Note: The code below pertains to CSS Media Queries Level 4. -- Since it is still too new and nobody implements it (afaik), -- I leave it here for future reference, when the need to cater for it -- arrives. {- mediaCondition = asciiCI "not" <|> asciiCI "and" <|> asciiCI "or" <|> mediaInParens mediaInParens = char '(' *> skipComments *> mediaCondition <* skipComments <* char ')' mediaFeature :: Parser MediaFeature mediaFeature = mfPlain <|> mfRange <|> mfBoolean where mfBoolean = ident mfRange = ident data MediaFeature = MFPlain Text Value | MFBoolean Text | MFRange Range data Range = Range1 Text RangeOp Value | Range2 Value RangeOp Text | Range3 Value RangeOp Text RangeOp Value data RangeOp = LTOP | GTOP | EQOP | GEQOP | LEQOP -- = <mf-name> [ '<' | '>' ]? '='? <mf-value> -- | <mf-value> [ '<' | '>' ]? '='? <mf-name> -- | <mf-value> '<' '='? <mf-name> '<' '='? <mf-value> -- | <mf-value> '>' '='? <mf-name> '>' '='? <mf-value> mfPlain = ident *> skipComments *> char ':' *> skipComments *> mfValue mfValue :: Parser Value mfValue = number <|> dimension <|> ident <|> ratio -- TODO check if both integers are positive (required by the spec) ratio :: Parser Value ratio = do n <- digits _ <- skipComments *> char '/' <* skipComments m <- digits pure $ Other (mconcat [n, "/", m]) -- expr -- : term [ operator? term ]* -- ; -- --term -- : unary_operator? -- [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* | -- TIME S* | FREQ S* ] -- | STRING S* | IDENT S* | URI S* | hexcolor | function -- ; -- data MediaFeatureType = Range | Discrete t = [("width", Range) ,("height", Range) ,("aspect-ratio", Range) ,("orientation", Discrete) ,("resolution", Range) ,("scan", Discrete) ,("grid", Discrete) ,("update", Discrete) ,("overflow-block", Discrete) ,("overflow-inline", Discrete) ,("color", Range) ,("color-index", Range) ,("monochrome", Range) ,("color-gamut", Discrete) ,("pointer", Discrete) ,("hover", Discrete) ,("any-pointer", Discrete) ,("any-hover", Discrete) ,("scripting", Discrete) ,("device-width", Range) ,("device-height", Range) ,("device-aspect-ratio", Range) ] -}
contivero/hasmin
src/Hasmin/Parser/Internal.hs
Haskell
bsd-3-clause
13,226
{-# language QuasiQuotes #-} {-# language TemplateHaskell #-} module OpenCV.Internal.Core.Types.Vec.TH ( mkVecType ) where import "base" Data.List ( intercalate ) import "base" Data.Monoid ( (<>) ) import "base" Foreign.Marshal.Alloc ( alloca ) import "base" Foreign.Storable ( peek ) import "base" System.IO.Unsafe ( unsafePerformIO ) import qualified "inline-c" Language.C.Inline.Unsafe as CU import "linear" Linear ( V2(..), V3(..), V4(..) ) import "template-haskell" Language.Haskell.TH import "template-haskell" Language.Haskell.TH.Quote ( quoteExp ) import "this" OpenCV.Internal.C.PlacementNew.TH ( mkPlacementNewInstance ) import "this" OpenCV.Internal.C.Types import "this" OpenCV.Internal.Core.Types.Vec import "this" OpenCV.Internal mkVecType :: String -- ^ Vec type name, for both Haskell and C -> Integer -- ^ Vec dimension -> Name -- ^ Depth type name in Haskell -> String -- ^ Depth type name in C -> Q [Dec] mkVecType vTypeNameStr dim depthTypeName cDepthTypeStr | dim < 2 || dim > 4 = fail $ "mkVecType: Unsupported dimension: " <> show dim | otherwise = fmap concat . sequence $ [ pure <$> vecTySynD , fromPtrDs , isVecOpenCVInstanceDs , isVecHaskellInstanceDs , mkPlacementNewInstance vTypeName ] where vTypeName :: Name vTypeName = mkName vTypeNameStr cVecTypeStr :: String cVecTypeStr = vTypeNameStr vTypeQ :: Q Type vTypeQ = conT vTypeName depthTypeQ :: Q Type depthTypeQ = conT depthTypeName dimTypeQ :: Q Type dimTypeQ = litT (numTyLit dim) vecTySynD :: Q Dec vecTySynD = tySynD vTypeName [] ([t|Vec|] `appT` dimTypeQ `appT` depthTypeQ) fromPtrDs :: Q [Dec] fromPtrDs = [d| instance FromPtr $(vTypeQ) where fromPtr = objFromPtr Vec $ $(finalizerExpQ) |] where finalizerExpQ :: Q Exp finalizerExpQ = do ptr <- newName "ptr" lamE [varP ptr] $ quoteExp CU.exp $ "void { delete $(" <> cVecTypeStr <> " * " <> nameBase ptr <> ") }" isVecOpenCVInstanceDs :: Q [Dec] isVecOpenCVInstanceDs = [d| instance IsVec (Vec $(dimTypeQ)) $(depthTypeQ) where toVec = id toVecIO = pure fromVec = id |] isVecHaskellInstanceDs :: Q [Dec] isVecHaskellInstanceDs = let ix = fromInteger dim - 2 in withLinear (linearTypeQs !! ix) (linearConNames !! ix) where linearTypeQs :: [Q Type] linearTypeQs = map conT [''V2, ''V3, ''V4] linearConNames :: [Name] linearConNames = ['V2, 'V3, 'V4] withLinear :: Q Type -> Name -> Q [Dec] withLinear lvTypeQ lvConName = [d| instance IsVec $(lvTypeQ) $(depthTypeQ) where toVec = unsafePerformIO . toVecIO toVecIO = $(toVecIOExpQ) fromVec = $(fromVecExpQ) |] where toVecIOExpQ :: Q Exp toVecIOExpQ = do ns <- mapM newName elemNames lamE [conP lvConName $ map varP ns] $ appE [e|fromPtr|] $ quoteExp CU.exp $ inlineCStr ns where inlineCStr :: [Name] -> String inlineCStr ns = concat [ cVecTypeStr , " * { new cv::Vec<" , cDepthTypeStr , ", " , show dim , ">(" <> intercalate ", " (map elemQuote ns) <> ")" , " }" ] where elemQuote :: Name -> String elemQuote n = "$(" <> cDepthTypeStr <> " " <> nameBase n <> ")" fromVecExpQ :: Q Exp fromVecExpQ = do vec <- newName "vec" vecPtr <- newName "vecPtr" ptrNames <- mapM (newName . (<> "Ptr")) elemNames withPtrNames vec vecPtr ptrNames where withPtrNames :: Name -> Name -> [Name] -> Q Exp withPtrNames vec vecPtr ptrNames = lamE [varP vec] $ appE [e|unsafePerformIO|] $ withPtrVarsExpQ ptrNames where withPtrVarsExpQ :: [Name] -> Q Exp withPtrVarsExpQ = foldr (\p -> appE [e|alloca|] . lamE [varP p]) withAllocatedVars withAllocatedVars :: Q Exp withAllocatedVars = appE ([e|withPtr|] `appE` varE vec) $ lamE [varP vecPtr] $ doE [ noBindS $ quoteExp CU.block inlineCStr , noBindS extractExpQ ] inlineCStr :: String inlineCStr = unlines $ concat [ "void {" , "const cv::Vec<" , cDepthTypeStr , ", " <> show dim <> "> & p = *$(" , cVecTypeStr , " * " , nameBase vecPtr , ");" ] : map ptrLine (zip [0..] ptrNames) <> ["}"] where ptrLine :: (Int, Name) -> String ptrLine (ix, ptrName) = "*$(" <> cDepthTypeStr <> " * " <> nameBase ptrName <> ") = p[" <> show ix <> "];" -- Applies the constructor to the values that are -- read from the pointers. extractExpQ :: Q Exp extractExpQ = foldl (\acc peekExp -> [e|(<*>)|] `appE` acc `appE` peekExp) ([e|pure|] `appE` conE lvConName) peekExpQs where peekExpQs :: [Q Exp] peekExpQs = map (\p -> [e|peek|] `appE` varE p) ptrNames elemNames :: [String] elemNames = take (fromInteger dim) ["x", "y", "z", "w"]
Cortlandd/haskell-opencv
src/OpenCV/Internal/Core/Types/Vec/TH.hs
Haskell
bsd-3-clause
6,443
module Network.Riak.HTTP.JSON (put, tryPut, putWithRandomKey, putWithIndexes, get, defaultClient) where import Network.Riak.HTTP.Types import Network.Riak.HTTP.Internal import Network.HTTP import Data.Aeson import Data.ByteString.Lazy (ByteString(..)) import qualified Data.ByteString.Lazy.Char8 as BLC put :: (ToJSON v) => Client -> Bucket -> Key -> v -> IO (Either String ()) put c b k v = putWithIndexes c b k [] v putWithRandomKey :: (ToJSON v) => Client -> Bucket -> v -> IO (Either String Key) putWithRandomKey c b = putWithContentTypeWithRandomKey "application/json" c b . encode -- | Try a put, finding a client where it succeeds tryPut :: (ToJSON v) => [Client] -> Bucket -> Key -> v -> IO (Either String ()) tryPut c b k v = tryPutWithIndexes c b k [] v putWithIndexes :: (ToJSON v) => Client -> Bucket -> Key -> [IndexTag] -> v -> IO (Either String ()) putWithIndexes client bucket key indexTags value = putWithContentType "application/json" client bucket key indexTags (encode value) tryPutWithIndexes :: (ToJSON v) => [Client] -> Bucket -> Key -> [IndexTag] -> v -> IO (Either String ()) tryPutWithIndexes clients bucket key indexTags value = tryClients clients $ \client -> putWithIndexes client bucket key indexTags value
ThoughtLeadr/Riak-Haskell-HTTP-Client
src/Network/Riak/HTTP/JSON.hs
Haskell
bsd-3-clause
1,316
-- | Equations. {-# LANGUAGE TypeFamilies #-} module Twee.Equation where import Twee.Base import Control.Monad -------------------------------------------------------------------------------- -- * Equations. -------------------------------------------------------------------------------- data Equation f = (:=:) { eqn_lhs :: {-# UNPACK #-} !(Term f), eqn_rhs :: {-# UNPACK #-} !(Term f) } deriving (Eq, Ord, Show) type EquationOf a = Equation (ConstantOf a) instance Symbolic (Equation f) where type ConstantOf (Equation f) = f termsDL (t :=: u) = termsDL t `mplus` termsDL u subst_ sub (t :=: u) = subst_ sub t :=: subst_ sub u instance PrettyTerm f => Pretty (Equation f) where pPrint (x :=: y) = pPrint x <+> text "=" <+> pPrint y -- | Order an equation roughly left-to-right. -- However, there is no guarantee that the result is oriented. order :: Function f => Equation f -> Equation f order (l :=: r) | l == r = l :=: r | lessEqSkolem l r = r :=: l | otherwise = l :=: r -- | Apply a function to both sides of an equation. bothSides :: (Term f -> Term f') -> Equation f -> Equation f' bothSides f (t :=: u) = f t :=: f u -- | Is an equation of the form t = t? trivial :: Eq f => Equation f -> Bool trivial (t :=: u) = t == u -- | A total order on equations. Equations with lesser terms are smaller. simplerThan :: Function f => Equation f -> Equation f -> Bool eq1 `simplerThan` eq2 = --traceShow (hang (pPrint eq1) 2 (text "`simplerThan`" <+> pPrint eq2 <+> text "=" <+> pPrint res)) res t1 `lessEqSkolem` t2 && (t1 /= t2 || ((u1 `lessEqSkolem` u2 && u1 /= u2))) where t1 :=: u1 = canonicalise (order eq1) t2 :=: u2 = canonicalise (order eq2) -- | Match one equation against another. matchEquation :: Equation f -> Equation f -> Maybe (Subst f) matchEquation (pat1 :=: pat2) (t1 :=: t2) = do sub <- match pat1 t1 matchIn sub pat2 t2
nick8325/kbc
src/Twee/Equation.hs
Haskell
bsd-3-clause
1,895
data Cartesian = Cartesian Double Double deriving Show mulC :: Cartesian -> Double -> Cartesian mulC (Cartesian x y) n = Cartesian (x * n) (y * n) point1 :: Cartesian point1 = Cartesian 8 5 data Polar = Polar Double Double deriving Show mulP :: Polar -> Double -> Polar mulP (Polar d r) n = Polar (d * n) r point2 :: Polar point2 = Polar 10 (pi / 6)
YoshikuniJujo/funpaala
samples/21_adt/cpd.hs
Haskell
bsd-3-clause
355
----------------------------------------------------------------------------- -- | -- Module : Main (HaddockCoverage) -- Copyright : (C) 2015 Ivan Perez -- License : BSD-style (see the file LICENSE) -- Maintainer : Ivan Perez <ivan.perez@keera.co.uk> -- Stability : provisional -- Portability : portable -- -- Copyright notice: This file borrows code -- https://hackage.haskell.org/package/lens-4.7/src/tests/doctests.hsc -- which is itself licensed BSD-style as well. -- -- Run haddock on a source tree and report if anything in any -- module is not documented. ----------------------------------------------------------------------------- module Main where import Control.Applicative import Control.Monad import Data.List import System.Directory import System.Exit import System.FilePath import System.IO import System.Process import Text.Regex.Posix main :: IO () main = do -- Find haskell modules -- TODO: Ideally cabal should do this (provide us with the -- list of modules). An alternative would be to use cabal haddock -- but that would need a --no-html argument or something like that. -- Alternatively, we could use cabal haddock with additional arguments. -- -- See: -- https://github.com/keera-studios/haddock/commit/d5d752943c4e5c6c9ffcdde4dc136fcee967c495 -- https://github.com/haskell/haddock/issues/309#issuecomment-150811929 files <- getSources let haddockArgs = [ "--no-warnings" ] ++ files let cabalArgs = [ "exec", "--", "haddock" ] ++ haddockArgs print cabalArgs (code, out, _err) <- readProcessWithExitCode "cabal" cabalArgs "" -- Filter out coverage lines, and find those that denote undocumented -- modules. -- -- TODO: is there a way to annotate a function as self-documenting, -- in the same way we do with ANN for hlint? let isIncompleteModule :: String -> Bool isIncompleteModule line = isCoverageLine line && not (line =~ "^ *100%") where isCoverageLine :: String -> Bool isCoverageLine line = line =~ "^ *[0-9]+%" let incompleteModules :: [String] incompleteModules = filter isIncompleteModule $ lines out -- Based on the result of haddock, report errors and exit. -- Note that, unline haddock, this script does not -- output anything to stdout. It uses stderr instead -- (as it should). case (code, incompleteModules) of (ExitSuccess , []) -> return () (ExitFailure _, _) -> exitFailure (_ , _) -> do hPutStrLn stderr "The following modules are not fully documented:" mapM_ (hPutStrLn stderr) incompleteModules exitFailure getSources :: IO [FilePath] getSources = filter isHaskellFile <$> go "src" where go dir = do (dirs, files) <- getFilesAndDirectories dir (files ++) . concat <$> mapM go dirs isHaskellFile fp = (isSuffixOf ".hs" fp || isSuffixOf ".lhs" fp) && not (any (`isSuffixOf` fp) excludedFiles) excludedFiles = [ "Yampa.hs", "Random.hs" ] getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath]) getFilesAndDirectories dir = do c <- map (dir </>) . filter (`notElem` ["..", "."]) <$> getDirectoryContents dir (,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c -- find-based implementation (not portable) -- -- getSources :: IO [FilePath] -- getSources = fmap lines $ readProcess "find" ["src/", "-iname", "*hs"] ""
ivanperez-keera/Yampa
yampa/tests/HaddockCoverage.hs
Haskell
bsd-3-clause
3,394
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Dimensions.KM ( allDimensions ) where import Duckling.Dimensions.Types allDimensions :: [Seal Dimension] allDimensions = [ Seal Distance , Seal Numeral , Seal Ordinal , Seal Quantity , Seal Temperature , Seal Volume ]
facebookincubator/duckling
Duckling/Dimensions/KM.hs
Haskell
bsd-3-clause
461
module Experiment (experiment, generators) where import Data.Monoid import Control.Arrow import Simulation.Aivika import Simulation.Aivika.Experiment import Simulation.Aivika.Experiment.Chart import qualified Simulation.Aivika.Results.Transform as T -- | The simulation specs. specs = Specs { spcStartTime = 0.0, spcStopTime = 8760.0, spcDT = 0.1, spcMethod = RungeKutta4, spcGeneratorType = SimpleGenerator } -- | The experiment. experiment :: Experiment experiment = defaultExperiment { experimentSpecs = specs, experimentRunCount = 500, -- experimentRunCount = 10, experimentTitle = "Port Operations" } portTime = resultByName "portTime" berth = T.Resource $ resultByName "berth" berthCountStats = T.tr $ T.resourceCountStats berth berthUtilisationCount = T.tr $ T.resourceUtilisationCountStats berth berthQueueCount = T.resourceQueueCount berth berthQueueCountStats = T.tr $ T.resourceQueueCountStats berth berthWaitTime = T.tr $ T.resourceWaitTime berth tug = T.Resource $ resultByName "tug" tugCountStats = T.tr $ T.resourceCountStats tug tugUtilisationCount = T.tr $ T.resourceUtilisationCountStats tug tugQueueCount = T.resourceQueueCount tug tugQueueCountStats = T.tr $ T.resourceQueueCountStats tug tugWaitTime = T.tr $ T.resourceWaitTime tug generators :: ChartRendering r => [WebPageGenerator r] generators = [outputView defaultExperimentSpecsView, outputView defaultInfoView, outputView $ defaultFinalStatsView { finalStatsTitle = "The Port Time Summary", finalStatsSeries = portTime }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Resource Queue Length", finalStatsSeries = berthQueueCountStats <> tugQueueCountStats }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Resource Wait Time", finalStatsSeries = berthWaitTime <> tugWaitTime }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Resource Utilisation Summary", finalStatsSeries = berthUtilisationCount <> tugUtilisationCount }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Resource Availability Summary", finalStatsSeries = berthCountStats <> tugCountStats }, outputView $ defaultDeviationChartView { deviationChartTitle = "The Berth Resource Queue Length", deviationChartRightYSeries = berthQueueCount <> berthQueueCountStats }, outputView $ defaultDeviationChartView { deviationChartTitle = "The Tug Resource Queue Length", deviationChartRightYSeries = tugQueueCount <> tugQueueCountStats }]
dsorokin/aivika-experiment-chart
examples/PortOperations/Experiment.hs
Haskell
bsd-3-clause
2,683
-- |Some common functions that are available to all hasp programs by default. -- -- Note that this does not include syntactic forms such as if, define, lambda, -- and and (since they require behaviour such as short circuiting and mutation -- that are not available to hasp functions), as well as standard library -- functions that can be more easily defined in the hasp language. module Builtins ( globalEnv , numericFold , minusHNum , numericBinOp , numericUnaryOp , numericBinPred , list , cons , car , cdr ) where import qualified Data.Map as Map import Error import DataTypes globalEnv :: Env globalEnv = Env $ Map.fromList [ ("+", numericFold (+) 0) , ("*", numericFold (*) 1) , ("-", minusHNum) , ("/", numericBinOp "/" divideHNum) , ("quotient", numericBinOp "quotient" divHNum) , ("modulo", numericBinOp "modulo" modHNum) , ("abs", numericUnaryOp "abs" abs) , ("sgn", numericUnaryOp "sgn" signum) , ("eq?", numericBinPred "eq?" (==)) , ("=", numericBinPred "=" (==)) , ("<", numericBinPred "<" (<)) , ("<=", numericBinPred "<=" (<=)) , (">", numericBinPred ">" (>)) , (">=", numericBinPred ">=" (>=)) , ("!=", numericBinPred "!=" (/=)) , ("list", list) , ("cons", cons) , ("car", car) , ("cdr", cdr) , ("empty?", testEmptyList) ] -- Builtin numeric operations foldlHNum :: (HNum -> HNum -> HNum) -> HNum -> [HData] -> ThrowsError HNum foldlHNum _ x0 [] = return x0 foldlHNum f x0 ((HN x):xs) = foldlHNum f (x0 `f` x) xs foldlHNum f x0 (x:xs) = throw . errNotNum $ show x foldlHNum1 :: String -> (HNum -> HNum -> HNum) -> [HData] -> ThrowsError HNum foldlHNum1 fname _ [] = throw $ errTooFewArgs fname foldlHNum1 _ f ((HN x):xs) = foldlHNum f x xs foldlHNum1 _ f (x:xs) = throw . errNotNum $ show x numericFold :: (HNum -> HNum -> HNum) -> HNum -> HData numericFold op x0 = HFunc emptyEnv $ \_ args -> do result <- foldlHNum op x0 args return $ HN result minusHNum :: HData minusHNum = HFunc emptyEnv $ \_ args -> case args of [HN x] -> return . HN $ negate x _ -> do result <- foldlHNum1 "-" (-) args return $ HN result divideByZeroError :: HaspError divideByZeroError = Error "Division by zero" divideHNum :: HNum -> HNum -> ThrowsError HNum _ `divideHNum` (HInt 0) = throw divideByZeroError _ `divideHNum` (HFloat 0) = throw divideByZeroError (HInt x) `divideHNum` (HInt y) = return $ HFloat ((fromIntegral x) / (fromIntegral y)) (HInt x) `divideHNum` (HFloat y) = return $ HFloat ((fromIntegral x) / y) (HFloat x) `divideHNum` (HInt y) = return $ HFloat (x / (fromIntegral y)) (HFloat x) `divideHNum` (HFloat y) = return $ HFloat (x / y) numericBinOp :: String -> (HNum -> HNum -> ThrowsError HNum) -> HData numericBinOp opName op = HFunc emptyEnv $ \_ args -> case args of [HN x, HN y] -> do result <- x `op` y return $ HN result [x, HN _] -> throw . errNotNum $ show x [HN _, y] -> throw . errNotNum $ show y [x, _] -> throw . errNotNum $ show x _ -> throw $ errNumArgs opName 2 (length args) numericBinPred :: String -> (HNum -> HNum -> Bool) -> HData numericBinPred predName op = HFunc emptyEnv $ \_ args -> case args of [HN x, HN y] -> return . HBool $ x `op` y [x, HN _] -> throw . errNotNum $ show x [HN _, y] -> throw . errNotNum $ show y [x, _] -> throw . errNotNum $ show x _ -> throw $ errNumArgs predName 2 (length args) notIntegerError :: HData -> HaspError notIntegerError x = TypeError $ "Value `" ++ show x ++ "` is not of type Integer." divHNum :: HNum -> HNum -> ThrowsError HNum _ `divHNum` (HInt 0) = throw divideByZeroError _ `divHNum` y@(HFloat _) = throw $ notIntegerError (HN y) x@(HFloat _) `divHNum` _ = throw $ notIntegerError (HN x) (HInt x) `divHNum` (HInt y) = return $ HInt (x `div` y) modHNum :: HNum -> HNum -> ThrowsError HNum _ `modHNum` (HInt 0) = throw divideByZeroError _ `modHNum` y@(HFloat _) = throw $ notIntegerError (HN y) x@(HFloat _) `modHNum` _ = throw $ notIntegerError (HN x) (HInt x) `modHNum` (HInt y) = return $ HInt (x `mod` y) numericUnaryOp :: String -> (HNum -> HNum) -> HData numericUnaryOp fname f = HFunc emptyEnv $ \_ args -> case args of [HN x] -> return . HN $ f x [x] -> throw . errNotNum $ show x _ -> throw $ errNumArgs fname 1 (length args) -- Builtin list operations list :: HData list = HFunc emptyEnv $ \_ args -> return $ HList args cons :: HData cons = HFunc emptyEnv $ \_ args -> case args of [x, HList xs] -> return $ HList (x:xs) [_, _] -> throw $ errWrongType "cons" "list" _ -> throw $ errNumArgs "cons" 2 (length args) car :: HData car = HFunc emptyEnv $ \_ args -> case args of [HList []] -> throw $ errEmptyList "car" [HList (x:_)] -> return x [_] -> throw $ errWrongType "car" "list" _ -> throw $ errNumArgs "car" 1 (length args) cdr :: HData cdr = HFunc emptyEnv $ \_ args -> case args of [HList []] -> throw $ errEmptyList "cdr" [HList (_:xs)] -> return $ HList xs [_] -> throw $ errWrongType "cdr" "list" _ -> throw $ errNumArgs "cdr" 1 (length args) testEmptyList :: HData testEmptyList = HFunc emptyEnv $ \_ args -> case args of [HList []] -> return $ HBool True [HList (_:_)] -> return $ HBool False [_] -> throw $ errWrongType "empty?" "list" _ -> throw $ errNumArgs "empty?" 1 (length args)
aldld/hasp
src/Builtins.hs
Haskell
bsd-3-clause
5,719
-- | The type of tile kinds. Every terrain tile in the game is -- an instantiated tile kind. module Game.LambdaHack.Content.TileKind ( pattern S_UNKNOWN_SPACE, pattern S_UNKNOWN_OUTER_FENCE, pattern S_BASIC_OUTER_FENCE, pattern AQUATIC , TileKind(..), ProjectileTriggers(..), Feature(..) , makeData , isUknownSpace, unknownId , isSuspectKind, isOpenableKind, isClosableKind , talterForStairs, floorSymbol , mandatoryGroups, mandatoryGroupsSingleton #ifdef EXPOSE_INTERNAL -- * Internal operations , validateSingle, validateAll, validateDups #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import Data.Word (Word8) import Game.LambdaHack.Content.ItemKind (ItemKind) import Game.LambdaHack.Definition.Color import Game.LambdaHack.Definition.ContentData import Game.LambdaHack.Definition.Defs import Game.LambdaHack.Definition.DefsInternal -- | The type of kinds of terrain tiles. See @Tile.hs@ for explanation -- of the absence of a corresponding type @Tile@ that would hold -- particular concrete tiles in the dungeon. -- Note that tile names (and any other content names) should not be plural -- (that would lead to "a stairs"), so "road with cobblestones" is fine, -- but "granite cobblestones" is wrong. -- -- Tile kind for unknown space has the minimal @ContentId@ index. -- The @talter@ for unknown space is @1@ and no other tile kind has that value. data TileKind = TileKind { tsymbol :: Char -- ^ map symbol , tname :: Text -- ^ short description , tfreq :: Freqs TileKind -- ^ frequency within groups , tcolor :: Color -- ^ map color , tcolor2 :: Color -- ^ map color when not in FOV , talter :: Word8 -- ^ minimal skill needed to activate embeds -- and, in case of big actors not standing on -- the tile, to alter the tile in any way , tfeature :: [Feature] -- ^ properties; order matters } deriving Show -- No Eq and Ord to make extending logically sound -- | All possible terrain tile features. data Feature = Embed (GroupName ItemKind) -- ^ initially an item of this group is embedded; -- we assume the item has effects and is supposed to be triggered | OpenTo (GroupName TileKind) -- ^ goes from a closed to closed or open tile when altered | CloseTo (GroupName TileKind) -- ^ goes from an open to open or closed tile when altered | ChangeTo (GroupName TileKind) -- ^ alters tile, but does not change walkability | OpenWith ProjectileTriggers [(Int, GroupName ItemKind)] (GroupName TileKind) -- ^ alters tile, as before, using up all listed items from the ground -- and equipment; the list never empty; for simplicity, such tiles -- are never taken into account when pathfinding | CloseWith ProjectileTriggers [(Int, GroupName ItemKind)] (GroupName TileKind) | ChangeWith ProjectileTriggers [(Int, GroupName ItemKind)] (GroupName TileKind) | HideAs (GroupName TileKind) -- ^ when hidden, looks as the unique tile of the group | BuildAs (GroupName TileKind) -- ^ when generating, may be transformed to the unique tile of the group | RevealAs (GroupName TileKind) -- ^ when generating in opening, can be revealed to belong to the group | ObscureAs (GroupName TileKind) -- ^ when generating in solid wall, can be revealed to belong to the group | Walkable -- ^ actors can walk through | Clear -- ^ actors can see through | Dark -- ^ is not lit with an ambient light | OftenItem -- ^ initial items often generated there | VeryOftenItem -- ^ initial items very often generated there | OftenActor -- ^ initial actors often generated there; -- counterpart of @VeryOftenItem@ for dark places | NoItem -- ^ no items ever generated there | NoActor -- ^ no actors ever generated there | ConsideredByAI -- ^ even if otherwise uninteresting, taken into -- account for triggering by AI | Trail -- ^ used for visible trails throughout the level | Spice -- ^ in place normal legend and in override, -- don't roll a tile kind only once per place, -- but roll for each position; one non-spicy -- (according to frequencies of non-spicy) and -- at most one spicy (according to their frequencies) -- is rolled per place and then, once for each -- position, one of the two is semi-randomly chosen -- (according to their individual frequencies only) deriving (Show, Eq) -- | Marks whether projectiles are permitted to trigger the tile transformation -- action. data ProjectileTriggers = ProjYes | ProjNo deriving (Show, Eq) -- | Validate a single tile kind. validateSingle :: TileKind -> [Text] validateSingle t@TileKind{..} = [ "suspect tile is walkable" | Walkable `elem` tfeature && isSuspectKind t ] ++ [ "openable tile is open" | Walkable `elem` tfeature && isOpenableKind t ] ++ [ "closable tile is closed" | Walkable `notElem` tfeature && isClosableKind t ] ++ [ "walkable tile is considered for activating by AI" | Walkable `elem` tfeature && ConsideredByAI `elem` tfeature ] ++ [ "trail tile not walkable" | Walkable `notElem` tfeature && Trail `elem` tfeature ] ++ [ "OftenItem and NoItem on a tile" | OftenItem `elem` tfeature && NoItem `elem` tfeature ] ++ [ "OftenActor and NoActor on a tile" | OftenItem `elem` tfeature && NoItem `elem` tfeature ] ++ (let f :: Feature -> Bool f OpenTo{} = True f CloseTo{} = True f ChangeTo{} = True f _ = False ts = filter f tfeature in [ "more than one OpenTo, CloseTo and ChangeTo specification" | length ts > 1 ]) ++ (let f :: Feature -> Bool f HideAs{} = True f _ = False ts = filter f tfeature in ["more than one HideAs specification" | length ts > 1]) ++ (let f :: Feature -> Bool f BuildAs{} = True f _ = False ts = filter f tfeature in ["more than one BuildAs specification" | length ts > 1]) ++ concatMap (validateDups t) [ Walkable, Clear, Dark, OftenItem, VeryOftenItem, OftenActor , NoItem, NoActor, ConsideredByAI, Trail, Spice ] validateDups :: TileKind -> Feature -> [Text] validateDups TileKind{..} feat = let ts = filter (== feat) tfeature in ["more than one" <+> tshow feat <+> "specification" | length ts > 1] -- | Validate all tile kinds. -- -- We don't check it any more, but if tiles look the same on the map -- (symbol and color), their substantial features should be the same, too, -- unless there is a good reason they shouldn't. Otherwise the player has -- to inspect manually all the tiles with this look to see if any is special. -- This tends to be tedious. Note that tiles may freely differ wrt text blurb, -- dungeon generation rules, AI preferences, etc., whithout causing the tedium. validateAll :: [TileKind] -> ContentData TileKind -> [Text] validateAll content cotile = let f :: Feature -> Bool f HideAs{} = True f BuildAs{} = True f _ = False wrongGrooup k grp = not (oisSingletonGroup cotile grp) || isJust (grp `lookup` tfreq k) wrongFooAsGroups = [ cgroup | k <- content , let (cgroup, notSingleton) = case find f (tfeature k) of Just (HideAs grp) | wrongGrooup k grp -> (grp, True) Just (BuildAs grp) | wrongGrooup k grp -> (grp, True) _ -> (undefined, False) , notSingleton ] in [ "HideAs or BuildAs groups not singletons or point to themselves:" <+> tshow wrongFooAsGroups | not $ null wrongFooAsGroups ] ++ [ "unknown tile (the first) should be the unknown one" | talter (head content) /= 1 || tname (head content) /= "unknown space" ] ++ [ "no tile other than the unknown (the first) should require skill 1" | any (\tk -> talter tk == 1) (tail content) ] -- * Mandatory item groups mandatoryGroupsSingleton :: [GroupName TileKind] mandatoryGroupsSingleton = [S_UNKNOWN_SPACE, S_UNKNOWN_OUTER_FENCE, S_BASIC_OUTER_FENCE] pattern S_UNKNOWN_SPACE, S_UNKNOWN_OUTER_FENCE, S_BASIC_OUTER_FENCE :: GroupName TileKind mandatoryGroups :: [GroupName TileKind] mandatoryGroups = [] pattern S_UNKNOWN_SPACE = GroupName "unknown space" pattern S_UNKNOWN_OUTER_FENCE = GroupName "unknown outer fence" pattern S_BASIC_OUTER_FENCE = GroupName "basic outer fence" -- * Optional item groups pattern AQUATIC :: GroupName TileKind pattern AQUATIC = GroupName "aquatic" isUknownSpace :: ContentId TileKind -> Bool {-# INLINE isUknownSpace #-} isUknownSpace tt = toContentId 0 == tt unknownId :: ContentId TileKind {-# INLINE unknownId #-} unknownId = toContentId 0 isSuspectKind :: TileKind -> Bool isSuspectKind t = let getTo RevealAs{} = True getTo ObscureAs{} = True getTo _ = False in any getTo $ tfeature t isOpenableKind :: TileKind -> Bool isOpenableKind t = let getTo OpenTo{} = True getTo _ = False in any getTo $ tfeature t isClosableKind :: TileKind -> Bool isClosableKind t = let getTo CloseTo{} = True getTo _ = False in any getTo $ tfeature t talterForStairs :: Word8 talterForStairs = 3 floorSymbol :: Char floorSymbol = '·' -- '\x00B7' -- Alter skill schema: -- 0 can be altered by everybody (escape) -- 1 unknown only -- 2 openable and suspect -- 3 stairs -- 4 closable -- 5 changeable (e.g., caches) -- 10 weak obstructions -- 50 considerable obstructions -- 100 walls -- maxBound impenetrable walls, etc., can never be altered makeData :: [TileKind] -> [GroupName TileKind] -> [GroupName TileKind] -> ContentData TileKind makeData content groupNamesAtMostOne groupNames = makeContentData "TileKind" tname tfreq validateSingle validateAll content (mandatoryGroupsSingleton ++ groupNamesAtMostOne) (mandatoryGroups ++ groupNames)
LambdaHack/LambdaHack
definition-src/Game/LambdaHack/Content/TileKind.hs
Haskell
bsd-3-clause
10,569
module Action where import Storage import Glue generateSolutions :: IO () generateSolutions = do prepareDB dbName mRest <- dbDo getRest case mRest of Nothing -> do (sols, rest) <- return $ firstSolutions 1 dbDo (addSolutions sols) dbDo (replaceRest rest) Just rest -> do (sols, newRest) <- return $ makeSolutions 1 rest dbDo (addSolutions sols) dbDo (replaceRest newRest) generatePuzzles :: IO () generatePuzzles = do prepareDB dbName sols <- dbDo getSolutions puzzles <- return $ makePuzzles sols dbDo (addPuzzles puzzles) generateGradedPuzzles :: IO () generateGradedPuzzles = do prepareDB dbName sols <- dbDo getSolutions gradedPuzzles <- return $ makeAndGradePuzzles sols (sols, gradedList) <- return $ unzip gradedPuzzles puzzles <- return $ map (\graded -> fst $ unzip graded) gradedList dbDo (addPuzzles (zip sols puzzles)) dbDo (addGrades (concat gradedList))
Stulv/sudoku
src/Action.hs
Haskell
bsd-3-clause
944
module Data.Geo.GPX.Lens.HdopL where import Data.Lens.Common class HdopL a where hdopL :: Lens a (Maybe Double)
tonymorris/geo-gpx
src/Data/Geo/GPX/Lens/HdopL.hs
Haskell
bsd-3-clause
117
{-# LANGUAGE ScopedTypeVariables #-} module SplitBill where import Control.Exception import Control.Monad import Data.Char import Data.Decimal import System.Directory import System.Environment import System.FilePath import System.IO import qualified Data.Map as Map -- | `AnswersMap` binds textual answers to values of some type so that we can -- easily pattern-match on them later. type AnswersMap a = Map.Map Char a -- #### -- #### Typical questions with corresponding answers maps -- #### data YesNoQuestion = Yes | No deriving (Eq, Show) yesNoAnswersMap :: AnswersMap YesNoQuestion yesNoAnswersMap = Map.fromList [ ( 'y', Yes ), ( 'Y', Yes ), ( 'n', No ), ( 'N', No ) ] data WhoPaidQuestion = Me | He deriving (Eq, Show) whoPaidAnswersMap :: AnswersMap WhoPaidQuestion whoPaidAnswersMap = Map.fromList [ ('m', Me), ('h', He) ] data BoughtForWhomQuestion = ForMe | ForHim | ForBoth deriving (Eq, Show) boughtForWhomAnswersMap :: AnswersMap BoughtForWhomQuestion boughtForWhomAnswersMap = Map.fromList [ ('m', ForMe), ('h', ForHim), ('b', ForBoth) ] data CategoryQuestion = Food | Sweets | Misc deriving (Eq, Show) categoryAnswersMap :: AnswersMap CategoryQuestion categoryAnswersMap = Map.fromList [ ('f', Food), ('s', Sweets), ('m', Misc) ] -- | This functon asks user-specified question as many times as that takes, up -- until user gives one of the acceptable answers. The value that is paired to -- the answer in the answers map is returned. ask :: String -> AnswersMap a -> IO a ask question answers = withoutBuffering $ do putStr question unless (last question == ' ') $ putStr " " hFlush stdout answer <- getChar putStrLn "" case Map.lookup answer answers of Just value -> return value Nothing -> ask question answers -- #### -- #### Helper functions that deal with input-output buffering -- #### -- | Sets specified buffer mode for the duration of the action, resetting things -- back to their previous value afterwards withBufferMode :: BufferMode -> IO a -> IO a withBufferMode mode action = bracket initialize finalize (const action) where initialize = do bufferMode <- hGetBuffering stdin hSetBuffering stdin mode return bufferMode finalize initialMode = hSetBuffering stdin initialMode -- | Run action with line I/O buffering withBuffering :: IO a -> IO a withBuffering = withBufferMode LineBuffering -- | Run action without I/O buffering withoutBuffering :: IO a -> IO a withoutBuffering = withBufferMode NoBuffering -- | Run the action, ask if there are more bills to process. If the answer is -- "yes", repeat, stop otherwise. whileThereAreBills :: IO () -> IO () whileThereAreBills action = do action answer <- ask "Are there more bills to process? (y/n)" yesNoAnswersMap case answer of Yes -> do putStrLn "" whileThereAreBills action No -> return () -- | Ask who paid the bill, then process each of the items of the bill and dump -- the resulting transaction into `hledger.journal`. processBill :: IO () processBill = do date <- askForBillDate payee <- ask "Who paid for this bill? ([m]e/[h]e)" whoPaidAnswersMap state <- whileThereAreItems payee processItem dumpTransaction date state -- | A piece of state that we'll be carrying while processing items data BillProcessingState = BillProcessingState { -- | How much went into expenses:food food :: Decimal -- | How much went into expenses:food:sweets , sweets :: Decimal -- | How much went into expenses:misc , misc :: Decimal -- | How much I withdrew from assets:cash:envelope , wallet :: Decimal -- | How much I lent to or borrowed from assets:loans:vadim , loan :: Decimal } deriving (Eq, Show) -- need those for tests whileThereAreItems :: WhoPaidQuestion -> (WhoPaidQuestion -> BillProcessingState -> IO BillProcessingState) -> IO BillProcessingState whileThereAreItems payee action = helper (BillProcessingState 0 0 0 0 0) where helper state = do state' <- action payee state answer <- ask "Is that all for this bill? (y/n)" yesNoAnswersMap case answer of Yes -> return state' No -> helper state' -- | Update processing state accordingly to how much the item cost, who will use -- it and what category it belonds to processItem :: WhoPaidQuestion -> BillProcessingState -> IO BillProcessingState processItem payee state = do cost <- askForCost boughtFor <- ask "Bought for whom? ([m]e / [h]im / [b]oth)" boughtForWhomAnswersMap category <- if (boughtFor /= ForHim) then ask "What category this item belongs to? ([f]ood / [s]weets / [m]isc)" categoryAnswersMap else return undefined return $ processItem' state payee cost boughtFor category processItem' :: BillProcessingState -> WhoPaidQuestion -> Decimal -> BoughtForWhomQuestion -> CategoryQuestion -> BillProcessingState processItem' state payee cost boughtFor category = let cost' = case boughtFor of ForMe -> cost ForHim -> 0 ForBoth -> cost / 2 loan' = case payee of Me -> case boughtFor of ForMe -> 0 ForHim -> cost ForBoth -> cost' He -> case boughtFor of ForMe -> negate cost ForHim -> 0 ForBoth -> negate cost' state' = if (boughtFor /= ForHim) then incrementCategory category cost' state else state in state' { wallet = wallet state' - if (payee == Me) then cost else 0 , loan = loan state' + loan' } where incrementCategory Food cost state = state { food = food state + cost } incrementCategory Sweets cost state = state { sweets = sweets state + cost } incrementCategory Misc cost state = state { misc = misc state + cost } -- | Trim whitespace (' ', \t, \n, \r, \f, \v) from both ends of the line -- -- Highly inefficient, don't use on huge strings! trim :: String -> String trim str = let dropSpaces = dropWhile isSpace in reverse $ dropSpaces $ reverse $ dropSpaces str -- | Ask for the bill's date in YYYY/MM/DD format askForBillDate :: IO String askForBillDate = withBuffering $ do putStr "Date (YYYY/MM/DD): " hFlush stdout date <- liftM trim getLine if (isMalformed date) then askForBillDate else return date where -- | The date should be in YYYY/MM/DD format isMalformed :: String -> Bool isMalformed s = not $ (length s == 10) && (all isDigit $ take 4 s) && (s !! 4 == '/') && (all isDigit $ take 2 $ drop 5 s) && (s !! 7 == '/') && (all isDigit $ take 2 $ drop 8 s) -- | Ask user how much an item cost askForCost :: IO Decimal askForCost = withBuffering $ do putStr "Cost: " hFlush stdout cost <- liftM trim getLine if (isMalformed cost) then askForCost else return $ read cost where -- | The cost is valid if it's a series of digits followed by a dot and -- another series of digits. The latter shouldn't be longer than two chars isMalformed :: String -> Bool isMalformed str = let str' = dropWhile isDigit str in not $ (null str') || ( (head str' == '.') && (all isDigit $ tail str') && (length (tail str') <= 2) ) -- | Get the default journal file path specified by the environment. -- Like ledger, we look first for the LEDGER_FILE environment -- variable, and if that does not exist, for the legacy LEDGER -- environment variable. If neither is set, or the value is blank, -- return the hard-coded default, which is @.hledger.journal@ in the -- users's home directory (or in the current directory, if we cannot -- determine a home directory). -- -- Shamelessly stolen from hledger's code. defaultJournalPath :: IO String defaultJournalPath = do s <- envJournalPath if null s then defaultJournalPath else return s where envJournalPath = getEnv "LEDGER_FILE" `catch` (\(_::IOException) -> getEnv "LEDGER" `catch` (\(_::IOException) -> return "")) defaultJournalPath = do home <- getHomeDirectory `catch` (\(_::IOException) -> return "") return $ home </> ".hledger.journal" -- | Write the transaction into `hledger.journal` dumpTransaction :: String -> BillProcessingState -> IO () dumpTransaction date state = do let str = transactionToString putStrLn "" putStrLn str good <- withoutBuffering $ ask "Write this transaction to the journal? (y/n) " yesNoAnswersMap case good of Yes -> do path <- defaultJournalPath putStrLn $ "Writing to " ++ path appendFile path ("\n" ++ str) No -> return () where transactionToString = unlines $ [ unwords $ [date, "Сходили с Вадиком в «Сельпо»"] ] ++ (transactionLine (food state) (/= 0) "expenses:food ") ++ (transactionLine (sweets state) (/= 0) "expenses:food:sweets") ++ (transactionLine (misc state) (/= 0) "expenses:misc ") ++ (transactionLine (wallet state) (< 0) "assets:cash:envelope") ++ (transactionLine (loan state) (/= 0) "assets:loan:vadim ") transactionLine value condition account = if (condition value) then [ concat [ offset, account, offset, amountToString value ] ] else [] offset = " " amountToString = show
Minoru/split-bill-hs
src/SplitBill.hs
Haskell
bsd-3-clause
9,743
{-# OPTIONS_HADDOCK hide, prune #-} module Import.NoFoundation ( module Import ) where import ClassyPrelude.Yesod as Import hiding (race_) import Model as Import import Settings as Import import Settings.StaticFiles as Import import Yesod.Auth as Import import Yesod.Core.Types as Import (loggerSet) import Yesod.Default.Config2 as Import
mb21/qua-kit
apps/hs/qua-server/src/Import/NoFoundation.hs
Haskell
mit
396
module TestDemoNeuron where import Test.Hspec import AI.DemoNeuron import TestNeuron testDemoNeuron :: IO () testDemoNeuron = hspec $ do describe "Reduced Neuron" $ it "should pass tests" $ True `shouldBe` True describe "L2 Neuron" $ it "should pass tests" $ True `shouldBe` True
jbarrow/LambdaNet
test/TestDemoNeuron.hs
Haskell
mit
308
{-# LANGUAGE RecordWildCards #-} -- | Logic of application and verification of data in Poll. module Pos.DB.Update.Poll.Logic.Apply ( verifyAndApplyUSPayload , verifyAndApplyProposal , verifyAndApplyVoteDo ) where import Universum hiding (id) import Control.Monad.Except (MonadError, runExceptT, throwError) import qualified Data.HashSet as HS import Data.List (partition) import qualified Data.List.NonEmpty as NE import Formatting (build, builder, int, sformat, (%)) import Pos.Binary.Class (biSize) import Pos.Chain.Block (HeaderHash, IsMainHeader (..), headerHashG, headerSlotL) import Pos.Chain.Genesis as Genesis (Config (..), configBlkSecurityParam, configBlockVersionData, configEpochSlots) import Pos.Chain.Update (BlockVersion, BlockVersionData (..), ConfirmedProposalState (..), DecidedProposalState (..), DpsExtra (..), MonadPoll (..), MonadPollRead (..), PollVerFailure (..), ProposalState (..), SoftwareVersion (..), UndecidedProposalState (..), UpId, UpdatePayload (..), UpdateProposal (..), UpdateVote (..), UpsExtra (..), blockVersionL, bvdUpdateProposalThd, checkUpdatePayload, psProposal) import Pos.Core (BlockCount, ChainDifficulty (..), Coin, EpochIndex, SlotCount, SlotId (..), addressHash, applyCoinPortionUp, coinToInteger, difficultyL, epochIndexL, flattenSlotId, sumCoins, unflattenSlotId, unsafeIntegerToCoin) import Pos.Core.Attributes (areAttributesKnown) import Pos.Crypto (hash, shortHashF) import Pos.DB.Update.Poll.Logic.Base (canBeAdoptedBV, canCreateBlockBV, confirmBlockVersion, isDecided, mkTotNegative, mkTotPositive, mkTotSum, putNewProposal, voteToUProposalState) import Pos.DB.Update.Poll.Logic.Version (verifyAndApplyProposalBVS, verifyBlockAndSoftwareVersions) import Pos.Util.Some (Some (..)) import Pos.Util.Wlog (logDebug, logInfo, logNotice) type ApplyMode m = ( MonadError PollVerFailure m , MonadPoll m ) -- | Verify UpdatePayload with respect to data provided by -- MonadPoll. If data is valid it is also applied. Otherwise -- PollVerificationFailure is thrown using MonadError type class. -- -- The first argument specifies whether we should perform unknown data -- checks. Currently it means that if it's 'True', then proposal (if -- it exists) must not have unknown attributes. -- -- When the second argument is 'Left epoch', it means that temporary payload -- for given slot is applied. In this case threshold for inclusion of proposal -- into block is intentionally not checked. -- When it is 'Right header', it means that payload from block with -- given header is applied and in this case threshold for update proposal is -- checked. verifyAndApplyUSPayload :: ApplyMode m => Genesis.Config -> BlockVersion -> Bool -> Either SlotId (Some IsMainHeader) -> UpdatePayload -> m () verifyAndApplyUSPayload genesisConfig lastAdopted verifyAllIsKnown slotOrHeader upp@UpdatePayload {..} = do -- First of all, we verify data. either (throwError . PollInvalidUpdatePayload) pure =<< runExceptT (checkUpdatePayload (configProtocolMagic genesisConfig) upp) whenRight slotOrHeader $ verifyHeader lastAdopted unless isEmptyPayload $ do -- Then we split all votes into groups. One group consists of -- votes for proposal from payload. Each other group consists of -- votes for other proposals. let upId = hash <$> upProposal let votePredicate vote = maybe False (uvProposalId vote ==) upId let (curPropVotes, otherVotes) = partition votePredicate upVotes let otherGroups = NE.groupWith uvProposalId otherVotes -- When there is proposal in payload, it's verified and applied. whenJust upProposal $ verifyAndApplyProposal genesisBvd verifyAllIsKnown slotOrHeader curPropVotes -- Then we also apply votes from other groups. -- ChainDifficulty is needed, because proposal may become approved -- and then we'll need to track whether it becomes confirmed. let cd = case slotOrHeader of Left _ -> Nothing Right h -> Just (h ^. difficultyL, h ^. headerHashG) mapM_ (verifyAndApplyVotesGroup genesisBvd cd) otherGroups -- If we are applying payload from block, we also check implicit -- agreement rule and depth of decided proposals (they can become -- confirmed/discarded). case slotOrHeader of Left _ -> pass Right mainHeader -> do applyImplicitAgreement (configEpochSlots genesisConfig) (mainHeader ^. headerSlotL) (mainHeader ^. difficultyL) (mainHeader ^. headerHashG) applyDepthCheck (configBlkSecurityParam genesisConfig) (mainHeader ^. epochIndexL) (mainHeader ^. headerHashG) (mainHeader ^. difficultyL) where genesisBvd = configBlockVersionData genesisConfig isEmptyPayload = isNothing upProposal && null upVotes -- Here we verify all US-related data from header. verifyHeader :: (MonadError PollVerFailure m, MonadPoll m, IsMainHeader mainHeader) => BlockVersion -> mainHeader -> m () verifyHeader lastAdopted header = do let versionInHeader = header ^. blockVersionL unlessM (canCreateBlockBV lastAdopted versionInHeader) $ do throwError $ PollWrongHeaderBlockVersion versionInHeader lastAdopted -- Get stake of stakeholder who issued given vote as per given epoch. -- If stakeholder wasn't richman at that point, PollNotRichman is thrown. resolveVoteStake :: (MonadError PollVerFailure m, MonadPollRead m) => BlockVersionData -> EpochIndex -> Coin -> UpdateVote -> m Coin resolveVoteStake genesisBvd epoch totalStake vote = do let !id = addressHash (uvKey vote) thresholdPortion <- bvdUpdateProposalThd <$> getAdoptedBVData let threshold = applyCoinPortionUp thresholdPortion totalStake let errNotRichman mbStake = PollNotRichman id threshold mbStake stake <- note (errNotRichman Nothing) =<< getRichmanStake genesisBvd epoch id when (stake < threshold) $ throwError $ errNotRichman (Just stake) return stake -- Do all necessary checks of new proposal and votes for it. -- If it's valid, apply. Specifically, these checks are done: -- -- 1. Check that no one stakeholder sent two update proposals within current epoch. -- 2. If 'verifyAllIsKnown' is 'True', check that proposal has -- no unknown attributes. -- 3. Proposal must not exceed maximal proposal size. -- 4. Check that there is no active proposal with the same id. -- 5. Verify consistenty with BlockVersionState for protocol version from proposal. -- 6. Verify that protocol version from proposal can follow last adopted protocol version. -- 7. Check that numeric software version of application is 1 more than -- of last confirmed proposal for this application. -- 8. If 'slotOrHeader' is 'Right', also check that sum of positive votes -- for this proposal is enough (at least 'updateProposalThd'). -- -- If all checks pass, proposal is added. It can be in undecided or decided -- state (if it has enough voted stake at once). verifyAndApplyProposal :: (MonadError PollVerFailure m, MonadPoll m) => BlockVersionData -> Bool -> Either SlotId (Some IsMainHeader) -> [UpdateVote] -> UpdateProposal -> m () verifyAndApplyProposal genesisBvd verifyAllIsKnown slotOrHeader votes up@UnsafeUpdateProposal {..} = do let !upId = hash up let !upFromId = addressHash upFrom whenM (HS.member upFromId <$> getEpochProposers) $ throwError $ PollMoreThanOneProposalPerEpoch upFromId upId let epoch = slotOrHeader ^. epochIndexL let proposalSize = biSize up proposalSizeLimit <- bvdMaxProposalSize <$> getAdoptedBVData when (verifyAllIsKnown && not (areAttributesKnown upAttributes)) $ throwError $ PollUnknownAttributesInProposal upId upAttributes when (proposalSize > proposalSizeLimit) $ throwError $ PollTooLargeProposal upId proposalSize proposalSizeLimit whenJustM (getProposal upId) $ const $ throwError $ PollProposalAlreadyActive upId -- Here we verify consistency with regards to data from 'BlockVersionState' -- and update relevant state if necessary. verifyAndApplyProposalBVS upId epoch up -- Then we verify the block and software versions from proposal are valid verifyBlockAndSoftwareVersions upId up -- After that we resolve stakes of all votes. totalStake <- note (PollUnknownStakes epoch) =<< getEpochTotalStake genesisBvd epoch votesAndStakes <- mapM (\v -> (v, ) <$> resolveVoteStake genesisBvd epoch totalStake v) votes -- When necessary, we also check that proposal itself has enough -- positive votes to be included into block. when (isRight slotOrHeader) $ verifyProposalStake totalStake votesAndStakes upId -- Finally we put it into context of MonadPoll together with votes for it. putNewProposal slotOrHeader totalStake votesAndStakes up -- Here we check that proposal has at least 'bvdUpdateProposalThd' stake of -- total stake in all positive votes for it. verifyProposalStake :: (MonadPollRead m, MonadError PollVerFailure m) => Coin -> [(UpdateVote, Coin)] -> UpId -> m () verifyProposalStake totalStake votesAndStakes upId = do thresholdPortion <- bvdUpdateProposalThd <$> getAdoptedBVData let threshold = applyCoinPortionUp thresholdPortion totalStake let thresholdInt = coinToInteger threshold let votesSum = sumCoins . map snd . filter (uvDecision . fst) $ votesAndStakes logDebug $ sformat ("Verifying stake for proposal "%shortHashF% ", threshold is "%int%", voted stake is "%int) upId thresholdInt votesSum when (votesSum < thresholdInt) $ throwError $ PollSmallProposalStake threshold (unsafeIntegerToCoin votesSum) upId -- Here we verify votes for proposal which is already active. Each -- vote must have enough stake as per distribution from epoch where -- proposal was added. -- We also verify that what votes correspond to real proposal in -- undecided state. -- Votes are assumed to be for the same proposal. verifyAndApplyVotesGroup :: ApplyMode m => BlockVersionData -> Maybe (ChainDifficulty, HeaderHash) -> NonEmpty UpdateVote -> m () verifyAndApplyVotesGroup genesisBvd cd votes = mapM_ verifyAndApplyVote votes where upId = uvProposalId $ NE.head votes verifyAndApplyVote vote = do let !stakeholderId = addressHash . uvKey $ NE.head votes unknownProposalErr = PollUnknownProposal stakeholderId upId ps <- note unknownProposalErr =<< getProposal upId case ps of PSDecided _ -> throwError $ PollProposalIsDecided upId stakeholderId PSUndecided ups -> verifyAndApplyVoteDo genesisBvd cd ups vote -- Here we actually apply vote to stored undecided proposal. verifyAndApplyVoteDo :: ApplyMode m => BlockVersionData -> Maybe (ChainDifficulty, HeaderHash) -> UndecidedProposalState -> UpdateVote -> m () verifyAndApplyVoteDo genesisBvd cd ups vote = do let e = siEpoch $ upsSlot ups totalStake <- note (PollUnknownStakes e) =<< getEpochTotalStake genesisBvd e voteStake <- resolveVoteStake genesisBvd e totalStake vote newUPS@UndecidedProposalState {..} <- voteToUProposalState (uvKey vote) voteStake (uvDecision vote) ups let newPS | Just decision <- isDecided (mkTotPositive upsPositiveStake) (mkTotNegative upsNegativeStake) (mkTotSum totalStake) = PSDecided DecidedProposalState { dpsUndecided = newUPS , dpsDecision = decision , dpsDifficulty = fst <$> cd , dpsExtra = DpsExtra . snd <$> cd <*> Just False } | otherwise = PSUndecided newUPS insertActiveProposal newPS -- According to implicit agreement rule all proposals which were put -- into blocks earlier than 'updateImplicit' slots before slot -- of current block become implicitly decided (approved or rejected). -- If proposal's total positive stake is bigger than negative, it's -- approved. Otherwise it's rejected. applyImplicitAgreement :: MonadPoll m => SlotCount-> SlotId -> ChainDifficulty -> HeaderHash-> m () applyImplicitAgreement epochSlots (flattenSlotId epochSlots -> slotId) cd hh = do BlockVersionData {..} <- getAdoptedBVData let oldSlot = unflattenSlotId epochSlots $ slotId - bvdUpdateImplicit -- There is no one implicit agreed proposal -- when slot of block is less than @bvdUpdateImplicit@ unless (slotId < bvdUpdateImplicit) $ mapM_ applyImplicitAgreementDo =<< getOldProposals oldSlot where applyImplicitAgreementDo ups = do let decided = makeImplicitlyDecided ups insertActiveProposal $ PSDecided decided let upId = hash $ upsProposal ups status | dpsDecision decided = "approved" | otherwise = "rejected" logInfo $ sformat ("Proposal "%build%" is implicitly "%builder) upId status makeImplicitlyDecided ups@UndecidedProposalState {..} = DecidedProposalState { dpsUndecided = ups , dpsDecision = upsPositiveStake > upsNegativeStake , dpsDifficulty = Just cd , dpsExtra = Just $ DpsExtra hh True } -- All decided proposals which became decided more than -- 'blkSecurityParam' blocks deeper than current block become -- confirmed or discarded (approved become confirmed, rejected become -- discarded). applyDepthCheck :: forall m . ApplyMode m => BlockCount -> EpochIndex -> HeaderHash -> ChainDifficulty -> m () applyDepthCheck k epoch hh (ChainDifficulty cd) | cd <= k = pass | otherwise = do deepProposals <- getDeepProposals (ChainDifficulty (cd - k)) -- 1. Group proposals by application name -- 2. Sort proposals in each group by tuple -- (decision, whether decision is implicit, positive stake, slot when it has been proposed) -- 3. We discard all proposals in each group except the head -- 4. Concatenate all groups and process all proposals let winners = concatMap (toList . discardAllExceptHead . NE.sortBy proposalCmp) $ NE.groupWith groupCriterion deepProposals unless (null deepProposals) $ mapM_ applyDepthCheckDo winners where upsAppName = svAppName . upSoftwareVersion . upsProposal discardAllExceptHead (a:|xs) = a :| map (\x->x {dpsDecision = False}) xs groupCriterion = upsAppName . dpsUndecided mkTuple a extra = ( dpsDecision a , not $ deImplicit extra , upsPositiveStake $ dpsUndecided a , upsSlot $ dpsUndecided a ) -- This comparator chooses the most appropriate proposal among -- proposals of one app and with same chain difficulty. proposalCmp a b | Just extraA <- dpsExtra a , Just extraB <- dpsExtra b = compare (mkTuple b extraB) (mkTuple a extraA) -- The following checks just in case, -- if there are proposals without dpsExtra | Just _ <- dpsExtra a = LT | Just _ <- dpsExtra b = GT | otherwise = compare (upsSlot $ dpsUndecided b) (upsSlot $ dpsUndecided a) applyDepthCheckDo :: DecidedProposalState -> m () applyDepthCheckDo DecidedProposalState {..} = do let UndecidedProposalState {..} = dpsUndecided let sv = upSoftwareVersion upsProposal let bv = upBlockVersion upsProposal let upId = hash upsProposal let status | dpsDecision = "confirmed" | otherwise = "discarded" when dpsDecision $ do setLastConfirmedSV sv DpsExtra {..} <- note (PollInternalError "DPS extra: expected Just, but got Nothing") dpsExtra UpsExtra {..} <- note (PollInternalError "UPS extra: expected Just, but got Nothing") upsExtra let cps = ConfirmedProposalState { cpsUpdateProposal = upsProposal , cpsVotes = upsVotes , cpsPositiveStake = upsPositiveStake , cpsNegativeStake = upsNegativeStake , cpsImplicit = deImplicit , cpsProposed = ueProposedBlk , cpsDecided = deDecidedBlk , cpsConfirmed = hh , cpsAdopted = Nothing } addConfirmedProposal cps proposals <- getProposalsByApp $ upsAppName dpsUndecided mapM_ (deactivateProposal . hash . psProposal) proposals needConfirmBV <- (dpsDecision &&) <$> canBeAdoptedBV bv if | needConfirmBV -> do confirmBlockVersion epoch bv logInfo $ sformat (build%" is competing now") bv | otherwise -> do delBVState bv logInfo $ sformat ("State of "%build%" is deleted") bv deactivateProposal upId logNotice $ sformat ("Proposal "%shortHashF%" is "%builder) upId status
input-output-hk/pos-haskell-prototype
db/src/Pos/DB/Update/Poll/Logic/Apply.hs
Haskell
mit
18,113
<?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="sl-SI"> <title>&gt;Run Applications | ZAP Extensions</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>
veggiespam/zap-extensions
addOns/invoke/src/main/javahelp/org/zaproxy/zap/extension/invoke/resources/help_sl_SI/helpset_sl_SI.hs
Haskell
apache-2.0
983
-- | Miscellaneous string manipulation functions. -- module Hakyll.Core.Util.String ( trim , replaceAll , splitAll ) where import Data.Char (isSpace) import Data.Maybe (listToMaybe) import Text.Regex.TDFA ((=~~)) -- | Trim a string (drop spaces, tabs and newlines at both sides). -- trim :: String -> String trim = reverse . trim' . reverse . trim' where trim' = dropWhile isSpace -- | A simple (but inefficient) regex replace funcion -- replaceAll :: String -- ^ Pattern -> (String -> String) -- ^ Replacement (called on capture) -> String -- ^ Source string -> String -- ^ Result replaceAll pattern f source = replaceAll' source where replaceAll' src = case listToMaybe (src =~~ pattern) of Nothing -> src Just (o, l) -> let (before, tmp) = splitAt o src (capture, after) = splitAt l tmp in before ++ f capture ++ replaceAll' after -- | A simple regex split function. The resulting list will contain no empty -- strings. -- splitAll :: String -- ^ Pattern -> String -- ^ String to split -> [String] -- ^ Result splitAll pattern = filter (not . null) . splitAll' where splitAll' src = case listToMaybe (src =~~ pattern) of Nothing -> [src] Just (o, l) -> let (before, tmp) = splitAt o src in before : splitAll' (drop l tmp)
sol/hakyll
src/Hakyll/Core/Util/String.hs
Haskell
bsd-3-clause
1,466
{-# LANGUAGE CPP #-} module Data.Streaming.FilesystemSpec (spec) where import Test.Hspec import Data.Streaming.Filesystem import Control.Exception (bracket) import Data.List (sort) #if !WINDOWS import System.Posix.Files (removeLink, createSymbolicLink, createNamedPipe) import Control.Exception (bracket, try, IOException) #endif spec :: Spec spec = describe "Data.Streaming.Filesystem" $ do it "dirstream" $ do res <- bracket (openDirStream "test/filesystem") closeDirStream $ \ds -> do Just w <- readDirStream ds Just x <- readDirStream ds Just y <- readDirStream ds Just z <- readDirStream ds return $ sort [w, x, y, z] res `shouldBe` ["bar.txt", "baz.txt", "bin", "foo.txt"] describe "getFileType" $ do it "file" $ getFileType "streaming-commons.cabal" >>= (`shouldBe` FTFile) it "dir" $ getFileType "Data" >>= (`shouldBe` FTDirectory) #if !WINDOWS it "file sym" $ do _ <- tryIO $ removeLink "tmp" createSymbolicLink "streaming-commons.cabal" "tmp" ft <- getFileType "tmp" _ <- tryIO $ removeLink "tmp" ft `shouldBe` FTFileSym it "file sym" $ do _ <- tryIO $ removeLink "tmp" createSymbolicLink "Data" "tmp" ft <- getFileType "tmp" _ <- tryIO $ removeLink "tmp" ft `shouldBe` FTDirectorySym it "other" $ do _ <- tryIO $ removeLink "tmp" createNamedPipe "tmp" 0 ft <- getFileType "tmp" _ <- tryIO $ removeLink "tmp" ft `shouldBe` FTOther it "recursive symlink is other" $ do _ <- tryIO $ removeLink "tmp" createSymbolicLink "tmp" "tmp" ft <- getFileType "tmp" _ <- tryIO $ removeLink "tmp" ft `shouldBe` FTOther it "dangling symlink is other" $ do _ <- tryIO $ removeLink "tmp" createSymbolicLink "doesnotexist" "tmp" ft <- getFileType "tmp" _ <- tryIO $ removeLink "tmp" ft `shouldBe` FTOther tryIO :: IO a -> IO (Either IOException a) tryIO = try #endif
phadej/streaming-commons
test/Data/Streaming/FilesystemSpec.hs
Haskell
mit
2,234
{- portable environment variables - - Copyright 2013 Joey Hess <joey@kitenet.net> - - License: BSD-2-clause -} {-# LANGUAGE CPP #-} module Utility.Env where #ifdef mingw32_HOST_OS import Utility.Exception import Control.Applicative import Data.Maybe import qualified System.Environment as E import qualified System.SetEnv #else import qualified System.Posix.Env as PE #endif getEnv :: String -> IO (Maybe String) #ifndef mingw32_HOST_OS getEnv = PE.getEnv #else getEnv = catchMaybeIO . E.getEnv #endif getEnvDefault :: String -> String -> IO String #ifndef mingw32_HOST_OS getEnvDefault = PE.getEnvDefault #else getEnvDefault var fallback = fromMaybe fallback <$> getEnv var #endif getEnvironment :: IO [(String, String)] #ifndef mingw32_HOST_OS getEnvironment = PE.getEnvironment #else getEnvironment = E.getEnvironment #endif {- Sets an environment variable. To overwrite an existing variable, - overwrite must be True. - - On Windows, setting a variable to "" unsets it. -} setEnv :: String -> String -> Bool -> IO () #ifndef mingw32_HOST_OS setEnv var val overwrite = PE.setEnv var val overwrite #else setEnv var val True = System.SetEnv.setEnv var val setEnv var val False = do r <- getEnv var case r of Nothing -> setEnv var val True Just _ -> return () #endif unsetEnv :: String -> IO () #ifndef mingw32_HOST_OS unsetEnv = PE.unsetEnv #else unsetEnv = System.SetEnv.unsetEnv #endif {- Adds the environment variable to the input environment. If already - present in the list, removes the old value. - - This does not really belong here, but Data.AssocList is for some reason - buried inside hxt. -} addEntry :: Eq k => k -> v -> [(k, v)] -> [(k, v)] addEntry k v l = ( (k,v) : ) $! delEntry k l addEntries :: Eq k => [(k, v)] -> [(k, v)] -> [(k, v)] addEntries = foldr (.) id . map (uncurry addEntry) . reverse delEntry :: Eq k => k -> [(k, v)] -> [(k, v)] delEntry _ [] = [] delEntry k (x@(k1,_) : rest) | k == k1 = rest | otherwise = ( x : ) $! delEntry k rest
avengerpenguin/propellor
src/Utility/Env.hs
Haskell
bsd-2-clause
2,003
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for the LV Parser -} {- Copyright (C) 2013 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 Test.Ganeti.Storage.Lvm.LVParser (testStorage_Lvm_LVParser) where import Prelude () import Ganeti.Prelude import Test.QuickCheck as QuickCheck hiding (Result) import Test.HUnit import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Data.List (intercalate) import Ganeti.Storage.Lvm.LVParser import Ganeti.Storage.Lvm.Types {-# ANN module "HLint: ignore Use camelCase" #-} -- | Test parsing a LV @lvs@ output. case_lvs_lv :: Assertion case_lvs_lv = testParser lvParser "lvs_lv.txt" [ LVInfo "nhasjL-cnZi-uqLS-WRLj-tkXI-nvCB-n0o2lj" "df9ff3f6-a833-48ff-8bd5-bff2eaeab759.disk0_data" "-wi-ao" (negate 1) (negate 1) 253 0 1073741824 1 "originstname+instance1.example.com" "" "uZgXit-eiRr-vRqe-xpEo-e9nU-mTuR-9nfVIU" "xenvg" "linear" 0 0 1073741824 "" "/dev/sda5:0-15" "/dev/sda5(0)" Nothing , LVInfo "5fW5mE-SBSs-GSU0-KZDg-hnwb-sZOC-zZt736" "df9ff3f6-a833-48ff-8bd5-bff2eaeab759.disk0_meta" "-wi-ao" (negate 1) (negate 1) 253 1 134217728 1 "originstname+instance1.example.com" "" "uZgXit-eiRr-vRqe-xpEo-e9nU-mTuR-9nfVIU" "xenvg" "linear" 0 0 134217728 "" "/dev/sda5:16-17" "/dev/sda5(16)" Nothing ] -- | Serialize a LVInfo in the same format that is output by @lvs@. -- The "instance" field is not serialized because it's not provided by @lvs@ -- so it is not part of this test. serializeLVInfo :: LVInfo -> String serializeLVInfo l = intercalate ";" [ lviUuid l , lviName l , lviAttr l , show $ lviMajor l , show $ lviMinor l , show $ lviKernelMajor l , show $ lviKernelMinor l , show (lviSize l) ++ "B" , show $ lviSegCount l , lviTags l , lviModules l , lviVgUuid l , lviVgName l , lviSegtype l , show (lviSegStart l) ++ "B" , show $ lviSegStartPe l , show (lviSegSize l) ++ "B" , lviSegTags l , lviSegPeRanges l , lviDevices l ] ++ "\n" -- | Serialize a list of LVInfo in the same format that is output by @lvs@. serializeLVInfos :: [LVInfo] -> String serializeLVInfos = concatMap serializeLVInfo -- | Arbitrary instance for LVInfo. -- The instance is always Nothing because it is not part of the parsed data: -- it is added afterwards from a different source. instance Arbitrary LVInfo where arbitrary = LVInfo <$> genUUID -- uuid <*> genName -- name <*> genName -- attr <*> arbitrary -- major <*> arbitrary -- minor <*> arbitrary -- kernel_major <*> arbitrary -- kernel_minor <*> genNonNegative -- size <*> arbitrary -- seg_cont <*> genName -- tags <*> genName -- modules <*> genUUID -- vg_uuid <*> genName -- vg_name <*> genName -- segtype <*> genNonNegative -- seg_start <*> arbitrary -- seg_start_pe <*> genNonNegative -- seg_size <*> genName -- seg_tags <*> genName -- seg_pe_ranges <*> genName -- devices <*> return Nothing -- instance -- | Test if a randomly generated LV lvs output is properly parsed. prop_parse_lvs_lv :: [LVInfo] -> Property prop_parse_lvs_lv expected = genPropParser lvParser (serializeLVInfos expected) expected testSuite "Storage/Lvm/LVParser" [ 'case_lvs_lv, 'prop_parse_lvs_lv ]
andir/ganeti
test/hs/Test/Ganeti/Storage/Lvm/LVParser.hs
Haskell
bsd-2-clause
4,731
{-# LANGUAGE OverloadedStrings #-} module ListTeamsForOrganization where import qualified Github.Auth as Github import qualified Github.Organizations.Teams as Github import System.Environment (getArgs) main = do args <- getArgs result <- case args of [team, token] -> Github.teamsOf' (Just $ Github.GithubOAuth token) team [team] -> Github.teamsOf team _ -> error "usage: ListTeamsForOrganization <team> [auth token]" case result of Left err -> putStrLn $ "Error: " ++ show err Right teams -> mapM_ (putStrLn . show) teams
beni55/github
samples/Organizations/Teams/ListTeamsForOrganization.hs
Haskell
bsd-3-clause
637
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.GLboolean -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- This is a purely internal module for (un-)marshaling GLboolean. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.GLboolean ( marshalGLboolean, unmarshalGLboolean ) where import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- marshalGLboolean :: Num a => Bool -> a marshalGLboolean x = fromIntegral $ case x of False -> gl_FALSE True -> gl_TRUE unmarshalGLboolean :: (Eq a, Num a) => a -> Bool unmarshalGLboolean = (/= fromIntegral gl_FALSE)
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/GLboolean.hs
Haskell
bsd-3-clause
940
module Aws.S3.Commands.DeleteObject where import Aws.Core import Aws.S3.Core import Data.ByteString.Char8 ({- IsString -}) import qualified Data.Text as T import qualified Data.Text.Encoding as T data DeleteObject = DeleteObject { doObjectName :: T.Text, doBucket :: Bucket } data DeleteObjectResponse = DeleteObjectResponse{ } -- | ServiceConfiguration: 'S3Configuration' instance SignQuery DeleteObject where type ServiceConfiguration DeleteObject = S3Configuration signQuery DeleteObject {..} = s3SignQuery S3Query { s3QMethod = Delete , s3QBucket = Just $ T.encodeUtf8 doBucket , s3QSubresources = [] , s3QQuery = [] , s3QContentType = Nothing , s3QContentMd5 = Nothing , s3QAmzHeaders = [] , s3QOtherHeaders = [] , s3QRequestBody = Nothing , s3QObject = Just $ T.encodeUtf8 doObjectName } instance ResponseConsumer DeleteObject DeleteObjectResponse where type ResponseMetadata DeleteObjectResponse = S3Metadata responseConsumer _ = s3ResponseConsumer $ \_ -> return DeleteObjectResponse instance Transaction DeleteObject DeleteObjectResponse instance AsMemoryResponse DeleteObjectResponse where type MemoryResponse DeleteObjectResponse = DeleteObjectResponse loadToMemory = return
frms-/aws
Aws/S3/Commands/DeleteObject.hs
Haskell
bsd-3-clause
1,624
-- The intention is that this will be the new unit test framework. -- Please add any working tests here. This file should do nothing -- but import tests from other modules. -- -- Stephen Blackheath, 2009 module Main where import PackageTests.BenchmarkExeV10.Check import PackageTests.BenchmarkOptions.Check import PackageTests.BenchmarkStanza.Check -- import PackageTests.BuildDeps.GlobalBuildDepsNotAdditive1.Check -- import PackageTests.BuildDeps.GlobalBuildDepsNotAdditive2.Check import PackageTests.BuildDeps.InternalLibrary0.Check import PackageTests.BuildDeps.InternalLibrary1.Check import PackageTests.BuildDeps.InternalLibrary2.Check import PackageTests.BuildDeps.InternalLibrary3.Check import PackageTests.BuildDeps.InternalLibrary4.Check import PackageTests.BuildDeps.SameDepsAllRound.Check import PackageTests.BuildDeps.TargetSpecificDeps1.Check import PackageTests.BuildDeps.TargetSpecificDeps2.Check import PackageTests.BuildDeps.TargetSpecificDeps3.Check import PackageTests.BuildTestSuiteDetailedV09.Check import PackageTests.PackageTester (PackageSpec(..), compileSetup) import PackageTests.PathsModule.Executable.Check import PackageTests.PathsModule.Library.Check import PackageTests.PreProcess.Check import PackageTests.TemplateHaskell.Check import PackageTests.CMain.Check import PackageTests.DeterministicAr.Check import PackageTests.EmptyLib.Check import PackageTests.Haddock.Check import PackageTests.TestOptions.Check import PackageTests.TestStanza.Check import PackageTests.TestSuiteExeV10.Check import PackageTests.OrderFlags.Check import PackageTests.ReexportedModules.Check import Distribution.Simple.Configure ( ConfigStateFileError(..), getConfigStateFile ) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..)) import Distribution.Simple.Program.Types (programPath) import Distribution.Simple.Program.Builtin ( ghcProgram, ghcPkgProgram, haddockProgram ) import Distribution.Simple.Program.Db (requireProgram) import Distribution.Simple.Utils (cabalVersion) import Distribution.Text (display) import Distribution.Verbosity (normal) import Distribution.Version (Version(Version)) import Control.Exception (try, throw) import System.Directory ( getCurrentDirectory, setCurrentDirectory ) import System.FilePath ((</>)) import System.IO (BufferMode(NoBuffering), hSetBuffering, stdout) import Test.Framework (Test, TestName, defaultMain, testGroup) import Test.Framework.Providers.HUnit (hUnitTestToTests) import qualified Test.HUnit as HUnit hunit :: TestName -> HUnit.Test -> Test hunit name test = testGroup name $ hUnitTestToTests test tests :: Version -> PackageSpec -> FilePath -> FilePath -> [Test] tests version inplaceSpec ghcPath ghcPkgPath = [ hunit "BuildDeps/SameDepsAllRound" (PackageTests.BuildDeps.SameDepsAllRound.Check.suite ghcPath) -- The two following tests were disabled by Johan Tibell as -- they have been failing for a long time: -- , hunit "BuildDeps/GlobalBuildDepsNotAdditive1/" -- (PackageTests.BuildDeps.GlobalBuildDepsNotAdditive1.Check.suite ghcPath) -- , hunit "BuildDeps/GlobalBuildDepsNotAdditive2/" -- (PackageTests.BuildDeps.GlobalBuildDepsNotAdditive2.Check.suite ghcPath) , hunit "BuildDeps/InternalLibrary0" (PackageTests.BuildDeps.InternalLibrary0.Check.suite version ghcPath) , hunit "PreProcess" (PackageTests.PreProcess.Check.suite ghcPath) , hunit "TestStanza" (PackageTests.TestStanza.Check.suite ghcPath) -- ^ The Test stanza test will eventually be required -- only for higher versions. , testGroup "TestSuiteExeV10" (PackageTests.TestSuiteExeV10.Check.checks ghcPath) , hunit "TestOptions" (PackageTests.TestOptions.Check.suite ghcPath) , hunit "BenchmarkStanza" (PackageTests.BenchmarkStanza.Check.suite ghcPath) -- ^ The benchmark stanza test will eventually be required -- only for higher versions. , hunit "BenchmarkExeV10/Test" (PackageTests.BenchmarkExeV10.Check.checkBenchmark ghcPath) , hunit "BenchmarkOptions" (PackageTests.BenchmarkOptions.Check.suite ghcPath) , hunit "TemplateHaskell/vanilla" (PackageTests.TemplateHaskell.Check.vanilla ghcPath) , hunit "TemplateHaskell/profiling" (PackageTests.TemplateHaskell.Check.profiling ghcPath) , hunit "PathsModule/Executable" (PackageTests.PathsModule.Executable.Check.suite ghcPath) , hunit "PathsModule/Library" (PackageTests.PathsModule.Library.Check.suite ghcPath) , hunit "DeterministicAr" (PackageTests.DeterministicAr.Check.suite ghcPath ghcPkgPath) , hunit "EmptyLib/emptyLib" (PackageTests.EmptyLib.Check.emptyLib ghcPath) , hunit "Haddock" (PackageTests.Haddock.Check.suite ghcPath) , hunit "BuildTestSuiteDetailedV09" (PackageTests.BuildTestSuiteDetailedV09.Check.suite inplaceSpec ghcPath) , hunit "OrderFlags" (PackageTests.OrderFlags.Check.suite ghcPath) , hunit "TemplateHaskell/dynamic" (PackageTests.TemplateHaskell.Check.dynamic ghcPath) , hunit "ReexportedModules" (PackageTests.ReexportedModules.Check.suite ghcPath) ] ++ -- These tests are only required to pass on cabal version >= 1.7 (if version >= Version [1, 7] [] then [ hunit "BuildDeps/TargetSpecificDeps1" (PackageTests.BuildDeps.TargetSpecificDeps1.Check.suite ghcPath) , hunit "BuildDeps/TargetSpecificDeps2" (PackageTests.BuildDeps.TargetSpecificDeps2.Check.suite ghcPath) , hunit "BuildDeps/TargetSpecificDeps3" (PackageTests.BuildDeps.TargetSpecificDeps3.Check.suite ghcPath) , hunit "BuildDeps/InternalLibrary1" (PackageTests.BuildDeps.InternalLibrary1.Check.suite ghcPath) , hunit "BuildDeps/InternalLibrary2" (PackageTests.BuildDeps.InternalLibrary2.Check.suite ghcPath ghcPkgPath) , hunit "BuildDeps/InternalLibrary3" (PackageTests.BuildDeps.InternalLibrary3.Check.suite ghcPath ghcPkgPath) , hunit "BuildDeps/InternalLibrary4" (PackageTests.BuildDeps.InternalLibrary4.Check.suite ghcPath ghcPkgPath) , hunit "PackageTests/CMain" (PackageTests.CMain.Check.checkBuild ghcPath) ] else []) main :: IO () main = do -- WORKAROUND: disable buffering on stdout to get streaming test logs -- test providers _should_ do this themselves hSetBuffering stdout NoBuffering wd <- getCurrentDirectory let dbFile = wd </> "dist/package.conf.inplace" inplaceSpec = PackageSpec { directory = [] , configOpts = [ "--package-db=" ++ dbFile , "--constraint=Cabal == " ++ display cabalVersion ] , distPref = Nothing } putStrLn $ "Cabal test suite - testing cabal version " ++ display cabalVersion lbi <- getPersistBuildConfig_ ("dist" </> "setup-config") (ghc, _) <- requireProgram normal ghcProgram (withPrograms lbi) (ghcPkg, _) <- requireProgram normal ghcPkgProgram (withPrograms lbi) (haddock, _) <- requireProgram normal haddockProgram (withPrograms lbi) let ghcPath = programPath ghc ghcPkgPath = programPath ghcPkg haddockPath = programPath haddock putStrLn $ "Using ghc: " ++ ghcPath putStrLn $ "Using ghc-pkg: " ++ ghcPkgPath putStrLn $ "Using haddock: " ++ haddockPath setCurrentDirectory "tests" -- Create a shared Setup executable to speed up Simple tests compileSetup "." ghcPath defaultMain (tests cabalVersion inplaceSpec ghcPath ghcPkgPath) -- Like Distribution.Simple.Configure.getPersistBuildConfig but -- doesn't check that the Cabal version matches, which it doesn't when -- we run Cabal's own test suite, due to bootstrapping issues. getPersistBuildConfig_ :: FilePath -> IO LocalBuildInfo getPersistBuildConfig_ filename = do eLBI <- try $ getConfigStateFile filename case eLBI of Left (ConfigStateFileBadVersion _ _ (Right lbi)) -> return lbi Left (ConfigStateFileBadVersion _ _ (Left err)) -> throw err Left err -> throw err Right lbi -> return lbi
DavidAlphaFox/ghc
libraries/Cabal/Cabal/tests/PackageTests.hs
Haskell
bsd-3-clause
8,160
module Type1 where data Data a = C1 a Int Char | C2 Int | C3 Float f :: Data a -> Int f (C1 a b c) = b f (C2 a) = a f (C3 a) = 42 (C1 (C1 x y z) b c) = 89
kmate/HaRe
old/testing/removeField/Type1.hs
Haskell
bsd-3-clause
194
module Test2 () where {-@ predicate CyclicC1 Q = CyclicC2 Q && CyclicC3 Q @-} {-@ predicate CyclicC2 Q = CyclicC1 Q @-} {-@ predicate CyclicC3 Q = CyclicC1 Q @-}
abakst/liquidhaskell
tests/crash/CyclicPredAlias2.hs
Haskell
bsd-3-clause
164
module Plugins ( FrontendPlugin(..), defaultFrontendPlugin, Plugin(..), CommandLineOption, defaultPlugin ) where import CoreMonad ( CoreToDo, CoreM ) import TcRnTypes ( TcPlugin ) import GhcMonad import DriverPhases -- | Command line options gathered from the -PModule.Name:stuff syntax -- are given to you as this type type CommandLineOption = String -- | 'Plugin' is the core compiler plugin data type. Try to avoid -- constructing one of these directly, and just modify some fields of -- 'defaultPlugin' instead: this is to try and preserve source-code -- compatability when we add fields to this. -- -- Nonetheless, this API is preliminary and highly likely to change in -- the future. data Plugin = Plugin { installCoreToDos :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo] -- ^ Modify the Core pipeline that will be used for compilation. -- This is called as the Core pipeline is built for every module -- being compiled, and plugins get the opportunity to modify the -- pipeline in a nondeterministic order. , tcPlugin :: [CommandLineOption] -> Maybe TcPlugin -- ^ An optional typechecker plugin, which may modify the -- behaviour of the constraint solver. } -- | Default plugin: does nothing at all! For compatability reasons -- you should base all your plugin definitions on this default value. defaultPlugin :: Plugin defaultPlugin = Plugin { installCoreToDos = const return , tcPlugin = const Nothing } type FrontendPluginAction = [String] -> [(String, Maybe Phase)] -> Ghc () data FrontendPlugin = FrontendPlugin { frontend :: FrontendPluginAction } defaultFrontendPlugin :: FrontendPlugin defaultFrontendPlugin = FrontendPlugin { frontend = \_ _ -> return () }
tjakway/ghcjvm
compiler/main/Plugins.hs
Haskell
bsd-3-clause
1,772
{-# LANGUAGE TypeFamilyDependencies #-} module T6018failclosed2 where -- this one is a strange beast. Last equation is unreachable and thus it is -- removed. It is then impossible to typecheck barapp and thus we generate an -- error type family Bar a = r | r -> a where Bar Int = Bool Bar Bool = Int Bar Bool = Char bar :: Bar a -> Bar a bar x = x barapp :: Char barapp = bar 'c'
olsner/ghc
testsuite/tests/typecheck/should_fail/T6018failclosed2.hs
Haskell
bsd-3-clause
398
-- 0xbf is an invalid character bad = '¿'
wxwxwwxxx/ghc
testsuite/tests/parser/unicode/utf8_011.hs
Haskell
bsd-3-clause
42
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} module Web.Ogma.Api where import Data.Aeson import Data.Text (Text) import Prelude hiding (Foldable) import Servant.API import Web.Ogma.Data type family Id a :: * type instance Id Location = Int data Identified a = Identified (Id a) a instance WeakFunctor Identified where wmap f (Identified idx x) = Identified idx (f x) instance (ToJSON a, ToJSON (Id a)) => ToJSON (Identified a) where toJSON (Identified idx value) = object [ "key" .= idx , "value" .= value ] type PaginatedGet x y = QueryParam "offset" Int :> QueryParam "count" Int :> Get x [y] type PaginatedFoldableGet x y = QueryParam "fold" Int :> PaginatedGet x y type PaginatedEntitiesGet x y = QueryParam "offset" Int :> QueryParam "count" Int :> QueryParam "fold" Int :> Get x (EntityList y) type FoldableGet x y = QueryParam "fold" Int :> Get x y class WeakFunctor f where wmap :: (a -> a) -> f a -> f a class Shrinkable a where shrink :: a -> a shrink = id instance Shrinkable Int instance Shrinkable String instance Shrinkable Text instance Shrinkable Bool class (Shrinkable a, Applicative m) => Expendable m a where expand :: Int -> a -> m a expand _ = pure class Fetchable m a where fetch :: Id a -> m a instance Applicative m => Expendable m Int instance Applicative m => Expendable m String instance Applicative m => Expendable m Text instance Applicative m => Expendable m Bool data Entity a = Complete (Identified a) | IdOnly (Id a) instance WeakFunctor Entity where wmap f (Complete x) = Complete (wmap f x) wmap _ x = x instance Shrinkable (Entity a) where shrink (Complete (Identified idx _)) = IdOnly idx shrink x = x instance (Monad m, Expendable m a, Fetchable m a) => Expendable m (Entity a) where expand x y@(IdOnly idx) | x < 1 = pure y | otherwise = (Complete . Identified idx) <$> (fetch idx >>= expand (x-1)) expand x (Complete (Identified idx value)) | x < 1 = pure $ IdOnly idx | otherwise = (Complete . Identified idx) <$> expand (x-1) value data EntityList a = CompleteList [Identified a] | IdOnlyList [Id a] instance WeakFunctor EntityList where wmap f (CompleteList x) = CompleteList (wmap f <$> x) wmap _ x = x instance (Shrinkable a) => Shrinkable (EntityList a) where shrink (CompleteList l) = IdOnlyList (foldI <$> l) where foldI :: Identified a -> Id a foldI (Identified idx _) = idx shrink x = x instance (Monad m, Expendable m a, Fetchable m a) => Expendable m (EntityList a) where expand x y@(IdOnlyList idxs) | x < 1 = pure y | otherwise = CompleteList <$> ((\idx -> Identified idx <$> (fetch idx >>= expand (x-1))) `mapM` idxs) expand x (CompleteList ids) | x < 1 = IdOnlyList <$> ((\(Identified idx _) -> pure idx) `mapM` ids) | otherwise = CompleteList <$> ((\(Identified idx value) -> Identified idx <$> (expand $ x-1) value) `mapM` ids) instance (ToJSON a, ToJSON (Id a)) => ToJSON (Entity a) where toJSON (IdOnly idx) = toJSON idx toJSON (Complete ex) = toJSON ex data Event = Event Title Description TimeInterval (Entity Location) type instance Id Event = Text instance ToJSON Event where toJSON (Event t d int s) = object [ "title" .= t , "description" .= d , "when" .= int , "where" .= s ] type OgmaAPI = "events" :> QueryParam "at" Surface :> QueryParam "when" TimeInterval :> PaginatedEntitiesGet '[JSON] Event :<|> "events" :> QueryParam "located" Surface :> QueryParam "when" TimeInterval :> PaginatedEntitiesGet '[JSON] Event :<|> "event" :> Capture "eventid" (Id Event) :> FoldableGet '[JSON] Event
ogma-project/ogma
src/Web/Ogma/Api.hs
Haskell
mit
4,325
main :: IO () main = do putStrLn "Ingrese un numero" numeroStr <- getLine putStrLn "Ingrese una potencia" potenciaStr <- getLine let numero = read numeroStr :: Int potencia = read potenciaStr :: Int putStrLn $ show $ exponente numero potencia where exponente :: Int -> Int -> Int exponente n a = exponente' n a 1 exponente' :: Int -> Int -> Int -> Int exponente' n 0 r = 1 exponente' n 1 r = r * n exponente' n a r = exponente' n (a - 1) (r * n)
clinoge/primer-semestre-udone
src/05-ciclos/exponente.hs
Haskell
mit
534
{-# htermination (fsEsFloat :: Float -> Float -> MyBool) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Float = Float MyInt MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; primEqNat :: Nat -> Nat -> MyBool; primEqNat Zero Zero = MyTrue; primEqNat Zero (Succ y) = MyFalse; primEqNat (Succ x) Zero = MyFalse; primEqNat (Succ x) (Succ y) = primEqNat x y; primEqInt :: MyInt -> MyInt -> MyBool; primEqInt (Pos (Succ x)) (Pos (Succ y)) = primEqNat x y; primEqInt (Neg (Succ x)) (Neg (Succ y)) = primEqNat x y; primEqInt (Pos Zero) (Neg Zero) = MyTrue; primEqInt (Neg Zero) (Pos Zero) = MyTrue; primEqInt (Neg Zero) (Neg Zero) = MyTrue; primEqInt (Pos Zero) (Pos Zero) = MyTrue; primEqInt vv vw = MyFalse; esEsMyInt :: MyInt -> MyInt -> MyBool esEsMyInt = primEqInt; primPlusNat :: Nat -> Nat -> Nat; primPlusNat Zero Zero = Zero; primPlusNat Zero (Succ y) = Succ y; primPlusNat (Succ x) Zero = Succ x; primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y)); primMulNat :: Nat -> Nat -> Nat; primMulNat Zero Zero = Zero; primMulNat Zero (Succ y) = Zero; primMulNat (Succ x) Zero = Zero; primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y); primMulInt :: MyInt -> MyInt -> MyInt; primMulInt (Pos x) (Pos y) = Pos (primMulNat x y); primMulInt (Pos x) (Neg y) = Neg (primMulNat x y); primMulInt (Neg x) (Pos y) = Neg (primMulNat x y); primMulInt (Neg x) (Neg y) = Pos (primMulNat x y); srMyInt :: MyInt -> MyInt -> MyInt srMyInt = primMulInt; primEqFloat :: Float -> Float -> MyBool; primEqFloat (Float x1 x2) (Float y1 y2) = esEsMyInt (srMyInt x1 y1) (srMyInt x2 y2); esEsFloat :: Float -> Float -> MyBool esEsFloat = primEqFloat; not :: MyBool -> MyBool; not MyTrue = MyFalse; not MyFalse = MyTrue; fsEsFloat :: Float -> Float -> MyBool fsEsFloat x y = not (esEsFloat x y);
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/SLASHEQ_5.hs
Haskell
mit
1,940
module NLP.Senna.Foreign.Types where import Foreign type CSenna = Ptr ()
slyrz/hase
src/NLP/Senna/Foreign/Types.hs
Haskell
mit
76
{-# LANGUAGE LambdaCase #-} {-@ fooMap :: _ -> i:[a] -> {o:[b] | (len i) = (len o)} @-} fooMap :: (a -> b) -> [a] -> [b] fooMap f = \case [] -> [] l -> map f l
santolucito/ives
tests/Foo.hs
Haskell
mit
167
module Language.FA ( driverDFA, driverNFA, trimUnreachableStates, minimizeDFA, replaceStatesDFA, replaceStatesNFA, nubStatesDFA, nubStatesNFA, collectState, collectStates, collect, dfa2nfa, nfa2dfa, -- NFA epsilonClosure, undistinguishableStates, ) where -------------------------------------------------------------- import Prelude hiding (negate) import Automaton.Type import Automaton.Util import Data.Bits (testBit) import Control.Applicative hiding (empty) import Control.Monad import qualified Data.List as List --import qualified Data.List as List (union, intersect) import Debug.Trace -------------------------------------------------------------- -- instance of Automaton instance Automaton DFA where automaton (DFA states alphabets mappings state []) _ = False automaton (DFA states alphabets mappings state accepts) [] = elem state accepts automaton (DFA states alphabets mappings state accepts) (x:xs) | notElem (Alphabet x) alphabets = False | otherwise = automaton (DFA states alphabets mappings nextState accepts) xs where nextState = (driverDFA mappings) state (Alphabet x) -- nub and replace states with natural numbers (states not minimized!!) normalize dfa = replaceStatesDFA function . nubStatesDFA $ dfa where getStates (DFA states _ _ _ _) = states table = zip (getStates dfa) [0..] function s = case lookup s table of Just a -> a Nothing -> 0 instance Automaton NFA where automaton (NFA states alphabets mappings state []) _ = False automaton (NFA states alphabets mappings state accepts) [] = (state `elem` accepts) || (or $ closure state >>= accept) where closure state = epsilonClosure mappings state accept state = return $ elem state accepts automaton (NFA states alphabets mappings state accepts) language | (Alphabet (head language)) `notElem` alphabets = False | otherwise = or $ consume language state where closure state = epsilonClosure mappings state jump x state = driverNFA mappings state x accept state = return $ elem state accepts consume [] state = closure state >>= accept consume (x:xs) state = closure state >>= jump (Alphabet x) >>= consume xs normalize nfa = replaceStatesNFA function . nubStatesNFA $ nfa where getStates (NFA s _ _ _ _) = s table = zip (getStates nfa) [0..] function s = case lookup s table of Just a -> a Nothing -> 0 ---------------------------------------------------------------------- ---------------------------- -- -- DFA <=> NFA -- ---------------------------- dfa2nfa :: DFA -> NFA dfa2nfa (DFA s a (TransitionsDFA mappings) i f) = (NFA s a (TransitionsNFA ndmappings) i f) where ndmappings = mapping2ndmapping <$> mappings mapping2ndmapping (state, alphabet, target) = (state, alphabet, [target]) nfa2dfa :: NFA -> DFA nfa2dfa nfa = nubStatesDFA $ DFA states' alphabets (TransitionsDFA mappings') start' accepts' where NFA statesN alphabets mappingsN startN acceptsN = normalize nfa transit = driverNFA mappingsN start = epsilonClosure mappingsN startN states = collectStates mappingsN alphabets startN mappings = [ ( state, alphabet, List.nub $ join ( (flip transit alphabet) <$> state) >>= epsilonClosure mappingsN ) | state <- states, alphabet <- alphabets ] accepts = filter acceptable states where acceptable = any (flip elem acceptsN) states' = encodePowerset <$> states mappings' = encodeMapping <$> mappings where encodeMapping (s, a, t) = (encodePowerset s, a, encodePowerset t) start' = encodePowerset start accepts' = encodePowerset <$> accepts ---------------------------- -- -- Negation -- ---------------------------- instance FiniteAutomaton DFA where negate (DFA states a m s accepts) = DFA states a m s (states List.\\ accepts) union dfa0 dfa1 = DFA states alphabets mappings start accepts where DFA states0 alphabets (TransitionsDFA mappings0) start0 accepts0 = normalize dfa0 DFA states1 _ (TransitionsDFA mappings1) start1 accepts1 = normalize dfa1 stateSpace = length states0 * length states1 encode (a, b) = a * length states1 + b states = [0 .. stateSpace - 1] mappings = TransitionsDFA [ (encode (s0, s1), a0, encode (t0, t1)) | (s0, a0, t0) <- mappings0, (s1, a1, t1) <- mappings1, a0 == a1] start = encode (start0, start1) accepts = [ encode (s0, s1) | s0 <- states0, s1 <- states1, elem s0 accepts0 || elem s1 accepts1 ] intersect dfa0 dfa1 = DFA states alphabets mappings start accepts where DFA states0 alphabets (TransitionsDFA mappings0) start0 accepts0 = normalize dfa0 DFA states1 _ (TransitionsDFA mappings1) start1 accepts1 = normalize dfa1 stateSpace = length states0 * length states1 encode (a, b) = a * length states1 + b states = [0 .. stateSpace - 1] mappings = TransitionsDFA [ (encode (s0, s1), a0, encode (t0, t1)) | (s0, a0, t0) <- mappings0, (s1, a1, t1) <- mappings1, a0 == a1] start = encode (start0, start1) accepts = curry encode <$> accepts0 <*> accepts1 concatenate dfa0 dfa1 = minimizeDFA . normalize . nfa2dfa $ nfa0 `concatenate` nfa1 where nfa0 = dfa2nfa dfa0 nfa1 = dfa2nfa dfa1 kleeneStar = nfa2dfa . kleeneStar . dfa2nfa instance FiniteAutomaton NFA where negate = dfa2nfa . negate . nfa2dfa union nfa0 nfa1 = NFA states alphabets mappings start accepts where NFA states0 alphabets (TransitionsNFA mappings0) start0 accepts0 = normalize nfa0 NFA states1 _ (TransitionsNFA mappings1) start1 accepts1 = replace nfa1 replace = replaceStatesNFA ((+) $ length states0) start = maximum states1 + 1 states = start `List.insert` (states0 `List.union` states1) mappings = TransitionsNFA $ mappings0 `List.union` mappings1 `List.union` [(start, Epsilon, [start0, start1])] accepts = accepts0 `List.union` accepts1 intersect nfa0 nfa1 = dfa2nfa dfaIntersection where dfa0 = nfa2dfa nfa0 dfa1 = nfa2dfa nfa1 dfaIntersection = minimizeDFA $ dfa0 `intersect` dfa1 concatenate nfa0 nfa1 = normalize (NFA states alphabets (TransitionsNFA mappings) start0 accepts1) where (NFA states0 alphabets (TransitionsNFA mappings0) start0 accepts0) = nfa0 (NFA states1 _ (TransitionsNFA mappings1) start1 accepts1) = replace nfa1 offset = maximum states0 - minimum states0 + 1 replace = replaceStatesNFA (+ offset) end = [ (s, Epsilon, t) | (s, a, t) <- mappings0, s `elem` accepts0, a == Epsilon ] mappings = case end of [] -> bridge `List.union` mappings0 `List.union` mappings1 otherwise -> bridge' `List.union` (mappings0 List.\\ end) `List.union` mappings1 where bridge = [ (s, Epsilon, [start1]) | s <- accepts0 ] bridge' = [ (s, a, start1 `List.insert` ts) | (s, a, ts) <- end ] states = states0 `List.union` states1 kleeneStar (NFA states alphabets (TransitionsNFA mappings) start accepts) = normalize (NFA states' alphabets (TransitionsNFA mappings') start' accepts') where start' = maximum states + 1 states' = start' `List.insert` states accepts' = start' `List.insert` accepts mappings' = mappings ++ (backToTheStart <$> (start':accepts)) backToTheStart state = (state, Epsilon, [start]) ---------------------------- -- -- Helper Functions -- ---------------------------- encodePowerset :: States -> State encodePowerset = sum . fmap ((^) 2) -- replace states with given SURJECTIVE function replaceStatesDFA :: (State -> State) -> DFA -> DFA replaceStatesDFA table (DFA states alphabets (TransitionsDFA mappings) start accepts) = DFA states' alphabets (TransitionsDFA mappings') start' accepts' where states' = table <$> states mappings' = replaceMapping <$> mappings where replaceMapping (s, a, t) = (table s, a, table t) start' = table start accepts' = table <$> accepts replaceStatesNFA :: (State -> State) -> NFA -> NFA replaceStatesNFA table (NFA states alphabets (TransitionsNFA mappings) start accepts) = NFA states' alphabets (TransitionsNFA mappings') start' accepts' where states' = table <$> states mappings' = replaceMapping <$> mappings where replaceMapping (s, a, t) = (table s, a, table <$> t) start' = table start accepts' = table <$> accepts -- nub the states nubStatesDFA :: DFA -> DFA nubStatesDFA (DFA states alphabets (TransitionsDFA mappings) start accepts) = DFA states' alphabets (TransitionsDFA mappings') start accepts' where states' = List.nub states mappings' = List.nub mappings accepts' = List.nub accepts nubStatesNFA :: NFA -> NFA nubStatesNFA (NFA states alphabets (TransitionsNFA mappings) start accepts) = NFA states' alphabets (TransitionsNFA mappings') start accepts' where states' = List.nub states mappings' = filter validTransition $ glue <$> (List.groupBy sameMapping $ List.sort mappings) accepts' = List.nub accepts validTransition (_, _, []) = False validTransition (_, _, _) = True sameMapping (s, a, t) (s', a', t') = s == s' && a == a' glue mappings = case glue' mappings $ head mappings of (s, Epsilon, ts) -> (s, Epsilon, List.delete s (List.nub ts)) (s, a, ts) -> (s, a, List.nub ts) glue' [] result = result glue' ((_, _, t):rest) (s, a, ts) = glue' rest (s, a, t ++ ts) minimizeDFA :: DFA -> DFA minimizeDFA dfa = nubStatesDFA $ replaceStatesDFA replace dfa where undistinguishablePairs = undistinguishableStates dfa replace a = case lookup a undistinguishablePairs of Just b -> b Nothing -> a undistinguishableStates :: DFA -> [(State, State)] undistinguishableStates dfa = combinations List.\\ collect' (distinguishable dfa) (initialDisguindished, initialMixed) where (DFA states alphabets (TransitionsDFA mappings) start accepts) = dfa combinations = pairCombinations states initialDisguindished = filter distinguishable combinations where distinguishable (a, b) = (a `elem` accepts && b `notElem` accepts) || (a `notElem` accepts && b `elem` accepts) initialMixed = combinations List.\\ initialDisguindished distinguishable :: DFA -> [(State, State)] -> (State, State) -> [(State, State)] distinguishable dfa distinguished pair = case or result of True -> [pair] False -> [] where (DFA states alphabets (TransitionsDFA mappings) start accepts) = dfa transitPair pair = jump pair <$> alphabets jump (a, b) alphabet = (driverDFA (TransitionsDFA mappings) a alphabet, driverDFA (TransitionsDFA mappings) b alphabet) sort (a, b) = if a < b then (a, b) else (b, a) check (a, b) = (a, b) `elem` distinguished && a /= b result = check . sort <$> transitPair pair pairCombinations :: (Ord a) => [a] -> [(a, a)] pairCombinations [] = [] pairCombinations (x:xs) = map (sort . curry id x) xs ++ pairCombinations xs where sort (a, b) = if a < b then (a, b) else (b, a) trimUnreachableStates :: DFA -> DFA trimUnreachableStates (DFA states alphabets (TransitionsDFA mappings) start accepts) = (DFA states' alphabets (TransitionsDFA mappings') start accepts') where states' = collectState (TransitionsDFA mappings) alphabets start trimmedStates = states List.\\ states' mappings' = filter (reachable states') mappings where reachable states (a, b, c) = elem a states && elem c states accepts' = accepts List.\\ trimmedStates collectState :: Transitions -> Alphabets -> State -> States collectState mappings alphabets start = collect next ([start], [start]) where next state = driverDFA mappings state <$> alphabets collectStates :: Transitions -> Alphabets -> State -> [States] collectStates mappings alphabets start = collect next (start', start') where bana alphabet state = driverNFA mappings state alphabet >>= closure next states = (\ alphabet -> List.nub . List.sort $ states >>= bana alphabet) <$> alphabets start' = return $ closure start closure state = epsilonClosure mappings state collect :: (Show a, Eq a) => (a -> [a]) -> ([a], [a]) -> [a] collect next (old, new) | emptied = old | reapeated = old | otherwise = (List.nub $ collect next (old', new')) where new' = List.nub $ old >>= next old' = List.nub (old `List.union` new) emptied = null new' reapeated = new' `subsetOf` old subsetOf elems list = and (flip elem list <$> elems) collect' :: (Show a, Eq a) => ([a] -> a -> [a]) -> ([a], [a]) -> [a] collect' next (old, new) | emptied = old | reapeated = old | otherwise = List.nub $ collect' next (old', new') where new' = List.nub $ new >>= next old old' = List.nub (old `List.union` new) emptied = null new' reapeated = new' `subsetOf` old subsetOf elems list = and (flip elem list <$> elems)
banacorn/formal-language
haskell-legacy/Language/fa.hs
Haskell
mit
14,187
import Data import Data.Elements ( MasyuPearl (..), Thermometer, ) import qualified Data.Grid as Grid import Data.Grid import Data.GridShape import qualified Data.GridShapeSpec import qualified Data.GridSpec import Data.List (sort) import qualified Data.Map.Strict as Map import Data.Pyramid (PyramidSol (..)) import Data.Util import Data.Yaml import qualified Draw.GridSpec import qualified Draw.PuzzleTypesSpec import Parse.Puzzle import Parse.PuzzleTypes import qualified Parse.PuzzleTypesSpec import Parse.Util ( parseChar, parseMultiOutsideClues, parsePlainEdgeGrid, ) import qualified Parse.UtilSpec import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.Hspec import Util main :: IO () main = do ss <- specs defaultMain . testGroup "Tests" $ tests ++ ss specs :: IO [TestTree] specs = mapM (uncurry testSpec) [ ("Data.Grid", Data.GridSpec.spec), ("Data.GridShape", Data.GridShapeSpec.spec), ("Draw.Grid", Draw.GridSpec.spec), ("Draw.PuzzleTypes", Draw.PuzzleTypesSpec.spec), ("Parse.PuzzleTypes", Parse.PuzzleTypesSpec.spec), ("Parse.Util", Parse.UtilSpec.spec) ] tests :: [TestTree] tests = [parseUtilTests, parseTests, parseDataTests, dataTests] testParsePzl :: Show a => String -> ParsePuzzle a b -> Value -> TestTree testParsePzl name parser yaml = testCase ("parse " ++ name) $ testParse (fst parser) yaml testParseSol :: Show b => String -> ParsePuzzle a b -> Value -> TestTree testParseSol name parser yaml = testCase ("parse " ++ name ++ " (sol)") $ testParse (snd parser) yaml testNonparsePzl :: Show a => String -> ParsePuzzle a b -> Value -> TestTree testNonparsePzl name parser yaml = testCase ("don't parse broken " ++ name) $ testNonparse (fst parser) yaml testNonparseSol :: Show b => String -> ParsePuzzle a b -> Value -> TestTree testNonparseSol name parser yaml = testCase ("don't parse broken " ++ name ++ " (sol)") $ testNonparse (snd parser) yaml parseUtilTests :: TestTree parseUtilTests = testGroup "Parsing infrastructure tests (parseChar)" [ testCase "parse digit" $ (parseMaybe parseChar '5' :: Maybe Int) @=? Just 5, testCase "don't parse hex chars" $ (parseMaybe parseChar 'a' :: Maybe Int) @=? Nothing, testCase "don't break on non-digits" $ (parseMaybe parseChar ' ' :: Maybe Int) @=? Nothing ] parseTests :: TestTree parseTests = testGroup "Parsing tests (full puzzles, no details)" [ testParsePzl "geradeweg" geradeweg geradeweg_1, testParseSol "geradeweg" geradeweg geradeweg_1_sol, testParsePzl "tightfit" tightfitskyscrapers tightfit_1, testParseSol "tightfit" tightfitskyscrapers tightfit_1_sol, testNonparsePzl "tightfit" tightfitskyscrapers tightfit_broken_1, testNonparsePzl "tightfit" tightfitskyscrapers tightfit_broken_2, testNonparseSol "tightfit" tightfitskyscrapers tightfit_sol_broken, testNonparseSol "tightfit" tightfitskyscrapers tightfit_sol_broken_2, testNonparseSol "slalom" slalom slalom_sol_broken, testParsePzl "kpyramid" kpyramid kpyramid_1, testParseSol "kpyramid" kpyramid kpyramid_1_sol, testNonparsePzl "kpyramid" kpyramid kpyramid_broken_1, testNonparsePzl "kpyramid" kpyramid kpyramid_broken_2, testNonparsePzl "kpyramid" kpyramid kpyramid_broken_3, testParsePzl "compass" compass compass_1, testNonparsePzl "compass" compass compass_broken_1, testNonparsePzl "compass" compass compass_broken_2, testNonparsePzl "compass" compass compass_broken_3, testNonparsePzl "compass" compass compass_broken_4, testNonparsePzl "compass" compass compass_broken_5, testParsePzl "thermosudoku" thermosudoku thermo_1, testParsePzl "thermosudoku" thermosudoku thermo_2, testNonparsePzl "thermosudoku" thermosudoku thermo_broken_1, testNonparsePzl "thermosudoku" thermosudoku thermo_broken_2 ] test_thermo_1 :: [Thermometer] test_thermo_1 = either (const []) snd $ parseEither (fst thermosudoku) thermo_1 -- two neighbouring a's, should be fine test_thermo_2 :: [Thermometer] test_thermo_2 = either (const []) snd $ parseEither (fst thermosudoku) thermo_2 testThermo :: [Thermometer] -> [[Coord]] -> Assertion testThermo t expect = sort t @?= map (map fromCoord) expect test_tightfit_1 :: Bool test_tightfit_1 = either (const False) test_both res where res = parseEither (fst tightfitskyscrapers) tightfit_1 test_both (o, g) = test_size g && test_clues o test_size g = Grid.size (Map.mapKeys toCoord g) == (3, 3) test_clues (Grid.OC l r b t) = l == [Nothing, Nothing, Just 3] && r == [Nothing, Just 4, Nothing] && b == [Just 3, Just 5, Nothing] && t == [Nothing, Nothing, Nothing] test_pyramid_sol :: Bool test_pyramid_sol = either (const False) test_content res where res = parseEither (snd kpyramid) kpyramid_1_sol test_content (PyramidSol rs) = rs == [[3], [8, 5], [1, 9, 4], [3, 2, 7, 3], [1, 2, 4, 3, 6]] test_multioutside :: Assertion test_multioutside = Right oc @=? res where res = parseEither parseMultiOutsideClues multioutside oc = OC [[3], [1, 2]] [[1, 0], []] [[0, 0, 1]] [[1, -1]] :: OutsideClues Coord [Int] test_plain_edge_grid :: Assertion test_plain_edge_grid = Right (gn, gc, sort es) @=? res' where res = parseEither parsePlainEdgeGrid edgeGrid_1 res' = fmap (\(x, y, e) -> (x, y, sort e)) res gn :: Grid.Grid N (Maybe MasyuPearl) gn = Map.mapKeys fromCoord . Map.fromList $ [ ((0, 0), Just MBlack), ((0, 1), Just MWhite), ((1, 0), Just MWhite), ((1, 1), Just MBlack), ((2, 0), Nothing), ((2, 1), Just MBlack), ((3, 0), Nothing), ((3, 1), Just MWhite) ] gc :: Grid.Grid C Int gc = Map.mapKeys fromCoord . Map.fromList $ [((0, 0), 1), ((1, 0), 2), ((2, 0), 3)] es = map (\(E c d) -> E (fromCoord c) d) [ E (0, 0) Horiz, E (0, 1) Horiz, E (1, 1) Horiz, E (2, 1) Horiz, E (0, 0) Vert, E (1, 0) Vert ] parseDataTests :: TestTree parseDataTests = testGroup "Parsing tests (full puzzles, result checks)" [ testCase "parse tightfit, correct size" $ test_tightfit_1 @? "error in puzzle", testCase "parse kpyramid sol properly" $ test_pyramid_sol @? "wrong solution", testCase "parse thermos" $ testThermo test_thermo_1 [[(0, 4), (1, 5), (2, 4), (1, 3)], [(4, 0), (3, 1), (4, 2), (5, 1)]], testCase "parse thermos" $ testThermo test_thermo_2 [ [(0, 1), (1, 0), (2, 0)], [(0, 2), (1, 3), (2, 4)], [(4, 0), (4, 1), (3, 2)] ], testCase "parse multioutsideclues" $ test_multioutside, testCase "parse edge grid" $ test_plain_edge_grid ] sorteq :: (Show a, Ord a) => [a] -> [a] -> Assertion sorteq xs ys = sort xs @?= sort ys testEdges :: Assertion testEdges = do inner `sorteq` expinner' outer `sorteq` expouter' where (outer, inner) = edges cs (`elem` cs) {- ### # # ### -} cs :: [C] cs = map fromCoord [(0, 0), (1, 0), (2, 0), (0, 1), (2, 1), (0, 2), (1, 2), (2, 2)] expouter = [ ((0, 0), (0, 1)), ((0, 1), (0, 2)), ((0, 2), (0, 3)), ((0, 3), (1, 3)), ((1, 3), (2, 3)), ((2, 3), (3, 3)), ((3, 3), (3, 2)), ((3, 2), (3, 1)), ((3, 1), (3, 0)), ((3, 0), (2, 0)), ((2, 0), (1, 0)), ((1, 0), (0, 0)), ((1, 1), (2, 1)), ((2, 1), (2, 2)), ((2, 2), (1, 2)), ((1, 2), (1, 1)) ] expouter' = map (uncurry edge' . fromCoord2) expouter expinner = [ ((0, 1), (1, 1)), ((0, 2), (1, 2)), ((1, 0), (1, 1)), ((2, 0), (2, 1)), ((1, 3), (1, 2)), ((2, 3), (2, 2)), ((3, 1), (2, 1)), ((3, 2), (2, 2)) ] expinner' = map (uncurry edge . fromCoord2) expinner fromCoord2 (p, q) = (fromCoord p, fromCoord q) testLoops :: Assertion testLoops = loops es @=? Just loopsexp where -- rotations of the loops would be fine -- inside and outside of: -- xxx -- x x -- xxx es = [ ((0, 0), (0, 1)), ((0, 1), (0, 2)), ((0, 2), (0, 3)), ((0, 3), (1, 3)), ((1, 3), (2, 3)), ((2, 3), (3, 3)), ((3, 3), (3, 2)), ((3, 2), (3, 1)), ((3, 1), (3, 0)), ((3, 0), (2, 0)), ((2, 0), (1, 0)), ((1, 0), (0, 0)), ((1, 1), (2, 1)), ((2, 1), (2, 2)), ((2, 2), (1, 2)), ((1, 2), (1, 1)) ] loopsexp :: [[(Int, Int)]] loopsexp = [ [ (0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (3, 3), (3, 2), (3, 1), (3, 0), (2, 0), (1, 0), (0, 0) ], [(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)] ] dataTests :: TestTree dataTests = testGroup "Generic tests for the Data modules" [testCase "edges" testEdges, testCase "loops" testLoops]
robx/puzzle-draw
tests/tests.hs
Haskell
mit
9,424
module Test.MLP(test) where import Data.MLP as P import qualified Data.DNN.Trainer as T import qualified Data.Matrix as M --utils import Control.Monad.Identity(runIdentity) import Control.Monad(forever,when,foldM) --test modules import System.Exit (exitFailure) import Test.QuickCheck(verboseCheckWithResult) import Test.QuickCheck.Test(isSuccess,stdArgs,maxSuccess,maxSize) import Data.Word(Word8) prop_feedForward :: Word8 -> Word8 -> Word8 -> Word8 -> Bool prop_feedForward bs ni nh no = runIdentity $ do let input = M.randomish (fi bs, fi ni) (0,1) seed fi ww = 1 + (fromIntegral ww) seed = product $ map fi [bs,ni,nh,no] mlp = new seed $ map fi [ni,nh,no] outs <- P.feedForward mlp input return $ (M.shape outs) == (fi bs, fi no) sigmoid :: Double -> Double sigmoid d = 1 / (1 + (exp (negate d))) prop_feedForward1 :: Bool prop_feedForward1 = runIdentity $ do let input = M.fromList (1,3) [1,0,1] let mlp = M.fromList (3,2) [1,-1, 1, 1, 1, 1] outs <- P.feedForward [mlp] input --(1+0+1 ignored since its bias, sigmoid of -1+0+1) return $ (M.toList outs) == [1, sigmoid 0] prop_backProp :: Word8 -> Word8 -> Word8 -> Bool prop_backProp bs ri nh = runIdentity $ do let input = M.fromList (4*(fi bs),3) $ concat $ replicate (fi bs) [1,1,1, 1,1,0, 1,0,1, 1,0,0] output = M.fromList (4*(fi bs),2) $ concat $ replicate (fi bs) [1,0, 1,1, 1,1, 1,0] fi ww = 1 + (fromIntegral ww) seed = fi nh mlp = new seed $ map fi [3,nh,2] train :: Monad m => T.Trainer m Bool train = forever $ do T.setLearnRate (0.001) ins <- mapM M.d2u $ M.splitRows (fi ri) input outs <- mapM M.d2u $ M.splitRows (fi ri) output mapM_ (uncurry T.backProp) $ zip ins outs err <- T.forwardErr input output cnt <- T.getCount when (err >= 0.20 && cnt > 1000) (T.finish False) when (err < 0.20) (T.finish True) fst <$> T.run mlp train prop_backProp1 :: Bool prop_backProp1 = runIdentity $ do let input = M.fromList (1,2) [1,1] let output = M.fromList (1,2) [1,1] let mlp = M.fromList (2,2) [-1,-1, -1,-1] let train (umlp,_) _ = P.backPropagate umlp 0.1 input output (_,e1) <- foldM train ([mlp],1) $ [0::Int] (_,e2) <- foldM train ([mlp],1) $ [0..100::Int] return $ e2 < e1 prop_backProp2 :: Bool prop_backProp2 = runIdentity $ do let input = M.fromList (1,2) [1,1] let output = M.fromList (1,2) [1,0] let mlp = M.fromList (2,2) [1,1, 1,1] let train (umlp,_) _ = P.backPropagate umlp 0.1 input output (_,e1) <- foldM train ([mlp],1) $ [0::Int] (_,e2) <- foldM train ([mlp],1) $ [0..100::Int] return $ e2 < e1 prop_backProp3 :: Bool prop_backProp3 = runIdentity $ do let input = M.fromList (1,2) [1,1] let output = M.fromList (1,2) [1,1] let mlp = M.fromList (2,2) [-1,-1, -1,-1] let train (umlp,_) _ = P.backPropagate umlp 0.1 input output (_,e1) <- foldM train ([mlp,mlp],1) $ [0::Int] (_,e2) <- foldM train ([mlp,mlp],1) $ [0..100::Int] return $ e2 < e1 prop_backProp4 :: Bool prop_backProp4 = runIdentity $ do let input = M.fromList (1,2) [1,1] let output = M.fromList (1,2) [1,0] let mlp = M.fromList (2,2) [1,1, 1,1] let train (umlp,_) _ = P.backPropagate umlp 0.1 input output (_,e1) <- foldM train ([mlp,mlp],1) $ [0::Int] (_,e2) <- foldM train ([mlp,mlp],1) $ [0..100::Int] return $ e2 < e1 prop_backPropXOR1 :: Bool prop_backPropXOR1 = runIdentity $ do let input = M.fromList (4,3) $ [1,1,1, 1,1,0, 1,0,1, 1,0,0] output = M.fromList (4,2) $ [1,0, 1,1, 1,1, 1,0] m1 = M.fromList (3,2) [1,1, 1,1, 1,1] m2 = M.fromList (2,2) [1,1, 1,1] train (umlp,_) _ = P.backPropagate umlp 0.1 input output (_,e1) <- foldM train ([m1,m2],1) $ [0::Int] (_,e2) <- foldM train ([m1,m2],1) $ [0..100::Int] return $ e2 < e1 prop_backPropXOR2 :: Bool prop_backPropXOR2 = runIdentity $ do let input = M.fromList (4,3) $ [1,1,1, 1,1,0, 1,0,1, 1,0,0] output = M.fromList (4,2) $ [1,0, 1,1, 1,1, 1,0] m1 = M.fromList (3,2) [-1,-1, -1,-1, -1,-1] m2 = M.fromList (2,2) [-1,-1, -1,-1] train (umlp,_) _ = P.backPropagate umlp 0.1 input output (_,e1) <- foldM train ([m1,m2],1) $ [0::Int] (_,e2) <- foldM train ([m1,m2],1) $ [0..100::Int] return $ e2 < e1 prop_DxE :: Bool prop_DxE = runIdentity $ do let d1 = M.fromList (2,2) [1,0, 0,2] let d2 = M.fromList (2,2) [3,0, 0,4] let d12 = M.fromList (2,2) [1,2, 3,4] let e1 = M.fromList (2,1) [5,6] let e2 = M.fromList (2,1) [7,8] let e12 = M.fromList (2,2) [5,6, 7,8] r1a <- d1 `M.mmult` e1 r1b <- d2 `M.mmult` e2 r12 <- M.d2u $ d12 M.*^ e12 return $ M.toList r1a ++ M.toList r1b == M.toList r12 prop_finish_ :: Bool prop_finish_ = () == (fst $ runIdentity $ T.run (new 0 []) T.finish_) prop_poplast :: Bool prop_poplast = (2,3) == rv where mlp = new 0 [1,2,3] rv = M.shape $ fst $ runIdentity $ T.run mlp $ T.popLastLayer prop_backward :: Bool prop_backward = (2,1) == rv where mlp = new 0 [1,2,3] rv = M.shape $ fst $ runIdentity $ T.run mlp $ T.backward (M.fromList (2,3) [1,2,3,4,5,6]) test :: IO () test = do let check rr = if (isSuccess rr) then return () else exitFailure cfg = stdArgs { maxSuccess = 100, maxSize = 10 } runtest tst p = do putStrLn tst; check =<< verboseCheckWithResult cfg p runtest "feedforward" prop_feedForward runtest "feedforward1" prop_feedForward1 runtest "backprop1" prop_backProp1 runtest "backprop2" prop_backProp2 runtest "backprop3" prop_backProp3 runtest "backprop4" prop_backProp4 runtest "backpropXOR1" prop_backPropXOR1 runtest "backpropXOR2" prop_backPropXOR2 runtest "dxe" prop_DxE runtest "backprop" prop_backProp runtest "finish_" prop_finish_ runtest "poplast" prop_poplast runtest "backward" prop_backward
aeyakovenko/rbm
Test/MLP.hs
Haskell
mit
6,475
{-# LANGUAGE CPP, DeriveDataTypeable, FlexibleContexts,OverloadedStrings, GeneralizedNewtypeDeriving, MultiParamTypeClasses, NoImplicitPrelude , TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric, DeriveDataTypeable #-} module Tach.Acid.Impulse.Cruds.Types where import CorePrelude import qualified Data.ByteString.Lazy as LB import Data.SafeCopy ( base, deriveSafeCopy ) newtype SuccessValue = SuccessValue { getSuccess :: ByteString} deriving (Typeable, Show) --newtype ErrorValue = ErrorValue { getError :: ByteString} deriving (Typeable, Show) newtype ErrorValue = ErrorValue { unCrudsError :: CrudsError} deriving (Typeable, Show) data CrudsError = ErrorNotFound | ErrorOutOfBounds | ErrorInvalidRange | ErrorIncorrectKey deriving (Typeable, Show) $(deriveSafeCopy 0 'base ''SuccessValue) $(deriveSafeCopy 0 'base ''ErrorValue) $(deriveSafeCopy 0 'base ''CrudsError)
smurphy8/tach
core-libs/tach-acid-impulse-lib/src/Tach/Acid/Impulse/Cruds/Types.hs
Haskell
mit
902
--marySue :: Maybe Bool marySue = do k <- Just 9 Just (k>8)
RAFIRAF/HASKELL
A Fistful of Monads/mary.hs
Haskell
mit
65
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html module Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationApplicationConfiguration where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationApplicationCodeConfiguration import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationApplicationSnapshotConfiguration import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationEnvironmentProperties import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationFlinkApplicationConfiguration import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationSqlApplicationConfiguration -- | Full data type definition for -- KinesisAnalyticsV2ApplicationApplicationConfiguration. See -- 'kinesisAnalyticsV2ApplicationApplicationConfiguration' for a more -- convenient constructor. data KinesisAnalyticsV2ApplicationApplicationConfiguration = KinesisAnalyticsV2ApplicationApplicationConfiguration { _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationCodeConfiguration :: Maybe KinesisAnalyticsV2ApplicationApplicationCodeConfiguration , _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationSnapshotConfiguration :: Maybe KinesisAnalyticsV2ApplicationApplicationSnapshotConfiguration , _kinesisAnalyticsV2ApplicationApplicationConfigurationEnvironmentProperties :: Maybe KinesisAnalyticsV2ApplicationEnvironmentProperties , _kinesisAnalyticsV2ApplicationApplicationConfigurationFlinkApplicationConfiguration :: Maybe KinesisAnalyticsV2ApplicationFlinkApplicationConfiguration , _kinesisAnalyticsV2ApplicationApplicationConfigurationSqlApplicationConfiguration :: Maybe KinesisAnalyticsV2ApplicationSqlApplicationConfiguration } deriving (Show, Eq) instance ToJSON KinesisAnalyticsV2ApplicationApplicationConfiguration where toJSON KinesisAnalyticsV2ApplicationApplicationConfiguration{..} = object $ catMaybes [ fmap (("ApplicationCodeConfiguration",) . toJSON) _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationCodeConfiguration , fmap (("ApplicationSnapshotConfiguration",) . toJSON) _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationSnapshotConfiguration , fmap (("EnvironmentProperties",) . toJSON) _kinesisAnalyticsV2ApplicationApplicationConfigurationEnvironmentProperties , fmap (("FlinkApplicationConfiguration",) . toJSON) _kinesisAnalyticsV2ApplicationApplicationConfigurationFlinkApplicationConfiguration , fmap (("SqlApplicationConfiguration",) . toJSON) _kinesisAnalyticsV2ApplicationApplicationConfigurationSqlApplicationConfiguration ] -- | Constructor for 'KinesisAnalyticsV2ApplicationApplicationConfiguration' -- containing required fields as arguments. kinesisAnalyticsV2ApplicationApplicationConfiguration :: KinesisAnalyticsV2ApplicationApplicationConfiguration kinesisAnalyticsV2ApplicationApplicationConfiguration = KinesisAnalyticsV2ApplicationApplicationConfiguration { _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationCodeConfiguration = Nothing , _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationSnapshotConfiguration = Nothing , _kinesisAnalyticsV2ApplicationApplicationConfigurationEnvironmentProperties = Nothing , _kinesisAnalyticsV2ApplicationApplicationConfigurationFlinkApplicationConfiguration = Nothing , _kinesisAnalyticsV2ApplicationApplicationConfigurationSqlApplicationConfiguration = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-applicationcodeconfiguration kavaacApplicationCodeConfiguration :: Lens' KinesisAnalyticsV2ApplicationApplicationConfiguration (Maybe KinesisAnalyticsV2ApplicationApplicationCodeConfiguration) kavaacApplicationCodeConfiguration = lens _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationCodeConfiguration (\s a -> s { _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationCodeConfiguration = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-applicationsnapshotconfiguration kavaacApplicationSnapshotConfiguration :: Lens' KinesisAnalyticsV2ApplicationApplicationConfiguration (Maybe KinesisAnalyticsV2ApplicationApplicationSnapshotConfiguration) kavaacApplicationSnapshotConfiguration = lens _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationSnapshotConfiguration (\s a -> s { _kinesisAnalyticsV2ApplicationApplicationConfigurationApplicationSnapshotConfiguration = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-environmentproperties kavaacEnvironmentProperties :: Lens' KinesisAnalyticsV2ApplicationApplicationConfiguration (Maybe KinesisAnalyticsV2ApplicationEnvironmentProperties) kavaacEnvironmentProperties = lens _kinesisAnalyticsV2ApplicationApplicationConfigurationEnvironmentProperties (\s a -> s { _kinesisAnalyticsV2ApplicationApplicationConfigurationEnvironmentProperties = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-flinkapplicationconfiguration kavaacFlinkApplicationConfiguration :: Lens' KinesisAnalyticsV2ApplicationApplicationConfiguration (Maybe KinesisAnalyticsV2ApplicationFlinkApplicationConfiguration) kavaacFlinkApplicationConfiguration = lens _kinesisAnalyticsV2ApplicationApplicationConfigurationFlinkApplicationConfiguration (\s a -> s { _kinesisAnalyticsV2ApplicationApplicationConfigurationFlinkApplicationConfiguration = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-sqlapplicationconfiguration kavaacSqlApplicationConfiguration :: Lens' KinesisAnalyticsV2ApplicationApplicationConfiguration (Maybe KinesisAnalyticsV2ApplicationSqlApplicationConfiguration) kavaacSqlApplicationConfiguration = lens _kinesisAnalyticsV2ApplicationApplicationConfigurationSqlApplicationConfiguration (\s a -> s { _kinesisAnalyticsV2ApplicationApplicationConfigurationSqlApplicationConfiguration = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsV2ApplicationApplicationConfiguration.hs
Haskell
mit
6,799
module P004 where import Euler solution :: EulerType solution = Left $ foldl ( \m a -> foldMaybe ( \m b -> let c = a * b in if c <= m then Nothing else if pal c then Just c else Just m ) m [999, (if a `divides` 11 then 998 else 988) .. a] ) 0 [999, 998 .. 100] main = printEuler solution
Undeterminant/euler-haskell
P004.hs
Haskell
cc0-1.0
321
{-# LANGUAGE RecordWildCards, NamedFieldPuns, BangPatterns #-} module SSync.RollingChecksum ( RollingChecksum , init , value , value16 , forBlock , roll ) where import Prelude hiding (init) import Data.Bits (shiftR, shiftL, xor, (.&.)) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS import Data.Word (Word32, Word8) import Data.Int (Int8) data RollingChecksum = RC { _rcBlockSize :: {-# UNPACK #-} !Word32 , _rc :: {-# UNPACK #-} !Word32 } deriving (Show) init :: Word32 -> RollingChecksum init blockSize = RC blockSize 0 value :: RollingChecksum -> Word32 value RC{..} = _rc {-# INLINE value #-} value16 :: RollingChecksum -> Word32 value16 RC{..} = (_rc `xor` (_rc `shiftR` 16)) .&. 0xffff {-# INLINE value16 #-} -- | Computes the checksum of the block at the start of the -- 'ByteString'. To check a block somewhere other than the start, -- 'BS.drop' the front off of it it yourself. forBlock :: RollingChecksum -> ByteString -> RollingChecksum forBlock RC{_rcBlockSize} bs = let a = aSum _rcBlockSize bs .&. 0xffff b = bSum _rcBlockSize bs .&. 0xffff in RC{ _rc = a + (b `shiftL` 16), .. } -- | This is a due to a stupid bug in the Java implementation; Java bytes are -- signed, and so when they're extended to word-size they need to fill -- the upper bits appropriately. The bug does not affect the -- "rolling" property of the rolling checksum, which is why it wasn't -- detected until now. signExtend :: Word8 -> Word32 signExtend = (fromIntegral :: Int8 -> Word32) . (fromIntegral :: Word8 -> Int8) aSum :: Word32 -> ByteString -> Word32 aSum blockSize bs = go 0 0 where limit = BS.length bs `min` fromIntegral blockSize go !i !a | i < limit = go (i+1) (a + signExtend (BS.unsafeIndex bs i)) | otherwise = a bSum :: Word32 -> ByteString -> Word32 bSum blockSize bs = go 0 0 where limit = BS.length bs `min` fromIntegral blockSize go :: Int -> Word32 -> Word32 go !i !b | i < limit = go (i+1) (b + (blockSize - fromIntegral i) * signExtend (BS.unsafeIndex bs i)) | otherwise = b roll :: RollingChecksum -> Word8 -> Word8 -> RollingChecksum roll RC{..} oldByte newByte = let ob = signExtend oldByte a = ((_rc .&. 0xffff) - ob + signExtend newByte) .&. 0xffff b = ((_rc `shiftR` 16) - _rcBlockSize * ob + a) .&. 0xffff in RC { _rc = a + (b `shiftL` 16), .. } {-# INLINE roll #-}
socrata-platform/ssync
src/main/haskell/SSync/RollingChecksum.hs
Haskell
apache-2.0
2,513
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 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 Test.Ganeti.Rpc (testRpc) where import Test.QuickCheck import Test.QuickCheck.Monadic (monadicIO, run, stop) import Control.Applicative import qualified Data.Map as Map import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Objects () import qualified Ganeti.Rpc as Rpc import qualified Ganeti.Objects as Objects import qualified Ganeti.Types as Types import qualified Ganeti.JSON as JSON import Ganeti.Types instance Arbitrary Rpc.RpcCallAllInstancesInfo where arbitrary = Rpc.RpcCallAllInstancesInfo <$> arbitrary instance Arbitrary Rpc.RpcCallInstanceList where arbitrary = Rpc.RpcCallInstanceList <$> arbitrary instance Arbitrary Rpc.RpcCallNodeInfo where arbitrary = Rpc.RpcCallNodeInfo <$> genStorageUnitMap <*> genHvSpecs genStorageUnit :: Gen StorageUnit genStorageUnit = do storage_type <- arbitrary storage_key <- genName storage_es <- arbitrary return $ addParamsToStorageUnit storage_es (SURaw storage_type storage_key) genStorageUnits :: Gen [StorageUnit] genStorageUnits = do num_storage_units <- choose (0, 5) vectorOf num_storage_units genStorageUnit genStorageUnitMap :: Gen (Map.Map String [StorageUnit]) genStorageUnitMap = do num_nodes <- choose (0,5) node_uuids <- vectorOf num_nodes genName storage_units_list <- vectorOf num_nodes genStorageUnits return $ Map.fromList (zip node_uuids storage_units_list) -- | Generate hypervisor specifications to be used for the NodeInfo call genHvSpecs :: Gen [ (Types.Hypervisor, Objects.HvParams) ] genHvSpecs = do numhv <- choose (0, 5) hvs <- vectorOf numhv arbitrary hvparams <- vectorOf numhv genHvParams let specs = zip hvs hvparams return specs -- FIXME: Generate more interesting hvparams -- | Generate Hvparams genHvParams :: Gen Objects.HvParams genHvParams = return $ JSON.GenericContainer Map.empty -- | Monadic check that, for an offline node and a call that does not -- offline nodes, we get a OfflineNodeError response. -- FIXME: We need a way of generalizing this, running it for -- every call manually will soon get problematic prop_noffl_request_allinstinfo :: Rpc.RpcCallAllInstancesInfo -> Property prop_noffl_request_allinstinfo call = forAll (arbitrary `suchThat` Objects.nodeOffline) $ \node -> monadicIO $ do res <- run $ Rpc.executeRpcCall [node] call stop $ res ==? [(node, Left Rpc.OfflineNodeError)] prop_noffl_request_instlist :: Rpc.RpcCallInstanceList -> Property prop_noffl_request_instlist call = forAll (arbitrary `suchThat` Objects.nodeOffline) $ \node -> monadicIO $ do res <- run $ Rpc.executeRpcCall [node] call stop $ res ==? [(node, Left Rpc.OfflineNodeError)] prop_noffl_request_nodeinfo :: Rpc.RpcCallNodeInfo -> Property prop_noffl_request_nodeinfo call = forAll (arbitrary `suchThat` Objects.nodeOffline) $ \node -> monadicIO $ do res <- run $ Rpc.executeRpcCall [node] call stop $ res ==? [(node, Left Rpc.OfflineNodeError)] testSuite "Rpc" [ 'prop_noffl_request_allinstinfo , 'prop_noffl_request_instlist , 'prop_noffl_request_nodeinfo ]
apyrgio/snf-ganeti
test/hs/Test/Ganeti/Rpc.hs
Haskell
bsd-2-clause
4,509
module Data.Drasil.Software.Products where import Language.Drasil import Utils.Drasil import Data.Drasil.Concepts.Documentation (game, video, open, source) import Data.Drasil.Concepts.Computation (computer) import Data.Drasil.Concepts.Software (program) import Data.Drasil.IdeaDicts prodtcon :: [NamedChunk] prodtcon = [sciCompS, videoGame, openSource, compPro] matlab :: CI matlab = commonIdeaWithDict "matlab" (pn' "MATLAB programming language") "MATLAB" [progLanguage] sciCompS :: NamedChunk sciCompS = nc "sciCompS" (cn' "scientific computing software") videoGame, openSource, compPro :: NamedChunk videoGame = compoundNC video game openSource = compoundNC open source compPro = compoundNC computer program
JacquesCarette/literate-scientific-software
code/drasil-data/Data/Drasil/Software/Products.hs
Haskell
bsd-2-clause
744
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} module Database.Sqroll.Table ( -- * Types Table (..) , NamedTable (..) , FieldInfo (..) -- * Creating tables , namedTable , field , mapTable -- * Inspecting tables , tableCreate , tableIndexes , tableInsert , tableSelect , tablePoke , tablePeek , tablePeekFrom , tablePeekFromMaybe , tableRefers , tableMakeDefaults , tableFields -- * Useful if you want to access raw fields , makeFieldNames ) where import Control.Applicative import Control.Arrow (first) import Control.Monad import Data.List (intercalate) import Data.Monoid (Monoid, mappend, mempty) import Database.Sqroll.Sqlite3 import Database.Sqroll.Table.Field data FieldInfo t a = FieldInfo { fieldName :: String , fieldExtract :: t -> a } fieldNames :: forall t a. Field a => FieldInfo t a -> [String] fieldNames fi = makeFieldNames (fieldName fi) (length $ fieldTypes (undefined :: a)) makeFieldNames :: String -> Int -> [String] makeFieldNames base 1 = [base] makeFieldNames base n = [base ++ "_" ++ show i | i <- [0 .. n-1]] fieldColumns' :: forall t a. Field a => FieldInfo t a -> Int fieldColumns' _ = length $ fieldTypes (undefined :: a) data Table t f where -- Applicative interface Map :: (a -> b) -> Table t a -> Table t b Pure :: a -> Table t a App :: Table t (a -> b) -> Table t a -> Table t b -- Primitives Primitive :: (Field a) => FieldInfo t a -> Table t a instance Functor (Table t) where fmap = Map instance Applicative (Table t) where pure = Pure (<*>) = App data NamedTable t = NamedTable { tableName :: String , tableTree :: Table t t } namedTable :: String -> Table t t -> NamedTable t namedTable = NamedTable field :: (Field a) => String -> (t -> a) -> Table t a field name extract = Primitive $ FieldInfo name extract mapTable :: forall t u. (t -> u) -> (u -> t) -> Table t t -> Table u u mapTable mk unmk = Map mk . go where go :: forall a. Table t a -> Table u a go (Map f t) = Map f (go t) go (Pure x) = Pure x go (App t1 t2) = App (go t1) (go t2) go (Primitive (FieldInfo n e)) = Primitive (FieldInfo n (e . unmk)) tableFoldMap :: forall t b. Monoid b => (forall a. Field a => FieldInfo t a -> b) -> NamedTable t -> b tableFoldMap f table = go (tableTree table) where go :: forall a. Table t a -> b go (Map _ t) = go t go (Pure _) = mempty go (App t1 t2) = go t1 `mappend` go t2 go (Primitive fi) = f fi tableFields :: forall t. NamedTable t -> [(String, SqlType)] tableFields = tableFoldMap fieldName' where fieldName' :: forall a. Field a => FieldInfo t a -> [(String, SqlType)] fieldName' fi = zip (fieldNames fi) (fieldTypes (undefined :: a)) tableCreate :: NamedTable t -> String tableCreate table = "CREATE TABLE IF NOT EXISTS [" ++ tableName table ++ "] (" ++ intercalate ", " (map makeField $ tableFields table) ++ ")" where makeField (name, fType) = "[" ++ name ++ "] " ++ sqlTypeToString fType tableIndexes :: forall t. NamedTable t -> [String] tableIndexes table = tableFoldMap tableIndex table where tableIndex :: forall a. Field a => FieldInfo t a -> [String] tableIndex fi = do index <- fieldIndexes (undefined :: a) let idxName = "index_" ++ tableName table ++ "_" ++ fieldName fi return $ case index of IndexFK _ -> "CREATE INDEX IF NOT EXISTS [" ++ idxName ++ "] ON [" ++ tableName table ++ "] ([" ++ fieldName fi ++ "])" IndexUnique -> "CREATE UNIQUE INDEX IF NOT EXISTS [unique_" ++ idxName ++ "] ON [" ++ tableName table ++ "] (" ++ intercalate ", " ["[" ++ n ++ "]" | n <- fieldNames fi] ++ ")" tableInsert :: NamedTable t -> String tableInsert table = "INSERT INTO [" ++ tableName table ++ "] ([" ++ intercalate "], [" (map fst $ tableFields table) ++ "]) VALUES (" ++ intercalate ", " (replicate (length fields) "?") ++ ")" where fields = tableFields table tableSelect :: NamedTable t -> String tableSelect table = "SELECT rowid, [" ++ intercalate "], [" (map fst $ tableFields table) ++ "] FROM [" ++ tableName table ++ "]" tablePoke :: forall t. NamedTable t -> SqlStmt -> t -> IO () tablePoke (NamedTable _ table) stmt = \t -> go table t 1 >> return () where -- go :: forall a. Field a => FieldInfo t a -> [Int -> t -> IO ()] -- go fi = [\n x -> fieldPoke stmt n (fieldExtract fi x)] go :: forall a. Table t a -> t -> Int -> IO Int go (Map _ t) x !n = go t x n go (Pure _) _ !n = return n go (App ft t) x !n = do n' <- go ft x n n'' <- go t x n' return n'' go (Primitive fi) x !n = do fieldPoke stmt n (fieldExtract fi x) return (n + fieldColumns' fi) tablePeek :: forall t. NamedTable t -> SqlStmt -> IO t tablePeek tbl stmt = fst <$> tablePeekFrom 1 tbl stmt tablePeekFromMaybe :: forall t. Int -> NamedTable t -> SqlStmt -> IO (Maybe t, Int) tablePeekFromMaybe startCol t stmt = do nullRow <- sqlColumnIsNothing stmt startCol if nullRow then return (Nothing, 1 + startCol + length (tableFields t)) else first Just <$> tablePeekFrom (startCol + 1) t stmt tablePeekFrom :: forall t. Int -> NamedTable t -> SqlStmt -> IO (t, Int) tablePeekFrom startCol (NamedTable _ table) stmt = go table startCol where go :: forall a. Table t a -> Int -> IO (a, Int) go (Map f t) !n = liftM (first f) (go t n) go (Pure x) !n = return (x, n) go (App ft t) !n = do (f, n') <- go ft n (x, n'') <- go t n' return (f x, n'') go (Primitive fi) !n = do x <- fieldPeek stmt n return (x, n + fieldColumns' fi) -- | Get the names of the columns with which the second table refers to the -- first table. In principle, there should be only one. tableRefers :: forall t u. NamedTable u -> NamedTable t -> [String] tableRefers (NamedTable name _) = tableFoldMap go where go :: forall a. Field a => FieldInfo t a -> [String] go fi = [ fieldName fi | IndexFK name' <- fieldIndexes (undefined :: a), name == name' ] -- | Check if columns are missing in the database and ensure the defaults are -- used in those cases tableMakeDefaults :: forall t. Sql -> Maybe t -> NamedTable t -> IO (NamedTable t) tableMakeDefaults sql defaultRecord (NamedTable name table) = do present <- sqlTableColumns sql name return $ NamedTable name $ go present table where go :: forall a. [String] -> Table t a -> Table t a go p (Map f t) = Map f (go p t) go _ (Pure x) = Pure x go p (App ft t) = App (go p ft) (go p t) go p (Primitive fi) -- All field names need to be present... | all (`elem` p) (fieldNames fi) = Primitive fi | otherwise = Pure $ maybe fieldDefault (fieldExtract fi) defaultRecord
pacak/sqroll
src/Database/Sqroll/Table.hs
Haskell
bsd-3-clause
7,280
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Sandbox -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- UI for the sandboxing functionality. ----------------------------------------------------------------------------- module Distribution.Client.Sandbox ( sandboxInit, sandboxDelete, sandboxAddSource, sandboxAddSourceSnapshot, sandboxDeleteSource, sandboxListSources, sandboxHcPkg, dumpPackageEnvironment, withSandboxBinDirOnSearchPath, getSandboxConfigFilePath, loadConfigOrSandboxConfig, findSavedDistPref, initPackageDBIfNeeded, maybeWithSandboxDirOnSearchPath, WereDepsReinstalled(..), reinstallAddSourceDeps, maybeReinstallAddSourceDeps, SandboxPackageInfo(..), maybeWithSandboxPackageInfo, tryGetIndexFilePath, sandboxBuildDir, getInstalledPackagesInSandbox, updateSandboxConfigFileFlag, updateInstallDirs, -- FIXME: move somewhere else configPackageDB', configCompilerAux' ) where import Distribution.Client.Setup ( SandboxFlags(..), ConfigFlags(..), ConfigExFlags(..), InstallFlags(..) , GlobalFlags(..), defaultConfigExFlags, defaultInstallFlags , defaultSandboxLocation, globalRepos ) import Distribution.Client.Sandbox.Timestamp ( listModifiedDeps , maybeAddCompilerTimestampRecord , withAddTimestamps , withRemoveTimestamps ) import Distribution.Client.Config ( SavedConfig(..), defaultUserInstall, loadConfig ) import Distribution.Client.Dependency ( foldProgress ) import Distribution.Client.IndexUtils ( BuildTreeRefType(..) ) import Distribution.Client.Install ( InstallArgs, makeInstallContext, makeInstallPlan, processInstallPlan ) import Distribution.Utils.NubList ( fromNubList ) import Distribution.Client.Sandbox.PackageEnvironment ( PackageEnvironment(..), IncludeComments(..), PackageEnvironmentType(..) , createPackageEnvironmentFile, classifyPackageEnvironment , tryLoadSandboxPackageEnvironmentFile, loadUserConfig , commentPackageEnvironment, showPackageEnvironmentWithComments , sandboxPackageEnvironmentFile, userPackageEnvironmentFile ) import Distribution.Client.Sandbox.Types ( SandboxPackageInfo(..) , UseSandbox(..) ) import Distribution.Client.SetupWrapper ( SetupScriptOptions(..), defaultSetupScriptOptions ) import Distribution.Client.Types ( PackageLocation(..) , SourcePackage(..) ) import Distribution.Client.Utils ( inDir, tryCanonicalizePath , tryFindAddSourcePackageDesc ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.PackageDescription.Parse ( readPackageDescription ) import Distribution.Simple.Compiler ( Compiler(..), PackageDB(..) , PackageDBStack ) import Distribution.Simple.Configure ( configCompilerAuxEx , interpretPackageDbFlags , getPackageDBContents , findDistPref ) import Distribution.Simple.PreProcess ( knownSuffixHandlers ) import Distribution.Simple.Program ( ProgramConfiguration ) import Distribution.Simple.Setup ( Flag(..), HaddockFlags(..) , fromFlagOrDefault ) import Distribution.Simple.SrcDist ( prepareTree ) import Distribution.Simple.Utils ( die, debug, notice, info, warn , debugNoWrap, defaultPackageDesc , intercalate, topHandlerWith , createDirectoryIfMissingVerbose ) import Distribution.Package ( Package(..) ) import Distribution.System ( Platform ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity, lessVerbose ) import Distribution.Compat.Environment ( lookupEnv, setEnv ) import Distribution.Client.Compat.FilePerms ( setFileHidden ) import qualified Distribution.Client.Sandbox.Index as Index import Distribution.Simple.PackageIndex ( InstalledPackageIndex ) import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex import qualified Distribution.Simple.Register as Register import qualified Data.Map as M import qualified Data.Set as S import Control.Exception ( assert, bracket_ ) import Control.Monad ( forM, liftM2, unless, when ) import Data.Bits ( shiftL, shiftR, xor ) import Data.Char ( ord ) import Data.IORef ( newIORef, writeIORef, readIORef ) import Data.List ( delete, foldl' ) import Data.Maybe ( fromJust ) #if !MIN_VERSION_base(4,8,0) import Data.Monoid ( mempty, mappend ) #endif import Data.Word ( Word32 ) import Numeric ( showHex ) import System.Directory ( createDirectory , doesDirectoryExist , doesFileExist , getCurrentDirectory , removeDirectoryRecursive , removeFile , renameDirectory ) import System.FilePath ( (</>), equalFilePath , getSearchPath , searchPathSeparator , takeDirectory ) -- -- * Constants -- -- | The name of the sandbox subdirectory where we keep snapshots of add-source -- dependencies. snapshotDirectoryName :: FilePath snapshotDirectoryName = "snapshots" -- | Non-standard build dir that is used for building add-source deps instead of -- "dist". Fixes surprising behaviour in some cases (see issue #1281). sandboxBuildDir :: FilePath -> FilePath sandboxBuildDir sandboxDir = "dist/dist-sandbox-" ++ showHex sandboxDirHash "" where sandboxDirHash = jenkins sandboxDir -- See http://en.wikipedia.org/wiki/Jenkins_hash_function jenkins :: String -> Word32 jenkins str = loop_finish $ foldl' loop 0 str where loop :: Word32 -> Char -> Word32 loop hash key_i' = hash''' where key_i = toEnum . ord $ key_i' hash' = hash + key_i hash'' = hash' + (shiftL hash' 10) hash''' = hash'' `xor` (shiftR hash'' 6) loop_finish :: Word32 -> Word32 loop_finish hash = hash''' where hash' = hash + (shiftL hash 3) hash'' = hash' `xor` (shiftR hash' 11) hash''' = hash'' + (shiftL hash'' 15) -- -- * Basic sandbox functions. -- -- | If @--sandbox-config-file@ wasn't given on the command-line, set it to the -- value of the @CABAL_SANDBOX_CONFIG@ environment variable, or else to -- 'NoFlag'. updateSandboxConfigFileFlag :: GlobalFlags -> IO GlobalFlags updateSandboxConfigFileFlag globalFlags = case globalSandboxConfigFile globalFlags of Flag _ -> return globalFlags NoFlag -> do f' <- fmap (maybe NoFlag Flag) . lookupEnv $ "CABAL_SANDBOX_CONFIG" return globalFlags { globalSandboxConfigFile = f' } -- | Return the path to the sandbox config file - either the default or the one -- specified with @--sandbox-config-file@. getSandboxConfigFilePath :: GlobalFlags -> IO FilePath getSandboxConfigFilePath globalFlags = do let sandboxConfigFileFlag = globalSandboxConfigFile globalFlags case sandboxConfigFileFlag of NoFlag -> do pkgEnvDir <- getCurrentDirectory return (pkgEnvDir </> sandboxPackageEnvironmentFile) Flag path -> return path -- | Load the @cabal.sandbox.config@ file (and possibly the optional -- @cabal.config@). In addition to a @PackageEnvironment@, also return a -- canonical path to the sandbox. Exit with error if the sandbox directory or -- the package environment file do not exist. tryLoadSandboxConfig :: Verbosity -> GlobalFlags -> IO (FilePath, PackageEnvironment) tryLoadSandboxConfig verbosity globalFlags = do path <- getSandboxConfigFilePath globalFlags tryLoadSandboxPackageEnvironmentFile verbosity path (globalConfigFile globalFlags) -- | Return the name of the package index file for this package environment. tryGetIndexFilePath :: SavedConfig -> IO FilePath tryGetIndexFilePath config = tryGetIndexFilePath' (savedGlobalFlags config) -- | The same as 'tryGetIndexFilePath', but takes 'GlobalFlags' instead of -- 'SavedConfig'. tryGetIndexFilePath' :: GlobalFlags -> IO FilePath tryGetIndexFilePath' globalFlags = do let paths = fromNubList $ globalLocalRepos globalFlags case paths of [] -> die $ "Distribution.Client.Sandbox.tryGetIndexFilePath: " ++ "no local repos found. " ++ checkConfiguration _ -> return $ (last paths) </> Index.defaultIndexFileName where checkConfiguration = "Please check your configuration ('" ++ userPackageEnvironmentFile ++ "')." -- | Try to extract a 'PackageDB' from 'ConfigFlags'. Gives a better error -- message than just pattern-matching. getSandboxPackageDB :: ConfigFlags -> IO PackageDB getSandboxPackageDB configFlags = do case configPackageDBs configFlags of [Just sandboxDB@(SpecificPackageDB _)] -> return sandboxDB -- TODO: should we allow multiple package DBs (e.g. with 'inherit')? [] -> die $ "Sandbox package DB is not specified. " ++ sandboxConfigCorrupt [_] -> die $ "Unexpected contents of the 'package-db' field. " ++ sandboxConfigCorrupt _ -> die $ "Too many package DBs provided. " ++ sandboxConfigCorrupt where sandboxConfigCorrupt = "Your 'cabal.sandbox.config' is probably corrupt." -- | Which packages are installed in the sandbox package DB? getInstalledPackagesInSandbox :: Verbosity -> ConfigFlags -> Compiler -> ProgramConfiguration -> IO InstalledPackageIndex getInstalledPackagesInSandbox verbosity configFlags comp conf = do sandboxDB <- getSandboxPackageDB configFlags getPackageDBContents verbosity comp sandboxDB conf -- | Temporarily add $SANDBOX_DIR/bin to $PATH. withSandboxBinDirOnSearchPath :: FilePath -> IO a -> IO a withSandboxBinDirOnSearchPath sandboxDir = bracket_ addBinDir rmBinDir where -- TODO: Instead of modifying the global process state, it'd be better to -- set the environment individually for each subprocess invocation. This -- will have to wait until the Shell monad is implemented; without it the -- required changes are too intrusive. addBinDir :: IO () addBinDir = do mbOldPath <- lookupEnv "PATH" let newPath = maybe sandboxBin ((++) sandboxBin . (:) searchPathSeparator) mbOldPath setEnv "PATH" newPath rmBinDir :: IO () rmBinDir = do oldPath <- getSearchPath let newPath = intercalate [searchPathSeparator] (delete sandboxBin oldPath) setEnv "PATH" newPath sandboxBin = sandboxDir </> "bin" -- | Initialise a package DB for this compiler if it doesn't exist. initPackageDBIfNeeded :: Verbosity -> ConfigFlags -> Compiler -> ProgramConfiguration -> IO () initPackageDBIfNeeded verbosity configFlags comp conf = do SpecificPackageDB dbPath <- getSandboxPackageDB configFlags packageDBExists <- doesDirectoryExist dbPath unless packageDBExists $ Register.initPackageDB verbosity comp conf dbPath when packageDBExists $ debug verbosity $ "The package database already exists: " ++ dbPath -- | Entry point for the 'cabal sandbox dump-pkgenv' command. dumpPackageEnvironment :: Verbosity -> SandboxFlags -> GlobalFlags -> IO () dumpPackageEnvironment verbosity _sandboxFlags globalFlags = do (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity globalFlags commentPkgEnv <- commentPackageEnvironment sandboxDir putStrLn . showPackageEnvironmentWithComments (Just commentPkgEnv) $ pkgEnv -- | Entry point for the 'cabal sandbox init' command. sandboxInit :: Verbosity -> SandboxFlags -> GlobalFlags -> IO () sandboxInit verbosity sandboxFlags globalFlags = do -- Warn if there's a 'cabal-dev' sandbox. isCabalDevSandbox <- liftM2 (&&) (doesDirectoryExist "cabal-dev") (doesFileExist $ "cabal-dev" </> "cabal.config") when isCabalDevSandbox $ warn verbosity $ "You are apparently using a legacy (cabal-dev) sandbox. " ++ "Legacy sandboxes may interact badly with native Cabal sandboxes. " ++ "You may want to delete the 'cabal-dev' directory to prevent issues." -- Create the sandbox directory. let sandboxDir' = fromFlagOrDefault defaultSandboxLocation (sandboxLocation sandboxFlags) createDirectoryIfMissingVerbose verbosity True sandboxDir' sandboxDir <- tryCanonicalizePath sandboxDir' setFileHidden sandboxDir -- Determine which compiler to use (using the value from ~/.cabal/config). userConfig <- loadConfig verbosity (globalConfigFile globalFlags) (comp, platform, conf) <- configCompilerAuxEx (savedConfigureFlags userConfig) -- Create the package environment file. pkgEnvFile <- getSandboxConfigFilePath globalFlags createPackageEnvironmentFile verbosity sandboxDir pkgEnvFile NoComments comp platform (_sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity globalFlags let config = pkgEnvSavedConfig pkgEnv configFlags = savedConfigureFlags config -- Create the index file if it doesn't exist. indexFile <- tryGetIndexFilePath config indexFileExists <- doesFileExist indexFile if indexFileExists then notice verbosity $ "Using an existing sandbox located at " ++ sandboxDir else notice verbosity $ "Creating a new sandbox at " ++ sandboxDir Index.createEmpty verbosity indexFile -- Create the package DB for the default compiler. initPackageDBIfNeeded verbosity configFlags comp conf maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile (compilerId comp) platform -- | Entry point for the 'cabal sandbox delete' command. sandboxDelete :: Verbosity -> SandboxFlags -> GlobalFlags -> IO () sandboxDelete verbosity _sandboxFlags globalFlags = do (useSandbox, _) <- loadConfigOrSandboxConfig verbosity globalFlags { globalRequireSandbox = Flag False } case useSandbox of NoSandbox -> warn verbosity "Not in a sandbox." UseSandbox sandboxDir -> do curDir <- getCurrentDirectory pkgEnvFile <- getSandboxConfigFilePath globalFlags -- Remove the @cabal.sandbox.config@ file, unless it's in a non-standard -- location. let isNonDefaultConfigLocation = not $ equalFilePath pkgEnvFile $ curDir </> sandboxPackageEnvironmentFile if isNonDefaultConfigLocation then warn verbosity $ "Sandbox config file is in non-default location: '" ++ pkgEnvFile ++ "'.\n Please delete manually." else removeFile pkgEnvFile -- Remove the sandbox directory, unless we're using a shared sandbox. let isNonDefaultSandboxLocation = not $ equalFilePath sandboxDir $ curDir </> defaultSandboxLocation when isNonDefaultSandboxLocation $ die $ "Non-default sandbox location used: '" ++ sandboxDir ++ "'.\nAssuming a shared sandbox. Please delete '" ++ sandboxDir ++ "' manually." notice verbosity $ "Deleting the sandbox located at " ++ sandboxDir removeDirectoryRecursive sandboxDir -- Common implementation of 'sandboxAddSource' and 'sandboxAddSourceSnapshot'. doAddSource :: Verbosity -> [FilePath] -> FilePath -> PackageEnvironment -> BuildTreeRefType -> IO () doAddSource verbosity buildTreeRefs sandboxDir pkgEnv refType = do let savedConfig = pkgEnvSavedConfig pkgEnv indexFile <- tryGetIndexFilePath savedConfig -- If we're running 'sandbox add-source' for the first time for this compiler, -- we need to create an initial timestamp record. (comp, platform, _) <- configCompilerAuxEx . savedConfigureFlags $ savedConfig maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile (compilerId comp) platform withAddTimestamps sandboxDir $ do -- FIXME: path canonicalisation is done in addBuildTreeRefs, but we do it -- twice because of the timestamps file. buildTreeRefs' <- mapM tryCanonicalizePath buildTreeRefs Index.addBuildTreeRefs verbosity indexFile buildTreeRefs' refType return buildTreeRefs' -- | Entry point for the 'cabal sandbox add-source' command. sandboxAddSource :: Verbosity -> [FilePath] -> SandboxFlags -> GlobalFlags -> IO () sandboxAddSource verbosity buildTreeRefs sandboxFlags globalFlags = do (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity globalFlags if fromFlagOrDefault False (sandboxSnapshot sandboxFlags) then sandboxAddSourceSnapshot verbosity buildTreeRefs sandboxDir pkgEnv else doAddSource verbosity buildTreeRefs sandboxDir pkgEnv LinkRef -- | Entry point for the 'cabal sandbox add-source --snapshot' command. sandboxAddSourceSnapshot :: Verbosity -> [FilePath] -> FilePath -> PackageEnvironment -> IO () sandboxAddSourceSnapshot verbosity buildTreeRefs sandboxDir pkgEnv = do let snapshotDir = sandboxDir </> snapshotDirectoryName -- Use 'D.S.SrcDist.prepareTree' to copy each package's files to our private -- location. createDirectoryIfMissingVerbose verbosity True snapshotDir -- Collect the package descriptions first, so that if some path does not refer -- to a cabal package, we fail immediately. pkgs <- forM buildTreeRefs $ \buildTreeRef -> inDir (Just buildTreeRef) $ return . flattenPackageDescription =<< readPackageDescription verbosity =<< defaultPackageDesc verbosity -- Copy the package sources to "snapshots/$PKGNAME-$VERSION-tmp". If -- 'prepareTree' throws an error at any point, the old snapshots will still be -- in consistent state. tmpDirs <- forM (zip buildTreeRefs pkgs) $ \(buildTreeRef, pkg) -> inDir (Just buildTreeRef) $ do let targetDir = snapshotDir </> (display . packageId $ pkg) targetTmpDir = targetDir ++ "-tmp" dirExists <- doesDirectoryExist targetTmpDir when dirExists $ removeDirectoryRecursive targetDir createDirectory targetTmpDir prepareTree verbosity pkg Nothing targetTmpDir knownSuffixHandlers return (targetTmpDir, targetDir) -- Now rename the "snapshots/$PKGNAME-$VERSION-tmp" dirs to -- "snapshots/$PKGNAME-$VERSION". snapshots <- forM tmpDirs $ \(targetTmpDir, targetDir) -> do dirExists <- doesDirectoryExist targetDir when dirExists $ removeDirectoryRecursive targetDir renameDirectory targetTmpDir targetDir return targetDir -- Once the packages are copied, just 'add-source' them as usual. doAddSource verbosity snapshots sandboxDir pkgEnv SnapshotRef -- | Entry point for the 'cabal sandbox delete-source' command. sandboxDeleteSource :: Verbosity -> [FilePath] -> SandboxFlags -> GlobalFlags -> IO () sandboxDeleteSource verbosity buildTreeRefs _sandboxFlags globalFlags = do (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity globalFlags indexFile <- tryGetIndexFilePath (pkgEnvSavedConfig pkgEnv) withRemoveTimestamps sandboxDir $ do Index.removeBuildTreeRefs verbosity indexFile buildTreeRefs notice verbosity $ "Note: 'sandbox delete-source' only unregisters the " ++ "source dependency, but does not remove the package " ++ "from the sandbox package DB.\n\n" ++ "Use 'sandbox hc-pkg -- unregister' to do that." -- | Entry point for the 'cabal sandbox list-sources' command. sandboxListSources :: Verbosity -> SandboxFlags -> GlobalFlags -> IO () sandboxListSources verbosity _sandboxFlags globalFlags = do (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity globalFlags indexFile <- tryGetIndexFilePath (pkgEnvSavedConfig pkgEnv) refs <- Index.listBuildTreeRefs verbosity Index.ListIgnored Index.LinksAndSnapshots indexFile when (null refs) $ notice verbosity $ "Index file '" ++ indexFile ++ "' has no references to local build trees." when (not . null $ refs) $ do notice verbosity $ "Source dependencies registered " ++ "in the current sandbox ('" ++ sandboxDir ++ "'):\n\n" mapM_ putStrLn refs notice verbosity $ "\nTo unregister source dependencies, " ++ "use the 'sandbox delete-source' command." -- | Entry point for the 'cabal sandbox hc-pkg' command. Invokes the @hc-pkg@ -- tool with provided arguments, restricted to the sandbox. sandboxHcPkg :: Verbosity -> SandboxFlags -> GlobalFlags -> [String] -> IO () sandboxHcPkg verbosity _sandboxFlags globalFlags extraArgs = do (_sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity globalFlags let configFlags = savedConfigureFlags . pkgEnvSavedConfig $ pkgEnv dbStack = configPackageDB' configFlags (comp, _platform, conf) <- configCompilerAux' configFlags Register.invokeHcPkg verbosity comp conf dbStack extraArgs updateInstallDirs :: Flag Bool -> (UseSandbox, SavedConfig) -> (UseSandbox, SavedConfig) updateInstallDirs userInstallFlag (useSandbox, savedConfig) = case useSandbox of NoSandbox -> let savedConfig' = savedConfig { savedConfigureFlags = configureFlags { configInstallDirs = installDirs } } in (useSandbox, savedConfig') _ -> (useSandbox, savedConfig) where configureFlags = savedConfigureFlags savedConfig userInstallDirs = savedUserInstallDirs savedConfig globalInstallDirs = savedGlobalInstallDirs savedConfig installDirs | userInstall = userInstallDirs | otherwise = globalInstallDirs userInstall = fromFlagOrDefault defaultUserInstall (configUserInstall configureFlags `mappend` userInstallFlag) -- | Check which type of package environment we're in and return a -- correctly-initialised @SavedConfig@ and a @UseSandbox@ value that indicates -- whether we're working in a sandbox. loadConfigOrSandboxConfig :: Verbosity -> GlobalFlags -- ^ For @--config-file@ and -- @--sandbox-config-file@. -> IO (UseSandbox, SavedConfig) loadConfigOrSandboxConfig verbosity globalFlags = do let configFileFlag = globalConfigFile globalFlags sandboxConfigFileFlag = globalSandboxConfigFile globalFlags ignoreSandboxFlag = globalIgnoreSandbox globalFlags pkgEnvDir <- getPkgEnvDir sandboxConfigFileFlag pkgEnvType <- classifyPackageEnvironment pkgEnvDir sandboxConfigFileFlag ignoreSandboxFlag case pkgEnvType of -- A @cabal.sandbox.config@ file (and possibly @cabal.config@) is present. SandboxPackageEnvironment -> do (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity globalFlags -- ^ Prints an error message and exits on error. let config = pkgEnvSavedConfig pkgEnv return (UseSandbox sandboxDir, config) -- Only @cabal.config@ is present. UserPackageEnvironment -> do config <- loadConfig verbosity configFileFlag userConfig <- loadUserConfig verbosity pkgEnvDir let config' = config `mappend` userConfig dieIfSandboxRequired config' return (NoSandbox, config') -- Neither @cabal.sandbox.config@ nor @cabal.config@ are present. AmbientPackageEnvironment -> do config <- loadConfig verbosity configFileFlag dieIfSandboxRequired config return (NoSandbox, config) where -- Return the path to the package environment directory - either the -- current directory or the one that @--sandbox-config-file@ resides in. getPkgEnvDir :: (Flag FilePath) -> IO FilePath getPkgEnvDir sandboxConfigFileFlag = do case sandboxConfigFileFlag of NoFlag -> getCurrentDirectory Flag path -> tryCanonicalizePath . takeDirectory $ path -- Die if @--require-sandbox@ was specified and we're not inside a sandbox. dieIfSandboxRequired :: SavedConfig -> IO () dieIfSandboxRequired config = checkFlag flag where flag = (globalRequireSandbox . savedGlobalFlags $ config) `mappend` (globalRequireSandbox globalFlags) checkFlag (Flag True) = die $ "'require-sandbox' is set to True, but no sandbox is present. " ++ "Use '--no-require-sandbox' if you want to override " ++ "'require-sandbox' temporarily." checkFlag (Flag False) = return () checkFlag (NoFlag) = return () -- | Return the saved \"dist/\" prefix, or the default prefix. findSavedDistPref :: SavedConfig -> Flag FilePath -> IO FilePath findSavedDistPref config flagDistPref = do let defDistPref = useDistPref defaultSetupScriptOptions flagDistPref' = configDistPref (savedConfigureFlags config) `mappend` flagDistPref findDistPref defDistPref flagDistPref' -- | If we're in a sandbox, call @withSandboxBinDirOnSearchPath@, otherwise do -- nothing. maybeWithSandboxDirOnSearchPath :: UseSandbox -> IO a -> IO a maybeWithSandboxDirOnSearchPath NoSandbox act = act maybeWithSandboxDirOnSearchPath (UseSandbox sandboxDir) act = withSandboxBinDirOnSearchPath sandboxDir $ act -- | Had reinstallAddSourceDeps actually reinstalled any dependencies? data WereDepsReinstalled = ReinstalledSomeDeps | NoDepsReinstalled -- | Reinstall those add-source dependencies that have been modified since -- we've last installed them. Assumes that we're working inside a sandbox. reinstallAddSourceDeps :: Verbosity -> ConfigFlags -> ConfigExFlags -> InstallFlags -> GlobalFlags -> FilePath -> IO WereDepsReinstalled reinstallAddSourceDeps verbosity configFlags' configExFlags installFlags globalFlags sandboxDir = topHandler' $ do let sandboxDistPref = sandboxBuildDir sandboxDir configFlags = configFlags' { configDistPref = Flag sandboxDistPref } haddockFlags = mempty { haddockDistPref = Flag sandboxDistPref } (comp, platform, conf) <- configCompilerAux' configFlags retVal <- newIORef NoDepsReinstalled withSandboxPackageInfo verbosity configFlags globalFlags comp platform conf sandboxDir $ \sandboxPkgInfo -> unless (null $ modifiedAddSourceDependencies sandboxPkgInfo) $ do let args :: InstallArgs args = ((configPackageDB' configFlags) ,(globalRepos globalFlags) ,comp, platform, conf ,UseSandbox sandboxDir, Just sandboxPkgInfo ,globalFlags, configFlags, configExFlags, installFlags ,haddockFlags) -- This can actually be replaced by a call to 'install', but we use a -- lower-level API because of layer separation reasons. Additionally, we -- might want to use some lower-level features this in the future. withSandboxBinDirOnSearchPath sandboxDir $ do installContext <- makeInstallContext verbosity args Nothing installPlan <- foldProgress logMsg die' return =<< makeInstallPlan verbosity args installContext processInstallPlan verbosity args installContext installPlan writeIORef retVal ReinstalledSomeDeps readIORef retVal where die' message = die (message ++ installFailedInSandbox) -- TODO: use a better error message, remove duplication. installFailedInSandbox = "Note: when using a sandbox, all packages are required to have consistent dependencies. Try reinstalling/unregistering the offending packages or recreating the sandbox." logMsg message rest = debugNoWrap verbosity message >> rest topHandler' = topHandlerWith $ \_ -> do warn verbosity "Couldn't reinstall some add-source dependencies." -- Here we can't know whether any deps have been reinstalled, so we have -- to be conservative. return ReinstalledSomeDeps -- | Produce a 'SandboxPackageInfo' and feed it to the given action. Note that -- we don't update the timestamp file here - this is done in -- 'postInstallActions'. withSandboxPackageInfo :: Verbosity -> ConfigFlags -> GlobalFlags -> Compiler -> Platform -> ProgramConfiguration -> FilePath -> (SandboxPackageInfo -> IO ()) -> IO () withSandboxPackageInfo verbosity configFlags globalFlags comp platform conf sandboxDir cont = do -- List all add-source deps. indexFile <- tryGetIndexFilePath' globalFlags buildTreeRefs <- Index.listBuildTreeRefs verbosity Index.DontListIgnored Index.OnlyLinks indexFile let allAddSourceDepsSet = S.fromList buildTreeRefs -- List all packages installed in the sandbox. installedPkgIndex <- getInstalledPackagesInSandbox verbosity configFlags comp conf let err = "Error reading sandbox package information." -- Get the package descriptions for all add-source deps. depsCabalFiles <- mapM (flip tryFindAddSourcePackageDesc err) buildTreeRefs depsPkgDescs <- mapM (readPackageDescription verbosity) depsCabalFiles let depsMap = M.fromList (zip buildTreeRefs depsPkgDescs) isInstalled pkgid = not . null . InstalledPackageIndex.lookupSourcePackageId installedPkgIndex $ pkgid installedDepsMap = M.filter (isInstalled . packageId) depsMap -- Get the package ids of modified (and installed) add-source deps. modifiedAddSourceDeps <- listModifiedDeps verbosity sandboxDir (compilerId comp) platform installedDepsMap -- 'fromJust' here is safe because 'modifiedAddSourceDeps' are guaranteed to -- be a subset of the keys of 'depsMap'. let modifiedDeps = [ (modDepPath, fromJust $ M.lookup modDepPath depsMap) | modDepPath <- modifiedAddSourceDeps ] modifiedDepsMap = M.fromList modifiedDeps assert (all (`S.member` allAddSourceDepsSet) modifiedAddSourceDeps) (return ()) if (null modifiedDeps) then info verbosity $ "Found no modified add-source deps." else notice verbosity $ "Some add-source dependencies have been modified. " ++ "They will be reinstalled..." -- Get the package ids of the remaining add-source deps (some are possibly not -- installed). let otherDeps = M.assocs (depsMap `M.difference` modifiedDepsMap) -- Finally, assemble a 'SandboxPackageInfo'. cont $ SandboxPackageInfo (map toSourcePackage modifiedDeps) (map toSourcePackage otherDeps) installedPkgIndex allAddSourceDepsSet where toSourcePackage (path, pkgDesc) = SourcePackage (packageId pkgDesc) pkgDesc (LocalUnpackedPackage path) Nothing -- | Same as 'withSandboxPackageInfo' if we're inside a sandbox and a no-op -- otherwise. maybeWithSandboxPackageInfo :: Verbosity -> ConfigFlags -> GlobalFlags -> Compiler -> Platform -> ProgramConfiguration -> UseSandbox -> (Maybe SandboxPackageInfo -> IO ()) -> IO () maybeWithSandboxPackageInfo verbosity configFlags globalFlags comp platform conf useSandbox cont = case useSandbox of NoSandbox -> cont Nothing UseSandbox sandboxDir -> withSandboxPackageInfo verbosity configFlags globalFlags comp platform conf sandboxDir (\spi -> cont (Just spi)) -- | Check if a sandbox is present and call @reinstallAddSourceDeps@ in that -- case. maybeReinstallAddSourceDeps :: Verbosity -> Flag (Maybe Int) -- ^ The '-j' flag -> ConfigFlags -- ^ Saved configure flags -- (from dist/setup-config) -> GlobalFlags -> (UseSandbox, SavedConfig) -> IO WereDepsReinstalled maybeReinstallAddSourceDeps verbosity numJobsFlag configFlags' globalFlags' (useSandbox, config) = do case useSandbox of NoSandbox -> return NoDepsReinstalled UseSandbox sandboxDir -> do -- Reinstall the modified add-source deps. let configFlags = savedConfigureFlags config `mappendSomeSavedFlags` configFlags' configExFlags = defaultConfigExFlags `mappend` savedConfigureExFlags config installFlags' = defaultInstallFlags `mappend` savedInstallFlags config installFlags = installFlags' { installNumJobs = installNumJobs installFlags' `mappend` numJobsFlag } globalFlags = savedGlobalFlags config -- This makes it possible to override things like 'remote-repo-cache' -- from the command line. These options are hidden, and are only -- useful for debugging, so this should be fine. `mappend` globalFlags' reinstallAddSourceDeps verbosity configFlags configExFlags installFlags globalFlags sandboxDir where -- NOTE: we can't simply do @sandboxConfigFlags `mappend` savedFlags@ -- because we don't want to auto-enable things like 'library-profiling' for -- all add-source dependencies even if the user has passed -- '--enable-library-profiling' to 'cabal configure'. These options are -- supposed to be set in 'cabal.config'. mappendSomeSavedFlags :: ConfigFlags -> ConfigFlags -> ConfigFlags mappendSomeSavedFlags sandboxConfigFlags savedFlags = sandboxConfigFlags { configHcFlavor = configHcFlavor sandboxConfigFlags `mappend` configHcFlavor savedFlags, configHcPath = configHcPath sandboxConfigFlags `mappend` configHcPath savedFlags, configHcPkg = configHcPkg sandboxConfigFlags `mappend` configHcPkg savedFlags, configProgramPaths = configProgramPaths sandboxConfigFlags `mappend` configProgramPaths savedFlags, configProgramArgs = configProgramArgs sandboxConfigFlags `mappend` configProgramArgs savedFlags, -- NOTE: Unconditionally choosing the value from -- 'dist/setup-config'. Sandbox package DB location may have been -- changed by 'configure -w'. configPackageDBs = configPackageDBs savedFlags -- FIXME: Is this compatible with the 'inherit' feature? } -- -- Utils (transitionary) -- -- FIXME: configPackageDB' and configCompilerAux' don't really belong in this -- module -- configPackageDB' :: ConfigFlags -> PackageDBStack configPackageDB' cfg = interpretPackageDbFlags userInstall (configPackageDBs cfg) where userInstall = fromFlagOrDefault True (configUserInstall cfg) configCompilerAux' :: ConfigFlags -> IO (Compiler, Platform, ProgramConfiguration) configCompilerAux' configFlags = configCompilerAuxEx configFlags --FIXME: make configCompilerAux use a sensible verbosity { configVerbosity = fmap lessVerbose (configVerbosity configFlags) }
ian-ross/cabal
cabal-install/Distribution/Client/Sandbox.hs
Haskell
bsd-3-clause
37,321
module Lang.Php.Ast.Stmt ( module Lang.Php.Ast.StmtParse, module Lang.Php.Ast.StmtTypes, module Lang.Php.Ast.StmtUnparse ) where import Lang.Php.Ast.StmtParse import Lang.Php.Ast.StmtTypes import Lang.Php.Ast.StmtUnparse
facebookarchive/lex-pass
src/Lang/Php/Ast/Stmt.hs
Haskell
bsd-3-clause
230
module Instruction ( RegUsage(..), noUsage, GenBasicBlock(..), blockId, ListGraph(..), NatCmm, NatCmmDecl, NatBasicBlock, topInfoTable, entryBlocks, Instruction(..) ) where import GhcPrelude import Reg import GHC.Cmm.BlockId import GHC.Cmm.Dataflow.Collections import GHC.Cmm.Dataflow.Label import DynFlags import GHC.Cmm hiding (topInfoTable) import GHC.Platform -- | Holds a list of source and destination registers used by a -- particular instruction. -- -- Machine registers that are pre-allocated to stgRegs are filtered -- out, because they are uninteresting from a register allocation -- standpoint. (We wouldn't want them to end up on the free list!) -- -- As far as we are concerned, the fixed registers simply don't exist -- (for allocation purposes, anyway). -- data RegUsage = RU [Reg] [Reg] -- | No regs read or written to. noUsage :: RegUsage noUsage = RU [] [] -- Our flavours of the Cmm types -- Type synonyms for Cmm populated with native code type NatCmm instr = GenCmmGroup RawCmmStatics (LabelMap RawCmmStatics) (ListGraph instr) type NatCmmDecl statics instr = GenCmmDecl statics (LabelMap RawCmmStatics) (ListGraph instr) type NatBasicBlock instr = GenBasicBlock instr -- | Returns the info table associated with the CmmDecl's entry point, -- if any. topInfoTable :: GenCmmDecl a (LabelMap i) (ListGraph b) -> Maybe i topInfoTable (CmmProc infos _ _ (ListGraph (b:_))) = mapLookup (blockId b) infos topInfoTable _ = Nothing -- | Return the list of BlockIds in a CmmDecl that are entry points -- for this proc (i.e. they may be jumped to from outside this proc). entryBlocks :: GenCmmDecl a (LabelMap i) (ListGraph b) -> [BlockId] entryBlocks (CmmProc info _ _ (ListGraph code)) = entries where infos = mapKeys info entries = case code of [] -> infos BasicBlock entry _ : _ -- first block is the entry point | entry `elem` infos -> infos | otherwise -> entry : infos entryBlocks _ = [] -- | Common things that we can do with instructions, on all architectures. -- These are used by the shared parts of the native code generator, -- specifically the register allocators. -- class Instruction instr where -- | Get the registers that are being used by this instruction. -- regUsage doesn't need to do any trickery for jumps and such. -- Just state precisely the regs read and written by that insn. -- The consequences of control flow transfers, as far as register -- allocation goes, are taken care of by the register allocator. -- regUsageOfInstr :: Platform -> instr -> RegUsage -- | Apply a given mapping to all the register references in this -- instruction. patchRegsOfInstr :: instr -> (Reg -> Reg) -> instr -- | Checks whether this instruction is a jump/branch instruction. -- One that can change the flow of control in a way that the -- register allocator needs to worry about. isJumpishInstr :: instr -> Bool -- | Give the possible destinations of this jump instruction. -- Must be defined for all jumpish instructions. jumpDestsOfInstr :: instr -> [BlockId] -- | Change the destination of this jump instruction. -- Used in the linear allocator when adding fixup blocks for join -- points. patchJumpInstr :: instr -> (BlockId -> BlockId) -> instr -- | An instruction to spill a register into a spill slot. mkSpillInstr :: DynFlags -> Reg -- ^ the reg to spill -> Int -- ^ the current stack delta -> Int -- ^ spill slot to use -> instr -- | An instruction to reload a register from a spill slot. mkLoadInstr :: DynFlags -> Reg -- ^ the reg to reload. -> Int -- ^ the current stack delta -> Int -- ^ the spill slot to use -> instr -- | See if this instruction is telling us the current C stack delta takeDeltaInstr :: instr -> Maybe Int -- | Check whether this instruction is some meta thing inserted into -- the instruction stream for other purposes. -- -- Not something that has to be treated as a real machine instruction -- and have its registers allocated. -- -- eg, comments, delta, ldata, etc. isMetaInstr :: instr -> Bool -- | Copy the value in a register to another one. -- Must work for all register classes. mkRegRegMoveInstr :: Platform -> Reg -- ^ source register -> Reg -- ^ destination register -> instr -- | Take the source and destination from this reg -> reg move instruction -- or Nothing if it's not one takeRegRegMoveInstr :: instr -> Maybe (Reg, Reg) -- | Make an unconditional jump instruction. -- For architectures with branch delay slots, its ok to put -- a NOP after the jump. Don't fill the delay slot with an -- instruction that references regs or you'll confuse the -- linear allocator. mkJumpInstr :: BlockId -> [instr] -- Subtract an amount from the C stack pointer mkStackAllocInstr :: Platform -> Int -> [instr] -- Add an amount to the C stack pointer mkStackDeallocInstr :: Platform -> Int -> [instr]
sdiehl/ghc
compiler/nativeGen/Instruction.hs
Haskell
bsd-3-clause
6,365
module ParseOutput(parseOutput) where import Text.Parsec import Text.Parsec.String import Text.Parsec.Perm import Data.Char import Types import ParseUtil parseOutput = do r <- permute ( combine <$$> (skipMany unwanted >> result) <||> (skipMany unwanted >> solutionLine)) skipMany unwanted eof return r where combine r1 r2 = (r1,concat r2) unwanted = comment <|> emptyLine <|> (objectiveValue >> return "") --parseOutput = do -- skipMany unwanted -- r1 <- result -- skipMany unwanted -- r2 <- solutionLine -- skipMany unwanted -- eof -- return (r1,concat r2) -- where -- combine r1 r2 = (r1,concat r2) -- unwanted = comment <|> emptyLine <|> (objectiveValue >> return "") solutionLine = many solution emptyLine = manyTill space newline comment = do char 'c' manyTill anyToken newline objectiveValue :: Parser Integer objectiveValue = do char 'o' spaces n <- number spaces return n result :: Parser Result result = do char 's' spaces result <- resultString spaces return result solution = do char 'v' optional spaces assignment <- literal `sepEndBy` spaces return assignment literal = (char '-' >> (variable >>= return . NegLit)) <|> ( (variable >>= return . PosLit)) resultString = (string "SATISFIABLE" >> return Sat) <|> (string "OPTIMUM FOUND" >> return OptFound) <|> (string "UNSATISFIABLE" >> return Unsat) <|> (string "UNKNOWN" >> return Unknown)
EJahren/PBCompOutputChecker
src/ParseOutput.hs
Haskell
bsd-3-clause
1,495
{-# LANGUAGE OverloadedStrings #-} module Cheapskate.Inlines ( parseInlines , pHtmlTag , pReference , pLinkLabel) where import Cheapskate.ParserCombinators import Cheapskate.Util import Cheapskate.Types import Data.Char hiding (Space) import qualified Data.Sequence as Seq import Data.Sequence (singleton, (<|), viewl, ViewL(..)) import Prelude hiding (takeWhile) import Control.Applicative import Data.Monoid import Control.Monad import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import qualified Data.Set as Set -- Returns tag type and whole tag. pHtmlTag :: Parser (HtmlTagType, Text) pHtmlTag = do char '<' -- do not end the tag with a > character in a quoted attribute. closing <- (char '/' >> return True) <|> return False tagname <- takeWhile1 (\c -> isAsciiAlphaNum c || c == '?' || c == '!') let tagname' = T.toLower tagname let attr = do ss <- takeWhile isSpace x <- satisfy isLetter xs <- takeWhile (\c -> isAsciiAlphaNum c || c == ':') skip (=='=') v <- pQuoted '"' <|> pQuoted '\'' <|> takeWhile1 isAlphaNum <|> return "" return $ ss <> T.singleton x <> xs <> "=" <> v attrs <- T.concat <$> many attr final <- takeWhile (\c -> isSpace c || c == '/') char '>' let tagtype = if closing then Closing tagname' else case T.stripSuffix "/" final of Just _ -> SelfClosing tagname' Nothing -> Opening tagname' return (tagtype, T.pack ('<' : ['/' | closing]) <> tagname <> attrs <> final <> ">") -- Parses a quoted attribute value. pQuoted :: Char -> Parser Text pQuoted c = do skip (== c) contents <- takeTill (== c) skip (== c) return (T.singleton c <> contents <> T.singleton c) -- Parses an HTML comment. This isn't really correct to spec, but should -- do for now. pHtmlComment :: Parser Text pHtmlComment = do string "<!--" rest <- manyTill anyChar (string "-->") return $ "<!--" <> T.pack rest <> "-->" -- A link label [like this]. Note the precedence: code backticks have -- precedence over label bracket markers, which have precedence over -- *, _, and other inline formatting markers. -- So, 2 below contains a link while 1 does not: -- 1. [a link `with a ](/url)` character -- 2. [a link *with emphasized ](/url) text* pLinkLabel :: Parser Text pLinkLabel = char '[' *> (T.concat <$> (manyTill (regChunk <|> pEscaped <|> bracketed <|> codeChunk) (char ']'))) where regChunk = takeWhile1 (\c -> c /='`' && c /='[' && c /=']' && c /='\\') codeChunk = snd <$> pCode' bracketed = inBrackets <$> pLinkLabel inBrackets t = "[" <> t <> "]" -- A URL in a link or reference. This may optionally be contained -- in `<..>`; otherwise whitespace and unbalanced right parentheses -- aren't allowed. Newlines aren't allowed in any case. pLinkUrl :: Parser Text pLinkUrl = do inPointy <- (char '<' >> return True) <|> return False if inPointy then T.pack <$> manyTill (pSatisfy (\c -> c /='\r' && c /='\n')) (char '>') else T.concat <$> many (regChunk <|> parenChunk) where regChunk = takeWhile1 (notInClass " \n()\\") <|> pEscaped parenChunk = parenthesize . T.concat <$> (char '(' *> manyTill (regChunk <|> parenChunk) (char ')')) parenthesize x = "(" <> x <> ")" -- A link title, single or double quoted or in parentheses. -- Note that Markdown.pl doesn't allow the parenthesized form in -- inline links -- only in references -- but this restriction seems -- arbitrary, so we remove it here. pLinkTitle :: Parser Text pLinkTitle = do c <- satisfy (\c -> c == '"' || c == '\'' || c == '(') next <- peekChar case next of Nothing -> mzero Just x | isWhitespace x -> mzero | x == ')' -> mzero | otherwise -> return () let ender = if c == '(' then ')' else c let pEnder = char ender <* nfb (skip isAlphaNum) let regChunk = takeWhile1 (\x -> x /= ender && x /= '\\') <|> pEscaped let nestedChunk = (\x -> T.singleton c <> x <> T.singleton ender) <$> pLinkTitle T.concat <$> manyTill (regChunk <|> nestedChunk) pEnder -- A link reference is a square-bracketed link label, a colon, -- optional space or newline, a URL, optional space or newline, -- and an optional link title. (Note: we assume the input is -- pre-stripped, with no leading/trailing spaces.) pReference :: Parser (Text, Text, Text) pReference = do lab <- pLinkLabel char ':' scanSpnl url <- pLinkUrl tit <- option T.empty $ scanSpnl >> pLinkTitle endOfInput return (lab, url, tit) -- Parses an escaped character and returns a Text. pEscaped :: Parser Text pEscaped = T.singleton <$> (skip (=='\\') *> satisfy isEscapable) -- Parses a (possibly escaped) character satisfying the predicate. pSatisfy :: (Char -> Bool) -> Parser Char pSatisfy p = satisfy (\c -> c /= '\\' && p c) <|> (char '\\' *> satisfy (\c -> isEscapable c && p c)) -- Parse a text into inlines, resolving reference links -- using the reference map. parseInlines :: ReferenceMap -> Text -> Inlines parseInlines refmap t = case parse (msum <$> many (pInline refmap) <* endOfInput) t of Left e -> error ("parseInlines: " ++ show e) -- should not happen Right r -> r pInline :: ReferenceMap -> Parser Inlines pInline refmap = pAsciiStr <|> pSpace <|> pEnclosure '*' refmap -- strong/emph <|> (notAfter isAlphaNum *> pEnclosure '_' refmap) <|> pCode <|> pLink refmap <|> pImage refmap <|> pRawHtml <|> pAutolink <|> pEntity <|> pSym -- Parse spaces or newlines, and determine whether -- we have a regular space, a line break (two spaces before -- a newline), or a soft break (newline without two spaces -- before). pSpace :: Parser Inlines pSpace = do ss <- takeWhile1 isWhitespace return $ singleton $ if T.any (=='\n') ss then if " " `T.isPrefixOf` ss then LineBreak else SoftBreak else Space isAsciiAlphaNum :: Char -> Bool isAsciiAlphaNum c = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') pAsciiStr :: Parser Inlines pAsciiStr = do t <- takeWhile1 isAsciiAlphaNum mbc <- peekChar case mbc of Just ':' -> if t `Set.member` schemeSet then pUri t else return $ singleton $ Str t _ -> return $ singleton $ Str t -- Catch all -- parse an escaped character, an escaped -- newline, or any remaining symbol character. pSym :: Parser Inlines pSym = do c <- anyChar let ch = singleton . Str . T.singleton if c == '\\' then ch <$> satisfy isEscapable <|> singleton LineBreak <$ satisfy (=='\n') <|> return (ch '\\') else return (ch c) -- http://www.iana.org/assignments/uri-schemes.html plus -- the unofficial schemes coap, doi, javascript. schemes :: [Text] schemes = [ -- unofficial "coap","doi","javascript" -- official ,"aaa","aaas","about","acap" ,"cap","cid","crid","data","dav","dict","dns","file","ftp" ,"geo","go","gopher","h323","http","https","iax","icap","im" ,"imap","info","ipp","iris","iris.beep","iris.xpc","iris.xpcs" ,"iris.lwz","ldap","mailto","mid","msrp","msrps","mtqp" ,"mupdate","news","nfs","ni","nih","nntp","opaquelocktoken","pop" ,"pres","rtsp","service","session","shttp","sieve","sip","sips" ,"sms","snmp","soap.beep","soap.beeps","tag","tel","telnet","tftp" ,"thismessage","tn3270","tip","tv","urn","vemmi","ws","wss" ,"xcon","xcon-userid","xmlrpc.beep","xmlrpc.beeps","xmpp","z39.50r" ,"z39.50s" -- provisional ,"adiumxtra","afp","afs","aim","apt","attachment","aw" ,"beshare","bitcoin","bolo","callto","chrome","chrome-extension" ,"com-eventbrite-attendee","content","cvs","dlna-playsingle" ,"dlna-playcontainer","dtn","dvb","ed2k","facetime","feed" ,"finger","fish","gg","git","gizmoproject","gtalk" ,"hcp","icon","ipn","irc","irc6","ircs","itms","jar" ,"jms","keyparc","lastfm","ldaps","magnet","maps","market" ,"message","mms","ms-help","msnim","mumble","mvn","notes" ,"oid","palm","paparazzi","platform","proxy","psyc","query" ,"res","resource","rmi","rsync","rtmp","secondlife","sftp" ,"sgn","skype","smb","soldat","spotify","ssh","steam","svn" ,"teamspeak","things","udp","unreal","ut2004","ventrilo" ,"view-source","webcal","wtai","wyciwyg","xfire","xri" ,"ymsgr" ] -- Make them a set for more efficient lookup. schemeSet :: Set.Set Text schemeSet = Set.fromList $ schemes ++ map T.toUpper schemes -- Parse a URI, using heuristics to avoid capturing final punctuation. pUri :: Text -> Parser Inlines pUri scheme = do char ':' x <- scan (OpenParens 0) uriScanner guard $ not $ T.null x let (rawuri, endingpunct) = case T.last x of c | c `elem` (".;?!:," :: String) -> (scheme <> ":" <> T.init x, singleton (Str (T.singleton c))) _ -> (scheme <> ":" <> x, mempty) return $ autoLink rawuri <> endingpunct -- Scan non-ascii characters and ascii characters allowed in a URI. -- We allow punctuation except when followed by a space, since -- we don't want the trailing '.' in 'http://google.com.' -- We want to allow -- http://en.wikipedia.org/wiki/State_of_emergency_(disambiguation) -- as a URL, while NOT picking up the closing paren in -- (http://wikipedia.org) -- So we include balanced parens in the URL. data OpenParens = OpenParens Int uriScanner :: OpenParens -> Char -> Maybe OpenParens uriScanner _ ' ' = Nothing uriScanner _ '\n' = Nothing uriScanner (OpenParens n) '(' = Just (OpenParens (n + 1)) uriScanner (OpenParens n) ')' | n > 0 = Just (OpenParens (n - 1)) | otherwise = Nothing uriScanner st '+' = Just st uriScanner st '/' = Just st uriScanner _ c | isSpace c = Nothing uriScanner st _ = Just st -- Parses material enclosed in *s, **s, _s, or __s. -- Designed to avoid backtracking. pEnclosure :: Char -> ReferenceMap -> Parser Inlines pEnclosure c refmap = do cs <- takeWhile1 (== c) (Str cs <|) <$> pSpace <|> case T.length cs of 3 -> pThree c refmap 2 -> pTwo c refmap mempty 1 -> pOne c refmap mempty _ -> return (singleton $ Str cs) -- singleton sequence or empty if contents are empty single :: (Inlines -> Inline) -> Inlines -> Inlines single constructor ils = if Seq.null ils then mempty else singleton (constructor ils) -- parse inlines til you hit a c, and emit Emph. -- if you never hit a c, emit '*' + inlines parsed. pOne :: Char -> ReferenceMap -> Inlines -> Parser Inlines pOne c refmap prefix = do contents <- msum <$> many ( (nfbChar c >> pInline refmap) <|> (string (T.pack [c,c]) >> nfbChar c >> pTwo c refmap mempty) ) (char c >> return (single Emph $ prefix <> contents)) <|> return (singleton (Str (T.singleton c)) <> (prefix <> contents)) -- parse inlines til you hit two c's, and emit Strong. -- if you never do hit two c's, emit '**' plus + inlines parsed. pTwo :: Char -> ReferenceMap -> Inlines -> Parser Inlines pTwo c refmap prefix = do let ender = string $ T.pack [c,c] contents <- msum <$> many (nfb ender >> pInline refmap) (ender >> return (single Strong $ prefix <> contents)) <|> return (singleton (Str $ T.pack [c,c]) <> (prefix <> contents)) -- parse inlines til you hit one c or a sequence of two c's. -- If one c, emit Emph and then parse pTwo. -- if two c's, emit Strong and then parse pOne. pThree :: Char -> ReferenceMap -> Parser Inlines pThree c refmap = do contents <- msum <$> (many (nfbChar c >> pInline refmap)) (string (T.pack [c,c]) >> (pOne c refmap (single Strong contents))) <|> (char c >> (pTwo c refmap (single Emph contents))) <|> return (singleton (Str $ T.pack [c,c,c]) <> contents) -- Inline code span. pCode :: Parser Inlines pCode = fst <$> pCode' -- this is factored out because it needed in pLinkLabel. pCode' :: Parser (Inlines, Text) pCode' = do ticks <- takeWhile1 (== '`') let end = string ticks >> nfb (char '`') let nonBacktickSpan = takeWhile1 (/= '`') let backtickSpan = takeWhile1 (== '`') contents <- T.concat <$> manyTill (nonBacktickSpan <|> backtickSpan) end return (singleton . Code . T.strip $ contents, ticks <> contents <> ticks) pLink :: ReferenceMap -> Parser Inlines pLink refmap = do lab <- pLinkLabel let lab' = parseInlines refmap lab pInlineLink lab' <|> pReferenceLink refmap lab lab' -- fallback without backtracking if it's not a link: <|> return (singleton (Str "[") <> lab' <> singleton (Str "]")) -- An inline link: [label](/url "optional title") pInlineLink :: Inlines -> Parser Inlines pInlineLink lab = do char '(' scanSpaces url <- pLinkUrl tit <- option "" $ scanSpnl *> pLinkTitle <* scanSpaces char ')' return $ singleton $ Link lab (Url url) tit lookupLinkReference :: ReferenceMap -> Text -- reference label -> Maybe (Text, Text) -- (url, title) lookupLinkReference refmap key = M.lookup (normalizeReference key) refmap -- A reference link: [label], [foo][label], or [label][]. pReferenceLink :: ReferenceMap -> Text -> Inlines -> Parser Inlines pReferenceLink _ rawlab lab = do ref <- option rawlab $ scanSpnl >> pLinkLabel return $ singleton $ Link lab (Ref ref) "" -- An image: ! followed by a link. pImage :: ReferenceMap -> Parser Inlines pImage refmap = do char '!' (linkToImage <$> pLink refmap) <|> return (singleton (Str "!")) linkToImage :: Inlines -> Inlines linkToImage ils = case viewl ils of (Link lab (Url url) tit :< x) | Seq.null x -> singleton (Image lab url tit) _ -> singleton (Str "!") <> ils -- An entity. We store these in a special inline element. -- This ensures that entities in the input come out as -- entities in the output. Alternatively we could simply -- convert them to characters and store them as Str inlines. pEntity :: Parser Inlines pEntity = do char '&' res <- pCharEntity <|> pDecEntity <|> pHexEntity char ';' return $ singleton $ Entity $ "&" <> res <> ";" pCharEntity :: Parser Text pCharEntity = takeWhile1 (\c -> isAscii c && isLetter c) pDecEntity :: Parser Text pDecEntity = do char '#' res <- takeWhile1 isDigit return $ "#" <> res pHexEntity :: Parser Text pHexEntity = do char '#' x <- char 'X' <|> char 'x' res <- takeWhile1 isHexDigit return $ "#" <> T.singleton x <> res -- Raw HTML tag or comment. pRawHtml :: Parser Inlines pRawHtml = singleton . RawHtml <$> (snd <$> pHtmlTag <|> pHtmlComment) -- A link like this: <http://whatever.com> or <me@mydomain.edu>. -- Markdown.pl does email obfuscation; we don't bother with that here. pAutolink :: Parser Inlines pAutolink = do skip (=='<') s <- takeWhile1 (\c -> c /= ':' && c /= '@') rest <- takeWhile1 (\c -> c /='>' && c /= ' ') skip (=='>') case True of _ | "@" `T.isPrefixOf` rest -> return $ emailLink (s <> rest) | s `Set.member` schemeSet -> return $ autoLink (s <> rest) | otherwise -> fail "Unknown contents of <>" autoLink :: Text -> Inlines autoLink t = singleton $ Link (toInlines t) (Url t) (T.empty) where toInlines t' = case parse pToInlines t' of Right r -> r Left e -> error $ "autolink: " ++ show e pToInlines = mconcat <$> many strOrEntity strOrEntity = ((singleton . Str) <$> takeWhile1 (/='&')) <|> pEntity <|> ((singleton . Str) <$> string "&") emailLink :: Text -> Inlines emailLink t = singleton $ Link (singleton $ Str t) (Url $ "mailto:" <> t) (T.empty)
nukisman/elm-format-short
markdown/Cheapskate/Inlines.hs
Haskell
bsd-3-clause
16,282
main :: IO () main = print $ sum [1..100] ^ 2 - sum (map (^ 2) [1..100])
jaredks/euler
006/006.hs
Haskell
bsd-3-clause
73
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.Compatibility30 -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.Compatibility30 ( -- * Types GLbitfield, GLboolean, GLbyte, GLchar, GLclampd, GLclampf, GLdouble, GLenum, GLfloat, GLhalf, GLint, GLintptr, GLshort, GLsizei, GLsizeiptr, GLubyte, GLuint, GLushort, GLvoid, -- * Enums pattern GL_2D, pattern GL_2_BYTES, pattern GL_3D, pattern GL_3D_COLOR, pattern GL_3D_COLOR_TEXTURE, pattern GL_3_BYTES, pattern GL_4D_COLOR_TEXTURE, pattern GL_4_BYTES, pattern GL_ACCUM, pattern GL_ACCUM_ALPHA_BITS, pattern GL_ACCUM_BLUE_BITS, pattern GL_ACCUM_BUFFER_BIT, pattern GL_ACCUM_CLEAR_VALUE, pattern GL_ACCUM_GREEN_BITS, pattern GL_ACCUM_RED_BITS, pattern GL_ACTIVE_ATTRIBUTES, pattern GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, pattern GL_ACTIVE_TEXTURE, pattern GL_ACTIVE_UNIFORMS, pattern GL_ACTIVE_UNIFORM_MAX_LENGTH, pattern GL_ADD, pattern GL_ADD_SIGNED, pattern GL_ALIASED_LINE_WIDTH_RANGE, pattern GL_ALIASED_POINT_SIZE_RANGE, pattern GL_ALL_ATTRIB_BITS, pattern GL_ALPHA, pattern GL_ALPHA12, pattern GL_ALPHA16, pattern GL_ALPHA4, pattern GL_ALPHA8, pattern GL_ALPHA_BIAS, pattern GL_ALPHA_BITS, pattern GL_ALPHA_INTEGER, pattern GL_ALPHA_SCALE, pattern GL_ALPHA_TEST, pattern GL_ALPHA_TEST_FUNC, pattern GL_ALPHA_TEST_REF, pattern GL_ALWAYS, pattern GL_AMBIENT, pattern GL_AMBIENT_AND_DIFFUSE, pattern GL_AND, pattern GL_AND_INVERTED, pattern GL_AND_REVERSE, pattern GL_ARRAY_BUFFER, pattern GL_ARRAY_BUFFER_BINDING, pattern GL_ATTACHED_SHADERS, pattern GL_ATTRIB_STACK_DEPTH, pattern GL_AUTO_NORMAL, pattern GL_AUX0, pattern GL_AUX1, pattern GL_AUX2, pattern GL_AUX3, pattern GL_AUX_BUFFERS, pattern GL_BACK, pattern GL_BACK_LEFT, pattern GL_BACK_RIGHT, pattern GL_BGR, pattern GL_BGRA, pattern GL_BGRA_INTEGER, pattern GL_BGR_INTEGER, pattern GL_BITMAP, pattern GL_BITMAP_TOKEN, pattern GL_BLEND, pattern GL_BLEND_COLOR, pattern GL_BLEND_DST, pattern GL_BLEND_DST_ALPHA, pattern GL_BLEND_DST_RGB, pattern GL_BLEND_EQUATION, pattern GL_BLEND_EQUATION_ALPHA, pattern GL_BLEND_EQUATION_RGB, pattern GL_BLEND_SRC, pattern GL_BLEND_SRC_ALPHA, pattern GL_BLEND_SRC_RGB, pattern GL_BLUE, pattern GL_BLUE_BIAS, pattern GL_BLUE_BITS, pattern GL_BLUE_INTEGER, pattern GL_BLUE_SCALE, pattern GL_BOOL, pattern GL_BOOL_VEC2, pattern GL_BOOL_VEC3, pattern GL_BOOL_VEC4, pattern GL_BUFFER_ACCESS, pattern GL_BUFFER_ACCESS_FLAGS, pattern GL_BUFFER_MAPPED, pattern GL_BUFFER_MAP_LENGTH, pattern GL_BUFFER_MAP_OFFSET, pattern GL_BUFFER_MAP_POINTER, pattern GL_BUFFER_SIZE, pattern GL_BUFFER_USAGE, pattern GL_BYTE, pattern GL_C3F_V3F, pattern GL_C4F_N3F_V3F, pattern GL_C4UB_V2F, pattern GL_C4UB_V3F, pattern GL_CCW, pattern GL_CLAMP, pattern GL_CLAMP_FRAGMENT_COLOR, pattern GL_CLAMP_READ_COLOR, pattern GL_CLAMP_TO_BORDER, pattern GL_CLAMP_TO_EDGE, pattern GL_CLAMP_VERTEX_COLOR, pattern GL_CLEAR, pattern GL_CLIENT_ACTIVE_TEXTURE, pattern GL_CLIENT_ALL_ATTRIB_BITS, pattern GL_CLIENT_ATTRIB_STACK_DEPTH, pattern GL_CLIENT_PIXEL_STORE_BIT, pattern GL_CLIENT_VERTEX_ARRAY_BIT, pattern GL_CLIP_DISTANCE0, pattern GL_CLIP_DISTANCE1, pattern GL_CLIP_DISTANCE2, pattern GL_CLIP_DISTANCE3, pattern GL_CLIP_DISTANCE4, pattern GL_CLIP_DISTANCE5, pattern GL_CLIP_DISTANCE6, pattern GL_CLIP_DISTANCE7, pattern GL_CLIP_PLANE0, pattern GL_CLIP_PLANE1, pattern GL_CLIP_PLANE2, pattern GL_CLIP_PLANE3, pattern GL_CLIP_PLANE4, pattern GL_CLIP_PLANE5, pattern GL_COEFF, pattern GL_COLOR, pattern GL_COLOR_ARRAY, pattern GL_COLOR_ARRAY_BUFFER_BINDING, pattern GL_COLOR_ARRAY_POINTER, pattern GL_COLOR_ARRAY_SIZE, pattern GL_COLOR_ARRAY_STRIDE, pattern GL_COLOR_ARRAY_TYPE, pattern GL_COLOR_ATTACHMENT0, pattern GL_COLOR_ATTACHMENT1, pattern GL_COLOR_ATTACHMENT10, pattern GL_COLOR_ATTACHMENT11, pattern GL_COLOR_ATTACHMENT12, pattern GL_COLOR_ATTACHMENT13, pattern GL_COLOR_ATTACHMENT14, pattern GL_COLOR_ATTACHMENT15, pattern GL_COLOR_ATTACHMENT16, pattern GL_COLOR_ATTACHMENT17, pattern GL_COLOR_ATTACHMENT18, pattern GL_COLOR_ATTACHMENT19, pattern GL_COLOR_ATTACHMENT2, pattern GL_COLOR_ATTACHMENT20, pattern GL_COLOR_ATTACHMENT21, pattern GL_COLOR_ATTACHMENT22, pattern GL_COLOR_ATTACHMENT23, pattern GL_COLOR_ATTACHMENT24, pattern GL_COLOR_ATTACHMENT25, pattern GL_COLOR_ATTACHMENT26, pattern GL_COLOR_ATTACHMENT27, pattern GL_COLOR_ATTACHMENT28, pattern GL_COLOR_ATTACHMENT29, pattern GL_COLOR_ATTACHMENT3, pattern GL_COLOR_ATTACHMENT30, pattern GL_COLOR_ATTACHMENT31, pattern GL_COLOR_ATTACHMENT4, pattern GL_COLOR_ATTACHMENT5, pattern GL_COLOR_ATTACHMENT6, pattern GL_COLOR_ATTACHMENT7, pattern GL_COLOR_ATTACHMENT8, pattern GL_COLOR_ATTACHMENT9, pattern GL_COLOR_BUFFER_BIT, pattern GL_COLOR_CLEAR_VALUE, pattern GL_COLOR_INDEX, pattern GL_COLOR_INDEXES, pattern GL_COLOR_LOGIC_OP, pattern GL_COLOR_MATERIAL, pattern GL_COLOR_MATERIAL_FACE, pattern GL_COLOR_MATERIAL_PARAMETER, pattern GL_COLOR_SUM, pattern GL_COLOR_WRITEMASK, pattern GL_COMBINE, pattern GL_COMBINE_ALPHA, pattern GL_COMBINE_RGB, pattern GL_COMPARE_REF_TO_TEXTURE, pattern GL_COMPARE_R_TO_TEXTURE, pattern GL_COMPILE, pattern GL_COMPILE_AND_EXECUTE, pattern GL_COMPILE_STATUS, pattern GL_COMPRESSED_ALPHA, pattern GL_COMPRESSED_INTENSITY, pattern GL_COMPRESSED_LUMINANCE, pattern GL_COMPRESSED_LUMINANCE_ALPHA, pattern GL_COMPRESSED_RED, pattern GL_COMPRESSED_RED_RGTC1, pattern GL_COMPRESSED_RG, pattern GL_COMPRESSED_RGB, pattern GL_COMPRESSED_RGBA, pattern GL_COMPRESSED_RG_RGTC2, pattern GL_COMPRESSED_SIGNED_RED_RGTC1, pattern GL_COMPRESSED_SIGNED_RG_RGTC2, pattern GL_COMPRESSED_SLUMINANCE, pattern GL_COMPRESSED_SLUMINANCE_ALPHA, pattern GL_COMPRESSED_SRGB, pattern GL_COMPRESSED_SRGB_ALPHA, pattern GL_COMPRESSED_TEXTURE_FORMATS, pattern GL_CONSTANT, pattern GL_CONSTANT_ALPHA, pattern GL_CONSTANT_ATTENUATION, pattern GL_CONSTANT_COLOR, pattern GL_CONTEXT_FLAGS, pattern GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT, pattern GL_COORD_REPLACE, pattern GL_COPY, pattern GL_COPY_INVERTED, pattern GL_COPY_PIXEL_TOKEN, pattern GL_CULL_FACE, pattern GL_CULL_FACE_MODE, pattern GL_CURRENT_BIT, pattern GL_CURRENT_COLOR, pattern GL_CURRENT_FOG_COORD, pattern GL_CURRENT_FOG_COORDINATE, pattern GL_CURRENT_INDEX, pattern GL_CURRENT_NORMAL, pattern GL_CURRENT_PROGRAM, pattern GL_CURRENT_QUERY, pattern GL_CURRENT_RASTER_COLOR, pattern GL_CURRENT_RASTER_DISTANCE, pattern GL_CURRENT_RASTER_INDEX, pattern GL_CURRENT_RASTER_POSITION, pattern GL_CURRENT_RASTER_POSITION_VALID, pattern GL_CURRENT_RASTER_SECONDARY_COLOR, pattern GL_CURRENT_RASTER_TEXTURE_COORDS, pattern GL_CURRENT_SECONDARY_COLOR, pattern GL_CURRENT_TEXTURE_COORDS, pattern GL_CURRENT_VERTEX_ATTRIB, pattern GL_CW, pattern GL_DECAL, pattern GL_DECR, pattern GL_DECR_WRAP, pattern GL_DELETE_STATUS, pattern GL_DEPTH, pattern GL_DEPTH24_STENCIL8, pattern GL_DEPTH32F_STENCIL8, pattern GL_DEPTH_ATTACHMENT, pattern GL_DEPTH_BIAS, pattern GL_DEPTH_BITS, pattern GL_DEPTH_BUFFER_BIT, pattern GL_DEPTH_CLEAR_VALUE, pattern GL_DEPTH_COMPONENT, pattern GL_DEPTH_COMPONENT16, pattern GL_DEPTH_COMPONENT24, pattern GL_DEPTH_COMPONENT32, pattern GL_DEPTH_COMPONENT32F, pattern GL_DEPTH_FUNC, pattern GL_DEPTH_RANGE, pattern GL_DEPTH_SCALE, pattern GL_DEPTH_STENCIL, pattern GL_DEPTH_STENCIL_ATTACHMENT, pattern GL_DEPTH_TEST, pattern GL_DEPTH_TEXTURE_MODE, pattern GL_DEPTH_WRITEMASK, pattern GL_DIFFUSE, pattern GL_DITHER, pattern GL_DOMAIN, pattern GL_DONT_CARE, pattern GL_DOT3_RGB, pattern GL_DOT3_RGBA, pattern GL_DOUBLE, pattern GL_DOUBLEBUFFER, pattern GL_DRAW_BUFFER, pattern GL_DRAW_BUFFER0, pattern GL_DRAW_BUFFER1, pattern GL_DRAW_BUFFER10, pattern GL_DRAW_BUFFER11, pattern GL_DRAW_BUFFER12, pattern GL_DRAW_BUFFER13, pattern GL_DRAW_BUFFER14, pattern GL_DRAW_BUFFER15, pattern GL_DRAW_BUFFER2, pattern GL_DRAW_BUFFER3, pattern GL_DRAW_BUFFER4, pattern GL_DRAW_BUFFER5, pattern GL_DRAW_BUFFER6, pattern GL_DRAW_BUFFER7, pattern GL_DRAW_BUFFER8, pattern GL_DRAW_BUFFER9, pattern GL_DRAW_FRAMEBUFFER, pattern GL_DRAW_FRAMEBUFFER_BINDING, pattern GL_DRAW_PIXEL_TOKEN, pattern GL_DST_ALPHA, pattern GL_DST_COLOR, pattern GL_DYNAMIC_COPY, pattern GL_DYNAMIC_DRAW, pattern GL_DYNAMIC_READ, pattern GL_EDGE_FLAG, pattern GL_EDGE_FLAG_ARRAY, pattern GL_EDGE_FLAG_ARRAY_BUFFER_BINDING, pattern GL_EDGE_FLAG_ARRAY_POINTER, pattern GL_EDGE_FLAG_ARRAY_STRIDE, pattern GL_ELEMENT_ARRAY_BUFFER, pattern GL_ELEMENT_ARRAY_BUFFER_BINDING, pattern GL_EMISSION, pattern GL_ENABLE_BIT, pattern GL_EQUAL, pattern GL_EQUIV, pattern GL_EVAL_BIT, pattern GL_EXP, pattern GL_EXP2, pattern GL_EXTENSIONS, pattern GL_EYE_LINEAR, pattern GL_EYE_PLANE, pattern GL_FALSE, pattern GL_FASTEST, pattern GL_FEEDBACK, pattern GL_FEEDBACK_BUFFER_POINTER, pattern GL_FEEDBACK_BUFFER_SIZE, pattern GL_FEEDBACK_BUFFER_TYPE, pattern GL_FILL, pattern GL_FIXED_ONLY, pattern GL_FLAT, pattern GL_FLOAT, pattern GL_FLOAT_32_UNSIGNED_INT_24_8_REV, pattern GL_FLOAT_MAT2, pattern GL_FLOAT_MAT2x3, pattern GL_FLOAT_MAT2x4, pattern GL_FLOAT_MAT3, pattern GL_FLOAT_MAT3x2, pattern GL_FLOAT_MAT3x4, pattern GL_FLOAT_MAT4, pattern GL_FLOAT_MAT4x2, pattern GL_FLOAT_MAT4x3, pattern GL_FLOAT_VEC2, pattern GL_FLOAT_VEC3, pattern GL_FLOAT_VEC4, pattern GL_FOG, pattern GL_FOG_BIT, pattern GL_FOG_COLOR, pattern GL_FOG_COORD, pattern GL_FOG_COORDINATE, pattern GL_FOG_COORDINATE_ARRAY, pattern GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING, pattern GL_FOG_COORDINATE_ARRAY_POINTER, pattern GL_FOG_COORDINATE_ARRAY_STRIDE, pattern GL_FOG_COORDINATE_ARRAY_TYPE, pattern GL_FOG_COORDINATE_SOURCE, pattern GL_FOG_COORD_ARRAY, pattern GL_FOG_COORD_ARRAY_BUFFER_BINDING, pattern GL_FOG_COORD_ARRAY_POINTER, pattern GL_FOG_COORD_ARRAY_STRIDE, pattern GL_FOG_COORD_ARRAY_TYPE, pattern GL_FOG_COORD_SRC, pattern GL_FOG_DENSITY, pattern GL_FOG_END, pattern GL_FOG_HINT, pattern GL_FOG_INDEX, pattern GL_FOG_MODE, pattern GL_FOG_START, pattern GL_FRAGMENT_DEPTH, pattern GL_FRAGMENT_SHADER, pattern GL_FRAGMENT_SHADER_DERIVATIVE_HINT, pattern GL_FRAMEBUFFER, pattern GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, pattern GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, pattern GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, pattern GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, pattern GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, pattern GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, pattern GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, pattern GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, pattern GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, pattern GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, pattern GL_FRAMEBUFFER_BINDING, pattern GL_FRAMEBUFFER_COMPLETE, pattern GL_FRAMEBUFFER_DEFAULT, pattern GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT, pattern GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER, pattern GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT, pattern GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE, pattern GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER, pattern GL_FRAMEBUFFER_SRGB, pattern GL_FRAMEBUFFER_UNDEFINED, pattern GL_FRAMEBUFFER_UNSUPPORTED, pattern GL_FRONT, pattern GL_FRONT_AND_BACK, pattern GL_FRONT_FACE, pattern GL_FRONT_LEFT, pattern GL_FRONT_RIGHT, pattern GL_FUNC_ADD, pattern GL_FUNC_REVERSE_SUBTRACT, pattern GL_FUNC_SUBTRACT, pattern GL_GENERATE_MIPMAP, pattern GL_GENERATE_MIPMAP_HINT, pattern GL_GEQUAL, pattern GL_GREATER, pattern GL_GREEN, pattern GL_GREEN_BIAS, pattern GL_GREEN_BITS, pattern GL_GREEN_INTEGER, pattern GL_GREEN_SCALE, pattern GL_HALF_FLOAT, pattern GL_HINT_BIT, pattern GL_INCR, pattern GL_INCR_WRAP, pattern GL_INDEX, pattern GL_INDEX_ARRAY, pattern GL_INDEX_ARRAY_BUFFER_BINDING, pattern GL_INDEX_ARRAY_POINTER, pattern GL_INDEX_ARRAY_STRIDE, pattern GL_INDEX_ARRAY_TYPE, pattern GL_INDEX_BITS, pattern GL_INDEX_CLEAR_VALUE, pattern GL_INDEX_LOGIC_OP, pattern GL_INDEX_MODE, pattern GL_INDEX_OFFSET, pattern GL_INDEX_SHIFT, pattern GL_INDEX_WRITEMASK, pattern GL_INFO_LOG_LENGTH, pattern GL_INT, pattern GL_INTENSITY, pattern GL_INTENSITY12, pattern GL_INTENSITY16, pattern GL_INTENSITY4, pattern GL_INTENSITY8, pattern GL_INTERLEAVED_ATTRIBS, pattern GL_INTERPOLATE, pattern GL_INT_SAMPLER_1D, pattern GL_INT_SAMPLER_1D_ARRAY, pattern GL_INT_SAMPLER_2D, pattern GL_INT_SAMPLER_2D_ARRAY, pattern GL_INT_SAMPLER_3D, pattern GL_INT_SAMPLER_CUBE, pattern GL_INT_VEC2, pattern GL_INT_VEC3, pattern GL_INT_VEC4, pattern GL_INVALID_ENUM, pattern GL_INVALID_FRAMEBUFFER_OPERATION, pattern GL_INVALID_OPERATION, pattern GL_INVALID_VALUE, pattern GL_INVERT, pattern GL_KEEP, pattern GL_LEFT, pattern GL_LEQUAL, pattern GL_LESS, pattern GL_LIGHT0, pattern GL_LIGHT1, pattern GL_LIGHT2, pattern GL_LIGHT3, pattern GL_LIGHT4, pattern GL_LIGHT5, pattern GL_LIGHT6, pattern GL_LIGHT7, pattern GL_LIGHTING, pattern GL_LIGHTING_BIT, pattern GL_LIGHT_MODEL_AMBIENT, pattern GL_LIGHT_MODEL_COLOR_CONTROL, pattern GL_LIGHT_MODEL_LOCAL_VIEWER, pattern GL_LIGHT_MODEL_TWO_SIDE, pattern GL_LINE, pattern GL_LINEAR, pattern GL_LINEAR_ATTENUATION, pattern GL_LINEAR_MIPMAP_LINEAR, pattern GL_LINEAR_MIPMAP_NEAREST, pattern GL_LINES, pattern GL_LINE_BIT, pattern GL_LINE_LOOP, pattern GL_LINE_RESET_TOKEN, pattern GL_LINE_SMOOTH, pattern GL_LINE_SMOOTH_HINT, pattern GL_LINE_STIPPLE, pattern GL_LINE_STIPPLE_PATTERN, pattern GL_LINE_STIPPLE_REPEAT, pattern GL_LINE_STRIP, pattern GL_LINE_TOKEN, pattern GL_LINE_WIDTH, pattern GL_LINE_WIDTH_GRANULARITY, pattern GL_LINE_WIDTH_RANGE, pattern GL_LINK_STATUS, pattern GL_LIST_BASE, pattern GL_LIST_BIT, pattern GL_LIST_INDEX, pattern GL_LIST_MODE, pattern GL_LOAD, pattern GL_LOGIC_OP, pattern GL_LOGIC_OP_MODE, pattern GL_LOWER_LEFT, pattern GL_LUMINANCE, pattern GL_LUMINANCE12, pattern GL_LUMINANCE12_ALPHA12, pattern GL_LUMINANCE12_ALPHA4, pattern GL_LUMINANCE16, pattern GL_LUMINANCE16_ALPHA16, pattern GL_LUMINANCE4, pattern GL_LUMINANCE4_ALPHA4, pattern GL_LUMINANCE6_ALPHA2, pattern GL_LUMINANCE8, pattern GL_LUMINANCE8_ALPHA8, pattern GL_LUMINANCE_ALPHA, pattern GL_MAJOR_VERSION, pattern GL_MAP1_COLOR_4, pattern GL_MAP1_GRID_DOMAIN, pattern GL_MAP1_GRID_SEGMENTS, pattern GL_MAP1_INDEX, pattern GL_MAP1_NORMAL, pattern GL_MAP1_TEXTURE_COORD_1, pattern GL_MAP1_TEXTURE_COORD_2, pattern GL_MAP1_TEXTURE_COORD_3, pattern GL_MAP1_TEXTURE_COORD_4, pattern GL_MAP1_VERTEX_3, pattern GL_MAP1_VERTEX_4, pattern GL_MAP2_COLOR_4, pattern GL_MAP2_GRID_DOMAIN, pattern GL_MAP2_GRID_SEGMENTS, pattern GL_MAP2_INDEX, pattern GL_MAP2_NORMAL, pattern GL_MAP2_TEXTURE_COORD_1, pattern GL_MAP2_TEXTURE_COORD_2, pattern GL_MAP2_TEXTURE_COORD_3, pattern GL_MAP2_TEXTURE_COORD_4, pattern GL_MAP2_VERTEX_3, pattern GL_MAP2_VERTEX_4, pattern GL_MAP_COLOR, pattern GL_MAP_FLUSH_EXPLICIT_BIT, pattern GL_MAP_INVALIDATE_BUFFER_BIT, pattern GL_MAP_INVALIDATE_RANGE_BIT, pattern GL_MAP_READ_BIT, pattern GL_MAP_STENCIL, pattern GL_MAP_UNSYNCHRONIZED_BIT, pattern GL_MAP_WRITE_BIT, pattern GL_MATRIX_MODE, pattern GL_MAX, pattern GL_MAX_3D_TEXTURE_SIZE, pattern GL_MAX_ARRAY_TEXTURE_LAYERS, pattern GL_MAX_ATTRIB_STACK_DEPTH, pattern GL_MAX_CLIENT_ATTRIB_STACK_DEPTH, pattern GL_MAX_CLIP_DISTANCES, pattern GL_MAX_CLIP_PLANES, pattern GL_MAX_COLOR_ATTACHMENTS, pattern GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, pattern GL_MAX_CUBE_MAP_TEXTURE_SIZE, pattern GL_MAX_DRAW_BUFFERS, pattern GL_MAX_ELEMENTS_INDICES, pattern GL_MAX_ELEMENTS_VERTICES, pattern GL_MAX_EVAL_ORDER, pattern GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, pattern GL_MAX_LIGHTS, pattern GL_MAX_LIST_NESTING, pattern GL_MAX_MODELVIEW_STACK_DEPTH, pattern GL_MAX_NAME_STACK_DEPTH, pattern GL_MAX_PIXEL_MAP_TABLE, pattern GL_MAX_PROGRAM_TEXEL_OFFSET, pattern GL_MAX_PROJECTION_STACK_DEPTH, pattern GL_MAX_RENDERBUFFER_SIZE, pattern GL_MAX_SAMPLES, pattern GL_MAX_TEXTURE_COORDS, pattern GL_MAX_TEXTURE_IMAGE_UNITS, pattern GL_MAX_TEXTURE_LOD_BIAS, pattern GL_MAX_TEXTURE_SIZE, pattern GL_MAX_TEXTURE_STACK_DEPTH, pattern GL_MAX_TEXTURE_UNITS, pattern GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, pattern GL_MAX_VARYING_COMPONENTS, pattern GL_MAX_VARYING_FLOATS, pattern GL_MAX_VERTEX_ATTRIBS, pattern GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, pattern GL_MAX_VERTEX_UNIFORM_COMPONENTS, pattern GL_MAX_VIEWPORT_DIMS, pattern GL_MIN, pattern GL_MINOR_VERSION, pattern GL_MIN_PROGRAM_TEXEL_OFFSET, pattern GL_MIRRORED_REPEAT, pattern GL_MODELVIEW, pattern GL_MODELVIEW_MATRIX, pattern GL_MODELVIEW_STACK_DEPTH, pattern GL_MODULATE, pattern GL_MULT, pattern GL_MULTISAMPLE, pattern GL_MULTISAMPLE_BIT, pattern GL_N3F_V3F, pattern GL_NAME_STACK_DEPTH, pattern GL_NAND, pattern GL_NEAREST, pattern GL_NEAREST_MIPMAP_LINEAR, pattern GL_NEAREST_MIPMAP_NEAREST, pattern GL_NEVER, pattern GL_NICEST, pattern GL_NONE, pattern GL_NOOP, pattern GL_NOR, pattern GL_NORMALIZE, pattern GL_NORMAL_ARRAY, pattern GL_NORMAL_ARRAY_BUFFER_BINDING, pattern GL_NORMAL_ARRAY_POINTER, pattern GL_NORMAL_ARRAY_STRIDE, pattern GL_NORMAL_ARRAY_TYPE, pattern GL_NORMAL_MAP, pattern GL_NOTEQUAL, pattern GL_NO_ERROR, pattern GL_NUM_COMPRESSED_TEXTURE_FORMATS, pattern GL_NUM_EXTENSIONS, pattern GL_OBJECT_LINEAR, pattern GL_OBJECT_PLANE, pattern GL_ONE, pattern GL_ONE_MINUS_CONSTANT_ALPHA, pattern GL_ONE_MINUS_CONSTANT_COLOR, pattern GL_ONE_MINUS_DST_ALPHA, pattern GL_ONE_MINUS_DST_COLOR, pattern GL_ONE_MINUS_SRC_ALPHA, pattern GL_ONE_MINUS_SRC_COLOR, pattern GL_OPERAND0_ALPHA, pattern GL_OPERAND0_RGB, pattern GL_OPERAND1_ALPHA, pattern GL_OPERAND1_RGB, pattern GL_OPERAND2_ALPHA, pattern GL_OPERAND2_RGB, pattern GL_OR, pattern GL_ORDER, pattern GL_OR_INVERTED, pattern GL_OR_REVERSE, pattern GL_OUT_OF_MEMORY, pattern GL_PACK_ALIGNMENT, pattern GL_PACK_IMAGE_HEIGHT, pattern GL_PACK_LSB_FIRST, pattern GL_PACK_ROW_LENGTH, pattern GL_PACK_SKIP_IMAGES, pattern GL_PACK_SKIP_PIXELS, pattern GL_PACK_SKIP_ROWS, pattern GL_PACK_SWAP_BYTES, pattern GL_PASS_THROUGH_TOKEN, pattern GL_PERSPECTIVE_CORRECTION_HINT, pattern GL_PIXEL_MAP_A_TO_A, pattern GL_PIXEL_MAP_A_TO_A_SIZE, pattern GL_PIXEL_MAP_B_TO_B, pattern GL_PIXEL_MAP_B_TO_B_SIZE, pattern GL_PIXEL_MAP_G_TO_G, pattern GL_PIXEL_MAP_G_TO_G_SIZE, pattern GL_PIXEL_MAP_I_TO_A, pattern GL_PIXEL_MAP_I_TO_A_SIZE, pattern GL_PIXEL_MAP_I_TO_B, pattern GL_PIXEL_MAP_I_TO_B_SIZE, pattern GL_PIXEL_MAP_I_TO_G, pattern GL_PIXEL_MAP_I_TO_G_SIZE, pattern GL_PIXEL_MAP_I_TO_I, pattern GL_PIXEL_MAP_I_TO_I_SIZE, pattern GL_PIXEL_MAP_I_TO_R, pattern GL_PIXEL_MAP_I_TO_R_SIZE, pattern GL_PIXEL_MAP_R_TO_R, pattern GL_PIXEL_MAP_R_TO_R_SIZE, pattern GL_PIXEL_MAP_S_TO_S, pattern GL_PIXEL_MAP_S_TO_S_SIZE, pattern GL_PIXEL_MODE_BIT, pattern GL_PIXEL_PACK_BUFFER, pattern GL_PIXEL_PACK_BUFFER_BINDING, pattern GL_PIXEL_UNPACK_BUFFER, pattern GL_PIXEL_UNPACK_BUFFER_BINDING, pattern GL_POINT, pattern GL_POINTS, pattern GL_POINT_BIT, pattern GL_POINT_DISTANCE_ATTENUATION, pattern GL_POINT_FADE_THRESHOLD_SIZE, pattern GL_POINT_SIZE, pattern GL_POINT_SIZE_GRANULARITY, pattern GL_POINT_SIZE_MAX, pattern GL_POINT_SIZE_MIN, pattern GL_POINT_SIZE_RANGE, pattern GL_POINT_SMOOTH, pattern GL_POINT_SMOOTH_HINT, pattern GL_POINT_SPRITE, pattern GL_POINT_SPRITE_COORD_ORIGIN, pattern GL_POINT_TOKEN, pattern GL_POLYGON, pattern GL_POLYGON_BIT, pattern GL_POLYGON_MODE, pattern GL_POLYGON_OFFSET_FACTOR, pattern GL_POLYGON_OFFSET_FILL, pattern GL_POLYGON_OFFSET_LINE, pattern GL_POLYGON_OFFSET_POINT, pattern GL_POLYGON_OFFSET_UNITS, pattern GL_POLYGON_SMOOTH, pattern GL_POLYGON_SMOOTH_HINT, pattern GL_POLYGON_STIPPLE, pattern GL_POLYGON_STIPPLE_BIT, pattern GL_POLYGON_TOKEN, pattern GL_POSITION, pattern GL_PREVIOUS, pattern GL_PRIMARY_COLOR, pattern GL_PRIMITIVES_GENERATED, pattern GL_PROJECTION, pattern GL_PROJECTION_MATRIX, pattern GL_PROJECTION_STACK_DEPTH, pattern GL_PROXY_TEXTURE_1D, pattern GL_PROXY_TEXTURE_1D_ARRAY, pattern GL_PROXY_TEXTURE_2D, pattern GL_PROXY_TEXTURE_2D_ARRAY, pattern GL_PROXY_TEXTURE_3D, pattern GL_PROXY_TEXTURE_CUBE_MAP, pattern GL_Q, pattern GL_QUADRATIC_ATTENUATION, pattern GL_QUADS, pattern GL_QUAD_STRIP, pattern GL_QUERY_BY_REGION_NO_WAIT, pattern GL_QUERY_BY_REGION_WAIT, pattern GL_QUERY_COUNTER_BITS, pattern GL_QUERY_NO_WAIT, pattern GL_QUERY_RESULT, pattern GL_QUERY_RESULT_AVAILABLE, pattern GL_QUERY_WAIT, pattern GL_R, pattern GL_R11F_G11F_B10F, pattern GL_R16, pattern GL_R16F, pattern GL_R16I, pattern GL_R16UI, pattern GL_R32F, pattern GL_R32I, pattern GL_R32UI, pattern GL_R3_G3_B2, pattern GL_R8, pattern GL_R8I, pattern GL_R8UI, pattern GL_RASTERIZER_DISCARD, pattern GL_READ_BUFFER, pattern GL_READ_FRAMEBUFFER, pattern GL_READ_FRAMEBUFFER_BINDING, pattern GL_READ_ONLY, pattern GL_READ_WRITE, pattern GL_RED, pattern GL_RED_BIAS, pattern GL_RED_BITS, pattern GL_RED_INTEGER, pattern GL_RED_SCALE, pattern GL_REFLECTION_MAP, pattern GL_RENDER, pattern GL_RENDERBUFFER, pattern GL_RENDERBUFFER_ALPHA_SIZE, pattern GL_RENDERBUFFER_BINDING, pattern GL_RENDERBUFFER_BLUE_SIZE, pattern GL_RENDERBUFFER_DEPTH_SIZE, pattern GL_RENDERBUFFER_GREEN_SIZE, pattern GL_RENDERBUFFER_HEIGHT, pattern GL_RENDERBUFFER_INTERNAL_FORMAT, pattern GL_RENDERBUFFER_RED_SIZE, pattern GL_RENDERBUFFER_SAMPLES, pattern GL_RENDERBUFFER_STENCIL_SIZE, pattern GL_RENDERBUFFER_WIDTH, pattern GL_RENDERER, pattern GL_RENDER_MODE, pattern GL_REPEAT, pattern GL_REPLACE, pattern GL_RESCALE_NORMAL, pattern GL_RETURN, pattern GL_RG, pattern GL_RG16, pattern GL_RG16F, pattern GL_RG16I, pattern GL_RG16UI, pattern GL_RG32F, pattern GL_RG32I, pattern GL_RG32UI, pattern GL_RG8, pattern GL_RG8I, pattern GL_RG8UI, pattern GL_RGB, pattern GL_RGB10, pattern GL_RGB10_A2, pattern GL_RGB12, pattern GL_RGB16, pattern GL_RGB16F, pattern GL_RGB16I, pattern GL_RGB16UI, pattern GL_RGB32F, pattern GL_RGB32I, pattern GL_RGB32UI, pattern GL_RGB4, pattern GL_RGB5, pattern GL_RGB5_A1, pattern GL_RGB8, pattern GL_RGB8I, pattern GL_RGB8UI, pattern GL_RGB9_E5, pattern GL_RGBA, pattern GL_RGBA12, pattern GL_RGBA16, pattern GL_RGBA16F, pattern GL_RGBA16I, pattern GL_RGBA16UI, pattern GL_RGBA2, pattern GL_RGBA32F, pattern GL_RGBA32I, pattern GL_RGBA32UI, pattern GL_RGBA4, pattern GL_RGBA8, pattern GL_RGBA8I, pattern GL_RGBA8UI, pattern GL_RGBA_INTEGER, pattern GL_RGBA_MODE, pattern GL_RGB_INTEGER, pattern GL_RGB_SCALE, pattern GL_RG_INTEGER, pattern GL_RIGHT, pattern GL_S, pattern GL_SAMPLER_1D, pattern GL_SAMPLER_1D_ARRAY, pattern GL_SAMPLER_1D_ARRAY_SHADOW, pattern GL_SAMPLER_1D_SHADOW, pattern GL_SAMPLER_2D, pattern GL_SAMPLER_2D_ARRAY, pattern GL_SAMPLER_2D_ARRAY_SHADOW, pattern GL_SAMPLER_2D_SHADOW, pattern GL_SAMPLER_3D, pattern GL_SAMPLER_CUBE, pattern GL_SAMPLER_CUBE_SHADOW, pattern GL_SAMPLES, pattern GL_SAMPLES_PASSED, pattern GL_SAMPLE_ALPHA_TO_COVERAGE, pattern GL_SAMPLE_ALPHA_TO_ONE, pattern GL_SAMPLE_BUFFERS, pattern GL_SAMPLE_COVERAGE, pattern GL_SAMPLE_COVERAGE_INVERT, pattern GL_SAMPLE_COVERAGE_VALUE, pattern GL_SCISSOR_BIT, pattern GL_SCISSOR_BOX, pattern GL_SCISSOR_TEST, pattern GL_SECONDARY_COLOR_ARRAY, pattern GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING, pattern GL_SECONDARY_COLOR_ARRAY_POINTER, pattern GL_SECONDARY_COLOR_ARRAY_SIZE, pattern GL_SECONDARY_COLOR_ARRAY_STRIDE, pattern GL_SECONDARY_COLOR_ARRAY_TYPE, pattern GL_SELECT, pattern GL_SELECTION_BUFFER_POINTER, pattern GL_SELECTION_BUFFER_SIZE, pattern GL_SEPARATE_ATTRIBS, pattern GL_SEPARATE_SPECULAR_COLOR, pattern GL_SET, pattern GL_SHADER_SOURCE_LENGTH, pattern GL_SHADER_TYPE, pattern GL_SHADE_MODEL, pattern GL_SHADING_LANGUAGE_VERSION, pattern GL_SHININESS, pattern GL_SHORT, pattern GL_SINGLE_COLOR, pattern GL_SLUMINANCE, pattern GL_SLUMINANCE8, pattern GL_SLUMINANCE8_ALPHA8, pattern GL_SLUMINANCE_ALPHA, pattern GL_SMOOTH, pattern GL_SMOOTH_LINE_WIDTH_GRANULARITY, pattern GL_SMOOTH_LINE_WIDTH_RANGE, pattern GL_SMOOTH_POINT_SIZE_GRANULARITY, pattern GL_SMOOTH_POINT_SIZE_RANGE, pattern GL_SOURCE0_ALPHA, pattern GL_SOURCE0_RGB, pattern GL_SOURCE1_ALPHA, pattern GL_SOURCE1_RGB, pattern GL_SOURCE2_ALPHA, pattern GL_SOURCE2_RGB, pattern GL_SPECULAR, pattern GL_SPHERE_MAP, pattern GL_SPOT_CUTOFF, pattern GL_SPOT_DIRECTION, pattern GL_SPOT_EXPONENT, pattern GL_SRC0_ALPHA, pattern GL_SRC0_RGB, pattern GL_SRC1_ALPHA, pattern GL_SRC1_RGB, pattern GL_SRC2_ALPHA, pattern GL_SRC2_RGB, pattern GL_SRC_ALPHA, pattern GL_SRC_ALPHA_SATURATE, pattern GL_SRC_COLOR, pattern GL_SRGB, pattern GL_SRGB8, pattern GL_SRGB8_ALPHA8, pattern GL_SRGB_ALPHA, pattern GL_STACK_OVERFLOW, pattern GL_STACK_UNDERFLOW, pattern GL_STATIC_COPY, pattern GL_STATIC_DRAW, pattern GL_STATIC_READ, pattern GL_STENCIL, pattern GL_STENCIL_ATTACHMENT, pattern GL_STENCIL_BACK_FAIL, pattern GL_STENCIL_BACK_FUNC, pattern GL_STENCIL_BACK_PASS_DEPTH_FAIL, pattern GL_STENCIL_BACK_PASS_DEPTH_PASS, pattern GL_STENCIL_BACK_REF, pattern GL_STENCIL_BACK_VALUE_MASK, pattern GL_STENCIL_BACK_WRITEMASK, pattern GL_STENCIL_BITS, pattern GL_STENCIL_BUFFER_BIT, pattern GL_STENCIL_CLEAR_VALUE, pattern GL_STENCIL_FAIL, pattern GL_STENCIL_FUNC, pattern GL_STENCIL_INDEX, pattern GL_STENCIL_INDEX1, pattern GL_STENCIL_INDEX16, pattern GL_STENCIL_INDEX4, pattern GL_STENCIL_INDEX8, pattern GL_STENCIL_PASS_DEPTH_FAIL, pattern GL_STENCIL_PASS_DEPTH_PASS, pattern GL_STENCIL_REF, pattern GL_STENCIL_TEST, pattern GL_STENCIL_VALUE_MASK, pattern GL_STENCIL_WRITEMASK, pattern GL_STEREO, pattern GL_STREAM_COPY, pattern GL_STREAM_DRAW, pattern GL_STREAM_READ, pattern GL_SUBPIXEL_BITS, pattern GL_SUBTRACT, pattern GL_T, pattern GL_T2F_C3F_V3F, pattern GL_T2F_C4F_N3F_V3F, pattern GL_T2F_C4UB_V3F, pattern GL_T2F_N3F_V3F, pattern GL_T2F_V3F, pattern GL_T4F_C4F_N3F_V4F, pattern GL_T4F_V4F, pattern GL_TEXTURE, pattern GL_TEXTURE0, pattern GL_TEXTURE1, pattern GL_TEXTURE10, pattern GL_TEXTURE11, pattern GL_TEXTURE12, pattern GL_TEXTURE13, pattern GL_TEXTURE14, pattern GL_TEXTURE15, pattern GL_TEXTURE16, pattern GL_TEXTURE17, pattern GL_TEXTURE18, pattern GL_TEXTURE19, pattern GL_TEXTURE2, pattern GL_TEXTURE20, pattern GL_TEXTURE21, pattern GL_TEXTURE22, pattern GL_TEXTURE23, pattern GL_TEXTURE24, pattern GL_TEXTURE25, pattern GL_TEXTURE26, pattern GL_TEXTURE27, pattern GL_TEXTURE28, pattern GL_TEXTURE29, pattern GL_TEXTURE3, pattern GL_TEXTURE30, pattern GL_TEXTURE31, pattern GL_TEXTURE4, pattern GL_TEXTURE5, pattern GL_TEXTURE6, pattern GL_TEXTURE7, pattern GL_TEXTURE8, pattern GL_TEXTURE9, pattern GL_TEXTURE_1D, pattern GL_TEXTURE_1D_ARRAY, pattern GL_TEXTURE_2D, pattern GL_TEXTURE_2D_ARRAY, pattern GL_TEXTURE_3D, pattern GL_TEXTURE_ALPHA_SIZE, pattern GL_TEXTURE_ALPHA_TYPE, pattern GL_TEXTURE_BASE_LEVEL, pattern GL_TEXTURE_BINDING_1D, pattern GL_TEXTURE_BINDING_1D_ARRAY, pattern GL_TEXTURE_BINDING_2D, pattern GL_TEXTURE_BINDING_2D_ARRAY, pattern GL_TEXTURE_BINDING_3D, pattern GL_TEXTURE_BINDING_CUBE_MAP, pattern GL_TEXTURE_BIT, pattern GL_TEXTURE_BLUE_SIZE, pattern GL_TEXTURE_BLUE_TYPE, pattern GL_TEXTURE_BORDER, pattern GL_TEXTURE_BORDER_COLOR, pattern GL_TEXTURE_COMPARE_FUNC, pattern GL_TEXTURE_COMPARE_MODE, pattern GL_TEXTURE_COMPONENTS, pattern GL_TEXTURE_COMPRESSED, pattern GL_TEXTURE_COMPRESSED_IMAGE_SIZE, pattern GL_TEXTURE_COMPRESSION_HINT, pattern GL_TEXTURE_COORD_ARRAY, pattern GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING, pattern GL_TEXTURE_COORD_ARRAY_POINTER, pattern GL_TEXTURE_COORD_ARRAY_SIZE, pattern GL_TEXTURE_COORD_ARRAY_STRIDE, pattern GL_TEXTURE_COORD_ARRAY_TYPE, pattern GL_TEXTURE_CUBE_MAP, pattern GL_TEXTURE_CUBE_MAP_NEGATIVE_X, pattern GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, pattern GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, pattern GL_TEXTURE_CUBE_MAP_POSITIVE_X, pattern GL_TEXTURE_CUBE_MAP_POSITIVE_Y, pattern GL_TEXTURE_CUBE_MAP_POSITIVE_Z, pattern GL_TEXTURE_DEPTH, pattern GL_TEXTURE_DEPTH_SIZE, pattern GL_TEXTURE_DEPTH_TYPE, pattern GL_TEXTURE_ENV, pattern GL_TEXTURE_ENV_COLOR, pattern GL_TEXTURE_ENV_MODE, pattern GL_TEXTURE_FILTER_CONTROL, pattern GL_TEXTURE_GEN_MODE, pattern GL_TEXTURE_GEN_Q, pattern GL_TEXTURE_GEN_R, pattern GL_TEXTURE_GEN_S, pattern GL_TEXTURE_GEN_T, pattern GL_TEXTURE_GREEN_SIZE, pattern GL_TEXTURE_GREEN_TYPE, pattern GL_TEXTURE_HEIGHT, pattern GL_TEXTURE_INTENSITY_SIZE, pattern GL_TEXTURE_INTENSITY_TYPE, pattern GL_TEXTURE_INTERNAL_FORMAT, pattern GL_TEXTURE_LOD_BIAS, pattern GL_TEXTURE_LUMINANCE_SIZE, pattern GL_TEXTURE_LUMINANCE_TYPE, pattern GL_TEXTURE_MAG_FILTER, pattern GL_TEXTURE_MATRIX, pattern GL_TEXTURE_MAX_LEVEL, pattern GL_TEXTURE_MAX_LOD, pattern GL_TEXTURE_MIN_FILTER, pattern GL_TEXTURE_MIN_LOD, pattern GL_TEXTURE_PRIORITY, pattern GL_TEXTURE_RED_SIZE, pattern GL_TEXTURE_RED_TYPE, pattern GL_TEXTURE_RESIDENT, pattern GL_TEXTURE_SHARED_SIZE, pattern GL_TEXTURE_STACK_DEPTH, pattern GL_TEXTURE_STENCIL_SIZE, pattern GL_TEXTURE_WIDTH, pattern GL_TEXTURE_WRAP_R, pattern GL_TEXTURE_WRAP_S, pattern GL_TEXTURE_WRAP_T, pattern GL_TRANSFORM_BIT, pattern GL_TRANSFORM_FEEDBACK_BUFFER, pattern GL_TRANSFORM_FEEDBACK_BUFFER_BINDING, pattern GL_TRANSFORM_FEEDBACK_BUFFER_MODE, pattern GL_TRANSFORM_FEEDBACK_BUFFER_SIZE, pattern GL_TRANSFORM_FEEDBACK_BUFFER_START, pattern GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, pattern GL_TRANSFORM_FEEDBACK_VARYINGS, pattern GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH, pattern GL_TRANSPOSE_COLOR_MATRIX, pattern GL_TRANSPOSE_MODELVIEW_MATRIX, pattern GL_TRANSPOSE_PROJECTION_MATRIX, pattern GL_TRANSPOSE_TEXTURE_MATRIX, pattern GL_TRIANGLES, pattern GL_TRIANGLE_FAN, pattern GL_TRIANGLE_STRIP, pattern GL_TRUE, pattern GL_UNPACK_ALIGNMENT, pattern GL_UNPACK_IMAGE_HEIGHT, pattern GL_UNPACK_LSB_FIRST, pattern GL_UNPACK_ROW_LENGTH, pattern GL_UNPACK_SKIP_IMAGES, pattern GL_UNPACK_SKIP_PIXELS, pattern GL_UNPACK_SKIP_ROWS, pattern GL_UNPACK_SWAP_BYTES, pattern GL_UNSIGNED_BYTE, pattern GL_UNSIGNED_BYTE_2_3_3_REV, pattern GL_UNSIGNED_BYTE_3_3_2, pattern GL_UNSIGNED_INT, pattern GL_UNSIGNED_INT_10F_11F_11F_REV, pattern GL_UNSIGNED_INT_10_10_10_2, pattern GL_UNSIGNED_INT_24_8, pattern GL_UNSIGNED_INT_2_10_10_10_REV, pattern GL_UNSIGNED_INT_5_9_9_9_REV, pattern GL_UNSIGNED_INT_8_8_8_8, pattern GL_UNSIGNED_INT_8_8_8_8_REV, pattern GL_UNSIGNED_INT_SAMPLER_1D, pattern GL_UNSIGNED_INT_SAMPLER_1D_ARRAY, pattern GL_UNSIGNED_INT_SAMPLER_2D, pattern GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, pattern GL_UNSIGNED_INT_SAMPLER_3D, pattern GL_UNSIGNED_INT_SAMPLER_CUBE, pattern GL_UNSIGNED_INT_VEC2, pattern GL_UNSIGNED_INT_VEC3, pattern GL_UNSIGNED_INT_VEC4, pattern GL_UNSIGNED_NORMALIZED, pattern GL_UNSIGNED_SHORT, pattern GL_UNSIGNED_SHORT_1_5_5_5_REV, pattern GL_UNSIGNED_SHORT_4_4_4_4, pattern GL_UNSIGNED_SHORT_4_4_4_4_REV, pattern GL_UNSIGNED_SHORT_5_5_5_1, pattern GL_UNSIGNED_SHORT_5_6_5, pattern GL_UNSIGNED_SHORT_5_6_5_REV, pattern GL_UPPER_LEFT, pattern GL_V2F, pattern GL_V3F, pattern GL_VALIDATE_STATUS, pattern GL_VENDOR, pattern GL_VERSION, pattern GL_VERTEX_ARRAY, pattern GL_VERTEX_ARRAY_BINDING, pattern GL_VERTEX_ARRAY_BUFFER_BINDING, pattern GL_VERTEX_ARRAY_POINTER, pattern GL_VERTEX_ARRAY_SIZE, pattern GL_VERTEX_ARRAY_STRIDE, pattern GL_VERTEX_ARRAY_TYPE, pattern GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, pattern GL_VERTEX_ATTRIB_ARRAY_ENABLED, pattern GL_VERTEX_ATTRIB_ARRAY_INTEGER, pattern GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, pattern GL_VERTEX_ATTRIB_ARRAY_POINTER, pattern GL_VERTEX_ATTRIB_ARRAY_SIZE, pattern GL_VERTEX_ATTRIB_ARRAY_STRIDE, pattern GL_VERTEX_ATTRIB_ARRAY_TYPE, pattern GL_VERTEX_PROGRAM_POINT_SIZE, pattern GL_VERTEX_PROGRAM_TWO_SIDE, pattern GL_VERTEX_SHADER, pattern GL_VIEWPORT, pattern GL_VIEWPORT_BIT, pattern GL_WEIGHT_ARRAY_BUFFER_BINDING, pattern GL_WRITE_ONLY, pattern GL_XOR, pattern GL_ZERO, pattern GL_ZOOM_X, pattern GL_ZOOM_Y, -- * Functions glAccum, glActiveTexture, glAlphaFunc, glAreTexturesResident, glArrayElement, glAttachShader, glBegin, glBeginConditionalRender, glBeginQuery, glBeginTransformFeedback, glBindAttribLocation, glBindBuffer, glBindBufferBase, glBindBufferRange, glBindFragDataLocation, glBindFramebuffer, glBindRenderbuffer, glBindTexture, glBindVertexArray, glBitmap, glBlendColor, glBlendEquation, glBlendEquationSeparate, glBlendFunc, glBlendFuncSeparate, glBlitFramebuffer, glBufferData, glBufferSubData, glCallList, glCallLists, glCheckFramebufferStatus, glClampColor, glClear, glClearAccum, glClearBufferfi, glClearBufferfv, glClearBufferiv, glClearBufferuiv, glClearColor, glClearDepth, glClearIndex, glClearStencil, glClientActiveTexture, glClipPlane, glColor3b, glColor3bv, glColor3d, glColor3dv, glColor3f, glColor3fv, glColor3i, glColor3iv, glColor3s, glColor3sv, glColor3ub, glColor3ubv, glColor3ui, glColor3uiv, glColor3us, glColor3usv, glColor4b, glColor4bv, glColor4d, glColor4dv, glColor4f, glColor4fv, glColor4i, glColor4iv, glColor4s, glColor4sv, glColor4ub, glColor4ubv, glColor4ui, glColor4uiv, glColor4us, glColor4usv, glColorMask, glColorMaski, glColorMaterial, glColorPointer, glCompileShader, glCompressedTexImage1D, glCompressedTexImage2D, glCompressedTexImage3D, glCompressedTexSubImage1D, glCompressedTexSubImage2D, glCompressedTexSubImage3D, glCopyPixels, glCopyTexImage1D, glCopyTexImage2D, glCopyTexSubImage1D, glCopyTexSubImage2D, glCopyTexSubImage3D, glCreateProgram, glCreateShader, glCullFace, glDeleteBuffers, glDeleteFramebuffers, glDeleteLists, glDeleteProgram, glDeleteQueries, glDeleteRenderbuffers, glDeleteShader, glDeleteTextures, glDeleteVertexArrays, glDepthFunc, glDepthMask, glDepthRange, glDetachShader, glDisable, glDisableClientState, glDisableVertexAttribArray, glDisablei, glDrawArrays, glDrawBuffer, glDrawBuffers, glDrawElements, glDrawPixels, glDrawRangeElements, glEdgeFlag, glEdgeFlagPointer, glEdgeFlagv, glEnable, glEnableClientState, glEnableVertexAttribArray, glEnablei, glEnd, glEndConditionalRender, glEndList, glEndQuery, glEndTransformFeedback, glEvalCoord1d, glEvalCoord1dv, glEvalCoord1f, glEvalCoord1fv, glEvalCoord2d, glEvalCoord2dv, glEvalCoord2f, glEvalCoord2fv, glEvalMesh1, glEvalMesh2, glEvalPoint1, glEvalPoint2, glFeedbackBuffer, glFinish, glFlush, glFlushMappedBufferRange, glFogCoordPointer, glFogCoordd, glFogCoorddv, glFogCoordf, glFogCoordfv, glFogf, glFogfv, glFogi, glFogiv, glFramebufferRenderbuffer, glFramebufferTexture1D, glFramebufferTexture2D, glFramebufferTexture3D, glFramebufferTextureLayer, glFrontFace, glFrustum, glGenBuffers, glGenFramebuffers, glGenLists, glGenQueries, glGenRenderbuffers, glGenTextures, glGenVertexArrays, glGenerateMipmap, glGetActiveAttrib, glGetActiveUniform, glGetAttachedShaders, glGetAttribLocation, glGetBooleani_v, glGetBooleanv, glGetBufferParameteriv, glGetBufferPointerv, glGetBufferSubData, glGetClipPlane, glGetCompressedTexImage, glGetDoublev, glGetError, glGetFloatv, glGetFragDataLocation, glGetFramebufferAttachmentParameteriv, glGetIntegeri_v, glGetIntegerv, glGetLightfv, glGetLightiv, glGetMapdv, glGetMapfv, glGetMapiv, glGetMaterialfv, glGetMaterialiv, glGetPixelMapfv, glGetPixelMapuiv, glGetPixelMapusv, glGetPointerv, glGetPolygonStipple, glGetProgramInfoLog, glGetProgramiv, glGetQueryObjectiv, glGetQueryObjectuiv, glGetQueryiv, glGetRenderbufferParameteriv, glGetShaderInfoLog, glGetShaderSource, glGetShaderiv, glGetString, glGetStringi, glGetTexEnvfv, glGetTexEnviv, glGetTexGendv, glGetTexGenfv, glGetTexGeniv, glGetTexImage, glGetTexLevelParameterfv, glGetTexLevelParameteriv, glGetTexParameterIiv, glGetTexParameterIuiv, glGetTexParameterfv, glGetTexParameteriv, glGetTransformFeedbackVarying, glGetUniformLocation, glGetUniformfv, glGetUniformiv, glGetUniformuiv, glGetVertexAttribIiv, glGetVertexAttribIuiv, glGetVertexAttribPointerv, glGetVertexAttribdv, glGetVertexAttribfv, glGetVertexAttribiv, glHint, glIndexMask, glIndexPointer, glIndexd, glIndexdv, glIndexf, glIndexfv, glIndexi, glIndexiv, glIndexs, glIndexsv, glIndexub, glIndexubv, glInitNames, glInterleavedArrays, glIsBuffer, glIsEnabled, glIsEnabledi, glIsFramebuffer, glIsList, glIsProgram, glIsQuery, glIsRenderbuffer, glIsShader, glIsTexture, glIsVertexArray, glLightModelf, glLightModelfv, glLightModeli, glLightModeliv, glLightf, glLightfv, glLighti, glLightiv, glLineStipple, glLineWidth, glLinkProgram, glListBase, glLoadIdentity, glLoadMatrixd, glLoadMatrixf, glLoadName, glLoadTransposeMatrixd, glLoadTransposeMatrixf, glLogicOp, glMap1d, glMap1f, glMap2d, glMap2f, glMapBuffer, glMapBufferRange, glMapGrid1d, glMapGrid1f, glMapGrid2d, glMapGrid2f, glMaterialf, glMaterialfv, glMateriali, glMaterialiv, glMatrixMode, glMultMatrixd, glMultMatrixf, glMultTransposeMatrixd, glMultTransposeMatrixf, glMultiDrawArrays, glMultiDrawElements, glMultiTexCoord1d, glMultiTexCoord1dv, glMultiTexCoord1f, glMultiTexCoord1fv, glMultiTexCoord1i, glMultiTexCoord1iv, glMultiTexCoord1s, glMultiTexCoord1sv, glMultiTexCoord2d, glMultiTexCoord2dv, glMultiTexCoord2f, glMultiTexCoord2fv, glMultiTexCoord2i, glMultiTexCoord2iv, glMultiTexCoord2s, glMultiTexCoord2sv, glMultiTexCoord3d, glMultiTexCoord3dv, glMultiTexCoord3f, glMultiTexCoord3fv, glMultiTexCoord3i, glMultiTexCoord3iv, glMultiTexCoord3s, glMultiTexCoord3sv, glMultiTexCoord4d, glMultiTexCoord4dv, glMultiTexCoord4f, glMultiTexCoord4fv, glMultiTexCoord4i, glMultiTexCoord4iv, glMultiTexCoord4s, glMultiTexCoord4sv, glNewList, glNormal3b, glNormal3bv, glNormal3d, glNormal3dv, glNormal3f, glNormal3fv, glNormal3i, glNormal3iv, glNormal3s, glNormal3sv, glNormalPointer, glOrtho, glPassThrough, glPixelMapfv, glPixelMapuiv, glPixelMapusv, glPixelStoref, glPixelStorei, glPixelTransferf, glPixelTransferi, glPixelZoom, glPointParameterf, glPointParameterfv, glPointParameteri, glPointParameteriv, glPointSize, glPolygonMode, glPolygonOffset, glPolygonStipple, glPopAttrib, glPopClientAttrib, glPopMatrix, glPopName, glPrioritizeTextures, glPushAttrib, glPushClientAttrib, glPushMatrix, glPushName, glRasterPos2d, glRasterPos2dv, glRasterPos2f, glRasterPos2fv, glRasterPos2i, glRasterPos2iv, glRasterPos2s, glRasterPos2sv, glRasterPos3d, glRasterPos3dv, glRasterPos3f, glRasterPos3fv, glRasterPos3i, glRasterPos3iv, glRasterPos3s, glRasterPos3sv, glRasterPos4d, glRasterPos4dv, glRasterPos4f, glRasterPos4fv, glRasterPos4i, glRasterPos4iv, glRasterPos4s, glRasterPos4sv, glReadBuffer, glReadPixels, glRectd, glRectdv, glRectf, glRectfv, glRecti, glRectiv, glRects, glRectsv, glRenderMode, glRenderbufferStorage, glRenderbufferStorageMultisample, glRotated, glRotatef, glSampleCoverage, glScaled, glScalef, glScissor, glSecondaryColor3b, glSecondaryColor3bv, glSecondaryColor3d, glSecondaryColor3dv, glSecondaryColor3f, glSecondaryColor3fv, glSecondaryColor3i, glSecondaryColor3iv, glSecondaryColor3s, glSecondaryColor3sv, glSecondaryColor3ub, glSecondaryColor3ubv, glSecondaryColor3ui, glSecondaryColor3uiv, glSecondaryColor3us, glSecondaryColor3usv, glSecondaryColorPointer, glSelectBuffer, glShadeModel, glShaderSource, glStencilFunc, glStencilFuncSeparate, glStencilMask, glStencilMaskSeparate, glStencilOp, glStencilOpSeparate, glTexCoord1d, glTexCoord1dv, glTexCoord1f, glTexCoord1fv, glTexCoord1i, glTexCoord1iv, glTexCoord1s, glTexCoord1sv, glTexCoord2d, glTexCoord2dv, glTexCoord2f, glTexCoord2fv, glTexCoord2i, glTexCoord2iv, glTexCoord2s, glTexCoord2sv, glTexCoord3d, glTexCoord3dv, glTexCoord3f, glTexCoord3fv, glTexCoord3i, glTexCoord3iv, glTexCoord3s, glTexCoord3sv, glTexCoord4d, glTexCoord4dv, glTexCoord4f, glTexCoord4fv, glTexCoord4i, glTexCoord4iv, glTexCoord4s, glTexCoord4sv, glTexCoordPointer, glTexEnvf, glTexEnvfv, glTexEnvi, glTexEnviv, glTexGend, glTexGendv, glTexGenf, glTexGenfv, glTexGeni, glTexGeniv, glTexImage1D, glTexImage2D, glTexImage3D, glTexParameterIiv, glTexParameterIuiv, glTexParameterf, glTexParameterfv, glTexParameteri, glTexParameteriv, glTexSubImage1D, glTexSubImage2D, glTexSubImage3D, glTransformFeedbackVaryings, glTranslated, glTranslatef, glUniform1f, glUniform1fv, glUniform1i, glUniform1iv, glUniform1ui, glUniform1uiv, glUniform2f, glUniform2fv, glUniform2i, glUniform2iv, glUniform2ui, glUniform2uiv, glUniform3f, glUniform3fv, glUniform3i, glUniform3iv, glUniform3ui, glUniform3uiv, glUniform4f, glUniform4fv, glUniform4i, glUniform4iv, glUniform4ui, glUniform4uiv, glUniformMatrix2fv, glUniformMatrix2x3fv, glUniformMatrix2x4fv, glUniformMatrix3fv, glUniformMatrix3x2fv, glUniformMatrix3x4fv, glUniformMatrix4fv, glUniformMatrix4x2fv, glUniformMatrix4x3fv, glUnmapBuffer, glUseProgram, glValidateProgram, glVertex2d, glVertex2dv, glVertex2f, glVertex2fv, glVertex2i, glVertex2iv, glVertex2s, glVertex2sv, glVertex3d, glVertex3dv, glVertex3f, glVertex3fv, glVertex3i, glVertex3iv, glVertex3s, glVertex3sv, glVertex4d, glVertex4dv, glVertex4f, glVertex4fv, glVertex4i, glVertex4iv, glVertex4s, glVertex4sv, glVertexAttrib1d, glVertexAttrib1dv, glVertexAttrib1f, glVertexAttrib1fv, glVertexAttrib1s, glVertexAttrib1sv, glVertexAttrib2d, glVertexAttrib2dv, glVertexAttrib2f, glVertexAttrib2fv, glVertexAttrib2s, glVertexAttrib2sv, glVertexAttrib3d, glVertexAttrib3dv, glVertexAttrib3f, glVertexAttrib3fv, glVertexAttrib3s, glVertexAttrib3sv, glVertexAttrib4Nbv, glVertexAttrib4Niv, glVertexAttrib4Nsv, glVertexAttrib4Nub, glVertexAttrib4Nubv, glVertexAttrib4Nuiv, glVertexAttrib4Nusv, glVertexAttrib4bv, glVertexAttrib4d, glVertexAttrib4dv, glVertexAttrib4f, glVertexAttrib4fv, glVertexAttrib4iv, glVertexAttrib4s, glVertexAttrib4sv, glVertexAttrib4ubv, glVertexAttrib4uiv, glVertexAttrib4usv, glVertexAttribI1i, glVertexAttribI1iv, glVertexAttribI1ui, glVertexAttribI1uiv, glVertexAttribI2i, glVertexAttribI2iv, glVertexAttribI2ui, glVertexAttribI2uiv, glVertexAttribI3i, glVertexAttribI3iv, glVertexAttribI3ui, glVertexAttribI3uiv, glVertexAttribI4bv, glVertexAttribI4i, glVertexAttribI4iv, glVertexAttribI4sv, glVertexAttribI4ubv, glVertexAttribI4ui, glVertexAttribI4uiv, glVertexAttribI4usv, glVertexAttribIPointer, glVertexAttribPointer, glVertexPointer, glViewport, glWindowPos2d, glWindowPos2dv, glWindowPos2f, glWindowPos2fv, glWindowPos2i, glWindowPos2iv, glWindowPos2s, glWindowPos2sv, glWindowPos3d, glWindowPos3dv, glWindowPos3f, glWindowPos3fv, glWindowPos3i, glWindowPos3iv, glWindowPos3s, glWindowPos3sv ) where import Graphics.GL.Types import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/Compatibility30.hs
Haskell
bsd-3-clause
45,469
module Data.UI.Input.Keyboard.ModKey(ModKey(..), unModKey, pretty) where import Data.Monoid(mempty) import Data.UI.Input.Keyboard.Mods(ModsState) import qualified Data.UI.Input.Keyboard.Mods as Mods import Data.UI.Input.Keyboard.Keys(Key) import qualified Data.UI.Input.Keyboard.Keys as Keys data ModKey = ModKey ModsState Key deriving (Show, Read, Eq, Ord) unModKey :: ModKey -> (ModsState, Key) unModKey (ModKey x y) = (x, y) pretty :: ModKey -> String pretty (ModKey modsState key) = (if modsState == mempty then "" else Mods.pretty modsState ++ "-") ++ Keys.pretty key
Peaker/keyboard
src/Data/UI/Input/Keyboard/ModKey.hs
Haskell
bsd-3-clause
589
-- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Texturing.TextureTarget -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : provisional -- Portability : portable -- -- This is a purely internal module for marshaling texture targets. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Texturing.TextureTarget ( TextureTarget(..), marshalTextureTarget, marshalProxyTextureTarget, CubeMapTarget(..), marshalCubeMapTarget ) where import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum ) import Graphics.Rendering.OpenGL.GL.PixelRectangles ( Proxy(..) ) -------------------------------------------------------------------------------- data TextureTarget = Texture1D | Texture2D | Texture3D | TextureCubeMap | TextureRectangle deriving ( Eq, Ord, Show ) marshalTextureTarget :: TextureTarget -> GLenum marshalTextureTarget x = case x of Texture1D -> 0xde0 Texture2D -> 0xde1 Texture3D -> 0x806f TextureCubeMap -> 0x8513 TextureRectangle -> 0x84f5 marshalProxyTextureTarget :: Proxy -> TextureTarget -> GLenum marshalProxyTextureTarget NoProxy x = marshalTextureTarget x marshalProxyTextureTarget Proxy x = case x of Texture1D -> 0x8063 Texture2D -> 0x8064 Texture3D -> 0x8070 TextureCubeMap -> 0x851b TextureRectangle -> 0x84f7 -------------------------------------------------------------------------------- data CubeMapTarget = TextureCubeMapPositiveX | TextureCubeMapNegativeX | TextureCubeMapPositiveY | TextureCubeMapNegativeY | TextureCubeMapPositiveZ | TextureCubeMapNegativeZ deriving ( Eq, Ord, Show ) marshalCubeMapTarget :: CubeMapTarget -> GLenum marshalCubeMapTarget x = case x of TextureCubeMapPositiveX -> 0x8515 TextureCubeMapNegativeX -> 0x8516 TextureCubeMapPositiveY -> 0x8517 TextureCubeMapNegativeY -> 0x8518 TextureCubeMapPositiveZ -> 0x8519 TextureCubeMapNegativeZ -> 0x851a
FranklinChen/hugs98-plus-Sep2006
packages/OpenGL/Graphics/Rendering/OpenGL/GL/Texturing/TextureTarget.hs
Haskell
bsd-3-clause
2,185
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-} #if MIN_VERSION_ghc_prim(0,3,1) {-# LANGUAGE MagicHash #-} #endif -- | -- Module: Data.Aeson.Parser.Internal -- Copyright: (c) 2011-2016 Bryan O'Sullivan -- (c) 2011 MailRank, Inc. -- License: BSD3 -- Maintainer: Bryan O'Sullivan <bos@serpentine.com> -- Stability: experimental -- Portability: portable -- -- Efficiently and correctly parse a JSON string. The string must be -- encoded as UTF-8. module Data.Aeson.Parser.Internal ( -- * Lazy parsers json, jsonEOF , value , jstring -- * Strict parsers , json', jsonEOF' , value' -- * Helpers , decodeWith , decodeStrictWith , eitherDecodeWith , eitherDecodeStrictWith ) where import Control.Monad.IO.Class (liftIO) import Data.Aeson.Types.Internal (IResult(..), JSONPath, Result(..), Value(..)) import Data.Attoparsec.ByteString.Char8 (Parser, char, endOfInput, scientific, skipSpace, string) import Data.Bits ((.|.), shiftL) import Data.ByteString.Internal (ByteString(..)) import Data.Char (chr) import Data.Text (Text) import Data.Text.Encoding (decodeUtf8') import Data.Text.Internal.Encoding.Utf8 (ord2, ord3, ord4) import Data.Text.Internal.Unsafe.Char (ord) import Data.Vector as Vector (Vector, empty, fromList, reverse) import Data.Word (Word8) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr (Ptr, plusPtr) import Foreign.Ptr (minusPtr) import Foreign.Storable (poke) import System.IO.Unsafe (unsafePerformIO) import qualified Data.Attoparsec.ByteString as A import qualified Data.Attoparsec.Lazy as L import qualified Data.Attoparsec.Zepto as Z import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Unsafe as B import qualified Data.HashMap.Strict as H #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((*>), (<$>), (<*), pure) #endif #if MIN_VERSION_ghc_prim(0,3,1) import GHC.Base (Int#, (==#), isTrue#, orI#, word2Int#) import GHC.Word (Word8(W8#)) #endif #define BACKSLASH 92 #define CLOSE_CURLY 125 #define CLOSE_SQUARE 93 #define COMMA 44 #define DOUBLE_QUOTE 34 #define OPEN_CURLY 123 #define OPEN_SQUARE 91 #define C_0 48 #define C_9 57 #define C_A 65 #define C_F 70 #define C_a 97 #define C_f 102 #define C_n 110 #define C_t 116 -- | Parse a top-level JSON value. -- -- The conversion of a parsed value to a Haskell value is deferred -- until the Haskell value is needed. This may improve performance if -- only a subset of the results of conversions are needed, but at a -- cost in thunk allocation. -- -- This function is an alias for 'value'. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json :: Parser Value json = value -- | Parse a top-level JSON value. -- -- This is a strict version of 'json' which avoids building up thunks -- during parsing; it performs all conversions immediately. Prefer -- this version if most of the JSON data needs to be accessed. -- -- This function is an alias for 'value''. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json' :: Parser Value json' = value' object_ :: Parser Value object_ = {-# SCC "object_" #-} Object <$> objectValues jstring value object_' :: Parser Value object_' = {-# SCC "object_'" #-} do !vals <- objectValues jstring' value' return (Object vals) where jstring' = do !s <- jstring return s objectValues :: Parser Text -> Parser Value -> Parser (H.HashMap Text Value) objectValues str val = do skipSpace w <- A.peekWord8' if w == CLOSE_CURLY then A.anyWord8 >> return H.empty else loop H.empty where loop m0 = do k <- str <* skipSpace <* char ':' v <- val <* skipSpace let !m = H.insert k v m0 ch <- A.satisfy $ \w -> w == COMMA || w == CLOSE_CURLY if ch == COMMA then skipSpace >> loop m else return m {-# INLINE objectValues #-} array_ :: Parser Value array_ = {-# SCC "array_" #-} Array <$> arrayValues value array_' :: Parser Value array_' = {-# SCC "array_'" #-} do !vals <- arrayValues value' return (Array vals) arrayValues :: Parser Value -> Parser (Vector Value) arrayValues val = do skipSpace w <- A.peekWord8' if w == CLOSE_SQUARE then A.anyWord8 >> return Vector.empty else loop [] where loop acc = do v <- val <* skipSpace ch <- A.satisfy $ \w -> w == COMMA || w == CLOSE_SQUARE if ch == COMMA then skipSpace >> loop (v:acc) else return (Vector.reverse (Vector.fromList (v:acc))) {-# INLINE arrayValues #-} -- | Parse any JSON value. You should usually 'json' in preference to -- this function, as this function relaxes the object-or-array -- requirement of RFC 4627. -- -- In particular, be careful in using this function if you think your -- code might interoperate with Javascript. A na&#xef;ve Javascript -- library that parses JSON data using @eval@ is vulnerable to attack -- unless the encoded data represents an object or an array. JSON -- implementations in other languages conform to that same restriction -- to preserve interoperability and security. value :: Parser Value value = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_) OPEN_CURLY -> A.anyWord8 *> object_ OPEN_SQUARE -> A.anyWord8 *> array_ C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> Number <$> scientific | otherwise -> fail "not a valid json value" -- | Strict version of 'value'. See also 'json''. value' :: Parser Value value' = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> do !s <- A.anyWord8 *> jstring_ return (String s) OPEN_CURLY -> A.anyWord8 *> object_' OPEN_SQUARE -> A.anyWord8 *> array_' C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> do !n <- scientific return (Number n) | otherwise -> fail "not a valid json value" -- | Parse a quoted JSON string. jstring :: Parser Text jstring = A.word8 DOUBLE_QUOTE *> jstring_ -- | Parse a string without a leading quote. jstring_ :: Parser Text {-# INLINE jstring_ #-} jstring_ = {-# SCC "jstring_" #-} do (s, fin) <- A.runScanner startState go _ <- A.anyWord8 s1 <- if isEscaped fin then case unescape s of Right r -> return r Left err -> fail err else return s case decodeUtf8' s1 of Right r -> return r Left err -> fail $ show err where #if MIN_VERSION_ghc_prim(0,3,1) isEscaped (S _ escaped) = isTrue# escaped startState = S 0# 0# go (S a b) (W8# c) | isTrue# a = Just (S 0# b) | isTrue# (word2Int# c ==# 34#) = Nothing -- double quote | otherwise = let a' = word2Int# c ==# 92# -- backslash in Just (S a' (orI# a' b)) data S = S Int# Int# #else isEscaped (S _ escaped) = escaped startState = S False False go (S a b) c | a = Just (S False b) | c == DOUBLE_QUOTE = Nothing | otherwise = let a' = c == backslash in Just (S a' (a' || b)) where backslash = BACKSLASH data S = S !Bool !Bool #endif unescape :: ByteString -> Either String ByteString unescape s = unsafePerformIO $ do let len = B.length s fp <- B.mallocByteString len -- We perform no bounds checking when writing to the destination -- string, as unescaping always makes it shorter than the source. withForeignPtr fp $ \ptr -> do ret <- Z.parseT (go ptr) s case ret of Left err -> return (Left err) Right p -> do let newlen = p `minusPtr` ptr slop = len - newlen Right <$> if slop >= 128 && slop >= len `quot` 4 then B.create newlen $ \np -> B.memcpy np ptr newlen else return (PS fp 0 newlen) where go ptr = do h <- Z.takeWhile (/=BACKSLASH) let rest = do start <- Z.take 2 let !slash = B.unsafeHead start !t = B.unsafeIndex start 1 escape = case B.elemIndex t "\"\\/ntbrfu" of Just i -> i _ -> 255 if slash /= BACKSLASH || escape == 255 then fail "invalid JSON escape sequence" else if t /= 117 -- 'u' then copy h ptr >>= word8 (B.unsafeIndex mapping escape) >>= go else do a <- hexQuad if a < 0xd800 || a > 0xdfff then copy h ptr >>= charUtf8 (chr a) >>= go else do b <- Z.string "\\u" *> hexQuad if a <= 0xdbff && b >= 0xdc00 && b <= 0xdfff then let !c = ((a - 0xd800) `shiftL` 10) + (b - 0xdc00) + 0x10000 in copy h ptr >>= charUtf8 (chr c) >>= go else fail "invalid UTF-16 surrogates" done <- Z.atEnd if done then copy h ptr else rest mapping = "\"\\/\n\t\b\r\f" hexQuad :: Z.ZeptoT IO Int hexQuad = do s <- Z.take 4 let hex n | w >= C_0 && w <= C_9 = w - C_0 | w >= C_a && w <= C_f = w - 87 | w >= C_A && w <= C_F = w - 55 | otherwise = 255 where w = fromIntegral $ B.unsafeIndex s n a = hex 0; b = hex 1; c = hex 2; d = hex 3 if (a .|. b .|. c .|. d) /= 255 then return $! d .|. (c `shiftL` 4) .|. (b `shiftL` 8) .|. (a `shiftL` 12) else fail "invalid hex escape" decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a decodeWith p to s = case L.parse p s of L.Done _ v -> case to v of Success a -> Just a _ -> Nothing _ -> Nothing {-# INLINE decodeWith #-} decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString -> Maybe a decodeStrictWith p to s = case either Error to (A.parseOnly p s) of Success a -> Just a _ -> Nothing {-# INLINE decodeStrictWith #-} eitherDecodeWith :: Parser Value -> (Value -> IResult a) -> L.ByteString -> Either (JSONPath, String) a eitherDecodeWith p to s = case L.parse p s of L.Done _ v -> case to v of ISuccess a -> Right a IError path msg -> Left (path, msg) L.Fail _ _ msg -> Left ([], msg) {-# INLINE eitherDecodeWith #-} eitherDecodeStrictWith :: Parser Value -> (Value -> IResult a) -> B.ByteString -> Either (JSONPath, String) a eitherDecodeStrictWith p to s = case either (IError []) to (A.parseOnly p s) of ISuccess a -> Right a IError path msg -> Left (path, msg) {-# INLINE eitherDecodeStrictWith #-} -- $lazy -- -- The 'json' and 'value' parsers decouple identification from -- conversion. Identification occurs immediately (so that an invalid -- JSON document can be rejected as early as possible), but conversion -- to a Haskell value is deferred until that value is needed. -- -- This decoupling can be time-efficient if only a smallish subset of -- elements in a JSON value need to be inspected, since the cost of -- conversion is zero for uninspected elements. The trade off is an -- increase in memory usage, due to allocation of thunks for values -- that have not yet been converted. -- $strict -- -- The 'json'' and 'value'' parsers combine identification with -- conversion. They consume more CPU cycles up front, but have a -- smaller memory footprint. -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json'. jsonEOF :: Parser Value jsonEOF = json <* skipSpace <* endOfInput -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json''. jsonEOF' :: Parser Value jsonEOF' = json' <* skipSpace <* endOfInput word8 :: Word8 -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) word8 w ptr = do liftIO $ poke ptr w return $! ptr `plusPtr` 1 copy :: ByteString -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) copy (PS fp off len) ptr = liftIO . withForeignPtr fp $ \src -> do B.memcpy ptr (src `plusPtr` off) len return $! ptr `plusPtr` len charUtf8 :: Char -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) charUtf8 ch ptr | ch < '\x80' = liftIO $ do poke ptr (fromIntegral (ord ch)) return $! ptr `plusPtr` 1 | ch < '\x800' = liftIO $ do let (a,b) = ord2 ch poke ptr a poke (ptr `plusPtr` 1) b return $! ptr `plusPtr` 2 | ch < '\xffff' = liftIO $ do let (a,b,c) = ord3 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c return $! ptr `plusPtr` 3 | otherwise = liftIO $ do let (a,b,c,d) = ord4 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c poke (ptr `plusPtr` 3) d return $! ptr `plusPtr` 4
roelvandijk/aeson
Data/Aeson/Parser/Internal.hs
Haskell
bsd-3-clause
13,841
----------------------------------------------------------------------------- -- | -- Module : Application.DevAdmin.Cabal -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Application.DevAdmin.Cabal where import System.FilePath -- import Data.Maybe import Application.DevAdmin.Project import Application.DevAdmin.Config import Distribution.Package import Distribution.PackageDescription import Distribution.ModuleName import Distribution.PackageDescription.Parse import Distribution.Verbosity import Control.Applicative getGenPkgDesc :: FilePath -> Project -> IO GenericPackageDescription getGenPkgDesc progbase proj = readPackageDescription normal . getCabalFileName progbase $ proj getAllGenPkgDesc :: BuildConfiguration -> ProjectConfiguration -> IO [GenericPackageDescription] getAllGenPkgDesc bc pc = do let projects = pc_projects pc -- let (p,w) = (,) <$> bc_srcbase <*> bc_workspacebase $ bc mapM (getGenPkgDesc (bc_srcbase bc)) projects getPkgName :: GenericPackageDescription -> String getPkgName = name . pkgName . package . packageDescription where name (PackageName str) = str getDependency :: GenericPackageDescription -> [String] getDependency desc = let rlib = condLibrary desc in case rlib of Nothing -> [] Just lib -> map matchDependentPackageName . condTreeConstraints $ lib getCabalFileName :: FilePath -> Project -> FilePath getCabalFileName prog (ProgProj pname) = prog </> pname </> (pname ++ ".cabal") -- getCabalFileName (_prog,workspace) (WorkspaceProj wname pname) -- = workspace </> wname </> pname </> (pname ++ ".cabal") matchDependentPackageName :: Dependency -> String matchDependentPackageName (Dependency (PackageName x) _) = x {- getModules :: GenericPackageDescription -> [FilePath] getModules dsc = let maybelib = library . packageDescription $ dsc in case maybelib of Nothing -> [] Just lib -> map ((<.>"hs") . toFilePath) (exposedModules lib) -} getModules :: GenericPackageDescription -> [(FilePath,ModuleName)] getModules dsc = let mnode = condLibrary dsc in maybe [] ((map <$> (,) . head . hsSourceDirs . libBuildInfo <*> exposedModules) . condTreeData) mnode getOtherModules :: GenericPackageDescription -> [(FilePath,ModuleName)] getOtherModules dsc = let mnode = condLibrary dsc in maybe [] ((map <$> (,) . head . hsSourceDirs . libBuildInfo <*> otherModules . libBuildInfo) . condTreeData) mnode
wavewave/devadmin
lib/Application/DevAdmin/Cabal.hs
Haskell
bsd-3-clause
2,720
{-# LANGUAGE OverloadedStrings #-} module RealWorld.Api ( Api, server ) where import Servant import qualified RealWorld.Api.Articles as Articles import qualified RealWorld.Api.Authentication as Authentication import qualified RealWorld.Api.Profiles as Profiles import qualified RealWorld.Api.Tags as Tags import qualified RealWorld.Api.User as User import RealWorld.Monad type Api = "users" :> Authentication.Api :<|> "user" :> User.Api :<|> "profiles" :> Profiles.Api :<|> "articles" :> Articles.Api :<|> "tags" :> Tags.Api server :: ServerT Api RealWorld server = Authentication.server :<|> User.server :<|> Profiles.server :<|> Articles.server :<|> Tags.server
zudov/servant-realworld-example-app
src/RealWorld/Api.hs
Haskell
bsd-3-clause
775
{- (c) The AQUA Project, Glasgow University, 1993-1998 \section[SimplMonad]{The simplifier Monad} -} module SimplMonad ( -- The monad SimplM, initSmpl, traceSmpl, getSimplRules, getFamEnvs, -- Unique supply MonadUnique(..), newId, -- Counting SimplCount, tick, freeTick, checkedTick, getSimplCount, zeroSimplCount, pprSimplCount, plusSimplCount, isZeroSimplCount ) where import Id ( Id, mkSysLocalOrCoVar ) import Type ( Type ) import FamInstEnv ( FamInstEnv ) import CoreSyn ( RuleEnv(..) ) import UniqSupply import DynFlags import CoreMonad import Outputable import FastString import MonadUtils import ErrUtils import BasicTypes ( IntWithInf, treatZeroAsInf, mkIntWithInf ) import Control.Monad ( when, liftM, ap ) {- ************************************************************************ * * \subsection{Monad plumbing} * * ************************************************************************ For the simplifier monad, we want to {\em thread} a unique supply and a counter. (Command-line switches move around through the explicitly-passed SimplEnv.) -} newtype SimplM result = SM { unSM :: SimplTopEnv -- Envt that does not change much -> UniqSupply -- We thread the unique supply because -- constantly splitting it is rather expensive -> SimplCount -> IO (result, UniqSupply, SimplCount)} -- we only need IO here for dump output data SimplTopEnv = STE { st_flags :: DynFlags , st_max_ticks :: IntWithInf -- Max #ticks in this simplifier run , st_rules :: RuleEnv , st_fams :: (FamInstEnv, FamInstEnv) } initSmpl :: DynFlags -> RuleEnv -> (FamInstEnv, FamInstEnv) -> UniqSupply -- No init count; set to 0 -> Int -- Size of the bindings, used to limit -- the number of ticks we allow -> SimplM a -> IO (a, SimplCount) initSmpl dflags rules fam_envs us size m = do (result, _, count) <- unSM m env us (zeroSimplCount dflags) return (result, count) where env = STE { st_flags = dflags, st_rules = rules , st_max_ticks = computeMaxTicks dflags size , st_fams = fam_envs } computeMaxTicks :: DynFlags -> Int -> IntWithInf -- Compute the max simplifier ticks as -- (base-size + pgm-size) * magic-multiplier * tick-factor/100 -- where -- magic-multiplier is a constant that gives reasonable results -- base-size is a constant to deal with size-zero programs computeMaxTicks dflags size = treatZeroAsInf $ fromInteger ((toInteger (size + base_size) * toInteger (tick_factor * magic_multiplier)) `div` 100) where tick_factor = simplTickFactor dflags base_size = 100 magic_multiplier = 40 -- MAGIC NUMBER, multiplies the simplTickFactor -- We can afford to be generous; this is really -- just checking for loops, and shouldn't usually fire -- A figure of 20 was too small: see Trac #5539. {-# INLINE thenSmpl #-} {-# INLINE thenSmpl_ #-} {-# INLINE returnSmpl #-} instance Functor SimplM where fmap = liftM instance Applicative SimplM where pure = returnSmpl (<*>) = ap (*>) = thenSmpl_ instance Monad SimplM where (>>) = (*>) (>>=) = thenSmpl return = pure returnSmpl :: a -> SimplM a returnSmpl e = SM (\_st_env us sc -> return (e, us, sc)) thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b thenSmpl_ :: SimplM a -> SimplM b -> SimplM b thenSmpl m k = SM $ \st_env us0 sc0 -> do (m_result, us1, sc1) <- unSM m st_env us0 sc0 unSM (k m_result) st_env us1 sc1 thenSmpl_ m k = SM $ \st_env us0 sc0 -> do (_, us1, sc1) <- unSM m st_env us0 sc0 unSM k st_env us1 sc1 -- TODO: this specializing is not allowed -- {-# SPECIALIZE mapM :: (a -> SimplM b) -> [a] -> SimplM [b] #-} -- {-# SPECIALIZE mapAndUnzipM :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c]) #-} -- {-# SPECIALIZE mapAccumLM :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c]) #-} traceSmpl :: String -> SDoc -> SimplM () traceSmpl herald doc = do { dflags <- getDynFlags ; when (dopt Opt_D_dump_simpl_trace dflags) $ liftIO $ printOutputForUser dflags alwaysQualify $ hang (text herald) 2 doc } {- ************************************************************************ * * \subsection{The unique supply} * * ************************************************************************ -} instance MonadUnique SimplM where getUniqueSupplyM = SM (\_st_env us sc -> case splitUniqSupply us of (us1, us2) -> return (us1, us2, sc)) getUniqueM = SM (\_st_env us sc -> case takeUniqFromSupply us of (u, us') -> return (u, us', sc)) getUniquesM = SM (\_st_env us sc -> case splitUniqSupply us of (us1, us2) -> return (uniqsFromSupply us1, us2, sc)) instance HasDynFlags SimplM where getDynFlags = SM (\st_env us sc -> return (st_flags st_env, us, sc)) instance MonadIO SimplM where liftIO m = SM $ \_ us sc -> do x <- m return (x, us, sc) getSimplRules :: SimplM RuleEnv getSimplRules = SM (\st_env us sc -> return (st_rules st_env, us, sc)) getFamEnvs :: SimplM (FamInstEnv, FamInstEnv) getFamEnvs = SM (\st_env us sc -> return (st_fams st_env, us, sc)) newId :: FastString -> Type -> SimplM Id newId fs ty = do uniq <- getUniqueM return (mkSysLocalOrCoVar fs uniq ty) {- ************************************************************************ * * \subsection{Counting up what we've done} * * ************************************************************************ -} getSimplCount :: SimplM SimplCount getSimplCount = SM (\_st_env us sc -> return (sc, us, sc)) tick :: Tick -> SimplM () tick t = SM (\st_env us sc -> let sc' = doSimplTick (st_flags st_env) t sc in sc' `seq` return ((), us, sc')) checkedTick :: Tick -> SimplM () -- Try to take a tick, but fail if too many checkedTick t = SM (\st_env us sc -> if st_max_ticks st_env <= mkIntWithInf (simplCountN sc) then pprPanic "Simplifier ticks exhausted" (msg sc) else let sc' = doSimplTick (st_flags st_env) t sc in sc' `seq` return ((), us, sc')) where msg sc = vcat [ text "When trying" <+> ppr t , text "To increase the limit, use -fsimpl-tick-factor=N (default 100)" , text "If you need to do this, let GHC HQ know, and what factor you needed" , pp_details sc , pprSimplCount sc ] pp_details sc | hasDetailedCounts sc = empty | otherwise = text "To see detailed counts use -ddump-simpl-stats" freeTick :: Tick -> SimplM () -- Record a tick, but don't add to the total tick count, which is -- used to decide when nothing further has happened freeTick t = SM (\_st_env us sc -> let sc' = doFreeSimplTick t sc in sc' `seq` return ((), us, sc'))
GaloisInc/halvm-ghc
compiler/simplCore/SimplMonad.hs
Haskell
bsd-3-clause
7,734
{-# LANGUAGE BangPatterns, PatternGuards #-} module SECDH.Eval ( secdhEval , secdhInit , secdhInitProgram , secdhFinish , secdhEvalStats , secdhFinishStats , secdhIter , Rule (..) ) where --import Debug.Trace import Language.Slambda.Types import Language.Slambda.Show import Language.Slambda.Util import SECDH.Types import SECDH.Show import Control.Monad import Data.Bits (shiftL, shiftR) import Data.Char import Data.List import Data.Monoid import Data.Map (Map, (!)) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Sequence (Seq, (|>)) import qualified Data.Sequence as Seq secdhStats :: SECDH -> Rule -> SECDHStats secdhStats (SECDH s e c d h) r = SECDHStats { secdhStatsIters = 1 , secdhStatsMaxStack = length s , secdhStatsMaxEnv = Map.size e , secdhStatsMaxControl = length c , secdhStatsMaxDump = length d , secdhStatsMaxHeap = Seq.length h , secdhStatsMaxRetained = 0 , secdhStatsGCs = 0 , secdhStatsRuleExecs = Map.singleton r 1 } emptyEnv :: Env emptyEnv = Map.empty emptyHeap :: Heap emptyHeap = Seq.empty loopA :: Atom loopA = ErrorA "loop" termToClosure :: Term -> Atom termToClosure (AbsT s i t) = ClosureA emptyEnv s i t termToClosure t = error $ "cannot make closure from non-abstraction term: " ++ termToString t trueA, falseA :: Atom trueA = termToClosure trueT falseA = termToClosure falseT pruneEnv :: Term -> Env -> Env pruneEnv t = let vs = freeVars t in Map.filterWithKey (\v n -> Set.member v vs) mkClosure :: Env -> Strictness -> Var -> Term -> Atom mkClosure e s i t = ClosureA (pruneEnv t e) s i t mkObject :: Env -> Term -> Object mkObject _ (ConstT k) = AtomOb (ConstA k) mkObject _ (PrimT p) = AtomOb (primToAtom p) mkObject e (AbsT s i t) = AtomOb (mkClosure e s i t) mkObject e t = SuspOb (pruneEnv t e) t primToAtom :: Prim -> Atom primToAtom IOReadP = IOActionA ReadIO primToAtom p = PrimA p [] primArity :: Prim -> Arity primArity IOReturnP = 1 primArity IOBindP = 2 primArity IOReadP = 0 primArity IOWriteP = 1 primArity UnitPP = 1 primArity IntegerPP = 1 primArity LambdaPP = 1 primArity NegP = 1 primArity SuccP = 1 primArity PredP = 1 primArity Mul2P = 1 primArity Div2P = 1 primArity ZeroPP = 1 primArity PosPP = 1 primArity EvenPP = 1 primArity OddPP = 1 primArity AddP = 2 primArity SubP = 2 primArity MulP = 2 primArity DivP = 2 primArity ModP = 2 primArity EqPP = 2 primArity ChrP = 1 primArity OrdP = 1 invalidPrimAppError :: Prim -> [Atom] -> Atom invalidPrimAppError p xs = ErrorA ("invalid application of primitive %" ++ primName p ++ " to arguments " ++ concat (intersperse ", " (map atomToString xs))) applyPrim :: Prim -> [Atom] -> Atom applyPrim p xs | length xs /= primArity p = error $ "invalid number of arguments (" ++ show (length xs) ++ ") supplied for primitive " ++ primName p applyPrim IOReturnP [a] = IOActionA (ReturnIO a) applyPrim IOBindP [ErrorA s, _] = ErrorA s applyPrim IOBindP [ConstA BottomC, _] = ConstA BottomC applyPrim IOBindP [IOActionA io, a] = IOActionA (BindIO io a) applyPrim IOBindP xs = invalidPrimAppError IOBindP xs -- the remaining primitives are strict in both arguments applyPrim _ args | Just a <- find (\a -> case a of ErrorA _ -> True; _ -> False) args = a applyPrim _ args | Just a <- find (\a -> case a of ConstA BottomC -> True; _ -> False) args = a applyPrim IOWriteP [ConstA (CharC ch)] = IOActionA (WriteIO ch) applyPrim UnitPP [ConstA UnitC] = trueA applyPrim UnitPP [_] = falseA applyPrim IntegerPP [ConstA (IntegerC _)] = trueA applyPrim IntegerPP [_] = falseA applyPrim LambdaPP [ClosureA _ _ _ _] = trueA applyPrim LambdaPP [PrimA p args] | primArity p - length args > 0 = trueA applyPrim LambdaPP [_] = falseA applyPrim NegP [ConstA (IntegerC x)] = ConstA (IntegerC (negate x)) applyPrim SuccP [ConstA (IntegerC x)] = ConstA (IntegerC (succ x)) applyPrim PredP [ConstA (IntegerC x)] = ConstA (IntegerC (pred x)) applyPrim Mul2P [ConstA (IntegerC x)] = ConstA (IntegerC (x * 2)) applyPrim Div2P [ConstA (IntegerC x)] = ConstA (IntegerC (x `div` 2)) applyPrim ZeroPP [ConstA (IntegerC 0)] = trueA applyPrim ZeroPP [_] = falseA applyPrim PosPP [ConstA (IntegerC n)] | n > 0 = trueA applyPrim PosPP [_] = falseA applyPrim EvenPP [ConstA (IntegerC n)] | even n = trueA applyPrim EvenPP [_] = falseA applyPrim OddPP [ConstA (IntegerC n)] | odd n = trueA applyPrim OddPP [_] = falseA applyPrim AddP [ConstA (IntegerC x), ConstA (IntegerC y)] = ConstA (IntegerC (x + y)) applyPrim SubP [ConstA (IntegerC x), ConstA (IntegerC y)] = ConstA (IntegerC (x - y)) applyPrim MulP [ConstA (IntegerC x), ConstA (IntegerC y)] = ConstA (IntegerC (x * y)) applyPrim DivP [ConstA (IntegerC x), ConstA (IntegerC y)] = ConstA (IntegerC (x `div` y)) applyPrim ModP [ConstA (IntegerC x), ConstA (IntegerC y)] = ConstA (IntegerC (x `mod` y)) applyPrim EqPP [ConstA (IntegerC x), ConstA (IntegerC y)] | x == y = trueA applyPrim EqPP [ConstA (CharC x), ConstA (CharC y)] | x == y = trueA applyPrim EqPP [ConstA UnitC, ConstA UnitC] = trueA applyPrim EqPP [_, _] = falseA applyPrim ChrP [ConstA (IntegerC n)] = ConstA (CharC (chr (fromInteger n))) applyPrim OrdP [ConstA (CharC c)] = ConstA (IntegerC (toInteger (ord c))) applyPrim p xs = invalidPrimAppError p xs secdhEval :: MonadSECDHIO m => Program -> m Atom secdhEval = liftM snd . secdhFinish . secdhGC . secdhInitProgram secdhEvalStats :: MonadSECDHIO m => Program -> m (Atom, SECDHStats) secdhEvalStats = liftM (\(_, r, s) -> (r, s)) . secdhFinishStats . secdhGC . secdhInitProgram secdhInit :: Env -> Heap -> Term -> SECDH secdhInit e h t = SECDH { secdhStack = [] , secdhEnv = e , secdhControl = [TermI t] , secdhDump = [] , secdhHeap = h } secdhInitProgram :: Program -> SECDH secdhInitProgram prog = secdhInit emptyEnv emptyHeap (LetRecT prog (VarT (Var mainProgramName))) secdhGCFactor = 4 secdhGCInitLimit = 1024 secdhFinish :: MonadSECDHIO m => SECDH -> m (SECDH, Atom) secdhFinish = secdhFinish' secdhGCInitLimit where secdhFinish' !gcLim !secdh = do (secdh', _, mbResult) <- secdhIter secdh case mbResult of Just r -> return (secdh', r) Nothing -> if Seq.length (secdhHeap secdh') > gcLim then let secdh'' = secdhGC secdh' gcLim' = max gcLim (secdhGCFactor * Seq.length (secdhHeap secdh'')) in --trace ("Retained: " ++ show (Seq.length (secdhHeap secdh'')) ++ "\nGC Limit: " ++ show gcLim') $ secdhFinish' gcLim' secdh'' else secdhFinish' gcLim secdh' secdhFinishStats :: MonadSECDHIO m => SECDH -> m (SECDH, Atom, SECDHStats) secdhFinishStats = secdhFinishStats' mempty secdhGCInitLimit where secdhFinishStats' !stats !gcLim secdh = do (secdh', rule, mbResult) <- secdhIter secdh case mbResult of Just r -> return (secdh', r, stats) Nothing -> if Seq.length (secdhHeap secdh') > gcLim then let !secdh'' = secdhGC secdh' !gcLim' = max gcLim (secdhGCFactor * Seq.length (secdhHeap secdh'')) !stats' = stats { secdhStatsGCs = succ (secdhStatsGCs stats) , secdhStatsMaxRetained = max (secdhStatsMaxRetained stats) (Seq.length (secdhHeap secdh'')) } in secdhFinishStats' (mappend stats' (secdhStats secdh rule)) gcLim' secdh'' else secdhFinishStats' (mappend stats (secdhStats secdh rule)) gcLim secdh' secdhApplyNonFunctionError :: String -> Atom secdhApplyNonFunctionError s = ErrorA (s ++ " is not a function, but treated as one") invalidSECDHState :: SECDH -> a invalidSECDHState secdh = error $ "invalid secdh state:\n" ++ secdhToString secdh secdhIter :: MonadSECDHIO m => SECDH -> m (SECDH, Rule, Maybe Atom) -- Perform IO secdhIter secdh@(SECDH [AtomV (IOActionA io)] _ [] [] h) = case io of ReturnIO a -> return ( secdh , Rule 1 , Just a ) BindIO io a -> return ( SECDH [AtomV (IOActionA io),AtomV a] emptyEnv [IOBindI] [] h , Rule 2 , Nothing ) ReadIO -> do mbc <- secdhRead return ( SECDH [AtomV (ConstA (maybe UnitC CharC mbc))] emptyEnv [] [] h , Rule 3 , Nothing ) WriteIO ch -> do secdhWrite ch return ( SECDH [AtomV (ConstA UnitC)] emptyEnv [] [] h , Rule 4 , Nothing ) -- Termination condition. secdhIter secdh@(SECDH [v@(AtomV a)] _ [] [] _) = return ( secdh , Rule 5 , Just a ) -- Pop off the dump stack when a sub-computation is completed. secdhIter (SECDH [v] _ [] ((s', e', c'):d') h) = return ( SECDH (v:s') e' c' d' h , Rule 6 , Nothing ) -- If a pointer is all that's left, dereference it and, if necessary, -- set up an update and enter a suspension. secdhIter (SECDH [PointerV n] e [] [] h) | n < Seq.length h = case Seq.index h n of AtomOb a -> return ( SECDH [AtomV a] e [] [] h , Rule 7 , Nothing ) SuspOb e' t -> return ( SECDH [] e' [TermI t] [([],e,[UpdateI n])] (Seq.update n UpdatingOb h) , Rule 8 , Nothing ) IndirOb n' -> return ( SECDH [PointerV n'] e [] [] h , Rule 9 , Nothing ) UpdatingOb -> return ( SECDH [AtomV loopA] e [] [] h , Rule 10 , Nothing ) secdhIter (SECDH (PointerV n:s) e (IOBindI:c) [] h) = case Seq.index h n of AtomOb a -> return ( SECDH (AtomV a:s) e (IOBindI:c) [] h , Rule 11 , Nothing ) SuspOb e' t -> return ( SECDH [] e' [TermI t] [(s,e,UpdateI n:IOBindI:c)] (Seq.update n UpdatingOb h) , Rule 12 , Nothing ) IndirOb n' -> return ( SECDH (PointerV n':s) e (IOBindI:c) [] h , Rule 13 , Nothing ) UpdatingOb -> return ( SECDH (AtomV loopA:s) e (IOBindI:c) [] h , Rule 14 , Nothing ) secdhIter (SECDH (AtomV (IOActionA io):s) e (IOBindI:c) [] h) = case io of ReturnIO a -> return ( SECDH (AtomV a:s) e (ApI True:c) [] h , Rule 15 , Nothing ) BindIO io a -> return ( SECDH (AtomV (IOActionA io):AtomV a:s) e (IOBindI:IOBindI:c) [] h , Rule 16 , Nothing ) ReadIO -> do mbc <- secdhRead return ( SECDH (AtomV (ConstA (maybe UnitC CharC mbc)):s) e (ApI True:c) [] h , Rule 17 , Nothing ) WriteIO ch -> do secdhWrite ch return ( SECDH (AtomV (ConstA UnitC):s) e (ApI True:c) [] h , Rule 18 , Nothing ) secdhIter (SECDH (AtomV (ErrorA r):s) e (IOBindI:c) [] h) = return ( SECDH (AtomV (ErrorA r):s) e (ApI True:c) [] h , Rule 19 , Nothing ) secdhIter (SECDH (AtomV (ConstA BottomC):s) e (IOBindI:c) [] h) = return ( SECDH (AtomV (ConstA BottomC):s) e (ApI True:c) [] h , Rule 20 , Nothing ) secdhIter (SECDH (AtomV a:s) e (IOBindI:c) [] h) = return ( SECDH (AtomV (ErrorA ("trying to leave io monad; result was: " ++ atomToString a)):s) e (ApI True:c) [] h , Rule 21 , Nothing ) -- Handle tail calls. secdhIter (SECDH [f,x] e [ApI False] ((s', e', c'):d) h) = return ( SECDH (f:x:s') e' (ApI False:c') d h , Rule 22 , Nothing ) -- If the next instruction is UpdateI, and we have an atom, then -- update the heap and pop the instruction secdhIter (SECDH s@(AtomV a:_) e (UpdateI n:c) d h) = return ( SECDH s e c d (Seq.update n (AtomOb a) h) , Rule 23 , Nothing ) -- If the next instruction is UpdateI, and we have a pointer: -- If the pointer is to an atom, just replace the pointer with the atom -- (the next iteration will do the update). -- If the pointer is to a suspension, then replace the suspension being pointed to by an indirection -- to the block being updated, and enter the suspension (this prevents a chain of updates from piling up on the C stack). -- If the pointer is already being updated, we're in a loop. secdhIter (SECDH (PointerV n:s) e c@(UpdateI u:c') d h) | n < Seq.length h = case Seq.index h n of AtomOb a -> return ( SECDH (AtomV a:s) e c d h , Rule 24 , Nothing ) SuspOb e' t -> return ( SECDH [] e' [TermI t] ((s,e,c):d) (Seq.update n (IndirOb u) h) , Rule 25 , Nothing ) IndirOb r -> return ( SECDH (PointerV r:s) e c d (Seq.update n (IndirOb u) h) , Rule 26 , Nothing ) UpdatingOb -> return ( SECDH (AtomV loopA:s) e c d h , Rule 27 , Nothing ) -- If the next instruction is TermI, move the term onto the stack, -- making abstractions into closures, and pushing ApI instructions for -- applications. -- LetRec creates a suspension in the updated environment. secdhIter (SECDH s e (TermI t:c) d h) | VarT i <- t = do let v = case Map.lookup i e of Just n -> PointerV n Nothing -> AtomV (ErrorA ("undefined variable: " ++ varName i)) return ( SECDH (v:s) e c d h , Rule 28 , Nothing ) | ConstT k <- t = return ( SECDH (AtomV (ConstA k):s) e c d h , Rule 29 , Nothing ) | PrimT p <- t = return ( SECDH (AtomV (primToAtom p):s) e c d h , Rule 30 , Nothing ) | AbsT a i t' <- t = do return ( SECDH (AtomV (mkClosure e a i t'):s) e c d h , Rule 31 , Nothing ) | AppT f x <- t = return ( SECDH (PointerV (Seq.length h):s) e (TermI f:ApI False:c) d (h |> mkObject e x) , Rule 32 , Nothing ) | LetRecT ds t' <- t = do let e' = foldl (flip (uncurry Map.insert)) e (zip (map fst ds) (enumFrom (Seq.length h))) h' = foldl (|>) h (map (mkObject e' . snd) ds) return ( SECDH (PointerV (Seq.length h'):s) e c d (h' |> mkObject e' t') , Rule 33 , Nothing ) -- Apply a function. If the function is a non-strict closure, just -- make an updated environment and heap for the argument, and enter -- the function after pushing the current state on the dump. The -- function is strict, swap the top 2 stack positions, and replace the -- (ApI False) instruction with an (ApI True) instruction. If the -- function is a pointer, deference the pointer and enter the -- suspension if necessary. secdhIter (SECDH (f:x:s) e (ApI False:c) d h) | AtomV (ErrorA str) <- f = return ( SECDH (f:s) e c d h , Rule 34 , Nothing ) | AtomV (ConstA BottomC) <- f = return ( SECDH (AtomV (ConstA BottomC):s) e c d h , Rule 35 , Nothing ) | AtomV (ConstA k) <- f = return ( SECDH (AtomV (secdhApplyNonFunctionError (constToString k)):s) e c d h , Rule 36 , Nothing ) | AtomV (PrimA p []) <- f, primArity p < 1 = return ( SECDH (AtomV (secdhApplyNonFunctionError ('%':primName p)):s) e c d h , Rule 37 , Nothing ) | AtomV (IOActionA io) <- f = return ( SECDH (AtomV (secdhApplyNonFunctionError (ioActionToString io)):s) e c d h , Rule 38 , Nothing ) | AtomV (PrimA p _) <- f, primArity p >= 1 = return ( SECDH (x:f:s) e (ApI True:c) d h , Rule 39 , Nothing ) | AtomV (ClosureA e False i t) <- f = do let (e', h') = case x of AtomV xA -> (Map.insert i (Seq.length h) e, h |> AtomOb xA) PointerV n -> (Map.insert i n e, h) return ( SECDH [] e' [TermI t] ((s,e,c):d) h' , Rule 40 , Nothing ) | AtomV (ClosureA e True i t) <- f = return ( SECDH (x:f:s) e (ApI True:c) d h , Rule 41 , Nothing ) | PointerV n <- f, n < Seq.length h = case Seq.index h n of AtomOb f' -> return ( SECDH (AtomV f':x:s) e (ApI False:c) d h , Rule 42 , Nothing ) SuspOb e' t' -> return ( SECDH [] e' [TermI t'] ((x:s,e,UpdateI n:ApI False:c):d) h , Rule 43 , Nothing ) IndirOb n' -> return ( SECDH (PointerV n':x:s) e (UpdateI n:ApI False:c) d h , Rule 44 , Nothing ) UpdatingOb -> return ( SECDH (AtomV loopA:s) e c d h , Rule 45 , Nothing ) -- Apply a strict function. If the argument is a pointer, deference it -- and, if necessary, set up the update and enter the suspension. secdhIter (SECDH (x:f:s) e (ApI True:c) d h) | PointerV n <- x, n < Seq.length h = case Seq.index h n of AtomOb xA -> return ( SECDH (AtomV xA:f:s) e (ApI True:c) d h , Rule 46 , Nothing ) SuspOb e' t' -> return ( SECDH [] e' [TermI t'] ((f:s,e,UpdateI n:ApI True:c):d) h , Rule 47 , Nothing ) IndirOb n' -> return ( SECDH (PointerV n':f:s) e (UpdateI n:ApI True:c) d h , Rule 48 , Nothing ) UpdatingOb -> return ( SECDH (AtomV loopA:s) e c d h , Rule 49 , Nothing ) | AtomV (ErrorA str) <- x = return ( SECDH (x:s) e c d h , Rule 50 , Nothing ) | AtomV xA <- x, AtomV (PrimA p args) <- f = if 1 + length args == primArity p then return ( SECDH (AtomV (applyPrim p (reverse (xA:args))):s) e c d h , Rule 51 , Nothing ) else return ( SECDH (AtomV (PrimA p (xA:args)):s) e c d h , Rule 52 , Nothing ) | AtomV xA <- x, AtomV (ClosureA e _ i t) <- f = return ( SECDH [] (Map.insert i (Seq.length h) e) [TermI t] ((s,e,c):d) (h |> AtomOb xA) , Rule 53 , Nothing ) -- Should never, ever, ever, ever get here. -- Ever. secdhIter secdh = invalidSECDHState secdh secdhGC :: SECDH -> SECDH secdhGC secdh@(SECDH s e c d h) = let ns = sRefs s ++ eRefs e ++ cRefs c ++ dRefs d (m, h') = copy ns h in SECDH (remaps m s) (remape m e) (remapc m c) (remapd m d) (remaph m h') where atomRefs :: Atom -> [Addr] atomRefs (PrimA _ args) = args >>= atomRefs atomRefs (ClosureA e _ _ _) = eRefs e atomRefs (IOActionA io) = ioRefs io atomRefs _ = mzero ioRefs (ReturnIO a) = atomRefs a ioRefs (BindIO io a) = ioRefs io `mplus` atomRefs a ioRefs _ = mzero sRefs :: Stack -> [Addr] sRefs s = do v <- s case v of AtomV a -> atomRefs a PointerV n -> return n eRefs :: Env -> [Addr] eRefs e = Map.elems e cRefs :: Control -> [Addr] cRefs c = do i <- c case i of UpdateI n -> return n _ -> mzero dRefs :: Dump -> [Addr] dRefs d = do (s,e,c) <- d sRefs s `mplus` eRefs e `mplus` cRefs c copy :: [Addr] -> Heap -> (Map Addr Addr, Heap) copy = let copy' :: Map Addr Addr -> Heap -> [Addr] -> Heap -> (Map Addr Addr, Heap) copy' m hn nos ho = case nos of [] -> (m, hn) no:nos' -> case Map.lookup no m of Just _ -> copy' m hn nos' ho Nothing -> let nn = Seq.length hn o = Seq.index h no m' = Map.insert no nn m hn' = hn |> o in case Seq.index ho no of SuspOb e _ -> copy' m' hn' (Map.elems e ++ nos') ho IndirOb po -> case Map.lookup po m of Just pn -> copy' (Map.insert no pn m) hn nos' ho Nothing -> copy' m hn (po:no:nos') ho AtomOb a -> copy' m' hn' (atomRefs a ++ nos') ho o -> copy' m' hn' nos' ho in copy' Map.empty Seq.empty remapio :: Map Addr Addr -> IOAction -> IOAction remapio m (ReturnIO a) = ReturnIO (remapAtom m a) remapio m (BindIO io a) = BindIO (remapio m io) (remapAtom m a) remapio _ io = io remapAtom :: Map Addr Addr -> Atom -> Atom remapAtom m (PrimA p args) = PrimA p (map (remapAtom m) args) remapAtom m (IOActionA io) = IOActionA (remapio m io) remapAtom m (ClosureA e s i t) = ClosureA (remape m e) s i t remapAtom _ a = a remaps :: Map Addr Addr -> Stack -> Stack remaps m = map $ \v -> case v of AtomV a -> AtomV (remapAtom m a) PointerV n -> PointerV (m ! n) remape :: Map Addr Addr -> Env -> Env remape m = Map.map (m!) remapc :: Map Addr Addr -> Control -> Control remapc m = map $ \i -> case i of UpdateI n -> UpdateI (m ! n) _ -> i remapd :: Map Addr Addr -> Dump -> Dump remapd m = map $ \(s, e, c) -> (remaps m s, remape m e, remapc m c) remaph :: Map Addr Addr -> Heap -> Heap remaph m = fmap $ \o -> case o of AtomOb a -> AtomOb (remapAtom m a) SuspOb e t -> SuspOb (remape m e) t IndirOb p -> IndirOb (m ! p) _ -> o
pgavin/secdh
lib/SECDH/Eval.hs
Haskell
bsd-3-clause
23,297
module Main where putStr str = case str of [ ] -> return () c : cs -> putChar c >> putStr cs putStrLn str = putStr str >> putChar '\n' main = putStrLn "Hello, world!"
YoshikuniJujo/toyhaskell_haskell
examples/hello.hs
Haskell
bsd-3-clause
172
-- | -- Module : Main -- Copyright : Jared Tobin 2012 -- License : BSD3 -- -- Maintainer : jared@jtobin.ca -- Stability : experimental -- Portability : unknown {-# OPTIONS_GHC -Wall #-} module Main where import Kospi import Control.Monad (forever, when) import Control.Monad.Trans (lift) import Control.Pipe import Data.Attoparsec.ByteString as A hiding (take) import Data.ByteString (ByteString) import Data.Maybe (fromMaybe) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Time import Data.Time.Clock.POSIX import Network.Pcap import Options.Applicative hiding (Parser) import qualified Options.Applicative as Options import System.Exit (exitSuccess) default (ByteString, Int) -- | Parse command line arguments and run the pcap parser accordingly. main :: IO () main = execParser opts >>= entry where opts = info (helper <*> options) ( fullDesc <> progDesc "Parse a pcap file according to spec." <> header "A Kospi Quote Parser" ) -- Argument parsing ------------------------------------------------------------ -- | Options consist of the target pcap dump file and the optional reorder flag. data Options = Options { reorder :: Bool, dumpFile :: FilePath } -- | An options parser. options :: Options.Parser Options options = Options <$> switch ( short 'r' <> long "reorder" <> help "Reorder quotes by accept time." ) <*> argument str (metavar "PCAPFILE") -- | Enter the program's IO pipeline. entry :: Options -> IO () entry (Options r d) = do d0 <- openOffline d runPipe $ yieldPackets d0 >+> extractQuotes >+> if r then sortingBuffer >+> printer else printer -- IO pipeline ----------------------------------------------------------------- -- | Yield the contents of a handle, terminating upon reaching an empty packet. -- Note that this should also work for live captures, though that's untested. yieldPackets :: PcapHandle -> Producer (PktHdr, ByteString) IO b yieldPackets handle = forever $ lift (nextBS handle) >>= yield -- | Yield only quote packets, according to spec. extractQuotes :: Monad m => Pipe (PktHdr, ByteString) (Maybe Quote) m b extractQuotes = forever $ do (hdr, payload) <- await when (hdrCaptureLength hdr == 0) $ yield Nothing case A.parse (quote (hdrUTCTime hdr)) payload of Fail {} -> return () Done _ r -> yield (Just r) Partial _ -> error $ "failed to filter quote packets (pcap stream " ++ "has likely ended or been corrupted)" -- | Await quotes and hold them in a 3-second buffer. If upstream yields a -- Nothing, flush the buffer and exit gracefully. sortingBuffer :: Pipe (Maybe Quote) (Maybe Quote) IO () sortingBuffer = go Map.empty where go buffer = await >>= \maybeQ -> case maybeQ of Nothing -> flush buffer Just q -> let buffer0 = Map.insert (hashTimes q) q buffer (minq, buffer1) = bufferMin buffer0 (maxq, _ ) = bufferMax buffer0 in if abs (pktTime maxq `diffUTCTime` acceptTime minq) > 3 then yield (Just minq) >> go buffer1 else go buffer0 -- | Flush a buffer. flush :: Monad m => Map k a -> Pipe b (Maybe a) m () flush b | Map.null b = yield Nothing | otherwise = (\(m, r) -> yield (Just m) >> flush r) (bufferMin b) -- | Await Maybes and print Justs to stdout. If a Nothing is received, exit the -- program gracefully. printer :: Show a => Consumer (Maybe a) IO b printer = forever $ await >>= \x -> case x of Nothing -> lift exitSuccess Just q -> (lift . print) q -- Utilities ------------------------------------------------------------------- -- | The minimum element of a buffer. bufferMin :: Map k a -> (a, Map k a) bufferMin b = fromMaybe (error buffError) (Map.minView b) -- | The maximum element of a buffer. bufferMax :: Map k a -> (a, Map k a) bufferMax b = fromMaybe (error buffError) (Map.maxView b) -- | Standard error to throw if a buffer behaves unexpectedly. buffError :: String buffError = "failed to buffer quote packets (pcap stream has likely been " ++ "corrupted)" -- | Convert a packet header's timestamp to UTC. hdrUTCTime :: PktHdr -> UTCTime hdrUTCTime = posixSecondsToUTCTime . realToFrac . hdrDiffTime -- | Create a unique key for packet/accept times. hashTimes :: Quote -> String hashTimes q = show (utcToInteger (acceptTime q)) ++ show (utcToInteger (pktTime q)) -- | Convert a UTC time to Integer (required to avoid overflow on 32-bit -- systems). utcToInteger :: UTCTime -> Integer utcToInteger t = truncate $ utcTimeToPOSIXSeconds t * 10^(6 :: Int)
jtobin/prompt-pcap
Main.hs
Haskell
bsd-3-clause
4,897
{-# OPTIONS_GHC -XFlexibleInstances #-} module Database.CouchDB.Tests ( main, allTests) where import Control.Monad.Trans (liftIO) import Control.Exception (finally) import Test.HUnit import Database.CouchDB import Database.CouchDB.JSON import Text.JSON -- ---------------------------------------------------------------------------- -- Helper functions -- assertDBEqual :: (Eq a, Show a) => String -> a -> CouchMonad a -> Assertion assertDBEqual msg v m = do v' <- runCouchDB' m assertEqual msg v' v instance Assertable (Either String a) where assert (Left s) = assertFailure s assert (Right _) = return () assertRight :: (Either String a) -> IO a assertRight (Left s) = assertFailure s >> fail "assertion failed" assertRight (Right a) = return a instance Assertable (Maybe a) where assert Nothing = assertFailure "expected (Just ...), got Nothing" assert (Just a) = return () assertJust :: Maybe a -> IO a assertJust (Just v) = return v assertJust Nothing = do assertFailure "expected (Just ...), got Nothing" fail "assertion failed" testWithDB :: String -> (DB -> CouchMonad Bool) -> Test testWithDB testDescription testCase = TestLabel testDescription $ TestCase $ do let action = runCouchDB' $ do createDB "haskellcouchdbtest" result <- testCase (db "haskellcouchdbtest") liftIO $ assertBool testDescription result let teardown = runCouchDB' (dropDB "haskellcouchdbtest") let failure _ = assertFailure (testDescription ++ "; exception signalled") action `catch` failure `finally` teardown main = do putStrLn "Running CouchDB test suite..." runTestTT allTests putStrLn "Testing complete." return () -- ----------------------------------------------------------------------------- -- Data definitions for testing -- data Age = Age { ageName :: String , ageValue :: Int } deriving (Eq,Show) instance JSON Age where showJSON (Age name val) = JSObject $ toJSObject [ ("name", showJSON name) , ("age", showJSON val) ] readJSON val = do obj <- jsonObject val name <- jsonField "name" obj age <- jsonField "age" obj return (Age name age) -- ---------------------------------------------------------------------------- -- Test cases -- testCreate = TestCase $ assertDBEqual "create/drop database" True $ do createDB "test1" dropDB "test1" -- returns True since the database exists. people = [ Age "Arjun" 18, Age "Alex" 17 ] testNamedDocs = testWithDB "add named documents" $ \mydb -> do newNamedDoc mydb (doc "arjun") (people !! 0) newNamedDoc mydb (doc "alex") (people !! 1) Just (_,_,v1) <- getDoc mydb (doc "arjun") Just (_,_,v2) <- getDoc mydb (doc "alex") return $ (v1 == people !! 0) && (v2 == people !! 1) allTests = TestList [ testCreate, testNamedDocs ]
astro/haskell-couchdb
src/Database/CouchDB/Tests.hs
Haskell
bsd-3-clause
2,815
module PFDS.Sec5.Ex8a where import PFDS.Commons.PairingHeap (PairingHeap (..)) data BinTree e = E' | T' e (BinTree e) (BinTree e) deriving (Show) toBinary :: PairingHeap e -> BinTree e toBinary E = E' toBinary (T e []) = T' e E' E' toBinary (T e (h1:hs)) = T' e (toBinary h1) (unloop hs) where unloop [] = E' unloop (E:_) = error "invalid" unloop (T e' hs':hs'') = T' e' (unloop hs') (unloop hs'') {-| Doctests for PairingHeap >>> (print . foldl (flip insert) (empty::PairingHeap Int)) [1..5] T 1 [T 5 [],T 4 [],T 3 [],T 2 []] >>> (print . toBinary . foldl (flip insert) (empty::PairingHeap Int)) [1..5] T' (Just 1) (T' Nothing (T' Nothing (T' (Just 5) E' E') (T' (Just 4) E' E')) (T' Nothing (T' (Just 3) E' E') (T' (Just 2) E' E'))) E' -}
matonix/pfds
src/PFDS/Sec5/Ex8a.hs
Haskell
bsd-3-clause
777
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-} module Test.Type( sleep, sleepFileTime, sleepFileTimeCalibrate, testBuildArgs, testBuild, testSimple, testNone, shakeRoot, defaultTest, hasTracker, notCI, notWindowsCI, notMacCI, copyDirectoryChanged, copyFileChangedIO, assertWithin, assertBool, assertBoolIO, assertException, assertExceptionAfter, assertContents, assertContentsUnordered, assertContentsWords, assertContentsInfix, assertExists, assertMissing, assertTimings, (===), (&?%>), Pat(PatWildcard), pat, BinarySentinel(..), RandomType(..), ) where import Development.Shake import Development.Shake.Classes import Development.Shake.Forward import Development.Shake.Internal.FileName import General.Extra import Development.Shake.Internal.FileInfo import Development.Shake.FilePath import Development.Shake.Internal.Paths import Control.Exception.Extra import Control.Monad.Extra import Data.List.Extra import Text.Read(readMaybe) import Data.Maybe import Data.Either import Data.Typeable import System.Directory.Extra as IO import System.Environment import System.Random import General.GetOpt import System.IO.Extra as IO import System.Time.Extra import System.Info.Extra testBuildArgs :: (([String] -> IO ()) -> IO ()) -- ^ The test driver -> [OptDescr (Either String a)] -- ^ Arguments the test can accept -> ([a] -> Rules ()) -- ^ The Shake script under test -> IO () -- ^ Sleep function, driven by passing @--sleep@ -> IO () testBuildArgs f opts g = shakenEx False opts f (\os args -> if null args then g os else want args >> withoutActions (g os)) testBuild :: (([String] -> IO ()) -> IO ()) -- ^ The test driver -> Rules () -- ^ The Shake script under test -> IO () -- ^ Sleep function, driven by passing @--sleep@ -> IO () testBuild f g = testBuildArgs f [] (const g) testSimple :: IO () -> IO () -> IO () testSimple act = testBuild (const act) (pure ()) testNone :: IO () -> IO () testNone _ = pure () shakenEx :: Bool -> [OptDescr (Either String a)] -> (([String] -> IO ()) -> IO ()) -> ([a] -> [String] -> Rules ()) -> IO () -> IO () shakenEx reenter options test rules sleeper = do initDataDirectory name:args <- getArgs putStrLn $ "## BUILD " ++ unwords (name:args) let forward = "--forward" `elem` args args <- pure $ delete "--forward" args let out = "output/" ++ name ++ "/" let change = if not reenter then withCurrentDirectory out else id let clean = do now <- getCurrentDirectory when (takeBaseName now /= name) $ fail $ "Clean went horribly wrong! Dangerous deleting: " ++ show now withCurrentDirectory (now </> "..") $ do removePathForcibly now createDirectoryRecursive now unless reenter $ createDirectoryRecursive out case args of "test":_ -> do putStrLn $ "## TESTING " ++ name change $ test (\args -> withArgs (name:args) $ shakenEx True options test rules sleeper) putStrLn $ "## FINISHED TESTING " ++ name "clean":args -> do when (args /= []) $ fail "Unexpected additional arguments to 'clean'" change clean "perturb":args -> forever $ do del <- removeFilesRandom out threads <- randomRIO (1,4) putStrLn $ "## TESTING PERTURBATION (" ++ show del ++ " files, " ++ show threads ++ " threads)" shake shakeOptions{shakeFiles=out, shakeThreads=threads, shakeVerbosity=Error} $ rules [] args args -> change $ do t <- tracker opts <- pure shakeOptions{shakeFiles = "."} cwd <- getCurrentDirectory opts <- pure $ if forward then forwardOptions opts{shakeLintInside=[""]} else opts {shakeLint = Just t ,shakeLintInside = [cwd </> ".." </> ".."] ,shakeLintIgnore = [".cabal-sandbox/**",".stack-work/**","../../.stack-work/**"]} withArgs args $ do let optionsBuiltin = optionsEnumDesc [(Clean, "Clean before building.") ,(Sleep, "Pause before executing.") ,(UsePredicate, "Use &?> in preference to &%>")] shakeArgsOptionsWith opts (optionsBuiltin `mergeOptDescr` options) $ \so extra files -> do let (extra1, extra2) = partitionEithers extra when (Clean `elem` extra1) clean when (Sleep `elem` extra1) sleeper so <- pure $ if UsePredicate `notElem` extra1 then so else so{shakeExtra = addShakeExtra UsePredicateYes $ shakeExtra so} if "clean" `elem` files then clean >> pure Nothing else pure $ Just $ (,) so $ do -- if you have passed sleep, suppress the "no actions" warning when (Sleep `elem` extra1) $ action $ pure () rules extra2 files data Flags = Clean -- ^ Clean all the files before starting | Sleep -- ^ Call 'sleepFileTimeCalibrate' before starting | UsePredicate -- ^ Use &?> in preference to &%> deriving (Eq,Show) data UsePredicateYes = UsePredicateYes deriving Typeable (&?%>) :: [FilePattern] -> ([FilePath] -> Action ()) -> Rules () deps &?%> act = do so :: Maybe UsePredicateYes <- getShakeExtraRules if isJust so then (\x -> if x `elem` deps then Just deps else Nothing) &?> act else deps &%> act -- A way to get back to the source files after you get directory changed shakeRoot :: FilePath shakeRoot = "../.." tracker :: IO Lint tracker = do fsatrace <- findExecutable $ "fsatrace" <.> exe -- Tracking on a Mac is pretty unreliable pure $ if not isMac && isJust fsatrace then LintFSATrace else LintBasic -- Tests that don't currently work on CI notCI :: IO () -> IO () notCI act = do b <- lookupEnv "CI" when (isNothing b) act -- Tests that don't currently work on Windows CI notWindowsCI :: IO () -> IO () notWindowsCI = if isWindows then notCI else id -- Tests that don't currently work on Mac CI notMacCI :: IO () -> IO () notMacCI = if isMac then notCI else id hasTracker :: IO Bool hasTracker = do t <- tracker pure $ t == LintFSATrace assertFail :: String -> IO a assertFail msg = error $ "ASSERTION FAILED: " ++ msg assertBool :: Bool -> String -> IO () assertBool b msg = unless b $ assertFail msg assertBoolIO :: IO Bool -> String -> IO () assertBoolIO b msg = do b <- b; assertBool b msg infix 4 === (===) :: (Show a, Eq a) => a -> a -> IO () a === b = assertBool (a == b) $ "failed in ===\nLHS: " ++ show a ++ "\nRHS: " ++ show b assertExists :: FilePath -> IO () assertExists file = do b <- IO.doesFileExist file assertBool b $ "File was expected to exist, but is missing: " ++ file assertMissing :: FilePath -> IO () assertMissing file = do b <- IO.doesFileExist file assertBool (not b) $ "File was expected to be missing, but exists: " ++ file assertWithin :: Seconds -> IO a -> IO a assertWithin n act = do t <- timeout n act case t of Nothing -> assertFail $ "Expected to complete within " ++ show n ++ " seconds, but did not" Just v -> pure v assertContents :: FilePath -> String -> IO () assertContents file want = do got <- IO.readFile' file assertBool (want == got) $ "File contents are wrong: " ++ file ++ "\nWANT: " ++ want ++ "\nGOT: " ++ got assertContentsInfix :: FilePath -> String -> IO () assertContentsInfix file want = do got <- IO.readFile' file assertBool (want `isInfixOf` got) $ "File contents are wrong: " ++ file ++ "\nWANT (infix): " ++ want ++ "\nGOT: " ++ got assertContentsOn :: (String -> String) -> FilePath -> String -> IO () assertContentsOn f file want = do got <- IO.readFile' file assertBool (f want == f got) $ "File contents are wrong: " ++ file ++ "\nWANT: " ++ want ++ "\nGOT: " ++ got ++ "\nWANT (transformed): " ++ f want ++ "\nGOT (transformed): " ++ f got assertContentsWords :: FilePath -> String -> IO () assertContentsWords = assertContentsOn (unwords . words) assertContentsUnordered :: FilePath -> [String] -> IO () assertContentsUnordered file xs = assertContentsOn (unlines . sort . lines) file (unlines xs) assertExceptionAfter :: (String -> String) -> [String] -> IO a -> IO () assertExceptionAfter tweak parts act = do res <- try_ act case res of Left err -> let s = tweak $ show err in forM_ parts $ \p -> assertBool (p `isInfixOf` s) $ "Incorrect exception, missing part:\nGOT: " ++ s ++ "\nWANTED: " ++ p Right _ -> error $ "Expected an exception containing " ++ show parts ++ ", but succeeded" assertException :: [String] -> IO a -> IO () assertException = assertExceptionAfter id assertTimings :: ([String] -> IO ()) -> [(String, Seconds)] -> IO () assertTimings build expect = do build ["--report=report.json","--no-build"] src <- IO.readFile' "report.json" let f ('[':'\"':xs) | (name,_:',':xs) <- break (== '\"') xs , num <- takeWhile (`notElem` ",]") xs , Just num <- readMaybe num = (name, num :: Double) f x = error $ "Failed to parse JSON output in assertTimings, " ++ show x let got = [f x | x <- map drop1 $ lines src, x /= ""] forM_ expect $ \(name, val) -> case lookup name got of Nothing -> assertFail $ "Couldn't find key " ++ show name ++ " in profiling output" Just v -> assertBool (v >= val && v < (val + 1)) $ "Unexpected value, got " ++ show v ++ ", hoping for " ++ show val ++ " (+ 1 sec)" defaultTest :: ([String] -> IO ()) -> IO () defaultTest build = do build ["--abbrev=output=$OUT","-j3","--report"] build ["--no-build","--report=-"] build [] -- | Sleep long enough for the modification time resolution to catch up sleepFileTime :: IO () sleepFileTime = sleep 1 sleepFileTimeCalibrate :: FilePath -> IO (IO ()) sleepFileTimeCalibrate file = do createDirectoryRecursive $ takeDirectory file -- with 10 measurements can get a bit slow, see #451 -- if it rounds to a second then 1st will be a fraction, but 2nd will be full second mtimes <- forM [1..2] $ \i -> fmap fst $ duration $ do writeFile file $ show i let time = fmap (fst . fromMaybe (error "File missing during sleepFileTimeCalibrate")) $ getFileInfo False $ fileNameFromString file t1 <- time flip loopM 0 $ \j -> do writeFile file $ show (i,j) t2 <- time pure $ if t1 == t2 then Left $ j+1 else Right () putStrLn $ "Longest file modification time lag was " ++ show (ceiling (maximum' mtimes * 1000)) ++ "ms" pure $ sleep $ min 1 $ maximum' mtimes * 2 removeFilesRandom :: FilePath -> IO Int removeFilesRandom x = do files <- getDirectoryContentsRecursive x n <- randomRIO (0,length files) rs <- replicateM (length files) (randomIO :: IO Double) mapM_ (removeFile . snd) $ sort $ zip rs files pure n getDirectoryContentsRecursive :: FilePath -> IO [FilePath] getDirectoryContentsRecursive dir = do xs <- IO.getDirectoryContents dir (dirs,files) <- partitionM IO.doesDirectoryExist [dir </> x | x <- xs, not $ "." `isPrefixOf` x] rest <- concatMapM getDirectoryContentsRecursive dirs pure $ files++rest copyDirectoryChanged :: FilePath -> FilePath -> IO () copyDirectoryChanged old new = do xs <- getDirectoryContentsRecursive old forM_ xs $ \from -> do let to = new </> drop (length $ addTrailingPathSeparator old) from createDirectoryRecursive $ takeDirectory to copyFileChangedIO from to copyFileChangedIO :: FilePath -> FilePath -> IO () copyFileChangedIO old new = unlessM (liftIO $ IO.doesFileExist new &&^ IO.fileEq old new) $ copyFile old new -- The operators %> ?> &*> &?> |?> |*> all have an isomorphism data Pat = PatWildcard | PatPredicate | PatOrWildcard | PatAndWildcard | PatAndPredicate deriving (Read, Show, Enum, Bounded) pat :: Pat -> FilePattern -> (FilePath -> Action ()) -> Rules () pat PatWildcard p act = p %> act pat PatPredicate p act = (p ?==) ?> act pat PatOrWildcard p act = [p] |%> act pat PatAndWildcard p act = -- single wildcard shortcircuits, so we use multiple to avoid that -- and thus have to fake writing an extra file [p, p ++ "'"] &%> \[x,x'] -> do act x; writeFile' x' "" pat PatAndPredicate p act = (\x -> if p ?== x then Just [x] else Nothing) &?> \[x] -> act x --------------------------------------------------------------------- -- TEST MATERIAL -- Some errors require multiple modules to replicate (e.g. #506), so put that here newtype BinarySentinel a = BinarySentinel () deriving (Eq,Show,NFData,Typeable,Hashable) instance forall a . Typeable a => Binary (BinarySentinel a) where put (BinarySentinel ()) = put $ show (typeRep (Proxy :: Proxy a)) get = do x <- get let want = show (typeRep (Proxy :: Proxy a)) if x == want then pure $ BinarySentinel () else error $ "BinarySentinel failed, got " ++ show x ++ " but wanted " ++ show want newtype RandomType = RandomType (BinarySentinel ()) deriving (Eq,Show,NFData,Typeable,Hashable,Binary)
ndmitchell/shake
src/Test/Type.hs
Haskell
bsd-3-clause
13,510
{-# LANGUAGE RecordWildCards #-} -- | Logic of local data processing in Update System. module Pos.DB.Update.Logic.Local ( -- * Proposals isProposalNeeded , getLocalProposalNVotes , processProposal -- * Votes , isVoteNeeded , getLocalVote , processVote -- * Normalization , usNormalize , processNewSlot , usPreparePayload , clearUSMemPool ) where import Universum hiding (id) import Control.Concurrent.STM (modifyTVar', writeTVar) import Control.Lens (views) import Control.Monad.Except (runExceptT, throwError) import Data.Default (Default (def)) import qualified Data.HashMap.Strict as HM import qualified Data.HashSet as HS import Formatting (sformat, (%)) import UnliftIO (MonadUnliftIO) import Pos.Binary.Class (biSize) import Pos.Chain.Block (HeaderHash) import Pos.Chain.Genesis as Genesis (Config, configBlockVersionData) import Pos.Chain.Update (BlockVersionData (..), MonadPoll (deactivateProposal), MonadPollRead (getProposal), PollModifier, PollVerFailure (..), UpId, UpdateConfiguration, UpdatePayload (..), UpdateProposal, UpdateVote (..), canCombineVotes, evalPollT, execPollT, getAdoptedBV, modifyPollModifier, psVotes, reportUnexpectedError, runPollT) import Pos.Core (SlotId (..), slotIdF) import Pos.Core.Reporting (MonadReporting) import Pos.Crypto (PublicKey, shortHashF) import Pos.DB.Class (MonadDBRead) import qualified Pos.DB.GState.Common as DB import Pos.DB.GState.Lock (StateLock) import Pos.DB.Lrc (HasLrcContext) import Pos.DB.Update.Context (UpdateContext (..)) import qualified Pos.DB.Update.GState as DB import Pos.DB.Update.MemState (LocalVotes, MemPool (..), MemState (..), MemVar (mvState), UpdateProposals, addToMemPool, withUSLock) import Pos.DB.Update.Poll.DBPoll (runDBPoll) import Pos.DB.Update.Poll.Logic.Apply (verifyAndApplyUSPayload) import Pos.DB.Update.Poll.Logic.Normalize (filterProposalsByThd, normalizePoll, refreshPoll) import Pos.Util.Util (HasLens (..), HasLens') import Pos.Util.Wlog (WithLogger, logWarning) type USLocalLogicMode ctx m = ( MonadIO m , MonadDBRead m , MonadUnliftIO m , WithLogger m , MonadReader ctx m , HasLens UpdateContext ctx UpdateContext , HasLens UpdateConfiguration ctx UpdateConfiguration , HasLrcContext ctx ) type USLocalLogicModeWithLock ctx m = ( USLocalLogicMode ctx m , MonadMask m , HasLens' ctx StateLock ) getMemPool :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => m MemPool getMemPool = msPool <$> (readTVarIO . mvState =<< views (lensOf @UpdateContext) ucMemState) clearUSMemPool :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => m () clearUSMemPool = atomically . flip modifyTVar' resetData . mvState =<< views (lensOf @UpdateContext) ucMemState where resetData memState = memState {msPool = def, msModifier = def} getPollModifier :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => m PollModifier getPollModifier = msModifier <$> (readTVarIO . mvState =<< views (lensOf @UpdateContext) ucMemState) getLocalProposals :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => m UpdateProposals getLocalProposals = mpProposals <$> getMemPool getLocalVotes :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => m LocalVotes getLocalVotes = mpLocalVotes <$> getMemPool -- Fetch memory state from 'TVar', modify it, write back. No -- synchronization is done, it's caller's responsibility. modifyMemState :: (MonadIO m, MonadReader ctx m, HasLens UpdateContext ctx UpdateContext) => (MemState -> m MemState) -> m () modifyMemState action = do stateVar <- mvState <$> views (lensOf @UpdateContext) ucMemState ms <- readTVarIO stateVar newMS <- action ms atomically $ writeTVar stateVar newMS ---------------------------------------------------------------------------- -- Data exchange in general ---------------------------------------------------------------------------- processSkeleton :: ( USLocalLogicModeWithLock ctx m , MonadReporting m ) => Genesis.Config -> UpdatePayload -> m (Either PollVerFailure ()) processSkeleton genesisConfig payload = reportUnexpectedError $ withUSLock $ runExceptT $ modifyMemState $ \ms@MemState {..} -> do dbTip <- lift DB.getTip -- We must check tip here, because we can't be sure that tip -- in DB is the same as the tip in memory. Normally it will be -- the case, but if normalization fails, it won't be true. -- -- If this equality holds, we can be sure that all further -- reads will be done for the same GState, because here we own -- global lock and nobody can modify GState. unless (dbTip == msTip) $ do let err = PollTipMismatch msTip dbTip throwError err maxBlockSize <- bvdMaxBlockSize <$> lift DB.getAdoptedBVData msIntermediate <- -- TODO: This is a rather arbitrary limit, we should revisit it (see CSL-1664) if | maxBlockSize * 2 <= mpSize msPool -> lift (refreshMemPool (configBlockVersionData genesisConfig) ms) | otherwise -> pure ms processSkeletonDo msIntermediate where processSkeletonDo ms@MemState {..} = do uc <- view (lensOf @UpdateConfiguration) modifierOrFailure <- lift . runDBPoll uc . runExceptT . evalPollT msModifier . execPollT def $ do lastAdopted <- getAdoptedBV verifyAndApplyUSPayload genesisConfig lastAdopted True (Left msSlot) payload case modifierOrFailure of Left failure -> throwError failure Right modifier -> do let newModifier = modifyPollModifier msModifier modifier let newPool = addToMemPool payload msPool pure $ ms {msModifier = newModifier, msPool = newPool} -- Remove most useless data from mem pool to make it smaller. refreshMemPool :: ( MonadDBRead m , MonadUnliftIO m , MonadReader ctx m , HasLrcContext ctx , WithLogger m , HasLens' ctx UpdateConfiguration ) => BlockVersionData -> MemState -> m MemState refreshMemPool genesisBvd ms@MemState {..} = do uc <- view (lensOf @UpdateConfiguration) let MemPool {..} = msPool ((newProposals, newVotes), newModifier) <- runDBPoll uc . runPollT def $ refreshPoll genesisBvd msSlot mpProposals mpLocalVotes let newPool = MemPool { mpProposals = newProposals , mpLocalVotes = newVotes , mpSize = biSize newProposals + biSize newVotes } return ms {msModifier = newModifier, msPool = newPool} ---------------------------------------------------------------------------- -- Proposals ---------------------------------------------------------------------------- -- | This function returns true if update proposal with given -- identifier should be requested. isProposalNeeded :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => UpId -> m Bool isProposalNeeded id = not . HM.member id <$> getLocalProposals -- | Get update proposal with given id if it is known. getLocalProposalNVotes :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => UpId -> m (Maybe (UpdateProposal, [UpdateVote])) getLocalProposalNVotes id = do prop <- HM.lookup id <$> getLocalProposals votes <- getLocalVotes pure $ case prop of Nothing -> Nothing Just p -> Just (p, toList $ HM.lookupDefault mempty id votes) -- | Process proposal received from network, checking it against -- current state (global + local) and adding to local state if it's -- valid with respect to it. -- If proposal is added to store, 'Right ()' is returned. -- Otherwise 'Left err' is returned and 'err' lets caller decide whether -- sender could be sure that error would happen. processProposal :: (USLocalLogicModeWithLock ctx m, MonadReporting m) => Genesis.Config -> UpdateProposal -> m (Either PollVerFailure ()) processProposal genesisConfig proposal = processSkeleton genesisConfig $ UpdatePayload (Just proposal) [] ---------------------------------------------------------------------------- -- Votes ---------------------------------------------------------------------------- lookupVote :: UpId -> PublicKey -> LocalVotes -> Maybe UpdateVote lookupVote propId pk locVotes = HM.lookup propId locVotes >>= HM.lookup pk -- | This function returns true if update vote proposal with given -- identifier issued by stakeholder with given PublicKey and with -- given decision should be requested. isVoteNeeded :: USLocalLogicMode ctx m => UpId -> PublicKey -> Bool -> m Bool isVoteNeeded propId pk decision = do uc <- view (lensOf @UpdateConfiguration) modifier <- getPollModifier runDBPoll uc . evalPollT modifier $ do proposal <- getProposal propId case proposal of Nothing -> pure False Just ps -> pure . canCombineVotes decision . HM.lookup pk . psVotes $ ps -- | Get update vote for proposal with given id from given issuer and -- with given decision if it is known. getLocalVote :: (MonadReader ctx m, HasLens UpdateContext ctx UpdateContext, MonadIO m) => UpId -> PublicKey -> Bool -> m (Maybe UpdateVote) getLocalVote propId pk decision = do voteMaybe <- lookupVote propId pk <$> getLocalVotes pure $ case voteMaybe of Nothing -> Nothing Just vote | uvDecision vote == decision -> Just vote | otherwise -> Nothing -- | Process vote received from network, checking it against -- current state (global + local) and adding to local state if it's -- valid with respect to it. -- If vote is added to store, 'Right ()' is returned. -- Otherwise 'Left err' is returned and 'err' lets caller decide whether -- sender could be sure that error would happen. processVote :: (USLocalLogicModeWithLock ctx m, MonadReporting m) => Genesis.Config -> UpdateVote -> m (Either PollVerFailure ()) processVote genesisConfig vote = processSkeleton genesisConfig $ UpdatePayload Nothing [vote] ---------------------------------------------------------------------------- -- Normalization and related ---------------------------------------------------------------------------- -- | Remove local data from memory state to make it consistent with -- current GState. This function assumes that GState is locked. It -- tries to leave as much data as possible. It assumes that -- 'stateLock' is taken. usNormalize :: USLocalLogicMode ctx m => BlockVersionData -> m () usNormalize genesisBvd = do tip <- DB.getTip stateVar <- mvState <$> views (lensOf @UpdateContext) ucMemState atomically . writeTVar stateVar =<< usNormalizeDo genesisBvd (Just tip) Nothing -- Normalization under lock. Note that here we don't care whether tip -- in mempool is the same as the one is DB, because we take payload -- from mempool and apply it to empty mempool, so it depends only on -- GState. usNormalizeDo :: USLocalLogicMode ctx m => BlockVersionData -> Maybe HeaderHash -> Maybe SlotId -> m MemState usNormalizeDo genesisBvd tip slot = do uc <- view (lensOf @UpdateConfiguration) stateVar <- mvState <$> views (lensOf @UpdateContext) ucMemState ms@MemState {..} <- readTVarIO stateVar let MemPool {..} = msPool ((newProposals, newVotes), newModifier) <- runDBPoll uc . runPollT def $ normalizePoll genesisBvd msSlot mpProposals mpLocalVotes let newTip = fromMaybe msTip tip let newSlot = fromMaybe msSlot slot let newPool = MemPool { mpProposals = newProposals , mpLocalVotes = newVotes , mpSize = biSize newProposals + biSize newVotes } let newMS = ms { msModifier = newModifier , msPool = newPool , msTip = newTip , msSlot = newSlot } return newMS -- | Update memory state to make it correct for given slot. processNewSlot :: USLocalLogicModeWithLock ctx m => BlockVersionData -> SlotId -> m () processNewSlot genesisBvd slotId = withUSLock $ processNewSlotNoLock genesisBvd slotId processNewSlotNoLock :: USLocalLogicMode ctx m => BlockVersionData -> SlotId -> m () processNewSlotNoLock genesisBvd slotId = modifyMemState $ \ms@MemState{..} -> do if | msSlot >= slotId -> pure ms -- Crucial changes happen only when epoch changes. | siEpoch msSlot == siEpoch slotId -> pure $ ms {msSlot = slotId} | otherwise -> usNormalizeDo genesisBvd Nothing (Just slotId) -- | Prepare UpdatePayload for inclusion into new block with given -- SlotId based on given tip. This function assumes that -- 'stateLock' is taken and nobody can apply/rollback blocks in -- parallel or modify US mempool. Sometimes payload can't be -- created. It can happen if we are trying to create block for slot -- which has already passed, for example. Or if we have different tip -- in mempool because normalization failed earlier. -- -- If we can't obtain payload for block creation, we use empty -- payload, because it's important to create blocks for system -- maintenance (empty blocks are better than no blocks). usPreparePayload :: USLocalLogicMode ctx m => BlockVersionData -> HeaderHash -> SlotId -> m UpdatePayload usPreparePayload genesisBvd neededTip slotId@SlotId{..} = do -- First of all, we make sure that mem state corresponds to given -- slot. If mem state corresponds to newer slot already, it won't -- be updated, but we don't want to create block in this case -- anyway. In normal cases 'processNewSlot' can't fail here -- because of tip mismatch, because we are under 'stateLock'. processNewSlotNoLock genesisBvd slotId -- After that we normalize payload to be sure it's valid. We try -- to keep it valid anyway, but we decided to have an extra -- precaution. We also do it because here we need to eliminate all -- proposals which don't have enough positive stake for inclusion -- into block. We check that payload corresponds to requested slot -- and return it if it does. preparePayloadDo where preparePayloadDo = do uc <- view (lensOf @UpdateConfiguration) -- Normalization is done just in case, as said before MemState {..} <- usNormalizeDo genesisBvd Nothing (Just slotId) -- If slot doesn't match, we can't provide payload for this slot. if | msSlot /= slotId -> def <$ logWarning (sformat slotMismatchFmt msSlot slotId) | msTip /= neededTip -> def <$ logWarning (sformat tipMismatchFmt msTip neededTip) | otherwise -> do -- Here we remove proposals which don't have enough -- positive stake for inclusion into payload. let MemPool {..} = msPool (filteredProposals, bad) <- runDBPoll uc . evalPollT msModifier $ filterProposalsByThd genesisBvd siEpoch mpProposals runDBPoll uc . evalPollT msModifier $ finishPrepare bad filteredProposals mpLocalVotes slotMismatchFmt = "US payload can't be created due to slot mismatch "% "(our payload is for "% slotIdF%", but requested one is "%slotIdF%")" tipMismatchFmt = "US payload can't be created due to tip mismatch " %"(our payload is for " %shortHashF%", but we want to create payload based on tip " %shortHashF%")" -- Here we basically choose only one proposal for inclusion and remove -- all votes for other proposals. finishPrepare :: MonadPoll m => HashSet UpId -> UpdateProposals -> LocalVotes -> m UpdatePayload finishPrepare badProposals proposals votes = do proposalPair <- foldM findProposal Nothing $ HM.toList proposals mapM_ (deactivate (fst <$> proposalPair)) $ HM.toList proposals let allVotes :: [UpdateVote] allVotes = concatMap toList $ toList votes goodVotes <- filterM isVoteValid allVotes return $ UpdatePayload {upProposal = snd <$> proposalPair, upVotes = goodVotes} where findProposal (Just x) _ = pure (Just x) findProposal Nothing x@(upId, _) = bool Nothing (Just x) <$> (isJust <$> getProposal upId) deactivate chosenUpId (upId, _) | chosenUpId == Just upId = pass | otherwise = deactivateProposal upId isVoteValid vote = do let id = uvProposalId vote proposalIsPresent <- isJust <$> getProposal id pure $ not (HS.member id badProposals) && proposalIsPresent
input-output-hk/pos-haskell-prototype
db/src/Pos/DB/Update/Logic/Local.hs
Haskell
mit
17,535
{-# LANGUAGE TypeOperators #-} {-# Language RebindableSyntax #-} {-# Language ScopedTypeVariables #-} {-# Language FlexibleContexts #-} module Main where import Prelude hiding ((>>=), (>>), fail, return, id, lookup) import Symmetry.Language import Symmetry.Verify import Symmetry.SymbEx import SrcHelper -- msg1 : Alloc, Lookup -- msg2 : Value -- msg3 : Free, Allocated type AllocT = (Int,Pid RSing) type LookupT = (Int,Pid RSing) type ValueT = (Int,Pid RSing) type ALV = AllocT :+: (LookupT :+: ValueT) type FreeAllocated = () :+: -- Free () -- Allocated type LookupResT = () :+: Int alloc_msg :: CDBSem repr => repr (Int -> Pid RSing -> ALV) alloc_msg = lam $ \n -> lam $ \pid -> inl $ pair n pid lookup_msg :: CDBSem repr => repr (Int -> Pid RSing -> ALV) lookup_msg = lam $ \n -> lam $ \pid -> inr $ inl $ pair n pid value_msg :: CDBSem repr => repr (Int -> Pid RSing -> ALV) value_msg = lam $ \n -> lam $ \pid -> inr $ inr $ pair n pid free_msg :: CDBSem repr => repr (FreeAllocated) free_msg = inl tt allocated_msg :: CDBSem repr => repr (FreeAllocated) allocated_msg = inr tt recv_alloc :: CDBSem repr => repr (Process repr AllocT) recv_alloc = do msg :: repr ALV <- recv match msg id reject recv_lookup :: CDBSem repr => repr (Process repr LookupT) recv_lookup = do msg :: repr ALV <- recv match msg reject $ lam $ \e1 -> match e1 id reject recv_value :: CDBSem repr => repr (Process repr ValueT) recv_value = do msg :: repr ALV <- recv match msg reject $ lam $ \e1 -> match e1 reject id class ( HelperSym repr ) => CDBSem repr instance CDBSem SymbEx concdb :: CDBSem repr => repr (Process repr ()) concdb = do r <- newRSing db <- spawn r (app database nil) rs <- newRMulti spawnMany rs arb (app client db) return tt type T_db = [(Int,Int)] f_database :: CDBSem repr => repr ((T_db -> Process repr T_db) -> T_db -> Process repr T_db) f_database = lam $ \database -> lam $ \l -> do let allocHandler = lam $ \msg -> do let key = proj1 msg p = proj2 msg lookup_res <- app2 SrcHelper.lookup key l match lookup_res (lam $ \_ -> do send p free_msg val <- recv_value ifte (eq (proj2 val) p) (app database (cons (pair key (proj1 val)) l)) fail) (lam $ \x -> do send p allocated_msg app database l) let lookupHandler = lam $ \msg -> do let key = proj1 msg p = proj2 msg lookup_res <- app2 SrcHelper.lookup key l send p lookup_res app database l msg :: repr ALV <- recv match msg allocHandler $ lam $ \e1 -> match e1 lookupHandler reject database :: CDBSem repr => repr ([(Int,Int)] -> Process repr ()) database = lam $ \l -> do app (fixM f_database) l ret tt f_client :: CDBSem repr => repr ((Pid RSing -> Process repr (Pid RSing)) -> Pid RSing -> Process repr (Pid RSing)) f_client = lam $ \client -> lam $ \db -> do me <- self let insert_h = do send db (app2 alloc_msg arb me) let free_h = lam $ \_ -> do send db (app2 value_msg arb me) app client db alloc_h = lam $ \_ -> app client db msg :: repr FreeAllocated <- recv match msg free_h alloc_h lookup_h = do send db (app2 lookup_msg arb me) msg :: repr LookupResT <- recv match msg (lam $ \_ -> app client db) (lam $ \x -> app client db) ifte arb insert_h lookup_h client :: CDBSem repr => repr (Pid RSing -> Process repr ()) client = lam $ \db -> do app (fixM f_client) db ret tt main :: IO () main = checkerMain $ exec concdb
abakst/symmetry
checker/tests/todo/SrcConcDB.hs
Haskell
mit
4,690
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} module LambdaCms.Core.Models where import Data.Text (Text) import Data.Time.Clock import Data.Typeable (Typeable) import Database.Persist.Quasi import Prelude import Yesod share [mkPersist sqlSettings, mkMigrate "migrateLambdaCmsCore"] $(persistFileWith lowerCaseSettings "config/models")
lambdacms/lambdacms
lambdacms-core/LambdaCms/Core/Models.hs
Haskell
mit
686
{-# 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
Haskell
apache-2.0
186
{-# 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 <dan.doel@gmail.com> -- 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
Haskell
bsd-2-clause
15,554
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
Haskell
bsd-3-clause
182
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.PackageIndex -- Copyright : (c) David Himmelstrup 2005, -- Bjorn Bringert 2007, -- Duncan Coutts 2008 -- -- Maintainer : cabal-devel@haskell.org -- 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
Haskell
bsd-3-clause
10,633
-- | 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
Haskell
mit
3,214
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
Haskell
apache-2.0
123
{-| 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
Haskell
bsd-2-clause
5,938
<?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
Haskell
apache-2.0
962
-- 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
Haskell
bsd-3-clause
7,644
{-# 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
Haskell
bsd-3-clause
202
{-# 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
Haskell
bsd-3-clause
390
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
Haskell
bsd-3-clause
734
-- !!! Importing unknown name module M where import Prelude(f)
urbanslug/ghc
testsuite/tests/module/mod80.hs
Haskell
bsd-3-clause
64
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
Haskell
mit
1,944
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
Haskell
mit
404
{-# 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
Haskell
mit
1,892
-- 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
Haskell
mit
187
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
Haskell
mit
1,954
{-# 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
Haskell
mit
2,040
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
Haskell
mit
233