code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE 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
bsd-3-clause
1,295
0
15
361
446
257
189
37
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE 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
bsd-3-clause
681
0
8
140
114
72
42
17
1
{-# 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
bsd-3-clause
8,397
0
18
2,065
1,862
1,004
858
144
15
{-# 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
bsd-3-clause
997
0
12
193
227
122
105
25
2
{-# 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
bsd-3-clause
2,838
0
10
780
884
482
402
77
0
{-# 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
bsd-3-clause
536
0
10
84
113
62
51
14
1
{-# 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
bsd-3-clause
2,682
0
12
839
1,399
715
684
85
4
{-# 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
bsd-3-clause
36,820
0
28
12,370
9,174
5,281
3,893
590
11
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
bsd-3-clause
123
0
6
29
45
23
22
-1
-1
{-# 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
bsd-3-clause
1,439
0
10
257
134
78
56
13
0
{-# 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
bsd-3-clause
13,226
0
17
3,401
2,383
1,245
1,138
184
3
{-# 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
bsd-3-clause
6,443
0
22
2,813
1,395
780
615
-1
-1
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
bsd-3-clause
1,316
0
14
269
456
245
211
25
1
-- | 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
bsd-3-clause
1,895
8
12
389
616
316
300
34
1
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
bsd-3-clause
355
0
7
77
159
84
75
10
1
----------------------------------------------------------------------------- -- | -- Module : Main (HaddockCoverage) -- Copyright : (C) 2015 Ivan Perez -- License : BSD-style (see the file LICENSE) -- Maintainer : Ivan Perez <[email protected]> -- 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
bsd-3-clause
3,394
0
14
656
574
317
257
42
3
-- 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
bsd-3-clause
461
0
6
90
75
44
31
11
1
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
bsd-3-clause
2,683
0
9
531
510
293
217
56
1
-- |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
bsd-3-clause
5,719
0
13
1,573
2,288
1,202
1,086
138
5
-- | 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
bsd-3-clause
10,569
5
20
2,923
1,856
1,039
817
-1
-1
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
bsd-3-clause
944
0
14
202
344
159
185
31
2
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
bsd-3-clause
117
0
9
20
40
23
17
4
0
{-# 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
bsd-3-clause
9,743
0
16
2,592
2,198
1,141
1,057
203
12
{-# 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
mit
396
0
5
100
71
51
20
10
0
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
mit
308
0
11
70
82
43
39
12
1
{-# 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
mit
18,113
0
18
4,939
3,363
1,729
1,634
-1
-1
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } func = do let foo True = True foo _ = False return ()
lspitzner/brittany
data/Test493.hs
agpl-3.0
180
0
10
37
35
16
19
5
2
<?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
apache-2.0
983
78
55
160
421
212
209
-1
-1
-- | 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
bsd-3-clause
1,466
0
15
457
366
201
165
30
2
{-# 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
mit
2,234
0
18
735
639
306
333
54
1
{- portable environment variables - - Copyright 2013 Joey Hess <[email protected]> - - 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
bsd-2-clause
2,003
0
10
365
452
259
193
22
1
{-# 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
bsd-2-clause
4,731
0
26
1,025
616
342
274
82
1
{-# 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
bsd-3-clause
637
0
15
187
157
83
74
14
4
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.GLboolean -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- 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
bsd-3-clause
940
0
8
132
119
74
45
10
2
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
bsd-3-clause
1,624
1
11
578
282
166
116
-1
-1
-- 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
bsd-3-clause
8,160
0
14
1,351
1,473
842
631
135
4
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
bsd-3-clause
194
2
8
88
114
60
54
9
1
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
bsd-3-clause
164
0
3
33
10
8
2
1
0
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
bsd-3-clause
1,772
0
12
350
237
148
89
21
1
{-# 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
bsd-3-clause
398
0
6
97
83
48
35
10
1
-- 0xbf is an invalid character bad = '¿'
wxwxwwxxx/ghc
testsuite/tests/parser/unicode/utf8_011.hs
bsd-3-clause
42
0
4
9
7
4
3
1
1
{-# 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
mit
4,325
0
17
1,223
1,530
779
751
92
0
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
mit
534
0
10
181
194
94
100
15
3
{-# 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
mit
1,940
0
9
415
905
479
426
47
1
module NLP.Senna.Foreign.Types where import Foreign type CSenna = Ptr ()
slyrz/hase
src/NLP/Senna/Foreign/Types.hs
mit
76
0
6
13
22
14
8
3
0
{-# 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
mit
167
0
8
47
60
32
28
5
2
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
mit
14,187
0
15
4,025
4,547
2,422
2,125
236
4
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
mit
9,424
0
15
2,691
3,595
2,120
1,475
262
1
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
mit
6,475
0
18
1,916
3,179
1,716
1,463
156
2
{-# 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
mit
902
0
8
108
162
96
66
13
0
--marySue :: Maybe Bool marySue = do k <- Just 9 Just (k>8)
RAFIRAF/HASKELL
A Fistful of Monads/mary.hs
mit
65
0
9
18
30
14
16
3
1
{-# 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
mit
6,799
0
12
350
509
296
213
47
1
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
cc0-1.0
321
14
16
101
156
87
69
12
4
module ControlPassesSpec where import Ohua.Prelude import Ohua.ALang.Lang import Ohua.ALang.PPrint (quickRender) import Ohua.ALang.Passes (normalize) import Ohua.ALang.Passes.If (ifRewrite) import Ohua.Test (embedALang, showWithPretty) import Test.Hspec runPass pass expr = runSilentLoggingT $ runFromExpr def pass expr transformInto pass expr expected = runPass (normalize >=> pass) expr >>= ((`shouldBe` Right (showWithPretty expected)) . fmap showWithPretty) spec :: Spec spec = do describe "conditionals" $ do it "nested-if" $ transformInto ifRewrite [embedALang| let cond1 = conditionals.iftest/get_ctrl_input () in let cond2 = conditionals.iftest/get_another_ctrl_input () in let inp = conditionals.iftest/get_input () in ohua.lang/if cond1 (\_ -> ohua.lang/if cond2 (\_ -> conditionals.iftest/modify_string_positive inp) (\ _ -> conditionals.iftest/modify_string_negative inp)) (\_ -> inp) |] [embedALang| let cond1 = conditionals.iftest/get_ctrl_input () in let cond2 = conditionals.iftest/get_another_ctrl_input () in let inp = conditionals.iftest/get_input () in let d = let ctrls_1 = ohua.lang/ifFun cond1 in let ctrlTrue_1 = ohua.lang/nth 0 2 ctrls_1 in let ctrlFalse_1 = ohua.lang/nth 1 2 ctrls_1 in let trueResult_1 = let ctrl_2 = ohua.lang/ctrl ctrlTrue_1 cond2 inp in let cond2_0 = ohua.lang/nth 0 2 ctrl_2 in let inp_2 = ohua.lang/nth 1 2 ctrl_2 in let c = let ctrls_0 = ohua.lang/ifFun cond2_0 in let ctrlTrue_0 = ohua.lang/nth 0 2 ctrls_0 in let ctrlFalse_0 = ohua.lang/nth 1 2 ctrls_0 in let trueResult_0 = let ctrl_0 = ohua.lang/ctrl ctrlTrue_0 inp_2 in let inp_0 = ohua.lang/nth 0 1 ctrl_0 in let a = conditionals.iftest/modify_string_positive inp_0 in a in let falseResult_0 = let ctrl_1 = ohua.lang/ctrl ctrlFalse_0 inp_2 in let inp_1 = ohua.lang/nth 0 1 ctrl_1 in let b = conditionals.iftest/modify_string_negative inp_1 in b in let result_0 = ohua.lang/select cond2_0 trueResult_0 falseResult_0 in result_0 in c in let falseResult_1 = let ctrl_3 = ohua.lang/ctrl ctrlFalse_1 inp in let inp_3 = ohua.lang/nth 0 1 ctrl_3 in let e = ohua.lang/id inp_3 in e in let result_1 = ohua.lang/select cond1 trueResult_1 falseResult_1 in result_1 in d |]
ohua-dev/ohua-core
tests/src/ControlPassesSpec.hs
epl-1.0
3,489
0
11
1,622
186
106
80
-1
-1
{-@ LIQUID "--pruneunsorted" @-} -- | Formats Haskell source code using HTML with font tags. module Language.Haskell.HsColour.HTML ( hscolour , top'n'tail -- * Internals , renderAnchors, renderComment, renderNewLinesAnchors, escape ) where {-@ LIQUID "--totality" @-} import Language.Haskell.HsColour.Anchors import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.Colourise import Data.Char(isAlphaNum) import Text.Printf -- | Formats Haskell source code using HTML with font tags. hscolour :: ColourPrefs -- ^ Colour preferences. -> Bool -- ^ Whether to include anchors. -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour pref anchor = pre . (if anchor then renderNewLinesAnchors . concatMap (renderAnchors (renderToken pref)) . insertAnchors else concatMap (renderToken pref)) . tokenise top'n'tail :: String -> String -> String top'n'tail title = (htmlHeader title ++) . (++htmlClose) pre :: String -> String pre = ("<pre>"++) . (++"</pre>") renderToken :: ColourPrefs -> (TokenType,String) -> String renderToken pref (t,s) = fontify (colourise pref t) (if t == Comment then renderComment s else escape s) renderAnchors :: (a -> String) -> Either String a -> String renderAnchors _ (Left v) = "<a name=\""++v++"\"></a>" renderAnchors render (Right r) = render r -- if there are http://links/ in a comment, turn them into -- hyperlinks renderComment :: String -> String renderComment ('h':'t':'t':'p':':':'/':'/':xs) = renderLink ("http://" ++ a) ++ renderComment b where -- see http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#characters isUrlChar x = isAlphaNum x || x `elem` ":/?#[]@!$&'()*+,;=-._~%" (a,b) = span isUrlChar xs renderLink link = "<a href=\"" ++ link ++ "\">" ++ escape link ++ "</a>" renderComment (x:xs) = escape [x] ++ renderComment xs renderComment [] = [] renderNewLinesAnchors :: String -> String renderNewLinesAnchors = unlines . map render . zip [1..] . lines where render (line, s) = "<a name=\"line-" ++ show line ++ "\"></a>" ++ s -- Html stuff fontify :: [Highlight] -> String -> String fontify [] s = s fontify (h:hs) s = font h (fontify hs s) font :: Highlight -> String -> String font Normal s = s font Bold s = "<b>"++s++"</b>" font Dim s = "<em>"++s++"</em>" font Underscore s = "<u>"++s++"</u>" font Blink s = "<blink>"++s++"</blink>" font ReverseVideo s = s font Concealed s = s font (Foreground (Rgb r g b)) s = printf "<font color=\"#%02x%02x%02x\">%s</font>" r g b s font (Background (Rgb r g b)) s = printf "<font bgcolor=\"#%02x%02x%02x\">%s</font>" r g b s font (Foreground c) s = "<font color="++show c++">"++s++"</font>" font (Background c) s = "<font bgcolor="++show c++">"++s++"</font>" font Italic s = "<i>"++s++"</i>" escape :: String -> String escape ('<':cs) = "&lt;"++escape cs escape ('>':cs) = "&gt;"++escape cs escape ('&':cs) = "&amp;"++escape cs escape (c:cs) = c: escape cs escape [] = [] htmlHeader :: String -> String htmlHeader title = unlines [ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">" , "<html>" , "<head>" ,"<!-- Generated by HsColour, http://code.haskell.org/~malcolm/hscolour/ -->" , "<title>"++title++"</title>" , "</head>" , "<body>" ] htmlClose :: String htmlClose = "\n</body>\n</html>"
nikivazou/hscolour
Language/Haskell/HsColour/HTML.hs
gpl-2.0
3,589
0
15
813
1,097
582
515
74
2
{-# LANGUAGE LambdaCase #-} -- | -- Most of the code is borrowed from -- <http://haskell.1045720.n5.nabble.com/darcs-patch-GenT-monad-transformer-variant-of-Gen-QuickCheck-2-td3172136.html a mailing list discussion>. -- Therefor, credits go to Paul Johnson and Felix Martini. module Sara.TestUtils.GenT where import qualified Prelude as P import Sara.TestUtils.GenT.Prelude import qualified Test.QuickCheck.Gen as QC import qualified System.Random as Random import Test.QuickCheck.Random newtype GenT m a = GenT { unGenT :: QCGen -> Int -> m a } instance (Functor m) => Functor (GenT m) where fmap f m = GenT $ \r n -> fmap f $ unGenT m r n instance (Monad m) => Monad (GenT m) where return a = GenT (\_ _ -> return a) m >>= k = GenT $ \r n -> do let (r1, r2) = Random.split r a <- unGenT m r1 n unGenT (k a) r2 n fail msg = GenT (\_ _ -> fail msg) instance (Functor m, Monad m) => Applicative (GenT m) where pure = P.return (<*>) = ap instance MonadTrans GenT where lift m = GenT (\_ _ -> m) instance (MonadIO m) => MonadIO (GenT m) where liftIO = lift . liftIO runGenT :: GenT m a -> QC.Gen (m a) runGenT (GenT run) = QC.MkGen run mapGenT :: (m a -> n b) -> GenT m a -> GenT n b mapGenT f g = GenT $ (\a b -> f $ unGenT g a b) class (Applicative g, Monad g) => MonadGen g where liftGen :: QC.Gen a -> g a variant :: Integral n => n -> g a -> g a sized :: (Int -> g a) -> g a resize :: Int -> g a -> g a choose :: Random.Random a => (a, a) -> g a instance (Applicative m, Monad m) => MonadGen (GenT m) where liftGen gen = GenT $ \r n -> return $ QC.unGen gen r n choose rng = GenT $ \r _ -> return $ fst $ Random.randomR rng r variant k (GenT g) = GenT $ \r n -> g (var k r) n sized f = GenT $ \r n -> let GenT g = f n in g r n resize n (GenT g) = GenT $ \r _ -> g r n instance MonadGen QC.Gen where liftGen = id variant k (QC.MkGen g) = QC.MkGen $ \r n -> g (var k r) n sized f = QC.MkGen $ \r n -> let QC.MkGen g = f n in g r n resize n (QC.MkGen g) = QC.MkGen $ \r _ -> g r n choose range = QC.MkGen $ \r _ -> fst $ Random.randomR range r -- | -- Private variant-generating function. Converts an integer into a chain -- of (fst . split) and (snd . split) applications. Every integer (including -- negative ones) will give rise to a different random number generator in -- log2 n steps. var :: Integral n => n -> QCGen -> QCGen var k = (if k == k' then id else var k') . (if even k then fst else snd) . Random.split where k' = k `div` 2 -------------------------------------------------------------------------- -- ** Common generator combinators -- | Adjust the size parameter, by transforming it with the given -- function. scale :: MonadGen m => (Int -> Int) -> m a -> m a scale f g = sized (\n -> resize (f n) g) -- | Generates a value that satisfies a predicate. suchThat :: MonadGen m => m a -> (a -> Bool) -> m a gen `suchThat` p = do mx <- gen `suchThatMaybe` p case mx of Just x -> return x Nothing -> sized (\n -> resize (n+1) (gen `suchThat` p)) -- | Tries to generate a value that satisfies a predicate. suchThatMaybe :: MonadGen m => m a -> (a -> Bool) -> m (Maybe a) gen `suchThatMaybe` p = sized (try 0 . max 1) where try _ 0 = return Nothing try k n = do x <- resize (2*k+n) gen if p x then return (Just x) else try (k+1) (n-1) -- | Generates a list of random length. The maximum length depends on the -- size parameter. listOf :: MonadGen m => m a -> m [a] listOf gen = sized $ \n -> do k <- choose (0,n) vectorOf k gen -- | Generates a non-empty list of random length. The maximum length -- depends on the size parameter. listOf1 :: MonadGen m => m a -> m [a] listOf1 gen = sized $ \n -> do k <- choose (1,1 `max` n) vectorOf k gen -- | Generates a list of the given length. vectorOf :: MonadGen m => Int -> m a -> m [a] vectorOf k gen = sequence [ gen | _ <- [1..k] ] -- * Partial functions ------------------------- -- | Randomly uses one of the given generators. The input list -- must be non-empty. oneof :: MonadGen m => [m a] -> m a oneof = fmap (fromMaybe (error "QuickCheck.GenT.oneof used with empty list")) . oneofMay -- | Chooses one of the given generators, with a weighted random distribution. -- The input list must be non-empty. frequency :: MonadGen m => [(Int, m a)] -> m a frequency [] = error "QuickCheck.GenT.frequency used with empty list" frequency xs0 = choose (1, tot) >>= (`pick` xs0) where tot = sum (map fst xs0) pick n ((k,x):xs) | n <= k = x | otherwise = pick (n-k) xs pick _ _ = error "QuickCheck.GenT.pick used with empty list" -- | Generates one of the given values. The input list must be non-empty. elements :: MonadGen m => [a] -> m a elements = fmap (fromMaybe (error "QuickCheck.GenT.elements used with empty list")) . elementsMay -- | Takes a list of elements of increasing size, and chooses -- among an initial segment of the list. The size of this initial -- segment increases with the size parameter. -- The input list must be non-empty. growingElements :: MonadGen m => [a] -> m a growingElements = fmap (fromMaybe (error "QuickCheck.GenT.growingElements used with empty list")) . growingElementsMay -- * Non-partial functions resulting in Maybe ------------------------- -- | -- Randomly uses one of the given generators. oneofMay :: MonadGen m => [m a] -> m (Maybe a) oneofMay = \case [] -> return Nothing l -> fmap Just $ choose (0, length l - 1) >>= (l !!) -- | Generates one of the given values. elementsMay :: MonadGen m => [a] -> m (Maybe a) elementsMay = \case [] -> return Nothing l -> Just . (l !!) <$> choose (0, length l - 1) -- | Takes a list of elements of increasing size, and chooses -- among an initial segment of the list. The size of this initial -- segment increases with the size parameter. growingElementsMay :: MonadGen m => [a] -> m (Maybe a) growingElementsMay = \case [] -> return Nothing xs -> fmap Just $ sized $ \n -> elements (take (1 `max` size n) xs) where k = length xs mx = 100 log' = round . log . fromIntegral size n = (log' n + 1) * k `div` log' mx
Lykos/Sara
tests/Sara/TestUtils/GenT.hs
gpl-3.0
6,204
0
15
1,451
2,278
1,174
1,104
109
3
import Data.Maybe import Distribution.PackageDescription import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Program import Distribution.Simple.Setup import Distribution.Verbosity import System.Directory (copyFile, createDirectoryIfMissing, doesDirectoryExist, getHomeDirectory, removeFile) import System.Environment (lookupEnv) import System.FilePath ((</>)) main :: IO () main = defaultMainWithHooks simpleUserHooks { buildHook = localBuildHook, instHook = localInstHook, copyHook = localCopyHook, regHook = localRegHook } logC :: String -> IO () logC s = putStrLn ("[*] " ++ s) localBuildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO () localBuildHook desc buildInfo hooks flags = do let progs = withPrograms buildInfo ghcProgram' = fromJust (lookupProgram ghcProgram progs) ghc = runProgram normal ghcProgram' gccProgram' = fromJust (lookupProgram gccProgram progs) gcc = runProgram normal gccProgram' hsc2hsProgram' = fromJust (lookupProgram hsc2hsProgram progs) hsc2hs = runProgram normal hsc2hsProgram' includeDirs' = includeDirs $ libBuildInfo $ fromJust $ library desc libInfo = libBuildInfo $ fromJust $ library desc ccOptions' = map ("-optc" ++) $ ccOptions libInfo cSources' = cSources libInfo modules = exposedModules $ fromJust $ library desc srcDir = head $ hsSourceDirs libInfo buildDir' = buildDir buildInfo extraLibDirs' = head $ extraLibDirs libInfo logC "Building IdaHaskell Plugin" createDirectoryIfMissing True buildDir' ghc $ ["-I" ++ head includeDirs', "-shared", "-o", buildDir' </> "IdaHaskell.plw", "-package", "ghc", "-package", "text", "-fPIC", "-odir", buildDir', srcDir </> "Ida.hs", srcDir </> "Cli.hs", "-lstdc++", extraLibDirs' </> "ida.a", srcDir </> "export.def"] ++ cSources' ++ ccOptions' logC "Preprocessing UserApi" hsc2hs $ ["-c", "g++", "-I" ++ head includeDirs', srcDir </> "UserApi.hsc"] ++ ccOptions libInfo logC "Static check of UserApi" ghc $ ["-fno-code", srcDir </> "UserApi.hs"] return () -- Some ugly codes findIdaDir :: IO String findIdaDir = do userDefined <- lookupEnv "IDA_PATH" case userDefined of Just path -> return path Nothing -> do test1 <- doesDirectoryExist "C:/Program Files (x86)/IDA 6.8" if test1 then return "C:/Program Files (x86)/IDA 6.8" else do test2 <- doesDirectoryExist "C:/Program Files/IDA 6.8" if test1 then return "C:/Program Files/IDA 6.8" else error "Could not find Ida Pro path, try set IDA_PATH env var" localCopyHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> CopyFlags -> IO () localCopyHook desc buildInfo hooks flags = do logC "Try to find Ida Pro installation path" idaDir <- findIdaDir logC $ "Found Ida Pro installation at " ++ show idaDir homeDir <- getHomeDirectory let libInfo = libBuildInfo $ fromJust $ library desc srcDir = head $ hsSourceDirs libInfo idaPluginsDir = idaDir </> "plugins" buildDir' = buildDir buildInfo logC "Installing IdaHaskell Plugin" copyFile (buildDir' </> "IdaHaskell.plw") (idaPluginsDir </> "IdaHaskell.plw") -- logC "Installing helpers library" -- copyFile (buildDir' </> "helpers.dll") (idaDir </> "helpers.dll") logC $ "Installing UserApi to " ++ homeDir copyFile (srcDir </> "UserApi.hs") (homeDir </> "UserApi.hs") return () localRegHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO () localRegHook desc buildInfo hooks flags = return () localInstHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO () localInstHook desc buildInfo userHooks flags = do logC "Try to find Ida Pro installation path" idaDir <- findIdaDir logC $ "Found Ida Pro installation at " ++ show idaDir homeDir <- getHomeDirectory let libInfo = libBuildInfo $ fromJust $ library desc srcDir = head $ hsSourceDirs libInfo idaPluginsDir = idaDir </> "plugins" buildDir' = buildDir buildInfo logC "Installing IdaHaskell Plugin" copyFile (buildDir' </> "IdaHaskell.plw") (idaPluginsDir </> "IdaHaskell.plw") -- logC "Installing helpers library" -- copyFile (buildDir' </> "helpers.dll") (idaPluginsDir </> "helpers.dll") logC $ "Installing UserApi to " ++ homeDir copyFile (srcDir </> "UserApi.hs") (homeDir </> "UserApi.hs") return ()
kvnesterov/IdaHaskell
Setup.hs
gpl-3.0
5,029
0
16
1,406
1,111
558
553
95
4
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TemplateHaskell, NoMonomorphismRestriction, ViewPatterns, TypeOperators, FlexibleContexts, TypeFamilies #-} {-# OPTIONS -Wall #-} module EdgeCentered( module Triangulation, module SimplicialPartialQuotient, EdgeNeighborhoodVertex(..), makeEdgeNeighborhood, polyprop_edgeIsGlued, edgeNeighborhoodVertexCoords, equatorVertexCoords ) where import Equivalence import Triangulation import Data.Map as M import Data.List as L import HomogenousTuples import Test.QuickCheck import Data.Vect.Double hiding((.*)) import SimplicialPartialQuotient import PrettyUtil import ShortShow import DisjointUnion import Triangulation.AbstractNeighborhood data EdgeNeighborhoodVertex = Bottom | Top | EquatorVertex Int deriving(Show,Eq,Ord) instance ShortShow EdgeNeighborhoodVertex where shortShow Bottom = "B" shortShow Top = "T" shortShow (EquatorVertex i) = show i instance Pretty EdgeNeighborhoodVertex where pretty = black . text . show makeEdgeNeighborhoodMap :: Triangulation -> OIEdge -> SimplicialPartialQuotient EdgeNeighborhoodVertex makeEdgeNeighborhoodMap tr oiEdge = case innerEdgeNeighborhood' tr oiEdge of Nothing -> error ("makeEdgeNeighborhoodMap: This function only works on inner edges, not " ++ show oiEdge) Just tets -> let n = length tets theAssocs = zipWith (\i ent -> ( ( mapI ent_bot ent , Bottom) , ( mapI ent_top ent , Top) , ( mapI ent_left ent , EquatorVertex i) , ( mapI ent_right ent , EquatorVertex (mod (i+1) n)) ) ) [0..] tets res = M.fromListWith collision (concatMap toList4 theAssocs) where collision _ _ = error ( prettyString ( vsep [ text ( "makeEdgeNeighborhoodMap: This function only works" ++ " on an edge which only has one preimage in each tetrahedron." ++ " The preimage-containing tetrahedra are:") , indent 4 (pretty tets) ])) in spq_fromMap tr res (L.map (asc4 . (map4 snd)) theAssocs) edgeNeighborhoodVertexCoords :: Double -- ^ height -> Int -- ^ number of equator vertices -> EdgeNeighborhoodVertex -> Vec3 edgeNeighborhoodVertexCoords h _ Bottom = (-h) *& vec3Z edgeNeighborhoodVertexCoords h _ Top = h *& vec3Z edgeNeighborhoodVertexCoords _ n (EquatorVertex i) = equatorVertexCoords n i equatorVertexCoords :: Int -> Int -> Vec3 equatorVertexCoords n i = Vec3 (sin phi) (-(cos phi)) 0 where phi = 2*pi*(2*i'-1)/(2*n') i' = fromIntegral i n' = fromIntegral n makeEdgeNeighborhood :: Triangulation -> OIEdge -> GluingLabeller -> SPQWithCoords EdgeNeighborhoodVertex makeEdgeNeighborhood tr oiEdge gluingLabeller = let m = makeEdgeNeighborhoodMap tr oiEdge n = tOIEdgeDegree tr oiEdge h = max 0.2 (sqrt (equatorEdgeLengthSqr - 1)) equatorEdgeLengthSqr = normsqr (equatorVertexCoords n 1 &- equatorVertexCoords n 0) coords = edgeNeighborhoodVertexCoords h n -- equatorEdgeLength = sqrt (1 + h^2) -- sqrt (equatorEdgeLengthSqr - 1) = h -- labels = fmap return letters ++ join (liftM2 (\x y -> [x,y])) letters ++ error "out of labels :(" -- letters = "FGJPQR?" in SPQWithCoords m coords gluingLabeller polyprop_edgeIsGlued :: Eq b => SimplicialPartialQuotient b -> OIEdge -> Property polyprop_edgeIsGlued m oiedge = let oEdgeClass = eqv_equivalents (oEdgeEqv . spq_tr $ m) oiedge im_oiedge = spq_mapEd m oiedge in forAll (elements oEdgeClass) (\oiedge2 -> spq_mapEd m oiedge2 == im_oiedge) --qc_EdgeCentered = $(quickCheckAll) isRegardedAsSimplexByDisjointUnionDeriving ''DIM0 [t|EdgeNeighborhoodVertex|]
DanielSchuessler/hstri
EdgeCentered.hs
gpl-3.0
4,359
0
23
1,419
892
473
419
94
2
-- Copyright (c) 2015, Sven Thiele <[email protected]> -- This file is part of hasple. -- hasple is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- hasple is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with hasple. If not, see <http://www.gnu.org/licenses/>. module Test ( unit_test, test, )where import Test.QuickCheck import ASP import Grounder import qualified GoodSolver -- import qualified CDNLSolverST import GrounderSolverST -- import STTest import LPParser -- for parsing tests import Data.List (sort) import Debug.Trace -- function to test test_good :: [Char] -> [[Atom]] test_good x = do case readProgram x of Left err -> [] Right prg -> sort (map sort (GoodSolver.anssets (groundProgram prg))) -- test_old :: [Char] -> [[Atom]] -- test_old x = -- do -- case readProgram x of -- Left err -> [] -- Right prg -> sort (map sort (CDNLSolver.anssets (groundProgram prg))) test_new :: [Char] -> [[Atom]] test_new x = do case readProgram x of Left err -> [] Right prg -> sort (map sort (gr_solve prg)) test :: [Char] -> IO() test x = do case readProgram x of Left err -> print $ "ParseError: " ++ (show err) Right prg -> putStrLn $ show (gr_solve prg) good_solver p = sort (map sort (GoodSolver.anssets (groundProgram p))) new_solver p = sort (map sort (gr_solve p)) -- Test properties prop_good_model p = new_solver p == good_solver p -- Test cases logic programs mpr1 = "a :- not b, not c.\n" ++ "b :- not a, not c.\n" ++ "c :- not a, not b.\n" Right mp1 = readProgram mpr1 mpr2 = " a :- not b.\n" Right mp2 = readProgram mpr2 mpr3 = "q(a) :- not p(a).\n" ++ "q(b) :- not p(b).\n" ++ "p(a) :- not q(a).\n" ++ "p(b) :- not q(b).\n" Right mp3 = readProgram mpr3 mpr4 = "a:-b.\n" ++ "b:-a.\n" Right mp4 = readProgram mpr4 mpr5 = "a :- b.\n" ++ "b :- not a.\n" Right mp5 = readProgram mpr5 mpr6 = "a :- b.\n" ++ "b :- not a.\n" ++ "b :- x.\n" ++ "x :- not y.\n" ++ "y :- not x.\n" Right mp6 = readProgram mpr6 mpr6a = "v :- u,y.\n" -- example from Conflict-Driven Answer Set Solving p4 ++ "u :- v.\n" ++ "u :- x.\n" ++ "x :- not y.\n" ++ "y :- not x.\n" Right mp6a = readProgram mpr6a mpr6b = "v :- u.\n" ++ "u :- v.\n" ++ "u :- x.\n" ++ "x :- not y.\n" ++ "y :- not x.\n" Right mp6b = readProgram mpr6b mpr7 = "a :- b.\n" ++ "b :- c.\n" ++ "c :- not a.\n" ++ "c :- x.\n" ++ "x :- not y.\n" ++ "y :- not x.\n" Right mp7 = readProgram mpr7 mpr8 = "f(a).\n" ++ "f(b).\n" ++ "f(c).\n" ++ "q(X):- f(X), not p(X). \n" ++ "p(X) :-f(X), not q(X). \n" Right mp8 = readProgram mpr8 mpr9 = "f(a).\n" ++ "f(b).\n" ++ "f(c).\n" ++ "f(d).\n" ++ "f(e).\n" ++ "f(f).\n" ++ "f(g).\n" ++ "f(h).\n" ++ "q(X):- f(X), not p(X), not r(X).\n" ++ "p(X) :-f(X), not q(X), not r(X).\n" ++ "r(X) :-f(X), not p(X), not q(X).\n" ++ ":- r(X).\n" Right mp9 = readProgram mpr9 mpr10 = ":- r(X).\n" Right mp10 = readProgram mpr10 mpr11 = "a.\n" ++ "b :- not a.\n" ++ "c :- a, not d.\n" ++ "d :- not c, not e.\n" ++ "e :- b.\n" ++ "e :- e.\n" Right mp11 = readProgram mpr11 mpr12 = "a :- not b.\n" ++ "b :- not a.\n" ++ "c :- a.\n" ++ "c :- b, d.\n" ++ "d :- b, c.\n" ++ "d :- e.\n" ++ "e :- b, not a.\n" ++ "e :- c, d.\n" Right mp12 = readProgram mpr12 mpr13 = "f(c).\n" ++ "q :- f(X), not p, not r.\n" ++ "p :-f(X), not q, not r\n." ++ "r :-f(X), not p, not q.\n" ++ ":- r.\n" ++ "p :- f(X), not q, not r.\n" ++ "f:-q.\n" Right mp13 = readProgram mpr13 -- test t0 = quickCheck prop_good_model t1 = (test_new mpr1)==(test_good mpr1) t2 = (test_new mpr2)==(test_good mpr2) t3 = (test_new mpr3)==(test_good mpr3) t4 = (test_new mpr4)==(test_good mpr4) t5 = (test_new mpr5)==(test_good mpr5) t6 = (test_new mpr6)==(test_good mpr6) t7 = (test_new mpr6a)==(test_good mpr6a) t8 = (test_new mpr6b)==(test_good mpr6b) t9 = (test_new mpr7)==(test_good mpr7) -- t10 = (test_new mpr8)==(test_good mpr8) -- test takes too long -- t11 = (test_new mpr9)==(test_good mpr9) -- test takes too long t12 = (test_new mpr10)==(test_good mpr10) t13 = (test_new mpr11)==(test_good mpr11) t14 = (test_new mpr12)==(test_good mpr12) t15 = (test_new mpr13)==(test_good mpr13) unit_test = trace ("test1: " ++ (show t1)) $ trace ("test2: " ++ (show t2)) $ trace ("test3: " ++ (show t3)) $ trace ("test4: " ++ (show t4)) $ trace ("test5: " ++ (show t5)) $ trace ("test6: " ++ (show t6)) $ trace ("test7: " ++ (show t7)) $ trace ("test8: " ++ (show t8)) $ trace ("test9: " ++ (show t9)) $ trace ("test12: " ++ (show t12)) $ trace ("test13: " ++ (show t13)) $ trace ("test14: " ++ (show t14)) $ trace ("test15: " ++ (show t15)) $ t1&&t2&&t3&&t4&&t5&&t6&&t7&&t8&&t9&&t12&&t13&&t14&&t15
sthiele/hasple
Test.hs
gpl-3.0
5,421
0
34
1,359
1,464
748
716
148
2
-- | Tests main module Main where import qualified MagneturiTests as Muri import qualified BencodeTests as Benc import qualified MetainfoTests as Minfo main :: IO () main = do Muri.tests Minfo.tests Benc.tests
vu3rdd/functorrent
test/Main.hs
gpl-3.0
220
0
7
42
53
33
20
9
1
{-| Module : Videotex Description : Copyright : (c) Frédéric BISSON, 2014 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX -} module Minitel.Type.Videotex ( MColor , ToMColor (toMColor) , Color (Black, Red, Green, Yellow, Blue, Magenta, Cyan, White) , Grey (Grey0, Grey1, Grey2, Grey3, Grey4, Grey5, Grey6, Grey7) , WhatToRemove (Column, Row) , WhatToInsert , CharSet (G0, G1, G'0, G'1) , CharWidth (SimpleWidth, DoubleWidth) , CharHeight (SimpleHeight, DoubleHeight) , WhatToClear (Everything, EndOfLine, EndOfScreen, StartOfScreen , StartOfLine, Line, StatusLine, ReallyEverything ) , MMode (VideoTex, Mixed, Terminal) ) where import Minitel.Type.MNatural (MNat) default (MNat) -- | Though the Minitel is generally shipped with a monochrome screen, it -- actually supports colors type MColor = MNat -- | Type class helping to convert a color to the actual color code of the -- Minitel class ToMColor a where toMColor :: a -> MColor -- | Colors the Minitel is able to render data Color = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White deriving (Ord, Eq, Show) -- | Grey scale the Minitel is able to render data Grey = Grey0 | Grey1 | Grey2 | Grey3 | Grey4 | Grey5 | Grey6 | Grey7 deriving (Ord, Eq, Show) instance ToMColor Color where toMColor a = case a of Black -> 0 Red -> 1 Green -> 2 Yellow -> 3 Blue -> 4 Magenta -> 5 Cyan -> 6 White -> 7 instance ToMColor Grey where toMColor a = case a of Grey0 -> 0 Grey1 -> 4 Grey2 -> 1 Grey3 -> 5 Grey4 -> 2 Grey5 -> 6 Grey6 -> 3 Grey7 -> 7 -- | Defines what can be removed on the Minitel screen data WhatToRemove = Column | Row -- | Defines what can be inserted on the Minitel screen type WhatToInsert = WhatToRemove -- | The Minitel uses four character sets: G0 and G1 data CharSet = G0 | G1 | G'0 | G'1 -- | The Minitel is able to double width or height of characters data CharWidth = SimpleWidth | DoubleWidth deriving Show data CharHeight = SimpleHeight | DoubleHeight deriving Show -- | Defines what can be cleared on the Minitel screen data WhatToClear = Everything -- ^ Clear everything except the status | EndOfLine -- ^ Clear from cursor to end of line | EndOfScreen -- ^ Clear from cursor to end of screen | StartOfScreen -- ^ Clear from cursor to start of screen | StartOfLine -- ^ Clear from cursor to start of line | Line -- ^ Clear the current line | StatusLine -- ^ Clear the status line | ReallyEverything -- ^ Clear everything and the status line -- | The Minitel supports 3 modes, with VideoTex being the standard one with -- semigraphic 40 columns. Terminal (TeleInformatique) mode is able to -- display textual 80 columns. data MMode = VideoTex | Mixed | Terminal deriving (Ord, Eq, Show)
Zigazou/HaMinitel
src/Minitel/Type/Videotex.hs
gpl-3.0
3,111
0
8
889
536
350
186
75
0
module XMonad.Hooks.DynamicLog.PrettyPrinter.PrettyLog where import XMonad.Hooks.DynamicLog.PrettyPrinter.DynamicLog
Fizzixnerd/xmonad-config
site-haskell/src/XMonad/Hooks/DynamicLog/PrettyPrinter/PrettyLog.hs
gpl-3.0
119
0
4
7
17
13
4
2
0
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE QuasiQuotes #-} -- | TODO we need to fix the start symbol (not that important, from whatever -- non-terminal we read the final result, make said non-terminal the start -- symbol. module Main where import qualified Language.Haskell.TH as TH import TupleTH import BioInf.GrammarProducts import BioInf.GrammarProducts.TH main :: IO () main = return () --x = $(pr "x") --hmm :: String -- hmm = [qqGV| -- Define the grammar "Test1" with one non-terminal X and two terminals "a" and -- "-". The Product will be named "Prod" (and the emitted symbol will be -- "gProd". We remove one symbol from the final grammar, namely the terminal -- made up of only deletions. All production rules with just that symbol will -- be deleted as well. -- -- TODO add algebra functions "X -> .f X a" .. if we use only one function ".f" -- and keep that one polymorphic, as down below, we should be happy enough as -- the product op should generate only one function ".ffff" for us. [qqGDhere| Grammar: Test1 N: X T: p T: a T: - T: e F: f F: g X -> f $ X p a X -> g $ X p - // Product: Prod Prod: Test1 * Test1 * Test1 * Test1 remove: -,-,-,- addrule: X,X,X,X -> h,h,h,h $ e,e,e,e // |] {- Grammar: Test1 X -> f $ X p a X -> g $ X p - // Grammar: Test2 X -> h $ e // Grammar: Test3 X -> i $ - Product: Prod Prod: Test1 ^>< 4 `union` Test2 ^>< 4 \\ Test3 ^>< 4 // -} allTuples = $(subtuples 4 2) {- foldTuples = $(foldlTuple 6) sumOfPairs f x = foldTuples f x . allTuples -} type LookupTable = () -- how to look up? -- | we probably want to add "x" later, not in each pairEval function ?! On -- the other hand, this is more like the usual algebra stuff, especially with -- regards to backtracking ... class PairEval a b where pairEval :: LookupTable -> Int -> (a,b) -> Int instance PairEval Int Int where pairEval lkup x (a,b) = x + (a+b) -- replace (a+b) with "lkup a b" instance PairEval Int () where pairEval lkup x (a,()) = x + (a) instance PairEval () Int where pairEval lkup x ((),a) = x + (a) instance PairEval () () where pairEval lkup x ((),()) = x + 0 allPE lkup x t = $(sumTuple 6) $ pe $ allTuples t where pe (a,b,c,d,e,f) = ( pairEval lkup x a , pairEval lkup x b , pairEval lkup x c , pairEval lkup x d , pairEval lkup x e , pairEval lkup x f ) --finalSOP = sumOfPairs (pairEval (undefined :: LookupTable)) i :: Int i = 1 {- -- We want and need attributes (f,g here) to be able to identify algebra -- functions we need to create. Maybe we can do it without explicit naming? -- More of a U/I questions. Grammar: Test_1 N: X T: a F: _f _g X -> _f < a X a | _g < X a -} {- test = [grammar| -- "-" aligns with terminals (doesn't introduce a new terminal hole), but -- modifies the vectorial terminal in the respective dimension to not advance. -- data VC <ynm> <xs>, where ynm = Yes|No|Maybe. Yes advances, No doesn't -- advance, maybe produces two cases, one advancing, one not. And since these -- are empty data decls, they are optimized away during compilation. Grammar: AlignAffine N: X Y T: u - X -> X u X -> Y u Y -> X - Y -> Y - |] -} -- example we want to be able to parse {- -- comments "--" should be comments -- simple productions. All uppercase strings provide non-terminals. All -- lower-case strings provide terminals. Different strings produce different -- symbols. This grammar will yield an ADPfusion grammar with "holes" for X,Y -- non-terminals. It will also provide "holes" for uu, u, v, z terminals. The -- special terminal "-" takes a normal character parser (like "Chr" from -- ADPfusion) and allows this parser to advance 0 characters. This is only -- really useful in higher-dimensional parsing, where we want to introduce -- in-del's X -> X uu X -> u X X -> u X v X -> u X v Y z Y -> X u | Y u -} {- -- In addition we want attributes for our grammars. <Char> is of type -- Z:.Char:.Char:.Char for 3-cross, and Z:.Char:.Char for 2-sequence alignment. X -> X u match :: \xi -> <Char> -> \xi || \xi is the E-type of the non-terminal table (here: Int) X -> Y u Y -> X - Y -> Y - -} {- -- the 2d version X -> Xu | Xu | Yu | Yu || f X1X2 <u1,u2> = X1X2 + match (u1,u2) X Xu | Yu | Xu | Yu || f :: Int -> <C,C> -> Int X -> Xu | Xu | Yu | Yu Y X- | Y- | X- | Y- Y -> X- | X- | Y- | Y- X Xu | Yu | Xu | Yu Y -> X- | X- | Y- | Y- Y X- | Y- | X- | Y- -} {- N: F^[0..2 | 3] -- these are three non-terminals, indexed by ints. the (| 3) "mod 3" operator leads to wrap-around T: u v w . F^i -> F^i u v w | F^i . . . -- one should remove productions where the RHS contains only "delete" terminals F^i -> F^(i+1) . v w F^i -> F^(i+2) . . w === N: P T: a . P -> P a | P . -}
choener/GrammarProducts
old/MultiAlign.hs
gpl-3.0
4,924
0
10
1,212
429
249
180
34
1
{-# LANGUAGE PatternGuards #-} {-# LANGUAGE NoMonomorphismRestriction #-} -- | -- -- local TODO list -- -- - build sstree -- - have diagrams running -- - be able to draw overlapped secondary structures -- - implement algorithm for being free of overlaps -- -- TODO we are repeating a lot of existing code for the sake of easier -- transition to C. fix this! module Main where import qualified Diagrams.Prelude as Dia import qualified Diagrams.Backend.Cairo.CmdLine as Dia import Data.Tree import Data.List import Data.Ord import Biobase.Primary import Biobase.Secondary import qualified Biobase.Secondary.Diagrams as D -- ** Construction of individual RNA secondary structure features and bounding -- boxes. Each individual element lives in its own local vector space. -- Combination of elements requires translating and rotating positional -- coordinates and bounding box coordinates. -- -- Again, we use what "diagrams" gives us but are verbose (and hopefully clear) -- on how to write this in C. -- -- The individual nucleotide position are given in 5' -> 3' order. The first 5' -- nucleotide forms the local origin. -- -- TODO For now, all construction functions produce "anonymous" structures that -- do not contain any nucleotide annotations. In principle, it should be "easy" -- later on, to annotate accordingly -- considering that we return only "R2" -- points for the nucleotides and the bounding boxes. -- -- TODO this could (and should) later on be extended to allow for different -- kinds of construction algorithms. -- -- TODO weird, if this works out, we will have a 5'->3' chain of nucleotide -- positions corresponding /exactly/ to the chain of nucleotides of the input. -- Hmm... -- -- TODO whenever we call one of stem, unpairedLoop, etc we need to test the -- resulting new thing for intersections... -- | Create a hairpin. -- -- TODO Should we use polytopes or circles? -- -- TODO right now, we always produce the same thing, for testing only. hairpin :: Int -> Candidates hairpin k = [(xs, Hard xs)] where xs = [ (0,0), (0,1), (1,1), (1,0) ] -- | A stem extends an existing structure by two nucleotides and produces a new -- bounding box. -- -- TODO switch from lists to a data structure that allows prepend/append in the -- same amount of time? stem :: Candidates -> Candidates stem cs = map f cs where f (xs,box) = (h : nxs ++ [l], nbox) where nxs = map (+(0,1)) xs nbox = softBox $ [translateBox (0,1) box, hardBox [(1,1),h,l]] h = (0,0) l = (1,0) -- | Bulges and interior loops. can be in stretched "stem-form" or with one of -- several possible angles. The possibilities are sorted by how nice they are, -- or whatever... . "i" and "j" are the number of unpaired nucleotides on -- either side. And again, we have to discuss if the should be a smooth form or -- an angled form on how to draw the unpaired stuff. unpairedLoop :: Int -> Int -> Candidates -> Candidates unpairedLoop i j cs | i==0 && j==0 = stem cs | otherwise = as ++ map stretched cs where -- Before trying the stretched version, we try to draw bulges and interior -- loops at an angle. If the number of relative unpairedness between the -- two strands is two small, we don't allow angles. as = if False then map angled cs else [] -- Ok, this smells of unification. Dependent on relative difference, we -- allow for certain kinds of angles... angled (xs,box) = undefined where angledness = fromIntegral (i+1) / fromIntegral (j+1) -- An interior loop that has been "stretched" to look like a normal stem. -- Nucleotides are supposed to be equidistant from each other for each -- individual strand. stretched (xs,box) = ([h] ++ unpI ++ nxs ++ unpJ ++ [l], nbox) where nxs = map (+(0, mij+1)) xs mij = fromIntegral $ max i j iScale = mij / fromIntegral i jScale = mij / fromIntegral j unpI = [ (0, fromIntegral k * iScale) | k<-[1..i] ] unpJ = [ (1, fromIntegral k * jScale) | k<-[1..j] ] nbox = softBox $ [translateBox (0,mij+1) box, hardBox [(0,0),(1,mij+1)]] h = (0,0) l = (1,0) -- | And finally, multibranched loops. Dependent on the number of branches -- (remember the additional one going "out"), we select possible angles. -- -- TODO For now, we just subdivide equally and see what happens, later on we -- probably have to take some state into account which restricts the total -- available angular freedom. -- -- TODO Simple hairpins may branch off at any point, complex stem structures -- may only branch off at certain angles. So basically, in "n" we count the -- number of complex things ... ? multibranchedLoop :: [Region] -> Candidates multibranchedLoop rs = undefined where n = 1 + (length . filter isPaired $ rs) l = 2 * n + sum (map len . filter isUnpaired $ rs) -- total number of nucleotides needed on the polytope / circle -- | Multibranched loops are combined of an ordered list of unpaired regions -- and regions closed by a pair. In addition, paired regions are actually each -- a list of one or more candidates. data Region = Unpaired {len :: Int} | Paired {cands :: Candidates} deriving (Show) isUnpaired :: Region -> Bool isUnpaired (Unpaired _) = True isUnpaired _ = False isPaired :: Region -> Bool isPaired (Paired _) = True isPaired _ = False test = unpairedLoop 2 4 . stem . hairpin $ 4 t = mapM_ print test -- | A candidate structure is a list of coordinates in 5'->3' form and a -- bounding box around that all. type Candidate = ([R2], BBox) -- | We typically deal with many candidates that then have to be evaluated. type Candidates = [Candidate] -- ** Bounding boxes. -- | We have two kinds of bounding boxes. Hard bounding boxes are concrete -- objects that may not intersect. Soft bounding boxes are a collection of soft -- and hard bounding boxes. On intersection with a soft bounding box, we have -- to recursively test until we have decided that no hard bounding box -- intersects or that there is indeed intersection. It is hoped, that most -- potential intersections are solved by the soft bounding boxes not -- intersecting, in which case the calculations are simpler. data BBox = Hard {bbox :: [R2]} | Soft {bbox :: [R2], subs :: [BBox]} deriving (Show) -- | Creation of a soft bounding box, given other bounding boxes. The only -- strict requirement is that the soft bounding box "bbox" is a convex -- polytope. -- -- All boxes that are to be enclosed have to live in the same local vector -- space! -- -- Currently, the enclosing box is a simple local-axis aligned bounding box. -- -- TODO let us check out, if calculating the smallest convex polytope reduces -- the runtime. softBox :: [BBox] -> BBox softBox bs = Soft xs bs where minX = minimum . concatMap (map fst . bbox) $ bs maxX = maximum . concatMap (map fst . bbox) $ bs minY = minimum . concatMap (map snd . bbox) $ bs maxY = maximum . concatMap (map snd . bbox) $ bs xs = [ (x,y) | x<-[minX,maxX], y<-[minY,maxY] ] -- | This produces a hard bounding box, which again is just a local-axis -- aligned bounding box. hardBox :: [R2] -> BBox hardBox bs = Hard xs where minX = minimum . map fst $ bs maxX = maximum . map fst $ bs minY = minimum . map snd $ bs maxY = maximum . map snd $ bs xs = [ (x,y) | x<-[minX,maxX], y<-[minY,maxY] ] -- | This function performs a recursive test to check if there are -- intersections between two 'BBox'es. As below, we either produce a seperating -- hyperplane or return 'Nothing' on intersection. If a soft bounding box is -- involved, the seperation is calculated based on the soft box, not the -- individual hard boxes. If the soft boxes intersect, but not the hard boxes, -- the answer is Just ((0,0),(0,0)) -- -- NOTE just to make sure: each individual box is NOT checked for consistency. boxIsect :: BBox -> BBox -> Maybe (R2,R2) boxIsect (Hard xs) (Hard ys) = seperatingHyperPlane xs ys boxIsect (Hard xs) (Soft ys sys) | Just shp <- seperatingHyperPlane xs ys = Just shp | any (==Nothing) is = Nothing | otherwise = Just zero where is = map (boxIsect (Hard xs)) sys zero = ((0,0),(0,0)) boxIsect x@(Soft _ _) y@(Hard _) = boxIsect y x boxIsect (Soft xs sxs) (Soft ys sys) | Just shp <- seperatingHyperPlane xs ys = Just shp | any (==Nothing) is = Nothing | otherwise = Just zero where is = [ boxIsect sx sy | sx<-sxs, sy<-sys ] zero = ((0,0),(0,0)) -- | Translate all coordinates of a bounding box. translateBox :: R2 -> BBox -> BBox translateBox p (Hard xs) = Hard $ map (+p) xs translateBox p (Soft xs sxs) = Soft (map (+p) xs) (map (translateBox p) sxs) -- | Rotate all coordinates of a bounding box. rotateBox :: Deg -> BBox -> BBox rotateBox theta (Hard xs) = Hard $ map (Dia.rotate theta) xs rotateBox theta (Soft xs sxs) = Soft (map (Dia.rotate theta) xs) (map (rotateBox theta) sxs) -- ** Calculations in 2-dimensional euclidean space. We use "diagrams" / -- "vector-space" functions but give the required calculations for C code, too. -- | Distance between two points in 2-d. -- -- |x,y| = sqrt ( (x_1-y_1)^2 + (x_2-y_2)^2 ) distance :: R2 -> R2 -> Double distance = Dia.distance -- | Given two sets of points, "xs" and "ys", find the two points with minimal -- distance. minimalDistance :: [R2] -> [R2] -> (R2,R2) minimalDistance xs ys = minimumBy (comparing $ uncurry distance) [ (x,y) | x<-xs, y<-ys ] -- | Given two sets of points, "xs" and "ys", determine if there exists a -- seperating hyperplane (how fancy to say in 2D). If yes, return "Just -- (originvector, unit normal)", otherwise return "Nothing". seperatingHyperPlane :: [R2] -> [R2] -> Maybe (R2,R2) seperatingHyperPlane xs ys | null xs || null ys = Nothing -- need points... | all (head sxs ==) sxs && all (head sys ==) sys && head sxs /= head sys = Just (ov,n) -- all points are on their respective sides of the hyperplane and the two sets are on different sides | otherwise = Nothing where (sX,sY) = minimalDistance xs ys ov = (sX+sY) / 2 n = Dia.normalized ov -- seperating hyperplane: ov + n txs = map (subtract ov) xs tys = map (subtract ov) ys dxs = map (n Dia.<.>) txs -- <.> is the inner/dot product dys = map (n Dia.<.>) tys sxs = map signum dxs sys = map signum dys -- ** Types and other stuff -- | The type of 2-d vectors: (Double,Double) type R2 = Dia.R2 -- | What kind of rotation are we doing, 0..360 degree kinds. type Deg = Dia.Deg -- ** test data testX = [ (0,0), (2,0), (0,2), (2,2) ] testY = map (+(1,1)) testX testZ = map (+(10,10)) testX main = return () {- -- draw test, these functions should produce all possible drawings, one after -- another. a filter can then be used to keep the first viable one. -- -- in a twist, we can "take 1000" or so, and if we get no result, we reduce the -- allowed angles where there are overlaps. drawTest (D.SSTree ij@(i,j) a []) = regPoly (j-i+1) 1 # withBounds (square 1 :: Diagram Cairo R2) -- showOrigin drawTest (D.SSTree ij@(i,j) a [x@(D.SSTree (k,l) _ _)]) -- missing: IL -- bulge right | j-l > 1 = append (-1,0) (regPoly 4 1 # lc blue # showOrigin) (drawTest x # rotateBy ( 1/4)) -- bulge left | k-i > 1 = append (1 ,0) (regPoly 4 1 # lc blue # showOrigin) (drawTest x # rotateBy (-1/4)) -- normal stem | k-i==1 && j-l==1 = append (0,1) (regPoly 4 1 # showOrigin) (drawTest x) | otherwise = error $ show (i,j,k,l) drawTest (D.SSTree ij@(i,j) a xs) -- a simple Y-shaped ML | length xs == 2 = append (1,0) (append (-1,0) (regPoly 4 1 # lc red # showOrigin) (drawTest (xs!!0) # rotateBy (1/4))) (drawTest (xs!!1) # rotateBy (-1/4)) -- 4-way junction -- anything bigger leads to regular n-things (should work for 4-way junction, too) drawTest (D.SSExt l a [x]) = drawTest x pair (i,j) = (circle 1 ||| hrule 1 ||| circle 1) # showOrigin -- | Hard bounding boxes for individual objects, soft bounding boxes for -- collections of objects. data BBox = Hard Points4 | Soft Points4 [BBox] -- | Determine if there is any intersection between two bounding boxes. intsect :: BBox -> BBox -> Bool intsect (Hard x) (Hard y) = isect x y intsect (Hard x) (Soft y ys) = isect x y && any (intsect (Hard x)) ys intsect (Soft x xs) (Hard y) = isect x y && any (intsect (Hard y)) xs intsect (Soft x xs) (Soft y ys) = isect x y && or [intsect x' y' | x'<-xs, y'<-ys] -- | Intersection between bounding boxes. isect xs ys = undefined where -- the two points minX,minY with minimal distance from each other (minX,minY) = minimumBy (comparing (uncurry dist)) [ (x,y) | x<-xs, y<-ys ] -- center point between x and y c = minX + (minY-minX)/2 -- normal vector at "c" nC = let (cx,cy) = c; l = vlen c in (cy, negate cx) `scale2d` (1/l) -- | scale vector by scalar scale2d (x,y) s = (x*s,y*s) -- | distance between points dist :: P2D -> P2D -> Double dist (x1,x2) (y1,y2) = sqrt $ (x1-y1)^2 + (x2-y2)^2 -- | length of a vector vlen (x,y) = sqrt $ x^2+y^2 type Points4 = [P2D] type P2D = (Double,Double) -- ** testing area main = defaultMain $ xyz xyz = drawTest big bulges = D.d1sTree $ D.mkD1S "(((((...(((...)))))).))" multil = D.d1sTree $ D.mkD1S "((.((...))..((....)).))" big = D.d1sTree $ D.mkD1S "((((..((....)))).(((((...))..))).))" verybig = D.d1sTree $ D.mkD1S "(.....(((.(((((((((((.....(((.....)))......)))))..((((((((.((((((....))).)))..(((((((((.((((((((((((......(((((..(((((((....))))))).)))))))).)).)))))))))))))))))).))))))................))))))))).......)" -}
choener/RNAdraw
RNAdraw.hs
gpl-3.0
13,512
0
14
2,768
2,347
1,331
1,016
122
2
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with grid. If not, see <http://www.gnu.org/licenses/>. -- module Game.Grid.GridWorld.CameraCommand ( CameraCommand (..), camcmdWait, camcmdTurn, camcmdTurnAdd, camcmdView, camcmdViewAdd, camcmdTurnView, camcmdTurnAddView, camcmdTurnViewAdd, camcmdTurnAddViewAdd, ) where import MyPrelude import Game.MEnv import Game.Data.View import Game.Grid.GridWorld.Turn data CameraCommand = CameraCommand { -- Turn cameracommandTurn :: !Turn, cameracommandTurnSpeed :: !Float, cameracommandTurnIsAdd :: !Bool, -- View cameracommandView :: !View, cameracommandViewSpeed :: !Float, cameracommandViewIsAdd :: !Bool, cameracommandTicks :: !Tick -- fixme: Node } -------------------------------------------------------------------------------- -- camcmdWait :: Tick -> CameraCommand camcmdWait ticks = camcmdViewAdd ticks 1.0 mempty camcmdTurn :: Tick -> Float -> Turn -> CameraCommand camcmdTurn ticks speed turn = CameraCommand { cameracommandTurn = turn, cameracommandTurnSpeed = speed, cameracommandTurnIsAdd = False, cameracommandView = mempty, cameracommandViewSpeed = 0.0, cameracommandViewIsAdd = True, cameracommandTicks = ticks } camcmdTurnAdd :: Tick -> Float -> Turn -> CameraCommand camcmdTurnAdd ticks speed turn = CameraCommand { cameracommandTurn = turn, cameracommandTurnSpeed = speed, cameracommandTurnIsAdd = True, cameracommandView = mempty, cameracommandViewSpeed = 0.0, cameracommandViewIsAdd = True, cameracommandTicks = ticks } camcmdView :: Tick -> Float -> View -> CameraCommand camcmdView ticks speed view = CameraCommand { cameracommandTurn = mempty, cameracommandTurnSpeed = 0.0, cameracommandTurnIsAdd = True, cameracommandView = view, cameracommandViewSpeed = speed, cameracommandViewIsAdd = False, cameracommandTicks = ticks } camcmdViewAdd :: Tick -> Float -> View -> CameraCommand camcmdViewAdd ticks speed view = CameraCommand { cameracommandTurn = mempty, cameracommandTurnSpeed = 0.0, cameracommandTurnIsAdd = True, cameracommandView = view, cameracommandViewSpeed = speed, cameracommandViewIsAdd = True, cameracommandTicks = ticks } camcmdTurnView :: Tick -> Float -> Turn -> Float -> View -> CameraCommand camcmdTurnView ticks tspeed turn vspeed view = CameraCommand { cameracommandTurn = turn, cameracommandTurnSpeed = tspeed, cameracommandTurnIsAdd = False, cameracommandView = view, cameracommandViewSpeed = vspeed, cameracommandViewIsAdd = False, cameracommandTicks = ticks } camcmdTurnAddView :: Tick -> Float -> Turn -> Float -> View -> CameraCommand camcmdTurnAddView ticks tspeed turn vspeed view = CameraCommand { cameracommandTurn = turn, cameracommandTurnSpeed = tspeed, cameracommandTurnIsAdd = True, cameracommandView = view, cameracommandViewSpeed = vspeed, cameracommandViewIsAdd = False, cameracommandTicks = ticks } camcmdTurnViewAdd :: Tick -> Float -> Turn -> Float -> View -> CameraCommand camcmdTurnViewAdd ticks tspeed turn vspeed view = CameraCommand { cameracommandTurn = turn, cameracommandTurnSpeed = tspeed, cameracommandTurnIsAdd = False, cameracommandView = view, cameracommandViewSpeed = vspeed, cameracommandViewIsAdd = True, cameracommandTicks = ticks } camcmdTurnAddViewAdd :: Tick -> Float -> Turn -> Float -> View -> CameraCommand camcmdTurnAddViewAdd ticks tspeed turn vspeed view = CameraCommand { cameracommandTurn = turn, cameracommandTurnSpeed = tspeed, cameracommandTurnIsAdd = True, cameracommandView = view, cameracommandViewSpeed = vspeed, cameracommandViewIsAdd = True, cameracommandTicks = ticks }
karamellpelle/grid
source/Game/Grid/GridWorld/CameraCommand.hs
gpl-3.0
4,972
0
9
1,350
803
489
314
122
1
module Database.Design.Ampersand ( -- Data Constructors: A_Context , P_Context(..), P_Population(..), PairView(..), PairViewSegment(..), SrcOrTgt(..), P_Rule(..), Term(..), TermPrim(..), P_NamedRel(..), P_Sign(..), P_Concept(..), P_Declaration(..), P_Pattern(..), P_Gen(..) , P_Markup(..), PRef2Obj(..), PPurpose(..), PMeaning(..), Meta(..), MetaObj(..) , A_Concept(..), A_Gen(..) , Signature(..), ConceptDef(..), ConceptStructure(..) , Activity(..) , AMeaning(..) , Quad(..), Conjunct(..) , Fswitchboard(..), ECArule(..), Event(..), InsDel(..) -- (required for --haskell output) , Pattern(..) , Declaration(..) , IdentityDef(..) , ViewDef(..) , IdentitySegment(..) , ViewSegment(..) , Expression(..) , Population(..) , FSpec(..), concDefs , PlugSQL(..), SqlField(..), SqlTType(..), PlugInfo(..) , PAclause(..) , Rule(..) , Prop(..), RuleOrigin(..) , Lang(..) , SqlFieldUsage(..) , DnfClause(..) , Options(..), DocTheme(..) , FilePos(..), Origin(..) , mkPair -- * Classes: , Association(..), flp , Collection(..) , Named(..) , ObjectDef(..) , Relational(..) , Interface(..) , getInterfaceByName , SubInterface(..) , Object(..) , Plugable(..) , Motivated(..) , Traced(..) , Language(..) , ShowHS(..), ShowHSName(..), haskellIdentifier -- * Functions on concepts , (<==>),meet,join,sortWith,atomValuesOf , smallerConcepts, largerConcepts, rootConcepts -- * Functions on relations -- * Functions on rules -- * Functions on expressions: , conjNF, disjNF, simplify , cfProof,dfProof,normPA , lookupCpt , showPrf , notCpl, isCpl, isPos, isNeg, foldrMapExpression , (.==.), (.|-.), (./\.), (.\/.), (.-.), (./.), (.\.), (.<>.), (.:.), (.!.), (.*.) , deMorganERad, deMorganECps, deMorganEUni, deMorganEIsc , exprUni2list, exprIsc2list, exprCps2list, exprRad2list, exprPrd2list -- * Functions with plugs: , showPlug, plugFields, fldauto -- * Parser related stuff , parseADL1pExpr, CtxError , createFSpec -- * Type checking and calculus , Guarded(..), pCtx2aCtx , makeFSpec -- * Generators of output , generateAmpersandOutput -- * Prettyprinters , ShowADL(..), showSQL, showSign -- * Functions with Options , getOptions , verboseLn, verbose ,helpNVersionTexts -- * Other functions , eqCl, showErr, unCap,upCap,escapeNonAlphaNum, fatalMsg , ampersandVersionStr, ampersandVersionWithoutBuildTimeStr , Database.Design.Ampersand.Basics.putStr , Database.Design.Ampersand.Basics.hGetContents , Database.Design.Ampersand.Basics.hPutStr , Database.Design.Ampersand.Basics.hPutStrLn , Database.Design.Ampersand.Basics.readFile , Database.Design.Ampersand.Basics.writeFile , fst3, snd3, thd3 , blockParenthesize, addToLastLine, indent , trace, showTrace, showTraceTag -- * Stuff that should probably not be in the prototype , A_Markup(..), blocks2String, aMarkup2String, PandocFormat(..), Meaning(..) , rulefromProp , fullContents, AAtomPair, apLeft,apRight , Purpose(..), ExplObj(..) , ContextInfo,AAtomValue ) where import Database.Design.Ampersand.Core.AbstractSyntaxTree import Database.Design.Ampersand.FSpec.FSpec import Database.Design.Ampersand.ADL1 import Database.Design.Ampersand.Classes import Database.Design.Ampersand.Basics import Database.Design.Ampersand.FSpec import Database.Design.Ampersand.Input import Database.Design.Ampersand.Misc import Database.Design.Ampersand.Components import Database.Design.Ampersand.ADL1.Expression (isPos,isNeg,foldrMapExpression) import Database.Design.Ampersand.FSpec.ToFSpec.ADL2Plug (showPlug) import Database.Design.Ampersand.FSpec.ToFSpec.NormalForms import Database.Design.Ampersand.ADL1.P2A_Converters
guoy34/ampersand
src/Database/Design/Ampersand.hs
gpl-3.0
3,826
0
5
632
1,021
730
291
93
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Jobs.Projects.Jobs.SearchForAlert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Searches for jobs using the provided SearchJobsRequest. This API call is -- intended for the use case of targeting passive job seekers (for example, -- job seekers who have signed up to receive email alerts about potential -- job opportunities), and has different algorithmic adjustments that are -- targeted to passive job seekers. This call constrains the visibility of -- jobs present in the database, and only returns jobs the caller has -- permission to search against. -- -- /See:/ <https://cloud.google.com/talent-solution/job-search/docs/ Cloud Talent Solution API Reference> for @jobs.projects.jobs.searchForAlert@. module Network.Google.Resource.Jobs.Projects.Jobs.SearchForAlert ( -- * REST Resource ProjectsJobsSearchForAlertResource -- * Creating a Request , projectsJobsSearchForAlert , ProjectsJobsSearchForAlert -- * Request Lenses , pjsfaParent , pjsfaXgafv , pjsfaUploadProtocol , pjsfaAccessToken , pjsfaUploadType , pjsfaPayload , pjsfaCallback ) where import Network.Google.Jobs.Types import Network.Google.Prelude -- | A resource alias for @jobs.projects.jobs.searchForAlert@ method which the -- 'ProjectsJobsSearchForAlert' request conforms to. type ProjectsJobsSearchForAlertResource = "v3p1beta1" :> Capture "parent" Text :> "jobs:searchForAlert" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SearchJobsRequest :> Post '[JSON] SearchJobsResponse -- | Searches for jobs using the provided SearchJobsRequest. This API call is -- intended for the use case of targeting passive job seekers (for example, -- job seekers who have signed up to receive email alerts about potential -- job opportunities), and has different algorithmic adjustments that are -- targeted to passive job seekers. This call constrains the visibility of -- jobs present in the database, and only returns jobs the caller has -- permission to search against. -- -- /See:/ 'projectsJobsSearchForAlert' smart constructor. data ProjectsJobsSearchForAlert = ProjectsJobsSearchForAlert' { _pjsfaParent :: !Text , _pjsfaXgafv :: !(Maybe Xgafv) , _pjsfaUploadProtocol :: !(Maybe Text) , _pjsfaAccessToken :: !(Maybe Text) , _pjsfaUploadType :: !(Maybe Text) , _pjsfaPayload :: !SearchJobsRequest , _pjsfaCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsJobsSearchForAlert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pjsfaParent' -- -- * 'pjsfaXgafv' -- -- * 'pjsfaUploadProtocol' -- -- * 'pjsfaAccessToken' -- -- * 'pjsfaUploadType' -- -- * 'pjsfaPayload' -- -- * 'pjsfaCallback' projectsJobsSearchForAlert :: Text -- ^ 'pjsfaParent' -> SearchJobsRequest -- ^ 'pjsfaPayload' -> ProjectsJobsSearchForAlert projectsJobsSearchForAlert pPjsfaParent_ pPjsfaPayload_ = ProjectsJobsSearchForAlert' { _pjsfaParent = pPjsfaParent_ , _pjsfaXgafv = Nothing , _pjsfaUploadProtocol = Nothing , _pjsfaAccessToken = Nothing , _pjsfaUploadType = Nothing , _pjsfaPayload = pPjsfaPayload_ , _pjsfaCallback = Nothing } -- | Required. The resource name of the project to search within. The format -- is \"projects\/{project_id}\", for example, -- \"projects\/api-test-project\". pjsfaParent :: Lens' ProjectsJobsSearchForAlert Text pjsfaParent = lens _pjsfaParent (\ s a -> s{_pjsfaParent = a}) -- | V1 error format. pjsfaXgafv :: Lens' ProjectsJobsSearchForAlert (Maybe Xgafv) pjsfaXgafv = lens _pjsfaXgafv (\ s a -> s{_pjsfaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pjsfaUploadProtocol :: Lens' ProjectsJobsSearchForAlert (Maybe Text) pjsfaUploadProtocol = lens _pjsfaUploadProtocol (\ s a -> s{_pjsfaUploadProtocol = a}) -- | OAuth access token. pjsfaAccessToken :: Lens' ProjectsJobsSearchForAlert (Maybe Text) pjsfaAccessToken = lens _pjsfaAccessToken (\ s a -> s{_pjsfaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pjsfaUploadType :: Lens' ProjectsJobsSearchForAlert (Maybe Text) pjsfaUploadType = lens _pjsfaUploadType (\ s a -> s{_pjsfaUploadType = a}) -- | Multipart request metadata. pjsfaPayload :: Lens' ProjectsJobsSearchForAlert SearchJobsRequest pjsfaPayload = lens _pjsfaPayload (\ s a -> s{_pjsfaPayload = a}) -- | JSONP pjsfaCallback :: Lens' ProjectsJobsSearchForAlert (Maybe Text) pjsfaCallback = lens _pjsfaCallback (\ s a -> s{_pjsfaCallback = a}) instance GoogleRequest ProjectsJobsSearchForAlert where type Rs ProjectsJobsSearchForAlert = SearchJobsResponse type Scopes ProjectsJobsSearchForAlert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/jobs"] requestClient ProjectsJobsSearchForAlert'{..} = go _pjsfaParent _pjsfaXgafv _pjsfaUploadProtocol _pjsfaAccessToken _pjsfaUploadType _pjsfaCallback (Just AltJSON) _pjsfaPayload jobsService where go = buildClient (Proxy :: Proxy ProjectsJobsSearchForAlertResource) mempty
brendanhay/gogol
gogol-jobs/gen/Network/Google/Resource/Jobs/Projects/Jobs/SearchForAlert.hs
mpl-2.0
6,479
0
17
1,435
796
470
326
118
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Directory.ChromeosDevices.Action -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Take action on Chrome OS Device -- -- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.chromeosdevices.action@. module Network.Google.Resource.Directory.ChromeosDevices.Action ( -- * REST Resource ChromeosDevicesActionResource -- * Creating a Request , chromeosDevicesAction , ChromeosDevicesAction -- * Request Lenses , cdaResourceId , cdaPayload , cdaCustomerId ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.chromeosdevices.action@ method which the -- 'ChromeosDevicesAction' request conforms to. type ChromeosDevicesActionResource = "admin" :> "directory" :> "v1" :> "customer" :> Capture "customerId" Text :> "devices" :> "chromeos" :> Capture "resourceId" Text :> "action" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ChromeOSDeviceAction :> Post '[JSON] () -- | Take action on Chrome OS Device -- -- /See:/ 'chromeosDevicesAction' smart constructor. data ChromeosDevicesAction = ChromeosDevicesAction' { _cdaResourceId :: !Text , _cdaPayload :: !ChromeOSDeviceAction , _cdaCustomerId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ChromeosDevicesAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cdaResourceId' -- -- * 'cdaPayload' -- -- * 'cdaCustomerId' chromeosDevicesAction :: Text -- ^ 'cdaResourceId' -> ChromeOSDeviceAction -- ^ 'cdaPayload' -> Text -- ^ 'cdaCustomerId' -> ChromeosDevicesAction chromeosDevicesAction pCdaResourceId_ pCdaPayload_ pCdaCustomerId_ = ChromeosDevicesAction' { _cdaResourceId = pCdaResourceId_ , _cdaPayload = pCdaPayload_ , _cdaCustomerId = pCdaCustomerId_ } -- | Immutable id of Chrome OS Device cdaResourceId :: Lens' ChromeosDevicesAction Text cdaResourceId = lens _cdaResourceId (\ s a -> s{_cdaResourceId = a}) -- | Multipart request metadata. cdaPayload :: Lens' ChromeosDevicesAction ChromeOSDeviceAction cdaPayload = lens _cdaPayload (\ s a -> s{_cdaPayload = a}) -- | Immutable id of the Google Apps account cdaCustomerId :: Lens' ChromeosDevicesAction Text cdaCustomerId = lens _cdaCustomerId (\ s a -> s{_cdaCustomerId = a}) instance GoogleRequest ChromeosDevicesAction where type Rs ChromeosDevicesAction = () type Scopes ChromeosDevicesAction = '["https://www.googleapis.com/auth/admin.directory.device.chromeos"] requestClient ChromeosDevicesAction'{..} = go _cdaCustomerId _cdaResourceId (Just AltJSON) _cdaPayload directoryService where go = buildClient (Proxy :: Proxy ChromeosDevicesActionResource) mempty
rueshyna/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/ChromeosDevices/Action.hs
mpl-2.0
3,883
0
18
945
477
283
194
79
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AndroidPublisher.Entitlements.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists the user\'s current inapp item or subscription entitlements -- -- /See:/ <https://developers.google.com/android-publisher Google Play Developer API Reference> for @androidpublisher.entitlements.list@. module Network.Google.Resource.AndroidPublisher.Entitlements.List ( -- * REST Resource EntitlementsListResource -- * Creating a Request , entitlementsList , EntitlementsList -- * Request Lenses , elPackageName , elToken , elStartIndex , elProductId , elMaxResults ) where import Network.Google.AndroidPublisher.Types import Network.Google.Prelude -- | A resource alias for @androidpublisher.entitlements.list@ method which the -- 'EntitlementsList' request conforms to. type EntitlementsListResource = "androidpublisher" :> "v2" :> "applications" :> Capture "packageName" Text :> "entitlements" :> QueryParam "token" Text :> QueryParam "startIndex" (Textual Word32) :> QueryParam "productId" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] EntitlementsListResponse -- | Lists the user\'s current inapp item or subscription entitlements -- -- /See:/ 'entitlementsList' smart constructor. data EntitlementsList = EntitlementsList' { _elPackageName :: !Text , _elToken :: !(Maybe Text) , _elStartIndex :: !(Maybe (Textual Word32)) , _elProductId :: !(Maybe Text) , _elMaxResults :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'EntitlementsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'elPackageName' -- -- * 'elToken' -- -- * 'elStartIndex' -- -- * 'elProductId' -- -- * 'elMaxResults' entitlementsList :: Text -- ^ 'elPackageName' -> EntitlementsList entitlementsList pElPackageName_ = EntitlementsList' { _elPackageName = pElPackageName_ , _elToken = Nothing , _elStartIndex = Nothing , _elProductId = Nothing , _elMaxResults = Nothing } -- | The package name of the application the inapp product was sold in (for -- example, \'com.some.thing\'). elPackageName :: Lens' EntitlementsList Text elPackageName = lens _elPackageName (\ s a -> s{_elPackageName = a}) elToken :: Lens' EntitlementsList (Maybe Text) elToken = lens _elToken (\ s a -> s{_elToken = a}) elStartIndex :: Lens' EntitlementsList (Maybe Word32) elStartIndex = lens _elStartIndex (\ s a -> s{_elStartIndex = a}) . mapping _Coerce -- | The product id of the inapp product (for example, \'sku1\'). This can be -- used to restrict the result set. elProductId :: Lens' EntitlementsList (Maybe Text) elProductId = lens _elProductId (\ s a -> s{_elProductId = a}) elMaxResults :: Lens' EntitlementsList (Maybe Word32) elMaxResults = lens _elMaxResults (\ s a -> s{_elMaxResults = a}) . mapping _Coerce instance GoogleRequest EntitlementsList where type Rs EntitlementsList = EntitlementsListResponse type Scopes EntitlementsList = '[] requestClient EntitlementsList'{..} = go _elPackageName _elToken _elStartIndex _elProductId _elMaxResults (Just AltJSON) androidPublisherService where go = buildClient (Proxy :: Proxy EntitlementsListResource) mempty
rueshyna/gogol
gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Entitlements/List.hs
mpl-2.0
4,398
0
17
1,061
662
382
280
93
1
{- ORMOLU_DISABLE -} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE LambdaCase #-} module GoldenSpec.Util (golden) where import Control.Monad.IO.Class (liftIO) import Graphics.Implicit (SymbolicObj3, writeSTL) import Prelude (IO, FilePath, Bool (True, False), String, Double, pure, (==), readFile, writeFile, (>>=), (<>), ($)) import System.Directory (getTemporaryDirectory, doesFileExist) import System.IO (hClose, openTempFile) import Test.Hspec (it, shouldBe, SpecWith) ------------------------------------------------------------------------------ -- | Construct a golden test for rendering the given 'SymbolicObj3' at the -- specified resolution. On the first run of this test, it will render the -- object and cache the results. Subsequent test runs will compare their result -- to the cached one. This is valuable for ensuring mesh generation doesn't -- break across commits. -- -- The objects are cached under @tests/golden/@, with the given name. Deleting -- this file is sufficient to update the test if changs in the mesh generation -- are intended. golden :: String -> Double -> SymbolicObj3 -> SpecWith () golden name resolution sym = it (name <> " (golden)") $ do (res, cached) <- liftIO $ do temp_fp <- getTemporaryFilePath "stl" -- Output the rendered mesh writeSTL resolution temp_fp sym !res <- readFile temp_fp let golden_fp = "./tests/golden/" <> name <> ".stl" -- Check if the cached results already exist. doesFileExist golden_fp >>= \case True -> pure () -- If not, save the mesh we just created in the cache. False -> writeFile golden_fp res !cached <- readFile golden_fp pure (res, cached) -- Finally, ceck if the two meshes are equal. if res == cached then pure () else False `shouldBe` True ------------------------------------------------------------------------------ -- | Get a temporary filepath with the desired extension. On unix systems, this -- is a file under @/tmp@. Useful for tests that need to write files. getTemporaryFilePath :: String -- ^ File extension -> IO FilePath getTemporaryFilePath ext = do tempdir <- getTemporaryDirectory -- The only means available to us for getting a temporary filename also opens -- its file handle. Because the 'writeSTL' function opens the file handle -- itself, we must first close our handle. (fp, h) <- openTempFile tempdir "implicit-golden" hClose h pure $ fp <> "." <> ext
colah/ImplicitCAD
tests/GoldenSpec/Util.hs
agpl-3.0
2,449
0
17
447
419
236
183
32
3
module Network.Haskoin.Node.Bloom ( BloomFlags(..) , BloomFilter(..) , FilterLoad(..) , FilterAdd(..) , bloomCreate , bloomInsert , bloomContains , isBloomValid , isBloomEmpty , isBloomFull ) where import Control.Monad (replicateM, forM_) import Control.DeepSeq (NFData, rnf) import Data.Word import Data.Bits import Data.Hash.Murmur (murmur3) import Data.Binary (Binary, get, put) import Data.Binary.Get ( getWord8 , getWord32le , getByteString ) import Data.Binary.Put ( putWord8 , putWord32le , putByteString ) import qualified Data.Foldable as F import qualified Data.Sequence as S import qualified Data.ByteString as BS import Network.Haskoin.Node.Types -- 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001% maxBloomSize :: Int maxBloomSize = 36000 maxHashFuncs :: Word32 maxHashFuncs = 50 ln2Squared :: Double ln2Squared = 0.4804530139182014246671025263266649717305529515945455 ln2 :: Double ln2 = 0.6931471805599453094172321214581765680755001343602552 bitMask :: [Word8] bitMask = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80] -- | The bloom flags are used to tell the remote peer how to auto-update -- the provided bloom filter. data BloomFlags = BloomUpdateNone -- ^ Never update | BloomUpdateAll -- ^ Auto-update on all outputs | BloomUpdateP2PubKeyOnly -- ^ Only auto-update on outputs that are pay-to-pubkey or pay-to-multisig. -- This is the default setting. deriving (Eq, Show, Read) instance NFData BloomFlags where rnf x = seq x () instance Binary BloomFlags where get = go =<< getWord8 where go 0 = return BloomUpdateNone go 1 = return BloomUpdateAll go 2 = return BloomUpdateP2PubKeyOnly go _ = fail "BloomFlags get: Invalid bloom flag" put f = putWord8 $ case f of BloomUpdateNone -> 0 BloomUpdateAll -> 1 BloomUpdateP2PubKeyOnly -> 2 -- | A bloom filter is a probabilistic data structure that SPV clients send to -- other peers to filter the set of transactions received from them. Bloom -- filters are probabilistic and have a false positive rate. Some transactions -- that pass the filter may not be relevant to the receiving peer. By -- controlling the false positive rate, SPV nodes can trade off bandwidth -- versus privacy. data BloomFilter = BloomFilter { bloomData :: !(S.Seq Word8) -- ^ Bloom filter data , bloomHashFuncs :: !Word32 -- ^ Number of hash functions for this filter , bloomTweak :: !Word32 -- ^ Hash function random nonce , bloomFlags :: !BloomFlags -- ^ Bloom filter auto-update flags } deriving (Eq, Show, Read) instance NFData BloomFilter where rnf (BloomFilter d h t g) = rnf d `seq` rnf h `seq` rnf t `seq` rnf g instance Binary BloomFilter where get = BloomFilter <$> (S.fromList <$> (readDat =<< get)) <*> getWord32le <*> getWord32le <*> get where readDat (VarInt len) = replicateM (fromIntegral len) getWord8 put (BloomFilter dat hashFuncs tweak flags) = do put $ VarInt $ fromIntegral $ S.length dat forM_ (F.toList dat) putWord8 putWord32le hashFuncs putWord32le tweak put flags -- | Set a new bloom filter on the peer connection. newtype FilterLoad = FilterLoad { filterLoadBloomFilter :: BloomFilter } deriving (Eq, Show, Read) instance NFData FilterLoad where rnf (FilterLoad f) = rnf f instance Binary FilterLoad where get = FilterLoad <$> get put (FilterLoad f) = put f -- | Add the given data element to the connections current filter without -- requiring a completely new one to be set. newtype FilterAdd = FilterAdd { getFilterData :: BS.ByteString } deriving (Eq, Show, Read) instance NFData FilterAdd where rnf (FilterAdd f) = rnf f instance Binary FilterAdd where get = do (VarInt len) <- get dat <- getByteString $ fromIntegral len return $ FilterAdd dat put (FilterAdd bs) = do put $ VarInt $ fromIntegral $ BS.length bs putByteString bs -- | Build a bloom filter that will provide the given false positive rate when -- the given number of elements have been inserted. bloomCreate :: Int -- ^ Number of elements -> Double -- ^ False positive rate -> Word32 -- ^ A random nonce (tweak) for the hash function. It should be -- a random number but the secureness of the random value is not -- of geat consequence. -> BloomFlags -- ^ Bloom filter flags -> BloomFilter -- ^ Bloom filter bloomCreate numElem fpRate tweak flags = BloomFilter (S.replicate bloomSize 0) numHashF tweak flags where -- Bloom filter size in bytes bloomSize = truncate $ (min a b) / 8 -- Suggested size in bits a = -1 / ln2Squared * (fromIntegral numElem) * log fpRate -- Maximum size in bits b = fromIntegral $ maxBloomSize * 8 numHashF = truncate $ min c (fromIntegral maxHashFuncs) -- Suggested number of hash functions c = (fromIntegral bloomSize) * 8 / (fromIntegral numElem) * ln2 bloomHash :: BloomFilter -> Word32 -> BS.ByteString -> Word32 bloomHash bfilter hashNum bs = murmur3 seed bs `mod` (fromIntegral (S.length (bloomData bfilter)) * 8) where seed = hashNum * 0xfba4c795 + (bloomTweak bfilter) -- | Insert arbitrary data into a bloom filter. Returns the new bloom filter -- containing the new data. bloomInsert :: BloomFilter -- ^ Original bloom filter -> BS.ByteString -- ^ New data to insert -> BloomFilter -- ^ Bloom filter containing the new data bloomInsert bfilter bs | isBloomFull bfilter = bfilter | otherwise = bfilter { bloomData = newData } where idxs = map (\i -> bloomHash bfilter i bs) [0..bloomHashFuncs bfilter - 1] upd s i = S.adjust (.|. bitMask !! fromIntegral (7 .&. i)) (fromIntegral $ i `shiftR` 3) s newData = foldl upd (bloomData bfilter) idxs -- | Tests if some arbitrary data matches the filter. This can be either because -- the data was inserted into the filter or because it is a false positive. bloomContains :: BloomFilter -- ^ Bloom filter -> BS.ByteString -- ^ Data that will be checked against the given bloom filter -> Bool -- ^ Returns True if the data matches the filter bloomContains bfilter bs | isBloomFull bfilter = True | isBloomEmpty bfilter = False | otherwise = and $ map isSet idxs where s = bloomData bfilter idxs = map (\i -> bloomHash bfilter i bs) [0..bloomHashFuncs bfilter - 1] isSet i = (S.index s (fromIntegral $ i `shiftR` 3)) .&. (bitMask !! fromIntegral (7 .&. i)) /= 0 -- TODO: Write bloomRelevantUpdate -- bloomRelevantUpdate :: BloomFilter -> Tx -> Hash256 -> Maybe BloomFilter -- | Returns True if the filter is empty (all bytes set to 0x00) isBloomEmpty :: BloomFilter -> Bool isBloomEmpty bfilter = all (== 0x00) $ F.toList $ bloomData bfilter -- | Returns True if the filter is full (all bytes set to 0xff) isBloomFull :: BloomFilter -> Bool isBloomFull bfilter = all (== 0xff) $ F.toList $ bloomData bfilter -- | Tests if a given bloom filter is valid. isBloomValid :: BloomFilter -- ^ Bloom filter to test -> Bool -- ^ True if the given filter is valid isBloomValid bfilter = (S.length $ bloomData bfilter) <= maxBloomSize && (bloomHashFuncs bfilter) <= maxHashFuncs
tphyahoo/haskoin
haskoin-core/Network/Haskoin/Node/Bloom.hs
unlicense
7,638
0
13
1,958
1,655
900
755
148
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE ScopedTypeVariables #-} module HW07_Editor where import System.IO import HW07_Buffer import Control.Exception import "mtl" Control.Monad.State import Control.Applicative import Control.Arrow (first, second) import Data.Char import Data.List -- Editor commands data Command = View | Edit | Load String | Line Int | Next | Prev | Quit | Help | Noop deriving (Eq, Show, Read) commands :: [String] commands = map show [View, Edit, Next, Prev, Quit] -- Editor monad newtype Editor b a = Editor (StateT (b,Int) IO a) deriving (Functor, Monad, MonadIO, MonadState (b,Int)) runEditor :: Buffer b => Editor b a -> b -> IO a runEditor (Editor e) b = evalStateT e (b,0) getCurLine :: Editor b Int getCurLine = gets snd setCurLine :: Int -> Editor b () setCurLine = modify . second . const onBuffer :: (b -> a) -> Editor b a onBuffer f = gets (f . fst) getBuffer :: Editor b b getBuffer = onBuffer id modBuffer :: (b -> b) -> Editor b () modBuffer = modify . first io :: MonadIO m => IO a -> m a io = liftIO -- Utility functions readMay :: Read a => String -> Maybe a readMay s = case reads s of [(r,_)] -> Just r _ -> Nothing -- Main editor loop editor :: Buffer b => Editor b () editor = io (hSetBuffering stdout NoBuffering) >> loop where loop = do prompt cmd <- getCommand when (cmd /= Quit) (doCommand cmd >> loop) prompt :: Buffer b => Editor b () prompt = do s <- onBuffer value io $ putStr (show s ++ "> ") getCommand :: Editor b Command getCommand = io $ readCom <$> getLine where readCom "" = Noop readCom inp@(c:cs) | isDigit c = maybe Noop Line (readMay inp) | toUpper c == 'L' = Load (unwords $ words cs) | c == '?' = Help | otherwise = maybe Noop read $ find ((== toUpper c) . head) commands doCommand :: Buffer b => Command -> Editor b () doCommand View = do cur <- getCurLine let ls = [(cur - 2) .. (cur + 2)] ss <- mapM (\l -> onBuffer $ line l) ls zipWithM_ (showL cur) ls ss where showL _ _ Nothing = return () showL l n (Just s) = io $ putStrLn (m ++ show n ++ ": " ++ s) where m | n == l = "*" | otherwise = " " doCommand Edit = do l <- getCurLine io $ putStr $ "Replace line " ++ show l ++ ": " new <- io getLine modBuffer $ replaceLine l new doCommand (Load filename) = do mstr <- io $ handle (\(_ :: IOException) -> putStrLn "File not found." >> return Nothing ) $ do h <- openFile filename ReadMode hSetEncoding h utf8 Just <$> hGetContents h maybe (return ()) (modBuffer . const . fromString) mstr doCommand (Line n) = modCurLine (const n) >> doCommand View doCommand Next = modCurLine (+1) >> doCommand View doCommand Prev = modCurLine (subtract 1) >> doCommand View doCommand Quit = return () -- do nothing, main loop notices this and quits doCommand Help = io . putStr . unlines $ [ "v --- view the current location in the document" , "n --- move to the next line" , "p --- move to the previous line" , "l --- load a file into the editor" , "e --- edit the current line" , "q --- quit" , "? --- show this list of commands" ] doCommand Noop = return () inBuffer :: Buffer b => Int -> Editor b Bool inBuffer n = do nl <- onBuffer numLines return (n >= 0 && n < nl) modCurLine :: Buffer b => (Int -> Int) -> Editor b () modCurLine f = do l <- getCurLine nl <- onBuffer numLines setCurLine . max 0 . min (nl - 1) $ f l
haroldcarr/learn-haskell-coq-ml-etc
haskell/course/2014-06-upenn/cis194/src/HW07_Editor.hs
unlicense
3,946
0
14
1,285
1,421
714
707
106
2
{-# 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
apache-2.0
2,513
0
15
572
752
414
338
51
1
{-# 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
bsd-2-clause
4,509
0
14
680
771
414
357
65
1
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
bsd-2-clause
744
0
7
107
182
110
72
17
1
{-# 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
bsd-3-clause
7,280
0
19
2,115
2,667
1,358
1,309
161
4
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Sandbox -- Maintainer : [email protected] -- 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
bsd-3-clause
37,321
0
19
10,127
5,810
3,045
2,765
546
6
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
bsd-3-clause
230
0
5
26
55
40
15
7
0
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
bsd-3-clause
6,365
0
13
2,418
708
420
288
103
2
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
bsd-3-clause
1,495
0
14
350
415
208
207
55
1
{-# 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 <[email protected]>. -- 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
bsd-3-clause
16,282
0
20
4,103
4,832
2,506
2,326
323
4
main :: IO () main = print $ sum [1..100] ^ 2 - sum (map (^ 2) [1..100])
jaredks/euler
006/006.hs
bsd-3-clause
73
0
9
18
56
29
27
2
1
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.Compatibility30 -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- 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
bsd-3-clause
45,469
0
5
6,485
7,549
4,668
2,881
1,768
0
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
bsd-3-clause
589
0
10
85
207
126
81
16
2
-- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Texturing.TextureTarget -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : [email protected] -- 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
bsd-3-clause
2,185
0
7
330
330
194
136
43
6
{-# 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 <[email protected]> -- 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
bsd-3-clause
13,841
1
31
4,215
3,631
1,890
1,741
270
9
----------------------------------------------------------------------------- -- | -- Module : Application.DevAdmin.Cabal -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- 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
bsd-3-clause
2,720
0
17
484
523
280
243
38
2
{-# 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
bsd-3-clause
775
0
14
189
161
98
63
-1
-1
{- (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
bsd-3-clause
7,734
0
15
2,466
1,654
907
747
128
2
{-# 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
bsd-3-clause
23,297
0
28
8,685
8,783
4,408
4,375
532
25
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
bsd-3-clause
172
4
9
41
79
38
41
6
2
-- | -- Module : Main -- Copyright : Jared Tobin 2012 -- License : BSD3 -- -- Maintainer : [email protected] -- 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
bsd-3-clause
4,897
0
19
1,248
1,181
624
557
78
3
{-# 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
bsd-3-clause
2,815
0
17
538
885
440
445
65
1
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
bsd-3-clause
777
0
10
175
218
114
104
10
3
{-# 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
bsd-3-clause
13,510
0
28
3,475
4,330
2,195
2,135
278
8
{-# 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
mit
17,535
0
17
4,442
3,546
1,859
1,687
-1
-1
{-# 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
mit
4,690
0
32
2,046
1,515
752
763
-1
-1
{-# 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
mit
686
0
8
210
81
49
32
16
0
import Debug.Trace data Val = IntVal Integer | StringVal String | BooleanVal Bool -- since we are implementing a Functional language, functions are -- first class citizens. | FunVal [String] Expr Env deriving (Show, Eq) ----------------------------------------------------------- data Expr = Const Val -- represents a variable | Var String -- integer multiplication | Expr :*: Expr -- integer addition and string concatenation | Expr :+: Expr -- equality test. Defined for all Val except FunVal | Expr :==: Expr -- semantically equivalent to a Haskell `if` | If Expr Expr Expr -- binds a a variable to a value (the second `Expr`), -- and makes that binding available in the third expression | Let String Expr Expr -- creates an anonymous function with an arbitrary number of parameters | Lambda [String] Expr -- calls a function with an arbitrary number values for parameters | Apply Expr [Expr] deriving (Show, Eq) ----------------------------------------------------------- data Env = EmptyEnv | ExtendEnv String Val Env deriving (Show, Eq)
2016-Fall-UPT-PLDA/homework
homework-02/your_name_here.hs
gpl-3.0
1,291
0
7
410
172
103
69
19
0
module CO4.Algorithms.Instantiator (MonadInstantiator(..), Instantiable(..), instantiateSubexpressions, instantiateSubtypes) where import CO4.Language class Monad m => MonadInstantiator m where instantiateScheme :: Scheme -> m Scheme instantiateScheme scheme = case scheme of SType t -> instantiate t >>= return . SType SForall n s -> do n' <- instantiate n s' <- instantiate s return $ SForall n' s' instantiateType :: Type -> m Type instantiateType = instantiateSubtypes instantiateUntypedName :: UntypedName -> m UntypedName instantiateUntypedName = return instantiateName :: Name -> m Name instantiateName (NTyped n s) = do s' <- instantiate s return $ NTyped n s' instantiateName name = return name instantiatePattern :: Pattern -> m Pattern instantiatePattern pat = case pat of PVar n -> instantiate n >>= return . PVar PCon n ps -> do n' <- instantiate n ps' <- instantiate ps return $ PCon n' ps' instantiateMatch :: Match -> m Match instantiateMatch (Match p e) = do p' <- instantiate p e' <- instantiate e return $ Match p' e' instantiateBinding :: Binding -> m Binding instantiateBinding (Binding n e) = do n' <- instantiate n e' <- instantiate e return $ Binding n' e' instantiateVar :: Expression -> m Expression instantiateVar (EVar n) = do n' <- instantiate n return $ EVar n' instantiateCon :: Expression -> m Expression instantiateCon (ECon n) = do n' <- instantiate n return $ ECon n' instantiateApp :: Expression -> m Expression instantiateApp (EApp f args) = do f' <- instantiate f args' <- instantiate args return $ EApp f' args' instantiateTApp :: Expression -> m Expression instantiateTApp (ETApp e types) = do e' <- instantiate e types' <- instantiate types return $ ETApp e' types' instantiateLam :: Expression -> m Expression instantiateLam (ELam ns e) = do ns' <- instantiate ns e' <- instantiate e return $ ELam ns' e' instantiateTLam :: Expression -> m Expression instantiateTLam (ETLam ns e) = do ns' <- instantiate ns e' <- instantiate e return $ ETLam ns' e' instantiateCase :: Expression -> m Expression instantiateCase (ECase e ms) = do e' <- instantiate e ms' <- instantiate ms return $ ECase e' ms' instantiateLet :: Expression -> m Expression instantiateLet (ELet b e) = do b' <- instantiate b e' <- instantiate e return $ ELet b' e' instantiateUndefined :: m Expression instantiateUndefined = return EUndefined instantiateExpression :: Expression -> m Expression instantiateExpression = instantiateSubexpressions instantiateConstructor :: Constructor -> m Constructor instantiateConstructor (CCon name types) = do name' <- instantiate name types' <- instantiate types return $ CCon name' types' instantiateBind :: Declaration -> m Declaration instantiateBind (DBind b) = instantiateBinding b >>= return . DBind instantiateAdt :: Adt -> m Adt instantiateAdt (Adt name ts cons) = do name' <- instantiate name ts' <- instantiate ts cons' <- instantiate cons return $ Adt name' ts' cons' instantiateSignature :: Signature -> m Signature instantiateSignature (Signature name scheme) = do name' <- instantiate name scheme' <- instantiate scheme return $ Signature name' scheme' instantiateDeclaration :: Declaration -> m Declaration instantiateDeclaration decl = case decl of DBind {} -> instantiateBind decl DAdt adt -> instantiate adt >>= return . DAdt DSig sig -> instantiate sig >>= return . DSig instantiateMain :: Binding -> m Binding instantiateMain main = do DBind main' <- instantiateDeclaration $ DBind main return main' instantiateProgram :: Program -> m Program instantiateProgram (Program main decls) = do main' <- instantiateMain main decls' <- instantiate decls return $ Program main' decls' instantiateSubexpressions :: MonadInstantiator m => Expression -> m Expression instantiateSubexpressions exp = case exp of EVar {} -> instantiateVar exp ECon {} -> instantiateCon exp EApp {} -> instantiateApp exp ETApp {} -> instantiateTApp exp ELam {} -> instantiateLam exp ETLam {} -> instantiateTLam exp ECase {} -> instantiateCase exp ELet {} -> instantiateLet exp EUndefined -> instantiateUndefined instantiateSubtypes :: MonadInstantiator m => Type -> m Type instantiateSubtypes t = case t of TVar v -> instantiate v >>= return . TVar TCon c ts -> do c' <- instantiate c ts' <- instantiate ts return $ TCon c' ts' class Instantiable a where instantiate :: MonadInstantiator m => a -> m a instance Instantiable Scheme where instantiate = instantiateScheme instance Instantiable Type where instantiate = instantiateType instance Instantiable UntypedName where instantiate = instantiateUntypedName instance Instantiable Name where instantiate = instantiateName instance Instantiable Pattern where instantiate = instantiatePattern instance Instantiable Match where instantiate = instantiateMatch instance Instantiable Binding where instantiate = instantiateBinding instance Instantiable Expression where instantiate = instantiateExpression instance Instantiable Adt where instantiate = instantiateAdt instance Instantiable Signature where instantiate = instantiateSignature instance Instantiable Declaration where instantiate = instantiateDeclaration instance Instantiable Constructor where instantiate = instantiateConstructor instance Instantiable Program where instantiate = instantiateProgram instance (Instantiable a) => Instantiable [a] where instantiate = mapM instantiate
abau/co4
src/CO4/Algorithms/Instantiator.hs
gpl-3.0
5,828
0
13
1,291
1,795
843
952
159
9