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 CPP, DeriveDataTypeable, FlexibleInstances, MagicHash, MultiParamTypeClasses, ScopedTypeVariables #-} -- | -- Module : Data.Vector.Storable.Mutable -- Copyright : (c) Roman Leshchinskiy 2009-2010 -- License : BSD-style -- -- Maintainer : Roman Leshchinskiy <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- Mutable vectors based on Storable. -- module Data.Vector.Storable.Mutable( -- * Mutable vectors of 'Storable' types MVector(..), IOVector, STVector, Storable, -- * Accessors -- ** Length information length, null, -- ** Extracting subvectors slice, init, tail, take, drop, splitAt, unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop, -- ** Overlapping overlaps, -- * Construction -- ** Initialisation new, unsafeNew, replicate, replicateM, clone, -- ** Growing grow, unsafeGrow, -- ** Restricting memory usage clear, -- * Accessing individual elements read, write, modify, swap, unsafeRead, unsafeWrite, unsafeModify, unsafeSwap, -- * Modifying vectors -- ** Filling and copying set, copy, move, unsafeCopy, unsafeMove, -- * Unsafe conversions unsafeCast, -- * Raw pointers unsafeFromForeignPtr, unsafeFromForeignPtr0, unsafeToForeignPtr, unsafeToForeignPtr0, unsafeWith ) where import Control.DeepSeq ( NFData(rnf) ) import qualified Data.Vector.Generic.Mutable as G import Data.Vector.Storable.Internal import Foreign.Storable import Foreign.ForeignPtr #if __GLASGOW_HASKELL__ >= 706 import GHC.ForeignPtr (mallocPlainForeignPtrAlignedBytes) #elif __GLASGOW_HASKELL__ >= 700 import Data.Primitive.ByteArray (MutableByteArray(..), newAlignedPinnedByteArray, unsafeFreezeByteArray) import GHC.Prim (byteArrayContents#, unsafeCoerce#) import GHC.ForeignPtr #endif import Foreign.Ptr import Foreign.Marshal.Array ( advancePtr, copyArray, moveArray ) import Control.Monad.Primitive import Data.Primitive.Addr import Data.Primitive.Types (Prim) import GHC.Word (Word8, Word16, Word32, Word64) import GHC.Ptr (Ptr(..)) import Prelude hiding ( length, null, replicate, reverse, map, read, take, drop, splitAt, init, tail ) import Data.Typeable ( Typeable ) -- Data.Vector.Internal.Check is not needed #define NOT_VECTOR_MODULE #include "vector.h" -- | Mutable 'Storable'-based vectors data MVector s a = MVector {-# UNPACK #-} !Int {-# UNPACK #-} !(ForeignPtr a) deriving ( Typeable ) type IOVector = MVector RealWorld type STVector s = MVector s instance NFData (MVector s a) where rnf (MVector _ _) = () instance Storable a => G.MVector MVector a where {-# INLINE basicLength #-} basicLength (MVector n _) = n {-# INLINE basicUnsafeSlice #-} basicUnsafeSlice j m (MVector _ fp) = MVector m (updPtr (`advancePtr` j) fp) -- FIXME: this relies on non-portable pointer comparisons {-# INLINE basicOverlaps #-} basicOverlaps (MVector m fp) (MVector n fq) = between p q (q `advancePtr` n) || between q p (p `advancePtr` m) where between x y z = x >= y && x < z p = getPtr fp q = getPtr fq {-# INLINE basicUnsafeNew #-} basicUnsafeNew n | n < 0 = error $ "Storable.basicUnsafeNew: negative length: " ++ show n | n > mx = error $ "Storable.basicUnsafeNew: length too large: " ++ show n | otherwise = unsafePrimToPrim $ do fp <- mallocVector n return $ MVector n fp where size = sizeOf (undefined :: a) mx = maxBound `quot` size :: Int {-# INLINE basicInitialize #-} basicInitialize = storableZero {-# INLINE basicUnsafeRead #-} basicUnsafeRead (MVector _ fp) i = unsafePrimToPrim $ withForeignPtr fp (`peekElemOff` i) {-# INLINE basicUnsafeWrite #-} basicUnsafeWrite (MVector _ fp) i x = unsafePrimToPrim $ withForeignPtr fp $ \p -> pokeElemOff p i x {-# INLINE basicSet #-} basicSet = storableSet {-# INLINE basicUnsafeCopy #-} basicUnsafeCopy (MVector n fp) (MVector _ fq) = unsafePrimToPrim $ withForeignPtr fp $ \p -> withForeignPtr fq $ \q -> copyArray p q n {-# INLINE basicUnsafeMove #-} basicUnsafeMove (MVector n fp) (MVector _ fq) = unsafePrimToPrim $ withForeignPtr fp $ \p -> withForeignPtr fq $ \q -> moveArray p q n storableZero :: forall a m. (Storable a, PrimMonad m) => MVector (PrimState m) a -> m () {-# INLINE storableZero #-} storableZero (MVector n fp) = unsafePrimToPrim . withForeignPtr fp $ \(Ptr p) -> do let q = Addr p setAddr q byteSize (0 :: Word8) where x :: a x = undefined byteSize :: Int byteSize = n * sizeOf x storableSet :: (Storable a, PrimMonad m) => MVector (PrimState m) a -> a -> m () {-# INLINE storableSet #-} storableSet (MVector n fp) x | n == 0 = return () | otherwise = unsafePrimToPrim $ case sizeOf x of 1 -> storableSetAsPrim n fp x (undefined :: Word8) 2 -> storableSetAsPrim n fp x (undefined :: Word16) 4 -> storableSetAsPrim n fp x (undefined :: Word32) 8 -> storableSetAsPrim n fp x (undefined :: Word64) _ -> withForeignPtr fp $ \p -> do poke p x let do_set i | 2*i < n = do copyArray (p `advancePtr` i) p i do_set (2*i) | otherwise = copyArray (p `advancePtr` i) p (n-i) do_set 1 storableSetAsPrim :: (Storable a, Prim b) => Int -> ForeignPtr a -> a -> b -> IO () {-# INLINE [0] storableSetAsPrim #-} storableSetAsPrim n fp x y = withForeignPtr fp $ \(Ptr p) -> do poke (Ptr p) x let q = Addr p w <- readOffAddr q 0 setAddr (q `plusAddr` sizeOf x) (n-1) (w `asTypeOf` y) {-# INLINE mallocVector #-} mallocVector :: Storable a => Int -> IO (ForeignPtr a) mallocVector = #if __GLASGOW_HASKELL__ >= 706 doMalloc undefined where doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b) doMalloc dummy size = mallocPlainForeignPtrAlignedBytes (size * sizeOf dummy) (alignment dummy) #elif __GLASGOW_HASKELL__ >= 700 doMalloc undefined where doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b) doMalloc dummy size = do arr@(MutableByteArray arr#) <- newAlignedPinnedByteArray arrSize arrAlign newConcForeignPtr (Ptr (byteArrayContents# (unsafeCoerce# arr#))) -- Keep reference to mutable byte array until whole ForeignPtr goes out -- of scope. (touch arr) where arrSize = size * sizeOf dummy arrAlign = alignment dummy #else mallocForeignPtrArray #endif -- Length information -- ------------------ -- | Length of the mutable vector. length :: Storable a => MVector s a -> Int {-# INLINE length #-} length = G.length -- | Check whether the vector is empty null :: Storable a => MVector s a -> Bool {-# INLINE null #-} null = G.null -- Extracting subvectors -- --------------------- -- | Yield a part of the mutable vector without copying it. slice :: Storable a => Int -> Int -> MVector s a -> MVector s a {-# INLINE slice #-} slice = G.slice take :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE take #-} take = G.take drop :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE drop #-} drop = G.drop splitAt :: Storable a => Int -> MVector s a -> (MVector s a, MVector s a) {-# INLINE splitAt #-} splitAt = G.splitAt init :: Storable a => MVector s a -> MVector s a {-# INLINE init #-} init = G.init tail :: Storable a => MVector s a -> MVector s a {-# INLINE tail #-} tail = G.tail -- | Yield a part of the mutable vector without copying it. No bounds checks -- are performed. unsafeSlice :: Storable a => Int -- ^ starting index -> Int -- ^ length of the slice -> MVector s a -> MVector s a {-# INLINE unsafeSlice #-} unsafeSlice = G.unsafeSlice unsafeTake :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE unsafeTake #-} unsafeTake = G.unsafeTake unsafeDrop :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE unsafeDrop #-} unsafeDrop = G.unsafeDrop unsafeInit :: Storable a => MVector s a -> MVector s a {-# INLINE unsafeInit #-} unsafeInit = G.unsafeInit unsafeTail :: Storable a => MVector s a -> MVector s a {-# INLINE unsafeTail #-} unsafeTail = G.unsafeTail -- Overlapping -- ----------- -- | Check whether two vectors overlap. overlaps :: Storable a => MVector s a -> MVector s a -> Bool {-# INLINE overlaps #-} overlaps = G.overlaps -- Initialisation -- -------------- -- | Create a mutable vector of the given length. new :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a) {-# INLINE new #-} new = G.new -- | Create a mutable vector of the given length. The memory is not initialized. unsafeNew :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a) {-# INLINE unsafeNew #-} unsafeNew = G.unsafeNew -- | Create a mutable vector of the given length (0 if the length is negative) -- and fill it with an initial value. replicate :: (PrimMonad m, Storable a) => Int -> a -> m (MVector (PrimState m) a) {-# INLINE replicate #-} replicate = G.replicate -- | Create a mutable vector of the given length (0 if the length is negative) -- and fill it with values produced by repeatedly executing the monadic action. replicateM :: (PrimMonad m, Storable a) => Int -> m a -> m (MVector (PrimState m) a) {-# INLINE replicateM #-} replicateM = G.replicateM -- | Create a copy of a mutable vector. clone :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> m (MVector (PrimState m) a) {-# INLINE clone #-} clone = G.clone -- Growing -- ------- -- | Grow a vector by the given number of elements. The number must be -- positive. grow :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a) {-# INLINE grow #-} grow = G.grow -- | Grow a vector by the given number of elements. The number must be -- positive but this is not checked. unsafeGrow :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a) {-# INLINE unsafeGrow #-} unsafeGrow = G.unsafeGrow -- Restricting memory usage -- ------------------------ -- | Reset all elements of the vector to some undefined value, clearing all -- references to external objects. This is usually a noop for unboxed vectors. clear :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> m () {-# INLINE clear #-} clear = G.clear -- Accessing individual elements -- ----------------------------- -- | Yield the element at the given position. read :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a {-# INLINE read #-} read = G.read -- | Replace the element at the given position. write :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m () {-# INLINE write #-} write = G.write -- | Modify the element at the given position. modify :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> (a -> a) -> Int -> m () {-# INLINE modify #-} modify = G.modify -- | Swap the elements at the given positions. swap :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m () {-# INLINE swap #-} swap = G.swap -- | Yield the element at the given position. No bounds checks are performed. unsafeRead :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a {-# INLINE unsafeRead #-} unsafeRead = G.unsafeRead -- | Replace the element at the given position. No bounds checks are performed. unsafeWrite :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m () {-# INLINE unsafeWrite #-} unsafeWrite = G.unsafeWrite -- | Modify the element at the given position. No bounds checks are performed. unsafeModify :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> (a -> a) -> Int -> m () {-# INLINE unsafeModify #-} unsafeModify = G.unsafeModify -- | Swap the elements at the given positions. No bounds checks are performed. unsafeSwap :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m () {-# INLINE unsafeSwap #-} unsafeSwap = G.unsafeSwap -- Filling and copying -- ------------------- -- | Set all elements of the vector to the given value. set :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> a -> m () {-# INLINE set #-} set = G.set -- | Copy a vector. The two vectors must have the same length and may not -- overlap. copy :: (PrimMonad m, Storable a) => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE copy #-} copy = G.copy -- | Copy a vector. The two vectors must have the same length and may not -- overlap. This is not checked. unsafeCopy :: (PrimMonad m, Storable a) => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE unsafeCopy #-} unsafeCopy = G.unsafeCopy -- | Move the contents of a vector. The two vectors must have the same -- length. -- -- If the vectors do not overlap, then this is equivalent to 'copy'. -- Otherwise, the copying is performed as if the source vector were -- copied to a temporary vector and then the temporary vector was copied -- to the target vector. move :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> MVector (PrimState m) a -> m () {-# INLINE move #-} move = G.move -- | Move the contents of a vector. The two vectors must have the same -- length, but this is not checked. -- -- If the vectors do not overlap, then this is equivalent to 'unsafeCopy'. -- Otherwise, the copying is performed as if the source vector were -- copied to a temporary vector and then the temporary vector was copied -- to the target vector. unsafeMove :: (PrimMonad m, Storable a) => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE unsafeMove #-} unsafeMove = G.unsafeMove -- Unsafe conversions -- ------------------ -- | /O(1)/ Unsafely cast a mutable vector from one element type to another. -- The operation just changes the type of the underlying pointer and does not -- modify the elements. -- -- The resulting vector contains as many elements as can fit into the -- underlying memory block. -- unsafeCast :: forall a b s. (Storable a, Storable b) => MVector s a -> MVector s b {-# INLINE unsafeCast #-} unsafeCast (MVector n fp) = MVector ((n * sizeOf (undefined :: a)) `div` sizeOf (undefined :: b)) (castForeignPtr fp) -- Raw pointers -- ------------ -- | Create a mutable vector from a 'ForeignPtr' with an offset and a length. -- -- Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector -- could have been frozen before the modification. -- -- If your offset is 0 it is more efficient to use 'unsafeFromForeignPtr0'. unsafeFromForeignPtr :: Storable a => ForeignPtr a -- ^ pointer -> Int -- ^ offset -> Int -- ^ length -> MVector s a {-# INLINE_FUSED unsafeFromForeignPtr #-} unsafeFromForeignPtr fp i n = unsafeFromForeignPtr0 fp' n where fp' = updPtr (`advancePtr` i) fp {-# RULES "unsafeFromForeignPtr fp 0 n -> unsafeFromForeignPtr0 fp n " forall fp n. unsafeFromForeignPtr fp 0 n = unsafeFromForeignPtr0 fp n #-} -- | /O(1)/ Create a mutable vector from a 'ForeignPtr' and a length. -- -- It is assumed the pointer points directly to the data (no offset). -- Use `unsafeFromForeignPtr` if you need to specify an offset. -- -- Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector -- could have been frozen before the modification. unsafeFromForeignPtr0 :: Storable a => ForeignPtr a -- ^ pointer -> Int -- ^ length -> MVector s a {-# INLINE unsafeFromForeignPtr0 #-} unsafeFromForeignPtr0 fp n = MVector n fp -- | Yield the underlying 'ForeignPtr' together with the offset to the data -- and its length. Modifying the data through the 'ForeignPtr' is -- unsafe if the vector could have frozen before the modification. unsafeToForeignPtr :: Storable a => MVector s a -> (ForeignPtr a, Int, Int) {-# INLINE unsafeToForeignPtr #-} unsafeToForeignPtr (MVector n fp) = (fp, 0, n) -- | /O(1)/ Yield the underlying 'ForeignPtr' together with its length. -- -- You can assume the pointer points directly to the data (no offset). -- -- Modifying the data through the 'ForeignPtr' is unsafe if the vector could -- have frozen before the modification. unsafeToForeignPtr0 :: Storable a => MVector s a -> (ForeignPtr a, Int) {-# INLINE unsafeToForeignPtr0 #-} unsafeToForeignPtr0 (MVector n fp) = (fp, n) -- | Pass a pointer to the vector's data to the IO action. Modifying data -- through the pointer is unsafe if the vector could have been frozen before -- the modification. unsafeWith :: Storable a => IOVector a -> (Ptr a -> IO b) -> IO b {-# INLINE unsafeWith #-} unsafeWith (MVector _ fp) = withForeignPtr fp
sergv/vector
Data/Vector/Storable/Mutable.hs
bsd-3-clause
17,219
0
22
4,022
3,868
2,099
1,769
279
5
{-# LANGUAGE ApplicativeDo #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE RecordWildCards #-} {-| This module exports the `tomlToDhall` function for translating a TOML syntax tree from @tomland@ to a Dhall syntax tree. For now, this package does not have type inference so a Dhall type is needed. For converting source code into a Dhall syntax tree see the @dhall@ package, and for converting the TOML syntax tree to source code see the @tomland@ package. This module also exports `tomlToDhallMain` which implements the @toml-to-dhall@ command which converts TOML source directly into Dhall source. In theory all TOML objects should be converted but there are some known failure cases: * Arrays of arrays of objects - not supported by @tomland@ * Arrays of heterogeneous primitive types - not supported by @tomland@ * Arrays of objects of different types are allowed (note that this requires conversion to a Dhall union) TOML bools translate to Dhall @Bool@s: > $ cat schema.dhall > { b : Bool } > $ toml-to-dhall schema.dhall <<< 'b = true' > { b = True } TOML numbers translate to Dhall numbers: > $ cat schema.dhall > { n : Natural, d : Double } > $ toml-to-dhall schema.dhall << EOF > n = 1 > d = 3.14 > EOF > { d = 3.14, n = 1} TOML text translates to Dhall @Text@: > $ cat schema.dhall > { t : Text } > $ toml-to-dhall schema.dhall << EOF > t = "Hello!" > EOF > { t = "Hello!" } TOML arrays and table arrays translate to Dhall @List@: > $ cat schema.dhall > { nums : List Natural, tables : List { a : Natural, b : Text } } > $ toml-to-dhall schema.dhall << EOF > nums = [1, 2, 3] > > [[tables]] > a = 1 > b = "Hello," > [[tables]] > a = 2 > b = " World!" > EOF > { nums = [ 1, 2, 3 ] > , tables = [ { a = 1, b = "Hello," }, { a = 2, b = " World!" } ] > } Note, [lists of lists of objects](https://github.com/kowainik/tomland/issues/373) and [heterogeneous lists](https://github.com/kowainik/tomland/issues/373) are not supported by @tomland@ so a paraser error will be returned: > $ cat schema.dhall > { list : List (<a : Natural | b : Bool>) } > $ toml-to-dhall schema.dhall << EOF > list = [1, true] > EOF > toml-to-dhall: invalid TOML: > 1:12: > | > 1 | list = [1, true] > | ^ > unexpected 't' > expecting ',', ']', or integer Because of this, unions have limited use in lists, but can be used fully in tables: > $ cat schema.dhall > { list : List (<a : Natural | b : Bool>), item : <a : Natural | b : Bool> } > $ toml-to-dhall schema.dhall << EOF > list = [1, 2] > item = true > EOF > { item = < a : Natural | b : Bool >.b True > , list = [ < a : Natural | b : Bool >.a 1, < a : Natural | b : Bool >.a 2 ] > } TOML tables translate to Dhall records: > $ cat schema.dhall > { num : Natural, table : { num1 : Natural, table1 : { num2 : Natural } } } > $ toml-to-dhall schema.dhall << EOF > num = 0 > > [table] > num1 = 1 > > [table.table1] > num2 = 2 > EOF > { num = 0, table = { num1 = 1, table1.num2 = 2 } } -} module Dhall.TomlToDhall ( tomlToDhall , tomlToDhallMain , CompileError ) where import Control.Exception (Exception, throwIO) import Data.Either (rights) import Data.Foldable (foldl', toList) import Data.List.NonEmpty (NonEmpty ((:|))) import Data.Text (Text) import Data.Version (showVersion) import Data.Void (Void) import Dhall.Core (DhallDouble (..), Expr) import Dhall.Parser (Src) import Dhall.Toml.Utils (fileToDhall) import Toml.Parser (TomlParseError) import Toml.Type.AnyValue (AnyValue (AnyValue)) import Toml.Type.Key (Key (Key), Piece (Piece)) import Toml.Type.PrefixTree (PrefixTree) import Toml.Type.TOML (TOML) import Toml.Type.Value (Value) import qualified Data.HashMap.Strict as HashMap import qualified Data.Sequence as Seq import qualified Data.Text import qualified Data.Text.IO as Text.IO import qualified Dhall.Core as Core import qualified Dhall.Map as Map import qualified Options.Applicative as OA import qualified Paths_dhall_toml as Meta import qualified Toml.Parser import qualified Toml.Type.AnyValue as Toml.AnyValue import qualified Toml.Type.PrefixTree as Toml.PrefixTree import qualified Toml.Type.TOML as Toml.TOML import qualified Toml.Type.Value as Value data CompileError = Unimplemented String | Incompatible (Expr Src Void) Object | InvalidToml TomlParseError | InternalError String | MissingKey String instance Show CompileError where show (Unimplemented s) = "unimplemented: " ++ s show (Incompatible e toml) = "incompatible: " ++ (show e) ++ " with " ++ (show toml) show (InvalidToml e) = "invalid TOML:\n" ++ (Data.Text.unpack $ Toml.Parser.unTomlParseError e) show (InternalError e) = "internal error: " ++ show e show (MissingKey e) = "missing key: " ++ show e instance Exception CompileError tomlToDhall :: Expr Src Void -> TOML -> Either CompileError (Expr Src Void) tomlToDhall schema toml = toDhall (Core.normalize schema) (tomlToObject toml) tomlValueToDhall :: Expr Src Void -> Value t -> Either CompileError (Expr Src Void) tomlValueToDhall exprType v = case (exprType, v) of (Core.Bool , Value.Bool a ) -> Right $ Core.BoolLit a (Core.Natural , Value.Integer a) -> Right $ Core.NaturalLit $ fromInteger a (Core.Double , Value.Double a ) -> Right $ Core.DoubleLit $ DhallDouble a (Core.Text , Value.Text a ) -> Right $ Core.TextLit $ Core.Chunks [] a (_ , Value.Zoned _ ) -> Left $ Unimplemented "toml time values" (_ , Value.Local _ ) -> Left $ Unimplemented "toml time values" (_ , Value.Day _ ) -> Left $ Unimplemented "toml time values" (t@(Core.App Core.List _) , Value.Array [] ) -> Right $ Core.ListLit (Just t) [] (Core.App Core.Optional t , a ) -> do o <- tomlValueToDhall t a return $ Core.Some o (Core.App Core.List t , Value.Array a ) -> do l <- mapM (tomlValueToDhall t) a return $ Core.ListLit Nothing (Seq.fromList l) -- TODO: allow different types of matching (ex. first, strict, none) -- currently we just pick the first enum that matches (Core.Union m , _) -> let f key maybeType = case maybeType of Just ty -> do expr <- tomlValueToDhall ty v return $ Core.App (Core.Field exprType $ Core.makeFieldSelection key) expr Nothing -> case v of Value.Text a | a == key -> return $ Core.Field exprType (Core.makeFieldSelection a) _ -> Left $ Incompatible exprType (Prim (AnyValue v)) in case rights (toList (Map.mapWithKey f m)) of [] -> Left $ Incompatible exprType (Prim (AnyValue v)) x:_ -> Right $ x _ -> Left $ Incompatible exprType (Prim (AnyValue v)) -- TODO: keep track of the path for more helpful error messages toDhall :: Expr Src Void -> Object -> Either CompileError (Expr Src Void) toDhall exprType value = case (exprType, value) of (_, Invalid) -> Left $ InternalError "invalid object" -- TODO: allow different types of matching (ex. first, strict, none) -- currently we just pick the first enum that matches (Core.Union m , _) -> let f key maybeType = case maybeType of Just ty -> do expr <- toDhall ty value return $ Core.App (Core.Field exprType $ Core.makeFieldSelection key) expr Nothing -> case value of Prim (AnyValue (Value.Text a)) | a == key -> return $ Core.Field exprType (Core.makeFieldSelection a) _ -> Left $ Incompatible exprType value in case rights (toList (Map.mapWithKey f m)) of [] -> Left $ Incompatible exprType value x:_ -> Right $ x (Core.App Core.List t, Array []) -> Right $ Core.ListLit (Just t) [] (Core.App Core.List t, Array a) -> do l <- mapM (toDhall t) a return $ Core.ListLit Nothing (Seq.fromList l) (Core.Record r, Table t) -> let f :: Text -> (Expr Src Void) -> Either CompileError (Expr Src Void) f k ty | Just val <- HashMap.lookup (Piece k) t = toDhall ty val | Core.App Core.Optional ty' <- ty = Right $ (Core.App Core.None ty') | Core.App Core.List _ <- ty = Right $ Core.ListLit (Just ty) [] | otherwise = Left $ MissingKey $ Data.Text.unpack k in do values <- Map.traverseWithKey f (Core.recordFieldValue <$> r) return $ Core.RecordLit (Core.makeRecordField <$> values) (_, Prim (AnyValue v)) -> tomlValueToDhall exprType v (ty, obj) -> Left $ Incompatible ty obj -- | An intermediate object created from a 'TOML' before an 'Expr'. -- It does two things, firstly joining the tomlPairs, tomlTables, -- and tomlTableArrays parts of the TOML. Second, it turns the dense -- paths (ex. a.b.c = 1) into sparse paths (ex. a = { b = { c = 1 }}). data Object = Prim Toml.AnyValue.AnyValue | Array [Object] | Table (HashMap.HashMap Piece Object) | Invalid deriving (Show) instance Semigroup Object where (Table ls) <> (Table rs) = Table (ls <> rs) -- this shouldn't happen because tomland has already verified correctness -- of the toml object _ <> _ = Invalid -- | Creates an arbitrarily nested object sparseObject :: Key -> Object -> Object sparseObject (Key (piece :| [])) value = Table $ HashMap.singleton piece value sparseObject (Key (piece :| rest:rest')) value = Table $ HashMap.singleton piece (sparseObject (Key $ rest :| rest') value) pairsToObject :: HashMap.HashMap Key Toml.AnyValue.AnyValue -> Object pairsToObject pairs = foldl' (<>) (Table HashMap.empty) $ HashMap.mapWithKey sparseObject $ fmap Prim pairs tablesToObject :: Toml.PrefixTree.PrefixMap TOML -> Object tablesToObject tables = foldl' (<>) (Table HashMap.empty) $ map prefixTreeToObject $ HashMap.elems tables prefixTreeToObject :: PrefixTree TOML -> Object prefixTreeToObject (Toml.PrefixTree.Leaf key toml) = sparseObject key (tomlToObject toml) prefixTreeToObject (Toml.PrefixTree.Branch prefix _ toml) = sparseObject prefix (tablesToObject toml) tableArraysToObject :: HashMap.HashMap Key (NonEmpty TOML) -> Object tableArraysToObject arrays = foldl' (<>) (Table HashMap.empty) $ HashMap.mapWithKey sparseObject $ fmap (Array . fmap tomlToObject . toList) arrays tomlToObject :: TOML -> Object tomlToObject toml = pairs <> tables <> tableArrays where pairs = pairsToObject $ Toml.TOML.tomlPairs toml tables = tablesToObject $ Toml.TOML.tomlTables toml tableArrays = tableArraysToObject $ Toml.TOML.tomlTableArrays toml data Options = Options { input :: Maybe FilePath , output :: Maybe FilePath , schemaFile :: FilePath } parserInfo :: OA.ParserInfo Options parserInfo = OA.info (OA.helper <*> versionOption <*> optionsParser) (OA.fullDesc <> OA.progDesc "Convert TOML to Dhall") where versionOption = OA.infoOption (showVersion Meta.version) $ OA.long "version" <> OA.help "Display version" optionsParser = do input <- OA.optional . OA.strOption $ OA.long "file" <> OA.help "Read TOML from file instead of standard input" <> fileOpts output <- OA.optional . OA.strOption $ OA.long "output" <> OA.help "Write Dhall to a file instead of standard output" <> fileOpts schemaFile <- OA.strArgument $ OA.help "Path to Dhall schema file" <> OA.action "file" <> OA.metavar "SCHEMA" pure Options {..} fileOpts = OA.metavar "FILE" <> OA.action "file" tomlToDhallMain :: IO () tomlToDhallMain = do Options {..} <- OA.execParser parserInfo text <- maybe Text.IO.getContents Text.IO.readFile input toml <- case Toml.Parser.parse text of Left tomlErr -> throwIO (InvalidToml tomlErr) Right toml -> return toml schema <- fileToDhall schemaFile dhall <- case tomlToDhall schema toml of Left err -> throwIO err Right dhall -> return dhall maybe Text.IO.putStrLn Text.IO.writeFile output $ Core.pretty dhall
Gabriel439/Haskell-Dhall-Library
dhall-toml/src/Dhall/TomlToDhall.hs
bsd-3-clause
12,634
0
23
3,334
2,947
1,508
1,439
186
15
{-# LANGUAGE TemplateHaskell #-} module Simulation ( -- * Simulation runSim )where import Graphics.Gloss import Graphics.Gloss.Interface.IO.Game import Graphics.Gloss.Data.Vector (mulSV) import System.Random (StdGen, getStdGen) import Control.Monad.Random (Rand, runRand) import Control.Lens import Control.Monad.Reader import Control.Monad.State import Flock data SimState = SimState { _plane :: Plane , _rgen :: StdGen , _pause :: Bool , _steps :: Integer , _pauseEvery :: Integer , _trail :: [Point] } deriving Show makeLenses ''SimState type Transition = SimState -> SimState window :: Int -> Int -> Display window w h = InWindow "Flock" (w,h) (0,0) bgColor :: Color bgColor = white fps :: Int fps = 120 -- | Simulation control inputHandler :: Event -> Transition inputHandler (EventKey (MouseButton LeftButton) Down _ p) = plane.planeObstacles %~ (o:) where o = Obstacle p 10 inputHandler (EventKey (MouseButton RightButton) Down _ p) = plane.planeAgents %~ (a:) where a = mkAgent p 5 (1,1) 1 80 inputHandler (EventKey (SpecialKey KeySpace) Down _ _) = pause %~ not inputHandler (EventKey (Char 'r') Down _ _) = (plane .~ Plane [] []).(trail .~ []).(pause .~ True) inputHandler _ = id -- | As @simStep@, but with its behavior function in a random monad. simStepR :: (Plane -> Agent -> Rand StdGen Agent) -> Float -> Transition simStepR f _ p | p^.pause = p | _pauseEvery p > 1 && _steps p `mod` _pauseEvery p == 0 = p { _pause = True, _steps = _steps p + 1 } | otherwise = p { _plane = plane' , _rgen = gen' , _steps = _steps p + 1 , _trail = averageP (map _agentPosition (_planeAgents._plane $ p)) : _trail p } where averageP ps = (1/toEnum (length ps)) `mulSV` sum ps (plane', gen') = runRand (stepR f (_plane p)) (_rgen p) -- | Runs the simulation in a window, given the window size, -- a plane, to simulate and a behavior function. runSim :: Int -> Int -> Integer -> Plane -> Behavior () -> IO () runSim w h s p b = runSimR w h s p (\pl ag -> do ((),a') <- runStateT (runReaderT b pl) ag return a') -- | As @runSim@ but with a random-monadic behavior function. runSimR :: Int -- ^ Window width -> Int -- ^ Window height -> Integer -- ^ Stop every n steps. -> Plane -- ^ Plane to simulate -> (Plane -> Agent -> Rand StdGen Agent) -- ^ Behavior function -> IO () runSimR w h s p f = do r <- getStdGen play (window w h) bgColor fps (SimState p r True 1 s []) (renderSim) inputHandler (simStepR f) renderSim :: SimState -> Picture renderSim ss = pictures [ line (_trail ss) , render (_plane ss) (_plane ss) ]
SRechenberger/flock
lib/Simulation.hs
bsd-3-clause
2,855
2
14
794
973
523
450
-1
-1
{-# LANGUAGE DeriveGeneric,DuplicateRecordFields,DeriveDataTypeable #-} module Api.Stockfighter.Jailbreak.Types where import Data.Aeson import Data.Data import Data.Typeable import GHC.Generics import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL type ApiKey = T.Text newtype HexString = HexString T.Text deriving (Generic, Show) type Addr = Int instance ToJSON HexString where instance FromJSON HexString where newtype Base64Bytes = Base64Bytes BS.ByteString deriving (Show) instance ToJSON Base64Bytes where toJSON (Base64Bytes bs) = toJSON (T.decodeUtf8 $ Base64.encode bs :: T.Text) instance FromJSON Base64Bytes where parseJSON json = do eResult <- Base64.decode <$> T.encodeUtf8 <$> parseJSON json case eResult of Left e -> fail e Right x -> return $ Base64Bytes x data JailbreakConfig = JailbreakConfig { apiKey :: ApiKey } deriving (Generic, Show) data GetDeviceStatusResponse = GetDeviceStatusResponse { ok :: Bool, address :: T.Text, runcount :: Int, apu_state :: ApuState } deriving (Generic, Show) instance ToJSON GetDeviceStatusResponse where instance FromJSON GetDeviceStatusResponse where data StartDeviceResponse = StartDeviceResponse { ok :: Bool, error :: T.Text } deriving (Generic, Show) instance ToJSON StartDeviceResponse where instance FromJSON StartDeviceResponse where data RestartDeviceResponse = RestartDeviceResponse { ok :: Bool, error :: T.Text } deriving (Generic, Show) instance ToJSON RestartDeviceResponse where instance FromJSON RestartDeviceResponse where data GetStdoutResponse = GetStdoutResponse { ok :: Bool, runcount :: Int, iov :: Iov } deriving (Generic, Show) instance ToJSON GetStdoutResponse where instance FromJSON GetStdoutResponse where data Iov = Iov { offset :: Int, base64bytes :: Base64Bytes } deriving (Generic, Show) instance ToJSON Iov where instance FromJSON Iov data StopDeviceResponse = StopDeviceResponse { ok :: Bool, error :: T.Text } deriving (Generic, Show) instance ToJSON StopDeviceResponse where instance FromJSON StopDeviceResponse where data GetCurrentLevelResponse = GetCurrentLevelResponse { ok :: Bool, level :: Int, name :: T.Text } deriving (Generic, Show) instance ToJSON GetCurrentLevelResponse where instance FromJSON GetCurrentLevelResponse where data LoadBytecodeResponse = LoadBytecodeResponse { ok :: Bool } deriving (Generic, Show) instance ToJSON LoadBytecodeResponse where instance FromJSON LoadBytecodeResponse where data ExecResponse = ExecResponse { ok :: Bool, error :: T.Text } deriving (Generic, Show) instance ToJSON ExecResponse where instance FromJSON ExecResponse where -- | Response from compiling a C program data CompileResponse = CompileResponse { ok :: Bool, bss :: Maybe T.Text, po :: Maybe Int, eov :: Maybe Int, raw :: Maybe T.Text, ep :: Maybe Int, row :: Int, text :: T.Text, token :: Maybe T.Text, functions :: Maybe [Function] } deriving (Generic, Show) instance ToJSON CompileResponse where instance FromJSON CompileResponse where data WriteBytecodeResponse = WriteBytecodeResponse { ok :: Bool, error :: Maybe T.Text } deriving (Generic, Show) instance ToJSON WriteBytecodeResponse where instance FromJSON WriteBytecodeResponse where data Function = Function { offset :: Int, name :: T.Text } deriving (Generic, Show) instance ToJSON Function where instance FromJSON Function where data ApuState = ApuState { -- | Instruction pointer pc :: Int, -- | Stack pointer sp :: HexString, -- | Flags register sr :: Int, -- | Flags register(string) sr_string :: T.Text, cycles :: Int, current_insn :: T.Text, registers :: [ HexString ] } deriving (Generic, Show) instance ToJSON ApuState where instance FromJSON ApuState where data Instruction = Instruction { ok :: Bool, raw64 :: T.Text, mnem :: T.Text, code :: Int, dest :: Int, src :: Int, k :: Int, s :: Int, b :: Int, a :: Maybe Int, q :: Maybe Int, offset :: Int, symbol :: Maybe T.Text, dump :: T.Text } deriving (Eq, Ord, Generic, Show, Data, Typeable) instance ToJSON Instruction where instance FromJSON Instruction where
MichaelBurge/stockfighter-jailbreak
src/Api/Stockfighter/Jailbreak/Types.hs
bsd-3-clause
4,538
0
12
904
1,237
711
526
142
0
{-# LANGUAGE MonoLocalBinds, ExistentialQuantification #-} -- | A specialised 'Manager' for 'Compiler's module Compiler.Manager ( -- * Interface to the module Compiler (..), Depmask (..), Bijection (..), -- * Building a manager Manager, mkCompilerManager, -- * Operations step, IndexError (..), Difference (..) ) where import Prelude hiding (lookup) import Control.Applicative ((<$>)) import Control.Arrow ((&&&)) import Compiler.Resources import Dependency.Manager (mkManager, Manager, Item (..),Depmask (..), step, Difference (..), IndexError (..)) import Data.Bijection -- | Abstract description of the steps leading to a compiled value. -- The compiled value /a/ type must be projectable to a common type /k/ to permit serialization. -- -- Each 'Compile' step require its type /a/ of dependencies, while the last 'Completed' step produces the compiled value /a/ -- -- Monad type /m/ for the computations and index type /b/ are free for the implementations -- data Monad m => Compiler m k b -- | Last compilation step, containing the new resource, and a set of new compilers. = forall a. Bijection a k => Completed (m a,[(b,Depmask b (Compiler m k b ))]) -- | Compile step. Dependency resources are expected with their index to produce next step. | forall a. Bijection a k => Compile (Depmask b ([(b,a)] -> m (Compiler m k b))) -- Maps compilers with a resource provider to an 'Item' builder mkItem :: (Monad m , Ord b) => (b -> Depmask b (Compiler m k b)) -- ^ base compilers for new resources , from dsl -> Resources m k b -- ^ resource manager -> b -- ^ a new index -> Depmask b (Item m b) -- ^ an item for the 'Dependency.Manager.mkManager' mkItem cs s x = mkItem' (x,cs x) where mkItem' (z,y) = f z <$> y f z co = Item (build' z co) (delete s z) build' z co = case co of Completed (y,cs) -> y >>= update s z >> return (map (fst &&& mkItem') cs) Compile (Depmask ds f) -> select s ds >>= f >>= build' z -- | Build a 'Manager' where each new 'Compiler' is projected in a new 'Item' for the 'Manager' to react on new indices. mkCompilerManager :: (Functor m, Monad m , Ord b) => (b -> Depmask b (Compiler m k b)) -- ^ base compiler selector for new resources -> Resources m k b -- ^ resource manager -> Manager m b -- ^ a fresh manager mkCompilerManager cs = mkManager . mkItem cs
paolino/dependencies-sm
Compiler/Manager.hs
bsd-3-clause
2,439
0
15
564
612
345
267
35
2
{-# LANGUAGE FlexibleContexts , GeneralizedNewtypeDeriving #-} module System.Heap.Heap where import Control.Applicative import Control.Exception import Control.Monad.Error import Control.Monad.Reader import Data.Binary import System.Heap.Error import System.Heap.Pointer import System.IO import qualified System.Heap.Alloc as Alloc import qualified System.Heap.Read as Read import qualified System.Heap.Write as Write newtype Heap a = Heap (Write.Heap a) deriving ( Functor , Applicative , Monad , MonadIO , MonadError HeapError ) write :: Binary a => a -> Heap (Pointer a) write = Heap . Write.write writeRoot :: Binary a => a -> Heap () writeRoot = Heap . Write.writeRoot read :: Binary a => Pointer a -> Heap a read = Heap . Write.read readRoot :: Binary a => Heap a readRoot = Heap Write.readRoot run :: FilePath -> Heap a -> IO (Either HeapError a) run f (Heap comp) = do me <- try $ withBinaryFile f ReadWriteMode $ \h -> runner h $ do initialize a <- comp Write.writeAllocationMap return a case me of Left e -> return (Left (IOError (show (e :: SomeException)))) Right r -> return r where runner h = Read.run h . Alloc.run . Write.run initialize :: Write.Heap () initialize = do fs <- ask >>= liftIO . hFileSize if fs == 0 -- Initialize new heap. then do _ <- Write.write magic -- magic file type identifier _ <- Write.write nullPtr -- pointer to allocation map _ <- Write.write nullPtr -- pointer to data structure root return () -- Initialize existing heap. else do m <- Write.read 0 when (m /= magic) (throwError InvalidHeapMagic) Write.readAllocationMap return ()
sebastiaanvisser/diskheap
src/System/Heap/Heap.hs
bsd-3-clause
1,861
0
17
540
567
290
277
53
2
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Network.SSH.LoadKeys where import Control.Monad ((<=<), unless) import Data.ByteArray.Encoding (Base(Base64), convertFromBase) import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Short as Short import Data.Serialize (runGet) import Text.Read (readMaybe) import qualified Crypto.PubKey.RSA as RSA import Network.SSH.Messages import Network.SSH.Named import Network.SSH.PrivateKeyFormat import Network.SSH.PubKey import Network.SSH.State #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif loadPublicKeys :: FilePath -> IO [SshPubCert] loadPublicKeys fp = do keys <- B.readFile fp return [ key | line <- B8.lines keys , key <- case decodePublicKey line of Right k -> [k] Left _ -> [] ] decodePublicKey :: ByteString -> Either String SshPubCert decodePublicKey xs = do (keyType, encoded) <- case B8.words xs of x:y:_ -> return (x,y) _ -> Left "Bad outer format" decoded <- convertFromBase Base64 encoded pubCert <- runGet getSshPubCert decoded unless (keyType == sshPubCertName pubCert) (Left "Mismatched key type") return pubCert -- | Load private keys from file. -- -- The keys file must be in OpenSSH format; see @:/server/README.md@. -- -- The 'ServerCredential' here is a misnomer, since both clients and -- servers use the same credential format. loadPrivateKeys :: FilePath -> IO [ServerCredential] loadPrivateKeys path = do res <- (extractPK <=< parsePrivateKeyFile) <$> B.readFile path case res of Left e -> fail ("Error loading server keys: " ++ e) Right pk -> return [ Named (Short.toShort (sshPubCertName pub)) (pub, priv) | (pub,priv,_comment) <- pk ] -- | Generate a random RSA 'ServerCredential' / named key pair. generateRsaKeyPair :: IO ServerCredential generateRsaKeyPair = do -- The '0x10001' exponent is suggested in the cryptonite -- documentation for 'RSA.generate'. (pub, priv) <- RSA.generate 256{-bytes-} 0x10001{-e-} let pub' = SshPubRsa (RSA.public_e pub) (RSA.public_n pub) let priv' = PrivateRsa priv return (Named "ssh-rsa" (pub', priv')) ---------------------------------------------------------------- -- Hacky serialization for use by CC. -- -- Some of the (non-RSA) types embedded 'ServerCredential' lack 'Read' -- or 'Show' instances, so we special case to RSA key pairs, which are -- the only type that CC uses. -- | String serialization for RSA key pairs. -- -- Fails for non-RSA credentials. showRsaKeyPair :: ServerCredential -> Maybe String showRsaKeyPair cred | "ssh-rsa" <- nameOf cred , (pub', priv') <- namedThing cred , SshPubRsa e n <- pub' , PrivateRsa priv <- priv' = Just $ show ("ssh-rsa" :: String, e, n, priv) | otherwise = Nothing -- | String de-serialization for RSA key pairs. -- -- Expects input produced by 'showRsaKeyPair'. readRsaKeyPair :: String -> Maybe ServerCredential readRsaKeyPair s | Just ( "ssh-rsa" :: String , e :: Integer , n :: Integer , priv :: RSA.PrivateKey ) <- readMaybe s , pub' <- SshPubRsa e n , priv' <- PrivateRsa priv = Just $ Named "ssh-rsa" (pub', priv') | otherwise = Nothing
glguy/ssh-hans
src/Network/SSH/LoadKeys.hs
bsd-3-clause
3,651
0
16
933
843
453
390
69
2
module Settings.Packages (packageArgs) where import Expression import Flavour import Oracles.Setting import Oracles.Flag import Packages import Rules.Gmp import Settings -- | Package-specific command-line arguments. packageArgs :: Args packageArgs = do stage <- getStage rtsWays <- getRtsWays path <- getBuildPath intLib <- getIntegerPackage compilerPath <- expr $ buildPath (vanillaContext stage compiler) gmpBuildPath <- expr gmpBuildPath let includeGmp = "-I" ++ gmpBuildPath -/- "include" -- Do not bind the result to a Boolean: this forces the configure rule -- immediately and may lead to cyclic dependencies. -- See: https://gitlab.haskell.org/ghc/ghc/issues/16809. cross = flag CrossCompiling mconcat --------------------------------- base --------------------------------- [ package base ? mconcat [ builder (Cabal Flags) ? notStage0 ? arg (pkgName intLib) -- This fixes the 'unknown symbol stat' issue. -- See: https://github.com/snowleopard/hadrian/issues/259. , builder (Ghc CompileCWithGhc) ? arg "-optc-O2" ] ------------------------------ bytestring ------------------------------ , package bytestring ? builder (Cabal Flags) ? intLib == integerSimple ? arg "integer-simple" --------------------------------- cabal -------------------------------- -- Cabal is a large library and slow to compile. Moreover, we build it -- for Stage0 only so we can link ghc-pkg against it, so there is little -- reason to spend the effort to optimise it. , package cabal ? stage0 ? builder Ghc ? arg "-O0" ------------------------------- compiler ------------------------------- , package compiler ? mconcat [ builder Alex ? arg "--latin1" , builder (Ghc CompileHs) ? mconcat [ inputs ["**/GHC.hs", "**/GhcMake.hs"] ? arg "-fprof-auto" , input "**/Parser.hs" ? pure ["-fno-ignore-interface-pragmas", "-fcmm-sink"] -- These files take a very long time to compile with -O1, -- so we use -O0 for them just in Stage0 to speed up the -- build but not affect Stage1+ executables , inputs ["**/HsInstances.hs", "**/DynFlags.hs"] ? stage0 ? pure ["-O0"] ] , builder (Cabal Setup) ? mconcat [ arg "--disable-library-for-ghci" , anyTargetOs ["openbsd"] ? arg "--ld-options=-E" , flag GhcUnregisterised ? arg "--ghc-option=-DNO_REGS" , notM targetSupportsSMP ? arg "--ghc-option=-DNOSMP" , notM targetSupportsSMP ? arg "--ghc-option=-optc-DNOSMP" , (any (wayUnit Threaded) rtsWays) ? notStage0 ? arg "--ghc-option=-optc-DTHREADED_RTS" , ghcWithInterpreter ? flag TablesNextToCode ? notM (flag GhcUnregisterised) ? notStage0 ? arg "--ghc-option=-DGHCI_TABLES_NEXT_TO_CODE" , ghcWithInterpreter ? ghciWithDebugger <$> flavour ? notStage0 ? arg "--ghc-option=-DDEBUGGER" , ghcProfiled <$> flavour ? notStage0 ? arg "--ghc-pkg-option=--force" ] , builder (Cabal Flags) ? mconcat [ ghcWithNativeCodeGen ? arg "ncg" , ghcWithInterpreter ? notStage0 ? arg "ghci" , cross ? arg "-terminfo" , notStage0 ? intLib == integerGmp ? arg "integer-gmp" , notStage0 ? intLib == integerSimple ? arg "integer-simple" ] , builder (Haddock BuildPackage) ? arg ("--optghc=-I" ++ path) ] ---------------------------------- ghc --------------------------------- , package ghc ? mconcat [ builder Ghc ? arg ("-I" ++ compilerPath) , builder (Cabal Flags) ? mconcat [ ghcWithInterpreter ? notStage0 ? arg "ghci" , cross ? arg "-terminfo" -- the 'threaded' flag is True by default, but -- let's record explicitly that we link all ghc -- executables with the threaded runtime. , arg "threaded" ] ] -------------------------------- ghcPkg -------------------------------- , package ghcPkg ? builder (Cabal Flags) ? cross ? arg "-terminfo" -------------------------------- ghcPrim ------------------------------- , package ghcPrim ? mconcat [ builder (Cabal Flags) ? arg "include-ghc-prim" , builder (Cc CompileC) ? (not <$> flag CcLlvmBackend) ? input "**/cbits/atomic.c" ? arg "-Wno-sync-nand" ] --------------------------------- ghci --------------------------------- -- TODO: This should not be @not <$> flag CrossCompiling@. Instead we -- should ensure that the bootstrap compiler has the same version as the -- one we are building. -- TODO: In that case we also do not need to build most of the Stage1 -- libraries, as we already know that the compiler comes with the most -- recent versions. -- TODO: The use case here is that we want to build @ghc-proxy@ for the -- cross compiler. That one needs to be compiled by the bootstrap -- compiler as it needs to run on the host. Hence @libiserv@ needs -- @GHCi.TH@, @GHCi.Message@ and @GHCi.Run@ from @ghci@. And those are -- behind the @-fghci@ flag. , package ghci ? mconcat [ notStage0 ? builder (Cabal Flags) ? arg "ghci" , cross ? stage0 ? builder (Cabal Flags) ? arg "ghci" ] -------------------------------- haddock ------------------------------- , package haddock ? builder (Cabal Flags) ? arg "in-ghc-tree" ------------------------------- haskeline ------------------------------ -- Hadrian doesn't currently support packages containing both libraries -- and executables. This flag disables the latter. , package haskeline ? builder (Cabal Flags) ? arg "-examples" -- Don't depend upon terminfo when cross-compiling to avoid unnecessary -- dependencies. -- TODO: Perhaps the user should rather be responsible for this? , package haskeline ? builder (Cabal Flags) ? cross ? arg "-terminfo" -------------------------------- hsc2hs -------------------------------- , package hsc2hs ? builder (Cabal Flags) ? arg "in-ghc-tree" ------------------------------ integerGmp ------------------------------ , package integerGmp ? mconcat [ builder Cc ? arg includeGmp , builder (Cabal Setup) ? mconcat [ flag GmpInTree ? arg "--configure-option=--with-intree-gmp" -- Windows is always built with inplace GMP until we have dynamic -- linking working. , windowsHost ? arg "--configure-option=--with-intree-gmp" , flag GmpFrameworkPref ? arg "--configure-option=--with-gmp-framework-preferred" , arg ("--configure-option=CFLAGS=" ++ includeGmp) , arg ("--gcc-options=" ++ includeGmp) ] ] ---------------------------------- rts --------------------------------- , package rts ? rtsPackageArgs -- RTS deserves a separate function -------------------------------- runGhc -------------------------------- , package runGhc ? builder Ghc ? input "**/Main.hs" ? (\version -> ["-cpp", "-DVERSION=" ++ show version]) <$> getSetting ProjectVersion --------------------------------- text --------------------------------- -- The package @text@ is rather tricky. It's a boot library, and it -- tries to determine on its own if it should link against @integer-gmp@ -- or @integer-simple@. For Stage0, we need to use the integer library -- that the bootstrap compiler has (since @interger@ is not a boot -- library) and therefore we copy it over into the Stage0 package-db. -- Maybe we should stop doing this? And subsequently @text@ for Stage1 -- detects the same integer library again, even though we don't build it -- in Stage1, and at that point the configuration is just wrong. , package text ? builder (Cabal Flags) ? notStage0 ? intLib == integerSimple ? pure ["+integer-simple", "-bytestring-builder"] ] -- | RTS-specific command line arguments. rtsPackageArgs :: Args rtsPackageArgs = package rts ? do projectVersion <- getSetting ProjectVersion hostPlatform <- getSetting HostPlatform hostArch <- getSetting HostArch hostOs <- getSetting HostOs hostVendor <- getSetting HostVendor buildPlatform <- getSetting BuildPlatform buildArch <- getSetting BuildArch buildOs <- getSetting BuildOs buildVendor <- getSetting BuildVendor targetPlatform <- getSetting TargetPlatform targetArch <- getSetting TargetArch targetOs <- getSetting TargetOs targetVendor <- getSetting TargetVendor ghcUnreg <- expr $ yesNo <$> flag GhcUnregisterised ghcEnableTNC <- expr $ yesNo <$> flag TablesNextToCode rtsWays <- getRtsWays way <- getWay path <- getBuildPath top <- expr topDirectory libffiName <- expr libffiLibraryName ffiIncludeDir <- getSetting FfiIncludeDir ffiLibraryDir <- getSetting FfiLibDir libdwIncludeDir <- getSetting LibdwIncludeDir libdwLibraryDir <- getSetting LibdwLibDir -- Arguments passed to GHC when compiling C and .cmm sources. let ghcArgs = mconcat [ arg "-Irts" , arg $ "-I" ++ path , flag WithLibdw ? if not (null libdwIncludeDir) then arg ("-I" ++ libdwIncludeDir) else mempty , flag WithLibdw ? if not (null libdwLibraryDir) then arg ("-L" ++ libdwLibraryDir) else mempty , arg $ "-DRtsWay=\"rts_" ++ show way ++ "\"" -- Set the namespace for the rts fs functions , arg $ "-DFS_NAMESPACE=rts" , arg $ "-DCOMPILING_RTS" , notM targetSupportsSMP ? arg "-DNOSMP" , way `elem` [debug, debugDynamic] ? arg "-DTICKY_TICKY" , Profiling `wayUnit` way ? arg "-DPROFILING" , Threaded `wayUnit` way ? arg "-DTHREADED_RTS" , notM targetSupportsSMP ? pure [ "-DNOSMP" , "-optc-DNOSMP" ] ] let cArgs = mconcat [ rtsWarnings , flag UseSystemFfi ? arg ("-I" ++ ffiIncludeDir) , flag WithLibdw ? arg ("-I" ++ libdwIncludeDir) , arg "-fomit-frame-pointer" -- RTS *must* be compiled with optimisations. The INLINE_HEADER macro -- requires that functions are inlined to work as expected. Inlining -- only happens for optimised builds. Otherwise we can assume that -- there is a non-inlined variant to use instead. But RTS does not -- provide non-inlined alternatives and hence needs the function to -- be inlined. See https://github.com/snowleopard/hadrian/issues/90. , arg "-O2" , arg "-g" , arg "-Irts" , arg $ "-I" ++ path , Debug `wayUnit` way ? pure [ "-DDEBUG" , "-fno-omit-frame-pointer" , "-g3" , "-O0" ] , useLibFFIForAdjustors ? arg "-DUSE_LIBFFI_FOR_ADJUSTORS" , inputs ["**/RtsMessages.c", "**/Trace.c"] ? arg ("-DProjectVersion=" ++ show projectVersion) , input "**/RtsUtils.c" ? pure [ "-DProjectVersion=" ++ show projectVersion , "-DHostPlatform=" ++ show hostPlatform , "-DHostArch=" ++ show hostArch , "-DHostOS=" ++ show hostOs , "-DHostVendor=" ++ show hostVendor , "-DBuildPlatform=" ++ show buildPlatform , "-DBuildArch=" ++ show buildArch , "-DBuildOS=" ++ show buildOs , "-DBuildVendor=" ++ show buildVendor , "-DTargetPlatform=" ++ show targetPlatform , "-DTargetArch=" ++ show targetArch , "-DTargetOS=" ++ show targetOs , "-DTargetVendor=" ++ show targetVendor , "-DGhcUnregisterised=" ++ show ghcUnreg , "-DTablesNextToCode=" ++ show ghcEnableTNC ] -- We're after pur performance here. So make sure fast math and -- vectorization is enabled. , input "**/xxhash.c" ? pure [ "-O3" , "-ffast-math" , "-ftree-vectorize" ] , inputs ["**/Evac.c", "**/Evac_thr.c"] ? arg "-funroll-loops" , speedHack ? inputs [ "**/Evac.c", "**/Evac_thr.c" , "**/Scav.c", "**/Scav_thr.c" , "**/Compact.c", "**/GC.c" ] ? arg "-fno-PIC" -- @-static@ is necessary for these bits, as otherwise the NCG -- generates dynamic references. , speedHack ? inputs [ "**/Updates.c", "**/StgMiscClosures.c" , "**/PrimOps.c", "**/Apply.c" , "**/AutoApply.c" ] ? pure ["-fno-PIC", "-static"] -- inlining warnings happen in Compact , inputs ["**/Compact.c"] ? arg "-Wno-inline" -- emits warnings about call-clobbered registers on x86_64 , inputs [ "**/StgCRun.c" , "**/win32/ConsoleHandler.c", "**/win32/ThrIOManager.c"] ? arg "-w" -- The above warning suppression flags are a temporary kludge. -- While working on this module you are encouraged to remove it and fix -- any warnings in the module. See: -- https://gitlab.haskell.org/ghc/ghc/wikis/working-conventions#Warnings , (not <$> flag CcLlvmBackend) ? inputs ["**/Compact.c"] ? arg "-finline-limit=2500" , input "**/RetainerProfile.c" ? flag CcLlvmBackend ? arg "-Wno-incompatible-pointer-types" , windowsHost ? arg ("-DWINVER=" ++ windowsVersion) -- libffi's ffi.h triggers various warnings , inputs [ "**/Interpreter.c", "**/Storage.c", "**/Adjustor.c" ] ? arg "-Wno-strict-prototypes" , inputs ["**/Interpreter.c", "**/Adjustor.c", "**/sm/Storage.c"] ? anyTargetArch ["powerpc"] ? arg "-Wno-undef" ] mconcat [ builder (Cabal Flags) ? mconcat [ any (wayUnit Profiling) rtsWays ? arg "profiling" , any (wayUnit Debug) rtsWays ? arg "debug" , any (wayUnit Logging) rtsWays ? arg "logging" , any (wayUnit Dynamic) rtsWays ? arg "dynamic" , Debug `wayUnit` way ? arg "find-ptr" ] , builder (Cc FindCDependencies) ? cArgs , builder (Ghc CompileCWithGhc) ? map ("-optc" ++) <$> cArgs , builder Ghc ? ghcArgs , builder HsCpp ? pure [ "-DTOP=" ++ show top , "-DFFI_INCLUDE_DIR=" ++ show ffiIncludeDir , "-DFFI_LIB_DIR=" ++ show ffiLibraryDir , "-DFFI_LIB=" ++ show libffiName , "-DLIBDW_LIB_DIR=" ++ show libdwLibraryDir ] , builder HsCpp ? flag WithLibdw ? arg "-DUSE_LIBDW" , builder HsCpp ? flag HaveLibMingwEx ? arg "-DHAVE_LIBMINGWEX" ] -- Compile various performance-critical pieces *without* -fPIC -dynamic -- even when building a shared library. If we don't do this, then the -- GC runs about 50% slower on x86 due to the overheads of PIC. The -- cost of doing this is a little runtime linking and less sharing, but -- not much. -- -- On x86_64 this doesn't work, because all objects in a shared library -- must be compiled with -fPIC (since the 32-bit relocations generated -- by the default small memory can't be resolved at runtime). So we -- only do this on i386. -- -- This apparently doesn't work on OS X (Darwin) nor on Solaris. -- On Darwin we get errors of the form -- -- ld: absolute addressing (perhaps -mdynamic-no-pic) used in _stg_ap_0_fast -- from rts/dist/build/Apply.dyn_o not allowed in slidable image -- -- and lots of these warnings: -- -- ld: warning codegen in _stg_ap_pppv_fast (offset 0x0000005E) prevents image -- from loading in dyld shared cache -- -- On Solaris we get errors like: -- -- Text relocation remains referenced -- against symbol offset in file -- .rodata (section) 0x11 rts/dist/build/Apply.dyn_o -- ... -- ld: fatal: relocations remain against allocatable but non-writable sections -- collect2: ld returned 1 exit status speedHack :: Action Bool speedHack = do i386 <- anyTargetArch ["i386"] goodOS <- not <$> anyTargetOs ["darwin", "solaris2"] return $ i386 && goodOS -- See @rts/ghc.mk@. rtsWarnings :: Args rtsWarnings = mconcat [ arg "-Wall" , arg "-Wextra" , arg "-Wstrict-prototypes" , arg "-Wmissing-prototypes" , arg "-Wmissing-declarations" , arg "-Winline" , arg "-Wpointer-arith" , arg "-Wmissing-noreturn" , arg "-Wnested-externs" , arg "-Wredundant-decls" , arg "-Wundef" , arg "-fno-strict-aliasing" ] -- These numbers can be found at: -- https://msdn.microsoft.com/en-us/library/windows/desktop/aa383745(v=vs.85).aspx -- If we're compiling on windows, enforce that we only support Vista SP1+ -- Adding this here means it doesn't have to be done in individual .c files -- and also centralizes the versioning. -- | Minimum supported Windows version. windowsVersion :: String windowsVersion = "0x06000100"
sdiehl/ghc
hadrian/src/Settings/Packages.hs
bsd-3-clause
18,226
0
20
5,600
2,857
1,461
1,396
235
3
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} module Matterhorn.State.Channels ( updateViewed , refreshChannel , refreshChannelsAndUsers , setFocus , refreshChannelById , applyPreferenceChange , leaveChannel , leaveCurrentChannel , getNextUnreadChannel , getNextUnreadUserOrChannel , nextUnreadChannel , nextUnreadUserOrChannel , createOrFocusDMChannel , prevChannel , nextChannel , recentChannel , setReturnChannel , resetReturnChannel , hideDMChannel , createGroupChannel , showGroupChannelPref , channelHistoryForward , channelHistoryBackward , handleNewChannel , createOrdinaryChannel , handleChannelInvite , addUserByNameToCurrentChannel , addUserToCurrentChannel , removeUserFromCurrentChannel , removeChannelFromState , isRecentChannel , isReturnChannel , isCurrentChannel , deleteCurrentChannel , startLeaveCurrentChannel , joinChannel , joinChannel' , joinChannelByName , changeChannelByName , setChannelTopic , getCurrentChannelTopic , beginCurrentChannelDeleteConfirm , toggleExpandedChannelTopics , updateChannelNotifyProps , renameChannelUrl , toggleChannelFavoriteStatus ) where import Prelude () import Matterhorn.Prelude import Brick.Main ( viewportScroll, vScrollToBeginning , invalidateCache, invalidateCacheEntry ) import Brick.Widgets.Edit ( applyEdit, getEditContents, editContentsL ) import Control.Concurrent.Async ( runConcurrently, Concurrently(..) ) import Control.Exception ( SomeException, try ) import Data.Char ( isAlphaNum ) import qualified Data.HashMap.Strict as HM import qualified Data.Foldable as F import Data.List ( nub ) import Data.Maybe ( fromJust ) import qualified Data.Set as S import qualified Data.Sequence as Seq import qualified Data.Text as T import Data.Text.Zipper ( textZipper, clearZipper, insertMany, gotoEOL ) import Data.Time.Clock ( getCurrentTime ) import Lens.Micro.Platform import qualified Network.Mattermost.Endpoints as MM import Network.Mattermost.Lenses import Network.Mattermost.Types import Matterhorn.Constants ( normalChannelSigil ) import Matterhorn.InputHistory import Matterhorn.State.Common import {-# SOURCE #-} Matterhorn.State.Messages ( fetchVisibleIfNeeded ) import Matterhorn.State.ChannelList import Matterhorn.State.Users import Matterhorn.State.Flagging import Matterhorn.Types import Matterhorn.Types.Common import Matterhorn.Zipper ( Zipper ) import qualified Matterhorn.Zipper as Z updateViewed :: Bool -> MH () updateViewed updatePrev = do csCurrentChannel.ccInfo.cdMentionCount .= 0 tId <- use csCurrentTeamId updateViewedChan updatePrev =<< use (csCurrentChannelId tId) -- | When a new channel has been selected for viewing, this will -- notify the server of the change, and also update the local channel -- state to set the last-viewed time for the previous channel and -- update the viewed time to now for the newly selected channel. -- -- The boolean argument indicates whether the view time of the previous -- channel (if any) should be updated, too. We typically want to do that -- only on channel switching; when we just want to update the view time -- of the specified channel, False should be provided. updateViewedChan :: Bool -> ChannelId -> MH () updateViewedChan updatePrev cId = use csConnectionStatus >>= \case -- Only do this if we're connected to avoid triggering noisy -- exceptions. Connected -> do withChannel cId $ \chan -> do pId <- if updatePrev then do case chan^.ccInfo.cdTeamId of Just tId -> use (csTeam(tId).tsRecentChannel) Nothing -> use (csCurrentTeam.tsRecentChannel) else return Nothing doAsyncChannelMM Preempt cId (\s c -> MM.mmViewChannel UserMe c pId s) (\c () -> Just $ setLastViewedFor pId c) Disconnected -> -- Cannot update server; make no local updates to avoid getting -- out of sync with the server. Assumes that this is a temporary -- break in connectivity and that after the connection is -- restored, the user's normal activities will update state as -- appropriate. If connectivity is permanently lost, managing -- this state is irrelevant. return () toggleExpandedChannelTopics :: MH () toggleExpandedChannelTopics = do mh invalidateCache csResources.crConfiguration.configShowExpandedChannelTopicsL %= not -- | If the current channel is a DM channel with a single user or a -- group of users, hide it from the sidebar and adjust the server-side -- preference to hide it persistently. Note that this does not actually -- hide the channel in our UI; we hide it in response to the preference -- change websocket event triggered by this function's API interaction -- with the server. -- -- If the current channel is any other kind of channel, complain with a -- usage error. hideDMChannel :: ChannelId -> MH () hideDMChannel cId = do me <- gets myUser session <- getSession withChannel cId $ \chan -> do case chan^.ccInfo.cdType of Direct -> do let pref = showDirectChannelPref (me^.userIdL) uId False Just uId = chan^.ccInfo.cdDMUserId csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing doAsyncWith Preempt $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing Group -> do let pref = hideGroupChannelPref cId (me^.userIdL) csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing doAsyncWith Preempt $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing _ -> do mhError $ GenericError "Cannot hide this channel. Consider using /leave instead." -- | Called on async completion when the currently viewed channel has -- been updated (i.e., just switched to this channel) to update local -- state. setLastViewedFor :: Maybe ChannelId -> ChannelId -> MH () setLastViewedFor prevId cId = do chan <- use (csChannels.to (findChannelById cId)) -- Update new channel's viewed time, creating the channel if needed case chan of Nothing -> -- It's possible for us to get spurious WMChannelViewed -- events from the server, e.g. for channels that have been -- deleted. So here we ignore the request since it's hard to -- detect it before this point. return () Just _ -> -- The server has been sent a viewed POST update, but there is -- no local information on what timestamp the server actually -- recorded. There are a couple of options for setting the -- local value of the viewed time: -- -- 1. Attempting to locally construct a value, which would -- involve scanning all (User) messages in the channel -- to find the maximum of the created date, the modified -- date, or the deleted date, and assuming that maximum -- mostly matched the server's viewed time. -- -- 2. Issuing a channel metadata request to get the server's -- new concept of the viewed time. -- -- 3. Having the "chan/viewed" POST that was just issued -- return a value from the server. See -- https://github.com/mattermost/platform/issues/6803. -- -- Method 3 would be the best and most lightweight. Until that -- is available, Method 2 will be used. The downside to Method -- 2 is additional client-server messaging, and a delay in -- updating the client data, but it's also immune to any new -- or removed Message date fields, or anything else that would -- contribute to the viewed/updated times on the server. doAsyncChannelMM Preempt cId (\ s _ -> (,) <$> MM.mmGetChannel cId s <*> MM.mmGetChannelMember cId UserMe s) (\pcid (cwd, member) -> Just $ csChannel(pcid).ccInfo %= channelInfoFromChannelWithData cwd member) -- Update the old channel's previous viewed time (allows tracking of -- new messages) case prevId of Nothing -> return () Just p -> clearChannelUnreadStatus p -- | Refresh information about all channels and users. This is usually -- triggered when a reconnect event for the WebSocket to the server -- occurs. refreshChannelsAndUsers :: MH () refreshChannelsAndUsers = do session <- getSession me <- gets myUser knownUsers <- gets allUserIds ts <- use csTeams doAsyncWith Preempt $ do pairs <- forM (HM.keys ts) $ \tId -> do runConcurrently $ (,) <$> Concurrently (MM.mmGetChannelsForUser UserMe tId session) <*> Concurrently (MM.mmGetChannelMembersForUser UserMe tId session) let (chans, datas) = (mconcat $ fst <$> pairs, mconcat $ snd <$> pairs) -- Collect all user IDs associated with DM channels so we can -- bulk-fetch their user records. let dmUsers = catMaybes $ flip map (F.toList chans) $ \chan -> case chan^.channelTypeL of Direct -> case userIdForDMChannel (userId me) (sanitizeUserText $ channelName chan) of Nothing -> Nothing Just otherUserId -> Just otherUserId _ -> Nothing uIdsToFetch = nub $ userId me : knownUsers <> dmUsers dataMap = HM.fromList $ toList $ (\d -> (channelMemberChannelId d, d)) <$> datas mkPair chan = (chan, fromJust $ HM.lookup (channelId chan) dataMap) chansWithData = mkPair <$> chans return $ Just $ -- Fetch user data associated with DM channels handleNewUsers (Seq.fromList uIdsToFetch) $ do -- Then refresh all loaded channels forM_ chansWithData $ uncurry (refreshChannel SidebarUpdateDeferred) updateSidebar Nothing -- | Refresh information about a specific channel. The channel -- metadata is refreshed, and if this is a loaded channel, the -- scrollback is updated as well. -- -- The sidebar update argument indicates whether this refresh should -- also update the sidebar. Ordinarily you want this, so pass -- SidebarUpdateImmediate unless you are very sure you know what you are -- doing, i.e., you are very sure that a call to refreshChannel will -- be followed immediately by a call to updateSidebar. We provide this -- control so that channel refreshes can be batched and then a single -- updateSidebar call can be used instead of the default behavior of -- calling it once per refreshChannel call, which is the behavior if the -- immediate setting is passed here. refreshChannel :: SidebarUpdate -> Channel -> ChannelMember -> MH () refreshChannel upd chan member = do ts <- use csTeams let ourTeams = HM.keys ts isOurTeam = case channelTeamId chan of Nothing -> True Just tId -> tId `elem` ourTeams case isOurTeam of False -> return () True -> do let cId = getId chan -- If this channel is unknown, register it first. mChan <- preuse (csChannel(cId)) when (isNothing mChan) $ handleNewChannel False upd chan member updateChannelInfo cId chan member handleNewChannel :: Bool -> SidebarUpdate -> Channel -> ChannelMember -> MH () handleNewChannel = handleNewChannel_ True handleNewChannel_ :: Bool -- ^ Whether to permit this call to recursively -- schedule itself for later if it can't locate -- a DM channel user record. This is to prevent -- uncontrolled recursion. -> Bool -- ^ Whether to switch to the new channel once it has -- been installed. -> SidebarUpdate -- ^ Whether to update the sidebar, in case the caller -- wants to batch these before updating it. Pass -- SidebarUpdateImmediate unless you know what -- you are doing, i.e., unless you intend to call -- updateSidebar yourself after calling this. -> Channel -- ^ The channel to install. -> ChannelMember -> MH () handleNewChannel_ permitPostpone switch sbUpdate nc member = do -- Only add the channel to the state if it isn't already known. me <- gets myUser mChan <- preuse (csChannel(getId nc)) case mChan of Just _ -> when switch $ setFocus (getId nc) Nothing -> do -- Create a new ClientChannel structure cChannel <- (ccInfo %~ channelInfoFromChannelWithData nc member) <$> makeClientChannel (me^.userIdL) nc st <- use id -- Add it to the message map, and to the name map so we -- can look it up by name. The name we use for the channel -- depends on its type: let chType = nc^.channelTypeL -- Get the channel name. If we couldn't, that means we have -- async work to do before we can register this channel (in -- which case abort because we got rescheduled). register <- case chType of Direct -> case userIdForDMChannel (myUserId st) (sanitizeUserText $ channelName nc) of Nothing -> return True Just otherUserId -> case userById otherUserId st of -- If we found a user ID in the channel -- name string but don't have that user's -- metadata, postpone adding this channel -- until we have fetched the metadata. This -- can happen when we have a channel record -- for a user that is no longer in the -- current team. To avoid recursion due to a -- problem, ensure that the rescheduled new -- channel handler is not permitted to try -- this again. -- -- If we're already in a recursive attempt -- to register this channel and still -- couldn't find a username, just bail and -- use the synthetic name (this has the same -- problems as above). Nothing -> do case permitPostpone of False -> return True True -> do mhLog LogAPI $ T.pack $ "handleNewChannel_: about to call handleNewUsers for " <> show otherUserId handleNewUsers (Seq.singleton otherUserId) (return ()) doAsyncWith Normal $ return $ Just $ handleNewChannel_ False switch sbUpdate nc member return False Just _ -> return True _ -> return True when register $ do csChannels %= addChannel (getId nc) cChannel when (sbUpdate == SidebarUpdateImmediate) $ do -- Note that we only check for whether we should -- switch to this channel when doing a sidebar -- update, since that's the only case where it's -- possible to do so. updateSidebar (cChannel^.ccInfo.cdTeamId) -- Finally, set our focus to the newly created -- channel if the caller requested a change of -- channel. Also consider the last join request -- state field in case this is an asynchronous -- channel addition triggered by a /join. pending1 <- checkPendingChannelChange (getId nc) pending2 <- case cChannel^.ccInfo.cdDMUserId of Nothing -> return False Just uId -> checkPendingChannelChangeByUserId uId when (switch || isJust pending1 || pending2) $ do setFocus (getId nc) case pending1 of Just (Just act) -> act _ -> return () -- | Check to see whether the specified channel has been queued up to -- be switched to. Note that this condition is only cleared by the -- actual setFocus switch to the channel because there may be multiple -- operations that must complete before the channel is fully ready for -- display/use. -- -- Returns Just if the specified channel has a pending switch. The -- result is an optional action to invoke after changing to the -- specified channel. checkPendingChannelChange :: ChannelId -> MH (Maybe (Maybe (MH ()))) checkPendingChannelChange cId = do ch <- use (csCurrentTeam.tsPendingChannelChange) curTid <- use csCurrentTeamId return $ case ch of Just (ChangeByChannelId tId i act) -> if i == cId && curTid == tId then Just act else Nothing _ -> Nothing -- | Check to see whether the specified channel has been queued up to -- be switched to. Note that this condition is only cleared by the -- actual setFocus switch to the channel because there may be multiple -- operations that must complete before the channel is fully ready for -- display/use. -- -- Returns Just if the specified channel has a pending switch. The -- result is an optional action to invoke after changing to the -- specified channel. checkPendingChannelChangeByUserId :: UserId -> MH Bool checkPendingChannelChangeByUserId uId = do ch <- use (csCurrentTeam.tsPendingChannelChange) return $ case ch of Just (ChangeByUserId i) -> i == uId _ -> False -- | Update the indicated Channel entry with the new data retrieved from -- the Mattermost server. Also update the channel name if it changed. updateChannelInfo :: ChannelId -> Channel -> ChannelMember -> MH () updateChannelInfo cid new member = do mh $ invalidateCacheEntry $ ChannelMessages cid csChannel(cid).ccInfo %= channelInfoFromChannelWithData new member withChannel cid $ \chan -> updateSidebar (chan^.ccInfo.cdTeamId) setFocus :: ChannelId -> MH () setFocus cId = do showChannelInSidebar cId True setFocusWith True (Z.findRight ((== cId) . channelListEntryChannelId)) (return ()) setFocusWith :: Bool -> (Zipper ChannelListGroup ChannelListEntry -> Zipper ChannelListGroup ChannelListEntry) -> MH () -> MH () setFocusWith updatePrev f onNoChange = do tId <- use csCurrentTeamId oldZipper <- use (csCurrentTeam.tsFocus) let newZipper = f oldZipper newFocus = Z.focus newZipper oldFocus = Z.focus oldZipper -- If we aren't changing anything, skip all the book-keeping because -- we'll end up clobbering things like tsRecentChannel. if newFocus /= oldFocus then do mh $ invalidateCacheEntry $ ChannelSidebar tId resetAutocomplete preChangeChannelCommon csCurrentTeam.tsFocus .= newZipper now <- liftIO getCurrentTime newCid <- use (csCurrentChannelId tId) csChannel(newCid).ccInfo.cdSidebarShowOverride .= Just now updateViewed updatePrev postChangeChannelCommon else onNoChange postChangeChannelCommon :: MH () postChangeChannelCommon = do resetEditorState updateChannelListScroll loadLastEdit fetchVisibleIfNeeded loadLastEdit :: MH () loadLastEdit = do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) oldEphemeral <- preuse (csChannel(cId).ccEditState) case oldEphemeral of Nothing -> return () Just e -> csCurrentTeam.tsEditState.cedEphemeral .= e loadLastChannelInput loadLastChannelInput :: MH () loadLastChannelInput = do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) inputHistoryPos <- use (csCurrentTeam.tsEditState.cedEphemeral.eesInputHistoryPosition) case inputHistoryPos of Just i -> loadHistoryEntryToEditor cId i Nothing -> do (lastEdit, lastEditMode) <- use (csCurrentTeam.tsEditState.cedEphemeral.eesLastInput) csCurrentTeam.tsEditState.cedEditor %= (applyEdit $ insertMany lastEdit . clearZipper) csCurrentTeam.tsEditState.cedEditMode .= lastEditMode updateChannelListScroll :: MH () updateChannelListScroll = do tId <- use csCurrentTeamId mh $ vScrollToBeginning (viewportScroll $ ChannelList tId) preChangeChannelCommon :: MH () preChangeChannelCommon = do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) csCurrentTeam.tsRecentChannel .= Just cId saveCurrentEdit resetEditorState :: MH () resetEditorState = do csCurrentTeam.tsEditState.cedEditMode .= NewPost clearEditor clearEditor :: MH () clearEditor = csCurrentTeam.tsEditState.cedEditor %= applyEdit clearZipper saveCurrentEdit :: MH () saveCurrentEdit = do saveCurrentChannelInput oldEphemeral <- use (csCurrentTeam.tsEditState.cedEphemeral) tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) csChannel(cId).ccEditState .= oldEphemeral saveCurrentChannelInput :: MH () saveCurrentChannelInput = do cmdLine <- use (csCurrentTeam.tsEditState.cedEditor) mode <- use (csCurrentTeam.tsEditState.cedEditMode) -- Only save the editor contents if the user is not navigating the -- history. inputHistoryPos <- use (csCurrentTeam.tsEditState.cedEphemeral.eesInputHistoryPosition) when (isNothing inputHistoryPos) $ csCurrentTeam.tsEditState.cedEphemeral.eesLastInput .= (T.intercalate "\n" $ getEditContents $ cmdLine, mode) applyPreferenceChange :: Preference -> MH () applyPreferenceChange pref = do -- always update our user preferences accordingly csResources.crUserPreferences %= setUserPreferences (Seq.singleton pref) -- Invalidate the entire rendering cache since many things depend on -- user preferences mh invalidateCache if | Just f <- preferenceToFlaggedPost pref -> do updateMessageFlag (flaggedPostId f) (flaggedPostStatus f) | Just tIds <- preferenceToTeamOrder pref -> applyTeamOrder tIds | Just d <- preferenceToDirectChannelShowStatus pref -> do updateSidebar Nothing cs <- use csChannels -- We need to check on whether this preference was to show a -- channel and, if so, whether it was the one we attempted to -- switch to (thus triggering the preference change). If so, -- we need to switch to it now. let Just cId = getDmChannelFor (directChannelShowUserId d) cs case directChannelShowValue d of True -> do pending <- checkPendingChannelChange cId case pending of Just mAct -> do setFocus cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | Just g <- preferenceToGroupChannelPreference pref -> do updateSidebar Nothing -- We need to check on whether this preference was to show a -- channel and, if so, whether it was the one we attempted to -- switch to (thus triggering the preference change). If so, -- we need to switch to it now. let cId = groupChannelId g case groupChannelShow g of True -> do pending <- checkPendingChannelChange cId case pending of Just mAct -> do setFocus cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | Just f <- preferenceToFavoriteChannelPreference pref -> do updateSidebar Nothing -- We need to check on whether this preference was to show a -- channel and, if so, whether it was the one we attempted to -- switch to (thus triggering the preference change). If so, -- we need to switch to it now. let cId = favoriteChannelId f case favoriteChannelShow f of True -> do pending <- checkPendingChannelChange cId case pending of Just mAct -> do setFocus cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | otherwise -> return () refreshChannelById :: ChannelId -> MH () refreshChannelById cId = do session <- getSession doAsyncWith Preempt $ do cwd <- MM.mmGetChannel cId session member <- MM.mmGetChannelMember cId UserMe session return $ Just $ do refreshChannel SidebarUpdateImmediate cwd member removeChannelFromState :: ChannelId -> MH () removeChannelFromState cId = do withChannel cId $ \ chan -> do when (chan^.ccInfo.cdType /= Direct) $ do case chan^.ccInfo.cdTeamId of Nothing -> return () Just tId -> do origFocus <- use (csCurrentChannelId tId) when (origFocus == cId) nextChannelSkipPrevView -- Update input history csInputHistory %= removeChannelHistory cId -- Update msgMap csChannels %= removeChannel cId case chan^.ccInfo.cdTeamId of Nothing -> do ts <- use csTeams forM_ (HM.keys ts) $ \tId -> csTeam(tId).tsFocus %= Z.filterZipper ((/= cId) . channelListEntryChannelId) Just tId -> do csTeam(tId).tsFocus %= Z.filterZipper ((/= cId) . channelListEntryChannelId) updateSidebar $ chan^.ccInfo.cdTeamId nextChannel :: MH () nextChannel = do resetReturnChannel setFocusWith True Z.right (return ()) -- | This is almost never what you want; we use this when we delete a -- channel and we don't want to update the deleted channel's view time. nextChannelSkipPrevView :: MH () nextChannelSkipPrevView = setFocusWith False Z.right (return ()) prevChannel :: MH () prevChannel = do resetReturnChannel setFocusWith True Z.left (return ()) recentChannel :: MH () recentChannel = do recent <- use (csCurrentTeam.tsRecentChannel) case recent of Nothing -> return () Just cId -> do ret <- use (csCurrentTeam.tsReturnChannel) when (ret == Just cId) resetReturnChannel setFocus cId resetReturnChannel :: MH () resetReturnChannel = do val <- use (csCurrentTeam.tsReturnChannel) case val of Nothing -> return () Just _ -> do tId <- use csCurrentTeamId mh $ invalidateCacheEntry $ ChannelSidebar tId csCurrentTeam.tsReturnChannel .= Nothing gotoReturnChannel :: MH () gotoReturnChannel = do ret <- use (csCurrentTeam.tsReturnChannel) case ret of Nothing -> return () Just cId -> do resetReturnChannel setFocus cId setReturnChannel :: MH () setReturnChannel = do ret <- use (csCurrentTeam.tsReturnChannel) case ret of Nothing -> do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) csCurrentTeam.tsReturnChannel .= Just cId mh $ invalidateCacheEntry $ ChannelSidebar tId Just _ -> return () nextUnreadChannel :: MH () nextUnreadChannel = do st <- use id setReturnChannel setFocusWith True (getNextUnreadChannel st) gotoReturnChannel nextUnreadUserOrChannel :: MH () nextUnreadUserOrChannel = do st <- use id setReturnChannel setFocusWith True (getNextUnreadUserOrChannel st) gotoReturnChannel leaveChannel :: ChannelId -> MH () leaveChannel cId = leaveChannelIfPossible cId False leaveChannelIfPossible :: ChannelId -> Bool -> MH () leaveChannelIfPossible cId delete = do st <- use id me <- gets myUser let isMe u = u^.userIdL == me^.userIdL case st ^? csChannel(cId).ccInfo of Nothing -> return () Just cInfo -> case canLeaveChannel cInfo of False -> return () True -> -- The server will reject an attempt to leave a private -- channel if we're the only member. To check this, we -- just ask for the first two members of the channel. -- If there is only one, it must be us: hence the "all -- isMe" check below. If there are two members, it -- doesn't matter who they are, because we just know -- that we aren't the only remaining member, so we can't -- delete the channel. doAsyncChannelMM Preempt cId (\s _ -> let query = MM.defaultUserQuery { MM.userQueryPage = Just 0 , MM.userQueryPerPage = Just 2 , MM.userQueryInChannel = Just cId } in toList <$> MM.mmGetUsers query s) (\_ members -> Just $ do -- If the channel is private: -- * leave it if we aren't the last member. -- * delete it if we are. -- -- Otherwise: -- * leave (or delete) the channel as specified -- by the delete argument. let func = case cInfo^.cdType of Private -> case all isMe members of True -> (\ s c -> MM.mmDeleteChannel c s) False -> (\ s c -> MM.mmRemoveUserFromChannel c UserMe s) Group -> \s _ -> let pref = hideGroupChannelPref cId (me^.userIdL) in MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) s _ -> if delete then (\ s c -> MM.mmDeleteChannel c s) else (\ s c -> MM.mmRemoveUserFromChannel c UserMe s) doAsyncChannelMM Preempt cId func endAsyncNOP ) getNextUnreadChannel :: ChatState -> (Zipper a ChannelListEntry -> Zipper a ChannelListEntry) getNextUnreadChannel st = -- The next channel with unread messages must also be a channel -- other than the current one, since the zipper may be on a channel -- that has unread messages and will stay that way until we leave -- it- so we need to skip that channel when doing the zipper search -- for the next candidate channel. Z.findRight (\e -> let cId = channelListEntryChannelId e in channelListEntryUnread e && (cId /= st^.csCurrentChannelId(st^.csCurrentTeamId))) getNextUnreadUserOrChannel :: ChatState -> Zipper a ChannelListEntry -> Zipper a ChannelListEntry getNextUnreadUserOrChannel st z = -- Find the next unread channel, prefering direct messages let cur = st^.csCurrentChannelId(st^.csCurrentTeamId) matches e = entryIsDMEntry e && isFresh e isFresh e = channelListEntryUnread e && (channelListEntryChannelId e /= cur) in fromMaybe (Z.findRight isFresh z) (Z.maybeFindRight matches z) leaveCurrentChannel :: MH () leaveCurrentChannel = do tId <- use csCurrentTeamId use (csCurrentChannelId tId) >>= leaveChannel createGroupChannel :: Text -> MH () createGroupChannel usernameList = do me <- gets myUser session <- getSession cs <- use csChannels doAsyncWith Preempt $ do let usernames = Seq.fromList $ fmap trimUserSigil $ T.words usernameList results <- MM.mmGetUsersByUsernames usernames session -- If we found all of the users mentioned, then create the group -- channel. case length results == length usernames of True -> do chan <- MM.mmCreateGroupMessageChannel (userId <$> results) session return $ Just $ do case findChannelById (channelId chan) cs of Just _ -> -- If we already know about the channel ID, -- that means the channel already exists so -- we can just switch to it. setFocus (channelId chan) Nothing -> do tId <- use csCurrentTeamId csCurrentTeam.tsPendingChannelChange .= (Just $ ChangeByChannelId tId (channelId chan) Nothing) let pref = showGroupChannelPref (channelId chan) (me^.userIdL) doAsyncWith Normal $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return $ Just $ applyPreferenceChange pref False -> do let foundUsernames = userUsername <$> results missingUsernames = S.toList $ S.difference (S.fromList $ F.toList usernames) (S.fromList $ F.toList foundUsernames) return $ Just $ do forM_ missingUsernames (mhError . NoSuchUser) channelHistoryForward :: MH () channelHistoryForward = do resetAutocomplete tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) inputHistoryPos <- use (csCurrentTeam.tsEditState.cedEphemeral.eesInputHistoryPosition) case inputHistoryPos of Just i | i == 0 -> do -- Transition out of history navigation csCurrentTeam.tsEditState.cedEphemeral.eesInputHistoryPosition .= Nothing loadLastChannelInput | otherwise -> do let newI = i - 1 loadHistoryEntryToEditor cId newI csCurrentTeam.tsEditState.cedEphemeral.eesInputHistoryPosition .= (Just newI) _ -> return () loadHistoryEntryToEditor :: ChannelId -> Int -> MH () loadHistoryEntryToEditor cId idx = do inputHistory <- use csInputHistory case getHistoryEntry cId idx inputHistory of Nothing -> return () Just entry -> do let eLines = T.lines entry mv = if length eLines == 1 then gotoEOL else id csCurrentTeam.tsEditState.cedEditor.editContentsL .= (mv $ textZipper eLines Nothing) channelHistoryBackward :: MH () channelHistoryBackward = do resetAutocomplete tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) inputHistoryPos <- use (csCurrentTeam.tsEditState.cedEphemeral.eesInputHistoryPosition) saveCurrentChannelInput let newI = maybe 0 (+ 1) inputHistoryPos loadHistoryEntryToEditor cId newI csCurrentTeam.tsEditState.cedEphemeral.eesInputHistoryPosition .= (Just newI) createOrdinaryChannel :: Bool -> Text -> MH () createOrdinaryChannel public name = do session <- getSession myTId <- use csCurrentTeamId doAsyncWith Preempt $ do -- create a new chat channel let slug = T.map (\ c -> if isAlphaNum c then c else '-') (T.toLower name) minChannel = MinChannel { minChannelName = slug , minChannelDisplayName = name , minChannelPurpose = Nothing , minChannelHeader = Nothing , minChannelType = if public then Ordinary else Private , minChannelTeamId = myTId } tryMM (do c <- MM.mmCreateChannel minChannel session chan <- MM.mmGetChannel (getId c) session member <- MM.mmGetChannelMember (getId c) UserMe session return (chan, member) ) (return . Just . uncurry (handleNewChannel True SidebarUpdateImmediate)) -- | When we are added to a channel not locally known about, we need -- to fetch the channel info for that channel. handleChannelInvite :: ChannelId -> MH () handleChannelInvite cId = do session <- getSession doAsyncWith Normal $ do member <- MM.mmGetChannelMember cId UserMe session tryMM (MM.mmGetChannel cId session) (\cwd -> return $ Just $ do pending <- checkPendingChannelChange cId handleNewChannel (isJust pending) SidebarUpdateImmediate cwd member) addUserByNameToCurrentChannel :: Text -> MH () addUserByNameToCurrentChannel uname = withFetchedUser (UserFetchByUsername uname) addUserToCurrentChannel addUserToCurrentChannel :: UserInfo -> MH () addUserToCurrentChannel u = do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) session <- getSession let channelMember = MinChannelMember (u^.uiId) cId doAsyncWith Normal $ do tryMM (void $ MM.mmAddUser cId channelMember session) (const $ return Nothing) removeUserFromCurrentChannel :: Text -> MH () removeUserFromCurrentChannel uname = withFetchedUser (UserFetchByUsername uname) $ \u -> do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) session <- getSession doAsyncWith Normal $ do tryMM (void $ MM.mmRemoveUserFromChannel cId (UserById $ u^.uiId) session) (const $ return Nothing) startLeaveCurrentChannel :: MH () startLeaveCurrentChannel = do cInfo <- use (csCurrentChannel.ccInfo) case cInfo^.cdType of Direct -> hideDMChannel (cInfo^.cdChannelId) Group -> hideDMChannel (cInfo^.cdChannelId) _ -> setMode LeaveChannelConfirm deleteCurrentChannel :: MH () deleteCurrentChannel = do setMode Main tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) leaveChannelIfPossible cId True isCurrentChannel :: ChatState -> ChannelId -> Bool isCurrentChannel st cId = st^.csCurrentChannelId(st^.csCurrentTeamId) == cId isRecentChannel :: ChatState -> ChannelId -> Bool isRecentChannel st cId = st^.csCurrentTeam.tsRecentChannel == Just cId isReturnChannel :: ChatState -> ChannelId -> Bool isReturnChannel st cId = st^.csCurrentTeam.tsReturnChannel == Just cId joinChannelByName :: Text -> MH () joinChannelByName rawName = do session <- getSession tId <- use csCurrentTeamId doAsyncWith Preempt $ do result <- try $ MM.mmGetChannelByName tId (trimChannelSigil rawName) session return $ Just $ case result of Left (_::SomeException) -> mhError $ NoSuchChannel rawName Right chan -> joinChannel $ getId chan -- | If the user is not a member of the specified channel, submit a -- request to join it. Otherwise switch to the channel. joinChannel :: ChannelId -> MH () joinChannel chanId = joinChannel' chanId Nothing joinChannel' :: ChannelId -> Maybe (MH ()) -> MH () joinChannel' chanId act = do setMode Main mChan <- preuse (csChannel(chanId)) case mChan of Just _ -> do setFocus chanId fromMaybe (return ()) act Nothing -> do myId <- gets myUserId tId <- use csCurrentTeamId let member = MinChannelMember myId chanId csCurrentTeam.tsPendingChannelChange .= (Just $ ChangeByChannelId tId chanId act) doAsyncChannelMM Preempt chanId (\ s c -> MM.mmAddUser c member s) (const $ return act) createOrFocusDMChannel :: UserInfo -> Maybe (ChannelId -> MH ()) -> MH () createOrFocusDMChannel user successAct = do cs <- use csChannels case getDmChannelFor (user^.uiId) cs of Just cId -> do setFocus cId case successAct of Nothing -> return () Just act -> act cId Nothing -> do -- We have a user of that name but no channel. Time to make one! myId <- gets myUserId session <- getSession csCurrentTeam.tsPendingChannelChange .= (Just $ ChangeByUserId $ user^.uiId) doAsyncWith Normal $ do -- create a new channel chan <- MM.mmCreateDirectMessageChannel (user^.uiId, myId) session return $ successAct <*> pure (channelId chan) -- | This switches to the named channel or creates it if it is a missing -- but valid user channel. changeChannelByName :: Text -> MH () changeChannelByName name = do myId <- gets myUserId mCId <- gets (channelIdByChannelName name) mDMCId <- gets (channelIdByUsername name) withFetchedUserMaybe (UserFetchByUsername name) $ \foundUser -> do if (_uiId <$> foundUser) == Just myId then return () else do setMode Main let err = mhError $ AmbiguousName name case (mCId, mDMCId) of (Nothing, Nothing) -> case foundUser of -- We know about the user but there isn't already a DM -- channel, so create one. Just user -> createOrFocusDMChannel user Nothing -- There were no matches of any kind. Nothing -> mhError $ NoSuchChannel name (Just cId, Nothing) -- We matched a channel and there was an explicit sigil, so we -- don't care about the username match. | normalChannelSigil `T.isPrefixOf` name -> setFocus cId -- We matched both a channel and a user, even though there is -- no DM channel. | Just _ <- foundUser -> err -- We matched a channel only. | otherwise -> setFocus cId (Nothing, Just cId) -> -- We matched a DM channel only. setFocus cId (Just _, Just _) -> -- We matched both a channel and a DM channel. err setChannelTopic :: Text -> MH () setChannelTopic msg = do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) let patch = defaultChannelPatch { channelPatchHeader = Just msg } doAsyncChannelMM Preempt cId (\s _ -> MM.mmPatchChannel cId patch s) (\_ _ -> Nothing) -- | This renames the current channel's url name. It makes a request -- to the server to change the name, but does not actually change the -- name in Matterhorn yet; that is handled by a websocket event handled -- asynchronously. renameChannelUrl :: Text -> MH () renameChannelUrl name = do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) s <- getSession let patch = defaultChannelPatch { channelPatchName = Just name } doAsyncWith Normal $ do _ <- MM.mmPatchChannel cId patch s return Nothing getCurrentChannelTopic :: MH Text getCurrentChannelTopic = do ch <- use csCurrentChannel return $ ch^.ccInfo.cdHeader beginCurrentChannelDeleteConfirm :: MH () beginCurrentChannelDeleteConfirm = do tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) withChannel cId $ \chan -> do let chType = chan^.ccInfo.cdType if chType /= Direct then setMode DeleteChannelConfirm else mhError $ GenericError "Direct message channels cannot be deleted." updateChannelNotifyProps :: ChannelId -> ChannelNotifyProps -> MH () updateChannelNotifyProps cId notifyProps = do withChannel cId $ \chan -> do csChannel(cId).ccInfo.cdNotifyProps .= notifyProps updateSidebar (chan^.ccInfo.cdTeamId) toggleChannelFavoriteStatus :: MH () toggleChannelFavoriteStatus = do myId <- gets myUserId tId <- use csCurrentTeamId cId <- use (csCurrentChannelId tId) userPrefs <- use (csResources.crUserPreferences) session <- getSession let favPref = favoriteChannelPreference userPrefs cId trueVal = "true" prefVal = case favPref of Just True -> "" Just False -> trueVal Nothing -> trueVal pref = Preference { preferenceUserId = myId , preferenceCategory = PreferenceCategoryFavoriteChannel , preferenceName = PreferenceName $ idString cId , preferenceValue = PreferenceValue prefVal } doAsyncWith Normal $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing
matterhorn-chat/matterhorn
src/Matterhorn/State/Channels.hs
bsd-3-clause
46,020
0
32
14,706
9,157
4,484
4,673
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Views.Tests (tests) where import Test.Framework (Test, testGroup) import qualified Views.PaginationSplicesTest (tests) import qualified Views.ReplySplicesTest (tests) tests :: Test tests = testGroup "Test.Views" [ Views.ReplySplicesTest.tests , Views.PaginationSplicesTest.tests ]
HaskellCNOrg/snap-web
tests/Views/Tests.hs
bsd-3-clause
368
0
7
77
74
46
28
9
1
module AbstractInterpreter.Tools where {- This module reexports functions to check totality and stricter values -} import TypeSystem import Utils.Utils import Utils.ToString import AbstractInterpreter.AbstractSet import AbstractInterpreter.Assignment import AbstractInterpreter.FunctionAnalysis import AbstractInterpreter.RuleAnalysis as RI import AbstractInterpreter.MinimalTypes import Data.Map (Map, (!)) import qualified Data.Map as M import Data.Set (Set) import qualified Data.Set as S import Data.List import Data.Maybe import Control.Monad import Control.Arrow ((&&&)) checkTS ts = let fs = get tsFunctions ts analysises = fs |> analyzeFunction' ts :: Map Name FunctionAnalysis in [checkTotality ts analysises, checkDeadClauses ts analysises, checkStrictestTypes ts] & allRight_ & inMsg "Warning" checkTotality :: TypeSystem -> Map Name FunctionAnalysis -> Either String () checkTotality ts analysises = do let syntax = get tsSyntax ts let leftOvers = analysises |> get functionLeftOvers & M.filter (not . S.null) & M.toList :: [(Name, Set Arguments)] leftOvers |> totalityErr & allRight_ totalityErr :: (Name, Set Arguments) -> Either String () totalityErr (nm, over) = inMsg ("While checking the totality of function "++show nm) $ inMsg "Following calls will fall through" $ do let msgs = over & S.toList |> toParsable' ", " |> inParens |> (nm++) & unlines Left msgs checkDeadClauses :: TypeSystem -> Map Name FunctionAnalysis -> Either String () checkDeadClauses ts analysises = analysises & M.toList |> checkDeadClausesFor ts & allRight_ checkDeadClausesFor :: TypeSystem -> (Name, FunctionAnalysis) -> Either String () checkDeadClausesFor ts (nm, analysis) = do let f = get tsFunctions ts ! nm inMsg ("While checking liveability of every clause in function "++show nm) $ analysis & get clauseAnalysises |> checkDeadClause (nm, f) & allRight_ checkDeadClause :: (Name, Function) -> ClauseAnalysis -> Either String () checkDeadClause (nm, MFunction _ clauses) ca = let isDead = (ca & get results & M.null) clause = clauses & safeIndex "No clause found in checkDeadClauses" (get clauseIndex ca) msg = toParsable' (nm, 24::Int) clause ++ " will never match anything, as the possible arguments are already consumed" in when isDead $ Left msg checkStrictestTypes :: TypeSystem -> Either String () checkStrictestTypes ts = inMsg "While checking that the functions do have the strictest possible types" $ do let stricter = stricterTypes ts (get tsFunctions ts) & M.toList let origType n = (get tsFunctions ts ! n) & typesOf & last stricter |> (\(nm, tp) -> show nm++" can be typed as "++show tp++", instead of a "++show (origType nm)) |> Left & allRight_
pietervdvn/ALGT
src/AbstractInterpreter/Tools.hs
bsd-3-clause
2,756
127
15
485
870
481
389
54
1
-- | The following example declare the top level ports and generates Verilog for a 'GCD' machine. module Main ( main ) where -- Import the TRS modules. import Language.TRS -- | The entry point of any Haskell program. main :: IO () main = do putStrLn "Hello TRS!" putStrLn "Generating a netlist for a sorter machine..." verilog "sorter" $ sorterExample 8 8 verilog "sorter_stimulus" $ sorterStimulus 8 8 data Sorter = Sorter [Reg] sorter :: Width -> Depth -> System Sorter sorter width depth = do regs <- regs "reg" width depth 0 swap 0 regs return $ Sorter regs where swap :: Int -> [Reg] -> System () swap _ [] = return () swap _ [_] = return () swap n (a:b:c) = do rule ("swap_" ++ show n ++ "_" ++ show (n + 1)) $ do when (value b <. value a) a <== value b b <== value a swap (n+1) (b:c) load :: [Signal] -> Sorter -> Action () load signals s@(Sorter regs) = do when $ isSorted s mapM_ (\ (r,s) -> r <== s) $ zip regs signals sortedValues :: Sorter -> [Signal] sortedValues (Sorter regs) = map value regs isSorted :: Sorter -> Signal isSorted (Sorter regs) = isSorted regs where isSorted :: [Reg] -> Signal isSorted [] = true isSorted [_] = true isSorted (a:b:c) = (value a <=. value b) &. isSorted (b:c) sorterExample :: Width -> Depth -> System () sorterExample w d = do loadData <- input "load" 1 ins <- inputs "in" w d s <- sorter w d rule "loadData" $ do when loadData load ins s output "sorted" $ isSorted s outputs "out" $ sortedValues s sorterStimulus :: Width -> Depth -> System () sorterStimulus w d = do sorted <- input "sorted" 1 outs <- inputs "out" w d load <- reg "loadData" 1 0 output "load" $ value load testValues <- regs "testValues" w d 0 outputs "in" $ map value testValues let tests = [ [0, 0, 0, 0, 0, 0, 0, 0] , [7, 6, 5, 4, 3, 2, 1, 0] , [6, 6, 4, 4, 2, 2, 0, 0] , [1, 0, 3, 2, 5, 4, 7, 6] , [6, 7, 4, 5, 2, 3, 0, 1] ] test vs = [startLoad, dropLoad, displaySorted] where startLoad = foldl (>>) (load <== true) $ map (\ (r,v) -> r <== constant (width r) v) $ zip testValues vs dropLoad = load <== false displaySorted = do when sorted display ("sorted: " ++ concatMap (\ _ -> "%d ") [1 .. d] ++ " => " ++ concatMap (\ _ -> "%d ") [1 .. d]) $ (map value testValues) ++ outs sequenceActions "testSequence" $ concatMap test tests ++ [finish "Test complete." []]
tomahawkins/trs
Examples/Sorter.hs
bsd-3-clause
2,534
0
23
711
1,124
568
556
65
3
-------------------------------------------------------------------- -- | -- Module : Text.PDF.Transformations -- Description : Functions for transforming PDF content. -- Copyright : (c) Dylan McNamee 2011 -- License : BSD3 -- -- Maintainer: Dylan McNamee <[email protected]> -- Stability : provisional -- Portability: portable -- -------------------------------------------------------------------- module Text.PDF.Transformations where import Text.PDF.Types -- Overlay a string each page of a document watermarkDocument :: String -> PDFDocumentParsed -> PDFDocumentParsed watermarkDocument markString doc@(PDFDocumentParsed pages {- _dict -} ) = doc { pageList = Prelude.map (appendStreamToPage markString) pages -- , globals = dict } appendStreamToPage :: String -> PDFPageParsed -> PDFPageParsed appendStreamToPage string page = page { contents = case (contents page) of (PDFStream s) -> PDFArray [(PDFStream s), (PDFStream string)] (PDFArray streams) -> PDFArray (streams ++ [(PDFStream string)] ) _ -> error "appendStreamToPage: neither Stream nor Array in contents of a page" } reversePages :: PDFDocumentParsed -> PDFDocumentParsed reversePages doc@(PDFDocumentParsed pages {- _dict -} ) = doc { pageList = reverse pages }
dylanmc/Haskell-PDF-Parsing-Library
Text/PDF/Transformations.hs
bsd-3-clause
1,284
0
15
209
233
132
101
14
3
{-# LANGUAGE RebindableSyntax #-} -- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) #define ONLY_SMALL_CASES 0 import Bind.Marshal.Prelude import Bind.Marshal.Verify import Bind.Marshal.SerAction.Base import Bind.Marshal.SerAction.Static import Bind.Marshal.SerAction.Verify.Static import Bind.Marshal.StdLib.Ser import Foreign.Storable import Foreign.Marshal.Alloc import System.IO t_0 = do ser () return () t_1 = do ser ( 0 :: Word8 ) return () t_2 (x :: Word8) = do ser x return () t_3 (x :: Word8) (y :: Word8) = do ser x ser y return () t_4 (x :: Word8) (y :: Word32) = do ser x ser y return () t_5 = do ser (0 :: Int32) ser (1 :: Int32) ser (2 :: Int32) ser (3 :: Int32) ser (4 :: Int32) ser (5 :: Word32) ser (6 :: Word32) return () #if !ONLY_SMALL_CASES t_6 = do ser (0 :: Int32) ser (1 :: Int32) ser (2 :: Int32) ser (3 :: Int32) ser (4 :: Int32) ser (5 :: Word32) ser (6 :: Word32) ser (7 :: Word32) ser (8 :: Word32) ser (9 :: Word32) ser (10 :: Word8) ser (11 :: Word8) ser (12 :: Word8) ser (13 :: Word8) ser (14 :: Word8) return () t_7 a b c d e f g h i j k l m n o = do ser (a :: Int32) ser (b :: Int32) ser (c :: Int32) ser (d :: Int32) ser (e :: Int32) ser (f :: Word32) ser (g :: Word32) ser (h :: Word32) ser (i :: Word32) ser (j :: Word32) ser (k :: Word8) ser (l :: Word8) ser (m :: Word8) ser (n :: Word8) ser (o :: Word8) return () #endif main = run_test $ do returnM () :: Test ()
coreyoconnor/bind-marshal
test/verify_seraction_static.hs
bsd-3-clause
1,674
7
9
523
786
386
400
-1
-1
{-# LANGUAGE OverloadedStrings #-} import Control.Concurrent import Control.Monad.IO.Class import Data.Maybe import Data.Text (Text) import Network.Consul (createManagedSession,getSessionInfo,initializeConsulClient,withSession,ConsulClient(..),ManagedSession(..)) import Network.Consul.Types import qualified Network.Consul.Internal as I import Network.HTTP.Client import Network.Socket (PortNumber(..)) import Test.Tasty import Test.Tasty.HUnit manager :: IO Manager manager = newManager defaultManagerSettings {- Internal Tests -} internalKVTests :: TestTree internalKVTests = testGroup "Internal Key Value" [testGetInvalidKey, testPutKey, testGetKey,testGetKeys,testListKeys,testDeleteKey,testGetNullValueKey] testGetInvalidKey :: TestTree testGetInvalidKey = testCase "testGetInvalidKey" $ do man <- manager x <- I.getKey man "localhost" (PortNum 8500) "nokey" Nothing Nothing Nothing assertEqual "testGetInvalidKey: Found a key that doesn't exist" x Nothing testPutKey :: TestTree testPutKey = testCase "testPutKey" $ do man <- manager let put = KeyValuePut "/testPutKey" "Test" Nothing Nothing x <- I.putKey man "localhost" (PortNum 8500) put Nothing assertEqual "testPutKey: Write failed" True x testGetKey :: TestTree testGetKey = testCase "testGetKey" $ do man <- manager let put = KeyValuePut "/testGetKey" "Test" Nothing Nothing x1 <- I.putKey man "localhost" (PortNum 8500) put Nothing assertEqual "testGetKey: Write failed" True x1 x2 <- I.getKey man "localhost" (PortNum 8500) "/testGetKey" Nothing Nothing Nothing case x2 of Just x -> assertEqual "testGetKey: Incorrect Value" (kvValue x) (Just "Test") Nothing -> assertFailure "testGetKey: No value returned" testGetNullValueKey :: TestTree testGetNullValueKey = testCase "testGetNullValueKey" $ do man <- manager man <- manager let put = KeyValuePut "/testGetNullValueKey" "" Nothing Nothing x1 <- I.putKey man "localhost" (PortNum 8500) put Nothing assertEqual "testGetNullValueKey: Write failed" True x1 x2 <- I.getKey man "localhost" (PortNum 8500) "/testGetNullValueKey" Nothing Nothing Nothing case x2 of Just x -> assertEqual "testGetNullValueKey: Incorrect Value" (kvValue x) Nothing Nothing -> assertFailure "testGetNullValueKey: No value returned" testGetKeys :: TestTree testGetKeys = testCase "testGetKeys" $ do man <- manager let put1 = KeyValuePut "/testGetKeys/key1" "Test" Nothing Nothing x1 <- I.putKey man "localhost" (PortNum 8500) put1 Nothing assertEqual "testGetKeys: Write failed" True x1 let put2 = KeyValuePut "/testGetKeys/key2" "Test" Nothing Nothing x2 <- I.putKey man "localhost" (PortNum 8500) put2 Nothing assertEqual "testGetKeys: Write failed" True x2 x3 <- I.getKeys man "localhost" (PortNum 8500) "/testGetKeys" Nothing Nothing Nothing assertEqual "testGetKeys: Incorrect number of results" 2 (length x3) testListKeys :: TestTree testListKeys = testCase "testListKeys" $ do man <- manager let put1 = KeyValuePut "/testListKeys/key1" "Test" Nothing Nothing x1 <- I.putKey man "localhost" (PortNum 8500) put1 Nothing assertEqual "testListKeys: Write failed" True x1 let put2 = KeyValuePut "/testListKeys/key2" "Test" Nothing Nothing x2 <- I.putKey man "localhost" (PortNum 8500) put2 Nothing assertEqual "testListKeys: Write failed" True x2 x3 <- I.listKeys man "localhost" (PortNum 8500) "/testListKeys/" Nothing Nothing Nothing assertEqual "testListKeys: Incorrect number of results" 2 (length x3) testDeleteKey :: TestTree testDeleteKey = testCase "testDeleteKey" $ do man <- manager let put1 = KeyValuePut "/testDeleteKey" "Test" Nothing Nothing x1 <- I.putKey man "localhost" (PortNum 8500) put1 Nothing assertEqual "testDeleteKey: Write failed" True x1 I.deleteKey man "localhost" (PortNum 8500) "/testDeleteKey" False Nothing x2 <- I.getKey man "localhost" (PortNum 8500) "/testDeleteKey" Nothing Nothing Nothing assertEqual "testDeleteKey: Key was not deleted" Nothing x2 {- Agent -} testRegisterService :: TestTree testRegisterService = testCase "testRegisterService" $ do man <- manager let req = RegisterService Nothing "testService" ["test"] Nothing (Just $ Ttl "10s") val <- I.registerService man "localhost" (PortNum 8500) req Nothing assertEqual "testRegisterService: Service was not created" val True testGetSelf :: TestTree testGetSelf = testCase "testGetSelf" $ do man <- manager x <- I.getSelf man "localhost" (PortNum 8500) assertEqual "testGetSelf: Self not returned" True (isJust x) {- testRegisterHealthCheck :: TestTree testRegisterHealthCheck = testCase "testRegisterHealthCheck" $ do man <- manager let check = RegisterHealthCheck "testHealthCheck" "testHealthCheck" "" Nothing Nothing (Just "15s") x1 <- I.registerHealthCheck man "localhost" (PortNum 8500) check undefined -} {- Health Checks -} testGetServiceHealth :: TestTree testGetServiceHealth = testCase "testGetServiceHealth" $ do man <- manager let req = RegisterService (Just "testGetServiceHealth") "testGetServiceHealth" [] Nothing Nothing r1 <- I.registerService man "localhost" (PortNum 8500) req Nothing case r1 of True -> do liftIO $ threadDelay 1000000 r2 <- I.getServiceHealth man "localhost" (PortNum 8500) "testGetServiceHealth" case r2 of Just [x] -> return () Just [] -> assertFailure "testGetServiceHealth: No Services Returned" Nothing -> assertFailure "testGetServiceHealth: Failed to parse result" False -> assertFailure "testGetServiceHealth: Service was not created" testHealth :: TestTree testHealth = testGroup "Health Check Tests" [testGetServiceHealth] {- Session -} testCreateSession :: TestTree testCreateSession = testCase "testCreateSession" $ do man <- manager let req = SessionRequest Nothing (Just "testCreateSession") Nothing ["serfHealth"] (Just Release) (Just "30s") result <- I.createSession man "localhost" (PortNum 8500) req Nothing case result of Just _ -> return () Nothing -> assertFailure "testCreateSession: No session was created" testGetSessionInfo :: TestTree testGetSessionInfo = testCase "testGetSessionInfo" $ do man <- manager let req = SessionRequest Nothing (Just "testGetSessionInfo") Nothing ["serfHealth"] (Just Release) (Just "30s") result <- I.createSession man "localhost" (PortNum 8500) req Nothing case result of Just x -> do x1 <- I.getSessionInfo man "localhost" (PortNum 8500) (sId x) Nothing case x1 of Just _ -> return () Nothing -> assertFailure "testGetSessionInfo: Session Info was not returned" Nothing -> assertFailure "testGetSessionInfo: No session was created" testRenewSession :: TestTree testRenewSession = testCase "testRenewSession" $ do man <- manager let req = SessionRequest Nothing (Just "testRenewSession") Nothing ["serfHealth"] (Just Release) (Just "30s") result <- I.createSession man "localhost" (PortNum 8500) req Nothing case result of Just x -> do x1 <- I.renewSession man "localhost" (PortNum 8500) x Nothing case x1 of True -> return () False -> assertFailure "testRenewSession: Session was not renewed" Nothing -> assertFailure "testRenewSession: No session was created" testDestroySession :: TestTree testDestroySession = testCase "testDestroySession" $ do man <- manager let req = SessionRequest Nothing (Just "testDestroySession") Nothing ["serfHealth"] (Just Release) (Just "30s") result <- I.createSession man "localhost" (PortNum 8500) req Nothing case result of Just x -> do _ <- I.destroySession man "localhost" (PortNum 8500) x Nothing x1 <- I.getSessionInfo man "localhost" (PortNum 8500) (sId x) Nothing assertEqual "testDestroySession: Session info was returned after destruction" Nothing x1 Nothing -> assertFailure "testDestroySession: No session was created" testInternalSession :: TestTree testInternalSession = testGroup "Internal Session Tests" [testCreateSession, testGetSessionInfo, testRenewSession, testDestroySession] {- Managed Session -} testCreateManagedSession :: TestTree testCreateManagedSession = testCase "testCreateManagedSession" $ do client <- initializeConsulClient "localhost" (PortNum 8500) Nothing x <- createManagedSession client (Just "testCreateManagedSession") "60s" assertEqual "testCreateManagedSession: Session not created" True (isJust x) testSessionMaintained :: TestTree testSessionMaintained = testCase "testSessionMaintained" $ do client <- initializeConsulClient "localhost" (PortNum 8500) Nothing x <- createManagedSession client (Just "testCreateManagedSession") "10s" assertEqual "testSessionMaintained: Session not created" True (isJust x) let (Just foo) = x threadDelay (12 * 1000000) y <- getSessionInfo client (sId $ msSession foo) Nothing assertEqual "testSessionMaintained: Session not found" True (isJust y) testWithSessionCancel :: TestTree testWithSessionCancel = testCase "testWithSessionCancel" $ do man <- manager client <- initializeConsulClient "localhost" (PortNum 8500) Nothing let req = SessionRequest Nothing (Just "testWithSessionCancel") Nothing ["serfHealth"] (Just Release) (Just "10s") result <- I.createSession man "localhost" (PortNum 8500) req Nothing case result of Just x -> do x1 <- withSession client x (\ y -> action y man ) cancelAction assertEqual "testWithSessionCancel: Incorrect value" "Canceled" x1 Nothing -> assertFailure "testWithSessionCancel: No session was created" where action x man = do I.destroySession man "localhost" (PortNum 8500) x Nothing threadDelay (30 * 1000000) return ("NotCanceled" :: Text) cancelAction = return ("Canceled" :: Text) managedSessionTests :: TestTree managedSessionTests = testGroup "Managed Session Tests" [ testCreateManagedSession, testSessionMaintained, testWithSessionCancel] agentTests :: TestTree agentTests = testGroup "Agent Tests" [testGetSelf,testRegisterService] allTests :: TestTree allTests = testGroup "All Tests" [testInternalSession, internalKVTests, managedSessionTests, agentTests,testHealth] main :: IO () main = defaultMain allTests
hellertime/consul-haskell
tests/Main.hs
bsd-3-clause
10,190
0
17
1,641
2,711
1,302
1,409
190
4
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Nix.XML (toXML) where import qualified Data.HashMap.Lazy as M import Data.List import Data.Ord import qualified Data.Text as Text import Nix.Atoms import Nix.Expr.Types import Nix.String import Nix.Value import Text.XML.Light toXML :: forall t f m . MonadDataContext f m => NValue t f m -> NixString toXML = runWithStringContext . fmap pp . iterNValue (\_ _ -> cyc) phi where cyc = return $ mkElem "string" "value" "<CYCLE>" pp = ("<?xml version='1.0' encoding='utf-8'?>\n" <>) . (<> "\n") . Text.pack . ppElement . (\e -> Element (unqual "expr") [] [Elem e] Nothing) phi :: NValue' t f m (WithStringContext Element) -> WithStringContext Element phi = \case NVConstant' a -> case a of NInt n -> return $ mkElem "int" "value" (show n) NFloat f -> return $ mkElem "float" "value" (show f) NBool b -> return $ mkElem "bool" "value" (if b then "true" else "false") NNull -> return $ Element (unqual "null") [] [] Nothing NVStr' str -> mkElem "string" "value" . Text.unpack <$> extractNixString str NVList' l -> sequence l >>= \els -> return $ Element (unqual "list") [] (Elem <$> els) Nothing NVSet' s _ -> sequence s >>= \kvs -> return $ Element (unqual "attrs") [] (map (\(k, v) -> Elem (Element (unqual "attr") [Attr (unqual "name") (Text.unpack k)] [Elem v] Nothing ) ) (sortBy (comparing fst) $ M.toList kvs) ) Nothing NVClosure' p _ -> return $ Element (unqual "function") [] (paramsXML p) Nothing NVPath' fp -> return $ mkElem "path" "value" fp NVBuiltin' name _ -> return $ mkElem "function" "name" name _ -> error "Pattern synonyms mask coverage" mkElem :: String -> String -> String -> Element mkElem n a v = Element (unqual n) [Attr (unqual a) v] [] Nothing paramsXML :: Params r -> [Content] paramsXML (Param name) = [Elem $ mkElem "varpat" "name" (Text.unpack name)] paramsXML (ParamSet s b mname) = [Elem $ Element (unqual "attrspat") (battr <> nattr) (paramSetXML s) Nothing] where battr = [ Attr (unqual "ellipsis") "1" | b ] nattr = maybe [] ((: []) . Attr (unqual "name") . Text.unpack) mname paramSetXML :: ParamSet r -> [Content] paramSetXML = map (\(k, _) -> Elem $ mkElem "attr" "name" (Text.unpack k))
jwiegley/hnix
src/Nix/XML.hs
bsd-3-clause
2,653
0
25
770
959
493
466
60
12
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} -- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-} -------------------------------------------------------------------- -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <[email protected]> -- Stability : experimental -- Portability: non-portable -- -- This module tests Pire's parser: erased applications. -------------------------------------------------------------------- module ParserTests.ErasedApp where import Test.Tasty import Test.Tasty.HUnit import Pire.Syntax import Pire.NoPos import Pire.Parser.Expr import Pire.Forget import Pire.Untie import Pire.Parser.ParseUtils import Pire.Parser.PiParseUtils #ifdef PiForallInstalled import qualified PiForall.Parser as P #endif -- erased app (ErasedApp) -- cf examples in Lec4 -- new as of May 2015 -- test w/ -- main' "erased app" parsingErasedAppU = testGroup "parsing erased app - unit tests" $ tail [ undefined , let s = "foo [bar]" in testGroup ("erased app '"++s++"'") $ tail [ undefined -- as an expr , testCase ("parsing erased app '"++s++"'") $ (nopos $ parse expr s) @?= (ErasedApp (V "foo") (V "bar")) , testCase ("parse & forget expr_ '"++s++"'") $ (forget $ parse expr_ s) @?= (parse expr s) ] #ifdef PiForallInstalled ++ tail [ undefined , testCase ("parse & untie expr '"++s++"'") $ (untie $ parse expr s) @?= (piParse P.expr s) ] #endif , let s = "\\ x . foo [bar]" in testGroup (">>= for erased app: \""++s++"\"") $ tail [ undefined -- make sure, the bind op for erased app is defined -- trivial equality , testCase ("parsing expr '"++s++"'") $ (parse expr s) @?= (parse expr s) , testCase ("parsing expr_ '"++s++"'") $ (parse expr_ s) @?= (parse expr_ s) -- , testCase ("parse & forget expr_ '"++s++"'") -- $ (forget $ parse expr_ s) @?= (parse expr s) ] -- indent! ]
reuleaux/pire
tests/ParserTests/ErasedApp.hs
bsd-3-clause
2,153
0
19
595
426
239
187
28
1
{-# LANGUAGE ScopedTypeVariables #-} module WeiXin.PublicPlatform.Material ( module WeiXin.PublicPlatform.Material , module WeiXin.PublicPlatform.Class ) where -- {{{1 imports import ClassyPrelude import qualified Control.Exception.Safe as ExcSafe import Network.Wreq import qualified Network.Wreq.Session as WS import Control.Lens hiding ((.=)) import Data.Aeson import Control.Monad.Logger #if !MIN_VERSION_base(4, 13, 0) import Control.Monad.Reader (asks) #endif import Data.SafeCopy -- import Data.Acid (query) import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Char8 as C8 import qualified Data.CaseInsensitive as CI import qualified Data.Text as T import Network.Mime (MimeType) -- import Data.Yaml (ParseException) import Data.Conduit import qualified Data.Conduit.List as CL -- import Data.Conduit.Combinators hiding (null) import WeiXin.PublicPlatform.Class -- import WeiXin.PublicPlatform.Acid import WeiXin.PublicPlatform.WS import WeiXin.PublicPlatform.Error import WeiXin.PublicPlatform.Utils import Yesod.Compat -- }}}1 -- | 查询永久素材中的图文消息中的文章,出现在从服务器返回的数据中 -- 与 WxppDurableArticle 几乎一样,区别只是 -- 多了 url 字段 data WxppDurableArticleS = WxppDurableArticleS { wxppDurableArticleSA :: WxppDurableArticle , wxppDurableArticleSUrl :: UrlText } deriving (Eq, Show) $(deriveSafeCopy 0 'base ''WxppDurableArticleS) instance FromJSON WxppDurableArticleS where parseJSON = withObject "WxppDurableArticleS" $ \o -> do WxppDurableArticleS <$> parseJSON (Object o) <*> (UrlText <$> o .: "url") instance ToJSON WxppDurableArticleS where toJSON x = object $ ("url" .= unUrlText (wxppDurableArticleSUrl x)) : wppDurableArticleToJsonPairs (wxppDurableArticleSA x) -- | 根据已保存至素材库的图文消息,生成可回复用的图文消息 -- 比较麻烦的是封面图的URL -- 这个URL可以比较曲折地取得:根据图文消息里的封面图media_id,遍历一次所有图片素材 -- 在media_id相同的项目内,找到其URL -- (微信目前不提供根据media_id找到图片URL的直接接口) wxppMakeArticleByDurableArticleS :: Maybe UrlText -- ^ 封面图的URL -> WxppDurableArticleS -> WxppArticle wxppMakeArticleByDurableArticleS m_pic_url s = WxppArticle (Just $ wxppDurableArticleTitle a) (wxppDurableArticleDigest a) m_pic_url (Just $ wxppDurableArticleSUrl s) where a = wxppDurableArticleSA s data DurableUploadResult = DurableUploadResult { durableUploadResultMediaID :: WxppDurableMediaID , durableUploadResultUrl :: Maybe UrlText -- ^ 只有图片素材才会返回 url,但这url只能用于腾讯系的应用 -- (不知道是何时更新的功能) } instance FromJSON DurableUploadResult where parseJSON = withObject "DurableUploadResult" $ \obj -> DurableUploadResult <$> obj .: "media_id" <*> (fmap UrlText <$> obj .:? "url") -- | 上传本地一个媒体文件,成为永久素材 wxppUploadDurableMediaInternal :: (WxppApiMonad env m) => AccessToken -> WxppMediaType -> Maybe (Text, Text) -- ^ 上传视频素材所需的额外信息:标题,简介 -> FilePath -- ^ the file to upload -> m DurableUploadResult wxppUploadDurableMediaInternal atk mtype m_title_intro fp = do wxppUploadDurableMediaInternalLBS atk mtype m_title_intro (partFileSource "media" fp) -- | 上传本地一个媒体文件,成为永久素材 wxppUploadDurableMediaInternalLBS :: (WxppApiMonad env m) => AccessToken -> WxppMediaType -> Maybe (Text, Text) -- ^ 上传视频素材所需的额外信息:标题,简介 -> Part -- ^ the @Part@ of uploaded file -> m DurableUploadResult wxppUploadDurableMediaInternalLBS (AccessToken { accessTokenData = atk }) mtype m_title_intro fpart = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf <> "/material/add_material" opts = defaults & param "access_token" .~ [ atk ] liftIO (WS.postWith opts sess url $ [ fpart & partName .~ "media" , partText "type" (wxppMediaTypeString mtype) ] ++ (case m_title_intro of Nothing -> [] Just (title, intro) -> [ partText "title" title , partText "introduction" intro ] ) ) >>= asWxppWsResponseNormal' -- | 上传本地视频成为永久素材 wxppUploadDurableMediaVideo :: (WxppApiMonad env m) => AccessToken -> Text -- ^ 标题 -> Text -- ^ 简介 -> FilePath -> m DurableUploadResult wxppUploadDurableMediaVideo atk title intro fp = do wxppUploadDurableMediaInternal atk WxppMediaTypeVideo (Just (title, intro)) fp wxppUploadDurableMediaVideoLBS :: (WxppApiMonad env m) => AccessToken -> Text -- ^ 标题 -> Text -- ^ 简介 -> FilePath -- ^ a dummy file name -> LB.ByteString -> m DurableUploadResult wxppUploadDurableMediaVideoLBS atk title intro fp lbs = do wxppUploadDurableMediaInternalLBS atk WxppMediaTypeVideo (Just (title, intro)) (partLBS "media" lbs & partFileName .~ Just fp) -- | 上传本地非视频媒体成为永久素材 wxppUploadDurableMediaNonVideo :: (WxppApiMonad env m) => AccessToken -> WxppMediaType -> FilePath -> m DurableUploadResult wxppUploadDurableMediaNonVideo atk mtype fp = do case mtype of WxppMediaTypeVideo -> liftIO $ throwIO $ userError "wxppUploadDurableMediaNonVideo cannot be used to upload video." _ -> return () wxppUploadDurableMediaInternal atk mtype Nothing fp -- | 上传本地非视频媒体成为永久素材 wxppUploadDurableMediaNonVideoLBS :: (WxppApiMonad env m) => AccessToken -> WxppMediaType -> FilePath -> LB.ByteString -> m DurableUploadResult wxppUploadDurableMediaNonVideoLBS atk mtype fp lbs = do case mtype of WxppMediaTypeVideo -> liftIO $ throwIO $ userError "wxppUploadDurableMediaNonVideo cannot be used to upload video." _ -> return () wxppUploadDurableMediaInternalLBS atk mtype Nothing (partLBS "media" lbs & partFileName .~ Just fp) -- | 上传一个图文素材成为永久素材 wxppUploadDurableNews :: (WxppApiMonad env m) => AccessToken -> WxppDurableNews -> m DurableUploadResult wxppUploadDurableNews (AccessToken { accessTokenData = atk }) news = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf <> "/material/add_news" opts = defaults & param "access_token" .~ [ atk ] liftIO (WS.postWith opts sess url $ encode $ toJSON news) >>= asWxppWsResponseNormal' -- | 查询永久素材的结果内容完全只能通过尝试的方式决定 -- 混合了多种情况 data WxppGetDurableResult = WxppGetDurableNews [WxppDurableArticleS] | WxppGetDurableVideo Text Text UrlText -- ^ title description download_url | WxppGetDurableRaw (Maybe MimeType) LB.ByteString deriving (Show) instance FromJSON WxppGetDurableResult where -- 这个函数不用处理 WxppGetDurableRaw,因为这种情况并非用 JSON 表示 parseJSON = withObject "WxppGetDurableResult" $ \obj -> do let parse_as_news = WxppGetDurableNews <$> obj .: "news_item" parse_as_video = WxppGetDurableVideo <$> obj .: "title" <*> obj .: "description" <*> (UrlText <$> obj .: "down_url") parse_as_news <|> parse_as_video -- | 获取永久素材 wxppGetDurableMedia :: (WxppApiMonad env m, ExcSafe.MonadCatch m) => AccessToken -> WxppDurableMediaID -> m WxppGetDurableResult wxppGetDurableMedia (AccessToken { accessTokenData = atk }) (WxppDurableMediaID mid) = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf <> "/material/get_material" opts = defaults & param "access_token" .~ [ atk ] r <- liftIO $ WS.postWith opts sess url $ object [ "media_id" .= mid ] asWxppWsResponseNormal' r `ExcSafe.catch` (\(_ :: JSONError) -> do let resp_headers = r ^. responseHeaders $logDebugS wxppLogSource $ T.append "get_material api response headers:\n" $ T.unlines $ flip map resp_headers $ \(ci_name, val) -> fromString $ C8.unpack $ mconcat [ CI.original ci_name, ": ", val ] -- XXX: 微信平台返回的 Content-Type 总是 text/plain -- 要自己找 mime 内容 let mime0 = r ^. responseHeader "Content-Type" m_mime = if null mime0 || mime0 == "text/plain" then Nothing else Just mime0 return $ WxppGetDurableRaw m_mime (r ^. responseBody) ) wxppGetDurableMediaMaybe :: (WxppApiMonad env m, ExcSafe.MonadCatch m) => AccessToken -> WxppDurableMediaID -> m (Maybe WxppGetDurableResult) wxppGetDurableMediaMaybe atk mid = do (liftM Just $ wxppGetDurableMedia atk mid) `ExcSafe.catch` \e -> do case e of WxppAppError xerr _ | wxppToErrorCodeX xerr == wxppToErrorCode WxppInvalidMediaId -> return Nothing _ -> liftIO $ throwIO e -- | 组合了 wxppUploadDurableNews 与 wxppGetDurableMedia -- 把 WxppDurableNews 保存至素材库后,再取出来,从而知道每个图文的URL -- 再生成一个 WxppOutMsg wxppUploadDurableNewsThenMakeOutMsg :: (WxppApiMonad env m, ExcSafe.MonadCatch m) => AccessToken -> [(WxppDurableArticle, Maybe UrlText)] -> m (WxppDurableMediaID, WxppOutMsg) wxppUploadDurableNewsThenMakeOutMsg atk article_and_url = do durable_media_id <- liftM durableUploadResultMediaID $ wxppUploadDurableNews atk $ WxppDurableNews $ map fst article_and_url get_result <- wxppGetDurableMedia atk durable_media_id case get_result of WxppGetDurableNews article_s_list -> do return $ (durable_media_id,) $ WxppOutMsgNews $ flip map (zip article_s_list $ map snd article_and_url) $ \(article_s, m_pic_url) -> wxppMakeArticleByDurableArticleS m_pic_url article_s _ -> do liftIO $ throwIO $ userError $ "wxppGetDurableMedia return unexpected result, should be a WxppGetDurableNews" <> ", but got " <> show get_result -- | 永久素材统计数 data WxppDurableCount = WxppDurableCount { wxppDurableCountVoice :: Int , wxppDurableCountVideo :: Int , wxppDurableCountImage :: Int , wxppDurableCountNews :: Int } instance FromJSON WxppDurableCount where parseJSON = withObject "WxppDurableCount" $ \obj -> do WxppDurableCount <$> ( obj .: "voice_count" ) <*> ( obj .: "video_count" ) <*> ( obj .: "image_count" ) <*> ( obj .: "news_count" ) instance ToJSON WxppDurableCount where toJSON x = object [ "voice_count" .= wxppDurableCountVoice x , "video_count" .= wxppDurableCountVideo x , "image_count" .= wxppDurableCountImage x , "news_count" .= wxppDurableCountNews x ] wxppCountDurableMedia :: (WxppApiMonad env m) => AccessToken -> m WxppDurableCount wxppCountDurableMedia (AccessToken { accessTokenData = atk }) = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf <> "/material/get_materialcount" opts = defaults & param "access_token" .~ [ atk ] liftIO (WS.getWith opts sess url) >>= asWxppWsResponseNormal' -- | 批量取永久素材接口,无论是图文还是一般的多媒体 -- 返回报文都是这样子的结构 data WxppBatchGetDurableResult a = WxppBatchGetDurableResult { wxppBatchGetDurableResultTotal :: Int , wxppBatchGetDurableResultCount :: Int , wxppBatchGetDurableResultItems :: [a] } instance FromJSON a => FromJSON (WxppBatchGetDurableResult a) where parseJSON = withObject "WxppBatchGetDurableResult" $ \obj -> do WxppBatchGetDurableResult <$> ( obj .: "total_count" ) <*> ( obj .: "item_count" ) <*> ( obj .: "item" ) -- | 批量取多媒体类型的永久素材,返回报文中的项目 data WxppBatchGetDurableMediaItem = WxppBatchGetDurableMediaItem { wxppBatchGetDurableMediaItemID :: WxppDurableMediaID , wxppBatchGetDurableMediaItemName :: Text , wxppBatchGetDurableMediaItemUrl :: Maybe UrlText , wxppBatchGetDurableMediaItemTime :: UTCTime } $(deriveSafeCopy 0 'base ''WxppBatchGetDurableMediaItem) instance FromJSON WxppBatchGetDurableMediaItem where parseJSON = withObject "WxppBatchGetDurableMediaItem" $ \obj -> do WxppBatchGetDurableMediaItem <$> ( obj .: "media_id" ) <*> ( obj .: "name") <*> (fmap UrlText <$> obj .:? "url") <*> ( epochIntToUtcTime <$> obj .: "update_time") instance ToJSON WxppBatchGetDurableMediaItem where toJSON x = object [ "media_id" .= wxppBatchGetDurableMediaItemID x , "name" .= wxppBatchGetDurableMediaItemName x , "update_time" .= wxppBatchGetDurableMediaItemTime x ] -- | 调用批量取多媒体类型的永久素材的接口 wxppBatchGetDurableMedia :: (WxppApiMonad env m) => AccessToken -> WxppMediaType -> Int -- ^ limit -> Int -- ^ offset -> m (WxppBatchGetDurableResult WxppBatchGetDurableMediaItem) wxppBatchGetDurableMedia (AccessToken { accessTokenData = atk }) mtype limit' offset' = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf <> "/material/batchget_material" opts = defaults & param "access_token" .~ [ atk ] liftIO (WS.postWith opts sess url $ object $ [ "type" .= (wxppMediaTypeString mtype :: Text) , "count" .= show limit , "offset" .= show offset ]) >>= asWxppWsResponseNormal' where limit = max 1 $ min 20 $ limit' offset = max 0 $ offset' -- | 批量取图文类型的永久素材,返回报文中的项目 data WxppBatchGetDurableNewsItem = WxppBatchGetDurableNewsItem { wxppBatchGetDurableNewsItemID :: WxppDurableMediaID , wxppBatchGetDurableNewsItemContent :: [WxppDurableArticleS] , wxppBatchGetDurableNewsItemTime :: UTCTime } deriving (Eq) $(deriveSafeCopy 0 'base ''WxppBatchGetDurableNewsItem) instance FromJSON WxppBatchGetDurableNewsItem where parseJSON = withObject "WxppBatchGetDurableNewsItem" $ \obj -> do WxppBatchGetDurableNewsItem <$> ( obj .: "media_id" ) <*> ( obj .: "content" >>= (\o -> o .: "news_item")) <*> ( epochIntToUtcTime <$> obj .: "update_time") instance ToJSON WxppBatchGetDurableNewsItem where toJSON x = object [ "media_id" .= wxppBatchGetDurableNewsItemID x , "content" .= object [ "news_item" .= wxppBatchGetDurableNewsItemContent x ] , "update_time" .= utcTimeToEpochInt (wxppBatchGetDurableNewsItemTime x) ] -- | 调用批量取图文消息类型的永久素材的接口 wxppBatchGetDurableNews :: (WxppApiMonad env m) => AccessToken -> Int -- ^ limit -> Int -- ^ offset -> m (WxppBatchGetDurableResult WxppBatchGetDurableNewsItem) wxppBatchGetDurableNews (AccessToken { accessTokenData = atk }) limit' offset' = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf <> "/material/batchget_material" opts = defaults & param "access_token" .~ [ atk ] liftIO (WS.postWith opts sess url $ object $ [ "type" .= ("news" :: Text) , "count" .= limit , "offset" .= offset ]) >>= asWxppWsResponseNormal' where limit = max 1 $ min 20 $ limit' offset = max 0 $ offset' -- | 把 limit/offset 风格的接口变成 conduit 风格:取全部数据 wxppBatchGetDurableToSrc' :: (WxppApiMonad env m) => (Int -> m (WxppBatchGetDurableResult a) ) -- ^ 这个函数可以从前面的函数应用上部分参数后得到, Int 参数是 offset -> SourceC m (WxppBatchGetDurableResult a) wxppBatchGetDurableToSrc' get_by_offset = go 0 where go offset = do result <- lift $ get_by_offset offset let items = wxppBatchGetDurableResultItems result if null items then return () else do yield result let batch_count = wxppBatchGetDurableResultCount result go $ offset + batch_count wxppBatchGetDurableToSrc :: (WxppApiMonad env m) => (Int -> m (WxppBatchGetDurableResult a) ) -- ^ 这个函数可以从前面的函数应用上部分参数后得到, Int 参数是 offset -> SourceC m a wxppBatchGetDurableToSrc get_by_offset = wxppBatchGetDurableToSrc' get_by_offset .| CL.concatMap wxppBatchGetDurableResultItems -- | 修改一个图文类型的永久素材: 只能修改其中一个文章 wxppReplaceArticleOfDurableNews :: (WxppApiMonad env m) => AccessToken -> WxppDurableMediaID -> Int -- ^ index -> WxppDurableArticle -> m () wxppReplaceArticleOfDurableNews (AccessToken { accessTokenData = atk }) material_id idx article = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf <> "/material/update_news" opts = defaults & param "access_token" .~ [ atk ] liftIO (WS.postWith opts sess url $ object $ [ "media_id" .= unWxppDurableMediaID material_id , "index" .= idx , "articles" .= article ]) >>= asWxppWsResponseVoid
yoo-e/weixin-mp-sdk
WeiXin/PublicPlatform/Material.hs
mit
22,096
0
18
8,025
3,756
1,965
1,791
-1
-1
{- | Module : ./Isabelle/IsaProve.hs Description : interface to the Isabelle theorem prover Copyright : (c) University of Cambridge, Cambridge, England adaption (c) Till Mossakowski, Uni Bremen 2002-2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Interface for Isabelle theorem prover. Interface between Isabelle and Hets: Hets writes Isabelle .thy file and starts Isabelle User extends .thy file with proofs User finishes Isabelle Hets reads in created *.deps files -} module Isabelle.IsaProve ( isabelleConsChecker , isabelleBatchProver , isabelleProver , IsaEditor (..) , isaProve ) where import Logic.Prover import Isabelle.IsaSign import Isabelle.IsaConsts import Isabelle.IsaPrint import Isabelle.IsaParse import Isabelle.Translate import Isabelle.MarkSimp import Common.AS_Annotation import Common.DocUtils import Common.DefaultMorphism import Common.ProofUtils import Common.Result import Common.Utils (getEnvDef, executeProcess) import qualified Data.Map as Map import qualified Data.Set as Set import Text.ParserCombinators.Parsec import Control.Monad import Control.Concurrent import Control.Exception (finally) import Data.Char import Data.List (isSuffixOf) import Data.Time (midnight) import System.Directory import System.Exit import System.Process isabelleS :: String isabelleS = "Isabelle" data IsaEditor = Emacs | JEdit instance Show IsaEditor where show e = case e of Emacs -> "emacs" JEdit -> "jedit" isabelleProcessS :: String isabelleProcessS = "isabelle_process" openIsaProofStatus :: String -> ProofStatus () openIsaProofStatus n = openProofStatus n isabelleS () isabelleProver :: IsaEditor -> Prover Sign Sentence (DefaultMorphism Sign) () () isabelleProver e = mkAutomaticProver "isabelle" (isabelleS ++ "-" ++ show e) () (isaProve e) isaBatchProve isabelleBatchProver :: Prover Sign Sentence (DefaultMorphism Sign) () () isabelleBatchProver = mkAutomaticProver isabelleProcessS isabelleProcessS () (isaProveAux Nothing) isaBatchProve isabelleConsChecker :: ConsChecker Sign Sentence () (DefaultMorphism Sign) () isabelleConsChecker = (mkUsableConsChecker "isabelle" "Isabelle-refute" () consCheck) { ccBatch = False , ccNeedsTimer = False } -- | the name of the inconsistent lemma for consistency checks inconsistentS :: String inconsistentS = "inconsistent" metaToTerm :: MetaTerm -> Term metaToTerm mt = case mt of Term t -> t Conditional ts t -> case ts of [] -> t _ -> binImpl (foldr1 binConj ts) t consCheck :: String -> b -> TheoryMorphism Sign Sentence (DefaultMorphism Sign) () -> a -> IO (CCStatus ()) consCheck thName _tac tm freedefs = case tTarget tm of Theory sig nSens -> do let (axs, _) = getAxioms $ toNamedList nSens l <- isaProve JEdit (thName ++ "_c") (Theory sig $ markAsGoal $ toThSens $ if null axs then [] else [ makeNamed inconsistentS $ mkRefuteSen $ termAppl notOp $ foldr1 binConj $ map (metaToTerm . metaTerm . sentence) axs ]) freedefs return $ CCStatus () midnight $ case filter isProvedStat l of [_] -> Just False -- inconsistency was proven _ -> Nothing -- consistency cannot be recorded automatically prepareTheory :: Theory Sign Sentence () -> (Sign, [Named Sentence], [Named Sentence], Map.Map String String) prepareTheory (Theory sig nSens) = let oSens = toNamedList nSens nSens' = prepareSenNames transString oSens (disAxs, disGoals) = getAxioms nSens' in (sig, map markSimp disAxs, map markThSimp disGoals, Map.fromList $ zip (map senAttr nSens') $ map senAttr oSens) -- return a reverse mapping for renamed sentences removeDepFiles :: String -> [String] -> IO () removeDepFiles thName = mapM_ $ \ thm -> do let depFile = getDepsFileName thName thm ex <- doesFileExist depFile when ex $ removeFile depFile getDepsFileName :: String -> String -> String getDepsFileName thName thm = thName ++ "_" ++ thm ++ ".deps" getProofDeps :: Map.Map String String -> String -> String -> IO (ProofStatus ()) getProofDeps m thName thm = do let file = getDepsFileName thName thm mapN n = Map.findWithDefault n n m strip = takeWhile (not . isSpace) . dropWhile isSpace b <- doesFileExist file if b then do s <- readFile file return $ mkProved (mapN thm) $ map mapN $ Set.toList $ Set.filter (not . null) $ Set.fromList $ map strip $ lines s else return $ openIsaProofStatus $ mapN thm getAllProofDeps :: Map.Map String String -> String -> [String] -> IO [ProofStatus ()] getAllProofDeps m = mapM . getProofDeps m checkFinalThyFile :: (TheoryHead, Body) -> String -> IO Bool checkFinalThyFile (ho, bo) thyFile = do s <- readFile thyFile case parse parseTheory thyFile s of Right (hb, b) -> do let ds = compatibleBodies bo b mapM_ (\ d -> putStrLn $ showDoc d "") $ ds ++ warnSimpAttr b if hb /= ho then do putStrLn "illegal change of theory header" return False else return $ null ds Left err -> print err >> return False mkProved :: String -> [String] -> ProofStatus () mkProved thm used = (openIsaProofStatus thm) { goalStatus = Proved True , usedAxioms = used , tacticScript = TacticScript "unknown isabelle user input" } prepareThyFiles :: (TheoryHead, Body) -> String -> String -> IO () prepareThyFiles ast thyFile thy = do let origFile = thyFile ++ ".orig" exOrig <- doesFileExist origFile exThyFile <- doesFileExist thyFile unless exOrig $ writeFile origFile thy unless exThyFile $ writeFile thyFile thy thy_time <- getModificationTime thyFile orig_time <- getModificationTime origFile s <- readFile origFile unless (thy_time >= orig_time && s == thy) $ patchThyFile ast origFile thyFile thy patchThyFile :: (TheoryHead, Body) -> FilePath -> FilePath -> String -> IO () patchThyFile (ho, bo) origFile thyFile thy = do let patchFile = thyFile ++ ".patch" oldFile = thyFile ++ ".old" diffCall = "diff -u " ++ origFile ++ " " ++ thyFile ++ " > " ++ patchFile patchCall = "patch -bfu " ++ thyFile ++ " " ++ patchFile callSystem diffCall renameFile thyFile oldFile removeFile origFile writeFile origFile thy writeFile thyFile thy callSystem patchCall s <- readFile thyFile case parse parseTheory thyFile s of Right (hb, b) -> do let ds = compatibleBodies bo b h = hb == ho mapM_ (\ d -> putStrLn $ showDoc d "") ds unless h $ putStrLn "theory header is corrupt" unless (h && null ds) $ revertThyFile thyFile thy Left err -> do print err revertThyFile thyFile thy revertThyFile :: String -> String -> IO () revertThyFile thyFile thy = do putStrLn $ "replacing corrupt file " ++ show thyFile removeFile thyFile writeFile thyFile thy callSystem :: String -> IO ExitCode callSystem s = putStrLn s >> system s isaProve :: IsaEditor -> String -> Theory Sign Sentence () -> a -> IO [ProofStatus ()] isaProve = isaProveAux . Just isaProveAux :: Maybe IsaEditor -> String -> Theory Sign Sentence () -> a -> IO [ProofStatus ()] isaProveAux meditor thName th _freedefs = do let (sig, axs, ths, m) = prepareTheory th thms = map senAttr ths thBaseName = reverse . takeWhile (/= '/') $ reverse thName useaxs = filter (\ s -> sentence s /= mkSen true && (isDef s || isSuffixOf "def" (senAttr s))) axs defaultProof = Just $ IsaProof (if null useaxs then [] else [Using $ map senAttr useaxs]) $ By Auto thy = shows (printIsaTheory thBaseName sig $ axs ++ map (mapNamed $ \ t -> case t of Sentence { thmProof = Nothing } -> t { thmProof = defaultProof } _ -> t) ths) "\n" thyFile = thBaseName ++ ".thy" case parse parseTheory thyFile thy of Right (ho, bo) -> do prepareThyFiles (ho, bo) thyFile thy removeDepFiles thBaseName thms case meditor of Nothing -> do (ex, out, err) <- executeProcess isabelleProcessS [] $ " use_thy \"" ++ thBaseName ++ "\";" putStrLn out case ex of ExitSuccess -> return () _ -> putStrLn err return ex Just editor -> do isabelle <- getEnvDef "HETS_ISABELLE" $ "isabelle " ++ show editor callSystem $ isabelle ++ " " ++ thyFile ok <- checkFinalThyFile (ho, bo) thyFile if ok then getAllProofDeps m thBaseName thms else return [] Left err -> do print err putStrLn $ "Sorry, generated theory cannot be parsed, see: " ++ thyFile writeFile thyFile thy putStrLn "aborting Isabelle proof attempt" return [] isaBatchProve :: Bool -- 1. -> Bool -- 2. -> MVar (Result [ProofStatus ()]) -- 3. -> String -- 4. -> TacticScript -- 5. -> Theory Sign Sentence () -- 6. -> a -> IO (ThreadId, MVar ()) isaBatchProve _incl _save resMVar thName _tac th freedefs = do mvar <- newEmptyMVar threadID <- forkIO (do ps <- isaProveAux Nothing thName th freedefs _ <- swapMVar resMVar $ return ps return () `finally` putMVar mvar ()) return (threadID, mvar)
spechub/Hets
Isabelle/IsaProve.hs
gpl-2.0
9,662
0
22
2,537
2,921
1,440
1,481
230
7
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} -- |Namelike definitions module CO4.Names ( Namelike (..), convertName, funName, listName, nilName, consName , tupleTypeName, tupleDataName, maybeName, eitherName, orderingName , natName, natTypeName, intName, boolName, unitName , mainName, deprecatedMainName , toValidTypeIdentifier, toValidDataIdentifier, toValidFunIdentifier ) where import CO4.Language (Name(..),UntypedName(..)) import qualified Language.Haskell.TH as TH class Namelike a where readName :: String -> a fromName :: a -> String mapName :: (String -> String) -> a -> a mapName f = readName . f . fromName untypedName :: a -> UntypedName untypedName = UntypedName . fromName name :: a -> Name name = NUntyped . fromName instance Namelike String where readName = id fromName = id instance Namelike UntypedName where readName = UntypedName fromName (UntypedName n) = n instance Namelike Name where readName = NUntyped fromName (NUntyped n) = n fromName (NTyped n _) = n mapName f (NUntyped n) = NUntyped $ f n mapName f (NTyped n s) = NTyped (f n) s name = id instance Namelike TH.Name where readName = TH.mkName fromName = show convertName :: (Namelike n,Namelike m) => n -> m convertName = readName . fromName funName :: Namelike n => n funName = convertName $ TH.nameBase ''(->) listName :: Namelike n => n listName = convertName $ TH.nameBase ''[] nilName :: Namelike n => n nilName = convertName $ TH.nameBase '[] consName :: Namelike n => n consName = convertName $ TH.nameBase '(:) maybeName :: Namelike n => n maybeName = convertName $ TH.nameBase ''Maybe eitherName :: Namelike n => n eitherName = convertName $ TH.nameBase ''Either orderingName :: Namelike n => n orderingName = convertName $ TH.nameBase ''Ordering tupleDataName :: Namelike n => Int -> n tupleDataName = convertName . TH.nameBase . TH.tupleDataName tupleTypeName :: Namelike n => Int -> n tupleTypeName = convertName . TH.nameBase . TH.tupleTypeName natTypeName :: Namelike n => n natTypeName = readName "Nat" natName :: Namelike n => n natName = readName "nat" intName :: Namelike n => n intName = convertName $ TH.nameBase ''Int boolName :: Namelike n => n boolName = convertName $ TH.nameBase ''Bool unitName :: Namelike n => n unitName = convertName $ TH.nameBase ''() mainName :: Namelike n => n mainName = readName "constraint" deprecatedMainName :: Namelike n => n deprecatedMainName = readName "main" toValidTypeIdentifier :: (Eq n, Namelike n) => n -> n toValidTypeIdentifier name = case name of n | n == listName -> readName "List" n | n == tupleDataName 2 -> readName "Tuple2" n | n == tupleDataName 3 -> readName "Tuple3" n | n == tupleDataName 4 -> readName "Tuple4" n | n == tupleDataName 5 -> readName "Tuple5" n | n == tupleTypeName 2 -> readName "Tuple2" n | n == tupleTypeName 3 -> readName "Tuple3" n | n == tupleTypeName 4 -> readName "Tuple4" n | n == tupleTypeName 5 -> readName "Tuple5" n | n == unitName -> readName "Unit" n -> n toValidDataIdentifier :: (Eq n, Namelike n) => n -> n toValidDataIdentifier name = case name of n | n == nilName -> readName "Nil" n | n == consName -> readName "Cons" n | n == tupleDataName 2 -> readName "Tuple2" n | n == tupleDataName 3 -> readName "Tuple3" n | n == tupleDataName 4 -> readName "Tuple4" n | n == tupleDataName 5 -> readName "Tuple5" n | n == tupleTypeName 2 -> readName "Tuple2" n | n == tupleTypeName 3 -> readName "Tuple3" n | n == tupleTypeName 4 -> readName "Tuple4" n | n == tupleTypeName 5 -> readName "Tuple5" n | n == unitName -> readName "Unit" n -> n toValidFunIdentifier :: (Eq n, Namelike n) => n -> n toValidFunIdentifier name = case name of n | n == convertName (TH.nameBase '(++)) -> readName "append" n | n == convertName (TH.nameBase '(&&)) -> readName "and2" n | n == convertName (TH.nameBase '(||)) -> readName "or2" n -> n
abau/co4
src/CO4/Names.hs
gpl-3.0
4,241
1
15
1,022
1,516
751
765
-1
-1
module PatBind2 where main :: Int main = x x :: Int (x:[]) = [1, 2, 3]
roberth/uu-helium
test/runtimeerrors/PatBind2.hs
gpl-3.0
74
0
7
20
43
26
17
5
1
module InfiniteType3 where insert :: (a -> a -> Bool) -> a -> [a] -> [a] insert f a [] = [a] insert f a (x:xs) | f a x = [a,x] ++ xs | True = [x] ++ (insert a xs)
roberth/uu-helium
test/typeerrors/Examples/InfiniteType3.hs
gpl-3.0
183
0
8
62
119
63
56
5
1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Main -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Main (main) where import Test.Tasty import Test.AWS.SES import Test.AWS.SES.Internal main :: IO () main = defaultMain $ testGroup "SES" [ testGroup "tests" tests , testGroup "fixtures" fixtures ]
fmapfmapfmap/amazonka
amazonka-ses/test/Main.hs
mpl-2.0
522
0
8
103
76
47
29
9
1
{-# LANGUAGE LambdaCase #-} -- | Event loop module Haskus.System.EventLoop ( L , JobResponse (..) , mainLoop ) where import Control.Concurrent.STM import Haskus.Utils.Flow -- Note [Event loop] -- ~~~~~~~~~~~~~~~~~ -- -- The event loop is loosely based on the EFL's main loop (Enlightenment -- Foundation Libraries). -- -- /------->-------\ -- | | -- | | -- | PreIdle jobs -- | | -- | |<-----------<-----------\ Execute idle jobs or sleep -- | Idle jobs (optional) or sleep | until an event occurs -- ^ |------------>-----------/ -- | | -- | PostIdle jobs -- | | -- | |<-----------<-----------\ -- | Event handlers | Handle all queued events -- | |------------>-----------/ -- | | -- \-------<-------/ -- -- Events happen asynchronously but their handlers are executed sequentially -- (i.e., without concurrency) in the event arrival order. We can use these -- handlers to modify a state without having to deal with race conditions or -- scheduling (fairness, etc.). -- -- As a consequence, jobs executed in the event loop must be as short as -- possible. They mustn't block or wait for events themselves. These jobs are -- executed by a single thread (no concurrence): longer jobs must be explicitly -- threaded. -- -- -- -- Note [Rendering loop] -- ~~~~~~~~~~~~~~~~~~~~~ -- -- The rendering loop manages the GUI. It is an event loop where events can be -- generated by input devices, timers, animators, etc. -- -- The GUI state is altered in event handlers (and maybe in some idle jobs). -- -- The rendering itself is performed by a PredIdle job. type L a = IO a data JobResponse = JobRenew | JobRemove deriving (Show,Eq) mainLoop :: TVar [L JobResponse] -> TQueue (L JobResponse) -> TVar [L JobResponse] -> TQueue (L ()) -> L () mainLoop enterers idlers exiters handlers = go where go = do execJobs enterers execIdle execJobs exiters execHandlers handlerLimit go -- if handlers appear faster than they are executed, we still want to -- execute the loop sometimes. We use this limit to ensure that we don't -- execute more than `handlerLimit` handlers in one iteration. handlerLimit :: Int handlerLimit = 1000 execJobs jobList = do jobs <- atomically <| swapTVar jobList [] res <- sequence jobs -- filter jobs that shouldn't be executed anymore let jobs' = (jobs `zip` res) |> filter ((== JobRenew) . snd) |> fmap fst -- append the renewed jobs to the jobs that may have been added since -- we started executing jobs atomically <| modifyTVar' jobList (jobs'++) -- execute idle jobs or sleep execIdle = do r <- atomically <| do emptyHandler <- isEmptyTQueue handlers emptyIdler <- isEmptyTQueue idlers case (emptyHandler, emptyIdler) of (True,True) -> retry -- sleep (True,False) -> tryReadTQueue idlers -- return idle job (False,_) -> return Nothing case r of Nothing -> return () Just j -> do -- execute idle job j >>= \case -- queue it again if necessary JobRenew -> atomically (writeTQueue idlers j) JobRemove -> return () -- loop execIdle -- execute handlers execHandlers 0 = return () execHandlers limit = do mj <- atomically <| tryReadTQueue handlers case mj of Nothing -> return () Just j -> do j execHandlers (limit - 1)
hsyl20/ViperVM
haskus-system/src/lib/Haskus/System/EventLoop.hs
bsd-3-clause
4,025
0
20
1,428
574
313
261
52
7
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Typecheck arrow notation -} {-# LANGUAGE RankNTypes #-} module TcArrows ( tcProc ) where import {-# SOURCE #-} TcExpr( tcMonoExpr, tcInferRho, tcSyntaxOp, tcCheckId, tcPolyExpr ) import HsSyn import TcMatches import TcHsSyn( hsLPatType ) import TcType import TcMType import TcBinds import TcPat import TcUnify import TcRnMonad import TcEnv import TcEvidence import Id( mkLocalId ) import Inst import Name import Coercion ( Role(..) ) import TysWiredIn import VarSet import TysPrim import BasicTypes( Arity ) import SrcLoc import Outputable import FastString import Util import Control.Monad {- Note [Arrow overivew] ~~~~~~~~~~~~~~~~~~~~~ Here's a summary of arrows and how they typecheck. First, here's a cut-down syntax: expr ::= .... | proc pat cmd cmd ::= cmd exp -- Arrow application | \pat -> cmd -- Arrow abstraction | (| exp cmd1 ... cmdn |) -- Arrow form, n>=0 | ... -- If, case in the usual way cmd_type ::= carg_type --> type carg_type ::= () | (type, carg_type) Note that * The 'exp' in an arrow form can mention only "arrow-local" variables * An "arrow-local" variable is bound by an enclosing cmd binding form (eg arrow abstraction) * A cmd_type is here written with a funny arrow "-->", The bit on the left is a carg_type (command argument type) which itself is a nested tuple, finishing with () * The arrow-tail operator (e1 -< e2) means (| e1 <<< arr snd |) e2 ************************************************************************ * * Proc * * ************************************************************************ -} tcProc :: InPat Name -> LHsCmdTop Name -- proc pat -> expr -> TcRhoType -- Expected type of whole proc expression -> TcM (OutPat TcId, LHsCmdTop TcId, TcCoercion) tcProc pat cmd exp_ty = newArrowScope $ do { (co, (exp_ty1, res_ty)) <- matchExpectedAppTy exp_ty ; (co1, (arr_ty, arg_ty)) <- matchExpectedAppTy exp_ty1 ; let cmd_env = CmdEnv { cmd_arr = arr_ty } ; (pat', cmd') <- tcPat ProcExpr pat arg_ty $ tcCmdTop cmd_env cmd (unitTy, res_ty) ; let res_co = mkTcTransCo co (mkTcAppCo co1 (mkTcNomReflCo res_ty)) ; return (pat', cmd', res_co) } {- ************************************************************************ * * Commands * * ************************************************************************ -} -- See Note [Arrow overview] type CmdType = (CmdArgType, TcTauType) -- cmd_type type CmdArgType = TcTauType -- carg_type, a nested tuple data CmdEnv = CmdEnv { cmd_arr :: TcType -- arrow type constructor, of kind *->*->* } mkCmdArrTy :: CmdEnv -> TcTauType -> TcTauType -> TcTauType mkCmdArrTy env t1 t2 = mkAppTys (cmd_arr env) [t1, t2] --------------------------------------- tcCmdTop :: CmdEnv -> LHsCmdTop Name -> CmdType -> TcM (LHsCmdTop TcId) tcCmdTop env (L loc (HsCmdTop cmd _ _ names)) cmd_ty@(cmd_stk, res_ty) = setSrcSpan loc $ do { cmd' <- tcCmd env cmd cmd_ty ; names' <- mapM (tcSyntaxName ProcOrigin (cmd_arr env)) names ; return (L loc $ HsCmdTop cmd' cmd_stk res_ty names') } ---------------------------------------- tcCmd :: CmdEnv -> LHsCmd Name -> CmdType -> TcM (LHsCmd TcId) -- The main recursive function tcCmd env (L loc cmd) res_ty = setSrcSpan loc $ do { cmd' <- tc_cmd env cmd res_ty ; return (L loc cmd') } tc_cmd :: CmdEnv -> HsCmd Name -> CmdType -> TcM (HsCmd TcId) tc_cmd env (HsCmdPar cmd) res_ty = do { cmd' <- tcCmd env cmd res_ty ; return (HsCmdPar cmd') } tc_cmd env (HsCmdLet binds (L body_loc body)) res_ty = do { (binds', body') <- tcLocalBinds binds $ setSrcSpan body_loc $ tc_cmd env body res_ty ; return (HsCmdLet binds' (L body_loc body')) } tc_cmd env in_cmd@(HsCmdCase scrut matches) (stk, res_ty) = addErrCtxt (cmdCtxt in_cmd) $ do (scrut', scrut_ty) <- tcInferRho scrut matches' <- tcMatchesCase match_ctxt scrut_ty matches res_ty return (HsCmdCase scrut' matches') where match_ctxt = MC { mc_what = CaseAlt, mc_body = mc_body } mc_body body res_ty' = tcCmd env body (stk, res_ty') tc_cmd env (HsCmdIf Nothing pred b1 b2) res_ty -- Ordinary 'if' = do { pred' <- tcMonoExpr pred boolTy ; b1' <- tcCmd env b1 res_ty ; b2' <- tcCmd env b2 res_ty ; return (HsCmdIf Nothing pred' b1' b2') } tc_cmd env (HsCmdIf (Just fun) pred b1 b2) res_ty -- Rebindable syntax for if = do { pred_ty <- newFlexiTyVarTy openTypeKind -- For arrows, need ifThenElse :: forall r. T -> r -> r -> r -- because we're going to apply it to the environment, not -- the return value. ; (_, [r_tv]) <- tcInstSkolTyVars [alphaTyVar] ; let r_ty = mkTyVarTy r_tv ; let if_ty = mkFunTys [pred_ty, r_ty, r_ty] r_ty ; checkTc (not (r_tv `elemVarSet` tyVarsOfType pred_ty)) (ptext (sLit "Predicate type of `ifThenElse' depends on result type")) ; fun' <- tcSyntaxOp IfOrigin fun if_ty ; pred' <- tcMonoExpr pred pred_ty ; b1' <- tcCmd env b1 res_ty ; b2' <- tcCmd env b2 res_ty ; return (HsCmdIf (Just fun') pred' b1' b2') } ------------------------------------------- -- Arrow application -- (f -< a) or (f -<< a) -- -- D |- fun :: a t1 t2 -- D,G |- arg :: t1 -- ------------------------ -- D;G |-a fun -< arg :: stk --> t2 -- -- D,G |- fun :: a t1 t2 -- D,G |- arg :: t1 -- ------------------------ -- D;G |-a fun -<< arg :: stk --> t2 -- -- (plus -<< requires ArrowApply) tc_cmd env cmd@(HsCmdArrApp fun arg _ ho_app lr) (_, res_ty) = addErrCtxt (cmdCtxt cmd) $ do { arg_ty <- newFlexiTyVarTy openTypeKind ; let fun_ty = mkCmdArrTy env arg_ty res_ty ; fun' <- select_arrow_scope (tcMonoExpr fun fun_ty) ; arg' <- tcMonoExpr arg arg_ty ; return (HsCmdArrApp fun' arg' fun_ty ho_app lr) } where -- Before type-checking f, use the environment of the enclosing -- proc for the (-<) case. -- Local bindings, inside the enclosing proc, are not in scope -- inside f. In the higher-order case (-<<), they are. -- See Note [Escaping the arrow scope] in TcRnTypes select_arrow_scope tc = case ho_app of HsHigherOrderApp -> tc HsFirstOrderApp -> escapeArrowScope tc ------------------------------------------- -- Command application -- -- D,G |- exp : t -- D;G |-a cmd : (t,stk) --> res -- ----------------------------- -- D;G |-a cmd exp : stk --> res tc_cmd env cmd@(HsCmdApp fun arg) (cmd_stk, res_ty) = addErrCtxt (cmdCtxt cmd) $ do { arg_ty <- newFlexiTyVarTy openTypeKind ; fun' <- tcCmd env fun (mkPairTy arg_ty cmd_stk, res_ty) ; arg' <- tcMonoExpr arg arg_ty ; return (HsCmdApp fun' arg') } ------------------------------------------- -- Lambda -- -- D;G,x:t |-a cmd : stk --> res -- ------------------------------ -- D;G |-a (\x.cmd) : (t,stk) --> res tc_cmd env (HsCmdLam (MG { mg_alts = [L mtch_loc (match@(Match pats _maybe_rhs_sig grhss))], mg_origin = origin })) (cmd_stk, res_ty) = addErrCtxt (pprMatchInCtxt match_ctxt match) $ do { (co, arg_tys, cmd_stk') <- matchExpectedCmdArgs n_pats cmd_stk -- Check the patterns, and the GRHSs inside ; (pats', grhss') <- setSrcSpan mtch_loc $ tcPats LambdaExpr pats arg_tys $ tc_grhss grhss cmd_stk' res_ty ; let match' = L mtch_loc (Match pats' Nothing grhss') arg_tys = map hsLPatType pats' cmd' = HsCmdLam (MG { mg_alts = [match'], mg_arg_tys = arg_tys , mg_res_ty = res_ty, mg_origin = origin }) ; return (mkHsCmdCast co cmd') } where n_pats = length pats match_ctxt = (LambdaExpr :: HsMatchContext Name) -- Maybe KappaExpr? pg_ctxt = PatGuard match_ctxt tc_grhss (GRHSs grhss binds) stk_ty res_ty = do { (binds', grhss') <- tcLocalBinds binds $ mapM (wrapLocM (tc_grhs stk_ty res_ty)) grhss ; return (GRHSs grhss' binds') } tc_grhs stk_ty res_ty (GRHS guards body) = do { (guards', rhs') <- tcStmtsAndThen pg_ctxt tcGuardStmt guards res_ty $ \ res_ty -> tcCmd env body (stk_ty, res_ty) ; return (GRHS guards' rhs') } ------------------------------------------- -- Do notation tc_cmd env (HsCmdDo stmts _) (cmd_stk, res_ty) = do { co <- unifyType unitTy cmd_stk -- Expecting empty argument stack ; stmts' <- tcStmts ArrowExpr (tcArrDoStmt env) stmts res_ty ; return (mkHsCmdCast co (HsCmdDo stmts' res_ty)) } ----------------------------------------------------------------- -- Arrow ``forms'' (| e c1 .. cn |) -- -- D; G |-a1 c1 : stk1 --> r1 -- ... -- D; G |-an cn : stkn --> rn -- D |- e :: forall e. a1 (e, stk1) t1 -- ... -- -> an (e, stkn) tn -- -> a (e, stk) t -- e \not\in (stk, stk1, ..., stkm, t, t1, ..., tn) -- ---------------------------------------------- -- D; G |-a (| e c1 ... cn |) : stk --> t tc_cmd env cmd@(HsCmdArrForm expr fixity cmd_args) (cmd_stk, res_ty) = addErrCtxt (cmdCtxt cmd) $ do { (cmd_args', cmd_tys) <- mapAndUnzipM tc_cmd_arg cmd_args ; let e_ty = mkForAllTy alphaTyVar $ -- We use alphaTyVar for 'w' mkFunTys cmd_tys $ mkCmdArrTy env (mkPairTy alphaTy cmd_stk) res_ty ; expr' <- tcPolyExpr expr e_ty ; return (HsCmdArrForm expr' fixity cmd_args') } where tc_cmd_arg :: LHsCmdTop Name -> TcM (LHsCmdTop TcId, TcType) tc_cmd_arg cmd = do { arr_ty <- newFlexiTyVarTy arrowTyConKind ; stk_ty <- newFlexiTyVarTy liftedTypeKind ; res_ty <- newFlexiTyVarTy liftedTypeKind ; let env' = env { cmd_arr = arr_ty } ; cmd' <- tcCmdTop env' cmd (stk_ty, res_ty) ; return (cmd', mkCmdArrTy env' (mkPairTy alphaTy stk_ty) res_ty) } ----------------------------------------------------------------- -- Base case for illegal commands -- This is where expressions that aren't commands get rejected tc_cmd _ cmd _ = failWithTc (vcat [ptext (sLit "The expression"), nest 2 (ppr cmd), ptext (sLit "was found where an arrow command was expected")]) matchExpectedCmdArgs :: Arity -> TcType -> TcM (TcCoercion, [TcType], TcType) matchExpectedCmdArgs 0 ty = return (mkTcNomReflCo ty, [], ty) matchExpectedCmdArgs n ty = do { (co1, [ty1, ty2]) <- matchExpectedTyConApp pairTyCon ty ; (co2, tys, res_ty) <- matchExpectedCmdArgs (n-1) ty2 ; return (mkTcTyConAppCo Nominal pairTyCon [co1, co2], ty1:tys, res_ty) } {- ************************************************************************ * * Stmts * * ************************************************************************ -} -------------------------------- -- Mdo-notation -- The distinctive features here are -- (a) RecStmts, and -- (b) no rebindable syntax tcArrDoStmt :: CmdEnv -> TcCmdStmtChecker tcArrDoStmt env _ (LastStmt rhs _) res_ty thing_inside = do { rhs' <- tcCmd env rhs (unitTy, res_ty) ; thing <- thing_inside (panic "tcArrDoStmt") ; return (LastStmt rhs' noSyntaxExpr, thing) } tcArrDoStmt env _ (BodyStmt rhs _ _ _) res_ty thing_inside = do { (rhs', elt_ty) <- tc_arr_rhs env rhs ; thing <- thing_inside res_ty ; return (BodyStmt rhs' noSyntaxExpr noSyntaxExpr elt_ty, thing) } tcArrDoStmt env ctxt (BindStmt pat rhs _ _) res_ty thing_inside = do { (rhs', pat_ty) <- tc_arr_rhs env rhs ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $ thing_inside res_ty ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) } tcArrDoStmt env ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = later_names , recS_rec_ids = rec_names }) res_ty thing_inside = do { let tup_names = rec_names ++ filterOut (`elem` rec_names) later_names ; tup_elt_tys <- newFlexiTyVarTys (length tup_names) liftedTypeKind ; let tup_ids = zipWith mkLocalId tup_names tup_elt_tys ; tcExtendIdEnv tup_ids $ do { (stmts', tup_rets) <- tcStmtsAndThen ctxt (tcArrDoStmt env) stmts res_ty $ \ _res_ty' -> -- ToDo: res_ty not really right zipWithM tcCheckId tup_names tup_elt_tys ; thing <- thing_inside res_ty -- NB: The rec_ids for the recursive things -- already scope over this part. This binding may shadow -- some of them with polymorphic things with the same Name -- (see note [RecStmt] in HsExpr) ; let rec_ids = takeList rec_names tup_ids ; later_ids <- tcLookupLocalIds later_names ; let rec_rets = takeList rec_names tup_rets ; let ret_table = zip tup_ids tup_rets ; let later_rets = [r | i <- later_ids, (j, r) <- ret_table, i == j] ; return (emptyRecStmtId { recS_stmts = stmts' , recS_later_ids = later_ids , recS_later_rets = later_rets , recS_rec_ids = rec_ids , recS_rec_rets = rec_rets , recS_ret_ty = res_ty }, thing) }} tcArrDoStmt _ _ stmt _ _ = pprPanic "tcArrDoStmt: unexpected Stmt" (ppr stmt) tc_arr_rhs :: CmdEnv -> LHsCmd Name -> TcM (LHsCmd TcId, TcType) tc_arr_rhs env rhs = do { ty <- newFlexiTyVarTy liftedTypeKind ; rhs' <- tcCmd env rhs (unitTy, ty) ; return (rhs', ty) } {- ************************************************************************ * * Helpers * * ************************************************************************ -} mkPairTy :: Type -> Type -> Type mkPairTy t1 t2 = mkTyConApp pairTyCon [t1,t2] arrowTyConKind :: Kind -- *->*->* arrowTyConKind = mkArrowKinds [liftedTypeKind, liftedTypeKind] liftedTypeKind {- ************************************************************************ * * Errors * * ************************************************************************ -} cmdCtxt :: HsCmd Name -> SDoc cmdCtxt cmd = ptext (sLit "In the command:") <+> ppr cmd
bitemyapp/ghc
compiler/typecheck/TcArrows.hs
bsd-3-clause
15,827
0
17
5,034
3,390
1,797
1,593
211
2
-- | -- Module : Crypto.PubKey.RSA -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : Good -- module Crypto.PubKey.RSA ( Error(..) , PublicKey(..) , PrivateKey(..) , Blinder(..) -- * generation function , generateWith , generate , generateBlinder ) where import Crypto.Internal.Imports import Crypto.Random.Types import Crypto.Number.ModArithmetic (inverse, inverseCoprimes) import Crypto.Number.Generate (generateMax) import Crypto.Number.Prime (generatePrime) import Crypto.PubKey.RSA.Types {- -- some bad implementation will not serialize ASN.1 integer properly, leading -- to negative modulus. -- TODO : Find a better place for this toPositive :: Integer -> Integer toPositive int | int < 0 = uintOfBytes $ bytesOfInt int | otherwise = int where uintOfBytes = foldl (\acc n -> (acc `shiftL` 8) + fromIntegral n) 0 bytesOfInt :: Integer -> [Word8] bytesOfInt n = if testBit (head nints) 7 then nints else 0xff : nints where nints = reverse $ plusOne $ reverse $ map complement $ bytesOfUInt (abs n) plusOne [] = [1] plusOne (x:xs) = if x == 0xff then 0 : plusOne xs else (x+1) : xs bytesOfUInt x = reverse (list x) where list i = if i <= 0xff then [fromIntegral i] else (fromIntegral i .&. 0xff) : list (i `shiftR` 8) -} -- | Generate a key pair given p and q. -- -- p and q need to be distinct prime numbers. -- -- e need to be coprime to phi=(p-1)*(q-1). If that's not the -- case, the function will not return a key pair. -- A small hamming weight results in better performance. -- -- * e=0x10001 is a popular choice -- -- * e=3 is popular as well, but proven to not be as secure for some cases. -- generateWith :: (Integer, Integer) -- ^ chosen distinct primes p and q -> Int -- ^ size in bytes -> Integer -- ^ RSA public exponant 'e' -> Maybe (PublicKey, PrivateKey) generateWith (p,q) size e = case inverse e phi of Nothing -> Nothing Just d -> Just (pub,priv d) where n = p*q phi = (p-1)*(q-1) -- q and p should be *distinct* *prime* numbers, hence always coprime qinv = inverseCoprimes q p pub = PublicKey { public_size = size , public_n = n , public_e = e } priv d = PrivateKey { private_pub = pub , private_d = d , private_p = p , private_q = q , private_dP = d `mod` (p-1) , private_dQ = d `mod` (q-1) , private_qinv = qinv } -- | generate a pair of (private, public) key of size in bytes. generate :: MonadRandom m => Int -- ^ size in bytes -> Integer -- ^ RSA public exponant 'e' -> m (PublicKey, PrivateKey) generate size e = loop where loop = do -- loop until we find a valid key pair given e pq <- generatePQ case generateWith pq size e of Nothing -> loop Just pp -> return pp generatePQ = do p <- generatePrime (8 * (size `div` 2)) q <- generateQ p return (p,q) generateQ p = do q <- generatePrime (8 * (size - (size `div` 2))) if p == q then generateQ p else return q -- | Generate a blinder to use with decryption and signing operation -- -- the unique parameter apart from the random number generator is the -- public key value N. generateBlinder :: MonadRandom m => Integer -- ^ RSA public N parameter. -> m Blinder generateBlinder n = (\r -> Blinder r (inverseCoprimes r n)) <$> generateMax n
nomeata/cryptonite
Crypto/PubKey/RSA.hs
bsd-3-clause
3,927
0
16
1,323
623
363
260
57
3
-------------------------------------------------------------------------------- module Network.WebSockets.Tests.Util ( ArbitraryUtf8 (..) , arbitraryUtf8 , arbitraryByteString ) where -------------------------------------------------------------------------------- import Control.Applicative ((<$>)) import qualified Data.ByteString.Lazy as BL import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import Test.QuickCheck (Arbitrary (..), Gen) -------------------------------------------------------------------------------- import Network.WebSockets.Types -------------------------------------------------------------------------------- newtype ArbitraryUtf8 = ArbitraryUtf8 {unArbitraryUtf8 :: BL.ByteString} deriving (Eq, Ord, Show) -------------------------------------------------------------------------------- instance Arbitrary ArbitraryUtf8 where arbitrary = ArbitraryUtf8 <$> arbitraryUtf8 -------------------------------------------------------------------------------- arbitraryUtf8 :: Gen BL.ByteString arbitraryUtf8 = toLazyByteString . TL.encodeUtf8 . TL.pack <$> arbitrary -------------------------------------------------------------------------------- arbitraryByteString :: Gen BL.ByteString arbitraryByteString = BL.pack <$> arbitrary
nsluss/websockets
tests/haskell/Network/WebSockets/Tests/Util.hs
bsd-3-clause
1,381
0
8
180
192
122
70
18
1
{-# LANGUAGE OverloadedStrings #-} -- | All hardcoded names in the compiler should go in here -- the convention is -- v_foo for values -- tc_foo for type constructors -- dc_foo for data constructors -- s_foo for sort names -- rt_foo for raw names -- class_foo for classes module Name.Names(module Name.Name,module Name.Names,module Name.Prim) where import Char(isDigit) import Name.Name import Name.Prim import Name.VConsts import StringTable.Atom import Ty.Level instance TypeNames Name where tInt = tc_Int tBool = tc_Bool tInteger = tc_Integer tChar = tc_Char tUnit = tc_Unit tIntzh = rt_bits32 tEnumzh = rt_bits16 tCharzh = tc_Char_ -- tWorld__ = tc_World__ --No tuple instance because it is easy to get the namespace wrong. use 'nameTuple' --instance ToTuple Name where -- toTuple n = toName DataConstructor (toTuple n :: (String,String)) nameTuple t 0 = toName t dc_Unit -- $ -- (toTuple n:: (String,String)) -- Qual (HsIdent ("(" ++ replicate (n - 1) ',' ++ ")")) nameTuple _ n | n < 2 = error "attempt to create tuple of length < 2" nameTuple t n = toName t $ (toTuple n:: (String,String)) -- Qual (HsIdent ("(" ++ replicate (n - 1) ',' ++ ")")) unboxedNameTuple t n = toName t $ "(#" ++ show n ++ "#)" fromUnboxedNameTuple n = case show n of '(':'#':xs | (ns@(_:_),"#)") <- span isDigit xs -> return (read ns::Int) _ -> fail $ "Not unboxed tuple: " ++ show n instance FromTupname Name where fromTupname name | m == mod_JhcPrimPrim = fromTupname (nn::String) where (_,(m,nn)) = fromName name fromTupname _ = fail "not a tuple" sFuncNames = FuncNames { func_equals = v_equals, func_fromInteger = v_fromInteger, func_fromInt = v_fromInt, func_fromRational = v_fromRational, func_negate = v_negate, func_runExpr = v_runExpr, func_runMain = v_runMain, func_runNoWrapper = v_runNoWrapper, func_runRaw = v_runRaw } -------------- -- tuple names -------------- name_TupleConstructor :: TyLevel -> Int -> Name name_TupleConstructor l 1 = error $ "name_TupleConstructor called for unary tuple at " ++ show l name_TupleConstructor l 0 = nameTyLevel_u (const l) dc_Unit name_TupleConstructor l n = mkName l True (Just mod_JhcPrimPrim) ("(" ++ replicate (n - 1) ',' ++ ")") name_UnboxedTupleConstructor :: TyLevel -> Int -> Name name_UnboxedTupleConstructor l n = mkName l True Nothing ("(#" ++ show n ++ "#)") -- checks whether it is either a normal or unboxed tuple. Bool return is whether -- it is boxed. fromName_Tuple :: Name -> Maybe (Bool,TyLevel,Int) fromName_Tuple n | n == dc_Unit = Just (True,termLevel,0) fromName_Tuple n | n == tc_Unit = Just (True,typeLevel,0) fromName_Tuple n = f (unMkName n) where f NameParts { nameQuoted = False, nameConstructor = True, nameOuter = [], nameUniquifier = Nothing, .. } | nameModule == Just mod_JhcPrimPrim, Just n <- fromTupname nameIdent = Just (True,nameLevel,n) | Just n <- fromUnboxedNameTuple (toAtom nameIdent) = Just (False,nameLevel,n) f _ = Nothing fromName_UnboxedTupleConstructor :: Name -> Maybe (TyLevel,Int) fromName_UnboxedTupleConstructor (fromName_Tuple -> Just (False,tl,n)) = Just (tl,n) fromName_UnboxedTupleConstructor _ = Nothing fromName_TupleConstructor :: Name -> Maybe (TyLevel,Int) fromName_TupleConstructor (fromName_Tuple -> Just (True,tl,n)) = Just (tl,n) fromName_TupleConstructor _ = Nothing
hvr/jhc
src/Name/Names.hs
mit
3,414
0
15
638
941
508
433
-1
-1
module LocalWhereIn2 where --A definition can be removed if it is not used by other declarations. --Where a definition is removed, it's type signature should also be removed. --In this Example: remove the defintion 'square' sumSquares x y =sq x + sq y sq x= x^pow where pow=2 anotherFun x =sumSquares x x
SAdams601/HaRe
old/testing/removeDef/LocalWhereIn2_TokOut.hs
bsd-3-clause
338
0
6
86
59
31
28
5
1
module Record1 where data C = F {f1 :: Int, f3 :: Bool} g = f1 (F 1 True)
SAdams601/HaRe
old/testing/removeField/Record1_TokOut.hs
bsd-3-clause
76
0
8
21
41
24
17
3
1
{-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} module T12668 where import GHC.Exts data Some r = Some (TYPE r -> TYPE r) doSomething :: forall (r :: RuntimeRep). forall (a :: TYPE r). () => Int -> (a -> Int) -> a -> a doSomething n f = case n of 1 -> error "hello" 3 -> error "hello"
sdiehl/ghc
testsuite/tests/polykinds/T12668.hs
bsd-3-clause
324
0
11
92
119
66
53
-1
-1
-- This file is understood to be in the public domain. module MonadTrans where {- - This provides a way of accessing a monad that is inside - another monad. -} class MonadTrans t where lift :: Monad m => m a -> t m a --liftTrans :: (MonadTrans t) => (a -> t m b) -> (t m a -> t m b) --liftTrans f m = do { a <- m ; f a }
seereason/ghcjs
test/nofib/spectral/cryptarithm2/MonadTrans.hs
mit
332
0
9
88
41
22
19
3
0
{-# LANGUAGE DeriveGeneric #-} module GenBigTypes where import GHC.Generics data BigSum = C0 | C1 | C2 | C3 | C4 | C5 | C6 | C7 | C8 | C9 | C10 | C11 | C12 | C13 | C14 | C15 | C16 | C17 | C18 | C19 | C20 | C21 | C22 | C23 | C24 | C25 | C26 | C27 | C28 | C29 | C30 | C31 | C32 | C33 | C34 | C35 | C36 | C37 | C38 | C39 | C40 | C41 | C42 | C43 | C44 | C45 | C46 | C47 | C48 | C49 | C50 | C51 | C52 | C53 | C54 | C55 | C56 | C57 | C58 | C59 | C60 | C61 | C62 | C63 | C64 | C65 | C66 | C67 | C68 | C69 | C70 | C71 | C72 | C73 | C74 | C75 | C76 | C77 | C78 | C79 | C80 | C81 | C82 | C83 | C84 | C85 | C86 | C87 | C88 | C89 | C90 | C91 | C92 | C93 | C94 | C95 | C96 | C97 | C98 | C99 deriving Generic
ezyang/ghc
testsuite/tests/perf/compiler/T5642.hs
bsd-3-clause
903
0
5
421
317
211
106
15
0
module A071 where
siddhanathan/ghc
testsuite/tests/driver/A071.hs
bsd-3-clause
18
0
2
3
4
3
1
1
0
sumNatNums :: Integer -> Integer sumNatNums 1 = 1 sumNatNums n = n + sumNatNums (n - 1) sumNatNums' :: Integer -> Integer -> Integer sumNatNums' 1 acc = acc + 1 sumNatNums' n acc = sumNatNums' (n - 1) (acc + n) main = do putStrLn $ show $ sumNatNums 5000000 putStrLn $ show $ sumNatNums' 5000000 0
fredmorcos/attic
snippets/haskell/NatNum.hs
isc
310
0
8
71
131
65
66
8
1
{-# htermination enumFrom :: () -> [()] #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_enumFrom_2.hs
mit
44
0
2
8
3
2
1
1
0
--Creates a new git repo in the current directory and --adds an empty README.md, barebones .gitignore, and --a copy of the MIT license, then commits them import System.Directory (getCurrentDirectory) import System.Environment(getArgs) import System.FilePath.Posix(splitPath) import System.Process(runCommand,waitForProcess) import Data.List(last,break,length,replicate) import Data.Time(getCurrentTime,utctDay,toGregorian) main = do args <- getArgs currentDir <- getCurrentDirectory date <- getCurrentTime writeFiles currentDir date runCommand ("git init " ++ concat args) >>= waitForProcess runCommand "git add ." >>= waitForProcess runCommand "git commit -m 'Initial commit'" >>= waitForProcess where writeFiles dir date = do writeFile "LICENSE" (createLicense date dir) writeFile "README.md" "This is an empty readme" writeFile ".gitignore" gitIgnore createLicense date cs = name ++ "\n" ++ dots ++ "\n" ++ "Author: Leif Grele\n" ++ "Copyright (c) Leif Grele " ++ show year ++ "\n\n" ++ mit where name = last (splitPath cs) dots = replicate (length cs) '-' (year,_,_) = toGregorian (utctDay date) mit = "License Agreement (The MIT License)\n\n\ \Permission is hereby granted, free of charge, to any person obtaining a copy\n\ \of this software and associated documentation files (the \"Software\"), to deal\n\ \in the Software without restriction, including without limitation the rights\n\ \to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ \copies of the Software, and to permit persons to whom the Software is\n\ \furnished to do so, subject to the following conditions:\n\n\ \The above copyright notice and this permission notice shall be included in\n\ \all copies or substantial portions of the Software.\n\n\ \THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\ \IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\ \FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\ \AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\ \LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\ \OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\ \THE SOFTWARE." gitIgnore = "#ignore builds\n\ \build/*\n\n\ \#ignore sublime project files\n\ \*.sublime-project\n\ \*.sublime-workspace\n\n\ \#ignore objects and archives\n\ \*.[oa]"
Hrothen/scripts
src/ginit/ginit.hs
mit
2,633
3
12
557
317
160
157
26
1
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE JavaScriptFFI #-} -- | JavaScript marshalling. This module is pretty unsafe. Be careful. module Alder.JavaScript ( JSObj , JSValue(..) , JSArgs(..) , window , (.:) , writeProp , call , apply ) where import Control.Applicative import Control.Monad.Trans import Data.Maybe import Data.Text as Text import GHCJS.Foreign import GHCJS.Marshal import GHCJS.Types type JSObj = JSRef () class JSValue a where toJSValue :: a -> IO (JSRef b) fromJSValue :: JSRef b -> IO a instance JSValue () where toJSValue _ = return nullRef fromJSValue _ = return () instance JSValue (JSRef a) where toJSValue = return . castRef fromJSValue = return . castRef instance JSValue a => JSValue (Maybe a) where toJSValue = maybe (return nullRef) toJSValue fromJSValue ref | isNull ref || isUndefined ref = return Nothing | otherwise = Just <$> fromJSValue ref instance JSValue Bool where toJSValue = return . castRef . toJSBool fromJSValue = return . fromJSBool' . castRef instance JSValue Int where toJSValue = fmap castRef . toJSRef fromJSValue = fmap (fromMaybe 0) . fromJSRef . castRef instance JSValue Text where toJSValue = return . castRef . toJSString fromJSValue ref = convert <$> typeOf ref where convert 4 = fromJSString (castRef ref) convert _ = Text.empty class JSArgs a where applyFunction :: JSRef b -> JSString -> a -> IO (JSRef c) instance JSArgs () where applyFunction obj fun () = do res <- apply0 obj fun fromJSValue res instance (JSValue a, JSValue b) => JSArgs (a, b) where applyFunction obj fun (a, b) = do arg1 <- toJSValue a arg2 <- toJSValue b res <- apply2 obj fun arg1 arg2 fromJSValue res instance (JSValue a, JSValue b, JSValue c) => JSArgs (a, b, c) where applyFunction obj fun (a, b, c) = do arg1 <- toJSValue a arg2 <- toJSValue b arg3 <- toJSValue c res <- apply3 obj fun arg1 arg2 arg3 fromJSValue res -- | The global @window@ object. window :: JSRef a window = getWindow -- | Get a property value. (.:) :: (MonadIO m, JSValue b) => JSRef a -> Text -> m b obj .: prop = liftIO $ do res <- unsafeGetProp prop obj fromJSValue res -- | Set a property value. writeProp :: (MonadIO m, JSValue b) => JSRef a -> Text -> b -> m () writeProp obj prop b = liftIO $ do val <- toJSValue b unsafeSetProp prop val obj -- | Apply a function to an argument. call :: (MonadIO m, JSValue b, JSValue c) => JSRef a -> Text -> b -> m c call obj fun b = liftIO $ do arg <- toJSValue b res <- apply1 obj (toJSString fun) arg fromJSValue res -- | Apply a function to multiple arguments. apply :: (MonadIO m, JSArgs b, JSValue c) => JSRef a -> Text -> b -> m c apply obj fun b = liftIO $ do res <- applyFunction obj (toJSString fun) b fromJSValue res foreign import javascript unsafe "$r = window;" getWindow :: JSRef a foreign import javascript unsafe "$r = $1[$2]();" apply0 :: JSRef a -> JSString -> IO (JSRef b) foreign import javascript unsafe "$r = $1[$2]($3);" apply1 :: JSRef a -> JSString -> JSRef b -> IO (JSRef c) foreign import javascript unsafe "$r = $1[$2]($3, $4);" apply2 :: JSRef a -> JSString -> JSRef b -> JSRef c -> IO (JSRef d) foreign import javascript unsafe "$r = $1[$2]($3, $4, $5);" apply3 :: JSRef a -> JSString -> JSRef b -> JSRef c -> JSRef d -> IO (JSRef e)
ghcjs/ghcjs-sodium
src/Alder/JavaScript.hs
mit
3,677
21
13
1,042
1,240
619
621
93
1
-- http://www.seas.upenn.edu/~cis194/spring13/lectures/11-applicative2.html -- -- Implementing a few functions from the lecture notes -- import Control.Applicative -- This is my version of *> pointRightStar :: Applicative f => f a -> f b -> f b pointRightStar = Control.Applicative.liftA2 (const id) {-| f = Maybe f = [] f = ZipList f = IO f = Parser -} mapA' :: Applicative f => (a -> f b) -> ([a] -> f [b]) mapA' g xs = sequenceA' $ map g xs {-| f = Maybe f = [] f = ZipList f = IO f = Parser -} -- Reverse engineered based on the actual sequenceA function -- sequenceA' :: Applicative f => [f a] -> f [a] sequenceA' = foldr f (pure []) where f = \x acc -> (:) <$> x <*> acc -- The version in Haskell -- http://hackage.haskell.org/package/base-4.9.0.0/docs/src/Data.Traversable.html#sequenceA -- {-| -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that ignores -- the results see 'Data.Foldable.traverse_'. traverse :: Applicative f => (a -> f b) -> t a -> f (t b) traverse f = sequenceA . fmap f -- | Evaluate each action in the structure from left to right, and -- and collect the results. For a version that ignores the results -- see 'Data.Foldable.sequenceA_'. sequenceA :: Applicative f => t (f a) -> f (t a) sequenceA = traverse id -} {-| f = Maybe f = [] f = ZipList f = IO f = Parser -} replicateA' :: Applicative f => Int -> f a -> f [a] replicateA' n x = sequenceA' $ replicate n x {-| f = Maybe f = [] f = ZipList f = IO f = Parser -}
umairsd/course-haskell-cis194
hw11/wk11.hs
mit
1,602
0
10
364
246
131
115
10
1
module Record.Syntax.Prelude ( module Exports, LazyText, TextBuilder, (∘), (∘∘), zipTraversableWith, zipTraversableWithM, ) where -- base-prelude ------------------------- import BasePrelude as Exports hiding (left, right, isLeft, isRight) -- transformers ------------------------- import Control.Monad.Trans.State.Strict as Exports hiding (liftCallCC, liftCatch, liftListen, liftPass) import Control.Monad.Trans.Reader as Exports hiding (liftCallCC, liftCatch, liftListen, liftPass) import Control.Monad.Trans.Writer as Exports hiding (liftCallCC, liftCatch, liftListen, liftPass) import Control.Monad.Trans.Maybe as Exports hiding (liftCallCC, liftCatch, liftListen, liftPass) import Control.Monad.Trans.Class as Exports import Control.Monad.IO.Class as Exports import Data.Functor.Identity as Exports -- text ------------------------- import Data.Text as Exports (Text) -- conversion ------------------------- import Conversion as Exports import Conversion.Text as Exports import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TLB type LazyText = TL.Text type TextBuilder = TLB.Builder (∘) :: (a -> b) -> (c -> a) -> (c -> b) (∘) = (.) (∘∘) :: (a -> b) -> (c -> d -> a) -> (c -> d -> b) (∘∘) a b = \c d -> a (b c d) zipTraversableWith :: (Traversable t1, Foldable t2) => (a1 -> a2 -> a3) -> t1 a1 -> t2 a2 -> t1 a3 zipTraversableWith f t1 t2 = flip evalState (toList t2) $ flip traverse t1 $ \a1 -> state $ \case a2 : tail -> (f a1 a2, tail) zipTraversableWithM :: (Traversable t1, Foldable t2, Applicative m, Monad m) => (a1 -> a2 -> m a3) -> t1 a1 -> t2 a2 -> m (t1 a3) zipTraversableWithM f t1 t2 = flip evalStateT (toList t2) $ flip traverse t1 $ \a1 -> StateT $ \case a2 : tail -> (,) <$> f a1 a2 <*> pure tail
nikita-volkov/record-syntax
library/Record/Syntax/Prelude.hs
mit
1,813
0
13
312
634
381
253
-1
-1
module Koofr.File where import Data.Aeson.TH import Koofr.Internal data FileList = FileList { fileListFiles :: [File] } deriving (Eq, Show) data File = File { fileName :: String , fileType :: String , fileModified :: Integer , fileSize :: Integer , fileContentType :: String , hash :: Maybe String } deriving (Eq, Show) deriveJSON defaultOptions{fieldLabelModifier = (lowerCamel . drop 4)} ''File deriveJSON defaultOptions{fieldLabelModifier = (lowerCamel . drop 8)} ''FileList
edofic/koofr-api-hs
src/Koofr/File.hs
mit
585
0
10
175
161
92
69
-1
-1
{-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleContexts #-} module RefParser (parseRefsSheet, refexpr) where import System.Environment import Text.ParserCombinators.Parsec -- hiding (string) import Control.Applicative ((<*), (<$>), (<*>)) import Control.Monad (liftM) import Data.Array import Data.Char import Data.Map as M hiding (map, foldl, foldr, fold) import Data.Maybe import Data.Either (rights) import Data.Either.Utils (fromRight) import Data.List import Data.Monoid import Data.Function import Sheet import Expr import Cell import Ref import Cat -- | Parse the user input stings to the CellFns in each cell parseRefsSheet :: Sheet String -> Sheet CellFn parseRefsSheet = fmap ((either (const $ sval "Parse error") id).(parse refexpr "")) refexpr :: Parser CellFn refexpr = do (try fexpr) <|> pstring -- | This is the exported parser. It parses one of a numerical, string or boolean expression fexpr :: Parser CellFn fexpr = do char '=' (try bexpr) <|> (try sexpr) <|> (nexpr) -- | Parse a numerical expression in parentheses parenNexpr:: Parser CellFn parenNexpr = do char '(' whitespace e <- nexpr char ')' return e -- | Parse a string expression in parentheses parenSexpr:: Parser CellFn parenSexpr = do char '(' whitespace e <- sexpr char ')' whitespace return e -- | Parse a boolean expression in parentheses parenBexpr:: Parser CellFn parenBexpr = do char '(' whitespace e <- bexpr char ')' whitespace return e -- | Parse a numerical expression nexpr :: Parser CellFn nexpr = do first <- mulTerm ops <- addOps return $ foldl buildExpr first ops where buildExpr acc ('+', x) = cfor x acc buildExpr acc ('-', x) = cfor x acc -- | Parse a string expression sexpr:: Parser CellFn sexpr = do first <- sterm ops <- concatOps return $ foldl buildExpr first ops where buildExpr acc ('&', x) = cfor x acc -- | Parse a boolean expression bexpr :: Parser CellFn bexpr = do first <- andTerm ops <- orOps return $ foldl buildExpr first ops where buildExpr acc ('|', x) = cfor x acc -- | Second level of numerical terms - after addition, before powers mulTerm:: Parser CellFn mulTerm = do first <- powTerm ops <- mulOps return $ foldl buildExpr first ops where buildExpr acc ('*', x) = cfor x acc buildExpr acc ('/', x) = cfor x acc -- | Third level of numerical terms - after multiplication powTerm:: Parser CellFn powTerm = do first <- nterm ops <- powOps return $ foldl buildExpr first ops where buildExpr acc ('^', x) = cfor x acc -- | Parse a built in numerical function, or a numerical terminal nfuncTerm :: Parser CellFn nfuncTerm = (try nfunc) <|> nterm -- | Parse the boolean AND terms andTerm:: Parser CellFn andTerm = do first <- compTerm ops <- andOps return $ foldl buildExpr first ops where buildExpr acc ('&', x) = cfor x acc -- This is a comparison term eg 1>3, True=False, "Nick">"Straw" compTerm :: Parser CellFn compTerm = do (try bcomp) <|> (try scomp) <|> (try ncomp) <|> (try bterm) -- Numerical comparisons ncomp :: Parser CellFn ncomp = do x <- nterm; op <- compOp; y <- nterm; return $ cfor x y -- Boolean comparisons bcomp :: Parser CellFn bcomp = do x <- bterm; op <- compOp; y <- bterm; return $ cfor x y -- String comparisons scomp :: Parser CellFn scomp = do x <- sterm; op <- compOp; y <- sterm; return $ cfor x y -- gives a list of Fix Cells, need Fix Cell to be a monoid so we can add them addOps :: Parser [(Char, CellFn)] addOps = many addOp mulOps :: Parser [(Char, CellFn)] mulOps = many mulOp powOps :: Parser [(Char, CellFn)] powOps = many powOp orOps :: Parser [(Char, CellFn)] orOps = many orOp andOps :: Parser [(Char, CellFn)] andOps = many andOp concatOps :: Parser [(Char, CellFn)] concatOps = many concatOp addOp :: Parser (Char, CellFn) addOp = do op <- oneOf "+-" whitespace t <- mulTerm whitespace return (op, t) compOp :: Parser Char compOp = do op <- oneOf ">=<"; whitespace return op mulOp :: Parser (Char, CellFn) mulOp = do op <- oneOf "*/" whitespace t <- powTerm whitespace return (op, t) powOp :: Parser (Char, CellFn) powOp = do op <- oneOf "^" whitespace t <- nterm whitespace return (op, t) concatOp :: Parser (Char, CellFn) concatOp = do op <- oneOf "&" whitespace t <- sterm whitespace return (op, t) andOp :: Parser (Char, CellFn) andOp = do op <- string "&&" whitespace t <- compTerm -- bterm whitespace return (head op, t) orOp :: Parser (Char, CellFn) orOp = do op <- string "||" whitespace t <- andTerm -- bterm whitespace return (head op, t) nterm :: Parser CellFn nterm = do t <- term' whitespace return t where term' = (try $ number) <|> (try parenNexpr) <|> (try $ nfunc) <|> (try nRef) sterm :: Parser CellFn sterm = do t <- sterm' whitespace return t where sterm' = (try $ qstring) <|> (try parenSexpr) <|> (try $ sfunc) <|> (try sRef) bterm :: Parser CellFn bterm = do t <- bterm' whitespace return t where bterm' = (try $ pbool) <|> (try parenBexpr) <|> (try $ bfunc) <|> (try bRef) -- Quoted string qstring :: Parser CellFn qstring = do char '"' s <- manyTill (noneOf ("\"")) (char '"') whitespace return $ bval False pstring :: Parser CellFn pstring = do char '"' s <- manyTill (noneOf ("\"")) (char '"') whitespace return $ bval False s2b::String->Bool s2b s = if (map toUpper s)=="TRUE" then True else False pbool :: Parser CellFn pbool = do whitespace s <- string "True" <|> string "False"; return $ bval False pDigit:: Parser Char pDigit = oneOf ['0'..'9'] pSign:: Parser Char pSign = option '+' $ oneOf "-+" pDigits:: Parser [Char] pDigits = many1 pDigit pDecimalPoint :: Parser Char pDecimalPoint = char '.' pFracPart :: Parser [Char] pFracPart = option "0" (pDecimalPoint >> pDigits) number :: Parser CellFn number = do sign <- pSign integerPart <- pDigits fracPart <- pFracPart expPart <- pExp let i = read integerPart let f = read fracPart let e = expPart let value = (i + (f / 10^(length fracPart))) * 10 ^^ e return $ bval False where pExp = option 0 $ do oneOf "eE" sign <- pSign num <- pDigits let n = read num return $ if sign == '-' then negate n else n whitespace = many $ oneOf "\n\t\r\v " nfunc :: Parser CellFn nfunc = do fname <- manyTill letter (char '(') ps <- nexpr `sepBy` (char ',') char ')' return $ foldl cfor (bval False) ps sfunc :: Parser CellFn sfunc = do char '@' fname <- manyTill letter (char '(') ps <- sexpr `sepBy` (char ',') char ')' return $ foldl cfor (bval False) ps bfunc :: Parser CellFn bfunc = do char '@' fname <- manyTill letter (char '(') ps <- bexpr `sepBy` (char ',') char ')' return $ foldl cfor (bval False) ps pAbs:: Parser Char pAbs = char '$' pAlpha :: Parser Char pAlpha = oneOf "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" nRef :: Parser CellFn nRef = fmap eref pRef bRef :: Parser CellFn bRef = fmap eref pRef sRef :: Parser CellFn sRef = fmap eref pRef pRef :: Parser Ref pRef = try pAbsAbs <|> try pAbsRel <|> try pRelAbs <|> pRelRel -- So, A goes to 1, column counting starts at 1 u2i :: Char -> Int u2i c = ord (toUpper c) - 64 pAbsAbs :: Parser Ref pAbsAbs = do ac <- pAbs c <- pAlpha rc <- pAbs r <- pDigits return $ Ref (CAbs $ u2i c) (RAbs (read r)) pAbsRel :: Parser Ref pAbsRel = do ac <- pAbs c <- pAlpha r <- pDigits return $ Ref (CAbs $ u2i c) (RRel (read r)) pRelAbs :: Parser Ref pRelAbs = do c <- pAlpha rc <- pAbs r <- pDigits return $ Ref (CRel $ u2i c) (RAbs (read r)) pRelRel :: Parser Ref pRelRel = do c <- pAlpha r <- pDigits return $ Ref (CRel $ u2i c) (RRel (read r))
b1g3ar5/Spreadsheet
RefParser.hs
mit
8,982
21
17
2,756
3,004
1,492
1,512
280
2
import Control.Monad import qualified Control.Exception as E import System.IO handler (E.ErrorCall s) = putStrLn $ "*** Exception" incomplete1 0 = [undefined] incomplete1 n = n:(incomplete1 $ n-1) incomplete2 0 = undefined incomplete2 n = n:(incomplete2 $ n-1) main = do hSetBuffering stdout NoBuffering forM_ codelist $ \code -> do forM_ [0..2] $ \x -> do E.catch (print $ code $ incomplete1 x) handler E.catch (print $ code $ incomplete2 x) handler putStrLn "-----------------------" codelist = [ ((\x16 -> (\x17 -> ((\x18 -> x17) x17))) (id (undefined :: Int))), (\x16 -> ((seq id) (((\x17 -> (\x18 -> x16)) ((seq id) x16)) (((\x17 -> (\x18 -> (\x19 -> (undefined :: Int)))) x16) ((\x17 -> x16) x16))))), (\x16 -> (((\x17 -> (\x18 -> ((\x19 -> x19) x18))) ((\x17 -> x16) (undefined :: Int))) ((\x17 -> x16) ((\x17 -> (\x18 -> x16)) x16)))), ((\x16 -> (((\x17 -> seq) (id (undefined :: Int))) (\x17 -> (undefined :: Int)))) (undefined :: Int)), ((\x16 -> (\x17 -> x17)) ((id seq) ((\x16 -> (undefined :: Int)) (id ((\x16 -> (undefined :: Int)) (\x16 -> x16)))))), (seq ((((\x16 -> id) (undefined :: Int)) seq) (undefined :: Int))), (seq id), (\x16 -> x16), (\x16 -> ((\x17 -> x16) (((\x17 -> id) (\x17 -> (\x18 -> (undefined :: Int)))) (id (undefined :: Int))))), (((\x16 -> ((\x17 -> (\x18 -> (\x19 -> x19))) (undefined :: Int))) (undefined :: Int)) ((\x16 -> (undefined :: Int)) (((\x16 -> (\x17 -> (\x18 -> (undefined :: Int)))) (undefined :: Int)) (undefined :: Int)))), (seq id), (seq id), (seq (((((\x16 -> (\x17 -> id)) (undefined :: Int)) (id seq)) (\x16 -> id)) (undefined :: Int))), (seq id), ((\x16 -> (seq (\x17 -> (undefined :: Int)))) ((\x16 -> (\x17 -> (id (undefined :: Int)))) (undefined :: Int))), (((\x16 -> seq) (undefined :: Int)) (\x16 -> (undefined :: Int))), (\x16 -> (((\x17 -> (\x18 -> x16)) x16) (\x17 -> ((\x18 -> (\x19 -> x16)) (\x18 -> (\x19 -> (\x20 -> x17))))))), (seq id), (((\x16 -> seq) (undefined :: Int)) ((\x16 -> id) ((\x16 -> (\x17 -> x16)) (undefined :: Int)))), (seq (\x16 -> (undefined :: Int))), (seq id), (\x16 -> ((seq id) ((\x17 -> x16) x16))), (\x16 -> ((\x17 -> ((\x18 -> x16) (undefined :: Int))) x16)), ((\x16 -> (\x17 -> ((seq (seq (undefined :: Int))) x17))) (\x16 -> (((\x17 -> seq) (undefined :: Int)) id))), (((((\x16 -> (\x17 -> (\x18 -> seq))) (\x16 -> (\x17 -> (undefined :: Int)))) (undefined :: Int)) ((id (id (\x16 -> (\x17 -> (undefined :: Int))))) (undefined :: Int))) ((id seq) ((\x16 -> (undefined :: Int)) (undefined :: Int)))), (((\x16 -> ((\x17 -> (\x18 -> (\x19 -> x19))) (undefined :: Int))) ((\x16 -> (undefined :: Int)) ((seq (undefined :: Int)) (undefined :: Int)))) ((((\x16 -> (\x17 -> (\x18 -> (\x19 -> (\x20 -> (undefined :: Int)))))) ((\x16 -> (\x17 -> x16)) (undefined :: Int))) ((\x16 -> (\x17 -> (\x18 -> (undefined :: Int)))) (undefined :: Int))) ((\x16 -> (id (undefined :: Int))) (\x16 -> (undefined :: Int))))), (seq ((((\x16 -> (\x17 -> seq)) (undefined :: Int)) (\x16 -> (\x17 -> (undefined :: Int)))) ((\x16 -> (undefined :: Int)) (id (id (undefined :: Int)))))), (seq (\x16 -> (undefined :: Int))), (\x16 -> ((((\x17 -> (\x18 -> (\x19 -> x16))) (undefined :: Int)) x16) (((\x17 -> id) (id (undefined :: Int))) (((\x17 -> (\x18 -> (\x19 -> (\x20 -> (undefined :: Int))))) (undefined :: Int)) ((\x17 -> (undefined :: Int)) x16))))), (seq (seq (id (undefined :: Int)))), ((\x16 -> (\x17 -> x17)) (undefined :: Int)), ((\x16 -> (seq id)) (undefined :: Int)), ((((\x16 -> (\x17 -> seq)) (undefined :: Int)) (undefined :: Int)) (\x16 -> (undefined :: Int))), (id (seq (id (\x16 -> seq x16 id) (undefined :: Int)))), (((\x16 -> seq) ((\x16 -> (undefined :: Int)) (\x16 -> (undefined :: Int)))) (((\x16 -> seq) (undefined :: Int)) (id (undefined :: Int)))), (\x16 -> ((seq id) ((\x17 -> x16) (undefined :: Int)))), ((((\x16 -> (\x17 -> seq)) (\x16 -> x16)) id) (seq (id (undefined :: Int)))), (((\x16 -> seq) (undefined :: Int)) (\x16 -> (undefined :: Int))), ((((\x16 -> (\x17 -> seq)) (undefined :: Int)) ((\x16 -> (\x17 -> (\x18 -> (\x19 -> (\x20 -> (undefined :: Int)))))) (id (undefined :: Int)))) (seq (undefined :: Int))), (seq ((id ((\x16 -> seq) (undefined :: Int))) (undefined :: Int))), ((\x16 -> (seq (\x17 -> x17))) (id ((\x16 -> (x16 (\x17 -> id))) (\x16 -> (undefined :: Int))))), (seq id), (seq ((\x16 -> (\x17 -> (undefined :: Int))) (\x16 -> ((\x17 -> (\x18 -> (\x19 -> x18))) (id (undefined :: Int)))))), (\x16 -> (((((\x17 -> (\x18 -> seq)) (\x17 -> (\x18 -> (undefined :: Int)))) (\x17 -> (id (undefined :: Int)))) ((\x17 -> ((\x18 -> id) x16)) x16)) (((\x17 -> (\x18 -> x16)) (id (undefined :: Int))) x16))), (((((\x16 -> (\x17 -> (\x18 -> (\x19 -> x18)))) (undefined :: Int)) (id (id (undefined :: Int)))) (((\x16 -> seq) (\x16 -> (\x17 -> (\x18 -> (undefined :: Int))))) id)) (seq (undefined :: Int))), (seq id), (seq id), (seq ((id (id (\x16 -> (seq (undefined :: Int))))) (id (id (id (undefined :: Int)))))), (\x16 -> x16), (\x16 -> x16), (((((\x16 -> ((\x17 -> (\x18 -> (\x19 -> seq))) (\x17 -> x17))) (undefined :: Int)) (\x16 -> (id (undefined :: Int)))) (id (id (undefined :: Int)))) id), ((((\x16 -> (\x17 -> seq)) (\x16 -> (\x17 -> x16))) (undefined :: Int)) ((id (\x16 -> (seq (undefined :: Int)))) (id (undefined :: Int)))), (((((\x16 -> (\x17 -> (\x18 -> seq))) (\x16 -> (\x17 -> (undefined :: Int)))) (seq (undefined :: Int))) (\x16 -> (undefined :: Int))) (\x16 -> (undefined :: Int))), (seq ((\x16 -> (\x17 -> (undefined :: Int))) (undefined :: Int))), (((\x16 -> seq) (id ((\x16 -> (undefined :: Int)) (seq id)))) ((\x16 -> (\x17 -> (undefined :: Int))) ((\x16 -> (id (undefined :: Int))) (undefined :: Int)))), (seq id), (((((\x16 -> (\x17 -> (\x18 -> (\x19 -> (\x20 -> x20))))) (id ((\x16 -> (undefined :: Int)) (undefined :: Int)))) (\x16 -> (undefined :: Int))) (undefined :: Int)) (((\x16 -> id) (undefined :: Int)) (((id (\x16 -> id)) (undefined :: Int)) (undefined :: Int)))), (seq (seq (id (((\x16 -> (\x17 -> (undefined :: Int))) (undefined :: Int)) (undefined :: Int))))), (seq ((((\x16 -> id) (undefined :: Int)) (\x16 -> ((\x17 -> (\x18 -> (undefined :: Int))) (undefined :: Int)))) (undefined :: Int))), (((((\x16 -> (\x17 -> (\x18 -> seq))) (id (undefined :: Int))) ((\x16 -> (undefined :: Int)) (\x16 -> (undefined :: Int)))) (((\x16 -> id) (undefined :: Int)) (undefined :: Int))) (seq (id (undefined :: Int)))), (seq id), ((((\x16 -> (\x17 -> seq)) (undefined :: Int)) (undefined :: Int)) (\x16 -> (undefined :: Int))), (seq ((\x16 -> id) ((\x16 -> (undefined :: Int)) (\x16 -> (id (undefined :: Int)))))), (((\x16 -> (\x17 -> ((\x18 -> (\x19 -> x19)) x16))) (undefined :: Int)) (((id (\x16 -> id)) (undefined :: Int)) (undefined :: Int))), (((\x16 -> seq) (id (id (undefined :: Int)))) (seq ((seq ((\x16 -> (undefined :: Int)) (\x16 -> (undefined :: Int)))) (id (id (undefined :: Int)))))), (((\x16 -> seq) (undefined :: Int)) ((id (id seq)) ((seq (undefined :: Int)) (undefined :: Int)))), (seq ((((\x16 -> ((\x17 -> id) (undefined :: Int))) (\x16 -> (\x17 -> (\x18 -> (undefined :: Int))))) (\x16 -> id)) (undefined :: Int))), (\x16 -> ((seq (\x17 -> (undefined :: Int))) x16)), ((((\x16 -> ((\x17 -> x17) (\x17 -> (\x18 -> (\x19 -> x19))))) (\x16 -> ((\x17 -> (undefined :: Int)) (undefined :: Int)))) (undefined :: Int)) (\x16 -> (undefined :: Int))), (seq id), (((\x16 -> seq) ((\x16 -> (undefined :: Int)) (\x16 -> (undefined :: Int)))) ((id seq) (undefined :: Int))), (\x16 -> (((\x17 -> (\x18 -> x16)) (((\x17 -> (\x18 -> (\x19 -> x16))) (\x17 -> (\x18 -> (\x19 -> x16)))) (\x17 -> ((\x18 -> id) (\x18 -> x16))))) ((\x17 -> x16) (\x17 -> (\x18 -> (undefined :: Int)))))), ((\x16 -> (\x17 -> (((\x18 -> (\x19 -> x18)) ((\x18 -> x17) (\x18 -> x17))) (\x18 -> x17)))) (\x16 -> (id ((\x17 -> (id (undefined :: Int))) (x16 (undefined :: Int)))))), ((\x16 -> (((\x17 -> seq) (undefined :: Int)) (\x17 -> (undefined :: Int)))) (seq ((seq (undefined :: Int)) (undefined :: Int)))), (\x16 -> ((seq (\x17 -> (id (undefined :: Int)))) x16)), (seq (\x16 -> (id ((\x17 -> x16) (\x17 -> (\x18 -> x17)))))), ((((\x16 -> (\x17 -> seq)) ((seq (undefined :: Int)) ((\x16 -> (undefined :: Int)) (undefined :: Int)))) (seq (undefined :: Int))) ((((\x16 -> (\x17 -> seq)) ((\x16 -> (undefined :: Int)) (undefined :: Int))) (\x16 -> (undefined :: Int))) (id (undefined :: Int)))), (((\x16 -> seq) (\x16 -> (id (undefined :: Int)))) ((id seq) (((\x16 -> id) (undefined :: Int)) (undefined :: Int)))), (\x16 -> ((seq (seq (undefined :: Int))) (((\x17 -> (\x18 -> x18)) x16) x16))), (seq id), (\x16 -> ((\x17 -> x16) (undefined :: Int))), (((\x16 -> seq) (undefined :: Int)) ((\x16 -> ((\x17 -> id) (undefined :: Int))) (undefined :: Int))), (seq id), (\x16 -> x16), (seq (\x16 -> x16)), (seq (seq (id ((\x16 -> (undefined :: Int)) (undefined :: Int))))), (\x16 -> ((\x17 -> ((\x18 -> ((\x19 -> x16) (\x19 -> (undefined :: Int)))) x16)) ((\x17 -> (\x18 -> x16)) ((\x17 -> (\x18 -> x16)) (\x17 -> ((\x18 -> x16) x16)))))), (\x16 -> x16), (((\x16 -> (\x17 -> (\x18 -> x18))) ((seq (undefined :: Int)) ((\x16 -> (undefined :: Int)) (undefined :: Int)))) (id ((seq (undefined :: Int)) (undefined :: Int)))), ((\x16 -> (\x17 -> x17)) (\x16 -> (\x17 -> (undefined :: Int)))), (((\x16 -> seq) (\x16 -> ((\x17 -> (\x18 -> x16)) (id (undefined :: Int))))) ((\x16 -> id) id)), ((((((\x16 -> (\x17 -> (\x18 -> (\x19 -> seq)))) (\x16 -> (undefined :: Int))) (undefined :: Int)) (undefined :: Int)) (id (undefined :: Int))) (\x16 -> ((\x17 -> (id (undefined :: Int))) (undefined :: Int)))), ((((\x16 -> (\x17 -> seq)) (undefined :: Int)) (id (undefined :: Int))) (seq (undefined :: Int))), (((\x16 -> (\x17 -> (((\x18 -> seq) (\x18 -> x16)) (\x18 -> (undefined :: Int))))) (undefined :: Int)) (((id (\x16 -> id)) (id (undefined :: Int))) (undefined :: Int))), (((\x16 -> seq) (seq ((\x16 -> (undefined :: Int)) (id (undefined :: Int))))) ((\x16 -> ((\x17 -> (\x18 -> (undefined :: Int))) (id (undefined :: Int)))) ((\x16 -> (\x17 -> (undefined :: Int))) (undefined :: Int)))), (seq ((\x16 -> (\x17 -> (undefined :: Int))) ((\x16 -> (\x17 -> (x17 (\x18 -> x16)))) (undefined :: Int)))), (\x16 -> ((\x17 -> x16) ((\x17 -> (\x18 -> x17)) (undefined :: Int)))), (((\x16 -> seq) (seq id)) id), (seq (seq (id (undefined :: Int)))), ((\x16 -> (seq (seq (id (undefined :: Int))))) (undefined :: Int)), (((\x16 -> (\x17 -> (\x18 -> x18))) ((\x16 -> (\x17 -> (\x18 -> (\x19 -> x19)))) (id (undefined :: Int)))) (((\x16 -> id) ((seq (undefined :: Int)) (undefined :: Int))) ((seq (undefined :: Int)) (undefined :: Int)))), (\x16 -> (((\x17 -> (seq (\x18 -> (undefined :: Int)))) x16) ((\x17 -> x16) ((\x17 -> (\x18 -> (\x19 -> (undefined :: Int)))) (\x17 -> (undefined :: Int)))))), (seq ((\x16 -> (\x17 -> (undefined :: Int))) ((\x16 -> (\x17 -> (\x18 -> (undefined :: Int)))) (id (undefined :: Int))))), (seq id), (((\x16 -> seq) (undefined :: Int)) (seq (undefined :: Int))), (\x16 -> ((seq id) ((seq id) ((\x17 -> x16) x16)))), (((\x16 -> seq) (id (undefined :: Int))) id), (\x16 -> (((\x17 -> (seq id)) (((\x17 -> (\x18 -> (\x19 -> x17))) (undefined :: Int)) (undefined :: Int))) x16)), (\x16 -> ((\x17 -> x16) ((((\x17 -> seq) (\x17 -> x16)) (\x17 -> (undefined :: Int))) x16))), (((\x16 -> ((\x17 -> seq) (undefined :: Int))) (undefined :: Int)) ((id (\x16 -> (\x17 -> (undefined :: Int)))) (undefined :: Int))) ]
QuickChick/Luck
luck/examples-template/ghc-counters/0.hs
mit
11,574
0
24
2,193
8,044
4,712
3,332
126
1
module ParserSpec (tests) where import Protolude import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) import Test.Tasty.QuickCheck as QC import TestUtils (testWithProvider) tests :: TestTree tests = testGroup "Parser" [properties, units] properties :: TestTree properties = testGroup "Properties" [ QC.testProperty "sort == sort . reverse" $ \xs -> sort (xs :: [Int]) == sort (reverse xs) ] units :: TestTree units = testGroup "Units" [ testCase "True is true" $ True @?= True ]
Archimidis/md2html
test/ParserSpec.hs
mit
538
0
12
103
164
95
69
15
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} -- | Various product types. -- module Network.AWS.Wolf.Types.Product where import Data.Aeson.TH import Network.AWS.Wolf.Prelude -- | Conf -- -- SWF and S3 configuration parameters. -- data Conf = Conf { _cTimeout :: Int -- ^ SWF regular timeout. , _cPollTimeout :: Int -- ^ SWF polling timeout. , _cDomain :: Text -- ^ SWF domain. , _cBucket :: Text -- ^ S3 bucket. , _cPrefix :: Text -- ^ S3 prefix. } deriving (Show, Eq) $(makeLenses ''Conf) $(deriveJSON spinalOptions ''Conf) -- | Control -- data Control = Control { _cRunUid :: Text -- ^ Run uid of workflow. } deriving (Show, Eq) $(makeLenses ''Control) $(deriveJSON spinalOptions ''Control) -- | Plan Task -- -- Work task. -- data PlanTask = PlanTask { _ptName :: Text -- ^ Name of task. , _ptVersion :: Text -- ^ Version of task. , _ptQueue :: Text -- ^ Queue for task. , _ptTimeout :: Text -- ^ Timeout for task. } deriving (Show, Eq) $(makeLenses ''PlanTask) $(deriveJSON spinalOptions ''PlanTask) -- | Plan -- -- Group of tasks. -- data Plan = Plan { _pStart :: PlanTask -- ^ Flow task. , _pTasks :: [PlanTask] -- ^ Worker tasks. } deriving (Show, Eq) $(makeLenses ''Plan) $(deriveJSON spinalOptions ''Plan)
mfine/wolf
src/Network/AWS/Wolf/Types/Product.hs
mit
1,352
0
9
326
311
184
127
33
0
module Spec.Comment (spec) where import ClassyPrelude import Test.Hspec import Feature.Comment.Types import Feature.User.Types import Feature.Article.Types import Feature.Auth.Types import qualified Misc.Client as RW import Spec.Common spec :: Spec spec = commentSpec commentSpec :: Spec commentSpec = describe "comments" $ do describe "add comment" $ do it "should require token" $ runClient (RW.addComment "invalidToken" "invalidSlug" "comment") `shouldReturn` Left (RW.ErrUnauthorized $ TokenErrorMalformed "BadCrypto") it "should reject commenting non-existent article" $ do Right user <- registerRandomUser let token = userToken user runClient (RW.addComment token "invalidSlug" "comment") `shouldReturn` Left (RW.ErrApp $ CommentErrorSlugNotFound "invalidSlug") it "should add comment successfully" $ do Right user <- registerRandomUser Right article <- createRandomArticle user [] let token = userToken user let slug = articleSlug article Right comment <- runClient (RW.addComment token slug "comment") runClient (RW.getComments (Just token) slug) `shouldReturn` Right [comment] describe "del comment" $ do it "should require token" $ runClient (RW.delComment "invalidToken" "invalidSlug" 1) `shouldReturn` Left (RW.ErrUnauthorized $ TokenErrorMalformed "BadCrypto") it "should reject deleting comment from non-existent article" $ do Right user <- registerRandomUser let token = userToken user runClient (RW.delComment token "invalidSlug" 1) `shouldReturn` Left (RW.ErrApp $ CommentErrorSlugNotFound "invalidSlug") it "should throw err for not found comment" $ do Right user <- registerRandomUser Right article <- createRandomArticle user [] let token = userToken user let slug = articleSlug article runClient (RW.delComment token slug (-1)) `shouldReturn` Left (RW.ErrApp $ CommentErrorNotFound (-1)) it "should reject deleting comment that is not owned by the user" $ do Right user1 <- registerRandomUser Right user2 <- registerRandomUser Right article <- createRandomArticle user1 [] let token1 = userToken user1 let token2 = userToken user2 let slug = articleSlug article Right comment <- runClient (RW.addComment token2 slug "comment") let cId = commentId comment runClient (RW.delComment token1 slug cId) `shouldReturn` Left (RW.ErrApp $ CommentErrorNotAllowed cId) it "should del comment successfully" $ do Right user <- registerRandomUser Right article <- createRandomArticle user [] let token = userToken user let slug = articleSlug article Right comment <- runClient (RW.addComment token slug "comment") let cId = commentId comment runClient (RW.delComment token slug cId) runClient (RW.getComments (Just token) slug) `shouldReturn` Right [] describe "get comments" $ it "should throw error for not found slug" $ runClient (RW.getComments Nothing "invalidSlug") `shouldReturn` Left (RW.ErrApp $ CommentErrorSlugNotFound "invalidSlug")
eckyputrady/haskell-scotty-realworld-example-app
test/Spec/Comment.hs
mit
3,321
0
20
834
926
429
497
72
1
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Util -- Copyright : HASLAb team, University of Minho -- License : MIT -- -- Maintainer : Victor Miraldo <[email protected]> -- Stability : provisional -- Portability : portable -- --General coding utilities. Mostly syntax-sugar for the programmer, you shouldn't --need to read this. ---------------------------------------------------------------------------- module MMM.Util.Util( module Control.Monad , module Control.Monad.Error , module Control.Monad.State , module Control.Monad.Writer , module Control.Applicative , MyMonad , E, errNoSuchVar1, errNoSuchVar , bug , author ) where import Control.Monad import Control.Monad.Error hiding (getAll) import Control.Monad.State import Control.Monad.Writer import Control.Applicative import MMM.OOP.Language.Syntax(IsVar(..)) ------------------------------------------------------------------------------- -- * Usefull Classes; abreviation for contexts only. class (Monad m, Functor m, Applicative m) => MyMonad m where instance MyMonad IO where -------------------------------------------------------------------------------- -- * Error Handling data Err = ErrLoc (Int, String) String | ErrNoLoc String instance Show Err where show (ErrNoLoc s) = s show (ErrLoc (l, f) s) = f ++ ":" ++ show l ++ ":" ++ s instance Error Err where strMsg = ErrNoLoc type E = ErrorT Err instance (MyMonad m) => MyMonad (E m) where errNoSuchVar1 :: (MyMonad m, IsVar id) => id -> E m a errNoSuchVar1 v = throwError $ ErrLoc (varLoc v) $ "Undefined variable: " ++ varName v errNoSuchVar :: (MyMonad m, IsVar id) => [id] -> E m a errNoSuchVar vs = throwError $ ErrLoc (varLoc $ head vs) $ "Undefined variable: " ++ concatMap ((++ ", ") . varName) vs -------------------------------------------------------------------------------- -- * General Utilities author :: String author = "Victor C. Miraldo <[email protected]>" bug :: (Show e) => e -> String -> a bug e s = error $ "Smells like it's burning... Sorry, my bad. Please report this bug to " ++ author ++ "\n[ERROR DESC]: " ++ s ++ "\n[TECH INFO ]: " ++ show e ++ "\n\n"
VictorCMiraldo/mmm
MMM/Util/Util.hs
mit
2,365
0
11
435
514
293
221
-1
-1
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} import Data.Monoid (mappend) import Hakyll import Text.Pandoc crunchWithCtx ctx = do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/page.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx >>= relativizeUrls -------------------------------------------------------------------------------- main :: IO () main = hakyll $ do match "static/*/*" $ do route idRoute compile copyFileCompiler match (fromList tops) $ crunchWithCtx siteCtx match "lectures/*" $ crunchWithCtx postCtx match "assignments/*" $ crunchWithCtx postCtx match "templates/*" $ compile templateCompiler {- create ["archive.html"] $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" let archiveCtx = listField "posts" postCtx (return posts) `mappend` constField "title" "Archives" `mappend` siteCtx makeItem "" >>= loadAndApplyTemplate "templates/archive.html" archiveCtx >>= loadAndApplyTemplate "templates/default.html" archiveCtx >>= relativizeUrls match "orig-index.html" $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" let indexCtx = listField "posts" postCtx (return posts) `mappend` constField "title" "Home" `mappend` siteCtx getResourceBody >>= applyAsTemplate indexCtx >>= loadAndApplyTemplate "templates/default.html" indexCtx >>= relativizeUrls -} -------------------------------------------------------------------------------- postCtx :: Context String postCtx = dateField "date" "%B %e, %Y" `mappend` -- constField "headerImg" "Eiffel.jpg" `mappend` siteCtx siteCtx :: Context String siteCtx = constField "baseurl" "https://ucsd-progsys.github.io/131-web" `mappend` constField "site_name" "cse131" `mappend` constField "site_description" "UCSD CSE 131" `mappend` -- constField "instagram_username" "ranjitjhala" `mappend` constField "site_username" "Ranjit Jhala" `mappend` constField "twitter_username" "ranjitjhala" `mappend` constField "github_username" "ucsd-progsys/131-web" `mappend` constField "google_username" "[email protected]" `mappend` constField "google_userid" "u/0/106612421534244742464" `mappend` constField "piazza_classid" "ucsd/fall2018/cse131/home" `mappend` defaultContext tops = [ "index.md" , "grades.md" , "lectures.md" , "links.md" , "assignments.md" , "calendar.md" , "contact.md" ]
ucsd-progsys/131-web
site.hs
mit
3,096
0
14
927
334
171
163
42
1
module Sets.Multiset where import Notes import Sets.Basics.Terms import Sets.Multiset.Macro import Sets.Multiset.Terms multisetS :: Note multisetS = section "Multisets" $ do multisetDefinition multisetNotation exneeded multisetDifferenceDefinition multisetUnionDefinition multisetDefinition :: Note multisetDefinition = de $ do lab multisetDefinitionLabel s ["A", multiset', "is a", set, "of", elements, "each imbued with a", multiplicity'] multisetNotation :: Note multisetNotation = nte $ do s ["Instead of stating an explicit", multiplicity, "we may also simply write", elements, "multiple times in the same set notation"] multisetDifferenceDefinition :: Note multisetDifferenceDefinition = de $ do let a = "A" b = "B" s [the, multiset, "union", "of two", multisets, m a, and, m b, "is defined as the", multiset, m $ a `msetun` b, "where the", elements, "are in the union of the underlying", sets, "and the", multiplicities, "are the sum of", multiplicities, "in the", multisets, m a, and, m b] multisetUnionDefinition :: Note multisetUnionDefinition = de $ do let a = "A" b = "B" s [the, multiset, "difference", "of two", multisets, m a, and, m b, "is defined as the", multiset, m $ a `msetdiff` b, "where the", elements, "are in the difference of the underlying", sets, "and the", multiplicities, "are the difference of", multiplicities, "in the", multisets, m a, and, m b]
NorfairKing/the-notes
src/Sets/Multiset.hs
gpl-2.0
1,492
0
11
317
400
230
170
29
1
-- -- Copyright (c) 2012 Citrix Systems, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- {-# LANGUAGE GeneralizedNewtypeDeriving, PatternGuards, MultiParamTypeClasses, ScopedTypeVariables #-} module Import ( importAppliance , ImportOptions (..) ) where import Control.Applicative import Control.Monad.Error import Control.Monad.Reader import Control.Concurrent import Data.String import Data.Maybe import Data.Time import qualified Control.Exception as E import qualified Data.Text.Lazy as T import qualified Data.ByteString.UTF8 as UTF8 import System.FilePath import System.Directory import System.IO import qualified Network.DBus as DBus import Text.Printf import Tools.FreezeIOM import Tools.Db import Tools.Process import Tools.IfM import Tools.Misc import Vm.ProductProperty import Util import Core.Types import Appliance import AppInventory import VirtualSystem import Rpc.Core import Rpc.Autogen.XenmgrClient import Rpc.Autogen.XenmgrVmClient import Rpc.Autogen.VmNicClient import Rpc.Autogen.VmDiskClient import Errors import Import.Types import Import.Monad import Import.Files import Import.Images newtype VmPath = VmPath String newtype NicPath = NicPath String newtype DiskPath = DiskPath String inform :: MonadIO m => String -> m () inform = liftIO . hPutStrLn stderr xenmgrObj = "/" xenmgrSrv = "com.citrix.xenclient.xenmgr" withXenmgr f = f xenmgrSrv xenmgrObj withXenmgrVm (VmPath vm) f = f xenmgrSrv vm withVmNic (NicPath nic) f = f xenmgrSrv nic withVmDisk (DiskPath d) f = f xenmgrSrv d importAppliance :: FilePath -> ImportOptions -> App -> IO () importAppliance ovfroot options app = do rpc_context <- rpcConnectTo SystemBus state <- newMVar (ImportState []) let imp_context = ImportContext ovfroot options (appID app) state errors =<< runImportRpc rpc_context ( runImport imp_context (doImport app) ) where errors (Left x) = error (show x) errors _ = return () onlyImages :: Import Bool onlyImages = do mode <- importMode <$> options case mode of ImportImagesOnly _ -> return True _ -> return False unregisterAppliance' appid = whenM (not <$> onlyImages) (unregisterAppliance appid True True) -- use temporary id, folders etc while installing, relink at last moment installApplianceWithTemporaryStructure :: Import a -> Import () -> Import a installApplianceWithTemporaryStructure install finalise = go =<< app where go id@(AppID name version) = applianceTempFolder >>= \temp -> local context' (body temp) where context' c = c { importAppID = temp_id } temp_id = AppID ("_temp_" ++ name) version body tempFolder = do -- cleanup the files temp folder liftIO $ rmDirRec tempFolder -- also erase it on errors/finish finallyCME (liftIO (rmDirRec tempFolder)) $ do whenM (not <$> onlyImages) $ do dbRm (appDBPath temp_id) dbWrite (appDBPath temp_id ++ "/temp") True dbWrite (appDBPath temp_id ++ "/version") version changeApplianceState temp_id AppInstalling rv <- (do r <- install liftIO $ finalRelinkFiles tempFolder -- custom finalisation code (i.e. remove previous appliance on upgrade etc) finalise return r) `catchError` (\e -> unregisterAppliance' temp_id >> throwError e) whenM (not <$> onlyImages) $ do changeApplianceState temp_id AppInstalled -- relink db dbMv (appDBPath temp_id) (appDBPath id) dbRm (appDBPath id ++ "/temp") return rv finalRelinkFiles :: FilePath -> IO () finalRelinkFiles tempFolder = do -- final relink of files from temp folder into destination folders inform "moving files.." forEveryDirFileRec tempFolder (relinkTest tempFolder) forEveryDirFileRec tempFolder (relinkFile tempFolder) relinkTest :: FilePath -> FilePath -> IO () relinkTest tempFolder f = do let dst = drop (length tempFolder) f exist <- doesFileExist dst when exist $ error ("file " ++ dst ++ " already exists and would be overwritten, aborting!") relinkFile :: FilePath -> FilePath -> IO () relinkFile tempFolder f = do let dst = drop (length tempFolder) f inform $ "move " ++ f ++ " -> " ++ dst createDirectoryIfMissing True (takeDirectory dst) -- rename doesn't work cross device (i.e. /storage to /config), so have to use mv mvFile f dst doImport :: App -> Import () doImport applianceData = removeFilesOnError $ do preImportVerification applianceData appid@(AppID name _) <- app whenM (not <$> onlyImages) (sanitiseUpgrades =<< findAppliance name) installApplianceWithTemporaryStructure goImport finalise where goImport = goImportWithMode =<< (importMode <$> options) goImportWithMode ImportAll = importDiskImages applianceData >>= importApp goImportWithMode (ImportImagesOnly file) = liftIO . writeDIM file =<< importDiskImages applianceData goImportWithMode (ImportWithExistingImages file) = importApp =<< liftIO (readDIM file) importApp images = do let systems = contentVirtualSystems $ appContent applianceData vmpaths <- mapM (importVirtualSystem images) systems mapM_ (\(p, sys) -> installVirtualSystem p sys) (zip vmpaths systems) removeFilesOnError f = f `catchError` (\e -> removeFiles >> throwError e) removeFiles = mapM_ remove =<< addedFiles where remove f = liftIO $ whenM (doesFileExist f) (removeFile f) finalise = do -- remove original appliance if it's there unregisterAppliance' (appID applianceData) sanitiseUpgrades Nothing = return () sanitiseUpgrades (Just (AppID appname currentVer)) = do AppID _ newVer <- app opts <- options case () of _ | newVer > currentVer, not (allowUpgrades opts) -> error $ msg "lower version" "--upgrade" | newVer < currentVer, not (allowDowngrades opts) -> error $ msg "higher version" "--downgrade" | newVer == currentVer, not (allowReinstall opts) -> error $ msg "same version" "--reinstall" | otherwise -> return () where msg ver opt = printf "Appliance '%s' already exists with %s. Please specify %s to override" appname ver opt toVmPath :: ObjectPath -> VmPath toVmPath p = VmPath (T.unpack $ strObjectPath p) preImportVerification :: App -> Import () preImportVerification app = do whenM (not <$> onlyImages) $ do vms <- map toVmPath <$> withXenmgr comCitrixXenclientXenmgrListVms uuids <- mapM (\vm -> fromString <$> withXenmgrVm vm comCitrixXenclientXenmgrVmGetUuid) vms mapM_ (verifyUuid uuids) systems where verifyUuid existing sys | Just uuid <- vsUuid sys, uuid `elem` existing = throwError (VmAlreadyExists uuid) | otherwise = return () systems = contentVirtualSystems $ appContent app importVirtualSystem :: DIM -> VirtualSystem -> Import VmPath importVirtualSystem images sys = do vm <- mkVmPath <$> (case vsUuid sys of Nothing -> withXenmgr comCitrixXenclientXenmgrCreateVmWithTemplate template_id Just uuid -> withXenmgr comCitrixXenclientXenmgrCreateVmWithTemplateAndUuid template_id (uuidStr uuid)) uuid <- fromString <$> withXenmgrVm vm comCitrixXenclientXenmgrVmGetUuid join (registerApplianceOwnedVm <$> app <*> pure uuid <*> pure (vsID sys)) withXenmgrVm vm comCitrixXenclientXenmgrVmSetName (vsName sys) withXenmgrVm vm comCitrixXenclientXenmgrVmSetMemory (fromIntegral $ vsMemory sys) withXenmgrVm vm comCitrixXenclientXenmgrVmSetVcpus (fromIntegral $ vsVcpus sys) withXenmgrVm vm comCitrixXenclientXenmgrVmSetOvfTransportIso (vsTransportIso sys) mapM_ (importDBEntry vm uuid) $ vsDB sys mapM_ (importDomStoreFile uuid) $ vsDomStoreFiles sys mapM_ (importEnvFile uuid) $ vsEnvFiles sys mapM (withXenmgrVm vm comCitrixXenclientXenmgrVmAddArgoFirewallRule) (vsArgoFirewall sys) -- FIXME: change to use xenmgr api when its there when (not $ null $ vsRpcFirewall sys) $ dbWrite ("/vm/" ++ show uuid ++ "/rpc-firewall-rules") (vsRpcFirewall sys) mapM_ (importPtRule vm) $ vsPciPt sys mapM_ (importProductProperty vm) $ vsProductProperties sys withXenmgrVm vm setProperties (vsPropertyOverrides sys) -- import disks/nics after property set (since behavior can be different depending on props) mapM_ (importNIC vm) $ vsNICs sys mapM_ (importDiskDefinition images vm) $ vsDisks sys return vm where VirtualSystemID vs_id = vsID sys TemplateID template_id = fromMaybe default_template_id (vsTemplate sys) default_template_id = TemplateID "new-vm-empty" installVirtualSystem :: VmPath -> VirtualSystem -> Import () installVirtualSystem vm sys | Just d <- vsInstallBootStopDelay sys = install d | otherwise = return () where install :: Int -> Import () install timeout = do t0 <- liftIO getCurrentTime let t1 = addUTCTime (realToFrac timeout) t0 runInstall t1 timeout --withTimeout timeout (throwError $ VmInstallTimeout (show $ vsID sys)) runInstall runInstall tmax timeout = do inform $ "starting VM " ++ (show $ vsID sys) ++ " to complete its install process..." withXenmgrVm vm comCitrixXenclientXenmgrVmStart waitShutdown tmax timeout expired timeout = do inform $ "vm installation timeout expired, stopping it & failing appliance install" withXenmgrVm vm comCitrixXenclientXenmgrVmDestroy throwError $ VmInstallTimeout (show $ vsID sys) timeout waitShutdown tmax timeout = do t <- liftIO getCurrentTime when (t > tmax) $ expired timeout state <- withXenmgrVm vm comCitrixXenclientXenmgrVmGetState if state == eVM_STATE_STOPPED then return () else liftIO (threadDelay (5 * 10^6) >> hPutChar stderr '.') >> waitShutdown tmax timeout importProductProperty :: VmPath -> ProductProperty -> Import () importProductProperty vm pp = do uuid <- fromString <$> withXenmgrVm vm comCitrixXenclientXenmgrVmGetUuid vmPPUpdate uuid pp importDBEntry :: VmPath -> Uuid -> DBEntry -> Import () importDBEntry vm uuid e = do let key = prefix ++ "/" ++ sanitise (dbePath e) prefix = case dbeSection e of VmSection -> "/vm/" ++ show uuid DomStoreSection -> "/dom-store/" ++ show uuid dbWrite key (dbeValue e) where -- make sure its relative sanitise = dropWhile (== '/') importNIC :: VmPath -> NIC -> Import () importNIC vm nic = do nicP <- mkNicPath <$> withXenmgrVm vm comCitrixXenclientXenmgrVmAddNic when (not . null $ nicNetwork nic) $ withVmNic nicP comCitrixXenclientVmnicSetNetwork (nicNetwork nic) withVmNic nicP comCitrixXenclientVmnicSetEnabled (nicEnabled nic) withVmNic nicP setProperties (nicPropertyOverrides nic) importPtRule :: VmPath -> PtRule -> Import () importPtRule vm (PtMatchID cls vendor dev) = let s Nothing = "any" s (Just x) = show x in withXenmgrVm vm comCitrixXenclientXenmgrVmPciAddPtRule (s cls) (s vendor) (s dev) importPtRule vm (PtMatchBDF bdf) = withXenmgrVm vm comCitrixXenclientXenmgrVmPciAddPtRuleBdf bdf appSystems = contentVirtualSystems . appContent registerDiskCryptoKeys :: DIM -> Disk -> Import () registerDiskCryptoKeys dim disk = case keyFile of Nothing -> return () Just key -> app >>= \appid -> registerApplianceOwnedFile appid key -- to clean the key up on appliance uninstall where keyFile = getDiskImportedKeyPath disk dim importDiskDefinition :: DIM -> VmPath -> Disk -> Import () importDiskDefinition dim vm disk = registerDiskCryptoKeys dim disk >> setupDiskFromFile hostFile where hostFile = fromMaybe "" (getDiskImportedPhysPath disk dim) setupDiskFromFile :: FilePath -> Import () setupDiskFromFile p = do diskP <- mkDiskPath <$> withXenmgrVm vm comCitrixXenclientXenmgrVmAddDisk let DiskPath diskPathStr = diskP appid <- app registerApplianceVmDisk appid disk diskPathStr withVmDisk diskP comCitrixXenclientVmdiskSetMode accessMode if (not $ diskIsCdrom disk) then do withVmDisk diskP comCitrixXenclientVmdiskAttachVhd p else do withVmDisk diskP comCitrixXenclientVmdiskSetPhysType "file" withVmDisk diskP comCitrixXenclientVmdiskSetDevtype "cdrom" withVmDisk diskP comCitrixXenclientVmdiskSetPhysPath p withVmDisk diskP comCitrixXenclientVmdiskSetShared True withVmDisk diskP comCitrixXenclientVmdiskSetEnabled (diskEnabled disk) withVmDisk diskP setProperties (diskPropertyOverrides disk) where accessMode = case diskAccess disk of DiskAccessRead -> "r" DiskAccessWrite -> "w" DiskAccessReadWrite -> "w" setProperties :: String -> String -> [DBusProperty] -> Import () setProperties srv path = mapM_ (setProperty srv path) setProperty :: String -> String -> DBusProperty -> Import () setProperty srv path p = rpcCallOnce call >> return () where call = RpcCall { callDest = fromString srv , callPath = fromString path , callInterfaceT = fromString "org.freedesktop.DBus.Properties" , callMemberT = fromString "Set" , callArgs = [ str (dbusPropertyInterface p) , str (dbusPropertyName p) , DBus.DBusVariant (dbusPropertyValue p) ] } str = DBus.DBusString . DBus.PackedString . UTF8.fromString mkVmPath = VmPath . pathStr mkNicPath = NicPath . pathStr mkDiskPath = DiskPath . pathStr pathStr = T.unpack . strObjectPath
OpenXT/manager
apptool/Import.hs
gpl-2.0
14,560
0
20
3,322
3,758
1,819
1,939
268
4
-- | standalone aufgabenconfig, -- damit jeder mal tutor spielen kann module Main where import Gateway.CGI import Inter.Evaluate import Inter.Make import Inter.Motd import Inter.Bank import Inter.Store import Inter.Login import Inter.Logged import Inter.Tutor import Inter.Student import qualified Control.Aufgabe.DB import qualified Inter.Param as P import qualified Inter.Statistik import Gateway.Help import Autolib.Multilingual ( Language (..), specialize ) import Autolib.Set import qualified Autolib.Output import qualified Autolib.Output as O import qualified Network.CGI import Control.Types ( toString, fromCGI, Name, Typ , Remark, HiLo (..), Status (..) , Oks (..), Nos (..), Time , Wert (..), MNr, SNr, VNr, ANr, UNr , TimeStatus (..) ) import qualified Control.Types import qualified Inter.Collector import Challenger.Partial import Inter.Types import Inter.Common import Control.Student.CGI import Control.Vorlesung.DB import qualified Control.Student.DB import qualified Control.Punkt import qualified Control.Stud_Aufg.DB import qualified Control.Aufgabe as A import qualified Control.Stud_Aufg as SA import qualified Control.Student as S import qualified Control.Vorlesung as V import qualified Control.Gruppe as G import qualified Control.Stud_Grp as SG import qualified Control.Schule as U import Control.Types ( VNr (..) ) import Autolib.Reporter.Type hiding ( wrap, initial ) import Autolib.ToDoc import qualified Autolib.Output as O import Autolib.Reader import Autolib.Util.Sort import Autolib.FiniteMap import qualified Util.Datei as D import Debug import qualified Local import System.Random import System.Directory import Data.Typeable import Data.Maybe import Data.Tree import Data.List ( partition ) import Control.Monad import qualified Text.XHtml import qualified Autolib.Multilingual as M import qualified Autolib.Multilingual.Html as H import Inter.DateTime ( defaults ) my_name = "Trial.cgi" main :: IO () main = Gateway.CGI.execute ( my_name ) $ do wrap $ do mtopic <- look "topic" case mtopic of Just topic -> fixed_topic topic Nothing -> do mproblem <- look "problem" case mproblem of Just problem -> fixed_problem problem Nothing -> free_choice free_choice = do selektor con <- io $ Inter.Motd.contents html con hr btabled :: Monad m => Form m a -> Form m a btabled = bracketed btable rowed :: Monad m => Form m a -> Form m a rowed = bracketed row mutexed :: ( Typeable a, Monad m ) => Form m () -> Form m a mutexed action = do begin ; action ; end bracketed b action = do open b; x <- action ; close ; return x selektor = do hr h2 "(Tutor) Aufgabe auswählen und konfigurieren" hr let tmk = Inter.Collector.tmakers action <- btabled $ click_choice "Auswahl..." [ ( "nach Vorlesungen", vor tmk ) , ( "nach Themen" , aufgaben tmk ) ] action dummy dummy = ( S.Student { }, VNr 42, True ) vor tmk pack = do schulen <- io $ U.get schule <- btabled $ click_choice "Hochschule" $ do u <- schulen return ( toString $ U.name u , u ) vors <- io $ V.get_at_school $ U.unr schule vor <- btabled $ click_choice "Vorlesung" $ do v <- vors return ( toString $ V.name v , v ) aufgaben <- io $ A.get ( Just $ V.vnr vor ) ( conf, auf ) <- mutexed $ btabled $ do rowed $ do plain "Aufgabe" ; plain "Typ" sequence_ $ do auf <- filter ( \ a -> Early /= A.timeStatus a ) aufgaben return $ rowed $ do plain $ toString $ A.name auf plain $ toString $ A.typ auf click ( "solve" , ( False, auf ) ) click ( "config and solve", ( True, auf ) ) common_aufgaben tmk pack ( Just auf ) conf fixed_problem problem = do [ auf ] <- io $ Control.Aufgabe.DB.get_this $ fromCGI problem open btable -- ? common_aufgaben Inter.Collector.tmakers dummy ( Just auf ) False fixed_topic topic = do let mks = do Right mk <- flatten Inter.Collector.tmakers ; return mk mk : _ <- return $ do mk @ ( Make _ doc _ _ _ ) <- mks guard $ doc == topic return mk open btable -- ? common_aufgaben_trailer dummy Nothing True mks mk False ----------------------------------------------------------------------------- aufgaben tmk pack = do common_aufgaben tmk pack Nothing True common_aufgaben tmk svt @ ( stud, vnr, tutor ) mauf conf = do -- plain $ "common_aufgaben.conf: " ++ show conf let mks = do Right mk <- flatten tmk ; return mk ( mk, type_click ) <- find_mk tmk conf mauf -- if the user chose a new type, ignore any predetermined configuration let conf' = conf || type_click mauf' = if type_click then Nothing else mauf common_aufgaben_trailer svt mauf' conf' mks mk type_click common_aufgaben_trailer ( stud, vnr, tutor ) mauf conf mks mk type_click = do -- plain $ "common_aufgaben_trailer.conf: " ++ show conf -- plain $ "common_aufgaben_trailer.type_click: " ++ show type_click auf' <- case ( mauf, conf ) of ( Just auf, False ) -> return auf _ -> edit_aufgabe_extra mks mk Nothing vnr Nothing type_click ( \ a -> Early /= A.timeStatus a ) stud' <- get_stud tutor stud hr h2 "(Student) Aufgabe lösen" hr ( minst :: Maybe H.Html, cs, res, com :: Maybe H.Html ) <- solution vnr Nothing stud' mk auf' scores <- scores_link hr plain "Link zu diesem Aufgabentyp:" let target = case mk of Make _ doc _ _ _ -> "Trial.cgi?topic=" ++ Network.CGI.urlEncode doc html $ specialize Autolib.Multilingual.DE $ ( O.render $ O.Link $ target :: H.Html ) hr case mauf of Nothing -> return () Just auf -> do plain "Link zu dieser Aufgabeninstanz:" let problem = "Trial.cgi?problem=" ++ Control.Types.toString ( A.anr auf' ) html $ specialize Autolib.Multilingual.DE $ ( O.render $ O.Link $ problem :: H.Html ) footer scores
Erdwolf/autotool-bonn
trial/src/Inter/Trial.hs
gpl-2.0
6,054
25
20
1,454
1,792
978
814
-1
-1
module Tweet.Test.Bayesian ( testWordFreq , testRelativeFreq , testSpamProb , testCombinedProbs , testMostInteresting , testSpamScore ) where import qualified Data.Map as Map import qualified Data.List as List import Test.QuickCheck import Test.HUnit import Tweet.Bayesian import Tweet.Types between :: Double -> Double -> Double -> Bool between a b x = a <= x && x <= b prop_sumWords :: [Word] -> Bool prop_sumWords w = sumValues == length w where sumValues = Map.foldr (+) 0 . runDict . wordFreqs $ w prop_distinctWords :: [Word] -> Bool prop_distinctWords w = distinctWords <= length w where distinctWords = Map.size . runDict . wordFreqs $ w prop_fromTweet :: Tweet -> Bool prop_fromTweet t = prop_sumWords w && prop_distinctWords w where w = extractWords $ text t testWordFreq :: IO () testWordFreq = do quickCheck prop_sumWords quickCheck prop_distinctWords quickCheck prop_fromTweet prop_sumFreqs :: Dict -> Bool prop_sumFreqs d = (1.0 - sumKeys) < 1e-6 where keys' = Map.keys . runDict relativeFreq' w = relativeFreq w d sumKeys = abs $ sum . map relativeFreq' . keys' $ d prop_rfZeroOne :: Dict -> Bool prop_rfZeroOne d = all betweenZeroOne . map relativeFreq' . keys' $ d where keys' = Map.keys . runDict betweenZeroOne x = x > 0 && x <= 1 relativeFreq' w = relativeFreq w d testRelativeFreq :: IO () testRelativeFreq = do quickCheck prop_sumFreqs quickCheck prop_rfZeroOne prop_98pc :: Stats -> Bool prop_98pc stats = all (between 0.01 0.99) spamProbs where badWords = Map.keys . runDict . badCounts $ stats spamProbs = map (\w -> runProb $ spamProb w stats) badWords testSpamProb :: IO () testSpamProb = quickCheck prop_98pc prop_cpZeroOne :: [Prob] -> Bool prop_cpZeroOne = between 0 1 . runProb . combinedProb testCombinedProbs :: IO () testCombinedProbs = quickCheck prop_cpZeroOne prop_descOrder :: Stats -> Bool prop_descOrder stats = List.sort res == reverse res where res = map snd $ mostInteresting 5 randWords stats randWords = Map.keys .runDict . badCounts $ stats testMostInteresting :: IO () testMostInteresting = quickCheck prop_descOrder testSpamScore :: Test testSpamScore = test [ "Manually calculated case" ~: combProb ~=? actualCP, "Manually calc'd most int" ~: mstInt ~=? actualMI, "Manually calc'd pSpams" ~: pSpams ~=? actualPS, "Manually calc'd gdRFs" ~: gdRelFreqs ~=? actualGRF, "Manually calc'd bdRFs" ~: bdRelFreqs ~=? actualBRF ] where rawGd = [("you",5),("eat",4),("love",8),("hate",8),("sweet",3),("hello",1),("everything",2),("suck",4),("lol",1),("bad",3),("fuck",1)] rawBd = [("free",4),("win",8),("click",9),("here",4),("you",5),("code",4),("sexy",6),("hot",6),("suck",3),("everything",1),("bad",2)] gd = Dict { runDict = Map.fromList [(Word w,i) | (w,i) <- rawGd] } bd = Dict { runDict = Map.fromList [(Word w,i) | (w,i) <- rawBd] } stats = Stats gd bd -- these words appear with higher relative frequencies in good than bad ws = map Word ["you", "suck", "bad", "everything", "java"] {- - Human calculations gdSum = 39 bdSum = 52 -} gdRelFreqs = [5/40, 4/40, 3/40, 2/40, 0/40] :: [Double] bdRelFreqs = [5/52, 3/52, 2/52, 1/52, 0/52] :: [Double] pSpams = [Prob x | x <- [0.4347826086956522, 0.3658536585365854, 0.33898305084745767, 0.2777777777777778, 0.01]] -- as it happens, the interestingness ordering is just reverse order mstInt = reverse $ zip ws pSpams {- - Human calculations prod pSpams = 1.4978042190149247e-4 prod 1-pSpams = 0.16940399374516954 -} combProb = Prob 8.83380052359703e-4 actualCP = spamScore ws stats actualMI = mostInteresting 5 ws stats actualPS = [spamProb w stats | w <- ws] actualGRF = [relativeFreq w gd | w <- ws] actualBRF = [relativeFreq w bd | w <- ws]
cbowdon/TweetFilter
Tweet/Test/Bayesian.hs
gpl-3.0
4,259
1
13
1,170
1,337
739
598
81
1
{- Copyright (C) 2015 Michael Dunsmuir 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/>. -} import Control.Monad import Control.Concurrent import Control.Concurrent.MVar import Control.Concurrent.Chan import Network.Socket import Hat.Message import Hat.Protocol main = do sock <- socket AF_INET Stream 0 setSocketOption sock ReuseAddr 1 bindSocket sock (SockAddrInet 4567 iNADDR_ANY) listen sock 3 relayChan <- newChan :: IO (Chan Message) acceptLoop sock relayChan acceptLoop :: Socket -> Chan Message -> IO () acceptLoop sock relayChan = forever $ do (sock, _) <- accept sock newClientThread sock relayChan newClientThread :: Socket -> Chan Message -> IO () newClientThread sock relayChan = do forkIO $ fromClientThread sock relayChan outChan <- dupChan relayChan forkFinally (toClientThread sock outChan) $ \result -> do case result of Left exc -> return () -- putStrLn $ show exc Right _ -> return () sClose sock return () fromClientThread :: Socket -> Chan Message -> IO () fromClientThread sock relayChan = do eitherMessage <- recvProtocol sock case eitherMessage of Left err -> return () --putStrLn err Right (MessageRequest msg) -> do writeChan relayChan msg fromClientThread sock relayChan toClientThread :: Socket -> Chan Message -> IO () toClientThread sock inChan = forever $ do msg <- readChan inChan sendProtocol sock $ MessageRequest msg
mdunsmuir/hat
src/Server.hs
gpl-3.0
2,043
1
15
424
459
211
248
41
2
module Reader ( drg -- reads a grammar from a string -- returns corresponding deterministic automaton , trg -- non- ) where import ExpParse (pline) import FiniteMap import Options import Defaults import Ids import IdStack import Gen import FA import FAtypes import FAdet import Gram2FA import Syntax import Semantik -------------------------------------------------------------------- trg :: String -> TNFA Int trg cs = let (Just x, _) = pline (opts0, genpid) cs g = docomp opts0 genenv x in g drg = t2d opts0 . trg
jwaldmann/rx
src/Reader.hs
gpl-3.0
567
2
10
133
138
80
58
23
1
{- | Module : Web.Handler Description : Application-specific handler functions. Copyright : (c) 2011 Cedric Staub, 2012 Benedikt Schmidt License : GPL-3 Maintainer : Cedric Staub <[email protected]> Stability : experimental Portability : non-portable -} {-# LANGUAGE OverloadedStrings, QuasiQuotes, TypeFamilies, FlexibleContexts, RankNTypes, TemplateHaskell, CPP #-} module Web.Handler ( getOverviewR , getOverviewDiffR , getRootR , postRootR , getTheorySourceR , getTheorySourceDiffR , getTheoryMessageDeductionR , getTheoryMessageDeductionDiffR , getTheoryVariantsR , getTheoryVariantsDiffR , getTheoryPathMR , getTheoryPathDiffMR -- , getTheoryPathDR , getTheoryGraphR , getTheoryGraphDiffR , getTheoryMirrorDiffR , getAutoProverR , getAutoDiffProverR , getAutoProverDiffR , getDeleteStepR , getDeleteStepDiffR , getKillThreadR , getNextTheoryPathR , getNextTheoryPathDiffR , getPrevTheoryPathR , getPrevTheoryPathDiffR , getSaveTheoryR , getDownloadTheoryR , getDownloadTheoryDiffR -- , getEditTheoryR -- , postEditTheoryR -- , getEditPathR -- , postEditPathR , getUnloadTheoryR , getUnloadTheoryDiffR -- , getThreadsR ) where import Theory ( ClosedTheory, ClosedDiffTheory, -- EitherClosedTheory, Side, thyName, diffThyName, removeLemma, removeLemmaDiff, removeDiffLemma, openTheory, sorryProver, runAutoProver, sorryDiffProver, runAutoDiffProver, prettyClosedTheory, prettyOpenTheory, openDiffTheory, prettyClosedDiffTheory, prettyOpenDiffTheory ) import Theory.Proof (AutoProver(..), SolutionExtractor(..), Prover, DiffProver, apDefaultHeuristic) import Text.PrettyPrint.Html import Theory.Constraint.System.Dot import Theory.Constraint.System.JSON -- for export of constraint system to JSON import Web.Hamlet import Web.Instances () import Web.Settings import Web.Theory import Web.Types import Yesod.Core import Control.Monad.Trans.Resource (runResourceT) import Control.Monad.Trans.Unlift import Data.Label import Data.Maybe import Data.String (fromString) import Data.List (intersperse) -- import Data.Monoid (mconcat) import Data.Conduit as C (runConduit,(.|)) import Data.Conduit.List (consume) import qualified Blaze.ByteString.Builder as B import qualified Data.ByteString.Char8 as BS import qualified Data.Map as M import qualified Data.Text as T import qualified Data.Text.Encoding as T (encodeUtf8, decodeUtf8) import qualified Data.Text.Lazy.Encoding as TLE import qualified Data.Traversable as Tr import Network.HTTP.Types ( urlDecode ) import Control.Applicative import Control.Concurrent import qualified Control.Concurrent.Thread as Thread ( forkIO ) import Control.DeepSeq import Control.Exception.Base import qualified Control.Exception.Lifted as E import Control.Monad import qualified Data.Binary as Bin import Data.Time.LocalTime import System.Directory import Debug.Trace (trace) -- Quasi-quotation syntax changed from GHC 6 to 7, -- so we need this switch in order to support both #if __GLASGOW_HASKELL__ >= 700 #define HAMLET hamlet #else #define HAMLET $hamlet #endif ------------------------------------------------------------------------------ -- Manipulate the state ------------------------------------------------------------------------------ -- | Store theory map in file if option enabled. storeTheory :: WebUI -> EitherTheoryInfo -> TheoryIdx -> IO () storeTheory yesod thy idx = when (autosaveProofstate yesod) $ do let f = workDir yesod++"/"++autosaveSubdir++"/"++show idx++".img" Bin.encodeFile (f++".tmp") thy renameFile (f++".tmp") f -- | Load a theory given an index. getTheory :: TheoryIdx -> Handler (Maybe EitherTheoryInfo) getTheory idx = do yesod <- getYesod liftIO $ withMVar (theoryVar yesod) $ return. M.lookup idx -- | Store a theory, return index. putTheory :: Maybe TheoryInfo -- ^ Index of parent theory -> Maybe TheoryOrigin -- ^ Origin of this theory -> ClosedTheory -- ^ The new closed theory -> Handler TheoryIdx putTheory parent origin thy = do yesod <- getYesod liftIO $ modifyMVar (theoryVar yesod) $ \theories -> do time <- getZonedTime let idx | M.null theories = 1 | otherwise = fst (M.findMax theories) + 1 parentIdx = tiIndex <$> parent parentOrigin = tiOrigin <$> parent newOrigin = parentOrigin <|> origin <|> (Just Interactive) newThy = Trace ( TheoryInfo idx thy time parentIdx False (fromJust newOrigin) (maybe (defaultAutoProver yesod) tiAutoProver parent)) storeTheory yesod newThy idx return (M.insert idx newThy theories, idx) -- | Store a theory, return index. putDiffTheory :: Maybe DiffTheoryInfo -- ^ Index of parent theory -> Maybe TheoryOrigin -- ^ Origin of this theory -> ClosedDiffTheory -- ^ The new closed theory -> Handler TheoryIdx putDiffTheory parent origin thy = do yesod <- getYesod liftIO $ modifyMVar (theoryVar yesod) $ \theories -> do time <- getZonedTime let idx | M.null theories = 1 | otherwise = fst (M.findMax theories) + 1 parentIdx = dtiIndex <$> parent parentOrigin = dtiOrigin <$> parent newOrigin = parentOrigin <|> origin <|> (Just Interactive) newThy = Diff ( DiffTheoryInfo idx thy time parentIdx False (fromJust newOrigin) (maybe (defaultAutoProver yesod) dtiAutoProver parent)) storeTheory yesod newThy idx return (M.insert idx newThy theories, idx) -- | Delete theory. delTheory :: TheoryIdx -> Handler () delTheory idx = do yesod <- getYesod liftIO $ modifyMVar_ (theoryVar yesod) $ \theories -> do let theories' = M.delete idx theories -- FIXME: delete from autosave directory? return theories' -- | Get a map of all stored theories. getTheories :: Handler TheoryMap getTheories = do yesod <- getYesod liftIO $ withMVar (theoryVar yesod) return -- -- | Modify a theory in the map of theories. -- adjTheory :: TheoryIdx -- -> (TheoryInfo -> TheoryInfo) -- -> Handler () -- adjTheory idx f = do -- yesod <- getYesod -- liftIO $ modifyMVar_ (theoryVar yesod) $ \theories -> -- case M.lookup idx theories of -- Just th -> do -- case th of -- Trace thy -> do -- let newThy = f thy -- storeTheory yesod (Trace newThy) idx -- return $ M.insert idx (Trace newThy) theories -- Diff _ -> error "adjTheory: found DiffTheory" -- Nothing -> error "adjTheory: invalid theory index" -- | Modify a theory in the map of theories. adjEitherTheory :: TheoryIdx -> (EitherTheoryInfo -> EitherTheoryInfo) -> Handler () adjEitherTheory idx f = do yesod <- getYesod liftIO $ modifyMVar_ (theoryVar yesod) $ \theories -> case M.lookup idx theories of Just thy -> do let newThy = f thy storeTheory yesod newThy idx return $ M.insert idx newThy theories Nothing -> error "adjEitherTheory: invalid theory index" -- -- | Modify a theory in the map of theories. -- adjDiffTheory :: TheoryIdx -- -> (DiffTheoryInfo -> DiffTheoryInfo) -- -> Handler () -- adjDiffTheory idx f = do -- yesod <- getYesod -- liftIO $ modifyMVar_ (theoryVar yesod) $ \theories -> -- case M.lookup idx theories of -- Just th -> do -- case th of -- Diff thy -> do -- let newThy = f thy -- storeTheory yesod (Diff newThy) idx -- return $ M.insert idx (Diff newThy) theories -- Trace _ -> error "adjTheory: found normal Theory" -- Nothing -> error "adjTheory: invalid theory index" -- | Debug tracing. dtrace :: WebUI -> String -> a -> a dtrace yesod msg | debug yesod = trace msg | otherwise = id -- | Register a thread for killing. putThread :: T.Text -- ^ Request path -> ThreadId -- ^ Thread ID -> Handler () putThread str tid = do yesod <- getYesod liftIO $ dtrace yesod msg $ modifyMVar_ (threadVar yesod) $ return . (M.insert str tid) where msg = "Registering thread: " ++ T.unpack str -- | Unregister a thread for killing. delThread :: T.Text -- ^ Request path -> Handler () delThread str = do yesod <- getYesod liftIO $ dtrace yesod msg $ modifyMVar_ (threadVar yesod) $ return . (M.delete str) where msg = "Deleting thread: " ++ T.unpack str -- | Get a thread for the given request URL. getThread :: T.Text -- ^ Request path -> Handler (Maybe ThreadId) getThread str = do yesod <- getYesod liftIO $ dtrace yesod msg $ withMVar (threadVar yesod) $ return . M.lookup str where msg = "Retrieving thread id of: " ++ T.unpack str {- -- | Get the map of all threads. -- getThreads :: MonadIO m -- => GenericHandler m [T.Text] getThreads = do yesod <- getYesod liftIO $ withMVar (threadVar yesod) (return . M.keys) -} ------------------------------------------------------------------------------ -- Helper functions ------------------------------------------------------------------------------ -- | Print exceptions, if they happen. traceExceptions :: MonadBaseControl IO m => String -> m a -> m a traceExceptions info = E.handle handler where handler :: MonadBaseControl IO m => E.SomeException -> m a handler e = trace (info ++ ": exception `" ++ show e ++ "'") $ E.throwIO e -- | Helper functions for generating JSON reponses. jsonResp :: JsonResponse -> Handler RepJson jsonResp = return . RepJson . toContent . responseToJson responseToJson :: JsonResponse -> Value responseToJson = go where jsonObj key val = object [ key .= val ] go (JsonAlert msg) = jsonObj "alert" $ toJSON msg go (JsonRedirect url) = jsonObj "redirect" $ toJSON url go (JsonHtml title content) = object [ "html" .= contentToJson content , "title" .= title ] contentToJson (ContentBuilder b _) = toJSON $ TLE.decodeUtf8 $ B.toLazyByteString b contentToJson _ = error "Unsupported content format in json response!" -- | Fully evaluate a value in a thread that can be canceled. evalInThread :: NFData a => IO a -> Handler (Either SomeException a) evalInThread io = do renderF <- getUrlRender maybeRoute <- getCurrentRoute case maybeRoute of Just route -> do let key = renderF route (tid, wait) <- liftIO $ Thread.forkIO $ do x <- io evaluate (rnf x) return x putThread key tid res <- liftIO $ wait delThread key return res Nothing -> Right `liftM` liftIO io -- | Evaluate a handler with a given theory specified by the index, -- return notFound if theory does not exist. withTheory :: TheoryIdx -> (TheoryInfo -> Handler a) -> Handler a withTheory idx handler = do maybeThy <- getTheory idx case maybeThy of Just eitherTi -> case eitherTi of Trace ti -> handler ti Diff _ -> notFound Nothing -> notFound -- | Evaluate a handler with a given theory specified by the index, -- return notFound if theory does not exist. withBothTheory :: TheoryIdx -> (TheoryInfo -> Handler a) -> (DiffTheoryInfo -> Handler a) -> Handler a withBothTheory idx handler diffhandler = do maybeThy <- getTheory idx case maybeThy of Just eitherTi -> case eitherTi of Trace ti -> handler ti Diff ti -> diffhandler ti Nothing -> notFound -- | Evaluate a handler with a given theory specified by the index, -- return notFound if theory does not exist. withDiffTheory :: TheoryIdx -> (DiffTheoryInfo -> Handler a) -> Handler a withDiffTheory idx handler = do maybeThy <- getTheory idx case maybeThy of Just eitherTi -> case eitherTi of Trace _ -> notFound Diff ti -> handler ti Nothing -> notFound -- | Evaluate a handler with a given theory specified by the index, -- return notFound if theory does not exist. withEitherTheory :: TheoryIdx -> (EitherTheoryInfo -> Handler a) -> Handler a withEitherTheory idx handler = do maybeThy <- getTheory idx case maybeThy of Just ti -> handler ti Nothing -> notFound {- -- | Run a form and provide a JSON response. -- formHandler :: (HamletValue h, HamletUrl h ~ WebUIRoute, h ~ Widget ()) -- => T.Text -- ^ The form title -- -> Form WebUI WebUI a -- ^ The formlet to run -- -> (Widget () -> Enctype -> Html -> h) -- ^ Template to render form with -- -> (a -> GenericHandler IO RepJson) -- ^ Function to call on success -- -> Handler RepJson formHandler title formlet template success = do -- (result, widget, enctype, nonce) <- runFormPost formlet ((result, widget), enctype) <- runFormPost formlet case result of FormMissing -> do RepHtml content <- ajaxLayout (template widget enctype) jsonResp $ JsonHtml title content FormFailure _ -> jsonResp $ JsonAlert "Missing fields in form. Please fill out all required fields." FormSuccess ret -> lift (success ret) -} -- | Modify a theory, redirect if successful. modifyTheory :: TheoryInfo -- ^ Theory to modify -> (ClosedTheory -> IO (Maybe ClosedTheory)) -- ^ Function to apply -> (ClosedTheory -> TheoryPath) -- ^ Compute the new path -> JsonResponse -- ^ Response on failure -> Handler Value modifyTheory ti f fpath errResponse = do res <- evalInThread (liftIO $ f (tiTheory ti)) case res of Left e -> return (excResponse e) Right Nothing -> return (responseToJson errResponse) Right (Just thy) -> do newThyIdx <- putTheory (Just ti) Nothing thy newUrl <- getUrlRender <*> pure (OverviewR newThyIdx (fpath thy)) return . responseToJson $ JsonRedirect newUrl where excResponse e = responseToJson (JsonAlert $ "Last request failed with exception: " `T.append` (T.pack (show e))) -- | Modify a theory, redirect if successful. modifyDiffTheory :: DiffTheoryInfo -- ^ Theory to modify -> (ClosedDiffTheory -> IO (Maybe ClosedDiffTheory)) -- ^ Function to apply -> (ClosedDiffTheory -> DiffTheoryPath) -- ^ Compute the new path -> JsonResponse -- ^ Response on failure -> Handler Value modifyDiffTheory ti f fpath errResponse = do res <- evalInThread (liftIO $ f (dtiTheory ti)) case res of Left e -> return (excResponse e) Right Nothing -> return (responseToJson errResponse) Right (Just thy) -> do newThyIdx <- putDiffTheory (Just ti) Nothing thy newUrl <- getUrlRender <*> pure (OverviewDiffR newThyIdx (fpath thy)) return . responseToJson $ JsonRedirect newUrl where excResponse e = responseToJson (JsonAlert $ "Last request failed with exception: " `T.append` (T.pack (show e))) ------------------------------------------------------------------------------ -- Handler functions ------------------------------------------------------------------------------ -- | The root handler lists all theories by default, -- or load a new theory if the corresponding form was submitted. getRootR :: Handler Html getRootR = do theories <- getTheories defaultLayout $ do setTitle "Welcome to the Tamarin prover" rootTpl theories data File = File T.Text deriving Show postRootR :: Handler Html postRootR = do result <- lookupFile "uploadedTheory" case result of Nothing -> setMessage "Post request failed." Just fileinfo -> do -- content <- liftIO $ LBS.fromChunks <$> (fileSource fileinfo $$ consume) -- content <- liftIO $ runResourceT (fileSource fileinfo C.$$ consume) content <- liftIO $ runResourceT $ C.runConduit (fileSource fileinfo C..| consume) if null content then setMessage "No theory file given." else do yesod <- getYesod if isDiffTheory yesod then do closedThy <- liftIO $ diffParseThy yesod (T.unpack $ T.decodeUtf8 $ BS.concat content) case closedThy of Left err -> setMessage $ "Theory loading failed:\n" <> toHtml err Right thy -> do void $ putDiffTheory Nothing (Just $ Upload $ T.unpack $ fileName fileinfo) thy wfReport <- liftIO $ thyWf yesod (T.unpack $ T.decodeUtf8 $ BS.concat content) setMessage $ toHtml $ "Loaded new theory!" ++ wfReport else do closedThy <- liftIO $ parseThy yesod (T.unpack $ T.decodeUtf8 $ BS.concat content) case closedThy of Left err -> setMessage $ "Theory loading failed:\n" <> toHtml err Right thy -> do void $ putTheory Nothing (Just $ Upload $ T.unpack $ fileName fileinfo) thy wfReport <- liftIO $ thyWf yesod (T.unpack $ T.decodeUtf8 $ BS.concat content) setMessage $ toHtml $ "Loaded new theory!" ++ wfReport theories <- getTheories defaultLayout $ do setTitle "Welcome to the Tamarin prover" rootTpl theories -- | Show overview over theory (framed layout). getOverviewR :: TheoryIdx -> TheoryPath -> Handler Html getOverviewR idx path = withTheory idx ( \ti -> do renderF <- getUrlRender defaultLayout $ do overview <- liftIO $ overviewTpl renderF ti path setTitle (toHtml $ "Theory: " ++ get thyName (tiTheory ti)) overview ) -- | Show overview over diff theory (framed layout). getOverviewDiffR :: TheoryIdx -> DiffTheoryPath -> Handler Html getOverviewDiffR idx path = withDiffTheory idx ( \ti -> do renderF <- getUrlRender defaultLayout $ do overview <- liftIO $ overviewDiffTpl renderF ti path setTitle (toHtml $ "DiffTheory: " ++ get diffThyName (dtiTheory ti)) overview ) -- | Show source (pretty-printed open theory). getTheorySourceR :: TheoryIdx -> Handler RepPlain getTheorySourceR idx = withBothTheory idx ( \ti -> return $ RepPlain $ toContent $ prettyRender ti) ( \ti -> return $ RepPlain $ toContent $ prettyRenderDiff ti) where prettyRender = render . prettyClosedTheory . tiTheory prettyRenderDiff = render . prettyClosedDiffTheory . dtiTheory -- | Show source (pretty-printed open diff theory). getTheorySourceDiffR :: TheoryIdx -> Handler RepPlain getTheorySourceDiffR idx = withBothTheory idx ( \ti -> return $ RepPlain $ toContent $ prettyRender ti) ( \ti -> return $ RepPlain $ toContent $ prettyRenderDiff ti) where prettyRender = render . prettyClosedTheory . tiTheory prettyRenderDiff = render . prettyClosedDiffTheory . dtiTheory -- | Show variants (pretty-printed closed theory). getTheoryVariantsR :: TheoryIdx -> Handler RepPlain getTheoryVariantsR idx = withBothTheory idx ( \ti -> return $ RepPlain $ toContent $ prettyRender ti ) ( \ti -> return $ RepPlain $ toContent $ prettyRenderDiff ti ) where prettyRender = render . prettyClosedTheory . tiTheory prettyRenderDiff = render . prettyClosedDiffTheory . dtiTheory -- | Show variants (pretty-printed closed diff theory). getTheoryVariantsDiffR :: TheoryIdx -> Handler RepPlain getTheoryVariantsDiffR idx = withBothTheory idx ( \ti -> return $ RepPlain $ toContent $ prettyRender ti ) ( \ti -> return $ RepPlain $ toContent $ prettyRenderDiff ti ) where prettyRender = render . prettyClosedTheory . tiTheory prettyRenderDiff = render . prettyClosedDiffTheory . dtiTheory -- | Show variants (pretty-printed closed theory). getTheoryMessageDeductionR :: TheoryIdx -> Handler RepPlain getTheoryMessageDeductionR idx = withBothTheory idx ( \ti -> return $ RepPlain $ toContent $ prettyRender ti ) ( \ti -> return $ RepPlain $ toContent $ prettyRenderDiff ti ) where prettyRender = render . prettyClosedTheory . tiTheory prettyRenderDiff = render . prettyClosedDiffTheory . dtiTheory -- | Show variants (pretty-printed closed theory). getTheoryMessageDeductionDiffR :: TheoryIdx -> Handler RepPlain getTheoryMessageDeductionDiffR idx = withBothTheory idx ( \ti -> return $ RepPlain $ toContent $ prettyRender ti ) ( \ti -> return $ RepPlain $ toContent $ prettyRenderDiff ti ) where prettyRender = render . prettyClosedTheory . tiTheory prettyRenderDiff = render . prettyClosedDiffTheory . dtiTheory -- | Show a given path within a theory (main view). getTheoryPathMR :: TheoryIdx -> TheoryPath -> Handler RepJson getTheoryPathMR idx path = do renderUrl <- getUrlRender jsonValue <- withTheory idx (go renderUrl path) return $ RepJson $ toContent jsonValue where -- -- Handle method paths by trying to solve the given goal/method -- go _ (TheoryMethod lemma proofPath i) ti = modifyTheory ti (\thy -> return $ applyMethodAtPath thy lemma proofPath heuristic i) (\thy -> nextSmartThyPath thy (TheoryProof lemma proofPath)) (JsonAlert "Sorry, but the prover failed on the selected method!") where heuristic = apDefaultHeuristic (tiAutoProver ti) -- -- Handle generic paths by trying to render them -- go renderUrl _ ti = do let title = T.pack $ titleThyPath (tiTheory ti) path let html = htmlThyPath renderUrl ti path return $ responseToJson (JsonHtml title $ toContent html) -- | Show a given path within a diff theory (main view). getTheoryPathDiffMR :: TheoryIdx -> DiffTheoryPath -> Handler RepJson getTheoryPathDiffMR idx path = do -- error ("failed in handler" ++ show path) renderUrl <- getUrlRender jsonValue <- withDiffTheory idx (goDiff renderUrl path) return $ RepJson $ toContent jsonValue where -- -- Handle method paths by trying to solve the given goal/method -- goDiff _ (DiffTheoryMethod s lemma proofPath i) ti = modifyDiffTheory ti (\thy -> return $ applyMethodAtPathDiff thy s lemma proofPath heuristic i) (\thy -> nextSmartDiffThyPath thy (DiffTheoryProof s lemma proofPath)) (JsonAlert "Sorry, but the prover failed on the selected method!") where heuristic = apDefaultHeuristic (dtiAutoProver ti) goDiff _ (DiffTheoryDiffMethod lemma proofPath i) ti = modifyDiffTheory ti (\thy -> return $ applyDiffMethodAtPath thy lemma proofPath heuristic i) (\thy -> nextSmartDiffThyPath thy (DiffTheoryDiffProof lemma proofPath)) (JsonAlert "Sorry, but the prover failed on the selected method!") where heuristic = apDefaultHeuristic (dtiAutoProver ti) -- -- Handle generic paths by trying to render them -- goDiff renderUrl _ ti = do let title = T.pack $ titleDiffThyPath (dtiTheory ti) path let html = htmlDiffThyPath renderUrl ti path return $ responseToJson (JsonHtml title $ toContent html) -- | Run the some prover on a given proof path. getProverR :: (T.Text, AutoProver -> Prover) -> TheoryIdx -> TheoryPath -> Handler RepJson getProverR (name, mkProver) idx path = do jsonValue <- withTheory idx (go path) return $ RepJson $ toContent jsonValue where go (TheoryProof lemma proofPath) ti = modifyTheory ti (\thy -> return $ applyProverAtPath thy lemma proofPath autoProver) (\thy -> nextSmartThyPath thy path) (JsonAlert $ "Sorry, but " <> name <> " failed!") where autoProver = mkProver (tiAutoProver ti) go _ _ = return $ responseToJson $ JsonAlert $ "Can't run " <> name <> " on the given theory path!" -- | Run the some prover on a given proof path. getProverDiffR :: (T.Text, AutoProver -> Prover) -> TheoryIdx -> Side -> DiffTheoryPath -> Handler RepJson getProverDiffR (name, mkProver) idx s path = do jsonValue <- withDiffTheory idx (goDiff s path) return $ RepJson $ toContent jsonValue where goDiff s'' (DiffTheoryProof s' lemma proofPath) ti = if s''==s' then modifyDiffTheory ti (\thy -> return $ applyProverAtPathDiff thy s' lemma proofPath autoProver) (\thy -> nextSmartDiffThyPath thy path) (JsonAlert $ "Sorry, but " <> name <> " failed!") else return $ responseToJson $ JsonAlert $ "Can't run " <> name <> " on the given theory path!" where autoProver = mkProver (dtiAutoProver ti) goDiff _ _ _ = return $ responseToJson $ JsonAlert $ "Can't run " <> name <> " on the given theory path!" -- | Run the some prover on a given proof path. getDiffProverR :: (T.Text, AutoProver -> DiffProver) -> TheoryIdx -> DiffTheoryPath -> Handler RepJson getDiffProverR (name, mkProver) idx path = do jsonValue <- withDiffTheory idx (goDiff path) return $ RepJson $ toContent jsonValue where goDiff (DiffTheoryDiffProof lemma proofPath) ti = modifyDiffTheory ti (\thy -> return $ applyDiffProverAtPath thy lemma proofPath autoProver) (\thy -> nextSmartDiffThyPath thy path) (JsonAlert $ "Sorry, but " <> name <> " failed!") where autoProver = mkProver (dtiAutoProver ti) goDiff _ _ = return $ responseToJson $ JsonAlert $ "Can't run " <> name <> " on the given theory path!" -- | Run an autoprover on a given proof path. getAutoProverR :: TheoryIdx -> SolutionExtractor -> Int -- autoprover bound to use -> TheoryPath -> Handler RepJson getAutoProverR idx extractor bound = getProverR (fullName, runAutoProver . adapt) idx where adapt autoProver = autoProver { apBound = actualBound, apCut = extractor } withCommas = intersperse ", " fullName = mconcat $ proverName : " (" : withCommas qualifiers ++ [")"] qualifiers = extractorQualfier ++ boundQualifier (actualBound, boundQualifier) | bound > 0 = (Just bound, ["bound " <> T.pack (show bound)]) | otherwise = (Nothing, [] ) (proverName, extractorQualfier) = case extractor of CutNothing -> ("characterization", ["dfs"] ) CutDFS -> ("the autoprover", [] ) CutBFS -> ("the autoprover", ["bfs"] ) CutSingleThreadDFS -> ("the autoprover", ["seqdfs"]) -- | Run an autoprover on a given proof path. getAutoProverDiffR :: TheoryIdx -> SolutionExtractor -> Int -- autoprover bound to use -> Side -> DiffTheoryPath -> Handler RepJson getAutoProverDiffR idx extractor bound s = getProverDiffR (fullName, runAutoProver . adapt) idx s where adapt autoProver = autoProver { apBound = actualBound, apCut = extractor } withCommas = intersperse ", " fullName = mconcat $ proverName : " (" : withCommas qualifiers ++ [")"] qualifiers = extractorQualfier ++ boundQualifier (actualBound, boundQualifier) | bound > 0 = (Just bound, ["bound " <> T.pack (show bound)]) | otherwise = (Nothing, [] ) (proverName, extractorQualfier) = case extractor of CutNothing -> ("characterization", ["dfs"] ) CutDFS -> ("the autoprover", [] ) CutBFS -> ("the autoprover", ["bfs"] ) CutSingleThreadDFS -> ("the autoprover", ["seqdfs"]) -- | Run an autoprover on a given proof path. getAutoDiffProverR :: TheoryIdx -> SolutionExtractor -> Int -- autoprover bound to use -> DiffTheoryPath -> Handler RepJson getAutoDiffProverR idx extractor bound = getDiffProverR (fullName, runAutoDiffProver . adapt) idx where adapt autoProver = autoProver { apBound = actualBound, apCut = extractor } withCommas = intersperse ", " fullName = mconcat $ proverName : " (" : withCommas qualifiers ++ [")"] qualifiers = extractorQualfier ++ boundQualifier (actualBound, boundQualifier) | bound > 0 = (Just bound, ["bound " <> T.pack (show bound)]) | otherwise = (Nothing, [] ) (proverName, extractorQualfier) = case extractor of CutNothing -> ("characterization", ["dfs"]) CutDFS -> ("the autoprover", [] ) CutSingleThreadDFS -> ("the autoprover", [] ) CutBFS -> ("the autoprover", ["bfs"]) {- -- | Show a given path within a theory (debug view). getTheoryPathDR :: TheoryIdx -> TheoryPath -> Handler Html getTheoryPathDR idx path = withTheory idx $ \ti -> ajaxLayout $ do -- let maybeDebug = htmlThyDbgPath (tiTheory ti) path -- let maybeWidget = wrapHtmlDoc <$> maybeDebug return [hamlet| <h2>Theory information</h2> <ul> <li>Index = #{show (tiIndex ti)} <li>Path = #{show path} <li>Time = #{show (tiTime ti)} <li>Origin = #{show (tiOrigin ti)} <li>NextPath = #{show (nextThyPath (tiTheory ti) path)} <li>PrevPath = #{show (prevThyPath (tiTheory ti) path)} <li>NextSmartPath = #{show (nextSmartThyPath (tiTheory ti) path)} <li>PrevSmartPath = #{show (prevSmartThyPath (tiTheory ti) path)} |] {- $if isJust maybeWidget <h2>Current sequent</h2><br> \^{fromJust maybeWidget} |] -} -} -- | Get rendered graph for theory and given path. getTheoryGraphR :: TheoryIdx -> TheoryPath -> Handler () getTheoryGraphR idx path = withTheory idx ( \ti -> do yesod <- getYesod compact <- isNothing <$> lookupGetParam "uncompact" compress <- isNothing <$> lookupGetParam "uncompress" abbreviate <- isNothing <$> lookupGetParam "unabbreviate" simplificationLevel <- fromMaybe "1" <$> lookupGetParam "simplification" img <- liftIO $ traceExceptions "getTheoryGraphR" $ imgThyPath (imageFormat yesod) (graphCmd yesod) (cacheDir yesod) (graphStyle compact compress) (sequentToJSONPretty) (show simplificationLevel) (abbreviate) (tiTheory ti) path sendFile (fromString . imageFormatMIME $ imageFormat yesod) img) where graphStyle d c = dotStyle d . compression c dotStyle True = dotSystemCompact CompactBoringNodes dotStyle False = dotSystemCompact FullBoringNodes compression True = compressSystem compression False = id -- | Get rendered graph for theory and given path. getTheoryGraphDiffR :: TheoryIdx -> DiffTheoryPath -> Handler () getTheoryGraphDiffR idx path = getTheoryGraphDiffR' idx path False -- | Get rendered graph for theory and given path. getTheoryGraphDiffR' :: TheoryIdx -> DiffTheoryPath -> Bool -> Handler () getTheoryGraphDiffR' idx path mirror = withDiffTheory idx ( \ti -> do yesod <- getYesod compact <- isNothing <$> lookupGetParam "uncompact" compress <- isNothing <$> lookupGetParam "uncompress" abbreviate <- isNothing <$> lookupGetParam "unabbreviate" simplificationLevel <- fromMaybe "1" <$> lookupGetParam "simplification" img <- liftIO $ traceExceptions "getTheoryGraphDiffR" $ imgDiffThyPath (imageFormat yesod) (snd $ graphCmd yesod) (cacheDir yesod) (graphStyle compact compress) (show simplificationLevel) (abbreviate) (dtiTheory ti) path (mirror) sendFile (fromString . imageFormatMIME $ imageFormat yesod) img) where graphStyle d c = dotStyle d . compression c dotStyle True = dotSystemCompact CompactBoringNodes dotStyle False = dotSystemCompact FullBoringNodes compression True = compressSystem compression False = id -- | Get rendered mirror graph for theory and given path. getTheoryMirrorDiffR :: TheoryIdx -> DiffTheoryPath -> Handler () getTheoryMirrorDiffR idx path = getTheoryGraphDiffR' idx path True -- | Kill a thread (aka 'cancel request'). getKillThreadR :: Handler RepPlain getKillThreadR = do maybeKey <- lookupGetParam "path" case maybeKey of Just key0 -> do let key = T.decodeUtf8 . urlDecode True . T.encodeUtf8 $ key0 tryKillThread key return $ RepPlain $ toContent ("Canceled request!" :: T.Text) Nothing -> invalidArgs ["No path to kill specified!"] where -- thread waiting for the result is responsible for -- updating the ThreadMap. tryKillThread k = do maybeTid <- getThread k case maybeTid of Nothing -> trace ("Killing failed: "++ T.unpack k) $ return () Just tid -> trace ("Killing: " ++ T.unpack k) (liftIO $ killThread tid) -- | Get the 'next' theory path for a given path. -- This function is used for implementing keyboard shortcuts. getNextTheoryPathR :: TheoryIdx -- ^ Theory index -> String -- ^ Jumping mode (smart?) -> TheoryPath -- ^ Current path -> Handler RepPlain getNextTheoryPathR idx md path = withTheory idx (\ti -> do url <- getUrlRender <*> pure (TheoryPathMR idx $ next md (tiTheory ti) path) return . RepPlain $ toContent url) where next "normal" = nextThyPath next "smart" = nextSmartThyPath next _ = const id -- | Get the 'next' theory path for a given path. -- This function is used for implementing keyboard shortcuts. getNextTheoryPathDiffR :: TheoryIdx -- ^ Theory index -> String -- ^ Jumping mode (smart?) -> DiffTheoryPath -- ^ Current path -> Handler RepPlain getNextTheoryPathDiffR idx md path = withDiffTheory idx (\ti -> do url <- getUrlRender <*> pure (TheoryPathDiffMR idx $ nextDiff md (dtiTheory ti) path) return . RepPlain $ toContent url) where nextDiff "normal" = nextDiffThyPath nextDiff "smart" = nextSmartDiffThyPath nextDiff _ = const id -- | Get the 'prev' theory path for a given path. -- This function is used for implementing keyboard shortcuts. getPrevTheoryPathR :: TheoryIdx -> String -> TheoryPath -> Handler RepPlain getPrevTheoryPathR idx md path = withTheory idx (\ti -> do url <- getUrlRender <*> pure (TheoryPathMR idx $ prev md (tiTheory ti) path) return $ RepPlain $ toContent url) where prev "normal" = prevThyPath prev "smart" = prevSmartThyPath prev _ = const id -- | Get the 'prev' theory path for a given path. -- This function is used for implementing keyboard shortcuts. getPrevTheoryPathDiffR :: TheoryIdx -> String -> DiffTheoryPath -> Handler RepPlain getPrevTheoryPathDiffR idx md path = withDiffTheory idx (\ti -> do url <- getUrlRender <*> pure (TheoryPathDiffMR idx $ prevDiff md (dtiTheory ti) path) return $ RepPlain $ toContent url) where prevDiff "normal" = prevDiffThyPath prevDiff "smart" = prevSmartDiffThyPath prevDiff _ = const id {- -- | Get the edit theory page. getEditTheoryR :: TheoryIdx -> Handler RepJson getEditTheoryR = postEditTheoryR -- | Post edit theory page form data. postEditTheoryR :: TheoryIdx -> Handler RepJson postEditTheoryR idx = withTheory idx $ \ti -> formHandler "Edit theory" (theoryFormlet ti) theoryFormTpl $ \(Textarea input) -> E.handle exHandler $ do yesod <- getYesod closedThy <- checkProofs <$> parseThy yesod (T.unpack input) newIdx <- putTheory (Just ti) Nothing closedThy jsonResp . JsonRedirect =<< getUrlRender <*> pure (OverviewR newIdx) where -- theoryFormlet ti = fieldsToDivs $ textareaField theoryFormlet ti = textareaField (FieldSettings ("Edit theory source: " `T.append` name ti) (toHtml $ name ti) Nothing Nothing) (Just $ Textarea $ T.pack $ render $ prettyClosedTheory $ tiTheory ti) exHandler :: MonadBaseControl IO m => E.SomeException -> GHandler m RepJson exHandler err = jsonResp $ JsonAlert $ T.unlines [ "Unable to load theory due to parse error!" , "Parser returned the message:" , T.pack $ show err ] name = T.pack . get thyName . tiTheory theoryFormTpl = formTpl (EditTheoryR idx) "Load as new theory" -} {- SM: Path editing hs bitrotted. Re-enable/implement once we really need it. -- | Get the add lemma page. getEditPathR :: TheoryIdx -> TheoryPath -> Handler RepJson getEditPathR = postEditPathR -- | Post edit theory page form data. postEditPathR :: TheoryIdx -> TheoryPath -> Handler RepJson postEditPathR idx (TheoryLemma lemmaName) = withTheory idx $ \ti -> do yesod <- getYesod let lemma = lookupLemma lemmaName (tiTheory ti) formHandler (T.pack $ action lemma) (formlet lemma) (lemmaFormTpl lemma) $ \(Textarea input) -> case parseLemma (T.unpack input) of Left err -> jsonResp $ JsonAlert $ T.unlines [ "Unable to add lemma to theory due to parse error!" , "Parser returned the message:" , T.pack $ show err ] Right newLemma -> (RepJson . toContent . fromValue) <$> modifyTheory ti -- Add or replace lemma (\thy -> do let openThy = openTheory thy openThy' = case lemma of Nothing -> addLemma newLemma openThy Just _ -> removeLemma lemmaName openThy >>= addLemma newLemma -- SM: Theory closing has to be implemented again. -- Probably, the whole path editing has to be rethought. traverse (closeThy yesod) openThy') -- Error response (JsonAlert $ T.unwords [ "Unable to add lemma to theory." , "Does a lemma with the same name already exist?" ]) where path (Just l) = TheoryLemma (get lName l) path Nothing = TheoryLemma "" action (Just l) = "Edit lemma " ++ get lName l action Nothing = "Add new lemma" -- formlet lemma = fieldsToDivs $ textareaField formlet lemma = textareaField (FieldSettings (T.pack $ action lemma) (toHtml $ action lemma) Nothing Nothing) (Textarea . T.pack . render . prettyLemma prettyProof <$> lemma) lemmaFormTpl lemma = formTpl (EditPathR idx (path lemma)) "Submit" postEditPathR _ _ = jsonResp $ JsonAlert $ "Editing for this path is not implemented!" -} -- | Delete a given proof step. getDeleteStepR :: TheoryIdx -> TheoryPath -> Handler RepJson getDeleteStepR idx path = do jsonValue <- withTheory idx (go path) return $ RepJson $ toContent jsonValue where go (TheoryLemma lemma) ti = modifyTheory ti (return . removeLemma lemma) (const path) (JsonAlert "Sorry, but removing the selected lemma failed!") go (TheoryProof lemma proofPath) ti = modifyTheory ti (\thy -> return $ applyProverAtPath thy lemma proofPath (sorryProver (Just "removed"))) (const path) (JsonAlert "Sorry, but removing the selected proof step failed!") go _ _ = return . responseToJson $ JsonAlert "Can't delete the given theory path!" -- | Delete a given proof step. getDeleteStepDiffR :: TheoryIdx -> DiffTheoryPath -> Handler RepJson getDeleteStepDiffR idx path = do jsonValue <- withDiffTheory idx (goDiff path) return $ RepJson $ toContent jsonValue where goDiff (DiffTheoryLemma s lemma) ti = modifyDiffTheory ti (return . removeLemmaDiff s lemma) (const path) (JsonAlert "Sorry, but removing the selected lemma failed!") goDiff (DiffTheoryProof s lemma proofPath) ti = modifyDiffTheory ti (\thy -> return $ applyProverAtPathDiff thy s lemma proofPath (sorryProver (Just "removed"))) (const path) (JsonAlert "Sorry, but removing the selected proof step failed!") goDiff (DiffTheoryDiffLemma lemma) ti = modifyDiffTheory ti (return . removeDiffLemma lemma) (const path) (JsonAlert "Sorry, but removing the selected lemma failed!") goDiff (DiffTheoryDiffProof lemma proofPath) ti = modifyDiffTheory ti (\thy -> return $ applyDiffProverAtPath thy lemma proofPath (sorryDiffProver (Just "removed"))) (const path) (JsonAlert "Sorry, but removing the selected proof step failed!") goDiff _ _ = return . responseToJson $ JsonAlert "Can't delete the given theory path!" -- | Save a theory to the working directory. getSaveTheoryR :: TheoryIdx -> Handler RepJson getSaveTheoryR idx = withEitherTheory idx $ \eti -> do case eti of Trace ti -> do let origin = tiOrigin ti case origin of -- Saving interactive/uploaded files not supported yet. Interactive -> notFound Upload _ -> notFound -- Saving of local files implemented. Local file -> do -- Save theory to disk liftIO $ writeFile file (prettyRender ti) -- Find original theorie(s) with same origin -- Set original -> modified thys <- M.filter (same origin) <$> getTheories _ <- Tr.mapM (\t -> adjEitherTheory (getEitherTheoryIndex t) (setPrimary False)) thys -- Find current theory -- Set modified -> original adjEitherTheory (tiIndex ti) (setPrimary True) -- Return message jsonResp (JsonAlert $ T.pack $ "Saved theory to file: " ++ file) Diff ti -> do let origin = dtiOrigin ti case origin of -- Saving interactive/uploaded files not supported yet. Interactive -> notFound Upload _ -> notFound -- Saving of local files implemented. Local file -> do -- Save theory to disk liftIO $ writeFile file (prettyRenderD ti) -- Find original theorie(s) with same origin -- Set original -> modified thys <- M.filter (same origin) <$> getTheories _ <- Tr.mapM (\t -> adjEitherTheory (getEitherTheoryIndex t) (setPrimary False)) thys -- Find current theory -- Set modified -> original adjEitherTheory (dtiIndex ti) (setPrimary True) -- Return message jsonResp (JsonAlert $ T.pack $ "Saved theory to file: " ++ file) where prettyRender ti = render $ prettyOpenTheory $ openTheory $ tiTheory ti prettyRenderD ti = render $ prettyOpenDiffTheory $ openDiffTheory $ dtiTheory ti same origin (Trace ti) = tiPrimary ti && (tiOrigin ti == origin) same origin (Diff ti) = dtiPrimary ti && (dtiOrigin ti == origin) setPrimary :: Bool -> EitherTheoryInfo -> EitherTheoryInfo setPrimary bool (Trace ti) = Trace (ti { tiPrimary = bool }) setPrimary bool (Diff ti) = Diff (ti { dtiPrimary = bool }) -- | Prompt downloading of theory. getDownloadTheoryR :: TheoryIdx -> String -> Handler (ContentType, Content) getDownloadTheoryR idx _ = do RepPlain source <- getTheorySourceR idx return (typeOctet, source) -- | Prompt downloading of theory. getDownloadTheoryDiffR :: TheoryIdx -> String -> Handler (ContentType, Content) getDownloadTheoryDiffR = getDownloadTheoryR -- | Unload a theory from the interactive server. getUnloadTheoryR :: TheoryIdx -> Handler RepPlain getUnloadTheoryR idx = do delTheory idx redirect RootR -- | Unload a theory from the interactive server. getUnloadTheoryDiffR :: TheoryIdx -> Handler RepPlain getUnloadTheoryDiffR = getUnloadTheoryR {- -- | Show a list of all currently running threads. getThreadsR :: Handler Html getThreadsR = do threads <- getThreads defaultLayout $ do setTitle "Registered threads" addWidget (threadsTpl threads) -}
kmilner/tamarin-prover
src/Web/Handler.hs
gpl-3.0
45,713
0
29
13,063
9,134
4,625
4,509
694
8
{-# LANGUAGE OverloadedStrings #-} module Slackware.Download ( download , downloadAll , filename ) where import Conduit (ZipSink(..), getZipSink, sinkFile) import Crypto.Hash (Digest, MD5) import Crypto.Hash.Conduit (sinkHash) import Data.Conduit ((.|), runConduitRes) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Text as Text import Network.HTTP.Req ( GET (..) , MonadHttp , NoReqBody(..) , defaultHttpConfig , reqBr , runReq , useURI ) import Network.HTTP.Req.Conduit (responseBodySource) import Text.URI (URI(..), unRText) filename :: URI -> String filename = maybe "" (Text.unpack . unRText . NonEmpty.last . snd) . uriPath get :: MonadHttp m => URI -> Maybe (m (Digest MD5)) get url = do parsedUrl <- useURI url let get' = getTo $ filename url in return $ either get' get' parsedUrl where getTo destination (method, options) = reqBr GET method NoReqBody options $ \r -> runConduitRes $ responseBodySource r .| getZipSink (ZipSink (sinkFile destination) *> ZipSink sinkHash) download :: URI -> Maybe (IO (Digest MD5)) download url = runReq defaultHttpConfig <$> get url downloadAll :: [URI] -> Maybe (IO [Digest MD5]) downloadAll urls = sequence <$> traverse download urls
Dlackware/dlackware
lib/Slackware/Download.hs
gpl-3.0
1,319
0
15
291
436
241
195
37
1
module Main where fatorial :: Int->Int fatorial x = fatorial' x 1 fatorial' :: Int->Int->Int fatorial' x r | x == 0 = r | x == 1 = r | otherwise = fatorial' (x-1) (r*x) coeficienteBinomial :: Int -> Int -> Int coeficienteBinomial m n = (fatorial m) `div` ( (fatorial n) * ( fatorial (m-n) ) ) main :: IO() main = do print (coeficienteBinomial 10 5)
llscm0202/BIGDATA2017
ATIVIDADE1/exerciciosFuncoes/ex7.hs
gpl-3.0
365
0
11
85
190
97
93
13
1
{-# LANGUAGE CPP #-} module HipSpec.Sig.Scope where import GHC hiding (Sig) import Control.Applicative import Data.Maybe import DataCon #if __GLASGOW_HASKELL__ >= 708 import ConLike #endif getIdsInScope :: (Id -> Id) -> Ghc [Id] getIdsInScope fix_id = do ns <- getNamesInScope things <- catMaybes <$> mapM lookupName ns return [ fix_id i | AnId i <- things ] parseName' :: String -> Ghc [Name] parseName' = handleSourceError (\ _ -> return []) . parseName inScope :: String -> Ghc Bool inScope s = do xs <- parseName' s return $ if null xs then False else True lookupString :: String -> Ghc [TyThing] lookupString s = do xs <- parseName' s catMaybes <$> mapM lookupName xs thingToId :: TyThing -> Maybe Id thingToId (AnId i) = Just i #if __GLASGOW_HASKELL__ >= 708 thingToId (AConLike (RealDataCon dc)) = Just (dataConWorkId dc) thingToId (AConLike (PatSynCon _pc)) = error "HipSpec.Sig.Scope: Pattern synonyms not supported" #else thingToId (ADataCon dc) = Just (dataConWorkId dc) #endif thingToId _ = Nothing mapJust :: (a -> Maybe b) -> [a] -> Maybe b mapJust k = listToMaybe . mapMaybe k
danr/hipspec
src/HipSpec/Sig/Scope.hs
gpl-3.0
1,150
0
11
238
380
193
187
27
2
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, NoMonomorphismRestriction, ScopedTypeVariables, UndecidableInstances #-} {- | Functions I found useful for doing webapps with HStringTemplate. More usage examples can be found by grep -r \"Text.StringTemplate.Helpers\" in happs-tutorial, on hackage. -} module Text.StringTemplate.Helpers ( directoryGroups' , directoryGroups -- uses function from HStringTemplate which isn't strict, and I believe should be fixed in distribution. , directoryGroupsOld , dirgroupKeys , getTemplateGroup , renderTemplateDirGroup , lookupDirgroup , renderTemplateGroup , render1 , STDirGroups , readTmplDef , readTmplM , readTmplTuples , badTmplVarName , directoryGroupNew' ) where import Text.StringTemplate import Text.StringTemplate.Base import System.Directory import System.FilePath import qualified System.IO.Strict as Strict import Control.Applicative import Data.List (find) import Data.Char import Control.Monad.Reader import qualified Data.Map as M import Text.StringTemplate.Classes import Safe import qualified System.FilePath.Find as Find import System.FilePath bracketCWD :: FilePath -> IO a -> IO a bracketCWD d action = do c <- getCurrentDirectory setCurrentDirectory d r <- action setCurrentDirectory c pure r {- | Chooses a template from an STGroup, or errors if not found. Render that template using attrs. If a template k/v pair is repeated, it appears twice. (Perhaps a clue to buggy behavior?) Repeated keys could be eliminated by running clean: > clean = nubBy (\(a1,b1) (a2,b2) -> a1 == a2) . sortBy (\(a1,b1) (a2,b2) -> a1 `compare` a2) The ToSElem type is probably either String or [String] -} renderTemplateGroup :: (ToSElem a) => STGroup String -> [(String, a)] -> [Char] -> String renderTemplateGroup gr attrs tmpl = maybe ( "template not found: " ++ tmpl ) ( toString . setManyAttribSafer attrs ) ( getStringTemplate tmpl gr ) renderTemplateGroupS :: STGroup String -> [(String, String)] -> [Char] -> String renderTemplateGroupS = renderTemplateGroup -- can this be done for Bytestrings? Below doesn't work, need an instance for (ToSElem B.ByteString) --renderTemplateGroupB :: STGroup String -> [(String, B.ByteString)] -> [Char] -> String --renderTemplateGroupB = renderTemplateGroup --t :: IO [FilePath] --t = do (map :: M.Map FilePath (STGroup String)) <- ( directoryGroupsSafer "/home/thartman/testtemplates" ) -- return $ M.keys map --getST type STDirGroups a = M.Map FilePath (STGroup a) {- | Helper function to calculate a map of directory groups from a top-level directory Each directory gives rise to its own groups. Groups are independent; groups from higher in the directory structure do not have access to groups lower. The top group has key \".\" (mnemonic, current directory), other groups have key names of subdirectories, including the starting ., eg \".\/templates\/path\/to/\subdir\" -} directoryGroups' :: (FilePath -> IO a) -> FilePath -> IO (M.Map FilePath a) directoryGroups' f' d = bracketCWD d $ do subDirs <- findDirectories $ "." return . M.fromList =<< mapM f subDirs where f d = do g <- f' d return (d,g) findDirectories d = Find.find Find.always (Find.fileType Find.==? Find.Directory) d {- | Non-strict. I'm pretty sure this is wrong. Based on default directoryGroup function in HStringTemplate package -} directoryGroupsOld :: (Stringable a) => FilePath -> IO (M.Map FilePath (STGroup a)) directoryGroupsOld = directoryGroups' directoryGroup {- | Strict directoryGroups, which is the right thing. -} directoryGroups :: (Stringable a) => FilePath -> IO (M.Map FilePath (STGroup a)) directoryGroups = directoryGroups' directoryGroupNew {- | I'm this does the same thing as directoryGroup (modulo IO strictness), which uses an applicative idiom that melts my brain. Not a direct translation, but it's easier for me to understand when written Important change: readFile is strict. If it is left lazy, appkiller.sh causes happstutorial to crash when in dynamicTemplateReload mode. (See HAppS GoogleGroup.) I think this needs to be fixed in HStringTemplate distribution as well. This should be fixed in HSTringTemplate package as well. -} directoryGroupNew :: (Stringable a) => FilePath -> IO (STGroup a) directoryGroupNew = directoryGroupNew' (\_ -> False) (\_ -> False) {- | directoryGroup helper function for more flexibility, and rewritten to use do notation rather than applicative style that melted my brain. ignoreTemplate specifies a filter for templates that should be skipped, eg backup files etc. errorTemplate specifies a filter which will cause function to fail. > directoryGroupHAppS = directoryGroupNew' ignoret badTmplVarName > where ignoret f = not . null . filter (=='#') $ f -} directoryGroupNew' :: (Stringable a) => (FilePath -> Bool) -> (String -> Bool) -> FilePath -> IO (STGroup a) directoryGroupNew' ignoreTemplate errorTemplate path = do fs1 <- return . ( filter filt ) =<< getDirectoryContents path fs <- mapM errT =<< return fs1 templates <- mapM readTemplate fs stmapping <- return . zip (map dropExtension fs) $ templates return $ groupStringTemplates stmapping where readTemplate f = do contents <- Strict.readFile $ path </> f return . newSTMP $ contents errT t = if ( errorTemplate . takeBaseName ) t then fail $ "directoryGroupNew', bad template name: " ++ t else return t filt f = ( ( (".st" ==) . takeExtension ) $ f) && ( (not . ignoreTemplate) $ f) {- | The STGroup can't be shown in a useful way because it's a function type, but you can at least show the directories via Data.Map.keys. -} dirgroupKeys :: (Stringable a) => STDirGroups a -> [FilePath] dirgroupKeys = M.keys lookupDirgroup :: (Stringable a) => FilePath -> STDirGroups a -> Maybe (STGroup a) lookupDirgroup d = M.lookup d -- | > example: getTG "./baselayout" ts' getTemplateGroup :: (Stringable a) => FilePath -> STDirGroups a -> STGroup a getTemplateGroup dir tdg = maybe (error $ "getTG, bad dir:" ++ dir) id . lookupDirgroup dir $ tdg -- | > example: renderTemplateDirGroup ts' "./baselayout" "base" renderTemplateDirGroup :: ToSElem a => STDirGroups String -> FilePath -> String -> [(String,a)] -> String renderTemplateDirGroup tdg dir tname attrs = let ts = getTemplateGroup dir tdg in renderTemplateGroup ts attrs tname setManyAttribSafer attrs st = let mbFoundbadattr = find badTmplVarName . map fst $ attrs in maybe (setManyAttrib attrs st) (\mbA -> newSTMP . ("setManyAttribSafer, bad template atr: "++) $ mbA) mbFoundbadattr (<$$>) :: (Functor f1, Functor f) => (a -> b) -> f (f1 a) -> f (f1 b) (<$$>) = (<$>) . (<$>) {- Check for a variable that will cause errors and heartache using HStringTemplate -} badTmplVarName :: String -> Bool badTmplVarName t = not . null . filter (not . isAlpha) $ t {- | > render1 [("name","Bill")] "Hi, my name is $name$" > render1 attribs tmpl = render . setManyAttrib attribs . newSTMP $ tmpl -} render1 :: [(String,String)] -> String -> String render1 attribs tmpl = render . setManyAttrib attribs . newSTMP $ tmpl -- useful for HAppS, eg for dynamic menus readTmplTuples :: STGroup String -> String -> [(String, String)] readTmplTuples = readTmplDef [("readTutTuples error","")] readTmplDef :: (Read b) => b -> STGroup String -> FilePath -> b readTmplDef def ts f = either (const def) id ( readTmplM ts f :: Read a => Either String a) readTmplM :: (Monad m, Read a) => STGroup String -> FilePath -> m a readTmplM ts file = safeRead . renderTemplateGroup ts ([] :: [(String,String)] ) . concatMap escapequote $ file where escapequote char = if char=='"' then "\\\"" else [char] safeRead :: (Monad m, Read a) => String -> m a safeRead s = maybe (fail $ "safeRead: " ++ s) return . readMay $ s
wavewave/cvmaker
src/Text/StringTemplate/Helpers.hs
gpl-3.0
8,189
0
12
1,736
1,654
875
779
109
2
module Database.Design.Ampersand.Output.PredLogic ( PredLogicShow(..), showLatex, showRtf, mkVar ) where import Data.List import Database.Design.Ampersand.Basics import Database.Design.Ampersand.ADL1 import Database.Design.Ampersand.Classes import Database.Design.Ampersand.Misc import Database.Design.Ampersand.FSpec.ShowADL import Data.Char import Database.Design.Ampersand.Output.PandocAux (latexEscShw,texOnly_Id) fatal :: Int -> String -> a fatal = fatalMsg "Output.PredLogic" -- data PredVar = PV String -- TODO Bedoeld om predicaten inzichtelijk te maken. Er bestaan namelijk nu verschillende manieren om hier mee om te gaan (zie ook Motivations. HJO. data PredLogic = Forall [Var] PredLogic | Exists [Var] PredLogic | Implies PredLogic PredLogic | Equiv PredLogic PredLogic | Conj [PredLogic] | Disj [PredLogic] | Not PredLogic | Pred String String | -- Pred nm v, with v::type is equiv. to Rel nm Nowhere [] (type,type) True (Sgn (showADL e) type type [] "" "" "" [Asy,Sym] Nowhere 0 False) PlK0 PredLogic | PlK1 PredLogic | R PredLogic Declaration PredLogic | Atom String | Funs String [Declaration] | Dom Expression Var | Cod Expression Var deriving Eq data Notation = Flr | Frl | Rn | Wrap deriving Eq -- yields notations y=r(x) | x=r(y) | x r y | exists ... respectively. -- predKeyWords l = -- case l of -- English -> class PredLogicShow a where showPredLogic :: Lang -> a -> String showPredLogic l r = predLshow (natLangOps l) (toPredLogic r) -- predLshow produces raw LaTeX toPredLogic :: a -> PredLogic instance PredLogicShow Rule where toPredLogic ru = assemble (rrexp ru) instance PredLogicShow Expression where toPredLogic = assemble -- showLatex ought to produce PandDoc mathematics instead of LaTeX source code. -- PanDoc, however, does not support mathematics sufficiently, as to date. For this reason we have showLatex. -- It circumvents the PanDoc structure and goes straight to LaTeX source code. -- TODO when PanDoc is up to the job. showLatex :: PredLogic -> [[String]] showLatex x = chop (predLshow ("\\forall", "\\exists", implies, "\\Leftrightarrow", "\\vee", "\\ \\wedge\t", "^{\\asterisk}", "^{+}", "\\neg", rel, fun, mathVars, "", " ", apply, "\\in") x) where rel r lhs rhs -- TODO: the stuff below is very sloppy. This ought to be derived from the stucture, instead of by this naming convention. = if isIdent r then lhs++"\\ =\\ "++rhs else case name r of "lt" -> lhs++"\\ <\\ "++rhs "gt" -> lhs++"\\ >\\ "++rhs "le" -> lhs++"\\ \\leq\\ "++rhs "leq" -> lhs++"\\ \\leq\\ "++rhs "ge" -> lhs++"\\ \\geq\\ "++rhs "geq" -> lhs++"\\ \\geq\\ "++rhs _ -> lhs++"\\ \\id{"++latexEscShw (name r)++"}\\ "++rhs fun r e = "\\id{"++latexEscShw (name r)++"}("++e++")" implies antc cons = antc++" \\Rightarrow "++cons apply :: Declaration -> String -> String -> String --TODO language afhankelijk maken. apply decl d c = case decl of Sgn{} -> d++"\\ \\id{"++latexEscShw (name decl)++"}\\ "++c Isn{} -> d++"\\ =\\ "++c Vs{} -> "V" mathVars :: String -> [Var] -> String mathVars q vs = if null vs then "" else q++" "++intercalate "; " [intercalate ", " var++"\\coloncolon\\id{"++latexEscShw dType++"}" | (var,dType)<-vss]++":\n" where vss = [(map fst varCl,show(snd (head varCl))) |varCl<-eqCl snd vs] chop :: String -> [[String]] chop str = (map chops.lins) str where lins "" = [] lins ('\n':cs) = "": lins cs lins (c:cs) = (c:r):rs where r:rs = case lins cs of [] -> [""] ; e -> e chops cs = let [a,b,c] = take 3 (tabs cs) in [a,b,c] tabs "" = ["","","",""] tabs ('\t':cs) = "": tabs cs tabs (c:cs) = (c:r):rs where r:rs = tabs cs showRtf :: PredLogic -> String showRtf p = predLshow (forallP, existsP, impliesP, equivP, orP, andP, k0P, k1P, notP, relP, funP, showVarsP, breakP, spaceP, apply, el) p where unicodeSym :: Int -> Char -> Char -> String unicodeSym fs sym altChar = "{\\fs"++show fs++" \\u"++show (ord sym)++[altChar]++"}" forallP = unicodeSym 32 '∀' 'A' --"{\\fs36 \\u8704A}" existsP = unicodeSym 32 '∃' 'E' impliesP antc cons = antc++" "++unicodeSym 26 '⇒' '?'++" "++cons equivP = unicodeSym 26 '⇔' '=' orP = unicodeSym 30 '∨' 'v' andP = unicodeSym 30 '∧' '^' k0P = "{\\super "++unicodeSym 30 '∗' '*'++"}" k1P = "{\\super +}" notP = unicodeSym 26 '¬' '!' el = unicodeSym 30 '∈' '?' relP r lhs rhs -- TODO: sloppy code, copied from showLatex = if isIdent r then lhs++"\\ =\\ "++rhs else case name r of "lt" -> lhs++" < "++rhs "gt" -> lhs++" > "++rhs "le" -> lhs++" "++unicodeSym 28 '≤' '?'++" "++rhs "leq" -> lhs++" "++unicodeSym 28 '≤' '?'++" "++rhs "ge" -> lhs++" "++unicodeSym 28 '≥' '?'++" "++rhs "geq" -> lhs++" "++unicodeSym 28 '≥' '?'++" "++rhs _ -> lhs++" "++name r++" "++rhs funP r e = name r++"("++e++")" apply :: Declaration -> String -> String -> String apply decl d c = case decl of Sgn{} -> d++" "++name decl++" "++c Isn{} -> d++" = "++c Vs{} -> "V" showVarsP :: String -> [Var] -> String showVarsP q vs = if null vs then "" else q++intercalate "; " [intercalate ", " var++" "++unicodeSym 28 '∷' '?'++" "++dType | (var,dType)<-vss]++":\\par\n" where vss = [(map fst varCl,show(snd (head varCl))) |varCl<-eqCl snd vs] breakP = "" spaceP = " " -- natLangOps exists for the purpose of translating a predicate logic expression to natural language. -- It yields a vector of mostly strings, which are used to assemble a natural language text in one of the natural languages supported by Ampersand. natLangOps :: Named a => Lang -> (String, String, String -> String -> String, String, String, String, String, String, String, Declaration -> String -> String -> String, a -> String -> String, String -> [(String, A_Concept)] -> String, String, String, Declaration -> String -> String -> String, String) natLangOps l = case l of -- parameternamen: (forallP, existsP, impliesP, equivP, orP, andP, k0P, k1P, notP, relP, funP, showVarsP, breakP, spaceP) English -> ("For each", "There exists", implies, "is equivalent to", "or", "and", "*", "+", "not", rel, fun, langVars , "\n ", " ", apply, "is element of") Dutch -> ("Voor elke", "Er is een", implies, "is equivalent met", "of", "en", "*", "+", "niet", rel, fun, langVars , "\n ", " ", apply, "is element van") where rel r = apply r fun r x' = texOnly_Id(name r)++"("++x'++")" implies antc cons = case l of English -> "If "++antc++", then "++cons Dutch -> "Als "++antc++", dan "++cons apply decl d c = case decl of Sgn{} -> if null (prL++prM++prR) then "$"++d++"$ "++name decl++" $"++c++"$" else prL++" $"++d++"$ "++prM++" $"++c++"$ "++prR where prL = decprL decl prM = decprM decl prR = decprR decl Isn{} -> case l of English -> "$"++d++"$ equals $"++c++"$" Dutch -> "$"++d++"$ is gelijk aan $"++c++"$" Vs{} -> case l of English -> show True Dutch -> "Waar" langVars :: String -> [(String, A_Concept)] -> String langVars q vs = case l of English | null vs -> "" | q=="Exists" -> intercalate " and " ["there exist" ++(if length vs'==1 then "s a "++dType else ' ':plural English dType) ++" called " ++intercalate ", " ['$':v'++"$" | v'<-vs'] | (vs',dType)<-vss] | otherwise -> "If "++langVars "Exists" vs++", " Dutch | null vs -> "" | q=="Er is" -> intercalate " en " ["er " ++(if length vs'==1 then "is een "++dType else "zijn "++plural Dutch dType) ++" genaamd " ++intercalate ", " ['$':v'++"$" | v'<-vs'] | (vs',dType)<-vss] | otherwise -> "Als "++langVars "Er is" vs++", " where vss = [(map fst vs',show(snd (head vs'))) |vs'<-eqCl snd vs] -- predLshow exists for the purpose of translating a predicate logic expression to natural language. -- It uses a vector of operators (mostly strings) in order to produce text. This vector can be produced by, for example, natLangOps. -- example: 'predLshow (natLangOps l) e' translates expression 'e' -- into a string that contains a natural language representation of 'e'. predLshow :: ( String -- forallP , String -- existsP , String -> String -> String -- impliesP , String -- equivP , String -- orP , String -- andP , String -- kleene * , String -- kleene + , String -- notP , Declaration -> String -> String -> String -- relP , Declaration -> String -> String -- funP , String -> [(String, A_Concept)] -> String -- showVarsP , String -- breakP , String -- spaceP , Declaration -> String -> String -> String -- apply , String -- set element ) -> PredLogic -> String predLshow (forallP, existsP, impliesP, equivP, orP, andP, k0P, k1P, notP, relP, funP, showVarsP, breakP, spaceP, apply, el) = charshow 0 where wrap i j str = if i<=j then str else "("++str++")" charshow :: Integer -> PredLogic -> String charshow i predexpr = case predexpr of Forall vars restr -> wrap i 1 (showVarsP forallP vars ++ charshow 1 restr) Exists vars restr -> wrap i 1 (showVarsP existsP vars ++ charshow 1 restr) Implies antc conseq -> wrap i 2 (breakP++impliesP (charshow 2 antc) (charshow 2 conseq)) Equiv lhs rhs -> wrap i 2 (breakP++charshow 2 lhs++spaceP++equivP++spaceP++ charshow 2 rhs) Disj rs -> if null rs then "" else wrap i 3 (intercalate (spaceP++orP ++spaceP) (map (charshow 3) rs)) Conj rs -> if null rs then "" else wrap i 4 (intercalate (spaceP++andP++spaceP) (map (charshow 4) rs)) Funs x ls -> case ls of [] -> x r:ms -> if isIdent r then charshow i (Funs x ms) else charshow i (Funs (funP r x) ms) Dom expr (x,_) -> x++el++funP (makeRel "dom") (showADL expr) Cod expr (x,_) -> x++el++funP (makeRel "cod") (showADL expr) R pexpr dec pexpr' -> case (pexpr,pexpr') of (Funs l [] , Funs r []) -> wrap i 5 (apply dec l r) {- (Funs l [f], Funs r []) -> wrap i 5 (if isIdent rel then apply (makeDeclaration f) l r else apply (makeDeclaration rel) (funP f l) r) (Funs l [] , Funs r [f]) -> wrap i 5 (if isIdent rel then apply (makeDeclaration f) l r else apply (makeDeclaration rel) l (funP f r)) -} (lhs,rhs) -> wrap i 5 (relP dec (charshow 5 lhs) (charshow 5 rhs)) Atom atom -> "'"++atom++"'" PlK0 rs -> wrap i 6 (charshow 6 rs++k0P) PlK1 rs -> wrap i 7 (charshow 7 rs++k1P) Not rs -> wrap i 8 (spaceP++notP++charshow 8 rs) Pred nm v' -> nm++"{"++v'++"}" makeRel :: String -> Declaration -- This function exists solely for the purpose of dom and cod makeRel str = Sgn { decnm = str , decsgn = fatal 217 "Do not refer to decsgn of this dummy relation" , decprps = [Uni,Tot] , decprps_calc = Nothing , decprL = "" , decprM = "" , decprR = "" , decMean = fatal 223 "Do not refer to decMean of this dummy relation" , decfpos = OriginUnknown , decusr = False , decpat = fatal 228 "Do not refer to decpat of this dummy relation" , decplug = fatal 229 "Do not refer to decplug of this dummy relation" } --objOrShow :: Lang -> PredLogic -> String --objOrShow l = predLshow ("For all", "Exists", implies, " = ", " = ", "<>", "OR", "AND", "*", "+", "NOT", rel, fun, langVars l, "\n", " ") -- where rel r lhs rhs = applyM (makeDeclaration r) lhs rhs -- fun r x = x++"."++name r -- implies antc cons = "IF "++antc++" THEN "++cons -- The function 'assemble' translates a rule to predicate logic. -- In order to remain independent of any representation, it transforms the Haskell data structure Rule -- into the data structure PredLogic, rather than manipulate with texts. type Var = (String,A_Concept) assemble :: Expression -> PredLogic assemble expr = case (source expr, target expr) of (ONE, ONE) -> rc (_ , ONE) -> Forall [s] rc (ONE, _) -> Forall [t] rc (_ , _) -> Forall [s,t] rc where [s,t] = mkVar [] [source expr, target expr] rc = f [s,t] expr (s,t) f :: [Var] -> Expression -> (Var,Var) -> PredLogic f exclVars (EEqu (l,r)) (a,b) = Equiv (f exclVars l (a,b)) (f exclVars r (a,b)) f exclVars (EImp (l,r)) (a,b) = Implies (f exclVars l (a,b)) (f exclVars r (a,b)) f exclVars e@EIsc{} (a,b) = Conj [f exclVars e' (a,b) | e'<-exprIsc2list e] f exclVars e@EUni{} (a,b) = Disj [f exclVars e' (a,b) | e'<-exprUni2list e] f exclVars (EDif (l,r)) (a,b) = Conj [f exclVars l (a,b), Not (f exclVars r (a,b))] f exclVars (ELrs (l,r)) (a,b) = Forall [c] (Implies (f eVars r (b,c)) (f eVars l (a,c))) where [c] = mkVar exclVars [target l] eVars = exclVars++[c] f exclVars (ERrs (l,r)) (a,b) = Forall [c] (Implies (f eVars l (c,a)) (f eVars r (c,b))) where [c] = mkVar exclVars [source l] eVars = exclVars++[c] f exclVars (EDia (l,r)) (a,b) = Forall [c] (Equiv (f eVars r (b,c)) (f eVars l (a,c))) where [c] = mkVar exclVars [target l] eVars = exclVars++[c] f exclVars e@ECps{} (a,b) = fECps exclVars e (a,b) -- special treatment, see below f exclVars e@ERad{} (a,b) = fERad exclVars e (a,b) -- special treatment, see below f _ (EPrd (l,r)) (a,b) = Conj [Dom l a, Cod r b] f exclVars (EKl0 e) (a,b) = PlK0 (f exclVars e (a,b)) f exclVars (EKl1 e) (a,b) = PlK1 (f exclVars e (a,b)) f exclVars (ECpl e) (a,b) = Not (f exclVars e (a,b)) f exclVars (EBrk e) (a,b) = f exclVars e (a,b) f _ e@(EDcD dcl) ((a,sv),(b,tv)) = res where res = case denote e of Flr -> R (Funs a [dcl]) (Isn tv) (Funs b []) Frl -> R (Funs a []) (Isn sv) (Funs b [dcl]) Rn -> R (Funs a []) (dcl) (Funs b []) Wrap -> fatal 246 "function res not defined when denote e == Wrap. " f _ e@(EFlp (EDcD dcl)) ((a,sv),(b,tv)) = res where res = case denote e of Flr -> R (Funs a [dcl]) (Isn tv) (Funs b []) Frl -> R (Funs a []) (Isn sv) (Funs b [dcl]) Rn -> R (Funs b []) (dcl) (Funs a []) Wrap -> fatal 253 "function res not defined when denote e == Wrap. " f exclVars (EFlp e) (a,b) = f exclVars e (b,a) f _ (EMp1 val _) _ = Atom . showADL $ val f _ (EDcI _) ((a,_),(b,tv)) = R (Funs a []) (Isn tv) (Funs b []) f _ (EDcV _) _ = Atom "True" f _ e _ = fatal 298 ("Non-exhaustive pattern in subexpression "++showADL e++" of assemble (<"++showADL expr++">)") -- fECps treats the case of a composition. It works as follows: -- An expression, e.g. r;s;t , is translated to Exists (zip ivs ics) (Conj (frels s t)), -- in which ivs is a list of variables that are used inside the resulting expression, -- ics contains their types, and frels s t the subexpressions that -- are used in the resulting conjuct (at the right of the quantifier). fECps :: [Var] -> Expression -> (Var,Var) -> PredLogic fECps exclVars e (a,b) -- f :: [Var] -> Expression -> (Var,Var) -> PredLogic | and [isCpl e' | e'<-es] = f exclVars (deMorganECps e) (a,b) | otherwise = Exists ivs (Conj (frels a b)) where es :: [Expression] es = [ x | x<-exprCps2list e, not (isEpsilon x) ] -- Step 1: split in fragments at those points where an exists-quantifier is needed. -- Each fragment represents a subexpression with variables -- at the outside only. Fragments will be reconstructed in a conjunct. res :: [(Var -> Var -> PredLogic, A_Concept, A_Concept)] res = pars3 (exclVars++ivs) (split es) -- yields triples (r,s,t): the fragment, its source and target. -- Step 2: assemble the intermediate variables from at the right spot in each fragment. frels :: Var -> Var -> [PredLogic] frels src trg = [r v w | ((r,_,_),v,w)<-zip3 res' (src: ivs) (ivs++[trg]) ] -- Step 3: compute the intermediate variables and their types res' :: [(Var -> Var -> PredLogic, A_Concept, A_Concept)] res' = [triple | triple<-res, not (atomic triple)] ivs :: [Var] ivs = mkvar exclVars ics ics :: [ Either PredLogic A_Concept ] -- each element is either an atom or a concept ics = concat [ case (v',w) of (Left _, Left _ ) -> [] (Left atom, Right _ ) -> [ Left atom ] (Right _ , Left atom) -> [ Left atom ] (Right trg, Right _ ) -> [ Right trg ] -- SJ 20131117, was: (if trg==src then [ Right trg ] else [ Right (trg `meet` src) ]) -- This code assumes no ISA's in the A-structure. This works due to the introduction of EEps expressions. | (v',w)<-zip [ case l ("",src) ("",trg) of atom@Atom{} -> Left atom _ -> Right trg | (l,src,trg)<-init res] [ case r ("",src) ("",trg) of atom@Atom{} -> Left atom _ -> Right src | (r,src,trg)<-tail res] ] atomic :: (Var -> Var -> PredLogic, A_Concept, A_Concept) -> Bool atomic (r,a,b) = case r ("",a) ("",b) of Atom{} -> True _ -> False mkvar :: [Var] -> [ Either PredLogic A_Concept ] -> [Var] mkvar exclVars (Right z: ics) = let vz = head (mkVar exclVars [z]) in vz: mkvar (exclVars++[vz]) ics mkvar exclVars (Left _: ics) = mkvar exclVars ics mkvar _ [] = [] fERad :: [Var] -> Expression -> (Var,Var) -> PredLogic fERad exclVars e (a,b) | and[isCpl e' |e'<-es] = f exclVars (deMorganERad e) (a,b) -- e.g. -r!-s!-t | isCpl (head es) = f exclVars (foldr1 (.:.) antr .\. foldr1 (.!.) conr) (a,b) -- e.g. -r!-s! t antr cannot be empty, because isCpl (head es) is True; conr cannot be empty, because es has an element that is not isCpl. | isCpl (last es) = f exclVars (foldr1 (.!.) conl ./. foldr1 (.:.) antl) (a,b) -- e.g. r!-s!-t antl cannot be empty, because isCpl (head es) is True; conl cannot be empty, because es has an element that is not isCpl. | otherwise = Forall ivs (Disj (frels a b)) -- e.g. r!-s! t the condition or [isCpl e' |e'<-es] is true. {- was: | otherwise = Forall ivs (Disj alls) where alls = [f (exclVars++ivs) e' (sv,tv) | (e',(sv,tv))<-zip es (zip (a:ivs) (ivs++[b]))] -} where es = [ x | x<-exprRad2list e, not (isEpsilon x) ] -- The definition of exprRad2list guarantees that length es>=2 res = pars3 (exclVars++ivs) (split es) -- yields triples (r,s,t): the fragment, its source and target. conr = dropWhile isCpl es -- There is at least one positive term, because conr is used in the second alternative (and the first alternative deals with absence of positive terms). -- So conr is not empty. antr = let x = (map notCpl.map flp.reverse.takeWhile isCpl) es in if null x then fatal 367 ("Entering in an empty foldr1") else x conl = let x = (reverse.dropWhile isCpl.reverse) es in if null x then fatal 369 ("Entering in an empty foldr1") else x antl = let x = (map notCpl.map flp.takeWhile isCpl.reverse) es in if null x then fatal 371 ("Entering in an empty foldr1") else x -- Step 2: assemble the intermediate variables from at the right spot in each fragment. frels :: Var -> Var -> [PredLogic] frels src trg = [r v w | ((r,_,_),v,w)<-zip3 res' (src: ivs) (ivs++[trg]) ] -- Step 3: compute the intermediate variables and their types res' :: [(Var -> Var -> PredLogic, A_Concept, A_Concept)] res' = [triple | triple<-res, not (atomic triple)] ivs :: [Var] ivs = mkvar exclVars ics ics :: [ Either PredLogic A_Concept ] -- each element is either an atom or a concept ics = concat [ case (v',w) of (Left _, Left _ ) -> [] (Left atom, Right _ ) -> [ Left atom ] (Right _ , Left atom) -> [ Left atom ] (Right trg, Right _ ) -> [ Right trg ] -- SJ 20131117, was: (if trg==src then [ Right trg ] else [ Right (trg `meet` src) ]) -- This code assumes no ISA's in the A-structure. This works due to the introduction of EEps expressions. | (v',w)<-zip [ case l ("",src) ("",trg) of atom@Atom{} -> Left atom _ -> Right trg | (l,src,trg)<-init res] [ case r ("",src) ("",trg) of atom@Atom{} -> Left atom _ -> Right src | (r,src,trg)<-tail res] ] relFun :: [Var] -> [Expression] -> Expression -> [Expression] -> Var->Var->PredLogic relFun exclVars lhs e rhs = case e of EDcD dcl -> \sv tv->R (Funs (fst sv) [r | t'<- lhs, r<-relsMentionedIn t']) dcl (Funs (fst tv) [r | t'<-reverse rhs, r<-relsMentionedIn t']) EFlp (EDcD dcl) -> \sv tv->R (Funs (fst tv) [r | t'<-reverse rhs, r<-relsMentionedIn t']) dcl (Funs (fst sv) [r | t'<- lhs, r<-relsMentionedIn t']) EMp1 val _ -> \_ _-> Atom . showADL $ val EFlp EMp1{} -> relFun exclVars lhs e rhs _ -> \sv tv->f (exclVars++[sv,tv]) e (sv,tv) pars3 :: [Var] -> [[Expression]] -> [(Var -> Var -> PredLogic, A_Concept, A_Concept)] pars3 exclVars (lhs: [e]: rhs: ts) | denotes lhs==Flr && denote e==Rn && denotes rhs==Frl = ( relFun exclVars lhs e rhs, source (head lhs), target (last rhs)): pars3 exclVars ts | otherwise = pars2 exclVars (lhs:[e]:rhs:ts) pars3 exclVars ts = pars2 exclVars ts -- for lists shorter than 3 pars2 :: [Var] -> [[Expression]]-> [(Var -> Var -> PredLogic, A_Concept, A_Concept)] pars2 exclVars (lhs: [e]: ts) | denotes lhs==Flr && denote e==Rn = (relFun exclVars lhs e [], source (head lhs), target e): pars3 exclVars ts | denotes lhs==Flr && denote e==Frl = (relFun exclVars lhs (EDcI (source e)) [e], source (head lhs), target e): pars3 exclVars ts | otherwise = pars1 exclVars (lhs:[e]:ts) pars2 exclVars ([e]: rhs: ts) | denotes rhs==Frl && denote e==Rn = (relFun exclVars [] e rhs, source e, target (last rhs)): pars3 exclVars ts | denote e==Flr && denotes rhs==Frl = (relFun exclVars [e] (EDcI (source e)) rhs, source e, target (last rhs)): pars3 exclVars ts | otherwise = pars1 exclVars ([e]:rhs:ts) pars2 exclVars (lhs: rhs: ts) | denotes lhs==Flr && denotes rhs==Frl = (relFun exclVars lhs (EDcI (source (head rhs))) rhs, source (head lhs), target (last rhs)): pars3 exclVars ts | otherwise = pars1 exclVars (lhs:rhs:ts) pars2 exclVars ts = pars1 exclVars ts -- for lists shorter than 2 pars1 :: [Var] -> [[Expression]] -> [(Var -> Var -> PredLogic, A_Concept, A_Concept)] pars1 exclVars expressions = case expressions of [] -> [] (lhs: ts) -> (pars0 exclVars lhs, source (head lhs), target (last lhs)): pars3 exclVars ts pars0 :: [Var] -> [Expression] -> Var -> Var -> PredLogic pars0 exclVars lhs | denotes lhs==Flr = relFun exclVars lhs (EDcI (source (last lhs))) [] | denotes lhs==Frl = relFun exclVars [] (EDcI (target (last lhs))) lhs | otherwise = relFun exclVars [] (let [r]=lhs in r) [] denote :: Expression -> Notation denote e = case e of (EDcD d) | null([Uni,Inj,Tot,Sur] >- multiplicities d) -> Rn | isUni d && isTot d -> Flr | isInj d && isSur d -> Frl | otherwise -> Rn _ -> Rn denotes :: [Expression] -> Notation denotes = denote . head split :: [Expression] -> [[Expression]] split [] = [] split [e] = [[e]] split (e:e':es) = --if denote e `eq` Wrap then (e:spl):spls else if denote e `eq` denote e' then (e:spl):spls else [e]:spl:spls where spl:spls = split (e':es) Flr `eq` Flr = True Frl `eq` Frl = True _ `eq` _ = False -- mkVar is bedoeld om nieuwe variabelen te genereren, gegeven een set (ex) van reeds vergeven variabelen. -- mkVar garandeert dat het resultaat niet in ex voorkomt, dus postconditie: not (mkVar ex cs `elem` ex) -- Dat gebeurt door het toevoegen van apostrofes. mkVar :: [Var] -> [A_Concept] -> [Var] mkVar ex cs = mknew (map fst ex) [([(toLower.head.(++"x").name) c],c) |c<-cs] where mknew _ [] = [] mknew ex' ((x,c):xs) = if x `elem` ex' then mknew ex' ((x++"'",c):xs) else (x,c): mknew (ex'++[x]) xs
guoy34/ampersand
src/Database/Design/Ampersand/Output/PredLogic.hs
gpl-3.0
29,871
1
19
11,698
9,274
4,903
4,371
422
62
{-# 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.Partners.Users.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a user. -- -- /See:/ <https://developers.google.com/partners/ Google Partners API Reference> for @partners.users.get@. module Network.Google.Resource.Partners.Users.Get ( -- * REST Resource UsersGetResource -- * Creating a Request , usersGet , UsersGet -- * Request Lenses , ugXgafv , ugUploadProtocol , ugAccessToken , ugUploadType , ugUserId , ugRequestMetadataPartnersSessionId , ugUserView , ugRequestMetadataLocale , ugRequestMetadataExperimentIds , ugRequestMetadataUserOverridesIPAddress , ugRequestMetadataTrafficSourceTrafficSubId , ugRequestMetadataUserOverridesUserId , ugRequestMetadataTrafficSourceTrafficSourceId , ugCallback ) where import Network.Google.Partners.Types import Network.Google.Prelude -- | A resource alias for @partners.users.get@ method which the -- 'UsersGet' request conforms to. type UsersGetResource = "v2" :> "users" :> Capture "userId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "requestMetadata.partnersSessionId" Text :> QueryParam "userView" Text :> QueryParam "requestMetadata.locale" Text :> QueryParams "requestMetadata.experimentIds" Text :> QueryParam "requestMetadata.userOverrides.ipAddress" Text :> QueryParam "requestMetadata.trafficSource.trafficSubId" Text :> QueryParam "requestMetadata.userOverrides.userId" Text :> QueryParam "requestMetadata.trafficSource.trafficSourceId" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] User -- | Gets a user. -- -- /See:/ 'usersGet' smart constructor. data UsersGet = UsersGet' { _ugXgafv :: !(Maybe Xgafv) , _ugUploadProtocol :: !(Maybe Text) , _ugAccessToken :: !(Maybe Text) , _ugUploadType :: !(Maybe Text) , _ugUserId :: !Text , _ugRequestMetadataPartnersSessionId :: !(Maybe Text) , _ugUserView :: !(Maybe Text) , _ugRequestMetadataLocale :: !(Maybe Text) , _ugRequestMetadataExperimentIds :: !(Maybe [Text]) , _ugRequestMetadataUserOverridesIPAddress :: !(Maybe Text) , _ugRequestMetadataTrafficSourceTrafficSubId :: !(Maybe Text) , _ugRequestMetadataUserOverridesUserId :: !(Maybe Text) , _ugRequestMetadataTrafficSourceTrafficSourceId :: !(Maybe Text) , _ugCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UsersGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ugXgafv' -- -- * 'ugUploadProtocol' -- -- * 'ugAccessToken' -- -- * 'ugUploadType' -- -- * 'ugUserId' -- -- * 'ugRequestMetadataPartnersSessionId' -- -- * 'ugUserView' -- -- * 'ugRequestMetadataLocale' -- -- * 'ugRequestMetadataExperimentIds' -- -- * 'ugRequestMetadataUserOverridesIPAddress' -- -- * 'ugRequestMetadataTrafficSourceTrafficSubId' -- -- * 'ugRequestMetadataUserOverridesUserId' -- -- * 'ugRequestMetadataTrafficSourceTrafficSourceId' -- -- * 'ugCallback' usersGet :: Text -- ^ 'ugUserId' -> UsersGet usersGet pUgUserId_ = UsersGet' { _ugXgafv = Nothing , _ugUploadProtocol = Nothing , _ugAccessToken = Nothing , _ugUploadType = Nothing , _ugUserId = pUgUserId_ , _ugRequestMetadataPartnersSessionId = Nothing , _ugUserView = Nothing , _ugRequestMetadataLocale = Nothing , _ugRequestMetadataExperimentIds = Nothing , _ugRequestMetadataUserOverridesIPAddress = Nothing , _ugRequestMetadataTrafficSourceTrafficSubId = Nothing , _ugRequestMetadataUserOverridesUserId = Nothing , _ugRequestMetadataTrafficSourceTrafficSourceId = Nothing , _ugCallback = Nothing } -- | V1 error format. ugXgafv :: Lens' UsersGet (Maybe Xgafv) ugXgafv = lens _ugXgafv (\ s a -> s{_ugXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ugUploadProtocol :: Lens' UsersGet (Maybe Text) ugUploadProtocol = lens _ugUploadProtocol (\ s a -> s{_ugUploadProtocol = a}) -- | OAuth access token. ugAccessToken :: Lens' UsersGet (Maybe Text) ugAccessToken = lens _ugAccessToken (\ s a -> s{_ugAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ugUploadType :: Lens' UsersGet (Maybe Text) ugUploadType = lens _ugUploadType (\ s a -> s{_ugUploadType = a}) -- | Identifier of the user. Can be set to 'me' to mean the currently -- authenticated user. ugUserId :: Lens' UsersGet Text ugUserId = lens _ugUserId (\ s a -> s{_ugUserId = a}) -- | Google Partners session ID. ugRequestMetadataPartnersSessionId :: Lens' UsersGet (Maybe Text) ugRequestMetadataPartnersSessionId = lens _ugRequestMetadataPartnersSessionId (\ s a -> s{_ugRequestMetadataPartnersSessionId = a}) -- | Specifies what parts of the user information to return. ugUserView :: Lens' UsersGet (Maybe Text) ugUserView = lens _ugUserView (\ s a -> s{_ugUserView = a}) -- | Locale to use for the current request. ugRequestMetadataLocale :: Lens' UsersGet (Maybe Text) ugRequestMetadataLocale = lens _ugRequestMetadataLocale (\ s a -> s{_ugRequestMetadataLocale = a}) -- | Experiment IDs the current request belongs to. ugRequestMetadataExperimentIds :: Lens' UsersGet [Text] ugRequestMetadataExperimentIds = lens _ugRequestMetadataExperimentIds (\ s a -> s{_ugRequestMetadataExperimentIds = a}) . _Default . _Coerce -- | IP address to use instead of the user\'s geo-located IP address. ugRequestMetadataUserOverridesIPAddress :: Lens' UsersGet (Maybe Text) ugRequestMetadataUserOverridesIPAddress = lens _ugRequestMetadataUserOverridesIPAddress (\ s a -> s{_ugRequestMetadataUserOverridesIPAddress = a}) -- | Second level identifier to indicate where the traffic comes from. An -- identifier has multiple letters created by a team which redirected the -- traffic to us. ugRequestMetadataTrafficSourceTrafficSubId :: Lens' UsersGet (Maybe Text) ugRequestMetadataTrafficSourceTrafficSubId = lens _ugRequestMetadataTrafficSourceTrafficSubId (\ s a -> s{_ugRequestMetadataTrafficSourceTrafficSubId = a}) -- | Logged-in user ID to impersonate instead of the user\'s ID. ugRequestMetadataUserOverridesUserId :: Lens' UsersGet (Maybe Text) ugRequestMetadataUserOverridesUserId = lens _ugRequestMetadataUserOverridesUserId (\ s a -> s{_ugRequestMetadataUserOverridesUserId = a}) -- | Identifier to indicate where the traffic comes from. An identifier has -- multiple letters created by a team which redirected the traffic to us. ugRequestMetadataTrafficSourceTrafficSourceId :: Lens' UsersGet (Maybe Text) ugRequestMetadataTrafficSourceTrafficSourceId = lens _ugRequestMetadataTrafficSourceTrafficSourceId (\ s a -> s{_ugRequestMetadataTrafficSourceTrafficSourceId = a}) -- | JSONP ugCallback :: Lens' UsersGet (Maybe Text) ugCallback = lens _ugCallback (\ s a -> s{_ugCallback = a}) instance GoogleRequest UsersGet where type Rs UsersGet = User type Scopes UsersGet = '[] requestClient UsersGet'{..} = go _ugUserId _ugXgafv _ugUploadProtocol _ugAccessToken _ugUploadType _ugRequestMetadataPartnersSessionId _ugUserView _ugRequestMetadataLocale (_ugRequestMetadataExperimentIds ^. _Default) _ugRequestMetadataUserOverridesIPAddress _ugRequestMetadataTrafficSourceTrafficSubId _ugRequestMetadataUserOverridesUserId _ugRequestMetadataTrafficSourceTrafficSourceId _ugCallback (Just AltJSON) partnersService where go = buildClient (Proxy :: Proxy UsersGetResource) mempty
brendanhay/gogol
gogol-partners/gen/Network/Google/Resource/Partners/Users/Get.hs
mpl-2.0
9,359
0
24
2,383
1,356
779
577
204
1
module HN.Optimizer.FormalArgumentsDeleter (runB) where import Compiler.Hoopl hiding ((<*>)) import Safe.Exact import HN.Intermediate import HN.Optimizer.Node import HN.Optimizer.Pass import HN.Optimizer.ExpressionRewriter import HN.Optimizer.ArgumentValues (ArgFact) import HN.Optimizer.Utils rewriteB :: DefinitionNode -> FactBase ArgFact -> Maybe DefinitionNode rewriteB (LetNode l expr) f = LetNode l <$> rewrite WithoutChildren (rewriteExpression f) expr rewriteB _ _ = Nothing convertFact :: ArgFact -> Maybe [WithTopAndBot ExpressionFix] convertFact ((PElem a, _), _) = Just a convertFact _ = Nothing rewriteExpression f (Application aa @ (Atom a) b) = fmap (smartApplication aa . map fst) . rewrite WithChildren deleteArg =<< zipExactMay b =<< convertFact =<< lookupFact a f rewriteExpression _ _ = Nothing smartApplication a [] = a smartApplication a b = Application a b deleteArg :: Rewrite [(ExpressionFix, WithTopAndBot ExpressionFix)] deleteArg ((_, PElem _) : tail) = Just tail deleteArg _ = Nothing runB :: Pass ArgFact ArgFact runB = runPassB PassParams { ppConvertFacts = const . convertFactBase , ppTransfer = noTransferMapB , ppRewrite = pureBRewrite $ rewriteExitB rewriteB }
ingvar-lynn/HNC
HN/Optimizer/FormalArgumentsDeleter.hs
lgpl-3.0
1,216
6
14
181
409
216
193
31
1
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, GeneralizedNewtypeDeriving, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} ------------------------------------------------------ -- | -- Module : Crypto.Noise.Internal.Handshake.State -- Maintainer : John Galt <[email protected]> -- Stability : experimental -- Portability : POSIX module Crypto.Noise.Internal.Handshake.State where import Control.Lens import Control.Monad.Coroutine import Control.Monad.Coroutine.SuspensionFunctors import Control.Monad.Catch.Pure import Control.Monad.State (MonadState(..), StateT) import Control.Monad.Trans.Class (MonadTrans(lift)) import Data.ByteArray (ScrubbedBytes, convert) import Data.ByteString (ByteString) import Data.Monoid ((<>)) import Data.Proxy import Crypto.Noise.Cipher import Crypto.Noise.DH import Crypto.Noise.Hash import Crypto.Noise.Internal.Handshake.Pattern hiding (ss) import Crypto.Noise.Internal.SymmetricState -- | Represents the side of the conversation upon which a party resides. data HandshakeRole = InitiatorRole | ResponderRole deriving (Show, Eq) -- | Represents the various options and keys for a handshake parameterized by -- the 'DH' method. data HandshakeOpts d = HandshakeOpts { _hoRole :: HandshakeRole , _hoPrologue :: Plaintext , _hoLocalEphemeral :: Maybe (KeyPair d) , _hoLocalStatic :: Maybe (KeyPair d) , _hoRemoteEphemeral :: Maybe (PublicKey d) , _hoRemoteStatic :: Maybe (PublicKey d) } $(makeLenses ''HandshakeOpts) -- | Holds all state associated with the interpreter. data HandshakeState c d h = HandshakeState { _hsSymmetricState :: SymmetricState c h , _hsOpts :: HandshakeOpts d , _hsPSKMode :: Bool , _hsMsgBuffer :: ScrubbedBytes } $(makeLenses ''HandshakeState) -- | This data structure is yielded by the coroutine when more data is needed. data HandshakeResult = HandshakeResultMessage ScrubbedBytes | HandshakeResultNeedPSK -- | All HandshakePattern interpreters run within this Monad. newtype Handshake c d h r = Handshake { runHandshake :: Coroutine (Request HandshakeResult ScrubbedBytes) (StateT (HandshakeState c d h) Catch) r } deriving ( Functor , Applicative , Monad , MonadThrow , MonadState (HandshakeState c d h) ) -- | @defaultHandshakeOpts role prologue@ returns a default set of handshake -- options. All keys are set to 'Nothing'. defaultHandshakeOpts :: HandshakeRole -> Plaintext -> HandshakeOpts d defaultHandshakeOpts r p = HandshakeOpts { _hoRole = r , _hoPrologue = p , _hoLocalEphemeral = Nothing , _hoLocalStatic = Nothing , _hoRemoteEphemeral = Nothing , _hoRemoteStatic = Nothing } -- | Sets the local ephemeral key. setLocalEphemeral :: Maybe (KeyPair d) -> HandshakeOpts d -> HandshakeOpts d setLocalEphemeral k opts = opts { _hoLocalEphemeral = k } -- | Sets the local static key. setLocalStatic :: Maybe (KeyPair d) -> HandshakeOpts d -> HandshakeOpts d setLocalStatic k opts = opts { _hoLocalStatic = k } -- | Sets the remote ephemeral key (rarely needed). setRemoteEphemeral :: Maybe (PublicKey d) -> HandshakeOpts d -> HandshakeOpts d setRemoteEphemeral k opts = opts { _hoRemoteEphemeral = k } -- | Sets the remote static key. setRemoteStatic :: Maybe (PublicKey d) -> HandshakeOpts d -> HandshakeOpts d setRemoteStatic k opts = opts { _hoRemoteStatic = k } -- | Given a protocol name, returns the full handshake name according to the -- rules in section 8. mkHandshakeName :: forall c d h proxy. (Cipher c, DH d, Hash h) => ByteString -> proxy (c, d, h) -> ScrubbedBytes mkHandshakeName protoName _ = "Noise_" <> convert protoName <> "_" <> d <> "_" <> c <> "_" <> h where c = cipherName (Proxy :: Proxy c) d = dhName (Proxy :: Proxy d) h = hashName (Proxy :: Proxy h) -- | Constructs a HandshakeState from a given set of options and a protocol -- name (such as "NN" or "IK"). handshakeState :: forall c d h. (Cipher c, DH d, Hash h) => HandshakeOpts d -> HandshakePattern -> HandshakeState c d h handshakeState ho hp = HandshakeState { _hsSymmetricState = ss' , _hsOpts = ho , _hsPSKMode = hp ^. hpPSKMode , _hsMsgBuffer = mempty } where ss = symmetricState $ mkHandshakeName (hp ^. hpName) (Proxy :: Proxy (c, d, h)) ss' = mixHash (ho ^. hoPrologue) ss instance (Functor f, MonadThrow m) => MonadThrow (Coroutine f m) where throwM = lift . throwM instance (Functor f, MonadState s m) => MonadState s (Coroutine f m) where get = lift get put = lift . put state = lift . state
centromere/cacophony
src/Crypto/Noise/Internal/Handshake/State.hs
unlicense
5,498
0
12
1,726
1,085
617
468
98
1
module Hocker.Flags (mergeConfigAndFlags, parseFlags, usage) where import Data.Char (toLower) import Data.Maybe (fromMaybe) import Data.Monoid (mempty, (<>)) import Data.Yaml import Hocker.Data import Hocker.Validation import Hocker.Version import System.Console.GetOpt import System.Exit (ExitCode (..)) import System.IO (stderr, stdout) parseFlags :: [String] -> (Either FError RunCommand, String) parseFlags args = let fs = parseFlags' args hl = hockerFileLoc fs in (fs, fromMaybe "./Hockerfile" hl) parseFlags' :: [String] -> Either FError RunCommand parseFlags' args = let (os, as, es) = getOpt Permute options args opts = foldr ($) (Right mempty) os fallback = either flags id opts action = validateActions as fallback errors = validateErrors es fallback in do o <- opts _ <- errors a <- action return $! RunCommand o a where validateActions :: [String] -> Flags -> Either FError Action validateActions [a] = parseAction a validateActions [] = Left . NoAction validateActions as = Left . MultipleActions as parseAction :: String -> Flags -> Either FError Action parseAction s o = maybe (Left (UnknownAction s o)) Right $ readAction s readAction :: String -> Maybe Action readAction s = case map toLower s of "start" -> Just Start "stop" -> Just Stop "restart" -> Just Restart "status" -> Just Status "logs" -> Just Logs _ -> Nothing validateErrors :: [String] -> Flags -> Either FError () validateErrors [] _ = Right () validateErrors es o = Left (ParseError es o) options :: [OptDescr AddFlag] options = [ Option "sw" ["shallow", "skip"] (NoArg setShallow) "Skip pre-start steps" , Option "nd" ["dry-run", "noop"] (NoArg setDryRun) "Only show what would have been done, but don't do it" , Option "q" ["quick"] (NoArg setQuick) "quick start and stop" , Option "Q" ["quiet"] (NoArg setQuiet) "Less chatter (twice for even lesser chatter)" , Option "l" ["linux"] (NoArg setLinux) "When on linux, skip checking for boot2docker" , Option "c" ["config", "file"] (ReqArg setHockerFile "FILE") "Specify the Hockerfile to use (default is Hockerfile)" , Option "vV" ["version"] (NoArg setVersion) "Show the version and exit" , Option "h?" ["help"] (NoArg setHelp) "Show this help and exit" ] {------- help formatting ----------} usage :: [String] -> FError -> HelpOutput usage cfg (Help fs) = (usage cfg (ParseError [] fs)) { to = stdout, exit = ExitSuccess } usage _ (Version _) = succeedWith (programName ++ " " ++ programVersion) usage cfg (NoAction fs) = usage cfg (Version fs) <> (usage cfg (Help fs)) { to = stderr } usage _ (UnknownAction a _) = failWith $ "Unkown action: " ++ a usage _ (MultipleActions as _) = failWith msg where msg = unlines ["Multiple actions given (" ++ unwords as ++ ")", "Can only do one at a time"] usage cfg (ParseError es _) = failWith $ formatUsage es options cfg validateFlags :: [String] -> Either FError RunCommand -> Either HelpOutput RunCommand validateFlags = lmap . usage validateConfig :: Either ParseException Config -> Either HelpOutput Config validateConfig = lmap errorToHelp errorToHelp :: ParseException -> HelpOutput errorToHelp x = HelpOutput (unlines . formatYamlError $ x) stderr (ExitFailure 2) hockerFileLoc :: Either FError RunCommand -> Maybe String hockerFileLoc (Right (RunCommand fs _)) = hockerFile fs hockerFileLoc (Left x) = hockerFile . flags $ x mergeConfigAndFlags :: Either ParseException Config -> Either FError RunCommand -> (Either HelpOutput Config, Either HelpOutput RunCommand) mergeConfigAndFlags parsedConfig parsedFlags = let configForHelp = formatParsedConfig parsedConfig validatedFlags = validateFlags configForHelp parsedFlags validatedConfig = validateConfig parsedConfig in (validatedConfig, validatedFlags) failWith :: String -> HelpOutput failWith s = HelpOutput s stderr (ExitFailure 1) succeedWith :: String -> HelpOutput succeedWith s = mempty { message = s } lmap :: (a -> b) -> Either a c -> Either b c lmap _ (Right r) = Right r lmap f (Left l) = Left (f l)
knutwalker/hocker
src/lib/Hocker/Flags.hs
apache-2.0
4,479
0
12
1,145
1,397
717
680
93
9
-- | -- Module : Text.Megaparsec.Expr -- Copyright : © 2015 Megaparsec contributors -- © 2007 Paolo Martini -- © 1999–2001 Daan Leijen -- License : BSD3 -- -- Maintainer : Mark Karpov <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- A helper module to parse expressions. Builds a parser given a table of -- operators. module Text.Megaparsec.Expr ( Operator (..) , makeExprParser ) where import Control.Applicative ((<|>)) import Text.Megaparsec.Combinator import Text.Megaparsec.Prim -- | This data type specifies operators that work on values of type @a@. -- An operator is either binary infix or unary prefix or postfix. A binary -- operator has also an associated associativity. data Operator s u m a = InfixN (ParsecT s u m (a -> a -> a)) -- ^ non-associative infix | InfixL (ParsecT s u m (a -> a -> a)) -- ^ left-associative infix | InfixR (ParsecT s u m (a -> a -> a)) -- ^ right-associative infix | Prefix (ParsecT s u m (a -> a)) -- ^ prefix | Postfix (ParsecT s u m (a -> a)) -- ^ postfix -- | @makeExprParser term table@ builds an expression parser for terms -- @term@ with operators from @table@, taking the associativity and -- precedence specified in @table@ into account. -- -- @table@ is a list of @[Operator s u m a]@ lists. The list is ordered in -- descending precedence. All operators in one list have the same precedence -- (but may have a different associativity). -- -- Prefix and postfix operators of the same precedence can only occur once -- (i.e. @--2@ is not allowed if @-@ is prefix negate). Prefix and postfix -- operators of the same precedence associate to the left (i.e. if @++@ is -- postfix increment, than @-2++@ equals @-1@, not @-3@). -- -- The @makeExprParser@ takes care of all the complexity involved in -- building expression parser. Here is an example of an expression parser -- that handles prefix signs, postfix increment and basic arithmetic. -- -- > expr = makeExprParser term table <?> "expression" -- > -- > term = parens expr <|> integer <?> "term" -- > -- > table = [ [ prefix "-" negate -- > , prefix "+" id ] -- > , [ postfix "++" (+1) ] -- > , [ binary "*" (*) -- > , binary "/" div ] -- > , [ binary "+" (+) -- > , binary "-" (-) ] ] -- > -- > binary name f = InfixL (reservedOp name >> return f) -- > prefix name f = Prefix (reservedOp name >> return f) -- > postfix name f = Postfix (reservedOp name >> return f) -- -- Please note that multi-character operators should use 'try' in order to -- be reported correctly in error messages. makeExprParser :: Stream s m t => ParsecT s u m a -> [[Operator s u m a]] -> ParsecT s u m a makeExprParser = foldl addPrecLevel -- | @addPrecLevel p ops@ adds ability to parse operators in table @ops@ to -- parser @p@. addPrecLevel :: Stream s m t => ParsecT s u m a -> [Operator s u m a] -> ParsecT s u m a addPrecLevel term ops = term' >>= \x -> choice [ras' x, las' x, nas' x, return x] <?> "operator" where (ras, las, nas, prefix, postfix) = foldr splitOp ([],[],[],[],[]) ops term' = pTerm (choice prefix) term (choice postfix) ras' = pInfixR (choice ras) term' las' = pInfixL (choice las) term' nas' = pInfixN (choice nas) term' -- | @pTerm prefix term postfix@ parses term with @term@ surrounded by -- optional prefix and postfix unary operators. Parsers @prefix@ and -- @postfix@ are allowed to fail, in this case 'id' is used. pTerm :: Stream s m t => ParsecT s u m (a -> a) -> ParsecT s u m a -> ParsecT s u m (a -> a) -> ParsecT s u m a pTerm prefix term postfix = do pre <- option id (hidden prefix) x <- term post <- option id (hidden postfix) return $ post (pre x) -- | @pInfixN op p x@ parses non-associative infix operator @op@, then term -- with parser @p@, then returns result of the operator application on @x@ -- and the term. pInfixN :: Stream s m t => ParsecT s u m (a -> a -> a) -> ParsecT s u m a -> a -> ParsecT s u m a pInfixN op p x = do f <- op y <- p return $ f x y -- | @pInfixL op p x@ parses left-associative infix operator @op@, then term -- with parser @p@, then returns result of the operator application on @x@ -- and the term. pInfixL :: Stream s m t => ParsecT s u m (a -> a -> a) -> ParsecT s u m a -> a -> ParsecT s u m a pInfixL op p x = do f <- op y <- p let r = f x y pInfixL op p r <|> return r -- | @pInfixR op p x@ parses right-associative infix operator @op@, then -- term with parser @p@, then returns result of the operator application on -- @x@ and the term. pInfixR :: Stream s m t => ParsecT s u m (a -> a -> a) -> ParsecT s u m a -> a -> ParsecT s u m a pInfixR op p x = do f <- op y <- p >>= \r -> pInfixR op p r <|> return r return $ f x y type Batch s u m a = ( [ParsecT s u m (a -> a -> a)] , [ParsecT s u m (a -> a -> a)] , [ParsecT s u m (a -> a -> a)] , [ParsecT s u m (a -> a)] , [ParsecT s u m (a -> a)] ) -- | A helper to separate various operators (binary, unary, and according to -- associativity) and return them in a tuple. splitOp :: Operator s u m a -> Batch s u m a -> Batch s u m a splitOp (InfixR op) (r, l, n, pre, post) = (op:r, l, n, pre, post) splitOp (InfixL op) (r, l, n, pre, post) = (r, op:l, n, pre, post) splitOp (InfixN op) (r, l, n, pre, post) = (r, l, op:n, pre, post) splitOp (Prefix op) (r, l, n, pre, post) = (r, l, n, op:pre, post) splitOp (Postfix op) (r, l, n, pre, post) = (r, l, n, pre, op:post)
omefire/megaparsec
Text/Megaparsec/Expr.hs
bsd-2-clause
5,656
0
11
1,433
1,476
808
668
62
1
-- 7295372 mm = 12000 nn1 = 1 dd1 = 3 nn2 = 1 dd2 = 2 -- count proper fractions in the (range] for the given denominator countFrac n1 d1 n2 d2 d = length $ filter isProper [x1..x2] where isProper x = gcd d x == 1 x1 = (d*n1) `div` d1 + 1 x2 = (d*n2) `div` d2 -- count proper fractions in the (range], minus one to produce (range) countFracs n1 d1 n2 d2 m = (sum $ map (countFrac n1 d1 n2 d2) [2..m]) - 1 main = putStrLn $ show $ countFracs nn1 dd1 nn2 dd2 mm
higgsd/euler
hs/73.hs
bsd-2-clause
486
8
11
130
213
103
110
11
1
----------------------------------------------------------------------------- -- | -- Module : Data.Semigroup.Bitraversable -- Copyright : (C) 2011 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : portable -- ---------------------------------------------------------------------------- module Data.Semigroup.Bitraversable ( Bitraversable1(..) , bifoldMap1Default ) where import Control.Applicative import Data.Bitraversable import Data.Bifunctor import Data.Functor.Apply import Data.Semigroup import Data.Semigroup.Bifoldable import Data.Tagged class (Bifoldable1 t, Bitraversable t) => Bitraversable1 t where bitraverse1 :: Apply f => (a -> f b) -> (c -> f d) -> t a c -> f (t b d) bitraverse1 f g = bisequence1 . bimap f g {-# INLINE bitraverse1 #-} bisequence1 :: Apply f => t (f a) (f b) -> f (t a b) bisequence1 = bitraverse1 id id {-# INLINE bisequence1 #-} bifoldMap1Default :: (Bitraversable1 t, Semigroup m) => (a -> m) -> (b -> m) -> t a b -> m bifoldMap1Default f g = getConst . bitraverse1 (Const . f) (Const . g) {-# INLINE bifoldMap1Default #-} instance Bitraversable1 Either where bitraverse1 f _ (Left a) = Left <$> f a bitraverse1 _ g (Right b) = Right <$> g b {-# INLINE bitraverse1 #-} instance Bitraversable1 (,) where bitraverse1 f g (a, b) = (,) <$> f a <.> g b {-# INLINE bitraverse1 #-} instance Bitraversable1 ((,,) x) where bitraverse1 f g (x, a, b) = (,,) x <$> f a <.> g b {-# INLINE bitraverse1 #-} instance Bitraversable1 ((,,,) x y) where bitraverse1 f g (x, y, a, b) = (,,,) x y <$> f a <.> g b {-# INLINE bitraverse1 #-} instance Bitraversable1 ((,,,,) x y z) where bitraverse1 f g (x, y, z, a, b) = (,,,,) x y z <$> f a <.> g b {-# INLINE bitraverse1 #-} instance Bitraversable1 Const where bitraverse1 f _ (Const a) = Const <$> f a {-# INLINE bitraverse1 #-} instance Bitraversable1 Tagged where bitraverse1 _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse1 #-}
phaazon/bifunctors
src/Data/Semigroup/Bitraversable.hs
bsd-2-clause
2,088
0
13
413
695
375
320
42
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveGeneric #-} module Distribution.Solver.Types.ResolverPackage ( ResolverPackage(..) , resolverPackageDeps ) where import Distribution.Solver.Types.SolverId import Distribution.Solver.Types.SolverPackage import qualified Distribution.Solver.Types.ComponentDeps as CD import Distribution.Compat.Binary (Binary(..)) import Distribution.Compat.Graph (IsNode(..)) import Distribution.InstalledPackageInfo (InstalledPackageInfo) import Distribution.Package (Package(..), HasUnitId(..)) import GHC.Generics (Generic) -- | The dependency resolver picks either pre-existing installed packages -- or it picks source packages along with package configuration. -- -- This is like the 'InstallPlan.PlanPackage' but with fewer cases. -- data ResolverPackage loc = PreExisting InstalledPackageInfo (CD.ComponentDeps [SolverId]) | Configured (SolverPackage loc) deriving (Eq, Show, Generic) instance Binary loc => Binary (ResolverPackage loc) instance Package (ResolverPackage loc) where packageId (PreExisting ipkg _) = packageId ipkg packageId (Configured spkg) = packageId spkg resolverPackageDeps :: ResolverPackage loc -> CD.ComponentDeps [SolverId] resolverPackageDeps (PreExisting _ deps) = deps resolverPackageDeps (Configured spkg) = solverPkgDeps spkg instance IsNode (ResolverPackage loc) where type Key (ResolverPackage loc) = SolverId nodeKey (PreExisting ipkg _) = PreExistingId (packageId ipkg) (installedUnitId ipkg) nodeKey (Configured spkg) = PlannedId (packageId spkg) -- Use dependencies for ALL components nodeNeighbors pkg = CD.flatDeps (resolverPackageDeps pkg)
kolmodin/cabal
cabal-install/Distribution/Solver/Types/ResolverPackage.hs
bsd-3-clause
1,685
0
9
241
399
223
176
28
1
{-# LANGUAGE TupleSections #-} module Main (main) where import Control.Applicative (empty) import Control.Monad (void) import Text.Megaparsec import Text.Megaparsec.String import qualified Text.Megaparsec.Lexer as L lineComment :: Parser () lineComment = L.skipLineComment "#" scn :: Parser () scn = L.space (void spaceChar) lineComment empty sc :: Parser () sc = L.space (void $ oneOf " \t") lineComment empty lexeme :: Parser a -> Parser a lexeme = L.lexeme sc pItem :: Parser String pItem = lexeme $ some (alphaNumChar <|> char '-') pComplexItem :: Parser (String, [String]) pComplexItem = L.indentBlock scn p where p = do header <- pItem return (L.IndentMany Nothing (return . (header, )) pLineFold) pLineFold :: Parser String pLineFold = L.lineFold scn $ \sc' -> let ps = some (alphaNumChar <|> char '-') `sepBy1` try sc' in unwords <$> ps <* sc pItemList :: Parser (String, [(String, [String])]) pItemList = L.nonIndented scn (L.indentBlock scn p) where p = do header <- pItem return (L.IndentSome Nothing (return . (header, )) pComplexItem) parser :: Parser (String, [(String, [String])]) parser = pItemList <* eof main :: IO () main = return ()
mrkkrp/megaparsec-site
tutorial-code/IndentationSensitiveParsing.hs
bsd-3-clause
1,205
0
15
232
475
254
221
35
1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} -- | -- Module : Data.Array.Nikola.Backend.CUDA.TH -- Copyright : (c) Geoffrey Mainland 2012 -- License : BSD-style -- -- Maintainer : Geoffrey Mainland <[email protected]> -- Stability : experimental -- Portability : non-portable module Data.Array.Nikola.Backend.CUDA.TH ( compileSig , compile ) where import Control.Applicative (Applicative, (<$>), (<*>), pure) import Control.Monad.State import qualified Data.ByteString.Char8 as B import Data.Int import Data.Word import Foreign (mallocArray, withArray, newForeignPtr_) import qualified Foreign.CUDA.Driver as CU import qualified Foreign.CUDA.ForeignPtr as CU import qualified Language.C.Syntax as C import Language.Haskell.TH (Q, DecQ, PatQ, ExpQ) import qualified Language.Haskell.TH as TH import Language.Haskell.TH.Syntax (Quasi(..)) import qualified Language.Haskell.TH.Syntax as TH import System.IO.Unsafe (unsafePerformIO) -- import Text.PrettyPrint.Mainland import qualified Data.Vector.Storable as V import qualified Data.Vector.CUDA.Storable as VCS import qualified Data.Vector.CUDA.Storable.Mutable as MVCS import qualified Data.Vector.CUDA.UnboxedForeign as VCUF import qualified Data.Vector.CUDA.UnboxedForeign.Mutable as MVCUF import qualified Data.Array.Repa as R import qualified Data.Array.Repa.Repr.CUDA.ForeignPtr as R import qualified Data.Array.Repa.Repr.CUDA.UnboxedForeign as R import Data.Array.Nikola.Backend.C.Monad import qualified Data.Array.Nikola.Backend.CUDA as N import qualified Data.Array.Nikola.Backend.CUDA.Nvcc as Nvcc import Data.Array.Nikola.Backend.Flags import Data.Array.Nikola.Backend.CUDA.TH.Compile import Data.Array.Nikola.Backend.CUDA.TH.Util import qualified Data.Array.Nikola.Exp as E import Data.Array.Nikola.Language.Generic import Data.Array.Nikola.Language.Monad (runR, REnv, emptyREnv, reset) import Data.Array.Nikola.Language.Optimize (optimizeHostProgram) import Data.Array.Nikola.Language.Reify import Data.Array.Nikola.Language.Sharing import Data.Array.Nikola.Language.Syntax import Data.Array.Nikola.Util.Bool -- The function 'compileToExpQ' handles generating a TH expression for the body -- of the Nikola lambda as well as the CUDA kernels needed by the Nikola -- computation, but we then have to coerce the Haskell arguments into the form -- expected by this body and coerce the result of running the body back to a -- Hakell result. The 'Compilable' class drives these coercions via instance -- selection, and the coercions themselves are built up in the 'NQ' monad. Note -- that we need to gensym binders sometimes that are bound in the Haskell lambda -- but show up in the right-hand side of a declaration, so the 'NQ' monad must -- be an instance of 'Quasi'. newtype NQ a = NQ { runNQ :: NQEnv -> Q (NQEnv, a) } execNQ :: [CudaKernel] -> [C.Definition] -> [(Var, Type)] -> ExpQ -> NQ () -> Q NQEnv execNQ kernels cdefs vtaus qbody m = fst <$> runNQ m (defaultNQEnv kernels cdefs vtaus qbody) data NQEnv = NQEnv { nqKernels :: [CudaKernel] -- ^ The list of CUDA kernels the Nikola -- program calls. , nqCDefs :: [C.Definition] -- ^ The C definitions that comprise the -- CUDA program containing the CUDA -- kernels needed by the Nikola program. , nqLamVars :: [(Var, Type)] -- ^ The variables bound by the top-level -- Nikola lambda. , nqLamPats :: [TH.Pat] -- ^ The patterns that the compiled -- program uses to bind the variables in -- the top-level Nikola lambda. , nqDecs :: [TH.Dec] -- ^ Declarations needed by the compiled -- Nikola program. This consists of a -- binding for the compiled CUDA module, -- of type 'CU.Module', as well as -- bindings for all the CUDA kernels, of -- type 'CU.Fun', used by the Nikola -- program. , nqBody :: TH.ExpQ -- ^ The body of the compiled Nikola -- program. , nqMorallyPure :: Bool -- ^ The function is morally pure, so add -- an 'unsafePerformIO' if the computation -- is monadic. } defaultNQEnv :: [CudaKernel] -> [C.Definition] -> [(Var, Type)] -> ExpQ -> NQEnv defaultNQEnv kernels cdefs vtaus qbody = NQEnv { nqKernels = kernels , nqCDefs = cdefs , nqLamVars = vtaus , nqLamPats = [] , nqDecs = [] , nqBody = qbody , nqMorallyPure = False } instance Monad NQ where return a = NQ $ \s -> return (s, a) m >>= f = NQ $ \s -> do (s', x) <- runNQ m s runNQ (f x) s' m1 >> m2 = NQ $ \s -> do (s', _) <- runNQ m1 s runNQ m2 s' fail err = NQ $ \_ -> fail err instance Functor NQ where fmap f x = x >>= return . f instance Applicative NQ where pure = return (<*>) = ap instance MonadState NQEnv NQ where get = NQ $ \s -> return (s, s) put s = NQ $ \_ -> return (s, ()) instance MonadIO NQ where liftIO m = NQ $ \s -> do x <- liftIO m return (s, x) liftQ :: Q a -> NQ a liftQ m = NQ $ \s -> do x <- m return (s, x) instance Quasi NQ where qNewName = liftQ . qNewName qReport flag msg = liftQ $ qReport flag msg qRecover _ _ = fail "qRecover: punting" qLookupName ns s = liftQ $ qLookupName ns s qReify = liftQ . qReify qReifyInstances n tys = liftQ $ qReifyInstances n tys qLocation = liftQ qLocation qRunIO = liftIO qAddDependentFile = liftQ . qAddDependentFile takeLamVar :: NQ (Var, Type) takeLamVar = do vtaus <- gets nqLamVars vtau <- case vtaus of vtau:_ -> return vtau _ -> fail "internal error in takeLamVar: no lambdas left!" modify $ \s -> s { nqLamVars = tail (nqLamVars s) } return vtau appendLamPats :: [TH.Pat] -> NQ () appendLamPats ps = modify $ \s -> s { nqLamPats = nqLamPats s ++ ps } appendDec :: [TH.Dec] -> NQ () appendDec ps = modify $ \s -> s { nqDecs = nqDecs s ++ ps } modifyBody :: (ExpQ -> ExpQ) -> NQ () modifyBody f = do qbody <- gets nqBody modify $ \s -> s { nqBody = f qbody } addResultCoercion :: (ExpQ -> ExpQ) -> PreExpQ a -> PreExpQ b addResultCoercion f (PreExpQ m) = PreExpQ $ do m qbody <- gets nqBody modify $ \s -> s { nqBody = f qbody } addArgBinder :: NQ () -> PreExpQ (a -> b) -> PreExpQ b addArgBinder m' (PreExpQ m) = PreExpQ (m >> m') setMorallyPure :: Bool -> PreExpQ a -> PreExpQ a setMorallyPure isPure (PreExpQ m) = PreExpQ $ do m modify $ \s -> s { nqMorallyPure = isPure } newtype PreExpQ a = PreExpQ { unPreExpQ :: NQ () } castPreExpQ :: PreExpQ a -> PreExpQ b castPreExpQ (PreExpQ qe) = PreExpQ qe -- 'Compilable' relates the type of a Nikola DSL expression to the type of the -- compiled version of the DSL expression. It really is a relation! The type -- index serves only to drive instance selection; we recursive over the index -- @a@, which is the type of a Nikola DSL term, and transform it into a @b@, -- which is the type of the compiled version of the Nikola DSL term, building up -- the 'PreExpQ' along the way. class Compilable a b where precompile :: PreExpQ a -> PreExpQ b -- 'Rsh' is a type function from Nikola shapes to Repa shapes. This allows -- 'Compilable' instances that involve arrays to be polymorphic in array shape. class ToRsh a where type Rsh a :: * toRshPatQ :: a -> [PatQ] -> PatQ toRshExpQ :: a -> [ExpQ] -> ExpQ instance ToRsh N.Z where type Rsh N.Z = R.Z toRshPatQ _ _ = [p|R.Z|] toRshExpQ _ _ = [|R.Z|] instance ToRsh sh => ToRsh (sh N.:. E.Exp N.CUDA E.Ix) where type Rsh (sh N.:. E.Exp N.CUDA E.Ix) = Rsh sh R.:. Int toRshPatQ _ qps = TH.infixP (toRshPatQ (undefined :: sh) (init qps)) (TH.mkName "R.:.") (last qps) toRshExpQ _ qes = [|$(toRshExpQ (undefined :: sh) (init qes)) R.:. $(last qes)|] -- -- These are the base cases -- instance (arep ~ N.Rep (N.Exp a), N.IsElem (N.Exp a), IsVal arep) => Compilable (N.Exp a) arep where precompile = setMorallyPure True . addResultCoercion (coerceResult (undefined :: arep)) instance (arep ~ N.Rep a, N.IsElem a, IsArrayVal [arep]) => Compilable (N.Array r N.DIM1 a) [arep] where precompile = setMorallyPure True . addResultCoercion (coerceResult (undefined :: [arep])) instance (arep ~ N.Rep a, N.IsElem a, IsArrayVal (V.Vector arep)) => Compilable (N.Array r N.DIM1 a) (V.Vector arep ) where precompile = setMorallyPure True . addResultCoercion (coerceResult (undefined :: V.Vector arep)) instance (arep ~ N.Rep (N.Exp a), N.IsElem (N.Exp a), IsArrayVal (VCS.Vector arep)) => Compilable (N.Array r N.DIM1 (N.Exp a)) (VCS.Vector arep ) where precompile = setMorallyPure True . addResultCoercion (coerceResult (undefined :: VCS.Vector arep)) instance (arep ~ N.Rep a, rsh ~ Rsh sh, ToRsh sh, N.Shape sh, N.IsElem a, IsVal (R.Array R.CF rsh arep)) => Compilable (N.Array r sh a) (R.Array R.CF rsh arep) where precompile = setMorallyPure True . addResultCoercion (coerceResult (undefined :: R.Array R.CF rsh arep)) instance (arep ~ N.Rep a, rsh ~ Rsh sh, ToRsh sh, N.Shape sh, N.IsElem a, IsVal (R.Array R.CUF rsh arep)) => Compilable (N.Array r sh a) (R.Array R.CUF rsh arep) where precompile = setMorallyPure True . addResultCoercion (coerceResult (undefined :: R.Array R.CUF rsh arep)) instance Compilable (N.P ()) (IO ()) where precompile = addResultCoercion id instance (arep ~ N.Rep a, rsh ~ Rsh sh, ToRsh sh, N.Shape sh, N.IsElem a, IsVal (R.Array R.CUF rsh arep)) => Compilable (N.P (N.Array r sh a)) (IO (R.Array R.CUF rsh arep)) where precompile = addResultCoercion $ coerceResult (undefined :: R.Array R.CUF rsh arep) -- -- And here are the inductive cases -- instance (arep ~ N.Rep (N.Exp a), N.IsElem (N.Exp a), IsVal arep, Compilable b c) => Compilable (N.Exp a -> b) (arep -> c) where precompile pq = castPreExpQ (precompile p' :: PreExpQ c) where p' :: PreExpQ b p' = addArgBinder (bindArgs (undefined :: arep)) pq instance (arep ~ N.Rep a, N.IsElem a, IsArrayVal [arep], Compilable b c) => Compilable (N.Array N.G N.DIM1 a -> b) ([arep] -> c) where precompile pq = castPreExpQ (precompile p' :: PreExpQ c) where p' :: PreExpQ b p' = addArgBinder (bindArgs (undefined :: [arep])) pq instance (arep ~ N.Rep a, N.IsElem a, IsArrayVal (V.Vector arep), Compilable b c) => Compilable (N.Array N.G N.DIM1 a -> b) (V.Vector arep -> c) where precompile pq = castPreExpQ (precompile p' :: PreExpQ c) where p' :: PreExpQ b p' = addArgBinder (bindArgs (undefined :: V.Vector arep)) pq instance (arep ~ N.Rep a, N.IsElem a, IsArrayVal (VCS.Vector arep), Compilable b c) => Compilable (N.Array N.G N.DIM1 a -> b) (VCS.Vector arep -> c) where precompile pq = castPreExpQ (precompile p' :: PreExpQ c) where p' :: PreExpQ b p' = addArgBinder (bindArgs (undefined :: VCS.Vector arep)) pq instance (rsh ~ Rsh sh, arep ~ N.Rep a, ToRsh sh, N.Shape sh, R.Shape (Rsh sh), N.IsElem a, IsVal (R.Array R.CF rsh arep), Compilable b c) => Compilable (N.Array N.G sh a -> b) (R.Array R.CF rsh arep -> c) where precompile pq = castPreExpQ (precompile p' :: PreExpQ c) where p' :: PreExpQ b p' = addArgBinder (bindArgs (undefined :: R.Array R.CF rsh arep)) pq instance (rsh ~ Rsh sh, arep ~ N.Rep a, ToRsh sh, N.Shape sh, R.Shape (Rsh sh), N.IsElem a, IsVal (R.Array R.CUF rsh arep), Compilable b c) => Compilable (N.Array N.G sh a -> b) (R.Array R.CUF rsh arep -> c) where precompile pq = castPreExpQ (precompile p' :: PreExpQ c) where p' :: PreExpQ b p' = addArgBinder (bindArgs (undefined :: R.Array R.CUF rsh arep)) pq instance (rsh ~ Rsh sh, arep ~ N.Rep a, ToRsh sh, N.Shape sh, R.Shape (Rsh sh), N.IsElem a, IsVal (R.MArray R.CUF rsh arep), Compilable b c) => Compilable (N.MArray N.G sh a -> b) (R.MArray R.CUF rsh arep -> c) where precompile pq = castPreExpQ (precompile p' :: PreExpQ c) where p' :: PreExpQ b p' = addArgBinder (bindArgs (undefined :: R.MArray R.CUF rsh arep)) pq -- | If we can reify a value of type @a@ as a Nikola program, and if we can -- compile a value of type @a@ into a value of type @b@, then 'compileSig' will -- reify, optimize, and compile it. Note that the second argument of type @b@ -- serves only to specify the type of the final compiled value---the value -- itself is never evaluated, so it is perfectly acceptable (and expected!) to -- pass 'undefined' as the second argument (with a proper type signature of -- course!). compileSig :: forall a b . (Compilable a b, Reifiable a Exp) => a -> b -> ExpQ compileSig a _ = do (_, p) <- liftIO $ flip runR env $ reset (reify a) >>= detectSharing ExpA >>= optimizeHostProgram (kernels, cdefs, (vtaus, qbody, isMonadic)) <- liftIO $ evalCEx (compileToExpQ p) let pexpq :: PreExpQ a pexpq = PreExpQ (return ()) pexpq' :: PreExpQ b pexpq' = precompile pexpq execNQ kernels cdefs vtaus qbody (unPreExpQ pexpq') >>= finalizeExpQ isMonadic where env :: REnv env = emptyREnv flags flags :: Flags flags = defaultFlags { fOptimize = ljust 1 } finalizeExpQ :: Bool -> NQEnv -> ExpQ finalizeExpQ isMonadic env = do kernelDecQs <- kernelDecQs (nqKernels env) (nqCDefs env) TH.lamE (map return (nqLamPats env)) $ TH.letE (kernelDecQs ++ map return (nqDecs env)) $ if isMonadic && nqMorallyPure env then [|unsafePerformIO $(nqBody env)|] else [|$(nqBody env)|] where kernelDecQs :: [CudaKernel] -> [C.Definition] -> Q [DecQ] kernelDecQs [] _ = return [] kernelDecQs kerns defs = do -- liftIO $ putStrLn $ pretty 200 $ ppr defs bs <- liftIO $ Nvcc.compile defs modName <- TH.qNewName "module" return $ modDecQ modName bs : map (workBlockCounterDecQ modName) (concatMap cukernWorkBlocks kerns) ++ map (kernDecQ modName) kerns where -- Generate the binding for the 'CU.Module' containing the CUDA kernels. modDecQ :: TH.Name -> B.ByteString -> DecQ modDecQ modName bs = do let qbs = TH.litE (TH.stringL (B.unpack bs)) let qbody = [|unsafePerformIO $ CU.loadData $ B.pack $qbs|] TH.valD (TH.varP modName) (TH.normalB qbody) [] -- Generate bindings for a work block counter workBlockCounterDecQ :: TH.Name -> CudaWorkBlock -> DecQ workBlockCounterDecQ modName wb = do let blockCounterName = TH.mkName (cuworkBlockCounter wb) let qbody = [|unsafePerformIO $ CU.getPtr $(TH.varE modName) $(TH.stringE (cuworkBlockCounter wb))|] TH.valD (TH.tupP [TH.varP blockCounterName, TH.wildP]) (TH.normalB qbody) [] -- Generate the binding for the CUDA kernel @kern@. kernDecQ :: TH.Name -> CudaKernel -> DecQ kernDecQ modName kern = do let kernName = TH.mkName (cukernName kern) let qbody = [|unsafePerformIO $ CU.getFun $(TH.varE modName) $(TH.stringE (cukernName kern))|] TH.valD (TH.varP kernName) (TH.normalB qbody) [] -- | If you only want the default compiled version of a Nikola program, use -- 'compile'. The default compilation scheme compiles Nikola expressions to -- their "natural" Haskell representation, i.e., 'Exp t Double' is compiled to -- 'Double', and compiles Nikola arrays to Repa arrays with the type tag -- 'R.CUF'. compile :: forall a . (Compilable a (Compiled a), Reifiable a Exp) => a -> ExpQ compile a = compileSig a (undefined :: Compiled a) -- The 'Compiled' type function specifies the default compilation scheme for -- 'compile'. type family Compiled a :: * type instance Compiled (N.P ()) = IO () type instance Compiled (N.Exp a) = N.Rep (N.Exp a) type instance Compiled (N.Array r sh a) = R.Array R.CUF (Rsh sh) (N.Rep a) type instance Compiled (N.P (N.Array N.G sh a)) = IO (R.Array R.CUF (Rsh sh) (N.Rep a)) type instance Compiled (N.Exp a -> b) = N.Rep (N.Exp a) -> Compiled b type instance Compiled (N.Array N.G sh a -> b) = R.Array R.CUF (Rsh sh) (N.Rep a) -> Compiled b type instance Compiled (N.MArray N.G sh a -> b) = R.MArray R.CUF (Rsh sh) (N.Rep a) -> Compiled b -- The 'IsVal' type class tells us how to bind arguments in the form expected by -- the TH expression representation of a Nikola program and how to coerce the -- results returned by the Nikola program into the desired form. class IsVal a where bindArgs :: a -> NQ () coerceResult :: a -> ExpQ -> ExpQ #define baseTypeVal(ty) \ instance IsVal ty where { \ ; bindArgs _ = do \ { v <- fst <$> takeLamVar \ ; p <- liftQ $ TH.varP (mkName v) \ ; appendLamPats [p] \ } \ ; coerceResult _ = id \ } baseTypeVal(Bool) baseTypeVal(Int8) baseTypeVal(Int16) baseTypeVal(Int32) baseTypeVal(Int64) baseTypeVal(Word8) baseTypeVal(Word16) baseTypeVal(Word32) baseTypeVal(Word64) baseTypeVal(Float) baseTypeVal(Double) -- -- Val instance for CUDA Foreign arrays -- instance IsVal (R.Array R.CF rsh a) where bindArgs _ = do arr <- fst <$> takeLamVar rarr <- qNewName "repa_arr" p <- liftQ $ TH.varP rarr appendLamPats [p] modifyBody $ \qm -> [|do { let fdptr = R.toForeignDevPtr $(TH.varE rarr) ; $(lamsE [arr] qm) (NArray fdptr (R.extent $(TH.varE rarr))) } |] coerceResult _ qm = [|$qm >>= \(NArray fdptr sh) -> do { return $ R.fromForeignDevPtr sh fdptr } |] -- -- Val instance for CUDA UnboxedForeign arrays -- instance IsArrayVal (VCUF.Vector a) => IsVal (R.Array R.CUF rsh a) where bindArgs _ = do arr <- fst <$> takeLamVar rarr <- qNewName "repa_arr" p <- liftQ $ TH.varP rarr appendLamPats [p] modifyBody $ \qm -> [|do { let { v = R.toUnboxedForeign $(TH.varE rarr) } ; $(coerceArrayArg (undefined :: VCUF.Vector a)) v $ \ptrs -> $(lamsE [arr] qm) (NArray ptrs (R.extent $(TH.varE rarr))) } |] coerceResult _ qm = [|$qm >>= \(NArray fdptrs sh) -> do { let sz = R.size sh ; v <- $(coerceArrayResult (undefined :: VCUF.Vector a)) fdptrs (R.Z R.:. sz) ; return $ R.fromUnboxedForeign sh v } |] -- -- Val instance for mutable CUDA UnboxedForeign arrays -- instance IsArrayVal (MVCUF.IOVector a) => IsVal (R.MArray R.CUF sh a) where bindArgs _ = do arr <- fst <$> takeLamVar rarr <- qNewName "repa_marr" p <- liftQ $ TH.varP rarr appendLamPats [p] modifyBody $ \qm -> [|do { let { R.MCFUnboxed sh v = $(TH.varE rarr) } ; $(coerceArrayArg (undefined :: MVCUF.IOVector a)) v $ \ptrs -> $(lamsE [arr] qm) (NArray ptrs sh) } |] coerceResult _ qm = [|$qm >>= \(NArray fdptrs sh) -> do { let sz = R.size sh ; v <- $(coerceArrayResult (undefined :: MVCUF.IOVector a)) fdptrs (R.Z R.:. sz) ; return $ R.MCFUnboxed sh v } |] -- -- Val instances for array-like things -- -- The 'IsArrayVal' type class tells us how to bind an 'a' and how to convert an -- 'a' to and from a Repa CF array. class IsArrayVal a where coerceArrayArg :: a -> ExpQ coerceArrayResult :: a -> ExpQ instance IsArrayVal [a] => IsVal [a] where bindArgs _ = do arr <- fst <$> takeLamVar xs <- qNewName "xs" p <- liftQ $ TH.varP xs appendLamPats [p] modifyBody $ \qm -> [|$(coerceArrayArg (undefined :: [a])) $(TH.varE xs) $ \ptrs -> $(lamsE [arr] qm) (NArray ptrs (R.ix1 (length $(TH.varE xs)))) |] coerceResult _ qm = [|$qm >>= \(NArray fdptrs sh) -> $(coerceArrayResult (undefined :: [a])) fdptrs sh|] instance IsArrayVal (V.Vector a) => IsVal (V.Vector a) where bindArgs _ = do arr <- fst <$> takeLamVar xs <- qNewName "xs" p <- liftQ $ TH.varP xs appendLamPats [p] modifyBody $ \qm -> [|$(coerceArrayArg (undefined :: V.Vector a)) $(TH.varE xs) $ \ptrs -> $(lamsE [arr] qm) (NArray ptrs (R.ix1 (V.length $(TH.varE xs)))) |] coerceResult _ qm = [|$qm >>= \(NArray fdptrs sh) -> $(coerceArrayResult (undefined :: V.Vector a)) fdptrs sh|] instance IsArrayVal (VCS.Vector a) => IsVal (VCS.Vector a) where bindArgs _ = do arr <- fst <$> takeLamVar xs <- qNewName "xs" p <- liftQ $ TH.varP xs appendLamPats [p] modifyBody $ \qm -> [|$(coerceArrayArg (undefined :: VCS.Vector a)) $(TH.varE xs) $ \ptrs -> $(lamsE [arr] qm) (NArray ptrs (R.ix1 (VCS.length $(TH.varE xs)))) |] coerceResult _ qm = [|$qm >>= \(NArray fdptrs sh) -> $(coerceArrayResult (undefined :: VCS.Vector a)) fdptrs sh|] -- -- 'IsArrayVal' instances for lists -- #define baseTypeListArrayVal(ty) \ instance IsArrayVal [ty] where { \ ; coerceArrayArg _ = \ [|\xs kont -> \ do { let { n = length xs } \ ; fdptr <- CU.mallocForeignDevPtrArray n \ ; withArray xs $ \ptr -> \ CU.withForeignDevPtr fdptr $ \dptr -> \ CU.pokeArray n ptr dptr \ ; kont fdptr \ } \ |] \ ; coerceArrayResult _ = \ [|\fdptr (R.Z R.:. n) -> \ do { CU.withForeignDevPtr fdptr $ \dptr -> \ CU.peekListArray n dptr \ } \ |] \ } baseTypeListArrayVal(Int8) baseTypeListArrayVal(Int16) baseTypeListArrayVal(Int32) baseTypeListArrayVal(Int64) baseTypeListArrayVal(Word8) baseTypeListArrayVal(Word16) baseTypeListArrayVal(Word32) baseTypeListArrayVal(Word64) baseTypeListArrayVal(Float) baseTypeListArrayVal(Double) instance IsArrayVal [Bool] where coerceArrayArg _ = [|\xs kont -> do let n = length xs fdptr <- CU.mallocForeignDevPtrArray n withArray (map fromBool xs) $ \ptr -> CU.withForeignDevPtr fdptr $ \dptr -> CU.pokeArray n ptr dptr kont fdptr |] coerceArrayResult _ = [|\fdptr (R.Z R.:. n) -> do xs <- CU.withForeignDevPtr fdptr $ \dptr -> CU.peekListArray n dptr return $ map toBool xs |] instance (IsArrayVal [a], IsArrayVal [b]) => IsArrayVal [(a, b)] where coerceArrayArg _ = [|\xs kont -> do let (as, bs) = unzip xs $(coerceArrayArg (undefined :: [a])) as $ \arra -> do $(coerceArrayArg (undefined :: [b])) bs $ \arrb -> do kont (arra, arrb) |] coerceArrayResult _ = [|\(arra, arrb) sh -> do as <- $(coerceArrayResult (undefined :: [a])) arra sh bs <- $(coerceArrayResult (undefined :: [b])) arrb sh return (as `zip` bs) |] -- -- 'IsArrayVal' instances for Storable 'Vector's -- #define baseTypeStorableVectorArrayVal(ty) \ instance IsArrayVal (V.Vector ty) where { \ ; coerceArrayArg _ = \ [|\xs kont -> \ do { let { n = V.length xs } \ ; fdptr <- CU.mallocForeignDevPtrArray n \ ; V.unsafeWith xs $ \ptr -> \ CU.withForeignDevPtr fdptr $ \dptr -> \ CU.pokeArray n ptr dptr \ ; kont fdptr \ } \ |] \ ; coerceArrayResult _ = \ [|\fdptr (R.Z R.:. n) -> \ do { ptr <- liftIO $ mallocArray n \ ; CU.withForeignDevPtr fdptr $ \dptr -> \ CU.peekArray n dptr ptr \ ; fptr <- newForeignPtr_ ptr \ ; return $ V.unsafeFromForeignPtr0 fptr n \ } \ |] \ } baseTypeStorableVectorArrayVal(Int8) baseTypeStorableVectorArrayVal(Int16) baseTypeStorableVectorArrayVal(Int32) baseTypeStorableVectorArrayVal(Int64) baseTypeStorableVectorArrayVal(Word8) baseTypeStorableVectorArrayVal(Word16) baseTypeStorableVectorArrayVal(Word32) baseTypeStorableVectorArrayVal(Word64) baseTypeStorableVectorArrayVal(Float) baseTypeStorableVectorArrayVal(Double) -- -- 'IsArrayVal' instances for CUDA Storable 'Vector's -- #define baseTypeCUDAStorableVectorArrayVal(ty) \ instance IsArrayVal (VCS.Vector ty) where { \ ; coerceArrayArg _ = \ [|\v kont -> \ do { let { (fdptr, _) = VCS.unsafeToForeignDevPtr0 v } \ ; kont fdptr \ } \ |] \ ; coerceArrayResult _ = \ [|\fdptr (R.Z R.:. n) -> \ return $ VCS.unsafeFromForeignDevPtr0 fdptr n \ |] \ } baseTypeCUDAStorableVectorArrayVal(Int8) baseTypeCUDAStorableVectorArrayVal(Int16) baseTypeCUDAStorableVectorArrayVal(Int32) baseTypeCUDAStorableVectorArrayVal(Int64) baseTypeCUDAStorableVectorArrayVal(Word8) baseTypeCUDAStorableVectorArrayVal(Word16) baseTypeCUDAStorableVectorArrayVal(Word32) baseTypeCUDAStorableVectorArrayVal(Word64) baseTypeCUDAStorableVectorArrayVal(Float) baseTypeCUDAStorableVectorArrayVal(Double) -- -- 'IsArrayVal' instances for CUDA UnboxedForeign Vectors -- #define baseTypeCUDAUnboxedVectorArrayVal(ty,con) \ instance IsArrayVal (VCUF.Vector ty) where { \ ; coerceArrayArg _ = \ [|\(con v) kont -> \ do { let { (fdptr, _) = VCS.unsafeToForeignDevPtr0 v } \ ; kont fdptr \ } \ |] \ ; coerceArrayResult _ = \ [|\fdptr (R.Z R.:. n) -> \ return $ con $ VCS.unsafeFromForeignDevPtr0 fdptr n \ |] \ } baseTypeCUDAUnboxedVectorArrayVal(Int8, VCUF.V_Int8) baseTypeCUDAUnboxedVectorArrayVal(Int16, VCUF.V_Int16) baseTypeCUDAUnboxedVectorArrayVal(Int32, VCUF.V_Int32) baseTypeCUDAUnboxedVectorArrayVal(Int64, VCUF.V_Int64) baseTypeCUDAUnboxedVectorArrayVal(Word8, VCUF.V_Word8) baseTypeCUDAUnboxedVectorArrayVal(Word16, VCUF.V_Word16) baseTypeCUDAUnboxedVectorArrayVal(Word32, VCUF.V_Word32) baseTypeCUDAUnboxedVectorArrayVal(Word64, VCUF.V_Word64) baseTypeCUDAUnboxedVectorArrayVal(Float, VCUF.V_Float) baseTypeCUDAUnboxedVectorArrayVal(Double, VCUF.V_Double) instance ( IsArrayVal (VCUF.Vector a) , IsArrayVal (VCUF.Vector b) ) => IsArrayVal (VCUF.Vector (a, b)) where coerceArrayArg _ = [|\(VCUF.V_2 _ v_a v_b) kont -> $(coerceArrayArg (undefined :: VCUF.Vector a)) v_a $ \ptr_a -> $(coerceArrayArg (undefined :: VCUF.Vector b)) v_b $ \ptr_b -> kont (ptr_a, ptr_b) |] coerceArrayResult _ = [|\(ptr_a, ptr_b) sh@(R.Z R.:. n) -> do { v_a <- $(coerceArrayResult (undefined :: VCUF.Vector a)) ptr_a sh ; v_b <- $(coerceArrayResult (undefined :: VCUF.Vector b)) ptr_b sh ; return $ VCUF.V_2 n v_a v_b } |] -- -- 'IsArrayVal' instances for mutable CUDA UnboxedForeign Vectors -- #define baseTypeCUDAUnboxedMVectorArrayVal(ty,con) \ instance IsArrayVal (MVCUF.IOVector ty) where { \ ; coerceArrayArg _ = \ [|\(con v) kont -> \ do { let { (fdptr, _) = MVCS.unsafeToForeignDevPtr0 v } \ ; kont fdptr \ } \ |] \ ; coerceArrayResult _ = \ [|\fdptr (R.Z R.:. n) -> \ return $ con $ MVCS.unsafeFromForeignDevPtr0 fdptr n \ |] \ } baseTypeCUDAUnboxedMVectorArrayVal(Int8, MVCUF.MV_Int8) baseTypeCUDAUnboxedMVectorArrayVal(Int16, MVCUF.MV_Int16) baseTypeCUDAUnboxedMVectorArrayVal(Int32, MVCUF.MV_Int32) baseTypeCUDAUnboxedMVectorArrayVal(Int64, MVCUF.MV_Int64) baseTypeCUDAUnboxedMVectorArrayVal(Word8, MVCUF.MV_Word8) baseTypeCUDAUnboxedMVectorArrayVal(Word16, MVCUF.MV_Word16) baseTypeCUDAUnboxedMVectorArrayVal(Word32, MVCUF.MV_Word32) baseTypeCUDAUnboxedMVectorArrayVal(Word64, MVCUF.MV_Word64) baseTypeCUDAUnboxedMVectorArrayVal(Float, MVCUF.MV_Float) baseTypeCUDAUnboxedMVectorArrayVal(Double, MVCUF.MV_Double) instance ( IsArrayVal (MVCUF.IOVector a) , IsArrayVal (MVCUF.IOVector b) ) => IsArrayVal (MVCUF.IOVector (a, b)) where coerceArrayArg _ = [|\(MVCUF.MV_2 _ v_a v_b) kont -> $(coerceArrayArg (undefined :: MVCUF.IOVector a)) v_a $ \ptr_a -> $(coerceArrayArg (undefined :: MVCUF.IOVector b)) v_b $ \ptr_b -> kont (ptr_a, ptr_b) |] coerceArrayResult _ = [|\(ptr_a, ptr_b) sh@(R.Z R.:. n) -> do { v_a <- $(coerceArrayResult (undefined :: MVCUF.IOVector a)) ptr_a sh ; v_b <- $(coerceArrayResult (undefined :: MVCUF.IOVector b)) ptr_b sh ; return $ MVCUF.MV_2 n v_a v_b } |]
mainland/nikola
src/Data/Array/Nikola/Backend/CUDA/TH.hs
bsd-3-clause
32,725
0
19
10,998
6,933
3,668
3,265
-1
-1
{-# LANGUAGE DataKinds, GADTs #-} -- | Semantics of 'Command.Cmd' client commands that return server commands. -- A couple of them do not take time, the rest does. -- Here prompts and menus and displayed, but any feedback resulting -- from the commands (e.g., from inventory manipulation) is generated later on, -- for all clients that witness the results of the commands. -- TODO: document module Game.LambdaHack.Client.UI.HandleHumanGlobalClient ( -- * Commands that usually take time moveRunHuman, waitHuman, moveItemHuman, describeItemHuman , projectHuman, applyHuman, alterDirHuman, triggerTileHuman , runOnceAheadHuman, moveOnceToCursorHuman , runOnceToCursorHuman, continueToCursorHuman -- * Commands that never take time , gameRestartHuman, gameExitHuman, gameSaveHuman, tacticHuman, automateHuman ) where import Control.Applicative import Control.Exception.Assert.Sugar import Control.Monad import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import Data.List import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified NLP.Miniutter.English as MU import Game.LambdaHack.Client.BfsClient import Game.LambdaHack.Client.CommonClient import qualified Game.LambdaHack.Client.Key as K import Game.LambdaHack.Client.MonadClient import Game.LambdaHack.Client.State import Game.LambdaHack.Client.UI.Config import Game.LambdaHack.Client.UI.HandleHumanLocalClient import Game.LambdaHack.Client.UI.HumanCmd (Trigger (..)) import Game.LambdaHack.Client.UI.InventoryClient import Game.LambdaHack.Client.UI.MonadClientUI import Game.LambdaHack.Client.UI.MsgClient import Game.LambdaHack.Client.UI.RunClient import Game.LambdaHack.Client.UI.WidgetClient import Game.LambdaHack.Common.Ability import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import Game.LambdaHack.Common.ItemStrongest import qualified Game.LambdaHack.Common.Kind as Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.Msg import Game.LambdaHack.Common.Point import Game.LambdaHack.Common.Random import Game.LambdaHack.Common.Request import Game.LambdaHack.Common.State import qualified Game.LambdaHack.Common.Tile as Tile import Game.LambdaHack.Common.Vector import qualified Game.LambdaHack.Content.ItemKind as IK import Game.LambdaHack.Content.ModeKind import Game.LambdaHack.Content.TileKind (TileKind) import qualified Game.LambdaHack.Content.TileKind as TK -- * Move and Run moveRunHuman :: MonadClientUI m => Bool -> Bool -> Bool -> Bool -> Vector -> m (SlideOrCmd RequestAnyAbility) moveRunHuman initialStep finalGoal run runAhead dir = do tgtMode <- getsClient stgtMode if isJust tgtMode then Left <$> moveCursorHuman dir (if run then 10 else 1) else do arena <- getArenaUI leader <- getLeaderUI sb <- getsState $ getActorBody leader fact <- getsState $ (EM.! bfid sb) . sfactionD -- Start running in the given direction. The first turn of running -- succeeds much more often than subsequent turns, because we ignore -- most of the disturbances, since the player is mostly aware of them -- and still explicitly requests a run, knowing how it behaves. sel <- getsClient sselected let runMembers = if runAhead || noRunWithMulti fact then [leader] -- TODO: warn? else ES.toList (ES.delete leader sel) ++ [leader] runParams = RunParams { runLeader = leader , runMembers , runInitial = True , runStopMsg = Nothing , runWaiting = 0 } macroRun25 = ["CTRL-comma", "CTRL-V"] when (initialStep && run) $ do modifyClient $ \cli -> cli {srunning = Just runParams} when runAhead $ modifyClient $ \cli -> cli {slastPlay = map K.mkKM macroRun25 ++ slastPlay cli} -- When running, the invisible actor is hit (not displaced!), -- so that running in the presence of roving invisible -- actors is equivalent to moving (with visible actors -- this is not a problem, since runnning stops early enough). -- TODO: stop running at invisible actor let tpos = bpos sb `shift` dir -- We start by checking actors at the the target position, -- which gives a partial information (actors can be invisible), -- as opposed to accessibility (and items) which are always accurate -- (tiles can't be invisible). tgts <- getsState $ posToActors tpos arena case tgts of [] -> do -- move or search or alter runStopOrCmd <- moveSearchAlterAid leader dir case runStopOrCmd of Left stopMsg -> failWith stopMsg Right runCmd -> -- Don't check @initialStep@ and @finalGoal@ -- and don't stop going to target: door opening is mundane enough. return $ Right runCmd [(target, _)] | run && initialStep -> -- No @stopPlayBack@: initial displace is benign enough. -- Displacing requires accessibility, but it's checked later on. fmap RequestAnyAbility <$> displaceAid target _ : _ : _ | run && initialStep -> do let !_A = assert (all (bproj . snd) tgts) () failSer DisplaceProjectiles (target, tb) : _ | initialStep && finalGoal -> do stopPlayBack -- don't ever auto-repeat melee -- No problem if there are many projectiles at the spot. We just -- attack the first one. -- We always see actors from our own faction. if bfid tb == bfid sb && not (bproj tb) then do let autoLvl = snd $ autoDungeonLevel fact if autoLvl then failSer NoChangeLvlLeader else do -- Select adjacent actor by bumping into him. Takes no time. success <- pickLeader True target let !_A = assert (success `blame` "bump self" `twith` (leader, target, tb)) () return $ Left mempty else -- Attacking does not require full access, adjacency is enough. fmap RequestAnyAbility <$> meleeAid target _ : _ -> failWith "actor in the way" -- | Actor atttacks an enemy actor or his own projectile. meleeAid :: MonadClientUI m => ActorId -> m (SlideOrCmd (RequestTimed 'AbMelee)) meleeAid target = do leader <- getLeaderUI sb <- getsState $ getActorBody leader tb <- getsState $ getActorBody target sfact <- getsState $ (EM.! bfid sb) . sfactionD mel <- pickWeaponClient leader target case mel of Nothing -> failWith "nothing to melee with" Just wp -> do let returnCmd = return $ Right wp res | bproj tb || isAtWar sfact (bfid tb) = returnCmd | isAllied sfact (bfid tb) = do go1 <- displayYesNo ColorBW "You are bound by an alliance. Really attack?" if not go1 then failWith "attack canceled" else returnCmd | otherwise = do go2 <- displayYesNo ColorBW "This attack will start a war. Are you sure?" if not go2 then failWith "attack canceled" else returnCmd res -- Seeing the actor prevents altering a tile under it, but that -- does not limit the player, he just doesn't waste a turn -- on a failed altering. -- | Actor swaps position with another. displaceAid :: MonadClientUI m => ActorId -> m (SlideOrCmd (RequestTimed 'AbDisplace)) displaceAid target = do cops <- getsState scops leader <- getLeaderUI sb <- getsState $ getActorBody leader tb <- getsState $ getActorBody target tfact <- getsState $ (EM.! bfid tb) . sfactionD activeItems <- activeItemsClient target disp <- getsState $ dispEnemy leader target activeItems let actorMaxSk = sumSkills activeItems immobile = EM.findWithDefault 0 AbMove actorMaxSk <= 0 spos = bpos sb tpos = bpos tb adj = checkAdjacent sb tb atWar = isAtWar tfact (bfid sb) if not adj then failSer DisplaceDistant else if not (bproj tb) && atWar && actorDying tb then failSer DisplaceDying else if not (bproj tb) && atWar && braced tb then failSer DisplaceBraced else if not (bproj tb) && atWar && immobile then failSer DisplaceImmobile else if not disp && atWar then failSer DisplaceSupported else do let lid = blid sb lvl <- getLevel lid -- Displacing requires full access. if accessible cops lvl spos tpos then do tgts <- getsState $ posToActors tpos lid case tgts of [] -> assert `failure` (leader, sb, target, tb) [_] -> return $ Right $ ReqDisplace target _ -> failSer DisplaceProjectiles else failSer DisplaceAccess -- | Actor moves or searches or alters. No visible actor at the position. moveSearchAlterAid :: MonadClient m => ActorId -> Vector -> m (Either Msg RequestAnyAbility) moveSearchAlterAid source dir = do [email protected]{cotile} <- getsState scops sb <- getsState $ getActorBody source actorSk <- actorSkillsClient source lvl <- getLevel $ blid sb let skill = EM.findWithDefault 0 AbAlter actorSk spos = bpos sb -- source position tpos = spos `shift` dir -- target position t = lvl `at` tpos runStopOrCmd -- Movement requires full access. | accessible cops lvl spos tpos = -- A potential invisible actor is hit. War started without asking. Right $ RequestAnyAbility $ ReqMove dir -- No access, so search and/or alter the tile. Non-walkability is -- not implied by the lack of access. | not (Tile.isWalkable cotile t) && (not (knownLsecret lvl) || (isSecretPos lvl tpos -- possible secrets here && (Tile.isSuspect cotile t -- not yet searched || Tile.hideAs cotile t /= t)) -- search again || Tile.isOpenable cotile t || Tile.isClosable cotile t || Tile.isChangeable cotile t) = if skill < 1 then Left $ showReqFailure AlterUnskilled else if EM.member tpos $ lfloor lvl then Left $ showReqFailure AlterBlockItem else Right $ RequestAnyAbility $ ReqAlter tpos Nothing -- We don't use MoveSer, because we don't hit invisible actors. -- The potential invisible actor, e.g., in a wall or in -- an inaccessible doorway, is made known, taking a turn. -- If server performed an attack for free -- on the invisible actor anyway, the player (or AI) -- would be tempted to repeatedly hit random walls -- in hopes of killing a monster lurking within. -- If the action had a cost, misclicks would incur the cost, too. -- Right now the player may repeatedly alter tiles trying to learn -- about invisible pass-wall actors, but when an actor detected, -- it costs a turn and does not harm the invisible actors, -- so it's not so tempting. -- Ignore a known boring, not accessible tile. | otherwise = Left "never mind" return $! runStopOrCmd -- * Wait -- | Leader waits a turn (and blocks, etc.). waitHuman :: MonadClientUI m => m (RequestTimed 'AbWait) waitHuman = do modifyClient $ \cli -> cli {swaitTimes = abs (swaitTimes cli) + 1} return ReqWait -- * MoveItem moveItemHuman :: forall m. MonadClientUI m => [CStore] -> CStore -> Maybe MU.Part -> Bool -> m (SlideOrCmd (RequestTimed 'AbMoveItem)) moveItemHuman cLegalRaw destCStore mverb auto = do let !_A = assert (destCStore `notElem` cLegalRaw) () let verb = fromMaybe (MU.Text $ verbCStore destCStore) mverb leader <- getLeaderUI b <- getsState $ getActorBody leader activeItems <- activeItemsClient leader -- This calmE is outdated when one of the items increases max Calm -- (e.g., in pickup, which handles many items at once), but this is OK, -- the server accepts item movement based on calm at the start, not end -- or in the middle. -- The calmE is inaccurate also if an item not IDed, but that's intended -- and the server will ignore and warn (and content may avoid that, -- e.g., making all rings identified) let calmE = calmEnough b activeItems cLegal | calmE = cLegalRaw | destCStore == CSha = [] | otherwise = delete CSha cLegalRaw ret4 :: MonadClientUI m => CStore -> [(ItemId, ItemFull)] -> Int -> [(ItemId, Int, CStore, CStore)] -> m (Either Slideshow [(ItemId, Int, CStore, CStore)]) ret4 _ [] _ acc = return $ Right $ reverse acc ret4 fromCStore ((iid, itemFull) : rest) oldN acc = do let k = itemK itemFull retRec toCStore = let n = oldN + if toCStore == CEqp then k else 0 in ret4 fromCStore rest n ((iid, k, fromCStore, toCStore) : acc) if cLegalRaw == [CGround] -- normal pickup then case destCStore of CEqp | calmE && goesIntoSha itemFull -> retRec CSha CEqp | not $ goesIntoEqp itemFull -> retRec CInv CEqp | eqpOverfull b (oldN + k) -> do -- If this stack doesn't fit, we don't equip any part of it, -- but we may equip a smaller stack later in the same pickup. -- TODO: try to ask for a number of items, thus giving the player -- the option of picking up a part. let fullWarn = if eqpOverfull b (oldN + 1) then EqpOverfull else EqpStackFull msgAdd $ "Warning:" <+> showReqFailure fullWarn <> "." retRec $ if calmE then CSha else CInv _ -> retRec destCStore else case destCStore of CEqp | eqpOverfull b (oldN + k) -> do -- If the chosen number from the stack doesn't fit, -- we don't equip any part of it and we exit item manipulation. let fullWarn = if eqpOverfull b (oldN + 1) then EqpOverfull else EqpStackFull failSer fullWarn _ -> retRec destCStore prompt = makePhrase ["What to", verb] promptEqp = makePhrase ["What consumable to", verb] p :: CStore -> (Text, m Suitability) p cstore = if cstore `elem` [CEqp, CSha] && cLegalRaw /= [CGround] then (promptEqp, return $ SuitsSomething goesIntoEqp) else (prompt, return SuitsEverything) (promptGeneric, psuit) = p destCStore ggi <- if auto then getAnyItems psuit prompt promptGeneric cLegalRaw cLegal False False else getAnyItems psuit prompt promptGeneric cLegalRaw cLegal True True case ggi of Right (l, MStore fromCStore) -> do leader2 <- getLeaderUI b2 <- getsState $ getActorBody leader2 activeItems2 <- activeItemsClient leader2 let calmE2 = calmEnough b2 activeItems2 -- This is not ideal, because the failure message comes late, -- but it's simple and good enough. if not calmE2 && destCStore == CSha then failSer ItemNotCalm else do l4 <- ret4 fromCStore l 0 [] return $! case l4 of Left sli -> Left sli Right [] -> assert `failure` ggi Right lr -> Right $ ReqMoveItems lr Left slides -> return $ Left slides _ -> assert `failure` ggi -- * DescribeItem -- | Display items from a given container store and describe the chosen one. describeItemHuman :: MonadClientUI m => ItemDialogMode -> m (SlideOrCmd (RequestTimed 'AbMoveItem)) describeItemHuman = describeItemC -- * Project projectHuman :: forall m. MonadClientUI m => [Trigger] -> m (SlideOrCmd (RequestTimed 'AbProject)) projectHuman ts = do leader <- getLeaderUI lidV <- viewedLevel oldTgtMode <- getsClient stgtMode -- Show the targeting line, temporarily. modifyClient $ \cli -> cli {stgtMode = Just $ TgtMode lidV} -- Set cursor to the personal target, permanently. tgt <- getsClient $ getTarget leader modifyClient $ \cli -> cli {scursor = fromMaybe (scursor cli) tgt} -- Let the user pick the item to fling. let posFromCursor :: m (Either Msg Point) posFromCursor = do canAim <- aidTgtAims leader lidV Nothing case canAim of Right newEps -> do -- Modify @seps@, permanently. modifyClient $ \cli -> cli {seps = newEps} mpos <- aidTgtToPos leader lidV Nothing case mpos of Nothing -> assert `failure` (tgt, leader, lidV) Just pos -> do munit <- projectCheck pos case munit of Nothing -> return $ Right pos Just reqFail -> return $ Left $ showReqFailure reqFail Left cause -> return $ Left cause mitem <- projectItem ts posFromCursor outcome <- case mitem of Right (iid, fromCStore) -> do mpos <- posFromCursor case mpos of Right pos -> do eps <- getsClient seps return $ Right $ ReqProject pos eps iid fromCStore Left cause -> failWith cause Left sli -> return $ Left sli modifyClient $ \cli -> cli {stgtMode = oldTgtMode} return outcome projectCheck :: MonadClientUI m => Point -> m (Maybe ReqFailure) projectCheck tpos = do Kind.COps{cotile} <- getsState scops leader <- getLeaderUI eps <- getsClient seps sb <- getsState $ getActorBody leader let lid = blid sb spos = bpos sb Level{lxsize, lysize} <- getLevel lid case bla lxsize lysize eps spos tpos of Nothing -> return $ Just ProjectAimOnself Just [] -> assert `failure` "project from the edge of level" `twith` (spos, tpos, sb) Just (pos : _) -> do lvl <- getLevel lid let t = lvl `at` pos if not $ Tile.isWalkable cotile t then return $ Just ProjectBlockTerrain else do lab <- getsState $ posToActors pos lid if all (bproj . snd) lab then return Nothing else return $ Just ProjectBlockActor projectItem :: forall m. MonadClientUI m => [Trigger] -> m (Either Msg Point) -> m (SlideOrCmd (ItemId, CStore)) projectItem ts posFromCursor = do leader <- getLeaderUI b <- getsState $ getActorBody leader activeItems <- activeItemsClient leader actorSk <- actorSkillsClient leader let skill = EM.findWithDefault 0 AbProject actorSk calmE = calmEnough b activeItems cLegalRaw = [CGround, CInv, CEqp, CSha] cLegal | calmE = cLegalRaw | otherwise = delete CSha cLegalRaw (verb1, object1) = case ts of [] -> ("aim", "item") tr : _ -> (verb tr, object tr) triggerSyms = triggerSymbols ts psuitReq :: m (Either Msg (ItemFull -> Either ReqFailure Bool)) psuitReq = do mpos <- posFromCursor case mpos of Left err -> return $ Left err Right pos -> return $ Right $ \itemFull@ItemFull{itemBase} -> do let legal = permittedProject triggerSyms False skill itemFull b activeItems case legal of Left{} -> legal Right False -> legal Right True -> Right $ totalRange itemBase >= chessDist (bpos b) pos psuit :: m Suitability psuit = do mpsuitReq <- psuitReq case mpsuitReq of -- If target invalid, no item is considered a (suitable) missile. Left err -> return $ SuitsNothing err Right psuitReqFun -> return $ SuitsSomething $ \itemFull -> case psuitReqFun itemFull of Left _ -> False Right suit -> suit prompt = makePhrase ["What", object1, "to", verb1] promptGeneric = "What to fling" ggi <- getGroupItem psuit prompt promptGeneric True cLegalRaw cLegal case ggi of Right ((iid, itemFull), MStore fromCStore) -> do mpsuitReq <- psuitReq case mpsuitReq of Left err -> failWith err Right psuitReqFun -> case psuitReqFun itemFull of Left reqFail -> failSer reqFail Right _ -> return $ Right (iid, fromCStore) Left slides -> return $ Left slides _ -> assert `failure` ggi triggerSymbols :: [Trigger] -> [Char] triggerSymbols [] = [] triggerSymbols (ApplyItem{symbol} : ts) = symbol : triggerSymbols ts triggerSymbols (_ : ts) = triggerSymbols ts -- * Apply applyHuman :: MonadClientUI m => [Trigger] -> m (SlideOrCmd (RequestTimed 'AbApply)) applyHuman ts = do leader <- getLeaderUI b <- getsState $ getActorBody leader actorSk <- actorSkillsClient leader let skill = EM.findWithDefault 0 AbApply actorSk activeItems <- activeItemsClient leader localTime <- getsState $ getLocalTime (blid b) let calmE = calmEnough b activeItems cLegalRaw = [CGround, CInv, CEqp, CSha] cLegal | calmE = cLegalRaw | otherwise = delete CSha cLegalRaw (verb1, object1) = case ts of [] -> ("apply", "item") tr : _ -> (verb tr, object tr) triggerSyms = triggerSymbols ts p itemFull = permittedApply triggerSyms localTime skill itemFull b activeItems prompt = makePhrase ["What", object1, "to", verb1] promptGeneric = "What to apply" ggi <- getGroupItem (return $ SuitsSomething $ either (const False) id . p) prompt promptGeneric False cLegalRaw cLegal case ggi of Right ((iid, itemFull), MStore fromCStore) -> case p itemFull of Left reqFail -> failSer reqFail Right _ -> return $ Right $ ReqApply iid fromCStore Left slides -> return $ Left slides _ -> assert `failure` ggi -- * AlterDir -- TODO: accept mouse, too -- | Ask for a direction and alter a tile, if possible. alterDirHuman :: MonadClientUI m => [Trigger] -> m (SlideOrCmd (RequestTimed 'AbAlter)) alterDirHuman ts = do Config{configVi, configLaptop} <- askConfig let verb1 = case ts of [] -> "alter" tr : _ -> verb tr keys = map (K.toKM K.NoModifier) (K.dirAllKey configVi configLaptop) prompt = makePhrase ["What to", verb1 <> "? [movement key"] me <- displayChoiceUI prompt emptyOverlay keys case me of Left slides -> failSlides slides Right e -> K.handleDir configVi configLaptop e (`alterTile` ts) (failWith "never mind") -- | Player tries to alter a tile using a feature. alterTile :: MonadClientUI m => Vector -> [Trigger] -> m (SlideOrCmd (RequestTimed 'AbAlter)) alterTile dir ts = do [email protected]{cotile} <- getsState scops leader <- getLeaderUI b <- getsState $ getActorBody leader actorSk <- actorSkillsClient leader lvl <- getLevel $ blid b as <- getsState $ actorList (const True) (blid b) let skill = EM.findWithDefault 0 AbAlter actorSk tpos = bpos b `shift` dir t = lvl `at` tpos alterFeats = alterFeatures ts case filter (\feat -> Tile.hasFeature cotile feat t) alterFeats of _ | skill < 1 -> failSer AlterUnskilled [] -> failWith $ guessAlter cops alterFeats t feat : _ -> if EM.notMember tpos $ lfloor lvl then if unoccupied as tpos then return $ Right $ ReqAlter tpos $ Just feat else failSer AlterBlockActor else failSer AlterBlockItem alterFeatures :: [Trigger] -> [TK.Feature] alterFeatures [] = [] alterFeatures (AlterFeature{feature} : ts) = feature : alterFeatures ts alterFeatures (_ : ts) = alterFeatures ts -- | Guess and report why the bump command failed. guessAlter :: Kind.COps -> [TK.Feature] -> Kind.Id TileKind -> Msg guessAlter Kind.COps{cotile} (TK.OpenTo _ : _) t | Tile.isClosable cotile t = "already open" guessAlter _ (TK.OpenTo _ : _) _ = "cannot be opened" guessAlter Kind.COps{cotile} (TK.CloseTo _ : _) t | Tile.isOpenable cotile t = "already closed" guessAlter _ (TK.CloseTo _ : _) _ = "cannot be closed" guessAlter _ _ _ = "never mind" -- * TriggerTile -- | Leader tries to trigger the tile he's standing on. triggerTileHuman :: MonadClientUI m => [Trigger] -> m (SlideOrCmd (RequestTimed 'AbTrigger)) triggerTileHuman ts = do tgtMode <- getsClient stgtMode if isJust tgtMode then do let getK tfs = case tfs of TriggerFeature {feature = TK.Cause (IK.Ascend k)} : _ -> Just k _ : rest -> getK rest [] -> Nothing mk = getK ts case mk of Nothing -> failWith "never mind" Just k -> Left <$> tgtAscendHuman k else triggerTile ts -- | Player tries to trigger a tile using a feature. triggerTile :: MonadClientUI m => [Trigger] -> m (SlideOrCmd (RequestTimed 'AbTrigger)) triggerTile ts = do [email protected]{cotile} <- getsState scops leader <- getLeaderUI b <- getsState $ getActorBody leader lvl <- getLevel $ blid b let t = lvl `at` bpos b triggerFeats = triggerFeatures ts case filter (\feat -> Tile.hasFeature cotile feat t) triggerFeats of [] -> failWith $ guessTrigger cops triggerFeats t feat : _ -> do go <- verifyTrigger leader feat case go of Right () -> return $ Right $ ReqTrigger $ Just feat Left slides -> return $ Left slides triggerFeatures :: [Trigger] -> [TK.Feature] triggerFeatures [] = [] triggerFeatures (TriggerFeature{feature} : ts) = feature : triggerFeatures ts triggerFeatures (_ : ts) = triggerFeatures ts -- | Verify important feature triggers, such as fleeing the dungeon. verifyTrigger :: MonadClientUI m => ActorId -> TK.Feature -> m (SlideOrCmd ()) verifyTrigger leader feat = case feat of TK.Cause IK.Escape{} -> do b <- getsState $ getActorBody leader side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD if not (fcanEscape $ gplayer fact) then failWith "This is the way out, but where would you go in this alien world?" else do go <- displayYesNo ColorFull "This is the way out. Really leave now?" if not go then failWith "game resumed" else do (_, total) <- getsState $ calculateTotal b if total == 0 then do -- The player can back off at each of these steps. go1 <- displayMore ColorBW "Afraid of the challenge? Leaving so soon and empty-handed?" if not go1 then failWith "brave soul!" else do go2 <- displayMore ColorBW "Next time try to grab some loot before escape!" if not go2 then failWith "here's your chance!" else return $ Right () else return $ Right () _ -> return $ Right () -- | Guess and report why the bump command failed. guessTrigger :: Kind.COps -> [TK.Feature] -> Kind.Id TileKind -> Msg guessTrigger Kind.COps{cotile} fs@(TK.Cause (IK.Ascend k) : _) t | Tile.hasFeature cotile (TK.Cause (IK.Ascend (-k))) t = if k > 0 then "the way goes down, not up" else if k < 0 then "the way goes up, not down" else assert `failure` fs guessTrigger _ fs@(TK.Cause (IK.Ascend k) : _) _ = if k > 0 then "cannot ascend" else if k < 0 then "cannot descend" else assert `failure` fs guessTrigger _ _ _ = "never mind" -- * RunOnceAhead runOnceAheadHuman :: MonadClientUI m => m (SlideOrCmd RequestAnyAbility) runOnceAheadHuman = do side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD leader <- getLeaderUI srunning <- getsClient srunning -- When running, stop if disturbed. If not running, stop at once. case srunning of Nothing -> do stopPlayBack return $ Left mempty Just RunParams{runMembers} | noRunWithMulti fact && runMembers /= [leader] -> do stopPlayBack Config{configRunStopMsgs} <- askConfig if configRunStopMsgs then failWith "run stop: automatic leader change" else return $ Left mempty Just runParams -> do arena <- getArenaUI runOutcome <- continueRun arena runParams case runOutcome of Left stopMsg -> do stopPlayBack Config{configRunStopMsgs} <- askConfig if configRunStopMsgs then failWith $ "run stop:" <+> stopMsg else return $ Left mempty Right runCmd -> return $ Right runCmd -- * MoveOnceToCursor moveOnceToCursorHuman :: MonadClientUI m => m (SlideOrCmd RequestAnyAbility) moveOnceToCursorHuman = goToCursor True False goToCursor :: MonadClientUI m => Bool -> Bool -> m (SlideOrCmd RequestAnyAbility) goToCursor initialStep run = do tgtMode <- getsClient stgtMode -- Movement is legal only outside targeting mode. if isJust tgtMode then failWith "cannot move in aiming mode" else do leader <- getLeaderUI b <- getsState $ getActorBody leader cursorPos <- cursorToPos case cursorPos of Nothing -> failWith "crosshair position invalid" Just c | c == bpos b -> if initialStep then return $ Right $ RequestAnyAbility ReqWait else do report <- getsClient sreport if nullReport report then return $ Left mempty -- Mark that the messages are accumulated, not just from last move. else failWith "crosshair now reached" Just c -> do running <- getsClient srunning case running of -- Don't use running params from previous run or goto-cursor. Just paramOld | not initialStep -> do arena <- getArenaUI runOutcome <- multiActorGoTo arena c paramOld case runOutcome of Left stopMsg -> failWith stopMsg Right (finalGoal, dir) -> moveRunHuman initialStep finalGoal run False dir _ -> do let !_A = assert (initialStep || not run) () (_, mpath) <- getCacheBfsAndPath leader c case mpath of Nothing -> failWith "no route to crosshair" Just [] -> assert `failure` (leader, b, c) Just (p1 : _) -> do let finalGoal = p1 == c dir = towards (bpos b) p1 moveRunHuman initialStep finalGoal run False dir multiActorGoTo :: MonadClient m => LevelId -> Point -> RunParams -> m (Either Msg (Bool, Vector)) multiActorGoTo arena c paramOld = case paramOld of RunParams{runMembers = []} -> return $ Left "selected actors no longer there" RunParams{runMembers = r : rs, runWaiting} -> do onLevel <- getsState $ memActor r arena if not onLevel then do let paramNew = paramOld {runMembers = rs} multiActorGoTo arena c paramNew else do s <- getState modifyClient $ updateLeader r s let runMembersNew = rs ++ [r] paramNew = paramOld { runMembers = runMembersNew , runWaiting = 0} b <- getsState $ getActorBody r (_, mpath) <- getCacheBfsAndPath r c case mpath of Nothing -> return $ Left "no route to crosshair" Just [] -> -- This actor already at goal; will be caught in goToCursor. return $ Left "" Just (p1 : _) -> do let finalGoal = p1 == c dir = towards (bpos b) p1 tpos = bpos b `shift` dir tgts <- getsState $ posToActors tpos arena case tgts of [] -> do modifyClient $ \cli -> cli {srunning = Just paramNew} return $ Right (finalGoal, dir) [(target, _)] | target `elem` rs || runWaiting <= length rs -> -- Let r wait until all others move. Mark it in runWaiting -- to avoid cycles. When all wait for each other, fail. multiActorGoTo arena c paramNew{runWaiting=runWaiting + 1} _ -> return $ Left "actor in the way" -- * RunOnceToCursor runOnceToCursorHuman :: MonadClientUI m => m (SlideOrCmd RequestAnyAbility) runOnceToCursorHuman = goToCursor True True -- * ContinueToCursor continueToCursorHuman :: MonadClientUI m => m (SlideOrCmd RequestAnyAbility) continueToCursorHuman = goToCursor False False{-irrelevant-} -- * GameRestart; does not take time gameRestartHuman :: MonadClientUI m => GroupName ModeKind -> m (SlideOrCmd RequestUI) gameRestartHuman t = do let restart = do leader <- getLeaderUI snxtDiff <- getsClient snxtDiff Config{configHeroNames} <- askConfig return $ Right $ ReqUIGameRestart leader t snxtDiff configHeroNames escAI <- getsClient sescAI if escAI == EscAIExited then restart else do let msg = "You just requested a new" <+> tshow t <+> "game." b1 <- displayMore ColorFull msg if not b1 then failWith "never mind" else do b2 <- displayYesNo ColorBW "Current progress will be lost! Really restart the game?" msg2 <- rndToAction $ oneOf [ "yea, would be a pity to leave them all to die" , "yea, a shame to get your own team stranded" ] if not b2 then failWith msg2 else restart -- * GameExit; does not take time gameExitHuman :: MonadClientUI m => m (SlideOrCmd RequestUI) gameExitHuman = do go <- displayYesNo ColorFull "Really save and exit?" if go then do leader <- getLeaderUI return $ Right $ ReqUIGameExit leader else failWith "save and exit canceled" -- * GameSave; does not take time gameSaveHuman :: MonadClientUI m => m RequestUI gameSaveHuman = do -- Announce before the saving started, since it can take some time -- and may slow down the machine, even if not block the client. -- TODO: do not save to history: msgAdd "Saving game backup." return ReqUIGameSave -- * Tactic; does not take time -- Note that the difference between seek-target and follow-the-leader tactic -- can influence even a faction with passive actors. E.g., if a passive actor -- has an extra active skill from equipment, he moves every turn. -- TODO: set tactic for allied passive factions, too or all allied factions -- and perhaps even factions with a leader should follow our leader -- and his target, not their leader. tacticHuman :: MonadClientUI m => m (SlideOrCmd RequestUI) tacticHuman = do fid <- getsClient sside fromT <- getsState $ ftactic . gplayer . (EM.! fid) . sfactionD let toT = if fromT == maxBound then minBound else succ fromT go <- displayMore ColorFull $ "Current tactic is '" <> tshow fromT <> "'. Switching tactic to '" <> tshow toT <> "'. (This clears targets.)" if not go then failWith "tactic change canceled" else return $ Right $ ReqUITactic toT -- * Automate; does not take time automateHuman :: MonadClientUI m => m (SlideOrCmd RequestUI) automateHuman = do -- BFS is not updated while automated, which would lead to corruption. modifyClient $ \cli -> cli {stgtMode = Nothing} escAI <- getsClient sescAI if escAI == EscAIExited then return $ Right ReqUIAutomate else do go <- displayMore ColorBW "Ceding control to AI (ESC to regain)." if not go then failWith "automation canceled" else return $ Right ReqUIAutomate
Concomitant/LambdaHack
Game/LambdaHack/Client/UI/HandleHumanGlobalClient.hs
bsd-3-clause
35,602
0
30
10,088
9,121
4,558
4,563
-1
-1
--- Demonstrate handling routes only if previous one import qualified Control.Monad.Trans.State.Strict as ST import qualified Control.Monad.Trans.Except as Exc import Data.List import Data.Maybe import Control.Monad -- State Monad -- How to use a State Monad type Response = Maybe String type Request = String type Application = Request -> Response type Route = Application -> Application data AppState = AppState { routes:: [Route]} type AppStateT = ST.State AppState -- client functions constructResponse = unwords routeHandler1 :: Request -> Response routeHandler1 request = Just $ constructResponse [ "request in handler1: got " ++ request] routeHandler2 :: t -> Maybe a routeHandler2 request = Nothing routeHandler3 :: Request -> Response routeHandler3 request = Just $ constructResponse [ "request in handler3:" ++ request] defaultRoute :: Request -> Response defaultRoute request = Just $ constructResponse [ request , "processed by defaultRoute"] cond :: Eq t => t -> t -> Bool cond condition_str = f where f i = i == condition_str myApp :: AppStateT () myApp = do addRoute routeHandler1 (== "handler1") addRoute routeHandler2 (== "handler2") addRoute routeHandler3 (== "handler3") main :: IO () main = myScotty myApp -- framework functions addRoute' mf s@AppState {routes = mw} = s {routes = mf:mw} route :: (Request -> Response) -> (Request -> Bool) -> Route route mw pat mw1 request = let tryNext = mw1 request in if pat request then let r = mw request in if isJust r then r else tryNext else tryNext addRoute :: Monad m => (String -> Maybe String) -> (String -> Bool) -> ST.StateT AppState m () addRoute mf pat = ST.modify $ \s -> addRoute' (route mf pat) s runMyApp :: (Request -> Response) -> AppState -> Request -> Response runMyApp def app_state request = do let output = foldl (flip ($)) def (routes app_state) request output userInputLoop :: AppState -> IO () userInputLoop app_state = do putStrLn "Please type in the request" putStrLn "(one of 'handler1', 'handler2', 'handler3', 'buggy' or any string for default handling)" request <- getLine unless (request == "q") $ do let response = runMyApp defaultRoute app_state request case response of Just x -> putStrLn x Nothing -> putStrLn "Error" userInputLoop app_state myScotty :: ST.State AppState a -> IO () myScotty my_app = do let app_state = ST.execState my_app AppState{ routes = []} userInputLoop app_state
gdevanla/scotty-from-ground-up
app/Main3.hs
bsd-3-clause
2,495
0
13
494
782
404
378
70
3
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances, MultiParamTypeClasses #-} module Development.Shake.Intern( Intern, Id, empty, insert, add, lookup, toList, fromList ) where import Development.Shake.Binary import Development.Shake.Classes import Prelude hiding (lookup) import qualified Data.HashMap.Strict as Map import Data.List(foldl') -- Invariant: The first field is the highest value in the Map data Intern a = Intern {-# UNPACK #-} !Word32 !(Map.HashMap a Id) newtype Id = Id Word32 deriving (Eq,Hashable,Binary,Show,NFData) instance BinaryWith w Id where putWith ctx = put getWith ctx = get empty :: Intern a empty = Intern 0 Map.empty insert :: (Eq a, Hashable a) => a -> Id -> Intern a -> Intern a insert k v@(Id i) (Intern n mp) = Intern (max n i) $ Map.insert k v mp add :: (Eq a, Hashable a) => a -> Intern a -> (Intern a, Id) add k (Intern v mp) = (Intern v2 $ Map.insert k (Id v2) mp, Id v2) where v2 = v + 1 lookup :: (Eq a, Hashable a) => a -> Intern a -> Maybe Id lookup k (Intern n mp) = Map.lookup k mp toList :: Intern a -> [(a, Id)] toList (Intern a b) = Map.toList b fromList :: (Eq a, Hashable a) => [(a, Id)] -> Intern a fromList xs = Intern (foldl' max 0 [i | (_, Id i) <- xs]) (Map.fromList xs)
nh2/shake
Development/Shake/Intern.hs
bsd-3-clause
1,278
0
12
267
556
297
259
30
1
{-# LANGUAGE DataKinds #-} -- -- PWR.hs --- PWR peripheral -- -- Copyright (C) 2014, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32.Peripheral.PWR ( PWR(..) , pwr , module Ivory.BSP.STM32.Peripheral.PWR.Regs ) where import Ivory.HW import Ivory.BSP.STM32.Peripheral.PWR.Regs import Ivory.BSP.STM32.MemoryMap (pwr_periph_base) data PWR = PWR { pwr_reg_cr :: BitDataReg PWR_CR , pwr_reg_csr :: BitDataReg PWR_CSR } pwr :: PWR pwr = PWR { pwr_reg_cr = mkBitDataRegNamed pwr_periph_base "pwr_cr" , pwr_reg_csr = mkBitDataRegNamed (pwr_periph_base + 0x04) "pwr_csr" }
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/PWR.hs
bsd-3-clause
615
0
9
112
132
86
46
15
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, PatternGuards, CPP #-} module Idris.REPL where import Idris.AbsSyntax import Idris.ASTUtils import Idris.Apropos (apropos) import Idris.REPLParser import Idris.ElabDecls import Idris.ElabTerm import Idris.Erasure import Idris.Error import Idris.ErrReverse import Idris.Delaborate import Idris.Docstrings (Docstring, overview, renderDocstring) import Idris.IdrisDoc import Idris.Prover import Idris.Parser hiding (indent) import Idris.Primitives import Idris.Coverage import Idris.Docs hiding (Doc) import Idris.Help import Idris.Completion import qualified Idris.IdeSlave as IdeSlave import Idris.Chaser import Idris.Imports import Idris.Colours hiding (colourise) import Idris.Inliner import Idris.CaseSplit import Idris.DeepSeq import Idris.Output import Idris.Interactive import Idris.WhoCalls import Idris.TypeSearch (searchByType) import Idris.Elab.Type import Idris.Elab.Clause import Idris.Elab.Data import Idris.Elab.Value import Version_idris (gitHash) import Util.System import Util.DynamicLinker import Util.Net (listenOnLocalhost, listenOnLocalhostAnyPort) import Util.Pretty hiding ((</>)) import Idris.Core.Evaluate import Idris.Core.Execute (execute) import Idris.Core.TT import Idris.Core.Unify import Idris.Core.Constraints import IRTS.Compiler import IRTS.CodegenCommon import IRTS.System import Control.Category import Prelude hiding ((.), id) import Data.List.Split (splitOn) import Data.List (groupBy) import qualified Data.Text as T import Text.Trifecta.Result(Result(..)) -- import RTS.SC -- import RTS.Bytecode -- import RTS.PreC -- import RTS.CodegenC import System.Console.Haskeline as H import System.FilePath import System.Exit import System.Environment import System.Process import System.Directory import System.IO import Control.Monad import Control.Monad.Trans.Error (ErrorT(..)) import Control.Monad.Trans.State.Strict ( StateT, execStateT, evalStateT, get, put ) import Control.Monad.Trans ( lift ) import Control.Concurrent.MVar import Network import Control.Concurrent import Data.Maybe import Data.List hiding (group) import Data.Char import Data.Version import Data.Word (Word) import Data.Either (partitionEithers) import Control.DeepSeq import Numeric ( readHex ) import Debug.Trace -- | Run the REPL repl :: IState -- ^ The initial state -> [FilePath] -- ^ The loaded modules -> InputT Idris () repl orig mods = -- H.catch do let quiet = opt_quiet (idris_options orig) i <- lift getIState let colour = idris_colourRepl i let theme = idris_colourTheme i let mvs = idris_metavars i let prompt = if quiet then "" else showMVs colour theme mvs ++ let str = mkPrompt mods ++ ">" in (if colour then colourisePrompt theme str else str) ++ " " x <- H.catch (getInputLine prompt) (ctrlC (return Nothing)) case x of Nothing -> do lift $ when (not quiet) (iputStrLn "Bye bye") return () Just input -> -- H.catch do ms <- H.catch (lift $ processInput input orig mods) (ctrlC (return (Just mods))) case ms of Just mods -> repl orig mods Nothing -> return () -- ctrlC) -- ctrlC where ctrlC :: InputT Idris a -> SomeException -> InputT Idris a ctrlC act e = do lift $ iputStrLn (show e) act -- repl orig mods showMVs c thm [] = "" showMVs c thm ms = "Metavariables: " ++ show' 4 c thm (map fst ms) ++ "\n" show' 0 c thm ms = let l = length ms in "... ( + " ++ show l ++ " other" ++ if l == 1 then ")" else "s)" show' n c thm [m] = showM c thm m show' n c thm (m : ms) = showM c thm m ++ ", " ++ show' (n - 1) c thm ms showM c thm n = if c then colouriseFun thm (show n) else show n -- | Run the REPL server startServer :: PortID -> IState -> [FilePath] -> Idris () startServer port orig fn_in = do tid <- runIO $ forkOS (serverLoop port) return () where serverLoop port = withSocketsDo $ do sock <- listenOnLocalhost port loop fn orig { idris_colourRepl = False } sock fn = case fn_in of (f:_) -> f _ -> "" loop fn ist sock = do (h,_,_) <- accept sock hSetEncoding h utf8 cmd <- hGetLine h let isth = case idris_outputmode ist of RawOutput _ -> ist {idris_outputmode = RawOutput h} IdeSlave n _ -> ist {idris_outputmode = IdeSlave n h} (ist', fn) <- processNetCmd orig isth h fn cmd hClose h loop fn ist' sock processNetCmd :: IState -> IState -> Handle -> FilePath -> String -> IO (IState, FilePath) processNetCmd orig i h fn cmd = do res <- case parseCmd i "(net)" cmd of Failure err -> return (Left (Msg " invalid command")) Success (Right c) -> runErrorT $ evalStateT (processNet fn c) i Success (Left err) -> return (Left (Msg err)) case res of Right x -> return x Left err -> do hPutStrLn h (show err) return (i, fn) where processNet fn Reload = processNet fn (Load fn Nothing) processNet fn (Load f toline) = do let ist = orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i , idris_colourRepl = False } putIState ist setErrContext True setOutH h setQuiet True setVerbose False mods <- loadInputs [f] toline ist <- getIState return (ist, f) processNet fn c = do process fn c ist <- getIState return (ist, fn) setOutH :: Handle -> Idris () setOutH h = do ist <- getIState putIState $ case idris_outputmode ist of RawOutput _ -> ist {idris_outputmode = RawOutput h} IdeSlave n _ -> ist {idris_outputmode = IdeSlave n h} -- | Run a command on the server on localhost runClient :: PortID -> String -> IO () runClient port str = withSocketsDo $ do h <- connectTo "localhost" port hSetEncoding h utf8 hPutStrLn h str resp <- hGetResp "" h putStr resp hClose h where hGetResp acc h = do eof <- hIsEOF h if eof then return acc else do l <- hGetLine h hGetResp (acc ++ l ++ "\n") h initIdeslaveSocket :: IO Handle initIdeslaveSocket = do (sock, port) <- listenOnLocalhostAnyPort putStrLn $ show port (h, _, _) <- accept sock hSetEncoding h utf8 return h -- | Run the IdeSlave ideslaveStart :: Bool -> IState -> [FilePath] -> Idris () ideslaveStart s orig mods = do h <- runIO $ if s then initIdeslaveSocket else return stdout setIdeSlave True h i <- getIState case idris_outputmode i of IdeSlave n h -> do runIO $ hPutStrLn h $ IdeSlave.convSExp "protocol-version" IdeSlave.ideSlaveEpoch n case mods of a:_ -> runIdeSlaveCommand h n i "" [] (IdeSlave.LoadFile a Nothing) _ -> return () ideslave h orig mods ideslave :: Handle -> IState -> [FilePath] -> Idris () ideslave h orig mods = do idrisCatch (do let inh = if h == stdout then stdin else h len' <- runIO $ IdeSlave.getLen inh len <- case len' of Left err -> ierror err Right n -> return n l <- runIO $ IdeSlave.getNChar inh len "" (sexp, id) <- case IdeSlave.parseMessage l of Left err -> ierror err Right (sexp, id) -> return (sexp, id) i <- getIState putIState $ i { idris_outputmode = (IdeSlave id h) } idrisCatch -- to report correct id back! (do let fn = case mods of (f:_) -> f _ -> "" case IdeSlave.sexpToCommand sexp of Just cmd -> runIdeSlaveCommand h id orig fn mods cmd Nothing -> iPrintError "did not understand" ) (\e -> do iPrintError $ show e)) (\e -> do iPrintError $ show e) ideslave h orig mods -- | Run IDESlave commands runIdeSlaveCommand :: Handle -- ^^ The handle for communication -> Integer -- ^^ The continuation ID for the client -> IState -- ^^ The original IState -> FilePath -- ^^ The current open file -> [FilePath] -- ^^ The currently loaded modules -> IdeSlave.IdeSlaveCommand -- ^^ The command to process -> Idris () runIdeSlaveCommand h id orig fn mods (IdeSlave.Interpret cmd) = do c <- colourise i <- getIState case parseCmd i "(input)" cmd of Failure err -> iPrintError $ show (fixColour False err) Success (Right (Prove n')) -> idrisCatch (do process fn (Prove n') isetPrompt (mkPrompt mods) case idris_outputmode i of IdeSlave n h -> -- signal completion of proof to ide runIO . hPutStrLn h $ IdeSlave.convSExp "return" (IdeSlave.SymbolAtom "ok", "") n _ -> return ()) (\e -> do ist <- getIState isetPrompt (mkPrompt mods) case idris_outputmode i of IdeSlave n h -> runIO . hPutStrLn h $ IdeSlave.convSExp "abandon-proof" "Abandoned" n _ -> return () iRenderError $ pprintErr ist e) Success (Right cmd) -> idrisCatch (ideslaveProcess fn cmd) (\e -> getIState >>= iRenderError . flip pprintErr e) Success (Left err) -> iPrintError err runIdeSlaveCommand h id orig fn mods (IdeSlave.REPLCompletions str) = do (unused, compls) <- replCompletion (reverse str, "") let good = IdeSlave.SexpList [IdeSlave.SymbolAtom "ok", IdeSlave.toSExp (map replacement compls, reverse unused)] runIO . hPutStrLn h $ IdeSlave.convSExp "return" good id runIdeSlaveCommand h id orig fn mods (IdeSlave.LoadFile filename toline) = do i <- getIState clearErr putIState (orig { idris_options = idris_options i, idris_outputmode = (IdeSlave id h) }) loadInputs [filename] toline isetPrompt (mkPrompt [filename]) -- Report either success or failure i <- getIState case (errSpan i) of Nothing -> let msg = maybe (IdeSlave.SexpList [IdeSlave.SymbolAtom "ok", IdeSlave.SexpList []]) (\fc -> IdeSlave.SexpList [IdeSlave.SymbolAtom "ok", IdeSlave.toSExp fc]) (idris_parsedSpan i) in runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id Just x -> iPrintError $ "didn't load " ++ filename ideslave h orig [filename] runIdeSlaveCommand h id orig fn mods (IdeSlave.TypeOf name) = case splitName name of Left err -> iPrintError err Right n -> process "(ideslave)" (Check (PRef (FC "(ideslave)" (0,0) (0,0)) n)) where splitName :: String -> Either String Name splitName s = case reverse $ splitOn "." s of [] -> Left ("Didn't understand name '" ++ s ++ "'") [n] -> Right $ sUN n (n:ns) -> Right $ sNS (sUN n) ns runIdeSlaveCommand h id orig fn mods (IdeSlave.DocsFor name) = case parseConst orig name of Success c -> process "(ideslave)" (DocStr (Right c)) Failure _ -> case splitName name of Left err -> iPrintError err Right n -> process "(ideslave)" (DocStr (Left n)) runIdeSlaveCommand h id orig fn mods (IdeSlave.CaseSplit line name) = process fn (CaseSplitAt False line (sUN name)) runIdeSlaveCommand h id orig fn mods (IdeSlave.AddClause line name) = process fn (AddClauseFrom False line (sUN name)) runIdeSlaveCommand h id orig fn mods (IdeSlave.AddProofClause line name) = process fn (AddProofClauseFrom False line (sUN name)) runIdeSlaveCommand h id orig fn mods (IdeSlave.AddMissing line name) = process fn (AddMissing False line (sUN name)) runIdeSlaveCommand h id orig fn mods (IdeSlave.MakeWithBlock line name) = process fn (MakeWith False line (sUN name)) runIdeSlaveCommand h id orig fn mods (IdeSlave.ProofSearch r line name hints depth) = doProofSearch fn False r line (sUN name) (map sUN hints) depth runIdeSlaveCommand h id orig fn mods (IdeSlave.MakeLemma line name) = case splitName name of Left err -> iPrintError err Right n -> process fn (MakeLemma False line n) runIdeSlaveCommand h id orig fn mods (IdeSlave.Apropos a) = process fn (Apropos a) runIdeSlaveCommand h id orig fn mods (IdeSlave.GetOpts) = do ist <- getIState let opts = idris_options ist let impshow = opt_showimp opts let errCtxt = opt_errContext opts let options = (IdeSlave.SymbolAtom "ok", [(IdeSlave.SymbolAtom "show-implicits", impshow), (IdeSlave.SymbolAtom "error-context", errCtxt)]) runIO . hPutStrLn h $ IdeSlave.convSExp "return" options id runIdeSlaveCommand h id orig fn mods (IdeSlave.SetOpt IdeSlave.ShowImpl b) = do setImpShow b let msg = (IdeSlave.SymbolAtom "ok", b) runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id runIdeSlaveCommand h id orig fn mods (IdeSlave.SetOpt IdeSlave.ErrContext b) = do setErrContext b let msg = (IdeSlave.SymbolAtom "ok", b) runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id runIdeSlaveCommand h id orig fn mods (IdeSlave.Metavariables cols) = do ist <- getIState let mvs = reverse $ map fst (idris_metavars ist) \\ primDefs let ppo = ppOptionIst ist -- splitMvs is a list of pairs of names and their split types let splitMvs = mapSnd (splitPi ist) (mvTys ist mvs) -- mvOutput is the pretty-printed version ready for conversion to SExpr let mvOutput = map (\(n, (hs, c)) -> (n, hs, c)) $ mapPair show (\(hs, c, pc) -> let bnd = [ n | (n,_,_) <- hs ] in let bnds = inits bnd in (map (\(bnd, h) -> processPremise ist bnd h) (zip bnds hs), render ist bnd c pc)) splitMvs runIO . hPutStrLn h $ IdeSlave.convSExp "return" (IdeSlave.SymbolAtom "ok", mvOutput) id where mapPair f g xs = zip (map (f . fst) xs) (map (g . snd) xs) mapSnd f xs = zip (map fst xs) (map (f . snd) xs) -- | Split a function type into a pair of premises, conclusion. -- Each maintains both the original and delaborated versions. splitPi :: IState -> Type -> ([(Name, Type, PTerm)], Type, PTerm) splitPi ist (Bind n (Pi t _) rest) = let (hs, c, pc) = splitPi ist rest in ((n, t, delabTy' ist [] t False False):hs, c, delabTy' ist [] c False False) splitPi ist tm = ([], tm, delabTy' ist [] tm False False) -- | Get the types of a list of metavariable names mvTys :: IState -> [Name] -> [(Name, Type)] mvTys ist = mapSnd vToP . mapMaybe (flip lookupTyNameExact (tt_ctxt ist)) -- | Show a type and its corresponding PTerm in a format suitable -- for the IDE - that is, pretty-printed and annotated. render :: IState -> [Name] -> Type -> PTerm -> (String, SpanList OutputAnnotation) render ist bnd t pt = let prettyT = pprintPTerm (ppOptionIst ist) (zip bnd (repeat False)) [] (idris_infixes ist) pt in displaySpans . renderPretty 0.9 cols . fmap (fancifyAnnots ist) . annotate (AnnTerm (zip bnd (take (length bnd) (repeat False))) t) $ prettyT -- | Juggle the bits of a premise to prepare for output. processPremise :: IState -> [Name] -- ^ the names to highlight as bound -> (Name, Type, PTerm) -> (String, String, SpanList OutputAnnotation) processPremise ist bnd (n, t, pt) = let (out, spans) = render ist bnd t pt in (show n , out, spans) runIdeSlaveCommand h id orig fn mods (IdeSlave.WhoCalls n) = case splitName n of Left err -> iPrintError err Right n -> do calls <- whoCalls n ist <- getIState let msg = (IdeSlave.SymbolAtom "ok", map (\ (n,ns) -> (pn ist n, map (pn ist) ns)) calls) runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id where pn ist = displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist) . prettyName True True [] runIdeSlaveCommand h id orig fn mods (IdeSlave.CallsWho n) = case splitName n of Left err -> iPrintError err Right n -> do calls <- callsWho n ist <- getIState let msg = (IdeSlave.SymbolAtom "ok", map (\ (n,ns) -> (pn ist n, map (pn ist) ns)) calls) runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id where pn ist = displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist) . prettyName True True [] runIdeSlaveCommand h id orig fn modes (IdeSlave.TermNormalise bnd tm) = do ctxt <- getContext ist <- getIState let tm' = force (normaliseAll ctxt [] tm) ptm = annotate (AnnTerm bnd tm') (pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) (delab ist tm')) msg = (IdeSlave.SymbolAtom "ok", displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist) $ ptm) runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id runIdeSlaveCommand h id orig fn modes (IdeSlave.TermShowImplicits bnd tm) = ideSlaveForceTermImplicits h id bnd True tm runIdeSlaveCommand h id orig fn modes (IdeSlave.TermNoImplicits bnd tm) = ideSlaveForceTermImplicits h id bnd False tm runIdeSlaveCommand h id orig fn mods (IdeSlave.PrintDef name) = case splitName name of Left err -> iPrintError err Right n -> process "(ideslave)" (PrintDef n) where splitName :: String -> Either String Name splitName s = case reverse $ splitOn "." s of [] -> Left ("Didn't understand name '" ++ s ++ "'") [n] -> Right $ sUN n (n:ns) -> Right $ sNS (sUN n) ns runIdeSlaveCommand h id orig fn modes (IdeSlave.ErrString e) = do ist <- getIState let out = displayS . renderPretty 1.0 60 $ pprintErr ist e msg = (IdeSlave.SymbolAtom "ok", IdeSlave.StringAtom $ out "") runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id runIdeSlaveCommand h id orig fn modes (IdeSlave.ErrPPrint e) = do ist <- getIState let (out, spans) = displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist) $ pprintErr ist e msg = (IdeSlave.SymbolAtom "ok", out, spans) runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id -- | Show a term for IDESlave with the specified implicitness ideSlaveForceTermImplicits :: Handle -> Integer -> [(Name, Bool)] -> Bool -> Term -> Idris () ideSlaveForceTermImplicits h id bnd impl tm = do ist <- getIState let expl = annotate (AnnTerm bnd tm) (pprintPTerm ((ppOptionIst ist) { ppopt_impl = impl }) bnd [] (idris_infixes ist) (delab ist tm)) msg = (IdeSlave.SymbolAtom "ok", displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist) $ expl) runIO . hPutStrLn h $ IdeSlave.convSExp "return" msg id splitName :: String -> Either String Name splitName s = case reverse $ splitOn "." s of [] -> Left ("Didn't understand name '" ++ s ++ "'") [n] -> Right $ sUN n (n:ns) -> Right $ sNS (sUN n) ns ideslaveProcess :: FilePath -> Command -> Idris () ideslaveProcess fn Warranty = process fn Warranty ideslaveProcess fn Help = process fn Help ideslaveProcess fn (ChangeDirectory f) = do process fn (ChangeDirectory f) iPrintResult "changed directory to" ideslaveProcess fn (Eval t) = process fn (Eval t) ideslaveProcess fn (NewDefn decls) = do process fn (NewDefn decls) iPrintResult "defined" ideslaveProcess fn (Undefine n) = process fn (Undefine n) ideslaveProcess fn (ExecVal t) = process fn (ExecVal t) ideslaveProcess fn (Check (PRef x n)) = process fn (Check (PRef x n)) ideslaveProcess fn (Check t) = process fn (Check t) ideslaveProcess fn (DocStr n) = process fn (DocStr n) ideslaveProcess fn Universes = process fn Universes ideslaveProcess fn (Defn n) = do process fn (Defn n) iPrintResult "" ideslaveProcess fn (TotCheck n) = process fn (TotCheck n) ideslaveProcess fn (DebugInfo n) = do process fn (DebugInfo n) iPrintResult "" ideslaveProcess fn (Search t) = process fn (Search t) ideslaveProcess fn (Spec t) = process fn (Spec t) -- RmProof and AddProof not supported! ideslaveProcess fn (ShowProof n') = process fn (ShowProof n') ideslaveProcess fn (HNF t) = process fn (HNF t) --ideslaveProcess fn TTShell = process fn TTShell -- need some prove mode! ideslaveProcess fn (TestInline t) = process fn (TestInline t) ideslaveProcess fn Execute = do process fn Execute iPrintResult "" ideslaveProcess fn (Compile codegen f) = do process fn (Compile codegen f) iPrintResult "" ideslaveProcess fn (LogLvl i) = do process fn (LogLvl i) iPrintResult "" ideslaveProcess fn (Pattelab t) = process fn (Pattelab t) ideslaveProcess fn (Missing n) = process fn (Missing n) ideslaveProcess fn (DynamicLink l) = do process fn (DynamicLink l) iPrintResult "" ideslaveProcess fn ListDynamic = do process fn ListDynamic iPrintResult "" ideslaveProcess fn Metavars = process fn Metavars ideslaveProcess fn (SetOpt ErrContext) = do process fn (SetOpt ErrContext) iPrintResult "" ideslaveProcess fn (UnsetOpt ErrContext) = do process fn (UnsetOpt ErrContext) iPrintResult "" ideslaveProcess fn (SetOpt ShowImpl) = do process fn (SetOpt ShowImpl) iPrintResult "" ideslaveProcess fn (UnsetOpt ShowImpl) = do process fn (UnsetOpt ShowImpl) iPrintResult "" ideslaveProcess fn (SetOpt ShowOrigErr) = do process fn (SetOpt ShowOrigErr) iPrintResult "" ideslaveProcess fn (UnsetOpt ShowOrigErr) = do process fn (UnsetOpt ShowOrigErr) iPrintResult "" ideslaveProcess fn (SetOpt x) = process fn (SetOpt x) ideslaveProcess fn (UnsetOpt x) = process fn (UnsetOpt x) ideslaveProcess fn (CaseSplitAt False pos str) = process fn (CaseSplitAt False pos str) ideslaveProcess fn (AddProofClauseFrom False pos str) = process fn (AddProofClauseFrom False pos str) ideslaveProcess fn (AddClauseFrom False pos str) = process fn (AddClauseFrom False pos str) ideslaveProcess fn (AddMissing False pos str) = process fn (AddMissing False pos str) ideslaveProcess fn (MakeWith False pos str) = process fn (MakeWith False pos str) ideslaveProcess fn (DoProofSearch False r pos str xs) = process fn (DoProofSearch False r pos str xs) ideslaveProcess fn (SetConsoleWidth w) = do process fn (SetConsoleWidth w) iPrintResult "" ideslaveProcess fn (Apropos a) = do process fn (Apropos a) iPrintResult "" ideslaveProcess fn (WhoCalls n) = process fn (WhoCalls n) ideslaveProcess fn (CallsWho n) = process fn (CallsWho n) ideslaveProcess fn (PrintDef n) = process fn (PrintDef n) ideslaveProcess fn (PPrint fmt n tm) = process fn (PPrint fmt n tm) ideslaveProcess fn _ = iPrintError "command not recognized or not supported" -- | The prompt consists of the currently loaded modules, or "Idris" if there are none mkPrompt [] = "Idris" mkPrompt [x] = "*" ++ dropExtension x mkPrompt (x:xs) = "*" ++ dropExtension x ++ " " ++ mkPrompt xs -- | Determine whether a file uses literate syntax lit f = case splitExtension f of (_, ".lidr") -> True _ -> False processInput :: String -> IState -> [FilePath] -> Idris (Maybe [FilePath]) processInput cmd orig inputs = do i <- getIState let opts = idris_options i let quiet = opt_quiet opts let fn = case inputs of (f:_) -> f _ -> "" c <- colourise case parseCmd i "(input)" cmd of Failure err -> do iputStrLn $ show (fixColour c err) return (Just inputs) Success (Right Reload) -> do putIState $ orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i } clearErr mods <- loadInputs inputs Nothing return (Just inputs) Success (Right (Load f toline)) -> do putIState orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i } clearErr mod <- loadInputs [f] toline return (Just [f]) Success (Right (ModImport f)) -> do clearErr fmod <- loadModule f return (Just (inputs ++ [fmod])) Success (Right Edit) -> do -- takeMVar stvar edit fn orig return (Just inputs) Success (Right Proofs) -> do proofs orig return (Just inputs) Success (Right Quit) -> do when (not quiet) (iputStrLn "Bye bye") return Nothing Success (Right cmd ) -> do idrisCatch (process fn cmd) (\e -> do msg <- showErr e ; iputStrLn msg) return (Just inputs) Success (Left err) -> do runIO $ putStrLn err return (Just inputs) resolveProof :: Name -> Idris Name resolveProof n' = do i <- getIState ctxt <- getContext n <- case lookupNames n' ctxt of [x] -> return x [] -> return n' ns -> ierror (CantResolveAlts ns) return n removeProof :: Name -> Idris () removeProof n = do i <- getIState let proofs = proof_list i let ps = filter ((/= n) . fst) proofs putIState $ i { proof_list = ps } edit :: FilePath -> IState -> Idris () edit "" orig = iputStrLn "Nothing to edit" edit f orig = do i <- getIState env <- runIO $ getEnvironment let editor = getEditor env let line = case errSpan i of Just l -> ['+' : show (fst (fc_start l))] Nothing -> [] let args = line ++ [fixName f] runIO $ rawSystem editor args clearErr putIState $ orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i } loadInputs [f] Nothing -- clearOrigPats iucheck return () where getEditor env | Just ed <- lookup "EDITOR" env = ed | Just ed <- lookup "VISUAL" env = ed | otherwise = "vi" fixName file | map toLower (takeExtension file) `elem` [".lidr", ".idr"] = file | otherwise = addExtension file "idr" proofs :: IState -> Idris () proofs orig = do i <- getIState let ps = proof_list i case ps of [] -> iputStrLn "No proofs available" _ -> iputStrLn $ "Proofs:\n\t" ++ (show $ map fst ps) insertScript :: String -> [String] -> [String] insertScript prf [] = "\n---------- Proofs ----------" : "" : [prf] insertScript prf (p@"---------- Proofs ----------" : "" : xs) = p : "" : prf : xs insertScript prf (x : xs) = x : insertScript prf xs process :: FilePath -> Command -> Idris () process fn Help = iPrintResult displayHelp process fn Warranty = iPrintResult warranty process fn (ChangeDirectory f) = do runIO $ setCurrentDirectory f return () process fn (Eval t) = withErrorReflection $ do logLvl 5 $ show t getIState >>= flip warnDisamb t (tm, ty) <- elabVal recinfo ERHS t ctxt <- getContext let tm' = force (normaliseAll ctxt [] tm) let ty' = force (normaliseAll ctxt [] ty) -- Add value to context, call it "it" updateContext (addCtxtDef (sUN "it") (Function ty' tm')) ist <- getIState logLvl 3 $ "Raw: " ++ show (tm', ty') logLvl 10 $ "Debug: " ++ showEnvDbg [] tm' let tmDoc = pprintDelab ist tm' tyDoc = pprintDelab ist ty' iPrintTermWithType tmDoc tyDoc process fn (NewDefn decls) = do logLvl 3 ("Defining names using these decls: " ++ show (showDecls verbosePPOption decls)) mapM_ defineName namedGroups where namedGroups = groupBy (\d1 d2 -> getName d1 == getName d2) decls getName :: PDecl -> Maybe Name getName (PTy docs argdocs syn fc opts name ty) = Just name getName (PClauses fc opts name (clause:clauses)) = Just (getClauseName clause) getName (PData doc argdocs syn fc opts dataDecl) = Just (d_name dataDecl) getName (PClass doc syn fc constraints name parms parmdocs decls) = Just name getName _ = Nothing -- getClauseName is partial and I am not sure it's used safely! -- trillioneyes getClauseName (PClause fc name whole with rhs whereBlock) = name getClauseName (PWith fc name whole with rhs whereBlock) = name defineName :: [PDecl] -> Idris () defineName (tyDecl@(PTy docs argdocs syn fc opts name ty) : decls) = do elabDecl EAll recinfo tyDecl elabClauses recinfo fc opts name (concatMap getClauses decls) setReplDefined (Just name) defineName [PClauses fc opts _ [clause]] = do let pterm = getRHS clause (tm,ty) <- elabVal recinfo ERHS pterm ctxt <- getContext let tm' = force (normaliseAll ctxt [] tm) let ty' = force (normaliseAll ctxt [] ty) updateContext (addCtxtDef (getClauseName clause) (Function ty' tm')) setReplDefined (Just $ getClauseName clause) defineName (PClauses{} : _) = tclift $ tfail (Msg "Only one function body is allowed without a type declaration.") -- fixity and syntax declarations are ignored by elabDecls, so they'll have to be handled some other way defineName (PFix fc fixity strs : defns) = do fmodifyState idris_fixities (map (Fix fixity) strs ++) unless (null defns) $ defineName defns defineName (PSyntax _ syntax:_) = do i <- get put (addReplSyntax i syntax) defineName decls = do elabDecls toplevel (map fixClauses decls) setReplDefined (getName (head decls)) getClauses (PClauses fc opts name clauses) = clauses getClauses _ = [] getRHS :: PClause -> PTerm getRHS (PClause fc name whole with rhs whereBlock) = rhs getRHS (PWith fc name whole with rhs whereBlock) = rhs getRHS (PClauseR fc with rhs whereBlock) = rhs getRHS (PWithR fc with rhs whereBlock) = rhs setReplDefined :: Maybe Name -> Idris () setReplDefined Nothing = return () setReplDefined (Just n) = do oldState <- get fmodifyState repl_definitions (n:) -- the "name" field of PClauses seems to always be MN 2 "__", so we need to -- retrieve the actual name from deeper inside. -- This should really be a full recursive walk through the structure of PDecl, but -- I think it should work this way and I want to test sooner. Also lazy. fixClauses :: PDecl' t -> PDecl' t fixClauses (PClauses fc opts _ css@(clause:cs)) = PClauses fc opts (getClauseName clause) css fixClauses (PInstance syn fc constraints cls parms ty instName decls) = PInstance syn fc constraints cls parms ty instName (map fixClauses decls) fixClauses decl = decl process fn (Undefine names) = undefine names where undefine :: [Name] -> Idris () undefine [] = do allDefined <- idris_repl_defs `fmap` get undefine' allDefined [] -- Keep track of which names you've removed so you can -- print them out to the user afterward undefine names = undefine' names [] undefine' [] list = do iRenderOutput $ printUndefinedNames list return () undefine' (n:names) already = do allDefined <- idris_repl_defs `fmap` get if n `elem` allDefined then do undefinedJustNow <- undefClosure n undefine' names (undefinedJustNow ++ already) else do tclift $ tfail $ Msg ("Can't undefine " ++ show n ++ " because it wasn't defined at the repl") undefine' names already undefOne n = do fputState (ctxt_lookup n . known_terms) Nothing -- for now just assume it's a class. Eventually we'll want some kind of -- smart detection of exactly what kind of name we're undefining. fputState (ctxt_lookup n . known_classes) Nothing fmodifyState repl_definitions (delete n) undefClosure n = do replDefs <- idris_repl_defs `fmap` get callGraph <- whoCalls n let users = case lookup n callGraph of Just ns -> nub ns Nothing -> fail ("Tried to undefine nonexistent name" ++ show n) undefinedJustNow <- concat `fmap` mapM undefClosure users undefOne n return (nub (n : undefinedJustNow)) process fn (ExecVal t) = do ctxt <- getContext ist <- getIState (tm, ty) <- elabVal recinfo ERHS t -- let tm' = normaliseAll ctxt [] tm let ty' = normaliseAll ctxt [] ty res <- execute tm let (resOut, tyOut) = (prettyIst ist (delab ist res), prettyIst ist (delab ist ty')) iPrintTermWithType resOut tyOut process fn (Check (PRef _ n)) = do ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist case lookupNames n ctxt of ts@(t:_) -> case lookup t (idris_metavars ist) of Just (_, i, _) -> iRenderResult . fmap (fancifyAnnots ist) $ showMetavarInfo ppo ist n i Nothing -> iPrintFunTypes [] n (map (\n -> (n, pprintDelabTy ist n)) ts) [] -> iPrintError $ "No such variable " ++ show n where showMetavarInfo ppo ist n i = case lookupTy n (tt_ctxt ist) of (ty:_) -> putTy ppo ist i [] (delab ist (errReverse ist ty)) putTy :: PPOption -> IState -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation putTy ppo ist 0 bnd sc = putGoal ppo ist bnd sc putTy ppo ist i bnd (PPi _ n t sc) = let current = text " " <> (case n of MN _ _ -> text "_" UN nm | ('_':'_':_) <- str nm -> text "_" _ -> bindingOf n False) <+> colon <+> align (tPretty bnd ist t) <> line in current <> putTy ppo ist (i-1) ((n,False):bnd) sc putTy ppo ist _ bnd sc = putGoal ppo ist ((n,False):bnd) sc putGoal ppo ist bnd g = text "--------------------------------------" <$> annotate (AnnName n Nothing Nothing Nothing) (text $ show n) <+> colon <+> align (tPretty bnd ist g) tPretty bnd ist t = pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) t process fn (Check t) = do (tm, ty) <- elabVal recinfo ERHS t ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist ty' = normaliseC ctxt [] ty case tm of TType _ -> iPrintTermWithType (prettyIst ist PType) type1Doc _ -> iPrintTermWithType (pprintDelab ist tm) (pprintDelab ist ty) process fn (DocStr (Left n)) = do ist <- getIState case lookupCtxtName n (idris_docstrings ist) of [] -> iPrintError $ "No documentation for " ++ show n ns -> do toShow <- mapM (showDoc ist) ns iRenderResult (vsep toShow) where showDoc ist (n, d) = do doc <- getDocs n return $ pprintDocs ist doc process fn (DocStr (Right c)) = do ist <- getIState iRenderResult $ pprintConstDocs ist c (constDocs c) process fn Universes = do i <- getIState let cs = idris_constraints i -- iputStrLn $ showSep "\n" (map show cs) iputStrLn $ show (map fst cs) let n = length cs iputStrLn $ "(" ++ show n ++ " constraints)" case ucheck cs of Error e -> iPrintError $ pshow i e OK _ -> iPrintResult "Universes OK" process fn (Defn n) = do i <- getIState iputStrLn "Compiled patterns:\n" iputStrLn $ show (lookupDef n (tt_ctxt i)) case lookupCtxt n (idris_patdefs i) of [] -> return () [(d, _)] -> do iputStrLn "Original definiton:\n" mapM_ (printCase i) d case lookupTotal n (tt_ctxt i) of [t] -> iputStrLn (showTotal t i) _ -> return () where printCase i (_, lhs, rhs) = let i' = i { idris_options = (idris_options i) { opt_showimp = True } } in iputStrLn (showTm i' (delab i lhs) ++ " = " ++ showTm i' (delab i rhs)) process fn (TotCheck n) = do i <- getIState case lookupNameTotal n (tt_ctxt i) of [] -> iPrintError $ "Unknown operator " ++ show n ts -> do ist <- getIState c <- colourise let ppo = ppOptionIst ist let showN = showName (Just ist) [] ppo c iPrintResult . concat . intersperse "\n" . map (\(n, t) -> showN n ++ " is " ++ showTotal t i) $ ts process fn (DebugUnify l r) = do (ltm, _) <- elabVal recinfo ERHS l (rtm, _) <- elabVal recinfo ERHS r ctxt <- getContext case unify ctxt [] ltm rtm [] [] [] [] of OK ans -> iputStrLn (show ans) Error e -> iputStrLn (show e) process fn (DebugInfo n) = do i <- getIState let oi = lookupCtxtName n (idris_optimisation i) when (not (null oi)) $ iputStrLn (show oi) let si = lookupCtxt n (idris_statics i) when (not (null si)) $ iputStrLn (show si) let di = lookupCtxt n (idris_datatypes i) when (not (null di)) $ iputStrLn (show di) let d = lookupDef n (tt_ctxt i) when (not (null d)) $ iputStrLn $ "Definition: " ++ (show (head d)) let cg = lookupCtxtName n (idris_callgraph i) i <- getIState let cg' = lookupCtxtName n (idris_callgraph i) sc <- checkSizeChange n iputStrLn $ "Size change: " ++ show sc let fn = lookupCtxtName n (idris_fninfo i) when (not (null cg')) $ do iputStrLn "Call graph:\n" iputStrLn (show cg') when (not (null fn)) $ iputStrLn (show fn) process fn (Search t) = searchByType t process fn (CaseSplitAt updatefile l n) = caseSplitAt fn updatefile l n process fn (AddClauseFrom updatefile l n) = addClauseFrom fn updatefile l n process fn (AddProofClauseFrom updatefile l n) = addProofClauseFrom fn updatefile l n process fn (AddMissing updatefile l n) = addMissing fn updatefile l n process fn (MakeWith updatefile l n) = makeWith fn updatefile l n process fn (MakeLemma updatefile l n) = makeLemma fn updatefile l n process fn (DoProofSearch updatefile rec l n hints) = doProofSearch fn updatefile rec l n hints Nothing process fn (Spec t) = do (tm, ty) <- elabVal recinfo ERHS t ctxt <- getContext ist <- getIState let tm' = simplify ctxt [] {- (idris_statics ist) -} tm iPrintResult (show (delab ist tm')) process fn (RmProof n') = do i <- getIState n <- resolveProof n' let proofs = proof_list i case lookup n proofs of Nothing -> iputStrLn "No proof to remove" Just _ -> do removeProof n insertMetavar n iputStrLn $ "Removed proof " ++ show n where insertMetavar :: Name -> Idris () insertMetavar n = do i <- getIState let ms = idris_metavars i putIState $ i { idris_metavars = (n, (Nothing, 0, False)) : ms } process fn' (AddProof prf) = do fn <- do let fn'' = takeWhile (/= ' ') fn' ex <- runIO $ doesFileExist fn'' let fnExt = fn'' <.> "idr" exExt <- runIO $ doesFileExist fnExt if ex then return fn'' else if exExt then return fnExt else ifail $ "Neither \""++fn''++"\" nor \""++fnExt++"\" exist" let fb = fn ++ "~" runIO $ copyFile fn fb -- make a backup in case something goes wrong! prog <- runIO $ readFile fb i <- getIState let proofs = proof_list i n' <- case prf of Nothing -> case proofs of [] -> ifail "No proof to add" ((x, p) : _) -> return x Just nm -> return nm n <- resolveProof n' case lookup n proofs of Nothing -> iputStrLn "No proof to add" Just p -> do let prog' = insertScript (showProof (lit fn) n p) ls runIO $ writeFile fn (unlines prog') removeProof n iputStrLn $ "Added proof " ++ show n where ls = (lines prog) process fn (ShowProof n') = do i <- getIState n <- resolveProof n' let proofs = proof_list i case lookup n proofs of Nothing -> iPrintError "No proof to show" Just p -> iPrintResult $ showProof False n p process fn (Prove n') = do ctxt <- getContext ist <- getIState let ns = lookupNames n' ctxt let metavars = mapMaybe (\n -> do c <- lookup n (idris_metavars ist); return (n, c)) ns n <- case metavars of [] -> ierror (Msg $ "Cannot find metavariable " ++ show n') [(n, (_,_,False))] -> return n [(_, (_,_,True))] -> ierror (Msg $ "Declarations not solvable using prover") ns -> ierror (CantResolveAlts (map fst ns)) prover (lit fn) n -- recheck totality i <- getIState totcheck (fileFC "(input)", n) mapM_ (\ (f,n) -> setTotality n Unchecked) (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) warnTotality process fn (HNF t) = do (tm, ty) <- elabVal recinfo ERHS t ctxt <- getContext ist <- getIState let tm' = hnf ctxt [] tm iPrintResult (show (delab ist tm')) process fn (TestInline t) = do (tm, ty) <- elabVal recinfo ERHS t ctxt <- getContext ist <- getIState let tm' = inlineTerm ist tm c <- colourise iPrintResult (showTm ist (delab ist tm')) process fn Execute = idrisCatch (do ist <- getIState (m, _) <- elabVal recinfo ERHS (PApp fc (PRef fc (sUN "run__IO")) [pexp $ PRef fc (sNS (sUN "main") ["Main"])]) (tmpn, tmph) <- runIO tempfile runIO $ hClose tmph t <- codegen ir <- compile t tmpn m runIO $ generate t (fst (head (idris_imported ist))) ir case idris_outputmode ist of RawOutput h -> do runIO $ rawSystem tmpn [] return () IdeSlave n h -> runIO . hPutStrLn h $ IdeSlave.convSExp "run-program" tmpn n) (\e -> getIState >>= iRenderError . flip pprintErr e) where fc = fileFC "main" process fn (Compile codegen f) | map toLower (takeExtension f) `elem` [".idr", ".lidr", ".idc"] = iPrintError $ "Invalid filename for compiler output \"" ++ f ++"\"" | otherwise = do (m, _) <- elabVal recinfo ERHS (PApp fc (PRef fc (sUN "run__IO")) [pexp $ PRef fc (sNS (sUN "main") ["Main"])]) ir <- compile codegen f m i <- getIState runIO $ generate codegen (fst (head (idris_imported i))) ir where fc = fileFC "main" process fn (LogLvl i) = setLogLevel i -- Elaborate as if LHS of a pattern (debug command) process fn (Pattelab t) = do (tm, ty) <- elabVal recinfo ELHS t iPrintResult $ show tm ++ "\n\n : " ++ show ty process fn (Missing n) = do i <- getIState let i' = i { idris_options = (idris_options i) { opt_showimp = True } } case lookupCtxt n (idris_patdefs i) of [] -> iPrintError $ "Unknown operator " ++ show n [(_, tms)] -> iPrintResult (showSep "\n" (map (showTm i') tms)) _ -> iPrintError $ "Ambiguous name" process fn (DynamicLink l) = do i <- getIState let importdirs = opt_importdirs (idris_options i) lib = trim l handle <- lift . lift $ tryLoadLib importdirs lib case handle of Nothing -> iPrintError $ "Could not load dynamic lib \"" ++ l ++ "\"" Just x -> do let libs = idris_dynamic_libs i if x `elem` libs then do iLOG ("Tried to load duplicate library " ++ lib_name x) return () else putIState $ i { idris_dynamic_libs = x:libs } where trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace process fn ListDynamic = do i <- getIState iputStrLn "Dynamic libraries:" showLibs $ idris_dynamic_libs i where showLibs [] = return () showLibs ((Lib name _):ls) = do iputStrLn $ "\t" ++ name; showLibs ls process fn Metavars = do ist <- getIState let mvs = map fst (idris_metavars ist) \\ primDefs case mvs of [] -> iPrintError "No global metavariables to solve" _ -> iPrintResult $ "Global metavariables:\n\t" ++ show mvs process fn NOP = return () process fn (SetOpt ErrContext) = setErrContext True process fn (UnsetOpt ErrContext) = setErrContext False process fn (SetOpt ShowImpl) = setImpShow True process fn (UnsetOpt ShowImpl) = setImpShow False process fn (SetOpt ShowOrigErr) = setShowOrigErr True process fn (UnsetOpt ShowOrigErr) = setShowOrigErr False process fn (SetOpt AutoSolve) = setAutoSolve True process fn (UnsetOpt AutoSolve) = setAutoSolve False process fn (SetOpt NoBanner) = setNoBanner True process fn (UnsetOpt NoBanner) = setNoBanner False process fn (SetOpt WarnReach) = fmodifyState opts_idrisCmdline $ nub . (WarnReach:) process fn (UnsetOpt WarnReach) = fmodifyState opts_idrisCmdline $ delete WarnReach process fn (SetOpt _) = iPrintError "Not a valid option" process fn (UnsetOpt _) = iPrintError "Not a valid option" process fn (SetColour ty c) = setColour ty c process fn ColourOn = do ist <- getIState putIState $ ist { idris_colourRepl = True } process fn ColourOff = do ist <- getIState putIState $ ist { idris_colourRepl = False } process fn ListErrorHandlers = do ist <- getIState iPrintResult $ case idris_errorhandlers ist of [] -> "No registered error handlers" handlers -> "Registered error handlers: " ++ (concat . intersperse ", " . map show) handlers process fn (SetConsoleWidth w) = setWidth w process fn (Apropos a) = do ist <- getIState let names = apropos ist (T.pack a) let aproposInfo = [ (n, delabTy ist n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings ist))) | n <- sort names, isUN n ] iRenderResult $ vsep (map (prettyDocumentedIst ist) aproposInfo) where isUN (UN _) = True isUN (NS n _) = isUN n isUN _ = False process fn (WhoCalls n) = do calls <- whoCalls n ist <- getIState iRenderResult . vsep $ map (\(n, ns) -> text "Callers of" <+> prettyName True True [] n <$> indent 1 (vsep (map ((text "*" <+>) . align . prettyName True True []) ns))) calls process fn (CallsWho n) = do calls <- callsWho n ist <- getIState iRenderResult . vsep $ map (\(n, ns) -> prettyName True True [] n <+> text "calls:" <$> indent 1 (vsep (map ((text "*" <+>) . align . prettyName True True []) ns))) calls -- IdrisDoc process fn (MakeDoc s) = do istate <- getIState let names = words s parse n | Success x <- runparser name istate fn n = Right x parse n = Left n (bad, nss) = partitionEithers $ map parse names cd <- runIO $ getCurrentDirectory let outputDir = cd </> "doc" result <- if null bad then runIO $ generateDocs istate nss outputDir else return . Left $ "Illegal name: " ++ head bad case result of Right _ -> iputStrLn "IdrisDoc generated" Left err -> iPrintError err process fn (PrintDef n) = do result <- pprintDef n case result of [] -> iPrintError "Not found" outs -> iRenderResult . vsep $ outs -- Show relevant transformation rules for the name 'n' process fn (TransformInfo n) = do i <- getIState let ts = lookupCtxt n (idris_transforms i) let res = map (showTrans i) ts iRenderResult . vsep $ concat res where showTrans :: IState -> [(Term, Term)] -> [Doc OutputAnnotation] showTrans i [] = [] showTrans i ((lhs, rhs) : ts) = let ppTm tm = annotate (AnnTerm [] tm) . pprintPTerm (ppOptionIst i) [] [] [] . delab i $ tm ts' = showTrans i ts in ppTm lhs <+> text " ==> " <+> ppTm rhs : ts' -- iRenderOutput (pretty lhs) -- iputStrLn " ==> " -- iPrintTermWithType (pprintDelab i rhs) -- iputStrLn "---------------" -- showTrans i ts process fn (PPrint fmt width (PRef _ n)) = do outs <- pprintDef n iPrintResult =<< renderExternal fmt width (vsep outs) process fn (PPrint fmt width t) = do (tm, ty) <- elabVal recinfo ERHS t ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist ty' = normaliseC ctxt [] ty iPrintResult =<< renderExternal fmt width (pprintDelab ist tm) showTotal :: Totality -> IState -> String showTotal t@(Partial (Other ns)) i = show t ++ "\n\t" ++ showSep "\n\t" (map (showTotalN i) ns) showTotal t i = show t showTotalN i n = case lookupTotal n (tt_ctxt i) of [t] -> showTotal t i _ -> "" displayHelp = let vstr = showVersion version in "\nIdris version " ++ vstr ++ "\n" ++ "--------------" ++ map (\x -> '-') vstr ++ "\n\n" ++ concatMap cmdInfo helphead ++ concatMap cmdInfo help where cmdInfo (cmds, args, text) = " " ++ col 16 12 (showSep " " cmds) (show args) text col c1 c2 l m r = l ++ take (c1 - length l) (repeat ' ') ++ m ++ take (c2 - length m) (repeat ' ') ++ r ++ "\n" pprintDef :: Name -> Idris [Doc OutputAnnotation] pprintDef n = do ist <- getIState ctxt <- getContext let ambiguous = length (lookupNames n ctxt) > 1 patdefs = idris_patdefs ist tyinfo = idris_datatypes ist return $ map (ppDef ambiguous ist) (lookupCtxtName n patdefs) ++ map (ppTy ambiguous ist) (lookupCtxtName n tyinfo) ++ map (ppCon ambiguous ist) (filter (flip isDConName ctxt) (lookupNames n ctxt)) where ppDef :: Bool -> IState -> (Name, ([([Name], Term, Term)], [PTerm])) -> Doc OutputAnnotation ppDef amb ist (n, (clauses, missing)) = prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) <$> ppClauses ist clauses <> ppMissing missing ppClauses ist [] = text "No clauses." ppClauses ist cs = vsep (map pp cs) where pp (vars, lhs, rhs) = let ppTm t = annotate (AnnTerm (zip vars (repeat False)) t) . pprintPTerm (ppOptionIst ist) (zip vars (repeat False)) [] [] . delab ist $ t in group $ ppTm lhs <+> text "=" <$> (group . align . hang 2 $ ppTm rhs) ppMissing _ = empty ppTy :: Bool -> IState -> (Name, TypeInfo) -> Doc OutputAnnotation ppTy amb ist (n, TI constructors isCodata _ _ _) = kwd key <+> prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) <+> kwd "where" <$> indent 2 (vsep (map (ppCon False ist) constructors)) where key | isCodata = "codata" | otherwise = "data" kwd = annotate AnnKeyword . text ppCon amb ist n = prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) helphead = [ (["Command"], SpecialHeaderArg, "Purpose"), ([""], NoArg, "") ] replSettings :: Maybe FilePath -> Settings Idris replSettings hFile = setComplete replCompletion $ defaultSettings { historyFile = hFile } -- | Invoke as if from command line. It is an error if there are unresolved totality problems. idris :: [Opt] -> IO (Maybe IState) idris opts = do res <- runErrorT $ execStateT totalMain idrisInit case res of Left err -> do putStrLn $ pshow idrisInit err return Nothing Right ist -> return (Just ist) where totalMain = do idrisMain opts ist <- getIState case idris_totcheckfail ist of ((fc, msg):_) -> ierror . At fc . Msg $ "Could not build: "++ msg [] -> return () loadInputs :: [FilePath] -> Maybe Int -> Idris () loadInputs inputs toline -- furthest line to read in input source files = idrisCatch (do ist <- getIState -- if we're in --check and not outputting anything, don't bother -- loading, as it gets really slow if there's lots of modules in -- a package (instead, reload all at the end to check for -- consistency only) opts <- getCmdLine let loadCode = case opt getOutput opts of [] -> not (NoREPL `elem` opts) _ -> True -- For each ifile list, check it and build ibcs in the same clean IState -- so that they don't interfere with each other when checking let ninputs = zip [1..] inputs ifiles <- mapWhileOK (\(num, input) -> do putIState ist modTree <- buildTree (map snd (take (num-1) ninputs)) input let ifiles = getModuleFiles modTree iLOG ("MODULE TREE : " ++ show modTree) iLOG ("RELOAD: " ++ show ifiles) when (not (all ibc ifiles) || loadCode) $ tryLoad False (filter (not . ibc) ifiles) -- return the files that need rechecking return ifiles) ninputs inew <- getIState let tidata = idris_tyinfodata inew let patdefs = idris_patdefs inew -- If it worked, load the whole thing from all the ibcs together case errSpan inew of Nothing -> do putIState (ist { idris_tyinfodata = tidata }) ibcfiles <- mapM findNewIBC (nub (concat ifiles)) tryLoad True (mapMaybe id ibcfiles) _ -> return () ist <- getIState putIState (ist { idris_tyinfodata = tidata, idris_patdefs = patdefs }) case opt getOutput opts of [] -> performUsageAnalysis -- interactive _ -> return [] -- batch, will be checked by the compiler return ()) (\e -> do i <- getIState case e of At f e' -> do setErrSpan f iWarn f $ pprintErr i e' ProgramLineComment -> return () -- fail elsewhere _ -> do setErrSpan emptyFC -- FIXME! Propagate it -- Issue #1576 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1576 iWarn emptyFC $ pprintErr i e) where -- load all files, stop if any fail tryLoad :: Bool -> [IFileType] -> Idris () tryLoad keepstate [] = warnTotality >> return () tryLoad keepstate (f : fs) = do ist <- getIState let maxline = case toline of Nothing -> Nothing Just l -> case f of IDR fn -> if any (fmatch fn) inputs then Just l else Nothing LIDR fn -> if any (fmatch fn) inputs then Just l else Nothing _ -> Nothing loadFromIFile True f maxline inew <- getIState -- FIXME: Save these in IBC to avoid this hack! Need to -- preserve it all from source inputs -- -- Issue #1577 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1577 let tidata = idris_tyinfodata inew let patdefs = idris_patdefs inew ok <- noErrors when ok $ do when (not keepstate) $ putIState ist ist <- getIState putIState (ist { idris_tyinfodata = tidata, idris_patdefs = patdefs }) tryLoad keepstate fs ibc (IBC _ _) = True ibc _ = False fmatch ('.':'/':xs) ys = fmatch xs ys fmatch xs ('.':'/':ys) = fmatch xs ys fmatch xs ys = xs == ys findNewIBC :: IFileType -> Idris (Maybe IFileType) findNewIBC i@(IBC _ _) = return (Just i) findNewIBC s@(IDR f) = do ist <- get ibcsd <- valIBCSubDir ist let ibc = ibcPathNoFallback ibcsd f ok <- runIO $ doesFileExist ibc if ok then return (Just (IBC ibc s)) else return Nothing findNewIBC s@(LIDR f) = do ist <- get ibcsd <- valIBCSubDir ist let ibc = ibcPathNoFallback ibcsd f ok <- runIO $ doesFileExist ibc if ok then return (Just (IBC ibc s)) else return Nothing -- Like mapM, but give up when there's an error mapWhileOK f [] = return [] mapWhileOK f (x : xs) = do x' <- f x ok <- noErrors if ok then do xs' <- mapWhileOK f xs return (x' : xs') else return [x'] idrisMain :: [Opt] -> Idris () idrisMain opts = do let inputs = opt getFile opts let quiet = Quiet `elem` opts let nobanner = NoBanner `elem` opts let idesl = Ideslave `elem` opts || IdeslaveSocket `elem` opts let runrepl = not (NoREPL `elem` opts) let verbose = runrepl || Verbose `elem` opts let output = opt getOutput opts let ibcsubdir = opt getIBCSubDir opts let importdirs = opt getImportDir opts let bcs = opt getBC opts let pkgdirs = opt getPkgDir opts -- Set default optimisations let optimise = case opt getOptLevel opts of [] -> 2 xs -> last xs setOptLevel optimise let outty = case opt getOutputTy opts of [] -> Executable xs -> last xs let cgn = case opt getCodegen opts of [] -> Via "c" xs -> last xs -- Now set/unset specifically chosen optimisations sequence_ (opt getOptimisation opts) script <- case opt getExecScript opts of [] -> return Nothing x:y:xs -> do iputStrLn "More than one interpreter expression found." runIO $ exitWith (ExitFailure 1) [expr] -> return (Just expr) let immediate = opt getEvalExpr opts let port = getPort opts when (DefaultTotal `elem` opts) $ do i <- getIState putIState (i { default_total = True }) setColourise $ not quiet && last (True : opt getColour opts) when (not runrepl) $ setWidth InfinitelyWide mapM_ addLangExt (opt getLanguageExt opts) setREPL runrepl setQuiet (quiet || isJust script || not (null immediate)) setVerbose verbose setCmdLine opts setOutputTy outty setNoBanner nobanner setCodegen cgn mapM_ makeOption opts -- if we have the --bytecode flag, drop into the bytecode assembler case bcs of [] -> return () xs -> return () -- runIO $ mapM_ bcAsm xs case ibcsubdir of [] -> setIBCSubDir "" (d:_) -> setIBCSubDir d setImportDirs importdirs setNoBanner nobanner when (not (NoBasePkgs `elem` opts)) $ do addPkgDir "prelude" addPkgDir "base" mapM_ addPkgDir pkgdirs elabPrims when (not (NoBuiltins `elem` opts)) $ do x <- loadModule "Builtins" addAutoImport "Builtins" return () when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude" addAutoImport "Prelude" return () when (runrepl && not idesl) initScript nobanner <- getNoBanner when (runrepl && not quiet && not idesl && not (isJust script) && not nobanner && null immediate) $ iputStrLn banner orig <- getIState when (not idesl) $ loadInputs inputs Nothing runIO $ hSetBuffering stdout LineBuffering ok <- noErrors when ok $ case output of [] -> return () (o:_) -> idrisCatch (process "" (Compile cgn o)) (\e -> do ist <- getIState ; iputStrLn $ pshow ist e) case immediate of [] -> return () exprs -> do setWidth InfinitelyWide mapM_ (\str -> do ist <- getIState c <- colourise case parseExpr ist str of Failure err -> do iputStrLn $ show (fixColour c err) runIO $ exitWith (ExitFailure 1) Success e -> process "" (Eval e)) exprs runIO $ exitWith ExitSuccess case script of Nothing -> return () Just expr -> execScript expr -- Create Idris data dir + repl history and config dir idrisCatch (do dir <- getIdrisUserDataDir exists <- runIO $ doesDirectoryExist dir unless exists $ iLOG ("Creating " ++ dir) runIO $ createDirectoryIfMissing True (dir </> "repl")) (\e -> return ()) historyFile <- fmap (</> "repl" </> "history") getIdrisUserDataDir when (runrepl && not idesl) $ do -- clearOrigPats startServer port orig inputs runInputT (replSettings (Just historyFile)) $ repl orig inputs let idesock = IdeslaveSocket `elem` opts when (idesl) $ ideslaveStart idesock orig inputs ok <- noErrors when (not ok) $ runIO (exitWith (ExitFailure 1)) where makeOption (OLogging i) = setLogLevel i makeOption TypeCase = setTypeCase True makeOption TypeInType = setTypeInType True makeOption NoCoverage = setCoverage False makeOption ErrContext = setErrContext True makeOption _ = return () addPkgDir :: String -> Idris () addPkgDir p = do ddir <- runIO $ getDataDir addImportDir (ddir </> p) addIBC (IBCImportDir (ddir </> p)) runMain :: Idris () -> IO () runMain prog = do res <- runErrorT $ execStateT prog idrisInit case res of Left err -> putStrLn $ "Uncaught error: " ++ show err Right _ -> return () execScript :: String -> Idris () execScript expr = do i <- getIState c <- colourise case parseExpr i expr of Failure err -> do iputStrLn $ show (fixColour c err) runIO $ exitWith (ExitFailure 1) Success term -> do ctxt <- getContext (tm, _) <- elabVal recinfo ERHS term res <- execute tm runIO $ exitWith ExitSuccess -- | Get the platform-specific, user-specific Idris dir getIdrisUserDataDir :: Idris FilePath getIdrisUserDataDir = runIO $ getAppUserDataDirectory "idris" -- | Locate the platform-specific location for the init script getInitScript :: Idris FilePath getInitScript = do idrisDir <- getIdrisUserDataDir return $ idrisDir </> "repl" </> "init" -- | Run the initialisation script initScript :: Idris () initScript = do script <- getInitScript idrisCatch (do go <- runIO $ doesFileExist script when go $ do h <- runIO $ openFile script ReadMode runInit h runIO $ hClose h) (\e -> iPrintError $ "Error reading init file: " ++ show e) where runInit :: Handle -> Idris () runInit h = do eof <- lift . lift $ hIsEOF h ist <- getIState unless eof $ do line <- runIO $ hGetLine h script <- getInitScript c <- colourise processLine ist line script c runInit h processLine i cmd input clr = case parseCmd i input cmd of Failure err -> runIO $ print (fixColour clr err) Success (Right Reload) -> iPrintError "Init scripts cannot reload the file" Success (Right (Load f _)) -> iPrintError "Init scripts cannot load files" Success (Right (ModImport f)) -> iPrintError "Init scripts cannot import modules" Success (Right Edit) -> iPrintError "Init scripts cannot invoke the editor" Success (Right Proofs) -> proofs i Success (Right Quit) -> iPrintError "Init scripts cannot quit Idris" Success (Right cmd ) -> process [] cmd Success (Left err) -> runIO $ print err getFile :: Opt -> Maybe String getFile (Filename str) = Just str getFile _ = Nothing getBC :: Opt -> Maybe String getBC (BCAsm str) = Just str getBC _ = Nothing getOutput :: Opt -> Maybe String getOutput (Output str) = Just str getOutput _ = Nothing getIBCSubDir :: Opt -> Maybe String getIBCSubDir (IBCSubDir str) = Just str getIBCSubDir _ = Nothing getImportDir :: Opt -> Maybe String getImportDir (ImportDir str) = Just str getImportDir _ = Nothing getPkgDir :: Opt -> Maybe String getPkgDir (Pkg str) = Just str getPkgDir _ = Nothing getPkg :: Opt -> Maybe (Bool, String) getPkg (PkgBuild str) = Just (False, str) getPkg (PkgInstall str) = Just (True, str) getPkg _ = Nothing getPkgClean :: Opt -> Maybe String getPkgClean (PkgClean str) = Just str getPkgClean _ = Nothing getPkgREPL :: Opt -> Maybe String getPkgREPL (PkgREPL str) = Just str getPkgREPL _ = Nothing getPkgCheck :: Opt -> Maybe String getPkgCheck (PkgCheck str) = Just str getPkgCheck _ = Nothing -- | Returns None if given an Opt which is not PkgMkDoc -- Otherwise returns Just x, where x is the contents of PkgMkDoc getPkgMkDoc :: Opt -- ^ Opt to extract -> Maybe String -- ^ Result getPkgMkDoc (PkgMkDoc str) = Just str getPkgMkDoc _ = Nothing getPkgTest :: Opt -- ^ the option to extract -> Maybe String -- ^ the package file to test getPkgTest (PkgTest f) = Just f getPkgTest _ = Nothing getCodegen :: Opt -> Maybe Codegen getCodegen (UseCodegen x) = Just x getCodegen _ = Nothing getExecScript :: Opt -> Maybe String getExecScript (InterpretScript expr) = Just expr getExecScript _ = Nothing getEvalExpr :: Opt -> Maybe String getEvalExpr (EvalExpr expr) = Just expr getEvalExpr _ = Nothing getOutputTy :: Opt -> Maybe OutputType getOutputTy (OutputTy t) = Just t getOutputTy _ = Nothing getLanguageExt :: Opt -> Maybe LanguageExt getLanguageExt (Extension e) = Just e getLanguageExt _ = Nothing getTriple :: Opt -> Maybe String getTriple (TargetTriple x) = Just x getTriple _ = Nothing getCPU :: Opt -> Maybe String getCPU (TargetCPU x) = Just x getCPU _ = Nothing getOptLevel :: Opt -> Maybe Int getOptLevel (OptLevel x) = Just x getOptLevel _ = Nothing getOptimisation :: Opt -> Maybe (Idris ()) getOptimisation (AddOpt p) = Just $ addOptimise p getOptimisation (RemoveOpt p) = Just $ removeOptimise p getOptimisation _ = Nothing getColour :: Opt -> Maybe Bool getColour (ColourREPL b) = Just b getColour _ = Nothing getClient :: Opt -> Maybe String getClient (Client x) = Just x getClient _ = Nothing -- Get the first valid port getPort :: [Opt] -> PortID getPort [] = defaultPort getPort (Port p:xs) | all (`elem` ['0'..'9']) p = PortNumber $ fromIntegral (read p) | otherwise = getPort xs getPort (_:xs) = getPort xs opt :: (Opt -> Maybe a) -> [Opt] -> [a] opt = mapMaybe ver = showVersion version ++ gitHash defaultPort :: PortID defaultPort = PortNumber (fromIntegral 4294) banner = " ____ __ _ \n" ++ " / _/___/ /____(_)____ \n" ++ " / // __ / ___/ / ___/ Version " ++ ver ++ "\n" ++ " _/ // /_/ / / / (__ ) http://www.idris-lang.org/ \n" ++ " /___/\\__,_/_/ /_/____/ Type :? for help \n" ++ "\n" ++ "Idris is free software with ABSOLUTELY NO WARRANTY. \n" ++ "For details type :warranty." warranty = "\n" ++ "\t THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY \n" ++ "\t EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n" ++ "\t IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR \n" ++ "\t PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE \n" ++ "\t LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n" ++ "\t CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n" ++ "\t SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR \n" ++ "\t BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n" ++ "\t WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n" ++ "\t OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n" ++ "\t IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
andyarvanitis/Idris-dev
src/Idris/REPL.hs
bsd-3-clause
78,408
0
25
30,337
23,663
11,405
12,258
1,542
60
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} -- | Build-specific types. module Stack.Types.Build (StackBuildException(..) ,FlagSource(..) ,UnusedFlags(..) ,InstallLocation(..) ,ModTime ,modTime ,Installed(..) ,PackageInstallInfo(..) ,Task(..) ,taskLocation ,LocalPackage(..) ,BaseConfigOpts(..) ,Plan(..) ,TestOpts(..) ,BenchmarkOpts(..) ,FileWatchOpts(..) ,BuildOpts(..) ,BuildSubset(..) ,defaultBuildOpts ,TaskType(..) ,TaskConfigOpts(..) ,ConfigCache(..) ,ConstructPlanException(..) ,configureOpts ,BadDependency(..) ,wantedLocalPackages ,FileCacheInfo (..) ,ConfigureOpts (..) ,PrecompiledCache (..)) where import Control.DeepSeq import Control.Exception import Data.Binary (getWord8, putWord8, gput, gget) import Data.Binary.VersionTagged import qualified Data.ByteString as S import Data.Char (isSpace) import Data.Data import Data.Hashable import Data.List (dropWhileEnd, nub, intercalate) import qualified Data.Map as Map import Data.Map.Strict (Map) import Data.Maybe import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Data.Time.Calendar import Data.Time.Clock import Distribution.System (Arch) import Distribution.PackageDescription (TestSuiteInterface) import Distribution.Text (display) import GHC.Generics import Path (Path, Abs, File, Dir, mkRelDir, toFilePath, parseRelDir, (</>)) import Path.Extra (toFilePathNoTrailingSep) import Prelude import Stack.Types.Compiler import Stack.Types.Config import Stack.Types.FlagName import Stack.Types.GhcPkgId import Stack.Types.Package import Stack.Types.PackageIdentifier import Stack.Types.PackageName import Stack.Types.Version import System.Exit (ExitCode (ExitFailure)) import System.FilePath (pathSeparator) import System.Process.Log (showProcessArgDebug) ---------------------------------------------- -- Exceptions data StackBuildException = Couldn'tFindPkgId PackageName | CompilerVersionMismatch (Maybe (CompilerVersion, Arch)) (CompilerVersion, Arch) GHCVariant VersionCheck (Maybe (Path Abs File)) Text -- recommended resolution -- ^ Path to the stack.yaml file | Couldn'tParseTargets [Text] | UnknownTargets (Set PackageName) -- no known version (Map PackageName Version) -- not in snapshot, here's the most recent version in the index (Path Abs File) -- stack.yaml | TestSuiteFailure PackageIdentifier (Map Text (Maybe ExitCode)) (Maybe (Path Abs File)) S.ByteString | TestSuiteTypeUnsupported TestSuiteInterface | ConstructPlanExceptions [ConstructPlanException] (Path Abs File) -- stack.yaml | CabalExitedUnsuccessfully ExitCode PackageIdentifier (Path Abs File) -- cabal Executable [String] -- cabal arguments (Maybe (Path Abs File)) -- logfiles location [Text] -- log contents | ExecutionFailure [SomeException] | LocalPackageDoesn'tMatchTarget PackageName Version -- local version Version -- version specified on command line | NoSetupHsFound (Path Abs Dir) | InvalidFlagSpecification (Set UnusedFlags) | TargetParseException [Text] | DuplicateLocalPackageNames [(PackageName, [Path Abs Dir])] | SolverGiveUp String | SolverMissingCabalInstall | SomeTargetsNotBuildable [(PackageName, NamedComponent)] | TestSuiteExeMissing Bool String String String | CabalCopyFailed Bool String deriving Typeable data FlagSource = FSCommandLine | FSStackYaml deriving (Show, Eq, Ord) data UnusedFlags = UFNoPackage FlagSource PackageName | UFFlagsNotDefined FlagSource Package (Set FlagName) | UFSnapshot PackageName deriving (Show, Eq, Ord) instance Show StackBuildException where show (Couldn'tFindPkgId name) = ("After installing " <> packageNameString name <> ", the package id couldn't be found " <> "(via ghc-pkg describe " <> packageNameString name <> "). This shouldn't happen, " <> "please report as a bug") show (CompilerVersionMismatch mactual (expected, earch) ghcVariant check mstack resolution) = concat [ case mactual of Nothing -> "No compiler found, expected " Just (actual, arch) -> concat [ "Compiler version mismatched, found " , compilerVersionString actual , " (" , display arch , ")" , ", but expected " ] , case check of MatchMinor -> "minor version match with " MatchExact -> "exact version " NewerMinor -> "minor version match or newer with " , compilerVersionString expected , " (" , display earch , ghcVariantSuffix ghcVariant , ") (based on " , case mstack of Nothing -> "command line arguments" Just stack -> "resolver setting in " ++ toFilePath stack , ").\n" , T.unpack resolution ] show (Couldn'tParseTargets targets) = unlines $ "The following targets could not be parsed as package names or directories:" : map T.unpack targets show (UnknownTargets noKnown notInSnapshot stackYaml) = unlines $ noKnown' ++ notInSnapshot' where noKnown' | Set.null noKnown = [] | otherwise = return $ "The following target packages were not found: " ++ intercalate ", " (map packageNameString $ Set.toList noKnown) notInSnapshot' | Map.null notInSnapshot = [] | otherwise = "The following packages are not in your snapshot, but exist" : "in your package index. Recommended action: add them to your" : ("extra-deps in " ++ toFilePath stackYaml) : "(Note: these are the most recent versions," : "but there's no guarantee that they'll build together)." : "" : map (\(name, version) -> "- " ++ packageIdentifierString (PackageIdentifier name version)) (Map.toList notInSnapshot) show (TestSuiteFailure ident codes mlogFile bs) = unlines $ concat [ ["Test suite failure for package " ++ packageIdentifierString ident] , flip map (Map.toList codes) $ \(name, mcode) -> concat [ " " , T.unpack name , ": " , case mcode of Nothing -> " executable not found" Just ec -> " exited with: " ++ show ec ] , return $ case mlogFile of Nothing -> "Logs printed to console" -- TODO Should we load up the full error output and print it here? Just logFile -> "Full log available at " ++ toFilePath logFile , if S.null bs then [] else ["", "", doubleIndent $ T.unpack $ decodeUtf8With lenientDecode bs] ] where indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines doubleIndent = indent . indent show (TestSuiteTypeUnsupported interface) = ("Unsupported test suite type: " <> show interface) show (ConstructPlanExceptions exceptions stackYaml) = "While constructing the BuildPlan the following exceptions were encountered:" ++ appendExceptions exceptions' ++ if Map.null extras then "" else (unlines $ ("\n\nRecommended action: try adding the following to your extra-deps in " ++ toFilePath stackYaml) : map (\(name, version) -> concat [ "- " , packageNameString name , "-" , versionString version ]) (Map.toList extras) ++ ["", "You may also want to try the 'stack solver' command"] ) where exceptions' = removeDuplicates exceptions appendExceptions = foldr (\e -> (++) ("\n\n--" ++ show e)) "" removeDuplicates = nub extras = Map.unions $ map getExtras exceptions' getExtras (DependencyCycleDetected _) = Map.empty getExtras (UnknownPackage _) = Map.empty getExtras (DependencyPlanFailures _ m) = Map.unions $ map go $ Map.toList m where go (name, (_range, Just version, NotInBuildPlan)) = Map.singleton name version go _ = Map.empty -- Supressing duplicate output show (CabalExitedUnsuccessfully exitCode taskProvides' execName fullArgs logFiles bss) = let fullCmd = unwords $ dropQuotes (toFilePath execName) : map (T.unpack . showProcessArgDebug) fullArgs logLocations = maybe "" (\fp -> "\n Logs have been written to: " ++ toFilePath fp) logFiles in "\n-- While building package " ++ dropQuotes (show taskProvides') ++ " using:\n" ++ " " ++ fullCmd ++ "\n" ++ " Process exited with code: " ++ show exitCode ++ (if exitCode == ExitFailure (-9) then " (THIS MAY INDICATE OUT OF MEMORY)" else "") ++ logLocations ++ (if null bss then "" else "\n\n" ++ doubleIndent (map T.unpack bss)) where doubleIndent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) dropQuotes = filter ('\"' /=) show (ExecutionFailure es) = intercalate "\n\n" $ map show es show (LocalPackageDoesn'tMatchTarget name localV requestedV) = concat [ "Version for local package " , packageNameString name , " is " , versionString localV , ", but you asked for " , versionString requestedV , " on the command line" ] show (NoSetupHsFound dir) = "No Setup.hs or Setup.lhs file found in " ++ toFilePath dir show (InvalidFlagSpecification unused) = unlines $ "Invalid flag specification:" : map go (Set.toList unused) where showFlagSrc :: FlagSource -> String showFlagSrc FSCommandLine = " (specified on command line)" showFlagSrc FSStackYaml = " (specified in stack.yaml)" go :: UnusedFlags -> String go (UFNoPackage src name) = concat [ "- Package '" , packageNameString name , "' not found" , showFlagSrc src ] go (UFFlagsNotDefined src pkg flags) = concat [ "- Package '" , name , "' does not define the following flags" , showFlagSrc src , ":\n" , intercalate "\n" (map (\flag -> " " ++ flagNameString flag) (Set.toList flags)) , "\n- Flags defined by package '" ++ name ++ "':\n" , intercalate "\n" (map (\flag -> " " ++ name ++ ":" ++ flagNameString flag) (Set.toList pkgFlags)) ] where name = packageNameString (packageName pkg) pkgFlags = packageDefinedFlags pkg go (UFSnapshot name) = concat [ "- Attempted to set flag on snapshot package " , packageNameString name , ", please add to extra-deps" ] show (TargetParseException [err]) = "Error parsing targets: " ++ T.unpack err show (TargetParseException errs) = unlines $ "The following errors occurred while parsing the build targets:" : map (("- " ++) . T.unpack) errs show (DuplicateLocalPackageNames pairs) = concat $ "The same package name is used in multiple local packages\n" : map go pairs where go (name, dirs) = unlines $ "" : (packageNameString name ++ " used in:") : map goDir dirs goDir dir = "- " ++ toFilePath dir show (SolverGiveUp msg) = concat [ "\nSolver could not resolve package dependencies.\n" , "You can try the following:\n" , msg ] show SolverMissingCabalInstall = unlines [ "Solver requires that cabal be on your PATH" , "Try running 'stack install cabal-install'" ] show (SomeTargetsNotBuildable xs) = "The following components have 'buildable: False' set in the cabal configuration, and so cannot be targets:\n " ++ T.unpack (renderPkgComponents xs) ++ "\nTo resolve this, either provide flags such that these components are buildable, or only specify buildable targets." show (TestSuiteExeMissing isSimpleBuildType exeName pkgName testName) = missingExeError isSimpleBuildType $ concat [ "Test suite executable \"" , exeName , " not found for " , pkgName , ":test:" , testName ] show (CabalCopyFailed isSimpleBuildType innerMsg) = missingExeError isSimpleBuildType $ concat [ "'cabal copy' failed. Error message:\n" , innerMsg , "\n" ] missingExeError :: Bool -> String -> String missingExeError isSimpleBuildType msg = unlines $ msg : case possibleCauses of [] -> [] [cause] -> ["One possible cause of this issue is:\n* " <> cause] _ -> "Possible causes of this issue:" : map ("* " <>) possibleCauses where possibleCauses = "No module named \"Main\". The 'main-is' source file should usually have a header indicating that it's a 'Main' module." : if isSimpleBuildType then [] else ["The Setup.hs file is changing the installation target dir."] instance Exception StackBuildException data ConstructPlanException = DependencyCycleDetected [PackageName] | DependencyPlanFailures Package (Map PackageName (VersionRange, LatestApplicableVersion, BadDependency)) | UnknownPackage PackageName -- TODO perhaps this constructor will be removed, and BadDependency will handle it all -- ^ Recommend adding to extra-deps, give a helpful version number? deriving (Typeable, Eq) -- | For display purposes only, Nothing if package not found type LatestApplicableVersion = Maybe Version -- | Reason why a dependency was not used data BadDependency = NotInBuildPlan | Couldn'tResolveItsDependencies | DependencyMismatch Version deriving (Typeable, Eq) instance Show ConstructPlanException where show e = let details = case e of (DependencyCycleDetected pNames) -> "While checking call stack,\n" ++ " dependency cycle detected in packages:" ++ indent (appendLines pNames) (DependencyPlanFailures pkg (Map.toList -> pDeps)) -> "Failure when adding dependencies:" ++ doubleIndent (appendDeps pDeps) ++ "\n" ++ " needed for package " ++ packageIdentifierString (packageIdentifier pkg) ++ appendFlags (packageFlags pkg) (UnknownPackage pName) -> "While attempting to add dependency,\n" ++ " Could not find package " ++ show pName ++ " in known packages" in indent details where appendLines = foldr (\pName-> (++) ("\n" ++ show pName)) "" indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines doubleIndent = indent . indent appendFlags flags = if Map.null flags then "" else " with flags:\n" ++ (doubleIndent . intercalate "\n" . map showFlag . Map.toList) flags showFlag (name, bool) = show name ++ ": " ++ show bool appendDeps = foldr (\dep-> (++) ("\n" ++ showDep dep)) "" showDep (name, (range, mlatestApplicable, badDep)) = concat [ show name , ": needed (" , display range , ")" , ", " , let latestApplicableStr = case mlatestApplicable of Nothing -> "" Just la -> " (latest applicable is " ++ versionString la ++ ")" in case badDep of NotInBuildPlan -> "stack configuration has no specified version" ++ latestApplicableStr Couldn'tResolveItsDependencies -> "couldn't resolve its dependencies" DependencyMismatch version -> case mlatestApplicable of Just la | la == version -> versionString version ++ " found (latest applicable version available)" _ -> versionString version ++ " found" ++ latestApplicableStr ] {- TODO Perhaps change the showDep function to look more like this: dropQuotes = filter ((/=) '\"') (VersionOutsideRange pName pIdentifier versionRange) -> "Exception: Stack.Build.VersionOutsideRange\n" ++ " While adding dependency for package " ++ show pName ++ ",\n" ++ " " ++ dropQuotes (show pIdentifier) ++ " was found to be outside its allowed version range.\n" ++ " Allowed version range is " ++ display versionRange ++ ",\n" ++ " should you correct the version range for " ++ dropQuotes (show pIdentifier) ++ ", found in [extra-deps] in the project's stack.yaml?" -} ---------------------------------------------- -- | Package dependency oracle. newtype PkgDepsOracle = PkgDeps PackageName deriving (Show,Typeable,Eq,Hashable,Binary,NFData) -- | Stored on disk to know whether the flags have changed or any -- files have changed. data ConfigCache = ConfigCache { configCacheOpts :: !ConfigureOpts -- ^ All options used for this package. , configCacheDeps :: !(Set GhcPkgId) -- ^ The GhcPkgIds of all of the dependencies. Since Cabal doesn't take -- the complete GhcPkgId (only a PackageIdentifier) in the configure -- options, just using the previous value is insufficient to know if -- dependencies have changed. , configCacheComponents :: !(Set S.ByteString) -- ^ The components to be built. It's a bit of a hack to include this in -- here, as it's not a configure option (just a build option), but this -- is a convenient way to force compilation when the components change. , configCacheHaddock :: !Bool -- ^ Are haddocks to be built? } deriving (Generic,Eq,Show) instance Binary ConfigCache where put x = do -- magic string putWord8 1 putWord8 3 putWord8 4 putWord8 8 gput $ from x get = do 1 <- getWord8 3 <- getWord8 4 <- getWord8 8 <- getWord8 fmap to gget instance NFData ConfigCache instance HasStructuralInfo ConfigCache instance HasSemanticVersion ConfigCache -- | A task to perform when building data Task = Task { taskProvides :: !PackageIdentifier -- ^ the package/version to be built , taskType :: !TaskType -- ^ the task type, telling us how to build this , taskConfigOpts :: !TaskConfigOpts , taskPresent :: !(Map PackageIdentifier GhcPkgId) -- ^ GhcPkgIds of already-installed dependencies , taskAllInOne :: !Bool -- ^ indicates that the package can be built in one step } deriving Show -- | Given the IDs of any missing packages, produce the configure options data TaskConfigOpts = TaskConfigOpts { tcoMissing :: !(Set PackageIdentifier) -- ^ Dependencies for which we don't yet have an GhcPkgId , tcoOpts :: !(Map PackageIdentifier GhcPkgId -> ConfigureOpts) -- ^ Produce the list of options given the missing @GhcPkgId@s } instance Show TaskConfigOpts where show (TaskConfigOpts missing f) = concat [ "Missing: " , show missing , ". Without those: " , show $ f Map.empty ] -- | The type of a task, either building local code or something from the -- package index (upstream) data TaskType = TTLocal LocalPackage | TTUpstream Package InstallLocation deriving Show taskLocation :: Task -> InstallLocation taskLocation task = case taskType task of TTLocal _ -> Local TTUpstream _ loc -> loc -- | A complete plan of what needs to be built and how to do it data Plan = Plan { planTasks :: !(Map PackageName Task) , planFinals :: !(Map PackageName Task) -- ^ Final actions to be taken (test, benchmark, etc) , planUnregisterLocal :: !(Map GhcPkgId (PackageIdentifier, Maybe Text)) -- ^ Text is reason we're unregistering, for display only , planInstallExes :: !(Map Text InstallLocation) -- ^ Executables that should be installed after successful building } deriving Show -- | Basic information used to calculate what the configure options are data BaseConfigOpts = BaseConfigOpts { bcoSnapDB :: !(Path Abs Dir) , bcoLocalDB :: !(Path Abs Dir) , bcoSnapInstallRoot :: !(Path Abs Dir) , bcoLocalInstallRoot :: !(Path Abs Dir) , bcoBuildOpts :: !BuildOpts , bcoBuildOptsCLI :: !BuildOptsCLI , bcoExtraDBs :: ![(Path Abs Dir)] } -- | Render a @BaseConfigOpts@ to an actual list of options configureOpts :: EnvConfig -> BaseConfigOpts -> Map PackageIdentifier GhcPkgId -- ^ dependencies -> Bool -- ^ wanted? -> Bool -- ^ local non-extra-dep? -> InstallLocation -> Package -> ConfigureOpts configureOpts econfig bco deps wanted isLocal loc package = ConfigureOpts { coDirs = configureOptsDirs bco loc package , coNoDirs = configureOptsNoDir econfig bco deps wanted isLocal package } configureOptsDirs :: BaseConfigOpts -> InstallLocation -> Package -> [String] configureOptsDirs bco loc package = concat [ ["--user", "--package-db=clear", "--package-db=global"] , map (("--package-db=" ++) . toFilePathNoTrailingSep) $ case loc of Snap -> bcoExtraDBs bco ++ [bcoSnapDB bco] Local -> bcoExtraDBs bco ++ [bcoSnapDB bco] ++ [bcoLocalDB bco] , [ "--libdir=" ++ toFilePathNoTrailingSep (installRoot </> $(mkRelDir "lib")) , "--bindir=" ++ toFilePathNoTrailingSep (installRoot </> bindirSuffix) , "--datadir=" ++ toFilePathNoTrailingSep (installRoot </> $(mkRelDir "share")) , "--libexecdir=" ++ toFilePathNoTrailingSep (installRoot </> $(mkRelDir "libexec")) , "--sysconfdir=" ++ toFilePathNoTrailingSep (installRoot </> $(mkRelDir "etc")) , "--docdir=" ++ toFilePathNoTrailingSep docDir , "--htmldir=" ++ toFilePathNoTrailingSep docDir , "--haddockdir=" ++ toFilePathNoTrailingSep docDir] ] where installRoot = case loc of Snap -> bcoSnapInstallRoot bco Local -> bcoLocalInstallRoot bco docDir = case pkgVerDir of Nothing -> installRoot </> docDirSuffix Just dir -> installRoot </> docDirSuffix </> dir pkgVerDir = parseRelDir (packageIdentifierString (PackageIdentifier (packageName package) (packageVersion package)) ++ [pathSeparator]) -- | Same as 'configureOpts', but does not include directory path options configureOptsNoDir :: EnvConfig -> BaseConfigOpts -> Map PackageIdentifier GhcPkgId -- ^ dependencies -> Bool -- ^ wanted? -> Bool -- ^ is this a local, non-extra-dep? -> Package -> [String] configureOptsNoDir econfig bco deps wanted isLocal package = concat [ depOptions , ["--enable-library-profiling" | boptsLibProfile bopts || boptsExeProfile bopts] , ["--enable-executable-profiling" | boptsExeProfile bopts && isLocal] , ["--enable-split-objs" | boptsSplitObjs bopts] , map (\(name,enabled) -> "-f" <> (if enabled then "" else "-") <> flagNameString name) (Map.toList (packageFlags package)) , concatMap (\x -> ["--ghc-options", T.unpack x]) allGhcOptions , map (("--extra-include-dirs=" ++) . T.unpack) (Set.toList (configExtraIncludeDirs config)) , map (("--extra-lib-dirs=" ++) . T.unpack) (Set.toList (configExtraLibDirs config)) , if whichCompiler (envConfigCompilerVersion econfig) == Ghcjs then ["--ghcjs"] else [] ] where config = getConfig econfig bopts = bcoBuildOpts bco boptsCli = bcoBuildOptsCLI bco depOptions = map (uncurry toDepOption) $ Map.toList deps where toDepOption = if envConfigCabalVersion econfig >= $(mkVersion "1.22") then toDepOption1_22 else toDepOption1_18 toDepOption1_22 ident gid = concat [ "--dependency=" , packageNameString $ packageIdentifierName ident , "=" , ghcPkgIdString gid ] toDepOption1_18 ident _gid = concat [ "--constraint=" , packageNameString name , "==" , versionString version ] where PackageIdentifier name version = ident allGhcOptions = concat [ Map.findWithDefault [] Nothing (configGhcOptions config) , Map.findWithDefault [] (Just $ packageName package) (configGhcOptions config) , concat [["-fhpc"] | isLocal && toCoverage (boptsTestOpts bopts)] , if (boptsLibProfile bopts || boptsExeProfile bopts) then ["-auto-all","-caf-all"] else [] , if includeExtraOptions then boptsCLIGhcOptions boptsCli else [] ] includeExtraOptions = case configApplyGhcOptions config of AGOTargets -> wanted AGOLocals -> isLocal AGOEverything -> True -- | Get set of wanted package names from locals. wantedLocalPackages :: [LocalPackage] -> Set PackageName wantedLocalPackages = Set.fromList . map (packageName . lpPackage) . filter lpWanted -- | One-way conversion to serialized time. modTime :: UTCTime -> ModTime modTime x = ModTime ( toModifiedJulianDay (utctDay x) , toRational (utctDayTime x)) -- | Configure options to be sent to Setup.hs configure data ConfigureOpts = ConfigureOpts { coDirs :: ![String] -- ^ Options related to various paths. We separate these out since they do -- not have an impact on the contents of the compiled binary for checking -- if we can use an existing precompiled cache. , coNoDirs :: ![String] } deriving (Show, Eq, Generic) instance Binary ConfigureOpts instance HasStructuralInfo ConfigureOpts instance NFData ConfigureOpts -- | Information on a compiled package: the library conf file (if relevant), -- and all of the executable paths. data PrecompiledCache = PrecompiledCache -- Use FilePath instead of Path Abs File for Binary instances { pcLibrary :: !(Maybe FilePath) -- ^ .conf file inside the package database , pcExes :: ![FilePath] -- ^ Full paths to executables } deriving (Show, Eq, Generic) instance Binary PrecompiledCache instance HasSemanticVersion PrecompiledCache instance HasStructuralInfo PrecompiledCache instance NFData PrecompiledCache
narrative/stack
src/Stack/Types/Build.hs
bsd-3-clause
28,819
0
21
9,142
5,575
2,999
2,576
621
8
----------------------------------------------------------------------------- -- | -- Module : Data.SBV.Examples.CodeGeneration.PopulationCount -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- Computing population-counts (number of set bits) and autimatically -- generating C code. ----------------------------------------------------------------------------- module Data.SBV.Examples.CodeGeneration.PopulationCount where import Data.SBV ----------------------------------------------------------------------------- -- * Reference: Slow but /obviously/ correct ----------------------------------------------------------------------------- -- | Given a 64-bit quantity, the simplest (and obvious) way to count the -- number of bits that are set in it is to simply walk through all the bits -- and add 1 to a running count. This is slow, as it requires 64 iterations, -- but is simple and easy to convince yourself that it is correct. For instance: -- -- >>> popCountSlow 0x0123456789ABCDEF -- 32 :: SWord8 popCountSlow :: SWord64 -> SWord8 popCountSlow inp = go inp 0 0 where go :: SWord64 -> Int -> SWord8 -> SWord8 go _ 64 c = c go x i c = go (x `shiftR` 1) (i+1) (ite (x .&. 1 .== 1) (c+1) c) ----------------------------------------------------------------------------- -- * Faster: Using a look-up table ----------------------------------------------------------------------------- -- | Faster version. This is essentially the same algorithm, except we -- go 8 bits at a time instead of one by one, by using a precomputed table -- of population-count values for each byte. This algorithm /loops/ only -- 8 times, and hence is at least 8 times more efficient. popCountFast :: SWord64 -> SWord8 popCountFast inp = go inp 0 0 where go :: SWord64 -> Int -> SWord8 -> SWord8 go _ 8 c = c go x i c = go (x `shiftR` 8) (i+1) (c + select pop8 0 (x .&. 0xff)) -- | Look-up table, containing population counts for all possible 8-bit -- value, from 0 to 255. Note that we do not \"hard-code\" the values, but -- merely use the slow version to compute them. pop8 :: [SWord8] pop8 = map popCountSlow [0 .. 255] ----------------------------------------------------------------------------- -- * Verification ----------------------------------------------------------------------------- {- $VerificationIntro We prove that `popCountFast` and `popCountSlow` are functionally equivalent. This is essential as we will automatically generate C code from `popCountFast`, and we would like to make sure that the fast version is correct with respect to the slower reference version. -} -- | States the correctness of faster population-count algorithm, with respect -- to the reference slow version. (We use yices here as it's quite fast for -- this problem. Z3 seems to take much longer.) We have: -- -- >>> proveWith yices fastPopCountIsCorrect -- Q.E.D. fastPopCountIsCorrect :: SWord64 -> SBool fastPopCountIsCorrect x = popCountFast x .== popCountSlow x ----------------------------------------------------------------------------- -- * Code generation ----------------------------------------------------------------------------- -- | Not only we can prove that faster version is correct, but we can also automatically -- generate C code to compute population-counts for us. This action will generate all the -- C files that you will need, including a driver program for test purposes. -- -- Below is the generated header file for `popCountFast`: -- -- >>> genPopCountInC -- == BEGIN: "Makefile" ================ -- # Makefile for popCount. Automatically generated by SBV. Do not edit! -- <BLANKLINE> -- # include any user-defined .mk file in the current directory. -- -include *.mk -- <BLANKLINE> -- CC=gcc -- CCFLAGS?=-Wall -O3 -DNDEBUG -fomit-frame-pointer -- <BLANKLINE> -- all: popCount_driver -- <BLANKLINE> -- popCount.o: popCount.c popCount.h -- ${CC} ${CCFLAGS} -c $< -o $@ -- <BLANKLINE> -- popCount_driver.o: popCount_driver.c -- ${CC} ${CCFLAGS} -c $< -o $@ -- <BLANKLINE> -- popCount_driver: popCount.o popCount_driver.o -- ${CC} ${CCFLAGS} $^ -o $@ -- <BLANKLINE> -- clean: -- rm -f *.o -- <BLANKLINE> -- veryclean: clean -- rm -f popCount_driver -- == END: "Makefile" ================== -- == BEGIN: "popCount.h" ================ -- /* Header file for popCount. Automatically generated by SBV. Do not edit! */ -- <BLANKLINE> -- #ifndef __popCount__HEADER_INCLUDED__ -- #define __popCount__HEADER_INCLUDED__ -- <BLANKLINE> -- #include <inttypes.h> -- #include <stdint.h> -- #include <stdbool.h> -- #include <math.h> -- <BLANKLINE> -- /* The boolean type */ -- typedef bool SBool; -- <BLANKLINE> -- /* The float type */ -- typedef float SFloat; -- <BLANKLINE> -- /* The double type */ -- typedef double SDouble; -- <BLANKLINE> -- /* Unsigned bit-vectors */ -- typedef uint8_t SWord8 ; -- typedef uint16_t SWord16; -- typedef uint32_t SWord32; -- typedef uint64_t SWord64; -- <BLANKLINE> -- /* Signed bit-vectors */ -- typedef int8_t SInt8 ; -- typedef int16_t SInt16; -- typedef int32_t SInt32; -- typedef int64_t SInt64; -- <BLANKLINE> -- /* Entry point prototype: */ -- SWord8 popCount(const SWord64 x); -- <BLANKLINE> -- #endif /* __popCount__HEADER_INCLUDED__ */ -- == END: "popCount.h" ================== -- == BEGIN: "popCount_driver.c" ================ -- /* Example driver program for popCount. */ -- /* Automatically generated by SBV. Edit as you see fit! */ -- <BLANKLINE> -- #include <inttypes.h> -- #include <stdint.h> -- #include <stdbool.h> -- #include <math.h> -- #include <stdio.h> -- #include "popCount.h" -- <BLANKLINE> -- int main(void) -- { -- const SWord8 __result = popCount(0x1b02e143e4f0e0e5ULL); -- <BLANKLINE> -- printf("popCount(0x1b02e143e4f0e0e5ULL) = %"PRIu8"\n", __result); -- <BLANKLINE> -- return 0; -- } -- == END: "popCount_driver.c" ================== -- == BEGIN: "popCount.c" ================ -- /* File: "popCount.c". Automatically generated by SBV. Do not edit! */ -- <BLANKLINE> -- #include <inttypes.h> -- #include <stdint.h> -- #include <stdbool.h> -- #include <math.h> -- #include "popCount.h" -- <BLANKLINE> -- SWord8 popCount(const SWord64 x) -- { -- const SWord64 s0 = x; -- static const SWord8 table0[] = { -- 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, -- 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, -- 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, -- 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, -- 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, -- 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, -- 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, -- 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, -- 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, -- 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, -- 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, -- 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 -- }; -- const SWord64 s11 = s0 & 0x00000000000000ffULL; -- const SWord8 s12 = table0[s11]; -- const SWord64 s13 = s0 >> 8; -- const SWord64 s14 = 0x00000000000000ffULL & s13; -- const SWord8 s15 = table0[s14]; -- const SWord8 s16 = s12 + s15; -- const SWord64 s17 = s13 >> 8; -- const SWord64 s18 = 0x00000000000000ffULL & s17; -- const SWord8 s19 = table0[s18]; -- const SWord8 s20 = s16 + s19; -- const SWord64 s21 = s17 >> 8; -- const SWord64 s22 = 0x00000000000000ffULL & s21; -- const SWord8 s23 = table0[s22]; -- const SWord8 s24 = s20 + s23; -- const SWord64 s25 = s21 >> 8; -- const SWord64 s26 = 0x00000000000000ffULL & s25; -- const SWord8 s27 = table0[s26]; -- const SWord8 s28 = s24 + s27; -- const SWord64 s29 = s25 >> 8; -- const SWord64 s30 = 0x00000000000000ffULL & s29; -- const SWord8 s31 = table0[s30]; -- const SWord8 s32 = s28 + s31; -- const SWord64 s33 = s29 >> 8; -- const SWord64 s34 = 0x00000000000000ffULL & s33; -- const SWord8 s35 = table0[s34]; -- const SWord8 s36 = s32 + s35; -- const SWord64 s37 = s33 >> 8; -- const SWord64 s38 = 0x00000000000000ffULL & s37; -- const SWord8 s39 = table0[s38]; -- const SWord8 s40 = s36 + s39; -- <BLANKLINE> -- return s40; -- } -- == END: "popCount.c" ================== genPopCountInC :: IO () genPopCountInC = compileToC Nothing "popCount" "" $ do cgSetDriverValues [0x1b02e143e4f0e0e5] -- remove this line to get a random test value x <- cgInput "x" cgReturn $ popCountFast x
Copilot-Language/sbv-for-copilot
Data/SBV/Examples/CodeGeneration/PopulationCount.hs
bsd-3-clause
8,735
0
12
1,684
544
377
167
21
2
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE OverloadedStrings #-} module Duckling.Email.Corpus ( corpus , negativeCorpus ) where import Prelude import Data.String import Duckling.Email.Types import Duckling.Testing.Types corpus :: Corpus corpus = (testContext, allExamples) negativeCorpus :: NegativeCorpus negativeCorpus = (testContext, examples) where examples = [ "hey@6" , "hey@you" ] allExamples :: [Example] allExamples = concat [ examples (EmailData "[email protected]") [ "[email protected]" ] , examples (EmailData "[email protected]") [ "[email protected]" ] , examples (EmailData "[email protected]") [ "[email protected]" ] , examples (EmailData "[email protected]") [ "[email protected]" ] ]
rfranek/duckling
Duckling/Email/Corpus.hs
bsd-3-clause
1,127
0
9
282
171
103
68
25
1
{-# LANGUAGE TypeFamilies, TypeSynonymInstances, FlexibleInstances, PackageImports, OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module File.Binary.Instances () where import Prelude hiding (take, drop, span) import File.Binary.Classes (Field(..), Binary(..)) import Data.Word (Word8) import Data.ByteString.Lazy (ByteString, take, drop, toChunks, fromChunks, pack, unpack, uncons, span) import qualified Data.ByteString.Lazy.Char8 as BSLC (pack, unpack) import qualified Data.ByteString as BS (ByteString, take, drop, concat, uncons, span) import qualified Data.ByteString.Char8 () import Control.Monad (foldM) import "monads-tf" Control.Monad.State (StateT(..)) import Control.Applicative ((<$>)) import Control.Arrow (first, (&&&)) import Data.Monoid (mempty) import Data.Char import Data.Maybe -------------------------------------------------------------------------------- instance Field ByteString where type FieldArgument ByteString = Int fromBinary a = return . getBytes a toBinary _ = return . makeBinary instance Field BS.ByteString where type FieldArgument BS.ByteString = Int fromBinary n = return . first (BS.concat . toChunks) . getBytes n toBinary _ = return . makeBinary . fromChunks . (: []) instance Field Char where type FieldArgument Char = () fromBinary _ = return . first (head . BSLC.unpack) . getBytes 1 toBinary _ = return . makeBinary . BSLC.pack . (: []) instance Field Word8 where type FieldArgument Word8 = () fromBinary _ = return . first (head . unpack) . getBytes 1 toBinary _ = return . makeBinary . pack . (: []) instance Field r => Field [r] where type FieldArgument [r] = [FieldArgument r] fromBits as = smap mempty as fromBits consToBits as fs ret = foldM (flip $ uncurry consToBits) ret $ reverse $ zip as fs myMapM :: (Monad m, Functor m) => (a -> m (Maybe b)) -> [a] -> m [b] myMapM _ [] = return [] myMapM f (x : xs) = do ret <- f x case ret of Just y -> (y :) <$> myMapM f xs Nothing -> return [] smap :: (Monad m, Functor m, Eq s) => s -> [a] -> (a -> s -> m (ret, s)) -> s -> m ([ret], s) smap e xs f = runStateT $ myMapM (StateT . f') xs where f' x s | s == e = return (Nothing, s) | otherwise = first Just <$> f x s -------------------------------------------------------------------------------- instance Binary String where getBytes n = first BSLC.pack . splitAt n unconsByte = fromIntegral . ord . head &&& tail makeBinary = BSLC.unpack instance Binary ByteString where getBytes n = take (fromIntegral n) &&& drop (fromIntegral n) spanBytes = span unconsByte = fromMaybe (0, "") . uncons makeBinary = id instance Binary BS.ByteString where getBytes n = fromChunks . (: []) . BS.take n &&& BS.drop n spanBytes p = first (fromChunks . (: [])) . BS.span p unconsByte = fromMaybe (0, "") . BS.uncons makeBinary = BS.concat . toChunks
YoshikuniJujo/binary-file
src/File/Binary/Instances.hs
bsd-3-clause
2,851
4
13
497
1,116
603
513
-1
-1
module Oden.SourceInfo where type Line = Int type Column = Int data Position = Position { fileName :: FilePath , line :: Line , column :: Column } deriving (Eq, Ord) instance Show Position where show (Position f l c) = f ++ ":" ++ show l ++ ":" ++ show c data SourceInfo = SourceInfo { position :: Position } | Predefined | Missing deriving (Eq, Ord) instance Show SourceInfo where show Predefined = "<predefined>" show Missing = "<missing>" show (SourceInfo pos) = show pos -- | Types from which you can get and set 'SourceInfo'. class HasSourceInfo t where getSourceInfo :: t -> SourceInfo setSourceInfo :: SourceInfo -> t -> t
oden-lang/oden
src/Oden/SourceInfo.hs
mit
762
0
9
245
209
114
95
20
0
module Tests.Writers.AsciiDoc (tests) where import Test.Framework import Text.Pandoc.Builder import Text.Pandoc import Tests.Helpers import Tests.Arbitrary() asciidoc :: (ToString a, ToPandoc a) => a -> String asciidoc = writeAsciiDoc def{ writerWrapText = False } . toPandoc tests :: [Test] tests = [ testGroup "emphasis" [ test asciidoc "emph word before" $ para (text "foo" <> emph (text "bar")) =?> "foo__bar__" , test asciidoc "emph word after" $ para (emph (text "foo") <> text "bar") =?> "__foo__bar" , test asciidoc "emph quoted" $ para (doubleQuoted (emph (text "foo"))) =?> "``__foo__''" , test asciidoc "strong word before" $ para (text "foo" <> strong (text "bar")) =?> "foo**bar**" , test asciidoc "strong word after" $ para (strong (text "foo") <> text "bar") =?> "**foo**bar" , test asciidoc "strong quoted" $ para (singleQuoted (strong (text "foo"))) =?> "`**foo**'" ] , testGroup "tables" [ test asciidoc "empty cells" $ simpleTable [] [[mempty],[mempty]] =?> unlines [ "[cols=\"\",]" , "|====" , "|" , "|" , "|====" ] , test asciidoc "multiblock cells" $ simpleTable [] [[para (text "Para 1") <> para (text "Para 2")]] =?> unlines [ "[cols=\"\",]" , "|=====" , "a|" , "Para 1" , "" , "Para 2" , "" , "|=====" ] ] ]
alexvong1995/pandoc
tests/Tests/Writers/AsciiDoc.hs
gpl-2.0
2,262
0
16
1,227
471
246
225
47
1
{-| The @notes@ command lists all unique notes (description part after a |) seen in transactions, sorted alphabetically. -} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE CPP #-} module Hledger.Cli.Commands.Notes ( notesmode ,notes ) where import Data.List.Extra (nubSort) import qualified Data.Text.IO as T import Hledger import Hledger.Cli.CliOptions -- | Command line options for this command. notesmode = hledgerCommandMode $(embedFileRelative "Hledger/Cli/Commands/Notes.txt") [] [generalflagsgroup1] hiddenflags ([], Just $ argsFlag "[QUERY]") -- | The notes command. notes :: CliOpts -> Journal -> IO () notes CliOpts{reportspec_=rspec} j = do let ts = entriesReport rspec j notes = nubSort $ map transactionNote ts mapM_ T.putStrLn notes
adept/hledger
hledger/Hledger/Cli/Commands/Notes.hs
gpl-3.0
877
0
11
145
171
97
74
23
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.SWF.RequestCancelWorkflowExecution -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Records a 'WorkflowExecutionCancelRequested' event in the currently running -- workflow execution identified by the given domain, workflowId, and runId. -- This logically requests the cancellation of the workflow execution as a -- whole. It is up to the decider to take appropriate actions when it receives -- an execution history with this event. -- -- If the runId is not specified, the 'WorkflowExecutionCancelRequested' event is -- recorded in the history of the current open workflow execution with the -- specified workflowId in the domain. Because this action allows the workflow -- to properly clean up and gracefully close, it should be used instead of 'TerminateWorkflowExecution' when possible. Access Control -- -- You can use IAM policies to control this action's access to Amazon SWF -- resources as follows: -- -- Use a 'Resource' element with the domain name to limit the action to only -- specified domains. Use an 'Action' element to allow or deny permission to call -- this action. You cannot use an IAM policy to constrain this action's -- parameters. If the caller does not have sufficient permissions to invoke the -- action, or the parameter values fall outside the specified constraints, the -- action fails. The associated event attribute's cause parameter will be set to -- OPERATION_NOT_PERMITTED. For details and example IAM policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAMto Manage Access to Amazon SWF Workflows>. -- -- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_RequestCancelWorkflowExecution.html> module Network.AWS.SWF.RequestCancelWorkflowExecution ( -- * Request RequestCancelWorkflowExecution -- ** Request constructor , requestCancelWorkflowExecution -- ** Request lenses , rcweDomain , rcweRunId , rcweWorkflowId -- * Response , RequestCancelWorkflowExecutionResponse -- ** Response constructor , requestCancelWorkflowExecutionResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.SWF.Types import qualified GHC.Exts data RequestCancelWorkflowExecution = RequestCancelWorkflowExecution { _rcweDomain :: Text , _rcweRunId :: Maybe Text , _rcweWorkflowId :: Text } deriving (Eq, Ord, Read, Show) -- | 'RequestCancelWorkflowExecution' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rcweDomain' @::@ 'Text' -- -- * 'rcweRunId' @::@ 'Maybe' 'Text' -- -- * 'rcweWorkflowId' @::@ 'Text' -- requestCancelWorkflowExecution :: Text -- ^ 'rcweDomain' -> Text -- ^ 'rcweWorkflowId' -> RequestCancelWorkflowExecution requestCancelWorkflowExecution p1 p2 = RequestCancelWorkflowExecution { _rcweDomain = p1 , _rcweWorkflowId = p2 , _rcweRunId = Nothing } -- | The name of the domain containing the workflow execution to cancel. rcweDomain :: Lens' RequestCancelWorkflowExecution Text rcweDomain = lens _rcweDomain (\s a -> s { _rcweDomain = a }) -- | The runId of the workflow execution to cancel. rcweRunId :: Lens' RequestCancelWorkflowExecution (Maybe Text) rcweRunId = lens _rcweRunId (\s a -> s { _rcweRunId = a }) -- | The workflowId of the workflow execution to cancel. rcweWorkflowId :: Lens' RequestCancelWorkflowExecution Text rcweWorkflowId = lens _rcweWorkflowId (\s a -> s { _rcweWorkflowId = a }) data RequestCancelWorkflowExecutionResponse = RequestCancelWorkflowExecutionResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'RequestCancelWorkflowExecutionResponse' constructor. requestCancelWorkflowExecutionResponse :: RequestCancelWorkflowExecutionResponse requestCancelWorkflowExecutionResponse = RequestCancelWorkflowExecutionResponse instance ToPath RequestCancelWorkflowExecution where toPath = const "/" instance ToQuery RequestCancelWorkflowExecution where toQuery = const mempty instance ToHeaders RequestCancelWorkflowExecution instance ToJSON RequestCancelWorkflowExecution where toJSON RequestCancelWorkflowExecution{..} = object [ "domain" .= _rcweDomain , "workflowId" .= _rcweWorkflowId , "runId" .= _rcweRunId ] instance AWSRequest RequestCancelWorkflowExecution where type Sv RequestCancelWorkflowExecution = SWF type Rs RequestCancelWorkflowExecution = RequestCancelWorkflowExecutionResponse request = post "RequestCancelWorkflowExecution" response = nullResponse RequestCancelWorkflowExecutionResponse
romanb/amazonka
amazonka-swf/gen/Network/AWS/SWF/RequestCancelWorkflowExecution.hs
mpl-2.0
5,657
0
9
1,083
512
317
195
61
1
{-# LANGUAGE PArr #-} {-# OPTIONS -fvectorise #-} module Matrix where import Data.Array.Parallel.Prelude import qualified Data.Array.Parallel.Prelude.Int as I import Data.Array.Parallel.Prelude.Double as D import qualified Prelude type MMatrix = [:D.Double:] div = I.div seqSize = 1::Prelude.Int mmMult m n = mmMult' (128::Prelude.Int) (fromPArrayP m) (fromPArrayP n) mmMult':: Prelude.Int -> MMatrix -> MMatrix -> MMatrix mmMult' order m n = m {- -- assumes size is 2^n mmMult':: Prelude.Int -> MMatrix -> MMatrix -> MMatrix mmMult' order m n | order I.== (1::Prelude.Int) = simpleMult m n | otherwise = n where o2 = order `div` (2::Prelude.Int) subs = replicateP 4 (o2 I.* o2) mss = attachShape (mkShape subs) m nss = attachShape (mkShape subs) n res = mapP (Prelude.uncurry (mmMult' o2)) (zipP mss nss) simpleMult::[:Double:] -> [:Double:] ->[:Double:] simpleMult m n = zipWithP (*) m n -} {- foo n = mapP sumP ((replicateP (4::Prelude.Int) (replicateP (1::Prelude.Int) (10.0)))) -}
mainland/dph
icebox/examples/matrix/Matrix.hs
bsd-3-clause
1,076
3
7
238
141
86
55
-1
-1
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Data/Vector/Storable/Mutable.hs" #-} {-# LANGUAGE CPP, DeriveDataTypeable, FlexibleInstances, MagicHash, MultiParamTypeClasses, ScopedTypeVariables #-} -- | -- Module : Data.Vector.Storable.Mutable -- Copyright : (c) Roman Leshchinskiy 2009-2010 -- License : BSD-style -- -- Maintainer : Roman Leshchinskiy <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- Mutable vectors based on Storable. -- module Data.Vector.Storable.Mutable( -- * Mutable vectors of 'Storable' types MVector(..), IOVector, STVector, Storable, -- * Accessors -- ** Length information length, null, -- ** Extracting subvectors slice, init, tail, take, drop, splitAt, unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop, -- ** Overlapping overlaps, -- * Construction -- ** Initialisation new, unsafeNew, replicate, replicateM, clone, -- ** Growing grow, unsafeGrow, -- ** Restricting memory usage clear, -- * Accessing individual elements read, write, modify, swap, unsafeRead, unsafeWrite, unsafeModify, unsafeSwap, -- * Modifying vectors -- ** Filling and copying set, copy, move, unsafeCopy, unsafeMove, -- * Unsafe conversions unsafeCast, -- * Raw pointers unsafeFromForeignPtr, unsafeFromForeignPtr0, unsafeToForeignPtr, unsafeToForeignPtr0, unsafeWith ) where import Control.DeepSeq ( NFData(rnf) ) import qualified Data.Vector.Generic.Mutable as G import Data.Vector.Storable.Internal import Foreign.Storable import Foreign.ForeignPtr import GHC.ForeignPtr (mallocPlainForeignPtrAlignedBytes) import Foreign.Ptr import Foreign.Marshal.Array ( advancePtr, copyArray, moveArray ) import Control.Monad.Primitive import Data.Primitive.Addr import Data.Primitive.Types (Prim) import GHC.Word (Word8, Word16, Word32, Word64) import GHC.Ptr (Ptr(..)) import Prelude hiding ( length, null, replicate, reverse, map, read, take, drop, splitAt, init, tail ) import Data.Typeable ( Typeable ) -- Data.Vector.Internal.Check is not needed -- | Mutable 'Storable'-based vectors data MVector s a = MVector {-# UNPACK #-} !Int {-# UNPACK #-} !(ForeignPtr a) deriving ( Typeable ) type IOVector = MVector RealWorld type STVector s = MVector s instance NFData (MVector s a) where rnf (MVector _ _) = () instance Storable a => G.MVector MVector a where {-# INLINE basicLength #-} basicLength (MVector n _) = n {-# INLINE basicUnsafeSlice #-} basicUnsafeSlice j m (MVector _ fp) = MVector m (updPtr (`advancePtr` j) fp) -- FIXME: this relies on non-portable pointer comparisons {-# INLINE basicOverlaps #-} basicOverlaps (MVector m fp) (MVector n fq) = between p q (q `advancePtr` n) || between q p (p `advancePtr` m) where between x y z = x >= y && x < z p = getPtr fp q = getPtr fq {-# INLINE basicUnsafeNew #-} basicUnsafeNew n | n < 0 = error $ "Storable.basicUnsafeNew: negative length: " ++ show n | n > mx = error $ "Storable.basicUnsafeNew: length too large: " ++ show n | otherwise = unsafePrimToPrim $ do fp <- mallocVector n return $ MVector n fp where size = sizeOf (undefined :: a) mx = maxBound `quot` size :: Int {-# INLINE basicInitialize #-} basicInitialize = storableZero {-# INLINE basicUnsafeRead #-} basicUnsafeRead (MVector _ fp) i = unsafePrimToPrim $ withForeignPtr fp (`peekElemOff` i) {-# INLINE basicUnsafeWrite #-} basicUnsafeWrite (MVector _ fp) i x = unsafePrimToPrim $ withForeignPtr fp $ \p -> pokeElemOff p i x {-# INLINE basicSet #-} basicSet = storableSet {-# INLINE basicUnsafeCopy #-} basicUnsafeCopy (MVector n fp) (MVector _ fq) = unsafePrimToPrim $ withForeignPtr fp $ \p -> withForeignPtr fq $ \q -> copyArray p q n {-# INLINE basicUnsafeMove #-} basicUnsafeMove (MVector n fp) (MVector _ fq) = unsafePrimToPrim $ withForeignPtr fp $ \p -> withForeignPtr fq $ \q -> moveArray p q n storableZero :: forall a m. (Storable a, PrimMonad m) => MVector (PrimState m) a -> m () {-# INLINE storableZero #-} storableZero (MVector n fp) = unsafePrimToPrim . withForeignPtr fp $ \(Ptr p) -> do let q = Addr p setAddr q byteSize (0 :: Word8) where x :: a x = undefined byteSize :: Int byteSize = n * sizeOf x storableSet :: (Storable a, PrimMonad m) => MVector (PrimState m) a -> a -> m () {-# INLINE storableSet #-} storableSet (MVector n fp) x | n == 0 = return () | otherwise = unsafePrimToPrim $ case sizeOf x of 1 -> storableSetAsPrim n fp x (undefined :: Word8) 2 -> storableSetAsPrim n fp x (undefined :: Word16) 4 -> storableSetAsPrim n fp x (undefined :: Word32) 8 -> storableSetAsPrim n fp x (undefined :: Word64) _ -> withForeignPtr fp $ \p -> do poke p x let do_set i | 2*i < n = do copyArray (p `advancePtr` i) p i do_set (2*i) | otherwise = copyArray (p `advancePtr` i) p (n-i) do_set 1 storableSetAsPrim :: (Storable a, Prim b) => Int -> ForeignPtr a -> a -> b -> IO () {-# INLINE [0] storableSetAsPrim #-} storableSetAsPrim n fp x y = withForeignPtr fp $ \(Ptr p) -> do poke (Ptr p) x let q = Addr p w <- readOffAddr q 0 setAddr (q `plusAddr` sizeOf x) (n-1) (w `asTypeOf` y) {-# INLINE mallocVector #-} mallocVector :: Storable a => Int -> IO (ForeignPtr a) mallocVector = doMalloc undefined where doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b) doMalloc dummy size = mallocPlainForeignPtrAlignedBytes (size * sizeOf dummy) (alignment dummy) -- Length information -- ------------------ -- | Length of the mutable vector. length :: Storable a => MVector s a -> Int {-# INLINE length #-} length = G.length -- | Check whether the vector is empty null :: Storable a => MVector s a -> Bool {-# INLINE null #-} null = G.null -- Extracting subvectors -- --------------------- -- | Yield a part of the mutable vector without copying it. slice :: Storable a => Int -> Int -> MVector s a -> MVector s a {-# INLINE slice #-} slice = G.slice take :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE take #-} take = G.take drop :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE drop #-} drop = G.drop splitAt :: Storable a => Int -> MVector s a -> (MVector s a, MVector s a) {-# INLINE splitAt #-} splitAt = G.splitAt init :: Storable a => MVector s a -> MVector s a {-# INLINE init #-} init = G.init tail :: Storable a => MVector s a -> MVector s a {-# INLINE tail #-} tail = G.tail -- | Yield a part of the mutable vector without copying it. No bounds checks -- are performed. unsafeSlice :: Storable a => Int -- ^ starting index -> Int -- ^ length of the slice -> MVector s a -> MVector s a {-# INLINE unsafeSlice #-} unsafeSlice = G.unsafeSlice unsafeTake :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE unsafeTake #-} unsafeTake = G.unsafeTake unsafeDrop :: Storable a => Int -> MVector s a -> MVector s a {-# INLINE unsafeDrop #-} unsafeDrop = G.unsafeDrop unsafeInit :: Storable a => MVector s a -> MVector s a {-# INLINE unsafeInit #-} unsafeInit = G.unsafeInit unsafeTail :: Storable a => MVector s a -> MVector s a {-# INLINE unsafeTail #-} unsafeTail = G.unsafeTail -- Overlapping -- ----------- -- | Check whether two vectors overlap. overlaps :: Storable a => MVector s a -> MVector s a -> Bool {-# INLINE overlaps #-} overlaps = G.overlaps -- Initialisation -- -------------- -- | Create a mutable vector of the given length. new :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a) {-# INLINE new #-} new = G.new -- | Create a mutable vector of the given length. The memory is not initialized. unsafeNew :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a) {-# INLINE unsafeNew #-} unsafeNew = G.unsafeNew -- | Create a mutable vector of the given length (0 if the length is negative) -- and fill it with an initial value. replicate :: (PrimMonad m, Storable a) => Int -> a -> m (MVector (PrimState m) a) {-# INLINE replicate #-} replicate = G.replicate -- | Create a mutable vector of the given length (0 if the length is negative) -- and fill it with values produced by repeatedly executing the monadic action. replicateM :: (PrimMonad m, Storable a) => Int -> m a -> m (MVector (PrimState m) a) {-# INLINE replicateM #-} replicateM = G.replicateM -- | Create a copy of a mutable vector. clone :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> m (MVector (PrimState m) a) {-# INLINE clone #-} clone = G.clone -- Growing -- ------- -- | Grow a vector by the given number of elements. The number must be -- positive. grow :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a) {-# INLINE grow #-} grow = G.grow -- | Grow a vector by the given number of elements. The number must be -- positive but this is not checked. unsafeGrow :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a) {-# INLINE unsafeGrow #-} unsafeGrow = G.unsafeGrow -- Restricting memory usage -- ------------------------ -- | Reset all elements of the vector to some undefined value, clearing all -- references to external objects. This is usually a noop for unboxed vectors. clear :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> m () {-# INLINE clear #-} clear = G.clear -- Accessing individual elements -- ----------------------------- -- | Yield the element at the given position. read :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a {-# INLINE read #-} read = G.read -- | Replace the element at the given position. write :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m () {-# INLINE write #-} write = G.write -- | Modify the element at the given position. modify :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> (a -> a) -> Int -> m () {-# INLINE modify #-} modify = G.modify -- | Swap the elements at the given positions. swap :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m () {-# INLINE swap #-} swap = G.swap -- | Yield the element at the given position. No bounds checks are performed. unsafeRead :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a {-# INLINE unsafeRead #-} unsafeRead = G.unsafeRead -- | Replace the element at the given position. No bounds checks are performed. unsafeWrite :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m () {-# INLINE unsafeWrite #-} unsafeWrite = G.unsafeWrite -- | Modify the element at the given position. No bounds checks are performed. unsafeModify :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> (a -> a) -> Int -> m () {-# INLINE unsafeModify #-} unsafeModify = G.unsafeModify -- | Swap the elements at the given positions. No bounds checks are performed. unsafeSwap :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m () {-# INLINE unsafeSwap #-} unsafeSwap = G.unsafeSwap -- Filling and copying -- ------------------- -- | Set all elements of the vector to the given value. set :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> a -> m () {-# INLINE set #-} set = G.set -- | Copy a vector. The two vectors must have the same length and may not -- overlap. copy :: (PrimMonad m, Storable a) => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE copy #-} copy = G.copy -- | Copy a vector. The two vectors must have the same length and may not -- overlap. This is not checked. unsafeCopy :: (PrimMonad m, Storable a) => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE unsafeCopy #-} unsafeCopy = G.unsafeCopy -- | Move the contents of a vector. The two vectors must have the same -- length. -- -- If the vectors do not overlap, then this is equivalent to 'copy'. -- Otherwise, the copying is performed as if the source vector were -- copied to a temporary vector and then the temporary vector was copied -- to the target vector. move :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> MVector (PrimState m) a -> m () {-# INLINE move #-} move = G.move -- | Move the contents of a vector. The two vectors must have the same -- length, but this is not checked. -- -- If the vectors do not overlap, then this is equivalent to 'unsafeCopy'. -- Otherwise, the copying is performed as if the source vector were -- copied to a temporary vector and then the temporary vector was copied -- to the target vector. unsafeMove :: (PrimMonad m, Storable a) => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE unsafeMove #-} unsafeMove = G.unsafeMove -- Unsafe conversions -- ------------------ -- | /O(1)/ Unsafely cast a mutable vector from one element type to another. -- The operation just changes the type of the underlying pointer and does not -- modify the elements. -- -- The resulting vector contains as many elements as can fit into the -- underlying memory block. -- unsafeCast :: forall a b s. (Storable a, Storable b) => MVector s a -> MVector s b {-# INLINE unsafeCast #-} unsafeCast (MVector n fp) = MVector ((n * sizeOf (undefined :: a)) `div` sizeOf (undefined :: b)) (castForeignPtr fp) -- Raw pointers -- ------------ -- | Create a mutable vector from a 'ForeignPtr' with an offset and a length. -- -- Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector -- could have been frozen before the modification. -- -- If your offset is 0 it is more efficient to use 'unsafeFromForeignPtr0'. unsafeFromForeignPtr :: Storable a => ForeignPtr a -- ^ pointer -> Int -- ^ offset -> Int -- ^ length -> MVector s a {-# INLINE [1] unsafeFromForeignPtr #-} unsafeFromForeignPtr fp i n = unsafeFromForeignPtr0 fp' n where fp' = updPtr (`advancePtr` i) fp {-# RULES "unsafeFromForeignPtr fp 0 n -> unsafeFromForeignPtr0 fp n " forall fp n. unsafeFromForeignPtr fp 0 n = unsafeFromForeignPtr0 fp n #-} -- | /O(1)/ Create a mutable vector from a 'ForeignPtr' and a length. -- -- It is assumed the pointer points directly to the data (no offset). -- Use `unsafeFromForeignPtr` if you need to specify an offset. -- -- Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector -- could have been frozen before the modification. unsafeFromForeignPtr0 :: Storable a => ForeignPtr a -- ^ pointer -> Int -- ^ length -> MVector s a {-# INLINE unsafeFromForeignPtr0 #-} unsafeFromForeignPtr0 fp n = MVector n fp -- | Yield the underlying 'ForeignPtr' together with the offset to the data -- and its length. Modifying the data through the 'ForeignPtr' is -- unsafe if the vector could have frozen before the modification. unsafeToForeignPtr :: Storable a => MVector s a -> (ForeignPtr a, Int, Int) {-# INLINE unsafeToForeignPtr #-} unsafeToForeignPtr (MVector n fp) = (fp, 0, n) -- | /O(1)/ Yield the underlying 'ForeignPtr' together with its length. -- -- You can assume the pointer points directly to the data (no offset). -- -- Modifying the data through the 'ForeignPtr' is unsafe if the vector could -- have frozen before the modification. unsafeToForeignPtr0 :: Storable a => MVector s a -> (ForeignPtr a, Int) {-# INLINE unsafeToForeignPtr0 #-} unsafeToForeignPtr0 (MVector n fp) = (fp, n) -- | Pass a pointer to the vector's data to the IO action. Modifying data -- through the pointer is unsafe if the vector could have been frozen before -- the modification. unsafeWith :: Storable a => IOVector a -> (Ptr a -> IO b) -> IO b {-# INLINE unsafeWith #-} unsafeWith (MVector _ fp) = withForeignPtr fp
phischu/fragnix
tests/packages/scotty/Data.Vector.Storable.Mutable.hs
bsd-3-clause
16,438
0
22
3,882
3,862
2,093
1,769
286
5
{-# LANGUAGE ScopedTypeVariables #-} module Properties.Layout.Tall where import Test.QuickCheck import Instances import Utils import XMonad.StackSet hiding (filter) import XMonad.Core import XMonad.Layout import Graphics.X11.Xlib.Types (Rectangle(..)) import Data.Maybe import Data.List (sort) import Data.Ratio ------------------------------------------------------------------------ -- The Tall layout -- 1 window should always be tiled fullscreen prop_tile_fullscreen rect = tile pct rect 1 1 == [rect] where pct = 1/2 -- multiple windows prop_tile_non_overlap rect windows nmaster = noOverlaps (tile pct rect nmaster windows) where _ = rect :: Rectangle pct = 3 % 100 -- splitting horizontally yields sensible results prop_split_horizontal (NonNegative n) x = (noOverflows (+) (rect_x x) (rect_width x)) ==> sum (map rect_width xs) == rect_width x && all (== rect_height x) (map rect_height xs) && (map rect_x xs) == (sort $ map rect_x xs) where xs = splitHorizontally n x -- splitting vertically yields sensible results prop_split_vertical (r :: Rational) x = rect_x x == rect_x a && rect_x x == rect_x b && rect_width x == rect_width a && rect_width x == rect_width b where (a,b) = splitVerticallyBy r x -- pureLayout works. prop_purelayout_tall n r1 r2 rect = do x <- (arbitrary :: Gen T) `suchThat` (isJust . peek) let layout = Tall n r1 r2 st = fromJust . stack . workspace . current $ x ts = pureLayout layout rect st return $ length ts == length (index x) && noOverlaps (map snd ts) && description layout == "Tall" -- Test message handling of Tall -- what happens when we send a Shrink message to Tall prop_shrink_tall (NonNegative n) (Positive delta) (NonNegative frac) = n == n' && delta == delta' -- these state components are unchanged && frac' <= frac && (if frac' < frac then frac' == 0 || frac' == frac - delta else frac == 0 ) -- remaining fraction should shrink where l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage Shrink) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- what happens when we send a Shrink message to Tall prop_expand_tall (NonNegative n) (Positive delta) (NonNegative n1) (Positive d1) = n == n' && delta == delta' -- these state components are unchanged && frac' >= frac && (if frac' > frac then frac' == 1 || frac' == frac + delta else frac == 1 ) -- remaining fraction should shrink where frac = min 1 (n1 % d1) l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage Expand) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- what happens when we send an IncMaster message to Tall prop_incmaster_tall (NonNegative n) (Positive delta) (NonNegative frac) (NonNegative k) = delta == delta' && frac == frac' && n' == n + k where l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage (IncMasterN k)) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- toMessage LT = SomeMessage Shrink -- toMessage EQ = SomeMessage Expand -- toMessage GT = SomeMessage (IncMasterN 1) prop_desc_mirror n r1 r2 = description (Mirror $! t) == "Mirror Tall" where t = Tall n r1 r2
atupal/xmonad-mirror
xmonad/tests/Properties/Layout/Tall.hs
mit
3,709
0
13
1,096
989
519
470
67
2
module Settings.Program ( programContext ) where import Base import Context import Oracles.Flavour import Packages -- TODO: there is duplication and inconsistency between this and -- Rules.Program.getProgramContexts. There should only be one way to -- get a context/contexts for a given stage and package. programContext :: Stage -> Package -> Action Context programContext stage pkg = do profiled <- askGhcProfiled dynGhcProgs <- askDynGhcPrograms --dynamicGhcPrograms =<< flavour return $ Context stage pkg (wayFor profiled dynGhcProgs) where wayFor prof dyn | prof && dyn = error "programContext: profiling+dynamic not supported" | pkg == ghc && prof && stage > Stage0 = profiling | dyn && stage > Stage0 = dynamic | otherwise = vanilla
sdiehl/ghc
hadrian/src/Settings/Program.hs
bsd-3-clause
894
0
13
265
167
84
83
17
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, BangPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Device -- Copyright : (c) The University of Glasgow, 1994-2008 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable -- -- Type classes for I/O providers. -- ----------------------------------------------------------------------------- module GHC.IO.Device ( RawIO(..), IODevice(..), IODeviceType(..), SeekMode(..) ) where import GHC.Base import GHC.Word import GHC.Arr import GHC.Enum import GHC.Read import GHC.Show import GHC.Ptr import Data.Maybe import GHC.Num import GHC.IO import {-# SOURCE #-} GHC.IO.Exception ( unsupportedOperation ) -- | A low-level I/O provider where the data is bytes in memory. class RawIO a where -- | Read up to the specified number of bytes, returning the number -- of bytes actually read. This function should only block if there -- is no data available. If there is not enough data available, -- then the function should just return the available data. A return -- value of zero indicates that the end of the data stream (e.g. end -- of file) has been reached. read :: a -> Ptr Word8 -> Int -> IO Int -- | Read up to the specified number of bytes, returning the number -- of bytes actually read, or 'Nothing' if the end of the stream has -- been reached. readNonBlocking :: a -> Ptr Word8 -> Int -> IO (Maybe Int) -- | Write the specified number of bytes. write :: a -> Ptr Word8 -> Int -> IO () -- | Write up to the specified number of bytes without blocking. Returns -- the actual number of bytes written. writeNonBlocking :: a -> Ptr Word8 -> Int -> IO Int -- | I/O operations required for implementing a 'Handle'. class IODevice a where -- | @ready dev write msecs@ returns 'True' if the device has data -- to read (if @write@ is 'False') or space to write new data (if -- @write@ is 'True'). @msecs@ specifies how long to wait, in -- milliseconds. -- ready :: a -> Bool -> Int -> IO Bool -- | closes the device. Further operations on the device should -- produce exceptions. close :: a -> IO () -- | returns 'True' if the device is a terminal or console. isTerminal :: a -> IO Bool isTerminal _ = return False -- | returns 'True' if the device supports 'seek' operations. isSeekable :: a -> IO Bool isSeekable _ = return False -- | seek to the specified position in the data. seek :: a -> SeekMode -> Integer -> IO () seek _ _ _ = ioe_unsupportedOperation -- | return the current position in the data. tell :: a -> IO Integer tell _ = ioe_unsupportedOperation -- | return the size of the data. getSize :: a -> IO Integer getSize _ = ioe_unsupportedOperation -- | change the size of the data. setSize :: a -> Integer -> IO () setSize _ _ = ioe_unsupportedOperation -- | for terminal devices, changes whether characters are echoed on -- the device. setEcho :: a -> Bool -> IO () setEcho _ _ = ioe_unsupportedOperation -- | returns the current echoing status. getEcho :: a -> IO Bool getEcho _ = ioe_unsupportedOperation -- | some devices (e.g. terminals) support a "raw" mode where -- characters entered are immediately made available to the program. -- If available, this operations enables raw mode. setRaw :: a -> Bool -> IO () setRaw _ _ = ioe_unsupportedOperation -- | returns the 'IODeviceType' corresponding to this device. devType :: a -> IO IODeviceType -- | duplicates the device, if possible. The new device is expected -- to share a file pointer with the original device (like Unix @dup@). dup :: a -> IO a dup _ = ioe_unsupportedOperation -- | @dup2 source target@ replaces the target device with the source -- device. The target device is closed first, if necessary, and then -- it is made into a duplicate of the first device (like Unix @dup2@). dup2 :: a -> a -> IO a dup2 _ _ = ioe_unsupportedOperation ioe_unsupportedOperation :: IO a ioe_unsupportedOperation = throwIO unsupportedOperation -- | Type of a device that can be used to back a -- 'GHC.IO.Handle.Handle' (see also 'GHC.IO.Handle.mkFileHandle'). The -- standard libraries provide creation of 'GHC.IO.Handle.Handle's via -- Posix file operations with file descriptors (see -- 'GHC.IO.Handle.FD.mkHandleFromFD') with FD being the underlying -- 'GHC.IO.Device.IODevice' instance. -- -- Users may provide custom instances of 'GHC.IO.Device.IODevice' -- which are expected to conform the following rules: data IODeviceType = Directory -- ^ The standard libraries do not have direct support -- for this device type, but a user implementation is -- expected to provide a list of file names in -- the directory, in any order, separated by @'\0'@ -- characters, excluding the @"."@ and @".."@ names. See -- also 'System.Directory.getDirectoryContents'. Seek -- operations are not supported on directories (other -- than to the zero position). | Stream -- ^ A duplex communications channel (results in -- creation of a duplex 'GHC.IO.Handle.Handle'). The -- standard libraries use this device type when -- creating 'GHC.IO.Handle.Handle's for open sockets. | RegularFile -- ^ A file that may be read or written, and also -- may be seekable. | RawDevice -- ^ A "raw" (disk) device which supports block binary -- read and write operations and may be seekable only -- to positions of certain granularity (block- -- aligned). deriving (Eq) -- ----------------------------------------------------------------------------- -- SeekMode type -- | A mode that determines the effect of 'hSeek' @hdl mode i@. data SeekMode = AbsoluteSeek -- ^ the position of @hdl@ is set to @i@. | RelativeSeek -- ^ the position of @hdl@ is set to offset @i@ -- from the current position. | SeekFromEnd -- ^ the position of @hdl@ is set to offset @i@ -- from the end of the file. deriving (Eq, Ord, Ix, Enum, Read, Show)
frantisekfarka/ghc-dsi
libraries/base/GHC/IO/Device.hs
bsd-3-clause
6,419
0
12
1,533
701
410
291
62
1
{-# LANGUAGE CPP, MagicHash, BangPatterns #-} import Data.Char import Data.Array import GHC.Exts import System.IO import System.IO.Unsafe import Debug.Trace import Control.Applicative (Applicative(..)) import Control.Monad (liftM, ap) -- parser produced by Happy Version 1.16 data HappyAbsSyn = HappyTerminal Token | HappyErrorToken Int | HappyAbsSyn4 (Exp) | HappyAbsSyn5 (Exp1) | HappyAbsSyn6 (Term) | HappyAbsSyn7 (Factor) happyActOffsets :: HappyAddr happyActOffsets = HappyA# "\x01\x00\x25\x00\x1e\x00\x1b\x00\x1d\x00\x18\x00\x00\x00\x00\x00\x00\x00\x01\x00\xf8\xff\x03\x00\x03\x00\x03\x00\x03\x00\x20\x00\x01\x00\x18\x00\x18\x00\x00\x00\x00\x00\x00\x00\x0a\x00\x01\x00\x00\x00\x00\x00"# happyGotoOffsets :: HappyAddr happyGotoOffsets = HappyA# "\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16\x00\x00\x00\x07\x00\xfe\xff\x1c\x00\x06\x00\x00\x00\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x00\x00"# happyDefActions :: HappyAddr happyDefActions = HappyA# "\x00\x00\x00\x00\x00\x00\x00\x00\xfd\xff\xfa\xff\xf7\xff\xf6\xff\xf5\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfb\xff\xfc\xff\xf8\xff\xf9\xff\xf4\xff\x00\x00\x00\x00\xfe\xff"# happyCheck :: HappyAddr happyCheck = HappyA# "\xff\xff\x03\x00\x01\x00\x0b\x00\x03\x00\x04\x00\x03\x00\x04\x00\x02\x00\x03\x00\x03\x00\x0a\x00\x02\x00\x0a\x00\x00\x00\x01\x00\x02\x00\x03\x00\x00\x00\x01\x00\x02\x00\x03\x00\x00\x00\x01\x00\x02\x00\x03\x00\x00\x00\x01\x00\x02\x00\x03\x00\x02\x00\x03\x00\x08\x00\x09\x00\x04\x00\x06\x00\x07\x00\x05\x00\x01\x00\x0c\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"# happyTable :: HappyAddr happyTable = HappyA# "\x00\x00\x13\x00\x03\x00\x16\x00\x08\x00\x09\x00\x08\x00\x09\x00\x11\x00\x06\x00\x14\x00\x0a\x00\x18\x00\x0a\x00\x18\x00\x04\x00\x05\x00\x06\x00\x16\x00\x04\x00\x05\x00\x06\x00\x0a\x00\x04\x00\x05\x00\x06\x00\x03\x00\x04\x00\x05\x00\x06\x00\x12\x00\x06\x00\x0c\x00\x0d\x00\x10\x00\x0e\x00\x0f\x00\x11\x00\x03\x00\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"# happyReduceArr = array (1, 11) [ (1 , happyReduce_1), (2 , happyReduce_2), (3 , happyReduce_3), (4 , happyReduce_4), (5 , happyReduce_5), (6 , happyReduce_6), (7 , happyReduce_7), (8 , happyReduce_8), (9 , happyReduce_9), (10 , happyReduce_10), (11 , happyReduce_11) ] happy_n_terms = 13 :: Int happy_n_nonterms = 4 :: Int happyReduce_1 = happyReduce 6# 0# happyReduction_1 happyReduction_1 ((HappyAbsSyn4 happy_var_6) `HappyStk` _ `HappyStk` (HappyAbsSyn4 happy_var_4) `HappyStk` _ `HappyStk` (HappyTerminal (TokenVar happy_var_2)) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn4 (Let happy_var_2 happy_var_4 happy_var_6 ) `HappyStk` happyRest happyReduce_2 = happySpecReduce_1 0# happyReduction_2 happyReduction_2 (HappyAbsSyn5 happy_var_1) = HappyAbsSyn4 (Exp1 happy_var_1 ) happyReduction_2 _ = notHappyAtAll happyReduce_3 = happySpecReduce_3 1# happyReduction_3 happyReduction_3 (HappyAbsSyn6 happy_var_3) _ (HappyAbsSyn5 happy_var_1) = HappyAbsSyn5 (Plus happy_var_1 happy_var_3 ) happyReduction_3 _ _ _ = notHappyAtAll happyReduce_4 = happySpecReduce_3 1# happyReduction_4 happyReduction_4 (HappyAbsSyn6 happy_var_3) _ (HappyAbsSyn5 happy_var_1) = HappyAbsSyn5 (Minus happy_var_1 happy_var_3 ) happyReduction_4 _ _ _ = notHappyAtAll happyReduce_5 = happySpecReduce_1 1# happyReduction_5 happyReduction_5 (HappyAbsSyn6 happy_var_1) = HappyAbsSyn5 (Term happy_var_1 ) happyReduction_5 _ = notHappyAtAll happyReduce_6 = happySpecReduce_3 2# happyReduction_6 happyReduction_6 (HappyAbsSyn7 happy_var_3) _ (HappyAbsSyn6 happy_var_1) = HappyAbsSyn6 (Times happy_var_1 happy_var_3 ) happyReduction_6 _ _ _ = notHappyAtAll happyReduce_7 = happySpecReduce_3 2# happyReduction_7 happyReduction_7 (HappyAbsSyn7 happy_var_3) _ (HappyAbsSyn6 happy_var_1) = HappyAbsSyn6 (Div happy_var_1 happy_var_3 ) happyReduction_7 _ _ _ = notHappyAtAll happyReduce_8 = happySpecReduce_1 2# happyReduction_8 happyReduction_8 (HappyAbsSyn7 happy_var_1) = HappyAbsSyn6 (Factor happy_var_1 ) happyReduction_8 _ = notHappyAtAll happyReduce_9 = happySpecReduce_1 3# happyReduction_9 happyReduction_9 (HappyTerminal (TokenInt happy_var_1)) = HappyAbsSyn7 (Int happy_var_1 ) happyReduction_9 _ = notHappyAtAll happyReduce_10 = happySpecReduce_1 3# happyReduction_10 happyReduction_10 (HappyTerminal (TokenVar happy_var_1)) = HappyAbsSyn7 (Var happy_var_1 ) happyReduction_10 _ = notHappyAtAll happyReduce_11 = happySpecReduce_3 3# happyReduction_11 happyReduction_11 _ (HappyAbsSyn4 happy_var_2) _ = HappyAbsSyn7 (Brack happy_var_2 ) happyReduction_11 _ _ _ = notHappyAtAll happyNewToken action sts stk [] = happyDoAction 12# notHappyAtAll action sts stk [] happyNewToken action sts stk (tk:tks) = let cont i = happyDoAction i tk action sts stk tks in case tk of { TokenLet -> cont 1#; TokenIn -> cont 2#; TokenInt happy_dollar_dollar -> cont 3#; TokenVar happy_dollar_dollar -> cont 4#; TokenEq -> cont 5#; TokenPlus -> cont 6#; TokenMinus -> cont 7#; TokenTimes -> cont 8#; TokenDiv -> cont 9#; TokenOB -> cont 10#; TokenCB -> cont 11#; _ -> happyError' (tk:tks) } happyError_ tk tks = happyError' (tk:tks) newtype HappyIdentity a = HappyIdentity a happyIdentity = HappyIdentity happyRunIdentity (HappyIdentity a) = a instance Functor HappyIdentity where fmap = liftM instance Applicative HappyIdentity where pure = return (<*>) = ap instance Monad HappyIdentity where return = HappyIdentity (HappyIdentity p) >>= q = q p happyThen :: () => HappyIdentity a -> (a -> HappyIdentity b) -> HappyIdentity b happyThen = (>>=) happyReturn :: () => a -> HappyIdentity a happyReturn = (return) happyThen1 m k tks = (>>=) m (\a -> k a tks) happyReturn1 :: () => a -> b -> HappyIdentity a happyReturn1 = \a tks -> (return) a happyError' :: () => [Token] -> HappyIdentity a happyError' = HappyIdentity . happyError calc tks = happyRunIdentity happySomeParser where happySomeParser = happyThen (happyParse 0# tks) (\x -> case x of {HappyAbsSyn4 z -> happyReturn z; _other -> notHappyAtAll }) happySeq = happyDontSeq happyError tks = error "Parse error" data Exp = Let String Exp Exp | Exp1 Exp1 data Exp1 = Plus Exp1 Term | Minus Exp1 Term | Term Term data Term = Times Term Factor | Div Term Factor | Factor Factor data Factor = Int Int | Var String | Brack Exp data Token = TokenLet | TokenIn | TokenInt Int | TokenVar String | TokenEq | TokenPlus | TokenMinus | TokenTimes | TokenDiv | TokenOB | TokenCB lexer :: String -> [Token] lexer [] = [] lexer (c:cs) | isSpace c = lexer cs | isAlpha c = lexVar (c:cs) | isDigit c = lexNum (c:cs) lexer ('=':cs) = TokenEq : lexer cs lexer ('+':cs) = TokenPlus : lexer cs lexer ('-':cs) = TokenMinus : lexer cs lexer ('*':cs) = TokenTimes : lexer cs lexer ('/':cs) = TokenDiv : lexer cs lexer ('(':cs) = TokenOB : lexer cs lexer (')':cs) = TokenCB : lexer cs lexNum cs = TokenInt (read num) : lexer rest where (num,rest) = span isDigit cs lexVar cs = case span isAlpha cs of ("let",rest) -> TokenLet : lexer rest ("in",rest) -> TokenIn : lexer rest (var,rest) -> TokenVar var : lexer rest runCalc :: String -> Exp runCalc = calc . lexer main = case runCalc "1 + 2 + 3" of { (Exp1 (Plus (Plus (Term (Factor (Int 1))) (Factor (Int 2))) (Factor (Int 3)))) -> case runCalc "1 * 2 + 3" of { (Exp1 (Plus (Term (Times (Factor (Int 1)) (Int 2))) (Factor (Int 3)))) -> case runCalc "1 + 2 * 3" of { (Exp1 (Plus (Term (Factor (Int 1))) (Times (Factor (Int 2)) (Int 3)))) -> case runCalc "let x = 2 in x * (x - 2)" of { (Let "x" (Exp1 (Term (Factor (Int 2)))) (Exp1 (Term (Times (Factor (Var "x")) (Brack (Exp1 (Minus (Term (Factor (Var "x"))) (Factor (Int 2))))))))) -> print "Test works\n"; _ -> quit } ; _ -> quit } ; _ -> quit } ; _ -> quit } quit = print "Test failed\n" {-# LINE 1 "GenericTemplate.hs" #-} {-# LINE 1 "<built-in>" #-} {-# LINE 1 "<command line>" #-} {-# LINE 1 "GenericTemplate.hs" #-} -- Id: GenericTemplate.hs,v 1.26 2005/01/14 14:47:22 simonmar Exp {-# LINE 28 "GenericTemplate.hs" #-} data Happy_IntList = HappyCons Int# Happy_IntList {-# LINE 49 "GenericTemplate.hs" #-} {-# LINE 59 "GenericTemplate.hs" #-} happyTrace string expr = unsafePerformIO $ do hPutStr stderr string return expr infixr 9 `HappyStk` data HappyStk a = HappyStk a (HappyStk a) ----------------------------------------------------------------------------- -- starting the parse happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll ----------------------------------------------------------------------------- -- Accepting the parse -- If the current token is 0#, it means we've just accepted a partial -- parse (a %partial parser). We must ignore the saved token on the top of -- the stack in this case. happyAccept 0# tk st sts (_ `HappyStk` ans `HappyStk` _) = happyReturn1 ans happyAccept j tk st sts (HappyStk ans _) = (happyTcHack j (happyTcHack st)) (happyReturn1 ans) ----------------------------------------------------------------------------- -- Arrays only: do the next action happyDoAction i tk st = (happyTrace ("state: " ++ show (I# (st)) ++ ",\ttoken: " ++ show (I# (i)) ++ ",\taction: ")) $ case action of 0# -> (happyTrace ("fail.\n")) $ happyFail i tk st -1# -> (happyTrace ("accept.\n")) $ happyAccept i tk st n | isTrue# (n <# (0# :: Int#)) -> (happyTrace ("reduce (rule " ++ show rule ++ ")")) $ (happyReduceArr ! rule) i tk st where rule = (I# ((negateInt# ((n +# (1# :: Int#)))))) n -> (happyTrace ("shift, enter state " ++ show (I# (new_state)) ++ "\n")) $ happyShift new_state i tk st where new_state = (n -# (1# :: Int#)) where off = indexShortOffAddr happyActOffsets st off_i = (off +# i) check = if isTrue# (off_i >=# (0# :: Int#)) then isTrue# (indexShortOffAddr happyCheck off_i ==# i) else False action | check = indexShortOffAddr happyTable off_i | otherwise = indexShortOffAddr happyDefActions st {-# LINE 127 "GenericTemplate.hs" #-} indexShortOffAddr (HappyA# arr) off = #if __GLASGOW_HASKELL__ > 500 narrow16Int# i #elif __GLASGOW_HASKELL__ == 500 intToInt16# i #else (i `iShiftL#` 16#) `iShiftRA#` 16# #endif where #if __GLASGOW_HASKELL__ >= 503 i = word2Int# ((high `uncheckedShiftL#` 8#) `or#` low) #else i = word2Int# ((high `shiftL#` 8#) `or#` low) #endif high = int2Word# (ord# (indexCharOffAddr# arr (off' +# 1#))) low = int2Word# (ord# (indexCharOffAddr# arr off')) off' = off *# 2# data HappyAddr = HappyA# Addr# ----------------------------------------------------------------------------- -- HappyState data type (not arrays) {-# LINE 170 "GenericTemplate.hs" #-} ----------------------------------------------------------------------------- -- Shifting a token happyShift new_state 0# tk st sts stk@(x `HappyStk` _) = let i = (case x of { HappyErrorToken (I# (i)) -> i }) in -- trace "shifting the error token" $ happyDoAction i tk new_state (HappyCons (st) (sts)) (stk) happyShift new_state i tk st sts stk = happyNewToken new_state (HappyCons (st) (sts)) ((HappyTerminal (tk))`HappyStk`stk) -- happyReduce is specialised for the common cases. happySpecReduce_0 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_0 nt fn j tk st@((action)) sts stk = happyGoto nt j tk st (HappyCons (st) (sts)) (fn `HappyStk` stk) happySpecReduce_1 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_1 nt fn j tk _ sts@((HappyCons (st@(action)) (_))) (v1`HappyStk`stk') = let r = fn v1 in happySeq r (happyGoto nt j tk st sts (r `HappyStk` stk')) happySpecReduce_2 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_2 nt fn j tk _ (HappyCons (_) (sts@((HappyCons (st@(action)) (_))))) (v1`HappyStk`v2`HappyStk`stk') = let r = fn v1 v2 in happySeq r (happyGoto nt j tk st sts (r `HappyStk` stk')) happySpecReduce_3 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_3 nt fn j tk _ (HappyCons (_) ((HappyCons (_) (sts@((HappyCons (st@(action)) (_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk') = let r = fn v1 v2 v3 in happySeq r (happyGoto nt j tk st sts (r `HappyStk` stk')) happyReduce k i fn 0# tk st sts stk = happyFail 0# tk st sts stk happyReduce k nt fn j tk st sts stk = case happyDrop (k -# (1# :: Int#)) sts of !sts1@((HappyCons (st1@(action)) (_))) -> let r = fn stk in -- it doesn't hurt to always seq here... happyDoSeq r (happyGoto nt j tk st1 sts1 r) happyMonadReduce k nt fn 0# tk st sts stk = happyFail 0# tk st sts stk happyMonadReduce k nt fn j tk st sts stk = happyThen1 (fn stk tk) (\r -> happyGoto nt j tk st1 sts1 (r `HappyStk` drop_stk)) where !sts1@((HappyCons (st1@(action)) (_))) = happyDrop k (HappyCons (st) (sts)) drop_stk = happyDropStk k stk happyMonad2Reduce k nt fn 0# tk st sts stk = happyFail 0# tk st sts stk happyMonad2Reduce k nt fn j tk st sts stk = happyThen1 (fn stk tk) (\r -> happyNewToken new_state sts1 (r `HappyStk` drop_stk)) where !sts1@((HappyCons (st1@(action)) (_))) = happyDrop k (HappyCons (st) (sts)) drop_stk = happyDropStk k stk off = indexShortOffAddr happyGotoOffsets st1 off_i = (off +# nt) new_state = indexShortOffAddr happyTable off_i happyDrop 0# l = l happyDrop n (HappyCons (_) (t)) = happyDrop (n -# (1# :: Int#)) t happyDropStk 0# l = l happyDropStk n (x `HappyStk` xs) = happyDropStk (n -# (1#::Int#)) xs ----------------------------------------------------------------------------- -- Moving to a new state after a reduction happyGoto nt j tk st = (happyTrace (", goto state " ++ show (I# (new_state)) ++ "\n")) $ happyDoAction j tk new_state where off = indexShortOffAddr happyGotoOffsets st off_i = (off +# nt) new_state = indexShortOffAddr happyTable off_i ----------------------------------------------------------------------------- -- Error recovery (0# is the error token) -- parse error if we are in recovery and we fail again happyFail 0# tk old_st _ stk = -- trace "failing" $ happyError_ tk {- We don't need state discarding for our restricted implementation of "error". In fact, it can cause some bogus parses, so I've disabled it for now --SDM -- discard a state happyFail 0# tk old_st (HappyCons ((action)) (sts)) (saved_tok `HappyStk` _ `HappyStk` stk) = -- trace ("discarding state, depth " ++ show (length stk)) $ happyDoAction 0# tk action sts ((saved_tok`HappyStk`stk)) -} -- Enter error recovery: generate an error token, -- save the old token and carry on. happyFail i tk (action) sts stk = -- trace "entering error recovery" $ happyDoAction 0# tk action sts ( (HappyErrorToken (I# (i))) `HappyStk` stk) -- Internal happy errors: notHappyAtAll = error "Internal Happy error\n" ----------------------------------------------------------------------------- -- Hack to get the typechecker to accept our action functions happyTcHack :: Int# -> a -> a happyTcHack x y = y {-# INLINE happyTcHack #-} ----------------------------------------------------------------------------- -- Seq-ing. If the --strict flag is given, then Happy emits -- happySeq = happyDoSeq -- otherwise it emits -- happySeq = happyDontSeq happyDoSeq, happyDontSeq :: a -> b -> b happyDoSeq a b = a `seq` b happyDontSeq a b = b ----------------------------------------------------------------------------- -- Don't inline any functions from the template. GHC has a nasty habit -- of deciding to inline happyGoto everywhere, which increases the size of -- the generated parser quite a bit. {-# NOINLINE happyDoAction #-} {-# NOINLINE happyTable #-} {-# NOINLINE happyCheck #-} {-# NOINLINE happyActOffsets #-} {-# NOINLINE happyGotoOffsets #-} {-# NOINLINE happyDefActions #-} {-# NOINLINE happyShift #-} {-# NOINLINE happySpecReduce_0 #-} {-# NOINLINE happySpecReduce_1 #-} {-# NOINLINE happySpecReduce_2 #-} {-# NOINLINE happySpecReduce_3 #-} {-# NOINLINE happyReduce #-} {-# NOINLINE happyMonadReduce #-} {-# NOINLINE happyGoto #-} {-# NOINLINE happyFail #-} -- end of Happy Template.
frantisekfarka/ghc-dsi
testsuite/tests/ghci.debugger/HappyTest.hs
bsd-3-clause
16,590
213
36
2,981
4,867
2,569
2,298
321
12
{-# LANGUAGE OverloadedLists, TypeFamilies #-} import qualified Data.Set as S import GHC.Exts main = do putStrLn (f []) putStrLn (f [1,2]) putStrLn (f [2,0]) putStrLn (f [3,2]) putStrLn (f [2,7]) putStrLn (f [2,2]) putStrLn (f [1..7]) f :: S.Set Int -> String f [] = "empty" f [_] = "one element" f [2,_] = "two elements, the smaller one is 2" f [_,2] = "two elements, the bigger one is 2" f _ = "else" instance Ord a => IsList (S.Set a) where type (Item (S.Set a)) = a fromList = S.fromList toList = S.toList
lukexi/ghc-7.8-arm64
testsuite/tests/overloadedlists/should_run/overloadedlistsrun04.hs
bsd-3-clause
621
0
10
206
278
141
137
20
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} module Resource ( BuildingResources , Store(..) , TileResources , UnitResources , units , buildings , tiles ) where import Control.Lens import Data.HashMap.Strict import SDL import Item import Grid hiding (tiles) {- Resource indexing: * Units -> Soldier * Buildings -> House * Tiles -> Rocks Resource using: 1. Describe unit/building/tile. 2. Describe the map (which units/building/tiles are used). 3. Load all images into the resource store and index them. 4. During rendering look up the key for the given unit/building/tile. -} type BuildingResources = HashMap BuildingDescription Texture type TileResources = HashMap TileDescription Texture type UnitResources = HashMap UnitDescription Texture data Store = Store { _units :: UnitResources , _buildings :: BuildingResources , _tiles :: TileResources } makeLenses ''Store
Unoriginal-War/unoriginal-war
src/Resource.hs
mit
1,004
0
8
192
130
81
49
25
0
module Utils.TesseractUtils ( runTesseract, tesseractCleanUp ) where import System.Directory import System.Process tesseractCmd fname = "tesseract -l eng " ++ fname ++ " output" runTesseract :: String -> IO () runTesseract filename = callCommand $ tesseractCmd filename tesseractCleanUp :: IO () tesseractCleanUp = removeFile "output.txt"
caneroj1/HaskellDocs
Utils/TesseractUtils.hs
mit
367
0
7
72
87
46
41
11
1
------------------------------------------------------------------------------ -- | Contains definitions for generating 'MediaType's. module Network.HTTP.Media.MediaType.Gen ( -- * Generating MediaTypes anything , genMediaType , genSubStar , genMaybeSubStar , subStarOf , genConcreteMediaType , genWithoutParams , genWithParams , stripParams , genDiffMediaTypesWith , genDiffMediaTypeWith , genDiffMediaTypes , genDiffMediaType , genMatchingPair -- * Generating Parameters , genParameters , genMaybeParameters , genDiffParameters -- * Rendering Parameters , renderParameters ) where import qualified Data.Map as Map import Control.Monad (filterM, liftM, liftM2) import Data.ByteString (ByteString) import Data.CaseInsensitive (CI, original) import Data.Foldable (foldlM) import Data.Map (fromList) import Data.Monoid ((<>)) import Test.QuickCheck.Gen import Network.HTTP.Media.Gen import Network.HTTP.Media.MediaType.Internal ------------------------------------------------------------------------------ -- | Parameter entry for testing. type ParamEntry = (CI ByteString, CI ByteString) ------------------------------------------------------------------------------ -- | The MediaType that matches anything. anything :: MediaType anything = MediaType "*" "*" Map.empty ------------------------------------------------------------------------------ -- | Generates any kind of MediaType. genMediaType :: Gen MediaType genMediaType = oneof [return anything, genSubStar, genConcreteMediaType] ------------------------------------------------------------------------------ -- | Generates a MediaType with just a concrete main type. genSubStar :: Gen MediaType genSubStar = do main <- genCIByteString return $ MediaType main "*" Map.empty ------------------------------------------------------------------------------ -- | Generates a MediaType whose sub type might be *. genMaybeSubStar :: Gen MediaType genMaybeSubStar = oneof [genSubStar, genConcreteMediaType] ------------------------------------------------------------------------------ -- | Strips the sub type and parameters from a MediaType. subStarOf :: MediaType -> MediaType subStarOf media = media { subType = "*", parameters = Map.empty } ------------------------------------------------------------------------------ -- | Generates a concrete MediaType which may have parameters. genConcreteMediaType :: Gen MediaType genConcreteMediaType = do main <- genCIByteString sub <- genCIByteString params <- oneof [return Map.empty, genParameters] return $ MediaType main sub params ------------------------------------------------------------------------------ -- | Generates a concrete MediaType with no parameters. genWithoutParams :: Gen MediaType genWithoutParams = do main <- genCIByteString sub <- genCIByteString return $ MediaType main sub Map.empty ------------------------------------------------------------------------------ -- | Generates a MediaType with at least one parameter. genWithParams :: Gen MediaType genWithParams = do main <- genCIByteString sub <- genCIByteString params <- genParameters return $ MediaType main sub params ------------------------------------------------------------------------------ -- | Strips the parameters from the given MediaType. stripParams :: MediaType -> MediaType stripParams media = media { parameters = Map.empty } ------------------------------------------------------------------------------ -- | Generates a different MediaType to the ones in the given list, using the -- given generator. genDiffMediaTypesWith :: Gen MediaType -> [MediaType] -> Gen MediaType genDiffMediaTypesWith gen media = do media' <- gen if media' `elem` media then genDiffMediaTypesWith gen media else return media' ------------------------------------------------------------------------------ -- | Generates a different MediaType to the given one, using the given -- generator. genDiffMediaTypeWith :: Gen MediaType -> MediaType -> Gen MediaType genDiffMediaTypeWith gen = genDiffMediaTypesWith gen . (: []) ------------------------------------------------------------------------------ -- | Generates a different MediaType to the ones in the given list. genDiffMediaTypes :: [MediaType] -> Gen MediaType genDiffMediaTypes = genDiffMediaTypesWith genMediaType ------------------------------------------------------------------------------ -- | Generates a different MediaType to the given one. genDiffMediaType :: MediaType -> Gen MediaType genDiffMediaType = genDiffMediaTypes . (: []) ------------------------------------------------------------------------------ -- | Reuse for 'mayParams' and 'someParams'. mkGenParams :: (Gen ParamEntry -> Gen [ParamEntry]) -> Gen Parameters mkGenParams = liftM fromList . ($ liftM2 (,) (genDiffCIByteString "q") genCIByteString) ------------------------------------------------------------------------------ -- | Generates some sort of parameters. genMaybeParameters :: Gen Parameters genMaybeParameters = mkGenParams listOf ------------------------------------------------------------------------------ -- | Generates at least one parameter. genParameters :: Gen Parameters genParameters = mkGenParams listOf1 ------------------------------------------------------------------------------ -- | Generates a set of parameters that is not a submap of the given -- parameters (but not necessarily vice versa). genDiffParameters :: Parameters -> Gen Parameters genDiffParameters params = do params' <- genParameters if params' `Map.isSubmapOf` params then genDiffParameters params else return params' ------------------------------------------------------------------------------ -- | Generates a set of parameters that is a strict submap of the given -- parameters. genSubParameters :: Parameters -> Gen (Maybe Parameters) genSubParameters params | Map.null params = return Nothing | otherwise = Just . Map.fromList <$> genStrictSublist where list = Map.toList params genStrictSublist = do sublist <- filterM (const $ choose (False, True)) list if sublist == list then genStrictSublist else return sublist ------------------------------------------------------------------------------ -- | Generates a pair of non-equal MediaType values that are in a 'matches' -- relation, with the more specific value on the left. genMatchingPair :: Gen (MediaType, MediaType) genMatchingPair = do a <- oneof [genSubStar, genConcreteMediaType] b <- if subType a == "*" then return anything else oneof $ withSubParameters a : map return [subStarOf a, anything] return (a, b) where withSubParameters a = do params <- genSubParameters (parameters a) return $ case params of Just sub -> a { parameters = sub } Nothing -> subStarOf a ------------------------------------------------------------------------------ -- | Render parameters with a generated amount of whitespace between the -- semicolons. Note that there is a leading semicolon in front of the -- parameters, as it is expected that this will always be attached to -- a preceding 'MediaType' rendering. renderParameters :: Parameters -> Gen ByteString renderParameters params = foldlM pad "" (Map.toList params) where pad s (k, v) = (s <>) . (<> original k <> "=" <> original v) <$> padString ";"
zmthy/http-media
test/Network/HTTP/Media/MediaType/Gen.hs
mit
7,831
0
14
1,477
1,222
667
555
113
3
type Birds = Int type Pole = (Birds, Birds) landLeft :: Birds -> Pole -> Maybe Pole landLeft n (left,right) | abs ((left + n) - right) < 4 = Just (left + n, right) | otherwise = Nothing landRight :: Birds -> Pole -> Maybe Pole landRight n (left,right) | abs (left - (right + n)) < 4 = Just (left, right + n) | otherwise = Nothing --version one functions... --landLeft :: Birds -> Pole -> Pole --landLeft n (left, right) = (left + n, right) --landRight :: Birds -> Pole -> Pole --landRight n (left, right) = (left, right + n) x -: f = f x banana :: Pole -> Maybe Pole banana _ = Nothing
rglew/lyah
birds.hs
mit
686
2
13
220
222
116
106
13
1
module Hasql.TH ( -- * Statements -- | -- Quasiquoters in this category produce Hasql `Statement`s, -- checking the correctness of SQL at compile-time. -- -- To extract the information about parameters and results of the statement, -- the quoter requires you to explicitly specify the Postgres types for placeholders and results. -- -- Here's an example of how to use it: -- -- >selectUserDetails :: Statement Int32 (Maybe (Text, Text, Maybe Text)) -- >selectUserDetails = -- > [maybeStatement| -- > select name :: text, email :: text, phone :: text? -- > from "user" -- > where id = $1 :: int4 -- > |] -- -- As you can see, it completely eliminates the need to mess with codecs. -- The quasiquoters directly produce `Statement`, -- which you can then `Data.Profunctor.dimap` over using its `Data.Profunctor.Profunctor` instance to get to your domain types. -- -- == Type mappings -- -- === Primitives -- -- Following is a list of supported Postgres types and their according types on the Haskell end. -- -- - @bool@ - `Bool` -- - @int2@ - `Int16` -- - @int4@ - `Int32` -- - @int8@ - `Int64` -- - @float4@ - `Float` -- - @float8@ - `Double` -- - @numeric@ - `Data.Scientific.Scientific` -- - @char@ - `Char` -- - @text@ - `Data.Text.Text` -- - @bytea@ - `Data.ByteString.ByteString` -- - @date@ - `Data.Time.Day` -- - @timestamp@ - `Data.Time.LocalTime` -- - @timestamptz@ - `Data.Time.UTCTime` -- - @time@ - `Data.Time.TimeOfDay` -- - @timetz@ - @(`Data.Time.TimeOfDay`, `Data.Time.TimeZone`)@ -- - @interval@ - `Data.Time.DiffTime` -- - @uuid@ - `Data.UUID.UUID` -- - @inet@ - @(`Network.IP.Addr.NetAddr` `Network.IP.Addr.IP`)@ -- - @json@ - `Data.Aeson.Value` -- - @jsonb@ - `Data.Aeson.Value` -- -- === Arrays -- -- Array mappings are also supported. -- They are specified according to Postgres syntax: by appending one or more @[]@ to the primitive type, -- depending on how many dimensions the array has. -- On the Haskell end array is mapped to generic `Data.Vector.Generic.Vector`, -- allowing you to choose which particular vector implementation to map to. -- -- === Nulls -- -- As you might have noticed in the example, -- we introduce one change to the Postgres syntax in the way -- the typesignatures are parsed: -- we interpret question-marks in them as specification of nullability. -- Here's more examples of that: -- -- >>> :t [singletonStatement| select a :: int4? |] -- ... -- :: Statement () (Maybe Int32) -- -- You can use it to specify the nullability of array elements: -- -- >>> :t [singletonStatement| select a :: int4?[] |] -- ... -- :: Data.Vector.Generic.Base.Vector v (Maybe Int32) => -- Statement () (v (Maybe Int32)) -- -- And of arrays themselves: -- -- >>> :t [singletonStatement| select a :: int4?[]? |] -- ... -- :: Data.Vector.Generic.Base.Vector v (Maybe Int32) => -- Statement () (Maybe (v (Maybe Int32))) -- ** Row-parsing statements singletonStatement, maybeStatement, vectorStatement, foldStatement, -- ** Row-ignoring statements resultlessStatement, rowsAffectedStatement, -- * SQL ByteStrings -- | -- ByteString-producing quasiquoters. -- -- For now they perform no compile-time checking. uncheckedSql, uncheckedSqlFile, ) where import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Vector (Vector) import Hasql.Statement (Statement) import qualified Hasql.TH.Construction.Exp as Exp import qualified Hasql.TH.Extraction.Exp as ExpExtraction import Hasql.TH.Prelude hiding (exp) import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax import qualified PostgresqlSyntax.Ast as Ast import qualified PostgresqlSyntax.Parsing as Parsing -- * Helpers exp :: (String -> Q Exp) -> QuasiQuoter exp = let _unsupported _ = fail "Unsupported" in \_exp -> QuasiQuoter _exp _unsupported _unsupported _unsupported expParser :: (Text -> Either Text Exp) -> QuasiQuoter expParser _parser = exp $ \_inputString -> either (fail . Text.unpack) return $ _parser $ fromString _inputString expPreparableStmtAstParser :: (Ast.PreparableStmt -> Either Text Exp) -> QuasiQuoter expPreparableStmtAstParser _parser = expParser $ \_input -> do _ast <- first fromString $ Parsing.run (Parsing.atEnd Parsing.preparableStmt) _input _parser _ast -- * Statement -- | -- @ -- :: `Statement` params row -- @ -- -- Statement producing exactly one result row. -- -- Will cause the running session to fail with the -- `Hasql.Session.UnexpectedAmountOfRows` error if it's any other. -- -- === __Examples__ -- -- >>> :t [singletonStatement|select 1 :: int2|] -- ... :: Statement () Int16 -- -- >>> :{ -- :t [singletonStatement| -- insert into "user" (email, name) -- values ($1 :: text, $2 :: text) -- returning id :: int4 -- |] -- :} -- ... -- ... :: Statement (Text, Text) Int32 -- -- Incorrect SQL: -- -- >>> :t [singletonStatement|elect 1|] -- ... -- | -- 1 | elect 1 -- | ^ -- ... singletonStatement :: QuasiQuoter singletonStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement Exp.singleRowResultDecoder) -- | -- @ -- :: `Statement` params (Maybe row) -- @ -- -- Statement producing one row or none. -- -- === __Examples__ -- -- >>> :t [maybeStatement|select 1 :: int2|] -- ... :: Statement () (Maybe Int16) maybeStatement :: QuasiQuoter maybeStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement Exp.rowMaybeResultDecoder) -- | -- @ -- :: `Statement` params (`Vector` row) -- @ -- -- Statement producing a vector of rows. -- -- === __Examples__ -- -- >>> :t [vectorStatement|select 1 :: int2|] -- ... :: Statement () (Vector Int16) vectorStatement :: QuasiQuoter vectorStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement Exp.rowVectorResultDecoder) -- | -- @ -- :: `Fold` row folding -> `Statement` params folding -- @ -- -- Function from `Fold` over rows to a statement producing the result of folding. -- Use this when you need to aggregate rows customly. -- -- === __Examples__ -- -- >>> :t [foldStatement|select 1 :: int2|] -- ... :: Fold Int16 b -> Statement () b foldStatement :: QuasiQuoter foldStatement = expPreparableStmtAstParser ExpExtraction.foldStatement -- | -- @ -- :: `Statement` params () -- @ -- -- Statement producing no results. -- -- === __Examples__ -- -- >>> :t [resultlessStatement|insert into "user" (name, email) values ($1 :: text, $2 :: text)|] -- ... -- ... :: Statement (Text, Text) () resultlessStatement :: QuasiQuoter resultlessStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement (const Exp.noResultResultDecoder)) -- | -- @ -- :: `Statement` params Int64 -- @ -- -- Statement counting the rows it affects. -- -- === __Examples__ -- -- >>> :t [rowsAffectedStatement|delete from "user" where password is null|] -- ... -- ... :: Statement () Int64 rowsAffectedStatement :: QuasiQuoter rowsAffectedStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement (const Exp.rowsAffectedResultDecoder)) -- * SQL ByteStrings -- | -- Quoter of a multiline Unicode SQL string, -- which gets converted into a format ready to be used for declaration of statements. uncheckedSql :: QuasiQuoter uncheckedSql = exp $ return . Exp.byteString . Text.encodeUtf8 . fromString -- | -- Read an SQL-file, containing multiple statements, -- and produce an expression of type `ByteString`. -- -- Allows to store plain SQL in external files and read it at compile time. -- -- E.g., -- -- >migration1 :: Hasql.Session.Session () -- >migration1 = Hasql.Session.sql [uncheckedSqlFile|migrations/1.sql|] uncheckedSqlFile :: QuasiQuoter uncheckedSqlFile = quoteFile uncheckedSql -- * Tests -- $ -- >>> :t [maybeStatement| select (password = $2 :: bytea) :: bool, id :: int4 from "user" where "email" = $1 :: text |] -- ... -- ... Statement (Text, ByteString) (Maybe (Bool, Int32)) -- -- >>> :t [maybeStatement| select id :: int4 from application where pub_key = $1 :: uuid and sec_key_pt1 = $2 :: int8 and sec_key_pt2 = $3 :: int8 |] -- ... -- ... Statement (UUID, Int64, Int64) (Maybe Int32) -- -- >>> :t [singletonStatement| select 1 :: int4 from a left join b on b.id = a.id |] -- ... -- ... Statement () Int32
nikita-volkov/hasql-th
library/Hasql/TH.hs
mit
8,626
0
14
1,791
721
495
226
49
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Data.Tape where import Control.Applicative import Data.Indexed import Data.Stream import Control.Comonad data Tape a = Tape { leftsT :: Stream a , headT :: a , rightsT :: Stream a } shiftL :: Tape a -> Tape a shiftL (Tape (l :~ ls) x rs) = Tape ls l (x :~ rs) shiftR :: Tape a -> Tape a shiftR (Tape ls x (r :~ rs)) = Tape (x :~ ls) r rs takeT :: Int -> Tape a -> ([a], a, [a]) takeT n (Tape ls x rs) = (reverse (takeS n ls), x, takeS n rs) iterateT :: (a -> a) -> (a -> a) -> a -> Tape a iterateT fl fr x = Tape (iterateS fl (fl x)) x (iterateS fr (fr x)) -- warning: behaves differenty from iterateT! "unfolds", but the first -- result on the *rightward* direction is taken to be the "central" value. unfoldT :: (b -> (a, b)) -> (b -> (a, b)) -> b -> Tape a unfoldT fl fr x = Tape ls y rs where ls = unfoldS fl x (y :~ rs) = unfoldS fr x -- foldlT :: ((b, Int) -> a -> (b, Bool)) -> (b -> b -> c) -> b -> Tape a -> c -- foldlT f g = g () -- where -- go n z (x :~ xs) = case f (z, n) x of -- (y, False) -> y -- (y, True) -> y `seq` go (n + 1) y xs -- foldrT :: ((a, Int) -> b -> b) -> Stream a -> b -- foldrT f = go 0 -- where -- go n (x :~ xs) = f (x, n) (go (n + 1) xs) instance (Ord a, Num a) => RelIndex a Tape where t ? n | n < 0 = ls ? (n - 1) | n > 0 = rs ? (n - 1) | otherwise = Just x where Tape ls x rs = t instance (Ord a, Num a) => TotalRelIndex a Tape where t # n | n < 0 = ls # (n - 1) | n > 0 = rs # (n - 1) | otherwise = x where Tape ls x rs = t instance (Ord a, Num a) => Index a Tape where instance (Ord a, Num a) => TotalIndex a Tape where instance Functor Tape where fmap f (Tape ls x rs) = Tape (fmap f ls) (f x) (fmap f rs) instance Applicative Tape where pure = iterateT id id Tape fls fx frs <*> Tape ls x rs = Tape (fls <*> ls) (fx x) (frs <*> rs) instance Comonad Tape where extract = headT duplicate xs = Tape (iterateS shiftL (shiftL xs)) xs (iterateS shiftR (shiftR xs)) extend f xs = Tape (fmap f (iterateS shiftL (shiftL xs))) (f xs) (fmap f (iterateS shiftR (shiftR xs))) -- tape with a stored reference to some "origin" data OffsetTape o a = OffsetTape { otTape :: Tape a , otOffset :: o } indexFromT :: o -> Tape a -> OffsetTape o a indexFromT = flip OffsetTape instance Functor (OffsetTape o) where fmap f (OffsetTape t o) = OffsetTape (fmap f t) o instance Enum o => Comonad (OffsetTape o) where extract = extract . otTape duplicate (OffsetTape t o) = OffsetTape t' o where t' = OffsetTape <$> iterateT shiftL shiftR t <*> iterateT succ pred o extend f (OffsetTape t o) = OffsetTape t' o where t' = fmap f . OffsetTape <$> iterateT shiftL shiftR t <*> iterateT succ pred o instance (Ord a, Num a) => RelIndex a (OffsetTape o) where (OffsetTape t _) ? n = t ? n instance (Ord a, Num a) => TotalRelIndex a (OffsetTape o) where (OffsetTape t _) # n = t # n instance (Ord a, Num a) => Index a (OffsetTape a) where (OffsetTape t o) ?@ n = t ? (n + o) instance (Ord a, Num a) => TotalIndex a (OffsetTape a) where (OffsetTape t o) #@ n = t # (n + o) -- instance Num i => Applicative (OffsetTape i) where -- pure = flip OffsetTape 0 . pure -- OffsetTape ft fi <*> OffsetTape xt xi = OffsetTape
mstksg/cm-dip
src/Data/Tape.hs
mit
3,780
0
12
1,295
1,420
727
693
69
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.Bool.CheckBox ( -- * The CheckBox Widget CheckBox, -- * Constructor mkCheckBox) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (when, join, void) import Data.Aeson import Data.HashMap.Strict as HM import Data.IORef (newIORef) import Data.Text (Text) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'CheckBox' represents a Checkbox widget from IPython.html.widgets. type CheckBox = IPythonWidget CheckBoxType -- | Create a new output widget mkCheckBox :: IO CheckBox mkCheckBox = do -- Default properties, with a random uuid uuid <- U.random let widgetState = WidgetState $ defaultBoolWidget "CheckboxView" stateIO <- newIORef widgetState let widget = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the image widget return widget instance IHaskellDisplay CheckBox where display b = do widgetSendView b return $ Display [] instance IHaskellWidget CheckBox where getCommUUID = uuid comm widget (Object dict1) _ = do let key1 = "sync_data" :: Text key2 = "value" :: Text Just (Object dict2) = HM.lookup key1 dict1 Just (Bool value) = HM.lookup key2 dict2 setField' widget BoolValue value triggerChange widget
beni55/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Bool/CheckBox.hs
mit
1,820
0
13
441
369
202
167
41
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NamedFieldPuns #-} module Twitch.API where import Streamer.Prelude import Twitch.Types import Twitch.Playlist import Network.HTTP.Simple import Data.Aeson import Data.Char import Data.Either.Combinators import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy as LBS import Control.Exception import Control.Monad instance FromJSON AccessToken where parseJSON (Object v) = AccessToken <$> v .: "token" <*> v .: "sig" type ClientID = String channelAccessTokenUrl channel = "http://api.twitch.tv/api/channels/" ++ map toLower channel ++ "/access_token" channelAccessToken :: ClientID -> ChannelName -> IO (Maybe AccessToken) channelAccessToken clientID channel = do request <- addRequestHeader "Client-ID" (BS.pack clientID) <$> parseRequest (channelAccessTokenUrl channel) response <- httpJSONEither request return $ rightToMaybe $ getResponseBody response streamIndexUrl channel = "http://usher.twitch.tv/api/channel/hls/" ++ map toLower channel ++ ".m3u8" streamIndexQueryString :: AccessToken -> [(BS.ByteString, Maybe BS.ByteString)] streamIndexQueryString AccessToken{tokenValue, signature} = [ ("token", Just $ BS.pack tokenValue) , ("sig", Just $ BS.pack signature) , ("allow_source", Just "true") , ("type", Just "any") ] streamPlaylists :: ClientID -> ChannelName -> IO (Maybe [HLSPlaylist]) streamPlaylists clientID channel = do mbToken <- channelAccessToken clientID channel whenJustMaybe performRequestWithToken mbToken where performRequestWithToken :: AccessToken -> IO (Maybe [HLSPlaylist]) performRequestWithToken token = do request <- setRequestQueryString (streamIndexQueryString token) <$> parseRequest (streamIndexUrl channel) mbResponse <- (Just <$> httpLBS request) `catch` nothingOnException return $ join (parsePlaylistsWithResponse <$> mbResponse) parsePlaylistsWithResponse :: Response LBS.ByteString -> Maybe [HLSPlaylist] parsePlaylistsWithResponse response = do let eitherPlaylists = parseHLSPlaylists $ getResponseBody response rightToMaybe eitherPlaylists nothingOnException :: HttpException -> IO (Maybe a) nothingOnException = const $ return Nothing
best-coloc-ever/twitch-cast
streamer/src/Twitch/API.hs
mit
2,376
0
13
458
585
303
282
55
1
{-| Module : Database.Orville.PostgreSQL.Internal.Where Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExistentialQuantification #-} module Database.Orville.PostgreSQL.Internal.Where ( WhereCondition(..) , (.==) , (.<>) , (.>) , (.>=) , (.<) , (.<=) , (.<-) , (%==) , whereConditionValues , whereAnd , whereOr , whereIn , whereLike , whereLikeInsensitive , whereNotIn , whereQualified , whereRaw , isNull , isNotNull , whereClause , whereValues , whereToSql ) where import qualified Data.List as List import Database.HDBC import Database.Orville.PostgreSQL.Internal.Expr import qualified Database.Orville.PostgreSQL.Internal.Expr.WhereExpr as E import Database.Orville.PostgreSQL.Internal.FieldDefinition import Database.Orville.PostgreSQL.Internal.QueryKey import Database.Orville.PostgreSQL.Internal.Types {- It would be nice to match the SqlValues in these with the types from the corresponding FieldDefinitions. However, this would require adding an Eq constraint for List.nub on the .<- operation, which I'm not willing to do at this moment. Alternately, we could eliminate storing the entire FieldDefinition here, thereby removing the need for ExistentialQuantification. Currently the field definition is being used in the QueryKeyable instances for WhereCondition for calls to qkOp an friends. Replacing FieldDefinition with just the field name here would be nice. We would probably want a fully-fledged FieldName type whech could provide the appropriate QueryKeyable instance. That then raises questions about the ergonomics users creating FieldDefinition values without requiring OverloadedStrings to be turned on. -} data WhereCondition = WhereConditionExpr E.WhereExpr | Or [WhereCondition] | And [WhereCondition] | forall a b c. Qualified (TableDefinition a b c) WhereCondition instance QueryKeyable WhereCondition where queryKey (WhereConditionExpr (Expr (Right form))) = queryKey form queryKey (WhereConditionExpr (Expr (Left raw))) = QKField $ rawExprToSql raw queryKey (Or conds) = qkOp "OR" conds queryKey (And conds) = qkOp "And" conds queryKey (Qualified _ cond) = queryKey cond (.==) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .== a = WhereConditionExpr . expr $ nameForm E..== sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<>) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .<> a = WhereConditionExpr . expr $ nameForm E..<> sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.>) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .> a = WhereConditionExpr . expr $ nameForm E..> sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.>=) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .>= a = WhereConditionExpr . expr $ nameForm E..>= sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .< a = WhereConditionExpr . expr $ nameForm E..< sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<=) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .<= a = WhereConditionExpr . expr $ nameForm E..<= sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<-) :: FieldDefinition nullability a -> [a] -> WhereCondition fieldDef .<- as = whereIn fieldDef as (%==) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef %== a = WhereConditionExpr . expr $ nameForm E.%== sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a whereConditionSql :: WhereCondition -> String whereConditionSql cond = internalWhereConditionSql Nothing cond internalWhereConditionSql :: Maybe (TableDefinition a b c) -> WhereCondition -> String internalWhereConditionSql mbTableDef whereCondition = case whereCondition of Or [] -> "FALSE" Or conds -> let condsSql = map innerCondSql conds in List.intercalate " OR " condsSql And [] -> "TRUE" And conds -> let condsSql = map innerCondSql conds in List.intercalate " AND " condsSql WhereConditionExpr expression -> case mbTableDef of Just tableDef -> rawExprToSql . generateSql $ expression `qualified` (tableName tableDef) Nothing -> rawExprToSql . generateSql $ expression Qualified tableDef cond -> internalWhereConditionSql (Just tableDef) cond where innerCondSql c = let sql = internalWhereConditionSql mbTableDef c in "(" ++ sql ++ ")" whereConditionValues :: WhereCondition -> [SqlValue] whereConditionValues (WhereConditionExpr (Expr (Right form))) = E.whereValues [form] whereConditionValues (WhereConditionExpr (Expr (Left _))) = [] whereConditionValues (Or conds) = concatMap whereConditionValues conds whereConditionValues (And conds) = concatMap whereConditionValues conds whereConditionValues (Qualified _ cond) = whereConditionValues cond whereAnd :: [WhereCondition] -> WhereCondition whereAnd = And whereOr :: [WhereCondition] -> WhereCondition whereOr = Or whereIn :: FieldDefinition nullability a -> [a] -> WhereCondition whereIn fieldDef values = WhereConditionExpr . expr $ E.whereIn (fieldToNameForm fieldDef) (map (fieldToSqlValue fieldDef) values) whereLike :: FieldDefinition nullability a -> String -> WhereCondition whereLike fieldDef raw = WhereConditionExpr . expr $ E.whereLike (fieldToNameForm fieldDef) (toSql raw) whereLikeInsensitive :: FieldDefinition nullability a -> String -> WhereCondition whereLikeInsensitive fieldDef raw = WhereConditionExpr . expr $ E.whereLikeInsensitive (fieldToNameForm fieldDef) (toSql raw) whereNotIn :: FieldDefinition nullability a -> [a] -> WhereCondition whereNotIn fieldDef values = WhereConditionExpr . expr $ E.whereNotIn (fieldToNameForm fieldDef) (map (fieldToSqlValue fieldDef) values) whereQualified :: TableDefinition a b c -> WhereCondition -> WhereCondition whereQualified tableDef cond = Qualified tableDef cond whereRaw :: String -> [SqlValue] -> WhereCondition whereRaw str values = WhereConditionExpr . expr $ E.whereRaw str values isNull :: FieldDefinition Nullable a -> WhereCondition isNull = WhereConditionExpr . expr . E.whereNull . fieldToNameForm isNotNull :: FieldDefinition Nullable a -> WhereCondition isNotNull = WhereConditionExpr . expr . E.whereNotNull . fieldToNameForm whereClause :: [WhereCondition] -> String whereClause [] = "" whereClause conds = "WHERE " ++ whereConditionSql (whereAnd conds) whereValues :: [WhereCondition] -> [SqlValue] whereValues = List.concatMap whereConditionValues whereToSql :: [WhereCondition] -> (String, [SqlValue]) whereToSql conds = (whereClause conds, whereValues conds)
flipstone/orville
orville-postgresql/src/Database/Orville/PostgreSQL/Internal/Where.hs
mit
7,122
0
13
1,250
1,751
921
830
144
7
{-# LANGUAGE FlexibleInstances #-} -- | An interface for bundling metrics in a way that they cna be iterated over for reporting or looked up for use by code that shares the registry. module Data.Metrics.Registry ( MetricRegistry, Metric(..), Register(..), metrics, newMetricRegistry, module Data.Metrics.Types ) where import Control.Concurrent.MVar import qualified Data.HashMap.Strict as H import Data.Metrics.Counter import Data.Metrics.Gauge import Data.Metrics.Histogram import Data.Metrics.Meter import Data.Metrics.Timer import Data.Metrics.Types import Data.Text (Text) -- | Initializes a new metric registry. newMetricRegistry :: IO (MetricRegistry IO) newMetricRegistry = fmap MetricRegistry $ newMVar H.empty -- | A container that tracks all metrics registered with it. -- All forms of metrics share the same namespace in the registry. -- Consequently, attempting to replace a metric with one of a different type will fail (return Nothing from a call to `register`). data MetricRegistry m = MetricRegistry { metrics :: !(MVar (H.HashMap Text (Metric m))) } -- | A sum type of all supported metric types that reporters should be able to output. data Metric m = MetricGauge !(Gauge m) | MetricCounter !(Counter m) | MetricHistogram !(Histogram m) | MetricMeter !(Meter m) | MetricTimer !(Timer m) -- | Add a new metric to a registry or retrieve the existing metric of the same name if one exists. class Register a where -- | If possible, avoid using 'register' to frequently retrieve metrics from a global registry. The metric registry is locked any time a lookup is performed, which may cause contention. register :: MetricRegistry IO -> Text -> IO a -> IO (Maybe a) instance Register (Counter IO) where register r t m = do hm <- takeMVar $ metrics r case H.lookup t hm of Nothing -> do c <- m putMVar (metrics r) $! H.insert t (MetricCounter c) hm return $ Just c Just im -> do putMVar (metrics r) hm return $! case im of MetricCounter c -> Just c _ -> Nothing instance Register (Gauge IO) where register r t m = do hm <- takeMVar $ metrics r case H.lookup t hm of Nothing -> do g <- m putMVar (metrics r) $! H.insert t (MetricGauge g) hm return $ Just g Just im -> do putMVar (metrics r) hm return $! case im of MetricGauge r -> Just r _ -> Nothing instance Register (Histogram IO) where register r t m = do hm <- takeMVar $ metrics r case H.lookup t hm of Nothing -> do h <- m putMVar (metrics r) $! H.insert t (MetricHistogram h) hm return $ Just h Just im -> do putMVar (metrics r) hm return $! case im of MetricHistogram h -> Just h _ -> Nothing instance Register (Meter IO) where register r t m = do hm <- takeMVar $ metrics r case H.lookup t hm of Nothing -> do mv <- m putMVar (metrics r) $! H.insert t (MetricMeter mv) hm return $ Just mv Just im -> do putMVar (metrics r) hm return $! case im of MetricMeter md -> Just md _ -> Nothing instance Register (Timer IO) where register r t m = do hm <- takeMVar $ metrics r case H.lookup t hm of Nothing -> do mv <- m putMVar (metrics r) $! H.insert t (MetricTimer mv) hm return $ Just mv Just im -> do putMVar (metrics r) hm return $! case im of MetricTimer md -> Just md _ -> Nothing
iand675/metrics
src/Data/Metrics/Registry.hs
mit
3,598
0
17
1,012
1,085
525
560
106
1