code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE RankNTypes #-}
module Main where
import Test.Framework (defaultMain)
------------------------------------------------------------------------------
import qualified Data.HashTable.Test.Common as Common
import qualified Data.HashTable.ST.Basic as B
import qualified Data.HashTable.ST.Cuckoo as C
import qualified Data.HashTable.ST.Linear as L
import qualified Data.HashTable.IO as IO
------------------------------------------------------------------------------
main :: IO ()
main = defaultMain tests
where
dummyBasicTable = Common.dummyTable
:: forall k v . IO.IOHashTable (B.HashTable) k v
dummyCuckooTable = Common.dummyTable
:: forall k v . IO.IOHashTable (C.HashTable) k v
dummyLinearTable = Common.dummyTable
:: forall k v . IO.IOHashTable (L.HashTable) k v
basicTests = Common.tests "basic" dummyBasicTable
cuckooTests = Common.tests "cuckoo" dummyCuckooTable
linearTests = Common.tests "linear" dummyLinearTable
tests = [basicTests, linearTests, cuckooTests]
|
cornell-pl/HsAdapton
|
weak-hashtables/test/suite/TestSuite.hs
|
Haskell
|
bsd-3-clause
| 1,086
|
module Web.Routes.Site where
import Data.ByteString
import Data.Monoid
import Data.Text (Text)
import Web.Routes.Base (decodePathInfo, encodePathInfo)
{-|
A site groups together the three functions necesary to make an application:
* A function to convert from the URL type to path segments.
* A function to convert from path segments to the URL, if possible.
* A function to return the application for a given URL.
There are two type parameters for Site: the first is the URL datatype, the
second is the application datatype. The application datatype will depend upon
your server backend.
-}
data Site url a
= Site {
{-|
Return the appropriate application for a given URL.
The first argument is a function which will give an appropriate
URL (as a String) for a URL datatype. This is usually
constructed by a combination of 'formatPathSegments' and the
prepending of an absolute application root.
Well behaving applications should use this function to
generating all internal URLs.
-}
handleSite :: (url -> [(Text, Maybe Text)] -> Text) -> url -> a
-- | This function must be the inverse of 'parsePathSegments'.
, formatPathSegments :: url -> ([Text], [(Text, Maybe Text)])
-- | This function must be the inverse of 'formatPathSegments'.
, parsePathSegments :: [Text] -> Either String url
}
-- | Override the \"default\" URL, ie the result of 'parsePathSegments' [].
setDefault :: url -> Site url a -> Site url a
setDefault defUrl (Site handle format parse) =
Site handle format parse'
where
parse' [] = Right defUrl
parse' x = parse x
instance Functor (Site url) where
fmap f site = site { handleSite = \showFn u -> f (handleSite site showFn u) }
-- | Retrieve the application to handle a given request.
--
-- NOTE: use 'decodePathInfo' to convert a 'ByteString' url to a properly decoded list of path segments
runSite :: Text -- ^ application root, with trailing slash
-> Site url a
-> [Text] -- ^ path info, (call 'decodePathInfo' on path with leading slash stripped)
-> (Either String a)
runSite approot site pathInfo =
case parsePathSegments site pathInfo of
(Left errs) -> (Left errs)
(Right url) -> Right $ handleSite site showFn url
where
showFn url qs =
let (pieces, qs') = formatPathSegments site url
in approot `mappend` (encodePathInfo pieces (qs ++ qs'))
|
shockkolate/web-routes
|
Web/Routes/Site.hs
|
Haskell
|
bsd-3-clause
| 2,569
|
module Main where
import Test.QuickCheck
import Data.List
mult :: Int -> Int -> Int -> Int
mult x y z = x*y*z
prop_mult x y z = (x * y * z) == mult x y z
prop_factorial_monotone (Positive x) = factorial x <= (factorial x+1)
newtype SmallIntList = SmallIntList [Int] deriving (Eq,Show)
instance Arbitrary SmallIntList where
arbitrary = sized $ \s -> do
n <- choose (0,s `min` 8)
xs <- vectorOf n (choose (-10000,10000))
return (SmallIntList xs)
shrink (SmallIntList xs) = map SmallIntList (shrink xs)
main = do
quickCheck prop_mult
|
chadbrewbaker/combinat
|
tests/Check.hs
|
Haskell
|
bsd-3-clause
| 599
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, TupleSections,
GeneralizedNewtypeDeriving, DeriveTraversable #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| JSON utility functions. -}
{-
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 Ganeti.JSON
( fromJResult
, fromJResultE
, readJSONWithDesc
, readEitherString
, JSRecord
, loadJSArray
, fromObj
, maybeFromObj
, fromObjWithDefault
, fromKeyValue
, fromJVal
, fromJValE
, jsonHead
, getMaybeJsonHead
, getMaybeJsonElem
, asJSObject
, asObjectList
, tryFromObj
, arrayMaybeFromJVal
, tryArrayMaybeFromObj
, toArray
, optionalJSField
, optFieldsToObj
, containerFromList
, lookupContainer
, alterContainerL
, readContainer
, mkUsedKeys
, allUsedKeys
, DictObject(..)
, showJSONtoDict
, readJSONfromDict
, ArrayObject(..)
, HasStringRepr(..)
, GenericContainer(..)
, emptyContainer
, Container
, MaybeForJSON(..)
, TimeAsDoubleJSON(..)
, Tuple5(..)
, nestedAccessByKey
, nestedAccessByKeyDotted
, branchOnField
, addField
, maybeParseMap
)
where
import Control.Applicative
import Control.DeepSeq
import Control.Monad.Error.Class
import Control.Monad.Writer
import qualified Data.Foldable as F
import qualified Data.Text as T
import qualified Data.Traversable as F
import Data.Maybe (fromMaybe, catMaybes)
import qualified Data.Map as Map
import qualified Data.Set as Set
import System.Time (ClockTime(..))
import Text.Printf (printf)
import qualified Text.JSON as J
import qualified Text.JSON.Types as JT
import Text.JSON.Pretty (pp_value)
-- Note: this module should not import any Ganeti-specific modules
-- beside BasicTypes, since it's used in THH which is used itself to
-- build many other modules.
import Ganeti.BasicTypes
-- Remove after we require >= 1.8.58
-- See: https://github.com/ndmitchell/hlint/issues/24
{-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-}
-- * JSON-related functions
instance NFData J.JSValue where
rnf J.JSNull = ()
rnf (J.JSBool b) = rnf b
rnf (J.JSRational b r) = rnf b `seq` rnf r
rnf (J.JSString s) = rnf $ J.fromJSString s
rnf (J.JSArray a) = rnf a
rnf (J.JSObject o) = rnf o
instance (NFData a) => NFData (J.JSObject a) where
rnf = rnf . J.fromJSObject
-- | A type alias for a field of a JSRecord.
type JSField = (String, J.JSValue)
-- | A type alias for the list-based representation of J.JSObject.
type JSRecord = [JSField]
-- | Annotate @readJSON@ error messages with descriptions of what
-- is being parsed into what.
readJSONWithDesc :: (J.JSON a)
=> String -- ^ description of @a@
-> Bool -- ^ include input in
-- error messages
-> J.JSValue -- ^ input value
-> J.Result a
readJSONWithDesc name incInput input =
case J.readJSON input of
J.Ok r -> J.Ok r
J.Error e -> J.Error $ if incInput then msg ++ " from " ++ show input
else msg
where msg = "Can't parse value for '" ++ name ++ "': " ++ e
-- | Converts a JSON Result into a monadic value.
fromJResult :: Monad m => String -> J.Result a -> m a
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
fromJResult _ (J.Ok x) = return x
-- | Converts a JSON Result into a MonadError value.
fromJResultE :: (Error e, MonadError e m) => String -> J.Result a -> m a
fromJResultE s (J.Error x) = throwError . strMsg $ s ++ ": " ++ x
fromJResultE _ (J.Ok x) = return x
-- | Tries to read a string from a JSON value.
--
-- In case the value was not a string, we fail the read (in the
-- context of the current monad.
readEitherString :: (Monad m) => J.JSValue -> m String
readEitherString v =
case v of
J.JSString s -> return $ J.fromJSString s
_ -> fail "Wrong JSON type"
-- | Converts a JSON message into an array of JSON objects.
loadJSArray :: (Monad m)
=> String -- ^ Operation description (for error reporting)
-> String -- ^ Input message
-> m [J.JSObject J.JSValue]
loadJSArray s = fromJResult s . J.decodeStrict
-- | Helper function for missing-key errors
buildNoKeyError :: JSRecord -> String -> String
buildNoKeyError o k =
printf "key '%s' not found, object contains only %s" k (show (map fst o))
-- | Reads the value of a key in a JSON object.
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
fromObj o k =
case lookup k o of
Nothing -> fail $ buildNoKeyError o k
Just val -> fromKeyValue k val
-- | Reads the value of an optional key in a JSON object. Missing
-- keys, or keys that have a \'null\' value, will be returned as
-- 'Nothing', otherwise we attempt deserialisation and return a 'Just'
-- value.
maybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m (Maybe a)
maybeFromObj o k =
case lookup k o of
Nothing -> return Nothing
-- a optional key with value JSNull is the same as missing, since
-- we can't convert it meaningfully anyway to a Haskell type, and
-- the Python code can emit 'null' for optional values (depending
-- on usage), and finally our encoding rules treat 'null' values
-- as 'missing'
Just J.JSNull -> return Nothing
Just val -> liftM Just (fromKeyValue k val)
-- | Reads the value of a key in a JSON object with a default if
-- missing. Note that both missing keys and keys with value \'null\'
-- will cause the default value to be returned.
fromObjWithDefault :: (J.JSON a, Monad m) =>
JSRecord -> String -> a -> m a
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
arrayMaybeFromJVal :: (J.JSON a, Monad m) => J.JSValue -> m [Maybe a]
arrayMaybeFromJVal (J.JSArray xs) =
mapM parse xs
where
parse J.JSNull = return Nothing
parse x = liftM Just $ fromJVal x
arrayMaybeFromJVal v =
fail $ "Expecting array, got '" ++ show (pp_value v) ++ "'"
-- | Reads an array of optional items
arrayMaybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m [Maybe a]
arrayMaybeFromObj o k =
case lookup k o of
Just a -> arrayMaybeFromJVal a
_ -> fail $ buildNoKeyError o k
-- | Wrapper for arrayMaybeFromObj with better diagnostic
tryArrayMaybeFromObj :: (J.JSON a)
=> String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result [Maybe a]
tryArrayMaybeFromObj t o = annotateResult t . arrayMaybeFromObj o
-- | Reads a JValue, that originated from an object key.
fromKeyValue :: (J.JSON a, Monad m)
=> String -- ^ The key name
-> J.JSValue -- ^ The value to read
-> m a
fromKeyValue k val =
fromJResult (printf "key '%s'" k) (J.readJSON val)
-- | Small wrapper over readJSON.
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
fromJVal v =
case J.readJSON v of
J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++
"', error: " ++ s)
J.Ok x -> return x
-- | Small wrapper over 'readJSON' for 'MonadError'.
fromJValE :: (Error e, MonadError e m, J.JSON a) => J.JSValue -> m a
fromJValE v =
case J.readJSON v of
J.Error s -> throwError . strMsg $
"Cannot convert value '" ++ show (pp_value v) ++
"', error: " ++ s
J.Ok x -> return x
-- | Helper function that returns Null or first element of the list.
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
jsonHead [] _ = J.JSNull
jsonHead (x:_) f = J.showJSON $ f x
-- | Helper for extracting Maybe values from a possibly empty list.
getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue
getMaybeJsonHead [] _ = J.JSNull
getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x)
-- | Helper for extracting Maybe values from a list that might be too short.
getMaybeJsonElem :: (J.JSON b) => [a] -> Int -> (a -> Maybe b) -> J.JSValue
getMaybeJsonElem [] _ _ = J.JSNull
getMaybeJsonElem xs 0 f = getMaybeJsonHead xs f
getMaybeJsonElem (_:xs) n f
| n < 0 = J.JSNull
| otherwise = getMaybeJsonElem xs (n - 1) f
-- | Converts a JSON value into a JSON object.
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
asJSObject (J.JSObject a) = return a
asJSObject _ = fail "not an object"
-- | Coneverts a list of JSON values into a list of JSON objects.
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
asObjectList = mapM asJSObject
-- | Try to extract a key from an object with better error reporting
-- than fromObj.
tryFromObj :: (J.JSON a) =>
String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result a
tryFromObj t o = annotateResult t . fromObj o
-- | Ensure a given JSValue is actually a JSArray.
toArray :: (Monad m) => J.JSValue -> m [J.JSValue]
toArray (J.JSArray arr) = return arr
toArray o =
fail $ "Invalid input, expected array but got " ++ show (pp_value o)
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField
-- will be Nothing as well.
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField
optionalJSField name (Just value) = Just (name, J.showJSON value)
optionalJSField _ Nothing = Nothing
-- | Creates an object with all the non-Nothing fields of the given list.
optFieldsToObj :: [Maybe JSField] -> J.JSValue
optFieldsToObj = J.makeObj . catMaybes
-- * Container type (special type for JSON serialisation)
-- | Class of types that can be converted from Strings. This is
-- similar to the 'Read' class, but it's using a different
-- serialisation format, so we have to define a separate class. Mostly
-- useful for custom key types in JSON dictionaries, which have to be
-- backed by strings.
class HasStringRepr a where
fromStringRepr :: (Monad m) => String -> m a
toStringRepr :: a -> String
-- | Trivial instance 'HasStringRepr' for 'String'.
instance HasStringRepr String where
fromStringRepr = return
toStringRepr = id
-- | The container type, a wrapper over Data.Map
newtype GenericContainer a b =
GenericContainer { fromContainer :: Map.Map a b }
deriving (Show, Eq, Ord, Functor, F.Foldable, F.Traversable)
instance (NFData a, NFData b) => NFData (GenericContainer a b) where
rnf = rnf . Map.toList . fromContainer
-- | The empty container.
emptyContainer :: GenericContainer a b
emptyContainer = GenericContainer Map.empty
-- | Type alias for string keys.
type Container = GenericContainer String
-- | Creates a GenericContainer from a list of key-value pairs.
containerFromList :: Ord a => [(a,b)] -> GenericContainer a b
containerFromList = GenericContainer . Map.fromList
-- | Looks up a value in a container with a default value.
-- If a key has no value, a given monadic default is returned.
-- This allows simple error handling, as the default can be
-- 'mzero', 'failError' etc.
lookupContainer :: (Monad m, Ord a)
=> m b -> a -> GenericContainer a b -> m b
lookupContainer dflt k = maybe dflt return . Map.lookup k . fromContainer
-- | Updates a value inside a container.
-- The signature of the function is crafted so that it can be directly
-- used as a lens.
alterContainerL :: (Functor f, Ord a)
=> a
-> (Maybe b -> f (Maybe b))
-> GenericContainer a b
-> f (GenericContainer a b)
alterContainerL key f (GenericContainer m) =
fmap (\v -> GenericContainer $ Map.alter (const v) key m)
(f $ Map.lookup key m)
-- | Container loader.
readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) =>
J.JSObject J.JSValue -> m (GenericContainer a b)
readContainer obj = do
let kjvlist = J.fromJSObject obj
kalist <- mapM (\(k, v) -> do
k' <- fromStringRepr k
v' <- fromKeyValue k v
return (k', v')) kjvlist
return $ GenericContainer (Map.fromList kalist)
{-# ANN showContainer "HLint: ignore Use ***" #-}
-- | Container dumper.
showContainer :: (HasStringRepr a, J.JSON b) =>
GenericContainer a b -> J.JSValue
showContainer =
J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) .
Map.toList . fromContainer
instance (HasStringRepr a, Ord a, J.JSON b) =>
J.JSON (GenericContainer a b) where
showJSON = showContainer
readJSON (J.JSObject o) = readContainer o
readJSON v = fail $ "Failed to load container, expected object but got "
++ show (pp_value v)
-- * Types that (de)serialize in a special form of JSON
newtype UsedKeys = UsedKeys (Maybe (Set.Set String))
instance Monoid UsedKeys where
mempty = UsedKeys (Just Set.empty)
mappend (UsedKeys xs) (UsedKeys ys) = UsedKeys $ liftA2 Set.union xs ys
mkUsedKeys :: Set.Set String -> UsedKeys
mkUsedKeys = UsedKeys . Just
allUsedKeys :: UsedKeys
allUsedKeys = UsedKeys Nothing
-- | Class of objects that can be converted from and to 'JSObject'
-- lists-format.
class DictObject a where
toDict :: a -> [(String, J.JSValue)]
fromDictWKeys :: [(String, J.JSValue)] -> WriterT UsedKeys J.Result a
fromDict :: [(String, J.JSValue)] -> J.Result a
fromDict = liftM fst . runWriterT . fromDictWKeys
-- | A default implementation of 'showJSON' using 'toDict'.
showJSONtoDict :: (DictObject a) => a -> J.JSValue
showJSONtoDict = J.makeObj . toDict
-- | A default implementation of 'readJSON' using 'fromDict'.
-- Checks that the input value is a JSON object and
-- converts it using 'fromDict'.
-- Also checks the input contains only the used keys returned by 'fromDict'.
readJSONfromDict :: (DictObject a)
=> J.JSValue -> J.Result a
readJSONfromDict jsv = do
dict <- liftM J.fromJSObject $ J.readJSON jsv
(r, UsedKeys keys) <- runWriterT $ fromDictWKeys dict
-- check that no superfluous dictionary keys are present
case keys of
Just allowedSet | not (Set.null superfluous) ->
fail $ "Superfluous dictionary keys: "
++ show (Set.toAscList superfluous) ++ ", but only "
++ show (Set.toAscList allowedSet) ++ " allowed."
where
superfluous = Set.fromList (map fst dict) Set.\\ allowedSet
_ -> return ()
return r
-- | Class of objects that can be converted from and to @[JSValue]@ with
-- a fixed length and order.
class ArrayObject a where
toJSArray :: a -> [J.JSValue]
fromJSArray :: [J.JSValue] -> J.Result a
-- * General purpose data types for working with JSON
-- | A Maybe newtype that allows for serialization more appropriate to the
-- semantics of Maybe and JSON in our calls. Does not produce needless
-- and confusing dictionaries.
--
-- In particular, `J.JSNull` corresponds to `Nothing`.
-- This also means that this `Maybe a` newtype should not be used with `a`
-- values that themselves can serialize to `null`.
newtype MaybeForJSON a = MaybeForJSON { unMaybeForJSON :: Maybe a }
deriving (Show, Eq, Ord)
instance (J.JSON a) => J.JSON (MaybeForJSON a) where
readJSON J.JSNull = return $ MaybeForJSON Nothing
readJSON x = (MaybeForJSON . Just) `liftM` J.readJSON x
showJSON (MaybeForJSON (Just x)) = J.showJSON x
showJSON (MaybeForJSON Nothing) = J.JSNull
newtype TimeAsDoubleJSON
= TimeAsDoubleJSON { unTimeAsDoubleJSON :: ClockTime }
deriving (Show, Eq, Ord)
instance J.JSON TimeAsDoubleJSON where
readJSON v = do
t <- J.readJSON v :: J.Result Double
return . TimeAsDoubleJSON . uncurry TOD
$ divMod (round $ t * pico) (pico :: Integer)
where
pico :: (Num a) => a
pico = 10^(12 :: Int)
showJSON (TimeAsDoubleJSON (TOD ss ps)) = J.showJSON
(fromIntegral ss + fromIntegral ps / 10^(12 :: Int) :: Double)
-- Text.JSON from the JSON package only has instances for tuples up to size 4.
-- We use these newtypes so that we don't get a breakage once the 'json'
-- package adds instances for larger tuples (or have to resort to CPP).
newtype Tuple5 a b c d e = Tuple5 { unTuple5 :: (a, b, c, d, e) }
instance (J.JSON a, J.JSON b, J.JSON c, J.JSON d, J.JSON e)
=> J.JSON (Tuple5 a b c d e) where
readJSON (J.JSArray [a,b,c,d,e]) =
Tuple5 <$> ((,,,,) <$> J.readJSON a
<*> J.readJSON b
<*> J.readJSON c
<*> J.readJSON d
<*> J.readJSON e)
readJSON _ = fail "Unable to read Tuple5"
showJSON (Tuple5 (a, b, c, d, e)) =
J.JSArray
[ J.showJSON a
, J.showJSON b
, J.showJSON c
, J.showJSON d
, J.showJSON e
]
-- | Look up a value in a JSON object. Accessing @["a", "b", "c"]@ on an
-- object is equivalent as accessing @myobject.a.b.c@ on a JavaScript object.
--
-- An error is returned if the object doesn't have such an accessor or if
-- any value during the nested access is not an object at all.
nestedAccessByKey :: [String] -> J.JSValue -> J.Result J.JSValue
nestedAccessByKey keys json = case keys of
[] -> return json
k:ks -> case json of
J.JSObject obj -> J.valFromObj k obj >>= nestedAccessByKey ks
_ -> J.Error $ "Cannot access non-object with key '" ++ k ++ "'"
-- | Same as `nestedAccessByKey`, but accessing with a dotted string instead
-- (like @nestedAccessByKeyDotted "a.b.c"@).
nestedAccessByKeyDotted :: String -> J.JSValue -> J.Result J.JSValue
nestedAccessByKeyDotted s =
nestedAccessByKey (map T.unpack . T.splitOn (T.pack ".") . T.pack $ s)
-- | Branch decoding on a field in a JSON object.
branchOnField :: String -- ^ fieldname to branch on
-> (J.JSValue -> J.Result a)
-- ^ decoding function if field is present and @true@; field
-- will already be removed in the input
-> (J.JSValue -> J.Result a)
-- ^ decoding function otherwise
-> J.JSValue -> J.Result a
branchOnField k ifTrue ifFalse (J.JSObject jobj) =
let fields = J.fromJSObject jobj
jobj' = J.JSObject . J.toJSObject $ filter ((/=) k . fst) fields
in if lookup k fields == Just (J.JSBool True)
then ifTrue jobj'
else ifFalse jobj'
branchOnField k _ _ _ = J.Error $ "Need an object to branch on key " ++ k
-- | Add a field to a JSON object; to nothing, if the argument is not an object.
addField :: (String, J.JSValue) -> J.JSValue -> J.JSValue
addField (n,v) (J.JSObject obj) = J.JSObject $ JT.set_field obj n v
addField _ jsval = jsval
-- | Maybe obtain a map from a JSON object.
maybeParseMap :: J.JSON a => J.JSValue -> Maybe (Map.Map String a)
maybeParseMap = liftM fromContainer . readContainer <=< asJSObject
|
grnet/snf-ganeti
|
src/Ganeti/JSON.hs
|
Haskell
|
bsd-2-clause
| 20,109
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[DataCon]{@DataCon@: Data Constructors}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module DataCon (
-- * Main data types
DataCon, DataConRep(..),
SrcStrictness(..), SrcUnpackedness(..),
HsSrcBang(..), HsImplBang(..),
StrictnessMark(..),
ConTag,
-- ** Field labels
FieldLbl(..), FieldLabel, FieldLabelString,
-- ** Type construction
mkDataCon, fIRST_TAG,
buildAlgTyCon,
-- ** Type deconstruction
dataConRepType, dataConSig, dataConInstSig, dataConFullSig,
dataConName, dataConIdentity, dataConTag, dataConTyCon,
dataConOrigTyCon, dataConUserType,
dataConUnivTyVars, dataConExTyVars, dataConAllTyVars,
dataConEqSpec, eqSpecPreds, dataConTheta,
dataConStupidTheta,
dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
dataConInstOrigArgTys, dataConRepArgTys,
dataConFieldLabels, dataConFieldType,
dataConSrcBangs,
dataConSourceArity, dataConRepArity, dataConRepRepArity,
dataConIsInfix,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConImplicitTyThings,
dataConRepStrictness, dataConImplBangs, dataConBoxer,
splitDataProductType_maybe,
-- ** Predicates on DataCons
isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon,
isVanillaDataCon, classDataCon, dataConCannotMatch,
isBanged, isMarkedStrict, eqHsBang, isSrcStrict, isSrcUnpacked,
-- ** Promotion related functions
promoteDataCon, promoteDataCon_maybe,
promoteType, promoteKind,
isPromotableType, computeTyConPromotability,
) where
#include "HsVersions.h"
import {-# SOURCE #-} MkId( DataConBoxer )
import Type
import ForeignCall( CType )
import TypeRep( Type(..) ) -- Used in promoteType
import PrelNames( liftedTypeKindTyConKey )
import Coercion
import Kind
import Unify
import TyCon
import FieldLabel
import Class
import Name
import Var
import Outputable
import Unique
import ListSetOps
import Util
import BasicTypes
import FastString
import Module
import VarEnv
import NameSet
import Binary
import qualified Data.Data as Data
import qualified Data.Typeable
import Data.Char
import Data.Word
import Data.List( mapAccumL, find )
{-
Data constructor representation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following Haskell data type declaration
data T = T !Int ![Int]
Using the strictness annotations, GHC will represent this as
data T = T Int# [Int]
That is, the Int has been unboxed. Furthermore, the Haskell source construction
T e1 e2
is translated to
case e1 of { I# x ->
case e2 of { r ->
T x r }}
That is, the first argument is unboxed, and the second is evaluated. Finally,
pattern matching is translated too:
case e of { T a b -> ... }
becomes
case e of { T a' b -> let a = I# a' in ... }
To keep ourselves sane, we name the different versions of the data constructor
differently, as follows.
Note [Data Constructor Naming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Each data constructor C has two, and possibly up to four, Names associated with it:
OccName Name space Name of Notes
---------------------------------------------------------------------------
The "data con itself" C DataName DataCon In dom( GlobalRdrEnv )
The "worker data con" C VarName Id The worker
The "wrapper data con" $WC VarName Id The wrapper
The "newtype coercion" :CoT TcClsName TyCon
EVERY data constructor (incl for newtypes) has the former two (the
data con itself, and its worker. But only some data constructors have a
wrapper (see Note [The need for a wrapper]).
Each of these three has a distinct Unique. The "data con itself" name
appears in the output of the renamer, and names the Haskell-source
data constructor. The type checker translates it into either the wrapper Id
(if it exists) or worker Id (otherwise).
The data con has one or two Ids associated with it:
The "worker Id", is the actual data constructor.
* Every data constructor (newtype or data type) has a worker
* The worker is very like a primop, in that it has no binding.
* For a *data* type, the worker *is* the data constructor;
it has no unfolding
* For a *newtype*, the worker has a compulsory unfolding which
does a cast, e.g.
newtype T = MkT Int
The worker for MkT has unfolding
\\(x:Int). x `cast` sym CoT
Here CoT is the type constructor, witnessing the FC axiom
axiom CoT : T = Int
The "wrapper Id", \$WC, goes as follows
* Its type is exactly what it looks like in the source program.
* It is an ordinary function, and it gets a top-level binding
like any other function.
* The wrapper Id isn't generated for a data type if there is
nothing for the wrapper to do. That is, if its defn would be
\$wC = C
Note [The need for a wrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why might the wrapper have anything to do? Two reasons:
* Unboxing strict fields (with -funbox-strict-fields)
data T = MkT !(Int,Int)
\$wMkT :: (Int,Int) -> T
\$wMkT (x,y) = MkT x y
Notice that the worker has two fields where the wapper has
just one. That is, the worker has type
MkT :: Int -> Int -> T
* Equality constraints for GADTs
data T a where { MkT :: a -> T [a] }
The worker gets a type with explicit equality
constraints, thus:
MkT :: forall a b. (a=[b]) => b -> T a
The wrapper has the programmer-specified type:
\$wMkT :: a -> T [a]
\$wMkT a x = MkT [a] a [a] x
The third argument is a coercion
[a] :: [a]~[a]
INVARIANT: the dictionary constructor for a class
never has a wrapper.
A note about the stupid context
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Data types can have a context:
data (Eq a, Ord b) => T a b = T1 a b | T2 a
and that makes the constructors have a context too
(notice that T2's context is "thinned"):
T1 :: (Eq a, Ord b) => a -> b -> T a b
T2 :: (Eq a) => a -> T a b
Furthermore, this context pops up when pattern matching
(though GHC hasn't implemented this, but it is in H98, and
I've fixed GHC so that it now does):
f (T2 x) = x
gets inferred type
f :: Eq a => T a b -> a
I say the context is "stupid" because the dictionaries passed
are immediately discarded -- they do nothing and have no benefit.
It's a flaw in the language.
Up to now [March 2002] I have put this stupid context into the
type of the "wrapper" constructors functions, T1 and T2, but
that turned out to be jolly inconvenient for generics, and
record update, and other functions that build values of type T
(because they don't have suitable dictionaries available).
So now I've taken the stupid context out. I simply deal with
it separately in the type checker on occurrences of a
constructor, either in an expression or in a pattern.
[May 2003: actually I think this decision could evasily be
reversed now, and probably should be. Generics could be
disabled for types with a stupid context; record updates now
(H98) needs the context too; etc. It's an unforced change, so
I'm leaving it for now --- but it does seem odd that the
wrapper doesn't include the stupid context.]
[July 04] With the advent of generalised data types, it's less obvious
what the "stupid context" is. Consider
C :: forall a. Ord a => a -> a -> T (Foo a)
Does the C constructor in Core contain the Ord dictionary? Yes, it must:
f :: T b -> Ordering
f = /\b. \x:T b.
case x of
C a (d:Ord a) (p:a) (q:a) -> compare d p q
Note that (Foo a) might not be an instance of Ord.
************************************************************************
* *
\subsection{Data constructors}
* *
************************************************************************
-}
-- | A data constructor
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
data DataCon
= MkData {
dcName :: Name, -- This is the name of the *source data con*
-- (see "Note [Data Constructor Naming]" above)
dcUnique :: Unique, -- Cached from Name
dcTag :: ConTag, -- ^ Tag, used for ordering 'DataCon's
-- Running example:
--
-- *** As declared by the user
-- data T a where
-- MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)
-- *** As represented internally
-- data T a where
-- MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
--
-- The next six fields express the type of the constructor, in pieces
-- e.g.
--
-- dcUnivTyVars = [a]
-- dcExTyVars = [x,y]
-- dcEqSpec = [a~(x,y)]
-- dcOtherTheta = [x~y, Ord x]
-- dcOrigArgTys = [x,y]
-- dcRepTyCon = T
dcVanilla :: Bool, -- True <=> This is a vanilla Haskell 98 data constructor
-- Its type is of form
-- forall a1..an . t1 -> ... tm -> T a1..an
-- No existentials, no coercions, nothing.
-- That is: dcExTyVars = dcEqSpec = dcOtherTheta = []
-- NB 1: newtypes always have a vanilla data con
-- NB 2: a vanilla constructor can still be declared in GADT-style
-- syntax, provided its type looks like the above.
-- The declaration format is held in the TyCon (algTcGadtSyntax)
dcUnivTyVars :: [TyVar], -- Universally-quantified type vars [a,b,c]
-- INVARIANT: length matches arity of the dcRepTyCon
--- result type of (rep) data con is exactly (T a b c)
dcExTyVars :: [TyVar], -- Existentially-quantified type vars
-- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
-- FOR THE PARENT TyCon. With GADTs the data con might not even have
-- the same number of type variables.
-- [This is a change (Oct05): previously, vanilla datacons guaranteed to
-- have the same type variables as their parent TyCon, but that seems ugly.]
-- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
-- Reason: less confusing, and easier to generate IfaceSyn
dcEqSpec :: [(TyVar,Type)], -- Equalities derived from the result type,
-- _as written by the programmer_
-- This field allows us to move conveniently between the two ways
-- of representing a GADT constructor's type:
-- MkT :: forall a b. (a ~ [b]) => b -> T a
-- MkT :: forall b. b -> T [b]
-- Each equality is of the form (a ~ ty), where 'a' is one of
-- the universally quantified type variables
-- The next two fields give the type context of the data constructor
-- (aside from the GADT constraints,
-- which are given by the dcExpSpec)
-- In GADT form, this is *exactly* what the programmer writes, even if
-- the context constrains only universally quantified variables
-- MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
dcOtherTheta :: ThetaType, -- The other constraints in the data con's type
-- other than those in the dcEqSpec
dcStupidTheta :: ThetaType, -- The context of the data type declaration
-- data Eq a => T a = ...
-- or, rather, a "thinned" version thereof
-- "Thinned", because the Report says
-- to eliminate any constraints that don't mention
-- tyvars free in the arg types for this constructor
--
-- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
-- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
--
-- "Stupid", because the dictionaries aren't used for anything.
-- Indeed, [as of March 02] they are no longer in the type of
-- the wrapper Id, because that makes it harder to use the wrap-id
-- to rebuild values after record selection or in generics.
dcOrigArgTys :: [Type], -- Original argument types
-- (before unboxing and flattening of strict fields)
dcOrigResTy :: Type, -- Original result type, as seen by the user
-- NB: for a data instance, the original user result type may
-- differ from the DataCon's representation TyCon. Example
-- data instance T [a] where MkT :: a -> T [a]
-- The OrigResTy is T [a], but the dcRepTyCon might be :T123
-- Now the strictness annotations and field labels of the constructor
dcSrcBangs :: [HsSrcBang],
-- See Note [Bangs on data constructor arguments]
--
-- The [HsSrcBang] as written by the programmer.
--
-- Matches 1-1 with dcOrigArgTys
-- Hence length = dataConSourceArity dataCon
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the dcOrigArgTys;
-- length = 0 (if not a record) or dataConSourceArity.
-- The curried worker function that corresponds to the constructor:
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
dcWorkId :: Id,
-- Constructor representation
dcRep :: DataConRep,
-- Cached
dcRepArity :: Arity, -- == length dataConRepArgTys
dcSourceArity :: Arity, -- == length dcOrigArgTys
-- Result type of constructor is T t1..tn
dcRepTyCon :: TyCon, -- Result tycon, T
dcRepType :: Type, -- Type of the constructor
-- forall a x y. (a~(x,y), x~y, Ord x) =>
-- x -> y -> T a
-- (this is *not* of the constructor wrapper Id:
-- see Note [Data con representation] below)
-- Notice that the existential type parameters come *second*.
-- Reason: in a case expression we may find:
-- case (e :: T t) of
-- MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
-- It's convenient to apply the rep-type of MkT to 't', to get
-- forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
-- and use that to check the pattern. Mind you, this is really only
-- used in CoreLint.
dcInfix :: Bool, -- True <=> declared infix
-- Used for Template Haskell and 'deriving' only
-- The actual fixity is stored elsewhere
dcPromoted :: Promoted TyCon -- The promoted TyCon if this DataCon is promotable
-- See Note [Promoted data constructors] in TyCon
}
deriving Data.Typeable.Typeable
data DataConRep
= NoDataConRep -- No wrapper
| DCR { dcr_wrap_id :: Id -- Takes src args, unboxes/flattens,
-- and constructs the representation
, dcr_boxer :: DataConBoxer
, dcr_arg_tys :: [Type] -- Final, representation argument types,
-- after unboxing and flattening,
-- and *including* all evidence args
, dcr_stricts :: [StrictnessMark] -- 1-1 with dcr_arg_tys
-- See also Note [Data-con worker strictness] in MkId.hs
, dcr_bangs :: [HsImplBang] -- The actual decisions made (including failures)
-- about the original arguments; 1-1 with orig_arg_tys
-- See Note [Bangs on data constructor arguments]
}
-- Algebraic data types always have a worker, and
-- may or may not have a wrapper, depending on whether
-- the wrapper does anything.
--
-- Data types have a worker with no unfolding
-- Newtypes just have a worker, which has a compulsory unfolding (just a cast)
-- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
-- The wrapper (if it exists) takes dcOrigArgTys as its arguments
-- The worker takes dataConRepArgTys as its arguments
-- If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys
-- The 'NoDataConRep' case is important
-- Not only is this efficient,
-- but it also ensures that the wrapper is replaced
-- by the worker (because it *is* the worker)
-- even when there are no args. E.g. in
-- f (:) x
-- the (:) *is* the worker.
-- This is really important in rule matching,
-- (We could match on the wrappers,
-- but that makes it less likely that rules will match
-- when we bring bits of unfoldings together.)
-------------------------
-- | Bangs on data constructor arguments as the user wrote them in the
-- source code.
--
-- (HsSrcBang _ SrcUnpack SrcLazy) and
-- (HsSrcBang _ SrcUnpack NoSrcStrict) (without StrictData) makes no sense, we
-- emit a warning (in checkValidDataCon) and treat it like
-- (HsSrcBang _ NoSrcUnpack SrcLazy)
data HsSrcBang =
HsSrcBang (Maybe SourceText) -- Note [Pragma source text] in BasicTypes
SrcUnpackedness
SrcStrictness
deriving (Data.Data, Data.Typeable)
-- | Bangs of data constructor arguments as generated by the compiler
-- after consulting HsSrcBang, flags, etc.
data HsImplBang
= HsLazy -- ^ Lazy field
| HsStrict -- ^ Strict but not unpacked field
| HsUnpack (Maybe Coercion)
-- ^ Strict and unpacked field
-- co :: arg-ty ~ product-ty HsBang
deriving (Data.Data, Data.Typeable)
-- | What strictness annotation the user wrote
data SrcStrictness = SrcLazy -- ^ Lazy, ie '~'
| SrcStrict -- ^ Strict, ie '!'
| NoSrcStrict -- ^ no strictness annotation
deriving (Eq, Data.Data, Data.Typeable)
-- | What unpackedness the user requested
data SrcUnpackedness = SrcUnpack -- ^ {-# UNPACK #-} specified
| SrcNoUnpack -- ^ {-# NOUNPACK #-} specified
| NoSrcUnpack -- ^ no unpack pragma
deriving (Eq, Data.Data, Data.Typeable)
-------------------------
-- StrictnessMark is internal only, used to indicate strictness
-- of the DataCon *worker* fields
data StrictnessMark = MarkedStrict | NotMarkedStrict
{- Note [Bangs on data constructor arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = MkT !Int {-# UNPACK #-} !Int Bool
When compiling the module, GHC will decide how to represent
MkT, depending on the optimisation level, and settings of
flags like -funbox-small-strict-fields.
Terminology:
* HsSrcBang: What the user wrote
Constructors: HsSrcBang
* HsImplBang: What GHC decided
Constructors: HsLazy, HsStrict, HsUnpack
* If T was defined in this module, MkT's dcSrcBangs field
records the [HsSrcBang] of what the user wrote; in the example
[ HsSrcBang _ NoSrcUnpack SrcStrict
, HsSrcBang _ SrcUnpack SrcStrict
, HsSrcBang _ NoSrcUnpack NoSrcStrictness]
* However, if T was defined in an imported module, the importing module
must follow the decisions made in the original module, regardless of
the flag settings in the importing module.
Also see Note [Bangs on imported data constructors] in MkId
* The dcr_bangs field of the dcRep field records the [HsImplBang]
If T was defined in this module, Without -O the dcr_bangs might be
[HsStrict, HsStrict, HsLazy]
With -O it might be
[HsStrict, HsUnpack _, HsLazy]
With -funbox-small-strict-fields it might be
[HsUnpack, HsUnpack _, HsLazy]
With -XStrictData it might be
[HsStrict, HsUnpack _, HsStrict]
Note [Data con representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The dcRepType field contains the type of the representation of a contructor
This may differ from the type of the constructor *Id* (built
by MkId.mkDataConId) for two reasons:
a) the constructor Id may be overloaded, but the dictionary isn't stored
e.g. data Eq a => T a = MkT a a
b) the constructor may store an unboxed version of a strict field.
Here's an example illustrating both:
data Ord a => T a = MkT Int! a
Here
T :: Ord a => Int -> a -> T a
but the rep type is
Trep :: Int# -> a -> T a
Actually, the unboxed part isn't implemented yet!
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq DataCon where
a == b = getUnique a == getUnique b
a /= b = getUnique a /= getUnique b
instance Ord DataCon where
a <= b = getUnique a <= getUnique b
a < b = getUnique a < getUnique b
a >= b = getUnique a >= getUnique b
a > b = getUnique a > getUnique b
compare a b = getUnique a `compare` getUnique b
instance Uniquable DataCon where
getUnique = dcUnique
instance NamedThing DataCon where
getName = dcName
instance Outputable DataCon where
ppr con = ppr (dataConName con)
instance OutputableBndr DataCon where
pprInfixOcc con = pprInfixName (dataConName con)
pprPrefixOcc con = pprPrefixName (dataConName con)
instance Data.Data DataCon where
-- don't traverse?
toConstr _ = abstractConstr "DataCon"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "DataCon"
instance Outputable HsSrcBang where
ppr (HsSrcBang _ prag mark) = ppr prag <+> ppr mark
instance Outputable HsImplBang where
ppr HsLazy = ptext (sLit "Lazy")
ppr (HsUnpack Nothing) = ptext (sLit "Unpacked")
ppr (HsUnpack (Just co)) = ptext (sLit "Unpacked") <> parens (ppr co)
ppr HsStrict = ptext (sLit "StrictNotUnpacked")
instance Outputable SrcStrictness where
ppr SrcLazy = char '~'
ppr SrcStrict = char '!'
ppr NoSrcStrict = empty
instance Outputable SrcUnpackedness where
ppr SrcUnpack = ptext (sLit "{-# UNPACK #-}")
ppr SrcNoUnpack = ptext (sLit "{-# NOUNPACK #-}")
ppr NoSrcUnpack = empty
instance Outputable StrictnessMark where
ppr MarkedStrict = ptext (sLit "!")
ppr NotMarkedStrict = empty
instance Binary SrcStrictness where
put_ bh SrcLazy = putByte bh 0
put_ bh SrcStrict = putByte bh 1
put_ bh NoSrcStrict = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcLazy
1 -> return SrcLazy
_ -> return NoSrcStrict
instance Binary SrcUnpackedness where
put_ bh SrcNoUnpack = putByte bh 0
put_ bh SrcUnpack = putByte bh 1
put_ bh NoSrcUnpack = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcNoUnpack
1 -> return SrcUnpack
_ -> return NoSrcUnpack
-- | Compare strictness annotations
eqHsBang :: HsImplBang -> HsImplBang -> Bool
eqHsBang HsLazy HsLazy = True
eqHsBang HsStrict HsStrict = True
eqHsBang (HsUnpack Nothing) (HsUnpack Nothing) = True
eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2))
= eqType (coercionType c1) (coercionType c2)
eqHsBang _ _ = False
isBanged :: HsImplBang -> Bool
isBanged (HsUnpack {}) = True
isBanged (HsStrict {}) = True
isBanged HsLazy = False
isSrcStrict :: SrcStrictness -> Bool
isSrcStrict SrcStrict = True
isSrcStrict _ = False
isSrcUnpacked :: SrcUnpackedness -> Bool
isSrcUnpacked SrcUnpack = True
isSrcUnpacked _ = False
isMarkedStrict :: StrictnessMark -> Bool
isMarkedStrict NotMarkedStrict = False
isMarkedStrict _ = True -- All others are strict
{-
************************************************************************
* *
\subsection{Construction}
* *
************************************************************************
-}
-- | Build a new data constructor
mkDataCon :: Name
-> Bool -- ^ Is the constructor declared infix?
-> Promoted TyConRepName -- ^ Whether promoted, and if so the TyConRepName
-- for the promoted TyCon
-> [HsSrcBang] -- ^ Strictness/unpack annotations, from user
-> [FieldLabel] -- ^ Field labels for the constructor,
-- if it is a record, otherwise empty
-> [TyVar] -- ^ Universally quantified type variables
-> [TyVar] -- ^ Existentially quantified type variables
-> [(TyVar,Type)] -- ^ GADT equalities
-> ThetaType -- ^ Theta-type occuring before the arguments proper
-> [Type] -- ^ Original argument types
-> Type -- ^ Original result type
-> TyCon -- ^ Representation type constructor
-> ThetaType -- ^ The "stupid theta", context of the data
-- declaration e.g. @data Eq a => T a ...@
-> Id -- ^ Worker Id
-> DataConRep -- ^ Representation
-> DataCon
-- Can get the tag from the TyCon
mkDataCon name declared_infix prom_info
arg_stricts -- Must match orig_arg_tys 1-1
fields
univ_tvs ex_tvs
eq_spec theta
orig_arg_tys orig_res_ty rep_tycon
stupid_theta work_id rep
-- Warning: mkDataCon is not a good place to check invariants.
-- If the programmer writes the wrong result type in the decl, thus:
-- data T a where { MkT :: S }
-- then it's possible that the univ_tvs may hit an assertion failure
-- if you pull on univ_tvs. This case is checked by checkValidDataCon,
-- so the error is detected properly... it's just that asaertions here
-- are a little dodgy.
= con
where
is_vanilla = null ex_tvs && null eq_spec && null theta
con = MkData {dcName = name, dcUnique = nameUnique name,
dcVanilla = is_vanilla, dcInfix = declared_infix,
dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec,
dcOtherTheta = theta,
dcStupidTheta = stupid_theta,
dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
dcRepTyCon = rep_tycon,
dcSrcBangs = arg_stricts,
dcFields = fields, dcTag = tag, dcRepType = rep_ty,
dcWorkId = work_id,
dcRep = rep,
dcSourceArity = length orig_arg_tys,
dcRepArity = length rep_arg_tys,
dcPromoted = mb_promoted }
-- The 'arg_stricts' passed to mkDataCon are simply those for the
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
rep_arg_tys = dataConRepArgTys con
rep_ty = mkForAllTys univ_tvs $ mkForAllTys ex_tvs $
mkFunTys rep_arg_tys $
mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
mb_promoted -- See Note [Promoted data constructors] in TyCon
= case prom_info of
NotPromoted -> NotPromoted
Promoted rep_nm -> Promoted (mkPromotedDataCon con name rep_nm prom_kind prom_roles)
prom_kind = promoteType (dataConUserType con)
prom_roles = map (const Nominal) (univ_tvs ++ ex_tvs) ++
map (const Representational) orig_arg_tys
eqSpecPreds :: [(TyVar,Type)] -> ThetaType
eqSpecPreds spec = [ mkEqPred (mkTyVarTy tv) ty | (tv,ty) <- spec ]
-- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
dataConName :: DataCon -> Name
dataConName = dcName
-- | The tag used for ordering 'DataCon's
dataConTag :: DataCon -> ConTag
dataConTag = dcTag
-- | The type constructor that we are building via this data constructor
dataConTyCon :: DataCon -> TyCon
dataConTyCon = dcRepTyCon
-- | The original type constructor used in the definition of this data
-- constructor. In case of a data family instance, that will be the family
-- type constructor.
dataConOrigTyCon :: DataCon -> TyCon
dataConOrigTyCon dc
| Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
| otherwise = dcRepTyCon dc
-- | The representation type of the data constructor, i.e. the sort
-- type that will represent values of this type at runtime
dataConRepType :: DataCon -> Type
dataConRepType = dcRepType
-- | Should the 'DataCon' be presented infix?
dataConIsInfix :: DataCon -> Bool
dataConIsInfix = dcInfix
-- | The universally-quantified type variables of the constructor
dataConUnivTyVars :: DataCon -> [TyVar]
dataConUnivTyVars = dcUnivTyVars
-- | The existentially-quantified type variables of the constructor
dataConExTyVars :: DataCon -> [TyVar]
dataConExTyVars = dcExTyVars
-- | Both the universal and existentiatial type variables of the constructor
dataConAllTyVars :: DataCon -> [TyVar]
dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
= univ_tvs ++ ex_tvs
-- | Equalities derived from the result type of the data constructor, as written
-- by the programmer in any GADT declaration
dataConEqSpec :: DataCon -> [(TyVar,Type)]
dataConEqSpec = dcEqSpec
-- | The *full* constraints on the constructor type
dataConTheta :: DataCon -> ThetaType
dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= eqSpecPreds eq_spec ++ theta
-- | Get the Id of the 'DataCon' worker: a function that is the "actual"
-- constructor and has no top level binding in the program. The type may
-- be different from the obvious one written in the source program. Panics
-- if there is no such 'Id' for this 'DataCon'
dataConWorkId :: DataCon -> Id
dataConWorkId dc = dcWorkId dc
-- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
-- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'.
-- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor
-- and also for a newtype (whose constructor is inlined compulsorily)
dataConWrapId_maybe :: DataCon -> Maybe Id
dataConWrapId_maybe dc = case dcRep dc of
NoDataConRep -> Nothing
DCR { dcr_wrap_id = wrap_id } -> Just wrap_id
-- | Returns an Id which looks like the Haskell-source constructor by using
-- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
-- the worker (see 'dataConWorkId')
dataConWrapId :: DataCon -> Id
dataConWrapId dc = case dcRep dc of
NoDataConRep-> dcWorkId dc -- worker=wrapper
DCR { dcr_wrap_id = wrap_id } -> wrap_id
-- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
-- the union of the 'dataConWorkId' and the 'dataConWrapId'
dataConImplicitTyThings :: DataCon -> [TyThing]
dataConImplicitTyThings (MkData { dcWorkId = work, dcRep = rep })
= [AnId work] ++ wrap_ids
where
wrap_ids = case rep of
NoDataConRep -> []
DCR { dcr_wrap_id = wrap } -> [AnId wrap]
-- | The labels for the fields of this particular 'DataCon'
dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields
-- | Extract the type for any given labelled field of the 'DataCon'
dataConFieldType :: DataCon -> FieldLabelString -> Type
dataConFieldType con label
= case find ((== label) . flLabel . fst) (dcFields con `zip` dcOrigArgTys con) of
Just (_, ty) -> ty
Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
-- | Strictness/unpack annotations, from user; or, for imported
-- DataCons, from the interface file
-- The list is in one-to-one correspondence with the arity of the 'DataCon'
dataConSrcBangs :: DataCon -> [HsSrcBang]
dataConSrcBangs = dcSrcBangs
-- | Source-level arity of the data constructor
dataConSourceArity :: DataCon -> Arity
dataConSourceArity (MkData { dcSourceArity = arity }) = arity
-- | Gives the number of actual fields in the /representation/ of the
-- data constructor. This may be more than appear in the source code;
-- the extra ones are the existentially quantified dictionaries
dataConRepArity :: DataCon -> Arity
dataConRepArity (MkData { dcRepArity = arity }) = arity
-- | The number of fields in the /representation/ of the constructor
-- AFTER taking into account the unpacking of any unboxed tuple fields
dataConRepRepArity :: DataCon -> RepArity
dataConRepRepArity dc = typeRepArity (dataConRepArity dc) (dataConRepType dc)
-- | Return whether there are any argument types for this 'DataCon's original source type
isNullarySrcDataCon :: DataCon -> Bool
isNullarySrcDataCon dc = null (dcOrigArgTys dc)
-- | Return whether there are any argument types for this 'DataCon's runtime representation type
isNullaryRepDataCon :: DataCon -> Bool
isNullaryRepDataCon dc = dataConRepArity dc == 0
dataConRepStrictness :: DataCon -> [StrictnessMark]
-- ^ Give the demands on the arguments of a
-- Core constructor application (Con dc args)
dataConRepStrictness dc = case dcRep dc of
NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc]
DCR { dcr_stricts = strs } -> strs
dataConImplBangs :: DataCon -> [HsImplBang]
-- The implementation decisions about the strictness/unpack of each
-- source program argument to the data constructor
dataConImplBangs dc
= case dcRep dc of
NoDataConRep -> replicate (dcSourceArity dc) HsLazy
DCR { dcr_bangs = bangs } -> bangs
dataConBoxer :: DataCon -> Maybe DataConBoxer
dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer
dataConBoxer _ = Nothing
-- | The \"signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConAllTyVars',
--
-- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
-- parameter - whatever)
--
-- 3) The type arguments to the constructor
--
-- 4) The /original/ result type of the 'DataCon'
dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
dataConSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec, dcOtherTheta = theta,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ theta, arg_tys, res_ty)
dataConInstSig
:: DataCon
-> [Type] -- Instantiate the *universal* tyvars with these types
-> ([TyVar], ThetaType, [Type]) -- Return instantiated existentials
-- theta and arg tys
-- ^ Instantantiate the universal tyvars of a data con,
-- returning the instantiated existentials, constraints, and args
dataConInstSig (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs
, dcEqSpec = eq_spec, dcOtherTheta = theta
, dcOrigArgTys = arg_tys })
univ_tys
= (ex_tvs'
, substTheta subst (eqSpecPreds eq_spec ++ theta)
, substTys subst arg_tys)
where
univ_subst = zipTopTvSubst univ_tvs univ_tys
(subst, ex_tvs') = mapAccumL Type.substTyVarBndr univ_subst ex_tvs
-- | The \"full signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConUnivTyVars'
--
-- 2) The result of 'dataConExTyVars'
--
-- 3) The result of 'dataConEqSpec'
--
-- 4) The result of 'dataConDictTheta'
--
-- 5) The original argument types to the 'DataCon' (i.e. before
-- any change of the representation of the type)
--
-- 6) The original result type of the 'DataCon'
dataConFullSig :: DataCon
-> ([TyVar], [TyVar], [(TyVar,Type)], ThetaType, [Type], Type)
dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec, dcOtherTheta = theta,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty)
dataConOrigResTy :: DataCon -> Type
dataConOrigResTy dc = dcOrigResTy dc
-- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
--
-- > data Eq a => T a = ...
dataConStupidTheta :: DataCon -> ThetaType
dataConStupidTheta dc = dcStupidTheta dc
dataConUserType :: DataCon -> Type
-- ^ The user-declared type of the data constructor
-- in the nice-to-read form:
--
-- > T :: forall a b. a -> b -> T [a]
--
-- rather than:
--
-- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
--
-- NB: If the constructor is part of a data instance, the result type
-- mentions the family tycon, not the internal one.
dataConUserType (MkData { dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
dcOtherTheta = theta, dcOrigArgTys = arg_tys,
dcOrigResTy = res_ty })
= mkForAllTys ((univ_tvs `minusList` map fst eq_spec) ++ ex_tvs) $
mkFunTys theta $
mkFunTys arg_tys $
res_ty
-- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
-- NB: these INCLUDE any dictionary args
-- but EXCLUDE the data-declaration context, which is discarded
-- It's all post-flattening etc; this is a representation type
dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
-- However, it can have a dcTheta (notably it can be a
-- class dictionary, with superclasses)
-> [Type] -- ^ Instantiated at these types
-> [Type]
dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length univ_tvs == length inst_tys
, ptext (sLit "dataConInstArgTys") <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
ASSERT2( null ex_tvs, ppr dc )
map (substTyWith univ_tvs inst_tys) (dataConRepArgTys dc)
-- | Returns just the instantiated /value/ argument types of a 'DataCon',
-- (excluding dictionary args)
dataConInstOrigArgTys
:: DataCon -- Works for any DataCon
-> [Type] -- Includes existential tyvar args, but NOT
-- equality constraints or dicts
-> [Type]
-- For vanilla datacons, it's all quite straightforward
-- But for the call in MatchCon, we really do want just the value args
dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length tyvars == length inst_tys
, ptext (sLit "dataConInstOrigArgTys") <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
map (substTyWith tyvars inst_tys) arg_tys
where
tyvars = univ_tvs ++ ex_tvs
-- | Returns the argument types of the wrapper, excluding all dictionary arguments
-- and without substituting for any type variables
dataConOrigArgTys :: DataCon -> [Type]
dataConOrigArgTys dc = dcOrigArgTys dc
-- | Returns the arg types of the worker, including *all* evidence, after any
-- flattening has been done and without substituting for any type variables
dataConRepArgTys :: DataCon -> [Type]
dataConRepArgTys (MkData { dcRep = rep
, dcEqSpec = eq_spec
, dcOtherTheta = theta
, dcOrigArgTys = orig_arg_tys })
= case rep of
NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys
DCR { dcr_arg_tys = arg_tys } -> arg_tys
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
dataConIdentity :: DataCon -> [Word8]
-- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
dataConIdentity dc = bytesFS (unitIdFS (moduleUnitId mod)) ++
fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
where name = dataConName dc
mod = ASSERT( isExternalName name ) nameModule name
isTupleDataCon :: DataCon -> Bool
isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
isUnboxedTupleCon :: DataCon -> Bool
isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
-- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
isVanillaDataCon :: DataCon -> Bool
isVanillaDataCon dc = dcVanilla dc
classDataCon :: Class -> DataCon
classDataCon clas = case tyConDataCons (classTyCon clas) of
(dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
[] -> panic "classDataCon"
dataConCannotMatch :: [Type] -> DataCon -> Bool
-- Returns True iff the data con *definitely cannot* match a
-- scrutinee of type (T tys)
-- where T is the dcRepTyCon for the data con
-- NB: look at *all* equality constraints, not only those
-- in dataConEqSpec; see Trac #5168
dataConCannotMatch tys con
| null inst_theta = False -- Common
| all isTyVarTy tys = False -- Also common
| otherwise = typesCantMatch (concatMap predEqs inst_theta)
where
(_, inst_theta, _) = dataConInstSig con tys
-- TODO: could gather equalities from superclasses too
predEqs pred = case classifyPredType pred of
EqPred NomEq ty1 ty2 -> [(ty1, ty2)]
_ -> []
{-
************************************************************************
* *
Promotion
These functions are here becuase
- isPromotableTyCon calls dataConFullSig
- mkDataCon calls promoteType
- It's nice to keep the promotion stuff together
* *
************************************************************************
Note [The overall promotion story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the overall plan.
* Compared to a TyCon T, the promoted 'T has
same Name (and hence Unique)
same TyConRepName
In future the two will collapse into one anyhow.
* Compared to a DataCon K, the promoted 'K (a type constructor) has
same Name (and hence Unique)
But it has a fresh TyConRepName; after all, the DataCon doesn't have
a TyConRepName at all. (See Note [Grand plan for Typeable] in TcTypeable
for TyConRepName.)
Why does 'K have the same unique as K? It's acceptable because we don't
mix types and terms, so we won't get them confused. And it's helpful mainly
so that we know when to print 'K as a qualified name in error message. The
PrintUnqualified stuff depends on whether K is lexically in scope.. but 'K
never is!
* It follows that the tick-mark (eg 'K) is not part of the Occ name of
either promoted data constructors or type constructors. Instead,
pretty-printing: the pretty-printer prints a tick in front of
- promoted DataCons (always)
- promoted TyCons (with -dppr-debug)
See TyCon.pprPromotionQuote
* For a promoted data constructor K, the pipeline goes like this:
User writes (in a type): K or 'K
Parser produces OccName: K{tc} or K{d}, respectively
Renamer makes Name: M.K{d}_r62 (i.e. same unique as DataCon K)
and K{tc} has been turned into K{d}
provided it was unambiguous
Typechecker makes TyCon: PromotedDataCon MK{d}_r62
Note [Checking whether a group is promotable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We only want to promote a TyCon if all its data constructors
are promotable; it'd be very odd to promote some but not others.
But the data constructors may mention this or other TyCons.
So we treat the recursive uses as all OK (ie promotable) and
do one pass to check that each TyCon is promotable.
Currently type synonyms are not promotable, though that
could change.
-}
promoteDataCon :: DataCon -> TyCon
promoteDataCon (MkData { dcPromoted = Promoted tc }) = tc
promoteDataCon dc = pprPanic "promoteDataCon" (ppr dc)
promoteDataCon_maybe :: DataCon -> Promoted TyCon
promoteDataCon_maybe (MkData { dcPromoted = mb_tc }) = mb_tc
computeTyConPromotability :: NameSet -> TyCon -> Bool
computeTyConPromotability rec_tycons tc
= isAlgTyCon tc -- Only algebraic; not even synonyms
-- (we could reconsider the latter)
&& ok_kind (tyConKind tc)
&& case algTyConRhs tc of
DataTyCon { data_cons = cs } -> all ok_con cs
TupleTyCon { data_con = c } -> ok_con c
NewTyCon { data_con = c } -> ok_con c
AbstractTyCon {} -> False
where
ok_kind kind = all isLiftedTypeKind args && isLiftedTypeKind res
where -- Checks for * -> ... -> * -> *
(args, res) = splitKindFunTys kind
-- See Note [Promoted data constructors] in TyCon
ok_con con = all (isLiftedTypeKind . tyVarKind) ex_tvs
&& null eq_spec -- No constraints
&& null theta
&& all (isPromotableType rec_tycons) orig_arg_tys
where
(_, ex_tvs, eq_spec, theta, orig_arg_tys, _) = dataConFullSig con
isPromotableType :: NameSet -> Type -> Bool
-- Must line up with promoteType
-- But the function lives here because we must treat the
-- *recursive* tycons as promotable
isPromotableType rec_tcs con_arg_ty
= go con_arg_ty
where
go (TyConApp tc tys) = tys `lengthIs` tyConArity tc
&& (tyConName tc `elemNameSet` rec_tcs
|| isPromotableTyCon tc)
&& all go tys
go (FunTy arg res) = go arg && go res
go (TyVarTy {}) = True
go _ = False
{-
Note [Promoting a Type to a Kind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppsoe we have a data constructor D
D :: forall (a:*). Maybe a -> T a
We promote this to be a type constructor 'D:
'D :: forall (k:BOX). 'Maybe k -> 'T k
The transformation from type to kind is done by promoteType
* Convert forall (a:*) to forall (k:BOX), and substitute
* Ensure all foralls are at the top (no higher rank stuff)
* Ensure that all type constructors mentioned (Maybe and T
in the example) are promotable; that is, they have kind
* -> ... -> * -> *
-}
-- | Promotes a type to a kind.
-- Assumes the argument satisfies 'isPromotableType'
promoteType :: Type -> Kind
promoteType ty
= mkForAllTys kvs (go rho)
where
(tvs, rho) = splitForAllTys ty
kvs = [ mkKindVar (tyVarName tv) superKind | tv <- tvs ]
env = zipVarEnv tvs kvs
go (TyConApp tc tys) | Promoted prom_tc <- promotableTyCon_maybe tc
= mkTyConApp prom_tc (map go tys)
go (FunTy arg res) = mkArrowKind (go arg) (go res)
go (TyVarTy tv) | Just kv <- lookupVarEnv env tv
= TyVarTy kv
go _ = panic "promoteType" -- Argument did not satisfy isPromotableType
promoteKind :: Kind -> SuperKind
-- Promote the kind of a type constructor
-- from (* -> * -> *) to (BOX -> BOX -> BOX)
promoteKind (TyConApp tc [])
| tc `hasKey` liftedTypeKindTyConKey = superKind
promoteKind (FunTy arg res) = FunTy (promoteKind arg) (promoteKind res)
promoteKind k = pprPanic "promoteKind" (ppr k)
{-
************************************************************************
* *
\subsection{Splitting products}
* *
************************************************************************
-}
-- | Extract the type constructor, type argument, data constructor and it's
-- /representation/ argument types from a type if it is a product type.
--
-- Precisely, we return @Just@ for any type that is all of:
--
-- * Concrete (i.e. constructors visible)
--
-- * Single-constructor
--
-- * Not existentially quantified
--
-- Whether the type is a @data@ type or a @newtype@
splitDataProductType_maybe
:: Type -- ^ A product type, perhaps
-> Maybe (TyCon, -- The type constructor
[Type], -- Type args of the tycon
DataCon, -- The data constructor
[Type]) -- Its /representation/ arg types
-- Rejecting existentials is conservative. Maybe some things
-- could be made to work with them, but I'm not going to sweat
-- it through till someone finds it's important.
splitDataProductType_maybe ty
| Just (tycon, ty_args) <- splitTyConApp_maybe ty
, Just con <- isDataProductTyCon_maybe tycon
= Just (tycon, ty_args, con, dataConInstArgTys con ty_args)
| otherwise
= Nothing
{-
************************************************************************
* *
Building an algebraic data type
* *
************************************************************************
buildAlgTyCon is here because it is called from TysWiredIn, which can
depend on this module, but not on BuildTyCl.
-}
buildAlgTyCon :: Name
-> [TyVar] -- ^ Kind variables and type variables
-> [Role]
-> Maybe CType
-> ThetaType -- ^ Stupid theta
-> AlgTyConRhs
-> RecFlag
-> Bool -- ^ True <=> this TyCon is promotable
-> Bool -- ^ True <=> was declared in GADT syntax
-> AlgTyConFlav
-> TyCon
buildAlgTyCon tc_name ktvs roles cType stupid_theta rhs
is_rec is_promotable gadt_syn parent
= tc
where
kind = mkPiKinds ktvs liftedTypeKind
-- tc and mb_promoted_tc are mutually recursive
tc = mkAlgTyCon tc_name kind ktvs roles cType stupid_theta
rhs parent is_rec gadt_syn
mb_promoted_tc
mb_promoted_tc
| is_promotable = Promoted (mkPromotedTyCon tc (promoteKind kind))
| otherwise = NotPromoted
|
AlexanderPankiv/ghc
|
compiler/basicTypes/DataCon.hs
|
Haskell
|
bsd-3-clause
| 51,933
|
{-# LANGUAGE BangPatterns #-}
module Randomish
( randomishInts
, randomishDoubles)
where
import Data.Word
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Generic as G
-- | Use the "minimal standard" Lehmer generator to quickly generate some random
-- numbers with reasonable statistical properties. By "reasonable" we mean good
-- enough for games and test data, but not cryptography or anything where the
-- quality of the randomness really matters.
--
-- From "Random Number Generators: Good ones are hard to find"
-- Stephen K. Park and Keith W. Miller.
-- Communications of the ACM, Oct 1988, Volume 31, Number 10.
--
randomishInts
:: Int -- Length of vector.
-> Int -- Minumum value in output.
-> Int -- Maximum value in output.
-> Int -- Random seed.
-> Vector Int -- Vector of random numbers.
randomishInts !len !valMin' !valMax' !seed'
= let -- a magic number (don't change it)
multiplier :: Word64
multiplier = 16807
-- a merzenne prime (don't change it)
modulus :: Word64
modulus = 2^(31 :: Integer) - 1
-- if the seed is 0 all the numbers in the sequence are also 0.
seed
| seed' == 0 = 1
| otherwise = seed'
!valMin = fromIntegral valMin'
!valMax = fromIntegral valMax' + 1
!range = valMax - valMin
{-# INLINE f #-}
f x = multiplier * x `mod` modulus
in G.create
$ do
vec <- MV.new len
let go !ix !x
| ix == len = return ()
| otherwise
= do let x' = f x
MV.write vec ix $ fromIntegral $ (x `mod` range) + valMin
go (ix + 1) x'
go 0 (f $ f $ f $ fromIntegral seed)
return vec
-- | Generate some randomish doubles with terrible statistical properties.
-- This is good enough for test data, but not much else.
randomishDoubles
:: Int -- Length of vector
-> Double -- Minimum value in output
-> Double -- Maximum value in output
-> Int -- Random seed.
-> Vector Double -- Vector of randomish doubles.
randomishDoubles !len !valMin !valMax !seed
= let range = valMax - valMin
mx = 2^(30 :: Integer) - 1
mxf = fromIntegral mx
ints = randomishInts len 0 mx seed
in V.map (\n -> valMin + (fromIntegral n / mxf) * range) ints
|
agremm/Matryoshka
|
examples/lib/Randomish.hs
|
Haskell
|
bsd-3-clause
| 2,267
|
{-# LANGUAGE StandaloneKindSignatures #-}
module SAKS_Fail007 where
import Data.Kind (Type)
type May a :: Type
data May a = Nay | Yay a
|
sdiehl/ghc
|
testsuite/tests/saks/should_fail/saks_fail007.hs
|
Haskell
|
bsd-3-clause
| 139
|
module HN.Blaze
(module Text.Blaze.Extra
,module Text.Blaze.Html5
,module Text.Blaze.Html5.Attributes
,module Text.Blaze.Renderer.Text
,module Text.Blaze.Linkify
,module Text.Blaze.Pagination
,module Text.Blaze.Bootstrap
)
where
import Text.Blaze.Extra
import Text.Blaze.Html5 hiding (output,map,i,title,cite,style,summary,object,footer)
import Text.Blaze.Html5.Attributes hiding (label,span,cite,form,summary)
import Text.Blaze.Renderer.Text
import Text.Blaze.Linkify
import Text.Blaze.Pagination
import Text.Blaze.Bootstrap
|
jwaldmann/haskellnews
|
src/HN/Blaze.hs
|
Haskell
|
bsd-3-clause
| 547
|
{-# LANGUAGE MagicHash #-}
{-# OPTIONS_GHC -Werror #-}
-- Trac #2806
module Foo where
import GHC.Base
foo :: Int
foo = 3
where (I# _x) = 4
|
hvr/jhc
|
regress/tests/1_typecheck/4_fail/ghc/T2806.hs
|
Haskell
|
mit
| 149
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ConstraintKinds #-}
-- | Tag a Binary instance with the stack version number to ensure we're
-- reading a compatible format.
module Data.Binary.VersionTagged
( taggedDecodeOrLoad
, taggedEncodeFile
, Binary (..)
, BinarySchema
, HasStructuralInfo
, HasSemanticVersion
, decodeFileOrFailDeep
, NFData (..)
) where
import Control.DeepSeq (NFData (..))
import Control.Exception (Exception)
import Control.Monad.Catch (MonadThrow (..))
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Data.Binary (Binary (..))
import Data.Binary.Get (ByteOffset)
import Data.Binary.Tagged (HasStructuralInfo, HasSemanticVersion)
import qualified Data.Binary.Tagged as BinaryTagged
import Data.Monoid ((<>))
import Data.Typeable (Typeable)
import Control.Exception.Enclosed (tryAnyDeep)
import Path
import Path.IO (ensureDir)
import qualified Data.Text as T
type BinarySchema a = (Binary a, NFData a, HasStructuralInfo a, HasSemanticVersion a)
-- | Write to the given file, with a binary-tagged tag.
taggedEncodeFile :: (BinarySchema a, MonadIO m)
=> Path Abs File
-> a
-> m ()
taggedEncodeFile fp x = liftIO $ do
ensureDir (parent fp)
BinaryTagged.taggedEncodeFile (toFilePath fp) x
-- | Read from the given file. If the read fails, run the given action and
-- write that back to the file. Always starts the file off with the version
-- tag.
taggedDecodeOrLoad :: (BinarySchema a, MonadIO m, MonadLogger m)
=> Path Abs File
-> m a
-> m a
taggedDecodeOrLoad fp mx = do
let fpt = T.pack (toFilePath fp)
$logDebug $ "Trying to decode " <> fpt
eres <- decodeFileOrFailDeep fp
case eres of
Left _ -> do
$logDebug $ "Failure decoding " <> fpt
x <- mx
taggedEncodeFile fp x
return x
Right x -> do
$logDebug $ "Success decoding " <> fpt
return x
-- | Ensure that there are no lurking exceptions deep inside the parsed
-- value... because that happens unfortunately. See
-- https://github.com/commercialhaskell/stack/issues/554
decodeFileOrFailDeep :: (BinarySchema a, MonadIO m, MonadThrow n)
=> Path loc File
-> m (n a)
decodeFileOrFailDeep fp = liftIO $ fmap (either throwM return) $ tryAnyDeep $ do
eres <- BinaryTagged.taggedDecodeFileOrFail (toFilePath fp)
case eres of
Left (offset, str) -> throwM $ DecodeFileFailure (toFilePath fp) offset str
Right x -> return x
data DecodeFileFailure = DecodeFileFailure FilePath ByteOffset String
deriving Typeable
instance Show DecodeFileFailure where
show (DecodeFileFailure fp offset str) = concat
[ "Decoding of "
, fp
, " failed at offset "
, show offset
, ": "
, str
]
instance Exception DecodeFileFailure
|
phadej/stack
|
src/Data/Binary/VersionTagged.hs
|
Haskell
|
bsd-3-clause
| 3,108
|
{-# LANGUAGE ScopedTypeVariables #-}
module BinaryDerive where
import Data.Generics
import Data.List
deriveM :: (Typeable a, Data a) => a -> IO ()
deriveM (a :: a) = mapM_ putStrLn . lines $ derive (undefined :: a)
derive :: (Typeable a, Data a) => a -> String
derive x =
"instance " ++ context ++ "Binary " ++ inst ++ " where\n" ++
concat putDefs ++ getDefs
where
context
| nTypeChildren > 0 =
wrap (join ", " (map ("Binary "++) typeLetters)) ++ " => "
| otherwise = ""
inst = wrap $ tyConString typeName ++ concatMap (" "++) typeLetters
wrap x = if nTypeChildren > 0 then "("++x++")" else x
join sep lst = concat $ intersperse sep lst
nTypeChildren = length typeChildren
typeLetters = take nTypeChildren manyLetters
manyLetters = map (:[]) ['a'..'z']
(typeName,typeChildren) = splitTyConApp (typeOf x)
constrs :: [(Int, (String, Int))]
constrs = zip [0..] $ map gen $ dataTypeConstrs (dataTypeOf x)
gen con = ( showConstr con
, length $ gmapQ undefined $ fromConstr con `asTypeOf` x
)
putDefs = map ((++"\n") . putDef) constrs
putDef (n, (name, ps)) =
let wrap = if ps /= 0 then ("("++) . (++")") else id
pattern = name ++ concatMap (' ':) (take ps manyLetters)
in
" put " ++ wrap pattern ++" = "
++ concat [ "putWord8 " ++ show n | length constrs > 1 ]
++ concat [ " >> " | length constrs > 1 && ps > 0 ]
++ concat [ "return ()" | length constrs == 1 && ps == 0 ]
++ join " >> " (map ("put "++) (take ps manyLetters))
getDefs =
(if length constrs > 1
then " get = do\n tag_ <- getWord8\n case tag_ of\n"
else " get =")
++ concatMap ((++"\n")) (map getDef constrs) ++
(if length constrs > 1
then " _ -> fail \"no decoding\""
else ""
)
getDef (n, (name, ps)) =
let wrap = if ps /= 0 then ("("++) . (++")") else id
in
concat [ " " ++ show n ++ " ->" | length constrs > 1 ]
++ concatMap (\x -> " get >>= \\"++x++" ->") (take ps manyLetters)
++ " return "
++ wrap (name ++ concatMap (" "++) (take ps manyLetters))
|
ezyang/binary
|
tools/derive/BinaryDerive.hs
|
Haskell
|
bsd-3-clause
| 2,273
|
{-# Language TemplateHaskell #-}
{-# Language DisambiguateRecordFields #-}
module T12130 where
import T12130a hiding (Block)
b = $(block)
|
olsner/ghc
|
testsuite/tests/th/T12130.hs
|
Haskell
|
bsd-3-clause
| 141
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{- |
Module : Database.Couch.Explicit.Design
Description : Design Document-oriented requests to CouchDB, with explicit parameters
Copyright : Copyright (c) 2015, Michael Alan Dorman
License : MIT
Maintainer : mdorman@jaunder.io
Stability : experimental
Portability : POSIX
This module is intended to be @import qualified@. /No attempt/ has been made to keep names of types or functions from clashing with obvious or otherwise commonly-used names, or even other modules within this package.
The functions here are derived from (and presented in the same order as) the <http://docs.couchdb.org/en/1.6.1/api/ddoc/common.html Design Document API documentation>. For each function, we attempt to link back to the original documentation, as well as make a notation as to how complete and correct we feel our implementation is.
Each function takes a 'Database.Couch.Types.Context'---which, among other things, holds the name of the database---as its final parameter, and returns a 'Database.Couch.Types.Result'.
-}
module Database.Couch.Explicit.Design where
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON, ToJSON, object,
toJSON)
import Data.Function (($))
import Data.Maybe (Maybe (Nothing))
import qualified Database.Couch.Explicit.DocBase as Base (accessBase, copy,
delete, get, meta,
put)
import Database.Couch.Internal (standardRequest)
import Database.Couch.RequestBuilder (RequestBuilder, addPath,
selectDoc, setJsonBody,
setMethod, setQueryParam)
import Database.Couch.Types (Context, DocId, DocRev,
ModifyDoc, Result,
RetrieveDoc, ViewParams,
toQueryParameters)
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#head--db-_design-ddoc Get the size and revision of the specified design document>
The return value is an object that should only contain the keys "rev" and "size", that can be easily parsed into a pair of (DocRev, Int):
>>> (,) <$> (getKey "rev" >>= toOutputType) <*> (getKey "size" >>= toOutputType)
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
meta :: (FromJSON a, MonadIO m)
=> RetrieveDoc -- ^ Parameters for the HEAD request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> Context
-> m (Result a)
meta = Base.meta "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#get--db-_design-ddoc Get the specified design document>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.get "pandas" Nothing ctx
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
get :: (FromJSON a, MonadIO m)
=> RetrieveDoc -- ^ Parameters for the HEAD request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> Context
-> m (Result a)
get = Base.get "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#put--db-_design-ddoc Create or replace the specified design document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- Design.put modifyDoc "pandas" Nothing SomeValue ctx >>= asBool
Status: __Complete__ -}
put :: (FromJSON a, MonadIO m, ToJSON b)
=> ModifyDoc -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> b
-> Context
-> m (Result a)
put = Base.put "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#delete--db-_design-ddoc Delete the specified design document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- Design.delete modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
delete :: (FromJSON a, MonadIO m)
=> ModifyDoc -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> Context
-> m (Result a)
delete = Base.delete "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#copy--db-_design-ddoc Copy the specified design document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- Design.delete modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
copy :: (FromJSON a, MonadIO m)
=> ModifyDoc -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> DocId
-> Context
-> m (Result a)
copy = Base.copy "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/ddoc/common.html#get--db-_design-ddoc-_info Get information on a design document>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.info "pandas" ctx
Status: __Complete__ -}
info :: (FromJSON a, MonadIO m)
=> DocId -- ^ The ID of the design document
-> Context
-> m (Result a)
info doc =
standardRequest request
where
request = do
Base.accessBase "_design" doc Nothing
addPath "_info"
{- | <http://docs.couchdb.org/en/1.6.1/api/ddoc/views.html#get--db-_design-ddoc-_view-view Get a list of all database documents>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.allDocs viewParams "pandas" "counter" ctx
Status: __Complete__ -}
allDocs :: (FromJSON a, MonadIO m)
=> ViewParams -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> DocId -- ^ The ID of the view
-> Context
-> m (Result a)
allDocs params doc view =
standardRequest $ viewBase params doc view
{- | <http://docs.couchdb.org/en/1.6.1/api/ddoc/views.html#post--db-_design-ddoc-_view-view Get a list of some database documents>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.someDocs viewParams "pandas" "counter" ["a", "b"] ctx
Status: __Complete__ -}
someDocs :: (FromJSON a, MonadIO m)
=> ViewParams -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> DocId -- ^ The ID of the view
-> [DocId] -- ^ The IDs of the documents of interest
-> Context
-> m (Result a)
someDocs params doc view ids =
standardRequest request
where
request = do
setMethod "POST"
viewBase params doc view
let docs = object [("keys", toJSON ids)]
setJsonBody docs
-- * Internal combinators
-- | Base bits for all view queries
viewBase :: ViewParams -> DocId -> DocId -> RequestBuilder ()
viewBase params doc view = do
Base.accessBase "_design" doc Nothing
addPath "_view"
selectDoc view
setQueryParam $ toQueryParameters params
|
mdorman/couch-simple
|
src/lib/Database/Couch/Explicit/Design.hs
|
Haskell
|
mit
| 8,043
|
{-# LANGUAGE BangPatterns #-}
module Feitoria.Types where
import Codec.MIME.Type
import qualified Data.ByteString as B
import Data.Time
import Data.Word
import Foreign.Ptr
import qualified Data.Text as T
import qualified Data.Vector as V
--data MMapTable = MMapTable {
-- mmapTblHeader :: !TableHeader
-- , mmapTblPtr :: !(Ptr ())
-- , mmapTblCols :: [MMapColumn]
-- , mmapTblNumColumns :: !Word64
-- , mmapTblNumRecords :: !Word64
-- , mmapTblColTblOffset :: !Int
-- , mmapTblStringLitOffset :: !Int
-- , mmapTblArrayLitOffset :: !Int
-- , mmapTblBinaryLitOffset :: !Int
-- }
--
--data MMapColumn = MMapColumn {
-- mmapHeader :: !ColumnHeader
-- , mmapOffset :: !Int
-- }
data CellType = CellTypeUInt
| CellTypeInt
| CellTypeDouble
| CellTypeDateTime
| CellTypeString
| CellTypeBinary MIMEType
| CellTypeBoolean
deriving (Eq, Ord, Show)
type Cell = Maybe CellData
data CellData = CellDataUInt Word64
| CellDataInt Int
| CellDataDouble Double
| CellDataDateTime UTCTime
| CellDataBoolean Bool
| CellDataString T.Text
| CellDataBinary B.ByteString
| CellDataArray (V.Vector CellData)
deriving (Eq, Ord, Show)
|
MadSciGuys/feitoria
|
src/Feitoria/Types.hs
|
Haskell
|
mit
| 1,412
|
{-# htermination addToFM_C :: (Ord a, Ord k) => (b -> b -> b) -> FiniteMap (Either a k) b -> (Either a k) -> b -> FiniteMap (Either a k) b #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_addToFM_C_10.hs
|
Haskell
|
mit
| 160
|
module EntityWrapper.Schema
( module EntityWrapper.Schema
, module EntityWrapper.Schema.Virus
) where
import qualified Database.Orville.PostgreSQL as O
import EntityWrapper.Schema.Virus
schema :: O.SchemaDefinition
schema = [O.Table virusTable]
|
flipstone/orville
|
orville-postgresql/test/EntityWrapper/Schema.hs
|
Haskell
|
mit
| 254
|
module Typing.Util where
import Typing.Env
import Typing.Kinds
import {-# SOURCE #-} Typing.Stmt
import Typing.Substitution
import Typing.Subtyping
import Typing.TypeError
import Typing.Types
import Util.Error
import Absyn.Base
import Absyn.Meta
import qualified Absyn.Untyped as U
import qualified Absyn.Typed as T
import Control.Monad (when)
import Data.Maybe (fromMaybe)
(<:!) :: Type -> Type -> Tc ()
actualTy <:! expectedTy =
when (not $ actualTy <: expectedTy) (throwError $ TypeError expectedTy actualTy)
assertKindStar :: Type -> Tc ()
assertKindStar ty =
let kind = kindOf ty
in when (kind /= Star) (throwError $ KindError ty Star kind)
resolveId :: U.Param -> Tc T.Id
resolveId (n, ty) = (,) n <$> resolveType ty
resolveType :: U.Type -> Tc Type
resolveType (U.TName v) =
lookupType v
resolveType (U.TArrow params ret) = do
params' <- mapM resolveType params
ret' <- resolveType ret
return $ Fun [] params' ret'
resolveType (U.TRecord fieldsTy) = do
fieldsTy' <- mapM resolveId fieldsTy
return $ Rec fieldsTy'
resolveType (U.TApp t1 t2) = do
t1' <- resolveType t1
t2' <- mapM resolveType t2
case t1' of
TyAbs params ty -> do
when (length params /= length t2) $ throwError TypeArityMismatch
return $ applySubst (zipSubst params t2') ty
_ -> return $ TyApp t1' t2'
resolveType U.TVoid = return void
resolveType U.TPlaceholder = undefined
resolveGenericBounds :: [(String, [String])] -> Tc [(String, [Intf])]
resolveGenericBounds gen =
mapM resolve gen
where
resolve (name, bounds) = do
bounds' <- mapM resolveConstraint bounds
return (name, bounds')
resolveConstraint intf = do
lookupInterface intf
resolveGenericVars :: [(String, [Intf])] -> Tc [BoundVar]
resolveGenericVars generics =
mapM aux generics
where
aux (g, bounds) = do
g' <- newVar g
return (g', bounds)
addGenerics :: [BoundVar] -> Tc ()
addGenerics generics =
mapM_ aux generics
where
aux (var, bounds) = do
insertType (varName var) (Var var bounds)
defaultBounds :: [a] -> [(a, [b])]
defaultBounds = map (flip (,) [])
i_fn :: U.Function -> Tc (T.Function, Type)
i_fn (meta :< fn) = do
gen' <- resolveGenericBounds (generics fn)
genericVars <- resolveGenericVars gen'
m <- startMarker
addGenerics genericVars
(ty, tyArgs, retType') <- fnTy (genericVars, params fn, retType fn)
mapM_ (uncurry insertValue) tyArgs
insertValue (name fn) ty
endMarker m
(body', bodyTy) <- i_body (body fn)
clearMarker m
bodyTy <:! retType'
let fn' = fn { body = body' }
return (meta :< fn', ty)
i_body :: U.CodeBlock -> Tc (T.CodeBlock, Type)
i_body (meta :< CodeBlock stmts) = do
m <- startMarker
(stmts', ty) <- i_stmts stmts
endMarker m
clearMarker m
return (meta :< CodeBlock stmts', fromMaybe void ty)
fnTy :: ([BoundVar], [(String, U.Type)], U.Type) -> Tc (Type, [(String, Type)], Type)
fnTy (generics, params, retType) = do
tyArgs <- mapM resolveId params
mapM_ (assertKindStar . snd) tyArgs
retType' <- resolveType retType
assertKindStar retType'
let tyArgs' = if null tyArgs
then [void]
else map snd tyArgs
let ty = Fun generics tyArgs' retType'
return (ty, tyArgs, retType')
|
tadeuzagallo/verve-lang
|
src/Typing/Util.hs
|
Haskell
|
mit
| 3,258
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Game.Implement.Card
-- Copyright : (c) 2017 Christopher A. Gorski
-- License : MIT
-- Maintainer : Christopher A. Gorski <cgorski@cgorski.org>
--
-- The Game.Implement.Card module provides fundamental operations for a deck of cards.
module Game.Implement.Card
(
Card (..)
, ValuedCard (..)
, OrderedCard (..)
, OrderedValuedCard (..)
)
where
import Control.Monad.Random
import System.Random.Shuffle (shuffleM)
import Data.List (nub, maximumBy, minimumBy, sortBy, foldl1', tails)
-- |
-- Represents a physical card with no order and no value.
-- Inherited Enum, Eq, Ord and Bounded typeclasses are used to
-- distingish cards for the purposes of manipulation within lists.
-- Game value functions are provided by other typeclasses.
class (Enum c, Eq c, Ord c, Bounded c) => Card c where
-- |
-- Return all combinations of size n of a deck of cards
choose :: Int -> [c] -> [[c]]
choose 0 _ = [[]]
choose n lst = do
(x:xs) <- tails lst
rest <- choose (n-1) xs
return $ x : rest
-- |
-- Return a full deck of cards. Cards are unique. Order is not guaranteed.
--
-- >>> fullDeck :: [PlayingCard]
-- [Ace of Clubs,Two of Clubs,Three of Clubs,Four of Clubs,Five of Clubs,Six of Clubs,Seven of Clubs,Eight of Clubs,Nine of Clubs,Ten of Clubs,Jack of Clubs,Queen of Clubs,King of Clubs,Ace of Diamonds,Two of Diamonds,Three of Diamonds,Four of Diamonds,Five of Diamonds,Six of Diamonds,Seven of Diamonds,Eight of Diamonds,Nine of Diamonds,Ten of Diamonds,Jack of Diamonds,Queen of Diamonds,King of Diamonds,Ace of Hearts,Two of Hearts,Three of Hearts,Four of Hearts,Five of Hearts,Six of Hearts,Seven of Hearts,Eight of Hearts,Nine of Hearts,Ten of Hearts,Jack of Hearts,Queen of Hearts,King of Hearts,Ace of Spades,Two of Spades,Three of Spades,Four of Spades,Five of Spades,Six of Spades,Seven of Spades,Eight of Spades,Nine of Spades,Ten of Spades,Jack of Spades,Queen of Spades,King of Spades]
fullDeck :: [c]
-- |
-- Returns all unique cards in a list. All duplicates are removed.
dedupe :: [c] -> [c]
-- |
-- Draws cards from a deck, and groups them based on the list provided
-- in the first argument. Returns the grouped hands and the remaining deck.
-- Arguments that are negative or exceed bounds return Nothing.
--
-- For instance, to simulate a three player Hold'em game, one might wish
-- to draw two cards for each player, and five cards for the community:
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw [2,2,2,5] deck
-- Just ([[Ace of Spades,Jack of Spades],[Queen of Hearts,Seven of Clubs],[Jack of Diamonds,Six of Hearts],[Jack of Hearts,Five of Spades,Three of Spades,Two of Diamonds,Ace of Hearts]],[Four of Clubs,Six of Diamonds,Four of Diamonds,Eight of Spades,Six of Clubs,Seven of Spades,Three of Diamonds,Ten of Diamonds,Eight of Hearts,Nine of Diamonds,Three of Clubs,Six of Spades,King of Clubs,Nine of Clubs,Four of Spades,Five of Diamonds,Nine of Spades,Queen of Spades,Ace of Diamonds,Four of Hearts,Two of Clubs,Five of Clubs,Two of Hearts,King of Diamonds,Ten of Spades,Eight of Clubs,Seven of Hearts,Three of Hearts,Queen of Diamonds,Queen of Clubs,Ten of Clubs,King of Hearts,Eight of Diamonds,Jack of Clubs,Ten of Hearts,Seven of Diamonds,Two of Spades,Nine of Hearts,King of Spades,Ace of Clubs,Five of Hearts])
draw :: [Int] -> [c] -> Maybe ([[c]],[c])
-- |
-- The same as 'draw', except throw away the deck
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw_ [2,2,2,5] deck
-- Just [[Eight of Hearts,Queen of Hearts],[Two of Clubs,Seven of Diamonds],[Ten of Clubs,Three of Hearts],[Ace of Spades,Nine of Spades,Five of Spades,Four of Diamonds,Two of Spades]]
draw_ :: [Int] -> [c] -> Maybe [[c]]
-- |
-- The same as 'draw', except draw only one hand of specified size.
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw1 5 deck
-- Just ([Six of Clubs,Ace of Hearts,Nine of Hearts,Four of Hearts,Two of Diamonds],[King of Diamonds,Queen of Spades,Four of Spades,Seven of Hearts,Five of Hearts,Seven of Clubs,Three of Hearts,Ace of Spades,Three of Diamonds,Seven of Diamonds,Two of Clubs,Five of Spades,King of Hearts,Jack of Hearts,Queen of Hearts,Ten of Clubs,Five of Clubs,Eight of Spades,Ace of Clubs,King of Clubs,Five of Diamonds,Queen of Diamonds,Eight of Hearts,Four of Clubs,Three of Clubs,Jack of Clubs,Jack of Diamonds,Ten of Diamonds,Queen of Clubs,Eight of Diamonds,Six of Diamonds,Eight of Clubs,Three of Spades,Two of Hearts,Six of Spades,King of Spades,Ten of Hearts,Nine of Spades,Nine of Diamonds,Two of Spades,Ten of Spades,Nine of Clubs,Four of Diamonds,Ace of Diamonds,Six of Hearts,Seven of Spades,Jack of Spades])
draw1 :: Int -> [c] -> Maybe ([c],[c])
-- |
-- The same as 'draw1', except throw away the deck.
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw1_ 5 deck
-- Just [Five of Hearts,Ace of Diamonds,Ten of Hearts,Two of Spades,Six of Clubs]
draw1_ :: Int -> [c] -> Maybe [c]
-- |
-- Shuffle a deck of cards.
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> [Three of Clubs,Nine of Spades,Five of Clubs,Two of Hearts,Four of Spades,King of Hearts,Ten of Hearts,Two of Clubs,Ace of Hearts,Eight of Diamonds,Six of Diamonds,Seven of Diamonds,Jack of Spades,Three of Hearts,Three of Spades,Queen of Clubs,Ten of Diamonds,Six of Spades,Two of Diamonds,Nine of Clubs,Five of Diamonds,Five of Spades,Seven of Spades,Jack of Clubs,Six of Hearts,Jack of Diamonds,Four of Hearts,Ace of Spades,Nine of Diamonds,King of Clubs,Two of Spades,Four of Clubs,Eight of Hearts,Queen of Hearts,Ace of Clubs,Five of Hearts,Ten of Spades,Six of Clubs,Ten of Clubs,Four of Diamonds,Three of Diamonds,Seven of Hearts,King of Diamonds,Ace of Diamonds,Nine of Hearts,Queen of Spades,Seven of Clubs,Jack of Hearts,King of Spades,Eight of Spades,Queen of Diamonds,Eight of Clubs]
shuffle :: RandomGen m => [c] -> Rand m [c]
-- |
-- Return a random card.
--
-- >>> card :: PlayingCard <- evalRandIO $ randomCard
-- >>> card
-- Four of Diamonds
randomCard :: RandomGen m => Rand m c
fullDeck = [minBound .. maxBound]
dedupe l = nub l
shuffle deck = shuffleM deck
randomCard =
let
minB = minBound :: (Bounded c, Card c) => c
maxB = maxBound :: (Bounded c, Card c) => c in
do
randomd <- getRandomR(fromEnum minB, fromEnum maxB)
return $ toEnum randomd
draw handSizeLst deck
| let
total = (foldl1' (+) handSizeLst)
anyNeg = (length (filter (\n -> n < 0) handSizeLst)) > 0
in
(total > (length deck)) || (total < 1) || anyNeg = Nothing
| otherwise = let
draw2 [] (houtput, doutput) = ((reverse houtput), doutput)
draw2 (nToTake:hst) (handOutput, deckOutput) = let
newHand = take nToTake deckOutput
newDeck = drop nToTake deckOutput in
draw2 hst (newHand:handOutput, newDeck)
in Just (draw2 handSizeLst ([],deck))
draw_ handSizes deck =
let f (Just (h, _)) = Just h
f _ = Nothing
in
f $ draw handSizes deck
draw1 handSize deck =
let
f (Just ([h], d)) = Just (h,d)
f _ = Nothing
in
f $ draw [handSize] deck
draw1_ handSize deck =
let
f (Just ([h], _)) = Just h
f _ = Nothing
in
f $ draw [handSize] deck
-- |
-- Represents a playing card with a game value. For instance,
-- a standard playing card with a type representing
-- rank and suit.
class (Card c) => ValuedCard c v where
-- |
-- Return a value associated with a card.
--
-- >>> card = PlayingCard Six Clubs
-- >>> toValue card :: Rank
-- Six
-- >>> toValue card :: Suit
-- Clubs
toValue :: c -> v
-- |
-- Return values associated with multiple cards.
--
-- >>> cards = [PlayingCard Six Clubs, PlayingCard Four Diamonds]
-- >>> toValueLst cards :: [Rank]
-- [Six,Four]
-- >>> toValueLst cards :: [Suit]
-- [Clubs,Diamonds]
toValueLst :: [c] -> [v]
toValueLst l = map toValue l
-- |
-- Orderings independent of a specific value
-- type of a Card.
class (Card c) => OrderedCard c o where
highestCardBy :: o -> [c] -> c
lowestCardBy :: o -> [c] -> c
compareCardBy :: o -> c -> c -> Ordering
sortCardsBy :: o -> [c] -> [c]
highestCardBy o cl = maximumBy (compareCardBy o) cl
lowestCardBy o cl = minimumBy (compareCardBy o) cl
sortCardsBy o cl = sortBy (compareCardBy o) cl
-- |
-- Orderings dependent on the specific value type of a Card
class (OrderedCard c o) => OrderedValuedCard c o vt where
-- |
-- Return an Int based on a card, an ordering and a value type.
toOrderedValue :: o -> vt -> c -> Int
|
cgorski/general-games
|
src/Game/Implement/Card.hs
|
Haskell
|
mit
| 8,909
|
import qualified Data.Hash.MD5 as MD5
md5snum str x = MD5.md5s $ MD5.Str $ str ++ show x
firstSixZeros str x
| take 6 (md5snum str x) == "000000" = x
| otherwise = -1
main = do
let word_part = "iwrupvqb"
print $ head [firstSixZeros word_part x | x <- [0..], firstSixZeros word_part x > 0]
|
RatanRSur/advent-of-haskell
|
day4/part2.hs
|
Haskell
|
mit
| 309
|
module Problem2 ( secondToLastElem ) where
secondToLastElem :: [a] -> a
secondToLastElem x = last (init x)
|
chanind/haskell-99-problems
|
Problem2.hs
|
Haskell
|
mit
| 107
|
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}
module Y2018.M05.D25.Solution where
import Control.Arrow ((&&&))
import Control.Concurrent (threadDelay)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.Types
import Network.HTTP.Conduit
import Network.HTTP.Types hiding (Query)
-- below imports available via 1HaskellADay
import Data.Logger hiding (mod)
import Data.LookupTable
import Store.SQL.Connection
import Store.SQL.Util.Indexed
import Store.SQL.Util.Logging
{--
Okay, let's do a little testy-testy.
Download some articles from the database, upload them to a rest endpoint, and
eh, that's today's exercise.
--}
nerEndpoint :: FilePath
nerEndpoint = "https://grby98heb8.execute-api.us-east-1.amazonaws.com/CORS"
{--
The curl command is:
curl -X POST -H "Content-Type: application/json" -d '{"text": "I am going to see Deadpool2 on Friday."}'
Or whatever you're sending from the database.
But you're going to do a HTTPS POST to the rest endpoint. So do that. AND get
the response, AND get the response type (200, 400, 504)
--}
data S = S { txt :: String }
instance FromRow S where
fromRow = S <$> field
type Conn1 = (Connection, LookupTable)
instance Show S where show = take 100 . txt
fetchStmt :: Int -> Int -> Query
fetchStmt n offset =
Query (B.pack ("SELECT id,full_text FROM article WHERE id > " ++ show offset
++ " LIMIT " ++ show n))
-- query looks like:
-- [sql|SELECT id,full_text FROM article WHERE id > ? LIMIT (?)|]
fetchIxArticle :: Connection -> Int -> Int -> IO [IxValue S]
fetchIxArticle conn n = query_ conn . fetchStmt n
-- fetches n articles.
-- Question: IDs are not sequential. What is the max id of the fetch?
curlCmd :: Conn1 -> Int -> IxValue S -> IO (Status, String)
curlCmd = cc' 30 0
cc' :: Int -> Int -> Conn1 -> Int -> IxValue S -> IO (Status, String)
cc' secs tries conn n msg =
if tries > 3 then return (Status 504 "failed", "")
else (newManager tlsManagerSettings >>= \mgr ->
parseRequest nerEndpoint >>= \req ->
let jsn = BL.pack ("{ \"text\": " ++ show (txt (val msg)) ++ " }")
req' = req { responseTimeout = responseTimeoutMicro (secs * 1000000),
method = "POST",
-- requestHeaders = [(CI "application", "json")],
requestBody = RequestBodyLBS jsn } in
httpLbs req' mgr >>= \((responseStatus &&& BL.unpack . responseBody) -> it) ->
logStatus conn n tries msg it >>
(if n `mod` 100 == 0
then info conn ("NER processed " ++ show n ++ " articles")
else return ()) >>
return it)
-- sends text, gets a response and status
logStatus :: Conn1 -> Int -> Int -> IxValue S -> (Status, String) -> IO ()
logStatus conn n tries art@(IxV x _) (stat, resp) =
if statusCode stat == 200
then debug conn n x resp
else warn conn tries n x stat resp >> cc' 30 (succ tries) conn n art >> return ()
where debug (conn,lk) n x msg =
roff conn lk DEBUG "Load Tester" "Y2018.M05.D25.Solution"
("Row " ++ show n ++ ", entities (article " ++ show x
++ "): " ++ take 200 resp)
warn :: Conn1 -> Int -> Int -> Integer -> Status -> String -> IO ()
warn (conn,lk) tries n x stat msg =
roff conn lk WARN "Load Tester" "Y2018.M05.D25.Solution"
("WARNING Row " ++ show n ++ ", code: "
++ show (statusCode stat) ++ " for article " ++ show x
++ ": " ++ msg)
info :: Conn1 -> String -> IO ()
info (conn,lk) = mkInfo "Load Tester" "Y2018.M05.D25.Solution" lk conn
-- And our application that brings it all together
main' :: [String] -> IO ()
main' [n, offset] =
let n1 = read n
off1 = read offset in
withConnection PILOT (\conn ->
initLogger conn >>= \lk ->
let log = info (conn,lk) in
log ("Load testing API Gateway with " ++ n ++ " articles from " ++ offset) >>
fetchIxArticle conn n1 off1 >>= \arts ->
log ("Fetched " ++ n ++ " articles") >>
mapM_ (\(x, art) -> curlCmd (conn, lk) x art >> threadDelay 2000) (zip [1..] arts) >>
log ("Processed entities for " ++ n ++ " articles") >>
log ("Max ID is " ++ show (maximum (map idx arts))))
{--
>>> main' (words "3 253013")
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Load testing API Gateway with 3 articles from 253013"}, time = 2018-05-25 15:11:13.885881}
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Fetched 3 articles"}, time = 2018-05-25 15:11:13.991414}
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Processed entities for 3 articles"}, time = 2018-05-25 15:11:51.739545}
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Max ID is 253016"}, time = 2018-05-25 15:11:51.743727}
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M05/D25/Solution.hs
|
Haskell
|
mit
| 5,075
|
module Main where
import Lib
import Text.Printf
n = 100::Integer
main :: IO ()
main = do
printf "Square of sum minus sum of squares = %d\n" (squareSum n - sumSquares n)
|
JohnL4/ProjectEuler
|
Haskell/Problem006/app/Main.hs
|
Haskell
|
mit
| 174
|
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module Chatwork.V0.Api (
module Chatwork.V0.ChatworkConfig
, module Chatwork.V0.Type
, module Chatwork.V0.Message
, login
, loadChat
, loadRoom
, readChat
, getUpdate
, sendChat
, getRoomInfo
)
where
import Network.HTTP.Conduit
import Network.HTTP.Types
import Control.Applicative (pure, (<$>))
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString.Char8 as C
import Text.ParserCombinators.Parsec
import qualified Data.ByteString.Lazy as BL
import Chatwork.V0.ChatworkConfig
import Chatwork.V0.Type
import Chatwork.V0.Message
import Data.Time.Clock (getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import Data.Aeson (eitherDecode, decode, encode, FromJSON, ToJSON, object, (.=), toJSON)
import System.IO.Unsafe (unsafePerformIO)
import qualified Control.Monad.State as State
import Control.Monad.IO.Class (liftIO)
import Prelude hiding (read)
import qualified Data.Text as T
import Data.List (intercalate)
import qualified Control.Exception as E
type QueryParam = [(String, String)]
type ApiResponse a = Either String (Chatwork.V0.Type.Response a)
sendChat :: String -> String -> Chatwork IO (ApiResponse ())
sendChat rid body = do
post "send_chat" params postdata
where
params = []
postdata = SendChatData {
text = body,
room_id = rid,
last_chat_id = "0",
read = "0",
edit_id = "0"
}
getUpdate :: String -> Chatwork IO (ApiResponse GetUpdate)
getUpdate _lastId = do
get "get_update" params
where params = [ ("last_id" , _lastId),
("new" , "1") ]
readChat :: RoomId -> MessageId -> Chatwork IO (ApiResponse ReadChat)
readChat roomId lastChatId = do
get "read" params
where params = [ ("last_chat_id" , lastChatId),
("room_id" , roomId) ]
loadChat :: RoomId -> Chatwork IO (ApiResponse LoadChat)
loadChat roomId = do
get "load_chat" params
where params = [ ("room_id" , roomId),
("last_chat_id" , "0"),
("first_chat_id" , "0"),
("jump_to_chat_id" , "0"),
("unread_num" , "0"),
("desc" , "1") ]
loadRoom :: LoadRequest -> Chatwork IO (ApiResponse ())
loadRoom request = do
post "get_room_info" [] (toJSON request)
getRoomInfo :: RoomId -> Chatwork IO (ApiResponse RespGetRoomInfo)
getRoomInfo roomId = do
post "get_room_info" [] pdata
where
pdata = object [
"i" .= object [
(T.pack roomId) .= object [
"c" .= (0 :: Int),
"u" .= (0 :: Int),
"l" .= (0 :: Int),
"t" .= (0 :: Int)
]
],
"p" .= ([] :: [Int]),
"m" .= ([] :: [Int]),
"d" .= ([] :: [Int]),
"t" .= object [],
"rid" .= (0 :: Int),
"type" .= ("" :: String),
"load_file_version" .= ("2" :: String)
]
get :: (FromJSON a) => String -> [(String, String)] -> Chatwork IO (ApiResponse a)
get cmd params = request "GET" cmd params Nothing
post :: (FromJSON a, ToJSON b) => String -> [(String, String)] -> b -> Chatwork IO (ApiResponse a)
post cmd params postdata = request "POST" cmd params (Just pdata)
where
pdata = RequestBodyLBS $ "pdata=" `BL.append` json
json = encode postdata
-- method command query paramter post data
request :: (FromJSON a) => Method -> String -> [(String, String)] -> Maybe RequestBody -> Chatwork IO (ApiResponse a)
request method cmd params postdata = do
let time = unsafePerformIO $ formatTime defaultTimeLocale "%s" <$> getCurrentTime
maybeAuth <- fmap auth State.get
case maybeAuth of
Just auth -> do
let query = (fmap.fmap) Just $ fmap (\(a, b) -> (C.pack a, C.pack b)) $ filter (not.null) $ ([("_", time), ("cmd", cmd)] ++ params ++ authParams auth)
base <- fmap base State.get
let url = base ++ "gateway.php?"
__req <- parseUrl url
let _req = setQueryString query __req
let contentType = ("Content-Type", C.pack "application/x-www-form-urlencoded; charset=UTF-8")
let req = case postdata of
Just m -> _req {cookieJar = Just (jar auth), method = method, requestBody = m, requestHeaders = [contentType]}
Nothing -> _req {cookieJar = Just (jar auth), method = method}
manager <- liftIO $ newManager tlsManagerSettings
runResourceT $ do
res <- httpLbs req manager
return $ eitherDecode (responseBody res)
`catchStateT` httpExceptionHandler
Nothing -> return (Left "auth failed")
catchStateT :: E.Exception e
=> State.StateT s IO a
-> (e -> State.StateT s IO a)
-> State.StateT s IO a
catchStateT a onE = do
s1 <- State.get
(result, s2) <- liftIO $ State.runStateT a s1 `E.catch` \e ->
State.runStateT (onE e) s1
State.put s2
return result
httpExceptionHandler :: (FromJSON a) => HttpException -> Chatwork IO (ApiResponse a)
httpExceptionHandler e = do
liftIO $ print e
return $ Left (show e)
authParams :: Auth -> QueryParam
authParams auth = [ ("myid" , myid auth),
-- ("account_id" , myid auth),
("_t" , accessToken auth),
("_v" , "1.80a"),
-- ("ver" , "1.80a"),
("_av" , "4") ]
login :: Chatwork IO (Maybe Auth)
login = do
_base <- fmap base State.get
req <- parseUrl $ _base ++ "login.php?lang=en&args="
password <- fmap pass State.get
email <- fmap user State.get
office <- fmap office State.get
let _params = fmap pack $ [("email", email), ("password", password), ("orgkey", office), ("auto_login", "on"), ("login", "Login")]
let _req = (urlEncodedBody _params req) {method="POST"}
manager <- liftIO $ newManager tlsManagerSettings
res <- httpLbs _req manager
let jar = responseCookieJar res
let body = responseBody res
let authinfo = either (\a -> []) id $ fmap (filter (not.emptuple)) (parse parseHTML "" ((C.unpack $ BL.toStrict body) ++ "\n"))
let myid = lookup "myid" authinfo
let token = lookup "ACCESS_TOKEN" authinfo
let auth = case (myid, token) of
(Just m, Just t) -> Just $ Auth {jar = jar, myid = m, accessToken = t}
_ -> Nothing
State.put ChatworkConfig { base = _base, office = office, user = email, pass = password, auth = auth}
liftIO.pure $ auth
where
pack (a, b) = (a, C.pack b)
emptuple (a, b) = a == "" && b == ""
find key ts = head $ map snd $ filter (\t -> fst t == key) ts
parseHTML :: GenParser Char st [(String, String)]
parseHTML = do
result <- many line
eof
return result
line :: GenParser Char st (String, String)
line =
do result <- anyAuthInfo
optional (char ';')
optional (char '\r')
eol
return result
jsString :: GenParser Char st String
jsString = do
oneOf "\"'"
s <- many (noneOf "'\"")
oneOf "\"'"
return s
anyAuthInfo :: GenParser Char st (String, String)
anyAuthInfo = do
var
try authInfo <|> do
many (noneOf "\n")
anyAuthInfo
<|> (many (noneOf "\n") >> return ("",""))
authInfo = _myid <|> _token
_myid = jsStrVar "myid"
_token = jsStrVar "ACCESS_TOKEN"
var :: GenParser Char st String
var = string "var" >> spaces >> return []
jsStrVar :: String -> GenParser Char st (String, String)
jsStrVar str = do
string str
spaces
char '='
spaces
s <- jsString
return (str, s)
eol :: GenParser Char st Char
eol = char '\n'
|
totem3/cwhs
|
src/Chatwork/V0/Api.hs
|
Haskell
|
mit
| 7,809
|
{-# LANGUAGE RecordWildCards #-}
module StructuralIsomorphism.Declarations (
-- * Types
Constructor(..), DataType(..),
-- * Map from Template Haskell to these simpler types
constructor, dataType
) where
import Language.Haskell.TH.Syntax
data Constructor = Constructor { conName :: !Name
, conArguments :: ![StrictType] }
deriving (Eq, Ord, Show)
constructor :: Con -> Maybe Constructor
constructor (NormalC conName conArguments) = Just Constructor{..}
constructor (RecC conName fields) = Just Constructor{ conArguments =
[(s,ty) | (_,s,ty) <- fields]
, .. }
constructor (InfixC arg1 conName arg2) = Just Constructor{ conArguments = [arg1, arg2]
, .. }
constructor (ForallC _tvs _cxt _con) = Nothing
constructor (GadtC _names _tys _res) = Nothing
constructor (RecGadtC _names _fields _res) = Nothing
data DataType = DataType { dtContext :: !Cxt
, dtName :: !Name
, dtParameters :: ![TyVarBndr]
, dtKind :: !(Maybe Kind)
, dtConstructors :: ![Constructor]
, dtDeriving :: !Cxt }
deriving (Eq, Ord, Show)
dataType :: Dec -> Maybe DataType
dataType (DataD dtContext dtName dtParameters dtKind dtCons dtDeriving) = do
dtConstructors <- traverse constructor dtCons
Just DataType{..}
dataType (NewtypeD dtContext dtName dtParameters dtKind dtCon dtDeriving) = do
dtConstructors <- pure <$> constructor dtCon
Just DataType{..}
dataType _ =
Nothing
|
antalsz/hs-to-coq
|
structural-isomorphism-plugin/src/StructuralIsomorphism/Declarations.hs
|
Haskell
|
mit
| 1,795
|
module HelperSequences.A006519Spec (main, spec) where
import Test.Hspec
import HelperSequences.A006519 (a006519)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A006519" $
it "correctly computes the first 20 elements" $
take 20 (map a006519 [1..]) `shouldBe` expectedValue where
expectedValue = [1,2,1,4,1,2,1,8,1,2,1,4,1,2,1,16,1,2,1,4]
|
peterokagey/haskellOEIS
|
test/HelperSequences/A006519Spec.hs
|
Haskell
|
apache-2.0
| 366
|
{-# LANGUAGE PackageImports #-}
import "ministeam" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "dist/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
|
XxNocturnxX/ministeam
|
devel.hs
|
Haskell
|
bsd-2-clause
| 703
|
module Foundation
( App (..)
, Route (..)
, AppMessage (..)
, resourcesApp
, Handler
, Widget
, Form
, maybeAuth
, requireAuth
, module Settings
, module Model
) where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Logger (Logger, logMsg, formatLogText)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.MongoDB
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getLogger :: Logger
, getStatic :: Static -- ^ Settings for static file serving.
, connPool :: Database.Persist.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
messageLogger y loc level msg =
formatLogText (getLogger y) loc level msg >>= logMsg (getLogger y)
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = Action
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert $ User (credsIdent creds) Nothing
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
|
jgenso/comunidadhaskell.org
|
Foundation.hs
|
Haskell
|
bsd-2-clause
| 6,083
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsPathItem_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:25
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsPathItem_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QGraphicsPathItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsPathItem_unSetUserMethod" qtc_QGraphicsPathItem_unSetUserMethod :: Ptr (TQGraphicsPathItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsPathItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsPathItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsPathItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsPathItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsPathItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setUserMethod" qtc_QGraphicsPathItem_setUserMethod :: Ptr (TQGraphicsPathItem a) -> CInt -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsPathItem :: (Ptr (TQGraphicsPathItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsPathItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setUserMethodVariant" qtc_QGraphicsPathItem_setUserMethodVariant :: Ptr (TQGraphicsPathItem a) -> CInt -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsPathItem :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsPathItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QGraphicsPathItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsPathItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsPathItem_unSetHandler" qtc_QGraphicsPathItem_unSetHandler :: Ptr (TQGraphicsPathItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsPathItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsPathItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler1" qtc_QGraphicsPathItem_setHandler1 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem1 :: (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqqboundingRect_h (QGraphicsPathItem ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_boundingRect" qtc_QGraphicsPathItem_boundingRect :: Ptr (TQGraphicsPathItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsPathItemSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsPathItem ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsPathItem_boundingRect_qth" qtc_QGraphicsPathItem_boundingRect_qth :: Ptr (TQGraphicsPathItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsPathItemSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler2" qtc_QGraphicsPathItem_setHandler2 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem2 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqcontains_h (QGraphicsPathItem ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsPathItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsPathItem_contains_qth" qtc_QGraphicsPathItem_contains_qth :: Ptr (TQGraphicsPathItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsPathItemSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsPathItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsPathItem ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_contains" qtc_QGraphicsPathItem_contains :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsPathItemSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler3" qtc_QGraphicsPathItem_setHandler3 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem3 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler4" qtc_QGraphicsPathItem_setHandler4 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem4 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QisObscuredBy_h (QGraphicsPathItem ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_isObscuredBy" qtc_QGraphicsPathItem_isObscuredBy :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsPathItemSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem" qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler5" qtc_QGraphicsPathItem_setHandler5 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem5 :: (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QopaqueArea_h (QGraphicsPathItem ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_opaqueArea" qtc_QGraphicsPathItem_opaqueArea :: Ptr (TQGraphicsPathItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsPathItemSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_opaqueArea cobj_x0
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler6" qtc_QGraphicsPathItem_setHandler6 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem6 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qpaint_h (QGraphicsPathItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsPathItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsPathItem_paint1" qtc_QGraphicsPathItem_paint1 :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsPathItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsPathItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance Qshape_h (QGraphicsPathItem ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_shape cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_shape" qtc_QGraphicsPathItem_shape :: Ptr (TQGraphicsPathItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsPathItemSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_shape cobj_x0
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler7" qtc_QGraphicsPathItem_setHandler7 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem7 :: (Ptr (TQGraphicsPathItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqtype_h (QGraphicsPathItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_type cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_type" qtc_QGraphicsPathItem_type :: Ptr (TQGraphicsPathItem a) -> IO CInt
instance Qqtype_h (QGraphicsPathItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_type cobj_x0
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler8" qtc_QGraphicsPathItem_setHandler8 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem8 :: (Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qadvance_h (QGraphicsPathItem ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsPathItem_advance" qtc_QGraphicsPathItem_advance :: Ptr (TQGraphicsPathItem a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsPathItemSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler9" qtc_QGraphicsPathItem_setHandler9 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem9 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler10" qtc_QGraphicsPathItem_setHandler10 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem10 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem" qtc_QGraphicsPathItem_collidesWithItem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem1" qtc_QGraphicsPathItem_collidesWithItem1 :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem" qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem" qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler11" qtc_QGraphicsPathItem_setHandler11 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem11 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler12" qtc_QGraphicsPathItem_setHandler12 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem12 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcollidesWithPath_h (QGraphicsPathItem ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_collidesWithPath" qtc_QGraphicsPathItem_collidesWithPath :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsPathItemSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsPathItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPathItem_collidesWithPath1" qtc_QGraphicsPathItem_collidesWithPath1 :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsPathItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler13" qtc_QGraphicsPathItem_setHandler13 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem13 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcontextMenuEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_contextMenuEvent" qtc_QGraphicsPathItem_contextMenuEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dragEnterEvent" qtc_QGraphicsPathItem_dragEnterEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dragLeaveEvent" qtc_QGraphicsPathItem_dragLeaveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dragMoveEvent" qtc_QGraphicsPathItem_dragMoveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dropEvent" qtc_QGraphicsPathItem_dropEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsPathItem ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_focusInEvent" qtc_QGraphicsPathItem_focusInEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsPathItemSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsPathItem ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_focusOutEvent" qtc_QGraphicsPathItem_focusOutEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsPathItemSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_hoverEnterEvent" qtc_QGraphicsPathItem_hoverEnterEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_hoverLeaveEvent" qtc_QGraphicsPathItem_hoverLeaveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_hoverMoveEvent" qtc_QGraphicsPathItem_hoverMoveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsPathItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_inputMethodEvent" qtc_QGraphicsPathItem_inputMethodEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsPathItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler14" qtc_QGraphicsPathItem_setHandler14 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem14 :: (Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QGraphicsPathItem ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsPathItem_inputMethodQuery" qtc_QGraphicsPathItem_inputMethodQuery :: Ptr (TQGraphicsPathItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsPathItemSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler15" qtc_QGraphicsPathItem_setHandler15 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem15 :: (Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QitemChange_h (QGraphicsPathItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsPathItem_itemChange" qtc_QGraphicsPathItem_itemChange :: Ptr (TQGraphicsPathItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsPathItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsPathItem ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_keyPressEvent" qtc_QGraphicsPathItem_keyPressEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsPathItemSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsPathItem ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_keyReleaseEvent" qtc_QGraphicsPathItem_keyReleaseEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsPathItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mouseDoubleClickEvent" qtc_QGraphicsPathItem_mouseDoubleClickEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mouseMoveEvent" qtc_QGraphicsPathItem_mouseMoveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mousePressEvent" qtc_QGraphicsPathItem_mousePressEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mouseReleaseEvent" qtc_QGraphicsPathItem_mouseReleaseEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler16" qtc_QGraphicsPathItem_setHandler16 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem16 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsceneEvent_h (QGraphicsPathItem ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_sceneEvent" qtc_QGraphicsPathItem_sceneEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsPathItemSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler17" qtc_QGraphicsPathItem_setHandler17 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem17 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPathItem_setHandler18" qtc_QGraphicsPathItem_setHandler18 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem18 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsceneEventFilter_h (QGraphicsPathItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsPathItem_sceneEventFilter" qtc_QGraphicsPathItem_sceneEventFilter :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsPathItemSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem" qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance QwheelEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_wheelEvent" qtc_QGraphicsPathItem_wheelEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_wheelEvent cobj_x0 cobj_x1
|
keera-studios/hsQt
|
Qtc/Gui/QGraphicsPathItem_h.hs
|
Haskell
|
bsd-2-clause
| 98,043
|
module Frontend.Val(Val(..),
TVal(TVal),
WithVal(..)) where
import qualified Data.Map as M
import Name
import Frontend.NS
import Frontend.Expr
import Frontend.Type
-- Value
data Val = BoolVal Bool
| IntVal Integer
| StructVal (M.Map Ident TVal)
| EnumVal Ident
| PtrVal LExpr
-- | ArrayVal [TVal]
| NondetVal
class WithVal a where
val :: a -> Val
data TVal = TVal {ttyp::Type, tval::Val}
instance WithType TVal where
typ = ttyp
instance WithVal TVal where
val = tval
-- Assumed comparable types
instance Eq Val where
(==) (BoolVal b1) (BoolVal b2) = b1 == b2
(==) (IntVal i1) (IntVal i2) = i1 == i2
(==) (StructVal s1) (StructVal s2) = and $ map (uncurry (==)) (zip (map snd $ M.toList s1) (map snd $ M.toList s2))
(==) (PtrVal p1) (PtrVal p2) = error $ "Eq PtrVal not implemented"
-- (==) (ArrayVal a1) (ArrayVal a2) = and $ map (uncurry (==)) (zip a1 a2)
(==) _ _ = False
instance Eq TVal where
(==) (TVal t1 v1) (TVal t2 v2) = v1 == v2
instance Ord Val where
compare (IntVal i1) (IntVal i2) = compare i1 i2
compare _ _ = error "Incomparable values in Ord Val"
instance Ord TVal where
compare (TVal t1 v1) (TVal t2 v2) = compare v1 v2
|
termite2/tsl
|
Frontend/Val.hs
|
Haskell
|
bsd-3-clause
| 1,399
|
import Data.Foldable (foldMap, foldr)
import Data.Monoid
import Data.Maybe
newtype Min a = Min { getMin :: Maybe a } deriving (Eq, Ord, Show)
newtype Max a = Max { getMax :: Maybe a } deriving (Eq, Ord, Show)
instance Ord a => Monoid (Min a) where
mempty = Min Nothing
Min (Nothing) `mappend` y = y
x `mappend` Min (Nothing) = x
Min (Just x) `mappend` Min (Just y) = Min $ Just (min x y)
instance Ord a => Monoid (Max a) where
mempty = Max Nothing
Max (Nothing) `mappend` y = y
x `mappend` Max (Nothing) = x
Max (Just x) `mappend` Max (Just y) = Max $ Just (max x y)
sum' :: (Foldable t, Num a) => t a -> a
sum' = foldr (+) 0
sum'' :: (Foldable t, Num a) => t a -> a
sum'' = getSum . foldMap Sum
product' :: (Foldable t, Num a) => t a -> a
product' = foldr (*) 1
product'' :: (Foldable t, Num a) => t a -> a
product'' = getProduct . foldMap Product
elem' :: (Functor t, Foldable t, Eq a) => a -> t a -> Bool
elem' a = getAny . foldMap Any . fmap (== a)
elem'' :: (Foldable t, Eq a) => a -> t a -> Bool
elem'' = any . (==)
minimum' :: (Foldable t, Ord a) => t a -> Maybe a
minimum' = foldr maybeMin Nothing
where maybeMin x Nothing = Just x
maybeMin x (Just y) = Just $ min x y
-- implement with foldMap needs a helper monoid (Min a)
minimum'' :: (Monoid a, Foldable t, Ord a) => t a -> Maybe a
minimum'' = getMin . foldMap (Min . Just)
maximum' :: (Foldable t, Ord a) => t a -> Maybe a
maximum' = foldr maybeMin Nothing
where maybeMin x Nothing = Just x
maybeMin x (Just y) = Just $ max x y
-- implement with foldMap needs a helper monoid (Min a)
maximum'' :: (Monoid a, Foldable t, Ord a) => t a -> Maybe a
maximum'' = getMax . foldMap (Max . Just)
-- using foldr
null' :: (Foldable t) => t a -> Bool
null' = foldr (\_ _ -> False) True
-- using foldMap
null'' :: (Foldable t) => t a -> Bool
null'' = getAll . foldMap (All . (\_ -> False))
-- using foldr
length' :: (Foldable t) => t a -> Int
length' = foldr (\_ b -> b + 1) 0
-- using foldMap
length'' :: (Foldable t) => t a -> Int
length'' = getSum . foldMap (Sum . (\_ -> 1))
-- using foldr
toList' :: (Foldable t) => t a -> [a]
toList' = foldr (\a b -> a : b) []
-- using foldMap
toList'' :: (Foldable t) => t a -> [a]
toList'' = foldMap (\a -> [a])
-- using foldMap
fold' :: (Foldable t, Monoid m) => t m -> m
fold' = foldMap id
-- using foldr
foldMap' :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
foldMap' f = foldr (\a b -> f a <> b) mempty
|
chengzh2008/hpffp
|
src/ch20-Foldable/foldable.hs
|
Haskell
|
bsd-3-clause
| 2,460
|
{-# LANGUAGE RankNTypes #-}
{-| Generic equal temperament pitch.
Use the type-level numbers to construct an temperement dividing
the octave in any number of equal-sized steps.
Common cases such as 6, 12 and 24 are provided for convenience.
-}
module Music.Pitch.Equal
(
-- * Equal temperament
Equal,
toEqual,
fromEqual,
equalToRatio,
size,
cast,
-- ** Synonyms
Equal6,
Equal12,
Equal17,
Equal24,
Equal36,
-- ** Extra type-level naturals
N20,
N30,
N17,
N24,
N36,
)
where
import Data.Maybe
import Data.Either
import Data.Semigroup
import Data.VectorSpace
import Data.AffineSpace
import Control.Monad
import Control.Applicative
import Music.Pitch.Absolute
import TypeUnary.Nat
-- Based on Data.Fixed
newtype Equal a = Equal { getEqual :: Int }
deriving instance Eq (Equal a)
deriving instance Ord (Equal a)
instance Show (Equal a) where
show (Equal a) = show a
-- OR:
-- showsPrec d (Equal x) = showParen (d > app_prec) $
-- showString "Equal " . showsPrec (app_prec+1) x
-- where app_prec = 10
instance IsNat a => Num (Equal a) where
Equal a + Equal b = Equal (a + b)
Equal a * Equal b = Equal (a * b)
negate (Equal a) = Equal (negate a)
abs (Equal a) = Equal (abs a)
signum (Equal a) = Equal (signum a)
fromInteger = toEqual . fromIntegral
instance IsNat a => Semigroup (Equal a) where
(<>) = (+)
instance IsNat a => Monoid (Equal a) where
mempty = 0
mappend = (+)
instance IsNat a => AdditiveGroup (Equal a) where
zeroV = 0
(^+^) = (+)
negateV = negate
instance IsNat a => VectorSpace (Equal a) where
type Scalar (Equal a) = Equal a
(*^) = (*)
-- Convenience to avoid ScopedTypeVariables etc
getSize :: IsNat a => Equal a -> Nat a
getSize _ = nat
{-| Size of this type (value not evaluated).
>>> size (undefined :: Equal N2)
2
>>> size (undefined :: Equal N12)
12
-}
size :: IsNat a => Equal a -> Int
size = natToZ . getSize
-- TODO I got this part wrong
--
-- This type implements limited values (useful for interval *steps*)
-- An ET-interval is just an int, with a type-level size (divMod is "separate")
-- -- | Create an equal-temperament value.
-- toEqual :: IsNat a => Int -> Maybe (Equal a)
-- toEqual = checkSize . Equal
--
-- -- | Unsafely create an equal-temperament value.
-- unsafeToEqual :: IsNat a => Int -> Equal a
-- unsafeToEqual n = case toEqual n of
-- Nothing -> error $ "Bad equal: " ++ show n
-- Just x -> x
--
-- checkSize :: IsNat a => Equal a -> Maybe (Equal a)
-- checkSize x = if 0 <= fromEqual x && fromEqual x < size x then Just x else Nothing
--
-- | Create an equal-temperament value.
toEqual :: IsNat a => Int -> Equal a
toEqual = Equal
-- | Extract an equal-temperament value.
fromEqual :: IsNat a => Equal a -> Int
fromEqual = getEqual
{-| Convert an equal-temeperament value to a frequency ratio.
>>> equalToRatio (7 :: Equal12)
1.4983070768766815
>>> equalToRatio (4 :: Equal12)
1.2599210498948732
-}
equalToRatio :: IsNat a => Equal a -> Double
equalToRatio x = 2**(realToFrac (fromEqual x) / realToFrac (size x))
{-| Safely cast a tempered value to another size.
>>> cast (1 :: Equal12) :: Equal24
2 :: Equal24
>>> cast (8 :: Equal12) :: Equal6
4 :: Equal6
>>> (2 :: Equal12) + cast (2 :: Equal24)
3 :: Equal12
-}
cast :: (IsNat a, IsNat b) => Equal a -> Equal b
cast = cast' undefined
cast' :: (IsNat a, IsNat b) => Equal b -> Equal a -> Equal b
cast' bDummy aDummy@(Equal a) = Equal $ (a * size bDummy) `div` size aDummy
type Equal6 = Equal N6
type Equal12 = Equal N12
type Equal17 = Equal N17
type Equal24 = Equal N24
type Equal36 = Equal N36
type N20 = N10 :*: N2
type N30 = N10 :*: N3
type N17 = N10 :+: N7
type N24 = N20 :+: N4
type N36 = N30 :+: N6
|
music-suite/music-pitch
|
src/Music/Pitch/Equal.hs
|
Haskell
|
bsd-3-clause
| 3,792
|
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Data.Set.Base
-- Copyright : (c) Daan Leijen 2002
-- License : BSD-style
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- An efficient implementation of sets.
--
-- These modules are intended to be imported qualified, to avoid name
-- clashes with Prelude functions, e.g.
--
-- > import Data.Set (Set)
-- > import qualified Data.Set as Set
--
-- The implementation of 'Set' is based on /size balanced/ binary trees (or
-- trees of /bounded balance/) as described by:
--
-- * Stephen Adams, \"/Efficient sets: a balancing act/\",
-- Journal of Functional Programming 3(4):553-562, October 1993,
-- <http://www.swiss.ai.mit.edu/~adams/BB/>.
--
-- * J. Nievergelt and E.M. Reingold,
-- \"/Binary search trees of bounded balance/\",
-- SIAM journal of computing 2(1), March 1973.
--
-- Note that the implementation is /left-biased/ -- the elements of a
-- first argument are always preferred to the second, for example in
-- 'union' or 'insert'. Of course, left-biasing can only be observed
-- when equality is an equivalence relation instead of structural
-- equality.
-----------------------------------------------------------------------------
-- [Note: Using INLINABLE]
-- ~~~~~~~~~~~~~~~~~~~~~~~
-- It is crucial to the performance that the functions specialize on the Ord
-- type when possible. GHC 7.0 and higher does this by itself when it sees th
-- unfolding of a function -- that is why all public functions are marked
-- INLINABLE (that exposes the unfolding).
-- [Note: Using INLINE]
-- ~~~~~~~~~~~~~~~~~~~~
-- For other compilers and GHC pre 7.0, we mark some of the functions INLINE.
-- We mark the functions that just navigate down the tree (lookup, insert,
-- delete and similar). That navigation code gets inlined and thus specialized
-- when possible. There is a price to pay -- code growth. The code INLINED is
-- therefore only the tree navigation, all the real work (rebalancing) is not
-- INLINED by using a NOINLINE.
--
-- All methods marked INLINE have to be nonrecursive -- a 'go' function doing
-- the real work is provided.
-- [Note: Type of local 'go' function]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- If the local 'go' function uses an Ord class, it sometimes heap-allocates
-- the Ord dictionary when the 'go' function does not have explicit type.
-- In that case we give 'go' explicit type. But this slightly decrease
-- performance, as the resulting 'go' function can float out to top level.
-- [Note: Local 'go' functions and capturing]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- As opposed to IntSet, when 'go' function captures an argument, increased
-- heap-allocation can occur: sometimes in a polymorphic function, the 'go'
-- floats out of its enclosing function and then it heap-allocates the
-- dictionary and the argument. Maybe it floats out too late and strictness
-- analyzer cannot see that these could be passed on stack.
--
-- For example, change 'member' so that its local 'go' function is not passing
-- argument x and then look at the resulting code for hedgeInt.
-- [Note: Order of constructors]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The order of constructors of Set matters when considering performance.
-- Currently in GHC 7.0, when type has 2 constructors, a forward conditional
-- jump is made when successfully matching second constructor. Successful match
-- of first constructor results in the forward jump not taken.
-- On GHC 7.0, reordering constructors from Tip | Bin to Bin | Tip
-- improves the benchmark by up to 10% on x86.
module Data.Set.Base (
-- * Set type
Set(..) -- instance Eq,Ord,Show,Read,Data,Typeable
-- * Operators
, (\\)
-- * Query
, null
, size
, member
, notMember
, lookupLT
, lookupGT
, lookupLE
, lookupGE
, isSubsetOf
, isProperSubsetOf
-- * Construction
, empty
, singleton
, insert
, delete
-- * Combine
, union
, unions
, difference
, intersection
-- * Filter
, filter
, partition
, split
, splitMember
-- * Indexed
, lookupIndex
, findIndex
, elemAt
, deleteAt
-- * Map
, map
, mapMonotonic
-- * Folds
, foldr
, foldl
-- ** Strict folds
, foldr'
, foldl'
-- ** Legacy folds
, fold
-- * Min\/Max
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, maxView
, minView
-- * Conversion
-- ** List
, elems
, toList
, fromList
-- ** Ordered list
, toAscList
, toDescList
, fromAscList
, fromDistinctAscList
-- * Debugging
, showTree
, showTreeWith
, valid
-- Internals (for testing)
, bin
, balanced
, join
, merge
) where
import Prelude hiding (filter,foldl,foldr,null,map)
import qualified Data.List as List
import Data.Bits (shiftL, shiftR)
import Data.Monoid (Monoid(..))
import qualified Data.Foldable as Foldable
import Data.Typeable
import Control.DeepSeq (NFData(rnf))
import Data.StrictPair
#if __GLASGOW_HASKELL__
import GHC.Exts ( build )
import Text.Read
import Data.Data
#endif
-- Use macros to define strictness of functions.
-- STRICT_x_OF_y denotes an y-ary function strict in the x-th parameter.
-- We do not use BangPatterns, because they are not in any standard and we
-- want the compilers to be compiled by as many compilers as possible.
#define STRICT_1_OF_2(fn) fn arg _ | arg `seq` False = undefined
#define STRICT_1_OF_3(fn) fn arg _ _ | arg `seq` False = undefined
#define STRICT_2_OF_3(fn) fn _ arg _ | arg `seq` False = undefined
{--------------------------------------------------------------------
Operators
--------------------------------------------------------------------}
infixl 9 \\ --
-- | /O(n+m)/. See 'difference'.
(\\) :: Ord a => Set a -> Set a -> Set a
m1 \\ m2 = difference m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE (\\) #-}
#endif
{--------------------------------------------------------------------
Sets are size balanced trees
--------------------------------------------------------------------}
-- | A set of values @a@.
-- See Note: Order of constructors
data Set a = Bin {-# UNPACK #-} !Size !a !(Set a) !(Set a)
| Tip
type Size = Int
instance Ord a => Monoid (Set a) where
mempty = empty
mappend = union
mconcat = unions
instance Foldable.Foldable Set where
fold Tip = mempty
fold (Bin _ k l r) = Foldable.fold l `mappend` k `mappend` Foldable.fold r
foldr = foldr
foldl = foldl
foldMap _ Tip = mempty
foldMap f (Bin _ k l r) = Foldable.foldMap f l `mappend` f k `mappend` Foldable.foldMap f r
#if __GLASGOW_HASKELL__
{--------------------------------------------------------------------
A Data instance
--------------------------------------------------------------------}
-- This instance preserves data abstraction at the cost of inefficiency.
-- We provide limited reflection services for the sake of data abstraction.
instance (Data a, Ord a) => Data (Set a) where
gfoldl f z set = z fromList `f` (toList set)
toConstr _ = fromListConstr
gunfold k z c = case constrIndex c of
1 -> k (z fromList)
_ -> error "gunfold"
dataTypeOf _ = setDataType
dataCast1 f = gcast1 f
fromListConstr :: Constr
fromListConstr = mkConstr setDataType "fromList" [] Prefix
setDataType :: DataType
setDataType = mkDataType "Data.Set.Base.Set" [fromListConstr]
#endif
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(1)/. Is this the empty set?
null :: Set a -> Bool
null Tip = True
null (Bin {}) = False
{-# INLINE null #-}
-- | /O(1)/. The number of elements in the set.
size :: Set a -> Int
size Tip = 0
size (Bin sz _ _ _) = sz
{-# INLINE size #-}
-- | /O(log n)/. Is the element in the set?
member :: Ord a => a -> Set a -> Bool
member = go
where
STRICT_1_OF_2(go)
go _ Tip = False
go x (Bin _ y l r) = case compare x y of
LT -> go x l
GT -> go x r
EQ -> True
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE member #-}
#else
{-# INLINE member #-}
#endif
-- | /O(log n)/. Is the element not in the set?
notMember :: Ord a => a -> Set a -> Bool
notMember a t = not $ member a t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE notMember #-}
#else
{-# INLINE notMember #-}
#endif
-- | /O(log n)/. Find largest element smaller than the given one.
--
-- > lookupLT 3 (fromList [3, 5]) == Nothing
-- > lookupLT 5 (fromList [3, 5]) == Just 3
lookupLT :: Ord a => a -> Set a -> Maybe a
lookupLT = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) | x <= y = goNothing x l
| otherwise = goJust x y r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) | x <= y = goJust x best l
| otherwise = goJust x y r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupLT #-}
#else
{-# INLINE lookupLT #-}
#endif
-- | /O(log n)/. Find smallest element greater than the given one.
--
-- > lookupGT 4 (fromList [3, 5]) == Just 5
-- > lookupGT 5 (fromList [3, 5]) == Nothing
lookupGT :: Ord a => a -> Set a -> Maybe a
lookupGT = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) | x < y = goJust x y l
| otherwise = goNothing x r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) | x < y = goJust x y l
| otherwise = goJust x best r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupGT #-}
#else
{-# INLINE lookupGT #-}
#endif
-- | /O(log n)/. Find largest element smaller or equal to the given one.
--
-- > lookupLE 2 (fromList [3, 5]) == Nothing
-- > lookupLE 4 (fromList [3, 5]) == Just 3
-- > lookupLE 5 (fromList [3, 5]) == Just 5
lookupLE :: Ord a => a -> Set a -> Maybe a
lookupLE = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) = case compare x y of LT -> goNothing x l
EQ -> Just y
GT -> goJust x y r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) = case compare x y of LT -> goJust x best l
EQ -> Just y
GT -> goJust x y r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupLE #-}
#else
{-# INLINE lookupLE #-}
#endif
-- | /O(log n)/. Find smallest element greater or equal to the given one.
--
-- > lookupGE 3 (fromList [3, 5]) == Just 3
-- > lookupGE 4 (fromList [3, 5]) == Just 5
-- > lookupGE 6 (fromList [3, 5]) == Nothing
lookupGE :: Ord a => a -> Set a -> Maybe a
lookupGE = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) = case compare x y of LT -> goJust x y l
EQ -> Just y
GT -> goNothing x r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) = case compare x y of LT -> goJust x y l
EQ -> Just y
GT -> goJust x best r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupGE #-}
#else
{-# INLINE lookupGE #-}
#endif
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. The empty set.
empty :: Set a
empty = Tip
{-# INLINE empty #-}
-- | /O(1)/. Create a singleton set.
singleton :: a -> Set a
singleton x = Bin 1 x Tip Tip
{-# INLINE singleton #-}
{--------------------------------------------------------------------
Insertion, Deletion
--------------------------------------------------------------------}
-- | /O(log n)/. Insert an element in a set.
-- If the set already contains an element equal to the given value,
-- it is replaced with the new value.
-- See Note: Type of local 'go' function
insert :: Ord a => a -> Set a -> Set a
insert = go
where
go :: Ord a => a -> Set a -> Set a
STRICT_1_OF_2(go)
go x Tip = singleton x
go x (Bin sz y l r) = case compare x y of
LT -> balanceL y (go x l) r
GT -> balanceR y l (go x r)
EQ -> Bin sz x l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insert #-}
#else
{-# INLINE insert #-}
#endif
-- Insert an element to the set only if it is not in the set.
-- Used by `union`.
-- See Note: Type of local 'go' function
insertR :: Ord a => a -> Set a -> Set a
insertR = go
where
go :: Ord a => a -> Set a -> Set a
STRICT_1_OF_2(go)
go x Tip = singleton x
go x t@(Bin _ y l r) = case compare x y of
LT -> balanceL y (go x l) r
GT -> balanceR y l (go x r)
EQ -> t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertR #-}
#else
{-# INLINE insertR #-}
#endif
-- | /O(log n)/. Delete an element from a set.
-- See Note: Type of local 'go' function
delete :: Ord a => a -> Set a -> Set a
delete = go
where
go :: Ord a => a -> Set a -> Set a
STRICT_1_OF_2(go)
go _ Tip = Tip
go x (Bin _ y l r) = case compare x y of
LT -> balanceR y (go x l) r
GT -> balanceL y l (go x r)
EQ -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE delete #-}
#else
{-# INLINE delete #-}
#endif
{--------------------------------------------------------------------
Subset
--------------------------------------------------------------------}
-- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
isProperSubsetOf s1 s2
= (size s1 < size s2) && (isSubsetOf s1 s2)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isProperSubsetOf #-}
#endif
-- | /O(n+m)/. Is this a subset?
-- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
isSubsetOf :: Ord a => Set a -> Set a -> Bool
isSubsetOf t1 t2
= (size t1 <= size t2) && (isSubsetOfX t1 t2)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isSubsetOf #-}
#endif
isSubsetOfX :: Ord a => Set a -> Set a -> Bool
isSubsetOfX Tip _ = True
isSubsetOfX _ Tip = False
isSubsetOfX (Bin _ x l r) t
= found && isSubsetOfX l lt && isSubsetOfX r gt
where
(lt,found,gt) = splitMember x t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isSubsetOfX #-}
#endif
{--------------------------------------------------------------------
Minimal, Maximal
--------------------------------------------------------------------}
-- | /O(log n)/. The minimal element of a set.
findMin :: Set a -> a
findMin (Bin _ x Tip _) = x
findMin (Bin _ _ l _) = findMin l
findMin Tip = error "Set.findMin: empty set has no minimal element"
-- | /O(log n)/. The maximal element of a set.
findMax :: Set a -> a
findMax (Bin _ x _ Tip) = x
findMax (Bin _ _ _ r) = findMax r
findMax Tip = error "Set.findMax: empty set has no maximal element"
-- | /O(log n)/. Delete the minimal element. Returns an empty set if the set is empty.
deleteMin :: Set a -> Set a
deleteMin (Bin _ _ Tip r) = r
deleteMin (Bin _ x l r) = balanceR x (deleteMin l) r
deleteMin Tip = Tip
-- | /O(log n)/. Delete the maximal element. Returns an empty set if the set is empty.
deleteMax :: Set a -> Set a
deleteMax (Bin _ _ l Tip) = l
deleteMax (Bin _ x l r) = balanceL x l (deleteMax r)
deleteMax Tip = Tip
{--------------------------------------------------------------------
Union.
--------------------------------------------------------------------}
-- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
unions :: Ord a => [Set a] -> Set a
unions = foldlStrict union empty
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unions #-}
#endif
-- | /O(n+m)/. The union of two sets, preferring the first set when
-- equal elements are encountered.
-- The implementation uses the efficient /hedge-union/ algorithm.
union :: Ord a => Set a -> Set a -> Set a
union Tip t2 = t2
union t1 Tip = t1
union t1 t2 = hedgeUnion NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE union #-}
#endif
hedgeUnion :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
hedgeUnion _ _ t1 Tip = t1
hedgeUnion blo bhi Tip (Bin _ x l r) = join x (filterGt blo l) (filterLt bhi r)
hedgeUnion _ _ t1 (Bin _ x Tip Tip) = insertR x t1 -- According to benchmarks, this special case increases
-- performance up to 30%. It does not help in difference or intersection.
hedgeUnion blo bhi (Bin _ x l r) t2 = join x (hedgeUnion blo bmi l (trim blo bmi t2))
(hedgeUnion bmi bhi r (trim bmi bhi t2))
where bmi = JustS x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeUnion #-}
#endif
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
-- | /O(n+m)/. Difference of two sets.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
difference :: Ord a => Set a -> Set a -> Set a
difference Tip _ = Tip
difference t1 Tip = t1
difference t1 t2 = hedgeDiff NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE difference #-}
#endif
hedgeDiff :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
hedgeDiff _ _ Tip _ = Tip
hedgeDiff blo bhi (Bin _ x l r) Tip = join x (filterGt blo l) (filterLt bhi r)
hedgeDiff blo bhi t (Bin _ x l r) = merge (hedgeDiff blo bmi (trim blo bmi t) l)
(hedgeDiff bmi bhi (trim bmi bhi t) r)
where bmi = JustS x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeDiff #-}
#endif
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
-- | /O(n+m)/. The intersection of two sets. The implementation uses an
-- efficient /hedge/ algorithm comparable with /hedge-union/. Elements of the
-- result come from the first set, so for example
--
-- > import qualified Data.Set as S
-- > data AB = A | B deriving Show
-- > instance Ord AB where compare _ _ = EQ
-- > instance Eq AB where _ == _ = True
-- > main = print (S.singleton A `S.intersection` S.singleton B,
-- > S.singleton B `S.intersection` S.singleton A)
--
-- prints @(fromList [A],fromList [B])@.
intersection :: Ord a => Set a -> Set a -> Set a
intersection Tip _ = Tip
intersection _ Tip = Tip
intersection t1 t2 = hedgeInt NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersection #-}
#endif
hedgeInt :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
hedgeInt _ _ _ Tip = Tip
hedgeInt _ _ Tip _ = Tip
hedgeInt blo bhi (Bin _ x l r) t2 = let l' = hedgeInt blo bmi l (trim blo bmi t2)
r' = hedgeInt bmi bhi r (trim bmi bhi t2)
in if x `member` t2 then join x l' r' else merge l' r'
where bmi = JustS x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeInt #-}
#endif
{--------------------------------------------------------------------
Filter and partition
--------------------------------------------------------------------}
-- | /O(n)/. Filter all elements that satisfy the predicate.
filter :: (a -> Bool) -> Set a -> Set a
filter _ Tip = Tip
filter p (Bin _ x l r)
| p x = join x (filter p l) (filter p r)
| otherwise = merge (filter p l) (filter p r)
-- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
-- the predicate and one with all elements that don't satisfy the predicate.
-- See also 'split'.
partition :: (a -> Bool) -> Set a -> (Set a,Set a)
partition p0 t0 = toPair $ go p0 t0
where
go _ Tip = (Tip :*: Tip)
go p (Bin _ x l r) = case (go p l, go p r) of
((l1 :*: l2), (r1 :*: r2))
| p x -> join x l1 r1 :*: merge l2 r2
| otherwise -> merge l1 r1 :*: join x l2 r2
{----------------------------------------------------------------------
Map
----------------------------------------------------------------------}
-- | /O(n*log n)/.
-- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
--
-- It's worth noting that the size of the result may be smaller if,
-- for some @(x,y)@, @x \/= y && f x == f y@
map :: Ord b => (a->b) -> Set a -> Set b
map f = fromList . List.map f . toList
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE map #-}
#endif
-- | /O(n)/. The
--
-- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
-- /The precondition is not checked./
-- Semi-formally, we have:
--
-- > and [x < y ==> f x < f y | x <- ls, y <- ls]
-- > ==> mapMonotonic f s == map f s
-- > where ls = toList s
mapMonotonic :: (a->b) -> Set a -> Set b
mapMonotonic _ Tip = Tip
mapMonotonic f (Bin sz x l r) = Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
{--------------------------------------------------------------------
Fold
--------------------------------------------------------------------}
-- | /O(n)/. Fold the elements in the set using the given right-associative
-- binary operator. This function is an equivalent of 'foldr' and is present
-- for compatibility only.
--
-- /Please note that fold will be deprecated in the future and removed./
fold :: (a -> b -> b) -> b -> Set a -> b
fold = foldr
{-# INLINE fold #-}
-- | /O(n)/. Fold the elements in the set using the given right-associative
-- binary operator, such that @'foldr' f z == 'Prelude.foldr' f z . 'toAscList'@.
--
-- For example,
--
-- > toAscList set = foldr (:) [] set
foldr :: (a -> b -> b) -> b -> Set a -> b
foldr f z = go z
where
go z' Tip = z'
go z' (Bin _ x l r) = go (f x (go z' r)) l
{-# INLINE foldr #-}
-- | /O(n)/. A strict version of 'foldr'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldr' :: (a -> b -> b) -> b -> Set a -> b
foldr' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ x l r) = go (f x (go z' r)) l
{-# INLINE foldr' #-}
-- | /O(n)/. Fold the elements in the set using the given left-associative
-- binary operator, such that @'foldl' f z == 'Prelude.foldl' f z . 'toAscList'@.
--
-- For example,
--
-- > toDescList set = foldl (flip (:)) [] set
foldl :: (a -> b -> a) -> a -> Set b -> a
foldl f z = go z
where
go z' Tip = z'
go z' (Bin _ x l r) = go (f (go z' l) x) r
{-# INLINE foldl #-}
-- | /O(n)/. A strict version of 'foldl'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldl' :: (a -> b -> a) -> a -> Set b -> a
foldl' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ x l r) = go (f (go z' l) x) r
{-# INLINE foldl' #-}
{--------------------------------------------------------------------
List variations
--------------------------------------------------------------------}
-- | /O(n)/. An alias of 'toAscList'. The elements of a set in ascending order.
-- Subject to list fusion.
elems :: Set a -> [a]
elems = toAscList
{--------------------------------------------------------------------
Lists
--------------------------------------------------------------------}
-- | /O(n)/. Convert the set to a list of elements. Subject to list fusion.
toList :: Set a -> [a]
toList = toAscList
-- | /O(n)/. Convert the set to an ascending list of elements. Subject to list fusion.
toAscList :: Set a -> [a]
toAscList = foldr (:) []
-- | /O(n)/. Convert the set to a descending list of elements. Subject to list
-- fusion.
toDescList :: Set a -> [a]
toDescList = foldl (flip (:)) []
-- List fusion for the list generating functions.
#if __GLASGOW_HASKELL__
-- The foldrFB and foldlFB are foldr and foldl equivalents, used for list fusion.
-- They are important to convert unfused to{Asc,Desc}List back, see mapFB in prelude.
foldrFB :: (a -> b -> b) -> b -> Set a -> b
foldrFB = foldr
{-# INLINE[0] foldrFB #-}
foldlFB :: (a -> b -> a) -> a -> Set b -> a
foldlFB = foldl
{-# INLINE[0] foldlFB #-}
-- Inline elems and toList, so that we need to fuse only toAscList.
{-# INLINE elems #-}
{-# INLINE toList #-}
-- The fusion is enabled up to phase 2 included. If it does not succeed,
-- convert in phase 1 the expanded to{Asc,Desc}List calls back to
-- to{Asc,Desc}List. In phase 0, we inline fold{lr}FB (which were used in
-- a list fusion, otherwise it would go away in phase 1), and let compiler do
-- whatever it wants with to{Asc,Desc}List -- it was forbidden to inline it
-- before phase 0, otherwise the fusion rules would not fire at all.
{-# NOINLINE[0] toAscList #-}
{-# NOINLINE[0] toDescList #-}
{-# RULES "Set.toAscList" [~1] forall s . toAscList s = build (\c n -> foldrFB c n s) #-}
{-# RULES "Set.toAscListBack" [1] foldrFB (:) [] = toAscList #-}
{-# RULES "Set.toDescList" [~1] forall s . toDescList s = build (\c n -> foldlFB (\xs x -> c x xs) n s) #-}
{-# RULES "Set.toDescListBack" [1] foldlFB (\xs x -> x : xs) [] = toDescList #-}
#endif
-- | /O(n*log n)/. Create a set from a list of elements.
--
-- If the elemens are ordered, linear-time implementation is used,
-- with the performance equal to 'fromDistinctAscList'.
-- For some reason, when 'singleton' is used in fromList or in
-- create, it is not inlined, so we inline it manually.
fromList :: Ord a => [a] -> Set a
fromList [] = Tip
fromList [x] = Bin 1 x Tip Tip
fromList (x0 : xs0) | not_ordered x0 xs0 = fromList' (Bin 1 x0 Tip Tip) xs0
| otherwise = go (1::Int) (Bin 1 x0 Tip Tip) xs0
where
not_ordered _ [] = False
not_ordered x (y : _) = x >= y
{-# INLINE not_ordered #-}
fromList' t0 xs = foldlStrict ins t0 xs
where ins t x = insert x t
STRICT_1_OF_3(go)
go _ t [] = t
go _ t [x] = insertMax x t
go s l xs@(x : xss) | not_ordered x xss = fromList' l xs
| otherwise = case create s xss of
(r, ys, []) -> go (s `shiftL` 1) (join x l r) ys
(r, _, ys) -> fromList' (join x l r) ys
-- The create is returning a triple (tree, xs, ys). Both xs and ys
-- represent not yet processed elements and only one of them can be nonempty.
-- If ys is nonempty, the keys in ys are not ordered with respect to tree
-- and must be inserted using fromList'. Otherwise the keys have been
-- ordered so far.
STRICT_1_OF_2(create)
create _ [] = (Tip, [], [])
create s xs@(x : xss)
| s == 1 = if not_ordered x xss then (Bin 1 x Tip Tip, [], xss)
else (Bin 1 x Tip Tip, xss, [])
| otherwise = case create (s `shiftR` 1) xs of
res@(_, [], _) -> res
(l, [y], zs) -> (insertMax y l, [], zs)
(l, ys@(y:yss), _) | not_ordered y yss -> (l, [], ys)
| otherwise -> case create (s `shiftR` 1) yss of
(r, zs, ws) -> (join y l r, zs, ws)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromList #-}
#endif
{--------------------------------------------------------------------
Building trees from ascending/descending lists can be done in linear time.
Note that if [xs] is ascending that:
fromAscList xs == fromList xs
--------------------------------------------------------------------}
-- | /O(n)/. Build a set from an ascending list in linear time.
-- /The precondition (input list is ascending) is not checked./
fromAscList :: Eq a => [a] -> Set a
fromAscList xs
= fromDistinctAscList (combineEq xs)
where
-- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
combineEq xs'
= case xs' of
[] -> []
[x] -> [x]
(x:xx) -> combineEq' x xx
combineEq' z [] = [z]
combineEq' z (x:xs')
| z==x = combineEq' z xs'
| otherwise = z:combineEq' x xs'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscList #-}
#endif
-- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
-- /The precondition (input list is strictly ascending) is not checked./
-- For some reason, when 'singleton' is used in fromDistinctAscList or in
-- create, it is not inlined, so we inline it manually.
fromDistinctAscList :: [a] -> Set a
fromDistinctAscList [] = Tip
fromDistinctAscList (x0 : xs0) = go (1::Int) (Bin 1 x0 Tip Tip) xs0
where
STRICT_1_OF_3(go)
go _ t [] = t
go s l (x : xs) = case create s xs of
(r, ys) -> go (s `shiftL` 1) (join x l r) ys
STRICT_1_OF_2(create)
create _ [] = (Tip, [])
create s xs@(x : xs')
| s == 1 = (Bin 1 x Tip Tip, xs')
| otherwise = case create (s `shiftR` 1) xs of
res@(_, []) -> res
(l, y:ys) -> case create (s `shiftR` 1) ys of
(r, zs) -> (join y l r, zs)
{--------------------------------------------------------------------
Eq converts the set to a list. In a lazy setting, this
actually seems one of the faster methods to compare two trees
and it is certainly the simplest :-)
--------------------------------------------------------------------}
instance Eq a => Eq (Set a) where
t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
{--------------------------------------------------------------------
Ord
--------------------------------------------------------------------}
instance Ord a => Ord (Set a) where
compare s1 s2 = compare (toAscList s1) (toAscList s2)
{--------------------------------------------------------------------
Show
--------------------------------------------------------------------}
instance Show a => Show (Set a) where
showsPrec p xs = showParen (p > 10) $
showString "fromList " . shows (toList xs)
{--------------------------------------------------------------------
Read
--------------------------------------------------------------------}
instance (Read a, Ord a) => Read (Set a) where
#ifdef __GLASGOW_HASKELL__
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
#else
readsPrec p = readParen (p > 10) $ \ r -> do
("fromList",s) <- lex r
(xs,t) <- reads s
return (fromList xs,t)
#endif
{--------------------------------------------------------------------
Typeable/Data
--------------------------------------------------------------------}
#include "Typeable.h"
INSTANCE_TYPEABLE1(Set,setTc,"Set")
{--------------------------------------------------------------------
NFData
--------------------------------------------------------------------}
instance NFData a => NFData (Set a) where
rnf Tip = ()
rnf (Bin _ y l r) = rnf y `seq` rnf l `seq` rnf r
{--------------------------------------------------------------------
Utility functions that return sub-ranges of the original
tree. Some functions take a `Maybe value` as an argument to
allow comparisons against infinite values. These are called `blow`
(Nothing is -\infty) and `bhigh` (here Nothing is +\infty).
We use MaybeS value, which is a Maybe strict in the Just case.
[trim blow bhigh t] A tree that is either empty or where [x > blow]
and [x < bhigh] for the value [x] of the root.
[filterGt blow t] A tree where for all values [k]. [k > blow]
[filterLt bhigh t] A tree where for all values [k]. [k < bhigh]
[split k t] Returns two trees [l] and [r] where all values
in [l] are <[k] and all keys in [r] are >[k].
[splitMember k t] Just like [split] but also returns whether [k]
was found in the tree.
--------------------------------------------------------------------}
data MaybeS a = NothingS | JustS !a
{--------------------------------------------------------------------
[trim blo bhi t] trims away all subtrees that surely contain no
values between the range [blo] to [bhi]. The returned tree is either
empty or the key of the root is between @blo@ and @bhi@.
--------------------------------------------------------------------}
trim :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a
trim NothingS NothingS t = t
trim (JustS lx) NothingS t = greater lx t where greater lo (Bin _ x _ r) | x <= lo = greater lo r
greater _ t' = t'
trim NothingS (JustS hx) t = lesser hx t where lesser hi (Bin _ x l _) | x >= hi = lesser hi l
lesser _ t' = t'
trim (JustS lx) (JustS hx) t = middle lx hx t where middle lo hi (Bin _ x _ r) | x <= lo = middle lo hi r
middle lo hi (Bin _ x l _) | x >= hi = middle lo hi l
middle _ _ t' = t'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE trim #-}
#endif
{--------------------------------------------------------------------
[filterGt b t] filter all values >[b] from tree [t]
[filterLt b t] filter all values <[b] from tree [t]
--------------------------------------------------------------------}
filterGt :: Ord a => MaybeS a -> Set a -> Set a
filterGt NothingS t = t
filterGt (JustS b) t = filter' b t
where filter' _ Tip = Tip
filter' b' (Bin _ x l r) =
case compare b' x of LT -> join x (filter' b' l) r
EQ -> r
GT -> filter' b' r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE filterGt #-}
#endif
filterLt :: Ord a => MaybeS a -> Set a -> Set a
filterLt NothingS t = t
filterLt (JustS b) t = filter' b t
where filter' _ Tip = Tip
filter' b' (Bin _ x l r) =
case compare x b' of LT -> join x l (filter' b' r)
EQ -> l
GT -> filter' b' l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE filterLt #-}
#endif
{--------------------------------------------------------------------
Split
--------------------------------------------------------------------}
-- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
-- where @set1@ comprises the elements of @set@ less than @x@ and @set2@
-- comprises the elements of @set@ greater than @x@.
split :: Ord a => a -> Set a -> (Set a,Set a)
split x0 t0 = toPair $ go x0 t0
where
go _ Tip = (Tip :*: Tip)
go x (Bin _ y l r)
= case compare x y of
LT -> let (lt :*: gt) = go x l in (lt :*: join y gt r)
GT -> let (lt :*: gt) = go x r in (join y l lt :*: gt)
EQ -> (l :*: r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE split #-}
#endif
-- | /O(log n)/. Performs a 'split' but also returns whether the pivot
-- element was found in the original set.
splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
splitMember _ Tip = (Tip, False, Tip)
splitMember x (Bin _ y l r)
= case compare x y of
LT -> let (lt, found, gt) = splitMember x l
gt' = join y gt r
in gt' `seq` (lt, found, gt')
GT -> let (lt, found, gt) = splitMember x r
lt' = join y l lt
in lt' `seq` (lt', found, gt)
EQ -> (l, True, r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE splitMember #-}
#endif
{--------------------------------------------------------------------
Indexing
--------------------------------------------------------------------}
-- | /O(log n)/. Return the /index/ of an element, which is its zero-based
-- index in the sorted sequence of elements. The index is a number from /0/ up
-- to, but not including, the 'size' of the set. Calls 'error' when the element
-- is not a 'member' of the set.
--
-- > findIndex 2 (fromList [5,3]) Error: element is not in the set
-- > findIndex 3 (fromList [5,3]) == 0
-- > findIndex 5 (fromList [5,3]) == 1
-- > findIndex 6 (fromList [5,3]) Error: element is not in the set
-- See Note: Type of local 'go' function
findIndex :: Ord a => a -> Set a -> Int
findIndex = go 0
where
go :: Ord a => Int -> a -> Set a -> Int
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go _ _ Tip = error "Set.findIndex: element is not in the set"
go idx x (Bin _ kx l r) = case compare x kx of
LT -> go idx x l
GT -> go (idx + size l + 1) x r
EQ -> idx + size l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE findIndex #-}
#endif
-- | /O(log n)/. Lookup the /index/ of an element, which is its zero-based index in
-- the sorted sequence of elements. The index is a number from /0/ up to, but not
-- including, the 'size' of the set.
--
-- > isJust (lookupIndex 2 (fromList [5,3])) == False
-- > fromJust (lookupIndex 3 (fromList [5,3])) == 0
-- > fromJust (lookupIndex 5 (fromList [5,3])) == 1
-- > isJust (lookupIndex 6 (fromList [5,3])) == False
-- See Note: Type of local 'go' function
lookupIndex :: Ord a => a -> Set a -> Maybe Int
lookupIndex = go 0
where
go :: Ord a => Int -> a -> Set a -> Maybe Int
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go _ _ Tip = Nothing
go idx x (Bin _ kx l r) = case compare x kx of
LT -> go idx x l
GT -> go (idx + size l + 1) x r
EQ -> Just $! idx + size l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupIndex #-}
#endif
-- | /O(log n)/. Retrieve an element by its /index/, i.e. by its zero-based
-- index in the sorted sequence of elements. If the /index/ is out of range (less
-- than zero, greater or equal to 'size' of the set), 'error' is called.
--
-- > elemAt 0 (fromList [5,3]) == 3
-- > elemAt 1 (fromList [5,3]) == 5
-- > elemAt 2 (fromList [5,3]) Error: index out of range
elemAt :: Int -> Set a -> a
STRICT_1_OF_2(elemAt)
elemAt _ Tip = error "Set.elemAt: index out of range"
elemAt i (Bin _ x l r)
= case compare i sizeL of
LT -> elemAt i l
GT -> elemAt (i-sizeL-1) r
EQ -> x
where
sizeL = size l
-- | /O(log n)/. Delete the element at /index/, i.e. by its zero-based index in
-- the sorted sequence of elements. If the /index/ is out of range (less than zero,
-- greater or equal to 'size' of the set), 'error' is called.
--
-- > deleteAt 0 (fromList [5,3]) == singleton 5
-- > deleteAt 1 (fromList [5,3]) == singleton 3
-- > deleteAt 2 (fromList [5,3]) Error: index out of range
-- > deleteAt (-1) (fromList [5,3]) Error: index out of range
deleteAt :: Int -> Set a -> Set a
deleteAt i t = i `seq`
case t of
Tip -> error "Set.deleteAt: index out of range"
Bin _ x l r -> case compare i sizeL of
LT -> balanceR x (deleteAt i l) r
GT -> balanceL x l (deleteAt (i-sizeL-1) r)
EQ -> glue l r
where
sizeL = size l
{--------------------------------------------------------------------
Utility functions that maintain the balance properties of the tree.
All constructors assume that all values in [l] < [x] and all values
in [r] > [x], and that [l] and [r] are valid trees.
In order of sophistication:
[Bin sz x l r] The type constructor.
[bin x l r] Maintains the correct size, assumes that both [l]
and [r] are balanced with respect to each other.
[balance x l r] Restores the balance and size.
Assumes that the original tree was balanced and
that [l] or [r] has changed by at most one element.
[join x l r] Restores balance and size.
Furthermore, we can construct a new tree from two trees. Both operations
assume that all values in [l] < all values in [r] and that [l] and [r]
are valid:
[glue l r] Glues [l] and [r] together. Assumes that [l] and
[r] are already balanced with respect to each other.
[merge l r] Merges two trees and restores balance.
Note: in contrast to Adam's paper, we use (<=) comparisons instead
of (<) comparisons in [join], [merge] and [balance].
Quickcheck (on [difference]) showed that this was necessary in order
to maintain the invariants. It is quite unsatisfactory that I haven't
been able to find out why this is actually the case! Fortunately, it
doesn't hurt to be a bit more conservative.
--------------------------------------------------------------------}
{--------------------------------------------------------------------
Join
--------------------------------------------------------------------}
join :: a -> Set a -> Set a -> Set a
join x Tip r = insertMin x r
join x l Tip = insertMax x l
join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
| delta*sizeL < sizeR = balanceL z (join x l lz) rz
| delta*sizeR < sizeL = balanceR y ly (join x ry r)
| otherwise = bin x l r
-- insertMin and insertMax don't perform potentially expensive comparisons.
insertMax,insertMin :: a -> Set a -> Set a
insertMax x t
= case t of
Tip -> singleton x
Bin _ y l r
-> balanceR y l (insertMax x r)
insertMin x t
= case t of
Tip -> singleton x
Bin _ y l r
-> balanceL y (insertMin x l) r
{--------------------------------------------------------------------
[merge l r]: merges two trees.
--------------------------------------------------------------------}
merge :: Set a -> Set a -> Set a
merge Tip r = r
merge l Tip = l
merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
| delta*sizeL < sizeR = balanceL y (merge l ly) ry
| delta*sizeR < sizeL = balanceR x lx (merge rx r)
| otherwise = glue l r
{--------------------------------------------------------------------
[glue l r]: glues two trees together.
Assumes that [l] and [r] are already balanced with respect to each other.
--------------------------------------------------------------------}
glue :: Set a -> Set a -> Set a
glue Tip r = r
glue l Tip = l
glue l r
| size l > size r = let (m,l') = deleteFindMax l in balanceR m l' r
| otherwise = let (m,r') = deleteFindMin r in balanceL m l r'
-- | /O(log n)/. Delete and find the minimal element.
--
-- > deleteFindMin set = (findMin set, deleteMin set)
deleteFindMin :: Set a -> (a,Set a)
deleteFindMin t
= case t of
Bin _ x Tip r -> (x,r)
Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balanceR x l' r)
Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
-- | /O(log n)/. Delete and find the maximal element.
--
-- > deleteFindMax set = (findMax set, deleteMax set)
deleteFindMax :: Set a -> (a,Set a)
deleteFindMax t
= case t of
Bin _ x l Tip -> (x,l)
Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balanceL x l r')
Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
-- | /O(log n)/. Retrieves the minimal key of the set, and the set
-- stripped of that element, or 'Nothing' if passed an empty set.
minView :: Set a -> Maybe (a, Set a)
minView Tip = Nothing
minView x = Just (deleteFindMin x)
-- | /O(log n)/. Retrieves the maximal key of the set, and the set
-- stripped of that element, or 'Nothing' if passed an empty set.
maxView :: Set a -> Maybe (a, Set a)
maxView Tip = Nothing
maxView x = Just (deleteFindMax x)
{--------------------------------------------------------------------
[balance x l r] balances two trees with value x.
The sizes of the trees should balance after decreasing the
size of one of them. (a rotation).
[delta] is the maximal relative difference between the sizes of
two trees, it corresponds with the [w] in Adams' paper.
[ratio] is the ratio between an outer and inner sibling of the
heavier subtree in an unbalanced setting. It determines
whether a double or single rotation should be performed
to restore balance. It is correspondes with the inverse
of $\alpha$ in Adam's article.
Note that according to the Adam's paper:
- [delta] should be larger than 4.646 with a [ratio] of 2.
- [delta] should be larger than 3.745 with a [ratio] of 1.534.
But the Adam's paper is errorneous:
- it can be proved that for delta=2 and delta>=5 there does
not exist any ratio that would work
- delta=4.5 and ratio=2 does not work
That leaves two reasonable variants, delta=3 and delta=4,
both with ratio=2.
- A lower [delta] leads to a more 'perfectly' balanced tree.
- A higher [delta] performs less rebalancing.
In the benchmarks, delta=3 is faster on insert operations,
and delta=4 has slightly better deletes. As the insert speedup
is larger, we currently use delta=3.
--------------------------------------------------------------------}
delta,ratio :: Int
delta = 3
ratio = 2
-- The balance function is equivalent to the following:
--
-- balance :: a -> Set a -> Set a -> Set a
-- balance x l r
-- | sizeL + sizeR <= 1 = Bin sizeX x l r
-- | sizeR > delta*sizeL = rotateL x l r
-- | sizeL > delta*sizeR = rotateR x l r
-- | otherwise = Bin sizeX x l r
-- where
-- sizeL = size l
-- sizeR = size r
-- sizeX = sizeL + sizeR + 1
--
-- rotateL :: a -> Set a -> Set a -> Set a
-- rotateL x l r@(Bin _ _ ly ry) | size ly < ratio*size ry = singleL x l r
-- | otherwise = doubleL x l r
-- rotateR :: a -> Set a -> Set a -> Set a
-- rotateR x l@(Bin _ _ ly ry) r | size ry < ratio*size ly = singleR x l r
-- | otherwise = doubleR x l r
--
-- singleL, singleR :: a -> Set a -> Set a -> Set a
-- singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
-- singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
--
-- doubleL, doubleR :: a -> Set a -> Set a -> Set a
-- doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
-- doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
--
-- It is only written in such a way that every node is pattern-matched only once.
--
-- Only balanceL and balanceR are needed at the moment, so balance is not here anymore.
-- In case it is needed, it can be found in Data.Map.
-- Functions balanceL and balanceR are specialised versions of balance.
-- balanceL only checks whether the left subtree is too big,
-- balanceR only checks whether the right subtree is too big.
-- balanceL is called when left subtree might have been inserted to or when
-- right subtree might have been deleted from.
balanceL :: a -> Set a -> Set a -> Set a
balanceL x l r = case r of
Tip -> case l of
Tip -> Bin 1 x Tip Tip
(Bin _ _ Tip Tip) -> Bin 2 x l Tip
(Bin _ lx Tip (Bin _ lrx _ _)) -> Bin 3 lrx (Bin 1 lx Tip Tip) (Bin 1 x Tip Tip)
(Bin _ lx ll@(Bin _ _ _ _) Tip) -> Bin 3 lx ll (Bin 1 x Tip Tip)
(Bin ls lx ll@(Bin lls _ _ _) lr@(Bin lrs lrx lrl lrr))
| lrs < ratio*lls -> Bin (1+ls) lx ll (Bin (1+lrs) x lr Tip)
| otherwise -> Bin (1+ls) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+size lrr) x lrr Tip)
(Bin rs _ _ _) -> case l of
Tip -> Bin (1+rs) x Tip r
(Bin ls lx ll lr)
| ls > delta*rs -> case (ll, lr) of
(Bin lls _ _ _, Bin lrs lrx lrl lrr)
| lrs < ratio*lls -> Bin (1+ls+rs) lx ll (Bin (1+rs+lrs) x lr r)
| otherwise -> Bin (1+ls+rs) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+rs+size lrr) x lrr r)
(_, _) -> error "Failure in Data.Map.balanceL"
| otherwise -> Bin (1+ls+rs) x l r
{-# NOINLINE balanceL #-}
-- balanceR is called when right subtree might have been inserted to or when
-- left subtree might have been deleted from.
balanceR :: a -> Set a -> Set a -> Set a
balanceR x l r = case l of
Tip -> case r of
Tip -> Bin 1 x Tip Tip
(Bin _ _ Tip Tip) -> Bin 2 x Tip r
(Bin _ rx Tip rr@(Bin _ _ _ _)) -> Bin 3 rx (Bin 1 x Tip Tip) rr
(Bin _ rx (Bin _ rlx _ _) Tip) -> Bin 3 rlx (Bin 1 x Tip Tip) (Bin 1 rx Tip Tip)
(Bin rs rx rl@(Bin rls rlx rll rlr) rr@(Bin rrs _ _ _))
| rls < ratio*rrs -> Bin (1+rs) rx (Bin (1+rls) x Tip rl) rr
| otherwise -> Bin (1+rs) rlx (Bin (1+size rll) x Tip rll) (Bin (1+rrs+size rlr) rx rlr rr)
(Bin ls _ _ _) -> case r of
Tip -> Bin (1+ls) x l Tip
(Bin rs rx rl rr)
| rs > delta*ls -> case (rl, rr) of
(Bin rls rlx rll rlr, Bin rrs _ _ _)
| rls < ratio*rrs -> Bin (1+ls+rs) rx (Bin (1+ls+rls) x l rl) rr
| otherwise -> Bin (1+ls+rs) rlx (Bin (1+ls+size rll) x l rll) (Bin (1+rrs+size rlr) rx rlr rr)
(_, _) -> error "Failure in Data.Map.balanceR"
| otherwise -> Bin (1+ls+rs) x l r
{-# NOINLINE balanceR #-}
{--------------------------------------------------------------------
The bin constructor maintains the size of the tree
--------------------------------------------------------------------}
bin :: a -> Set a -> Set a -> Set a
bin x l r
= Bin (size l + size r + 1) x l r
{-# INLINE bin #-}
{--------------------------------------------------------------------
Utilities
--------------------------------------------------------------------}
foldlStrict :: (a -> b -> a) -> a -> [b] -> a
foldlStrict f = go
where
go z [] = z
go z (x:xs) = let z' = f z x in z' `seq` go z' xs
{-# INLINE foldlStrict #-}
{--------------------------------------------------------------------
Debugging
--------------------------------------------------------------------}
-- | /O(n)/. Show the tree that implements the set. The tree is shown
-- in a compressed, hanging format.
showTree :: Show a => Set a -> String
showTree s
= showTreeWith True False s
{- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
the tree that implements the set. If @hang@ is
@True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
@wide@ is 'True', an extra wide version is shown.
> Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
> 4
> +--2
> | +--1
> | +--3
> +--5
>
> Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
> 4
> |
> +--2
> | |
> | +--1
> | |
> | +--3
> |
> +--5
>
> Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
> +--5
> |
> 4
> |
> | +--3
> | |
> +--2
> |
> +--1
-}
showTreeWith :: Show a => Bool -> Bool -> Set a -> String
showTreeWith hang wide t
| hang = (showsTreeHang wide [] t) ""
| otherwise = (showsTree wide [] [] t) ""
showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
showsTree wide lbars rbars t
= case t of
Tip -> showsBars lbars . showString "|\n"
Bin _ x Tip Tip
-> showsBars lbars . shows x . showString "\n"
Bin _ x l r
-> showsTree wide (withBar rbars) (withEmpty rbars) r .
showWide wide rbars .
showsBars lbars . shows x . showString "\n" .
showWide wide lbars .
showsTree wide (withEmpty lbars) (withBar lbars) l
showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
showsTreeHang wide bars t
= case t of
Tip -> showsBars bars . showString "|\n"
Bin _ x Tip Tip
-> showsBars bars . shows x . showString "\n"
Bin _ x l r
-> showsBars bars . shows x . showString "\n" .
showWide wide bars .
showsTreeHang wide (withBar bars) l .
showWide wide bars .
showsTreeHang wide (withEmpty bars) r
showWide :: Bool -> [String] -> String -> String
showWide wide bars
| wide = showString (concat (reverse bars)) . showString "|\n"
| otherwise = id
showsBars :: [String] -> ShowS
showsBars bars
= case bars of
[] -> id
_ -> showString (concat (reverse (tail bars))) . showString node
node :: String
node = "+--"
withBar, withEmpty :: [String] -> [String]
withBar bars = "| ":bars
withEmpty bars = " ":bars
{--------------------------------------------------------------------
Assertions
--------------------------------------------------------------------}
-- | /O(n)/. Test if the internal set structure is valid.
valid :: Ord a => Set a -> Bool
valid t
= balanced t && ordered t && validsize t
ordered :: Ord a => Set a -> Bool
ordered t
= bounded (const True) (const True) t
where
bounded lo hi t'
= case t' of
Tip -> True
Bin _ x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
balanced :: Set a -> Bool
balanced t
= case t of
Tip -> True
Bin _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
balanced l && balanced r
validsize :: Set a -> Bool
validsize t
= (realsize t == Just (size t))
where
realsize t'
= case t' of
Tip -> Just 0
Bin sz _ l r -> case (realsize l,realsize r) of
(Just n,Just m) | n+m+1 == sz -> Just sz
_ -> Nothing
|
ekmett/containers
|
Data/Set/Base.hs
|
Haskell
|
bsd-3-clause
| 54,658
|
{-# OPTIONS_GHC -F -pgmF inch #-}
{-# LANGUAGE RankNTypes, GADTs, KindSignatures, ScopedTypeVariables,
NPlusKPatterns #-}
module MergeSort where
import Vectors
comp f g x = f (g x)
data DTree :: * -> Integer -> * where
Empty :: DTree a 0
Leaf :: a -> DTree a 1
Even :: forall a (n :: Integer) . 1 <= n =>
DTree a n -> DTree a n -> DTree a (2*n)
Odd :: forall a (n :: Integer) . 1 <= n =>
DTree a (n+1) -> DTree a n -> DTree a (2*n+1)
deriving Show
insert :: forall a (n :: Integer) . a -> DTree a n -> DTree a (n+1)
insert i Empty = Leaf i
insert i (Leaf j) = Even (Leaf i) (Leaf j)
insert i (Even l r) = Odd (insert i l) r
insert i (Odd l r) = Even l (insert i r)
merge :: forall (m n :: Integer) .
Vec Integer m -> Vec Integer n -> Vec Integer (m+n)
merge VNil ys = ys
merge xs VNil = xs
merge (VCons x xs) (VCons y ys) | (<=) x y = VCons x (merge xs (VCons y ys))
| otherwise = VCons y (merge (VCons x xs) ys)
build = vifold Empty insert
flatten :: forall (n :: Integer) . DTree Integer n -> Vec Integer n
flatten Empty = VNil
flatten (Leaf i) = VCons i VNil
flatten (Even l r) = merge (flatten l) (flatten r)
flatten (Odd l r) = merge (flatten l) (flatten r)
sort = comp flatten build
data OVec :: Integer -> Integer -> Integer -> * where
ONil :: forall (l u :: Integer) . l <= u => OVec 0 l u
OCons :: forall (n l u :: Integer) . pi (x :: Integer) . l <= x =>
OVec n x u -> OVec (n+1) l u
deriving Show
ltCompare :: forall a. pi (x y :: Integer) . (x <= y => a) -> (x > y => a) -> a
ltCompare {x} {y} l g | {x <= y} = l
ltCompare {x} {y} l g | {x > y} = g
omerge :: forall (m n l u :: Integer) . OVec m l u -> OVec n l u -> OVec (m+n) l u
omerge ONil ys = ys
omerge xs ONil = xs
omerge (OCons {x} xs) (OCons {y} ys)
= ltCompare {x} {y} (OCons {x} (omerge xs (OCons {y} ys)))
(OCons {y} (omerge (OCons {x} xs) ys))
data In :: Integer -> Integer -> * where
In :: forall (l u :: Integer) . pi (x :: Integer) . (l <= x, x <= u) => In l u
deriving Show
oflatten :: forall (n l u :: Integer) . l <= u => DTree (In l u) n -> OVec n l u
oflatten Empty = ONil
oflatten (Leaf (In {i})) = OCons {i} ONil
oflatten (Even l r) = omerge (oflatten l) (oflatten r)
oflatten (Odd l r) = omerge (oflatten l) (oflatten r)
osort = comp oflatten build
|
adamgundry/inch
|
examples/MergeSort.hs
|
Haskell
|
bsd-3-clause
| 2,457
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module GithubWebhook.Types.Events.PushEvent
( PushEvent(..)
) where
import qualified Data.Text as T
import qualified Data.Aeson as A
import qualified Data.Aeson.TH as A
import qualified GithubWebhook.Types.SmallUser as SmallUser
import qualified GithubWebhook.Types.Repo as R
import qualified GithubWebhook.Types.Commit as C
import qualified GithubWebhook.Types.BigUser as BigUser
import GHC.Generics
import qualified Utils
data PushEvent = PushEvent
{ ref :: T.Text
, before :: T.Text
, after :: T.Text
, created :: Bool
, deleted :: Bool
, forced :: Bool
, baseRef :: Maybe T.Text
, compare :: T.Text
, commits :: [C.Commit]
, headCommit :: C.Commit
, repository :: R.Repo
, pusher :: SmallUser.SmallUser
, sender :: BigUser.BigUser } deriving (Eq, Generic, Show)
$(A.deriveJSON
A.defaultOptions
{A.fieldLabelModifier = Utils.camelCaseToSnakeCase}
''PushEvent)
|
bgwines/hueue
|
src/GithubWebhook/Types/Events/PushEvent.hs
|
Haskell
|
bsd-3-clause
| 997
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback2
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the NV_transform_feedback2 extension, see
-- <http://www.opengl.org/registry/specs/NV/transform_feedback2.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback2 (
-- * Functions
glBindTransformFeedback,
glDeleteTransformFeedbacks,
glGenTransformFeedbacks,
glIsTransformFeedback,
glPauseTransformFeedback,
glResumeTransformFeedback,
glDrawTransformFeedback,
-- * Tokens
gl_TRANSFORM_FEEDBACK,
gl_TRANSFORM_FEEDBACK_BUFFER_PAUSED,
gl_TRANSFORM_FEEDBACK_BUFFER_ACTIVE,
gl_TRANSFORM_FEEDBACK_BINDING
) where
import Graphics.Rendering.OpenGL.Raw.ARB.TransformFeedback2
|
mfpi/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/NV/TransformFeedback2.hs
|
Haskell
|
bsd-3-clause
| 1,062
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Description: Unique identifiers for internal an external use.
module Retcon.Identifier (
-- * Configuration names
EntityName(..),
SourceName(..),
-- * Unique identifiers
InternalID, ForeignID,
ForeignKey(..),
InternalKey(..),
-- * Checking compatibility
Synchronisable(..),
compatibleEntity,
compatibleSource,
) where
import Data.Aeson.TH
import Data.String
import Data.Text (Text)
import qualified Data.Text as T
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
-- | Unique name for an entity.
newtype EntityName = EntityName { ename :: Text }
deriving (Eq, Ord)
instance IsString EntityName where
fromString = EntityName . T.pack
instance Show EntityName where
show = T.unpack . ename
instance Read EntityName where
readsPrec _ s = [(EntityName (T.pack s), "")]
-- | Unique name for a data source.
newtype SourceName = SourceName { sname :: Text }
deriving (Eq, Ord)
instance Show SourceName where
show = T.unpack . sname
instance IsString SourceName where
fromString = SourceName . T.pack
instance Read SourceName where
readsPrec _ s = [(SourceName (T.pack s), "")]
-- | Types which participate, in one way or another, in the synchronisation
-- process.
class Synchronisable a where
-- | Get the 'EntityName' for which the value is valid.
getEntityName :: a -> EntityName
-- | Get the 'SourceName' for which the value is valid.
getSourceName :: a -> SourceName
--------------------------------------------------------------------------------
type InternalID = Int
type ForeignID = Text
-- | Uniquely identify a 'Document' shared across one or more 'DataSource's.
--
-- Each 'InternalKey' value can be mapped to the 'ForeignKey's for the
-- 'DataSource's which store copies of the associated 'Document'.
data InternalKey = InternalKey
{ ikEntity :: EntityName
, ikID :: InternalID
} deriving (Eq, Ord, Show)
instance Synchronisable InternalKey where
getEntityName = ikEntity
getSourceName _ = SourceName ""
-- | Uniquely identify a 'Document' stored in 'DataSource'.
data ForeignKey = ForeignKey
{ fkEntity :: EntityName
, fkSource :: SourceName
, fkID :: ForeignID
} deriving (Eq, Ord, Show)
instance Synchronisable ForeignKey where
getEntityName = fkEntity
getSourceName = fkSource
-- json
$(deriveJSON defaultOptions ''EntityName)
$(deriveJSON defaultOptions ''SourceName)
$(deriveJSON defaultOptions ''ForeignKey)
-- postgres
instance ToField EntityName where
toField (EntityName n) = toField n
instance ToField SourceName where
toField (SourceName n) = toField n
instance ToRow ForeignKey where
toRow (ForeignKey a b c) = toRow (a,b,c)
instance ToRow InternalKey where
toRow (InternalKey a b) = toRow (a,b)
--------------------------------------------------------------------------------
-- | Check that two synchronisable values have the same entity.
compatibleEntity
:: (Synchronisable a, Synchronisable b)
=> a
-> b
-> Bool
compatibleEntity a b = getEntityName a == getEntityName b
-- | Check that two synchronisable values have the same data source.
compatibleSource
:: (Synchronisable a, Synchronisable b)
=> a
-> b
-> Bool
compatibleSource a b = compatibleEntity a b && getSourceName a == getSourceName b
|
anchor/retcon
|
lib/Retcon/Identifier.hs
|
Haskell
|
bsd-3-clause
| 3,539
|
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.X11.Xlib
-- Copyright : (c) Alastair Reid, 1999-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- A collection of FFI declarations for interfacing with Xlib.
--
-- The library aims to provide a direct translation of the X
-- binding into Haskell so the most important documentation you
-- should read is /The Xlib Programming Manual/, available online at
-- <http://tronche.com/gui/x/xlib/>. Let me say that again because
-- it is very important. Get hold of this documentation and read it:
-- it tells you almost everything you need to know to use this library.
--
-----------------------------------------------------------------------------
module Graphics.X11.Xlib
( -- * Conventions
-- $conventions
-- * Types
module Graphics.X11.Types,
-- module Graphics.X11.Xlib.Types,
Display, Screen, Visual, GC, SetWindowAttributes,
Point(..), Rectangle(..), Arc(..), Segment(..), Color(..),
Pixel, Position, Dimension, Angle, ScreenNumber, Buffer,
-- * X11 library functions
module Graphics.X11.Xlib.Event,
module Graphics.X11.Xlib.Display,
module Graphics.X11.Xlib.Screen,
module Graphics.X11.Xlib.Window,
module Graphics.X11.Xlib.Context,
module Graphics.X11.Xlib.Color,
module Graphics.X11.Xlib.Font,
module Graphics.X11.Xlib.Atom,
module Graphics.X11.Xlib.Region,
module Graphics.X11.Xlib.Misc,
) where
import Graphics.X11.Types
import Graphics.X11.Xlib.Types
import Graphics.X11.Xlib.Event
import Graphics.X11.Xlib.Display
import Graphics.X11.Xlib.Screen
import Graphics.X11.Xlib.Window
import Graphics.X11.Xlib.Context
import Graphics.X11.Xlib.Color
import Graphics.X11.Xlib.Font
import Graphics.X11.Xlib.Atom
import Graphics.X11.Xlib.Region
import Graphics.X11.Xlib.Misc
{- $conventions
In translating the library, we had to change names to conform with
Haskell's lexical syntax: function names and names of constants must start
with a lowercase letter; type names must start with an uppercase letter.
The case of the remaining letters is unchanged.
In addition, we chose to take advantage of Haskell's module system to
allow us to drop common prefixes (@X@, @XA_@, etc.) attached to X11
identifiers.
We named enumeration types so that function types would be easier
to understand. For example, we added 'Status', 'WindowClass', etc.
Note that the types are synonyms for 'Int' so no extra typesafety was
obtained.
We consistently raise exceptions when a function returns an error code.
In practice, this only affects the following functions because most Xlib
functions do not return error codes: 'allocColor', 'allocNamedColor',
'fetchBuffer', 'fetchBytes', 'fontFromGC', 'getGeometry', 'getIconName',
'iconifyWindow', 'loadQueryFont', 'lookupColor', 'openDisplay',
'parseColor', 'queryBestCursor', 'queryBestSize', 'queryBestStipple',
'queryBestTile', 'rotateBuffers', 'selectInput', 'storeBuffer',
'storeBytes', 'withdrawWindow'.
-}
----------------------------------------------------------------
-- End
----------------------------------------------------------------
|
FranklinChen/hugs98-plus-Sep2006
|
packages/X11/Graphics/X11/Xlib.hs
|
Haskell
|
bsd-3-clause
| 3,374
|
{-# LANGUAGE OverloadedStrings #-}
-- | High level functions for downloading files.
module Control.Shell.Download
( URI
, fetch, fetchBytes
, fetchFile
, fetchTags, fetchXML, fetchFeed
) where
import Data.ByteString as BS (ByteString, writeFile)
import Data.ByteString.UTF8 as BS
import Data.ByteString.Lazy as LBS
import Data.ByteString.Lazy.UTF8 as LBS
import Data.String
import Network.HTTP.Simple
import Network.HTTP.Types
import Text.Feed.Import (parseFeedString)
import Text.Feed.Types (Feed)
import Text.HTML.TagSoup (Tag, parseTags)
import Text.XML.Light (Content, parseXML)
import Control.Shell
-- | A Uniform Resource Locator.
type URI = String
liftE :: Show e => IO (Either e a) -> Shell a
liftE m = do
res <- liftIO m
case res of
Left e -> fail (show e)
Right x -> return x
httpFail :: Int -> BS.ByteString -> Shell a
httpFail code reason =
fail $ "HTTP error " ++ show code ++ ": " ++ BS.toString reason
fetchSomething :: URI -> Shell LBS.ByteString
fetchSomething uri = do
req <- assert ("could not parse URI `" ++ uri ++ "'") $ do
try $ liftIO $ parseRequest uri
rsp <- httpLBS req
case getResponseStatus rsp of
(Status 200 _) -> return (getResponseBody rsp)
(Status code reason) -> httpFail code reason
-- | Download content specified by a URL, returning the content
-- as a strict 'ByteString'.
fetchBytes :: URI -> Shell BS.ByteString
fetchBytes = fmap LBS.toStrict . fetchSomething
-- | Download content specified by a URL, returning the content
-- as a 'String'. The content is interpreted as UTF8.
fetch :: URI -> Shell String
fetch = fmap LBS.toString . fetchSomething
-- | Download content specified by a URL, writing the content to
-- the file specified by the given 'FilePath'.
fetchFile :: FilePath -> URI -> Shell ()
fetchFile file = fetchSomething >=> liftIO . LBS.writeFile file
-- | Download the content as for 'fetch', but return it as a list of parsed
-- tags using the tagsoup html parser.
fetchTags :: URI -> Shell [Tag String]
fetchTags = fmap parseTags . fetch
-- | Download the content as for 'fetch', but return it as parsed XML, using
-- the xml-light parser.
fetchXML :: URI -> Shell [Content]
fetchXML = fmap parseXML . fetch
-- | Download the content as for 'fetch', but return it as as parsed RSS or
-- Atom content, using the feed library parser.
fetchFeed :: URI -> Shell Feed
fetchFeed uri = do
str <- LBS.toString <$> fetchSomething uri
assert ("could not parse feed from `" ++ uri ++ "'") (parseFeedString str)
|
valderman/shellmate
|
shellmate-extras/Control/Shell/Download.hs
|
Haskell
|
bsd-3-clause
| 2,534
|
module QACG.CircGen.Bit.Toffoli
( tof
,tofMatchedD1
,leftTof
,rightTof
) where
import QACG.CircUtils.CircuitState
import Control.Exception(assert)
tof :: String -> String -> String -> CircuitState ()
tof a b c = do consts <- getConst 4
assert (length consts == 4) $ applyTof a b c consts
freeConst consts
where applyTof x y z [c0,c1,c2,c3]
= do hadamard z
cnot y c2
cnot x c0
cnot y c1
cnot z c2
cnot c0 c3
cnot x c1
cnot z c3
cnot c2 c0
tgate x
tgate y
tgate z
tgate c0
tgateInv c1
tgateInv c2
tgateInv c3
cnot c2 c0
cnot z c3
cnot x c1
cnot c0 c3
cnot z c2
cnot y c1
cnot x c0
cnot y c2
hadamard z
applyTof _ _ _ _ = assert False $ return () --Should never happen!
tofMatchedD1 :: String -> String -> String -> CircuitState ()
tofMatchedD1 e f g = do consts <- getConst 1
applyTof e f g (head consts)
freeConst consts
where applyTof x y z c
= do hadamard z
cnot z y
cnot x c
cnot z x
cnot y c
tgateInv x
tgateInv y
tgate z
tgate c
cnot y c
cnot z x
cnot x c
cnot z y
hadamard z
leftTof :: String -> String -> String -> CircuitState ()
leftTof x y z
= do hadamard z
cnot z y
cnot y x
tgate x
tgateInv y
tgate z
cnot z y
cnot y x
tgateInv x
cnot z x
hadamard z
rightTof :: String -> String -> String -> CircuitState ()
rightTof x y z
= do hadamard z
cnot z x
tgateInv x
cnot y x
cnot z y
tgate z
tgateInv y
tgate x
cnot y x
cnot z y
hadamard z
|
aparent/qacg
|
src/QACG/CircGen/Bit/Toffoli.hs
|
Haskell
|
bsd-3-clause
| 2,226
|
#!/usr/bin/env stack
-- stack --install-ghc runghc --package=shake --package=extra --package=zip-archive --package=mime-types --package=http-types --package=http-conduit --package=text --package=conduit-combinators --package=conduit --package=case-insensitive --package=aeson --package=zlib --package tar
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.List
import Data.Maybe
import Distribution.PackageDescription.Parse
import Distribution.Text
import Distribution.System
import Distribution.Package
import Distribution.PackageDescription hiding (options)
import Distribution.Verbosity
import System.Console.GetOpt
import System.Environment
import System.Directory
import System.IO.Error
import System.Process
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Zip as Zip
import qualified Codec.Compression.GZip as GZip
import Data.Aeson
import qualified Data.CaseInsensitive as CI
import Data.Conduit
import qualified Data.Conduit.Combinators as CC
import Data.List.Extra
import qualified Data.Text as T
import Development.Shake
import Development.Shake.FilePath
import Network.HTTP.Conduit
import Network.HTTP.Types
import Network.Mime
import Prelude -- Silence AMP warning
-- | Entrypoint.
main :: IO ()
main =
shakeArgsWith
shakeOptions { shakeFiles = releaseDir
, shakeVerbosity = Chatty
, shakeChange = ChangeModtimeAndDigestInput }
options $
\flags args -> do
gStackPackageDescription <-
packageDescription <$> readPackageDescription silent "stack.cabal"
gGithubAuthToken <- lookupEnv githubAuthTokenEnvVar
gGitRevCount <- length . lines <$> readProcess "git" ["rev-list", "HEAD"] ""
gGitSha <- trim <$> readProcess "git" ["rev-parse", "HEAD"] ""
gHomeDir <- getHomeDirectory
let gGpgKey = "9BEFB442"
gAllowDirty = False
gGithubReleaseTag = Nothing
Platform arch _ = buildPlatform
gArch = arch
gBinarySuffix = ""
gUploadLabel = Nothing
gLocalInstallRoot = "" -- Set to real value below.
gProjectRoot = "" -- Set to real value velow.
global0 = foldl (flip id) Global{..} flags
-- Need to get paths after options since the '--arch' argument can effect them.
localInstallRoot' <- getStackPath global0 "local-install-root"
projectRoot' <- getStackPath global0 "project-root"
let global = global0
{ gLocalInstallRoot = localInstallRoot'
, gProjectRoot = projectRoot' }
return $ Just $ rules global args
where
getStackPath global path = do
out <- readProcess stackProgName (stackArgs global ++ ["path", "--" ++ path]) ""
return $ trim $ fromMaybe out $ stripPrefix (path ++ ":") out
-- | Additional command-line options.
options :: [OptDescr (Either String (Global -> Global))]
options =
[ Option "" [gpgKeyOptName]
(ReqArg (\v -> Right $ \g -> g{gGpgKey = v}) "USER-ID")
"GPG user ID to sign distribution package with."
, Option "" [allowDirtyOptName] (NoArg $ Right $ \g -> g{gAllowDirty = True})
"Allow a dirty working tree for release."
, Option "" [githubAuthTokenOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubAuthToken = Just v}) "TOKEN")
("Github personal access token (defaults to " ++
githubAuthTokenEnvVar ++
" environment variable).")
, Option "" [githubReleaseTagOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubReleaseTag = Just v}) "TAG")
"Github release tag to upload to."
, Option "" [archOptName]
(ReqArg
(\v -> case simpleParse v of
Nothing -> Left $ "Unknown architecture in --arch option: " ++ v
Just arch -> Right $ \g -> g{gArch = arch})
"ARCHITECTURE")
"Architecture to build (e.g. 'i386' or 'x86_64')."
, Option "" [binaryVariantOptName]
(ReqArg (\v -> Right $ \g -> g{gBinarySuffix = v}) "SUFFIX")
"Extra suffix to add to binary executable archive filename."
, Option "" [uploadLabelOptName]
(ReqArg (\v -> Right $ \g -> g{gUploadLabel = Just v}) "LABEL")
"Label to give the uploaded release asset" ]
-- | Shake rules.
rules :: Global -> [String] -> Rules ()
rules global@Global{..} args = do
case args of
[] -> error "No wanted target(s) specified."
_ -> want args
phony releasePhony $ do
need [checkPhony]
need [uploadPhony]
phony cleanPhony $
removeFilesAfter releaseDir ["//*"]
phony checkPhony $
need [releaseCheckDir </> binaryExeFileName]
phony uploadPhony $
mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryPkgFileNames
phony buildPhony $
mapM_ (\f -> need [releaseDir </> f]) binaryPkgFileNames
distroPhonies ubuntuDistro ubuntuVersions debPackageFileName
distroPhonies debianDistro debianVersions debPackageFileName
distroPhonies centosDistro centosVersions rpmPackageFileName
distroPhonies fedoraDistro fedoraVersions rpmPackageFileName
phony archUploadPhony $ need [archDir </> archPackageFileName <.> uploadExt]
phony archBuildPhony $ need [archDir </> archPackageFileName]
releaseDir </> "*" <.> uploadExt %> \out -> do
let srcFile = dropExtension out
mUploadLabel =
if takeExtension srcFile == ascExt
then fmap (++ " (GPG signature)") gUploadLabel
else gUploadLabel
uploadToGithubRelease global srcFile mUploadLabel
copyFileChanged srcFile out
releaseCheckDir </> binaryExeFileName %> \out -> do
need [installBinDir </> stackExeFileName]
Stdout dirty <- cmd "git status --porcelain"
when (not gAllowDirty && not (null (trim dirty))) $
error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.")
let instExeFile = installBinDir </> stackExeFileName
tmpExeFile = installBinDir </> stackExeFileName <.> "tmp"
--EKB FIXME: once 'stack install --path' implemented, use it instead of this temp file.
liftIO $ renameFile instExeFile tmpExeFile
actionFinally
(do opt <- addPath [installBinDir] []
-- () <- cmd opt stackProgName (stackArgs global) "build --pedantic --haddock --no-haddock-deps"
() <- cmd opt stackProgName (stackArgs global) "build --pedantic"
() <- cmd opt stackProgName (stackArgs global) "clean"
() <- cmd opt stackProgName (stackArgs global) "build --pedantic"
() <- cmd opt stackProgName (stackArgs global) "test --pedantic --flag stack:integration-tests"
return ())
(renameFile tmpExeFile instExeFile)
copyFileChanged (installBinDir </> stackExeFileName) out
releaseDir </> binaryPkgZipFileName %> \out -> do
stageFiles <- getBinaryPkgStageFiles
putNormal $ "zip " ++ out
liftIO $ do
entries <- forM stageFiles $ \stageFile -> do
Zip.readEntry
[Zip.OptLocation
(dropDirectoryPrefix (releaseStageDir </> binaryPkgStageDirName) stageFile)
False]
stageFile
let archive = foldr Zip.addEntryToArchive Zip.emptyArchive entries
L8.writeFile out (Zip.fromArchive archive)
releaseDir </> binaryPkgTarGzFileName %> \out -> do
stageFiles <- getBinaryPkgStageFiles
writeTarGz out releaseStageDir stageFiles
releaseStageDir </> binaryPkgStageDirName </> stackExeFileName %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
releaseStageDir </> (binaryPkgStageDirName ++ "//*") %> \out -> do
copyFileChanged
(dropDirectoryPrefix (releaseStageDir </> binaryPkgStageDirName) out)
out
releaseDir </> binaryExeFileName %> \out -> do
need [installBinDir </> stackExeFileName]
case platformOS of
Windows -> do
-- Windows doesn't have or need a 'strip' command, so skip it.
-- Instead, we sign the executable
liftIO $ copyFile (installBinDir </> stackExeFileName) out
actionOnException
(command_ [] "c:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\signtool.exe"
["sign"
,"/v"
,"/d", synopsis gStackPackageDescription
,"/du", homepage gStackPackageDescription
,"/n", "FP Complete, Corporation"
,"/t", "http://timestamp.verisign.com/scripts/timestamp.dll"
,out])
(removeFile out)
Linux ->
cmd "strip -p --strip-unneeded --remove-section=.comment -o"
[out, installBinDir </> stackExeFileName]
_ ->
cmd "strip -o"
[out, installBinDir </> stackExeFileName]
releaseDir </> binaryPkgSignatureFileName %> \out -> do
need [out -<.> ""]
_ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out)
cmd "gpg --detach-sig --armor"
[ "-u", gGpgKey
, dropExtension out ]
installBinDir </> stackExeFileName %> \out -> do
alwaysRerun
actionOnException
(cmd stackProgName (stackArgs global) "--install-ghc build --pedantic")
(removeFile out)
debDistroRules ubuntuDistro ubuntuVersions
debDistroRules debianDistro debianVersions
rpmDistroRules centosDistro centosVersions
rpmDistroRules fedoraDistro fedoraVersions
archDir </> archPackageFileName <.> uploadExt %> \out -> do
let pkgFile = dropExtension out
need [pkgFile]
() <- cmd "aws s3 cp"
[ pkgFile
, "s3://download.fpcomplete.com/archlinux/" ++ takeFileName pkgFile ]
copyFileChanged pkgFile out
archDir </> archPackageFileName %> \out -> do
docFiles <- getDocFiles
let inputFiles = concat
[[archStagedExeFile
,archStagedBashCompletionFile]
,map (archStagedDocDir </>) docFiles]
need inputFiles
putNormal $ "tar gzip " ++ out
writeTarGz out archStagingDir inputFiles
archStagedExeFile %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
archStagedBashCompletionFile %> \out -> do
writeBashCompletion archStagedExeFile archStagingDir out
archStagedDocDir ++ "//*" %> \out -> do
let origFile = dropDirectoryPrefix archStagedDocDir out
copyFileChanged origFile out
where
debDistroRules debDistro0 debVersions = do
let anyVersion0 = anyDistroVersion debDistro0
distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 <.> uploadExt %> \out -> do
let DistroVersion{..} = distroVersionFromPath out debVersions
pkgFile = dropExtension out
need [pkgFile]
() <- cmd "deb-s3 upload -b download.fpcomplete.com --preserve-versions"
[ "--sign=" ++ gGpgKey
, "--prefix=" ++ dvDistro ++ "/" ++ dvCodeName
, pkgFile ]
copyFileChanged pkgFile out
distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 %> \out -> do
docFiles <- getDocFiles
let dv@DistroVersion{..} = distroVersionFromPath out debVersions
inputFiles = concat
[[debStagedExeFile dv
,debStagedBashCompletionFile dv]
,map (debStagedDocDir dv </>) docFiles]
need inputFiles
cmd "fpm -f -s dir -t deb"
"--deb-recommends git --deb-recommends gnupg"
"-d g++ -d gcc -d libc6-dev -d libffi-dev -d libgmp-dev -d make -d xz-utils -d zlib1g-dev"
["-n", stackProgName
,"-C", debStagingDir dv
,"-v", debPackageVersionStr dv
,"-p", out
,"-m", maintainer gStackPackageDescription
,"--description", synopsis gStackPackageDescription
,"--license", display (license gStackPackageDescription)
,"--url", homepage gStackPackageDescription]
(map (dropDirectoryPrefix (debStagingDir dv)) inputFiles)
debStagedExeFile anyVersion0 %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
debStagedBashCompletionFile anyVersion0 %> \out -> do
let dv = distroVersionFromPath out debVersions
writeBashCompletion (debStagedExeFile dv) (debStagingDir dv) out
debStagedDocDir anyVersion0 ++ "//*" %> \out -> do
let dv@DistroVersion{..} = distroVersionFromPath out debVersions
origFile = dropDirectoryPrefix (debStagedDocDir dv) out
copyFileChanged origFile out
rpmDistroRules rpmDistro0 rpmVersions = do
let anyVersion0 = anyDistroVersion rpmDistro0
distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 <.> uploadExt %> \out -> do
let DistroVersion{..} = distroVersionFromPath out rpmVersions
pkgFile = dropExtension out
need [pkgFile]
let rpmmacrosFile = gHomeDir </> ".rpmmacros"
rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile
when rpmmacrosExists $
error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.")
actionFinally
(do writeFileLines rpmmacrosFile
[ "%_signature gpg"
, "%_gpg_name " ++ gGpgKey ]
() <- cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com"
[ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion
, pkgFile ]
return ())
(liftIO $ removeFile rpmmacrosFile)
copyFileChanged pkgFile out
distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 %> \out -> do
docFiles <- getDocFiles
let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions
inputFiles = concat
[[rpmStagedExeFile dv
,rpmStagedBashCompletionFile dv]
,map (rpmStagedDocDir dv </>) docFiles]
need inputFiles
cmd "fpm -s dir -t rpm"
"-d perl -d make -d automake -d gcc -d gmp-devel -d libffi -d zlib -d xz -d tar"
["-n", stackProgName
,"-C", rpmStagingDir dv
,"-v", rpmPackageVersionStr dv
,"--iteration", rpmPackageIterationStr dv
,"-p", out
,"-m", maintainer gStackPackageDescription
,"--description", synopsis gStackPackageDescription
,"--license", display (license gStackPackageDescription)
,"--url", homepage gStackPackageDescription]
(map (dropDirectoryPrefix (rpmStagingDir dv)) inputFiles)
rpmStagedExeFile anyVersion0 %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
rpmStagedBashCompletionFile anyVersion0 %> \out -> do
let dv = distroVersionFromPath out rpmVersions
writeBashCompletion (rpmStagedExeFile dv) (rpmStagingDir dv) out
rpmStagedDocDir anyVersion0 ++ "//*" %> \out -> do
let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions
origFile = dropDirectoryPrefix (rpmStagedDocDir dv) out
copyFileChanged origFile out
writeBashCompletion stagedStackExeFile stageDir out = do
need [stagedStackExeFile]
(Stdout bashCompletionScript) <- cmd [stagedStackExeFile] "--bash-completion-script" [dropDirectoryPrefix stageDir stagedStackExeFile]
writeFileChanged out bashCompletionScript
getBinaryPkgStageFiles = do
docFiles <- getDocFiles
let stageFiles = concat
[[releaseStageDir </> binaryPkgStageDirName </> stackExeFileName]
,map ((releaseStageDir </> binaryPkgStageDirName) </>) docFiles]
need stageFiles
return stageFiles
getDocFiles = getDirectoryFiles "." ["LICENSE", "*.md", "doc//*"]
distroVersionFromPath path versions =
let path' = dropDirectoryPrefix releaseDir path
version = takeDirectory1 (dropDirectory1 path')
in DistroVersion (takeDirectory1 path') version (lookupVersionCodeName version versions)
distroPhonies distro0 versions0 makePackageFileName =
forM_ versions0 $ \(version0,_) -> do
let dv@DistroVersion{..} = DistroVersion distro0 version0 (lookupVersionCodeName version0 versions0)
phony (distroUploadPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv <.> uploadExt]
phony (distroBuildPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv]
lookupVersionCodeName version versions =
fromMaybe (error $ "lookupVersionCodeName: could not find " ++ show version ++ " in " ++ show versions) $
lookup version versions
releasePhony = "release"
checkPhony = "check"
uploadPhony = "upload"
cleanPhony = "clean"
buildPhony = "build"
distroUploadPhony DistroVersion{..} = "upload-" ++ dvDistro ++ "-" ++ dvVersion
distroBuildPhony DistroVersion{..} = "build-" ++ dvDistro ++ "-" ++ dvVersion
archUploadPhony = "upload-" ++ archDistro
archBuildPhony = "build-" ++ archDistro
releaseCheckDir = releaseDir </> "check"
releaseStageDir = releaseDir </> "stage"
installBinDir = gLocalInstallRoot </> "bin"
distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion
binaryPkgFileNames = [binaryPkgFileName, binaryPkgSignatureFileName]
binaryPkgSignatureFileName = binaryPkgFileName <.> ascExt
binaryPkgFileName =
case platformOS of
Windows -> binaryPkgZipFileName
_ -> binaryPkgTarGzFileName
binaryPkgZipFileName = binaryName global <.> zipExt
binaryPkgTarGzFileName = binaryName global <.> tarGzExt
binaryPkgStageDirName = binaryName global
binaryExeFileName = binaryName global <.> exe
stackExeFileName = stackProgName <.> exe
debStagedDocDir dv = debStagingDir dv </> "usr/share/doc" </> stackProgName
debStagedBashCompletionFile dv = debStagingDir dv </> "etc/bash_completion.d/stack"
debStagedExeFile dv = debStagingDir dv </> "usr/bin/stack"
debStagingDir dv = distroVersionDir dv </> debPackageName dv
debPackageFileName dv = debPackageName dv <.> debExt
debPackageName dv = stackProgName ++ "_" ++ debPackageVersionStr dv ++ "_amd64"
debPackageVersionStr DistroVersion{..} = stackVersionStr global ++ "-0~" ++ dvCodeName
rpmStagedDocDir dv = rpmStagingDir dv </> "usr/share/doc" </> (stackProgName ++ "-" ++ rpmPackageVersionStr dv)
rpmStagedBashCompletionFile dv = rpmStagingDir dv </> "etc/bash_completion.d/stack"
rpmStagedExeFile dv = rpmStagingDir dv </> "usr/bin/stack"
rpmStagingDir dv = distroVersionDir dv </> rpmPackageName dv
rpmPackageFileName dv = rpmPackageName dv <.> rpmExt
rpmPackageName dv = stackProgName ++ "-" ++ rpmPackageVersionStr dv ++ "-" ++ rpmPackageIterationStr dv ++ ".x86_64"
rpmPackageIterationStr DistroVersion{..} = "0." ++ dvCodeName
rpmPackageVersionStr _ = stackVersionStr global
archStagedDocDir = archStagingDir </> "usr/share/doc" </> stackProgName
archStagedBashCompletionFile = archStagingDir </> "usr/share/bash-completion/completions/stack"
archStagedExeFile = archStagingDir </> "usr/bin/stack"
archStagingDir = archDir </> archPackageName
archPackageFileName = archPackageName <.> tarGzExt
archPackageName = stackProgName ++ "_" ++ stackVersionStr global ++ "-" ++ "x86_64"
archDir = releaseDir </> archDistro
ubuntuVersions =
[ ("12.04", "precise")
, ("14.04", "trusty")
, ("14.10", "utopic")
, ("15.04", "vivid") ]
debianVersions =
[ ("7", "wheezy")
, ("8", "jessie") ]
centosVersions =
[ ("7", "el7")
, ("6", "el6") ]
fedoraVersions =
[ ("21", "fc21")
, ("22", "fc22") ]
ubuntuDistro = "ubuntu"
debianDistro = "debian"
centosDistro = "centos"
fedoraDistro = "fedora"
archDistro = "arch"
anyDistroVersion distro = DistroVersion distro "*" "*"
zipExt = ".zip"
tarGzExt = tarExt <.> gzExt
gzExt = ".gz"
tarExt = ".tar"
ascExt = ".asc"
uploadExt = ".upload"
debExt = ".deb"
rpmExt = ".rpm"
-- | Upload file to Github release.
uploadToGithubRelease :: Global -> FilePath -> Maybe String -> Action ()
uploadToGithubRelease global@Global{..} file mUploadLabel = do
need [file]
putNormal $ "Uploading to Github: " ++ file
GithubRelease{..} <- getGithubRelease
resp <- liftIO $ callGithubApi global
[(CI.mk $ S8.pack "Content-Type", defaultMimeLookup (T.pack file))]
(Just file)
(replace
"{?name,label}"
("?name=" ++ urlEncodeStr (takeFileName file) ++
(case mUploadLabel of
Nothing -> ""
Just uploadLabel -> "&label=" ++ urlEncodeStr uploadLabel))
relUploadUrl)
case eitherDecode resp of
Left e -> error ("Could not parse Github asset upload response (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right (GithubReleaseAsset{..}) ->
when (assetState /= "uploaded") $
error ("Invalid asset state after Github asset upload: " ++ assetState)
where
urlEncodeStr = S8.unpack . urlEncode True . S8.pack
getGithubRelease = do
releases <- getGithubReleases
let tag = fromMaybe ("v" ++ stackVersionStr global) gGithubReleaseTag
return $ fromMaybe
(error ("Could not find Github release with tag '" ++ tag ++ "'.\n" ++
"Use --" ++ githubReleaseTagOptName ++ " option to specify a different tag."))
(find (\r -> relTagName r == tag) releases)
getGithubReleases :: Action [GithubRelease]
getGithubReleases = do
resp <- liftIO $ callGithubApi global
[] Nothing "https://api.github.com/repos/commercialhaskell/stack/releases"
case eitherDecode resp of
Left e -> error ("Could not parse Github releases (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right r -> return r
-- | Make a request to the Github API and return the response.
callGithubApi :: Global -> RequestHeaders -> Maybe FilePath -> String -> IO L8.ByteString
callGithubApi Global{..} headers mpostFile url = do
req0 <- parseUrl url
let authToken =
fromMaybe
(error $
"Github auth token required.\n" ++
"Use " ++ githubAuthTokenEnvVar ++ " environment variable\n" ++
"or --" ++ githubAuthTokenOptName ++ " option to specify.")
gGithubAuthToken
req1 =
req0
{ checkStatus = \_ _ _ -> Nothing
, requestHeaders =
[ (CI.mk $ S8.pack "Authorization", S8.pack $ "token " ++ authToken)
, (CI.mk $ S8.pack "User-Agent", S8.pack "commercialhaskell/stack") ] ++
headers }
req <- case mpostFile of
Nothing -> return req1
Just postFile -> do
lbs <- L8.readFile postFile
return $ req1
{ method = S8.pack "POST"
, requestBody = RequestBodyLBS lbs }
manager <- newManager tlsManagerSettings
runResourceT $ do
res <- http req manager
responseBody res $$+- CC.sinkLazy
-- | Create a .tar.gz files from files. The paths should be absolute, and will
-- be made relative to the base directory in the tarball.
writeTarGz :: FilePath -> FilePath -> [FilePath] -> Action ()
writeTarGz out baseDir inputFiles = liftIO $ do
content <- Tar.pack baseDir $ map (dropDirectoryPrefix baseDir) inputFiles
L8.writeFile out $ GZip.compress $ Tar.write content
-- | Drops a directory prefix from a path. The prefix automatically has a path
-- separator character appended. Fails if the path does not begin with the prefix.
dropDirectoryPrefix :: FilePath -> FilePath -> FilePath
dropDirectoryPrefix prefix path =
case stripPrefix (toStandard prefix ++ "/") (toStandard path) of
Nothing -> error ("dropDirectoryPrefix: cannot drop " ++ show prefix ++ " from " ++ show path)
Just stripped -> stripped
-- | Build a Docker image and write its ID to a file if changed.
buildDockerImage :: FilePath -> String -> FilePath -> Action String
buildDockerImage buildDir imageTag out = do
alwaysRerun
() <- cmd "docker build" ["--tag=" ++ imageTag, buildDir]
(Stdout imageIdOut) <- cmd "docker inspect --format={{.Id}}" [imageTag]
writeFileChanged out imageIdOut
return (trim imageIdOut)
-- | Name of the release binary (e.g. @stack-x.y.x-arch-os[-variant]@)
binaryName :: Global -> String
binaryName global@Global{..} =
concat
[ stackProgName
, "-"
, stackVersionStr global
, "-"
, platformName global
, if null gBinarySuffix then "" else "-" ++ gBinarySuffix ]
-- | String representation of stack package version.
stackVersionStr :: Global -> String
stackVersionStr =
display . pkgVersion . package . gStackPackageDescription
-- | Name of current platform.
platformName :: Global -> String
platformName Global{..} =
display (Platform gArch platformOS)
-- | Current operating system.
platformOS :: OS
platformOS =
let Platform _ os = buildPlatform
in os
-- | Directory in which to store build and intermediate files.
releaseDir :: FilePath
releaseDir = "_release"
-- | @GITHUB_AUTH_TOKEN@ environment variale name.
githubAuthTokenEnvVar :: String
githubAuthTokenEnvVar = "GITHUB_AUTH_TOKEN"
-- | @--github-auth-token@ command-line option name.
githubAuthTokenOptName :: String
githubAuthTokenOptName = "github-auth-token"
-- | @--github-release-tag@ command-line option name.
githubReleaseTagOptName :: String
githubReleaseTagOptName = "github-release-tag"
-- | @--gpg-key@ command-line option name.
gpgKeyOptName :: String
gpgKeyOptName = "gpg-key"
-- | @--allow-dirty@ command-line option name.
allowDirtyOptName :: String
allowDirtyOptName = "allow-dirty"
-- | @--arch@ command-line option name.
archOptName :: String
archOptName = "arch"
-- | @--binary-variant@ command-line option name.
binaryVariantOptName :: String
binaryVariantOptName = "binary-variant"
-- | @--upload-label@ command-line option name.
uploadLabelOptName :: String
uploadLabelOptName = "upload-label"
-- | Arguments to pass to all 'stack' invocations.
stackArgs :: Global -> [String]
stackArgs Global{..} = ["--arch=" ++ display gArch]
-- | Name of the 'stack' program.
stackProgName :: FilePath
stackProgName = "stack"
-- | Linux distribution/version combination.
data DistroVersion = DistroVersion
{ dvDistro :: !String
, dvVersion :: !String
, dvCodeName :: !String }
-- | A Github release, as returned by the Github API.
data GithubRelease = GithubRelease
{ relUploadUrl :: !String
, relTagName :: !String }
deriving (Show)
instance FromJSON GithubRelease where
parseJSON = withObject "GithubRelease" $ \o ->
GithubRelease
<$> o .: T.pack "upload_url"
<*> o .: T.pack "tag_name"
-- | A Github release asset, as returned by the Github API.
data GithubReleaseAsset = GithubReleaseAsset
{ assetState :: !String }
deriving (Show)
instance FromJSON GithubReleaseAsset where
parseJSON = withObject "GithubReleaseAsset" $ \o ->
GithubReleaseAsset
<$> o .: T.pack "state"
-- | Global values and options.
data Global = Global
{ gStackPackageDescription :: !PackageDescription
, gLocalInstallRoot :: !FilePath
, gGpgKey :: !String
, gAllowDirty :: !Bool
, gGithubAuthToken :: !(Maybe String)
, gGithubReleaseTag :: !(Maybe String)
, gGitRevCount :: !Int
, gGitSha :: !String
, gProjectRoot :: !FilePath
, gHomeDir :: !FilePath
, gArch :: !Arch
, gBinarySuffix :: !String
, gUploadLabel ::(Maybe String)}
deriving (Show)
|
robstewart57/stack
|
etc/scripts/release.hs
|
Haskell
|
bsd-3-clause
| 28,996
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE DeriveFunctor #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.ParserCombinators.ReadP
-- Copyright : (c) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : non-portable (local universal quantification)
--
-- This is a library of parser combinators, originally written by Koen Claessen.
-- It parses all alternatives in parallel, so it never keeps hold of
-- the beginning of the input string, a common source of space leaks with
-- other parsers. The '(+++)' choice combinator is genuinely commutative;
-- it makes no difference which branch is \"shorter\".
-----------------------------------------------------------------------------
module Text.ParserCombinators.ReadP
(
-- * The 'ReadP' type
ReadP,
-- * Primitive operations
get,
look,
(+++),
(<++),
gather,
-- * Other operations
pfail,
eof,
satisfy,
char,
string,
munch,
munch1,
skipSpaces,
choice,
count,
between,
option,
optional,
many,
many1,
skipMany,
skipMany1,
sepBy,
sepBy1,
endBy,
endBy1,
chainr,
chainl,
chainl1,
chainr1,
manyTill,
-- * Running a parser
ReadS,
readP_to_S,
readS_to_P,
-- * Properties
-- $properties
)
where
import {-# SOURCE #-} GHC.Unicode ( isSpace )
import GHC.List ( replicate, null )
import GHC.Base hiding ( many )
infixr 5 +++, <++
------------------------------------------------------------------------
-- ReadS
-- | A parser for a type @a@, represented as a function that takes a
-- 'String' and returns a list of possible parses as @(a,'String')@ pairs.
--
-- Note that this kind of backtracking parser is very inefficient;
-- reading a large structure may be quite slow (cf 'ReadP').
type ReadS a = String -> [(a,String)]
-- ---------------------------------------------------------------------------
-- The P type
-- is representation type -- should be kept abstract
data P a
= Get (Char -> P a)
| Look (String -> P a)
| Fail
| Result a (P a)
| Final [(a,String)] -- invariant: list is non-empty!
deriving Functor
-- Monad, MonadPlus
instance Applicative P where
pure = return
(<*>) = ap
instance MonadPlus P where
mzero = empty
mplus = (<|>)
instance Monad P where
return x = Result x Fail
(Get f) >>= k = Get (\c -> f c >>= k)
(Look f) >>= k = Look (\s -> f s >>= k)
Fail >>= _ = Fail
(Result x p) >>= k = k x <|> (p >>= k)
(Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s]
fail _ = Fail
instance Alternative P where
empty = Fail
-- most common case: two gets are combined
Get f1 <|> Get f2 = Get (\c -> f1 c <|> f2 c)
-- results are delivered as soon as possible
Result x p <|> q = Result x (p <|> q)
p <|> Result x q = Result x (p <|> q)
-- fail disappears
Fail <|> p = p
p <|> Fail = p
-- two finals are combined
-- final + look becomes one look and one final (=optimization)
-- final + sthg else becomes one look and one final
Final r <|> Final t = Final (r ++ t)
Final r <|> Look f = Look (\s -> Final (r ++ run (f s) s))
Final r <|> p = Look (\s -> Final (r ++ run p s))
Look f <|> Final r = Look (\s -> Final (run (f s) s ++ r))
p <|> Final r = Look (\s -> Final (run p s ++ r))
-- two looks are combined (=optimization)
-- look + sthg else floats upwards
Look f <|> Look g = Look (\s -> f s <|> g s)
Look f <|> p = Look (\s -> f s <|> p)
p <|> Look f = Look (\s -> p <|> f s)
-- ---------------------------------------------------------------------------
-- The ReadP type
newtype ReadP a = R (forall b . (a -> P b) -> P b)
-- Functor, Monad, MonadPlus
instance Functor ReadP where
fmap h (R f) = R (\k -> f (k . h))
instance Applicative ReadP where
pure = return
(<*>) = ap
instance Monad ReadP where
return x = R (\k -> k x)
fail _ = R (\_ -> Fail)
R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k))
instance Alternative ReadP where
empty = mzero
(<|>) = mplus
instance MonadPlus ReadP where
mzero = pfail
mplus = (+++)
-- ---------------------------------------------------------------------------
-- Operations over P
final :: [(a,String)] -> P a
-- Maintains invariant for Final constructor
final [] = Fail
final r = Final r
run :: P a -> ReadS a
run (Get f) (c:s) = run (f c) s
run (Look f) s = run (f s) s
run (Result x p) s = (x,s) : run p s
run (Final r) _ = r
run _ _ = []
-- ---------------------------------------------------------------------------
-- Operations over ReadP
get :: ReadP Char
-- ^ Consumes and returns the next character.
-- Fails if there is no input left.
get = R Get
look :: ReadP String
-- ^ Look-ahead: returns the part of the input that is left, without
-- consuming it.
look = R Look
pfail :: ReadP a
-- ^ Always fails.
pfail = R (\_ -> Fail)
(+++) :: ReadP a -> ReadP a -> ReadP a
-- ^ Symmetric choice.
R f1 +++ R f2 = R (\k -> f1 k <|> f2 k)
(<++) :: ReadP a -> ReadP a -> ReadP a
-- ^ Local, exclusive, left-biased choice: If left parser
-- locally produces any result at all, then right parser is
-- not used.
R f0 <++ q =
do s <- look
probe (f0 return) s 0#
where
probe (Get f) (c:s) n = probe (f c) s (n+#1#)
probe (Look f) s n = probe (f s) s n
probe p@(Result _ _) _ n = discard n >> R (p >>=)
probe (Final r) _ _ = R (Final r >>=)
probe _ _ _ = q
discard 0# = return ()
discard n = get >> discard (n-#1#)
gather :: ReadP a -> ReadP (String, a)
-- ^ Transforms a parser into one that does the same, but
-- in addition returns the exact characters read.
-- IMPORTANT NOTE: 'gather' gives a runtime error if its first argument
-- is built using any occurrences of readS_to_P.
gather (R m)
= R (\k -> gath id (m (\a -> return (\s -> k (s,a)))))
where
gath :: (String -> String) -> P (String -> P b) -> P b
gath l (Get f) = Get (\c -> gath (l.(c:)) (f c))
gath _ Fail = Fail
gath l (Look f) = Look (\s -> gath l (f s))
gath l (Result k p) = k (l []) <|> gath l p
gath _ (Final _) = error "do not use readS_to_P in gather!"
-- ---------------------------------------------------------------------------
-- Derived operations
satisfy :: (Char -> Bool) -> ReadP Char
-- ^ Consumes and returns the next character, if it satisfies the
-- specified predicate.
satisfy p = do c <- get; if p c then return c else pfail
char :: Char -> ReadP Char
-- ^ Parses and returns the specified character.
char c = satisfy (c ==)
eof :: ReadP ()
-- ^ Succeeds iff we are at the end of input
eof = do { s <- look
; if null s then return ()
else pfail }
string :: String -> ReadP String
-- ^ Parses and returns the specified string.
string this = do s <- look; scan this s
where
scan [] _ = do return this
scan (x:xs) (y:ys) | x == y = do _ <- get; scan xs ys
scan _ _ = do pfail
munch :: (Char -> Bool) -> ReadP String
-- ^ Parses the first zero or more characters satisfying the predicate.
-- Always succeds, exactly once having consumed all the characters
-- Hence NOT the same as (many (satisfy p))
munch p =
do s <- look
scan s
where
scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s)
scan _ = do return ""
munch1 :: (Char -> Bool) -> ReadP String
-- ^ Parses the first one or more characters satisfying the predicate.
-- Fails if none, else succeeds exactly once having consumed all the characters
-- Hence NOT the same as (many1 (satisfy p))
munch1 p =
do c <- get
if p c then do s <- munch p; return (c:s)
else pfail
choice :: [ReadP a] -> ReadP a
-- ^ Combines all parsers in the specified list.
choice [] = pfail
choice [p] = p
choice (p:ps) = p +++ choice ps
skipSpaces :: ReadP ()
-- ^ Skips all whitespace.
skipSpaces =
do s <- look
skip s
where
skip (c:s) | isSpace c = do _ <- get; skip s
skip _ = do return ()
count :: Int -> ReadP a -> ReadP [a]
-- ^ @count n p@ parses @n@ occurrences of @p@ in sequence. A list of
-- results is returned.
count n p = sequence (replicate n p)
between :: ReadP open -> ReadP close -> ReadP a -> ReadP a
-- ^ @between open close p@ parses @open@, followed by @p@ and finally
-- @close@. Only the value of @p@ is returned.
between open close p = do _ <- open
x <- p
_ <- close
return x
option :: a -> ReadP a -> ReadP a
-- ^ @option x p@ will either parse @p@ or return @x@ without consuming
-- any input.
option x p = p +++ return x
optional :: ReadP a -> ReadP ()
-- ^ @optional p@ optionally parses @p@ and always returns @()@.
optional p = (p >> return ()) +++ return ()
many :: ReadP a -> ReadP [a]
-- ^ Parses zero or more occurrences of the given parser.
many p = return [] +++ many1 p
many1 :: ReadP a -> ReadP [a]
-- ^ Parses one or more occurrences of the given parser.
many1 p = liftM2 (:) p (many p)
skipMany :: ReadP a -> ReadP ()
-- ^ Like 'many', but discards the result.
skipMany p = many p >> return ()
skipMany1 :: ReadP a -> ReadP ()
-- ^ Like 'many1', but discards the result.
skipMany1 p = p >> skipMany p
sepBy :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @sepBy p sep@ parses zero or more occurrences of @p@, separated by @sep@.
-- Returns a list of values returned by @p@.
sepBy p sep = sepBy1 p sep +++ return []
sepBy1 :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @sepBy1 p sep@ parses one or more occurrences of @p@, separated by @sep@.
-- Returns a list of values returned by @p@.
sepBy1 p sep = liftM2 (:) p (many (sep >> p))
endBy :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @endBy p sep@ parses zero or more occurrences of @p@, separated and ended
-- by @sep@.
endBy p sep = many (do x <- p ; _ <- sep ; return x)
endBy1 :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @endBy p sep@ parses one or more occurrences of @p@, separated and ended
-- by @sep@.
endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x)
chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
-- ^ @chainr p op x@ parses zero or more occurrences of @p@, separated by @op@.
-- Returns a value produced by a /right/ associative application of all
-- functions returned by @op@. If there are no occurrences of @p@, @x@ is
-- returned.
chainr p op x = chainr1 p op +++ return x
chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
-- ^ @chainl p op x@ parses zero or more occurrences of @p@, separated by @op@.
-- Returns a value produced by a /left/ associative application of all
-- functions returned by @op@. If there are no occurrences of @p@, @x@ is
-- returned.
chainl p op x = chainl1 p op +++ return x
chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
-- ^ Like 'chainr', but parses one or more occurrences of @p@.
chainr1 p op = scan
where scan = p >>= rest
rest x = do f <- op
y <- scan
return (f x y)
+++ return x
chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
-- ^ Like 'chainl', but parses one or more occurrences of @p@.
chainl1 p op = p >>= rest
where rest x = do f <- op
y <- p
rest (f x y)
+++ return x
manyTill :: ReadP a -> ReadP end -> ReadP [a]
-- ^ @manyTill p end@ parses zero or more occurrences of @p@, until @end@
-- succeeds. Returns a list of values returned by @p@.
manyTill p end = scan
where scan = (end >> return []) <++ (liftM2 (:) p scan)
-- ---------------------------------------------------------------------------
-- Converting between ReadP and Read
readP_to_S :: ReadP a -> ReadS a
-- ^ Converts a parser into a Haskell ReadS-style function.
-- This is the main way in which you can \"run\" a 'ReadP' parser:
-- the expanded type is
-- @ readP_to_S :: ReadP a -> String -> [(a,String)] @
readP_to_S (R f) = run (f return)
readS_to_P :: ReadS a -> ReadP a
-- ^ Converts a Haskell ReadS-style function into a parser.
-- Warning: This introduces local backtracking in the resulting
-- parser, and therefore a possible inefficiency.
readS_to_P r =
R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s']))
-- ---------------------------------------------------------------------------
-- QuickCheck properties that hold for the combinators
{- $properties
The following are QuickCheck specifications of what the combinators do.
These can be seen as formal specifications of the behavior of the
combinators.
We use bags to give semantics to the combinators.
> type Bag a = [a]
Equality on bags does not care about the order of elements.
> (=~) :: Ord a => Bag a -> Bag a -> Bool
> xs =~ ys = sort xs == sort ys
A special equality operator to avoid unresolved overloading
when testing the properties.
> (=~.) :: Bag (Int,String) -> Bag (Int,String) -> Bool
> (=~.) = (=~)
Here follow the properties:
> prop_Get_Nil =
> readP_to_S get [] =~ []
>
> prop_Get_Cons c s =
> readP_to_S get (c:s) =~ [(c,s)]
>
> prop_Look s =
> readP_to_S look s =~ [(s,s)]
>
> prop_Fail s =
> readP_to_S pfail s =~. []
>
> prop_Return x s =
> readP_to_S (return x) s =~. [(x,s)]
>
> prop_Bind p k s =
> readP_to_S (p >>= k) s =~.
> [ ys''
> | (x,s') <- readP_to_S p s
> , ys'' <- readP_to_S (k (x::Int)) s'
> ]
>
> prop_Plus p q s =
> readP_to_S (p +++ q) s =~.
> (readP_to_S p s ++ readP_to_S q s)
>
> prop_LeftPlus p q s =
> readP_to_S (p <++ q) s =~.
> (readP_to_S p s +<+ readP_to_S q s)
> where
> [] +<+ ys = ys
> xs +<+ _ = xs
>
> prop_Gather s =
> forAll readPWithoutReadS $ \p ->
> readP_to_S (gather p) s =~
> [ ((pre,x::Int),s')
> | (x,s') <- readP_to_S p s
> , let pre = take (length s - length s') s
> ]
>
> prop_String_Yes this s =
> readP_to_S (string this) (this ++ s) =~
> [(this,s)]
>
> prop_String_Maybe this s =
> readP_to_S (string this) s =~
> [(this, drop (length this) s) | this `isPrefixOf` s]
>
> prop_Munch p s =
> readP_to_S (munch p) s =~
> [(takeWhile p s, dropWhile p s)]
>
> prop_Munch1 p s =
> readP_to_S (munch1 p) s =~
> [(res,s') | let (res,s') = (takeWhile p s, dropWhile p s), not (null res)]
>
> prop_Choice ps s =
> readP_to_S (choice ps) s =~.
> readP_to_S (foldr (+++) pfail ps) s
>
> prop_ReadS r s =
> readP_to_S (readS_to_P r) s =~. r s
-}
|
spacekitteh/smcghc
|
libraries/base/Text/ParserCombinators/ReadP.hs
|
Haskell
|
bsd-3-clause
| 14,899
|
-- |
-- Type classes and built-in implementation for primitive Haskell types
--
module Ntha.Z3.Class (
-- ** Types whose values are encodable to Z3 internal AST
Z3Encoded(..),
-- ** Types representable as Z3 Sort
-- XXX: Unsound now
-- XXX: Too flexible, can be used to encode Type ADT
Z3Sorted(..),
-- ** Type proxy helper, used with Z3Sorted
Z3Sort(..),
-- ** Types with reserved value for Z3 encoding use
-- XXX: Magic value for built-in types
Z3Reserved(..),
-- ** Monad which can be instantiated into a concrete context
SMT(..)
) where
import Ntha.Z3.Logic
import Z3.Monad
import Control.Monad.Except
import qualified Data.Map as M
import qualified Data.Set as S
data Z3Sort a = Z3Sort
class Z3Encoded a where
encode :: SMT m e => a -> m e AST
-- | XXX: Unsound
class Z3Sorted a where
-- | Map a value to Sort, the value should be a type-level thing
sort :: SMT m e => a -> m e Sort
sort _ = sortPhantom (Z3Sort :: Z3Sort a)
-- | Map a Haskell type to Sort
sortPhantom :: SMT m e => Z3Sort a -> m e Sort
sortPhantom _ = smtError "sort error"
class Z3Encoded a => Z3Reserved a where
def :: a
class (MonadError String (m e), MonadZ3 (m e)) => SMT m e where
-- | Globally unique id
genFreshId :: m e Int
-- | Given data type declarations, extra field, and the SMT monad, return the fallible result in IO monad
runSMT :: Z3Sorted ty => [(String, [(String, [(String, ty)])])] -> e -> m e a -> IO (Either String a)
-- | Binding a variable String name to two things: an de Brujin idx as Z3 AST generated by mkBound and binder's Sort
bindQualified :: String -> AST -> Sort -> m e ()
-- | Get the above AST
-- FIXME: The context management need extra -- we need to make sure that old binding wouldn't be destoryed
-- XXX: We shouldn't expose a Map here. A fallible query interface is better
getQualifierCtx :: m e (M.Map String (AST, Sort))
-- | Get the preprocessed datatype context, a map from ADT's type name to its Z3 Sort
-- XXX: We shouldn't expose a Map here. A fallible query interface is better
getDataTypeCtx :: m e (M.Map String Sort)
-- | Get extra
getExtra :: m e e
-- | Set extra
modifyExtra :: (e -> e) -> m e ()
-- | User don't have to import throwError
smtError :: String -> m e a
smtError = throwError
instance Z3Reserved Int where
def = -1 -- XXX: Magic number
instance Z3Sorted Int where
sortPhantom _ = mkIntSort
instance Z3Encoded Int where
encode i = mkIntSort >>= mkInt i
instance Z3Reserved Double where
def = -1.0 -- XXX: Magic number
instance Z3Sorted Double where
sortPhantom _ = mkRealSort
instance Z3Encoded Double where
encode = mkRealNum
instance Z3Reserved Bool where
def = False -- XXX: Magic number
instance Z3Sorted Bool where
sortPhantom _ = mkBoolSort
instance Z3Encoded Bool where
encode = mkBool
-- The basic idea:
-- For each (k, v), assert in Z3 that if we select k from array we will get
-- the same value v
-- HACK: to set a default value for rest fields (or else we always get the last asserted value
-- as default, which is certainly not complying to finite map's definition), thus the
-- user should guarantee that he/she will never never think this value as a vaid one,
-- if not, he/she might get "a valid value mapped to a invalid key" semantics
instance (Z3Sorted k, Z3Encoded k, Z3Sorted v, Z3Reserved v) => Z3Encoded (M.Map k v) where
encode m = do
fid <- genFreshId
arrSort <- sort m
arr <- mkFreshConst ("map" ++ "_" ++ show fid) arrSort
mapM_ (\(k, v) -> do
kast <- encode k
vast <- encode v
sel <- mkSelect arr kast
mkEq sel vast >>= assert) (M.toList m)
arrValueDef <- mkArrayDefault arr
vdef <- encode (def :: v)
mkEq arrValueDef vdef >>= assert
return arr
instance (Z3Sorted k, Z3Sorted v) => Z3Sorted (M.Map k v) where
sortPhantom _ = do
sk <- sortPhantom (Z3Sort :: Z3Sort k)
sv <- sortPhantom (Z3Sort :: Z3Sort v)
mkArraySort sk sv
-- Basic idea:
-- Set v =def= Map v {0, 1}
-- Thank god, this is much more sound
instance (Z3Sorted v, Z3Encoded v) => Z3Encoded (S.Set v) where
encode s = do
setSort <- sort s
fid <- genFreshId
arr <- mkFreshConst ("set" ++ "_" ++ show fid) setSort
mapM_ (\e -> do
ast <- encode e
sel <- mkSelect arr ast
one <- (mkIntSort >>= mkInt 1)
mkEq sel one >>= assert) (S.toList s)
arrValueDef <- mkArrayDefault arr
zero <- (mkIntSort >>= mkInt 0)
mkEq zero arrValueDef >>= assert
return arr
instance Z3Sorted v => Z3Sorted (S.Set v) where
sortPhantom _ = do
sortElem <- sortPhantom (Z3Sort :: Z3Sort v)
intSort <- mkIntSort
mkArraySort sortElem intSort
instance (Z3Sorted t, Z3Sorted ty, Z3Encoded a) => Z3Encoded (Pred t ty a) where
encode PTrue = mkTrue
encode PFalse = mkFalse
encode (PConj p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkAnd [a1, a2]
encode (PDisj p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkOr [a1, a2]
encode (PXor p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkXor a1 a2
encode (PNeg p) = encode p >>= mkNot
encode (PForAll x ty p) = do
sym <- mkStringSymbol x
xsort <- sort ty
-- "0" is de brujin idx for current binder
-- it is passed to Z3 which returns an intenal (idx :: AST)
-- This (idx :: AST) will be used to replace the variable
-- in the abstraction body when encountered, thus it is stored
-- in context by bindQualified we provide
-- XXX: we should save and restore qualifier context here
idx <- mkBound 0 xsort
local $ do
bindQualified x idx xsort
body <- encode p
-- The first [] is [Pattern], which is not really useful here
mkForall [] [sym] [xsort] body
encode (PExists x ty p) = do
sym <- mkStringSymbol x
xsort <- sort ty
idx <- mkBound 0 xsort
local $ do
bindQualified x idx xsort
a <- encode p
mkExists [] [sym] [xsort] a
-- HACK
encode (PExists2 x y ty p) = do
sym1 <- mkStringSymbol x
sym2 <- mkStringSymbol y
xsort <- sort ty
idx1 <- mkBound 0 xsort
idx2 <- mkBound 1 xsort
local $ do
bindQualified x idx1 xsort
bindQualified y idx2 xsort
a <- encode p
mkExists [] [sym1, sym2] [xsort, xsort] a
encode (PImpli p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkImplies a1 a2
encode (PIff p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkIff a1 a2
encode (PAssert a) = encode a
|
zjhmale/Ntha
|
src/Ntha/Z3/Class.hs
|
Haskell
|
bsd-3-clause
| 7,015
|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module System.EtCetera.LxcSpec where
import Control.Monad.Trans (liftIO)
import Data.List (intercalate)
import System.EtCetera.Internal (Optional(..))
import System.EtCetera.Lxc.Internal (Arch(..), emptyConfig, emptyNetwork, LxcConfig,
Network(..), NetworkType(..), parse, serialize,
SerializtionError(..), Switch(..),
LxcConfig(..))
import Test.Hspec (describe, it, shouldBe, Spec)
suite :: Spec
suite = do
describe "System.EtCetera.Lxc parse" $ do
it "parses single option line with new line char at the end" $
parse "lxc.aa_profile=/mnt/rootfs.complex" `shouldBe`
Right (emptyConfig {lxcAaProfile = Present "/mnt/rootfs.complex"})
it "parses single comment without new line" $
parse "# comment" `shouldBe`
Right emptyConfig
it "parses single comment with new line" $
parse "# comment\n" `shouldBe`
Right emptyConfig
it "parses network type correctly" $
parse "lxc.network.type = macvlan" `shouldBe`
(Right $ emptyConfig { lxcNetwork = [emptyNetwork { lxcNetworkType = Present Macvlan } ] })
it "parses multiple network declarations" $
parse (unlines [ "lxc.network.type = macvlan"
, "lxc.network.name = eth0"
, "lxc.network.type = veth"
, "lxc.network.name = eth1"
]) `shouldBe`
(Right $ emptyConfig { lxcNetwork = [ emptyNetwork { lxcNetworkType = Present Macvlan
, lxcNetworkName = Present "eth0"}
, emptyNetwork { lxcNetworkType = Present Veth
, lxcNetworkName = Present "eth1"}] } )
it "parses integer value correctly" $
parse "lxc.start.delay = 8" `shouldBe`
(Right $ emptyConfig { lxcStartDelay = Present 8})
it "parses multiple options" $
parse (unlines [ "lxc.aa_profile=/mnt/rootfs.complex"
, "lxc.include=/var/lib/lxc/lxc-common.conf"
, "lxc.include=/var/lib/lxc/custom"
]) `shouldBe`
Right (emptyConfig { lxcAaProfile = Present "/mnt/rootfs.complex"
, lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"
]})
it "parses mixed multiple options line with new line char at the end" $
parse (unlines [ "lxc.include=/var/lib/lxc/lxc-common.conf"
, "# comment"
, "lxc.aa_profile=/mnt/rootfs.complex"
, "# another comment"
, ""
, "lxc.include=/var/lib/lxc/custom"
]) `shouldBe`
Right (emptyConfig { lxcAaProfile = Present "/mnt/rootfs.complex"
, lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"
]})
it "parses mixed multiple lines without new line at the end" $
parse (intercalate "\n" [ "#comment "
, "lxc.include = /var/lib/lxc/lxc-common.conf"
, "lxc.include = /var/lib/lxc/custom"
, "lxc.rootfs = /mnt/rootfs.complex"
, "# another comment "
, "\t"
]) `shouldBe`
(Right $ emptyConfig { lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"]
, lxcRootfs = Present "/mnt/rootfs.complex"
})
it "parsing regression 2016.02.18.1" $
parse (intercalate "\n" [ "lxc.arch=x86_64\n"
, "lxc.rootfs=/var/lib/lxc/stream6-clone.nadaje.com/rootfs"
, "lxc.utsname=stream6-clone.nadaje.com"
, "lxc.include=/usr/share/lxc/config/debian.common.conf"
, "lxc.network.type=veth"
, "lxc.network.flags=up"
, "lxc.network.ipv4=10.0.0.3"
, "lxc.network.ipv4.gateway=10.0.0.2"
, "lxc.network.link=lxc-br01"
, "lxc.network.name=eth0"
, "\n"
, "\n"
]) `shouldBe`
(Right
emptyConfig
{ lxcArch = Present X86_64
, lxcRootfs = Present "/var/lib/lxc/stream6-clone.nadaje.com/rootfs"
, lxcUtsname = Present "stream6-clone.nadaje.com"
, lxcInclude = ["/usr/share/lxc/config/debian.common.conf"]
, lxcNetwork = [ emptyNetwork
{ lxcNetworkType = Present Veth
, lxcNetworkFlags = Present "up"
, lxcNetworkIpv4 = Present "10.0.0.3"
, lxcNetworkIpv4Gateway = Present "10.0.0.2"
, lxcNetworkLink = Present "lxc-br01"
, lxcNetworkName = Present "eth0"
}
]
})
describe "System.EtCetera.Lxc serialize" $ do
it "serializes multiple options" $
serialize (emptyConfig { lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"]
, lxcAaProfile = Present "/mnt/rootfs.complex"
}) `shouldBe`
(Right . unlines $ [ "lxc.aa_profile=/mnt/rootfs.complex"
, "lxc.include=/var/lib/lxc/lxc-common.conf"
, "lxc.include=/var/lib/lxc/custom"
])
it "serializes multiple correct networks" $
serialize
(emptyConfig
{ lxcNetwork = [ emptyNetwork { lxcNetworkType = Present Macvlan }
, emptyNetwork { lxcNetworkType = Present Veth
, lxcNetworkName = Present "eth0" }]
}) `shouldBe`
Right "lxc.network.type=macvlan\nlxc.network.type=veth\nlxc.network.name=eth0\n"
|
paluh/et-cetera
|
test/System/EtCetera/LxcSpec.hs
|
Haskell
|
bsd-3-clause
| 6,700
|
#! /usr/bin/env stack
-- stack runghc
module Advent.Day8 where
import Advent
import Data.Char (chr)
import Numeric (readHex)
unencode ('"':s) = _unencode s
where
_unencode ('\\':'"':s) = '"':_unencode s
_unencode ('\\':'\\':s) = '\\':_unencode s
_unencode ('\\':'x':a:b:s) = (chr $ (fst . head) parses):_unencode s
where parses = readHex (a:b:[])
_unencode ('"':[]) = ""
_unencode (c:[]) = error "must end in '\"'"
_unencode (c:s) = c:_unencode s
_unencode x = error $ "WTF '" ++ x ++ "'"
unencode s = error $ "must start with '\"', was '" ++ s ++ "'"
encode s = '"':_encode s
where
_encode ('\\':s) = '\\':'\\':_encode s
_encode ('"':s) = '\\':'"':_encode s
_encode [] = '"':[]
_encode (c:s) = c:_encode s
solveA input = sum (map length words) - sum (map (length . unencode) words)
where words = filter ((>1) . length) $ lines input
solveB input = sum (map (length . encode) words) - sum (map length words)
where words = filter ((>1) . length) $ lines input
main = do
solvePuzzle 8 solveA
solvePuzzle 8 solveB
|
cpennington/adventofcode
|
src/Advent/Day8.hs
|
Haskell
|
bsd-3-clause
| 1,084
|
{-# LANGUAGE TypeSynonymInstances #-}
module CarbonCopy.MailHeaders (
Header(..),
StrHeader,
HeaderMatcher,
extractHeaders,
msg_id_hdr,
from_hdr,
in_reply_to_hdr
) where
import Prelude as P
import Data.Char
import Data.ByteString.Char8 as BStr hiding (concatMap, takeWhile)
import Text.ParserCombinators.ReadP as R
data (Eq keyT) => Header keyT valueT = Header { name :: keyT, value :: valueT } deriving Eq
type StrHeader = Header String String
instance Show StrHeader where
show (Header name value) = show name ++ ":" ++ show value
type HeaderMatcher = ReadP StrHeader
msg_id_hdr = "message-id"
in_reply_to_hdr = "in-reply-to"
from_hdr = "from"
extractHeaders :: ByteString -> HeaderMatcher -> [StrHeader]
extractHeaders src matcher = concatMap parse . takeWhile ( /= BStr.empty) $ lines
where
lines = BStr.lines src
parse l = P.map fst $ readP_to_S matcher line
where line = BStr.unpack ( BStr.map toLower l ) ++ "\n"
|
jdevelop/carboncopy
|
CarbonCopy/MailHeaders.hs
|
Haskell
|
bsd-3-clause
| 1,110
|
{-# LANGUAGE PatternGuards, TypeSynonymInstances, TypeFamilies, FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Berp.Compile.Compile
-- Copyright : (c) 2010 Bernie Pope
-- License : BSD-style
-- Maintainer : florbitous@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- The compiler for berp. The compiler translates Python 3 into Haskell.
--
-----------------------------------------------------------------------------
module Berp.Compile.Compile (compiler, Compilable (..)) where
import Prelude hiding (read, init, mapM, putStrLn, sequence)
import Language.Python.Common.PrettyAST ()
import Language.Python.Common.Pretty (prettyText)
import Language.Python.Common.AST as Py
import Data.Traversable
import Data.Foldable (foldrM)
import Language.Haskell.Exts.Syntax as Hask
import Language.Haskell.Exts.Build as Hask
import Control.Applicative
import qualified Data.Set as Set
import Data.Set ((\\))
import Control.Monad hiding (mapM, sequence)
import qualified Berp.Compile.PrimName as Prim
import Berp.Compile.Monad
import Berp.Compile.HsSyntaxUtils as Hask
import Berp.Compile.PySyntaxUtils as Py
import Berp.Compile.Utils
import Berp.Base.Mangle (mangle)
import Berp.Base.Hash (Hash (..))
import Berp.Compile.IdentString (IdentString (..), ToIdentString (..), identString)
import Berp.Compile.Scope as Scope (Scope (..), topBindings, funBindings)
import qualified Berp.Compile.Scope as Scope (isGlobal)
compiler :: Compilable a => a -> IO (CompileResult a)
compiler = runCompileMonad . compile
class Compilable a where
type CompileResult a :: *
compile :: a -> Compile (CompileResult a)
instance Compilable a => Compilable [a] where
type CompileResult [a] = [CompileResult a]
compile = mapM compile
instance Compilable a => Compilable (Maybe a) where
type CompileResult (Maybe a) = Maybe (CompileResult a)
compile = mapM compile
instance Compilable InterpreterStmt where
type CompileResult InterpreterStmt = Hask.Exp
compile (InterpreterStmt suite) = do
stmts <- nestedScope topBindings $ compile $ Block suite
return $ mkLambda stmts
where
mkLambda :: [Hask.Stmt] -> Hask.Exp
mkLambda stmts = lamE bogusSrcLoc [Prim.globalsPat] $ doBlock stmts
instance Compilable ModuleSpan where
type CompileResult ModuleSpan = String -> (Hask.Module, [String])
compile (Py.Module suite) = do
stmts <- nestedScope topBindings $ compile $ Block suite
-- let allStmts = stmts ++ [qualStmt Prim.mkModule]
importedModules <- Set.toList <$> getImports
return $ \modName ->
let init = initDecl $ doBlock stmts in
(Hask.Module bogusSrcLoc
(ModuleName modName) pragmas warnings exports
(imports importedModules) [init],
importedModules)
where
initDecl :: Hask.Exp -> Hask.Decl
-- initDecl = patBind bogusSrcLoc $ pvar $ name initName
initDecl = simpleFun bogusSrcLoc (name initName) (name Prim.globalsName)
pragmas = []
warnings = Nothing
exports = Just [EVar $ UnQual $ name initName]
srcImports names = mkImportStmts $ map mkSrcImport names
stdImports = mkImportStmts [(Prim.preludeModuleName,False,Just []),
(Prim.berpModuleName,False,Nothing)]
imports names = stdImports ++ srcImports (map mkBerpModuleName names)
initName :: String
initName = "init"
mkSrcImport :: String -> (ModuleName, Bool, Maybe [String])
mkSrcImport name = (ModuleName name, True, Just [initName])
mkImportStmts :: [(ModuleName, Bool, Maybe [String])] -> [ImportDecl]
mkImportStmts = map toImportStmt
toImportStmt :: (ModuleName, Bool, Maybe [String]) -> ImportDecl
toImportStmt (moduleName, qualified, items) =
ImportDecl
{ importLoc = bogusSrcLoc
, importModule = moduleName
, importQualified = qualified
, importSrc = False
, importAs = Nothing
, importSpecs = mkImportSpecs items
, importPkg = Nothing
}
mkImportSpecs :: Maybe [String] -> Maybe (Bool, [ImportSpec])
mkImportSpecs Nothing = Nothing
mkImportSpecs (Just items) = Just (False, map (IVar . name) items)
instance Compilable StatementSpan where
type (CompileResult StatementSpan) = [Stmt]
-- XXX is it necessary to compile generators this way?
-- can the yield statement be made to dynamically build a generator object?
compile (Fun {fun_name = fun, fun_args = params, fun_body = body}) = do
oldSeenYield <- getSeenYield
unSetSeenYield
bindings <- checkEither $ funBindings params body
compiledBody <- nestedScope bindings $ compileBlockDo $ Block body
let args = Hask.PList $ map (identToMangledPatVar . paramIdent) params
isGenerator <- getSeenYield
setSeenYield oldSeenYield
let lambdaBody =
if isGenerator
-- this warrants a special case of returnGenerator, otherwise
-- the compiled code is slightly uglier.
then app Prim.returnGenerator $ parens compiledBody
else compiledBody
lambda = lamE bogusSrcLoc [args] lambdaBody
arityExp = intE $ fromIntegral $ length params
doc = docString body
defExp = appFun Prim.def [arityExp, doc, parens lambda]
(binderStmts, binderExp) <- stmtBinder defExp
writeStmt <- qualStmt <$> compileWrite fun binderExp
return $ binderStmts ++ [writeStmt]
-- Handle the single assignment case specially. In the multi-assign case
-- we want to share the evaluation of the rhs, hence the use of compileExprComp.
-- This is not needed in the single assign case, and would be overkill in general.
compile (Assign { assign_to = [lhs], assign_expr = rhs }) = do
(stmtsRhs, compiledRhs) <- compileExprObject rhs
assignStmts <- compileAssign lhs compiledRhs
return $ stmtsRhs ++ assignStmts
compile (Assign { assign_to = lhss, assign_expr = rhs }) = do
(stmtsRhs, compiledRhs) <- compileExprComp rhs
(binderStmts, binderExp) <- stmtBinder compiledRhs
assignStmtss <- mapM (flip compileAssign binderExp) lhss
return $ stmtsRhs ++ binderStmts ++ concat assignStmtss
compile (Conditional { cond_guards = guards, cond_else = elseBranch })
| length guards == 1 && isEmptySuite elseBranch,
(condExp, condSuite) <- head guards = do
condVal <- compileExprBlock condExp
condBody <- compileSuiteDo condSuite
returnStmt $ appFun Prim.ifThen [parens condVal, parens condBody]
| otherwise = do
elseExp <- compileSuiteDo elseBranch
condExp <- foldM compileGuard elseExp $ reverse guards
returnStmt condExp
compile (Return { return_expr = maybeExpr })
| Just call@(Call {}) <- maybeExpr = do
(stmts, compiledExpr) <- compileTailCall call
let newStmt = qualStmt compiledExpr
return (stmts ++ [newStmt])
| otherwise = do
(stmts, compiledExpr) <- maybe (returnExp Prim.none) compileExprObject maybeExpr
let newStmt = qualStmt $ app Prim.ret $ parens compiledExpr
return (stmts ++ [newStmt])
{-
Even though it looks like we could eliminate stmt expressions, we do need to
compile them to code just in case they have side effects (like raising exceptions).
It is very hard to determine that an expression is effect free. Constant values
are the easy case, but probably not worth the effort. Furthermore, top-level
constant expressions must be preserved for the repl of the interpreter.
-}
compile (StmtExpr { stmt_expr = expr }) = do
(stmts, compiledExpr) <- compileExprComp expr
let newStmt = qualStmt $ compiledExpr
return (stmts ++ [newStmt])
compile (While { while_cond = cond, while_body = body, while_else = elseSuite }) = do
condVal <- compileExprBlock cond
bodyExp <- compileSuiteDo body
if isEmptySuite elseSuite
then returnStmt $ appFun Prim.while [parens condVal, parens bodyExp]
else do
elseExp <- compileSuiteDo elseSuite
returnStmt $ appFun Prim.whileElse [parens condVal, parens bodyExp, parens elseExp]
-- XXX fixme, only supports one target
compile (For { for_targets = [var], for_generator = generator, for_body = body, for_else = elseSuite }) = do
(generatorStmts, compiledGenerator) <- compileExprObject generator
compiledStmtss <- compile body
newVar <- freshHaskellVar
writeStmt <- qualStmt <$> compileWrite var (Hask.var newVar)
let lambdaBody = lamE bogusSrcLoc [pvar newVar] $ doBlock $ (writeStmt : concat compiledStmtss)
if isEmptySuite elseSuite
then return (generatorStmts ++ [qualStmt $ appFun Prim.for [compiledGenerator, parens lambdaBody]])
else do
compiledElse <- compileSuiteDo elseSuite
return (generatorStmts ++ [qualStmt $ appFun Prim.forElse [compiledGenerator, parens lambdaBody, parens compiledElse]])
compile (Pass {}) = returnStmt Prim.pass
compile (NonLocal {}) = return []
compile (Global {}) = return []
-- XXX need to check if we are compiling a local or global variable.
-- XXX perhaps the body of a class is evaluated in a similar fashion to a module?
-- more dynamic than currently. Yes it is!
compile (Class { class_name = ident, class_args = args, class_body = body }) = do
bindings <- checkEither $ funBindings [] body
-- XXX slightly dodgy since the syntax allows Argument types in class definitions but
-- I'm not sure what their meaning is, or if it is just a case of the grammar over specifying
-- the language
(argsStmtss, compiledArgs) <- mapAndUnzipM (compileExprObject . arg_expr) args
compiledBody <- nestedScope bindings $ compile $ Block body
let locals = Set.toList $ localVars bindings
attributes <- qualStmt <$> app Prim.pure <$> listE <$> mapM compileClassLocal locals
let klassExp = appFun Prim.klass
[ strE $ identString ident
, listE compiledArgs
, parens $ doBlock $ compiledBody ++ [attributes]]
(binderStmts, binderExp) <- stmtBinder klassExp
writeStmt <- qualStmt <$> compileWrite ident binderExp
return (concat argsStmtss ++ binderStmts ++ [writeStmt])
where
compileClassLocal :: IdentString -> Compile Hask.Exp
compileClassLocal ident = do
hashedIdent <- compile ident
let mangledIdent = identToMangledVar ident
return $ Hask.tuple [hashedIdent, mangledIdent]
compile (Try { try_body = body, try_excepts = handlers, try_else = elseSuite, try_finally = finally }) = do
bodyExp <- compileSuiteDo body
asName <- freshHaskellVar
handlerExp <- compileHandlers (Hask.var asName) handlers
let handlerLam = lamE bogusSrcLoc [pvar asName] handlerExp
compiledElse <- compile elseSuite
compiledFinally <- compile finally
returnStmt $ mkTry (parens bodyExp) handlerLam (concat compiledElse) (concat compiledFinally)
compile (Raise { raise_expr = RaiseV3 raised }) =
case raised of
Nothing -> returnStmt Prim.reRaise
Just (e, maybeFrom) ->
case maybeFrom of
Nothing -> do
(stmts, obj) <- compileExprObject e
let newStmt = qualStmt $ app Prim.raise obj
return (stmts ++ [newStmt])
Just fromExp -> do
(stmts1, obj1) <- compileExprObject e
(stmts2, obj2) <- compileExprObject fromExp
let newStmt = qualStmt $ appFun Prim.raiseFrom [obj1, obj2]
return (stmts1 ++ stmts2 ++ [newStmt])
compile (Break {}) = returnStmt Prim.break
compile (Continue {}) = returnStmt Prim.continue
compile (Import { import_items = items }) = concat <$> mapM compile items
compile stmt@(FromImport { from_module = mod, from_items = items }) = do
case import_relative_module mod of
Nothing -> unsupported $ prettyText stmt
Just dottedName ->
case dottedName of
[ident] -> do
let identStr = ident_string ident
berpIdentStr = mkBerpModuleName identStr
importExp = appFun Prim.importModule
[strE identStr, qvar (ModuleName berpIdentStr) (name initName)]
(binderStmts, binderExp) <- stmtBinder importExp
itemsStmts <- compileFromItems binderExp items
addImport identStr
return (binderStmts ++ itemsStmts)
_other -> unsupported $ prettyText stmt
compile other = unsupported $ prettyText other
compileRead :: ToIdentString a => a -> Compile Exp
compileRead ident = do
compiledIdent <- compile $ toIdentString ident
global <- isGlobal ident
{-
let reader = if global then Prim.readGlobal else Prim.readLocal
return $ appFun reader [Prim.globals, compiledIdent]
-}
return $
if global
then appFun Prim.readGlobal [Prim.globals, compiledIdent]
else appFun Prim.readLocal [compiledIdent]
compileWrite :: ToIdentString a => a -> Exp -> Compile Exp
compileWrite ident exp = do
compiledIdent <- compile $ toIdentString ident
global <- isGlobal ident
{-
let writer = if global then Prim.writeGlobal else Prim.writeLocal
return $ appFun writer [Prim.globals, compiledIdent, exp]
-}
return $
if global
then appFun Prim.writeGlobal [Prim.globals, compiledIdent, exp]
else appFun Prim.writeLocal [compiledIdent, exp]
compileFromItems :: Exp -> FromItemsSpan -> Compile [Hask.Stmt]
compileFromItems exp (ImportEverything {}) = do
topLevel <- isTopLevel
if topLevel
then returnStmt $ appFun Prim.importAll [Prim.globals, exp]
else fail "Syntax Error: import * only allowed at module level"
compileFromItems exp (FromItems { from_items_items = items }) =
concat <$> mapM (compileFromItem exp) items
compileFromItem :: Exp -> FromItemSpan -> Compile [Hask.Stmt]
compileFromItem exp (FromItem { from_item_name = item, from_as_name = maybeAsName }) = do
let objectName = maybe item id maybeAsName
compiledItem <- compile item
(projectStmts, obj) <- stmtBinder (infixApp exp (Prim.primOp ".") compiledItem)
writeStmt <- qualStmt <$> compileWrite objectName obj
return (projectStmts ++ [writeStmt])
instance Compilable ImportItemSpan where
type CompileResult ImportItemSpan = [Hask.Stmt]
compile (ImportItem {import_item_name = dottedName, import_as_name = maybeAsName }) =
case dottedName of
[ident] -> do
let identStr = ident_string ident
berpIdentStr = mkBerpModuleName identStr
importExp = appFun Prim.importModule
[strE identStr, qvar (ModuleName berpIdentStr) (name initName)]
(binderStmts, binderExp) <- stmtBinder importExp
let objectName = maybe ident id maybeAsName
writeStmt <- qualStmt <$> compileWrite objectName binderExp
addImport identStr
return (binderStmts ++ [writeStmt])
_other -> unsupported ("import of " ++ show dottedName)
mkBerpModuleName :: String -> String
mkBerpModuleName = ("Berp_" ++)
docString :: SuiteSpan -> Exp
docString (StmtExpr { stmt_expr = Strings { strings_strings = ss }} : _)
= parens $ Prim.string $ trimString $ concat ss
docString _other = Prim.none
mkTry :: Exp -> Exp -> [Stmt] -> [Stmt] -> Exp
mkTry body handler elseSuite finally =
case (elseSuite, finally) of
([], []) -> appFun Prim.try [body, handler]
(_:_, []) -> appFun Prim.tryElse [body, handler, elseBlock]
([], _:_) -> appFun Prim.tryFinally [body, handler, finallyBlock]
(_:_, _:_) -> appFun Prim.tryElseFinally [body, handler, elseBlock, finallyBlock]
where
elseBlock = parens $ doBlock elseSuite
finallyBlock = parens $ doBlock finally
instance Compilable IdentSpan where
type CompileResult IdentSpan = Hask.Exp
compile = compile . toIdentString
instance Compilable IdentString where
type CompileResult IdentString = Hask.Exp
compile ident = do
global <- isGlobal ident
if global
then do
let str = identString $ toIdentString ident
mangled = mangle str
-- hashedVal = intE $ fromIntegral $ hash str
hashedVal = intE $ fromIntegral $ hash mangled
return $ Hask.tuple [hashedVal, strE mangled]
else
return $ identToMangledVar ident
instance Compilable ExprSpan where
type (CompileResult ExprSpan) = ([Stmt], Exp)
compile (Py.Strings { strings_strings = ss }) =
returnExp $ Prim.string $ concat $ map trimString ss
compile (Py.Bool { bool_value = b}) = returnExp $ Prim.bool b
compile (Py.Int { int_value = i}) = returnExp $ intE i
compile (Py.Float { float_value = f}) = returnExp $ Lit $ Frac $ toRational f
compile (Py.Imaginary { imaginary_value = i}) =
returnExp $ app Prim.complex $ paren c
where
real = Lit $ Frac 0
imag = Lit $ Frac $ toRational i
c = infixApp real (op $ sym ":+") imag
compile (Py.Var { var_ident = ident}) = do
readExp <- compileRead ident
return ([], readExp)
compile (Py.BinaryOp { operator = op, left_op_arg = leftExp, right_op_arg = rightExp })
| Dot {} <- op, Py.Var { var_ident = method } <- rightExp = do
(leftStmts, compiledLeft) <- compileExprObject leftExp
compiledMethod <- compile method
let newExp = infixApp compiledLeft (Prim.opExp op) compiledMethod
return (leftStmts, newExp)
| otherwise = do
(leftStmts, compiledLeft) <- compileExprObject leftExp
(rightStmts, compiledRight) <- compileExprObject rightExp
let newExp = infixApp compiledLeft (Prim.opExp op) compiledRight
return (leftStmts ++ rightStmts, newExp)
compile (Py.UnaryOp { operator = op, op_arg = arg }) = do
(argStmts, compiledArg) <- compileExprObject arg
let compiledOp = compileUnaryOp op
return (argStmts, app compiledOp compiledArg)
compile (Call { call_fun = fun, call_args = args }) = do
(funStmts, compiledFun) <- compileExprObject fun
(argsStmtss, compiledArgs) <- mapAndUnzipM compile args
let newExp = infixApp compiledFun Prim.apply (listE compiledArgs)
return (funStmts ++ concat argsStmtss, newExp)
compile (Py.Tuple { tuple_exprs = elements }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject elements
let newExp = app Prim.tuple $ listE exprs
return (concat stmtss, newExp)
compile (Py.Lambda { lambda_args = params, lambda_body = body }) = do
bindings <- checkEither $ funBindings params body
compiledBody <- nestedScope bindings $ compileExprBlock body
let args = Hask.PList $ map (identToMangledPatVar . paramIdent) params
let lambda = lamE bogusSrcLoc [args] compiledBody
returnExp $ appFun Prim.lambda [intE (fromIntegral $ length params), parens lambda]
compile (Py.List { list_exprs = elements }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject elements
let newExp = app Prim.list $ listE exprs
return (concat stmtss, newExp)
compile (Py.Dictionary { dict_mappings = mappings }) = do
let compileExprObjectPair (e1, e2) = do
(stmts1, compiledE1) <- compileExprObject e1
(stmts2, compiledE2) <- compileExprObject e2
return (stmts1 ++ stmts2, (compiledE1, compiledE2))
(stmtss, exprPairs) <- mapAndUnzipM compileExprObjectPair mappings
let newExp = app Prim.dict $ listE $ map (\(x,y) -> Hask.tuple [x,y]) exprPairs
return (concat stmtss, newExp)
compile (Py.Set { set_exprs = elements }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject elements
let newExp = app Prim.set $ listE exprs
return (concat stmtss, newExp)
compile (Subscript { subscriptee = obj_expr, subscript_expr = sub }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject [obj_expr, sub]
let newExp = appFun Prim.subscript exprs
return (concat stmtss, newExp)
compile (Yield { yield_expr = maybeExpr }) = do
(stmts, compiledExpr) <- maybe (returnExp Prim.none) compileExprObject maybeExpr
let newExpr = app Prim.yield $ parens compiledExpr
setSeenYield True
return (stmts, newExpr)
compile (Py.Paren { paren_expr = e }) = compile e
compile (None {}) = returnExp Prim.none
compile (Py.Generator { gen_comprehension = comp }) = compileComprehens GenComprehension comp
compile (Py.ListComp { list_comprehension = comp }) = compileComprehens ListComprehension comp
compile (DictComp { dict_comprehension = comp }) =
compileComprehens DictComprehension $ normaliseDictComprehension comp
compile (SetComp { set_comprehension = comp }) = compileComprehens SetComprehension comp
compile other = unsupported $ prettyText other
data ComprehensType = GenComprehension | ListComprehension | DictComprehension | SetComprehension
deriving (Eq, Show)
-- XXX maybe it would make more sense if we normalised dict comprehensions in the parser.
-- could simplify the types somewhat.
normaliseDictComprehension :: ComprehensionSpan (ExprSpan, ExprSpan) -> ComprehensionSpan ExprSpan
normaliseDictComprehension comp@(Comprehension { comprehension_expr = (e1, e2) })
= comp { comprehension_expr = Py.tuple [e1, e2] }
compileComprehens :: ComprehensType -> ComprehensionSpan ExprSpan -> Compile ([Stmt], Exp)
compileComprehens GenComprehension comprehension = do
let resultStmt = stmtExpr $ yield $ comprehension_expr comprehension
desugaredFor <- desugarComprehensFor resultStmt $ comprehension_for comprehension
bindings <- checkEither $ funBindings [] desugaredFor
compiledBody <- nestedScope bindings $ compileBlockDo $ Block [desugaredFor]
let mkGenApp = app Prim.generator $ parens compiledBody
return ([], mkGenApp)
compileComprehens ty comprehension = do
v <- freshPythonVar
let newVar = Py.var v
let initStmt = comprehensInit ty newVar
resultStmt = comprehensUpdater ty newVar $ comprehension_expr comprehension
desugaredFor <- desugarComprehensFor resultStmt $ comprehension_for comprehension
bindings <- checkEither $ funBindings [] desugaredFor
let oldLocals = localVars bindings
newLocals = Set.insert (toIdentString v) oldLocals
let newBindings = bindings { localVars = newLocals }
compiledBody <- nestedScope newBindings $ compile $ Block [initStmt, desugaredFor]
-- XXX this should be a readLocal
return (compiledBody, app Prim.read $ identToMangledVar v)
comprehensInit :: ComprehensType -> ExprSpan -> StatementSpan
comprehensInit ListComprehension var = var `assign` list []
comprehensInit SetComprehension var = var `assign` set []
comprehensInit DictComprehension var = var `assign` dict []
comprehensInit GenComprehension _var = error $ "comprehensInit called on generator comprehension"
comprehensUpdater :: ComprehensType -> ExprSpan -> ExprSpan -> StatementSpan
comprehensUpdater ListComprehension lhs rhs =
stmtExpr $ call (binOp dot lhs $ Py.var $ ident "append") [rhs]
comprehensUpdater SetComprehension lhs rhs =
stmtExpr $ call (binOp dot lhs $ Py.var $ ident "add") [rhs]
comprehensUpdater DictComprehension lhs (Py.Tuple { tuple_exprs = [key, val] }) =
assign (subscript lhs key) val
comprehensUpdater GenComprehension _lhs _rhs =
error $ "comprehensUpdater called on generator comprehension"
comprehensUpdater _other _lhs _rhs =
error $ "comprehensUpdater called on badly formed comprehension"
desugarComprehensFor :: StatementSpan -> CompForSpan -> Compile StatementSpan
desugarComprehensFor result
(CompFor { comp_for_exprs = pat, comp_in_expr = inExpr, comp_for_iter = rest }) = do
stmts <- desugarComprehensMaybeIter result rest
return $ Py.for pat inExpr stmts
desugarComprehensMaybeIter :: StatementSpan -> (Maybe CompIterSpan) -> Compile [StatementSpan]
desugarComprehensMaybeIter result Nothing = return [result]
desugarComprehensMaybeIter result (Just iter) = desugarComprehensIter result iter
desugarComprehensIter :: StatementSpan -> CompIterSpan -> Compile [StatementSpan]
desugarComprehensIter result (IterFor { comp_iter_for = compFor })
= (:[]) <$> desugarComprehensFor result compFor
desugarComprehensIter result (IterIf { comp_iter_if = compIf })
= desugarComprehensIf result compIf
desugarComprehensIf :: StatementSpan -> CompIfSpan -> Compile [StatementSpan]
desugarComprehensIf result (CompIf { comp_if = ifPart, comp_if_iter = iter }) = do
stmts <- desugarComprehensMaybeIter result iter
let guards = [(ifPart, stmts)]
return [Py.conditional guards []]
compileTailCall :: ExprSpan -> Compile ([Stmt], Exp)
compileTailCall (Call { call_fun = fun, call_args = args }) = do
(funStmts, compiledFun) <- compileExprObject fun
(argsStmtss, compiledArgs) <- mapAndUnzipM compile args
let newExp = appFun Prim.tailCall [compiledFun, listE compiledArgs]
return (funStmts ++ concat argsStmtss, newExp)
compileTailCall other = error $ "compileTailCall on non call expression: " ++ show other
instance Compilable ArgumentSpan where
type (CompileResult ArgumentSpan) = ([Stmt], Exp)
compile (ArgExpr { arg_expr = expr }) = compileExprObject expr
compile other = unsupported $ prettyText other
newtype Block = Block [StatementSpan]
newtype TopBlock = TopBlock [StatementSpan]
instance Compilable TopBlock where
type (CompileResult TopBlock) = ([Hask.Stmt], [Hask.Stmt])
compile (TopBlock []) = return ([], [qualStmt Prim.pass])
compile (TopBlock stmts) = do
scope <- getScope
let locals = localVars scope
varDecls <- mapM declareTopInterpreterVar $ Set.toList locals
haskStmtss <- compile stmts
return (varDecls, concat haskStmtss)
instance Compilable Block where
type (CompileResult Block) = [Hask.Stmt]
compile (Block []) = return [qualStmt Prim.pass]
compile (Block stmts) = do
scope <- getScope
let locals = localVars scope
varDecls <- mapM declareVar $ Set.toList locals
haskStmtss <- compile stmts
return (varDecls ++ concat haskStmtss)
-- This compiles an Expression to something with type (Eval Object). In cases where
-- the expression is atomic, it wraps the result in a call to "pure".
-- This is because compiling an atomic expression gives something
-- of type Object.
compileExprComp :: Py.ExprSpan -> Compile ([Stmt], Exp)
compileExprComp exp
| isAtomicExpr exp = do
(stmts, compiledExp) <- compile exp
return (stmts, app Prim.pureObj $ parens compiledExp)
| otherwise = compile exp
-- This compiles an expression to something with type Object. In cases where
-- the expression is non-atomic, it binds the result of evaluating the expression
-- to a variable. This is because compiling a non-atomic expression gives something
-- of type (Eval Object)
compileExprObject :: Py.ExprSpan -> Compile ([Stmt], Exp)
compileExprObject exp
| isAtomicExpr exp = compile exp
| otherwise = do
(expStmts, compiledExp) <- compile exp
(binderStmts, binderExp) <- stmtBinder compiledExp
return (expStmts ++ binderStmts, binderExp)
compileHandlers :: Exp -> [HandlerSpan] -> Compile Exp
compileHandlers asName handlers = do
validate handlers
foldrM (compileHandler asName) (parens $ app Prim.raise asName) handlers
compileHandler :: Exp -> HandlerSpan -> Exp -> Compile Exp
compileHandler asName (Handler { handler_clause = clause, handler_suite = body }) nextHandler = do
bodyStmts <- compile body
case except_clause clause of
Nothing -> return $ appFun Prim.exceptDefault
[parens $ doBlock $ concat bodyStmts, parens nextHandler]
Just (exceptClass, maybeExceptVar) -> do
varStmts <-
case maybeExceptVar of
Nothing -> return []
Just (Py.Var { var_ident = ident }) -> do
identDecl <- declareVar ident
-- XXX I think this should always be a local variable assignment
let newAssign = qualStmt $ infixApp (Hask.var $ identToMangledName ident) Prim.assignOp asName
return [identDecl, newAssign]
other -> error $ "exception expression not a variable: " ++ show other
(classStmts, classObj) <- compileExprObject exceptClass
let newBody = parens $ doBlock (varStmts ++ concat bodyStmts)
newStmt = qualStmt $ appFun Prim.except [asName, classObj, newBody, parens nextHandler]
return $ doBlock (classStmts ++ [newStmt])
compileAssign :: Py.ExprSpan -> Hask.Exp -> Compile [Stmt]
compileAssign (Py.Paren { paren_expr = expr }) rhs = compileAssign expr rhs
compileAssign (Py.Tuple { tuple_exprs = patElements }) rhs =
compileUnpack patElements rhs
compileAssign (Py.List { list_exprs = patElements }) rhs =
compileUnpack patElements rhs
-- Right argument of dot is always a variable, because dot associates to the left
compileAssign (Py.BinaryOp { operator = Dot {}
, left_op_arg = lhs
, right_op_arg = Py.Var { var_ident = attribute}}
) rhs = do
(stmtsLhs, compiledLhs) <- compileExprObject lhs
compiledAttribute <- compile attribute
let newStmt = qualStmt $ appFun Prim.setAttr [compiledLhs, compiledAttribute, rhs]
return (stmtsLhs ++ [newStmt])
compileAssign (Py.Subscript { subscriptee = objExpr, subscript_expr = sub }) rhs = do
(stmtsObj, compiledObj) <- compileExprObject objExpr
(stmtsSub, compiledSub) <- compileExprObject sub
let newStmt = qualStmt $ appFun Prim.setItem [compiledObj, compiledSub, rhs]
return (stmtsObj ++ stmtsSub ++ [newStmt])
compileAssign (Py.Var { var_ident = ident}) rhs =
(:[]) <$> qualStmt <$> compileWrite ident rhs
compileAssign lhs _rhs = unsupported ("Assignment to " ++ prettyText lhs)
compileUnpack :: [Py.ExprSpan] -> Hask.Exp -> Compile [Stmt]
compileUnpack exps rhs = do
let pat = mkUnpackPat exps
returnStmt $ appFun Prim.unpack [pat, rhs]
where
mkUnpackPat :: [Py.ExprSpan] -> Hask.Exp
mkUnpackPat listExps =
appFun (Con $ UnQual $ name "G")
[ intE $ fromIntegral $ length listExps
, listE $ map unpackComponent listExps]
unpackComponent :: Py.ExprSpan -> Hask.Exp
unpackComponent (Py.Var { var_ident = ident }) =
App (Con $ UnQual $ name "V") (identToMangledVar ident)
unpackComponent (Py.List { list_exprs = elements }) = mkUnpackPat elements
unpackComponent (Py.Tuple { tuple_exprs = elements }) = mkUnpackPat elements
unpackComponent (Py.Paren { paren_expr = exp }) = unpackComponent exp
unpackComponent other = error $ "unpack assignment to " ++ prettyText other
compileUnaryOp :: Py.OpSpan -> Hask.Exp
compileUnaryOp (Plus {}) = Prim.unaryPlus
compileUnaryOp (Minus {}) = Prim.unaryMinus
compileUnaryOp (Invert {}) = Prim.invert
compileUnaryOp (Not {}) = Prim.not
compileUnaryOp other = error ("Syntax Error: not a valid unary operator: " ++ show other)
stmtBinder :: Exp -> Compile ([Stmt], Exp)
stmtBinder exp = do
v <- freshHaskellVar
let newStmt = genStmt bogusSrcLoc (pvar v) exp
return ([newStmt], Hask.var v)
compileExprBlock :: ExprSpan -> Compile Hask.Exp
compileExprBlock exp = do
(stmts, exp) <- compileExprComp exp
return $ doBlock (stmts ++ [qualStmt exp])
compileBlockDo :: Block -> Compile Hask.Exp
compileBlockDo block = doBlock <$> compile block
compileSuiteDo :: SuiteSpan -> Compile Exp
compileSuiteDo [] = return Prim.pass
compileSuiteDo stmts = do
compiledStmtss <- compile stmts
return $ doBlock $ concat compiledStmtss
nestedScope :: Scope -> Compile a -> Compile a
nestedScope bindings comp = do
outerScope <- getScope
let newEnclosingVars = enclosingVars outerScope `Set.union`
localVars outerScope `Set.union`
paramVars outerScope
let newLevel = nestingLevel outerScope + 1
newScope = bindings { nestingLevel = newLevel, enclosingVars = newEnclosingVars }
setScope newScope
result <- comp
setScope outerScope
return result
returnStmt :: Exp -> Compile [Stmt]
returnStmt e = return [qualStmt e]
returnExp :: Exp -> Compile ([Stmt], Exp)
returnExp e = return ([], e)
declareTopInterpreterVar :: ToIdentString a => a -> Compile Hask.Stmt
declareTopInterpreterVar ident = do
let mangledPatVar = identToMangledPatVar ident
str = strE $ identString ident
return $ genStmt bogusSrcLoc mangledPatVar $ app Prim.topVar str
declareVar :: ToIdentString a => a -> Compile Hask.Stmt
declareVar ident = do
let mangledPatVar = identToMangledPatVar ident
str = strE $ identString ident
return $ genStmt bogusSrcLoc mangledPatVar $ app Prim.variable str
compileGuard :: Hask.Exp -> (ExprSpan, SuiteSpan) -> Compile Hask.Exp
compileGuard elseExp (guard, body) =
Hask.conditional <$> compileExprBlock guard <*> compileSuiteDo body <*> pure elseExp
identToMangledName :: ToIdentString a => a -> Hask.Name
identToMangledName = name . mangle . identString
identToMangledVar :: ToIdentString a => a -> Hask.Exp
identToMangledVar = Hask.var . identToMangledName
identToMangledPatVar :: ToIdentString a => a -> Hask.Pat
identToMangledPatVar = pvar . identToMangledName
-- Check that the syntax is valid Python (the parser is sometimes too liberal).
class Validate t where
validate :: t -> Compile ()
instance Validate [HandlerSpan] where
validate [] = fail "Syntax Error: try statement must have one or more handlers"
validate [_] = return ()
validate (h:hs)
| Nothing <- except_clause $ handler_clause h
= if null hs then return ()
else fail "Syntax Error: default 'except:' must be last"
| otherwise = validate hs
-- Trim (one or three) quote marks off front and end of string which are left by the lexer/parser.
trimString :: String -> String
trimString [] = []
trimString (w:x:y:zs)
| all isQuote [w,x,y] && all (== w) [x,y] = trimStringEnd zs
| isQuote w = trimStringEnd (x:y:zs)
| otherwise = w:x:y:trimStringEnd zs
trimString (x:xs)
| isQuote x = trimStringEnd xs
| otherwise = x : trimStringEnd xs
trimStringEnd :: String -> String
trimStringEnd [] = []
trimStringEnd str@[x]
| isQuote x = []
| otherwise = str
trimStringEnd str@[x,y,z]
| all isQuote str && all (== x) [y,z] = []
| otherwise = x : trimStringEnd [y,z]
trimStringEnd (x:xs) = x : trimStringEnd xs
isQuote :: Char -> Bool
isQuote '\'' = True
isQuote '"' = True
isQuote _ = False
-- test if a variable is global
isGlobal :: ToIdentString a => a -> Compile Bool
isGlobal ident = withScope $ \scope -> Scope.isGlobal (toIdentString ident) scope
|
bjpop/berp
|
libs/src/Berp/Compile/Compile.hs
|
Haskell
|
bsd-3-clause
| 35,150
|
{-# LANGUAGE OverloadedStrings #-}
{-
This file is part of the Haskell package cassava-streams. It is
subject to the license terms in the LICENSE file found in the
top-level directory of this distribution and at
git://pmade.com/cassava-streams/LICENSE. No part of cassava-streams
package, including this file, may be copied, modified, propagated, or
distributed except according to the terms contained in the LICENSE
file.
-}
--------------------------------------------------------------------------------
-- | A simple tutorial on using the cassava-streams library to glue
-- together cassava and io-streams.
--
-- Note: if you're reading this on Hackage or in Haddock then you
-- should switch to source view with the \"Source\" link at the top of
-- this page or open this file in your favorite text editor.
module System.IO.Streams.Csv.Tutorial
( -- * Types representing to-do items and their state
Item (..)
, TState (..)
-- * Functions which use cassava-streams functions
, onlyTodo
, markDone
) where
--------------------------------------------------------------------------------
import Control.Monad
import Data.Csv
import qualified Data.Vector as V
import System.IO
import qualified System.IO.Streams as Streams
import System.IO.Streams.Csv
--------------------------------------------------------------------------------
-- | A to-do item.
data Item = Item
{ title :: String -- ^ Title.
, state :: TState -- ^ State.
, time :: Maybe Double -- ^ Seconds taken to complete.
} deriving (Show, Eq)
instance FromNamedRecord Item where
parseNamedRecord m = Item <$> m .: "Title"
<*> m .: "State"
<*> m .: "Time"
instance ToNamedRecord Item where
toNamedRecord (Item t s tm) =
namedRecord [ "Title" .= t
, "State" .= s
, "Time" .= tm
]
--------------------------------------------------------------------------------
-- | Possible states for a to-do item.
data TState = Todo -- ^ Item needs to be completed.
| Done -- ^ Item has been finished.
deriving (Show, Eq)
instance FromField TState where
parseField "TODO" = return Todo
parseField "DONE" = return Done
parseField _ = mzero
instance ToField TState where
toField Todo = "TODO"
toField Done = "DONE"
--------------------------------------------------------------------------------
-- | The @onlyTodo@ function reads to-do 'Item's from the given input
-- handle (in CSV format) and writes them back to the output handle
-- (also in CSV format), but only if the items are in the @Todo@
-- state. In another words, the CSV data is filtered so that the
-- output handle only receives to-do 'Item's which haven't been
-- completed.
--
-- The io-streams @handleToInputStream@ function is used to create an
-- @InputStream ByteString@ stream from the given input handle.
--
-- That stream is then given to the cassava-streams function
-- 'decodeStreamByName' which converts the @InputStream ByteString@
-- stream into an @InputStream Item@ stream.
--
-- Notice that the cassava-streams function 'onlyValidRecords' is used
-- to transform the decoding stream into one that only produces valid
-- records. Any records which fail type conversion (via
-- @FromNamedRecord@ or @FromRecord@) will not escape from
-- 'onlyValidRecords' but instead will throw an exception.
--
-- Finally the io-streams @filter@ function is used to filter the
-- input stream so that it only produces to-do items which haven't
-- been completed.
onlyTodo :: Handle -- ^ Input handle where CSV data can be read.
-> Handle -- ^ Output handle where CSV data can be written.
-> IO ()
onlyTodo inH outH = do
-- A stream which produces items which are not 'Done'.
input <- Streams.handleToInputStream inH >>=
decodeStreamByName >>= onlyValidRecords >>=
Streams.filter (\item -> state item /= Done)
-- A stream to write items into. They will be converted to CSV.
output <- Streams.handleToOutputStream outH >>=
encodeStreamByName (V.fromList ["State", "Time", "Title"])
-- Connect the input and output streams.
Streams.connect input output
--------------------------------------------------------------------------------
-- | The @markDone@ function will read to-do items from the given
-- input handle and mark any matching items as @Done@. All to-do
-- items are written to the given output handle.
markDone :: String -- ^ Items with this title are marked as @Done@.
-> Handle -- ^ Input handle where CSV data can be read.
-> Handle -- ^ Output handle where CSV data can be written.
-> IO ()
markDone titleOfItem inH outH = do
-- Change matching items to the 'Done' state.
let markDone' item = if title item == titleOfItem
then item {state = Done}
else item
-- A stream which produces items and converts matching items to the
-- 'Done' state.
input <- Streams.handleToInputStream inH >>=
decodeStreamByName >>= onlyValidRecords >>=
Streams.map markDone'
-- A stream to write items into. They will be converted to CSV.
output <- Streams.handleToOutputStream outH >>=
encodeStreamByName (V.fromList ["State", "Time", "Title"])
-- Connect the input and output streams.
Streams.connect input output
|
pjones/cassava-streams
|
src/System/IO/Streams/Csv/Tutorial.hs
|
Haskell
|
bsd-3-clause
| 5,484
|
{-# LANGUAGE GADTs #-}
{- |
* Parse 'String' into @['Node']@.
* Parse macro definitions in @['Node']@ giving a @'Context'@ and an @'Program' 'RenderI'@.
Only macro definition in the current level is parsed.
* @'IO' a@.
-}
module Text.Velocity.Example where
import Control.Error
import Text.Velocity
import Text.Velocity.Context
import Text.Velocity.Parse
import Text.Velocity.Render
import Text.Velocity.Types
example1 :: Either VelocityError Node
example1 = parseVelocity "-" "Hello world."
example2 :: Either VelocityError Node
example2 = parseVelocity "-" "$abc$!abc$!{abc}$abc.def$100#100 'dojima rice $exchange'"
example3 :: IO ()
example3 = runEitherT (parseVelocityFile "test/variable.vm") >>= print
example4 :: IO ()
example4 = runEitherT (renderVelocityFile2 con "test/variable.vm") >>= either print putStr
where
con = emptyContext
|
edom/velocity
|
Text/Velocity/Example.hs
|
Haskell
|
bsd-3-clause
| 891
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
-- #define DEBUG
{-|
Module : AERN2.PPoly.MinMax
Description : PPoly pointwise min and max
Copyright : (c) Michal Konecny, Eike Neumann
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Poly pointwise min and max
-}
module AERN2.PPoly.MinMax where
#ifdef DEBUG
import Debug.Trace (trace)
#define maybeTrace trace
#define maybeTraceIO putStrLn
#else
#define maybeTrace (\ (_ :: String) t -> t)
#define maybeTraceIO (\ (_ :: String) -> return ())
#endif
import MixedTypesNumPrelude
import AERN2.MP
import AERN2.MP.Dyadic
import AERN2.Interval
-- import AERN2.RealFun.Operations
import AERN2.Poly.Cheb
import AERN2.Poly.Cheb.MaximumInt (intify)
import AERN2.Poly.Conversion (cheb2Power)
import AERN2.Poly.Power.RootsIntVector (findRootsWithEvaluation)
import AERN2.Poly.Cheb.Ring ()
import AERN2.Poly.Ball
import AERN2.PPoly.Type
{- min/max -}
instance CanMinMaxAsymmetric PPoly PPoly where
type MinMaxType PPoly PPoly = PPoly
max = ppolyMax
min a b = negate (max (-a) (-b))
ppolyMax ::
PPoly -> PPoly -> PPoly
ppolyMax a b =
if ppoly_dom a /= ppoly_dom b then
error "ppolyMax: PPoly domains do not match."
else
PPoly (concat (map chebMax (refine a b)))
(ppoly_dom a)
where
chebMax ((Interval domL domR), p, q) =
polys
where
acGuide = getAccuracyGuide p `max` getAccuracyGuide q
precision = getPrecision p `max` getPrecision q
-- realAcc = getAccuracy p `min` getAccuracy q
diffC = centre $ p - q
diffC' = derivativeExact diffC
evalDiffOnInterval (Interval l r) =
evalDf diffC diffC' $
fromEndpointsAsIntervals (mpBallP precision l) (mpBallP precision r)
(_diffCIntErr, diffCInt) = intify diffC
diffCRoots =
map
(\(Interval l r, err) ->
(centre $ mpBallP (ac2prec acGuide) $ (l + r)/!2, errorBound err)) $
findRootsWithEvaluation
(cheb2Power diffCInt)
(abs . evalDiffOnInterval)
(\v -> (v <= (dyadic 0.5)^!(fromAccuracy acGuide)) == Just True)
(rational domL) (rational domR)
intervals :: [(DyadicInterval, ErrorBound)]
intervals =
reverse $
aux [] (domL, errorBound 0) (diffCRoots ++ [(domR, errorBound 0)])
where
aux is (l, e0) ((x, e1) : []) =
(Interval l x, max e0 e1) : is
aux is (l, e0) ((x, e1) : xs) =
aux ((Interval l x, max e0 e1) : is) (x, e1) xs
aux _ _ [] = []
biggest :: (DyadicInterval, ErrorBound) -> (DyadicInterval, Cheb)
biggest (i@(Interval l r), e) =
if (pm >= qm) == Just True then
(i, p')
else
(i, q')
where
-- TODO: check and fix the following if necesary
p' = updateRadius (+ e) p
q' = updateRadius (+ e) q
m = (dyadic 0.5) * (l + r)
pm = evalDirect p (mpBall m)
qm = evalDirect q (mpBall m)
polys :: [(DyadicInterval, Cheb)]
polys =
map biggest intervals
|
michalkonecny/aern2
|
aern2-fun-univariate/src/AERN2/PPoly/MinMax.hs
|
Haskell
|
bsd-3-clause
| 3,049
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
module Language.Haskell.Liquid.Bare.GhcSpec (
GhcSpec(..)
, makeGhcSpec
) where
import CoreSyn hiding (Expr)
import HscTypes
import Id
import NameSet
import TyCon
import Var
import TysWiredIn
import Control.Applicative ((<$>))
import Control.Monad.Reader
import Control.Monad.State
import Data.Bifunctor
import Data.Maybe
import Data.Monoid
import qualified Control.Exception as Ex
import qualified Data.List as L
import qualified Data.HashMap.Strict as M
import qualified Data.HashSet as S
import Language.Fixpoint.Misc
import Language.Fixpoint.Names (takeWhileSym, nilName, consName)
import Language.Fixpoint.Types hiding (BE)
import Language.Haskell.Liquid.Dictionaries
import Language.Haskell.Liquid.GhcMisc (getSourcePosE, getSourcePos, sourcePosSrcSpan)
import Language.Haskell.Liquid.PredType (makeTyConInfo)
import Language.Haskell.Liquid.RefType
import Language.Haskell.Liquid.Types
import Language.Haskell.Liquid.WiredIn
import Language.Haskell.Liquid.Visitors
import Language.Haskell.Liquid.CoreToLogic
import qualified Language.Haskell.Liquid.Measure as Ms
import Language.Haskell.Liquid.Bare.Check
import Language.Haskell.Liquid.Bare.DataType
import Language.Haskell.Liquid.Bare.Env
import Language.Haskell.Liquid.Bare.Existential
import Language.Haskell.Liquid.Bare.Measure
import Language.Haskell.Liquid.Bare.Misc (makeSymbols, mkVarExpr)
import Language.Haskell.Liquid.Bare.Plugged
import Language.Haskell.Liquid.Bare.RTEnv
import Language.Haskell.Liquid.Bare.Spec
import Language.Haskell.Liquid.Bare.SymSort
import Language.Haskell.Liquid.Bare.RefToLogic
------------------------------------------------------------------
---------- Top Level Output --------------------------------------
------------------------------------------------------------------
makeGhcSpec :: Config -> ModName -> [CoreBind] -> [Var] -> [Var] -> NameSet -> HscEnv -> Either Error LogicMap
-> [(ModName,Ms.BareSpec)]
-> IO GhcSpec
makeGhcSpec cfg name cbs vars defVars exports env lmap specs
= do sp <- throwLeft =<< execBare act initEnv
let renv = ghcSpecEnv sp cbs
throwLeft $ checkGhcSpec specs renv $ postProcess cbs renv sp
where
act = makeGhcSpec' cfg cbs vars defVars exports specs
throwLeft = either Ex.throw return
initEnv = BE name mempty mempty mempty env lmap' mempty mempty
lmap' = case lmap of {Left e -> Ex.throw e; Right x -> x `mappend` listLMap}
listLMap = toLogicMap [(nilName, [], hNil),
(consName, [x, xs], hCons (EVar <$> [x,xs]))
]
where
x = symbol "x"
xs = symbol "xs"
hNil = EApp (dummyLoc $ symbol nilDataCon ) []
hCons = EApp (dummyLoc $ symbol consDataCon)
postProcess :: [CoreBind] -> SEnv SortedReft -> GhcSpec -> GhcSpec
postProcess cbs specEnv sp@(SP {..}) = sp { tySigs = tySigs', texprs = ts, asmSigs = asmSigs', dicts = dicts' }
-- HEREHEREHEREHERE (addTyConInfo stuff)
where
(sigs, ts) = replaceLocalBinds tcEmbeds tyconEnv tySigs texprs specEnv cbs
tySigs' = mapSnd (addTyConInfo tcEmbeds tyconEnv <$>) <$> sigs
asmSigs' = mapSnd (addTyConInfo tcEmbeds tyconEnv <$>) <$> asmSigs
dicts' = dmapty (addTyConInfo tcEmbeds tyconEnv) dicts
ghcSpecEnv sp cbs = fromListSEnv binds
where
emb = tcEmbeds sp
binds = [(x, rSort t) | (x, Loc _ _ t) <- meas sp]
++ [(symbol v, rSort t) | (v, Loc _ _ t) <- ctors sp]
++ [(x, vSort v) | (x, v) <- freeSyms sp, isConLikeId v]
++ [(val x , rSort stringrSort) | Just (ELit x s) <- mkLit <$> lconsts, isString s]
rSort = rTypeSortedReft emb
vSort = rSort . varRSort
varRSort :: Var -> RSort
varRSort = ofType . varType
lconsts = literals cbs
stringrSort :: RSort
stringrSort = ofType stringTy
isString s = rTypeSort emb stringrSort == s
------------------------------------------------------------------------------------------------
makeGhcSpec' :: Config -> [CoreBind] -> [Var] -> [Var] -> NameSet -> [(ModName, Ms.BareSpec)] -> BareM GhcSpec
------------------------------------------------------------------------------------------------
makeGhcSpec' cfg cbs vars defVars exports specs
= do name <- modName <$> get
makeBounds name defVars cbs specs
makeRTEnv specs
(tycons, datacons, dcSs, tyi, embs) <- makeGhcSpecCHOP1 specs
modify $ \be -> be { tcEnv = tyi }
(cls, mts) <- second mconcat . unzip . mconcat <$> mapM (makeClasses name cfg vars) specs
(measures, cms', ms', cs', xs') <- makeGhcSpecCHOP2 cbs specs dcSs datacons cls embs
(invs, ialias, sigs, asms) <- makeGhcSpecCHOP3 cfg vars defVars specs name mts embs
syms <- makeSymbols (vars ++ map fst cs') xs' (sigs ++ asms ++ cs') ms' (invs ++ (snd <$> ialias))
let su = mkSubst [ (x, mkVarExpr v) | (x, v) <- syms]
return (emptySpec cfg)
>>= makeGhcSpec0 cfg defVars exports name
>>= makeGhcSpec1 vars embs tyi exports name sigs asms cs' ms' cms' su
>>= makeGhcSpec2 invs ialias measures su
>>= makeGhcSpec3 datacons tycons embs syms
>>= makeGhcSpec4 defVars specs name su
>>= makeSpecDictionaries embs vars specs
emptySpec :: Config -> GhcSpec
emptySpec cfg = SP [] [] [] [] [] [] [] [] [] mempty [] [] [] [] mempty mempty cfg mempty [] mempty mempty
makeGhcSpec0 cfg defVars exports name sp
= do targetVars <- makeTargetVars name defVars $ binders cfg
return $ sp { config = cfg
, exports = exports
, tgtVars = targetVars }
makeGhcSpec1 vars embs tyi exports name sigs asms cs' ms' cms' su sp
= do tySigs <- makePluggedSigs name embs tyi exports $ tx sigs
asmSigs <- makePluggedAsmSigs embs tyi $ tx asms
ctors <- makePluggedAsmSigs embs tyi $ tx cs'
lmap <- logicEnv <$> get
inlmap <- inlines <$> get
let ctors' = [ (x, txRefToLogic lmap inlmap <$> t) | (x, t) <- ctors ]
return $ sp { tySigs = tySigs
, asmSigs = asmSigs
, ctors = ctors'
, meas = tx' $ tx $ ms' ++ varMeasures vars ++ cms' }
where
tx = fmap . mapSnd . subst $ su
tx' = fmap (mapSnd $ fmap uRType)
makeGhcSpec2 invs ialias measures su sp
= return $ sp { invariants = subst su invs
, ialiases = subst su ialias
, measures = subst su
<$> M.elems (Ms.measMap measures)
++ Ms.imeas measures
}
makeGhcSpec3 datacons tycons embs syms sp
= do tcEnv <- gets tcEnv
lmap <- logicEnv <$> get
inlmap <- inlines <$> get
let dcons' = mapSnd (txRefToLogic lmap inlmap) <$> datacons
return $ sp { tyconEnv = tcEnv
, dconsP = dcons'
, tconsP = tycons
, tcEmbeds = embs
, freeSyms = [(symbol v, v) | (_, v) <- syms] }
makeGhcSpec4 defVars specs name su sp
= do decr' <- mconcat <$> mapM (makeHints defVars . snd) specs
texprs' <- mconcat <$> mapM (makeTExpr defVars . snd) specs
lazies <- mkThing makeLazy
lvars' <- mkThing makeLVar
hmeas <- mkThing makeHIMeas
quals <- mconcat <$> mapM makeQualifiers specs
let sigs = strengthenHaskellMeasures hmeas ++ tySigs sp
lmap <- logicEnv <$> get
inlmap <- inlines <$> get
let tx = mapSnd (fmap $ txRefToLogic lmap inlmap)
let mtx = txRefToLogic lmap inlmap
return $ sp { qualifiers = subst su quals
, decr = decr'
, texprs = texprs'
, lvars = lvars'
, lazy = lazies
, tySigs = tx <$> sigs
, asmSigs = tx <$> (asmSigs sp)
, measures = mtx <$> (measures sp)
}
where
mkThing mk = S.fromList . mconcat <$> sequence [ mk defVars s | (m, s) <- specs, m == name ]
makeGhcSpecCHOP1 specs
= do (tcs, dcs) <- mconcat <$> mapM makeConTypes specs
let tycons = tcs ++ wiredTyCons
let tyi = makeTyConInfo tycons
embs <- mconcat <$> mapM makeTyConEmbeds specs
datacons <- makePluggedDataCons embs tyi (concat dcs ++ wiredDataCons)
let dcSelectors = concat $ map makeMeasureSelectors datacons
return $ (tycons, second val <$> datacons, dcSelectors, tyi, embs)
makeGhcSpecCHOP3 cfg vars defVars specs name mts embs
= do sigs' <- mconcat <$> mapM (makeAssertSpec name cfg vars defVars) specs
asms' <- mconcat <$> mapM (makeAssumeSpec name cfg vars defVars) specs
invs <- mconcat <$> mapM makeInvariants specs
ialias <- mconcat <$> mapM makeIAliases specs
let dms = makeDefaultMethods vars mts
tyi <- gets tcEnv
let sigs = [ (x, txRefSort tyi embs . txExpToBind <$> t) | (_, x, t) <- sigs' ++ mts ++ dms ]
let asms = [ (x, txRefSort tyi embs . txExpToBind <$> t) | (_, x, t) <- asms' ]
return (invs, ialias, sigs, asms)
makeGhcSpecCHOP2 cbs specs dcSelectors datacons cls embs
= do measures' <- mconcat <$> mapM makeMeasureSpec specs
tyi <- gets tcEnv
name <- gets modName
mapM_ (makeHaskellInlines cbs name) specs
hmeans <- mapM (makeHaskellMeasures cbs name) specs
let measures = mconcat (measures':Ms.mkMSpec' dcSelectors:hmeans)
let (cs, ms) = makeMeasureSpec' measures
let cms = makeClassMeasureSpec measures
let cms' = [ (x, Loc l l' $ cSort t) | (Loc l l' x, t) <- cms ]
let ms' = [ (x, Loc l l' t) | (Loc l l' x, t) <- ms, isNothing $ lookup x cms' ]
let cs' = [ (v, Loc (getSourcePos v) (getSourcePosE v) (txRefSort tyi embs t)) | (v, t) <- meetDataConSpec cs (datacons ++ cls)]
let xs' = val . fst <$> ms
return (measures, cms', ms', cs', xs')
data ReplaceEnv = RE { _re_env :: M.HashMap Symbol Symbol
, _re_fenv :: SEnv SortedReft
, _re_emb :: TCEmb TyCon
, _re_tyi :: M.HashMap TyCon RTyCon
}
type ReplaceState = ( M.HashMap Var (Located SpecType)
, M.HashMap Var [Expr]
)
type ReplaceM = ReaderT ReplaceEnv (State ReplaceState)
replaceLocalBinds :: TCEmb TyCon
-> M.HashMap TyCon RTyCon
-> [(Var, Located SpecType)]
-> [(Var, [Expr])]
-> SEnv SortedReft
-> CoreProgram
-> ([(Var, Located SpecType)], [(Var, [Expr])])
replaceLocalBinds emb tyi sigs texprs senv cbs
= (M.toList s, M.toList t)
where
(s,t) = execState (runReaderT (mapM_ (`traverseBinds` return ()) cbs)
(RE M.empty senv emb tyi))
(M.fromList sigs, M.fromList texprs)
traverseExprs (Let b e)
= traverseBinds b (traverseExprs e)
traverseExprs (Lam b e)
= withExtendedEnv [b] (traverseExprs e)
traverseExprs (App x y)
= traverseExprs x >> traverseExprs y
traverseExprs (Case e _ _ as)
= traverseExprs e >> mapM_ (traverseExprs . thd3) as
traverseExprs (Cast e _)
= traverseExprs e
traverseExprs (Tick _ e)
= traverseExprs e
traverseExprs _
= return ()
traverseBinds b k = withExtendedEnv (bindersOf b) $ do
mapM_ traverseExprs (rhssOfBind b)
k
withExtendedEnv vs k
= do RE env' fenv' emb tyi <- ask
let env = L.foldl' (\m v -> M.insert (takeWhileSym (/='#') $ symbol v) (symbol v) m) env' vs
fenv = L.foldl' (\m v -> insertSEnv (symbol v) (rTypeSortedReft emb (ofType $ varType v :: RSort)) m) fenv' vs
withReaderT (const (RE env fenv emb tyi)) $ do
mapM_ replaceLocalBindsOne vs
k
replaceLocalBindsOne :: Var -> ReplaceM ()
replaceLocalBindsOne v
= do mt <- gets (M.lookup v . fst)
case mt of
Nothing -> return ()
Just (Loc l l' (toRTypeRep -> t@(RTypeRep {..}))) -> do
(RE env' fenv emb tyi) <- ask
let f m k = M.lookupDefault k k m
let (env,args) = L.mapAccumL (\e (v,t) -> (M.insert v v e, substa (f e) t))
env' (zip ty_binds ty_args)
let res = substa (f env) ty_res
let t' = fromRTypeRep $ t { ty_args = args, ty_res = res }
let msg = ErrTySpec (sourcePosSrcSpan l) (pprint v) t'
case checkTy msg emb tyi fenv t' of
Just err -> Ex.throw err
Nothing -> modify (first $ M.insert v (Loc l l' t'))
mes <- gets (M.lookup v . snd)
case mes of
Nothing -> return ()
Just es -> do
let es' = substa (f env) es
case checkTerminationExpr emb fenv (v, Loc l l' t', es') of
Just err -> Ex.throw err
Nothing -> modify (second $ M.insert v es')
|
rolph-recto/liquidhaskell
|
src/Language/Haskell/Liquid/Bare/GhcSpec.hs
|
Haskell
|
bsd-3-clause
| 13,679
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Physics.Falling3d.Transform3d
(
Transform3d
)
where
import Control.Monad(liftM)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import Data.Vector.Unboxed
import Physics.Falling.Math.Transform hiding(Vector)
import Data.Vect.Double.Util.Projective
type Transform3d = Proj4
instance DeltaTransform Transform3d Vec3 where
deltaTransform p v = v .* dt
where
t = fromProjective p
dt = trim t :: Mat3
deltaTransformTranspose p v = dt *. v
where
t = fromProjective p
dt = trim t :: Mat3
instance Translatable Transform3d Vec3 where
translation p = trim t :: Vec3
where
(Mat4 _ _ _ t) = fromProjective p
translate = translate4
instance Rotatable Transform3d Vec3 where
rotate orientationVector = if magnitude /= 0.0 then
rotateProj4 magnitude normal
else
id
where
magnitude = len orientationVector
normal = toNormalUnsafe $ orientationVector &* (1.0 / magnitude)
instance PerpProd Vec3 Vec3 where
perp = crossprod
instance Transform Transform3d Vec3
instance TransformSystem Transform3d Vec3 Vec3
newtype instance MVector s Vec3 = MV_Vec3 (MVector s (Double, Double, Double))
newtype instance Vector Vec3 = V_Vec3 (Vector (Double, Double, Double))
instance Unbox Vec3
instance M.MVector MVector Vec3 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_Vec3 v) = M.basicLength v
basicUnsafeSlice i n (MV_Vec3 v) = MV_Vec3 $ M.basicUnsafeSlice i n v
basicOverlaps (MV_Vec3 v1) (MV_Vec3 v2) = M.basicOverlaps v1 v2
basicUnsafeNew n = MV_Vec3 `liftM` M.basicUnsafeNew n
basicUnsafeReplicate n (Vec3 x y z) = MV_Vec3 `liftM` M.basicUnsafeReplicate n (x, y, z)
basicUnsafeRead (MV_Vec3 v) i = (\(x,y,z) -> Vec3 x y z) `liftM` M.basicUnsafeRead v i
basicUnsafeWrite (MV_Vec3 v) i (Vec3 x y z) = M.basicUnsafeWrite v i (x, y, z)
basicClear (MV_Vec3 v) = M.basicClear v
basicSet (MV_Vec3 v) (Vec3 x y z) = M.basicSet v (x, y, z)
basicUnsafeCopy (MV_Vec3 v1) (MV_Vec3 v2) = M.basicUnsafeCopy v1 v2
basicUnsafeGrow (MV_Vec3 v) n = MV_Vec3 `liftM` M.basicUnsafeGrow v n
instance G.Vector Vector Vec3 where
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicUnsafeFreeze (MV_Vec3 v) = V_Vec3 `liftM` G.basicUnsafeFreeze v
basicUnsafeThaw (V_Vec3 v) = MV_Vec3 `liftM` G.basicUnsafeThaw v
basicLength (V_Vec3 v) = G.basicLength v
basicUnsafeSlice i n (V_Vec3 v) = V_Vec3 $ G.basicUnsafeSlice i n v
basicUnsafeIndexM (V_Vec3 v) i = (\(x,y,z) -> Vec3 x y z) `liftM` G.basicUnsafeIndexM v i
basicUnsafeCopy (MV_Vec3 mv) (V_Vec3 v) = G.basicUnsafeCopy mv v
elemseq _ = seq
|
sebcrozet/falling3d
|
Physics/Falling3d/Transform3d.hs
|
Haskell
|
bsd-3-clause
| 3,759
|
module Data.Astro.TypesTest
(
tests
, testDecimalDegrees
, testDecimalHours
)
where
import Test.Framework (testGroup)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit
import Test.HUnit.Approx
import Test.QuickCheck
import Data.Ratio ((%))
import Data.Astro.Types
tests = [testGroup "DecimalDegrees <-> DecimalHours" [
testDecimalDegrees "12.03 H -> 180.45 D" 0.000001 (DD 180.45) $ fromDecimalHours (DH 12.03)
, testDecimalHours "180.45 D -> 12.03 H" 0.000001 (DH 12.03) $ toDecimalHours (DD 180.45)
, testProperty "property" prop_DHConversion
]
, testGroup "DecimalDegrees <-> Radians" [
testCase "0 -> 0 (rad)" $ assertApproxEqual "" 0.000000001 0 $ toRadians (DD 0)
, testCase "45 -> PI/4" $ assertApproxEqual "" 0.000000001 (pi*0.25) $ toRadians (DD 45)
, testCase "90 -> PI/2" $ assertApproxEqual "" 0.000000001 (pi*0.5) $ toRadians (DD 90)
, testCase "180 -> PI" $ assertApproxEqual "" 0.000000001 pi $ toRadians (DD 180)
, testCase "360 -> 2*PI" $ assertApproxEqual "" 0.000000001 (pi*2) $ toRadians (DD 360)
, testDecimalDegrees "0 -> 0 (deg)" 0.000000001 (DD 0) (fromRadians 0)
, testDecimalDegrees "pi/4 -> 45" 0.000000001 (DD 45) (fromRadians (pi*0.25))
, testDecimalDegrees "pi/2 -> 90" 0.000000001 (DD 90) (fromRadians (pi*0.5))
, testDecimalDegrees "pi -> 180" 0.000000001 (DD 180) (fromRadians pi)
, testDecimalDegrees "2*pi -> 360" 0.000000001 (DD 360) (fromRadians (pi*2))
]
, testGroup "DecimalDegrees <-> DMS" [
testDecimalDegrees "182 31' 27''" 0.00001 (DD 182.52417) $ fromDMS 182 31 27
, testCase "182.5" $ toDMS (DD 182.5) @?= (182, 30, 0)
, testProperty "property" prop_DMSConversion
]
, testGroup "DecimalHours <-> HMS" [
testDecimalHours "HMS -> DH 6:00" 0.00000001 (DH 6.0) (fromHMS 6 0 0)
, testDecimalHours "HMS -> DH 18:00" 0.00000001 (DH 18.0) (fromHMS 18 0 0)
, testDecimalHours "HMS -> DH 18:30" 0.00000001 (DH $ (18*2 + 1) / 2) (fromHMS 18 30 0)
, testDecimalHours "HMS -> DH 00:00:30" 0.00000001 (DH $ 30 / (60*60)) (fromHMS 0 0 30)
, testDecimalHours "HMS -> DH 00:00:10" 0.00000001 (DH 0.002777777778) $ fromHMS 0 0 10
, testDecimalHours "HMS -> DH 23:59:59.99999" 0.00000001 (DH 24.0) $ fromHMS 23 59 59.99999
, testCase "DH -> HMS 6:00" $ toHMS (DH 6.0) @?= (6, 0, 0)
, testCase "DH -> HMS 18:00" $ toHMS (DH 18.0) @?= (18, 0, 0)
, testCase "DH -> HMS 18:30" $ toHMS (DH $ (18*2 + 1) / 2) @?= (18, 30, 0)
, testCase "DH -> HMS 00:00:30" $ toHMS (DH $ (30 / (60*60))) @?= (0, 0, 30)
, testProperty "property" prop_HMSConversion
]
, testGroup "Light travel time" [
testDecimalHours "7.7 AU" 0.0000001 1.06722 (lightTravelTime 7.7)
]
, testGroup "KM <-> AU" [
testCase "KM -> AU" $ assertApproxEqual "" 1e-5 (AU 7.8) (kmToAU 1166863391.46)
, testCase "AU -> KM" $ assertApproxEqual "" 1e-5 1166863391.46 (auToKM 7.8)
]
, testGroup "DD: standard typeclasses" [
testCase "show" $ "DD 15.5" @=? show (DD 15.5)
, testCase "showList" $ "[DD 15.3,DD 15.7]" @=? showList [DD 15.3, DD 15.7] ""
, testCase "showsPrec" $ "DD 15.5" @=? showsPrec 0 (DD 15.5) ""
, testCase "== (True)" $ True @=? (DD 15.5) == (DD 15.5)
, testCase "== (False)" $ False @=? (DD 15.3) == (DD 15.5)
, testCase "/= (True)" $ True @=? (DD 15.3) /= (DD 15.5)
, testCase "/= (False)" $ False @=? (DD 15.5) /= (DD 15.5)
, testCase "compare: LT" $ LT @=? (DD 15.3) `compare` (DD 15.5)
, testCase "compare: EQ" $ EQ @=? (DD 15.5) `compare` (DD 15.5)
, testCase "compare: GT" $ GT @=? (DD 15.7) `compare` (DD 15.5)
, testCase "<" $ True @=? (DD 15.3) < (DD 15.7)
, testCase "<=" $ True @=? (DD 15.3) <= (DD 15.7)
, testCase ">" $ False @=? (DD 15.3) > (DD 15.7)
, testCase ">=" $ False @=? (DD 15.3) >= (DD 15.7)
, testCase "max" $ (DD 15.7) @=? max (DD 15.3) (DD 15.7)
, testCase "min" $ (DD 15.3) @=? min (DD 15.3) (DD 15.7)
, testCase "abs" $ (DD 15.7) @=? abs (DD (-15.7))
, testCase "signum > 0" $ (DD 1.0) @=? signum (DD 15.5)
, testCase "signum = 0" $ (DD 0.0) @=? signum (DD 0.0)
, testCase "signum < 0" $ (DD $ -1.0) @=? signum (DD $ -15.5)
, testCase "toRational" $ (31 % 2) @=? toRational (DD 15.5)
, testCase "recip" $ (DD 0.01) @=? recip (DD 100)
, testCase "properFraction" $ (15, DD 0.5) @=? properFraction (DD 15.5)
]
, testGroup "DH: standard typeclasses" [
testCase "show" $ "DH 15.5" @=? show (DH 15.5)
, testCase "showList" $ "[DH 15.3,DH 15.7]" @=? showList [DH 15.3, DH 15.7] ""
, testCase "showsPrec" $ "DH 15.5" @=? showsPrec 0 (DH 15.5) ""
, testCase "== (True)" $ True @=? (DH 15.5) == (DH 15.5)
, testCase "== (False)" $ False @=? (DH 15.3) == (DH 15.5)
, testCase "/= (True)" $ True @=? (DH 15.3) /= (DH 15.5)
, testCase "/= (False)" $ False @=? (DH 15.5) /= (DH 15.5)
, testCase "compare: LT" $ LT @=? (DH 15.3) `compare` (DH 15.5)
, testCase "compare: EQ" $ EQ @=? (DH 15.5) `compare` (DH 15.5)
, testCase "compare: GT" $ GT @=? (DH 15.7) `compare` (DH 15.5)
, testCase "<" $ True @=? (DH 15.3) < (DH 15.7)
, testCase "<=" $ True @=? (DH 15.3) <= (DH 15.7)
, testCase ">" $ False @=? (DH 15.3) > (DH 15.7)
, testCase ">=" $ False @=? (DH 15.3) >= (DH 15.7)
, testCase "max" $ (DH 15.7) @=? max (DH 15.3) (DH 15.7)
, testCase "min" $ (DH 15.3) @=? min (DH 15.3) (DH 15.7)
, testCase "abs" $ (DH 15.7) @=? abs (DH (-15.7))
, testCase "signum > 0" $ (DH 1.0) @=? signum (DH 15.5)
, testCase "signum = 0" $ (DH 0.0) @=? signum (DH 0.0)
, testCase "signum < 0" $ (DH $ -1.0) @=? signum (DH $ -15.5)
, testCase "toRational" $ (31 % 2) @=? toRational (DH 15.5)
, testCase "recip" $ (DH 0.01) @=? recip (DH 100)
, testCase "properFraction" $ (15, DH 0.5) @=? properFraction (DH 15.5)
]
, testGroup "AU: standard typeclasses" [
testCase "show" $ "AU 15.5" @=? show (AU 15.5)
, testCase "showList" $ "[AU 15.3,AU 15.7]" @=? showList [AU 15.3, AU 15.7] ""
, testCase "showsPrec" $ "AU 15.5" @=? showsPrec 0 (AU 15.5) ""
, testCase "== (True)" $ True @=? (AU 15.5) == (AU 15.5)
, testCase "== (False)" $ False @=? (AU 15.3) == (AU 15.5)
, testCase "/= (True)" $ True @=? (AU 15.3) /= (AU 15.5)
, testCase "/= (False)" $ False @=? (AU 15.5) /= (AU 15.5)
, testCase "compare: LT" $ LT @=? (AU 15.3) `compare` (AU 15.5)
, testCase "compare: EQ" $ EQ @=? (AU 15.5) `compare` (AU 15.5)
, testCase "compare: GT" $ GT @=? (AU 15.7) `compare` (AU 15.5)
, testCase "<" $ True @=? (AU 15.3) < (AU 15.7)
, testCase "<=" $ True @=? (AU 15.3) <= (AU 15.7)
, testCase ">" $ False @=? (AU 15.3) > (AU 15.7)
, testCase ">=" $ False @=? (AU 15.3) >= (AU 15.7)
, testCase "max" $ (AU 15.7) @=? max (AU 15.3) (AU 15.7)
, testCase "min" $ (AU 15.3) @=? min (AU 15.3) (AU 15.7)
, testCase "+" $ (AU 17.5) @=? (AU 15.5) + (AU 2)
, testCase "-" $ (AU 13.5) @=? (AU 15.5) - (AU 2)
, testCase "*" $ (AU 31) @=? (AU 15.5) * (AU 2)
, testCase "negate" $ (AU 15.5) @=? negate (AU $ -15.5)
, testCase "abs" $ (AU 15.7) @=? abs (AU (-15.7))
, testCase "signum > 0" $ (AU 1.0) @=? signum (AU 15.5)
, testCase "signum = 0" $ (AU 0.0) @=? signum (AU 0.0)
, testCase "signum < 0" $ (AU $ -1.0) @=? signum (AU $ -15.5)
, testCase "fromInteger" $ (AU 17) @=? fromInteger 17
, testCase "toRational" $ (31 % 2) @=? toRational (AU 15.5)
, testCase "/" $ (AU 10) @=? (AU 30) / (AU 3)
, testCase "recip" $ (AU 0.01) @=? recip (AU 100)
, testCase "properFraction" $ (15, AU 0.5) @=? properFraction (AU 15.5)
]
]
testDecimalDegrees msg eps (DD expected) (DD actual) =
testCase msg $ assertApproxEqual "" eps expected actual
testDecimalHours msg eps (DH expected) (DH actual) =
testCase msg $ assertApproxEqual "" eps expected actual
prop_DHConversion n =
let DH h = toDecimalHours . fromDecimalHours $ DH n
DD d = fromDecimalHours . toDecimalHours $ DD n
eps = 0.00000001
in abs(n-h) < eps && abs(n-d) < eps
where types = (n::Double)
prop_DMSConversion dd =
let (d, m, s) = toDMS $ DD dd
DD d' = fromDMS d m s
in abs(dd-d') < 0.0000001
where types = (dd::Double)
prop_HMSConversion =
forAll (choose (0, 1.0)) $ checkHMSConversionProperties
checkHMSConversionProperties :: Double -> Bool
checkHMSConversionProperties n =
let (h, m, s) = toHMS $ DH n
DH n2 = fromHMS h m s
in abs (n-n2) < 0.00000001
|
Alexander-Ignatyev/astro
|
test/Data/Astro/TypesTest.hs
|
Haskell
|
bsd-3-clause
| 9,736
|
module Foreign.Storable.OrphansSpec (main, spec) where
import Test.Hspec
import Data.Complex
import Data.Orphans ()
import Data.Ratio
import Foreign.Storable
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Storable Complex instance" $ do
it "has twice the sizeOf its realPart" $ do
sizeOf ((1 :: Double) :+ 2) `shouldBe` 2*sizeOf (1 :: Double)
it "has the alignment of its realPart" $ do
alignment ((1 :: Double) :+ 2) `shouldBe` alignment (1 :: Double)
describe "Storable Ratio instance" $ do
it "has twice the sizeOf its parameterized type" $ do
sizeOf ((1 :: Int) % 2) `shouldBe` 2*sizeOf (1 :: Int)
it "has the alignment of its parameterized type" $ do
alignment ((1 :: Int) % 2) `shouldBe` alignment (1 :: Int)
|
phadej/base-orphans
|
test/Foreign/Storable/OrphansSpec.hs
|
Haskell
|
mit
| 781
|
{-# LANGUAGE OverloadedStrings #-}
module Foreign.JavaScript.V8.ContextSpec (main, spec) where
import Test.Hspec
import Data.String.Builder (build)
import Control.Monad (replicateM_)
import Control.Exception (bracket)
import Foreign.JavaScript.V8
import Foreign.JavaScript.V8.Value (numberOfHandles)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Context" $ do
describe "contextNew" $ do
it "takes a template for the global object" $ do
withHandleScope $ do
t <- mkObjectTemplate
objectTemplateAddFunction t "reverse" jsReverse
objectTemplateAddFunction t "concat" jsConcat
bracket (contextNew t) dispose $ \c -> do
withContextScope c $ do
(runScript "reverse('foo')" >>= toString) `shouldReturn` "oof"
(runScript "concat('foo', 'bar')" >>= toString) `shouldReturn` "foobar"
it "does not leak handles" $ do
withHandleScope $ do
t <- mkObjectTemplate
numberOfHandles `shouldReturn` 1
c <- contextNew t
numberOfHandles `shouldReturn` 1
dispose c
describe "dispose" $ do
it "disposes the associated object template" $ do
withHandleScope $ do
t <- mkObjectTemplate
contextNew t >>= dispose
dispose t `shouldThrow` (== AlreadyDisposed)
it "can share values with other contexts" $ do
withHandleScope $ do
c1 <- mkObjectTemplate >>= contextNew
v <- withContextScope c1 $ do
runScript "'bar'"
t <- mkObjectTemplate
objectTemplateAddFunction t "foo" $ \_ -> do
return v
bracket (contextNew t) dispose $ \c2 -> do
withContextScope c2 $ do
(runScript "foo()" >>= toString) `shouldReturn` "bar"
dispose c1
it "can share objects with other contexts" $ do
withHandleScope $ do
c1 <- mkObjectTemplate >>= contextNew
v <- withContextScope c1 $ do
runScript . build $ do
"var foo = new Object()"
"foo.bar = 23"
"foo"
t <- mkObjectTemplate
objectTemplateAddFunction t "foo" $ \_ -> do
return v
bracket (contextNew t) dispose $ \c2 -> do
withContextScope c2 $ do
(runScript "foo().bar" >>= toString) `shouldReturn` "23"
dispose c1
describe "objectTemplateAddFunction" $ do
context "when the native function is called" $ do
it "does not leak handles" $ do
withHandleScope $ do
t <- mkObjectTemplate
objectTemplateAddFunction t "foo" $ \_ -> do
n <- numberOfHandles
replicateM_ 10 (runScript "new Object();")
numberOfHandles `shouldReturn` (n + 10)
mkUndefined
bracket (contextNew t) dispose $ \c -> withContextScope c $ do
numberOfHandles `shouldReturn` 1
_ <- runScript "foo()"
numberOfHandles `shouldReturn` 2
where
jsReverse args = do
s <- argumentsGet 0 args >>= toString
mkString (reverse s)
jsConcat args = do
a <- argumentsGet 0 args >>= toString
b <- argumentsGet 1 args >>= toString
mkString (a ++ b)
|
sol/v8
|
test/Foreign/JavaScript/V8/ContextSpec.hs
|
Haskell
|
mit
| 3,307
|
{-# LANGUAGE OverloadedStrings #-}
module Dashdo.Rdash (rdash, charts, controls, defaultSidebar, Sidebar(..)) where
import Dashdo.Types
import Lucid
import Lucid.Bootstrap3
import qualified Lucid.Rdash as RD
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Text hiding (map, intersperse, length)
import Data.Monoid
import Control.Applicative ((<$>))
sidebarMain :: Sidebar -> Html ()
sidebarMain sb = a_ [href_ "#"] $ do
toHtml $ title sb
span_ [class_ "menu-icon glyphicon glyphicon-transfer"] (return ())
sidebarList :: [RDashdo m] -> [RD.SidebarItem]
sidebarList rdashdos = (sidebarListItem <$> rdashdos) -- <> [div_ [id_ "dashdo-sidebar"] mempty ]
where
sidebarListItem = \rd ->
RD.SidebarLink (rdTitle rd) (pack $ rdFid rd) "tachometer"
data Sidebar = Sidebar
{ title:: T.Text
, subTitle:: T.Text
, footer:: Html ()
}
defaultSidebar :: Sidebar
defaultSidebar = Sidebar "Dashdo" "Dashboards" $ rowEven XS
[ a_ [href_ "https://github.com/diffusionkinetics/open/dashdo"] (i_ [class_ "fa fa-lg fa-github"] mempty <> "Github")
, a_ [href_ "#"] $ i_ [id_ "spinner", class_ "fa fa-cog fa-2x"] mempty
]
rdash :: [RDashdo m] -> Html () -> Sidebar -> TL.Text
rdash rdashdos headExtra sb = do
renderText $ doctypehtml_ $ do
head_ $ do
meta_ [charset_ "utf-8"]
meta_ [name_ "viewport", content_ "width=device-width"] -- TODO: add attribute initial-scale=1
-- If href doesn't end with a slash, redirect to the one with slashes
-- this is needed to make relative urls work
script_ $ T.unlines
[ "if (!window.location.href.match(/\\/$/)) {"
, " window.location.href = window.location.href + '/';"
, "}"
]
cdnFontAwesome
cdnCSS
RD.rdashCSS
cdnJqueryJS
headExtra
body_ $ do
let sb' = (RD.mkSidebar (sidebarMain sb) $ sidebarList rdashdos) <> div_ [id_ "dashdo-sidebar"] mempty
sbf = RD.mkSidebarFooter $ footer sb
sbw = RD.mkSidebarWrapper sb' sbf
cw = RD.mkPageContent $ do
RD.mkHeaderBar [RD.mkMetaBox [RD.mkMetaTitle (span_ [id_ "dashdo-title"] mempty)]]
div_ [id_ "dashdo-main"] mempty
pgw = form_ [id_ "dashdo-form", method_ "post"] $ RD.mkPageWrapperOpen sbw cw
--RD.mkIndexPage (RD.mkHead "Dashdo") (
pgw
cdnBootstrapJS
script_ [src_ "js/dashdo.js"] ("" :: Text)
script_ [src_ "js/runners/rdashdo.js"] ("" :: Text)
controls :: Monad m => HtmlT m () -> HtmlT m ()
controls content = do
div_ [class_ "row"] $
mkCol [(XS, 12), (MD, 12)] $
div_ [class_ "widget"] $ do
div_ [class_ "widget-header"] "Settings"
div_ [class_ "widget-body"] $
div_ [class_ "widget-content"] $
content
charts :: Monad m =>[(Text, HtmlT m ())] -> HtmlT m ()
charts cs = do
div_ [class_ "row"] $ sequence_ widgets
where
widgets = map widget cs
widget = \(titl, content) -> do
mkCol [(XS, 12), (MD, 12 `div` length cs)] $
div_ [class_ "widget"] $ do
div_ [class_ "widget-header"] (toHtml titl)
div_ [class_ "widget-body no-padding"] $
div_ [class_ "widget-content"] $
content
|
diffusionkinetics/open
|
dashdo/src/Dashdo/Rdash.hs
|
Haskell
|
mit
| 3,346
|
<?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>Code Dx | 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>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_az_AZ/helpset_az_AZ.hs
|
Haskell
|
apache-2.0
| 969
|
{-# LANGUAGE RankNTypes, FlexibleContexts #-}
{-| Implementation of functions specific to configuration management.
-}
{-
Copyright (C) 2013, 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.WConfd.ConfigWriter
( loadConfigFromFile
, readConfig
, writeConfig
, saveConfigAsyncTask
, distMCsAsyncTask
, distSSConfAsyncTask
) where
import Control.Applicative
import Control.Monad.Base
import Control.Monad.Error
import qualified Control.Monad.State.Strict as S
import Control.Monad.Trans.Control
import Data.Monoid
import Ganeti.BasicTypes
import Ganeti.Errors
import Ganeti.Config
import Ganeti.Logging
import Ganeti.Objects
import Ganeti.Rpc
import Ganeti.Runtime
import Ganeti.Utils
import Ganeti.Utils.Atomic
import Ganeti.Utils.AsyncWorker
import Ganeti.WConfd.ConfigState
import Ganeti.WConfd.Monad
import Ganeti.WConfd.Ssconf
-- | Loads the configuration from the file, if it hasn't been loaded yet.
-- The function is internal and isn't thread safe.
loadConfigFromFile :: FilePath
-> ResultG (ConfigData, FStat)
loadConfigFromFile path = withLockedFile path $ \_ -> do
stat <- liftBase $ getFStat path
cd <- mkResultT (loadConfig path)
return (cd, stat)
-- | Writes the current configuration to the file. The function isn't thread
-- safe.
-- Neither distributes the configuration (to nodes and ssconf) nor
-- updates the serial number.
writeConfigToFile :: (MonadBase IO m, MonadError GanetiException m, MonadLog m)
=> ConfigData -> FilePath -> FStat -> m FStat
writeConfigToFile cfg path oldstat = do
logDebug $ "Async. config. writer: Commencing write\
\ serial no " ++ show (serialOf cfg)
r <- toErrorBase $ atomicUpdateLockedFile_ path oldstat doWrite
logDebug "Async. config. writer: written"
return r
where
doWrite fname fh = do
setOwnerAndGroupFromNames fname GanetiWConfd
(DaemonGroup GanetiConfd)
setOwnerWGroupR fname
saveConfig fh cfg
-- Reads the current configuration state in the 'WConfdMonad'.
readConfig :: WConfdMonad ConfigData
readConfig = csConfigData <$> readConfigState
-- Replaces the current configuration state within the 'WConfdMonad'.
writeConfig :: ConfigData -> WConfdMonad ()
writeConfig cd = modifyConfigState $ const ((), mkConfigState cd)
-- * Asynchronous tasks
-- | Runs the given action on success, or logs an error on failure.
finishOrLog :: (Show e, MonadLog m)
=> Priority
-> String
-> (a -> m ())
-> GenericResult e a
-> m ()
finishOrLog logPrio logPrefix =
genericResult (logAt logPrio . (++) (logPrefix ++ ": ") . show)
-- | Creates a stateless asynchronous task that handles errors in its actions.
mkStatelessAsyncTask :: (MonadBaseControl IO m, MonadLog m, Show e, Monoid i)
=> Priority
-> String
-> (i -> ResultT e m ())
-> m (AsyncWorker i ())
mkStatelessAsyncTask logPrio logPrefix action =
mkAsyncWorker $ runResultT . action
>=> finishOrLog logPrio logPrefix return
-- | Creates an asynchronous task that handles errors in its actions.
-- If an error occurs, it's logged and the internal state remains unchanged.
mkStatefulAsyncTask :: (MonadBaseControl IO m, MonadLog m, Show e, Monoid i)
=> Priority
-> String
-> s
-> (s -> i -> ResultT e m s)
-> m (AsyncWorker i ())
mkStatefulAsyncTask logPrio logPrefix start action =
flip S.evalStateT start . mkAsyncWorker $ \i ->
S.get >>= lift . runResultT . flip action i
>>= finishOrLog logPrio logPrefix S.put -- put on success
-- | Construct an asynchronous worker whose action is to save the
-- configuration to the master file.
-- The worker's action reads the configuration using the given @IO@ action
-- and uses 'FStat' to check if the configuration hasn't been modified by
-- another process.
--
-- If 'Any' of the input requests is true, given additional worker
-- will be executed synchronously after sucessfully writing the configuration
-- file. Otherwise, they'll be just triggered asynchronously.
saveConfigAsyncTask :: FilePath -- ^ Path to the config file
-> FStat -- ^ The initial state of the config. file
-> IO ConfigState -- ^ An action to read the current config
-> [AsyncWorker () ()] -- ^ Workers to be triggered
-- afterwards
-> ResultG (AsyncWorker Any ())
saveConfigAsyncTask fpath fstat cdRef workers =
lift . mkStatefulAsyncTask
EMERGENCY "Can't write the master configuration file" fstat
$ \oldstat (Any flush) -> do
cd <- liftBase (csConfigData `liftM` cdRef)
writeConfigToFile cd fpath oldstat
<* if flush then logDebug "Running distribution synchronously"
>> triggerAndWaitMany_ workers
else logDebug "Running distribution asynchronously"
>> mapM trigger_ workers
-- | Performs a RPC call on the given list of nodes and logs any failures.
-- If any of the calls fails, fail the computation with 'failError'.
execRpcCallAndLog :: (Rpc a b) => [Node] -> a -> ResultG ()
execRpcCallAndLog nodes req = do
rs <- liftIO $ executeRpcCall nodes req
es <- logRpcErrors rs
unless (null es) $ failError "At least one of the RPC calls failed"
-- | Construct an asynchronous worker whose action is to distribute the
-- configuration to master candidates.
distMCsAsyncTask :: RuntimeEnts
-> FilePath -- ^ Path to the config file
-> IO ConfigState -- ^ An action to read the current config
-> ResultG (AsyncWorker () ())
distMCsAsyncTask ents cpath cdRef =
lift . mkStatelessAsyncTask ERROR "Can't distribute the configuration\
\ to master candidates"
$ \_ -> do
cd <- liftBase (csConfigData <$> cdRef) :: ResultG ConfigData
logDebug $ "Distributing the configuration to master candidates,\
\ serial no " ++ show (serialOf cd)
fupload <- prepareRpcCallUploadFile ents cpath
execRpcCallAndLog (getMasterCandidates cd) fupload
logDebug "Successfully finished distributing the configuration"
-- | Construct an asynchronous worker whose action is to construct SSConf
-- and distribute it to master candidates.
-- The worker's action reads the configuration using the given @IO@ action,
-- computes the current SSConf, compares it to the previous version, and
-- if different, distributes it.
distSSConfAsyncTask
:: IO ConfigState -- ^ An action to read the current config
-> ResultG (AsyncWorker () ())
distSSConfAsyncTask cdRef =
lift . mkStatefulAsyncTask ERROR "Can't distribute Ssconf" emptySSConf
$ \oldssc _ -> do
cd <- liftBase (csConfigData <$> cdRef) :: ResultG ConfigData
let ssc = mkSSConf cd
if oldssc == ssc
then logDebug "SSConf unchanged, not distributing"
else do
logDebug $ "Starting the distribution of SSConf\
\ serial no " ++ show (serialOf cd)
execRpcCallAndLog (getOnlineNodes cd)
(RpcCallWriteSsconfFiles ssc)
logDebug "Successfully finished distributing SSConf"
return ssc
|
bitemyapp/ganeti
|
src/Ganeti/WConfd/ConfigWriter.hs
|
Haskell
|
bsd-2-clause
| 8,861
|
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Generate.Index (toHtml, getInfo, getPkg) where
import Control.Monad
import Control.Monad.Except (ExceptT, liftIO, runExceptT, throwError)
import Data.Aeson as Json
import qualified Data.ByteString.Lazy.UTF8 as BSU8
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Elm.Package as Pkg
import qualified Elm.Package.Description as Desc
import qualified Elm.Package.Paths as Paths
import qualified Elm.Package.Solution as S
import System.Directory (doesDirectoryExist, doesFileExist, getDirectoryContents)
import System.FilePath ((</>), splitDirectories, takeExtension)
import qualified Text.Blaze.Html5 as H
import qualified Generate.Help as Help
import qualified StaticFiles
-- INFO
data Info = Info
{ _pwd :: [String]
, _dirs :: [FilePath]
, _files :: [(FilePath, Bool)]
, _pkg :: Maybe PackageInfo
, _readme :: Maybe String
}
data PackageInfo = PackageInfo
{ _version :: Pkg.Version
, _repository :: String
, _summary :: String
, _dependencies :: [(Pkg.Name, Pkg.Version)]
}
-- TO JSON
instance ToJSON Info where
toJSON info =
object
[ "pwd" .= _pwd info
, "dirs" .= _dirs info
, "files" .= _files info
, "pkg" .= _pkg info
, "readme" .= _readme info
]
instance ToJSON PackageInfo where
toJSON pkgInfo =
object
[ "version" .= _version pkgInfo
, "repository" .= _repository pkgInfo
, "summary" .= _summary pkgInfo
, "dependencies" .= _dependencies pkgInfo
]
-- GENERATE HTML
toHtml :: Info -> H.Html
toHtml info@(Info pwd _ _ _ _) =
Help.makeHtml
(List.intercalate "/" ("~" : pwd))
("/" ++ StaticFiles.indexPath)
("Elm.Index.fullscreen(" ++ BSU8.toString (Json.encode info) ++ ");")
-- GET INFO FOR THIS LOCATION
getInfo :: FilePath -> IO Info
getInfo directory =
do packageInfo <- getPackageInfo
(dirs, files) <- getDirectoryInfo directory
readme <- getReadme directory
return $ Info
{ _pwd = toPwd directory
, _dirs = dirs
, _files = files
, _pkg = packageInfo
, _readme = readme
}
toPwd :: FilePath -> [String]
toPwd directory =
case splitDirectories directory of
"." : path ->
path
path ->
path
getPackageInfo :: IO (Maybe PackageInfo)
getPackageInfo =
fmap (either (const Nothing) Just) $ runExceptT $
do
desc <- getDescription
solutionExists <- liftIO (doesFileExist Paths.solvedDependencies)
when (not solutionExists) (throwError "file not found")
solution <- S.read id Paths.solvedDependencies
let publicSolution =
Map.intersection solution (Map.fromList (Desc.dependencies desc))
return $ PackageInfo
{ _version = Desc.version desc
, _repository = Desc.repo desc
, _summary = Desc.summary desc
, _dependencies = Map.toList publicSolution
}
getDescription :: ExceptT String IO Desc.Description
getDescription =
do descExists <- liftIO (doesFileExist Paths.description)
when (not descExists) (throwError "file not found")
Desc.read id Paths.description
getPkg :: IO Pkg.Name
getPkg =
fmap
(either (const Pkg.dummyName) Desc.name)
(runExceptT getDescription)
getDirectoryInfo :: FilePath -> IO ([FilePath], [(FilePath, Bool)])
getDirectoryInfo directory =
do directoryContents <-
getDirectoryContents directory
allDirectories <-
filterM (doesDirectoryExist . (directory </>)) directoryContents
let isLegit name =
List.notElem name [".", "..", "elm-stuff"]
let directories =
filter isLegit allDirectories
rawFiles <-
filterM (doesFileExist . (directory </>)) directoryContents
files <- mapM (inspectFile directory) rawFiles
return (directories, files)
inspectFile :: FilePath -> FilePath -> IO (FilePath, Bool)
inspectFile directory filePath =
if takeExtension filePath == ".elm" then
do source <- Text.readFile (directory </> filePath)
let hasMain = Text.isInfixOf "\nmain " source
return (filePath, hasMain)
else
return (filePath, False)
getReadme :: FilePath -> IO (Maybe String)
getReadme directory =
do exists <- doesFileExist (directory </> "README.md")
if exists
then
Just `fmap` readFile (directory </> "README.md")
else
return Nothing
|
rehno-lindeque/elm-reactor
|
src/backend/Generate/Index.hs
|
Haskell
|
bsd-3-clause
| 4,630
|
{-
(c) The University of Glasgow, 1994-2006
Core pass to saturate constructors and PrimOps
-}
{-# LANGUAGE BangPatterns, CPP #-}
module CorePrep (
corePrepPgm, corePrepExpr, cvtLitInteger,
lookupMkIntegerName, lookupIntegerSDataConName
) where
#include "HsVersions.h"
import OccurAnal
import HscTypes
import PrelNames
import MkId ( realWorldPrimId )
import CoreUtils
import CoreArity
import CoreFVs
import CoreMonad ( CoreToDo(..) )
import CoreLint ( endPassIO )
import CoreSyn
import CoreSubst
import MkCore hiding( FloatBind(..) ) -- We use our own FloatBind here
import Type
import Literal
import Coercion
import TcEnv
import TyCon
import Demand
import Var
import VarSet
import VarEnv
import Id
import IdInfo
import TysWiredIn
import DataCon
import PrimOp
import BasicTypes
import Module
import UniqSupply
import Maybes
import OrdList
import ErrUtils
import DynFlags
import Util
import Pair
import Outputable
import Platform
import FastString
import Config
import Name ( NamedThing(..), nameSrcSpan )
import SrcLoc ( SrcSpan(..), realSrcLocSpan, mkRealSrcLoc )
import Data.Bits
import MonadUtils ( mapAccumLM )
import Data.List ( mapAccumL )
import Control.Monad
{-
-- ---------------------------------------------------------------------------
-- Overview
-- ---------------------------------------------------------------------------
The goal of this pass is to prepare for code generation.
1. Saturate constructor and primop applications.
2. Convert to A-normal form; that is, function arguments
are always variables.
* Use case for strict arguments:
f E ==> case E of x -> f x
(where f is strict)
* Use let for non-trivial lazy arguments
f E ==> let x = E in f x
(were f is lazy and x is non-trivial)
3. Similarly, convert any unboxed lets into cases.
[I'm experimenting with leaving 'ok-for-speculation'
rhss in let-form right up to this point.]
4. Ensure that *value* lambdas only occur as the RHS of a binding
(The code generator can't deal with anything else.)
Type lambdas are ok, however, because the code gen discards them.
5. [Not any more; nuked Jun 2002] Do the seq/par munging.
6. Clone all local Ids.
This means that all such Ids are unique, rather than the
weaker guarantee of no clashes which the simplifier provides.
And that is what the code generator needs.
We don't clone TyVars or CoVars. The code gen doesn't need that,
and doing so would be tiresome because then we'd need
to substitute in types and coercions.
7. Give each dynamic CCall occurrence a fresh unique; this is
rather like the cloning step above.
8. Inject bindings for the "implicit" Ids:
* Constructor wrappers
* Constructor workers
We want curried definitions for all of these in case they
aren't inlined by some caller.
9. Replace (lazy e) by e. See Note [lazyId magic] in MkId.hs
Also replace (noinline e) by e.
10. Convert (LitInteger i t) into the core representation
for the Integer i. Normally this uses mkInteger, but if
we are using the integer-gmp implementation then there is a
special case where we use the S# constructor for Integers that
are in the range of Int.
11. Uphold tick consistency while doing this: We move ticks out of
(non-type) applications where we can, and make sure that we
annotate according to scoping rules when floating.
This is all done modulo type applications and abstractions, so that
when type erasure is done for conversion to STG, we don't end up with
any trivial or useless bindings.
Invariants
~~~~~~~~~~
Here is the syntax of the Core produced by CorePrep:
Trivial expressions
triv ::= lit | var
| triv ty | /\a. triv
| truv co | /\c. triv | triv |> co
Applications
app ::= lit | var | app triv | app ty | app co | app |> co
Expressions
body ::= app
| let(rec) x = rhs in body -- Boxed only
| case body of pat -> body
| /\a. body | /\c. body
| body |> co
Right hand sides (only place where value lambdas can occur)
rhs ::= /\a.rhs | \x.rhs | body
We define a synonym for each of these non-terminals. Functions
with the corresponding name produce a result in that syntax.
-}
type CpeTriv = CoreExpr -- Non-terminal 'triv'
type CpeApp = CoreExpr -- Non-terminal 'app'
type CpeBody = CoreExpr -- Non-terminal 'body'
type CpeRhs = CoreExpr -- Non-terminal 'rhs'
{-
************************************************************************
* *
Top level stuff
* *
************************************************************************
-}
corePrepPgm :: HscEnv -> Module -> ModLocation -> CoreProgram -> [TyCon]
-> IO CoreProgram
corePrepPgm hsc_env this_mod mod_loc binds data_tycons =
withTiming (pure dflags)
(text "CorePrep"<+>brackets (ppr this_mod))
(const ()) $ do
us <- mkSplitUniqSupply 's'
initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
let implicit_binds = mkDataConWorkers dflags mod_loc data_tycons
-- NB: we must feed mkImplicitBinds through corePrep too
-- so that they are suitably cloned and eta-expanded
binds_out = initUs_ us $ do
floats1 <- corePrepTopBinds initialCorePrepEnv binds
floats2 <- corePrepTopBinds initialCorePrepEnv implicit_binds
return (deFloatTop (floats1 `appendFloats` floats2))
endPassIO hsc_env alwaysQualify CorePrep binds_out []
return binds_out
where
dflags = hsc_dflags hsc_env
corePrepExpr :: DynFlags -> HscEnv -> CoreExpr -> IO CoreExpr
corePrepExpr dflags hsc_env expr =
withTiming (pure dflags) (text "CorePrep [expr]") (const ()) $ do
us <- mkSplitUniqSupply 's'
initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
let new_expr = initUs_ us (cpeBodyNF initialCorePrepEnv expr)
dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" (ppr new_expr)
return new_expr
corePrepTopBinds :: CorePrepEnv -> [CoreBind] -> UniqSM Floats
-- Note [Floating out of top level bindings]
corePrepTopBinds initialCorePrepEnv binds
= go initialCorePrepEnv binds
where
go _ [] = return emptyFloats
go env (bind : binds) = do (env', bind') <- cpeBind TopLevel env bind
binds' <- go env' binds
return (bind' `appendFloats` binds')
mkDataConWorkers :: DynFlags -> ModLocation -> [TyCon] -> [CoreBind]
-- See Note [Data constructor workers]
-- c.f. Note [Injecting implicit bindings] in TidyPgm
mkDataConWorkers dflags mod_loc data_tycons
= [ NonRec id (tick_it (getName data_con) (Var id))
-- The ice is thin here, but it works
| tycon <- data_tycons, -- CorePrep will eta-expand it
data_con <- tyConDataCons tycon,
let id = dataConWorkId data_con
]
where
-- If we want to generate debug info, we put a source note on the
-- worker. This is useful, especially for heap profiling.
tick_it name
| debugLevel dflags == 0 = id
| RealSrcSpan span <- nameSrcSpan name = tick span
| Just file <- ml_hs_file mod_loc = tick (span1 file)
| otherwise = tick (span1 "???")
where tick span = Tick (SourceNote span $ showSDoc dflags (ppr name))
span1 file = realSrcLocSpan $ mkRealSrcLoc (mkFastString file) 1 1
{-
Note [Floating out of top level bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NB: we do need to float out of top-level bindings
Consider x = length [True,False]
We want to get
s1 = False : []
s2 = True : s1
x = length s2
We return a *list* of bindings, because we may start with
x* = f (g y)
where x is demanded, in which case we want to finish with
a = g y
x* = f a
And then x will actually end up case-bound
Note [CafInfo and floating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
What happens when we try to float bindings to the top level? At this
point all the CafInfo is supposed to be correct, and we must make certain
that is true of the new top-level bindings. There are two cases
to consider
a) The top-level binding is marked asCafRefs. In that case we are
basically fine. The floated bindings had better all be lazy lets,
so they can float to top level, but they'll all have HasCafRefs
(the default) which is safe.
b) The top-level binding is marked NoCafRefs. This really happens
Example. CoreTidy produces
$fApplicativeSTM [NoCafRefs] = D:Alternative retry# ...blah...
Now CorePrep has to eta-expand to
$fApplicativeSTM = let sat = \xy. retry x y
in D:Alternative sat ...blah...
So what we *want* is
sat [NoCafRefs] = \xy. retry x y
$fApplicativeSTM [NoCafRefs] = D:Alternative sat ...blah...
So, gruesomely, we must set the NoCafRefs flag on the sat bindings,
*and* substutite the modified 'sat' into the old RHS.
It should be the case that 'sat' is itself [NoCafRefs] (a value, no
cafs) else the original top-level binding would not itself have been
marked [NoCafRefs]. The DEBUG check in CoreToStg for
consistentCafInfo will find this.
This is all very gruesome and horrible. It would be better to figure
out CafInfo later, after CorePrep. We'll do that in due course.
Meanwhile this horrible hack works.
Note [Data constructor workers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create any necessary "implicit" bindings for data con workers. We
create the rather strange (non-recursive!) binding
$wC = \x y -> $wC x y
i.e. a curried constructor that allocates. This means that we can
treat the worker for a constructor like any other function in the rest
of the compiler. The point here is that CoreToStg will generate a
StgConApp for the RHS, rather than a call to the worker (which would
give a loop). As Lennart says: the ice is thin here, but it works.
Hmm. Should we create bindings for dictionary constructors? They are
always fully applied, and the bindings are just there to support
partial applications. But it's easier to let them through.
Note [Dead code in CorePrep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Imagine that we got an input program like this (see Trac #4962):
f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
f x = (g True (Just x) + g () (Just x), g)
where
g :: Show a => a -> Maybe Int -> Int
g _ Nothing = x
g y (Just z) = if z > 100 then g y (Just (z + length (show y))) else g y unknown
After specialisation and SpecConstr, we would get something like this:
f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
f x = (g$Bool_True_Just x + g$Unit_Unit_Just x, g)
where
{-# RULES g $dBool = g$Bool
g $dUnit = g$Unit #-}
g = ...
{-# RULES forall x. g$Bool True (Just x) = g$Bool_True_Just x #-}
g$Bool = ...
{-# RULES forall x. g$Unit () (Just x) = g$Unit_Unit_Just x #-}
g$Unit = ...
g$Bool_True_Just = ...
g$Unit_Unit_Just = ...
Note that the g$Bool and g$Unit functions are actually dead code: they
are only kept alive by the occurrence analyser because they are
referred to by the rules of g, which is being kept alive by the fact
that it is used (unspecialised) in the returned pair.
However, at the CorePrep stage there is no way that the rules for g
will ever fire, and it really seems like a shame to produce an output
program that goes to the trouble of allocating a closure for the
unreachable g$Bool and g$Unit functions.
The way we fix this is to:
* In cloneBndr, drop all unfoldings/rules
* In deFloatTop, run a simple dead code analyser on each top-level
RHS to drop the dead local bindings. For that call to OccAnal, we
disable the binder swap, else the occurrence analyser sometimes
introduces new let bindings for cased binders, which lead to the bug
in #5433.
The reason we don't just OccAnal the whole output of CorePrep is that
the tidier ensures that all top-level binders are GlobalIds, so they
don't show up in the free variables any longer. So if you run the
occurrence analyser on the output of CoreTidy (or later) you e.g. turn
this program:
Rec {
f = ... f ...
}
Into this one:
f = ... f ...
(Since f is not considered to be free in its own RHS.)
************************************************************************
* *
The main code
* *
************************************************************************
-}
cpeBind :: TopLevelFlag -> CorePrepEnv -> CoreBind
-> UniqSM (CorePrepEnv, Floats)
cpeBind top_lvl env (NonRec bndr rhs)
= do { (_, bndr1) <- cpCloneBndr env bndr
; let dmd = idDemandInfo bndr
is_unlifted = isUnliftedType (idType bndr)
; (floats, bndr2, rhs2) <- cpePair top_lvl NonRecursive
dmd
is_unlifted
env bndr1 rhs
-- See Note [Inlining in CorePrep]
; if cpe_ExprIsTrivial rhs2 && isNotTopLevel top_lvl
then return (extendCorePrepEnvExpr env bndr rhs2, floats)
else do {
; let new_float = mkFloat dmd is_unlifted bndr2 rhs2
-- We want bndr'' in the envt, because it records
-- the evaluated-ness of the binder
; return (extendCorePrepEnv env bndr bndr2,
addFloat floats new_float) }}
cpeBind top_lvl env (Rec pairs)
= do { let (bndrs,rhss) = unzip pairs
; (env', bndrs1) <- cpCloneBndrs env (map fst pairs)
; stuff <- zipWithM (cpePair top_lvl Recursive topDmd False env') bndrs1 rhss
; let (floats_s, bndrs2, rhss2) = unzip3 stuff
all_pairs = foldrOL add_float (bndrs2 `zip` rhss2)
(concatFloats floats_s)
; return (extendCorePrepEnvList env (bndrs `zip` bndrs2),
unitFloat (FloatLet (Rec all_pairs))) }
where
-- Flatten all the floats, and the currrent
-- group into a single giant Rec
add_float (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
add_float (FloatLet (Rec prs1)) prs2 = prs1 ++ prs2
add_float b _ = pprPanic "cpeBind" (ppr b)
---------------
cpePair :: TopLevelFlag -> RecFlag -> Demand -> Bool
-> CorePrepEnv -> Id -> CoreExpr
-> UniqSM (Floats, Id, CpeRhs)
-- Used for all bindings
cpePair top_lvl is_rec dmd is_unlifted env bndr rhs
= do { (floats1, rhs1) <- cpeRhsE env rhs
-- See if we are allowed to float this stuff out of the RHS
; (floats2, rhs2) <- float_from_rhs floats1 rhs1
-- Make the arity match up
; (floats3, rhs3)
<- if manifestArity rhs1 <= arity
then return (floats2, cpeEtaExpand arity rhs2)
else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
-- Note [Silly extra arguments]
(do { v <- newVar (idType bndr)
; let float = mkFloat topDmd False v rhs2
; return ( addFloat floats2 float
, cpeEtaExpand arity (Var v)) })
-- Wrap floating ticks
; let (floats4, rhs4) = wrapTicks floats3 rhs3
-- Record if the binder is evaluated
-- and otherwise trim off the unfolding altogether
-- It's not used by the code generator; getting rid of it reduces
-- heap usage and, since we may be changing uniques, we'd have
-- to substitute to keep it right
; let bndr' | exprIsHNF rhs3 = bndr `setIdUnfolding` evaldUnfolding
| otherwise = bndr `setIdUnfolding` noUnfolding
; return (floats4, bndr', rhs4) }
where
platform = targetPlatform (cpe_dynFlags env)
arity = idArity bndr -- We must match this arity
---------------------
float_from_rhs floats rhs
| isEmptyFloats floats = return (emptyFloats, rhs)
| isTopLevel top_lvl = float_top floats rhs
| otherwise = float_nested floats rhs
---------------------
float_nested floats rhs
| wantFloatNested is_rec dmd is_unlifted floats rhs
= return (floats, rhs)
| otherwise = dontFloat floats rhs
---------------------
float_top floats rhs -- Urhgh! See Note [CafInfo and floating]
| mayHaveCafRefs (idCafInfo bndr)
, allLazyTop floats
= return (floats, rhs)
-- So the top-level binding is marked NoCafRefs
| Just (floats', rhs') <- canFloatFromNoCaf platform floats rhs
= return (floats', rhs')
| otherwise
= dontFloat floats rhs
dontFloat :: Floats -> CpeRhs -> UniqSM (Floats, CpeBody)
-- Non-empty floats, but do not want to float from rhs
-- So wrap the rhs in the floats
-- But: rhs1 might have lambdas, and we can't
-- put them inside a wrapBinds
dontFloat floats1 rhs
= do { (floats2, body) <- rhsToBody rhs
; return (emptyFloats, wrapBinds floats1 $
wrapBinds floats2 body) }
{- Note [Silly extra arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we had this
f{arity=1} = \x\y. e
We *must* match the arity on the Id, so we have to generate
f' = \x\y. e
f = \x. f' x
It's a bizarre case: why is the arity on the Id wrong? Reason
(in the days of __inline_me__):
f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
When InlineMe notes go away this won't happen any more. But
it seems good for CorePrep to be robust.
-}
-- ---------------------------------------------------------------------------
-- CpeRhs: produces a result satisfying CpeRhs
-- ---------------------------------------------------------------------------
cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- If
-- e ===> (bs, e')
-- then
-- e = let bs in e' (semantically, that is!)
--
-- For example
-- f (g x) ===> ([v = g x], f v)
cpeRhsE _env expr@(Type {}) = return (emptyFloats, expr)
cpeRhsE _env expr@(Coercion {}) = return (emptyFloats, expr)
cpeRhsE env (Lit (LitInteger i _))
= cpeRhsE env (cvtLitInteger (cpe_dynFlags env) (getMkIntegerId env)
(cpe_integerSDataCon env) i)
cpeRhsE _env expr@(Lit {}) = return (emptyFloats, expr)
cpeRhsE env expr@(Var {}) = cpeApp env expr
cpeRhsE env expr@(App {}) = cpeApp env expr
cpeRhsE env (Let bind expr)
= do { (env', new_binds) <- cpeBind NotTopLevel env bind
; (floats, body) <- cpeRhsE env' expr
; return (new_binds `appendFloats` floats, body) }
cpeRhsE env (Tick tickish expr)
| tickishPlace tickish == PlaceNonLam && tickish `tickishScopesLike` SoftScope
= do { (floats, body) <- cpeRhsE env expr
-- See [Floating Ticks in CorePrep]
; return (unitFloat (FloatTick tickish) `appendFloats` floats, body) }
| otherwise
= do { body <- cpeBodyNF env expr
; return (emptyFloats, mkTick tickish' body) }
where
tickish' | Breakpoint n fvs <- tickish
-- See also 'substTickish'
= Breakpoint n (map (getIdFromTrivialExpr . lookupCorePrepEnv env) fvs)
| otherwise
= tickish
cpeRhsE env (Cast expr co)
= do { (floats, expr') <- cpeRhsE env expr
; return (floats, Cast expr' co) }
cpeRhsE env expr@(Lam {})
= do { let (bndrs,body) = collectBinders expr
; (env', bndrs') <- cpCloneBndrs env bndrs
; body' <- cpeBodyNF env' body
; return (emptyFloats, mkLams bndrs' body') }
cpeRhsE env (Case scrut bndr ty alts)
= do { (floats, scrut') <- cpeBody env scrut
; let bndr1 = bndr `setIdUnfolding` evaldUnfolding
-- Record that the case binder is evaluated in the alternatives
; (env', bndr2) <- cpCloneBndr env bndr1
; alts' <- mapM (sat_alt env') alts
; return (floats, Case scrut' bndr2 ty alts') }
where
sat_alt env (con, bs, rhs)
= do { (env2, bs') <- cpCloneBndrs env bs
; rhs' <- cpeBodyNF env2 rhs
; return (con, bs', rhs') }
cvtLitInteger :: DynFlags -> Id -> Maybe DataCon -> Integer -> CoreExpr
-- Here we convert a literal Integer to the low-level
-- represenation. Exactly how we do this depends on the
-- library that implements Integer. If it's GMP we
-- use the S# data constructor for small literals.
-- See Note [Integer literals] in Literal
cvtLitInteger dflags _ (Just sdatacon) i
| inIntRange dflags i -- Special case for small integers
= mkConApp sdatacon [Lit (mkMachInt dflags i)]
cvtLitInteger dflags mk_integer _ i
= mkApps (Var mk_integer) [isNonNegative, ints]
where isNonNegative = if i < 0 then mkConApp falseDataCon []
else mkConApp trueDataCon []
ints = mkListExpr intTy (f (abs i))
f 0 = []
f x = let low = x .&. mask
high = x `shiftR` bits
in mkConApp intDataCon [Lit (mkMachInt dflags low)] : f high
bits = 31
mask = 2 ^ bits - 1
-- ---------------------------------------------------------------------------
-- CpeBody: produces a result satisfying CpeBody
-- ---------------------------------------------------------------------------
-- | Convert a 'CoreExpr' so it satisfies 'CpeBody', without
-- producing any floats (any generated floats are immediately
-- let-bound using 'wrapBinds'). Generally you want this, esp.
-- when you've reached a binding form (e.g., a lambda) and
-- floating any further would be incorrect.
cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
cpeBodyNF env expr
= do { (floats, body) <- cpeBody env expr
; return (wrapBinds floats body) }
-- | Convert a 'CoreExpr' so it satisfies 'CpeBody'; also produce
-- a list of 'Floats' which are being propagated upwards. In
-- fact, this function is used in only two cases: to
-- implement 'cpeBodyNF' (which is what you usually want),
-- and in the case when a let-binding is in a case scrutinee--here,
-- we can always float out:
--
-- case (let x = y in z) of ...
-- ==> let x = y in case z of ...
--
cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
cpeBody env expr
= do { (floats1, rhs) <- cpeRhsE env expr
; (floats2, body) <- rhsToBody rhs
; return (floats1 `appendFloats` floats2, body) }
--------
rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
-- Remove top level lambdas by let-binding
rhsToBody (Tick t expr)
| tickishScoped t == NoScope -- only float out of non-scoped annotations
= do { (floats, expr') <- rhsToBody expr
; return (floats, mkTick t expr') }
rhsToBody (Cast e co)
-- You can get things like
-- case e of { p -> coerce t (\s -> ...) }
= do { (floats, e') <- rhsToBody e
; return (floats, Cast e' co) }
rhsToBody expr@(Lam {})
| Just no_lam_result <- tryEtaReducePrep bndrs body
= return (emptyFloats, no_lam_result)
| all isTyVar bndrs -- Type lambdas are ok
= return (emptyFloats, expr)
| otherwise -- Some value lambdas
= do { fn <- newVar (exprType expr)
; let rhs = cpeEtaExpand (exprArity expr) expr
float = FloatLet (NonRec fn rhs)
; return (unitFloat float, Var fn) }
where
(bndrs,body) = collectBinders expr
rhsToBody expr = return (emptyFloats, expr)
-- ---------------------------------------------------------------------------
-- CpeApp: produces a result satisfying CpeApp
-- ---------------------------------------------------------------------------
data CpeArg = CpeArg CoreArg
| CpeCast Coercion
| CpeTick (Tickish Id)
{- Note [runRW arg]
~~~~~~~~~~~~~~~~~~~
If we got, say
runRW# (case bot of {})
which happened in Trac #11291, we do /not/ want to turn it into
(case bot of {}) realWorldPrimId#
because that gives a panic in CoreToStg.myCollectArgs, which expects
only variables in function position. But if we are sure to make
runRW# strict (which we do in MkId), this can't happen
-}
cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- May return a CpeRhs because of saturating primops
cpeApp top_env expr
= do { let (terminal, args, depth) = collect_args expr
; cpe_app top_env terminal args depth
}
where
-- We have a nested data structure of the form
-- e `App` a1 `App` a2 ... `App` an, convert it into
-- (e, [CpeArg a1, CpeArg a2, ..., CpeArg an], depth)
-- We use 'CpeArg' because we may also need to
-- record casts and ticks. Depth counts the number
-- of arguments that would consume strictness information
-- (so, no type or coercion arguments.)
collect_args :: CoreExpr -> (CoreExpr, [CpeArg], Int)
collect_args e = go e [] 0
where
go (App fun arg) as depth
= go fun (CpeArg arg : as)
(if isTyCoArg arg then depth else depth + 1)
go (Cast fun co) as depth
= go fun (CpeCast co : as) depth
go (Tick tickish fun) as depth
| tickishPlace tickish == PlaceNonLam
&& tickish `tickishScopesLike` SoftScope
= go fun (CpeTick tickish : as) depth
go terminal as depth = (terminal, as, depth)
cpe_app :: CorePrepEnv
-> CoreExpr
-> [CpeArg]
-> Int
-> UniqSM (Floats, CpeRhs)
cpe_app env (Var f) (CpeArg Type{} : CpeArg arg : args) depth
| f `hasKey` lazyIdKey -- Replace (lazy a) with a, and
|| f `hasKey` noinlineIdKey -- Replace (noinline a) with a
-- Consider the code:
--
-- lazy (f x) y
--
-- We need to make sure that we need to recursively collect arguments on
-- "f x", otherwise we'll float "f x" out (it's not a variable) and
-- end up with this awful -ddump-prep:
--
-- case f x of f_x {
-- __DEFAULT -> f_x y
-- }
--
-- rather than the far superior "f x y". Test case is par01.
= let (terminal, args', depth') = collect_args arg
in cpe_app env terminal (args' ++ args) (depth + depth' - 1)
cpe_app env (Var f) [CpeArg _runtimeRep@Type{}, CpeArg _type@Type{}, CpeArg arg] 1
| f `hasKey` runRWKey
-- Replace (runRW# f) by (f realWorld#), beta reducing if possible (this
-- is why we return a CorePrepEnv as well)
= case arg of
Lam s body -> cpe_app (extendCorePrepEnv env s realWorldPrimId) body [] 0
_ -> cpe_app env arg [CpeArg (Var realWorldPrimId)] 1
cpe_app env (Var v) args depth
= do { v1 <- fiddleCCall v
; let e2 = lookupCorePrepEnv env v1
hd = getIdFromTrivialExpr_maybe e2
-- NB: depth from collect_args is right, because e2 is a trivial expression
-- and thus its embedded Id *must* be at the same depth as any
-- Apps it is under are type applications only (c.f.
-- cpe_ExprIsTrivial). But note that we need the type of the
-- expression, not the id.
; (app, floats) <- rebuild_app args e2 (exprType e2) emptyFloats stricts
; mb_saturate hd app floats depth }
where
stricts = case idStrictness v of
StrictSig (DmdType _ demands _)
| listLengthCmp demands depth /= GT -> demands
-- length demands <= depth
| otherwise -> []
-- If depth < length demands, then we have too few args to
-- satisfy strictness info so we have to ignore all the
-- strictness info, e.g. + (error "urk")
-- Here, we can't evaluate the arg strictly, because this
-- partial application might be seq'd
-- We inlined into something that's not a var and has no args.
-- Bounce it back up to cpeRhsE.
cpe_app env fun [] _ = cpeRhsE env fun
-- N-variable fun, better let-bind it
cpe_app env fun args depth
= do { (fun_floats, fun') <- cpeArg env evalDmd fun ty
-- The evalDmd says that it's sure to be evaluated,
-- so we'll end up case-binding it
; (app, floats) <- rebuild_app args fun' ty fun_floats []
; mb_saturate Nothing app floats depth }
where
ty = exprType fun
-- Saturate if necessary
mb_saturate head app floats depth =
case head of
Just fn_id -> do { sat_app <- maybeSaturate fn_id app depth
; return (floats, sat_app) }
_other -> return (floats, app)
-- Deconstruct and rebuild the application, floating any non-atomic
-- arguments to the outside. We collect the type of the expression,
-- the head of the application, and the number of actual value arguments,
-- all of which are used to possibly saturate this application if it
-- has a constructor or primop at the head.
rebuild_app
:: [CpeArg] -- The arguments (inner to outer)
-> CpeApp
-> Type
-> Floats
-> [Demand]
-> UniqSM (CpeApp, Floats)
rebuild_app [] app _ floats ss = do
MASSERT(null ss) -- make sure we used all the strictness info
return (app, floats)
rebuild_app (a : as) fun' fun_ty floats ss = case a of
CpeArg arg@(Type arg_ty) ->
rebuild_app as (App fun' arg) (piResultTy fun_ty arg_ty) floats ss
CpeArg arg@(Coercion {}) ->
rebuild_app as (App fun' arg) (funResultTy fun_ty) floats ss
CpeArg arg -> do
let (ss1, ss_rest) -- See Note [lazyId magic] in MkId
= case (ss, isLazyExpr arg) of
(_ : ss_rest, True) -> (topDmd, ss_rest)
(ss1 : ss_rest, False) -> (ss1, ss_rest)
([], _) -> (topDmd, [])
(arg_ty, res_ty) = expectJust "cpeBody:collect_args" $
splitFunTy_maybe fun_ty
(fs, arg') <- cpeArg top_env ss1 arg arg_ty
rebuild_app as (App fun' arg') res_ty (fs `appendFloats` floats) ss_rest
CpeCast co ->
let Pair _ty1 ty2 = coercionKind co
in rebuild_app as (Cast fun' co) ty2 floats ss
CpeTick tickish ->
-- See [Floating Ticks in CorePrep]
rebuild_app as fun' fun_ty (addFloat floats (FloatTick tickish)) ss
isLazyExpr :: CoreExpr -> Bool
-- See Note [lazyId magic] in MkId
isLazyExpr (Cast e _) = isLazyExpr e
isLazyExpr (Tick _ e) = isLazyExpr e
isLazyExpr (Var f `App` _ `App` _) = f `hasKey` lazyIdKey
isLazyExpr _ = False
-- ---------------------------------------------------------------------------
-- CpeArg: produces a result satisfying CpeArg
-- ---------------------------------------------------------------------------
-- This is where we arrange that a non-trivial argument is let-bound
cpeArg :: CorePrepEnv -> Demand
-> CoreArg -> Type -> UniqSM (Floats, CpeTriv)
cpeArg env dmd arg arg_ty
= do { (floats1, arg1) <- cpeRhsE env arg -- arg1 can be a lambda
; (floats2, arg2) <- if want_float floats1 arg1
then return (floats1, arg1)
else dontFloat floats1 arg1
-- Else case: arg1 might have lambdas, and we can't
-- put them inside a wrapBinds
; if cpe_ExprIsTrivial arg2 -- Do not eta expand a trivial argument
then return (floats2, arg2)
else do
{ v <- newVar arg_ty
; let arg3 = cpeEtaExpand (exprArity arg2) arg2
arg_float = mkFloat dmd is_unlifted v arg3
; return (addFloat floats2 arg_float, varToCoreExpr v) } }
where
is_unlifted = isUnliftedType arg_ty
want_float = wantFloatNested NonRecursive dmd is_unlifted
{-
Note [Floating unlifted arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider C (let v* = expensive in v)
where the "*" indicates "will be demanded". Usually v will have been
inlined by now, but let's suppose it hasn't (see Trac #2756). Then we
do *not* want to get
let v* = expensive in C v
because that has different strictness. Hence the use of 'allLazy'.
(NB: the let v* turns into a FloatCase, in mkLocalNonRec.)
------------------------------------------------------------------------------
-- Building the saturated syntax
-- ---------------------------------------------------------------------------
maybeSaturate deals with saturating primops and constructors
The type is the type of the entire application
-}
maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
maybeSaturate fn expr n_args
| Just DataToTagOp <- isPrimOpId_maybe fn -- DataToTag must have an evaluated arg
-- A gruesome special case
= saturateDataToTag sat_expr
| hasNoBinding fn -- There's no binding
= return sat_expr
| otherwise
= return expr
where
fn_arity = idArity fn
excess_arity = fn_arity - n_args
sat_expr = cpeEtaExpand excess_arity expr
-------------
saturateDataToTag :: CpeApp -> UniqSM CpeApp
-- See Note [dataToTag magic]
saturateDataToTag sat_expr
= do { let (eta_bndrs, eta_body) = collectBinders sat_expr
; eta_body' <- eval_data2tag_arg eta_body
; return (mkLams eta_bndrs eta_body') }
where
eval_data2tag_arg :: CpeApp -> UniqSM CpeBody
eval_data2tag_arg app@(fun `App` arg)
| exprIsHNF arg -- Includes nullary constructors
= return app -- The arg is evaluated
| otherwise -- Arg not evaluated, so evaluate it
= do { arg_id <- newVar (exprType arg)
; let arg_id1 = setIdUnfolding arg_id evaldUnfolding
; return (Case arg arg_id1 (exprType app)
[(DEFAULT, [], fun `App` Var arg_id1)]) }
eval_data2tag_arg (Tick t app) -- Scc notes can appear
= do { app' <- eval_data2tag_arg app
; return (Tick t app') }
eval_data2tag_arg other -- Should not happen
= pprPanic "eval_data2tag" (ppr other)
{-
Note [dataToTag magic]
~~~~~~~~~~~~~~~~~~~~~~
Horrid: we must ensure that the arg of data2TagOp is evaluated
(data2tag x) --> (case x of y -> data2tag y)
(yuk yuk) take into account the lambdas we've now introduced
How might it not be evaluated? Well, we might have floated it out
of the scope of a `seq`, or dropped the `seq` altogether.
************************************************************************
* *
Simple CoreSyn operations
* *
************************************************************************
-}
cpe_ExprIsTrivial :: CoreExpr -> Bool
-- Version that doesn't consider an scc annotation to be trivial.
-- See also 'exprIsTrivial'
cpe_ExprIsTrivial (Var _) = True
cpe_ExprIsTrivial (Type _) = True
cpe_ExprIsTrivial (Coercion _) = True
cpe_ExprIsTrivial (Lit _) = True
cpe_ExprIsTrivial (App e arg) = not (isRuntimeArg arg) && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Lam b e) = not (isRuntimeVar b) && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Tick t e) = not (tickishIsCode t) && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Cast e _) = cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Case e _ _ []) = cpe_ExprIsTrivial e
-- See Note [Empty case is trivial] in CoreUtils
cpe_ExprIsTrivial _ = False
{-
-- -----------------------------------------------------------------------------
-- Eta reduction
-- -----------------------------------------------------------------------------
Note [Eta expansion]
~~~~~~~~~~~~~~~~~~~~~
Eta expand to match the arity claimed by the binder Remember,
CorePrep must not change arity
Eta expansion might not have happened already, because it is done by
the simplifier only when there at least one lambda already.
NB1:we could refrain when the RHS is trivial (which can happen
for exported things). This would reduce the amount of code
generated (a little) and make things a little words for
code compiled without -O. The case in point is data constructor
wrappers.
NB2: we have to be careful that the result of etaExpand doesn't
invalidate any of the assumptions that CorePrep is attempting
to establish. One possible cause is eta expanding inside of
an SCC note - we're now careful in etaExpand to make sure the
SCC is pushed inside any new lambdas that are generated.
Note [Eta expansion and the CorePrep invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It turns out to be much much easier to do eta expansion
*after* the main CorePrep stuff. But that places constraints
on the eta expander: given a CpeRhs, it must return a CpeRhs.
For example here is what we do not want:
f = /\a -> g (h 3) -- h has arity 2
After ANFing we get
f = /\a -> let s = h 3 in g s
and now we do NOT want eta expansion to give
f = /\a -> \ y -> (let s = h 3 in g s) y
Instead CoreArity.etaExpand gives
f = /\a -> \y -> let s = h 3 in g s y
-}
cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
cpeEtaExpand arity expr
| arity == 0 = expr
| otherwise = etaExpand arity expr
{-
-- -----------------------------------------------------------------------------
-- Eta reduction
-- -----------------------------------------------------------------------------
Why try eta reduction? Hasn't the simplifier already done eta?
But the simplifier only eta reduces if that leaves something
trivial (like f, or f Int). But for deLam it would be enough to
get to a partial application:
case x of { p -> \xs. map f xs }
==> case x of { p -> map f }
-}
tryEtaReducePrep :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
tryEtaReducePrep bndrs expr@(App _ _)
| ok_to_eta_reduce f
, n_remaining >= 0
, and (zipWith ok bndrs last_args)
, not (any (`elemVarSet` fvs_remaining) bndrs)
, exprIsHNF remaining_expr -- Don't turn value into a non-value
-- else the behaviour with 'seq' changes
= Just remaining_expr
where
(f, args) = collectArgs expr
remaining_expr = mkApps f remaining_args
fvs_remaining = exprFreeVars remaining_expr
(remaining_args, last_args) = splitAt n_remaining args
n_remaining = length args - length bndrs
ok bndr (Var arg) = bndr == arg
ok _ _ = False
-- We can't eta reduce something which must be saturated.
ok_to_eta_reduce (Var f) = not (hasNoBinding f)
ok_to_eta_reduce _ = False -- Safe. ToDo: generalise
tryEtaReducePrep bndrs (Let bind@(NonRec _ r) body)
| not (any (`elemVarSet` fvs) bndrs)
= case tryEtaReducePrep bndrs body of
Just e -> Just (Let bind e)
Nothing -> Nothing
where
fvs = exprFreeVars r
-- NB: do not attempt to eta-reduce across ticks
-- Otherwise we risk reducing
-- \x. (Tick (Breakpoint {x}) f x)
-- ==> Tick (breakpoint {x}) f
-- which is bogus (Trac #17228)
-- tryEtaReducePrep bndrs (Tick tickish e)
-- = fmap (mkTick tickish) $ tryEtaReducePrep bndrs e
tryEtaReducePrep _ _ = Nothing
{-
************************************************************************
* *
Floats
* *
************************************************************************
Note [Pin demand info on floats]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We pin demand info on floated lets so that we can see the one-shot thunks.
-}
data FloatingBind
= FloatLet CoreBind -- Rhs of bindings are CpeRhss
-- They are always of lifted type;
-- unlifted ones are done with FloatCase
| FloatCase
Id CpeBody
Bool -- The bool indicates "ok-for-speculation"
-- | See Note [Floating Ticks in CorePrep]
| FloatTick (Tickish Id)
data Floats = Floats OkToSpec (OrdList FloatingBind)
instance Outputable FloatingBind where
ppr (FloatLet b) = ppr b
ppr (FloatCase b r ok) = brackets (ppr ok) <+> ppr b <+> equals <+> ppr r
ppr (FloatTick t) = ppr t
instance Outputable Floats where
ppr (Floats flag fs) = text "Floats" <> brackets (ppr flag) <+>
braces (vcat (map ppr (fromOL fs)))
instance Outputable OkToSpec where
ppr OkToSpec = text "OkToSpec"
ppr IfUnboxedOk = text "IfUnboxedOk"
ppr NotOkToSpec = text "NotOkToSpec"
-- Can we float these binds out of the rhs of a let? We cache this decision
-- to avoid having to recompute it in a non-linear way when there are
-- deeply nested lets.
data OkToSpec
= OkToSpec -- Lazy bindings of lifted type
| IfUnboxedOk -- A mixture of lazy lifted bindings and n
-- ok-to-speculate unlifted bindings
| NotOkToSpec -- Some not-ok-to-speculate unlifted bindings
mkFloat :: Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat dmd is_unlifted bndr rhs
| use_case = FloatCase bndr rhs (exprOkForSpeculation rhs)
| is_hnf = FloatLet (NonRec bndr rhs)
| otherwise = FloatLet (NonRec (setIdDemandInfo bndr dmd) rhs)
-- See Note [Pin demand info on floats]
where
is_hnf = exprIsHNF rhs
is_strict = isStrictDmd dmd
use_case = is_unlifted || is_strict && not is_hnf
-- Don't make a case for a value binding,
-- even if it's strict. Otherwise we get
-- case (\x -> e) of ...!
emptyFloats :: Floats
emptyFloats = Floats OkToSpec nilOL
isEmptyFloats :: Floats -> Bool
isEmptyFloats (Floats _ bs) = isNilOL bs
wrapBinds :: Floats -> CpeBody -> CpeBody
wrapBinds (Floats _ binds) body
= foldrOL mk_bind body binds
where
mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
mk_bind (FloatLet bind) body = Let bind body
mk_bind (FloatTick tickish) body = mkTick tickish body
addFloat :: Floats -> FloatingBind -> Floats
addFloat (Floats ok_to_spec floats) new_float
= Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
where
check (FloatLet _) = OkToSpec
check (FloatCase _ _ ok_for_spec)
| ok_for_spec = IfUnboxedOk
| otherwise = NotOkToSpec
check FloatTick{} = OkToSpec
-- The ok-for-speculation flag says that it's safe to
-- float this Case out of a let, and thereby do it more eagerly
-- We need the top-level flag because it's never ok to float
-- an unboxed binding to the top level
unitFloat :: FloatingBind -> Floats
unitFloat = addFloat emptyFloats
appendFloats :: Floats -> Floats -> Floats
appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
= Floats (combine spec1 spec2) (floats1 `appOL` floats2)
concatFloats :: [Floats] -> OrdList FloatingBind
concatFloats = foldr (\ (Floats _ bs1) bs2 -> appOL bs1 bs2) nilOL
combine :: OkToSpec -> OkToSpec -> OkToSpec
combine NotOkToSpec _ = NotOkToSpec
combine _ NotOkToSpec = NotOkToSpec
combine IfUnboxedOk _ = IfUnboxedOk
combine _ IfUnboxedOk = IfUnboxedOk
combine _ _ = OkToSpec
deFloatTop :: Floats -> [CoreBind]
-- For top level only; we don't expect any FloatCases
deFloatTop (Floats _ floats)
= foldrOL get [] floats
where
get (FloatLet b) bs = occurAnalyseRHSs b : bs
get b _ = pprPanic "corePrepPgm" (ppr b)
-- See Note [Dead code in CorePrep]
occurAnalyseRHSs (NonRec x e) = NonRec x (occurAnalyseExpr_NoBinderSwap e)
occurAnalyseRHSs (Rec xes) = Rec [(x, occurAnalyseExpr_NoBinderSwap e) | (x, e) <- xes]
---------------------------------------------------------------------------
canFloatFromNoCaf :: Platform -> Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
-- Note [CafInfo and floating]
canFloatFromNoCaf platform (Floats ok_to_spec fs) rhs
| OkToSpec <- ok_to_spec -- Worth trying
, Just (subst, fs') <- go (emptySubst, nilOL) (fromOL fs)
= Just (Floats OkToSpec fs', subst_expr subst rhs)
| otherwise
= Nothing
where
subst_expr = substExpr (text "CorePrep")
go :: (Subst, OrdList FloatingBind) -> [FloatingBind]
-> Maybe (Subst, OrdList FloatingBind)
go (subst, fbs_out) [] = Just (subst, fbs_out)
go (subst, fbs_out) (FloatLet (NonRec b r) : fbs_in)
| rhs_ok r
= go (subst', fbs_out `snocOL` new_fb) fbs_in
where
(subst', b') = set_nocaf_bndr subst b
new_fb = FloatLet (NonRec b' (subst_expr subst r))
go (subst, fbs_out) (FloatLet (Rec prs) : fbs_in)
| all rhs_ok rs
= go (subst', fbs_out `snocOL` new_fb) fbs_in
where
(bs,rs) = unzip prs
(subst', bs') = mapAccumL set_nocaf_bndr subst bs
rs' = map (subst_expr subst') rs
new_fb = FloatLet (Rec (bs' `zip` rs'))
go (subst, fbs_out) (ft@FloatTick{} : fbs_in)
= go (subst, fbs_out `snocOL` ft) fbs_in
go _ _ = Nothing -- Encountered a caffy binding
------------
set_nocaf_bndr subst bndr
= (extendIdSubst subst bndr (Var bndr'), bndr')
where
bndr' = bndr `setIdCafInfo` NoCafRefs
------------
rhs_ok :: CoreExpr -> Bool
-- We can only float to top level from a NoCaf thing if
-- the new binding is static. However it can't mention
-- any non-static things or it would *already* be Caffy
rhs_ok = rhsIsStatic platform (\_ -> False)
(\i -> pprPanic "rhsIsStatic" (integer i))
-- Integer literals should not show up
wantFloatNested :: RecFlag -> Demand -> Bool -> Floats -> CpeRhs -> Bool
wantFloatNested is_rec dmd is_unlifted floats rhs
= isEmptyFloats floats
|| isStrictDmd dmd
|| is_unlifted
|| (allLazyNested is_rec floats && exprIsHNF rhs)
-- Why the test for allLazyNested?
-- v = f (x `divInt#` y)
-- we don't want to float the case, even if f has arity 2,
-- because floating the case would make it evaluated too early
allLazyTop :: Floats -> Bool
allLazyTop (Floats OkToSpec _) = True
allLazyTop _ = False
allLazyNested :: RecFlag -> Floats -> Bool
allLazyNested _ (Floats OkToSpec _) = True
allLazyNested _ (Floats NotOkToSpec _) = False
allLazyNested is_rec (Floats IfUnboxedOk _) = isNonRec is_rec
{-
************************************************************************
* *
Cloning
* *
************************************************************************
-}
-- ---------------------------------------------------------------------------
-- The environment
-- ---------------------------------------------------------------------------
-- Note [Inlining in CorePrep]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- There is a subtle but important invariant that must be upheld in the output
-- of CorePrep: there are no "trivial" updatable thunks. Thus, this Core
-- is impermissible:
--
-- let x :: ()
-- x = y
--
-- (where y is a reference to a GLOBAL variable). Thunks like this are silly:
-- they can always be profitably replaced by inlining x with y. Consequently,
-- the code generator/runtime does not bother implementing this properly
-- (specifically, there is no implementation of stg_ap_0_upd_info, which is the
-- stack frame that would be used to update this thunk. The "0" means it has
-- zero free variables.)
--
-- In general, the inliner is good at eliminating these let-bindings. However,
-- there is one case where these trivial updatable thunks can arise: when
-- we are optimizing away 'lazy' (see Note [lazyId magic], and also
-- 'cpeRhsE'.) Then, we could have started with:
--
-- let x :: ()
-- x = lazy @ () y
--
-- which is a perfectly fine, non-trivial thunk, but then CorePrep will
-- drop 'lazy', giving us 'x = y' which is trivial and impermissible.
-- The solution is CorePrep to have a miniature inlining pass which deals
-- with cases like this. We can then drop the let-binding altogether.
--
-- Why does the removal of 'lazy' have to occur in CorePrep?
-- The gory details are in Note [lazyId magic] in MkId, but the
-- main reason is that lazy must appear in unfoldings (optimizer
-- output) and it must prevent call-by-value for catch# (which
-- is implemented by CorePrep.)
--
-- An alternate strategy for solving this problem is to have the
-- inliner treat 'lazy e' as a trivial expression if 'e' is trivial.
-- We decided not to adopt this solution to keep the definition
-- of 'exprIsTrivial' simple.
--
-- There is ONE caveat however: for top-level bindings we have
-- to preserve the binding so that we float the (hacky) non-recursive
-- binding for data constructors; see Note [Data constructor workers].
--
-- Note [CorePrep inlines trivial CoreExpr not Id]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Why does cpe_env need to be an IdEnv CoreExpr, as opposed to an
-- IdEnv Id? Naively, we might conjecture that trivial updatable thunks
-- as per Note [Inlining in CorePrep] always have the form
-- 'lazy @ SomeType gbl_id'. But this is not true: the following is
-- perfectly reasonable Core:
--
-- let x :: ()
-- x = lazy @ (forall a. a) y @ Bool
--
-- When we inline 'x' after eliminating 'lazy', we need to replace
-- occurences of 'x' with 'y @ bool', not just 'y'. Situations like
-- this can easily arise with higher-rank types; thus, cpe_env must
-- map to CoreExprs, not Ids.
data CorePrepEnv
= CPE { cpe_dynFlags :: DynFlags
, cpe_env :: IdEnv CoreExpr -- Clone local Ids
-- ^ This environment is used for three operations:
--
-- 1. To support cloning of local Ids so that they are
-- all unique (see item (6) of CorePrep overview).
--
-- 2. To support beta-reduction of runRW, see
-- Note [runRW magic] and Note [runRW arg].
--
-- 3. To let us inline trivial RHSs of non top-level let-bindings,
-- see Note [lazyId magic], Note [Inlining in CorePrep]
-- and Note [CorePrep inlines trivial CoreExpr not Id] (#12076)
, cpe_mkIntegerId :: Id
, cpe_integerSDataCon :: Maybe DataCon
}
lookupMkIntegerName :: DynFlags -> HscEnv -> IO Id
lookupMkIntegerName dflags hsc_env
= guardIntegerUse dflags $ liftM tyThingId $
lookupGlobal hsc_env mkIntegerName
lookupIntegerSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupIntegerSDataConName dflags hsc_env = case cIntegerLibraryType of
IntegerGMP -> guardIntegerUse dflags $ liftM (Just . tyThingDataCon) $
lookupGlobal hsc_env integerSDataConName
IntegerSimple -> return Nothing
-- | Helper for 'lookupMkIntegerName' and 'lookupIntegerSDataConName'
guardIntegerUse :: DynFlags -> IO a -> IO a
guardIntegerUse dflags act
| thisPackage dflags == primUnitId
= return $ panic "Can't use Integer in ghc-prim"
| thisPackage dflags == integerUnitId
= return $ panic "Can't use Integer in integer-*"
| otherwise = act
mkInitialCorePrepEnv :: DynFlags -> HscEnv -> IO CorePrepEnv
mkInitialCorePrepEnv dflags hsc_env
= do mkIntegerId <- lookupMkIntegerName dflags hsc_env
integerSDataCon <- lookupIntegerSDataConName dflags hsc_env
return $ CPE {
cpe_dynFlags = dflags,
cpe_env = emptyVarEnv,
cpe_mkIntegerId = mkIntegerId,
cpe_integerSDataCon = integerSDataCon
}
extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv cpe id id'
= cpe { cpe_env = extendVarEnv (cpe_env cpe) id (Var id') }
extendCorePrepEnvExpr :: CorePrepEnv -> Id -> CoreExpr -> CorePrepEnv
extendCorePrepEnvExpr cpe id expr
= cpe { cpe_env = extendVarEnv (cpe_env cpe) id expr }
extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
extendCorePrepEnvList cpe prs
= cpe { cpe_env = extendVarEnvList (cpe_env cpe)
(map (\(id, id') -> (id, Var id')) prs) }
lookupCorePrepEnv :: CorePrepEnv -> Id -> CoreExpr
lookupCorePrepEnv cpe id
= case lookupVarEnv (cpe_env cpe) id of
Nothing -> Var id
Just exp -> exp
getMkIntegerId :: CorePrepEnv -> Id
getMkIntegerId = cpe_mkIntegerId
------------------------------------------------------------------------------
-- Cloning binders
-- ---------------------------------------------------------------------------
cpCloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
cpCloneBndrs env bs = mapAccumLM cpCloneBndr env bs
cpCloneBndr :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
cpCloneBndr env bndr
| isLocalId bndr, not (isCoVar bndr)
= do bndr' <- setVarUnique bndr <$> getUniqueM
-- We are going to OccAnal soon, so drop (now-useless) rules/unfoldings
-- so that we can drop more stuff as dead code.
-- See also Note [Dead code in CorePrep]
let bndr'' = bndr' `setIdUnfolding` noUnfolding
`setIdSpecialisation` emptyRuleInfo
return (extendCorePrepEnv env bndr bndr'', bndr'')
| otherwise -- Top level things, which we don't want
-- to clone, have become GlobalIds by now
-- And we don't clone tyvars, or coercion variables
= return (env, bndr)
------------------------------------------------------------------------------
-- Cloning ccall Ids; each must have a unique name,
-- to give the code generator a handle to hang it on
-- ---------------------------------------------------------------------------
fiddleCCall :: Id -> UniqSM Id
fiddleCCall id
| isFCallId id = (id `setVarUnique`) <$> getUniqueM
| otherwise = return id
------------------------------------------------------------------------------
-- Generating new binders
-- ---------------------------------------------------------------------------
newVar :: Type -> UniqSM Id
newVar ty
= seqType ty `seq` do
uniq <- getUniqueM
return (mkSysLocalOrCoVar (fsLit "sat") uniq ty)
------------------------------------------------------------------------------
-- Floating ticks
-- ---------------------------------------------------------------------------
--
-- Note [Floating Ticks in CorePrep]
--
-- It might seem counter-intuitive to float ticks by default, given
-- that we don't actually want to move them if we can help it. On the
-- other hand, nothing gets very far in CorePrep anyway, and we want
-- to preserve the order of let bindings and tick annotations in
-- relation to each other. For example, if we just wrapped let floats
-- when they pass through ticks, we might end up performing the
-- following transformation:
--
-- src<...> let foo = bar in baz
-- ==> let foo = src<...> bar in src<...> baz
--
-- Because the let-binding would float through the tick, and then
-- immediately materialize, achieving nothing but decreasing tick
-- accuracy. The only special case is the following scenario:
--
-- let foo = src<...> (let a = b in bar) in baz
-- ==> let foo = src<...> bar; a = src<...> b in baz
--
-- Here we would not want the source tick to end up covering "baz" and
-- therefore refrain from pushing ticks outside. Instead, we copy them
-- into the floating binds (here "a") in cpePair. Note that where "b"
-- or "bar" are (value) lambdas we have to push the annotations
-- further inside in order to uphold our rules.
--
-- All of this is implemented below in @wrapTicks@.
-- | Like wrapFloats, but only wraps tick floats
wrapTicks :: Floats -> CoreExpr -> (Floats, CoreExpr)
wrapTicks (Floats flag floats0) expr = (Floats flag floats1, expr')
where (floats1, expr') = foldrOL go (nilOL, expr) floats0
go (FloatTick t) (fs, e) = ASSERT(tickishPlace t == PlaceNonLam)
(mapOL (wrap t) fs, mkTick t e)
go other (fs, e) = (other `consOL` fs, e)
wrap t (FloatLet bind) = FloatLet (wrapBind t bind)
wrap t (FloatCase b r ok) = FloatCase b (mkTick t r) ok
wrap _ other = pprPanic "wrapTicks: unexpected float!"
(ppr other)
wrapBind t (NonRec binder rhs) = NonRec binder (mkTick t rhs)
wrapBind t (Rec pairs) = Rec (mapSnd (mkTick t) pairs)
|
snoyberg/ghc
|
compiler/coreSyn/CorePrep.hs
|
Haskell
|
bsd-3-clause
| 57,558
|
-- |
-- Module: Data.Aeson.Types
-- Copyright: (c) 2011-2016 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: BSD3
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: experimental
-- Portability: portable
--
-- Types for working with JSON data.
module Data.Aeson.Types
(
-- * Core JSON types
Value(..)
, Encoding
, unsafeToEncoding
, fromEncoding
, Series
, Array
, emptyArray
, Pair
, Object
, emptyObject
-- * Convenience types and functions
, DotNetTime(..)
, typeMismatch
-- * Type conversion
, Parser
, Result(..)
, FromJSON(..)
, fromJSON
, parse
, parseEither
, parseMaybe
, ToJSON(..)
, KeyValue(..)
, modifyFailure
-- ** Keys for maps
, ToJSONKey(..)
, ToJSONKeyFunction(..)
, toJSONKeyText
, contramapToJSONKeyFunction
, FromJSONKey(..)
, FromJSONKeyFunction(..)
, fromJSONKeyCoerce
, coerceFromJSONKeyFunction
, mapFromJSONKeyFunction
-- ** Liftings to unary and binary type constructors
, FromJSON1(..)
, parseJSON1
, FromJSON2(..)
, parseJSON2
, ToJSON1(..)
, toJSON1
, toEncoding1
, ToJSON2(..)
, toJSON2
, toEncoding2
-- ** Generic JSON classes
, GFromJSON(..)
, FromArgs(..)
, GToJSON(..)
, GToEncoding(..)
, ToArgs(..)
, Zero
, One
, genericToJSON
, genericLiftToJSON
, genericToEncoding
, genericLiftToEncoding
, genericParseJSON
, genericLiftParseJSON
-- * Inspecting @'Value's@
, withObject
, withText
, withArray
, withNumber
, withScientific
, withBool
, pairs
, foldable
, (.:)
, (.:?)
, (.:!)
, (.!=)
, object
, listEncoding
, listValue
, listParser
-- * Generic and TH encoding configuration
, Options(..)
, SumEncoding(..)
, camelTo
, camelTo2
, defaultOptions
, defaultTaggedObject
) where
import Prelude ()
import Prelude.Compat
import Data.Aeson.Encoding (Encoding, unsafeToEncoding, fromEncoding, Series, pairs)
import Data.Aeson.Types.Class
import Data.Aeson.Types.Internal
import Data.Foldable (toList)
-- | Encode a 'Foldable' as a JSON array.
foldable :: (Foldable t, ToJSON a) => t a -> Encoding
foldable = toEncoding . toList
{-# INLINE foldable #-}
|
tolysz/prepare-ghcjs
|
spec-lts8/aeson/Data/Aeson/Types.hs
|
Haskell
|
bsd-3-clause
| 2,392
|
module B1 (myFringe)where
import D1 hiding (sumSquares)
import qualified D1
instance SameOrNot Float where
isSame a b = a ==b
isNotSame a b = a /=b
myFringe:: Tree a -> [a]
myFringe (Leaf x ) = [x]
myFringe (Branch left right) = myFringe right
sumSquares (x:xs)= x^2 + sumSquares xs
sumSquares [] =0
|
kmate/HaRe
|
old/testing/renaming/B1.hs
|
Haskell
|
bsd-3-clause
| 320
|
module WhereIn3 where
sumSquares x y
= (sq_1 pow x) + (sq_1 pow y) where pow = 2
sq_1 pow 0 = 0
sq_1 pow z = z ^ pow
anotherFun 0 y = sq y
sq x = x ^ 2
|
kmate/HaRe
|
old/testing/liftOneLevel/WhereIn3_AstOut.hs
|
Haskell
|
bsd-3-clause
| 163
|
{-# LANGUAGE CPP #-}
module GHCi.Signals (installSignalHandlers) where
import Control.Concurrent
import Control.Exception
import System.Mem.Weak ( deRefWeak )
#ifndef mingw32_HOST_OS
import System.Posix.Signals
#endif
#if defined(mingw32_HOST_OS)
import GHC.ConsoleHandler
#endif
-- | Install standard signal handlers for catching ^C, which just throw an
-- exception in the target thread. The current target thread is the
-- thread at the head of the list in the MVar passed to
-- installSignalHandlers.
installSignalHandlers :: IO ()
installSignalHandlers = do
main_thread <- myThreadId
wtid <- mkWeakThreadId main_thread
let interrupt = do
r <- deRefWeak wtid
case r of
Nothing -> return ()
Just t -> throwTo t UserInterrupt
#if !defined(mingw32_HOST_OS)
_ <- installHandler sigQUIT (Catch interrupt) Nothing
_ <- installHandler sigINT (Catch interrupt) Nothing
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
_ <- installHandler (Catch sig_handler)
#endif
return ()
|
tolysz/prepare-ghcjs
|
spec-lts8/ghci/GHCi/Signals.hs
|
Haskell
|
bsd-3-clause
| 1,393
|
{-# LANGUAGE UndecidableInstances, OverlappingInstances, Rank2Types,
KindSignatures, EmptyDataDecls, MultiParamTypeClasses, CPP #-}
{-
(C) 2004--2005 Ralf Laemmel, Simon D. Foster
This module approximates Data.Generics.Basics.
-}
module T1735_Help.Basics (
module Data.Typeable,
module T1735_Help.Context,
module T1735_Help.Basics
) where
import Data.Typeable
import T1735_Help.Context
------------------------------------------------------------------------------
-- The ingenious Data class
class (Typeable a, Sat (ctx a)) => Data ctx a
where
gfoldl :: Proxy ctx
-> (forall b c. Data ctx b => w (b -> c) -> b -> w c)
-> (forall g. g -> w g)
-> a -> w a
-- Default definition for gfoldl
-- which copes immediately with basic datatypes
--
gfoldl _ _ z = z
gunfold :: Proxy ctx
-> (forall b r. Data ctx b => c (b -> r) -> c r)
-> (forall r. r -> c r)
-> Constr
-> c a
toConstr :: Proxy ctx -> a -> Constr
dataTypeOf :: Proxy ctx -> a -> DataType
-- incomplete implementation
gunfold _ _ _ _ = undefined
dataTypeOf _ _ = undefined
-- | Mediate types and unary type constructors
dataCast1 :: Typeable t
=> Proxy ctx
-> (forall b. Data ctx b => w (t b))
-> Maybe (w a)
dataCast1 _ _ = Nothing
-- | Mediate types and binary type constructors
dataCast2 :: Typeable t
=> Proxy ctx
-> (forall b c. (Data ctx b, Data ctx c) => w (t b c))
-> Maybe (w a)
dataCast2 _ _ = Nothing
------------------------------------------------------------------------------
-- Generic transformations
type GenericT ctx = forall a. Data ctx a => a -> a
-- Generic map for transformations
gmapT :: Proxy ctx -> GenericT ctx -> GenericT ctx
gmapT ctx f x = unID (gfoldl ctx k ID x)
where
k (ID g) y = ID (g (f y))
-- The identity type constructor
newtype ID x = ID { unID :: x }
------------------------------------------------------------------------------
-- Generic monadic transformations
type GenericM m ctx = forall a. Data ctx a => a -> m a
-- Generic map for monadic transformations
gmapM :: Monad m => Proxy ctx -> GenericM m ctx -> GenericM m ctx
gmapM ctx f = gfoldl ctx k return
where k c x = do c' <- c
x' <- f x
return (c' x')
------------------------------------------------------------------------------
-- Generic queries
type GenericQ ctx r = forall a. Data ctx a => a -> r
-- Map for queries
gmapQ :: Proxy ctx -> GenericQ ctx r -> GenericQ ctx [r]
gmapQ ctx f = gmapQr ctx (:) [] f
gmapQr :: Data ctx a
=> Proxy ctx
-> (r' -> r -> r)
-> r
-> GenericQ ctx r'
-> a
-> r
gmapQr ctx o r f x = unQr (gfoldl ctx k (const (Qr id)) x) r
where
k (Qr g) y = Qr (\s -> g (f y `o` s))
-- The type constructor used in definition of gmapQr
newtype Qr r a = Qr { unQr :: r -> r }
------------------------------------------------------------------------------
--
-- Generic unfolding
--
------------------------------------------------------------------------------
-- | Build a term skeleton
fromConstr :: Data ctx a => Proxy ctx -> Constr -> a
fromConstr ctx = fromConstrB ctx undefined
-- | Build a term and use a generic function for subterms
fromConstrB :: Data ctx a
=> Proxy ctx
-> (forall b. Data ctx b => b)
-> Constr
-> a
fromConstrB ctx f = unID . gunfold ctx k z
where
k c = ID (unID c f)
z = ID
-- | Monadic variation on \"fromConstrB\"
fromConstrM :: (Monad m, Data ctx a)
=> Proxy ctx
-> (forall b. Data ctx b => m b)
-> Constr
-> m a
fromConstrM ctx f = gunfold ctx k z
where
k c = do { c' <- c; b <- f; return (c' b) }
z = return
------------------------------------------------------------------------------
--
-- Datatype and constructor representations
--
------------------------------------------------------------------------------
--
-- | Representation of datatypes.
-- | A package of constructor representations with names of type and module.
-- | The list of constructors could be an array, a balanced tree, or others.
--
data DataType = DataType
{ tycon :: String
, datarep :: DataRep
}
deriving Show
-- | Representation of constructors
data Constr = Constr
{ conrep :: ConstrRep
, constring :: String
, confields :: [String] -- for AlgRep only
, confixity :: Fixity -- for AlgRep only
, datatype :: DataType
}
instance Show Constr where
show = constring
-- | Equality of constructors
instance Eq Constr where
c == c' = constrRep c == constrRep c'
-- | Public representation of datatypes
data DataRep = AlgRep [Constr]
| IntRep
| FloatRep
| StringRep
| NoRep
deriving (Eq,Show)
-- | Public representation of constructors
data ConstrRep = AlgConstr ConIndex
| IntConstr Integer
| FloatConstr Double
| StringConstr String
deriving (Eq,Show)
--
-- | Unique index for datatype constructors.
-- | Textual order is respected. Starts at 1.
--
type ConIndex = Int
-- | Fixity of constructors
data Fixity = Prefix
| Infix -- Later: add associativity and precedence
deriving (Eq,Show)
------------------------------------------------------------------------------
--
-- Observers for datatype representations
--
------------------------------------------------------------------------------
-- | Gets the type constructor including the module
dataTypeName :: DataType -> String
dataTypeName = tycon
-- | Gets the public presentation of datatypes
dataTypeRep :: DataType -> DataRep
dataTypeRep = datarep
-- | Gets the datatype of a constructor
constrType :: Constr -> DataType
constrType = datatype
-- | Gets the public presentation of constructors
constrRep :: Constr -> ConstrRep
constrRep = conrep
-- | Look up a constructor by its representation
repConstr :: DataType -> ConstrRep -> Constr
repConstr dt cr =
case (dataTypeRep dt, cr) of
(AlgRep cs, AlgConstr i) -> cs !! (i-1)
(IntRep, IntConstr i) -> mkIntConstr dt i
(FloatRep, FloatConstr f) -> mkFloatConstr dt f
(StringRep, StringConstr str) -> mkStringConstr dt str
_ -> error "repConstr"
------------------------------------------------------------------------------
--
-- Representations of algebraic data types
--
------------------------------------------------------------------------------
-- | Constructs an algebraic datatype
mkDataType :: String -> [Constr] -> DataType
mkDataType str cs = DataType
{ tycon = str
, datarep = AlgRep cs
}
-- | Constructs a constructor
mkConstr :: DataType -> String -> [String] -> Fixity -> Constr
mkConstr dt str fields fix =
Constr
{ conrep = AlgConstr idx
, constring = str
, confields = fields
, confixity = fix
, datatype = dt
}
where
idx = head [ i | (c,i) <- dataTypeConstrs dt `zip` [1..],
showConstr c == str ]
-- | Gets the constructors
dataTypeConstrs :: DataType -> [Constr]
dataTypeConstrs dt = case datarep dt of
(AlgRep cons) -> cons
_ -> error "dataTypeConstrs"
-- | Gets the field labels of a constructor
constrFields :: Constr -> [String]
constrFields = confields
-- | Gets the fixity of a constructor
constrFixity :: Constr -> Fixity
constrFixity = confixity
------------------------------------------------------------------------------
--
-- From strings to constr's and vice versa: all data types
--
------------------------------------------------------------------------------
-- | Gets the string for a constructor
showConstr :: Constr -> String
showConstr = constring
-- | Lookup a constructor via a string
readConstr :: DataType -> String -> Maybe Constr
readConstr dt str =
case dataTypeRep dt of
AlgRep cons -> idx cons
IntRep -> mkReadCon (\i -> (mkPrimCon dt str (IntConstr i)))
FloatRep -> mkReadCon (\f -> (mkPrimCon dt str (FloatConstr f)))
StringRep -> Just (mkStringConstr dt str)
NoRep -> Nothing
where
-- Read a value and build a constructor
mkReadCon :: Read t => (t -> Constr) -> Maybe Constr
mkReadCon f = case (reads str) of
[(t,"")] -> Just (f t)
_ -> Nothing
-- Traverse list of algebraic datatype constructors
idx :: [Constr] -> Maybe Constr
idx cons = let fit = filter ((==) str . showConstr) cons
in if fit == []
then Nothing
else Just (head fit)
------------------------------------------------------------------------------
--
-- Convenience funtions: algebraic data types
--
------------------------------------------------------------------------------
-- | Test for an algebraic type
isAlgType :: DataType -> Bool
isAlgType dt = case datarep dt of
(AlgRep _) -> True
_ -> False
-- | Gets the constructor for an index
indexConstr :: DataType -> ConIndex -> Constr
indexConstr dt idx = case datarep dt of
(AlgRep cs) -> cs !! (idx-1)
_ -> error "indexConstr"
-- | Gets the index of a constructor
constrIndex :: Constr -> ConIndex
constrIndex con = case constrRep con of
(AlgConstr idx) -> idx
_ -> error "constrIndex"
-- | Gets the maximum constructor index
maxConstrIndex :: DataType -> ConIndex
maxConstrIndex dt = case dataTypeRep dt of
AlgRep cs -> length cs
_ -> error "maxConstrIndex"
------------------------------------------------------------------------------
--
-- Representation of primitive types
--
------------------------------------------------------------------------------
-- | Constructs the Int type
mkIntType :: String -> DataType
mkIntType = mkPrimType IntRep
-- | Constructs the Float type
mkFloatType :: String -> DataType
mkFloatType = mkPrimType FloatRep
-- | Constructs the String type
mkStringType :: String -> DataType
mkStringType = mkPrimType StringRep
-- | Helper for mkIntType, mkFloatType, mkStringType
mkPrimType :: DataRep -> String -> DataType
mkPrimType dr str = DataType
{ tycon = str
, datarep = dr
}
-- Makes a constructor for primitive types
mkPrimCon :: DataType -> String -> ConstrRep -> Constr
mkPrimCon dt str cr = Constr
{ datatype = dt
, conrep = cr
, constring = str
, confields = error $ concat ["constrFields : ", (tycon dt), " is primative"]
, confixity = error "constrFixity"
}
mkIntConstr :: DataType -> Integer -> Constr
mkIntConstr dt i = case datarep dt of
IntRep -> mkPrimCon dt (show i) (IntConstr i)
_ -> error "mkIntConstr"
mkFloatConstr :: DataType -> Double -> Constr
mkFloatConstr dt f = case datarep dt of
FloatRep -> mkPrimCon dt (show f) (FloatConstr f)
_ -> error "mkFloatConstr"
mkStringConstr :: DataType -> String -> Constr
mkStringConstr dt str = case datarep dt of
StringRep -> mkPrimCon dt str (StringConstr str)
_ -> error "mkStringConstr"
------------------------------------------------------------------------------
--
-- Non-representations for non-presentable types
--
------------------------------------------------------------------------------
-- | Constructs a non-representation
mkNorepType :: String -> DataType
mkNorepType str = DataType
{ tycon = str
, datarep = NoRep
}
-- | Test for a non-representable type
isNorepType :: DataType -> Bool
isNorepType dt = case datarep dt of
NoRep -> True
_ -> False
|
siddhanathan/ghc
|
testsuite/tests/typecheck/should_run/T1735_Help/Basics.hs
|
Haskell
|
bsd-3-clause
| 13,203
|
module Geometria.Cuboide
( volume
, area
) where
volume :: Float -> Float -> Float -> Float
volume a b c = areaRetangulo a b * c
area :: Float -> Float -> Float -> Float
area a b c = areaRetangulo a b * 2 + areaRetangulo a c * 2 + areaRetangulo c b * 2
areaRetangulo :: Float -> Float -> Float
areaRetangulo a b = a * b
|
tonussi/freezing-dubstep
|
proj1/Cuboide.hs
|
Haskell
|
mit
| 329
|
{-# LANGUAGE DeriveFunctor #-}
module Test.Smoke.Types.Results where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Test.Smoke.Paths
import Test.Smoke.Types.Assert
import Test.Smoke.Types.Base
import Test.Smoke.Types.Errors
import Test.Smoke.Types.Plans
import Test.Smoke.Types.Tests
class IsSuccess a where
isSuccess :: a -> Bool
isFailure :: a -> Bool
isFailure = not . isSuccess
type Results = [SuiteResult]
data SuiteResult
= SuiteResultError SuiteName SuiteError
| SuiteResult SuiteName (ResolvedPath Dir) [TestResult]
data TestResult
= TestResult
{ resultPlan :: TestPlan,
resultStatus :: EqualityResult Status,
resultStdOut :: AssertionResult StdOut,
resultStdErr :: AssertionResult StdErr,
resultFiles :: Map (RelativePath File) (AssertionResult TestFileContents)
}
| TestError Test SmokeError
| TestIgnored Test
instance IsSuccess TestResult where
isSuccess (TestResult _ statusResult stdOutResult stdErrResult filesResults) =
isSuccess statusResult && isSuccess stdOutResult && isSuccess stdErrResult && all isSuccess (Map.elems filesResults)
isSuccess TestError {} =
False
isSuccess TestIgnored {} =
False
data EqualityResult a
= EqualitySuccess
| EqualityFailure (Expected a) (Actual a)
deriving (Functor)
instance IsSuccess (EqualityResult a) where
isSuccess EqualitySuccess = True
isSuccess EqualityFailure {} = False
data AssertionResult a
= AssertionSuccess
| AssertionFailure (AssertionFailures a)
deriving (Functor)
instance IsSuccess (AssertionResult a) where
isSuccess AssertionSuccess = True
isSuccess AssertionFailure {} = False
|
SamirTalwar/Smoke
|
src/lib/Test/Smoke/Types/Results.hs
|
Haskell
|
mit
| 1,689
|
module AddStuff where
addStuff :: Integer -> Integer -> Integer
addStuff a b = a + b + 5
addTen = addStuff 5
fifteen = addTen 5
main :: IO ()
main = do
let x = addStuff 10 15
y = addTen 100
z = fifteen
putStrLn "=== Calculations ==="
putStr "addStuff 10 15: "
print x
putStr "addTen 100 : "
print y
putStr "fifteen : "
print z
-- print
-- print fifteen
|
Lyapunov/haskell-programming-from-first-principles
|
chapter_5/addstuff.hs
|
Haskell
|
mit
| 408
|
module Yesod.Auth.WeiXin.Utils where
import ClassyPrelude
import Yesod
import Control.Monad.Except hiding (replicateM)
import Data.List ((!!))
import Network.Wai (rawQueryString)
import System.Random (randomIO)
import qualified Control.Exception.Safe as ExcSafe
import Yesod.Compat
import WeiXin.PublicPlatform
import Yesod.Auth.WeiXin.Class
logSource :: Text
logSource = "WeixinAuthPlugin"
{-
hWithRedirectUrl :: (MonadHandler m, site ~ HandlerSite m, YesodAuthWeiXin site)
=> Route site
-> [(Text, Text)]
-> OAuthScope
-- ^ used only when inside WX
-> (WxppAppID -> UrlText -> m a)
-> m a
hWithRedirectUrl oauth_return_route params0 oauth_scope f = do
is_client_wx <- isJust <$> handlerGetWeixinClientVersion
let params = filter ((/= "code") . fst) params0
url_render <- getUrlRenderParams
let oauth_retrurn_url = UrlText $ url_render oauth_return_route params
oauth_retrurn_url2 <- liftHandlerT $ wxAuthConfigFixReturnUrl oauth_retrurn_url
let oauth_rdr_and_app_id = do
if is_client_wx
then do
app_id <- fmap fst wxAuthConfigInsideWX
random_state <- wxppOAuthMakeRandomState app_id
let m_comp_app_id = Nothing
let url = wxppOAuthRequestAuthInsideWx
m_comp_app_id
app_id
oauth_scope
oauth_retrurn_url2
random_state
return (app_id, url)
else do
app_id <- fmap fst wxAuthConfigOutsideWX
random_state <- wxppOAuthMakeRandomState app_id
let url = wxppOAuthRequestAuthOutsideWx app_id
oauth_retrurn_url2
random_state
return (app_id, url)
(app_id, rdr_url) <- liftHandlerT oauth_rdr_and_app_id
f app_id rdr_url
--}
neverCache :: MonadHandler m => m ()
neverCache = do
addHeader "Cache-Control" "no-cache, no-store, must-revalidate"
addHeader "Pragma" "no-cache"
addHeader "Expires" "0"
getCurrentUrl :: MonadHandler m => m Text
getCurrentUrl = do
req <- waiRequest
current_route <- getCurrentRoute >>= maybe (error "getCurrentRoute failed") return
url_render <- getUrlRender
return $ url_render current_route <> decodeUtf8 (rawQueryString req)
getOAuthAccessTokenBySecretOrBroker :: (IsString e, WxppApiBroker a
, HasWxppUrlConfig env, HasWxppUrlConfig env, HasWreqSession env
, ExcSafe.MonadCatch m, MonadIO m, MonadLogger m
)
=> env
-> Either WxppAppSecret a
-> WxppAppID
-> OAuthCode
-> ExceptT e m (Maybe OAuthAccessTokenResult)
getOAuthAccessTokenBySecretOrBroker wx_api_env secret_or_broker app_id code = do
case secret_or_broker of
Left secret -> do
err_or_atk_info <- lift $ tryWxppWsResult $
flip runReaderT wx_api_env $
wxppOAuthGetAccessToken app_id secret code
case err_or_atk_info of
Left err -> do
if fmap wxppToErrorCodeX (wxppCallWxError err) == Just (wxppToErrorCode WxppOAuthCodeHasBeenUsed)
then return Nothing
else do
$logErrorS logSource $
"wxppOAuthGetAccessToken failed: " <> tshow err
throwError "微信服务接口错误,请稍后重试"
Right x -> return $ Just x
Right broker -> do
bres <- liftIO $ wxppApiBrokerOAuthGetAccessToken broker app_id code
case bres of
Nothing -> do
$logErrorS logSource $
"wxppApiBrokerOAuthGetAccessToken return Nothing"
throwError "程序配置错误,请稍后重试"
Just (WxppWsResp (Left err@(WxppAppError wxerr _msg))) -> do
if wxppToErrorCodeX wxerr == wxppToErrorCode WxppOAuthCodeHasBeenUsed
then return Nothing
else do
$logErrorS logSource $
"wxppApiBrokerOAuthGetAccessToken failed: " <> tshow err
throwError "微信服务接口错误,请稍后重试"
Just (WxppWsResp (Right x)) -> return $ Just x
handlerGetQrCodeStateStorage :: (MonadHandler m, HandlerSite m ~ site, YesodAuthWeiXin site)
=> m ( Text -> HandlerOf site (Maybe WxScanQrCodeSess)
, Text -> WxScanQrCodeSess -> HandlerOf site ()
)
handlerGetQrCodeStateStorage = do
master_site <- getYesod
let m_storage = wxAuthQrCodeStateStorage master_site
case m_storage of
Just x -> return x
Nothing -> permissionDenied "no session storage available"
handlerGetQrCodeStateStorageAndSession :: ( m ~ HandlerOf site, YesodAuthWeiXin site)
=> Text
-> m ( ( Text -> HandlerOf site (Maybe WxScanQrCodeSess)
, Text -> WxScanQrCodeSess -> HandlerOf site ()
)
, WxScanQrCodeSess
)
handlerGetQrCodeStateStorageAndSession sess = do
(get_stat, save_stat) <- handlerGetQrCodeStateStorage
m_sess_dat <- get_stat sess
sess_dat <- case m_sess_dat of
Just x -> return x
Nothing -> permissionDenied "invalid session"
return ((get_stat, save_stat), sess_dat)
randomPick :: MonadIO m => [a] -> m a
randomPick choices = do
idx' <- liftIO randomIO
let idx = abs idx' `rem` chlen
return $ choices !! idx
where
chlen = length choices
randomString :: MonadIO m => Int -> [Char] -> m [Char]
randomString len chars = replicateM len (randomPick chars)
randomUrlSafeString :: MonadIO m => Int -> m [Char]
randomUrlSafeString = flip randomString $ ['0'..'9'] <> ['a'..'z'] <> ['A'..'Z'] <> "-_"
|
txkaduo/yesod-auth-wx
|
Yesod/Auth/WeiXin/Utils.hs
|
Haskell
|
mit
| 6,525
|
{------------------------------------------------------------------------------
uPuppet: Catalog rendering in JSON
------------------------------------------------------------------------------}
module UPuppet.ShowJSON ( showJSON ) where
import UPuppet.CState
import UPuppet.Catalog
import UPuppet.AST
import Data.Aeson
import Data.Text (Text,pack)
import Data.ByteString.Char8 (unpack)
import Data.ByteString.Lazy (toStrict)
-- would be nice if a type like this was used everywhere for resources.
-- creating a local version here so we can use it with the JSON typeclass
-- (paul)
data ResourceT = ResourceT (Name, Name, [(Attri, UPuppet.AST.Value)])
showJSON :: CState -> Catalog -> String
showJSON st catalog = unpack $ toStrict $ encode (map ResourceT catalog)
instance ToJSON ResourceT where
-- only emit parameter map if nonempty
toJSON ( ResourceT ( typeString, titleString, [] ) ) =
object [ typeJSON, titleJSON ]
where
typeJSON = paramToJSON ( "type", ValueString typeString )
titleJSON = paramToJSON( "title", ValueString titleString )
toJSON ( ResourceT ( typeString, titleString, params ) ) =
object [ typeJSON, titleJSON, paramsJSON ]
where
typeJSON = paramToJSON ( "type", ValueString typeString )
titleJSON = paramToJSON( "title", ValueString titleString )
paramsJSON = (pack "parameters") .=
( object $ map paramToJSON params )
paramToJSON :: (Attri, UPuppet.AST.Value) -> (Text,Data.Aeson.Value)
paramToJSON (attr,value) = (pack attr) .= toJSON value
instance ToJSON UPuppet.AST.Value where
toJSON (ValueInt n) = toJSON n
toJSON (ValueBool b) = toJSON b
toJSON (ValueString str) = toJSON str
toJSON (ValueFloat f) = toJSON f
toJSON (ValueArray vs) = toJSON vs
toJSON (ValueHash vvs) = object $ map hashPairToJSON vvs
toJSON (ValueRef rn t) = toJSON (rn ++ "[" ++ t ++ "]")
-- I think that the type definitions are wrong here?
-- surely, the hash keys should be strings (only) ?
-- (paul)
hashPairToJSON :: (UPuppet.AST.Value, UPuppet.AST.Value) -> (Text,Data.Aeson.Value)
hashPairToJSON (attrValue,value) = case attrValue of
(ValueString s) -> (pack s) .= toJSON value
otherwise -> error "hash key is not a string???"
|
dcspaul/uPuppet
|
Src/UPuppet/ShowJSON.hs
|
Haskell
|
mit
| 2,224
|
module Pattern1 where
data Bool = False | True
not True = False
not False = True
|
Lemmih/haskell-tc
|
tests/Pattern1.hs
|
Haskell
|
mit
| 83
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Hpack.Render.Dsl (
-- * AST
Element (..)
, Value (..)
-- * Render
, RenderSettings (..)
, CommaStyle (..)
, defaultRenderSettings
, Alignment (..)
, Nesting
, render
-- * Utils
, sortFieldsBy
#ifdef TEST
, Lines (..)
, renderValue
, addSortKey
#endif
) where
import Data.String
import Data.List
data Value =
Literal String
| CommaSeparatedList [String]
| LineSeparatedList [String]
| WordList [String]
deriving (Eq, Show)
data Element = Stanza String [Element] | Group Element Element | Field String Value | Verbatim String
deriving (Eq, Show)
data Lines = SingleLine String | MultipleLines [String]
deriving (Eq, Show)
data CommaStyle = LeadingCommas | TrailingCommas
deriving (Eq, Show)
newtype Nesting = Nesting Int
deriving (Eq, Show, Num, Enum)
newtype Alignment = Alignment Int
deriving (Eq, Show, Num)
data RenderSettings = RenderSettings {
renderSettingsIndentation :: Int
, renderSettingsFieldAlignment :: Alignment
, renderSettingsCommaStyle :: CommaStyle
} deriving (Eq, Show)
defaultRenderSettings :: RenderSettings
defaultRenderSettings = RenderSettings 2 0 LeadingCommas
render :: RenderSettings -> Nesting -> Element -> [String]
render settings nesting (Stanza name elements) = indent settings nesting name : renderElements settings (succ nesting) elements
render settings nesting (Group a b) = render settings nesting a ++ render settings nesting b
render settings nesting (Field name value) = renderField settings nesting name value
render settings nesting (Verbatim str) = map (indent settings nesting) (lines str)
renderElements :: RenderSettings -> Nesting -> [Element] -> [String]
renderElements settings nesting = concatMap (render settings nesting)
renderField :: RenderSettings -> Nesting -> String -> Value -> [String]
renderField settings@RenderSettings{..} nesting name value = case renderValue settings value of
SingleLine "" -> []
SingleLine x -> [indent settings nesting (name ++ ": " ++ padding ++ x)]
MultipleLines [] -> []
MultipleLines xs -> (indent settings nesting name ++ ":") : map (indent settings $ succ nesting) xs
where
Alignment fieldAlignment = renderSettingsFieldAlignment
padding = replicate (fieldAlignment - length name - 2) ' '
renderValue :: RenderSettings -> Value -> Lines
renderValue RenderSettings{..} v = case v of
Literal s -> SingleLine s
WordList ws -> SingleLine $ unwords ws
LineSeparatedList xs -> renderLineSeparatedList renderSettingsCommaStyle xs
CommaSeparatedList xs -> renderCommaSeparatedList renderSettingsCommaStyle xs
renderLineSeparatedList :: CommaStyle -> [String] -> Lines
renderLineSeparatedList style = MultipleLines . map (padding ++)
where
padding = case style of
LeadingCommas -> " "
TrailingCommas -> ""
renderCommaSeparatedList :: CommaStyle -> [String] -> Lines
renderCommaSeparatedList style = MultipleLines . case style of
LeadingCommas -> map renderLeadingComma . zip (True : repeat False)
TrailingCommas -> map renderTrailingComma . reverse . zip (True : repeat False) . reverse
where
renderLeadingComma :: (Bool, String) -> String
renderLeadingComma (isFirst, x)
| isFirst = " " ++ x
| otherwise = ", " ++ x
renderTrailingComma :: (Bool, String) -> String
renderTrailingComma (isLast, x)
| isLast = x
| otherwise = x ++ ","
instance IsString Value where
fromString = Literal
indent :: RenderSettings -> Nesting -> String -> String
indent RenderSettings{..} (Nesting nesting) s = replicate (nesting * renderSettingsIndentation) ' ' ++ s
sortFieldsBy :: [String] -> [Element] -> [Element]
sortFieldsBy existingFieldOrder =
map snd
. sortOn fst
. addSortKey
. map (\a -> (existingIndex a, a))
where
existingIndex :: Element -> Maybe Int
existingIndex (Field name _) = name `elemIndex` existingFieldOrder
existingIndex _ = Nothing
addSortKey :: [(Maybe Int, a)] -> [((Int, Int), a)]
addSortKey = go (-1) . zip [0..]
where
go :: Int -> [(Int, (Maybe Int, a))] -> [((Int, Int), a)]
go n xs = case xs of
[] -> []
(x, (Just y, a)) : ys -> ((y, x), a) : go y ys
(x, (Nothing, a)) : ys -> ((n, x), a) : go n ys
|
haskell-tinc/hpack
|
src/Hpack/Render/Dsl.hs
|
Haskell
|
mit
| 4,314
|
module Storage.Distributed where
|
axman6/HaskellMR
|
src/Storage/Distributed.hs
|
Haskell
|
mit
| 34
|
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Yage.Geometry
( module Yage.Geometry
, module Elements
) where
import Yage.Lens
import Yage.Math
import Yage.Prelude hiding (any, sum, toList, (++))
import Control.Applicative (liftA3)
import Data.Binary
import Data.Foldable (any, toList)
import Data.Vector ((++))
import qualified Data.Vector as V
import qualified Data.Vector.Binary ()
import Yage.Geometry.Elements as Elements
-- wrapping neccassry because of ghc bug
-- https://github.com/bos/vector-binary-instances/issues/4
newtype GeoSurface e = GeoSurface { unGeoSurface :: Vector e }
deriving ( Show, Eq, Ord, Functor, Foldable, Traversable, Generic )
data Geometry e v = Geometry
{ _geoVertices :: Vector v
-- ^ all vertices of this geometry
, _geoSurfaces :: Vector (GeoSurface e)
-- ^ list of surfaces of the geometry. defined by objects (like Triangle Int) with indices to `geoVertices`
} deriving ( Show, Eq, Ord, Functor, Foldable, Traversable, Generic )
makeLenses ''Geometry
type TriGeo = Geometry (Triangle Int)
-- | constructs a TriGeo from vertices, interpreted as triangles, as single surface and without reindexing
makeSimpleTriGeo :: Vector v -> TriGeo v
makeSimpleTriGeo verts = Geometry verts simpleIxs
where
triCnt = V.length verts `div` 3
simpleIxs = V.singleton . GeoSurface $ V.zipWith3 Triangle
(V.generate triCnt (3*))
(V.generate triCnt (\i -> i*3+1))
(V.generate triCnt (\i -> i*3+2))
-- | like `makeSimpleTriGeo` but extracts vertices from a `Foldable`
makeSimpleTriGeoF :: ( HasTriangles t, Foldable f ) => f (t v) -> TriGeo v
makeSimpleTriGeoF = makeSimpleTriGeo . V.concatMap (V.fromList . vertices) . V.map triangles . V.fromList . toList
empty :: Geometry e v
empty = Geometry V.empty V.empty
{--
indexedSurface :: Eq v => Surface (Triangle v) -> TriGeo v
indexedSurface triSurf =
let surfVec = V.fromList $ nub $ concatMap vertices $ getSurface triSurf
in Geometry { geoVerices = undefined
, geoElements = undefined
}
--}
type Pos = V3
type Normal = V3
type Tex = V2
type TBN a = M33 a
-- | calc tangent spaces for each triangle. averages for normals and tangents are calculated on surfaces
calcTangentSpaces :: ( Epsilon a, Floating a ) =>
TriGeo (Pos a) ->
TriGeo (Tex a) ->
TriGeo (TBN a)
calcTangentSpaces posGeo texGeo =
calcTangentSpaces' posGeo texGeo $ calcNormals posGeo
calcNormals :: ( Epsilon a, Floating a )
=> TriGeo (Pos a) -> TriGeo (Normal a)
calcNormals geo = uncurry Geometry normalsOverSurfaces
where
normalsOverSurfaces = V.foldl' normalsForSurface (V.empty, V.empty) (geo^.geoSurfaces)
normalsForSurface (normsAccum, surfacesAccum) (GeoSurface surface) =
let (normVerts, normedSurface) = V.foldl' (normalsForTriangle surface) (normsAccum, V.empty) surface
in (normVerts, surfacesAccum `V.snoc` (GeoSurface normedSurface) )
normalsForTriangle inSurface (vertsAccum, surfaceAccum) triangle =
let normedTri = fmap (calcAvgNorm inSurface) triangle
idx = V.length vertsAccum
idxTri = Triangle idx (idx + 1) (idx + 2)
in vertsAccum `seq`
surfaceAccum `seq`
(vertsAccum ++ (V.fromList . toList $ normedTri), surfaceAccum `V.snoc` idxTri)
posVerts = geo^.geoVertices
calcAvgNorm surface idx = averageNorm $ V.map (triangleUnnormal . toPosTri) $ getShares idx surface
toPosTri = fmap (posVerts V.!)
calcTangentSpaces' :: forall a. ( Epsilon a, Floating a ) =>
TriGeo (Pos a) ->
TriGeo (Tex a) ->
TriGeo (Normal a) ->
TriGeo (TBN a)
calcTangentSpaces' posGeo texGeo normGeo
| not compatibleSurfaces = error "calcTangentSpaces': surfaces doesn't match"
| otherwise = uncurry Geometry tbnOverSurfaces
where
tbnOverSurfaces = V.foldl' tbnForSurface (V.empty, V.empty) pntIdxs
tbnForSurface (tbnAccum, surfacesAccum) (GeoSurface geoSurface) =
let (tbnVerts, tbnSurface) = V.foldl' (tbnForTriangle geoSurface) (tbnAccum, V.empty) geoSurface
in tbnVerts `seq`
surfacesAccum `seq`
(tbnVerts, surfacesAccum `V.snoc` (GeoSurface tbnSurface) )
tbnForTriangle inSurface (vertsAccum, surfaceAccum) triangle =
let tbnTriangle = fmap (calcTangentSpace inSurface) triangle
idx = V.length vertsAccum
idxTri = Triangle idx (idx + 1) (idx + 2)
in vertsAccum `seq`
surfaceAccum `seq`
(vertsAccum ++ (V.fromList . toList $ tbnTriangle), surfaceAccum `V.snoc` idxTri )
pntIdxs :: Vector (GeoSurface (Triangle (Int, Int, Int)))
pntIdxs =
let mkSurface (GeoSurface p) (GeoSurface n) (GeoSurface t) = GeoSurface $ V.zipWith3 (liftA3 (,,)) p n t
in V.zipWith3 mkSurface (posGeo^.geoSurfaces) ( normGeo^.geoSurfaces) ( texGeo^.geoSurfaces)
toPNTTri :: ( Epsilon a, Floating a) => Triangle (Int, Int, Int) -> (Triangle (Pos a), Triangle (Normal a), Triangle (Tex a))
toPNTTri tri = ( (V.!) (posGeo^.geoVertices) . (^._1) <$> tri
, (V.!) (normGeo^.geoVertices) . (^._2) <$> tri
, (V.!) (texGeo^.geoVertices) . (^._3) <$> tri
)
calcTangentSpace :: ( Epsilon a, Floating a) => V.Vector (Triangle (Int, Int, Int)) -> (Int, Int, Int) -> M33 a
calcTangentSpace geoSurface (posIdx, normIdx, _texIdx) =
let normal = V.unsafeIndex (normGeo^.geoVertices) normIdx
toPTTri (p,_,t) = (p,t)
sharePosIdx :: Int -> Triangle (Int, Int, Int) -> Bool
sharePosIdx i = any (\(p,_,_) -> p==i)
~(V3 t b _n) = V.sum $ V.map (uncurry triangleTangentSpace . toPTTri . toPNTTri) $ V.filter (sharePosIdx posIdx) geoSurface
in orthonormalize $ V3 t b normal
compatibleSurfaces =
let posSurfaces = posGeo^.geoSurfaces^..traverse.to (length.unGeoSurface)
texSurfaces = texGeo^.geoSurfaces^..traverse.to (length.unGeoSurface)
normSurfaces = normGeo^.geoSurfaces^..traverse.to (length.unGeoSurface)
in posSurfaces == texSurfaces && posSurfaces == normSurfaces
getShares :: Int -> Vector (Triangle Int) -> Vector (Triangle Int)
getShares i = V.filter (any (==i))
instance Binary e => Binary (GeoSurface e)
instance (Binary e, Binary v) => Binary (Geometry e v)
instance (NFData e) => NFData (GeoSurface e) where rnf = genericRnf
instance (NFData e, NFData v) => NFData (Geometry e v) where rnf = genericRnf
|
MaxDaten/yage-geometry
|
src/Yage/Geometry.hs
|
Haskell
|
mit
| 7,237
|
-- | pontarius core
module Main where
|
Philonous/pontarius-core
|
src/Main.hs
|
Haskell
|
mit
| 39
|
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Text.Parsec
import Control.Monad (when)
import Data.Maybe (fromJust, listToMaybe, catMaybes)
import System.Environment (getArgs)
import System.Console.Docopt
import System.IO (stderr, hPutStrLn)
import System.IO.Unsafe (unsafePerformIO)
{-import Data.Maybe (isJust, fromJust)-}
{-import Debug.Trace-}
patterns :: Docopt
patterns = [docoptFile|USAGE|]
main'' = putStrLn "Hello World!"
main' = do
(infile:outfile:_) <- getArgs
contents <- readFile infile
let res = parse cmParse "" contents
case res of
Left err -> putStrLn $ show err
Right res' -> writeFile outfile res'
main = do
args <- parseArgsOrExit patterns =<< getArgs
when (isPresent args (longOption "help")) $ do
exitWithUsage patterns
when ((isPresent args (argument "INFILE")) || (isPresent args (argument "OUTFILE"))) $ do
hPutStrLn stderr deprecationWarning
contents <- input args
case (parse cmParse "" contents) of
Left err -> putStrLn $ show err
Right out -> output args out
where
deprecationWarning = "`criticmarkuphs INFILE OUTFILE` is deprecated\nSee `criticmarkuphs -h`"
maybeFile args lo ar = listToMaybe $ catMaybes [getArg args (longOption lo), getArg args (argument ar)]
input args = case (maybeFile args "infile" "INFILE") of
Just file -> readFile file
Nothing -> getContents
output args out = case (maybeFile args "outfile" "OUTFILE") of
Just file -> writeFile file out
Nothing -> putStr out
-- should CM keep or drop the text between tags
data Keep = Keep | Drop
deriving (Show)
-- 3 types of tages
-- EOF tag
-- "terminator" tag, containing string indicating end of tag
-- regular tag, containing:
-- . open tag string
-- . transition tag ending current tag
-- . keep/drop text in tag
data CMTag = EOF | Close String | Tag String CMTag Keep
deriving (Show)
-- critic markup tags
cmAdd = Tag "{++" (Close "++}") Keep
cmDel = Tag "{--" (Close "--}") Drop
cmSub = Tag "{~~" (Tag "~>" (Close "~~}") Keep) Drop
cmHil = Tag "{==" (Close "==}") Keep
cmCom = Tag "{>>" (Close "<<}") Drop
cmTags :: [CMTag]
cmTags = [cmAdd,cmDel,cmSub,cmHil,cmCom]
-- | builds the stop characters
stopChars :: String -> CMTag -> String
stopChars stops EOF = stops
stopChars stops (Close str) = addHead stops str
stopChars stops (Tag str _ _) = addHead stops str
-- | prepends the head of a possibly empty string to another string
addHead :: String -> String -> String
addHead str "" = str
addHead str (x:xs) = x:str
-- | keep or drop results of the parser
-- n.b. have to make sure to run the parser even when dropping its results
keepFilter :: Keep -> Parsec String () String -> Parsec String () String
keepFilter Keep x = x
keepFilter Drop x = x >> return ""
matchTag :: CMTag -> Parsec String () String
matchTag EOF = eof >> return ""
matchTag (Close x) = try $ string x >> return ""
matchTag (Tag start stop keep) = do
try $ string start
pre <- keepFilter keep (many $ noneOf stopChars')
post <- matchTag stop <|> -- match the end tag
choice (map innerTag cmTags) <|> -- match a new tag, and continue parsing
choice (map loneStopChar stopChars') -- match a lone stop character, and continue parsing
return (pre ++ post)
where
tagStarts = "{~"
stopChars' = stopChars tagStarts stop
restTag = matchTag (Tag "" stop keep)
loneStopChar x = innerParse (char x >> return [x])
innerTag tag = innerParse (matchTag tag)
innerParse x = do
inner <- keepFilter keep $ x
rest <- restTag
return (inner ++ rest)
cmParse :: Parsec String () String
cmParse = matchTag (Tag "" EOF Keep)
{-cmStart' :: CMTag -> Parsec String () String-}
{-cmStart' (Tag )-}
{- what's the structure of a critic markup document?
- n.b. there is not actually a spec wrt:
- 1. escaping tags in text: e.g. how to insert a literal "{++"?
- 2. overlapping tags: "{++ lorem {>> ipsum ++} dolor <<}" parses to what?
- let's ban overlaps, and no escaping for now
- structure:
- text -> tag + text -> recurse
-}
{-cmStart :: Maybe String -> Parsec String () String-}
{-cmStart Nothing = do-}
{-pre <- many (noneOf "{")-}
{--- we've hit the typical break-}
{-(inner, post) <- cmRest Nothing-}
{-return (concat [pre,inner,post])-}
{-cmStart (Just end@(x:xs)) = do-}
{-pre <- many (noneOf $ x:"{")-}
{--- we stopped because: we ended the tag, we matched the end of tag char, or the usual break-}
{-(try $ string end >> return pre) <|>-}
{-(try $ char x >> cmStart (Just end) >>= \post -> return (concat [pre,[x],post])) <|>-}
{-(cmRest (Just end) >>= \(inner,post) -> return (concat [pre,inner,post]))-}
runTests = sequence_ $ map (outstr) tests
where
outstr' x = putStr ("\"" ++ x ++ "\" :=>: ") >> (parseTest cmParse x)
outstr (x,y) = do
let res = parse cmParse "" x
case res of
Left err -> putStrLn ("Error :: \"" ++ x ++ "\" :=>: " ++ (show err))
Right res' -> if res' == y then putStr "" else putStrLn ("Misparse :: \"" ++ x ++ "\" :=>: \"" ++ res' ++ "\"")
tests = [
("test","test"),
("test {++foo++} test","test foo test"),
("test {--foo--} test","test test"),
("test {--{++foo++}bar--} test","test test"),
("test {++{--foo--}bar++} test","test bar test"),
("test {~~foo~>bar~~} test","test bar test"),
("test {~~foo{++baz++}~>bar~~} test","test bar test"),
("test {~~foo{--baz--}~>bar~~} test","test bar test"),
("test {++foo",""),
("test","test")
]
{-tests = [-}
{-("{++test++}","test"),-}
{-("{++test{++tester++}++}","test{++tester++}")]-}
|
balachia/CriticMarkup.hs
|
CriticMarkup.hs
|
Haskell
|
mit
| 5,862
|
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module CustomContentsDialog where
import Data.Maybe (isJust, fromJust)
import Data.List
import Control.Applicative
import Graphics.UI.Gtk
import Control.Lens hiding (set)
import Data.Either
import SettingsWindowData
import GtkViewModel
import FrameRenderer
import Settings
import Helpers
completionDataDate :: [(String, String)]
completionDataDate = [
(__ "Date formatted in your system language", "%x"),
(__ "Hours and minutes", "%R"),
(__ "Hours, minutes and seconds", "%X"),
(__ "Hour of the day (24h). 00-23", "%H"),
(__ "Hour of the day (24h). 0-23", "%k"),
(__ "Hour of half-day (12h). 01-12", "%I"),
(__ "Hour of half-day (12h). 1-12", "%l"),
(__ "Minute of hour, 00-59", "%M"),
(__ "Second of minute, 00-60", "%S"),
(__ "Year", "%Y"),
(__ "Year of century, 00-99", "%y"),
(__ "Month name, long form, January-December", "%B"),
(__ "Month name, short form, Jan-Dec", "%b"),
(__ "Month of year, 01-12", "%m"),
(__ "Day of month, 01-31", "%d"),
(__ "Day of month, 1-31", "%e"),
(__ "Day of week, short form, Sun-Sat", "%a"),
(__ "Day of week, long form, Sunday-Saturday", "%A")
]
defaultEnvironmentInfo :: EnvironmentInfo
#ifdef CABAL_OS_WINDOWS
defaultEnvironmentInfo = EnvironmentInfo "c:\\Users\\user"
#else
defaultEnvironmentInfo = EnvironmentInfo "/home/user"
#endif
data CompletionRecordType = NormalCompletion | DateCompletion
deriving (Eq, Show)
data CompletionRecord = CompletionRecord
{
complRecordType :: CompletionRecordType,
complRecordDesc :: String,
complRecordValue :: String
} deriving Show
isDateRecord :: CompletionRecord -> Bool
isDateRecord (CompletionRecord t _ _) = t == DateCompletion
showCustomContentsDialog :: WindowClass a => a -> BuilderHolder -> Model DisplayItem -> IO ()
showCustomContentsDialog parent builderHolder displayItemModel = do
let builder = boundBuilder builderHolder
dialog <- builderGetObject builder castToDialog "customContentsDialog"
customContentsEntry <- builderGetObject builder castToEntry "customContentsEntry"
curContents <- itemContents <$> readModel displayItemModel
okBtnBinder <- builderHolderGetButtonBinder builderHolder "customContentsOK"
let okBtn = boundButton okBtnBinder
cancelBtn <- builderGetObject builder castToButton "customContentsCancel"
defaultDisplayItem <- readModel displayItemModel
parseResultLabel <- builderGetObject builder castToLabel "parseResultLabel"
customContentsEntry `on` editableChanged $ do
text <- entryGetText customContentsEntry
let isParseOk = not $ isLeft $ parseFormat text
labelSetMarkup parseResultLabel $ if isParseOk
then getTextToRender (defaultDisplayItem {itemContents = text}) fakeImageInfo defaultEnvironmentInfo
else __ "<span color='red'><b>Incorrect syntax</b></span>"
widgetSetSensitivity okBtn isParseOk
entrySetText customContentsEntry curContents
completion <- entryCompletionNew
let completionData = fmap (uncurry $ CompletionRecord NormalCompletion) completionComboData
++ [CompletionRecord NormalCompletion (__ "% sign") "%%"]
++ fmap (uncurry $ CompletionRecord DateCompletion) completionDataDate
++ [CompletionRecord DateCompletion (__ "% sign") "%%"]
completionStore <- listStoreNew completionData
entryCompletionSetModel completion $ Just completionStore
cellValue <- cellRendererTextNew
cellLayoutPackStart completion cellValue True
cellLayoutSetAttributes completion cellValue completionStore
(\val -> [cellText := complRecordDesc val])
cellDesc <- cellRendererTextNew
cellLayoutPackStart completion cellDesc True
cellLayoutSetAttributes completion cellDesc completionStore
(\val -> [cellText := complRecordValue val])
entryCompletionSetMinimumKeyLength completion 1
entryCompletionSetMatchFunc completion $
customContentsCompletionCb completionData customContentsEntry
entrySetCompletion customContentsEntry completion
completion `on` matchSelected $ \_ iter -> do
let candidate = completionData !! listStoreIterToIndex iter
textSoFar <- entryGetText customContentsEntry
cursorPosBefore <- get customContentsEntry entryCursorPosition
let (beforeCursor, afterCursor) = splitAt cursorPosBefore textSoFar
textWhichGotCompleted <- fromJust <$> textBeforeCursorFromSymbol "%" customContentsEntry
let lengthBeforeCompletion = length beforeCursor - length textWhichGotCompleted
let newText = take lengthBeforeCompletion textSoFar
++ complRecordValue candidate ++ afterCursor
entrySetText customContentsEntry newText
let newPos = lengthBeforeCompletion + length (complRecordValue candidate)
editableSetPosition customContentsEntry newPos
return True
buttonBindCallback okBtnBinder $ do
newText <- entryGetText customContentsEntry
modifyModel displayItemModel $ itemContentsL .~ newText
widgetHide dialog
cancelBtn `on` buttonActivated $ widgetHide dialog
showDialog dialog parent
textBeforeCursorFromSymbol :: String -> Entry -> IO (Maybe String)
textBeforeCursorFromSymbol symbol entry = do
cursorPos <- get entry entryCursorPosition
typed <- take cursorPos <$> entryGetText entry
return $ find (isPrefixOf symbol) $ tail $ reverse $ tails typed
customContentsCompletionCb :: [CompletionRecord] -> Entry -> String -> TreeIter -> IO Bool
customContentsCompletionCb completionModel entry _ iter = do
let candidate = completionModel !! listStoreIterToIndex iter
beforePercent <- textBeforeCursorFromSymbol "%" entry
beforeDate <- textBeforeCursorFromSymbol "%date{" entry
let inDateContext = isJust beforeDate && not ("}" `isInfixOf` fromJust beforeDate)
case beforePercent of
Nothing -> return False
Just fromPercent | inDateContext ->
return $ isDateRecord candidate && fromPercent `isPrefixOf` complRecordValue candidate
Just fromPercent ->
return $ not (isDateRecord candidate) && fromPercent `isPrefixOf` complRecordValue candidate
|
emmanueltouzery/imprint
|
src/CustomContentsDialog.hs
|
Haskell
|
mit
| 6,301
|
import TwoPhase
import Control.Applicative
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import System.IO
main :: IO ()
main = do
args <- getArgs
path <- case args of
[] -> (</> ".tseven") <$> getHomeDirectory
p : _ -> return p
createDirectoryIfMissing
True -- createParents
path
let p1 = path </> "phase1"
p2 = path </> "phase2"
fileExists <- and <$> mapM doesFileExist [p1,p2]
case fileExists of
True -> do
hPutStrLn stderr $ "File(s) already exist(s) in '" ++ path ++"'."
exitFailure
False -> do
putStrLn "Phase 1"
encodeFile p1 phase1Compressed'
putStrLn "Phase 2"
encodeFile p2 phase2Compressed'
exitSuccess
|
Lysxia/twentyseven
|
exec-src/tstables.hs
|
Haskell
|
mit
| 755
|
--
-- Euler published the remarkable quadratic formula:
--
-- n^2 + n + 41
--
-- It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39.
-- However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when
-- n = 41, 41² + 41 + 41 is clearly divisible by 41.
--
-- Using computers, the incredible formula n^2 79n + 1601 was discovered, which produces
-- 80 primes for the consecutive values n = 0 to 79. The product of the coefficients,
-- 79 and 1601, is 126479.
--
-- Considering quadratics of the form:
--
-- n^2 + an + b, where |a| < 1000 and |b| < 1000
--
-- where |n| is the modulus/absolute value of n
-- e.g. |11| = 11 and |4| = 4
-- Find the product of the coefficients, a and b, for the quadratic expression that produces
-- the maximum number of primes for consecutive values of n, starting with n = 0.
--
import List
import Maybe
import Data.Ord
primes
= 2 : 3 : filter isPrime [5,7..]
isPrime n
= all (notDivs n) $ takeWhile (\ p -> p * p <= n) primes
where notDivs n p = n `mod` p /= 0
numPrimesInQuadratic a b
= length $ takeWhile nthIsPrime [0..]
where nthIsPrime n = isPrime $ toInteger $ abs $ n * n + a * n + b
consecutives
= do a <- [-999 .. 999]
b <- [-999 .. 999]
return (a * b, numPrimesInQuadratic a b)
main
= print $ maximumBy (comparing snd) consecutives
|
stu-smith/project-euler-haskell
|
Euler-027.hs
|
Haskell
|
mit
| 1,440
|
{-# LANGUAGE OverloadedStrings #-}
module HepMC.Units
( Units, unitMomentum, unitLength
, parserUnits
) where
import Control.Lens
import HepMC.Parse
data UnitMomentum = MEV | GEV deriving (Eq, Ord, Show)
data UnitLength = MM | CM deriving (Eq, Ord, Show)
type Units = (UnitMomentum, UnitLength)
unitMomentum :: Lens' Units UnitMomentum
unitMomentum = _1
unitLength :: Lens' Units UnitLength
unitLength = _2
unitP :: Parser UnitMomentum
unitP =
string "MEV" *> return MEV <|> string "GEV" *> return GEV
unitL :: Parser UnitLength
unitL =
string "MM" *> return MM <|> string "CM" *> return CM
parserUnits :: Parser Units
parserUnits = tuple (unitP <* skipSpace) (unitL <* skipSpace)
|
cspollard/HHepMC
|
src/HepMC/Units.hs
|
Haskell
|
apache-2.0
| 720
|
-- do can have explicit semi colons
f x = do x
x; x
|
metaborg/jsglr
|
org.spoofax.jsglr/tests-offside/terms/doaitse/layout10.hs
|
Haskell
|
apache-2.0
| 60
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.SecurityContext where
import GHC.Generics
import Kubernetes.V1.Capabilities
import Kubernetes.V1.SELinuxOptions
import qualified Data.Aeson
-- | SecurityContext holds security configuration that will be applied to a container. Some fields are present in both SecurityContext and PodSecurityContext. When both are set, the values in SecurityContext take precedence.
data SecurityContext = SecurityContext
{ capabilities :: Maybe Capabilities -- ^ The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime.
, privileged :: Maybe Bool -- ^ Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false.
, seLinuxOptions :: Maybe SELinuxOptions -- ^ The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
, runAsUser :: Maybe Integer -- ^ The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
, runAsNonRoot :: Maybe Bool -- ^ Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON SecurityContext
instance Data.Aeson.ToJSON SecurityContext
|
minhdoboi/deprecated-openshift-haskell-api
|
kubernetes/lib/Kubernetes/V1/SecurityContext.hs
|
Haskell
|
apache-2.0
| 2,187
|
module Kernel.KernelMonad where
import Kernel.Term
import Kernel.Env
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.Error
data KernelError = TypeError String [(LocalEnv, Term)]
| FatalError String
instance Error KernelError where
strMsg = FatalError
{-
instance Show KernelError where
show (TypeError s ts) = "type error: " ++ s ++ " " ++ show (map (uncurry LocalTerm) ts)
show (FatalError s) = "fatal error: " ++ s
-}
newtype Kernel a = Kernel { unKernel :: ErrorT KernelError (Reader Global) a }
instance Functor Kernel where
fmap = liftM
instance Applicative Kernel where
pure = return
(<*>) = ap
instance Monad Kernel where
return = Kernel . return
(Kernel m) >>= k = Kernel $ m >>= \x -> unKernel (k x)
getGlobalBindings :: Kernel GlobalBindings
getGlobalBindings = Kernel $ gbindings <$> ask
getUniverseBindings :: Kernel UnivBindings
getUniverseBindings = Kernel $ ubindings <$> ask
typeError :: String -> [(LocalEnv, Term)] -> Kernel a
typeError s ts = Kernel $ throwError $ TypeError s ts
fatalError :: String -> Kernel a
fatalError s = Kernel $ throwError $ FatalError s
|
kik/ToyPr
|
src/Kernel/KernelMonad.hs
|
Haskell
|
apache-2.0
| 1,156
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDragMoveEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QDragMoveEvent (
QqqDragMoveEvent(..), QqDragMoveEvent(..)
,QqqDragMoveEvent_nf(..), QqDragMoveEvent_nf(..)
,qaccept
,qanswerRect, answerRect
,qignore
,qDragMoveEvent_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Core.QEvent
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
class QqqDragMoveEvent x1 where
qqDragMoveEvent :: x1 -> IO (QDragMoveEvent ())
class QqDragMoveEvent x1 where
qDragMoveEvent :: x1 -> IO (QDragMoveEvent ())
instance QqDragMoveEvent ((QDragMoveEvent t1)) where
qDragMoveEvent (x1)
= withQDragMoveEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent cobj_x1
foreign import ccall "qtc_QDragMoveEvent" qtc_QDragMoveEvent :: Ptr (TQDragMoveEvent t1) -> IO (Ptr (TQDragMoveEvent ()))
instance QqqDragMoveEvent ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragMoveEvent (x1, x2, x3, x4, x5)
= withQDragMoveEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragMoveEvent1" qtc_QDragMoveEvent1 :: Ptr (TQPoint t1) -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
instance QqDragMoveEvent ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragMoveEvent (x1, x2, x3, x4, x5)
= withQDragMoveEventResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragMoveEvent2" qtc_QDragMoveEvent2 :: CInt -> CInt -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
instance QqqDragMoveEvent ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qqDragMoveEvent (x1, x2, x3, x4, x5, x6)
= withQDragMoveEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent3 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
foreign import ccall "qtc_QDragMoveEvent3" qtc_QDragMoveEvent3 :: Ptr (TQPoint t1) -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
instance QqDragMoveEvent ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qDragMoveEvent (x1, x2, x3, x4, x5, x6)
= withQDragMoveEventResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent4 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
foreign import ccall "qtc_QDragMoveEvent4" qtc_QDragMoveEvent4 :: CInt -> CInt -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
class QqqDragMoveEvent_nf x1 where
qqDragMoveEvent_nf :: x1 -> IO (QDragMoveEvent ())
class QqDragMoveEvent_nf x1 where
qDragMoveEvent_nf :: x1 -> IO (QDragMoveEvent ())
instance QqDragMoveEvent_nf ((QDragMoveEvent t1)) where
qDragMoveEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent cobj_x1
instance QqqDragMoveEvent_nf ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragMoveEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
instance QqDragMoveEvent_nf ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragMoveEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
instance QqqDragMoveEvent_nf ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qqDragMoveEvent_nf (x1, x2, x3, x4, x5, x6)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent3 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
instance QqDragMoveEvent_nf ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qDragMoveEvent_nf (x1, x2, x3, x4, x5, x6)
= withObjectRefResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent4 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
instance Qaccept (QDragMoveEvent a) (()) where
accept x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_accept cobj_x0
foreign import ccall "qtc_QDragMoveEvent_accept" qtc_QDragMoveEvent_accept :: Ptr (TQDragMoveEvent a) -> IO ()
qaccept :: QDragMoveEvent a -> ((QRect t1)) -> IO ()
qaccept x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent_accept1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDragMoveEvent_accept1" qtc_QDragMoveEvent_accept1 :: Ptr (TQDragMoveEvent a) -> Ptr (TQRect t1) -> IO ()
instance Qaccept (QDragMoveEvent a) ((Rect)) where
accept x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QDragMoveEvent_accept1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QDragMoveEvent_accept1_qth" qtc_QDragMoveEvent_accept1_qth :: Ptr (TQDragMoveEvent a) -> CInt -> CInt -> CInt -> CInt -> IO ()
qanswerRect :: QDragMoveEvent a -> (()) -> IO (QRect ())
qanswerRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_answerRect cobj_x0
foreign import ccall "qtc_QDragMoveEvent_answerRect" qtc_QDragMoveEvent_answerRect :: Ptr (TQDragMoveEvent a) -> IO (Ptr (TQRect ()))
answerRect :: QDragMoveEvent a -> (()) -> IO (Rect)
answerRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_answerRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QDragMoveEvent_answerRect_qth" qtc_QDragMoveEvent_answerRect_qth :: Ptr (TQDragMoveEvent a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance Qignore (QDragMoveEvent a) (()) where
ignore x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_ignore cobj_x0
foreign import ccall "qtc_QDragMoveEvent_ignore" qtc_QDragMoveEvent_ignore :: Ptr (TQDragMoveEvent a) -> IO ()
qignore :: QDragMoveEvent a -> ((QRect t1)) -> IO ()
qignore x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent_ignore1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDragMoveEvent_ignore1" qtc_QDragMoveEvent_ignore1 :: Ptr (TQDragMoveEvent a) -> Ptr (TQRect t1) -> IO ()
instance Qignore (QDragMoveEvent a) ((Rect)) where
ignore x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QDragMoveEvent_ignore1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QDragMoveEvent_ignore1_qth" qtc_QDragMoveEvent_ignore1_qth :: Ptr (TQDragMoveEvent a) -> CInt -> CInt -> CInt -> CInt -> IO ()
qDragMoveEvent_delete :: QDragMoveEvent a -> IO ()
qDragMoveEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_delete cobj_x0
foreign import ccall "qtc_QDragMoveEvent_delete" qtc_QDragMoveEvent_delete :: Ptr (TQDragMoveEvent a) -> IO ()
|
keera-studios/hsQt
|
Qtc/Gui/QDragMoveEvent.hs
|
Haskell
|
bsd-2-clause
| 8,638
|
{-| Converts a configuration state into a Ssconf map.
As TemplateHaskell require that splices be defined in a separate
module, we combine all the TemplateHaskell functionality that HTools
needs in this module (except the one for unittests).
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.WConfd.Ssconf
( SSConf(..)
, emptySSConf
, mkSSConf
) where
import Control.Arrow ((&&&), (***), first)
import qualified Data.ByteString.UTF8 as UTF8
import Data.Foldable (Foldable(..), toList)
import Data.List (partition)
import Data.Maybe (mapMaybe)
import qualified Data.Map as M
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Config
import Ganeti.Constants
import Ganeti.JSON
import Ganeti.Objects
import Ganeti.Ssconf
import Ganeti.Utils
import Ganeti.Types
eqPair :: (String, String) -> String
eqPair (x, y) = x ++ "=" ++ y
mkSSConfHvparams :: Cluster -> [(Hypervisor, [String])]
mkSSConfHvparams cluster = map (id &&& hvparams) [minBound..maxBound]
where
hvparams :: Hypervisor -> [String]
hvparams h = maybe [] hvparamsStrings
$ lookupContainer Nothing h (clusterHvparams cluster)
-- | Convert a collection of hypervisor parameters to strings in the form
-- @key=value@.
hvparamsStrings :: HvParams -> [String]
hvparamsStrings =
map (eqPair . (UTF8.toString *** hvparamShow)) . M.toList . fromContainer
-- | Convert a hypervisor parameter in its JSON representation to a String.
-- Strings, numbers and booleans are just printed (without quotes), booleans
-- printed as @True@/@False@ and other JSON values (should they exist) as
-- their JSON representations.
hvparamShow :: J.JSValue -> String
hvparamShow (J.JSString s) = J.fromJSString s
hvparamShow (J.JSRational _ r) = J.showJSRational r []
hvparamShow (J.JSBool b) = show b
hvparamShow x = J.encode x
mkSSConf :: ConfigData -> SSConf
mkSSConf cdata = SSConf . M.fromList $
[ (SSClusterName, return $ clusterClusterName cluster)
, (SSClusterTags, toList $ tagsOf cluster)
, (SSFileStorageDir, return $ clusterFileStorageDir cluster)
, (SSSharedFileStorageDir, return $ clusterSharedFileStorageDir cluster)
, (SSGlusterStorageDir, return $ clusterGlusterStorageDir cluster)
, (SSMasterCandidates, mapLines nodeName mcs)
, (SSMasterCandidatesIps, mapLines nodePrimaryIp mcs)
, (SSMasterCandidatesCerts, mapLines eqPair . toPairs
. clusterCandidateCerts $ cluster)
, (SSMasterIp, return $ clusterMasterIp cluster)
, (SSMasterNetdev, return $ clusterMasterNetdev cluster)
, (SSMasterNetmask, return . show $ clusterMasterNetmask cluster)
, (SSMasterNode, return
. genericResult (const "NO MASTER") nodeName
. getNode cdata $ clusterMasterNode cluster)
, (SSNodeList, mapLines nodeName nodes)
, (SSNodePrimaryIps, mapLines (spcPair . (nodeName &&& nodePrimaryIp))
nodes )
, (SSNodeSecondaryIps, mapLines (spcPair . (nodeName &&& nodeSecondaryIp))
nodes )
, (SSNodeVmCapable, mapLines (eqPair . (nodeName &&& show . nodeVmCapable))
nodes)
, (SSOfflineNodes, mapLines nodeName offline )
, (SSOnlineNodes, mapLines nodeName online )
, (SSPrimaryIpFamily, return . show . ipFamilyToRaw
. clusterPrimaryIpFamily $ cluster)
, (SSInstanceList, niceSort . mapMaybe instName
. toList . configInstances $ cdata)
, (SSReleaseVersion, return releaseVersion)
, (SSHypervisorList, mapLines hypervisorToRaw
. clusterEnabledHypervisors $ cluster)
, (SSMaintainNodeHealth, return . show . clusterMaintainNodeHealth
$ cluster)
, (SSUidPool, mapLines formatUidRange . clusterUidPool $ cluster)
, (SSNodegroups, mapLines (spcPair . (uuidOf &&& groupName))
nodeGroups)
, (SSNetworks, mapLines (spcPair . (uuidOf
&&& (fromNonEmpty . networkName)))
. configNetworks $ cdata)
, (SSEnabledUserShutdown, return . show . clusterEnabledUserShutdown
$ cluster)
, (SSSshPorts, mapLines (eqPair . (nodeName
&&& getSshPort cdata)) nodes)
] ++
map (first hvparamsSSKey) (mkSSConfHvparams cluster)
where
mapLines :: (Foldable f) => (a -> String) -> f a -> [String]
mapLines f = map f . toList
spcPair (x, y) = x ++ " " ++ y
toPairs = M.assocs . M.mapKeys UTF8.toString . fromContainer
cluster = configCluster cdata
mcs = getMasterOrCandidates cdata
nodes = niceSortKey nodeName . toList $ configNodes cdata
(offline, online) = partition nodeOffline nodes
nodeGroups = niceSortKey groupName . toList $ configNodegroups cdata
-- This will return the empty string only for the situation where the
-- configuration is corrupted and no nodegroup can be found for that node.
getSshPort :: ConfigData -> Node -> String
getSshPort cfg node = maybe "" (show . ndpSshPort)
$ getNodeNdParams cfg node
|
leshchevds/ganeti
|
src/Ganeti/WConfd/Ssconf.hs
|
Haskell
|
bsd-2-clause
| 6,530
|
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TypeSynonymInstances #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-
Forth target code generator for MSP430.
Code generation is done by instantiating the Primitive type class which results
from a cross compilation.
-}
module Language.Forth.Target.MSP430 (bindMSP430, codeGenerateMSP430) where
import Control.Lens
import qualified Data.ByteString.Char8 as C
import Data.Bits
import Data.Int
import Data.Monoid
import Data.ByteString.Lazy (ByteString)
import Data.IntMap (IntMap)
import qualified Data.Set as Set
import Language.Forth.CellVal
import Language.Forth.CrossCompiler.CodeGenerate
import Language.Forth.Dictionary
import Language.Forth.Primitive
import Language.Forth.TargetPrimitive
import Language.Forth.Word
import Translator.Assembler.Generate
import Translator.Assembler.Target.MSP430
import Translator.Expression
import Translator.Symbol
-- | Bind a polymorphic target dictionary to be an MSP430 specific one
bindMSP430 :: (Dictionary (IM Instr430), IntMap (ForthWord (IM Instr430))) ->
(Dictionary (IM Instr430), IntMap (ForthWord (IM Instr430)))
bindMSP430 = id
-- Forth machine registers
tos = RegOp R4 -- top of stack, cached in register
w = RegOp R5
stack = RegOp R6
ip = RegOp R7
sp = RegOp SP
-- Helpers to unwrap Forth machine registers when used in other addressing modes
indirect (RegOp reg) = Indirect reg
indirectInc (RegOp reg) = IndirectInc reg
-- Helpers to wrap instructions in an insRec
add = binary ADD
and_ = binary AND
bis = binary BIS
call = insRec . CALL
clrc = insRec CLRC
dec = unary DEC
decd = unary DECD
inc = unary INC
incd = unary INCD
inv = unary INV
jc = insRec . JC
jnc = insRec . JNC
jz = insRec . JZ
jmp = insRec . JMP
mov = binary MOV
pop = unary POP
push = unary PUSH
rla = unary RLA
rra = unary RRA
rrc = unary RRC
sub = binary SUB
subc = binary SUBC
tst = unary TST
xor_ = binary XOR
binary ctor s op1 op2 = insRec $ ctor s op1 op2
unary ctor s op = insRec $ ctor s op
label = labRec . mkSymbol
-- | Primitive words for MSP430.
instance Primitive (IM Instr430) where
exit = pop W ip
execute = mov W tos ip <>
popStack tos
swap = mov W tos w <>
mov W (indirect stack) tos <>
mov W w (indirect stack)
drop = popStack tos
dup = pushStack tos
over = mov W (indirect stack) w <>
pushStack tos <>
mov W w tos
rto = pushStack tos <>
pop W tos
tor = push W tos <>
popStack tos
rfetch = pushStack tos <>
mov W (indirect sp) tos
fetch = mov W (indirect tos) tos
cfetch = mov B (indirect tos) tos
store = mov W (indirectInc stack) w <>
mov W w (indirect tos) <>
popStack tos
cstore = mov W (indirectInc stack) w <>
mov B w (indirect tos) <>
popStack tos
plus = add W (indirectInc stack) tos
minus = sub W (indirectInc stack) tos <>
inv W tos <>
inc W tos
and = and_ W (indirectInc stack) tos
or = bis W (indirectInc stack) tos
xor = xor_ W (indirectInc stack) tos
twoStar = rla W tos
twoSlash = rra W tos
lshift = multiShift 'l' rla
rshift = multiShift 'r' (\s r -> clrc <> rrc s r)
zerop = sub W (Imm 1) tos <>
subc W tos tos
lt0 = rla W tos <>
subc W tos tos
constant = pushStack tos <>
mov W (indirect w) tos
umstar = mov W (indirect stack) (Absolute (Identifier "MPY")) <>
mov W tos (Absolute (Identifier "OP2")) <>
mov W (Absolute (Identifier "RESLO")) (indirect stack) <>
mov W (Absolute (Identifier "RESHI")) tos
ummod = mempty -- TBD
colonToken tok = insRec $ Directive $ WORD [tok]
instance TargetPrimitive Instr430 where
cellValue e = insRec $ Directive $ LONG [e]
wordToken (TargetToken _ sym) = colonToken (Identifier sym)
literal val = colonToken (Identifier litSymbol) <> colonToken val
labelOffset sym = colonToken $ Identifier sym - locationCounter
docol = call (Imm (Identifier docolSymbol))
doconst e = call (Imm (Identifier doconstSymbol)) <>
colonToken e
dohere dict tt = (does tt, does)
where does (TargetToken _ _) =
call (Imm (Identifier dohereSymbol)) <>
insRec (Directive $ WORD [Identifier ramBaseSymbol + dict^.tdict.hereRAM])
next = jmp (Imm (Identifier nextSymbol))
lit = pushStack tos <>
mov W (indirectInc ip) tos
docolImpl = mempty -- TBD
doconstImpl = mempty -- TBD
hereImpl = mempty -- TBD
nextImpl = mempty -- TBD
resetRStack = mempty -- TBD
resetStack = mempty -- TBD
-- reservedLabels _ = Set.fromList [mkSymbol (p:b) | p <- ['l', 'r'], b <- [shiftloop, shiftskip]]
-- Helper function for implementing LSHIFT and RSHIFT
multiShift t shift =
popStack w <>
tst W tos <>
jz skip <>
label loop <>
shift W w <>
label skip <>
dec W tos <>
jnc loop <>
mov W w tos
where loop = t : shiftloop
skip = t : shiftskip
shiftloop = "shiftloop"
shiftskip = "shiftskip"
-- Pop data stack to given register
popStack r = mov W (indirectInc stack) r
-- Push given register to data stack. Pushing 'tos' effectively makes room
-- for pushing a new value on the stack (by moving it to 'tos').
-- MSP430 cannot predecrement, so used 'decd' to adjust data stack pointer.
pushStack r = decd W stack <>
mov W r (indirect stack)
-- | Generate code for a dictionary for MSP430
-- codeGenerateMSP430 :: (forall t. Dictionary (IM t)) -> ByteString
codeGenerateMSP430 (dict, allwords) =
emitCode $ codeGenerate Directive pad2 (bindMSP430 (dict, allwords))
|
hth313/hthforth
|
src/Language/Forth/Target/MSP430.hs
|
Haskell
|
bsd-2-clause
| 5,836
|
{-# LANGUAGE TypeOperators, DeriveDataTypeable, FlexibleInstances #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Paskell.Expr where
import Data.Generics
import Data.List
import Control.Monad
import Control.Monad.State.Lazy
import Control.Monad.Error
import Data.IORef
data EvalS = ES {
values :: [(String, IORef V)],
decls :: [D]
}
--newtype EvalM a = EvalM { unEvalM :: EvalS -> Either String (IO (a, EvalS)) }
type EvalM = StateT EvalS (ErrorT String IO)
type FailIO = ErrorT String IO
data D = DLet Pat E
| DMkType String [String] [(String, [T])]
| DDecTy [String] T
| DImport String
deriving (Show, Eq, Read)
data V = VReal Double
| VInt Int
-- | VSeed Seed
| VLam ([V]->FailIO V)
| VString String
| VCons String [V]
| VRec [(String,V)]
| VSig E
deriving (Show, Eq, Read)
data T = TLam [T] T
| TApp T T
| TCon String
| TVar String
| TRec [(String,T)]
deriving (Show, Eq, Read, Data, Typeable)
data E = ECon V
| EApp E [E]
| EAssign Pat E
| ELam [Pat] [E]
| EVar String
| ECase E [(Pat, [E])]
| ETy T E
| EIf E [E] [E]
deriving (Show, Eq, Read)
data Pat = PLit V
| PWild
| PVar String
| PCons String [Pat]
-- | PBang Pat
| PTy T Pat
-- | PWithRec
deriving (Show, Eq, Read)
instance Show ([V]->FailIO V) where
show f = "<function>"
instance Read ([V]->FailIO V) where
readsPrec _ s = error $ "read: <function>" ++s
instance Eq ([V]->FailIO V) where
f == g = error "eq: <function>"
flatP e@(PVar nm) = [e]
flatP PWild = []
flatP (PTy _ p) = flatP p
qmap :: (Data a, Typeable b) => (b -> b) -> a -> a
qmap f = everywhere (mkT f)
--qcatMap :: (Data a, Typeable b) => (b -> [b]) -> a -> a
--qcatMap f = everywhere (mkT f)
qquery :: (Data a1, Typeable b) => (b -> [a]) -> a1 -> [a]
qquery qf = everything (++) ([] `mkQ` qf)
flat :: (Data a) => a -> [a]
flat = qquery (:[])
|
glutamate/paskell
|
Paskell/Expr.hs
|
Haskell
|
bsd-3-clause
| 2,115
|
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE FlexibleContexts #-}
module Network.Xmpp.Tls where
import Control.Applicative ((<$>))
import qualified Control.Exception.Lifted as Ex
import Control.Monad
import Control.Monad.Error
import Control.Monad.State.Strict
import "crypto-random" Crypto.Random
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC8
import qualified Data.ByteString.Lazy as BL
import Data.Conduit
import Data.IORef
import Data.Monoid
import Data.XML.Types
import Network.DNS.Resolver (ResolvConf)
import Network.TLS
import Network.Xmpp.Stream
import Network.Xmpp.Types
import System.Log.Logger (debugM, errorM, infoM)
import System.X509
mkBackend :: StreamHandle -> Backend
mkBackend con = Backend { backendSend = \bs -> void (streamSend con bs)
, backendRecv = bufferReceive (streamReceive con)
, backendFlush = streamFlush con
, backendClose = streamClose con
}
where
bufferReceive _ 0 = return BS.empty
bufferReceive recv n = BS.concat `liftM` (go n)
where
go m = do
mbBs <- recv m
bs <- case mbBs of
Left e -> Ex.throwIO e
Right r -> return r
case BS.length bs of
0 -> return []
l -> if l < m
then (bs :) `liftM` go (m - l)
else return [bs]
starttlsE :: Element
starttlsE = Element "{urn:ietf:params:xml:ns:xmpp-tls}starttls" [] []
-- | Checks for TLS support and run starttls procedure if applicable
tls :: Stream -> IO (Either XmppFailure ())
tls con = fmap join -- We can have Left values both from exceptions and the
-- error monad. Join unifies them into one error layer
. wrapExceptions
. flip withStream con
. runErrorT $ do
conf <- gets streamConfiguration
sState <- gets streamConnectionState
case sState of
Plain -> return ()
Closed -> do
liftIO $ errorM "Pontarius.Xmpp.Tls" "The stream is closed."
throwError XmppNoStream
Finished -> do
liftIO $ errorM "Pontarius.Xmpp.Tls" "The stream is finished."
throwError XmppNoStream
Secured -> do
liftIO $ errorM "Pontarius.Xmpp.Tls" "The stream is already secured."
throwError TlsStreamSecured
features <- lift $ gets streamFeatures
case (tlsBehaviour conf, streamFeaturesTls features) of
(RequireTls , Just _ ) -> startTls
(RequireTls , Nothing ) -> throwError TlsNoServerSupport
(PreferTls , Just _ ) -> startTls
(PreferTls , Nothing ) -> skipTls
(PreferPlain , Just True) -> startTls
(PreferPlain , _ ) -> skipTls
(RefuseTls , Just True) -> throwError XmppOtherFailure
(RefuseTls , _ ) -> skipTls
where
skipTls = liftIO $ infoM "Pontarius.Xmpp.Tls" "Skipping TLS negotiation"
startTls = do
liftIO $ infoM "Pontarius.Xmpp.Tls" "Running StartTLS"
params <- gets $ tlsParams . streamConfiguration
ErrorT $ pushElement starttlsE
answer <- lift $ pullElement
case answer of
Left e -> throwError e
Right (Element "{urn:ietf:params:xml:ns:xmpp-tls}proceed" [] []) ->
return ()
Right (Element "{urn:ietf:params:xml:ns:xmpp-tls}failure" _ _) -> do
liftIO $ errorM "Pontarius.Xmpp" "startTls: TLS initiation failed."
throwError XmppOtherFailure
Right r ->
liftIO $ errorM "Pontarius.Xmpp.Tls" $
"Unexpected element: " ++ show r
hand <- gets streamHandle
(_raw, _snk, psh, recv, ctx) <- lift $ tlsinit params (mkBackend hand)
let newHand = StreamHandle { streamSend = catchPush . psh
, streamReceive = wrapExceptions . recv
, streamFlush = contextFlush ctx
, streamClose = bye ctx >> streamClose hand
}
lift $ modify ( \x -> x {streamHandle = newHand})
liftIO $ infoM "Pontarius.Xmpp.Tls" "Stream Secured."
either (lift . Ex.throwIO) return =<< lift restartStream
modify (\s -> s{streamConnectionState = Secured})
return ()
client :: MonadIO m => ClientParams -> Backend -> m Context
client params backend = contextNew backend params
tlsinit :: (MonadIO m, MonadIO m1) =>
ClientParams
-> Backend
-> m ( Source m1 BS.ByteString
, Sink BS.ByteString m1 ()
, BS.ByteString -> IO ()
, Int -> m1 BS.ByteString
, Context
)
tlsinit params backend = do
liftIO $ debugM "Pontarius.Xmpp.Tls" "TLS with debug mode enabled."
-- gen <- liftIO (cprgCreate <$> createEntropyPool :: IO SystemRNG)
sysCStore <- liftIO getSystemCertificateStore
let params' = params{clientShared =
(clientShared params){ sharedCAStore =
sysCStore <> sharedCAStore (clientShared params)}}
con <- client params' backend
handshake con
let src = forever $ do
dt <- liftIO $ recvData con
liftIO $ debugM "Pontarius.Xmpp.Tls" ("In :" ++ BSC8.unpack dt)
yield dt
let snk = do
d <- await
case d of
Nothing -> return ()
Just x -> do
sendData con (BL.fromChunks [x])
snk
readWithBuffer <- liftIO $ mkReadBuffer (recvData con)
return ( src
, snk
-- Note: sendData already sends the data to the debug output
, \s -> sendData con $ BL.fromChunks [s]
, liftIO . readWithBuffer
, con
)
mkReadBuffer :: IO BS.ByteString -> IO (Int -> IO BS.ByteString)
mkReadBuffer recv = do
buffer <- newIORef BS.empty
let read' n = do
nc <- readIORef buffer
bs <- if BS.null nc then recv
else return nc
let (result, rest) = BS.splitAt n bs
writeIORef buffer rest
return result
return read'
-- | Connect to an XMPP server and secure the connection with TLS before
-- starting the XMPP streams
--
-- /NB/ RFC 6120 does not specify this method, but some servers, notably GCS,
-- seem to use it.
connectTls :: ResolvConf -- ^ Resolv conf to use (try 'defaultResolvConf' as a
-- default)
-> ClientParams -- ^ TLS parameters to use when securing the connection
-> String -- ^ Host to use when connecting (will be resolved
-- using SRV records)
-> ErrorT XmppFailure IO StreamHandle
connectTls config params host = do
h <- connectSrv config host >>= \h' -> case h' of
Nothing -> throwError TcpConnectionFailure
Just h'' -> return h''
let hand = handleToStreamHandle h
let params' = params{clientServerIdentification
= case clientServerIdentification params of
("", _) -> (host, "")
csi -> csi
}
(_raw, _snk, psh, recv, ctx) <- tlsinit params' $ mkBackend hand
return StreamHandle{ streamSend = catchPush . psh
, streamReceive = wrapExceptions . recv
, streamFlush = contextFlush ctx
, streamClose = bye ctx >> streamClose hand
}
wrapExceptions :: IO a -> IO (Either XmppFailure a)
wrapExceptions f = Ex.catches (liftM Right $ f)
[ Ex.Handler $ return . Left . XmppIOException
, Ex.Handler $ wrap . XmppTlsError
, Ex.Handler $ wrap . XmppTlsException
, Ex.Handler $ return . Left
]
where
wrap = return . Left . TlsError
|
Philonous/pontarius-xmpp
|
source/Network/Xmpp/Tls.hs
|
Haskell
|
bsd-3-clause
| 8,390
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Dimensions.UK
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Some Dimension]
allDimensions =
[ This Numeral
, This Ordinal
]
|
rfranek/duckling
|
Duckling/Dimensions/UK.hs
|
Haskell
|
bsd-3-clause
| 484
|
{-# LANGUAGE QuasiQuotes #-}
import DBus.QuasiQuoter
import DBus
import Data.Int
import qualified Data.Map as Map
import Data.Maybe
import Data.Word
import Test.QuickCheck
import Text.Printf
main :: IO ()
main = mapM_ (\(s,a) -> printf "%-25s: " s >> a) tests
prop_simple x y = show (x + y) == [dbus| i i -> s |] f x y
where
f :: [Variant] -> [Variant]
f xs = [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_nospaces x y = show (x + y) == [dbus|ii->s|] f x y
where
f :: [Variant] -> [Variant]
f xs = [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_spaces x y = show (x + y) == [dbus| ii-> s |] f x y
where
f :: [Variant] -> [Variant]
f xs = [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_functor x y = Just (show (x + y)) == [dbusF| i i -> s |] f x y
where
f :: [Variant] -> Maybe [Variant]
f xs = Just [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_maps = Map.empty == [dbus| a{su} -> a{on} |] f Map.empty
where
f :: [Variant] -> [Variant]
f _ = [toVariant (Map.empty :: Map.Map ObjectPath Int16)]
prop_tuples x y = show x ++ y == [dbus| (is) -> s |] f (x, y)
where
f :: [Variant] -> [Variant]
f [x] =
let (n, s) = fromJust (fromVariant x) :: (Int32, String)
in [toVariant $ show n ++ s]
prop_retvals x = (x, x) == [dbus| i -> ii |] f x
where
f :: [Variant] -> [Variant]
f [x] = [x, x]
prop_values x = x * 2 == [dbus| -> i |] f
where
f :: [Variant] -> [Variant]
f _ = [toVariant (x * 2)]
prop_unit x = () == [dbus| s -> |] f x
where
f :: [Variant] -> [Variant]
f _ = []
tests = [("simple", quickCheck prop_simple)
,("functor", quickCheck prop_functor)
,("maps", quickCheck prop_maps)
,("tuples", quickCheck prop_tuples)
,("retvals", quickCheck prop_retvals)
,("values", quickCheck prop_values)
,("unit", quickCheck prop_unit)
,("no spaces", quickCheck prop_nospaces)
,("spaces", quickCheck prop_spaces)]
|
pcapriotti/dbus-qq
|
tests/Tests.hs
|
Haskell
|
bsd-3-clause
| 2,113
|
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Fling where
import Control.Arrow (second, (&&&))
import Data.List (sort, groupBy)
import Data.Function (on)
import Data.Tree (Tree(..), Forest, drawForest)
-- Example puzzles
example0 :: Game
example0 = mkGame [[1,4],[1,5],[2,1],[2,5],[5,5],[7,2]]
example1 :: Game
example1 = mkGame [[0,0],[1,2],[2,0],[3,1],[6,3],[7,1]]
example2 :: Game
example2 = mkGame [[1,4],[6,4],[7,4]]
puzzle9_1 :: Game
puzzle9_1 = mkGame [[0,0],[0,2],[1,6],[2,6],[4,1],[5,2],[6,5],[7,3]]
-- Some types
type Point = [Int]
type X = Int
type Y = [Int] -- Dimensions other than X, needs a better name.
newtype Furball = Furball { unFurball :: Point }
deriving Eq
type Row = [X]
type Game = [Furball]
data Move = Move Furball Dir
deriving (Eq, Show)
newtype Dir = Dir { unDir :: Point }
deriving (Eq)
instance Show Furball where
show (Furball pt) = show pt
instance Show Dir where
show (Dir [ 0, -1]) = "North"
show (Dir [ 1, 0]) = "East"
show (Dir [ 0, 1]) = "South"
show (Dir [-1, 0]) = "West"
show (Dir [ 1, 0, 0]) = "Right"
show (Dir [-1, 0, 0]) = "Left"
show (Dir [ 0, 1, 0]) = "Up"
show (Dir [ 0, -1, 0]) = "Down"
show (Dir [ 0, 0, 1]) = "Forwards"
show (Dir [ 0, 0, -1]) = "Backwards"
show (Dir vec) = show vec
-- Transforming stuff
type Transformation = Point -> Point
class Transform a where
transform :: Transformation -> a -> a
instance Transform Furball where
transform xf = Furball . xf . unFurball
instance Transform Dir where
transform xf = Dir . xf . unDir
instance Transform a => Transform [a] where
transform xf = map (transform xf)
instance Transform Move where
transform xf (Move pt dir) = Move (transform xf pt) (transform xf dir)
instance (Transform a, Transform b) => Transform (a, b) where
transform xf (a, b) = (transform xf a, transform xf b)
transformations :: Int -> [(Transformation, Transformation)]
transformations n = zip
[ mx . md | mx <- [id, mirrorX], md <- take n $ iterate ( mirrorDiag .) id]
[ md . mx | mx <- [id, mirrorX], md <- take n $ iterate (revMirrorDiag .) id]
mirrorX :: Point -> Point
mirrorX [] = []
mirrorX (x:dims) = -x:dims
mirrorDiag :: Point -> Point
mirrorDiag [] = []
mirrorDiag (x:dims) = dims ++ [x]
revMirrorDiag :: Point -> Point
revMirrorDiag [] = []
revMirrorDiag dims = last dims : init dims
-- Top-level API
-- | Print a neat forest of winning strategies.
printSolutions :: Game -> IO ()
printSolutions = putStr . drawForest . (fmap . fmap) show . solutions . search
-- | Prune a game tree to only keep the winning paths.
solutions :: Forest (Move, Game) -> Forest (Move, Game)
solutions = concatMap f
where
-- One furball left: we have a winning position.
f n@(Node (_, [_]) []) = [n]
-- Multiple furballs left: recurse.
f (Node mg cs) =
case solutions cs of
[] -> []
cs' -> [Node mg cs']
-- | Build move tree from a starting position.
search :: Game -> Forest (Move, Game)
search = map (\(m, g') -> Node (m, g') (search g')) . moves
-- | Make a game from a list of coordinates.
mkGame :: [Point] -> Game
mkGame = map Furball
-- Generating moves
-- | Noemt gegeven een state alle mogelijke zetten in die state, elk gekoppeld
-- met de bijbehorende nieuwe state.
moves :: Game -> [(Move, Game)]
moves g = concatMap f (transformations n)
where
n = length . unFurball . head $ g
f xf = transform (snd xf)
. (map . second) fromRows
. shifts
. toRows
. transform (fst xf)
$ g
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn f = groupBy ((==) `on` f)
toRows :: Game -> [(Y, Row)]
toRows = map (\row -> (fst (head row), map snd row)) . groupOn fst . sort . map ((tail &&& head) . unFurball)
fromRows :: [(Y, Row)] -> Game
fromRows = concatMap (\(y, row) -> map (Furball . (:y)) row)
-- | Probeert voor alle rijen alle bolletjes naar rechts te rollen.
shifts :: [(Y, Row)] -> [(Move, [(Y, Row)])]
shifts [] = []
shifts ((y, row) : yrows) =
map (\(x, r) -> (mkMove x y, (y, r) : yrows)) (shift row) ++
map (second ((y, row) :)) (shifts yrows)
where
mkMove x dims = Move (Furball $ x : dims) (Dir $ 1 : replicate (length dims) 0)
-- | Probeert voor 1 rij alle balletjes naar rechts te rollen (per balletje shift1).
shift :: Row -> [(X, Row)]
shift [] = []
shift [x,y] | x + 2 == y && y <= 0 = []
shift (x : xs) = maybe id (:) (shift1 (x : xs)) ((fmap . second) (x :) (shift xs))
-- | Probeert voor 1 rij het eerste balletje naar rechts te rollen.
shift1 :: Row -> Maybe (X, Row)
shift1 (x : y : [])
| x + 1 == y = Nothing
| otherwise = Just (x, [pred y])
shift1 (x : y : zs) = Just (x, map pred (y : zs))
shift1 _ = Nothing
|
MedeaMelana/FlingSolver
|
Fling.hs
|
Haskell
|
bsd-3-clause
| 4,844
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Numeric.AERN.Poly.IntPoly.Evaluation
Description : evaluation of interval polynomials
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Evaluation of interval polynomials in general using its instance of 'CanEvaluateOtherType'
and specilised cases for evaluation at a point and on an interval.
-}
module Numeric.AERN.Poly.IntPoly.Evaluation
(
PolyEvalOps(..),
PolyEvalMonoOps(..)
-- ,
-- evalPolyAtPointOut,
-- evalPolyAtPointIn,
-- evalPolyOnIntervalOut,
-- evalPolyOnIntervalIn
)
where
import Numeric.AERN.Poly.IntPoly.Config
import Numeric.AERN.Poly.IntPoly.IntPoly
import Numeric.AERN.Poly.IntPoly.New ()
import Numeric.AERN.Poly.IntPoly.Show ()
import Numeric.AERN.Poly.IntPoly.Differentiation
import Numeric.AERN.RmToRn.Domain
import Numeric.AERN.RmToRn.Evaluation
import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut
import qualified Numeric.AERN.RealArithmetic.NumericOrderRounding as ArithUpDn
--import Numeric.AERN.RealArithmetic.NumericOrderRounding (ConvertEffortIndicator) -- needed for ghc 6.12
import Numeric.AERN.RealArithmetic.ExactOps
import Numeric.AERN.RealArithmetic.Measures
import qualified Numeric.AERN.RefinementOrder as RefOrd
import qualified Numeric.AERN.NumericOrder as NumOrd
import Numeric.AERN.Basics.SizeLimits
import Numeric.AERN.Basics.Consistency
import Numeric.AERN.Basics.Effort
import qualified Data.IntMap as IntMap
--import qualified Data.Map as Map
import Data.List (sortBy)
import Numeric.AERN.Misc.Debug
_ = unsafePrint
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
RefOrd.IntervalLike cf,
HasConsistency cf)
=>
CanEvaluateOtherType (IntPoly var cf)
where
type EvalOps (IntPoly var cf) = PolyEvalOps var cf
evalOtherType ops valsMap p@(IntPoly cfg _) =
case polyEvalMonoOps ops of
Nothing -> evalDirect valsLZ p
_ -> evalPolyMono evalDirect ops valsLZ p
where
evalDirect = evalPolyDirect ops
valsLZ = valsMapToValuesLZ subtrCf cfg valsMap
subtrCf val domLE =
addV val (cfV $ neg domLE)
addV = polyEvalAdd ops
cfV = polyEvalCoeff ops
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
RefOrd.IntervalLike cf,
HasAntiConsistency cf)
=>
CanEvaluateOtherTypeInner (IntPoly var cf)
where
evalOtherTypeInner ops valsMap p@(IntPoly cfg _) =
case polyEvalMonoOps ops of
Nothing -> evalDirect valsLZ p
_ -> evalPolyMono evalDirect ops valsLZ p
where
evalDirect vals p2 =
flipConsistency $
evalPolyDirect ops vals $
flipConsistencyPoly p2
valsLZ = valsMapToValuesLZ subtrCf cfg valsMap
subtrCf val domLE =
addV val (cfV $ neg domLE)
addV = polyEvalAdd ops
cfV = polyEvalCoeff ops
valsMapToValuesLZ ::
(Ord var, Show var, Show t)
=>
(t -> cf -> t) ->
IntPolyCfg var cf ->
(VarBox (IntPoly var cf) t) ->
[t]
valsMapToValuesLZ subtractCf cfg valsMap =
zipWith subtractCf vals domsLE
where
vals = map getValue vars
vars = ipolycfg_vars cfg
domsLE = ipolycfg_domsLE cfg
getValue var =
case lookupVar valsMap var of
Just val -> val
_ -> error $
"aern-poly internal error in Evaluation...valsMapToValuesLZ:"
++ "\n var " ++ show var ++ " not present in valsMap"
++ "\n valsMap = " ++ show valsMap
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
HasAntiConsistency cf,
RefOrd.IntervalLike cf)
=>
CanEvaluate (IntPoly var cf)
where
type (EvaluationEffortIndicator (IntPoly var cf)) =
IntPolyEffort cf
evaluationDefaultEffort (IntPoly cfg _) =
ipolycfg_effort cfg
evalAtPointOutEff eff valsMap p@(IntPoly cfg _)
| valuesAreExact valsLZ =
evalPolyAtPointOut effCf maxSplitSize valsLZ p
| otherwise =
evalPolyOnIntervalOut effCf maxSplitSize valsLZ p
where
valsLZ = valsMapToValuesLZ (<->) cfg valsMap
(<->) = ArithInOut.subtrOutEff effAdd
effAdd = ArithInOut.fldEffortAdd sampleCf $ ArithInOut.rrEffortField sampleCf effCf
maxSplitSize = ipolyeff_evalMaxSplitSize eff
effCf = ipolyeff_cfRoundedRealEffort eff
sampleCf = ipolycfg_sample_cf cfg
evalAtPointInEff eff valsMap p@(IntPoly cfg _)
| valuesAreExact valsLZ =
evalPolyAtPointIn effCf maxSplitSize valsLZ p
| otherwise =
evalPolyOnIntervalIn effCf maxSplitSize valsLZ p
where
valsLZ = valsMapToValuesLZ (>-<) cfg valsMap
(>-<) = ArithInOut.subtrInEff effAdd
effAdd = ArithInOut.fldEffortAdd sampleCf $ ArithInOut.rrEffortField sampleCf effCf
maxSplitSize = ipolyeff_evalMaxSplitSize eff
effCf = ipolyeff_cfRoundedRealEffort eff
sampleCf = ipolycfg_sample_cf cfg
valuesAreExact ::
HasConsistency t
=>
[t] -> Bool
valuesAreExact values =
and $ map isCertainlyExact values
where
isCertainlyExact val =
isExact val == Just True
--instance
-- (Ord var, Show var,
-- ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
-- HasConsistency cf,
-- Show cf, Show (SizeLimits cf))
-- =>
-- HasEvalOps (IntPoly var cf) cf
-- where
-- type EvalOpsEffortIndicator (IntPoly var cf) cf =
-- IntPolyEffort cf
-- evalOpsDefaultEffort _p@(IntPoly cfg _) _sampleCf =
-- ipolycfg_effort cfg
---- (ArithInOut.roundedRealDefaultEffort sampleCf, Int1To10 depth)
---- where
---- depth = 1 + (maxDeg `div` 2)
---- maxDeg = ipolycfg_maxdeg cfg
--
-- evalOpsEff eff _sampleP sampleCf =
-- coeffPolyEvalOpsOut effCf maxSplitSize sampleCf
-- where
-- maxSplitSize = ipolyeff_evalMaxSplitSize eff
-- effCf = ipolyeff_cfRoundedRealEffort eff
data PolyEvalOps var cf val =
PolyEvalOps
{
polyEvalZero :: val,
polyEvalAdd :: (val -> val -> val),
polyEvalMult :: (val -> val -> val),
polyEvalPow :: (val -> Int -> val), {-^ non-negative integer power -}
polyEvalCoeff :: (cf -> val), {-^ coeff conversion -}
polyEvalMaybePoly :: (IntPolyTerms var cf -> Maybe val), {-^ optional direct poly conversion -}
polyEvalSplitMaxSize :: Int,
polyEvalMonoOps :: Maybe (PolyEvalMonoOps var cf val)
}
data PolyEvalMonoOps var cf val =
PolyEvalMonoOps
{
polyEvalMonoOuter :: PolyEvalOps var cf val,
polyEvalMonoLeq :: (val -> val -> Maybe Bool),
polyEvalMonoGetEndpoints :: val -> (val, val),
polyEvalMonoFromEndpoints :: (val, val) -> val,
polyEvalMonoIsExact :: val -> Bool,
polyEvalMonoSplit :: val -> (val, val),
polyEvalMonoMerge :: (val, val) -> val,
polyEvalMonoMin :: val -> val -> val,
polyEvalMonoMax :: val -> val -> val,
polyEvalMonoGetWidthAsDouble :: val -> Double,
polyEvalMonoCfEffortIndicator :: ArithInOut.RoundedRealEffortIndicator cf
}
coeffPolyEvalOpsOut ::
(RefOrd.IntervalLike cf, ArithInOut.RoundedReal cf, HasConsistency cf)
=>
(ArithInOut.RoundedRealEffortIndicator cf) ->
Int ->
cf ->
PolyEvalOps var cf cf
coeffPolyEvalOpsOut eff depth sample =
result
where
result =
PolyEvalOps (zero sample) (<+>) (<*>) (<^>) id (const Nothing) depth $
Just $ PolyEvalMonoOps
result -- outer rounded ops = itself
(<=?)
RefOrd.getEndpointsOut
RefOrd.fromEndpointsOut
isDefinitelyExact
split
(uncurry (</\>))
(NumOrd.minOutEff effMinmax)
(NumOrd.maxOutEff effMinmax)
getWidthAsDouble
eff
isDefinitelyExact a =
isExact a == Just True
split val = (val1, val2)
where
val1 = RefOrd.fromEndpointsOut (valL, valM)
val2 = RefOrd.fromEndpointsOut (valM, valR)
(valL, valR) = RefOrd.getEndpointsOut val
valM = (valL <+> valR) </>| (2 :: Int)
getWidthAsDouble val = wD
where
Just wD = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort val (0::Double)) 0 w
w = valR <-> valL
(valL, valR) = RefOrd.getEndpointsOut val
(<=?) = NumOrd.pLeqEff effComp
(</\>) = RefOrd.meetOutEff effJoin
(<+>) = ArithInOut.addOutEff effAdd
(<->) = ArithInOut.subtrOutEff effAdd
(<*>) = ArithInOut.multOutEff effMult
(<^>) = ArithInOut.powerToNonnegIntOutEff effPwr
(</>|) = ArithInOut.mixedDivOutEff effDivInt
effMult = ArithInOut.fldEffortMult sample $ ArithInOut.rrEffortField sample eff
effPwr = ArithInOut.fldEffortPow sample $ ArithInOut.rrEffortField sample eff
effAdd = ArithInOut.fldEffortAdd sample $ ArithInOut.rrEffortField sample eff
effDivInt = ArithInOut.mxfldEffortDiv sample (1::Int) $ ArithInOut.rrEffortIntMixedField sample eff
effComp = ArithInOut.rrEffortNumComp sample eff
effJoin = ArithInOut.rrEffortJoinMeet sample eff
effMinmax = ArithInOut.rrEffortMinmaxInOut sample eff
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
HasAntiConsistency cf,
RefOrd.IntervalLike cf)
=>
(HasDistance (IntPoly var cf))
where
type Distance (IntPoly var cf) = cf
type DistanceEffortIndicator (IntPoly var cf) =
IntPolyEffort cf
distanceDefaultEffort p =
evaluationDefaultEffort p
distanceBetweenEff eff p1 p2 =
ArithInOut.absOutEff effAbs $ evalAtPointOutEff eff dombox diff
where
dombox = getDomainBox diff
diff = polyJoinWith (zero sampleCf) (uncurry $ ArithInOut.subtrOutEff effAdd) (p1, p2)
sampleCf = getSampleDomValue p1
effAdd =
ArithInOut.fldEffortAdd sampleCf $
ArithInOut.rrEffortField sampleCf effCf
effAbs =
ArithInOut.rrEffortAbs sampleCf effCf
effCf = ipolyeff_cfRoundedRealEffort eff
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
HasAntiConsistency cf,
RefOrd.IntervalLike cf)
=>
(HasImprecision (IntPoly var cf))
where
type Imprecision (IntPoly var cf) = cf
type ImprecisionEffortIndicator (IntPoly var cf) =
IntPolyEffort cf
imprecisionDefaultEffort p =
evaluationDefaultEffort p
imprecisionOfEff eff p = distanceBetweenEff eff p p
--instance
-- (Ord var, Show var,
-- ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
-- HasAntiConsistency cf,
-- Show cf)
-- =>
-- ArithUpDn.Convertible (IntPoly var cf) cf
-- where
-- type ConvertEffortIndicator (IntPoly var cf) cf =
-- (EvaluationEffortIndicator (IntPoly var cf),
-- RefOrd.GetEndpointsEffortIndicator cf)
-- convertDefaultEffort sampleP sampleCf =
-- (evaluationDefaultEffort sampleP,
-- RefOrd.getEndpointsDefaultEffort sampleCf)
-- convertUpEff (effEval, effGetEndpts) sampleCf p =
-- Just $ snd $ RefOrd.getEndpointsOutEff effGetEndpts range
-- where
-- range = evalOtherType (evalOpsEff effEval sampleP sampleCf) varDoms p
-- varDoms = getDomainBox p
-- sampleP = p
-- convertDnEff (effEval, effGetEndpts) sampleCf p =
-- Just $ fst $ RefOrd.getEndpointsOutEff effGetEndpts range
-- where
-- range = evalOtherType (evalOpsEff effEval sampleP sampleCf) varDoms p
-- varDoms = getDomainBox p
-- sampleP = p
evalPolyAtPointOut, evalPolyAtPointIn ::
(Ord var, Show var,
ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
HasAntiConsistency cf,
Show cf)
=>
(ArithInOut.RoundedRealEffortIndicator cf) ->
Int ->
[cf] {- values for each variable respectively -} ->
IntPoly var cf -> cf
evalPolyAtPointOut eff depth values p@(IntPoly cfg _)
=
evalPolyDirect (coeffPolyEvalOpsOut eff depth sample) values p
where
sample = ipolycfg_sample_cf cfg
evalPolyAtPointIn eff depth values p@(IntPoly cfg _)
=
flipConsistency $
evalPolyDirect (coeffPolyEvalOpsOut eff depth sample) values $
flipConsistencyPoly p
where
sample = ipolycfg_sample_cf cfg
evalPolyOnIntervalOut, evalPolyOnIntervalIn ::
(Ord var, Show var,
ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
HasAntiConsistency cf,
Show cf, Show (SizeLimits cf))
=>
ArithInOut.RoundedRealEffortIndicator cf
->
Int
->
[cf] {- values for each variable respectively -}
->
IntPoly var cf -> cf
evalPolyOnIntervalOut eff maxSplitDepth values p@(IntPoly cfg _)
=
evalPolyMono evalOut ops values p
where
evalOut = evalPolyDirect ops
ops = coeffPolyEvalOpsOut eff maxSplitDepth sample
sample = ipolycfg_sample_cf cfg
evalPolyOnIntervalIn eff maxSplitDepth values p@(IntPoly cfg _)
=
evalPolyMono evalIn ops values p
where
evalIn values2 p2 =
flipConsistency $
evalPolyDirect ops values2 $
flipConsistencyPoly p2
ops = coeffPolyEvalOpsOut eff maxSplitDepth sample
sample = ipolycfg_sample_cf cfg
evalPolyDirect ::
(Ord var, Show var, Show cf, Show val, Neg cf) =>
(PolyEvalOps var cf val) ->
[val] ->
IntPoly var cf -> val
evalPolyDirect opsV valuesLZ _p@(IntPoly _cfg terms)
=
-- unsafePrint
-- (
-- "evalPolyDirect: "
-- ++ "\n values = " ++ show values
-- ++ "\n p = " ++ show p
-- ) $
ev valuesLZ terms
where
zV = polyEvalZero opsV
addV = polyEvalAdd opsV
multV = polyEvalMult opsV
powV = polyEvalPow opsV
cfV = polyEvalCoeff opsV
polyV = polyEvalMaybePoly opsV
ev [] (IntPolyC cf) = cfV cf
ev (varValueLZ : restValues) (IntPolyV _ powers)
| IntMap.null powers = zV
| lowestExponent == 0 =
resultMaybeWithoutConstantTerm
| otherwise =
(varValueLZ `powV` lowestExponent) `multV` resultMaybeWithoutConstantTerm
where
(lowestExponent, resultMaybeWithoutConstantTerm)
= IntMap.foldWithKey addTerm (highestExponent, zV) powers
(highestExponent, _) = IntMap.findMax powers
addTerm exponent_2 poly (prevExponent, prevVal) = (exponent_2, newVal)
where
newVal = -- Horner scheme:
polyValue
`addV`
(prevVal `multV` (varValueLZ `powV` (prevExponent - exponent_2)))
polyValue =
case polyV poly of
Just value -> value
Nothing -> ev restValues poly
ev varVals terms_2 =
error $
"evalPolyDirect: illegal case:"
++ "\n varVals = " ++ show varVals
++ "\n terms = " ++ show terms_2
-- TODO: make the following function generic for any function representation with nominal derivatives
evalPolyMono ::
(Ord var, Show var,
ArithInOut.RoundedReal cf,
RefOrd.IntervalLike cf,
HasConsistency cf,
Show cf, Show (SizeLimits cf), Show val)
=>
([val] -> IntPoly var cf -> val) -- ^ direct evaluator (typically, @evalPolyDirect opsV@)
->
(PolyEvalOps var cf val)
->
[val] {-^ value for each variable -}
->
IntPoly var cf
->
val
evalPolyMono evalDirect opsV valuesG pOrig@(IntPoly cfg _)
| noMonoOps = direct
-- | noMonotoneVar = useMonotonicityAndSplit
| otherwise =
-- (case segCount > 1 of
-- False -> id
-- True ->
-- unsafePrint
-- (
-- "evalPolyMono:"
-- ++ "\n split into " ++ show segCount ++ " segment(s), "
-- ++ show (emsCountIgnoreNodes resultEMS) ++ " pruned"
-- ++ " (maxSplitSize = " ++ show maxSplitSize ++ ")"
-- ++ "\n polyTermSize p = " ++ show (polyTermSize p)
-- ))
-- unsafePrint
-- (
-- "evalPolyMono: "
-- ++ "\n pOrig = " ++ show pOrig
-- ++ "\n maybeResultL = " ++ show maybeResultL
-- ++ "\n maybeResultR = " ++ show maybeResultR
-- ++ "\n direct = " ++ show direct
-- ) $
case (maybeResultL, maybeResultR) of
(Just resultL, Just resultR) ->
mergeV (resultL, resultR)
_ -> error $
"evalPolyMono: maybeResultL = " ++ show maybeResultL
++ "; maybeResultR = " ++ show maybeResultR
where
vars = ipolycfg_vars cfg
direct = evalDirect valuesG pOrig
(pL, pR) = RefOrd.getEndpointsOut pOrig
maybeResultL = maybeResultForP pL
maybeResultR = maybeResultForP pR
maybeResultForP p =
emsCollectResultsSoFar (curry mergeV) $
useMonotonicityAndSplitting (direct, direct) $
EMSTODO (direct, [direct]) $ zip valuesG $ repeat (False, False)
where
useMonotonicityAndSplitting (minSoFar, maxSoFar) emsTree =
case evalNextLevel 0 emsTree of
(emsTreeNew, Nothing, _) -> emsTreeNew
(emsTreeNew, _, False) -> emsTreeNew
(emsTreeNew, _, _) ->
case emsCollectMinMax minV maxV emsTreeNew of
Just (minSoFarNew, maxSoFarNew) ->
-- unsafePrint
-- (
-- "evalPolyMono: useMonotonicityAndSplitting: processing next layer:"
-- ++ "\n size of emsTreeNew = " ++ show (emsCountNodes emsTreeNew)
-- ++ "\n minSoFarNew = " ++ show minSoFarNew
-- ++ "\n maxSoFarNew = " ++ show maxSoFarNew
-- ) $
useMonotonicityAndSplitting (minSoFarNew, maxSoFarNew) emsTreeNew
_ ->
error $
"evalPolyMono: useMonotonicityAndSplitting: no result in tree!"
++ "\n p = " ++ show p
++ "\n valuesG = " ++ show valuesG
++ "\n minSoFar = " ++ show minSoFar
++ "\n maxSoFar = " ++ show maxSoFar
++ "\n emsTree = " ++ show emsTree
++ "\n emsTreeNew = " ++ show emsTreeNew
where
evalNextLevel nodeCountSoFar (EMSSplit left right) =
(EMSSplit leftNew rightNew, maybeNodeCountR, updatedL || updatedR)
where
(leftNew, maybeNodeCountL, updatedL) = evalNextLevel nodeCountSoFar left
(rightNew, maybeNodeCountR, updatedR) =
case maybeNodeCountL of
Just nodeCountL ->
evalNextLevel nodeCountL right
Nothing ->
(right, Nothing, False)
evalNextLevel nodeCountSoFar t@(EMSDone _) = (t, Just (nodeCountSoFar + 1), False)
evalNextLevel nodeCountSoFar t@(EMSIgnore _) = (t, Just (nodeCountSoFar + 1), False)
evalNextLevel nodeCountSoFar (EMSTODO nosplitResultSamples valuesAndDetectedMonotonicity)
| insideOthers =
(EMSIgnore nosplitResultSamples, Just (nodeCountSoFar + 1), False)
| nodeCountSoFar + 1 >= maxSplitSize = -- node count limit reached
(EMSDone nosplitResultSamples, Nothing, False)
| splitHelps =
(EMSSplit (EMSTODO (leftRes, leftSamples) leftValsEtc) (EMSTODO (rightRes, rightSamples) rightValsEtc),
Just $ nodeCountSoFar + 2, True)
| otherwise = -- ie splitting further does not help:
(EMSDone nosplitResultSamples, Just (nodeCountSoFar + 1), False)
where
insideOthers =
(minSoFar `leqV` nosplitResult == Just True) &&
(nosplitResult `leqV` maxSoFar == Just True)
nosplitResultWidth = getWidthDblV nosplitResult
nosplitResult = fst nosplitResultSamples
leftSamples = getSamplesFor leftValsEtc
rightSamples = getSamplesFor rightValsEtc
getSamplesFor valuesAndDetectedMonotonicity2 =
-- unsafePrint
-- (
-- "getSamplesFor:"
-- ++ "\n valuesAndDetectedMonotonicity2 = " ++ show valuesAndDetectedMonotonicity2
-- ++ "\n samplePoints2 = \n"
-- ++ unlines (map show samplePoints2)
-- ) $
map (fst . useMonotonicity) samplePoints
where
samplePoints = take maxSplitSize samplePoints2
samplePoints2
| someMonotonicityInfo =
interleaveLists
(getPoints True [] valuesAndDetectedMonotonicity2)
(getPoints False [] valuesAndDetectedMonotonicity2)
| otherwise =
getPoints True [] valuesAndDetectedMonotonicity2
someMonotonicityInfo =
or $ map (\(_,(isMono, _)) -> isMono) valuesAndDetectedMonotonicity2
getPoints _shouldAimDown prevValues [] = [reverse prevValues]
getPoints shouldAimDown prevValues (vdm@(value, dm@(detectedMono, isIncreasing)) : rest)
| isExactV value =
getPoints shouldAimDown (vdm : prevValues) rest
| detectedMono =
getPoints shouldAimDown ((valueEndpt, (True, True)) : prevValues) rest
| otherwise =
interleaveLists
(getPoints shouldAimDown ((valueLE, (True, True)) : prevValues) rest)
(getPoints shouldAimDown ((valueRE, (True, True)) : prevValues) rest)
where
valueEndpt
| isIncreasing `xor` shouldAimDown = valueLE
| otherwise = valueRE
(valueLE, valueRE) = getEndPtsV value
splitHelps
| null possibleSplits = False
| otherwise = bestSplitWidth < nosplitResultWidth
((bestSplitWidth, ((leftRes, leftValsEtc), (rightRes, rightValsEtc))))
= bestSplitInfo
(bestSplitInfo : _) =
sortBy (\ (a,_) (b,_) -> compare a b) splitsInfo
splitsInfo =
map getWidth splitResults
where
getWidth result@((leftVal, _),(rightVal, _)) = (width :: Double, result)
where
width = getWidthDblV $ mergeV (leftVal, rightVal)
splitResults =
map computeSplitResult possibleSplits
possibleSplits =
getSplits [] [] valuesAndDetectedMonotonicity
where
getSplits prevSplits _prevValues [] = prevSplits
getSplits prevSplits prevValues (vd@(value, dmAndIncr@(detectedMono, _)) : rest)
| detectedMono =
getSplits prevSplits (vd : prevValues) rest -- do not split value for which p is monotone
| otherwise =
getSplits (newSplit : prevSplits) (vd : prevValues) rest
where
newSplit =
(
prevValuesRev ++ [(valueL, dmAndIncr)] ++ rest
,
prevValuesRev ++ [(valueR, dmAndIncr)] ++ rest
)
prevValuesRev = reverse prevValues
(valueL, valueR) = splitV value
computeSplitResult (valuesAndDM_L, valuesAndDM_R) =
(useMonotonicity valuesAndDM_L, useMonotonicity valuesAndDM_R)
useMonotonicity valuesAndPrevDetectedMonotonicity =
(fromEndPtsV (left, right), valuesAndCurrentDetectedMonotonicity)
where
values = map fst valuesAndPrevDetectedMonotonicity
left = evalDirect valuesL p
right = evalDirect valuesR p
(_noMonotoneVar, valuesL, valuesR, valuesAndCurrentDetectedMonotonicity) =
let ?mixedMultInOutEffort = effMult in
detectMono True [] [] [] $
reverse $ -- undo reverse due to the accummulators
zip vars $ valuesAndPrevDetectedMonotonicity
detectMono noMonotoneVarPrev valuesLPrev valuesRPrev
valuesAndCurrentDetectedMonotonicityPrev []
= (noMonotoneVarPrev, valuesLPrev, valuesRPrev,
valuesAndCurrentDetectedMonotonicityPrev)
detectMono noMonotoneVarPrev valuesLPrev valuesRPrev
valuesAndCurrentDetectedMonotonicityPrev ((var, (val, dmAndIncr@(prevDM, isIncreasing))) : rest)
=
-- unsafePrint
-- (
-- "evalPolyMono: detectMono: deriv = " ++ show deriv
-- ) $
detectMono noMonotoneVarNew (valLNew : valuesLPrev) (valRNew : valuesRPrev)
((val, newDMAndIncr) : valuesAndCurrentDetectedMonotonicityPrev) rest
where
noMonotoneVarNew = noMonotoneVarPrev && varNotMono
(valLNew, valRNew, newDMAndIncr)
| prevDM && isIncreasing = (valL, valR, dmAndIncr)
| prevDM = (valR, valL, dmAndIncr)
| varNotMono = (val, val, dmAndIncr) -- not monotone, we have to be safe
| varNonDecr = (valL, valR, (True, True)) -- non-decreasing on the whole domain - can use endpoints
| otherwise = (valR, valL, (True, False)) -- non-increasing on the whole domain - can use swapped endpoints
(varNonDecr, varNotMono) =
case (valIsExact, zV `leqV` deriv, deriv `leqV` zV) of
(True, _, _) -> (undefined, True) -- when a variable has a thin domain, do not bother separating endpoints
(_, Just True, _) -> (True, False)
(_, _, Just True) -> (False, False)
_ -> (undefined, True)
deriv =
evalPolyDirect opsVOut values $ -- this evaluation must be outer-rounded!
diffPolyOut effCf var p -- range of (d p)/(d var)
(valL, valR) = getEndPtsV val
valIsExact = isExactV val
zV = polyEvalZero opsV
maxSplitSize = polyEvalSplitMaxSize opsV
(noMonoOps, monoOpsV) =
case polyEvalMonoOps opsV of
Nothing -> (True, error "evalPolyMono: internal error: monoOpsV used when not present")
Just monoOpsV_2 -> (False, monoOpsV_2)
leqV = polyEvalMonoLeq monoOpsV
fromEndPtsV = polyEvalMonoFromEndpoints monoOpsV
getEndPtsV = polyEvalMonoGetEndpoints monoOpsV
isExactV = polyEvalMonoIsExact monoOpsV
splitV = polyEvalMonoSplit monoOpsV
mergeV = polyEvalMonoMerge monoOpsV
minV = polyEvalMonoMin monoOpsV
maxV = polyEvalMonoMax monoOpsV
getWidthDblV = polyEvalMonoGetWidthAsDouble monoOpsV
effCf = polyEvalMonoCfEffortIndicator monoOpsV
opsVOut = polyEvalMonoOuter monoOpsV
effMult = ArithInOut.mxfldEffortMult sampleCf (1::Int) $ ArithInOut.rrEffortIntMixedField sampleCf effCf
sampleCf = ipolycfg_sample_cf cfg
-- useMonotonicityAndSplitWith remainingDepth valuesAndPrevDetectedMonotonicity
-- | remainingDepth > 0 && splitHelps =
---- unsafePrint
---- (
---- "evalPolyMono: useMonotonicityAndSplitWith: SPLIT"
---- ++ "\n remainingDepth = " ++ show remainingDepth
---- ++ "\n valuesAndPrevDetectedMonotonicity = " ++ show valuesAndPrevDetectedMonotonicity
---- ++ "\n valuesAndCurrentDetectedMonotonicity = " ++ show valuesAndCurrentDetectedMonotonicity
---- ++ "\n nosplitResult = " ++ show nosplitResult
---- ++ "\n nosplitResultWidth = " ++ show nosplitResultWidth
---- ++ "\n bestSplit = " ++ show bestSplit
---- ++ "\n bestSplitResult = " ++ show _bestSplitResult
---- ++ "\n bestSplitWidth = " ++ show bestSplitWidth
---- ) $
-- computeSplitResultContinueSplitting bestSplit
-- | otherwise =
---- unsafePrint
---- (
---- "evalPolyMono: useMonotonicityAndSplitWith: DONE"
---- ++ "\n remainingDepth = " ++ show remainingDepth
---- ++ "\n valuesAndPrevDetectedMonotonicity = " ++ show valuesAndPrevDetectedMonotonicity
---- ++ "\n valuesAndCurrentDetectedMonotonicity = " ++ show valuesAndCurrentDetectedMonotonicity
---- ++ "\n nosplitResult = " ++ show nosplitResult
---- ++ "\n nosplitResultWidth = " ++ show nosplitResultWidth
---- ) $
-- (nosplitResult, 1 :: Int)
-- where
-- nosplitResult = fromEndPtsV nosplitResultLR
-- (nosplitResultLR, valuesAndCurrentDetectedMonotonicity) =
-- useMonotonicity valuesAndPrevDetectedMonotonicity
-- nosplitResultWidth = getWidthDblV nosplitResult
--
-- splitHelps
-- | null possibleSplits = False
-- | otherwise = bestSplitWidth < nosplitResultWidth
-- (((bestSplitWidth, _bestSplitResult), bestSplit) : _) =
-- sortBy (\ ((a,_),_) ((b,_),_) -> compare a b) $ zip splitWidths possibleSplits
-- splitWidths =
-- map getWidth splitResults
-- where
-- getWidth result = (width :: Double, result)
-- where
-- width = getWidthDblV result
-- splitResults =
-- map computeSplitResult possibleSplits
-- possibleSplits =
-- getSplits [] [] valuesAndCurrentDetectedMonotonicity
-- where
-- getSplits prevSplits _prevValues [] = prevSplits
-- getSplits prevSplits prevValues (vd@(value, dmAndIncr@(detectedMono, _)) : rest)
-- | detectedMono =
-- getSplits prevSplits (vd : prevValues) rest -- do not split value for which p is monotone
-- | otherwise =
-- getSplits (newSplit : prevSplits) (vd : prevValues) rest
-- where
-- newSplit =
-- (
-- prevValuesRev ++ [(valueL, dmAndIncr)] ++ rest
-- ,
-- prevValuesRev ++ [(valueR, dmAndIncr)] ++ rest
-- )
-- prevValuesRev = reverse prevValues
-- (valueL, valueR) = splitV value
--
-- computeSplitResult (valuesAndDM_L, valuesAndDM_R) =
-- mergeV (resultL, resultR)
-- where
-- resultL = fromEndPtsV $ fst $ useMonotonicity valuesAndDM_L
-- resultR = fromEndPtsV $ fst $ useMonotonicity valuesAndDM_R
--
-- computeSplitResultContinueSplitting (valuesAndDM_L, valuesAndDM_R) =
-- (mergeV (resultL, resultR), splitCountL + splitCountR)
-- where
-- (resultL, splitCountL) = useMonotonicityAndSplitWith (remainingDepth - 1) valuesAndDM_L
-- (resultR, splitCountR) = useMonotonicityAndSplitWith (remainingDepth - 1) valuesAndDM_R
interleaveLists :: [a] -> [a] -> [a]
interleaveLists (h1 : t1) (h2 : t2) = h1 : h2 : (interleaveLists t1 t2)
interleaveLists [] list2 = list2
interleaveLists list1 [] = list1
xor False b = b
xor True b = not b
data EvalMonoSpliting task value =
EMSSplit (EvalMonoSpliting task value) (EvalMonoSpliting task value)
| EMSTODO (value, [value]) task
| EMSDone (value, [value])
| EMSIgnore (value, [value])
deriving Show
emsCountNodes ::
EvalMonoSpliting task value -> Int
emsCountNodes (EMSSplit left right) =
(emsCountNodes left) + (emsCountNodes right)
emsCountNodes _ = 1
emsCountIgnoreNodes ::
EvalMonoSpliting task value -> Int
emsCountIgnoreNodes (EMSSplit left right) =
(emsCountIgnoreNodes left) + (emsCountIgnoreNodes right)
emsCountIgnoreNodes (EMSIgnore _) = 1
emsCountIgnoreNodes _ = 0
emsCollectResultsSoFar ::
(value -> value -> value) ->
EvalMonoSpliting task value ->
Maybe value
emsCollectResultsSoFar mergeV emsTree =
aux emsTree
where
aux (EMSIgnore (val, _)) = Just val
aux (EMSDone (val, _)) = Just val
aux (EMSTODO (val, _) _) = Just val
aux (EMSSplit left right) =
do
leftVal <- aux left
rightVal <- aux right
return $ leftVal `mergeV` rightVal
emsCollectMinMax ::
(value -> value -> value) ->
(value -> value -> value) ->
EvalMonoSpliting task value ->
Maybe (value, value)
emsCollectMinMax minV maxV emsTree =
aux emsTree
where
aux (EMSIgnore (_, samples)) = minmaxFromSamples samples
aux (EMSDone (_, samples)) = minmaxFromSamples samples
aux (EMSTODO (_, samples) _) = minmaxFromSamples samples
aux (EMSSplit left right) =
do
(leftMin, leftMax) <- aux left
(rightMin, rightMax) <- aux right
return $
(leftMin `minV` rightMin, leftMax `maxV` rightMax)
minmaxFromSamples [] = Nothing
minmaxFromSamples samples =
Just (foldl1 minV samples, foldl1 maxV samples)
--partiallyEvalPolyAtPointOut ::
-- (Ord var, ArithInOut.RoundedReal cf)
-- =>
-- ArithInOut.RoundedRealEffortIndicator cf ->
-- Map.Map var cf ->
-- IntPoly var cf ->
-- IntPoly var cf
--partiallyEvalPolyAtPointOut effCf valsMap _p@(IntPoly cfg terms) =
-- {- currently there is massive dependency effect here,
-- move this to Composition and deal with it as a special case
-- of composition
-- -}
-- IntPoly cfgVarsRemoved $ pev domsLE terms
-- where
-- cfgVarsRemoved =
-- cfg
-- {
-- ipolycfg_vars = newVars,
-- ipolycfg_domsLE = newDomsLE,
-- ipolycfg_domsLZ = newDomsLZ
-- }
-- where
-- (newVars, newDomsLE, newDomsLZ)
-- = unzip3 $ filter notSubstituted $ zip3 vars domsLE domsLZ
-- where
-- vars = ipolycfg_vars cfg
-- domsLZ = ipolycfg_domsLZ cfg
-- notSubstituted (var, _, _) =
-- var `Map.notMember` valsMap
-- domsLE = ipolycfg_domsLE cfg
-- pev _ t@(IntPolyC _) = t
-- pev (domLE : restDomsLE) (IntPolyV var powers) =
-- case Map.lookup var valsMap of
-- Just value ->
-- let ?addInOutEffort = effAdd in
-- -- evaluate evaluatedPowers using the Horner scheme:
-- foldl (addAndScale (value <-> domLE) highestExponent) heTerms lowerPowers
-- _ ->
-- IntPolyV var evaluatedPowers
-- where
-- evaluatedPowers =
-- IntMap.map (pev restDomsLE) powers
-- ((highestExponent, heTerms) : lowerPowers) =
-- reverse $ IntMap.toAscList evaluatedPowers
-- addAndScale value prevExponent termsSoFar (currExponent, currTerms) =
-- let ?multInOutEffort = effMult in
-- addTermsAux currTerms $ termsMapCoeffs (<*> valuePower) termsSoFar
-- where
-- valuePower =
-- let ?intPowerInOutEffort = effPow in
-- value <^> (prevExponent - currExponent)
-- addTermsAux (IntPolyV v powers1) (IntPolyV _ powers2) =
-- IntPolyV v $ IntMap.unionWith addTermsAux powers1 powers2
-- addTermsAux (IntPolyC val1) (IntPolyC val2) =
-- let ?addInOutEffort = effAdd in
-- IntPolyC $ val1 <+> val2
-- effAdd = ArithInOut.fldEffortAdd sampleCf $ ArithInOut.rrEffortField sampleCf effCf
-- effMult = ArithInOut.fldEffortMult sampleCf $ ArithInOut.rrEffortField sampleCf effCf
-- effPow = ArithInOut.fldEffortPow sampleCf $ ArithInOut.rrEffortField sampleCf effCf
-- sampleCf = domLE
--
|
michalkonecny/aern
|
aern-poly/src/Numeric/AERN/Poly/IntPoly/Evaluation.hs
|
Haskell
|
bsd-3-clause
| 37,815
|
-- Author: Lee Ehudin
-- Contains the entry point for the text editor
module Controller.Runner (hasked) where
import Controller.EventHandler (handleEvents)
import Model.Buffer (newBuffer, newBufferFromFile, writeBufferToFile, getScreen,
getCursorPos)
import View.Curses (updateText, getScreenSize, withCurses)
import Data.Maybe (listToMaybe)
import System.Environment (getArgs)
-- Entry point for the hasked program. Sets up an initial buffer by possibly
-- reading from a file, refreshes the screen once, then goes into the event
-- handler loop.
hasked :: IO ()
hasked = withCurses $ do
args <- getArgs
buffer <- maybe newBuffer newBufferFromFile (listToMaybe args)
screenSize <- getScreenSize
cursorPos <- getCursorPos buffer
getScreen screenSize buffer >>= updateText cursorPos screenSize
handleEvents screenSize buffer
writeBufferToFile buffer
|
percivalgambit/hasked
|
src/Controller/Runner.hs
|
Haskell
|
bsd-3-clause
| 903
|
module Control.Pipe.Zip (
controllable,
controllable_,
zip,
zip_,
ProducerControl(..),
ZipControl(..),
) where
import qualified Control.Exception as E
import Control.Monad
import Control.Pipe
import Control.Pipe.Coroutine
import Control.Pipe.Exception
import Prelude hiding (zip)
data ProducerControl r
= Done r
| Error E.SomeException
controllable :: Monad m
=> Producer a m r
-> Pipe (Either () (ProducerControl r)) a m r
controllable p = do
x <- pipe (const ()) >+> suspend p
case x of
Left r -> return r
Right (b, p') ->
join $ onException
(await >>= \c -> case c of
Left () -> yield b >> return (controllable (resume p'))
Right (Done r) -> return $ (pipe (const ()) >+> terminate p') >> return r
Right (Error e) -> return $ (pipe (const ()) >+> terminate p') >> throw e)
(pipe (const ()) >+> terminate p')
controllable_ :: Monad m
=> Producer a m r
-> Producer a m r
controllable_ p = pipe Left >+> controllable p
data ZipControl r
= LeftZ (ProducerControl r)
| RightZ (ProducerControl r)
zip :: Monad m
=> Producer a m r
-> Producer b m r
-> Pipe (Either () (ZipControl r)) (Either a b) m r
zip p1 p2 = translate >+> (controllable p1 *+* controllable p2)
where
translate = forever $ await >>= \c -> case c of
Left () -> (yield . Left . Left $ ()) >> (yield . Right . Left $ ())
Right (LeftZ c) -> (yield . Left . Right $ c) >> (yield . Right . Left $ ())
Right (RightZ c) -> (yield . Left . Left $ ()) >> (yield . Right . Right $ c)
zip_ :: Monad m
=> Producer a m r
-> Producer b m r
-> Producer (Either a b) m r
zip_ p1 p2 = pipe Left >+> zip p1 p2
(*+*) :: Monad m
=> Pipe a b m r
-> Pipe a' b' m r
-> Pipe (Either a a') (Either b b') m r
p1 *+* p2 = (continue p1 *** continue p2) >+> both
where
continue p = do
r <- p >+> pipe Right
yield $ Left r
discard
both = await >>= \x -> case x of
Left c -> either (const right) (\a -> yield (Left a) >> both) c
Right c -> either (const left) (\b -> yield (Right b) >> both) c
left = await >>= \x -> case x of
Left c -> either return (\a -> yield (Left a) >> left) c
Right _ -> left
right = await >>= \x -> case x of
Left _ -> right
Right c -> either return (\b -> yield (Right b) >> right) c
|
pcapriotti/pipes-extra
|
Control/Pipe/Zip.hs
|
Haskell
|
bsd-3-clause
| 2,433
|
module Main where
import PScheme.Repl
import PScheme.Reader
import PScheme.Eval (exceptT, defaultEnv, runEval, eval)
import System.IO
import System.Environment (getArgs)
import System.Exit (exitFailure)
import Control.Monad (forM_)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except
import Control.Monad.IO.Class (liftIO, MonadIO)
parseForms :: [[Token]] -> Either ReadError [Value]
parseForms [] = pure []
parseForms (ts:tss) = do
state <- parse ts
parseLines tss state
parseLines :: [[Token]] -> ParseOutcome -> Either ReadError [Value]
parseLines [] state = case (parsedValue state) of
Nothing -> pure []
Just v -> pure [v]
parseLines (ts:tss) state = case (parsedValue state) of
Nothing -> (parseNext state ts) >>= (parseLines tss)
Just v -> do
state' <- parseNext state ts
vs <- parseLines tss state'
pure (v:vs)
tokeniseAll :: String -> Either ReadError [[Token]]
tokeniseAll s = tokeniseLines (lines s) where
tokeniseLines [] = pure []
tokeniseLines (l:ls) = do
ts <- readTokens l
tss <- tokeniseLines ls
pure $ ts:tss
readHandle :: Handle -> ExceptT ReadError IO [Value]
readHandle h = do
contents <- liftIO $ hGetContents h
lineTokens <- exceptT $ tokeniseAll contents
exceptT $ parseForms lineTokens
evalFile :: FilePath -> IO ()
evalFile filePath = withFile filePath ReadMode $ \h -> do
result <- runExceptT $ readHandle h
case result of
Left err -> print err
Right forms -> do
env <- defaultEnv
valsOrError <- runEval env (traverse eval forms)
case valsOrError of
Left err -> print err
Right vals ->
forM_ vals print
main :: IO ()
main = do
args <- getArgs
case args of
[] -> repl
[filePath] -> evalFile filePath
_ -> do
hPutStrLn stderr "Usage: pscheme [file]"
exitFailure
|
lkitching/PScheme
|
app/Main.hs
|
Haskell
|
bsd-3-clause
| 1,848
|
{-|
Module : Control.Monad.Fork
Description : Multithreading within monad transformer stacks
Copyright : (c) Andrew Melnick 2016
License : BSD3
Maintainer : Andrew Melnick
Stability : experimental
Portability : portable
Lifting the concept of forking a new thread into common monad transformers
Monads in the MonadFork class are able to run actions in a new thread, but
require some sort of "handler" data in order to do so properly, for example,
the `ExceptT` Transformer requires some action to be run in the event that
the new thread has an exception
The `:<:` operator joins handlers into a chain, so the monad
@(AT (BT (CT IO)))@ will have a handler that looks like
@(A :<: B :<: C :<: ())@, (where `()` is the handler for `IO`), indicating that
the handlers will be applied in the same order as the effects if one were
unwrapping the stack using @runCT (runBT (runAT x)))@
-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Control.Monad.Fork where
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import qualified Control.Monad.State.Lazy as Lazy
import qualified Control.Monad.State.Strict as Strict
import qualified Control.Monad.Writer.Lazy as Lazy
import qualified Control.Monad.Writer.Strict as Strict
import qualified Control.Monad.RWS.Lazy as Lazy
import qualified Control.Monad.RWS.Strict as Strict
import Control.Monad.Reader
import Control.Monad.Except
import Control.Monad.Catch
import Control.Concurrent
infixr 1 :<:
-- | Monads whose actions can be run in a new thread, provided a handler of
-- type `h` is provided
class Monad m => MonadFork h m where
-- | Run an action in a new thread, and return the id of the new thread
forkT :: h -> m () -> m ThreadId
-- | Monads whose actions can not only be run in a new thread, but are able to
-- react to asynchronous exceptions being thrown in the thread
class (MonadMask m, MonadFork h m) => MonadForkFinally h m where
-- | Like `forkT`, but also takes an action to execute on thread completion
--
-- A default implementation is available based on the relationship between
-- `forkIO` and `forkFinally`, however, that implementation will
-- A) Only execute the handler if no exception is thrown, and B)
-- Execute the handler before the thread completion handler, so any effects
-- caused by it will be lost
forkFinallyT :: h -> m a -> (Either SomeException a -> m ()) -> m ThreadId
forkFinallyT handler action and_then = mask $ \restore ->
forkT handler $ try (restore action) >>= and_then
-- | Base of the instance stack, handler does nothing
instance MonadFork () IO where
forkT _ = forkIO
instance MonadForkFinally () IO where
forkFinallyT _ = forkFinally
-- | Environment is provided to the new thread, handler does nothing
instance MonadFork h m => MonadFork h (ReaderT r m) where
forkT subHandler action = ReaderT $ \env ->
forkT subHandler (runReaderT action env)
instance (MonadMask m, MonadForkFinally h m) => MonadForkFinally h (ReaderT r m)
-- | Handler should report a `Nothing` result
instance MonadFork h m => MonadFork (m () :<: h) (MaybeT m) where
forkT (onNothing :<: subHandler) action = MaybeT $ fmap Just $ forkT subHandler $
runMaybeT action >>= \result -> case result of
Just () -> return ()
Nothing -> onNothing
-- | Handler should report a `Left` result
instance MonadFork h m => MonadFork ((e -> m ()) :<: h) (ExceptT e m) where
forkT (onException :<: subHandler) action = ExceptT $ fmap Right $ forkT subHandler $
runExceptT action >>= \result -> case result of
Right () -> return ()
Left ex -> onException ex
-- | Handler should report original and final state
instance MonadFork h m => MonadFork ((s -> s -> m ()) :<: h) (Lazy.StateT s m) where
forkT (reportState :<: subHandler) action = Lazy.StateT $ \s -> fmap (flip (,) s) $ forkT subHandler $
Lazy.runStateT action s >>= \((), s') -> reportState s s'
instance (MonadMask m, MonadForkFinally h m) => MonadForkFinally ((s -> s -> m ()) :<: h) (Lazy.StateT s m)
-- | Handler should report original and final state
instance MonadFork h m => MonadFork ((s -> s -> m ()) :<: h) (Strict.StateT s m) where
forkT (reportState :<: subHandler) action = Strict.StateT $ \s -> fmap (flip (,) s) $ forkT subHandler $
Strict.runStateT action s >>= \((), s') -> reportState s s'
instance (MonadMask m, MonadForkFinally h m) => MonadForkFinally ((s -> s -> m ()) :<: h) (Strict.StateT s m)
-- | Handler should report final monoidal value
instance (Monoid w, MonadFork h m) => MonadFork ((w -> m ()) :<: h) (Lazy.WriterT w m) where
forkT (reportLog :<: subHandler) action = Lazy.WriterT $ fmap (flip (,) mempty) $ forkT subHandler $
Lazy.runWriterT action >>= \((), w) -> reportLog w
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> m ()) :<: h) (Lazy.WriterT w m)
-- | Handler should report final monoidal value
instance (Monoid w, MonadFork h m) => MonadFork ((w -> m ()) :<: h) (Strict.WriterT w m) where
forkT (reportLog :<: subHandler) action = Strict.WriterT $ fmap (flip (,) mempty) $ forkT subHandler $
Strict.runWriterT action >>= \((), w) -> reportLog w
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> m ()) :<: h) (Strict.WriterT w m)
-- | Environment is provided to the new thread, handler should report final monoid value, initial state, and final state
instance (Monoid w, MonadFork h m) => MonadFork ((w -> s -> s -> m ()) :<: h) (Lazy.RWST r w s m) where
forkT (reportLogAndState :<: subHandler) action = Lazy.RWST $ \r s -> fmap (\x -> (x, s, mempty)) $ forkT subHandler $
Lazy.runRWST action r s >>= \((), s', w) -> reportLogAndState w s s'
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> s -> s -> m ()) :<: h) (Lazy.RWST r w s m)
-- | Environment is provided to the new thread, handler should report final monoid value, initial state, and final state
instance (Monoid w, MonadFork h m) => MonadFork ((w -> s -> s -> m ()) :<: h) (Strict.RWST r w s m) where
forkT (reportLogAndState :<: subHandler) action = Strict.RWST $ \r s -> fmap (\x -> (x, s, mempty)) $ forkT subHandler $
Strict.runRWST action r s >>= \((), s', w) -> reportLogAndState w s s'
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> s -> s -> m ()) :<: h) (Strict.RWST r w s m)
-- | A handler chain, a is used to handle the top of the stack, b is then used
-- to handle the rest of the stack
data a :<: b = a :<: b
-- | Convenience type family for referring to handlers
type family ForkHandler (m :: * -> *)
type instance ForkHandler IO = ()
type instance ForkHandler (ReaderT r m) = ForkHandler m
type instance ForkHandler (MaybeT m) = m () :<: ForkHandler m
type instance ForkHandler (ExceptT e m) = (e -> m ()) :<: ForkHandler m
type instance ForkHandler (Lazy.StateT s m) = (s -> s -> m ()) :<: ForkHandler m
type instance ForkHandler (Strict.StateT s m) = (s -> s -> m ()) :<: ForkHandler m
type instance ForkHandler (Lazy.WriterT w m) = (w -> m ()) :<: ForkHandler m
type instance ForkHandler (Strict.WriterT w m) = (w -> m ()) :<: ForkHandler m
type instance ForkHandler (Lazy.RWST r w s m) = (w -> s -> s -> m ()) :<: ForkHandler m
type instance ForkHandler (Strict.RWST r w s m) = (w -> s -> s -> m ()) :<: ForkHandler m
|
meln5674/monad-fork2
|
Control/Monad/Fork.hs
|
Haskell
|
bsd-3-clause
| 7,555
|
{-| Makes @Closure@ (see "AST") an instance of @Translatable@ (see "CodeGen.Typeclasses") -}
module CodeGen.Closure (
translateClosure,
varSubFromTypeVars,
) where
import CodeGen.Type
import CodeGen.Typeclasses
import CodeGen.Expr ()
import CodeGen.Trace (traceVariable)
import CodeGen.CCodeNames
import CodeGen.ClassTable
import qualified CodeGen.Context as Ctx
import CodeGen.DTrace
import CCode.Main
import qualified Identifiers as ID
import Data.List (intersect)
import qualified AST.AST as A
import qualified AST.Util as Util
import qualified AST.Meta as Meta
import Types as Ty
import Control.Monad.State hiding (void)
import Control.Arrow(first)
import Debug.Trace
varSubFromTypeVars :: [Type] -> [(ID.Name, CCode Lval)]
varSubFromTypeVars = map each
where
each ty =
let ty' = typeVarRefName ty
in (ID.Name $ Ty.getId ty, AsLval ty')
translateClosure :: A.Expr -> [Type] -> ProgramTable -> CCode Toplevel
translateClosure closure typeVars table
| A.isClosure closure =
let arrowType = A.getType closure
resultType = Ty.getResultType arrowType
argTypes = Ty.getArgTypes arrowType
params = A.eparams closure
body = A.body closure
id = Meta.getMetaId . A.getMeta $ closure
funName = closureFunName id
envName = closureEnvName id
traceName = closureTraceName id
boundVars = map (ID.qName . show . A.pname) params
freeVars = map (first ID.qnlocal) $
filter (ID.isLocalQName . fst) $
Util.freeVariables boundVars body
fTypeVars = typeVars `intersect` Util.freeTypeVars body
encEnvNames = map fst freeVars
envNames = map (AsLval . fieldName) encEnvNames
encArgNames = map A.pname params
argNames = map (AsLval . argName) encArgNames
subst = zip encEnvNames envNames ++
zip encArgNames argNames ++
varSubFromTypeVars fTypeVars
ctx = Ctx.setClsCtx (Ctx.new subst table) closure
((bodyName, bodyStat), _) = runState (translate body) ctx
in
Concat [buildEnvironment envName freeVars fTypeVars,
tracefunDecl traceName envName freeVars fTypeVars,
Function (Static $ Typ "value_t") funName
[(Ptr (Ptr encoreCtxT), encoreCtxVar),
(Ptr (Ptr ponyTypeT), encoreRuntimeType),
(Typ "value_t", Var "_args[]"),
(Ptr void, envVar)]
(Seq $
dtraceClosureEntry argNames :
extractArguments params ++
extractEnvironment envName freeVars fTypeVars ++
[bodyStat
,dtraceClosureExit
,returnStmnt bodyName resultType])]
| otherwise =
error
"Tried to translate a closure from something that was not a closure"
where
returnStmnt var ty
| isUnitType ty = Return $ asEncoreArgT (translate ty) unit
| otherwise = Return $ asEncoreArgT (translate ty) var
extractArguments params = extractArguments' params 0
extractArguments' [] _ = []
extractArguments' ((A.Param{A.pname, A.ptype}):args) i =
Assign (Decl (ty, arg)) (getArgument i) : extractArguments' args (i+1)
where
ty = translate ptype
arg = AsLval $ argName pname
getArgument i = fromEncoreArgT ty $ AsExpr $ ArrAcc i (Var "_args")
buildEnvironment name vars typeVars =
StructDecl (Typ $ show name) $
(map translateBinding vars) ++ (map translateTypeVar typeVars)
where
translateBinding (name, ty) =
(translate ty, AsLval $ fieldName name)
translateTypeVar ty =
(Ptr ponyTypeT, AsLval $ typeVarRefName ty)
extractEnvironment envName vars typeVars =
map assignVar vars ++ map assignTypeVar typeVars
where
assignVar (name, ty) =
let fName = fieldName name
in Assign (Decl (translate ty, AsLval fName)) $ getVar fName
assignTypeVar ty =
let fName = typeVarRefName ty
in Seq [Assign (Decl (Ptr ponyTypeT, AsLval fName)) $ getVar fName,
encoreAssert (AsExpr $ AsLval fName)]
getVar name =
(Deref $ Cast (Ptr $ Struct envName) envVar) `Dot` name
tracefunDecl traceName envName members fTypeVars =
Function (Static void) traceName args body
where
args = [(Ptr encoreCtxT, ctxArg), (Ptr void, Var "p")]
ctxArg = Var "_ctx_arg"
body = Seq $
Assign (Decl (Ptr (Ptr encoreCtxT), encoreCtxVar)) (Amp ctxArg) :
Assign (Decl (Ptr $ Struct envName, envVar)) (Var "p") :
extractEnvironment envName members fTypeVars ++
map traceMember members
traceMember (name, ty) = traceVariable ty $ getVar name
getVar name = envVar `Arrow` fieldName name
|
Paow/encore
|
src/back/CodeGen/Closure.hs
|
Haskell
|
bsd-3-clause
| 5,274
|
{-# LANGUAGE OverloadedStrings #-}
module Websave.Web.Data
( getData
) where
import Control.Monad (join)
import Data.ByteString (ByteString)
import Network.Wai (queryString)
import Yesod.Core (MonadHandler, getRequest, reqWaiRequest)
-- TODO move to YesodTools
-- TODO process POST data as well
getData :: MonadHandler m => m (Maybe ByteString)
getData = join . lookup "data" . queryString . reqWaiRequest <$> getRequest
|
dimsmol/websave
|
src/Websave/Web/Data.hs
|
Haskell
|
bsd-3-clause
| 427
|
--------------------------------------------------------------------------
-- |
-- Module: Harpy
-- Copyright: (c) 2006-2015 Martin Grabmueller and Dirk Kleeblatt
-- License: BSD3
--
-- Maintainer: martin@grabmueller.de
-- Stability: provisional
-- Portability: portable
--
-- Harpy is a library for run-time code generation of x86 machine code.
--
-- This is a convenience module which re-exports the modules which are
-- essential for using Harpy.
----------------------------------------------------------------------------
module Harpy(module Harpy.CodeGenMonad,
module Harpy.Call,
module Harpy.X86Assembler,
module Control.Monad.Trans) where
import Harpy.CodeGenMonad
import Harpy.Call
import Harpy.X86Assembler
import Control.Monad.Trans
|
mgrabmueller/harpy
|
Harpy.hs
|
Haskell
|
bsd-3-clause
| 799
|
module LinAlg where
import ListNumSyntax
import Data.Number.IReal
import Data.Number.IReal.FoldB
import Data.Ratio
import Data.List
import Data.Bits
type Vector a = [a]
type Matrix a = [Vector a]
-- Ad hoc choice of precision restriction
prec0 x = prec 200 x
-- Multiplication ------------------------------------------
mulM :: (VarPrec a, Num a) => Matrix a -> Matrix a -> Matrix a
mulM = map . apply
apply :: (Num a, VarPrec a) => Matrix a -> Vector a -> Vector a
apply ass bs = map (`dot` bs) (transpose ass)
-- Multiplication with scalar --------------------------------------------------
smul :: Num a => a -> Vector a -> Vector a
smul x = map (x *)
smulM :: Num a => a -> Matrix a -> Matrix a
smulM x = map (smul x)
-- Scalar product --------------------------------------------------------------
dot :: (Num a, VarPrec a) => Vector a -> Vector a -> a
dot xs ys = prec0 (bsum (xs * ys))
-- Norms of vector ------------------------------------------------------------
norm2, norm1, normInf :: (Floating a, Ord a, VarPrec a) => Vector a -> a
norm2 xs = sqrt (dot xs xs)
norm1 = bsum . map abs
normInf = maximum . map abs
-- L_1 and L_infinity norms of matrix -----------------------------------------
normM1, normMInf :: (Ord a, Floating a, VarPrec a) => Matrix a -> a
normM1 = maximum . map norm1
normMInf = normM1 . transpose
-- Condition number of matrix (in L_1 norm) -----------------------------------
condM :: (Floating a, Ord a, VarPrec a) => Matrix a -> a
condM ass = normM1 ass * normM1 (inverse ass)
-- LQ factorization ------------------------------------------------------------
-- LQ factorization of quadratic matrix.
-- We choose LQ rather than QR since it fits better with
-- head/tail access pattern of lists. Returns L and Q, where
-- L is on triangular form, i.e. only non-zero elements present, and
-- Q is represented as a list of normal vectors of Householder reflectors.
lq :: (Floating a, Ord a, VarPrec a) => Matrix a -> (Matrix a, [Vector a])
lq ass@((x:xs):xss@(_:_)) = (bs : lss, vs : vss)
where h:hs = map head ass
d = norm2 (h:hs)
vs = (if h >= 0 then h + d else h - d): hs
v2 = 2*d*(d+abs h) -- d1 = ||vs||^2
-- Multiply ass by Householder reflector matrix
-- generated by vector vs, i.e. compute A - 2*A*v*v^t
bs : bss = prec0 (zipWith f ass vs)
where f as x = as - apply ass vs * repeat (2*x/v2)
(lss,vss) = lq (map tail bss)
lq ass = (ass, [])
-- Solve quadratic, non-singular system Ax = b, using LQ factorization.
solve :: (Floating a, Ord a, VarPrec a) => Matrix a -> Vector a -> Vector a
solve ass = qIter vss . subst lss
where (lss,vss) = lq ass
-- Solve triangular system (matrix is lower triangular)
subst :: Fractional a => [[a]] -> [a] -> [a]
subst [] _ = []
subst ((x:xs):xss) (b:bs) = y : subst xss (bs - xs * repeat y)
where y = b/x
-- Multiply by sequence of Householder matrices
qIter :: (Fractional a, VarPrec a) => [Vector a] -> Vector a -> Vector a
qIter [] bs = bs
qIter (vs : vss) (b : bs) = hh vs (b : qIter vss bs)
-- Vector rs multiplied by Householder reflector matrix generated by vs
hh :: (Fractional a, VarPrec a) => Vector a -> Vector a -> Vector a
hh vs rs = rs - vs * repeat x
where x = 2 * dot rs vs/dot vs vs
inverse :: (Floating a, Ord a, VarPrec a) => Matrix a -> Matrix a
inverse ass = map (solve ass) bss
where bss = map (\k -> replicate k 0 ++ 1 : replicate (n-1-k) 0) [0..n-1]
n = length ass
-- Notorious ill-conditioned example: Hilbert matrix
hilbert n = [[fromRational (1 % (i+j-1)) | i <- [1..n] ] | j <- [1..n] ]
vandermonde xs = take n (iterate (*xs) (replicate n 1))
where n = length xs
{-
Examples:
> condM (hilbert 15) ?? 20
0.15391915629553122413e22
(0.82 secs, 283246752 bytes)
> let ass = hilbert 25 :: Matrix IReal
> mapM_ (? 100) $ solve ass (map sqrt [1..25])
705.1533284963290956608362822423912734910227236293299614122851194081918876326343926875640023119369034821
-439673.9873388597705868990725370476651285605876080956807569044940939165590176737169191270235259441503432119
68204344.9731886365740080624537609996623689444810205308753901423565119434568104831725210699973202379088129882
-4664448582.3034346633655587322862893452286509473730850571024608318992483060505363965128396539508414113288932734
177397301669.4470302993210422259749351478977835134529306395373729499456573463841842107447990766834809423011040738
-4254091706828.1686190716920574829426672777980678548199026748623525425695787052836566266674697317136802722120565833
69545239200122.9144040744433369547417865224879339613940156554671219472545236203917004334667205391996866968931595183
-816847000729018.7737530264497363783287163634866491132650857885691558585008629694744116239295210128489892702899000614
7154341228591462.3012615296054988779018448134073649486823700047095232218238925733189512085896861380925718869840128164
-48009667586828894.5767332565013430439910972214304035550971986293103555764342546810272410148080254252305995120781866206
251844392677531274.0709127325911434838350769774189068254774415143641327544366238651541772916524464117349357235144334991
-1048143734335817624.0336204855464617426412722915751934481683873315855051574469784131062190560275498658327486102529792226
3498210324096944636.4524065506620210607308978049694297040490003525118886804565590254308130573820526159628678426741651309
-9431171401929169455.3424006600477669947185012388808800099904639824329048176939584968420634515763762886683395660091124001
20625644400616390081.3023145571266820730894216095277381736236614083175100283703764598631503021932601076440164701624585386
-36637408250801684992.2327515887414617772781813348542150962395077849459653041754367086153854944131054328104108083193973575
52765488024278928905.4679536245314145289284377844729508688894134162341828418605873919241149475390504553871953987733953659
-61295595789243212173.9536012643337759381753284186801798055604026908049933788464084009039536683226486562275743371985047603
56896779843800653456.9314422266376319337514520994749231451564802652135775892050259875530397079988163136075067115610230454
-41573863983516368926.7055317586515189490950549358051162588877518503235490221753772940736406787440880748304465115113504359
23365653654180951042.9851530663181890194238095089360096426483401824061668322486605839625160258109763064486458688933759486
-9740723523526602431.8575162294625153120767034736388134987019551900158949982443457241958170904379968964746678508149489593
2835293607475155284.1978846389721895478771840783053407794046273623991370837498430393230149403586055906293606569603644531
-514097728749287006.1850108351735689777337751827160575523829387979908417439866364790805580176949298837083538483210154166
43696874386454381.7499373427978656981157281081737498936218190682725431997586473877133365258605530660231535107025476866
(1.06 secs, 291352880 bytes)
-}
|
sydow/ireal
|
applications/LinAlg.hs
|
Haskell
|
bsd-3-clause
| 7,044
|
module Messages where
import qualified Sound.OSC as SO
import qualified System.MIDI as SM
data DX200Msg = OSCMsg SO.Message | MidiMsg SM.MidiMessage deriving (Show)
|
rumblesan/dx200-programmer
|
src/Messages.hs
|
Haskell
|
bsd-3-clause
| 170
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.