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 OverloadedStrings #-} module Main where import Control.Monad.Trans (lift) import qualified Data.Text as T import Data.Either import Reflex.Dom import Frontend.Function import Frontend.ImageWidget import Frontend.WebcamWidget main :: IO () main = mainWidget $ do d <- lift askDocument -- imageInputWidget d def functionPage d -- imageInputWidget d def -- webcamWidget d (constDyn mempty) -- loader <- fileImageLoader -- displayImg =<< holdDyn (T.pack "") (fmap snd loader) blank hush :: Either e a -> Maybe a hush (Right a) = Just a hush _ = Nothing
CBMM/CBaaS
cbaas-frontend/exec/Frontend.hs
bsd-3-clause
591
0
9
114
134
74
60
17
1
module Horbits.Body (bodyUiColor, getBody, fromBodyId, module X) where import Control.Lens hiding ((*~), _2, _3, _4) import Horbits.Body.Atmosphere as X import Horbits.Body.Body as X import Horbits.Body.Color as X import Horbits.Body.Data as X import Horbits.Body.Id as X bodyUiColor :: Fold BodyId (RgbaColor Float) bodyUiColor = to getColor . traverse -- Data getBody :: BodyId -> Body getBody bId = Body bId (_bodyName bId) mu r t soi atm where soi = getSphereOfInfluence bId (r, t, mu) = getPhysicalAttrs bId atm = getAtmosphere bId _bodyName :: BodyId -> String _bodyName Sun = "Kerbol" _bodyName b = show b fromBodyId :: Getter BodyId Body fromBodyId = to getBody
chwthewke/horbits
src/horbits/Horbits/Body.hs
bsd-3-clause
790
0
7
224
232
135
97
19
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | All types. module HIndent.Types (Printer(..) ,PrintState(..) ,Extender(..) ,Style(..) ,Config(..) ,defaultConfig ,NodeInfo(..) ,ComInfo(..) ,ComInfoLocation(..) ) where import Control.Applicative import Control.Monad import Control.Monad.State.Strict (MonadState(..),StateT) import Control.Monad.Trans.Maybe import Data.Data import Data.Default import Data.Functor.Identity import Data.Int (Int64) import Data.Text (Text) import Data.Text.Lazy.Builder (Builder) import Language.Haskell.Exts.Comments import Language.Haskell.Exts.Parser import Language.Haskell.Exts.SrcLoc -- | A pretty printing monad. newtype Printer s a = Printer {runPrinter :: StateT (PrintState s) (MaybeT Identity) a} deriving (Applicative,Monad,Functor,MonadState (PrintState s),MonadPlus,Alternative) -- | The state of the pretty printer. data PrintState s = PrintState {psIndentLevel :: !Int64 -- ^ Current indentation level. ,psOutput :: !Builder -- ^ The current output. ,psNewline :: !Bool -- ^ Just outputted a newline? ,psColumn :: !Int64 -- ^ Current column. ,psLine :: !Int64 -- ^ Current line number. ,psUserState :: !s -- ^ User state. ,psExtenders :: ![Extender s] -- ^ Extenders. ,psConfig :: !Config -- ^ Config which styles may or may not pay attention to. ,psEolComment :: !Bool -- ^ An end of line comment has just been outputted. ,psInsideCase :: !Bool -- ^ Whether we're in a case statement, used for Rhs printing. ,psParseMode :: !ParseMode -- ^ Mode used to parse the original AST. } instance Eq (PrintState s) where PrintState ilevel out newline col line _ _ _ eolc inc pm == PrintState ilevel' out' newline' col' line' _ _ _ eolc' inc' pm' = (ilevel,out,newline,col,line,eolc, inc) == (ilevel',out',newline',col',line',eolc', inc') -- | A printer extender. Takes as argument the user state that the -- printer was run with, and the current node to print. Use -- 'prettyNoExt' to fallback to the built-in printer. data Extender s where Extender :: forall s a. (Typeable a) => (a -> Printer s ()) -> Extender s CatchAll :: forall s. (forall a. Typeable a => s -> a -> Maybe (Printer s ())) -> Extender s -- | A printer style. data Style = forall s. Style {styleName :: !Text -- ^ Name of the style, used in the commandline interface. ,styleAuthor :: !Text -- ^ Author of the printer (as opposed to the author of the style). ,styleDescription :: !Text -- ^ Description of the style. ,styleInitialState :: !s -- ^ User state, if needed. ,styleExtenders :: ![Extender s] -- ^ Extenders to the printer. ,styleDefConfig :: !Config -- ^ Default config to use for this style. } -- | Configurations shared among the different styles. Styles may pay -- attention to or completely disregard this configuration. data Config = Config {configMaxColumns :: !Int64 -- ^ Maximum columns to fit code into ideally. ,configIndentSpaces :: !Int64 -- ^ How many spaces to indent? ,configClearEmptyLines :: !Bool -- ^ Remove spaces on lines that are otherwise empty? } instance Default Config where def = Config {configMaxColumns = 80 ,configIndentSpaces = 2 ,configClearEmptyLines = False} -- | Default style configuration. defaultConfig :: Config defaultConfig = def -- | Information for each node in the AST. data NodeInfo = NodeInfo {nodeInfoSpan :: !SrcSpanInfo -- ^ Location info from the parser. ,nodeInfoComments :: ![ComInfo] -- ^ Comments which are attached to this node. } deriving (Typeable,Show,Data) -- | Comment relative locations. data ComInfoLocation = Before | After deriving (Show,Typeable,Data,Eq) -- | Comment with some more info. data ComInfo = ComInfo {comInfoComment :: !Comment -- ^ The normal comment type. ,comInfoLocation :: !(Maybe ComInfoLocation) -- ^ Where the comment lies relative to the node. } deriving (Show,Typeable,Data)
adamse/hindent
src/HIndent/Types.hs
bsd-3-clause
4,328
0
15
1,009
841
507
334
-1
-1
module Graphics.Vty.Widgets.Builder.SrcHelpers ( defAttr , toAST , call , bind , tBind , noLoc , act , expr , mkTyp , parseType , mkList , parens , mkName , mkString , mkInt , mkChar , mkTup , opApp , mkLet , mkImportDecl , nameStr , attrsToExpr ) where import qualified Language.Haskell.Exts as Hs defAttr :: Hs.Exp defAttr = expr $ mkName "def_attr" toAST :: (Show a) => a -> Hs.Exp toAST thing = parsed where Hs.ParseOk parsed = Hs.parse $ show thing call :: String -> [Hs.Exp] -> Hs.Exp call func [] = Hs.Var $ Hs.UnQual $ mkName func call func args = mkApp (Hs.Var $ Hs.UnQual $ mkName func) args where mkApp app [] = app mkApp app (arg:rest) = mkApp (Hs.App app arg) rest bind :: Hs.Name -> String -> [Hs.Exp] -> Hs.Stmt bind lval func args = Hs.Generator noLoc (Hs.PVar lval) $ call func args tBind :: [Hs.Name] -> String -> [Hs.Exp] -> Hs.Stmt tBind lvals func args = Hs.Generator noLoc (Hs.PTuple (map Hs.PVar lvals)) $ call func args act :: Hs.Exp -> Hs.Stmt act = Hs.Qualifier expr :: Hs.Name -> Hs.Exp expr = Hs.Var . Hs.UnQual parens :: Hs.Exp -> Hs.Exp parens = Hs.Paren mkString :: String -> Hs.Exp mkString = Hs.Lit . Hs.String mkInt :: Int -> Hs.Exp mkInt = Hs.Lit . Hs.Int . toEnum mkChar :: Char -> Hs.Exp mkChar = Hs.Lit . Hs.Char mkTup :: [Hs.Exp] -> Hs.Exp mkTup = Hs.Tuple mkList :: [Hs.Exp] -> Hs.Exp mkList = Hs.List opApp :: Hs.Exp -> Hs.Name -> Hs.Exp -> Hs.Exp opApp a op b = Hs.InfixApp a (Hs.QVarOp $ Hs.UnQual op) b mkLet :: [(Hs.Name, Hs.Exp)] -> Hs.Stmt mkLet pairs = Hs.LetStmt $ Hs.BDecls $ map mkDecl pairs where mkDecl (nam, e) = Hs.PatBind noLoc (Hs.PVar nam) Nothing (Hs.UnGuardedRhs e) (Hs.BDecls []) mkName :: String -> Hs.Name mkName = Hs.Ident mkImportDecl :: String -> [String] -> Hs.ImportDecl mkImportDecl name hidden = Hs.ImportDecl { Hs.importLoc = noLoc , Hs.importModule = Hs.ModuleName name , Hs.importQualified = False , Hs.importSrc = False , Hs.importPkg = Nothing , Hs.importAs = Nothing , Hs.importSpecs = case hidden of [] -> Nothing is -> Just (True, map (Hs.IVar . mkName) is) } parseType :: String -> Hs.Type parseType s = case Hs.parse s of Hs.ParseOk val -> val Hs.ParseFailed _ msg -> error $ "Error parsing type string '" ++ s ++ "': " ++ msg attrsToExpr :: (Maybe String, Maybe String) -> Maybe Hs.Exp attrsToExpr (Nothing, Nothing) = Nothing attrsToExpr (Just fg, Nothing) = Just $ call "fgColor" [expr $ mkName fg] attrsToExpr (Nothing, Just bg) = Just $ call "bgColor" [expr $ mkName bg] attrsToExpr (Just fg, Just bg) = Just $ opApp (expr $ mkName fg) (mkName "on") (expr $ mkName bg) nameStr :: Hs.Name -> String nameStr (Hs.Ident s) = s nameStr n = error $ "Unsupported name: " ++ (show n) noLoc :: Hs.SrcLoc noLoc = Hs.SrcLoc { Hs.srcFilename = "-" , Hs.srcLine = 0 , Hs.srcColumn = 0 } mkTyp :: String -> [Hs.Type] -> Hs.Type mkTyp tyCon [] = Hs.TyCon $ Hs.UnQual $ mkName tyCon mkTyp tyCon args = mkApp (Hs.TyCon (Hs.UnQual (mkName tyCon))) args where mkApp ty [] = ty mkApp ty (ty':tys) = mkApp (Hs.TyApp ty ty') tys
jtdaugherty/vty-ui-builder
src/Graphics/Vty/Widgets/Builder/SrcHelpers.hs
bsd-3-clause
3,680
0
15
1,224
1,378
730
648
105
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE CPP #-} module Control.Distributed.Process.Serializable ( Serializable , encodeFingerprint , decodeFingerprint , fingerprint , sizeOfFingerprint , Fingerprint , showFingerprint , SerializableDict(SerializableDict) , TypeableDict(TypeableDict) ) where import Data.Binary (Binary) #if MIN_VERSION_base(4,7,0) import Data.Typeable (Typeable) import Data.Typeable.Internal (TypeRep(TypeRep), typeOf) #else import Data.Typeable (Typeable(..)) import Data.Typeable.Internal (TypeRep(TypeRep)) #endif import Numeric (showHex) import Control.Exception (throw) import GHC.Fingerprint.Type (Fingerprint(..)) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI ( unsafeCreate , inlinePerformIO , toForeignPtr ) import Foreign.Storable (pokeByteOff, peekByteOff, sizeOf) import Foreign.ForeignPtr (withForeignPtr) -- | Reification of 'Serializable' (see "Control.Distributed.Process.Closure") data SerializableDict a where SerializableDict :: Serializable a => SerializableDict a deriving (Typeable) -- | Reification of 'Typeable'. data TypeableDict a where TypeableDict :: Typeable a => TypeableDict a deriving (Typeable) -- | Objects that can be sent across the network class (Binary a, Typeable a) => Serializable a instance (Binary a, Typeable a) => Serializable a -- | Encode type representation as a bytestring encodeFingerprint :: Fingerprint -> ByteString encodeFingerprint fp = -- Since all CH nodes will run precisely the same binary, we don't have to -- worry about cross-arch issues here (like endianness) BSI.unsafeCreate sizeOfFingerprint $ \p -> pokeByteOff p 0 fp -- | Decode a bytestring into a fingerprint. Throws an IO exception on failure decodeFingerprint :: ByteString -> Fingerprint decodeFingerprint bs | BS.length bs /= sizeOfFingerprint = throw $ userError "decodeFingerprint: Invalid length" | otherwise = BSI.inlinePerformIO $ do let (fp, offset, _) = BSI.toForeignPtr bs withForeignPtr fp $ \p -> peekByteOff p offset -- | Size of a fingerprint sizeOfFingerprint :: Int sizeOfFingerprint = sizeOf (undefined :: Fingerprint) -- | The fingerprint of the typeRep of the argument fingerprint :: Typeable a => a -> Fingerprint fingerprint a = let TypeRep fp _ _ = typeOf a in fp -- | Show fingerprint (for debugging purposes) showFingerprint :: Fingerprint -> ShowS showFingerprint (Fingerprint hi lo) = showString "(" . showHex hi . showString "," . showHex lo . showString ")"
mboes/distributed-process
src/Control/Distributed/Process/Serializable.hs
bsd-3-clause
2,835
1
13
569
552
309
243
-1
-1
module Utils ( wordCount, makeBatch, accuracy ) where import Control.Arrow ( (&&&) ) import Data.List ( sort, group, reverse, nub ) import Control.Monad ( join ) wordCount :: (Eq a, Ord a) => [a] -> [(a, Int)] wordCount = map (head &&& length) . group . sort makeBatch :: Int -> [a] -> [[a]] makeBatch _ [] = [] makeBatch size xs = let (x, xs') = splitAt size xs in x:makeBatch size xs' accuracy :: Eq a => [[a]] -> [[a]] -> Float accuracy pred gold = realToFrac correct / realToFrac (length pred') where correct = length $ filter (\(p, g) -> p == g) $ zip pred' gold' pred' = join pred gold' = join gold
masashi-y/dynet.hs
examples/utils/Utils.hs
bsd-3-clause
653
0
12
166
308
169
139
17
1
module Data.Aeson.TH.Extra where import Data.Aeson.TH ( defaultOptions , Options(..) ) import Data.String.Extra (dropL1) prefixRemovedOpts :: Int -> Options prefixRemovedOpts i = defaultOptions {fieldLabelModifier = dropL1 i}
onurzdg/clicklac
src/Data/Aeson/TH/Extra.hs
bsd-3-clause
260
0
7
56
65
40
25
7
1
{-#LANGUAGE FlexibleInstances #-} {-#LANGUAGE FlexibleContexts #-} {-#LANGUAGE LambdaCase #-} {-#LANGUAGE MultiParamTypeClasses #-} {-#LANGUAGE OverloadedStrings #-} {-#LANGUAGE Rank2Types #-} {-#LANGUAGE ScopedTypeVariables #-} module Twilio.Types ( APIVersion(..) , module X -- * Misc , makeTwilioRequest , makeTwilioRequest' , makeTwilioPOSTRequest , makeTwilioPOSTRequest' ) where import Control.Monad import Control.Monad.Reader.Class import Data.Aeson import qualified Data.ByteString.Char8 as C import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Network.HTTP.Client import Control.Monad.Twilio import Twilio.Types.AddressRequirement as X import Twilio.Types.AuthToken as X import Twilio.Types.Capability as X import Twilio.Types.ISOCountryCode as X import Twilio.Types.List as X import Twilio.Types.PriceUnit as X import Twilio.Types.SID as X import Twilio.Internal.Parser import Twilio.Internal.Request data APIVersion = API_2010_04_01 | API_2008_08_01 deriving Eq instance Read APIVersion where readsPrec _ = \case "2010-04-01" -> return (API_2010_04_01, "") "2008-08-01" -> return (API_2008_08_01, "") _ -> mzero instance Show APIVersion where show API_2010_04_01 = "2010-04-01" show API_2008_08_01 = "2008-08-01" instance FromJSON APIVersion where parseJSON (String "2010-04-01") = return API_2010_04_01 parseJSON (String "2008-08-01") = return API_2008_08_01 parseJSON _ = mzero makeTwilioRequest' :: Monad m => Text -> TwilioT m Request makeTwilioRequest' suffix = do ((accountSID, authToken), _) <- ask let Just request = parseUrl . T.unpack $ baseURL <> suffix return $ applyBasicAuth (C.pack . T.unpack $ getSID accountSID) (C.pack . T.unpack $ getAuthToken authToken) request makeTwilioRequest :: Monad m => Text -> TwilioT m Request makeTwilioRequest suffix = do ((_, _), accountSID) <- ask makeTwilioRequest' $ "/Accounts/" <> getSID accountSID <> suffix makeTwilioPOSTRequest' :: Monad m => Text -> [(C.ByteString, C.ByteString)] -> TwilioT m Request makeTwilioPOSTRequest' resourceURL params = makeTwilioRequest' resourceURL <&> urlEncodedBody params makeTwilioPOSTRequest :: Monad m => Text -> [(C.ByteString, C.ByteString)] -> TwilioT m Request makeTwilioPOSTRequest resourceURL params = makeTwilioRequest resourceURL <&> urlEncodedBody params
seagreen/twilio-haskell
src/Twilio/Types.hs
bsd-3-clause
2,543
0
13
521
616
344
272
70
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} ------------------------------------------------------------------------------- -- | -- Module : Database.Bloodhound.Types.Internal -- Copyright : (C) 2014 Chris Allen -- License : BSD-style (see the file LICENSE) -- Maintainer : Chris Allen <[email protected]> -- Stability : provisional -- Portability : DeriveGeneric, RecordWildCards -- -- Internal data types for Bloodhound. These types may change without -- notice so import at your own risk. ------------------------------------------------------------------------------- module Database.V5.Bloodhound.Types.Internal ( BHEnv(..) , Server(..) , MonadBH(..) ) where import Control.Applicative as A import Control.Monad.Reader import Data.Aeson import Data.Text (Text) import Data.Typeable (Typeable) import GHC.Generics (Generic) import Network.HTTP.Client {-| Common environment for Elasticsearch calls. Connections will be pipelined according to the provided HTTP connection manager. -} data BHEnv = BHEnv { bhServer :: Server , bhManager :: Manager , bhRequestHook :: Request -> IO Request -- ^ Low-level hook that is run before every request is sent. Used to implement custom authentication strategies. Defaults to 'return' with 'mkBHEnv'. } instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where getBHEnv = ask {-| 'Server' is used with the client functions to point at the ES instance -} newtype Server = Server Text deriving (Eq, Show, Generic, Typeable, FromJSON) {-| All API calls to Elasticsearch operate within MonadBH . The idea is that it can be easily embedded in your own monad transformer stack. A default instance for a ReaderT and alias 'BH' is provided for the simple case. -} class (Functor m, A.Applicative m, MonadIO m) => MonadBH m where getBHEnv :: m BHEnv
bermanjosh/bloodhound
src/Database/V5/Bloodhound/Types/Internal.hs
bsd-3-clause
2,168
0
10
522
253
156
97
23
0
{- Problem 30 Numbers that can be written as powers of their digits Result 443839 6.28 s Comment The upper boundary can be estimated since 999... = 10^k - 1 has to be equal to 9^5 + 9^5 + ... = k 9^5, which yields the maximum condition k 9^5 = 10^k - 1. A numeric solution for this is 5.51257, which yields a maximum of 10^5.51257 = 325514.24. -} module Problem30 (solution) where import CommonFunctions solution = fromIntegral . sum' $ filter is5thPowerSum [2..325515] -- Can x be written as the sum of fifth power of its digits? is5thPowerSum x = x == (sum' . map toTheFifth $ show x) -- Memoize powers toTheFifth '0' = 0^5 toTheFifth '1' = 1^5 toTheFifth '2' = 2^5 toTheFifth '3' = 3^5 toTheFifth '4' = 4^5 toTheFifth '5' = 5^5 toTheFifth '6' = 6^5 toTheFifth '7' = 7^5 toTheFifth '8' = 8^5 toTheFifth '9' = 9^5 toTheFifth _ = error "Not a digit 'to the fifth' in problem 30"
quchen/HaskellEuler
src/Problem30.hs
bsd-3-clause
990
0
9
278
198
102
96
15
1
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} #ifdef DEFAULT_SIGNATURES {-# LANGUAGE DefaultSignatures #-} #endif #ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.At -- Copyright : (C) 2012 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable -- ---------------------------------------------------------------------------- module Control.Lens.At ( -- * Indexed Lens At(at) , ixAt , ixEach -- * Indexed Traversal , Ixed(ix) -- * Deprecated , _at , contains , resultAt ) where import Control.Applicative import Control.Lens.Combinators import Control.Lens.Each import Control.Lens.Indexed import Control.Lens.IndexedLens import Control.Lens.IndexedTraversal import Control.Lens.Traversal import Data.Array.IArray as Array import Data.Array.Unboxed import Data.Hashable import Data.HashMap.Lazy as HashMap import Data.HashSet as HashSet import Data.IntMap as IntMap import Data.IntSet as IntSet import Data.Map as Map import Data.Set as Set import Data.Sequence as Seq import Data.Vector as Vector hiding (indexed) import Data.Vector.Primitive as Prim import Data.Vector.Storable as Storable -- $setup -- >>> import Control.Lens -- >>> import Debug.SimpleReflect.Expr -- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g) -- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f -- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g -- | A deprecated alias for 'ix' contains, _at, resultAt :: (Indexable (IxKey m) p, Ixed f m) => IxKey m -> IndexedLensLike' p f m (IxValue m) contains = ix _at = ix resultAt = ix {-# DEPRECATED _at, contains, resultAt "use 'ix'. This function will be removed in version 3.9" #-} type family IxKey (m :: *) :: * type family IxValue (m :: *) :: * -- | This simple indexed traversal lets you 'traverse' the value at a given key in a map or element at an ordinal -- position in a list or sequence. class Ixed f m where -- | What is the index type? -- | This simple indexed traversal lets you 'traverse' the value at a given key in a map. -- -- *NB:* _setting_ the value of this 'Traversal' will only set the value in the lens -- if it is already present. -- -- If you want to be able to insert /missing/ values, you want 'at'. -- -- >>> Seq.fromList [a,b,c,d] & ix 2 %~ f -- fromList [a,b,f c,d] -- -- >>> Seq.fromList [a,b,c,d] & ix 2 .~ e -- fromList [a,b,e,d] -- -- >>> Seq.fromList [a,b,c,d] ^? ix 2 -- Just c -- -- >>> Seq.fromList [] ^? ix 2 -- Nothing -- -- >>> IntSet.fromList [1,2,3,4] & ix 3 .~ False -- fromList [1,2,4] -- -- >>> IntSet.fromList [1,2,3,4] ^. ix 3 -- True -- >>> IntSet.fromList [1,2,3,4] ^. ix 5 -- False ix :: Indexable (IxKey m) p => IxKey m -> IndexedLensLike' p f m (IxValue m) #ifdef DEFAULT_SIGNATURES default ix :: (Indexable (IxKey m) p, Applicative f, At m) => IxKey m -> IndexedLensLike' p f m (IxValue m) ix = ixAt #endif -- | A definition of 'ix' for types with an 'At' instance. This is the default -- if you don't specify a definition for 'ix'. ixAt :: (Indexable (IxKey m) p, Applicative f, At m) => IxKey m -> IndexedLensLike' p f m (IxValue m) ixAt i = at i <. traverse {-# INLINE ixAt #-} -- | A definition of 'ix' for types with an 'Each' instance. ixEach :: (Indexable (IxKey m) p, Applicative f, Eq (IxKey m), Each (IxKey m) f m m (IxValue m) (IxValue m)) => IxKey m -> IndexedLensLike' p f m (IxValue m) ixEach i = iwhereOf each (i ==) {-# INLINE ixEach #-} type instance IxKey [a] = Int type instance IxValue [a] = a instance Applicative f => Ixed f [a] where ix k f xs0 = go xs0 k where go [] _ = pure [] go (a:as) 0 = indexed f k a <&> (:as) go (a:as) i = (a:) <$> (go as $! i - 1) {-# INLINE ix #-} type instance IxKey (Seq a) = Int type instance IxValue (Seq a) = a instance Applicative f => Ixed f (Seq a) where ix i f m | 0 <= i && i < Seq.length m = indexed f i (Seq.index m i) <&> \a -> Seq.update i a m | otherwise = pure m {-# INLINE ix #-} type instance IxKey (IntMap a) = Int type instance IxValue (IntMap a) = a instance Applicative f => Ixed f (IntMap a) where ix k f m = case IntMap.lookup k m of Just v -> indexed f k v <&> \v' -> IntMap.insert k v' m Nothing -> pure m {-# INLINE ix #-} type instance IxKey (Map k a) = k type instance IxValue (Map k a) = a instance (Applicative f, Ord k) => Ixed f (Map k a) where ix k f m = case Map.lookup k m of Just v -> indexed f k v <&> \v' -> Map.insert k v' m Nothing -> pure m {-# INLINE ix #-} type instance IxKey (HashMap k a) = k type instance IxValue (HashMap k a) = a instance (Applicative f, Eq k, Hashable k) => Ixed f (HashMap k a) where ix k f m = case HashMap.lookup k m of Just v -> indexed f k v <&> \v' -> HashMap.insert k v' m Nothing -> pure m {-# INLINE ix #-} type instance IxKey (Array i e) = i type instance IxValue (Array i e) = e -- | -- @ -- arr '!' i ≡ arr '^.' 'ix' i -- arr '//' [(i,e)] ≡ 'ix' i '.~' e '$' arr -- @ instance (Applicative f, Ix i) => Ixed f (Array i e) where ix i f arr | inRange (bounds arr) i = indexed f i (arr Array.! i) <&> \e -> arr Array.// [(i,e)] | otherwise = pure arr {-# INLINE ix #-} type instance IxKey (UArray i e) = i type instance IxValue (UArray i e) = e -- | -- @ -- arr '!' i ≡ arr '^.' 'ix' i -- arr '//' [(i,e)] ≡ 'ix' i '.~' e '$' arr -- @ instance (Applicative f, IArray UArray e, Ix i) => Ixed f (UArray i e) where ix i f arr | inRange (bounds arr) i = indexed f i (arr Array.! i) <&> \e -> arr Array.// [(i,e)] | otherwise = pure arr {-# INLINE ix #-} type instance IxKey (Vector.Vector a) = Int type instance IxValue (Vector.Vector a) = a instance Applicative f => Ixed f (Vector.Vector a) where ix i f v | 0 <= i && i < Vector.length v = indexed f i (v Vector.! i) <&> \a -> v Vector.// [(i, a)] | otherwise = pure v {-# INLINE ix #-} type instance IxKey (Prim.Vector a) = Int type instance IxValue (Prim.Vector a) = a instance (Applicative f, Prim a) => Ixed f (Prim.Vector a) where ix i f v | 0 <= i && i < Prim.length v = indexed f i (v Prim.! i) <&> \a -> v Prim.// [(i, a)] | otherwise = pure v {-# INLINE ix #-} type instance IxKey (Storable.Vector a) = Int type instance IxValue (Storable.Vector a) = a instance (Applicative f, Storable a) => Ixed f (Storable.Vector a) where ix i f v | 0 <= i && i < Storable.length v = indexed f i (v Storable.! i) <&> \a -> v Storable.// [(i, a)] | otherwise = pure v {-# INLINE ix #-} type instance IxKey IntSet = Int type instance IxValue IntSet = Bool instance Functor f => Ixed f IntSet where ix k f s = indexed f k (IntSet.member k s) <&> \b -> if b then IntSet.insert k s else IntSet.delete k s {-# INLINE ix #-} type instance IxKey (Set a) = a type instance IxValue (Set a) = Bool instance (Functor f, Ord a) => Ixed f (Set a) where ix k f s = indexed f k (Set.member k s) <&> \b -> if b then Set.insert k s else Set.delete k s {-# INLINE ix #-} type instance IxKey (HashSet a) = a type instance IxValue (HashSet a) = Bool instance (Functor f, Eq a, Hashable a) => Ixed f (HashSet a) where ix k f s = indexed f k (HashSet.member k s) <&> \b -> if b then HashSet.insert k s else HashSet.delete k s {-# INLINE ix #-} type instance IxKey (k -> a) = k type instance IxValue (k -> a) = a instance (Functor f, Eq k) => Ixed f (k -> a) where ix e g f = indexed g e (f e) <&> \a' e' -> if e == e' then a' else f e' {-# INLINE ix #-} type instance IxKey (a,a) = Int type instance IxValue (a,a) = a instance (Applicative f, a ~ b) => Ixed f (a,b) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a) = Int type instance IxValue (a,a,a) = a instance (Applicative f, a ~ b, b ~ c) => Ixed f (a,b,c) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a) = Int type instance IxValue (a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d) => Ixed f (a,b,c,d) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e) => Ixed f (a,b,c,d,e) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f') => Ixed f (a,b,c,d,e,f') where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f', f' ~ g) => Ixed f (a,b,c,d,e,f',g) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f', f' ~ g, g ~ h) => Ixed f (a,b,c,d,e,f',g,h) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f', f' ~ g, g ~ h, h ~ i) => Ixed f (a,b,c,d,e,f',g,h,i) where ix = ixEach {-# INLINE ix #-} -- | 'At' provides a lens that can be used to read, -- write or delete the value associated with a key in a map-like -- container on an ad hoc basis. -- -- An instance of @At@ should satisfy: -- -- @'el' k ≡ 'at' k '<.' 'traverse'@ class At m where -- | -- >>> Map.fromList [(1,"world")] ^.at 1 -- Just "world" -- -- >>> at 1 ?~ "hello" $ Map.empty -- fromList [(1,"hello")] -- -- /Note:/ 'Map'-like containers form a reasonable instance, but not 'Array'-like ones, where -- you cannot satisfy the 'Lens' laws. at :: IxKey m -> IndexedLens' (IxKey m) m (Maybe (IxValue m)) instance At (IntMap a) where at k f m = indexed f k mv <&> \r -> case r of Nothing -> maybe m (const (IntMap.delete k m)) mv Just v' -> IntMap.insert k v' m where mv = IntMap.lookup k m {-# INLINE at #-} instance Ord k => At (Map k a) where at k f m = indexed f k mv <&> \r -> case r of Nothing -> maybe m (const (Map.delete k m)) mv Just v' -> Map.insert k v' m where mv = Map.lookup k m {-# INLINE at #-} instance (Eq k, Hashable k) => At (HashMap k a) where at k f m = indexed f k mv <&> \r -> case r of Nothing -> maybe m (const (HashMap.delete k m)) mv Just v' -> HashMap.insert k v' m where mv = HashMap.lookup k m {-# INLINE at #-}
np/lens
src/Control/Lens/At.hs
bsd-3-clause
10,918
0
16
2,571
4,050
2,236
1,814
211
1
module Parser ()where import Text.XML.HXT.Core import Data.String.UTF8 import Control.Monad odd :: (->) Int Bool odd a = True css tag = multi (hasName tag) testDoc = do html <- readFile "test.html" let doc = readString [withParseHTML yes, withWarnings no] html texts <- runX $ doc //> getText mapM_ putStrLn texts main = do html <- readFile "test.html" let doc = readString [withParseHTML yes, withWarnings no] html links <- runX $ doc //> hasName "a" >>> getAttrValue "href" mapM_ putStrLn links
Numberartificial/workflow
snipets/src/Demo/Parser.hs
mit
525
0
12
108
201
98
103
18
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.OSX -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : <maintainer at leksah.org> -- Stability : provisional -- Portability : portable -- -- -- Support for OSX -- --------------------------------------------------------------------------------- module IDE.OSX ( applicationNew , updateMenu , applicationReady , allowFullscreen ) where import Graphics.UI.Gtk import IDE.Core.State #if defined(darwin_HOST_OS) import Control.Monad.Reader (liftIO) import Control.Monad.Reader.Class (ask) import Graphics.UI.Gtk.OSX import IDE.Command (canQuit) import Data.Text (Text) updateMenu :: Application -> UIManager -> IDEM () updateMenu app uiManager = do ideR <- ask liftIO $ do mbMenu <- uiManagerGetWidget uiManager ("/ui/menubar" :: Text) case mbMenu of Just menu -> do widgetHide menu applicationSetMenuBar app (castToMenuShell menu) Nothing -> return () mbQuit <- uiManagerGetWidget uiManager ("/ui/menubar/_File/_Quit" :: Text) case mbQuit of Just quit -> widgetHide quit Nothing -> return () mbAbout <- uiManagerGetWidget uiManager ("/ui/menubar/_Help/_About" :: Text) case mbAbout of Just about -> do applicationInsertAppMenuItem app (castToMenuItem about) 0 sep <- separatorMenuItemNew applicationInsertAppMenuItem app sep 1 Nothing -> return () mbPrefs <- uiManagerGetWidget uiManager ("/ui/menubar/_Tools/_Preferences" :: Text) case mbPrefs of Just prefs -> do applicationInsertAppMenuItem app (castToMenuItem prefs) 2 Nothing -> return () app `on` blockTermination $ reflectIDE (fmap not canQuit) ideR applicationSetUseQuartsAccelerators app True #else data Application = Application applicationNew :: IO Application applicationNew = return Application updateMenu :: Application -> UIManager -> IDEM () updateMenu _ _ = return () applicationReady :: Application -> IO () applicationReady _ = return () allowFullscreen :: DrawWindowClass window => window -> IO () allowFullscreen _ = return () #endif
jaccokrijnen/leksah
src/IDE/OSX.hs
gpl-2.0
2,447
0
17
601
429
222
207
18
1
module RSA.Break where import RSA.Break.Data import RSA.Euclid import Faktor.Prim import Faktor.Certify ( powmod ) import Data.Typeable import Challenger.Partial import Autolib.ToDoc import Autolib.Reporter import Autolib.Ana import Inter.Types data RSA_Code_Break = RSA_Code_Break deriving ( Read, Show, Typeable ) instance OrderScore RSA_Code_Break where scoringOrder _ = None instance Partial RSA_Code_Break Config Integer where describe RSA_Code_Break conf = vcat [ text "Finden Sie den Klartext für eine RSA-Verschlüsselung mit" , nest 4 $ toDoc conf ] initial RSA_Code_Break conf = let (d, n) = public_key conf b = 3 xs = based b n in unbased b $ reverse xs total RSA_Code_Break conf x = do let ( d, n ) = public_key conf let y = powmod x d n inform $ vcat [ text "bei Verschlüsselung von" <+> toDoc x , fsep [ text "erhält man" , toDoc x, text "^", toDoc d, text "=" , toDoc y, text "mod", toDoc n ] ] assert ( y == message conf ) $ text "Stimmt das mit vorliegender Nachricht überein?" instance Measure RSA_Code_Break Config Integer where measure RSA_Code_Break c i = 0 break :: Config -> Integer -> Integer break conf x = let (d, n) = public_key conf Just [(p, 1), (q, 1)] = factor n phi = pred p * pred q (a, b) = euclid phi d e = b `mod` phi in powmod x e n make :: Make make = direct RSA_Code_Break RSA.Break.Data.example
florianpilz/autotool
src/RSA/Break.hs
gpl-2.0
1,487
41
9
383
515
276
239
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Dependency.Types -- Copyright : (c) Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Common types for dependency resolution. ----------------------------------------------------------------------------- module Distribution.Client.Dependency.Types ( ExtDependency(..), PreSolver(..), Solver(..), DependencyResolver, PackageConstraint(..), PackagePreferences(..), InstalledPreference(..), PackagesPreferenceDefault(..), Progress(..), foldProgress, ) where import Control.Applicative ( Applicative(..), Alternative(..) ) import Data.Char ( isAlpha, toLower ) import Data.Monoid ( Monoid(..) ) import Distribution.Client.Types ( OptionalStanza, SourcePackage(..) ) import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Compat.ReadP ( (<++) ) import qualified Distribution.Compat.ReadP as Parse ( pfail, munch1 ) import Distribution.PackageDescription ( FlagAssignment ) import qualified Distribution.Client.PackageIndex as PackageIndex ( PackageIndex ) import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex ( PackageIndex ) import Distribution.Package ( Dependency, PackageName, InstalledPackageId ) import Distribution.Version ( VersionRange ) import Distribution.Compiler ( CompilerId ) import Distribution.System ( Platform ) import Distribution.Text ( Text(..) ) import Text.PrettyPrint ( text ) import Prelude hiding (fail) -- | Covers source dependencies and installed dependencies in -- one type. data ExtDependency = SourceDependency Dependency | InstalledDependency InstalledPackageId instance Text ExtDependency where disp (SourceDependency dep) = disp dep disp (InstalledDependency dep) = disp dep parse = (SourceDependency `fmap` parse) <++ (InstalledDependency `fmap` parse) -- | All the solvers that can be selected. data PreSolver = AlwaysTopDown | AlwaysModular | Choose deriving (Eq, Ord, Show, Bounded, Enum) -- | All the solvers that can be used. data Solver = TopDown | Modular deriving (Eq, Ord, Show, Bounded, Enum) instance Text PreSolver where disp AlwaysTopDown = text "topdown" disp AlwaysModular = text "modular" disp Choose = text "choose" parse = do name <- Parse.munch1 isAlpha case map toLower name of "topdown" -> return AlwaysTopDown "modular" -> return AlwaysModular "choose" -> return Choose _ -> Parse.pfail -- | A dependency resolver is a function that works out an installation plan -- given the set of installed and available packages and a set of deps to -- solve for. -- -- The reason for this interface is because there are dozens of approaches to -- solving the package dependency problem and we want to make it easy to swap -- in alternatives. -- type DependencyResolver = Platform -> CompilerId -> InstalledPackageIndex.PackageIndex -> PackageIndex.PackageIndex SourcePackage -> (PackageName -> PackagePreferences) -> [PackageConstraint] -> [PackageName] -> Progress String String [InstallPlan.PlanPackage] -- | Per-package constraints. Package constraints must be respected by the -- solver. Multiple constraints for each package can be given, though obviously -- it is possible to construct conflicting constraints (eg impossible version -- range or inconsistent flag assignment). -- data PackageConstraint = PackageConstraintVersion PackageName VersionRange | PackageConstraintInstalled PackageName | PackageConstraintSource PackageName | PackageConstraintFlags PackageName FlagAssignment | PackageConstraintStanzas PackageName [OptionalStanza] deriving (Show,Eq) -- | A per-package preference on the version. It is a soft constraint that the -- 'DependencyResolver' should try to respect where possible. It consists of -- a 'InstalledPreference' which says if we prefer versions of packages -- that are already installed. It also hase a 'PackageVersionPreference' which -- is a suggested constraint on the version number. The resolver should try to -- use package versions that satisfy the suggested version constraint. -- -- It is not specified if preferences on some packages are more important than -- others. -- data PackagePreferences = PackagePreferences VersionRange InstalledPreference -- | Whether we prefer an installed version of a package or simply the latest -- version. -- data InstalledPreference = PreferInstalled | PreferLatest -- | Global policy for all packages to say if we prefer package versions that -- are already installed locally or if we just prefer the latest available. -- data PackagesPreferenceDefault = -- | Always prefer the latest version irrespective of any existing -- installed version. -- -- * This is the standard policy for upgrade. -- PreferAllLatest -- | Always prefer the installed versions over ones that would need to be -- installed. Secondarily, prefer latest versions (eg the latest installed -- version or if there are none then the latest source version). | PreferAllInstalled -- | Prefer the latest version for packages that are explicitly requested -- but prefers the installed version for any other packages. -- -- * This is the standard policy for install. -- | PreferLatestForSelected -- | A type to represent the unfolding of an expensive long running -- calculation that may fail. We may get intermediate steps before the final -- retult which may be used to indicate progress and\/or logging messages. -- data Progress step fail done = Step step (Progress step fail done) | Fail fail | Done done -- | Consume a 'Progress' calculation. Much like 'foldr' for lists but with two -- base cases, one for a final result and one for failure. -- -- Eg to convert into a simple 'Either' result use: -- -- > foldProgress (flip const) Left Right -- foldProgress :: (step -> a -> a) -> (fail -> a) -> (done -> a) -> Progress step fail done -> a foldProgress step fail done = fold where fold (Step s p) = step s (fold p) fold (Fail f) = fail f fold (Done r) = done r instance Functor (Progress step fail) where fmap f = foldProgress Step Fail (Done . f) instance Monad (Progress step fail) where return a = Done a p >>= f = foldProgress Step Fail f p instance Applicative (Progress step fail) where pure a = Done a p <*> x = foldProgress Step Fail (flip fmap x) p instance Monoid fail => Alternative (Progress step fail) where empty = Fail mempty p <|> q = foldProgress Step (const q) Done p
jwiegley/ghc-release
libraries/Cabal/cabal-install/Distribution/Client/Dependency/Types.hs
gpl-3.0
7,142
0
14
1,625
1,129
659
470
105
3
import Control.Monad import Control.Monad.Trans.Resource import System.IO import System.Exit import System.Environment import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.Conduit.Binary as CB import qualified Data.ByteString.Char8 as BS import Data.Conduit.ZMQ3 (zmqSource) import System.ZMQ3.Monad (makeSocket, runZMQ) import qualified System.ZMQ3.Monad as ZMQ main :: IO () main = do args <- getArgs when (length args < 1) $ do hPutStrLn stderr "usage: display <address> [<address>, ...]" exitFailure runResourceT $ runZMQ 1 $ do s <- makeSocket ZMQ.Sub ZMQ.subscribe s "" mapM_ (ZMQ.connect s) args zmqSource s $= CL.map (`BS.append` newline) $$ CB.sinkHandle stdout where newline = BS.pack "\n"
rgrinberg/zeromq3-conduit
examples/display.hs
lgpl-2.1
800
1
13
165
247
132
115
24
1
{-# LANGUAGE CPP #-} module Graphics.ImageMagick.MagickWand.PixelWand ( pixelWand -- , clearPixelWand -- , cloneWand -- , cloneWands , isPixelWandSimilar -- , isPixelWand , setColorCount, getColorCount -- ** Literal names , setColor , getColorAsString, getColorAsNormalizedString -- HSL , getHSL, setHSL , getMagickColor, setMagickColor , setColorFromWand , getQuantumColor, setQuantumColor -- ** Color parts -- Index , getIndex, setIndex -- Fuzz , getFuzz, setFuzz -- Alpha , getOpacity, getOpacityQuantum, setOpacity, setOpacityQuantum , getAlpha, getAlphaQuantum, setAlpha, setAlphaQuantum -- RGB , getRed, getRedQuantum, setRed, setRedQuantum , getBlue, getBlueQuantum, setBlue, setBlueQuantum , getGreen, getGreenQuantum, setGreen, setGreenQuantum -- CMYK , getCyan, getCyanQuantum, setCyan, setCyanQuantum , getMagenta, getMagentaQuantum, setMagenta, setMagentaQuantum , getYellow, getYellowQuantum, setYellow, setYellowQuantum , getBlack, getBlackQuantum, setBlack, setBlackQuantum ) where import Control.Monad (void) import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.ByteString (ByteString, packCString, useAsCString) import Foreign hiding (void) import Foreign.C.Types (CDouble) import qualified Graphics.ImageMagick.MagickWand.FFI.PixelWand as F import Graphics.ImageMagick.MagickWand.Types import Graphics.ImageMagick.MagickWand.Utils pixelWand :: (MonadResource m) => m PPixelWand pixelWand = fmap snd (allocate F.newPixelWand destroy) where destroy = void . F.destroyPixelWand setColor :: (MonadResource m) => PPixelWand -> ByteString -> m () setColor p s = withException_ p $ useAsCString s (F.pixelSetColor p) getMagickColor :: (MonadResource m) => PPixelWand -> m PMagickPixelPacket getMagickColor w = liftIO $ do p <- mallocForeignPtr withForeignPtr p (F.pixelGetMagickColor w) return p setMagickColor :: (MonadResource m) => PPixelWand -> PMagickPixelPacket -> m () setMagickColor w p = liftIO $ withForeignPtr p (F.pixelSetMagickColor w) setColorCount :: (MonadResource m) => PPixelWand -> Int -> m () setColorCount w i = liftIO $ F.pixelSetColorCount w (fromIntegral i) getColorCount :: (MonadResource m) => PPixelWand -> m Int getColorCount w = liftIO (F.pixelGetColorCount w) >>= return . fromIntegral getColorAsString :: (MonadResource m) => PPixelWand -> m ByteString getColorAsString w = liftIO $ F.pixelGetColorAsString w >>= packCString getColorAsNormalizedString :: (MonadResource m) => PPixelWand -> m ByteString getColorAsNormalizedString w = liftIO $ F.pixelGetColorAsNormalizedString w >>= packCString getHSL :: (MonadResource m) => PPixelWand -> m (Double, Double, Double) getHSL w = liftIO $ fmap (map3 realToFrac) (with3 (F.pixelGetHSL w)) setHSL :: (MonadResource m) => PPixelWand -> Double -> Double -> Double -> m () setHSL w h s l = liftIO $ F.pixelSetHSL w (realToFrac h) (realToFrac s) (realToFrac l) setColorFromWand :: (MonadResource m) => PPixelWand -> PPixelWand -> m () setColorFromWand = (liftIO .). F.pixelSetColorFromWand getIndex :: (MonadResource m) => PPixelWand -> m IndexPacket getIndex = liftIO . F.pixelGetIndex setIndex :: (MonadResource m) => PPixelWand -> IndexPacket -> m () setIndex w i = liftIO $ F.pixelSetIndex w i getQuantumColor :: (MonadResource m) => PPixelWand -> m PPixelPacket getQuantumColor w = liftIO $ do p <- mallocForeignPtr withForeignPtr p (F.pixelGetQuantumColor w) return p setQuantumColor :: (MonadResource m) => PPixelWand -> PPixelPacket -> m () setQuantumColor w p = liftIO $ withForeignPtr p (F.pixelSetQuantumColor w) getFuzz :: (MonadResource m) => PPixelWand -> m Double getFuzz = liftIO . ((fmap realToFrac) . F.pixelGetFuzz) setFuzz :: (MonadResource m) => PPixelWand -> Double -> m () setFuzz w i = liftIO $ F.pixelSetFuzz w (realToFrac i) isPixelWandSimilar :: (MonadResource m) => PPixelWand -> PPixelWand -> Double -> m Bool isPixelWandSimilar pw1 pw2 fuzz = fromMBool $ F.isPixelWandSimilar pw1 pw2 (realToFrac fuzz) setRedQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setRedQuantum = (liftIO .) . F.pixelSetRedQuantum getRed :: (MonadResource m) => PPixelWand -> m Double getRed = (fmap realToFrac) . liftIO . F.pixelGetRed setRed :: (MonadResource m) => PPixelWand -> Double -> m () setRed = (liftIO .) . (. realToFrac) . F.pixelSetRed getRedQuantum :: (MonadResource m) => PPixelWand -> m Quantum getRedQuantum = liftIO . F.pixelGetRedQuantum setGreenQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setGreenQuantum = (liftIO .) . F.pixelSetGreenQuantum getGreen :: (MonadResource m) => PPixelWand -> m Double getGreen = (fmap realToFrac) . liftIO . F.pixelGetGreen setGreen :: (MonadResource m) => PPixelWand -> Double -> m () setGreen = (liftIO .) . (. realToFrac) . F.pixelSetGreen getGreenQuantum :: (MonadResource m) => PPixelWand -> m Quantum getGreenQuantum = liftIO . F.pixelGetGreenQuantum setBlueQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setBlueQuantum = (liftIO .) . F.pixelSetBlueQuantum getBlue :: (MonadResource m) => PPixelWand -> m Double getBlue = (fmap realToFrac) . liftIO . F.pixelGetBlue setBlue :: (MonadResource m) => PPixelWand -> Double -> m () setBlue = (liftIO .) . (. realToFrac) . F.pixelSetBlue getBlueQuantum :: (MonadResource m) => PPixelWand -> m Quantum getBlueQuantum = liftIO . F.pixelGetBlueQuantum setAlphaQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setAlphaQuantum = (liftIO .) . F.pixelSetAlphaQuantum getAlphaQuantum :: (MonadResource m) => PPixelWand -> m Quantum getAlphaQuantum = liftIO . F.pixelGetAlphaQuantum setAlpha :: (MonadResource m) => PPixelWand -> Double -> m () setAlpha = (liftIO .) . (. realToFrac) . F.pixelSetAlpha getAlpha :: (MonadResource m) => PPixelWand -> m Double getAlpha = (fmap realToFrac) . liftIO . F.pixelGetAlpha setOpacityQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setOpacityQuantum = (liftIO .) . F.pixelSetOpacityQuantum getOpacityQuantum :: (MonadResource m) => PPixelWand -> m Quantum getOpacityQuantum = liftIO . F.pixelGetOpacityQuantum setOpacity :: (MonadResource m) => PPixelWand -> Double -> m () setOpacity = (liftIO .) . (. realToFrac) . F.pixelSetOpacity getOpacity :: (MonadResource m) => PPixelWand -> m Double getOpacity = (fmap realToFrac) . liftIO . F.pixelGetOpacity setBlackQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setBlackQuantum = (liftIO .) . F.pixelSetBlackQuantum getBlackQuantum :: (MonadResource m) => PPixelWand -> m Quantum getBlackQuantum = liftIO . F.pixelGetBlackQuantum setBlack :: (MonadResource m) => PPixelWand -> Double -> m () setBlack = (liftIO .) . (. realToFrac) . F.pixelSetBlack getBlack :: (MonadResource m) => PPixelWand -> m Double getBlack = (fmap realToFrac) . liftIO . F.pixelGetBlack setCyanQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setCyanQuantum = (liftIO .) . F.pixelSetCyanQuantum getCyanQuantum :: (MonadResource m) => PPixelWand -> m Quantum getCyanQuantum = liftIO . F.pixelGetCyanQuantum setCyan :: (MonadResource m) => PPixelWand -> Double -> m () setCyan = (liftIO .) . (. realToFrac) . F.pixelSetCyan getCyan :: (MonadResource m) => PPixelWand -> m Double getCyan = (fmap realToFrac) . liftIO . F.pixelGetCyan setMagentaQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setMagentaQuantum = (liftIO .) . F.pixelSetMagentaQuantum getMagentaQuantum :: (MonadResource m) => PPixelWand -> m Quantum getMagentaQuantum = liftIO . F.pixelGetMagentaQuantum setMagenta :: (MonadResource m) => PPixelWand -> Double -> m () setMagenta = (liftIO .) . (. realToFrac) . F.pixelSetMagenta getMagenta :: (MonadResource m) => PPixelWand -> m Double getMagenta = (fmap realToFrac) . liftIO . F.pixelGetMagenta setYellowQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setYellowQuantum = (liftIO .) . F.pixelSetYellowQuantum getYellowQuantum :: (MonadResource m) => PPixelWand -> m Quantum getYellowQuantum = liftIO . F.pixelGetYellowQuantum setYellow :: (MonadResource m) => PPixelWand -> Double -> m () setYellow = (liftIO .) . (. realToFrac) . F.pixelSetYellow getYellow :: (MonadResource m) => PPixelWand -> m Double getYellow = (fmap realToFrac) . liftIO . F.pixelGetYellow --- with3 :: (Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()) -> IO (CDouble, CDouble, CDouble) with3 f = alloca (\x -> alloca (\y -> alloca (\z -> do _ <- f x y z x' <- peek x y' <- peek y z' <- peek z return (x',y',z') ))) map3 :: (a -> b) -> (a, a, a) -> (b, b, b) map3 f (a,b,c) = (f a, f b, f c)
flowbox-public/imagemagick
Graphics/ImageMagick/MagickWand/PixelWand.hs
apache-2.0
9,048
0
17
1,773
2,945
1,593
1,352
159
1
module Main where import CLI.Main (runCLI) import Data.Version (showVersion) import Paths_gtfsschedule (version) programHeader :: String programHeader = "gtfsschedule - Be on time for your next public transport service (v. " ++ showVersion version ++ ")" main :: IO () main = runCLI programHeader "Shows schedule of departing vehicles based on static GTFS data."
romanofski/gtfsbrisbane
app/Main.hs
bsd-3-clause
371
0
7
61
73
41
32
9
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} module Test.Foundation.String ( testStringRefs ) where -- import Control.Monad (replicateM) import Foundation import Foundation.Check import Foundation.String import Foundation.Primitive (AsciiString) import Test.Data.List import Test.Checks.Property.Collection --import Test.Foundation.Encoding testStringRefs :: Test testStringRefs = Group "String" [ Group "UTF8" $ [ collectionProperties "String" (Proxy :: Proxy String) arbitrary ] <> testStringCases {- <> [ testGroup "Encoding Sample0" (testEncodings sample0) , testGroup "Encoding Sample1" (testEncodings sample1) , testGroup "Encoding Sample2" (testEncodings sample2) ] -} , Group "ASCII" $ [ collectionProperties "AsciiString" (Proxy :: Proxy AsciiString) arbitrary ] -- <> testAsciiStringCases ] testStringCases :: [Test] testStringCases = [ Group "Validation" [ Property "fromBytes . toBytes == valid" $ \l -> let s = fromList l in (fromBytes UTF8 $ toBytes UTF8 s) === (s, Nothing, mempty) , Property "Streaming" $ \(l, randomInts) -> let wholeS = fromList l wholeBA = toBytes UTF8 wholeS reconstruct (prevBa, errs, acc) ba = let ba' = prevBa `mappend` ba (s, merr, nextBa) = fromBytes UTF8 ba' in (nextBa, merr : errs, s : acc) (remainingBa, allErrs, chunkS) = foldl' reconstruct (mempty, [], []) $ chunks randomInts wholeBA in (catMaybes allErrs === []) `propertyAnd` (remainingBa === mempty) `propertyAnd` (mconcat (reverse chunkS) === wholeS) ] , Group "ModifiedUTF8" [ propertyModifiedUTF8 "The foundation Serie" "基地系列" "基地系列" , propertyModifiedUTF8 "has null bytes" "let's\0 do \0 it" "let's\0 do \0 it" , propertyModifiedUTF8 "Vincent's special" "abc\0안, 蠀\0, ☃" "abc\0안, 蠀\0, ☃" , propertyModifiedUTF8 "Long string" "this is only a simple string but quite longer than the 64 bytes used in the modified UTF8 parser" "this is only a simple string but quite longer than the 64 bytes used in the modified UTF8 parser" ] , Group "CaseMapping" [ Property "upper . upper == upper" $ \l -> let s = fromList l in upper (upper s) === upper s , CheckPlan "a should capitalize to A" $ validate "a" $ upper "a" == "A" , CheckPlan "b should capitalize to B" $ validate "b" $ upper "b" == "B" , CheckPlan "B should not capitalize" $ validate "B" $ upper "B" == "B" , CheckPlan "é should capitalize to É" $ validate "é" $ upper "é" == "É" , CheckPlan "ß should capitalize to SS" $ validate "ß" $ upper "ß" == "SS" , CheckPlan "ffl should capitalize to FFL" $ validate "ffl" $ upper "fflfflfflfflfflfflfflfflfflffl" == "FFLFFLFFLFFLFFLFFLFFLFFLFFLFFL" , CheckPlan "0a should capitalize to 0A" $ validate "0a" $ upper "\0a" == "\0A" , CheckPlan "0a should capitalize to 0A" $ validate "0a" $ upper "a\0a" == "A\0A" , CheckPlan "0a should capitalize to 0A" $ validate "0a" $ upper "\0\0" == "\0\0" , CheckPlan "00 should not capitalize" $ validate "00" $ upper "00" == "00" ] {- , testGroup "replace" [ testCase "indices '' 'bb' should raise an error" $ do res <- try (evaluate $ indices "" "bb") case res of (Left (_ :: SomeException)) -> return () Right _ -> fail "Expecting an error to be thrown, but it did not." , testCase "indices 'aa' 'bb' == []" $ do indices "aa" "bb" @?= [] , testCase "indices 'aa' 'aabbccabbccEEaaaaabb' is correct" $ do indices "aa" "aabbccabbccEEaaaaabb" @?= [Offset 0,Offset 13,Offset 15] , testCase "indices 'aa' 'aaccaadd' is correct" $ do indices "aa" "aaccaadd" @?= [Offset 0,Offset 4] , testCase "replace '' 'bb' 'foo' raises an error" $ do (res :: Either SomeException String) <- try (evaluate $ replace "" "bb" "foo") assertBool "Expecting an error to be thrown, but it did not." (isLeft res) , testCase "replace 'aa' 'bb' '' == ''" $ do replace "aa" "bb" "" @?= "" , testCase "replace 'aa' '' 'aabbcc' == 'aabbcc'" $ do replace "aa" "" "aabbcc" @?= "bbcc" , testCase "replace 'aa' 'bb' 'aa' == 'bb'" $ do replace "aa" "bb" "aa" @?= "bb" , testCase "replace 'aa' 'bb' 'aabb' == 'bbbb'" $ do replace "aa" "bb" "aabb" @?= "bbbb" , testCase "replace 'aa' 'bb' 'aaccaadd' == 'bbccbbdd'" $ do replace "aa" "bb" "aaccaadd" @?= "bbccbbdd" , testCase "replace 'aa' 'LongLong' 'aaccaadd' == 'LongLongccLongLongdd'" $ do replace "aa" "LongLong" "aaccaadd" @?= "LongLongccLongLongdd" , testCase "replace 'aa' 'bb' 'aabbccabbccEEaaaaabb' == 'bbbbccabbccEEbbbbabb'" $ do replace "aa" "bb" "aabbccabbccEEaaaaabb" @?= "bbbbccabbccEEbbbbabb" , testCase "replace 'å' 'ä' 'ååññ' == 'ääññ'" $ do replace "å" "ä" "ååññ" @?= "ääññ" ] , testGroup "Cases" [ testGroup "Invalid-UTF8" [ testCase "ff" $ expectFromBytesErr UTF8 ("", Just InvalidHeader, 0) (fromList [0xff]) , testCase "80" $ expectFromBytesErr UTF8 ("", Just InvalidHeader, 0) (fromList [0x80]) , testCase "E2 82 0C" $ expectFromBytesErr UTF8 ("", Just InvalidContinuation, 0) (fromList [0xE2,0x82,0x0c]) , testCase "30 31 E2 82 0C" $ expectFromBytesErr UTF8 ("01", Just InvalidContinuation, 2) (fromList [0x30,0x31,0xE2,0x82,0x0c]) ] ] , testGroup "Lines" [ testCase "Hello<LF>Foundation" $ (breakLine "Hello\nFoundation" @?= Right ("Hello", "Foundation")) , testCase "Hello<CRLF>Foundation" $ (breakLine "Hello\r\nFoundation" @?= Right ("Hello", "Foundation")) , testCase "Hello<LF>Foundation" $ (breakLine (drop 5 "Hello\nFoundation\nSomething") @?= Right ("", "Foundation\nSomething")) , testCase "Hello<CR>" $ (breakLine "Hello\r" @?= Left True) , testCase "CR" $ (breakLine "\r" @?= Left True) , testCase "LF" $ (breakLine "\n" @?= Right ("", "")) , testCase "empty" $ (breakLine "" @?= Left False) ] -} ] {- testAsciiStringCases :: [Test] testAsciiStringCases = [ Group "Validation-ASCII7" [ Property "fromBytes . toBytes == valid" $ \l -> let s = fromList . fromLStringASCII $ l in (fromBytes ASCII7 $ toBytes ASCII7 s) === (s, Nothing, mempty) , Property "Streaming" $ \(l, randomInts) -> let wholeS = fromList . fromLStringASCII $ l wholeBA = toBytes ASCII7 wholeS reconstruct (prevBa, errs, acc) ba = let ba' = prevBa `mappend` ba (s, merr, nextBa) = fromBytes ASCII7 ba' in (nextBa, merr : errs, s : acc) (remainingBa, allErrs, chunkS) = foldl' reconstruct (mempty, [], []) $ chunks randomInts wholeBA in (catMaybes allErrs === []) .&&. (remainingBa === mempty) .&&. (mconcat (reverse chunkS) === wholeS) ] , Group "Cases" [ Group "Invalid-ASCII7" [ testCase "ff" $ expectFromBytesErr ASCII7 ("", Just BuildingFailure, 0) (fromList [0xff]) ] ] ] expectFromBytesErr :: Encoding -> ([Char], Maybe ValidationFailure, CountOf Word8) -> UArray Word8 -> IO () expectFromBytesErr enc (expectedString,expectedErr,positionErr) ba = do let x = fromBytes enc ba (s', merr, ba') = x assertEqual "error" expectedErr merr assertEqual "remaining" (drop positionErr ba) ba' assertEqual "string" expectedString (toList s') -} propertyModifiedUTF8 :: String -> [Char] -> String -> Test propertyModifiedUTF8 name chars str = Property name $ chars === toList str chunks :: Sequential c => RandomList -> c -> [c] chunks (RandomList randomInts) = loop (randomInts <> [1..]) where loop rx c | null c = [] | otherwise = case rx of r:rs -> let (c1,c2) = splitAt (CountOf r) c in c1 : loop rs c2 [] -> loop randomInts c
vincenthz/hs-foundation
foundation/tests/Test/Foundation/String.hs
bsd-3-clause
8,790
0
18
2,644
955
489
466
69
2
{-# LANGUAGE OverloadedStrings #-} module Web.Server ( runServer , formalizerApp -- Exposed for testing. ) where import Network.Wai.Middleware.RequestLogger import Network.Wai.Middleware.Static import Web.Actions as Action import Web.Spock.Safe import Web.Types -- Run the spock app. runServer :: AppConfig -> IO () runServer conf = let port = cPort conf state = AppState (cPath conf) (cSMTP conf) spockCfg = defaultSpockCfg Nothing PCNoDatabase state in runSpock port $ spock spockCfg formalizerApp -- Path for static files like .js and .css. staticPath :: String staticPath = "web/static" -- Middlewares for application. appMiddleware :: FormalizeApp () appMiddleware = do middleware logStdout middleware . staticPolicy $ noDots >-> addBase staticPath -- Routes for application. appRoutes :: FormalizeApp () appRoutes = do get root Action.home post "/submit" Action.submit hookAny GET Action.notFound -- Join middlewares and routes to spock app. formalizerApp :: FormalizeApp () formalizerApp = appMiddleware >> appRoutes
Lepovirta/Crystallize
app/Web/Server.hs
bsd-3-clause
1,172
0
11
288
248
131
117
28
1
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1998 This module contains definitions for the IdInfo for things that have a standard form, namely: - data constructors - record selectors - method and superclass selectors - primitive operations -} {-# LANGUAGE CPP #-} module MkId ( mkDictFunId, mkDictFunTy, mkDictSelId, mkDictSelRhs, mkPrimOpId, mkFCallId, wrapNewTypeBody, unwrapNewTypeBody, wrapFamInstBody, unwrapFamInstScrut, wrapTypeUnbranchedFamInstBody, unwrapTypeUnbranchedFamInstScrut, DataConBoxer(..), mkDataConRep, mkDataConWorkId, -- And some particular Ids; see below for why they are wired in wiredInIds, ghcPrimIds, unsafeCoerceName, unsafeCoerceId, realWorldPrimId, voidPrimId, voidArgId, nullAddrId, seqId, lazyId, lazyIdKey, runRWId, coercionTokenId, magicDictId, coerceId, proxyHashId, -- Re-export error Ids module PrelRules ) where #include "HsVersions.h" import Rules import TysPrim import TysWiredIn import PrelRules import Type import FamInstEnv import Coercion import TcType import MkCore import CoreUtils ( exprType, mkCast ) import CoreUnfold import Literal import TyCon import CoAxiom import Class import NameSet import VarSet import Name import PrimOp import ForeignCall import DataCon import Id import IdInfo import Demand import CoreSyn import Unique import UniqSupply import PrelNames import BasicTypes hiding ( SuccessFlag(..) ) import Util import Pair import DynFlags import Outputable import FastString import ListSetOps import qualified GHC.LanguageExtensions as LangExt import Data.Maybe ( maybeToList ) {- ************************************************************************ * * \subsection{Wired in Ids} * * ************************************************************************ Note [Wired-in Ids] ~~~~~~~~~~~~~~~~~~~ There are several reasons why an Id might appear in the wiredInIds: (1) The ghcPrimIds are wired in because they can't be defined in Haskell at all, although the can be defined in Core. They have compulsory unfoldings, so they are always inlined and they have no definition site. Their home module is GHC.Prim, so they also have a description in primops.txt.pp, where they are called 'pseudoops'. (2) The 'error' function, eRROR_ID, is wired in because we don't yet have a way to express in an interface file that the result type variable is 'open'; that is can be unified with an unboxed type [The interface file format now carry such information, but there's no way yet of expressing at the definition site for these error-reporting functions that they have an 'open' result type. -- sof 1/99] (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because the desugarer generates code that mentions them directly, and (b) for the same reason as eRROR_ID (4) lazyId is wired in because the wired-in version overrides the strictness of the version defined in GHC.Base In cases (2-4), the function has a definition in a library module, and can be called; but the wired-in version means that the details are never read from that module's interface file; instead, the full definition is right here. -} wiredInIds :: [Id] wiredInIds = [lazyId, dollarId, oneShotId, runRWId] ++ errorIds -- Defined in MkCore ++ ghcPrimIds -- These Ids are exported from GHC.Prim ghcPrimIds :: [Id] ghcPrimIds = [ -- These can't be defined in Haskell, but they have -- perfectly reasonable unfoldings in Core realWorldPrimId, voidPrimId, unsafeCoerceId, nullAddrId, seqId, magicDictId, coerceId, proxyHashId ] {- ************************************************************************ * * \subsection{Data constructors} * * ************************************************************************ The wrapper for a constructor is an ordinary top-level binding that evaluates any strict args, unboxes any args that are going to be flattened, and calls the worker. We're going to build a constructor that looks like: data (Data a, C b) => T a b = T1 !a !Int b T1 = /\ a b -> \d1::Data a, d2::C b -> \p q r -> case p of { p -> case q of { q -> Con T1 [a,b] [p,q,r]}} Notice that * d2 is thrown away --- a context in a data decl is used to make sure one *could* construct dictionaries at the site the constructor is used, but the dictionary isn't actually used. * We have to check that we can construct Data dictionaries for the types a and Int. Once we've done that we can throw d1 away too. * We use (case p of q -> ...) to evaluate p, rather than "seq" because all that matters is that the arguments are evaluated. "seq" is very careful to preserve evaluation order, which we don't need to be here. You might think that we could simply give constructors some strictness info, like PrimOps, and let CoreToStg do the let-to-case transformation. But we don't do that because in the case of primops and functions strictness is a *property* not a *requirement*. In the case of constructors we need to do something active to evaluate the argument. Making an explicit case expression allows the simplifier to eliminate it in the (common) case where the constructor arg is already evaluated. Note [Wrappers for data instance tycons] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the case of data instances, the wrapper also applies the coercion turning the representation type into the family instance type to cast the result of the wrapper. For example, consider the declarations data family Map k :: * -> * data instance Map (a, b) v = MapPair (Map a (Pair b v)) The tycon to which the datacon MapPair belongs gets a unique internal name of the form :R123Map, and we call it the representation tycon. In contrast, Map is the family tycon (accessible via tyConFamInst_maybe). A coercion allows you to move between representation and family type. It is accessible from :R123Map via tyConFamilyCoercion_maybe and has kind Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v} The wrapper and worker of MapPair get the types -- Wrapper $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v) -- Worker MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v This coercion is conditionally applied by wrapFamInstBody. It's a bit more complicated if the data instance is a GADT as well! data instance T [a] where T1 :: forall b. b -> T [Maybe b] Hence we translate to -- Wrapper $WT1 :: forall b. b -> T [Maybe b] $WT1 b v = T1 (Maybe b) b (Maybe b) v `cast` sym (Co7T (Maybe b)) -- Worker T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c -- Coercion from family type to representation type Co7T a :: T [a] ~ :R7T a Note [Newtype datacons] ~~~~~~~~~~~~~~~~~~~~~~~ The "data constructor" for a newtype should always be vanilla. At one point this wasn't true, because the newtype arising from class C a => D a looked like newtype T:D a = D:D (C a) so the data constructor for T:C had a single argument, namely the predicate (C a). But now we treat that as an ordinary argument, not part of the theta-type, so all is well. ************************************************************************ * * \subsection{Dictionary selectors} * * ************************************************************************ Selecting a field for a dictionary. If there is just one field, then there's nothing to do. Dictionary selectors may get nested forall-types. Thus: class Foo a where op :: forall b. Ord b => a -> b -> b Then the top-level type for op is op :: forall a. Foo a => forall b. Ord b => a -> b -> b -} mkDictSelId :: Name -- Name of one of the *value* selectors -- (dictionary superclass or method) -> Class -> Id mkDictSelId name clas = mkGlobalId (ClassOpId clas) name sel_ty info where tycon = classTyCon clas sel_names = map idName (classAllSelIds clas) new_tycon = isNewTyCon tycon [data_con] = tyConDataCons tycon tyvars = dataConUnivTyVarBinders data_con n_ty_args = length tyvars arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses val_index = assoc "MkId.mkDictSelId" (sel_names `zip` [0..]) name sel_ty = mkForAllTys tyvars $ mkFunTy (mkClassPred clas (mkTyVarTys (binderVars tyvars))) $ getNth arg_tys val_index base_info = noCafIdInfo `setArityInfo` 1 `setStrictnessInfo` strict_sig info | new_tycon = base_info `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkInlineUnfolding (Just 1) (mkDictSelRhs clas val_index) -- See Note [Single-method classes] in TcInstDcls -- for why alwaysInlinePragma | otherwise = base_info `setRuleInfo` mkRuleInfo [rule] -- Add a magic BuiltinRule, but no unfolding -- so that the rule is always available to fire. -- See Note [ClassOp/DFun selection] in TcInstDcls -- This is the built-in rule that goes -- op (dfT d1 d2) ---> opT d1 d2 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS` occNameFS (getOccName name) , ru_fn = name , ru_nargs = n_ty_args + 1 , ru_try = dictSelRule val_index n_ty_args } -- The strictness signature is of the form U(AAAVAAAA) -> T -- where the V depends on which item we are selecting -- It's worth giving one, so that absence info etc is generated -- even if the selector isn't inlined strict_sig = mkClosedStrictSig [arg_dmd] topRes arg_dmd | new_tycon = evalDmd | otherwise = mkManyUsedDmd $ mkProdDmd [ if name == sel_name then evalDmd else absDmd | sel_name <- sel_names ] mkDictSelRhs :: Class -> Int -- 0-indexed selector among (superclasses ++ methods) -> CoreExpr mkDictSelRhs clas val_index = mkLams tyvars (Lam dict_id rhs_body) where tycon = classTyCon clas new_tycon = isNewTyCon tycon [data_con] = tyConDataCons tycon tyvars = dataConUnivTyVars data_con arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses the_arg_id = getNth arg_ids val_index pred = mkClassPred clas (mkTyVarTys tyvars) dict_id = mkTemplateLocal 1 pred arg_ids = mkTemplateLocalsNum 2 arg_tys rhs_body | new_tycon = unwrapNewTypeBody tycon (mkTyVarTys tyvars) (Var dict_id) | otherwise = Case (Var dict_id) dict_id (idType the_arg_id) [(DataAlt data_con, arg_ids, varToCoreExpr the_arg_id)] -- varToCoreExpr needed for equality superclass selectors -- sel a b d = case x of { MkC _ (g:a~b) _ -> CO g } dictSelRule :: Int -> Arity -> RuleFun -- Tries to persuade the argument to look like a constructor -- application, using exprIsConApp_maybe, and then selects -- from it -- sel_i t1..tk (D t1..tk op1 ... opm) = opi -- dictSelRule val_index n_ty_args _ id_unf _ args | (dict_arg : _) <- drop n_ty_args args , Just (_, _, con_args) <- exprIsConApp_maybe id_unf dict_arg = Just (getNth con_args val_index) | otherwise = Nothing {- ************************************************************************ * * Data constructors * * ************************************************************************ -} mkDataConWorkId :: Name -> DataCon -> Id mkDataConWorkId wkr_name data_con | isNewTyCon tycon = mkGlobalId (DataConWrapId data_con) wkr_name nt_wrap_ty nt_work_info | otherwise = mkGlobalId (DataConWorkId data_con) wkr_name alg_wkr_ty wkr_info where tycon = dataConTyCon data_con ----------- Workers for data types -------------- alg_wkr_ty = dataConRepType data_con wkr_arity = dataConRepArity data_con wkr_info = noCafIdInfo `setArityInfo` wkr_arity `setStrictnessInfo` wkr_sig `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated, -- even if arity = 0 wkr_sig = mkClosedStrictSig (replicate wkr_arity topDmd) (dataConCPR data_con) -- Note [Data-con worker strictness] -- Notice that we do *not* say the worker is strict -- even if the data constructor is declared strict -- e.g. data T = MkT !(Int,Int) -- Why? Because the *wrapper* is strict (and its unfolding has case -- expressions that do the evals) but the *worker* itself is not. -- If we pretend it is strict then when we see -- case x of y -> $wMkT y -- the simplifier thinks that y is "sure to be evaluated" (because -- $wMkT is strict) and drops the case. No, $wMkT is not strict. -- -- When the simplifier sees a pattern -- case e of MkT x -> ... -- it uses the dataConRepStrictness of MkT to mark x as evaluated; -- but that's fine... dataConRepStrictness comes from the data con -- not from the worker Id. ----------- Workers for newtypes -------------- (nt_tvs, _, nt_arg_tys, _) = dataConSig data_con res_ty_args = mkTyVarTys nt_tvs nt_wrap_ty = dataConUserType data_con nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo `setArityInfo` 1 -- Arity 1 `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` newtype_unf id_arg1 = mkTemplateLocal 1 (head nt_arg_tys) newtype_unf = ASSERT2( isVanillaDataCon data_con && isSingleton nt_arg_tys, ppr data_con ) -- Note [Newtype datacons] mkCompulsoryUnfolding $ mkLams nt_tvs $ Lam id_arg1 $ wrapNewTypeBody tycon res_ty_args (Var id_arg1) dataConCPR :: DataCon -> DmdResult dataConCPR con | isDataTyCon tycon -- Real data types only; that is, -- not unboxed tuples or newtypes , null (dataConExTyVars con) -- No existentials , wkr_arity > 0 , wkr_arity <= mAX_CPR_SIZE = if is_prod then vanillaCprProdRes (dataConRepArity con) else cprSumRes (dataConTag con) | otherwise = topRes where is_prod = isProductTyCon tycon tycon = dataConTyCon con wkr_arity = dataConRepArity con mAX_CPR_SIZE :: Arity mAX_CPR_SIZE = 10 -- We do not treat very big tuples as CPR-ish: -- a) for a start we get into trouble because there aren't -- "enough" unboxed tuple types (a tiresome restriction, -- but hard to fix), -- b) more importantly, big unboxed tuples get returned mainly -- on the stack, and are often then allocated in the heap -- by the caller. So doing CPR for them may in fact make -- things worse. {- ------------------------------------------------- -- Data constructor representation -- -- This is where we decide how to wrap/unwrap the -- constructor fields -- -------------------------------------------------- -} type Unboxer = Var -> UniqSM ([Var], CoreExpr -> CoreExpr) -- Unbox: bind rep vars by decomposing src var data Boxer = UnitBox | Boxer (TCvSubst -> UniqSM ([Var], CoreExpr)) -- Box: build src arg using these rep vars newtype DataConBoxer = DCB ([Type] -> [Var] -> UniqSM ([Var], [CoreBind])) -- Bind these src-level vars, returning the -- rep-level vars to bind in the pattern mkDataConRep :: DynFlags -> FamInstEnvs -> Name -> Maybe [HsImplBang] -- See Note [Bangs on imported data constructors] -> DataCon -> UniqSM DataConRep mkDataConRep dflags fam_envs wrap_name mb_bangs data_con | not wrapper_reqd = return NoDataConRep | otherwise = do { wrap_args <- mapM newLocal wrap_arg_tys ; wrap_body <- mk_rep_app (wrap_args `zip` dropList eq_spec unboxers) initial_wrap_app ; let wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty wrap_info wrap_info = noCafIdInfo `setArityInfo` wrap_arity -- It's important to specify the arity, so that partial -- applications are treated as values `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` wrap_unf `setStrictnessInfo` wrap_sig -- We need to get the CAF info right here because TidyPgm -- does not tidy the IdInfo of implicit bindings (like the wrapper) -- so it not make sure that the CAF info is sane wrap_sig = mkClosedStrictSig wrap_arg_dmds (dataConCPR data_con) wrap_arg_dmds = map mk_dmd arg_ibangs mk_dmd str | isBanged str = evalDmd | otherwise = topDmd -- The Cpr info can be important inside INLINE rhss, where the -- wrapper constructor isn't inlined. -- And the argument strictness can be important too; we -- may not inline a constructor when it is partially applied. -- For example: -- data W = C !Int !Int !Int -- ...(let w = C x in ...(w p q)...)... -- we want to see that w is strict in its two arguments wrap_unf = mkInlineUnfolding (Just wrap_arity) wrap_rhs wrap_tvs = (univ_tvs `minusList` map eqSpecTyVar eq_spec) ++ ex_tvs wrap_rhs = mkLams wrap_tvs $ mkLams wrap_args $ wrapFamInstBody tycon res_ty_args $ wrap_body ; return (DCR { dcr_wrap_id = wrap_id , dcr_boxer = mk_boxer boxers , dcr_arg_tys = rep_tys , dcr_stricts = rep_strs , dcr_bangs = arg_ibangs }) } where (univ_tvs, ex_tvs, eq_spec, theta, orig_arg_tys, _orig_res_ty) = dataConFullSig data_con res_ty_args = substTyVars (mkTvSubstPrs (map eqSpecPair eq_spec)) univ_tvs tycon = dataConTyCon data_con -- The representation TyCon (not family) wrap_ty = dataConUserType data_con ev_tys = eqSpecPreds eq_spec ++ theta all_arg_tys = ev_tys ++ orig_arg_tys ev_ibangs = map (const HsLazy) ev_tys orig_bangs = dataConSrcBangs data_con wrap_arg_tys = theta ++ orig_arg_tys wrap_arity = length wrap_arg_tys -- The wrap_args are the arguments *other than* the eq_spec -- Because we are going to apply the eq_spec args manually in the -- wrapper arg_ibangs = case mb_bangs of Nothing -> zipWith (dataConSrcToImplBang dflags fam_envs) orig_arg_tys orig_bangs Just bangs -> bangs (rep_tys_w_strs, wrappers) = unzip (zipWith dataConArgRep all_arg_tys (ev_ibangs ++ arg_ibangs)) (unboxers, boxers) = unzip wrappers (rep_tys, rep_strs) = unzip (concat rep_tys_w_strs) wrapper_reqd = not (isNewTyCon tycon) -- Newtypes have only a worker && (any isBanged (ev_ibangs ++ arg_ibangs) -- Some forcing/unboxing (includes eq_spec) || isFamInstTyCon tycon -- Cast result || (not $ null eq_spec)) -- GADT initial_wrap_app = Var (dataConWorkId data_con) `mkTyApps` res_ty_args `mkVarApps` ex_tvs `mkCoApps` map (mkReflCo Nominal . eqSpecType) eq_spec mk_boxer :: [Boxer] -> DataConBoxer mk_boxer boxers = DCB (\ ty_args src_vars -> do { let (ex_vars, term_vars) = splitAtList ex_tvs src_vars subst1 = zipTvSubst univ_tvs ty_args subst2 = extendTvSubstList subst1 ex_tvs (mkTyVarTys ex_vars) ; (rep_ids, binds) <- go subst2 boxers term_vars ; return (ex_vars ++ rep_ids, binds) } ) go _ [] src_vars = ASSERT2( null src_vars, ppr data_con ) return ([], []) go subst (UnitBox : boxers) (src_var : src_vars) = do { (rep_ids2, binds) <- go subst boxers src_vars ; return (src_var : rep_ids2, binds) } go subst (Boxer boxer : boxers) (src_var : src_vars) = do { (rep_ids1, arg) <- boxer subst ; (rep_ids2, binds) <- go subst boxers src_vars ; return (rep_ids1 ++ rep_ids2, NonRec src_var arg : binds) } go _ (_:_) [] = pprPanic "mk_boxer" (ppr data_con) mk_rep_app :: [(Id,Unboxer)] -> CoreExpr -> UniqSM CoreExpr mk_rep_app [] con_app = return con_app mk_rep_app ((wrap_arg, unboxer) : prs) con_app = do { (rep_ids, unbox_fn) <- unboxer wrap_arg ; expr <- mk_rep_app prs (mkVarApps con_app rep_ids) ; return (unbox_fn expr) } {- Note [Bangs on imported data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We pass Maybe [HsImplBang] to mkDataConRep to make use of HsImplBangs from imported modules. - Nothing <=> use HsSrcBangs - Just bangs <=> use HsImplBangs For imported types we can't work it all out from the HsSrcBangs, because we want to be very sure to follow what the original module (where the data type was declared) decided, and that depends on what flags were enabled when it was compiled. So we record the decisions in the interface file. The HsImplBangs passed are in 1-1 correspondence with the dataConOrigArgTys of the DataCon. -} ------------------------- newLocal :: Type -> UniqSM Var newLocal ty = do { uniq <- getUniqueM ; return (mkSysLocalOrCoVar (fsLit "dt") uniq ty) } -- | Unpack/Strictness decisions from source module dataConSrcToImplBang :: DynFlags -> FamInstEnvs -> Type -> HsSrcBang -> HsImplBang dataConSrcToImplBang dflags fam_envs arg_ty (HsSrcBang ann unpk NoSrcStrict) | xopt LangExt.StrictData dflags -- StrictData => strict field = dataConSrcToImplBang dflags fam_envs arg_ty (HsSrcBang ann unpk SrcStrict) | otherwise -- no StrictData => lazy field = HsLazy dataConSrcToImplBang _ _ _ (HsSrcBang _ _ SrcLazy) = HsLazy dataConSrcToImplBang dflags fam_envs arg_ty (HsSrcBang _ unpk_prag SrcStrict) | not (gopt Opt_OmitInterfacePragmas dflags) -- Don't unpack if -fomit-iface-pragmas -- Don't unpack if we aren't optimising; rather arbitrarily, -- we use -fomit-iface-pragmas as the indication , let mb_co = topNormaliseType_maybe fam_envs arg_ty -- Unwrap type families and newtypes arg_ty' = case mb_co of { Just (_,ty) -> ty; Nothing -> arg_ty } , isUnpackableType dflags fam_envs arg_ty' , (rep_tys, _) <- dataConArgUnpack arg_ty' , case unpk_prag of NoSrcUnpack -> gopt Opt_UnboxStrictFields dflags || (gopt Opt_UnboxSmallStrictFields dflags && length rep_tys <= 1) -- See Note [Unpack one-wide fields] srcUnpack -> isSrcUnpacked srcUnpack = case mb_co of Nothing -> HsUnpack Nothing Just (co,_) -> HsUnpack (Just co) | otherwise -- Record the strict-but-no-unpack decision = HsStrict -- | Wrappers/Workers and representation following Unpack/Strictness -- decisions dataConArgRep :: Type -> HsImplBang -> ([(Type,StrictnessMark)] -- Rep types ,(Unboxer,Boxer)) dataConArgRep arg_ty HsLazy = ([(arg_ty, NotMarkedStrict)], (unitUnboxer, unitBoxer)) dataConArgRep arg_ty HsStrict = ([(arg_ty, MarkedStrict)], (seqUnboxer, unitBoxer)) dataConArgRep arg_ty (HsUnpack Nothing) | (rep_tys, wrappers) <- dataConArgUnpack arg_ty = (rep_tys, wrappers) dataConArgRep _ (HsUnpack (Just co)) | let co_rep_ty = pSnd (coercionKind co) , (rep_tys, wrappers) <- dataConArgUnpack co_rep_ty = (rep_tys, wrapCo co co_rep_ty wrappers) ------------------------- wrapCo :: Coercion -> Type -> (Unboxer, Boxer) -> (Unboxer, Boxer) wrapCo co rep_ty (unbox_rep, box_rep) -- co :: arg_ty ~ rep_ty = (unboxer, boxer) where unboxer arg_id = do { rep_id <- newLocal rep_ty ; (rep_ids, rep_fn) <- unbox_rep rep_id ; let co_bind = NonRec rep_id (Var arg_id `Cast` co) ; return (rep_ids, Let co_bind . rep_fn) } boxer = Boxer $ \ subst -> do { (rep_ids, rep_expr) <- case box_rep of UnitBox -> do { rep_id <- newLocal (TcType.substTy subst rep_ty) ; return ([rep_id], Var rep_id) } Boxer boxer -> boxer subst ; let sco = substCoUnchecked subst co ; return (rep_ids, rep_expr `Cast` mkSymCo sco) } ------------------------ seqUnboxer :: Unboxer seqUnboxer v = return ([v], \e -> Case (Var v) v (exprType e) [(DEFAULT, [], e)]) unitUnboxer :: Unboxer unitUnboxer v = return ([v], \e -> e) unitBoxer :: Boxer unitBoxer = UnitBox ------------------------- dataConArgUnpack :: Type -> ( [(Type, StrictnessMark)] -- Rep types , (Unboxer, Boxer) ) dataConArgUnpack arg_ty | Just (tc, tc_args) <- splitTyConApp_maybe arg_ty , Just con <- tyConSingleAlgDataCon_maybe tc -- NB: check for an *algebraic* data type -- A recursive newtype might mean that -- 'arg_ty' is a newtype , let rep_tys = dataConInstArgTys con tc_args = ASSERT( isVanillaDataCon con ) ( rep_tys `zip` dataConRepStrictness con ,( \ arg_id -> do { rep_ids <- mapM newLocal rep_tys ; let unbox_fn body = Case (Var arg_id) arg_id (exprType body) [(DataAlt con, rep_ids, body)] ; return (rep_ids, unbox_fn) } , Boxer $ \ subst -> do { rep_ids <- mapM (newLocal . TcType.substTyUnchecked subst) rep_tys ; return (rep_ids, Var (dataConWorkId con) `mkTyApps` (substTysUnchecked subst tc_args) `mkVarApps` rep_ids ) } ) ) | otherwise = pprPanic "dataConArgUnpack" (ppr arg_ty) -- An interface file specified Unpacked, but we couldn't unpack it isUnpackableType :: DynFlags -> FamInstEnvs -> Type -> Bool -- True if we can unpack the UNPACK the argument type -- See Note [Recursive unboxing] -- We look "deeply" inside rather than relying on the DataCons -- we encounter on the way, because otherwise we might well -- end up relying on ourselves! isUnpackableType dflags fam_envs ty | Just (tc, _) <- splitTyConApp_maybe ty , Just con <- tyConSingleAlgDataCon_maybe tc , isVanillaDataCon con = ok_con_args (unitNameSet (getName tc)) con | otherwise = False where ok_arg tcs (ty, bang) = not (attempt_unpack bang) || ok_ty tcs norm_ty where norm_ty = topNormaliseType fam_envs ty ok_ty tcs ty | Just (tc, _) <- splitTyConApp_maybe ty , let tc_name = getName tc = not (tc_name `elemNameSet` tcs) && case tyConSingleAlgDataCon_maybe tc of Just con | isVanillaDataCon con -> ok_con_args (tcs `extendNameSet` getName tc) con _ -> True | otherwise = True ok_con_args tcs con = all (ok_arg tcs) (dataConOrigArgTys con `zip` dataConSrcBangs con) -- NB: dataConSrcBangs gives the *user* request; -- We'd get a black hole if we used dataConImplBangs attempt_unpack (HsSrcBang _ SrcUnpack NoSrcStrict) = xopt LangExt.StrictData dflags attempt_unpack (HsSrcBang _ SrcUnpack SrcStrict) = True attempt_unpack (HsSrcBang _ NoSrcUnpack SrcStrict) = True -- Be conservative attempt_unpack (HsSrcBang _ NoSrcUnpack NoSrcStrict) = xopt LangExt.StrictData dflags -- Be conservative attempt_unpack _ = False {- Note [Unpack one-wide fields] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The flag UnboxSmallStrictFields ensures that any field that can (safely) be unboxed to a word-sized unboxed field, should be so unboxed. For example: data A = A Int# newtype B = B A data C = C !B data D = D !C data E = E !() data F = F !D data G = G !F !F All of these should have an Int# as their representation, except G which should have two Int#s. However data T = T !(S Int) data S = S !a Here we can represent T with an Int#. Note [Recursive unboxing] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data R = MkR {-# UNPACK #-} !S Int data S = MkS {-# UNPACK #-} !Int The representation arguments of MkR are the *representation* arguments of S (plus Int); the rep args of MkS are Int#. This is all fine. But be careful not to try to unbox this! data T = MkT {-# UNPACK #-} !T Int Because then we'd get an infinite number of arguments. Here is a more complicated case: data S = MkS {-# UNPACK #-} !T Int data T = MkT {-# UNPACK #-} !S Int Each of S and T must decide independently whether to unpack and they had better not both say yes. So they must both say no. Also behave conservatively when there is no UNPACK pragma data T = MkS !T Int with -funbox-strict-fields or -funbox-small-strict-fields we need to behave as if there was an UNPACK pragma there. But it's the *argument* type that matters. This is fine: data S = MkS S !Int because Int is non-recursive. ************************************************************************ * * Wrapping and unwrapping newtypes and type families * * ************************************************************************ -} wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr -- The wrapper for the data constructor for a newtype looks like this: -- newtype T a = MkT (a,Int) -- MkT :: forall a. (a,Int) -> T a -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a) -- where CoT is the coercion TyCon associated with the newtype -- -- The call (wrapNewTypeBody T [a] e) returns the -- body of the wrapper, namely -- e `cast` (CoT [a]) -- -- If a coercion constructor is provided in the newtype, then we use -- it, otherwise the wrap/unwrap are both no-ops -- -- If the we are dealing with a newtype *instance*, we have a second coercion -- identifying the family instance with the constructor of the newtype -- instance. This coercion is applied in any case (ie, composed with the -- coercion constructor of the newtype or applied by itself). wrapNewTypeBody tycon args result_expr = ASSERT( isNewTyCon tycon ) wrapFamInstBody tycon args $ mkCast result_expr (mkSymCo co) where co = mkUnbranchedAxInstCo Representational (newTyConCo tycon) args [] -- When unwrapping, we do *not* apply any family coercion, because this will -- be done via a CoPat by the type checker. We have to do it this way as -- computing the right type arguments for the coercion requires more than just -- a spliting operation (cf, TcPat.tcConPat). unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr unwrapNewTypeBody tycon args result_expr = ASSERT( isNewTyCon tycon ) mkCast result_expr (mkUnbranchedAxInstCo Representational (newTyConCo tycon) args []) -- If the type constructor is a representation type of a data instance, wrap -- the expression into a cast adjusting the expression type, which is an -- instance of the representation type, to the corresponding instance of the -- family instance type. -- See Note [Wrappers for data instance tycons] wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr wrapFamInstBody tycon args body | Just co_con <- tyConFamilyCoercion_maybe tycon = mkCast body (mkSymCo (mkUnbranchedAxInstCo Representational co_con args [])) | otherwise = body -- Same as `wrapFamInstBody`, but for type family instances, which are -- represented by a `CoAxiom`, and not a `TyCon` wrapTypeFamInstBody :: CoAxiom br -> Int -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr wrapTypeFamInstBody axiom ind args cos body = mkCast body (mkSymCo (mkAxInstCo Representational axiom ind args cos)) wrapTypeUnbranchedFamInstBody :: CoAxiom Unbranched -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr wrapTypeUnbranchedFamInstBody axiom = wrapTypeFamInstBody axiom 0 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr unwrapFamInstScrut tycon args scrut | Just co_con <- tyConFamilyCoercion_maybe tycon = mkCast scrut (mkUnbranchedAxInstCo Representational co_con args []) -- data instances only | otherwise = scrut unwrapTypeFamInstScrut :: CoAxiom br -> Int -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr unwrapTypeFamInstScrut axiom ind args cos scrut = mkCast scrut (mkAxInstCo Representational axiom ind args cos) unwrapTypeUnbranchedFamInstScrut :: CoAxiom Unbranched -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr unwrapTypeUnbranchedFamInstScrut axiom = unwrapTypeFamInstScrut axiom 0 {- ************************************************************************ * * \subsection{Primitive operations} * * ************************************************************************ -} mkPrimOpId :: PrimOp -> Id mkPrimOpId prim_op = id where (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op ty = mkSpecForAllTys tyvars (mkFunTys arg_tys res_ty) name = mkWiredInName gHC_PRIM (primOpOcc prim_op) (mkPrimOpIdUnique (primOpTag prim_op)) (AnId id) UserSyntax id = mkGlobalId (PrimOpId prim_op) name ty info info = noCafIdInfo `setRuleInfo` mkRuleInfo (maybeToList $ primOpRules name prim_op) `setArityInfo` arity `setStrictnessInfo` strict_sig `setInlinePragInfo` neverInlinePragma -- We give PrimOps a NOINLINE pragma so that we don't -- get silly warnings from Desugar.dsRule (the inline_shadows_rule -- test) about a RULE conflicting with a possible inlining -- cf Trac #7287 -- For each ccall we manufacture a separate CCallOpId, giving it -- a fresh unique, a type that is correct for this particular ccall, -- and a CCall structure that gives the correct details about calling -- convention etc. -- -- The *name* of this Id is a local name whose OccName gives the full -- details of the ccall, type and all. This means that the interface -- file reader can reconstruct a suitable Id mkFCallId :: DynFlags -> Unique -> ForeignCall -> Type -> Id mkFCallId dflags uniq fcall ty = ASSERT( isEmptyVarSet (tyCoVarsOfType ty) ) -- A CCallOpId should have no free type variables; -- when doing substitutions won't substitute over it mkGlobalId (FCallId fcall) name ty info where occ_str = showSDoc dflags (braces (ppr fcall <+> ppr ty)) -- The "occurrence name" of a ccall is the full info about the -- ccall; it is encoded, but may have embedded spaces etc! name = mkFCallName uniq occ_str info = noCafIdInfo `setArityInfo` arity `setStrictnessInfo` strict_sig (bndrs, _) = tcSplitPiTys ty arity = count isAnonTyBinder bndrs strict_sig = mkClosedStrictSig (replicate arity topDmd) topRes -- the call does not claim to be strict in its arguments, since they -- may be lifted (foreign import prim) and the called code doesn't -- necessarily force them. See Trac #11076. {- ************************************************************************ * * \subsection{DictFuns and default methods} * * ************************************************************************ Note [Dict funs and default methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dict funs and default methods are *not* ImplicitIds. Their definition involves user-written code, so we can't figure out their strictness etc based on fixed info, as we can for constructors and record selectors (say). NB: See also Note [Exported LocalIds] in Id -} mkDictFunId :: Name -- Name to use for the dict fun; -> [TyVar] -> ThetaType -> Class -> [Type] -> Id -- Implements the DFun Superclass Invariant (see TcInstDcls) -- See Note [Dict funs and default methods] mkDictFunId dfun_name tvs theta clas tys = mkExportedLocalId (DFunId is_nt) dfun_name dfun_ty where is_nt = isNewTyCon (classTyCon clas) dfun_ty = mkDictFunTy tvs theta clas tys mkDictFunTy :: [TyVar] -> ThetaType -> Class -> [Type] -> Type mkDictFunTy tvs theta clas tys = mkSpecSigmaTy tvs theta (mkClassPred clas tys) {- ************************************************************************ * * \subsection{Un-definable} * * ************************************************************************ These Ids can't be defined in Haskell. They could be defined in unfoldings in the wired-in GHC.Prim interface file, but we'd have to ensure that they were definitely, definitely inlined, because there is no curried identifier for them. That's what mkCompulsoryUnfolding does. If we had a way to get a compulsory unfolding from an interface file, we could do that, but we don't right now. unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that just gets expanded into a type coercion wherever it occurs. Hence we add it as a built-in Id with an unfolding here. The type variables we use here are "open" type variables: this means they can unify with both unlifted and lifted types. Hence we provide another gun with which to shoot yourself in the foot. -} lazyIdName, unsafeCoerceName, nullAddrName, seqName, realWorldName, voidPrimIdName, coercionTokenName, magicDictName, coerceName, proxyName, dollarName, oneShotName, runRWName :: Name unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId voidPrimIdName = mkWiredInIdName gHC_PRIM (fsLit "void#") voidPrimIdKey voidPrimId lazyIdName = mkWiredInIdName gHC_MAGIC (fsLit "lazy") lazyIdKey lazyId coercionTokenName = mkWiredInIdName gHC_PRIM (fsLit "coercionToken#") coercionTokenIdKey coercionTokenId magicDictName = mkWiredInIdName gHC_PRIM (fsLit "magicDict") magicDictKey magicDictId coerceName = mkWiredInIdName gHC_PRIM (fsLit "coerce") coerceKey coerceId proxyName = mkWiredInIdName gHC_PRIM (fsLit "proxy#") proxyHashKey proxyHashId dollarName = mkWiredInIdName gHC_BASE (fsLit "$") dollarIdKey dollarId oneShotName = mkWiredInIdName gHC_MAGIC (fsLit "oneShot") oneShotKey oneShotId runRWName = mkWiredInIdName gHC_MAGIC (fsLit "runRW#") runRWKey runRWId dollarId :: Id -- Note [dollarId magic] dollarId = pcMiscPrelId dollarName ty (noCafIdInfo `setUnfoldingInfo` unf) where fun_ty = mkFunTy alphaTy openBetaTy ty = mkSpecForAllTys [runtimeRep2TyVar, alphaTyVar, openBetaTyVar] $ mkFunTy fun_ty fun_ty unf = mkInlineUnfolding (Just 2) rhs [f,x] = mkTemplateLocals [fun_ty, alphaTy] rhs = mkLams [runtimeRep2TyVar, alphaTyVar, openBetaTyVar, f, x] $ App (Var f) (Var x) ------------------------------------------------ proxyHashId :: Id proxyHashId = pcMiscPrelId proxyName ty (noCafIdInfo `setUnfoldingInfo` evaldUnfolding) -- Note [evaldUnfoldings] where -- proxy# :: forall k (a:k). Proxy# k a bndrs = mkTemplateKiTyVars [liftedTypeKind] (\ks -> ks) [k,t] = mkTyVarTys bndrs ty = mkSpecForAllTys bndrs (mkProxyPrimTy k t) ------------------------------------------------ unsafeCoerceId :: Id unsafeCoerceId = pcMiscPrelId unsafeCoerceName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs -- unsafeCoerce# :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep) -- (a :: TYPE r1) (b :: TYPE r2). -- a -> b bndrs = mkTemplateKiTyVars [runtimeRepTy, runtimeRepTy] (\ks -> map tYPE ks) [_, _, a, b] = mkTyVarTys bndrs ty = mkSpecForAllTys bndrs (mkFunTy a b) [x] = mkTemplateLocals [a] rhs = mkLams (bndrs ++ [x]) $ Cast (Var x) (mkUnsafeCo Representational a b) ------------------------------------------------ nullAddrId :: Id -- nullAddr# :: Addr# -- The reason is is here is because we don't provide -- a way to write this literal in Haskell. nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding (Lit nullAddrLit) ------------------------------------------------ seqId :: Id -- See Note [seqId magic] seqId = pcMiscPrelId seqName ty info where info = noCafIdInfo `setInlinePragInfo` inline_prag `setUnfoldingInfo` mkCompulsoryUnfolding rhs `setRuleInfo` mkRuleInfo [seq_cast_rule] inline_prag = alwaysInlinePragma `setInlinePragmaActivation` ActiveAfter "0" 0 -- Make 'seq' not inline-always, so that simpleOptExpr -- (see CoreSubst.simple_app) won't inline 'seq' on the -- LHS of rules. That way we can have rules for 'seq'; -- see Note [seqId magic] ty = mkSpecForAllTys [alphaTyVar,betaTyVar] (mkFunTy alphaTy (mkFunTy betaTy betaTy)) [x,y] = mkTemplateLocals [alphaTy, betaTy] rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x betaTy [(DEFAULT, [], Var y)]) -- See Note [Built-in RULES for seq] -- NB: ru_nargs = 3, not 4, to match the code in -- Simplify.rebuildCase which tries to apply this rule seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast" , ru_fn = seqName , ru_nargs = 3 , ru_try = match_seq_of_cast } match_seq_of_cast :: RuleFun -- See Note [Built-in RULES for seq] match_seq_of_cast _ _ _ [Type _, Type res_ty, Cast scrut co] = Just (fun `App` scrut) where fun = Lam x $ Lam y $ Case (Var x) x res_ty [(DEFAULT,[],Var y)] -- Generate a Case directly, not a call to seq, which -- might be ill-kinded if res_ty is unboxed [x,y] = mkTemplateLocals [scrut_ty, res_ty] scrut_ty = pFst (coercionKind co) match_seq_of_cast _ _ _ _ = Nothing ------------------------------------------------ lazyId :: Id -- See Note [lazyId magic] lazyId = pcMiscPrelId lazyIdName ty info where info = noCafIdInfo ty = mkSpecForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy) oneShotId :: Id -- See Note [The oneShot function] oneShotId = pcMiscPrelId oneShotName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs ty = mkSpecForAllTys [ runtimeRep1TyVar, runtimeRep2TyVar , openAlphaTyVar, openBetaTyVar ] (mkFunTy fun_ty fun_ty) fun_ty = mkFunTy openAlphaTy openBetaTy [body, x] = mkTemplateLocals [fun_ty, openAlphaTy] x' = setOneShotLambda x rhs = mkLams [ runtimeRep1TyVar, runtimeRep2TyVar , openAlphaTyVar, openBetaTyVar , body, x'] $ Var body `App` Var x runRWId :: Id -- See Note [runRW magic] in this module runRWId = pcMiscPrelId runRWName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma `setStrictnessInfo` strict_sig `setArityInfo` 1 strict_sig = mkClosedStrictSig [strictApply1Dmd] topRes -- Important to express its strictness, -- since it is not inlined until CorePrep -- Also see Note [runRW arg] in CorePrep -- State# RealWorld stateRW = mkTyConApp statePrimTyCon [realWorldTy] -- (# State# RealWorld, o #) ret_ty = mkTupleTy Unboxed [stateRW, openAlphaTy] -- State# RealWorld -> (# State# RealWorld, o #) arg_ty = stateRW `mkFunTy` ret_ty -- (State# RealWorld -> (# State# RealWorld, o #)) -- -> (# State# RealWorld, o #) ty = mkSpecForAllTys [runtimeRep1TyVar, openAlphaTyVar] $ arg_ty `mkFunTy` ret_ty -------------------------------------------------------------------------------- magicDictId :: Id -- See Note [magicDictId magic] magicDictId = pcMiscPrelId magicDictName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma ty = mkSpecForAllTys [alphaTyVar] alphaTy -------------------------------------------------------------------------------- coerceId :: Id coerceId = pcMiscPrelId coerceName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs eqRTy = mkTyConApp coercibleTyCon [ liftedTypeKind , alphaTy, betaTy ] eqRPrimTy = mkTyConApp eqReprPrimTyCon [ liftedTypeKind , liftedTypeKind , alphaTy, betaTy ] ty = mkSpecForAllTys [alphaTyVar, betaTyVar] $ mkFunTys [eqRTy, alphaTy] betaTy [eqR,x,eq] = mkTemplateLocals [eqRTy, alphaTy, eqRPrimTy] rhs = mkLams [alphaTyVar, betaTyVar, eqR, x] $ mkWildCase (Var eqR) eqRTy betaTy $ [(DataAlt coercibleDataCon, [eq], Cast (Var x) (mkCoVarCo eq))] {- Note [dollarId magic] ~~~~~~~~~~~~~~~~~~~~~ The only reason that ($) is wired in is so that its type can be forall (a:*, b:Open). (a->b) -> a -> b That is, the return type can be unboxed. E.g. this is OK foo $ True where foo :: Bool -> Int# because ($) doesn't inspect or move the result of the call to foo. See Trac #8739. There is a special typing rule for ($) in TcExpr, so the type of ($) isn't looked at there, BUT Lint subsequently (and rightly) complains if sees ($) applied to Int# (say), unless we give it a wired-in type as we do here. Note [Unsafe coerce magic] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We define a *primitive* GHC.Prim.unsafeCoerce# and then in the base library we define the ordinary function Unsafe.Coerce.unsafeCoerce :: forall (a:*) (b:*). a -> b unsafeCoerce x = unsafeCoerce# x Notice that unsafeCoerce has a civilized (albeit still dangerous) polymorphic type, whose type args have kind *. So you can't use it on unboxed values (unsafeCoerce 3#). In contrast unsafeCoerce# is even more dangerous because you *can* use it on unboxed things, (unsafeCoerce# 3#) :: Int. Its type is forall (a:OpenKind) (b:OpenKind). a -> b Note [seqId magic] ~~~~~~~~~~~~~~~~~~ 'GHC.Prim.seq' is special in several ways. a) In source Haskell its second arg can have an unboxed type x `seq` (v +# w) But see Note [Typing rule for seq] in TcExpr, which explains why we give seq itself an ordinary type seq :: forall a b. a -> b -> b and treat it as a language construct from a typing point of view. b) Its fixity is set in LoadIface.ghcPrimIface c) It has quite a bit of desugaring magic. See DsUtils.hs Note [Desugaring seq (1)] and (2) and (3) d) There is some special rule handing: Note [User-defined RULES for seq] Note [User-defined RULES for seq] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Roman found situations where he had case (f n) of _ -> e where he knew that f (which was strict in n) would terminate if n did. Notice that the result of (f n) is discarded. So it makes sense to transform to case n of _ -> e Rather than attempt some general analysis to support this, I've added enough support that you can do this using a rewrite rule: RULE "f/seq" forall n. seq (f n) = seq n You write that rule. When GHC sees a case expression that discards its result, it mentally transforms it to a call to 'seq' and looks for a RULE. (This is done in Simplify.rebuildCase.) As usual, the correctness of the rule is up to you. VERY IMPORTANT: to make this work, we give the RULE an arity of 1, not 2. If we wrote RULE "f/seq" forall n e. seq (f n) e = seq n e with rule arity 2, then two bad things would happen: - The magical desugaring done in Note [seqId magic] item (c) for saturated application of 'seq' would turn the LHS into a case expression! - The code in Simplify.rebuildCase would need to actually supply the value argument, which turns out to be awkward. Note [Built-in RULES for seq] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We also have the following built-in rule for seq seq (x `cast` co) y = seq x y This eliminates unnecessary casts and also allows other seq rules to match more often. Notably, seq (f x `cast` co) y --> seq (f x) y and now a user-defined rule for seq (see Note [User-defined RULES for seq]) may fire. Note [lazyId magic] ~~~~~~~~~~~~~~~~~~~ lazy :: forall a?. a? -> a? (i.e. works for unboxed types too) 'lazy' is used to make sure that a sub-expression, and its free variables, are truly used call-by-need, with no code motion. Key examples: * pseq: pseq a b = a `seq` lazy b We want to make sure that the free vars of 'b' are not evaluated before 'a', even though the expression is plainly strict in 'b'. * catch: catch a b = catch# (lazy a) b Again, it's clear that 'a' will be evaluated strictly (and indeed applied to a state token) but we want to make sure that any exceptions arising from the evaluation of 'a' are caught by the catch (see Trac #11555). Implementing 'lazy' is a bit tricky: * It must not have a strictness signature: by being a built-in Id, all the info about lazyId comes from here, not from GHC.Base.hi. This is important, because the strictness analyser will spot it as strict! * It must not have an unfolding: it gets "inlined" by a HACK in CorePrep. It's very important to do this inlining *after* unfoldings are exposed in the interface file. Otherwise, the unfolding for (say) pseq in the interface file will not mention 'lazy', so if we inline 'pseq' we'll totally miss the very thing that 'lazy' was there for in the first place. See Trac #3259 for a real world example. * Suppose CorePrep sees (catch# (lazy e) b). At all costs we must avoid using call by value here: case e of r -> catch# r b Avoiding that is the whole point of 'lazy'. So in CorePrep (which generate the 'case' expression for a call-by-value call) we must spot the 'lazy' on the arg (in CorePrep.cpeApp), and build a 'let' instead. * lazyId is defined in GHC.Base, so we don't *have* to inline it. If it appears un-applied, we'll end up just calling it. Note [runRW magic] ~~~~~~~~~~~~~~~~~~ Some definitions, for instance @runST@, must have careful control over float out of the bindings in their body. Consider this use of @runST@, f x = runST ( \ s -> let (a, s') = newArray# 100 [] s (_, s'') = fill_in_array_or_something a x s' in freezeArray# a s'' ) If we inline @runST@, we'll get: f x = let (a, s') = newArray# 100 [] realWorld#{-NB-} (_, s'') = fill_in_array_or_something a x s' in freezeArray# a s'' And now if we allow the @newArray#@ binding to float out to become a CAF, we end up with a result that is totally and utterly wrong: f = let (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!! in \ x -> let (_, s'') = fill_in_array_or_something a x s' in freezeArray# a s'' All calls to @f@ will share a {\em single} array! Clearly this is nonsense and must be prevented. This is what @runRW#@ gives us: by being inlined extremely late in the optimization (right before lowering to STG, in CorePrep), we can ensure that no further floating will occur. This allows us to safely inline things like @runST@, which are otherwise needlessly expensive (see #10678 and #5916). While the definition of @GHC.Magic.runRW#@, we override its type in @MkId@ to be open-kinded, runRW# :: forall (r1 :: RuntimeRep). (o :: TYPE r) => (State# RealWorld -> (# State# RealWorld, o #)) -> (# State# RealWorld, o #) Note [The oneShot function] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the context of making left-folds fuse somewhat okish (see ticket #7994 and Note [Left folds via right fold]) it was determined that it would be useful if library authors could explicitly tell the compiler that a certain lambda is called at most once. The oneShot function allows that. 'oneShot' is open kinded, i.e. the type variables can refer to unlifted types as well (Trac #10744); e.g. oneShot (\x:Int# -> x +# 1#) Like most magic functions it has a compulsary unfolding, so there is no need for a real definition somewhere. We have one in GHC.Magic for the convenience of putting the documentation there. It uses `setOneShotLambda` on the lambda's binder. That is the whole magic: A typical call looks like oneShot (\y. e) after unfolding the definition `oneShot = \f \x[oneshot]. f x` we get (\f \x[oneshot]. f x) (\y. e) --> \x[oneshot]. ((\y.e) x) --> \x[oneshot] e[x/y] which is what we want. It is only effective if the one-shot info survives as long as possible; in particular it must make it into the interface in unfoldings. See Note [Preserve OneShotInfo] in CoreTidy. Also see https://ghc.haskell.org/trac/ghc/wiki/OneShot. Note [magicDictId magic] ~~~~~~~~~~~~~~~~~~~~~~~~~ The identifier `magicDict` is just a place-holder, which is used to implement a primitve that we cannot define in Haskell but we can write in Core. It is declared with a place-holder type: magicDict :: forall a. a The intention is that the identifier will be used in a very specific way, to create dictionaries for classes with a single method. Consider a class like this: class C a where f :: T a We are going to use `magicDict`, in conjunction with a built-in Prelude rule, to cast values of type `T a` into dictionaries for `C a`. To do this, we define a function like this in the library: data WrapC a b = WrapC (C a => Proxy a -> b) withT :: (C a => Proxy a -> b) -> T a -> Proxy a -> b withT f x y = magicDict (WrapC f) x y The purpose of `WrapC` is to avoid having `f` instantiated. Also, it avoids impredicativity, because `magicDict`'s type cannot be instantiated with a forall. The field of `WrapC` contains a `Proxy` parameter which is used to link the type of the constraint, `C a`, with the type of the `Wrap` value being made. Next, we add a built-in Prelude rule (see prelude/PrelRules.hs), which will replace the RHS of this definition with the appropriate definition in Core. The rewrite rule works as follows: magicDict @t (wrap @a @b f) x y ----> f (x `cast` co a) y The `co` coercion is the newtype-coercion extracted from the type-class. The type class is obtain by looking at the type of wrap. ------------------------------------------------------------- @realWorld#@ used to be a magic literal, \tr{void#}. If things get nasty as-is, change it back to a literal (@Literal@). voidArgId is a Local Id used simply as an argument in functions where we just want an arg to avoid having a thunk of unlifted type. E.g. x = \ void :: Void# -> (# p, q #) This comes up in strictness analysis Note [evaldUnfoldings] ~~~~~~~~~~~~~~~~~~~~~~ The evaldUnfolding makes it look that some primitive value is evaluated, which in turn makes Simplify.interestingArg return True, which in turn makes INLINE things applied to said value likely to be inlined. -} realWorldPrimId :: Id -- :: State# RealWorld realWorldPrimId = pcMiscPrelId realWorldName realWorldStatePrimTy (noCafIdInfo `setUnfoldingInfo` evaldUnfolding -- Note [evaldUnfoldings] `setOneShotInfo` stateHackOneShot) voidPrimId :: Id -- Global constant :: Void# voidPrimId = pcMiscPrelId voidPrimIdName voidPrimTy (noCafIdInfo `setUnfoldingInfo` evaldUnfolding) -- Note [evaldUnfoldings] voidArgId :: Id -- Local lambda-bound :: Void# voidArgId = mkSysLocal (fsLit "void") voidArgIdKey voidPrimTy coercionTokenId :: Id -- :: () ~ () coercionTokenId -- Used to replace Coercion terms when we go to STG = pcMiscPrelId coercionTokenName (mkTyConApp eqPrimTyCon [liftedTypeKind, liftedTypeKind, unitTy, unitTy]) noCafIdInfo pcMiscPrelId :: Name -> Type -> IdInfo -> Id pcMiscPrelId name ty info = mkVanillaGlobalWithInfo name ty info -- We lie and say the thing is imported; otherwise, we get into -- a mess with dependency analysis; e.g., core2stg may heave in -- random calls to GHCbase.unpackPS__. If GHCbase is the module -- being compiled, then it's just a matter of luck if the definition -- will be in "the right place" to be in scope.
vTurbine/ghc
compiler/basicTypes/MkId.hs
bsd-3-clause
59,709
0
21
16,498
7,361
4,015
3,346
600
6
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.HTools.Instance ( testHTools_Instance , genInstanceSmallerThanNode , genInstanceMaybeBiggerThanNode , genInstanceOnNodeList , genInstanceList , Instance.Instance(..) ) where import Prelude () import Ganeti.Prelude import Control.Arrow ((&&&)) import Control.Monad (liftM) import Test.QuickCheck hiding (Result) import Test.Ganeti.TestHTools (nullISpec) import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.HTools.Types () import Ganeti.BasicTypes import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Loader as Loader import qualified Ganeti.HTools.Types as Types -- * Arbitrary instances -- | Generates a random instance with maximum and minimum disk/mem/cpu values. genInstanceWithin :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Gen Instance.Instance genInstanceWithin min_mem min_dsk min_cpu min_spin max_mem max_dsk max_cpu max_spin = do name <- genFQDN mem <- choose (min_mem, max_mem) dsk <- choose (min_dsk, max_dsk) run_st <- arbitrary pn <- arbitrary sn <- arbitrary vcpus <- choose (min_cpu, max_cpu) dt <- arbitrary spindles <- case max_spin of Nothing -> genMaybe $ choose (min_spin, maxSpindles) Just ls -> liftM Just $ choose (min_spin, ls) forthcoming <- arbitrary let disk = Instance.Disk dsk spindles return $ Instance.create name mem dsk [disk] vcpus run_st [] True pn sn dt 1 [] forthcoming -- | Generate an instance with maximum disk/mem/cpu values. genInstanceSmallerThan :: Int -> Int -> Int -> Maybe Int -> Gen Instance.Instance genInstanceSmallerThan = genInstanceWithin 1 0 1 0 -- | Generates an instance smaller than a node. genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance genInstanceSmallerThanNode node = genInstanceSmallerThan (Node.availMem node `div` 2) (Node.availDisk node `div` 2) (Node.availCpu node `div` 2) (if Node.exclStorage node then Just $ Node.fSpindlesForth node `div` 2 else Nothing) -- | Generates an instance possibly bigger than a node. -- In any case, that instance will be bigger than the node's ipolicy's lower -- bound. genInstanceMaybeBiggerThanNode :: Node.Node -> Gen Instance.Instance genInstanceMaybeBiggerThanNode node = let minISpec = runListHead nullISpec Types.minMaxISpecsMinSpec . Types.iPolicyMinMaxISpecs $ Node.iPolicy node in genInstanceWithin (Types.iSpecMemorySize minISpec) (Types.iSpecDiskSize minISpec) (Types.iSpecCpuCount minISpec) (Types.iSpecSpindleUse minISpec) (Node.availMem node + Types.unitMem * 2) (Node.availDisk node + Types.unitDsk * 3) (Node.availCpu node + Types.unitCpu * 4) (if Node.exclStorage node then Just $ Node.fSpindles node + Types.unitSpindle * 5 else Nothing) -- | Generates an instance with nodes on a node list. -- The following rules are respected: -- 1. The instance is never bigger than its primary node -- 2. If possible the instance has different pnode and snode -- 3. Else disk templates which require secondary nodes are disabled genInstanceOnNodeList :: Node.List -> Gen Instance.Instance genInstanceOnNodeList nl = do let nsize = Container.size nl pnode <- choose (0, nsize-1) let (snodefilter, dtfilter) = if nsize >= 2 then ((/= pnode), const True) else (const True, not . Instance.hasSecondary) snode <- choose (0, nsize-1) `suchThat` snodefilter i <- genInstanceSmallerThanNode (Container.find pnode nl) `suchThat` dtfilter return $ i { Instance.pNode = pnode, Instance.sNode = snode } -- | Generates an instance list given an instance generator. genInstanceList :: Gen Instance.Instance -> Gen Instance.List genInstanceList igen = fmap (snd . Loader.assignIndices) names_instances where names_instances = map (Instance.name &&& id) <$> listOf igen -- let's generate a random instance instance Arbitrary Instance.Instance where arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu Nothing -- * Test cases -- Simple instance tests, we only have setter/getters prop_creat :: Instance.Instance -> Property prop_creat inst = Instance.name inst ==? Instance.alias inst prop_setIdx :: Instance.Instance -> Types.Idx -> Property prop_setIdx inst idx = Instance.idx (Instance.setIdx inst idx) ==? idx prop_setName :: Instance.Instance -> String -> Bool prop_setName inst name = Instance.name newinst == name && Instance.alias newinst == name where newinst = Instance.setName inst name prop_setAlias :: Instance.Instance -> String -> Bool prop_setAlias inst name = Instance.name newinst == Instance.name inst && Instance.alias newinst == name where newinst = Instance.setAlias inst name prop_setPri :: Instance.Instance -> Types.Ndx -> Property prop_setPri inst pdx = Instance.pNode (Instance.setPri inst pdx) ==? pdx prop_setSec :: Instance.Instance -> Types.Ndx -> Property prop_setSec inst sdx = Instance.sNode (Instance.setSec inst sdx) ==? sdx prop_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool prop_setBoth inst pdx sdx = Instance.pNode si == pdx && Instance.sNode si == sdx where si = Instance.setBoth inst pdx sdx prop_shrinkMG :: Instance.Instance -> Property prop_shrinkMG inst = Instance.mem inst >= 2 * Types.unitMem ==> case Instance.shrinkByType inst Types.FailMem of Ok inst' -> Instance.mem inst' ==? Instance.mem inst - Types.unitMem Bad msg -> failTest msg prop_shrinkMF :: Instance.Instance -> Property prop_shrinkMF inst = forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem -> let inst' = inst { Instance.mem = mem} in isBad $ Instance.shrinkByType inst' Types.FailMem prop_shrinkCG :: Instance.Instance -> Property prop_shrinkCG inst = Instance.vcpus inst >= 2 * Types.unitCpu ==> case Instance.shrinkByType inst Types.FailCPU of Ok inst' -> Instance.vcpus inst' ==? Instance.vcpus inst - Types.unitCpu Bad msg -> failTest msg prop_shrinkCF :: Instance.Instance -> Property prop_shrinkCF inst = forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus -> let inst' = inst { Instance.vcpus = vcpus } in isBad $ Instance.shrinkByType inst' Types.FailCPU prop_shrinkDG :: Instance.Instance -> Property prop_shrinkDG inst = Instance.dsk inst >= 2 * Types.unitDsk ==> case Instance.shrinkByType inst Types.FailDisk of Ok inst' -> Instance.dsk inst' ==? Instance.dsk inst - Types.unitDsk Bad msg -> failTest msg prop_shrinkDF :: Instance.Instance -> Property prop_shrinkDF inst = forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk -> let inst' = inst { Instance.dsk = dsk , Instance.disks = [Instance.Disk dsk Nothing] } in isBad $ Instance.shrinkByType inst' Types.FailDisk prop_setMovable :: Instance.Instance -> Bool -> Property prop_setMovable inst m = Instance.movable inst' ==? m where inst' = Instance.setMovable inst m testSuite "HTools/Instance" [ 'prop_creat , 'prop_setIdx , 'prop_setName , 'prop_setAlias , 'prop_setPri , 'prop_setSec , 'prop_setBoth , 'prop_shrinkMG , 'prop_shrinkMF , 'prop_shrinkCG , 'prop_shrinkCF , 'prop_shrinkDG , 'prop_shrinkDF , 'prop_setMovable ]
leshchevds/ganeti
test/hs/Test/Ganeti/HTools/Instance.hs
bsd-2-clause
9,291
0
15
2,096
2,118
1,107
1,011
166
2
module Compiler.Simplify where import Data.Generics.PlateData import Compiler.Type import Data.List import Data.Maybe simplify :: Program1 -> Program2 simplify = addDollar . reform . freezeRules -- change rule application rule(arg) to rule_arg and replace all bits freezeRules :: Program1 -> Program1 freezeRules xs = map useDyn $ staticRules ++ dynInvoke where (staticRules,dynRules) = partition (\(Stmt1 a b c) -> null b) xs dynNames = [(a, (b,c)) | Stmt1 a b c <- dynRules] dynInvoke = [gen name arg res |Call1 name (Just arg) bind <- nub $ universeBi staticRules ,Just res <- [lookup name dynNames]] gen name arg (var,bod) = Stmt1 (getName name arg) "" (transformBi f bod) where f (Call1 v Nothing Nothing) | v == var = arg f x = x useDyn = transformBi f where f (Call1 v (Just x) y) | v `elem` map fst dynNames = Call1 (getName v x) Nothing y f x = x getName name (Literal1 x) = name ++ "_" ++ fromMaybe x (lookup x reps) where reps = [("'","squot"),("\"","dquot")] reform :: Program1 -> Program2 reform = concatMap reformStmt reformStmt (Stmt1 a "" (Choice1 xs)) | fst (last xs) == Call1 "_" Nothing Nothing = Stmt2 a (Choice2 (zipWith f [1..] $ init xs) (g $ length xs)) : zipWith (\i (_,v) -> Stmt2 (g i) (reformSeq v)) [1..] xs where f i (Literal1 x,_) = (x, g i) g i = a ++ "_" ++ show i reformStmt (Stmt1 a "" x) = [Stmt2 a $ reformSeq x] reformSeq (Seq1 act xs) = Seq2 act (map reformItem xs) reformItem (Literal1 x) = Literal2 x reformItem (Call1 name (Just (Literal1 x)) y) | name `elem` prims = Prim2 name x y reformItem (Call1 name Nothing y) = Rule2 name y addDollar :: Program2 -> Program2 addDollar = transformBi f where f (Seq2 act xs) | all (isNothing . getBind) xs && length (filter (isJust . getBind) ys) == 1 = Seq2 act ys where ys = transformBi (const $ Just (1::Int)) xs f x = x
silkapp/tagsoup
dead/parser/Compiler/old/Simplify.hs
bsd-3-clause
2,095
0
16
624
903
458
445
42
3
-- ---------------------------------------------------------------------------- -- | Handle conversion of CmmData to LLVM code. -- module LlvmCodeGen.Data ( genLlvmData, resolveLlvmDatas, resolveLlvmData ) where #include "HsVersions.h" import Llvm import LlvmCodeGen.Base import BlockId import CLabel import OldCmm import FastString import qualified Outputable import Data.List (foldl') -- ---------------------------------------------------------------------------- -- * Constants -- -- | The string appended to a variable name to create its structure type alias structStr :: LMString structStr = fsLit "_struct" -- ---------------------------------------------------------------------------- -- * Top level -- -- | Pass a CmmStatic section to an equivalent Llvm code. Can't -- complete this completely though as we need to pass all CmmStatic -- sections before all references can be resolved. This last step is -- done by 'resolveLlvmData'. genLlvmData :: LlvmEnv -> (Section, CmmStatics) -> LlvmUnresData genLlvmData env (sec, Statics lbl xs) = let static = map genData xs label = strCLabel_llvm env lbl types = map getStatTypes static getStatTypes (Left x) = cmmToLlvmType $ cmmLitType x getStatTypes (Right x) = getStatType x strucTy = LMStruct types alias = LMAlias ((label `appendFS` structStr), strucTy) in (lbl, sec, alias, static) resolveLlvmDatas :: LlvmEnv -> [LlvmUnresData] -> (LlvmEnv, [LlvmData]) resolveLlvmDatas env ldata = foldl' res (env, []) ldata where res (e, xs) ll = let (e', nd) = resolveLlvmData e ll in (e', nd:xs) -- | Fix up CLabel references now that we should have passed all CmmData. resolveLlvmData :: LlvmEnv -> LlvmUnresData -> (LlvmEnv, LlvmData) resolveLlvmData env (lbl, sec, alias, unres) = let (env', static, refs) = resDatas env unres ([], []) struct = Just $ LMStaticStruc static alias label = strCLabel_llvm env lbl link = if (externallyVisibleCLabel lbl) then ExternallyVisible else Internal const = isSecConstant sec glob = LMGlobalVar label alias link Nothing Nothing const in (env', ((glob,struct):refs, [alias])) -- | Should a data in this section be considered constant isSecConstant :: Section -> Bool isSecConstant Text = True isSecConstant ReadOnlyData = True isSecConstant RelocatableReadOnlyData = True isSecConstant ReadOnlyData16 = True isSecConstant Data = False isSecConstant UninitialisedData = False isSecConstant (OtherSection _) = False -- ---------------------------------------------------------------------------- -- ** Resolve Data/CLabel references -- -- | Resolve data list resDatas :: LlvmEnv -> [UnresStatic] -> ([LlvmStatic], [LMGlobal]) -> (LlvmEnv, [LlvmStatic], [LMGlobal]) resDatas env [] (stats, glob) = (env, stats, glob) resDatas env (cmm:rest) (stats, globs) = let (env', nstat, nglob) = resData env cmm in resDatas env' rest (stats ++ [nstat], globs ++ nglob) -- | Resolve an individual static label if it needs to be. -- -- We check the 'LlvmEnv' to see if the reference has been defined in this -- module. If it has we can retrieve its type and make a pointer, otherwise -- we introduce a generic external definition for the referenced label and -- then make a pointer. resData :: LlvmEnv -> UnresStatic -> (LlvmEnv, LlvmStatic, [LMGlobal]) resData env (Right stat) = (env, stat, []) resData env (Left cmm@(CmmLabel l)) = let label = strCLabel_llvm env l ty = funLookup label env lmty = cmmToLlvmType $ cmmLitType cmm in case ty of -- Make generic external label defenition and then pointer to it Nothing -> let glob@(var, _) = genStringLabelRef label env' = funInsert label (pLower $ getVarType var) env ptr = LMStaticPointer var in (env', LMPtoI ptr lmty, [glob]) -- Referenced data exists in this module, retrieve type and make -- pointer to it. Just ty' -> let var = LMGlobalVar label (LMPointer ty') ExternallyVisible Nothing Nothing False ptr = LMStaticPointer var in (env, LMPtoI ptr lmty, []) resData env (Left (CmmLabelOff label off)) = let (env', var, glob) = resData env (Left (CmmLabel label)) offset = LMStaticLit $ LMIntLit (toInteger off) llvmWord in (env', LMAdd var offset, glob) resData env (Left (CmmLabelDiffOff l1 l2 off)) = let (env1, var1, glob1) = resData env (Left (CmmLabel l1)) (env2, var2, glob2) = resData env1 (Left (CmmLabel l2)) var = LMSub var1 var2 offset = LMStaticLit $ LMIntLit (toInteger off) llvmWord in (env2, LMAdd var offset, glob1 ++ glob2) resData _ _ = panic "resData: Non CLabel expr as left type!" -- ---------------------------------------------------------------------------- -- * Generate static data -- -- | Handle static data genData :: CmmStatic -> UnresStatic genData (CmmString str) = let v = map (\x -> LMStaticLit $ LMIntLit (fromIntegral x) i8) str ve = v ++ [LMStaticLit $ LMIntLit 0 i8] in Right $ LMStaticArray ve (LMArray (length ve) i8) genData (CmmUninitialised bytes) = Right $ LMUninitType (LMArray bytes i8) genData (CmmStaticLit lit) = genStaticLit lit -- | Generate Llvm code for a static literal. -- -- Will either generate the code or leave it unresolved if it is a 'CLabel' -- which isn't yet known. genStaticLit :: CmmLit -> UnresStatic genStaticLit (CmmInt i w) = Right $ LMStaticLit (LMIntLit i (LMInt $ widthInBits w)) genStaticLit (CmmFloat r w) = Right $ LMStaticLit (LMFloatLit (fromRational r) (widthToLlvmFloat w)) -- Leave unresolved, will fix later genStaticLit c@(CmmLabel _ ) = Left $ c genStaticLit c@(CmmLabelOff _ _) = Left $ c genStaticLit c@(CmmLabelDiffOff _ _ _) = Left $ c genStaticLit (CmmBlock b) = Left $ CmmLabel $ infoTblLbl b genStaticLit (CmmHighStackMark) = panic "genStaticLit: CmmHighStackMark unsupported!" -- ----------------------------------------------------------------------------- -- * Misc -- -- | Error Function panic :: String -> a panic s = Outputable.panic $ "LlvmCodeGen.Data." ++ s
nomeata/ghc
compiler/llvmGen/LlvmCodeGen/Data.hs
bsd-3-clause
6,479
0
17
1,559
1,652
892
760
103
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Blackbox.Tests ( tests , remove , removeDir ) where ------------------------------------------------------------------------------ import Control.Exception (catch, finally, throwIO) import Control.Monad import Control.Monad.Trans import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.Monoid import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.Encoding as T import Network.Http.Client import Prelude hiding (catch) import System.Directory import System.FilePath import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit import Test.HUnit hiding (Test, path) ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ testServer :: String testServer = "http://127.0.0.1" ------------------------------------------------------------------------------ testPort :: String testPort = "9753" ------------------------------------------------------------------------------ -- | The server uri, without the leading slash. testServerUri :: String testServerUri = testServer ++ ":" ++ testPort ------------------------------------------------------------------------------ -- | The server url, with the leading slash. testServerUrl :: String testServerUrl = testServerUri ++ "/" -------------------- -- TEST LOADER -- -------------------- ------------------------------------------------------------------------------ tests :: Test tests = testGroup "non-cabal-tests" [ requestTest "hello" "hello world" , requestTest "index" "index page\n" , requestTest "" "index page\n" , requestTest "splicepage" "splice page contents of the app splice\n" , requestTest "routeWithSplice" "routeWithSplice: foo snaplet data stringz" , requestTest "routeWithConfig" "routeWithConfig: topConfigValue" , requestTest "foo/foopage" "foo template page\n" , requestTest "foo/fooConfig" "fooValue" , requestTest "foo/fooRootUrl" "foo" , requestTest "barconfig" "barValue" , requestTest "bazpage" "baz template page <barsplice></barsplice>\n" , requestTest "bazpage2" "baz template page contents of the bar splice\n" , requestTest "bazpage3" "baz template page <barsplice></barsplice>\n" , requestTest "bazpage4" "baz template page <barsplice></barsplice>\n" , requestTest "barrooturl" "url" , requestExpectingError "bazbadpage" 500 "A web handler threw an exception. Details:\nTemplate \"cpyga\" not found." , requestTest "foo/fooSnapletName" "foosnaplet" , fooConfigPathTest -- Test the embedded snaplet , requestTest "embed/heist/embeddedpage" "embedded snaplet page <asplice></asplice>\n" , requestTest "embed/aoeuhtns" "embedded snaplet page splice value42\n" , requestTest "embed/heist/onemoredir/extra" "This is an extra template\n" -- This set of tests highlights the differences in the behavior of the -- get... functions from MonadSnaplet. , fooHandlerConfigTest , barHandlerConfigTest , bazpage5Test , bazConfigTest , requestTest "sessionDemo" "[(\"foo\",\"bar\")]\n" , reloadTest ] ------------------------------------------------------------------------------ testName :: String -> String testName uri = "internal/" ++ uri --testName = id ------------------------------------------------------------------------------ requestTest :: String -> Text -> Test requestTest url desired = testCase (testName url) $ requestTest' url desired ------------------------------------------------------------------------------ requestTest' :: String -> Text -> IO () requestTest' url desired = do actual <- get (S.pack $ testServerUrl ++ url) concatHandler assertEqual url desired (T.decodeUtf8 $ L.fromChunks [actual]) ------------------------------------------------------------------------------ requestExpectingError :: String -> Int -> Text -> Test requestExpectingError url status desired = testCase (testName url) $ requestExpectingError' url status desired ------------------------------------------------------------------------------ requestExpectingError' :: String -> Int -> Text -> IO () requestExpectingError' url status desired = do let fullUrl = testServerUrl ++ url get (S.pack fullUrl) $ \resp is -> do assertEqual ("Status code: "++fullUrl) status (getStatusCode resp) res <- concatHandler resp is assertEqual fullUrl desired (T.decodeUtf8 $ L.fromChunks [res]) ------------------------------------------------------------------------------ fooConfigPathTest :: Test fooConfigPathTest = testCase (testName "foo/fooFilePath") $ do b <- liftM L.unpack $ grab "/foo/fooFilePath" assertRelativelyTheSame b "snaplets/foosnaplet" ------------------------------------------------------------------------------ assertRelativelyTheSame :: FilePath -> FilePath -> IO () assertRelativelyTheSame p expected = do b <- makeRelativeToCurrentDirectory p assertEqual ("expected " ++ expected) expected b ------------------------------------------------------------------------------ grab :: MonadIO m => String -> m L.ByteString grab path = liftIO $ liftM (L.fromChunks . (:[])) $ get (S.pack $ testServerUri ++ path) concatHandler ------------------------------------------------------------------------------ testWithCwd :: String -> (String -> L.ByteString -> Assertion) -> Test testWithCwd uri f = testCase (testName uri) $ testWithCwd' uri f ------------------------------------------------------------------------------ testWithCwd' :: String -> (String -> L.ByteString -> Assertion) -> Assertion testWithCwd' uri f = do b <- grab slashUri cwd <- getCurrentDirectory f cwd b where slashUri = '/' : uri ------------------------------------------------------------------------------ fooHandlerConfigTest :: Test fooHandlerConfigTest = testWithCwd "foo/handlerConfig" $ \cwd b -> do let response = L.fromChunks [ "([\"app\"],\"" , S.pack cwd , "/snaplets/foosnaplet\"," , "Just \"foosnaplet\",\"A demonstration " , "snaplet called foo.\",\"foo\")" ] assertEqual "" response b ------------------------------------------------------------------------------ barHandlerConfigTest :: Test barHandlerConfigTest = testWithCwd "bar/handlerConfig" $ \cwd b -> do let response = L.fromChunks [ "([\"app\"],\"" , S.pack cwd , "/snaplets/baz\"," , "Just \"baz\",\"An example snaplet called " , "bar.\",\"\")" ] assertEqual "" response b ------------------------------------------------------------------------------ -- bazpage5 uses barsplice bound by renderWithSplices at request time bazpage5Test :: Test bazpage5Test = testWithCwd "bazpage5" $ \cwd b -> do let response = L.fromChunks [ "baz template page ([\"app\"],\"" , S.pack cwd , "/snaplets/baz\"," , "Just \"baz\",\"An example snaplet called " , "bar.\",\"\")\n" ] assertEqual "" (T.decodeUtf8 response) (T.decodeUtf8 b) ------------------------------------------------------------------------------ -- bazconfig uses two splices, appconfig and fooconfig. appconfig is bound with -- the non type class version of addSplices in the main app initializer. -- fooconfig is bound by addSplices in fooInit. bazConfigTest :: Test bazConfigTest = testWithCwd "bazconfig" $ \cwd b -> do let response = L.fromChunks [ "baz config page ([],\"" , S.pack cwd , "\",Just \"app\"," -- TODO, right? , "\"Test application\",\"\") " , "([\"app\"],\"" , S.pack cwd , "/snaplets/foosnaplet\"," , "Just \"foosnaplet\",\"A demonstration snaplet " , "called foo.\",\"foo\")\n" ] assertEqual "" (T.decodeUtf8 response) (T.decodeUtf8 b) ------------------------------------------------------------------------------ expect404 :: String -> IO () expect404 url = do get (S.pack $ testServerUrl ++ url) $ \resp i -> do case getStatusCode resp of 404 -> return () _ -> assertFailure "expected 404" ------------------------------------------------------------------------------ request404Test :: String -> Test request404Test url = testCase (testName url) $ expect404 url remove :: FilePath -> IO () remove f = do exists <- doesFileExist f when exists $ removeFile f removeDir :: FilePath -> IO () removeDir d = do exists <- doesDirectoryExist d when exists $ removeDirectoryRecursive "snaplets/foosnaplet" ------------------------------------------------------------------------------ reloadTest :: Test reloadTest = testCase "internal/reload-test" $ do let goodTplOrig = "good.tpl" let badTplOrig = "bad.tpl" let goodTplNew = "snaplets" </> "heist" </> "templates" </> "good.tpl" let badTplNew = "snaplets" </> "heist" </> "templates" </> "bad.tpl" goodExists <- doesFileExist goodTplNew badExists <- doesFileExist badTplNew assertBool "good.tpl exists" (not goodExists) assertBool "bad.tpl exists" (not badExists) expect404 "bad" copyFile badTplOrig badTplNew expect404 "good" expect404 "bad" flip finally (remove badTplNew) $ testWithCwd' "admin/reload" $ \cwd' b -> do let cwd = S.pack cwd' let response = T.concat [ "Error reloading site!\n\nInitializer " , "threw an exception...\n" , T.pack cwd' , "/snaplets/heist" , "/templates/bad.tpl \"" , T.pack cwd' , "/snaplets/heist/templates" , "/bad.tpl\" (line 2, column 1):\nunexpected " , "end of input\nexpecting \"=\", \"/\" or " , "\">\"\n\n...but before it died it generated " , "the following output:\nInitializing app @ /\n" , "Initializing heist @ /heist\n\n" ] assertEqual "admin/reload" response (T.decodeUtf8 b) copyFile goodTplOrig goodTplNew testWithCwd' "admin/reload" $ \cwd' b -> do -- TODO/NOTE: Needs cleanup let cwd = S.pack cwd' let response = L.fromChunks [ "Initializing app @ /\nInitializing heist @ ", "/heist\n...loaded 9 templates from ", cwd, "/snaplets/heist/templates\nInitializing CookieSession ", "@ /session\nInitializing foosnaplet @ /foo\n...adding 1 ", "templates from ", cwd, "/snaplets/foosnaplet/templates with route prefix ", "foo/\nInitializing baz @ /\n...adding 2 templates from ", cwd, "/snaplets/baz/templates with route prefix /\nInitializing ", "embedded @ /\nInitializing heist @ /heist\n...loaded ", "1 templates from ", cwd, "/snaplets/embedded/snaplets/heist/templates\n...adding ", "1 templates from ", cwd, "/snaplets/embedded/extra-templates with route prefix ", "onemoredir/\n...adding 0 templates from ", cwd, "/templates with route prefix extraTemplates/\n", "Initializing JsonFileAuthManager @ ", "/auth\nSite successfully reloaded.\n" ] assertEqual "admin/reload" response b requestTest' "good" "Good template\n"
sopvop/snap
test/suite/Blackbox/Tests.hs
bsd-3-clause
12,605
0
18
3,358
2,023
1,054
969
217
2
{-# LANGUAGE DataKinds, PolyKinds, TypeOperators, TypeFamilies , TypeApplications, TypeInType #-} module DumpParsedAst where import Data.Kind data Peano = Zero | Succ Peano type family Length (as :: [k]) :: Peano where Length (a : as) = Succ (Length as) Length '[] = Zero -- vis kind app data T f (a :: k) = MkT (f a) type family F1 (a :: k) (f :: k -> Type) :: Type where F1 @Peano a f = T @Peano f a main = putStrLn "hello"
sdiehl/ghc
testsuite/tests/parser/should_compile/DumpParsedAst.hs
bsd-3-clause
456
2
8
114
159
93
66
-1
-1
module HLint.Generalise where import Data.Monoid import Control.Monad warn = concatMap ==> (=<<) warn = liftM ==> fmap warn = map ==> fmap warn = a ++ b ==> a `Data.Monoid.mappend` b
bergmark/hlint
data/Generalise.hs
bsd-3-clause
186
0
7
34
67
40
27
7
1
-- https://www.fpcomplete.com/school/starting-with-haskell/libraries-and-frameworks/randoms import System.Random import Control.Monad (replicateM) main = replicateM 10 (randomIO :: IO Float) >>= print
junnf/Functional-Programming
codes/random.hs
unlicense
202
1
8
18
43
22
21
3
1
module Type where newtype TVar = TV String deriving (Show, Eq, Ord) data Type = TVar TVar | TCon String | TArr Type Type deriving (Show, Eq, Ord) infixr `TArr` data Scheme = Forall [TVar] Type deriving (Show, Eq, Ord) typeInt :: Type typeInt = TCon "Int" typeBool :: Type typeBool = TCon "Bool"
yupferris/write-you-a-haskell
chapter7/poly/src/Type.hs
mit
314
0
7
73
123
70
53
15
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="az-AZ"> <title>Passive Scan Rules - Alpha | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>İndeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Axtar</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/pscanrulesAlpha/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesAlpha/resources/help_az_AZ/helpset_az_AZ.hs
apache-2.0
988
83
53
162
403
212
191
-1
-1
module A1 where import D1 (sumSquares, fringe) import D1 import C1 import B1 main :: (Tree Int) -> Bool main t = isSame (sumSquares (fringe t)) ((sumSquares (B1.myFringe t)) + (sumSquares (C1.myFringe t)))
SAdams601/HaRe
old/testing/mkImpExplicit/A1_AstOut.hs
bsd-3-clause
234
4
12
61
103
56
47
10
1
-- | Register coalescing. module RegAlloc.Graph.Coalesce ( regCoalesce, slurpJoinMovs ) where import GhcPrelude import RegAlloc.Liveness import Instruction import Reg import Cmm import Bag import Digraph import UniqFM import UniqSet import UniqSupply import Data.List -- | Do register coalescing on this top level thing -- -- For Reg -> Reg moves, if the first reg dies at the same time the -- second reg is born then the mov only serves to join live ranges. -- The two regs can be renamed to be the same and the move instruction -- safely erased. regCoalesce :: Instruction instr => [LiveCmmDecl statics instr] -> UniqSM [LiveCmmDecl statics instr] regCoalesce code = do let joins = foldl' unionBags emptyBag $ map slurpJoinMovs code let alloc = foldl' buildAlloc emptyUFM $ bagToList joins let patched = map (patchEraseLive (sinkReg alloc)) code return patched -- | Add a v1 = v2 register renaming to the map. -- The register with the lowest lexical name is set as the -- canonical version. buildAlloc :: UniqFM Reg -> (Reg, Reg) -> UniqFM Reg buildAlloc fm (r1, r2) = let rmin = min r1 r2 rmax = max r1 r2 in addToUFM fm rmax rmin -- | Determine the canonical name for a register by following -- v1 = v2 renamings in this map. sinkReg :: UniqFM Reg -> Reg -> Reg sinkReg fm r = case lookupUFM fm r of Nothing -> r Just r' -> sinkReg fm r' -- | Slurp out mov instructions that only serve to join live ranges. -- -- During a mov, if the source reg dies and the destination reg is -- born then we can rename the two regs to the same thing and -- eliminate the move. slurpJoinMovs :: Instruction instr => LiveCmmDecl statics instr -> Bag (Reg, Reg) slurpJoinMovs live = slurpCmm emptyBag live where slurpCmm rs CmmData{} = rs slurpCmm rs (CmmProc _ _ _ sccs) = foldl' slurpBlock rs (flattenSCCs sccs) slurpBlock rs (BasicBlock _ instrs) = foldl' slurpLI rs instrs slurpLI rs (LiveInstr _ Nothing) = rs slurpLI rs (LiveInstr instr (Just live)) | Just (r1, r2) <- takeRegRegMoveInstr instr , elementOfUniqSet r1 $ liveDieRead live , elementOfUniqSet r2 $ liveBorn live -- only coalesce movs between two virtuals for now, -- else we end up with allocatable regs in the live -- regs list.. , isVirtualReg r1 && isVirtualReg r2 = consBag (r1, r2) rs | otherwise = rs
ezyang/ghc
compiler/nativeGen/RegAlloc/Graph/Coalesce.hs
bsd-3-clause
2,760
0
14
903
565
288
277
57
3
module Existential where -- Hmm, this is universal quantification, not existential. data U = U (forall a . (a,a->Int,Int->a,a->a->a)) -- This is existential quantification data E = forall a . {-Eq a =>-} E (a,a->Int,Int->a,a->a->a) e = E (1,id,id,(+)) -- OK: f (E (x,toint,fromint,op)) = toint (x `op` x) -- Error: it assumes that the existentially quantified type is Bool --g (E (x,toint,fromint,op)) = toint (False `op` x) -- Error: assuming two different existentially quantifier variables are the same --h (E (_,toint,_,_)) (E (x,_,_,_)) = toint x -- Error: the existentially quantified type variable escapes -- (and becomes universally quantified) --j (E (x,_,_,_)) = x
forste/haReFork
tools/base/tests/Existential.hs
bsd-3-clause
682
0
11
112
162
100
62
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Builtin -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : [email protected] -- Portability : portable -- -- The module defines all the known built-in 'Program's. -- -- Where possible we try to find their version numbers. -- module Distribution.Simple.Program.Builtin ( -- * The collection of unconfigured and configured programs builtinPrograms, -- * Programs that Cabal knows about ghcProgram, ghcPkgProgram, ghcjsProgram, ghcjsPkgProgram, lhcProgram, lhcPkgProgram, hmakeProgram, jhcProgram, haskellSuiteProgram, haskellSuitePkgProgram, uhcProgram, gccProgram, arProgram, stripProgram, happyProgram, alexProgram, hsc2hsProgram, c2hsProgram, cpphsProgram, hscolourProgram, haddockProgram, greencardProgram, ldProgram, tarProgram, cppProgram, pkgConfigProgram, hpcProgram, ) where import Distribution.Simple.Program.Find import Distribution.Simple.Program.Internal import Distribution.Simple.Program.Run import Distribution.Simple.Program.Types import Distribution.Simple.Utils import Distribution.Compat.Exception import Distribution.Verbosity import Distribution.Version import Data.Char ( isDigit ) import qualified Data.Map as Map -- ------------------------------------------------------------ -- * Known programs -- ------------------------------------------------------------ -- | The default list of programs. -- These programs are typically used internally to Cabal. builtinPrograms :: [Program] builtinPrograms = [ -- compilers and related progs ghcProgram , ghcPkgProgram , ghcjsProgram , ghcjsPkgProgram , haskellSuiteProgram , haskellSuitePkgProgram , hmakeProgram , jhcProgram , lhcProgram , lhcPkgProgram , uhcProgram , hpcProgram -- preprocessors , hscolourProgram , haddockProgram , happyProgram , alexProgram , hsc2hsProgram , c2hsProgram , cpphsProgram , greencardProgram -- platform toolchain , gccProgram , arProgram , stripProgram , ldProgram , tarProgram -- configuration tools , pkgConfigProgram ] ghcProgram :: Program ghcProgram = (simpleProgram "ghc") { programFindVersion = findProgramVersion "--numeric-version" id, -- Workaround for https://ghc.haskell.org/trac/ghc/ticket/8825 -- (spurious warning on non-english locales) programPostConf = \_verbosity ghcProg -> do let ghcProg' = ghcProg { programOverrideEnv = ("LANGUAGE", Just "en") : programOverrideEnv ghcProg } -- Only the 7.8 branch seems to be affected. Fixed in 7.8.4. affectedVersionRange = intersectVersionRanges (laterVersion $ Version [7,8,0] []) (earlierVersion $ Version [7,8,4] []) return $ maybe ghcProg (\v -> if withinRange v affectedVersionRange then ghcProg' else ghcProg) (programVersion ghcProg) } ghcPkgProgram :: Program ghcPkgProgram = (simpleProgram "ghc-pkg") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "ghc-pkg --version" gives a string like -- "GHC package manager version 6.4.1" case words str of (_:_:_:_:ver:_) -> ver _ -> "" } ghcjsProgram :: Program ghcjsProgram = (simpleProgram "ghcjs") { programFindVersion = findProgramVersion "--numeric-ghcjs-version" id } -- note: version is the version number of the GHC version that ghcjs-pkg was built with ghcjsPkgProgram :: Program ghcjsPkgProgram = (simpleProgram "ghcjs-pkg") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "ghcjs-pkg --version" gives a string like -- "GHCJS package manager version 6.4.1" case words str of (_:_:_:_:ver:_) -> ver _ -> "" } lhcProgram :: Program lhcProgram = (simpleProgram "lhc") { programFindVersion = findProgramVersion "--numeric-version" id } lhcPkgProgram :: Program lhcPkgProgram = (simpleProgram "lhc-pkg") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "lhc-pkg --version" gives a string like -- "LHC package manager version 0.7" case words str of (_:_:_:_:ver:_) -> ver _ -> "" } hmakeProgram :: Program hmakeProgram = (simpleProgram "hmake") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "hmake --version" gives a string line -- "/usr/local/bin/hmake: 3.13 (2006-11-01)" case words str of (_:ver:_) -> ver _ -> "" } jhcProgram :: Program jhcProgram = (simpleProgram "jhc") { programFindVersion = findProgramVersion "--version" $ \str -> -- invoking "jhc --version" gives a string like -- "jhc 0.3.20080208 (wubgipkamcep-2) -- compiled by ghc-6.8 on a x86_64 running linux" case words str of (_:ver:_) -> ver _ -> "" } uhcProgram :: Program uhcProgram = (simpleProgram "uhc") { programFindVersion = findProgramVersion "--version-dotted" id } hpcProgram :: Program hpcProgram = (simpleProgram "hpc") { programFindVersion = findProgramVersion "version" $ \str -> case words str of (_ : _ : _ : ver : _) -> ver _ -> "" } -- This represents a haskell-suite compiler. Of course, the compiler -- itself probably is not called "haskell-suite", so this is not a real -- program. (But we don't know statically the name of the actual compiler, -- so this is the best we can do.) -- -- Having this Program value serves two purposes: -- -- 1. We can accept options for the compiler in the form of -- -- --haskell-suite-option(s)=... -- -- 2. We can find a program later using this static id (with -- requireProgram). -- -- The path to the real compiler is found and recorded in the ProgramDb -- during the configure phase. haskellSuiteProgram :: Program haskellSuiteProgram = (simpleProgram "haskell-suite") { -- pretend that the program exists, otherwise it won't be in the -- "configured" state programFindLocation = \_verbosity _searchPath -> return $ Just ("haskell-suite-dummy-location", []) } -- This represent a haskell-suite package manager. See the comments for -- haskellSuiteProgram. haskellSuitePkgProgram :: Program haskellSuitePkgProgram = (simpleProgram "haskell-suite-pkg") { programFindLocation = \_verbosity _searchPath -> return $ Just ("haskell-suite-pkg-dummy-location", []) } happyProgram :: Program happyProgram = (simpleProgram "happy") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "happy --version" gives a string like -- "Happy Version 1.16 Copyright (c) ...." case words str of (_:_:ver:_) -> ver _ -> "" } alexProgram :: Program alexProgram = (simpleProgram "alex") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "alex --version" gives a string like -- "Alex version 2.1.0, (c) 2003 Chris Dornan and Simon Marlow" case words str of (_:_:ver:_) -> takeWhile (\x -> isDigit x || x == '.') ver _ -> "" } gccProgram :: Program gccProgram = (simpleProgram "gcc") { programFindVersion = findProgramVersion "-dumpversion" id } arProgram :: Program arProgram = simpleProgram "ar" stripProgram :: Program stripProgram = (simpleProgram "strip") { programFindVersion = \verbosity -> findProgramVersion "--version" stripExtractVersion (lessVerbose verbosity) } hsc2hsProgram :: Program hsc2hsProgram = (simpleProgram "hsc2hs") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "hsc2hs --version" gives a string like "hsc2hs version 0.66" case words str of (_:_:ver:_) -> ver _ -> "" } c2hsProgram :: Program c2hsProgram = (simpleProgram "c2hs") { programFindVersion = findProgramVersion "--numeric-version" id } cpphsProgram :: Program cpphsProgram = (simpleProgram "cpphs") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "cpphs --version" gives a string like "cpphs 1.3" case words str of (_:ver:_) -> ver _ -> "" } hscolourProgram :: Program hscolourProgram = (simpleProgram "hscolour") { programFindLocation = \v p -> findProgramOnSearchPath v p "HsColour", programFindVersion = findProgramVersion "-version" $ \str -> -- Invoking "HsColour -version" gives a string like "HsColour 1.7" case words str of (_:ver:_) -> ver _ -> "" } haddockProgram :: Program haddockProgram = (simpleProgram "haddock") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "haddock --version" gives a string like -- "Haddock version 0.8, (c) Simon Marlow 2006" case words str of (_:_:ver:_) -> takeWhile (`elem` ('.':['0'..'9'])) ver _ -> "" } greencardProgram :: Program greencardProgram = simpleProgram "greencard" ldProgram :: Program ldProgram = simpleProgram "ld" tarProgram :: Program tarProgram = (simpleProgram "tar") { -- See #1901. Some versions of 'tar' (OpenBSD, NetBSD, ...) don't support the -- '--format' option. programPostConf = \verbosity tarProg -> do tarHelpOutput <- getProgramInvocationOutput verbosity (programInvocation tarProg ["--help"]) -- Some versions of tar don't support '--help'. `catchIO` (\_ -> return "") let k = "Supports --format" v = if ("--format" `isInfixOf` tarHelpOutput) then "YES" else "NO" m = Map.insert k v (programProperties tarProg) return $ tarProg { programProperties = m } } cppProgram :: Program cppProgram = simpleProgram "cpp" pkgConfigProgram :: Program pkgConfigProgram = (simpleProgram "pkg-config") { programFindVersion = findProgramVersion "--version" id }
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/Distribution/Simple/Program/Builtin.hs
bsd-3-clause
10,350
0
17
2,525
1,912
1,094
818
205
2
module T7848 where data A = (:&&) Int Int | A Int Int x (+) ((&)@z) ((:&&) a b) (c :&& d) (e `A` f) (A g h) = y where infixl 3 `y` y _ = (&) {-# INLINE (&) #-} {-# SPECIALIZE (&) :: a #-} (&) = x
gridaphobe/ghc
testsuite/tests/parser/should_fail/T7848.hs
bsd-3-clause
233
8
7
88
122
71
51
8
1
module Main where main = putStrLn $ s ++ show s where s = "module Main where\n\nmain = putStrLn $ s ++ show s\n where s = "
HalosGhost/hs
intro/quine.hs
isc
134
0
6
38
27
15
12
3
1
module Test.Scher.Property ( forAll , Property (verify) ) where import Test.Scher.Generic import Test.Scher.Symbolic import System.IO.Unsafe import System.Random import Data.IORef class Property b where verify :: b -> IO () instance Property Bool where verify b = assert b forAll :: (Symbolic a, Property b) => String -> (a -> b) -> All a b forAll = All instance (Symbolic a, Property b) => Property (All a b) where verify (All name f) = do arg <- run $ make name verify $ f arg instance (Symbolic a, Property b) => Property (a -> b) where verify f = do name <- genSym arg <- run $ make name verify $ f arg data All a b = All String (a -> b) counter :: IORef Int counter = unsafePerformIO $ newIORef 0 genSym :: IO String genSym = do num <- getStdRandom (random) :: IO Int return $ "#AUTO-" ++ show (abs num)
m-alvarez/scher
Test/Scher/Property.hs
mit
858
0
10
202
366
189
177
32
1
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module Web.Mackerel.Types.Host where import Control.Applicative ((<|>)) import Data.Aeson import qualified Data.Aeson as Aeson import Data.Aeson.TH (deriveJSON, constructorTagModifier, fieldLabelModifier) import Data.Aeson.Types (Parser, typeMismatch) import Data.Char (toLower) import Data.Default (Default(..)) import qualified Data.HashMap.Lazy as HM import Data.Maybe (isJust) import qualified Data.Text as Text import Web.Mackerel.Internal.TH data HostId = HostId String deriving (Eq, Show) instance FromJSON HostId where parseJSON (Aeson.String hostId) = return $ HostId $ Text.unpack hostId parseJSON o = typeMismatch "HostId" o instance ToJSON HostId where toJSON (HostId hostId) = toJSON hostId data HostMetaCloud = HostMetaCloud { metaCloudProvider :: String, metaCloudMetadata :: HM.HashMap String Value } deriving (Eq, Show) $(deriveJSON options { fieldLabelModifier = map toLower . drop 9 } ''HostMetaCloud) data HostMetaCpu = HostMetaCpu { metaCpuCacheSize :: Maybe String, metaCpuCoreId :: Maybe String, metaCpuCores :: Maybe String, metaCpuFamily :: Maybe String, metaCpuMhz :: Maybe String, metaCpuModel :: Maybe String, metaCpuModelName :: Maybe String, metaCpuPhysicalId :: Maybe String, metaCpuStepping :: Maybe String, metaCpuVendorId :: Maybe String } deriving (Eq, Show) instance FromJSON HostMetaCpu where parseJSON (Object o) = HostMetaCpu <$> o .:? "cache_size" <*> o .:? "core_id" <*> o .:? "cores" <*> o .:? "family" <*> (o .:? "mhz" <|> fmap show <$> (o .:? "mhz" :: Parser (Maybe Integer))) <*> (o .:? "model" <|> fmap show <$> (o .:? "model" :: Parser (Maybe Integer))) <*> o .:? "model_name" <*> o .:? "physical_id" <*> o .:? "stepping" <*> o .:? "vendor_id" parseJSON o = typeMismatch "HostMetaCpu" o instance ToJSON HostMetaCpu where toJSON (HostMetaCpu cacheSize coreId cores family mhz model modelName physicalId stepping vendorId) = object [ key .= value | (key, value) <- [ ("cache_size", cacheSize), ("core_id", coreId), ("cores", cores), ("family", family), ("mhz", mhz), ("model", model), ("model_name", modelName), ("physical_id", physicalId), ("stepping", stepping), ("vendor_id", vendorId) ], isJust value ] data HostMeta = HostMeta { metaAgentName :: Maybe String, metaAgentRevision :: Maybe String, metaAgentVersion :: Maybe String, metaBlockDevice :: Maybe (HM.HashMap String (HM.HashMap String String)), metaCpu :: Maybe [HostMetaCpu], metaFilesystem :: Maybe (HM.HashMap String (HM.HashMap String Value)), metaKernel :: Maybe (HM.HashMap String String), metaMemory :: Maybe (HM.HashMap String String), metaCloud :: Maybe HostMetaCloud } deriving (Eq, Show) instance Default HostMeta where def = HostMeta def def def def def def def def def $(deriveJSON options { fieldLabelModifier = \xs -> let ys = drop 4 xs in if take 5 ys == "Agent" then kebabCase ys else snakeCase ys } ''HostMeta) data HostStatus = HostStatusWorking | HostStatusStandby | HostStatusMaintenance | HostStatusPoweroff deriving Eq instance Show HostStatus where show HostStatusWorking = "working" show HostStatusStandby = "standby" show HostStatusMaintenance = "maintenance" show HostStatusPoweroff = "poweroff" instance Read HostStatus where readsPrec _ xs = [ (hs, drop (length str) xs) | (hs, str) <- pairs', take (length str) xs == str ] where pairs' = [(HostStatusWorking, "working"), (HostStatusStandby, "standby"), (HostStatusMaintenance, "maintenance"), (HostStatusPoweroff, "poweroff")] $(deriveJSON options { constructorTagModifier = map toLower . drop 10 } ''HostStatus) data HostInterface = HostInterface { hostInterfaceName :: String, hostInterfaceMacAddress :: Maybe String, hostInterfaceIpv4Addresses :: Maybe [String], hostInterfaceIpv6Addresses :: Maybe [String] } deriving (Eq, Show) $(deriveJSON options { fieldLabelModifier = (\(c:cs) -> toLower c : cs) . drop 13 } ''HostInterface) data Host = Host { hostId :: HostId, hostName :: String, hostDisplayName :: Maybe String, hostStatus :: HostStatus, hostMemo :: String, hostRoles :: HM.HashMap String [String], hostIsRetired :: Bool, hostCreatedAt :: Integer, hostMeta :: HostMeta, hostInterfaces :: [HostInterface] } deriving (Eq, Show) $(deriveJSON options ''Host) data HostCreate = HostCreate { hostCreateName :: String, hostCreateDisplayName :: Maybe String, hostCreateCustomIdentifier :: Maybe String, hostCreateMeta :: HostMeta, hostCreateInterfaces :: Maybe [HostInterface], hostCreateRoleFullnames :: Maybe [String], hostCreateChecks :: Maybe [String] } deriving (Eq, Show) instance Default HostCreate where def = HostCreate def def def def def def def $(deriveJSON options { fieldLabelModifier = (\(c:cs) -> toLower c : cs) . drop 10 } ''HostCreate)
itchyny/mackerel-client-hs
src/Web/Mackerel/Types/Host.hs
mit
5,116
0
23
1,042
1,593
878
715
122
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Game where import Data.Monoid ((<>)) import Control.Concurrent (MVar, newEmptyMVar, putMVar) import Control.Monad.State import qualified Data.ByteString.Char8 as B import Data.Char (toLower) import Data.Maybe (listToMaybe) import System.Random (randomRIO) data GameState = GameState { robots :: [Robot], mvar :: MVar GameState } data Robot = Robot { rId :: ID, pos :: Position, status :: RobotState, kind :: RobotKind } deriving (Eq) data RobotState = Off | Idle | Performing Action deriving (Eq) data Action = Access | Move | Query | Scan | Spawn | Start deriving (Eq, Show) data RobotKind = Headquarters | Engineer | Specialist | Factory deriving (Eq, Show) data Direction = North | East | South | West type Position = (Int, Int) type Area = (Position, Position) type Circle = (Position, Int) type ID = B.ByteString -- poor man’s json formatter (for fun!) jsonifyRobot :: Robot -> B.ByteString jsonifyRobot robot = "{" <> field "type" (kindToString . kind) <> "," <> field "uuid" rId <> "," <> field "x" (B.pack . show . fst . pos) <> "," <> field "y" (B.pack . show . snd . pos) <> "," <> field "status" (jsonifyState . status) <> "}" where field str fun = "\"" <> str <> "\":\"" <> fun robot <> "\"" jsonifyState Off = "off" jsonifyState Idle = "idle" jsonifyState (Performing action) = firstLower . B.pack $ show action kindToString :: RobotKind -> B.ByteString kindToString = firstLower . B.pack . show firstLower :: B.ByteString -> B.ByteString firstLower str = (B.singleton . toLower $ B.head str) <> B.tail str stringToKind :: B.ByteString -> Maybe RobotKind stringToKind "engineer" = Just Engineer stringToKind "headquarters" = Just Headquarters stringToKind "specialist" = Just Specialist stringToKind "factory" = Just Factory stringToKind _ = Nothing stringToDirection :: B.ByteString -> Maybe Direction stringToDirection "north" = Just North stringToDirection "east" = Just East stringToDirection "west" = Just West stringToDirection "south" = Just South stringToDirection _ = Nothing initialMVar :: IO (MVar GameState) initialMVar = do mvar <- newEmptyMVar putMVar mvar (GameState [] mvar) return mvar collision :: Position -> GameState -> Maybe Robot collision position state = listToMaybe . filter ((== position) . pos) $ robots state lookupRobot :: ID -> GameState -> Maybe Robot lookupRobot ident state = listToMaybe . filter ((== ident) . rId) $ robots state spawnRobot :: Robot -> GameState -> GameState spawnRobot robot state = state { robots = robot : robots state } changeRobot :: ID -> (Robot -> Robot) -> GameState -> GameState changeRobot uuid fun state = state { robots = map mapFun $ robots state } where mapFun robot | rId robot == uuid = fun robot | otherwise = robot move :: Direction -> Position -> Position move dir (x, y) = (x + dx, y + dy) where dx = case dir of East -> 1 West -> -1 _ -> 0 dy = case dir of North -> 1 South -> -1 _ -> 0 moveRobot :: Direction -> Robot -> Robot moveRobot dir rob = rob { pos = move dir $ pos rob } setStatus :: (MonadState GameState m) => ID -> RobotState -> m () setStatus robotID status = modify . changeRobot robotID $ \r -> r { status = status } randomPosition :: Area -> IO Position randomPosition ((x1,y1),(x2,y2))= do x <- randomRIO (x1, x2) y <- randomRIO (y1, y2) return (x, y) randomPositionInCircle :: Circle -> IO Position randomPositionInCircle arg@((x,y), r) = do pos <- randomPosition ((x - r, y - r), (x + r, y + r)) if distance (x,y) pos <= fromIntegral r then return pos else randomPositionInCircle arg distance :: (Floating a) => Position -> Position -> a distance (x1,y1) (x2,y2)= sqrt $ (fromIntegral x1 - fromIntegral x2) ** 2 + (fromIntegral y1 - fromIntegral y2) ** 2
shak-mar/botstrats
server/Game.hs
mit
4,115
0
17
1,009
1,469
781
688
95
5
module Banjo where areYouPlayingBanjo :: String -> String areYouPlayingBanjo name@('R':xs) = name ++ " plays banjo" areYouPlayingBanjo name@('r':xs) = name ++ " plays banjo" areYouPlayingBanjo name = name ++ " does not play banjo"
dzeban/haskell-exercises
Banjo.hs
mit
232
0
8
35
69
38
31
5
1
{-# LANGUAGE ExistentialQuantification, Rank2Types #-} module Control.Monad.Trans.Store where import qualified Data.Map as M import Control.Monad import Control.Monad.Hoist import Control.Monad.Trans -- The semantics of store should be that it continues as soon as the reference -- has been calculated, but that the entire operation shouldn't complete until -- all of the store operations have completed. data Step k v m a = Done a | Get k (v -> StoreT k v m a) | Store v (k -> StoreT k v m a) data StoreT k v m a = StoreT { runStoreT :: m (Step k v m a) } instance Monad m => Monad (StoreT k v m) where return = StoreT . return . Done m >>= f = StoreT $ do step <- runStoreT m case step of Done x -> runStoreT $ f x Get k c -> return $ Get k (\i -> c i >>= f) Store v c -> return $ Store v (\i -> c i >>= f) instance MonadTrans (StoreT k v) where lift m = StoreT $ liftM Done m instance MonadIO m => MonadIO (StoreT k v m) where liftIO m = StoreT $ liftM Done (liftIO m) instance MonadHoist (StoreT k v) where hoist f m = StoreT $ do step <- f $ runStoreT m case step of Done a -> return $ Done a Get k c -> return $ Get k $ hoist f . c Store v c -> return $ Store v $ hoist f . c get :: Monad m => k -> StoreT k a m a get k = StoreT $ return $ Get k return store :: Monad m => v -> StoreT a v m a store v = StoreT $ return $ Store v return keyChange :: Monad m => (k0 -> k1) -> (k1 -> k0) -> StoreT k0 v m a -> StoreT k1 v m a keyChange forwards backwards op = StoreT $ do step <- runStoreT op case step of Done a -> return $ Done a Get k c -> return $ Get (forwards k) (keyChange forwards backwards . c) Store v c -> return $ Store v (keyChange forwards backwards . c . backwards) valueChange :: Monad m => (v0 -> v1) -> (v1 -> v0) -> StoreT k v0 m a -> StoreT k v1 m a valueChange forwards backwards op = StoreT $ do step <- runStoreT op case step of Done a -> return $ Done a Get k c -> return $ Get k (valueChange forwards backwards . c . backwards) Store v c -> return $ Store (forwards v) (valueChange forwards backwards . c) cache :: (Ord k, Monad m) => StoreT k v m a -> StoreT k v m a cache op = do cache' M.empty op where cache' m op' = do step <- lift $ runStoreT op' case step of Done a -> return a Get k c -> do case M.lookup k m of Just v -> cache' m $ c v Nothing -> do v <- get k cache' (M.insert k v m) $ c v Store v c -> do k <- store v cache' (M.insert k v m) $ c k
DanielWaterworth/siege
src/Control/Monad/Trans/Store.hs
mit
2,617
0
23
774
1,178
570
608
66
4
{-# LANGUAGE OverloadedStrings, RecordWildCards #-} module Main where import Text.XML.HXT.Core main = do runX (readDocument [ withValidate no, withParseHTML yes, withInputEncoding utf8 ] "" >>> processChildren (process1 `when` isElem) >>> writeDocument [] "-" ) process1 :: ArrowXml a => a XmlTree XmlTree process1 = addNav >>> processTopDown ( (returnA <+> (followingSiblingAxis >>> filterAxis (hasName "p") ) ) `when` withoutNav (hasName "p") ) >>> remNav deleteExtraParas :: ArrowXml a => a XmlTree XmlTree deleteExtraParas = addNav >>> (getChildren >>> withoutNav (isElem >>> hasName "p")) >>> remNav addText :: ArrowXml a => a XmlTree XmlTree addText = replaceChildren (getChildren <+> txt " test") {- process = deep (isElem >>> hasName "p") >>> withNav (followingSiblingAxis >>> filterAxis (isElem >>> hasName "p")) -}
danchoi/hxt-nav
Main.hs
mit
1,011
0
16
305
236
122
114
21
1
main = print $ (foldl1 cross $ map (`map` [1..]) [t, p, h]) !! 2 t n = n * ( n + 1) `div` 2 p n = n * (3 * n - 1) `div` 2 h n = n * (2 * n - 1) -- Lazily intersects ordered lists cross a@(x:xs) b@(y:ys) | x > y = cross a ys | x < y = cross xs b | otherwise = x : cross xs ys
nickspinale/euler
complete/045.hs
mit
293
0
11
98
206
109
97
8
1
module Azure.BlobStorage.Util where import qualified Blaze.ByteString.Builder as Builder import Control.Applicative import Control.Monad.Reader hiding (forM) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Char8 as Char8 import qualified Data.ByteString.Lazy as LBS import qualified Data.Char as Char import Data.Conduit import Data.Maybe (fromMaybe) import Data.Monoid import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time (getCurrentTime, formatTime) import Network.HTTP.Conduit import Prelude import Safe (readMay) import System.Locale (defaultTimeLocale) -- | Use the read instance to remove escaping. If that fails, then -- just return the original. unescapeText :: Text -> Text unescapeText input = fromMaybe input $ readMay $ "\"" ++ Text.unpack input ++ "\"" asciiLowercase :: ByteString -> ByteString asciiLowercase = Char8.map Char.toLower toStrict :: LBS.ByteString -> ByteString toStrict = BS.concat . LBS.toChunks fromStrict :: BS.ByteString -> LBS.ByteString fromStrict = LBS.fromChunks . (: []) encodeBase64Text :: Text -> Text encodeBase64Text = Text.decodeUtf8 . Base64.encode . Text.encodeUtf8 strip :: ByteString -> ByteString strip = snd . Char8.span Char.isSpace . fst . Char8.spanEnd Char.isSpace pad :: Int -> Text -> Text -> Text pad n c bs = Text.replicate (n - Text.length bs) c <> bs rfc1123Time :: IO String rfc1123Time = formatTime defaultTimeLocale "%a, %d %b %Y %H:%M:%S GMT" <$> getCurrentTime -- | Conduit which coalesces results of the specified byte-length. -- The last result may be shorter than the specified length. splitBytes :: Monad m => Int -> Conduit ByteString m RequestBody splitBytes stride = go 0 mempty where go l b = do mx <- await case mx of Nothing -> when (l > 0) $ yield $ RequestBodyBuilder (fromIntegral l) b Just x -> do let l' = l + BS.length x if l' < stride then go l' (b <> Builder.fromByteString x) else do let (before, after) = BS.splitAt (stride - l) x yield $ RequestBodyBuilder (fromIntegral stride) (b <> Builder.fromByteString before) when (BS.length after > 0) $ leftover after go 0 mempty
fpco/schoolofhaskell.com
src/Azure/BlobStorage/Util.hs
mit
2,517
0
22
608
684
372
312
54
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} module Ch15.SupplyClass ( S.Supply , S.runSupply , S.runRandomSupply , MonadSupply (..) ) where import qualified Ch15.Supply as S class (Monad m) => (MonadSupply s) m | m -> s where next :: m (Maybe s) instance MonadSupply s (S.Supply s) where next = S.next showTwo_class :: (Show s, Monad m, MonadSupply s m) => m String showTwo_class = showTwo <$> next <*> next where showTwo x y = (show "a: " ++ show x ++ ", b: " ++ show y)
futtetennista/IntroductionToFunctionalProgramming
RWH/src/ch15/SupplyClass.hs
mit
677
2
11
228
193
104
89
17
1
module Main where import Data.List import Light.Cameras import Light.Film import Light.Filters import Light.Geometry f :: Film f = film (16, 12) (boxFilter (1, 1)) p1, p2 :: PerspectiveCamera p1 = perspectiveCamera f (pi/3) p2 = perspectiveCamera f (pi/2) o :: OrthographicCamera o = orthographicCamera f 1 getRays :: (Camera c) => c -> [Ray] getRays camera = let (fw, fh) = (filmDimensions.cameraFilm) camera in [cameraRay camera (fromIntegral x + 0.5, fromIntegral y + 0.5) | x <- [0..fw-1], y <- [0..fh-1]] main :: IO () main = do putStrLn "graphics_toolkit (\"fltk\");" putStrLn "clf" drawPerspectivePlot 1 "Perspective (60)" p1 drawPerspectivePlot 2 "Perspective (90)" p2 drawOrthographicPlot 3 "Orthographic" o drawPerspectivePlot :: Int -> String -> PerspectiveCamera -> IO () drawPerspectivePlot ix title camera = let fovY = perspectiveVerticalFOV camera (_,fh) = (filmDimensions.cameraFilm) camera in drawPlot ix title camera (fromIntegral fh / (2 * tan (fovY/2))) drawOrthographicPlot :: Int -> String -> OrthographicCamera -> IO () drawOrthographicPlot ix title camera = let (fw, fh) = (filmDimensions.cameraFilm) camera in drawPlot ix title camera (fromIntegral (min fw fh)) drawPlot :: (Camera c) => Int -> String -> c -> Double -> IO () drawPlot ix title camera imagePlaneHeight = do putStrLn $ "figure (" ++ show ix ++ ");" putStrLn $ "x = linspace (" ++ intercalate ", " (map show [-fw/2, fw/2, fw+1]) ++ ");" putStrLn $ "y = linspace (" ++ intercalate ", " (map show [-fh/2, fh/2, fh+1]) ++ ");" putStrLn "[xx, yy] = meshgrid(x, y);" putStrLn $ "zz = (xx.*0).+" ++ show imagePlaneHeight ++ ";" putStrLn "mesh (xx, yy, zz);" putStrLn "hold on;" putStrLn "grid off;" putStrLn "box off;" putStrLn $ "axis ([" ++ intercalate ", " (map show [-dim/2, dim/2, -dim/2, dim/2, 0, dim]) ++ "], \"square\");" putStrLn "daspect ([1, 1, 1]);" putStrLn "pbaspect ([1, 1, 1]);" putStrLn $ "title (\"" ++ title ++ "\");" putStrLn $ "ox = [" ++ intercalate ", " (map show ox) ++ "];" putStrLn $ "oy = [" ++ intercalate ", " (map show oy) ++ "];" putStrLn $ "oz = [" ++ intercalate ", " (map show oz) ++ "];" putStrLn $ "dx = [" ++ intercalate ", " (map show vx) ++ "];" putStrLn $ "dy = [" ++ intercalate ", " (map show vy) ++ "];" putStrLn $ "dz = [" ++ intercalate ", " (map show vz) ++ "];" putStrLn "q = quiver3 (ox, oy, oz, dx, dy, dz, 0);" putStrLn "set (q, \"maxheadsize\", 0);" putStrLn "hold off;" where fw = (fromIntegral.fst.filmDimensions.cameraFilm) camera fh = (fromIntegral.snd.filmDimensions.cameraFilm) camera dim = foldl max 0 [fw, fh, imagePlaneHeight] + 4 rays = getRays camera ox = map (px.rayOrigin) rays oy = map (py.rayOrigin) rays oz = map (pz.rayOrigin) rays vx = map (\r -> (dx $ rayDirection r)*imagePlaneHeight*1.2/(dz $ rayDirection r)) rays vy = map (\r -> (dy $ rayDirection r)*imagePlaneHeight*1.2/(dz $ rayDirection r)) rays vz = map (\r -> (dz $ rayDirection r)*imagePlaneHeight*1.2/(dz $ rayDirection r)) rays
jtdubs/Light
src/App/CameraDiagrams.hs
mit
3,326
0
15
866
1,239
618
621
65
1
{-# LANGUAGE OverloadedStrings #-} module Day13 (day13, day13', run) where import Data.Attoparsec.Text ( Parser(..) , char , decimal , endOfLine , isHorizontalSpace , many' , option , parseOnly , string , takeTill ) import Data.Function (on) import Data.List (groupBy, nub, sortBy) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map (empty, fromList, keys, union) import Data.Monoid (Sum(..)) import Data.Set (Set) import qualified Data.Set as Set (delete, fromList) import Data.Text (Text, pack) import Graph -- Parsing types and type synonyms for the problem at hand type Person = Text type Happiness = Sum Int data Source = Source (Edge Person) Happiness deriving (Show, Eq) type SourceData = EdgeWeightMap Person Happiness sourceEdge :: Source -> Edge Person sourceEdge (Source e _) = e sourceHappiness :: Source -> Happiness sourceHappiness (Source _ h) = h compileMap :: [Source] -> SourceData compileMap [] = Map.empty compileMap xs = Map.fromList . map collapseSameSources . groupBy ((==) `on` sourceEdge) . sortBy (compare `on` sourceEdge) $ xs collapseSameSources :: [Source] -> (Edge Person, Happiness) collapseSameSources [] = undefined collapseSameSources xs@(x:_) = (sourceEdge x, mconcat . map sourceHappiness $ xs) parseSourceData :: Parser SourceData parseSourceData = do sources <- many' parseSource return $ compileMap sources parseSource :: Parser Source parseSource = do a <- takeTill isHorizontalSpace string " would " gainOrLose <- takeTill isHorizontalSpace char ' ' h <- decimal string " happiness units by sitting next to " b <- takeTill (== '.') char '.' option () endOfLine let happiness = if gainOrLose == "gain" then h else (-h) return $ Source (Edge (Node a) (Node b)) (Sum happiness) allPeople :: SourceData -> [Person] allPeople = nub . concatMap (\(Edge (Node a) (Node b)) -> [a, b]) . Map.keys bestFullCycle :: SourceData -> Maybe (Traversal Person Happiness) bestFullCycle g = case allPeople g of [] -> Just $ Traversal [] mempty (x:_) -> bestTraversal' g compare start start rest where start = Just $ Node x rest = Set.delete (Node x) (Set.fromList . map Node . allPeople $ g) day13 :: String -> Int day13 input = case parseOnly parseSourceData . pack $ input of (Left _) -> -1 (Right sourceData) -> case bestFullCycle sourceData of Nothing -> -2 (Just t) -> getSum . traversalWeight $ t addSelf :: SourceData -> SourceData addSelf g = Map.union (Map.fromList selfEdges) g where self = Node "Self" selfEdges = map (\p -> (Edge self (Node p), 0)) $ allPeople g day13' :: String -> Int day13' input = case parseOnly parseSourceData . pack $ input of (Left _) -> -1 (Right sourceData) -> case bestFullCycle $ addSelf sourceData of Nothing -> -2 (Just t) -> getSum . traversalWeight $ t -- Input run :: IO () run = do putStrLn "Day 13 results: " input <- readFile "inputs/day13.txt" putStrLn $ " " ++ show (day13 input) putStrLn $ " " ++ show (day13' input)
brianshourd/adventOfCode2015
src/Day13.hs
mit
3,167
0
15
731
1,153
604
549
90
3
module U.Util.Components where import qualified Data.Graph as Graph import qualified Data.Map as Map import qualified Data.Set as Set import Data.Set (Set) import Data.Maybe (fromMaybe) -- | Order bindings by dependencies and group into components. -- Each component consists of > 1 bindings, each of which depends -- transitively on all other bindings in the component. -- -- 1-element components may or may not depend on themselves. -- -- The order is such that a component at index i will not depend -- on components and indexes > i. But a component at index i does not -- _necessarily_ depend on any components at earlier indices. -- -- Example: -- -- let rec -- ping n = pong (n + 1); -- pong n = ping (n + 1); -- g = id 42; -- y = id "hi" -- id x = x; -- in ping g -- -- `components` would produce `[[ping,pong], [id], [g], [y]]` -- Notice that `id` comes before `g` and `y` in the output, since -- both `g` and `y` depend on `id`. -- -- Uses Tarjan's algorithm: -- https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm components :: Ord v => (t -> Set v) -> [(v, t)] -> [[(v, t)]] components freeVars bs = let varIds = Map.fromList (map fst bs `zip` reverse [(1 :: Int) .. length bs]) -- something horribly wrong if this bombs varId v = fromMaybe msg $ Map.lookup v varIds where msg = error "Components.components bug" -- use ints as keys for graph to preserve original source order as much as -- possible graph = [ ((v, b), varId v, deps b) | (v, b) <- bs ] vars = Set.fromList (map fst bs) deps b = varId <$> Set.toList (Set.intersection vars (freeVars b)) in Graph.flattenSCC <$> Graph.stronglyConnComp graph
unisonweb/platform
codebase2/util/U/Util/Components.hs
mit
1,739
0
14
386
326
193
133
16
1
{-# LANGUAGE DeriveGeneric #-} -- Object.hs; Mun Hon Cheong ([email protected]) 2005 module Object ( Object, ObjInput(..), ObjOutput(..), ObsObjState(..), Message(..), isRay, -- :: ObsObjState -> Bool isAICube, -- :: ObsObjState -> Bool isProjectile, -- :: ObsObjState -> Bool isCamera, -- :: ObsObjState -> Bool ) where import FRP.Yampa.Core (SF, Event) import Control.DeepSeq import Camera import IdentityList import MD3 (AnimState) import GameInputParser (GameInput) import GHC.Generics (Generic) type Object = SF ObjInput ObjOutput data ObjInput = ObjInput { oiHit :: !(Event [(ILKey,ObsObjState)]), oiMessage :: !(Event [(ILKey,Message)]), oiCollision :: !Camera, oiCollisionPos :: !(Double,Double,Double), oiOnLand :: !Bool, oiGameInput :: !GameInput, oiVisibleObjs :: !(Event [(ILKey,ObsObjState)]) } data ObjOutput = ObjOutput { ooObsObjState :: !ObsObjState, ooSendMessage :: !(Event [(ILKey,(ILKey,Message))]), ooKillReq :: Event (), ooSpawnReq :: Event [ILKey->Object] } data Message = Coord !(Double,Double,Double) | PlayerLockedOn | PlayerLockedOn2 | TargetPosition !(Double,Double,Double) | TargetPosition2 !(Double,Double,Double) | EnemyDown -- most fields are strict to prevent space leaks data ObsObjState = OOSCamera { newCam :: !Camera, oldCam :: !Camera, health :: !Double, ammo :: !Double, score :: !Int, cood :: ![(Double,Double,Double)] } | OOSRay { rayStart :: !(Double,Double,Double), rayEnd :: !(Double,Double,Double), rayUC :: !(Double,Double,Double), clipped :: !Bool, firedFrom :: !ILKey } | OOSProjectile { projectileOldPos :: !(Double,Double,Double), projectileNewPos :: !(Double,Double,Double), firedFrom :: !ILKey } | OOSWayPoint !(Double,Double,Double) | OOSAICube { oosOldCubePos :: !(Double,Double,Double), oosNewCubePos :: !(Double,Double,Double), oosCubeSize :: !(Double,Double,Double), oosCubeAngle :: !Double, oosCubePitch :: !Double, upperAnim :: !AnimState, lowerAnim :: !AnimState, health :: !Double, modelName :: !String, target :: !(Double,Double,Double), fade :: !Float } deriving Generic--, Camera) --instance Forceable ObsObjState where -- If non-strict fields: oosNonStrict1 obj `seq` ... `seq` obj --force obj = obj instance NFData Camera instance NFData ObsObjState isRay :: ObsObjState -> Bool isRay OOSRay {} = True isRay _ = False isCamera :: ObsObjState -> Bool isCamera OOSCamera {} = True isCamera _ = False isAICube :: ObsObjState -> Bool isAICube OOSAICube {} = True isAICube _ = False isProjectile :: ObsObjState -> Bool isProjectile OOSProjectile {} = True isProjectile _ = False
pushkinma/frag
src/Object.hs
gpl-2.0
3,377
0
14
1,156
804
479
325
160
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Reffit.User where import Data.Aeson import Data.SafeCopy (Migrate, MigrateFrom, base, deriveSafeCopy, extension, migrate) import Data.Serialize import qualified Data.Set as Set import Data.Text import Data.Time import Data.Typeable import GHC.Generics import Reffit.FieldTag import Reffit.Types data UserEvent = WroteOComment DocumentId OverviewCommentId | VotedOnOComment DocumentId OverviewCommentId (Maybe UpDownVote) UTCTime | PostedDocument DocumentId | FollowedUser UserName UTCTime | PinnedDoc DocumentId UTCTime deriving (Show, Read, Eq, Ord, Generic, Typeable) deriveSafeCopy 1 'extension ''UserEvent instance Serialize UserEvent where instance ToJSON UserEvent instance FromJSON UserEvent data User = User { userName :: UserName , userEmail :: Text , userFollowing :: Set.Set UserName , userFollowedBy :: Set.Set UserName , userHistory :: [UserEvent] , userPinboard :: Set.Set DocumentId , userTags :: Set.Set TagPath , userJoinTime :: UTCTime } deriving (Show, Read, Eq, Ord, Generic,Typeable) deriveSafeCopy 0 'base ''User instance Serialize User where instance ToJSON User instance FromJSON User data UserEvent0 = WroteCritique0 DocumentId CritiqueId | VotedOnCritique0 DocumentId CritiqueId (Maybe UpDownVote) UTCTime | WroteSummary0 DocumentId SummaryId | VotedOnSummary0 DocumentId SummaryId (Maybe UpDownVote) UTCTime | PostedDocument0 DocumentId | FollowedUser0 UserName UTCTime | PinnedDoc0 DocumentId UTCTime deriving (Show, Eq, Ord, Generic, Typeable) deriveSafeCopy 0 'base ''UserEvent0 -- Is there a less boilerplate way to do this? instance Migrate UserEvent where type MigrateFrom UserEvent = UserEvent0 migrate (WroteCritique0 d c) = WroteOComment d c migrate (VotedOnCritique0 d c u t) = VotedOnOComment d c u t migrate (WroteSummary0 d c) = WroteOComment d c migrate (VotedOnSummary0 d c u t) = VotedOnOComment d c u t migrate (PostedDocument0 d) = PostedDocument d migrate (FollowedUser0 un t) = FollowedUser un t migrate (PinnedDoc0 d t) = PinnedDoc d t {- data User0 = User0 { userName0 :: UserName , userEmail0 :: Text , userFollowing0 :: Set.Set UserName , userFollowedBy0 :: Set.Set UserName , userHistory0 :: [UserEvent0] , userPinboard0 :: Set.Set DocumentId , userTags0 :: Set.Set TagPath , userJoinTime0 :: UTCTime } deriving (Show, Eq, Ord, Generic,Typeable) deriveSafeCopy 0 'base ''User0 instance Migrate User where type MigrateFrom User = User0 <<<<<<< HEAD migrate (User0 n e f fb h p t jt) = User n e f fb (Prelude.map migrate h) p t jt ======= migrate (User0 n e f fb h p t jt) = User n e f fb h p t jt >>>>>>> 7fc6b9f38b1bf312e6cd104a1609ec53a6ce8248 -}
imalsogreg/reffit
src/Reffit/User.hs
gpl-3.0
3,518
0
10
1,169
619
331
288
57
0
-- BNF Converter: Error Monad -- Copyright (C) 2004 Author: Aarne Ranta -- This file comes with NO WARRANTY and may be used FOR ANY PURPOSE. module Dict.ErrM where -- the Error monad: like Maybe type with error msgs import Control.Monad (MonadPlus(..), liftM) data Err a = Ok a | Bad String deriving (Read, Show, Eq, Ord) instance Monad Err where return = Ok fail = Bad Ok a >>= f = f a Bad s >>= f = Bad s instance Functor Err where fmap = liftM instance MonadPlus Err where mzero = Bad "Err.mzero" mplus (Bad _) y = y mplus x _ = x
isido/functional-morphology-for-koine-greek
lib/Dict/ErrM.hs
gpl-3.0
580
0
8
153
168
90
78
15
0
module Main where import System.Environment import Control.Monad displayLines :: String -> IO () displayLines fn = do content <- readFile fn let fLines = lines content forM_ fLines putStrLn displayFiles :: [String] -> IO () displayFiles [] = return () displayFiles xs = forM_ xs displayLines main = do args <- getArgs case args of [] -> putStrLn "Usage: cat file [optional: additional files]" xs -> displayFiles xs
aauger/HaskellCoreUtils
HaskellCoreUtils/src/cat.hs
gpl-3.0
427
0
10
80
150
72
78
16
2
module German where import Data.Char import Language data Case = Nom | Acc | Dat | Gen deriving (Show, Eq) instance Language.Case German.Case data AdjectiveInflection = Strong | Mixed | Weak deriving Eq nom, acc, dat, gen :: NounPhrase German.Case -> [String] [nom, acc, dat, gen] = map applyCase [Nom, Acc, Dat, Gen] ---- Morphology ---- eInflect = addSuffix "e" erInflect = addSuffix "er" emInflect = addSuffix "em" esInflect = addSuffix "es" enInflect = let special str | str `elem` ["e", "el", "er"] = str ++ "n" special "en" = "en" in addSpecialSuffix "en" $ maybeize special stInflect = let special c | c `elem` ["s", "ß", "z"] = c ++ "t" special "t" = "test" in addSpecialSuffix "st" $ maybeize special tInflect = let special "t" = "tet" in addSpecialSuffix "t" $ maybeize special teInflect = eInflect . tInflect capitalize [] = [] capitalize (c:cs) = toUpper c : cs ---- Declension ---- byCase nom _ _ _ Nom = nom byCase _ acc _ _ Acc = acc byCase _ _ dat _ Dat = dat byCase _ _ _ gen Gen = gen -- M N F P -- male neutral femaleOrPlural -- en -- em er en -- es er article :: (String, String, String, String, String, String, String) -> Number -> Gender -> German.Case -> String article (male, neutral, femaleOrPlural, en, em, es, er) = let -- Dat|Gen declined number gender c | c == Dat || c == Gen = case (number, gender, c) of (S, F, _) -> er (S, _, Dat) -> em (S, _, Gen) -> es (P, _, Dat) -> en (P, _, Gen) -> er -- Nom|Acc declined S M Nom = male declined S M Acc = en declined S N _ = neutral declined _ _ _ = femaleOrPlural in declined attributiveAdjective :: String -> Number -> Gender -> German.Case -> AdjectiveInflection -> String attributiveAdjective stem = let (e, er, en, em, es) = (eInflect stem, erInflect stem, enInflect stem, emInflect stem, esInflect stem) -- Dat|Gen declined number gender c i | c == Dat || c == Gen = case i of -- In the case of no article, the adjective itself resembles an article Strong -> case (number, gender, c) of (S, F, _) -> er (S, _, Dat) -> em (S, _, Gen) -> en (P, _, Dat) -> en (P, _, Gen) -> er _ -> en -- Nom|Acc: declined P _ _ Strong = e declined P _ _ _ = en -- Mixed|Strong M|N -- Resembles the same corner in article declension (der/den + das) -- Provides gender and case information that would otherwise come from the definite article declined S gender c i | (i == Mixed || i == Strong) && (gender == M || gender == N) = case (gender, c) of (M, Nom) -> er (M, Acc) -> en (N, _) -> es declined S M Acc _ = en declined S _ _ _ = e in declined ---- Words ---- definiteArticle = article ("der", "das", "die", "den", "dem", "des", "der") indefiniteArticle = article ("ein", "ein", "eine", "einen", "einem", "eines", "einer") demonstrativeArticle = article ("dieser", "dieses", "diese", "diesen", "diesem", "dieses", "dieser") [the, an, this] = map modifier [definiteArticle, indefiniteArticle, demonstrativeArticle] -- "dies-" is both a pronoun and an article thisPronoun gender number = (\c -> [demonstrativeArticle number gender c], number, gender, ThirdPerson) personalPronoun :: Person -> Number -> Gender -> German.Case -> String -- Third person pronouns are fairly article-like personalPronoun ThirdPerson number gender c = case (number, gender, c) of (S, F, Dat) -> "ihr" (P, _, Dat) -> "ihnen" _ -> article ("er", "es", "sie", "ihn", "ihm", "seiner", "ihrer") number gender c -- The formal pronoun is the third person plural, capitalised personalPronoun SecondPersonFormal _ _ c = capitalize $ personalPronoun ThirdPerson P N c personalPronoun FirstPerson S _ Nom = "ich" personalPronoun SecondPerson S _ Nom = "du" -- Singular pronouns follow a pattern of the stem indicating person and a suffix for case personalPronoun person S _ c = case person of FirstPerson -> "m" SecondPerson -> "d" ++ case c of Acc -> "ich" Dat -> "ir" Gen -> "einer" -- Plural pronouns are not very patternful personalPronoun FirstPerson P _ c = byCase "wir" "uns" "uns" "unser" c personalPronoun SecondPerson P _ c = byCase "ihr" "euch" "euch" "euer" c reflexivePronoun :: Person -> Number -> Gender -> String reflexivePronoun ThirdPerson _ _ = "sich" reflexivePronoun p n g = personalPronoun p n g Acc -- Interrogative pronouns -- ( what, why, how, when, where_) = ("was", "warum", "wie", "wann", "wo") ( whereTo, whereFrom) = ("wohin", "woher") who = byCase "wer" "wen" "wem" "wessen" which = article ("welcher", "welches", "welche", "welchen", "welchem", "welches", "welcher") ---- Vocabulary ---- cat = noun "katze" "katzen" F girl = noun "mädchen" "mädchen" N -- TODO: capitalize nouns ---- Verb conjugation ---- -- Simple verbs are conjugated for person/number -- The most irregular have five forms e.g. bin bist ist sind seid simpleVerb first second third plural secondPlural number person = case (number, person) of (S, FirstPerson) -> [first] (S, SecondPerson) -> [second] (P, SecondPerson) -> [secondPlural] (S, ThirdPerson) -> [third] (P, _) -> [plural] (_, SecondPersonFormal) -> [plural] -- Verbs are conjugated with -e, -en, -st, or -t and may have a stem change verbWithStemChange firstOrPlural secondOrThirdSingle = simpleVerb (eInflect firstOrPlural) (stInflect secondOrThirdSingle) (tInflect secondOrThirdSingle) (enInflect firstOrPlural) (tInflect firstOrPlural) -- Strong verbs have a change of stem strongVerb firstOrPlural secondOrThirdSingle = verbWithStemChange firstOrPlural secondOrThirdSingle -- Weak verbs are completely regular, all forms are based on one stem weakVerb stem = verbWithStemChange stem stem ---- Words ---- is = simpleVerb "bin" "bist" "ist" "sind" "seid" has = strongVerb "hab" "ha" sleeps = strongVerb "schlaf" "schläf" eats = strongVerb "ess" "iss" comes = strongVerb "komm" "komm" knows = simpleVerb "weiß" "weißt" "weiß" "wissen" "wisst" says = weakVerb "sag" ---- Structures ---- statement :: Clause German.Case statement (subject, number, _, person) verb objects = (subject Nom) ++ (verb number person) ++ (concatMap acc objects) question :: Clause German.Case question (subject, number, _, person) verb objects = -- Verb first (verb number person) ++ (subject Nom) ++ (concatMap acc objects)
Fedjmike/ngen
german.hs
gpl-3.0
6,865
0
16
1,796
2,086
1,145
941
130
13
module Sara.TestUtils.TestUtils where import Sara.Reporter nopReporter :: Reporter nopReporter = Reporter nop nop nop where nop :: a -> IO () nop _ = return ()
Lykos/Sara
tests/Sara/TestUtils/TestUtils.hs
gpl-3.0
172
0
9
38
58
31
27
6
1
module Figure where import Graphics.Rendering.Plot makePlot :: Figure () -> FilePath -> IO () makePlot fig filename = writeFigure SVG filename (1200, 800) fig createMatrixFigure :: Dataset a => a -> Figure () createMatrixFigure m = do setPlots 1 1 withPlot (1,1) $ do setDataset m addAxis XAxis (Side Upper) $ withAxisLabel $ setText "Tace" addAxis YAxis (Side Lower) $ withAxisLabel $ setText "Depth/Time" setRangeFromData XAxis Lower Linear setRangeFromData YAxis Lower Linear --createGraphFigure x y = do -- withTextDefaults $ setFontFamily "OpenSymbol" -- withTitle $ setText "Testing plot package:" -- setPlots 1 1 -- withPlot (1,1) $ do -- setDataset (x,[line y blue, point y black]) -- addAxis XAxis (Side Lower) $ withAxisLabel $ setText "time (s)" -- addAxis YAxis (Side Lower) $ withAxisLabel $ setText "amplitude" -- addAxis XAxis (Value 0) $ return () -- setRangeFromData XAxis Lower Linear -- setRangeFromData YAxis Lower Linear --setRange YAxis Lower Linear (-1.25) 1.25
Toeplitz/haskell
Figure.hs
gpl-3.0
1,043
0
14
209
199
100
99
13
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Numerical.PETSc.Internal.Class.RealVectorSpace -- Copyright : (c) Marco Zocca 2015 -- License : LGPL3 -- Maintainer : zocca . marco . gmail . com -- Stability : experimental -- -- | real vector spaces, dual pairings, normed spaces -- ----------------------------------------------------------------------------- module Numerical.PETSc.Internal.Class.RealVectorSpace where import qualified Data.Vector as V {- |Instances should satisfy the following laws: > forall x,y. x .+. y = y .+. x -- additive commutativity > forall x,y,z. x .+. (y .+. z) = (x .+. y) .+. z -- additive associativity > forall x. vzero .+. x = x -- additive identity > forall x. x .-. x = vzero -- additive inverse > forall x,y. x .-. y = x .+. (-1 *. y) -- subtraction is addition > forall x. 1 *. x = x -- multiplicative identity > forall a,x. (x .* a) ./ a = x -- multiplicative scalar inverse > forall r,x. r *. x = x .* r -- scalar multiplication commutes > forall r,s,x. r *. (s *. x) = (r * s) *. x -- multiplicative associativity > forall r,s,x. (r + s) *. x = r *.x + s *.x -- scalar distributivity > forall r,x,y. r *. (x .+. y) = r *.x + r *.y -- vector distributivity -} class RealVectorSpace v where (.+.) :: v -> v -> v (.-.) :: v -> v -> v infixl 6 .+. infixl 6 .-. (*.) :: Double -> v -> v (.*) :: v -> Double -> v (./) :: v -> Double -> v -- (*.) :: Num a => a -> v -> v -- (.*) :: Num a => v -> a -> v -- (./) :: Fractional a => v -> a -> v infixl 7 *. infixl 7 .* infixl 7 ./ vzero :: v vnegate :: v -> v -- |Default methods (.*) = flip (*.) (*.) = flip (.*) x ./ a = x .* (1/a) x .-. y = x .+. vnegate y vnegate = ((-1) *.) {- |We also encode the notion of a dual vector space, which is a space associated to every real vector space, and consists of all linear functionals on v. Note that the dual space is also a vector space. Instances should satisfy the following laws: > forall m,x,y. m `pairing` (x .+. y) = m `pairing` x + m `pairing` y -- linearity in v > forall m,n,x. (m .+. n) `pairing` x = m `pairing` x + n `pairing` x -- linearity in d > forall a,m,x. m `pairing` (a *. x) = a * (m `pairing` x) -- linearity > forall a,m,x. (a *. m) `pairing` x = a * (m `pairing` x) -- linearity > forall m. m `pairing` vzero = 0 -- zero > forall x. vzero `pairing` x = 0 -- zero -} class (RealVectorSpace d, RealVectorSpace v) => DualPair d v where pairing :: d -> v -> Double {- |An inner product space is a vector space in which an inner (dot) product between vectors exists. Instances should satisfy the following laws: > forall x,y. innerProd x y = innerProd y x -- symmetry > forall a,x,y. innerProd (a *. x) y = a * (innerProd x y) -- linearity > forall x,y,z. innerProd (x .+. y) z = (innerProd x z) + (innerProd y z) -- linearity > forall x. innerProd x x = normSquared x -- compatibility -} -- class (RealNormedSpace a) => RealInnerProductSpace a where -- innerProd :: a -> a -> Double class (RealVectorSpace a) => RealInnerProductSpace a where innerProd :: a -> a -> Double (<.>) :: RealInnerProductSpace v => v -> v -> Double (<.>) = innerProd {- |A normed vector space also includes a 1-homogeneous norm function satisfying the triangle inequality. Instances should satisfy the following laws: > forall x. norm x > 0 -- non-negativity > forall a,x. norm (a *. x) = (abs a) * (norm x) -- 1-homogeneity > forall x,y. norm (x .+. y) <= (norm x) + (norm y) -- triangle inequality In addition, the norm and normSquared functions should be compatible: > forall x. normSquared x = (norm x) * (norm x) Minimal definition: one of `norm` or `normSquared` -} class (RealInnerProductSpace a) => RealNormedSpace a where norm :: a -> Double -- normSquared :: a -> Double -- -- |Default methods. -- norm = sqrt . normSquared -- normSquared x = let n = norm x in n * n -- | testing testing instance RealVectorSpace (V.Vector Double) where (.+.) = V.zipWith (+) vzero = V.singleton 0 (*.) a = V.map (* a) instance RealInnerProductSpace (V.Vector Double) where innerProd a b = V.sum $ V.zipWith (*) a b instance RealNormedSpace (V.Vector Double) where norm a = sqrt $ innerProd a a v0 = V.fromList [1..10] v1 = V.fromList [3, pi .. 10] v2 :: V.Vector Double v2 = v1 .+. v0 v3 = pi *. v2 nv3 = norm v3 --
ocramz/petsc-hs
src/Numerical/PETSc/Internal/Class/RealVectorSpace.hs
gpl-3.0
4,591
0
9
1,044
579
335
244
45
1
module PropT07 where import Prelude(Bool(..)) import Zeno -- Definitions True && x = x _ && _ = False False || x = x _ || _ = True not True = False not False = True -- Nats data Nat = S Nat | Z (+) :: Nat -> Nat -> Nat Z + y = y (S x) + y = S (x + y) (*) :: Nat -> Nat -> Nat Z * _ = Z (S x) * y = y + (x * y) (==),(/=) :: Nat -> Nat -> Bool Z == Z = True Z == _ = False S _ == Z = False S x == S y = x == y x /= y = not (x == y) (<=) :: Nat -> Nat -> Bool Z <= _ = True _ <= Z = False S x <= S y = x <= y one, zero :: Nat zero = Z one = S Z double :: Nat -> Nat double Z = Z double (S x) = S (S (double x)) even :: Nat -> Bool even Z = True even (S Z) = False even (S (S x)) = even x half :: Nat -> Nat half Z = Z half (S Z) = Z half (S (S x)) = S (half x) mult :: Nat -> Nat -> Nat -> Nat mult Z _ acc = acc mult (S x) y acc = mult x y (y + acc) fac :: Nat -> Nat fac Z = S Z fac (S x) = S x * fac x qfac :: Nat -> Nat -> Nat qfac Z acc = acc qfac (S x) acc = qfac x (S x * acc) exp :: Nat -> Nat -> Nat exp _ Z = S Z exp x (S n) = x * exp x n qexp :: Nat -> Nat -> Nat -> Nat qexp x Z acc = acc qexp x (S n) acc = qexp x n (x * acc) -- Lists length :: [a] -> Nat length [] = Z length (_:xs) = S (length xs) (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) drop :: Nat -> [a] -> [a] drop Z xs = xs drop _ [] = [] drop (S x) (_:xs) = drop x xs rev :: [a] -> [a] rev [] = [] rev (x:xs) = rev xs ++ [x] qrev :: [a] -> [a] -> [a] qrev [] acc = acc qrev (x:xs) acc = qrev xs (x:acc) revflat :: [[a]] -> [a] revflat [] = [] revflat ([]:xss) = revflat xss revflat ((x:xs):xss) = revflat (xs:xss) ++ [x] qrevflat :: [[a]] -> [a] -> [a] qrevflat [] acc = acc qrevflat ([]:xss) acc = qrevflat xss acc qrevflat ((x:xs):xss) acc = qrevflat (xs:xss) (x:acc) rotate :: Nat -> [a] -> [a] rotate Z xs = xs rotate _ [] = [] rotate (S n) (x:xs) = rotate n (xs ++ [x]) elem :: Nat -> [Nat] -> Bool elem _ [] = False elem n (x:xs) = n == x || elem n xs subset :: [Nat] -> [Nat] -> Bool subset [] ys = True subset (x:xs) ys = x `elem` xs && subset xs ys intersect,union :: [Nat] -> [Nat] -> [Nat] (x:xs) `intersect` ys | x `elem` ys = x:(xs `intersect` ys) | otherwise = xs `intersect` ys [] `intersect` ys = [] union (x:xs) ys | x `elem` ys = union xs ys | otherwise = x:(union xs ys) union [] ys = ys isort :: [Nat] -> [Nat] isort [] = [] isort (x:xs) = insert x (isort xs) insert :: Nat -> [Nat] -> [Nat] insert n [] = [n] insert n (x:xs) = case n <= x of True -> n : x : xs False -> x : (insert n xs) count :: Nat -> [Nat] -> Nat count n (x:xs) | n == x = S (count n xs) | otherwise = count n xs count n [] = Z sorted :: [Nat] -> Bool sorted (x:y:xs) = x <= y && sorted (y:xs) sorted _ = True -- Theorem prop_T07 :: [a] -> [a] -> Prop prop_T07 x y = prove (length (qrev x y) :=: length x + length y)
danr/hipspec
testsuite/prod/zeno_version/PropT07.hs
gpl-3.0
2,990
0
11
921
2,010
1,045
965
114
2
{- Chapter 4 -} maximum' :: (Ord a) => [a] -> a maximum' [] = error "maximum of empty list!" maximum' [x] = x maximum' (x:xs) = max x (maximum' xs) replicate' :: Int -> a -> [a] replicate' n x | n <= 0 = [] | otherwise = x : replicate' (n-1) x take' :: (Num i, Ord i) => i -> [a] -> [a] take' n _ | n <= 0 = [] take' _ [] = [] take' n (x:xs) = x : take' (n-1) xs reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x] zip' :: [a] -> [b] -> [(a,b)] zip' _ [] = [] zip' [] _ = [] zip' (x:xs) (y:ys) = (x,y):zip' xs ys elem' :: (Eq a) => a -> [a] -> Bool elem' a [] = False elem' a (x:xs) | a == x = True | otherwise = elem a xs
medik/lang-hack
Haskell/LearnYouAHaskell/c04/chapter4.hs
gpl-3.0
688
2
8
200
460
241
219
25
1
module Main where import SLParser import Text.Parsec import VCGenerator import Z3.Monad import Data.List main :: IO () main = do input <- getContents let res = parse parseSL "" input either print (\x -> putStrLn "AST:" >> print x >> putStrLn "" >> do (w,res) <- evalZ3 (script x) mapM_ (\(num,(a,b)) -> putStrLn ("VC "++(show num)++": ") >> putStrLn b >> putStr "Result: " >> treatResult a >> putStrLn "") $ zip [1..] $ zip res w ) res where treatResult Unsat = putStrLn "Valid" treatResult Sat = putStrLn "Invalid" script :: SL -> Z3 ([String],[Result]) script x = do (decls,vcs) <- vcGen x w <- mapM astToString vcs res <- foldr (\(str,k) accum -> if "(= " `isPrefixOf` str then foldrAux1 str k accum else foldrAux2 str k accum ) (return []) $ zip w vcs return (map fst res,map snd res) where foldrAux1 str k accum = solverReset >> solverAssertCnstr k >> solverCheck >>= (\_ -> accum ) foldrAux2 str k accum = solverReset >> mkNot k >>= solverAssertCnstr >> solverCheck >>= (\x -> do { ac <- accum; return ((str,x):ac); } )
jbddc/vf-verifier
src/Main.hs
gpl-3.0
1,126
0
27
285
502
255
247
26
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.UserRoles.Insert -- 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) -- -- Inserts a new user role. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.userRoles.insert@. module Network.Google.Resource.DFAReporting.UserRoles.Insert ( -- * REST Resource UserRolesInsertResource -- * Creating a Request , userRolesInsert , UserRolesInsert -- * Request Lenses , uriProFileId , uriPayload ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.userRoles.insert@ method which the -- 'UserRolesInsert' request conforms to. type UserRolesInsertResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "userRoles" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] UserRole :> Post '[JSON] UserRole -- | Inserts a new user role. -- -- /See:/ 'userRolesInsert' smart constructor. data UserRolesInsert = UserRolesInsert' { _uriProFileId :: !(Textual Int64) , _uriPayload :: !UserRole } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UserRolesInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uriProFileId' -- -- * 'uriPayload' userRolesInsert :: Int64 -- ^ 'uriProFileId' -> UserRole -- ^ 'uriPayload' -> UserRolesInsert userRolesInsert pUriProFileId_ pUriPayload_ = UserRolesInsert' { _uriProFileId = _Coerce # pUriProFileId_ , _uriPayload = pUriPayload_ } -- | User profile ID associated with this request. uriProFileId :: Lens' UserRolesInsert Int64 uriProFileId = lens _uriProFileId (\ s a -> s{_uriProFileId = a}) . _Coerce -- | Multipart request metadata. uriPayload :: Lens' UserRolesInsert UserRole uriPayload = lens _uriPayload (\ s a -> s{_uriPayload = a}) instance GoogleRequest UserRolesInsert where type Rs UserRolesInsert = UserRole type Scopes UserRolesInsert = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient UserRolesInsert'{..} = go _uriProFileId (Just AltJSON) _uriPayload dFAReportingService where go = buildClient (Proxy :: Proxy UserRolesInsertResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/UserRoles/Insert.hs
mpl-2.0
3,221
0
14
741
406
242
164
63
1
{-# LANGUAGE UnicodeSyntax, Rank2Types #-} module Graphics.Gloss.Interface.FRP.Sodium (playSodium, InputEvent) where import Graphics.Gloss import Graphics.Gloss.Interface.IO.Game (playIO) import qualified Graphics.Gloss.Interface.IO.Game as G import FRP.Sodium import Control.Monad (void) -- | A useful type synonym for Gloss event values, to avoid confusion between -- Gloss and Sodium. type InputEvent = G.Event -- | Play the game in a window, updating when the value of the provided -- Behavior Picture changes. playSodium ∷ Display -- ^ The display method → Color -- ^ The background colour → Int -- ^ The refresh rate, in Hertz → ( Event Float → Event InputEvent → Reactive (Behavior Picture)) -- ^ A Reactive action to generate the Picture Behavior, taking -- the refresh and input Events with respect to which to build it. -- The refresh event generates a Float indicating the time delta -- since the last refresh. → IO () playSodium display colour frequency mPicture = do (unreg, bPicture, pushTick, pushInput) ← sync $ do (eTick, pushTick ) ← newEvent (eInput, pushInput) ← newEvent bPicture ← mPicture eTick eInput -- To avoid https://github.com/kentuckyfriedtakahe/sodium/issues/14 unreg ← listen (value bPicture) . const $ return () return (unreg, bPicture, pushTick, pushInput) playIO display colour frequency () (\ _ → sync $ sample bPicture) (\ ev _ → void . sync $ pushInput ev ) (\ time _ → void . sync $ pushTick time ) unreg
Twey/gloss-sodium
Graphics/Gloss/Interface/FRP/Sodium.hs
agpl-3.0
1,679
0
16
432
336
187
149
27
1
import ViperVM.Platform import ViperVM.Platform.Logger import ViperVM.Platform.TransferResult import ViperVM.Platform.LinkCapabilities import ViperVM.Platform.RegionTransferManager import ViperVM.Platform.RegionLockManager import ViperVM.Platform.BufferManager (createBufferManager) import Control.Monad import Text.Printf import qualified Data.Set as Set main :: IO () main = do let config = Configuration { libraryOpenCL = "/usr/lib/libOpenCL.so", logger = stdOutLogger . filterLevel LogDebug } putStrLn "Initializing platform..." platform <- initPlatform config putStrLn "Initializing transfer manager..." bm <- createBufferManager platform rm <- createRegionLockManager bm tm <- createRegionTransferManager rm let bSize = 1024 * 1024 putStrLn $ printf "\nTrying to transfer %d KB on each link..." (bSize `div` 1024) forM_ (links platform) $ \link -> do let (src,dst) = linkEndpoints link Just srcBuf <- allocateBuffer rm src bSize Just dstBuf <- allocateBuffer rm dst bSize let reg = Region1D 0 bSize putStrLn $ "Transferring on " ++ (show link) ++ "... " let tr = RegionTransfer srcBuf reg [RegionTransferStep link dstBuf reg] putStr " - Preparing transfer... " res1 <- prepareRegionTransferIO tm tr if res1 /= PrepareSuccess then putStrLn "ERROR" else putStrLn "SUCCEEDED" putStr " - Performing transfer... " res2 <- performRegionTransfer tm tr if any (/= RegionTransferSuccess) res2 then putStrLn "ERROR" else putStrLn "SUCCEEDED" putStr " - Preparing transfer... " res3 <- prepareRegionTransferIO tm tr if res3 /= PrepareSuccess then putStrLn "ERROR" else putStrLn "SUCCEEDED" putStr " - Performing transfer... " res4 <- performRegionTransfer tm tr if any (/= RegionTransferSuccess) res4 then putStrLn "ERROR" else putStrLn "SUCCEEDED" void $ releaseBuffer rm srcBuf void $ releaseBuffer rm dstBuf putStrLn $ printf "\nTrying to perform multi-step (ping pong) transfer of %d KB on each couple of links..." (bSize `div` 1024) forM_ (links platform) $ \link -> do let (src,dst) = linkEndpoints link -- Find associated reverse link let r = filter (\x -> linkEndpoints x == (dst,src)) (links platform) forM r $ \link2 -> do Just srcBuf <- allocateBuffer rm src bSize Just step1Buf <- allocateBuffer rm dst bSize Just step2Buf <- allocateBuffer rm src bSize Just dstBuf <- allocateBuffer rm dst bSize let reg = Region1D 0 bSize putStrLn $ "Ping-pong through " ++ show link ++ " and " ++ show link2 ++ "... " let tr = RegionTransfer srcBuf reg [ RegionTransferStep link step1Buf reg, RegionTransferStep link2 step2Buf reg, RegionTransferStep link dstBuf reg ] res <- performRegionTransfer tm tr if any (/= RegionTransferSuccess) res then putStrLn "ERROR" else putStrLn "SUCCEEDED" forM_ [srcBuf, step1Buf, step2Buf, dstBuf] (releaseBuffer rm) putStrLn "\nTrying to perform 2D transfer transfer on each link..." forM_ (links platform) $ \link -> do let (src,dst) = linkEndpoints link if Set.notMember Transfer2D (linkCapabilities link) then putStrLn ("2D transfers not supported by link " ++ show link) else do let reg2D = Region2D 0 32 30 2 -- 2 bytes of padding, 32 bytes aligned bsize = 32*32 Just srcBuf <- allocateBuffer rm src bsize Just dstBuf <- allocateBuffer rm dst bsize putStrLn $ "Performing 2D transfer through " ++ show link let tr = RegionTransfer srcBuf reg2D [ RegionTransferStep link dstBuf reg2D ] res <- performRegionTransfer tm tr if any (/= RegionTransferSuccess) res then putStrLn "ERROR" else putStrLn "SUCCEEDED" forM_ [srcBuf, dstBuf] (releaseBuffer rm) putStrLn "Done."
hsyl20/HViperVM
apps/RegionTransferManagerTest.hs
lgpl-3.0
4,192
0
20
1,201
1,109
523
586
91
8
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable #-} -- | Virtual machines control module THIS.Hypervisor (runVM, shutdownVM ) where import Control.Monad import Control.Exception as E import Control.Concurrent import Data.Object import Data.Time import System.LibVirt as V import THIS.Types import THIS.Yaml import THIS.Templates.XML -- | Run VM if needed runVM :: StringObject -> Variables -> VMConfig -> IO () runVM object vars vm = withConnection (vmHypervisor vm) $ \conn -> do putStrLn "connect ok" mbdom <- do x <- E.try $ lookupDomainName conn (vmName vm) case x of Left (e :: V.Error) -> do putStrLn "lookupDomainName:" print e return Nothing Right dom -> return (Just dom) case mbdom of Just dom -> do di <- getDomainInfo dom putStrLn $ "domain got ok: " ++ show di case diState di of DomainRunning -> return () DomainPaused -> do if vmEmpty vm then restoreDomain conn (vmSnapshot vm) >> return () else resumeDomain dom >> return () DomainShutoff -> do if vmEmpty vm then restoreDomain conn (vmSnapshot vm) >> return () else do createDomain dom waitVMStartup vm return () st -> fail $ "Don't know what to do with virtual domain " ++ vmName vm ++ " in state " ++ show st Nothing -> do xml <- forceTHIS XMLTemplateError $ evalXMLFile object vars (vmTemplatePath vm) createDomainXML conn xml [] return () -- | Wait for VM to start up waitVMStartup :: VMConfig -> IO () waitVMStartup vm = do now <- getCurrentTime putStrLn $ "Waiting for VM to start up: " ++ show (vmStartupTime vm) ++ "s" threadDelay (vmStartupTime vm * 1000 * 1000) now' <- getCurrentTime putStrLn $ show now ++ " - " ++ show now' -- | Shutdown VM shutdownVM :: VMConfig -> IO () shutdownVM vm = withConnection (vmHypervisor vm) $ \conn -> do mbdom <- do x <- E.try $ lookupDomainName conn (vmName vm) case x of Left (e :: V.Error) -> do print e return Nothing Right dom -> return (Just dom) case mbdom of Nothing -> fail $ "No such domain on hypervisor: " ++ vmName vm Just dom -> do shutdownDomain dom return ()
portnov/integration-server
THIS/Hypervisor.hs
lgpl-3.0
2,607
0
23
960
747
350
397
69
8
{- - This file is part of Bilder. - - Bilder is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Bilder is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with Bilder. If not, see <http://www.gnu.org/licenses/>. - - Copyright © 2012-2013 Filip Lundborg - Copyright © 2012-2013 Ingemar Ådahl - -} {-# LANGUAGE UnicodeSyntax #-} module Compiler.Simple.ToGLSL where import qualified FrontEnd.AbsGLSL as G import qualified Compiler.Simple.AbsSimple as S -- Simple to GLSL funToPrototype ∷ S.Function → G.TopLevel funToPrototype fun = G.FunctionPrototype (typeToGLSL (S.returnType fun)) -- return type (G.Ident $ S.functionName fun) -- name (map variableToGLSLParam (S.parameters fun)) -- parameters funToGLSL ∷ S.Function → G.TopLevel funToGLSL fun = G.Function (typeToGLSL (S.returnType fun)) -- return type (G.Ident $ S.functionName fun) -- name (map variableToGLSLParam (S.parameters fun)) -- parameters (map stmToGLSL (S.statements fun)) -- statements stmToGLSL ∷ S.Stm → G.Stm stmToGLSL (S.SDecl v) = G.SDecl (varToGLSLDecl v) stmToGLSL (S.SDeclAss v e) = G.SDecl (varToGLSLDeclAss v (expToGLSL e)) stmToGLSL (S.SStruct s) = G.SDecl $ G.Struct (G.Ident $ S.structName s) [G.SVDecl (varToGLSLDecl v) | v ← S.declarations s] stmToGLSL (S.SExp e) = G.SExp $ expToGLSL e stmToGLSL (S.SWhile e ss) = G.SWhile (expToGLSL e) (G.SBlock $ map stmToGLSL ss) stmToGLSL (S.SDoWhile ss e) = G.SDoWhile (G.SBlock $ map stmToGLSL ss) (expToGLSL e) stmToGLSL (S.SFor dss ec el ss) | not $ isForDecl dss && dss /= [] = error $ "compiler error - for statements must only contain SDeclAss or SExp: " ++ show dss | otherwise = G.SFor (map stmToForDecl dss) (map expToGLSL ec) (map expToGLSL el) (G.SBlock $ map stmToGLSL ss) stmToGLSL (S.SReturn e) = G.SReturn (expToGLSL e) stmToGLSL (S.SVoidReturn) = G.SVoidReturn stmToGLSL (S.SIf e ss) = G.SIf (expToGLSL e) (G.SBlock $ map stmToGLSL ss) stmToGLSL (S.SIfElse e sst ssf) = G.SIfElse (expToGLSL e) (G.SBlock $ map stmToGLSL sst) (G.SBlock $ map stmToGLSL ssf) stmToGLSL (S.SBreak) = G.SBreak stmToGLSL (S.SContinue) = G.SContinue stmToGLSL (S.SDiscard) = G.SDiscard stmToForDecl ∷ S.Stm → G.ForDecl stmToForDecl (S.SDeclAss v e) = G.FDecl (varToGLSLDeclAss v (expToGLSL e)) stmToForDecl (S.SExp e) = G.FExp (expToGLSL e) isForDecl ∷ [S.Stm] → Bool isForDecl [] = True isForDecl (S.SDeclAss {}:ss) = isForDecl ss isForDecl (S.SExp {}:ss) = isForDecl ss isForDecl _ = False expToGLSL ∷ S.Exp → G.Exp expToGLSL (S.EAss el er) = G.EAss (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssAdd el er) = G.EAssAdd (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssSub el er) = G.EAssSub (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssMul el er) = G.EAssMul (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssDiv el er) = G.EAssDiv (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssMod el er) = G.EAssMod (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssBWAnd el er) = G.EAssBWAnd (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssBWXOR el er) = G.EAssBWXOR (expToGLSL el) (expToGLSL er) expToGLSL (S.EAssBWOR el er) = G.EAssBWOR (expToGLSL el) (expToGLSL er) expToGLSL (S.ECond ec et ef) = G.ECond (expToGLSL ec) (expToGLSL et) (expToGLSL ef) expToGLSL (S.EOR el er) = G.EOR (expToGLSL el) (expToGLSL er) expToGLSL (S.EXOR el er) = G.EXOR (expToGLSL el) (expToGLSL er) expToGLSL (S.EAnd el er) = G.EAnd (expToGLSL el) (expToGLSL er) expToGLSL (S.EBWOR el er) = G.EBWOR (expToGLSL el) (expToGLSL er) expToGLSL (S.EBWXOR el er) = G.EBWXOR (expToGLSL el) (expToGLSL er) expToGLSL (S.EBWAnd el er) = G.EBWAnd (expToGLSL el) (expToGLSL er) expToGLSL (S.EEqual el er) = G.EEqual (expToGLSL el) (expToGLSL er) expToGLSL (S.ENEqual el er) = G.ENEqual (expToGLSL el) (expToGLSL er) expToGLSL (S.ELt el er) = G.ELt (expToGLSL el) (expToGLSL er) expToGLSL (S.EGt el er) = G.EGt (expToGLSL el) (expToGLSL er) expToGLSL (S.ELEt el er) = G.ELEt (expToGLSL el) (expToGLSL er) expToGLSL (S.EGEt el er) = G.EGEt (expToGLSL el) (expToGLSL er) expToGLSL (S.EBWShiftLeft el er) = G.EBWShiftLeft (expToGLSL el) (expToGLSL er) expToGLSL (S.EBWShiftRight el er) = G.EBWShiftRight (expToGLSL el) (expToGLSL er) expToGLSL (S.EAdd el er) = G.EAdd (expToGLSL el) (expToGLSL er) expToGLSL (S.ESub el er) = G.ESub (expToGLSL el) (expToGLSL er) expToGLSL (S.EMul el er) = G.EMul (expToGLSL el) (expToGLSL er) expToGLSL (S.EDiv el er) = G.EDiv (expToGLSL el) (expToGLSL er) expToGLSL (S.EMod el er) = G.EMod (expToGLSL el) (expToGLSL er) expToGLSL (S.ENeg e) = G.ENeg (expToGLSL e) expToGLSL (S.ENegSign e) = G.ENegSign (expToGLSL e) expToGLSL (S.EComplement e) = G.EComplement (expToGLSL e) expToGLSL (S.EPos e) = G.EPos (expToGLSL e) expToGLSL (S.EPreInc e) = G.EPreInc (expToGLSL e) expToGLSL (S.EPreDec e) = G.EPreDec (expToGLSL e) expToGLSL (S.EPostInc e) = G.EPostInc (expToGLSL e) expToGLSL (S.EPostDec e) = G.EPostDec (expToGLSL e) expToGLSL (S.EMember e i) = G.ESwizzler (expToGLSL e) (G.EVar $ G.Ident i) expToGLSL (S.ECall i es) = G.ECall (G.Ident i) (map expToGLSL es) expToGLSL (S.ETypeCall t es) = G.ETypeCall (typeToGLSL t) (map expToGLSL es) expToGLSL (S.EVar i) = G.EVar (G.Ident i) expToGLSL (S.EIndex ei e) = G.EIndex (expToGLSL ei) (expToGLSL e) expToGLSL (S.EFloat f) = G.EFloat (G.CFloat (show f)) expToGLSL (S.EInt i) = G.EInt i expToGLSL (S.ETrue) = G.ETrue expToGLSL (S.EFalse) = G.EFalse expToGLSL e = error $ "Not implemented: " ++ show e variableToGLSLParam ∷ S.Variable → G.Param variableToGLSLParam var = G.ParamDec [] (typeToGLSL $ S.variableType var) (G.Ident $ S.variableName var) typeToGLSL ∷ S.Type → G.Type typeToGLSL (S.TVoid) = G.TVoid typeToGLSL (S.TFloat) = G.TFloat typeToGLSL (S.TBool) = G.TBool typeToGLSL (S.TInt) = G.TInt typeToGLSL (S.TVec2) = G.TVec2 typeToGLSL (S.TVec3) = G.TVec3 typeToGLSL (S.TVec4) = G.TVec4 typeToGLSL (S.TMat2) = G.TMat2 typeToGLSL (S.TMat3) = G.TMat3 typeToGLSL (S.TMat4) = G.TMat4 typeToGLSL (S.TStruct i) = G.TStruct (G.Ident i) typeToGLSL (S.TSampler) = G.TSampler2D structToGLSL ∷ S.Struct → G.TopLevel structToGLSL s = G.TopDecl $ G.Struct (G.Ident $ S.structName s) (map (G.SVDecl . varToGLSLDecl) (S.declarations s)) varToGLSLDecl ∷ S.Variable → G.Decl varToGLSLDecl var = case S.value var of Nothing → G.Declaration [] -- qualifiers (typeToGLSL $ S.variableType var) -- type [G.Ident $ S.variableName var] -- names Just e → G.DefaultDeclaration [] -- qualifiers (typeToGLSL $ S.variableType var) -- type [G.Ident $ S.variableName var] -- names (expToGLSL e) varToGLSLDeclAss ∷ S.Variable → G.Exp → G.Decl varToGLSLDeclAss var = G.DefaultDeclaration [] -- qualifiers (typeToGLSL $ S.variableType var) -- type [G.Ident $ S.variableName var] -- names
ingemaradahl/bilder
src/Compiler/Simple/ToGLSL.hs
lgpl-3.0
7,285
0
12
1,223
3,074
1,531
1,543
135
2
k = 1000000007 ans m 0 = 1 ans m 1 = m ans m n = let n' = n `div` 2 x = ans m n' y = ans m (n-2*n') in (x * x * y) `mod` k main = do l <- getLine let (m:n:_) = map read $ words l :: [Integer] o = ans m n print o
a143753/AOJ
NTL_1_B.hs
apache-2.0
249
1
12
101
172
84
88
13
1
import Prelude data Tree a = Node (Tree a) a (Tree a) | Empty deriving Show areTreesEqual :: Tree Int -> Tree Int -> Bool areTreesEqual Empty Empty = True areTreesEqual Empty _ = False areTreesEqual _ Empty = False areTreesEqual (Node leftTree1 a rightTree1) (Node leftTree2 b rightTree2) = if a == b then (areTreesEqual leftTree1 leftTree2) && (areTreesEqual rightTree1 rightTree2) else False main :: IO () main = do -- let a = Empty b = Empty in putStrLn $ show (areTreesEqual a b) let a = Empty b = Node Empty 3 (Node Empty 2 Empty) in putStrLn $ show (areTreesEqual a b) let a = Node Empty 3 (Node Empty 2 Empty) b = Empty in putStrLn $ show (areTreesEqual a b) let a = Node Empty 3 (Node Empty 2 Empty) b = Node Empty 3 (Node Empty 2 Empty) in putStrLn $ show (areTreesEqual a b) let a = Node Empty 3 (Node Empty 2 Empty) b = Node (Node Empty 3 (Node Empty 4 Empty)) 3 (Node Empty 2 Empty) in putStrLn $ show (areTreesEqual a b)
omefire/HaskellProjects
areTreesEqual.hs
apache-2.0
1,047
0
15
297
455
223
232
29
2
module Explession where level:: Int -> String -> Int level lv (head:tail) | head == '(' && lv >= 0 = level (lv + 1) tail | head == ')' && lv >= 0 = level (lv - 1) tail | otherwise = lv level lv ([]) = lv {- - Checks whether an expression contains a balanced amount of brackets - Example: - isBalanced "( ( text2 ) and ( test3 ) )" == True - isBalanced " ( text1 ) text2)" == False -} isBalanced:: String -> Bool isBalanced str = level 0 filteredStr == 0 where filteredStr = filter (\a -> a =='(' || a == ')') str
art4ul/HaskellSandbox
Expression.hs
apache-2.0
574
0
12
172
180
92
88
9
1
module Data.Binary.Get.Machine where import Data.ByteString (ByteString) import Data.Binary.Get (Decoder(..), Get, pushChunk, runGetIncremental) import Data.Machine (MachineT(..), ProcessT, Step(Await, Yield), Is(Refl), stopped) processGet :: Monad m => Get a -> ProcessT m ByteString a processGet getA = processDecoder (runGetIncremental getA) processDecoder :: Monad m => Decoder a -> ProcessT m ByteString a processDecoder decA = MachineT . return $ Await f Refl stopped where f xs = case pushChunk decA xs of -- TODO Add `Fail` case Done _ _ a -> MachineT . return $ Yield a stopped decA' -> processDecoder decA'
aloiscochard/thinkgear
src/Data/Binary/Get/Machine.hs
apache-2.0
645
0
11
119
225
122
103
11
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QAbstractTextDocumentLayout.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:18 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QAbstractTextDocumentLayout ( qAbstractTextDocumentLayout ,QblockBoundingRect(..), QqblockBoundingRect(..) ,QdocumentChanged(..) ,QdocumentSize(..), QqdocumentSize(..) ,QdrawInlineObject(..), QqdrawInlineObject(..) ,QformatIndex(..) ,QframeBoundingRect(..), QqframeBoundingRect(..) ,handlerForObject ,QhitTest(..), QqhitTest(..) ,paintDevice ,QpositionInlineObject(..) ,registerHandler ,QresizeInlineObject(..) ,QsetPaintDevice(..) ,qAbstractTextDocumentLayout_delete ,qAbstractTextDocumentLayout_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QAbstractTextDocumentLayout ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractTextDocumentLayout_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QAbstractTextDocumentLayout_userMethod" qtc_QAbstractTextDocumentLayout_userMethod :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO () instance QuserMethod (QAbstractTextDocumentLayoutSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractTextDocumentLayout_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QAbstractTextDocumentLayout ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractTextDocumentLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QAbstractTextDocumentLayout_userMethodVariant" qtc_QAbstractTextDocumentLayout_userMethodVariant :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QAbstractTextDocumentLayoutSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractTextDocumentLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj qAbstractTextDocumentLayout :: (QTextDocument t1) -> IO (QAbstractTextDocumentLayout ()) qAbstractTextDocumentLayout (x1) = withQAbstractTextDocumentLayoutResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout" qtc_QAbstractTextDocumentLayout :: Ptr (TQTextDocument t1) -> IO (Ptr (TQAbstractTextDocumentLayout ())) instance QanchorAt (QAbstractTextDocumentLayout a) ((PointF)) where anchorAt x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QAbstractTextDocumentLayout_anchorAt_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QAbstractTextDocumentLayout_anchorAt_qth" qtc_QAbstractTextDocumentLayout_anchorAt_qth :: Ptr (TQAbstractTextDocumentLayout a) -> CDouble -> CDouble -> IO (Ptr (TQString ())) instance QqanchorAt (QAbstractTextDocumentLayout a) ((QPointF t1)) where qanchorAt x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_anchorAt cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_anchorAt" qtc_QAbstractTextDocumentLayout_anchorAt :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPointF t1) -> IO (Ptr (TQString ())) class QblockBoundingRect x0 x1 where blockBoundingRect :: x0 -> x1 -> IO (RectF) class QqblockBoundingRect x0 x1 where qblockBoundingRect :: x0 -> x1 -> IO (QRectF ()) instance QqblockBoundingRect (QAbstractTextDocumentLayout ()) ((QTextBlock t1)) where qblockBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_blockBoundingRect_h" qtc_QAbstractTextDocumentLayout_blockBoundingRect_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextBlock t1) -> IO (Ptr (TQRectF ())) instance QqblockBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextBlock t1)) where qblockBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_h cobj_x0 cobj_x1 instance QblockBoundingRect (QAbstractTextDocumentLayout ()) ((QTextBlock t1)) where blockBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h foreign import ccall "qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h" qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextBlock t1) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () instance QblockBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextBlock t1)) where blockBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h instance Qdocument (QAbstractTextDocumentLayout a) (()) where document x0 () = withQTextDocumentResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_document cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_document" qtc_QAbstractTextDocumentLayout_document :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQTextDocument ())) class QdocumentChanged x0 x1 where documentChanged :: x0 -> x1 -> IO () instance QdocumentChanged (QAbstractTextDocumentLayout ()) ((Int, Int, Int)) where documentChanged x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentChanged_h cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) foreign import ccall "qtc_QAbstractTextDocumentLayout_documentChanged_h" qtc_QAbstractTextDocumentLayout_documentChanged_h :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> CInt -> CInt -> IO () instance QdocumentChanged (QAbstractTextDocumentLayoutSc a) ((Int, Int, Int)) where documentChanged x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentChanged_h cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) class QdocumentSize x0 x1 where documentSize :: x0 -> x1 -> IO (SizeF) class QqdocumentSize x0 x1 where qdocumentSize :: x0 -> x1 -> IO (QSizeF ()) instance QqdocumentSize (QAbstractTextDocumentLayout ()) (()) where qdocumentSize x0 () = withQSizeFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_h cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_documentSize_h" qtc_QAbstractTextDocumentLayout_documentSize_h :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQSizeF ())) instance QqdocumentSize (QAbstractTextDocumentLayoutSc a) (()) where qdocumentSize x0 () = withQSizeFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_h cobj_x0 instance QdocumentSize (QAbstractTextDocumentLayout ()) (()) where documentSize x0 () = withSizeFResult $ \csizef_ret_w csizef_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_qth_h cobj_x0 csizef_ret_w csizef_ret_h foreign import ccall "qtc_QAbstractTextDocumentLayout_documentSize_qth_h" qtc_QAbstractTextDocumentLayout_documentSize_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr CDouble -> Ptr CDouble -> IO () instance QdocumentSize (QAbstractTextDocumentLayoutSc a) (()) where documentSize x0 () = withSizeFResult $ \csizef_ret_w csizef_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_qth_h cobj_x0 csizef_ret_w csizef_ret_h instance Qdraw (QAbstractTextDocumentLayout ()) ((QPainter t1, PaintContext t2)) where draw x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_draw_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractTextDocumentLayout_draw_h" qtc_QAbstractTextDocumentLayout_draw_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPainter t1) -> Ptr (TPaintContext t2) -> IO () instance Qdraw (QAbstractTextDocumentLayoutSc a) ((QPainter t1, PaintContext t2)) where draw x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_draw_h cobj_x0 cobj_x1 cobj_x2 class QdrawInlineObject x0 x1 where drawInlineObject :: x0 -> x1 -> IO () class QqdrawInlineObject x0 x1 where qdrawInlineObject :: x0 -> x1 -> IO () instance QqdrawInlineObject (QAbstractTextDocumentLayout ()) ((QPainter t1, QRectF t2, QTextInlineObject t3, Int, QTextFormat t5)) where qdrawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 (toCInt x4) cobj_x5 foreign import ccall "qtc_QAbstractTextDocumentLayout_drawInlineObject_h" qtc_QAbstractTextDocumentLayout_drawInlineObject_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPainter t1) -> Ptr (TQRectF t2) -> Ptr (TQTextInlineObject t3) -> CInt -> Ptr (TQTextFormat t5) -> IO () instance QqdrawInlineObject (QAbstractTextDocumentLayoutSc a) ((QPainter t1, QRectF t2, QTextInlineObject t3, Int, QTextFormat t5)) where qdrawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 (toCInt x4) cobj_x5 instance QdrawInlineObject (QAbstractTextDocumentLayout ()) ((QPainter t1, RectF, QTextInlineObject t3, Int, QTextFormat t5)) where drawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h cobj_x3 (toCInt x4) cobj_x5 foreign import ccall "qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h" qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> CDouble -> CDouble -> Ptr (TQTextInlineObject t3) -> CInt -> Ptr (TQTextFormat t5) -> IO () instance QdrawInlineObject (QAbstractTextDocumentLayoutSc a) ((QPainter t1, RectF, QTextInlineObject t3, Int, QTextFormat t5)) where drawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h cobj_x3 (toCInt x4) cobj_x5 instance Qformat (QAbstractTextDocumentLayout ()) ((Int)) (IO (QTextCharFormat ())) where format x0 (x1) = withQTextCharFormatResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_format cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractTextDocumentLayout_format" qtc_QAbstractTextDocumentLayout_format :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO (Ptr (TQTextCharFormat ())) instance Qformat (QAbstractTextDocumentLayoutSc a) ((Int)) (IO (QTextCharFormat ())) where format x0 (x1) = withQTextCharFormatResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_format cobj_x0 (toCInt x1) class QformatIndex x0 x1 where formatIndex :: x0 -> x1 -> IO (Int) instance QformatIndex (QAbstractTextDocumentLayout ()) ((Int)) where formatIndex x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_formatIndex cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractTextDocumentLayout_formatIndex" qtc_QAbstractTextDocumentLayout_formatIndex :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO CInt instance QformatIndex (QAbstractTextDocumentLayoutSc a) ((Int)) where formatIndex x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_formatIndex cobj_x0 (toCInt x1) class QframeBoundingRect x0 x1 where frameBoundingRect :: x0 -> x1 -> IO (RectF) class QqframeBoundingRect x0 x1 where qframeBoundingRect :: x0 -> x1 -> IO (QRectF ()) instance QqframeBoundingRect (QAbstractTextDocumentLayout ()) ((QTextFrame t1)) where qframeBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_frameBoundingRect_h" qtc_QAbstractTextDocumentLayout_frameBoundingRect_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextFrame t1) -> IO (Ptr (TQRectF ())) instance QqframeBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextFrame t1)) where qframeBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_h cobj_x0 cobj_x1 instance QframeBoundingRect (QAbstractTextDocumentLayout ()) ((QTextFrame t1)) where frameBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h foreign import ccall "qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h" qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextFrame t1) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () instance QframeBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextFrame t1)) where frameBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h handlerForObject :: QAbstractTextDocumentLayout a -> ((Int)) -> IO (QTextObjectInterface ()) handlerForObject x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_handlerForObject cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractTextDocumentLayout_handlerForObject" qtc_QAbstractTextDocumentLayout_handlerForObject :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO (Ptr (TQTextObjectInterface ())) class QhitTest x0 x1 where hitTest :: x0 -> x1 -> IO (Int) class QqhitTest x0 x1 where qhitTest :: x0 -> x1 -> IO (Int) instance QhitTest (QAbstractTextDocumentLayout ()) ((PointF, HitTestAccuracy)) where hitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QAbstractTextDocumentLayout_hitTest_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QAbstractTextDocumentLayout_hitTest_qth_h" qtc_QAbstractTextDocumentLayout_hitTest_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> CDouble -> CDouble -> CLong -> IO CInt instance QhitTest (QAbstractTextDocumentLayoutSc a) ((PointF, HitTestAccuracy)) where hitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QAbstractTextDocumentLayout_hitTest_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y (toCLong $ qEnum_toInt x2) instance QqhitTest (QAbstractTextDocumentLayout ()) ((QPointF t1, HitTestAccuracy)) where qhitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_hitTest_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QAbstractTextDocumentLayout_hitTest_h" qtc_QAbstractTextDocumentLayout_hitTest_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPointF t1) -> CLong -> IO CInt instance QqhitTest (QAbstractTextDocumentLayoutSc a) ((QPointF t1, HitTestAccuracy)) where qhitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_hitTest_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QpageCount (QAbstractTextDocumentLayout ()) (()) where pageCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_pageCount_h cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_pageCount_h" qtc_QAbstractTextDocumentLayout_pageCount_h :: Ptr (TQAbstractTextDocumentLayout a) -> IO CInt instance QpageCount (QAbstractTextDocumentLayoutSc a) (()) where pageCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_pageCount_h cobj_x0 paintDevice :: QAbstractTextDocumentLayout a -> (()) -> IO (QPaintDevice ()) paintDevice x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_paintDevice cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_paintDevice" qtc_QAbstractTextDocumentLayout_paintDevice :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQPaintDevice ())) class QpositionInlineObject x0 x1 where positionInlineObject :: x0 -> x1 -> IO () instance QpositionInlineObject (QAbstractTextDocumentLayout ()) ((QTextInlineObject t1, Int, QTextFormat t3)) where positionInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_positionInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractTextDocumentLayout_positionInlineObject_h" qtc_QAbstractTextDocumentLayout_positionInlineObject_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextInlineObject t1) -> CInt -> Ptr (TQTextFormat t3) -> IO () instance QpositionInlineObject (QAbstractTextDocumentLayoutSc a) ((QTextInlineObject t1, Int, QTextFormat t3)) where positionInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_positionInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 registerHandler :: QAbstractTextDocumentLayout a -> ((Int, QObject t2)) -> IO () registerHandler x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_registerHandler cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QAbstractTextDocumentLayout_registerHandler" qtc_QAbstractTextDocumentLayout_registerHandler :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> Ptr (TQObject t2) -> IO () class QresizeInlineObject x0 x1 where resizeInlineObject :: x0 -> x1 -> IO () instance QresizeInlineObject (QAbstractTextDocumentLayout ()) ((QTextInlineObject t1, Int, QTextFormat t3)) where resizeInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_resizeInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractTextDocumentLayout_resizeInlineObject_h" qtc_QAbstractTextDocumentLayout_resizeInlineObject_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextInlineObject t1) -> CInt -> Ptr (TQTextFormat t3) -> IO () instance QresizeInlineObject (QAbstractTextDocumentLayoutSc a) ((QTextInlineObject t1, Int, QTextFormat t3)) where resizeInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_resizeInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 class QsetPaintDevice x1 where setPaintDevice :: QAbstractTextDocumentLayout a -> x1 -> IO () instance QsetPaintDevice ((QPaintDevice t1)) where setPaintDevice x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_setPaintDevice cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_setPaintDevice" qtc_QAbstractTextDocumentLayout_setPaintDevice :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPaintDevice t1) -> IO () instance QsetPaintDevice ((QWidget t1)) where setPaintDevice x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_setPaintDevice_widget cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_setPaintDevice_widget" qtc_QAbstractTextDocumentLayout_setPaintDevice_widget :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQWidget t1) -> IO () qAbstractTextDocumentLayout_delete :: QAbstractTextDocumentLayout a -> IO () qAbstractTextDocumentLayout_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_delete cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_delete" qtc_QAbstractTextDocumentLayout_delete :: Ptr (TQAbstractTextDocumentLayout a) -> IO () qAbstractTextDocumentLayout_deleteLater :: QAbstractTextDocumentLayout a -> IO () qAbstractTextDocumentLayout_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_deleteLater cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_deleteLater" qtc_QAbstractTextDocumentLayout_deleteLater :: Ptr (TQAbstractTextDocumentLayout a) -> IO () instance QchildEvent (QAbstractTextDocumentLayout ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_childEvent" qtc_QAbstractTextDocumentLayout_childEvent :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QAbstractTextDocumentLayoutSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QAbstractTextDocumentLayout ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_connectNotify" qtc_QAbstractTextDocumentLayout_connectNotify :: Ptr (TQAbstractTextDocumentLayout a) -> CWString -> IO () instance QconnectNotify (QAbstractTextDocumentLayoutSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QAbstractTextDocumentLayout ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_customEvent" qtc_QAbstractTextDocumentLayout_customEvent :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QAbstractTextDocumentLayoutSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QAbstractTextDocumentLayout ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_disconnectNotify" qtc_QAbstractTextDocumentLayout_disconnectNotify :: Ptr (TQAbstractTextDocumentLayout a) -> CWString -> IO () instance QdisconnectNotify (QAbstractTextDocumentLayoutSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_disconnectNotify cobj_x0 cstr_x1 instance Qevent (QAbstractTextDocumentLayout ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_event_h" qtc_QAbstractTextDocumentLayout_event_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QAbstractTextDocumentLayoutSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_event_h cobj_x0 cobj_x1 instance QeventFilter (QAbstractTextDocumentLayout ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractTextDocumentLayout_eventFilter_h" qtc_QAbstractTextDocumentLayout_eventFilter_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QAbstractTextDocumentLayoutSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QAbstractTextDocumentLayout ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_receivers" qtc_QAbstractTextDocumentLayout_receivers :: Ptr (TQAbstractTextDocumentLayout a) -> CWString -> IO CInt instance Qreceivers (QAbstractTextDocumentLayoutSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_receivers cobj_x0 cstr_x1 instance Qsender (QAbstractTextDocumentLayout ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_sender cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_sender" qtc_QAbstractTextDocumentLayout_sender :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQObject ())) instance Qsender (QAbstractTextDocumentLayoutSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_sender cobj_x0 instance QtimerEvent (QAbstractTextDocumentLayout ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_timerEvent" qtc_QAbstractTextDocumentLayout_timerEvent :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QAbstractTextDocumentLayoutSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QAbstractTextDocumentLayout.hs
bsd-2-clause
28,773
0
18
3,961
7,795
3,973
3,822
-1
-1
{-# LANGUAGE BangPatterns #-} import Control.Concurrent.STM as S import qualified STMContainers.Map as TMap import qualified ListT as LT import qualified Data.ByteString.Char8 as L import Control.Monad import Debug.Trace import System.Random import Control.Concurrent.Async import Options type Key = Int type StoredObject = L.ByteString data Change = Update Key StoredObject | Remove Key deriving (Show, Eq) type AppState = (TMap.Map Key StoredObject, TVar [Change]) traceKey :: [Change] -> [Key] traceKey changes = [ case c of Update key _ -> key Remove key -> key | c <- changes ] update :: AppState -> [Change] -> Bool -> IO AppState update appState !changes useChangeLog = atomically $ do let (tm, changeLog) = appState sequence_ [ case c of Update key val -> do v <- TMap.lookup key tm case v of Nothing -> TMap.insert val key tm Just _ -> return () Remove key -> TMap.delete key tm | c <- changes ] when useChangeLog $ modifyTVar' changeLog (\log_ -> changes ++ log_) -- trace ("processing: " ++ show (traceKey changes)) $ return (tm, changeLog) randString :: Int -> IO L.ByteString randString n = liftM (L.pack . take n . randomRs ('a','z')) newStdGen randStringFake n = return $ L.pack $ replicate n 'z' randInt :: Int -> IO Int randInt n = liftM (fst . randomR (1, n)) newStdGen randUpdateSet :: Int -> IO [Change] randUpdateSet n = do !i <- randInt n replicateM i $ do (!k1, !v1) <- (,) <$> randInt 4000000000 <*> randStringFake 1000 return $ Update k1 v1 updater :: AppState -> Int -> Bool -> IO () updater state changes useChangeLog = replicateM_ changes $ do !changeSet <- randUpdateSet 250 void $ update state changeSet useChangeLog data Opts = Opts Int Int Bool instance Options Opts where defineOptions = pure Opts <*> simpleOption "threads" 10 "Number of threads" <*> simpleOption "changes" 50 "Number of changes" <*> simpleOption "use-change-log" True "Use change log or not" main :: IO () main = runCommand $ \(Opts threads changes useChangeLog) _ -> do initState <- atomically $ (,) <$> TMap.new <*> newTVar [] as <- replicateM threads $ async $ updater initState changes useChangeLog mapM_ wait as -- force all the data to be calculated s <- atomically $ LT.toList $ TMap.stream $ fst initState trace ("length = " ++ show (length s)) $ return ()
lolepezy/rpki-pub-server
test/changeLog/changeLogList.hs
bsd-2-clause
2,612
107
10
729
807
437
370
61
3
{-# LANGUAGE RecordWildCards #-} -- | A map from hashable keys to values. module Data.DAWG.Gen.HashMap ( Hash (..) , HashMap (..) , empty , lookup , insertUnsafe , lookupUnsafe , deleteUnsafe ) where import Prelude hiding (lookup) -- import Control.Applicative ((<$>), (<*>)) -- import Data.Binary (Binary, Get, put, get) import qualified Data.Map as M import qualified Data.IntMap as I --------------------------------------------------------------- -- Hash Class --------------------------------------------------------------- -- | Class for types which provide hash values. class Ord a => Hash a where hash :: a -> Int instance Hash Int where hash = id instance Hash Bool where hash b = hash $ if b then 1 :: Int else 0 instance Hash a => Hash (Maybe a) where hash (Just x) | h < 0 = h | otherwise = h + 1 where h = hash x hash Nothing = 0 --------------------------------------------------------------- -- HashMap Values --------------------------------------------------------------- -- | Value in a HashMap. data Value a b = Single !a !b | Multi !(M.Map a b) deriving (Show, Eq, Ord) -- | Value Binary instance. -- instance (Ord a, Binary a, Binary b) => Binary (Value a b) where -- put (Single x y) = put (1 :: Int) >> put x >> put y -- put (Multi m) = put (2 :: Int) >> put m -- get = do -- x <- get :: Get Int -- case x of -- 1 -> Single <$> get <*> get -- _ -> Multi <$> get -- | Find element associated to a value key. find :: Ord a => a -> Value a b -> Maybe b find x (Single x' y) = if x == x' then Just y else Nothing find x (Multi m) = M.lookup x m -- | Unsafe `find` version. -- Assumption: element is a member of the 'Value'. findUnsafe :: Ord a => a -> Value a b -> Maybe b findUnsafe _ (Single _ y) = Just y -- unsafe findUnsafe x (Multi m) = M.lookup x m -- | Convert a regular map into a hash value (and into a 'Single' -- form if possible). trySingle :: M.Map a b -> Value a b trySingle m = if M.size m == 1 then uncurry Single (M.findMin m) else Multi m -- | Insert (key, valye) pair into a hash value. embed :: Ord a => a -> b -> Value a b -> Value a b embed x y (Single x' y') = Multi $ M.fromList [(x, y), (x', y')] embed x y (Multi m) = Multi $ M.insert x y m -- | Delete element from a value. Return 'Nothing' if the resultant -- value is empty. It is unsafe because, if the value is -- `Single`, it assumes that it contains the given key. ejectUnsafe :: Ord a => a -> Value a b -> Maybe (Value a b) ejectUnsafe _ (Single _ _) = Nothing -- unsafe ejectUnsafe x (Multi m) = (Just . trySingle) (M.delete x m) --------------------------------------------------------------- -- HashMap --------------------------------------------------------------- -- | A map from /a/ keys to /b/ elements where keys instantiate the -- 'Hash' type class. Key/element pairs are kept in 'Value' objects -- which takes care of potential hash collisions. data HashMap a b = HashMap { size :: {-# UNPACK #-} !Int , hashMap :: !(I.IntMap (Value a b)) } deriving (Show, Eq, Ord) -- instance (Ord a, Binary a, Binary b) => Binary (HashMap a b) where -- put HashMap{..} = put size >> put hashMap -- get = HashMap <$> get <*> get -- | Empty map. empty :: HashMap a b empty = HashMap 0 I.empty -- | Lookup element in the map. lookup :: Hash a => a -> HashMap a b -> Maybe b lookup x (HashMap _ m) = I.lookup (hash x) m >>= find x -- | Unsafe version of `lookup`. -- Assumption: element is present in the map. lookupUnsafe :: Hash a => a -> HashMap a b -> b lookupUnsafe x (HashMap _ m) = fromJust (I.lookup (hash x) m >>= findUnsafe x) -- | Insert a new element. The function doesn't check -- if the element is already present in the map. -- Q: What's the unsafe element? If the only unsafety here is -- that the HashMap size is incremented anyway, maybe it would be -- better to make it safe? insertUnsafe :: Hash a => a -> b -> HashMap a b -> HashMap a b insertUnsafe x y (HashMap n m) = let i = hash x f (Just v) = embed x y v f Nothing = Single x y in HashMap (n + 1) $ I.alter (Just . f) i m -- | Assumption: element is present in the map. deleteUnsafe :: Hash a => a -> HashMap a b -> HashMap a b deleteUnsafe x (HashMap n m) = HashMap (n - 1) $ I.update (ejectUnsafe x) (hash x) m --------------------------------------------------------------- -- Utils --------------------------------------------------------------- -- | A custom version of `fromJust`. fromJust :: Maybe a -> a fromJust (Just x) = x fromJust Nothing = error "fromJust: Nothing" {-# INLINE fromJust #-}
kawu/dawg-ord
src/Data/DAWG/Gen/HashMap.hs
bsd-2-clause
4,762
0
13
1,141
1,197
631
566
77
2
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.OpCodes ( testOpCodes , OpCodes.OpCode(..) ) where import Test.HUnit as HUnit import Test.QuickCheck as QuickCheck import Control.Applicative import Control.Monad import Data.Char import Data.List import qualified Data.Map as Map import qualified Text.JSON as J import Text.Printf (printf) import Test.Ganeti.Objects () import Test.Ganeti.Query.Language () import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Types (genReasonTrail) import Ganeti.BasicTypes import qualified Ganeti.Constants as C import qualified Ganeti.ConstantUtils as CU import qualified Ganeti.OpCodes as OpCodes import Ganeti.Types import Ganeti.OpParams import Ganeti.JSON {-# ANN module "HLint: ignore Use camelCase" #-} -- * Arbitrary instances arbitraryOpTagsGet :: Gen OpCodes.OpCode arbitraryOpTagsGet = do kind <- arbitrary OpCodes.OpTagsSet kind <$> genTags <*> genOpCodesTagName kind arbitraryOpTagsSet :: Gen OpCodes.OpCode arbitraryOpTagsSet = do kind <- arbitrary OpCodes.OpTagsSet kind <$> genTags <*> genOpCodesTagName kind arbitraryOpTagsDel :: Gen OpCodes.OpCode arbitraryOpTagsDel = do kind <- arbitrary OpCodes.OpTagsDel kind <$> genTags <*> genOpCodesTagName kind $(genArbitrary ''OpCodes.ReplaceDisksMode) $(genArbitrary ''DiskAccess) instance Arbitrary OpCodes.DiskIndex where arbitrary = choose (0, C.maxDisks - 1) >>= OpCodes.mkDiskIndex instance Arbitrary INicParams where arbitrary = INicParams <$> genMaybe genNameNE <*> genMaybe genName <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genName <*> genMaybe genNameNE <*> genMaybe genNameNE instance Arbitrary IDiskParams where arbitrary = IDiskParams <$> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNameNE <*> genAndRestArguments instance Arbitrary RecreateDisksInfo where arbitrary = oneof [ pure RecreateDisksAll , RecreateDisksIndices <$> arbitrary , RecreateDisksParams <$> arbitrary ] instance Arbitrary DdmOldChanges where arbitrary = oneof [ DdmOldIndex <$> arbitrary , DdmOldMod <$> arbitrary ] instance (Arbitrary a) => Arbitrary (SetParamsMods a) where arbitrary = oneof [ pure SetParamsEmpty , SetParamsDeprecated <$> arbitrary , SetParamsNew <$> arbitrary ] instance Arbitrary ExportTarget where arbitrary = oneof [ ExportTargetLocal <$> genNodeNameNE , ExportTargetRemote <$> pure [] ] arbitraryDataCollector :: Gen (Container Bool) arbitraryDataCollector = do els <- listOf . elements $ CU.toList C.dataCollectorNames activation <- vector $ length els return . GenericContainer . Map.fromList $ zip els activation arbitraryDataCollectorInterval :: Gen (Maybe (Container Int)) arbitraryDataCollectorInterval = do els <- listOf . elements $ CU.toList C.dataCollectorNames intervals <- vector $ length els genMaybe . return . containerFromList $ zip els intervals instance Arbitrary OpCodes.OpCode where arbitrary = do op_id <- elements OpCodes.allOpIDs case op_id of "OP_TEST_DELAY" -> OpCodes.OpTestDelay <$> arbitrary <*> arbitrary <*> genNodeNamesNE <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_REPLACE_DISKS" -> OpCodes.OpInstanceReplaceDisks <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> genDiskIndices <*> genMaybe genNodeNameNE <*> return Nothing <*> genMaybe genNameNE "OP_INSTANCE_FAILOVER" -> OpCodes.OpInstanceFailover <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_INSTANCE_MIGRATE" -> OpCodes.OpInstanceMigrate <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> arbitrary "OP_TAGS_GET" -> arbitraryOpTagsGet "OP_TAGS_SEARCH" -> OpCodes.OpTagsSearch <$> genNameNE "OP_TAGS_SET" -> arbitraryOpTagsSet "OP_TAGS_DEL" -> arbitraryOpTagsDel "OP_CLUSTER_POST_INIT" -> pure OpCodes.OpClusterPostInit "OP_CLUSTER_RENEW_CRYPTO" -> OpCodes.OpClusterRenewCrypto <$> arbitrary <*> arbitrary "OP_CLUSTER_DESTROY" -> pure OpCodes.OpClusterDestroy "OP_CLUSTER_QUERY" -> pure OpCodes.OpClusterQuery "OP_CLUSTER_VERIFY" -> OpCodes.OpClusterVerify <$> arbitrary <*> arbitrary <*> genListSet Nothing <*> genListSet Nothing <*> arbitrary <*> genMaybe genNameNE "OP_CLUSTER_VERIFY_CONFIG" -> OpCodes.OpClusterVerifyConfig <$> arbitrary <*> arbitrary <*> genListSet Nothing <*> arbitrary "OP_CLUSTER_VERIFY_GROUP" -> OpCodes.OpClusterVerifyGroup <$> genNameNE <*> arbitrary <*> arbitrary <*> genListSet Nothing <*> genListSet Nothing <*> arbitrary "OP_CLUSTER_VERIFY_DISKS" -> pure OpCodes.OpClusterVerifyDisks "OP_GROUP_VERIFY_DISKS" -> OpCodes.OpGroupVerifyDisks <$> genNameNE "OP_CLUSTER_REPAIR_DISK_SIZES" -> OpCodes.OpClusterRepairDiskSizes <$> genNodeNamesNE "OP_CLUSTER_CONFIG_QUERY" -> OpCodes.OpClusterConfigQuery <$> genFieldsNE "OP_CLUSTER_RENAME" -> OpCodes.OpClusterRename <$> genNameNE "OP_CLUSTER_SET_PARAMS" -> OpCodes.OpClusterSetParams <$> arbitrary -- force <*> emptyMUD -- hv_state <*> emptyMUD -- disk_state <*> genMaybe genName -- vg_name <*> genMaybe arbitrary -- enabled_hypervisors <*> genMaybe genEmptyContainer -- hvparams <*> emptyMUD -- beparams <*> genMaybe genEmptyContainer -- os_hvp <*> genMaybe genEmptyContainer -- osparams <*> genMaybe genEmptyContainer -- osparams_private_cluster <*> genMaybe genEmptyContainer -- diskparams <*> genMaybe arbitrary -- candidate_pool_size <*> genMaybe arbitrary -- max_running_jobs <*> genMaybe arbitrary -- max_tracked_jobs <*> arbitrary -- uid_pool <*> arbitrary -- add_uids <*> arbitrary -- remove_uids <*> arbitrary -- maintain_node_health <*> arbitrary -- prealloc_wipe_disks <*> arbitrary -- nicparams <*> emptyMUD -- ndparams <*> emptyMUD -- ipolicy <*> genMaybe genPrintableAsciiString -- drbd_helper <*> genMaybe genPrintableAsciiString -- default_iallocator <*> emptyMUD -- default_iallocator_params <*> genMaybe genMacPrefix -- mac_prefix <*> genMaybe genPrintableAsciiString -- master_netdev <*> arbitrary -- master_netmask <*> genMaybe (listOf genPrintableAsciiStringNE) -- reserved_lvs <*> genMaybe (listOf ((,) <$> arbitrary <*> genPrintableAsciiStringNE)) -- hidden_os <*> genMaybe (listOf ((,) <$> arbitrary <*> genPrintableAsciiStringNE)) -- blacklisted_os <*> arbitrary -- use_external_mip_script <*> arbitrary -- enabled_disk_templates <*> arbitrary -- modify_etc_hosts <*> genMaybe genName -- file_storage_dir <*> genMaybe genName -- shared_file_storage_dir <*> genMaybe genName -- gluster_file_storage_dir <*> genMaybe genPrintableAsciiString -- install_image <*> genMaybe genPrintableAsciiString -- instance_communication_network <*> genMaybe genPrintableAsciiString -- zeroing_image <*> genMaybe (listOf genPrintableAsciiStringNE) -- compression_tools <*> arbitrary -- enabled_user_shutdown <*> genMaybe arbitraryDataCollector -- enabled_data_collectors <*> arbitraryDataCollectorInterval -- data_collector_interval "OP_CLUSTER_REDIST_CONF" -> pure OpCodes.OpClusterRedistConf "OP_CLUSTER_ACTIVATE_MASTER_IP" -> pure OpCodes.OpClusterActivateMasterIp "OP_CLUSTER_DEACTIVATE_MASTER_IP" -> pure OpCodes.OpClusterDeactivateMasterIp "OP_QUERY" -> OpCodes.OpQuery <$> arbitrary <*> arbitrary <*> genNamesNE <*> pure Nothing "OP_QUERY_FIELDS" -> OpCodes.OpQueryFields <$> arbitrary <*> genMaybe genNamesNE "OP_OOB_COMMAND" -> OpCodes.OpOobCommand <$> genNodeNamesNE <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> (arbitrary `suchThat` (>0)) "OP_NODE_REMOVE" -> OpCodes.OpNodeRemove <$> genNodeNameNE <*> return Nothing "OP_NODE_ADD" -> OpCodes.OpNodeAdd <$> genNodeNameNE <*> emptyMUD <*> emptyMUD <*> genMaybe genNameNE <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> arbitrary <*> emptyMUD <*> arbitrary "OP_NODE_QUERYVOLS" -> OpCodes.OpNodeQueryvols <$> genNamesNE <*> genNodeNamesNE "OP_NODE_QUERY_STORAGE" -> OpCodes.OpNodeQueryStorage <$> genNamesNE <*> arbitrary <*> genNodeNamesNE <*> genMaybe genNameNE "OP_NODE_MODIFY_STORAGE" -> OpCodes.OpNodeModifyStorage <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> pure emptyJSObject "OP_REPAIR_NODE_STORAGE" -> OpCodes.OpRepairNodeStorage <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> arbitrary "OP_NODE_SET_PARAMS" -> OpCodes.OpNodeSetParams <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> emptyMUD <*> emptyMUD <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> emptyMUD <*> arbitrary "OP_NODE_POWERCYCLE" -> OpCodes.OpNodePowercycle <$> genNodeNameNE <*> return Nothing <*> arbitrary "OP_NODE_MIGRATE" -> OpCodes.OpNodeMigrate <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_NODE_EVACUATE" -> OpCodes.OpNodeEvacuate <$> arbitrary <*> genNodeNameNE <*> return Nothing <*> genMaybe genNodeNameNE <*> return Nothing <*> genMaybe genNameNE <*> arbitrary "OP_INSTANCE_CREATE" -> OpCodes.OpInstanceCreate <$> genFQDN -- instance_name <*> arbitrary -- force_variant <*> arbitrary -- wait_for_sync <*> arbitrary -- name_check <*> arbitrary -- ignore_ipolicy <*> arbitrary -- opportunistic_locking <*> pure emptyJSObject -- beparams <*> arbitrary -- disks <*> arbitrary -- disk_template <*> genMaybe genNameNE -- group_name <*> arbitrary -- file_driver <*> genMaybe genNameNE -- file_storage_dir <*> pure emptyJSObject -- hvparams <*> arbitrary -- hypervisor <*> genMaybe genNameNE -- iallocator <*> arbitrary -- identify_defaults <*> arbitrary -- ip_check <*> arbitrary -- conflicts_check <*> arbitrary -- mode <*> arbitrary -- nics <*> arbitrary -- no_install <*> pure emptyJSObject -- osparams <*> genMaybe arbitraryPrivateJSObj -- osparams_private <*> genMaybe arbitraryPrivateJSObj -- osparams_secret <*> genMaybe genNameNE -- os_type <*> genMaybe genNodeNameNE -- pnode <*> return Nothing -- pnode_uuid <*> genMaybe genNodeNameNE -- snode <*> return Nothing -- snode_uuid <*> genMaybe (pure []) -- source_handshake <*> genMaybe genNodeNameNE -- source_instance_name <*> arbitrary -- source_shutdown_timeout <*> genMaybe genNodeNameNE -- source_x509_ca <*> return Nothing -- src_node <*> genMaybe genNodeNameNE -- src_node_uuid <*> genMaybe genNameNE -- src_path <*> genPrintableAsciiString -- compress <*> arbitrary -- start <*> (genTags >>= mapM mkNonEmpty) -- tags <*> arbitrary -- instance_communication <*> arbitrary -- helper_startup_timeout <*> arbitrary -- helper_shutdown_timeout "OP_INSTANCE_MULTI_ALLOC" -> OpCodes.OpInstanceMultiAlloc <$> arbitrary <*> genMaybe genNameNE <*> pure [] "OP_INSTANCE_REINSTALL" -> OpCodes.OpInstanceReinstall <$> genFQDN <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> genMaybe (pure emptyJSObject) <*> genMaybe arbitraryPrivateJSObj <*> genMaybe arbitraryPrivateJSObj "OP_INSTANCE_REMOVE" -> OpCodes.OpInstanceRemove <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary "OP_INSTANCE_RENAME" -> OpCodes.OpInstanceRename <$> genFQDN <*> return Nothing <*> genNodeNameNE <*> arbitrary <*> arbitrary "OP_INSTANCE_STARTUP" -> OpCodes.OpInstanceStartup <$> genFQDN <*> -- instance_name return Nothing <*> -- instance_uuid arbitrary <*> -- force arbitrary <*> -- ignore_offline_nodes pure emptyJSObject <*> -- hvparams pure emptyJSObject <*> -- beparams arbitrary <*> -- no_remember arbitrary <*> -- startup_paused arbitrary -- shutdown_timeout "OP_INSTANCE_SHUTDOWN" -> OpCodes.OpInstanceShutdown <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_REBOOT" -> OpCodes.OpInstanceReboot <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_MOVE" -> OpCodes.OpInstanceMove <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> genNodeNameNE <*> return Nothing <*> genPrintableAsciiString <*> arbitrary "OP_INSTANCE_CONSOLE" -> OpCodes.OpInstanceConsole <$> genFQDN <*> return Nothing "OP_INSTANCE_ACTIVATE_DISKS" -> OpCodes.OpInstanceActivateDisks <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary "OP_INSTANCE_DEACTIVATE_DISKS" -> OpCodes.OpInstanceDeactivateDisks <$> genFQDN <*> return Nothing <*> arbitrary "OP_INSTANCE_RECREATE_DISKS" -> OpCodes.OpInstanceRecreateDisks <$> genFQDN <*> return Nothing <*> arbitrary <*> genNodeNamesNE <*> return Nothing <*> genMaybe genNameNE "OP_INSTANCE_QUERY_DATA" -> OpCodes.OpInstanceQueryData <$> arbitrary <*> genNodeNamesNE <*> arbitrary "OP_INSTANCE_SET_PARAMS" -> OpCodes.OpInstanceSetParams <$> genFQDN -- instance_name <*> return Nothing -- instance_uuid <*> arbitrary -- force <*> arbitrary -- force_variant <*> arbitrary -- ignore_ipolicy <*> arbitrary -- nics <*> arbitrary -- disks <*> pure emptyJSObject -- beparams <*> arbitrary -- runtime_mem <*> pure emptyJSObject -- hvparams <*> arbitrary -- disk_template <*> pure emptyJSObject -- ext_params <*> arbitrary -- file_driver <*> genMaybe genNameNE -- file_storage_dir <*> genMaybe genNodeNameNE -- pnode <*> return Nothing -- pnode_uuid <*> genMaybe genNodeNameNE -- remote_node <*> return Nothing -- remote_node_uuid <*> genMaybe genNameNE -- os_name <*> pure emptyJSObject -- osparams <*> genMaybe arbitraryPrivateJSObj -- osparams_private <*> arbitrary -- wait_for_sync <*> arbitrary -- offline <*> arbitrary -- conflicts_check <*> arbitrary -- hotplug <*> arbitrary -- hotplug_if_possible <*> arbitrary -- instance_communication "OP_INSTANCE_GROW_DISK" -> OpCodes.OpInstanceGrowDisk <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_CHANGE_GROUP" -> OpCodes.OpInstanceChangeGroup <$> genFQDN <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> genMaybe (resize maxNodes (listOf genNameNE)) "OP_GROUP_ADD" -> OpCodes.OpGroupAdd <$> genNameNE <*> arbitrary <*> emptyMUD <*> genMaybe genEmptyContainer <*> emptyMUD <*> emptyMUD <*> emptyMUD "OP_GROUP_ASSIGN_NODES" -> OpCodes.OpGroupAssignNodes <$> genNameNE <*> arbitrary <*> genNodeNamesNE <*> return Nothing "OP_GROUP_SET_PARAMS" -> OpCodes.OpGroupSetParams <$> genNameNE <*> arbitrary <*> emptyMUD <*> genMaybe genEmptyContainer <*> emptyMUD <*> emptyMUD <*> emptyMUD "OP_GROUP_REMOVE" -> OpCodes.OpGroupRemove <$> genNameNE "OP_GROUP_RENAME" -> OpCodes.OpGroupRename <$> genNameNE <*> genNameNE "OP_GROUP_EVACUATE" -> OpCodes.OpGroupEvacuate <$> genNameNE <*> arbitrary <*> genMaybe genNameNE <*> genMaybe genNamesNE <*> arbitrary <*> arbitrary "OP_OS_DIAGNOSE" -> OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE "OP_EXT_STORAGE_DIAGNOSE" -> OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE "OP_BACKUP_PREPARE" -> OpCodes.OpBackupPrepare <$> genFQDN <*> return Nothing <*> arbitrary "OP_BACKUP_EXPORT" -> OpCodes.OpBackupExport <$> genFQDN <*> return Nothing <*> genPrintableAsciiString <*> arbitrary <*> arbitrary <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe (pure []) <*> genMaybe genNameNE <*> arbitrary <*> arbitrary <*> arbitrary "OP_BACKUP_REMOVE" -> OpCodes.OpBackupRemove <$> genFQDN <*> return Nothing "OP_TEST_ALLOCATOR" -> OpCodes.OpTestAllocator <$> arbitrary <*> arbitrary <*> genNameNE <*> genMaybe (pure []) <*> genMaybe (pure []) <*> arbitrary <*> genMaybe genNameNE <*> (genTags >>= mapM mkNonEmpty) <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNodeNamesNE <*> arbitrary <*> genMaybe genNamesNE <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_TEST_JQUEUE" -> OpCodes.OpTestJqueue <$> arbitrary <*> arbitrary <*> resize 20 (listOf genFQDN) <*> arbitrary "OP_TEST_DUMMY" -> OpCodes.OpTestDummy <$> pure J.JSNull <*> pure J.JSNull <*> pure J.JSNull <*> pure J.JSNull "OP_NETWORK_ADD" -> OpCodes.OpNetworkAdd <$> genNameNE <*> genIPv4Network <*> genMaybe genIPv4Address <*> pure Nothing <*> pure Nothing <*> genMaybe genMacPrefix <*> genMaybe (listOf genIPv4Address) <*> arbitrary <*> (genTags >>= mapM mkNonEmpty) "OP_NETWORK_REMOVE" -> OpCodes.OpNetworkRemove <$> genNameNE <*> arbitrary "OP_NETWORK_SET_PARAMS" -> OpCodes.OpNetworkSetParams <$> genNameNE <*> genMaybe genIPv4Address <*> pure Nothing <*> pure Nothing <*> genMaybe genMacPrefix <*> genMaybe (listOf genIPv4Address) <*> genMaybe (listOf genIPv4Address) "OP_NETWORK_CONNECT" -> OpCodes.OpNetworkConnect <$> genNameNE <*> genNameNE <*> arbitrary <*> genNameNE <*> genPrintableAsciiString <*> arbitrary "OP_NETWORK_DISCONNECT" -> OpCodes.OpNetworkDisconnect <$> genNameNE <*> genNameNE "OP_RESTRICTED_COMMAND" -> OpCodes.OpRestrictedCommand <$> arbitrary <*> genNodeNamesNE <*> return Nothing <*> genNameNE _ -> fail $ "Undefined arbitrary for opcode " ++ op_id instance Arbitrary OpCodes.CommonOpParams where arbitrary = OpCodes.CommonOpParams <$> arbitrary <*> arbitrary <*> arbitrary <*> resize 5 arbitrary <*> genMaybe genName <*> genReasonTrail -- * Helper functions -- | Empty JSObject. emptyJSObject :: J.JSObject J.JSValue emptyJSObject = J.toJSObject [] -- | Empty maybe unchecked dictionary. emptyMUD :: Gen (Maybe (J.JSObject J.JSValue)) emptyMUD = genMaybe $ pure emptyJSObject -- | Generates an empty container. genEmptyContainer :: (Ord a) => Gen (GenericContainer a b) genEmptyContainer = pure . GenericContainer $ Map.fromList [] -- | Generates list of disk indices. genDiskIndices :: Gen [DiskIndex] genDiskIndices = do cnt <- choose (0, C.maxDisks) genUniquesList cnt arbitrary -- | Generates a list of node names. genNodeNames :: Gen [String] genNodeNames = resize maxNodes (listOf genFQDN) -- | Generates a list of node names in non-empty string type. genNodeNamesNE :: Gen [NonEmptyString] genNodeNamesNE = genNodeNames >>= mapM mkNonEmpty -- | Gets a node name in non-empty type. genNodeNameNE :: Gen NonEmptyString genNodeNameNE = genFQDN >>= mkNonEmpty -- | Gets a name (non-fqdn) in non-empty type. genNameNE :: Gen NonEmptyString genNameNE = genName >>= mkNonEmpty -- | Gets a list of names (non-fqdn) in non-empty type. genNamesNE :: Gen [NonEmptyString] genNamesNE = resize maxNodes (listOf genNameNE) -- | Returns a list of non-empty fields. genFieldsNE :: Gen [NonEmptyString] genFieldsNE = genFields >>= mapM mkNonEmpty -- | Generate a 3-byte MAC prefix. genMacPrefix :: Gen NonEmptyString genMacPrefix = do octets <- vectorOf 3 $ choose (0::Int, 255) mkNonEmpty . intercalate ":" $ map (printf "%02x") octets -- | JSObject of arbitrary data. -- -- Since JSValue does not implement Arbitrary, I'll simply generate -- (String, String) objects. arbitraryPrivateJSObj :: Gen (J.JSObject (Private J.JSValue)) arbitraryPrivateJSObj = constructor <$> (fromNonEmpty <$> genNameNE) <*> (fromNonEmpty <$> genNameNE) where constructor k v = showPrivateJSObject [(k, v)] -- | Arbitrary instance for MetaOpCode, defined here due to TH ordering. $(genArbitrary ''OpCodes.MetaOpCode) -- | Small helper to check for a failed JSON deserialisation isJsonError :: J.Result a -> Bool isJsonError (J.Error _) = True isJsonError _ = False -- * Test cases -- | Check that opcode serialization is idempotent. prop_serialization :: OpCodes.OpCode -> Property prop_serialization = testSerialisation -- | Check that Python and Haskell defined the same opcode list. case_AllDefined :: HUnit.Assertion case_AllDefined = do py_stdout <- runPython "from ganeti import opcodes\n\ \from ganeti import serializer\n\ \import sys\n\ \print serializer.Dump([opid for opid in opcodes.OP_MAPPING])\n" "" >>= checkPythonResult py_ops <- case J.decode py_stdout::J.Result [String] of J.Ok ops -> return ops J.Error msg -> HUnit.assertFailure ("Unable to decode opcode names: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode opcode names" let hs_ops = sort OpCodes.allOpIDs extra_py = py_ops \\ hs_ops extra_hs = hs_ops \\ py_ops HUnit.assertBool ("Missing OpCodes from the Haskell code:\n" ++ unlines extra_py) (null extra_py) HUnit.assertBool ("Extra OpCodes in the Haskell code code:\n" ++ unlines extra_hs) (null extra_hs) -- | Custom HUnit test case that forks a Python process and checks -- correspondence between Haskell-generated OpCodes and their Python -- decoded, validated and re-encoded version. -- -- Note that we have a strange beast here: since launching Python is -- expensive, we don't do this via a usual QuickProperty, since that's -- slow (I've tested it, and it's indeed quite slow). Rather, we use a -- single HUnit assertion, and in it we manually use QuickCheck to -- generate 500 opcodes times the number of defined opcodes, which -- then we pass in bulk to Python. The drawbacks to this method are -- two fold: we cannot control the number of generated opcodes, since -- HUnit assertions don't get access to the test options, and for the -- same reason we can't run a repeatable seed. We should probably find -- a better way to do this, for example by having a -- separately-launched Python process (if not running the tests would -- be skipped). case_py_compat_types :: HUnit.Assertion case_py_compat_types = do let num_opcodes = length OpCodes.allOpIDs * 100 opcodes <- genSample (vectorOf num_opcodes (arbitrary::Gen OpCodes.MetaOpCode)) let with_sum = map (\o -> (OpCodes.opSummary $ OpCodes.metaOpCode o, o)) opcodes serialized = J.encode opcodes -- check for non-ASCII fields, usually due to 'arbitrary :: String' mapM_ (\op -> when (any (not . isAscii) (J.encode op)) . HUnit.assertFailure $ "OpCode has non-ASCII fields: " ++ show op ) opcodes py_stdout <- runPython "from ganeti import opcodes\n\ \from ganeti import serializer\n\ \import sys\n\ \op_data = serializer.Load(sys.stdin.read())\n\ \decoded = [opcodes.OpCode.LoadOpCode(o) for o in op_data]\n\ \for op in decoded:\n\ \ op.Validate(True)\n\ \encoded = [(op.Summary(), op.__getstate__())\n\ \ for op in decoded]\n\ \print serializer.Dump(\ \ encoded,\ \ private_encoder=serializer.EncodeWithPrivateFields)" serialized >>= checkPythonResult let deserialised = J.decode py_stdout::J.Result [(String, OpCodes.MetaOpCode)] decoded <- case deserialised of J.Ok ops -> return ops J.Error msg -> HUnit.assertFailure ("Unable to decode opcodes: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode opcodes" HUnit.assertEqual "Mismatch in number of returned opcodes" (length decoded) (length with_sum) mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding") ) $ zip with_sum decoded -- | Custom HUnit test case that forks a Python process and checks -- correspondence between Haskell OpCodes fields and their Python -- equivalent. case_py_compat_fields :: HUnit.Assertion case_py_compat_fields = do let hs_fields = sort $ map (\op_id -> (op_id, OpCodes.allOpFields op_id)) OpCodes.allOpIDs py_stdout <- runPython "from ganeti import opcodes\n\ \import sys\n\ \from ganeti import serializer\n\ \fields = [(k, sorted([p[0] for p in v.OP_PARAMS]))\n\ \ for k, v in opcodes.OP_MAPPING.items()]\n\ \print serializer.Dump(fields)" "" >>= checkPythonResult let deserialised = J.decode py_stdout::J.Result [(String, [String])] py_fields <- case deserialised of J.Ok v -> return $ sort v J.Error msg -> HUnit.assertFailure ("Unable to decode op fields: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode op fields" HUnit.assertEqual "Mismatch in number of returned opcodes" (length hs_fields) (length py_fields) HUnit.assertEqual "Mismatch in defined OP_IDs" (map fst hs_fields) (map fst py_fields) mapM_ (\((py_id, py_flds), (hs_id, hs_flds)) -> do HUnit.assertEqual "Mismatch in OP_ID" py_id hs_id HUnit.assertEqual ("Mismatch in fields for " ++ hs_id) py_flds hs_flds ) $ zip hs_fields py_fields -- | Checks that setOpComment works correctly. prop_setOpComment :: OpCodes.MetaOpCode -> String -> Property prop_setOpComment op comment = let (OpCodes.MetaOpCode common _) = OpCodes.setOpComment comment op in OpCodes.opComment common ==? Just comment -- | Tests wrong (negative) disk index. prop_mkDiskIndex_fail :: QuickCheck.Positive Int -> Property prop_mkDiskIndex_fail (Positive i) = case mkDiskIndex (negate i) of Bad msg -> printTestCase "error message " $ "Invalid value" `isPrefixOf` msg Ok v -> failTest $ "Succeeded to build disk index '" ++ show v ++ "' from negative value " ++ show (negate i) -- | Tests a few invalid 'readRecreateDisks' cases. case_readRecreateDisks_fail :: Assertion case_readRecreateDisks_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result RecreateDisksInfo) assertBool "string" $ isJsonError (J.readJSON (J.showJSON "abc")::J.Result RecreateDisksInfo) -- | Tests a few invalid 'readDdmOldChanges' cases. case_readDdmOldChanges_fail :: Assertion case_readDdmOldChanges_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result DdmOldChanges) assertBool "string" $ isJsonError (J.readJSON (J.showJSON "abc")::J.Result DdmOldChanges) -- | Tests a few invalid 'readExportTarget' cases. case_readExportTarget_fail :: Assertion case_readExportTarget_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result ExportTarget) assertBool "int" $ isJsonError (J.readJSON (J.showJSON (5::Int))::J.Result ExportTarget) testSuite "OpCodes" [ 'prop_serialization , 'case_AllDefined , 'case_py_compat_types , 'case_py_compat_fields , 'prop_setOpComment , 'prop_mkDiskIndex_fail , 'case_readRecreateDisks_fail , 'case_readDdmOldChanges_fail , 'case_readExportTarget_fail ]
ganeti-github-testing/ganeti-test-1
test/hs/Test/Ganeti/OpCodes.hs
bsd-2-clause
33,826
0
55
10,176
5,802
2,918
2,884
573
2
-- 228 import Data.List(sort) import Euler(splitOn) parseTris [] = [] parseTris (x:xs) = t : parseTris xs where xy = map read $ splitOn ',' x t = sort $ zipWith toTheta (map (xy!!) [0,2,4]) (map (xy!!) [1,3,5]) toTheta a b = atan2 b a containsOrigin xs | length xs /= 3 = error "containsOrigin: length" | otherwise = all (\x -> -pi < x && x < pi) [b-a, c-b, a-c+2*pi] where [a,b,c] = take 3 xs numWithOrigin ws = length $ filter id os where ts = parseTris ws os = map containsOrigin ts main = do contents <- readFile "../files/p102_triangles.txt" putStrLn $ show $ numWithOrigin $ lines contents
higgsd/euler
hs/102.hs
bsd-2-clause
658
4
11
173
327
168
159
17
1
{-# LANGUAGE OverloadedStrings #-} module Appoint.Users where import Control.Lens import Control.Monad.Reader import Data.Monoid ((<>)) import Appoint.Types.Config import Appoint.Types.Users (User(..), Collaborators(..)) import qualified Data.Text as T import qualified Data.Vector as V import qualified GitHub.Data as GitHub import qualified GitHub.Endpoints.Repos.Collaborators as GitHub collaboratorsOn :: ReaderT Config IO (Either GitHub.Error (V.Vector GitHub.SimpleUser)) collaboratorsOn = do config <- ask liftIO $ GitHub.collaboratorsOn' (config ^. cAuth) (config ^. cOwner) (config ^. cRepo) mkUser :: GitHub.SimpleUser -> User mkUser u = User { userName = gitHubUserName u , profileURL = GitHub.getUrl (GitHub.simpleUserUrl u) } gitHubUserName :: GitHub.SimpleUser -> T.Text gitHubUserName = GitHub.untagName . GitHub.simpleUserLogin mkCollaborators :: GitHub.Name GitHub.Owner -> GitHub.Name GitHub.Repo -> [GitHub.SimpleUser] -> [Collaborators] mkCollaborators name' repo' users' = [ Collaborators { _path = GitHub.untagName name' <> "/" <> GitHub.untagName repo' , _users = map mkUser users' }]
rob-b/appoint
src/Appoint/Users.hs
bsd-3-clause
1,168
0
11
193
339
193
146
35
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module Futhark.Pass.ExtractKernels.BlockedKernel ( blockedReduction , blockedReductionStream , blockedMap , blockedScan , blockedSegmentedScan , blockedKernelSize , chunkLambda , mapKernel , mapKernelFromBody , KernelInput(..) , mapKernelSkeleton , newKernelSpace ) where import Control.Applicative import Control.Monad import Data.Maybe import Data.Monoid import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import Prelude import Futhark.Representation.Kernels import Futhark.MonadFreshNames import Futhark.Tools import Futhark.Transform.Rename import Futhark.Transform.FirstOrderTransform (doLoopMapAccumL) import Futhark.Representation.AST.Attributes.Aliases import qualified Futhark.Analysis.Alias as Alias import Futhark.Util blockedReductionStream :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> Certificates -> SubExp -> Commutativity -> Lambda -> Lambda -> [SubExp] -> [VName] -> m [Binding] blockedReductionStream pat cs w comm reduce_lam fold_lam nes arrs = runBinder_ $ do step_one_size <- blockedKernelSize w let one = constant (1 :: Int32) num_chunks = kernelWorkgroups step_one_size let (acc_idents, arr_idents) = splitAt (length nes) $ patternIdents pat step_one_pat <- basicPattern' [] <$> ((++) <$> mapM (mkIntermediateIdent num_chunks) acc_idents <*> pure arr_idents) let (_fold_chunk_param, _fold_acc_params, _fold_inp_params) = partitionChunkedFoldParameters (length nes) $ lambdaParams fold_lam fold_lam' <- kerneliseLambda nes fold_lam my_index <- newVName "my_index" other_offset <- newVName "other_offset" let my_index_param = Param my_index (Prim int32) other_offset_param = Param other_offset (Prim int32) reduce_lam' = reduce_lam { lambdaParams = my_index_param : other_offset_param : lambdaParams reduce_lam } params_to_arrs = zip (map paramName $ drop 1 $ lambdaParams fold_lam') arrs consumedArray v = fromMaybe v $ lookup v params_to_arrs consumed_in_fold = HS.map consumedArray $ consumedByLambda $ Alias.analyseLambda fold_lam arrs_copies <- forM arrs $ \arr -> if arr `HS.member` consumed_in_fold then letExp (baseString arr <> "_copy") $ PrimOp $ Copy arr else return arr step_one <- chunkedReduceKernel cs w step_one_size comm reduce_lam' fold_lam' nes arrs_copies addBinding =<< renameBinding (Let step_one_pat () $ Op step_one) step_two_pat <- basicPattern' [] <$> mapM (mkIntermediateIdent $ constant (1 :: Int32)) acc_idents let step_two_size = KernelSize one num_chunks one num_chunks one num_chunks step_two <- reduceKernel [] step_two_size reduce_lam' nes $ take (length nes) $ patternNames step_one_pat addBinding $ Let step_two_pat () $ Op step_two forM_ (zip (patternNames step_two_pat) (patternIdents pat)) $ \(arr, x) -> addBinding $ mkLet' [] [x] $ PrimOp $ Index [] arr [constant (0 :: Int32)] where mkIntermediateIdent chunk_size ident = newIdent (baseString $ identName ident) $ arrayOfRow (identType ident) chunk_size chunkedReduceKernel :: (MonadBinder m, Lore m ~ Kernels) => Certificates -> SubExp -> KernelSize -> Commutativity -> Lambda -> Lambda -> [SubExp] -> [VName] -> m (Kernel Kernels) chunkedReduceKernel cs w step_one_size comm reduce_lam' fold_lam' nes arrs = do let ordering = case comm of Commutative -> Disorder Noncommutative -> InOrder group_size = kernelWorkgroupSize step_one_size num_nonconcat = length nes (chunk_red_pes, chunk_map_pes, chunk_and_fold) <- blockedPerThread w step_one_size ordering fold_lam' num_nonconcat arrs space <- newKernelSpace (kernelWorkgroups step_one_size, group_size, kernelNumThreads step_one_size) [] let red_ts = map patElemType chunk_red_pes map_ts = map (rowType . patElemType) chunk_map_pes ts = red_ts ++ map_ts chunk_red_pes' <- forM red_ts $ \red_t -> do pe_name <- newVName "chunk_fold_red" return $ PatElem pe_name BindVar $ red_t `arrayOfRow` group_size let combine_reds = [ Combine pe' [(spaceLocalId space, group_size)] $ Var $ patElemName pe | (pe', pe) <- zip chunk_red_pes' chunk_red_pes ] final_red_pes <- forM (lambdaReturnType reduce_lam') $ \t -> do pe_name <- newVName "final_result" return $ PatElem pe_name BindVar t let reduce_chunk = GroupReduce final_red_pes group_size reduce_lam' $ zip nes $ map patElemName chunk_red_pes' red_rets <- forM final_red_pes $ \pe -> return $ ThreadsReturn (OneThreadPerGroup (constant (0::Int32))) $ Var $ patElemName pe map_rets <- forM chunk_map_pes $ \pe -> return $ ConcatReturns ordering w (kernelElementsPerThread step_one_size) $ patElemName pe let rets = red_rets ++ map_rets return $ Kernel cs space ts $ KernelBody (chunk_and_fold++combine_reds++[reduce_chunk]) rets reduceKernel :: (MonadBinder m, Lore m ~ Kernels) => Certificates -> KernelSize -> Lambda -> [SubExp] -> [VName] -> m (Kernel Kernels) reduceKernel cs step_two_size reduce_lam' nes arrs = do let group_size = kernelWorkgroupSize step_two_size red_ts = lambdaReturnType reduce_lam' space <- newKernelSpace (kernelWorkgroups step_two_size, group_size, kernelNumThreads step_two_size) [] let thread_id = spaceGlobalId space (copy_input, arrs_index) <- fmap unzip $ forM (zip red_ts arrs) $ \(t, arr) -> do arr_index <- newVName (baseString arr ++ "_index") return (Thread AllThreads $ Let (Pattern [] [PatElem arr_index BindVar t]) () $ PrimOp $ Index [] arr [Var thread_id] , arr_index) (combine_arrs, arrs') <- fmap unzip $ forM (zip red_ts arrs_index) $ \(red_t, arr_index) -> do arr' <- newVName $ baseString arr_index ++ "_combined" let pe = PatElem arr' BindVar $ red_t `arrayOfRow` group_size return (Combine pe [(spaceLocalId space, group_size)] (Var arr_index), arr') final_res_pes <- forM (lambdaReturnType reduce_lam') $ \t -> do pe_name <- newVName "final_result" return $ PatElem pe_name BindVar t let reduce = GroupReduce final_res_pes group_size reduce_lam' $ zip nes arrs' rets <- forM final_res_pes $ \pe -> return $ ThreadsReturn (OneThreadPerGroup (constant (0::Int32))) $ Var $ patElemName pe return $ Kernel cs space (lambdaReturnType reduce_lam') $ KernelBody (copy_input++combine_arrs++[reduce]) rets chunkLambda :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> [SubExp] -> Lambda -> m Lambda chunkLambda pat nes fold_lam = do chunk_size <- newVName "chunk_size" let arr_idents = drop (length nes) $ patternIdents pat (fold_acc_params, fold_arr_params) = splitAt (length nes) $ lambdaParams fold_lam chunk_size_param = Param chunk_size (Prim int32) arr_chunk_params <- mapM (mkArrChunkParam $ Var chunk_size) fold_arr_params map_arr_params <- forM arr_idents $ \arr -> newParam (baseString (identName arr) <> "_in") $ setOuterSize (identType arr) (Var chunk_size) fold_acc_params' <- forM fold_acc_params $ \p -> newParam (baseString $ paramName p) $ paramType p let param_scope = scopeOfLParams $ fold_acc_params' ++ arr_chunk_params ++ map_arr_params (seq_loop, seq_loop_prologue) <- runBinder $ localScope param_scope $ doLoopMapAccumL [] (Var chunk_size) (Alias.analyseLambda fold_lam) (map (Var . paramName) fold_acc_params') (map paramName arr_chunk_params) (map paramName map_arr_params) dummys <- mapM (newIdent "dummy" . paramType) arr_chunk_params let seq_rt = let (acc_ts, arr_ts) = splitAt (length nes) $ lambdaReturnType fold_lam in acc_ts ++ map (`arrayOfRow` Var chunk_size) arr_ts res_idents = zipWith Ident (patternValueNames pat) seq_rt seq_loop_bnd = mkLet' [] (dummys++res_idents) seq_loop seq_body = mkBody (seq_loop_prologue++[seq_loop_bnd]) $ map (Var . identName) res_idents return Lambda { lambdaParams = chunk_size_param : fold_acc_params' ++ arr_chunk_params ++ map_arr_params , lambdaReturnType = seq_rt , lambdaBody = seq_body } where mkArrChunkParam chunk_size arr_param = newParam (baseString (paramName arr_param) <> "_chunk") $ arrayOfRow (paramType arr_param) chunk_size -- | Given a chunked fold lambda that takes its initial accumulator -- value as parameters, bind those parameters to the neutral element -- instead. Also fix the index computation. kerneliseLambda :: MonadFreshNames m => [SubExp] -> Lambda -> m Lambda kerneliseLambda nes lam = do thread_index <- newVName "thread_index" let thread_index_param = Param thread_index $ Prim int32 (fold_chunk_param, fold_acc_params, fold_inp_params) = partitionChunkedFoldParameters (length nes) $ lambdaParams lam mkAccInit p (Var v) | not $ primType $ paramType p = mkLet' [] [paramIdent p] $ PrimOp $ Copy v mkAccInit p x = mkLet' [] [paramIdent p] $ PrimOp $ SubExp x acc_init_bnds = zipWith mkAccInit fold_acc_params nes return lam { lambdaBody = insertBindings acc_init_bnds $ lambdaBody lam , lambdaParams = thread_index_param : fold_chunk_param : fold_inp_params } blockedReduction :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> Certificates -> SubExp -> Commutativity -> Lambda -> Lambda -> [SubExp] -> [VName] -> m [Binding] blockedReduction pat cs w comm reduce_lam fold_lam nes arrs = runBinder_ $ do fold_lam' <- chunkLambda pat nes fold_lam let arr_idents = drop (length nes) $ patternIdents pat map_out_arrs <- forM arr_idents $ \(Ident name t) -> letExp (baseString name <> "_out_in") $ PrimOp $ Scratch (elemType t) (arrayDims t) mapM_ addBinding =<< blockedReductionStream pat cs w comm reduce_lam fold_lam' nes (arrs ++ map_out_arrs) blockedMap :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> Certificates -> SubExp -> StreamOrd -> Lambda -> [SubExp] -> [VName] -> m (Binding, [Binding]) blockedMap concat_pat cs w ordering lam nes arrs = runBinder $ do kernel_size <- blockedKernelSize w let num_nonconcat = length (lambdaReturnType lam) - patternSize concat_pat num_groups = kernelWorkgroups kernel_size group_size = kernelWorkgroupSize kernel_size num_threads = kernelNumThreads kernel_size lam' <- kerneliseLambda nes lam (chunk_red_pes, chunk_map_pes, chunk_and_fold) <- blockedPerThread w kernel_size ordering lam' num_nonconcat arrs nonconcat_pat <- fmap (Pattern []) $ forM (take num_nonconcat $ lambdaReturnType lam) $ \t -> do name <- newVName "nonconcat" return $ PatElem name BindVar $ t `arrayOfRow` num_threads let pat = nonconcat_pat <> concat_pat ts = map patElemType chunk_red_pes ++ map (rowType . patElemType) chunk_map_pes nonconcat_rets <- forM chunk_red_pes $ \pe -> return $ ThreadsReturn AllThreads $ Var $ patElemName pe concat_rets <- forM chunk_map_pes $ \pe -> return $ ConcatReturns ordering w (kernelElementsPerThread kernel_size) $ patElemName pe space <- newKernelSpace (num_groups, group_size, num_threads) [] return $ Let pat () $ Op $ Kernel cs space ts $ KernelBody chunk_and_fold $ nonconcat_rets ++ concat_rets blockedPerThread :: MonadFreshNames m => SubExp -> KernelSize -> StreamOrd -> Lambda -> Int -> [VName] -> m ([PatElem], [PatElem], [KernelStm Kernels]) blockedPerThread w kernel_size ordering lam num_nonconcat arrs = do let (_, chunk_size, [], arr_params) = partitionChunkedKernelFoldParameters 0 $ lambdaParams lam split_bound <- forM arr_params $ \arr_param -> do let chunk_t = paramType arr_param `setOuterSize` Var (paramName chunk_size) return $ PatElem (paramName arr_param) BindVar chunk_t let chunk_stm = SplitArray (paramName chunk_size, split_bound) ordering w (kernelElementsPerThread kernel_size) arrs red_ts = take num_nonconcat $ lambdaReturnType lam map_ts = map rowType $ drop num_nonconcat $ lambdaReturnType lam chunk_red_pes <- forM red_ts $ \red_t -> do pe_name <- newVName "chunk_fold_red" return $ PatElem pe_name BindVar red_t chunk_map_pes <- forM map_ts $ \map_t -> do pe_name <- newVName "chunk_fold_map" return $ PatElem pe_name BindVar $ map_t `arrayOfRow` Var (paramName chunk_size) let (chunk_red_ses, chunk_map_ses) = splitAt num_nonconcat $ bodyResult $ lambdaBody lam fold_chunk = map (Thread AllThreads) (bodyBindings (lambdaBody lam)) ++ [ Thread AllThreads $ Let (Pattern [] [pe]) () $ PrimOp $ SubExp se | (pe,se) <- zip chunk_red_pes chunk_red_ses ] ++ [ Thread AllThreads $ Let (Pattern [] [pe]) () $ PrimOp $ SubExp se | (pe,se) <- zip chunk_map_pes chunk_map_ses ] return (chunk_red_pes, chunk_map_pes, chunk_stm : fold_chunk) blockedKernelSize :: (MonadBinder m, Lore m ~ Kernels) => SubExp -> m KernelSize blockedKernelSize w = do num_groups <- letSubExp "num_groups" $ Op NumGroups group_size <- letSubExp "group_size" $ Op GroupSize num_threads <- letSubExp "num_threads" $ PrimOp $ BinOp (Mul Int32) num_groups group_size per_thread_elements <- letSubExp "per_thread_elements" =<< eDivRoundingUp Int32 (eSubExp w) (eSubExp num_threads) return $ KernelSize num_groups group_size per_thread_elements w per_thread_elements num_threads blockedScan :: (MonadBinder m, Lore m ~ Kernels) => Pattern -> Certificates -> SubExp -> Lambda -> Lambda -> [SubExp] -> [VName] -> m () blockedScan pat cs w lam foldlam nes arrs = do first_scan_size <- blockedKernelSize w my_index <- newVName "my_index" other_index <- newVName "other_index" let num_groups = kernelWorkgroups first_scan_size group_size = kernelWorkgroupSize first_scan_size num_threads = kernelNumThreads first_scan_size my_index_param = Param my_index (Prim int32) other_index_param = Param other_index (Prim int32) first_scan_foldlam <- renameLambda foldlam { lambdaParams = my_index_param : other_index_param : lambdaParams foldlam } first_scan_lam <- renameLambda lam { lambdaParams = my_index_param : other_index_param : lambdaParams lam } let (scan_idents, arr_idents) = splitAt (length nes) $ patternIdents pat final_res_pat = Pattern [] $ take (length nes) $ patternValueElements pat first_scan_pat <- basicPattern' [] <$> (((.).(.)) (++) (++) <$> -- Dammit Haskell mapM (mkIntermediateIdent "seq_scanned" [w]) scan_idents <*> mapM (mkIntermediateIdent "group_sums" [num_groups]) scan_idents <*> pure arr_idents) addBinding $ Let first_scan_pat () $ Op $ ScanKernel cs w first_scan_size first_scan_lam first_scan_foldlam nes arrs let (sequentially_scanned, group_carry_out, _) = splitAt3 (length nes) (length nes) $ patternNames first_scan_pat let second_scan_size = KernelSize one num_groups one num_groups one num_groups second_scan_lam <- renameLambda first_scan_lam second_scan_lam_renamed <- renameLambda first_scan_lam group_carry_out_scanned <- letTupExp "group_carry_out_scanned" $ Op $ ScanKernel cs num_groups second_scan_size second_scan_lam second_scan_lam_renamed nes group_carry_out lam''' <- renameLambda lam j <- newVName "j" let (acc_params, arr_params) = splitAt (length nes) $ lambdaParams lam''' result_map_input = zipWith (mkKernelInput [Var j]) arr_params sequentially_scanned chunks_per_group <- letSubExp "chunks_per_group" =<< eDivRoundingUp Int32 (eSubExp w) (eSubExp num_threads) elems_per_group <- letSubExp "elements_per_group" $ PrimOp $ BinOp (Mul Int32) chunks_per_group group_size result_map_body <- runBodyBinder $ localScope (scopeOfLParams $ map kernelInputParam result_map_input) $ do group_id <- letSubExp "group_id" $ PrimOp $ BinOp (SQuot Int32) (Var j) elems_per_group let do_nothing = pure $ resultBody $ map (Var . paramName) arr_params add_carry_in = runBodyBinder $ do forM_ (zip acc_params group_carry_out_scanned) $ \(p, arr) -> do carry_in_index <- letSubExp "carry_in_index" $ PrimOp $ BinOp (Sub Int32) group_id one letBindNames'_ [paramName p] $ PrimOp $ Index [] arr [carry_in_index] return $ lambdaBody lam''' group_lasts <- letTupExp "final_result" =<< eIf (eCmpOp (CmpEq int32) (eSubExp zero) (eSubExp group_id)) do_nothing add_carry_in return $ resultBody $ map Var group_lasts (mapk_bnds, mapk) <- mapKernelFromBody [] w [(j, w)] result_map_input (lambdaReturnType lam) result_map_body mapM_ addBinding mapk_bnds letBind_ final_res_pat $ Op mapk where one = constant (1 :: Int32) zero = constant (0 :: Int32) mkIntermediateIdent desc shape ident = newIdent (baseString (identName ident) ++ "_" ++ desc) $ arrayOf (rowType $ identType ident) (Shape shape) NoUniqueness mkKernelInput indices p arr = KernelInput { kernelInputName = paramName p , kernelInputType = paramType p , kernelInputArray = arr , kernelInputIndices = indices } blockedSegmentedScan :: (MonadBinder m, Lore m ~ Kernels) => SubExp -> Pattern -> Certificates -> SubExp -> Lambda -> [(SubExp, VName)] -> m () blockedSegmentedScan segment_size pat cs w lam input = do x_flag <- newVName "x_flag" y_flag <- newVName "y_flag" let x_flag_param = Param x_flag $ Prim Bool y_flag_param = Param y_flag $ Prim Bool (x_params, y_params) = splitAt (length input) $ lambdaParams lam params = [x_flag_param] ++ x_params ++ [y_flag_param] ++ y_params body <- runBodyBinder $ localScope (scopeOfLParams params) $ do new_flag <- letSubExp "new_flag" $ PrimOp $ BinOp LogOr (Var x_flag) (Var y_flag) seg_res <- letTupExp "seg_res" $ If (Var y_flag) (resultBody $ map (Var . paramName) y_params) (lambdaBody lam) (staticShapes $ lambdaReturnType lam) return $ resultBody $ new_flag : map Var seg_res flags_i <- newVName "flags_i" flags_body <- runBodyBinder $ localScope (HM.singleton flags_i IndexInfo) $ do segment_index <- letSubExp "segment_index" $ PrimOp $ BinOp (SRem Int32) (Var flags_i) segment_size start_of_segment <- letSubExp "start_of_segment" $ PrimOp $ CmpOp (CmpEq int32) segment_index zero flag <- letSubExp "flag" $ If start_of_segment (resultBody [true]) (resultBody [false]) [Prim Bool] return $ resultBody [flag] (mapk_bnds, mapk) <- mapKernelFromBody [] w [(flags_i, w)] [] [Prim Bool] flags_body mapM_ addBinding mapk_bnds flags <- letExp "flags" $ Op mapk unused_flag_array <- newVName "unused_flag_array" let lam' = Lambda { lambdaParams = params , lambdaBody = body , lambdaReturnType = Prim Bool : lambdaReturnType lam } pat' = pat { patternValueElements = PatElem unused_flag_array BindVar (arrayOf (Prim Bool) (Shape [w]) NoUniqueness) : patternValueElements pat } (nes, arrs) = unzip input lam_renamed <- renameLambda lam' blockedScan pat' cs w lam' lam_renamed (false:nes) (flags:arrs) where zero = constant (0 :: Int32) true = constant True false = constant False mapKernelSkeleton :: (HasScope Kernels m, MonadFreshNames m) => SubExp -> [KernelInput] -> m ([Binding], (SubExp,SubExp,SubExp), [Binding]) mapKernelSkeleton w inputs = do group_size_v <- newVName "group_size" ((num_threads, num_groups), ksize_bnds) <- runBinder $ do letBindNames'_ [group_size_v] $ Op GroupSize numThreadsAndGroups w $ Var group_size_v read_input_bnds <- forM inputs $ \inp -> do let pe = PatElem (kernelInputName inp) BindVar $ kernelInputType inp return $ Let (Pattern [] [pe]) () $ PrimOp $ Index [] (kernelInputArray inp) (kernelInputIndices inp) let ksize = (num_groups, Var group_size_v, num_threads) return (ksize_bnds, ksize, read_input_bnds) -- Given the desired minium number of threads and the number of -- threads per group, compute the number of groups and total number of -- threads. numThreadsAndGroups :: MonadBinder m => SubExp -> SubExp -> m (SubExp, SubExp) numThreadsAndGroups w group_size = do num_groups <- letSubExp "num_groups" =<< eDivRoundingUp Int32 (eSubExp w) (eSubExp group_size) num_threads <- letSubExp "num_threads" $ PrimOp $ BinOp (Mul Int32) num_groups group_size return (num_threads, num_groups) mapKernel :: (HasScope Kernels m, MonadFreshNames m) => Certificates -> SubExp -> [(VName, SubExp)] -> [KernelInput] -> [Type] -> KernelBody Kernels -> m ([Binding], Kernel Kernels) mapKernel cs w ispace inputs rts (KernelBody kstms krets) = do (ksize_bnds, ksize, read_input_bnds) <- mapKernelSkeleton w inputs space <- newKernelSpace ksize ispace let kstms' = map (Thread ThreadsInSpace) read_input_bnds ++ kstms kbody' = KernelBody kstms' krets return (ksize_bnds, Kernel cs space rts kbody') mapKernelFromBody :: (HasScope Kernels m, MonadFreshNames m) => Certificates -> SubExp -> [(VName, SubExp)] -> [KernelInput] -> [Type] -> Body -> m ([Binding], Kernel Kernels) mapKernelFromBody cs w ispace inputs rts body = mapKernel cs w ispace inputs rts kbody where kbody = KernelBody kstms krets kstms = map (Thread ThreadsInSpace) $ bodyBindings body krets = map (ThreadsReturn ThreadsInSpace) $ bodyResult body data KernelInput = KernelInput { kernelInputName :: VName , kernelInputType :: Type , kernelInputArray :: VName , kernelInputIndices :: [SubExp] } kernelInputParam :: KernelInput -> Param Type kernelInputParam p = Param (kernelInputName p) (kernelInputType p) newKernelSpace :: MonadFreshNames m => (SubExp,SubExp,SubExp) -> [(VName, SubExp)] -> m KernelSpace newKernelSpace (num_groups, group_size, num_threads) dims = KernelSpace <$> newVName "global_tid" <*> newVName "local_tid" <*> newVName "group_id" <*> pure num_threads <*> pure num_groups <*> pure group_size <*> pure (FlatSpace dims)
mrakgr/futhark
src/Futhark/Pass/ExtractKernels/BlockedKernel.hs
bsd-3-clause
24,449
1
25
6,697
7,123
3,504
3,619
481
2
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-} module Data.Number.LogFloat.Vector () where import Data.Number.LogFloat import Data.Vector.Unboxed import Control.Monad import qualified Data.Vector.Unboxed.Base import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Generic as G newtype instance MVector s LogFloat = MV_LogFloat (MVector s Double) newtype instance Vector LogFloat = V_LogFloat (Vector Double) instance Unbox LogFloat instance M.MVector MVector LogFloat where {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicOverlaps #-} {-# INLINE basicUnsafeNew #-} {-# INLINE basicUnsafeReplicate #-} {-# INLINE basicUnsafeRead #-} {-# INLINE basicUnsafeWrite #-} {-# INLINE basicClear #-} {-# INLINE basicSet #-} {-# INLINE basicUnsafeCopy #-} {-# INLINE basicUnsafeGrow #-} basicLength (MV_LogFloat v) = M.basicLength v basicUnsafeSlice i n (MV_LogFloat v) = MV_LogFloat $ M.basicUnsafeSlice i n v basicOverlaps (MV_LogFloat v1) (MV_LogFloat v2) = M.basicOverlaps v1 v2 basicUnsafeNew n = MV_LogFloat `liftM` M.basicUnsafeNew n basicUnsafeReplicate n rec = MV_LogFloat `liftM` M.basicUnsafeReplicate n (logFromLogFloat rec) basicUnsafeRead (MV_LogFloat v) i = logToLogFloat `liftM` M.basicUnsafeRead v i basicUnsafeWrite (MV_LogFloat v) i rec = M.basicUnsafeWrite v i $ logFromLogFloat rec basicClear (MV_LogFloat v) = M.basicClear v basicSet (MV_LogFloat v) rec = M.basicSet v $ logFromLogFloat rec basicUnsafeCopy (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeCopy v1 v2 basicUnsafeMove (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeMove v1 v2 basicUnsafeGrow (MV_LogFloat v) n = MV_LogFloat `liftM` M.basicUnsafeGrow v n instance G.Vector Vector LogFloat where {-# INLINE basicUnsafeFreeze #-} {-# INLINE basicUnsafeThaw #-} {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicUnsafeIndexM #-} {-# INLINE elemseq #-} basicUnsafeFreeze (MV_LogFloat v) = V_LogFloat `liftM` G.basicUnsafeFreeze v basicUnsafeThaw (V_LogFloat v) = MV_LogFloat `liftM` G.basicUnsafeThaw v basicLength (V_LogFloat v) = G.basicLength v basicUnsafeSlice i n (V_LogFloat v) = V_LogFloat $ G.basicUnsafeSlice i n v basicUnsafeIndexM (V_LogFloat v) i = logToLogFloat `liftM` G.basicUnsafeIndexM v i basicUnsafeCopy (MV_LogFloat mv) (V_LogFloat v) = G.basicUnsafeCopy mv v elemseq _ rec y = G.elemseq (undefined :: Vector Double) (logFromLogFloat rec) y
bgamari/logfloat-unboxed
Data/Number/LogFloat/Vector.hs
bsd-3-clause
2,503
0
9
390
662
350
312
49
0
module Handler.CampaignNew where import Import import Import.Premium (hasPremium) import Import.Semantic (renderSemantic) campaignForm :: UserId -> Form Campaign campaignForm user = renderSemantic $ Campaign <$> areq textField "Name" Nothing <*> pure user getCampaignNewR :: Handler Html getCampaignNewR = do Entity uid user <- requireAuth prem <- hasPremium user unless prem $ do ownedCamps <- runDB $ count [CampaignOwnerId ==. uid] when (ownedCamps >= 1) $ do setMessage "Campaign limit reached. Upgrade to Premium for unlimited campaigns." redirect HomeR (campaignWidget, enctype) <- generateFormPost $ campaignForm uid defaultLayout $ do setTitle "New Campaign" $(widgetFile "campaignnew") postCampaignNewR :: Handler Html postCampaignNewR = do user <- requireAuthId ((res,_), _) <- runFormPost $ campaignForm user case res of FormSuccess campaignData -> do camp <- runDB $ insert campaignData setMessage . toHtml $ campaignName campaignData <> " created" redirect . EntriesR $ EntryListR camp _ -> defaultLayout $ do setMessage "Error creating entry." $(widgetFile "error")
sulami/hGM
Handler/CampaignNew.hs
bsd-3-clause
1,210
0
15
278
343
161
182
34
2
module Forum.Internal (module X) where import Forum.Internal.SQL as X import Forum.Internal.Class as X import Forum.Internal.Types as X import Forum.Internal.Decoding as X
turingjump/forum
src/Forum/Internal.hs
bsd-3-clause
173
0
4
22
44
32
12
5
0
{- | Copyright : 2014 Tomáš Musil License : BSD-3 Stability : experimental Portability : portable Nearest Neighbour heuristic for TSP. -} module Problems.TSP.NN ( optimize ) where import Control.Arrow --import Data.List.Stream --import Prelude hiding ((++), lines, map, minimum, splitAt, sum, repeat, tail, take, words, zip) --TODO zrušit explicitní rekurzi a zkusit znovu import qualified Data.Set as Set import Problems.TSP import qualified Problems.TSP.TwoOpt as Topt findPath :: Size -> FDist -> Vertex -> Path findPath n dist origin = origin : fp dist origin origin (Set.delete origin (Set.fromAscList [1..n])) fp dist frst lst unv | not (Set.null unv) = nearest : fp dist frst nearest (Set.delete nearest unv) where nearest = snd (minimum (map dist' (Set.elems unv))) dist' x = (dist (lst, x), x) fp _ frst _ _ = [frst] allPaths :: FDist -> Size -> [Path] --allPaths dist n = map (findPath n dist) [1..n] allPaths dist n = map (Topt.optimize dist . findPath n dist) [1..n] pathLen :: FDist -> Path -> Distance pathLen dist path = sum . map dist $ zip path (tail path) optimize :: FDist -> Int -> (Distance, Path) optimize dist = minimum . allPathlens dist allPathlens :: FDist -> Int -> [(Distance, Path)] allPathlens dist n = map (pathLen dist &&& id) $ allPaths dist n
tomasmcz/discrete-opt
src/Problems/TSP/NN.hs
bsd-3-clause
1,320
0
14
254
421
223
198
20
1
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Language.Haskell.Liquid.Prelude foo x y | compare x y == EQ = liquidAssertB (x == y) | compare x y == LT = liquidAssertB (x < y) | compare x y == GT = liquidAssertB (x > y) prop = foo n m where n = choose 0 m = choose 1
spinda/liquidhaskell
tests/gsoc15/unknown/pos/compare1.hs
bsd-3-clause
299
1
9
80
137
66
71
10
1
{-| Module : Werewolf.Command.Unvote Description : Handler for the unvote subcommand. Copyright : (c) Henry J. Wylde, 2016 License : BSD3 Maintainer : [email protected] Handler for the unvote subcommand. -} module Werewolf.Command.Unvote ( -- * Handle handle, ) where import Control.Lens import Control.Monad.Except import Control.Monad.Extra import Control.Monad.Random import Control.Monad.State import Control.Monad.Writer import Data.Text (Text) import Game.Werewolf import Game.Werewolf.Command import Game.Werewolf.Command.Villager as Villager import Game.Werewolf.Command.Werewolf as Werewolf import Game.Werewolf.Engine import Game.Werewolf.Message.Error import Werewolf.System handle :: (MonadIO m, MonadRandom m) => Text -> Text -> m () handle callerName tag = do unlessM (doesGameExist tag) $ exitWith failure { messages = [noGameRunningMessage callerName] } game <- readGame tag command <- case game ^. stage of VillagesTurn -> return $ Villager.unvoteCommand callerName WerewolvesTurn -> return $ Werewolf.unvoteCommand callerName _ -> exitWith failure { messages = [playerCannotDoThatRightNowMessage callerName] } result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game case result of Left errorMessages -> exitWith failure { messages = errorMessages } Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
hjwylde/werewolf
app/Werewolf/Command/Unvote.hs
bsd-3-clause
1,584
0
15
351
357
195
162
30
4
module Main where import MixedTypesNumPrelude -- import qualified Prelude as P -- import Control.Applicative (liftA2) import System.Environment import AERN2.MP -- import qualified AERN2.MP.Ball as MPBall import AERN2.Poly.Cheb import AERN2.Poly.Cheb.Maximum import AERN2.Poly.Cheb.MaxNaive import qualified AERN2.Local as Local import qualified AERN2.Local.Poly as Local import AERN2.Local.DPoly main :: IO () main = do args <- getArgs (computationDescription, result) <- processArgs args putStrLn $ computationDescription putStrLn $ "result = " ++ show result putStrLn $ "accuracy: " ++ show (getAccuracy result) putStrLn $ "precision = " ++ show (getPrecision result) processArgs :: [String] -> IO (String, MPBall) processArgs [alg, fun] = let desc = "Computing maximum of "++(funName fun)++" over [-1,1] using "++(algName alg)++"." in case alg of "A" -> do let f = case fun of "0" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*x) + cos(20*x) + 7*x^!3 "1" -> let x = setAccuracyGuide (bits 80) _chPolyX in 10*sin(10*x)^!2 + 20*cos(20*x)^!2 "2" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*sin(10*x) + 20*x^!2) + cos(20*x) _ -> error "unkown function code." return (desc, AERN2.Poly.Cheb.MaxNaive.maxNaive f (-1.0) (1.0) (bits 70)) "B" -> do let f = case fun of "0" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*x) + cos(20*x) + 7*x^!3 "1" -> let x = setAccuracyGuide (bits 80) _chPolyX in 10*sin(10*x)^!2 + 20*cos(20*x)^!2 "2" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*sin(10*x) + 20*x^!2) + cos(20*x) _ -> error "unkown function code." return (desc, AERN2.Poly.Cheb.Maximum.maximumOptimised f (mpBall $ -1) (mpBall 1) 5 5) "C" -> do let x = Local.variable let f = case fun of "0" -> sin(10*x) + cos(20*x) + 7*x^!3 "1" -> 10*sin(10*x)^!2 + 20*cos(20*x)^!2 "2" -> sin(10*sin(10*x) + 20*x^!2) + cos(20*x) _ -> error "unkown function code." return (desc, Local.maximum f (mpBall $ -1) (mpBall 1) (bits 53)) "D" -> do let x = Local.variable let f = case fun of "0" -> DPoly (sin(10*x) + cos(20*x) + 7*x^!3) (\z -> sin(10*z) + cos(20*z) + 7*z^!3) (\z -> 10*cos(10*z) - 20*sin(20*z) + 21*z^!2) "1" -> DPoly (10*sin(10*x)^!2 + 20*cos(20*x)^!2) (\z -> 10*sin(10*z)^!2 + 20*cos(20*z)^!2) (\z -> 200*sin(10*z)*cos(10*z) - 800*cos(20*z)*sin(20*z)) "2" -> DPoly (sin(10*sin(10*x) + 20*x^!2) + cos(20*x)) (\z -> sin(10*sin(10*z) + 20*z^!2) + cos(20*z)) (\z -> cos(10*sin(10*z) + 20*z^!2)*(100*cos(10*z) + 40*z) - 20*sin(20*z)) _ -> error "unkown function code." return (desc, Local.maximum f (mpBall $ -1) (mpBall 1) (bits 53)) _ -> error "unkown algorithm code." processArgs _ = error "usage: <algorithm code> <function code>" algName :: String -> String algName "A" = "naive maximisation" algName "B" = "maximisation with global approximations" algName "C" = "maximisation with local approximations" algName "D" = "maximisation with local approximations and enrichments" algName _ = undefined funName :: String -> String funName "0" = "sin(10*x) + cos(20*x) + 7*x^3" funName "1" = "10*sin(10*x)^2 + 20*cos(20*x)^2" funName "2" = "sin(10*sin(10*x) + 20*x^2) + cos(20*x)" funName _ = undefined
michalkonecny/aern2
aern2-fnreps/main/waac-benchmarks.hs
bsd-3-clause
3,999
0
32
1,340
1,730
876
854
94
17
module Data.Symbol.UnitTest(tests) where import Data.Symbol import Test.HUnit tests = TestList [ "name (symbol i s) = s" ~: "s" ~?= (name (symbol 1 "s")), "(symbol 1 s) == (symbol 1 s)" ~: assertBool "" ((symbol 1 "s") == (symbol 1 "s")), "unused == unused" ~: assertBool "" (unused == unused), "(symbol 1 s) != (symbol 2 s)" ~: assertBool "" ((symbol 1 "s") /= (symbol 2 "s")), "unused != (symbol 2 s)" ~: assertBool "" (unused /= (symbol 2 "s")), "(symbol 1 s) != unused" ~: assertBool "" ((symbol 1 "s") /= unused), "(symbol 1 s) < (symbol 2 s)" ~: assertBool "" ((symbol 1 "s") < (symbol 2 "s")), "(symbol 2 s) > (symbol 1 s)" ~: assertBool "" ((symbol 2 "s") > (symbol 1 "s")), "unused < (symbol 2 s)" ~: assertBool "" (unused < (symbol 2 "s")), "(symbol 2 s) > unused" ~: assertBool "" ((symbol 2 "s") > unused), "number (symbol 1 s) = 1" ~: 1 ~?= (number (symbol 1 "s")) ]
emc2/proglang-util
Data/Symbol/UnitTest.hs
bsd-3-clause
937
0
12
224
347
182
165
23
1
module M06MultipleChildren where import Rumpus {- You can call spawnChild as many times as you like. Let's create a field of dreams: ``` -} start :: Start start = do forM_ [0..99] $ \i -> do let x = (fromIntegral (i `mod` 10) - 5) * 0.1 z = (fromIntegral (i `div` 10) - 5) * 0.1 spawnChild $ do myColor ==> colorHSL 0.5 0.7 0.7 myShape ==> Sphere myPose ==> position (V3 0 1 0) mySize ==> 0.05 myUpdate ==> do t <- getNow let t2 = t + fromIntegral i setPosition (V3 x (sin t2 * 0.05 + 0.5) (z - 0.5)) setColor (colorHSL (sin (t2/2)) 0.7 0.7) {- ``` -}
lukexi/rumpus
pristine/Coding Guide/M06MultipleChildren.hs
bsd-3-clause
759
0
23
320
250
125
125
17
1
module Main where import Language main :: IO () main = putStr $ unlines [show vs ++ " -> " ++ show (interpret peg time_env) | (vs, time_env) <- iterations labels] where (labels, peg) = figure_3_c iterations [] = [([], emptyTimeEnv)] iterations (l:ls) = do v <- [0..10] fmap ((v:) `pair` insertTimeEnv l v) (iterations ls) pair f g (a, b) = (f a, g b) figure_2_a :: ([Label], PEG Int) figure_2_a = ([l], n1) where n1 = Lift2 (*) n2 (Const 5) n2 = Theta l (Const 0) n3 n3 = Phi delta n4 n5 n4 = Lift2 (+) (Const 3) n5 n5 = Lift2 (+) (Const 1) n2 l = 1 delta = Lift2 (<=) n2 (Const 10) figure_3_a :: ([Label], PEG Int) figure_3_a = ([l], n1) where n1 = Eval l n2 n4 n2 = Theta l (Const 0) n3 n3 = Lift2 (+) (Const 2) n2 n4 = Pass l n5 n5 = Lift2 (>=) n2 (Const 29) l = 1 figure_3_b :: ([Label], PEG Int) figure_3_b = ([l1, l2], n1) where n1 = Theta l2 n2 n3 n2 = Theta l1 (Const 0) n4 n3 = Lift2 (+) (Const 1) n1 n4 = Eval l2 n1 n5 n5 = Pass l2 n6 n6 = Lift2 (>=) n7 (Const (10 :: Int)) n7 = Theta l2 (Const 0) n8 n8 = Lift2 (+) (Const 1) n7 l1 = 1 l2 = 2 figure_3_c :: ([Label], PEG Int) figure_3_c = ([l1, l2], n1) where n1 = Lift2 (+) n2 n5 n2 = Lift2 (*) (Const 10) n3 n3 = Theta l1 (Const 0) n4 n4 = Lift2 (+) (Const 1) n3 n5 = Theta l2 (Const 0) n6 n6 = Lift2 (+) (Const 1) n5 l1 = 1 l2 = 2
batterseapower/pegs
Main.hs
bsd-3-clause
1,529
0
12
529
799
438
361
50
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main where import Control.Applicative import Control.Monad.Loops import Control.Monad.State.Strict import qualified Data.Attoparsec.Char8 as A import qualified Data.ByteString.Char8 as B import Data.List.Zipper import System.Environment newtype BF a = BF { unBF :: StateT (Zipper Int) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadState (Zipper Int)) runBF :: BF a -> IO a runBF m = evalStateT (unBF m) $ fromList $ replicate 30000 0 bf :: A.Parser (BF ()) bf = (sequence_ <$>) . many $ A.char '>' *> return (modify right) <|> A.char '<' *> return (modify left) <|> A.char '+' *> return (modify $ \z -> replace (cursor z + 1) z) <|> A.char '-' *> return (modify $ \z -> replace (cursor z - 1) z) <|> A.char '.' *> return (gets cursor >>= liftIO . putChar . toEnum) <|> A.char ',' *> return (liftIO getChar >>= modify . replace . fromEnum) <|> whileM_ ((/= 0) <$> gets cursor) <$> (A.char '[' *> bf <* A.char ']') <|> A.notChar ']' *> bf main :: IO () main = do [file] <- getArgs progn <- B.readFile file case A.parseOnly bf progn of Left err -> error err Right p -> runBF p
tanakh/brainfuck
main.hs
bsd-3-clause
1,182
0
23
241
518
264
254
30
2
{-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Forum.Internal.Decoding where import Bookkeeper import Hasql.Class (Decodable(decode)) import Hasql.Decoders (Row) import Data.Proxy instance (All Decodable entries) => Decodable (Book' Identity entries) where decode = decodeBook decodeBook :: All Decodable entries => Row (Book' Identity entries) decodeBook = bsequence $ bmapConstraint (Proxy :: Proxy Decodable) decodeProxy bproxies where decodeProxy :: Decodable a => Proxy a -> Row a decodeProxy _ = decode
turingjump/forum
src/Forum/Internal/Decoding.hs
bsd-3-clause
560
0
9
85
155
84
71
-1
-1
{-# LANGUAGE TupleSections #-} module KMeans ( Point , Cluster , localKMeans , distrKMeans , createGnuPlot , __remoteTable ) where import System.IO import Data.List (minimumBy) import Data.Function (on) import Data.Array (Array, (!), bounds) import qualified Data.Map as Map (fromList, elems, toList, size) import Control.Distributed.Process import Control.Distributed.Process.Closure import MapReduce import PolyDistrMapReduce hiding (__remoteTable) type Point = (Double, Double) type Cluster = (Double, Double) average :: Fractional a => [a] -> a average xs = sum xs / fromIntegral (length xs) distanceSq :: Point -> Point -> Double distanceSq (x1, y1) (x2, y2) = a * a + b * b where a = x2 - x1 b = y2 - y1 nearest :: Point -> [Cluster] -> Cluster nearest p = minimumBy (compare `on` distanceSq p) center :: [Point] -> Point center ps = let (xs, ys) = unzip ps in (average xs, average ys) kmeans :: Array Int Point -> MapReduce (Int, Int) [Cluster] Cluster Point ([Point], Point) kmeans points = MapReduce { mrMap = \(lo, hi) cs -> [ let p = points ! i in (nearest p cs, p) | i <- [lo .. hi] ] , mrReduce = \_ ps -> (ps, center ps) } localKMeans :: Array Int Point -> [Cluster] -> Int -> Map Cluster ([Point], Point) localKMeans points cs iterations = go (iterations - 1) where mr :: [Cluster] -> Map Cluster ([Point], Point) mr = localMapReduce (kmeans points) . trivialSegmentation go :: Int -> Map Cluster ([Point], Point) go 0 = mr cs go n = mr . map snd . Map.elems . go $ n - 1 trivialSegmentation :: [Cluster] -> Map (Int, Int) [Cluster] trivialSegmentation cs' = Map.fromList [(bounds points, cs')] dictIn :: SerializableDict ((Int, Int), [Cluster]) dictIn = SerializableDict dictOut :: SerializableDict [(Cluster, Point)] dictOut = SerializableDict remotable ['kmeans, 'dictIn, 'dictOut] distrKMeans :: Array Int Point -> [Cluster] -> [NodeId] -> Int -> Process (Map Cluster ([Point], Point)) distrKMeans points cs mappers iterations = distrMapReduce $(mkStatic 'dictIn) $(mkStatic 'dictOut) ($(mkClosure 'kmeans) points) mappers (go (iterations - 1)) where go :: Int -> (Map (Int, Int) [Cluster] -> Process (Map Cluster ([Point], Point))) -> Process (Map Cluster ([Point], Point)) go 0 iteration = iteration (Map.fromList $ map (, cs) segments) go n iteration = do clusters <- go (n - 1) iteration let centers = map snd $ Map.elems clusters iteration (Map.fromList $ map (, centers) segments) segments :: [(Int, Int)] segments = let (lo, _) = bounds points in dividePoints numPoints lo dividePoints :: Int -> Int -> [(Int, Int)] dividePoints pointsLeft offset | pointsLeft <= pointsPerMapper = [(offset, offset + pointsLeft - 1)] | otherwise = let offset' = offset + pointsPerMapper in (offset, offset' - 1) : dividePoints (pointsLeft - pointsPerMapper) offset' pointsPerMapper :: Int pointsPerMapper = ceiling (toRational numPoints / toRational (length mappers)) numPoints :: Int numPoints = let (lo, hi) = bounds points in hi - lo + 1 -- | Create a gnuplot data file for the output of the k-means algorithm -- -- To plot the data, use -- -- > plot "<<filename>>" u 1:2:3 with points palette createGnuPlot :: Map KMeans.Cluster ([KMeans.Point], KMeans.Point) -> Handle -> IO () createGnuPlot clusters h = mapM_ printPoint . flatten . zip colors . Map.toList $ clusters where printPoint (x, y, color) = hPutStrLn h $ show x ++ " " ++ show y ++ " " ++ show color flatten :: [(Float, (KMeans.Cluster, ([KMeans.Point], KMeans.Point)))] -> [(Double, Double, Float)] flatten = concatMap (\(color, (_, (points, _))) -> map (\(x, y) -> (x, y, color)) points) colors :: [Float] colors = [0, 1 / fromIntegral (Map.size clusters) .. 1]
haskell-distributed/distributed-process-demos
src/MapReduce/KMeans.hs
bsd-3-clause
4,139
0
15
1,102
1,575
864
711
-1
-1
{-# LANGUAGE CPP #-} -- | This module reexports the six necessary type classes that every 'Rule' type must support. -- You can use this module to define new rules without depending on the @binary@, @deepseq@ and @hashable@ packages. module Development.Shake.Classes( Show(..), Typeable(..), Eq(..), Hashable(..), Binary(..), NFData(..) ) where import Data.Hashable import Data.Typeable import Data.Binary import Control.DeepSeq
nh2/shake
Development/Shake/Classes.hs
bsd-3-clause
440
0
5
69
74
51
23
7
0
module Methods where import qualified Data.ByteString.Lazy.Char8 as C import qualified Data.ByteString.Lazy as L import Data.List import System.IO import Data.Word import Data.Binary.Get import Data.Int import Memory assure :: Maybe a -> a assure (Just a) = a assure _ = error "Error: can't convert Nothing to value" assure' :: String -> Maybe a -> a assure' _ (Just a) = a assure' errorMsg _ = error errorMsg select :: Bool -> a -> a -> a select True x _ = x select False _ x = x isGreater :: Maybe Int -> Int -> Bool isGreater Nothing _ = False isGreater (Just a) b = a > b sub :: Maybe Int -> Int -> Maybe Int sub Nothing _ = Nothing sub (Just a) b = Just $ a - b pick :: [String] -> Maybe Int -> Maybe String pick _ Nothing = Nothing pick strings (Just i) = Just $ strings !! i deleteAt :: Int -> [a] -> [a] deleteAt index list = take index list ++ tail (drop index list) findStringIndex :: [String] -> String -> Int findStringIndex [] _ = -1 findStringIndex (string : r_strings) stringToFind | string == stringToFind = 0 | otherwise = 1 + findStringIndex r_strings stringToFind printList :: Show a => [a] -> IO () printList [] = putStr "[]" printList list = putStr "[" >> go (init list) >> (putStr . show . last) list >> putStr "]" where go [] = return () go (x : xs) = (putStr . show) x >> putStr ", " >> go xs printStringList :: [String] -> IO () printStringList = foldr ((>>) . putStrLn) (return ()) printByteStringList :: [L.ByteString] -> IO () printByteStringList list = putStr "[" >> foldr ((>>) . C.putStr) (return ()) (intersperse (C.pack ", ") list) >> putStr "]" boolToInt :: Bool -> Int boolToInt True = 1 boolToInt False = 0 printState :: ([String], [String], [TD]) -> IO () printState (strings, _, tDs) = printTypeDescs tDs >> eL 2 printState' :: ([String], [String], [TD]) -> IO () printState' (strings, _, tDs) = mapM_ print strings >> putStrLn "%%%%%%%%" >> printTypeDescs tDs >> eL 2 tDs'toString :: [TD] -> String tDs'toString [] = [] tDs'toString ((TD id name count fieldDescs subtypes _) : r_tDs) = " ### Type " ++ show id ++ " : " ++ name ++ " ###\n" ++ concatMap fDs'toString fieldDescs ++ "\nNumber of Subtypes: " ++ show (length subtypes) ++ tDs'toString subtypes >> tDs'toString r_tDs fDs'toString :: FD -> String fDs'toString (name, d, (rawD, _, _)) = " > Field " ++ name ++ ": \n" ++ d'toString rawD ++ " -> " ++ list'toString d ++ "\n" list'toString :: Show a => [a] -> String list'toString [] = "[]" list'toString list = "[" ++ go (init list) ++ (show . last) list ++ "]" where go [] = "" go (x : xs) = show x ++ ", " ++ go xs d'toString :: L.ByteString -> String d'toString d = list'toString (runGet getter d) where getter = repeatGet ((fromIntegral . C.length) d) getWord8 printTypeDescs :: [TD] -> IO () printTypeDescs [] = return () printTypeDescs ((TD id name count fDs subtypes _) : r_tDs) = putStrLn (" ### Type " ++ show id ++ " : " ++ name ++ " ###") >> eL 1 >> mapM_ printFD fDs >> eL 1 >> putStr "Number of Subtypes: " >> print (length subtypes) >> printTypeDescs subtypes >> printTypeDescs r_tDs printFD :: FD -> IO () printFD (name, d, (rawD, _, _)) = putStr (" > Field " ++ name ++ ": ") >> printData rawD >> putStr " -> " >> printList d >> eL 1 printData :: L.ByteString -> IO () printData d' = printList (runGet getter d') where getter = repeatGet ((fromIntegral . C.length) d') getWord8 convertData :: L.ByteString -> [Word8] convertData d = runGet getter d where getter = repeatGet ((fromIntegral . C.length) d) getWord8 printRealData :: Get [Something] -> L.ByteString -> IO () printRealData getter string = printList (runGet getter string) >> eL 1 printTestName :: String -> IO () printTestName string = eL 2 >> putStrLn minuses >> putStrLn ("-- Test " ++ string ++ " --") >> putStrLn minuses where minuses = replicate (11 + length string) '-' eL :: Int -> IO () eL 0 = return () eL i = putStrLn "" >> eL (i-1) isJust :: Maybe a -> Bool isJust (Just _) = True isJust Nothing = False subIndex :: Int -> Int subIndex i = i-1 repeatGet :: Int -> Get a -> Get [a] repeatGet 0 _ = return [] repeatGet i getter = getter >>= \d -> repeatGet (i-1) getter >>= \rest -> return (d : rest) remodel :: [Get a] -> Get [a] remodel [] = return [] remodel (getter : rest) = getter >>= \a -> remodel rest >>= \r -> return (a : r) remodel' :: (Get a, Get a) -> Get (a, a) remodel' (g1, g2) = g1 >>= \v1 -> g2 >>= \v2 -> return (v1, v2) -- replaces an element at a specific index in a list, returns the changed list replace' :: Int -> a -> [a] -> [a] replace' _ _ [] = [] replace' 0 newElem (x : r_list) = newElem : r_list replace' i newElem (x : r_list) = x : replace' (i-1) newElem r_list replaceSection :: Int -> Int -> a -> [a] -> [a] replaceSection 0 count newElem list = replicate count newElem ++ drop count list replaceSection i count newElem (e : r_list) = e : replaceSection (i-1) count newElem r_list -- cutSlice [1,2,3,4,5,6,7,8,9] (3, 5) = ([1,2,3,9],[4,5,6,7,8]) cutSlice :: [a] -> (Int, Int) -> ([a], [a]) cutSlice xs (offset, count) = (xsA1 ++ xsA2, xsB) where (xsA1, xsR) = splitAt offset xs (xsB, xsA2) = splitAt count xsR splitGet :: (Int, Int) -> Get [a] -> (Get [a], Get [a]) splitGet (offset, count) getter = (dropMid offset count `fmap` getter, subList offset count `fmap` getter) subList :: Int -> Int -> [a] -> [a] subList offset count = take count . drop offset dropMid :: Int -> Int -> [a] -> [a] dropMid offset count list = take offset list ++ drop (count + offset) list appendMaybe :: Maybe [a] -> [a] -> [a] appendMaybe Nothing = id appendMaybe (Just list1) = (++) list1 -- replaces element at a given index in a list r :: Int -> a -> [a] -> [a] r index elem list = take index list ++ [elem] ++ drop (index + 1) list -- follows a pointer to its target -- this procedure operates on two modes, starting on mode 1 -- in mode 1, search for the tD with the correct id (as given by (fst ref)) -- in mode 2, go back downward through the respective subtree, searching for the right instance -- the mode is signaled by the attribute ssc; ssc < 0 -> enter mode 2 (and stay there) -- until then ssc equals the sum of the counts of all local super types reach :: Ref -> [TD] -> ([FD], String, Int) reach ref tDs = (fDs, name, pos) where (TD id name count fDs s_tDs rec, pos) = assure $ go 0 ref tDs go :: Int -> (Int, Int) -> [TD] -> (Maybe (TD, Int)) go _ _ [] = Nothing go (-1) (_, i2) (TD id name count fDs s_tDs record : r_f_tDs) -- ||| Mode 2 ||| | i2 < count = Just $ (TD id name count fDs s_tDs record, i2) -- index applies locally -> SUCCESS | otherwise = case (go (-1) (undefined, i2 - count) s_tDs) -- index too high -> subtract it and call downward of Just res -> Just res Nothing -> case (go (-1) (undefined, i2 - count) r_f_tDs) of Just res -> Just res -- call forward Nothing -> Nothing go ssc (i1, i2) (TD id name count fDs s_tDs record : r_f_tDs) -- ||| Mode 1 ||| | id == i1 = go (-1) (undefined, i2 - ssc) [TD id name count fDs s_tDs record] -- found tD with id -> SWITCH TO MODE 2, self-call | otherwise = case (go (ssc + count) (i1, i2) s_tDs) -- didn't find tD yet -> keep looking, call downward of Just res -> Just res Nothing -> case (go ssc (i1, i2) s_tDs) of Just res -> Just res -- call forward Nothing -> Nothing lengthBS :: L.ByteString -> Int lengthBS = fromIntegral . L.length fst' (a,b,c) = a snd' (a,b,c) = b trd' (a,b,c) = c fst'' (a,b,c,d) = a snd'' (a,b,c,d) = b trd'' (a,b,c,d) = c fth'' (a,b,c,d) = d -- ghci macro p :: String -> String p name = "C:/input/" ++ name ++ ".sf" getFDs :: TD -> [FD] getFDs (TD _ _ _ fDs _ _) = fDs a = L.append fI :: Word64 -> Int fI = fromIntegral
skill-lang/skill
deps/haskell/Methods.hs
bsd-3-clause
8,340
0
18
2,260
3,389
1,768
1,621
156
7
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE LiberalTypeSynonyms #-} {-# LANGUAGE ImpredicativeTypes #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} module Lib ( ) where import Data.Comp import Data.Comp.Derive import Data.Comp.Ops import Data.Comp.Render import Data.Comp.TermRewriting (matchRules,matchRule,appRule,reduce,appTRS,parallelStep,parTopStep,Step,Rule) import Data.Rewriting.Rules import Data.Rewriting.FirstOrder (bottomUp) import Data.Rewriting.HigherOrder import Data.String(IsString(..)) import Data.Maybe(fromMaybe) import qualified Data.Set as Set import Data.Map import Derive1 import Control.Monad (guard,(>=>),(<=<)) import Control.Monad.Reader import Control.Monad.Writer import Debug.Trace data STUDENT a = Student a a a a deriving Show data MAJOR a = English | Math | Physics deriving Show newtype LIT b a = L {unL ::b} deriving Show data NUM a = Plus a a | Minus a a | Times a a | Negate a | Divide a a deriving Show data LIST a = NIL | CONS a a deriving (Show,Eq,Ord) --[ $(derive [makeFunctor,makeTraversable,makeFoldable, makeEqF,makeOrdF,makeShowF,smartConstructors,makeShowConstr] [''STUDENT,''LIT,''MAJOR,''NUM]) $(derive [makeFunctor,makeTraversable,makeFoldable, makeEqF,makeOrdF,makeShowF,smartConstructors,makeShowConstr] [''LIST]) $(derive [makeEqF,makeShowF,smartConstructors,makeShowConstr] [''WILD]) $(derive [smartRep] [''STUDENT,''LIT,''MAJOR,''LIST]) $(derive [smartRep'] [''STUDENT,''LIT,''MAJOR,''LIST]) $(derive [makeOrdF] [''VAR,''LAM,''APP]) --] type SIG = LIST :+: NUM :+: STUDENT :+: MAJOR :+: LIT Int :+: LIT String :+: LIT Float :+: ADDONS type ADDONS = VAR :+: LAM :+: APP -- Not needed as written, but allow higher order rewrite rules. newtype Expr f a = Expr {unExpr :: Term f} deriving Functor -- Restricted smart constructors [ student :: (Rep r,STUDENT :<: PF r) => r Int -> r String -> r Int -> r (MAJOR b) -> r b student = rStudent l :: (LIT a :<: PF r, Rep r) => a -> r a l = rL s :: (LIT a :<: PF' r, Rep' r) => a -> r a s = sL --] deriving instance Functor (LHS f) deriving instance Functor (RHS f) instance (LIT a :<: PF' (r f),Functor (r f),Num a,Rep' (r f)) => Num (r (f :: * -> *) a) where --[ fromInteger = s . fromInteger abs (fromRep' -> a) = s $ fromMaybe 0 $ do a' <- project a return $ abs $ unL a' instance (LIT a :<: PF' (r f),Functor (r f),Fractional a,Rep' (r f)) => Fractional (r (f :: * -> *) a) where fromRational = s . fromRational instance (LIT String :<: PF' (r f),Functor (r f),Rep' (r f)) => IsString (r (f :: * -> *) String) where fromString = s . fromString --] type STUFF f = (VAR :<: f,LAM :<: f,APP :<: f,VAR :<: PF (LHS f),LAM :<: PF (LHS f)) matchML :: (Functor f,Foldable f,EqF f,STUFF f) => [LHS f a] -> Term (f :&: Set.Set Name) -> ReaderT AlphaEnv (WriterT (Subst (f :&: Set.Set Name)) Maybe) () matchML lhss t = do mapM_ (\x -> matchM x t) lhss matchL :: (Functor f,Foldable f,EqF f, STUFF f) => [LHS f a] -> Term (f :&: Set.Set Name) -> Maybe (Subst (f :&: Set.Set Name)) matchL lhs = solveSubstAlpha <=< execWriterT . flip runReaderT oEmpty . matchML lhs rewrite' --[ :: ( VAR :<: f , LAM :<: f , APP :<: f , VAR :<: PF (LHS' f) , LAM :<: PF (LHS' f) , VAR :<: PF (RHS f) , LAM :<: PF (RHS f) , Traversable f, EqF f,OrdF f,Render f , g ~ (f :&: Set.Set Name) ) => (Term g -> Term g -> Term g) -- ^ Application operator -> Data.Rewriting.Rules.Rule (LHS' f) (RHS f) -> Term g -> Maybe (Term g) --] rewrite' app (Rule lhs'@(LHS' conds lhss) rhs) t = do subst <- matchL lhss t --trace (showTerm $ unLHS $ head $ lhss) (Just undefined) case conds of Nothing -> return () Just c -> do cont <- unBOOL (unTerm c) subst guard cont substitute app subst rhs -- Render and Show and Rep Expr [ instance Render NUM instance Render LIST instance Render STUDENT instance Show b => Render (LIT b) instance Render MAJOR instance Render WILD instance (MetaRep f ~ MetaId) => Render (META f) instance (MetaRep f ~ MetaId) => ShowConstr (META f) where showConstr (Meta (MVar (MetaId rep))) = show rep instance Rep (Expr f) where type PF (Expr f) = f toRep = Expr fromRep = unExpr instance Rep (LHS' f) where type PF (LHS' f) = WILD :+: META (LHS f) :+: f toRep = LHS'' . (:[]) . LHS fromRep = unLHS . head . unLHS' --] data LHS' f a = LHS' { unC :: Maybe (Conditional f), unLHS' :: [LHS f a] } --Term (WILD :+: (META (LHS' f) :+: f))} pattern LHS'' a = LHS' Nothing a data BOOL f a = Boolean {unBOOL :: Data.Rewriting.Rules.Subst (f :&: Set.Set Name) -> Maybe Bool} | a :&& a | Not a type Conditional f = Term (BOOL f) --[ guarded a b = LHS' (Just b) a boolHelper boolFun f g = Term $ Boolean $ \subs -> do f' <- unBOOL (unTerm f) subs g' <- unBOOL (unTerm g) subs return (f' `boolFun` g') (.&&) = boolHelper (&&) (.||) = boolHelper (||) infixr 4 .&& , .|| notB f = Boolean $ unBOOL f >=> return . not ordHelp :: (Traversable f,Ord a,VAR :<: f,LAM :<: f,VAR :<: PF (RHS f),LAM :<: PF (RHS f),APP :<: f,OrdF f) => [Ordering] -> RHS f a -> RHS f a -> Term (BOOL f) ordHelp ords a b = Term $ Boolean $ \subs -> do a' <- substitute app subs a b' <- substitute app subs b return $ elem (compareF (stripAnn a') (stripAnn b')) ords (.<) = ordHelp [LT] (.>) = ordHelp [GT] (.>=) = ordHelp [GT,EQ] (.<=) = ordHelp [LT,EQ] (.==) = ordHelp [EQ] (.|) = guarded infixr 2 .| -- ] {- ex :: Expr SIG a ex = student 2 "NOT matched" 2 rEnglish -} --student_rule3 :: _ => MetaId Int -> Rule (LHS' f) rhs student_rule x y= [student (meta x) __ (meta y) rEnglish ] .| meta x .> 0 .&& meta y .> meta x ===> student (meta x) "matched!" (meta x) rMath student_rule2 x y= [student (meta x) __ (meta y) rEnglish ,student 2 __ (meta x) rEnglish] .| meta x .== meta y ===> student (meta x) "matched!" (meta x) rMath instance Functor f => Rep (Cxt NoHole f) where type PF (Cxt NoHole f) = f toRep = toCxt fromRep r = fmap (const ()) r f,f2 :: Cxt Hole SIG String f = iStudent (Hole "num") (Hole "only") (iL (2::Int)) iEnglish --f = iStudent (Hole "num") (Hole "only") (iL (2::Int)) iEnglish f2 = iStudent (iL (9::Int)) (iCONS (Hole "only") (Hole "only")) (Hole "num") iEnglish f3 :: Cxt NoHole SIG () f3 = iStudent (iL (5::Int)) (iL ("start"::String)) (iL (2::Int)) iEnglish g = iL (5 ::Int) g2 = iL (7 ::Int) m r cxt conds = do (c,mapping) <- matchRule r cxt guard $ conds mapping return (c,mapping) m2 r cxt = do (c,mapping) <- matchRule r cxt guard $ and $ fmap (\(a@(V t f),_) -> f mapping) $ toList mapping return (c,mapping) g3 = iL (5 ::Int) g4,g5 :: Cxt Hole (LIT Int) (V Hole (LIT Int) String Int) g4 = iL (7 ::Int) g5 = iL (7 ::Int) --g5 = v "num" (< iL (5::Int)) data V h f v a = V v (Map (V h f v a) (Cxt h f a) -> Bool) pattern Stud a b c d <- Term (proj -> Just ((Student a b c d))) _s,_id :: (SIG :<: f,STUDENT :<: f,Functor f) => Cxt h f a -> Cxt h f a -> Cxt h f a Stud _ b c d `_id` (deepProject -> Just (a:: Cxt h SIG a)) = iStudent (prep a) (prep b) (prep c) (prep d) Stud _ b c d `_s` (deepProject -> Just (a:: Cxt h SIG a)) = iStudent (prep a) (prep b) (prep c) (prep d) -- _s :: LHS' SIG a -> LHS' SIG a -> LHS' SIG a prep = deepInject data Expr2 h f a b = Expr2 {unExpr2 :: Cxt h f a} deriving Show data Hole2 h f a = H String [([Ordering],Cxt h f (Hole2 h f a))] | Wild instance Eq (Hole2 h f a) where H a _ == H b _ = a == b instance Ord (Hole2 h f a) where H a _ `compare` H b _ = a `compare` b instance (ShowF f,Functor f) => Show (Hole2 h f a) where show (H s b) = "Hole2 " ++ show s ++ " " ++ show b --type LHS2 h f a b = LHS2 {unLHS2 :: Cxt h f (Hole2 h f a)} deriving Show newtype LHS2 h a f b = LHS2 {unLHS2 :: Cxt h f (Hole2 h f a)} deriving (Show,Functor) sstudent :: (STUDENT :<: PF' r,Rep' r) => r Int -> r String -> r Int -> r (MAJOR a) -> r a sstudent = sStudent lhs2 :: LHS2 Hole a SIG b lhs2 = sstudent ("id" ..< 3) ("s" ..= "hi") __ __ (==>) :: LHS2 Hole a f b -> LHS2 Hole a g b -> (Context f (Hole2 Hole f a) ,Context g (Hole2 Hole g a)) LHS2 a ==> LHS2 b = (a,b) v a func term = LHS2 $ Hole (H a [(func,term)]) h a = LHS2 $ Hole (H a []) (..<),(..=),(..>),(..!=) :: (Functor f,Traversable f) => String -> LHS2 Hole a f b -> LHS2 Hole a f b a ..< b = v a [LT] $ c b c b = maybe (error "undefined coerce") id $ deepProject $ fromRep' b a ..= b = v a [EQ] $ c b a ..> b = v a [GT] $ c b a ..!= b = v a [LT,GT] $ c b instance WildCard (LHS2 Hole a f) where __ = LHS2 $ Hole $ Wild instance Functor f => Rep' (Cxt NoHole f) where type PF' (Cxt NoHole f) = f type PHOLE' (Cxt NoHole f) = () type PHOLE'' (Cxt NoHole f) = NoHole toRep' = toCxt fromRep' = fmap (const ()) instance (Functor f) => Rep' (LHS2 h a f) where type PF' (LHS2 h a f) = f type PHOLE' (LHS2 h a f) = Hole2 h f a type PHOLE'' (LHS2 h a f) = h toRep' = LHS2 fromRep' = unLHS2 instance Rep' (LHS f) where type PF' (LHS f) = (WILD :+: META (LHS f) :+: f) type PHOLE' (LHS f) = () type PHOLE'' (LHS f) = NoHole toRep' = LHS fromRep' = unLHS instance Rep' (RHS f) where type PF' (RHS f) = (META (RHS f) :+: f) type PHOLE' (RHS f) = () type PHOLE'' (RHS f) = NoHole toRep' = RHS fromRep' = unRHS type HoledCxt h f a = Cxt h f (Hole2 h f a) example = sstudent ("x" ..< 2) "hi" ("y" ..!= h "x") sMath ==> sstudent (h "y") "MATCHED" (h "x") sEnglish main = do --drawTerm $ reduce (parallelStep [(g,g2),(f,f2)]) f3 --putStrLn $ show $ ( d4 :: Expr2 Hole SIG (V Hole SIG String (Cxt Hole L2 )) b) --putStrLn $ show $ m2 (g5,g4) g3 mapM_ drawTerm $ appRule' example $ (sstudent 1 "hi" 0 sMath :: Term SIG) {- putStrLn $ show $ m (f,f2) f3 (\mp -> mp ! "num" < iL (6 :: Int)) let e = unExpr ex drawTerm $ rewriteWith (reduce $ rewrite' app $ quantify student_rule) e drawTerm $ rewriteWith (reduce $ rewrite' app $ quantify student_rule2) e -} appRule' :: (Ord a,OrdF f,Show a,ShowF f,v ~ Hole2 Hole f a,Ord v, EqF f, Eq a, Functor f, Foldable f) => Data.Comp.TermRewriting.Rule f f v -> Step (Cxt h f a) appRule' rule t = do (res, subst) <- matchRule rule t trace (concatMap (\(a,b) -> show a ++ "::::" ++ show b) $ toList subst) (Just undefined) let x = concatMap (\(H v conds,b) -> fmap (\(ords,cond) -> elem (compare b (substHoles' cond subst)) ords ) conds) $ toList subst trace (show x) $ return () if and x then return $ substHoles' res subst else return t
tomberek/RETE
src/RETE/Lib4.hs
bsd-3-clause
11,486
0
21
2,930
5,111
2,677
2,434
-1
-1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} -- {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} #ifndef MIN_VERSION_transformers #define MIN_VERSION_transformers(x,y,z) 4 #endif -- -- #ifdef MIN_VERSION_GLASGOW_HASKELL -- -- #if MIN_VERSION_GLASGOW_HASKELL(8,0,1,0) -- -- -- ghc >= 8.0.1 -- -- {-# LANGUAGE StandaloneDeriving #-} -- -- #else -- -- -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined -- -- #endif -- -- #else -- -- -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) -- -- #endif -- for debugging -- {-# LANGUAGE InstanceSigs #-} -- {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <[email protected]> -- Stability : experimental -- Portability: non-portable -- -- This module provides Pire's syntax, -- ie. Pire's flavour of Pi-forall syntax: -- expressions, annotations, ... (mutally recursive defs) module Pire.Syntax.Expr where -- import Data.List import Control.Monad #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) import Data.Functor.Classes import Data.Eq.Deriving (deriveEq1) import Data.Ord.Deriving (deriveOrd1) import Text.Show.Deriving (deriveShow1) import Text.Show (showListWith) import Text.Read.Deriving (deriveRead1) #else import Prelude.Extras #endif import Bound import Bound.Name import Bound.Scope import Data.Bifoldable import Data.Bifunctor import Data.Bitraversable import Text.Trifecta.Delta (Delta) import Pire.Syntax.Ws import Pire.Syntax.Token import Pire.Syntax.Nm import Pire.Syntax.Binder import Pire.Syntax.Eps import Pire.Syntax.Pattern -- import Pire.Syntax.GetNm() -- import Debug.Trace import Control.Lens import Data.Typeable hiding (Refl) import Pire.Syntax.NatPrime infixl 9 :@ data Expr t a = V a | Nat' (PossiblyVar t) | Ws_ (Expr t a) (Ws t) -- -- | WildcardSeen_ (Expr t a) -- -- | WildcardInferred_ Integer | BndV t (Expr t a) -- bracketed var, eg. [ v ], originally defined as -- BracketedV_ (BracketOpen...) a Ws (BracketClose...) -- but later needed any kind of expr within brackets anyway, for args ie. | Brackets_ (Token 'BracketOpenTy t) (Expr t a) (Token 'BracketCloseTy t) -- parenthesized term, useful for printing | Paren (Expr t a) | Paren_ (Token 'ParenOpenTy t) (Expr t a) (Token 'ParenCloseTy t) | Type | Type_ t (Ws t) | (Expr t a) :@ (Expr t a) | ErasedApp (Expr t a) (Expr t a) | Lam t (Scope () (Expr t) a) | Lam_ (Token 'LamTokTy t) (Binder t) (Token 'DotTy t) (Scope () (Expr t) a) -- defs w/ (original) Name s - they are not really needed, but convenient to have: -- (in the following a prime as in Lam' indicates a Scope w/ (original) Name s) -- this would seem a natural def according to the Bound.Name docs: -- -- | Lam' t (Scope (Name a ()) (Expr t) a) -- however it gets in the way of automatically deriving Functor, Foldable, and Traversable below -- this I came up w/ instead - worked for a while -- (but wasn't too sure, if it makes sense in the first place): -- -- | Lam' t (Scope (Name t ()) (Expr t) a) -- however, as then discovered, this gets in the way of making Expr bitraversable below, -- which is not only nice to have (eg. for Text2String) -- but essential for our position/range calculations -- so we resort to using a fixed data type: String (or T.Text or whatever) | Lam' t (Scope (Name String ()) (Expr t) a) -- and the corresponding plural version: | Lams' [t] (Scope (Name String Int) (Expr t) a) -- the caveat is that, that desugaring (so far generic: for any kind of Expr), -- becomes tied to String (or...) that way, ie. if we want to desugar Lams' to Lam' etc. -- (or we would need different versions of desugaring functions, for String, T.Text etc) -- so Scopes w/ Names are really not that useful (and not really needed anyway), -- they are just convenient to have when starting out w/ Bound. -- That's why they are not used in the following defs of other Exprs -- (in particular there are not white space aware versions of the above: Lam'_, Lams'_ ) -- Lam' and Lams' kept here nevertheless, just for experimentation | ErasedLam t (Scope () (Expr t) a) | ErasedLam_ (Token 'LamTokTy t) (Binder t) (Token 'DotTy t) (Scope () (Expr t) a) -- desugaring is handled here explicitly, -- ie. a lambda with multiple binders will become a Lams: -- (plural s, white space aware: Lams_), desugared to Lam (Lam_) -- these are superseded by the following LamPAs, -- which cover also the notion of a RuntimeP/ErasedP pattern (P), -- as well as an annotation (A), to sum up: -- Lams are desugared to Lam -- Lams_ to Lam_ -- LamPAs to LamPA -- LamPAs_ to LamPA_ - one would think (and maybe LamPA_ should be added), -- but desugaring is really needed only for untie (conversion to PiForall data structures), -- and there we have long thrown away the white space w/ forget | Lams [t] (Scope Int (Expr t) a) | Lams_ (Token 'LamTokTy t) [Binder t] (Token 'DotTy t) (Scope Int (Expr t) a) | LamPA Eps t (Annot t a) (Scope () (Expr t) a) #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) | LamPAs [(Eps, t, Annot t a)] (Scope Int (Expr t) a) #else | LamPAs [(Eps, t, Annot t a)] (Scope Int (Expr t) a) #endif -- need this as well for List 2 Vect: the notion of a yet to be filled in var | LamPAs' [(Eps, PossiblyVar t, Annot t a)] (Scope Int (Expr t) a) | LamPAs_ (Token 'LamTokTy t) [(Eps, Binder t, Annot t a)] (Token 'DotTy t) (Scope Int (Expr t) a) -- the simplest kind of Pi type | Pi t (Expr t a) (Scope () (Expr t) a) | Pi_ (Expr t a) (Token 'ArrowTy t) (Scope () (Expr t) a) -- keep track of pattern (instead of Pi/ErasedPi), similar to LamPA/LamPAs -- pi's are binders (binding type: embed), hence the use of t -- get rid of scopes w/ orig Names -- -- | PiP Eps t (Expr t a) (Scope (Name t ()) (Expr t) a) | PiP Eps t (Expr t a) (Scope () (Expr t) a) -- -- Pi_ (Ann_ ...) -- -- reuse Ann_ for the binding in Pi_ here, thereby making its def simple -- -- need to keep track maybe, if we actually have seen some parens/colon -- -- idea so far: if not, than the name will start with _: _/_1/_2 etc -- -- maybe use some (new) flag for Ann_ instead -- get rid of scope's w/ orig Names -- -- | PiP_ Eps (Expr t a) (Arrow t) (Scope (Name t ()) (Expr t) a) | PiP_ Eps (Expr t a) (Token 'ArrowTy t) (Scope () (Expr t) a) -- just a trifecta delta -- when untied, this will become a Parsec/PiForall Pos -- not to be confused with the data type Pos of Refactor/Range.hs | Position Delta (Expr t a) -- an axiom 'TRUSTME', inhabits all types | TrustMe (Annot t a) | TrustMe_ t (Ws t) (Annot t a) -- unit -- The type with a single inhabitant `One` | TyUnit | TyUnit_ t (Ws t) -- The inhabitant, written `tt` | LitUnit | LitUnit_ t (Ws t) -- boolean expressions -- The type with two inhabitants | TyBool | TyBool_ t (Ws t) -- True and False | LitBool Bool | LitBool_ Bool t (Ws t) -- if expression for eliminating booleans | If (Expr t a) (Expr t a) (Expr t a) (Annot t a) | If_ (Token 'IfTokTy t) (Expr t a) (Token 'ThenTokTy t) (Expr t a) (Token 'ElseTokTy t) (Expr t a) (Annot t a) -- sigma types -- `{ x : A | B }` -- -- | Sigma (Bind (TName, Embed Term) Term) | Sigma t (Expr t a) (Scope () (Expr t) a) | Sigma_ (Token 'BraceOpenTy t) (Binder t) (Token 'ColonTy t) (Expr t a) (Token 'VBarTy t) (Scope () (Expr t) a) (Token 'BraceCloseTy t) -- introduction for sigmas `( a , b )` | Prod (Expr t a) (Expr t a) (Annot t a) | Prod_ (Token 'ParenOpenTy t) (Expr t a) (Token 'CommaTy t) (Expr t a) (Token 'ParenCloseTy t) (Annot t a) -- elimination form `pcase p of (x,y) -> p` -- -- | Pcase Term (Bind (TName, TName) Term) Annot -- rethink if scope is well defined ! -- todo: rethink Scope for both Pcase and Pcase_ -- maybe () is not enough ? -- -- | Pcase (Expr t a) (t, t) (Scope () (Expr t) a) (Annot t a) | Pcase (Expr t a) (t, t) (Scope Int (Expr t) a) (Annot t a) -- -- | Pcase_ (PcaseTok t) (Expr t a) (Of t) -- -- (ParenOpen t) (Binder t) (Comma t) (Binder t) (ParenClose t) -- -- (Arrow t) (Scope () (Expr t) a) (Annot t a) | Pcase_ (Token 'PcaseTokTy t) (Expr t a) (Token 'OfTy t) (Token 'ParenOpenTy t) (Binder t) (Token 'CommaTy t) (Binder t) (Token 'ParenCloseTy t) (Token 'ArrowTy t) (Scope Int (Expr t) a) (Annot t a) -- -- | Let {-# UNPACK #-} !Int [Scope Int Exp a] (Scope Int Exp a) -- let w/ scope - closer to the def above -- -- | LetS (Scope (Name String ()) Exp a) (Scope (Name String ()) Exp a) -- ! in pi-forall: binding type: embed | Let t (Expr t a) (Scope () (Expr t) a) | Let_ (Token 'LetTokTy t) (Binder t) (Token 'EqualTy t) (Expr t a) (Token 'InTy t) (Scope () (Expr t) a) -- Equality type `a = b` | TyEq (Expr t a) (Expr t a) | TyEq_ (Expr t a) (Token 'EqualTy t) (Expr t a) -- Proof of equality | Refl (Annot t a) -- the whitespace aware version is now just -- Ws_ (Refl (Annot t a)) (Ws t) -- but maybe not a good idea: the ws is before the annot! | Refl_ t (Ws t) (Annot t a) -- equality elimination | Subst (Expr t a) (Expr t a) (Annot t a) | Subst_ (Token 'SubstTokTy t) (Expr t a) (Token 'ByTy t) (Expr t a) (Annot t a) -- witness to an equality contradiction | Contra (Expr t a) (Annot t a) | Contra_ (Token 'ContraTokTy t) (Expr t a) (Annot t a) -- datatypes -- type constructors (fully applied) -- -- | TCon t [Expr t a] -- -- | TCon_ (Nm t) [Expr t a] | TCon a [Expr t a] | TCon_ (Nm t a) [Expr t a] -- -- | TCon a [Expr t a] -- -- | TCon_ (Expr t a) [Expr t a] -- term constructors | DCon t [Arg t a] (Annot t a) | DCon_ (Nm1 t) [Arg t a] (Annot t a) -- don't want implicit desugaring for nats -- (so keep the orig) | Nat Integer | Nat_ Integer t (Ws t) -- case analysis -- (fully applied, erased arguments first) -- -- | Case (Expr t a) [Match t a] (Annot t a) | Case (Expr t a) [Match t a] (Annot t a) -- -- | Case_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) -- -- (Maybe (Token 'BraceOpenTy t)) [(Match t a, Maybe (Token 'SemiColonTy t))] (Maybe (Token 'BraceCloseTy t)) -- -- (Annot t a) | Case_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) (Maybe (Token 'BraceOpenTy t)) [(Maybe (Token 'SemiColonTy t), Match t a)] (Maybe (Token 'BraceCloseTy t)) (Annot t a) -- -- | CaseIndented_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) [Match t a] (Annot t a) -- -- | CaseWithBraces_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) -- -- (Token 'BraceOpenTy t) [(Match t a, Maybe (Token 'SemiColonTy t))] (Token 'BraceCloseTy t) -- -- (Annot t a) -- Annotated terms `( x : A )` | Ann (Expr t a) (Expr t a) -- originally just -- | Ann_ ParenOpen (Exp_ a) Colon (Exp_ a) ParenClose -- but need to be more specific here: -- have witnessed an annotation / or just inferred it (think of "_ : A"), in parens / brackets -- -- todo: rework this comment (only parts still valid) -- can't really make up my mind if the x should be a binder here -- my current take is: no, it's not (there is no Scope involved), -- ie. it's a binder only in the case of a Pi-type à la: (x:A) -> B -- ie. the ...Bnd  variants are used for Pi-types in PiP_... -- and [later]: as I can't make up my mind, if x should be a binder, -- these constructors come in pairs now: one, where it isn't a binder, -- and one where it is -- reuse Paren_ + Brackets_ for Ann_ as well -- eg. -- Ann_ $ Paren_ (ParenOpen...) (WitnessedAnnEx_ ...)(ParenClose...) -- Ann_ $ Brackets_ (BracketOpen...)(Witnessed...) (BracketClose...) -- Ann_ $ InferredAnnBnd_ -- always make clear however that it's an Ann_ (wrap it in Ann_) -- to not confuse annotations with a simple Paren_ exprs eg. | WitnessedAnnEx_ (Expr t a) (Token 'ColonTy t) (Expr t a) | InferredAnnBnd_ (Binder t) (Expr t a) | WitnessedAnnBnd_ (Binder t) (Token 'ColonTy t) (Expr t a) | Ann_ (Expr t a) deriving (Functor,Foldable,Traversable) extract :: Expr t a -> a extract (V a) = a extract (Ws_ ex _) = extract ex extract (Brackets_ _ ex _) = extract ex extract _ = error "tried to extract from other than V. Ws_, or Brackets_" instance Applicative (Expr t) where pure = V (<*>) = ap instance Monad (Expr t) where return = V Nat' x >>= _ = Nat' x V a >>= f = f a Ws_ x ws >>= f = Ws_ (x >>= f) ws (x :@ y) >>= f = (x >>= f) :@ (y >>= f) ErasedApp x y >>= f = ErasedApp (x >>= f) (y >>= f) Type >>= _ = Type (Type_ ty ws) >>= _ = Type_ ty ws BndV v ex >>= f = BndV v (ex >>= f) Lam n s >>= f = Lam n (s >>>= f) Lam_ lamtok v dot s >>= f = Lam_ lamtok v dot (s >>>= f) -- missing ErasedLam / ErasedLam_ Lams ns s >>= f = Lams ns (s >>>= f) Lams_ lamtok ns dot s >>= f = Lams_ lamtok ns dot (s >>>= f) Lam' n s >>= f = Lam' n (s >>>= f) Lams' ns s >>= f = Lams' ns (s >>>= f) LamPA pat n (Annot ann) scope >>= f = LamPA pat n (Annot $ (>>= f) <$> ann) (scope >>>= f) LamPA _ _ (Annot_ {}) _ >>= _ = error "LamPA w/ Annot_" LamPAs nas s >>= f = LamPAs [ (pat, n, Annot $ (>>= f) <$> ann) | (pat, n, Annot ann) <- nas] (s >>>= f) LamPAs_ lamtok nas dottok s >>= f = LamPAs_ lamtok [ (pat, n, (Annot_ ((>>= f) <$> ann) ws)) | (pat, n, Annot_ ann ws) <- nas] dottok (s >>>= f) ErasedLam n s >>= f = ErasedLam n (s >>>= f) ErasedLam_ lamtok v dot s >>= f = Lam_ lamtok v dot (s >>>= f) TrustMe (Annot ann) >>= f = TrustMe (Annot $ (>>= f) <$> ann) TrustMe (Annot_ {}) >>= _ = error "TrustMe w/ Annot_" TrustMe_ tme ws (Annot_ ann ws') >>= f = TrustMe_ tme ws (Annot_ ((>>= f) <$> ann) ws') TrustMe_ _ _ (Annot {}) >>= _ = error "TrustMe_ w/ Annot" Position p e >>= f = Position p (e >>= f) Pi nm ty sc >>= f = Pi nm (ty >>= f) (sc >>>= f) Pi_ ann arr sc >>= f = Pi_ (ann >>= f) arr (sc >>>= f) PiP eps n e s >>= f = PiP eps n (e >>= f) (s >>>= f) PiP_ eps n arr s >>= f = PiP_ eps (n >>= f) arr (s >>>= f) TyUnit >>= _ = TyUnit TyUnit_ ty ws >>= _ = TyUnit_ ty ws LitUnit >>= _ = LitUnit LitUnit_ tt ws >>= _ = LitUnit_ tt ws TyBool >>= _ = TyBool TyBool_ tb ws >>= _ = TyBool_ tb ws LitBool b >>= _ = LitBool b LitBool_ b lb ws >>= _ = LitBool_ b lb ws Sigma str' ex scope >>= f = Sigma str' (ex >>= f) (scope >>>= f) Sigma_ bo str' col ex vb scope bc >>= f = Sigma_ bo str' col (ex >>= f) vb (scope >>>= f) bc Prod a b (Annot ann) >>= f = Prod (a >>=f ) (b >>= f) (Annot $ (>>= f) <$> ann) Prod _ _ (Annot_ {}) >>= _ = error "Prod w/ Annot_" Prod_ po a cmm b pc (Annot_ ann ws) >>= f = Prod_ po (a >>=f ) cmm (b >>= f) pc (Annot_ ((>>= f) <$> ann) ws) Prod_ _ _ _ _ _ (Annot {}) >>= _ = error "Prod_ w/ Annot" -- -- elimination form `pcase p of (x,y) -> p` Pcase ex (s, t) sc (Annot ann) >>= f = Pcase (ex >>=f) (s, t) (sc >>>=f) (Annot $ (>>= f) <$> ann) Pcase_ pcase ex of' po s comma t pc arr sc (Annot_ ann ws) >>= f = Pcase_ pcase (ex >>= f) of' po s comma t pc arr (sc >>>= f) (Annot_ ((>>= f) <$> ann) ws) -- Let n bs e >>= f = Let n (map (>>>= f) bs) (e >>>= f) Let n b e >>= f = Let n (b >>= f) (e >>>= f) Let_ let' n eq b in' e >>= f = Let_ let' n eq (b >>= f) in' (e >>>= f) -- matches are binders: thus leave the pattern pat as is Case e ms (Annot ann) >>= f = Case (e >>= f) [Match (bpattern pat) (s >>>= f) | (Match pat s) <- ms] (Annot $ (>>= f) <$> ann) where bpattern (PatVar tt) = PatVar tt -- bpattern (PatVar tt) = PatVar $ a2b tt -- bpattern (PatCon aa ls) = PatCon (a2b aa) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon aa ls) = PatCon (a2b aa) [ (eps, bpattern p) | (eps, p) <- ls] -- -- bpattern (PatVar_ nm) = PatVar_ $ bnm nm bpattern (PatVar_ nm) = PatVar_ $ nm -- bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (eps, bpattern p) | (eps, p) <- ls] bpattern (NatPatVar n) = NatPatVar n a2b = extract . f bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' -- -- Case_ ctok e oftok bo ms bc (Annot_ ann ws) >>= -- -- f = Case_ -- -- ctok -- -- (e >>= f) -- -- oftok -- -- bo -- -- [(Match_ (bpattern pat) arr (s >>>= f), semi) | (Match_ pat arr s, semi) <- ms] -- -- bc -- -- (Annot_ ((>>= f) <$> ann) ws) -- -- where -- -- bpattern (PatVar tt) = PatVar tt -- -- -- bpattern (PatVar tt) = PatVar $ a2b tt -- -- bpattern (PatCon aa ls) = PatCon (a2b aa) [ (bpattern p, eps) | (p, eps) <- ls] -- -- -- bpattern (PatCon aa ls) = PatCon aa [ (bpattern p, eps) | (p, eps) <- ls] -- -- -- -- bpattern (PatVar_ nm) = PatVar_ $ bnm nm -- -- bpattern (PatVar_ nm) = PatVar_ $ nm -- -- bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (bpattern p, eps) | (p, eps) <- ls] -- -- bpattern (PatInBrackets_ bo' pat bc') = PatInBrackets_ bo' (bpattern pat) bc' -- -- bpattern (PatInParens_ po pat pc) = PatInParens_ po (bpattern pat) pc -- -- bpattern (NatPatVar n) = NatPatVar n -- -- -- TODO -- -- -- more cases ... -- -- a2b = extract . f -- -- bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' Case_ ctok e oftok bo ms bc (Annot_ ann ws) >>= f = Case_ ctok (e >>= f) oftok bo [(semi, Match_ (bpattern pat) arr (s >>>= f)) | (semi, Match_ pat arr s) <- ms] bc (Annot_ ((>>= f) <$> ann) ws) where bpattern (PatVar tt) = PatVar tt -- bpattern (PatVar tt) = PatVar $ a2b tt -- bpattern (PatCon aa ls) = PatCon (a2b aa) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon aa ls) = PatCon (a2b aa) [ (eps, bpattern p) | (eps, p) <- ls] -- -- bpattern (PatVar_ nm) = PatVar_ $ bnm nm bpattern (PatVar_ nm) = PatVar_ $ nm -- bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (eps, bpattern p) | (eps, p) <- ls] bpattern (PatInBrackets_ bo' pat bc') = PatInBrackets_ bo' (bpattern pat) bc' bpattern (PatInParens_ po pat pc) = PatInParens_ po (bpattern pat) pc bpattern (NatPatVar n) = NatPatVar n -- TODO -- more cases ... a2b = extract . f bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' -- CaseIndented_ ctok e oftok ms (Annot_ ann ws) >>= -- f = CaseIndented_ -- ctok -- (e >>= f) -- oftok -- [Match_ pat arr (s >>>= f) | Match_ pat arr s <- ms] -- (Annot_ ((>>= f) <$> ann) ws) -- CaseWithBraces_ ctok e oftok bo ms bc (Annot_ ann ws) >>= -- f = CaseWithBraces_ -- ctok -- (e >>= f) -- oftok -- bo -- [(Match_ pat arr (s >>>= f), semi) | (Match_ pat arr s, semi) <- ms] -- bc -- (Annot_ ((>>= f) <$> ann) ws) -- TCon s es >>= f = TCon s (map (>>= f) es) -- TCon_ s es >>= f = TCon_ s (map (>>= f) es) TCon s es >>= f = TCon (a2b s) (map (>>= f) es) where a2b = extract . f TCon_ s es >>= f = TCon_ (bnm s) (map (>>= f) es) where a2b = extract . f bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' -- -- TCon s es >>= f = TCon (s >>= f) (map (>>= f) es) -- -- TCon_ s es >>= f = TCon_ (s >>= f) (map (>>= f) es) DCon s as (Annot ann) >>= f = DCon s [ Arg pat (e >>= f) | (Arg pat e) <- as] (Annot $ (>>= f) <$> ann) DCon_ s as (Annot_ ann ws) >>= f = DCon_ s [ Arg pat (e >>= f) | (Arg pat e) <- as] (Annot_ ((>>= f) <$> ann) ws) If cond t e (Annot ann) >>= f = If (cond >>= f) (t >>= f) (e >>= f) (Annot $ (>>= f) <$> ann) If_ iftok cond thentok t etok e (Annot_ ann ws) >>= f = If_ iftok (cond >>= f) thentok (t >>= f) etok (e >>= f) (Annot_ ((>>= f) <$> ann) ws) Paren e >>= f = Paren (e >>= f) Paren_ po e pc >>= f = Paren_ po (e >>= f) pc Nat n >>= _ = Nat n Nat_ nmbr tok ws >>= _ = Nat_ nmbr tok ws TyEq a b >>= f = TyEq (a >>= f) (b >>= f) TyEq_ a eq b >>= f = TyEq_ (a >>= f) eq (b >>= f) Subst a b (Annot ann) >>= f = Subst (a >>= f) (b >>= f) (Annot $ (>>= f) <$> ann) Subst_ subst a by b (Annot_ ann ws) >>= f = Subst_ subst (a >>= f) by (b >>= f) (Annot_ ((>>= f) <$> ann) ws) Contra a (Annot ann) >>= f = Contra (a >>= f) (Annot $ (>>= f) <$> ann) Contra_ ctok a (Annot_ ann ws) >>= f = Contra_ ctok (a >>= f) (Annot_ ((>>= f) <$> ann) ws) Refl (Annot ann) >>= f = Refl (Annot $ (>>= f) <$> ann) Refl_ rfl ws (Annot_ ann ws') >>= f = Refl_ rfl ws (Annot_ ((>>= f) <$> ann) ws') Ann a b >>= f = Ann (a >>= f) (b >>= f) -- exmpl -- lams_ ["x", "y"] $ (V_ "b" $ Ws "{-foo-}") -- lam_ "x" $ (V_ "b" $ Ws "{-foo-}") Brackets_ bo e bc >>= f = Brackets_ bo (e >>= f) bc -- -- WitnessedAnnInParens_ po ex col ty pc >>= f = WitnessedAnnInParens_ po (ex >>= f) col (ty >>= f) pc -- -- WitnessedAnnInParensBnd_ po b col ty pc >>= f = WitnessedAnnInParensBnd_ po b col (ty >>= f) pc -- -- WitnessedAnnInBrackets_ bo ex col ty bc >>= f = WitnessedAnnInBrackets_ bo (ex >>= f) col (ty >>= f) bc -- -- WitnessedAnnInBracketsBnd_ bo bnd col ty bc >>= f = WitnessedAnnInBracketsBnd_ bo bnd col (ty >>= f) bc -- -- InferredAnn_ ex ty >>= f = InferredAnn_ (ex >>= f) (ty >>= f) -- -- InferredAnnBnd_ bnd ty >>= f = InferredAnnBnd_ bnd (ty >>= f) -- -- InferredAnnInBrackets_ bo ex ty bc >>= f = InferredAnnInBrackets_ bo (ex >>= f) (ty >>= f) bc -- -- InferredAnnInBracketsBnd_ bo ex ty bc >>= f = InferredAnnInBracketsBnd_ bo ex (ty >>= f) bc -- AnnInParens_ bt po ex col ty pc >>= f = AnnInParens_ bt po (ex >>= f) col (ty >>= f) pc -- AnnInParensBnd_ bt po b col ty pc >>= f = AnnInParensBnd_ bt po b col (ty >>= f) pc -- AnnInBrackets_ bt bo ex col ty bc >>= f = AnnInBrackets_ bt bo (ex >>= f) col (ty >>= f) bc -- AnnInBracketsBnd_ bt bo bnd col ty bc >>= f = AnnInBracketsBnd_ bt bo bnd col (ty >>= f) bc WitnessedAnnEx_ ex col ty >>= f = WitnessedAnnEx_ (ex >>= f) col (ty >>= f) InferredAnnBnd_ bnd ty >>= f = InferredAnnBnd_ bnd (ty >>= f) WitnessedAnnBnd_ bnd col ty >>= f = WitnessedAnnBnd_ bnd col (ty >>= f) Ann_ ann >>= f = Ann_ (ann >>= f) instance Bifunctor Expr where bimap = bimapDefault instance Bifoldable Expr where bifoldMap = bifoldMapDefault -- (silence $ runExceptT $ getModules_ ["samples"] "M") >>= return . (\m -> fromRight' $ (ezipper $ Mod m) >>= lineColumn 6 5 >>= focus) . last . fromRight' -- _decls mm instance Bitraversable Expr where {-# INLINE bitraverse #-} -- for debugging: require Show b -- bitraverse :: Applicative f => (a -> f c) -> (b -> f d) -> Expr a b -> f (Expr c d) -- bitraverse :: (Applicative f, Show b) => (a -> f c) -> (b -> f d) -> Expr a b -> f (Expr c d) bitraverse f g = bt where bt (V a) = V <$> g a bt (Nat' x ) = Nat' <$> traverse f x bt (Ws_ x ws) = Ws_ <$> bt x <*> traverse f ws bt (Brackets_ bo x bc) = Brackets_ <$> traverse f bo <*> bt x <*> traverse f bc bt (Paren x) = Paren <$> bt x bt (Paren_ po x pc) = Paren_ <$> traverse f po <*> bt x <*> traverse f pc bt (Type) = pure Type bt (Type_ tt ws) = Type_ <$> f tt <*> traverse f ws bt (l :@ r) = (:@) <$> bt l <*> bt r bt (ErasedApp l r) = ErasedApp <$> bt l <*> bt r bt (BndV v ex) = BndV <$> f v <*> bt ex bt (Nat n) = Nat <$> pure n bt (Nat_ n ntxt ws) = Nat_ <$> pure n <*> f ntxt <*> traverse f ws bt (Lam p b) = Lam <$> f p <*> bitraverseScope f g b bt (Lam_ lamtok binder dot sc) = Lam_ <$> traverse f lamtok <*> traverse f binder <*> traverse f dot <*> bitraverseScope f g sc -- bt (Lam' p b) = Lam' <$> f p <*> bitraverseScope f g b bt (ErasedLam p b) = ErasedLam <$> f p <*> bitraverseScope f g b -- bt (Lams ts b) = Lams <$> traverse (traverse f) ts <*> bitraverseScope f g b bt (Lams ts b) = Lams <$> traverse f ts <*> bitraverseScope f g b bt (LamPA eps bnd annot sc) = LamPA <$> pure eps <*> f bnd <*> bitraverseAnnot f g annot <*> bitraverseScope f g sc bt (LamPAs ps sc) = LamPAs <$> btTripleList ps <*> bitraverseScope f g sc where btTriple (eps, nm, annot) = (,,) <$> pure eps <*> f nm <*> bitraverseAnnot f g annot btTripleList trs = traverse btTriple trs bt (LamPAs' ps sc) = LamPAs' <$> btTripleList ps <*> bitraverseScope f g sc where btTriple (eps, nm, annot) = (,,) <$> pure eps <*> traverse f nm <*> bitraverseAnnot f g annot btTripleList trs = traverse btTriple trs bt (LamPAs_ lamtok ps dot sc) = LamPAs_ <$> traverse f lamtok <*> btTripleList ps <*> traverse f dot <*> bitraverseScope f g sc where btTriple (eps, binder, annot) = (,,) <$> pure eps <*> traverse f binder <*> bitraverseAnnot f g annot btTripleList trs = traverse btTriple trs bt (Lams_ {}) = error "bt: Lams__" bt (If a b c annot) = If <$> bt a <*> bt b <*> bt c <*> bitraverse f g annot bt (If_ iftok a thentok b elsetok c annot) = If_ <$> traverse f iftok <*> bt a <*> traverse f thentok <*> bt b <*> traverse f elsetok <*> bt c <*> bitraverse f g annot bt (Position d b) = Position d <$> bt b bt (Pi nm ty sc) = Pi <$> f nm <*> bt ty <*> bitraverseScope f g sc bt (Pi_ ex arr sc) = Pi_ <$> bt ex <*> traverse f arr <*> bitraverseScope f g sc bt (PiP eps nm ty sc) = PiP <$> pure eps <*> f nm <*> bt ty <*> bitraverseScope f g sc bt (PiP_ eps ex arr sc) = PiP_ <$> pure eps <*> bt ex <*> traverse f arr <*> bitraverseScope f g sc bt (Ann ex ty) = Ann <$> bt ex <*> bt ty bt (WitnessedAnnEx_ ex colon ty) = WitnessedAnnEx_ <$> bt ex <*> traverse f colon <*> bt ty bt (InferredAnnBnd_ bnd ty) = InferredAnnBnd_ <$> traverse f bnd <*> bt ty bt (WitnessedAnnBnd_ bnd colon ty) = WitnessedAnnBnd_ <$> traverse f bnd <*> traverse f colon <*> bt ty bt (Ann_ ex) = Ann_ <$> bt ex -- -- bt (TCon tt exprs) = TCon <$> f tt <*> traverse bt exprs -- -- bt (TCon_ nm exprs) = TCon_ <$> traverse f nm <*> traverse bt exprs bt (TCon aa exprs) = TCon <$> g aa <*> traverse bt exprs bt (TCon_ nm exprs) = TCon_ <$> bitraverseNm f g nm <*> traverse bt exprs bt (DCon tt args annot) = DCon <$> f tt <*> traverse (bitraverseArg f g) args <*> bitraverseAnnot f g annot bt (DCon_ nm args annot) = DCon_ <$> traverse f nm <*> traverse (bitraverseArg f g) args <*> bitraverseAnnot f g annot -- better way of debugging ? - unfortunately we don't have Show b... -- bt other = error $ "bt: " ++ (show $ other) -- bt other = trace (show other) $ error $ "bt: " bt (TrustMe annot) = TrustMe <$> bitraverse f g annot bt (TrustMe_ tt ws annot) = TrustMe_ <$> f tt <*> traverse f ws <*> bitraverse f g annot -- -- bt (TyUnit {}) = error "bt: TyUnit" -- -- bt (TyUnit_ {}) = error "bt: TyUnit_" bt (TyUnit) = pure TyUnit bt (TyUnit_ tt ws) = TyUnit_ <$> f tt <*> traverse f ws bt (LitUnit) = pure LitUnit bt (LitUnit_ tt ws) = LitUnit_ <$> f tt <*> traverse f ws bt (LitBool b) = LitBool <$> pure b bt (LitBool_ b tok ws) = LitBool_ <$> pure b <*> f tok <*> traverse f ws bt TyBool = pure TyBool bt (TyBool_ tok ws) = TyBool_ <$> f tok <*> traverse f ws bt (Lam' {}) = error "bt: Lam'" bt (Lams' {}) = error "bt: Lams'" bt (Subst ex1 ex2 annot) = Subst <$> bt ex1 <*> bt ex2 <*> bitraverse f g annot bt (Subst_ subst ex1 by ex2 annot) = Subst_ <$> traverse f subst <*> bt ex1 <*> traverse f by <*> bt ex2 <*> bitraverse f g annot -- -- -- witness to an equality contradiction -- -- | Contra (Expr t a) (Annot t a) -- -- | Contra_ (ContraTok t) (Expr t a) (Annot t a) bt (Contra ex annot) = Contra <$> bt ex <*> bitraverse f g annot bt (Contra_ contratok ex annot) = Contra_ <$> traverse f contratok <*> bt ex <*> bitraverse f g annot bt (Sigma nm ex sc) = Sigma <$> f nm <*> bt ex <*> bitraverseScope f g sc bt (Sigma_ bo bndr col ex vbar sc bc) = Sigma_ <$> traverse f bo <*> traverse f bndr <*> traverse f col <*> bt ex <*> traverse f vbar <*> bitraverseScope f g sc <*> traverse f bc bt (TyEq ex1 ex2) = TyEq <$> bt ex1 <*> bt ex2 bt (TyEq_ ex1 eq ex2) = TyEq_ <$> bt ex1 <*> traverse f eq <*> bt ex2 bt (Refl annot) = Refl <$> bitraverseAnnot f g annot bt (Refl_ tt ws annot) = Refl_ <$> f tt <*> traverse f ws <*> bitraverseAnnot f g annot bt (Prod ex1 ex2 annot) = Prod <$> bt ex1 <*> bt ex2 <*> bitraverse f g annot bt (Prod_ po ex1 comma ex2 pc annot) = Prod_ <$> traverse f po <*> bt ex1 <*> traverse f comma <*> bt ex2 <*> traverse f pc <*> bitraverse f g annot -- -- bt (Let bs ss) = Let <$> traverse (bitraverse f g) bs <*> bitraverseScope f g ss bt (Let nm ex sc) = Let <$> f nm <*> bt ex <*> bitraverseScope f g sc bt (Let_ lettok bndr eq ex intok sc) = Let_ <$> traverse f lettok <*> traverse f bndr <*> traverse f eq <*> bt ex <*> traverse f intok <*> bitraverseScope f g sc bt (Pcase scrut (x, a) sc annot) = Pcase <$> bt scrut <*> ((,) <$> f x <*> f a) <*> bitraverseScope f g sc <*> bitraverseAnnot f g annot bt (Pcase_ pcase ex of' po s comma t pc arr sc annot) = Pcase_ <$> traverse f pcase <*> bt ex <*> traverse f of' <*> traverse f po <*> traverse f s <*> traverse f comma <*> traverse f t <*> traverse f pc <*> traverse f arr <*> bitraverseScope f g sc <*> bitraverse f g annot bt (Case ex matches annot) = Case <$> bitraverseExpr f g ex <*> traverse (bitraverseMatch f g) matches <*> bitraverseAnnot f g annot -- -- bt (Case_ casetok ex oftok mayopen matches mayclose annot) = -- -- Case_ -- -- <$> traverse f casetok -- -- <*> bitraverseExpr f g ex -- -- <*> traverse f oftok -- -- <*> traverse (traverse f) mayopen -- -- <*> btPairs matches -- -- <*> traverse (traverse f) mayclose -- -- <*> bitraverseAnnot f g annot -- -- where -- -- btPair (match, maysemi) = (,) <$> bitraverseMatch f g match <*> traverse (traverse f) maysemi -- -- btPairs ps = traverse btPair ps bt (Case_ casetok ex oftok mayopen matches mayclose annot) = Case_ <$> traverse f casetok <*> bitraverseExpr f g ex <*> traverse f oftok <*> traverse (traverse f) mayopen <*> btPairs matches <*> traverse (traverse f) mayclose <*> bitraverseAnnot f g annot where btPair (maysemi, match) = (,) <$> traverse (traverse f) maysemi <*> bitraverseMatch f g match btPairs ps = traverse btPair ps -- -- bt (CaseIndented_ casetok ex oftok matches annot) = -- -- CaseIndented_ -- -- <$> traverse f casetok -- -- <*> bitraverseExpr f g ex -- -- <*> traverse f oftok -- -- <*> traverse (bitraverseMatch f g) matches -- -- <*> bitraverseAnnot f g annot -- -- bt (CaseWithBraces_ casetok ex oftok bo matches bc annot) = -- -- CaseWithBraces_ -- -- <$> traverse f casetok -- -- <*> bitraverseExpr f g ex -- -- <*> traverse f oftok -- -- <*> traverse f bo -- -- <*> btPairs matches -- -- <*> traverse f bc -- -- <*> bitraverseAnnot f g annot -- -- where -- -- btPair (match, maysemi) = (,) <$> bitraverseMatch f g match <*> traverse (traverse f) maysemi -- -- btPairs ps = traverse btPair ps bitraverseExpr :: Applicative f => (a -> f c) -> (b -> f d) -> Expr a b -> f (Expr c d) bitraverseExpr = bitraverse -- for the sake of writing this in the least verbose manner: -- using record wild cards for data constructors that are not declared with record fields here, -- works fine, but is not allowed according to -- https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/syntax-extns.html -- hope this will not break in the future wsAware :: Expr t a -> Bool wsAware (V _) = False wsAware (Ws_ {}) = True wsAware (x :@ _) = wsAware x wsAware (ErasedApp x _) = wsAware x wsAware (Position _ x) = wsAware x wsAware (Lam {}) = False wsAware (Lam_ {}) = True wsAware (Lam' {}) = False wsAware (Lams' {}) = False wsAware (LamPA {}) = False -- doesn't exist -- wsAware (LamPA_ {}) = True wsAware (LamPAs {}) = False wsAware (LamPAs_ {}) = True wsAware (PiP {}) = False wsAware (PiP_ {}) = True wsAware (Sigma {}) = False wsAware (Sigma_ {}) = True wsAware (If {}) = False wsAware (If_ {}) = True wsAware (Prod {}) = False wsAware (Prod_ {}) = True wsAware (Case {}) = False -- -- wsAware (Case_ {}) = True -- -- wsAware (CaseIndented_ {}) = True -- -- wsAware (CaseWithBraces_ {}) = True wsAware (Pcase {}) = False wsAware (Pcase_ {}) = True wsAware (Nat_ {}) = True wsAware (Nat {}) = False wsAware (TCon {}) = False wsAware (TCon_ {}) = True wsAware (TyEq {}) = False wsAware (TyEq_ {}) = True wsAware (Ann {}) = False wsAware (WitnessedAnnEx_ {}) = True wsAware (InferredAnnBnd_ {}) = True wsAware (WitnessedAnnBnd_ {}) = True wsAware (Ann_ {}) = True -- no catch all so far: let it break -- -- an 'Annot' is optional type information data Annot t a = Annot (Maybe (Expr t a)) | Annot_ (Maybe (Expr t a)) (Ws t) deriving (Functor,Foldable,Traversable) instance Applicative (Annot t) where pure = Annot . Just . V (<*>) = ap -- todo: think about the other cases -- or maybe better make Annot/Annot_ newtypes and automatically derive Monad, Applicative -- Monad really needed ? instance Monad (Annot t) where return = Annot . Just . V Annot (Nothing) >>= _ = Annot (Nothing) instance Bifunctor Annot where bimap = bimapDefault instance Bifoldable Annot where bifoldMap = bifoldMapDefault instance Bitraversable Annot where bitraverse f g (Annot mayex) = Annot <$> traverse (bitraverseExpr f g) mayex bitraverse f g (Annot_ mayex ws) = Annot_ <$> traverse (bitraverseExpr f g) mayex <*> traverse f ws bitraverseAnnot :: Applicative f => (a -> f c) -> (b -> f d) -> Annot a b -> f (Annot c d) bitraverseAnnot = bitraverse data Match t a = Match (Pattern t a) (Scope Int (Expr t) a) | Match_ (Pattern t a) (Token 'ArrowTy t) (Scope Int (Expr t) a) deriving (Functor,Foldable,Traversable) instance Bifunctor Match where bimap = bimapDefault instance Bifoldable Match where bifoldMap = bifoldMapDefault instance Bitraversable Match where bitraverse f g (Match pattern sc) = Match <$> (bitraverse f g pattern) <*> bitraverseScope f g sc bitraverse f g (Match_ pattern arr sc) = Match_ <$> bitraverse f g pattern <*> traverse f arr <*> bitraverseScope f g sc bitraverseMatch :: Applicative f => (a -> f c) -> (b -> f d) -> Match a b -> f (Match c d) bitraverseMatch = bitraverse -- an argument is tagged with whether it should be erased data Arg t a = Arg Eps (Expr t a) deriving (Functor,Foldable,Traversable) instance Bifunctor Arg where bimap = bimapDefault instance Bifoldable Arg where bifoldMap = bifoldMapDefault instance Bitraversable Arg where bitraverse f g (Arg eps ex) = Arg <$> pure eps <*> bitraverseExpr f g ex bitraverseArg :: Applicative f => (a -> f c) -> (b -> f d) -> Arg a b -> f (Arg c d) bitraverseArg = bitraverse -- some lenses for common tasks: get the binders etc -- exmpls -- (nopos $ parse expr_ "\\ a b c . f a b" ) ^. bndrs bndrs :: Lens' (Expr t a) [Binder t] bndrs = lens getter setter where getter = (\case { ; (Pcase_ _ _ _ _ b _ b2 _ _ _ _) -> [b, b2] ; (Lam_ _ b _ _) -> [b] ; (Let_ _ b _ _ _ _) -> [b] ; (Sigma_ _ bndr _ _ _ _ _) -> [bndr] ; (WitnessedAnnBnd_ bndr _ _ ) -> [bndr] ; (InferredAnnBnd_ bndr _ ) -> [bndr] ; (PiP_ _ ex _ _) -> getter ex ; (Paren_ _ ex _ ) -> getter ex ; (Brackets_ _ ex _ ) -> getter ex ; (Ann_ ex) -> getter ex ; (LamPAs_ _ triples _ _) -> (^. _2) <$> triples -- ... ; _ -> error "bndrs > getter: missing Expr" }) -- haven't tried the setter yet, exmples? setter = (\e newbs -> case e of { ; Pcase_ pcasetok ex oftok po _ comma _ pc arr sc annot -> Pcase_ pcasetok ex oftok po (newbs !! 0) comma (newbs !! 1) pc arr sc annot ; Lam_ lamtok _ dot sc -> Lam_ lamtok (newbs !! 0) dot sc ; Let_ lettok _ eq ex in' sc -> Let_ lettok (newbs !! 0) eq ex in' sc ; Sigma_ bo _ colon ex vbar sc bc -> Sigma_ bo (newbs !! 0) colon ex vbar sc bc ; WitnessedAnnBnd_ _ col ex -> WitnessedAnnBnd_ (newbs !! 0) col ex ; InferredAnnBnd_ _ ex -> InferredAnnBnd_ (newbs !! 0) ex ; PiP_ eps ex arr sc -> PiP_ eps (setter ex newbs) arr sc ; Paren_ po ex pc -> Paren_ po (setter ex newbs) pc ; Brackets_ bo ex bc -> Brackets_ bo (setter ex newbs) bc ; Ann_ ex -> Ann_ (setter ex newbs) -- OK ? ; LamPAs_ lamtok triples dot sc -> LamPAs_ lamtok [(eps, newbs !! y, annot) | (eps, _, annot) <- triples, y <- [0..]] dot sc -- ... ; other -> other }) -- instance MkVisible t => GetNm (Expr t a) t where -- name' (InferredAnnBnd_ bndr _) = name' bndr -- name' (WitnessedAnnBnd_ bndr _ _) = name' bndr -- name' (WitnessedAnnEx_ ex _ _) = name' ex -- name' (Ws_ ex _) = name' ex -- -- name' (V x) = x -- name' (Ann_ ex) = name' ex -- name' (Paren_ _ ex _) = name' ex -- name' (Brackets_ _ ex _) = name' ex -- at the bottom of the file -- http://stackoverflow.com/questions/20876147/haskell-template-haskell-and-the-scope #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if MIN_VERSION_transformers(0,5,0) -- instance Eq t => Eq1 ((,,) Eps t) where -- liftEq eq (someEps, someT, more) (otherEps, otherT, other) = eq someEps otherEps && eq someT otherT && eq more other -- instance Eq t => Eq1 (Expr t) where -- liftEq eq (Lam n sc) (Lam n' sc') = n == n' && liftEq eq sc sc' -- data Triple t a = Triple Eps t (Annot t a) -- deriveEq1 ''Triple -- need Eq1 for triples as well -- defined here in a similar fashion as Eq for (,) in -- https://hackage.haskell.org/package/base-4.9.0.0/docs/src/Data.Functor.Classes.html class Eq3 g where liftEq3 :: (a -> b -> Bool) -> (c -> d -> Bool) -> (e -> f -> Bool) -> g a c e -> g b d f -> Bool instance Eq3 (,,) where liftEq3 e1 e2 e3 (x1, y1, z1) (x2, y2, z2) = e1 x1 x2 && e2 y1 y2 && e3 z1 z2 instance (Eq a, Eq b) => Eq1 ((,,) a b) where liftEq = liftEq3 (==) (==) -- class (Eq3 g) => Ord3 g where liftCompare3 :: (a -> b -> Ordering) -> (c -> d -> Ordering) -> (e -> f -> Ordering) -> g a c e -> g b d f -> Ordering instance Ord3 (,,) where liftCompare3 comp1 comp2 comp3 (x1, y1, z1) (x2, y2, z2) = comp1 x1 x2 `mappend` comp2 y1 y2 `mappend` comp3 z1 z2 instance (Ord a, Ord b) => Ord1 ((,,) a b) where liftCompare = liftCompare3 compare compare -- class Show3 f where liftShowsPrec3 :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> (Int -> c -> ShowS) -> ([c] -> ShowS) -> Int -> f a b c -> ShowS liftShowList3 :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> (Int -> c -> ShowS) -> ([c] -> ShowS) -> [f a b c] -> ShowS liftShowList3 sp1 sl1 sp2 sl2 sp3 sl3 = showListWith (liftShowsPrec3 sp1 sl1 sp2 sl2 sp3 sl3 0) instance Show3 (,,) where liftShowsPrec3 sp1 _ sp2 _ sp3 _ _ (x, y, z) = showChar '(' . sp1 0 x . showChar ',' . sp2 0 y . showChar ',' . sp3 0 z . showChar ')' instance (Show a, Show b) => Show1 ((,,) a b) where liftShowsPrec = liftShowsPrec3 showsPrec showList showsPrec showList deriveEq1 ''Expr deriveOrd1 ''Expr deriveShow1 ''Expr -- deriveRead1 ''Expr deriving instance (Eq t, Eq a) => Eq (Expr t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Expr t a) deriving instance (Ord t, Ord a) => Ord (Expr t a) deriving instance (Show t, Show a) => Show (Expr t a) -- deriving instance (Read t, Read a) => Read (Expr t a) #else instance Eq t => Eq1 (Expr t) instance (Ord t, Typeable t) => Ord1 (Expr t) -- instance Ord t => Ord1 (Expr t) instance Show t => Show1 (Expr t) -- instance Read t => Read1 (Expr t) deriving instance (Eq t, Eq a) => Eq (Expr t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Expr t a) -- deriving instance (Ord t, Ord a) => Ord (Expr t a) deriving instance (Show t, Show a) => Show (Expr t a) -- deriving instance (Read t, Read a, Read Delta, Read (PossiblyVar t)) => Read (Expr t a) #endif #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) deriveEq1 ''Annot deriveOrd1 ''Annot deriveShow1 ''Annot -- deriveRead1 ''Annot deriving instance (Eq t, Eq a) => Eq (Annot t a) deriving instance (Ord t, Ord a) => Ord (Annot t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Annot t a) deriving instance (Show t, Show a) => Show (Annot t a) -- deriving instance (Read t, Read a) => Read (Annot t a) #else instance Eq t => Eq1 (Annot t) -- instance (Ord t, Typeable t) => Ord1 (Annot t) -- instance Ord t => Ord1 (Annotr t) instance Show t => Show1 (Annot t) -- instance Read t => Read1 (Annotr t) deriving instance (Eq t, Eq a) => Eq (Annot t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Annot t a) -- deriving instance (Ord t, Ord a) => Ord (Annot t a) deriving instance (Show t, Show a) => Show (Annot t a) #endif #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) deriveEq1 ''Arg deriveOrd1 ''Arg deriveShow1 ''Arg -- deriveRead1 ''Arg deriving instance (Eq t, Eq a) => Eq (Arg t a) deriving instance (Ord t, Ord a) => Ord (Arg t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Arg t a) deriving instance (Show t, Show a) => Show (Arg t a) -- deriving instance (Read t, Read a) => Read (Arg t a) #else instance Eq t => Eq1 (Arg t) -- instance (Ord t, Typeable t) => Ord1 (Arg t) -- instance Ord t => Ord1 (Argr t) instance Show t => Show1 (Arg t) -- instance Read t => Read1 (Argr t) deriving instance (Eq t, Eq a) => Eq (Arg t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Arg t a) -- deriving instance (Ord t, Ord a) => Ord (Arg t a) deriving instance (Show t, Show a) => Show (Arg t a) #endif #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) deriveEq1 ''Match deriveOrd1 ''Match deriveShow1 ''Match -- deriveRead1 ''Match deriving instance (Eq t, Eq a) => Eq (Match t a) deriving instance (Ord t, Ord a) => Ord (Match t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Match t a) deriving instance (Show t, Show a) => Show (Match t a) -- deriving instance (Read t, Read a) => Read (Match t a) #else instance Eq t => Eq1 (Match t) instance (Ord t, Typeable t) => Ord1 (Match t) -- instance Ord t => Ord1 (Match t) instance Show t => Show1 (Match t) -- instance Read t => Read1 (Match t) deriving instance (Eq t, Eq a) => Eq (Match t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Match t a) -- deriving instance (Ord t, Ord a) => Ord (Match t a) deriving instance (Show t, Show a) => Show (Match t a) #endif
reuleaux/pire
src/Pire/Syntax/Expr.hs
bsd-3-clause
48,148
2
19
15,487
13,010
6,705
6,305
516
23
{-| Module : Graphics.Sudbury.Protocol.Runtime Description : Protocol data without docs: can project XML protocols to runtime protocols Copyright : (c) Auke Booij, 2015-2017 License : MIT Maintainer : [email protected] Stability : experimental Portability : POSIX -} module Graphics.Sudbury.Protocol.Runtime where
abooij/sudbury
Graphics/Sudbury/Protocol/Runtime.hs
mit
326
0
3
53
9
7
2
1
0
------------------------------------------------------------------------- -- -- MakeTree.hs -- -- Turn a frequency table into a Huffman tree -- -- (c) Addison-Wesley, 1996-2011. -- ------------------------------------------------------------------------- module MakeTree ( makeTree ) where import Types ( Tree(Leaf,Node), Bit(L,R), HCode, Table ) -- Convert the trees to a list, then amalgamate into a single -- tree. makeTree :: [ (Char,Int) ] -> Tree makeTree = makeCodes . toTreeList -- Huffman codes are created bottom up: look for the least -- two frequent letters, make these a new "isAlpha" (i.e. tree) -- and repeat until one tree formed. -- The function toTreeList makes the initial data structure. toTreeList :: [ (Char,Int) ] -> [ Tree ] toTreeList = map (uncurry Leaf) -- The value of a tree. value :: Tree -> Int value (Leaf _ n) = n value (Node n _ _) = n -- Pair two trees. pair :: Tree -> Tree -> Tree pair t1 t2 = Node (v1+v2) t1 t2 where v1 = value t1 v2 = value t2 -- Insert a tree in a list of trees sorted by ascending value. insTree :: Tree -> [Tree] -> [Tree] insTree t [] = [t] insTree t (t1:ts) | (value t <= value t1) = t:t1:ts | otherwise = t1 : insTree t ts -- -- Amalgamate the front two elements of the list of trees. amalgamate :: [ Tree ] -> [ Tree ] amalgamate ( t1 : t2 : ts ) = insTree (pair t1 t2) ts -- Make codes: amalgamate the whole list. makeCodes :: [Tree] -> Tree makeCodes [t] = t makeCodes ts = makeCodes (amalgamate ts)
Numberartificial/workflow
snipets/src/Craft/Chapter15/MakeTree.hs
mit
1,891
0
10
691
402
228
174
24
1
{- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} program = drawingOf(blank) 5 = 2 + 2
alphalambda/codeworld
codeworld-compiler/test/testcases/varlessPattern/source.hs
apache-2.0
648
0
6
124
23
12
11
2
1
-- | Parallel Arrays. --- -- Parallel arrays use a fixed generic representation. All data stored in -- them is converted to the generic representation, and we have a small -- number of operators that work on arrays of these generic types. -- -- Representation types include Ints, Floats, Tuples and Sums, so arrays of -- these types can be stored directly. However, user defined algebraic data -- needs to be converted as we don't have operators that work directly on -- arrays of these types. -- -- The top-level PArray type is built up from several type families and -- clases: -- -- PArray - This is the top level type. It holds an array length, -- and array data in the generic representation (PData). -- -- PRepr - Family of types that can be converted to the generic -- representation. We supply instances for basic types -- like Ints Floats etc, but the vectoriser needs to make -- the instances for user-defined data types itself. -- PA class - Contains methods to convert to and from the generic -- representation (PData). -- -- PData - Family of types that can be stored directly in parallel -- arrays. We supply all the PData instances we need here -- in the library. -- PR class - Contains methods that work directly on parallel arrays. -- Most of these are just wrappers for the corresponding -- U.Array operators. -- -- Scalar class - Contains methods to convert between the generic -- representation (PData) and plain U.Arrays. -- -- Note that the PRepr family and PA class are related. -- so are the PData family and PR class. -- -- For motivational material see: -- "An Approach to Fast Arrays in Haskell", Chakravarty and Keller, 2003 -- -- For discussion of how the mapping to generic types works see: -- "Instant Generics: Fast and Easy", Chakravarty, Ditu and Keller, 2009 -- module Data.Array.Parallel.PArray ( PArray, PA, Random(..), -- * Evaluation nf, -- * Constructors empty, singleton, replicate, (+:+), concat, nestUSegd, -- * Projections length, (!:), slice, -- * Update update, -- * Pack and Combine pack, bpermute, -- * Enumerations enumFromTo, indexed, -- * Tuples zip, unzip, -- * Conversions fromList, toList, fromUArray, toUArray, fromUArray2, fromUArray3 ) where import Data.Array.Parallel.Lifted.PArray import Data.Array.Parallel.PArray.PReprInstances () import Data.Array.Parallel.Lifted.Combinators import Data.Array.Parallel.Lifted.Scalar import Data.Array.Parallel.Base.Text import qualified Data.Array.Parallel.Unlifted as U import qualified System.Random as R import Prelude hiding ( length, replicate, zip, unzip, enumFromTo, concat ) -- NOTE: -- Most of these functions just export the corresponding "vectorised" -- function from "Data.Array.Parallel.Lifted.Closure". We don't export -- higher-order functions like map and filter because the versions -- from there want closures as their function parameters. -- -- Instead, we should probably move the first-order "vectorised" -- functions from D.A.P.L.Closure into this module, and just define -- the higher-order and lifted ones there. -- -- We still want to export these plain PArray functions to make it easier -- to convert between vectorised and unvectorised code in benchmarks. -- -- | O(1). An empty array, with no elements. empty :: PA a => PArray a {-# INLINE empty #-} empty = emptyPA -- | O(1). Retrieve a numbered element from an array. (!:) :: PA a => PArray a -> Int -> a {-# INLINE (!:) #-} (!:) = indexPA_v -- | O(1). Yield the length of an array. length :: PA a => PArray a -> Int {-# INLINE length #-} length = lengthPA_v -- | O(n). Produce an array containing copies of a given element. replicate :: PA a => Int -> a -> PArray a {-# INLINE replicate #-} replicate = replicatePA_v -- | O(1). Produce an array containing a single element. singleton :: PA a => a -> PArray a {-# INLINE singleton #-} singleton = singletonPA_v -- | O(1). Takes two arrays and returns an array of corresponding pairs. -- If one array is short, excess elements of the longer array are -- discarded. zip :: (PA a, PA b) => PArray a -> PArray b -> PArray (a,b) {-# INLINE zip #-} zip = zipPA_v -- | O(1). Transform an array into an array of the first components, -- and an array of the second components. unzip :: (PA a, PA b) => PArray (a,b) -> (PArray a, PArray b) {-# INLINE unzip #-} unzip = unzipPA_v -- | Select the elements of an array that have their tag set as True. -- -- @ -- packPA [12, 24, 42, 93] [True, False, False, True] -- = [24, 42] -- @ pack :: PA a => PArray a -> PArray Bool -> PArray a {-# INLINE pack #-} pack = packPA_v -- | Concatenate an array of arrays into a single array. concat :: PA a => PArray (PArray a) -> PArray a {-# INLINE concat #-} concat = concatPA_v -- | Append two arrays (+:+) :: PA a => PArray a -> PArray a -> PArray a {-# INLINE (+:+) #-} (+:+) = appPA_v -- | O(n). Tag each element of an array with its index. -- -- @indexed [42, 93, 13] = [(0, 42), (1, 93), (2, 13)]@ -- indexed :: PA a => PArray a -> PArray (Int, a) {-# INLINE indexed #-} indexed = indexedPA_v -- | Extract a subrange of elements from an array. -- The first argument is the starting index, while the second is the -- length of the slice. -- slice :: PA a => Int -> Int -> PArray a -> PArray a {-# INLINE slice #-} slice = slicePA_v -- | Copy the source array in the destination, using new values for the given indices. update :: PA a => PArray a -> PArray (Int,a) -> PArray a {-# INLINE update #-} update = updatePA_v -- | O(n). Backwards permutation of array elements. -- -- @bpermute [50, 60, 20, 30] [0, 3, 2] = [50, 30, 20]@ -- bpermute :: PA a => PArray a -> PArray Int -> PArray a {-# INLINE bpermute #-} bpermute = bpermutePA_v -- | O(n). Generate a range of @Int@s. enumFromTo :: Int -> Int -> PArray Int {-# INLINE enumFromTo #-} enumFromTo = enumFromToPA_v -- Conversion ----------------------------------------------------------------- -- | Create a `PArray` from a list. fromList :: PA a => [a] -> PArray a {-# INLINE fromList #-} fromList = fromListPA -- | Create a list from a `PArray`. toList :: PA a => PArray a -> [a] toList xs = [indexPA_v xs i | i <- [0 .. length xs - 1]] instance (PA a, Show a) => Show (PArray a) where showsPrec n xs = showsApp n "fromList<PArray>" (toList xs) -- Evaluation ----------------------------------------------------------------- -- | Ensure an array is fully evaluated. nf :: PA a => PArray a -> () nf = nfPA -- Randoms -------------------------------------------------------------------- class Random a where randoms :: R.RandomGen g => Int -> g -> PArray a randomRs :: R.RandomGen g => Int -> (a, a) -> g -> PArray a prim_randoms :: (Scalar a, R.Random a, R.RandomGen g) => Int -> g -> PArray a prim_randoms n = fromUArray . U.randoms n prim_randomRs :: (Scalar a, R.Random a, R.RandomGen g) => Int -> (a, a) -> g -> PArray a prim_randomRs n r = fromUArray . U.randomRs n r instance Random Int where randoms = prim_randoms randomRs = prim_randomRs instance Random Double where randoms = prim_randoms randomRs = prim_randomRs
mainland/dph
dph-lifted-copy/Data/Array/Parallel/PArray.hs
bsd-3-clause
7,497
0
11
1,739
1,192
700
492
98
1
-- | Unsafe coerce. module Unsafe.Coerce where import FFI unsafeCoerce :: a -> b unsafeCoerce = ffi "%1"
beni55/fay
fay-base/src/Unsafe/Coerce.hs
bsd-3-clause
108
0
5
21
27
16
11
4
1
module Network.MPD.Applicative ( Command , runCommand -- * Querying MPD's status , module Network.MPD.Applicative.Status -- * Playback options , module Network.MPD.Applicative.PlaybackOptions -- * Controlling playback , module Network.MPD.Applicative.PlaybackControl -- * The current playlist , module Network.MPD.Applicative.CurrentPlaylist -- * Stored playlists , module Network.MPD.Applicative.StoredPlaylists -- * The music database , module Network.MPD.Applicative.Database -- * Stickers , module Network.MPD.Applicative.Stickers -- * Connection settings , module Network.MPD.Applicative.Connection -- * Audio output devices , module Network.MPD.Applicative.Output -- * Reflection , module Network.MPD.Applicative.Reflection -- * Mounting , module Network.MPD.Applicative.Mount -- * Client-to-client , module Network.MPD.Applicative.ClientToClient ) where import Network.MPD.Applicative.Internal import Network.MPD.Applicative.ClientToClient import Network.MPD.Applicative.Connection import Network.MPD.Applicative.CurrentPlaylist import Network.MPD.Applicative.Database import Network.MPD.Applicative.Mount import Network.MPD.Applicative.Output import Network.MPD.Applicative.PlaybackControl import Network.MPD.Applicative.PlaybackOptions import Network.MPD.Applicative.Reflection import Network.MPD.Applicative.Status import Network.MPD.Applicative.Stickers import Network.MPD.Applicative.StoredPlaylists
matthewleon/libmpd-haskell
src/Network/MPD/Applicative.hs
mit
1,428
0
5
134
214
159
55
28
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module HERMIT.Dictionary.Induction ( -- * Induction externals , caseSplitOnR ) where import Control.Arrow import Control.Monad import Data.String import HERMIT.Context import HERMIT.Core import HERMIT.External import HERMIT.GHC import HERMIT.Kure import HERMIT.Lemma import HERMIT.Name import HERMIT.Dictionary.Common import HERMIT.Dictionary.Local.Case hiding (externals) import HERMIT.Dictionary.Undefined hiding (externals) ------------------------------------------------------------------------------ externals :: [External] externals = [ external "induction" (promoteClauseR . caseSplitOnR True . cmpHN2Var :: HermitName -> RewriteH LCore) [ "Induct on specified value quantifier." ] , external "prove-by-cases" (promoteClauseR . caseSplitOnR False . cmpHN2Var :: HermitName -> RewriteH LCore) [ "Case split on specified value quantifier." ] ] ------------------------------------------------------------------------------ -- TODO: revisit design here to make one level caseSplitOnR :: Bool -> (Id -> Bool) -> RewriteH Clause caseSplitOnR induction idPred = withPatFailMsg "induction can only be performed on universally quantified terms." $ do let p b = idPred b && isId b (bs, cl) <- arr collectQs guardMsg (any p bs) "specified identifier is not universally quantified in this lemma. (Induction cannot be performed on type quantifiers.)" let (as,b:bs') = break p bs -- safe because above guard guardMsg (not (any p bs')) "multiple matching quantifiers." ue <- mkUndefinedValT (varType b) -- undefined case cases <- liftM (ue:) $ constT $ caseExprsForM $ varToCoreExpr b let newBs = as ++ bs' substructural = filter (typeAlphaEq (varType b) . varType) go [] = return [] go (e:es) = do let cl' = substClause b e cl fvs = varSetElems $ delVarSetList (localFreeVarsExpr e) newBs -- Generate induction hypotheses for the recursive cases. antes <- if induction then forM (zip [(0::Int)..] $ substructural fvs) $ \ (i,b') -> withVarsInScope fvs $ transform $ \ c q -> let nm = fromString $ "ind-hyp-" ++ show i in liftM ((nm,) . discardUniVars) $ instClause (boundVars c) (==b) (Var b') q else return [] rs <- go es return $ mkForall fvs (foldr (uncurry Impl) cl' antes) : rs qs <- go cases return $ mkForall newBs $ foldr1 Conj qs
ku-fpg/hermit
src/HERMIT/Dictionary/Induction.hs
bsd-2-clause
2,691
0
25
664
697
360
337
52
3
{- | Module : $Id$ Description : shared ATerm conversion instances Copyright : (c) Christian Maeder and Uni Bremen 2005-2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable (existential types) This folder provides conversion methods, converting between Hets data structures and shared ATerms. Most of the modules have been automatically created using /DriFT/ from the /utils/ folder. An execption are the modules with existential types, such as "ATC.Grothendieck". -} module ATC where
mariefarrell/Hets
ATC.hs
gpl-2.0
594
0
2
105
5
4
1
1
0