code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
import System.Plugins import API conf = "../Plugin.in" stub = "../Plugin.stub" main = do status <- makeWith conf stub ["-i../api", "-i../../../../src/altdata"] o <- case status of MakeFailure e -> mapM_ putStrLn e >> error "failed" MakeSuccess _ o -> return o m_v <- dynload o ["../api"] [] "resource_dyn" case m_v of LoadFailure _ -> error "didn't compile" LoadSuccess _ v -> do putStrLn $ (function v) makeCleaner o
abuiles/turbinado-blog
tmp/dependencies/hs-plugins-1.3.1/testsuite/dynload/should_fail_3/prog/Main.hs
bsd-3-clause
565
0
14
214
160
75
85
14
3
{-# LANGUAGE CPP #-} #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif #include "containers.h" ----------------------------------------------------------------------------- -- | -- Module : Data.Set -- Copyright : (c) Daan Leijen 2002 -- License : BSD-style -- Maintainer : [email protected] -- 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. -- -- /Warning/: The size of the set must not exceed @maxBound::Int@. Violation of -- this condition is not detected and if the size limit is exceeded, its -- behaviour is undefined. ----------------------------------------------------------------------------- module Data.Set ( -- * Strictness properties -- $strictness -- * Set type #if !defined(TESTING) Set -- instance Eq,Ord,Show,Read,Data,Typeable #else Set(..) #endif -- * Operators , (\\) -- * Query , S.null , size , member , notMember , lookupLT , lookupGT , lookupLE , lookupGE , isSubsetOf , isProperSubsetOf -- * Construction , empty , singleton , insert , delete -- * Combine , union , unions , difference , intersection -- * Filter , S.filter , partition , split , splitMember , splitRoot -- * Indexed , lookupIndex , findIndex , elemAt , deleteAt -- * Map , S.map , mapMonotonic -- * Folds , S.foldr , S.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 #if defined(TESTING) -- Internals (for testing) , bin , balanced , link , merge #endif ) where import Data.Set.Base as S -- $strictness -- -- This module satisfies the following strictness property: -- -- * Key arguments are evaluated to WHNF -- -- Here are some examples that illustrate the property: -- -- > delete undefined s == undefined
iu-parfunc/containers
Data/Set.hs
bsd-3-clause
3,937
0
5
1,499
279
211
68
57
0
module LayoutIn4 where --Layout rule applies after 'where','let','do' and 'of' --In this Example: rename 'ioFun' to 'io' main = io "hello" where io s= do let k = reverse s --There is a commet s <- getLine let q = (k ++ s) putStr q putStr "foo"
kmate/HaRe
old/testing/renaming/LayoutIn4_TokOut.hs
bsd-3-clause
389
0
13
192
72
35
37
6
1
x <|> y = y main :: IO () main = do{ putStrLn "foo"; putStrLn "bar" } <|> putStrLn "baz"
hvr/jhc
regress/tests/0_parse/2_pass/DoInfix.hs
mit
94
0
8
25
49
23
26
3
1
module PrettyDoc where import TokenTags data Layout = Horiz Sep | Vert | HorizOrVert Sep | Fill Sep deriving (Show) data Sep = Cat | Sep deriving (Show) nonEmpty Empty = False nonEmpty d = True data Doc = Empty | Char Char | Text String | Attr TokenTag Doc | Nest Int Doc | Group Layout [Doc] deriving (Show) {- class Doc doc where -- Required methods: empty :: doc text :: String->doc nest :: Int->doc->doc group :: Layout->[doc]->doc -- Methods with default implementations: char :: Char->doc char c = text [c] -}
forste/haReFork
tools/base/pretty/PrettyDoc.hs
bsd-3-clause
551
0
7
129
118
69
49
14
1
{-# OPTIONS_GHC -fwarn-unused-pattern-binds #-} -- Trac #17 module Temp (foo, bar, quux) where top :: Int top = 1 foo :: () foo = let True = True in () bar :: Int -> Int bar match = 1 quux :: Int quux = let local = True in 2
wxwxwwxxx/ghc
testsuite/tests/rename/should_compile/T17c.hs
bsd-3-clause
238
0
8
63
91
51
40
11
1
{-# LANGUAGE TemplateHaskell, ForeignFunctionInterface, InterruptibleFFI #-} module TH_foreign where import Foreign.Ptr import Language.Haskell.TH $(return [ForeignD (ImportF CCall Interruptible "&" (mkName "foo") (AppT (ConT ''Ptr) (ConT ''())))]) -- Should generate the same as this: foreign import ccall interruptible "&" foo1 :: Ptr ()
urbanslug/ghc
testsuite/tests/th/TH_foreignInterruptible.hs
bsd-3-clause
344
0
17
46
98
52
46
6
0
module Extras.Data.String where indent :: [String] -> [String] indent = map (" " ++)
fredmorcos/attic
projects/pet/archive/pet_haskell_modular_1/Extras/Data/String.hs
isc
87
0
6
16
34
21
13
3
1
module Main where import Data.List import Data.Ord data Item = Item { itemName :: String, itemCost, itemDamage, itemArmor :: Int } deriving (Show, Read) main = do print $ minimumBy (comparing itemCost) $ filter fight $ gearOptions print $ maximumBy (comparing itemCost) $ filter (not . fight) $ gearOptions emptyItem :: String -> Item emptyItem name = Item name 0 0 0 --Weapons: Cost Damage Armor weapons :: [Item] weapons = [ Item "Dagger" 8 4 0 , Item "Shortsword" 10 5 0 , Item "Warhammer" 25 6 0 , Item "Longsword" 40 7 0 , Item "Greataxe" 74 8 0 ] --Armor: Cost Damage Armor armors :: [Item] armors = [ Item "Leather" 13 0 1 , Item "Chainmail" 31 0 2 , Item "Splintmail" 53 0 3 , Item "Bandedmail" 75 0 4 , Item "Platemail" 102 0 5 ] -- Rings: Cost Damage Armor rings :: [Item] rings = [ Item "Damage +1" 25 1 0 , Item "Damage +2" 50 2 0 , Item "Damage +3" 100 3 0 , Item "Defense +1" 20 0 1 , Item "Defense +2" 40 0 2 , Item "Defense +3" 80 0 3 ] combine :: Item -> Item -> Item combine x y = Item { itemName = itemName x ++ " and " ++ itemName y , itemCost = itemCost x + itemCost y , itemDamage = itemDamage x + itemDamage y , itemArmor = itemArmor x + itemArmor y } gearOptions :: [Item] gearOptions = do weapon <- weapons armor <- emptyItem "unarmored" : armors ring <- chooseUpTo 2 rings return (foldl1 combine (weapon : armor : ring)) chooseUpTo 0 _ = [[]] chooseUpTo _ [] = [[]] chooseUpTo n (x:xs) = map (x:) (chooseUpTo (n-1) xs) ++ chooseUpTo n xs fight gear = outcome 100 (max 1 (8 - itemArmor gear)) 104 (max 1 (itemDamage gear - 1)) outcome :: Int -> Int -> Int -> Int -> Bool outcome hp1 dec1 hp2 dec2 = (hp1-1)`quot`dec1 >= (hp2-1)`quot`dec2
glguy/advent2015
Day21.hs
isc
2,042
0
12
712
740
385
355
57
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.Navigator (js_getGamepads, getGamepads, js_webkitGetUserMedia, webkitGetUserMedia, js_registerProtocolHandler, registerProtocolHandler, js_isProtocolHandlerRegistered, isProtocolHandlerRegistered, js_unregisterProtocolHandler, unregisterProtocolHandler, js_vibratePattern, vibratePattern, js_vibrate, vibrate, js_javaEnabled, javaEnabled, js_getStorageUpdates, getStorageUpdates, js_getWebkitBattery, getWebkitBattery, js_getGeolocation, getGeolocation, js_getWebkitTemporaryStorage, getWebkitTemporaryStorage, js_getWebkitPersistentStorage, getWebkitPersistentStorage, js_getAppCodeName, getAppCodeName, js_getAppName, getAppName, js_getAppVersion, getAppVersion, js_getLanguage, getLanguage, js_getUserAgent, getUserAgent, js_getPlatform, getPlatform, js_getPlugins, getPlugins, js_getMimeTypes, getMimeTypes, js_getProduct, getProduct, js_getProductSub, getProductSub, js_getVendor, getVendor, js_getVendorSub, getVendorSub, js_getCookieEnabled, getCookieEnabled, js_getOnLine, getOnLine, js_getHardwareConcurrency, getHardwareConcurrency, Navigator, castToNavigator, gTypeNavigator) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"getGamepads\"]()" js_getGamepads :: Navigator -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getGamepads Mozilla Navigator.getGamepads documentation> getGamepads :: (MonadIO m) => Navigator -> m [Maybe Gamepad] getGamepads self = liftIO ((js_getGamepads (self)) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"webkitGetUserMedia\"]($2, $3,\n$4)" js_webkitGetUserMedia :: Navigator -> Nullable Dictionary -> Nullable NavigatorUserMediaSuccessCallback -> Nullable NavigatorUserMediaErrorCallback -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.webkitGetUserMedia Mozilla Navigator.webkitGetUserMedia documentation> webkitGetUserMedia :: (MonadIO m, IsDictionary options) => Navigator -> Maybe options -> Maybe NavigatorUserMediaSuccessCallback -> Maybe NavigatorUserMediaErrorCallback -> m () webkitGetUserMedia self options successCallback errorCallback = liftIO (js_webkitGetUserMedia (self) (maybeToNullable (fmap toDictionary options)) (maybeToNullable successCallback) (maybeToNullable errorCallback)) foreign import javascript unsafe "$1[\"registerProtocolHandler\"]($2,\n$3, $4)" js_registerProtocolHandler :: Navigator -> JSString -> JSString -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.registerProtocolHandler Mozilla Navigator.registerProtocolHandler documentation> registerProtocolHandler :: (MonadIO m, ToJSString scheme, ToJSString url, ToJSString title) => Navigator -> scheme -> url -> title -> m () registerProtocolHandler self scheme url title = liftIO (js_registerProtocolHandler (self) (toJSString scheme) (toJSString url) (toJSString title)) foreign import javascript unsafe "$1[\"isProtocolHandlerRegistered\"]($2,\n$3)" js_isProtocolHandlerRegistered :: Navigator -> JSString -> JSString -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.isProtocolHandlerRegistered Mozilla Navigator.isProtocolHandlerRegistered documentation> isProtocolHandlerRegistered :: (MonadIO m, ToJSString scheme, ToJSString url, FromJSString result) => Navigator -> scheme -> url -> m result isProtocolHandlerRegistered self scheme url = liftIO (fromJSString <$> (js_isProtocolHandlerRegistered (self) (toJSString scheme) (toJSString url))) foreign import javascript unsafe "$1[\"unregisterProtocolHandler\"]($2,\n$3)" js_unregisterProtocolHandler :: Navigator -> JSString -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.unregisterProtocolHandler Mozilla Navigator.unregisterProtocolHandler documentation> unregisterProtocolHandler :: (MonadIO m, ToJSString scheme, ToJSString url) => Navigator -> scheme -> url -> m () unregisterProtocolHandler self scheme url = liftIO (js_unregisterProtocolHandler (self) (toJSString scheme) (toJSString url)) foreign import javascript unsafe "($1[\"vibrate\"]($2) ? 1 : 0)" js_vibratePattern :: Navigator -> JSVal -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vibrate Mozilla Navigator.vibrate documentation> vibratePattern :: (MonadIO m) => Navigator -> [Word] -> m Bool vibratePattern self pattern' = liftIO (toJSVal pattern' >>= \ pattern'' -> js_vibratePattern (self) pattern'') foreign import javascript unsafe "($1[\"vibrate\"]($2) ? 1 : 0)" js_vibrate :: Navigator -> Word -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vibrate Mozilla Navigator.vibrate documentation> vibrate :: (MonadIO m) => Navigator -> Word -> m Bool vibrate self time = liftIO (js_vibrate (self) time) foreign import javascript unsafe "($1[\"javaEnabled\"]() ? 1 : 0)" js_javaEnabled :: Navigator -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.javaEnabled Mozilla Navigator.javaEnabled documentation> javaEnabled :: (MonadIO m) => Navigator -> m Bool javaEnabled self = liftIO (js_javaEnabled (self)) foreign import javascript unsafe "$1[\"getStorageUpdates\"]()" js_getStorageUpdates :: Navigator -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getStorageUpdates Mozilla Navigator.getStorageUpdates documentation> getStorageUpdates :: (MonadIO m) => Navigator -> m () getStorageUpdates self = liftIO (js_getStorageUpdates (self)) foreign import javascript unsafe "$1[\"webkitBattery\"]" js_getWebkitBattery :: Navigator -> IO (Nullable BatteryManager) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.webkitBattery Mozilla Navigator.webkitBattery documentation> getWebkitBattery :: (MonadIO m) => Navigator -> m (Maybe BatteryManager) getWebkitBattery self = liftIO (nullableToMaybe <$> (js_getWebkitBattery (self))) foreign import javascript unsafe "$1[\"geolocation\"]" js_getGeolocation :: Navigator -> IO (Nullable Geolocation) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.geolocation Mozilla Navigator.geolocation documentation> getGeolocation :: (MonadIO m) => Navigator -> m (Maybe Geolocation) getGeolocation self = liftIO (nullableToMaybe <$> (js_getGeolocation (self))) foreign import javascript unsafe "$1[\"webkitTemporaryStorage\"]" js_getWebkitTemporaryStorage :: Navigator -> IO (Nullable StorageQuota) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.webkitTemporaryStorage Mozilla Navigator.webkitTemporaryStorage documentation> getWebkitTemporaryStorage :: (MonadIO m) => Navigator -> m (Maybe StorageQuota) getWebkitTemporaryStorage self = liftIO (nullableToMaybe <$> (js_getWebkitTemporaryStorage (self))) foreign import javascript unsafe "$1[\"webkitPersistentStorage\"]" js_getWebkitPersistentStorage :: Navigator -> IO (Nullable StorageQuota) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.webkitPersistentStorage Mozilla Navigator.webkitPersistentStorage documentation> getWebkitPersistentStorage :: (MonadIO m) => Navigator -> m (Maybe StorageQuota) getWebkitPersistentStorage self = liftIO (nullableToMaybe <$> (js_getWebkitPersistentStorage (self))) foreign import javascript unsafe "$1[\"appCodeName\"]" js_getAppCodeName :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.appCodeName Mozilla Navigator.appCodeName documentation> getAppCodeName :: (MonadIO m, FromJSString result) => Navigator -> m result getAppCodeName self = liftIO (fromJSString <$> (js_getAppCodeName (self))) foreign import javascript unsafe "$1[\"appName\"]" js_getAppName :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.appName Mozilla Navigator.appName documentation> getAppName :: (MonadIO m, FromJSString result) => Navigator -> m result getAppName self = liftIO (fromJSString <$> (js_getAppName (self))) foreign import javascript unsafe "$1[\"appVersion\"]" js_getAppVersion :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.appVersion Mozilla Navigator.appVersion documentation> getAppVersion :: (MonadIO m, FromJSString result) => Navigator -> m result getAppVersion self = liftIO (fromJSString <$> (js_getAppVersion (self))) foreign import javascript unsafe "$1[\"language\"]" js_getLanguage :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.language Mozilla Navigator.language documentation> getLanguage :: (MonadIO m, FromJSString result) => Navigator -> m result getLanguage self = liftIO (fromJSString <$> (js_getLanguage (self))) foreign import javascript unsafe "$1[\"userAgent\"]" js_getUserAgent :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.userAgent Mozilla Navigator.userAgent documentation> getUserAgent :: (MonadIO m, FromJSString result) => Navigator -> m result getUserAgent self = liftIO (fromJSString <$> (js_getUserAgent (self))) foreign import javascript unsafe "$1[\"platform\"]" js_getPlatform :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.platform Mozilla Navigator.platform documentation> getPlatform :: (MonadIO m, FromJSString result) => Navigator -> m result getPlatform self = liftIO (fromJSString <$> (js_getPlatform (self))) foreign import javascript unsafe "$1[\"plugins\"]" js_getPlugins :: Navigator -> IO (Nullable PluginArray) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.plugins Mozilla Navigator.plugins documentation> getPlugins :: (MonadIO m) => Navigator -> m (Maybe PluginArray) getPlugins self = liftIO (nullableToMaybe <$> (js_getPlugins (self))) foreign import javascript unsafe "$1[\"mimeTypes\"]" js_getMimeTypes :: Navigator -> IO (Nullable MimeTypeArray) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.mimeTypes Mozilla Navigator.mimeTypes documentation> getMimeTypes :: (MonadIO m) => Navigator -> m (Maybe MimeTypeArray) getMimeTypes self = liftIO (nullableToMaybe <$> (js_getMimeTypes (self))) foreign import javascript unsafe "$1[\"product\"]" js_getProduct :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.product Mozilla Navigator.product documentation> getProduct :: (MonadIO m, FromJSString result) => Navigator -> m result getProduct self = liftIO (fromJSString <$> (js_getProduct (self))) foreign import javascript unsafe "$1[\"productSub\"]" js_getProductSub :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.productSub Mozilla Navigator.productSub documentation> getProductSub :: (MonadIO m, FromJSString result) => Navigator -> m result getProductSub self = liftIO (fromJSString <$> (js_getProductSub (self))) foreign import javascript unsafe "$1[\"vendor\"]" js_getVendor :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vendor Mozilla Navigator.vendor documentation> getVendor :: (MonadIO m, FromJSString result) => Navigator -> m result getVendor self = liftIO (fromJSString <$> (js_getVendor (self))) foreign import javascript unsafe "$1[\"vendorSub\"]" js_getVendorSub :: Navigator -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vendorSub Mozilla Navigator.vendorSub documentation> getVendorSub :: (MonadIO m, FromJSString result) => Navigator -> m result getVendorSub self = liftIO (fromJSString <$> (js_getVendorSub (self))) foreign import javascript unsafe "($1[\"cookieEnabled\"] ? 1 : 0)" js_getCookieEnabled :: Navigator -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.cookieEnabled Mozilla Navigator.cookieEnabled documentation> getCookieEnabled :: (MonadIO m) => Navigator -> m Bool getCookieEnabled self = liftIO (js_getCookieEnabled (self)) foreign import javascript unsafe "($1[\"onLine\"] ? 1 : 0)" js_getOnLine :: Navigator -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.onLine Mozilla Navigator.onLine documentation> getOnLine :: (MonadIO m) => Navigator -> m Bool getOnLine self = liftIO (js_getOnLine (self)) foreign import javascript unsafe "$1[\"hardwareConcurrency\"]" js_getHardwareConcurrency :: Navigator -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.hardwareConcurrency Mozilla Navigator.hardwareConcurrency documentation> getHardwareConcurrency :: (MonadIO m) => Navigator -> m Int getHardwareConcurrency self = liftIO (js_getHardwareConcurrency (self))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Navigator.hs
mit
14,541
192
11
2,505
2,815
1,521
1,294
217
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, FlexibleContexts, EmptyDataDecls, ScopedTypeVariables, TypeOperators, TypeSynonymInstances, TypeFamilies #-} import Prelude hiding (lookup,read,last) {- State ref and stack -} class Memory m where data Malloc :: * -> * -> * malloc :: m -> a -> Malloc a m free :: Malloc a m -> m read :: Malloc a m -> a write :: a -> Malloc a m -> Malloc a m class (Memory m,Monad (st m m)) => State st m where data Ref st :: * -> * -> * eval :: Ref st m a -> st m m a (.=) :: Ref st m a -> a -> st m m () delete :: st (Malloc a m) m () new :: a -> st m (Malloc a m) (Ref st (Malloc a m) a) (>>+) :: (Memory m', Memory m'') => st m m' a -> (a -> st m' m'' b) -> st m m'' b (*=) :: State st s => Ref st s a -> (a->a) -> st s s () ref *= f = do v <- eval ref ref .= (f v) {- Records -} class (State st m) => Record r st m where data Label st r :: * -> * (<==) :: (Ref st) m r -> Label st r a -> (Ref st) m a {- Mutable Implementation -} {- HList -} data Nil = Nil deriving (Show) class HList l instance HList Nil instance HList tl => HList (Malloc h tl) data Z = Z data S n = S n class CNum n instance CNum Z instance CNum n => CNum (S n) type family HLength l :: * type instance HLength Nil = Z type instance HLength (Malloc h tl) = S (HLength tl) type family HAt l n :: * type instance HAt (Malloc h tl) Z = h type instance HAt (Malloc h tl) (S n) = HAt tl n class (HList l, CNum n) => HLookup l n where lookup :: l -> n -> HAt l n update :: l -> n -> HAt l n -> l instance (HList tl) => HLookup (Malloc h tl) Z where lookup (Malloc h tl) _ = h update (Malloc h tl) _ h' = (Malloc h' tl) instance (HList tl, CNum n, HLookup tl n) => HLookup (Malloc h tl) (S n) where lookup (Malloc _ tl) _ = lookup tl (undefined::n) update (Malloc h tl) _ v' = (Malloc h (update tl (undefined::n) v')) {- State Monad Implementation -} data St s s' a = St(s->(a,s')) type Get s a = St s s a type Set s a = a -> St s s () instance Monad (St s s) where return x = St(\s -> (x,s)) (St st) >>= k = St(\s -> let (res,s') = st s (St k') = k res in k' s') runSt :: St s s' a -> s -> a runSt (St st) s = fst (st s) {- Memory and State Implementation -} instance (HList m) => Memory m where data Malloc a m = Malloc a m deriving (Show) malloc m a = Malloc a m free (Malloc h tl) = tl read (Malloc h tl) = h write h' (Malloc h tl) = Malloc h' tl instance (HList m, n~HLength m) => State St m where data Ref St m a = StRef (Get m a) (Set m a) eval (StRef get set) = get (StRef get set) .= v = set v delete = St(\s -> ((), free s)) new v = let new_ref = StRef (St (\s -> (read s, s))) (\v' -> St(\s -> ((), write v' s))) in St (\s -> (new_ref, malloc s v)) (St st) >>+ k = St(\s -> let (res,s') = st s (St k') = k res in k' s') {- State Example -} --ex1 :: forall m0 m1 . (m0 ~ Nil, m1 ~ (Malloc(m0,Int))) => St m0 m1 Int ex1 = new 10 >>+ (\i -> do i *= (+2) eval i) res1 :: Int res1 = runSt ex1 Nil {- Record Implementation -} instance (HList m, HList r) => Record r St m where data Label St r a = StLabel (r->a) (r->a->r) StRef get set <== StLabel read write = StRef(do r <- get return (read r)) (\v'-> do r <- get set (write r v')) labelAt :: forall l n . (HList l, CNum n, HLookup l n) => n -> Label St l (HAt l n) labelAt _ = StLabel (\l -> lookup l (undefined::n)) (\l -> \v -> update l (undefined::n) v) {- Record Example -} infixr `Malloc` type Person = String `Malloc` String `Malloc` Int `Malloc` Nil first :: Label St Person String first = labelAt Z last :: Label St Person String last = labelAt (S Z) age :: Label St Person Int age = labelAt (S (S Z)) mk_person :: String -> String -> Int -> Person mk_person f l a = (f `Malloc` l `Malloc` a `Malloc` Nil) ex2 = new (mk_person "John" "Smith" 27) >>+ (\p -> do (p <== last) *= (++ " Jr.") (p <== age) .= 25 eval p) res2 = runSt ex2 Nil
vs-team/Papers
Before Giuseppe's PhD/Monads/ObjectiveMonad/MonadicObjects/trunk/Src v2/Objell.hs
mit
4,397
0
17
1,421
2,137
1,106
1,031
-1
-1
{-# LANGUAGE CPP #-} #define DO_NOT_EDIT (doNotEdit __FILE__ __LINE__) -- | Generates code for HTML tags. -- module Util.GenerateHtmlCombinators where import Control.Arrow ((&&&)) import Data.List (sort, sortBy, intersperse, intercalate) import Data.Ord (comparing) import System.Directory (createDirectoryIfMissing) import System.FilePath ((</>), (<.>)) import Data.Map (Map) import qualified Data.Map as M import Data.Char (toLower) import qualified Data.Set as S import Util.Sanitize (sanitize, prelude) -- | Datatype for an HTML variant. -- data HtmlVariant = HtmlVariant { version :: [String] , docType :: [String] , parents :: [String] , leafs :: [String] , attributes :: [String] , selfClosing :: Bool } deriving (Eq) instance Show HtmlVariant where show = map toLower . intercalate "-" . version -- | Get the full module name for an HTML variant. -- getModuleName :: HtmlVariant -> String getModuleName = ("Haste.Markup." ++) . intercalate "." . version -- | Get the attribute module name for an HTML variant. -- getAttributeModuleName :: HtmlVariant -> String getAttributeModuleName = (++ ".Attributes") . getModuleName -- | Check if a given name causes a name clash. -- isNameClash :: HtmlVariant -> String -> Bool isNameClash v t -- Both an element and an attribute | (t `elem` parents v || t `elem` leafs v) && t `elem` attributes v = True -- Already a prelude function | sanitize t `S.member` prelude = True | otherwise = False -- | Write an HTML variant. -- writeHtmlVariant :: HtmlVariant -> IO () writeHtmlVariant htmlVariant = do -- Make a directory. createDirectoryIfMissing True basePath let tags = zip parents' (repeat makeParent) ++ zip leafs' (repeat (makeLeaf $ selfClosing htmlVariant)) sortedTags = sortBy (comparing fst) tags appliedTags = map (\(x, f) -> f x) sortedTags -- Write the main module. writeFile' (basePath <.> "hs") $ removeTrailingNewlines $ unlines [ DO_NOT_EDIT , "{-# LANGUAGE OverloadedStrings #-}" , "-- | This module exports HTML combinators used to create documents." , "--" , exportList modulName $ "module Haste.Markup.Html" : "docType" : "docTypeHtml" : map (sanitize . fst) sortedTags , DO_NOT_EDIT , "import Prelude ((>>), (.))" , "" , "import Haste.Markup" , "import Haste.Markup.Internal" , "import Haste.Markup.Html" , "" , makeDocType $ docType htmlVariant , makeDocTypeHtml $ docType htmlVariant , unlines appliedTags ] let sortedAttributes = sort attributes' -- Write the attribute module. writeFile' (basePath </> "Attributes.hs") $ removeTrailingNewlines $ unlines [ DO_NOT_EDIT , "-- | This module exports combinators that provide you with the" , "-- ability to set attributes on HTML elements." , "--" , "{-# LANGUAGE OverloadedStrings #-}" , exportList attributeModuleName $ map sanitize sortedAttributes , DO_NOT_EDIT , "import Prelude ()" , "" , "import Haste.Markup.Internal (Attribute, AttributeValue, attribute)" , "" , unlines (map makeAttribute sortedAttributes) ] where basePath = "src" </> "Haste" </> "Markup" </> foldl1 (</>) version' modulName = getModuleName htmlVariant attributeModuleName = getAttributeModuleName htmlVariant attributes' = attributes htmlVariant parents' = parents htmlVariant leafs' = leafs htmlVariant version' = version htmlVariant removeTrailingNewlines = reverse . drop 2 . reverse writeFile' file content = do putStrLn ("Generating " ++ file) writeFile file content -- | Create a string, consisting of @x@ spaces, where @x@ is the length of the -- argument. -- spaces :: String -> String spaces = flip replicate ' ' . length -- | Join blocks of code with a newline in between. -- unblocks :: [String] -> String unblocks = unlines . intersperse "\n" -- | A warning to not edit the generated code. -- doNotEdit :: FilePath -> Int -> String doNotEdit fileName lineNumber = init $ unlines [ "-- WARNING: The next block of code was automatically generated by" , "-- " ++ fileName ++ ":" ++ show lineNumber , "--" ] -- | Generate an export list for a Haskell module. -- exportList :: String -- ^ Module name. -> [String] -- ^ List of functions. -> String -- ^ Resulting string. exportList _ [] = error "exportList without functions." exportList name (f:functions) = unlines $ [ "module " ++ name , " ( " ++ f ] ++ map (" , " ++) functions ++ [ " ) where"] -- | Generate a function for a doctype. -- makeDocType :: [String] -> String makeDocType lines' = unlines [ DO_NOT_EDIT , "-- | Combinator for the document type. This should be placed at the top" , "-- of every HTML page." , "--" , "-- Example:" , "--" , "-- > docType" , "--" , "-- Result:" , "--" , unlines (map ("-- > " ++) lines') ++ "--" , "docType :: Html -- ^ The document type HTML." , "docType = preEscapedText " ++ show (unlines lines') , "{-# INLINE docType #-}" ] -- | Generate a function for the HTML tag (including the doctype). -- makeDocTypeHtml :: [String] -- ^ The doctype. -> String -- ^ Resulting combinator function. makeDocTypeHtml lines' = unlines [ DO_NOT_EDIT , "-- | Combinator for the @\\<html>@ element. This combinator will also" , "-- insert the correct doctype." , "--" , "-- Example:" , "--" , "-- > docTypeHtml $ span $ toHtml \"foo\"" , "--" , "-- Result:" , "--" , unlines (map ("-- > " ++) lines') ++ "-- > <html><span>foo</span></html>" , "--" , "docTypeHtml :: Html -- ^ Inner HTML." , " -> Html -- ^ Resulting HTML." , "docTypeHtml inner = docType >> html inner" , "{-# INLINE docTypeHtml #-}" ] -- | Generate a function for an HTML tag that can be a parent. -- makeParent :: String -> String makeParent tag = unlines [ DO_NOT_EDIT , "-- | Combinator for the @\\<" ++ tag ++ ">@ element." , "--" , "-- Example:" , "--" , "-- > " ++ function ++ " $ span $ toHtml \"foo\"" , "--" , "-- Result:" , "--" , "-- > <" ++ tag ++ "><span>foo</span></" ++ tag ++ ">" , "--" , function ++ " :: Html -- ^ Inner HTML." , spaces function ++ " -> Html -- ^ Resulting HTML." , function ++ " = Parent \"" ++ tag ++ "\" \"<" ++ tag ++ "\" \"</" ++ tag ++ ">\"" ++ modifier , "{-# INLINE " ++ function ++ " #-}" ] where function = sanitize tag modifier = if tag `elem` ["style", "script"] then " . external" else "" -- | Generate a function for an HTML tag that must be a leaf. -- makeLeaf :: Bool -- ^ Make leaf tags self-closing -> String -- ^ Tag for the combinator -> String -- ^ Combinator code makeLeaf closing tag = unlines [ DO_NOT_EDIT , "-- | Combinator for the @\\<" ++ tag ++ " />@ element." , "--" , "-- Example:" , "--" , "-- > " ++ function , "--" , "-- Result:" , "--" , "-- > <" ++ tag ++ " />" , "--" , function ++ " :: Html -- ^ Resulting HTML." , function ++ " = Leaf \"" ++ tag ++ "\" \"<" ++ tag ++ "\" " ++ "\"" ++ (if closing then " /" else "") ++ ">\"" , "{-# INLINE " ++ function ++ " #-}" ] where function = sanitize tag -- | Generate a function for an HTML attribute. -- makeAttribute :: String -> String makeAttribute name = unlines [ DO_NOT_EDIT , "-- | Combinator for the @" ++ name ++ "@ attribute." , "--" , "-- Example:" , "--" , "-- > div ! " ++ function ++ " \"bar\" $ \"Hello.\"" , "--" , "-- Result:" , "--" , "-- > <div " ++ name ++ "=\"bar\">Hello.</div>" , "--" , function ++ " :: AttributeValue -- ^ Attribute value." , spaces function ++ " -> Attribute -- ^ Resulting attribute." , function ++ " = attribute \"" ++ name ++ "\" \" " ++ name ++ "=\\\"\"" , "{-# INLINE " ++ function ++ " #-}" ] where function = sanitize name -- | HTML 4.01 Strict. -- A good reference can be found here: http://www.w3schools.com/tags/default.asp -- html4Strict :: HtmlVariant html4Strict = HtmlVariant { version = ["Html4", "Strict"] , docType = [ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"" , " \"http://www.w3.org/TR/html4/strict.dtd\">" ] , parents = [ "a", "abbr", "acronym", "address", "b", "bdo", "big", "blockquote" , "body" , "button", "caption", "cite", "code", "colgroup", "dd", "del" , "dfn", "div" , "dl", "dt", "em", "fieldset", "form", "h1", "h2", "h3" , "h4", "h5", "h6", "head", "html", "i", "ins" , "kbd", "label" , "legend", "li", "map", "noscript", "object", "ol", "optgroup" , "option", "p", "pre", "q", "samp", "script", "select", "small" , "span", "strong", "style", "sub", "sup", "table", "tbody", "td" , "textarea", "tfoot", "th", "thead", "title", "tr", "tt", "ul", "var" ] , leafs = [ "area", "br", "col", "hr", "link", "img", "input", "meta", "param" ] , attributes = [ "abbr", "accept", "accesskey", "action", "align", "alt", "archive" , "axis", "border", "cellpadding", "cellspacing", "char", "charoff" , "charset", "checked", "cite", "class", "classid", "codebase" , "codetype", "cols", "colspan", "content", "coords", "data", "datetime" , "declare", "defer", "dir", "disabled", "enctype", "for", "frame" , "headers", "height", "href", "hreflang", "http-equiv", "id", "label" , "lang", "maxlength", "media", "method", "multiple", "name", "nohref" , "onabort", "onblur", "onchange", "onclick", "ondblclick", "onfocus" , "onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown" , "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onreset" , "onselect", "onsubmit", "onunload", "profile", "readonly", "rel" , "rev", "rows", "rowspan", "rules", "scheme", "scope", "selected" , "shape", "size", "span", "src", "standby", "style", "summary" , "tabindex", "title", "type", "usemap", "valign", "value", "valuetype" , "width" ] , selfClosing = False } -- | HTML 4.0 Transitional -- html4Transitional :: HtmlVariant html4Transitional = HtmlVariant { version = ["Html4", "Transitional"] , docType = [ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"" , " \"http://www.w3.org/TR/html4/loose.dtd\">" ] , parents = parents html4Strict ++ [ "applet", "center", "dir", "font", "iframe", "isindex", "menu" , "noframes", "s", "u" ] , leafs = leafs html4Strict ++ ["basefont"] , attributes = attributes html4Strict ++ [ "background", "bgcolor", "clear", "compact", "hspace", "language" , "noshade", "nowrap", "start", "target", "vspace" ] , selfClosing = False } -- | HTML 4.0 FrameSet -- html4FrameSet :: HtmlVariant html4FrameSet = HtmlVariant { version = ["Html4", "FrameSet"] , docType = [ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 FrameSet//EN\"" , " \"http://www.w3.org/TR/html4/frameset.dtd\">" ] , parents = parents html4Transitional ++ ["frameset"] , leafs = leafs html4Transitional ++ ["frame"] , attributes = attributes html4Transitional ++ [ "frameborder", "scrolling" ] , selfClosing = False } -- | XHTML 1.0 Strict -- xhtml1Strict :: HtmlVariant xhtml1Strict = HtmlVariant { version = ["XHtml1", "Strict"] , docType = [ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" , " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ] , parents = parents html4Strict , leafs = leafs html4Strict , attributes = attributes html4Strict , selfClosing = True } -- | XHTML 1.0 Transitional -- xhtml1Transitional :: HtmlVariant xhtml1Transitional = HtmlVariant { version = ["XHtml1", "Transitional"] , docType = [ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"" , " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" ] , parents = parents html4Transitional , leafs = leafs html4Transitional , attributes = attributes html4Transitional , selfClosing = True } -- | XHTML 1.0 FrameSet -- xhtml1FrameSet :: HtmlVariant xhtml1FrameSet = HtmlVariant { version = ["XHtml1", "FrameSet"] , docType = [ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 FrameSet//EN\"" , " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">" ] , parents = parents html4FrameSet , leafs = leafs html4FrameSet , attributes = attributes html4FrameSet , selfClosing = True } -- | HTML 5.0 -- A good reference can be found here: -- http://www.w3schools.com/html5/html5_reference.asp -- html5 :: HtmlVariant html5 = HtmlVariant { version = ["Html5"] , docType = ["<!DOCTYPE HTML>"] , parents = [ "a", "abbr", "address", "article", "aside", "audio", "b" , "bdo", "blockquote", "body", "button", "canvas", "caption", "cite" , "code", "colgroup", "command", "datalist", "dd", "del", "details" , "dfn", "div", "dl", "dt", "em", "fieldset", "figcaption", "figure" , "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header" , "hgroup", "html", "i", "iframe", "ins", "kbd", "label" , "legend", "li", "map", "mark", "menu", "meter", "nav", "noscript" , "object", "ol", "optgroup", "option", "output", "p", "pre", "progress" , "q", "rp", "rt", "ruby", "samp", "script", "section", "select" , "small", "span", "strong", "style", "sub", "summary", "sup" , "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time" , "title", "tr", "ul", "var", "video" ] , leafs = -- http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#void-elements [ "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen" , "link", "menuitem", "meta", "param", "source", "track", "wbr" ] , attributes = [ "accept", "accept-charset", "accesskey", "action", "alt", "async" , "autocomplete", "autofocus", "autoplay", "challenge", "charset" , "checked", "cite", "class", "cols", "colspan", "content" , "contenteditable", "contextmenu", "controls", "coords", "data" , "datetime", "defer", "dir", "disabled", "draggable", "enctype", "for" , "form", "formaction", "formenctype", "formmethod", "formnovalidate" , "formtarget", "headers", "height", "hidden", "high", "href" , "hreflang", "http-equiv", "icon", "id", "ismap", "item", "itemprop" , "keytype", "label", "lang", "list", "loop", "low", "manifest", "max" , "maxlength", "media", "method", "min", "multiple", "name" , "novalidate", "onbeforeonload", "onbeforeprint", "onblur", "oncanplay" , "oncanplaythrough", "onchange", "oncontextmenu", "onclick" , "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave" , "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied" , "onended", "onerror", "onfocus", "onformchange", "onforminput" , "onhaschange", "oninput", "oninvalid", "onkeydown", "onkeyup" , "onload", "onloadeddata", "onloadedmetadata", "onloadstart" , "onmessage", "onmousedown", "onmousemove", "onmouseout", "onmouseover" , "onmouseup", "onmousewheel", "ononline", "onpagehide", "onpageshow" , "onpause", "onplay", "onplaying", "onprogress", "onpropstate" , "onratechange", "onreadystatechange", "onredo", "onresize", "onscroll" , "onseeked", "onseeking", "onselect", "onstalled", "onstorage" , "onsubmit", "onsuspend", "ontimeupdate", "onundo", "onunload" , "onvolumechange", "onwaiting", "open", "optimum", "pattern", "ping" , "placeholder", "preload", "pubdate", "radiogroup", "readonly", "rel" , "required", "reversed", "rows", "rowspan", "sandbox", "scope" , "scoped", "seamless", "selected", "shape", "size", "sizes", "span" , "spellcheck", "src", "srcdoc", "start", "step", "style", "subject" , "summary", "tabindex", "target", "title", "type", "usemap", "value" , "width", "wrap", "xmlns" ] , selfClosing = False } -- | XHTML 5.0 -- xhtml5 :: HtmlVariant xhtml5 = HtmlVariant { version = ["XHtml5"] , docType = ["<!DOCTYPE HTML>"] , parents = parents html5 , leafs = leafs html5 , attributes = attributes html5 , selfClosing = True } -- | A map of HTML variants, per version, lowercase. -- htmlVariants :: Map String HtmlVariant htmlVariants = M.fromList $ map (show &&& id) [ html4Strict , html4Transitional , html4FrameSet , xhtml1Strict , xhtml1Transitional , xhtml1FrameSet , html5 , xhtml5 ] main :: IO () main = mapM_ (writeHtmlVariant . snd) $ M.toList htmlVariants
ajnsit/haste-markup
src/Util/GenerateHtmlCombinators.hs
mit
17,568
0
16
4,531
3,763
2,299
1,464
356
2
{-# LANGUAGE DeriveGeneric, TemplateHaskell #-} module Ffs.Jira ( Issue(..) , issueKey , issueURI , issueFields , nullIssue , SearchResults(..) , issuesStartAt , issuesMaxResults , issuesTotal , issues , User(..) , userName , userDisplayName , userUrl , WorkLogItems(..) , logStartsAt , logMaxResults , logTotal , logItems , WorkLogItem(..) , logUrl , logComment , logWorkStarted , logAuthor , logTimeSpent , FieldDescription(..) , FieldType(..) , fldName , fldId , fldType , fldClauseNames , search , getIssue , getWorkLog , getFields ) where import Control.Exception import Control.Lens import Data.Aeson as Aeson import Data.Aeson.Types import qualified Data.ByteString as BS import Data.HashMap.Lazy as HashMap import Data.Map.Strict as Map import Data.Text as Text import Data.Time.Calendar import Data.Time.Clock import Data.Text.Encoding import Data.Time.Format import Data.Time.LocalTime import qualified Data.URLEncoded as URLEncoded import Network.URI import Network.Wreq as Wreq import System.Log.Logger as Log import Text.Printf import Ffs.Time info = Log.infoM "jira" debug = Log.debugM "jira" -- | An issue reference returned as a search result data Issue = Issue { _issueKey :: Text , _issueURI :: Text , _issueFields :: Aeson.Object } deriving (Show, Eq) makeLenses ''Issue nullIssue = Issue { _issueKey = "" , _issueURI = "" , _issueFields = HashMap.empty } instance FromJSON Issue where parseJSON = withObject "Search Result" $ \obj -> do key <- obj .: "key" uri <- obj .: "self" fields <- case HashMap.lookup "fields" obj of Nothing -> fail "key fields not present" Just val -> withObject "fields" return val return $ Issue key uri fields where repack :: Aeson.Object -> Parser (Map.Map Text Aeson.Value) repack obj = return $ HashMap.foldlWithKey' (\a k v -> Map.insert k v a) Map.empty obj -- | Search results from a JQL query returning a list of issues data SearchResults = SearchResults { _issuesStartAt :: Int , _issuesMaxResults :: Int , _issuesTotal :: Int , _issues :: [Issue] } deriving (Show, Eq) makeLenses ''SearchResults instance FromJSON SearchResults where parseJSON = withObject "Search results" $ \obj -> SearchResults <$> obj .: "startAt" <*> obj .: "maxResults" <*> obj .: "total" <*> obj .: "issues" -- | A brief description of a JIRA user account data User = User { _userName :: Text , _userDisplayName :: Text , _userUrl :: Text } deriving (Show, Eq) makeLenses ''User instance FromJSON User where parseJSON = withObject "User" $ \obj -> User <$> obj .: "name" <*> obj .: "displayName" <*> obj .: "self" instance Eq ZonedTime where (==) l r = if zonedTimeZone l == zonedTimeZone r then zonedTimeToLocalTime l == zonedTimeToLocalTime r else zonedTimeToUTC l == zonedTimeToUTC r -- | A single work log entry data WorkLogItem = WorkLogItem { _logUrl :: Text , _logComment :: Text , _logWorkStarted :: ZonedTime , _logAuthor :: User , _logTimeSpent :: Int } deriving (Show, Eq) makeLenses ''WorkLogItem instance FromJSON WorkLogItem where parseJSON = withObject "Work log item" $ \obj -> WorkLogItem <$> obj .: "self" <*> obj .: "comment" <*> obj .: "started" <*> obj .: "author" <*> obj .: "timeSpentSeconds" -- | A collection of work log items. We assume that they all relate to the -- same issue. data WorkLogItems = WorkLogItems { _logStartsAt :: Int , _logMaxResults :: Int , _logTotal :: Int , _logItems :: [WorkLogItem] } deriving (Show, Eq) makeLenses ''WorkLogItems instance FromJSON WorkLogItems where parseJSON = withObject "Work Logs" $ \obj -> WorkLogItems <$> obj .: "startAt" <*> obj .: "maxResults" <*> obj .: "total" <*> obj .: "worklogs" -- | URL escape a string escape :: String -> String escape = escapeURIString isAllowedInURI search :: Wreq.Options -> URI -> Text -> IO [Issue] search options host jql = do debug $ printf "Fetching %s..." url resp <- Wreq.getWith options url >>= asJSON return $ resp ^. responseBody ^. issues where url = uriToString id completeUrl "" completeUrl = host { uriPath = "/rest/api/2/search" , uriQuery = printf "?jql=%s" (escape $ Text.unpack jql) } getWorkLog :: Wreq.Options -> URI -> Text -> IO [WorkLogItem] getWorkLog options host key = do debug $ printf "Fetching worklog for issue %s..." key response <- Wreq.getWith options url >>= asJSON return $ response ^. responseBody ^. logItems where url = uriToString id absoluteUrl "" absoluteUrl = host { uriPath = printf "/rest/api/2/issue/%s/worklog" key } data FieldType = StringField | NumberField | ArrayField | OptionField | DateTimeField | AnyField | UnknownFieldType | OtherFieldType Text deriving (Show, Eq) instance FromJSON FieldType where parseJSON = withText "field type" $ \t -> let ft = case t of "string" -> StringField "number" -> NumberField "array" -> ArrayField "option" -> OptionField "any" -> AnyField _ -> OtherFieldType t in return ft data FieldDescription = FieldDescription { _fldId :: Text , _fldName :: Text , _fldClauseNames :: [Text] , _fldType :: FieldType } deriving (Show, Eq) makeLenses ''FieldDescription instance FromJSON FieldDescription where parseJSON = withObject "field description" $ \obj -> do fieldId <- obj .: "id" fieldName <- obj .: "name" clauseNames <- obj .: "clauseNames" schema <- obj .:? "schema" fieldType <- maybe (return UnknownFieldType) (.: "type") schema return $ FieldDescription fieldId fieldName clauseNames fieldType getFields :: Wreq.Options -> URI -> IO [FieldDescription] getFields options host = do debug $ printf "Fetching field descriptors from %s..." url response <- Wreq.getWith options url >>= asJSON return $ response ^. responseBody where url = uriToString id absoluteUrl "" absoluteUrl = host { uriPath = "/rest/api/2/field" } getIssue :: Wreq.Options -> URI -> Text -> IO Issue getIssue options host key = do debug $ printf "Fetching issue %s..." key response <- Wreq.getWith options url >>= asJSON return $ response ^. responseBody where url = uriToString id absoluteUrl "" absoluteUrl = host { uriPath = printf "/rest/api/2/issue/%s" key }
tcsc/ffs
src/Ffs/Jira.hs
mit
6,733
0
17
1,704
1,798
975
823
205
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Network.GDAX.Core ( Endpoint , AccessKey, SecretKey, Passphrase , Path, Method , Gdax , HasGdax (..) , HasNetworkManager (..) , HasRestEndpoint (..) , HasSocketEndpoint (..) , HasAccessKey (..) , HasSecretKey (..) , HasPassphrase (..) , mkLiveGdax, mkSandboxGdax , mkLiveUnsignedGdax, mkSandboxUnsignedGdax , gdaxGet , gdaxGetWith , gdaxSignedGet , gdaxSignedPost , gdaxSignedDelete ) where import Control.Lens import Control.Monad.Catch import Control.Monad.IO.Class import Crypto.Hash import Data.Aeson (FromJSON (..), ToJSON (..)) import qualified Data.Aeson as Aeson import Data.Byteable import Data.ByteString (ByteString) import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Char8 as CBS import qualified Data.ByteString.Lazy.Char8 as CLBS import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Time import Data.Time.Clock.POSIX import Network.GDAX.Exceptions import Network.HTTP.Client (Manager) import Network.HTTP.Client.TLS (newTlsManager) import Network.Wreq import Text.Printf type Endpoint = String type AccessKey = ByteString type SecretKey = ByteString type Passphrase = ByteString type Path = String type Method = ByteString type Params = [(Text, Text)] liveRest :: Endpoint liveRest = "https://api.gdax.com" sandboxRest :: Endpoint sandboxRest = "https://api-public.sandbox.gdax.com" liveSocket :: Endpoint liveSocket = "ws-feed.gdax.com" sandboxSocket :: Endpoint sandboxSocket = "ws-feed-public.sandbox.gdax.com" class HasNetworkManager a where networkManager :: Lens' a Manager class HasRestEndpoint a where restEndpoint :: Lens' a Endpoint class HasSocketEndpoint a where socketEndpoint :: Lens' a Endpoint class HasAccessKey a where accessKey :: Lens' a AccessKey class HasSecretKey a where secretKey :: Lens' a SecretKey class HasPassphrase a where passphrase :: Lens' a Passphrase data Gdax = Gdax { _gdaxNetworkManager :: Manager , _gdaxRestEndpoint :: Endpoint , _gdaxSocketEndpoint :: Endpoint , _gdaxAccessKey :: AccessKey , _gdaxSecretKey :: SecretKey , _gdaxPassphrase :: Passphrase } $(makeClassy ''Gdax) instance HasNetworkManager Gdax where networkManager = gdaxNetworkManager instance HasRestEndpoint Gdax where restEndpoint = gdaxRestEndpoint instance HasSocketEndpoint Gdax where socketEndpoint = gdaxSocketEndpoint instance HasAccessKey Gdax where accessKey = gdaxAccessKey instance HasSecretKey Gdax where secretKey = gdaxSecretKey instance HasPassphrase Gdax where passphrase = gdaxPassphrase mkLiveGdax :: (MonadIO m) => AccessKey -> SecretKey -> Passphrase -> m Gdax mkLiveGdax a s p = do m <- newTlsManager return $ Gdax m liveRest liveSocket a s p mkSandboxGdax :: (MonadIO m) => AccessKey -> SecretKey -> Passphrase -> m Gdax mkSandboxGdax a s p = do m <- newTlsManager return $ Gdax m sandboxRest sandboxSocket a s p mkLiveUnsignedGdax :: (MonadIO m) => m Gdax mkLiveUnsignedGdax = do m <- newTlsManager return $ Gdax m liveRest liveSocket "" "" "" mkSandboxUnsignedGdax :: (MonadIO m) => m Gdax mkSandboxUnsignedGdax = do m <- newTlsManager return $ Gdax m sandboxRest sandboxSocket "" "" "" gdaxGet :: (MonadIO m, MonadThrow m, FromJSON b) => Gdax -> Path -> m b {-# INLINE gdaxGet #-} gdaxGet g path = do res <- liftIO $ getWith opts (g ^. restEndpoint <> path) decodeResult res where opts = defaults & manager .~ Right (g ^. networkManager) gdaxGetWith :: (MonadIO m, MonadThrow m, FromJSON b) => Gdax -> Path -> Options -> m b {-# INLINE gdaxGetWith #-} gdaxGetWith g path opts' = do res <- liftIO $ getWith opts (g ^. restEndpoint <> path) decodeResult res where opts = opts' & manager .~ Right (g ^. networkManager) gdaxSignedGet :: (MonadIO m, MonadThrow m, FromJSON b) => Gdax -> Path -> Params -> m b {-# INLINE gdaxSignedGet #-} gdaxSignedGet g path par = do signedOpts <- signOptions g "GET" path Nothing opts res <- liftIO $ getWith signedOpts (g ^. restEndpoint <> path) decodeResult res where opts = defaults & manager .~ Right (g ^. networkManager) & params .~ par gdaxSignedPost :: (MonadIO m, MonadThrow m, ToJSON a, FromJSON b) => Gdax -> Path -> Params -> a -> m b {-# INLINE gdaxSignedPost #-} gdaxSignedPost g path par body = do signedOpts <- signOptions g "POST" path (Just bodyBS) opts res <- liftIO $ postWith signedOpts (g ^. restEndpoint <> path) bodyBS decodeResult res where opts = defaults & header "Content-Type" .~ [ "application/json" ] & manager .~ Right (g ^. networkManager) & params .~ par bodyBS = CLBS.toStrict $ Aeson.encode body gdaxSignedDelete :: (MonadIO m, MonadThrow m, FromJSON b) => Gdax -> Path -> Params -> m b {-# INLINE gdaxSignedDelete #-} gdaxSignedDelete g path par = do signedOpts <- signOptions g "DELETE" path Nothing opts res <- liftIO $ deleteWith signedOpts (g ^. restEndpoint <> path) decodeResult res where opts = defaults & manager .~ Right (g ^. networkManager) & params .~ par decodeResult :: (MonadThrow m, FromJSON a) => Response CLBS.ByteString -> m a {-# INLINE decodeResult #-} decodeResult res = case Aeson.eitherDecode' (res ^. responseBody) of Left err -> throwM $ MalformedGdaxResponse (T.pack err) Right val -> return val signOptions :: (MonadIO m) => Gdax -> Method -> Path -> (Maybe ByteString) -> Options -> m Options {-# INLINE signOptions #-} signOptions g method path mBody opts = do time <- liftIO $ getCurrentTime let timestamp = CBS.pack $ printf "%.0f" (realToFrac (utcTimeToPOSIXSeconds time) :: Double) sigString = timestamp <> method <> (CBS.pack path) <> maybe "" id mBody sig = Base64.encode $ toBytes (hmac (g ^. secretKey) sigString :: HMAC SHA256) return $ opts & header "CB-ACCESS-KEY" .~ [ (g ^. accessKey) ] & header "CB-ACCESS-SIGN" .~ [ sig ] & header "CB-ACCESS-TIMESTAMP" .~ [ timestamp ] & header "CB-ACCESS-PASSPHRASE" .~ [ (g ^. passphrase) ]
AndrewRademacher/gdax
lib/Network/GDAX/Core.hs
mit
6,667
0
16
1,668
1,877
1,001
876
157
2
module Phone (number) where import Data.Char (isDigit) number :: String -> Maybe String number xs | isValid cleanNumber = Just cleanNumber | otherwise = Nothing where cleanNumber = (stripCountryCode . filter isDigit) xs stripCountryCode :: String -> String stripCountryCode xs | length xs == 11 && head xs == '1' = tail xs | otherwise = xs isValid :: String -> Bool isValid phone = validLength && validArea && validExchange where validLength = length phone == 10 validArea = validSubCode $ head phone validExchange = validSubCode $ phone !! 3 validSubCode = (`elem` ['2'..'9'])
enolive/exercism
haskell/phone-number/src/Phone.hs
mit
613
0
11
129
213
108
105
17
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} ------------------------------------------- -- | -- Module : Web.Stripe.Event -- Copyright : (c) David Johnson, 2014 -- Maintainer : [email protected] -- Stability : experimental -- Portability : POSIX -- -- < https:/\/\stripe.com/docs/api#events > -- -- @ -- {-\# LANGUAGE OverloadedStrings \#-} -- import Web.Stripe -- import Web.Stripe.Event -- -- main :: IO () -- main = do -- let config = StripeConfig (StripeKey "secret_key") -- result <- stripe config $ getEvents -- case result of -- Right events -> print events -- Left stripeError -> print stripeError -- @ module Web.Stripe.Event ( -- * API GetEvent , getEvent , GetEvents , getEvents -- * Types , Created (..) , EndingBefore (..) , EventId (..) , Event (..) , EventData (..) , EventType (..) , StripeList (..) , Limit (..) , StartingAfter (..) ) where import Web.Stripe.StripeRequest (Method (GET), StripeHasParam, StripeRequest (..), StripeReturn, mkStripeRequest) import Web.Stripe.Util ((</>)) import Web.Stripe.Types (Created(..), Event (..), EventId (..), Limit, EventData(..), EventType(..), StripeList (..), Limit(..), StartingAfter(..), EndingBefore(..)) ------------------------------------------------------------------------------ -- | `Event` to retrieve by `EventId` getEvent :: EventId -- ^ The ID of the Event to retrieve -> StripeRequest GetEvent getEvent (EventId eventid) = request where request = mkStripeRequest GET url params url = "events" </> eventid params = [] data GetEvent type instance StripeReturn GetEvent = Event ------------------------------------------------------------------------------ -- | `StripeList` of `Event`s to retrieve getEvents :: StripeRequest GetEvents getEvents = request where request = mkStripeRequest GET url params url = "events" params = [] data GetEvents type instance StripeReturn GetEvents = (StripeList Event) instance StripeHasParam GetEvents Created instance StripeHasParam GetEvents (EndingBefore EventId) instance StripeHasParam GetEvents Limit instance StripeHasParam GetEvents (StartingAfter EventId) -- instance StripeHasParam GetEvents EventType -- FIXME
dmjio/stripe
stripe-core/src/Web/Stripe/Event.hs
mit
2,849
0
7
911
412
267
145
-1
-1
module Graphics.Pylon.Binding.Pango.Cairo where import Graphics.Pylon.Foreign.Pango.Cairo import Graphics.Pylon.Foreign.Pango.Layout import Graphics.Pylon.Foreign.Pango.Font import Graphics.Pylon.Foreign.GObject import Graphics.Pylon.Foreign.Cairo.Cairo import Foreign.ForeignPtr fontMapGetDefault :: IO FontMap fontMapGetDefault = fmap FontMap $ pango_cairo_font_map_get_default >>= newForeignPtr_ createLayout :: Cairo s -> IO Layout createLayout (Cairo c) = fmap Layout $ pango_cairo_create_layout c >>= newForeignPtr p'g_object_unref updateLayout :: Cairo s -> Layout -> IO () updateLayout (Cairo c) (Layout f'l) = withForeignPtr f'l $ \lay -> pango_cairo_update_layout c lay showLayout :: Cairo s -> Layout -> IO () showLayout (Cairo c) (Layout f'l) = withForeignPtr f'l $ \lay -> pango_cairo_show_layout c lay
philopon/pylon
Graphics/Pylon/Binding/Pango/Cairo.hs
mit
841
0
8
117
243
130
113
20
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} module WykopUtils where import WykopTypes import Control.Monad (liftM) import Data.Aeson (decode, FromJSON) import Data.Digest.Pure.MD5 (md5) import Network.HTTP import qualified Data.ByteString.Lazy.Internal as BS import qualified Data.ByteString.Lazy.Char8 as C import qualified Data.List as L urlBase :: String urlBase = "http://a.wykop.pl/" signURL :: Keys -> URL -> PostData -> String signURL (Keys _ s) u p = show $ md5 fullURL where fullURL = BS.packChars $ s ++ u ++ postValues sortedPost sortedPost = L.sort p postValues d = L.intercalate "," $ map snd d makeURL :: Keys -> String -> GetData -> String makeURL (Keys a _) resource g = urlBase ++ resource ++ "/appkey," ++ a ++ "," ++ getParams where getParams = L.intercalate "," $ map deTuple g deTuple (a, b) = a ++ "," ++ b makeRequest :: Keys -> PostData -> GetData -> String -> Request_String makeRequest k p g res = request where request = insertHeader apisignHeader md5sum req apisignHeader = HdrCustom "apisign" md5sum = signURL k url p url = makeURL k res g req = case p of [] -> getRequest url _ -> postRequestWithBody url contentType $ makeQuery p contentType = "application/x-www-form-urlencoded" makeQuery p = L.intercalate "&" $ map eq p eq (a, b) = a ++ "=" ++ b getRaw :: Keys -> PostData -> GetData -> String -> IO (C.ByteString) getRaw k p g resource = do resp <- simpleHTTP $ makeRequest k p g resource str <- getResponseBody resp return $ C.pack str get :: (FromJSON a) => Keys -> PostData -> GetData -> String -> IO (Maybe a) get keys p g res = do raw <- getRaw keys p g res return $ decode raw toGet :: Userkey -> GetData toGet u = [("userkey", u)] mToGet :: Maybe Userkey -> GetData mToGet = \case Just x -> toGet x _ -> [] mPageToGet :: Maybe Int -> GetData mPageToGet = \case Just x -> [("page", show x)] _ -> []
mikusp/hwykop
WykopUtils.hs
mit
2,063
0
12
533
732
381
351
53
2
{-# LANGUAGE OverloadedStrings #-} import Control.Concurrent import Control.Monad import Common main :: IO () main = do void . forkIO $ runHttpsClient httpsPort putStrLn "HTTPS client thread started." runHttpServer httpPort
erikd-ambiata/test-warp-wai
test-warp-wai.hs
mit
239
0
8
45
56
27
29
9
1
-- Paths in the Grid -- http://www.codewars.com/kata/56a127b14d9687bba200004d module Kata.GridPath where numberOfRoutes :: Int -> Int -> Integer numberOfRoutes m n = product [succ b .. a + b] `div` product [1 .. a] where a = fromIntegral (min m n) b = fromIntegral (max m n)
gafiatulin/codewars
src/6 kyu/GridPath.hs
mit
291
0
9
62
96
52
44
5
1
-- | -- Module : Ez.System.Elf -- Copyright : (c) Eike Ziller -- License : MIT -- -- Stability : experimental -- Portability : non-portable (ELF - only) -- -- Running @objdump@ on files and interpreting its output. module Ez.System.Elf (readRpaths) where import Ez.System.Internal import System.Process import Text.Parsec import Text.Parsec.String (Parser) -- | Runs @objdump -p@ on the given file path and returns its output. objdumpOutput :: FilePath -> IO String objdumpOutput filePath = do (_, out, _) <- readProcessWithExitCode "objdump" ["-p", filePath] "" return out pPath :: Parser String pPath = many1 (notFollowedBy space >> noneOf [':']) pRpathLine :: Parser [String] pRpathLine = do spaces try (string "RPATH") <|> string "RUNPATH" spaces paths <- pPath `sepBy1` char ':' endOfLine return paths pRpaths :: Parser [String] pRpaths = do manyTill skipRestOfLine $ try (lookAhead pRpathLine) pRpathLine parseRpaths :: String -> Maybe [String] parseRpaths = eitherToMaybe . runParser pRpaths () "" -- | Takes a file path and returns either 'Nothing', -- if it fails to read any binary information (for example if the file is -- not readable, or not a binary), or 'Just' the list of successfully read RPATHs. readRpaths :: FilePath -> IO (Maybe [String]) readRpaths filePath = fmap parseRpaths (objdumpOutput filePath)
e4z9/binutils
Ez/System/Elf.hs
mit
1,435
0
10
314
316
167
149
27
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html module Stratosphere.Resources.ElasticLoadBalancingV2Listener where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.ElasticLoadBalancingV2ListenerCertificate import Stratosphere.ResourceProperties.ElasticLoadBalancingV2ListenerAction -- | Full data type definition for ElasticLoadBalancingV2Listener. See -- 'elasticLoadBalancingV2Listener' for a more convenient constructor. data ElasticLoadBalancingV2Listener = ElasticLoadBalancingV2Listener { _elasticLoadBalancingV2ListenerCertificates :: Maybe [ElasticLoadBalancingV2ListenerCertificate] , _elasticLoadBalancingV2ListenerDefaultActions :: [ElasticLoadBalancingV2ListenerAction] , _elasticLoadBalancingV2ListenerLoadBalancerArn :: Val Text , _elasticLoadBalancingV2ListenerPort :: Val Integer , _elasticLoadBalancingV2ListenerProtocol :: Val Text , _elasticLoadBalancingV2ListenerSslPolicy :: Maybe (Val Text) } deriving (Show, Eq) instance ToResourceProperties ElasticLoadBalancingV2Listener where toResourceProperties ElasticLoadBalancingV2Listener{..} = ResourceProperties { resourcePropertiesType = "AWS::ElasticLoadBalancingV2::Listener" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("Certificates",) . toJSON) _elasticLoadBalancingV2ListenerCertificates , (Just . ("DefaultActions",) . toJSON) _elasticLoadBalancingV2ListenerDefaultActions , (Just . ("LoadBalancerArn",) . toJSON) _elasticLoadBalancingV2ListenerLoadBalancerArn , (Just . ("Port",) . toJSON) _elasticLoadBalancingV2ListenerPort , (Just . ("Protocol",) . toJSON) _elasticLoadBalancingV2ListenerProtocol , fmap (("SslPolicy",) . toJSON) _elasticLoadBalancingV2ListenerSslPolicy ] } -- | Constructor for 'ElasticLoadBalancingV2Listener' containing required -- fields as arguments. elasticLoadBalancingV2Listener :: [ElasticLoadBalancingV2ListenerAction] -- ^ 'elbvlDefaultActions' -> Val Text -- ^ 'elbvlLoadBalancerArn' -> Val Integer -- ^ 'elbvlPort' -> Val Text -- ^ 'elbvlProtocol' -> ElasticLoadBalancingV2Listener elasticLoadBalancingV2Listener defaultActionsarg loadBalancerArnarg portarg protocolarg = ElasticLoadBalancingV2Listener { _elasticLoadBalancingV2ListenerCertificates = Nothing , _elasticLoadBalancingV2ListenerDefaultActions = defaultActionsarg , _elasticLoadBalancingV2ListenerLoadBalancerArn = loadBalancerArnarg , _elasticLoadBalancingV2ListenerPort = portarg , _elasticLoadBalancingV2ListenerProtocol = protocolarg , _elasticLoadBalancingV2ListenerSslPolicy = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-certificates elbvlCertificates :: Lens' ElasticLoadBalancingV2Listener (Maybe [ElasticLoadBalancingV2ListenerCertificate]) elbvlCertificates = lens _elasticLoadBalancingV2ListenerCertificates (\s a -> s { _elasticLoadBalancingV2ListenerCertificates = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-defaultactions elbvlDefaultActions :: Lens' ElasticLoadBalancingV2Listener [ElasticLoadBalancingV2ListenerAction] elbvlDefaultActions = lens _elasticLoadBalancingV2ListenerDefaultActions (\s a -> s { _elasticLoadBalancingV2ListenerDefaultActions = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-loadbalancerarn elbvlLoadBalancerArn :: Lens' ElasticLoadBalancingV2Listener (Val Text) elbvlLoadBalancerArn = lens _elasticLoadBalancingV2ListenerLoadBalancerArn (\s a -> s { _elasticLoadBalancingV2ListenerLoadBalancerArn = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-port elbvlPort :: Lens' ElasticLoadBalancingV2Listener (Val Integer) elbvlPort = lens _elasticLoadBalancingV2ListenerPort (\s a -> s { _elasticLoadBalancingV2ListenerPort = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-protocol elbvlProtocol :: Lens' ElasticLoadBalancingV2Listener (Val Text) elbvlProtocol = lens _elasticLoadBalancingV2ListenerProtocol (\s a -> s { _elasticLoadBalancingV2ListenerProtocol = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-sslpolicy elbvlSslPolicy :: Lens' ElasticLoadBalancingV2Listener (Maybe (Val Text)) elbvlSslPolicy = lens _elasticLoadBalancingV2ListenerSslPolicy (\s a -> s { _elasticLoadBalancingV2ListenerSslPolicy = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/ElasticLoadBalancingV2Listener.hs
mit
5,086
0
15
479
646
371
275
55
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html module Stratosphere.Resources.NeptuneDBCluster where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.Tag -- | Full data type definition for NeptuneDBCluster. See 'neptuneDBCluster' -- for a more convenient constructor. data NeptuneDBCluster = NeptuneDBCluster { _neptuneDBClusterAvailabilityZones :: Maybe (ValList Text) , _neptuneDBClusterBackupRetentionPeriod :: Maybe (Val Integer) , _neptuneDBClusterDBClusterIdentifier :: Maybe (Val Text) , _neptuneDBClusterDBClusterParameterGroupName :: Maybe (Val Text) , _neptuneDBClusterDBSubnetGroupName :: Maybe (Val Text) , _neptuneDBClusterIamAuthEnabled :: Maybe (Val Bool) , _neptuneDBClusterKmsKeyId :: Maybe (Val Text) , _neptuneDBClusterPort :: Maybe (Val Integer) , _neptuneDBClusterPreferredBackupWindow :: Maybe (Val Text) , _neptuneDBClusterPreferredMaintenanceWindow :: Maybe (Val Text) , _neptuneDBClusterSnapshotIdentifier :: Maybe (Val Text) , _neptuneDBClusterStorageEncrypted :: Maybe (Val Bool) , _neptuneDBClusterTags :: Maybe [Tag] , _neptuneDBClusterVpcSecurityGroupIds :: Maybe (ValList Text) } deriving (Show, Eq) instance ToResourceProperties NeptuneDBCluster where toResourceProperties NeptuneDBCluster{..} = ResourceProperties { resourcePropertiesType = "AWS::Neptune::DBCluster" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("AvailabilityZones",) . toJSON) _neptuneDBClusterAvailabilityZones , fmap (("BackupRetentionPeriod",) . toJSON) _neptuneDBClusterBackupRetentionPeriod , fmap (("DBClusterIdentifier",) . toJSON) _neptuneDBClusterDBClusterIdentifier , fmap (("DBClusterParameterGroupName",) . toJSON) _neptuneDBClusterDBClusterParameterGroupName , fmap (("DBSubnetGroupName",) . toJSON) _neptuneDBClusterDBSubnetGroupName , fmap (("IamAuthEnabled",) . toJSON) _neptuneDBClusterIamAuthEnabled , fmap (("KmsKeyId",) . toJSON) _neptuneDBClusterKmsKeyId , fmap (("Port",) . toJSON) _neptuneDBClusterPort , fmap (("PreferredBackupWindow",) . toJSON) _neptuneDBClusterPreferredBackupWindow , fmap (("PreferredMaintenanceWindow",) . toJSON) _neptuneDBClusterPreferredMaintenanceWindow , fmap (("SnapshotIdentifier",) . toJSON) _neptuneDBClusterSnapshotIdentifier , fmap (("StorageEncrypted",) . toJSON) _neptuneDBClusterStorageEncrypted , fmap (("Tags",) . toJSON) _neptuneDBClusterTags , fmap (("VpcSecurityGroupIds",) . toJSON) _neptuneDBClusterVpcSecurityGroupIds ] } -- | Constructor for 'NeptuneDBCluster' containing required fields as -- arguments. neptuneDBCluster :: NeptuneDBCluster neptuneDBCluster = NeptuneDBCluster { _neptuneDBClusterAvailabilityZones = Nothing , _neptuneDBClusterBackupRetentionPeriod = Nothing , _neptuneDBClusterDBClusterIdentifier = Nothing , _neptuneDBClusterDBClusterParameterGroupName = Nothing , _neptuneDBClusterDBSubnetGroupName = Nothing , _neptuneDBClusterIamAuthEnabled = Nothing , _neptuneDBClusterKmsKeyId = Nothing , _neptuneDBClusterPort = Nothing , _neptuneDBClusterPreferredBackupWindow = Nothing , _neptuneDBClusterPreferredMaintenanceWindow = Nothing , _neptuneDBClusterSnapshotIdentifier = Nothing , _neptuneDBClusterStorageEncrypted = Nothing , _neptuneDBClusterTags = Nothing , _neptuneDBClusterVpcSecurityGroupIds = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-availabilityzones ndbcAvailabilityZones :: Lens' NeptuneDBCluster (Maybe (ValList Text)) ndbcAvailabilityZones = lens _neptuneDBClusterAvailabilityZones (\s a -> s { _neptuneDBClusterAvailabilityZones = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-backupretentionperiod ndbcBackupRetentionPeriod :: Lens' NeptuneDBCluster (Maybe (Val Integer)) ndbcBackupRetentionPeriod = lens _neptuneDBClusterBackupRetentionPeriod (\s a -> s { _neptuneDBClusterBackupRetentionPeriod = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-dbclusteridentifier ndbcDBClusterIdentifier :: Lens' NeptuneDBCluster (Maybe (Val Text)) ndbcDBClusterIdentifier = lens _neptuneDBClusterDBClusterIdentifier (\s a -> s { _neptuneDBClusterDBClusterIdentifier = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-dbclusterparametergroupname ndbcDBClusterParameterGroupName :: Lens' NeptuneDBCluster (Maybe (Val Text)) ndbcDBClusterParameterGroupName = lens _neptuneDBClusterDBClusterParameterGroupName (\s a -> s { _neptuneDBClusterDBClusterParameterGroupName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-dbsubnetgroupname ndbcDBSubnetGroupName :: Lens' NeptuneDBCluster (Maybe (Val Text)) ndbcDBSubnetGroupName = lens _neptuneDBClusterDBSubnetGroupName (\s a -> s { _neptuneDBClusterDBSubnetGroupName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-iamauthenabled ndbcIamAuthEnabled :: Lens' NeptuneDBCluster (Maybe (Val Bool)) ndbcIamAuthEnabled = lens _neptuneDBClusterIamAuthEnabled (\s a -> s { _neptuneDBClusterIamAuthEnabled = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-kmskeyid ndbcKmsKeyId :: Lens' NeptuneDBCluster (Maybe (Val Text)) ndbcKmsKeyId = lens _neptuneDBClusterKmsKeyId (\s a -> s { _neptuneDBClusterKmsKeyId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-port ndbcPort :: Lens' NeptuneDBCluster (Maybe (Val Integer)) ndbcPort = lens _neptuneDBClusterPort (\s a -> s { _neptuneDBClusterPort = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-preferredbackupwindow ndbcPreferredBackupWindow :: Lens' NeptuneDBCluster (Maybe (Val Text)) ndbcPreferredBackupWindow = lens _neptuneDBClusterPreferredBackupWindow (\s a -> s { _neptuneDBClusterPreferredBackupWindow = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-preferredmaintenancewindow ndbcPreferredMaintenanceWindow :: Lens' NeptuneDBCluster (Maybe (Val Text)) ndbcPreferredMaintenanceWindow = lens _neptuneDBClusterPreferredMaintenanceWindow (\s a -> s { _neptuneDBClusterPreferredMaintenanceWindow = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-snapshotidentifier ndbcSnapshotIdentifier :: Lens' NeptuneDBCluster (Maybe (Val Text)) ndbcSnapshotIdentifier = lens _neptuneDBClusterSnapshotIdentifier (\s a -> s { _neptuneDBClusterSnapshotIdentifier = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-storageencrypted ndbcStorageEncrypted :: Lens' NeptuneDBCluster (Maybe (Val Bool)) ndbcStorageEncrypted = lens _neptuneDBClusterStorageEncrypted (\s a -> s { _neptuneDBClusterStorageEncrypted = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-tags ndbcTags :: Lens' NeptuneDBCluster (Maybe [Tag]) ndbcTags = lens _neptuneDBClusterTags (\s a -> s { _neptuneDBClusterTags = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbcluster.html#cfn-neptune-dbcluster-vpcsecuritygroupids ndbcVpcSecurityGroupIds :: Lens' NeptuneDBCluster (Maybe (ValList Text)) ndbcVpcSecurityGroupIds = lens _neptuneDBClusterVpcSecurityGroupIds (\s a -> s { _neptuneDBClusterVpcSecurityGroupIds = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/NeptuneDBCluster.hs
mit
8,246
0
14
865
1,370
774
596
90
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scriptbootstrapactionconfig.html module Stratosphere.ResourceProperties.EMRClusterScriptBootstrapActionConfig where import Stratosphere.ResourceImports -- | Full data type definition for EMRClusterScriptBootstrapActionConfig. See -- 'emrClusterScriptBootstrapActionConfig' for a more convenient -- constructor. data EMRClusterScriptBootstrapActionConfig = EMRClusterScriptBootstrapActionConfig { _eMRClusterScriptBootstrapActionConfigArgs :: Maybe (ValList Text) , _eMRClusterScriptBootstrapActionConfigPath :: Val Text } deriving (Show, Eq) instance ToJSON EMRClusterScriptBootstrapActionConfig where toJSON EMRClusterScriptBootstrapActionConfig{..} = object $ catMaybes [ fmap (("Args",) . toJSON) _eMRClusterScriptBootstrapActionConfigArgs , (Just . ("Path",) . toJSON) _eMRClusterScriptBootstrapActionConfigPath ] -- | Constructor for 'EMRClusterScriptBootstrapActionConfig' containing -- required fields as arguments. emrClusterScriptBootstrapActionConfig :: Val Text -- ^ 'emrcsbacPath' -> EMRClusterScriptBootstrapActionConfig emrClusterScriptBootstrapActionConfig patharg = EMRClusterScriptBootstrapActionConfig { _eMRClusterScriptBootstrapActionConfigArgs = Nothing , _eMRClusterScriptBootstrapActionConfigPath = patharg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scriptbootstrapactionconfig.html#cfn-elasticmapreduce-cluster-scriptbootstrapactionconfig-args emrcsbacArgs :: Lens' EMRClusterScriptBootstrapActionConfig (Maybe (ValList Text)) emrcsbacArgs = lens _eMRClusterScriptBootstrapActionConfigArgs (\s a -> s { _eMRClusterScriptBootstrapActionConfigArgs = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scriptbootstrapactionconfig.html#cfn-elasticmapreduce-cluster-scriptbootstrapactionconfig-path emrcsbacPath :: Lens' EMRClusterScriptBootstrapActionConfig (Val Text) emrcsbacPath = lens _eMRClusterScriptBootstrapActionConfigPath (\s a -> s { _eMRClusterScriptBootstrapActionConfigPath = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EMRClusterScriptBootstrapActionConfig.hs
mit
2,327
0
13
213
266
152
114
28
1
module AiVsAi.Util where import Prelude import Control.Monad.State --Take from the end of a list takeEnd :: Int -> [a] -> [a] takeEnd n l = reverse $ take n $ reverse l --Zip, but store the excess in a pair zipWithLeftover :: [a] -> [b] -> ([(a,b)], [a], [b]) zipWithLeftover la lb = (zipList, fst leftover, snd leftover) where zipList = zip la lb leftover | (length la) == (length lb) = ([], []) | (length la) > (length lb) = (takeEnd (length la - length lb) la, []) | otherwise = ([], takeEnd (length lb - length la) lb) toState :: a -> State a () toState a = do put a return () euclidDist :: (Int, Int) -> (Int, Int) -> Double euclidDist (xi,yi) (xxi,yyi) = sqrt $ (x-xx)^2 + (y - yy)^2 where x = fromIntegral xi y = fromIntegral yi xx = fromIntegral xxi yy = fromIntegral yyi concatPairs :: [(a,a)] -> [a] concatPairs [] = [] concatPairs ((a,b): t) = [a,b] ++ concatPairs t data InfInt = Infinity | Finite Int deriving (Eq, Show) instance Ord InfInt where Infinity < Infinity = False Finite _ < Infinity = True Infinity < Finite _ = False Finite a < Finite b = a < b maybeEmpty :: [a] -> Maybe [a] maybeEmpty [] = Nothing maybeEmpty l = Just l
JoeyEremondi/ai-vs-ai-common
src/AiVsAi/Util.hs
gpl-2.0
1,315
0
12
391
609
320
289
35
1
-- -- -- (C) 2011-16 Nicola Bonelli <[email protected]> -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software Foundation, -- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- -- The full GNU General Public License is included in this distribution in -- the file called "COPYING". {-# LANGUAGE ScopedTypeVariables #-} module Main where import Network.PFQ as Q import Network.PFQ.Lang import Network.PFQ.Lang.Default import Foreign import System.Environment import Numeric import Control.Monad -- import Debug.Trace dumpPacket :: Q.Packet -> IO () dumpPacket p = do Q.waitForPacket p bytes <- peekByteOff (Q.pData p) 0 :: IO Word64 putStrLn $ "[" ++ showHex bytes "" ++ "]" recvLoop ::PfqHandlePtr -> IO () recvLoop q = do queue <- Q.read q 100000000 gid <- Q.getGroupId q if Q.qLen queue == 0 then recvLoop q else do ps <- Q.getPackets queue mapM_ (getPacketHeader >=> print) ps mapM_ dumpPacket ps Q.getGroupCounters q gid >>= print recvLoop q -- Context shared as Storable Pair -- dumper :: String -> IO () dumper dev = do putStrLn $ "dumping " ++ dev ++ "..." fp <- Q.open 64 4096 64 4096 Q.withPfq fp $ \q -> do Q.timestampingEnable q True gid <- Q.getGroupId q Q.bindGroup q gid dev (-1) Q.enable q let m = bloomCalcM 2 0.000001 let comp = bloom_filter (fromIntegral m) ["192.168.0.0"] 16 >-> log_packet putStrLn $ pretty comp Q.setGroupComputation q gid comp recvLoop q main :: IO () main = do args <- getArgs case length args of 0 -> error "usage: test-bloom dev" _ -> dumper (head args)
pfq/PFQ
user/pfq-regression/Haskell/test-bloom.hs
gpl-2.0
2,373
0
17
644
516
255
261
46
2
-- Starting in the top left corner of a 2×2 grid, and only being able to move to the right -- and down, there are exactly 6 routes to the bottom right corner. -- How many such routes are there through a 20×20 grid? -- Well this is just combinatorics ... -- * All paths are 20x20 == 40 long, you have to go right 20 and down 20 however you go -- * Think about the moves as a series of r and d moves -- * Each possible series of moves must have a unique set of 20 positions of r and of d moves -- * So this is a combination without repetition. The formula is -- n! -- -------- -- r!(n-r!) -- -- With r as 20 (the positions of the down moves) and n as the total length of the series -- of moves -- 40 -- -- 137846528820 moves :: Integer moves = (fac n) `div` ((fac r)*(fac (n-r))) where n = 40 r = 20 fac :: Integer -> Integer fac n = product [1..n]
ciderpunx/project_euler_in_haskell
euler015.hs
gpl-2.0
882
2
11
215
104
64
40
7
1
{-# LANGUAGE OverloadedStrings #-} -- Copyright (c) 2011, Diego Souza -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * 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. -- * Neither the name of the <ORGANIZATION> nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- 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. -- This is simply a copy with mutation of: -- http://www.haskell.org/haskellwiki/Roll_your_own_IRC_bot module TikTok.Plugins.Uptime ( new ) where import Control.Monad.Reader import System.Time import Network.SimpleIRC.Messages import Network.SimpleIRC.Core import TikTok.Bot import TikTok.Plugins.CalendarTimeHelpers import TikTok.Plugins.ByteStringHelpers new :: ClockTime -> Plugin new start = Plugin (eventHandler start) "uptime" eventHandler :: ClockTime -> Event -> Bot () eventHandler start (EvtPrivmsg m) | "!uptime" == mMsg m = do { irc <- asks ircConn ; now <- liftIO getClockTime ; dest <- liftIO $ getDest irc m ; sayPrivmsg dest (tobs $ pretty (diffClockTimes now start)) } | otherwise = return () eventHandler _ _ = return ()
dgvncsz0f/tiktok
src/main/TikTok/Plugins/Uptime.hs
gpl-3.0
2,510
0
13
542
251
143
108
20
1
module WorkingFluid where import Utility import Numeric.Units.Dimensional.Prelude import qualified Prelude data GasData = GasData { condition :: GasCond, model :: GasModel } data GasCond = GasCond { pressure :: Pressure Double, temperature :: Temperature Double } data GasModel = GasModel { soundVelocity :: GasCond -> Velocity Double, thermalConductivity :: GasCond -> ThermalConductivity Double, dynamicViscosity :: GasCond -> DynamicViscosity Double, density :: GasCond -> Density Double, cpSpecHeat :: SpecificHeatCapacity Double, cvSpecHeat :: SpecificHeatCapacity Double } getVal :: (GasModel -> GasCond -> a) -> GasData -> a getVal f dat = f (model dat) (condition dat) getTemp dat = temperature (condition dat) getPres dat = pressure (condition dat) getSV = getVal soundVelocity getTC = getVal thermalConductivity getDV = getVal dynamicViscosity getRHO = getVal density getCP dat = cpSpecHeat (model dat) getCV dat = cvSpecHeat (model dat) getGAM a = getCP a / getCV a getPRN a = getCP a * getDV a / getTC a atmoPres = 101325.0 *~ pascal roomTemp = 298.15 *~ kelvin stpTemp = 273.15 *~ kelvin roomCond :: GasCond roomCond = GasCond atmoPres roomTemp -- These models should be within 5% relative error for temperatures -- between 200 K and 400 K and pressures between 0.5 bar and 50 bar heliumModel :: GasModel heliumModel = GasModel sosU kgU muU rhoU cp cv where sosU (GasCond p t) = sos (p /~ pascal) (t /~ kelvin) *~ (meter / second) sos p t = 480.59 !+ (1.79 !* t) kgU (GasCond p t) = kg (p /~ pascal) (t /~ kelvin) *~ (watt / (meter * kelvin)) kg p t = ((2.3889 `e` (-4)) !* t) !** 0.710 muU (GasCond p t) = mu (p /~ pascal) (t /~ kelvin) *~ (pascal * milli second) mu p t = ((7.9639 `e` (-6)) !* t) !** 0.647 rhoU (GasCond p t) = rho (p /~ pascal) (t /~ kelvin) *~ (gram / milli liter) rho p t = (0.4791 !* (p !/ 100000)) !/ (t !+ 0.0000) cp = 5.193 *~ (joule / (gram * kelvin)) cv = 3.116 *~ (joule / (gram * kelvin)) nitrogenModel :: GasModel nitrogenModel = GasModel sosU kgU muU rhoU cp cv where sosU (GasCond p t) = sos (p /~ pascal) (t /~ kelvin) *~ (meter / second) sos p t = 186.77 !+ (0.55 !* t) kgU (GasCond p t) = kg (p /~ pascal) (t /~ kelvin) *~ (watt / (meter * kelvin)) kg p t = ((2.9929 `e` (-5)) !* t) !** 0.775 muU (GasCond p t) = mu (p /~ pascal) (t /~ kelvin) *~ (pascal * milli second) mu p t = ((1.8417 `e` (-5)) !* t) !** 0.775 rhoU (GasCond p t) = rho (p /~ pascal) (t /~ kelvin) *~ (gram / milli liter) rho p t = (0.3440 !* (p !/ 100000)) !/ (t !+ 2.4543) cp = 1.040 *~ (joule / (gram * kelvin)) cv = 0.743 *~ (joule / (gram * kelvin)) airModel :: GasModel airModel = GasModel sosU kgU muU rhoU cp cv where sosU (GasCond p t) = sos (p /~ pascal) (t /~ kelvin) *~ (meter / second) sos p t = 174.00 !+ (0.58 !* t) kgU (GasCond p t) = kg (p /~ pascal) (t /~ kelvin) *~ (watt / (meter * kelvin)) kg p t = ((2.9929 `e` (-5)) !* t) !** 0.775 muU (GasCond p t) = mu (p /~ pascal) (t /~ kelvin) *~ (pascal * milli second) mu p t = ((2.1284 `e` (-5)) !* t) !** 0.790 rhoU (GasCond p t) = rho (p /~ pascal) (t /~ kelvin) *~ (gram / milli liter) rho p t = (0.3590 !* (p !/ 100000)) !/ (t !+ 2.4543) cp = 1.005 *~ (joule / (gram * kelvin)) cv = 0.718 *~ (joule / (gram * kelvin))
taktoa/ThermoCalc
src/WorkingFluid.hs
gpl-3.0
3,774
0
13
1,199
1,565
835
730
70
1
-- Vigenere.hs This module provides all of the functions used to -- encrypt/decrypt/crypanalyize the Vigenere cipher -- -- Author: Brendan Fahy <[email protected]> ----------------------------------------------------------------------- -- This program is free software: you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------ module Vigenere ( encrypt , decrypt , kasiski , indiciesOfCoincidence , strip , findkey ) where import Char import Data.List import qualified Data.Map as Map import Maybe encrypt :: String -> String -> String -- Encrypt plaintext encrypt s key = z26tostring (zipWith modadd (cycle keystream) plaintext) where plaintext = stringtoz26 s keystream = stringtoz26 key modadd x y = (x+y)`mod`26 decrypt :: String -> String -> String -- Decrypt ciphertext decrypt s key = z26tostring (zipWith modsubtract (cycle keystream) plaintext) where plaintext = stringtoz26 s keystream = stringtoz26 key modsubtract x y = (y-x)`mod`26 strip :: String -> String -- remove non alpha characters and change to uppercase strip = map toUpper . filter isAlpha --strip x = map toUpper (filter isAlpha x) stringtoz26 :: String -> [Int] --convert characters to number [0-25] stringtoz26 x = map ((\x -> x-65) . ord) (strip x) z26tostring :: [Int] -> String -- convert numbers 0-25 to characters z26tostring = map (chr . (+65)) -- pair trigrams with their location in the list trigrampairs :: (Ord a, Ord t, Num t, Enum t) => [a] -> [([a], t)] trigrampairs x = sort $ zip (map (trigram x) [0..(l-3)]) [1..] where l = length x trigram x a = take 3 $ drop a x -- Find the location of pairs which are repeated. locrepeatedpairs :: (Ord a, Ord b, Num b, Enum b) => [a] -> [[b]] locrepeatedpairs x = map snds $ sortBy complengths $filter long $ groupBy fstequ $ trigrampairs x where fstequ a b = fst a == fst b complengths a b = compare (length b) (length a) long x = length x > 2 snds a = [snd b | b<- a] -- the kasiski test. Find the GCD of the differences in position kasiski :: (Integral a, Ord a1) => [a1] -> [a] kasiski x = map (foldl gcd 0 .diff) (locrepeatedpairs x ) where diff x = map (subtract $ head x) (tail x) -- Split a string into groups of n splitst :: Int -> String -> [String] splitst _ "" = [] splitst n x = take n x : splitst n (drop n x) -- Make n new strings each with every nth letter nstrings :: Int -> String -> [String] nstrings n = transpose . splitst n -- count the frequencies of each letter freqcount :: (Num b) => String -> [b] freqcount xs = map (\a -> fromIntegral $ length $ elemIndices a xs) allLetters where allLetters = ['A'..'Z'] n = length xs -- calculate the index of coincindence of a list indexOfCoincidence :: (Fractional b) => String -> b indexOfCoincidence xs = foldr ((+) . p) 0.0 freq /(n*(n-1.0)) where freq = freqcount xs n = fromIntegral $ length xs p f = f*(f-1.0) -- find the indicies of coincidence of the n substrings indiciesOfCoincidence :: (Fractional b) => Int -> String -> [b] indiciesOfCoincidence n = map indexOfCoincidence . nstrings n -- Get statistical information about a ceaser shift guessshift :: String -> Int -> Double guessshift xs g = sum (zipWith (\p f -> (p*f)) probabilities $freqs)/n where n = fromIntegral $ length xs freqs = drop g $ cycle $ freqcount xs -- Find the key to a ceaser shift findShift :: String -> Int findShift xs = fromJust $ elemIndex =<< minimum $ ics where ics = map ((\x -> abs $ 0.065-x) . guessshift xs) [0..25] -- find the key to a vigenere cipher knowing the key length findkey :: Int -> String -> String findkey n = z26tostring . map findShift . nstrings n probabilities = [0.082,0.015,0.028,0.043,0.127,0.022,0.020,0.061,0.070,0.002, 0.008,0.040,0.024,0.067,0.075,0.019,0.001,0.060,0.063,0.091, 0.028,0.010,0.023,0.001,0.020,0.001] -- example = "the almond tree was in tentative blossom. The days were longer, often ending with magnificent evenings of corrugated pink skies. The hunting season was over, with hounds and guns put away for six months. The vineyards were busy again as the well-organized farmers treated their vines and the more lackadaisical neighbors hurried to do the pruning they should have done in November." -- ciexample = encrypt example "janet"
f4hy/Vigenery
Vigenere.hs
gpl-3.0
5,158
1
13
1,183
1,329
722
607
68
1
{- | Module : $Header$ Description : Module for factorising numbers using Lenstra's ECM algorithm Copyright : (c) Michal Parusinski License : GPLv3 Maintainer : [email protected] Stability : experimental Portability : portable -} module Factoring.Lenstra where import EllipticCurves.ModularEllipticCurves import Primes.Sieve import Data.Either import Data.Maybe import Control.Monad import Control.Concurrent repeatedCubicLaw :: (Integral a, Integral b) => ModularEllipticCurve a -> Point a -> b -> a -> Either (Point a) a -- repeatedCubicLaw _ _ 0 _ = Left $ SimplePoint 0 0 -- point at infinity repeatedCubicLaw _ point 1 _ = Left point repeatedCubicLaw ellipticCurve point times modulus | result == Left Inf = Left Inf -- skip recursion | rem == 0 = square | otherwise = squarePlus1 where (half, rem) = divMod times 2 result = repeatedCubicLaw ellipticCurve point half modulus square = either (\x -> cubicLaw ellipticCurve x x modulus) Right result squarePlus1 = either (\x -> cubicLaw ellipticCurve x point modulus) Right square repeatedParallelCubic :: (Integral a, Integral b) => [ModularEllipticCurve a] -> [Point a] -> b -> a -> Either [Point a] a repeatedParallelCubic _ points 1 _ = Left points repeatedParallelCubic ecs points times modulus | rem == 0 = square | otherwise = squarePlus1 where (half, rem) = divMod times 2 result = repeatedParallelCubic ecs points half modulus square = case result of Left ps -> parallelCubicLaw ecs ps ps modulus Right div -> Right div squarePlus1 = case square of Left ps -> parallelCubicLaw ecs points ps modulus Right div -> Right div lenstraECMSmartBound number = lenstraECM number (smartBound number) lenstraECMParallelSmartBound number = lenstraECMParallel number (smartBound number) lenstraECM :: Integer -> Integer -> Maybe Integer lenstraECM number bound | number `mod` 2 == 0 = Just 2 | number `mod` 3 == 0 = Just 3 | number `mod` 5 == 0 = Just 5 | otherwise = let primes = eratosthenesSieve bound primePowers = map (findHighestPower bound) primes upperBound = (number - 1) curves = filter (isElliptic number) $ map (\x -> MEC x 1) [1..upperBound] in lenstraECMLoop number primePowers curves where lenstraECMLoop _ _ [] = Nothing lenstraECMLoop number primePowers (ec:ecs) = if isNothing result then recurse else result where result = lenstraECMTryEC number primePowers initP ec recurse = lenstraECMLoop number primePowers ecs initP = Point 0 1 lenstraECMTryEC _ [] _ _ = Nothing lenstraECMTryEC number (p:ps) accumPoint ec = either recurse Just result where recurse point = lenstraECMTryEC number ps point ec result = repeatedCubicLaw ec accumPoint p number isElliptic num (MEC a b) = (4 * a^3 + 27 * b^2) `mod` num /= 0 -- Good chunksize was obtained from experimentation lenstraECMParallel :: Integer -> Integer -> Maybe Integer lenstraECMParallel number bound | number `mod` 2 == 0 = Just 2 | number `mod` 3 == 0 = Just 3 | number `mod` 5 == 0 = Just 5 | otherwise = let primes = eratosthenesSieve bound primePowers = map (findHighestPower bound) primes upperBound = (number - 1) curves = filter (isElliptic number) $ map (\x -> MEC x 1) [1..upperBound] in lenstraECMLoop number primePowers curves where lenstraECMLoop _ _ [] = Nothing lenstraECMLoop number primePowers ecs = if isNothing result then recurse else result where result = lenstraECMTryChunk number primePowers points ecChunk recurse = lenstraECMLoop number primePowers ecRest ecChunk = take chunkSize ecs ecRest = drop chunkSize ecs points = take chunkSize $ repeat (Point 0 1) chunkSize = if number < 100 then fromIntegral number else 100 lenstraECMTryChunk _ [] _ _ = Nothing lenstraECMTryChunk number (p:ps) accumPoints ecChunk = either recurse Just result where recurse points = lenstraECMTryChunk number ps points ecChunk result = repeatedParallelCubic ecChunk accumPoints p number findHighestPower n p = findHighestPowerAccum bound p 1 where bound = floor $ (fromIntegral n :: Double) / (fromIntegral p :: Double) findHighestPowerAccum bound p accum | accum > bound = accum | otherwise = findHighestPowerAccum bound p (accum * p) smartBound number = ceiling $ (l number) ** (1 / sqrt 2) where l x = exp (sqrt $ log x_ * log (log x_)) where x_ = sqrt $ fromIntegral x
mparusinski/Haskell-number-theory-library
Factoring/Lenstra.hs
gpl-3.0
5,141
0
14
1,620
1,483
739
744
95
5
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with grid. If not, see <http://www.gnu.org/licenses/>. -- module Game.Grid.Output ( cameraModelMat4, cameraViewMat4, mat4TranslateNode, mat4Turn, mat4RotateTurn, mat4Segment, #ifdef GRID_STYLE_FANCY module Game.Grid.Output.Fancy, #endif #ifdef GRID_STYLE_PLAIN module Game.Grid.Output.Plain #endif ) where import MyPrelude import Game import Game.Grid import OpenGL import OpenGL.Helpers #ifdef GRID_STYLE_FANCY import Game.Grid.Output.Fancy #endif #ifdef GRID_STYLE_PLAIN import Game.Grid.Output.Plain #endif -------------------------------------------------------------------------------- -- -- how to typically output to Screen: -- -- 0. setup screen: done by Scene -- 1. define projection matrix (a view property of GL camera): sceneProj2D/sceneProj3D -- 2. define modelview matrix (GL camera placement): cameraViewMat4/cameraModelMat4 -- 3. set shaders using these matrices, and draw -------------------------------------------------------------------------------- -- -- | view matrix from Camera cameraViewMat4 :: Camera -> Mat4 cameraViewMat4 camera = let View a b c = cameraView camera View a' b' c' = cameraViewIdeal camera a'' = smooth a a' $ cameraViewAAlpha camera b'' = smooth b b' $ cameraViewBAlpha camera c'' = smooth c c' $ cameraViewCAlpha camera in mat4ViewABC (tau * 0.25 + a'') b'' c'' -- | model matrix from camera cameraModelMat4 :: Camera -> Mat4 cameraModelMat4 camera = let -- TurnB: turnB = turnInverse $ cameraTurnB camera turnB' = turnInverse $ cameraTurnBIdeal camera matTurnB = mat4SmoothTurn turnB turnB' $ cameraTurnBAlpha camera -- TurnA: turnA = turnInverse $ cameraTurnA camera turnA' = turnInverse $ cameraTurnAIdeal camera matTurnA = mat4SmoothTurn turnA turnA' $ cameraTurnAAlpha camera -- translate: node = cameraNode camera node' = cameraNodeIdeal camera Vec4 x y z w = smoothNode node node' $ cameraNodeAlpha camera matTranslate = mat4TranslationAnti x y z w in matTurnB `mappend` matTurnA `mappend` matTranslate mat4Turn :: Turn -> Mat4 mat4Turn (Turn a0 a1 a2 b0 b1 b2 c0 c1 c2) = Mat4 (fI a0) (fI a1) (fI a2) 0 (fI b0) (fI b1) (fI b2) 0 (fI c0) (fI c1) (fI c2) 0 0 0 0 1 mat4RotateTurn :: Mat4 -> Turn -> Mat4 mat4RotateTurn mat turn = mat `mappend` mat4Turn turn mat4TranslateNode :: Mat4 -> Node -> Mat4 mat4TranslateNode mat (Node x y z) = case Mat4 1 0 0 0 0 1 0 0 0 0 1 0 (fI x) (fI y) (fI z) 1 of mat' -> mat `mappend` mat' mat4Segment :: Segment -> Mat4 mat4Segment (Segment (Node x y z) (Turn a0 a1 a2 b0 b1 b2 c0 c1 c2)) = Mat4 (fI a0) (fI a1) (fI a2) 0 (fI b0) (fI b1) (fI b2) 0 (fI c0) (fI c1) (fI c2) 0 (fI x) (fI y) (fI z) 1 -------------------------------------------------------------------------------- -- smoothNode :: Node -> Node -> Float -> Vec4 smoothNode (Node x y z) (Node x' y' z') alpha = let a = 1 - alpha a' = alpha in Vec4 (a * fromIntegral x + a' * fromIntegral x') (a * fromIntegral y + a' * fromIntegral y') (a * fromIntegral z + a' * fromIntegral z') 1 -- | note: this will only work if no column c in turn is mapped to -c in turn' ! mat4SmoothTurn :: Turn -> Turn -> Float -> Mat4 mat4SmoothTurn turn turn' alpha = let Turn x0 x1 x2 y0 y1 y2 z0 z1 z2 = turn Turn x0' x1' x2' y0' y1' y2' z0' z1' z2' = turn' a = (1 - alpha) a' = alpha x0'' = a * (fromIntegral x0) + a' * (fromIntegral x0') x1'' = a * (fromIntegral x1) + a' * (fromIntegral x1') x2'' = a * (fromIntegral x2) + a' * (fromIntegral x2') y0'' = a * (fromIntegral y0) + a' * (fromIntegral y0') y1'' = a * (fromIntegral y1) + a' * (fromIntegral y1') y2'' = a * (fromIntegral y2) + a' * (fromIntegral y2') z0'' = a * (fromIntegral z0) + a' * (fromIntegral z0') z1'' = a * (fromIntegral z1) + a' * (fromIntegral z1') z2'' = a * (fromIntegral z2) + a' * (fromIntegral z2') xscale = scale x0'' x1'' x2'' yscale = scale y0'' y1'' y2'' zscale = scale z0'' z1'' z2'' in Mat4 (xscale * x0'') (xscale * x1'') (xscale * x2'') 0 (yscale * y0'') (yscale * y1'') (yscale * y2'') 0 (zscale * z0'') (zscale * z1'') (zscale * z2'') 0 0 0 0 1 where scale a0 a1 a2 = 1 / (sqrt $ a0 * a0 + a1 * a1 + a2 * a2) -- note: fails if zero
karamellpelle/grid
source/Game/Grid/Output.hs
gpl-3.0
5,672
0
14
1,770
1,520
801
719
97
1
module Inquire ( PrologInquireBoolForm(..), inquirePrologBool ) where import Import hiding(Form) import CCGraph import Form import ShowText import Control.Monad.CC.CCCxe import Language.Prolog2.Syntax import Authentication import qualified Data.Text as T breadcrumbWidget :: CCState -> Widget breadcrumbWidget st = do path' <- handlerToWidget $ spine (ccsCurrentNode st) let nodes = map snd' path' snd' (a,b,c) = b titles <- handlerToWidget $ mapM lookupCCNodeTitle nodes case path' of [] -> [whamlet||] (root,_,_):_ -> [whamlet| <nav class="breadcrumb"> $forall (node,mtitle) <- zip nodes titles &gt; $maybe title <- mtitle <a href="@{PrologExecuteTestContR node}"> #{show node}:#{title} $nothing <a href="@{PrologExecuteTestContR node}"> #{show node} |] data PrologInquireBoolForm = PrologInquireBoolForm Bool deriving (Eq,Ord,Show, Typeable) prologInquireBoolForm :: Term -> Html -> MForm Handler (FormResult PrologInquireBoolForm, Widget) prologInquireBoolForm t = renderDivs $ PrologInquireBoolForm <$> areq boolField (fromString $ showU t) Nothing -- <$> areq boolField (fromString $ show t) Nothing prologInquireBoolWidget :: CCState -> CCNode -> Widget -> Enctype -> Widget prologInquireBoolWidget st node formWidget _enctype = do uid <- handlerToWidget $ getUserAccountId [whamlet| ^{breadcrumbWidget st} <form action=@{PrologExecuteTestContR node} method="GET"> ^{formWidget} <button type="submit" value="Submit">Submit</button> |] prologInquireBoolHtml :: CCState -> Term -> CCContentTypeM App prologInquireBoolHtml st t node = do (formWidget, enctype) <- lift $ generateCCFormGet (prologInquireBoolForm t) CCContentHtml <$> (lift $ defaultLayout $ prologInquireBoolWidget st node formWidget enctype) inquirePrologBool :: CCState -> Term -> CCPrologHandler CCState inquirePrologBool st t = do let title = T.pack $ showU t inquireGetUntil st title (prologInquireBoolHtml st t) (prologInquireBoolForm t) showU :: Term -> String showU (UTerm (TStruct a [])) = T.unpack a showU t = show t
nishiuramakoto/logiku
app/Inquire.hs
gpl-3.0
2,410
0
11
664
526
278
248
-1
-1
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import qualified Data.ByteString.Lazy as BL import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import Test.HUnit import Test.QuickCheck import qualified Formatter as Formatter import Lib import qualified Model as Model import qualified Parser as Parser reverseList :: [Int] -> Bool reverseList xs = xs == reverse (reverse xs) testClean :: Test testClean = TestCase $ do assertEqual "" "abc" (Parser.clean "abc // adsfasdf") assertEqual "" "abc" (Parser.clean " abc ") testParseLabel :: Test testParseLabel = TestCase $ do assertEqual "really a label" (Just . Model.LabelInstruction $ "LOOP") (Parser.parseLabel " (LOOP) // start here") assertEqual "not a label at all" Nothing (Parser.parseLabel " @lol // not a label") assertEqual "not a label either" Nothing (Parser.parseLabel "(adf // syntax error") testParseAddress :: Test testParseAddress = TestCase $ do assertEqual "a literal address" (Just . Model.AddrInstruction . Model.AddrLiteral $ 1234) (Parser.parseAddr "@1234 // lol") assertEqual "a symbolic address" (Just . Model.AddrInstruction . Model.AddrSymbol $ "sum") (Parser.parseAddr " @sum") forM_ [ Parser.parseAddr " D=A" , Parser.parseAddr " // nothing here" , Parser.parseAddr "(LOOP)" ] $ \c -> assertEqual "not an address" Nothing c testFormatting :: Test testFormatting = TestCase $ do assertEqual "C-instruction expression" "011111" (Formatter.formatCompExpr Model.DPlusOne) assertEqual "C-instruction destination" "101" (Formatter.formatDest $ Set.fromList [Model.RegA, Model.RegM]) assertEqual "C-instruction destination (2)" "100" (Formatter.formatDest $ Set.singleton Model.RegA) assertEqual "C-instruction jump" "011" (Formatter.formatJump $ Set.fromList [EQ, GT]) assertEqual "C-instruction jump (2)" "001" (Formatter.formatJump $ Set.fromList [GT]) assertEqual "A-instruction" (Just "0000000000000101") (Formatter.formatAddr Map.empty (Model.AddrLiteral 5)) assertEqual "Whole C-instruction" "1111110010110011" (Formatter.formatComp (Set.fromList [Model.RegA, Model.RegD]) Model.RSubOne Model.UseM (Set.fromList [GT, EQ])) main :: IO () main = do quickCheck reverseList runTestTT $ TestList [ TestLabel "clean" testClean , TestLabel "parse label" testParseLabel , TestLabel "parse address" testParseAddress , TestLabel "format instructions" testFormatting ] return ()
easoncxz/hack-assembler
test/Spec.hs
gpl-3.0
2,856
0
14
708
711
367
344
97
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionNotificationEndpoints.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns the specified NotificationEndpoint resource in the given region. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionNotificationEndpoints.get@. module Network.Google.Resource.Compute.RegionNotificationEndpoints.Get ( -- * REST Resource RegionNotificationEndpointsGetResource -- * Creating a Request , regionNotificationEndpointsGet , RegionNotificationEndpointsGet -- * Request Lenses , rnegProject , rnegNotificationEndpoint , rnegRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionNotificationEndpoints.get@ method which the -- 'RegionNotificationEndpointsGet' request conforms to. type RegionNotificationEndpointsGetResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "notificationEndpoints" :> Capture "notificationEndpoint" Text :> QueryParam "alt" AltJSON :> Get '[JSON] NotificationEndpoint -- | Returns the specified NotificationEndpoint resource in the given region. -- -- /See:/ 'regionNotificationEndpointsGet' smart constructor. data RegionNotificationEndpointsGet = RegionNotificationEndpointsGet' { _rnegProject :: !Text , _rnegNotificationEndpoint :: !Text , _rnegRegion :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionNotificationEndpointsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rnegProject' -- -- * 'rnegNotificationEndpoint' -- -- * 'rnegRegion' regionNotificationEndpointsGet :: Text -- ^ 'rnegProject' -> Text -- ^ 'rnegNotificationEndpoint' -> Text -- ^ 'rnegRegion' -> RegionNotificationEndpointsGet regionNotificationEndpointsGet pRnegProject_ pRnegNotificationEndpoint_ pRnegRegion_ = RegionNotificationEndpointsGet' { _rnegProject = pRnegProject_ , _rnegNotificationEndpoint = pRnegNotificationEndpoint_ , _rnegRegion = pRnegRegion_ } -- | Project ID for this request. rnegProject :: Lens' RegionNotificationEndpointsGet Text rnegProject = lens _rnegProject (\ s a -> s{_rnegProject = a}) -- | Name of the NotificationEndpoint resource to return. rnegNotificationEndpoint :: Lens' RegionNotificationEndpointsGet Text rnegNotificationEndpoint = lens _rnegNotificationEndpoint (\ s a -> s{_rnegNotificationEndpoint = a}) -- | Name of the region scoping this request. rnegRegion :: Lens' RegionNotificationEndpointsGet Text rnegRegion = lens _rnegRegion (\ s a -> s{_rnegRegion = a}) instance GoogleRequest RegionNotificationEndpointsGet where type Rs RegionNotificationEndpointsGet = NotificationEndpoint type Scopes RegionNotificationEndpointsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient RegionNotificationEndpointsGet'{..} = go _rnegProject _rnegRegion _rnegNotificationEndpoint (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy RegionNotificationEndpointsGetResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionNotificationEndpoints/Get.hs
mpl-2.0
4,380
0
16
970
466
278
188
82
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.CloudResourceManager.TagKeys.Patch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the attributes of the TagKey resource. -- -- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> for @cloudresourcemanager.tagKeys.patch@. module Network.Google.Resource.CloudResourceManager.TagKeys.Patch ( -- * REST Resource TagKeysPatchResource -- * Creating a Request , tagKeysPatch , TagKeysPatch -- * Request Lenses , tkpXgafv , tkpValidateOnly , tkpUploadProtocol , tkpUpdateMask , tkpAccessToken , tkpUploadType , tkpPayload , tkpName , tkpCallback ) where import Network.Google.Prelude import Network.Google.ResourceManager.Types -- | A resource alias for @cloudresourcemanager.tagKeys.patch@ method which the -- 'TagKeysPatch' request conforms to. type TagKeysPatchResource = "v3" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "validateOnly" Bool :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TagKey :> Patch '[JSON] Operation -- | Updates the attributes of the TagKey resource. -- -- /See:/ 'tagKeysPatch' smart constructor. data TagKeysPatch = TagKeysPatch' { _tkpXgafv :: !(Maybe Xgafv) , _tkpValidateOnly :: !(Maybe Bool) , _tkpUploadProtocol :: !(Maybe Text) , _tkpUpdateMask :: !(Maybe GFieldMask) , _tkpAccessToken :: !(Maybe Text) , _tkpUploadType :: !(Maybe Text) , _tkpPayload :: !TagKey , _tkpName :: !Text , _tkpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TagKeysPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tkpXgafv' -- -- * 'tkpValidateOnly' -- -- * 'tkpUploadProtocol' -- -- * 'tkpUpdateMask' -- -- * 'tkpAccessToken' -- -- * 'tkpUploadType' -- -- * 'tkpPayload' -- -- * 'tkpName' -- -- * 'tkpCallback' tagKeysPatch :: TagKey -- ^ 'tkpPayload' -> Text -- ^ 'tkpName' -> TagKeysPatch tagKeysPatch pTkpPayload_ pTkpName_ = TagKeysPatch' { _tkpXgafv = Nothing , _tkpValidateOnly = Nothing , _tkpUploadProtocol = Nothing , _tkpUpdateMask = Nothing , _tkpAccessToken = Nothing , _tkpUploadType = Nothing , _tkpPayload = pTkpPayload_ , _tkpName = pTkpName_ , _tkpCallback = Nothing } -- | V1 error format. tkpXgafv :: Lens' TagKeysPatch (Maybe Xgafv) tkpXgafv = lens _tkpXgafv (\ s a -> s{_tkpXgafv = a}) -- | Set as true to perform validations necessary for updating the resource, -- but not actually perform the action. tkpValidateOnly :: Lens' TagKeysPatch (Maybe Bool) tkpValidateOnly = lens _tkpValidateOnly (\ s a -> s{_tkpValidateOnly = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). tkpUploadProtocol :: Lens' TagKeysPatch (Maybe Text) tkpUploadProtocol = lens _tkpUploadProtocol (\ s a -> s{_tkpUploadProtocol = a}) -- | Fields to be updated. The mask may only contain \`description\` or -- \`etag\`. If omitted entirely, both \`description\` and \`etag\` are -- assumed to be significant. tkpUpdateMask :: Lens' TagKeysPatch (Maybe GFieldMask) tkpUpdateMask = lens _tkpUpdateMask (\ s a -> s{_tkpUpdateMask = a}) -- | OAuth access token. tkpAccessToken :: Lens' TagKeysPatch (Maybe Text) tkpAccessToken = lens _tkpAccessToken (\ s a -> s{_tkpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). tkpUploadType :: Lens' TagKeysPatch (Maybe Text) tkpUploadType = lens _tkpUploadType (\ s a -> s{_tkpUploadType = a}) -- | Multipart request metadata. tkpPayload :: Lens' TagKeysPatch TagKey tkpPayload = lens _tkpPayload (\ s a -> s{_tkpPayload = a}) -- | Immutable. The resource name for a TagKey. Must be in the format -- \`tagKeys\/{tag_key_id}\`, where \`tag_key_id\` is the generated numeric -- id for the TagKey. tkpName :: Lens' TagKeysPatch Text tkpName = lens _tkpName (\ s a -> s{_tkpName = a}) -- | JSONP tkpCallback :: Lens' TagKeysPatch (Maybe Text) tkpCallback = lens _tkpCallback (\ s a -> s{_tkpCallback = a}) instance GoogleRequest TagKeysPatch where type Rs TagKeysPatch = Operation type Scopes TagKeysPatch = '["https://www.googleapis.com/auth/cloud-platform"] requestClient TagKeysPatch'{..} = go _tkpName _tkpXgafv _tkpValidateOnly _tkpUploadProtocol _tkpUpdateMask _tkpAccessToken _tkpUploadType _tkpCallback (Just AltJSON) _tkpPayload resourceManagerService where go = buildClient (Proxy :: Proxy TagKeysPatchResource) mempty
brendanhay/gogol
gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/TagKeys/Patch.hs
mpl-2.0
5,801
0
18
1,364
939
546
393
132
1
{-# LANGUAGE OverloadedStrings #-} module Actions.Responses ( url , infoResponse , errorResponse , logInResponse ) where import Text.Blaze.Html5 (Html,(!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Web.Scotty (RoutePattern) import App (Action) import qualified Page url :: RoutePattern url = "/info" data InfoType = OKInfo | ErrorInfo view :: InfoType -> Html -> Html view infoType message = do H.div ! (case infoType of OKInfo -> A.class_ "bar message" ErrorInfo -> A.class_ "bar error") $ message H.a ! A.href "/" $ H.button ! A.class_ "info" $ "OK" infoResponse :: Html -> Action infoResponse msg = Page.render (view OKInfo msg) Page.defaultPageConfig errorResponse :: Html -> Action errorResponse msg = Page.render (view ErrorInfo msg) Page.defaultPageConfig logInResponse :: Action logInResponse = errorResponse "Please log in first."
DataStewardshipPortal/ds-wizard
DSServer/app/Actions/Responses.hs
apache-2.0
935
0
14
167
277
154
123
28
2
module Synthax.Algebra ( Algebra , MAlgebra , Fix(..) , LazyFix(..) , cata , lazyCata , mcata , lazyMCata ) where import Prelude type Algebra f a = f a -> a type MAlgebra m f a = f (m a) -> m a newtype Fix f = Fx (f (Fix f)) newtype LazyFix f = Fx' (f (LazyFix f) (LazyFix f)) unFix :: Fix f -> f (Fix f) unFix (Fx x) = x lazyUnFix :: LazyFix f -> f (LazyFix f) (LazyFix f) lazyUnFix (Fx' x) = x cata :: Functor f => Algebra f a -> Fix f -> a cata alg = alg . fmap (cata alg) . unFix lazyCata :: Functor (f (LazyFix f)) => Algebra (f (LazyFix f)) a -> LazyFix f -> a lazyCata alg = alg . fmap (lazyCata alg) . lazyUnFix mcata :: Functor f => MAlgebra m f a -> Fix f -> m a mcata alg = alg . fmap (mcata alg) . unFix lazyMCata :: Functor (f (LazyFix f)) => MAlgebra m (f (LazyFix f)) a -> LazyFix f -> m a lazyMCata alg = alg . fmap (lazyMCata alg) . lazyUnFix
burz/sonada
Synthax/Algebra.hs
apache-2.0
870
0
11
203
481
246
235
26
1
{-# LANGUAGE CPP, OverloadedStrings, FlexibleContexts #-} module SSync.Hash ( forName , name , HashAlgorithm(..) , HashState , HashT , withHashT , initState , update , digest , digestSize , updateS , digestS , digestSizeS , hexString , withHashState , withHashState' ) where import Control.Monad (liftM) import Control.Monad.State.Strict (StateT, MonadState, evalStateT, get, put, modify) import Control.Monad.Trans (lift) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Base16 as B16 import Data.Text (Text) #ifdef STUPID_HASH import Crypto.Types (BitLength) import qualified Data.DList as DL import qualified Data.Digest.Pure.MD5 as MD5 -- pureMD5 is 10x faster than Crypto's MD5 import Data.Serialize (encode) import Data.Tagged (untag, Tagged) data HashAlgorithm = MD5 deriving (Read, Show, Eq, Ord, Bounded, Enum) initState :: HashAlgorithm -> HashState initState MD5 = fromCtx MD5.initialCtx DL.empty targetBlockSizeBytes where fromCtx :: MD5.MD5Context -> DL.DList ByteString -> Int -> HashState fromCtx ctx leftovers remaining = ctx `seq` HashState { update = abstractUpdate ctx leftovers remaining , digest = abstractFinalize ctx leftovers } abstractUpdate ctx leftovers remaining new = let leftovers' = DL.snoc leftovers new remaining' = remaining - BS.length new in if remaining' <= 0 then let (chunks, lastChunk) = chunk targetBlockSizeBytes $ leftoversBytes leftovers' ctx' = MD5.updateCtx ctx chunks in if BS.null lastChunk then fromCtx ctx' DL.empty targetBlockSizeBytes else fromCtx ctx' (DL.singleton lastChunk) (targetBlockSizeBytes - BS.length lastChunk) else fromCtx ctx leftovers' remaining' abstractFinalize ctx leftovers = encode $ MD5.finalize ctx (leftoversBytes leftovers) leftoversBytes = BS.concat . DL.toList chunk target bs = let splitPoint = BS.length bs - (BS.length bs `rem` target) in BS.splitAt splitPoint bs targetBlockSizeBytes = untag (MD5.blockLength :: Tagged MD5.MD5Digest BitLength) `div` 8 forName :: Text -> Maybe HashAlgorithm forName "MD5" = Just MD5 forName _ = Nothing name :: HashAlgorithm -> Text name MD5 = "MD5" #else import qualified Crypto.Hash as C import Data.Byteable (toBytes) data HashAlgorithm = MD4 | MD5 | SHA1 | SHA256 | SHA512 deriving (Read, Show, Eq, Ord, Bounded, Enum) initState :: HashAlgorithm -> HashState initState alg = result where result = case alg of MD4 -> fromCtx (C.hashInit :: C.Context C.MD4) MD5 -> fromCtx (C.hashInit :: C.Context C.MD5) SHA1 -> fromCtx (C.hashInit :: C.Context C.SHA1) SHA256 -> fromCtx (C.hashInit :: C.Context C.SHA256) SHA512 -> fromCtx (C.hashInit :: C.Context C.SHA512) fromCtx :: (C.HashAlgorithm a) => C.Context a -> HashState fromCtx ctx = ctx `seq` HashState { update = abstractUpdate ctx , digest = abstractFinalize ctx } abstractUpdate :: (C.HashAlgorithm a) => C.Context a -> ByteString -> HashState abstractUpdate ctx = fromCtx . C.hashUpdate ctx abstractFinalize :: (C.HashAlgorithm a) => C.Context a -> ByteString abstractFinalize = toBytes . C.hashFinalize forName :: Text -> Maybe HashAlgorithm forName "MD4" = Just MD4 forName "MD5" = Just MD5 forName "SHA1" = Just SHA1 forName "SHA-1" = Just SHA1 forName "SHA-256" = Just SHA256 forName "SHA-512" = Just SHA512 forName _ = Nothing name :: HashAlgorithm -> Text name MD4 = "MD4" name MD5 = "MD5" name SHA1 = "SHA1" -- compat with Java which omits the dash name SHA256 = "SHA-256" name SHA512 = "SHA-512" #endif data HashState = HashState { update :: ByteString -> HashState , digest :: ByteString } class DigestSizable a where digestSize :: a -> Int instance DigestSizable HashState where digestSize = BS.length . digest instance DigestSizable HashAlgorithm where digestSize = digestSize . initState -- this is deliberately non-opaque type HashT = StateT HashState class HashInit a where startState :: a -> HashState instance HashInit HashAlgorithm where startState = initState instance HashInit HashState where startState = id withHashT :: (Monad m, HashInit h) => h -> HashT m a -> m a withHashT = flip evalStateT . startState updateS :: (MonadState HashState m) => ByteString -> m () updateS bs = modify (flip update bs) digestS :: (MonadState HashState m) => m ByteString digestS = liftM digest get digestSizeS :: (MonadState HashState m) => m Int digestSizeS = liftM digestSize get hexString :: ByteString -> ByteString hexString = B16.encode withHashState :: (Monad m) => (HashState -> m (HashState, a)) -> HashT m a withHashState act = do s0 <- get (s1, res) <- lift $ act s0 put s1 return res withHashState' :: (Monad m) => (HashState -> m HashState) -> HashT m () withHashState' act = do s0 <- get s1 <- lift $ act s0 put s1
socrata-platform/ssync
src/main/haskell/SSync/Hash.hs
apache-2.0
5,282
0
17
1,321
1,110
596
514
93
5
-- | Application entry point {-# LANGUAGE RecordWildCards #-} module Main where import Configuration import Data.Configurator (Worth (..), load) import Data.Mongo import Database.MongoDB import Web.Routing main :: IO () main = do conf <- load [Required "app.config"] WebConf {..} <- loadWebConf conf MongoConf {..} <- loadMongoConf conf let scottMsg = "Will run scotty on port: " ++ show wPort mongoMsg = "Will run mongo as:\n" ++ "\tConnection: " ++ show mConnection ++ "\n" ++ "\tDatabase: " ++ show mDatabase ++ "\n" ++ "\tCollection: " ++ show mCollection ++ "\n" putStrLn "Starting up\n" putStrLn scottMsg putStrLn mongoMsg mongoPipe <- mongoConnect mConnection let mongoRunner = createRunner mongoPipe master mDatabase upserter = upsertItem mCollection mongoRunner deleter = deleteItem mCollection mongoRunner putStrLn "Connected to mongo" webApplication upserter deleter wPort putStrLn "Done"
khanage/mongoweb
Main.hs
apache-2.0
1,037
0
18
264
256
122
134
27
1
module Propellor.Property.Grub where import Propellor.Base import qualified Propellor.Property.File as File import qualified Propellor.Property.Apt as Apt -- | Eg, \"hd0,0\" or \"xen/xvda1\" type GrubDevice = String -- | Eg, \"\/dev/sda\" type OSDevice = String type TimeoutSecs = Int -- | Types of machines that grub can boot. data BIOS = PC | EFI64 | EFI32 | Coreboot | Xen -- | Installs the grub package. This does not make grub be used as the -- bootloader. -- -- This includes running update-grub. installed :: BIOS -> Property DebianLike installed bios = installed' bios `onChange` mkConfig -- Run update-grub, to generate the grub boot menu. It will be -- automatically updated when kernel packages are installed. mkConfig :: Property DebianLike mkConfig = tightenTargets $ cmdProperty "update-grub" [] `assume` MadeChange -- | Installs grub; does not run update-grub. installed' :: BIOS -> Property Linux installed' bios = (aptinstall `pickOS` unsupportedOS) `describe` "grub package installed" where aptinstall :: Property DebianLike aptinstall = Apt.installed [debpkg] debpkg = case bios of PC -> "grub-pc" EFI64 -> "grub-efi-amd64" EFI32 -> "grub-efi-ia32" Coreboot -> "grub-coreboot" Xen -> "grub-xen" -- | Installs grub onto a device, so the system can boot from that device. -- -- You may want to install grub to multiple devices; eg for a system -- that uses software RAID. -- -- Note that this property does not check if grub is already installed -- on the device; it always does the work to reinstall it. It's a good idea -- to arrange for this property to only run once, by eg making it be run -- onChange after OS.cleanInstallOnce. boots :: OSDevice -> Property Linux boots dev = tightenTargets $ cmdProperty "grub-install" [dev] `assume` MadeChange `describe` ("grub boots " ++ dev) -- | Use PV-grub chaining to boot -- -- Useful when the VPS's pv-grub is too old to boot a modern kernel image. -- -- <http://notes.pault.ag/linode-pv-grub-chainning/> -- -- The rootdev should be in the form "hd0", while the bootdev is in the form -- "xen/xvda". chainPVGrub :: GrubDevice -> GrubDevice -> TimeoutSecs -> Property DebianLike chainPVGrub rootdev bootdev timeout = combineProperties desc $ props & File.dirExists "/boot/grub" & "/boot/grub/menu.lst" `File.hasContent` [ "default 1" , "timeout " ++ val timeout , "" , "title grub-xen shim" , "root (" ++ rootdev ++ ")" , "kernel /boot/xen-shim" , "boot" ] & "/boot/load.cf" `File.hasContent` [ "configfile (" ++ bootdev ++ ")/boot/grub/grub.cfg" ] & installed Xen & flip flagFile "/boot/xen-shim" xenshim where desc = "chain PV-grub" xenshim = scriptProperty ["grub-mkimage --prefix '(" ++ bootdev ++ ")/boot/grub' -c /boot/load.cf -O x86_64-xen /usr/lib/grub/x86_64-xen/*.mod > /boot/xen-shim"] `assume` MadeChange `describe` "/boot-xen-shim"
ArchiveTeam/glowing-computing-machine
src/Propellor/Property/Grub.hs
bsd-2-clause
2,871
18
13
491
494
287
207
47
5
{-# LANGUAGE OverloadedStrings #-} module Main where import Web.Twitter.Conduit import Common import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.Map as M import System.Environment main :: IO () main = do [screenName] <- getArgs twInfo <- getTWInfoFromEnv mgr <- newManager tlsManagerSettings let sn = ScreenNameParam screenName folids <- runConduit $ sourceWithCursor twInfo mgr (followersIds sn) .| CL.consume friids <- runConduit $ sourceWithCursor twInfo mgr (friendsIds sn) .| CL.consume let folmap = M.fromList $ map (flip (,) True) folids os = filter (\uid -> M.notMember uid folmap) friids bo = filter (\usr -> M.member usr folmap) friids putStrLn "one sided:" print os putStrLn "both following:" print bo
Javran/twitter-conduit
sample/oslist.hs
bsd-2-clause
812
0
14
174
260
131
129
23
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QHostInfo.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Network.QHostInfo ( HostInfoError ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CHostInfoError a = CHostInfoError a type HostInfoError = QEnum(CHostInfoError Int) ieHostInfoError :: Int -> HostInfoError ieHostInfoError x = QEnum (CHostInfoError x) instance QEnumC (CHostInfoError Int) where qEnum_toInt (QEnum (CHostInfoError x)) = x qEnum_fromInt x = QEnum (CHostInfoError x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> HostInfoError -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeNoError HostInfoError where eNoError = ieHostInfoError $ 0 instance QeHostNotFound HostInfoError where eHostNotFound = ieHostInfoError $ 1 instance QeUnknownError HostInfoError where eUnknownError = ieHostInfoError $ 2
keera-studios/hsQt
Qtc/Enums/Network/QHostInfo.hs
bsd-2-clause
2,509
0
18
535
612
310
302
55
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Util.NamedWindows -- Description : Associate the X titles of windows with them. -- Copyright : (c) David Roundy <[email protected]> -- License : BSD3-style (see LICENSE) -- -- Maintainer : none -- Stability : unstable -- Portability : unportable -- -- This module allows you to associate the X titles of windows with -- them. -- ----------------------------------------------------------------------------- module XMonad.Util.NamedWindows ( -- * Usage -- $usage NamedWindow, getName, getNameWMClass, withNamedWindow, unName ) where import Control.Exception as E import XMonad.Prelude ( fromMaybe, listToMaybe, (>=>) ) import qualified XMonad.StackSet as W ( peek ) import XMonad -- $usage -- See "XMonad.Layout.Tabbed" for an example of its use. data NamedWindow = NW !String !Window instance Eq NamedWindow where (NW s _) == (NW s' _) = s == s' instance Ord NamedWindow where compare (NW s _) (NW s' _) = compare s s' instance Show NamedWindow where show (NW n _) = n getName :: Window -> X NamedWindow getName w = withDisplay $ \d -> do -- TODO, this code is ugly and convoluted -- clean it up let getIt = bracket getProp (xFree . tp_value) (fmap (`NW` w) . copy) getProp = (internAtom d "_NET_WM_NAME" False >>= getTextProperty d w) `E.catch` \(SomeException _) -> getTextProperty d w wM_NAME copy prop = fromMaybe "" . listToMaybe <$> wcTextPropertyToTextList d prop io $ getIt `E.catch` \(SomeException _) -> (`NW` w) . resName <$> getClassHint d w -- | Get 'NamedWindow' using 'wM_CLASS' getNameWMClass :: Window -> X NamedWindow getNameWMClass w = withDisplay $ \d -- TODO, this code is ugly and convoluted -- clean it up -> do let getIt = bracket getProp (xFree . tp_value) (fmap (`NW` w) . copy) getProp = getTextProperty d w wM_CLASS copy prop = fromMaybe "" . listToMaybe <$> wcTextPropertyToTextList d prop io $ getIt `E.catch` \(SomeException _) -> (`NW` w) . resName <$> getClassHint d w unName :: NamedWindow -> Window unName (NW _ w) = w withNamedWindow :: (NamedWindow -> X ()) -> X () withNamedWindow f = do ws <- gets windowset whenJust (W.peek ws) (getName >=> f)
xmonad/xmonad-contrib
XMonad/Util/NamedWindows.hs
bsd-3-clause
2,644
0
16
807
630
343
287
44
1
module Inter where class Functor' f where fmap' :: (a -> b) -> f a -> f b -- | tests how to do fmap -- >>> fmap' (3*) [1,2,3] -- [3,6,9] -- Relative Difficulty: 1 instance Functor' [] where fmap' f [] = [] fmap' f (x:xs) = f x : fmap' f xs -- | test: maybe for fmap' -- >>> fmap' (3+) (Just 3) -- Just 6 -- Exercise 2 -- Relative Difficulty: 1 instance Functor' Maybe where fmap' f Nothing = Nothing fmap' f (Just a) = Just (f a) -- Exercise 3 -- Relative Difficulty: 5 -- | test: (->) r for fmap' -- >>> fmap' (3+) (*4) 6 -- 27 instance Functor' ((->) t) where fmap' = (.) -- this shows that Either could be either left or right convention newtype EitherLeft b a = EitherLeft (Either a b) newtype EitherRight a b = EitherRight (Either a b) -- Exercise 4 -- Relative Difficulty: 5 instance Functor' (EitherLeft t) where fmap' f (EitherLeft (Left x)) = EitherLeft (Left (f x)) fmap' f (EitherLeft (Right x))= EitherLeft (Right x) -- Exercise 5 -- Relative Difficulty: 5 instance Functor' (EitherRight t) where fmap' f (EitherRight (Right a)) = EitherRight (Right (f a)) fmap' f (EitherRight (Left x)) = EitherRight (Left x) -- fmap' f (EitherRight z) = EitherRight z --fmap' f x = x class Functor' m => Monad' m where bind' :: (a -> m b) -> m a -> m b bind'' :: m a -> (a -> m b) -> m b return' :: a -> m a -- Exercise 6 -- Relative Difficulty: 3 -- (use bind' and/or return') --fmap'' :: (a -> b) -> m a -> m b -- x = ma --fmap'' f = bind' $ return' . f bind'' = flip bind' -- | -- -- Exercise 7 -- Relative Difficulty: 2 instance Monad' [] where bind' f x = concat (fmap' f x) return' x = [x] -- Exercise 8 -- Relative Difficulty: 2 instance Monad' Maybe where bind' f Nothing = Nothing bind' f (Just x)= f x return' = Just -- Exercise 9 -- Relative Difficulty: 6 instance Monad' ((->) t) where bind' f x = \y -> f (x y) y return' = const -- Exercise 10 -- Relative Difficulty: 6 instance Monad' (EitherLeft t) where bind' f (EitherLeft (Left x)) = f x bind' f (EitherLeft (Right x))= EitherLeft (Right x) return' x = EitherLeft (Left x) -- Exercise 11 -- Relative Difficulty: 6 instance Monad' (EitherRight t) where bind' f (EitherRight (Right x)) = f x bind' f (EitherRight (Left y)) = EitherRight (Left y) return' x = EitherRight (Right x) -- Exercise 12 -- Relative Difficulty: 3 join' :: (Monad' m) => m (m a) -> m a join' mma = bind' id mma -- Exercise 13 -- Relative Difficulty: 6 apply' :: (Monad' m) => m a -> m (a -> b) -> m b -- bind' :: (a - mb) -> ma -> mb -- (\f -> fmap'' f ma) -- apply' = bind' . flip fmap'' apply' ma = bind' $ flip fmap' ma ap :: (Monad' m) => m (a -> b) -> m a -> m b ap mf mx = bind'' mf ( \f -> bind'' mx ( \x -> return' (f x) )) --apply'' :: (Monad' m) => m (a ->b) -> m a -> m b --apply'' ma = bind' $ fmap'' ma -- Exercise 14 -- Relative Difficulty: 6 -- actually a 'forM' forM' :: (Monad' m) => [a] -> (a -> m b) -> m [b] forM' as a_to_mb = foldr fn (return' []) as where fn a mlb = bind' (\x -> bind' (\lb -> return' (x : lb )) mlb ) (a_to_mb a) mapM' :: (Monad' m) => (a -> m b ) -> [a] -> m [b] mapM' a_to_mb = foldr binary_fn (return' []) where binary_fn a mlb = bind'' (a_to_mb a) (\x -> bind'' mlb (\lb -> return' (x : lb) )) -- mb --- bind' (\b -> do some stuff here) mb -- mlb --- bind' (\lb -> do some stuff with [b] here) mlb -- Exercise 15 -- Relative Difficulty: 6 -- (bonus: use moppy) -- (bonus: use forM) seq':: (Monad' m) => [m a] -> m [a] seq' = mapM' id -- Exercise 16 -- Relative Difficulty: 6 -- (bonus: use ap + fmap'') ap' and fmap'' -- <*> :: f (a->b) -> (f a -> f b) lift2' :: (Monad' m) => (a -> b -> c) -> m a -> m b -> m c lift2' f ma mb = f `fmap'` ma `ap` mb -- Exercise 17 -- Relative Difficulty: 6 -- (bonus: use ap + lift2' ) lift3' :: (Monad' m) => (a -> b -> c -> d) -> m a -> m b -> m c -> m d lift3' f ma mb mc = (lift2' f ma mb) `ap` mc -- Exercise 18 -- Relative Difficulty: 6 -- (bonus: use ap + lift3') lift4' :: (Monad' m) => (a -> b -> c -> d -> e) -> m a -> m b -> m c -> m d -> m e lift4' f ma mb mc = ap (lift3' f ma mb mc) newtype State s a = State { state :: (s -> (s, a)) } -- Exercise 19 -- aztecrex -- Relative Difficulty: 9 -- fmap' :: (a ->b) -> f a - > f b -- s -> (s, a) -- apply the function f -- instance Functor' (State s) where fmap' f ms = State $ \s -> let (s', a) = state ms s in (s', f a) -- Exercise 20 -- Relative Difficulty: 10 instance Monad' (State s) where bind' f x = State $ \s -> let (s', a) = state x s in state (f a) s' -- it gets the s' and the a from binding above return' a = State $ \s -> (s, a)
halarnold2000/morris-exercises
src/Inter.hs
bsd-3-clause
4,752
0
15
1,245
1,728
914
814
82
1
{-# LANGUAGE OverloadedStrings, FlexibleInstances #-} import System.Environment(getArgs) import Network import Control.Monad import System.IO(Handle, hFlush, hPutChar) import Data.Aeson import qualified Data.Aeson.Generic as GJ import Data.Maybe import Data.Data import Data.Typeable import qualified Data.ByteString.Lazy.Char8 as L import Domain main = do handle <- connectSocket "localhost" 8080 let name = "rapala" :: String send handle "join" name handleMessages handle connectSocket host port = connectTo host (PortNumber $ fromInteger port) send :: ToJSON a => Handle -> String -> a -> IO () send h msgType msgData = do let json = encode $ object ["msgType" .= msgType, "data" .= msgData] L.hPut h $ json hPutChar h '\n' hFlush h --putStrLn $ ">> " ++ (show json) handleMessages h = do lines <- liftM (L.split '\n') $ L.hGetContents h forM_ lines $ \msg -> do case decode msg of Just json -> do let (msgType, msgData) = fromOk $ fromJSON json handleMessage h msgType msgData Nothing -> fail $ "Error parsing JSON: " ++ (show msg) handleMessage ::Handle -> [Char] -> Value -> IO () handleMessage h "chessboard" boardJson = do let board = fromOk $ GJ.fromJSON boardJson :: ChessBoard putStrLn $ "<< " ++ (show board) instance FromJSON (String, Value) where parseJSON (Object v) = do msgType <- v .: "msgType" msgData <- v .: "data" return (msgType, msgData) parseJSON x = fail $ "Not an JSON object: " ++ (show x) -- JSON helpers -- fromOk (Success x) = x
raimohanska/huskybot
src/Main.hs
bsd-3-clause
1,556
0
20
329
542
272
270
43
2
{-# Language OverloadedStrings #-} {-# Language FlexibleContexts #-} module Hooks.PlusOne where import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Hooks.Algebra import Network.IRC import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString as BS import Text.StringLike (castString) import Text.HTML.TagSoup import Data.Maybe (listToMaybe) import Data.Char (isSpace) import Data.List (find) import Data.Acid.Database import Data.Monoid import Types plusOneHook (PrivMsg nick target msg) = case T.words msg of (which:"+1":_) -> update (PlusOne (T.filter (/= ':') which)) >> respondTo nick target "+1'd" ["!top", n] -> query (TopOnes (read $ T.unpack n)) >>= respondTo nick target . format _ -> return () where format = T.intercalate ", "
MasseR/FreeIrc
src/Hooks/PlusOne.hs
bsd-3-clause
880
0
16
141
280
161
119
25
3
{-# LANGUAGE BangPatterns, CPP #-} module Language.Haskell.GhcMod.Logger ( withLogger , checkErrorPrefix ) where import Bag (Bag, bagToList) import Control.Applicative ((<$>),(*>)) import CoreMonad (liftIO) import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef) import Data.List (isPrefixOf) import Data.Maybe (fromMaybe) import ErrUtils (ErrMsg, errMsgShortDoc, errMsgExtraInfo) import Exception (ghandle) import GHC (DynFlags, SrcSpan, Severity(SevError)) import qualified GHC as G import HscTypes (SourceError, srcErrorMessages) import Language.Haskell.GhcMod.Doc (showPage, getStyle) import Language.Haskell.GhcMod.GHCApi (withDynFlags, withCmdFlags) import qualified Language.Haskell.GhcMod.Gap as Gap import Language.Haskell.GhcMod.Convert (convert') import Language.Haskell.GhcMod.Monad import Language.Haskell.GhcMod.Types (Options(..)) import Outputable (PprStyle, SDoc) import System.FilePath (normalise) ---------------------------------------------------------------- type Builder = [String] -> [String] newtype LogRef = LogRef (IORef Builder) newLogRef :: IO LogRef newLogRef = LogRef <$> newIORef id readAndClearLogRef :: LogRef -> GhcMod String readAndClearLogRef (LogRef ref) = do b <- liftIO $ readIORef ref liftIO $ writeIORef ref id convert' (b []) appendLogRef :: DynFlags -> LogRef -> DynFlags -> Severity -> SrcSpan -> PprStyle -> SDoc -> IO () appendLogRef df (LogRef ref) _ sev src style msg = do let !l = ppMsg src sev df style msg modifyIORef ref (\b -> b . (l:)) ---------------------------------------------------------------- -- | Set the session flag (e.g. "-Wall" or "-w:") then -- executes a body. Logged messages are returned as 'String'. -- Right is success and Left is failure. withLogger :: (DynFlags -> DynFlags) -> GhcMod () -> GhcMod (Either String String) withLogger setDF body = ghandle sourceError $ do logref <- liftIO $ newLogRef wflags <- filter ("-fno-warn" `isPrefixOf`) . ghcOpts <$> options withDynFlags (setLogger logref . setDF) $ do withCmdFlags wflags $ do body *> (Right <$> readAndClearLogRef logref) where setLogger logref df = Gap.setLogAction df $ appendLogRef df logref ---------------------------------------------------------------- -- | Converting 'SourceError' to 'String'. sourceError :: SourceError -> GhcMod (Either String String) sourceError err = do dflags <- G.getSessionDynFlags style <- toGhcMod getStyle ret <- convert' $ (errBagToStrList dflags style . srcErrorMessages $ err) return $ Left ret errBagToStrList :: DynFlags -> PprStyle -> Bag ErrMsg -> [String] errBagToStrList dflag style = map (ppErrMsg dflag style) . reverse . bagToList ---------------------------------------------------------------- ppErrMsg :: DynFlags -> PprStyle -> ErrMsg -> String ppErrMsg dflag style err = ppMsg spn SevError dflag style msg ++ ext where spn = Gap.errorMsgSpan err msg = errMsgShortDoc err ext = showPage dflag style (errMsgExtraInfo err) ppMsg :: SrcSpan -> Severity-> DynFlags -> PprStyle -> SDoc -> String ppMsg spn sev dflag style msg = prefix ++ cts where cts = showPage dflag style msg defaultPrefix | Gap.isDumpSplices dflag = "" | otherwise = checkErrorPrefix prefix = fromMaybe defaultPrefix $ do (line,col,_,_) <- Gap.getSrcSpan spn file <- normalise <$> Gap.getSrcFile spn let severityCaption = Gap.showSeverityCaption sev return $ file ++ ":" ++ show line ++ ":" ++ show col ++ ":" ++ severityCaption checkErrorPrefix :: String checkErrorPrefix = "Dummy:0:0:Error:"
darthdeus/ghc-mod-ng
Language/Haskell/GhcMod/Logger.hs
bsd-3-clause
3,676
0
17
670
1,058
564
494
71
1
{-| Module : Idris.Coverage Description : Clause generation for coverage checking Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE FlexibleContexts, PatternGuards #-} module Idris.Coverage(genClauses, validCoverageCase, recoverableCoverage, mkPatTm) where import Idris.AbsSyntax import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT import Idris.Delaborate import Idris.Elab.Utils import Idris.Error import Control.Monad.State.Strict import Data.Char import Data.List import Data.Maybe -- | Generate a pattern from an 'impossible' LHS. -- -- We need this to eliminate the pattern clauses which have been -- provided explicitly from new clause generation. -- -- This takes a type directed approach to disambiguating names. If we -- can't immediately disambiguate by looking at the expected type, it's an -- error (we can't do this the usual way of trying it to see what type checks -- since the whole point of an impossible case is that it won't type check!) mkPatTm :: PTerm -> Idris Term mkPatTm t = do i <- getIState let timp = addImpl' True [] [] [] i t evalStateT (toTT Nothing timp) 0 where toTT :: Maybe Type -> PTerm -> StateT Int Idris Term toTT ty (PRef _ _ n) = do i <- lift getIState case lookupDefExact n (tt_ctxt i) of Just (TyDecl nt _) -> return $ P nt n Erased _ -> return $ P Ref n Erased toTT ty (PApp _ t@(PRef _ _ n) args) = do i <- lift getIState let aTys = case lookupTyExact n (tt_ctxt i) of Just nty -> map (Just . snd) (getArgTys nty) Nothing -> map (const Nothing) args args' <- zipWithM toTT aTys (map getTm args) t' <- toTT Nothing t return $ mkApp t' args' toTT ty (PApp _ t args) = do t' <- toTT Nothing t args' <- mapM (toTT Nothing . getTm) args return $ mkApp t' args' toTT ty (PDPair _ _ _ l _ r) = do l' <- toTT Nothing l r' <- toTT Nothing r return $ mkApp (P Ref sigmaCon Erased) [Erased, Erased, l', r'] toTT ty (PPair _ _ _ l r) = do l' <- toTT Nothing l r' <- toTT Nothing r return $ mkApp (P Ref pairCon Erased) [Erased, Erased, l', r'] -- For alternatives, pick the first and drop the namespaces. It doesn't -- really matter which is taken since matching will ignore the namespace. toTT (Just ty) (PAlternative _ _ as) | (hd, _) <- unApply ty = do i <- lift getIState case pruneByType True [] hd ty i as of [a] -> toTT (Just ty) a _ -> lift $ ierror $ CantResolveAlts (map getAltName as) toTT Nothing (PAlternative _ _ as) = lift $ ierror $ CantResolveAlts (map getAltName as) toTT ty _ = do v <- get put (v + 1) return (P Bound (sMN v "imp") Erased) getAltName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) | l == txt "Delay" = getAltName (getTm arg) getAltName (PApp _ (PRef _ _ n) _) = n getAltName (PRef _ _ n) = n getAltName (PApp _ h _) = getAltName h getAltName (PHidden h) = getAltName h getAltName x = sUN "_" -- should never happen here -- | Given a list of LHSs, generate a extra clauses which cover the remaining -- cases. The ones which haven't been provided are marked 'absurd' so -- that the checker will make sure they can't happen. -- -- This will only work after the given clauses have been typechecked and the -- names are fully explicit! genClauses :: FC -> Name -> [([Name], Term)] -> -- (Argument names, LHS) [PTerm] -> Idris [PTerm] -- No clauses (only valid via elab reflection). We should probably still do -- a check here somehow, e.g. that one of the arguments is an obviously -- empty type. In practice, this should only really be used for Void elimination. genClauses fc n lhs_tms [] = return [] genClauses fc n lhs_tms given = do i <- getIState let lhs_given = zipWith removePlaceholders lhs_tms (map (stripUnmatchable i) (map flattenArgs given)) logCoverage 5 $ "Building coverage tree for:\n" ++ showSep "\n" (map showTmImpls given) logCoverage 10 $ "Building coverage tree for:\n" ++ showSep "\n" (map show lhs_given) logCoverage 10 $ "From terms:\n" ++ showSep "\n" (map show lhs_tms) let givenpos = mergePos (map getGivenPos given) (cns, ctree_in) <- case simpleCase False (UnmatchedCase "Undefined") False (CoverageCheck givenpos) emptyFC [] [] lhs_given (const []) of OK (CaseDef cns ctree_in _) -> return (cns, ctree_in) Error e -> tclift $ tfail $ At fc e let ctree = trimOverlapping (addMissingCons i ctree_in) let (coveredas, missingas) = mkNewClauses (tt_ctxt i) n cns ctree let covered = map (\t -> delab' i t True True) coveredas let missing = filter (\x -> x `notElem` covered) $ map (\t -> delab' i t True True) missingas logCoverage 5 $ "Coverage from case tree for " ++ show n ++ ": " ++ show ctree logCoverage 2 $ show (length missing) ++ " missing clauses for " ++ show n logCoverage 3 $ "Missing clauses:\n" ++ showSep "\n" (map showTmImpls missing) logCoverage 10 $ "Covered clauses:\n" ++ showSep "\n" (map showTmImpls covered) return missing where flattenArgs (PApp fc (PApp _ f as) as') = flattenArgs (PApp fc f (as ++ as')) flattenArgs t = t getGivenPos :: PTerm -> [Int] getGivenPos (PApp _ _ pargs) = getGiven 0 (map getTm pargs) where getGiven i (Placeholder : tms) = getGiven (i + 1) tms getGiven i (_ : tms) = i : getGiven (i + 1) tms getGiven i [] = [] getGivenPos _ = [] -- Return a list of Ints which are in every list mergePos :: [[Int]] -> [Int] mergePos [] = [] mergePos [x] = x mergePos (x : xs) = intersect x (mergePos xs) removePlaceholders :: ([Name], Term) -> PTerm -> ([Name], Term, Term) removePlaceholders (ns, tm) ptm = (ns, rp tm ptm, Erased) where rp Erased Placeholder = Erased rp tm Placeholder = Inferred tm rp tm (PApp _ pf pargs) | (tf, targs) <- unApply tm = let tf' = rp tf pf targs' = zipWith rp targs (map getTm pargs) in mkApp tf' targs' rp tm (PPair _ _ _ pl pr) | (tf, [tyl, tyr, tl, tr]) <- unApply tm = let tl' = rp tl pl tr' = rp tr pr in mkApp tf [Erased, Erased, tl', tr'] rp tm (PDPair _ _ _ pl pt pr) | (tf, [tyl, tyr, tl, tr]) <- unApply tm = let tl' = rp tl pl tr' = rp tr pr in mkApp tf [Erased, Erased, tl', tr'] rp tm _ = tm mkNewClauses :: Context -> Name -> [Name] -> SC -> ([Term], [Term]) mkNewClauses ctxt fn ns sc = (map (mkPlApp (P Ref fn Erased)) $ mkFromSC True (map (\n -> P Ref n Erased) ns) sc, map (mkPlApp (P Ref fn Erased)) $ mkFromSC False (map (\n -> P Ref n Erased) ns) sc) where mkPlApp f args = mkApp f (map erasePs args) erasePs ap@(App t f a) | (f, args) <- unApply ap = mkApp f (map erasePs args) erasePs (P _ n _) | not (isConName n ctxt) = Erased erasePs tm = tm mkFromSC cov args sc = evalState (mkFromSC' cov args sc) [] mkFromSC' :: Bool -> [Term] -> SC -> State [[Term]] [[Term]] mkFromSC' cov args (STerm _) = if cov then return [args] else return [] -- leaf of provided case mkFromSC' cov args (UnmatchedCase _) = if cov then return [] else return [args] -- leaf of missing case mkFromSC' cov args ImpossibleCase = return [] mkFromSC' cov args (Case _ x alts) = do done <- get if (args `elem` done) then return [] else do alts' <- mapM (mkFromAlt cov args x) alts put (args : done) return (concat alts') mkFromSC' cov args _ = return [] -- Should never happen mkFromAlt :: Bool -> [Term] -> Name -> CaseAlt -> State [[Term]] [[Term]] mkFromAlt cov args x (ConCase c t conargs sc) = let argrep = mkApp (P (DCon t (length args) False) c Erased) (map (\n -> P Ref n Erased) conargs) args' = map (subst x argrep) args in mkFromSC' cov args' sc mkFromAlt cov args x (ConstCase c sc) = let argrep = Constant c args' = map (subst x argrep) args in mkFromSC' cov args' sc mkFromAlt cov args x (DefaultCase sc) = mkFromSC' cov args sc mkFromAlt cov _ _ _ = return [] -- Modify the generated case tree (the case tree builder doesn't have access -- to the context, so can't do this itself). -- Replaces any missing cases with explicit cases for the missing constructors addMissingCons :: IState -> SC -> SC addMissingCons ist sc = evalState (addMissingConsSt ist sc) 0 addMissingConsSt :: IState -> SC -> State Int SC addMissingConsSt ist (Case t n alts) = liftM (Case t n) (addMissingAlts n alts) where addMissingAlt :: CaseAlt -> State Int CaseAlt addMissingAlt (ConCase n i ns sc) = liftM (ConCase n i ns) (addMissingConsSt ist sc) addMissingAlt (FnCase n ns sc) = liftM (FnCase n ns) (addMissingConsSt ist sc) addMissingAlt (ConstCase c sc) = liftM (ConstCase c) (addMissingConsSt ist sc) addMissingAlt (SucCase n sc) = liftM (SucCase n) (addMissingConsSt ist sc) addMissingAlt (DefaultCase sc) = liftM DefaultCase (addMissingConsSt ist sc) addMissingAlts argn as -- | any hasDefault as = map addMissingAlt as | cons@(n:_) <- mapMaybe collectCons as, Just tyn <- getConType n, Just ti <- lookupCtxtExact tyn (idris_datatypes ist) -- If we've fallen through on this argument earlier, then the -- things which were matched in other cases earlier can't be missing -- cases now = let missing = con_names ti \\ cons in do as' <- addCases missing as mapM addMissingAlt as' | consts@(n:_) <- mapMaybe collectConsts as = let missing = nub (map nextConst consts) \\ consts in mapM addMissingAlt (addCons missing as) addMissingAlts n as = mapM addMissingAlt as addCases missing [] = return [] addCases missing (DefaultCase rhs : rest) = do missing' <- mapM (genMissingAlt rhs) missing return (mapMaybe id missing' ++ rest) addCases missing (c : rest) = liftM (c :) $ addCases missing rest addCons missing [] = [] addCons missing (DefaultCase rhs : rest) = map (genMissingConAlt rhs) missing ++ rest addCons missing (c : rest) = c : addCons missing rest genMissingAlt rhs n | Just (TyDecl (DCon tag arity _) ty) <- lookupDefExact n (tt_ctxt ist) = do name <- get put (name + arity) let args = map (name +) [0..arity-1] return $ Just $ ConCase n tag (map (\i -> sMN i "m") args) rhs | otherwise = return Nothing genMissingConAlt rhs n = ConstCase n rhs collectCons (ConCase n i args sc) = Just n collectCons _ = Nothing collectConsts (ConstCase c sc) = Just c collectConsts _ = Nothing getConType n = do ty <- lookupTyExact n (tt_ctxt ist) case unApply (getRetTy (normalise (tt_ctxt ist) [] ty)) of (P _ tyn _, _) -> Just tyn _ -> Nothing -- for every constant in a term (at any level) take next one to make sure -- that constants which are not explicitly handled are covered nextConst (I c) = I (c + 1) nextConst (BI c) = BI (c + 1) nextConst (Fl c) = Fl (c + 1) nextConst (B8 c) = B8 (c + 1) nextConst (B16 c) = B16 (c + 1) nextConst (B32 c) = B32 (c + 1) nextConst (B64 c) = B64 (c + 1) nextConst (Ch c) = Ch (chr $ ord c + 1) nextConst (Str c) = Str (c ++ "'") nextConst o = o addMissingConsSt ist sc = return sc trimOverlapping :: SC -> SC trimOverlapping sc = trim [] [] sc where trim :: [(Name, (Name, [Name]))] -> -- Variable - constructor+args already matched [(Name, [Name])] -> -- Variable - constructors which it can't be SC -> SC trim mustbes nots (Case t vn alts) | Just (c, args) <- lookup vn mustbes = Case t vn (trimAlts mustbes nots vn (substMatch (c, args) alts)) | Just cantbe <- lookup vn nots = let alts' = filter (notConMatch cantbe) alts in Case t vn (trimAlts mustbes nots vn alts') | otherwise = Case t vn (trimAlts mustbes nots vn alts) trim cs nots sc = sc trimAlts cs nots vn [] = [] trimAlts cs nots vn (ConCase cn t args sc : rest) = ConCase cn t args (trim (addMatch vn (cn, args) cs) nots sc) : trimAlts cs (addCantBe vn cn nots) vn rest trimAlts cs nots vn (FnCase n ns sc : rest) = FnCase n ns (trim cs nots sc) : trimAlts cs nots vn rest trimAlts cs nots vn (ConstCase c sc : rest) = ConstCase c (trim cs nots sc) : trimAlts cs nots vn rest trimAlts cs nots vn (SucCase n sc : rest) = SucCase n (trim cs nots sc) : trimAlts cs nots vn rest trimAlts cs nots vn (DefaultCase sc : rest) = DefaultCase (trim cs nots sc) : trimAlts cs nots vn rest substMatch :: (Name, [Name]) -> [CaseAlt] -> [CaseAlt] substMatch ca [] = [] substMatch (c,args) (ConCase cn t args' sc : _) | c == cn = [ConCase c t args (substNames (zip args' args) sc)] substMatch ca (_:cs) = substMatch ca cs substNames [] sc = sc substNames ((n, n') : ns) sc = substNames ns (substSC n n' sc) notConMatch cs (ConCase cn t args sc) = cn `notElem` cs notConMatch cs _ = True addMatch vn cn cs = (vn, cn) : cs addCantBe :: Name -> Name -> [(Name, [Name])] -> [(Name, [Name])] addCantBe vn cn [] = [(vn, [cn])] addCantBe vn cn ((n, cbs) : nots) | vn == n = ((n, nub (cn : cbs)) : nots) | otherwise = ((n, cbs) : addCantBe vn cn nots) -- | Does this error result rule out a case as valid when coverage checking? validCoverageCase :: Context -> Err -> Bool validCoverageCase ctxt (CantUnify _ (topx, _) (topy, _) e _ _) = let topx' = normalise ctxt [] topx topy' = normalise ctxt [] topy in not (sameFam topx' topy' || not (validCoverageCase ctxt e)) where sameFam topx topy = case (unApply topx, unApply topy) of ((P _ x _, _), (P _ y _, _)) -> x == y _ -> False validCoverageCase ctxt (InfiniteUnify _ _ _) = False validCoverageCase ctxt (CantConvert topx topy _) = let topx' = normalise ctxt [] topx topy' = normalise ctxt [] topy in not (sameFam topx' topy') where sameFam topx topy = case (unApply topx, unApply topy) of ((P _ x _, _), (P _ y _, _)) -> x == y _ -> False validCoverageCase ctxt (At _ e) = validCoverageCase ctxt e validCoverageCase ctxt (Elaborating _ _ _ e) = validCoverageCase ctxt e validCoverageCase ctxt (ElaboratingArg _ _ _ e) = validCoverageCase ctxt e validCoverageCase ctxt _ = True -- | Check whether an error is recoverable in the sense needed for -- coverage checking. recoverableCoverage :: Context -> Err -> Bool recoverableCoverage ctxt (CantUnify r (topx, _) (topy, _) e _ _) = let topx' = normalise ctxt [] topx topy' = normalise ctxt [] topy in evalState (checkRec topx' topy') [] recoverableCoverage ctxt (CantConvert topx topy _) = let topx' = normalise ctxt [] topx topy' = normalise ctxt [] topy in evalState (checkRec topx' topy') [] recoverableCoverage ctxt (InfiniteUnify _ _ _) = False -- always unrecoverable recoverableCoverage ctxt (At _ e) = recoverableCoverage ctxt e recoverableCoverage ctxt (Elaborating _ _ _ e) = recoverableCoverage ctxt e recoverableCoverage ctxt (ElaboratingArg _ _ _ e) = recoverableCoverage ctxt e recoverableCoverage _ _ = False -- different notion of recoverable than in unification, since we -- have no metavars -- just looking to see if a constructor is failing -- to unify with a function that may be reduced later, or if any -- variables need to have two different constructor forms -- The state is a mapping of name to what it has failed to unify -- with checkRec :: Term -> Term -> State [(Name, Term)] Bool checkRec (P Bound x _) tm | isCon tm = do nmap <- get case lookup x nmap of Nothing -> do put ((x, tm) : nmap) return True Just y' -> checkRec tm y' where isCon tm | (P yt _ _, _) <- unApply tm, conType yt = True isCon (Constant _) = True isCon _ = False conType (DCon _ _ _) = True conType (TCon _ _) = True conType _ = False checkRec tm (P Bound y _) | isCon tm = do nmap <- get case lookup y nmap of Nothing -> do put ((y, tm) : nmap) return True Just x' -> checkRec tm x' where isCon tm | (P yt _ _, _) <- unApply tm, conType yt = True isCon (Constant _) = True isCon _ = False conType (DCon _ _ _) = True conType (TCon _ _) = True conType _ = False checkRec (App _ f a) p@(P _ _ _) = checkRec f p checkRec (App _ f a) p@(Constant _) = checkRec f p checkRec p@(P _ _ _) (App _ f a) = checkRec p f checkRec p@(Constant _) (App _ f a) = checkRec p f checkRec fa@(App _ _ _) fa'@(App _ _ _) | (f, as) <- unApply fa, (f', as') <- unApply fa' = if (length as /= length as') then checkRec f f' -- Same function but different args is recoverable, -- and vice versa, if it's an ordinary function -- If a constructor, everything has to be recoverable else do fok <- checkRec f f' argok <- checkRecs (f : as) (f : as') return (if conType f then fok && argok else fok || argok) where checkRecs [] [] = return True checkRecs (a : as) (b : bs) = do aok <- checkRec a b asok <- checkRecs as bs return (aok && asok) conType (P (DCon _ _ _) _ _) = True conType (P (TCon _ _) _ _) = True conType (Constant _) = True conType _ = False checkRec (P xt x _) (P yt y _) | x == y = return True | ntRec xt yt = return True where -- If either name is a reference or a bound variable, then further -- development may fix the error, so consider it recoverable. -- If both names are constructors, and the name is different, then -- it's not recoverable ntRec x y | Ref <- x = True | Ref <- y = True | Bound <- x = True | Bound <- y = True | otherwise = False -- name is different, unrecoverable -- A function reference against a constant might be recoverable if we get to -- reduce the function checkRec (P Ref _ _) (Constant _) = return True checkRec (Constant _) (P Ref _ _) = return True checkRec _ _ = return False
uuhan/Idris-dev
src/Idris/Coverage.hs
bsd-3-clause
19,812
0
17
6,418
7,133
3,550
3,583
367
22
{-# LANGUAGE OverloadedStrings #-} module Article.DataSource.Article ( createArticle , getArticle , removeArticle , getArticleIdList , countArticle , updateArticle , updateArticleCover , updateArticleExtra , updateArticleTitle , updateArticleSummary , updateArticleContent , existsArticle ) where import Control.Monad (void) import Database.MySQL.Simple (Only (..), execute, insertID, query, query_) import Yuntan.Types.HasMySQL (MySQL) import Control.Applicative ((<$>)) import Crypto.Hash.SHA1 (hash) import Data.ByteString.Char8 (pack) import Data.Hex (hex) import Data.String (fromString) import Article.Types import Article.Utils (onlyToMaybe) import Control.Monad.IO.Class (liftIO) import Data.Aeson (Value (..), encode) import Data.Int (Int64) import Data.Maybe (listToMaybe) import Data.UnixTime import Prelude hiding (id) import Yuntan.Types.ListResult (From, Size) import Yuntan.Types.OrderBy (OrderBy) createArticle :: Title -> Summary -> Content -> FromURL -> CreatedAt -> MySQL Int64 createArticle title summary content fromURL ct prefix conn = do oldID <- existsArticle fromURL prefix conn ct' <- if ct > 0 then return ct else liftIO $ read . show . toEpochTime <$> getUnixTime case oldID of Just id -> return id Nothing -> do void $ execute conn sql (title, summary, content, fromURL, fromURLHash, ct') fromIntegral <$> insertID conn where fromURLHash = hex $ hash (pack fromURL) sql = fromString $ concat [ "INSERT INTO `", prefix, "_articles` " , "(`title`, `summary`, `content`, `from_url`," , " `from_url_hash`, `created_at`)" , " VALUES " , "( ?, ?, ?, ?, ?, ?)" ] existsArticle :: FromURL -> MySQL (Maybe Int64) existsArticle fromURL prefix conn = onlyToMaybe . listToMaybe <$> query conn sql (Only fromURLHash) where fromURLHash = hex $ hash (pack fromURL) sql = fromString $ concat ["SELECT `id` FROM `", prefix, "_articles` WHERE `from_url_hash` = ?"] getArticle :: ID -> MySQL (Maybe Article) getArticle aid prefix conn = listToMaybe <$> query conn sql (Only aid) where sql = fromString $ concat ["SELECT * FROM `", prefix, "_articles` WHERE `id`=?"] removeArticle :: ID -> MySQL Int64 removeArticle aid prefix conn = execute conn sql (Only aid) where sql = fromString $ concat [ "DELETE FROM `", prefix, "_articles` WHERE `id`=?"] updateArticle :: ID -> Title -> Summary -> Content -> MySQL Int64 updateArticle aid title summary content prefix conn = execute conn sql (title, summary, content, aid) where sql = fromString $ concat [ "UPDATE `", prefix, "_articles` SET `title` = ?, `summary` = ?, `content` = ? WHERE `id` = ?"] updateArticleCover :: ID -> Maybe File -> MySQL Int64 updateArticleCover artId (Just cover) prefix conn = execute conn sql (encode cover, artId) where sql = fromString $ concat [ "UPDATE `", prefix, "_articles` SET `cover` = ? WHERE `id` = ?" ] updateArticleCover artId Nothing prefix conn = execute conn sql (Only artId) where sql = fromString $ concat [ "UPDATE `", prefix, "_articles` SET `cover` = NULL WHERE `id` = ?" ] updateArticleExtra :: ID -> Value -> MySQL Int64 updateArticleExtra artId extra prefix conn = execute conn sql (encode extra, artId) where sql = fromString $ concat [ "UPDATE `", prefix, "_articles` SET `extra` = ? WHERE `id` = ?" ] updateArticleTitle :: ID -> Title -> MySQL Int64 updateArticleTitle aid title prefix conn = execute conn sql (title, aid) where sql = fromString $ concat [ "UPDATE `", prefix, "_articles` SET `title` = ? WHERE `id` = ?" ] updateArticleSummary :: ID -> Summary -> MySQL Int64 updateArticleSummary aid summary prefix conn = execute conn sql (summary, aid) where sql = fromString $ concat [ "UPDATE `", prefix, "_articles` SET `summary` = ? WHERE `id` = ?" ] updateArticleContent :: ID -> Content -> MySQL Int64 updateArticleContent aid content prefix conn = execute conn sql (content, aid) where sql = fromString $ concat [ "UPDATE `", prefix, "_articles` SET `content` = ? WHERE `id` = ?" ] getArticleIdList :: From -> Size -> OrderBy -> MySQL [ID] getArticleIdList from size o prefix conn = map fromOnly <$> query conn sql (from, size) where sql = fromString $ concat [ "SELECT `id` FROM `", prefix, "_articles` ", show o, " LIMIT ?,?" ] countArticle :: MySQL Int64 countArticle prefix conn = maybe 0 fromOnly . listToMaybe <$> query_ conn sql where sql = fromString $ concat [ "SELECT count(*) FROM `", prefix, "_articles`" ]
Lupino/dispatch-article
src/Article/DataSource/Article.hs
bsd-3-clause
4,985
0
14
1,321
1,322
717
605
92
3
module Properties.Failure where import XMonad.StackSet hiding (filter) import qualified Control.Exception as C import System.IO.Unsafe import Data.List (isPrefixOf) -- --------------------------------------------------------------------- -- testing for failure and help out hpc -- -- Since base 4.9.0.0 `error` appends a stack trace. The tests below -- use `isPrefixOf` to only test equality on the error message. -- prop_abort :: Int -> Bool prop_abort _ = unsafePerformIO $ C.catch (abort "fail") check where check (C.SomeException e) = return $ "xmonad: StackSet: fail" `isPrefixOf` show e -- new should fail with an abort prop_new_abort :: Int -> Bool prop_new_abort _ = unsafePerformIO $ C.catch f check where f = new undefined{-layout-} [] [] `seq` return False check (C.SomeException e) = return $ "xmonad: StackSet: non-positive argument to StackSet.new" `isPrefixOf` show e -- TODO: Fix this? -- prop_view_should_fail = view {- with some bogus data -}
xmonad/xmonad
tests/Properties/Failure.hs
bsd-3-clause
1,001
0
10
178
200
113
87
14
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Database.PostgreSQL.Schedule where import Control.Concurrent (forkIO) import Data.Aeson (toJSON, ToJSON, Value) import Data.AffineSpace ((.-.)) import Data.Text (Text) import qualified Data.Text as T import Data.Thyme.Clock (fromSeconds, getCurrentTime, toSeconds, UTCTime) import Data.Thyme.Time (fromGregorian, mkUTCTime, utcTimeToPOSIXSeconds) import qualified Data.Time.Clock as C (UTCTime) import qualified Data.Time.Clock.POSIX as C (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) import Data.Thyme.Format (formatTime) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.Notification import System.IO (stdout, hFlush) import System.Locale (defaultTimeLocale, iso8601DateFormat) import System.Cron.WakeUp import qualified Database.PostgreSQL.Queue as Q ---------------------------------------------------------------------- -- Setup ---------------------------------------------------------------------- -- All the SQL queries are the ones from queue_classic. create :: Connection -> IO () create con = createTable con >> createFunctions con drop :: Connection -> IO () drop con = dropFunctions con >> dropTable con createTable :: Connection -> IO () createTable con = withTransaction con $ execute_ con createTableQuery >> return () dropTable :: Connection -> IO () dropTable con = withTransaction con $ execute_ con dropTableQuery >> return () createFunctions :: Connection -> IO () createFunctions con = withTransaction con $ execute_ con createFunctionsQuery >> return () dropFunctions :: Connection -> IO () dropFunctions con = withTransaction con $ execute_ con dropFunctionsQuery >> return () ---------------------------------------------------------------------- -- Setup query strings ---------------------------------------------------------------------- createTableQuery :: Query createTableQuery = "CREATE TABLE scheduled_jobs (\n\ \ id bigserial PRIMARY KEY,\n\ \ q_name text NOT NULL CHECK(length(q_name) > 0),\n\ \ method text NOT NULL CHECK(length(method) > 0),\n\ \ args json NOT NULL,\n\ \ created_at timestamptz DEFAULT now(),\n\ \ next_push_at timestamptz\n\ \);\n\ \ " dropTableQuery :: Query dropTableQuery = "DROP TABLE IF EXISTS scheduled_jobs" createFunctionsQuery :: Query createFunctionsQuery = "-- humming_schedule_notify function and trigger\n\ \CREATE FUNCTIOn humming_schedule_notify()\n\ \RETURNS TRIGGER AS $$\n\ \BEGIN\n\ \ PERFORM pg_notify('humming_schedule', '');\n\ \ RETURN NULL;\n\ \END;\n\ \$$ LANGUAGE plpgsql;\n\ \\n\ \CREATE TRIGGER humming_schedule_notify\n\ \AFTER UPDATE OR INSERT OR DELETE ON scheduled_jobs\n\ \FOR EACH ROW\n\ \EXECUTE PROCEDURE humming_schedule_notify();\n\ \ " dropFunctionsQuery :: Query dropFunctionsQuery = "DROP FUNCTION IF EXISTS humming_schedule_notify() cascade;" nextScheduledJob :: Connection -> IO (Maybe Task) nextScheduledJob con = do jobs <- query_ con "SELECT id, next_push_at, q_name, method, args FROM scheduled_jobs \ \ORDER BY next_push_at ASC LIMIT 1" case jobs of [] -> return Nothing -- Use Data.Time.Clock ... (i, r::C.UTCTime, q, m, a):_ -> do -- ... then convert from epoch to Thyme's UTCTime. let secondsSinceEpoch = (floor $ C.utcTimeToPOSIXSeconds r) :: Int t = mkUTCTime (fromGregorian 1970 0 0) (fromSeconds secondsSinceEpoch) return . Just $ Task i t q m a Nothing -- TODO Task repetition. ---------------------------------------------------------------------- -- Scheduled jobs ---------------------------------------------------------------------- -- | A `NOTIFY` is automatically sent by a trigger. plan :: ToJSON a => Connection -> Text -> Text -> a -> UTCTime -> IO () plan con name method args at = runInsert con name method args at runInsert :: ToJSON a => Connection -> Text -> Text -> a -> UTCTime -> IO () runInsert con name method args at = do let q = "INSERT INTO scheduled_jobs (q_name, method, args, next_push_at) VALUES (?, ?, ?, ?)" _ <- execute con q (name, method, toJSON args, at') return () where at' = C.posixSecondsToUTCTime $ toSeconds $ utcTimeToPOSIXSeconds at ---------------------------------------------------------------------- -- Job scheduling ---------------------------------------------------------------------- -- | Observe the database and move jobs from scheduled_jobs to -- queue_classic_jobs. schedule :: Connection -> IO () schedule con = wakeupService True $ \request -> do -- Thread to detect a change in the set of jobs. let loop = do mjob <- nextScheduledJob con case mjob of Nothing -> return () Just job -> do putStrLn "The set of scheduled jobs has changed." hFlush stdout amount <- amountToSleep job request amount _ <- execute_ con "LISTEN humming_schedule" -- TODO The Ruby version waits with a timeout. _ <- getNotification con _ <- execute_ con "UNLISTEN humming_schedule" Q.drainNotifications con loop _ <- forkIO loop return . Client $ runTasks con -- | Give a chance to tasks to be run. Return possibly a request to receive -- another wakeup n seconds later. runTasks :: Connection -> IO (Maybe Int) runTasks con = do mtask <- nextScheduledJob con case mtask of Nothing -> return Nothing Just task -> do amount <- amountToSleep task if amount > 0 then do -- Wakeup is too early. putStrLn $ "Next task: " ++ T.unpack (taskMethod task) ++ " @ " ++ formatTime locale format (taskWhen task) hFlush stdout return $ Just amount else do putStrLn $ "Running: " ++ T.unpack (taskMethod task) ++ " @ " ++ formatTime locale format (taskWhen task) hFlush stdout _ <- execute con "INSERT INTO queue_classic_jobs (q_name, method, args) VALUES (?, ?, ?)" (taskQueueName task, taskMethod task, taskArguments task) -- Remove this task. _ <- execute con "DELETE FROM scheduled_jobs WHERE ID=?" [taskId task] -- Select next task and return how long to wait. mtask' <- nextScheduledJob con case mtask' of Nothing -> return Nothing Just task' -> do amount' <- amountToSleep task' putStrLn $ "Next task: " ++ T.unpack (taskMethod task') ++ " @ " ++ formatTime locale format (taskWhen task') hFlush stdout return $ Just amount' where locale = defaultTimeLocale format = iso8601DateFormat $ Just "%H:%M:%S" amountToSleep :: Task -> IO Int amountToSleep Task{..} = do now <- getCurrentTime -- TODO In a recent version of Thyme, we could use `microseconds` instead -- of second * 10^6. return $ ceiling . (* (1000 :: Double)) . (* 1000) . toSeconds $ taskWhen .-. now data Task = Task { taskId :: Int , taskWhen :: UTCTime , taskQueueName :: Text , taskMethod :: Text , taskArguments :: Value , taskRepetition :: Maybe (Maybe Int, Int) -- ^ Possibly repeat the task, possibly a finite number of times, every n -- seconds. }
noteed/humming
Database/PostgreSQL/Schedule.hs
bsd-3-clause
7,340
0
25
1,591
1,527
783
744
129
4
{-| Module : Database.Relational.Into Description : Definition of INTO. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} module Database.Relational.Into ( INTO(..) ) where data INTO term = INTO term
avieth/Relational
Database/Relational/Into.hs
bsd-3-clause
365
0
6
75
28
19
9
4
0
{- | Module : SAWScript.Crucible.Common.MethodSpec Description : Language-neutral method specifications License : BSD3 Maintainer : langston Stability : provisional This module uses GADTs & type families to distinguish syntax-extension- (source language-) specific code. This technique is described in the paper \"Trees That Grow\", and is prevalent across the Crucible codebase. -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE UndecidableInstances #-} module SAWScript.Crucible.Common.MethodSpec where import Data.Constraint (Constraint) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import Data.Time.Clock import Data.Void (Void) import Control.Monad.Trans.Maybe import Control.Monad.Trans (lift) import Control.Lens import Data.Kind (Type) import qualified Prettyprinter as PP import Data.Parameterized.Nonce -- what4 import What4.ProgramLoc (ProgramLoc(plSourceLoc), Position) import qualified Lang.Crucible.Types as Crucible (IntrinsicType, EmptyCtx) import qualified Lang.Crucible.CFG.Common as Crucible (GlobalVar) import qualified Cryptol.Utils.PP as Cryptol import Verifier.SAW.TypedTerm as SAWVerifier import Verifier.SAW.SharedTerm as SAWVerifier import SAWScript.Options import SAWScript.Prover.SolverStats import SAWScript.Utils (bullets) import SAWScript.Proof (TheoremNonce) -- | How many allocations have we made in this method spec? newtype AllocIndex = AllocIndex Int deriving (Eq, Ord, Show) nextAllocIndex :: AllocIndex -> AllocIndex nextAllocIndex (AllocIndex n) = AllocIndex (n + 1) -- | Are we writing preconditions or postconditions? data PrePost = PreState | PostState deriving (Eq, Ord, Show) -------------------------------------------------------------------------------- -- *** Extension-specific information type family CrucibleContext ext :: Type -- | How to specify allocations in this syntax extension type family AllocSpec ext :: Type -- | The type of identifiers for types in this syntax extension type family TypeName ext :: Type -- | The type of types of the syntax extension we're dealing with type family ExtType ext :: Type -- | The types that can appear in casts type family CastType ext :: Type -- | The type of points-to assertions type family PointsTo ext :: Type -- | The type of global allocations type family AllocGlobal ext :: Type -- | The type of \"resolved\" state type family ResolvedState ext :: Type -------------------------------------------------------------------------------- -- ** SetupValue -- | An injective type family mapping type-level booleans to types type family BoolToType (b :: Bool) = (t :: Type) | t -> b where BoolToType 'True = () BoolToType 'False = Void type B b = BoolToType b -- The following type families describe what SetupValues are legal for which -- languages. type family HasSetupNull ext :: Bool type family HasSetupStruct ext :: Bool type family HasSetupArray ext :: Bool type family HasSetupElem ext :: Bool type family HasSetupField ext :: Bool type family HasSetupGlobal ext :: Bool type family HasSetupCast ext :: Bool type family HasSetupUnion ext :: Bool type family HasSetupGlobalInitializer ext :: Bool -- | From the manual: \"The SetupValue type corresponds to values that can occur -- during symbolic execution, which includes both 'Term' values, pointers, and -- composite types consisting of either of these (both structures and arrays).\" data SetupValue ext where SetupVar :: AllocIndex -> SetupValue ext SetupTerm :: TypedTerm -> SetupValue ext SetupNull :: B (HasSetupNull ext) -> SetupValue ext -- | If the 'Bool' is 'True', it's a (LLVM) packed struct SetupStruct :: B (HasSetupStruct ext) -> Bool -> [SetupValue ext] -> SetupValue ext SetupArray :: B (HasSetupArray ext) -> [SetupValue ext] -> SetupValue ext SetupElem :: B (HasSetupElem ext) -> SetupValue ext -> Int -> SetupValue ext SetupField :: B (HasSetupField ext) -> SetupValue ext -> String -> SetupValue ext SetupCast :: B (HasSetupCast ext) -> SetupValue ext -> CastType ext -> SetupValue ext SetupUnion :: B (HasSetupUnion ext) -> SetupValue ext -> String -> SetupValue ext -- | A pointer to a global variable SetupGlobal :: B (HasSetupGlobal ext) -> String -> SetupValue ext -- | This represents the value of a global's initializer. SetupGlobalInitializer :: B (HasSetupGlobalInitializer ext) -> String -> SetupValue ext -- | This constraint can be solved for any ext so long as '()' and 'Void' have -- the constraint. Unfortunately, GHC can't (yet?) reason over the equations -- in our closed type family, and realize that type SetupValueHas (c :: Type -> Constraint) ext = ( c (B (HasSetupNull ext)) , c (B (HasSetupStruct ext)) , c (B (HasSetupArray ext)) , c (B (HasSetupElem ext)) , c (B (HasSetupField ext)) , c (B (HasSetupCast ext)) , c (B (HasSetupUnion ext)) , c (B (HasSetupGlobal ext)) , c (B (HasSetupGlobalInitializer ext)) , c (CastType ext) ) deriving instance (SetupValueHas Show ext) => Show (SetupValue ext) -- TypedTerm is neither Eq nor Ord -- deriving instance (SetupValueHas Eq ext) => Eq (SetupValue ext) -- deriving instance (SetupValueHas Ord ext) => Ord (SetupValue ext) -- | Note that most 'SetupValue' concepts (like allocation indices) -- are implementation details and won't be familiar to users. -- Consider using 'resolveSetupValue' and printing an 'LLVMVal' -- with @PP.pretty@ instead. ppSetupValue :: Show (CastType ext) => SetupValue ext -> PP.Doc ann ppSetupValue setupval = case setupval of SetupTerm tm -> ppTypedTerm tm SetupVar i -> ppAllocIndex i SetupNull _ -> PP.pretty "NULL" SetupStruct _ packed vs | packed -> PP.angles (PP.braces (commaList (map ppSetupValue vs))) | otherwise -> PP.braces (commaList (map ppSetupValue vs)) SetupArray _ vs -> PP.brackets (commaList (map ppSetupValue vs)) SetupElem _ v i -> PP.parens (ppSetupValue v) PP.<> PP.pretty ("." ++ show i) SetupField _ v f -> PP.parens (ppSetupValue v) PP.<> PP.pretty ("." ++ f) SetupUnion _ v u -> PP.parens (ppSetupValue v) PP.<> PP.pretty ("." ++ u) SetupCast _ v tp -> PP.parens (ppSetupValue v) PP.<> PP.pretty (" AS " ++ show tp) SetupGlobal _ nm -> PP.pretty ("global(" ++ nm ++ ")") SetupGlobalInitializer _ nm -> PP.pretty ("global_initializer(" ++ nm ++ ")") where commaList :: [PP.Doc ann] -> PP.Doc ann commaList [] = PP.emptyDoc commaList (x:xs) = x PP.<> PP.hcat (map (\y -> PP.comma PP.<+> y) xs) ppAllocIndex :: AllocIndex -> PP.Doc ann ppAllocIndex i = PP.pretty '@' <> PP.viaShow i ppTypedTerm :: TypedTerm -> PP.Doc ann ppTypedTerm (TypedTerm tp tm) = PP.unAnnotate (ppTerm defaultPPOpts tm) PP.<+> PP.pretty ":" PP.<+> ppTypedTermType tp ppTypedTermType :: TypedTermType -> PP.Doc ann ppTypedTermType (TypedTermSchema sch) = PP.viaShow (Cryptol.ppPrec 0 sch) ppTypedTermType (TypedTermKind k) = PP.viaShow (Cryptol.ppPrec 0 k) ppTypedTermType (TypedTermOther tp) = PP.unAnnotate (ppTerm defaultPPOpts tp) ppTypedExtCns :: TypedExtCns -> PP.Doc ann ppTypedExtCns (TypedExtCns tp ec) = PP.unAnnotate (ppName (ecName ec)) PP.<+> PP.pretty ":" PP.<+> PP.viaShow (Cryptol.ppPrec 0 tp) setupToTypedTerm :: Options {-^ Printing options -} -> SharedContext -> SetupValue ext -> MaybeT IO TypedTerm setupToTypedTerm opts sc sv = case sv of SetupTerm term -> return term _ -> do t <- setupToTerm opts sc sv lift $ mkTypedTerm sc t -- | Convert a setup value to a SAW-Core term. This is a partial -- function, as certain setup values ---SetupVar, SetupNull and -- SetupGlobal--- don't have semantics outside of the symbolic -- simulator. setupToTerm :: Options -> SharedContext -> SetupValue ext -> MaybeT IO Term setupToTerm opts sc = \case SetupTerm term -> return (ttTerm term) SetupStruct _ _ fields -> do ts <- mapM (setupToTerm opts sc) fields lift $ scTuple sc ts SetupArray _ elems@(_:_) -> do ts@(t:_) <- mapM (setupToTerm opts sc) elems typt <- lift $ scTypeOf sc t vec <- lift $ scVector sc typt ts typ <- lift $ scTypeOf sc vec lift $ printOutLn opts Info $ show vec lift $ printOutLn opts Info $ show typ return vec SetupElem _ base ind -> case base of SetupArray _ elems@(e:_) -> do let intToNat = fromInteger . toInteger art <- setupToTerm opts sc base ixt <- lift $ scNat sc $ intToNat ind lent <- lift $ scNat sc $ intToNat $ length elems et <- setupToTerm opts sc e typ <- lift $ scTypeOf sc et lift $ scAt sc lent typ art ixt SetupStruct _ _ fs -> do st <- setupToTerm opts sc base lift $ scTupleSelector sc st ind (length fs) _ -> MaybeT $ return Nothing -- SetupVar, SetupNull, SetupGlobal _ -> MaybeT $ return Nothing -------------------------------------------------------------------------------- -- ** Ghost state -- TODO: This is language-independent, it should be always-true rather than a -- toggle. -- TODO: documentation type family HasGhostState ext :: Bool type GhostValue = "GhostValue" type GhostType = Crucible.IntrinsicType GhostValue Crucible.EmptyCtx type GhostGlobal = Crucible.GlobalVar GhostType -------------------------------------------------------------------------------- -- ** Pre- and post-conditions -------------------------------------------------------------------------------- -- *** StateSpec data SetupCondition ext where SetupCond_Equal :: ProgramLoc -> SetupValue ext -> SetupValue ext -> SetupCondition ext SetupCond_Pred :: ProgramLoc -> TypedTerm -> SetupCondition ext SetupCond_Ghost :: B (HasGhostState ext) -> ProgramLoc -> GhostGlobal -> TypedTerm -> SetupCondition ext deriving instance ( SetupValueHas Show ext , Show (B (HasGhostState ext)) ) => Show (SetupCondition ext) -- | Verification state (either pre- or post-) specification data StateSpec ext = StateSpec { _csAllocs :: Map AllocIndex (AllocSpec ext) -- ^ allocated or declared pointers , _csPointsTos :: [PointsTo ext] -- ^ points-to statements , _csConditions :: [SetupCondition ext] -- ^ equality, propositions, and ghost-variable conditions , _csFreshVars :: [TypedExtCns] -- ^ fresh variables created in this state , _csVarTypeNames :: !(Map AllocIndex (TypeName ext)) -- ^ names for types of variables, for diagnostics } makeLenses ''StateSpec initialStateSpec :: StateSpec ext initialStateSpec = StateSpec { _csAllocs = Map.empty , _csPointsTos = [] , _csConditions = [] , _csFreshVars = [] , _csVarTypeNames = Map.empty } -------------------------------------------------------------------------------- -- *** Method specs -- | How to identify methods in a codebase type family MethodId ext :: Type -- | A body of code in which a method resides -- -- Examples: An 'LLVMModule', a Java 'Codebase' type family Codebase ext :: Type data CrucibleMethodSpecIR ext = CrucibleMethodSpec { _csMethod :: MethodId ext , _csArgs :: [ExtType ext] , _csRet :: Maybe (ExtType ext) , _csPreState :: StateSpec ext -- ^ state before the function runs , _csPostState :: StateSpec ext -- ^ state after the function runs , _csArgBindings :: Map Integer (ExtType ext, SetupValue ext) -- ^ function arguments , _csRetValue :: Maybe (SetupValue ext) -- ^ function return value , _csGlobalAllocs :: [AllocGlobal ext] -- ^ globals allocated , _csCodebase :: Codebase ext -- ^ the codebase this spec was verified against , _csLoc :: ProgramLoc -- ^ where in the SAWscript was this spec? } makeLenses ''CrucibleMethodSpecIR data ProofMethod = SpecAdmitted | SpecProved type SpecNonce ext = Nonce GlobalNonceGenerator (ProvedSpec ext) data ProvedSpec ext = ProvedSpec { _psSpecIdent :: Nonce GlobalNonceGenerator (ProvedSpec ext) , _psProofMethod :: ProofMethod , _psSpec :: CrucibleMethodSpecIR ext , _psSolverStats :: SolverStats -- ^ statistics about the proof that produced this , _psTheoremDeps :: Set TheoremNonce -- ^ theorems depended on by this proof , _psSpecDeps :: Set (SpecNonce ext) -- ^ Other proved specifications this proof depends on , _psElapsedTime :: NominalDiffTime -- ^ The time elapsed during the proof of this specification } makeLenses ''ProvedSpec mkProvedSpec :: ProofMethod -> CrucibleMethodSpecIR ext -> SolverStats -> Set TheoremNonce -> Set (SpecNonce ext) -> NominalDiffTime -> IO (ProvedSpec ext) mkProvedSpec m mspec stats thms sps elapsed = do n <- freshNonce globalNonceGenerator let ps = ProvedSpec n m mspec stats thms sps elapsed return ps -- TODO: remove when what4 switches to prettyprinter prettyPosition :: Position -> PP.Doc ann prettyPosition = PP.viaShow ppMethodSpec :: ( PP.Pretty (MethodId ext) , PP.Pretty (ExtType ext) ) => CrucibleMethodSpecIR ext -> PP.Doc ann ppMethodSpec methodSpec = PP.vcat [ PP.pretty "Name: " <> PP.pretty (methodSpec ^. csMethod) , PP.pretty "Location: " <> prettyPosition (plSourceLoc (methodSpec ^. csLoc)) , PP.pretty "Argument types: " , bullets '-' (map PP.pretty (methodSpec ^. csArgs)) , PP.pretty "Return type: " <> case methodSpec ^. csRet of Nothing -> PP.pretty "<void>" Just ret -> PP.pretty ret ] csAllocations :: CrucibleMethodSpecIR ext -> Map AllocIndex (AllocSpec ext) csAllocations = Map.unions . toListOf ((csPreState <> csPostState) . csAllocs) csTypeNames :: CrucibleMethodSpecIR ext -> Map AllocIndex (TypeName ext) csTypeNames = Map.unions . toListOf ((csPreState <> csPostState) . csVarTypeNames) makeCrucibleMethodSpecIR :: MethodId ext -> [ExtType ext] -> Maybe (ExtType ext) -> ProgramLoc -> Codebase ext -> CrucibleMethodSpecIR ext makeCrucibleMethodSpecIR meth args ret loc code = do CrucibleMethodSpec {_csMethod = meth ,_csArgs = args ,_csRet = ret ,_csPreState = initialStateSpec ,_csPostState = initialStateSpec ,_csArgBindings = Map.empty ,_csRetValue = Nothing ,_csGlobalAllocs = [] ,_csLoc = loc ,_csCodebase = code }
GaloisInc/saw-script
src/SAWScript/Crucible/Common/MethodSpec.hs
bsd-3-clause
15,087
0
17
3,402
3,577
1,890
1,687
283
12
-- Copyright 2013 Kevin Backhouse. {-| This example is a variation on the 'Control.Monad.MultiPass.Example.Assembler.assembler' example. It illustrates how one might convert a control flow graph into a linear sequence of instructions. The example is less complete than the 'Control.Monad.MultiPass.Example.Assembler.assembler' example, so the output is not real machine code. Instead the output is a simple serialised representation of the control flow graph. In this example, the control flow graph is represented as a 'Data.Array.Array', which is an immutable datatype. The example can also be implemented with a mutable representation of the control flow graph, as shown in "Control.Monad.MultiPass.Example.CFG2". -} module Control.Monad.MultiPass.Example.CFG ( Node(..), emitCFG ) where import Control.Monad.ST2 import Control.Monad.MultiPass import Control.Monad.MultiPass.Instrument.EmitST2Array import Control.Monad.MultiPass.Instrument.Knot3 import Control.Monad.MultiPass.Instrument.Delay import Control.Monad.MultiPass.Utils import Data.Array type CFG = Array Node [Node] newtype Node = Node Int deriving (Eq, Ord, Ix) newtype Position = Position Int deriving (Eq, Ord, Ix) instance Num Position where (Position x) + (Position y) = Position (x + y) (Position x) - (Position y) = Position (x - y) (Position x) * (Position y) = Position (x * y) negate (Position x) = Position (negate x) abs (Position x) = Position (abs x) signum (Position x) = Position (signum x) fromInteger x = Position (fromInteger x) type EmitCFGType r w p1 p2 p3 tc = Knot3 (Array Node Position) r w p1 p2 p3 tc -> EmitST2Array Position Int r w p1 p2 p3 tc -> Delay p2 p3 tc -> MultiPassMain r w tc (p3 (ST2Array r w Position Int)) newtype EmitCFG r w p1 p2 p3 tc = EmitCFG (EmitCFGType r w p1 p2 p3 tc) instance MultiPassAlgorithm (EmitCFG r w p1 p2 p3 tc) (EmitCFGType r w p1 p2 p3 tc) where unwrapMultiPassAlgorithm (EmitCFG f) = f emitCFG :: CFG -> ST2 r w (ST2Array r w Position Int) emitCFG g = run $ PassS $ PassS $ PassS $ PassZ $ EmitCFG $ emitMain g emitMain :: (Monad p1, Monad p2, Monad p3) => CFG -> EmitCFGType r w p1 p2 p3 tc emitMain g kn emitter delay12 = mkMultiPassMain (return ()) (\() -> knot3 kn (emitNodes emitter delay12 g)) (\() -> getResult emitter) emitNodes :: (Monad p1, Monad p2, Monad p3) => EmitST2Array Position Int r w p1 p2 p3 tc -> Delay p2 p3 tc -> CFG -> p3 (Array Node Position) -> MultiPass r w tc (p2 (Array Node Position), ()) emitNodes emitter delay12 g offsets = do g' <- pmapM g (emitNode emitter delay12 offsets) return (g', ()) emitNode :: (Monad p1, Monad p2, Monad p3) => EmitST2Array Position Int r w p1 p2 p3 tc -> Delay p2 p3 tc -> p3 (Array Node Position) -> [Node] -> MultiPass r w tc (p2 Position) emitNode emitter delay12 offsets ys = do -- Emit the number of edges. emit emitter (return (length ys)) sequence_ [ do -- Emit a relative offset for each edge. pos <- getIndex emitter emit emitter $ do pos' <- delay delay12 pos offsets' <- offsets let offset = offsets' ! y return (positionDiff offset pos') | y <- ys ] getIndex emitter positionDiff :: Position -> Position -> Int positionDiff (Position a) (Position b) = a - b
kevinbackhouse/Control-Monad-MultiPass
src/Control/Monad/MultiPass/Example/CFG.hs
bsd-3-clause
3,435
0
17
802
1,095
562
533
-1
-1
module ElmFormat.Render.ElmStructureTest where import Elm.Utils ((|>)) import Test.Tasty import Test.Tasty.HUnit import qualified Data.Text.Lazy as LazyText import qualified Data.Text as Text import AST.V0_16 import Box import ElmFormat.Render.ElmStructure trim :: String -> String trim text = text |> LazyText.pack |> LazyText.lines |> map LazyText.stripEnd |> LazyText.unlines |> LazyText.unpack assertLineOutput :: String -> Line -> Assertion assertLineOutput expected actual = assertOutput (expected ++ "\n") (line actual) assertOutput :: String -> Box -> Assertion assertOutput expected actual = assertEqual expected expected $ trim $ Text.unpack $ render $ actual word :: String -> Box word = line . identifier block :: String -> Box block text = stack1 [ line $ row [ w, w ] , line $ row [ w, w ] ] where w = identifier text tests :: TestTree tests = testGroup "ElmFormat.Render.ElmStructure" [ testCase "application (single line)" $ assertOutput "a b c\n" $ application (FAJoinFirst JoinAll) (word "a" ) $ map word [ "b", "c" ] , testCase "application (multiline)" $ assertOutput ( unlines [ "aa" , "aa" , " bb" , " bb" , " c" ] ) $ application (FAJoinFirst JoinAll) ( block "a" ) [ block "b" , line $ identifier "c" ] , testCase "group (empty)" $ assertOutput "()\n" $ group True "(" "," ")" False [] , testCase "group (single item, single line)" $ assertOutput "( foo )\n" $ group True "(" "," ")" False [ word "foo" ] , testCase "group (single line)" $ assertOutput "( foo, bar )\n" $ group True "(" "," ")" False [ word "foo", word "bar" ] , testCase "group (single line, no spaces)" $ assertOutput "(foo, bar)\n" $ group False "(" "," ")" False [ word "foo", word "bar" ] , testCase "group (multiline)" $ assertOutput "( aa\n aa\n, b\n, cc\n cc\n)\n" $ group True "(" "," ")" False [ block "a", word "b", block "c" ] , testCase "group (forced multiline)" $ assertOutput "( a\n, b\n, c\n)\n" $ group True "(" "," ")" True [ word "a", word "b", word "c" ] ]
nukisman/elm-format-short
tests/ElmFormat/Render/ElmStructureTest.hs
bsd-3-clause
2,499
0
12
867
663
342
321
71
1
module Rubik.D2 where import Data.Ix import Rubik.Negate as N import Rubik.Axis as V import Rubik.Turn as T import Rubik.Key as K -- http://en.wikipedia.org/wiki/Cartesian_coordinate_system data D2 = X | Y deriving (Eq,Ord,Show,Enum,Ix) instance Key D2 where universe = [ X, Y ] -- (clockwise) turn turnD2 :: Axis D2 -> Axis D2 turnD2 (Axis X dir) = Axis Y (N.negate dir) turnD2 (Axis Y dir) = Axis X dir -- 4 turns gets back to original value prop_1_turnD2 :: Axis D2 -> Bool prop_1_turnD2 a = turnD2 (turnD2 (turnD2 (turnD2 a))) == a -- any single turn will not give the same value prop_2_turnD2 :: Axis D2 -> Bool prop_2_turnD2 a = turnD2 a /= a
andygill/rubik-solver
src/Rubik/D2.hs
bsd-3-clause
669
0
12
135
232
126
106
17
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} module HVX ( Var , Vars , Vex(..) , Mon(..) -- * Constructors for supported primitives. , Expr(EConst, EVar) , hadd , (+~) , hmul , (*~) , habs , neg , hlog , hexp , logsumexp , hmax , hmin , norm , berhu , huber , quadform , powBaseP0 , powBaseP01 , powBaseP1 , powBaseP1InfEven , powBaseP1InfNotInt -- * Evaluating expressions and their subgradients. , evaluate , jacobianWrtVar -- * Constructors for constraints. , leq , (<=~) , geq , (>=~) , Constraint -- * Solvers and step size functions. , subgradMinimize , subgradMaximize , ellipsoidMinimize , ellipsoidMaximize , decNonSumStep , constStep -- * check validity without calling an optimizer , validVex , ApplyVex ) where import HVX.Primitives import HVX.Internal.DCP import HVX.Internal.Constraints import HVX.Internal.Primitives import HVX.Internal.Solvers import HVX.Internal.SymbolicSubgrad
chrisnc/hvx
src/HVX.hs
bsd-3-clause
997
0
5
234
190
133
57
52
0
{-# LANGUAGE RecordWildCards #-} -- | read/write ImpulseTracker files module Codec.Tracker.IT ( Module(..) , getModule , putModule ) where import Control.Monad import Data.Binary import Data.Binary.Get import Data.Binary.Put import Codec.Tracker.IT.Header import Codec.Tracker.IT.Instrument import Codec.Tracker.IT.Pattern import Codec.Tracker.IT.Sample import Util -- | An ImpulseTracker module data Module = Module { header :: Header , orders :: [Word8] , message :: [Word8] , instruments :: [Instrument] , sampleHeaders :: [SampleHeader] , patterns :: [Pattern] } deriving (Show, Eq) -- | Read a `Module` from the monad state. getModule :: Get Module getModule = label "IT" $ do header <- getHeader message <- getAtOffset (replicateM (fromIntegral $ messageLength header) getWord8) $ messageOffset header orders <- replicateM (fromIntegral (songLength header)) getWord8 insOffsets <- replicateM (fromIntegral (numInstruments header)) getWord32le smpOffsets <- replicateM (fromIntegral (numSamples header)) getWord32le patOffsets <- replicateM (fromIntegral (numPatterns header)) getWord32le instruments <- mapM (getAtOffset getInstrument) insOffsets sampleHeaders <- mapM (getAtOffset getSampleHeader) smpOffsets patterns <- sequence [ if x == 0 then getEmptyPattern else getAtOffset getPattern x | x <- patOffsets ] return Module{..} -- | Write a `Module` to the buffer. putModule :: Module -> Put putModule Module{..} = do putHeader header mapM_ putWord8 orders let body = 192 + length orders + 4 * (length instruments + length sampleHeaders + length patterns) ins = 550 * length instruments samp = 80 * length sampleHeaders mapM_ (putWord32le . fromIntegral) [ length message + body + i * 550 | i <- [0..length instruments - 1]] mapM_ (putWord32le . fromIntegral) [ length message + body + ins + s * 80 | s <- [0..length sampleHeaders - 1]] mapM_ (putWord32le . fromIntegral) $ scanl (\x y -> x + (fromIntegral $ patternLength y)) (body + ins + samp) patterns mapM_ putWord8 message mapM_ putInstrument instruments mapM_ putSampleHeader sampleHeaders mapM_ putPattern patterns
riottracker/modfile
src/Codec/Tracker/IT.hs
bsd-3-clause
2,534
0
15
747
700
359
341
50
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Main(main) where import Dirs(funName) import Goal(simplifyE) import SolutionMap (saveAxiomaticFunSolution) import StorageBackend(localStorage, localSharedStorage , disableRead, disableWrite) import Theory(Name,Expr,parse) import SiteState import Data.Text ( Text ) import qualified Data.Text as Text import Text.Read(readMaybe) import qualified Data.ByteString.Lazy as L import System.Environment(getArgs) import System.IO(hPutStrLn, stderr) import System.Exit(exitFailure) import System.FilePath((</>)) -------------------------------------------------------------------------------- primsDir :: FilePath primsDir = "primitives" main :: IO () main = do args <- getArgs case args of [] -> hPutStrLn stderr "Need a list of primitives." _ -> mapM_ (setPrePost . Text.pack) args setPrePost :: Name -> IO () setPrePost fun = do pre <- getProp preFile post <- getProp postFile let sharedSto = localSharedStorage siteState <- newSiteState (disableWrite localStorage) (disableRead sharedSto) let simp = simplifyE [] x <- saveAxiomaticFunSolution siteState (funName fun) (simp pre) (simp post) print x where preFile = primsDir </> Text.unpack fun </> "pre" postFile = primsDir </> Text.unpack fun </> "post" getProp :: FilePath -> IO Expr getProp file = do txt <- L.readFile file case parse txt of Right a -> return a Left err -> do hPutStrLn stderr (file ++ ": " ++ err) exitFailure
GaloisInc/verification-game
web-prover/exes/SetPrePost.hs
bsd-3-clause
1,724
0
15
462
476
250
226
46
2
module LispVector ( makeVector , vector , vectorSet , vectorLength , vectorRef , vectorToList , vectorFill ) where import Data.Array.IArray import Definition -- size must be >= 0 makeVector :: Int -> a -> SVector a makeVector size val = let (low, high) = getLVecBounds size in array (low, high) $ zip [low..high] (repeat val) vector :: [a] -> SVector a vector vals = let bounds = getLVecBounds $ length vals in listArray bounds vals getLVecBounds :: Int -> (Int, Int) getLVecBounds size = (0, size - 1) vectorSet :: Int -> a -> SVector a -> SVector a vectorSet i val vec = vec // [(i, val)] vectorLength :: SVector a -> Int vectorLength = (+1) . snd . bounds vectorRef :: SVector a -> Int -> a vectorRef = (!) vectorToList :: SVector a -> [a] vectorToList = elems vectorFill :: b -> SVector a -> SVector b vectorFill val = amap (const val)
comraq/scheme-interpreter
src/LispVector.hs
bsd-3-clause
877
0
10
193
348
186
162
30
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Language.Inferno.TRef (TRef, newTRef, readTRef, TransM, writeTRef, tentatively, indubitably) where import Control.Monad.Catch import Control.Monad.Reader import Data.Maybe import Control.Applicative import Data.Typeable import Control.Monad.Ref import Control.Monad.EqRef {- Every cell records both its current (possibly uncommitted) value and its last committed value. A cell is considered stable when these two values are (physically) equal, and unstable otherwise. -} type TransM a m = ReaderT (Ref m [TRef m a]) m data TRef m a = TRef { current :: Ref m a, committed :: Ref m a } instance (MonadEqRef m) => Eq (TRef m a) where tr1 == tr2 = eqRef' (current tr1) (current tr2) && eqRef' (committed tr1) (committed tr2) where eqRef' = eqRef (Proxy :: Proxy m) -- TRefs are not created after the beginning of a transaction -- newTRef :: MonadRef r m => a -> m (TRef r a) newTRef v = do cur <- newRef v com <- newRef v return $ TRef cur com readTRef :: MonadRef m => TRef m a -> m a readTRef cell = readRef (current cell) writeTRef :: (MonadRef m, Eq a) => TRef m a -> a -> TransM a m () writeTRef cell v = do cur <- readRef (current cell) unless (v == cur) $ do com <- readRef (committed cell) when (cur == com) $ do stack <- ask transactions <- readRef stack writeRef stack (cell : transactions) writeRef (current cell) v commit :: (MonadRef m) => TRef m a -> m () commit cell = do cur <- readRef (current cell) writeRef (committed cell) cur rollback :: (MonadRef m) => TRef m a -> m () rollback cell = do com <- readRef (committed cell) writeRef (current cell) com tentatively :: forall a b e m r . (MonadCatch m, MonadRef m, Eq a, Exception e) => Proxy e -> TransM a m b -> m b tentatively _ f = do stack <- newRef [] indubitably f {- (do result <- runReaderT f stack transactions <- readRef stack forM_ transactions commit return result) -} `catch` \(e :: e) -> do transactions <- readRef stack forM_ transactions rollback throwM e indubitably :: forall a b m r . (MonadRef m) => TransM a m b -> m b indubitably f = do stack <- newRef [] result <- runReaderT f stack transactions <- readRef stack forM_ transactions commit return result
sweirich/hs-inferno
src/Language/Inferno/Generic/TRef.hs
bsd-3-clause
2,634
0
15
691
835
418
417
67
1
{-# LANGUAGE TemplateHaskell #-} module Chess.Move.Generator ( -- * Legality checks PseudoLegalMove , Legality , mkPseudo , mkLegality , legalCheck , capturedPiece' , from' , to' -- * Generators , moves , forcingMoves , anyMove ) where import Control.Monad import qualified Data.Foldable as F import Data.List import Data.Maybe import Data.Monoid import Data.Ord import qualified Data.Set as S import Control.Lens hiding (to, from) import Chess.Board import qualified Chess.Board as B (opponent) import Chess.Magic import Chess.Move.Execute import Chess.Move.Move import Data.BitBoard import Data.ChessTypes import qualified Data.ChessTypes as T (opponent) import Data.Square -------------- -- Legality -- -------------- ------------------------------------------------------------------------------ -- | A move that might leave our king in check newtype PseudoLegalMove = PseudoLegalMove Move deriving (Show, Eq, Ord) data Legality = Legality { _board :: Board , _inCheck' :: Bool , _pins :: BitBoard , _nubs :: S.Set PseudoLegalMove } $(makeLenses ''Legality) ------------------------------------------------------------------------------ -- | Move legality checker constructor mkLegality :: Board -> Legality mkLegality b = let checkers = attackedFromBB b (occupancy b) (b^.B.opponent) (myKingPos b) in Legality b (checkers /= mempty) (pinned b) S.empty ------------------------------------------------------------------------------ -- | if the move is legal then Just move and the new Legality legalCheck :: Legality -> PseudoLegalMove -> (Legality, Maybe Move) legalCheck l psm@(PseudoLegalMove m) = if psm `S.member` (l^.nubs) then (l, Nothing) else let f = if l^.inCheck' then legal (l^.board) else ok (l^.board) (l^.pins) nl = (nubs %~ S.insert psm) l in (nl, if f m then Just m else Nothing) ------------------------------------------------------------------------------ -- | Conversion from Move to PseudoLegalMove mkPseudo :: Move -> PseudoLegalMove mkPseudo = PseudoLegalMove capturedPiece' :: PseudoLegalMove -> Maybe PieceType capturedPiece' (PseudoLegalMove m) = m^.capturedPiece from' :: PseudoLegalMove -> Square from' (PseudoLegalMove m) = m^.from to' :: PseudoLegalMove -> Square to' (PseudoLegalMove m) = m^.to ------------------------------------------------------------------------------ -- | Pseudo legal moves moves :: Board -> [ PseudoLegalMove ] moves b = let checkers = attackedFromBB b (occupancy b) (b^.B.opponent) (myKingPos b) cs = simpleChecks b ++ discoveredChecks b ++ pawnSimpleChecks b ++ pawnDiscoveredChecks b ++ castleChecks b ps = pawnCapturesSorted b ++ pawnPromotions b ++ capturesSorted b ++ pawnEnPassants b ts = castleQuiet b nq = quietMovesSorted b ++ pawnQuietMovesSorted b in map PseudoLegalMove $ if checkers /= mempty then defendCheck b checkers else cs ++ ps ++ ts ++ nq ------------------------------------------------------------------------------ -- | Checks, captures and promotions, or moving out of check forcingMoves :: Board -> [ PseudoLegalMove ] forcingMoves b = let checkers = attackedFromBB b (occupancy b) (b^.B.opponent) (myKingPos b) ms = simpleChecks b ++ discoveredChecks b ++ pawnSimpleChecks b ++ pawnDiscoveredChecks b ++ castleChecks b ++ pawnCapturesSorted b ++ pawnPromotions b ++ capturesSorted b ++ pawnEnPassants b in map PseudoLegalMove $ if checkers /= mempty then defendCheck b checkers else ms ------------------------------------------------------------------------------ -- | Is there a legal move? anyMove :: Board -> Bool anyMove b = let pins' = pinned b checkers = attackedFromBB b (occupancy b) (b^.B.opponent) (myKingPos b) in if checkers /= mempty then any (legal b) $ defendCheck b checkers else or [ any (ok b pins') ms | ms <- [ quietMoves b , pawnQuietMoves b , captures b , pawnCaptures b , simpleChecks b , pawnSimpleChecks b , discoveredChecks b , pawnDiscoveredChecks b , pawnEnPassants b , pawnPromotions b ] ] ------------------------------------------------------------------------------ -- Legality check (fast). Check if the moving piece is not pinned. King is -- also handled here. ok :: Board -> BitBoard -> Move -> Bool ok b pins' m = case m^.piece of King -> legal b m _ -> (pins' .&. fromSquare (m^.from)) == mempty -- not pinned -- or pinned, but staying in line with the King || lineBB (myKingPos b) (m^.to) .&. fromSquare (m^.from) /= mempty || lineBB (myKingPos b) (m^.from) .&. fromSquare (m^.to) /= mempty ------------------------------------------------------------------------------ -- Legality check (slow). Makes the move and then checks whether our own king -- is in check legal :: Board -> Move -> Bool legal b m = not $ inCheck (makeMoveSimplified m b) (b^.next) --------------------------------------------- -- Move generation in case we are in check -- --------------------------------------------- ------------------------------------------------------------------------------ defendCheck :: Board -> BitBoard -> [ Move ] defendCheck b checkers = let numCheckers = popCount checkers in case numCheckers of 1 -> let checker = head $ toList checkers in captureChecker b checker ++ blockSlider b checker ++ moveKing b 2 -> moveKing b _ -> error "unexpected number of checkers" ------------------------------------------------------------------------------ -- Captures the checking piece (generates pseudo legal moves) captureChecker :: Board -> Square -> [ Move ] captureChecker b checker = let pt = fromJust $ pieceAt b checker in sortBy captureHeuristics $ map (capturedPiece .~ Just pt) $ captureTo b checker ------------------------------------------------------------------------------ -- Blocks a slider piece blockSlider :: Board -> Square -> [ Move ] blockSlider b checker = sortBy moveValHeuristics $ concat $ do let endSquares = piecesOf b (b^.next) King .|. fromSquare checker t <- toList $ lineBB (myKingPos b) checker .&. complement endSquares return $ moveTo b t ------------------------------------------------------------------------------ moveKing :: Board -> [ Move ] moveKing b = do t <- toList $ moveFun b King (myKingPos b) .&. complement (myPieces b) return $ (capturedPiece .~ pieceAt b t) $ defaultMove (myKingPos b) t King (b^.next) ------------------------------------------------------------------------------ -- moves capturing on the given square. This function doesn't set the -- capturedPiece. This function is used for capturing the checking piece. captureTo :: Board -> Square -> [ Move ] captureTo b t = do pt <- [ Pawn, Knight, Bishop, Rook, Queen, King ] let sqrs = if pt == Pawn then pawnAttackBB t (b^.B.opponent) else moveFun b pt t pcs = sqrs .&. piecesOf b (b^.next) pt f <- toList pcs return $ defaultMove f t pt (b^.next) ------------------------------------------------------------------------------ -- moving to the specified square (non capture) to block a check moveTo :: Board -> Square -> [ Move ] moveTo b t = do pt <- [ Pawn, Knight, Bishop, Rook, Queen ] let pwn = filter (\(_, t', _) -> t' == t) $ pawnAdvanceSquares b sqrs = if pt == Pawn then foldr ((<>) . fromSquare . (\(f, _, _) -> f)) mempty pwn else moveFun b pt t pcs = sqrs .&. piecesOf b (b^.next) pt f <- toList pcs return $ defaultMove f t pt (b^.next) ------------------------------------------------------------------------------ -- | enemy king position eKingPos :: Board -> Square eKingPos b = kingByColour (b^.B.opponent) b {-# INLINE eKingPos #-} ------------------------------------------------------------------------------ -- | my king position myKingPos :: Board -> Square myKingPos b = kingByColour (b^.next) b {-# INLINE myKingPos #-} ------------------------------------------------------------------------------ -- | knight, bishop, rook, queen simple checks - not discovered check simpleChecks :: Board -> [ Move ] simpleChecks b = do pt <- [ Queen, Rook, Bishop, Knight ] let kingMoves = moveFun b pt (eKingPos b) .&. complement (myPieces b) f <- toList $ piecesOf b (b^.next) pt let pieceMoves = moveFun b pt f common = kingMoves .&. pieceMoves -- common should be mempty most of the time, so we should -- short circuit the calcualtion from this point t <- toList common guard $ moveValid pt f t return $ (capturedPiece .~ pieceAt b t) $ defaultMove f t pt (b^.next) where moveValid Knight f t = let hd = hDist f t vd = vDist f t in (hd == 1 && vd == 2) || (hd == 2 && vd == 1) moveValid Bishop f t = hDist f t == vDist f t moveValid Rook f t = hDist f t == 0 || vDist f t == 0 moveValid Queen f t = moveValid Rook f t || moveValid Bishop f t moveValid _ _ _ = error "unexpected piece type" ------------------------------------------------------------------------------ -- | discovered checks (with any piece type except pawns) discoveredChecks :: Board -> [ Move ] discoveredChecks b = do pt <- [ Queen, Rook, Bishop, Knight, King ] let ps = piecesOf b (b^.next) pt .&. discoverer b -- ps should be mempty most of the time.. f <- toList ps t <- toList $ moveFun b pt f .&. complement (myPieces b) -- make sure that the enemy king is in check.. guard $ inRayCheck b (occupancy b `xor` fromSquare f `xor` fromSquare t) return $ (capturedPiece .~ pieceAt b t) $ defaultMove f t pt (b^.next) ------------------------------------------------------------------------------ inRayCheck :: Board -> BitBoard -> Bool inRayCheck b occ = or $ do pt <- [ Queen, Rook, Bishop ] -- King casting rays .. let eKingRay = magic pt (eKingPos b) occ return $ mempty /= eKingRay .&. myPiecesOf b pt ------------------------------------------------------------------------------ castleChecks :: Board -> [ Move ] castleChecks = flip castleMoves True ------------------------------------------------------------------------------ pawnDiscoveredChecks :: Board -> [ Move ] pawnDiscoveredChecks b = pawnMoves b (\f _ -> fromSquare f .&. discoverer b /= mempty) ------------------------------------------------------------------------------ pawnSimpleChecks :: Board -> [ Move ] pawnSimpleChecks b = let kp = [ offset (eKingPos b) (direction (b^.B.opponent) lr) | lr <- [ 7, 9] ] in pawnMoves b (\_ t -> F.any (== t) kp) ------------------------------------------------------------------------------ pawnPromotions :: Board -> [ Move ] pawnPromotions b = let opSecond = rankBB $ case b^.next of White -> seventhRank Black -> secondRank in pawnMoves b (\f _ -> fromSquare f .&. opSecond /= mempty) ------------------------------------------------------------------------------ pawnCaptures :: Board -> [ Move ] pawnCaptures b = pawnMoves b (\_ t -> (fromSquare t .&. opponentsPieces b) /= mempty) ------------------------------------------------------------------------------ pawnCapturesSorted :: Board -> [ Move ] pawnCapturesSorted = sortBy captureHeuristics . pawnCaptures ------------------------------------------------------------------------------ pawnEnPassants :: Board -> [ Move ] pawnEnPassants b = do (f, t, enp) <- pawnEnPassantSquares b return $ (enPassantTarget .~ enp) $ defaultMove f t Pawn (b^.next) ------------------------------------------------------------------------------ -- pieces that can give discovered checks discoverer :: Board -> BitBoard discoverer b = discovererOrPinned b (b^.B.opponent) (b^.next) ------------------------------------------------------------------------------ -- pieces that are pinned pinned :: Board -> BitBoard pinned b = discovererOrPinned b (b^.next) (b^.next) ------------------------------------------------------------------------------ discovererOrPinned :: Board -> Colour -- ^ Colour of the King -> Colour -- ^ Colour of the Piece that is pinned or gives discovered check -> BitBoard discovererOrPinned b c1 c2 = mconcat $ do pt <- [ Rook, Bishop ] let kingPos = kingByColour c1 b -- King casting rays .. kingRay = pseudoAttackBB pt kingPos -- magic pt kingPos (occupancy b) casters = kingRay .&. (piecesOf b (T.opponent c1) pt <> piecesOf b (T.opponent c1) Queen) caster <- toList casters let inBetween = lineBB kingPos caster `xor` fromSquare kingPos `xor` fromSquare caster guard (popCount (inBetween .&. occupancy b) < 2) return $ inBetween .&. piecesByColour b c2 ------------------------------------------------------------------------------ captures :: Board -> [ Move ] captures b = normMoveGen b (opponentsPieces b) ------------------------------------------------------------------------------ capturesSorted :: Board -> [ Move ] capturesSorted = sortBy captureHeuristics . captures ------------------------------------------------------------------------------ quietMoves :: Board -> [ Move ] quietMoves b = normMoveGen b (vacated b) ------------------------------------------------------------------------------ quietMovesSorted :: Board -> [ Move ] quietMovesSorted = sortBy moveValHeuristics . quietMoves ------------------------------------------------------------------------------ castleQuiet :: Board -> [ Move ] castleQuiet b = castleMoves b False ------------------------------------------------------------------------------ pawnQuietMoves :: Board -> [ Move ] pawnQuietMoves b = do (f, t, _) <- pawnAdvanceSquares b concatMap promote [ defaultMove f t Pawn (b^.next) ] ------------------------------------------------------------------------------ pawnQuietMovesSorted :: Board -> [ Move ] pawnQuietMovesSorted = sortBy moveValHeuristics . pawnQuietMoves ------------------------------------------------------------------------------ -- captures or quiet moves normMoveGen :: Board -> BitBoard -> [ Move ] normMoveGen b filt = do pt <- [ Queen, Rook, Bishop, Knight, King ] let ps = piecesOf b (b^.next) pt f <- toList ps t <- toList $ moveFun b pt f .&. filt return $ (capturedPiece .~ pieceAt b t) $ defaultMove f t pt (b^.next) ------------------------------------------------------------------------------ moveFun :: Board -> PieceType -> Square -> BitBoard moveFun b pt | pt == Knight = knightAttackBB | pt == King = kingAttackBB | pt == Pawn = error "moveFun is not implemented for Pawns" | otherwise = \t -> magic pt t (occupancy b) ------------------------------------------------------------------------------ pawnMoves :: Board -> (Square -> Square -> Bool) -> [ Move ] pawnMoves b fun = do (f, t, enp) <- pawnAdvanceSquares b ++ pawnCaptureSquares b ++ pawnEnPassantSquares b guard $ fun f t map (enPassantTarget .~ enp) $ promote $ (capturedPiece .~ pieceAt b t) $ defaultMove f t Pawn (b^.next) ------------------------------------------------------------------------------ promote :: Move -> [ Move ] promote m = if fromSquare (m^.to) .&. (rankBB firstRank .|. rankBB eighthRank) /= mempty then do promo <- [ Queen, Rook, Knight, Bishop ] return $ (promotion .~ Just promo) m else [ m ] ------------------------------------------------------------------------------ -- | Pawn captures (from, to) including promotions, excluding advances or -- en Passant pawnCaptureSquares :: Board -> [ (Square, Square, Maybe Square) ] pawnCaptureSquares b = do let myPawns = myPiecesOf b Pawn -- files from which we can left/right capture cFiles 7 White = complement $ fileBB aFile cFiles 9 White = complement $ fileBB hFile cFiles 7 Black = complement $ fileBB hFile cFiles 9 Black = complement $ fileBB aFile cFiles _ _ = error "Unexpected numbers" capture <- [7, 9] -- left and right capture target <- toList $ opponentsPieces b .&. ((myPawns .&. cFiles capture (b^.next)) `shift` direction (b^.next) capture) return (offset target (direction (b^.B.opponent) capture), target, Nothing) ------------------------------------------------------------------------------ -- Pawn advances (from, to) including promotions, excluding captures pawnAdvanceSquares :: Board -> [ (Square, Square, Maybe Square) ] pawnAdvanceSquares b = do step <- [ 1, 2 ] let myPawns' = myPiecesOf b Pawn myPawns = if step == 1 then myPawns' else myPawns' .&. mySecond mySecond = rankBB $ if b^.next == White then secondRank else seventhRank unblocked = complement $ foldl1 (<>) [ occupancy b `shift` direction (b^.next) (-8 * j) | j <- [ 1 .. step ] ] pawn <- toList $ myPawns .&. unblocked return (pawn, offset pawn $ step * direction (b^.next) 8, Nothing) ------------------------------------------------------------------------------ pawnEnPassantSquares :: Board -> [ (Square, Square, Maybe Square) ] pawnEnPassantSquares b = case b^.enPassant of Just square -> do pawn <- toList $ (fromSquare (offset square 1) .|. fromSquare (offset square (-1))) .&. largeNeighbourFilesBB (file square) .&. myPiecesOf b Pawn return (pawn, offset square $ direction (b^.next) 8, Just square) Nothing -> [] ------------------------------------------------------------------------------ captureHeuristics :: Move -> Move -> Ordering captureHeuristics = comparing (Down . pieceValue . fromJust . view capturedPiece) ------------------------------------------------------------------------------ moveValHeuristics :: Move -> Move -> Ordering moveValHeuristics = comparing (Down . moveValue) ------------------------------------------------------------------------------ castleMoves :: Board -> Bool -> [ Move ] castleMoves b chk = do side <- toCastleList $ b^.castleRightsByColour (b^.next) let kRays = magic Rook (eKingPos b) (occupancy b) (f, t) = kingCastleMove (b^.next) side rt = toEnum $ (fromEnum f + fromEnum t) `div` 2 checkSqrs = toList $ checkCastleBB (b^.next) side guard $ chk /= (fromSquare rt .&. kRays == mempty) guard $ (vacancyCastleBB (b^.next) side .&. occupancy b) == mempty guard $ not $ F.any (isAttacked b (b^.B.opponent)) checkSqrs return $ (castle .~ Just side) $ defaultMove f t King $ b^.next ------------------------------------------------------------------------------ vacancyCastleBB :: Colour -> Castle -> BitBoard vacancyCastleBB White Long = mconcat [ fromSquare sq | sq <- [(toSquare bFile firstRank) .. (toSquare dFile firstRank)] ] vacancyCastleBB White Short = mconcat [ fromSquare sq | sq <- [(toSquare fFile firstRank) .. (toSquare gFile firstRank)] ] vacancyCastleBB Black Long = mconcat [ fromSquare sq | sq <- [(toSquare bFile eighthRank) .. (toSquare dFile eighthRank)] ] vacancyCastleBB Black Short = mconcat [ fromSquare sq | sq <- [(toSquare fFile eighthRank) .. (toSquare gFile eighthRank)] ] {-# INLINE vacancyCastleBB #-} ------------------------------------------------------------------------------ checkCastleBB :: Colour -> Castle -> BitBoard checkCastleBB White Long = mconcat [ fromSquare sq | sq <- [(toSquare cFile firstRank) .. (toSquare eFile firstRank)] ] checkCastleBB White Short = mconcat [ fromSquare sq | sq <- [(toSquare eFile firstRank) .. (toSquare gFile firstRank)] ] checkCastleBB Black Long = mconcat [ fromSquare sq | sq <- [(toSquare cFile eighthRank) .. (toSquare eFile eighthRank)] ] checkCastleBB Black Short = mconcat [ fromSquare sq | sq <- [(toSquare eFile eighthRank) .. (toSquare gFile eighthRank)] ] {-# INLINE checkCastleBB #-} ------------------------------------------------------------------------------ kingCastleMove :: Colour -> Castle -> (Square, Square) kingCastleMove White Long = (toSquare eFile firstRank, toSquare cFile firstRank) kingCastleMove White Short = (toSquare eFile firstRank, toSquare gFile firstRank) kingCastleMove Black Long = (toSquare eFile eighthRank, toSquare cFile eighthRank) kingCastleMove Black Short = (toSquare eFile eighthRank, toSquare gFile eighthRank) {-# INLINE kingCastleMove #-}
phaul/chess
Chess/Move/Generator.hs
bsd-3-clause
21,658
0
20
5,061
5,725
2,968
2,757
387
5
module ImageQuery.Parser where import ImageQuery ( ImageQueryStatement(SetImageQueryParameter,GetImageQueryResult), ImageQueryParameter(Threshold,Channel,Smoothing,SubRect,StencilImage,Polarity), ImageQuery(TableQuery,IslandImage,ImageOfAverage,LineImage,AreaHistogram), TableQuery(ValueInPoint,AverageAroundPoint,AverageOfImage,IslandQuery), IslandQuery(NumberOfIslands,AverageAreaOfIslands,AverageOutlineOfIslands), Polarity(Bright,Dark), Orientation(Horizontal,Vertical), Channel(Red,Green,Blue), Power(One,OneOverTwo,ThreeOverTwo)) import Text.Parsec ( sepEndBy,newline,choice,try,string,spaces,digit,many1,(<|>),many,noneOf) import Text.Parsec.String (Parser) import Control.Monad (replicateM) imageQueriesParser :: Parser [ImageQueryStatement] imageQueriesParser = imageQueryParser `sepEndBy` newline imageQueryParser :: Parser ImageQueryStatement imageQueryParser = choice [setPropertyParser,tableQueryParser,outputParser] setPropertyParser :: Parser ImageQueryStatement setPropertyParser = choice (map try (map (fmap SetImageQueryParameter) [ thresholdParser, channelParser, smoothingParser, subrectParser, stencilParser, polarityParser])) thresholdParser :: Parser ImageQueryParameter thresholdParser = do string "set_threshold" spaces thresholdstring <- digits return (Threshold (read thresholdstring)) channelParser :: Parser ImageQueryParameter channelParser = do string "set_channel" spaces channeltype <- channelTypeParser return (Channel channeltype) smoothingParser :: Parser ImageQueryParameter smoothingParser = do string "set_smoothing" spaces smoothingstring <- digits return (Smoothing (read smoothingstring)) subrectParser :: Parser ImageQueryParameter subrectParser = do string "set_subrect" [x,y,w,h] <- replicateM 4 (do spaces numberstring <- digits return (read numberstring)) return (SubRect (x,y,w,h)) stencilParser :: Parser ImageQueryParameter stencilParser = do string "set_stencil" spaces stencilFilePath <- many (noneOf ['\n']) return (StencilImage stencilFilePath Nothing) polarityParser :: Parser ImageQueryParameter polarityParser = do string "set_polarity" spaces polarity <- polarityTypeParser return (Polarity polarity) tableQueryParser :: Parser ImageQueryStatement tableQueryParser = choice (map try (map (fmap (GetImageQueryResult . TableQuery)) [ valueInPointParser, averageAroundPointParser, averageOfImageParser, numberOfIslandsParser, averageAreaOfIslandsParser, averageOutlineOfIslandsParser])) valueInPointParser :: Parser TableQuery valueInPointParser = do string "table_value_in_point" spaces xstring <- digits spaces ystring <- digits return (ValueInPoint (read xstring) (read ystring)) averageAroundPointParser :: Parser TableQuery averageAroundPointParser = do string "table_average_around_point" spaces xstring <- digits spaces ystring <- digits spaces rstring <- digits return (AverageAroundPoint (read xstring) (read ystring) (read rstring)) averageOfImageParser :: Parser TableQuery averageOfImageParser = do string "table_average_of_image" return AverageOfImage numberOfIslandsParser :: Parser TableQuery numberOfIslandsParser = do string "table_number_of_islands" return (IslandQuery NumberOfIslands) averageAreaOfIslandsParser :: Parser TableQuery averageAreaOfIslandsParser = do string "table_average_area_of_islands" return (IslandQuery AverageAreaOfIslands) averageOutlineOfIslandsParser :: Parser TableQuery averageOutlineOfIslandsParser = do string "table_average_outline_of_islands" return (IslandQuery AverageOutlineOfIslands) outputParser :: Parser ImageQueryStatement outputParser = choice (map try (map (fmap GetImageQueryResult) [ islandImagesParser, averageImageParser, lineImageParser, areaHistogramParser])) islandImagesParser :: Parser ImageQuery islandImagesParser = do string "output_island_images" return IslandImage averageImageParser :: Parser ImageQuery averageImageParser = do string "output_average_image" return ImageOfAverage lineImageParser :: Parser ImageQuery lineImageParser = do string "output_line_image" spaces orientation <- orientationParser spaces xstring <- digits spaces ystring <- digits spaces lstring <- digits return (LineImage orientation (read xstring) (read ystring) (read lstring)) areaHistogramParser :: Parser ImageQuery areaHistogramParser = do string "output_area_histogram" spaces binsize <- digits spaces power <- powerParser return (AreaHistogram (read binsize) power) orientationParser :: Parser Orientation orientationParser = (string "horizontal" >> return Horizontal) <|> (string "vertical" >> return Vertical) polarityTypeParser :: Parser Polarity polarityTypeParser = (string "bright" >> return Bright) <|> (string "dark" >> return Dark) channelTypeParser :: Parser Channel channelTypeParser = (string "red" >> return Red) <|> (string "green" >> return Green) <|> (string "blue" >> return Blue) powerParser :: Parser Power powerParser = (string "one" >> return One) <|> (string "one_over_two" >> return OneOverTwo) <|> (string "three_over_two" >> return ThreeOverTwo) digits :: Parser String digits = many1 digit
phischu/pem-images
src/ImageQuery/Parser.hs
bsd-3-clause
5,470
0
14
912
1,410
721
689
157
1
{-# LANGUAGE OverloadedStrings #-} module Crawl.BadForms where import Data.List (find) import qualified Data.HashMap.Strict as H import Crawl.Move import Crawl.Status data Form = Normal | Tree | Fungus | Spider | Pig | Wisp filterLegalInForm :: Player -> Maybe Move -> Maybe Move filterLegalInForm p (Just (Go _ _)) | hasStatus "Fear" p || hasStatus "Mesm" p = Just Rest filterLegalInForm p (Just (Attack dx dy)) | isConfused p = filterLegalInForm p (Just (Go dx dy)) filterLegalInForm p (Just m) | legalInForm p m = Just m filterLegalInForm _ _ = Nothing legalInForm :: Player -> Move -> Bool legalInForm p m = case (form, m) of (_, ScanItem _ _) -> True (Spider, Wield _) -> False (Spider, Wear _) -> False (Spider, TakeOff _) -> False (Pig, Wield _) -> False (Pig, Wear _) -> False (Pig, TakeOff _) -> False (Wisp, Wield _) -> False (Wisp, Wear _) -> False (Wisp, TakeOff _) -> False (Tree, Attack _ _) -> True (Tree, Rest) -> True (Tree, LongRest) -> True (Tree, _) -> False (Fungus, Go _ _) -> False (Fungus, Wield _) -> False (Fungus, Wear _) -> False (Fungus, TakeOff _) -> False (_, _) -> True where form = maybe Normal snd $ find (\(light, _) -> light `H.member` _statuses p) badforms badforms = [("Tree", Tree), ("Fungus", Fungus), ("Spider", Spider), ("Pig", Pig), ("Wisp", Wisp)]
rwbarton/rw
Crawl/BadForms.hs
bsd-3-clause
1,353
0
12
289
624
337
287
38
19
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} module Network.BitTorrent.Client ( -- * Options Options (..) -- * Client session , Client -- ** Session data , clientPeerId , clientListenerPort , allowedExtensions -- ** Session initialization , LogFun , newClient , closeClient , withClient , simpleClient -- * BitTorrent monad , MonadBitTorrent (..) , BitTorrent , runBitTorrent , getClient -- * Handle , Handle , handleTopic , handleTrackers , handleExchange -- ** Construction , TorrentSource (..) , closeHandle -- ** Query , getHandle , getIndex -- ** Management , start , pause , stop ) where import Control.Applicative import Control.Exception import Control.Concurrent import Control.Concurrent.Chan.Split as CS import Control.Monad.Logger import Control.Monad.Trans import Control.Monad.Trans.Resource import Data.Default import Data.HashMap.Strict as HM import Data.Text import Network import Data.Torrent import Network.BitTorrent.Address import Network.BitTorrent.Client.Types import Network.BitTorrent.Client.Handle import Network.BitTorrent.DHT as DHT hiding (Options) import Network.BitTorrent.Tracker as Tracker hiding (Options) import Network.BitTorrent.Exchange as Exchange hiding (Options) import qualified Network.BitTorrent.Exchange as Exchange (Options(..)) data Options = Options { optFingerprint :: Fingerprint , optName :: Text , optPort :: PortNumber , optExtensions :: [Extension] , optNodeAddr :: NodeAddr IPv4 , optBootNode :: Maybe (NodeAddr IPv4) } instance Default Options where def = Options { optFingerprint = def , optName = "hs-bittorrent" , optPort = 6882 , optExtensions = [] , optNodeAddr = "0.0.0.0:6882" , optBootNode = Nothing } exchangeOptions :: PeerId -> Options -> Exchange.Options exchangeOptions pid Options {..} = Exchange.Options { optPeerAddr = PeerAddr (Just pid) (peerHost def) optPort , optBacklog = optBacklog def } connHandler :: MVar (HashMap InfoHash Handle) -> Exchange.Handler connHandler tmap ih = do m <- readMVar tmap case HM.lookup ih m of Nothing -> error "torrent not found" Just (Handle {..}) -> return handleExchange initClient :: Options -> LogFun -> ResIO Client initClient opts @ Options {..} logFun = do pid <- liftIO genPeerId tmap <- liftIO $ newMVar HM.empty let peerInfo = PeerInfo pid Nothing optPort let mkTracker = Tracker.newManager def peerInfo (_, tmgr) <- allocate mkTracker Tracker.closeManager let mkEx = Exchange.newManager (exchangeOptions pid opts) (connHandler tmap) (_, emgr) <- allocate mkEx Exchange.closeManager let mkNode = DHT.newNode defaultHandlers def optNodeAddr logFun (_, node) <- allocate mkNode DHT.closeNode resourceMap <- getInternalState eventStream <- liftIO newSendPort return Client { clientPeerId = pid , clientListenerPort = optPort , allowedExtensions = toCaps optExtensions , clientResources = resourceMap , trackerManager = tmgr , exchangeManager = emgr , clientNode = node , clientTorrents = tmap , clientLogger = logFun , clientEvents = eventStream } newClient :: Options -> LogFun -> IO Client newClient opts logFun = do s <- createInternalState runInternalState (initClient opts logFun) s `onException` closeInternalState s closeClient :: Client -> IO () closeClient Client {..} = closeInternalState clientResources withClient :: Options -> LogFun -> (Client -> IO a) -> IO a withClient opts lf action = bracket (newClient opts lf) closeClient action -- do not perform IO in 'initClient', do it in the 'boot' --boot :: BitTorrent () --boot = do -- Options {..} <- asks options -- liftDHT $ bootstrap (maybeToList optBootNode) -- | Run bittorrent client with default options and log to @stderr@. -- -- For testing purposes only. -- simpleClient :: BitTorrent () -> IO () simpleClient m = do runStderrLoggingT $ LoggingT $ \ logger -> do withClient def logger (`runBitTorrent` m) {----------------------------------------------------------------------- -- Torrent identifiers -----------------------------------------------------------------------} class TorrentSource s where openHandle :: FilePath -> s -> BitTorrent Handle instance TorrentSource InfoHash where openHandle path ih = openMagnet path (nullMagnet ih) {-# INLINE openHandle #-} instance TorrentSource Magnet where openHandle = openMagnet {-# INLINE openHandle #-} instance TorrentSource InfoDict where openHandle path dict = openTorrent path (nullTorrent dict) {-# INLINE openHandle #-} instance TorrentSource Torrent where openHandle = openTorrent {-# INLINE openHandle #-} instance TorrentSource FilePath where openHandle contentDir torrentPath = do t <- liftIO $ fromFile torrentPath openTorrent contentDir t {-# INLINE openHandle #-} getIndex :: BitTorrent [Handle] getIndex = do Client {..} <- getClient elems <$> liftIO (readMVar clientTorrents)
pxqr/bittorrent
src/Network/BitTorrent/Client.hs
bsd-3-clause
5,518
1
13
1,341
1,233
683
550
-1
-1
{-# LANGUAGE NamedFieldPuns, TupleSections #-} module Distribution where import Data.List ( intercalate ) import Data.Map ( Map ) import qualified Data.Map as Map import Data.Monoid ( (<>) ) import Data.Set ( Set ) import qualified Data.Set as Set data Distribution a = Distribution { total :: Int, parts :: Map a Integer } instance Show a => Show (Distribution a) where show Distribution{total, parts} = mconcat [ "[" , intercalate ", " [ show k <> " = " <> show p <> "%" | (k, v) <- Map.toList parts , let p = if total == 0 then 0 else v * 100 // total ] , "]" ] where x // y = round (fromIntegral x / fromIntegral y :: Double) :: Integer infixl 7 // distributionExclusive :: Ord a => [a] -> Distribution a distributionExclusive xs = Distribution { total = length xs , parts = Map.fromListWith (+) $ fmap (, 1) xs } distributionInclusive :: Ord a => [Set a] -> Distribution a distributionInclusive votes = Distribution { total = length votes , parts = Map.fromListWith (+) $ concatMap (fmap (, 1) . Set.toList) votes }
cblp/ruhaskell-meetup-reg-form-stats
src/Distribution.hs
bsd-3-clause
1,225
0
16
394
404
221
183
-1
-1
{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE RecordWildCards #-} -- | Functionality related to 'Address' data type and related types. module Pos.Core.Common.Address ( Address (..) , Address' (..) -- * Formatting , addressF , addressDetailedF , decodeTextAddress -- * Spending data checks , checkAddrSpendingData , checkPubKeyAddress , checkScriptAddress , checkRedeemAddress -- * Encoding , addrToBase58 , encodeAddr , encodeAddrCRC32 -- * Utilities , addrAttributesUnwrapped , deriveLvl2KeyPair , deriveFirstHDAddress -- * Pattern-matching helpers , isRedeemAddress , isUnknownAddressType , isBootstrapEraDistrAddress -- * Construction , IsBootstrapEraAddr (..) , makeAddress , makeAddress' , makePubKeyAddress , makePubKeyAddressBoot , makeRootPubKeyAddress , makePubKeyHdwAddress , makeScriptAddress , makeRedeemAddress , createHDAddressNH , createHDAddressH -- * Maximal sizes (needed for tx creation) , largestPubKeyAddressBoot , maxPubKeyAddressSizeBoot , largestPubKeyAddressSingleKey , maxPubKeyAddressSizeSingleKey , largestHDAddressBoot , maxHDAddressSizeBoot ) where import Universum import Control.Lens (makePrisms) import qualified Data.Aeson as Aeson (FromJSON (..), FromJSONKey (..), FromJSONKeyFunction (..), ToJSON (toJSON), ToJSONKey (..)) import qualified Data.Aeson.Types as Aeson (toJSONKeyText) import qualified Data.ByteString as BS import Data.ByteString.Base58 (Alphabet (..), bitcoinAlphabet, decodeBase58, encodeBase58) import Data.Hashable (Hashable (..)) import Data.SafeCopy (base, deriveSafeCopySimple) import Formatting (Format, bprint, build, builder, later, sformat, (%)) import qualified Formatting.Buildable as Buildable import Serokell.Data.Memory.Units (Byte) import Serokell.Util (listJson) import Text.JSON.Canonical (FromJSON (..), FromObjectKey (..), JSValue (..), ReportSchemaErrors, ToJSON (..), ToObjectKey (..)) import Pos.Binary.Class (Bi (..), Encoding, biSize, encodeCrcProtected, encodedCrcProtectedSizeExpr) import qualified Pos.Binary.Class as Bi import Pos.Core.Attributes (Attributes (..), attrData, mkAttributes) import Pos.Core.Common.Coin () import Pos.Core.Constants (accountGenesisIndex, wAddressGenesisIndex) import Pos.Core.NetworkMagic (NetworkMagic (..)) import Pos.Crypto.Hashing (hashHexF) import Pos.Crypto.HD (HDAddressPayload, HDPassphrase, ShouldCheckPassphrase (..), deriveHDPassphrase, deriveHDPublicKey, deriveHDSecretKey, packHDAddressAttr) import Pos.Crypto.Signing (EncryptedSecretKey, PassPhrase, PublicKey, RedeemPublicKey, SecretKey, deterministicKeyGen, emptyPassphrase, encToPublic, noPassEncrypt) import Pos.Util.Json.Canonical (formatJSString) import Pos.Util.Json.Parse (tryParseString) import Pos.Util.Util (toAesonError) import Pos.Core.Common.AddrAttributes import Pos.Core.Common.AddressHash import Pos.Core.Common.AddrSpendingData import Pos.Core.Common.AddrStakeDistribution import Pos.Core.Common.Script import Pos.Core.Common.StakeholderId -- | Hash of this data is stored in 'Address'. This type exists mostly -- for internal usage. newtype Address' = Address' { unAddress' :: (AddrType, AddrSpendingData, Attributes AddrAttributes) } deriving stock (Eq, Show, Generic) deriving newtype Bi -- | 'Address' is where you can send coins. data Address = Address { addrRoot :: !(AddressHash Address') -- ^ Root of imaginary pseudo Merkle tree stored in this address. , addrAttributes :: !(Attributes AddrAttributes) -- ^ Attributes associated with this address. , addrType :: !AddrType -- ^ The type of this address. Should correspond to -- 'AddrSpendingData', but it can't be checked statically, because -- spending data is hashed. } deriving (Eq, Ord, Generic, Typeable, Show) instance NFData Address instance Bi Address where encode Address{..} = Bi.encodeCrcProtected (addrRoot, addrAttributes, addrType) decode = do (addrRoot, addrAttributes, addrType) <- Bi.decodeCrcProtected let res = Address {..} pure res encodedSizeExpr size pxy = encodedCrcProtectedSizeExpr size ( (,,) <$> (addrRoot <$> pxy) <*> (addrAttributes <$> pxy) <*> (addrType <$> pxy) ) instance Buildable [Address] where build = bprint listJson instance Hashable Address where hashWithSalt s = hashWithSalt s . Bi.serialize instance Monad m => ToObjectKey m Address where toObjectKey = pure . formatJSString addressF instance ReportSchemaErrors m => FromObjectKey m Address where fromObjectKey = fmap Just . tryParseString decodeTextAddress . JSString instance Monad m => ToJSON m Address where toJSON = fmap JSString . toObjectKey instance ReportSchemaErrors m => FromJSON m Address where fromJSON = tryParseString decodeTextAddress instance Aeson.FromJSONKey Address where fromJSONKey = Aeson.FromJSONKeyTextParser (toAesonError . decodeTextAddress) instance Aeson.ToJSONKey Address where toJSONKey = Aeson.toJSONKeyText (sformat addressF) instance Aeson.FromJSON Address where parseJSON = toAesonError . decodeTextAddress <=< Aeson.parseJSON instance Aeson.ToJSON Address where toJSON = Aeson.toJSON . sformat addressF ---------------------------------------------------------------------------- -- Formatting, pretty-printing ---------------------------------------------------------------------------- -- | A formatter showing guts of an 'Address'. addressDetailedF :: Format r (Address -> r) addressDetailedF = later $ \Address {..} -> bprint (builder%" address with root "%hashHexF%", attributes: "%build) (formattedType addrType) addrRoot addrAttributes where formattedType = \case ATPubKey -> "PubKey" ATScript -> "Script" ATRedeem -> "Redeem" ATUnknown tag -> "Unknown#" <> Buildable.build tag -- | Currently we gonna use Bitcoin alphabet for representing addresses in -- base58 addrAlphabet :: Alphabet addrAlphabet = bitcoinAlphabet addrToBase58 :: Address -> ByteString addrToBase58 = encodeBase58 addrAlphabet . Bi.serialize' instance Buildable Address where build = Buildable.build . decodeUtf8 @Text . addrToBase58 -- | Specialized formatter for 'Address'. addressF :: Format r (Address -> r) addressF = build -- | A function which decodes base58-encoded 'Address'. decodeTextAddress :: Text -> Either Text Address decodeTextAddress = decodeAddress . encodeUtf8 where decodeAddress :: ByteString -> Either Text Address decodeAddress bs = do let base58Err = "Invalid base58 representation of address" dbs <- maybeToRight base58Err $ decodeBase58 addrAlphabet bs Bi.decodeFull' dbs ---------------------------------------------------------------------------- -- Constructors ---------------------------------------------------------------------------- {-# ANN makeAddress ("HLint: ignore Reduce duplication" :: Text) #-} {-# ANN makeAddress' ("HLint: ignore Reduce duplication" :: Text) #-} -- | Make an 'Address' from spending data and attributes. makeAddress :: AddrSpendingData -> AddrAttributes -> Address makeAddress spendingData attributesUnwrapped = Address { addrRoot = addressHash address' , addrAttributes = attributes , addrType = addrType' } where addrType' = addrSpendingDataToType spendingData attributes = mkAttributes attributesUnwrapped address' = Address' (addrType', spendingData, attributes) -- | Make an 'Address'' from spending data and attributes. makeAddress' :: AddrSpendingData -> AddrAttributes -> Address' makeAddress' spendingData attributesUnwrapped = address' where addrType' = addrSpendingDataToType spendingData attributes = mkAttributes attributesUnwrapped address' = Address' (addrType', spendingData, attributes) -- | This newtype exists for clarity. It is used to tell pubkey -- address creation functions whether an address is intended for -- bootstrap era. newtype IsBootstrapEraAddr = IsBootstrapEraAddr Bool -- | A function for making an address from 'PublicKey'. makePubKeyAddress :: NetworkMagic -> IsBootstrapEraAddr -> PublicKey -> Address makePubKeyAddress nm = makePubKeyAddressImpl nm Nothing -- | A function for making an address from 'PublicKey' for bootstrap era. makePubKeyAddressBoot :: NetworkMagic -> PublicKey -> Address makePubKeyAddressBoot nm = makePubKeyAddress nm (IsBootstrapEraAddr True) -- | This function creates a root public key address. Stake -- distribution doesn't matter for root addresses because by design -- nobody should even use these addresses as outputs, so we can put -- arbitrary distribution there. We use bootstrap era distribution -- because its representation is more compact. makeRootPubKeyAddress :: NetworkMagic -> PublicKey -> Address makeRootPubKeyAddress = makePubKeyAddressBoot -- | A function for making an HDW address. makePubKeyHdwAddress :: NetworkMagic -> IsBootstrapEraAddr -> HDAddressPayload -- ^ Derivation path -> PublicKey -> Address makePubKeyHdwAddress nm ibe path = makePubKeyAddressImpl nm (Just path) ibe makePubKeyAddressImpl :: NetworkMagic -> Maybe HDAddressPayload -> IsBootstrapEraAddr -> PublicKey -> Address makePubKeyAddressImpl nm path (IsBootstrapEraAddr isBootstrapEra) key = makeAddress spendingData attrs where spendingData = PubKeyASD key distr | isBootstrapEra = BootstrapEraDistr | otherwise = SingleKeyDistr (addressHash key) attrs = AddrAttributes { aaStakeDistribution = distr , aaPkDerivationPath = path , aaNetworkMagic = nm } -- | A function for making an address from a validation 'Script'. It -- takes an optional 'StakeholderId'. If it's given, it will receive -- the stake sent to the resulting 'Address'. Otherwise it's assumed -- that an 'Address' is created for bootstrap era. makeScriptAddress :: NetworkMagic -> Maybe StakeholderId -> Script -> Address makeScriptAddress nm stakeholder scr = makeAddress spendingData attrs where spendingData = ScriptASD scr aaStakeDistribution = maybe BootstrapEraDistr SingleKeyDistr stakeholder attrs = AddrAttributes { aaPkDerivationPath = Nothing , aaNetworkMagic = nm , ..} -- | A function for making an address from 'RedeemPublicKey'. makeRedeemAddress :: NetworkMagic -> RedeemPublicKey -> Address makeRedeemAddress nm key = makeAddress spendingData attrs where spendingData = RedeemASD key attrs = AddrAttributes { aaStakeDistribution = BootstrapEraDistr , aaPkDerivationPath = Nothing , aaNetworkMagic = nm } -- | Create address from secret key in hardened way. createHDAddressH :: NetworkMagic -> IsBootstrapEraAddr -> ShouldCheckPassphrase -> PassPhrase -> HDPassphrase -> EncryptedSecretKey -> [Word32] -> Word32 -> Maybe (Address, EncryptedSecretKey) createHDAddressH nm ibea scp passphrase hdPassphrase parent parentPath childIndex = do derivedSK <- deriveHDSecretKey scp passphrase parent childIndex let addressPayload = packHDAddressAttr hdPassphrase $ parentPath ++ [childIndex] let pk = encToPublic derivedSK return (makePubKeyHdwAddress nm ibea addressPayload pk, derivedSK) -- | Create address from public key via non-hardened way. createHDAddressNH :: NetworkMagic -> IsBootstrapEraAddr -> HDPassphrase -> PublicKey -> [Word32] -> Word32 -> (Address, PublicKey) createHDAddressNH nm ibea passphrase parent parentPath childIndex = do let derivedPK = deriveHDPublicKey parent childIndex let addressPayload = packHDAddressAttr passphrase $ parentPath ++ [childIndex] (makePubKeyHdwAddress nm ibea addressPayload derivedPK, derivedPK) ---------------------------------------------------------------------------- -- Checks ---------------------------------------------------------------------------- -- | Check whether given 'AddrSpendingData' corresponds to given -- 'Address'. checkAddrSpendingData :: AddrSpendingData -> Address -> Bool checkAddrSpendingData asd Address {..} = addrRoot == addressHash address' && addrType == addrSpendingDataToType asd where address' = Address' (addrType, asd, addrAttributes) -- | Check if given 'Address' is created from given 'PublicKey' checkPubKeyAddress :: PublicKey -> Address -> Bool checkPubKeyAddress pk = checkAddrSpendingData (PubKeyASD pk) -- | Check if given 'Address' is created from given validation script checkScriptAddress :: Script -> Address -> Bool checkScriptAddress script = checkAddrSpendingData (ScriptASD script) -- | Check if given 'Address' is created from given 'RedeemPublicKey' checkRedeemAddress :: RedeemPublicKey -> Address -> Bool checkRedeemAddress rpk = checkAddrSpendingData (RedeemASD rpk) ---------------------------------------------------------------------------- -- Utils ---------------------------------------------------------------------------- -- | Get 'AddrAttributes' from 'Address'. addrAttributesUnwrapped :: Address -> AddrAttributes addrAttributesUnwrapped = attrData . addrAttributes -- | Makes account secret key for given wallet set. deriveLvl2KeyPair :: NetworkMagic -> IsBootstrapEraAddr -> ShouldCheckPassphrase -> PassPhrase -> EncryptedSecretKey -- ^ key of wallet -> Word32 -- ^ account derivation index -> Word32 -- ^ address derivation index -> Maybe (Address, EncryptedSecretKey) deriveLvl2KeyPair nm ibea scp passphrase wsKey accountIndex addressIndex = do wKey <- deriveHDSecretKey scp passphrase wsKey accountIndex let hdPass = deriveHDPassphrase $ encToPublic wsKey -- We don't need to check passphrase twice createHDAddressH nm ibea (ShouldCheckPassphrase False) passphrase hdPass wKey [accountIndex] addressIndex deriveFirstHDAddress :: NetworkMagic -> IsBootstrapEraAddr -> PassPhrase -> EncryptedSecretKey -- ^ key of wallet set -> Maybe (Address, EncryptedSecretKey) deriveFirstHDAddress nm ibea passphrase wsKey = deriveLvl2KeyPair nm ibea (ShouldCheckPassphrase False) passphrase wsKey accountGenesisIndex wAddressGenesisIndex ---------------------------------------------------------------------------- -- Pattern-matching helpers ---------------------------------------------------------------------------- -- | Check whether an 'Address' is redeem address. isRedeemAddress :: Address -> Bool isRedeemAddress Address {..} = case addrType of ATRedeem -> True _ -> False isUnknownAddressType :: Address -> Bool isUnknownAddressType Address {..} = case addrType of ATUnknown {} -> True _ -> False -- | Check whether an 'Address' has bootstrap era stake distribution. isBootstrapEraDistrAddress :: Address -> Bool isBootstrapEraDistrAddress (addrAttributesUnwrapped -> AddrAttributes {..}) = case aaStakeDistribution of BootstrapEraDistr -> True _ -> False ---------------------------------------------------------------------------- -- Maximal size ---------------------------------------------------------------------------- -- | Largest (considering size of serialized data) PubKey address with -- BootstrapEra distribution. Actual size depends on CRC32 value which -- is serialized using var-length encoding. largestPubKeyAddressBoot :: NetworkMagic -> Address largestPubKeyAddressBoot nm = makePubKeyAddressBoot nm goodPk -- | Maximal size of PubKey address with BootstrapEra -- distribution (43). maxPubKeyAddressSizeBoot :: NetworkMagic -> Byte maxPubKeyAddressSizeBoot = biSize . largestPubKeyAddressBoot -- | Largest (considering size of serialized data) PubKey address with -- SingleKey distribution. Actual size depends on CRC32 value which -- is serialized using var-length encoding. largestPubKeyAddressSingleKey :: NetworkMagic -> Address largestPubKeyAddressSingleKey nm = makePubKeyAddress nm (IsBootstrapEraAddr False) goodPk -- | Maximal size of PubKey address with SingleKey -- distribution (78). maxPubKeyAddressSizeSingleKey :: NetworkMagic -> Byte maxPubKeyAddressSizeSingleKey = biSize . largestPubKeyAddressSingleKey -- | Largest (considering size of serialized data) HD address with -- BootstrapEra distribution. Actual size depends on CRC32 value which -- is serialized using var-length encoding. largestHDAddressBoot :: NetworkMagic -> Address largestHDAddressBoot nm = case deriveLvl2KeyPair nm (IsBootstrapEraAddr True) (ShouldCheckPassphrase False) emptyPassphrase encSK maxBound maxBound of Nothing -> error "largestHDAddressBoot failed" Just (addr, _) -> addr where encSK = noPassEncrypt goodSk -- | Maximal size of HD address with BootstrapEra -- distribution (76). maxHDAddressSizeBoot :: NetworkMagic -> Byte maxHDAddressSizeBoot = biSize . largestHDAddressBoot -- Public key and secret key for which we know that they produce -- largest addresses in all cases we are interested in. It was checked -- manually. goodSkAndPk :: (PublicKey, SecretKey) goodSkAndPk = deterministicKeyGen $ BS.replicate 32 0 goodPk :: PublicKey goodPk = fst goodSkAndPk goodSk :: SecretKey goodSk = snd goodSkAndPk -- Encodes the `Address` __without__ the CRC32. -- It's important to keep this function separated from the `encode` -- definition to avoid that `encode` would call `crc32` and -- the latter invoke `crc32Update`, which would then try to call `encode` -- indirectly once again, in an infinite loop. encodeAddr :: Address -> Encoding encodeAddr Address {..} = encode addrRoot <> encode addrAttributes <> encode addrType encodeAddrCRC32 :: Address -> Encoding encodeAddrCRC32 Address{..} = encodeCrcProtected (addrRoot, addrAttributes, addrType) makePrisms ''Address deriveSafeCopySimple 0 'base ''Address' deriveSafeCopySimple 0 'base ''Address
input-output-hk/pos-haskell-prototype
core/src/Pos/Core/Common/Address.hs
mit
18,978
0
14
4,048
3,139
1,761
1,378
-1
-1
{-# LANGUAGE StrictData #-} {-# LANGUAGE Trustworthy #-} module Network.Tox.DHT.DhtPacketSpec where import Test.Hspec import Test.QuickCheck import Data.Binary (Binary) import qualified Data.Binary as Binary (get, put) import qualified Data.Binary.Get as Binary (runGet) import qualified Data.Binary.Put as Binary (runPut) import Data.Proxy (Proxy (..)) import Network.Tox.Crypto.Key (Nonce) import Network.Tox.Crypto.KeyPair (KeyPair (..)) import Network.Tox.DHT.DhtPacket (DhtPacket (..)) import qualified Network.Tox.DHT.DhtPacket as DhtPacket import Network.Tox.EncodingSpec import Network.Tox.NodeInfo.NodeInfo (NodeInfo) encodeAndDecode :: (Binary a, Binary b) => KeyPair -> KeyPair -> Nonce -> a -> Maybe b encodeAndDecode senderKeyPair receiverKeyPair nonce payload = let KeyPair _ receiverPublicKey = receiverKeyPair packet = DhtPacket.encode senderKeyPair receiverPublicKey nonce payload packet' = Binary.runGet Binary.get $ Binary.runPut $ Binary.put packet in DhtPacket.decode receiverKeyPair packet' encodeAndDecodeString :: KeyPair -> KeyPair -> Nonce -> String -> Maybe String encodeAndDecodeString = encodeAndDecode encodeCharAndDecodeString :: KeyPair -> KeyPair -> Nonce -> Char -> Maybe String encodeCharAndDecodeString = encodeAndDecode encodeIntAndDecodeNodeInfo :: KeyPair -> KeyPair -> Nonce -> Int -> Maybe NodeInfo encodeIntAndDecodeNodeInfo = encodeAndDecode spec :: Spec spec = do rpcSpec (Proxy :: Proxy DhtPacket) binarySpec (Proxy :: Proxy DhtPacket) readShowSpec (Proxy :: Proxy DhtPacket) it "encodes and decodes packets" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeAndDecodeString senderKeyPair receiverKeyPair nonce payload `shouldBe` Just payload it "fails to decode packets with the wrong secret key" $ property $ \senderKeyPair (KeyPair _ receiverPublicKey) badSecretKey nonce payload -> encodeAndDecodeString senderKeyPair (KeyPair badSecretKey receiverPublicKey) nonce payload `shouldBe` Nothing it "fails to decode packets with the wrong payload type (Partial)" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeCharAndDecodeString senderKeyPair receiverKeyPair nonce payload `shouldBe` Nothing it "fails to decode packets with the wrong payload type (Fail)" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeIntAndDecodeNodeInfo senderKeyPair receiverKeyPair nonce payload `shouldBe` Nothing it "should decode empty CipherText correctly" $ expectDecoded [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ] $ DhtPacket (read "\"0000000000000000000000000000000000000000000000000000000000000000\"") (read "\"000000000000000000000000000000000000000000000000\"") (read "\"00000000000000000000000000000000\"")
iphydf/hs-toxcore
test/Network/Tox/DHT/DhtPacketSpec.hs
gpl-3.0
3,143
0
12
644
861
493
368
56
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.Lambda.GetEventSourceMapping -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns configuration information for the specified event source mapping (see 'CreateEventSourceMapping'). -- -- This operation requires permission for the 'lambda:GetEventSourceMapping' -- action. -- -- <http://docs.aws.amazon.com/lambda/latest/dg/API_GetEventSourceMapping.html> module Network.AWS.Lambda.GetEventSourceMapping ( -- * Request GetEventSourceMapping -- ** Request constructor , getEventSourceMapping -- ** Request lenses , gesmUUID -- * Response , GetEventSourceMappingResponse -- ** Response constructor , getEventSourceMappingResponse -- ** Response lenses , gesmrBatchSize , gesmrEventSourceArn , gesmrFunctionArn , gesmrLastModified , gesmrLastProcessingResult , gesmrState , gesmrStateTransitionReason , gesmrUUID ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.RestJSON import Network.AWS.Lambda.Types import qualified GHC.Exts newtype GetEventSourceMapping = GetEventSourceMapping { _gesmUUID :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'GetEventSourceMapping' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gesmUUID' @::@ 'Text' -- getEventSourceMapping :: Text -- ^ 'gesmUUID' -> GetEventSourceMapping getEventSourceMapping p1 = GetEventSourceMapping { _gesmUUID = p1 } -- | The AWS Lambda assigned ID of the event source mapping. gesmUUID :: Lens' GetEventSourceMapping Text gesmUUID = lens _gesmUUID (\s a -> s { _gesmUUID = a }) data GetEventSourceMappingResponse = GetEventSourceMappingResponse { _gesmrBatchSize :: Maybe Nat , _gesmrEventSourceArn :: Maybe Text , _gesmrFunctionArn :: Maybe Text , _gesmrLastModified :: Maybe POSIX , _gesmrLastProcessingResult :: Maybe Text , _gesmrState :: Maybe Text , _gesmrStateTransitionReason :: Maybe Text , _gesmrUUID :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'GetEventSourceMappingResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gesmrBatchSize' @::@ 'Maybe' 'Natural' -- -- * 'gesmrEventSourceArn' @::@ 'Maybe' 'Text' -- -- * 'gesmrFunctionArn' @::@ 'Maybe' 'Text' -- -- * 'gesmrLastModified' @::@ 'Maybe' 'UTCTime' -- -- * 'gesmrLastProcessingResult' @::@ 'Maybe' 'Text' -- -- * 'gesmrState' @::@ 'Maybe' 'Text' -- -- * 'gesmrStateTransitionReason' @::@ 'Maybe' 'Text' -- -- * 'gesmrUUID' @::@ 'Maybe' 'Text' -- getEventSourceMappingResponse :: GetEventSourceMappingResponse getEventSourceMappingResponse = GetEventSourceMappingResponse { _gesmrUUID = Nothing , _gesmrBatchSize = Nothing , _gesmrEventSourceArn = Nothing , _gesmrFunctionArn = Nothing , _gesmrLastModified = Nothing , _gesmrLastProcessingResult = Nothing , _gesmrState = Nothing , _gesmrStateTransitionReason = Nothing } -- | The largest number of records that AWS Lambda will retrieve from your event -- source at the time of invoking your function. Your function receives an event -- with all the retrieved records. gesmrBatchSize :: Lens' GetEventSourceMappingResponse (Maybe Natural) gesmrBatchSize = lens _gesmrBatchSize (\s a -> s { _gesmrBatchSize = a }) . mapping _Nat -- | The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the -- source of events. gesmrEventSourceArn :: Lens' GetEventSourceMappingResponse (Maybe Text) gesmrEventSourceArn = lens _gesmrEventSourceArn (\s a -> s { _gesmrEventSourceArn = a }) -- | The Lambda function to invoke when AWS Lambda detects an event on the stream. gesmrFunctionArn :: Lens' GetEventSourceMappingResponse (Maybe Text) gesmrFunctionArn = lens _gesmrFunctionArn (\s a -> s { _gesmrFunctionArn = a }) -- | The UTC time string indicating the last time the event mapping was updated. gesmrLastModified :: Lens' GetEventSourceMappingResponse (Maybe UTCTime) gesmrLastModified = lens _gesmrLastModified (\s a -> s { _gesmrLastModified = a }) . mapping _Time -- | The result of the last AWS Lambda invocation of your Lambda function. gesmrLastProcessingResult :: Lens' GetEventSourceMappingResponse (Maybe Text) gesmrLastProcessingResult = lens _gesmrLastProcessingResult (\s a -> s { _gesmrLastProcessingResult = a }) -- | The state of the event source mapping. It can be "Creating", "Enabled", -- "Disabled", "Enabling", "Disabling", "Updating", or "Deleting". gesmrState :: Lens' GetEventSourceMappingResponse (Maybe Text) gesmrState = lens _gesmrState (\s a -> s { _gesmrState = a }) -- | The reason the event source mapping is in its current state. It is either -- user-requested or an AWS Lambda-initiated state transition. gesmrStateTransitionReason :: Lens' GetEventSourceMappingResponse (Maybe Text) gesmrStateTransitionReason = lens _gesmrStateTransitionReason (\s a -> s { _gesmrStateTransitionReason = a }) -- | The AWS Lambda assigned opaque identifier for the mapping. gesmrUUID :: Lens' GetEventSourceMappingResponse (Maybe Text) gesmrUUID = lens _gesmrUUID (\s a -> s { _gesmrUUID = a }) instance ToPath GetEventSourceMapping where toPath GetEventSourceMapping{..} = mconcat [ "/2015-03-31/event-source-mappings/" , toText _gesmUUID ] instance ToQuery GetEventSourceMapping where toQuery = const mempty instance ToHeaders GetEventSourceMapping instance ToJSON GetEventSourceMapping where toJSON = const (toJSON Empty) instance AWSRequest GetEventSourceMapping where type Sv GetEventSourceMapping = Lambda type Rs GetEventSourceMapping = GetEventSourceMappingResponse request = get response = jsonResponse instance FromJSON GetEventSourceMappingResponse where parseJSON = withObject "GetEventSourceMappingResponse" $ \o -> GetEventSourceMappingResponse <$> o .:? "BatchSize" <*> o .:? "EventSourceArn" <*> o .:? "FunctionArn" <*> o .:? "LastModified" <*> o .:? "LastProcessingResult" <*> o .:? "State" <*> o .:? "StateTransitionReason" <*> o .:? "UUID"
romanb/amazonka
amazonka-lambda/gen/Network/AWS/Lambda/GetEventSourceMapping.hs
mpl-2.0
7,299
0
23
1,553
993
586
407
106
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.OpsWorks.StartInstance -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Starts a specified instance. For more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-starting.html Starting, Stopping,and Rebooting Instances>. -- -- Required Permissions: To use this action, an IAM user must have a Manage -- permissions level for the stack, or an attached policy that explicitly grants -- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>. -- -- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_StartInstance.html> module Network.AWS.OpsWorks.StartInstance ( -- * Request StartInstance -- ** Request constructor , startInstance -- ** Request lenses , si1InstanceId -- * Response , StartInstanceResponse -- ** Response constructor , startInstanceResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.OpsWorks.Types import qualified GHC.Exts newtype StartInstance = StartInstance { _si1InstanceId :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'StartInstance' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'si1InstanceId' @::@ 'Text' -- startInstance :: Text -- ^ 'si1InstanceId' -> StartInstance startInstance p1 = StartInstance { _si1InstanceId = p1 } -- | The instance ID. si1InstanceId :: Lens' StartInstance Text si1InstanceId = lens _si1InstanceId (\s a -> s { _si1InstanceId = a }) data StartInstanceResponse = StartInstanceResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'StartInstanceResponse' constructor. startInstanceResponse :: StartInstanceResponse startInstanceResponse = StartInstanceResponse instance ToPath StartInstance where toPath = const "/" instance ToQuery StartInstance where toQuery = const mempty instance ToHeaders StartInstance instance ToJSON StartInstance where toJSON StartInstance{..} = object [ "InstanceId" .= _si1InstanceId ] instance AWSRequest StartInstance where type Sv StartInstance = OpsWorks type Rs StartInstance = StartInstanceResponse request = post "StartInstance" response = nullResponse StartInstanceResponse
romanb/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/StartInstance.hs
mpl-2.0
3,361
0
9
680
360
221
139
48
1
{-# LANGUAGE CPP #-} ---------------------------------------------------------------------------- -- -- Stg to C--: primitive operations -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmPrim ( cgOpApp, cgPrimOp, -- internal(ish), used by cgCase to get code for a -- comparison without also turning it into a Bool. shouldInlinePrimOp ) where #include "HsVersions.h" import StgCmmLayout import StgCmmForeign import StgCmmEnv import StgCmmMonad import StgCmmUtils import StgCmmTicky import StgCmmHeap import StgCmmProf ( costCentreFrom, curCCS ) import DynFlags import Platform import BasicTypes import MkGraph import StgSyn import Cmm import CmmInfo import Type ( Type, tyConAppTyCon ) import TyCon import CLabel import CmmUtils import PrimOp import SMRep import FastString import Outputable import Util #if __GLASGOW_HASKELL__ >= 709 import Prelude hiding ((<*>)) #endif import Data.Bits ((.&.), bit) import Control.Monad (liftM, when) ------------------------------------------------------------------------ -- Primitive operations and foreign calls ------------------------------------------------------------------------ {- Note [Foreign call results] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ A foreign call always returns an unboxed tuple of results, one of which is the state token. This seems to happen even for pure calls. Even if we returned a single result for pure calls, it'd still be right to wrap it in a singleton unboxed tuple, because the result might be a Haskell closure pointer, we don't want to evaluate it. -} ---------------------------------- cgOpApp :: StgOp -- The op -> [StgArg] -- Arguments -> Type -- Result type (always an unboxed tuple) -> FCode ReturnKind -- Foreign calls cgOpApp (StgFCallOp fcall _) stg_args res_ty = cgForeignCall fcall stg_args res_ty -- Note [Foreign call results] -- tagToEnum# is special: we need to pull the constructor -- out of the table, and perform an appropriate return. cgOpApp (StgPrimOp TagToEnumOp) [arg] res_ty = ASSERT(isEnumerationTyCon tycon) do { dflags <- getDynFlags ; args' <- getNonVoidArgAmodes [arg] ; let amode = case args' of [amode] -> amode _ -> panic "TagToEnumOp had void arg" ; emitReturn [tagToClosure dflags tycon amode] } where -- If you're reading this code in the attempt to figure -- out why the compiler panic'ed here, it is probably because -- you used tagToEnum# in a non-monomorphic setting, e.g., -- intToTg :: Enum a => Int -> a ; intToTg (I# x#) = tagToEnum# x# -- That won't work. tycon = tyConAppTyCon res_ty cgOpApp (StgPrimOp primop) args res_ty = do dflags <- getDynFlags cmm_args <- getNonVoidArgAmodes args case shouldInlinePrimOp dflags primop cmm_args of Nothing -> do -- out-of-line let fun = CmmLit (CmmLabel (mkRtsPrimOpLabel primop)) emitCall (NativeNodeCall, NativeReturn) fun cmm_args Just f -- inline | ReturnsPrim VoidRep <- result_info -> do f [] emitReturn [] | ReturnsPrim rep <- result_info -> do dflags <- getDynFlags res <- newTemp (primRepCmmType dflags rep) f [res] emitReturn [CmmReg (CmmLocal res)] | ReturnsAlg tycon <- result_info, isUnboxedTupleTyCon tycon -> do (regs, _hints) <- newUnboxedTupleRegs res_ty f regs emitReturn (map (CmmReg . CmmLocal) regs) | otherwise -> panic "cgPrimop" where result_info = getPrimOpResultInfo primop cgOpApp (StgPrimCallOp primcall) args _res_ty = do { cmm_args <- getNonVoidArgAmodes args ; let fun = CmmLit (CmmLabel (mkPrimCallLabel primcall)) ; emitCall (NativeNodeCall, NativeReturn) fun cmm_args } -- | Interpret the argument as an unsigned value, assuming the value -- is given in two-complement form in the given width. -- -- Example: @asUnsigned W64 (-1)@ is 18446744073709551615. -- -- This function is used to work around the fact that many array -- primops take Int# arguments, but we interpret them as unsigned -- quantities in the code gen. This means that we have to be careful -- every time we work on e.g. a CmmInt literal that corresponds to the -- array size, as it might contain a negative Integer value if the -- user passed a value larger than 2^(wORD_SIZE_IN_BITS-1) as the Int# -- literal. asUnsigned :: Width -> Integer -> Integer asUnsigned w n = n .&. (bit (widthInBits w) - 1) -- TODO: Several primop implementations (e.g. 'doNewByteArrayOp') use -- ByteOff (or some other fixed width signed type) to represent -- array sizes or indices. This means that these will overflow for -- large enough sizes. -- | Decide whether an out-of-line primop should be replaced by an -- inline implementation. This might happen e.g. if there's enough -- static information, such as statically know arguments, to emit a -- more efficient implementation inline. -- -- Returns 'Nothing' if this primop should use its out-of-line -- implementation (defined elsewhere) and 'Just' together with a code -- generating function that takes the output regs as arguments -- otherwise. shouldInlinePrimOp :: DynFlags -> PrimOp -- ^ The primop -> [CmmExpr] -- ^ The primop arguments -> Maybe ([LocalReg] -> FCode ()) shouldInlinePrimOp dflags NewByteArrayOp_Char [(CmmLit (CmmInt n w))] | asUnsigned w n <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> doNewByteArrayOp res (fromInteger n) shouldInlinePrimOp dflags NewArrayOp [(CmmLit (CmmInt n w)), init] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> doNewArrayOp res (arrPtrsRep dflags (fromInteger n)) mkMAP_DIRTY_infoLabel [ (mkIntExpr dflags (fromInteger n), fixedHdrSize dflags + oFFSET_StgMutArrPtrs_ptrs dflags) , (mkIntExpr dflags (nonHdrSizeW (arrPtrsRep dflags (fromInteger n))), fixedHdrSize dflags + oFFSET_StgMutArrPtrs_size dflags) ] (fromInteger n) init shouldInlinePrimOp _ CopyArrayOp [src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] = Just $ \ [] -> doCopyArrayOp src src_off dst dst_off (fromInteger n) shouldInlinePrimOp _ CopyMutableArrayOp [src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] = Just $ \ [] -> doCopyMutableArrayOp src src_off dst dst_off (fromInteger n) shouldInlinePrimOp _ CopyArrayArrayOp [src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] = Just $ \ [] -> doCopyArrayOp src src_off dst dst_off (fromInteger n) shouldInlinePrimOp _ CopyMutableArrayArrayOp [src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] = Just $ \ [] -> doCopyMutableArrayOp src src_off dst dst_off (fromInteger n) shouldInlinePrimOp dflags CloneArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneArray mkMAP_FROZEN_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags CloneMutableArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneArray mkMAP_DIRTY_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags FreezeArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneArray mkMAP_FROZEN_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags ThawArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneArray mkMAP_DIRTY_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags NewSmallArrayOp [(CmmLit (CmmInt n w)), init] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> doNewArrayOp res (smallArrPtrsRep (fromInteger n)) mkSMAP_DIRTY_infoLabel [ (mkIntExpr dflags (fromInteger n), fixedHdrSize dflags + oFFSET_StgSmallMutArrPtrs_ptrs dflags) ] (fromInteger n) init shouldInlinePrimOp _ CopySmallArrayOp [src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] = Just $ \ [] -> doCopySmallArrayOp src src_off dst dst_off (fromInteger n) shouldInlinePrimOp _ CopySmallMutableArrayOp [src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] = Just $ \ [] -> doCopySmallMutableArrayOp src src_off dst dst_off (fromInteger n) shouldInlinePrimOp dflags CloneSmallArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneSmallArray mkSMAP_FROZEN_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags CloneSmallMutableArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneSmallArray mkSMAP_DIRTY_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags FreezeSmallArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneSmallArray mkSMAP_FROZEN_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags ThawSmallArrayOp [src, src_off, (CmmLit (CmmInt n w))] | wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) = Just $ \ [res] -> emitCloneSmallArray mkSMAP_DIRTY_infoLabel res src src_off (fromInteger n) shouldInlinePrimOp dflags primop args | primOpOutOfLine primop = Nothing | otherwise = Just $ \ regs -> emitPrimOp dflags regs primop args -- TODO: Several primops, such as 'copyArray#', only have an inline -- implementation (below) but could possibly have both an inline -- implementation and an out-of-line implementation, just like -- 'newArray#'. This would lower the amount of code generated, -- hopefully without a performance impact (needs to be measured). --------------------------------------------------- cgPrimOp :: [LocalReg] -- where to put the results -> PrimOp -- the op -> [StgArg] -- arguments -> FCode () cgPrimOp results op args = do dflags <- getDynFlags arg_exprs <- getNonVoidArgAmodes args emitPrimOp dflags results op arg_exprs ------------------------------------------------------------------------ -- Emitting code for a primop ------------------------------------------------------------------------ emitPrimOp :: DynFlags -> [LocalReg] -- where to put the results -> PrimOp -- the op -> [CmmExpr] -- arguments -> FCode () -- First we handle various awkward cases specially. The remaining -- easy cases are then handled by translateOp, defined below. emitPrimOp _ [res] ParOp [arg] = -- for now, just implement this in a C function -- later, we might want to inline it. emitCCall [(res,NoHint)] (CmmLit (CmmLabel (mkForeignLabel (fsLit "newSpark") Nothing ForeignLabelInExternalPackage IsFunction))) [(CmmReg (CmmGlobal BaseReg), AddrHint), (arg,AddrHint)] emitPrimOp dflags [res] SparkOp [arg] = do -- returns the value of arg in res. We're going to therefore -- refer to arg twice (once to pass to newSpark(), and once to -- assign to res), so put it in a temporary. tmp <- assignTemp arg tmp2 <- newTemp (bWord dflags) emitCCall [(tmp2,NoHint)] (CmmLit (CmmLabel (mkForeignLabel (fsLit "newSpark") Nothing ForeignLabelInExternalPackage IsFunction))) [(CmmReg (CmmGlobal BaseReg), AddrHint), ((CmmReg (CmmLocal tmp)), AddrHint)] emitAssign (CmmLocal res) (CmmReg (CmmLocal tmp)) emitPrimOp dflags [res] GetCCSOfOp [arg] = emitAssign (CmmLocal res) val where val | gopt Opt_SccProfilingOn dflags = costCentreFrom dflags (cmmUntag dflags arg) | otherwise = CmmLit (zeroCLit dflags) emitPrimOp _ [res] GetCurrentCCSOp [_dummy_arg] = emitAssign (CmmLocal res) curCCS emitPrimOp dflags [res] ReadMutVarOp [mutv] = emitAssign (CmmLocal res) (cmmLoadIndexW dflags mutv (fixedHdrSizeW dflags) (gcWord dflags)) emitPrimOp dflags [] WriteMutVarOp [mutv,var] = do emitStore (cmmOffsetW dflags mutv (fixedHdrSizeW dflags)) var emitCCall [{-no results-}] (CmmLit (CmmLabel mkDirty_MUT_VAR_Label)) [(CmmReg (CmmGlobal BaseReg), AddrHint), (mutv,AddrHint)] -- #define sizzeofByteArrayzh(r,a) \ -- r = ((StgArrWords *)(a))->bytes emitPrimOp dflags [res] SizeofByteArrayOp [arg] = emit $ mkAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags) (bWord dflags)) -- #define sizzeofMutableByteArrayzh(r,a) \ -- r = ((StgArrWords *)(a))->bytes emitPrimOp dflags [res] SizeofMutableByteArrayOp [arg] = emitPrimOp dflags [res] SizeofByteArrayOp [arg] -- #define getSizzeofMutableByteArrayzh(r,a) \ -- r = ((StgArrWords *)(a))->bytes emitPrimOp dflags [res] GetSizeofMutableByteArrayOp [arg] = emitAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags) (bWord dflags)) -- #define touchzh(o) /* nothing */ emitPrimOp _ res@[] TouchOp args@[_arg] = do emitPrimCall res MO_Touch args -- #define byteArrayContentszh(r,a) r = BYTE_ARR_CTS(a) emitPrimOp dflags [res] ByteArrayContents_Char [arg] = emitAssign (CmmLocal res) (cmmOffsetB dflags arg (arrWordsHdrSize dflags)) -- #define stableNameToIntzh(r,s) (r = ((StgStableName *)s)->sn) emitPrimOp dflags [res] StableNameToIntOp [arg] = emitAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags) (bWord dflags)) -- #define eqStableNamezh(r,sn1,sn2) \ -- (r = (((StgStableName *)sn1)->sn == ((StgStableName *)sn2)->sn)) emitPrimOp dflags [res] EqStableNameOp [arg1,arg2] = emitAssign (CmmLocal res) (CmmMachOp (mo_wordEq dflags) [ cmmLoadIndexW dflags arg1 (fixedHdrSizeW dflags) (bWord dflags), cmmLoadIndexW dflags arg2 (fixedHdrSizeW dflags) (bWord dflags) ]) emitPrimOp dflags [res] ReallyUnsafePtrEqualityOp [arg1,arg2] = emitAssign (CmmLocal res) (CmmMachOp (mo_wordEq dflags) [arg1,arg2]) -- #define addrToHValuezh(r,a) r=(P_)a emitPrimOp _ [res] AddrToAnyOp [arg] = emitAssign (CmmLocal res) arg -- #define dataToTagzh(r,a) r=(GET_TAG(((StgClosure *)a)->header.info)) -- Note: argument may be tagged! emitPrimOp dflags [res] DataToTagOp [arg] = emitAssign (CmmLocal res) (getConstrTag dflags (cmmUntag dflags arg)) {- Freezing arrays-of-ptrs requires changing an info table, for the benefit of the generational collector. It needs to scavenge mutable objects, even if they are in old space. When they become immutable, they can be removed from this scavenge list. -} -- #define unsafeFreezzeArrayzh(r,a) -- { -- SET_INFO((StgClosure *)a,&stg_MUT_ARR_PTRS_FROZEN0_info); -- r = a; -- } emitPrimOp _ [res] UnsafeFreezeArrayOp [arg] = emit $ catAGraphs [ setInfo arg (CmmLit (CmmLabel mkMAP_FROZEN0_infoLabel)), mkAssign (CmmLocal res) arg ] emitPrimOp _ [res] UnsafeFreezeArrayArrayOp [arg] = emit $ catAGraphs [ setInfo arg (CmmLit (CmmLabel mkMAP_FROZEN0_infoLabel)), mkAssign (CmmLocal res) arg ] emitPrimOp _ [res] UnsafeFreezeSmallArrayOp [arg] = emit $ catAGraphs [ setInfo arg (CmmLit (CmmLabel mkSMAP_FROZEN0_infoLabel)), mkAssign (CmmLocal res) arg ] -- #define unsafeFreezzeByteArrayzh(r,a) r=(a) emitPrimOp _ [res] UnsafeFreezeByteArrayOp [arg] = emitAssign (CmmLocal res) arg -- Reading/writing pointer arrays emitPrimOp _ [res] ReadArrayOp [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [res] IndexArrayOp [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [] WriteArrayOp [obj,ix,v] = doWritePtrArrayOp obj ix v emitPrimOp _ [res] IndexArrayArrayOp_ByteArray [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [res] IndexArrayArrayOp_ArrayArray [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [res] ReadArrayArrayOp_ByteArray [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [res] ReadArrayArrayOp_MutableByteArray [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [res] ReadArrayArrayOp_ArrayArray [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [res] ReadArrayArrayOp_MutableArrayArray [obj,ix] = doReadPtrArrayOp res obj ix emitPrimOp _ [] WriteArrayArrayOp_ByteArray [obj,ix,v] = doWritePtrArrayOp obj ix v emitPrimOp _ [] WriteArrayArrayOp_MutableByteArray [obj,ix,v] = doWritePtrArrayOp obj ix v emitPrimOp _ [] WriteArrayArrayOp_ArrayArray [obj,ix,v] = doWritePtrArrayOp obj ix v emitPrimOp _ [] WriteArrayArrayOp_MutableArrayArray [obj,ix,v] = doWritePtrArrayOp obj ix v emitPrimOp _ [res] ReadSmallArrayOp [obj,ix] = doReadSmallPtrArrayOp res obj ix emitPrimOp _ [res] IndexSmallArrayOp [obj,ix] = doReadSmallPtrArrayOp res obj ix emitPrimOp _ [] WriteSmallArrayOp [obj,ix,v] = doWriteSmallPtrArrayOp obj ix v -- Getting the size of pointer arrays emitPrimOp dflags [res] SizeofArrayOp [arg] = emit $ mkAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags + bytesToWordsRoundUp dflags (oFFSET_StgMutArrPtrs_ptrs dflags)) (bWord dflags)) emitPrimOp dflags [res] SizeofMutableArrayOp [arg] = emitPrimOp dflags [res] SizeofArrayOp [arg] emitPrimOp dflags [res] SizeofArrayArrayOp [arg] = emitPrimOp dflags [res] SizeofArrayOp [arg] emitPrimOp dflags [res] SizeofMutableArrayArrayOp [arg] = emitPrimOp dflags [res] SizeofArrayOp [arg] emitPrimOp dflags [res] SizeofSmallArrayOp [arg] = emit $ mkAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags + bytesToWordsRoundUp dflags (oFFSET_StgSmallMutArrPtrs_ptrs dflags)) (bWord dflags)) emitPrimOp dflags [res] SizeofSmallMutableArrayOp [arg] = emitPrimOp dflags [res] SizeofSmallArrayOp [arg] -- IndexXXXoffAddr emitPrimOp dflags res IndexOffAddrOp_Char args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res IndexOffAddrOp_WideChar args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp dflags res IndexOffAddrOp_Int args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res IndexOffAddrOp_Word args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res IndexOffAddrOp_Addr args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp _ res IndexOffAddrOp_Float args = doIndexOffAddrOp Nothing f32 res args emitPrimOp _ res IndexOffAddrOp_Double args = doIndexOffAddrOp Nothing f64 res args emitPrimOp dflags res IndexOffAddrOp_StablePtr args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res IndexOffAddrOp_Int8 args = doIndexOffAddrOp (Just (mo_s_8ToWord dflags)) b8 res args emitPrimOp dflags res IndexOffAddrOp_Int16 args = doIndexOffAddrOp (Just (mo_s_16ToWord dflags)) b16 res args emitPrimOp dflags res IndexOffAddrOp_Int32 args = doIndexOffAddrOp (Just (mo_s_32ToWord dflags)) b32 res args emitPrimOp _ res IndexOffAddrOp_Int64 args = doIndexOffAddrOp Nothing b64 res args emitPrimOp dflags res IndexOffAddrOp_Word8 args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res IndexOffAddrOp_Word16 args = doIndexOffAddrOp (Just (mo_u_16ToWord dflags)) b16 res args emitPrimOp dflags res IndexOffAddrOp_Word32 args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp _ res IndexOffAddrOp_Word64 args = doIndexOffAddrOp Nothing b64 res args -- ReadXXXoffAddr, which are identical, for our purposes, to IndexXXXoffAddr. emitPrimOp dflags res ReadOffAddrOp_Char args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res ReadOffAddrOp_WideChar args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp dflags res ReadOffAddrOp_Int args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res ReadOffAddrOp_Word args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res ReadOffAddrOp_Addr args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp _ res ReadOffAddrOp_Float args = doIndexOffAddrOp Nothing f32 res args emitPrimOp _ res ReadOffAddrOp_Double args = doIndexOffAddrOp Nothing f64 res args emitPrimOp dflags res ReadOffAddrOp_StablePtr args = doIndexOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res ReadOffAddrOp_Int8 args = doIndexOffAddrOp (Just (mo_s_8ToWord dflags)) b8 res args emitPrimOp dflags res ReadOffAddrOp_Int16 args = doIndexOffAddrOp (Just (mo_s_16ToWord dflags)) b16 res args emitPrimOp dflags res ReadOffAddrOp_Int32 args = doIndexOffAddrOp (Just (mo_s_32ToWord dflags)) b32 res args emitPrimOp _ res ReadOffAddrOp_Int64 args = doIndexOffAddrOp Nothing b64 res args emitPrimOp dflags res ReadOffAddrOp_Word8 args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res ReadOffAddrOp_Word16 args = doIndexOffAddrOp (Just (mo_u_16ToWord dflags)) b16 res args emitPrimOp dflags res ReadOffAddrOp_Word32 args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp _ res ReadOffAddrOp_Word64 args = doIndexOffAddrOp Nothing b64 res args -- IndexXXXArray emitPrimOp dflags res IndexByteArrayOp_Char args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res IndexByteArrayOp_WideChar args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp dflags res IndexByteArrayOp_Int args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res IndexByteArrayOp_Word args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res IndexByteArrayOp_Addr args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp _ res IndexByteArrayOp_Float args = doIndexByteArrayOp Nothing f32 res args emitPrimOp _ res IndexByteArrayOp_Double args = doIndexByteArrayOp Nothing f64 res args emitPrimOp dflags res IndexByteArrayOp_StablePtr args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res IndexByteArrayOp_Int8 args = doIndexByteArrayOp (Just (mo_s_8ToWord dflags)) b8 res args emitPrimOp dflags res IndexByteArrayOp_Int16 args = doIndexByteArrayOp (Just (mo_s_16ToWord dflags)) b16 res args emitPrimOp dflags res IndexByteArrayOp_Int32 args = doIndexByteArrayOp (Just (mo_s_32ToWord dflags)) b32 res args emitPrimOp _ res IndexByteArrayOp_Int64 args = doIndexByteArrayOp Nothing b64 res args emitPrimOp dflags res IndexByteArrayOp_Word8 args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res IndexByteArrayOp_Word16 args = doIndexByteArrayOp (Just (mo_u_16ToWord dflags)) b16 res args emitPrimOp dflags res IndexByteArrayOp_Word32 args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp _ res IndexByteArrayOp_Word64 args = doIndexByteArrayOp Nothing b64 res args -- ReadXXXArray, identical to IndexXXXArray. emitPrimOp dflags res ReadByteArrayOp_Char args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res ReadByteArrayOp_WideChar args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp dflags res ReadByteArrayOp_Int args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res ReadByteArrayOp_Word args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res ReadByteArrayOp_Addr args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp _ res ReadByteArrayOp_Float args = doIndexByteArrayOp Nothing f32 res args emitPrimOp _ res ReadByteArrayOp_Double args = doIndexByteArrayOp Nothing f64 res args emitPrimOp dflags res ReadByteArrayOp_StablePtr args = doIndexByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res ReadByteArrayOp_Int8 args = doIndexByteArrayOp (Just (mo_s_8ToWord dflags)) b8 res args emitPrimOp dflags res ReadByteArrayOp_Int16 args = doIndexByteArrayOp (Just (mo_s_16ToWord dflags)) b16 res args emitPrimOp dflags res ReadByteArrayOp_Int32 args = doIndexByteArrayOp (Just (mo_s_32ToWord dflags)) b32 res args emitPrimOp _ res ReadByteArrayOp_Int64 args = doIndexByteArrayOp Nothing b64 res args emitPrimOp dflags res ReadByteArrayOp_Word8 args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args emitPrimOp dflags res ReadByteArrayOp_Word16 args = doIndexByteArrayOp (Just (mo_u_16ToWord dflags)) b16 res args emitPrimOp dflags res ReadByteArrayOp_Word32 args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args emitPrimOp _ res ReadByteArrayOp_Word64 args = doIndexByteArrayOp Nothing b64 res args -- WriteXXXoffAddr emitPrimOp dflags res WriteOffAddrOp_Char args = doWriteOffAddrOp (Just (mo_WordTo8 dflags)) b8 res args emitPrimOp dflags res WriteOffAddrOp_WideChar args = doWriteOffAddrOp (Just (mo_WordTo32 dflags)) b32 res args emitPrimOp dflags res WriteOffAddrOp_Int args = doWriteOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res WriteOffAddrOp_Word args = doWriteOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res WriteOffAddrOp_Addr args = doWriteOffAddrOp Nothing (bWord dflags) res args emitPrimOp _ res WriteOffAddrOp_Float args = doWriteOffAddrOp Nothing f32 res args emitPrimOp _ res WriteOffAddrOp_Double args = doWriteOffAddrOp Nothing f64 res args emitPrimOp dflags res WriteOffAddrOp_StablePtr args = doWriteOffAddrOp Nothing (bWord dflags) res args emitPrimOp dflags res WriteOffAddrOp_Int8 args = doWriteOffAddrOp (Just (mo_WordTo8 dflags)) b8 res args emitPrimOp dflags res WriteOffAddrOp_Int16 args = doWriteOffAddrOp (Just (mo_WordTo16 dflags)) b16 res args emitPrimOp dflags res WriteOffAddrOp_Int32 args = doWriteOffAddrOp (Just (mo_WordTo32 dflags)) b32 res args emitPrimOp _ res WriteOffAddrOp_Int64 args = doWriteOffAddrOp Nothing b64 res args emitPrimOp dflags res WriteOffAddrOp_Word8 args = doWriteOffAddrOp (Just (mo_WordTo8 dflags)) b8 res args emitPrimOp dflags res WriteOffAddrOp_Word16 args = doWriteOffAddrOp (Just (mo_WordTo16 dflags)) b16 res args emitPrimOp dflags res WriteOffAddrOp_Word32 args = doWriteOffAddrOp (Just (mo_WordTo32 dflags)) b32 res args emitPrimOp _ res WriteOffAddrOp_Word64 args = doWriteOffAddrOp Nothing b64 res args -- WriteXXXArray emitPrimOp dflags res WriteByteArrayOp_Char args = doWriteByteArrayOp (Just (mo_WordTo8 dflags)) b8 res args emitPrimOp dflags res WriteByteArrayOp_WideChar args = doWriteByteArrayOp (Just (mo_WordTo32 dflags)) b32 res args emitPrimOp dflags res WriteByteArrayOp_Int args = doWriteByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res WriteByteArrayOp_Word args = doWriteByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res WriteByteArrayOp_Addr args = doWriteByteArrayOp Nothing (bWord dflags) res args emitPrimOp _ res WriteByteArrayOp_Float args = doWriteByteArrayOp Nothing f32 res args emitPrimOp _ res WriteByteArrayOp_Double args = doWriteByteArrayOp Nothing f64 res args emitPrimOp dflags res WriteByteArrayOp_StablePtr args = doWriteByteArrayOp Nothing (bWord dflags) res args emitPrimOp dflags res WriteByteArrayOp_Int8 args = doWriteByteArrayOp (Just (mo_WordTo8 dflags)) b8 res args emitPrimOp dflags res WriteByteArrayOp_Int16 args = doWriteByteArrayOp (Just (mo_WordTo16 dflags)) b16 res args emitPrimOp dflags res WriteByteArrayOp_Int32 args = doWriteByteArrayOp (Just (mo_WordTo32 dflags)) b32 res args emitPrimOp _ res WriteByteArrayOp_Int64 args = doWriteByteArrayOp Nothing b64 res args emitPrimOp dflags res WriteByteArrayOp_Word8 args = doWriteByteArrayOp (Just (mo_WordTo8 dflags)) b8 res args emitPrimOp dflags res WriteByteArrayOp_Word16 args = doWriteByteArrayOp (Just (mo_WordTo16 dflags)) b16 res args emitPrimOp dflags res WriteByteArrayOp_Word32 args = doWriteByteArrayOp (Just (mo_WordTo32 dflags)) b32 res args emitPrimOp _ res WriteByteArrayOp_Word64 args = doWriteByteArrayOp Nothing b64 res args -- Copying and setting byte arrays emitPrimOp _ [] CopyByteArrayOp [src,src_off,dst,dst_off,n] = doCopyByteArrayOp src src_off dst dst_off n emitPrimOp _ [] CopyMutableByteArrayOp [src,src_off,dst,dst_off,n] = doCopyMutableByteArrayOp src src_off dst dst_off n emitPrimOp _ [] CopyByteArrayToAddrOp [src,src_off,dst,n] = doCopyByteArrayToAddrOp src src_off dst n emitPrimOp _ [] CopyMutableByteArrayToAddrOp [src,src_off,dst,n] = doCopyMutableByteArrayToAddrOp src src_off dst n emitPrimOp _ [] CopyAddrToByteArrayOp [src,dst,dst_off,n] = doCopyAddrToByteArrayOp src dst dst_off n emitPrimOp _ [] SetByteArrayOp [ba,off,len,c] = doSetByteArrayOp ba off len c emitPrimOp _ [res] BSwap16Op [w] = emitBSwapCall res w W16 emitPrimOp _ [res] BSwap32Op [w] = emitBSwapCall res w W32 emitPrimOp _ [res] BSwap64Op [w] = emitBSwapCall res w W64 emitPrimOp dflags [res] BSwapOp [w] = emitBSwapCall res w (wordWidth dflags) -- Population count emitPrimOp _ [res] PopCnt8Op [w] = emitPopCntCall res w W8 emitPrimOp _ [res] PopCnt16Op [w] = emitPopCntCall res w W16 emitPrimOp _ [res] PopCnt32Op [w] = emitPopCntCall res w W32 emitPrimOp _ [res] PopCnt64Op [w] = emitPopCntCall res w W64 emitPrimOp dflags [res] PopCntOp [w] = emitPopCntCall res w (wordWidth dflags) -- count leading zeros emitPrimOp _ [res] Clz8Op [w] = emitClzCall res w W8 emitPrimOp _ [res] Clz16Op [w] = emitClzCall res w W16 emitPrimOp _ [res] Clz32Op [w] = emitClzCall res w W32 emitPrimOp _ [res] Clz64Op [w] = emitClzCall res w W64 emitPrimOp dflags [res] ClzOp [w] = emitClzCall res w (wordWidth dflags) -- count trailing zeros emitPrimOp _ [res] Ctz8Op [w] = emitCtzCall res w W8 emitPrimOp _ [res] Ctz16Op [w] = emitCtzCall res w W16 emitPrimOp _ [res] Ctz32Op [w] = emitCtzCall res w W32 emitPrimOp _ [res] Ctz64Op [w] = emitCtzCall res w W64 emitPrimOp dflags [res] CtzOp [w] = emitCtzCall res w (wordWidth dflags) -- Unsigned int to floating point conversions emitPrimOp _ [res] Word2FloatOp [w] = emitPrimCall [res] (MO_UF_Conv W32) [w] emitPrimOp _ [res] Word2DoubleOp [w] = emitPrimCall [res] (MO_UF_Conv W64) [w] -- SIMD primops emitPrimOp dflags [res] (VecBroadcastOp vcat n w) [e] = do checkVecCompatibility dflags vcat n w doVecPackOp (vecElemInjectCast dflags vcat w) ty zeros (replicate n e) res where zeros :: CmmExpr zeros = CmmLit $ CmmVec (replicate n zero) zero :: CmmLit zero = case vcat of IntVec -> CmmInt 0 w WordVec -> CmmInt 0 w FloatVec -> CmmFloat 0 w ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags [res] (VecPackOp vcat n w) es = do checkVecCompatibility dflags vcat n w when (length es /= n) $ panic "emitPrimOp: VecPackOp has wrong number of arguments" doVecPackOp (vecElemInjectCast dflags vcat w) ty zeros es res where zeros :: CmmExpr zeros = CmmLit $ CmmVec (replicate n zero) zero :: CmmLit zero = case vcat of IntVec -> CmmInt 0 w WordVec -> CmmInt 0 w FloatVec -> CmmFloat 0 w ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecUnpackOp vcat n w) [arg] = do checkVecCompatibility dflags vcat n w when (length res /= n) $ panic "emitPrimOp: VecUnpackOp has wrong number of results" doVecUnpackOp (vecElemProjectCast dflags vcat w) ty arg res where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags [res] (VecInsertOp vcat n w) [v,e,i] = do checkVecCompatibility dflags vcat n w doVecInsertOp (vecElemInjectCast dflags vcat w) ty v e i res where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecIndexByteArrayOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexByteArrayOp Nothing ty res args where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecReadByteArrayOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexByteArrayOp Nothing ty res args where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecWriteByteArrayOp vcat n w) args = do checkVecCompatibility dflags vcat n w doWriteByteArrayOp Nothing ty res args where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecIndexOffAddrOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexOffAddrOp Nothing ty res args where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecReadOffAddrOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexOffAddrOp Nothing ty res args where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecWriteOffAddrOp vcat n w) args = do checkVecCompatibility dflags vcat n w doWriteOffAddrOp Nothing ty res args where ty :: CmmType ty = vecVmmType vcat n w emitPrimOp dflags res (VecIndexScalarByteArrayOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexByteArrayOpAs Nothing vecty ty res args where vecty :: CmmType vecty = vecVmmType vcat n w ty :: CmmType ty = vecCmmCat vcat w emitPrimOp dflags res (VecReadScalarByteArrayOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexByteArrayOpAs Nothing vecty ty res args where vecty :: CmmType vecty = vecVmmType vcat n w ty :: CmmType ty = vecCmmCat vcat w emitPrimOp dflags res (VecWriteScalarByteArrayOp vcat n w) args = do checkVecCompatibility dflags vcat n w doWriteByteArrayOp Nothing ty res args where ty :: CmmType ty = vecCmmCat vcat w emitPrimOp dflags res (VecIndexScalarOffAddrOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexOffAddrOpAs Nothing vecty ty res args where vecty :: CmmType vecty = vecVmmType vcat n w ty :: CmmType ty = vecCmmCat vcat w emitPrimOp dflags res (VecReadScalarOffAddrOp vcat n w) args = do checkVecCompatibility dflags vcat n w doIndexOffAddrOpAs Nothing vecty ty res args where vecty :: CmmType vecty = vecVmmType vcat n w ty :: CmmType ty = vecCmmCat vcat w emitPrimOp dflags res (VecWriteScalarOffAddrOp vcat n w) args = do checkVecCompatibility dflags vcat n w doWriteOffAddrOp Nothing ty res args where ty :: CmmType ty = vecCmmCat vcat w -- Prefetch emitPrimOp _ [] PrefetchByteArrayOp3 args = doPrefetchByteArrayOp 3 args emitPrimOp _ [] PrefetchMutableByteArrayOp3 args = doPrefetchMutableByteArrayOp 3 args emitPrimOp _ [] PrefetchAddrOp3 args = doPrefetchAddrOp 3 args emitPrimOp _ [] PrefetchValueOp3 args = doPrefetchValueOp 3 args emitPrimOp _ [] PrefetchByteArrayOp2 args = doPrefetchByteArrayOp 2 args emitPrimOp _ [] PrefetchMutableByteArrayOp2 args = doPrefetchMutableByteArrayOp 2 args emitPrimOp _ [] PrefetchAddrOp2 args = doPrefetchAddrOp 2 args emitPrimOp _ [] PrefetchValueOp2 args = doPrefetchValueOp 2 args emitPrimOp _ [] PrefetchByteArrayOp1 args = doPrefetchByteArrayOp 1 args emitPrimOp _ [] PrefetchMutableByteArrayOp1 args = doPrefetchMutableByteArrayOp 1 args emitPrimOp _ [] PrefetchAddrOp1 args = doPrefetchAddrOp 1 args emitPrimOp _ [] PrefetchValueOp1 args = doPrefetchValueOp 1 args emitPrimOp _ [] PrefetchByteArrayOp0 args = doPrefetchByteArrayOp 0 args emitPrimOp _ [] PrefetchMutableByteArrayOp0 args = doPrefetchMutableByteArrayOp 0 args emitPrimOp _ [] PrefetchAddrOp0 args = doPrefetchAddrOp 0 args emitPrimOp _ [] PrefetchValueOp0 args = doPrefetchValueOp 0 args -- Atomic read-modify-write emitPrimOp dflags [res] FetchAddByteArrayOp_Int [mba, ix, n] = doAtomicRMW res AMO_Add mba ix (bWord dflags) n emitPrimOp dflags [res] FetchSubByteArrayOp_Int [mba, ix, n] = doAtomicRMW res AMO_Sub mba ix (bWord dflags) n emitPrimOp dflags [res] FetchAndByteArrayOp_Int [mba, ix, n] = doAtomicRMW res AMO_And mba ix (bWord dflags) n emitPrimOp dflags [res] FetchNandByteArrayOp_Int [mba, ix, n] = doAtomicRMW res AMO_Nand mba ix (bWord dflags) n emitPrimOp dflags [res] FetchOrByteArrayOp_Int [mba, ix, n] = doAtomicRMW res AMO_Or mba ix (bWord dflags) n emitPrimOp dflags [res] FetchXorByteArrayOp_Int [mba, ix, n] = doAtomicRMW res AMO_Xor mba ix (bWord dflags) n emitPrimOp dflags [res] AtomicReadByteArrayOp_Int [mba, ix] = doAtomicReadByteArray res mba ix (bWord dflags) emitPrimOp dflags [] AtomicWriteByteArrayOp_Int [mba, ix, val] = doAtomicWriteByteArray mba ix (bWord dflags) val emitPrimOp dflags [res] CasByteArrayOp_Int [mba, ix, old, new] = doCasByteArray res mba ix (bWord dflags) old new -- The rest just translate straightforwardly emitPrimOp dflags [res] op [arg] | nopOp op = emitAssign (CmmLocal res) arg | Just (mop,rep) <- narrowOp op = emitAssign (CmmLocal res) $ CmmMachOp (mop rep (wordWidth dflags)) [CmmMachOp (mop (wordWidth dflags) rep) [arg]] emitPrimOp dflags r@[res] op args | Just prim <- callishOp op = do emitPrimCall r prim args | Just mop <- translateOp dflags op = let stmt = mkAssign (CmmLocal res) (CmmMachOp mop args) in emit stmt emitPrimOp dflags results op args = case callishPrimOpSupported dflags op of Left op -> emit $ mkUnsafeCall (PrimTarget op) results args Right gen -> gen results args type GenericOp = [CmmFormal] -> [CmmActual] -> FCode () callishPrimOpSupported :: DynFlags -> PrimOp -> Either CallishMachOp GenericOp callishPrimOpSupported dflags op = case op of IntQuotRemOp | ncg && x86ish -> Left (MO_S_QuotRem (wordWidth dflags)) | otherwise -> Right (genericIntQuotRemOp dflags) WordQuotRemOp | ncg && x86ish -> Left (MO_U_QuotRem (wordWidth dflags)) | otherwise -> Right (genericWordQuotRemOp dflags) WordQuotRem2Op | (ncg && x86ish) || llvm -> Left (MO_U_QuotRem2 (wordWidth dflags)) | otherwise -> Right (genericWordQuotRem2Op dflags) WordAdd2Op | (ncg && x86ish) || llvm -> Left (MO_Add2 (wordWidth dflags)) | otherwise -> Right genericWordAdd2Op IntAddCOp | (ncg && x86ish) || llvm -> Left (MO_AddIntC (wordWidth dflags)) | otherwise -> Right genericIntAddCOp IntSubCOp | (ncg && x86ish) || llvm -> Left (MO_SubIntC (wordWidth dflags)) | otherwise -> Right genericIntSubCOp WordMul2Op | ncg && x86ish || llvm -> Left (MO_U_Mul2 (wordWidth dflags)) | otherwise -> Right genericWordMul2Op _ -> pprPanic "emitPrimOp: can't translate PrimOp " (ppr op) where ncg = case hscTarget dflags of HscAsm -> True _ -> False llvm = case hscTarget dflags of HscLlvm -> True _ -> False x86ish = case platformArch (targetPlatform dflags) of ArchX86 -> True ArchX86_64 -> True _ -> False genericIntQuotRemOp :: DynFlags -> GenericOp genericIntQuotRemOp dflags [res_q, res_r] [arg_x, arg_y] = emit $ mkAssign (CmmLocal res_q) (CmmMachOp (MO_S_Quot (wordWidth dflags)) [arg_x, arg_y]) <*> mkAssign (CmmLocal res_r) (CmmMachOp (MO_S_Rem (wordWidth dflags)) [arg_x, arg_y]) genericIntQuotRemOp _ _ _ = panic "genericIntQuotRemOp" genericWordQuotRemOp :: DynFlags -> GenericOp genericWordQuotRemOp dflags [res_q, res_r] [arg_x, arg_y] = emit $ mkAssign (CmmLocal res_q) (CmmMachOp (MO_U_Quot (wordWidth dflags)) [arg_x, arg_y]) <*> mkAssign (CmmLocal res_r) (CmmMachOp (MO_U_Rem (wordWidth dflags)) [arg_x, arg_y]) genericWordQuotRemOp _ _ _ = panic "genericWordQuotRemOp" genericWordQuotRem2Op :: DynFlags -> GenericOp genericWordQuotRem2Op dflags [res_q, res_r] [arg_x_high, arg_x_low, arg_y] = emit =<< f (widthInBits (wordWidth dflags)) zero arg_x_high arg_x_low where ty = cmmExprType dflags arg_x_high shl x i = CmmMachOp (MO_Shl (wordWidth dflags)) [x, i] shr x i = CmmMachOp (MO_U_Shr (wordWidth dflags)) [x, i] or x y = CmmMachOp (MO_Or (wordWidth dflags)) [x, y] ge x y = CmmMachOp (MO_U_Ge (wordWidth dflags)) [x, y] ne x y = CmmMachOp (MO_Ne (wordWidth dflags)) [x, y] minus x y = CmmMachOp (MO_Sub (wordWidth dflags)) [x, y] times x y = CmmMachOp (MO_Mul (wordWidth dflags)) [x, y] zero = lit 0 one = lit 1 negone = lit (fromIntegral (widthInBits (wordWidth dflags)) - 1) lit i = CmmLit (CmmInt i (wordWidth dflags)) f :: Int -> CmmExpr -> CmmExpr -> CmmExpr -> FCode CmmAGraph f 0 acc high _ = return (mkAssign (CmmLocal res_q) acc <*> mkAssign (CmmLocal res_r) high) f i acc high low = do roverflowedBit <- newTemp ty rhigh' <- newTemp ty rhigh'' <- newTemp ty rlow' <- newTemp ty risge <- newTemp ty racc' <- newTemp ty let high' = CmmReg (CmmLocal rhigh') isge = CmmReg (CmmLocal risge) overflowedBit = CmmReg (CmmLocal roverflowedBit) let this = catAGraphs [mkAssign (CmmLocal roverflowedBit) (shr high negone), mkAssign (CmmLocal rhigh') (or (shl high one) (shr low negone)), mkAssign (CmmLocal rlow') (shl low one), mkAssign (CmmLocal risge) (or (overflowedBit `ne` zero) (high' `ge` arg_y)), mkAssign (CmmLocal rhigh'') (high' `minus` (arg_y `times` isge)), mkAssign (CmmLocal racc') (or (shl acc one) isge)] rest <- f (i - 1) (CmmReg (CmmLocal racc')) (CmmReg (CmmLocal rhigh'')) (CmmReg (CmmLocal rlow')) return (this <*> rest) genericWordQuotRem2Op _ _ _ = panic "genericWordQuotRem2Op" genericWordAdd2Op :: GenericOp genericWordAdd2Op [res_h, res_l] [arg_x, arg_y] = do dflags <- getDynFlags r1 <- newTemp (cmmExprType dflags arg_x) r2 <- newTemp (cmmExprType dflags arg_x) let topHalf x = CmmMachOp (MO_U_Shr (wordWidth dflags)) [x, hww] toTopHalf x = CmmMachOp (MO_Shl (wordWidth dflags)) [x, hww] bottomHalf x = CmmMachOp (MO_And (wordWidth dflags)) [x, hwm] add x y = CmmMachOp (MO_Add (wordWidth dflags)) [x, y] or x y = CmmMachOp (MO_Or (wordWidth dflags)) [x, y] hww = CmmLit (CmmInt (fromIntegral (widthInBits (halfWordWidth dflags))) (wordWidth dflags)) hwm = CmmLit (CmmInt (halfWordMask dflags) (wordWidth dflags)) emit $ catAGraphs [mkAssign (CmmLocal r1) (add (bottomHalf arg_x) (bottomHalf arg_y)), mkAssign (CmmLocal r2) (add (topHalf (CmmReg (CmmLocal r1))) (add (topHalf arg_x) (topHalf arg_y))), mkAssign (CmmLocal res_h) (topHalf (CmmReg (CmmLocal r2))), mkAssign (CmmLocal res_l) (or (toTopHalf (CmmReg (CmmLocal r2))) (bottomHalf (CmmReg (CmmLocal r1))))] genericWordAdd2Op _ _ = panic "genericWordAdd2Op" genericIntAddCOp :: GenericOp genericIntAddCOp [res_r, res_c] [aa, bb] {- With some bit-twiddling, we can define int{Add,Sub}Czh portably in C, and without needing any comparisons. This may not be the fastest way to do it - if you have better code, please send it! --SDM Return : r = a + b, c = 0 if no overflow, 1 on overflow. We currently don't make use of the r value if c is != 0 (i.e. overflow), we just convert to big integers and try again. This could be improved by making r and c the correct values for plugging into a new J#. { r = ((I_)(a)) + ((I_)(b)); \ c = ((StgWord)(~(((I_)(a))^((I_)(b))) & (((I_)(a))^r))) \ >> (BITS_IN (I_) - 1); \ } Wading through the mass of bracketry, it seems to reduce to: c = ( (~(a^b)) & (a^r) ) >>unsigned (BITS_IN(I_)-1) -} = do dflags <- getDynFlags emit $ catAGraphs [ mkAssign (CmmLocal res_r) (CmmMachOp (mo_wordAdd dflags) [aa,bb]), mkAssign (CmmLocal res_c) $ CmmMachOp (mo_wordUShr dflags) [ CmmMachOp (mo_wordAnd dflags) [ CmmMachOp (mo_wordNot dflags) [CmmMachOp (mo_wordXor dflags) [aa,bb]], CmmMachOp (mo_wordXor dflags) [aa, CmmReg (CmmLocal res_r)] ], mkIntExpr dflags (wORD_SIZE_IN_BITS dflags - 1) ] ] genericIntAddCOp _ _ = panic "genericIntAddCOp" genericIntSubCOp :: GenericOp genericIntSubCOp [res_r, res_c] [aa, bb] {- Similarly: #define subIntCzh(r,c,a,b) \ { r = ((I_)(a)) - ((I_)(b)); \ c = ((StgWord)((((I_)(a))^((I_)(b))) & (((I_)(a))^r))) \ >> (BITS_IN (I_) - 1); \ } c = ((a^b) & (a^r)) >>unsigned (BITS_IN(I_)-1) -} = do dflags <- getDynFlags emit $ catAGraphs [ mkAssign (CmmLocal res_r) (CmmMachOp (mo_wordSub dflags) [aa,bb]), mkAssign (CmmLocal res_c) $ CmmMachOp (mo_wordUShr dflags) [ CmmMachOp (mo_wordAnd dflags) [ CmmMachOp (mo_wordXor dflags) [aa,bb], CmmMachOp (mo_wordXor dflags) [aa, CmmReg (CmmLocal res_r)] ], mkIntExpr dflags (wORD_SIZE_IN_BITS dflags - 1) ] ] genericIntSubCOp _ _ = panic "genericIntSubCOp" genericWordMul2Op :: GenericOp genericWordMul2Op [res_h, res_l] [arg_x, arg_y] = do dflags <- getDynFlags let t = cmmExprType dflags arg_x xlyl <- liftM CmmLocal $ newTemp t xlyh <- liftM CmmLocal $ newTemp t xhyl <- liftM CmmLocal $ newTemp t r <- liftM CmmLocal $ newTemp t -- This generic implementation is very simple and slow. We might -- well be able to do better, but for now this at least works. let topHalf x = CmmMachOp (MO_U_Shr (wordWidth dflags)) [x, hww] toTopHalf x = CmmMachOp (MO_Shl (wordWidth dflags)) [x, hww] bottomHalf x = CmmMachOp (MO_And (wordWidth dflags)) [x, hwm] add x y = CmmMachOp (MO_Add (wordWidth dflags)) [x, y] sum = foldl1 add mul x y = CmmMachOp (MO_Mul (wordWidth dflags)) [x, y] or x y = CmmMachOp (MO_Or (wordWidth dflags)) [x, y] hww = CmmLit (CmmInt (fromIntegral (widthInBits (halfWordWidth dflags))) (wordWidth dflags)) hwm = CmmLit (CmmInt (halfWordMask dflags) (wordWidth dflags)) emit $ catAGraphs [mkAssign xlyl (mul (bottomHalf arg_x) (bottomHalf arg_y)), mkAssign xlyh (mul (bottomHalf arg_x) (topHalf arg_y)), mkAssign xhyl (mul (topHalf arg_x) (bottomHalf arg_y)), mkAssign r (sum [topHalf (CmmReg xlyl), bottomHalf (CmmReg xhyl), bottomHalf (CmmReg xlyh)]), mkAssign (CmmLocal res_l) (or (bottomHalf (CmmReg xlyl)) (toTopHalf (CmmReg r))), mkAssign (CmmLocal res_h) (sum [mul (topHalf arg_x) (topHalf arg_y), topHalf (CmmReg xhyl), topHalf (CmmReg xlyh), topHalf (CmmReg r)])] genericWordMul2Op _ _ = panic "genericWordMul2Op" -- These PrimOps are NOPs in Cmm nopOp :: PrimOp -> Bool nopOp Int2WordOp = True nopOp Word2IntOp = True nopOp Int2AddrOp = True nopOp Addr2IntOp = True nopOp ChrOp = True -- Int# and Char# are rep'd the same nopOp OrdOp = True nopOp _ = False -- These PrimOps turn into double casts narrowOp :: PrimOp -> Maybe (Width -> Width -> MachOp, Width) narrowOp Narrow8IntOp = Just (MO_SS_Conv, W8) narrowOp Narrow16IntOp = Just (MO_SS_Conv, W16) narrowOp Narrow32IntOp = Just (MO_SS_Conv, W32) narrowOp Narrow8WordOp = Just (MO_UU_Conv, W8) narrowOp Narrow16WordOp = Just (MO_UU_Conv, W16) narrowOp Narrow32WordOp = Just (MO_UU_Conv, W32) narrowOp _ = Nothing -- Native word signless ops translateOp :: DynFlags -> PrimOp -> Maybe MachOp translateOp dflags IntAddOp = Just (mo_wordAdd dflags) translateOp dflags IntSubOp = Just (mo_wordSub dflags) translateOp dflags WordAddOp = Just (mo_wordAdd dflags) translateOp dflags WordSubOp = Just (mo_wordSub dflags) translateOp dflags AddrAddOp = Just (mo_wordAdd dflags) translateOp dflags AddrSubOp = Just (mo_wordSub dflags) translateOp dflags IntEqOp = Just (mo_wordEq dflags) translateOp dflags IntNeOp = Just (mo_wordNe dflags) translateOp dflags WordEqOp = Just (mo_wordEq dflags) translateOp dflags WordNeOp = Just (mo_wordNe dflags) translateOp dflags AddrEqOp = Just (mo_wordEq dflags) translateOp dflags AddrNeOp = Just (mo_wordNe dflags) translateOp dflags AndOp = Just (mo_wordAnd dflags) translateOp dflags OrOp = Just (mo_wordOr dflags) translateOp dflags XorOp = Just (mo_wordXor dflags) translateOp dflags NotOp = Just (mo_wordNot dflags) translateOp dflags SllOp = Just (mo_wordShl dflags) translateOp dflags SrlOp = Just (mo_wordUShr dflags) translateOp dflags AddrRemOp = Just (mo_wordURem dflags) -- Native word signed ops translateOp dflags IntMulOp = Just (mo_wordMul dflags) translateOp dflags IntMulMayOfloOp = Just (MO_S_MulMayOflo (wordWidth dflags)) translateOp dflags IntQuotOp = Just (mo_wordSQuot dflags) translateOp dflags IntRemOp = Just (mo_wordSRem dflags) translateOp dflags IntNegOp = Just (mo_wordSNeg dflags) translateOp dflags IntGeOp = Just (mo_wordSGe dflags) translateOp dflags IntLeOp = Just (mo_wordSLe dflags) translateOp dflags IntGtOp = Just (mo_wordSGt dflags) translateOp dflags IntLtOp = Just (mo_wordSLt dflags) translateOp dflags AndIOp = Just (mo_wordAnd dflags) translateOp dflags OrIOp = Just (mo_wordOr dflags) translateOp dflags XorIOp = Just (mo_wordXor dflags) translateOp dflags NotIOp = Just (mo_wordNot dflags) translateOp dflags ISllOp = Just (mo_wordShl dflags) translateOp dflags ISraOp = Just (mo_wordSShr dflags) translateOp dflags ISrlOp = Just (mo_wordUShr dflags) -- Native word unsigned ops translateOp dflags WordGeOp = Just (mo_wordUGe dflags) translateOp dflags WordLeOp = Just (mo_wordULe dflags) translateOp dflags WordGtOp = Just (mo_wordUGt dflags) translateOp dflags WordLtOp = Just (mo_wordULt dflags) translateOp dflags WordMulOp = Just (mo_wordMul dflags) translateOp dflags WordQuotOp = Just (mo_wordUQuot dflags) translateOp dflags WordRemOp = Just (mo_wordURem dflags) translateOp dflags AddrGeOp = Just (mo_wordUGe dflags) translateOp dflags AddrLeOp = Just (mo_wordULe dflags) translateOp dflags AddrGtOp = Just (mo_wordUGt dflags) translateOp dflags AddrLtOp = Just (mo_wordULt dflags) -- Char# ops translateOp dflags CharEqOp = Just (MO_Eq (wordWidth dflags)) translateOp dflags CharNeOp = Just (MO_Ne (wordWidth dflags)) translateOp dflags CharGeOp = Just (MO_U_Ge (wordWidth dflags)) translateOp dflags CharLeOp = Just (MO_U_Le (wordWidth dflags)) translateOp dflags CharGtOp = Just (MO_U_Gt (wordWidth dflags)) translateOp dflags CharLtOp = Just (MO_U_Lt (wordWidth dflags)) -- Double ops translateOp _ DoubleEqOp = Just (MO_F_Eq W64) translateOp _ DoubleNeOp = Just (MO_F_Ne W64) translateOp _ DoubleGeOp = Just (MO_F_Ge W64) translateOp _ DoubleLeOp = Just (MO_F_Le W64) translateOp _ DoubleGtOp = Just (MO_F_Gt W64) translateOp _ DoubleLtOp = Just (MO_F_Lt W64) translateOp _ DoubleAddOp = Just (MO_F_Add W64) translateOp _ DoubleSubOp = Just (MO_F_Sub W64) translateOp _ DoubleMulOp = Just (MO_F_Mul W64) translateOp _ DoubleDivOp = Just (MO_F_Quot W64) translateOp _ DoubleNegOp = Just (MO_F_Neg W64) -- Float ops translateOp _ FloatEqOp = Just (MO_F_Eq W32) translateOp _ FloatNeOp = Just (MO_F_Ne W32) translateOp _ FloatGeOp = Just (MO_F_Ge W32) translateOp _ FloatLeOp = Just (MO_F_Le W32) translateOp _ FloatGtOp = Just (MO_F_Gt W32) translateOp _ FloatLtOp = Just (MO_F_Lt W32) translateOp _ FloatAddOp = Just (MO_F_Add W32) translateOp _ FloatSubOp = Just (MO_F_Sub W32) translateOp _ FloatMulOp = Just (MO_F_Mul W32) translateOp _ FloatDivOp = Just (MO_F_Quot W32) translateOp _ FloatNegOp = Just (MO_F_Neg W32) -- Vector ops translateOp _ (VecAddOp FloatVec n w) = Just (MO_VF_Add n w) translateOp _ (VecSubOp FloatVec n w) = Just (MO_VF_Sub n w) translateOp _ (VecMulOp FloatVec n w) = Just (MO_VF_Mul n w) translateOp _ (VecDivOp FloatVec n w) = Just (MO_VF_Quot n w) translateOp _ (VecNegOp FloatVec n w) = Just (MO_VF_Neg n w) translateOp _ (VecAddOp IntVec n w) = Just (MO_V_Add n w) translateOp _ (VecSubOp IntVec n w) = Just (MO_V_Sub n w) translateOp _ (VecMulOp IntVec n w) = Just (MO_V_Mul n w) translateOp _ (VecQuotOp IntVec n w) = Just (MO_VS_Quot n w) translateOp _ (VecRemOp IntVec n w) = Just (MO_VS_Rem n w) translateOp _ (VecNegOp IntVec n w) = Just (MO_VS_Neg n w) translateOp _ (VecAddOp WordVec n w) = Just (MO_V_Add n w) translateOp _ (VecSubOp WordVec n w) = Just (MO_V_Sub n w) translateOp _ (VecMulOp WordVec n w) = Just (MO_V_Mul n w) translateOp _ (VecQuotOp WordVec n w) = Just (MO_VU_Quot n w) translateOp _ (VecRemOp WordVec n w) = Just (MO_VU_Rem n w) -- Conversions translateOp dflags Int2DoubleOp = Just (MO_SF_Conv (wordWidth dflags) W64) translateOp dflags Double2IntOp = Just (MO_FS_Conv W64 (wordWidth dflags)) translateOp dflags Int2FloatOp = Just (MO_SF_Conv (wordWidth dflags) W32) translateOp dflags Float2IntOp = Just (MO_FS_Conv W32 (wordWidth dflags)) translateOp _ Float2DoubleOp = Just (MO_FF_Conv W32 W64) translateOp _ Double2FloatOp = Just (MO_FF_Conv W64 W32) -- Word comparisons masquerading as more exotic things. translateOp dflags SameMutVarOp = Just (mo_wordEq dflags) translateOp dflags SameMVarOp = Just (mo_wordEq dflags) translateOp dflags SameMutableArrayOp = Just (mo_wordEq dflags) translateOp dflags SameMutableByteArrayOp = Just (mo_wordEq dflags) translateOp dflags SameMutableArrayArrayOp= Just (mo_wordEq dflags) translateOp dflags SameSmallMutableArrayOp= Just (mo_wordEq dflags) translateOp dflags SameTVarOp = Just (mo_wordEq dflags) translateOp dflags EqStablePtrOp = Just (mo_wordEq dflags) translateOp _ _ = Nothing -- These primops are implemented by CallishMachOps, because they sometimes -- turn into foreign calls depending on the backend. callishOp :: PrimOp -> Maybe CallishMachOp callishOp DoublePowerOp = Just MO_F64_Pwr callishOp DoubleSinOp = Just MO_F64_Sin callishOp DoubleCosOp = Just MO_F64_Cos callishOp DoubleTanOp = Just MO_F64_Tan callishOp DoubleSinhOp = Just MO_F64_Sinh callishOp DoubleCoshOp = Just MO_F64_Cosh callishOp DoubleTanhOp = Just MO_F64_Tanh callishOp DoubleAsinOp = Just MO_F64_Asin callishOp DoubleAcosOp = Just MO_F64_Acos callishOp DoubleAtanOp = Just MO_F64_Atan callishOp DoubleLogOp = Just MO_F64_Log callishOp DoubleExpOp = Just MO_F64_Exp callishOp DoubleSqrtOp = Just MO_F64_Sqrt callishOp FloatPowerOp = Just MO_F32_Pwr callishOp FloatSinOp = Just MO_F32_Sin callishOp FloatCosOp = Just MO_F32_Cos callishOp FloatTanOp = Just MO_F32_Tan callishOp FloatSinhOp = Just MO_F32_Sinh callishOp FloatCoshOp = Just MO_F32_Cosh callishOp FloatTanhOp = Just MO_F32_Tanh callishOp FloatAsinOp = Just MO_F32_Asin callishOp FloatAcosOp = Just MO_F32_Acos callishOp FloatAtanOp = Just MO_F32_Atan callishOp FloatLogOp = Just MO_F32_Log callishOp FloatExpOp = Just MO_F32_Exp callishOp FloatSqrtOp = Just MO_F32_Sqrt callishOp _ = Nothing ------------------------------------------------------------------------------ -- Helpers for translating various minor variants of array indexing. doIndexOffAddrOp :: Maybe MachOp -> CmmType -> [LocalReg] -> [CmmExpr] -> FCode () doIndexOffAddrOp maybe_post_read_cast rep [res] [addr,idx] = mkBasicIndexedRead 0 maybe_post_read_cast rep res addr rep idx doIndexOffAddrOp _ _ _ _ = panic "StgCmmPrim: doIndexOffAddrOp" doIndexOffAddrOpAs :: Maybe MachOp -> CmmType -> CmmType -> [LocalReg] -> [CmmExpr] -> FCode () doIndexOffAddrOpAs maybe_post_read_cast rep idx_rep [res] [addr,idx] = mkBasicIndexedRead 0 maybe_post_read_cast rep res addr idx_rep idx doIndexOffAddrOpAs _ _ _ _ _ = panic "StgCmmPrim: doIndexOffAddrOpAs" doIndexByteArrayOp :: Maybe MachOp -> CmmType -> [LocalReg] -> [CmmExpr] -> FCode () doIndexByteArrayOp maybe_post_read_cast rep [res] [addr,idx] = do dflags <- getDynFlags mkBasicIndexedRead (arrWordsHdrSize dflags) maybe_post_read_cast rep res addr rep idx doIndexByteArrayOp _ _ _ _ = panic "StgCmmPrim: doIndexByteArrayOp" doIndexByteArrayOpAs :: Maybe MachOp -> CmmType -> CmmType -> [LocalReg] -> [CmmExpr] -> FCode () doIndexByteArrayOpAs maybe_post_read_cast rep idx_rep [res] [addr,idx] = do dflags <- getDynFlags mkBasicIndexedRead (arrWordsHdrSize dflags) maybe_post_read_cast rep res addr idx_rep idx doIndexByteArrayOpAs _ _ _ _ _ = panic "StgCmmPrim: doIndexByteArrayOpAs" doReadPtrArrayOp :: LocalReg -> CmmExpr -> CmmExpr -> FCode () doReadPtrArrayOp res addr idx = do dflags <- getDynFlags mkBasicIndexedRead (arrPtrsHdrSize dflags) Nothing (gcWord dflags) res addr (gcWord dflags) idx doWriteOffAddrOp :: Maybe MachOp -> CmmType -> [LocalReg] -> [CmmExpr] -> FCode () doWriteOffAddrOp maybe_pre_write_cast idx_ty [] [addr,idx,val] = mkBasicIndexedWrite 0 maybe_pre_write_cast addr idx_ty idx val doWriteOffAddrOp _ _ _ _ = panic "StgCmmPrim: doWriteOffAddrOp" doWriteByteArrayOp :: Maybe MachOp -> CmmType -> [LocalReg] -> [CmmExpr] -> FCode () doWriteByteArrayOp maybe_pre_write_cast idx_ty [] [addr,idx,val] = do dflags <- getDynFlags mkBasicIndexedWrite (arrWordsHdrSize dflags) maybe_pre_write_cast addr idx_ty idx val doWriteByteArrayOp _ _ _ _ = panic "StgCmmPrim: doWriteByteArrayOp" doWritePtrArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> FCode () doWritePtrArrayOp addr idx val = do dflags <- getDynFlags let ty = cmmExprType dflags val mkBasicIndexedWrite (arrPtrsHdrSize dflags) Nothing addr ty idx val emit (setInfo addr (CmmLit (CmmLabel mkMAP_DIRTY_infoLabel))) -- the write barrier. We must write a byte into the mark table: -- bits8[a + header_size + StgMutArrPtrs_size(a) + x >> N] emit $ mkStore ( cmmOffsetExpr dflags (cmmOffsetExprW dflags (cmmOffsetB dflags addr (arrPtrsHdrSize dflags)) (loadArrPtrsSize dflags addr)) (CmmMachOp (mo_wordUShr dflags) [idx, mkIntExpr dflags (mUT_ARR_PTRS_CARD_BITS dflags)]) ) (CmmLit (CmmInt 1 W8)) loadArrPtrsSize :: DynFlags -> CmmExpr -> CmmExpr loadArrPtrsSize dflags addr = CmmLoad (cmmOffsetB dflags addr off) (bWord dflags) where off = fixedHdrSize dflags + oFFSET_StgMutArrPtrs_ptrs dflags mkBasicIndexedRead :: ByteOff -- Initial offset in bytes -> Maybe MachOp -- Optional result cast -> CmmType -- Type of element we are accessing -> LocalReg -- Destination -> CmmExpr -- Base address -> CmmType -- Type of element by which we are indexing -> CmmExpr -- Index -> FCode () mkBasicIndexedRead off Nothing ty res base idx_ty idx = do dflags <- getDynFlags emitAssign (CmmLocal res) (cmmLoadIndexOffExpr dflags off ty base idx_ty idx) mkBasicIndexedRead off (Just cast) ty res base idx_ty idx = do dflags <- getDynFlags emitAssign (CmmLocal res) (CmmMachOp cast [ cmmLoadIndexOffExpr dflags off ty base idx_ty idx]) mkBasicIndexedWrite :: ByteOff -- Initial offset in bytes -> Maybe MachOp -- Optional value cast -> CmmExpr -- Base address -> CmmType -- Type of element by which we are indexing -> CmmExpr -- Index -> CmmExpr -- Value to write -> FCode () mkBasicIndexedWrite off Nothing base idx_ty idx val = do dflags <- getDynFlags emitStore (cmmIndexOffExpr dflags off (typeWidth idx_ty) base idx) val mkBasicIndexedWrite off (Just cast) base idx_ty idx val = mkBasicIndexedWrite off Nothing base idx_ty idx (CmmMachOp cast [val]) -- ---------------------------------------------------------------------------- -- Misc utils cmmIndexOffExpr :: DynFlags -> ByteOff -- Initial offset in bytes -> Width -- Width of element by which we are indexing -> CmmExpr -- Base address -> CmmExpr -- Index -> CmmExpr cmmIndexOffExpr dflags off width base idx = cmmIndexExpr dflags width (cmmOffsetB dflags base off) idx cmmLoadIndexOffExpr :: DynFlags -> ByteOff -- Initial offset in bytes -> CmmType -- Type of element we are accessing -> CmmExpr -- Base address -> CmmType -- Type of element by which we are indexing -> CmmExpr -- Index -> CmmExpr cmmLoadIndexOffExpr dflags off ty base idx_ty idx = CmmLoad (cmmIndexOffExpr dflags off (typeWidth idx_ty) base idx) ty setInfo :: CmmExpr -> CmmExpr -> CmmAGraph setInfo closure_ptr info_ptr = mkStore closure_ptr info_ptr ------------------------------------------------------------------------------ -- Helpers for translating vector primops. vecVmmType :: PrimOpVecCat -> Length -> Width -> CmmType vecVmmType pocat n w = vec n (vecCmmCat pocat w) vecCmmCat :: PrimOpVecCat -> Width -> CmmType vecCmmCat IntVec = cmmBits vecCmmCat WordVec = cmmBits vecCmmCat FloatVec = cmmFloat vecElemInjectCast :: DynFlags -> PrimOpVecCat -> Width -> Maybe MachOp vecElemInjectCast _ FloatVec _ = Nothing vecElemInjectCast dflags IntVec W8 = Just (mo_WordTo8 dflags) vecElemInjectCast dflags IntVec W16 = Just (mo_WordTo16 dflags) vecElemInjectCast dflags IntVec W32 = Just (mo_WordTo32 dflags) vecElemInjectCast _ IntVec W64 = Nothing vecElemInjectCast dflags WordVec W8 = Just (mo_WordTo8 dflags) vecElemInjectCast dflags WordVec W16 = Just (mo_WordTo16 dflags) vecElemInjectCast dflags WordVec W32 = Just (mo_WordTo32 dflags) vecElemInjectCast _ WordVec W64 = Nothing vecElemInjectCast _ _ _ = Nothing vecElemProjectCast :: DynFlags -> PrimOpVecCat -> Width -> Maybe MachOp vecElemProjectCast _ FloatVec _ = Nothing vecElemProjectCast dflags IntVec W8 = Just (mo_s_8ToWord dflags) vecElemProjectCast dflags IntVec W16 = Just (mo_s_16ToWord dflags) vecElemProjectCast dflags IntVec W32 = Just (mo_s_32ToWord dflags) vecElemProjectCast _ IntVec W64 = Nothing vecElemProjectCast dflags WordVec W8 = Just (mo_u_8ToWord dflags) vecElemProjectCast dflags WordVec W16 = Just (mo_u_16ToWord dflags) vecElemProjectCast dflags WordVec W32 = Just (mo_u_32ToWord dflags) vecElemProjectCast _ WordVec W64 = Nothing vecElemProjectCast _ _ _ = Nothing -- Check to make sure that we can generate code for the specified vector type -- given the current set of dynamic flags. checkVecCompatibility :: DynFlags -> PrimOpVecCat -> Length -> Width -> FCode () checkVecCompatibility dflags vcat l w = do when (hscTarget dflags /= HscLlvm) $ do sorry $ unlines ["SIMD vector instructions require the LLVM back-end." ,"Please use -fllvm."] check vecWidth vcat l w where check :: Width -> PrimOpVecCat -> Length -> Width -> FCode () check W128 FloatVec 4 W32 | not (isSseEnabled dflags) = sorry $ "128-bit wide single-precision floating point " ++ "SIMD vector instructions require at least -msse." check W128 _ _ _ | not (isSse2Enabled dflags) = sorry $ "128-bit wide integer and double precision " ++ "SIMD vector instructions require at least -msse2." check W256 FloatVec _ _ | not (isAvxEnabled dflags) = sorry $ "256-bit wide floating point " ++ "SIMD vector instructions require at least -mavx." check W256 _ _ _ | not (isAvx2Enabled dflags) = sorry $ "256-bit wide integer " ++ "SIMD vector instructions require at least -mavx2." check W512 _ _ _ | not (isAvx512fEnabled dflags) = sorry $ "512-bit wide " ++ "SIMD vector instructions require -mavx512f." check _ _ _ _ = return () vecWidth = typeWidth (vecVmmType vcat l w) ------------------------------------------------------------------------------ -- Helpers for translating vector packing and unpacking. doVecPackOp :: Maybe MachOp -- Cast from element to vector component -> CmmType -- Type of vector -> CmmExpr -- Initial vector -> [CmmExpr] -- Elements -> CmmFormal -- Destination for result -> FCode () doVecPackOp maybe_pre_write_cast ty z es res = do dst <- newTemp ty emitAssign (CmmLocal dst) z vecPack dst es 0 where vecPack :: CmmFormal -> [CmmExpr] -> Int -> FCode () vecPack src [] _ = emitAssign (CmmLocal res) (CmmReg (CmmLocal src)) vecPack src (e : es) i = do dst <- newTemp ty if isFloatType (vecElemType ty) then emitAssign (CmmLocal dst) (CmmMachOp (MO_VF_Insert len wid) [CmmReg (CmmLocal src), cast e, iLit]) else emitAssign (CmmLocal dst) (CmmMachOp (MO_V_Insert len wid) [CmmReg (CmmLocal src), cast e, iLit]) vecPack dst es (i + 1) where -- vector indices are always 32-bits iLit = CmmLit (CmmInt (toInteger i) W32) cast :: CmmExpr -> CmmExpr cast val = case maybe_pre_write_cast of Nothing -> val Just cast -> CmmMachOp cast [val] len :: Length len = vecLength ty wid :: Width wid = typeWidth (vecElemType ty) doVecUnpackOp :: Maybe MachOp -- Cast from vector component to element result -> CmmType -- Type of vector -> CmmExpr -- Vector -> [CmmFormal] -- Element results -> FCode () doVecUnpackOp maybe_post_read_cast ty e res = vecUnpack res 0 where vecUnpack :: [CmmFormal] -> Int -> FCode () vecUnpack [] _ = return () vecUnpack (r : rs) i = do if isFloatType (vecElemType ty) then emitAssign (CmmLocal r) (cast (CmmMachOp (MO_VF_Extract len wid) [e, iLit])) else emitAssign (CmmLocal r) (cast (CmmMachOp (MO_V_Extract len wid) [e, iLit])) vecUnpack rs (i + 1) where -- vector indices are always 32-bits iLit = CmmLit (CmmInt (toInteger i) W32) cast :: CmmExpr -> CmmExpr cast val = case maybe_post_read_cast of Nothing -> val Just cast -> CmmMachOp cast [val] len :: Length len = vecLength ty wid :: Width wid = typeWidth (vecElemType ty) doVecInsertOp :: Maybe MachOp -- Cast from element to vector component -> CmmType -- Vector type -> CmmExpr -- Source vector -> CmmExpr -- Element -> CmmExpr -- Index at which to insert element -> CmmFormal -- Destination for result -> FCode () doVecInsertOp maybe_pre_write_cast ty src e idx res = do dflags <- getDynFlags -- vector indices are always 32-bits let idx' :: CmmExpr idx' = CmmMachOp (MO_SS_Conv (wordWidth dflags) W32) [idx] if isFloatType (vecElemType ty) then emitAssign (CmmLocal res) (CmmMachOp (MO_VF_Insert len wid) [src, cast e, idx']) else emitAssign (CmmLocal res) (CmmMachOp (MO_V_Insert len wid) [src, cast e, idx']) where cast :: CmmExpr -> CmmExpr cast val = case maybe_pre_write_cast of Nothing -> val Just cast -> CmmMachOp cast [val] len :: Length len = vecLength ty wid :: Width wid = typeWidth (vecElemType ty) ------------------------------------------------------------------------------ -- Helpers for translating prefetching. -- | Translate byte array prefetch operations into proper primcalls. doPrefetchByteArrayOp :: Int -> [CmmExpr] -> FCode () doPrefetchByteArrayOp locality [addr,idx] = do dflags <- getDynFlags mkBasicPrefetch locality (arrWordsHdrSize dflags) addr idx doPrefetchByteArrayOp _ _ = panic "StgCmmPrim: doPrefetchByteArrayOp" -- | Translate mutable byte array prefetch operations into proper primcalls. doPrefetchMutableByteArrayOp :: Int -> [CmmExpr] -> FCode () doPrefetchMutableByteArrayOp locality [addr,idx] = do dflags <- getDynFlags mkBasicPrefetch locality (arrWordsHdrSize dflags) addr idx doPrefetchMutableByteArrayOp _ _ = panic "StgCmmPrim: doPrefetchByteArrayOp" -- | Translate address prefetch operations into proper primcalls. doPrefetchAddrOp ::Int -> [CmmExpr] -> FCode () doPrefetchAddrOp locality [addr,idx] = mkBasicPrefetch locality 0 addr idx doPrefetchAddrOp _ _ = panic "StgCmmPrim: doPrefetchAddrOp" -- | Translate value prefetch operations into proper primcalls. doPrefetchValueOp :: Int -> [CmmExpr] -> FCode () doPrefetchValueOp locality [addr] = do dflags <- getDynFlags mkBasicPrefetch locality 0 addr (CmmLit (CmmInt 0 (wordWidth dflags))) doPrefetchValueOp _ _ = panic "StgCmmPrim: doPrefetchValueOp" -- | helper to generate prefetch primcalls mkBasicPrefetch :: Int -- Locality level 0-3 -> ByteOff -- Initial offset in bytes -> CmmExpr -- Base address -> CmmExpr -- Index -> FCode () mkBasicPrefetch locality off base idx = do dflags <- getDynFlags emitPrimCall [] (MO_Prefetch_Data locality) [cmmIndexExpr dflags W8 (cmmOffsetB dflags base off) idx] return () -- ---------------------------------------------------------------------------- -- Allocating byte arrays -- | Takes a register to return the newly allocated array in and the -- size of the new array in bytes. Allocates a new -- 'MutableByteArray#'. doNewByteArrayOp :: CmmFormal -> ByteOff -> FCode () doNewByteArrayOp res_r n = do dflags <- getDynFlags let info_ptr = mkLblExpr mkArrWords_infoLabel rep = arrWordsRep dflags n tickyAllocPrim (mkIntExpr dflags (arrWordsHdrSize dflags)) (mkIntExpr dflags (nonHdrSize dflags rep)) (zeroExpr dflags) let hdr_size = fixedHdrSize dflags base <- allocHeapClosure rep info_ptr curCCS [ (mkIntExpr dflags n, hdr_size + oFFSET_StgArrWords_bytes dflags) ] emit $ mkAssign (CmmLocal res_r) base -- ---------------------------------------------------------------------------- -- Copying byte arrays -- | Takes a source 'ByteArray#', an offset in the source array, a -- destination 'MutableByteArray#', an offset into the destination -- array, and the number of bytes to copy. Copies the given number of -- bytes from the source array to the destination array. doCopyByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode () doCopyByteArrayOp = emitCopyByteArray copy where -- Copy data (we assume the arrays aren't overlapping since -- they're of different types) copy _src _dst dst_p src_p bytes = emitMemcpyCall dst_p src_p bytes 1 -- | Takes a source 'MutableByteArray#', an offset in the source -- array, a destination 'MutableByteArray#', an offset into the -- destination array, and the number of bytes to copy. Copies the -- given number of bytes from the source array to the destination -- array. doCopyMutableByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode () doCopyMutableByteArrayOp = emitCopyByteArray copy where -- The only time the memory might overlap is when the two arrays -- we were provided are the same array! -- TODO: Optimize branch for common case of no aliasing. copy src dst dst_p src_p bytes = do dflags <- getDynFlags [moveCall, cpyCall] <- forkAlts [ getCode $ emitMemmoveCall dst_p src_p bytes 1, getCode $ emitMemcpyCall dst_p src_p bytes 1 ] emit =<< mkCmmIfThenElse (cmmEqWord dflags src dst) moveCall cpyCall emitCopyByteArray :: (CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode ()) -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode () emitCopyByteArray copy src src_off dst dst_off n = do dflags <- getDynFlags dst_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags dst (arrWordsHdrSize dflags)) dst_off src_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags src (arrWordsHdrSize dflags)) src_off copy src dst dst_p src_p n -- | Takes a source 'ByteArray#', an offset in the source array, a -- destination 'Addr#', and the number of bytes to copy. Copies the given -- number of bytes from the source array to the destination memory region. doCopyByteArrayToAddrOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode () doCopyByteArrayToAddrOp src src_off dst_p bytes = do -- Use memcpy (we are allowed to assume the arrays aren't overlapping) dflags <- getDynFlags src_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags src (arrWordsHdrSize dflags)) src_off emitMemcpyCall dst_p src_p bytes 1 -- | Takes a source 'MutableByteArray#', an offset in the source array, a -- destination 'Addr#', and the number of bytes to copy. Copies the given -- number of bytes from the source array to the destination memory region. doCopyMutableByteArrayToAddrOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode () doCopyMutableByteArrayToAddrOp = doCopyByteArrayToAddrOp -- | Takes a source 'Addr#', a destination 'MutableByteArray#', an offset into -- the destination array, and the number of bytes to copy. Copies the given -- number of bytes from the source memory region to the destination array. doCopyAddrToByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode () doCopyAddrToByteArrayOp src_p dst dst_off bytes = do -- Use memcpy (we are allowed to assume the arrays aren't overlapping) dflags <- getDynFlags dst_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags dst (arrWordsHdrSize dflags)) dst_off emitMemcpyCall dst_p src_p bytes 1 -- ---------------------------------------------------------------------------- -- Setting byte arrays -- | Takes a 'MutableByteArray#', an offset into the array, a length, -- and a byte, and sets each of the selected bytes in the array to the -- character. doSetByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode () doSetByteArrayOp ba off len c = do dflags <- getDynFlags p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags ba (arrWordsHdrSize dflags)) off emitMemsetCall p c len 1 -- ---------------------------------------------------------------------------- -- Allocating arrays -- | Allocate a new array. doNewArrayOp :: CmmFormal -- ^ return register -> SMRep -- ^ representation of the array -> CLabel -- ^ info pointer -> [(CmmExpr, ByteOff)] -- ^ header payload -> WordOff -- ^ array size -> CmmExpr -- ^ initial element -> FCode () doNewArrayOp res_r rep info payload n init = do dflags <- getDynFlags let info_ptr = mkLblExpr info tickyAllocPrim (mkIntExpr dflags (hdrSize dflags rep)) (mkIntExpr dflags (nonHdrSize dflags rep)) (zeroExpr dflags) base <- allocHeapClosure rep info_ptr curCCS payload arr <- CmmLocal `fmap` newTemp (bWord dflags) emit $ mkAssign arr base -- Initialise all elements of the the array p <- assignTemp $ cmmOffsetB dflags (CmmReg arr) (hdrSize dflags rep) for <- newLabelC emitLabel for let loopBody = [ mkStore (CmmReg (CmmLocal p)) init , mkAssign (CmmLocal p) (cmmOffsetW dflags (CmmReg (CmmLocal p)) 1) , mkBranch for ] emit =<< mkCmmIfThen (cmmULtWord dflags (CmmReg (CmmLocal p)) (cmmOffsetW dflags (CmmReg arr) (hdrSizeW dflags rep + n))) (catAGraphs loopBody) emit $ mkAssign (CmmLocal res_r) (CmmReg arr) -- ---------------------------------------------------------------------------- -- Copying pointer arrays -- EZY: This code has an unusually high amount of assignTemp calls, seen -- nowhere else in the code generator. This is mostly because these -- "primitive" ops result in a surprisingly large amount of code. It -- will likely be worthwhile to optimize what is emitted here, so that -- our optimization passes don't waste time repeatedly optimizing the -- same bits of code. -- More closely imitates 'assignTemp' from the old code generator, which -- returns a CmmExpr rather than a LocalReg. assignTempE :: CmmExpr -> FCode CmmExpr assignTempE e = do t <- assignTemp e return (CmmReg (CmmLocal t)) -- | Takes a source 'Array#', an offset in the source array, a -- destination 'MutableArray#', an offset into the destination array, -- and the number of elements to copy. Copies the given number of -- elements from the source array to the destination array. doCopyArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff -> FCode () doCopyArrayOp = emitCopyArray copy where -- Copy data (we assume the arrays aren't overlapping since -- they're of different types) copy _src _dst dst_p src_p bytes = do dflags <- getDynFlags emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes) (wORD_SIZE dflags) -- | Takes a source 'MutableArray#', an offset in the source array, a -- destination 'MutableArray#', an offset into the destination array, -- and the number of elements to copy. Copies the given number of -- elements from the source array to the destination array. doCopyMutableArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff -> FCode () doCopyMutableArrayOp = emitCopyArray copy where -- The only time the memory might overlap is when the two arrays -- we were provided are the same array! -- TODO: Optimize branch for common case of no aliasing. copy src dst dst_p src_p bytes = do dflags <- getDynFlags [moveCall, cpyCall] <- forkAlts [ getCode $ emitMemmoveCall dst_p src_p (mkIntExpr dflags bytes) (wORD_SIZE dflags), getCode $ emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes) (wORD_SIZE dflags) ] emit =<< mkCmmIfThenElse (cmmEqWord dflags src dst) moveCall cpyCall emitCopyArray :: (CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> ByteOff -> FCode ()) -- ^ copy function -> CmmExpr -- ^ source array -> CmmExpr -- ^ offset in source array -> CmmExpr -- ^ destination array -> CmmExpr -- ^ offset in destination array -> WordOff -- ^ number of elements to copy -> FCode () emitCopyArray copy src0 src_off dst0 dst_off0 n = do dflags <- getDynFlags when (n /= 0) $ do -- Passed as arguments (be careful) src <- assignTempE src0 dst <- assignTempE dst0 dst_off <- assignTempE dst_off0 -- Set the dirty bit in the header. emit (setInfo dst (CmmLit (CmmLabel mkMAP_DIRTY_infoLabel))) dst_elems_p <- assignTempE $ cmmOffsetB dflags dst (arrPtrsHdrSize dflags) dst_p <- assignTempE $ cmmOffsetExprW dflags dst_elems_p dst_off src_p <- assignTempE $ cmmOffsetExprW dflags (cmmOffsetB dflags src (arrPtrsHdrSize dflags)) src_off let bytes = wordsToBytes dflags n copy src dst dst_p src_p bytes -- The base address of the destination card table dst_cards_p <- assignTempE $ cmmOffsetExprW dflags dst_elems_p (loadArrPtrsSize dflags dst) emitSetCards dst_off dst_cards_p n doCopySmallArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff -> FCode () doCopySmallArrayOp = emitCopySmallArray copy where -- Copy data (we assume the arrays aren't overlapping since -- they're of different types) copy _src _dst dst_p src_p bytes = do dflags <- getDynFlags emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes) (wORD_SIZE dflags) doCopySmallMutableArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff -> FCode () doCopySmallMutableArrayOp = emitCopySmallArray copy where -- The only time the memory might overlap is when the two arrays -- we were provided are the same array! -- TODO: Optimize branch for common case of no aliasing. copy src dst dst_p src_p bytes = do dflags <- getDynFlags [moveCall, cpyCall] <- forkAlts [ getCode $ emitMemmoveCall dst_p src_p (mkIntExpr dflags bytes) (wORD_SIZE dflags) , getCode $ emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes) (wORD_SIZE dflags) ] emit =<< mkCmmIfThenElse (cmmEqWord dflags src dst) moveCall cpyCall emitCopySmallArray :: (CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> ByteOff -> FCode ()) -- ^ copy function -> CmmExpr -- ^ source array -> CmmExpr -- ^ offset in source array -> CmmExpr -- ^ destination array -> CmmExpr -- ^ offset in destination array -> WordOff -- ^ number of elements to copy -> FCode () emitCopySmallArray copy src0 src_off dst0 dst_off n = do dflags <- getDynFlags -- Passed as arguments (be careful) src <- assignTempE src0 dst <- assignTempE dst0 -- Set the dirty bit in the header. emit (setInfo dst (CmmLit (CmmLabel mkSMAP_DIRTY_infoLabel))) dst_p <- assignTempE $ cmmOffsetExprW dflags (cmmOffsetB dflags dst (smallArrPtrsHdrSize dflags)) dst_off src_p <- assignTempE $ cmmOffsetExprW dflags (cmmOffsetB dflags src (smallArrPtrsHdrSize dflags)) src_off let bytes = wordsToBytes dflags n copy src dst dst_p src_p bytes -- | Takes an info table label, a register to return the newly -- allocated array in, a source array, an offset in the source array, -- and the number of elements to copy. Allocates a new array and -- initializes it from the source array. emitCloneArray :: CLabel -> CmmFormal -> CmmExpr -> CmmExpr -> WordOff -> FCode () emitCloneArray info_p res_r src src_off n = do dflags <- getDynFlags let info_ptr = mkLblExpr info_p rep = arrPtrsRep dflags n tickyAllocPrim (mkIntExpr dflags (arrPtrsHdrSize dflags)) (mkIntExpr dflags (nonHdrSize dflags rep)) (zeroExpr dflags) let hdr_size = fixedHdrSize dflags base <- allocHeapClosure rep info_ptr curCCS [ (mkIntExpr dflags n, hdr_size + oFFSET_StgMutArrPtrs_ptrs dflags) , (mkIntExpr dflags (nonHdrSizeW rep), hdr_size + oFFSET_StgMutArrPtrs_size dflags) ] arr <- CmmLocal `fmap` newTemp (bWord dflags) emit $ mkAssign arr base dst_p <- assignTempE $ cmmOffsetB dflags (CmmReg arr) (arrPtrsHdrSize dflags) src_p <- assignTempE $ cmmOffsetExprW dflags src (cmmAddWord dflags (mkIntExpr dflags (arrPtrsHdrSizeW dflags)) src_off) emitMemcpyCall dst_p src_p (mkIntExpr dflags (wordsToBytes dflags n)) (wORD_SIZE dflags) emit $ mkAssign (CmmLocal res_r) (CmmReg arr) -- | Takes an info table label, a register to return the newly -- allocated array in, a source array, an offset in the source array, -- and the number of elements to copy. Allocates a new array and -- initializes it from the source array. emitCloneSmallArray :: CLabel -> CmmFormal -> CmmExpr -> CmmExpr -> WordOff -> FCode () emitCloneSmallArray info_p res_r src src_off n = do dflags <- getDynFlags let info_ptr = mkLblExpr info_p rep = smallArrPtrsRep n tickyAllocPrim (mkIntExpr dflags (smallArrPtrsHdrSize dflags)) (mkIntExpr dflags (nonHdrSize dflags rep)) (zeroExpr dflags) let hdr_size = fixedHdrSize dflags base <- allocHeapClosure rep info_ptr curCCS [ (mkIntExpr dflags n, hdr_size + oFFSET_StgSmallMutArrPtrs_ptrs dflags) ] arr <- CmmLocal `fmap` newTemp (bWord dflags) emit $ mkAssign arr base dst_p <- assignTempE $ cmmOffsetB dflags (CmmReg arr) (smallArrPtrsHdrSize dflags) src_p <- assignTempE $ cmmOffsetExprW dflags src (cmmAddWord dflags (mkIntExpr dflags (smallArrPtrsHdrSizeW dflags)) src_off) emitMemcpyCall dst_p src_p (mkIntExpr dflags (wordsToBytes dflags n)) (wORD_SIZE dflags) emit $ mkAssign (CmmLocal res_r) (CmmReg arr) -- | Takes and offset in the destination array, the base address of -- the card table, and the number of elements affected (*not* the -- number of cards). The number of elements may not be zero. -- Marks the relevant cards as dirty. emitSetCards :: CmmExpr -> CmmExpr -> WordOff -> FCode () emitSetCards dst_start dst_cards_start n = do dflags <- getDynFlags start_card <- assignTempE $ cardCmm dflags dst_start let end_card = cardCmm dflags (cmmSubWord dflags (cmmAddWord dflags dst_start (mkIntExpr dflags n)) (mkIntExpr dflags 1)) emitMemsetCall (cmmAddWord dflags dst_cards_start start_card) (mkIntExpr dflags 1) (cmmAddWord dflags (cmmSubWord dflags end_card start_card) (mkIntExpr dflags 1)) 1 -- no alignment (1 byte) -- Convert an element index to a card index cardCmm :: DynFlags -> CmmExpr -> CmmExpr cardCmm dflags i = cmmUShrWord dflags i (mkIntExpr dflags (mUT_ARR_PTRS_CARD_BITS dflags)) ------------------------------------------------------------------------------ -- SmallArray PrimOp implementations doReadSmallPtrArrayOp :: LocalReg -> CmmExpr -> CmmExpr -> FCode () doReadSmallPtrArrayOp res addr idx = do dflags <- getDynFlags mkBasicIndexedRead (smallArrPtrsHdrSize dflags) Nothing (gcWord dflags) res addr (gcWord dflags) idx doWriteSmallPtrArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> FCode () doWriteSmallPtrArrayOp addr idx val = do dflags <- getDynFlags let ty = cmmExprType dflags val mkBasicIndexedWrite (smallArrPtrsHdrSize dflags) Nothing addr ty idx val emit (setInfo addr (CmmLit (CmmLabel mkSMAP_DIRTY_infoLabel))) ------------------------------------------------------------------------------ -- Atomic read-modify-write -- | Emit an atomic modification to a byte array element. The result -- reg contains that previous value of the element. Implies a full -- memory barrier. doAtomicRMW :: LocalReg -- ^ Result reg -> AtomicMachOp -- ^ Atomic op (e.g. add) -> CmmExpr -- ^ MutableByteArray# -> CmmExpr -- ^ Index -> CmmType -- ^ Type of element by which we are indexing -> CmmExpr -- ^ Op argument (e.g. amount to add) -> FCode () doAtomicRMW res amop mba idx idx_ty n = do dflags <- getDynFlags let width = typeWidth idx_ty addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags) width mba idx emitPrimCall [ res ] (MO_AtomicRMW width amop) [ addr, n ] -- | Emit an atomic read to a byte array that acts as a memory barrier. doAtomicReadByteArray :: LocalReg -- ^ Result reg -> CmmExpr -- ^ MutableByteArray# -> CmmExpr -- ^ Index -> CmmType -- ^ Type of element by which we are indexing -> FCode () doAtomicReadByteArray res mba idx idx_ty = do dflags <- getDynFlags let width = typeWidth idx_ty addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags) width mba idx emitPrimCall [ res ] (MO_AtomicRead width) [ addr ] -- | Emit an atomic write to a byte array that acts as a memory barrier. doAtomicWriteByteArray :: CmmExpr -- ^ MutableByteArray# -> CmmExpr -- ^ Index -> CmmType -- ^ Type of element by which we are indexing -> CmmExpr -- ^ Value to write -> FCode () doAtomicWriteByteArray mba idx idx_ty val = do dflags <- getDynFlags let width = typeWidth idx_ty addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags) width mba idx emitPrimCall [ {- no results -} ] (MO_AtomicWrite width) [ addr, val ] doCasByteArray :: LocalReg -- ^ Result reg -> CmmExpr -- ^ MutableByteArray# -> CmmExpr -- ^ Index -> CmmType -- ^ Type of element by which we are indexing -> CmmExpr -- ^ Old value -> CmmExpr -- ^ New value -> FCode () doCasByteArray res mba idx idx_ty old new = do dflags <- getDynFlags let width = (typeWidth idx_ty) addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags) width mba idx emitPrimCall [ res ] (MO_Cmpxchg width) [ addr, old, new ] ------------------------------------------------------------------------------ -- Helpers for emitting function calls -- | Emit a call to @memcpy@. emitMemcpyCall :: CmmExpr -> CmmExpr -> CmmExpr -> Int -> FCode () emitMemcpyCall dst src n align = do emitPrimCall [ {-no results-} ] (MO_Memcpy align) [ dst, src, n ] -- | Emit a call to @memmove@. emitMemmoveCall :: CmmExpr -> CmmExpr -> CmmExpr -> Int -> FCode () emitMemmoveCall dst src n align = do emitPrimCall [ {- no results -} ] (MO_Memmove align) [ dst, src, n ] -- | Emit a call to @memset@. The second argument must fit inside an -- unsigned char. emitMemsetCall :: CmmExpr -> CmmExpr -> CmmExpr -> Int -> FCode () emitMemsetCall dst c n align = do emitPrimCall [ {- no results -} ] (MO_Memset align) [ dst, c, n ] emitBSwapCall :: LocalReg -> CmmExpr -> Width -> FCode () emitBSwapCall res x width = do emitPrimCall [ res ] (MO_BSwap width) [ x ] emitPopCntCall :: LocalReg -> CmmExpr -> Width -> FCode () emitPopCntCall res x width = do emitPrimCall [ res ] (MO_PopCnt width) [ x ] emitClzCall :: LocalReg -> CmmExpr -> Width -> FCode () emitClzCall res x width = do emitPrimCall [ res ] (MO_Clz width) [ x ] emitCtzCall :: LocalReg -> CmmExpr -> Width -> FCode () emitCtzCall res x width = do emitPrimCall [ res ] (MO_Ctz width) [ x ]
acowley/ghc
compiler/codeGen/StgCmmPrim.hs
bsd-3-clause
96,640
3
21
25,780
24,918
12,461
12,457
-1
-1
{-# LANGUAGE BangPatterns #-} -- | This module defines a type for mutable, string-valued labels. -- Labels are variable values and can be used to track e.g. the -- command line arguments or other free-form values. All operations on -- labels are thread-safe. module System.Remote.Label ( Label , set , modify ) where import Data.IORef (atomicModifyIORef) import qualified Data.Text as T import System.Remote.Label.Internal -- | Set the label to the given value. set :: Label -> T.Text -> IO () set (C ref) !i = atomicModifyIORef ref $ \ _ -> (i, ()) -- | Set the label to the result of applying the given function to the -- value. modify :: (T.Text -> T.Text) -> Label -> IO () modify f (C ref) = do !_ <- atomicModifyIORef ref $ \ i -> let i' = f i in (i', i') return ()
ekmett/ekg
System/Remote/Label.hs
bsd-3-clause
806
0
14
178
201
111
90
15
1
{-# LANGUAGE Unsafe #-} {-# LANGUAGE NoImplicitPrelude , DeriveDataTypeable , MagicHash , UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Stable -- Copyright : (c) The University of Glasgow, 1992-2004 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- Stable pointers. -- ----------------------------------------------------------------------------- module GHC.Stable ( StablePtr(..), newStablePtr, deRefStablePtr, freeStablePtr, castStablePtrToPtr, castPtrToStablePtr ) where import GHC.Ptr import GHC.Base import Data.Typeable.Internal ----------------------------------------------------------------------------- -- Stable Pointers {- | A /stable pointer/ is a reference to a Haskell expression that is guaranteed not to be affected by garbage collection, i.e., it will neither be deallocated nor will the value of the stable pointer itself change during garbage collection (ordinary references may be relocated during garbage collection). Consequently, stable pointers can be passed to foreign code, which can treat it as an opaque reference to a Haskell value. A value of type @StablePtr a@ is a stable pointer to a Haskell expression of type @a@. -} data {-# CTYPE "HsStablePtr" #-} StablePtr a = StablePtr (StablePtr# a) deriving( Typeable ) -- | -- Create a stable pointer referring to the given Haskell value. -- newStablePtr :: a -> IO (StablePtr a) newStablePtr a = IO $ \ s -> case makeStablePtr# a s of (# s', sp #) -> (# s', StablePtr sp #) -- | -- Obtain the Haskell value referenced by a stable pointer, i.e., the -- same value that was passed to the corresponding call to -- 'makeStablePtr'. If the argument to 'deRefStablePtr' has -- already been freed using 'freeStablePtr', the behaviour of -- 'deRefStablePtr' is undefined. -- deRefStablePtr :: StablePtr a -> IO a deRefStablePtr (StablePtr sp) = IO $ \s -> deRefStablePtr# sp s -- | -- Dissolve the association between the stable pointer and the Haskell -- value. Afterwards, if the stable pointer is passed to -- 'deRefStablePtr' or 'freeStablePtr', the behaviour is -- undefined. However, the stable pointer may still be passed to -- 'castStablePtrToPtr', but the @'Foreign.Ptr.Ptr' ()@ value returned -- by 'castStablePtrToPtr', in this case, is undefined (in particular, -- it may be 'Foreign.Ptr.nullPtr'). Nevertheless, the call -- to 'castStablePtrToPtr' is guaranteed not to diverge. -- foreign import java unsafe "@static eta.runtime.stg.StablePtrTable.free" freeStablePtr :: StablePtr a -> IO () -- | -- Coerce a stable pointer to an address. No guarantees are made about -- the resulting value, except that the original stable pointer can be -- recovered by 'castPtrToStablePtr'. In particular, the address may not -- refer to an accessible memory location and any attempt to pass it to -- the member functions of the class 'Foreign.Storable.Storable' leads to -- undefined behaviour. -- castStablePtrToPtr :: StablePtr a -> Ptr () castStablePtrToPtr (StablePtr s) = Ptr (stablePtr2Addr# s) -- | -- The inverse of 'castStablePtrToPtr', i.e., we have the identity -- -- > sp == castPtrToStablePtr (castStablePtrToPtr sp) -- -- for any stable pointer @sp@ on which 'freeStablePtr' has -- not been executed yet. Moreover, 'castPtrToStablePtr' may -- only be applied to pointers that have been produced by -- 'castStablePtrToPtr'. -- castPtrToStablePtr :: Ptr () -> StablePtr a castPtrToStablePtr (Ptr a) = StablePtr (addr2StablePtr# a) instance Eq (StablePtr a) where (StablePtr sp1) == (StablePtr sp2) = case eqStablePtr# sp1 sp2 of 0# -> False _ -> True
alexander-at-github/eta
libraries/base/GHC/Stable.hs
bsd-3-clause
3,905
5
11
719
395
233
162
-1
-1
{-# LANGUAGE PatternGuards, TemplateHaskell, QuasiQuotes #-} -- | -- Module : Language.C.Inline.ObjC.Marshal -- Copyright : [2013] Manuel M T Chakravarty -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Objective-C-specific marshalling functions. -- -- FIXME: Some of the code can go into a module for general marshalling, as only some of it is ObjC-specific. module Language.C.Inline.ObjC.Marshal ( -- * Determine corresponding foreign types of Haskell types haskellTypeToCType, -- * Marshaller types HaskellMarshaller, CMarshaller, -- * Compute bridging types and marshallers generateHaskellToCMarshaller, generateCToHaskellMarshaller ) where -- common libraries import Data.Map as Map import Data.Word import Foreign.C as C import Foreign.Marshal as C import Foreign.Ptr as C import Foreign.ForeignPtr as C import Foreign.StablePtr as C import Language.Haskell.TH as TH -- quasi-quotation libraries import Language.C.Quote as QC import Language.C.Quote.ObjC as QC -- friends import Language.C.Inline.Error import Language.C.Inline.State import Language.C.Inline.TH -- Determine foreign types -- ----------------------- -- |Determine the C type that we map a given Haskell type to. -- haskellTypeToCType :: QC.Extensions -> TH.Type -> Q (Maybe QC.Type) haskellTypeToCType lang (ForallT _tvs _ctxt ty) -- ignore quantifiers and contexts = haskellTypeToCType lang ty haskellTypeToCType lang ty = do { maybe_marshaller <- lookupMarshaller ty ; case maybe_marshaller of Just (_, _, cTy, _, _) -> return $ Just cTy -- use a custom marshaller if one is available for this type Nothing -> haskellTypeToCType' lang ty -- otherwise, continue below... } where haskellTypeToCType' lang' (ListT `AppT` (ConT ch)) -- marshal '[Char]' as 'String' | ch == ''Char = haskellTypeNameToCType lang' ''String haskellTypeToCType' lang' ty'@(ConT maybeC `AppT` argTy) -- encode a 'Maybe' around a pointer type in the pointer | maybeC == ''Maybe = do { cargTy <- haskellTypeToCType lang argTy ; if fmap isCPtrType cargTy == Just True then return cargTy else unknownType lang' ty' } haskellTypeToCType' lang' (ConT tc) -- nullary type constructors are delegated = haskellTypeNameToCType lang' tc haskellTypeToCType' lang' ty'@(VarT _) -- can't marshal an unknown type = unknownType lang' ty' haskellTypeToCType' lang' ty'@(UnboxedTupleT _) -- there is nothing like unboxed tuples in C = unknownType lang' ty' haskellTypeToCType' _lang _ty -- everything else is marshalled as a stable pointer = return $ Just [cty| typename HsStablePtr |] unknownType lang' ty' = do { reportErrorWithLang lang' $ "don't know a foreign type suitable for Haskell type '" ++ TH.pprint ty' ++ "'" ; return Nothing } -- |Determine the C type that we map a given Haskell type constructor to — i.e., we map all Haskell types -- whose outermost constructor is the given type constructor to the returned C type. -- -- All types representing boxed values that are not explicitly mapped to a specific C type, are mapped to -- stable pointers. -- haskellTypeNameToCType :: QC.Extensions -> TH.Name -> Q (Maybe QC.Type) haskellTypeNameToCType ext tyname = case Map.lookup tyname (haskellToCTypeMap ext) of Just c -> return $ Just c Nothing -> do { info <- reify tyname ; case info of PrimTyConI _ _ True -> unknownUnboxedType _ -> return $ Just [cty| typename HsStablePtr |] } where unknownUnboxedType = do { reportErrorWithLang ext $ "don't know a foreign type suitable for the unboxed Haskell type '" ++ show tyname ++ "'" ; return Nothing } haskellToCTypeMap :: QC.Extensions -> Map TH.Name QC.Type haskellToCTypeMap ObjC = Map.fromList [ (''CChar, [cty| char |]) , (''CSChar, [cty| signed char |]) , (''CUChar, [cty| unsigned char |]) , (''CShort, [cty| short |]) , (''CUShort, [cty| unsigned short |]) , (''Int, [cty| typename NSInteger |]) , (''CInt, [cty| int |]) , (''Word, [cty| typename NSUInteger |]) , (''CUInt, [cty| unsigned int |]) , (''CLong, [cty| long |]) , (''CULong, [cty| unsigned long |]) , (''CLLong, [cty| long long |]) , (''CULLong, [cty| unsigned long long |]) -- , (''Float, [cty| float |]) , (''CFloat, [cty| float |]) , (''Double, [cty| double |]) , (''CDouble, [cty| double |]) -- , (''Bool, [cty| typename BOOL |]) , (''String, [cty| typename NSString * |]) , (''(), [cty| void |]) ] haskellToCTypeMap _lang = Map.empty -- Check whether the given C type is an overt pointer. -- isCPtrType :: QC.Type -> Bool isCPtrType (Type _ (Ptr {}) _) = True isCPtrType (Type _ (BlockPtr {}) _) = True isCPtrType (Type _ (Array {}) _) = True isCPtrType ty | ty == [cty| typename HsStablePtr |] = True | otherwise = False -- Determine marshallers and their bridging types -- ---------------------------------------------- -- |Constructs Haskell code to marshal a value (used to marshal arguments and results). -- -- * The first argument is the code referring to the value to be marshalled. -- * The second argument is the continuation that gets the marshalled value as an argument. -- type HaskellMarshaller = TH.ExpQ -> TH.ExpQ -> TH.ExpQ -- |Constructs C code to marshal an argument (used to marshal arguments and results). -- -- * The argument is the identifier of the value to be marshalled. -- * The result of the generated expression is the marshalled value. -- type CMarshaller = TH.Name -> QC.Exp -- |Generate the type-specific marshalling code for Haskell to C land marshalling for a Haskell-C type pair. -- -- The result has the following components: -- -- * Haskell type after Haskell-side marshalling. -- * C type before C-side marshalling. -- * Generator for the Haskell-side marshalling code. -- * Generator for the C-side marshalling code. -- generateHaskellToCMarshaller :: TH.Type -> QC.Type -> Q (TH.TypeQ, QC.Type, HaskellMarshaller, CMarshaller) generateHaskellToCMarshaller hsTy cTy@(Type (DeclSpec _ _ (Tnamed (Id name _) _ _) _) (Ptr _ (DeclRoot _) _) _) | Just name == maybeHeadName -- wrapped ForeignPtr mapped to an Objective-C class = return ( ptrOfForeignPtrWrapper hsTy , cTy , \val cont -> [| C.withForeignPtr ($(unwrapForeignPtrWrapper hsTy) $val) $cont |] , \argName -> [cexp| $id:(show argName) |] ) | otherwise = do { maybe_marshaller <- lookupMarshaller hsTy ; case maybe_marshaller of Just (_, classTy, cTy', haskellToC, _cToHaskell) | cTy' == cTy -- custom marshaller mapping to an Objective-C class -> return ( ptrOfForeignPtrWrapper classTy , cTy , \val cont -> [| do { nsClass <- $(varE haskellToC) $val ; C.withForeignPtr ($(unwrapForeignPtrWrapper classTy) nsClass) $cont } |] , \argName -> [cexp| $id:(show argName) |] ) Nothing -- other => continue below -> generateHaskellToCMarshaller' hsTy cTy } where maybeHeadName = fmap nameBase $ headTyConName hsTy generateHaskellToCMarshaller hsTy cTy = generateHaskellToCMarshaller' hsTy cTy generateHaskellToCMarshaller' :: TH.Type -> QC.Type -> Q (TH.TypeQ, QC.Type, HaskellMarshaller, CMarshaller) generateHaskellToCMarshaller' hsTy@(ConT mbe `AppT` argTy) cTy | mbe == ''Maybe && isCPtrType cTy = do { (argTy', cTy', hsMarsh, cMarsh) <- generateHaskellToCMarshaller argTy cTy ; ty <- argTy' ; resolve ty argTy' cTy' hsMarsh cMarsh } where resolve ty argTy' cTy' hsMarsh cMarsh = case ty of ConT ptr `AppT` _ | ptr == ''C.Ptr -> return ( argTy' , cTy' , \val cont -> [| case $val of Nothing -> $cont C.nullPtr Just val' -> $(hsMarsh [|val'|] cont) |] , cMarsh ) | ptr == ''C.StablePtr -> return ( argTy' , cTy' , \val cont -> [| case $val of Nothing -> $cont (C.castPtrToStablePtr C.nullPtr) Just val' -> $(hsMarsh [|val'|] cont) |] -- NB: the above cast works for GHC, but is in the grey area -- of the FFI spec , cMarsh ) ConT con -> do { info <- reify con ; case info of TyConI (TySynD _name [] tysyn) -> resolve tysyn argTy' cTy' hsMarsh cMarsh -- chase type synonyms (only nullary ones at the moment) _ -> missingErr } _ -> missingErr missingErr = reportErrorAndFail ObjC $ "missing 'Maybe' marshalling for '" ++ prettyQC cTy ++ "' to '" ++ TH.pprint hsTy ++ "'" generateHaskellToCMarshaller' hsTy cTy | Just hsMarshalTy <- Map.lookup cTy cIntegralMap -- checking whether it is an integral type = return ( hsMarshalTy , cTy , \val cont -> [| $cont (fromIntegral $val) |] , \argName -> [cexp| $id:(show argName) |] ) | Just hsMarshalTy <- Map.lookup cTy cFloatingMap -- checking whether it is a floating type = return ( hsMarshalTy , cTy , \val cont -> [| $cont (realToFrac $val) |] , \argName -> [cexp| $id:(show argName) |] ) | cTy == [cty| typename BOOL |] = return ( [t| C.CSChar |] , cTy , \val cont -> [| $cont (C.fromBool $val) |] , \argName -> [cexp| ($id:(show argName)) |] ) | cTy == [cty| typename NSString * |] = return ( [t| C.CString |] , [cty| char * |] , \val cont -> [| C.withCString $val $cont |] , \argName -> [cexp| ($id:(show argName)) ? [NSString stringWithUTF8String: $id:(show argName)] : nil |] ) | cTy == [cty| typename HsStablePtr |] = return ( [t| C.StablePtr $(return hsTy) |] , cTy , \val cont -> [| do { C.newStablePtr $val >>= $cont } |] , \argName -> [cexp| $id:(show argName) |] ) | otherwise = reportErrorAndFail ObjC $ "cannot marshal '" ++ TH.pprint hsTy ++ "' to '" ++ prettyQC cTy ++ "'" -- |Generate the type-specific marshalling code for Haskell to C land marshalling for a C-Haskell type pair. -- -- The result has the following components: -- -- * Haskell type after Haskell-side marshalling. -- * C type before C-side marshalling. -- * Generator for the Haskell-side marshalling code. -- * Generator for the C-side marshalling code. -- generateCToHaskellMarshaller :: TH.Type -> QC.Type -> Q (TH.TypeQ, QC.Type, HaskellMarshaller, CMarshaller) generateCToHaskellMarshaller hsTy cTy@(Type (DeclSpec _ _ (Tnamed (Id name _) _ _) _) (Ptr _ (DeclRoot _) _) _) | Just name == maybeHeadName -- ForeignPtr mapped to an Objective-C class = return ( ptrOfForeignPtrWrapper hsTy , cTy , \val cont -> do { let datacon = foreignWrapperDatacon hsTy ; [| do { fptr <- newForeignPtr_ $val; $cont ($datacon fptr) } |] } , \argName -> [cexp| $id:(show argName) |] ) | otherwise = do { maybe_marshaller <- lookupMarshaller hsTy ; case maybe_marshaller of Just (_, classTy, cTy', _haskellToC, cToHaskell) | cTy' == cTy -- custom marshaller mapping to an Objective-C class -> return ( ptrOfForeignPtrWrapper classTy , cTy , \val cont -> do { let datacon = foreignWrapperDatacon classTy ; [| do { fptr <- newForeignPtr_ $val ; hsVal <- $(varE cToHaskell) ($datacon fptr) ; $cont hsVal } |] } , \argName -> [cexp| $id:(show argName) |] ) Nothing -- other => continue below -> generateCToHaskellMarshaller' hsTy cTy } where maybeHeadName = fmap nameBase $ headTyConName hsTy generateCToHaskellMarshaller hsTy cTy = generateCToHaskellMarshaller' hsTy cTy generateCToHaskellMarshaller' :: TH.Type -> QC.Type -> Q (TH.TypeQ, QC.Type, HaskellMarshaller, CMarshaller) generateCToHaskellMarshaller' hsTy@(ConT mbe `AppT` argTy) cTy | mbe == ''Maybe && isCPtrType cTy = do { (argTy', cTy', hsMarsh, cMarsh) <- generateCToHaskellMarshaller argTy cTy ; ty <- argTy' ; resolve ty argTy' cTy' hsMarsh cMarsh } where resolve ty argTy' cTy' hsMarsh cMarsh = case ty of ConT ptr `AppT` _ | ptr == ''C.Ptr -> return ( argTy' , cTy' , \val cont -> [| if $val == C.nullPtr then $cont Nothing else $(hsMarsh val [| $cont . Just |]) |] , cMarsh ) | ptr == ''C.StablePtr -> return ( argTy' , cTy' , \val cont -> [| if (C.castStablePtrToPtr $val) == C.nullPtr then $cont Nothing else $(hsMarsh val [| $cont . Just |]) |] -- NB: the above cast works for GHC, but is in the grey area -- of the FFI spec , cMarsh ) ConT con -> do { info <- reify con ; case info of TyConI (TySynD _name [] tysyn) -> resolve tysyn argTy' cTy' hsMarsh cMarsh -- chase type synonyms (only nullary ones at the moment) _ -> missingErr } _ -> missingErr missingErr = reportErrorAndFail ObjC $ "missing 'Maybe' marshalling for '" ++ prettyQC cTy ++ "' to '" ++ TH.pprint hsTy ++ "'" generateCToHaskellMarshaller' hsTy cTy | Just hsMarshalTy <- Map.lookup cTy cIntegralMap -- checking whether it is an integral type = return ( hsMarshalTy , cTy , \val cont -> [| $cont (fromIntegral $val) |] , \argName -> [cexp| $id:(show argName) |] ) | Just hsMarshalTy <- Map.lookup cTy cFloatingMap -- checking whether it is a floating type = return ( hsMarshalTy , cTy , \val cont -> [| $cont (realToFrac $val) |] , \argName -> [cexp| $id:(show argName) |] ) | cTy == [cty| typename BOOL |] = return ( [t| C.CSChar |] , cTy , \val cont -> [| $cont (C.toBool $val) |] , \argName -> [cexp| $id:(show argName) |] ) | cTy == [cty| typename NSString * |] = return ( [t| C.CString |] , [cty| char * |] , \val cont -> [| do { str <- C.peekCString $val; C.free $val; $cont str } |] , \argName -> let arg = show argName in [cexp| ( $id:arg ) ? ({ typename NSUInteger maxLen = [$id:arg maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1; char *buffer = malloc (maxLen); if (![$id:arg getCString:buffer maxLength:maxLen encoding:NSUTF8StringEncoding]) *buffer = '\0'; buffer; }) : nil |] ) | cTy == [cty| typename HsStablePtr |] = return ( [t| C.StablePtr $(return hsTy) |] , cTy , \val cont -> [| do { C.deRefStablePtr $val >>= $cont } |] , \argName -> [cexp| $id:(show argName) |] ) | cTy == [cty| void |] = return ( [t| () |] , [cty| void |] , \val cont -> [| $cont $val |] , \argName -> [cexp| $id:(show argName) |] ) | otherwise = reportErrorAndFail ObjC $ "cannot marshall '" ++ prettyQC cTy ++ "' to '" ++ TH.pprint hsTy ++ "'" cIntegralMap :: Map QC.Type TypeQ cIntegralMap = Map.fromList [ ([cty| char |], [t| C.CChar |]) , ([cty| signed char |], [t| C.CChar |]) , ([cty| unsigned char |], [t| C.CUChar |]) , ([cty| short |], [t| C.CShort |]) , ([cty| unsigned short |], [t| C.CUShort |]) , ([cty| int |], [t| C.CInt |]) , ([cty| unsigned int |], [t| C.CUInt |]) , ([cty| long |], [t| C.CLong |]) , ([cty| unsigned long |], [t| C.CULong |]) , ([cty| long long |], [t| C.CLLong |]) , ([cty| unsigned long long |], [t| C.CULLong |]) , ([cty| typename NSInteger |], [t| Int |]) , ([cty| typename NSUInteger |], [t| Word |]) ] cFloatingMap :: Map QC.Type TypeQ cFloatingMap = Map.fromList [ ([cty| float |] , [t| C.CFloat |]) , ([cty| double |], [t| C.CDouble |]) ]
beni55/language-c-inline
Language/C/Inline/ObjC/Marshal.hs
bsd-3-clause
19,242
14
20
7,391
3,663
2,174
1,489
289
8
-- | We create a file <root>/test/ghcconfig containing configuration of test -- | compiler. We need to search this file for required keys and setting -- | required for testsuite e.g. WORDSIZE, HOSTOS etc. module Oracles.TestSettings (TestSetting (..), testSetting, testRTSSettings) where import Base import Hadrian.Oracles.TextFile testConfigFile :: Action FilePath testConfigFile = buildRoot <&> (-/- "test/ghcconfig") -- | Test settings that are obtained from ghcconfig file. data TestSetting = TestHostOS | TestWORDSIZE | TestTARGETPLATFORM | TestTargetOS_CPP | TestTargetARCH_CPP | TestGhcStage | TestGhcDebugged | TestGhcWithNativeCodeGen | TestGhcWithInterpreter | TestGhcUnregisterised | TestGhcWithSMP | TestGhcDynamicByDefault | TestGhcDynamic | TestGhcProfiled | TestAR | TestCLANG | TestLLC | TestTEST_CC | TestGhcPackageDbFlag | TestMinGhcVersion711 | TestMinGhcVersion801 deriving (Show) -- | Lookup a test setting in @ghcconfig@ file. -- | To obtain RTS ways supported in @ghcconfig@ file, use 'testRTSSettings'. testSetting :: TestSetting -> Action String testSetting key = do file <- testConfigFile lookupValueOrError file $ case key of TestHostOS -> "HostOS" TestWORDSIZE -> "WORDSIZE" TestTARGETPLATFORM -> "TARGETPLATFORM" TestTargetOS_CPP -> "TargetOS_CPP" TestTargetARCH_CPP -> "TargetARCH_CPP" TestGhcStage -> "GhcStage" TestGhcDebugged -> "GhcDebugged" TestGhcWithNativeCodeGen -> "GhcWithNativeCodeGen" TestGhcWithInterpreter -> "GhcWithInterpreter" TestGhcUnregisterised -> "GhcUnregisterised" TestGhcWithSMP -> "GhcWithSMP" TestGhcDynamicByDefault -> "GhcDynamicByDefault" TestGhcDynamic -> "GhcDynamic" TestGhcProfiled -> "GhcProfiled" TestAR -> "AR" TestCLANG -> "CLANG" TestLLC -> "LLC" TestTEST_CC -> "TEST_CC" TestGhcPackageDbFlag -> "GhcPackageDbFlag" TestMinGhcVersion711 -> "MinGhcVersion711" TestMinGhcVersion801 -> "MinGhcVersion801" -- | Get the RTS ways of the test compiler testRTSSettings :: Action [String] testRTSSettings = do file <- testConfigFile words <$> lookupValueOrError file "GhcRTSWays"
snowleopard/shaking-up-ghc
src/Oracles/TestSettings.hs
bsd-3-clause
2,784
0
10
984
334
186
148
56
21
{- | Description : logic for first order provers like SPASS This folder contains the interface to the SoftFOL provers. Currently there are three prover interfaces available: SPASS, the MathServ Broker and Vampire whereas the latter is called via MathServ, too. The MathServ Broker chooses the best prover depending on the problem, as there are E, Otter, SPASS, Vampire. The folder will be renamed to SoftFOL when the repository's version administrating system changes from CVS to Subversion. The SPASS project homepage is located at <http://spass.mpi-sb.mpg.de/>. "SoftFOL.Sign" provides data structures for SoftFOL signatures, formulae and problems. The emphasis is on outputting theories with the pretty printer ("SoftFOL.Print"); hence, not only the kernel language of SPASS is supported. Because the SPASS logic is only used for proving, no parser and static analysis are provided. "SoftFOL.ProveSPASS" is an interactive (SPASS is fully automated) interface to the SPASS prover. It uses 'GUI.GenericATP.genericATPgui' for display and interaction. "SoftFOL.ProveMathServ" is similar to "SoftFOL.ProveSPASS" as it addresses the MathServ Broker using the same GUI. The prover result (given by MathServ response) will be parsed and mapped into 'GUI.GenericATPState.GenericConfig' prover structures. "SoftFOL.ProveVampire" is quite similar to "SoftFOL.ProveMathServ", using MathServ for adressing the Vampire prover. "SoftFOL.MathServParsing" provides functions for parsing a MathServ output into a MathServResponse structure. "SoftFOL.MathServMapping" maps a 'SoftFOL.MathServParsing.MathServResponse' into a 'GUI.GenericATPState.GenericConfig' structure. "SoftFOL.ProverState" provides data structures and initialising functions for Prover state and configurations. "SoftFOL.Logic_SoftFOL" provides the SoftFOL instance of type class 'Logic.Logic.Logic'. "SoftFOL.ATC_SoftFOL": Automatic ATC derivation "SoftFOL.Conversions" provides functions to convert to internal SP\* data structures. "SoftFOL.CreateDFGDoc" prints a (G_theory CASL _) into a DFG Doc. "SoftFOL.Translate" provides collection of functions used by "Comorphisms.SuleCFOL2SoftFOL" and all prover interfaces ("SoftFOL.ProveSPASS", "SoftFOL.ProveMathServ", "SoftFOL.ProveVampire", "SoftFOL.ProveDarwin") for the translation of CASL identifiers and axiom labels into valid SoftFOL identifiers. "SoftFOL.Print" arranges pretty printing for SoftFOL signatures in DFG syntax. Refer to <http://spass.mpi-sb.mpg.de/webspass/help/syntax/dfgsyntax.html> for the DFG syntax documentation. "SoftFOL.PrintTPTP" arranges pretty printing for SoftFOL signatures in TPTP syntax. Refer to <http://www.cs.miami.edu/~tptp/TPTP/SyntaxBNF.html> for the TPTP syntax documentation. Relevant papers on SPASS include: C. Weidenbach, Spass: Combining superposition, sorts and splitting, in Handbook of Automated Reasoning, A. Robinson and A. Voronkov, Eds. Elsevier, 1999. -} module SoftFOL where
keithodulaigh/Hets
SoftFOL.hs
gpl-2.0
2,959
0
2
378
5
4
1
1
0
<?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="de-DE"> <title>Regular Expression Tester</title> <maps> <homeID>regextester</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>
kingthorin/zap-extensions
addOns/regextester/src/main/javahelp/help_de_DE/helpset_de_DE.hs
apache-2.0
978
77
66
157
409
207
202
-1
-1
{-# OPTIONS -cpp #-} {-# LANGUAGE NoMonomorphismRestriction #-} module Set60204 where #if __GLASGOW_HASKELL__ >= 604 import qualified Data.Set as S differenceS = S.difference unionsS = S.unions intersectionS = S.intersection fromListS = S.fromList emptyS = S.empty memberS = S.member mapS = S.map elemsS = S.elems unionS = S.union #else import qualified Sets as S difference = S.minusSet unionsS = S.unionManySets intersectionS=S.intersect fromListS = S.mkSet emptyS = S.emptySet memberS = S.elementOf mapS = S.mapSet elemsS = S.setToList unionS = S.union #endif
kmate/HaRe
old/tools/base/Set60204.hs
bsd-3-clause
566
0
5
82
80
50
30
13
1
{-# LANGUAGE AllowAmbiguousTypes, TypeFamilies #-} module ContextStack2 where type family TF a :: * type instance TF (a,b) = (TF a, TF b) t :: (a ~ TF (a,Int)) => Int t = undefined
spacekitteh/smcghc
testsuite/tests/typecheck/should_fail/ContextStack2.hs
bsd-3-clause
184
0
9
37
72
43
29
6
1
{-# LANGUAGE CPP #-} #include "T12135.h" main = print message
olsner/ghc
testsuite/tests/driver/T12135.hs
bsd-3-clause
62
0
5
10
11
6
5
2
1
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Thrift.Protocol.Compact ( module Thrift.Protocol , CompactProtocol(..) ) where import Control.Applicative import Control.Exception ( throw ) import Control.Monad import Data.Attoparsec.ByteString as P import Data.Attoparsec.ByteString.Lazy as LP import Data.Bits import Data.ByteString.Lazy.Builder as B import Data.Int import Data.List as List import Data.Monoid import Data.Word import Data.Text.Lazy.Encoding ( decodeUtf8, encodeUtf8 ) import Thrift.Protocol hiding (versionMask) import Thrift.Transport import Thrift.Types import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.HashMap.Strict as Map import qualified Data.Text.Lazy as LT -- | the Compact Protocol implements the standard Thrift 'TCompactProcotol' -- which is similar to the 'TBinaryProtocol', but takes less space on the wire. -- Integral types are encoded using as varints. data CompactProtocol a = CompactProtocol a -- ^ Constuct a 'CompactProtocol' with a 'Transport' protocolID, version, typeMask :: Int8 protocolID = 0x82 -- 1000 0010 version = 0x01 versionMask = 0x1f -- 0001 1111 typeMask = 0xe0 -- 1110 0000 typeBits = 0x07 -- 0000 0111 typeShiftAmount :: Int typeShiftAmount = 5 instance Protocol CompactProtocol where getTransport (CompactProtocol t) = t writeMessageBegin p (n, t, s) = tWrite (getTransport p) $ toLazyByteString $ B.int8 protocolID <> B.int8 ((version .&. versionMask) .|. (((fromIntegral $ fromEnum t) `shiftL` typeShiftAmount) .&. typeMask)) <> buildVarint (i32ToZigZag s) <> buildCompactValue (TString $ encodeUtf8 n) readMessageBegin p = runParser p $ do pid <- fromIntegral <$> P.anyWord8 when (pid /= protocolID) $ error "Bad Protocol ID" w <- fromIntegral <$> P.anyWord8 let ver = w .&. versionMask when (ver /= version) $ error "Bad Protocol version" let typ = (w `shiftR` typeShiftAmount) .&. typeBits seqId <- parseVarint zigZagToI32 TString name <- parseCompactValue T_STRING return (decodeUtf8 name, toEnum $ fromIntegral $ typ, seqId) serializeVal _ = toLazyByteString . buildCompactValue deserializeVal _ ty bs = case LP.eitherResult $ LP.parse (parseCompactValue ty) bs of Left s -> error s Right val -> val readVal p ty = runParser p $ parseCompactValue ty -- | Writing Functions buildCompactValue :: ThriftVal -> Builder buildCompactValue (TStruct fields) = buildCompactStruct fields buildCompactValue (TMap kt vt entries) = let len = fromIntegral $ length entries :: Word32 in if len == 0 then B.word8 0x00 else buildVarint len <> B.word8 (fromTType kt `shiftL` 4 .|. fromTType vt) <> buildCompactMap entries buildCompactValue (TList ty entries) = let len = length entries in (if len < 15 then B.word8 $ (fromIntegral len `shiftL` 4) .|. fromTType ty else B.word8 (0xF0 .|. fromTType ty) <> buildVarint (fromIntegral len :: Word32)) <> buildCompactList entries buildCompactValue (TSet ty entries) = buildCompactValue (TList ty entries) buildCompactValue (TBool b) = B.word8 $ toEnum $ if b then 1 else 0 buildCompactValue (TByte b) = int8 b buildCompactValue (TI16 i) = buildVarint $ i16ToZigZag i buildCompactValue (TI32 i) = buildVarint $ i32ToZigZag i buildCompactValue (TI64 i) = buildVarint $ i64ToZigZag i buildCompactValue (TDouble d) = doubleBE d buildCompactValue (TString s) = buildVarint len <> lazyByteString s where len = fromIntegral (LBS.length s) :: Word32 buildCompactStruct :: Map.HashMap Int16 (LT.Text, ThriftVal) -> Builder buildCompactStruct = flip (loop 0) mempty . Map.toList where loop _ [] acc = acc <> B.word8 (fromTType T_STOP) loop lastId ((fid, (_,val)) : fields) acc = loop fid fields $ acc <> (if fid > lastId && fid - lastId <= 15 then B.word8 $ fromIntegral ((fid - lastId) `shiftL` 4) .|. typeOf val else B.word8 (typeOf val) <> buildVarint (i16ToZigZag fid)) <> (if typeOf val > 0x02 -- Not a T_BOOL then buildCompactValue val else mempty) -- T_BOOLs are encoded in the type buildCompactMap :: [(ThriftVal, ThriftVal)] -> Builder buildCompactMap = foldl combine mempty where combine s (key, val) = buildCompactValue key <> buildCompactValue val <> s buildCompactList :: [ThriftVal] -> Builder buildCompactList = foldr (mappend . buildCompactValue) mempty -- | Reading Functions parseCompactValue :: ThriftType -> Parser ThriftVal parseCompactValue (T_STRUCT _) = TStruct <$> parseCompactStruct parseCompactValue (T_MAP kt' vt') = do n <- parseVarint id if n == 0 then return $ TMap kt' vt' [] else do w <- P.anyWord8 let kt = typeFrom $ w `shiftR` 4 vt = typeFrom $ w .&. 0x0F TMap kt vt <$> parseCompactMap kt vt n parseCompactValue (T_LIST ty) = TList ty <$> parseCompactList parseCompactValue (T_SET ty) = TSet ty <$> parseCompactList parseCompactValue T_BOOL = TBool . (/=0) <$> P.anyWord8 parseCompactValue T_BYTE = TByte . fromIntegral <$> P.anyWord8 parseCompactValue T_I16 = TI16 <$> parseVarint zigZagToI16 parseCompactValue T_I32 = TI32 <$> parseVarint zigZagToI32 parseCompactValue T_I64 = TI64 <$> parseVarint zigZagToI64 parseCompactValue T_DOUBLE = TDouble . bsToDouble <$> P.take 8 parseCompactValue T_STRING = do len :: Word32 <- parseVarint id TString . LBS.fromStrict <$> P.take (fromIntegral len) parseCompactValue ty = error $ "Cannot read value of type " ++ show ty parseCompactStruct :: Parser (Map.HashMap Int16 (LT.Text, ThriftVal)) parseCompactStruct = Map.fromList <$> parseFields 0 where parseFields :: Int16 -> Parser [(Int16, (LT.Text, ThriftVal))] parseFields lastId = do w <- P.anyWord8 if w == 0x00 then return [] else do let ty = typeFrom (w .&. 0x0F) modifier = (w .&. 0xF0) `shiftR` 4 fid <- if modifier /= 0 then return (lastId + fromIntegral modifier) else parseVarint zigZagToI16 val <- if ty == T_BOOL then return (TBool $ (w .&. 0x0F) == 0x01) else parseCompactValue ty ((fid, (LT.empty, val)) : ) <$> parseFields fid parseCompactMap :: ThriftType -> ThriftType -> Int32 -> Parser [(ThriftVal, ThriftVal)] parseCompactMap kt vt n | n <= 0 = return [] | otherwise = do k <- parseCompactValue kt v <- parseCompactValue vt ((k,v) :) <$> parseCompactMap kt vt (n-1) parseCompactList :: Parser [ThriftVal] parseCompactList = do w <- P.anyWord8 let ty = typeFrom $ w .&. 0x0F lsize = w `shiftR` 4 size <- if lsize == 0xF then parseVarint id else return $ fromIntegral lsize loop ty size where loop :: ThriftType -> Int32 -> Parser [ThriftVal] loop ty n | n <= 0 = return [] | otherwise = liftM2 (:) (parseCompactValue ty) (loop ty (n-1)) -- Signed numbers must be converted to "Zig Zag" format before they can be -- serialized in the Varint format i16ToZigZag :: Int16 -> Word16 i16ToZigZag n = fromIntegral $ (n `shiftL` 1) `xor` (n `shiftR` 15) zigZagToI16 :: Word16 -> Int16 zigZagToI16 n = fromIntegral $ (n `shiftR` 1) `xor` negate (n .&. 0x1) i32ToZigZag :: Int32 -> Word32 i32ToZigZag n = fromIntegral $ (n `shiftL` 1) `xor` (n `shiftR` 31) zigZagToI32 :: Word32 -> Int32 zigZagToI32 n = fromIntegral $ (n `shiftR` 1) `xor` negate (n .&. 0x1) i64ToZigZag :: Int64 -> Word64 i64ToZigZag n = fromIntegral $ (n `shiftL` 1) `xor` (n `shiftR` 63) zigZagToI64 :: Word64 -> Int64 zigZagToI64 n = fromIntegral $ (n `shiftR` 1) `xor` negate (n .&. 0x1) buildVarint :: (Bits a, Integral a) => a -> Builder buildVarint n | n .&. complement 0x7F == 0 = B.word8 $ fromIntegral n | otherwise = B.word8 (0x80 .|. (fromIntegral n .&. 0x7F)) <> buildVarint (n `shiftR` 7) parseVarint :: (Bits a, Integral a, Ord a) => (a -> b) -> Parser b parseVarint fromZigZag = do bytestemp <- BS.unpack <$> P.takeTill (not . flip testBit 7) lsb <- P.anyWord8 let bytes = lsb : List.reverse bytestemp return $ fromZigZag $ List.foldl' combine 0x00 bytes where combine a b = (a `shiftL` 7) .|. (fromIntegral b .&. 0x7f) -- | Compute the Compact Type fromTType :: ThriftType -> Word8 fromTType ty = case ty of T_STOP -> 0x00 T_BOOL -> 0x01 T_BYTE -> 0x03 T_I16 -> 0x04 T_I32 -> 0x05 T_I64 -> 0x06 T_DOUBLE -> 0x07 T_STRING -> 0x08 T_LIST{} -> 0x09 T_SET{} -> 0x0A T_MAP{} -> 0x0B T_STRUCT{} -> 0x0C T_VOID -> error "No Compact type for T_VOID" typeOf :: ThriftVal -> Word8 typeOf v = case v of TBool True -> 0x01 TBool False -> 0x02 TByte _ -> 0x03 TI16 _ -> 0x04 TI32 _ -> 0x05 TI64 _ -> 0x06 TDouble _ -> 0x07 TString _ -> 0x08 TList{} -> 0x09 TSet{} -> 0x0A TMap{} -> 0x0B TStruct{} -> 0x0C typeFrom :: Word8 -> ThriftType typeFrom w = case w of 0x01 -> T_BOOL 0x02 -> T_BOOL 0x03 -> T_BYTE 0x04 -> T_I16 0x05 -> T_I32 0x06 -> T_I64 0x07 -> T_DOUBLE 0x08 -> T_STRING 0x09 -> T_LIST T_VOID 0x0A -> T_SET T_VOID 0x0B -> T_MAP T_VOID T_VOID 0x0C -> T_STRUCT Map.empty n -> error $ "typeFrom: " ++ show n ++ " is not a compact type"
traceguide/api-php
vendor/apache/thrift/lib/hs/src/Thrift/Protocol/Compact.hs
mit
10,297
0
19
2,334
3,217
1,677
1,540
228
13
{-# LANGUAGE Safe #-} -- Since Safe we require base package be trusted to compile module Check04_B where import Check04_A mainM :: Int -> Int mainM n = trace "Allowed Leak" $ n * 2
urbanslug/ghc
testsuite/tests/safeHaskell/check/Check04_B.hs
bsd-3-clause
185
0
7
39
37
21
16
5
1
{-# LANGUAGE Safe #-} {-# OPTIONS_GHC -fenable-rewrite-rules #-} -- | Check rules are disabled under Safe module Main where data T = T1 | T2 | T3 deriving ( Eq, Ord, Show ) lookupx :: Ord key => Show val => [(key,val)] -> key -> Maybe val lookupx [] _ = Nothing lookupx ((t,a):xs) t' | t == t' = Just a | otherwise = lookupx xs t' {-# RULES "lookupx/T" lookupx = tLookup #-} tLookup :: [(T,a)] -> T -> Maybe a tLookup [] _ = Nothing tLookup ((t,a):xs) t' | t /= t' = Just a | otherwise = tLookup xs t' space = [(T1,"a"),(T2,"b"),(T3,"c")] key = T3 main = do putStrLn $ "looking for " ++ show key putStrLn $ "in space " ++ show space putStrLn $ "Found: " ++ show (fromMaybe "Not Found!" $ lookupx space key) let b | Just "c" <- lookupx space key = "YES" | otherwise = "NO" putStrLn $ "Rules Disabled: " ++ b fromMaybe :: a -> Maybe a -> a fromMaybe a Nothing = a fromMaybe _ (Just a) = a
urbanslug/ghc
testsuite/tests/safeHaskell/safeLanguage/SafeLang05.hs
bsd-3-clause
1,036
0
14
332
412
210
202
-1
-1
module ShouldFail where class A a where p1 :: a -> a p2 :: a -> a -> a class (A b) => B b where p3 :: b p4 :: b -> b class (A c) => C c where p5 :: c -> c p6 :: c -> Int class (B d,C d) => D d where p7 :: d -> d instance D [a] where p7 l = []
hferreiro/replay
testsuite/tests/typecheck/should_fail/tcfail019.hs
bsd-3-clause
257
0
8
86
157
83
74
14
0
{-# LANGUAGE OverloadedStrings #-} module ConfigMenu where -- import Graphics.Vty hiding (pad) import Graphics.Vty.Widgets.All -- import System.Locale -- import Control.Monad import qualified Data.Text as T -- Multi-state checkbox value type data FlowControlType = Hardware | Software deriving (Eq, Show) -- data SpeedT = 15220 | 9600 data Config = Config FlowControlType T.Text T.Text deriving (Show) type ConfigBoxT = Box (Box (Box (Box (HFixed (Box FormattedText (CheckBox FlowControlType))) FormattedText) (HFixed Edit)) FormattedText) (HFixed Edit) data ConfigInput = ConfigInput { configInputWidgit :: Widget ConfigBoxT , speed :: Widget Edit , device :: Widget Edit , activateHandlers :: Handlers Config } -- ------------------ -- -- Configuration Menu -- -- ------------------ -- configMenu :: IO (ConfigInput, Widget FocusGroup) configMenu = do ahs <- newHandlers r1 <- newMultiStateCheckbox "FlowControl" [ (Hardware, 'H') , (Software, 'S') ] r1State <- plainText T.empty rbox <- return r1State <++> return r1 e1 <- editWidget e2 <- editWidget ui <- hFixed 4 rbox <++> plainText "-" <++> hFixed 4 e1 <++> plainText "-" <++> hFixed 4 e2 let w = ConfigInput ui e1 e2 ahs doFireEvent = const $ do conf <- mkConfig fireEvent w (return . activateHandlers) conf mkConfig = do h1 <- getCheckboxState r1 s1 <- getEditText e1 s2 <- getEditText e2 return $ Config h1 s1 s2 setCheckboxState r1 Software -- It would be nice if we didn't have to do this, but the -- setCheckboxState call above will not notify any state-change -- handlers because the state isn't actually changing (from its -- original value of Chocolate, the first value in its state list). setText r1State "you chose: Software" e1 `onActivate` doFireEvent -- e2 `onActivate` doFireEvent -- r1 `onChange` \s -> when (T.length s == 3) $ focus e1 -- e1 `onChange` \s -> when (T.length s == 3) $ focus e2 r1 `onCheckboxChange` \v -> setText r1State $ T.pack ("you chose: " ++ show v) fgc <- newFocusGroup mapM_ (addToFocusGroup fgc) [e1, e2] return (w, fgc)
alterapraxisptyltd/serialterm
src/ConfigMenu.hs
isc
2,435
0
17
736
538
276
262
45
1
module Main where import FD import Sudoku import Queens2 import SendMoreMoney testPuzzle :: Puzzle testPuzzle = [ 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 6, 5, 0, 7, 4, 0, 2, 7, 0, 0, 0, 0, 0, 0, 8, 0, 3, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 0, 5, 0, 0, 9, 0, 7, 0, 0, 5, 0, 0, 0, 8, 0, 0, 6, 3, 0, 1, 2, 0, 4, 0, 0, 0, 0, 0, 6, 0, 1, 0, 0, 0, 0 ] hard1 :: Puzzle hard1 = [ 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 9, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0, 5, 0, 9, 0, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 8, 5, 0, 0, 4, 0, 7, 0, 0, 0, 0, 0, 6, 0, 0, 0, 3, 0, 0, 0, 9, 0, 8, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1 ] hard2 :: Puzzle hard2 = [ 0, 0, 1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 6, 0, 3, 0, 5, 0, 0, 0, 9, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 7, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 8, 5, 0, 0, 0, 7, 0, 6, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 6, 0, 0, 9, 2, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0 ] main = do putStrLn "Sudoku hard2" printSudoku hard2 putStrLn "8 Queens" print $ runFD $ nQueens 8 >>= labelling -- putStrLn "send + more = money" -- print $ zip ['s', 'e', 'n', 'd', 'm', 'o', 'r', 'y'] sendMoreMoney test = do putStrLn "test" print $ runFD $ do vars@[a, b, c] <- news 3 (1, 9) a #== b * c labelling vars
dmoverton/finite-domain
app/Main.hs
mit
1,393
0
12
514
887
568
319
49
1
-- In this class, I can USE the data instance of AnonClass, but I'm not allowed -- to actually construct it module Main where import ClassExample main :: IO () main = printAnon $ anonClass "Hello" printAnon :: (Show a) => AnonClass a -> IO () printAnon = print
iduhetonas/haskell-projects
DataTypes/ClassTest.hs
mit
265
0
8
53
62
34
28
6
1
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- import System.Environment (getArgs) import Data.Ord import Data.List import Data.Maybe import Data.Array import Debug.Trace type Mote = Integer type Problem = (Mote, [Mote]) type Result = Int main :: IO () main = do [file] <- getArgs ip <- readFile file writeFile ((takeWhile (/= '.') file) ++ ".out" ) (processInput ip) writeOutput :: [(Int, Result)] -> [String] writeOutput = map (\(i, r) -> ("Case #" ++ (show i) ++ ": " ++ (writeResult r))) processInput :: String -> String processInput = unlines . writeOutput . zip [1..] . map solveProblem . parseProblem . tail . lines writeResult :: Result -> String writeResult = show parseProblem :: [String] -> [Problem] parseProblem [] = [] parseProblem (an:ns:ss) = let [a, n] = map read . words $ an nums = map read . words $ ns in (a, nums) : parseProblem ss -- x, 2x - 1, 4x - 3, 8x - 7 .... sumAbsorbedMotes :: Mote -> Int -> Mote sumAbsorbedMotes x i = (2^i)*x - (2^i - 1) -- computes number of motes needed to absorb the next one -- binary search the range, to get log N instead of N efficiency computeNumMotes :: Mote -> Mote -> Int -> Int -> Int computeNumMotes curMote tgtMote loGuess hiGuess = let midGuess = (loGuess + hiGuess) `div` 2 loSum = sumAbsorbedMotes curMote loGuess midSum= sumAbsorbedMotes curMote midGuess hiSum = sumAbsorbedMotes curMote hiGuess in if loGuess + 1 >= hiGuess -- can't binary search anymore then if loSum >= tgtMote then loGuess else if hiSum >= tgtMote then hiGuess else error "Probably initial bounds for guesses incorrect" else if loSum == tgtMote then loGuess else if hiSum == tgtMote then hiGuess else if (midSum > tgtMote) then computeNumMotes curMote tgtMote loGuess midGuess else computeNumMotes curMote tgtMote midGuess hiGuess solveProblem' :: Problem -> Result solveProblem' (_, []) = 0 solveProblem' (1, ms) = length ms solveProblem' pb@(a, ms) = let m = head ms ms' = tail ms loGuess = 0 hiGuess = fromIntegral $ (m `div` a) + 1 num = computeNumMotes a (m+1) loGuess hiGuess val = sumAbsorbedMotes a num numRec = solveProblem' (val, ms) in if a > m then solveProblem' ((a + m), ms') else if (num > length ms) || (num == 0) || (num + numRec >= length ms) then length ms -- delete everything that is left else num + numRec solveProblem :: Problem -> Result solveProblem pb@(a, ms) = solveProblem' (a, sort ms)
cbrghostrider/Hacking
codeJam/2013/osmos/osmos.hs
mit
3,141
0
13
889
887
484
403
65
7
{-# LANGUAGE DeriveGeneric #-} -- | RSA crypto utility functions -- -- High-level wrapper around the somewhat arcane HsOpenssl library. There are -- various alternative libraries around, but I don't trust them. I would really -- like to use libsodium / saltine, but the author specifically advices against -- using it, so I will follow that advice. -- -- Furthermore, there are various other pure-haskell RSA/AES libraries around, -- but I don't think they have undergone the same scrutiny and peer reviews as -- OpenSSL has. So for now, we will wrap OpenSSL in a nice interface, and mark -- this as a to-do for the future. We will hard-code our preferences in this -- module. -- -- The implementation of this module, and usage of the HsOpenSSL API, will need -- proper peer review. module Dissent.Crypto.Rsa where import GHC.Generics (Generic) import qualified Data.Binary as B import qualified Data.ByteString as BS import Data.Maybe (fromJust) import OpenSSL (withOpenSSL) import qualified OpenSSL.EVP.Cipher as Cipher import qualified OpenSSL.EVP.Open as Open import qualified OpenSSL.EVP.PKey as PKey import qualified OpenSSL.EVP.Seal as Seal import qualified OpenSSL.PEM as PEM import qualified OpenSSL.RSA as RSA import qualified Crypto.Padding as Pad (padPKCS5, unpadPKCS5) import qualified Dissent.Internal.Debug as D type PublicKey = RSA.RSAPubKey type PrivateKey = RSA.RSAKeyPair data KeyPair = KeyPair { public :: PublicKey, private :: PrivateKey } deriving (Eq, Show) data Encrypted = Encrypted { output :: BS.ByteString, -- ^ Output string key :: BS.ByteString, -- ^ Encrypted assymetric key iv :: BS.ByteString -- ^ Input vector } deriving (Eq, Show, Generic) instance B.Binary Encrypted -- Our cipher key length cipherBits :: Int cipherBits = 256 allCiphers :: IO [String] allCiphers = withOpenSSL Cipher.getCipherNames cipherName :: String cipherName = "AES-" ++ show cipherBits ++ "-CBC" -- When we are using a cypher in block mode, we need to ensure we are using a -- proper padding, otherwise an attacker can determine the message length of -- the last block. -- -- It is tempting to think that paddingBytes = cypherBits / 8, but the -- cypher bits is the *key* length, not the block length. AES uses -- a fixed block length, according to Wikipedia: -- -- "AES is a variant of Rijndael which has a fixed block size of 128 -- bits" -- -- http://en.wikipedia.org/wiki/Advanced_Encryption_Standard paddingBytes :: Int paddingBytes = quot 128 8 -- | We will be using AES as Cipher for our RSA encryption getCipher :: IO Cipher.Cipher getCipher = withOpenSSL $ (return . fromJust) =<< Cipher.getCipherByName cipherName -- | We want to be able to represent our public key as string serializePublicKey :: PublicKey -> IO String serializePublicKey = PEM.writePublicKey -- | And we want to be able to get our string representation back as public key deserializePublicKey :: String -> IO PublicKey deserializePublicKey someKey = let unsafeCast :: PKey.SomePublicKey -> PublicKey unsafeCast = fromJust . PKey.toPublicKey in (return . unsafeCast) =<< PEM.readPublicKey someKey generateKeyPair :: IO KeyPair generateKeyPair = withOpenSSL $ -- Use a large key size / exponent let keySize = 4096 keyExponent = 65537 generateRsaKey = RSA.generateRSAKey' keySize keyExponent -- Extracts public key part out of a private key extractPublicKey :: PrivateKey -> IO PublicKey extractPublicKey = RSA.rsaCopyPublic in do privateKey <- D.log "Generating RSA key pair" generateRsaKey publicKey <- extractPublicKey privateKey return (KeyPair publicKey privateKey) encrypt :: PublicKey -> BS.ByteString -> IO Encrypted encrypt publicKey input = withOpenSSL $ -- AES-CBC requires us to pad the input message if the messages are/can be -- of variable length. let pad :: BS.ByteString -> BS.ByteString pad = Pad.padPKCS5 paddingBytes in do cipher <- getCipher (encrypted, [encKey], inputVector) <- Seal.sealBS cipher [PKey.fromPublicKey publicKey] (pad input) return (Encrypted encrypted encKey inputVector) decrypt :: PrivateKey -> Encrypted -> IO BS.ByteString decrypt privateKey encrypted = let encKey = key encrypted inputVector = iv encrypted input = output encrypted unpad :: BS.ByteString -> BS.ByteString unpad = Pad.unpadPKCS5 in do cipher <- getCipher (return . unpad) (Open.openBS cipher encKey inputVector privateKey input)
solatis/dissent
src/Dissent/Crypto/Rsa.hs
mit
4,714
0
14
1,043
799
455
344
74
1
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -- | This module provides a function for reading .xlsx files module Codec.Xlsx.Parser ( toXlsx ) where import qualified Codec.Archive.Zip as Zip import Control.Applicative import Control.Arrow ((&&&)) import Control.Monad (liftM4) import Control.Monad.IO.Class() import qualified Data.ByteString.Lazy as L import Data.ByteString.Lazy.Char8() import Data.IntMap (IntMap) import qualified Data.IntMap as IM import Data.List import qualified Data.Map as M import Data.Maybe import Data.Ord import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Read as T import Data.XML.Types import Prelude hiding (sequence) import Text.XML as X import Text.XML.Cursor import Codec.Xlsx.Types -- | Reads `Xlsx' from raw data (lazy bytestring) toXlsx :: L.ByteString -> Xlsx toXlsx bs = Xlsx sheets styles where ar = Zip.toArchive bs ss = getSharedStrings ar styles = getStyles ar wfs = getWorksheetFiles ar sheets = M.fromList $ map (wfName &&& extractSheet ar ss) wfs data WorksheetFile = WorksheetFile { wfName :: Text , wfPath :: FilePath } deriving Show decimal :: Monad m => Text -> m Int decimal t = case T.decimal t of Right (d, _) -> return d _ -> fail "invalid decimal" rational :: Monad m => Text -> m Double rational t = case T.rational t of Right (r, _) -> return r _ -> fail "invalid rational" extractSheet :: Zip.Archive -> IM.IntMap Text -> WorksheetFile -> Worksheet extractSheet ar ss wf = Worksheet cws rowProps cells merges where file = fromJust $ Zip.fromEntry <$> Zip.findEntryByPath (wfPath wf) ar cur = case parseLBS def file of Left _ -> error "could not read file" Right d -> fromDocument d cws = cur $/ element (n"cols") &/ element (n"col") >=> liftM4 ColumnsWidth <$> (attribute "min" >=> decimal) <*> (attribute "max" >=> decimal) <*> (attribute "width" >=> rational) <*> (attribute "style" >=> decimal) (rowProps, cells) = collect $ cur $/ element (n"sheetData") &/ element (n"row") >=> parseRow parseRow c = do r <- c $| attribute "r" >=> decimal let ht = if attribute "customHeight" c == ["true"] then listToMaybe $ c $| attribute "ht" >=> rational else Nothing let s = if attribute "s" c /= [] then listToMaybe $ c $| attribute "s" >=> decimal else Nothing let rp = if isNothing s && isNothing ht then Nothing else Just (RowProps ht s) return (r, rp, c $/ element (n"c") >=> parseCell) parseCell :: Cursor -> [(Int, Int, Cell)] parseCell cell = do let s = listToMaybe $ cell $| attribute "s" >=> decimal t = fromMaybe "n" $ listToMaybe $ cell $| attribute "t" d = listToMaybe $ cell $/ element (n"v") &/ content >=> extractCellValue ss t (c, r) <- T.span (>'9') <$> (cell $| attribute "r") return (int r, col2int c, Cell s d) collect = foldr collectRow (M.empty, M.empty) collectRow (_, Nothing, rowCells) (rowMap, cellMap) = (rowMap, foldr collectCell cellMap rowCells) collectRow (r, Just h, rowCells) (rowMap, cellMap) = (M.insert r h rowMap, foldr collectCell cellMap rowCells) collectCell (x, y, cd) = M.insert (x,y) cd merges = cur $/ parseMerges parseMerges :: Cursor -> [Text] parseMerges = element (n"mergeCells") &/ element (n"mergeCell") >=> parseMerge parseMerge c = c $| attribute "ref" extractCellValue :: IntMap Text -> Text -> Text -> [CellValue] extractCellValue ss "s" v = case T.decimal v of Right (d, _) -> maybeToList $ fmap CellText $ IM.lookup d ss _ -> [] extractCellValue _ "str" str = [CellText str] extractCellValue _ "n" v = case T.rational v of Right (d, _) -> [CellDouble d] _ -> [] extractCellValue _ "b" "1" = [CellBool True] extractCellValue _ "b" "0" = [CellBool False] extractCellValue _ _ _ = [] -- | Add sml namespace to name n :: Text -> Name n x = Name { nameLocalName = x , nameNamespace = Just "http://schemas.openxmlformats.org/spreadsheetml/2006/main" , namePrefix = Nothing } -- | Add office document relationship namespace to name odr :: Text -> Name odr x = Name { nameLocalName = x , nameNamespace = Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships" , namePrefix = Nothing } -- | Add package relationship namespace to name pr :: Text -> Name pr x = Name { nameLocalName = x , nameNamespace = Just "http://schemas.openxmlformats.org/package/2006/relationships" , namePrefix = Nothing } -- | Get xml cursor from the specified file inside the zip archive. xmlCursor :: Zip.Archive -> FilePath -> Maybe Cursor xmlCursor ar fname = parse <$> Zip.findEntryByPath fname ar where parse entry = case parseLBS def (Zip.fromEntry entry) of Left _ -> error "could not read file" Right d -> fromDocument d -- | Get shared strings (if there are some) into IntMap. getSharedStrings :: Zip.Archive -> IM.IntMap Text getSharedStrings x = case xmlCursor x "xl/sharedStrings.xml" of Nothing -> IM.empty Just c -> IM.fromAscList $ zip [0..] (c $/ element (n"si") &/ element (n"t") &/ content) getStyles :: Zip.Archive -> Styles getStyles ar = case Zip.fromEntry <$> Zip.findEntryByPath "xl/styles.xml" ar of Nothing -> Styles L.empty Just xml -> Styles xml -- | getWorksheetFiles pulls the names of the sheets getWorksheetFiles :: Zip.Archive -> [WorksheetFile] getWorksheetFiles ar = case xmlCursor ar "xl/workbook.xml" of Nothing -> error "invalid workbook" Just c -> let sheetData = c $/ element (n"sheets") &/ element (n"sheet") >=> liftA2 (,) <$> attribute "name" <*> attribute (odr"id") wbRels = getWbRels ar in [WorksheetFile name ("xl/" ++ T.unpack (fromJust $ lookup rId wbRels)) | (name, rId) <- sheetData] getWbRels :: Zip.Archive -> [(Text, Text)] getWbRels ar = case xmlCursor ar "xl/_rels/workbook.xml.rels" of Nothing -> [] Just c -> c $/ element (pr"Relationship") >=> liftA2 (,) <$> attribute "Id" <*> attribute "Target" int :: Text -> Int int = either error fst . T.decimal
lookunder/xlsx
src/Codec/Xlsx/Parser.hs
mit
6,636
0
19
1,769
2,097
1,090
1,007
148
6
{-# LANGUAGE DeriveDataTypeable #-} module BT.Config where import Data.Configurator (lookup, Worth(Required), load) import Data.Configurator.Types (Configured, Config) import Data.Text (pack) import Data.Maybe (fromMaybe) import Data.Typeable (Typeable) import Control.Exception data ConfigException = ConfigException String deriving (Show, Typeable) instance Exception ConfigException makeConfig :: IO Config makeConfig = load [Required "/etc/bittoll/bittoll.conf"] getConfig :: Configured a => Config -> String -> IO a getConfig c k = do t <- Data.Configurator.lookup c (pack k) return $ fromMaybe (throw $ ConfigException k) t
c00w/BitToll
haskell/BT/Config.hs
mit
648
0
11
95
201
109
92
17
1
-------------------------------------------------------------------------------- -- Highly divisible triangular number -- Problem 12 -- The sequence of triangle numbers is generated by adding the natural numbers. -- So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. -- The first ten terms would be: -- 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... -- Let us list the factors of the first seven triangle numbers: -- 1: 1 -- 3: 1,3 -- 6: 1,2,3,6 -- 10: 1,2,5,10 -- 15: 1,3,5,15 -- 21: 1,3,7,21 -- 28: 1,2,4,7,14,28 -- We can see that 28 is the first triangle number to have over five divisors. -- What is the value of the first triangle number to have over five hundred divisors? -------------------------------------------------------------------------------- -- some further examples also showing prime factors. -- ======== =========== =========================================== -- triangle prime divisors -- number factors -- ======== =========== =========================================== -- 3 [3] [1,3] -- 6 [2,3] [1,2,3,6] -- 28 [2,2,7] [1,2,4,7,14,28] -- 36 [2,2,3,3] [1,2,3,4,6,9,12,18,36] -- 120 [2,2,2,3,5] [1,2,3,4,5,6,8,10,12,15,20,24,30,40,60,120] -- ======== =========== =========================================== import Data.Numbers.Primes import Data.List -- infnite list of triangle numbers [1,3,6,10..] triangles :: Integral a => [a] triangles = scanl1 (+) [1..] -- take a list of prime factors and return a list of divisors divisors factors = nub $ sort $ map product $ subsequences factors solve limit = solve' triangles where solve' ts | n >= limit = (limit,n,t,p,d) | otherwise = solve' (tail ts) where t = head ts p = primeFactors t d = divisors p n = length d main = do print $ take 20 triangles print $ solve 2 print $ solve 3 print $ solve 4 print $ solve 5 print $ solve 501
bertdouglas/euler-haskell
001-050/12a.hs
mit
2,046
0
10
519
264
144
120
21
1
{-# LANGUAGE OverloadedStrings #-} module Database.RethinkDB.Model.IO where import Database.RethinkDB.NoClash import Control.Monad.Trans.Reader import Control.Monad.Trans (liftIO) -- RethinkIO --------------------------------------------- runDb :: (Expr a, Result r) => a -> RethinkIO r runDb e = do h <- ask liftIO $ run h e type RethinkIO = ReaderT RethinkDBHandle IO
seanhess/rethinkdb-model
Database/RethinkDB/Model/IO.hs
mit
385
0
8
61
99
56
43
10
1
{-# LANGUAGE FlexibleInstances #-} module Model where import ClassyPrelude.Yesod import Database.Persist.Quasi -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models") -- TODO : meerdere persist files in één app, gaat dat (namespacing)? -- dependencies? instance Eq Company where -- (==) = undefined (==) = (==) `on` companyName instance RenderMessage master Company where -- renderMessage _ _ = undefined renderMessage _ _ = companyName
KasperJanssens/yesod-tutorial
Model.hs
mit
711
0
8
117
96
57
39
-1
-1
module Main where import Control.Applicative import Data.Char (digitToInt) import System.IO (print) main = print $ maximum $ map sumOfDigits gogol gogol = (^) <$> [1..100] <*> [1..100] sumOfDigits = sum . map digitToInt . show
t00n/ProjectEuler
Euler/Euler56/main.hs
epl-1.0
281
0
7
89
88
50
38
7
1
import Math import Data.List import Data.Function -- PROBLEM 85 csrec i j m n = (succ (m - i)) * (succ (n - j)) crec m n = sum [csrec i j m n | i <- [1..m], j <- [1..n]] sol_85 size lim = minimumBy (compare `on` snd) res where res = [(i*j, abs (lim - (crec i j))) | i <- [1..size], j <- [1..size]] -- ELAPSED TIME 30 SECONDS!!
zeniuseducation/poly-euler
haskell/prob76-100.hs
epl-1.0
338
0
13
83
199
107
92
7
1
{-# language RankNTypes #-} {-# language ScopedTypeVariables #-} {-# language FlexibleContexts #-} module Machine.Numerical.Make where import Inter.Types import Machine.Class import qualified Machine.Var as M import qualified Machine.Numerical.Type as N import qualified Machine.Numerical.Config as Con import Challenger.Partial import Autolib.ToDoc import Autolib.Reporter import System.Random import Data.Typeable instance OrderScore N.Computer where scoringOrder _ = Increasing testliste :: Int -> Int -> Integer -> IO [[Integer]] testliste len ari hei = sequence $ replicate len $ do xs <- sequence $ replicate ari $ randomRIO (0, hei) return xs make :: forall c m dat conf b . ( Show c, Con.Check c m , Con.ConfigC c m , Machine m dat conf , Partial N.Computer ( N.Type c m ) b , Typeable b ) => Con.Config c m -> Make make ( defcon :: Con.Config c m ) = let t = "Machine.Numerical" ++ "." ++ Con.name defcon in Make N.Computer t ( \ ( conf :: Con.Config c m ) -> Var { problem = N.Computer , tag = t , key = \ matrikel -> return matrikel -- , gen = \ _vnr _manr key _cache -> fnum conf key , generate = \ salt cachefun -> fnum conf salt -- FIXME: cachefun ? } ) ( \ _con -> return () ) -- verify defcon fnum :: ( Show c , Con.Check c m , Con.ConfigC c m , Machine m dat conf ) => Con.Config c m -> Int -> IO ( Reporter ( N.Type c m )) fnum conf key = do xss <- testliste ( Con.num_args conf ) ( Con.arity conf ) ( Con.max_arg conf ) let xs = map M.Var [ 1 .. fromIntegral $ Con.arity conf ] return $ return $ N.Make { N.op = Con.op conf , N.key = fromIntegral key , N.fun_info = fsep [ text "\\" , toDoc xs , text "->", toDoc $ Con.op conf ] , N.extra_info = vcat $ (text "Die Maschine soll die folgenden Bedingungen erfüllen:") : (do c <- map show ( Con.checks conf) ++ Con.conditions conf return $ nest 4 $ text $ "* " ++ c ) , N.args = xss , N.cut = Con.cut conf , N.checks = Con.checks conf , N.start = Con.start conf }
marcellussiegburg/autotool
collection/src/Machine/Numerical/Make.hs
gpl-2.0
2,421
0
19
863
768
406
362
58
1
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} -- | Korrekturfunktion für Faktorisierung -- [email protected] -- benutzt code für challenger/PCProblem -- von Markus Kreuz [email protected] module Faktor.Times ( make_fixed , make_quiz ) where import Challenger.Partial import Autolib.ToDoc import Autolib.Reporter import Autolib.Ana import Autolib.Size import Inter.Types import Inter.Quiz import Faktor.Times.Param import System.Random import Data.Typeable ------------------------------------------------------------------------------- data Times = Times deriving ( Eq, Show, Read, Typeable ) instance OrderScore Times where scoringOrder _ = None instance Size Integer where size _ = 1 instance Partial Times [ Integer ] Integer where describe Times xs = vcat [ text "Gesucht ist das Produkt der Zahlen " , nest 4 $ toDoc xs ] initial Times xs = sum xs total Times xs y = do let p = product xs when (y /= p) $ reject $ fsep [ text "Das Produkt der Zahlen" , toDoc xs, text "ist nicht", toDoc y ] make_fixed :: Make make_fixed = direct Times [ 222222222 :: Integer , 44444444444444, 555555555555555 ] ------------------------------------------------------------------------------- make_quiz :: Make make_quiz = quiz Times Faktor.Times.Param.example roll :: Param -> IO [ Integer ] roll p = sequence $ do i <- [ 1 .. anzahl p ] return $ do cs <- sequence $ replicate ( stellen p ) $ randomRIO ( 0, 9 ) return $ foldl ( \ a b -> 10 * a + b ) 0 cs instance Generator Times Param [ Integer ] where generator _ conf key = do xs <- roll conf return xs instance Project Times [ Integer ][ Integer ] where project _ = id
Erdwolf/autotool-bonn
src/Faktor/Times.hs
gpl-2.0
1,860
13
17
448
482
251
231
45
1
{-# LANGUAGE TemplateHaskell #-} module Algebraic.Relation.Restriction where import Condition import Autolib.Reader import Autolib.ToDoc import Autolib.Size import Autolib.Reporter import Data.Typeable data Restriction = Size_Range (Int, Int) deriving ( Eq, Ord, Typeable ) $(derives [makeReader, makeToDoc] [''Restriction]) -- local variables: -- mode: haskell -- end:
florianpilz/autotool
src/Algebraic/Relation/Restriction.hs
gpl-2.0
394
0
9
67
92
55
37
12
0