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 Haskell98 #-} {-# LINE 1 "Data/Streaming/Text.hs" #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE UnliftedFFITypes #-} -- -- Module : Data.Text.Lazy.Encoding.Fusion -- Copyright : (c) 2009, 2010 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : portable -- -- /Warning/: this is an internal module, and does not have a stable -- API or name. Functions in this module may not check or enforce -- preconditions expected by public modules. Use at your own risk! -- -- Fusible 'Stream'-oriented functions for converting between lazy -- 'Text' and several common encodings. -- | Provides a stream-based approach to decoding Unicode data. Each function -- below works the same way: you give it a chunk of data, and it gives back a -- @DecodeResult@. If the parse was a success, then you get a chunk of @Text@ -- (possibly empty) and a continuation parsing function. If the parse was a -- failure, you get a chunk of successfully decoded @Text@ (possibly empty) and -- the unconsumed bytes. -- -- In order to indicate end of stream, you pass an empty @ByteString@ to the -- decode function. This call may result in a failure, if there were unused -- bytes left over from a previous step which formed part of a code sequence. module Data.Streaming.Text ( -- * Streaming decodeUtf8 , decodeUtf8Pure , decodeUtf16LE , decodeUtf16BE , decodeUtf32LE , decodeUtf32BE -- * Type , DecodeResult (..) ) where import Control.Monad.ST (ST, runST) import Control.Monad.ST.Unsafe (unsafeIOToST, unsafeSTToIO) import Data.Bits ((.|.)) import qualified Data.ByteString as B import Data.ByteString.Internal (ByteString (PS)) import qualified Data.ByteString.Unsafe as B import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Array as A import Data.Text.Internal (text) import qualified Data.Text.Internal.Encoding.Utf16 as U16 import qualified Data.Text.Internal.Encoding.Utf32 as U32 import qualified Data.Text.Internal.Encoding.Utf8 as U8 import Data.Text.Internal.Unsafe.Char (unsafeChr, unsafeChr32, unsafeChr8) import Data.Text.Internal.Unsafe.Char (unsafeWrite) import Data.Text.Internal.Unsafe.Shift (shiftL) import Data.Word (Word32, Word8) import Foreign.C.Types (CSize (..)) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Marshal.Utils (with) import Foreign.Ptr (Ptr, minusPtr, nullPtr, plusPtr) import Foreign.Storable (Storable, peek, poke) import GHC.Base (MutableByteArray#) data S = S0 | S1 {-# UNPACK #-} !Word8 | S2 {-# UNPACK #-} !Word8 {-# UNPACK #-} !Word8 | S3 {-# UNPACK #-} !Word8 {-# UNPACK #-} !Word8 {-# UNPACK #-} !Word8 deriving Show data DecodeResult = DecodeResultSuccess !Text !(B.ByteString -> DecodeResult) | DecodeResultFailure !Text !B.ByteString toBS :: S -> B.ByteString toBS S0 = B.empty toBS (S1 a) = B.pack [a] toBS (S2 a b) = B.pack [a, b] toBS (S3 a b c) = B.pack [a, b, c] {-# INLINE toBS #-} getText :: Int -> A.MArray s -> ST s Text getText j marr = do arr <- A.unsafeFreeze marr return $! text arr 0 j {-# INLINE getText #-} foreign import ccall unsafe "_hs_streaming_commons_decode_utf8_state" c_decode_utf8_with_state :: MutableByteArray# s -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr Word8 -> Ptr CodePoint -> Ptr DecoderState -> IO (Ptr Word8) newtype CodePoint = CodePoint Word32 deriving (Eq, Show, Num, Storable) newtype DecoderState = DecoderState Word32 deriving (Eq, Show, Num, Storable) -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using -- UTF-8 encoding. decodeUtf8 :: B.ByteString -> DecodeResult decodeUtf8 = decodeChunk B.empty 0 0 where decodeChunkCheck :: B.ByteString -> CodePoint -> DecoderState -> B.ByteString -> DecodeResult decodeChunkCheck bsOld codepoint state bs | B.null bs = if B.null bsOld then DecodeResultSuccess T.empty decodeUtf8 else DecodeResultFailure T.empty bsOld | otherwise = decodeChunk bsOld codepoint state bs -- We create a slightly larger than necessary buffer to accommodate a -- potential surrogate pair started in the last buffer decodeChunk :: B.ByteString -> CodePoint -> DecoderState -> B.ByteString -> DecodeResult decodeChunk bsOld codepoint0 state0 bs@(PS fp off len) = runST $ (unsafeIOToST . decodeChunkToBuffer) =<< A.new (len+1) where decodeChunkToBuffer :: A.MArray s -> IO DecodeResult decodeChunkToBuffer dest = withForeignPtr fp $ \ptr -> with (0::CSize) $ \destOffPtr -> with codepoint0 $ \codepointPtr -> with state0 $ \statePtr -> with nullPtr $ \curPtrPtr -> let end = ptr `plusPtr` (off + len) loop curPtr = do poke curPtrPtr curPtr _ <- c_decode_utf8_with_state (A.maBA dest) destOffPtr curPtrPtr end codepointPtr statePtr state <- peek statePtr n <- peek destOffPtr chunkText <- unsafeSTToIO $ do arr <- A.unsafeFreeze dest return $! text arr 0 (fromIntegral n) lastPtr <- peek curPtrPtr let left = lastPtr `minusPtr` curPtr -- The logic here is: if any text was generated, then the -- previous leftovers were completely consumed already. -- If no text was generated, then any leftovers from the -- previous step are still leftovers now. unused | not $ T.null chunkText = B.unsafeDrop left bs | B.null bsOld = bs | otherwise = B.append bsOld bs case unused `seq` state of 12 -> -- We encountered an encoding error return $! DecodeResultFailure chunkText unused _ -> do codepoint <- peek codepointPtr return $! DecodeResultSuccess chunkText $! decodeChunkCheck unused codepoint state in loop (ptr `plusPtr` off) -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using -- UTF-8 encoding. decodeUtf8Pure :: B.ByteString -> DecodeResult decodeUtf8Pure = beginChunk S0 where beginChunk :: S -> B.ByteString -> DecodeResult beginChunk s bs | B.null bs = case s of S0 -> DecodeResultSuccess T.empty (beginChunk S0) _ -> DecodeResultFailure T.empty $ toBS s beginChunk s0 ps = runST $ do let initLen = B.length ps marr <- A.new (initLen + 1) let start !i !j | i >= len = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk S0) | U8.validate1 a = addChar' 1 (unsafeChr8 a) | i + 1 < len && U8.validate2 a b = addChar' 2 (U8.chr2 a b) | i + 2 < len && U8.validate3 a b c = addChar' 3 (U8.chr3 a b c) | i + 3 < len && U8.validate4 a b c d = addChar' 4 (U8.chr4 a b c d) | i + 3 < len = do t <- getText j marr return $! DecodeResultFailure t (B.unsafeDrop i ps) | i + 2 < len = continue (S3 a b c) | i + 1 < len = continue (S2 a b) | otherwise = continue (S1 a) where a = B.unsafeIndex ps i b = B.unsafeIndex ps (i+1) c = B.unsafeIndex ps (i+2) d = B.unsafeIndex ps (i+3) addChar' deltai char = do deltaj <- unsafeWrite marr j char start (i + deltai) (j + deltaj) continue s = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk s) checkCont s !i | i >= len = return $! DecodeResultSuccess T.empty (beginChunk s) checkCont s !i = case s of S0 -> start i 0 S1 a | U8.validate2 a x -> addChar' (U8.chr2 a x) | otherwise -> checkCont (S2 a x) (i + 1) S2 a b | U8.validate3 a b x -> addChar' (U8.chr3 a b x) | otherwise -> checkCont (S3 a b x) (i + 1) S3 a b c | U8.validate4 a b c x -> addChar' (U8.chr4 a b c x) _ -> return $! DecodeResultFailure T.empty $! B.append (toBS s) (B.unsafeDrop i ps) where x = B.unsafeIndex ps i addChar' c = do d <- unsafeWrite marr 0 c start (i + 1) d checkCont s0 0 where len = B.length ps {-# INLINE beginChunk #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using little -- endian UTF-16 encoding. decodeUtf16LE :: B.ByteString -> DecodeResult decodeUtf16LE = beginChunk S0 where beginChunk :: S -> B.ByteString -> DecodeResult beginChunk s bs | B.null bs = case s of S0 -> DecodeResultSuccess T.empty (beginChunk S0) _ -> DecodeResultFailure T.empty $ toBS s beginChunk s0 ps = runST $ do let initLen = B.length ps marr <- A.new (initLen + 1) let start !i !j | i >= len = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk S0) | i + 1 < len && U16.validate1 x1 = addChar' 2 (unsafeChr x1) | i + 3 < len && U16.validate2 x1 x2 = addChar' 4 (U16.chr2 x1 x2) | i + 3 < len = do t <- getText j marr return $! DecodeResultFailure t (B.unsafeDrop i ps) | i + 2 < len = continue (S3 a b c) | i + 1 < len = continue (S2 a b) | otherwise = continue (S1 a) where a = B.unsafeIndex ps i b = B.unsafeIndex ps (i+1) c = B.unsafeIndex ps (i+2) d = B.unsafeIndex ps (i+3) x1 = combine a b x2 = combine c d addChar' deltai char = do deltaj <- unsafeWrite marr j char start (i + deltai) (j + deltaj) continue s = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk s) checkCont s !i | i >= len = return $! DecodeResultSuccess T.empty (beginChunk s) checkCont s !i = case s of S0 -> start i 0 S1 a -> let x1 = combine a x in if U16.validate1 x1 then addChar' (unsafeChr x1) else checkCont (S2 a x) (i + 1) S2 a b -> checkCont (S3 a b x) (i + 1) S3 a b c -> let x1 = combine a b x2 = combine c x in if U16.validate2 x1 x2 then addChar' (U16.chr2 x1 x2) else return $! DecodeResultFailure T.empty $! B.append (toBS s) (B.unsafeDrop i ps) where x = B.unsafeIndex ps i addChar' c = do d <- unsafeWrite marr 0 c start (i + 1) d checkCont s0 0 where len = B.length ps combine w1 w2 = fromIntegral w1 .|. (fromIntegral w2 `shiftL` 8) {-# INLINE beginChunk #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using big -- endian UTF-16 encoding. decodeUtf16BE :: B.ByteString -> DecodeResult decodeUtf16BE = beginChunk S0 where beginChunk :: S -> B.ByteString -> DecodeResult beginChunk s bs | B.null bs = case s of S0 -> DecodeResultSuccess T.empty (beginChunk S0) _ -> DecodeResultFailure T.empty $ toBS s beginChunk s0 ps = runST $ do let initLen = B.length ps marr <- A.new (initLen + 1) let start !i !j | i >= len = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk S0) | i + 1 < len && U16.validate1 x1 = addChar' 2 (unsafeChr x1) | i + 3 < len && U16.validate2 x1 x2 = addChar' 4 (U16.chr2 x1 x2) | i + 3 < len = do t <- getText j marr return $! DecodeResultFailure t (B.unsafeDrop i ps) | i + 2 < len = continue (S3 a b c) | i + 1 < len = continue (S2 a b) | otherwise = continue (S1 a) where a = B.unsafeIndex ps i b = B.unsafeIndex ps (i+1) c = B.unsafeIndex ps (i+2) d = B.unsafeIndex ps (i+3) x1 = combine a b x2 = combine c d addChar' deltai char = do deltaj <- unsafeWrite marr j char start (i + deltai) (j + deltaj) continue s = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk s) checkCont s !i | i >= len = return $! DecodeResultSuccess T.empty (beginChunk s) checkCont s !i = case s of S0 -> start i 0 S1 a -> let x1 = combine a x in if U16.validate1 x1 then addChar' (unsafeChr x1) else checkCont (S2 a x) (i + 1) S2 a b -> checkCont (S3 a b x) (i + 1) S3 a b c -> let x1 = combine a b x2 = combine c x in if U16.validate2 x1 x2 then addChar' (U16.chr2 x1 x2) else return $! DecodeResultFailure T.empty $! B.append (toBS s) (B.unsafeDrop i ps) where x = B.unsafeIndex ps i addChar' c = do d <- unsafeWrite marr 0 c start (i + 1) d checkCont s0 0 where len = B.length ps combine w1 w2 = (fromIntegral w1 `shiftL` 8) .|. fromIntegral w2 {-# INLINE beginChunk #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using little -- endian UTF-32 encoding. decodeUtf32LE :: B.ByteString -> DecodeResult decodeUtf32LE = beginChunk S0 where beginChunk :: S -> B.ByteString -> DecodeResult beginChunk s bs | B.null bs = case s of S0 -> DecodeResultSuccess T.empty (beginChunk S0) _ -> DecodeResultFailure T.empty $ toBS s beginChunk s0 ps = runST $ do let initLen = B.length ps `div` 2 marr <- A.new (initLen + 1) let start !i !j | i >= len = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk S0) | i + 3 < len && U32.validate x1 = addChar' 4 (unsafeChr32 x1) | i + 3 < len = do t <- getText j marr return $! DecodeResultFailure t (B.unsafeDrop i ps) | i + 2 < len = continue (S3 a b c) | i + 1 < len = continue (S2 a b) | otherwise = continue (S1 a) where a = B.unsafeIndex ps i b = B.unsafeIndex ps (i+1) c = B.unsafeIndex ps (i+2) d = B.unsafeIndex ps (i+3) x1 = combine a b c d addChar' deltai char = do deltaj <- unsafeWrite marr j char start (i + deltai) (j + deltaj) continue s = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk s) checkCont s !i | i >= len = return $! DecodeResultSuccess T.empty (beginChunk s) checkCont s !i = case s of S0 -> start i 0 S1 a -> checkCont (S2 a x) (i + 1) S2 a b -> checkCont (S3 a b x) (i + 1) S3 a b c -> let x1 = combine a b c x in if U32.validate x1 then addChar' (unsafeChr32 x1) else return $! DecodeResultFailure T.empty $! B.append (toBS s) (B.unsafeDrop i ps) where x = B.unsafeIndex ps i addChar' c = do d <- unsafeWrite marr 0 c start (i + 1) d checkCont s0 0 where len = B.length ps combine w1 w2 w3 w4 = shiftL (fromIntegral w4) 24 .|. shiftL (fromIntegral w3) 16 .|. shiftL (fromIntegral w2) 8 .|. (fromIntegral w1) {-# INLINE beginChunk #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using big -- endian UTF-32 encoding. decodeUtf32BE :: B.ByteString -> DecodeResult decodeUtf32BE = beginChunk S0 where beginChunk :: S -> B.ByteString -> DecodeResult beginChunk s bs | B.null bs = case s of S0 -> DecodeResultSuccess T.empty (beginChunk S0) _ -> DecodeResultFailure T.empty $ toBS s beginChunk s0 ps = runST $ do let initLen = B.length ps `div` 2 marr <- A.new (initLen + 1) let start !i !j | i >= len = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk S0) | i + 3 < len && U32.validate x1 = addChar' 4 (unsafeChr32 x1) | i + 3 < len = do t <- getText j marr return $! DecodeResultFailure t (B.unsafeDrop i ps) | i + 2 < len = continue (S3 a b c) | i + 1 < len = continue (S2 a b) | otherwise = continue (S1 a) where a = B.unsafeIndex ps i b = B.unsafeIndex ps (i+1) c = B.unsafeIndex ps (i+2) d = B.unsafeIndex ps (i+3) x1 = combine a b c d addChar' deltai char = do deltaj <- unsafeWrite marr j char start (i + deltai) (j + deltaj) continue s = do t <- getText j marr return $! DecodeResultSuccess t (beginChunk s) checkCont s !i | i >= len = return $! DecodeResultSuccess T.empty (beginChunk s) checkCont s !i = case s of S0 -> start i 0 S1 a -> checkCont (S2 a x) (i + 1) S2 a b -> checkCont (S3 a b x) (i + 1) S3 a b c -> let x1 = combine a b c x in if U32.validate x1 then addChar' (unsafeChr32 x1) else return $! DecodeResultFailure T.empty $! B.append (toBS s) (B.unsafeDrop i ps) where x = B.unsafeIndex ps i addChar' c = do d <- unsafeWrite marr 0 c start (i + 1) d checkCont s0 0 where len = B.length ps combine w1 w2 w3 w4 = shiftL (fromIntegral w1) 24 .|. shiftL (fromIntegral w2) 16 .|. shiftL (fromIntegral w3) 8 .|. (fromIntegral w4) {-# INLINE beginChunk #-}
phischu/fragnix
tests/packages/scotty/Data.Streaming.Text.hs
bsd-3-clause
21,281
0
33
9,263
6,020
2,944
3,076
408
9
{-| Implementation of global N+1 redundancy -} {- Copyright (C) 2015 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.GlobalN1 ( canEvacuateNode , redundant , redundantGrp , allocGlobalN1 ) where import Control.Monad (foldM, foldM_) import qualified Data.Foldable as Foldable import Data.Function (on) import Data.List (partition, sortBy) import Ganeti.BasicTypes (isOk, Result) import Ganeti.HTools.AlgorithmParams (AlgorithmOptions(..), defaultOptions) import Ganeti.HTools.Cluster.AllocatePrimitives (allocateOnSingle) import qualified Ganeti.HTools.Cluster.AllocationSolution as AllocSol import qualified Ganeti.HTools.Cluster.Evacuate as Evacuate import Ganeti.HTools.Cluster.Moves (move) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node import Ganeti.HTools.Types ( IMove(Failover), Ndx, Gdx, Idx, opToResult, FailMode(FailN1) ) import Ganeti.Types ( DiskTemplate(DTDrbd8), diskTemplateMovable , EvacMode(ChangePrimary)) -- | Foldable function describing how a non-DRBD instance -- is to be evacuated. evac :: Gdx -> [Ndx] -> (Node.List, Instance.List) -> Idx -> Result (Node.List, Instance.List) evac gdx ndxs (nl, il) idx = do let opts = defaultOptions { algIgnoreSoftErrors = True, algEvacMode = True } inst = Container.find idx il (nl', il', _) <- Evacuate.nodeEvacInstance opts nl il ChangePrimary inst gdx ndxs return (nl', il') -- | Foldable function describing how a non-movable instance is to -- be recreated on one of the given nodes. recreate :: [Ndx] -> (Node.List, Instance.List) -> Instance.Instance -> Result (Node.List, Instance.List) recreate targetnodes (nl, il) inst = do let opts = defaultOptions { algIgnoreSoftErrors = True, algEvacMode = True } sols = foldl (\cstate -> AllocSol.concatAllocCollections cstate . allocateOnSingle opts nl inst ) AllocSol.emptyAllocCollection targetnodes sol = AllocSol.collectionToSolution FailN1 (const True) sols alloc <- maybe (fail "No solution found") return $ AllocSol.asSolution sol let il' = AllocSol.updateIl il $ Just alloc nl' = AllocSol.extractNl nl il $ Just alloc return (nl', il') -- | Decide if a node can be evacuated, i.e., all DRBD instances -- failed over and all shared/external storage instances moved off -- to other nodes. canEvacuateNode :: (Node.List, Instance.List) -> Node.Node -> Bool canEvacuateNode (nl, il) n = isOk $ do let (drbdIdxs, otherIdxs) = partition ((==) DTDrbd8 . Instance.diskTemplate . flip Container.find il) $ Node.pList n (sharedIdxs, nonMoveIdxs) = partition (diskTemplateMovable . Instance.diskTemplate . flip Container.find il) otherIdxs -- failover all DRBD instances with primaries on n (nl', il') <- opToResult . foldM move (nl, il) $ map (flip (,) Failover) drbdIdxs -- evacuate other instances let grp = Node.group n escapenodes = filter (/= Node.idx n) . map Node.idx . filter ((== grp) . Node.group) $ Container.elems nl' (nl'', il'') <- foldM (evac grp escapenodes) (nl',il') sharedIdxs let recreateInstances = sortBy (flip compare `on` Instance.mem) $ map (`Container.find` il'') nonMoveIdxs foldM_ (recreate escapenodes) (nl'', il'') recreateInstances -- | Predicate on wheter a given situation is globally N+1 redundant. redundant :: AlgorithmOptions -> Node.List -> Instance.List -> Bool redundant opts nl il = let filterFun = if algAcceptExisting opts then Container.filter (not . Node.offline) else id in Foldable.all (canEvacuateNode (nl, il)) . Container.filter (not . (`elem` algCapacityIgnoreGroups opts) . Node.group) $ filterFun nl -- | Predicate on wheter a given group is globally N+1 redundant. redundantGrp :: AlgorithmOptions -> Node.List -> Instance.List -> Gdx -> Bool redundantGrp opts nl il gdx = redundant opts (Container.filter ((==) gdx . Node.group) nl) il -- | Predicate on wheter an allocation element leads to a globally N+1 redundant -- state. allocGlobalN1 :: AlgorithmOptions -> Node.List -- ^ the original list of nodes -> Instance.List -- ^ the original list of instances -> AllocSol.GenericAllocElement a -> Bool allocGlobalN1 opts nl il alloc = let il' = AllocSol.updateIl il $ Just alloc nl' = AllocSol.extractNl nl il $ Just alloc in redundant opts nl' il'
leshchevds/ganeti
src/Ganeti/HTools/GlobalN1.hs
bsd-2-clause
6,140
0
17
1,455
1,250
688
562
85
2
module ComplexPatIn2 where --The application of a function is replaced by the right-hand side of the definition, --with actual parameters replacing formals. --In this example, unfold the 'tup' in 'foo' --This example aims to test unfolding a complex pattern binding, as well as layout --adjustment. main :: Int main = foo 3 foo :: Int -> Int foo x = h + t + (snd (let tup@(h, t) = head $ (zip [1 .. x] [3 .. 15]) in tup)) where t::Int h::Int tup :: (Int,Int) tup@(h,t) = head $ zip [1..x] [3..15]
kmate/HaRe
old/testing/unfoldDef/ComplexPatIn2_TokOut.hs
bsd-3-clause
641
0
16
237
158
91
67
9
1
module Distribution.Solver.Types.PackagePath ( PackagePath(..) , Namespace(..) , Qualifier(..) , dispQualifier , Qualified(..) , QPN , dispQPN , showQPN ) where import Distribution.Package import Distribution.Text import qualified Text.PrettyPrint as Disp import Distribution.Solver.Compat.Prelude ((<<>>)) -- | A package path consists of a namespace and a package path inside that -- namespace. data PackagePath = PackagePath Namespace Qualifier deriving (Eq, Ord, Show) -- | Top-level namespace -- -- Package choices in different namespaces are considered completely independent -- by the solver. data Namespace = -- | The default namespace DefaultNamespace -- | A namespace for a specific build target | Independent PackageName deriving (Eq, Ord, Show) -- | Pretty-prints a namespace. The result is either empty or -- ends in a period, so it can be prepended onto a qualifier. dispNamespace :: Namespace -> Disp.Doc dispNamespace DefaultNamespace = Disp.empty dispNamespace (Independent i) = disp i <<>> Disp.text "." -- | Qualifier of a package within a namespace (see 'PackagePath') data Qualifier = -- | Top-level dependency in this namespace QualToplevel -- | Any dependency on base is considered independent -- -- This makes it possible to have base shims. | QualBase PackageName -- | Setup dependency -- -- By rights setup dependencies ought to be nestable; after all, the setup -- dependencies of a package might themselves have setup dependencies, which -- are independent from everything else. However, this very quickly leads to -- infinite search trees in the solver. Therefore we limit ourselves to -- a single qualifier (within a given namespace). | QualSetup PackageName -- | If we depend on an executable from a package (via -- @build-tools@), we should solve for the dependencies of that -- package separately (since we're not going to actually try to -- link it.) We qualify for EACH package separately; e.g., -- @'Exe' pn1 pn2@ qualifies the @build-tools@ dependency on -- @pn2@ from package @pn1@. (If we tracked only @pn1@, that -- would require a consistent dependency resolution for all -- of the depended upon executables from a package; if we -- tracked only @pn2@, that would require us to pick only one -- version of an executable over the entire install plan.) | QualExe PackageName PackageName deriving (Eq, Ord, Show) -- | Pretty-prints a qualifier. The result is either empty or -- ends in a period, so it can be prepended onto a package name. -- -- NOTE: the base qualifier is for a dependency _on_ base; the qualifier is -- there to make sure different dependencies on base are all independent. -- So we want to print something like @"A.base"@, where the @"A."@ part -- is the qualifier and @"base"@ is the actual dependency (which, for the -- 'Base' qualifier, will always be @base@). dispQualifier :: Qualifier -> Disp.Doc dispQualifier QualToplevel = Disp.empty dispQualifier (QualSetup pn) = disp pn <<>> Disp.text ":setup." dispQualifier (QualExe pn pn2) = disp pn <<>> Disp.text ":" <<>> disp pn2 <<>> Disp.text ":exe." dispQualifier (QualBase pn) = disp pn <<>> Disp.text "." -- | A qualified entity. Pairs a package path with the entity. data Qualified a = Q PackagePath a deriving (Eq, Ord, Show) -- | Qualified package name. type QPN = Qualified PackageName -- | Pretty-prints a qualified package name. dispQPN :: QPN -> Disp.Doc dispQPN (Q (PackagePath ns qual) pn) = dispNamespace ns <<>> dispQualifier qual <<>> disp pn -- | String representation of a qualified package name. showQPN :: QPN -> String showQPN = Disp.renderStyle flatStyle . dispQPN
themoritz/cabal
cabal-install/Distribution/Solver/Types/PackagePath.hs
bsd-3-clause
3,801
0
9
779
493
287
206
42
1
module C2 where import D2 sumSquares1 ((x : xs)) = ((sq sq_f) x) + (sumSquares1 xs) sumSquares1 [] = 0 sq_f_1 = 0
kmate/HaRe
old/testing/addOneParameter/C2_AstOut.hs
bsd-3-clause
121
0
9
30
62
34
28
6
1
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-} {- A base bundle is used for incremental linking. it contains information about the symbols that have already been linked. These symbols are not included again in the incrementally linked program. The base contains a CompactorState for consistent renaming of private names and packed initialization of info tables and static closures. -} module Gen2.Base where import qualified Gen2.Object as Object import Compiler.JMacro import Control.Applicative import Control.Lens import Control.Monad import Data.Array import qualified Data.Binary as DB import qualified Data.Binary.Get as DB import qualified Data.Binary.Put as DB import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import qualified Data.HashSet as HS import qualified Data.Map as M import Data.Monoid import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T newLocals :: [Ident] newLocals = filter (not . isKeyword) $ map (TxtI . T.pack) $ (map (:[]) chars0) ++ concatMap mkIdents [1..] where mkIdents n = [c0:cs | c0 <- chars0, cs <- replicateM n chars] chars0 = ['a'..'z']++['A'..'Z'] chars = chars0++['0'..'9'] isKeyword (TxtI i) = i `HS.member` kwSet kwSet = HS.fromList keywords keywords = [ "break", "case", "catch", "continue", "debugger" , "default", "delete", "do", "else", "finally", "for" , "function", "if", "in", "instanceof", "new", "return" , "switch", "this", "throw", "try", "typeof", "var", "void" , "while", "with" , "class", "enum", "export", "extends", "import", "super", "const" , "implements", "interface", "let", "package", "private", "protected" , "public", "static", "yield" , "null", "true", "false" ] renamedVars :: [Ident] renamedVars = map (\(TxtI xs) -> TxtI ("h$$"<>xs)) newLocals data CompactorState = CompactorState { _identSupply :: [Ident] -- ^ ident supply for new names , _nameMap :: !(HashMap Text Ident) -- ^ renaming mapping for internal names , _entries :: !(HashMap Text Int) -- ^ entry functions (these get listed in the metadata init array) , _numEntries :: !Int , _statics :: !(HashMap Text Int) -- ^ mapping of global closure -> index in current block, for static initialisation , _numStatics :: !Int -- ^ number of static entries , _labels :: !(HashMap Text Int) -- ^ non-Haskell JS labels , _numLabels :: !Int -- ^ number of labels , _parentEntries :: !(HashMap Text Int) -- ^ entry functions we're not linking, offset where parent gets [0..n], grantparent [n+1..k] etc , _parentStatics :: !(HashMap Text Int) -- ^ objects we're not linking in base bundle , _parentLabels :: !(HashMap Text Int) -- ^ non-Haskell JS labels in parent } deriving (Show) makeLenses ''CompactorState emptyCompactorState :: CompactorState emptyCompactorState = CompactorState renamedVars HM.empty HM.empty 0 HM.empty 0 HM.empty 0 HM.empty HM.empty HM.empty showBase :: Base -> String showBase b = unlines [ "Base:" , " packages: " ++ show (basePkgs b) , " number of units: " ++ show (S.size $ baseUnits b) , " renaming table size: " ++ show (baseCompactorState b ^. nameMap . to HM.size) ] data Base = Base { baseCompactorState :: CompactorState , basePkgs :: [Object.Package] , baseUnits :: Set (Object.Package, Text, Int) } emptyBase :: Base emptyBase = Base emptyCompactorState [] S.empty putBase :: Base -> DB.Put putBase (Base cs packages funs) = do DB.putByteString "GHCJSBASE" DB.putLazyByteString Object.versionTag putCs cs putList DB.put packages putList putPkg pkgs putList DB.put mods putList putFun (S.toList funs) where pi :: Int -> DB.Put pi = DB.putWord32le . fromIntegral uniq :: Ord a => [a] -> [a] uniq = S.toList . S.fromList pkgs = uniq (map (\(x,_,_) -> x) $ S.toList funs) pkgsM = M.fromList (zip pkgs [(0::Int)..]) mods = uniq (map (\(_,x,_) -> x) $ S.toList funs) modsM = M.fromList (zip mods [(0::Int)..]) putList f xs = pi (length xs) >> mapM_ f xs -- serialise the compactor state putCs (CompactorState [] _ _ _ _ _ _ _ _ _ _) = error "putBase: putCs exhausted renamer symbol names" putCs (CompactorState (ns:_) nm es _ ss _ ls _ pes pss pls) = do DB.put ns DB.put (HM.toList nm) DB.put (HM.toList es) DB.put (HM.toList ss) DB.put (HM.toList ls) DB.put (HM.toList pes) DB.put (HM.toList pss) DB.put (HM.toList pls) putPkg (Object.Package k) = DB.put k -- fixme group things first putFun (p,m,s) = pi (pkgsM M.! p) >> pi (modsM M.! m) >> DB.put s getBase :: FilePath -> DB.Get Base getBase file = getBase' where gi :: DB.Get Int gi = fromIntegral <$> DB.getWord32le getList f = DB.getWord32le >>= \n -> replicateM (fromIntegral n) f getFun ps ms = (,,) <$> ((ps!) <$> gi) <*> ((ms!) <$> gi) <*> DB.get la xs = listArray (0, length xs - 1) xs getPkg = Object.Package <$> DB.get getCs = do n <- DB.get nm <- HM.fromList <$> DB.get es <- HM.fromList <$> DB.get ss <- HM.fromList <$> DB.get ls <- HM.fromList <$> DB.get pes <- HM.fromList <$> DB.get pss <- HM.fromList <$> DB.get pls <- HM.fromList <$> DB.get return (CompactorState (dropWhile (/=n) renamedVars) nm es (HM.size es) ss (HM.size ss) ls (HM.size ls) pes pss pls) getBase' = do hdr <- DB.getByteString 9 when (hdr /= "GHCJSBASE") (error $ "getBase: invalid base file: " <> file) vt <- DB.getLazyByteString (fromIntegral Object.versionTagLength) when (vt /= Object.versionTag) (error $ "getBase: incorrect version: " <> file) cs <- makeCompactorParent <$> getCs linkedPackages <- getList DB.get pkgs <- la <$> getList getPkg mods <- la <$> getList DB.get funs <- getList (getFun pkgs mods) return (Base cs linkedPackages $ S.fromList funs) -- | make a base state from a CompactorState: empty the current symbols sets, move everything to -- the parent makeCompactorParent :: CompactorState -> CompactorState makeCompactorParent (CompactorState is nm es nes ss nss ls nls pes pss pls) = CompactorState is nm HM.empty 0 HM.empty 0 HM.empty 0 (HM.union (fmap (+nes) pes) es) (HM.union (fmap (+nss) pss) ss) (HM.union (fmap (+nls) pls) ls) instance DB.Binary Base where get = getBase "<unknown file>" put = putBase
seereason/ghcjs
src/Gen2/Base.hs
mit
7,064
0
14
2,002
2,165
1,153
1,012
-1
-1
-- !!! cumulative re-exportation of class methods module M where import Mod159_D -- Mod159_D re-exports the class C using (..). C is defined -- in Mod159_A, but (only) two of its methods are visible -- in Mod159_D, one via Mod159_B, the other via Mod159_C. a = m1 'a' b = m2 'b'
holzensp/ghc
testsuite/tests/module/mod159.hs
bsd-3-clause
281
0
5
54
27
17
10
4
1
{-# LANGUAGE TypeOperators, MultiParamTypeClasses, LiberalTypeSynonyms #-} -- Test infix type constructors for type synonyms module ShouldCompile where infix 9 :-+-: type (f :-+-: g) t o1 o2 = Either (f t o1 o2) (g t o1 o2) data Foo a b c = Foo (a,b,c) type App f = f Int Bool Int f :: (Foo :-+-: Foo) Bool Int Bool f = error "urk" g :: App (Foo :-+-: Foo) g = error "urk" -------- classes -------- class (Eq a, Eq b) => a :&: b where op :: a -> b h :: (a :&: b) => a -> b h x = op x
wxwxwwxxx/ghc
testsuite/tests/typecheck/should_compile/tc188.hs
bsd-3-clause
498
1
7
121
199
112
87
14
1
module Main where import Types mistrustF = tftDefault Betray mistrust :: Strategy mistrust = S("mistrust", mistrustF) main = dilemmaMain mistrust
barkmadley/etd-retreat-2014-hteam
src/Mistrust/Main.hs
mit
149
0
6
23
42
24
18
6
1
{-# LANGUAGE FlexibleContexts #-} {-| Module : Network.WebexTeams.Conduit Copyright : (c) Naoto Shimazaki 2018 License : MIT (see the file LICENSE) Maintainer : https://github.com/nshimaza Stability : experimental This module provides Conduit wrapper for Cisco Webex Teams list APIs. -} module Network.WebexTeams.Conduit ( -- * Functions streamListWithFilter , streamTeamList , streamOrganizationList , streamRoleList ) where import Conduit (ConduitT, MonadIO, liftIO, yieldMany) import Control.Monad (unless) import Network.WebexTeams hiding (streamOrganizationList, streamRoleList, streamTeamList) {-| Common worker function for List APIs. It accesses List API with given 'Request', unwrap result into list of items, stream them to Conduit pipe and finally it automatically accesses next page designated via HTTP Link header if available. -} readerToSource :: (MonadIO m) => ListReader i -> ConduitT () i m () readerToSource reader = go where go = do xs <- liftIO reader unless (null xs) $ yieldMany xs *> go -- | Get list of entities with query parameter and stream it into Conduit pipe. It automatically performs pagination. streamListWithFilter :: (MonadIO m, WebexTeamsFilter filter, WebexTeamsListItem (ToResponse filter)) => Authorization -- ^ Authorization string against Webex Teams API. -> WebexTeamsRequest -- ^ Predefined part of 'Request' commonly used for Webex Teams API. -> filter -- ^ Filter criteria of the request. Type of filter automatically determines -- item type in response. -> ConduitT () (ToResponse filter) m () streamListWithFilter auth base param = getListWithFilter auth base param >>= readerToSource -- | List of 'Team' and stream it into Conduit pipe. It automatically performs pagination. streamTeamList :: MonadIO m => Authorization -> WebexTeamsRequest -> ConduitT () Team m () streamTeamList auth base = getTeamList auth base >>= readerToSource -- | Filter list of 'Organization' and stream it into Conduit pipe. It automatically performs pagination. streamOrganizationList :: MonadIO m => Authorization -> WebexTeamsRequest -> ConduitT () Organization m () streamOrganizationList auth base = getOrganizationList auth base >>= readerToSource -- | List of 'Role' and stream it into Conduit pipe. It automatically performs pagination. streamRoleList :: MonadIO m => Authorization -> WebexTeamsRequest -> ConduitT () Role m () streamRoleList auth base = getRoleList auth base >>= readerToSource
nshimaza/cisco-spark-api
webex-teams-conduit/src/Network/WebexTeams/Conduit.hs
mit
2,682
0
13
598
401
211
190
29
1
listan(N,L):- N1 is N-1, listan(N1,L1), append(L1,[N],L). listan(0,[]).
RAFIRAF/HASKELL
kkkk.hs
mit
86
4
9
21
74
39
35
-1
-1
{-# LANGUAGE DoAndIfThenElse #-} module Cook.Uploader ( Uploader , mkUploader , killUploader , enqueueImage , waitForCompletion ) where import Cook.Types import Cook.Util import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Data.Maybe import GHC.Natural import System.Process import System.Exit import qualified Data.Text as T data Uploader = Uploader { _u_threadId :: ThreadId , _u_queue :: TBQueue DockerImage , _u_task :: TVar (Maybe DockerImage) } mkUploader :: Natural -> IO Uploader mkUploader queueSize = do q <- newTBQueueIO queueSize v <- newTVarIO Nothing tid <- forkIO (uploader q v) return (Uploader tid q v) enqueueImage :: Uploader -> DockerImage -> IO () enqueueImage (Uploader _ queue _) im = atomically $ writeTBQueue queue im killUploader :: Uploader -> IO [DockerImage] killUploader (Uploader tid queue taskV) = do (queueVals, currentTask) <- atomically $ ((,) <$> readAll <*> readTVar taskV) killThread tid return $ queueVals ++ (maybeToList currentTask) where readAll :: STM [DockerImage] readAll = do qr <- tryReadTBQueue queue case qr of Just val -> do more <- readAll return (val : more) Nothing -> return [] waitForCompletion :: Uploader -> IO () waitForCompletion (Uploader _ q v) = atomically $ do isEmpty <- isEmptyTBQueue q mTask <- readTVar v when ((not isEmpty) || (isJust mTask)) $ retry uploadImage :: DockerImage -> IO (Either String ()) uploadImage (DockerImage imName') = do let imName = T.unpack imName' logInfo ("Pushing " ++ imName ++ " to the registry") (ec, stdOut, stdErr) <- readProcessWithExitCode "docker" ["push" , imName] "" if ec == ExitSuccess then return $ Right () else return $ Left ("Failed to upload " ++ imName ++ "\n" ++ stdOut ++ "\n" ++ stdErr ) uploader :: TBQueue DockerImage -> TVar (Maybe DockerImage) -> IO () uploader q v = do nextImage <- atomically $ do t <- readTBQueue q writeTVar v (Just t) return t uploadStatus <- uploadImage nextImage atomically $ writeTVar v Nothing case uploadStatus of Left err -> logWarn (err ++ "\n Uploader quit.") Right _ -> do atomically $ writeTVar v Nothing uploader q v
factisresearch/dockercook
src/lib/Cook/Uploader.hs
mit
2,742
0
16
974
796
392
404
81
2
import Data.Array.CArray import Data.Complex import Math.FFT (dft, idft) -- Binding to fftw type Vector = CArray Int (Complex Double) calculateEnergy :: Double -> Vector -> Vector -> Vector -> Double calculateEnergy dx kin pot wfc = (* dx) . sum . map realPart $ elems total where total = liftArray2 (+) kineticE potentialE potentialE = wfcConj .* pot .* wfc kineticE = wfcConj .* idft (kin .* dft wfc) wfcConj = liftArray conjugate wfc a .* b = liftArray2 (*) a b
Gathros/algorithm-archive
contents/quantum_systems/code/haskell/Energy.hs
mit
489
0
11
106
181
96
85
11
1
{-#LANGUAGE TemplateHaskell#-} {-#LANGUAGE QuasiQuotes#-} module Algebra.CAS.Diff where import Algebra.CAS.Base -- | Partial derivative -- -- >>> let [x,y] = map V ["x","y"] -- >>> diff (x*y) x -- y -- >>> diff (sin(x)*y) x -- y*(cos(x)) -- >>> diff (x^3) x -- 3*(x^2) diff :: Formula -> Formula -> Formula diff (V x') (V y') | x' == y' = C One | otherwise = C Zero diff (x :+: y) z = (diff x z) + (diff y z) diff (x :*: y) z = (diff x z) * y + x * (diff y z) diff (x :/: y) z = ((diff x z) * y - x * (diff y z)) / (y * y) diff (x :^: C One) z = diff x z diff (x :^: C (CI 1)) z = diff x z diff (x :^: C (CI 2)) z = 2 * x * (diff x z) diff (x :^: C (CI n)) z = (fromIntegral n) * (x ** (fromIntegral (n-1))) * (diff x z) diff (S (Sin x')) y' = (S (Cos x')) * (diff x' y') diff (S (Cos x')) y' = - ((S (Sin x')) * (diff x' y')) diff (S (Exp x')) y' = (S (Exp x')) * (diff x' y') diff a@(S (Tan x')) y' = ( a**2 + 1 )* (diff x' y') diff (C _) _ = C Zero diff Pi _ = C Zero diff (CV _) _ = C Zero diff (S (Log x')) y' = recip x' * diff x' y' diff a b = error $ "diff // can not parse : " ++ show a ++ " ## " ++ show b diffn :: Integer -> Formula -> Formula -> Formula diffn 0 a _ = a diffn 1 a b = diff a b diffn n a b | n < 0 = error $ "diffn can not do negative diff. n:" ++ show n | otherwise = diffn (n-1) (diff a b) b
junjihashimoto/th-cas
Algebra/CAS/Diff.hs
mit
1,362
0
12
377
809
409
400
28
1
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} module Pianola.Orphans where import Prelude hiding (catch) import Data.Tree import Data.Aeson import Data.Functor.Identity import Control.Applicative import Data.MessagePack import Data.Attoparsec.ByteString -- This orphan instance is possibly a bad idea, but I need to derive ToJSON and -- FromJSON instances, and I can't be bothered to declare the instances -- manually. instance ToJSON a => ToJSON (Tree a) where toJSON (Node a forest) = object ["root" .= a,"branches" .= forest] instance FromJSON a => FromJSON (Tree a) where parseJSON (Object v) = Node <$> v .: "root" <*> v .: "branches" parseJSON _ = fail "" -- Same for Identity instance ToJSON a => ToJSON (Identity a) where toJSON (Identity a) = object ["identity" .= a] instance FromJSON a => FromJSON (Identity a) where parseJSON (Object v) = Identity <$> v .: "identity" parseJSON _ = fail "" -- Useful msgpack instances instance (Unpackable a, Unpackable b) => Unpackable (Either a b) where get = do tag <- get::Parser Int case tag of 1 -> Left <$> get 0 -> Right <$> get instance Unpackable a => Unpackable (Tree a) where get = Node <$> get <*> get instance Unpackable a => Unpackable (Identity a) where get = Identity <$> get
danidiaz/pianola
src/Pianola/Orphans.hs
mit
1,359
0
11
309
409
212
197
30
0
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} module Routes.TH.RouteAttrs ( mkRouteAttrsInstance ) where import Routes.TH.Types import Routes.Class import Language.Haskell.TH.Syntax import Data.Set (fromList) import Data.Text (pack) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif mkRouteAttrsInstance :: Type -> [ResourceTree a] -> Q Dec mkRouteAttrsInstance typ ress = do clauses <- mapM (goTree id) ress return $ instanceD [] (ConT ''RouteAttrs `AppT` typ) [ FunD 'routeAttrs $ concat clauses ] goTree :: (Pat -> Pat) -> ResourceTree a -> Q [Clause] goTree front (ResourceLeaf res) = return <$> goRes front res goTree front (ResourceParent name _check pieces trees) = concat <$> mapM (goTree front') trees where ignored = (replicate toIgnore WildP ++) . return toIgnore = length $ filter isDynamic pieces isDynamic Dynamic{} = True isDynamic Static{} = False front' = front . ConP (mkName name) . ignored goRes :: (Pat -> Pat) -> Resource a -> Q Clause goRes front Resource {..} = return $ Clause [front $ RecP (mkName resourceName) []] (NormalB $ VarE 'fromList `AppE` ListE (map toText resourceAttrs)) [] where toText s = VarE 'pack `AppE` LitE (StringL s) instanceD :: Cxt -> Type -> [Dec] -> Dec #if MIN_VERSION_template_haskell(2,11,0) instanceD = InstanceD Nothing #else instanceD = InstanceD #endif
ajnsit/snap-routes
src/Routes/TH/RouteAttrs.hs
mit
1,471
0
12
303
495
262
233
34
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-} module SwaggyJenkins.Types ( AllView (..), BranchImpl (..), BranchImpllinks (..), BranchImplpermissions (..), CauseAction (..), CauseUserIdCause (..), ClassesByClass (..), ClockDifference (..), ComputerSet (..), DefaultCrumbIssuer (..), DiskSpaceMonitorDescriptorDiskSpace (..), EmptyChangeLogSet (..), ExtensionClassContainerImpl1 (..), ExtensionClassContainerImpl1links (..), ExtensionClassContainerImpl1map (..), ExtensionClassImpl (..), ExtensionClassImpllinks (..), FavoriteImpl (..), FavoriteImpllinks (..), FreeStyleBuild (..), FreeStyleProject (..), FreeStyleProjectactions (..), FreeStyleProjecthealthReport (..), GenericResource (..), GithubContent (..), GithubFile (..), GithubOrganization (..), GithubOrganizationlinks (..), GithubRepositories (..), GithubRepositorieslinks (..), GithubRepository (..), GithubRepositorylinks (..), GithubRepositorypermissions (..), GithubRespositoryContainer (..), GithubRespositoryContainerlinks (..), GithubScm (..), GithubScmlinks (..), Hudson (..), HudsonMasterComputer (..), HudsonMasterComputerexecutors (..), HudsonMasterComputermonitorData (..), HudsonassignedLabels (..), InputStepImpl (..), InputStepImpllinks (..), Label1 (..), Link (..), ListView (..), MultibranchPipeline (..), NullSCM (..), Organisation (..), Pipeline (..), PipelineActivity (..), PipelineActivityartifacts (..), PipelineBranchesitem (..), PipelineBranchesitemlatestRun (..), PipelineBranchesitempullRequest (..), PipelineBranchesitempullRequestlinks (..), PipelineFolderImpl (..), PipelineImpl (..), PipelineImpllinks (..), PipelineRun (..), PipelineRunImpl (..), PipelineRunImpllinks (..), PipelineRunNode (..), PipelineRunNodeedges (..), PipelineRunartifacts (..), PipelineStepImpl (..), PipelineStepImpllinks (..), PipelinelatestRun (..), PipelinelatestRunartifacts (..), Queue (..), QueueBlockedItem (..), QueueItemImpl (..), QueueLeftItem (..), ResponseTimeMonitorData (..), StringParameterDefinition (..), StringParameterValue (..), SwapSpaceMonitorMemoryUsage2 (..), UnlabeledLoadStatistics (..), User (..), ) where import ClassyPrelude.Yesod import Data.Foldable (foldl) import Data.Maybe (fromMaybe) import Data.Aeson (Value, FromJSON(..), ToJSON(..), genericToJSON, genericParseJSON) import Data.Aeson.Types (Options(..), defaultOptions) import qualified Data.Char as Char import qualified Data.Text as T import qualified Data.Map as Map import GHC.Generics (Generic) import Data.Function ((&)) -- | data AllView = AllView { allViewUnderscoreclass :: Maybe Text -- ^ , allViewName :: Maybe Text -- ^ , allViewUrl :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON AllView where parseJSON = genericParseJSON (removeFieldLabelPrefix True "allView") instance ToJSON AllView where toJSON = genericToJSON (removeFieldLabelPrefix False "allView") -- | data BranchImpl = BranchImpl { branchImplUnderscoreclass :: Maybe Text -- ^ , branchImplDisplayName :: Maybe Text -- ^ , branchImplEstimatedDurationInMillis :: Maybe Int -- ^ , branchImplFullDisplayName :: Maybe Text -- ^ , branchImplFullName :: Maybe Text -- ^ , branchImplName :: Maybe Text -- ^ , branchImplOrganization :: Maybe Text -- ^ , branchImplParameters :: Maybe [StringParameterDefinition] -- ^ , branchImplPermissions :: Maybe BranchImplpermissions -- ^ , branchImplWeatherScore :: Maybe Int -- ^ , branchImplPullRequest :: Maybe Text -- ^ , branchImplUnderscorelinks :: Maybe BranchImpllinks -- ^ , branchImplLatestRun :: Maybe PipelineRunImpl -- ^ } deriving (Show, Eq, Generic) instance FromJSON BranchImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "branchImpl") instance ToJSON BranchImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "branchImpl") -- | data BranchImpllinks = BranchImpllinks { branchImpllinksSelf :: Maybe Link -- ^ , branchImpllinksActions :: Maybe Link -- ^ , branchImpllinksRuns :: Maybe Link -- ^ , branchImpllinksQueue :: Maybe Link -- ^ , branchImpllinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON BranchImpllinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "branchImpllinks") instance ToJSON BranchImpllinks where toJSON = genericToJSON (removeFieldLabelPrefix False "branchImpllinks") -- | data BranchImplpermissions = BranchImplpermissions { branchImplpermissionsCreate :: Maybe Bool -- ^ , branchImplpermissionsRead :: Maybe Bool -- ^ , branchImplpermissionsStart :: Maybe Bool -- ^ , branchImplpermissionsStop :: Maybe Bool -- ^ , branchImplpermissionsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON BranchImplpermissions where parseJSON = genericParseJSON (removeFieldLabelPrefix True "branchImplpermissions") instance ToJSON BranchImplpermissions where toJSON = genericToJSON (removeFieldLabelPrefix False "branchImplpermissions") -- | data CauseAction = CauseAction { causeActionUnderscoreclass :: Maybe Text -- ^ , causeActionCauses :: Maybe [CauseUserIdCause] -- ^ } deriving (Show, Eq, Generic) instance FromJSON CauseAction where parseJSON = genericParseJSON (removeFieldLabelPrefix True "causeAction") instance ToJSON CauseAction where toJSON = genericToJSON (removeFieldLabelPrefix False "causeAction") -- | data CauseUserIdCause = CauseUserIdCause { causeUserIdCauseUnderscoreclass :: Maybe Text -- ^ , causeUserIdCauseShortDescription :: Maybe Text -- ^ , causeUserIdCauseUserId :: Maybe Text -- ^ , causeUserIdCauseUserName :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON CauseUserIdCause where parseJSON = genericParseJSON (removeFieldLabelPrefix True "causeUserIdCause") instance ToJSON CauseUserIdCause where toJSON = genericToJSON (removeFieldLabelPrefix False "causeUserIdCause") -- | data ClassesByClass = ClassesByClass { classesByClassClasses :: Maybe [Text] -- ^ , classesByClassUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON ClassesByClass where parseJSON = genericParseJSON (removeFieldLabelPrefix True "classesByClass") instance ToJSON ClassesByClass where toJSON = genericToJSON (removeFieldLabelPrefix False "classesByClass") -- | data ClockDifference = ClockDifference { clockDifferenceUnderscoreclass :: Maybe Text -- ^ , clockDifferenceDiff :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON ClockDifference where parseJSON = genericParseJSON (removeFieldLabelPrefix True "clockDifference") instance ToJSON ClockDifference where toJSON = genericToJSON (removeFieldLabelPrefix False "clockDifference") -- | data ComputerSet = ComputerSet { computerSetUnderscoreclass :: Maybe Text -- ^ , computerSetBusyExecutors :: Maybe Int -- ^ , computerSetComputer :: Maybe [HudsonMasterComputer] -- ^ , computerSetDisplayName :: Maybe Text -- ^ , computerSetTotalExecutors :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON ComputerSet where parseJSON = genericParseJSON (removeFieldLabelPrefix True "computerSet") instance ToJSON ComputerSet where toJSON = genericToJSON (removeFieldLabelPrefix False "computerSet") -- | data DefaultCrumbIssuer = DefaultCrumbIssuer { defaultCrumbIssuerUnderscoreclass :: Maybe Text -- ^ , defaultCrumbIssuerCrumb :: Maybe Text -- ^ , defaultCrumbIssuerCrumbRequestField :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON DefaultCrumbIssuer where parseJSON = genericParseJSON (removeFieldLabelPrefix True "defaultCrumbIssuer") instance ToJSON DefaultCrumbIssuer where toJSON = genericToJSON (removeFieldLabelPrefix False "defaultCrumbIssuer") -- | data DiskSpaceMonitorDescriptorDiskSpace = DiskSpaceMonitorDescriptorDiskSpace { diskSpaceMonitorDescriptorDiskSpaceUnderscoreclass :: Maybe Text -- ^ , diskSpaceMonitorDescriptorDiskSpaceTimestamp :: Maybe Int -- ^ , diskSpaceMonitorDescriptorDiskSpacePath :: Maybe Text -- ^ , diskSpaceMonitorDescriptorDiskSpaceSize :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON DiskSpaceMonitorDescriptorDiskSpace where parseJSON = genericParseJSON (removeFieldLabelPrefix True "diskSpaceMonitorDescriptorDiskSpace") instance ToJSON DiskSpaceMonitorDescriptorDiskSpace where toJSON = genericToJSON (removeFieldLabelPrefix False "diskSpaceMonitorDescriptorDiskSpace") -- | data EmptyChangeLogSet = EmptyChangeLogSet { emptyChangeLogSetUnderscoreclass :: Maybe Text -- ^ , emptyChangeLogSetKind :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON EmptyChangeLogSet where parseJSON = genericParseJSON (removeFieldLabelPrefix True "emptyChangeLogSet") instance ToJSON EmptyChangeLogSet where toJSON = genericToJSON (removeFieldLabelPrefix False "emptyChangeLogSet") -- | data ExtensionClassContainerImpl1 = ExtensionClassContainerImpl1 { extensionClassContainerImpl1Underscoreclass :: Maybe Text -- ^ , extensionClassContainerImpl1Underscorelinks :: Maybe ExtensionClassContainerImpl1links -- ^ , extensionClassContainerImpl1Map :: Maybe ExtensionClassContainerImpl1map -- ^ } deriving (Show, Eq, Generic) instance FromJSON ExtensionClassContainerImpl1 where parseJSON = genericParseJSON (removeFieldLabelPrefix True "extensionClassContainerImpl1") instance ToJSON ExtensionClassContainerImpl1 where toJSON = genericToJSON (removeFieldLabelPrefix False "extensionClassContainerImpl1") -- | data ExtensionClassContainerImpl1links = ExtensionClassContainerImpl1links { extensionClassContainerImpl1linksSelf :: Maybe Link -- ^ , extensionClassContainerImpl1linksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON ExtensionClassContainerImpl1links where parseJSON = genericParseJSON (removeFieldLabelPrefix True "extensionClassContainerImpl1links") instance ToJSON ExtensionClassContainerImpl1links where toJSON = genericToJSON (removeFieldLabelPrefix False "extensionClassContainerImpl1links") -- | data ExtensionClassContainerImpl1map = ExtensionClassContainerImpl1map { extensionClassContainerImpl1mapIoPeriodjenkinsPeriodblueoceanPeriodservicePeriodembeddedPeriodrestPeriodPipelineImpl :: Maybe ExtensionClassImpl -- ^ , extensionClassContainerImpl1mapIoPeriodjenkinsPeriodblueoceanPeriodservicePeriodembeddedPeriodrestPeriodMultiBranchPipelineImpl :: Maybe ExtensionClassImpl -- ^ , extensionClassContainerImpl1mapUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON ExtensionClassContainerImpl1map where parseJSON = genericParseJSON (removeFieldLabelPrefix True "extensionClassContainerImpl1map") instance ToJSON ExtensionClassContainerImpl1map where toJSON = genericToJSON (removeFieldLabelPrefix False "extensionClassContainerImpl1map") -- | data ExtensionClassImpl = ExtensionClassImpl { extensionClassImplUnderscoreclass :: Maybe Text -- ^ , extensionClassImplUnderscorelinks :: Maybe ExtensionClassImpllinks -- ^ , extensionClassImplClasses :: Maybe [Text] -- ^ } deriving (Show, Eq, Generic) instance FromJSON ExtensionClassImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "extensionClassImpl") instance ToJSON ExtensionClassImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "extensionClassImpl") -- | data ExtensionClassImpllinks = ExtensionClassImpllinks { extensionClassImpllinksSelf :: Maybe Link -- ^ , extensionClassImpllinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON ExtensionClassImpllinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "extensionClassImpllinks") instance ToJSON ExtensionClassImpllinks where toJSON = genericToJSON (removeFieldLabelPrefix False "extensionClassImpllinks") -- | data FavoriteImpl = FavoriteImpl { favoriteImplUnderscoreclass :: Maybe Text -- ^ , favoriteImplUnderscorelinks :: Maybe FavoriteImpllinks -- ^ , favoriteImplItem :: Maybe PipelineImpl -- ^ } deriving (Show, Eq, Generic) instance FromJSON FavoriteImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "favoriteImpl") instance ToJSON FavoriteImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "favoriteImpl") -- | data FavoriteImpllinks = FavoriteImpllinks { favoriteImpllinksSelf :: Maybe Link -- ^ , favoriteImpllinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON FavoriteImpllinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "favoriteImpllinks") instance ToJSON FavoriteImpllinks where toJSON = genericToJSON (removeFieldLabelPrefix False "favoriteImpllinks") -- | data FreeStyleBuild = FreeStyleBuild { freeStyleBuildUnderscoreclass :: Maybe Text -- ^ , freeStyleBuildNumber :: Maybe Int -- ^ , freeStyleBuildUrl :: Maybe Text -- ^ , freeStyleBuildActions :: Maybe [CauseAction] -- ^ , freeStyleBuildBuilding :: Maybe Bool -- ^ , freeStyleBuildDescription :: Maybe Text -- ^ , freeStyleBuildDisplayName :: Maybe Text -- ^ , freeStyleBuildDuration :: Maybe Int -- ^ , freeStyleBuildEstimatedDuration :: Maybe Int -- ^ , freeStyleBuildExecutor :: Maybe Text -- ^ , freeStyleBuildFullDisplayName :: Maybe Text -- ^ , freeStyleBuildId :: Maybe Text -- ^ , freeStyleBuildKeepLog :: Maybe Bool -- ^ , freeStyleBuildQueueId :: Maybe Int -- ^ , freeStyleBuildResult :: Maybe Text -- ^ , freeStyleBuildTimestamp :: Maybe Int -- ^ , freeStyleBuildBuiltOn :: Maybe Text -- ^ , freeStyleBuildChangeSet :: Maybe EmptyChangeLogSet -- ^ } deriving (Show, Eq, Generic) instance FromJSON FreeStyleBuild where parseJSON = genericParseJSON (removeFieldLabelPrefix True "freeStyleBuild") instance ToJSON FreeStyleBuild where toJSON = genericToJSON (removeFieldLabelPrefix False "freeStyleBuild") -- | data FreeStyleProject = FreeStyleProject { freeStyleProjectUnderscoreclass :: Maybe Text -- ^ , freeStyleProjectName :: Maybe Text -- ^ , freeStyleProjectUrl :: Maybe Text -- ^ , freeStyleProjectColor :: Maybe Text -- ^ , freeStyleProjectActions :: Maybe [FreeStyleProjectactions] -- ^ , freeStyleProjectDescription :: Maybe Text -- ^ , freeStyleProjectDisplayName :: Maybe Text -- ^ , freeStyleProjectDisplayNameOrNull :: Maybe Text -- ^ , freeStyleProjectFullDisplayName :: Maybe Text -- ^ , freeStyleProjectFullName :: Maybe Text -- ^ , freeStyleProjectBuildable :: Maybe Bool -- ^ , freeStyleProjectBuilds :: Maybe [FreeStyleBuild] -- ^ , freeStyleProjectFirstBuild :: Maybe FreeStyleBuild -- ^ , freeStyleProjectHealthReport :: Maybe [FreeStyleProjecthealthReport] -- ^ , freeStyleProjectInQueue :: Maybe Bool -- ^ , freeStyleProjectKeepDependencies :: Maybe Bool -- ^ , freeStyleProjectLastBuild :: Maybe FreeStyleBuild -- ^ , freeStyleProjectLastCompletedBuild :: Maybe FreeStyleBuild -- ^ , freeStyleProjectLastFailedBuild :: Maybe Text -- ^ , freeStyleProjectLastStableBuild :: Maybe FreeStyleBuild -- ^ , freeStyleProjectLastSuccessfulBuild :: Maybe FreeStyleBuild -- ^ , freeStyleProjectLastUnstableBuild :: Maybe Text -- ^ , freeStyleProjectLastUnsuccessfulBuild :: Maybe Text -- ^ , freeStyleProjectNextBuildNumber :: Maybe Int -- ^ , freeStyleProjectQueueItem :: Maybe Text -- ^ , freeStyleProjectConcurrentBuild :: Maybe Bool -- ^ , freeStyleProjectScm :: Maybe NullSCM -- ^ } deriving (Show, Eq, Generic) instance FromJSON FreeStyleProject where parseJSON = genericParseJSON (removeFieldLabelPrefix True "freeStyleProject") instance ToJSON FreeStyleProject where toJSON = genericToJSON (removeFieldLabelPrefix False "freeStyleProject") -- | data FreeStyleProjectactions = FreeStyleProjectactions { freeStyleProjectactionsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON FreeStyleProjectactions where parseJSON = genericParseJSON (removeFieldLabelPrefix True "freeStyleProjectactions") instance ToJSON FreeStyleProjectactions where toJSON = genericToJSON (removeFieldLabelPrefix False "freeStyleProjectactions") -- | data FreeStyleProjecthealthReport = FreeStyleProjecthealthReport { freeStyleProjecthealthReportDescription :: Maybe Text -- ^ , freeStyleProjecthealthReportIconClassName :: Maybe Text -- ^ , freeStyleProjecthealthReportIconUrl :: Maybe Text -- ^ , freeStyleProjecthealthReportScore :: Maybe Int -- ^ , freeStyleProjecthealthReportUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON FreeStyleProjecthealthReport where parseJSON = genericParseJSON (removeFieldLabelPrefix True "freeStyleProjecthealthReport") instance ToJSON FreeStyleProjecthealthReport where toJSON = genericToJSON (removeFieldLabelPrefix False "freeStyleProjecthealthReport") -- | data GenericResource = GenericResource { genericResourceUnderscoreclass :: Maybe Text -- ^ , genericResourceDisplayName :: Maybe Text -- ^ , genericResourceDurationInMillis :: Maybe Int -- ^ , genericResourceId :: Maybe Text -- ^ , genericResourceResult :: Maybe Text -- ^ , genericResourceStartTime :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GenericResource where parseJSON = genericParseJSON (removeFieldLabelPrefix True "genericResource") instance ToJSON GenericResource where toJSON = genericToJSON (removeFieldLabelPrefix False "genericResource") -- | data GithubContent = GithubContent { githubContentName :: Maybe Text -- ^ , githubContentSha :: Maybe Text -- ^ , githubContentUnderscoreclass :: Maybe Text -- ^ , githubContentRepo :: Maybe Text -- ^ , githubContentSize :: Maybe Int -- ^ , githubContentOwner :: Maybe Text -- ^ , githubContentPath :: Maybe Text -- ^ , githubContentBase64Data :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubContent where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubContent") instance ToJSON GithubContent where toJSON = genericToJSON (removeFieldLabelPrefix False "githubContent") -- | data GithubFile = GithubFile { githubFileContent :: Maybe GithubContent -- ^ , githubFileUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubFile where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubFile") instance ToJSON GithubFile where toJSON = genericToJSON (removeFieldLabelPrefix False "githubFile") -- | data GithubOrganization = GithubOrganization { githubOrganizationUnderscoreclass :: Maybe Text -- ^ , githubOrganizationUnderscorelinks :: Maybe GithubOrganizationlinks -- ^ , githubOrganizationJenkinsOrganizationPipeline :: Maybe Bool -- ^ , githubOrganizationName :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubOrganization where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubOrganization") instance ToJSON GithubOrganization where toJSON = genericToJSON (removeFieldLabelPrefix False "githubOrganization") -- | data GithubOrganizationlinks = GithubOrganizationlinks { githubOrganizationlinksRepositories :: Maybe Link -- ^ , githubOrganizationlinksSelf :: Maybe Link -- ^ , githubOrganizationlinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubOrganizationlinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubOrganizationlinks") instance ToJSON GithubOrganizationlinks where toJSON = genericToJSON (removeFieldLabelPrefix False "githubOrganizationlinks") -- | data GithubRepositories = GithubRepositories { githubRepositoriesUnderscoreclass :: Maybe Text -- ^ , githubRepositoriesUnderscorelinks :: Maybe GithubRepositorieslinks -- ^ , githubRepositoriesItems :: Maybe [GithubRepository] -- ^ , githubRepositoriesLastPage :: Maybe Int -- ^ , githubRepositoriesNextPage :: Maybe Int -- ^ , githubRepositoriesPageSize :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubRepositories where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubRepositories") instance ToJSON GithubRepositories where toJSON = genericToJSON (removeFieldLabelPrefix False "githubRepositories") -- | data GithubRepositorieslinks = GithubRepositorieslinks { githubRepositorieslinksSelf :: Maybe Link -- ^ , githubRepositorieslinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubRepositorieslinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubRepositorieslinks") instance ToJSON GithubRepositorieslinks where toJSON = genericToJSON (removeFieldLabelPrefix False "githubRepositorieslinks") -- | data GithubRepository = GithubRepository { githubRepositoryUnderscoreclass :: Maybe Text -- ^ , githubRepositoryUnderscorelinks :: Maybe GithubRepositorylinks -- ^ , githubRepositoryDefaultBranch :: Maybe Text -- ^ , githubRepositoryDescription :: Maybe Text -- ^ , githubRepositoryName :: Maybe Text -- ^ , githubRepositoryPermissions :: Maybe GithubRepositorypermissions -- ^ , githubRepositoryPrivate :: Maybe Bool -- ^ , githubRepositoryFullName :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubRepository where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubRepository") instance ToJSON GithubRepository where toJSON = genericToJSON (removeFieldLabelPrefix False "githubRepository") -- | data GithubRepositorylinks = GithubRepositorylinks { githubRepositorylinksSelf :: Maybe Link -- ^ , githubRepositorylinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubRepositorylinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubRepositorylinks") instance ToJSON GithubRepositorylinks where toJSON = genericToJSON (removeFieldLabelPrefix False "githubRepositorylinks") -- | data GithubRepositorypermissions = GithubRepositorypermissions { githubRepositorypermissionsAdmin :: Maybe Bool -- ^ , githubRepositorypermissionsPush :: Maybe Bool -- ^ , githubRepositorypermissionsPull :: Maybe Bool -- ^ , githubRepositorypermissionsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubRepositorypermissions where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubRepositorypermissions") instance ToJSON GithubRepositorypermissions where toJSON = genericToJSON (removeFieldLabelPrefix False "githubRepositorypermissions") -- | data GithubRespositoryContainer = GithubRespositoryContainer { githubRespositoryContainerUnderscoreclass :: Maybe Text -- ^ , githubRespositoryContainerUnderscorelinks :: Maybe GithubRespositoryContainerlinks -- ^ , githubRespositoryContainerRepositories :: Maybe GithubRepositories -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubRespositoryContainer where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubRespositoryContainer") instance ToJSON GithubRespositoryContainer where toJSON = genericToJSON (removeFieldLabelPrefix False "githubRespositoryContainer") -- | data GithubRespositoryContainerlinks = GithubRespositoryContainerlinks { githubRespositoryContainerlinksSelf :: Maybe Link -- ^ , githubRespositoryContainerlinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubRespositoryContainerlinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubRespositoryContainerlinks") instance ToJSON GithubRespositoryContainerlinks where toJSON = genericToJSON (removeFieldLabelPrefix False "githubRespositoryContainerlinks") -- | data GithubScm = GithubScm { githubScmUnderscoreclass :: Maybe Text -- ^ , githubScmUnderscorelinks :: Maybe GithubScmlinks -- ^ , githubScmCredentialId :: Maybe Text -- ^ , githubScmId :: Maybe Text -- ^ , githubScmUri :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubScm where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubScm") instance ToJSON GithubScm where toJSON = genericToJSON (removeFieldLabelPrefix False "githubScm") -- | data GithubScmlinks = GithubScmlinks { githubScmlinksSelf :: Maybe Link -- ^ , githubScmlinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON GithubScmlinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "githubScmlinks") instance ToJSON GithubScmlinks where toJSON = genericToJSON (removeFieldLabelPrefix False "githubScmlinks") -- | data Hudson = Hudson { hudsonUnderscoreclass :: Maybe Text -- ^ , hudsonAssignedLabels :: Maybe [HudsonassignedLabels] -- ^ , hudsonMode :: Maybe Text -- ^ , hudsonNodeDescription :: Maybe Text -- ^ , hudsonNodeName :: Maybe Text -- ^ , hudsonNumExecutors :: Maybe Int -- ^ , hudsonDescription :: Maybe Text -- ^ , hudsonJobs :: Maybe [FreeStyleProject] -- ^ , hudsonPrimaryView :: Maybe AllView -- ^ , hudsonQuietingDown :: Maybe Bool -- ^ , hudsonSlaveAgentPort :: Maybe Int -- ^ , hudsonUnlabeledLoad :: Maybe UnlabeledLoadStatistics -- ^ , hudsonUseCrumbs :: Maybe Bool -- ^ , hudsonUseSecurity :: Maybe Bool -- ^ , hudsonViews :: Maybe [AllView] -- ^ } deriving (Show, Eq, Generic) instance FromJSON Hudson where parseJSON = genericParseJSON (removeFieldLabelPrefix True "hudson") instance ToJSON Hudson where toJSON = genericToJSON (removeFieldLabelPrefix False "hudson") -- | data HudsonMasterComputer = HudsonMasterComputer { hudsonMasterComputerUnderscoreclass :: Maybe Text -- ^ , hudsonMasterComputerDisplayName :: Maybe Text -- ^ , hudsonMasterComputerExecutors :: Maybe [HudsonMasterComputerexecutors] -- ^ , hudsonMasterComputerIcon :: Maybe Text -- ^ , hudsonMasterComputerIconClassName :: Maybe Text -- ^ , hudsonMasterComputerIdle :: Maybe Bool -- ^ , hudsonMasterComputerJnlpAgent :: Maybe Bool -- ^ , hudsonMasterComputerLaunchSupported :: Maybe Bool -- ^ , hudsonMasterComputerLoadStatistics :: Maybe Label1 -- ^ , hudsonMasterComputerManualLaunchAllowed :: Maybe Bool -- ^ , hudsonMasterComputerMonitorData :: Maybe HudsonMasterComputermonitorData -- ^ , hudsonMasterComputerNumExecutors :: Maybe Int -- ^ , hudsonMasterComputerOffline :: Maybe Bool -- ^ , hudsonMasterComputerOfflineCause :: Maybe Text -- ^ , hudsonMasterComputerOfflineCauseReason :: Maybe Text -- ^ , hudsonMasterComputerTemporarilyOffline :: Maybe Bool -- ^ } deriving (Show, Eq, Generic) instance FromJSON HudsonMasterComputer where parseJSON = genericParseJSON (removeFieldLabelPrefix True "hudsonMasterComputer") instance ToJSON HudsonMasterComputer where toJSON = genericToJSON (removeFieldLabelPrefix False "hudsonMasterComputer") -- | data HudsonMasterComputerexecutors = HudsonMasterComputerexecutors { hudsonMasterComputerexecutorsCurrentExecutable :: Maybe FreeStyleBuild -- ^ , hudsonMasterComputerexecutorsIdle :: Maybe Bool -- ^ , hudsonMasterComputerexecutorsLikelyStuck :: Maybe Bool -- ^ , hudsonMasterComputerexecutorsNumber :: Maybe Int -- ^ , hudsonMasterComputerexecutorsProgress :: Maybe Int -- ^ , hudsonMasterComputerexecutorsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON HudsonMasterComputerexecutors where parseJSON = genericParseJSON (removeFieldLabelPrefix True "hudsonMasterComputerexecutors") instance ToJSON HudsonMasterComputerexecutors where toJSON = genericToJSON (removeFieldLabelPrefix False "hudsonMasterComputerexecutors") -- | data HudsonMasterComputermonitorData = HudsonMasterComputermonitorData { hudsonMasterComputermonitorDataHudsonPeriodnodeUnderscoremonitorsPeriodSwapSpaceMonitor :: Maybe SwapSpaceMonitorMemoryUsage2 -- ^ , hudsonMasterComputermonitorDataHudsonPeriodnodeUnderscoremonitorsPeriodTemporarySpaceMonitor :: Maybe DiskSpaceMonitorDescriptorDiskSpace -- ^ , hudsonMasterComputermonitorDataHudsonPeriodnodeUnderscoremonitorsPeriodDiskSpaceMonitor :: Maybe DiskSpaceMonitorDescriptorDiskSpace -- ^ , hudsonMasterComputermonitorDataHudsonPeriodnodeUnderscoremonitorsPeriodArchitectureMonitor :: Maybe Text -- ^ , hudsonMasterComputermonitorDataHudsonPeriodnodeUnderscoremonitorsPeriodResponseTimeMonitor :: Maybe ResponseTimeMonitorData -- ^ , hudsonMasterComputermonitorDataHudsonPeriodnodeUnderscoremonitorsPeriodClockMonitor :: Maybe ClockDifference -- ^ , hudsonMasterComputermonitorDataUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON HudsonMasterComputermonitorData where parseJSON = genericParseJSON (removeFieldLabelPrefix True "hudsonMasterComputermonitorData") instance ToJSON HudsonMasterComputermonitorData where toJSON = genericToJSON (removeFieldLabelPrefix False "hudsonMasterComputermonitorData") -- | data HudsonassignedLabels = HudsonassignedLabels { hudsonassignedLabelsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON HudsonassignedLabels where parseJSON = genericParseJSON (removeFieldLabelPrefix True "hudsonassignedLabels") instance ToJSON HudsonassignedLabels where toJSON = genericToJSON (removeFieldLabelPrefix False "hudsonassignedLabels") -- | data InputStepImpl = InputStepImpl { inputStepImplUnderscoreclass :: Maybe Text -- ^ , inputStepImplUnderscorelinks :: Maybe InputStepImpllinks -- ^ , inputStepImplId :: Maybe Text -- ^ , inputStepImplMessage :: Maybe Text -- ^ , inputStepImplOk :: Maybe Text -- ^ , inputStepImplParameters :: Maybe [StringParameterDefinition] -- ^ , inputStepImplSubmitter :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON InputStepImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "inputStepImpl") instance ToJSON InputStepImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "inputStepImpl") -- | data InputStepImpllinks = InputStepImpllinks { inputStepImpllinksSelf :: Maybe Link -- ^ , inputStepImpllinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON InputStepImpllinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "inputStepImpllinks") instance ToJSON InputStepImpllinks where toJSON = genericToJSON (removeFieldLabelPrefix False "inputStepImpllinks") -- | data Label1 = Label1 { label1Underscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON Label1 where parseJSON = genericParseJSON (removeFieldLabelPrefix True "label1") instance ToJSON Label1 where toJSON = genericToJSON (removeFieldLabelPrefix False "label1") -- | data Link = Link { linkUnderscoreclass :: Maybe Text -- ^ , linkHref :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON Link where parseJSON = genericParseJSON (removeFieldLabelPrefix True "link") instance ToJSON Link where toJSON = genericToJSON (removeFieldLabelPrefix False "link") -- | data ListView = ListView { listViewUnderscoreclass :: Maybe Text -- ^ , listViewDescription :: Maybe Text -- ^ , listViewJobs :: Maybe [FreeStyleProject] -- ^ , listViewName :: Maybe Text -- ^ , listViewUrl :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON ListView where parseJSON = genericParseJSON (removeFieldLabelPrefix True "listView") instance ToJSON ListView where toJSON = genericToJSON (removeFieldLabelPrefix False "listView") -- | data MultibranchPipeline = MultibranchPipeline { multibranchPipelineDisplayName :: Maybe Text -- ^ , multibranchPipelineEstimatedDurationInMillis :: Maybe Int -- ^ , multibranchPipelineLatestRun :: Maybe Text -- ^ , multibranchPipelineName :: Maybe Text -- ^ , multibranchPipelineOrganization :: Maybe Text -- ^ , multibranchPipelineWeatherScore :: Maybe Int -- ^ , multibranchPipelineBranchNames :: Maybe [Text] -- ^ , multibranchPipelineNumberOfFailingBranches :: Maybe Int -- ^ , multibranchPipelineNumberOfFailingPullRequests :: Maybe Int -- ^ , multibranchPipelineNumberOfSuccessfulBranches :: Maybe Int -- ^ , multibranchPipelineNumberOfSuccessfulPullRequests :: Maybe Int -- ^ , multibranchPipelineTotalNumberOfBranches :: Maybe Int -- ^ , multibranchPipelineTotalNumberOfPullRequests :: Maybe Int -- ^ , multibranchPipelineUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON MultibranchPipeline where parseJSON = genericParseJSON (removeFieldLabelPrefix True "multibranchPipeline") instance ToJSON MultibranchPipeline where toJSON = genericToJSON (removeFieldLabelPrefix False "multibranchPipeline") -- | data NullSCM = NullSCM { nullSCMUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON NullSCM where parseJSON = genericParseJSON (removeFieldLabelPrefix True "nullSCM") instance ToJSON NullSCM where toJSON = genericToJSON (removeFieldLabelPrefix False "nullSCM") -- | data Organisation = Organisation { organisationUnderscoreclass :: Maybe Text -- ^ , organisationName :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON Organisation where parseJSON = genericParseJSON (removeFieldLabelPrefix True "organisation") instance ToJSON Organisation where toJSON = genericToJSON (removeFieldLabelPrefix False "organisation") -- | data Pipeline = Pipeline { pipelineUnderscoreclass :: Maybe Text -- ^ , pipelineOrganization :: Maybe Text -- ^ , pipelineName :: Maybe Text -- ^ , pipelineDisplayName :: Maybe Text -- ^ , pipelineFullName :: Maybe Text -- ^ , pipelineWeatherScore :: Maybe Int -- ^ , pipelineEstimatedDurationInMillis :: Maybe Int -- ^ , pipelineLatestRun :: Maybe PipelinelatestRun -- ^ } deriving (Show, Eq, Generic) instance FromJSON Pipeline where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipeline") instance ToJSON Pipeline where toJSON = genericToJSON (removeFieldLabelPrefix False "pipeline") -- | data PipelineActivity = PipelineActivity { pipelineActivityUnderscoreclass :: Maybe Text -- ^ , pipelineActivityArtifacts :: Maybe [PipelineActivityartifacts] -- ^ , pipelineActivityDurationInMillis :: Maybe Int -- ^ , pipelineActivityEstimatedDurationInMillis :: Maybe Int -- ^ , pipelineActivityEnQueueTime :: Maybe Text -- ^ , pipelineActivityEndTime :: Maybe Text -- ^ , pipelineActivityId :: Maybe Text -- ^ , pipelineActivityOrganization :: Maybe Text -- ^ , pipelineActivityPipeline :: Maybe Text -- ^ , pipelineActivityResult :: Maybe Text -- ^ , pipelineActivityRunSummary :: Maybe Text -- ^ , pipelineActivityStartTime :: Maybe Text -- ^ , pipelineActivityState :: Maybe Text -- ^ , pipelineActivityType :: Maybe Text -- ^ , pipelineActivityCommitId :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineActivity where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineActivity") instance ToJSON PipelineActivity where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineActivity") -- | data PipelineActivityartifacts = PipelineActivityartifacts { pipelineActivityartifactsName :: Maybe Text -- ^ , pipelineActivityartifactsSize :: Maybe Int -- ^ , pipelineActivityartifactsUrl :: Maybe Text -- ^ , pipelineActivityartifactsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineActivityartifacts where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineActivityartifacts") instance ToJSON PipelineActivityartifacts where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineActivityartifacts") -- | data PipelineBranchesitem = PipelineBranchesitem { pipelineBranchesitemDisplayName :: Maybe Text -- ^ , pipelineBranchesitemEstimatedDurationInMillis :: Maybe Int -- ^ , pipelineBranchesitemName :: Maybe Text -- ^ , pipelineBranchesitemWeatherScore :: Maybe Int -- ^ , pipelineBranchesitemLatestRun :: Maybe PipelineBranchesitemlatestRun -- ^ , pipelineBranchesitemOrganization :: Maybe Text -- ^ , pipelineBranchesitemPullRequest :: Maybe PipelineBranchesitempullRequest -- ^ , pipelineBranchesitemTotalNumberOfPullRequests :: Maybe Int -- ^ , pipelineBranchesitemUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineBranchesitem where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineBranchesitem") instance ToJSON PipelineBranchesitem where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineBranchesitem") -- | data PipelineBranchesitemlatestRun = PipelineBranchesitemlatestRun { pipelineBranchesitemlatestRunDurationInMillis :: Maybe Int -- ^ , pipelineBranchesitemlatestRunEstimatedDurationInMillis :: Maybe Int -- ^ , pipelineBranchesitemlatestRunEnQueueTime :: Maybe Text -- ^ , pipelineBranchesitemlatestRunEndTime :: Maybe Text -- ^ , pipelineBranchesitemlatestRunId :: Maybe Text -- ^ , pipelineBranchesitemlatestRunOrganization :: Maybe Text -- ^ , pipelineBranchesitemlatestRunPipeline :: Maybe Text -- ^ , pipelineBranchesitemlatestRunResult :: Maybe Text -- ^ , pipelineBranchesitemlatestRunRunSummary :: Maybe Text -- ^ , pipelineBranchesitemlatestRunStartTime :: Maybe Text -- ^ , pipelineBranchesitemlatestRunState :: Maybe Text -- ^ , pipelineBranchesitemlatestRunType :: Maybe Text -- ^ , pipelineBranchesitemlatestRunCommitId :: Maybe Text -- ^ , pipelineBranchesitemlatestRunUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineBranchesitemlatestRun where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineBranchesitemlatestRun") instance ToJSON PipelineBranchesitemlatestRun where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineBranchesitemlatestRun") -- | data PipelineBranchesitempullRequest = PipelineBranchesitempullRequest { pipelineBranchesitempullRequestUnderscorelinks :: Maybe PipelineBranchesitempullRequestlinks -- ^ , pipelineBranchesitempullRequestAuthor :: Maybe Text -- ^ , pipelineBranchesitempullRequestId :: Maybe Text -- ^ , pipelineBranchesitempullRequestTitle :: Maybe Text -- ^ , pipelineBranchesitempullRequestUrl :: Maybe Text -- ^ , pipelineBranchesitempullRequestUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineBranchesitempullRequest where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineBranchesitempullRequest") instance ToJSON PipelineBranchesitempullRequest where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineBranchesitempullRequest") -- | data PipelineBranchesitempullRequestlinks = PipelineBranchesitempullRequestlinks { pipelineBranchesitempullRequestlinksSelf :: Maybe Text -- ^ , pipelineBranchesitempullRequestlinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineBranchesitempullRequestlinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineBranchesitempullRequestlinks") instance ToJSON PipelineBranchesitempullRequestlinks where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineBranchesitempullRequestlinks") -- | data PipelineFolderImpl = PipelineFolderImpl { pipelineFolderImplUnderscoreclass :: Maybe Text -- ^ , pipelineFolderImplDisplayName :: Maybe Text -- ^ , pipelineFolderImplFullName :: Maybe Text -- ^ , pipelineFolderImplName :: Maybe Text -- ^ , pipelineFolderImplOrganization :: Maybe Text -- ^ , pipelineFolderImplNumberOfFolders :: Maybe Int -- ^ , pipelineFolderImplNumberOfPipelines :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineFolderImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineFolderImpl") instance ToJSON PipelineFolderImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineFolderImpl") -- | data PipelineImpl = PipelineImpl { pipelineImplUnderscoreclass :: Maybe Text -- ^ , pipelineImplDisplayName :: Maybe Text -- ^ , pipelineImplEstimatedDurationInMillis :: Maybe Int -- ^ , pipelineImplFullName :: Maybe Text -- ^ , pipelineImplLatestRun :: Maybe Text -- ^ , pipelineImplName :: Maybe Text -- ^ , pipelineImplOrganization :: Maybe Text -- ^ , pipelineImplWeatherScore :: Maybe Int -- ^ , pipelineImplUnderscorelinks :: Maybe PipelineImpllinks -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineImpl") instance ToJSON PipelineImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineImpl") -- | data PipelineImpllinks = PipelineImpllinks { pipelineImpllinksRuns :: Maybe Link -- ^ , pipelineImpllinksSelf :: Maybe Link -- ^ , pipelineImpllinksQueue :: Maybe Link -- ^ , pipelineImpllinksActions :: Maybe Link -- ^ , pipelineImpllinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineImpllinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineImpllinks") instance ToJSON PipelineImpllinks where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineImpllinks") -- | data PipelineRun = PipelineRun { pipelineRunUnderscoreclass :: Maybe Text -- ^ , pipelineRunArtifacts :: Maybe [PipelineRunartifacts] -- ^ , pipelineRunDurationInMillis :: Maybe Int -- ^ , pipelineRunEstimatedDurationInMillis :: Maybe Int -- ^ , pipelineRunEnQueueTime :: Maybe Text -- ^ , pipelineRunEndTime :: Maybe Text -- ^ , pipelineRunId :: Maybe Text -- ^ , pipelineRunOrganization :: Maybe Text -- ^ , pipelineRunPipeline :: Maybe Text -- ^ , pipelineRunResult :: Maybe Text -- ^ , pipelineRunRunSummary :: Maybe Text -- ^ , pipelineRunStartTime :: Maybe Text -- ^ , pipelineRunState :: Maybe Text -- ^ , pipelineRunType :: Maybe Text -- ^ , pipelineRunCommitId :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineRun where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineRun") instance ToJSON PipelineRun where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineRun") -- | data PipelineRunImpl = PipelineRunImpl { pipelineRunImplUnderscoreclass :: Maybe Text -- ^ , pipelineRunImplUnderscorelinks :: Maybe PipelineRunImpllinks -- ^ , pipelineRunImplDurationInMillis :: Maybe Int -- ^ , pipelineRunImplEnQueueTime :: Maybe Text -- ^ , pipelineRunImplEndTime :: Maybe Text -- ^ , pipelineRunImplEstimatedDurationInMillis :: Maybe Int -- ^ , pipelineRunImplId :: Maybe Text -- ^ , pipelineRunImplOrganization :: Maybe Text -- ^ , pipelineRunImplPipeline :: Maybe Text -- ^ , pipelineRunImplResult :: Maybe Text -- ^ , pipelineRunImplRunSummary :: Maybe Text -- ^ , pipelineRunImplStartTime :: Maybe Text -- ^ , pipelineRunImplState :: Maybe Text -- ^ , pipelineRunImplType :: Maybe Text -- ^ , pipelineRunImplCommitId :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineRunImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineRunImpl") instance ToJSON PipelineRunImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineRunImpl") -- | data PipelineRunImpllinks = PipelineRunImpllinks { pipelineRunImpllinksNodes :: Maybe Link -- ^ , pipelineRunImpllinksLog :: Maybe Link -- ^ , pipelineRunImpllinksSelf :: Maybe Link -- ^ , pipelineRunImpllinksActions :: Maybe Link -- ^ , pipelineRunImpllinksSteps :: Maybe Link -- ^ , pipelineRunImpllinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineRunImpllinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineRunImpllinks") instance ToJSON PipelineRunImpllinks where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineRunImpllinks") -- | data PipelineRunNode = PipelineRunNode { pipelineRunNodeUnderscoreclass :: Maybe Text -- ^ , pipelineRunNodeDisplayName :: Maybe Text -- ^ , pipelineRunNodeDurationInMillis :: Maybe Int -- ^ , pipelineRunNodeEdges :: Maybe [PipelineRunNodeedges] -- ^ , pipelineRunNodeId :: Maybe Text -- ^ , pipelineRunNodeResult :: Maybe Text -- ^ , pipelineRunNodeStartTime :: Maybe Text -- ^ , pipelineRunNodeState :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineRunNode where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineRunNode") instance ToJSON PipelineRunNode where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineRunNode") -- | data PipelineRunNodeedges = PipelineRunNodeedges { pipelineRunNodeedgesId :: Maybe Text -- ^ , pipelineRunNodeedgesUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineRunNodeedges where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineRunNodeedges") instance ToJSON PipelineRunNodeedges where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineRunNodeedges") -- | data PipelineRunartifacts = PipelineRunartifacts { pipelineRunartifactsName :: Maybe Text -- ^ , pipelineRunartifactsSize :: Maybe Int -- ^ , pipelineRunartifactsUrl :: Maybe Text -- ^ , pipelineRunartifactsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineRunartifacts where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineRunartifacts") instance ToJSON PipelineRunartifacts where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineRunartifacts") -- | data PipelineStepImpl = PipelineStepImpl { pipelineStepImplUnderscoreclass :: Maybe Text -- ^ , pipelineStepImplUnderscorelinks :: Maybe PipelineStepImpllinks -- ^ , pipelineStepImplDisplayName :: Maybe Text -- ^ , pipelineStepImplDurationInMillis :: Maybe Int -- ^ , pipelineStepImplId :: Maybe Text -- ^ , pipelineStepImplInput :: Maybe InputStepImpl -- ^ , pipelineStepImplResult :: Maybe Text -- ^ , pipelineStepImplStartTime :: Maybe Text -- ^ , pipelineStepImplState :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineStepImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineStepImpl") instance ToJSON PipelineStepImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineStepImpl") -- | data PipelineStepImpllinks = PipelineStepImpllinks { pipelineStepImpllinksSelf :: Maybe Link -- ^ , pipelineStepImpllinksActions :: Maybe Link -- ^ , pipelineStepImpllinksUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelineStepImpllinks where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelineStepImpllinks") instance ToJSON PipelineStepImpllinks where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelineStepImpllinks") -- | data PipelinelatestRun = PipelinelatestRun { pipelinelatestRunArtifacts :: Maybe [PipelinelatestRunartifacts] -- ^ , pipelinelatestRunDurationInMillis :: Maybe Int -- ^ , pipelinelatestRunEstimatedDurationInMillis :: Maybe Int -- ^ , pipelinelatestRunEnQueueTime :: Maybe Text -- ^ , pipelinelatestRunEndTime :: Maybe Text -- ^ , pipelinelatestRunId :: Maybe Text -- ^ , pipelinelatestRunOrganization :: Maybe Text -- ^ , pipelinelatestRunPipeline :: Maybe Text -- ^ , pipelinelatestRunResult :: Maybe Text -- ^ , pipelinelatestRunRunSummary :: Maybe Text -- ^ , pipelinelatestRunStartTime :: Maybe Text -- ^ , pipelinelatestRunState :: Maybe Text -- ^ , pipelinelatestRunType :: Maybe Text -- ^ , pipelinelatestRunCommitId :: Maybe Text -- ^ , pipelinelatestRunUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelinelatestRun where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelinelatestRun") instance ToJSON PipelinelatestRun where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelinelatestRun") -- | data PipelinelatestRunartifacts = PipelinelatestRunartifacts { pipelinelatestRunartifactsName :: Maybe Text -- ^ , pipelinelatestRunartifactsSize :: Maybe Int -- ^ , pipelinelatestRunartifactsUrl :: Maybe Text -- ^ , pipelinelatestRunartifactsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON PipelinelatestRunartifacts where parseJSON = genericParseJSON (removeFieldLabelPrefix True "pipelinelatestRunartifacts") instance ToJSON PipelinelatestRunartifacts where toJSON = genericToJSON (removeFieldLabelPrefix False "pipelinelatestRunartifacts") -- | data Queue = Queue { queueUnderscoreclass :: Maybe Text -- ^ , queueItems :: Maybe [QueueBlockedItem] -- ^ } deriving (Show, Eq, Generic) instance FromJSON Queue where parseJSON = genericParseJSON (removeFieldLabelPrefix True "queue") instance ToJSON Queue where toJSON = genericToJSON (removeFieldLabelPrefix False "queue") -- | data QueueBlockedItem = QueueBlockedItem { queueBlockedItemUnderscoreclass :: Maybe Text -- ^ , queueBlockedItemActions :: Maybe [CauseAction] -- ^ , queueBlockedItemBlocked :: Maybe Bool -- ^ , queueBlockedItemBuildable :: Maybe Bool -- ^ , queueBlockedItemId :: Maybe Int -- ^ , queueBlockedItemInQueueSince :: Maybe Int -- ^ , queueBlockedItemParams :: Maybe Text -- ^ , queueBlockedItemStuck :: Maybe Bool -- ^ , queueBlockedItemTask :: Maybe FreeStyleProject -- ^ , queueBlockedItemUrl :: Maybe Text -- ^ , queueBlockedItemWhy :: Maybe Text -- ^ , queueBlockedItemBuildableStartMilliseconds :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON QueueBlockedItem where parseJSON = genericParseJSON (removeFieldLabelPrefix True "queueBlockedItem") instance ToJSON QueueBlockedItem where toJSON = genericToJSON (removeFieldLabelPrefix False "queueBlockedItem") -- | data QueueItemImpl = QueueItemImpl { queueItemImplUnderscoreclass :: Maybe Text -- ^ , queueItemImplExpectedBuildNumber :: Maybe Int -- ^ , queueItemImplId :: Maybe Text -- ^ , queueItemImplPipeline :: Maybe Text -- ^ , queueItemImplQueuedTime :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON QueueItemImpl where parseJSON = genericParseJSON (removeFieldLabelPrefix True "queueItemImpl") instance ToJSON QueueItemImpl where toJSON = genericToJSON (removeFieldLabelPrefix False "queueItemImpl") -- | data QueueLeftItem = QueueLeftItem { queueLeftItemUnderscoreclass :: Maybe Text -- ^ , queueLeftItemActions :: Maybe [CauseAction] -- ^ , queueLeftItemBlocked :: Maybe Bool -- ^ , queueLeftItemBuildable :: Maybe Bool -- ^ , queueLeftItemId :: Maybe Int -- ^ , queueLeftItemInQueueSince :: Maybe Int -- ^ , queueLeftItemParams :: Maybe Text -- ^ , queueLeftItemStuck :: Maybe Bool -- ^ , queueLeftItemTask :: Maybe FreeStyleProject -- ^ , queueLeftItemUrl :: Maybe Text -- ^ , queueLeftItemWhy :: Maybe Text -- ^ , queueLeftItemCancelled :: Maybe Bool -- ^ , queueLeftItemExecutable :: Maybe FreeStyleBuild -- ^ } deriving (Show, Eq, Generic) instance FromJSON QueueLeftItem where parseJSON = genericParseJSON (removeFieldLabelPrefix True "queueLeftItem") instance ToJSON QueueLeftItem where toJSON = genericToJSON (removeFieldLabelPrefix False "queueLeftItem") -- | data ResponseTimeMonitorData = ResponseTimeMonitorData { responseTimeMonitorDataUnderscoreclass :: Maybe Text -- ^ , responseTimeMonitorDataTimestamp :: Maybe Int -- ^ , responseTimeMonitorDataAverage :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON ResponseTimeMonitorData where parseJSON = genericParseJSON (removeFieldLabelPrefix True "responseTimeMonitorData") instance ToJSON ResponseTimeMonitorData where toJSON = genericToJSON (removeFieldLabelPrefix False "responseTimeMonitorData") -- | data StringParameterDefinition = StringParameterDefinition { stringParameterDefinitionUnderscoreclass :: Maybe Text -- ^ , stringParameterDefinitionDefaultParameterValue :: Maybe StringParameterValue -- ^ , stringParameterDefinitionDescription :: Maybe Text -- ^ , stringParameterDefinitionName :: Maybe Text -- ^ , stringParameterDefinitionType :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON StringParameterDefinition where parseJSON = genericParseJSON (removeFieldLabelPrefix True "stringParameterDefinition") instance ToJSON StringParameterDefinition where toJSON = genericToJSON (removeFieldLabelPrefix False "stringParameterDefinition") -- | data StringParameterValue = StringParameterValue { stringParameterValueUnderscoreclass :: Maybe Text -- ^ , stringParameterValueName :: Maybe Text -- ^ , stringParameterValueValue :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON StringParameterValue where parseJSON = genericParseJSON (removeFieldLabelPrefix True "stringParameterValue") instance ToJSON StringParameterValue where toJSON = genericToJSON (removeFieldLabelPrefix False "stringParameterValue") -- | data SwapSpaceMonitorMemoryUsage2 = SwapSpaceMonitorMemoryUsage2 { swapSpaceMonitorMemoryUsage2Underscoreclass :: Maybe Text -- ^ , swapSpaceMonitorMemoryUsage2AvailablePhysicalMemory :: Maybe Int -- ^ , swapSpaceMonitorMemoryUsage2AvailableSwapSpace :: Maybe Int -- ^ , swapSpaceMonitorMemoryUsage2TotalPhysicalMemory :: Maybe Int -- ^ , swapSpaceMonitorMemoryUsage2TotalSwapSpace :: Maybe Int -- ^ } deriving (Show, Eq, Generic) instance FromJSON SwapSpaceMonitorMemoryUsage2 where parseJSON = genericParseJSON (removeFieldLabelPrefix True "swapSpaceMonitorMemoryUsage2") instance ToJSON SwapSpaceMonitorMemoryUsage2 where toJSON = genericToJSON (removeFieldLabelPrefix False "swapSpaceMonitorMemoryUsage2") -- | data UnlabeledLoadStatistics = UnlabeledLoadStatistics { unlabeledLoadStatisticsUnderscoreclass :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON UnlabeledLoadStatistics where parseJSON = genericParseJSON (removeFieldLabelPrefix True "unlabeledLoadStatistics") instance ToJSON UnlabeledLoadStatistics where toJSON = genericToJSON (removeFieldLabelPrefix False "unlabeledLoadStatistics") -- | data User = User { userUnderscoreclass :: Maybe Text -- ^ , userId :: Maybe Text -- ^ , userFullName :: Maybe Text -- ^ , userEmail :: Maybe Text -- ^ , userName :: Maybe Text -- ^ } deriving (Show, Eq, Generic) instance FromJSON User where parseJSON = genericParseJSON (removeFieldLabelPrefix True "user") instance ToJSON User where toJSON = genericToJSON (removeFieldLabelPrefix False "user") uncapitalize :: String -> String uncapitalize (c : cs) = Char.toLower c : cs uncapitalize [] = [] -- | Remove a field label prefix during JSON parsing. -- Also perform any replacements for special characters. -- The @forParsing@ parameter is to distinguish between the cases in which we're using this -- to power a @FromJSON@ or a @ToJSON@ instance. In the first case we're parsing, and we want -- to replace special characters with their quoted equivalents (because we cannot have special -- chars in identifier names), while we want to do vice versa when sending data instead. removeFieldLabelPrefix :: Bool -> String -> Options removeFieldLabelPrefix forParsing prefix = defaultOptions { omitNothingFields = True , fieldLabelModifier = uncapitalize . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix . replaceSpecialChars } where replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars) specialChars = [ ("@", "'At") , ("\\", "'Back_Slash") , ("<=", "'Less_Than_Or_Equal_To") , ("\"", "'Double_Quote") , ("[", "'Left_Square_Bracket") , ("]", "'Right_Square_Bracket") , ("^", "'Caret") , ("_", "'Underscore") , ("`", "'Backtick") , ("!", "'Exclamation") , ("#", "'Hash") , ("$", "'Dollar") , ("%", "'Percent") , ("&", "'Ampersand") , ("'", "'Quote") , ("(", "'Left_Parenthesis") , (")", "'Right_Parenthesis") , ("*", "'Star") , ("+", "'Plus") , (",", "'Comma") , ("-", "'Dash") , (".", "'Period") , ("/", "'Slash") , (":", "'Colon") , (";", "'Semicolon") , ("{", "'Left_Curly_Bracket") , ("|", "'Pipe") , ("<", "'LessThan") , ("!=", "'Not_Equal") , ("=", "'Equal") , ("}", "'Right_Curly_Bracket") , (">", "'GreaterThan") , ("~", "'Tilde") , ("?", "'Question_Mark") , (">=", "'Greater_Than_Or_Equal_To") , ("~=", "'Tilde_Equal") ] mkCharReplacement (replaceStr, searchStr) = T.unpack . replacer (T.pack searchStr) (T.pack replaceStr) . T.pack replacer = if forParsing then flip T.replace else T.replace
cliffano/swaggy-jenkins
clients/haskell-yesod/generated/src/SwaggyJenkins/Types.hs
mit
57,608
0
14
8,946
11,836
6,724
5,112
1,095
2
{-# OPTIONS_GHC -XTemplateHaskell #-} module Euler.Problem011Test (suite) where import Numeric.LinearAlgebra.Data (Matrix, loadMatrix) import Test.Tasty (TestTree) import Test.Tasty.HUnit import Test.Tasty.TH (testGroupGenerator) import Euler.Problem011 suite :: TestTree suite = $(testGroupGenerator) matrix :: IO (Matrix Double) matrix = loadMatrix "input/011.txt" case_count_of_vectors_in_input :: Assertion case_count_of_vectors_in_input = matrix >>= \m -> 10 @=? (length . vectors . head $ submatrices 4 m) case_count_of_4x4_submatrices_in_input :: Assertion case_count_of_4x4_submatrices_in_input = matrix >>= \m -> 17 * 17 @=? (length $ submatrices 4 m)
whittle/euler
test/Euler/Problem011Test.hs
mit
672
0
11
86
176
100
76
-1
-1
module RoundPermutations (initialPermutation, finalPermutation) where import Utilities(blank64BitBlock, listPermute) import RoundMappings(ipMapping, fpMapping) import Data.Word(Word8) initialPermutation :: [Word8] -> [Word8] initialPermutation bs = listPermute ipMapping bs blank64BitBlock finalPermutation :: [Word8] -> [Word8] finalPermutation bs = listPermute fpMapping bs blank64BitBlock
tombusby/haskell-des
round/RoundPermutations.hs
mit
397
0
6
42
104
60
44
8
1
{-# LANGUAGE DataKinds #-} import Control.Monad import Control.Monad.Trans import Options.Declarative greet :: Flag "n" '["name"] "STRING" "name" [String] -> Cmd "Count the number of people" () greet name = let people_name_list = get name num_people = length people_name_list in liftIO $ do putStrLn $ "There are " ++ show num_people ++ " people on the list." putStrLn " -- " forM_ people_name_list putStrLn main :: IO () main = run_ greet
tanakh/optparse-declarative
example/list.hs
mit
519
0
12
150
137
67
70
15
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE OverloadedStrings #-} import Control.Applicative ((<$>), (<*>)) import Control.Monad (mzero) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger import Control.Monad.Trans.Resource (runResourceT, ResourceT) import Data.Aeson hiding (json) import qualified Data.Text as Text import Data.Maybe (fromMaybe) import Network.HTTP.Types.Status (status404) import Network.Wai (Middleware) import Network.Wai.Middleware.AddHeaders import System.Environment import Web.Scotty import Web.PathPieces import qualified Database.Persist.Class as DB import qualified Database.Persist.Sqlite as Sqlite import Database.Persist.TH share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Todo title String completed Bool order Int deriving Show |] instance ToJSON (Sqlite.Entity Todo) where toJSON entity = object [ "id" .= key , "url" .= ("http://todobackend-scotty.herokuapp.com/todos/" ++ keyText) , "title" .= todoTitle val , "completed" .= todoCompleted val , "order" .= todoOrder val ] where key = Sqlite.entityKey entity val = Sqlite.entityVal entity keyText = Text.unpack $ toPathPiece key data TodoAction = TodoAction { actTitle :: Maybe String , actCompleted :: Maybe Bool , actOrder :: Maybe Int } deriving Show instance FromJSON TodoAction where parseJSON (Object o) = TodoAction <$> o .:? "title" <*> o .:? "completed" <*> o .:? "order" parseJSON _ = mzero instance ToJSON TodoAction where toJSON (TodoAction mTitle mCompl mOrder) = noNullsObject [ "title" .= mTitle , "completed" .= mCompl , "order" .= mOrder ] where noNullsObject = object . filter notNull notNull (_, Null) = False notNull _ = True actionToTodo :: TodoAction -> Todo actionToTodo (TodoAction mTitle mCompleted mOrder) = Todo title completed order where title = fromMaybe "" mTitle completed = fromMaybe False mCompleted order = fromMaybe 0 mOrder actionToUpdates :: TodoAction -> [Sqlite.Update Todo] actionToUpdates act = updateTitle ++ updateCompl ++ updateOrd where updateTitle = maybe [] (\title -> [TodoTitle Sqlite.=. title]) (actTitle act) updateCompl = maybe [] (\compl -> [TodoCompleted Sqlite.=. compl]) (actCompleted act) updateOrd = maybe [] (\ord -> [TodoOrder Sqlite.=. ord]) (actOrder act) allowCors :: Middleware allowCors = addHeaders [ ("Access-Control-Allow-Origin", "*"), ("Access-Control-Allow-Headers", "Accept, Content-Type"), ("Access-Control-Allow-Methods", "GET, HEAD, POST, DELETE, OPTIONS, PUT, PATCH") ] runDb :: Sqlite.SqlPersistT (ResourceT (NoLoggingT IO)) a -> IO a runDb = runNoLoggingT . runResourceT . Sqlite.withSqliteConn "dev.sqlite3" . Sqlite.runSqlConn main :: IO () main = do runDb $ Sqlite.runMigration migrateAll port <- read <$> getEnv "PORT" scotty port $ do middleware allowCors get "/todos" $ do todos <- liftIO readTodos json todos get "/todos/:id" $ do pid <- param "id" actionOr404 pid (\tid -> do Just todo <- liftIO $ readTodo tid json (Sqlite.Entity tid todo)) patch "/todos/:id" $ do pid <- param "id" actionOr404 pid (\tid -> do todoAct <- jsonData let todoUp = actionToUpdates todoAct todo <- liftIO $ runDb $ DB.updateGet tid todoUp json (Sqlite.Entity tid todo)) delete "/todos/:id" $ do pid <- param "id" actionOr404 pid (liftIO . deleteTodo) post "/todos" $ do todoAct <- jsonData let todo = actionToTodo todoAct tid <- liftIO $ insertTodo todo json (Sqlite.Entity tid todo) delete "/todos" $ liftIO $ runDb $ DB.deleteWhere ([] :: [Sqlite.Filter Todo]) matchAny "/todos" $ text "ok" matchAny "/todos/:id" $ text "ok" where readTodos :: IO [Sqlite.Entity Todo] readTodos = runDb $ DB.selectList [] [] readTodo :: Sqlite.Key Todo -> IO (Maybe Todo) readTodo tid = runDb $ DB.get tid deleteTodo :: Sqlite.Key Todo -> IO () deleteTodo tid = runDb $ DB.delete tid insertTodo :: Todo -> IO (Sqlite.Key Todo) insertTodo todo = runDb $ DB.insert todo actionOr404 pid action = case fromPathPiece pid of Nothing -> status status404 Just tid -> action tid
jhedev/todobackend-scotty-persistent
src/Main.hs
mit
4,786
0
21
1,218
1,383
706
677
120
2
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Data.Foldable.Compat" -- from a globally unique namespace. module Data.Foldable.Compat.Repl.Batteries ( module Data.Foldable.Compat ) where import "this" Data.Foldable.Compat
haskell-compat/base-compat
base-compat-batteries/src/Data/Foldable/Compat/Repl/Batteries.hs
mit
294
0
5
31
29
22
7
5
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SQLError (pattern UNKNOWN_ERR, pattern DATABASE_ERR, pattern VERSION_ERR, pattern TOO_LARGE_ERR, pattern QUOTA_ERR, pattern SYNTAX_ERR, pattern CONSTRAINT_ERR, pattern TIMEOUT_ERR, js_getCode, getCode, js_getMessage, getMessage, SQLError, castToSQLError, gTypeSQLError) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums pattern UNKNOWN_ERR = 0 pattern DATABASE_ERR = 1 pattern VERSION_ERR = 2 pattern TOO_LARGE_ERR = 3 pattern QUOTA_ERR = 4 pattern SYNTAX_ERR = 5 pattern CONSTRAINT_ERR = 6 pattern TIMEOUT_ERR = 7 foreign import javascript unsafe "$1[\"code\"]" js_getCode :: SQLError -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLError.code Mozilla SQLError.code documentation> getCode :: (MonadIO m) => SQLError -> m Word getCode self = liftIO (js_getCode (self)) foreign import javascript unsafe "$1[\"message\"]" js_getMessage :: SQLError -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLError.message Mozilla SQLError.message documentation> getMessage :: (MonadIO m, FromJSString result) => SQLError -> m result getMessage self = liftIO (fromJSString <$> (js_getMessage (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SQLError.hs
mit
2,015
12
10
272
539
326
213
37
1
module Language.TaPL.Arith.Parser (parseString, parseFile) where import qualified Text.Parsec.Token as Token import Text.Parsec.Language (emptyDef) import Text.Parsec.Prim (parse) import Text.Parsec.String (Parser) import Control.Applicative ((<|>)) import Control.Monad (liftM) import Language.TaPL.Arith.Syntax (Term(..), integerToTerm) -- This module is adapted from: http://www.haskell.org/haskellwiki/Parsing_a_simple_imperative_language booleanDef = emptyDef { Token.reservedNames = [ "if" , "then" , "else" , "true" , "false" , "zero" , "succ" , "pred" , "iszero" ] } lexer = Token.makeTokenParser booleanDef reserved = Token.reserved lexer -- parses a reserved name parens = Token.parens lexer -- parses surrounding parenthesis: -- parens p -- takes care of the parenthesis and -- uses p to parse what's inside them whiteSpace = Token.whiteSpace lexer -- parses whitespace integer = Token.integer lexer -- parses an integer booleanParser :: Parser Term booleanParser = whiteSpace >> expr expr :: Parser Term expr = parens expr <|> ifExpr <|> (reserved "true" >> return TmTrue) <|> (reserved "false" >> return TmFalse) <|> arithExpr ifExpr :: Parser Term ifExpr = do reserved "if" t1 <- expr reserved "then" t2 <- expr reserved "else" t3 <- expr return $ TmIf t1 t2 t3 arithExpr :: Parser Term arithExpr = (reserved "zero" >> return TmZero) <|> predExpr <|> succExpr <|> iszeroExpr <|> liftM integerToTerm integer predExpr :: Parser Term predExpr = oneArgExprHelper TmPred "pred" succExpr :: Parser Term succExpr = oneArgExprHelper TmSucc "succ" iszeroExpr :: Parser Term iszeroExpr = oneArgExprHelper TmIsZero "iszero" oneArgExprHelper :: (Term -> Term) -> String -> Parser Term oneArgExprHelper constructor word = do reserved word t <- expr return $ constructor t parseString :: String -> Term parseString str = case parse booleanParser "" str of Left e -> error $ show e Right t -> t parseFile :: String -> IO Term parseFile file = do program <- readFile file case parse booleanParser "" program of Left e -> print e >> fail "parse error" Right t -> return t
zeckalpha/TaPL
src/Language/TaPL/Arith/Parser.hs
mit
2,834
0
11
1,073
625
325
300
66
2
module Three where import Data.List import qualified Data.Map as M import qualified Data.Set as S first :: [a] -> Maybe a first [] = Nothing first (x : _) = Just x rest :: [a] -> [a] rest [] = [] rest (x : xs) = xs take' :: Int -> [a] -> [a] take' _ [] = [] take' 0 _ = [] take' n (x : xs) = x : take' (pred n) xs drop' :: Int -> [a] -> [a] drop' _ [] = [] drop' 0 xs = xs drop' n (x:xs) = drop' (pred n) xs rev :: [a] -> [a] rev [] = [] rev (x : xs) = rev xs ++ [x] rev' :: [a] -> [a] rev' lst = iter lst [] where iter [] res = res iter (x : xs) res = iter xs (x:res) trev :: [a] -> [a] trev [] = [] trev (x:[]) = [x] trev xs = trev lpart ++ trev fpart where lcount = div (length xs) 2 fpart = take lcount xs lpart = drop lcount xs remove :: Eq a => a -> [a] -> [a] remove elmt lst = iter lst [] where iter [] res = res iter (x : xs) res | x == elmt = (rev' res) ++ xs | otherwise = iter xs (x:res) removeAll :: Eq a => a -> [a] -> [a] removeAll elmt lst = iter lst [] where iter [] res = res iter (x : xs) res | x == elmt = (rev' res) ++ (removeAll elmt xs) | otherwise = iter xs (x:res) member :: Eq a => a -> [a] -> Bool member elmt lst = iter lst where iter [] = False iter (x:xs) = if x == elmt then True else False qsort :: Ord a => [a] -> [a] qsort [] = [] qsort (x:[]) = [x] qsort (x:xs) = qsort (filter (<= x) xs) ++ [x] ++ qsort (filter (> x) xs) is_prime :: Integral a => a -> Bool is_prime 2 = True is_prime n = if odd n then iter 3 else False where lim = ceiling $ sqrt $ fromIntegral n iter i | i > lim = True | 0 == rem n i = False | otherwise = iter $ i+2 odd_prime :: Int -> Bool odd_prime n = all (\x -> rem n x /= 0) $ takeWhile (\x-> x <= div n x) [3,5..] sum_primes :: Int -> Int sum_primes lim = sum $ filter odd_prime [3,5..lim]
zeniuseducation/poly-euler
Alfa/haskell/tutorial/three.hs
epl-1.0
1,823
0
11
497
1,129
585
544
64
3
{-# LANGUAGE Arrows, FlexibleContexts, NoMonomorphismRestriction, RankNTypes, ScopedTypeVariables, TypeOperators #-} {- The Mr S(um) and Mr P(roduct) puzzle analysed by McCarthy, and van - Ditmarsch, Ruan, Verbrugge. - Copyright : (C)opyright 2011 peteg42 at gmail dot com - License : GPL (see COPYING for details) - - ghc -O -main-is Main.main -rtsopts -prof -auto-all -caf-all -package ADHOC SandP_circuits_dialogue.hs - - For some reason ghc 7.0.3 does a terrible job *without* profiling. - However 7.4.1 is OK and the result is faster than with profiling. - ghc -O -main-is Main.main -rtsopts -package ADHOC SandP_circuits_dialogue.hs - ghci -package ADHOC SandP_circuits_dialogue.hs - BDDs blow up on multipliers, and more specifically, when we try to quotient the initial states under multiplication. This version adds the multiplication to the states so that Mr. P's observation is simply equality. The game is to define a dialogue combinator that supports an abstract description. The puzzle according to McCarthy: Two numbers m and n are chosen such that 2 ≤ m ≤ n ≤ 99. Mr. S is told their sum and Mr. P is told their product. The following dialogue ensues: Mr. P: I don’t know the numbers. Mr. S: I knew you didn’t know. I don’t know either. Mr. P: Now I know the numbers. Mr. S: Now I know them too. In view of the above dialogue, what are the numbers? http://www-formal.stanford.edu/jmc/puzzles/puzzles.html -} module Main ( main ) where ------------------------------------------------------------------- -- Dependencies. ------------------------------------------------------------------- import Prelude hiding ( (.), id ) import ADHOC import ADHOC.Data.Arithmetic import ADHOC.NonDet import ADHOC.Knowledge import ADHOC.ModelChecker.CTL as CTL import ADHOC.ModelChecker.CounterExamples import Dialogue ------------------------------------------------------------------- disjoinAC :: ArrowComb (~>) => ([env ~> B (~>)]) -> (env ~> B (~>)) disjoinAC = foldr (\f fs -> proc env -> ((f -< env) `orAC` (fs -< env))) falseA natAW = natA (undefined :: Seven) natAWM = natA (undefined :: Fourteen) ------------------------------------------------------------------- -- The scenario. ------------------------------------------------------------------- mrS :: AgentID mrS = "Mr. S." mrP :: AgentID mrP = "Mr. P." mP, nP, mrSactP, mrPactP :: ProbeID mP = "m" nP = "n" mrSactP = "mrS says" mrPactP = "mrP says" -- | An agent knows the two values. knows_mn :: AgentID -> KF knows_mn aid = aid `knows_hat` mP /\ aid `knows_hat` nP -- | Initially Mr. S is told their sum and Mr. P is told their product. agent_init_arrs = mkSizedListA [ (mrS, numCastA <<< addA <<< arr fst) , (mrP, arr snd) ] `withLength` (undefined :: Two) dialogue :: Dialogue Four dialogue = mkSizedListA [ -- Mr. P: I don’t know the numbers. mrP :> now (neg (knows_mn mrP)) -- Mr. S: I knew you didn’t know. I don’t know either. , mrS :> pre (mrS `knows` neg (knows_mn mrP)) /\ now (neg (knows_mn mrS)) -- Mr. P: Now I know the numbers. , mrP :> now (knows_mn mrP) -- Mr. S: Now I know them too. , mrS :> now (knows_mn mrS) ] top = proc () -> do (mn, p) <- (| nondetLatchAC (\s0 -> disjoinAC initAs -< s0) |) acts <- runDialogue agent_init_arrs dialogue -< (mn, p) let [mrSact, mrPact] = unSizedListA acts probeA mP *** probeA nP -< mn probeA mrSactP *** probeA mrPactP -< (mrSact, mrPact) where initAs = [ proc ((m, n), p) -> ( ((natAW -< m) `eqAC` (fromIntegerA vm -< ())) `andAC` ((natAW -< n) `eqAC` (fromIntegerA vn -< ())) `andAC` ((natAWM -< p) `eqAC` (fromIntegerA (vm * vn) -< ())) ) | vm <- [ 2 .. 99 ], vn <- [ vm .. 99 ] ] ------------------------------------------------------------------- -- Synthesis and model checking. ------------------------------------------------------------------- -- Synthesis using the SPR semantics -- Don't run stamina, we don't have all day. Just (kautos, m, _) = broadcastSprSynth MinBisim top -- Just (kautos, m, _) = broadcastSprSynth MinNone top ctlM = mkCTLModel m -- We want the initial state(s) where the dialogue went to plan. -- This is where all (four of) the announcements came out true. --dialogue_result = showWitness ctlM (ex (ex (p /\ ex (p /\ ex (p /\ ex p))))) dialogue_result = showCounterExample ctlM (af (neg p)) where p = probe mrSactP /\ probe mrPactP -- | This example is big enough that we need to compile it... It -- seems that ReorderStableWindow3 is faster than ReorderSift. main :: IO () main = do dynamicReordering ReorderStableWindow3 -- ReorderSift -- ReorderStableWindow3 -- print m -- print test_dialogue -- dot kautos dialogue_result
peteg/ADHOC
Apps/SandP/SandP_circuits_dialogue.hs
gpl-2.0
4,831
5
16
953
855
487
368
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Core.CTypes -- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GPL -- -- Maintainer : maintainer@leksah.org -- Stability : provisional -- Portability : -- -- | -- ----------------------------------------------------------------------------- module IDE.Core.CTypes ( PackageDescr(..) , ModuleKey(..) , displayModuleKey , parseModuleKey , moduleKeyToName , ModuleDescr(..) , Descr(..) , RealDescr(..) , ReexportedDescr(..) , Present(..) , TypeDescr(..) , DescrType(..) , SimpleDescr(..) , GenScope(..) , dscName , dscMbTypeStr , dscMbModu , dsMbModu , dscMbLocation , dscMbComment , dscTypeHint , dscExported , descrType , isReexported , PackScope(..) , SymbolTable(..) , PackModule(..) , parsePackModule , showPackModule , packageIdentifierToString , packageIdentifierFromString , Location(..) , SrcSpan(..) , Scope(..) , ServerCommand(..) , ServerAnswer(..) , leksahVersion , configDirName , metadataVersion , ImportDecl(..) , ImportSpecList(..) , ImportSpec(..) , getThisPackage , PackageIdAndKey(..) , RetrieveStrategy(..) ) where import Control.Applicative ((<$>)) import Prelude import Data.Typeable (Typeable) import Data.Map (Map) import Data.Set (Set) import Data.Maybe (fromMaybe) import Default (Default(..)) import MyMissing (nonEmptyLines) #if MIN_VERSION_ghc(7,6,0) import Distribution.Package (PackageIdentifier(..)) #else import Distribution.Package (PackageIdentifier(..),PackageName(..)) #endif import Distribution.ModuleName (main, components, ModuleName) import Data.ByteString.Char8 (ByteString) #if !MIN_VERSION_bytestring(0,10,0) import Data.Version (Version(..)) #endif import Distribution.Text (simpleParse, display) import qualified Data.ByteString.Char8 as BS (unpack, empty) import qualified Data.Map as Map (lookup,keysSet,splitLookup, insertWith,empty,elems,union) import Text.PrinterParser import Data.Char (isAlpha) import Control.DeepSeq (NFData(..)) import PackageConfig (PackageConfig) #if MIN_VERSION_ghc(7,10,0) import Module (PackageKey) import PackageConfig (sourcePackageIdString, packageKey) import Data.Maybe (fromJust) #else import qualified Distribution.InstalledPackageInfo as IPI #endif import Data.Text (Text) import Data.Monoid ((<>)) import Text.PrettyPrint (fsep, Doc, (<+>), empty, text) import qualified Text.PrettyPrint as PP (text, comma, punctuate, parens) import qualified Data.Text as T (pack, tail, span, unpack) #if !MIN_VERSION_ghc(7,7,0) import Distribution.Package(PackageName(..)) #endif -- --------------------------------------------------------------------- -- | Information about the system, extraced from .hi and source files -- leksahVersion, configDirName :: FilePath leksahVersion = "0.15" configDirName = ".leksah-" <> leksahVersion metadataVersion :: Integer metadataVersion = 7 data PackageIdAndKey = PackageIdAndKey { packId :: PackageIdentifier #if MIN_VERSION_ghc(7,10,0) , packKey :: PackageKey #endif } getThisPackage :: PackageConfig -> PackageIdAndKey getThisPackage p = PackageIdAndKey #if MIN_VERSION_ghc(7,10,0) (fromJust . simpleParse $ sourcePackageIdString p) (packageKey p) #else (IPI.sourcePackageId p) #endif data RetrieveStrategy = RetrieveThenBuild | BuildThenRetrieve | NeverRetrieve deriving (Show, Read, Eq, Ord, Enum, Bounded) data ServerCommand = SystemCommand { scRebuild :: Bool, scSources :: Bool, scExtract :: Bool, scPackageDBs :: [[FilePath]]} | WorkspaceCommand { wcRebuild :: Bool, wcPackage :: PackageIdentifier, wcPath :: FilePath, wcModList :: [(Text,FilePath)]} | ParseHeaderCommand { hcFilePath :: FilePath} deriving (Eq,Ord,Show,Read) data ServerAnswer = ServerOK | ServerFailed Text | ServerHeader (Either [ImportDecl] Int) deriving (Eq,Ord,Show,Read) data PackScope alpha = SymbolTable alpha => PackScope (Map PackageIdentifier PackageDescr) alpha data GenScope = forall alpha. SymbolTable alpha => GenScopeC (PackScope alpha) class SymbolTable alpha where symLookup :: Text -> alpha -> [Descr] symbols :: alpha -> Set Text symSplitLookup :: Text -> alpha -> (alpha , Maybe [Descr], alpha) symInsert :: Text -> [Descr] -> alpha -> alpha symEmpty :: alpha symElems :: alpha -> [[Descr]] symUnion :: alpha -> alpha -> alpha instance SymbolTable (Map Text [Descr]) where symLookup str smap = fromMaybe [] (str `Map.lookup` smap) symbols = Map.keysSet symSplitLookup = Map.splitLookup symInsert = Map.insertWith (++) symEmpty = Map.empty symElems = Map.elems symUnion = Map.union data PackageDescr = PackageDescr { pdPackage :: PackageIdentifier , pdMbSourcePath :: Maybe FilePath , pdModules :: [ModuleDescr] , pdBuildDepends :: [PackageIdentifier] } deriving (Show,Typeable) instance Default PackageDescr where getDefault = PackageDescr getDefault getDefault getDefault getDefault newtype Present alpha = Present alpha instance Show (Present PackageDescr) where show (Present pd) = T.unpack $ (packageIdentifierToString . pdPackage) pd instance Eq PackageDescr where (== ) a b = pdPackage a == pdPackage b instance Ord PackageDescr where (<=) a b = pdPackage a <= pdPackage b -- | Key we use to identify a module in the metadata. -- But for "Main" modules we need to know the source file path. data ModuleKey = LibModule ModuleName | MainModule FilePath deriving (Show, Eq, Ord) -- | Display a the module key displayModuleKey :: ModuleKey -> String displayModuleKey (LibModule m) = display m displayModuleKey (MainModule f) = "Main (" ++ f ++ ")" -- | Parse a module key from the name of the module and the source file path. parseModuleKey :: String -> FilePath -> Maybe ModuleKey parseModuleKey "Main" sourcePath = Just $ MainModule sourcePath parseModuleKey s _ = LibModule <$> simpleParse s -- | Extract the module name from the module key moduleKeyToName :: ModuleKey -> ModuleName moduleKeyToName (LibModule m) = m moduleKeyToName (MainModule _) = main data ModuleDescr = ModuleDescr { mdModuleId :: PackModule , mdMbSourcePath :: Maybe FilePath -- unqualified , mdReferences :: Map ModuleName (Set Text) -- imports , mdIdDescriptions :: [Descr] } deriving (Show,Typeable) instance Default ModuleDescr where getDefault = ModuleDescr getDefault getDefault Map.empty getDefault instance Show (Present ModuleDescr) where show (Present md) = (show . mdModuleId) md instance Eq ModuleDescr where (== ) a b = let idEq = mdModuleId a == mdModuleId b -- Main modules are only the same if they use the same file in if idEq && ["Main"] == components (modu (mdModuleId a)) then mdMbSourcePath a == mdMbSourcePath b else idEq instance Ord ModuleDescr where (<=) a b = let idEq = mdModuleId a == mdModuleId b -- use source files for main modules in if idEq && ["Main"] == components (modu (mdModuleId a)) then mdMbSourcePath a <= mdMbSourcePath b else mdModuleId a <= mdModuleId b data Descr = Real RealDescr | Reexported ReexportedDescr deriving (Show,Read,Typeable,Eq,Ord) data RealDescr = RealDescr { dscName' :: Text , dscMbTypeStr' :: Maybe ByteString , dscMbModu' :: Maybe PackModule , dscMbLocation' :: Maybe Location , dscMbComment' :: Maybe ByteString , dscTypeHint' :: TypeDescr , dscExported' :: Bool } deriving (Show,Read,Typeable) data ReexportedDescr = ReexportedDescr { dsrMbModu :: Maybe PackModule , dsrDescr :: Descr} deriving (Show,Read,Typeable) -- Metadata accessors isReexported :: Descr -> Bool isReexported (Reexported _) = True isReexported _ = False dscName :: Descr -> Text dscName (Reexported d) = dscName (dsrDescr d) dscName (Real d) = dscName' d dscMbTypeStr :: Descr -> Maybe ByteString dscMbTypeStr (Reexported d) = dscMbTypeStr (dsrDescr d) dscMbTypeStr (Real d) = dscMbTypeStr' d -- | The definition module dscMbModu :: Descr -> Maybe PackModule dscMbModu (Reexported d) = dscMbModu (dsrDescr d) dscMbModu (Real d) = dscMbModu' d -- | The exporting module dsMbModu :: Descr -> Maybe PackModule dsMbModu (Reexported d) = dsrMbModu d dsMbModu (Real d) = dscMbModu' d dscMbLocation :: Descr -> Maybe Location dscMbLocation (Reexported d) = dscMbLocation (dsrDescr d) dscMbLocation (Real d) = dscMbLocation' d dscMbComment :: Descr -> Maybe ByteString dscMbComment (Reexported d) = dscMbComment (dsrDescr d) dscMbComment (Real d) = dscMbComment' d dscTypeHint :: Descr -> TypeDescr dscTypeHint (Reexported d) = dscTypeHint (dsrDescr d) dscTypeHint (Real d) = dscTypeHint' d dscExported :: Descr -> Bool dscExported (Reexported _) = True dscExported (Real d) = dscExported' d data TypeDescr = VariableDescr | FieldDescr Descr | ConstructorDescr Descr | DataDescr [SimpleDescr] [SimpleDescr] -- ^ first constructors, then fields | TypeDescr | NewtypeDescr SimpleDescr (Maybe SimpleDescr) -- ^ first constructors, then maybe field | ClassDescr [Text] [SimpleDescr] -- ^ first super, then methods | MethodDescr Descr -- ^ classDescr | InstanceDescr [Text] -- ^ binds | KeywordDescr | ExtensionDescr | ModNameDescr | QualModNameDescr | ErrorDescr | PatternSynonymDescr --the descrName is the type Konstructor? deriving (Show,Read,Eq,Ord,Typeable) data DescrType = Variable | Field | Constructor | Data | Type | Newtype | Class | Method | Instance | Keyword | Extension | ModName | QualModName | Error | PatternSynonym deriving (Show, Eq, Ord, Bounded, Enum, Read) instance Default DescrType where getDefault = Variable data SimpleDescr = SimpleDescr { sdName :: Text, sdType :: Maybe ByteString, sdLocation :: Maybe Location, sdComment :: Maybe ByteString, sdExported :: Bool} deriving (Show,Read,Eq,Ord,Typeable) descrType :: TypeDescr -> DescrType descrType VariableDescr = Variable descrType (FieldDescr _) = Field descrType (ConstructorDescr _) = Constructor descrType (DataDescr _ _) = Data descrType TypeDescr = Type descrType (NewtypeDescr _ _) = Newtype descrType (ClassDescr _ _) = Class descrType (MethodDescr _) = Method descrType (InstanceDescr _) = Instance descrType KeywordDescr = Keyword descrType ExtensionDescr = Extension descrType ModNameDescr = ModName descrType QualModNameDescr = QualModName descrType ErrorDescr = Error descrType PatternSynonymDescr = PatternSynonym data PackModule = PM { pack :: PackageIdentifier , modu :: ModuleName} deriving (Eq, Ord,Read,Show,Typeable) instance Show (Present PackModule) where showsPrec _ (Present pd) = showString (T.unpack $ (packageIdentifierToString . pack) pd) . showChar ':' . showString (display (modu pd)) parsePackModule :: Text -> PackModule parsePackModule str = let (pack',mod') = T.span (/= ':') str in case packageIdentifierFromString pack' of Nothing -> perror . T.unpack $ "Types>>parsePackModule: Can't parse package:" <> str Just pi'-> case simpleParse . T.unpack $ T.tail mod' of Nothing -> perror . T.unpack $ "Types>>parsePackModule: Can't parse module:" <> str Just mn -> PM pi' mn where perror s = error $ "cannot parse PackModule from " ++ s showPackModule :: PackModule -> Text showPackModule = T.pack . show . Present packageIdentifierToString :: PackageIdentifier -> Text packageIdentifierToString = T.pack . display packageIdentifierFromString :: Text -> Maybe PackageIdentifier packageIdentifierFromString = simpleParse . T.unpack instance Show (Present Descr) where showsPrec _ (Present descr) = case dscMbComment descr of Just comment -> p . showChar '\n' . c comment . t Nothing -> p . showChar '\n' . showChar '\n' . t where p = case dsMbModu descr of Just ds -> showString "-- " . shows (Present ds) Nothing -> id c com = showString $ unlines $ map (\(i,l) -> if i == 0 then "-- | " ++ l else "-- " ++ l) $ zip [0 .. length nelines - 1] nelines where nelines = nonEmptyLines $ BS.unpack com t = case dscMbTypeStr descr of Just ti -> showString $ BS.unpack ti Nothing -> id instance Eq RealDescr where (== ) a b = dscName' a == dscName' b && dscTypeHint' a == dscTypeHint' b instance Ord RealDescr where (<=) a b = if dscName' a == dscName' b then dscTypeHint' a <= dscTypeHint' b else dscName' a < dscName' b instance Eq ReexportedDescr where (== ) a b = dscName (Reexported a) == dscName (Reexported b) && dscTypeHint (Reexported a) == dscTypeHint (Reexported b) instance Ord ReexportedDescr where (<=) a b = if dscName (Reexported a) == dscName (Reexported b) then dscTypeHint (Reexported a) <= dscTypeHint (Reexported b) else dscName (Reexported a) < dscName (Reexported b) instance Default PackModule where getDefault = parsePackModule "unknow-0:Undefined" instance Default PackageIdentifier where getDefault = fromMaybe (error "CTypes.getDefault: Can't parse Package Identifier") (packageIdentifierFromString "unknown-0") -- | A portion of the source, spanning one or more lines and zero or more columns. data SrcSpan = SrcSpan { srcSpanFilename :: FilePath , srcSpanStartLine :: Int , srcSpanStartColumn :: Int , srcSpanEndLine :: Int , srcSpanEndColumn :: Int } deriving (Eq,Ord,Show) data Location = Location { locationFile :: FilePath , locationSLine :: Int , locationSCol :: Int , locationELine :: Int , locationECol :: Int } deriving (Show,Eq,Ord,Read,Typeable) instance Default ByteString where getDefault = BS.empty data Scope = PackageScope Bool | WorkspaceScope Bool | SystemScope -- True -> with imports, False -> without imports deriving (Show, Eq, Read) instance Ord Scope where _ <= SystemScope = True WorkspaceScope False <= WorkspaceScope True = True WorkspaceScope False <= PackageScope True = True PackageScope True <= WorkspaceScope True = True PackageScope False <= PackageScope True = True _ <= _ = False -- | An import declaration. data ImportDecl = ImportDecl { importLoc :: Location , importModule :: Text -- ^ name of the module imported. , importQualified :: Bool -- ^ imported @qualified@? , importSrc :: Bool -- ^ imported with @{-\# SOURCE \#-}@? , importPkg :: Maybe Text -- ^ imported with explicit package name , importAs :: Maybe Text -- ^ optional alias name in an @as@ clause. , importSpecs :: Maybe ImportSpecList -- ^ optional list of import specifications. } deriving (Eq,Ord,Read,Show) instance Pretty ImportDecl where pretty (ImportDecl _ mod' qual _ _ mbName mbSpecs) = mySep [text "import", if qual then text "qualified" else empty, pretty mod', maybePP (\m' -> text "as" <+> pretty m') mbName, maybePP exports mbSpecs] where exports (ImportSpecList b specList) = if b then text "hiding" <+> specs else specs where specs = parenList . map pretty $ specList parenList :: [Doc] -> Doc parenList = PP.parens . fsep . PP.punctuate PP.comma mySep :: [Doc] -> Doc mySep [x] = x mySep (x:xs) = x <+> fsep xs mySep [] = error "Internal error: mySep" -- | An explicit import specification list. data ImportSpecList = ImportSpecList Bool [ImportSpec] -- A list of import specifications. -- The 'Bool' is 'True' if the names are excluded -- by @hiding@. deriving (Eq,Ord,Read,Show) -- | An import specification, representing a single explicit item imported -- (or hidden) from a module. data ImportSpec = IVar Text -- ^ variable | IAbs Text -- ^ @T@: -- the name of a class, datatype or type synonym. | IThingAll Text -- ^ @T(..)@: -- a class imported with all of its methods, or -- a datatype imported with all of its constructors. | IThingWith Text [Text] -- ^ @T(C_1,...,C_n)@: -- a class imported with some of its methods, or -- a datatype imported with some of its constructors. deriving (Eq,Ord,Read,Show) newtype VName = VName Text instance Pretty ImportSpec where pretty (IVar name) = pretty (VName name) pretty (IAbs name) = pretty name pretty (IThingAll name) = pretty name <> text "(..)" pretty (IThingWith name nameList) = pretty name <> parenList (map (pretty . VName) nameList) instance Pretty VName where pretty (VName t) = let str = T.unpack t in if isOperator str then PP.parens (PP.text str) else PP.text str isOperator :: String -> Bool isOperator ('(':_) = False -- (), (,) etc isOperator ('[':_) = False -- [] isOperator ('$':c:_) = not (isAlpha c) -- Don't treat $d as an operator isOperator (':':c:_) = not (isAlpha c) -- Don't treat :T as an operator isOperator ('_':_) = False -- Not an operator isOperator (c:_) = not (isAlpha c) -- Starts with non-alpha isOperator _ = False -- --------------------------------------------------------------------- -- NFData instances for forcing evaluation -- #if MIN_VERSION_deepseq(1,2,0) && !MIN_VERSION_containers(0,4,2) instance (NFData k, NFData a) => NFData (Map k a) where rnf = rnf . Map.toList instance NFData a => NFData (Set a) where rnf = rnf . Set.toList #endif instance NFData Location where rnf pd = rnf (locationSLine pd) `seq` rnf (locationSCol pd) `seq` rnf (locationELine pd) `seq` rnf (locationECol pd) instance NFData PackageDescr where rnf pd = rnf (pdPackage pd) `seq` rnf (pdMbSourcePath pd) `seq` rnf (pdModules pd) `seq` rnf (pdBuildDepends pd) instance NFData ModuleDescr where rnf pd = rnf (mdModuleId pd) `seq` rnf (mdMbSourcePath pd) `seq` rnf (mdReferences pd) `seq` rnf (mdIdDescriptions pd) instance NFData Descr where rnf (Real (RealDescr dscName'' dscMbTypeStr'' dscMbModu'' dscMbLocation'' dscMbComment'' dscTypeHint'' dscExported'')) = rnf dscName'' `seq` rnf dscMbTypeStr'' `seq` rnf dscMbModu'' `seq` rnf dscMbLocation'' `seq` rnf dscMbComment'' `seq` rnf dscTypeHint'' `seq` rnf dscExported'' rnf (Reexported (ReexportedDescr reexpModu' impDescr')) = rnf reexpModu' `seq` rnf impDescr' instance NFData TypeDescr where rnf (FieldDescr typeDescrF') = rnf typeDescrF' rnf (ConstructorDescr typeDescrC') = rnf typeDescrC' rnf (DataDescr constructors' fields') = constructors' `seq` rnf fields' rnf (NewtypeDescr constructor' mbField') = rnf constructor' `seq` rnf mbField' rnf (ClassDescr super' methods') = rnf super' `seq` rnf methods' rnf (MethodDescr classDescrM') = rnf classDescrM' rnf (InstanceDescr binds') = rnf binds' rnf a = seq a () instance NFData SimpleDescr where rnf pd = rnf (sdName pd) `seq` rnf (sdType pd) `seq` rnf (sdLocation pd) `seq` rnf (sdComment pd) `seq` rnf (sdExported pd) #if !MIN_VERSION_ghc(7,7,0) instance NFData PackageIdentifier where rnf pd = rnf (pkgName pd) `seq` rnf (pkgVersion pd) #endif instance NFData DescrType where rnf a = seq a () #if !MIN_VERSION_bytestring(0,10,0) instance NFData ByteString where rnf b = seq b () #endif #if !MIN_VERSION_deepseq(1,3,0) instance NFData Version where rnf v = seq v () #endif instance NFData PackModule where rnf pd = rnf (pack pd) `seq` rnf (modu pd) instance NFData ModuleName where rnf = rnf . components #if !MIN_VERSION_ghc(7,7,0) instance NFData PackageName where rnf (PackageName s) = rnf s #endif
JPMoresmau/leksah-server
src/IDE/Core/CTypes.hs
gpl-2.0
22,920
0
16
7,000
5,701
3,096
2,605
450
3
-- -*- mode: haskell -*- {-# LANGUAGE TemplateHaskell #-} module Grammatik.CF.Instance.Config ( Config (..) -- , Long (..) , module Autolib.Long ) where -- -- $Id$ import Language.Syntax import Grammatik.Property import Autolib.Long import Autolib.ToDoc import Autolib.Reader import Data.Typeable data Config = Config { lang :: Language.Syntax.Type , properties :: [ Property ] , yeah :: Long ( Long Char ) , noh :: Long ( Long Char ) } deriving ( Eq, Typeable ) $(derives [makeReader, makeToDoc] [''Config])
florianpilz/autotool
src/Grammatik/CF/Instance/Config.hs
gpl-2.0
550
3
10
119
143
90
53
17
0
module Hectare.Util where interleave :: [a] -> [a] -> [a] interleave [] ys = ys interleave xs [] = xs interleave xs ys = head xs : head ys : interleave (tail xs) (tail ys) pairSwap :: [([a],[a])] -> [([a],[a])] pairSwap [] = [] pairSwap [x] = [x] pairSwap (x:(s,t):xs) = x : (reverse s,reverse t) : pairSwap xs concatBash :: [[a]] -> [a] concatBash [] = [] concatBash xs = (head . head) xs : concatMap tail xs boustrophedron :: [[a]] -> [a] boustrophedron [] = [] boustrophedron [x] = x boustrophedron (x:y:xs) = tail x ++ (tail . reverse) y ++ boustrophedron xs -- boustrophedron (x:y:xs) = x ++ [last x,last x] ++ (reverse y) ++ [head y] ++ boustrophedron xs bundle :: Int -> [a] -> [[a]] bundle _ [] = [] bundle n xs = ys : bundle n yss where (ys, yss) = splitAt n xs log2 :: Int -> Int log2 1 = 0 log2 n = 1 + log2 (n `div` 2) (×) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) (f × g) (x, y) = (f x, g y)
zenzike/hectare
src/Hectare/Util.hs
gpl-2.0
923
0
11
208
543
293
250
25
1
{-# LANGUAGE FlexibleContexts , FlexibleInstances , RecordWildCards , ScopedTypeVariables #-} module Hammer.Math.Optimum ( lineSearch , bfgs , defaultBFGS , BFGScfg (..) ) where import Linear.Vect import Linear.Mat () -- =================================== Line Search ======================================= -- | Inexact line search algorithm using strong Wolfe conditions. lineSearch :: (LinearMap Double v, DotProd Double v) => (v Double -> (Double, v Double)) -> v Double -> v Double -> Double lineSearch func x p | dphi0 < 0 = upper 0 1 | otherwise = 1 where dir = p c1 = 0.0001 c2 = 0.3 eval a = let (f, g) = func (x &+ a *& dir) in (f, dir &. g) (phi0, dphi0) = eval 0 upper :: Int -> Double -> Double upper n1 a | n1 > 200 = a | wolfe0 = zoom 0 (a / 2, a) | wolfe1 = zoom 0 (0, a) | wolfe2 = a | dphia >= 0 = zoom 0 (a, a / 2) | otherwise = upper (n1+1) (a * 2) where (phia, dphia) = eval a phiOlda = fst $ eval (a/2) wolfe0 = (wolfe1 || phia >= phiOlda) && n1 > 0 wolfe1 = phia > phi0 + c1 * a * dphi0 wolfe2 = abs dphia <= -c2 * dphi0 zoom :: Int -> (Double, Double) -> Double zoom n2 (al, ah) | n2 > 500 = a | abs (ah - al) < 1e-5 = a | wolfe1 = zoom (n2+1) (al, a) | phia >= phial = zoom (n2+1) (al, a) | wolfe2 = a | dphia * (ah - al) >= 0 = zoom (n2+1) (a, al) | otherwise = zoom (n2+1) (a, ah) where a = (al + ah) / 2 (phia, dphia) = eval a phial = fst $ eval al wolfe1 = phia > phi0 + c1 * a * dphi0 wolfe2 = abs dphia <= -c2 * dphi0 -- ======================================= BFGS ========================================== data BFGScfg = BFGScfg { epsi :: Double , tol :: Double , niter :: Int } deriving (Show) defaultBFGS :: BFGScfg defaultBFGS = BFGScfg { epsi = 1e-9, tol = 1e-7, niter = 100 } -- | Quasi-Newton algorithm BFGS for function minimization. Implementation based on: -- "Springer Series in Operations Research and Financial Engineering" bfgs :: forall v m . ( LinearMap Double v , LinearMap Double m , Norm Double v , SquareMatrix (m Double) , MultSemiGroup (m Double) , Tensor (m Double) (v Double) , LeftModule (m Double) (v Double) ) => BFGScfg -> (v Double -> (Double, v Double)) -> v Double -> v Double bfgs BFGScfg{..} func x = go 0 (x, g, idmtx) where (_, g) = func x go counter (x0, g0, h0) | counter > niter = x1 | norm g1 < epsi = x1 | norm (x0 &- x1) < tol = x1 | counter < 1 = go (counter + 1) (x1, g1, h1a) | otherwise = go (counter + 1) (x1, g1, h1) where dir = neg (h0 *. g0) a1 = lineSearch func x0 dir x1 = x0 &+ a1 *& dir (_, g1) = func x1 s0 = x1 &- x0 y0 = g1 &- g0 p0 = 1 / (y0 &. s0) -- Improve first H guess h1a = ((y0 &. s0) / (y0 &. y0)) *& idmtx -- Update H using estimation technique h1 :: m Double h1 = let ma = idmtx &- (p0 *& (outer s0 y0)) mb = idmtx &- (p0 *& (outer y0 s0)) mc = p0 *& (outer s0 s0) in ma .*. h0 .*. mb &+ mc -- =================================== Test functions===================================== testLS :: Double testLS = lineSearch (\(Vec2 x y) -> (x*x + y*y, Vec2 (2*x) (2*y))) (Vec2 1 0) (Vec2 (-4) (-2)) testBFGS :: Vec2 Double testBFGS = bfgs defaultBFGS func (Vec2 100 (431)) where func (Vec2 x y) = (2*x*x + 2*x*y + 2*y*y - 6*x, Vec2 (4*x + 2*y - 6) (2*x + 4*y))
lostbean/Hammer
src/Hammer/Math/Optimum.hs
gpl-3.0
3,782
0
17
1,285
1,586
837
749
94
1
{- | Module : FMP.Color Copyright : (c) 2003-2010 Peter Simons (c) 2002-2003 Ferenc Wágner (c) 2002-2003 Meik Hellmund (c) 1998-2002 Ralf Hinze (c) 1998-2002 Joachim Korittky (c) 1998-2002 Marco Kuhlmann License : GPLv3 Maintainer : simons@cryp.to Stability : provisional Portability : portable -} {- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} module FMP.Color ( Color(..), HasColor(..), HasBGColor(..), white, black, red, green, blue, yellow, cyan, magenta, grey, color, hsv2rgb, graduateLow, graduateMed, graduateHigh, graduate ) where data Color = DefaultColor | Color Double Double Double | Graduate Color Color Double Int deriving (Eq, Show, Read) class HasColor a where setColor :: Color -> a -> a setDefaultColor :: a -> a getColor :: a -> Color class HasBGColor a where setBGColor :: Color -> a -> a setDefaultBGColor :: a -> a getBGColor :: a -> Color white, black, red, green, blue , yellow, cyan, magenta :: Color white = Color 1 1 1 black = Color 0 0 0 red = Color 1 0 0 green = Color 0 1 0 blue = Color 0 0 1 yellow = Color 1 1 0 cyan = Color 0 1 1 magenta = Color 1 0 1 grey :: Double -> Color grey n = Color n n n color :: Double -> Double -> Double -> Color color r g b = Color r g b graduateLow :: Color -> Color -> Double -> Color graduateLow c1 c2 a = graduate c1 c2 a 16 graduateMed :: Color -> Color -> Double -> Color graduateMed c1 c2 a = graduate c1 c2 a 64 graduateHigh :: Color -> Color -> Double -> Color graduateHigh c1 c2 a = graduate c1 c2 a 256 graduate :: Color -> Color -> Double -> Int -> Color graduate c1 c2 a n = Graduate c1 c2 a n instance Num Color where Color r1 g1 b1 + Color r2 g2 b2 = Color (r1+r2) (g1+g2) (b1+b2) Graduate c1 c2 a n + c3@(Color _ _ _) = Graduate (c1+c3) (c2+c3) a n c3@(Color _ _ _) + Graduate c1 c2 a n = Graduate (c1+c3) (c2+c3) a n Graduate c1 c2 a n + Graduate c3 c4 a' n' = Graduate (c1+c3) (c2+c4) ((a+a')/2) (maximum [n,n']) a + DefaultColor = a DefaultColor + a = a Color r1 g1 b1 - Color r2 g2 b2 = Color (r1-r2) (g1-g2) (b1-b2) Graduate c1 c2 a n - c3@(Color _ _ _) = Graduate (c1-c3) (c2-c3) a n c3@(Color _ _ _) - Graduate c1 c2 a n = Graduate (c3-c1) (c3-c2) a n Graduate c1 c2 a n - Graduate c3 c4 a' n' = Graduate (c1-c3) (c2-c4) ((a+a')/2) (maximum [n,n']) a - DefaultColor = a DefaultColor - a = a Color r1 g1 b1 * Color r2 g2 b2 = Color (r1*r2) (g1*g2) (b1*b2) Graduate c1 c2 a n * c3@(Color _ _ _) = Graduate (c1*c3) (c2*c3) a n c3@(Color _ _ _) * Graduate c1 c2 a n = Graduate (c3*c1) (c3*c2) a n Graduate c1 c2 a n * Graduate c3 c4 a' n' = Graduate (c1*c3) (c2*c4) ((a+a')/2) (maximum [n,n']) a * DefaultColor = a DefaultColor * a = a negate (Color r g b) = Color (1-r) (1-g) (1-b) negate (Graduate c1 c2 a n) = Graduate (-c1) (-c2) a n negate DefaultColor = DefaultColor abs a = a signum a = a fromInteger i = Color f f f where f = fromInteger i instance Fractional Color where Color r1 g1 b1 / Color r2 g2 b2 = Color (r1/r2) (g1/g2) (b1/b2) Graduate c1 c2 a n / c3@(Color _ _ _) = Graduate (c1/c3) (c2/c3) a n c3@(Color _ _ _) / Graduate c1 c2 a n = Graduate (c3/c1) (c3/c2) a n Graduate c1 c2 a n / Graduate c3 c4 a' n' = Graduate (c1/c3) (c2/c4) ((a+a')/2) (maximum [n,n']) a / _ = a recip (Color r g b) = Color (recip r) (recip g) (recip b) recip a = a fromRational i = Color f f f where f = fromRational i hsv2rgb :: (Double,Double,Double) -> Color hsv2rgb (_, 0, v) = Color v v v hsv2rgb (h, s, v) = case i' of 0 -> Color v t3 t1 1 -> Color t2 v t1 2 -> Color t1 v t3 3 -> Color t1 t2 v 4 -> Color t3 t1 v _ -> Color v t1 t2 where h' = h / 60.0 i' = mod (floor h') 6 i = floor h' fract = h' - fromIntegral i t1 = v * (1 - s) t2 = v * (1 - s * fract) t3 = v * (1 - s * (1 - fract))
peti/funcmp
FMP/Color.hs
gpl-3.0
6,644
0
11
3,283
2,057
1,058
999
111
6
{- - Copyright (C) 2013 Alexander Berntsen <alexander@plaimi.net> - Copyright (C) 2013 Stian Ellingsen <stian@plaimi.net> - - This file is part of bweakfwu. - - bweakfwu 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. - - bweakfwu 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 bweakfwu. If not, see <http://www.gnu.org/licenses/>. -} module Vector where import Graphics.Gloss.Data.Vector (Vector, dotV, magV) infixl 7 ^.^ (^.^) :: Vector -> Vector -> Float -- | '^.^' finds the scalar (dot) product of two 2D 'Vector's. (I.e. the -- product of the magnitudes and the cosine of the angle between them.) (^.^) = dotV vecScalarOp :: (Float -> Float -> Float) -> Vector -> Float -> Vector -- | 'vecScalarOp' takes a binary mathematical operator and applies it to -- a number and both components of a 2D 'Vector'. vecScalarOp op (x, y) s = (op x s, op y s) infixl 7 ^/^ (^/^) :: Vector -> Float -> Vector -- | '^/^' divides both components of a 2D 'Vector' with a number. (^/^) = vecScalarOp (/) infixl 7 ^*^ -- | '^*^' multiplies both components of a 2D 'Vector' with a number. (^*^) :: Vector -> Float -> Vector (^*^) = vecScalarOp (*) magVec :: Vector -> Float -- | 'magVec' finds the magnitude of a 2D 'Vector'. magVec = magV vecLimitMag :: Float -> Vector -> Vector -- | 'vecLimitMag' clamps the magnitude of a 2D 'Vector' to an argument. vecLimitMag maxMag v | m > maxMag = v ^*^ (maxMag / m) | otherwise = v where m = magVec v vecNorm :: Vector -> Vector -- | 'vecNorm' normalises a 2D 'Vector'. vecNorm v | v == (0, 0) = v | otherwise = v ^*^ (1 / magVec v)
plaimi/bweakfwu
src/bweakfwu/Vector.hs
gpl-3.0
2,036
0
9
399
318
182
136
24
1
module Main where import Control.Monad (forever) import Network.Socket hiding (recv) import Network.Socket.ByteString (recv, sendAll) logAndEcho :: Socket -> IO () logAndEcho sock = forever $ do (soc, _) <- accept sock printAndKickback soc sClose soc where printAndKickback conn = do msg <- recv conn 1024 print msg sendAll conn msg main :: IO () main = withSocketsDo $ do addrinfos <- getAddrInfo (Just $ defaultHints { addrFlags = [AI_PASSIVE]}) Nothing (Just "79") let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol bindSocket sock (addrAddress serveraddr) listen sock 1 logAndEcho sock sClose sock
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
FingerDaemon/debug/Main.hs
gpl-3.0
828
0
14
278
252
122
130
27
1
{-# LANGUAGE FlexibleContexts #-} module Solver.SafetyInvariant ( checkSafetyInvariantSat , SafetyInvariant , trapToSafetyInvariant ) where import Data.SBV import Data.List (intercalate) import qualified Data.Map as M import Control.Arrow (second) import Util import Solver import Property import PetriNet type SimpleTerm = (Vector Place, Integer) type NamedTerm = (String, SimpleTerm) data SafetyInvariant = SafetyPlaceInvariant SimpleTerm | SafetyTrapInvariant Trap instance Show SafetyInvariant where show (SafetyPlaceInvariant (ps, c)) = intercalate " + " (map showWeighted (items ps)) ++ " ≤ " ++ show c show (SafetyTrapInvariant ps) = intercalate " + " (map show ps) ++ " ≥ 1" instance Invariant SafetyInvariant where invariantSize (SafetyPlaceInvariant (ps, _)) = size ps invariantSize (SafetyTrapInvariant ps) = length ps formulaToSimpleTerms :: Formula Place -> [SimpleTerm] formulaToSimpleTerms = transformF where transformF FTrue = [] transformF (p :&: q) = transformF p ++ transformF q transformF (LinearInequation ps Gt (Const 0)) = transformT 1 ps 1 transformF (LinearInequation ps Ge (Const 1)) = transformT 1 ps 1 transformF (LinearInequation ps Eq (Const 0)) = transformT (-1) ps 0 transformF (LinearInequation ps Le (Const 0)) = transformT (-1) ps 0 transformF (LinearInequation ps Lt (Const 1)) = transformT (-1) ps 0 transformF f = error $ "formula not supported for invariant: " ++ show f transformT fac ps w = [(buildVector (transformTerm fac ps), w)] transformTerm fac (t :+: u) = transformTerm fac t ++ transformTerm fac u transformTerm fac (t :-: u) = transformTerm fac t ++ transformTerm (- fac) u transformTerm fac (Const c :*: t) = transformTerm (fac * c) t transformTerm fac (t :*: Const c) = transformTerm (fac * c) t transformTerm fac (Var x) = [(x, fac)] transformTerm _ t = error $ "term not supported for invariant: " ++ show t trapToSimpleTerm :: Trap -> SimpleTerm trapToSimpleTerm traps = (buildVector (map (\p -> (p, 1)) traps), 1) checkInductivityConstraint :: PetriNet -> SIMap Place -> SBool checkInductivityConstraint net lambda = bAnd $ map checkInductivity $ transitions net where checkInductivity t = let incoming = map addPlace $ lpre net t outgoing = map addPlace $ lpost net t in sum outgoing - sum incoming .<= 0 addPlace (p,w) = literal w * val lambda p checkSafetyConstraint :: PetriNet -> [NamedTerm] -> SIMap Place -> SIMap String -> SBool checkSafetyConstraint net terms lambda y = sum (map addPlace (linitials net)) .< sum (map addTerm terms) where addPlace (p,w) = literal w * val lambda p addTerm (n,(_,c)) = literal c * val y n checkPropertyConstraint :: PetriNet -> [NamedTerm] -> SIMap Place -> SIMap String -> SBool checkPropertyConstraint net terms lambda y = bAnd $ map checkPlace $ places net where checkPlace p = val lambda p .>= sum (map (addTerm p) terms) addTerm p (n,(ps,_)) = val y n * literal (val ps p) checkNonNegativityConstraint :: [NamedTerm] -> SIMap String -> SBool checkNonNegativityConstraint terms y = bAnd $ map checkVal terms where checkVal (n,_) = val y n .>= 0 checkSafetyInvariant :: PetriNet -> [NamedTerm] -> SIMap Place -> SIMap String -> SBool checkSafetyInvariant net terms lambda y = checkInductivityConstraint net lambda &&& checkSafetyConstraint net terms lambda y &&& checkPropertyConstraint net terms lambda y &&& checkNonNegativityConstraint terms y -- TODO: split up into many smaller sat problems checkSafetyInvariantSat :: PetriNet -> Formula Place -> [Trap] -> ConstraintProblem Integer SafetyInvariant checkSafetyInvariantSat net f traps = let formTerms = formulaToSimpleTerms f namedTraps = numPref "@trap" `zip` traps namedTrapTerms = map (second trapToSimpleTerm) namedTraps namedFormTerms = numPref "@term" `zip` formTerms namedTerms = namedFormTerms ++ namedTrapTerms lambda = makeVarMap $ places net names = map fst namedTerms myVarMap fvm = M.fromList $ names `zip` fmap fvm names in ("safety invariant constraints", "safety invariant", getNames lambda ++ names, \fm -> checkSafetyInvariant net namedTerms (fmap fm lambda) (myVarMap fm), \fm -> getSafetyInvariant net (fmap fm lambda)) trapToSafetyInvariant :: Trap -> SafetyInvariant trapToSafetyInvariant = SafetyTrapInvariant getSafetyInvariant :: PetriNet -> IMap Place -> SafetyInvariant getSafetyInvariant net lambda = SafetyPlaceInvariant (buildVector (items lambda), sum (map (\(p,i) -> val lambda p * i) (linitials net)))
cryptica/slapnet
src/Solver/SafetyInvariant.hs
gpl-3.0
5,340
0
13
1,605
1,614
824
790
112
13
module Experimentation.P22 (p22_test) where import Test.HUnit import Data.List range_rec :: (Ord a, Enum a) => a -> a -> [a] range_rec a b | a > b = [] | otherwise = a : range_rec (succ a) b range_fold :: (Enum a) => a -> a -> [a] range_fold a b = foldl (\x y -> x ++ [y]) [] [a..b] -- Tests test_range_rec = TestCase $ do assertEqual "for (range_rec 4 9)" [4,5,6,7,8,9] (range_rec 4 9) assertEqual "for (range_rec 'a' 'c')" "abc" (range_rec 'a' 'c') test_range_fold = TestCase $ do assertEqual "for (range_fold 4 9)" [4,5,6,7,8,9] (range_fold 4 9) assertEqual "for (range_fold 'a' 'c')" "abc" (range_fold 'a' 'c') p22_test = do runTestTT p22_tests p22_tests = TestList [ TestLabel "test_range_rec" test_range_rec, TestLabel "test_range_fold" test_range_fold ]
adarqui/99problems-hs
Experimentation/P22.hs
gpl-3.0
782
0
10
146
326
171
155
20
1
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} module SugarScape.Agent ( agentSF , dieOfAge , agentMetabolism , agentDies , starvedToDeath ) where import Control.Monad.Random import Control.Monad.State.Strict import FRP.BearRiver import SugarScape.AgentMonad import SugarScape.Common import SugarScape.Discrete import SugarScape.Model import SugarScape.Random import SugarScape.Utils type InternalAgentMonadT g = StateT SugEnvironment (AgentT (Rand g)) ------------------------------------------------------------------------------------------------------------------------ agentSF :: RandomGen g => SugarScapeParams -> AgentId -> SugAgentState -> SugAgent g agentSF params aid s0 = feedback s0 (proc (env, s) -> do t <- time -< () let age = floor t (ao, s', env') <- arrM (\(age, s, env) -> do ((ao, s'), env') <- lift $ runStateT (runStateT (agentBehaviour params aid age) s) env return (ao, s', env')) -< (age, s, env) returnA -< ((ao, env'), s')) ------------------------------------------------------------------------------------------------------------------------ -- Chapter II: Life And Death On The Sugarscape ------------------------------------------------------------------------------------------------------------------------ agentBehaviour :: RandomGen g => SugarScapeParams -> AgentId -> Int -> StateT SugAgentState (InternalAgentMonadT g) (SugAgentOut g) agentBehaviour params aid age = do agentAgeing age harvestAmount <- agentMove params aid metabAmount <- agentMetabolism agentPolute params harvestAmount (fromIntegral metabAmount) ifThenElseM (starvedToDeath `orM` dieOfAge) (agentDies params) observable agentMove :: RandomGen g => SugarScapeParams -> AgentId -> StateT SugAgentState (InternalAgentMonadT g) Double agentMove params aid = do cellsInSight <- agentLookout coord <- agentProperty sugAgCoord let uoc = filter (cellUnoccupied . snd) cellsInSight ifThenElse (null uoc) (agentHarvestCell coord) (do -- NOTE included self but this will be always kicked out because self is occupied by self, need to somehow add this -- what we want is that in case of same sugar on all fields (including self), the agent does not move because staying is the lowest distance (=0) selfCell <- lift $ cellAtM coord let uoc' = (coord, selfCell) : uoc bf = bestCellFunc params bcs = selectBestCells bf coord uoc' (cellCoord, _) <- lift $ lift $ lift $ randomElemM bcs agentMoveTo aid cellCoord agentHarvestCell cellCoord) agentLookout :: RandomGen g => StateT SugAgentState (InternalAgentMonadT g) [(Discrete2dCoord, SugEnvCell)] agentLookout = do vis <- agentProperty sugAgVision coord <- agentProperty sugAgCoord lift $ neighboursInNeumannDistanceM coord vis False agentMoveTo :: RandomGen g => AgentId -> Discrete2dCoord -> StateT SugAgentState (InternalAgentMonadT g) () agentMoveTo aid cellCoord = do unoccupyPosition updateAgentState (\s -> s { sugAgCoord = cellCoord }) cell <- lift $ cellAtM cellCoord let co = cell { sugEnvCellOccupier = Just aid } lift $ changeCellAtM cellCoord co agentHarvestCell :: RandomGen g => Discrete2dCoord -> StateT SugAgentState (InternalAgentMonadT g) Double agentHarvestCell cellCoord = do cell <- lift $ cellAtM cellCoord sugarLevelAgent <- agentProperty sugAgSugarLevel let sugarLevelCell = sugEnvCellSugarLevel cell let newSugarLevelAgent = sugarLevelCell + sugarLevelAgent updateAgentState (\s -> s { sugAgSugarLevel = newSugarLevelAgent }) let cellHarvested = cell { sugEnvCellSugarLevel = 0 } lift $ changeCellAtM cellCoord cellHarvested return sugarLevelCell agentMetabolism :: MonadState SugAgentState m => m Int agentMetabolism = do sugarMetab <- agentProperty sugAgSugarMetab sugarLevel <- agentProperty sugAgSugarLevel let sugarLevel' = max 0 (sugarLevel - fromIntegral sugarMetab) updateAgentState (\s' -> s' { sugAgSugarLevel = sugarLevel' }) return sugarMetab agentPolute :: RandomGen g => SugarScapeParams -> Double -> Double -> StateT SugAgentState (InternalAgentMonadT g) () agentPolute params s m = agentPoluteAux $ spPolutionFormation params where agentPoluteAux :: RandomGen g => PolutionFormation -> StateT SugAgentState (InternalAgentMonadT g) () agentPoluteAux NoPolution = return () agentPoluteAux (Polute a b) = do let polution = a * s + b * m (coord, c) <- agentCellOnCoord let c' = c { sugEnvCellPolutionLevel = sugEnvCellPolutionLevel c + polution } lift $ changeCellAtM coord c' -- this is rule R implemented, see page 32/33 "when an agent dies it is replaced by an agent -- of agent 0 having random genetic attributes, random position on the sugarscape..." -- => will happen if agent starves to death (spice or sugar) or dies from age agentDies :: RandomGen g => SugarScapeParams -> StateT SugAgentState (InternalAgentMonadT g) (SugAgentOut g) agentDies params = do unoccupyPosition let ao = kill agentOut if spReplaceAgents params then do (_, newA) <- birthNewAgent params return $ newAgent newA ao else return ao birthNewAgent :: RandomGen g => SugarScapeParams -> StateT SugAgentState (InternalAgentMonadT g) (AgentId, SugAgentDef g) birthNewAgent params = do newAid <- lift $ lift nextAgentId (newCoord, newCell) <- findUnoccpiedRandomPosition (newA, _) <- lift $ lift $ lift $ randomAgent params (newAid, newCoord) (agentSF params) id -- need to occupy the cell to prevent other agents occupying it let newCell' = newCell { sugEnvCellOccupier = Just newAid } lift $ changeCellAtM newCoord newCell' return (newAid, newA) where -- the more cells occupied the less likely an unoccupied position will be found -- => restrict number of recursions and if not found then take up same position findUnoccpiedRandomPosition :: RandomGen g => StateT SugAgentState (InternalAgentMonadT g) (Discrete2dCoord, SugEnvCell) findUnoccpiedRandomPosition = do e <- lift get (c, coord) <- lift $ lift $ lift $ randomCell e -- TODO: replace by randomCellM ifThenElse (cellOccupied c) findUnoccpiedRandomPosition (return (coord, c)) agentAgeing :: MonadState SugAgentState m => Int -> m () agentAgeing age = updateAgentState (\s' -> s' { sugAgAge = age }) dieOfAge :: MonadState SugAgentState m => m Bool dieOfAge = do ageSpan <- agentProperty sugAgMaxAge case ageSpan of Nothing -> return False Just maxAge -> do age <- agentProperty sugAgAge return $ age >= maxAge starvedToDeath :: MonadState SugAgentState m => m Bool starvedToDeath = do sugar <- agentProperty sugAgSugarLevel return $ sugar <= 0 unoccupyPosition :: RandomGen g => StateT SugAgentState (InternalAgentMonadT g) () unoccupyPosition = do (coord, cell) <- agentCellOnCoord let cell' = cell { sugEnvCellOccupier = Nothing } lift $ changeCellAtM coord cell' agentCellOnCoord :: RandomGen g => StateT SugAgentState (InternalAgentMonadT g) (Discrete2dCoord, SugEnvCell) agentCellOnCoord = do coord <- agentProperty sugAgCoord cell <- lift $ cellAtM coord return (coord, cell) updateAgentState :: MonadState SugAgentState m => (SugAgentState -> SugAgentState) -> m () updateAgentState = modify agentProperty :: MonadState SugAgentState m => (SugAgentState -> p) -> m p agentProperty = gets observable :: (MonadState SugAgentState m, RandomGen g) => m (SugAgentOut g) observable = get >>= \s -> return $ agentOutObservable $ sugObservableFromState s
thalerjonathan/phd
public/towards/SugarScape/experimental/chapter2_environment/src/SugarScape/Agent.hs
gpl-3.0
8,502
1
22
2,307
2,073
1,030
1,043
186
2
module Main (main) where import Data.Time.Clock import Data.Time.Format import Data.Csv import Network.HTTP.Client import Network.HTTP.Client.TLS import qualified Data.ByteString.Lazy as BS import Onliner main :: IO () main = do time <- getCurrentTime manager <- newManager tlsManagerSettings putStrLn "Retrieving data..." flats <- grab manager let csv = encodeDefaultOrderedByName flats filename = formatTime defaultTimeLocale "onliner-%Y-%m-%dT%H:%M:%S.csv" time putStrLn "Saving data..." BS.writeFile filename csv putStrLn $ "Saved to " ++ filename
kurnevsky/flats
src/Main.hs
agpl-3.0
576
0
10
90
150
78
72
19
1
module HW6 where import Prelude hiding (and,or,not,pred,succ,fst,snd,either) import Data.Maybe import DeBruijn import Church -- -- * Part 1: Church pair update functions -- -- | 1. A lambda calculus function that replaces the first element in a -- Church-encoded pair. The first argument to the function is the original -- pair, the second is the new first element. -- -- >>> :{ -- eval (app2 pair true (num 3)) == -- eval (app2 setFst (app2 pair (num 2) (num 3)) true) -- :} -- True setFst :: Exp setFst = abs2 ( app2 pair (Ref 0) (App snd (Ref 1)) ) -- | 2. A lambda calculus function that replaces the second element in a -- Church-encoded pair. The first argument to the function is the original -- pair, the second is the new second element. -- -- >>> :{ -- eval (app2 pair (num 2) true) == -- eval (app2 setSnd (app2 pair (num 2) (num 3)) true) -- :} -- True -- setSnd :: Exp setSnd = abs2 ( app2 pair (App fst (Ref 1)) (Ref 0) ) -- -- * Part 2: Church encoding a Haskell program -- -- | Pretend Haskell's Int is restricted to Nats. type Nat = Int -- | A simple data type with three cases. data Foo = N Nat | B Bool | P Nat Bool deriving (Eq,Show) -- | Compute a numeric value from a Foo. -- (This is just an arbitrary function.) bar :: Foo -> Nat bar (N n) = n * 3 bar (B True) = 1 bar (B False) = 0 bar (P n b) = n + if b then 1 else 0 -- | 3. Write a Haskell function that converts a Foo into a -- lambda calculus term. encodeFoo :: Foo -> Exp encodeFoo (N n) = Abs (app2 mult (num n) three) -- or (N n) = num n encodeFoo (B True) = one encodeFoo (B False) = zero encodeFoo (P n b) = abs2 ( app2 add (num n) (app3 if_ (bExp' (b == True)) one zero) ) -- or (P n b) = app2 pair (num n) (bExp' b) -- | 4. Implement the bar function as a lambda calculus term. bExp :: Foo -> Maybe Exp bExp (B True) = Just true bExp (B False) = Just false _ = Nothing nExp :: Foo -> Maybe Exp nExp (N n) = Just (num n) _ = Nothing pExp :: Foo -> Exp pExp (P n b) = app2 pair (num n) (bExp' b) bExp' :: Bool -> Exp bExp' True = true bExp' False = false toFoo :: Exp -> Foo toFoo false = (B False) toFoo true = (B True) toFoo one = (N 1) toFoo zero = (N 0) _ = (N 4) --buildInt :: Exp -> Int -- test (N 4) doesnt work -- I assumed that Ref 0 in line 104 would be an Exp number -- Then we multiply it by 3. But I dont know why its not returning true -- I shouldnt need to convert to a foo, just operate right on the Exp -- Could be an error in the line above -- barExp :: Exp barExp = Abs ( app3 if_ (bExp' (isJust (bExp (toFoo (Ref 0))))) ( app3 if_ (bExp' ((fromJust (bExp (toFoo (Ref 0)))) == true)) one zero ) ( app3 if_ (bExp' (isJust (nExp (toFoo (Ref 0))))) ( app2 mult (Ref 0) three ) ( app2 add (App fst (pExp (toFoo (Ref 0)))) (app3 if_ (bExp' ((App snd (fromJust (bExp (toFoo (Ref 0))))) == true)) one zero ) ) ) ) -- | Run your lambda-encoded bar function on a lambda-encoded Foo. runBar :: Foo -> Exp runBar x = eval (App barExp (encodeFoo x)) -- | A function for testing encodeFoo and barExp. Checks to see if the lambda -- calculus encoding returns the same number as the given value function. -- -- >>> test (N 4) -- True -- -- >>> test (B True) -- True -- -- >>> test (B False) -- True -- -- >>> test (P 5 True) -- True -- -- >>> test (P 5 False) -- True -- test :: Foo -> Bool test x = num (bar x) == eval (App barExp (encodeFoo x))
neale/CS-program
581-FunctionalProgramming/week6/HW6.hs
unlicense
3,765
0
27
1,144
1,017
552
465
56
2
-- This file is part of "Loopless Functional Algorithms". -- Copyright (c) 2005 Jamie Snape, Oxford University Computing Laboratory. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- https://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module LooplessMixallForest where import List (unfoldr) import RealTimeQueue data Rose a = Node a (Queue (Rose a)) mixall = unfoldr step . prolog prolog = wrapQueue . fst . foldr tmix (empty,empty) tmix xs (ytq,qty) = if even (length xs) then (fmix xs (ytq,qty),fmix sx (qty,ytq)) else (fmix xs (ytq,qty),fmix sx (ytq,qty)) where sx = reverse xs fmix xs (ytq,qty) = append ytq (zipWith Node xs qyqs) where qyqs = qty:ytq:qyqs append = foldl insert wrapQueue xtq = consQueue xtq [] consQueue xtq xtqs = if isEmpty xtq then xtqs else xtq:xtqs step [] = Nothing step (xtq:xtqs) = Just (x,consQueue ytq (consQueue ztq xtqs)) where (Node x ytq,ztq) = remove xtq
snape/LooplessFunctionalAlgorithms
LooplessMixallForest.hs
apache-2.0
1,502
0
10
378
351
194
157
18
2
module Scenario where import Force data Scenario = Scenario { scenMapName :: String , scenBlueOOB :: Force -- XXX , scenRedOOB :: Force } -------------------------------------------------------------------- voidScenario :: Scenario voidScenario = Scenario "*void*" (voidForce Blue) (voidForce Red) testScenario :: Scenario testScenario = Scenario "NTC1" (Force Blue [ Unit 10 10 "Blue Unit One" Armor Battalion 30 1 , Unit 100 100 "Blue Unit Two" Mech Battalion 20 2]) (Force Red [Unit 300 300 "Red Unit One" Mech Brigade 60 301])
nbrk/ld
library/old/Scenario.hs
bsd-2-clause
565
0
9
113
152
83
69
16
1
-- http://www.codewars.com/kata/545cedaa9943f7fe7b000048 module Pangram where import Data.List import Data.Char isPangram :: String -> Bool isPangram = (==['a'..'z']) . map head . group . sort . map toLower . filter isAlpha
Bodigrim/katas
src/haskell/6-Detect-Pangram.hs
bsd-2-clause
225
0
11
31
67
37
30
5
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Network_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:33 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Classes.Network_h ( QmajorVersion_h(..) , QminorVersion_h(..) , QtoString_h(..) ) where import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.ClassTypes.Network class QmajorVersion_h a b where majorVersion_h :: a -> b -> IO (Int) class QminorVersion_h a b where minorVersion_h :: a -> b -> IO (Int) class QtoString_h a b where toString_h :: a -> b -> IO (String)
uduki/hsQt
Qtc/Classes/Network_h.hs
bsd-2-clause
813
0
10
145
142
82
60
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Language.JavaScript.ParseError -- Based on language-python version by Bernie Pope -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Stability : experimental -- Portability : ghc -- -- Error values for the lexer and parser. ----------------------------------------------------------------------------- module Language.JavaScript.Parser.ParseError ( ParseError (..) ) where --import Language.JavaScript.Parser.Pretty -- import Control.Monad.Error.Class -- Control.Monad.Trans.Except import Language.JavaScript.Parser.Lexer import Language.JavaScript.Parser.SrcLocation (TokenPosn) -- import Language.JavaScript.Parser.Token (Token) data ParseError = UnexpectedToken Token -- ^ An error from the parser. Token found where it should not be. -- Note: tokens contain their own source span. | UnexpectedChar Char TokenPosn -- ^ An error from the lexer. Character found where it should not be. | StrError String -- ^ A generic error containing a string message. No source location. deriving (Eq, {- Ord,-} Show) class Error a where -- | Creates an exception without a message. -- The default implementation is @'strMsg' \"\"@. noMsg :: a -- | Creates an exception with a message. -- The default implementation of @'strMsg' s@ is 'noMsg'. strMsg :: String -> a instance Error ParseError where noMsg = StrError "" strMsg = StrError
Murano/language-javascript
src/Language/JavaScript/Parser/ParseError.hs
bsd-3-clause
1,513
0
7
271
135
89
46
14
0
{-# LANGUAGE OverloadedStrings #-} module Parser.Base ( module Transaction , ParserException(..) , FileType(..) , ParseTarget(..) , mkTransaction ) where import Prelude hiding (length) import Control.Exception import Data.Default import Data.Sequence (length, foldlWithIndex, Seq) import Data.Text (Text) import Transaction import Utils newtype ParserException = ParserException Text deriving Show instance Exception ParserException data FileType = CSV | HTML data ParseTarget = ParseTarget !FileType !Text mkTransaction :: Seq Text -> Transaction mkTransaction xs | length xs /= 16 = throw $ ParserException "Invalid data shape" | otherwise = foldlWithIndex toTransactionField def xs toTransactionField :: Transaction -> Int -> Text -> Transaction toTransactionField t i v = toTransactionField' t i (normalize v) toTransactionField' :: Transaction -> Int -> String -> Transaction toTransactionField' t 1 v = t { action = read v } toTransactionField' t 4 v = t { currency = read v } toTransactionField' t 5 v = t { amount = parseNum v } toTransactionField' t 6 v = t { vpp = parseNum v } toTransactionField' t 7 v = t { coins = parseNum v } toTransactionField' t 8 v = t { tournamentMoney = parseNum v } toTransactionField' t 10 v = t { runningBalance = parseNum v } toTransactionField' t _ _ = t
ostronom/pokerstars-audit
src/Parser/Base.hs
bsd-3-clause
1,323
0
9
232
417
225
192
37
1
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Main where import Util import System.Exit ( exitFailure, exitSuccess ) import Test.HUnit testTakeUntil = "takeUntil" ~: [ takeUntil (> 1) [] ~=? [], takeUntil (> 1) [2] ~=? [2]] testOne = [testTakeUntil] main = do cnt <- runTestTT (test testOne) if errors cnt + failures cnt == 0 then exitSuccess else exitFailure
guillaume-nargeot/hpc-coveralls-testing2
test1/TestOne.hs
bsd-3-clause
451
0
10
98
132
74
58
15
2
-- | -- Module : Text.Search.Whistlepig.IO -- Copyright : (c) Austin Seipp 2012 -- License : BSD3 -- -- Maintainer : mad.one@gmail.com -- Stability : experimental -- Portability : portable -- -- This module provides a mid-level FFI binding to the Whistlepig -- search engine. It is different from the top-level interface -- in that it *returns* errors, and does not throw them. -- module Text.Search.Whistlepig.Direct ( -- * Whistlepig search index -- $whistlepig module Text.Search.Whistlepig.Index , module Text.Search.Whistlepig.Query , module Text.Search.Whistlepig.Entry -- * Error type , Error ) where import Text.Search.Whistlepig.Index import Text.Search.Whistlepig.Query import Text.Search.Whistlepig.Entry import Text.Search.Whistlepig.Util (Error) ------------------------------------------------------------------------------- -- Docs -- $whistlepig -- Whistlepig is a minimalist realtime full-text search index. Its goal is to -- be as small and maintainable as possible, while still remaining useful, -- performant and scalable to large corpora. If you want realtime full-text -- search without the frills, Whistlepig may be for you. --
thoughtpolice/hs-whistlepig
src/Text/Search/Whistlepig/Direct.hs
bsd-3-clause
1,230
0
5
231
94
74
20
10
0
{- | Basic functions for initiating and working with a connection to an X11 server. -} module Graphics.XHB.Connection (Connection ,connect ,connectTo ,displayInfo ,connectionSetup ,mkConnection ,newResource ,pollForEvent ,waitForEvent ,pollForError ,waitForError ,setCrashOnError ,SomeError ,SomeEvent ,getRoot ) where import Data.Word -- MAY import generated type modules (XHB.Gen.*.Types) -- MAY NOT import other generated modules import Control.Concurrent.STM import Control.Concurrent import Control.Monad import System.IO import System.ByteOrder import Foreign.C.String import Data.List (genericLength) import Data.Maybe import Data.Monoid(mempty) import qualified Data.Map as M import Data.ByteString.Lazy(ByteString) import qualified Data.ByteString.Lazy as BS import Data.Binary.Get import Data.Binary.Put import Data.Bits import Graphics.XHB.Gen.Xproto.Types import Graphics.XHB.Gen.Extension import Graphics.XHB.Connection.Types import Graphics.XHB.Connection.Internal import Graphics.XHB.Connection.Open import Graphics.XHB.Shared import Graphics.X11.Xauth -- | Returns the 'Setup' information returned by the server -- during the initiation of the connection. connectionSetup :: Connection -> Setup connectionSetup = conf_setup . conn_conf newResource :: XidLike a => Connection -> IO a newResource c = do xidM <- nextXid c case xidM of Just xid -> return . fromXid $ xid Nothing -> error "resource ids exhausted" -- request more here nextXid :: Connection -> IO (Maybe Xid) nextXid c = atomically $ do let tv = conn_resource_ids c xids <- readTVar tv case xids of [] -> return Nothing (x:xs) -> do writeTVar tv xs return . return $ x pollForEvent :: Connection -> IO (Maybe SomeEvent) pollForEvent c = atomically $ pollTChan $ conn_event_queue c waitForEvent :: Connection -> IO SomeEvent waitForEvent c = atomically $ readTChan $ conn_event_queue c pollForError :: Connection -> IO (Maybe SomeError) pollForError c = atomically $ pollTChan $ conn_error_queue c waitForError :: Connection -> IO SomeError waitForError c = atomically $ readTChan $ conn_error_queue c pollTChan :: TChan a -> STM (Maybe a) pollTChan tc = do empty <- isEmptyTChan tc if empty then return Nothing else Just `liftM` readTChan tc -- | If you don't feel like writing error handlers, but at least want to know that -- one happened for debugging purposes, call this to have execution come to an -- abrupt end if an error is received. setCrashOnError :: Connection -> IO () setCrashOnError c = do forkIO $ do waitForError c error "Received error from server. Crashing." return () -- Any response from the server is first read into -- this type. data GenericReply = GenericReply {grep_response_type :: ResponseType ,grep_error_code :: Word8 ,grep_sequence :: Word16 ,grep_reply_length :: Word32 -- only useful for replies } data ResponseType = ResponseTypeEvent Word8 | ResponseTypeError | ResponseTypeReply instance Deserialize GenericReply where deserialize = do type_flag <- deserialize let rType = case type_flag of 0 -> ResponseTypeError 1 -> ResponseTypeReply _ -> ResponseTypeEvent type_flag code <- deserialize sequence <- deserialize reply_length <- deserialize return $ GenericReply rType code sequence reply_length -- state maintained by the read loop data ReadLoop = ReadLoop {read_error_queue :: TChan SomeError -- write only ,read_event_queue :: TChan SomeEvent -- write only ,read_input_queue :: Handle -- read only ,read_reps :: TChan PendedReply -- read only ,read_config :: ConnectionConfig ,read_extensions :: TVar ExtensionMap } ---- Processing for events/errors -- reverse-lookup infrastructure for extensions. Not pretty or -- maybe not even fast. But it is straight-forward. queryExtMap :: (QueryExtensionReply -> Word8) -> ReadLoop -> Word8 -> IO (Maybe (ExtensionId, Word8)) queryExtMap f r code = do ext_map <- atomically . readTVar $ read_extensions r return $ findFromCode ext_map where findFromCode xmap = foldr go Nothing (M.toList xmap) go (ident, extInfo) old | num <= code = case old of Just (_oldIndent, oldNum) | oldNum > num -> old _ -> Just (ident, num) | otherwise = old where num = f extInfo -- | Returns the extension id and the base event code extensionIdFromEventCode :: ReadLoop -> Word8 -> IO (Maybe (ExtensionId, Word8)) extensionIdFromEventCode = queryExtMap first_event_QueryExtensionReply -- | Returns the extension id and the base error code extensionIdFromErrorCode :: ReadLoop -> Word8 -> IO (Maybe (ExtensionId, Word8)) extensionIdFromErrorCode = queryExtMap first_error_QueryExtensionReply bsToError :: ReadLoop -> ByteString -- ^Raw data -> Word8 -- ^Error code -> IO SomeError bsToError _r chunk code | code < 128 = case deserializeError code of Nothing -> return . toError . UnknownError $ chunk Just getAction -> return $ runGet getAction chunk bsToError r chunk code = extensionIdFromErrorCode r code >>= \errInfo -> case errInfo of Nothing -> return . toError . UnknownError $ chunk Just (extId, baseErr) -> case errorDispatch extId (code - baseErr) of Nothing -> return . toError . UnknownError $ chunk Just getAction -> return $ runGet getAction chunk bsToEvent :: ReadLoop -> ByteString -- ^Raw data -> Word8 -- ^Event code -> IO SomeEvent bsToEvent _r chunk code | code < 64 = case deserializeEvent code of Nothing -> return . toEvent . UnknownEvent $ chunk Just getAction -> return $ runGet getAction chunk bsToEvent r chunk code = extensionIdFromEventCode r code >>= \evInfo -> case evInfo of Nothing -> return . toEvent . UnknownEvent $ chunk Just (extId, baseEv) -> case eventDispatch extId (code - baseEv) of Nothing -> return . toEvent . UnknownEvent $ chunk Just getAction -> return $ runGet getAction chunk deserializeInReadLoop rl = deserialize readBytes :: ReadLoop -> Int -> IO ByteString readBytes rl n = BS.hGet (read_input_queue rl) n -- the read loop slurps bytes off of the handle, and places -- them into the appropriate shared structure. readLoop :: ReadLoop -> IO () readLoop rl = do chunk <- readBytes rl 32 let genRep = flip runGet chunk $ deserialize case grep_response_type genRep of ResponseTypeError -> readLoopError rl genRep chunk ResponseTypeReply -> readLoopReply rl genRep chunk ResponseTypeEvent _ -> readLoopEvent rl genRep chunk readLoop rl -- handle a response to a request readLoopReply :: ReadLoop -> GenericReply -> ByteString -> IO () readLoopReply rl genRep chunk = do -- grab the rest of the response bytes let rlength = grep_reply_length genRep extra <- readBytes rl $ fromIntegral $ 4 * rlength let bytes = chunk `BS.append` extra -- place the response into the pending reply TMVar, or discard it atomically $ do nextPend <- readTChan $ read_reps rl if (pended_sequence nextPend) == (grep_sequence genRep) then putReceipt (pended_reply nextPend) $ Right bytes else unGetTChan (read_reps rl) nextPend -- take the bytes making up the error response, shove it in -- a queue. -- -- If the error corresponds to one of the pending replies, -- place the error into the pending reply TMVar instead. readLoopError rl genRep chunk = do let errorCode = grep_error_code genRep err <- bsToError rl chunk errorCode atomically $ do nextPend <- readTChan $ read_reps rl if (pended_sequence nextPend) == (grep_sequence genRep) then putReceipt (pended_reply nextPend) $ Left err else do unGetTChan (read_reps rl) nextPend writeTChan (read_error_queue rl) err -- take the bytes making up the event response, shove it in -- a queue readLoopEvent rl genRep chunk = do ev <- bsToEvent rl chunk eventCode atomically $ writeTChan (read_event_queue rl) ev where eventCode = case grep_response_type genRep of ResponseTypeEvent w -> w .&. 127 -- | Connect to the the default display. connect :: IO (Maybe Connection) connect = connectTo "" -- | Connect to the display specified. -- The string must be of the format used in the -- DISPLAY environment variable. connectTo :: String -> IO (Maybe Connection) connectTo display = do (h, xau, dispName) <- open display hSetBuffering h NoBuffering mkConnection h xau dispName -- | Returns the information about what we originally tried to -- connect to. displayInfo :: Connection -> DispName displayInfo = conn_dispInfo -- Handshake with the server -- parse result of handshake -- launch the thread which holds the handle for reading mkConnection :: Handle -> Maybe Xauth -> DispName -> IO (Maybe Connection) mkConnection hnd auth dispInfo = do errorQueue <- newTChanIO eventQueue <- newTChanIO replies <- newTChanIO sequence <- initialSequence extensions <- newTVarIO mempty wrappedHandle <- newMVar hnd confM <- handshake hnd auth if isNothing confM then return Nothing else do let Just conf = confM rIds <- newTVarIO $ resourceIds conf let rlData = ReadLoop errorQueue eventQueue hnd replies conf extensions readTid <- forkIO $ readLoop rlData return $ Just $ Connection errorQueue eventQueue readTid wrappedHandle replies conf sequence rIds extensions dispInfo resourceIds :: ConnectionConfig -> [Xid] resourceIds cc = resourceIdsFromSetup $ conf_setup cc resourceIdsFromSetup :: Setup -> [Xid] resourceIdsFromSetup s = let base = resource_id_base_Setup s mask = resource_id_mask_Setup s max = mask step = mask .&. (-mask) in map MkXid $ map (.|. base) [0,step .. max] -- first 8 bytes of the response from the setup request data GenericSetup = GenericSetup {setup_status :: SetupStatus ,setup_length :: Word16 } deriving Show instance Deserialize GenericSetup where deserialize = do status <- deserialize skip 5 length <- deserialize return $ GenericSetup status length data SetupStatus = SetupFailed | SetupAuthenticate | SetupSuccess deriving Show instance Deserialize SetupStatus where deserialize = wordToStatus `liftM` deserialize where wordToStatus :: Word8 -> SetupStatus wordToStatus 0 = SetupFailed wordToStatus 1 = SetupSuccess wordToStatus 2 = SetupAuthenticate wordToStatus n = error $ "Unkonwn setup status flag: " ++ show n -- send the setup request to the server, -- receive the setup response handshake :: Handle -> Maybe Xauth -> IO (Maybe ConnectionConfig) handshake hnd auth = do -- send setup request let requestChunk = runPut $ serialize $ setupRequest auth BS.hPut hnd $ requestChunk -- grab an 8-byte chunk to get the response type and size firstChunk <- BS.hGet hnd 8 let genSetup = runGet deserialize firstChunk -- grab the rest of the setup response secondChunk <- BS.hGet hnd $ fromIntegral $ (4 *) $ setup_length genSetup let setupBytes = firstChunk `BS.append` secondChunk -- handle the response type case setup_status genSetup of SetupFailed -> do let failed = runGet deserialize setupBytes failMessage = map castCCharToChar (reason_SetupFailed failed) hPutStrLn stderr failMessage return Nothing SetupAuthenticate -> do let auth = runGet deserialize setupBytes authMessage = map castCCharToChar (reason_SetupAuthenticate auth) hPutStrLn stderr authMessage return Nothing SetupSuccess -> do let setup = runGet deserialize setupBytes return . return $ ConnectionConfig setup padBS n = BS.replicate n 0 initialSequence :: IO (TVar SequenceId) initialSequence = newTVarIO 1 setupRequest :: Maybe Xauth -> SetupRequest setupRequest auth = MkSetupRequest (fromIntegral $ byteOrderToNum byteOrder) 11 -- major version 0 -- minor version anamelen -- auth name length adatalen -- auth data length -- TODO this manual padding is a horrible hack, it should be -- done by the serialization instance (aname ++ replicate (requiredPadding anamelen) 0) -- auth name (adata ++ replicate (requiredPadding adatalen) 0) -- auth data where (anamelen, aname, adatalen, adata) = case auth of Nothing -> (0, [], 0, []) Just (Xauth n d) -> (genericLength n, n, genericLength d, d) -- | I plan on deprecating this one soon, but until I put together -- some sort of 'utils' package, it will live here. -- -- Given a connection, this function returns the root window of the -- first screen. -- -- If your display string specifies a screen other than the first, -- this probably doesnt do what you want. getRoot :: Connection -> WINDOW getRoot = root_SCREEN . head . roots_Setup . conf_setup . conn_conf
aslatter/xhb
Graphics/XHB/Connection.hs
bsd-3-clause
13,698
0
17
3,504
3,194
1,623
1,571
-1
-1
module HaskellRoguelike.Action where data Direction = Here | North | East | South | West | NorthEast | NorthWest | SouthEast | SouthWest | Up | UpNorth | UpEast | UpSouth | UpWest | UpNorthEast | UpNorthWest | UpSouthEast | UpSouthWest | Down | DownNorth | DownEast | DownSouth | DownWest | DownNorthEast | DownNorthWest | DownSouthEast | DownSouthWest | Next | Prev deriving (Eq, Show, Enum, Bounded) toOffset :: Direction -> (Int,Int,Int,Int) toOffset dir = case dir of Here -> ( 0, 0, 0, 0) North -> ( 0,-1, 0, 0) East -> ( 1, 0, 0, 0) South -> ( 0, 1, 0, 0) West -> (-1, 0, 0, 0) NorthEast -> ( 1,-1, 0, 0) NorthWest -> (-1,-1, 0, 0) SouthEast -> ( 1, 1, 0, 0) SouthWest -> (-1, 1, 0, 0) Up -> ( 0, 0, 1, 0) UpNorth -> ( 0,-1, 1, 0) UpEast -> ( 1, 0, 1, 0) UpSouth -> ( 0, 1, 1, 0) UpWest -> (-1, 0, 1, 0) UpNorthEast -> ( 1,-1, 1, 0) UpNorthWest -> (-1,-1, 1, 0) UpSouthEast -> ( 1, 1, 1, 0) UpSouthWest -> (-1, 1, 1, 0) Down -> ( 0, 0,-1, 0) DownNorth -> ( 0,-1,-1, 0) DownEast -> ( 1, 0,-1, 0) DownSouth -> ( 0, 1,-1, 0) DownWest -> (-1, 0,-1, 0) DownNorthEast -> ( 1,-1,-1, 0) DownNorthWest -> (-1,-1,-1, 0) DownSouthEast -> ( 1, 1,-1, 0) DownSouthWest -> (-1, 1,-1, 0) Next -> ( 0, 0, 0, 1) Prev -> ( 0, 0, 0,-1) data Action = None | PlayerAction | Move Direction deriving (Eq, Show)
jameseb7/haskell-roguelike
HaskellRoguelike/Action.hs
bsd-3-clause
2,191
0
9
1,164
753
455
298
44
29
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} -- | This module defines a parser for @GraphQL@ request documents. module Data.GraphQL.Parser where import Prelude hiding (takeWhile) import Control.Applicative ((<|>), Alternative, empty, many, optional) import Control.Monad (when) import Data.Char (isDigit, isSpace) import Data.Foldable (traverse_) import Data.Monoid ((<>)) import Data.List.NonEmpty (NonEmpty((:|))) import Data.Scientific (floatingOrInteger, scientific, toBoundedInteger) import Data.Text (Text, append) import Data.Attoparsec.Combinator (lookAhead) import Data.Attoparsec.Text ( Parser , (<?>) , anyChar , endOfLine , inClass , many1 , manyTill , option , peekChar , takeWhile , takeWhile1 ) import qualified Data.Attoparsec.Text as Attoparsec (scientific) import Data.GraphQL.AST -- * Name name :: Parser Name name = tok $ append <$> takeWhile1 isA_z <*> takeWhile ((||) <$> isDigit <*> isA_z) where -- `isAlpha` handles many more Unicode Chars isA_z = inClass $ '_' : ['A'..'Z'] <> ['a'..'z'] -- * Document document :: Parser Document document = whiteSpace *> manyNE definition definition :: Parser Definition definition = DefinitionOperation <$> operationDefinition <|> DefinitionFragment <$> fragmentDefinition <?> "definition error!" operationDefinition :: Parser OperationDefinition operationDefinition = OperationSelectionSet <$> selectionSet <|> OperationDefinition <$> operationType <*> optional name <*> opt variableDefinitions <*> opt directives <*> selectionSet <?> "operationDefinition error" operationType :: Parser OperationType operationType = Query <$ tok "query" <|> Mutation <$ tok "mutation" <?> "operationType error" -- * SelectionSet selectionSet :: Parser SelectionSet selectionSet = braces $ manyNE selection selectionSetOpt :: Parser SelectionSetOpt selectionSetOpt = braces $ many1 selection selection :: Parser Selection selection = SelectionField <$> field <|> SelectionFragmentSpread <$> fragmentSpread <|> SelectionInlineFragment <$> inlineFragment <?> "selection error!" -- * Field field :: Parser Field field = Field <$> optional alias <*> name <*> opt arguments <*> opt directives <*> opt selectionSetOpt alias :: Parser Alias alias = name <* tok ":" -- * Arguments arguments :: Parser Arguments arguments = parens $ many1 argument argument :: Parser Argument argument = Argument <$> name <* tok ":" <*> value -- * Fragments fragmentSpread :: Parser FragmentSpread fragmentSpread = FragmentSpread <$ tok "..." <*> fragmentName <*> opt directives inlineFragment :: Parser InlineFragment inlineFragment = InlineFragment <$ tok "..." <*> optional typeCondition <*> opt directives <*> selectionSet fragmentDefinition :: Parser FragmentDefinition fragmentDefinition = FragmentDefinition <$ tok "fragment" <*> name <*> typeCondition <*> opt directives <*> selectionSet fragmentName :: Parser FragmentName fragmentName = but (tok "on") *> name typeCondition :: Parser TypeCondition typeCondition = tok "on" *> name -- * Input Values value :: Parser Value value = ValueVariable <$> variable <|> tok floatOrInt32Value <|> ValueBoolean <$> booleanValue <|> ValueNull <$ tok "null" <|> ValueString <$> stringValue <|> ValueEnum <$> enumValue <|> ValueList <$> listValue <|> ValueObject <$> objectValue <?> "value error!" where booleanValue :: Parser Bool booleanValue = True <$ tok "true" <|> False <$ tok "false" floatOrInt32Value :: Parser Value floatOrInt32Value = Attoparsec.scientific >>= either (pure . ValueFloat) (maybe (fail "Integer value is out of range.") (pure . ValueInt) . toBoundedInteger . (`scientific` 0)) . floatingOrInteger -- TODO: Escape characters. Look at `jsstring_` in aeson package. stringValue :: Parser Text stringValue = quotes (takeWhile (/= '"')) enumValue :: Parser Name enumValue = but (tok "true") *> but (tok "false") *> but (tok "null") *> name listValue :: Parser [Value] listValue = brackets $ many1 value objectValue :: Parser [ObjectField] objectValue = braces $ many1 objectField objectField :: Parser ObjectField objectField = ObjectField <$> name <* tok ":" <*> value -- * Variables variableDefinitions :: Parser VariableDefinitions variableDefinitions = parens $ many1 variableDefinition variableDefinition :: Parser VariableDefinition variableDefinition = VariableDefinition <$> variable <* tok ":" <*> type_ <*> optional defaultValue variable :: Parser Variable variable = tok "$" *> name defaultValue :: Parser DefaultValue defaultValue = tok "=" *> value -- * Input Types type_ :: Parser Type type_ = TypeNamed <$> name <* but "!" <|> TypeList <$> brackets type_ <|> TypeNonNull <$> nonNullType <?> "type_ error!" nonNullType :: Parser NonNullType nonNullType = NonNullTypeNamed <$> name <* tok "!" <|> NonNullTypeList <$> brackets type_ <* tok "!" <?> "nonNullType error!" -- * Directives directives :: Parser Directives directives = many1 directive directive :: Parser Directive directive = Directive <$ tok "@" <*> name <*> opt arguments -- * Internal tok :: Parser a -> Parser a tok p = p <* whiteSpace parens :: Parser a -> Parser a parens = between "(" ")" braces :: Parser a -> Parser a braces = between "{" "}" quotes :: Parser a -> Parser a quotes = between "\"" "\"" brackets :: Parser a -> Parser a brackets = between "[" "]" between :: Parser Text -> Parser Text -> Parser a -> Parser a between open close p = tok open *> p <* tok close opt :: Monoid a => Parser a -> Parser a opt = option mempty -- Hack to reverse parser success but :: Parser a -> Parser () but pn = False <$ lookAhead pn <|> pure True >>= \case False -> empty True -> pure () manyNE :: Alternative f => f a -> f (NonEmpty a) manyNE p = (:|) <$> p <*> many p whiteSpace :: Parser () whiteSpace = peekChar >>= traverse_ (\c -> if isSpace c || c == ',' then anyChar *> whiteSpace else when (c == '#') $ manyTill anyChar endOfLine *> whiteSpace)
jdnavarro/graphql-haskell
Data/GraphQL/Parser.hs
bsd-3-clause
6,947
0
19
1,980
1,745
905
840
173
2
module HsVerilog ( module HsVerilog.Type , module HsVerilog.Verilog , module HsVerilog.Simulation , module HsVerilog.Library ) where import HsVerilog.Type import HsVerilog.Verilog import HsVerilog.Simulation import HsVerilog.Library
junjihashimoto/hsverilog
src/HsVerilog.hs
bsd-3-clause
237
0
5
28
50
32
18
9
0
{-# LANGUAGE OverloadedStrings #-} module GithubWebhook.Constants ( githubEvent ) where import qualified Data.Text.Lazy as TL type Error = String githubEvent :: TL.Text githubEvent = "X-GitHub-Event"
bgwines/hueue
src/GithubWebhook/Constants.hs
bsd-3-clause
204
0
5
29
39
26
13
7
1
{-# LANGUAGE OverloadedStrings #-} module Web.View.Cake (render) where import qualified Text.Blaze.Html4.Strict as H import Text.Blaze.Html.Renderer.Utf8 import Data.Monoid import qualified Blaze.ByteString.Builder import Control.Monad import qualified Model.Cake render :: [Model.Cake.Cake] -> Blaze.ByteString.Builder.Builder render cakeList = renderHtmlBuilder $ H.docTypeHtml $ do H.head $ do H.title "Haskell Cake Store Cake List" H.body $ do H.h1 "Cake List" _ <- forM cakeList (\cake -> H.p (mappend "Cake name: " $ H.toHtml $ Model.Cake.name cake)) return ()
stevechy/HaskellCakeStore
Web/View/Cake.hs
bsd-3-clause
601
0
19
105
180
99
81
17
1
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-} module Web.HaskellCakeStoreWeb ( app, buildApp ) where import Network.Wai as Wai import qualified Web.Handler.HomePage as HomePage import qualified Web.Handler.CakesPage import Web.WebHandler as WebHandler import qualified Configuration.Types import qualified Data.DataHandler import qualified Service.ServiceHandler import Control.Monad.Trans.Class (lift) import qualified Web.WebHelper import Data.Dynamic import System.Log.Logger data Logger = Logger deriving Typeable logger = "Web.HaskellCakeStoreWeb."++ (show $ typeOf Logger) buildApp :: Configuration.Types.Configuration -> IO ( Wai.Application ) buildApp configuration = do dataConfiguration <- Data.DataHandler.setupDataMonad configuration serviceConfiguration <- Service.ServiceHandler.setupServiceMonad configuration dataConfiguration webConfiguration <- WebHandler.setupHandlerMonad configuration serviceConfiguration return $ app webConfiguration app :: WebHandler.WebConfiguration -> Wai.Application app webConfiguration request = case pathInfo request of [] -> WebHandler.handleMonadWithConfiguration webConfiguration HomePage.handleMonad "cakes" : rest -> WebHandler.handleMonadWithConfiguration webConfiguration $ Web.Handler.CakesPage.route rest path@_ -> do lift $ warningM logger $ "Not found " ++ (show path) return $ Web.WebHelper.notFoundValue $ Web.WebHelper.toBuilder ["Not Found"]
stevechy/HaskellCakeStore
Web/HaskellCakeStoreWeb.hs
bsd-3-clause
1,449
0
13
174
330
181
149
29
3
module Arhelk.Russian.Lemma.Data.Common where import TextShow -- | Род. Grammatical gender of word data GrammarGender = GrammarMale -- ^ Мужской | GrammarFemale -- ^ Женский | GrammarNeuter -- ^ Средний deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow GrammarGender where showb v = case v of GrammarMale -> "муж. род" GrammarFemale -> "жен. род" GrammarNeuter -> "ср. род" -- | Множественное или единственное число data GrammarQuantity = GrammarSingle -- ^ Единственное | GrammarMultiple -- ^ Множественное deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow GrammarQuantity where showb v = case v of GrammarSingle -> "ед. число" GrammarMultiple -> "мн. число" -- | Лицо data GrammarPerson = FirstPerson -- ^ Первое лицо | SecondPerson -- ^ Второе лицо | ThirdPerson -- ^ Третье лицо deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow GrammarPerson where showb v = case v of FirstPerson -> "1 лицо" SecondPerson -> "2 лицо" ThirdPerson -> "3 лицо"
Teaspot-Studio/arhelk-russian
src/Arhelk/Russian/Lemma/Data/Common.hs
bsd-3-clause
1,209
0
8
230
236
132
104
30
0
{-# LANGUAGE MultiParamTypeClasses #-} {- - The Pee Shell, an interactive environment for evaluating pure untyped pee terms. - Copyright (C) 2005-2007, Robert Dockins - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} module Language.PiEtaEpsilon.Interactive.Shell where import Control.Monad.Trans import System.IO import Data.List (isPrefixOf) import Language.PiEtaEpsilon.Evaluator import Language.PiEtaEpsilon.Syntax hiding (Left, Right) import Language.PiEtaEpsilon.Parser.Term import Language.PiEtaEpsilon.Interactive.Version import qualified Data.Map as Map import Text.ParserCombinators.Parsec (runParser) import Language.PiEtaEpsilon.Pretty.REPL import Language.PiEtaEpsilon.Pretty.Class import System.Console.Shell import System.Console.Shell.ShellMonad --import System.Console.Shell.Backend.Readline import System.Console.Shell.Backend.Haskeline import Language.PiEtaEpsilon.Interactive.StatementParser import Language.LBNF.Runtime import Data.Default defaultBackend = haskelineBackend type Bindings = Map.Map String Term ------------------------------------------------------- -- Define types to allow completion of let-bound names completeLetBindings :: PeeShellState -> String -> IO [String] completeLetBindings st prefix = return . filter (prefix `isPrefixOf`) . Map.keys . letBindings $ st data LetBinding = LetBinding instance Completion LetBinding PeeShellState where complete _ = completeLetBindings completableLabel _ = "<name>" ---------------------------------------------------------- -- Define the shell state -- | Keeps track of all the state that is needed for the -- operation of the pee shell. data PeeShellState = PeeShellState { letBindings :: Map.Map String Term -- ^ All \"let\" bindings currently in scope , forwards :: Bool -- ^ Which direction should we evaluate , histFile :: Maybe String -- ^ A file for command history } deriving(Show, Eq) -- | Default settings for all elements of shell state. initialShellState = PeeShellState { letBindings = Map.empty , forwards = True , histFile = Nothing } ----------------------------------------------------------------- -- Main entry point to the shell -- | Run an interactive shell starting with the -- given shell state and returning the final, -- possibly modified, state. peeShell :: PeeShellState -> IO PeeShellState peeShell init = do let desc = (mkShellDescription commands evaluate) { defaultCompletions = Just completeLetBindings , historyFile = histFile init , greetingText = Just (versionInfo ++ shellMessage) , secondaryPrompt = Just $ \_ -> return "] " } runShell desc defaultBackend init ----------------------------------------------------------------- -- read definitions from a file -- A few things to note. Since there is no subsitution, I completely ignore -- the bindings, because we don't perform any subsitution readDefinitionFile :: Bindings -> String -> IO (Bindings) readDefinitionFile = error "readDefinitionFile" --readDefinitionFile _ file = do -- str <- openFile file ReadMode >>= hGetContents -- --TODO add back the comment stripping -- case parseTerm str of -- Bad err -> fail (show err) -- Ok b' -> return b' ---------------------------------------------------------------- -- Definition of all the shell commands commands :: [ShellCommand PeeShellState] commands = [ exitCommand "quit" , exitCommand "exit" , helpCommand "help" , toggle "reverse" "Toggle the direction mode" forwards (\x st -> st { forwards = x }) , cmd "showall" showBindings "Show all let bindings" , cmd "show" showBinding "Show a let binding" , cmd "load" loadDefFile "Load definitions from a file" , cmd "clear" clearBindings "Clear all let bindings" , cmd "nowarranty" (shellPutInfo noWarranty) "Print the warranty disclaimer" , cmd "gpl" (shellPutInfo gpl) "Print the GNU GPLv2, under which this software is licensed" , cmd "version" (shellPutInfo versionInfo) "Print version info" ] showBinding :: Completable LetBinding -> Sh PeeShellState () showBinding (Completable name) = do st <- getShellSt case Map.lookup name (letBindings st) of Nothing -> shellPutErrLn $ concat ["'",name,"' not bound"] Just t -> shellPutInfoLn $ concat [name," = ", ppr t] showBindings :: Sh PeeShellState () showBindings = do st <- getShellSt shellPutStrLn $ Map.foldWithKey (\name t x -> concat [name," = ", ppr t,"\n",x]) "" (letBindings st) clearBindings :: Sh PeeShellState () clearBindings = modifyShellSt (\st -> st{ letBindings = Map.empty }) loadDefFile :: File -> Sh PeeShellState () loadDefFile = error "loadDefFile" --loadDefFile (File path) = do -- st <- getShellSt -- newBinds <- liftIO $ readDefinitionFile path -- putShellSt st{ letBindings = newBinds } ---------------------------------------------------------------- -- Normal statement evaluation evaluate :: String -> Sh PeeShellState () evaluate str = do case reverse str of '@':_ -> shellSpecial (ShellContinueLine (init str)) _ -> do st <- getShellSt case pStatement str of Left err -> shellPutErrLn ("parse error " ++ show err) Right stmt -> case stmt of Stmt_eval expr value -> evalExpr expr value Stmt_let nm expr -> modifyShellSt (\st -> st{ letBindings = Map.insert nm expr (letBindings st) }) Stmt_empty -> return () evalExpr :: Term -> UValue -> Sh PeeShellState () evalExpr t v = getShellSt >>= \st -> eval t v st where eval t' v' st' = do let z = topLevelWithState (shellStateToMachineState st') t' v' shellPutStrLn $ ppr z shellStateToMachineState :: PeeShellState -> MachineState shellStateToMachineState (PeeShellState _ forwards _) = def {forward = forwards }
dmwit/pi-eta-epsilon
src/Language/PiEtaEpsilon/Interactive/Shell.hs
bsd-3-clause
6,740
0
25
1,445
1,201
655
546
104
5
{-# LANGUAGE PatternGuards #-} module Idris.ElabTerm where import Idris.AbsSyntax import Idris.DSL import Idris.Delaborate import Idris.Error import Idris.ProofSearch import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Typecheck (check) import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.State.Strict import Data.List import qualified Data.Map as M import Data.Maybe (mapMaybe) import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace -- Data to pass to recursively called elaborators; e.g. for where blocks, -- paramaterised declarations, etc. data ElabInfo = EInfo { params :: [(Name, PTerm)], inblock :: Ctxt [Name], -- names in the block, and their params liftname :: Name -> Name, namespace :: Maybe [String] } toplevel = EInfo [] emptyContext id Nothing -- Using the elaborator, convert a term in raw syntax to a fully -- elaborated, typechecked term. -- -- If building a pattern match, we convert undeclared variables from -- holes to pattern bindings. -- Also find deferred names in the term and their types build :: IState -> ElabInfo -> Bool -> FnOpts -> Name -> PTerm -> ElabD (Term, [(Name, (Int, Maybe Name, Type))], [PDecl]) build ist info pattern opts fn tm = do elab ist info pattern opts fn tm ivs <- get_instances hs <- get_holes ptm <- get_term -- Resolve remaining type classes. Two passes - first to get the -- default Num instances, second to clean up the rest when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal try (resolveTC 7 g fn ist) (movelast n)) ivs ivs <- get_instances hs <- get_holes when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal resolveTC 7 g fn ist) ivs tm <- get_term ctxt <- get_context when (not pattern) $ do matchProblems; unifyProblems probs <- get_probs case probs of [] -> return () ((_,_,_,e):es) -> lift (Error e) is <- getAux tt <- get_term let (tm, ds) = runState (collectDeferred (Just fn) tt) [] log <- getLog if (log /= "") then trace log $ return (tm, ds, is) else return (tm, ds, is) -- Build a term autogenerated as a typeclass method definition -- (Separate, so we don't go overboard resolving things that we don't -- know about yet on the LHS of a pattern def) buildTC :: IState -> ElabInfo -> Bool -> FnOpts -> Name -> PTerm -> ElabD (Term, [(Name, (Int, Maybe Name, Type))], [PDecl]) buildTC ist info pattern opts fn tm = do -- set name supply to begin after highest index in tm let ns = allNamesIn tm initNextNameFrom ns elab ist info pattern opts fn tm probs <- get_probs tm <- get_term case probs of [] -> return () ((_,_,_,e):es) -> lift (Error e) is <- getAux tt <- get_term let (tm, ds) = runState (collectDeferred (Just fn) tt) [] log <- getLog if (log /= "") then trace log $ return (tm, ds, is) else return (tm, ds, is) -- Returns the set of declarations we need to add to complete the definition -- (most likely case blocks to elaborate) elab :: IState -> ElabInfo -> Bool -> FnOpts -> Name -> PTerm -> ElabD () elab ist info pattern opts fn tm = do let loglvl = opt_logLevel (idris_options ist) when (loglvl > 5) $ unifyLog True compute -- expand type synonyms, etc elabE (False, False, False) tm -- (in argument, guarded, in type) end_unify when pattern -- convert remaining holes to pattern vars (do update_term orderPats mkPat) where tcgen = Dictionary `elem` opts reflect = Reflection `elem` opts isph arg = case getTm arg of Placeholder -> (True, priority arg) _ -> (False, priority arg) toElab ina arg = case getTm arg of Placeholder -> Nothing v -> Just (priority arg, elabE ina v) toElab' ina arg = case getTm arg of Placeholder -> Nothing v -> Just (elabE ina v) mkPat = do hs <- get_holes tm <- get_term case hs of (h: hs) -> do patvar h; mkPat [] -> return () elabE :: (Bool, Bool, Bool) -> PTerm -> ElabD () elabE ina t = {- do g <- goal tm <- get_term trace ("Elaborating " ++ show t ++ " : " ++ show g ++ "\n\tin " ++ show tm) $ -} do t' <- insertCoerce ina t g <- goal tm <- get_term ps <- get_probs hs <- get_holes -- trace ("Elaborating " ++ show t' ++ " in " ++ show g -- -- ++ "\n" ++ show tm -- ++ "\nholes " ++ show hs -- ++ "\nproblems " ++ show ps -- ++ "\n-----------\n") $ -- trace ("ELAB " ++ show t') $ elab' ina t' local f = do e <- get_env return (f `elem` map fst e) -- | Is a constant a type? constType :: Const -> Bool constType (AType _) = True constType StrType = True constType PtrType = True constType VoidType = True constType _ = False elab' :: (Bool, Bool, Bool) -- ^ (in an argument, guarded, in a type) -> PTerm -- ^ The term to elaborate -> ElabD () elab' ina (PNoImplicits t) = elab' ina t -- skip elabE step elab' ina PType = do apply RType []; solve elab' (_,_,inty) (PConstant c) | constType c && pattern && not reflect && not inty = lift $ tfail (Msg "Typecase is not allowed") elab' ina (PConstant c) = do apply (RConstant c) []; solve elab' ina (PQuote r) = do fill r; solve elab' ina (PTrue fc) = try (elab' ina (PRef fc unitCon)) (elab' ina (PRef fc unitTy)) elab' ina (PFalse fc) = elab' ina (PRef fc falseTy) elab' ina (PResolveTC (FC "HACK" _ _)) -- for chasing parent classes = do g <- goal; resolveTC 5 g fn ist elab' ina (PResolveTC fc) | True = do c <- getNameFrom (sMN 0 "class") instanceArg c | otherwise = do g <- goal try (resolveTC 2 g fn ist) (do c <- getNameFrom (sMN 0 "class") instanceArg c) elab' ina (PRefl fc t) = elab' ina (PApp fc (PRef fc eqCon) [pimp (sMN 0 "A") Placeholder True, pimp (sMN 0 "x") t False]) elab' ina (PEq fc l r) = elab' ina (PApp fc (PRef fc eqTy) [pimp (sMN 0 "A") Placeholder True, pimp (sMN 0 "B") Placeholder False, pexp l, pexp r]) elab' ina@(_, a, inty) (PPair fc l r) = do hnf_compute g <- goal case g of TType _ -> elabE (True, a,inty) (PApp fc (PRef fc pairTy) [pexp l,pexp r]) _ -> elabE (True, a, inty) (PApp fc (PRef fc pairCon) [pimp (sMN 0 "A") Placeholder True, pimp (sMN 0 "B") Placeholder True, pexp l, pexp r]) elab' ina (PDPair fc l@(PRef _ n) t r) = case t of Placeholder -> do hnf_compute g <- goal case g of TType _ -> asType _ -> asValue _ -> asType where asType = elab' ina (PApp fc (PRef fc sigmaTy) [pexp t, pexp (PLam n Placeholder r)]) asValue = elab' ina (PApp fc (PRef fc existsCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina (PDPair fc l t r) = elab' ina (PApp fc (PRef fc existsCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina (PAlternative True as) = do hnf_compute ty <- goal ctxt <- get_context let (tc, _) = unApply ty let as' = pruneByType tc ctxt as tryAll (zip (map (elab' ina) as') (map showHd as')) where showHd (PApp _ (PRef _ n) _) = show n showHd (PRef _ n) = show n showHd (PApp _ h _) = show h showHd x = show x elab' ina (PAlternative False as) = trySeq as where -- if none work, take the error from the first trySeq (x : xs) = let e1 = elab' ina x in try' e1 (trySeq' e1 xs) True trySeq' deferr [] = proofFail deferr trySeq' deferr (x : xs) = try' (elab' ina x) (trySeq' deferr xs) True elab' ina (PPatvar fc n) | pattern = patvar n elab' (_, _, inty) (PRef fc f) | isTConName f (tt_ctxt ist) && pattern && not reflect && not inty = lift $ tfail (Msg "Typecase is not allowed") elab' (ina, guarded, inty) (PRef fc n) | pattern && not (inparamBlock n) = do ctxt <- get_context let defined = case lookupTy n ctxt of [] -> False _ -> True -- this is to stop us resolve type classes recursively -- trace (show (n, guarded)) $ if (tcname n && ina) then erun fc $ patvar n else if (defined && not guarded) then do apply (Var n) []; solve else try (do apply (Var n) []; solve) (patvar n) where inparamBlock n = case lookupCtxtName n (inblock info) of [] -> False _ -> True elab' ina f@(PInferRef fc n) = elab' ina (PApp fc f []) elab' ina (PRef fc n) = erun fc $ do apply (Var n) []; solve elab' ina@(_, a, inty) (PLam n Placeholder sc) = do -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n attack; intro (Just n); -- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm) elabE (True, a, inty) sc; solve elab' ina@(_, a, inty) (PLam n ty sc) = do tyn <- getNameFrom (sMN 0 "lamty") -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n claim tyn RType explicit tyn attack ptm <- get_term hs <- get_holes introTy (Var tyn) (Just n) focus tyn elabE (True, a, True) ty elabE (True, a, inty) sc solve elab' ina@(_, a, _) (PPi _ n Placeholder sc) = do attack; arg n (sMN 0 "ty"); elabE (True, a, True) sc; solve elab' ina@(_, a, _) (PPi _ n ty sc) = do attack; tyn <- getNameFrom (sMN 0 "ty") claim tyn RType n' <- case n of MN _ _ -> unique_hole n _ -> return n forall n' (Var tyn) focus tyn elabE (True, a, True) ty elabE (True, a, True) sc solve elab' ina@(_, a, inty) (PLet n ty val sc) = do attack; tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) explicit valn letbind n (Var tyn) (Var valn) case ty of Placeholder -> return () _ -> do focus tyn explicit tyn elabE (True, a, True) ty focus valn elabE (True, a, True) val env <- get_env elabE (True, a, inty) sc -- HACK: If the name leaks into its type, it may leak out of -- scope outside, so substitute in the outer scope. expandLet n (case lookup n env of Just (Let t v) -> v) solve elab' ina@(_, a, inty) (PGoal fc r n sc) = do rty <- goal attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letbind n (Var tyn) (Var valn) focus valn elabE (True, a, True) (PApp fc r [pexp (delab ist rty)]) env <- get_env computeLet n elabE (True, a, inty) sc solve -- elab' ina (PLet n Placeholder -- (PApp fc r [pexp (delab ist rty)]) sc) elab' ina tm@(PApp fc (PInferRef _ f) args) = do rty <- goal ds <- get_deferred ctxt <- get_context -- make a function type a -> b -> c -> ... -> rty for the -- new function name env <- get_env argTys <- claimArgTys env args fn <- getNameFrom (sMN 0 "inf_fn") let fty = fnTy argTys rty -- trace (show (ptm, map fst argTys)) $ focus fn -- build and defer the function application attack; deferType (mkN f) fty (map fst argTys); solve -- elaborate the arguments, to unify their types. They all have to -- be explicit. mapM_ elabIArg (zip argTys args) where claimArgTys env [] = return [] claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg) = do nty <- get_type (Var n) ans <- claimArgTys env xs return ((n, (False, forget nty)) : ans) claimArgTys env (_ : xs) = do an <- getNameFrom (sMN 0 "inf_argTy") aval <- getNameFrom (sMN 0 "inf_arg") claim an RType claim aval (Var an) ans <- claimArgTys env xs return ((aval, (True, (Var an))) : ans) fnTy [] ret = forget ret fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi xt) (fnTy xs ret) localVar env (PRef _ x) = case lookup x env of Just _ -> Just x _ -> Nothing localVar env _ = Nothing elabIArg ((n, (True, ty)), def) = do focus n; elabE ina (getTm def) elabIArg _ = return () -- already done, just a name mkN n@(NS _ _) = n mkN n@(SN _) = n mkN n = case namespace info of Just xs@(_:_) -> sNS n xs _ -> n elab' ina (PMatchApp fc fn) = do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of [(n, args)] -> return (n, map (const True) args) _ -> lift $ tfail (NoSuchVariable fn) ns <- match_apply (Var fn') (map (\x -> (x,0)) imps) solve elab' (_, _, inty) (PApp fc (PRef _ f) args') | isTConName f (tt_ctxt ist) && pattern && not reflect && not inty = lift $ tfail (Msg "Typecase is not allowed") -- if f is local, just do a simple_app elab' (ina, g, inty) tm@(PApp fc (PRef _ f) args) = do env <- get_env if (f `elem` map fst env && length args == 1) then -- simple app, as below do simple_app (elabE (ina, g, inty) (PRef fc f)) (elabE (True, g, inty) (getTm (head args))) (show tm) solve else do ivs <- get_instances ps <- get_probs -- HACK: we shouldn't resolve type classes if we're defining an instance -- function or default definition. let isinf = f == inferCon || tcname f -- if f is a type class, we need to know its arguments so that -- we can unify with them case lookupCtxt f (idris_classes ist) of [] -> return () _ -> mapM_ setInjective (map getTm args) ctxt <- get_context let guarded = isConName f ctxt -- trace ("args is " ++ show args) $ return () ns <- apply (Var f) (map isph args) -- trace ("ns is " ++ show ns) $ return () -- Sort so that the implicit tactics and alternatives go last let (ns', eargs) = unzip $ sortBy cmpArg (zip ns args) elabArgs ist (ina || not isinf, guarded, inty) [] fc False f ns' (map (\x -> (lazyarg x, getTm x)) eargs) solve ivs' <- get_instances -- Attempt to resolve any type classes which have 'complete' types, -- i.e. no holes in them when (not pattern || (ina && not tcgen && not guarded)) $ mapM_ (\n -> do focus n g <- goal env <- get_env hs <- get_holes if all (\n -> not (n `elem` hs)) (freeNames g) -- let insts = filter tcname $ map fst (ctxtAlist (tt_ctxt ist)) then try (resolveTC 7 g fn ist) (movelast n) else movelast n) (ivs' \\ ivs) where tcArg (n, PConstraint _ _ Placeholder _) = True tcArg _ = False -- normal < tactic < default tactic cmpArg (_, x) (_, y) = compare (priority x + alt x) (priority y + alt y) where alt t = case getTm t of PAlternative False _ -> 5 _ -> 0 tacTm (PTactics _) = True tacTm (PProof _) = True tacTm _ = False setInjective (PRef _ n) = setinj n setInjective (PApp _ (PRef _ n) _) = setinj n setInjective _ = return () elab' ina@(_, a, inty) tm@(PApp fc f [arg]) = erun fc $ do simple_app (elabE ina f) (elabE (True, a, inty) (getTm arg)) (show tm) solve elab' ina Placeholder = do (h : hs) <- get_holes movelast h elab' ina (PMetavar n) = let n' = mkN n in do attack; defer n'; solve where mkN n@(NS _ _) = n mkN n = case namespace info of Just xs@(_:_) -> sNS n xs _ -> n elab' ina (PProof ts) = do compute; mapM_ (runTac True ist) ts elab' ina (PTactics ts) | not pattern = do mapM_ (runTac False ist) ts | otherwise = elab' ina Placeholder elab' ina (PElabError e) = fail (pshow ist e) elab' ina (PRewrite fc r sc newg) = do attack tyn <- getNameFrom (sMN 0 "rty") claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab' ina r compute g <- goal rewrite (Var letn) g' <- goal when (g == g') $ lift $ tfail (NoRewriting g) case newg of Nothing -> elab' ina sc Just t -> doEquiv t sc solve where doEquiv t sc = do attack tyn <- getNameFrom (sMN 0 "ety") claim tyn RType valn <- getNameFrom (sMN 0 "eqval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "equiv_val") letbind letn (Var tyn) (Var valn) focus tyn elab' ina t focus valn elab' ina sc elab' ina (PRef fc letn) solve elab' ina@(_, a, inty) c@(PCase fc scr opts) = do attack tyn <- getNameFrom (sMN 0 "scty") claim tyn RType valn <- getNameFrom (sMN 0 "scval") scvn <- getNameFrom (sMN 0 "scvar") claim valn (Var tyn) letbind scvn (Var tyn) (Var valn) focus valn elabE (True, a, inty) scr args <- get_env cname <- unique_hole' True (mkCaseName fn) let cname' = mkN cname elab' ina (PMetavar cname') -- if the scrutinee is one of the 'args' in env, we should -- inspect it directly, rather than adding it as a new argument let newdef = PClauses fc [] cname' (caseBlock fc cname' (map (isScr scr) (reverse args)) opts) -- elaborate case env <- get_env updateAux (newdef : ) -- if we haven't got the type yet, hopefully we'll get it later! movelast tyn solve where mkCaseName (NS n ns) = NS (mkCaseName n) ns mkCaseName n = SN (CaseN n) -- mkCaseName (UN x) = UN (x ++ "_case") -- mkCaseName (MN i x) = MN i (x ++ "_case") mkN n@(NS _ _) = n mkN n = case namespace info of Just xs@(_:_) -> sNS n xs _ -> n elab' ina (PUnifyLog t) = do unifyLog True elab' ina t unifyLog False elab' ina x = fail $ "Unelaboratable syntactic form " ++ show x isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term)) isScr (PRef _ n) (n', b) = (n', (n == n', b)) isScr _ (n', b) = (n', (False, b)) caseBlock :: FC -> Name -> [(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause] caseBlock fc n env opts = let args' = findScr env args = map mkarg (map getNmScr args') in map (mkClause args) opts where -- Find the variable we want as the scrutinee and mark it as -- 'True'. If the scrutinee is in the environment, match on that -- otherwise match on the new argument we're adding. findScr ((n, (True, t)) : xs) = (n, (True, t)) : scrName n xs findScr [(n, (_, t))] = [(n, (True, t))] findScr (x : xs) = x : findScr xs -- [] can't happen since scrutinee is in the environment! -- To make sure top level pattern name remains in scope, put -- it at the end of the environment scrName n [] = [] scrName n [(_, t)] = [(n, t)] scrName n (x : xs) = x : scrName n xs getNmScr (n, (s, _)) = (n, s) mkarg (n, s) = (PRef fc n, s) -- may be shadowed names in the new pattern - so replace the -- old ones with an _ mkClause args (l, r) = let args' = map (shadowed (allNamesIn l)) args lhs = PApp (getFC fc l) (PRef (getFC fc l) n) (map (mkLHSarg l) args') in PClause (getFC fc l) n lhs [] r [] mkLHSarg l (tm, True) = pexp l mkLHSarg l (tm, False) = pexp tm shadowed new (PRef _ n, s) | n `elem` new = (Placeholder, s) shadowed new t = t getFC d (PApp fc _ _) = fc getFC d (PRef fc _) = fc getFC d (PAlternative _ (x:_)) = getFC d x getFC d x = d insertCoerce ina t = do ty <- goal -- Check for possible coercions to get to the goal -- and add them as 'alternatives' env <- get_env let ty' = normalise (tt_ctxt ist) env ty let cs = getCoercionsTo ist ty' let t' = case (t, cs) of (PCoerced tm, _) -> tm (_, []) -> t (_, cs) -> PAlternative False [t , PAlternative True (map (mkCoerce t) cs)] return t' where mkCoerce t n = let fc = fileFC "Coercion" in -- line never appears! addImpl ist (PApp fc (PRef fc n) [pexp (PCoerced t)]) -- | Elaborate the arguments to a function elabArgs :: IState -- ^ The current Idris state -> (Bool, Bool, Bool) -- ^ (in an argument, guarded, in a type) -> [Bool] -> FC -- ^ Source location -> Bool -> Name -- ^ Name of the function being applied -> [(Name, Name)] -- ^ (Argument Name, Hole Name) -> [(Bool, PTerm)] -- ^ (Laziness, argument) -> ElabD () elabArgs ist ina failed fc retry f [] _ -- | retry = let (ns, ts) = unzip (reverse failed) in -- elabArgs ina [] False ns ts | otherwise = return () elabArgs ist ina failed fc r f (n:ns) ((_, Placeholder) : args) = elabArgs ist ina failed fc r f ns args elabArgs ist ina failed fc r f ((argName, holeName):ns) ((lazy, t) : args) | lazy && not pattern = elabArg argName holeName (PApp bi (PRef bi (sUN "lazy")) [pimp (sUN "a") Placeholder True, pexp t]) | otherwise = elabArg argName holeName t where elabArg argName holeName t = reflectFunctionErrors ist f argName $ do hs <- get_holes tm <- get_term failed' <- -- trace (show (n, t, hs, tm)) $ -- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $ case holeName `elem` hs of True -> do focus holeName; elabE ina t; return failed False -> return failed elabArgs ist ina failed fc r f ns args -- | Perform error reflection for function applicaitons with specific error handlers reflectFunctionErrors :: IState -> Name -> Name -> ElabD a -> ElabD a reflectFunctionErrors ist f arg action = do elabState <- get (result, newState) <- case runStateT action elabState of OK (res, newState) -> return (res, newState) Error e@(ReflectionError _ _) -> (lift . tfail) e Error e@(ReflectionFailed _ _) -> (lift . tfail) e Error e -> handle e >>= lift . tfail put newState return result where handle :: Err -> ElabD Err handle e = do let funhandlers = (maybe M.empty id . lookupCtxtExact f . idris_function_errorhandlers) ist handlers = (maybe [] S.toList . M.lookup arg) funhandlers reports = map (\n -> RApp (Var n) (reflectErr e)) handlers -- Typecheck error handlers - if this fails, then something else was wrong earlier! handlers <- case mapM (check (tt_ctxt ist) []) reports of Error e -> lift . tfail $ ReflectionFailed "Type error while constructing reflected error" e OK hs -> return hs -- Normalize error handler terms to produce the new messages let ctxt = tt_ctxt ist results = map (normalise ctxt []) (map fst handlers) -- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results) errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of Left err -> lift (tfail err) Right ok -> return ok return $ case errorparts of [] -> e parts -> ReflectionError errorparts e -- For every alternative, look at the function at the head. Automatically resolve -- any nested alternatives where that function is also at the head pruneAlt :: [PTerm] -> [PTerm] pruneAlt xs = map prune xs where prune (PApp fc1 (PRef fc2 f) as) = PApp fc1 (PRef fc2 f) (fmap (fmap (choose f)) as) prune t = t choose f (PAlternative a as) = let as' = fmap (choose f) as fs = filter (headIs f) as' in case fs of [a] -> a _ -> PAlternative a as' choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as) choose f t = t headIs f (PApp _ (PRef _ f') _) = f == f' headIs f (PApp _ f' _) = headIs f f' headIs f _ = True -- keep if it's not an application -- Rule out alternatives that don't return the same type as the head of the goal -- (If there are none left as a result, do nothing) pruneByType :: Term -> Context -> [PTerm] -> [PTerm] pruneByType (P _ n _) c as -- if the goal type is polymorphic, keep e | [] <- lookupTy n c = as | otherwise = let asV = filter (headIs True n) as as' = filter (headIs False n) as in case as' of [] -> case asV of [] -> as _ -> asV _ -> as' where headIs var f (PApp _ (PRef _ f') _) = typeHead var f f' headIs var f (PApp _ f' _) = headIs var f f' headIs var f (PPi _ _ _ sc) = headIs var f sc headIs _ _ _ = True -- keep if it's not an application typeHead var f f' = case lookupTy f' c of [ty] -> let ty' = normalise c [] ty in case unApply (getRetTy ty') of (P _ ftyn _, _) -> ftyn == f (V _, _) -> var -- keep, variable _ -> False _ -> False pruneByType t _ as = as findInstances :: IState -> Term -> [Name] findInstances ist t | (P _ n _, _) <- unApply t = case lookupCtxt n (idris_classes ist) of [CI _ _ _ _ _ ins] -> ins _ -> [] | otherwise = [] trivial' ist = trivial (elab ist toplevel False [] (sMN 0 "tac")) ist proofSearch' ist top n hints = proofSearch (elab ist toplevel False [] (sMN 0 "tac")) top n hints ist resolveTC :: Int -> Term -> Name -> IState -> ElabD () resolveTC 0 topg fn ist = fail $ "Can't resolve type class" resolveTC 1 topg fn ist = try' (trivial' ist) (resolveTC 0 topg fn ist) True resolveTC depth topg fn ist = do hnf_compute g <- goal ptm <- get_term ulog <- getUnifyLog hs <- get_holes traceWhen ulog ("Resolving class " ++ show g) $ try' (trivial' ist) (do t <- goal let (tc, ttypes) = unApply t scopeOnly <- needsDefault t tc ttypes let insts_in = findInstances ist t let insts = if scopeOnly then filter chaser insts_in else insts_in tm <- get_term let depth' = if scopeOnly then 2 else depth blunderbuss t depth' insts) True where elabTC n | n /= fn && tcname n = (resolve n depth, show n) | otherwise = (fail "Can't resolve", show n) -- HACK! Rather than giving a special name, better to have some kind -- of flag in ClassInfo structure chaser (UN nm) | ('@':'@':_) <- str nm = True -- old way chaser (SN (ParentN _ _)) = True chaser (NS n _) = chaser n chaser _ = False numclass = sNS (sUN "Num") ["Classes","Prelude"] needsDefault t num@(P _ nc _) [P Bound a _] | nc == numclass = do focus a fill (RConstant (AType (ATInt ITBig))) -- default Integer solve return False needsDefault t f as | all boundVar as = return True -- fail $ "Can't resolve " ++ show t needsDefault t f a = return False -- trace (show t) $ return () boundVar (P Bound _ _) = True boundVar _ = False blunderbuss t d [] = do -- c <- get_env -- ps <- get_probs lift $ tfail $ CantResolve topg blunderbuss t d (n:ns) | n /= fn && tcname n = try' (resolve n d) (blunderbuss t d ns) True | otherwise = blunderbuss t d ns resolve n depth | depth == 0 = fail $ "Can't resolve type class" | otherwise = do t <- goal let (tc, ttypes) = unApply t -- if (all boundVar ttypes) then resolveTC (depth - 1) fn insts ist -- else do -- if there's a hole in the goal, don't even try let imps = case lookupCtxtName n (idris_implicits ist) of [] -> [] [args] -> map isImp (snd args) -- won't be overloaded! ps <- get_probs tm <- get_term args <- map snd <$> try' (apply (Var n) imps) (match_apply (Var n) imps) True ps' <- get_probs when (length ps < length ps') $ fail "Can't apply type class" -- traceWhen (all boundVar ttypes) ("Progress: " ++ show t ++ " with " ++ show n) $ mapM_ (\ (_,n) -> do focus n t' <- goal let (tc', ttype) = unApply t' let depth' = if t == t' then depth - 1 else depth resolveTC depth' topg fn ist) (filter (\ (x, y) -> not x) (zip (map fst imps) args)) -- if there's any arguments left, we've failed to resolve hs <- get_holes ulog <- getUnifyLog solve traceWhen ulog ("Got " ++ show n) $ return () where isImp (PImp p _ _ _ _ _) = (True, p) isImp arg = (False, priority arg) collectDeferred :: Maybe Name -> Term -> State [(Name, (Int, Maybe Name, Type))] Term collectDeferred top (Bind n (GHole i t) app) = do ds <- get when (not (n `elem` map fst ds)) $ put ((n, (i, top, t)) : ds) collectDeferred top app collectDeferred top (Bind n b t) = do b' <- cdb b t' <- collectDeferred top t return (Bind n b' t') where cdb (Let t v) = liftM2 Let (collectDeferred top t) (collectDeferred top v) cdb (Guess t v) = liftM2 Guess (collectDeferred top t) (collectDeferred top v) cdb b = do ty' <- collectDeferred top (binderTy b) return (b { binderTy = ty' }) collectDeferred top (App f a) = liftM2 App (collectDeferred top f) (collectDeferred top a) collectDeferred top t = return t -- Running tactics directly -- if a tactic adds unification problems, return an error runTac :: Bool -> IState -> PTactic -> ElabD () runTac autoSolve ist tac = do env <- get_env g <- goal no_errors (runT (fmap (addImplBound ist (map fst env)) tac)) (Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env))) where runT (Intro []) = do g <- goal attack; intro (bname g) where bname (Bind n _ _) = Just n bname _ = Nothing runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs runT Intros = do g <- goal attack; intro (bname g) try' (runT Intros) (return ()) True where bname (Bind n _ _) = Just n bname _ = Nothing runT (Exact tm) = do elab ist toplevel False [] (sMN 0 "tac") tm when autoSolve solveAll runT (MatchRefine fn) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns) let tacs = map (\ (fn', imps) -> (match_apply (Var fn') (map (\x -> (x, 0)) imps), show fn')) fnimps tryAll tacs when autoSolve solveAll where envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn []) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map isImp a)) ns) let tacs = map (\ (fn', imps) -> (apply (Var fn') (map (\x -> (x, 0)) imps), show fn')) fnimps tryAll tacs when autoSolve solveAll where isImp (PImp _ _ _ _ _ _) = True isImp _ = False envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps) when autoSolve solveAll runT (Equiv tm) -- let bind tm, then = do attack tyn <- getNameFrom (sMN 0 "ety") claim tyn RType valn <- getNameFrom (sMN 0 "eqval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "equiv_val") letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel False [] (sMN 0 "tac") tm focus valn when autoSolve solveAll runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that = do attack; -- (h:_) <- get_holes tyn <- getNameFrom (sMN 0 "rty") -- start_unify h claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel False [] (sMN 0 "tac") tm rewrite (Var letn) when autoSolve solveAll runT (Induction nm) = do induction nm when autoSolve solveAll runT (LetTac n tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel False [] (sMN 0 "tac") tm when autoSolve solveAll runT (LetTacTy n ty tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel False [] (sMN 0 "tac") ty focus valn elab ist toplevel False [] (sMN 0 "tac") tm when autoSolve solveAll runT Compute = compute runT Trivial = do trivial' ist; when autoSolve solveAll runT (ProofSearch top n hints) = do proofSearch' ist top n hints; when autoSolve solveAll runT (Focus n) = focus n runT Solve = solve runT (Try l r) = do try' (runT l) (runT r) True runT (TSeq l r) = do runT l; runT r runT (ApplyTactic tm) = do tenv <- get_env -- store the environment tgoal <- goal -- store the goal attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ... script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script elab ist toplevel False [] (sMN 0 "tac") tm (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal and context restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (raw_apply (forget script') [reflectEnv tenv, reflect tgoal]) restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") listTy = Var (sNS (sUN "List") ["List", "Prelude"]) scriptTy = (RBind (sUN "__pi_arg") (Pi (RApp listTy envTupleType)) (RBind (sUN "__pi_arg1") (Pi (Var $ reflm "TT")) tacticTy)) runT (ByReflection tm) -- run the reflection function 'tm' on the -- goal, then apply the resulting reflected Tactic = do tgoal <- goal attack script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script ptm <- get_term elab ist toplevel False [] (sMN 0 "tac") (PApp emptyFC tm [pexp (delabTy' ist [] tgoal True True)]) (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (forget script') restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") scriptTy = tacticTy runT (Reflect v) = do attack -- let x = reflect v in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel False [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = hnf ctxt env value runTac autoSolve ist (Exact $ PQuote (reflect value')) runT (Fill v) = do attack -- let x = fill x in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel False [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = normalise ctxt env value rawValue <- reifyRaw value' runTac autoSolve ist (Exact $ PQuote rawValue) runT (GoalType n tac) = do g <- goal case unApply g of (P _ n' _, _) -> if nsroot n' == sUN n then runT tac else fail "Wrong goal type" _ -> fail "Wrong goal type" runT ProofState = do g <- goal return () runT x = fail $ "Not implemented " ++ show x runReflected t = do t' <- reify ist t runTac autoSolve ist t' -- | Prefix a name with the "Language.Reflection" namespace reflm :: String -> Name reflm n = sNS (sUN n) ["Reflection", "Language"] -- | Reify tactics from their reflected representation reify :: IState -> Term -> ElabD PTactic reify _ (P _ n _) | n == reflm "Intros" = return Intros reify _ (P _ n _) | n == reflm "Trivial" = return Trivial reify _ (P _ n _) | n == reflm "Solve" = return Solve reify _ (P _ n _) | n == reflm "Compute" = return Compute reify ist t@(App _ _) | (P _ f _, args) <- unApply t = reifyApp ist f args reify _ t = fail ("Unknown tactic " ++ show t) reifyApp :: IState -> Name -> [Term] -> ElabD PTactic reifyApp ist t [l, r] | t == reflm "Try" = liftM2 Try (reify ist l) (reify ist r) reifyApp _ t [x] | t == reflm "Refine" = do n <- reifyTTName x return $ Refine n [] reifyApp ist t [l, r] | t == reflm "Seq" = liftM2 TSeq (reify ist l) (reify ist r) reifyApp ist t [Constant (Str n), x] | t == reflm "GoalType" = liftM (GoalType n) (reify ist x) reifyApp _ t [Constant (Str n)] | t == reflm "Intro" = return $ Intro [sUN n] reifyApp ist t [t'] | t == reflm "ApplyTactic" = liftM (ApplyTactic . delab ist) (reifyTT t') reifyApp ist t [t'] | t == reflm "Reflect" = liftM (Reflect . delab ist) (reifyTT t') reifyApp _ t [t'] | t == reflm "Fill" = liftM (Fill . PQuote) (reifyRaw t') reifyApp ist t [t'] | t == reflm "Exact" = liftM (Exact . delab ist) (reifyTT t') reifyApp ist t [x] | t == reflm "Focus" = liftM Focus (reifyTTName x) reifyApp ist t [t'] | t == reflm "Rewrite" = liftM (Rewrite . delab ist) (reifyTT t') reifyApp ist t [n, t'] | t == reflm "LetTac" = do n' <- reifyTTName n t'' <- reifyTT t' return $ LetTac n' (delab ist t') reifyApp ist t [n, tt', t'] | t == reflm "LetTacTy" = do n' <- reifyTTName n tt'' <- reifyTT tt' t'' <- reifyTT t' return $ LetTacTy n' (delab ist tt'') (delab ist t'') reifyApp _ f args = fail ("Unknown tactic " ++ show (f, args)) -- shouldn't happen -- | Reify terms from their reflected representation reifyTT :: Term -> ElabD Term reifyTT t@(App _ _) | (P _ f _, args) <- unApply t = reifyTTApp f args reifyTT t@(P _ n _) | n == reflm "Erased" = return $ Erased reifyTT t@(P _ n _) | n == reflm "Impossible" = return $ Impossible reifyTT t = fail ("Unknown reflection term: " ++ show t) reifyTTApp :: Name -> [Term] -> ElabD Term reifyTTApp t [nt, n, x] | t == reflm "P" = do nt' <- reifyTTNameType nt n' <- reifyTTName n x' <- reifyTT x return $ P nt' n' x' reifyTTApp t [Constant (I i)] | t == reflm "V" = return $ V i reifyTTApp t [n, b, x] | t == reflm "Bind" = do n' <- reifyTTName n b' <- reifyTTBinder reifyTT (reflm "TT") b x' <- reifyTT x return $ Bind n' b' x' reifyTTApp t [f, x] | t == reflm "App" = do f' <- reifyTT f x' <- reifyTT x return $ App f' x' reifyTTApp t [c] | t == reflm "TConst" = liftM Constant (reifyTTConst c) reifyTTApp t [t', Constant (I i)] | t == reflm "Proj" = do t'' <- reifyTT t' return $ Proj t'' i reifyTTApp t [tt] | t == reflm "TType" = liftM TType (reifyTTUExp tt) reifyTTApp t args = fail ("Unknown reflection term: " ++ show (t, args)) -- | Reify raw terms from their reflected representation reifyRaw :: Term -> ElabD Raw reifyRaw t@(App _ _) | (P _ f _, args) <- unApply t = reifyRawApp f args reifyRaw t@(P _ n _) | n == reflm "RType" = return $ RType reifyRaw t = fail ("Unknown reflection raw term: " ++ show t) reifyRawApp :: Name -> [Term] -> ElabD Raw reifyRawApp t [n] | t == reflm "Var" = liftM Var (reifyTTName n) reifyRawApp t [n, b, x] | t == reflm "RBind" = do n' <- reifyTTName n b' <- reifyTTBinder reifyRaw (reflm "Raw") b x' <- reifyRaw x return $ RBind n' b' x' reifyRawApp t [f, x] | t == reflm "RApp" = liftM2 RApp (reifyRaw f) (reifyRaw x) reifyRawApp t [t'] | t == reflm "RForce" = liftM RForce (reifyRaw t') reifyRawApp t [c] | t == reflm "RConstant" = liftM RConstant (reifyTTConst c) reifyRawApp t args = fail ("Unknown reflection raw term: " ++ show (t, args)) reifyTTName :: Term -> ElabD Name reifyTTName t | (P _ f _, args) <- unApply t = reifyTTNameApp f args reifyTTName t = fail ("Unknown reflection term name: " ++ show t) reifyTTNameApp :: Name -> [Term] -> ElabD Name reifyTTNameApp t [Constant (Str n)] | t == reflm "UN" = return $ sUN n reifyTTNameApp t [n, ns] | t == reflm "NS" = do n' <- reifyTTName n ns' <- reifyTTNamespace ns return $ sNS n' ns' reifyTTNameApp t [Constant (I i), Constant (Str n)] | t == reflm "MN" = return $ sMN i n reifyTTNameApp t [] | t == reflm "NErased" = return NErased reifyTTNameApp t args = fail ("Unknown reflection term name: " ++ show (t, args)) reifyTTNamespace :: Term -> ElabD [String] reifyTTNamespace t@(App _ _) = case unApply t of (P _ f _, [Constant StrType]) | f == sNS (sUN "Nil") ["List", "Prelude"] -> return [] (P _ f _, [Constant StrType, Constant (Str n), ns]) | f == sNS (sUN "::") ["List", "Prelude"] -> liftM (n:) (reifyTTNamespace ns) _ -> fail ("Unknown reflection namespace arg: " ++ show t) reifyTTNamespace t = fail ("Unknown reflection namespace arg: " ++ show t) reifyTTNameType :: Term -> ElabD NameType reifyTTNameType t@(P _ n _) | n == reflm "Bound" = return $ Bound reifyTTNameType t@(P _ n _) | n == reflm "Ref" = return $ Ref reifyTTNameType t@(App _ _) = case unApply t of (P _ f _, [Constant (I tag), Constant (I num)]) | f == reflm "DCon" -> return $ DCon tag num | f == reflm "TCon" -> return $ TCon tag num _ -> fail ("Unknown reflection name type: " ++ show t) reifyTTNameType t = fail ("Unknown reflection name type: " ++ show t) reifyTTBinder :: (Term -> ElabD a) -> Name -> Term -> ElabD (Binder a) reifyTTBinder reificator binderType t@(App _ _) = case unApply t of (P _ f _, bt:args) | forget bt == Var binderType -> reifyTTBinderApp reificator f args _ -> fail ("Mismatching binder reflection: " ++ show t) reifyTTBinder _ _ t = fail ("Unknown reflection binder: " ++ show t) reifyTTBinderApp :: (Term -> ElabD a) -> Name -> [Term] -> ElabD (Binder a) reifyTTBinderApp reif f [t] | f == reflm "Lam" = liftM Lam (reif t) reifyTTBinderApp reif f [t] | f == reflm "Pi" = liftM Pi (reif t) reifyTTBinderApp reif f [x, y] | f == reflm "Let" = liftM2 Let (reif x) (reif y) reifyTTBinderApp reif f [x, y] | f == reflm "NLet" = liftM2 NLet (reif x) (reif y) reifyTTBinderApp reif f [t] | f == reflm "Hole" = liftM Hole (reif t) reifyTTBinderApp reif f [t] | f == reflm "GHole" = liftM (GHole 0) (reif t) reifyTTBinderApp reif f [x, y] | f == reflm "Guess" = liftM2 Guess (reif x) (reif y) reifyTTBinderApp reif f [t] | f == reflm "PVar" = liftM PVar (reif t) reifyTTBinderApp reif f [t] | f == reflm "PVTy" = liftM PVTy (reif t) reifyTTBinderApp _ f args = fail ("Unknown reflection binder: " ++ show (f, args)) reifyTTConst :: Term -> ElabD Const reifyTTConst (P _ n _) | n == reflm "IType" = return (AType (ATInt ITNative)) reifyTTConst (P _ n _) | n == reflm "BIType" = return (AType (ATInt ITBig)) reifyTTConst (P _ n _) | n == reflm "FlType" = return (AType ATFloat) reifyTTConst (P _ n _) | n == reflm "ChType" = return (AType (ATInt ITChar)) reifyTTConst (P _ n _) | n == reflm "StrType" = return $ StrType reifyTTConst (P _ n _) | n == reflm "B8Type" = return (AType (ATInt (ITFixed IT8))) reifyTTConst (P _ n _) | n == reflm "B16Type" = return (AType (ATInt (ITFixed IT16))) reifyTTConst (P _ n _) | n == reflm "B32Type" = return (AType (ATInt (ITFixed IT32))) reifyTTConst (P _ n _) | n == reflm "B64Type" = return (AType (ATInt (ITFixed IT64))) reifyTTConst (P _ n _) | n == reflm "PtrType" = return $ PtrType reifyTTConst (P _ n _) | n == reflm "VoidType" = return $ VoidType reifyTTConst (P _ n _) | n == reflm "Forgot" = return $ Forgot reifyTTConst t@(App _ _) | (P _ f _, [arg]) <- unApply t = reifyTTConstApp f arg reifyTTConst t = fail ("Unknown reflection constant: " ++ show t) reifyTTConstApp :: Name -> Term -> ElabD Const reifyTTConstApp f (Constant c@(I _)) | f == reflm "I" = return $ c reifyTTConstApp f (Constant c@(BI _)) | f == reflm "BI" = return $ c reifyTTConstApp f (Constant c@(Fl _)) | f == reflm "Fl" = return $ c reifyTTConstApp f (Constant c@(I _)) | f == reflm "Ch" = return $ c reifyTTConstApp f (Constant c@(Str _)) | f == reflm "Str" = return $ c reifyTTConstApp f (Constant c@(B8 _)) | f == reflm "B8" = return $ c reifyTTConstApp f (Constant c@(B16 _)) | f == reflm "B16" = return $ c reifyTTConstApp f (Constant c@(B32 _)) | f == reflm "B32" = return $ c reifyTTConstApp f (Constant c@(B64 _)) | f == reflm "B64" = return $ c reifyTTConstApp f arg = fail ("Unknown reflection constant: " ++ show (f, arg)) reifyTTUExp :: Term -> ElabD UExp reifyTTUExp t@(App _ _) = case unApply t of (P _ f _, [Constant (I i)]) | f == reflm "UVar" -> return $ UVar i (P _ f _, [Constant (I i)]) | f == reflm "UVal" -> return $ UVal i _ -> fail ("Unknown reflection type universe expression: " ++ show t) reifyTTUExp t = fail ("Unknown reflection type universe expression: " ++ show t) -- | Create a reflected call to a named function/constructor reflCall :: String -> [Raw] -> Raw reflCall funName args = raw_apply (Var (reflm funName)) args -- | Lift a term into its Language.Reflection.TT representation reflect :: Term -> Raw reflect (P nt n t) = reflCall "P" [reflectNameType nt, reflectName n, reflect t] reflect (V n) = reflCall "V" [RConstant (I n)] reflect (Bind n b x) = reflCall "Bind" [reflectName n, reflectBinder b, reflect x] reflect (App f x) = reflCall "App" [reflect f, reflect x] reflect (Constant c) = reflCall "TConst" [reflectConstant c] reflect (Proj t i) = reflCall "Proj" [reflect t, RConstant (I i)] reflect (Erased) = Var (reflm "Erased") reflect (Impossible) = Var (reflm "Impossible") reflect (TType exp) = reflCall "TType" [reflectUExp exp] reflectNameType :: NameType -> Raw reflectNameType (Bound) = Var (reflm "Bound") reflectNameType (Ref) = Var (reflm "Ref") reflectNameType (DCon x y) = reflCall "DCon" [RConstant (I x), RConstant (I y)] reflectNameType (TCon x y) = reflCall "TCon" [RConstant (I x), RConstant (I y)] reflectName :: Name -> Raw reflectName (UN s) = reflCall "UN" [RConstant (Str (str s))] reflectName (NS n ns) = reflCall "NS" [ reflectName n , foldr (\ n s -> raw_apply ( Var $ sNS (sUN "::") ["List", "Prelude"] ) [ RConstant StrType, RConstant (Str n), s ]) ( raw_apply ( Var $ sNS (sUN "Nil") ["List", "Prelude"] ) [ RConstant StrType ]) (map str ns) ] reflectName (MN i n) = reflCall "MN" [RConstant (I i), RConstant (Str (str n))] reflectName (NErased) = Var (reflm "NErased") reflectName n = Var (reflm "NErased") -- special name, not yet implemented reflectBinder :: Binder Term -> Raw reflectBinder (Lam t) = reflCall "Lam" [Var (reflm "TT"), reflect t] reflectBinder (Pi t) = reflCall "Pi" [Var (reflm "TT"), reflect t] reflectBinder (Let x y) = reflCall "Let" [Var (reflm "TT"), reflect x, reflect y] reflectBinder (NLet x y) = reflCall "NLet" [Var (reflm "TT"), reflect x, reflect y] reflectBinder (Hole t) = reflCall "Hole" [Var (reflm "TT"), reflect t] reflectBinder (GHole _ t) = reflCall "GHole" [Var (reflm "TT"), reflect t] reflectBinder (Guess x y) = reflCall "Guess" [Var (reflm "TT"), reflect x, reflect y] reflectBinder (PVar t) = reflCall "PVar" [Var (reflm "TT"), reflect t] reflectBinder (PVTy t) = reflCall "PVTy" [Var (reflm "TT"), reflect t] reflectConstant :: Const -> Raw reflectConstant c@(I _) = reflCall "I" [RConstant c] reflectConstant c@(BI _) = reflCall "BI" [RConstant c] reflectConstant c@(Fl _) = reflCall "Fl" [RConstant c] reflectConstant c@(Ch _) = reflCall "Ch" [RConstant c] reflectConstant c@(Str _) = reflCall "Str" [RConstant c] reflectConstant (AType (ATInt ITNative)) = Var (reflm "IType") reflectConstant (AType (ATInt ITBig)) = Var (reflm "BIType") reflectConstant (AType ATFloat) = Var (reflm "FlType") reflectConstant (AType (ATInt ITChar)) = Var (reflm "ChType") reflectConstant (StrType) = Var (reflm "StrType") reflectConstant c@(B8 _) = reflCall "B8" [RConstant c] reflectConstant c@(B16 _) = reflCall "B16" [RConstant c] reflectConstant c@(B32 _) = reflCall "B32" [RConstant c] reflectConstant c@(B64 _) = reflCall "B64" [RConstant c] reflectConstant (AType (ATInt (ITFixed IT8))) = Var (reflm "B8Type") reflectConstant (AType (ATInt (ITFixed IT16))) = Var (reflm "B16Type") reflectConstant (AType (ATInt (ITFixed IT32))) = Var (reflm "B32Type") reflectConstant (AType (ATInt (ITFixed IT64))) = Var (reflm "B64Type") reflectConstant (PtrType) = Var (reflm "PtrType") reflectConstant (VoidType) = Var (reflm "VoidType") reflectConstant (Forgot) = Var (reflm "Forgot") reflectUExp :: UExp -> Raw reflectUExp (UVar i) = reflCall "UVar" [RConstant (I i)] reflectUExp (UVal i) = reflCall "UVal" [RConstant (I i)] -- | Reflect the environment of a proof into a List (TTName, Binder TT) reflectEnv :: Env -> Raw reflectEnv = foldr consToEnvList emptyEnvList where consToEnvList :: (Name, Binder Term) -> Raw -> Raw consToEnvList (n, b) l = raw_apply (Var (sNS (sUN "::") ["List", "Prelude"])) [ envTupleType , raw_apply (Var pairCon) [ (Var $ reflm "TTName") , (RApp (Var $ reflm "Binder") (Var $ reflm "TT")) , reflectName n , reflectBinder b ] , l ] emptyEnvList :: Raw emptyEnvList = raw_apply (Var (sNS (sUN "Nil") ["List", "Prelude"])) [envTupleType] -- | Reflect an error into the internal datatype of Idris -- TODO rawBool :: Bool -> Raw rawBool True = Var (sNS (sUN "True") ["Bool", "Prelude"]) rawBool False = Var (sNS (sUN "False") ["Bool", "Prelude"]) rawNil :: Raw -> Raw rawNil ty = raw_apply (Var (sNS (sUN "Nil") ["List", "Prelude"])) [ty] rawCons :: Raw -> Raw -> Raw -> Raw rawCons ty hd tl = raw_apply (Var (sNS (sUN "::") ["List", "Prelude"])) [ty, hd, tl] rawList :: Raw -> [Raw] -> Raw rawList ty = foldr (rawCons ty) (rawNil ty) rawPairTy :: Raw -> Raw -> Raw rawPairTy t1 t2 = raw_apply (Var pairTy) [t1, t2] rawPair :: (Raw, Raw) -> (Raw, Raw) -> Raw rawPair (a, b) (x, y) = raw_apply (Var pairCon) [a, b, x, y] reflectCtxt :: [(Name, Type)] -> Raw reflectCtxt ctxt = rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TT")) (map (\ (n, t) -> (rawPair (Var $ reflm "TTName", Var $ reflm "TT") (reflectName n, reflect t))) ctxt) reflectErr :: Err -> Raw reflectErr (Msg msg) = raw_apply (Var $ reflErrName "Msg") [RConstant (Str msg)] reflectErr (InternalMsg msg) = raw_apply (Var $ reflErrName "InternalMsg") [RConstant (Str msg)] reflectErr (CantUnify b t1 t2 e ctxt i) = raw_apply (Var $ reflErrName "CantUnify") [ rawBool b , reflect t1 , reflect t2 , reflectErr e , reflectCtxt ctxt , RConstant (I i)] reflectErr (InfiniteUnify n tm ctxt) = raw_apply (Var $ reflErrName "InfiniteUnify") [ reflectName n , reflect tm , reflectCtxt ctxt ] reflectErr (CantConvert t t' ctxt) = raw_apply (Var $ reflErrName "CantConvert") [ reflect t , reflect t' , reflectCtxt ctxt ] reflectErr (CantSolveGoal t ctxt) = raw_apply (Var $ reflErrName "CantSolveGoal") [ reflect t , reflectCtxt ctxt ] reflectErr (UnifyScope n n' t ctxt) = raw_apply (Var $ reflErrName "UnifyScope") [ reflectName n , reflectName n' , reflect t , reflectCtxt ctxt ] reflectErr (CantInferType str) = raw_apply (Var $ reflErrName "CantInferType") [RConstant (Str str)] reflectErr (NonFunctionType t t') = raw_apply (Var $ reflErrName "NonFunctionType") [reflect t, reflect t'] reflectErr (NotEquality t t') = raw_apply (Var $ reflErrName "NotEquality") [reflect t, reflect t'] reflectErr (TooManyArguments n) = raw_apply (Var $ reflErrName "TooManyArguments") [reflectName n] reflectErr (CantIntroduce t) = raw_apply (Var $ reflErrName "CantIntroduce") [reflect t] reflectErr (NoSuchVariable n) = raw_apply (Var $ reflErrName "NoSuchVariable") [reflectName n] reflectErr (NoTypeDecl n) = raw_apply (Var $ reflErrName "NoTypeDecl") [reflectName n] reflectErr (NotInjective t1 t2 t3) = raw_apply (Var $ reflErrName "NotInjective") [ reflect t1 , reflect t2 , reflect t3 ] reflectErr (CantResolve t) = raw_apply (Var $ reflErrName "CantResolve") [reflect t] reflectErr (CantResolveAlts ss) = raw_apply (Var $ reflErrName "CantResolve") [rawList (Var $ (sUN "String")) (map (RConstant . Str) ss)] reflectErr (IncompleteTerm t) = raw_apply (Var $ reflErrName "IncompleteTerm") [reflect t] reflectErr UniverseError = Var $ reflErrName "UniverseError" reflectErr ProgramLineComment = Var $ reflErrName "ProgramLineComment" reflectErr (Inaccessible n) = raw_apply (Var $ reflErrName "Inaccessible") [reflectName n] reflectErr (NonCollapsiblePostulate n) = raw_apply (Var $ reflErrName "NonCollabsiblePostulate") [reflectName n] reflectErr (AlreadyDefined n) = raw_apply (Var $ reflErrName "AlreadyDefined") [reflectName n] reflectErr (ProofSearchFail e) = raw_apply (Var $ reflErrName "ProofSearchFail") [reflectErr e] reflectErr (NoRewriting tm) = raw_apply (Var $ reflErrName "NoRewriting") [reflect tm] reflectErr (At fc err) = raw_apply (Var $ reflErrName "At") [reflectFC fc, reflectErr err] where reflectFC (FC source line col) = raw_apply (Var $ reflErrName "FileLoc") [ RConstant (Str source) , RConstant (I line) , RConstant (I col) ] reflectErr (Elaborating str n e) = raw_apply (Var $ reflErrName "Elaborating") [ RConstant (Str str) , reflectName n , reflectErr e ] reflectErr (ProviderError str) = raw_apply (Var $ reflErrName "ProviderError") [RConstant (Str str)] reflectErr (LoadingFailed str err) = raw_apply (Var $ reflErrName "LoadingFailed") [RConstant (Str str)] reflectErr x = raw_apply (Var (sNS (sUN "Msg") ["Errors", "Reflection", "Language"])) [RConstant . Str $ "Default reflection: " ++ show x] withErrorReflection :: Idris a -> Idris a withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror) where handle :: Err -> Idris Err handle e@(ReflectionError _ _) = do logLvl 3 "Skipping reflection of error reflection result" return e -- Don't do meta-reflection of errors handle e@(ReflectionFailed _ _) = do logLvl 3 "Skipping reflection of reflection failure" return e handle e = do ist <- getIState logLvl 2 "Starting error reflection" let handlers = idris_errorhandlers ist logLvl 3 $ "Using reflection handlers " ++ concat (intersperse ", " (map show handlers)) let reports = map (\n -> RApp (Var n) (reflectErr e)) handlers -- Typecheck error handlers - if this fails, then something else was wrong earlier! handlers <- case mapM (check (tt_ctxt ist) []) reports of Error e -> ierror $ ReflectionFailed "Type error while constructing reflected error" e OK hs -> return hs -- Normalize error handler terms to produce the new messages ctxt <- getContext let results = map (normalise ctxt []) (map fst handlers) logLvl 3 $ "New error message info: " ++ concat (intersperse " and " (map show results)) -- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results) errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of Left err -> ierror err Right ok -> return ok return $ case errorparts of [] -> e parts -> ReflectionError errorparts e fromTTMaybe :: Term -> Maybe Term -- WARNING: Assumes the term has type Maybe a fromTTMaybe (App (App (P (DCon _ _) (NS (UN just) _) _) ty) tm) | just == txt "Just" = Just tm fromTTMaybe x = Nothing reflErrName :: String -> Name reflErrName n = sNS (sUN n) ["Errors", "Reflection", "Language"] -- | Attempt to reify a report part from TT to the internal -- representation. Not in Idris or ElabD monads because it should be usable -- from either. reifyReportPart :: Term -> Either Err ErrorReportPart reifyReportPart (App (P (DCon _ _) n _) (Constant (Str msg))) | n == reflErrName "TextPart" = Right (TextPart msg) reifyReportPart (App (P (DCon _ _) n _) ttn) | n == reflErrName "NamePart" = case runElab [] (reifyTTName ttn) (initElaborator NErased initContext Erased) of Error e -> Left . InternalMsg $ "could not reify name term " ++ show ttn ++ " when reflecting an error:" ++ show e OK (n', _)-> Right $ NamePart n' reifyReportPart (App (P (DCon _ _) n _) tm) | n == reflErrName "TermPart" = case runElab [] (reifyTT tm) (initElaborator NErased initContext Erased) of Error e -> Left . InternalMsg $ "could not reify reflected term " ++ show tm ++ " when reflecting an error:" ++ show e OK (tm', _) -> Right $ TermPart tm' reifyReportPart (App (P (DCon _ _) n _) tm) | n == reflErrName "SubReport" = case unList tm of Just xs -> do subParts <- mapM reifyReportPart xs Right (SubReport subParts) Nothing -> Left . InternalMsg $ "could not reify subreport " ++ show tm reifyReportPart x = Left . InternalMsg $ "could not reify " ++ show x envTupleType :: Raw envTupleType = raw_apply (Var pairTy) [ (Var $ reflm "TTName") , (RApp (Var $ reflm "Binder") (Var $ reflm "TT")) ] solveAll = try (do solve; solveAll) (return ())
ctford/Idris-Elba-dev
src/Idris/ElabTerm.hs
bsd-3-clause
72,545
0
24
29,488
24,395
11,868
12,527
1,353
102
{-| Time Interval Data Type to use to schedule jobs, (Secs, Minutes, Hours, Days), coupled along with convenience function to convert datatype to a rational number. Please note this data type guards against negative time which will result in 0 Addition/multiplication/division's resultant type instance will determined by the left operand Sec x + Day y = Sec z Day x + Minute y = Day z -} module TinyScheduler.Time ( Interval(..) , intervalToSecs ) where import Data.Time data Interval = Secs Rational | Minutes Rational | Hours Rational | Days Rational | Weeks Rational deriving (Show) intervalToSecs :: Interval -> Rational intervalToSecs z = case z of (Secs x) -> x (Minutes x) -> 60 * x (Hours x) -> 3600 * x (Days x) -> 24 * 3600 * x (Weeks x) -> 3600 * 24 * 7 * x convertToSecs = Secs . intervalToSecs convertToHours = Hours . flip (/) 3600 . intervalToSecs convertToMinutes = Minutes . flip (/) 60 . intervalToSecs convertToDays = Days . flip (/) (24 * 3600) . intervalToSecs convertToWeeks = Weeks . flip (/) (3600 * 24 * 7) . intervalToSecs filterOutNegative :: Rational -> Rational filterOutNegative x = (1 + signum x) * (abs x) / 2 -- to ensure no negative time arrives as a result guardAgainstZero :: Interval -> Interval guardAgainstZero y = case y of (Secs x) -> Secs . filterOutNegative $ x (Minutes x) -> Minutes . filterOutNegative $ x (Hours x) -> Hours . filterOutNegative $ x (Days x) -> Days . filterOutNegative $ x (Weeks x) -> Days . filterOutNegative $ x instance Eq Interval where Secs x == Secs y = x == y Minutes x == Minutes y = x == y Hours x == Hours y = x == y Days x == Days y = x == y Weeks x == Weeks y = x == y x == y = (intervalToSecs x) == (intervalToSecs y) instance Num Interval where Secs x + Secs y = Secs (x + y) Secs x + y = Secs x + convertToSecs y Minutes x + Minutes y = Minutes (x + y) Minutes x + y = Minutes x + convertToMinutes y Hours x + Hours y = Hours (x + y) Hours x + y = Hours x + convertToHours y Days x + Days y = Days (x + y) Days x + y = Days x + convertToDays y Weeks x + Weeks y = Weeks (x + y) Weeks x + y = Weeks x + convertToWeeks y Secs x * Secs y = Secs (x * y) Secs x * y = Secs x * convertToSecs y Minutes x * Minutes y = Minutes (x * y) Minutes x * y = Minutes x * convertToMinutes y Hours x * Hours y = Hours (x * y) Hours x * y = Hours x * convertToHours y Days x * Days y = Days (x * y) Days x * y = Days x * convertToDays y Weeks x * Weeks y = Weeks (x * y) Weeks x * y = Weeks x * convertToWeeks y -- negation of time makes no sense, this ain't quantum mechanics negate _ = Secs 0 Secs x - Secs y = Secs . filterOutNegative $ (x - y) Secs x - y = Secs x - convertToSecs y Minutes x - Minutes y = Minutes . filterOutNegative $ (x - y) Minutes x - y = Minutes x * convertToMinutes y Hours x - Hours y = Hours . filterOutNegative $ (x - y) Hours x - y = Hours x - convertToHours y Days x - Days y = Days . filterOutNegative $ (x - y) Days x - y = Days x - convertToDays y Weeks x - Weeks y = Weeks . filterOutNegative $ (x - y) Weeks x - y = Weeks x - convertToWeeks y abs = guardAgainstZero signum = abs fromInteger = Secs . fromIntegral
functor-soup/tiny-scheduler
TinyScheduler/Time.hs
bsd-3-clause
3,293
0
10
851
1,408
662
746
76
5
module Machine.Acceptor.Inter2 where import qualified Machine.Acceptor.Type2 as A import Machine.Akzeptieren import Machine.Class import Condition import Language.Sampler import Language.Inter import Language.Type import qualified Challenger as C import Inter.Types import Autolib.Reporter hiding ( output ) import Autolib.ToDoc import Autolib.Reader import Autolib.Hash import Autolib.Informed instance ( Condition prop m , Reader m, Hash m , Machine m String conf , ToDoc [prop] , ToDoc prop , Reader [prop] , Reader prop ) => C.Partial ( A.Acceptor ) ( A.Type m String prop ) m where describe p i = vcat [ text "Gesucht ist ein" <+> text ( A.machine_desc i ) , text "für die Sprache" , nest 4 $ toDoc $ inter $ language $ A.source i , text "über dem Alphabet" <+> toDoc ( alphabet $ inter $ language $ A.source i ) , text "" , text "mit diesen Eigenschaften" <+> toDoc (A.properties i) ] initial p i = A.start i partial p i b = investigate ( A.properties i ) b total p i b = do let ( yeahs, nohs ) = Language.Sampler.create ( A.source i ) ( hash b ) Nothing positiv_liste (A.cut i) b $ yeahs negativ_liste (A.cut i) b $ nohs return ()
florianpilz/autotool
src/Machine/Acceptor/Inter2.hs
gpl-2.0
1,319
8
14
377
451
234
217
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.EC2.UnmonitorInstances -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Disables monitoring for a running instance. For more information about -- monitoring instances, see -- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html Monitoring Your Instances and Volumes> -- in the /Amazon Elastic Compute Cloud User Guide/. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-UnmonitorInstances.html AWS API Reference> for UnmonitorInstances. module Network.AWS.EC2.UnmonitorInstances ( -- * Creating a Request unmonitorInstances , UnmonitorInstances -- * Request Lenses , uiDryRun , uiInstanceIds -- * Destructuring the Response , unmonitorInstancesResponse , UnmonitorInstancesResponse -- * Response Lenses , uirsInstanceMonitorings , uirsResponseStatus ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'unmonitorInstances' smart constructor. data UnmonitorInstances = UnmonitorInstances' { _uiDryRun :: !(Maybe Bool) , _uiInstanceIds :: ![Text] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UnmonitorInstances' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uiDryRun' -- -- * 'uiInstanceIds' unmonitorInstances :: UnmonitorInstances unmonitorInstances = UnmonitorInstances' { _uiDryRun = Nothing , _uiInstanceIds = mempty } -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have -- the required permissions, the error response is 'DryRunOperation'. -- Otherwise, it is 'UnauthorizedOperation'. uiDryRun :: Lens' UnmonitorInstances (Maybe Bool) uiDryRun = lens _uiDryRun (\ s a -> s{_uiDryRun = a}); -- | One or more instance IDs. uiInstanceIds :: Lens' UnmonitorInstances [Text] uiInstanceIds = lens _uiInstanceIds (\ s a -> s{_uiInstanceIds = a}) . _Coerce; instance AWSRequest UnmonitorInstances where type Rs UnmonitorInstances = UnmonitorInstancesResponse request = postQuery eC2 response = receiveXML (\ s h x -> UnmonitorInstancesResponse' <$> (x .@? "instancesSet" .!@ mempty >>= may (parseXMLList "item")) <*> (pure (fromEnum s))) instance ToHeaders UnmonitorInstances where toHeaders = const mempty instance ToPath UnmonitorInstances where toPath = const "/" instance ToQuery UnmonitorInstances where toQuery UnmonitorInstances'{..} = mconcat ["Action" =: ("UnmonitorInstances" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), "DryRun" =: _uiDryRun, toQueryList "InstanceId" _uiInstanceIds] -- | /See:/ 'unmonitorInstancesResponse' smart constructor. data UnmonitorInstancesResponse = UnmonitorInstancesResponse' { _uirsInstanceMonitorings :: !(Maybe [InstanceMonitoring]) , _uirsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UnmonitorInstancesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uirsInstanceMonitorings' -- -- * 'uirsResponseStatus' unmonitorInstancesResponse :: Int -- ^ 'uirsResponseStatus' -> UnmonitorInstancesResponse unmonitorInstancesResponse pResponseStatus_ = UnmonitorInstancesResponse' { _uirsInstanceMonitorings = Nothing , _uirsResponseStatus = pResponseStatus_ } -- | Monitoring information for one or more instances. uirsInstanceMonitorings :: Lens' UnmonitorInstancesResponse [InstanceMonitoring] uirsInstanceMonitorings = lens _uirsInstanceMonitorings (\ s a -> s{_uirsInstanceMonitorings = a}) . _Default . _Coerce; -- | The response status code. uirsResponseStatus :: Lens' UnmonitorInstancesResponse Int uirsResponseStatus = lens _uirsResponseStatus (\ s a -> s{_uirsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/UnmonitorInstances.hs
mpl-2.0
4,911
0
15
1,000
658
393
265
82
1
{-# LANGUAGE TemplateHaskell #-} -- for HscInterpreted module Mutual1 where import Mutual2
cabrera/ghc-mod
test/data/Mutual1.hs
bsd-3-clause
93
0
3
14
9
7
2
3
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Ros.Turtlesim.SpawnResponse where import qualified Prelude as P import Prelude ((.), (+), (*)) import qualified Data.Typeable as T import Control.Applicative import Ros.Internal.RosBinary import Ros.Internal.Msg.MsgInfo import qualified GHC.Generics as G import qualified Data.Default.Generics as D import Ros.Internal.Msg.SrvInfo import Lens.Family.TH (makeLenses) import Lens.Family (view, set) data SpawnResponse = SpawnResponse { _name :: P.String } deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic) $(makeLenses ''SpawnResponse) instance RosBinary SpawnResponse where put obj' = put (_name obj') get = SpawnResponse <$> get instance MsgInfo SpawnResponse where sourceMD5 _ = "c1f3d28f1b044c871e6eff2e9fc3c667" msgTypeName _ = "turtlesim/SpawnResponse" instance D.Default SpawnResponse instance SrvInfo SpawnResponse where srvMD5 _ = "0b2d2e872a8e2887d5ed626f2bf2c561" srvTypeName _ = "turtlesim/Spawn"
acowley/roshask
msgs/Turtlesim/Ros/Turtlesim/SpawnResponse.hs
bsd-3-clause
1,107
1
9
172
264
157
107
29
0
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Data/UnixTime/Conv.hs" #-} {-# LANGUAGE OverloadedStrings, ForeignFunctionInterface #-} module Data.UnixTime.Conv ( formatUnixTime, formatUnixTimeGMT , parseUnixTime, parseUnixTimeGMT , webDateFormat, mailDateFormat , fromEpochTime, toEpochTime , fromClockTime, toClockTime ) where import Control.Applicative import Data.ByteString import Data.ByteString.Unsafe import Data.UnixTime.Types import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc import System.IO.Unsafe (unsafePerformIO) import System.Posix.Types (EpochTime) import System.Time (ClockTime(..)) -- $setup -- >>> import Data.Function (on) foreign import ccall unsafe "c_parse_unix_time" c_parse_unix_time :: CString -> CString -> IO CTime foreign import ccall unsafe "c_parse_unix_time_gmt" c_parse_unix_time_gmt :: CString -> CString -> IO CTime foreign import ccall unsafe "c_format_unix_time" c_format_unix_time :: CString -> CTime -> CString -> CInt -> IO CSize foreign import ccall unsafe "c_format_unix_time_gmt" c_format_unix_time_gmt :: CString -> CTime -> CString -> CInt -> IO CSize ---------------------------------------------------------------- -- | -- Parsing 'ByteString' to 'UnixTime' interpreting as localtime. -- This is a wrapper for strptime_l(). -- Many implementations of strptime_l() do not support %Z and -- some implementations of strptime_l() do not support %z, either. -- 'utMicroSeconds' is always set to 0. parseUnixTime :: Format -> ByteString -> UnixTime parseUnixTime fmt str = unsafePerformIO $ useAsCString fmt $ \cfmt -> useAsCString str $ \cstr -> do sec <- c_parse_unix_time cfmt cstr return $ UnixTime sec 0 -- | -- Parsing 'ByteString' to 'UnixTime' interpreting as GMT. -- This is a wrapper for strptime_l(). -- 'utMicroSeconds' is always set to 0. -- -- >>> parseUnixTimeGMT webDateFormat "Thu, 01 Jan 1970 00:00:00 GMT" -- UnixTime {utSeconds = 0, utMicroSeconds = 0} parseUnixTimeGMT :: Format -> ByteString -> UnixTime parseUnixTimeGMT fmt str = unsafePerformIO $ useAsCString fmt $ \cfmt -> useAsCString str $ \cstr -> do sec <- c_parse_unix_time_gmt cfmt cstr return $ UnixTime sec 0 ---------------------------------------------------------------- -- | -- Formatting 'UnixTime' to 'ByteString' in local time. -- This is a wrapper for strftime_l(). -- 'utMicroSeconds' is ignored. -- The result depends on the TZ environment variable. formatUnixTime :: Format -> UnixTime -> IO ByteString formatUnixTime fmt t = formatUnixTimeHelper c_format_unix_time fmt t {-# INLINE formatUnixTime #-} -- | -- Formatting 'UnixTime' to 'ByteString' in GMT. -- This is a wrapper for strftime_l(). -- 'utMicroSeconds' is ignored. -- -- >>> formatUnixTimeGMT webDateFormat $ UnixTime 0 0 -- "Thu, 01 Jan 1970 00:00:00 GMT" -- >>> let ut = UnixTime 100 200 -- >>> let str = formatUnixTimeGMT "%s" ut -- >>> let ut' = parseUnixTimeGMT "%s" str -- >>> ((==) `on` utSeconds) ut ut' -- True -- >>> ((==) `on` utMicroSeconds) ut ut' -- False formatUnixTimeGMT :: Format -> UnixTime -> ByteString formatUnixTimeGMT fmt t = unsafePerformIO $ formatUnixTimeHelper c_format_unix_time_gmt fmt t {-# INLINE formatUnixTimeGMT #-} -- | -- Helper handling memory allocation for formatUnixTime and formatUnixTimeGMT. formatUnixTimeHelper :: (CString -> CTime -> CString -> CInt -> IO CSize) -> Format -> UnixTime -> IO ByteString formatUnixTimeHelper formatFun fmt (UnixTime sec _) = useAsCString fmt $ \cfmt -> do let siz = 80 ptr <- mallocBytes siz len <- fromIntegral <$> formatFun cfmt sec ptr (fromIntegral siz) ptr' <- reallocBytes ptr (len + 1) unsafePackMallocCString ptr' -- FIXME: Use unsafePackMallocCStringLen from bytestring-0.10.2.0 ---------------------------------------------------------------- -- | -- Format for web (RFC 2616). -- The value is \"%a, %d %b %Y %H:%M:%S GMT\". -- This should be used with 'formatUnixTimeGMT' and 'parseUnixTimeGMT'. webDateFormat :: Format webDateFormat = "%a, %d %b %Y %H:%M:%S GMT" -- | -- Format for e-mail (RFC 5322). -- The value is \"%a, %d %b %Y %H:%M:%S %z\". -- This should be used with 'formatUnixTime' and 'parseUnixTime'. mailDateFormat :: Format mailDateFormat = "%a, %d %b %Y %H:%M:%S %z" ---------------------------------------------------------------- -- | -- From 'EpochTime' to 'UnixTime' setting 'utMicroSeconds' to 0. fromEpochTime :: EpochTime -> UnixTime fromEpochTime sec = UnixTime sec 0 -- | -- From 'UnixTime' to 'EpochTime' ignoring 'utMicroSeconds'. toEpochTime :: UnixTime -> EpochTime toEpochTime (UnixTime sec _) = sec -- | -- From 'ClockTime' to 'UnixTime'. fromClockTime :: ClockTime -> UnixTime fromClockTime (TOD sec psec) = UnixTime sec' usec' where sec' = fromIntegral sec usec' = fromIntegral $ psec `div` 1000000 -- | -- From 'UnixTime' to 'ClockTime'. toClockTime :: UnixTime -> ClockTime toClockTime (UnixTime sec usec) = TOD sec' psec' where sec' = truncate (toRational sec) psec' = fromIntegral $ usec * 1000000
phischu/fragnix
tests/packages/scotty/Data.UnixTime.Conv.hs
bsd-3-clause
5,182
0
13
930
835
465
370
75
1
module ETA.Main.Plugins ( Plugin(..), CommandLineOption, defaultPlugin ) where import ETA.SimplCore.CoreMonad ( CoreToDo, CoreM ) import ETA.TypeCheck.TcRnTypes ( TcPlugin ) -- | 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 }
alexander-at-github/eta
compiler/ETA/Main/Plugins.hs
bsd-3-clause
1,455
0
12
294
151
98
53
13
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} -- Create a source distribution tarball module Stack.SDist ( getSDistTarball , checkSDistTarball , checkSDistTarball' ) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Compression.GZip as GZip import Control.Applicative import Control.Concurrent.Execute (ActionContext(..)) import Control.Monad (unless, void, liftM) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control (liftBaseWith) import Control.Monad.Trans.Resource import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Data (Data, Typeable, cast, gmapT) import Data.Either (partitionEithers) import Data.List import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TLE import Data.Time.Clock.POSIX import Distribution.Package (Dependency (..)) import qualified Distribution.PackageDescription.Check as Check import Distribution.PackageDescription.PrettyPrint (showGenericPackageDescription) import Distribution.Version (simplifyVersionRange, orLaterVersion, earlierVersion) import Distribution.Version.Extra import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Path.IO import Prelude -- Fix redundant import warnings import Stack.Build (mkBaseConfigOpts) import Stack.Build.Execute import Stack.Build.Installed import Stack.Build.Source (loadSourceMap, getPackageConfig) import Stack.Build.Target import Stack.Constants import Stack.Package import Stack.Types import Stack.Types.Internal import System.Directory (getModificationTime, getPermissions, Permissions(..)) import System.IO.Temp (withSystemTempDirectory) import qualified System.FilePath as FP -- | Special exception to throw when you want to fail because of bad results -- of package check. data CheckException = CheckException (NonEmpty Check.PackageCheck) deriving (Typeable) instance Exception CheckException instance Show CheckException where show (CheckException xs) = "Package check reported the following errors:\n" ++ (intercalate "\n" . fmap show . NE.toList $ xs) type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env) -- | Given the path to a local package, creates its source -- distribution tarball. -- -- While this yields a 'FilePath', the name of the tarball, this -- tarball is not written to the disk and instead yielded as a lazy -- bytestring. getSDistTarball :: M env m => Maybe PvpBounds -- ^ Override Config value -> Path Abs Dir -- ^ Path to local package -> m (FilePath, L.ByteString) -- ^ Filename and tarball contents getSDistTarball mpvpBounds pkgDir = do config <- asks getConfig let pvpBounds = fromMaybe (configPvpBounds config) mpvpBounds tweakCabal = pvpBounds /= PvpBoundsNone pkgFp = toFilePath pkgDir lp <- readLocalPackage pkgDir $logInfo $ "Getting file list for " <> T.pack pkgFp (fileList, cabalfp) <- getSDistFileList lp $logInfo $ "Building sdist tarball for " <> T.pack pkgFp files <- normalizeTarballPaths (lines fileList) -- NOTE: Could make this use lazy I/O to only read files as needed -- for upload (both GZip.compress and Tar.write are lazy). -- However, it seems less error prone and more predictable to read -- everything in at once, so that's what we're doing for now: let tarPath isDir fp = either error id (Tar.toTarPath isDir (pkgId FP.</> fp)) packWith f isDir fp = liftIO $ f (pkgFp FP.</> fp) (tarPath isDir fp) packDir = packWith Tar.packDirectoryEntry True packFile fp | tweakCabal && isCabalFp fp = do lbs <- getCabalLbs pvpBounds $ toFilePath cabalfp return $ Tar.fileEntry (tarPath False fp) lbs | otherwise = packWith packFileEntry False fp isCabalFp fp = toFilePath pkgDir FP.</> fp == toFilePath cabalfp tarName = pkgId FP.<.> "tar.gz" pkgId = packageIdentifierString (packageIdentifier (lpPackage lp)) dirEntries <- mapM packDir (dirsFromFiles files) fileEntries <- mapM packFile files return (tarName, GZip.compress (Tar.write (dirEntries ++ fileEntries))) -- | Get the PVP bounds-enabled version of the given cabal file getCabalLbs :: M env m => PvpBounds -> FilePath -> m L.ByteString getCabalLbs pvpBounds fp = do bs <- liftIO $ S.readFile fp (_warnings, gpd) <- readPackageUnresolvedBS Nothing bs (_, _, _, _, sourceMap) <- loadSourceMap AllowNoTargets defaultBuildOpts menv <- getMinimalEnvOverride (installedMap, _, _, _) <- getInstalled menv GetInstalledOpts { getInstalledProfiling = False , getInstalledHaddock = False } sourceMap let gpd' = gtraverseT (addBounds sourceMap installedMap) gpd return $ TLE.encodeUtf8 $ TL.pack $ showGenericPackageDescription gpd' where addBounds :: SourceMap -> InstalledMap -> Dependency -> Dependency addBounds sourceMap installedMap dep@(Dependency cname range) = case lookupVersion (fromCabalPackageName cname) of Nothing -> dep Just version -> Dependency cname $ simplifyVersionRange $ (if toAddUpper && not (hasUpper range) then addUpper version else id) $ (if toAddLower && not (hasLower range) then addLower version else id) range where lookupVersion name = case Map.lookup name sourceMap of Just (PSLocal lp) -> Just $ packageVersion $ lpPackage lp Just (PSUpstream version _ _) -> Just version Nothing -> case Map.lookup name installedMap of Just (_, installed) -> Just (installedVersion installed) Nothing -> Nothing addUpper version = intersectVersionRanges (earlierVersion $ toCabalVersion $ nextMajorVersion version) addLower version = intersectVersionRanges (orLaterVersion (toCabalVersion version)) (toAddLower, toAddUpper) = case pvpBounds of PvpBoundsNone -> (False, False) PvpBoundsUpper -> (False, True) PvpBoundsLower -> (True, False) PvpBoundsBoth -> (True, True) -- | Traverse a data type. gtraverseT :: (Data a,Typeable b) => (Typeable b => b -> b) -> a -> a gtraverseT f = gmapT (\x -> case cast x of Nothing -> gtraverseT f x Just b -> fromMaybe x (cast (f b))) -- | Read in a 'LocalPackage' config. This makes some default decisions -- about 'LocalPackage' fields that might not be appropriate for other -- use-cases. readLocalPackage :: M env m => Path Abs Dir -> m LocalPackage readLocalPackage pkgDir = do cabalfp <- getCabalFileName pkgDir name <- parsePackageNameFromFilePath cabalfp config <- getPackageConfig defaultBuildOpts name (warnings,package) <- readPackage config cabalfp mapM_ (printCabalFileWarning cabalfp) warnings return LocalPackage { lpPackage = package , lpWanted = False -- HACK: makes it so that sdist output goes to a log instead of a file. , lpDir = pkgDir , lpCabalFile = cabalfp -- NOTE: these aren't the 'correct values, but aren't used in -- the usage of this function in this module. , lpTestDeps = Map.empty , lpBenchDeps = Map.empty , lpTestBench = Nothing , lpDirtyFiles = Just Set.empty , lpNewBuildCache = Map.empty , lpFiles = Set.empty , lpComponents = Set.empty , lpUnbuildable = Set.empty } -- | Returns a newline-separate list of paths, and the absolute path to the .cabal file. getSDistFileList :: M env m => LocalPackage -> m (String, Path Abs File) getSDistFileList lp = withCanonicalizedSystemTempDirectory (stackProgName <> "-sdist") $ \tmpdir -> do menv <- getMinimalEnvOverride let bopts = defaultBuildOpts baseConfigOpts <- mkBaseConfigOpts bopts (_, _mbp, locals, _extraToBuild, _sourceMap) <- loadSourceMap NeedTargets bopts runInBase <- liftBaseWith $ \run -> return (void . run) withExecuteEnv menv bopts baseConfigOpts locals [] [] [] -- provide empty list of globals. This is a hack around custom Setup.hs files $ \ee -> withSingleContext runInBase ac ee task Nothing (Just "sdist") $ \_package cabalfp _pkgDir cabal _announce _console _mlogFile -> do let outFile = toFilePath tmpdir FP.</> "source-files-list" cabal False ["sdist", "--list-sources", outFile] contents <- liftIO (readFile outFile) return (contents, cabalfp) where package = lpPackage lp ac = ActionContext Set.empty task = Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskType = TTLocal lp , taskConfigOpts = TaskConfigOpts { tcoMissing = Set.empty , tcoOpts = \_ -> ConfigureOpts [] [] } , taskPresent = Map.empty , taskAllInOne = True } normalizeTarballPaths :: M env m => [FilePath] -> m [FilePath] normalizeTarballPaths fps = do -- TODO: consider whether erroring out is better - otherwise the -- user might upload an incomplete tar? unless (null outsideDir) $ $logWarn $ T.concat [ "Warning: These files are outside of the package directory, and will be omitted from the tarball: " , T.pack (show outsideDir)] return files where (outsideDir, files) = partitionEithers (map pathToEither fps) pathToEither fp = maybe (Left fp) Right (normalizePath fp) normalizePath :: FilePath -> Maybe FilePath normalizePath = fmap FP.joinPath . go . FP.splitDirectories . FP.normalise where go [] = Just [] go ("..":_) = Nothing go (_:"..":xs) = go xs go (x:xs) = (x :) <$> go xs dirsFromFiles :: [FilePath] -> [FilePath] dirsFromFiles dirs = Set.toAscList (Set.delete "." results) where results = foldl' (\s -> go s . FP.takeDirectory) Set.empty dirs go s x | Set.member x s = s | otherwise = go (Set.insert x s) (FP.takeDirectory x) -- | Check package in given tarball. This will log all warnings -- and will throw an exception in case of critical errors. -- -- Note that we temporarily decompress the archive to analyze it. checkSDistTarball :: (MonadIO m, MonadMask m, MonadThrow m, MonadCatch m, MonadLogger m, MonadReader env m, HasEnvConfig env) => Path Abs File -- ^ Absolute path to tarball -> m () checkSDistTarball tarball = withTempTarGzContents tarball $ \pkgDir' -> do pkgDir <- (pkgDir' </>) `liftM` (parseRelDir . FP.takeBaseName . FP.takeBaseName . toFilePath $ tarball) -- ^ drop ".tar" ^ drop ".gz" cabalfp <- getCabalFileName pkgDir name <- parsePackageNameFromFilePath cabalfp config <- getPackageConfig defaultBuildOpts name (gdesc, pkgDesc) <- readPackageDescriptionDir config pkgDir $logInfo $ "Checking package '" <> packageNameText name <> "' for common mistakes" let pkgChecks = Check.checkPackage gdesc (Just pkgDesc) fileChecks <- liftIO $ Check.checkPackageFiles pkgDesc (toFilePath pkgDir) let checks = pkgChecks ++ fileChecks (errors, warnings) = let criticalIssue (Check.PackageBuildImpossible _) = True criticalIssue (Check.PackageDistInexcusable _) = True criticalIssue _ = False in partition criticalIssue checks unless (null warnings) $ $logWarn $ "Package check reported the following warnings:\n" <> T.pack (intercalate "\n" . fmap show $ warnings) case NE.nonEmpty errors of Nothing -> return () Just ne -> throwM $ CheckException ne -- | Version of 'checkSDistTarball' that first saves lazy bytestring to -- temporary directory and then calls 'checkSDistTarball' on it. checkSDistTarball' :: (MonadIO m, MonadMask m, MonadThrow m, MonadCatch m, MonadLogger m, MonadReader env m, HasEnvConfig env) => String -- ^ Tarball name -> L.ByteString -- ^ Tarball contents as a byte string -> m () checkSDistTarball' name bytes = withSystemTempDirectory "stack" $ \tdir -> do tpath <- parseAbsDir tdir npath <- (tpath </>) `liftM` parseRelFile name liftIO $ L.writeFile (toFilePath npath) bytes checkSDistTarball npath withTempTarGzContents :: (MonadIO m, MonadMask m, MonadThrow m) => Path Abs File -- ^ Location of tarball -> (Path Abs Dir -> m a) -- ^ Perform actions given dir with tarball contents -> m a withTempTarGzContents apath f = withSystemTempDirectory "stack" $ \tdir -> do tpath <- parseAbsDir tdir archive <- liftIO $ L.readFile (toFilePath apath) liftIO . Tar.unpack (toFilePath tpath) . Tar.read . GZip.decompress $ archive f tpath -------------------------------------------------------------------------------- -- Copy+modified from the tar package to avoid issues with lazy IO ( see -- https://github.com/commercialhaskell/stack/issues/1344 ) packFileEntry :: FilePath -- ^ Full path to find the file on the local disk -> Tar.TarPath -- ^ Path to use for the tar Entry in the archive -> IO Tar.Entry packFileEntry filepath tarpath = do mtime <- getModTime filepath perms <- getPermissions filepath content <- S.readFile filepath let size = fromIntegral (S.length content) return (Tar.simpleEntry tarpath (Tar.NormalFile (L.fromStrict content) size)) { Tar.entryPermissions = if executable perms then Tar.executableFilePermissions else Tar.ordinaryFilePermissions, Tar.entryTime = mtime } getModTime :: FilePath -> IO Tar.EpochTime getModTime path = do t <- getModificationTime path return . floor . utcTimeToPOSIXSeconds $ t
rubik/stack
src/Stack/SDist.hs
bsd-3-clause
15,020
0
19
3,800
3,631
1,898
1,733
268
10
-- | This module contains a single function that extracts the cabal information about a target file, if any. -- This information can be used to extend the source-directories that are searched to find modules that are -- imported by the target file. {-@ LIQUID "--no-termination" @-} {-@ LIQUID "--diff" @-} {-@ LIQUID "--short-names" @-} {-@ LIQUID "--cabaldir" @-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE CPP #-} module Language.Haskell.Liquid.Cabal (cabalInfo, Info(..)) where import Control.Applicative ((<$>)) import Data.Bits ( shiftL, shiftR, xor ) import Data.Char ( ord ) import Data.List import Data.Maybe import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Word ( Word32 ) import Distribution.Compiler import Distribution.Package import Distribution.PackageDescription import Distribution.PackageDescription.Configuration import Distribution.PackageDescription.Parse import Distribution.Simple.BuildPaths import Distribution.System import Distribution.Verbosity import Language.Haskell.Extension import Numeric ( showHex ) import System.Console.CmdArgs import System.Environment import System.Exit import System.FilePath import System.Directory import System.Info import Language.Haskell.Liquid.Errors -- To use in ghci: -- exitWithPanic = undefined ----------------------------------------------------------------------------------------------- cabalInfo :: FilePath -> IO (Maybe Info) ----------------------------------------------------------------------------------------------- cabalInfo f = do f <- canonicalizePath f cf <- findCabalFile f case cf of Just f -> Just <$> processCabalFile f Nothing -> return Nothing processCabalFile :: FilePath -> IO Info processCabalFile f = do let sandboxDir = sandboxBuildDir (takeDirectory f </> ".cabal-sandbox") b <- doesDirectoryExist sandboxDir let distDir = if b then sandboxDir else "dist" i <- cabalConfiguration f distDir <$> readPackageDescription silent f i <- addPackageDbs =<< canonicalizePaths i whenLoud $ putStrLn $ "Cabal Info: " ++ show i return i ----------------------------------------------------------------------------------------------- findCabalFile :: FilePath -> IO (Maybe FilePath) ----------------------------------------------------------------------------------------------- findCabalFile = fmap listToMaybe . findInPath isCabal where isCabal = (".cabal" ==) . takeExtension findInPath :: (FilePath -> Bool) -> FilePath -> IO [FilePath] findInPath p f = concat <$> mapM (findInDir p) (ancestorDirs f) ancestorDirs :: FilePath -> [FilePath] ancestorDirs = go . takeDirectory where go f | f == f' = [f] | otherwise = f : go f' where f' = takeDirectory f findInDir :: (FilePath -> Bool) -> FilePath -> IO [FilePath] findInDir p dir = do files <- getDirectoryContents dir return [ dir </> f | f <- files, p f ] ----------------------------------------------------------------------------------------------- -- INVARIANT: all FilePaths must be absolute data Info = Info { cabalFile :: FilePath , buildDirs :: [FilePath] , sourceDirs :: [FilePath] , exts :: [Extension] , otherOptions :: [String] , packageDbs :: [String] , packageDeps :: [String] , macroPath :: FilePath } deriving (Show) addPackageDbs :: Info -> IO Info addPackageDbs i = maybe i addDB <$> getSandboxDB i where addDB db = i { packageDbs = T.unpack db : packageDbs i} getSandboxDB :: Info -> IO (Maybe T.Text) getSandboxDB i = do tM <- maybeReadFile $ sandBoxFile i case tM of Just t -> return $ Just $ parsePackageDb t Nothing -> return Nothing -- fmap <$> maybeReadFile (sandBoxFile i) parsePackageDb :: T.Text -> T.Text parsePackageDb t = case dbs of [db] -> T.strip db _ -> exitWithPanic $ "Malformed package-db in sandbox: " ++ show dbs where dbs = mapMaybe (T.stripPrefix pfx) $ T.lines t pfx = "package-db:" -- /Users/rjhala/research/liquid/liquidhaskell/.cabal-sandbox/x86_64-osx-ghc-7.8.3-packages.conf.d maybeReadFile :: FilePath -> IO (Maybe T.Text) maybeReadFile f = do b <- doesFileExist f if b then Just <$> TIO.readFile f else return Nothing sandBoxFile :: Info -> FilePath sandBoxFile i = dir </> "cabal.sandbox.config" where dir = takeDirectory $ cabalFile i dumpPackageDescription :: PackageDescription -> FilePath -> FilePath -> Info dumpPackageDescription pkgDesc file distDir = Info { cabalFile = file , buildDirs = nub (map normalise buildDirs) , sourceDirs = nub (normalise <$> getSourceDirectories buildInfo dir) , exts = nub (concatMap usedExtensions buildInfo) , otherOptions = nub (filter isAllowedOption (concatMap (hcOptions GHC) buildInfo)) , packageDbs = [] , packageDeps = nub [ unPackName n | Dependency n _ <- buildDepends pkgDesc, n /= thisPackage ] , macroPath = macroPath } where (buildDirs, macroPath) = getBuildDirectories pkgDesc distDir buildInfo = allBuildInfo pkgDesc dir = dropFileName file thisPackage = (pkgName . package) pkgDesc unPackName :: PackageName -> String unPackName (PackageName s) = s getSourceDirectories :: [BuildInfo] -> FilePath -> [String] getSourceDirectories buildInfo cabalDir = map (cabalDir </>) (concatMap hsSourceDirs buildInfo) allowedOptions :: [String] allowedOptions = ["-W" ,"-w" ,"-Wall" ,"-fglasgow-exts" ,"-fpackage-trust" ,"-fhelpful-errors" ,"-F" ,"-cpp"] allowedOptionPrefixes :: [String] allowedOptionPrefixes = ["-fwarn-" ,"-fno-warn-" ,"-fcontext-stack=" ,"-firrefutable-tuples" ,"-D" ,"-U" ,"-I" ,"-fplugin=" ,"-fplugin-opt=" ,"-pgm" ,"-opt"] getBuildDirectories :: PackageDescription -> FilePath -> ([String], FilePath) getBuildDirectories pkgDesc distDir = (case library pkgDesc of Just _ -> buildDir : buildDirs Nothing -> buildDirs ,autogenDir </> cppHeaderName) where buildDir = distDir </> "build" autogenDir = buildDir </> "autogen" execBuildDir e = buildDir </> exeName e </> (exeName e ++ "-tmp") buildDirs = autogenDir : map execBuildDir (executables pkgDesc) -- See https://github.com/haskell/cabal/blob/master/cabal-install/Distribution/Client/Sandbox.hs#L137-L158 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) isAllowedOption :: String -> Bool isAllowedOption opt = elem opt allowedOptions || any (`isPrefixOf` opt) allowedOptionPrefixes buildCompiler :: CompilerId buildCompiler = CompilerId buildCompilerFlavor compilerVersion cabalConfiguration :: FilePath -> FilePath -> GenericPackageDescription -> Info cabalConfiguration cabalFile distDir desc = case finalizePackageDescription [] (const True) buildPlatform #if MIN_VERSION_Cabal(1,22,0) (unknownCompilerInfo buildCompiler NoAbiTag) #else buildCompiler #endif [] desc of Right (pkgDesc,_) -> dumpPackageDescription pkgDesc cabalFile distDir Left e -> exitWithPanic $ "Issue with package configuration\n" ++ show e canonicalizePaths :: Info -> IO Info canonicalizePaths i = do buildDirs <- mapM canonicalizePath (buildDirs i) macroPath <- canonicalizePath (macroPath i) return (i { buildDirs = buildDirs, macroPath = macroPath })
mightymoose/liquidhaskell
src/Language/Haskell/Liquid/Cabal.hs
bsd-3-clause
8,651
0
13
2,077
2,048
1,093
955
179
2
import Text.Pandoc import Text.Pandoc.Shared (readDataFile, normalize) import Criterion.Main import Data.List (isSuffixOf) import Text.JSON.Generic readerBench :: Pandoc -> (String, ParserState -> String -> Pandoc) -> Benchmark readerBench doc (name, reader) = let writer = case lookup name writers of Just w -> w Nothing -> error $ "Could not find writer for " ++ name inp = writer defaultWriterOptions{ writerWrapText = True , writerLiterateHaskell = "+lhs" `isSuffixOf` name } doc -- we compute the length to force full evaluation getLength (Pandoc (Meta a b c) d) = length a + length b + length c + length d in bench (name ++ " reader") $ whnf (getLength . reader defaultParserState{ stateSmart = True , stateStandalone = True , stateLiterateHaskell = "+lhs" `isSuffixOf` name }) inp writerBench :: Pandoc -> (String, WriterOptions -> Pandoc -> String) -> Benchmark writerBench doc (name, writer) = bench (name ++ " writer") $ nf (writer defaultWriterOptions{ writerWrapText = True , writerLiterateHaskell = "+lhs" `isSuffixOf` name }) doc normalizeBench :: Pandoc -> [Benchmark] normalizeBench doc = [ bench "normalize - with" $ nf (encodeJSON . normalize) doc , bench "normalize - without" $ nf encodeJSON doc ] main = do inp <- readDataFile (Just ".") "README" let ps = defaultParserState{ stateSmart = True } let doc = readMarkdown ps inp let readerBs = map (readerBench doc) readers defaultMain $ map (writerBench doc) writers ++ readerBs ++ normalizeBench doc
Lythimus/lptv
sites/all/modules/jgm-pandoc-8be6cc2/Benchmark.hs
gpl-2.0
1,890
0
14
651
512
268
244
38
2
-- ----------------------------------------------------------------------------- -- | -- Module : Text.IPv6Addr -- Copyright : Copyright © Michel Boucey 2011-2015 -- License : BSD-Style -- Maintainer : michel.boucey@gmail.com -- -- Dealing with IPv6 address text representations, canonization and manipulations. -- -- ----------------------------------------------------------------------------- module QC.IPv6.Types where import qualified Data.Text as T data IPv6Addr = IPv6Addr T.Text instance Show IPv6Addr where show (IPv6Addr addr) = T.unpack addr data IPv6AddrToken = SixteenBit T.Text -- ^ A four hexadecimal digits group representing a 16-Bit chunk | AllZeros -- ^ An all zeros 16-Bit chunk | Colon -- ^ A separator between 16-Bit chunks | DoubleColon -- ^ A double-colon stands for a unique compression of many consecutive 16-Bit chunks | IPv4Addr T.Text -- ^ An embedded IPv4 address as representation of the last 32-Bit deriving (Eq,Show)
beni55/attoparsec
tests/QC/IPv6/Types.hs
bsd-3-clause
1,036
0
8
213
106
67
39
12
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} module T16204b where import Data.Kind ----- -- singletons machinery ----- data family Sing :: forall k. k -> Type data SomeSing :: Type -> Type where SomeSing :: Sing (a :: k) -> SomeSing k ----- -- (Simplified) GHC.Generics ----- class Generic (a :: Type) where type Rep a :: Type from :: a -> Rep a to :: Rep a -> a class PGeneric (a :: Type) where -- type PFrom ... type PTo (x :: Rep a) :: a class SGeneric k where -- sFrom :: ... sTo :: forall (a :: Rep k). Sing a -> Sing (PTo a :: k) ----- class SingKind k where type Demote k :: Type -- fromSing :: ... toSing :: Demote k -> SomeSing k genericToSing :: forall k. ( SingKind k, SGeneric k, SingKind (Rep k) , Generic (Demote k), Rep (Demote k) ~ Demote (Rep k) ) => Demote k -> SomeSing k genericToSing d = withSomeSing (from d) $ SomeSing . sTo withSomeSing :: forall k r . SingKind k => Demote k -> (forall (a :: k). Sing a -> r) -> r withSomeSing x f = case toSing x of SomeSing x' -> f x'
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T16204b.hs
bsd-3-clause
1,338
2
12
380
420
229
191
-1
-1
module InOut where import PointlessP.Functors import PointlessP.Combinators import PointlessP.Isomorphisms import PointlessP.RecursionPatterns tail' = app . (((curry (app . ((curry ((((inN (_L :: [a])) . (Left . bang)) \/ snd) . distr)) /\ ((ouT (_L :: [a])) . snd)))) . bang) /\ id)
kmate/HaRe
old/testing/pointwiseToPointfree/InOutAST.hs
bsd-3-clause
350
16
27
108
154
88
66
15
1
{- Copyright 2009 Mario Blazevic This file is part of the Streaming Component Combinators (SCC) project. The SCC project 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. SCC 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 SCC. If not, see <http://www.gnu.org/licenses/>. -} -- | Module "Trampoline" defines the pipe computations and their basic building blocks. {-# LANGUAGE ScopedTypeVariables, Rank2Types, MultiParamTypeClasses, TypeFamilies, KindSignatures, FlexibleContexts, FlexibleInstances, OverlappingInstances, UndecidableInstances #-} {- Somewhere we get: Wanted: AncestorFunctor (EitherFunctor a (TryYield a)) d This should not reduce because of overlapping instances If it (erroneously) does reduce, via dfun2 we get Wanted: Functor (EitherFunctor a (TryYield a) Functor d' Functor d d ~ EitherFunctor d' s AncestorFunctor (EitherFunctor a (TryYield a) d' And that gives an infinite loop in the type checker! -} module Main where import Control.Monad (liftM, liftM2, when, ap) -- import Control.Monad.Identity import Debug.Trace (trace) ------------- class (Functor a, Functor d) => AncestorFunctor a d where liftFunctor :: a x -> d x -- dfun 1 instance Functor a => AncestorFunctor a a where liftFunctor = trace "liftFunctor id" . id -- dfun 2 instance ( Functor a , Functor d' , Functor d , d ~ EitherFunctor d' s , AncestorFunctor a d') => AncestorFunctor a d where liftFunctor = LeftF . (trace "liftFunctor other" . liftFunctor :: a x -> d' x) ------------- newtype Identity a = Identity { runIdentity :: a } instance Functor Identity where fmap = liftM instance Applicative Identity where pure = return (<*>) = ap instance Monad Identity where return a = Identity a m >>= k = k (runIdentity m) newtype Trampoline m s r = Trampoline {bounce :: m (TrampolineState m s r)} data TrampolineState m s r = Done r | Suspend! (s (Trampoline m s r)) instance (Monad m, Functor s) => Functor (Trampoline m s) where fmap = liftM instance (Monad m, Functor s) => Applicative (Trampoline m s) where pure = return (<*>) = ap instance (Monad m, Functor s) => Monad (Trampoline m s) where return x = Trampoline (return (Done x)) t >>= f = Trampoline (bounce t >>= apply f) where apply f (Done x) = bounce (f x) apply f (Suspend s) = return (Suspend (fmap (>>= f) s)) data Yield x y = Yield! x y instance Functor (Yield x) where fmap f (Yield x y) = trace "fmap yield" $ Yield x (f y) data Await x y = Await! (x -> y) instance Functor (Await x) where fmap f (Await g) = trace "fmap await" $ Await (f . g) data EitherFunctor l r x = LeftF (l x) | RightF (r x) instance (Functor l, Functor r) => Functor (EitherFunctor l r) where fmap f v = trace "fmap Either" $ case v of LeftF l -> trace "fmap LeftF" $ LeftF (fmap f l) RightF r -> trace "fmap RightF" $ RightF (fmap f r) type TryYield x = EitherFunctor (Yield x) (Await Bool) suspend :: (Monad m, Functor s) => s (Trampoline m s x) -> Trampoline m s x suspend s = Trampoline (return (Suspend s)) yield :: forall m x. Monad m => x -> Trampoline m (Yield x) () yield x = suspend (Yield x (return ())) await :: forall m x. Monad m => Trampoline m (Await x) x await = suspend (Await return) tryYield :: forall m x. Monad m => x -> Trampoline m (TryYield x) Bool tryYield x = suspend (LeftF (Yield x (suspend (RightF (Await return))))) canYield :: forall m x. Monad m => Trampoline m (TryYield x) Bool canYield = suspend (RightF (Await return)) liftBounce :: Monad m => m x -> Trampoline m s x liftBounce = Trampoline . liftM Done fromTrampoline :: Monad m => Trampoline m s x -> m x fromTrampoline t = bounce t >>= \(Done x)-> return x runTrampoline :: Monad m => Trampoline m Maybe x -> m x runTrampoline = fromTrampoline coupleNestedFinite :: (Functor s, Monad m) => Trampoline m (EitherFunctor s (TryYield a)) x -> Trampoline m (EitherFunctor s (Await (Maybe a))) y -> Trampoline m s (x, y) coupleNestedFinite t1 t2 = trace "bounce start" $ liftBounce (liftM2 (,) (bounce t1) (bounce t2)) >>= \(s1, s2)-> trace "bounce end" $ case (s1, s2) of (Done x, Done y) -> return (x, y) (Done x, Suspend (RightF (Await c2))) -> coupleNestedFinite (return x) (c2 Nothing) (Suspend (RightF (LeftF (Yield _ c1))), Done y) -> coupleNestedFinite c1 (return y) (Suspend (RightF (LeftF (Yield x c1))), Suspend (RightF (Await c2))) -> coupleNestedFinite c1 (c2 $ Just x) (Suspend (RightF (RightF (Await c1))), Suspend s2@(RightF Await{})) -> coupleNestedFinite (c1 True) (suspend s2) (Suspend (RightF (RightF (Await c1))), Done y) -> coupleNestedFinite (c1 False) (return y) (Suspend (LeftF s), Done y) -> suspend (fmap (flip coupleNestedFinite (return y)) s) (Done x, Suspend (LeftF s)) -> suspend (fmap (coupleNestedFinite (return x)) s) (Suspend (LeftF s1), Suspend (LeftF s2)) -> suspend (fmap (coupleNestedFinite $ suspend $ LeftF s1) s2) (Suspend (LeftF s1), Suspend (RightF s2)) -> suspend (fmap (flip coupleNestedFinite (suspend $ RightF s2)) s1) (Suspend (RightF s1), Suspend (LeftF s2)) -> suspend (fmap (coupleNestedFinite (suspend $ RightF s1)) s2) local :: forall m l r x. (Monad m, Functor r) => Trampoline m r x -> Trampoline m (EitherFunctor l r) x local (Trampoline mr) = Trampoline (liftM inject mr) where inject :: TrampolineState m r x -> TrampolineState m (EitherFunctor l r) x inject (Done x) = Done x inject (Suspend r) = Suspend (RightF $ fmap local r) out :: forall m l r x. (Monad m, Functor l) => Trampoline m l x -> Trampoline m (EitherFunctor l r) x out (Trampoline ml) = Trampoline (liftM inject ml) where inject :: TrampolineState m l x -> TrampolineState m (EitherFunctor l r) x inject (Done x) = Done x inject (Suspend l) = Suspend (LeftF $ fmap out l) liftOut :: forall m a d x. (Monad m, Functor a, AncestorFunctor a d) => Trampoline m a x -> Trampoline m d x liftOut (Trampoline ma) = trace "liftOut" $ Trampoline (liftM inject ma) where inject :: TrampolineState m a x -> TrampolineState m d x inject (Done x) = Done x inject (Suspend a) = trace "inject suspend" $ Suspend (liftFunctor $ trace "calling fmap" $ fmap liftOut (trace "poking a" a)) data Sink (m :: * -> *) a x = Sink {put :: forall d. (AncestorFunctor (EitherFunctor a (TryYield x)) d) => x -> Trampoline m d Bool, canPut :: forall d. (AncestorFunctor (EitherFunctor a (TryYield x)) d) => Trampoline m d Bool} newtype Source (m :: * -> *) a x = Source {get :: forall d. (AncestorFunctor (EitherFunctor a (Await (Maybe x))) d) => Trampoline m d (Maybe x)} pipe :: forall m a x r1 r2. (Monad m, Functor a) => (Sink m a x -> Trampoline m (EitherFunctor a (TryYield x)) r1) -> (Source m a x -> Trampoline m (EitherFunctor a (Await (Maybe x))) r2) -> Trampoline m a (r1, r2) pipe producer consumer = coupleNestedFinite (producer sink) (consumer source) where sink = Sink {put= liftOut . (local . tryYield :: x -> Trampoline m (EitherFunctor a (TryYield x)) Bool), canPut= liftOut (local canYield :: Trampoline m (EitherFunctor a (TryYield x)) Bool)} :: Sink m a x source = Source (liftOut (local await :: Trampoline m (EitherFunctor a (Await (Maybe x))) (Maybe x))) :: Source m a x pipeProducer sink = do put sink 1 (c, d) <- pipe (\sink'-> do put sink' 2 put sink 3 put sink' 4 return 5) (\source'-> do Just n <- get source' put sink n put sink 6 return n) put sink c put sink d return (c, d) testPipe = print $ runIdentity $ runTrampoline $ do (a, b) <- pipe pipeProducer (\source-> do Just n1 <- get source Just n2 <- get source Just n3 <- get source return (n1, n2, n3)) return (a, b) main = testPipe
urbanslug/ghc
testsuite/tests/simplCore/should_run/T3591.hs
bsd-3-clause
9,342
23
18
2,886
3,213
1,643
1,570
144
11
{-# LANGUAGE GADTs #-} module T7321a where data Exp a where LamE :: (Exp a -> Exp b) -> Exp (Exp a -> Exp b)
urbanslug/ghc
testsuite/tests/gadt/T7321a.hs
bsd-3-clause
113
0
10
29
48
26
22
4
0
module DataNodeProxy where import Network.Socket hiding (send) import Control.Distributed.Process hiding (handleMessage) import Control.Monad (forever) import qualified Data.ByteString.Char8 as B import Data.Binary (encode,decode) import qualified System.IO as IO import System.IO.Streams (InputStream, OutputStream) import qualified System.IO.Streams as Streams import Messages dnDataDir :: String dnDataDir = "./data/" -- We wait for a client to connect with a socket. We then spawn a local -- thread to handle the clients requests. datanodeproxy :: Socket -> ProcessId -> Process () datanodeproxy socket pid = do forever $ do (sock,_) <- liftIO $ accept socket spawnLocal $ do handleClient sock pid liftIO $ sClose sock -- Once the client has connected we simply wait for a message on the socket handleClient :: Socket -> ProcessId -> Process () handleClient sock pid = do (prod,cons) <- liftIO $ Streams.socketToStreams sock Just msg <- liftIO $ Streams.read prod handleMessage (fromByteString msg) (prod,cons) pid -- If the client asks to read a file the proxy will return it directly to him handleMessage :: ClientToDataNode -> (InputStream B.ByteString,OutputStream B.ByteString) -> ProcessId -> Process () handleMessage (CDNRead bid) (prod,cons) pid = liftIO $ do putStrLn $ "Received read request for BlockId: " ++ show bid Streams.withFileAsInput (getFileName bid) (\fprod -> do Streams.connect fprod cons) -- If the client wants to read a file we write it locally and send a CDNWrite to -- the datanode to record the new file handleMessage (CDNWrite bid) (prod,cons) pid = do liftIO $ do Streams.write (Just $ toByteString OK) cons putStrLn $ "Received write request for BlockId: " ++ show bid Streams.withFileAsOutput (getFileName bid) (\fcons -> do Streams.connect prod fcons ) send pid (CDNWriteP bid) getFileName :: BlockId -> FilePath getFileName bid = dnDataDir ++ show bid ++ ".dat"
Ferdinand-vW/HHDFS
src/DataNodeProxy.hs
isc
2,027
0
16
410
535
279
256
38
1
module J2S.AITest ( aiTests ) where import Test.Framework import J2S.AI.RandomTest aiTests :: Test aiTests = testGroup "AI Tests" [ randomTests ]
berewt/J2S
test/J2S/AITest.hs
mit
157
0
6
32
40
24
16
7
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -F -pgmFderive -optF-F #-} module Pyrec.IR.Desugar where -- The IR after desugaring import qualified Data.Map as M import Data.Map (Map) import Data.List import Pyrec.Misc import Pyrec.Error import qualified Pyrec.IR as IR #ifdef TEST import Test.Hspec import Test.Hspec.QuickCheck (prop) import Test.QuickCheck hiding ((.&.)) import Pyrec.TestMisc #endif type Id = String data BindT = BT Unique String Type deriving (Eq, Show) data BindN = BN Unique String deriving (Eq, Show) data Type = T (IR.Type BindN Id Type) | TUnknown deriving (Eq, Show) data Expr = E Unique Type (IR.Expr BindT BindN Id Type Expr) | Constraint Unique Type Expr deriving (Eq, Show) data Error = EndBlockWithDef | SameLineStatements deriving (Eq, Show) type ErrorMessage = Message Error #ifdef TEST {-! deriving instance Arbitrary BindT deriving instance Arbitrary BindN deriving instance Arbitrary Type deriving instance Arbitrary Expr deriving instance Arbitrary Error !-} #endif
kmicklas/pyrec
src/Pyrec/IR/Desugar.hs
mit
1,127
0
9
279
256
153
103
29
0
{-# LANGUAGE OverloadedStrings #-} module Typecrawl.Exporter where import qualified Data.Text as T import qualified Data.Text.IO as TIO import Typecrawl.Types postToHTML :: Post -> T.Text postToHTML (Post t d c) = let title = T.concat ["<h2>", t, "</h2>"] date = T.concat ["<div>", d, "</div>"] in T.unlines [title, date, c] -- | A simple storage in a single HTML page containing -- everything we parsed. storeScrapped :: FilePath -> [Post] -> IO () storeScrapped dest posts = let mainContent = T.unlines . map postToHTML $ posts in TIO.writeFile dest . T.concat $ ["<html>", "<head>", "<meta charset='utf-8'/>", "</head>", "<body>", mainContent, "</body>", "</html>"]
Raveline/typecrawl
lib/Typecrawl/Exporter.hs
mit
1,003
0
11
433
212
120
92
20
1
----------------------------------------------------------------------------- -- -- Module : SGC.Object.Measures.Templates -- Copyright : -- License : MIT -- -- Maintainer : -- Stability : -- Portability : -- -- | -- {-# LANGUAGE TemplateHaskell #-} module SGC.Object.Measures.Templates ( _genMeasurableObjKey ) where import Language.Haskell.TH import PhyQ import SGC.Object import Data.Typeable (Typeable) ----------------------------------------------------------------------------- _genMeasurableObjKey :: (PhysicalQuantity q) => String -> q -> DecsQ _genMeasurableObjKey name' q = do let obj' = mkName "obj" t' = mkName "t" m' = mkName "m" v' = mkName "v" qt' = mkName $ quantityName q name = mkName $ "Obj" ++ name' has' = mkName $ "Has" ++ name' readF' = mkName $ "read" ++ name' getF' = mkName $ "get" ++ name' writeF' = mkName $ "write" ++ name' updateF' = mkName $ "update" ++ name' updateValF' = mkName $ "update" ++ name' ++ "Value" obj = varT obj' t = varT t' m = varT m' v = varT v' qt = conT qt' k = conT name has = conT has' kExpr = conE name data' <- dataD (cxt []) name [PlainTV v'] Nothing [normalC name []] (cxt []) instK <- instanceD (cxt [ [t|Typeable $v|] ]) [t|ObjectKey ($k $v)|] [ tySynInstD (mkName "KeyValue") $ tySynEqn [[t|$k $v|]] [t|Measurable $qt $v|] ] hasConstr <- tySynD (mkName $ "Has" ++ name') [PlainTV obj', PlainTV t', PlainTV m', PlainTV v'] [t|ObjectHas $obj $m $t '[$k $v]|] let fConstr c = forallT [PlainTV obj', PlainTV m', PlainTV v'] (cxt [ [t|$has $obj $c $m $v|] ]) fClauses e = [clause [] (normalB e) []] mkF fname c sig e = sequence [ sigD fname $ fConstr c sig , funD fname $ fClauses e ] readFunc <- mkF readF' [t|Any|] [t|$obj -> $m (Measurable $qt $v)|] [e|readValue $kExpr|] getFunc <- mkF getF' [t|Const|] [t|$obj -> Measurable $qt $v|] [e|getConst $kExpr|] writeFunc <- mkF writeF' [t|Var|] [t|Measurable $qt $v -> $obj -> $m ()|] [e|writeVar $kExpr|] updateFunc <- mkF updateF' [t|Var|] [t|(Measurable $qt $v -> Measurable $qt $v) -> $obj -> $m ()|] [e|updateVar $kExpr|] updateValFunc <- mkF updateValF' [t|Var|] [t|($v -> $v) -> $obj -> $m ()|] [e|updateVar $kExpr . fmap|] return $ [data', instK, hasConstr] ++ readFunc ++ getFunc ++ writeFunc ++ updateFunc ++ updateValFunc -----------------------------------------------------------------------------
fehu/hsgc
SGC/Object/Measures/Templates.hs
mit
2,997
0
13
1,049
756
428
328
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} import System.Environment (getArgs) import Network.Transport import Network.Transport.AMQP (createTransport, AMQPParameters(..)) import Network.AMQP (openConnection) import Control.Monad.State (evalStateT, modify, get) import Control.Monad (forever) import Control.Exception import Control.Monad.IO.Class (liftIO) import qualified Data.Map.Strict as Map (empty, insert, delete, elems) import qualified Data.ByteString.Char8 as BSC (pack) import qualified Data.Text as T import Data.Monoid main :: IO () main = do server:_ <- getArgs conn <- openConnection "localhost" "/" "guest" "guest" let amqpTransport = AMQPParameters conn "multicast" (Just . T.pack $ server) transport <- createTransport amqpTransport Right endpoint <- newEndPoint transport putStrLn $ "Chat server ready at " ++ (show . endPointAddressToByteString . address $ endpoint) go endpoint `catch` \(e :: SomeException) -> do print e closeEndPoint endpoint where go endpoint = flip evalStateT Map.empty . forever $ do event <- liftIO $ receive endpoint liftIO $ print $ "Received: " <> show event case event of ConnectionOpened cid _ addr -> do liftIO $ print $ "Connection opened with ID " <> show cid get >>= \clients -> liftIO $ do Right conn <- connect endpoint addr ReliableOrdered defaultConnectHints send conn [BSC.pack . show . Map.elems $ clients] close conn modify $ Map.insert cid (endPointAddressToByteString addr) ConnectionClosed cid -> do liftIO $ print $ "Connection closed with ID " <> show cid modify $ Map.delete cid ErrorEvent (TransportError (EventConnectionLost addr) msg) -> do liftIO $ do print $ "Connection lost with " <> show addr print msg
iconnect/network-transport-amqp
examples/ChatServer.hs
mit
1,869
0
25
402
568
287
281
43
3
module CastManagement where import System.IO.Unsafe import Data.Unique import Data.List import Data.String.Utils import TypeSystem import Static import TypeSystemForCC import FinalType import FlowDiscovery import CastInsertion import LazyUD as LUD import LazyD as LD sigOfdynamic :: Signature sigOfdynamic = [Decl "ground" "o" Nothing Nothing [Simple "typ"], Decl "getGroundOf" "o" Nothing Nothing [Simple "typ", Simple "typ"], Decl "sameGround" "o" Nothing Nothing [Simple "typ", Simple "typ"], Decl "error" "o" Nothing Nothing [Simple "term"] -- Decl "equal" "o" Nothing [Simple "term", Simple "term"] ] castManagement :: CastStrategy -> TypeSystem -> TypeSystem castManagement strategy (Ts sig rules) = renameToStepTickedIFNECESSARY (extend (castManagementGeneral strategy (Ts sig rules)) (Ts [] (concat (map (castForOperators strategy (Ts sig rules)) (onlyDeconstructorsOfHigher sig))))) castManagementGeneral :: CastStrategy -> TypeSystem -> TypeSystem castManagementGeneral strategy (Ts sig rules) = case strategy of LazyUDTwo -> (Ts sig ((LUD.valuesDefinitions sig) ++ LUD.blameIsError_rule ++ LUD.castManagement_rules ++ (LUD.auxiliaryDefinitions sig))) LazyDTwo -> (Ts sig ((LD.valuesDefinitions sig) ++ LD.blameIsError_rule ++ LD.castManagement_rules ++ LD.auxiliaryDefinitions)) -- Only deconstructors of higher order types () castForOperators :: CastStrategy -> TypeSystem -> SignatureEntry -> [Rule] castForOperators strategy (Ts sig rules) (Decl c typ contraInfo contexts entries) = case (searchRuleByPredAndName (Ts sig rules) typeOfCC c) of (Rule premises conclusion) -> case conclusion of (Formula pred strings interms outterms) -> let canonical = (extractCanonicalType (Rule premises conclusion) premises) in let substitutions = substitutionsFromCanonical canonical (enc "" canonical) in let pkgSub = (makePkg sig (Rule substitutions conclusion)) in let flowPremises = (flowPremisesFromCasts pkgSub c canonical) in let pkgFlow = (makePkg sig (Rule flowPremises conclusion)) in let newTypeAnnotations = replaceTypeAnnotationWith pkgSub (head interms) in let newAssignedType = (destinationType pkgSub (head outterms)) in let newConclusion = (Formula pred strings [newTypeAnnotations] [newAssignedType]) in (extractOperationalRule (addWholeCast pkgFlow (castInsertion_rule sig (Rule ((map (castIrreplaceable canonical) premises) ++ flowPremises) newConclusion))) pkgFlow canonical (head interms)) -- in let (complement, leftovers) = (complementRules result flowPremises) in case result of (Rule resultPrems resultConcl) -> (Rule (resultPrems ++ leftovers) resultConcl):complement addWholeCast :: Package -> Rule -> Rule addWholeCast pkg (Rule premises conclusion) = let originalTerm = getFirstInputOfPremise conclusion in let [castTerm,provedType] = getOutputsOfPremise conclusion in let newAssignedType = (destinationType pkg provedType) in (Rule [] (Formula typeOfCI [] [originalTerm] [makeCastTerm (replaceDeconstructingTerm pkg castTerm (Var "V")) provedType newAssignedType, newAssignedType])) --error ((show pkg) ++ (show provedType) ++ (show newAssignedType) ++ (show (Rule [] (Formula typeOfCI [] [originalTerm] [makeCastTerm (replaceDeconstructingTerm pkg castTerm (Var "V")) provedType newAssignedType, newAssignedType])))) -- error ((show (castTerm)) ++ (show ((replaceDeconstructingTerm pkg castTerm (Var "V"))))) castIrreplaceable :: Term -> Premise -> Premise castIrreplaceable canonical premise = case premise of { (Hypothetical (Formula pred1 strings1 interms1 [typ]) (Formula pred2 strings2 [Application var applied] outterms2)) -> if elem typ (varsOf canonical) then (Hypothetical (Formula pred1 strings1 interms1 [typ]) (Formula pred2 strings2 [Application var (makeCastTerm applied typ (enc "" typ))] outterms2)) else premise ; otherwise -> premise } extractOperationalRule :: Rule -> Package -> Term -> Term -> [Rule] extractOperationalRule (Rule premises conclusion) pkg canonical original = let castOnV = makeCastTerm (Var "V") (enc "" canonical) canonical in case conclusion of (Formula pred strings intermsRule outtermRule) -> let target = (head outtermRule) in [(Rule [(Formula "value" [] [(Var "V")] [])] (Formula "step" [] [replaceDeconstructingTerm pkg original castOnV] [target]))] substitutionsFromCanonical :: Term -> Term -> [Premise] substitutionsFromCanonical (Constructor c1 terms1) (Constructor c2 terms2) = (zipWith makeFlow terms1 terms2) extractCanonicalType :: Rule -> [Premise] -> Term extractCanonicalType cc [] = error ("ERROR extractCanonicalType: I did not find a deconstructed type in the rule" ++ (show cc)) extractCanonicalType cc (premise:rest) = case premise of (Formula pred info interms outterms) -> if pred == typeOfCC then case (head outterms) of { (Constructor c terms) -> (Constructor c terms) ; otherwise -> extractCanonicalType cc rest } else extractCanonicalType cc rest flowPremisesFromCasts :: Package -> String -> Term -> [Premise] flowPremisesFromCasts pkg c_app canonical = case canonical of (Constructor c_arrow terms) -> let encArguments = map (enc "") terms in let split = contravariantArguments pkg c_arrow in (zipWith makeFlow (take split terms) (take split encArguments)) ++ (zipWith makeFlow (drop split encArguments) (drop split terms)) replaceTypeAnnotationWith :: Package -> Term -> Term replaceTypeAnnotationWith pkg (Constructor c terms) = let numero = numberOfTypeAnnotations (pkg_getSig pkg) c in let newTerms = (map (destinationType pkg) (take numero terms)) ++ (drop numero terms) in (Constructor c newTerms) complementRules :: Rule -> [Premise] -> ([Rule], [Premise]) complementRules (Rule premises conclusion) flowPremises = let leftovers = (flowPremises \\ (flowsInside (getFirstOutputOfPremise conclusion))) in ((map createComplementRule leftovers), leftovers) where createComplementRule = \premise -> (Rule [Negated premise] (Formula "step" [] [(getFirstInputOfPremise conclusion)] [blame (Var "L")])) flowsInside :: Term -> [Premise] flowsInside (Var variable) = [] flowsInside (Constructor c terms) = (if c == "cast" then [(Formula "flow" [] [(terms !! 1), (terms !! 3) ] []), (Formula "flow" [] [(terms !! 3), (terms !! 1) ] [])] ++ rest else rest) where rest = (concat (map flowsInside terms)) flowsInside (Application term1 term2) = flowsInside term1 ++ flowsInside term2 flowsInside (Bound x) = [] flowsInside (Lambda bound term) = flowsInside term renameToStepTickedIFNECESSARY :: TypeSystem -> TypeSystem renameToStepTickedIFNECESSARY (Ts sig rules) = case searchDeclByName sig "step" of {Nothing -> error "ERROR: There is no predicate step" ; Just entry -> case entry of (Decl c2 typ contraInfo contexts entries) -> case entries of [(Simple "term"),(Simple "term")] -> (Ts sig rules) ; otherwise -> (Ts sig ((map (renamingInRule "step" "step'") (rules)) ++ (wrappedStep' otherwise)))} wrappedStep' :: [TypeEntry] -> [Rule] wrappedStep' typeentries = case findIndices (\x -> (Simple "term") == x) typeentries of [n1, n2] -> [(Rule [Formula "step'" [] [Var "E"] [Var "E'"]] (Formula "step" [] ((Var "E"):createVars) ((Var "E'"):createVars)))] where createVars = map (\n -> Var ("X" ++ (show n))) [1 .. (n2-1)] --(Formula "step" [] (mapi (createvar n1 n2) typeentries) []))] where createvar = \n1 -> \n2 -> \i -> \entry -> if i == n1 then Var "E" else if i == n2 then Var "E'" else Var ("X" ++ (show (i `mod` n2)))
mcimini/Gradualizer
CastManagement.hs
mit
7,430
2
40
1,070
2,413
1,252
1,161
53
3
import Control.Exception import Database.PostgreSQL.Simple (ConnectInfo, close, connect) import Data.Map (toList) import Data.Char (toUpper) import Control.Monad (forM_, when) import Data.Maybe (fromMaybe) import System.Console.CmdArgs (cmdArgsRun) import qualified Utils as UT import qualified Database as DB import qualified CmdArguments as CA -- aux updateUserAccount :: ConnectInfo -> [(UT.User,[UT.Permission])] -> IO () updateUserAccount connectInfo usersConfig = do putStrLn "Updating all user accounts..." bracket (connect connectInfo) close $ \db -> forM_ usersConfig $ \(user,permissions) -> do DB.createUserIfMissing db user DB.updateUserPasswordIfExists db user revokeAllUserPermission :: ConnectInfo -> DB.SchemaPattern -> [(UT.User,[UT.Permission])] -> IO () revokeAllUserPermission connectInfo schemaPattern usersConfig = do putStrLn "Revoking all users permissions..." bracket (connect connectInfo) close $ \db -> forM_ (map (UT.name.fst) usersConfig) $ \uname -> DB.revokeAllUsersPermissionIfExists db schemaPattern uname updateUserPermission :: ConnectInfo -> DB.SchemaPattern -> [(UT.User,[UT.Permission])] -> IO () updateUserPermission connectInfo schemaPattern usersConfig = do putStrLn "Updating all user permissions..." bracket (connect connectInfo) close $ \db -> -- working on each permission forM_ usersConfig $ \(user,permissions) -> forM_ permissions $ \permission -> DB.grantUserPermissionIfExists db schemaPattern user permission transferOwnership :: ConnectInfo -> DB.Username -> DB.Username -> IO () transferOwnership connectInfo unameOld unameNew = do putStrLn $ "Transfering all ownership of " ++ unameOld ++ " to " ++ unameNew ++ "..." bracket (connect connectInfo) close $ \db -> DB.transferAllOwnershipIfExists db unameOld unameNew dropUser :: ConnectInfo -> DB.Username -> IO () dropUser connectInfo uname = do putStrLn $ "Revoking all privileges and dropping " ++ uname ++ "..." bracket (connect connectInfo) close $ \db -> do DB.revokeAllUsersPermissionIfExists db "%" uname DB.dropUserIfExists db uname -- main's methods doUpdateAll :: ConnectInfo -> [(UT.User,[UT.Permission])] -> DB.SchemaPattern -> IO () doUpdateAll connectInfo usersConfig schemaPattern = do updateUserAccount connectInfo usersConfig updateUserPermission connectInfo schemaPattern usersConfig -- doFullUpdateAll means revoke all permission and then update, cost more time but safer. doFullUpdateAll :: ConnectInfo -> [(UT.User,[UT.Permission])] -> DB.SchemaPattern -> IO () doFullUpdateAll connectInfo usersConfig schemaPattern = do revokeAllUserPermission connectInfo schemaPattern usersConfig doUpdateAll connectInfo usersConfig schemaPattern doTransferOwnership :: ConnectInfo -> DB.Username -> DB.Username -> Bool -> IO () doTransferOwnership connectInfo unameOld unameNew force | unameOld `elem` ["rdsdb"] = putStrLn "Transfering this user is prohibited." | force = transferOwnership connectInfo unameOld unameNew | otherwise = do putStrLn $ "About to transfer all ownerships of " ++ unameOld ++ " to " ++ unameNew ++ ". Are you sure? (Y/N)" confirm <- getChar when (toUpper confirm == 'Y') $ transferOwnership connectInfo unameOld unameNew doDropUser :: ConnectInfo -> DB.Username -> Bool -> IO () doDropUser connectInfo uname force | uname `elem` ["rdsdb"] = putStrLn "Deleting this user is prohibited." | force = dropUser connectInfo uname | otherwise = do putStrLn $ "About to remove " ++ uname ++ ". Are you sure? (Y/N)" confirm <- getChar when (toUpper confirm == 'Y') $ dropUser connectInfo uname -- main main :: IO () main = do opts <- cmdArgsRun CA.myModes connectInfo <- UT.readConnectInfo usersConfig <- UT.readUsersConfig case opts of CA.UpdateMode schemaName -> doUpdateAll connectInfo (toList usersConfig) (fromMaybe "%" schemaName) CA.FullUpdateMode schemaName -> doFullUpdateAll connectInfo (toList usersConfig) (fromMaybe "%" schemaName) CA.TransferMode unameOld unameNew force -> doTransferOwnership connectInfo unameOld unameNew force CA.DropMode uname force -> doDropUser connectInfo uname force
zalora/postgresql-user-manager
src/UserPrivilegesManager.hs
mit
4,432
0
15
907
1,203
601
602
82
4
import Control.Monad xsComp :: [(Int, Int)] xsComp = [(x, y) | x <- [1, 2], y <- [6, 7], x + y /= 8] xsComp' :: [(Int, Int)] xsComp' = do x <- [1, 2] y <- [6, 7] guard (x + y /= 8) return (x, y) xsComp'' :: [(Int, Int)] xsComp'' = [1,2] >>= \x -> [6, 7] >>= \y -> guard (x + y /= 8) >> return (x, y) xsComp''' :: [(Int, Int)] xsComp''' = concat (map (\x -> concat (map (\y -> guard (x + y /= 8) >> return (x, y)) [6, 7])) [1, 2]) main = do print $ xsComp print $ xsComp' print $ xsComp'' print $ xsComp'''
kdungs/coursework-functional-programming
11/listMonad.hs
mit
569
0
19
179
353
196
157
22
1
-- GENERATED by C->Haskell Compiler, version 0.16.5 Crystal Seed, 24 Jan 2009 (Haskell) -- Edit the ORIGNAL .chs file instead! {-# LINE 1 "System/NanoMsg/C/NanoMsg.chs" #-}{-# LANGUAGE CPP, ForeignFunctionInterface #-} -- | This module aims at exposing nanomsg function directly to haskell, no api construct except the use of ForeignFreePointers. Function specific documentation is therefore the official nanomsg documentation. An exception is also done for error handling, here we use maybe or either. Note that it is a c2hs module and that returning type of function may contain function parameter when they may be changed (a tuple with firstly function return type then all parameters in order). -- Send and receive function are not set unsafe, this is thread unsafe, but waiting for some issue (during tests) to set them safe and use similar work arround as in zmq binding (nowait all the time but use haskell threadWriteRead to wait in a ghc non blocking thread way). module System.NanoMsg.C.NanoMsg where import System.NanoMsg.C.NanoMsgStruct import Foreign import Foreign.C.Types import Foreign.C.String import Control.Monad((<=<),liftM) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as C import qualified Data.ByteString.Unsafe as U import qualified Data.List as L import System.Posix.Types(Fd) import Control.Concurrent(threadWaitWrite,threadWaitRead) import qualified Data.ByteString as BS import Data.List(foldl') import Control.Monad(foldM,foldM_) import Data.ByteString.Internal(ByteString(PS)) -- #include "nanomsg/transport.h" -- #include "nanomsg/protocol.h" newtype NnSocket = NnSocket CInt deriving (Eq, Show) socketToCInt :: NnSocket -> CInt socketToCInt (NnSocket s) = s newtype NnEndPoint = NnEndPoint CInt deriving (Eq, Show) endPointToCInt :: NnEndPoint -> CInt endPointToCInt (NnEndPoint s) = s data NnError = ENOTSUP | ENOMEM | EPROTONOSUPPORT | ENAMETOOLONG | ENODEV | ENOBUFS | ENETDOWN | EADDRINUSE | EADDRNOTAVAIL | ECONNREFUSED | EINPROGRESS | ENOTSOCK | EAFNOSUPPORT | EPROTO | EAGAIN | EBADF | EINVAL | EINTR | EMFILE | EFAULT | EACCESS | ENETRESET | ENETUNREACH | EHOSTUNREACH | ENOTCONN | EMSGSIZE | ETIMEDOUT | ECONNABORTED | ECONNRESET | ENOPROTOOPT | EISCONN | ETERM | EFSM deriving (Eq,Ord,Show) instance Enum NnError where fromEnum ENOTSUP = 95 fromEnum ENOMEM = 12 fromEnum EPROTONOSUPPORT = 93 fromEnum ENAMETOOLONG = 36 fromEnum ENODEV = 19 fromEnum ENOBUFS = 105 fromEnum ENETDOWN = 100 fromEnum EADDRINUSE = 98 fromEnum EADDRNOTAVAIL = 99 fromEnum ECONNREFUSED = 111 fromEnum EINPROGRESS = 115 fromEnum ENOTSOCK = 88 fromEnum EAFNOSUPPORT = 97 fromEnum EPROTO = 71 fromEnum EAGAIN = 11 fromEnum EBADF = 9 fromEnum EINVAL = 22 fromEnum EINTR = 4 fromEnum EMFILE = 24 fromEnum EFAULT = 14 fromEnum EACCESS = 156384729 fromEnum ENETRESET = 102 fromEnum ENETUNREACH = 101 fromEnum EHOSTUNREACH = 113 fromEnum ENOTCONN = 107 fromEnum EMSGSIZE = 90 fromEnum ETIMEDOUT = 110 fromEnum ECONNABORTED = 103 fromEnum ECONNRESET = 104 fromEnum ENOPROTOOPT = 92 fromEnum EISCONN = 106 fromEnum ETERM = 156384765 fromEnum EFSM = 156384766 toEnum 95 = ENOTSUP toEnum 12 = ENOMEM toEnum 93 = EPROTONOSUPPORT toEnum 36 = ENAMETOOLONG toEnum 19 = ENODEV toEnum 105 = ENOBUFS toEnum 100 = ENETDOWN toEnum 98 = EADDRINUSE toEnum 99 = EADDRNOTAVAIL toEnum 111 = ECONNREFUSED toEnum 115 = EINPROGRESS toEnum 88 = ENOTSOCK toEnum 97 = EAFNOSUPPORT toEnum 71 = EPROTO toEnum 11 = EAGAIN toEnum 9 = EBADF toEnum 22 = EINVAL toEnum 4 = EINTR toEnum 24 = EMFILE toEnum 14 = EFAULT toEnum 156384729 = EACCESS toEnum 102 = ENETRESET toEnum 101 = ENETUNREACH toEnum 113 = EHOSTUNREACH toEnum 107 = ENOTCONN toEnum 90 = EMSGSIZE toEnum 110 = ETIMEDOUT toEnum 103 = ECONNABORTED toEnum 104 = ECONNRESET toEnum 92 = ENOPROTOOPT toEnum 106 = EISCONN toEnum 156384765 = ETERM toEnum 156384766 = EFSM toEnum unmatched = error ("NnError.toEnum: Cannot match " ++ show unmatched) -- TODO instance show with nnStrerror (but with code to be able to reverse) data AddressFamilies = AF_SP | AF_SP_RAW deriving (Eq,Ord,Show) instance Enum AddressFamilies where fromEnum AF_SP = 1 fromEnum AF_SP_RAW = 2 toEnum 1 = AF_SP toEnum 2 = AF_SP_RAW toEnum unmatched = error ("AddressFamilies.toEnum: Cannot match " ++ show unmatched) {-# LINE 85 "System/NanoMsg/C/NanoMsg.chs" #-} data NnTransport = NN_IPC | NN_INPROC | NN_TCP deriving (Eq,Ord,Show) instance Enum NnTransport where fromEnum NN_IPC = (-2) fromEnum NN_INPROC = (-1) fromEnum NN_TCP = (-3) toEnum (-2) = NN_IPC toEnum (-1) = NN_INPROC toEnum (-3) = NN_TCP toEnum unmatched = error ("NnTransport.toEnum: Cannot match " ++ show unmatched) {-# LINE 90 "System/NanoMsg/C/NanoMsg.chs" #-} -- TODO link with their protocol data ProtocolFamilies = NN_PROTO_PUBSUB | NN_PROTO_BUS | NN_PROTO_PAIR | NN_PROTO_PIPELINE | NN_PROTO_REQREP | NN_PROTO_SURVEY deriving (Eq,Ord,Show) instance Enum ProtocolFamilies where fromEnum NN_PROTO_PUBSUB = 2 fromEnum NN_PROTO_BUS = 7 fromEnum NN_PROTO_PAIR = 1 fromEnum NN_PROTO_PIPELINE = 5 fromEnum NN_PROTO_REQREP = 3 fromEnum NN_PROTO_SURVEY = 6 toEnum 2 = NN_PROTO_PUBSUB toEnum 7 = NN_PROTO_BUS toEnum 1 = NN_PROTO_PAIR toEnum 5 = NN_PROTO_PIPELINE toEnum 3 = NN_PROTO_REQREP toEnum 6 = NN_PROTO_SURVEY toEnum unmatched = error ("ProtocolFamilies.toEnum: Cannot match " ++ show unmatched) {-# LINE 98 "System/NanoMsg/C/NanoMsg.chs" #-} data NnProtocol = NN_PUB | NN_SUB | NN_BUS | NN_PAIR | NN_PUSH | NN_PULL | NN_REQ | NN_REP | NN_SURVEYOR | NN_RESPONDENT deriving (Eq,Ord,Show) instance Enum NnProtocol where fromEnum NN_PUB = 32 fromEnum NN_SUB = 33 fromEnum NN_BUS = 112 fromEnum NN_PAIR = 16 fromEnum NN_PUSH = 80 fromEnum NN_PULL = 81 fromEnum NN_REQ = 48 fromEnum NN_REP = 49 fromEnum NN_SURVEYOR = 96 fromEnum NN_RESPONDENT = 97 toEnum 32 = NN_PUB toEnum 33 = NN_SUB toEnum 112 = NN_BUS toEnum 16 = NN_PAIR toEnum 80 = NN_PUSH toEnum 81 = NN_PULL toEnum 48 = NN_REQ toEnum 49 = NN_REP toEnum 96 = NN_SURVEYOR toEnum 97 = NN_RESPONDENT toEnum unmatched = error ("NnProtocol.toEnum: Cannot match " ++ show unmatched) {-# LINE 110 "System/NanoMsg/C/NanoMsg.chs" #-} -- | those constants might be useless, if they are of any use we might consider using c2hs #const instead data NNConstants = NN_SOCKADDR_MAX deriving (Eq,Ord,Show) instance Enum NNConstants where fromEnum NN_SOCKADDR_MAX = 128 toEnum 128 = NN_SOCKADDR_MAX toEnum unmatched = error ("NNConstants.toEnum: Cannot match " ++ show unmatched) {-# LINE 116 "System/NanoMsg/C/NanoMsg.chs" #-} data SolSocket = NN_SOL_SOCKET deriving (Eq,Ord,Show) instance Enum SolSocket where fromEnum NN_SOL_SOCKET = 0 toEnum 0 = NN_SOL_SOCKET toEnum unmatched = error ("SolSocket.toEnum: Cannot match " ++ show unmatched) {-# LINE 120 "System/NanoMsg/C/NanoMsg.chs" #-} data SocketOptions = NN_LINGER | NN_SNDBUF | NN_RCVBUF | NN_SNDTIMEO | NN_RCVTIMEO | NN_RECONNECT_IVL | NN_RECONNECT_IVL_MAX | NN_SNDPRIO | NN_SNDFD | NN_RCVFD | NN_IPV4ONLY deriving (Eq,Ord,Show) instance Enum SocketOptions where fromEnum NN_LINGER = 1 fromEnum NN_SNDBUF = 2 fromEnum NN_RCVBUF = 3 fromEnum NN_SNDTIMEO = 4 fromEnum NN_RCVTIMEO = 5 fromEnum NN_RECONNECT_IVL = 6 fromEnum NN_RECONNECT_IVL_MAX = 7 fromEnum NN_SNDPRIO = 8 fromEnum NN_SNDFD = 10 fromEnum NN_RCVFD = 11 fromEnum NN_IPV4ONLY = 14 toEnum 1 = NN_LINGER toEnum 2 = NN_SNDBUF toEnum 3 = NN_RCVBUF toEnum 4 = NN_SNDTIMEO toEnum 5 = NN_RCVTIMEO toEnum 6 = NN_RECONNECT_IVL toEnum 7 = NN_RECONNECT_IVL_MAX toEnum 8 = NN_SNDPRIO toEnum 10 = NN_SNDFD toEnum 11 = NN_RCVFD toEnum 14 = NN_IPV4ONLY toEnum unmatched = error ("SocketOptions.toEnum: Cannot match " ++ show unmatched) {-# LINE 135 "System/NanoMsg/C/NanoMsg.chs" #-} data SocketReadOptions = NN_DOMAIN | NN_PROTOCOL deriving (Eq,Ord,Show) instance Enum SocketReadOptions where fromEnum NN_DOMAIN = 12 fromEnum NN_PROTOCOL = 13 toEnum 12 = NN_DOMAIN toEnum 13 = NN_PROTOCOL toEnum unmatched = error ("SocketReadOptions.toEnum: Cannot match " ++ show unmatched) {-# LINE 140 "System/NanoMsg/C/NanoMsg.chs" #-} data PubSubOptions = NN_REQ_RESEND_IVL deriving (Eq,Ord,Show) instance Enum PubSubOptions where fromEnum NN_REQ_RESEND_IVL = 1 toEnum 1 = NN_REQ_RESEND_IVL toEnum unmatched = error ("PubSubOptions.toEnum: Cannot match " ++ show unmatched) {-# LINE 144 "System/NanoMsg/C/NanoMsg.chs" #-} data SurveyOptions = NN_SURVEYOR_DEADLINE deriving (Eq,Ord,Show) instance Enum SurveyOptions where fromEnum NN_SURVEYOR_DEADLINE = 1 toEnum 1 = NN_SURVEYOR_DEADLINE toEnum unmatched = error ("SurveyOptions.toEnum: Cannot match " ++ show unmatched) {-# LINE 148 "System/NanoMsg/C/NanoMsg.chs" #-} data ReqRepOptions = NN_SUB_SUBSCRIBE | NN_SUB_UNSUBSCRIBE deriving (Eq,Ord,Show) instance Enum ReqRepOptions where fromEnum NN_SUB_SUBSCRIBE = 1 fromEnum NN_SUB_UNSUBSCRIBE = 2 toEnum 1 = NN_SUB_SUBSCRIBE toEnum 2 = NN_SUB_UNSUBSCRIBE toEnum unmatched = error ("ReqRepOptions.toEnum: Cannot match " ++ show unmatched) {-# LINE 154 "System/NanoMsg/C/NanoMsg.chs" #-} data TcpOptions = NN_TCP_NODELAY deriving (Eq,Ord,Show) instance Enum TcpOptions where fromEnum NN_TCP_NODELAY = 1 toEnum 1 = NN_TCP_NODELAY toEnum unmatched = error ("TcpOptions.toEnum: Cannot match " ++ show unmatched) {-# LINE 158 "System/NanoMsg/C/NanoMsg.chs" #-} -- | internal only class (Enum a, Show a, Eq a) => AllSocketOptions a instance AllSocketOptions ReqRepOptions instance AllSocketOptions SurveyOptions instance AllSocketOptions PubSubOptions instance AllSocketOptions SocketOptions instance AllSocketOptions TcpOptions instance AllSocketOptions SocketReadOptions -- | internal only class (Enum a, Show a, Eq a) => AllLevelOptions a instance AllLevelOptions NnProtocol instance AllLevelOptions SolSocket instance AllLevelOptions NnTransport data SndRcvFlags = NN_DONTWAIT deriving (Eq,Ord,Show) instance Enum SndRcvFlags where fromEnum NN_DONTWAIT = 1 toEnum 1 = NN_DONTWAIT toEnum unmatched = error ("SndRcvFlags.toEnum: Cannot match " ++ show unmatched) {-# LINE 179 "System/NanoMsg/C/NanoMsg.chs" #-} flagsToCInt :: Enum a => [a] -> CInt flagsToCInt b = L.foldl' (\ac en -> ac + cIntFromEnum en ) 0 b rFlagsToCInt :: Enum a => [a] -> (CInt,Bool) rFlagsToCInt b = let f = L.foldl' (\ac en -> ac + cIntFromEnum en ) 0 b in if (nN_DONTWAIT .&. f) == 0 then (nN_DONTWAIT `xor` f, True) else (f, False) sFlagsToCInt :: Enum a => [a] -> (CInt,Bool) sFlagsToCInt = rFlagsToCInt cIntToEnum :: Enum a => CInt -> a cIntToEnum = toEnum . fromIntegral cIntFromEnum :: Enum a => a -> CInt cIntFromEnum = fromIntegral . fromEnum peekInt :: (Storable a, Integral a) => Ptr a -> IO Int peekInt = (liftM fromIntegral) . peek -- TODO inline withPStorable :: (Storable a) => a -> (Ptr a -> IO b) -> IO b withPStorable i r = alloca (\p -> poke p i >> r p) withPStorable' :: (Storable a) => a -> (Ptr c -> IO b) -> IO b withPStorable' i r = alloca (\p -> poke p i >> r (castPtr p)) withPIntegral :: (Storable a, Num a, Integral c) => c -> (Ptr a -> IO b) -> IO b withPIntegral i = withPStorable (fromIntegral i) --withPForeign :: ForeignPtr () -> (Ptr () -> IO b) -> IO b --withPForeign fp r = withForeignPtr fp (\p -> alloca (\pp -> poke pp p >> r (castPtr pp))) withPPtr :: Ptr () -> (Ptr () -> IO b) -> IO b withPPtr p r = alloca (\pp -> poke pp p >> r (castPtr pp)) foreignFree :: Ptr a -> IO(ForeignPtr a) foreignFree = newForeignPtr finalizerFree foreignVoid :: Ptr () -> IO(ForeignPtr ()) foreignVoid = newForeignPtr finalizerFree foreignPMsg :: Ptr () -> IO(ForeignPtr ()) foreignPMsg pv = do v <- peek (castPtr pv) free pv newForeignPtr nnFunPtrFreeMsg v pVoid :: Ptr () -> IO(Ptr ()) pVoid pv = do v <- peek (castPtr pv) free pv return v foreignFreeMsg :: Ptr () -> IO(Either NnError (ForeignPtr ())) foreignFreeMsg = either (return . Left) (return . Right <=< newForeignPtr nnFunPtrFreeMsg) <=< errorFromNewPointer cPackCString :: CString -> IO ByteString cPackCString = C.packCString ucPackCString :: Ptr a -> IO ByteString ucPackCString = C.packCString . castPtr uPackCString :: CString -> IO ByteString uPackCString = U.unsafePackCString uuPackCString :: Ptr a -> IO ByteString uuPackCString = U.unsafePackCString . castPtr errorFromRetCode :: CInt -> IO(Maybe NnError) errorFromRetCode r = if r < 0 then nnErrno >>= return . Just else return Nothing errorFromNewPointer :: Ptr () -> IO(Either NnError (Ptr ())) errorFromNewPointer ptr = if ptr == nullPtr then nnErrno >>= return . Left else return $ Right ptr errorFromLength :: CInt -> IO(Either NnError Int) errorFromLength r = if r < 0 then nnErrno >>= return . Left else (return . Right . fromIntegral) r errorFromSocket :: CInt -> IO(Either NnError NnSocket) errorFromSocket r = if r < 0 then nnErrno >>= return . Left else (return . Right . NnSocket) r errorFromEndPoint :: CInt -> IO(Either NnError NnEndPoint) errorFromEndPoint r = if r < 0 then nnErrno >>= return . Left else (return . Right . NnEndPoint) r nnErrno :: IO ((NnError)) nnErrno = nnErrno'_ >>= \res -> let {res' = cIntToEnum res} in return (res') {-# LINE 265 "System/NanoMsg/C/NanoMsg.chs" #-} -- Mostly useless as c2hs uses macro, so no mapping from Int values to Enum nnSymbol :: (Int) -> IO ((String), (Int)) nnSymbol a1 = let {a1' = fromIntegral a1} in alloca $ \a2' -> nnSymbol'_ a1' a2' >>= \res -> peekCString res >>= \res' -> peekInt a2'>>= \a2'' -> return (res', a2'') {-# LINE 267 "System/NanoMsg/C/NanoMsg.chs" #-} nnStrerror :: (NnError) -> IO ((String)) nnStrerror a1 = let {a1' = cIntFromEnum a1} in nnStrerror'_ a1' >>= \res -> peekCString res >>= \res' -> return (res') {-# LINE 268 "System/NanoMsg/C/NanoMsg.chs" #-} dummy' :: IO () dummy' = nnTerm {-# LINE 271 "System/NanoMsg/C/NanoMsg.chs" #-} -- type of allocation is transport dependant -- see transport implementation --> for haskell api link it to the transport used -- TODO (tricky??) nnAllocmsg' :: (Int) -> (Int) -> IO ((Either NnError (ForeignPtr ()))) nnAllocmsg' a1 a2 = let {a1' = fromIntegral a1} in let {a2' = fromIntegral a2} in nnAllocmsg''_ a1' a2' >>= \res -> foreignFreeMsg res >>= \res' -> return (res') {-# LINE 274 "System/NanoMsg/C/NanoMsg.chs" #-} nnAllocmsg :: (Int) -> (Int) -> IO ((Either NnError (Ptr ()))) nnAllocmsg a1 a2 = let {a1' = fromIntegral a1} in let {a2' = fromIntegral a2} in nnAllocmsg'_ a1' a2' >>= \res -> errorFromNewPointer res >>= \res' -> return (res') {-# LINE 275 "System/NanoMsg/C/NanoMsg.chs" #-} -- do not use if nnAllocmsg' used nnFreemsg :: (Ptr ()) -> IO ((Maybe NnError)) nnFreemsg a1 = let {a1' = id a1} in nnFreemsg'_ a1' >>= \res -> errorFromRetCode res >>= \res' -> return (res') {-# LINE 278 "System/NanoMsg/C/NanoMsg.chs" #-} cmsgFirstHdr :: (NNMsgHdr) -> IO ((Maybe NNCMsgHdr)) cmsgFirstHdr a1 = fromMsgHdr a1 $ \a1' -> cmsgFirstHdr'_ a1' >>= \res -> maybeCMsg res >>= \res' -> return (res') {-# LINE 280 "System/NanoMsg/C/NanoMsg.chs" #-} cmsgNxtHdr :: (NNMsgHdr) -> (NNCMsgHdr) -> IO ((Maybe NNCMsgHdr)) cmsgNxtHdr a1 a2 = fromMsgHdr a1 $ \a1' -> fromCMsgHdr a2 $ \a2' -> cmsgNxtHdr'_ a1' a2' >>= \res -> maybeCMsg res >>= \res' -> return (res') {-# LINE 281 "System/NanoMsg/C/NanoMsg.chs" #-} -- | use of byteString for char * here. Note that Bytestring is copied. -- not we use unsigned char and do a cast ptr : ByteString should not be use with unicode. cmsgData :: (NNCMsgHdr) -> IO ((ByteString)) cmsgData a1 = fromCMsgHdr a1 $ \a1' -> cmsgData'_ a1' >>= \res -> ucPackCString res >>= \res' -> return (res') {-# LINE 283 "System/NanoMsg/C/NanoMsg.chs" #-} -- | unsafe version for efficiency. To test but might be ok. cmsgData' :: (NNCMsgHdr) -> IO ((ByteString)) cmsgData' a1 = fromCMsgHdr a1 $ \a1' -> cmsgData''_ a1' >>= \res -> uuPackCString res >>= \res' -> return (res') {-# LINE 285 "System/NanoMsg/C/NanoMsg.chs" #-} -- | might not be pure in the future but given current nanomsg implementation it is ok cmsgLen :: (Int) -> (Int) cmsgLen a1 = let {a1' = fromIntegral a1} in let {res = cmsgLen'_ a1'} in let {res' = fromIntegral res} in (res') {-# LINE 287 "System/NanoMsg/C/NanoMsg.chs" #-} cmsgLen' :: (Int) -> IO ((Int)) cmsgLen' a1 = let {a1' = fromIntegral a1} in cmsgLen''_ a1' >>= \res -> let {res' = fromIntegral res} in return (res') {-# LINE 288 "System/NanoMsg/C/NanoMsg.chs" #-} -- | might not be pure in the future but given current nanomsg implementation it is ok cmsgSpace :: (Int) -> (Int) cmsgSpace a1 = let {a1' = fromIntegral a1} in let {res = cmsgSpace'_ a1'} in let {res' = fromIntegral res} in (res') {-# LINE 290 "System/NanoMsg/C/NanoMsg.chs" #-} cmsgSpace' :: (Int) -> IO ((Int)) cmsgSpace' a1 = let {a1' = fromIntegral a1} in cmsgSpace''_ a1' >>= \res -> let {res' = fromIntegral res} in return (res') {-# LINE 291 "System/NanoMsg/C/NanoMsg.chs" #-} -- TODO enum for domain??? nnSocket :: (AddressFamilies) -> (NnProtocol) -> IO ((Either NnError NnSocket)) nnSocket a1 a2 = let {a1' = cIntFromEnum a1} in let {a2' = cIntFromEnum a2} in nnSocket'_ a1' a2' >>= \res -> errorFromSocket res >>= \res' -> return (res') {-# LINE 295 "System/NanoMsg/C/NanoMsg.chs" #-} nnClose :: (NnSocket) -> IO ((Maybe NnError)) nnClose a1 = let {a1' = socketToCInt a1} in nnClose'_ a1' >>= \res -> errorFromRetCode res >>= \res' -> return (res') {-# LINE 297 "System/NanoMsg/C/NanoMsg.chs" #-} nnSetsockopt :: (AllSocketOptions a, AllLevelOptions b) => (NnSocket) -> (b) -> (a) -> (Ptr ()) -> (Int) -> IO ((Maybe NnError)) nnSetsockopt a1 a2 a3 a4 a5 = let {a1' = socketToCInt a1} in let {a2' = cIntFromEnum a2} in let {a3' = cIntFromEnum a3} in let {a4' = id a4} in let {a5' = fromIntegral a5} in nnSetsockopt'_ a1' a2' a3' a4' a5' >>= \res -> errorFromRetCode res >>= \res' -> return (res') {-# LINE 299 "System/NanoMsg/C/NanoMsg.chs" #-} withNullPPtr :: (Ptr () -> IO b) -> IO b withNullPPtr r = do pp <- malloc poke pp nullPtr r $ castPtr pp withNullPtr :: (Ptr () -> IO b) -> IO b withNullPtr r = r nullPtr -- | handling of values for options out of c api - we do not allocate memory for return value of option -- and do not send size -- should use a stablepointer?? -- to test thoroughly (doc initiate size and pointer which does not make any sense --{#fun unsafe nn_getsockopt as ^ `(AllSocketOptions a, AllLevelOptions b)' => {socketToCInt `NnSocket', cIntFromEnum `b', cIntFromEnum `a', withNullPtr- `Ptr ()' id, alloca- `Int' peekInt*} -> `Maybe NnError' errorFromRetCode* #} nnGetsockopt :: (AllSocketOptions a, AllLevelOptions b) => (NnSocket) -> (b) -> (a) -> (Ptr ()) -> (Int) -> IO ((Maybe NnError), (Ptr ()), (Int)) nnGetsockopt a1 a2 a3 a4 a5 = let {a1' = socketToCInt a1} in let {a2' = cIntFromEnum a2} in let {a3' = cIntFromEnum a3} in let {a4' = id a4} in withPIntegral a5 $ \a5' -> nnGetsockopt'_ a1' a2' a3' a4' a5' >>= \res -> errorFromRetCode res >>= \res' -> let {a4'' = id a4'} in peekInt a5'>>= \a5'' -> return (res', a4'', a5'') {-# LINE 310 "System/NanoMsg/C/NanoMsg.chs" #-} -- TODO bind an address type to avoid address without :// (in api(one per transport) using NN_SOCKADDR_MAX) nnBind :: (NnSocket) -> (String) -> IO ((Either NnError NnEndPoint)) nnBind a1 a2 = let {a1' = socketToCInt a1} in withCString a2 $ \a2' -> nnBind'_ a1' a2' >>= \res -> errorFromEndPoint res >>= \res' -> return (res') {-# LINE 313 "System/NanoMsg/C/NanoMsg.chs" #-} nnConnect :: (NnSocket) -> (String) -> IO ((Either NnError NnEndPoint)) nnConnect a1 a2 = let {a1' = socketToCInt a1} in withCString a2 $ \a2' -> nnConnect'_ a1' a2' >>= \res -> errorFromEndPoint res >>= \res' -> return (res') {-# LINE 315 "System/NanoMsg/C/NanoMsg.chs" #-} nnShutdown :: (NnSocket) -> (NnEndPoint) -> IO ((Maybe NnError)) nnShutdown a1 a2 = let {a1' = socketToCInt a1} in let {a2' = endPointToCInt a2} in nnShutdown'_ a1' a2' >>= \res -> errorFromRetCode res >>= \res' -> return (res') {-# LINE 317 "System/NanoMsg/C/NanoMsg.chs" #-} -- All recv functions are derived from C2hs generation to enforce nn_dont_wait and depending on set flags wait in haskell (issue with poll c function when using ffi). Normal c2hs receive are kept postfixed B (as Bogus). nnRecvDynB' :: (NnSocket) -> ([SndRcvFlags]) -> IO ((Either NnError Int), (Ptr ())) nnRecvDynB' a1 a4 = let {a1' = socketToCInt a1} in withNullPPtr $ \a2' -> withNnMSG $ \a3' -> let {a4' = flagsToCInt a4} in nnRecvDynB''_ a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> pVoid a2'>>= \a2'' -> return (res', a2'') {-# LINE 320 "System/NanoMsg/C/NanoMsg.chs" #-} nnRecvDynB :: (NnSocket) -> ([SndRcvFlags]) -> IO ((Either NnError Int), (ForeignPtr ())) nnRecvDynB a1 a4 = let {a1' = socketToCInt a1} in withNullPPtr $ \a2' -> withNnMSG $ \a3' -> let {a4' = flagsToCInt a4} in nnRecvDynB'_ a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> foreignPMsg a2'>>= \a2'' -> return (res', a2'') {-# LINE 321 "System/NanoMsg/C/NanoMsg.chs" #-} -- TODO fn with foreign does not make too much sense (should be in api) nnRecvB :: (NnSocket) -> (ForeignPtr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnRecvB a1 a2 a3 a4 = let {a1' = socketToCInt a1} in withForeignPtr a2 $ \a2' -> let {a3' = fromIntegral a3} in let {a4' = flagsToCInt a4} in nnRecvB'_ a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 323 "System/NanoMsg/C/NanoMsg.chs" #-} nnRecvB' :: (NnSocket) -> (Ptr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnRecvB' a1 a2 a3 a4 = let {a1' = socketToCInt a1} in let {a2' = id a2} in let {a3' = fromIntegral a3} in let {a4' = flagsToCInt a4} in nnRecvB''_ a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 324 "System/NanoMsg/C/NanoMsg.chs" #-} nn_recvmsgB :: (NnSocket) -> (NNMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nn_recvmsgB a1 a2 a3 = let {a1' = socketToCInt a1} in fromMsgHdr a2 $ \a2' -> let {a3' = flagsToCInt a3} in nn_recvmsgB'_ a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 326 "System/NanoMsg/C/NanoMsg.chs" #-} nnRecvfmsgB :: (NnSocket) -> (NNFMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnRecvfmsgB a1 a2 a3 = let {a1' = socketToCInt a1} in fromFMsgHdr a2 $ \a2' -> let {a3' = flagsToCInt a3} in nnRecvfmsgB'_ a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 327 "System/NanoMsg/C/NanoMsg.chs" #-} foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recv" nn_recv_c :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recvmsg" nn_recvmsg_c :: (CInt -> ((Ptr ()) -> (CInt -> (IO CInt)))) pollRecFd :: Bool -> CInt -> Ptr () -> CULong -> CInt -> IO CInt pollRecFd True s ptr psize fls = do res <- nn_recv_c s ptr psize fls if res == (-1) then do err <- nnErrno if err == EAGAIN then do getFd NN_RCVFD s >>= threadWaitRead >> pollRecFd True s ptr psize fls else return res else return res pollRecFd False s ptr psize fls = nn_recv_c s ptr psize fls pollRecFdMsg :: Bool -> CInt -> Ptr () -> CInt -> IO CInt pollRecFdMsg True s ptr fls = do res <- nn_recvmsg_c s ptr fls if res == (-1) then do err <- nnErrno if err == EAGAIN then do getFd NN_RCVFD s >>= threadWaitRead >> pollRecFdMsg True s ptr fls else return res else return res pollRecFdMsg False s ptr fls = nn_recvmsg_c s ptr fls pollSndFd :: Bool -> CInt -> Ptr () -> CULong -> CInt -> IO CInt pollSndFd True s ptr psize fls = do res <- nn_send_c s ptr psize fls if res == (-1) then do err <- nnErrno if err == EAGAIN then do getFd NN_SNDFD s >>= threadWaitWrite >> pollSndFd True s ptr psize fls else return res else return res pollSndFd False s ptr psize fls = nn_send_c s ptr psize fls pollSndFdMsg :: Bool -> CInt -> Ptr () -> CInt -> IO CInt pollSndFdMsg True s ptr fls = do res <- nn_sendmsg_c s ptr fls if res == (-1) then do err <- nnErrno if err == EAGAIN then do getFd NN_SNDFD s >>= threadWaitWrite >> pollSndFdMsg True s ptr fls else return res else return res pollSndFdMsg False s ptr fls = nn_sendmsg_c s ptr fls -- TODO manage error (no fd result from getOption) getFd :: (Enum c) => c -> CInt -> IO Fd getFd f s = let sol = cIntFromEnum NN_SOL_SOCKET fdo = cIntFromEnum f fdSize = fromIntegral $ sizeOf (undefined :: Fd) in alloca $ \ptr -> alloca $ \psize -> do poke psize fdSize size <- nnGetsockopt'_ s sol fdo (castPtr (ptr :: Ptr Fd)) psize peek ptr -- boileplate copy from c2hs generated code to include test on dont wait and haskell polling of file descriptor nnRecvDyn' :: (NnSocket) -> ([SndRcvFlags]) -> IO ((Either NnError Int), (Ptr ())) nnRecvDyn' soc fls = let s = socketToCInt soc in withNullPPtr $ \nulptr -> withNnMSG $ \size -> let {(f,w) = rFlagsToCInt fls} in pollRecFd w s nulptr size f >>= \res -> errorFromLength res >>= \res' -> pVoid nulptr>>= \a2'' -> return (res', a2'') nnRecvDyn :: (NnSocket) -> ([SndRcvFlags]) -> IO ((Either NnError Int), (ForeignPtr ())) nnRecvDyn a1 a4 = let {a1' = socketToCInt a1} in withNullPPtr $ \a2' -> withNnMSG $ \a3' -> let {(a4',w) = rFlagsToCInt a4} in pollRecFd w a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> foreignPMsg a2'>>= \a2'' -> return (res', a2'') nnRecv :: (NnSocket) -> (ForeignPtr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnRecv a1 a2 a3 a4 = let {a1' = socketToCInt a1} in withForeignPtr a2 $ \a2' -> let {a3' = fromIntegral a3} in let {(a4',w) = rFlagsToCInt a4} in pollRecFd w a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') nnRecv' :: (NnSocket) -> (Ptr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnRecv' a1 a2 a3 a4 = let {a1' = socketToCInt a1} in let {a2' = id a2} in let {a3' = fromIntegral a3} in let {(a4',w) = rFlagsToCInt a4} in pollRecFd w a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') nnRecvmsg :: (NnSocket) -> (NNMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnRecvmsg a1 a2 a3 = let {a1' = socketToCInt a1} in fromMsgHdr a2 $ \a2' -> let {(a3',w) = rFlagsToCInt a3} in pollRecFdMsg w a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') nnRecvfmsg :: (NnSocket) -> (NNFMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnRecvfmsg a1 a2 a3 = let {a1' = socketToCInt a1} in fromFMsgHdr a2 $ \a2' -> let {(a3',w) = rFlagsToCInt a3} in pollRecFdMsg w a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') -- | type to send not in C (not even storable) nnSendB :: (NnSocket) -> (ForeignPtr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendB a1 a2 a3 a4 = let {a1' = socketToCInt a1} in withForeignPtr a2 $ \a2' -> let {a3' = fromIntegral a3} in let {a4' = flagsToCInt a4} in nnSendB'_ a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 452 "System/NanoMsg/C/NanoMsg.chs" #-} -- | not ForeignFree nnSendB' :: (NnSocket) -> (Ptr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendB' a1 a2 a3 a4 = let {a1' = socketToCInt a1} in let {a2' = id a2} in let {a3' = fromIntegral a3} in let {a4' = flagsToCInt a4} in nnSendB''_ a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 454 "System/NanoMsg/C/NanoMsg.chs" #-} -- | no foreign (deallocate is managed by nanomq) nnSendDynB :: (NnSocket) -> (Ptr ()) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendDynB a1 a2 a4 = let {a1' = socketToCInt a1} in withPPtr a2 $ \a2' -> withNnMSG $ \a3' -> let {a4' = flagsToCInt a4} in nnSendDynB'_ a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 456 "System/NanoMsg/C/NanoMsg.chs" #-} --{#fun unsafe nn_send as nnSendDyn {socketToCInt `NnSocket', withPForeign* `ForeignPtr ()', withNnMSG- `Int', flagsToCInt `[SndRcvFlags]'} -> `Either NnError Int' errorFromLength* #} -- Do no send with foreing free pointer because nn deallocate nnSendmsgB :: (NnSocket) -> (NNMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendmsgB a1 a2 a3 = let {a1' = socketToCInt a1} in fromMsgHdr a2 $ \a2' -> let {a3' = flagsToCInt a3} in nnSendmsgB'_ a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 459 "System/NanoMsg/C/NanoMsg.chs" #-} nnSendfmsgB :: (NnSocket) -> (NNFMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendfmsgB a1 a2 a3 = let {a1' = socketToCInt a1} in fromFMsgHdr a2 $ \a2' -> let {a3' = flagsToCInt a3} in nnSendfmsgB'_ a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 460 "System/NanoMsg/C/NanoMsg.chs" #-} foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_send" nn_send_c :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_sendmsg" nn_sendmsg_c :: (CInt -> ((Ptr ()) -> (CInt -> (IO CInt)))) -- same as with receive (issue with poll) -- | type to send not in C (not even storable) nnSend :: (NnSocket) -> (ForeignPtr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSend a1 a2 a3 a4 = let {a1' = socketToCInt a1} in withForeignPtr a2 $ \a2' -> let {a3' = fromIntegral a3} in let {(a4',w) = sFlagsToCInt a4} in pollSndFd w a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') -- | not ForeignFree nnSend' :: (NnSocket) -> (Ptr ()) -> (Int) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSend' a1 a2 a3 a4 = let {a1' = socketToCInt a1} in let {a2' = id a2} in let {a3' = fromIntegral a3} in let {(a4',w) = sFlagsToCInt a4} in pollSndFd w a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') {-# LINE 315 "System/NanoMsg/C/NanoMsg.chs" #-} -- | no foreign (deallocate is managed by nanomq) nnSendDyn :: (NnSocket) -> (Ptr ()) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendDyn a1 a2 a4 = let {a1' = socketToCInt a1} in withPPtr a2 $ \a2' -> withNnMSG $ \a3' -> let {(a4',w) = sFlagsToCInt a4} in pollSndFd w a1' a2' a3' a4' >>= \res -> errorFromLength res >>= \res' -> return (res') nnSendmsg :: (NnSocket) -> (NNMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendmsg a1 a2 a3 = let {a1' = socketToCInt a1} in fromMsgHdr a2 $ \a2' -> let {(a3',w) = sFlagsToCInt a3} in pollSndFdMsg w a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') nnSendfmsg :: (NnSocket) -> (NNFMsgHdr) -> ([SndRcvFlags]) -> IO ((Either NnError Int)) nnSendfmsg a1 a2 a3 = let {a1' = socketToCInt a1} in fromFMsgHdr a2 $ \a2' -> let {(a3',w) = sFlagsToCInt a3} in pollSndFdMsg w a1' a2' a3' >>= \res -> errorFromLength res >>= \res' -> return (res') withFmsghdr :: ForeignPtr a -> (Ptr c -> IO b) -> IO b withFmsghdr f r = withForeignPtr f (r . castPtr) withNnMSG :: Num a => (a -> b) -> b withNnMSG a = a (fromIntegral nN_MSG) -- TODO api with fork (with correct mask) + socket type incompatibilities? nnDevice :: (NnSocket) -> (NnSocket) -> IO ((Maybe NnError)) nnDevice a1 a2 = let {a1' = socketToCInt a1} in let {a2' = socketToCInt a2} in nnDevice'_ a1' a2' >>= \res -> errorFromRetCode res >>= \res' -> return (res') {-# LINE 525 "System/NanoMsg/C/NanoMsg.chs" #-} -- Struct related Code for simplicity and to avoid boilerplate code, this could be refactor in a separate hs2c module with usage of data, or moved in c helper functions. fromMsgHdr :: NNMsgHdr -> (Ptr () -> IO b) -> IO b fromMsgHdr = withPStorable' fromFMsgHdr :: NNFMsgHdr -> (Ptr () -> IO b) -> IO b fromFMsgHdr = withPStorable' fromCMsgHdr :: NNCMsgHdr -> (Ptr () -> IO b) -> IO b fromCMsgHdr = withPStorable' toCMsgHdr :: Ptr () -> IO NNCMsgHdr toCMsgHdr = peek . castPtr maybeCMsg :: Ptr () -> IO (Maybe NNCMsgHdr) maybeCMsg m = if m == nullPtr then return Nothing else toCMsgHdr m >>= (return . Just) -- | MsgHdr helpers newRawMsgHdr :: (Storable s) => s -> IO (Either NnError (Ptr NNCMsgHdr)) newRawMsgHdr s = do let totle = sizeOf s mem <- nnAllocmsg (totle) 0 case mem of (Left e) -> return $ Left e (Right ptr') -> do let ptr = castPtr ptr' poke ptr s return $ Right ptr getRawMsgHdr :: (Storable s) => (Ptr NNCMsgHdr) -> IO (Either NnError s) getRawMsgHdr pt = do r <- peek (castPtr pt) er <- nnFreemsg (castPtr pt) -- as bs are copied case er of (Just e) -> return $ Left e Nothing -> return $ Right r newMSgHdr :: [(BS.ByteString, Int, Int)] -> IO (Either NnError (Ptr NNCMsgHdr)) newMSgHdr hdrs = do let totle = foldl' (\acc (bs, _, _)-> acc + BS.length bs + hdrsize) 0 hdrs -- TODO do not use BS.length mem <- nnAllocmsg (totle) 0 case mem of (Left e) -> return $ Left e (Right ptr') -> do let ptr = castPtr ptr' foldM_ (pokeEl (ptr)) 0 hdrs return $ Right ptr where pokeEl :: (Ptr NNCMsgHdr) -> Int -> (BS.ByteString, Int, Int) -> IO Int pokeEl ptr offset ((PS pbs pof ple), lev, typ ) = do poke (ptr `plusPtr` offset) $ NNCMsgHdr (fromIntegral (ple - pof)) (fromIntegral lev) (fromIntegral typ) --pokeElemOff ptr (offset + sizeOf hdr) bs withForeignPtr pbs $ \pbs' -> copyBytes (ptr `plusPtr` (offset + hdrsize)) ((castPtr pbs') `plusPtr` pof) (ple - pof) -- TODO use unsafe bytestring api instead return (offset + hdrsize + (ple - pof)) hdrsize = sizeOf (undefined :: NNCMsgHdr) -- test MsgHdr not nullPtr not here getMSgHdr :: (Ptr NNCMsgHdr) -> Int -> IO (Either NnError [(BS.ByteString, Int, Int)]) getMSgHdr pt nbh = do r <- if nbh == fromIntegral nN_MSG then do id <- peek (castPtr pt) :: IO CUInt return [(BS.pack [],fromIntegral id,0)] else do (_,r) <- foldM (\acc _ -> peekmsg pt acc ) (0,[]) [1..nbh] return r er <- nnFreemsg (castPtr pt) -- as bs are copied case er of (Just e) -> return $ Left e Nothing -> return $ Right $ reverse r where peekmsg ptr' (offset, acc) = do let ptr = ptr' `plusPtr` offset ptch <- peek ptr bs <- BS.packCStringLen (ptr `plusPtr` (sizeOf ptch ), (fromIntegral (cmsglen ptch))) -- here use bytestring PS instead let newoffset = offset + sizeOf ptch + fromIntegral (cmsglen ptch) return (newoffset, (bs, fromIntegral (cmsglev ptch), fromIntegral (cmsgtyp ptch)) : acc) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_errno" nnErrno'_ :: (IO CInt) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_symbol" nnSymbol'_ :: (CInt -> ((Ptr CInt) -> (IO (Ptr CChar)))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_strerror" nnStrerror'_ :: (CInt -> (IO (Ptr CChar))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_term" nnTerm :: (IO ()) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_allocmsg" nnAllocmsg''_ :: (CULong -> (CInt -> (IO (Ptr ())))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_allocmsg" nnAllocmsg'_ :: (CULong -> (CInt -> (IO (Ptr ())))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_freemsg" nnFreemsg'_ :: ((Ptr ()) -> (IO CInt)) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h wfirsthdr" cmsgFirstHdr'_ :: ((Ptr ()) -> (IO (Ptr ()))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h wnxthdr" cmsgNxtHdr'_ :: ((Ptr ()) -> ((Ptr ()) -> (IO (Ptr ())))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h wdata" cmsgData'_ :: ((Ptr ()) -> (IO (Ptr CUChar))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h wdata" cmsgData''_ :: ((Ptr ()) -> (IO (Ptr CUChar))) foreign import ccall safe "System/NanoMsg/C/NanoMsg.chs.h wlen" cmsgLen'_ :: (CULong -> CULong) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h wlen" cmsgLen''_ :: (CULong -> (IO CULong)) foreign import ccall safe "System/NanoMsg/C/NanoMsg.chs.h wspace" cmsgSpace'_ :: (CULong -> CULong) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h wspace" cmsgSpace''_ :: (CULong -> (IO CULong)) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_socket" nnSocket'_ :: (CInt -> (CInt -> (IO CInt))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_close" nnClose'_ :: (CInt -> (IO CInt)) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_setsockopt" nnSetsockopt'_ :: (CInt -> (CInt -> (CInt -> ((Ptr ()) -> (CULong -> (IO CInt)))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_getsockopt" nnGetsockopt'_ :: (CInt -> (CInt -> (CInt -> ((Ptr ()) -> ((Ptr CULong) -> (IO CInt)))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_bind" nnBind'_ :: (CInt -> ((Ptr CChar) -> (IO CInt))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_connect" nnConnect'_ :: (CInt -> ((Ptr CChar) -> (IO CInt))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_shutdown" nnShutdown'_ :: (CInt -> (CInt -> (IO CInt))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recv" nnRecvDynB''_ :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recv" nnRecvDynB'_ :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recv" nnRecvB'_ :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recv" nnRecvB''_ :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recvmsg" nn_recvmsgB'_ :: (CInt -> ((Ptr ()) -> (CInt -> (IO CInt)))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_recvmsg" nnRecvfmsgB'_ :: (CInt -> ((Ptr ()) -> (CInt -> (IO CInt)))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_send" nnSendB'_ :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_send" nnSendB''_ :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_send" nnSendDynB'_ :: (CInt -> ((Ptr ()) -> (CULong -> (CInt -> (IO CInt))))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_sendmsg" nnSendmsgB'_ :: (CInt -> ((Ptr ()) -> (CInt -> (IO CInt)))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_sendmsg" nnSendfmsgB'_ :: (CInt -> ((Ptr ()) -> (CInt -> (IO CInt)))) foreign import ccall unsafe "System/NanoMsg/C/NanoMsg.chs.h nn_device" nnDevice'_ :: (CInt -> (CInt -> (IO CInt)))
cheme/nanomsg-hs
System/NanoMsg/C/NanoMsg.hs
mit
40,752
36
25
9,081
12,785
6,794
5,991
-1
-1
-- Emit to stdout a series of dot(1) edges specifying dependencies. -- "A -> B" means "A depends on B". -- -- Build with 'ghc dependency-graph.hs' -- -- Input is a text file containing lines as follows: -- (some indentation) (some extraneous text) (file-A) in (some directory) -- (some extra indentation) (some extraneous text) (file-B) in (some directory) -- (some indentation matching the first line above) (some extraneous text) (file-C) in (some directory) -- -- This means that file-A depends on file-B, but neither file-A nor file-B depend on file-C. -- -- Sample: -- Helios.MigrationTool.Common.AssemblyUtils.GetAssemblyList() Information: 0 : Processing SXA.Compass.Config.ViewModel.dll in C:\Program Files (x86)\Allscripts Sunrise\Clinical Manager Client\7.2.5575.0\ -- Helios.MigrationTool.Common.AssemblyUtils.GetAssemblyList() Information: 0 : Adding C:\Program Files (x86)\Allscripts Sunrise\Clinical Manager Client\7.2.5575.0\SXA.Compass.Config.ViewModel.dll (IsPresent=true) to assemblyList at beginning of GetAssemblyListEx() -- Helios.MigrationTool.Common.AssemblyUtils.GetAssemblyList() Information: 0 : Processing SXA.Compass.Config.Utils.dll in C:\Program Files (x86)\Allscripts Sunrise\Clinical Manager Client\7.2.5575.0\ -- -- (Need to skip the line containing "Adding", and only process the ones containing "Processing".) import Debug.Trace import System.Environment import Prelude -- hiding (readFile) -- Because we want the System.IO.Strict version import System.IO import Text.Regex.TDFA import qualified Data.Map.Strict as Map import Data.List import Data.Map.Strict as Map ((!)) -- See http://stackoverflow.com/q/32149354/370611 -- toRegex = makeRegexOpts defaultCompOpt{multiline=False} defaultExecOpt -- Escape parens? -- initialFillerRegex :: String -- initialFillerRegex = "Helios.MigrationTool.Common.AssemblyUtils.GetAssemblyList\\(\\) Information: 0 : Processing" -- Regex matching (marking) a line to be processed -- valuableLineRegex :: String -- valuableLineRegex = "\\bProcessing\\b" -- |Regex matching line to be parsed parseLineRegex :: String parseLineRegex = "^(.* Information: 0 : Processing )([^ ]*)[ \t]+in (.*)" -- 3 subexpressions main :: IO() main = do args <- getArgs logContents <- if length args == 0 then do putStrLn "Reading stdin..." getContents else do putStrLn ("Reading " ++ show (args !! 0) ++ "...") handle <- openFile (args !! 0) ReadMode hGetContents handle putStrLn $ unlines $ process (map parseIndent $ lines logContents) $ State {stack=[], edges=Map.empty, nodes=Map.empty} -- |A line of indented text. data IndentedText = IndentedText { indent :: Int, -- ^ The indent (expected to be a number of spaces) text :: String -- ^ The text (expected not to start with a space). } deriving (Show) -- |An edge data Edge = Edge { from :: String, to :: String } deriving (Show, Ord, Eq) -- |Internal pgm state data State = State { stack :: [IndentedText], -- ^ A stack of indented log lines, each at a higher indent level than the -- ^ previous. Head is top of stack. edges :: Map.Map Edge Int, -- ^ A set of edges with frequency counts. Node names will be abbreviated. nodes :: Map.Map String String -- ^ A map from long filepath to abbreviation } deriving (Show) ---------------------------------------------------------------- -- |Parses out the leading indentation of the given String into a count of spaces and the rest of the line parseIndent :: String -> IndentedText parseIndent s = let matchv = (fourth $ (s =~ "^( *)(.*)" :: (String,String,String,[String]))) in IndentedText { indent = length $ matchv !! 0, text = matchv !! 1 } ---------------------------------------------------------------- -- |Process the input, keeping track of state while doing so. process :: [IndentedText] -> State -> [String] process [] state = (edgeDump $ Map.assocs $ edges state) ++ [""] -- blank line ++ (nodeDump $ sortBy nodeSort $ Map.assocs $ nodes state) process (line:rest) state | processable = trace "Processing line" process rest $ newState state line | otherwise = trace "Skipping line" process rest state -- Unprocessable line ==> continue, no state change where processable = text line =~ parseLineRegex :: Bool ---------------------------------------------------------------- -- |Update state while processing. Input (IndentedText) is a line from the log being processed. newState :: State -> IndentedText -> State newState state curLine | (length $ stack state) == 0 = -- initial state State { stack = [curLine], edges = Map.empty, nodes = Map.singleton (fullname $ text curLine) "f0" } | indent curLine > (indent $ head $ stack state) = -- indented State { stack = (curLine:(stack state)), edges = (Map.insertWith (+) (edgeFromTo (head $ stack state) curLine nnmap) 1 (edges state)), nodes = nnmap } | indent curLine == (indent $ head $ stack state) = -- same level State { stack = (curLine:prevStack), edges = if (length prevStack) == 0 then edges state else (Map.insertWith (+) (edgeFromTo (head prevStack) curLine nnmap) 1 (edges state)), nodes = nnmap } | indent curLine < (indent $ head $ stack state) = -- outdented State { stack = (curLine:prevStack), edges = if length prevStack == 0 then edges state -- No new edge, since the stack is empty else (Map.insertWith (+) (edgeFromTo (head prevStack) curLine nnmap) 1 (edges state)), nodes = nnmap } where prevStack = -- Unwind the stack to where its top corresponds to a line with smaller indent than the current line. (dropWhile greaterIndent (stack state)) -- Could use in "==" case? greaterIndent stackLine = (indent stackLine) >= (indent curLine) -- Could drop entire stack, returning [] nnmap = newNodesMap (nodes state) curLine ---------------------------------------------------------------- -- |Returns a new nodes map which is the old nodes map, possibly with a new node inserted from the IndentedText argument. newNodesMap :: Map.Map String String -- ^ Old nodes map -> IndentedText -- ^ Possible source of new node -> Map.Map String String -- ^ New nodes map newNodesMap aMap indText | Map.member key aMap = trace ("Abbrev already exists for key " ++ show key) aMap | otherwise = trace ("Inserting new node abbrev f" ++ (show $ Map.size aMap) ++ " for " ++ show key) Map.insert key ("f" ++ (show $ Map.size aMap)) aMap where key = fullname $ text indText ---------------------------------------------------------------- -- |Returns an "abbreviated edge" in which long filenames generated from the passed IndentedText are replaced with -- |abbreviations from the given map. edgeFromTo :: IndentedText -> IndentedText -> Map.Map String String -> Edge -- edgeFromTo f t m | trace ("edgeFrom " ++ show f ++ " " ++ show t ++ " " ++ show m) False = undefined edgeFromTo aFrom aTo aMap = Edge { from = (aMap ! (fullname $ text aFrom)), to = (aMap ! (fullname $ text aTo)) } ---------------------------------------------------------------- -- fullname :: (String,String,String,[String]) -> String -- fullname (_,_,_,[_,fileName,directoryName]) = directoryName ++ fileName -- |Return full filename from given string matching parseLineRegex fullname :: String -> String fullname aText = let matchv = fourth $ (aText =~ parseLineRegex :: (String,String,String,[String])) in if length matchv == 3 then (matchv !! 2) ++ (matchv !! 1) else error ("Match failed on \"" ++ show aText ++ "\"") ---------------------------------------------------------------- -- |Returns a list of edges as strings, possibly with comments indicating occurrence counts > 1 edgeDump :: [(Edge,Int)] -- ^ List of (edge,count) tuples -> [String] -- ^ List of edges, possibly w/comments -- edgeDump a | trace ("edgedump " ++ show a) False = undefined edgeDump [] = [] edgeDump ((edge,count):rest) | count <= 1 = edgeAsString edge:(edgeDump rest) | otherwise = (edgeAsString edge ++ " [color=red] /* " ++ (show count) ++ " occurrences */"):(edgeDump rest) ---------------------------------------------------------------- -- |Renders an Edge as a string (but not using Show, since this is a one-way rendering for the purposes of whatever -- |external process is going to consume this string. edgeAsString :: Edge -> String edgeAsString e = from e ++ " -> " ++ to e ---------------------------------------------------------------- -- |Return a printable list of strings representing the given Map entries (long filename -> abbreviation), in -- |abbreviation order. nodeDump :: [(String,String)] -> [String] nodeDump nodeAbbrevs = map nodeXform nodeAbbrevs ---------------------------------------------------------------- -- |Printable node representation nodeXform :: (String,String) -> String nodeXform (long,short) = short ++ " is " ++ long ---------------------------------------------------------------- nodeSort :: (String,String) -> (String,String) -> Ordering nodeSort a b | snd a < snd b = LT | snd a == snd b = EQ | otherwise = GT ---------------------------------------------------------------- first :: (a,b,c,d) -> a first (x,_,_,_) = x fourth :: (a,b,c,d) -> d fourth (_,_,_,x) = x
JohnL4/DependencyGraph
dependency-graph.hs
mit
10,033
0
17
2,369
1,868
1,030
838
117
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} module Handler.Api.Run where import Import import qualified Data.Aeson as Aeson import qualified Util.Handler as HandlerUtils import qualified Handler.Run as RunHandler import qualified GHC.Generics as GHC import qualified Glot.Language as Language import Data.Function ((&)) getApiRunLanguagesR :: Handler Value getApiRunLanguagesR = do App{..} <- getYesod renderUrl <- getUrlRender languages & filter Language.isRunnable & map Language.identifier & map (toRunLanguage renderUrl) & Aeson.toJSON & pure data RunLanguage = RunLanguage { name :: Language.Id , url :: Text } deriving (Show, GHC.Generic) instance Aeson.ToJSON RunLanguage toRunLanguage :: (Route App -> Text) -> Language.Id -> RunLanguage toRunLanguage renderUrl langId = RunLanguage { name = langId , url = renderUrl (ApiRunVersionsR langId) } getApiRunVersionsR :: Language.Id -> Handler Value getApiRunVersionsR langId = do maybeLanguage <- HandlerUtils.lookupLanguage langId _ <- HandlerUtils.fromMaybeOrJsonError maybeLanguage $ HandlerUtils.JsonErrorResponse status404 "Language is not supported" renderUrl <- getUrlRender let version = "latest" RunVersion { version = version , url = renderUrl (ApiRunR langId version) } & Aeson.toJSON & pure data RunVersion = RunVersion { version :: Text , url :: Text } deriving (Show, GHC.Generic) instance Aeson.ToJSON RunVersion postApiRunR :: Language.Id -> Text -> Handler Value postApiRunR langId _ = do maybeApiUser <- HandlerUtils.lookupApiUser case fmap apiUserUserId maybeApiUser of Just _ -> RunHandler.postRunR langId Nothing -> sendResponseStatus status401 $ object ["message" .= Aeson.String "A valid access token is required to run code"] getApiRunR :: Language.Id -> Text -> Handler Value getApiRunR _ _ = do sendResponseStatus status405 $ Aeson.object [ "message" .= Aeson.String "Do a POST request instead of GET to run code" ]
prasmussen/glot-www
Handler/Api/Run.hs
mit
2,169
0
15
505
544
284
260
-1
-1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SecurityPolicy (js_allowsConnectionTo, allowsConnectionTo, js_allowsFontFrom, allowsFontFrom, js_allowsFormAction, allowsFormAction, js_allowsFrameFrom, allowsFrameFrom, js_allowsImageFrom, allowsImageFrom, js_allowsMediaFrom, allowsMediaFrom, js_allowsObjectFrom, allowsObjectFrom, js_allowsPluginType, allowsPluginType, js_allowsScriptFrom, allowsScriptFrom, js_allowsStyleFrom, allowsStyleFrom, js_getAllowsEval, getAllowsEval, js_getAllowsInlineScript, getAllowsInlineScript, js_getAllowsInlineStyle, getAllowsInlineStyle, js_getIsActive, getIsActive, js_getReportURIs, getReportURIs, SecurityPolicy, castToSecurityPolicy, gTypeSecurityPolicy) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "($1[\"allowsConnectionTo\"]($2) ? 1 : 0)" js_allowsConnectionTo :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsConnectionTo Mozilla SecurityPolicy.allowsConnectionTo documentation> allowsConnectionTo :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsConnectionTo self url = liftIO (js_allowsConnectionTo (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsFontFrom\"]($2) ? 1 : 0)" js_allowsFontFrom :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsFontFrom Mozilla SecurityPolicy.allowsFontFrom documentation> allowsFontFrom :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsFontFrom self url = liftIO (js_allowsFontFrom (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsFormAction\"]($2) ? 1 : 0)" js_allowsFormAction :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsFormAction Mozilla SecurityPolicy.allowsFormAction documentation> allowsFormAction :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsFormAction self url = liftIO (js_allowsFormAction (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsFrameFrom\"]($2) ? 1 : 0)" js_allowsFrameFrom :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsFrameFrom Mozilla SecurityPolicy.allowsFrameFrom documentation> allowsFrameFrom :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsFrameFrom self url = liftIO (js_allowsFrameFrom (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsImageFrom\"]($2) ? 1 : 0)" js_allowsImageFrom :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsImageFrom Mozilla SecurityPolicy.allowsImageFrom documentation> allowsImageFrom :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsImageFrom self url = liftIO (js_allowsImageFrom (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsMediaFrom\"]($2) ? 1 : 0)" js_allowsMediaFrom :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsMediaFrom Mozilla SecurityPolicy.allowsMediaFrom documentation> allowsMediaFrom :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsMediaFrom self url = liftIO (js_allowsMediaFrom (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsObjectFrom\"]($2) ? 1 : 0)" js_allowsObjectFrom :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsObjectFrom Mozilla SecurityPolicy.allowsObjectFrom documentation> allowsObjectFrom :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsObjectFrom self url = liftIO (js_allowsObjectFrom (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsPluginType\"]($2) ? 1 : 0)" js_allowsPluginType :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsPluginType Mozilla SecurityPolicy.allowsPluginType documentation> allowsPluginType :: (MonadIO m, ToJSString type') => SecurityPolicy -> type' -> m Bool allowsPluginType self type' = liftIO (js_allowsPluginType (unSecurityPolicy self) (toJSString type')) foreign import javascript unsafe "($1[\"allowsScriptFrom\"]($2) ? 1 : 0)" js_allowsScriptFrom :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsScriptFrom Mozilla SecurityPolicy.allowsScriptFrom documentation> allowsScriptFrom :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsScriptFrom self url = liftIO (js_allowsScriptFrom (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsStyleFrom\"]($2) ? 1 : 0)" js_allowsStyleFrom :: JSRef SecurityPolicy -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsStyleFrom Mozilla SecurityPolicy.allowsStyleFrom documentation> allowsStyleFrom :: (MonadIO m, ToJSString url) => SecurityPolicy -> url -> m Bool allowsStyleFrom self url = liftIO (js_allowsStyleFrom (unSecurityPolicy self) (toJSString url)) foreign import javascript unsafe "($1[\"allowsEval\"] ? 1 : 0)" js_getAllowsEval :: JSRef SecurityPolicy -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsEval Mozilla SecurityPolicy.allowsEval documentation> getAllowsEval :: (MonadIO m) => SecurityPolicy -> m Bool getAllowsEval self = liftIO (js_getAllowsEval (unSecurityPolicy self)) foreign import javascript unsafe "($1[\"allowsInlineScript\"] ? 1 : 0)" js_getAllowsInlineScript :: JSRef SecurityPolicy -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsInlineScript Mozilla SecurityPolicy.allowsInlineScript documentation> getAllowsInlineScript :: (MonadIO m) => SecurityPolicy -> m Bool getAllowsInlineScript self = liftIO (js_getAllowsInlineScript (unSecurityPolicy self)) foreign import javascript unsafe "($1[\"allowsInlineStyle\"] ? 1 : 0)" js_getAllowsInlineStyle :: JSRef SecurityPolicy -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.allowsInlineStyle Mozilla SecurityPolicy.allowsInlineStyle documentation> getAllowsInlineStyle :: (MonadIO m) => SecurityPolicy -> m Bool getAllowsInlineStyle self = liftIO (js_getAllowsInlineStyle (unSecurityPolicy self)) foreign import javascript unsafe "($1[\"isActive\"] ? 1 : 0)" js_getIsActive :: JSRef SecurityPolicy -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.isActive Mozilla SecurityPolicy.isActive documentation> getIsActive :: (MonadIO m) => SecurityPolicy -> m Bool getIsActive self = liftIO (js_getIsActive (unSecurityPolicy self)) foreign import javascript unsafe "$1[\"reportURIs\"]" js_getReportURIs :: JSRef SecurityPolicy -> IO (JSRef DOMStringList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicy.reportURIs Mozilla SecurityPolicy.reportURIs documentation> getReportURIs :: (MonadIO m) => SecurityPolicy -> m (Maybe DOMStringList) getReportURIs self = liftIO ((js_getReportURIs (unSecurityPolicy self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SecurityPolicy.hs
mit
8,768
110
11
1,416
1,667
904
763
135
1
-- lazy.hs -- Demonstrates concepts of laziness in Haskell -- Weak Head Normal Form f = let (x, y) = (length [1..5], reverse "hello") in (x, y) g = let (x, y) = (undefined, undefined) in 2 head' ::[a] -> a head' ~x = undefined head' ~(x:xs) = x
gitrookie/functionalcode
code/Haskell/snippets/lazy.hs
mit
258
0
11
62
116
63
53
7
1
doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y doubleSmallNumber x = if x > 100 then x else x*2 removeNonUppercase :: [Char] -> [Char] removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]
axnion/playground
random/haskell/baby.hs
mit
212
0
8
49
106
56
50
5
2
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Graphics.UI.Feckless where import Data.IORef import Data.Map (Map) import Graphics.Rendering.OpenGL import Graphics.UI.Feckless.Manager data FlBar = FlBar data Scope = Global | FecklessBar deriving (Show, Eq) data BarProperty = BarHelp !String | BarSize !Size | BarColor !(Color3 GLfloat) deriving (Show, Eq) type EnumVal a = Map a String class VarType a where instance VarType Bool instance VarType GLfloat instance VarType GLuint instance VarType Float instance VarType a => VarType (Color4 a) instance VarType a => VarType (Vector4 a) instance VarType a => VarType (Vertex3 a) data VarProperty a = VarLabel !String | VarMin !a | VarMax !a | VarStep !a | VarKeyIncr !Char | VarKeyDecr !Char | VarKey !Char | VarHelp !String | VarGroup !String | VarOpened !Bool | VarEnum !(EnumVal a) deriving (Show, Eq) init :: IO () init = return () draw :: IORef Manager -> IO () draw man = return () windowSize :: GLint -> GLint -> IO () windowSize width height = return () newBar :: String -> IO FlBar newBar name = return FlBar define :: Scope -> [BarProperty] -> IO () define scope properties = return () addVarRW :: VarType a => FlBar -> String -- ^ Variable name. -> IORef a -> [VarProperty a] -> IO () addVarRW bar name var properties = return () addVarCB :: VarType a => FlBar -> String -> (a -> IO b) -- ^ Set var callback. -> IO a -- ^ Get var callback. -> Maybe c -> [VarProperty a] -> IO () addVarCB bar name setter getter clientData properties = return ()
triplepointfive/fecklessbar
src/Graphics/UI/Feckless.hs
mit
1,742
0
13
470
593
298
295
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} module Control.Eff.Log.Simple ( SimpleLog , Severity(..) , logTo , debug , info , notice , warning , error , critical , alert , panic ) where import Control.Eff (Eff, Member) import Control.Eff.Log import Data.Monoid ((<>)) import Data.Typeable (Typeable) import Prelude hiding (error) import System.Log.FastLogger (ToLogStr, toLogStr) data Severity = DEBUG | INFO | NOTICE | WARNING | ERROR | CRITICAL | ALERT | PANIC deriving (Bounded, Enum, Eq, Ord, Read, Show, Typeable) type SimpleLog a = Log (Severity, a) instance ToLogStr Severity where toLogStr DEBUG = "DEBUG" toLogStr INFO = "INFO" toLogStr NOTICE = "NOTICE" toLogStr WARNING = "WARNING" toLogStr ERROR = "ERROR" toLogStr CRITICAL = "CRITICAL" toLogStr ALERT = "ALERT" toLogStr PANIC = "PANIC" instance ToLogStr a => ToLogStr (Severity, a) where toLogStr (sev, line) = "[" <> toLogStr sev <> "] " <> toLogStr line <> "\n" logTo :: (Typeable l, Member (Log (Severity, l)) r) => Severity -> l -> Eff r () logTo sev line = logE (sev, line) debug :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () debug = logTo DEBUG info :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () info = logTo INFO notice :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () notice = logTo NOTICE warning :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () warning = logTo WARNING error :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () error = logTo ERROR critical :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () critical = logTo CRITICAL alert :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () alert = logTo ALERT panic :: (Typeable l, Member (Log (Severity, l)) r) => l -> Eff r () panic = logTo PANIC
ibotty/log-effect
src/Control/Eff/Log/Simple.hs
mit
2,141
0
10
521
814
449
365
59
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module JoScript.Util.Debug ( printPass , consumeSyntax , consumeBlockPass , consumeLexerPass ) where import Protolude hiding (ByteString, error) import Control.Lens (view) import Control.Monad.Trans.Writer (WriterT, tell, runWriterT) import Data.Aeson ((.=)) import Data.Sequence (singleton) import Data.ByteString.Lazy.Internal (ByteString) import qualified Data.Conduit as C import qualified Data.Aeson as A import qualified Data.Aeson.Encode.Pretty as A import JoScript.Data.Debug import JoScript.Data.Error (Error) import JoScript.Data.Lexer (LexerPass) import JoScript.Data.Block (BlockPass) import JoScript.Data.Syntax (SynModule) import JoScript.Data.Config (DebugKind(..), debugModeText, FileBuildM(..), filename') import JoScript.Util.Conduit (Result, ResultSink) -------------------------------------------------------------- -- exports -- -------------------------------------------------------------- type Impl m v a = ExceptT Error (WriterT (Seq v) (C.Sink (Result v) m)) a consumePass' :: Monad m => (Seq a -> PassDebug) -> ResultSink a m FileDebug consumePass' fn = runImpl impl where runImpl i = runWriterT (runExceptT i) >>= \(error, written) -> do filename <- lift (view filename') pure (FileDebug filename (fn written) (leftToMaybe error)) await :: Monad m => Impl m a (Maybe (Result a)) await = lift (lift C.await) record :: a -> Impl m a () record item = lift (tell (singleton item)) throw :: Error -> Impl m a () throw = throwError impl :: Monad m => Impl m a () impl = await >>= \case Nothing -> pure () Just (Left e) -> throw e Just (Right i) -> record i >> impl consumeBlockPass :: Monad m => ResultSink BlockPass m FileDebug consumeBlockPass = consumePass' PDebugBlock consumeLexerPass :: Monad m => ResultSink LexerPass m FileDebug consumeLexerPass = consumePass' PDebugLexer consumeSyntax :: Monad m => Result SynModule -> FileBuildM m FileDebug consumeSyntax result = impl where output = PDebugSyntax (rightToMaybe result) error = leftToMaybe result impl = view filename' >>= \file -> pure (FileDebug { file, error, output }) printPass :: MonadIO m => Bool -> FileDebug -> m () printPass pretty filedebug = putStrLn (encode filedebug) where encode :: FileDebug -> ByteString encode = if pretty then A.encodePretty' config else A.encode config = A.defConfig { A.confIndent = A.Spaces 2, A.confNumFormat = A.Decimal }
AKST/jo
source/lib/JoScript/Util/Debug.hs
mit
2,551
0
15
466
831
453
378
-1
-1
module Operate.Store where import Util.Datei import qualified System.Posix import qualified Operate.Param as P import Control.Types (toString, fromCGI, File, Wert(..)) import Control.Monad ( when ) import Operate.Logged import Data.Maybe import Data.Char data Type = Instant | Input | Report deriving ( Eq, Ord, Show ) -- | alles: speichert in "latest.input" -- d. h. überschreibt immer -- zur sicherheit auch: von richtigen einsendungen: speicher in "$pid.input" -- d. h. eigentlich kein überschreiben store :: Type -> P.Type -> IO ( String, Maybe File ) store ty p = logged "Operate.store" $ do pid <- fmap show $ System.Posix.getProcessID let flag = case P.mresult p of Just (Okay {}) -> True ; _ -> False mthing = case ty of Input -> P.input p Instant -> fmap show $ P.minstant p Report -> fmap show $ P.report p when flag $ do logged "Operate.store.schreiben" $ mschreiben ( location ty p pid flag ) $ mthing return () f <- mschreiben ( location ty p "latest" flag ) $ mthing return ( pid , fmap fromCGI f ) latest :: Type -> P.Type -> IO String latest ty p = logged "Operate.latest" $ do lesen ( location ty p "latest" False ) load :: Type -> P.Type -> String -> Bool -> IO String load ty p pid flag = logged "Operate.load" $ do lesen ( location ty p pid flag ) location :: Type -> P.Type -> String -> Bool -> Datei location ty p pid flag = Datei { pfad = [ "autotool", "done" , toString $ P.vnr p , toString $ P.anr p , P.sident p , if flag then "OK" else "NO" ] , name = pid , extension = map toLower $ show ty }
marcellussiegburg/autotool
db/src/Operate/Store.hs
gpl-2.0
1,751
4
16
515
591
304
287
39
4
{-# LANGUAGE OverloadedStrings #-} {-| Implementation of the Ganeti confd server functionality. -} {- Copyright (C) 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Monitoring.Server ( main , checkMain , prepMain ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Data.ByteString.Char8 hiding (map, filter, find) import Data.List import qualified Data.Map as Map import Snap.Core import Snap.Http.Server import qualified Text.JSON as J import Control.Concurrent import qualified Ganeti.BasicTypes as BT import Ganeti.Daemon import qualified Ganeti.DataCollectors.CPUload as CPUload import qualified Ganeti.DataCollectors.Diskstats as Diskstats import qualified Ganeti.DataCollectors.Drbd as Drbd import qualified Ganeti.DataCollectors.InstStatus as InstStatus import qualified Ganeti.DataCollectors.Lv as Lv import Ganeti.DataCollectors.Types import qualified Ganeti.Constants as C import Ganeti.Runtime -- * Types and constants definitions -- | Type alias for checkMain results. type CheckResult = () -- | Type alias for prepMain results. type PrepResult = Config Snap () -- | Version of the latest supported http API. latestAPIVersion :: Int latestAPIVersion = C.mondLatestApiVersion -- | A report of a data collector might be stateful or stateless. data Report = StatelessR (IO DCReport) | StatefulR (Maybe CollectorData -> IO DCReport) -- | Type describing a data collector basic information data DataCollector = DataCollector { dName :: String -- ^ Name of the data collector , dCategory :: Maybe DCCategory -- ^ Category (storage, instance, ecc) -- of the collector , dKind :: DCKind -- ^ Kind (performance or status reporting) of -- the data collector , dReport :: Report -- ^ Report produced by the collector , dUpdate :: Maybe (Maybe CollectorData -> IO CollectorData) -- ^ Update operation for stateful collectors. } -- | The list of available builtin data collectors. collectors :: [DataCollector] collectors = [ DataCollector Diskstats.dcName Diskstats.dcCategory Diskstats.dcKind (StatelessR Diskstats.dcReport) Nothing , DataCollector Drbd.dcName Drbd.dcCategory Drbd.dcKind (StatelessR Drbd.dcReport) Nothing , DataCollector InstStatus.dcName InstStatus.dcCategory InstStatus.dcKind (StatelessR InstStatus.dcReport) Nothing , DataCollector Lv.dcName Lv.dcCategory Lv.dcKind (StatelessR Lv.dcReport) Nothing , DataCollector CPUload.dcName CPUload.dcCategory CPUload.dcKind (StatefulR CPUload.dcReport) (Just CPUload.dcUpdate) ] -- * Configuration handling -- | The default configuration for the HTTP server. defaultHttpConf :: FilePath -> FilePath -> Config Snap () defaultHttpConf accessLog errorLog = setAccessLog (ConfigFileLog accessLog) . setCompression False . setErrorLog (ConfigFileLog errorLog) $ setVerbose False emptyConfig -- * Helper functions -- | Check function for the monitoring agent. checkMain :: CheckFn CheckResult checkMain _ = return $ Right () -- | Prepare function for monitoring agent. prepMain :: PrepFn CheckResult PrepResult prepMain opts _ = do accessLog <- daemonsExtraLogFile GanetiMond AccessLog errorLog <- daemonsExtraLogFile GanetiMond ErrorLog return . setPort (maybe C.defaultMondPort fromIntegral (optPort opts)) . maybe id (setBind . pack) (optBindAddress opts) $ defaultHttpConf accessLog errorLog -- * Query answers -- | Reply to the supported API version numbers query. versionQ :: Snap () versionQ = writeBS . pack $ J.encode [latestAPIVersion] -- | Version 1 of the monitoring HTTP API. version1Api :: MVar CollectorMap -> Snap () version1Api mvar = let returnNull = writeBS . pack $ J.encode J.JSNull :: Snap () in ifTop returnNull <|> route [ ("list", listHandler) , ("report", reportHandler mvar) ] -- | Get the JSON representation of a data collector to be used in the collector -- list. dcListItem :: DataCollector -> J.JSValue dcListItem dc = J.JSArray [ J.showJSON $ dName dc , maybe J.JSNull J.showJSON $ dCategory dc , J.showJSON $ dKind dc ] -- | Handler for returning lists. listHandler :: Snap () listHandler = dir "collectors" . writeBS . pack . J.encode $ map dcListItem collectors -- | Handler for returning data collector reports. reportHandler :: MVar CollectorMap -> Snap () reportHandler mvar = route [ ("all", allReports mvar) , (":category/:collector", oneReport mvar) ] <|> errorReport -- | Return the report of all the available collectors. allReports :: MVar CollectorMap -> Snap () allReports mvar = do reports <- mapM (liftIO . getReport mvar) collectors writeBS . pack . J.encode $ reports -- | Takes the CollectorMap and a DataCollector and returns the report for this -- collector. getReport :: MVar CollectorMap -> DataCollector -> IO DCReport getReport mvar collector = case dReport collector of StatelessR r -> r StatefulR r -> do colData <- getColData (dName collector) mvar r colData -- | Returns the data for the corresponding collector. getColData :: String -> MVar CollectorMap -> IO (Maybe CollectorData) getColData name mvar = do m <- readMVar mvar return $ Map.lookup name m -- | Returns a category given its name. -- If "collector" is given as the name, the collector has no category, and -- Nothing will be returned. catFromName :: String -> BT.Result (Maybe DCCategory) catFromName "instance" = BT.Ok $ Just DCInstance catFromName "storage" = BT.Ok $ Just DCStorage catFromName "daemon" = BT.Ok $ Just DCDaemon catFromName "hypervisor" = BT.Ok $ Just DCHypervisor catFromName "default" = BT.Ok Nothing catFromName _ = BT.Bad "No such category" errorReport :: Snap () errorReport = do modifyResponse $ setResponseStatus 404 "Not found" writeBS "Unable to produce a report for the requested resource" error404 :: Snap () error404 = do modifyResponse $ setResponseStatus 404 "Not found" writeBS "Resource not found" -- | Return the report of one collector. oneReport :: MVar CollectorMap -> Snap () oneReport mvar = do categoryName <- maybe mzero unpack <$> getParam "category" collectorName <- maybe mzero unpack <$> getParam "collector" category <- case catFromName categoryName of BT.Ok cat -> return cat BT.Bad msg -> fail msg collector <- case find (\col -> collectorName == dName col) $ filter (\c -> category == dCategory c) collectors of Just col -> return col Nothing -> fail "Unable to find the requested collector" dcr <- liftIO $ getReport mvar collector writeBS . pack . J.encode $ dcr -- | The function implementing the HTTP API of the monitoring agent. monitoringApi :: MVar CollectorMap -> Snap () monitoringApi mvar = ifTop versionQ <|> dir "1" (version1Api mvar) <|> error404 -- | The function collecting data for each data collector providing a dcUpdate -- function. collect :: CollectorMap -> DataCollector -> IO CollectorMap collect m collector = case dUpdate collector of Nothing -> return m Just update -> do let name = dName collector existing = Map.lookup name m new_data <- update existing return $ Map.insert name new_data m -- | Invokes collect for each data collector. collection :: CollectorMap -> IO CollectorMap collection m = foldM collect m collectors -- | The thread responsible for the periodical collection of data for each data -- data collector. collectord :: MVar CollectorMap -> IO () collectord mvar = do m <- takeMVar mvar m' <- collection m putMVar mvar m' threadDelay $ 10^(6 :: Int) * C.mondTimeInterval collectord mvar -- | Main function. main :: MainFn CheckResult PrepResult main _ _ httpConf = do mvar <- newMVar Map.empty _ <- forkIO $ collectord mvar httpServe httpConf . method GET $ monitoringApi mvar
kawamuray/ganeti
src/Ganeti/Monitoring/Server.hs
gpl-2.0
8,704
0
14
1,770
1,897
968
929
166
3
-- | This script generates a man page for patat. {-# LANGUAGE OverloadedStrings #-} import Control.Exception (throw) import Control.Monad (guard) import Control.Monad.Trans (liftIO) import Data.Char (isSpace, toLower) import Data.List (isPrefixOf) import qualified Data.Map as M import Data.Maybe (isJust) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Time as Time import qualified GHC.IO.Encoding as Encoding import Prelude import System.Environment (getEnv) import qualified System.IO as IO import Text.DocTemplates as DT import qualified Text.Pandoc as Pandoc getVersion :: IO String getVersion = dropWhile isSpace . drop 1 . dropWhile (/= ':') . head . filter (\l -> "version:" `isPrefixOf` map toLower l) . map (dropWhile isSpace) . lines <$> readFile "patat.cabal" getPrettySourceDate :: IO String getPrettySourceDate = do epoch <- getEnv "SOURCE_DATE_EPOCH" utc <- Time.parseTimeM True locale "%s" epoch :: IO Time.UTCTime return $ Time.formatTime locale "%B %d, %Y" utc where locale = Time.defaultTimeLocale type Sections = [(Int, T.Text, [Pandoc.Block])] toSections :: Int -> [Pandoc.Block] -> Sections toSections level = go where go [] = [] go (h : xs) = case toSectionHeader h of Nothing -> go xs Just (l, title) -> let (section, cont) = break (isJust . toSectionHeader) xs in (l, title, section) : go cont toSectionHeader :: Pandoc.Block -> Maybe (Int, T.Text) toSectionHeader (Pandoc.Header l _ inlines) = do guard (l <= level) let doc = Pandoc.Pandoc Pandoc.nullMeta [Pandoc.Plain inlines] txt = case Pandoc.runPure (Pandoc.writeMarkdown Pandoc.def doc) of Left err -> throw err -- Bad! Right x -> x return (l, txt) toSectionHeader _ = Nothing fromSections :: Sections -> [Pandoc.Block] fromSections = concatMap $ \(level, title, blocks) -> Pandoc.Header level ("", [], []) [Pandoc.Str title] : blocks reorganizeSections :: Pandoc.Pandoc -> Pandoc.Pandoc reorganizeSections (Pandoc.Pandoc meta0 blocks0) = let sections0 = toSections 2 blocks0 in Pandoc.Pandoc meta0 $ fromSections $ [ (1, "NAME", nameSection) ] ++ [ (1, "SYNOPSIS", s) | (_, _, s) <- lookupSection "Running" sections0 ] ++ [ (1, "DESCRIPTION", []) ] ++ [ (2, n, s) | (_, n, s) <- lookupSection "Controls" sections0 ] ++ [ (2, n, s) | (_, n, s) <- lookupSection "Input format" sections0 ] ++ [ (2, n, s) | (_, n, s) <- lookupSection "Configuration" sections0 ] ++ [ (1, "OPTIONS", s) | (_, _, s) <- lookupSection "Options" sections0 ] ++ [ (1, "SEE ALSO", seeAlsoSection) ] where nameSection = mkPara "patat - Presentations Atop The ANSI Terminal" seeAlsoSection = mkPara "pandoc(1)" mkPara str = [Pandoc.Para [Pandoc.Str str]] lookupSection name sections = [section | section@(_, n, _) <- sections, name == n] simpleContext :: [(T.Text, T.Text)] -> DT.Context T.Text simpleContext = DT.toContext . M.fromList main :: IO () main = Pandoc.runIOorExplode $ do liftIO $ Encoding.setLocaleEncoding Encoding.utf8 let readerOptions = Pandoc.def { Pandoc.readerExtensions = Pandoc.pandocExtensions } source <- liftIO $ T.readFile "README.md" pandoc0 <- Pandoc.readMarkdown readerOptions source template <- Pandoc.compileDefaultTemplate "man" version <- T.pack <$> liftIO getVersion date <- T.pack <$> liftIO getPrettySourceDate let writerOptions = Pandoc.def { Pandoc.writerTemplate = Just template , Pandoc.writerVariables = simpleContext [ ("author", "Jasper Van der Jeugt") , ("title", "patat manual") , ("date", date) , ("footer", "patat v" <> version) , ("section", "1") ] } let pandoc1 = reorganizeSections $ pandoc0 txt <- Pandoc.writeMan writerOptions pandoc1 liftIO $ do T.putStr txt IO.hPutStrLn IO.stderr "Wrote man page."
jaspervdj/patat
extra/make-man.hs
gpl-2.0
4,522
0
17
1,410
1,375
743
632
103
5
{-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} -- we have lots of parsers which don't want signatures; and we have -- uniplate patterns {-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-incomplete-patterns -fno-warn-name-shadowing #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Syntax.Haskell -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- NOTES: -- Note if the layout of the first line (not comments) -- is wrong the parser will only parse what is in the blocks given by Layout.hs module Yi.Syntax.Haskell ( PModule , PModuleDecl , PImport , Exp (..) , Tree , parse , indentScanner ) where import Control.Applicative import Data.Foldable hiding (elem, notElem) import Data.Maybe import Data.List ((\\)) import Yi.IncrementalParse import Yi.Lexer.Alex import Yi.Lexer.Haskell import Yi.Syntax.Layout import Yi.Syntax.Tree import Yi.Syntax import Control.Arrow ((&&&)) indentScanner :: Scanner (AlexState lexState) TT -> Scanner (Yi.Syntax.Layout.State Token lexState) TT indentScanner = layoutHandler startsLayout [(Special '(', Special ')'), (Reserved Let, Reserved In), (Special '[', Special ']'), (Special '{', Special '}')] ignoredToken (Special '<', Special '>', Special '.') isBrace -- HACK: We insert the Special '<', '>', '.', which do not occur in -- normal haskell parsing. -- | Check if a token is a brace, this function is used to -- fix the layout so that do { works correctly isBrace :: TT -> Bool isBrace (Tok br _ _) = Special '{' == br -- | Theese are the tokens ignored by the layout handler. ignoredToken :: TT -> Bool ignoredToken (Tok t _ (Posn{})) = isComment t || t == CppDirective type Tree = PModule type PAtom = Exp type Block = Exp type PGuard = Exp type PModule = Exp type PModuleDecl = Exp type PImport = Exp -- | Exp can be expression or declaration data Exp t = PModule { comments :: [t] , progMod :: Maybe (PModule t) } | ProgMod { modDecl :: PModuleDecl t , body :: PModule t -- ^ The module declaration part } | Body { imports :: Exp t -- [PImport t] , content :: Block t , extraContent :: Block t -- ^ The body of the module } | PModuleDecl { moduleKeyword :: PAtom t , name :: PAtom t , exports :: Exp t , whereKeyword :: Exp t } | PImport { importKeyword :: PAtom t , qual :: Exp t , name' :: PAtom t , as :: Exp t , specification :: Exp t } | TS t [Exp t] -- ^ Type signature | PType { typeKeyword :: PAtom t , typeCons :: Exp t , equal :: PAtom t , btype :: Exp t } -- ^ Type declaration | PData { dataKeyword :: PAtom t , dtypeCons :: Exp t , dEqual :: Exp t , dataRhs :: Exp t } -- ^ Data declaration | PData' { dEqual :: PAtom t , dataCons :: Exp t -- ^ Data declaration RHS } | PClass { cKeyword :: PAtom t -- Can be class or instance , cHead :: Exp t , cwhere :: Exp t -- ^ Class declaration } -- declaration -- declarations and parts of them follow | Paren (PAtom t) [Exp t] (PAtom t) -- ^ A parenthesized, bracked or braced | Block [Exp t] -- ^ A block of things separated by layout | PAtom t [t] -- ^ An atom is a token followed by many comments | Expr [Exp t] -- ^ | PWhere (PAtom t) (Exp t) (Exp t) -- ^ Where clause | Bin (Exp t) (Exp t) -- an error with comments following so we never color comments in wrong -- color. The error has an extra token, the Special '!' token to -- indicate that it contains an error | PError { errorTok :: t , marker :: t , commentList :: [t] -- ^ An wrapper for errors } -- rhs that begins with Equal | RHS (PAtom t) (Exp t) -- ^ Righthandside of functions with = | Opt (Maybe (Exp t)) -- ^ An optional | Modid t [t] -- ^ Module identifier | Context (Exp t) (Exp t) (PAtom t) -- ^ | PGuard [PGuard t] -- ^ Righthandside of functions with | -- the PAtom in PGuard' does not contain any comments | PGuard' (PAtom t) (Exp t) (PAtom t) -- type constructor is just a wrapper to indicate which highlightning to -- use. | TC (Exp t) -- ^ Type constructor -- data constructor same as with the TC constructor | DC (Exp t) -- ^ Data constructor | PLet (PAtom t) (Exp t) (Exp t) -- ^ let expression | PIn t [Exp t] deriving (Show, Foldable) instance IsTree Exp where emptyNode = Expr [] uniplate tree = case tree of (ProgMod a b) -> ([a,b], \[a,b] -> ProgMod a b) (Body x exp exp') -> ([x, exp, exp'], \[x, exp, exp'] -> Body x exp exp') (PModule x (Just e)) -> ([e],\[e] -> PModule x (Just e)) (Paren l g r) -> -- TODO: improve (l:g ++ [r], \(l:gr) -> Paren l (init gr) (last gr)) (RHS l g) -> ([l,g],\[l,g] -> (RHS l g)) (Block s) -> (s,Block) (PLet l s i) -> ([l,s,i],\[l,s,i] -> PLet l s i) (PIn x ts) -> (ts,PIn x) (Expr a) -> (a,Expr) (PClass a b c) -> ([a,b,c],\[a,b,c] -> PClass a b c) (PWhere a b c) -> ([a,b,c],\[a,b,c] -> PWhere a b c) (Opt (Just x)) -> ([x],\[x] -> (Opt (Just x))) (Bin a b) -> ([a,b],\[a,b] -> (Bin a b)) (PType a b c d) -> ([a,b,c,d],\[a,b,c,d] -> PType a b c d) (PData a b c d) -> ([a,b,c,d],\[a,b,c,d] -> PData a b c d) (PData' a b) -> ([a,b] ,\[a,b] -> PData' a b) (Context a b c) -> ([a,b,c],\[a,b,c] -> Context a b c) (PGuard xs) -> (xs,PGuard) (PGuard' a b c) -> ([a,b,c],\[a,b,c] -> PGuard' a b c) (TC e) -> ([e],\[e] -> TC e) (DC e) -> ([e],\[e] -> DC e) PModuleDecl a b c d -> ([a,b,c,d],\[a,b,c,d] -> PModuleDecl a b c d) PImport a b c d e -> ([a,b,c,d,e],\[a,b,c,d,e] -> PImport a b c d e) t -> ([],const t) -- | The parser parse :: P TT (Tree TT) parse = pModule <* eof -- | @pModule@ parse a module pModule :: Parser TT (PModule TT) pModule = PModule <$> pComments <*> optional (pBlockOf' (ProgMod <$> pModuleDecl <*> pModBody <|> pBody)) -- | Parse a body that follows a module pModBody :: Parser TT (PModule TT) pModBody = (exact [startBlock] *> (Body <$> pImports <*> ((pTestTok elems *> pBod) <|> pEmptyBL) <* exact [endBlock] <*> pBod <|> Body <$> noImports <*> ((pBod <|> pEmptyBL) <* exact [endBlock]) <*> pBod)) <|> (exact [nextLine] *> pBody) <|> Body <$> pure emptyNode <*> pEmptyBL <*> pEmptyBL where pBod = Block <$> pBlocks pTopDecl elems = [Special ';', nextLine, startBlock] -- | @pEmptyBL@ A parser returning an empty block pEmptyBL :: Parser TT (Exp TT) pEmptyBL = Block <$> pEmpty -- | Parse a body of a program pBody :: Parser TT (PModule TT) pBody = Body <$> noImports <*> (Block <$> pBlocks pTopDecl) <*> pEmptyBL <|> Body <$> pImports <*> ((pTestTok elems *> (Block <$> pBlocks pTopDecl)) <|> pEmptyBL) <*> pEmptyBL where elems = [nextLine, startBlock] noImports :: Parser TT (Exp TT) noImports = notNext [Reserved Import] *> pure emptyNode where notNext f = testNext $ uncurry (||) . (&&&) isNothing (flip notElem f . tokT . fromJust) -- Helper functions for parsing follows -- | Parse Variables pVarId :: Parser TT (Exp TT) pVarId = pAtom [VarIdent, Reserved Other, Reserved As] -- | Parse VarIdent and ConsIdent pQvarid :: Parser TT (Exp TT) pQvarid = pAtom [VarIdent, ConsIdent, Reserved Other, Reserved As] -- | Parse an operator using please pQvarsym :: Parser TT (Exp TT) pQvarsym = pParen ((:) <$> please (PAtom <$> sym isOperator <*> pComments) <*> pEmpty) -- | Parse any operator isOperator :: Token -> Bool isOperator (Operator _) = True isOperator (ReservedOp _) = True isOperator (ConsOperator _) = True isOperator _ = False -- | Parse a consident pQtycon :: Parser TT (Exp TT) pQtycon = pAtom [ConsIdent] -- | Parse many variables pVars :: Parser TT (Exp TT) pVars = pMany pVarId -- | Parse a nextline token (the nexLine token is inserted by Layout.hs) nextLine :: Token nextLine = Special '.' -- | Parse a startBlock token startBlock :: Token startBlock = Special '<' -- | Parse a endBlock token endBlock :: Token endBlock = Special '>' pEmpty :: Applicative f => f [a] pEmpty = pure [] pToList :: Applicative f => f a -> f [a] pToList = (box <$>) where box x = [x] -- | @sym f@ returns a parser parsing @f@ as a special symbol sym :: (Token -> Bool) -> Parser TT TT sym f = symbol (f . tokT) -- | @exact tokList@ parse anything that is in @tokList@ exact :: [Token] -> Parser TT TT exact = sym . flip elem -- | @please p@ returns a parser parsing either @p@ or recovers with the -- (Special '!') token. please :: Parser TT (Exp TT) -> Parser TT (Exp TT) please = (<|>) (PError <$> recoverWith errTok <*> errTok <*> pEmpty) -- | Parse anything, as errors pErr :: Parser TT (Exp TT) pErr = PError <$> recoverWith (sym $ not . uncurry (||) . (&&&) isComment (== CppDirective)) <*> errTok <*> pComments -- | Parse an ConsIdent ppCons :: Parser TT (Exp TT) ppCons = ppAtom [ConsIdent] -- | Parse a keyword pKW :: [Token] -> Parser TT (Exp TT) -> Parser TT (Exp TT) pKW k r = Bin <$> pAtom k <*> r -- | Parse an unary operator with and without using please pOP :: [Token] -> Parser TT (Exp TT) -> Parser TT (Exp TT) pOP op r = Bin <$> pAtom op <*> r --ppOP op r = Bin <$> ppAtom op <*> r -- | Parse comments pComments :: Parser TT [TT] pComments = many $ sym $ uncurry (||) . (&&&) isComment (== CppDirective) -- | Parse something thats optional pOpt :: Parser TT (Exp TT) -> Parser TT (Exp TT) pOpt x = Opt <$> optional x -- | Parse an atom with, and without using please pAtom, ppAtom :: [Token] -> Parser TT (Exp TT) pAtom = flip pCAtom pComments ppAtom at = pAtom at <|> recoverAtom recoverAtom :: Parser TT (Exp TT) recoverAtom = PAtom <$> recoverWith errTok <*> pEmpty -- | Parse an atom with optional comments pCAtom :: [Token] -> Parser TT [TT] -> Parser TT (Exp TT) pCAtom r c = PAtom <$> exact r <*> c pBareAtom a = pCAtom a pEmpty -- | @pSepBy p sep@ parse /zero/ or more occurences of @p@, separated -- by @sep@, with optional ending @sep@, -- this is quite similar to the sepBy function provided in -- Parsec, but this one allows an optional extra separator at the end. -- -- > commaSep p = p `pSepBy` (symbol (==(Special ','))) pSepBy :: Parser TT (Exp TT) -> Parser TT (Exp TT) -> Parser TT [Exp TT] pSepBy p sep = pEmpty <|> (:) <$> p <*> (pSepBy1 p sep <|> pEmpty) <|> pToList sep -- optional ending separator where pSepBy1 r p' = (:) <$> p' <*> (pEmpty <|> pSepBy1 p' r) -- | Separate a list of things separated with comma inside of parenthesis pParenSep :: Parser TT (Exp TT) -> Parser TT (Exp TT) pParenSep = pParen . flip pSepBy pComma -- | Parse a comma separator pComma :: Parser TT (Exp TT) pComma = pAtom [Special ','] -- End of helper functions Parsing different parts follows -- | Parse a Module declaration pModuleDecl :: Parser TT (PModuleDecl TT) pModuleDecl = PModuleDecl <$> pAtom [Reserved Module] <*> ppAtom [ConsIdent] <*> pOpt (pParenSep pExport) <*> (optional (exact [nextLine]) *> (Bin <$> ppAtom [Reserved Where]) <*> pMany pErr) <* pTestTok elems where elems = [nextLine, startBlock, endBlock] pExport :: Parser TT (Exp TT) pExport = optional (exact [nextLine]) *> please ( pVarId <|> pEModule <|> Bin <$> pQvarsym <*> (DC <$> pOpt expSpec) -- typeOperator <|> Bin <$> (TC <$> pQtycon) <*> (DC <$> pOpt expSpec) ) where expSpec = pParen (pToList (please (pAtom [ReservedOp DoubleDot])) <|> pSepBy pQvarid pComma) -- | Check if next token is in given list pTestTok :: [Token] -> Parser TT () pTestTok f = testNext (uncurry (||) . (&&&) isNothing (flip elem f . tokT . fromJust)) -- | Parse several imports pImports :: Parser TT (Exp TT) -- [PImport TT] pImports = Expr <$> many (pImport <* pTestTok pEol <* optional (some $ exact [nextLine, Special ';'])) where pEol = [Special ';', nextLine, endBlock] -- | Parse one import pImport :: Parser TT (PImport TT) pImport = PImport <$> pAtom [Reserved Import] <*> pOpt (pAtom [Reserved Qualified]) <*> ppAtom [ConsIdent] <*> pOpt (pKW [Reserved As] ppCons) <*> (TC <$> pImpSpec) where pImpSpec = Bin <$> pKW [Reserved Hiding] (please pImpS) <*> pMany pErr <|> Bin <$> pImpS <*> pMany pErr <|> pMany pErr pImpS = DC <$> pParenSep pExp' pExp' = Bin <$> (PAtom <$> sym (uncurry (||) . (&&&) (`elem` [VarIdent, ConsIdent]) isOperator) <*> pComments <|> pQvarsym) <*> pOpt pImpS -- | Parse simple type synonyms pType :: Parser TT (Exp TT) pType = PType <$> (Bin <$> pAtom [Reserved Type] <*> pOpt (pAtom [Reserved Instance])) <*> (TC . Expr <$> pTypeExpr') <*> ppAtom [ReservedOp Equal] <*> (TC . Expr <$> pTypeExpr') -- | Parse data declarations pData :: Parser TT (Exp TT) pData = PData <$> pAtom [Reserved Data, Reserved NewType] <*> (TC . Expr <$> pTypeExpr') <*> pOpt (pDataRHS <|> pGadt) <*> pOpt pDeriving pGadt :: Parser TT (Exp TT) pGadt = pWhere pTypeDecl -- | Parse second half of the data declaration, if there is one pDataRHS :: Parser TT (Exp TT) pDataRHS = PData' <$> pAtom [ReservedOp Equal] <*> pConstrs -- | Parse a deriving pDeriving :: Parser TT (Exp TT) pDeriving = pKW [Reserved Deriving] (TC . Expr <$> pTypeExpr') pAtype :: Parser TT (Exp TT) pAtype = pAtype' <|> pErr pAtype' :: Parser TT (Exp TT) pAtype' = pTypeCons <|> pParen (many $ pExprElem []) <|> pBrack (many $ pExprElem []) pTypeCons :: Parser TT (Exp TT) pTypeCons = Bin <$> pAtom [ConsIdent] <*> please (pMany $ pAtom [VarIdent, ConsIdent]) pContext :: Parser TT (Exp TT) pContext = Context <$> pOpt pForAll <*> (TC <$> (pClass' <|> pParenSep pClass')) <*> ppAtom [ReservedOp DoubleRightArrow] where pClass' :: Parser TT (Exp TT) pClass' = Bin <$> pQtycon <*> (please pVarId <|> pParen ((:) <$> please pVarId <*> many pAtype')) -- | Parse for all pForAll :: Parser TT (Exp TT) pForAll = pKW [Reserved Forall] (Bin <$> pVars <*> ppAtom [Operator "."]) pConstrs :: Parser TT (Exp TT) pConstrs = Bin <$> (Bin <$> pOpt pContext <*> pConstr) <*> pMany (pOP [ReservedOp Pipe] (Bin <$> pOpt pContext <*> please pConstr)) pConstr :: Parser TT (Exp TT) pConstr = Bin <$> pOpt pForAll <*> (Bin <$> (Bin <$> (DC <$> pAtype) <*> (TC <$> pMany (strictF pAtype))) <*> pOpt st) <|> Bin <$> lrHs <*> pMany (strictF pAtype) <|> pErr where lrHs = pOP [Operator "!"] pAtype st = pEBrace (pTypeDecl `sepBy1` pBareAtom [Special ',']) -- named fields declarations -- | Parse optional strict variables strictF :: Parser TT (Exp TT) -> Parser TT (Exp TT) strictF a = Bin <$> pOpt (pAtom [Operator "!"]) <*> a -- | Exporting module pEModule ::Parser TT (Exp TT) pEModule = pKW [Reserved Module] $ please (Modid <$> exact [ConsIdent] <*> pComments) -- | Parse a Let expression pLet :: Parser TT (Exp TT) pLet = PLet <$> pAtom [Reserved Let] <*> pBlock pFunDecl <*> pOpt (pBareAtom [Reserved In]) -- | Parse a Do block pDo :: Parser TT (Exp TT) pDo = Bin <$> pAtom [Reserved Do] <*> pBlock (pExpr ((Special ';' : recognizedSometimes) \\ [ReservedOp LeftArrow])) -- | Parse part of a lambda binding. pLambda :: Parser TT (Exp TT) pLambda = Bin <$> pAtom [ReservedOp BackSlash] <*> (Bin <$> (Expr <$> pPattern) <*> please (pBareAtom [ReservedOp RightArrow])) -- | Parse an Of block pOf :: Parser TT (Exp TT) pOf = Bin <$> pAtom [Reserved Of] <*> pBlock pAlternative pAlternative = Bin <$> (Expr <$> pPattern) <*> please (pFunRHS (ReservedOp RightArrow)) -- | Parse classes and instances -- This is very imprecise, but shall suffice for now. -- At least is does not complain too often. pClass :: Parser TT (Exp TT) pClass = PClass <$> pAtom [Reserved Class, Reserved Instance] <*> (TC . Expr <$> pTypeExpr') <*> pOpt (please (pWhere pTopDecl)) -- use topDecl since we have associated types and such. -- | Parse some guards and a where clause pGuard :: Token -> Parser TT (Exp TT) pGuard equalSign = PGuard <$> some (PGuard' <$> pCAtom [ReservedOp Pipe] pEmpty <*> -- comments are by default parsed after this pExpr (recognizedSometimes -- these two symbols can appear in guards. \\ [ReservedOp LeftArrow, Special ',']) <*> please (pEq equalSign)) -- this must be -> if used in case -- | Right-hand-side of a function or case equation (after the pattern) pFunRHS :: Token -> Parser TT (Exp TT) pFunRHS equalSign = Bin <$> (pGuard equalSign <|> pEq equalSign) <*> pOpt (pWhere pFunDecl) pWhere :: Parser TT (Exp TT) -> Parser TT (Exp TT) pWhere p = PWhere <$> pAtom [Reserved Where] <*> please (pBlock p) <*> pMany pErr -- After a where there might "misaligned" code that do not "belong" to anything. -- Here we swallow it as errors. -- Note that this can both parse an equation and a type declaration. -- Since they can start with the same token, the left part is factored here. pDecl :: Bool -> Bool -> Parser TT (Exp TT) pDecl acceptType acceptEqu = Expr <$> ((Yuck $ Enter "missing end of type or equation declaration" $ pure []) <|> ((:) <$> pElem False recognizedSometimes <*> pToList (pDecl acceptType acceptEqu)) <|> ((:) <$> pBareAtom [Special ','] <*> pToList (pDecl acceptType False)) -- if a comma is found, then the rest must be a type -- declaration. <|> (if acceptType then pTypeEnding else empty) <|> (if acceptEqu then pEquEnding else empty)) where pTypeEnding = (:) <$> (TS <$> exact [ReservedOp DoubleColon] <*> pTypeExpr') <*> pure [] pEquEnding = (:) <$> pFunRHS (ReservedOp Equal) <*> pure [] pFunDecl = pDecl True True pTypeDecl = pDecl True False --pEquation = pDecl False True -- | The RHS of an equation. pEq :: Token -> Parser TT (Exp TT) pEq equalSign = RHS <$> pBareAtom [equalSign] <*> pExpr' -- | Parse many of something pMany :: Parser TT (Exp TT) -> Parser TT (Exp TT) pMany p = Expr <$> many p -- | Parse a some of something separated by the token (Special '.') pBlocks :: Parser TT r -> Parser TT [r] pBlocks p = p `sepBy1` exact [nextLine] -- | Parse a some of something separated by the token (Special '.'), or nothing --pBlocks' :: Parser TT r -> Parser TT (BL.BList r) pBlocks' p = pBlocks p <|> pure [] -- | Parse a block of some something separated by the tok (Special '.') pBlockOf :: Parser TT (Exp TT) -> Parser TT (Exp TT) pBlockOf p = Block <$> pBlockOf' (pBlocks p) -- see HACK above pBlock :: Parser TT (Exp TT) -> Parser TT (Exp TT) pBlock p = pBlockOf' (Block <$> pBlocks' p) <|> pEBrace (p `sepBy1` exact [Special ';'] <|> pure []) <|> (Yuck $ Enter "block expected" pEmptyBL) -- | Parse something surrounded by (Special '<') and (Special '>') pBlockOf' :: Parser TT a -> Parser TT a pBlockOf' p = exact [startBlock] *> p <* exact [endBlock] -- see HACK above -- note that, by construction, '<' and '>' will always be matched, so -- we don't try to recover errors with them. -- | Parse something that can contain a data, type declaration or a class pTopDecl :: Parser TT (Exp TT) pTopDecl = pFunDecl <|> pType <|> pData <|> pClass <|> pure emptyNode -- | A "normal" expression, where none of the following symbols are acceptable. pExpr' = pExpr recognizedSometimes recognizedSometimes = [ReservedOp DoubleDot, Special ',', ReservedOp Pipe, ReservedOp Equal, ReservedOp LeftArrow, ReservedOp RightArrow, ReservedOp DoubleRightArrow, ReservedOp BackSlash, ReservedOp DoubleColon ] -- | Parse an expression, as a concatenation of elements. pExpr :: [Token] -> Parser TT (Exp TT) pExpr at = Expr <$> pExprOrPattern True at -- | Parse an expression, as a concatenation of elements. pExprOrPattern :: Bool -> [Token] -> Parser TT [Exp TT] pExprOrPattern isExpresssion at = pure [] <|> ((:) <$> pElem isExpresssion at <*> pExprOrPattern True at) <|> ((:) <$> (TS <$> exact [ReservedOp DoubleColon] <*> pTypeExpr') <*> pure []) -- TODO: not really correct: in (x :: X , y :: Z), all after the -- first :: will be a "type". pPattern = pExprOrPattern False recognizedSometimes pExprElem = pElem True -- | Parse an "element" of an expression or a pattern. -- "at" is a list of symbols that, if found, should be considered errors. pElem :: Bool -> [Token] -> Parser TT (Exp TT) pElem isExpresssion at = pCParen (pExprOrPattern isExpresssion -- might be a tuple, so accept commas as noise (recognizedSometimes \\ [Special ','])) pEmpty <|> pCBrack (pExprOrPattern isExpresssion (recognizedSometimes \\ [ ReservedOp DoubleDot, ReservedOp Pipe , ReservedOp LeftArrow , Special ','])) pEmpty -- list thing <|> pCBrace (many $ pElem isExpresssion -- record: TODO: improve (recognizedSometimes \\ [ ReservedOp Equal, Special ',' , ReservedOp Pipe])) pEmpty <|> (Yuck $ Enter "incorrectly placed block" $ -- no error token, but the previous keyword will be one. (of, where, ...) pBlockOf (pExpr recognizedSometimes)) <|> (PError <$> recoverWith (sym $ flip elem $ isNoiseErr at) <*> errTok <*> pEmpty) <|> (PAtom <$> sym (`notElem` isNotNoise at) <*> pEmpty) <|> if isExpresssion then pLet <|> pDo <|> pOf <|> pLambda else empty -- TODO: support type expressions pTypeExpr at = many (pTypeElem at) pTypeExpr' = pTypeExpr (recognizedSometimes \\ [ReservedOp RightArrow, ReservedOp DoubleRightArrow]) pTypeElem :: [Token] -> Parser TT (Exp TT) pTypeElem at = pCParen (pTypeExpr (recognizedSometimes \\ [ ReservedOp RightArrow, ReservedOp DoubleRightArrow, -- might be a tuple, so accept commas as noise Special ','])) pEmpty <|> pCBrack pTypeExpr' pEmpty <|> pCBrace pTypeExpr' pEmpty -- TODO: this is an error: mark as such. <|> (Yuck $ Enter "incorrectly placed block" $ pBlockOf (pExpr recognizedSometimes)) <|> (PError <$> recoverWith (sym $ flip elem $ isNoiseErr at) <*> errTok <*> pEmpty) <|> (PAtom <$> sym (`notElem` isNotNoise at) <*> pEmpty) -- | List of things that always should be parsed as errors isNoiseErr :: [Token] -> [Token] isNoiseErr r = recoverableSymbols ++ r recoverableSymbols = recognizedSymbols \\ fmap Special "([{<>." -- We just don't recover opening symbols (only closing are "fixed"). -- Layout symbols "<>." are never recovered, because layout is -- constructed correctly. -- | List of things that should not be parsed as noise isNotNoise :: [Token] -> [Token] isNotNoise r = recognizedSymbols ++ r -- | These symbols are always properly recognized, and therefore they -- should never be accepted as "noise" inside expressions. recognizedSymbols = [ Reserved Let , Reserved In , Reserved Do , Reserved Of , Reserved Class , Reserved Instance , Reserved Deriving , Reserved Module , Reserved Import , Reserved Type , Reserved Data , Reserved NewType , Reserved Where] ++ fmap Special "()[]{}<>." -- | Parse parenthesis, brackets and braces containing -- an expression followed by possible comments pCParen, pCBrace, pCBrack :: Parser TT [Exp TT] -> Parser TT [TT] -> Parser TT (Exp TT) pCParen p c = Paren <$> pCAtom [Special '('] c <*> p <*> (recoverAtom <|> pCAtom [Special ')'] c) pCBrace p c = Paren <$> pCAtom [Special '{'] c <*> p <*> (recoverAtom <|> pCAtom [Special '}'] c) pCBrack p c = Paren <$> pCAtom [Special '['] c <*> p <*> (recoverAtom <|> pCAtom [Special ']'] c) pParen, pBrack :: Parser TT [Exp TT] -> Parser TT (Exp TT) pParen = flip pCParen pComments --pBrace = flip pCBrace pComments pBrack = flip pCBrack pComments -- pEBrace parse an opening brace, followed by zero comments -- then followed by an closing brace and some comments pEBrace p = Paren <$> pCAtom [Special '{'] pEmpty <*> p <*> (recoverAtom <|> pCAtom [Special '}'] pComments) -- | Create a special error token. (e.g. fill in where there is no -- correct token to parse) Note that the position of the token has to -- be correct for correct computation of node spans. errTok = mkTok <$> curPos where curPos = tB <$> lookNext tB Nothing = maxBound tB (Just x) = tokBegin x mkTok p = Tok (Special '!') 0 (startPosn {posnOfs = p})
atsukotakahashi/wi
src/library/Yi/Syntax/Haskell.hs
gpl-2.0
27,074
0
24
8,211
7,942
4,227
3,715
477
3
type Function = Double -> Double -- ^ Type alias for Real-valued functions of a Real variable. leftRiemannSum :: Function -> Double -> Double -> Integer -> Double -- ^ Returns Riemann sum using left endpoints. leftRiemannSum f a b n = sum [ f(x i) * dx | i <- [0..(n-1)] ] where dx = (b - a) / fromInteger n x i = a + fromInteger i * dx rightRiemannSum :: Function -> Double -> Double -> Integer -> Double -- ^ Returns Riemann sum using right endpoints. rightRiemannSum f a b n = sum [ f(x i) * dx | i <- [1..n] ] where dx = (b - a) / fromInteger n x i = a + fromInteger i * dx
friedbrice/Haskell
integrator/integrator2.hs
gpl-2.0
602
0
11
149
235
121
114
9
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Arrows #-} module Main where import Prelude hiding (putStrLn, getLine) import Control.Applicative import Control.Monad import Control.Monad.State.Strict import Data.Char import Data.ByteString.Char8 as B import Data.Attoparsec.ByteString.Char8 import Data.Map (Map) import qualified Data.Map as M import Data.Hashable import System.Exit import System.Environment main :: IO () main = do args <- getArgs debug <- case args of "debug":_ -> return True _ -> return False runGame emptyGame{ gameIsDebug = debug } where runGame g = execStateT loop g >>= runGame render :: Game -> IO () render = putStrLn . (" " `append`) . intercalate "\n " . gameMsgs loop :: GameT () loop = do g <- get liftIO $ render g put g{ gameMsgs = [] } i <- liftIO $ getInput applyInput i applyInput :: Input -> GameT () applyInput Quit = do addMsg "goodbye" get >>= liftIO . render liftIO exitSuccess applyInput (Err e) = do debug <- gets gameIsDebug when debug $ liftIO $ putStrLn $ "! " `append` e applyInput Look = do pos <- gets (playerPosition . gamePlayer) wld <- gets gameWorld case M.lookup pos wld of Nothing -> addMsg $ B.unwords ["You are falling (or are you floating?)" ,"through an infinite void." ] Just room -> addMsg $ roomDescription room applyInput Pass = return () addMsg :: ByteString -> GameT () addMsg m = modify $ \g@Game{ gameMsgs = ms} -> g{ gameMsgs = ms ++ [m] } emptyGame :: Game emptyGame = Game { gamePlayer = emptyPlayer , gameWorld = emptyWorld , gameMsgs = ["Welcome to Caltrops"] , gameIsDebug = False } emptyPlayer :: Player emptyPlayer = Player { playerPosition = (0,0,0) , playerBag = mempty } emptyWorld :: Map (Int,Int,Int) Space emptyWorld = mk 0 0 0 (Room "Starting room") mempty where mk x y z s = M.insert (x,y,z) s getInput :: IO Input getInput = do ln <- getLine return $ case parseOnly input ln of Left err -> Err $ pack err Right i -> i input :: Parser Input input = wait <|> look <|> move <|> quit <?> "input" wait :: Parser Input wait = Pass <$ string "wait" <?> "wait" look :: Parser Input look = Look <$ string "look" <?> "look" quit :: Parser Input quit = Quit <$ string "quit" <?> "quit" move :: Parser Input move = Move <$> direction <?> "move" direction :: Parser Direction direction = up <|> down <|> north <|> east <|> south <|> west <?> "direction" where up = Up <$ string "up" <?> "up" down = Down <$ string "down" <?> "down" north = North <$ string "north" <?> "north" east = East <$ string "east" <?> "east" south = South <$ string "south" <?> "south" west = West <$ string "west" <?> "west" type GameT = StateT Game IO data Input = Pass | Quit | Look | Move Direction | Err ByteString deriving (Show, Eq) data Direction = Up | Down | North | East | South | West deriving (Show, Eq) data Game = Game { gamePlayer :: Player , gameWorld :: Map (Int,Int,Int) Space , gameMsgs :: [ByteString] , gameIsDebug:: Bool } data Player = Player { playerPosition :: (Int, Int, Int) , playerBag :: Map ByteString Object } deriving (Eq, Show) data Space = Room { roomDescription :: ByteString } deriving (Show, Eq) instance Show Object where show (Object s) = show s instance Eq Object where a == b = hash a == hash b instance Hashable Object where hashWithSalt s (Object o) = s `hashWithSalt` o data Object where Object :: (Hashable a, Show a) => a -> Object
schell/challenge
code/src/Main.hs
gpl-3.0
3,995
0
12
1,253
1,307
694
613
113
2
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} module System.UtilsBox.Echo where import Prelude hiding (getLine, putStrLn) import qualified Control.Monad.Free as F import System.UtilsBoxSpec.CoreTypes ((:<:)) import System.UtilsBoxSpec.Exit (ExitAPI) import System.UtilsBoxSpec.Teletype (TeletypeAPI, putStrLn) import System.UtilsBoxSpec.Environment import System.UtilsBox.Optparse (execParserFreeExit) import qualified Options.Applicative as OA import Data.Monoid data EchoOptions = EchoOptions { echoArgument :: Maybe String } echoOptions :: OA.Parser EchoOptions echoOptions = EchoOptions <$> (OA.optional $ OA.argument OA.str (OA.metavar "STRING")) echoOptionsInfo :: OA.ParserInfo EchoOptions echoOptionsInfo = OA.info (OA.helper <*> echoOptions) (OA.fullDesc <> OA.progDesc "Prints STRINGs to standard output" <> OA.header "Echo stuff to stdout") echoF :: (EnvironmentAPI :<: f, TeletypeAPI :<: f, ExitAPI :<: f) => F.Free f () echoF = do echoOpts <- execParserFreeExit "echo" echoOptionsInfo echoFWithOpts echoOpts echoFWithOpts :: (TeletypeAPI :<: f) => EchoOptions -> F.Free f () echoFWithOpts opts = case echoArgument opts of Nothing -> putStrLn "" Just toEcho -> putStrLn toEcho
changlinli/utilsbox
System/UtilsBox/Echo.hs
gpl-3.0
1,378
0
11
286
345
190
155
28
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Drive.Files.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a file\'s metadata or content by ID. -- -- /See:/ <https://developers.google.com/drive/ Drive API Reference> for @drive.files.get@. module Network.Google.Resource.Drive.Files.Get ( -- * REST Resource FilesGetResource -- * Creating a Request , filesGet , FilesGet -- * Request Lenses , fgSupportsAllDrives , fgIncludePermissionsForView , fgAcknowledgeAbuse , fgFileId , fgSupportsTeamDrives ) where import Network.Google.Drive.Types import Network.Google.Prelude -- | A resource alias for @drive.files.get@ method which the -- 'FilesGet' request conforms to. type FilesGetResource = "drive" :> "v3" :> "files" :> Capture "fileId" Text :> QueryParam "supportsAllDrives" Bool :> QueryParam "includePermissionsForView" Text :> QueryParam "acknowledgeAbuse" Bool :> QueryParam "supportsTeamDrives" Bool :> QueryParam "alt" AltJSON :> Get '[JSON] File :<|> "drive" :> "v3" :> "files" :> Capture "fileId" Text :> QueryParam "supportsAllDrives" Bool :> QueryParam "includePermissionsForView" Text :> QueryParam "acknowledgeAbuse" Bool :> QueryParam "supportsTeamDrives" Bool :> QueryParam "alt" AltMedia :> Get '[OctetStream] Stream -- | Gets a file\'s metadata or content by ID. -- -- /See:/ 'filesGet' smart constructor. data FilesGet = FilesGet' { _fgSupportsAllDrives :: !Bool , _fgIncludePermissionsForView :: !(Maybe Text) , _fgAcknowledgeAbuse :: !Bool , _fgFileId :: !Text , _fgSupportsTeamDrives :: !Bool } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FilesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fgSupportsAllDrives' -- -- * 'fgIncludePermissionsForView' -- -- * 'fgAcknowledgeAbuse' -- -- * 'fgFileId' -- -- * 'fgSupportsTeamDrives' filesGet :: Text -- ^ 'fgFileId' -> FilesGet filesGet pFgFileId_ = FilesGet' { _fgSupportsAllDrives = False , _fgIncludePermissionsForView = Nothing , _fgAcknowledgeAbuse = False , _fgFileId = pFgFileId_ , _fgSupportsTeamDrives = False } -- | Whether the requesting application supports both My Drives and shared -- drives. fgSupportsAllDrives :: Lens' FilesGet Bool fgSupportsAllDrives = lens _fgSupportsAllDrives (\ s a -> s{_fgSupportsAllDrives = a}) -- | Specifies which additional view\'s permissions to include in the -- response. Only \'published\' is supported. fgIncludePermissionsForView :: Lens' FilesGet (Maybe Text) fgIncludePermissionsForView = lens _fgIncludePermissionsForView (\ s a -> s{_fgIncludePermissionsForView = a}) -- | Whether the user is acknowledging the risk of downloading known malware -- or other abusive files. This is only applicable when alt=media. fgAcknowledgeAbuse :: Lens' FilesGet Bool fgAcknowledgeAbuse = lens _fgAcknowledgeAbuse (\ s a -> s{_fgAcknowledgeAbuse = a}) -- | The ID of the file. fgFileId :: Lens' FilesGet Text fgFileId = lens _fgFileId (\ s a -> s{_fgFileId = a}) -- | Deprecated use supportsAllDrives instead. fgSupportsTeamDrives :: Lens' FilesGet Bool fgSupportsTeamDrives = lens _fgSupportsTeamDrives (\ s a -> s{_fgSupportsTeamDrives = a}) instance GoogleRequest FilesGet where type Rs FilesGet = File type Scopes FilesGet = '["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.appdata", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive.metadata", "https://www.googleapis.com/auth/drive.metadata.readonly", "https://www.googleapis.com/auth/drive.photos.readonly", "https://www.googleapis.com/auth/drive.readonly"] requestClient FilesGet'{..} = go _fgFileId (Just _fgSupportsAllDrives) _fgIncludePermissionsForView (Just _fgAcknowledgeAbuse) (Just _fgSupportsTeamDrives) (Just AltJSON) driveService where go :<|> _ = buildClient (Proxy :: Proxy FilesGetResource) mempty instance GoogleRequest (MediaDownload FilesGet) where type Rs (MediaDownload FilesGet) = Stream type Scopes (MediaDownload FilesGet) = Scopes FilesGet requestClient (MediaDownload FilesGet'{..}) = go _fgFileId (Just _fgSupportsAllDrives) _fgIncludePermissionsForView (Just _fgAcknowledgeAbuse) (Just _fgSupportsTeamDrives) (Just AltMedia) driveService where _ :<|> go = buildClient (Proxy :: Proxy FilesGetResource) mempty
brendanhay/gogol
gogol-drive/gen/Network/Google/Resource/Drive/Files/Get.hs
mpl-2.0
5,819
0
26
1,523
842
475
367
125
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Debugger.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Debugger.Types.Product where import Network.Google.Debugger.Types.Sum import Network.Google.Prelude -- | Response for registering a debuggee. -- -- /See:/ 'registerDebuggeeResponse' smart constructor. data RegisterDebuggeeResponse = RegisterDebuggeeResponse' { _rdrAgentId :: !(Maybe Text) , _rdrDebuggee :: !(Maybe Debuggee) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegisterDebuggeeResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rdrAgentId' -- -- * 'rdrDebuggee' registerDebuggeeResponse :: RegisterDebuggeeResponse registerDebuggeeResponse = RegisterDebuggeeResponse' {_rdrAgentId = Nothing, _rdrDebuggee = Nothing} -- | A unique ID generated for the agent. Each RegisterDebuggee request will -- generate a new agent ID. rdrAgentId :: Lens' RegisterDebuggeeResponse (Maybe Text) rdrAgentId = lens _rdrAgentId (\ s a -> s{_rdrAgentId = a}) -- | Debuggee resource. The field \`id\` is guaranteed to be set (in addition -- to the echoed fields). If the field \`is_disabled\` is set to \`true\`, -- the agent should disable itself by removing all breakpoints and -- detaching from the application. It should however continue to poll -- \`RegisterDebuggee\` until reenabled. rdrDebuggee :: Lens' RegisterDebuggeeResponse (Maybe Debuggee) rdrDebuggee = lens _rdrDebuggee (\ s a -> s{_rdrDebuggee = a}) instance FromJSON RegisterDebuggeeResponse where parseJSON = withObject "RegisterDebuggeeResponse" (\ o -> RegisterDebuggeeResponse' <$> (o .:? "agentId") <*> (o .:? "debuggee")) instance ToJSON RegisterDebuggeeResponse where toJSON RegisterDebuggeeResponse'{..} = object (catMaybes [("agentId" .=) <$> _rdrAgentId, ("debuggee" .=) <$> _rdrDebuggee]) -- | A SourceContext is a reference to a tree of files. A SourceContext -- together with a path point to a unique revision of a single file or -- directory. -- -- /See:/ 'sourceContext' smart constructor. data SourceContext = SourceContext' { _scCloudWorkspace :: !(Maybe CloudWorkspaceSourceContext) , _scCloudRepo :: !(Maybe CloudRepoSourceContext) , _scGerrit :: !(Maybe GerritSourceContext) , _scGit :: !(Maybe GitSourceContext) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SourceContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scCloudWorkspace' -- -- * 'scCloudRepo' -- -- * 'scGerrit' -- -- * 'scGit' sourceContext :: SourceContext sourceContext = SourceContext' { _scCloudWorkspace = Nothing , _scCloudRepo = Nothing , _scGerrit = Nothing , _scGit = Nothing } -- | A SourceContext referring to a snapshot in a cloud workspace. scCloudWorkspace :: Lens' SourceContext (Maybe CloudWorkspaceSourceContext) scCloudWorkspace = lens _scCloudWorkspace (\ s a -> s{_scCloudWorkspace = a}) -- | A SourceContext referring to a revision in a cloud repo. scCloudRepo :: Lens' SourceContext (Maybe CloudRepoSourceContext) scCloudRepo = lens _scCloudRepo (\ s a -> s{_scCloudRepo = a}) -- | A SourceContext referring to a Gerrit project. scGerrit :: Lens' SourceContext (Maybe GerritSourceContext) scGerrit = lens _scGerrit (\ s a -> s{_scGerrit = a}) -- | A SourceContext referring to any third party Git repo (e.g. GitHub). scGit :: Lens' SourceContext (Maybe GitSourceContext) scGit = lens _scGit (\ s a -> s{_scGit = a}) instance FromJSON SourceContext where parseJSON = withObject "SourceContext" (\ o -> SourceContext' <$> (o .:? "cloudWorkspace") <*> (o .:? "cloudRepo") <*> (o .:? "gerrit") <*> (o .:? "git")) instance ToJSON SourceContext where toJSON SourceContext'{..} = object (catMaybes [("cloudWorkspace" .=) <$> _scCloudWorkspace, ("cloudRepo" .=) <$> _scCloudRepo, ("gerrit" .=) <$> _scGerrit, ("git" .=) <$> _scGit]) -- | Response for setting a breakpoint. -- -- /See:/ 'setBreakpointResponse' smart constructor. newtype SetBreakpointResponse = SetBreakpointResponse' { _sbrBreakpoint :: Maybe Breakpoint } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SetBreakpointResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sbrBreakpoint' setBreakpointResponse :: SetBreakpointResponse setBreakpointResponse = SetBreakpointResponse' {_sbrBreakpoint = Nothing} -- | Breakpoint resource. The field \`id\` is guaranteed to be set (in -- addition to the echoed fields). sbrBreakpoint :: Lens' SetBreakpointResponse (Maybe Breakpoint) sbrBreakpoint = lens _sbrBreakpoint (\ s a -> s{_sbrBreakpoint = a}) instance FromJSON SetBreakpointResponse where parseJSON = withObject "SetBreakpointResponse" (\ o -> SetBreakpointResponse' <$> (o .:? "breakpoint")) instance ToJSON SetBreakpointResponse where toJSON SetBreakpointResponse'{..} = object (catMaybes [("breakpoint" .=) <$> _sbrBreakpoint]) -- | A generic empty message that you can re-use to avoid defining duplicated -- empty messages in your APIs. A typical example is to use it as the -- request or the response type of an API method. For instance: service Foo -- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The -- JSON representation for \`Empty\` is empty JSON object \`{}\`. -- -- /See:/ 'empty' smart constructor. data Empty = Empty' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Empty' with the minimum fields required to make a request. -- empty :: Empty empty = Empty' instance FromJSON Empty where parseJSON = withObject "Empty" (\ o -> pure Empty') instance ToJSON Empty where toJSON = const emptyObject -- | Response for updating an active breakpoint. The message is defined to -- allow future extensions. -- -- /See:/ 'updateActiveBreakpointResponse' smart constructor. data UpdateActiveBreakpointResponse = UpdateActiveBreakpointResponse' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UpdateActiveBreakpointResponse' with the minimum fields required to make a request. -- updateActiveBreakpointResponse :: UpdateActiveBreakpointResponse updateActiveBreakpointResponse = UpdateActiveBreakpointResponse' instance FromJSON UpdateActiveBreakpointResponse where parseJSON = withObject "UpdateActiveBreakpointResponse" (\ o -> pure UpdateActiveBreakpointResponse') instance ToJSON UpdateActiveBreakpointResponse where toJSON = const emptyObject -- | A SourceContext referring to a Gerrit project. -- -- /See:/ 'gerritSourceContext' smart constructor. data GerritSourceContext = GerritSourceContext' { _gscGerritProject :: !(Maybe Text) , _gscAliasName :: !(Maybe Text) , _gscRevisionId :: !(Maybe Text) , _gscHostURI :: !(Maybe Text) , _gscAliasContext :: !(Maybe AliasContext) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GerritSourceContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gscGerritProject' -- -- * 'gscAliasName' -- -- * 'gscRevisionId' -- -- * 'gscHostURI' -- -- * 'gscAliasContext' gerritSourceContext :: GerritSourceContext gerritSourceContext = GerritSourceContext' { _gscGerritProject = Nothing , _gscAliasName = Nothing , _gscRevisionId = Nothing , _gscHostURI = Nothing , _gscAliasContext = Nothing } -- | The full project name within the host. Projects may be nested, so -- \"project\/subproject\" is a valid project name. The \"repo name\" is -- hostURI\/project. gscGerritProject :: Lens' GerritSourceContext (Maybe Text) gscGerritProject = lens _gscGerritProject (\ s a -> s{_gscGerritProject = a}) -- | The name of an alias (branch, tag, etc.). gscAliasName :: Lens' GerritSourceContext (Maybe Text) gscAliasName = lens _gscAliasName (\ s a -> s{_gscAliasName = a}) -- | A revision (commit) ID. gscRevisionId :: Lens' GerritSourceContext (Maybe Text) gscRevisionId = lens _gscRevisionId (\ s a -> s{_gscRevisionId = a}) -- | The URI of a running Gerrit instance. gscHostURI :: Lens' GerritSourceContext (Maybe Text) gscHostURI = lens _gscHostURI (\ s a -> s{_gscHostURI = a}) -- | An alias, which may be a branch or tag. gscAliasContext :: Lens' GerritSourceContext (Maybe AliasContext) gscAliasContext = lens _gscAliasContext (\ s a -> s{_gscAliasContext = a}) instance FromJSON GerritSourceContext where parseJSON = withObject "GerritSourceContext" (\ o -> GerritSourceContext' <$> (o .:? "gerritProject") <*> (o .:? "aliasName") <*> (o .:? "revisionId") <*> (o .:? "hostUri") <*> (o .:? "aliasContext")) instance ToJSON GerritSourceContext where toJSON GerritSourceContext'{..} = object (catMaybes [("gerritProject" .=) <$> _gscGerritProject, ("aliasName" .=) <$> _gscAliasName, ("revisionId" .=) <$> _gscRevisionId, ("hostUri" .=) <$> _gscHostURI, ("aliasContext" .=) <$> _gscAliasContext]) -- | A unique identifier for a cloud repo. -- -- /See:/ 'repoId' smart constructor. data RepoId = RepoId' { _riUid :: !(Maybe Text) , _riProjectRepoId :: !(Maybe ProjectRepoId) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RepoId' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'riUid' -- -- * 'riProjectRepoId' repoId :: RepoId repoId = RepoId' {_riUid = Nothing, _riProjectRepoId = Nothing} -- | A server-assigned, globally unique identifier. riUid :: Lens' RepoId (Maybe Text) riUid = lens _riUid (\ s a -> s{_riUid = a}) -- | A combination of a project ID and a repo name. riProjectRepoId :: Lens' RepoId (Maybe ProjectRepoId) riProjectRepoId = lens _riProjectRepoId (\ s a -> s{_riProjectRepoId = a}) instance FromJSON RepoId where parseJSON = withObject "RepoId" (\ o -> RepoId' <$> (o .:? "uid") <*> (o .:? "projectRepoId")) instance ToJSON RepoId where toJSON RepoId'{..} = object (catMaybes [("uid" .=) <$> _riUid, ("projectRepoId" .=) <$> _riProjectRepoId]) -- | Labels with user defined metadata. -- -- /See:/ 'extendedSourceContextLabels' smart constructor. newtype ExtendedSourceContextLabels = ExtendedSourceContextLabels' { _esclAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ExtendedSourceContextLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'esclAddtional' extendedSourceContextLabels :: HashMap Text Text -- ^ 'esclAddtional' -> ExtendedSourceContextLabels extendedSourceContextLabels pEsclAddtional_ = ExtendedSourceContextLabels' {_esclAddtional = _Coerce # pEsclAddtional_} esclAddtional :: Lens' ExtendedSourceContextLabels (HashMap Text Text) esclAddtional = lens _esclAddtional (\ s a -> s{_esclAddtional = a}) . _Coerce instance FromJSON ExtendedSourceContextLabels where parseJSON = withObject "ExtendedSourceContextLabels" (\ o -> ExtendedSourceContextLabels' <$> (parseJSONObject o)) instance ToJSON ExtendedSourceContextLabels where toJSON = toJSON . _esclAddtional -- | Selects a repo using a Google Cloud Platform project ID (e.g. -- winged-cargo-31) and a repo name within that project. -- -- /See:/ 'projectRepoId' smart constructor. data ProjectRepoId = ProjectRepoId' { _priRepoName :: !(Maybe Text) , _priProjectId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectRepoId' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'priRepoName' -- -- * 'priProjectId' projectRepoId :: ProjectRepoId projectRepoId = ProjectRepoId' {_priRepoName = Nothing, _priProjectId = Nothing} -- | The name of the repo. Leave empty for the default repo. priRepoName :: Lens' ProjectRepoId (Maybe Text) priRepoName = lens _priRepoName (\ s a -> s{_priRepoName = a}) -- | The ID of the project. priProjectId :: Lens' ProjectRepoId (Maybe Text) priProjectId = lens _priProjectId (\ s a -> s{_priProjectId = a}) instance FromJSON ProjectRepoId where parseJSON = withObject "ProjectRepoId" (\ o -> ProjectRepoId' <$> (o .:? "repoName") <*> (o .:? "projectId")) instance ToJSON ProjectRepoId where toJSON ProjectRepoId'{..} = object (catMaybes [("repoName" .=) <$> _priRepoName, ("projectId" .=) <$> _priProjectId]) -- | Represents a message with parameters. -- -- /See:/ 'formatMessage' smart constructor. data FormatMessage = FormatMessage' { _fmFormat :: !(Maybe Text) , _fmParameters :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FormatMessage' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fmFormat' -- -- * 'fmParameters' formatMessage :: FormatMessage formatMessage = FormatMessage' {_fmFormat = Nothing, _fmParameters = Nothing} -- | Format template for the message. The \`format\` uses placeholders -- \`$0\`, \`$1\`, etc. to reference parameters. \`$$\` can be used to -- denote the \`$\` character. Examples: * \`Failed to load \'$0\' which -- helps debug $1 the first time it is loaded. Again, $0 is very -- important.\` * \`Please pay $$10 to use $0 instead of $1.\` fmFormat :: Lens' FormatMessage (Maybe Text) fmFormat = lens _fmFormat (\ s a -> s{_fmFormat = a}) -- | Optional parameters to be embedded into the message. fmParameters :: Lens' FormatMessage [Text] fmParameters = lens _fmParameters (\ s a -> s{_fmParameters = a}) . _Default . _Coerce instance FromJSON FormatMessage where parseJSON = withObject "FormatMessage" (\ o -> FormatMessage' <$> (o .:? "format") <*> (o .:? "parameters" .!= mempty)) instance ToJSON FormatMessage where toJSON FormatMessage'{..} = object (catMaybes [("format" .=) <$> _fmFormat, ("parameters" .=) <$> _fmParameters]) -- | ------------------------------------------------------------------------------ -- ## Breakpoint (the resource) Represents the breakpoint specification, -- status and results. -- -- /See:/ 'breakpoint' smart constructor. data Breakpoint = Breakpoint' { _bStatus :: !(Maybe StatusMessage) , _bState :: !(Maybe BreakpointState) , _bLogLevel :: !(Maybe BreakpointLogLevel) , _bLocation :: !(Maybe SourceLocation) , _bAction :: !(Maybe BreakpointAction) , _bFinalTime :: !(Maybe DateTime') , _bExpressions :: !(Maybe [Text]) , _bLogMessageFormat :: !(Maybe Text) , _bId :: !(Maybe Text) , _bLabels :: !(Maybe BreakpointLabels) , _bUserEmail :: !(Maybe Text) , _bVariableTable :: !(Maybe [Variable]) , _bCanaryExpireTime :: !(Maybe DateTime') , _bStackFrames :: !(Maybe [StackFrame]) , _bCondition :: !(Maybe Text) , _bEvaluatedExpressions :: !(Maybe [Variable]) , _bCreateTime :: !(Maybe DateTime') , _bIsFinalState :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Breakpoint' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bStatus' -- -- * 'bState' -- -- * 'bLogLevel' -- -- * 'bLocation' -- -- * 'bAction' -- -- * 'bFinalTime' -- -- * 'bExpressions' -- -- * 'bLogMessageFormat' -- -- * 'bId' -- -- * 'bLabels' -- -- * 'bUserEmail' -- -- * 'bVariableTable' -- -- * 'bCanaryExpireTime' -- -- * 'bStackFrames' -- -- * 'bCondition' -- -- * 'bEvaluatedExpressions' -- -- * 'bCreateTime' -- -- * 'bIsFinalState' breakpoint :: Breakpoint breakpoint = Breakpoint' { _bStatus = Nothing , _bState = Nothing , _bLogLevel = Nothing , _bLocation = Nothing , _bAction = Nothing , _bFinalTime = Nothing , _bExpressions = Nothing , _bLogMessageFormat = Nothing , _bId = Nothing , _bLabels = Nothing , _bUserEmail = Nothing , _bVariableTable = Nothing , _bCanaryExpireTime = Nothing , _bStackFrames = Nothing , _bCondition = Nothing , _bEvaluatedExpressions = Nothing , _bCreateTime = Nothing , _bIsFinalState = Nothing } -- | Breakpoint status. The status includes an error flag and a human -- readable message. This field is usually unset. The message can be either -- informational or an error message. Regardless, clients should always -- display the text message back to the user. Error status indicates -- complete failure of the breakpoint. Example (non-final state): \`Still -- loading symbols...\` Examples (final state): * \`Invalid line number\` -- referring to location * \`Field f not found in class C\` referring to -- condition bStatus :: Lens' Breakpoint (Maybe StatusMessage) bStatus = lens _bStatus (\ s a -> s{_bStatus = a}) -- | The current state of the breakpoint. bState :: Lens' Breakpoint (Maybe BreakpointState) bState = lens _bState (\ s a -> s{_bState = a}) -- | Indicates the severity of the log. Only relevant when action is \`LOG\`. bLogLevel :: Lens' Breakpoint (Maybe BreakpointLogLevel) bLogLevel = lens _bLogLevel (\ s a -> s{_bLogLevel = a}) -- | Breakpoint source location. bLocation :: Lens' Breakpoint (Maybe SourceLocation) bLocation = lens _bLocation (\ s a -> s{_bLocation = a}) -- | Action that the agent should perform when the code at the breakpoint -- location is hit. bAction :: Lens' Breakpoint (Maybe BreakpointAction) bAction = lens _bAction (\ s a -> s{_bAction = a}) -- | Time this breakpoint was finalized as seen by the server in seconds -- resolution. bFinalTime :: Lens' Breakpoint (Maybe UTCTime) bFinalTime = lens _bFinalTime (\ s a -> s{_bFinalTime = a}) . mapping _DateTime -- | List of read-only expressions to evaluate at the breakpoint location. -- The expressions are composed using expressions in the programming -- language at the source location. If the breakpoint action is \`LOG\`, -- the evaluated expressions are included in log statements. bExpressions :: Lens' Breakpoint [Text] bExpressions = lens _bExpressions (\ s a -> s{_bExpressions = a}) . _Default . _Coerce -- | Only relevant when action is \`LOG\`. Defines the message to log when -- the breakpoint hits. The message may include parameter placeholders -- \`$0\`, \`$1\`, etc. These placeholders are replaced with the evaluated -- value of the appropriate expression. Expressions not referenced in -- \`log_message_format\` are not logged. Example: \`Message received, id = -- $0, count = $1\` with \`expressions\` = \`[ message.id, message.count -- ]\`. bLogMessageFormat :: Lens' Breakpoint (Maybe Text) bLogMessageFormat = lens _bLogMessageFormat (\ s a -> s{_bLogMessageFormat = a}) -- | Breakpoint identifier, unique in the scope of the debuggee. bId :: Lens' Breakpoint (Maybe Text) bId = lens _bId (\ s a -> s{_bId = a}) -- | A set of custom breakpoint properties, populated by the agent, to be -- displayed to the user. bLabels :: Lens' Breakpoint (Maybe BreakpointLabels) bLabels = lens _bLabels (\ s a -> s{_bLabels = a}) -- | E-mail address of the user that created this breakpoint bUserEmail :: Lens' Breakpoint (Maybe Text) bUserEmail = lens _bUserEmail (\ s a -> s{_bUserEmail = a}) -- | The \`variable_table\` exists to aid with computation, memory and -- network traffic optimization. It enables storing a variable once and -- reference it from multiple variables, including variables stored in the -- \`variable_table\` itself. For example, the same \`this\` object, which -- may appear at many levels of the stack, can have all of its data stored -- once in this table. The stack frame variables then would hold only a -- reference to it. The variable \`var_table_index\` field is an index into -- this repeated field. The stored objects are nameless and get their name -- from the referencing variable. The effective variable is a merge of the -- referencing variable and the referenced variable. bVariableTable :: Lens' Breakpoint [Variable] bVariableTable = lens _bVariableTable (\ s a -> s{_bVariableTable = a}) . _Default . _Coerce -- | The deadline for the breakpoint to stay in CANARY_ACTIVE state. The -- value is meaningless when the breakpoint is not in CANARY_ACTIVE state. bCanaryExpireTime :: Lens' Breakpoint (Maybe UTCTime) bCanaryExpireTime = lens _bCanaryExpireTime (\ s a -> s{_bCanaryExpireTime = a}) . mapping _DateTime -- | The stack at breakpoint time, where stack_frames[0] represents the most -- recently entered function. bStackFrames :: Lens' Breakpoint [StackFrame] bStackFrames = lens _bStackFrames (\ s a -> s{_bStackFrames = a}) . _Default . _Coerce -- | Condition that triggers the breakpoint. The condition is a compound -- boolean expression composed using expressions in a programming language -- at the source location. bCondition :: Lens' Breakpoint (Maybe Text) bCondition = lens _bCondition (\ s a -> s{_bCondition = a}) -- | Values of evaluated expressions at breakpoint time. The evaluated -- expressions appear in exactly the same order they are listed in the -- \`expressions\` field. The \`name\` field holds the original expression -- text, the \`value\` or \`members\` field holds the result of the -- evaluated expression. If the expression cannot be evaluated, the -- \`status\` inside the \`Variable\` will indicate an error and contain -- the error text. bEvaluatedExpressions :: Lens' Breakpoint [Variable] bEvaluatedExpressions = lens _bEvaluatedExpressions (\ s a -> s{_bEvaluatedExpressions = a}) . _Default . _Coerce -- | Time this breakpoint was created by the server in seconds resolution. bCreateTime :: Lens' Breakpoint (Maybe UTCTime) bCreateTime = lens _bCreateTime (\ s a -> s{_bCreateTime = a}) . mapping _DateTime -- | When true, indicates that this is a final result and the breakpoint -- state will not change from here on. bIsFinalState :: Lens' Breakpoint (Maybe Bool) bIsFinalState = lens _bIsFinalState (\ s a -> s{_bIsFinalState = a}) instance FromJSON Breakpoint where parseJSON = withObject "Breakpoint" (\ o -> Breakpoint' <$> (o .:? "status") <*> (o .:? "state") <*> (o .:? "logLevel") <*> (o .:? "location") <*> (o .:? "action") <*> (o .:? "finalTime") <*> (o .:? "expressions" .!= mempty) <*> (o .:? "logMessageFormat") <*> (o .:? "id") <*> (o .:? "labels") <*> (o .:? "userEmail") <*> (o .:? "variableTable" .!= mempty) <*> (o .:? "canaryExpireTime") <*> (o .:? "stackFrames" .!= mempty) <*> (o .:? "condition") <*> (o .:? "evaluatedExpressions" .!= mempty) <*> (o .:? "createTime") <*> (o .:? "isFinalState")) instance ToJSON Breakpoint where toJSON Breakpoint'{..} = object (catMaybes [("status" .=) <$> _bStatus, ("state" .=) <$> _bState, ("logLevel" .=) <$> _bLogLevel, ("location" .=) <$> _bLocation, ("action" .=) <$> _bAction, ("finalTime" .=) <$> _bFinalTime, ("expressions" .=) <$> _bExpressions, ("logMessageFormat" .=) <$> _bLogMessageFormat, ("id" .=) <$> _bId, ("labels" .=) <$> _bLabels, ("userEmail" .=) <$> _bUserEmail, ("variableTable" .=) <$> _bVariableTable, ("canaryExpireTime" .=) <$> _bCanaryExpireTime, ("stackFrames" .=) <$> _bStackFrames, ("condition" .=) <$> _bCondition, ("evaluatedExpressions" .=) <$> _bEvaluatedExpressions, ("createTime" .=) <$> _bCreateTime, ("isFinalState" .=) <$> _bIsFinalState]) -- | A set of custom breakpoint properties, populated by the agent, to be -- displayed to the user. -- -- /See:/ 'breakpointLabels' smart constructor. newtype BreakpointLabels = BreakpointLabels' { _blAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BreakpointLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'blAddtional' breakpointLabels :: HashMap Text Text -- ^ 'blAddtional' -> BreakpointLabels breakpointLabels pBlAddtional_ = BreakpointLabels' {_blAddtional = _Coerce # pBlAddtional_} blAddtional :: Lens' BreakpointLabels (HashMap Text Text) blAddtional = lens _blAddtional (\ s a -> s{_blAddtional = a}) . _Coerce instance FromJSON BreakpointLabels where parseJSON = withObject "BreakpointLabels" (\ o -> BreakpointLabels' <$> (parseJSONObject o)) instance ToJSON BreakpointLabels where toJSON = toJSON . _blAddtional -- | Response for getting breakpoint information. -- -- /See:/ 'getBreakpointResponse' smart constructor. newtype GetBreakpointResponse = GetBreakpointResponse' { _gbrBreakpoint :: Maybe Breakpoint } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GetBreakpointResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gbrBreakpoint' getBreakpointResponse :: GetBreakpointResponse getBreakpointResponse = GetBreakpointResponse' {_gbrBreakpoint = Nothing} -- | Complete breakpoint state. The fields \`id\` and \`location\` are -- guaranteed to be set. gbrBreakpoint :: Lens' GetBreakpointResponse (Maybe Breakpoint) gbrBreakpoint = lens _gbrBreakpoint (\ s a -> s{_gbrBreakpoint = a}) instance FromJSON GetBreakpointResponse where parseJSON = withObject "GetBreakpointResponse" (\ o -> GetBreakpointResponse' <$> (o .:? "breakpoint")) instance ToJSON GetBreakpointResponse where toJSON GetBreakpointResponse'{..} = object (catMaybes [("breakpoint" .=) <$> _gbrBreakpoint]) -- | Represents a variable or an argument possibly of a compound object type. -- Note how the following variables are represented: 1) A simple variable: -- int x = 5 { name: \"x\", value: \"5\", type: \"int\" } \/\/ Captured -- variable 2) A compound object: struct T { int m1; int m2; }; T x = { 3, -- 7 }; { \/\/ Captured variable name: \"x\", type: \"T\", members { name: -- \"m1\", value: \"3\", type: \"int\" }, members { name: \"m2\", value: -- \"7\", type: \"int\" } } 3) A pointer where the pointee was captured: T -- x = { 3, 7 }; T* p = &x; { \/\/ Captured variable name: \"p\", type: -- \"T*\", value: \"0x00500500\", members { name: \"m1\", value: \"3\", -- type: \"int\" }, members { name: \"m2\", value: \"7\", type: \"int\" } } -- 4) A pointer where the pointee was not captured: T* p = new T; { \/\/ -- Captured variable name: \"p\", type: \"T*\", value: \"0x00400400\" -- status { is_error: true, description { format: \"unavailable\" } } } The -- status should describe the reason for the missing value, such as \`\`, -- \`\`, \`\`. Note that a null pointer should not have members. 5) An -- unnamed value: int* p = new int(7); { \/\/ Captured variable name: -- \"p\", value: \"0x00500500\", type: \"int*\", members { value: \"7\", -- type: \"int\" } } 6) An unnamed pointer where the pointee was not -- captured: int* p = new int(7); int** pp = &p; { \/\/ Captured variable -- name: \"pp\", value: \"0x00500500\", type: \"int**\", members { value: -- \"0x00400400\", type: \"int*\" status { is_error: true, description: { -- format: \"unavailable\" } } } } } To optimize computation, memory and -- network traffic, variables that repeat in the output multiple times can -- be stored once in a shared variable table and be referenced using the -- \`var_table_index\` field. The variables stored in the shared table are -- nameless and are essentially a partition of the complete variable. To -- reconstruct the complete variable, merge the referencing variable with -- the referenced variable. When using the shared variable table, the -- following variables: T x = { 3, 7 }; T* p = &x; T& r = x; { name: \"x\", -- var_table_index: 3, type: \"T\" } \/\/ Captured variables { name: \"p\", -- value \"0x00500500\", type=\"T*\", var_table_index: 3 } { name: \"r\", -- type=\"T&\", var_table_index: 3 } { \/\/ Shared variable table entry #3: -- members { name: \"m1\", value: \"3\", type: \"int\" }, members { name: -- \"m2\", value: \"7\", type: \"int\" } } Note that the pointer address is -- stored with the referencing variable and not with the referenced -- variable. This allows the referenced variable to be shared between -- pointers and references. The type field is optional. The debugger agent -- may or may not support it. -- -- /See:/ 'variable' smart constructor. data Variable = Variable' { _vStatus :: !(Maybe StatusMessage) , _vVarTableIndex :: !(Maybe (Textual Int32)) , _vMembers :: !(Maybe [Variable]) , _vValue :: !(Maybe Text) , _vName :: !(Maybe Text) , _vType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Variable' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vStatus' -- -- * 'vVarTableIndex' -- -- * 'vMembers' -- -- * 'vValue' -- -- * 'vName' -- -- * 'vType' variable :: Variable variable = Variable' { _vStatus = Nothing , _vVarTableIndex = Nothing , _vMembers = Nothing , _vValue = Nothing , _vName = Nothing , _vType = Nothing } -- | Status associated with the variable. This field will usually stay unset. -- A status of a single variable only applies to that variable or -- expression. The rest of breakpoint data still remains valid. Variables -- might be reported in error state even when breakpoint is not in final -- state. The message may refer to variable name with \`refers_to\` set to -- \`VARIABLE_NAME\`. Alternatively \`refers_to\` will be set to -- \`VARIABLE_VALUE\`. In either case variable value and members will be -- unset. Example of error message applied to name: \`Invalid expression -- syntax\`. Example of information message applied to value: \`Not -- captured\`. Examples of error message applied to value: * \`Malformed -- string\`, * \`Field f not found in class C\` * \`Null pointer -- dereference\` vStatus :: Lens' Variable (Maybe StatusMessage) vStatus = lens _vStatus (\ s a -> s{_vStatus = a}) -- | Reference to a variable in the shared variable table. More than one -- variable can reference the same variable in the table. The -- \`var_table_index\` field is an index into \`variable_table\` in -- Breakpoint. vVarTableIndex :: Lens' Variable (Maybe Int32) vVarTableIndex = lens _vVarTableIndex (\ s a -> s{_vVarTableIndex = a}) . mapping _Coerce -- | Members contained or pointed to by the variable. vMembers :: Lens' Variable [Variable] vMembers = lens _vMembers (\ s a -> s{_vMembers = a}) . _Default . _Coerce -- | Simple value of the variable. vValue :: Lens' Variable (Maybe Text) vValue = lens _vValue (\ s a -> s{_vValue = a}) -- | Name of the variable, if any. vName :: Lens' Variable (Maybe Text) vName = lens _vName (\ s a -> s{_vName = a}) -- | Variable type (e.g. \`MyClass\`). If the variable is split with -- \`var_table_index\`, \`type\` goes next to \`value\`. The interpretation -- of a type is agent specific. It is recommended to include the dynamic -- type rather than a static type of an object. vType :: Lens' Variable (Maybe Text) vType = lens _vType (\ s a -> s{_vType = a}) instance FromJSON Variable where parseJSON = withObject "Variable" (\ o -> Variable' <$> (o .:? "status") <*> (o .:? "varTableIndex") <*> (o .:? "members" .!= mempty) <*> (o .:? "value") <*> (o .:? "name") <*> (o .:? "type")) instance ToJSON Variable where toJSON Variable'{..} = object (catMaybes [("status" .=) <$> _vStatus, ("varTableIndex" .=) <$> _vVarTableIndex, ("members" .=) <$> _vMembers, ("value" .=) <$> _vValue, ("name" .=) <$> _vName, ("type" .=) <$> _vType]) -- | Response for listing breakpoints. -- -- /See:/ 'listBreakpointsResponse' smart constructor. data ListBreakpointsResponse = ListBreakpointsResponse' { _lbrNextWaitToken :: !(Maybe Text) , _lbrBreakpoints :: !(Maybe [Breakpoint]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListBreakpointsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lbrNextWaitToken' -- -- * 'lbrBreakpoints' listBreakpointsResponse :: ListBreakpointsResponse listBreakpointsResponse = ListBreakpointsResponse' {_lbrNextWaitToken = Nothing, _lbrBreakpoints = Nothing} -- | A wait token that can be used in the next call to \`list\` (REST) or -- \`ListBreakpoints\` (RPC) to block until the list of breakpoints has -- changes. lbrNextWaitToken :: Lens' ListBreakpointsResponse (Maybe Text) lbrNextWaitToken = lens _lbrNextWaitToken (\ s a -> s{_lbrNextWaitToken = a}) -- | List of breakpoints matching the request. The fields \`id\` and -- \`location\` are guaranteed to be set on each breakpoint. The fields: -- \`stack_frames\`, \`evaluated_expressions\` and \`variable_table\` are -- cleared on each breakpoint regardless of its status. lbrBreakpoints :: Lens' ListBreakpointsResponse [Breakpoint] lbrBreakpoints = lens _lbrBreakpoints (\ s a -> s{_lbrBreakpoints = a}) . _Default . _Coerce instance FromJSON ListBreakpointsResponse where parseJSON = withObject "ListBreakpointsResponse" (\ o -> ListBreakpointsResponse' <$> (o .:? "nextWaitToken") <*> (o .:? "breakpoints" .!= mempty)) instance ToJSON ListBreakpointsResponse where toJSON ListBreakpointsResponse'{..} = object (catMaybes [("nextWaitToken" .=) <$> _lbrNextWaitToken, ("breakpoints" .=) <$> _lbrBreakpoints]) -- | Response for listing debuggees. -- -- /See:/ 'listDebuggeesResponse' smart constructor. newtype ListDebuggeesResponse = ListDebuggeesResponse' { _ldrDebuggees :: Maybe [Debuggee] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListDebuggeesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ldrDebuggees' listDebuggeesResponse :: ListDebuggeesResponse listDebuggeesResponse = ListDebuggeesResponse' {_ldrDebuggees = Nothing} -- | List of debuggees accessible to the calling user. The fields -- \`debuggee.id\` and \`description\` are guaranteed to be set. The -- \`description\` field is a human readable field provided by agents and -- can be displayed to users. ldrDebuggees :: Lens' ListDebuggeesResponse [Debuggee] ldrDebuggees = lens _ldrDebuggees (\ s a -> s{_ldrDebuggees = a}) . _Default . _Coerce instance FromJSON ListDebuggeesResponse where parseJSON = withObject "ListDebuggeesResponse" (\ o -> ListDebuggeesResponse' <$> (o .:? "debuggees" .!= mempty)) instance ToJSON ListDebuggeesResponse where toJSON ListDebuggeesResponse'{..} = object (catMaybes [("debuggees" .=) <$> _ldrDebuggees]) -- | Request to update an active breakpoint. -- -- /See:/ 'updateActiveBreakpointRequest' smart constructor. newtype UpdateActiveBreakpointRequest = UpdateActiveBreakpointRequest' { _uabrBreakpoint :: Maybe Breakpoint } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UpdateActiveBreakpointRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uabrBreakpoint' updateActiveBreakpointRequest :: UpdateActiveBreakpointRequest updateActiveBreakpointRequest = UpdateActiveBreakpointRequest' {_uabrBreakpoint = Nothing} -- | Required. Updated breakpoint information. The field \`id\` must be set. -- The agent must echo all Breakpoint specification fields in the update. uabrBreakpoint :: Lens' UpdateActiveBreakpointRequest (Maybe Breakpoint) uabrBreakpoint = lens _uabrBreakpoint (\ s a -> s{_uabrBreakpoint = a}) instance FromJSON UpdateActiveBreakpointRequest where parseJSON = withObject "UpdateActiveBreakpointRequest" (\ o -> UpdateActiveBreakpointRequest' <$> (o .:? "breakpoint")) instance ToJSON UpdateActiveBreakpointRequest where toJSON UpdateActiveBreakpointRequest'{..} = object (catMaybes [("breakpoint" .=) <$> _uabrBreakpoint]) -- | Represents a contextual status message. The message can indicate an -- error or informational status, and refer to specific parts of the -- containing object. For example, the \`Breakpoint.status\` field can -- indicate an error referring to the \`BREAKPOINT_SOURCE_LOCATION\` with -- the message \`Location not found\`. -- -- /See:/ 'statusMessage' smart constructor. data StatusMessage = StatusMessage' { _smRefersTo :: !(Maybe StatusMessageRefersTo) , _smIsError :: !(Maybe Bool) , _smDescription :: !(Maybe FormatMessage) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusMessage' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'smRefersTo' -- -- * 'smIsError' -- -- * 'smDescription' statusMessage :: StatusMessage statusMessage = StatusMessage' {_smRefersTo = Nothing, _smIsError = Nothing, _smDescription = Nothing} -- | Reference to which the message applies. smRefersTo :: Lens' StatusMessage (Maybe StatusMessageRefersTo) smRefersTo = lens _smRefersTo (\ s a -> s{_smRefersTo = a}) -- | Distinguishes errors from informational messages. smIsError :: Lens' StatusMessage (Maybe Bool) smIsError = lens _smIsError (\ s a -> s{_smIsError = a}) -- | Status message text. smDescription :: Lens' StatusMessage (Maybe FormatMessage) smDescription = lens _smDescription (\ s a -> s{_smDescription = a}) instance FromJSON StatusMessage where parseJSON = withObject "StatusMessage" (\ o -> StatusMessage' <$> (o .:? "refersTo") <*> (o .:? "isError") <*> (o .:? "description")) instance ToJSON StatusMessage where toJSON StatusMessage'{..} = object (catMaybes [("refersTo" .=) <$> _smRefersTo, ("isError" .=) <$> _smIsError, ("description" .=) <$> _smDescription]) -- | Response for listing active breakpoints. -- -- /See:/ 'listActiveBreakpointsResponse' smart constructor. data ListActiveBreakpointsResponse = ListActiveBreakpointsResponse' { _labrNextWaitToken :: !(Maybe Text) , _labrBreakpoints :: !(Maybe [Breakpoint]) , _labrWaitExpired :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListActiveBreakpointsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'labrNextWaitToken' -- -- * 'labrBreakpoints' -- -- * 'labrWaitExpired' listActiveBreakpointsResponse :: ListActiveBreakpointsResponse listActiveBreakpointsResponse = ListActiveBreakpointsResponse' { _labrNextWaitToken = Nothing , _labrBreakpoints = Nothing , _labrWaitExpired = Nothing } -- | A token that can be used in the next method call to block until the list -- of breakpoints changes. labrNextWaitToken :: Lens' ListActiveBreakpointsResponse (Maybe Text) labrNextWaitToken = lens _labrNextWaitToken (\ s a -> s{_labrNextWaitToken = a}) -- | List of all active breakpoints. The fields \`id\` and \`location\` are -- guaranteed to be set on each breakpoint. labrBreakpoints :: Lens' ListActiveBreakpointsResponse [Breakpoint] labrBreakpoints = lens _labrBreakpoints (\ s a -> s{_labrBreakpoints = a}) . _Default . _Coerce -- | If set to \`true\`, indicates that there is no change to the list of -- active breakpoints and the server-selected timeout has expired. The -- \`breakpoints\` field would be empty and should be ignored. labrWaitExpired :: Lens' ListActiveBreakpointsResponse (Maybe Bool) labrWaitExpired = lens _labrWaitExpired (\ s a -> s{_labrWaitExpired = a}) instance FromJSON ListActiveBreakpointsResponse where parseJSON = withObject "ListActiveBreakpointsResponse" (\ o -> ListActiveBreakpointsResponse' <$> (o .:? "nextWaitToken") <*> (o .:? "breakpoints" .!= mempty) <*> (o .:? "waitExpired")) instance ToJSON ListActiveBreakpointsResponse where toJSON ListActiveBreakpointsResponse'{..} = object (catMaybes [("nextWaitToken" .=) <$> _labrNextWaitToken, ("breakpoints" .=) <$> _labrBreakpoints, ("waitExpired" .=) <$> _labrWaitExpired]) -- | An ExtendedSourceContext is a SourceContext combined with additional -- details describing the context. -- -- /See:/ 'extendedSourceContext' smart constructor. data ExtendedSourceContext = ExtendedSourceContext' { _escContext :: !(Maybe SourceContext) , _escLabels :: !(Maybe ExtendedSourceContextLabels) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ExtendedSourceContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'escContext' -- -- * 'escLabels' extendedSourceContext :: ExtendedSourceContext extendedSourceContext = ExtendedSourceContext' {_escContext = Nothing, _escLabels = Nothing} -- | Any source context. escContext :: Lens' ExtendedSourceContext (Maybe SourceContext) escContext = lens _escContext (\ s a -> s{_escContext = a}) -- | Labels with user defined metadata. escLabels :: Lens' ExtendedSourceContext (Maybe ExtendedSourceContextLabels) escLabels = lens _escLabels (\ s a -> s{_escLabels = a}) instance FromJSON ExtendedSourceContext where parseJSON = withObject "ExtendedSourceContext" (\ o -> ExtendedSourceContext' <$> (o .:? "context") <*> (o .:? "labels")) instance ToJSON ExtendedSourceContext where toJSON ExtendedSourceContext'{..} = object (catMaybes [("context" .=) <$> _escContext, ("labels" .=) <$> _escLabels]) -- | A GitSourceContext denotes a particular revision in a third party Git -- repository (e.g. GitHub). -- -- /See:/ 'gitSourceContext' smart constructor. data GitSourceContext = GitSourceContext' { _gURL :: !(Maybe Text) , _gRevisionId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GitSourceContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gURL' -- -- * 'gRevisionId' gitSourceContext :: GitSourceContext gitSourceContext = GitSourceContext' {_gURL = Nothing, _gRevisionId = Nothing} -- | Git repository URL. gURL :: Lens' GitSourceContext (Maybe Text) gURL = lens _gURL (\ s a -> s{_gURL = a}) -- | Git commit hash. required. gRevisionId :: Lens' GitSourceContext (Maybe Text) gRevisionId = lens _gRevisionId (\ s a -> s{_gRevisionId = a}) instance FromJSON GitSourceContext where parseJSON = withObject "GitSourceContext" (\ o -> GitSourceContext' <$> (o .:? "url") <*> (o .:? "revisionId")) instance ToJSON GitSourceContext where toJSON GitSourceContext'{..} = object (catMaybes [("url" .=) <$> _gURL, ("revisionId" .=) <$> _gRevisionId]) -- | Represents a location in the source code. -- -- /See:/ 'sourceLocation' smart constructor. data SourceLocation = SourceLocation' { _slPath :: !(Maybe Text) , _slLine :: !(Maybe (Textual Int32)) , _slColumn :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SourceLocation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slPath' -- -- * 'slLine' -- -- * 'slColumn' sourceLocation :: SourceLocation sourceLocation = SourceLocation' {_slPath = Nothing, _slLine = Nothing, _slColumn = Nothing} -- | Path to the source file within the source context of the target binary. slPath :: Lens' SourceLocation (Maybe Text) slPath = lens _slPath (\ s a -> s{_slPath = a}) -- | Line inside the file. The first line in the file has the value \`1\`. slLine :: Lens' SourceLocation (Maybe Int32) slLine = lens _slLine (\ s a -> s{_slLine = a}) . mapping _Coerce -- | Column within a line. The first column in a line as the value \`1\`. -- Agents that do not support setting breakpoints on specific columns -- ignore this field. slColumn :: Lens' SourceLocation (Maybe Int32) slColumn = lens _slColumn (\ s a -> s{_slColumn = a}) . mapping _Coerce instance FromJSON SourceLocation where parseJSON = withObject "SourceLocation" (\ o -> SourceLocation' <$> (o .:? "path") <*> (o .:? "line") <*> (o .:? "column")) instance ToJSON SourceLocation where toJSON SourceLocation'{..} = object (catMaybes [("path" .=) <$> _slPath, ("line" .=) <$> _slLine, ("column" .=) <$> _slColumn]) -- | Represents a stack frame context. -- -- /See:/ 'stackFrame' smart constructor. data StackFrame = StackFrame' { _sfFunction :: !(Maybe Text) , _sfLocation :: !(Maybe SourceLocation) , _sfArguments :: !(Maybe [Variable]) , _sfLocals :: !(Maybe [Variable]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StackFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sfFunction' -- -- * 'sfLocation' -- -- * 'sfArguments' -- -- * 'sfLocals' stackFrame :: StackFrame stackFrame = StackFrame' { _sfFunction = Nothing , _sfLocation = Nothing , _sfArguments = Nothing , _sfLocals = Nothing } -- | Demangled function name at the call site. sfFunction :: Lens' StackFrame (Maybe Text) sfFunction = lens _sfFunction (\ s a -> s{_sfFunction = a}) -- | Source location of the call site. sfLocation :: Lens' StackFrame (Maybe SourceLocation) sfLocation = lens _sfLocation (\ s a -> s{_sfLocation = a}) -- | Set of arguments passed to this function. Note that this might not be -- populated for all stack frames. sfArguments :: Lens' StackFrame [Variable] sfArguments = lens _sfArguments (\ s a -> s{_sfArguments = a}) . _Default . _Coerce -- | Set of local variables at the stack frame location. Note that this might -- not be populated for all stack frames. sfLocals :: Lens' StackFrame [Variable] sfLocals = lens _sfLocals (\ s a -> s{_sfLocals = a}) . _Default . _Coerce instance FromJSON StackFrame where parseJSON = withObject "StackFrame" (\ o -> StackFrame' <$> (o .:? "function") <*> (o .:? "location") <*> (o .:? "arguments" .!= mempty) <*> (o .:? "locals" .!= mempty)) instance ToJSON StackFrame where toJSON StackFrame'{..} = object (catMaybes [("function" .=) <$> _sfFunction, ("location" .=) <$> _sfLocation, ("arguments" .=) <$> _sfArguments, ("locals" .=) <$> _sfLocals]) -- | A CloudRepoSourceContext denotes a particular revision in a cloud repo -- (a repo hosted by the Google Cloud Platform). -- -- /See:/ 'cloudRepoSourceContext' smart constructor. data CloudRepoSourceContext = CloudRepoSourceContext' { _crscRepoId :: !(Maybe RepoId) , _crscAliasName :: !(Maybe Text) , _crscRevisionId :: !(Maybe Text) , _crscAliasContext :: !(Maybe AliasContext) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CloudRepoSourceContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'crscRepoId' -- -- * 'crscAliasName' -- -- * 'crscRevisionId' -- -- * 'crscAliasContext' cloudRepoSourceContext :: CloudRepoSourceContext cloudRepoSourceContext = CloudRepoSourceContext' { _crscRepoId = Nothing , _crscAliasName = Nothing , _crscRevisionId = Nothing , _crscAliasContext = Nothing } -- | The ID of the repo. crscRepoId :: Lens' CloudRepoSourceContext (Maybe RepoId) crscRepoId = lens _crscRepoId (\ s a -> s{_crscRepoId = a}) -- | The name of an alias (branch, tag, etc.). crscAliasName :: Lens' CloudRepoSourceContext (Maybe Text) crscAliasName = lens _crscAliasName (\ s a -> s{_crscAliasName = a}) -- | A revision ID. crscRevisionId :: Lens' CloudRepoSourceContext (Maybe Text) crscRevisionId = lens _crscRevisionId (\ s a -> s{_crscRevisionId = a}) -- | An alias, which may be a branch or tag. crscAliasContext :: Lens' CloudRepoSourceContext (Maybe AliasContext) crscAliasContext = lens _crscAliasContext (\ s a -> s{_crscAliasContext = a}) instance FromJSON CloudRepoSourceContext where parseJSON = withObject "CloudRepoSourceContext" (\ o -> CloudRepoSourceContext' <$> (o .:? "repoId") <*> (o .:? "aliasName") <*> (o .:? "revisionId") <*> (o .:? "aliasContext")) instance ToJSON CloudRepoSourceContext where toJSON CloudRepoSourceContext'{..} = object (catMaybes [("repoId" .=) <$> _crscRepoId, ("aliasName" .=) <$> _crscAliasName, ("revisionId" .=) <$> _crscRevisionId, ("aliasContext" .=) <$> _crscAliasContext]) -- | A set of custom debuggee properties, populated by the agent, to be -- displayed to the user. -- -- /See:/ 'debuggeeLabels' smart constructor. newtype DebuggeeLabels = DebuggeeLabels' { _dlAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DebuggeeLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dlAddtional' debuggeeLabels :: HashMap Text Text -- ^ 'dlAddtional' -> DebuggeeLabels debuggeeLabels pDlAddtional_ = DebuggeeLabels' {_dlAddtional = _Coerce # pDlAddtional_} dlAddtional :: Lens' DebuggeeLabels (HashMap Text Text) dlAddtional = lens _dlAddtional (\ s a -> s{_dlAddtional = a}) . _Coerce instance FromJSON DebuggeeLabels where parseJSON = withObject "DebuggeeLabels" (\ o -> DebuggeeLabels' <$> (parseJSONObject o)) instance ToJSON DebuggeeLabels where toJSON = toJSON . _dlAddtional -- | Represents the debugged application. The application may include one or -- more replicated processes executing the same code. Each of these -- processes is attached with a debugger agent, carrying out the debugging -- commands. Agents attached to the same debuggee identify themselves as -- such by using exactly the same Debuggee message value when registering. -- -- /See:/ 'debuggee' smart constructor. data Debuggee = Debuggee' { _dStatus :: !(Maybe StatusMessage) , _dUniquifier :: !(Maybe Text) , _dProject :: !(Maybe Text) , _dExtSourceContexts :: !(Maybe [ExtendedSourceContext]) , _dAgentVersion :: !(Maybe Text) , _dIsDisabled :: !(Maybe Bool) , _dId :: !(Maybe Text) , _dLabels :: !(Maybe DebuggeeLabels) , _dCanaryMode :: !(Maybe DebuggeeCanaryMode) , _dDescription :: !(Maybe Text) , _dIsInactive :: !(Maybe Bool) , _dSourceContexts :: !(Maybe [SourceContext]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Debuggee' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dStatus' -- -- * 'dUniquifier' -- -- * 'dProject' -- -- * 'dExtSourceContexts' -- -- * 'dAgentVersion' -- -- * 'dIsDisabled' -- -- * 'dId' -- -- * 'dLabels' -- -- * 'dCanaryMode' -- -- * 'dDescription' -- -- * 'dIsInactive' -- -- * 'dSourceContexts' debuggee :: Debuggee debuggee = Debuggee' { _dStatus = Nothing , _dUniquifier = Nothing , _dProject = Nothing , _dExtSourceContexts = Nothing , _dAgentVersion = Nothing , _dIsDisabled = Nothing , _dId = Nothing , _dLabels = Nothing , _dCanaryMode = Nothing , _dDescription = Nothing , _dIsInactive = Nothing , _dSourceContexts = Nothing } -- | Human readable message to be displayed to the user about this debuggee. -- Absence of this field indicates no status. The message can be either -- informational or an error status. dStatus :: Lens' Debuggee (Maybe StatusMessage) dStatus = lens _dStatus (\ s a -> s{_dStatus = a}) -- | Uniquifier to further distinguish the application. It is possible that -- different applications might have identical values in the debuggee -- message, thus, incorrectly identified as a single application by the -- Controller service. This field adds salt to further distinguish the -- application. Agents should consider seeding this field with value that -- identifies the code, binary, configuration and environment. dUniquifier :: Lens' Debuggee (Maybe Text) dUniquifier = lens _dUniquifier (\ s a -> s{_dUniquifier = a}) -- | Project the debuggee is associated with. Use project number or id when -- registering a Google Cloud Platform project. dProject :: Lens' Debuggee (Maybe Text) dProject = lens _dProject (\ s a -> s{_dProject = a}) -- | References to the locations and revisions of the source code used in the -- deployed application. dExtSourceContexts :: Lens' Debuggee [ExtendedSourceContext] dExtSourceContexts = lens _dExtSourceContexts (\ s a -> s{_dExtSourceContexts = a}) . _Default . _Coerce -- | Version ID of the agent. Schema: -- \`domain\/language-platform\/vmajor.minor\` (for example -- \`google.com\/java-gcp\/v1.1\`). dAgentVersion :: Lens' Debuggee (Maybe Text) dAgentVersion = lens _dAgentVersion (\ s a -> s{_dAgentVersion = a}) -- | If set to \`true\`, indicates that the agent should disable itself and -- detach from the debuggee. dIsDisabled :: Lens' Debuggee (Maybe Bool) dIsDisabled = lens _dIsDisabled (\ s a -> s{_dIsDisabled = a}) -- | Unique identifier for the debuggee generated by the controller service. dId :: Lens' Debuggee (Maybe Text) dId = lens _dId (\ s a -> s{_dId = a}) -- | A set of custom debuggee properties, populated by the agent, to be -- displayed to the user. dLabels :: Lens' Debuggee (Maybe DebuggeeLabels) dLabels = lens _dLabels (\ s a -> s{_dLabels = a}) -- | Used when setting breakpoint canary for this debuggee. dCanaryMode :: Lens' Debuggee (Maybe DebuggeeCanaryMode) dCanaryMode = lens _dCanaryMode (\ s a -> s{_dCanaryMode = a}) -- | Human readable description of the debuggee. Including a human-readable -- project name, environment name and version information is recommended. dDescription :: Lens' Debuggee (Maybe Text) dDescription = lens _dDescription (\ s a -> s{_dDescription = a}) -- | If set to \`true\`, indicates that Controller service does not detect -- any activity from the debuggee agents and the application is possibly -- stopped. dIsInactive :: Lens' Debuggee (Maybe Bool) dIsInactive = lens _dIsInactive (\ s a -> s{_dIsInactive = a}) -- | References to the locations and revisions of the source code used in the -- deployed application. dSourceContexts :: Lens' Debuggee [SourceContext] dSourceContexts = lens _dSourceContexts (\ s a -> s{_dSourceContexts = a}) . _Default . _Coerce instance FromJSON Debuggee where parseJSON = withObject "Debuggee" (\ o -> Debuggee' <$> (o .:? "status") <*> (o .:? "uniquifier") <*> (o .:? "project") <*> (o .:? "extSourceContexts" .!= mempty) <*> (o .:? "agentVersion") <*> (o .:? "isDisabled") <*> (o .:? "id") <*> (o .:? "labels") <*> (o .:? "canaryMode") <*> (o .:? "description") <*> (o .:? "isInactive") <*> (o .:? "sourceContexts" .!= mempty)) instance ToJSON Debuggee where toJSON Debuggee'{..} = object (catMaybes [("status" .=) <$> _dStatus, ("uniquifier" .=) <$> _dUniquifier, ("project" .=) <$> _dProject, ("extSourceContexts" .=) <$> _dExtSourceContexts, ("agentVersion" .=) <$> _dAgentVersion, ("isDisabled" .=) <$> _dIsDisabled, ("id" .=) <$> _dId, ("labels" .=) <$> _dLabels, ("canaryMode" .=) <$> _dCanaryMode, ("description" .=) <$> _dDescription, ("isInactive" .=) <$> _dIsInactive, ("sourceContexts" .=) <$> _dSourceContexts]) -- | A CloudWorkspaceSourceContext denotes a workspace at a particular -- snapshot. -- -- /See:/ 'cloudWorkspaceSourceContext' smart constructor. data CloudWorkspaceSourceContext = CloudWorkspaceSourceContext' { _cwscWorkspaceId :: !(Maybe CloudWorkspaceId) , _cwscSnapshotId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CloudWorkspaceSourceContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cwscWorkspaceId' -- -- * 'cwscSnapshotId' cloudWorkspaceSourceContext :: CloudWorkspaceSourceContext cloudWorkspaceSourceContext = CloudWorkspaceSourceContext' {_cwscWorkspaceId = Nothing, _cwscSnapshotId = Nothing} -- | The ID of the workspace. cwscWorkspaceId :: Lens' CloudWorkspaceSourceContext (Maybe CloudWorkspaceId) cwscWorkspaceId = lens _cwscWorkspaceId (\ s a -> s{_cwscWorkspaceId = a}) -- | The ID of the snapshot. An empty snapshot_id refers to the most recent -- snapshot. cwscSnapshotId :: Lens' CloudWorkspaceSourceContext (Maybe Text) cwscSnapshotId = lens _cwscSnapshotId (\ s a -> s{_cwscSnapshotId = a}) instance FromJSON CloudWorkspaceSourceContext where parseJSON = withObject "CloudWorkspaceSourceContext" (\ o -> CloudWorkspaceSourceContext' <$> (o .:? "workspaceId") <*> (o .:? "snapshotId")) instance ToJSON CloudWorkspaceSourceContext where toJSON CloudWorkspaceSourceContext'{..} = object (catMaybes [("workspaceId" .=) <$> _cwscWorkspaceId, ("snapshotId" .=) <$> _cwscSnapshotId]) -- | Request to register a debuggee. -- -- /See:/ 'registerDebuggeeRequest' smart constructor. newtype RegisterDebuggeeRequest = RegisterDebuggeeRequest' { _rDebuggee :: Maybe Debuggee } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegisterDebuggeeRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rDebuggee' registerDebuggeeRequest :: RegisterDebuggeeRequest registerDebuggeeRequest = RegisterDebuggeeRequest' {_rDebuggee = Nothing} -- | Required. Debuggee information to register. The fields \`project\`, -- \`uniquifier\`, \`description\` and \`agent_version\` of the debuggee -- must be set. rDebuggee :: Lens' RegisterDebuggeeRequest (Maybe Debuggee) rDebuggee = lens _rDebuggee (\ s a -> s{_rDebuggee = a}) instance FromJSON RegisterDebuggeeRequest where parseJSON = withObject "RegisterDebuggeeRequest" (\ o -> RegisterDebuggeeRequest' <$> (o .:? "debuggee")) instance ToJSON RegisterDebuggeeRequest where toJSON RegisterDebuggeeRequest'{..} = object (catMaybes [("debuggee" .=) <$> _rDebuggee]) -- | An alias to a repo revision. -- -- /See:/ 'aliasContext' smart constructor. data AliasContext = AliasContext' { _acKind :: !(Maybe AliasContextKind) , _acName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AliasContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acKind' -- -- * 'acName' aliasContext :: AliasContext aliasContext = AliasContext' {_acKind = Nothing, _acName = Nothing} -- | The alias kind. acKind :: Lens' AliasContext (Maybe AliasContextKind) acKind = lens _acKind (\ s a -> s{_acKind = a}) -- | The alias name. acName :: Lens' AliasContext (Maybe Text) acName = lens _acName (\ s a -> s{_acName = a}) instance FromJSON AliasContext where parseJSON = withObject "AliasContext" (\ o -> AliasContext' <$> (o .:? "kind") <*> (o .:? "name")) instance ToJSON AliasContext where toJSON AliasContext'{..} = object (catMaybes [("kind" .=) <$> _acKind, ("name" .=) <$> _acName]) -- | A CloudWorkspaceId is a unique identifier for a cloud workspace. A cloud -- workspace is a place associated with a repo where modified files can be -- stored before they are committed. -- -- /See:/ 'cloudWorkspaceId' smart constructor. data CloudWorkspaceId = CloudWorkspaceId' { _cwiRepoId :: !(Maybe RepoId) , _cwiName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CloudWorkspaceId' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cwiRepoId' -- -- * 'cwiName' cloudWorkspaceId :: CloudWorkspaceId cloudWorkspaceId = CloudWorkspaceId' {_cwiRepoId = Nothing, _cwiName = Nothing} -- | The ID of the repo containing the workspace. cwiRepoId :: Lens' CloudWorkspaceId (Maybe RepoId) cwiRepoId = lens _cwiRepoId (\ s a -> s{_cwiRepoId = a}) -- | The unique name of the workspace within the repo. This is the name -- chosen by the client in the Source API\'s CreateWorkspace method. cwiName :: Lens' CloudWorkspaceId (Maybe Text) cwiName = lens _cwiName (\ s a -> s{_cwiName = a}) instance FromJSON CloudWorkspaceId where parseJSON = withObject "CloudWorkspaceId" (\ o -> CloudWorkspaceId' <$> (o .:? "repoId") <*> (o .:? "name")) instance ToJSON CloudWorkspaceId where toJSON CloudWorkspaceId'{..} = object (catMaybes [("repoId" .=) <$> _cwiRepoId, ("name" .=) <$> _cwiName])
brendanhay/gogol
gogol-debugger/gen/Network/Google/Debugger/Types/Product.hs
mpl-2.0
66,103
0
28
15,440
11,466
6,637
4,829
1,231
1
-- Copyright (C) 2016 Red Hat, Inc. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RankNTypes #-} import Conduit((.|), Conduit, MonadResource, Producer, awaitForever, runConduitRes, sinkFile, sourceLazy, sourceFile, yield) import Control.Monad(void, when) import Control.Monad.Except(MonadError, runExceptT) import Control.Monad.IO.Class(liftIO) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BC import Data.CPIO(Entry(..), isEntryDirectory, readCPIO) import qualified Data.Conduit.Combinators as DCC import Data.Conduit.Lzma(decompress) import System.Directory(createDirectoryIfMissing) import System.Environment(getArgs) import System.Exit(exitFailure) import System.FilePath((</>), splitFileName) import RPM.Parse(parseRPMC) import RPM.Types(RPM(..)) -- Grab an RPM from stdin and convert it into a chunked conduit of ByteStrings. This could -- just as easily come from a stdin (using stdinC) or over the network (see httpSink in -- the http-conduit package, for instance). -- -- Important note: stdinC produces a conduit of multiple ByteStrings. A single ByteString -- is some chunk of the file - I don't know how much, but it feels like maybe 32k. conduit calls -- this chunked data, and while chunks are more efficient for conduit to work with, they don't do -- much for us. To examine the RPM header, we need individual bytes. Luckily, the *CE functions -- out of conduit let us get at individual elements out of the stream of chunks without even -- having to think about a chunk or asking for more. That all happens for us. -- -- Long story short, chunks are useful for when we need to just pipe lots of data from one place -- to another or when we need to tell conduit about types. Elements are useful for when we need -- to do something to the contents. getRPM :: MonadResource m => FilePath -> Producer m BS.ByteString getRPM = sourceFile -- If a cpio entry is a directory, just create it. If it's a file, create the directory containing -- it and then stream the contents onto disk. I'm not worrying with permissions, file mode, timestamps, -- or any of that stuff here. This is just a demo. writeCpioEntry :: Entry -> IO () writeCpioEntry entry@Entry{..} | isEntryDirectory entry = createDirectoryIfMissing True (BC.unpack cpioFileName) | otherwise = do let (d, f) = splitFileName (BC.unpack cpioFileName) createDirectoryIfMissing True d void $ runConduitRes $ sourceLazy cpioFileData .| sinkFile (d </> f) -- Pull the rpmArchive out of the RPM record payloadC :: MonadError e m => Conduit RPM m BS.ByteString payloadC = awaitForever (yield . rpmArchive) processRPM :: FilePath -> IO () processRPM path = do -- Hopefully self-explanatory - runErrorT and runResourceT execute and unwrap the monads, giving the -- actual result of the whole conduit. That's either an error message nothing, and the files are -- written out in the pipeline kind of as a side effect. result <- runExceptT $ runConduitRes $ getRPM path .| parseRPMC .| payloadC .| decompress Nothing .| readCPIO .| DCC.mapM_ (liftIO . writeCpioEntry) either print return result main :: IO () main = do -- Read the list of rpms to process from the command line arguments argv <- getArgs when (length argv < 1) $ do putStrLn "Usage: unrpm RPM [RPM ...]" exitFailure mapM_ processRPM argv
dashea/bdcs
haskell-rpm/unrpm.hs
lgpl-2.1
4,264
0
14
921
576
328
248
44
1
repli :: [a] -> Int -> [a] repli [] _ = [] repli _ 0 = [] repli (x:xs) n = x:(repli [x] (n-1)) ++ repli xs n
alephnil/h99
15.hs
apache-2.0
108
0
10
27
94
49
45
4
1