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
module Src.Model.SecureEmployee(SEmployee, viewPublicDetails, fromEmployee, firstName, lastName, birthdate, salary, email, leader, increaseSalary) where import qualified Src.Model.Employee as E import Security.SecureFlow import Security.Lattice import Security.ThreeLevels -- | A secure version of Employee where every field is given a specific security -- level. data SEmployee = SEmployee { firstName :: SecureFlow Low String , lastName :: SecureFlow Low String , birthdate :: SecureFlow Low String , salary :: SecureFlow High Int , email :: SecureFlow Medium String , leader :: SecureFlow Low Bool } -- Cast function from a ''normal'' Employee fromEmployee :: E.Employee -> SEmployee fromEmployee e = SEmployee (pure $ E.firstName e) (pure $ E.lastName e) (pure $ E.birthdate e) (pure $ E.salary e) (pure $ E.email e) (pure $ E.leader e) -- | In order to view public details (i.e. all but salary) a `medium` ticked is -- required. Since `email` has a `Medium` level, a `low` ticket is not enough. viewPublicDetails :: LEQ Medium s => Ticket s -> SEmployee -> String viewPublicDetails Ticket se = "Firstname: " ++ (open' $ firstName se) ++ "\nLastname: " ++ (open' $ lastName se) ++ "\nBirthdate: " ++ (open' $ birthdate se) ++ "\nEmail address: " ++ (open' $ email se) ++ "\nIs a leader?: " ++ show (open' $ leader se) where open' e = open medium e -- | A simple function for increasing the salary without reading it. Here the -- functorial `fmap` function is used since the salary is encapsulated into a -- SecureFlox box. increaseSalary :: Int -> SEmployee -> SEmployee increaseSalary i se = SEmployee f l b s e le where f = firstName se l = lastName se b = birthdate se s = fmap (\s -> s+i) $ salary se e = email se le = leader se
mdipirro/haskell-secure-types
app/Src/Model/SecureEmployee.hs
gpl-3.0
2,382
0
16
940
494
264
230
-1
-1
module Public (publicSuffixTests) where import Data.Functor import Test.HUnit import Network.DNS.Public import Network.DNS.Public.Types (dropSubdomains) checkPublicSuffix :: Rules -> String -> String -> Test checkPublicSuffix rules domain suffix = TestLabel label $ TestCase $ assertBool (show $ showDomain <$> suffix'') pass where label = "(" ++ domain ++ "," ++ suffix ++ ")" domain' = makeStringDomain domain suffix' = if null suffix then domain' else dropSubdomains 1 <$> makeStringDomain suffix suffix'' = publicSuffix rules <$> domain' pass = suffix' == suffix'' publicSuffixTests :: Rules -> [Test] publicSuffixTests r = [ checkPublicSuffix r "COM" "" , checkPublicSuffix r "example.COM" "example.com" , checkPublicSuffix r "WwW.example.COM" "example.com" , checkPublicSuffix r ".com" "" , checkPublicSuffix r ".example" "" , checkPublicSuffix r ".example.com" "example.com" , checkPublicSuffix r ".example.example" "example.example" , checkPublicSuffix r "example" "" , checkPublicSuffix r "example.example" "example.example" , checkPublicSuffix r "b.example.example" "example.example" , checkPublicSuffix r "a.b.example.example" "example.example" , checkPublicSuffix r "biz" "" , checkPublicSuffix r "domain.biz" "domain.biz" , checkPublicSuffix r "b.domain.biz" "domain.biz" , checkPublicSuffix r "a.b.domain.biz" "domain.biz" , checkPublicSuffix r "com" "" , checkPublicSuffix r "example.com" "example.com" , checkPublicSuffix r "b.example.com" "example.com" , checkPublicSuffix r "a.b.example.com" "example.com" , checkPublicSuffix r "uk.com" "" , checkPublicSuffix r "example.uk.com" "example.uk.com" , checkPublicSuffix r "b.example.uk.com" "example.uk.com" , checkPublicSuffix r "a.b.example.uk.com" "example.uk.com" , checkPublicSuffix r "test.ac" "test.ac" , checkPublicSuffix r "cy" "" , checkPublicSuffix r "c.cy" "" , checkPublicSuffix r "b.c.cy" "b.c.cy" , checkPublicSuffix r "a.b.c.cy" "b.c.cy" , checkPublicSuffix r "jp" "" , checkPublicSuffix r "test.jp" "test.jp" , checkPublicSuffix r "www.test.jp" "test.jp" , checkPublicSuffix r "ac.jp" "" , checkPublicSuffix r "test.ac.jp" "test.ac.jp" , checkPublicSuffix r "www.test.ac.jp" "test.ac.jp" , checkPublicSuffix r "kyoto.jp" "" , checkPublicSuffix r "c.kyoto.jp" "c.kyoto.jp" , checkPublicSuffix r "b.c.kyoto.jp" "c.kyoto.jp" , checkPublicSuffix r "a.b.c.kyoto.jp" "c.kyoto.jp" , checkPublicSuffix r "pref.kyoto.jp" "pref.kyoto.jp" , checkPublicSuffix r "www.pref.kyoto.jp" "pref.kyoto.jp" , checkPublicSuffix r "city.kyoto.jp" "city.kyoto.jp" , checkPublicSuffix r "www.city.kyoto.jp" "city.kyoto.jp" , checkPublicSuffix r "om" "" , checkPublicSuffix r "test.om" "" , checkPublicSuffix r "b.test.om" "b.test.om" , checkPublicSuffix r "a.b.test.om" "b.test.om" , checkPublicSuffix r "songfest.om" "songfest.om" , checkPublicSuffix r "www.songfest.om" "songfest.om" , checkPublicSuffix r "us" "" , checkPublicSuffix r "test.us" "test.us" , checkPublicSuffix r "www.test.us" "test.us" , checkPublicSuffix r "ak.us" "" , checkPublicSuffix r "test.ak.us" "test.ak.us" , checkPublicSuffix r "www.test.ak.us" "test.ak.us" , checkPublicSuffix r "k12.ak.us" "" , checkPublicSuffix r "test.k12.ak.us" "test.k12.ak.us" , checkPublicSuffix r "www.test.k12.ak.us" "test.k12.ak.us" ]
ktvoelker/cookie-jar
test/Public.hs
gpl-3.0
3,412
0
10
537
761
388
373
75
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.BackendServices.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves the list of BackendService resources available to the -- specified project. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.backendServices.list@. module Network.Google.Resource.Compute.BackendServices.List ( -- * REST Resource BackendServicesListResource -- * Creating a Request , backendServicesList , BackendServicesList -- * Request Lenses , bslReturnPartialSuccess , bslOrderBy , bslProject , bslFilter , bslPageToken , bslMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.backendServices.list@ method which the -- 'BackendServicesList' request conforms to. type BackendServicesListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "backendServices" :> QueryParam "returnPartialSuccess" Bool :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] BackendServiceList -- | Retrieves the list of BackendService resources available to the -- specified project. -- -- /See:/ 'backendServicesList' smart constructor. data BackendServicesList = BackendServicesList' { _bslReturnPartialSuccess :: !(Maybe Bool) , _bslOrderBy :: !(Maybe Text) , _bslProject :: !Text , _bslFilter :: !(Maybe Text) , _bslPageToken :: !(Maybe Text) , _bslMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BackendServicesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bslReturnPartialSuccess' -- -- * 'bslOrderBy' -- -- * 'bslProject' -- -- * 'bslFilter' -- -- * 'bslPageToken' -- -- * 'bslMaxResults' backendServicesList :: Text -- ^ 'bslProject' -> BackendServicesList backendServicesList pBslProject_ = BackendServicesList' { _bslReturnPartialSuccess = Nothing , _bslOrderBy = Nothing , _bslProject = pBslProject_ , _bslFilter = Nothing , _bslPageToken = Nothing , _bslMaxResults = 500 } -- | Opt-in for partial success behavior which provides partial results in -- case of failure. The default value is false. bslReturnPartialSuccess :: Lens' BackendServicesList (Maybe Bool) bslReturnPartialSuccess = lens _bslReturnPartialSuccess (\ s a -> s{_bslReturnPartialSuccess = a}) -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the -- \`creationTimestamp\` field in reverse chronological order (newest -- result first). Use this to sort resources like operations so that the -- newest operation is returned first. Currently, only sorting by \`name\` -- or \`creationTimestamp desc\` is supported. bslOrderBy :: Lens' BackendServicesList (Maybe Text) bslOrderBy = lens _bslOrderBy (\ s a -> s{_bslOrderBy = a}) -- | Project ID for this request. bslProject :: Lens' BackendServicesList Text bslProject = lens _bslProject (\ s a -> s{_bslProject = a}) -- | A filter expression that filters resources listed in the response. The -- expression must specify the field name, a comparison operator, and the -- value that you want to use for filtering. The value must be a string, a -- number, or a boolean. The comparison operator must be either \`=\`, -- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute -- Engine instances, you can exclude instances named \`example-instance\` -- by specifying \`name != example-instance\`. You can also filter nested -- fields. For example, you could specify \`scheduling.automaticRestart = -- false\` to include instances only if they are not scheduled for -- automatic restarts. You can use filtering on nested fields to filter -- based on resource labels. To filter on multiple expressions, provide -- each separate expression within parentheses. For example: \`\`\` -- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\") -- \`\`\` By default, each expression is an \`AND\` expression. However, -- you can include \`AND\` and \`OR\` expressions explicitly. For example: -- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel -- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\` bslFilter :: Lens' BackendServicesList (Maybe Text) bslFilter = lens _bslFilter (\ s a -> s{_bslFilter = a}) -- | Specifies a page token to use. Set \`pageToken\` to the -- \`nextPageToken\` returned by a previous list request to get the next -- page of results. bslPageToken :: Lens' BackendServicesList (Maybe Text) bslPageToken = lens _bslPageToken (\ s a -> s{_bslPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than \`maxResults\`, Compute -- Engine returns a \`nextPageToken\` that can be used to get the next page -- of results in subsequent list requests. Acceptable values are \`0\` to -- \`500\`, inclusive. (Default: \`500\`) bslMaxResults :: Lens' BackendServicesList Word32 bslMaxResults = lens _bslMaxResults (\ s a -> s{_bslMaxResults = a}) . _Coerce instance GoogleRequest BackendServicesList where type Rs BackendServicesList = BackendServiceList type Scopes BackendServicesList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient BackendServicesList'{..} = go _bslProject _bslReturnPartialSuccess _bslOrderBy _bslFilter _bslPageToken (Just _bslMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy BackendServicesListResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/BackendServices/List.hs
mpl-2.0
7,205
0
19
1,550
758
454
304
109
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.GamesConfiguration.AchievementConfigurations.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Delete the achievement configuration with the given ID. -- -- /See:/ <https://developers.google.com/games/services Google Play Game Services Publishing API Reference> for @gamesConfiguration.achievementConfigurations.delete@. module Network.Google.Resource.GamesConfiguration.AchievementConfigurations.Delete ( -- * REST Resource AchievementConfigurationsDeleteResource -- * Creating a Request , achievementConfigurationsDelete , AchievementConfigurationsDelete -- * Request Lenses , acdAchievementId ) where import Network.Google.GamesConfiguration.Types import Network.Google.Prelude -- | A resource alias for @gamesConfiguration.achievementConfigurations.delete@ method which the -- 'AchievementConfigurationsDelete' request conforms to. type AchievementConfigurationsDeleteResource = "games" :> "v1configuration" :> "achievements" :> Capture "achievementId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Delete the achievement configuration with the given ID. -- -- /See:/ 'achievementConfigurationsDelete' smart constructor. newtype AchievementConfigurationsDelete = AchievementConfigurationsDelete' { _acdAchievementId :: Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AchievementConfigurationsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acdAchievementId' achievementConfigurationsDelete :: Text -- ^ 'acdAchievementId' -> AchievementConfigurationsDelete achievementConfigurationsDelete pAcdAchievementId_ = AchievementConfigurationsDelete' { _acdAchievementId = pAcdAchievementId_ } -- | The ID of the achievement used by this method. acdAchievementId :: Lens' AchievementConfigurationsDelete Text acdAchievementId = lens _acdAchievementId (\ s a -> s{_acdAchievementId = a}) instance GoogleRequest AchievementConfigurationsDelete where type Rs AchievementConfigurationsDelete = () type Scopes AchievementConfigurationsDelete = '["https://www.googleapis.com/auth/androidpublisher"] requestClient AchievementConfigurationsDelete'{..} = go _acdAchievementId (Just AltJSON) gamesConfigurationService where go = buildClient (Proxy :: Proxy AchievementConfigurationsDeleteResource) mempty
rueshyna/gogol
gogol-games-configuration/gen/Network/Google/Resource/GamesConfiguration/AchievementConfigurations/Delete.hs
mpl-2.0
3,342
0
12
677
303
186
117
52
1
{-# LANGUAGE OverloadedStrings #-} module Web.Stylus ( generateStylusCSS ) where import Control.Monad.IO.Class (liftIO) import System.Process (callProcess) import System.FilePath (takeExtensions) import Files import Web import Web.Types import Web.Files import Web.Generate generateStylusCSS :: WebGenerator generateStylusCSS = \fo@(f, _) -> do let src = "app.styl" sl <- liftIO $ findWebFiles ".styl" fpRel <- liftIO $ unRawFilePath $ webFileRel f fpAbs <- liftIO $ unRawFilePath $ webFileAbs f srcAbs <- liftIO $ (unRawFilePath . webFileAbs) =<< makeWebFilePath =<< rawFilePath src webRegenerate (callProcess "stylus" $ (if takeExtensions fpRel == ".min.css" then ("-c":) else id) [ "-u", "nib" , "-u", "autoprefixer-stylus" , "-o", fpAbs , srcAbs ]) [] sl fo
databrary/databrary
src/Web/Stylus.hs
agpl-3.0
827
0
15
169
247
135
112
29
2
{-# LANGUAGE TemplateHaskell #-} module Moonbase.Desktop where import Control.Lens import Control.Monad import Control.Monad.STM import Control.Concurrent.STM.TVar import Control.Monad.State import qualified Graphics.UI.Gtk as Gtk import qualified System.Glib.GError as Glib import Moonbase.Core import Moonbase.Signal import Moonbase.Theme (Color) import Moonbase.Util import Moonbase.Util.Gtk import Data.Word type MonitorNum = Int data Monitor = Monitor { _monitorNum :: MonitorNum , _monitorGeo :: Gtk.Rectangle , _monitorWindow :: Gtk.Window } makeLenses ''Monitor type ScreenNum = Int data Screen = Screen { _screenNum :: ScreenNum , _screenResolution :: (Int, Int) , _screenMonitors :: [Monitor] , _screenComposited :: Bool , _screenScreen :: Gtk.Screen , _screenConfigure :: Configure Screen () } makeLenses ''Screen data DesktopState = DesktopState { _desktopScreens :: [Screen] , _desktopDisplay :: Gtk.Display } type Desktop = TVar DesktopState makeLenses ''DesktopState initializeScreen :: Gtk.Display -> ScreenNum -> Moon Screen initializeScreen disp num = do debug $ "Initialize screen " ++ show num ++ "..." screen <- liftIO $ Gtk.displayGetScreen disp num numMonitors <- liftIO $ Gtk.screenGetNMonitors screen w <- liftIO $ Gtk.screenGetWidth screen h <- liftIO $ Gtk.screenGetHeight screen composited <- liftIO $ Gtk.screenIsComposited screen debug $ " :: " ++ show numMonitors ++ " assigned to this screen" monitors <- mapM (initializeMonitor screen) [0..(numMonitors - 1)] return $ Screen num (w,h) monitors composited screen (return ()) initializeMonitor :: Gtk.Screen -> MonitorNum -> Moon Monitor initializeMonitor screen num = do debug $ "Initialize monitor " ++ show num ++ "..." rect <- liftIO $ Gtk.screenGetMonitorGeometry screen num window <- liftIO $ newMonitorWindow num screen rect return $ Monitor num rect window withDesktop :: Configure DesktopState () -> Moon Desktop withDesktop conf = do debug "with basic Desktop..." disp <- checkDisplay =<< liftIO Gtk.displayGetDefault numScreens <- liftIO $ Gtk.displayGetNScreens disp debug $ " :: " ++ show numScreens ++ " screens available" screens <- mapM (initializeScreen disp) [0..(numScreens - 1)] let state = DesktopState screens disp state' <- configure state conf showDesktops state' liftIO $ atomically $ newTVar state' -- TODO: -- Add displayClosed handling -- Add screenChanged handling -- Add compositChanged handling showDesktops :: DesktopState -> Moon () showDesktops state = do let windows = state ^.. allMonitors . traverse . monitorWindow forM_ windows $ \w -> liftIO $ do Gtk.widgetQueueDraw w Gtk.widgetShowAll w where allMonitors = desktopScreens . traverse . screenMonitors onEveryScreen :: Configure Screen () -> Configure DesktopState () onEveryScreen conf = do lift $ debug "running on every screen" desktopScreens . traverse . screenConfigure .= conf screens <- use desktopScreens screens' <- mapM configure' screens desktopScreens .= screens' where configure' s = lift $ configure s conf onEveryMonitor :: Configure Monitor () -> Configure DesktopState () onEveryMonitor conf = onEveryScreen $ do lift $ debug "running on every monitor..." monitors <- use screenMonitors monitors' <- mapM configure' monitors screenMonitors .= monitors' where configure' m = lift $ configure m conf setBackgroundColor :: Color -> Configure Monitor () setBackgroundColor c = do window <- use monitorWindow num <- use monitorNum (Gtk.Rectangle x y w h) <- use monitorGeo lift $ debug $ "Setting Color of Monitor " ++ show num ++ " to " ++ c image <- liftIO $ do buf <- Gtk.pixbufNew Gtk.ColorspaceRgb False 8 w h Gtk.pixbufFill buf r g b 255 Gtk.imageNewFromPixbuf buf liftIO $ Gtk.containerAdd window image where (r,g,b,_) = parseColorTuple c :: (Word8, Word8, Word8, Word8) setWallpaper :: FilePath -> Configure Monitor () setWallpaper path = do window <- use monitorWindow num <- use monitorNum (Gtk.Rectangle x y w h) <- use monitorGeo lift $ debug $ "Setting Wallpaper of Monitor " ++ show num ++ " to " ++ path image <- liftIO $ do pixbuf <- Glib.catchGErrorJustDomain (wallpaper w h) (errorPixBuf w h) Gtk.imageNewFromPixbuf pixbuf liftIO $ Gtk.containerAdd window image where wallpaper w h = Gtk.pixbufNewFromFileAtScale path w h False errorPixBuf :: Int -> Int -> Gtk.PixbufError -> Glib.GErrorMessage -> IO Gtk.Pixbuf errorPixBuf w h _ _ = do buf <- Gtk.pixbufNew Gtk.ColorspaceRgb False 8 w h Gtk.pixbufFill buf 0 0 0 255 return buf newMonitorWindow :: Int -> Gtk.Screen -> Gtk.Rectangle -> IO Gtk.Window newMonitorWindow i screen (Gtk.Rectangle x y w h) = do window <- Gtk.windowNew Gtk.windowSetScreen window screen Gtk.widgetSetName window ("desktop-" ++ show i) Gtk.windowSetGeometryHints window noWidget size size Nothing Nothing Nothing Gtk.windowMove window x y Gtk.windowSetDefaultSize window w h Gtk.widgetSetSizeRequest window w h Gtk.windowResize window w h Gtk.windowSetTypeHint window Gtk.WindowTypeHintDesktop Gtk.windowSetGravity window Gtk.GravityStatic Gtk.widgetSetCanFocus window False return window where noWidget :: Maybe Gtk.Widget noWidget = Nothing size :: Maybe (Int, Int) size = Just (w, h) setComposited :: Gtk.Display -> Screen -> Moon Screen setComposited disp screen = do screen' <- liftIO $ Gtk.displayGetScreen disp $ _screenNum screen composited <- liftIO $ Gtk.screenIsComposited screen' return $ screen { _screenComposited = composited }
felixsch/moonbase-ng
src/Moonbase/Desktop.hs
lgpl-2.1
6,042
0
14
1,449
1,811
878
933
-1
-1
{-| This package provides test types for Network.Haskoin -} module Network.Haskoin.Test ( -- * Util Arbitrary instances ArbitraryByteString(..) , ArbitraryNotNullByteString(..) , ArbitraryUTCTime(..) -- * Crypto Arbitrary instances , ArbitraryPoint(..) , ArbitraryInfPoint(..) , ArbitraryPrvKey(..) , ArbitraryPrvKeyC(..) , ArbitraryPrvKeyU(..) , ArbitraryPubKey(..) , ArbitraryPubKeyC(..) , ArbitraryPubKeyU(..) , ArbitraryAddress(..) , ArbitraryPubKeyAddress(..) , ArbitraryScriptAddress(..) , ArbitrarySignature(..) , ArbitraryDetSignature(..) , ArbitraryXPrvKey(..) , ArbitraryXPubKey(..) , ArbitraryMasterKey(..) , ArbitraryAccPrvKey(..) , ArbitraryAccPubKey(..) , ArbitraryAddrPrvKey(..) , ArbitraryAddrPubKey(..) -- * Node Arbitrary instances , ArbitraryVarInt(..) , ArbitraryVarString(..) , ArbitraryNetworkAddress(..) , ArbitraryNetworkAddressTime(..) , ArbitraryInvType(..) , ArbitraryInvVector(..) , ArbitraryInv(..) , ArbitraryVersion(..) , ArbitraryAddr(..) , ArbitraryAlert(..) , ArbitraryReject(..) , ArbitraryRejectCode(..) , ArbitraryGetData(..) , ArbitraryNotFound(..) , ArbitraryPing(..) , ArbitraryPong(..) , ArbitraryBloomFlags(..) , ArbitraryBloomFilter(..) , ArbitraryFilterLoad(..) , ArbitraryFilterAdd(..) , ArbitraryMessageCommand(..) -- * Message Arbitrary instances , ArbitraryMessageHeader(..) , ArbitraryMessage(..) -- * Script Arbitrary instances , ArbitraryScriptOp(..) , ArbitraryScript(..) , ArbitraryIntScriptOp(..) , ArbitraryPushDataType(..) , ArbitraryTxSignature(..) , ArbitraryDetTxSignature(..) , ArbitrarySigHash(..) , ArbitraryValidSigHash(..) , ArbitraryMSParam(..) , ArbitraryScriptOutput(..) , ArbitrarySimpleOutput(..) , ArbitraryPKOutput(..) , ArbitraryPKHashOutput(..) , ArbitraryMSOutput(..) , ArbitraryMSCOutput(..) , ArbitrarySHOutput(..) , ArbitraryScriptInput(..) , ArbitrarySimpleInput(..) , ArbitraryPKInput(..) , ArbitraryPKHashInput(..) , ArbitraryPKHashCInput(..) , ArbitraryMSInput(..) , ArbitrarySHInput(..) , ArbitraryMulSigSHCInput(..) -- * Transaction Arbitrary instances , ArbitrarySatoshi(..) , ArbitraryTx(..) , ArbitraryTxIn(..) , ArbitraryTxOut(..) , ArbitraryOutPoint(..) , ArbitraryCoinbaseTx(..) , ArbitraryAddrOnlyTx(..) , ArbitraryAddrOnlyTxIn(..) , ArbitraryAddrOnlyTxOut(..) , ArbitraryCoin(..) , ArbitrarySigInput(..) , ArbitraryPKSigInput(..) , ArbitraryPKHashSigInput(..) , ArbitraryMSSigInput(..) , ArbitrarySHSigInput(..) , ArbitrarySigningData(..) , ArbitraryPartialTxs(..) -- * Block Arbitrary instances , ArbitraryBlock(..) , ArbitraryBlockHeader(..) , ArbitraryGetBlocks(..) , ArbitraryGetHeaders(..) , ArbitraryHeaders(..) , ArbitraryMerkleBlock(..) -- * Stratum Arbitrary instances , ReqRes(..) ) where import Network.Haskoin.Test.Util import Network.Haskoin.Test.Crypto import Network.Haskoin.Test.Node import Network.Haskoin.Test.Message import Network.Haskoin.Test.Script import Network.Haskoin.Test.Transaction import Network.Haskoin.Test.Block import Network.Haskoin.Test.Stratum
nuttycom/haskoin
Network/Haskoin/Test.hs
unlicense
3,003
0
5
288
732
525
207
104
0
module OpIO (run) where import Hello import Op import Control.Monad.Free import Data.Time.Clock.POSIX import System.Environment run :: Op r -> IO r run (Pure r) = return r run (Free (PutStrLn s t)) = putStrLn s >> run t run (Free (ReadFile p f)) = readFile p >>= run . f run (Free (GetTimestamp f)) = fmap (realToFrac) getPOSIXTime >>= run . f run (Free (GetArgs f)) = getArgs >>= run . f
aztecrex/haskell-testing-with-free-monad
src/OpIO.hs
unlicense
392
0
9
75
194
100
94
12
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module DeployR.API where -- this will be split into several files, just for notes right now import Servant.API import Servant.Client -- picked up from servant tutorial code. TODO reduce if possible import Data.Proxy import GHC.Generics import Data.Text(Text) import qualified Data.Text as T import Data.List(isPrefixOf) import DeployR.Types -- Data types for the API ---------------------------- -- DeployR API spec, grouped -- | overall API. Everything starts by "r" type DeployRAPI = "deployr" :> "r" :> ( DeployRUserAPI :<|> DeployRProjectAPI :<|> DeployRRepoAPI -- :<|> DeployRJobAPI :<|> DeployREventAPI -- irrelevant for our use case ) ------------------------------------------------------------ -- pattern-matching out the sub-APIs, following the type structure userAPI :<|> projectAPI :<|> repoAPI = client (Proxy :: Proxy DeployRAPI) -- | User login, logout (Info and options not implemented) type DeployRUserAPI = "user" :> ( "login" :> ReqBody '[FormUrlEncoded] LoginData :> Post '[JSON] (DRResponse DRUser) :<|> "logout" :> ReqBody '[FormUrlEncoded] LogoutData :> Header "Cookie" Text :> Post '[JSON] (DRResponse ()) ) -- pattern-matching out the client functions, following the type structure login :<|> logout = userAPI ------------------------------------------------------------ -- | Project API: execution in context, project files, workspace (R -- environment), project management (TODO not implemented) type DeployRProjectAPI = "project" :> ( DeployRExecAPI -- execute in project (differs from "script" in repo :<|> DeployRPDirAPI -- project dir API, differs from Repo Dir API :<|> DeployRWorkspaceAPI -- specific to projects -- :<|> DeployROtherAPI -- creation, access, closing (sin-bin approach) ) -- sub-APIs execAPI :<|> pDirAPI :<|> wspaceAPI = projectAPI -- | execution of code in project context type DeployRExecAPI = "execute" :> ( "code" :> ReqBody '[FormUrlEncoded] ExecCode :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Post '[JSON] (DRResponse ExecResult) :<|> "script" :> ReqBody '[FormUrlEncoded] ExecScript :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Post '[JSON] (DRResponse ExecResult) :<|> "flush" :> ReqBody '[FormUrlEncoded] RqProject :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Post '[JSON] (DRResponse DRProject) -- and a few more, concerned with exec. history, not too relevant for us ) -- sub-APIs execCode :<|> execScript :<|> execFlush = execAPI -- | Directory of a project type DeployRPDirAPI = "directory" :> ( "list" :> QueryParam "format" Format -- not really needed :> QueryParam "project" Text :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Get '[JSON] (DRResponse [ProjectFile]) :<|> "upload" -- :> ReqBody something missing :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Post '[JSON] (DRResponse ProjectFile) -- and a lot more... ) -- client functions pDirList :<|> pDirUpload -- :<|> and more = pDirAPI -- | Workspace of projects (R environment) type DeployRWorkspaceAPI = "workspace" :> ( "list" :> QueryParam "format" Format :> QueryParam "project" Text :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Get '[JSON] (DRResponse WSObjects) -- and a lot more... ) -- client functions wspaceList -- :<|> and more = wspaceAPI ------------------------------------------------------------ -- File Repository API: directories (1 level), files, script execution type DeployRRepoAPI = "repository" :> ( DeployRDirAPI -- repo dir API :<|> DeployRFileAPI -- repo file API :<|> DeployRScriptAPI -- script listing and execution -- :<|> DeployRRepoMoreStuff -- all that we could not fit ) -- sub-APIs rDirAPI :<|> rFileAPI :<|> rScriptAPI -- :<|> and more = repoAPI -- | Directories in projects and repository type DeployRDirAPI = "directory" :> ( "list" :> QueryParam "format" Format :> QueryParam "directory" Text -- optional :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Get '[JSON] (DRResponse ()) -- TODO wrong return type :<|> "create" :> ReqBody '[FormUrlEncoded] RqDir :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Post '[JSON] (DRResponse ()) -- TODO wrong return type -- and a lot more... ) -- client functions rDirList :<|> rDirCreate -- :<|> and more = rDirAPI -- | Files in the repository type DeployRFileAPI = "file" :> ( "list" :> QueryParam "format" Format -- :> QueryParam "filename" Text -- optional -- :> QueryParam "directory" Text -- optional, with filename :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Get '[JSON] (DRResponse [RepoFile]) :<|> "upload" {- :> ReqBody something missing -} :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Post '[JSON] (DRResponse RepoFile) -- and a lot more... ) -- client functions rFileList :<|> rFileUpload -- :<|> and more = rFileAPI -- | execution and query of scripts that reside in the repository. -- Not corresponding to execution of scripts in projects (although -- largely similar) type DeployRScriptAPI = "script" :> ( "list" {- :> QueryParam missing -} :> QueryParam "format" Format :> QueryParam "filename" Text -- optional :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Get '[JSON] (DRResponse [RepoScript]) :<|> "execute" :> ReqBody '[FormUrlEncoded] ExecScript -- project ignored! :> Header "Cookie" Text -- will contain "JSESSIONID=<cookie>" :> Post '[JSON] (DRResponse ExecResult) -- and two more ... ) -- client functions rScriptList :<|> rScriptExec -- :<|> and more = rScriptAPI
jberthold/deployR-hs
src/DeployR/API.hs
apache-2.0
6,370
0
20
1,609
1,036
570
466
107
1
import System.Cmd import System.Environment import System.FilePath import System.Exit import System.Directory import Data.List import Control.Monad import Text.Regex main = do args <- getArgs dir <- getCurrentDirectory contents <- getDirectoryContents (dir </> "output") if not $ null args then mapM copy [ "output" </> file | file <- contents, ".html" `isSuffixOf` file, takeBaseName file `elem` args ] else mapM copy [ "output" </> file | file <- contents, ".html" `isSuffixOf` file ] copy file = do let new = "tests" </> takeFileName file <.> ".ref" print file print new contents <- readFile file writeFile new (stripLinks contents) stripLinks f = subRegex (mkRegexWithOpts "<A HREF=[^>]*>" False False) f "<A HREF=\"\">"
nominolo/haddock2
tests/golden-tests/copy.hs
bsd-2-clause
771
0
12
153
257
128
129
22
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Web.Twitter.Conduit.Cursor ( IdsCursorKey, UsersCursorKey, ListsCursorKey, EventsCursorKey, WithCursor (..), ) where import Control.DeepSeq (NFData) import Data.Aeson import Data.Proxy (Proxy (..)) import Data.String import GHC.Generics import GHC.TypeLits (KnownSymbol, Symbol, symbolVal) -- $setup -- >>> import Data.Text -- >>> type UserId = Integer type IdsCursorKey = "ids" type UsersCursorKey = "users" type ListsCursorKey = "lists" type EventsCursorKey = "events" -- | A wrapper for API responses which have "next_cursor" field. -- -- The first type parameter of 'WithCursor' specifies the field name of contents. -- -- >>> let Just res = decode "{\"previous_cursor\": 0, \"next_cursor\": 1234567890, \"ids\": [1111111111]}" :: Maybe (WithCursor Integer "ids" UserId) -- >>> nextCursor res -- Just 1234567890 -- >>> contents res -- [1111111111] -- -- >>> let Just res = decode "{\"previous_cursor\": 0, \"next_cursor\": 0, \"users\": [1000]}" :: Maybe (WithCursor Integer "users" UserId) -- >>> nextCursor res -- Just 0 -- >>> contents res -- [1000] -- -- >>> let Just res = decode "{\"next_cursor\": \"hogehoge\", \"events\": [1000]}" :: Maybe (WithCursor Text "events" UserId) -- >>> nextCursor res -- Just "hogehoge" -- >>> contents res -- [1000] data WithCursor cursorType (cursorKey :: Symbol) wrapped = WithCursor { previousCursor :: Maybe cursorType , nextCursor :: Maybe cursorType , contents :: [wrapped] } deriving (Show, Eq, Generic, Generic1, Functor, Foldable, Traversable) instance (KnownSymbol cursorKey, FromJSON cursorType) => FromJSON1 (WithCursor cursorType cursorKey) where liftParseJSON _ lp = withObject ("WithCursor \"" ++ cursorKeyStr ++ "\"") $ \obj -> WithCursor <$> obj .:? "previous_cursor" <*> obj .:? "next_cursor" <*> (obj .: fromString cursorKeyStr >>= lp) where cursorKeyStr = symbolVal (Proxy :: Proxy cursorKey) instance (KnownSymbol cursorKey, FromJSON cursorType, FromJSON wrapped) => FromJSON (WithCursor cursorType cursorKey wrapped) where parseJSON = parseJSON1 instance (NFData cursorType, NFData wrapped) => NFData (WithCursor cursorType cursorKey wrapped)
himura/twitter-conduit
src/Web/Twitter/Conduit/Cursor.hs
bsd-2-clause
2,495
0
12
442
410
246
164
39
0
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} import qualified Data.ByteString.Char8 as C import Data.ByteString.Lazy.Builder #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 707 import Data.ByteString.Lazy.Builder.ASCII #endif import Data.Array.Unboxed import Data.Array.IO #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707 import Data.Array.Unsafe #endif import Control.Monad import Data.Monoid import Data.List import Data.Char import System.IO (stdout) type Palin = UArray Int Int fromBS :: C.ByteString -> UArray Int Int fromBS s = amap dig $ listArray (0, l-1) (C.unpack s) where dig x = ord x - ord '0' l = C.length s type PalinM = IOUArray Int Int arraySizeM iou = getBounds iou >>= \(i, j) -> return $! j - i + 1 arraySize u = j - i + 1 where (i, j) = bounds u fixupM :: PalinM -> Int -> Int -> IO () fixupM m i j | i < 0 = return () | i == 0 = readArray m i >>= \vi -> when (vi > 9 && i /= j) ( writeArray m j 1 ) | otherwise = do let !i' = pred i !j' = succ j vi <- readArray m i vi' <- readArray m i' when (vi > 9) (writeArray m i 0 >> writeArray m j 0 >> writeArray m i' (succ vi') >> writeArray m j' (succ vi')) fixupM m i' j' nextPalinM :: PalinM -> IO () nextPalinM x = arraySizeM x >>= \len -> go x 0 (len-1) False False where go m !i !j !c u | i >= j = when (c || not u) (readArray m j >>= \v1 -> writeArray m j (succ v1) >> writeArray m i (succ v1) ) >> fixupM m j i | otherwise = do v1 <- readArray m i v2 <- readArray m j let !i' = succ i !j' = pred j case compare v1 v2 of EQ -> go m i' j' c u GT -> writeArray m j v1 >> go m i' j' False True LT -> writeArray m j v1 >> go m i' j' True True go :: PalinM -> Int -> Int -> Bool -> Bool -> IO () c1 = C.pack "2134" c2 = C.pack "94187978322" c3 = C.pack "214633" nextPalinMut :: C.ByteString -> IO Palin nextPalinMut c = do let v1 = fromBS c v2 <- unsafeThaw v1 :: IO PalinM nextPalinM v2 v3 <- unsafeFreeze v2 :: IO Palin return v3 printPalin :: Palin -> IO () printPalin x = hPutBuilder stdout (go x 0 (len)) where go v 0 l = if (l == 1 && (v ! 0 > 9) ) then string8 "11\n" else intDec (v ! 0) <> go v 1 l go v !i l | i >= l = char8 '\n' | otherwise = intDec (v ! i) <> go v (succ i) l len = arraySize x doNextPalin_ :: C.ByteString -> IO () doNextPalin_ s = nextPalinMut s >>= printPalin getinputs s = C.lines rest where (_, t1) = C.break (== '\n') s (_, rest) = C.span (== '\n') t1 process = mapM_ doNextPalin_ . getinputs main = C.getContents >>= process
wangbj/haskell
0005a.hs
bsd-2-clause
2,718
0
16
780
1,228
602
626
69
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} -- | This module contains the code that is used for generating the PureScript -- client code. module PureFlowy.Client where import Control.Applicative import Control.Lens import Data.Proxy import Language.PureScript.Bridge import Servant.PureScript import PureFlowy.Api.Todos (Api, Todo) -- | We have been lazy and defined our types in the WebAPI module, -- we use this opportunity to show how to create a custom bridge moving those -- types to Counter.ServerTypes. fixTypesModule :: BridgePart fixTypesModule = do typeModule ^== "PureFlowy.Api" t <- view haskType TypeInfo (_typePackage t) "Counter.ServerTypes" (_typeName t) <$> psTypeParameters myBridge :: BridgePart myBridge = defaultBridge <|> fixTypesModule data MyBridge myBridgeProxy :: Proxy MyBridge myBridgeProxy = Proxy instance HasBridge MyBridge where languageBridge _ = buildBridge myBridge myTypes :: [SumType 'Haskell] myTypes = [ mkSumType (Proxy :: Proxy Todo) ] mySettings :: Settings mySettings = defaultSettings & apiModuleName .~ "PureFlowy.Api" generateClient :: IO () generateClient = do let frontEndRoot = "ui/src" writeAPIModuleWithSettings mySettings frontEndRoot myBridgeProxy (Proxy :: Proxy Api) writePSTypes frontEndRoot (buildBridge myBridge) myTypes
parsonsmatt/pureflowy
src/PureFlowy/Client.hs
bsd-3-clause
1,392
0
10
264
267
144
123
-1
-1
module Liste (skaste, mezofatcidu, mezosetcidu, mezopatcidu) where import Data.Maybe skaste :: [(String, (Int, Int, Int))] skaste = [ ("xekri", (0, 0, 0)), ("blabi", (255, 255, 255)), ("xunre", (255, 0, 0)), ("labri'o", (0, 255, 0)), -- Lime ("crinyblabi", (0, 255, 0)), -- Lime ("blanu", (0, 0, 255)), ("pelxu", (255, 255, 0)), ("cicna", (0, 255, 255)), ("nukni", (255, 0, 255)), ("rijyska", (192, 192, 192)), -- Silver ("grusi", (128, 128, 128)), -- ("?", (128, 0, 0)), -- Maroon ("alzaityska", (128, 128, 0)), -- Olive ("crino", (0, 128, 0)), ("zirpu", (128, 0, 128)), -- Purple -- ("?", (0, 128, 128)), -- Teal -- ("?", (0, 0, 128)), -- Navy ("bunre", (165, 42, 42)), -- Brown ("narju", (255, 165, 0)), -- Orange ("sloska", (255, 215, 0)), -- Gold ("xunblabi", (255, 192, 203)) -- Pink ] mezofatcidu :: String -> Int mezofatcidu = fromJust . flip lookup mezofaliste mezofaliste :: [(String, Int)] mezofaliste = [ ("fa", 1), ("fe", 2), ("fi", 3), ("fo", 4), ("fu", 5) ] mezopatcidu :: [String] -> Double mezopatcidu ("ni'u" : pas) = - (pti $ reverse $ processKIhO pas) mezopatcidu pas = pti $ reverse $ processKIhO pas pti :: [String] -> Double pti [] = 0 pti (p : rest) = fromJust (lookup' p mezopaliste) + 10 * pti rest lookup' :: Eq a => a -> [([a], b)] -> Maybe b lookup' _ [] = Nothing lookup' x ((xs, y) : ys) | x `elem` xs = Just y | otherwise = lookup' x ys processKIhO :: [String] -> [String] processKIhO = reverse . pk 3 . reverse where pk _ [] = [] pk n ("ki'o" : rest) = replicate n "no" ++ pk 3 rest pk n (pa : rest) | n > 0 = pa : pk (n - 1) rest | otherwise = pa : pk 2 rest mezopaliste :: [([String], Double)] mezopaliste = [ (["no", "0"], 0), (["pa", "1"], 1), (["re", "2"], 2), (["ci", "3"], 3), (["vo", "4"], 4), (["mu", "5"], 5), (["xa", "6"], 6), (["ze", "7"], 7), (["bi", "8"], 8), (["so", "9"], 9) ] mezosetcidu :: String -> Int mezosetcidu = fromJust . flip lookup mezoseliste mezoseliste :: [(String, Int)] mezoseliste = [ ("se", 2), ("te", 3), ("ve", 4), ("xe", 5) ]
YoshikuniJujo/cakyrespa
src/Liste.hs
bsd-3-clause
2,066
74
11
438
1,157
696
461
69
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Main (main) where import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as Text.IO import Graphics.Blank import qualified Graphics.Blank.Style as Style import Paths_blank_canvas_examples import Prelude.Compat main :: IO () main = do dat <- getDataDir print dat blankCanvas 3000 { events = ["mousedown"] , debug = True , root = dat } $ \ canvas -> do princessURL <- staticURL canvas "type/jpeg" "/images/princess.jpg" fanURL <- staticURL canvas "type/jpeg" "/images/fan.jpg" sequence_ [ -- blank the screeen do send canvas $ do let (w,h) = size canvas clearRect (0,0,w,h) beginPath() globalAlpha 1.0 -- reset this global property -- run this example send canvas $ do save() example $ EC { ecCanvas = canvas , ecPrincessURL = princessURL , ecFanURL = fanURL } send canvas $ do restore() -- draw the watermark in corner send canvas $ message canvas name -- wait for a mouse press wait canvas | (example,name) <- drop 15 $ cycle (map wrap examples ++ io_examples) ] where wrap (example,name) = (\ec -> send (ecCanvas ec) (example ec), name) examples :: [(ExampleContext -> Canvas (), Text)] examples = -- Lines [ (example_1_2_1,"1.2.1 Line") , (example_1_2_2,"1.2.2 Line Width") , (example_1_2_3,"1.2.3 Line Color") , (example_1_2_4,"1.2.4 Line Cap") -- Curves , (example_1_3_1,"1.3.1 Arc") , (example_1_3_2,"1.3.2 Quadratic Curve") , (example_1_3_3,"1.3.3 Bezier Curve") -- Paths , (example_1_4_1,"1.4.1 Path") , (example_1_4_2,"1.4.2 Line Join") , (example_1_4_3,"1.4.3 Rounded Corners") -- Shapes , (example_1_5_1,"1.5.1 Custom Shape") , (example_1_5_2,"1.5.2 Rectangle") , (example_1_5_3,"1.5.3 Circle") , (example_1_5_4,"1.5.4 Semicircle") -- Fill Styles , (example_1_6_1,"1.6.1 Shape Fill") , (example_1_6_2,"1.6.2 Linear Gradient") , (example_1_6_3,"1.6.3 Radial Gradient") , (example_1_6_4,"1.6.4 Pattern") -- Images , (example_1_7_1,"1.7.1 Image") , (example_1_7_2,"1.7.2 Image Size") , (example_1_7_3,"1.7.3 Image Crop") , (example_1_7_4,"1.7.4 Image Loader") -- Text , (example_1_8_1,"1.8.1 Text Font & Size") , (example_1_8_2,"1.8.2 Text Color") , (example_1_8_3,"1.8.3 Text Stroke") , (example_1_8_4,"1.8.4 Text Align") , (example_1_8_5,"1.8.5 Text Baseline") , (example_1_8_6,"1.8.6 Text Metrics") , (example_1_8_7,"1.8.7 Text Wrap") -- Transformations 2.1 , (example_2_1_1,"2.1.1 Translate Transform") -- Composites 2.2 , (example_2_2_1,"2.2.1 Shadow") , (example_2_2_2,"2.2.2 Global Alpha") , (example_2_2_3,"2.2.3 Clipping Region") , (example_2_2_4,"2.2.4 Global Composite Operations") -- Image Data & URLs 2.3 -- , (example_2_3_1,"2.3.1 Image Data") -- , (example_2_3_2,"2.3.2 Invert Image Colors") -- , (example_2_3_3,"2.3.3 Grayscale Image Colors") -- Animation 2.4 -- Mouse Detection 2.5 ] io_examples :: [(ExampleContext -> IO (), Text)] io_examples = [ (example_2_3_4,"2.3.4 Get Image Data URL") , (example_2_3_5,"2.3.5 Load Image Data URL") ] data ExampleContext = EC { ecCanvas :: DeviceContext , ecPrincessURL :: URL , ecFanURL :: URL } -- Examples taken from http://www.html5canvastutorials.com/tutorials/html5-canvas-tutorials-introduction/ {- For example, here is the JavaScript for 1.2.1 moveTo(100, 150); lineTo(450, 50); stroke(); -} example_1_2_1, example_1_2_2, example_1_2_3, example_1_2_4, example_1_3_1, example_1_3_2, example_1_3_3, example_1_4_1, example_1_4_2, example_1_4_3, example_1_5_1, example_1_5_2, example_1_5_3, example_1_5_4, example_1_6_1, example_1_6_2, example_1_6_3, example_1_6_4, example_1_7_1, example_1_7_2, example_1_7_3, example_1_7_4, example_1_8_1, example_1_8_2, example_1_8_3, example_1_8_4, example_1_8_5, example_1_8_6, example_1_8_7, example_2_1_1, example_2_2_1, example_2_2_2, example_2_2_3, example_2_2_4 :: ExampleContext -> Canvas () example_1_2_1 _ = do moveTo(100,150) lineTo(450,50) stroke() example_1_2_2 _ = do moveTo(100,150) lineTo(450,50) lineWidth 15 stroke() example_1_2_3 _ = do moveTo(100,150) lineTo(450,50) lineWidth 5 strokeStyle "#ff0000" stroke() example_1_2_4 EC{ecCanvas = canvas} = do let (w,h) = size canvas sequence_ [ do beginPath() moveTo(200, h / 2 + n) lineTo(w - 200, h / 2 + n) lineWidth 20 strokeStyle "#0000ff" lineCap cap stroke() | (cap,n) <- zip ["butt","round","square"] [-50,0,50] ] example_1_3_1 EC{ecCanvas = canvas} = do let (w,h) = size canvas let centerX = w / 2; let centerY = h / 2; let radius = 75; let startingAngle = 1.1 * pi let endingAngle = 1.9 * pi let counterclockwise = False arc(centerX, centerY, radius, startingAngle, endingAngle, counterclockwise) lineWidth 15 strokeStyle "black" stroke() example_1_3_2 _ = do beginPath() moveTo(188, 150) quadraticCurveTo(288, 0, 388, 150) lineWidth 10 -- line color strokeStyle "black" stroke() example_1_3_3 _ = do beginPath() moveTo(188, 150) bezierCurveTo(140, 10, 388, 10, 388, 170) lineWidth 10 -- line color strokeStyle "black" stroke() example_1_4_1 _ = do beginPath() moveTo(100, 20) -- line 1 lineTo(200, 160) -- quadratic curve quadraticCurveTo(230, 200, 250, 120) -- bezier curve bezierCurveTo(290, -40, 300, 200, 400, 150) -- line 2 lineTo(500, 90) lineWidth 5 strokeStyle "blue" stroke() example_1_4_2 _ = do lineWidth 25; -- miter line join (left) beginPath(); moveTo(99, 150); lineTo(149, 50); lineTo(199, 150); lineJoin "miter"; stroke(); -- round line join (middle) beginPath(); moveTo(239, 150); lineTo(289, 50); lineTo(339, 150); lineJoin "round"; stroke(); -- bevel line join (right) beginPath(); moveTo(379, 150); lineTo(429, 50); lineTo(479, 150); lineJoin "bevel"; stroke(); example_1_4_3 _ = do lineWidth 25; let rectWidth = 200; let rectHeight = 100; let rectX = 189; let rectY = 50; let cornerRadius = 50; beginPath(); moveTo(rectX, rectY); lineTo(rectX + rectWidth - cornerRadius, rectY); arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius, cornerRadius); lineTo(rectX + rectWidth, rectY + rectHeight); lineWidth 5; stroke(); example_1_5_1 _ = do beginPath(); moveTo(170, 80); bezierCurveTo(130, 100, 130, 150, 230, 150); bezierCurveTo(250, 180, 320, 180, 340, 150); bezierCurveTo(420, 150, 420, 120, 390, 100); bezierCurveTo(430, 40, 370, 30, 340, 50); bezierCurveTo(320, 5, 250, 20, 250, 50); bezierCurveTo(200, 5, 150, 20, 170, 80); -- complete custom shape closePath(); lineWidth 5; strokeStyle "blue"; stroke(); example_1_5_2 _ = do beginPath(); rect(188, 50, 200, 100); fillStyle "yellow"; fill(); lineWidth 7; strokeStyle "black"; stroke(); example_1_5_3 EC{ecCanvas = canvas} = do let (w,h) = size canvas let centerX = w / 2 let centerY = h / 2 let radius = 70 beginPath() arc(centerX, centerY, radius, 0, 2 * pi, False) fillStyle "#8ED6FF" fill() lineWidth 5 strokeStyle "black" stroke() example_1_5_4 _ = do beginPath(); arc(288, 75, 70, 0, pi, False); closePath(); lineWidth 5; fillStyle "red"; fill(); strokeStyle "#550000"; stroke(); example_1_6_1 _ = do beginPath(); moveTo(170, 80); bezierCurveTo(130, 100, 130, 150, 230, 150); bezierCurveTo(250, 180, 320, 180, 340, 150); bezierCurveTo(420, 150, 420, 120, 390, 100); bezierCurveTo(430, 40, 370, 30, 340, 50); bezierCurveTo(320, 5, 250, 20, 250, 50); bezierCurveTo(200, 5, 150, 20, 170, 80); -- complete custom shape closePath(); lineWidth 5; fillStyle "#8ED6FF"; fill(); strokeStyle "blue"; stroke(); example_1_6_2 EC{ecCanvas = canvas} = do let (w,h) = size canvas rect(0, 0, w, h) grd <- createLinearGradient(0, 0, w, h) -- light blue grd # addColorStop(0, "#8ED6FF") -- dark blue grd # addColorStop(1, "#004CB3") Style.fillStyle grd; fill(); example_1_6_3 EC{ecCanvas = canvas} = do let (w,h) = size canvas rect(0, 0, w, h) grd <- createRadialGradient (238, 50, 10, 238, 50, 300) -- light blue grd # addColorStop(0, "#8ED6FF") -- dark blue grd # addColorStop(1, "#004CB3") Style.fillStyle grd; fill(); example_1_6_4 EC{ecCanvas = canvas, ecFanURL = fanURL} = do let (w,h) = size canvas imageObj <- newImage fanURL pattern <- createPattern (imageObj,"repeat") rect(0, 0, w, h); Style.fillStyle pattern; fill(); example_1_7_1 EC{ecPrincessURL = princessURL} = do img <- newImage princessURL drawImage(img,[69,50]) example_1_7_2 EC{ecPrincessURL = princessURL} = do img <- newImage princessURL drawImage(img,[69,50,97,129]) example_1_7_3 EC{ecPrincessURL = princessURL} = do img <- newImage princessURL drawImage(img,[400,200,300,400,100,100,150,200]) example_1_7_4 EC{ecPrincessURL = princessURL, ecFanURL = fanURL} = do img1 <- newImage princessURL img2 <- newImage fanURL drawImage(img1,[69,50,97,129]) drawImage(img2,[400,50]) example_1_8_1 _ = do font "40pt Calibri" fillText("Hello World!", 150, 100) example_1_8_2 _ = do font "40pt Calibri" fillStyle "#0000ff" fillText("Hello World!", 150, 100) example_1_8_3 _ = do font "60pt Calibri" lineWidth 3 strokeStyle "blue" strokeText("Hello World!", 80, 110) example_1_8_4 EC{ecCanvas = canvas} = do let (w,h) = size canvas let x = w / 2 let y = h / 2 font "30pt Calibri" textAlign "center" fillStyle "blue" fillText("Hello World!", x, y) example_1_8_5 EC{ecCanvas = canvas} = do let (w,h) = size canvas let x = w / 2 let y = h / 2 font "30pt Calibri" textAlign "center" textBaseline "middle" fillStyle "blue" fillText("Hello World!", x, y) example_1_8_6 EC{ecCanvas = canvas} = do let (w,h) = size canvas let x = w / 2 let y = h / 2 - 10; let text = "Hello World!" font "30pt Calibri" textAlign "center" fillStyle "blue" fillText(text, x, y) TextMetrics w' <- measureText text font "20pt Calibri" textAlign "center" fillStyle "#555" fillText("(" <> Text.pack (show w') <> "px wide)", x, y + 40) example_1_8_7 EC{ecCanvas = canvas} = do let w = width canvas font "lighter 16pt Calibri" fillStyle "#000" let maxWidth = w / 3 wrapText 0 (Text.words message') ((w - maxWidth) / 2) 60 maxWidth 25 where message' = "All the world's a stage, and all the men and women merely players. " <> "They have their exits and their entrances; And one man in his time plays many parts." wrapText _ [] _ _ _ _ = return () wrapText wc text x y maxWidth lineHeight = do TextMetrics testWidth <- measureText $ Text.unwords $ take (wc+1) $ text if (testWidth > maxWidth && wc > 0) || length text <= wc then do fillText(Text.unwords $ take wc $ text,x,y) wrapText 0 (drop wc text) x (y + lineHeight) maxWidth lineHeight else do wrapText (wc+1) text x y maxWidth lineHeight example_2_1_1 EC{ecCanvas = canvas} = do let (w,h) = size canvas let rectWidth = 150; let rectHeight = 75; translate(w / 2, h / 2); fillStyle "blue"; fillRect(rectWidth / (-2), rectHeight / (-2), rectWidth, rectHeight); example_2_2_1 _ = do rect(188, 40, 200, 100); fillStyle "red"; shadowColor "#999"; shadowBlur 20; shadowOffsetX 15; shadowOffsetY 15; fill() example_2_2_2 _ = do -- draw blue rectangle beginPath(); rect(200, 20, 100, 100); fillStyle "blue"; fill(); -- draw transparent red circle globalAlpha 0.5; beginPath(); arc(320, 120, 60, 0, 2 * pi, False); fillStyle "red"; fill(); example_2_2_3 EC{ecCanvas = canvas} = do let (w,h) = size canvas let x = w / 2; let y = h / 2; let radius = 75; let offset = 50; {- * save() allows us to save the canvas context before * defining the clipping region so that we can return * to the default state later on -} save(); beginPath(); arc(x, y, radius, 0, 2 * pi, False); clip(); -- draw blue circle inside clipping region beginPath(); arc(x - offset, y - offset, radius, 0, 2 * pi, False); fillStyle "blue"; fill(); -- draw yellow circle inside clipping region beginPath(); arc(x + offset, y, radius, 0, 2 * pi, False); fillStyle "yellow"; fill(); -- draw red circle inside clipping region beginPath(); arc(x, y + offset, radius, 0, 2 * pi, False); fillStyle "red"; fill(); {- * restore() restores the canvas context to its original state * before we defined the clipping region -} restore(); beginPath(); arc(x, y, radius, 0, 2 * pi, False); lineWidth 10; strokeStyle "blue"; stroke(); example_2_2_4 EC{ecCanvas = canvas} = do let (w,h) = size canvas :: (Double, Double) tempCanvas <- newCanvas (round w,round h) console_log tempCanvas let (w',h') = size tempCanvas console_log $ Text.pack $ show $ (w',h') sync let squareWidth = 55; let circleRadius = 35; let shapeOffset = 50; -- let operationOffset = 150; let compss = [["source-atop", "source-in", "source-out", "source-over"] ,["destination-atop","destination-in","destination-out","destination-over"] ,["lighter","darker","xor","copy"] ] -- translate context to add 10px padding translate(10, 10); sequence_ [ do -- clear temp context with tempCanvas $ do save(); clearRect(0, 0, w', h'); -- draw rectangle (destination) beginPath(); rect(0, 0, squareWidth, squareWidth); fillStyle "blue"; fill(); -- set global composite globalCompositeOperation thisOperation; -- draw circle (source) beginPath(); arc(shapeOffset, shapeOffset, circleRadius, 0, 2 * pi, False); fillStyle "red"; fill(); restore(); font "10pt Verdana"; fillStyle "black"; fillText(thisOperation, 0, squareWidth + 45); drawImage(tempCanvas, [x * 125, y * 125]); | (comps,y) <- compss `zip` [0..] , (thisOperation,x) <- comps `zip` [0..] ] example_2_3_4, example_2_3_5 :: ExampleContext -> IO () example_2_3_4 EC{ecCanvas = canvas} = do url <- send canvas $ do beginPath(); moveTo(170, 80); bezierCurveTo(130, 100, 130, 150, 230, 150); bezierCurveTo(250, 180, 320, 180, 340, 150); bezierCurveTo(420, 150, 420, 120, 390, 100); bezierCurveTo(430, 40, 370, 30, 340, 50); bezierCurveTo(320, 5, 250, 20, 250, 50); bezierCurveTo(200, 5, 150, 20, 170, 80); -- complete custom shape closePath(); lineWidth 5; strokeStyle "blue"; stroke(); toDataURL(); send canvas $ do font "18pt Calibri" fillText(Text.pack $ show $ Text.take 50 $ url, 10, 300) example_2_3_5 EC{ecCanvas = canvas} = do fileName <- getDataFileName "static/data/dataURL.txt" url <- Text.IO.readFile fileName send canvas $ do img <- newImage (URL url) drawImage (img,[0,0]) -- example_last :: Canvas () -- example_last = do -- todo -- marker for the scanning sof the examples --------------------------------------------------------------------------- -- todo :: Canvas () -- todo = do -- font "40pt Calibri" -- fillText("(TODO)", 150, 100) -- Small "watermark-like text in the bottom corner" message :: DeviceContext -> Text -> Canvas () message canvas msg = do save() let h = height canvas font "30pt Calibri" textAlign "left" fillStyle "#8090a0" fillText(msg, 10, h - 10) restore() size :: (Image image, Num a, Num b) => image -> (a, b) size image = (width image, height image)
ku-fpg/blank-canvas
examples/html5canvastutorial/Main.hs
bsd-3-clause
18,901
0
21
6,563
5,879
3,082
2,797
464
3
{-# LANGUAGE FlexibleContexts #-} module Hrpg.Framework.Combat.EncounterData ( EncounterData (..) , doPlayerAction , doMobAction , getMob , getPlayer , updateMob , updatePlayer ) where import Control.Monad.State import Control.Monad.Random import Hrpg.Framework.Combat.CombatAction import Hrpg.Framework.Combat.CombatData import Hrpg.Framework.Combat.CombatResult import Hrpg.Framework.Combat.Dmg import Hrpg.Framework.Combat.MeleeAttack import Hrpg.Framework.Player import Hrpg.Framework.Mobs.Mob data EncounterData = EncounterData { player :: Player , mob :: Mob } deriving Show getMob :: MonadState EncounterData m => m Mob getMob = do e <- get return (mob e) getPlayer :: MonadState EncounterData m => m Player getPlayer = do e <- get return (player e) getPlayerCombatData :: MonadState EncounterData m => m CombatData getPlayerCombatData = do p <- getPlayer return (playerCombatData p) getMobCombatData :: MonadState EncounterData m => m CombatData getMobCombatData = do m <- getMob return (mobCombatData m) reduceMobHp :: MonadState EncounterData m => Int -> m () reduceMobHp x = do e <- get m <- getMob let hp = mobCurrentHp m let m' = m { mobCurrentHp = hp - x } put e { mob = m' } return () reducePlayerHp :: MonadState EncounterData m => Int -> m () reducePlayerHp x = do e <- get p <- getPlayer let hp = playerCurrentHp p let p' = p { playerCurrentHp = hp - x } put e { player = p' } return () updatePlayer :: MonadState EncounterData m => CombatResult -> m () updatePlayer (MeleeHit (Dmg x)) = reducePlayerHp x updatePlayer (MeleeCrit (Dmg x)) = reducePlayerHp x updatePlayer _ = return () updateMob :: MonadState EncounterData m => CombatResult -> m () updateMob (MeleeHit (Dmg x)) = reduceMobHp x updateMob (MeleeCrit (Dmg x)) = reduceMobHp x updateMob _ = return () doAction :: MonadRandom m => CombatAction -> CombatData -> CombatData -> m CombatResult doAction MeleeAttack attacker defender = meleeAttack attacker defender doPlayerAction :: (MonadState EncounterData m, MonadRandom m) => CombatAction -> m CombatResult doPlayerAction action = do attacker <- getPlayerCombatData defender <- getMobCombatData doAction action attacker defender doMobAction :: (MonadState EncounterData m, MonadRandom m) => CombatAction -> m CombatResult doMobAction action = do attacker <- getMobCombatData defender <- getPlayerCombatData doAction action attacker defender
cwmunn/hrpg
src/Hrpg/Framework/Combat/EncounterData.hs
bsd-3-clause
2,542
0
12
517
814
409
405
74
1
module Transformer.SymbolicExecution where import Control.Monad (when) import Printer.Dot import Printer.SymTree () import SymbolicExecution (topLevel) import System.Directory import System.FilePath ((</>)) import System.Process (system) import Text.Printf transform n filename goal = do let tree = (topLevel n) goal let path = "test/out/sym" </> filename exists <- doesDirectoryExist path when exists (removeDirectoryRecursive path) createDirectoryIfMissing True path printTree (path </> "tree.dot") tree system (printf "dot -O -Tpdf %s/*.dot" path) return ()
kajigor/uKanren_transformations
src/Transformer/SymbolicExecution.hs
bsd-3-clause
670
0
12
176
181
92
89
18
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} -- | Bindings to the Docker Registry API. If you want more control on the -- exact data passed to the server, use `Network.Docker.Registry.Internal`. module Network.Docker.Registry where import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as LC import Data.Digest.Pure.SHA (showDigest, sha256) import Data.List (intersperse) import System.IO.Streams.SHA import qualified System.IO.Streams as Streams import Network.Docker.Registry.Internal import Network.Docker.Registry.Types ---------------------------------------------------------------------- -- Repositories ---------------------------------------------------------------------- pushRepository :: Repository -> IO Int pushRepository r@Repository{..} = let json = repositoryJson r in putRepository repositoryCredentials repositoryHost repositoryNamespace repositoryName json pushRepositoryTag :: Repository -> Image -> Tag -> IO Int pushRepositoryTag Repository{..} Image{..} tag = putRepositoryTag repositoryCredentials repositoryHost repositoryNamespace repositoryName tag imageName ---------------------------------------------------------------------- -- Images ---------------------------------------------------------------------- pushImageJson :: Repository -> Image -> IO Int pushImageJson Repository{..} Image{..} = putImageJson repositoryCredentials repositoryHost imageName imageJson pullImageJson :: Repository -> Image -> IO (Int, ByteString) pullImageJson Repository{..} Image{..} = getImageJson repositoryCredentials repositoryHost imageName pushImageLayer :: Repository -> Image -> IO Int pushImageLayer Repository{..} Image{..} = putImageLayer repositoryCredentials repositoryHost imageName imageLayer pushImageChecksum :: Repository -> Image -> IO Int pushImageChecksum Repository{..} i@Image{..} = do -- TODO Compute the checksum when the layer is uploaded, and cache it -- to re-use it here. checksum <- imageChecksum i putImageChecksum repositoryCredentials repositoryHost imageName checksum ---------------------------------------------------------------------- -- Helpers ---------------------------------------------------------------------- repositoryJson :: Repository -> LC.ByteString repositoryJson Repository{..} = LB.fromChunks $ "[" : (concat . (intersperse [","]) . map (\i -> ["{\"id\":\"", imageName $ fst i, "\"}"])) repositoryImages ++ ["]"] imageChecksum :: Image -> IO LC.ByteString imageChecksum i = do digest256 <- imageLayer i (\is -> do j <- Streams.fromLazyByteString $ imageJson i `LB.append` "\n" is' <- Streams.appendInputStream j is (is'', getSha256) <- sha256Input is' Streams.skipToEof is'' getSha256) return $ "sha256:" `LB.append` (LC.pack $ showDigest digest256) -- The checksum used by Docker depends on the exact string representation of -- JSON meta-data...
noteed/rescoyl-checks
Network/Docker/Registry.hs
bsd-3-clause
2,993
0
16
388
653
351
302
49
1
{-# LANGUAGE OverloadedStrings #-} module PeerReview.SubmissionRepo.FPCourseSpec ( main , spec ) where import Test.Hspec import PeerReview.Config import qualified PeerReview.SubmissionRepo.FPCourse as FPCourse import qualified PeerReview.SubmissionRepo.FPCourseMockAPIClient as FPCourseMockAPIClient import PeerReview.Types main :: IO () main = hspec spec spec :: Spec spec = do describe ".listAll" $ it "parses all submissions from test data" $ do r <- repo allRepos <- srAll r length allRepos `shouldBe` 6 describe ".forTask" $ it "filters submissions by task name" $ do r <- repo let taskID = "SimpleTypeDrivenExercise" subsByTask <- srFindByTaskId r taskID length subsByTask `shouldBe` 2 describe ".forUser" $ it "filters submissions by user email" $ do r <- repo let userID = "mikko@cc.jyu.fi" subsByUser <- srFindByUserId r userID length subsByUser `shouldBe` 3 describe ".byId" $ it "parses submission data correctly" $ do r <- repo let subId = "sha1" expect = Just $ SubmissionDetails "sha1" "SimpleTypeDrivenExercise" ["mikko@cc.jyu.fi"] "Submission Content" submission <- srFindById r subId submission `shouldBe` expect repo :: IO SubmissionRepo repo = do let client = FPCourseMockAPIClient.client FPCourse.repoWithClient client <$> readSubmissionRepoConfig "test/fixtures/config/submission_repo.json"
keveri/peer-review-service
test/PeerReview/SubmissionRepo/FPCourseSpec.hs
bsd-3-clause
1,625
0
15
483
351
172
179
46
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} -- | Module providing the basic types for image manipulation in the library. -- Defining the types used to store all those _Juicy Pixels_ module Codec.Picture.Types( -- * Types -- ** Image types Image( .. ) , MutableImage( .. ) , DynamicImage( .. ) , Palette -- ** Image functions , createMutableImage , newMutableImage , freezeImage , unsafeFreezeImage , thawImage , unsafeThawImage -- ** Image Lenses , Traversal , imagePixels , imageIPixels -- ** Pixel types , Pixel8 , Pixel16 , Pixel32 , PixelF , PixelYA8( .. ) , PixelYA16( .. ) , PixelRGB8( .. ) , PixelRGB16( .. ) , PixelRGBF( .. ) , PixelRGBA8( .. ) , PixelRGBA16( .. ) , PixelCMYK8( .. ) , PixelCMYK16( .. ) , PixelYCbCr8( .. ) , PixelYCbCrK8( .. ) -- * Type classes , ColorConvertible( .. ) , Pixel(..) -- $graph , ColorSpaceConvertible( .. ) , LumaPlaneExtractable( .. ) , TransparentPixel( .. ) -- * Helper functions , pixelMap , pixelMapXY , pixelFold , pixelFoldM , pixelFoldMap , dynamicMap , dynamicPixelMap , dropAlphaLayer , withImage , zipPixelComponent3 , generateImage , generateFoldImage , gammaCorrection , toneMapping -- * Color plane extraction , ColorPlane ( ) , PlaneRed( .. ) , PlaneGreen( .. ) , PlaneBlue( .. ) , PlaneAlpha( .. ) , PlaneLuma( .. ) , PlaneCr( .. ) , PlaneCb( .. ) , PlaneCyan( .. ) , PlaneMagenta( .. ) , PlaneYellow( .. ) , PlaneBlack( .. ) , extractComponent , unsafeExtractComponent -- * Packeable writing (unsafe but faster) , PackeablePixel( .. ) , fillImageWith , readPackedPixelAt , writePackedPixelAt , unsafeWritePixelBetweenAt ) where #if !MIN_VERSION_base(4,8,0) import Data.Monoid( Monoid, mempty ) import Control.Applicative( Applicative, pure, (<*>), (<$>) ) #endif import Data.Monoid( (<>) ) import Control.Monad( foldM, liftM, ap ) import Control.DeepSeq( NFData( .. ) ) import Control.Monad.ST( ST, runST ) import Control.Monad.Primitive ( PrimMonad, PrimState ) import Foreign.ForeignPtr( castForeignPtr ) import Foreign.Storable ( Storable ) import Data.Bits( unsafeShiftL, unsafeShiftR, (.|.), (.&.) ) import Data.Word( Word8, Word16, Word32, Word64 ) import Data.Vector.Storable ( (!) ) import qualified Data.Vector.Storable as V import qualified Data.Vector.Storable.Mutable as M #include "ConvGraph.hs" -- | The main type of this package, one that most -- functions work on, is Image. -- -- Parameterized by the underlying pixel format it -- forms a rigid type. If you wish to store images -- of different or unknown pixel formats use 'DynamicImage'. -- -- Image is essentially a rectangular pixel buffer -- of specified width and height. The coordinates are -- assumed to start from the upper-left corner -- of the image, with the horizontal position first -- and vertical second. data Image a = Image { -- | Width of the image in pixels imageWidth :: {-# UNPACK #-} !Int -- | Height of the image in pixels. , imageHeight :: {-# UNPACK #-} !Int -- | Image pixel data. To extract pixels at a given position -- you should use the helper functions. -- -- Internally pixel data is stored as consecutively packed -- lines from top to bottom, scanned from left to right -- within individual lines, from first to last color -- component within each pixel. , imageData :: V.Vector (PixelBaseComponent a) } -- | Type for the palette used in Gif & PNG files. type Palette = Image PixelRGB8 -- | Class used to describle plane present in the pixel -- type. If a pixel has a plane description associated, -- you can use the plane name to extract planes independently. class ColorPlane pixel planeToken where -- | Retrieve the index of the component in the -- given pixel type. toComponentIndex :: pixel -> planeToken -> Int -- | Define the plane for the red color component data PlaneRed = PlaneRed -- | Define the plane for the green color component data PlaneGreen = PlaneGreen -- | Define the plane for the blue color component data PlaneBlue = PlaneBlue -- | Define the plane for the alpha (transparency) component data PlaneAlpha = PlaneAlpha -- | Define the plane for the luma component data PlaneLuma = PlaneLuma -- | Define the plane for the Cr component data PlaneCr = PlaneCr -- | Define the plane for the Cb component data PlaneCb = PlaneCb -- | Define plane for the cyan component of the -- CMYK color space. data PlaneCyan = PlaneCyan -- | Define plane for the magenta component of the -- CMYK color space. data PlaneMagenta = PlaneMagenta -- | Define plane for the yellow component of the -- CMYK color space. data PlaneYellow = PlaneYellow -- | Define plane for the black component of -- the CMYK color space. data PlaneBlack = PlaneBlack -- | Extract a color plane from an image given a present plane in the image -- examples: -- -- @ -- extractRedPlane :: Image PixelRGB8 -> Image Pixel8 -- extractRedPlane = extractComponent PlaneRed -- @ -- extractComponent :: forall px plane. ( Pixel px , Pixel (PixelBaseComponent px) , PixelBaseComponent (PixelBaseComponent px) ~ PixelBaseComponent px , ColorPlane px plane ) => plane -> Image px -> Image (PixelBaseComponent px) extractComponent plane = unsafeExtractComponent idx where idx = toComponentIndex (undefined :: px) plane -- | Extract a plane of an image. Returns the requested color -- component as a greyscale image. -- -- If you ask for a component out of bound, the `error` function will -- be called. unsafeExtractComponent :: forall a . ( Pixel a , Pixel (PixelBaseComponent a) , PixelBaseComponent (PixelBaseComponent a) ~ PixelBaseComponent a) => Int -- ^ The component index, beginning at 0 ending at (componentCount - 1) -> Image a -- ^ Source image -> Image (PixelBaseComponent a) unsafeExtractComponent comp img@(Image { imageWidth = w, imageHeight = h }) | comp >= padd = error $ "extractComponent : invalid component index (" ++ show comp ++ ", max:" ++ show padd ++ ")" | otherwise = Image { imageWidth = w, imageHeight = h, imageData = plane } where plane = stride img padd comp padd = componentCount (undefined :: a) -- | For any image with an alpha component (transparency), -- drop it, returning a pure opaque image. dropAlphaLayer :: (TransparentPixel a b) => Image a -> Image b dropAlphaLayer = pixelMap dropTransparency -- | Class modeling transparent pixel, should provide a method -- to combine transparent pixels class (Pixel a, Pixel b) => TransparentPixel a b | a -> b where -- | Just return the opaque pixel value dropTransparency :: a -> b -- | access the transparency (alpha layer) of a given -- transparent pixel type. getTransparency :: a -> PixelBaseComponent a {-# DEPRECATED getTransparency "please use 'pixelOpacity' instead" #-} instance TransparentPixel PixelRGBA8 PixelRGB8 where {-# INLINE dropTransparency #-} dropTransparency (PixelRGBA8 r g b _) = PixelRGB8 r g b {-# INLINE getTransparency #-} getTransparency (PixelRGBA8 _ _ _ a) = a lineFold :: (Monad m) => a -> Int -> (a -> Int -> m a) -> m a {-# INLINE lineFold #-} lineFold initial count f = go 0 initial where go n acc | n >= count = return acc go n acc = f acc n >>= go (n + 1) stride :: (Storable (PixelBaseComponent a)) => Image a -> Int -> Int -> V.Vector (PixelBaseComponent a) stride Image { imageWidth = w, imageHeight = h, imageData = array } padd firstComponent = runST $ do let cell_count = w * h outArray <- M.new cell_count let go writeIndex _ | writeIndex >= cell_count = return () go writeIndex readIndex = do (outArray `M.unsafeWrite` writeIndex) $ array `V.unsafeIndex` readIndex go (writeIndex + 1) $ readIndex + padd go 0 firstComponent V.unsafeFreeze outArray instance NFData (Image a) where rnf (Image width height dat) = width `seq` height `seq` dat `seq` () -- | Image or pixel buffer, the coordinates are assumed to start -- from the upper-left corner of the image, with the horizontal -- position first, then the vertical one. The image can be transformed in place. data MutableImage s a = MutableImage { -- | Width of the image in pixels mutableImageWidth :: {-# UNPACK #-} !Int -- | Height of the image in pixels. , mutableImageHeight :: {-# UNPACK #-} !Int -- | The real image, to extract pixels at some position -- you should use the helpers functions. , mutableImageData :: M.STVector s (PixelBaseComponent a) } -- | `O(n)` Yield an immutable copy of an image by making a copy of it freezeImage :: (Storable (PixelBaseComponent px), PrimMonad m) => MutableImage (PrimState m) px -> m (Image px) freezeImage (MutableImage w h d) = Image w h `liftM` V.freeze d -- | `O(n)` Yield a mutable copy of an image by making a copy of it. thawImage :: (Storable (PixelBaseComponent px), PrimMonad m) => Image px -> m (MutableImage (PrimState m) px) thawImage (Image w h d) = MutableImage w h `liftM` V.thaw d -- | `O(1)` Unsafe convert an imutable image to an mutable one without copying. -- The source image shouldn't be used after this operation. unsafeThawImage :: (Storable (PixelBaseComponent px), PrimMonad m) => Image px -> m (MutableImage (PrimState m) px) {-# NOINLINE unsafeThawImage #-} unsafeThawImage (Image w h d) = MutableImage w h `liftM` V.unsafeThaw d -- | `O(1)` Unsafe convert a mutable image to an immutable one without copying. -- The mutable image may not be used after this operation. unsafeFreezeImage :: (Storable (PixelBaseComponent a), PrimMonad m) => MutableImage (PrimState m) a -> m (Image a) unsafeFreezeImage (MutableImage w h d) = Image w h `liftM` V.unsafeFreeze d -- | Create a mutable image, filled with the given background color. createMutableImage :: (Pixel px, PrimMonad m) => Int -- ^ Width -> Int -- ^ Height -> px -- ^ Background color -> m (MutableImage (PrimState m) px) createMutableImage width height background = generateMutableImage (\_ _ -> background) width height -- | Create a mutable image with garbage as content. All data -- is uninitialized. newMutableImage :: forall px m. (Pixel px, PrimMonad m) => Int -- ^ Width -> Int -- ^ Height -> m (MutableImage (PrimState m) px) newMutableImage w h = MutableImage w h `liftM` M.new (w * h * compCount) where compCount = componentCount (undefined :: px) instance NFData (MutableImage s a) where rnf (MutableImage width height dat) = width `seq` height `seq` dat `seq` () -- | Image type enumerating all predefined pixel types. -- It enables loading and use of images of different -- pixel types. data DynamicImage = -- | A greyscale image. ImageY8 (Image Pixel8) -- | A greyscale image with 16bit components | ImageY16 (Image Pixel16) -- | A greyscale HDR image | ImageYF (Image PixelF) -- | An image in greyscale with an alpha channel. | ImageYA8 (Image PixelYA8) -- | An image in greyscale with alpha channel on 16 bits. | ImageYA16 (Image PixelYA16) -- | An image in true color. | ImageRGB8 (Image PixelRGB8) -- | An image in true color with 16bit depth. | ImageRGB16 (Image PixelRGB16) -- | An image with HDR pixels | ImageRGBF (Image PixelRGBF) -- | An image in true color and an alpha channel. | ImageRGBA8 (Image PixelRGBA8) -- | A true color image with alpha on 16 bits. | ImageRGBA16 (Image PixelRGBA16) -- | An image in the colorspace used by Jpeg images. | ImageYCbCr8 (Image PixelYCbCr8) -- | An image in the colorspace CMYK | ImageCMYK8 (Image PixelCMYK8) -- | An image in the colorspace CMYK and 16 bits precision | ImageCMYK16 (Image PixelCMYK16) -- | Helper function to help extract information from dynamic -- image. To get the width of a dynamic image, you can use -- the following snippet: -- -- > dynWidth :: DynamicImage -> Int -- > dynWidth img = dynamicMap imageWidth img -- dynamicMap :: (forall pixel . (Pixel pixel) => Image pixel -> a) -> DynamicImage -> a dynamicMap f (ImageY8 i) = f i dynamicMap f (ImageY16 i) = f i dynamicMap f (ImageYF i) = f i dynamicMap f (ImageYA8 i) = f i dynamicMap f (ImageYA16 i) = f i dynamicMap f (ImageRGB8 i) = f i dynamicMap f (ImageRGB16 i) = f i dynamicMap f (ImageRGBF i) = f i dynamicMap f (ImageRGBA8 i) = f i dynamicMap f (ImageRGBA16 i) = f i dynamicMap f (ImageYCbCr8 i) = f i dynamicMap f (ImageCMYK8 i) = f i dynamicMap f (ImageCMYK16 i) = f i -- | Equivalent of the `pixelMap` function for the dynamic images. -- You can perform pixel colorspace independant operations with this -- function. -- -- For instance, if you want to extract a square crop of any image, -- without caring about colorspace, you can use the following snippet. -- -- > dynSquare :: DynamicImage -> DynamicImage -- > dynSquare = dynamicPixelMap squareImage -- > -- > squareImage :: Pixel a => Image a -> Image a -- > squareImage img = generateImage (\x y -> pixelAt img x y) edge edge -- > where edge = min (imageWidth img) (imageHeight img) -- dynamicPixelMap :: (forall pixel . (Pixel pixel) => Image pixel -> Image pixel) -> DynamicImage -> DynamicImage dynamicPixelMap f = aux where aux (ImageY8 i) = ImageY8 (f i) aux (ImageY16 i) = ImageY16 (f i) aux (ImageYF i) = ImageYF (f i) aux (ImageYA8 i) = ImageYA8 (f i) aux (ImageYA16 i) = ImageYA16 (f i) aux (ImageRGB8 i) = ImageRGB8 (f i) aux (ImageRGB16 i) = ImageRGB16 (f i) aux (ImageRGBF i) = ImageRGBF (f i) aux (ImageRGBA8 i) = ImageRGBA8 (f i) aux (ImageRGBA16 i) = ImageRGBA16 (f i) aux (ImageYCbCr8 i) = ImageYCbCr8 (f i) aux (ImageCMYK8 i) = ImageCMYK8 (f i) aux (ImageCMYK16 i) = ImageCMYK16 (f i) instance NFData DynamicImage where rnf (ImageY8 img) = rnf img rnf (ImageY16 img) = rnf img rnf (ImageYF img) = rnf img rnf (ImageYA8 img) = rnf img rnf (ImageYA16 img) = rnf img rnf (ImageRGB8 img) = rnf img rnf (ImageRGB16 img) = rnf img rnf (ImageRGBF img) = rnf img rnf (ImageRGBA8 img) = rnf img rnf (ImageRGBA16 img) = rnf img rnf (ImageYCbCr8 img) = rnf img rnf (ImageCMYK8 img) = rnf img rnf (ImageCMYK16 img) = rnf img -- | Type alias for 8bit greyscale pixels. For simplicity, -- greyscale pixels use plain numbers instead of a separate type. type Pixel8 = Word8 -- | Type alias for 16bit greyscale pixels. type Pixel16 = Word16 -- | Type alias for 32bit greyscale pixels. type Pixel32 = Word32 -- | Type alias for 32bit floating point greyscale pixels. The standard -- bounded value range is mapped to the closed interval [0,1] i.e. -- -- > map promotePixel [0, 1 .. 255 :: Pixel8] == [0/255, 1/255 .. 1.0 :: PixelF] type PixelF = Float -- | Pixel type storing 8bit Luminance (Y) and alpha (A) information. -- Values are stored in the following order: -- -- * Luminance -- -- * Alpha -- data PixelYA8 = PixelYA8 {-# UNPACK #-} !Pixel8 -- Luminance {-# UNPACK #-} !Pixel8 -- Alpha value deriving (Eq, Ord, Show) -- | Pixel type storing 16bit Luminance (Y) and alpha (A) information. -- Values are stored in the following order: -- -- * Luminance -- -- * Alpha -- data PixelYA16 = PixelYA16 {-# UNPACK #-} !Pixel16 -- Luminance {-# UNPACK #-} !Pixel16 -- Alpha value deriving (Eq, Ord, Show) -- | Classic pixel type storing 8bit red, green and blue (RGB) information. -- Values are stored in the following order: -- -- * Red -- -- * Green -- -- * Blue -- data PixelRGB8 = PixelRGB8 {-# UNPACK #-} !Pixel8 -- Red {-# UNPACK #-} !Pixel8 -- Green {-# UNPACK #-} !Pixel8 -- Blue deriving (Eq, Ord, Show) -- | Pixel type storing value for the YCCK color space: -- -- * Y (Luminance) -- -- * Cb -- -- * Cr -- -- * Black -- data PixelYCbCrK8 = PixelYCbCrK8 {-# UNPACK #-} !Pixel8 {-# UNPACK #-} !Pixel8 {-# UNPACK #-} !Pixel8 {-# UNPACK #-} !Pixel8 deriving (Eq, Ord, Show) -- | Pixel type storing 16bit red, green and blue (RGB) information. -- Values are stored in the following order: -- -- * Red -- -- * Green -- -- * Blue -- data PixelRGB16 = PixelRGB16 {-# UNPACK #-} !Pixel16 -- Red {-# UNPACK #-} !Pixel16 -- Green {-# UNPACK #-} !Pixel16 -- Blue deriving (Eq, Ord, Show) -- | HDR pixel type storing floating point 32bit red, green and blue (RGB) information. -- Same value range and comments apply as for 'PixelF'. -- Values are stored in the following order: -- -- * Red -- -- * Green -- -- * Blue -- data PixelRGBF = PixelRGBF {-# UNPACK #-} !PixelF -- Red {-# UNPACK #-} !PixelF -- Green {-# UNPACK #-} !PixelF -- Blue deriving (Eq, Ord, Show) -- | Pixel type storing 8bit luminance, blue difference and red difference (YCbCr) information. -- Values are stored in the following order: -- -- * Y (luminance) -- -- * Cb -- -- * Cr -- data PixelYCbCr8 = PixelYCbCr8 {-# UNPACK #-} !Pixel8 -- Y luminance {-# UNPACK #-} !Pixel8 -- Cb blue difference {-# UNPACK #-} !Pixel8 -- Cr red difference deriving (Eq, Ord, Show) -- | Pixel type storing 8bit cyan, magenta, yellow and black (CMYK) information. -- Values are stored in the following order: -- -- * Cyan -- -- * Magenta -- -- * Yellow -- -- * Black -- data PixelCMYK8 = PixelCMYK8 {-# UNPACK #-} !Pixel8 -- Cyan {-# UNPACK #-} !Pixel8 -- Magenta {-# UNPACK #-} !Pixel8 -- Yellow {-# UNPACK #-} !Pixel8 -- Black deriving (Eq, Ord, Show) -- | Pixel type storing 16bit cyan, magenta, yellow and black (CMYK) information. -- Values are stored in the following order: -- -- * Cyan -- -- * Magenta -- -- * Yellow -- -- * Black -- data PixelCMYK16 = PixelCMYK16 {-# UNPACK #-} !Pixel16 -- Cyan {-# UNPACK #-} !Pixel16 -- Magenta {-# UNPACK #-} !Pixel16 -- Yellow {-# UNPACK #-} !Pixel16 -- Black deriving (Eq, Ord, Show) -- | Classical pixel type storing 8bit red, green, blue and alpha (RGBA) information. -- Values are stored in the following order: -- -- * Red -- -- * Green -- -- * Blue -- -- * Alpha -- data PixelRGBA8 = PixelRGBA8 {-# UNPACK #-} !Pixel8 -- Red {-# UNPACK #-} !Pixel8 -- Green {-# UNPACK #-} !Pixel8 -- Blue {-# UNPACK #-} !Pixel8 -- Alpha deriving (Eq, Ord, Show) -- | Pixel type storing 16bit red, green, blue and alpha (RGBA) information. -- Values are stored in the following order: -- -- * Red -- -- * Green -- -- * Blue -- -- * Alpha -- data PixelRGBA16 = PixelRGBA16 {-# UNPACK #-} !Pixel16 -- Red {-# UNPACK #-} !Pixel16 -- Green {-# UNPACK #-} !Pixel16 -- Blue {-# UNPACK #-} !Pixel16 -- Alpha deriving (Eq, Ord, Show) -- | Definition of pixels used in images. Each pixel has a color space, and a representative -- component (Word8 or Float). class ( Storable (PixelBaseComponent a) , Num (PixelBaseComponent a), Eq a ) => Pixel a where -- | Type of the pixel component, "classical" images -- would have Word8 type as their PixelBaseComponent, -- HDR image would have Float for instance type PixelBaseComponent a :: * -- | Call the function for every component of the pixels. -- For example for RGB pixels mixWith is declared like this: -- -- > mixWith f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) = -- > PixelRGB8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) -- mixWith :: (Int -> PixelBaseComponent a -> PixelBaseComponent a -> PixelBaseComponent a) -> a -> a -> a -- | Extension of the `mixWith` which separate the treatment -- of the color components of the alpha value (transparency component). -- For pixel without alpha components, it is equivalent to mixWith. -- -- > mixWithAlpha f fa (PixelRGBA8 ra ga ba aa) (PixelRGB8 rb gb bb ab) = -- > PixelRGBA8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (fa aa ab) -- mixWithAlpha :: (Int -> PixelBaseComponent a -> PixelBaseComponent a -> PixelBaseComponent a) -- ^ Function for color component -> (PixelBaseComponent a -> PixelBaseComponent a -> PixelBaseComponent a) -- ^ Function for alpha component -> a -> a -> a {-# INLINE mixWithAlpha #-} mixWithAlpha f _ = mixWith f -- | Return the opacity of a pixel, if the pixel has an -- alpha layer, return the alpha value. If the pixel -- doesn't have an alpha value, return a value -- representing the opaqueness. pixelOpacity :: a -> PixelBaseComponent a -- | Return the number of components of the pixel componentCount :: a -> Int -- | Apply a function to each component of a pixel. -- If the color type possess an alpha (transparency channel), -- it is treated like the other color components. colorMap :: (PixelBaseComponent a -> PixelBaseComponent a) -> a -> a -- | Calculate the index for the begining of the pixel pixelBaseIndex :: Image a -> Int -> Int -> Int pixelBaseIndex (Image { imageWidth = w }) x y = (x + y * w) * componentCount (undefined :: a) -- | Calculate theindex for the begining of the pixel at position x y mutablePixelBaseIndex :: MutableImage s a -> Int -> Int -> Int mutablePixelBaseIndex (MutableImage { mutableImageWidth = w }) x y = (x + y * w) * componentCount (undefined :: a) -- | Extract a pixel at a given position, (x, y), the origin -- is assumed to be at the corner top left, positive y to the -- bottom of the image pixelAt :: Image a -> Int -> Int -> a -- | Same as pixelAt but for mutable images. readPixel :: PrimMonad m => MutableImage (PrimState m) a -> Int -> Int -> m a -- | Write a pixel in a mutable image at position x y writePixel :: PrimMonad m => MutableImage (PrimState m) a -> Int -> Int -> a -> m () -- | Unsafe version of pixelAt, read a pixel at the given -- index without bound checking (if possible). -- The index is expressed in number (PixelBaseComponent a) unsafePixelAt :: V.Vector (PixelBaseComponent a) -> Int -> a -- | Unsafe version of readPixel, read a pixel at the given -- position without bound checking (if possible). The index -- is expressed in number (PixelBaseComponent a) unsafeReadPixel :: PrimMonad m => M.STVector (PrimState m) (PixelBaseComponent a) -> Int -> m a -- | Unsafe version of writePixel, write a pixel at the -- given position without bound checking. This can be _really_ unsafe. -- The index is expressed in number (PixelBaseComponent a) unsafeWritePixel :: PrimMonad m => M.STVector (PrimState m) (PixelBaseComponent a) -> Int -> a -> m () -- | Implement upcasting for pixel types. -- Minimal declaration of `promotePixel`. -- It is strongly recommended to overload promoteImage to keep -- performance acceptable class (Pixel a, Pixel b) => ColorConvertible a b where -- | Convert a pixel type to another pixel type. This -- operation should never lose any data. promotePixel :: a -> b -- | Change the underlying pixel type of an image by performing a full copy -- of it. promoteImage :: Image a -> Image b promoteImage = pixelMap promotePixel -- | This class abstract colorspace conversion. This -- conversion can be lossy, which ColorConvertible cannot class (Pixel a, Pixel b) => ColorSpaceConvertible a b where -- | Pass a pixel from a colorspace (say RGB) to the second one -- (say YCbCr) convertPixel :: a -> b -- | Helper function to convert a whole image by taking a -- copy it. convertImage :: Image a -> Image b convertImage = pixelMap convertPixel generateMutableImage :: forall m px. (Pixel px, PrimMonad m) => (Int -> Int -> px) -- ^ Generating function, with `x` and `y` params. -> Int -- ^ Width in pixels -> Int -- ^ Height in pixels -> m (MutableImage (PrimState m) px) {-# INLINE generateMutableImage #-} generateMutableImage f w h = MutableImage w h `liftM` generated where compCount = componentCount (undefined :: px) generated = do arr <- M.new (w * h * compCount) let lineGenerator _ !y | y >= h = return () lineGenerator !lineIdx y = column lineIdx 0 where column !idx !x | x >= w = lineGenerator idx $ y + 1 column idx x = do unsafeWritePixel arr idx $ f x y column (idx + compCount) $ x + 1 lineGenerator 0 0 return arr -- | Create an image given a function to generate pixels. -- The function will receive values from 0 to width-1 for the x parameter -- and 0 to height-1 for the y parameter. The coordinates 0,0 are the upper -- left corner of the image, and (width-1, height-1) the lower right corner. -- -- for example, to create a small gradient image: -- -- > imageCreator :: String -> IO () -- > imageCreator path = writePng path $ generateImage pixelRenderer 250 300 -- > where pixelRenderer x y = PixelRGB8 (fromIntegral x) (fromIntegral y) 128 -- generateImage :: forall px. (Pixel px) => (Int -> Int -> px) -- ^ Generating function, with `x` and `y` params. -> Int -- ^ Width in pixels -> Int -- ^ Height in pixels -> Image px {-# INLINE generateImage #-} generateImage f w h = runST img where img :: ST s (Image px) img = generateMutableImage f w h >>= unsafeFreezeImage -- | Create an image using a monadic initializer function. -- The function will receive values from 0 to width-1 for the x parameter -- and 0 to height-1 for the y parameter. The coordinates 0,0 are the upper -- left corner of the image, and (width-1, height-1) the lower right corner. -- -- The function is called for each pixel in the line from left to right (0 to width - 1) -- and for each line (0 to height - 1). withImage :: forall m pixel. (Pixel pixel, PrimMonad m) => Int -- ^ Image width -> Int -- ^ Image height -> (Int -> Int -> m pixel) -- ^ Generating functions -> m (Image pixel) withImage width height pixelGenerator = do let pixelComponentCount = componentCount (undefined :: pixel) arr <- M.new (width * height * pixelComponentCount) let mutImage = MutableImage { mutableImageWidth = width , mutableImageHeight = height , mutableImageData = arr } let pixelPositions = [(x, y) | y <- [0 .. height-1], x <- [0..width-1]] sequence_ [pixelGenerator x y >>= unsafeWritePixel arr idx | ((x,y), idx) <- zip pixelPositions [0, pixelComponentCount ..]] unsafeFreezeImage mutImage -- | Create an image given a function to generate pixels. -- The function will receive values from 0 to width-1 for the x parameter -- and 0 to height-1 for the y parameter. The coordinates 0,0 are the upper -- left corner of the image, and (width-1, height-1) the lower right corner. -- -- the acc parameter is a user defined one. -- -- The function is called for each pixel in the line from left to right (0 to width - 1) -- and for each line (0 to height - 1). generateFoldImage :: forall a acc. (Pixel a) => (acc -> Int -> Int -> (acc, a)) -- ^ Function taking the state, x and y -> acc -- ^ Initial state -> Int -- ^ Width in pixels -> Int -- ^ Height in pixels -> (acc, Image a) generateFoldImage f intialAcc w h = (finalState, Image { imageWidth = w, imageHeight = h, imageData = generated }) where compCount = componentCount (undefined :: a) (finalState, generated) = runST $ do arr <- M.new (w * h * compCount) let mutImage = MutableImage { mutableImageWidth = w, mutableImageHeight = h, mutableImageData = arr } foldResult <- foldM (\acc (x,y) -> do let (acc', px) = f acc x y writePixel mutImage x y px return acc') intialAcc [(x,y) | y <- [0 .. h-1], x <- [0 .. w-1]] frozen <- V.unsafeFreeze arr return (foldResult, frozen) -- | Fold over the pixel of an image with a raster scan order: -- from top to bottom, left to right {-# INLINE pixelFold #-} pixelFold :: forall acc pixel. (Pixel pixel) => (acc -> Int -> Int -> pixel -> acc) -> acc -> Image pixel -> acc pixelFold f initialAccumulator img@(Image { imageWidth = w, imageHeight = h }) = columnFold 0 initialAccumulator 0 where !compCount = componentCount (undefined :: pixel) !vec = imageData img lfold !y acc !x !idx | x >= w = columnFold (y + 1) acc idx | otherwise = lfold y (f acc x y $ unsafePixelAt vec idx) (x + 1) (idx + compCount) columnFold !y lineAcc !readIdx | y >= h = lineAcc | otherwise = lfold y lineAcc 0 readIdx -- | Fold over the pixel of an image with a raster scan order: -- from top to bottom, left to right, carrying out a state pixelFoldM :: (Pixel pixel, Monad m) => (acc -> Int -> Int -> pixel -> m acc) -- ^ monadic mapping function -> acc -- ^ Initial state -> Image pixel -- ^ Image to fold over -> m acc {-# INLINE pixelFoldM #-} pixelFoldM action initialAccumulator img@(Image { imageWidth = w, imageHeight = h }) = lineFold initialAccumulator h columnFold where pixelFolder y acc x = action acc x y $ pixelAt img x y columnFold lineAcc y = lineFold lineAcc w (pixelFolder y) -- | Fold over the pixel of an image with a raster scan order: -- from top to bottom, left to right. This functions is analog -- to the foldMap from the 'Foldable' typeclass, but due to the -- Pixel constraint, Image cannot be made an instance of it. pixelFoldMap :: forall m px. (Pixel px, Monoid m) => (px -> m) -> Image px -> m pixelFoldMap f Image { imageWidth = w, imageHeight = h, imageData = vec } = folder 0 where compCount = componentCount (undefined :: px) maxi = w * h * compCount folder idx | idx >= maxi = mempty folder idx = f (unsafePixelAt vec idx) <> folder (idx + compCount) -- | `map` equivalent for an image, working at the pixel level. -- Little example : a brightness function for an rgb image -- -- > brightnessRGB8 :: Int -> Image PixelRGB8 -> Image PixelRGB8 -- > brightnessRGB8 add = pixelMap brightFunction -- > where up v = fromIntegral (fromIntegral v + add) -- > brightFunction (PixelRGB8 r g b) = -- > PixelRGB8 (up r) (up g) (up b) -- pixelMap :: forall a b. (Pixel a, Pixel b) => (a -> b) -> Image a -> Image b {-# SPECIALIZE INLINE pixelMap :: (PixelYCbCr8 -> PixelRGB8) -> Image PixelYCbCr8 -> Image PixelRGB8 #-} {-# SPECIALIZE INLINE pixelMap :: (PixelRGB8 -> PixelYCbCr8) -> Image PixelRGB8 -> Image PixelYCbCr8 #-} {-# SPECIALIZE INLINE pixelMap :: (PixelRGB8 -> PixelRGB8) -> Image PixelRGB8 -> Image PixelRGB8 #-} {-# SPECIALIZE INLINE pixelMap :: (PixelRGB8 -> PixelRGBA8) -> Image PixelRGB8 -> Image PixelRGBA8 #-} {-# SPECIALIZE INLINE pixelMap :: (PixelRGBA8 -> PixelRGBA8) -> Image PixelRGBA8 -> Image PixelRGBA8 #-} {-# SPECIALIZE INLINE pixelMap :: (Pixel8 -> PixelRGB8) -> Image Pixel8 -> Image PixelRGB8 #-} {-# SPECIALIZE INLINE pixelMap :: (Pixel8 -> Pixel8) -> Image Pixel8 -> Image Pixel8 #-} pixelMap f Image { imageWidth = w, imageHeight = h, imageData = vec } = Image w h pixels where sourceComponentCount = componentCount (undefined :: a) destComponentCount = componentCount (undefined :: b) pixels = runST $ do newArr <- M.new (w * h * destComponentCount) let lineMapper _ _ y | y >= h = return () lineMapper readIdxLine writeIdxLine y = colMapper readIdxLine writeIdxLine 0 where colMapper readIdx writeIdx x | x >= w = lineMapper readIdx writeIdx $ y + 1 | otherwise = do unsafeWritePixel newArr writeIdx . f $ unsafePixelAt vec readIdx colMapper (readIdx + sourceComponentCount) (writeIdx + destComponentCount) (x + 1) lineMapper 0 0 0 -- unsafeFreeze avoids making a second copy and it will be -- safe because newArray can't be referenced as a mutable array -- outside of this where block V.unsafeFreeze newArr -- | Helpers to embed a rankNTypes inside an Applicative newtype GenST a = GenST { genAction :: forall s. ST s (M.STVector s a) } -- | Traversal type matching the definition in the Lens package. type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t writePx :: Pixel px => Int -> GenST (PixelBaseComponent px) -> px -> GenST (PixelBaseComponent px) {-# INLINE writePx #-} writePx idx act px = GenST $ do vec <- genAction act unsafeWritePixel vec idx px return vec freezeGenST :: Pixel px => Int -> Int -> GenST (PixelBaseComponent px) -> Image px freezeGenST w h act = Image w h (runST (genAction act >>= V.unsafeFreeze)) -- | Traversal in "raster" order, from left to right the top to bottom. -- This traversal is matching pixelMap in spirit. -- -- Since 3.2.4 imagePixels :: forall pxa pxb. (Pixel pxa, Pixel pxb) => Traversal (Image pxa) (Image pxb) pxa pxb {-# INLINE imagePixels #-} imagePixels f Image { imageWidth = w, imageHeight = h, imageData = vec } = freezeGenST w h <$> pixels where sourceComponentCount = componentCount (undefined :: pxa) destComponentCount = componentCount (undefined :: pxb) maxi = w * h * sourceComponentCount pixels = go (pure $ GenST $ M.new (w * h * destComponentCount)) 0 0 go act readIdx _ | readIdx >= maxi = act go act readIdx writeIdx = go newAct (readIdx + sourceComponentCount) (writeIdx + destComponentCount) where px = f (unsafePixelAt vec readIdx) newAct = writePx writeIdx <$> act <*> px -- | Traversal providing the pixel position with it's value. -- The traversal in raster order, from lef to right, then top -- to bottom. The traversal match pixelMapXY in spirit. -- -- Since 3.2.4 imageIPixels :: forall pxa pxb. (Pixel pxa, Pixel pxb) => Traversal (Image pxa) (Image pxb) (Int, Int, pxa) pxb {-# INLINE imageIPixels #-} imageIPixels f Image { imageWidth = w, imageHeight = h, imageData = vec } = freezeGenST w h <$> pixels where sourceComponentCount = componentCount (undefined :: pxa) destComponentCount = componentCount (undefined :: pxb) pixels = lineMapper (pure $ GenST $ M.new (w * h * destComponentCount)) 0 0 0 lineMapper act _ _ y | y >= h = act lineMapper act readIdxLine writeIdxLine y = go act readIdxLine writeIdxLine 0 where go cact readIdx writeIdx x | x >= w = lineMapper cact readIdx writeIdx $ y + 1 | otherwise = do let px = f (x, y, unsafePixelAt vec readIdx) go (writePx writeIdx <$> cact <*> px) (readIdx + sourceComponentCount) (writeIdx + destComponentCount) (x + 1) -- | Just like `pixelMap` only the function takes the pixel coordinates as -- additional parameters. pixelMapXY :: forall a b. (Pixel a, Pixel b) => (Int -> Int -> a -> b) -> Image a -> Image b {-# SPECIALIZE INLINE pixelMapXY :: (Int -> Int -> PixelYCbCr8 -> PixelRGB8) -> Image PixelYCbCr8 -> Image PixelRGB8 #-} {-# SPECIALIZE INLINE pixelMapXY :: (Int -> Int -> PixelRGB8 -> PixelYCbCr8) -> Image PixelRGB8 -> Image PixelYCbCr8 #-} {-# SPECIALIZE INLINE pixelMapXY :: (Int -> Int -> PixelRGB8 -> PixelRGB8) -> Image PixelRGB8 -> Image PixelRGB8 #-} {-# SPECIALIZE INLINE pixelMapXY :: (Int -> Int -> PixelRGB8 -> PixelRGBA8) -> Image PixelRGB8 -> Image PixelRGBA8 #-} {-# SPECIALIZE INLINE pixelMapXY :: (Int -> Int -> PixelRGBA8 -> PixelRGBA8) -> Image PixelRGBA8 -> Image PixelRGBA8 #-} {-# SPECIALIZE INLINE pixelMapXY :: (Int -> Int -> Pixel8 -> PixelRGB8) -> Image Pixel8 -> Image PixelRGB8 #-} pixelMapXY f Image { imageWidth = w, imageHeight = h, imageData = vec } = Image w h pixels where sourceComponentCount = componentCount (undefined :: a) destComponentCount = componentCount (undefined :: b) pixels = runST $ do newArr <- M.new (w * h * destComponentCount) let lineMapper _ _ y | y >= h = return () lineMapper readIdxLine writeIdxLine y = colMapper readIdxLine writeIdxLine 0 where colMapper readIdx writeIdx x | x >= w = lineMapper readIdx writeIdx $ y + 1 | otherwise = do unsafeWritePixel newArr writeIdx . f x y $ unsafePixelAt vec readIdx colMapper (readIdx + sourceComponentCount) (writeIdx + destComponentCount) (x + 1) lineMapper 0 0 0 -- unsafeFreeze avoids making a second copy and it will be -- safe because newArray can't be referenced as a mutable array -- outside of this where block V.unsafeFreeze newArr -- | Combine, pixel by pixel and component by component -- the values of 3 different images. Usage example: -- -- > averageBrightNess c1 c2 c3 = clamp $ toInt c1 + toInt c2 + toInt c3 -- > where clamp = fromIntegral . min 0 . max 255 -- > toInt :: a -> Int -- > toInt = fromIntegral -- > ziPixelComponent3 averageBrightNess img1 img2 img3 -- zipPixelComponent3 :: forall px. ( V.Storable (PixelBaseComponent px)) => (PixelBaseComponent px -> PixelBaseComponent px -> PixelBaseComponent px -> PixelBaseComponent px) -> Image px -> Image px -> Image px -> Image px {-# INLINE zipPixelComponent3 #-} zipPixelComponent3 f i1@(Image { imageWidth = w, imageHeight = h }) i2 i3 | not isDimensionEqual = error "Different image size zipPairwisePixelComponent" | otherwise = Image { imageWidth = w , imageHeight = h , imageData = V.zipWith3 f data1 data2 data3 } where data1 = imageData i1 data2 = imageData i2 data3 = imageData i3 isDimensionEqual = w == imageWidth i2 && w == imageWidth i3 && h == imageHeight i2 && h == imageHeight i3 -- | Helper class to help extract a luma plane out -- of an image or a pixel class (Pixel a, Pixel (PixelBaseComponent a)) => LumaPlaneExtractable a where -- | Compute the luminance part of a pixel computeLuma :: a -> PixelBaseComponent a -- | Extract a luma plane out of an image. This -- method is in the typeclass to help performant -- implementation. -- -- > jpegToGrayScale :: FilePath -> FilePath -> IO () -- > jpegToGrayScale source dest extractLumaPlane :: Image a -> Image (PixelBaseComponent a) extractLumaPlane = pixelMap computeLuma instance LumaPlaneExtractable Pixel8 where {-# INLINE computeLuma #-} computeLuma = id extractLumaPlane = id instance LumaPlaneExtractable Pixel16 where {-# INLINE computeLuma #-} computeLuma = id extractLumaPlane = id instance LumaPlaneExtractable Pixel32 where {-# INLINE computeLuma #-} computeLuma = id extractLumaPlane = id instance LumaPlaneExtractable PixelF where {-# INLINE computeLuma #-} computeLuma = id extractLumaPlane = id instance LumaPlaneExtractable PixelRGBF where {-# INLINE computeLuma #-} computeLuma (PixelRGBF r g b) = 0.3 * r + 0.59 * g + 0.11 * b instance LumaPlaneExtractable PixelRGBA8 where {-# INLINE computeLuma #-} computeLuma (PixelRGBA8 r g b _) = floor $ 0.3 * toRational r + 0.59 * toRational g + 0.11 * toRational b instance LumaPlaneExtractable PixelYCbCr8 where {-# INLINE computeLuma #-} computeLuma (PixelYCbCr8 y _ _) = y extractLumaPlane = extractComponent PlaneLuma -- | Free promotion for identic pixel types instance (Pixel a) => ColorConvertible a a where {-# INLINE promotePixel #-} promotePixel = id {-# INLINE promoteImage #-} promoteImage = id -------------------------------------------------- ---- Pixel8 instances -------------------------------------------------- instance Pixel Pixel8 where type PixelBaseComponent Pixel8 = Word8 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f = f 0 {-# INLINE colorMap #-} colorMap f = f {-# INLINE componentCount #-} componentCount _ = 1 {-# INLINE pixelAt #-} pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w) {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.read` mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.write` mutablePixelBaseIndex image x y {-# INLINE unsafePixelAt #-} unsafePixelAt = V.unsafeIndex {-# INLINE unsafeReadPixel #-} unsafeReadPixel = M.unsafeRead {-# INLINE unsafeWritePixel #-} unsafeWritePixel = M.unsafeWrite instance ColorConvertible Pixel8 PixelYA8 where {-# INLINE promotePixel #-} promotePixel c = PixelYA8 c 255 instance ColorConvertible Pixel8 PixelF where {-# INLINE promotePixel #-} promotePixel c = fromIntegral c / 255.0 instance ColorConvertible Pixel8 Pixel16 where {-# INLINE promotePixel #-} promotePixel c = fromIntegral c * 257 instance ColorConvertible Pixel8 PixelRGB8 where {-# INLINE promotePixel #-} promotePixel c = PixelRGB8 c c c instance ColorConvertible Pixel8 PixelRGBA8 where {-# INLINE promotePixel #-} promotePixel c = PixelRGBA8 c c c 255 -------------------------------------------------- ---- Pixel16 instances -------------------------------------------------- instance Pixel Pixel16 where type PixelBaseComponent Pixel16 = Word16 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f = f 0 {-# INLINE colorMap #-} colorMap f = f {-# INLINE componentCount #-} componentCount _ = 1 {-# INLINE pixelAt #-} pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w) {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.read` mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.write` mutablePixelBaseIndex image x y {-# INLINE unsafePixelAt #-} unsafePixelAt = V.unsafeIndex {-# INLINE unsafeReadPixel #-} unsafeReadPixel = M.unsafeRead {-# INLINE unsafeWritePixel #-} unsafeWritePixel = M.unsafeWrite instance ColorConvertible Pixel16 PixelYA16 where {-# INLINE promotePixel #-} promotePixel c = PixelYA16 c maxBound instance ColorConvertible Pixel16 PixelRGB16 where {-# INLINE promotePixel #-} promotePixel c = PixelRGB16 c c c instance ColorConvertible Pixel16 PixelRGBA16 where {-# INLINE promotePixel #-} promotePixel c = PixelRGBA16 c c c maxBound -------------------------------------------------- ---- Pixel32 instances -------------------------------------------------- instance Pixel Pixel32 where type PixelBaseComponent Pixel32 = Word32 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f = f 0 {-# INLINE colorMap #-} colorMap f = f {-# INLINE componentCount #-} componentCount _ = 1 {-# INLINE pixelAt #-} pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w) {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.read` mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.write` mutablePixelBaseIndex image x y {-# INLINE unsafePixelAt #-} unsafePixelAt = V.unsafeIndex {-# INLINE unsafeReadPixel #-} unsafeReadPixel = M.unsafeRead {-# INLINE unsafeWritePixel #-} unsafeWritePixel = M.unsafeWrite -------------------------------------------------- ---- PixelF instances -------------------------------------------------- instance Pixel PixelF where type PixelBaseComponent PixelF = Float {-# INLINE pixelOpacity #-} pixelOpacity = const 1.0 {-# INLINE mixWith #-} mixWith f = f 0 {-# INLINE colorMap #-} colorMap f = f {-# INLINE componentCount #-} componentCount _ = 1 {-# INLINE pixelAt #-} pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w) {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.read` mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y = arr `M.write` mutablePixelBaseIndex image x y {-# INLINE unsafePixelAt #-} unsafePixelAt = V.unsafeIndex {-# INLINE unsafeReadPixel #-} unsafeReadPixel = M.unsafeRead {-# INLINE unsafeWritePixel #-} unsafeWritePixel = M.unsafeWrite instance ColorConvertible PixelF PixelRGBF where {-# INLINE promotePixel #-} promotePixel c = PixelRGBF c c c-- (c / 0.3) (c / 0.59) (c / 0.11) -------------------------------------------------- ---- PixelYA8 instances -------------------------------------------------- instance Pixel PixelYA8 where type PixelBaseComponent PixelYA8 = Word8 {-# INLINE pixelOpacity #-} pixelOpacity (PixelYA8 _ a) = a {-# INLINE mixWith #-} mixWith f (PixelYA8 ya aa) (PixelYA8 yb ab) = PixelYA8 (f 0 ya yb) (f 1 aa ab) {-# INLINE colorMap #-} colorMap f (PixelYA8 y a) = PixelYA8 (f y) (f a) {-# INLINE componentCount #-} componentCount _ = 2 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelYA8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do yv <- arr `M.read` baseIdx av <- arr `M.read` (baseIdx + 1) return $ PixelYA8 yv av where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYA8 yv av) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) yv (arr `M.write` (baseIdx + 1)) av {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelYA8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelYA8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelYA8 y a) = M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) a instance ColorConvertible PixelYA8 PixelRGB8 where {-# INLINE promotePixel #-} promotePixel (PixelYA8 y _) = PixelRGB8 y y y instance ColorConvertible PixelYA8 PixelRGBA8 where {-# INLINE promotePixel #-} promotePixel (PixelYA8 y a) = PixelRGBA8 y y y a instance ColorPlane PixelYA8 PlaneLuma where toComponentIndex _ _ = 0 instance ColorPlane PixelYA8 PlaneAlpha where toComponentIndex _ _ = 1 instance TransparentPixel PixelYA8 Pixel8 where {-# INLINE dropTransparency #-} dropTransparency (PixelYA8 y _) = y {-# INLINE getTransparency #-} getTransparency (PixelYA8 _ a) = a instance LumaPlaneExtractable PixelYA8 where {-# INLINE computeLuma #-} computeLuma (PixelYA8 y _) = y extractLumaPlane = extractComponent PlaneLuma -------------------------------------------------- ---- PixelYA16 instances -------------------------------------------------- instance Pixel PixelYA16 where type PixelBaseComponent PixelYA16 = Word16 {-# INLINE pixelOpacity #-} pixelOpacity (PixelYA16 _ a) = a {-# INLINE mixWith #-} mixWith f (PixelYA16 ya aa) (PixelYA16 yb ab) = PixelYA16 (f 0 ya yb) (f 1 aa ab) {-# INLINE mixWithAlpha #-} mixWithAlpha f fa (PixelYA16 ya aa) (PixelYA16 yb ab) = PixelYA16 (f 0 ya yb) (fa aa ab) {-# INLINE colorMap #-} colorMap f (PixelYA16 y a) = PixelYA16 (f y) (f a) {-# INLINE componentCount #-} componentCount _ = 2 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelYA16 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do yv <- arr `M.read` baseIdx av <- arr `M.read` (baseIdx + 1) return $ PixelYA16 yv av where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYA16 yv av) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) yv (arr `M.write` (baseIdx + 1)) av {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelYA16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelYA16 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelYA16 y a) = M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) a instance ColorConvertible PixelYA16 PixelRGBA16 where {-# INLINE promotePixel #-} promotePixel (PixelYA16 y a) = PixelRGBA16 y y y a instance ColorPlane PixelYA16 PlaneLuma where toComponentIndex _ _ = 0 instance ColorPlane PixelYA16 PlaneAlpha where toComponentIndex _ _ = 1 instance TransparentPixel PixelYA16 Pixel16 where {-# INLINE dropTransparency #-} dropTransparency (PixelYA16 y _) = y {-# INLINE getTransparency #-} getTransparency (PixelYA16 _ a) = a -------------------------------------------------- ---- PixelRGBF instances -------------------------------------------------- instance Pixel PixelRGBF where type PixelBaseComponent PixelRGBF = PixelF {-# INLINE pixelOpacity #-} pixelOpacity = const 1.0 {-# INLINE mixWith #-} mixWith f (PixelRGBF ra ga ba) (PixelRGBF rb gb bb) = PixelRGBF (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) {-# INLINE colorMap #-} colorMap f (PixelRGBF r g b) = PixelRGBF (f r) (f g) (f b) {-# INLINE componentCount #-} componentCount _ = 3 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelRGBF (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do rv <- arr `M.read` baseIdx gv <- arr `M.read` (baseIdx + 1) bv <- arr `M.read` (baseIdx + 2) return $ PixelRGBF rv gv bv where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBF rv gv bv) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) rv (arr `M.write` (baseIdx + 1)) gv (arr `M.write` (baseIdx + 2)) bv {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelRGBF (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelRGBF `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelRGBF r g b) = M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g >> M.unsafeWrite v (idx + 2) b instance ColorPlane PixelRGBF PlaneRed where toComponentIndex _ _ = 0 instance ColorPlane PixelRGBF PlaneGreen where toComponentIndex _ _ = 1 instance ColorPlane PixelRGBF PlaneBlue where toComponentIndex _ _ = 2 -------------------------------------------------- ---- PixelRGB16 instances -------------------------------------------------- instance Pixel PixelRGB16 where type PixelBaseComponent PixelRGB16 = Pixel16 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f (PixelRGB16 ra ga ba) (PixelRGB16 rb gb bb) = PixelRGB16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) {-# INLINE colorMap #-} colorMap f (PixelRGB16 r g b) = PixelRGB16 (f r) (f g) (f b) {-# INLINE componentCount #-} componentCount _ = 3 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelRGB16 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do rv <- arr `M.read` baseIdx gv <- arr `M.read` (baseIdx + 1) bv <- arr `M.read` (baseIdx + 2) return $ PixelRGB16 rv gv bv where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGB16 rv gv bv) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) rv (arr `M.write` (baseIdx + 1)) gv (arr `M.write` (baseIdx + 2)) bv {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelRGB16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelRGB16 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelRGB16 r g b) = M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g >> M.unsafeWrite v (idx + 2) b instance ColorPlane PixelRGB16 PlaneRed where toComponentIndex _ _ = 0 instance ColorPlane PixelRGB16 PlaneGreen where toComponentIndex _ _ = 1 instance ColorPlane PixelRGB16 PlaneBlue where toComponentIndex _ _ = 2 instance ColorSpaceConvertible PixelRGB16 PixelCMYK16 where {-# INLINE convertPixel #-} convertPixel (PixelRGB16 r g b) = integralRGBToCMYK PixelCMYK16 (r, g, b) instance ColorConvertible PixelRGB16 PixelRGBA16 where {-# INLINE promotePixel #-} promotePixel (PixelRGB16 r g b) = PixelRGBA16 r g b maxBound instance LumaPlaneExtractable PixelRGB16 where {-# INLINE computeLuma #-} computeLuma (PixelRGB16 r g b) = floor $ 0.3 * toRational r + 0.59 * toRational g + 0.11 * toRational b -------------------------------------------------- ---- PixelRGB8 instances -------------------------------------------------- instance Pixel PixelRGB8 where type PixelBaseComponent PixelRGB8 = Word8 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) = PixelRGB8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) {-# INLINE colorMap #-} colorMap f (PixelRGB8 r g b) = PixelRGB8 (f r) (f g) (f b) {-# INLINE componentCount #-} componentCount _ = 3 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelRGB8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do rv <- arr `M.read` baseIdx gv <- arr `M.read` (baseIdx + 1) bv <- arr `M.read` (baseIdx + 2) return $ PixelRGB8 rv gv bv where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGB8 rv gv bv) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) rv (arr `M.write` (baseIdx + 1)) gv (arr `M.write` (baseIdx + 2)) bv {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelRGB8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelRGB8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelRGB8 r g b) = M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g >> M.unsafeWrite v (idx + 2) b instance ColorConvertible PixelRGB8 PixelRGBA8 where {-# INLINE promotePixel #-} promotePixel (PixelRGB8 r g b) = PixelRGBA8 r g b maxBound instance ColorConvertible PixelRGB8 PixelRGBF where {-# INLINE promotePixel #-} promotePixel (PixelRGB8 r g b) = PixelRGBF (toF r) (toF g) (toF b) where toF v = fromIntegral v / 255.0 instance ColorConvertible PixelRGB8 PixelRGB16 where {-# INLINE promotePixel #-} promotePixel (PixelRGB8 r g b) = PixelRGB16 (promotePixel r) (promotePixel g) (promotePixel b) instance ColorConvertible PixelRGB8 PixelRGBA16 where {-# INLINE promotePixel #-} promotePixel (PixelRGB8 r g b) = PixelRGBA16 (promotePixel r) (promotePixel g) (promotePixel b) maxBound instance ColorPlane PixelRGB8 PlaneRed where toComponentIndex _ _ = 0 instance ColorPlane PixelRGB8 PlaneGreen where toComponentIndex _ _ = 1 instance ColorPlane PixelRGB8 PlaneBlue where toComponentIndex _ _ = 2 instance LumaPlaneExtractable PixelRGB8 where {-# INLINE computeLuma #-} computeLuma (PixelRGB8 r g b) = floor $ 0.3 * toRational r + 0.59 * toRational g + 0.11 * toRational b -------------------------------------------------- ---- PixelRGBA8 instances -------------------------------------------------- instance Pixel PixelRGBA8 where type PixelBaseComponent PixelRGBA8 = Word8 {-# INLINE pixelOpacity #-} pixelOpacity (PixelRGBA8 _ _ _ a) = a {-# INLINE mixWith #-} mixWith f (PixelRGBA8 ra ga ba aa) (PixelRGBA8 rb gb bb ab) = PixelRGBA8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (f 3 aa ab) {-# INLINE mixWithAlpha #-} mixWithAlpha f fa (PixelRGBA8 ra ga ba aa) (PixelRGBA8 rb gb bb ab) = PixelRGBA8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (fa aa ab) {-# INLINE colorMap #-} colorMap f (PixelRGBA8 r g b a) = PixelRGBA8 (f r) (f g) (f b) (f a) {-# INLINE componentCount #-} componentCount _ = 4 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelRGBA8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) (arr ! (baseIdx + 3)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do rv <- arr `M.read` baseIdx gv <- arr `M.read` (baseIdx + 1) bv <- arr `M.read` (baseIdx + 2) av <- arr `M.read` (baseIdx + 3) return $ PixelRGBA8 rv gv bv av where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBA8 rv gv bv av) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) rv (arr `M.write` (baseIdx + 1)) gv (arr `M.write` (baseIdx + 2)) bv (arr `M.write` (baseIdx + 3)) av {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelRGBA8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) (V.unsafeIndex v $ idx + 3) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelRGBA8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) `ap` M.unsafeRead vec (idx + 3) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelRGBA8 r g b a) = M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g >> M.unsafeWrite v (idx + 2) b >> M.unsafeWrite v (idx + 3) a instance ColorConvertible PixelRGBA8 PixelRGBA16 where {-# INLINE promotePixel #-} promotePixel (PixelRGBA8 r g b a) = PixelRGBA16 (promotePixel r) (promotePixel g) (promotePixel b) (promotePixel a) instance ColorPlane PixelRGBA8 PlaneRed where toComponentIndex _ _ = 0 instance ColorPlane PixelRGBA8 PlaneGreen where toComponentIndex _ _ = 1 instance ColorPlane PixelRGBA8 PlaneBlue where toComponentIndex _ _ = 2 instance ColorPlane PixelRGBA8 PlaneAlpha where toComponentIndex _ _ = 3 -------------------------------------------------- ---- PixelRGBA16 instances -------------------------------------------------- instance Pixel PixelRGBA16 where type PixelBaseComponent PixelRGBA16 = Pixel16 {-# INLINE pixelOpacity #-} pixelOpacity (PixelRGBA16 _ _ _ a) = a {-# INLINE mixWith #-} mixWith f (PixelRGBA16 ra ga ba aa) (PixelRGBA16 rb gb bb ab) = PixelRGBA16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (f 3 aa ab) {-# INLINE mixWithAlpha #-} mixWithAlpha f fa (PixelRGBA16 ra ga ba aa) (PixelRGBA16 rb gb bb ab) = PixelRGBA16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (fa aa ab) {-# INLINE colorMap #-} colorMap f (PixelRGBA16 r g b a) = PixelRGBA16 (f r) (f g) (f b) (f a) {-# INLINE componentCount #-} componentCount _ = 4 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelRGBA16 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) (arr ! (baseIdx + 3)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do rv <- arr `M.read` baseIdx gv <- arr `M.read` (baseIdx + 1) bv <- arr `M.read` (baseIdx + 2) av <- arr `M.read` (baseIdx + 3) return $ PixelRGBA16 rv gv bv av where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBA16 rv gv bv av) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) rv (arr `M.write` (baseIdx + 1)) gv (arr `M.write` (baseIdx + 2)) bv (arr `M.write` (baseIdx + 3)) av {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelRGBA16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) (V.unsafeIndex v $ idx + 3) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelRGBA16 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) `ap` M.unsafeRead vec (idx + 3) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelRGBA16 r g b a) = M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g >> M.unsafeWrite v (idx + 2) b >> M.unsafeWrite v (idx + 3) a instance TransparentPixel PixelRGBA16 PixelRGB16 where {-# INLINE dropTransparency #-} dropTransparency (PixelRGBA16 r g b _) = PixelRGB16 r g b {-# INLINE getTransparency #-} getTransparency (PixelRGBA16 _ _ _ a) = a instance ColorPlane PixelRGBA16 PlaneRed where toComponentIndex _ _ = 0 instance ColorPlane PixelRGBA16 PlaneGreen where toComponentIndex _ _ = 1 instance ColorPlane PixelRGBA16 PlaneBlue where toComponentIndex _ _ = 2 instance ColorPlane PixelRGBA16 PlaneAlpha where toComponentIndex _ _ = 3 -------------------------------------------------- ---- PixelYCbCr8 instances -------------------------------------------------- instance Pixel PixelYCbCr8 where type PixelBaseComponent PixelYCbCr8 = Word8 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f (PixelYCbCr8 ya cba cra) (PixelYCbCr8 yb cbb crb) = PixelYCbCr8 (f 0 ya yb) (f 1 cba cbb) (f 2 cra crb) {-# INLINE colorMap #-} colorMap f (PixelYCbCr8 y cb cr) = PixelYCbCr8 (f y) (f cb) (f cr) {-# INLINE componentCount #-} componentCount _ = 3 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelYCbCr8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do yv <- arr `M.read` baseIdx cbv <- arr `M.read` (baseIdx + 1) crv <- arr `M.read` (baseIdx + 2) return $ PixelYCbCr8 yv cbv crv where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYCbCr8 yv cbv crv) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) yv (arr `M.write` (baseIdx + 1)) cbv (arr `M.write` (baseIdx + 2)) crv {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelYCbCr8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelYCbCr8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelYCbCr8 y cb cr) = M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) cb >> M.unsafeWrite v (idx + 2) cr instance (Pixel a) => ColorSpaceConvertible a a where convertPixel = id convertImage = id scaleBits, oneHalf :: Int scaleBits = 16 oneHalf = 1 `unsafeShiftL` (scaleBits - 1) fix :: Float -> Int fix x = floor $ x * fromIntegral ((1 :: Int) `unsafeShiftL` scaleBits) + 0.5 rYTab, gYTab, bYTab, rCbTab, gCbTab, bCbTab, gCrTab, bCrTab :: V.Vector Int rYTab = V.fromListN 256 [fix 0.29900 * i | i <- [0..255] ] gYTab = V.fromListN 256 [fix 0.58700 * i | i <- [0..255] ] bYTab = V.fromListN 256 [fix 0.11400 * i + oneHalf | i <- [0..255] ] rCbTab = V.fromListN 256 [(- fix 0.16874) * i | i <- [0..255] ] gCbTab = V.fromListN 256 [(- fix 0.33126) * i | i <- [0..255] ] bCbTab = V.fromListN 256 [fix 0.5 * i + (128 `unsafeShiftL` scaleBits) + oneHalf - 1| i <- [0..255] ] gCrTab = V.fromListN 256 [(- fix 0.41869) * i | i <- [0..255] ] bCrTab = V.fromListN 256 [(- fix 0.08131) * i | i <- [0..255] ] instance ColorSpaceConvertible PixelRGB8 PixelYCbCr8 where {-# INLINE convertPixel #-} convertPixel (PixelRGB8 r g b) = PixelYCbCr8 (fromIntegral y) (fromIntegral cb) (fromIntegral cr) where ri = fromIntegral r gi = fromIntegral g bi = fromIntegral b y = (rYTab `V.unsafeIndex` ri + gYTab `V.unsafeIndex` gi + bYTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits cb = (rCbTab `V.unsafeIndex` ri + gCbTab `V.unsafeIndex` gi + bCbTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits cr = (bCbTab `V.unsafeIndex` ri + gCrTab `V.unsafeIndex` gi + bCrTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits convertImage Image { imageWidth = w, imageHeight = h, imageData = d } = Image w h newData where maxi = w * h rY = fix 0.29900 gY = fix 0.58700 bY = fix 0.11400 rCb = - fix 0.16874 gCb = - fix 0.33126 bCb = fix 0.5 gCr = - fix 0.41869 bCr = - fix 0.08131 newData = runST $ do block <- M.new $ maxi * 3 let traductor _ idx | idx >= maxi = return block traductor readIdx idx = do let ri = fromIntegral $ d `V.unsafeIndex` readIdx gi = fromIntegral $ d `V.unsafeIndex` (readIdx + 1) bi = fromIntegral $ d `V.unsafeIndex` (readIdx + 2) y = (rY * ri + gY * gi + bY * bi + oneHalf) `unsafeShiftR` scaleBits cb = (rCb * ri + gCb * gi + bCb * bi + (128 `unsafeShiftL` scaleBits) + oneHalf - 1) `unsafeShiftR` scaleBits cr = (bCb * ri + (128 `unsafeShiftL` scaleBits) + oneHalf - 1+ gCr * gi + bCr * bi) `unsafeShiftR` scaleBits (block `M.unsafeWrite` (readIdx + 0)) $ fromIntegral y (block `M.unsafeWrite` (readIdx + 1)) $ fromIntegral cb (block `M.unsafeWrite` (readIdx + 2)) $ fromIntegral cr traductor (readIdx + 3) (idx + 1) traductor 0 0 >>= V.freeze crRTab, cbBTab, crGTab, cbGTab :: V.Vector Int crRTab = V.fromListN 256 [(fix 1.40200 * x + oneHalf) `unsafeShiftR` scaleBits | x <- [-128 .. 127]] cbBTab = V.fromListN 256 [(fix 1.77200 * x + oneHalf) `unsafeShiftR` scaleBits | x <- [-128 .. 127]] crGTab = V.fromListN 256 [negate (fix 0.71414) * x | x <- [-128 .. 127]] cbGTab = V.fromListN 256 [negate (fix 0.34414) * x + oneHalf | x <- [-128 .. 127]] instance ColorSpaceConvertible PixelYCbCr8 PixelRGB8 where {-# INLINE convertPixel #-} convertPixel (PixelYCbCr8 y cb cr) = PixelRGB8 (clampWord8 r) (clampWord8 g) (clampWord8 b) where clampWord8 = fromIntegral . max 0 . min 255 yi = fromIntegral y cbi = fromIntegral cb cri = fromIntegral cr r = yi + crRTab `V.unsafeIndex` cri g = yi + (cbGTab `V.unsafeIndex` cbi + crGTab `V.unsafeIndex` cri) `unsafeShiftR` scaleBits b = yi + cbBTab `V.unsafeIndex` cbi convertImage Image { imageWidth = w, imageHeight = h, imageData = d } = Image w h newData where maxi = w * h clampWord8 v | v < 0 = 0 | v > 255 = 255 | otherwise = fromIntegral v newData = runST $ do block <- M.new $ maxi * 3 let traductor _ idx | idx >= maxi = return block traductor readIdx idx = do let yi = fromIntegral $ d `V.unsafeIndex` readIdx cbi = fromIntegral $ d `V.unsafeIndex` (readIdx + 1) cri = fromIntegral $ d `V.unsafeIndex` (readIdx + 2) r = yi + crRTab `V.unsafeIndex` cri g = yi + (cbGTab `V.unsafeIndex` cbi + crGTab `V.unsafeIndex` cri) `unsafeShiftR` scaleBits b = yi + cbBTab `V.unsafeIndex` cbi (block `M.unsafeWrite` (readIdx + 0)) $ clampWord8 r (block `M.unsafeWrite` (readIdx + 1)) $ clampWord8 g (block `M.unsafeWrite` (readIdx + 2)) $ clampWord8 b traductor (readIdx + 3) (idx + 1) traductor 0 0 >>= V.freeze instance ColorPlane PixelYCbCr8 PlaneLuma where toComponentIndex _ _ = 0 instance ColorPlane PixelYCbCr8 PlaneCb where toComponentIndex _ _ = 1 instance ColorPlane PixelYCbCr8 PlaneCr where toComponentIndex _ _ = 2 -------------------------------------------------- ---- PixelCMYK8 instances -------------------------------------------------- instance Pixel PixelCMYK8 where type PixelBaseComponent PixelCMYK8 = Word8 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f (PixelCMYK8 ca ma ya ka) (PixelCMYK8 cb mb yb kb) = PixelCMYK8 (f 0 ca cb) (f 1 ma mb) (f 2 ya yb) (f 3 ka kb) {-# INLINE colorMap #-} colorMap f (PixelCMYK8 c m y k) = PixelCMYK8 (f c) (f m) (f y) (f k) {-# INLINE componentCount #-} componentCount _ = 4 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelCMYK8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) (arr ! (baseIdx + 3)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do rv <- arr `M.read` baseIdx gv <- arr `M.read` (baseIdx + 1) bv <- arr `M.read` (baseIdx + 2) av <- arr `M.read` (baseIdx + 3) return $ PixelCMYK8 rv gv bv av where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelCMYK8 rv gv bv av) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) rv (arr `M.write` (baseIdx + 1)) gv (arr `M.write` (baseIdx + 2)) bv (arr `M.write` (baseIdx + 3)) av {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelCMYK8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) (V.unsafeIndex v $ idx + 3) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelCMYK8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) `ap` M.unsafeRead vec (idx + 3) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelCMYK8 r g b a) = M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g >> M.unsafeWrite v (idx + 2) b >> M.unsafeWrite v (idx + 3) a instance ColorSpaceConvertible PixelCMYK8 PixelRGB8 where convertPixel (PixelCMYK8 c m y k) = PixelRGB8 (clampWord8 r) (clampWord8 g) (clampWord8 b) where clampWord8 = fromIntegral . max 0 . min 255 . (`div` 255) ik :: Int ik = 255 - fromIntegral k r = (255 - fromIntegral c) * ik g = (255 - fromIntegral m) * ik b = (255 - fromIntegral y) * ik -------------------------------------------------- ---- PixelYCbCrK8 instances -------------------------------------------------- instance Pixel PixelYCbCrK8 where type PixelBaseComponent PixelYCbCrK8 = Word8 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f (PixelYCbCrK8 ya cba cra ka) (PixelYCbCrK8 yb cbb crb kb) = PixelYCbCrK8 (f 0 ya yb) (f 1 cba cbb) (f 2 cra crb) (f 3 ka kb) {-# INLINE colorMap #-} colorMap f (PixelYCbCrK8 y cb cr k) = PixelYCbCrK8 (f y) (f cb) (f cr) (f k) {-# INLINE componentCount #-} componentCount _ = 4 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelYCbCrK8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) (arr ! (baseIdx + 3)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do yv <- arr `M.read` baseIdx cbv <- arr `M.read` (baseIdx + 1) crv <- arr `M.read` (baseIdx + 2) kv <- arr `M.read` (baseIdx + 3) return $ PixelYCbCrK8 yv cbv crv kv where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYCbCrK8 yv cbv crv kv) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) yv (arr `M.write` (baseIdx + 1)) cbv (arr `M.write` (baseIdx + 2)) crv (arr `M.write` (baseIdx + 3)) kv {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelYCbCrK8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) (V.unsafeIndex v $ idx + 3) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelYCbCrK8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) `ap` M.unsafeRead vec (idx + 3) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelYCbCrK8 y cb cr k) = M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) cb >> M.unsafeWrite v (idx + 2) cr >> M.unsafeWrite v (idx + 3) k instance ColorSpaceConvertible PixelYCbCrK8 PixelRGB8 where convertPixel (PixelYCbCrK8 y cb cr _k) = PixelRGB8 (clamp r) (clamp g) (clamp b) where tof :: Word8 -> Float tof = fromIntegral clamp :: Float -> Word8 clamp = floor . max 0 . min 255 yf = tof y r = yf + 1.402 * tof cr - 179.456 g = yf - 0.3441363 * tof cb - 0.71413636 * tof cr + 135.4589 b = yf + 1.772 * tof cb - 226.816 instance ColorSpaceConvertible PixelYCbCrK8 PixelCMYK8 where convertPixel (PixelYCbCrK8 y cb cr k) = PixelCMYK8 c m ye k where tof :: Word8 -> Float tof = fromIntegral clamp :: Float -> Word8 clamp = floor . max 0 . min 255 yf = tof y r = yf + 1.402 * tof cr - 179.456 g = yf - 0.3441363 * tof cb - 0.71413636 * tof cr + 135.4589 b = yf + 1.772 * tof cb - 226.816 c = clamp $ 255 - r m = clamp $ 255 - g ye = clamp $ 255 - b {-# SPECIALIZE integralRGBToCMYK :: (Word8 -> Word8 -> Word8 -> Word8 -> b) -> (Word8, Word8, Word8) -> b #-} {-# SPECIALIZE integralRGBToCMYK :: (Word16 -> Word16 -> Word16 -> Word16 -> b) -> (Word16, Word16, Word16) -> b #-} integralRGBToCMYK :: (Bounded a, Integral a) => (a -> a -> a -> a -> b) -- ^ Pixel building function -> (a, a, a) -- ^ RGB sample -> b -- ^ Resulting sample integralRGBToCMYK build (r, g, b) = build (clamp c) (clamp m) (clamp y) (fromIntegral kInt) where maxi = maxBound ir = fromIntegral $ maxi - r :: Int ig = fromIntegral $ maxi - g ib = fromIntegral $ maxi - b kInt = minimum [ir, ig, ib] ik = fromIntegral maxi - kInt c = (ir - kInt) `div` ik m = (ig - kInt) `div` ik y = (ib - kInt) `div` ik clamp = fromIntegral . max 0 instance ColorSpaceConvertible PixelRGB8 PixelCMYK8 where convertPixel (PixelRGB8 r g b) = integralRGBToCMYK PixelCMYK8 (r, g, b) instance ColorPlane PixelCMYK8 PlaneCyan where toComponentIndex _ _ = 0 instance ColorPlane PixelCMYK8 PlaneMagenta where toComponentIndex _ _ = 1 instance ColorPlane PixelCMYK8 PlaneYellow where toComponentIndex _ _ = 2 instance ColorPlane PixelCMYK8 PlaneBlack where toComponentIndex _ _ = 3 -------------------------------------------------- ---- PixelCMYK16 instances -------------------------------------------------- instance Pixel PixelCMYK16 where type PixelBaseComponent PixelCMYK16 = Word16 {-# INLINE pixelOpacity #-} pixelOpacity = const maxBound {-# INLINE mixWith #-} mixWith f (PixelCMYK16 ca ma ya ka) (PixelCMYK16 cb mb yb kb) = PixelCMYK16 (f 0 ca cb) (f 1 ma mb) (f 2 ya yb) (f 3 ka kb) {-# INLINE colorMap #-} colorMap f (PixelCMYK16 c m y k) = PixelCMYK16 (f c) (f m) (f y) (f k) {-# INLINE componentCount #-} componentCount _ = 4 {-# INLINE pixelAt #-} pixelAt image@(Image { imageData = arr }) x y = PixelCMYK16 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1)) (arr ! (baseIdx + 2)) (arr ! (baseIdx + 3)) where baseIdx = pixelBaseIndex image x y {-# INLINE readPixel #-} readPixel image@(MutableImage { mutableImageData = arr }) x y = do rv <- arr `M.read` baseIdx gv <- arr `M.read` (baseIdx + 1) bv <- arr `M.read` (baseIdx + 2) av <- arr `M.read` (baseIdx + 3) return $ PixelCMYK16 rv gv bv av where baseIdx = mutablePixelBaseIndex image x y {-# INLINE writePixel #-} writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelCMYK16 rv gv bv av) = do let baseIdx = mutablePixelBaseIndex image x y (arr `M.write` (baseIdx + 0)) rv (arr `M.write` (baseIdx + 1)) gv (arr `M.write` (baseIdx + 2)) bv (arr `M.write` (baseIdx + 3)) av {-# INLINE unsafePixelAt #-} unsafePixelAt v idx = PixelCMYK16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2) (V.unsafeIndex v $ idx + 3) {-# INLINE unsafeReadPixel #-} unsafeReadPixel vec idx = PixelCMYK16 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1) `ap` M.unsafeRead vec (idx + 2) `ap` M.unsafeRead vec (idx + 3) {-# INLINE unsafeWritePixel #-} unsafeWritePixel v idx (PixelCMYK16 r g b a) = M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g >> M.unsafeWrite v (idx + 2) b >> M.unsafeWrite v (idx + 3) a instance ColorSpaceConvertible PixelCMYK16 PixelRGB16 where convertPixel (PixelCMYK16 c m y k) = PixelRGB16 (clampWord16 r) (clampWord16 g) (clampWord16 b) where clampWord16 = fromIntegral . (`unsafeShiftR` 16) ik :: Int ik = 65535 - fromIntegral k r = (65535 - fromIntegral c) * ik g = (65535 - fromIntegral m) * ik b = (65535 - fromIntegral y) * ik instance ColorPlane PixelCMYK16 PlaneCyan where toComponentIndex _ _ = 0 instance ColorPlane PixelCMYK16 PlaneMagenta where toComponentIndex _ _ = 1 instance ColorPlane PixelCMYK16 PlaneYellow where toComponentIndex _ _ = 2 instance ColorPlane PixelCMYK16 PlaneBlack where toComponentIndex _ _ = 3 -- | Perform a gamma correction for an image with HDR pixels. gammaCorrection :: PixelF -- ^ Gamma value, should be between 0.5 and 3.0 -> Image PixelRGBF -- ^ Image to treat. -> Image PixelRGBF gammaCorrection gammaVal = pixelMap gammaCorrector where gammaExponent = 1.0 / gammaVal fixVal v = v ** gammaExponent gammaCorrector (PixelRGBF r g b) = PixelRGBF (fixVal r) (fixVal g) (fixVal b) -- | Perform a tone mapping operation on an High dynamic range image. toneMapping :: PixelF -- ^ Exposure parameter -> Image PixelRGBF -- ^ Image to treat. -> Image PixelRGBF toneMapping exposure img = Image (imageWidth img) (imageHeight img) scaledData where coeff = exposure * (exposure / maxBrightness + 1.0) / (exposure + 1.0); maxBrightness = pixelFold (\luma _ _ px -> max luma $ computeLuma px) 0 img scaledData = V.map (* coeff) $ imageData img -------------------------------------------------- ---- Packable pixel -------------------------------------------------- -- | This typeclass exist for performance reason, it allow -- to pack a pixel value to a simpler "primitive" data -- type to allow faster writing to moemory. class PackeablePixel a where -- | Primitive type asociated to the current pixel -- It's Word32 for PixelRGBA8 for instance type PackedRepresentation a -- | The packing function, allowing to transform -- to a primitive. packPixel :: a -> PackedRepresentation a -- | Inverse transformation, to speed up -- reading unpackPixel :: PackedRepresentation a -> a instance PackeablePixel Pixel8 where type PackedRepresentation Pixel8 = Pixel8 packPixel = id {-# INLINE packPixel #-} unpackPixel = id {-# INLINE unpackPixel #-} instance PackeablePixel Pixel16 where type PackedRepresentation Pixel16 = Pixel16 packPixel = id {-# INLINE packPixel #-} unpackPixel = id {-# INLINE unpackPixel #-} instance PackeablePixel Pixel32 where type PackedRepresentation Pixel32 = Pixel32 packPixel = id {-# INLINE packPixel #-} unpackPixel = id {-# INLINE unpackPixel #-} instance PackeablePixel PixelF where type PackedRepresentation PixelF = PixelF packPixel = id {-# INLINE packPixel #-} unpackPixel = id {-# INLINE unpackPixel #-} instance PackeablePixel PixelRGBA8 where type PackedRepresentation PixelRGBA8 = Word32 {-# INLINE packPixel #-} packPixel (PixelRGBA8 r g b a) = (fi r `unsafeShiftL` (0 * bitCount)) .|. (fi g `unsafeShiftL` (1 * bitCount)) .|. (fi b `unsafeShiftL` (2 * bitCount)) .|. (fi a `unsafeShiftL` (3 * bitCount)) where fi = fromIntegral bitCount = 8 {-# INLINE unpackPixel #-} unpackPixel w = PixelRGBA8 (low w) (low $ w `unsafeShiftR` bitCount) (low $ w `unsafeShiftR` (2 * bitCount)) (low $ w `unsafeShiftR` (3 * bitCount)) where low v = fromIntegral (v .&. 0xFF) bitCount = 8 instance PackeablePixel PixelRGBA16 where type PackedRepresentation PixelRGBA16 = Word64 {-# INLINE packPixel #-} packPixel (PixelRGBA16 r g b a) = (fi r `unsafeShiftL` (0 * bitCount)) .|. (fi g `unsafeShiftL` (1 * bitCount)) .|. (fi b `unsafeShiftL` (2 * bitCount)) .|. (fi a `unsafeShiftL` (3 * bitCount)) where fi = fromIntegral bitCount = 16 {-# INLINE unpackPixel #-} unpackPixel w = PixelRGBA16 (low w) (low $ w `unsafeShiftR` bitCount) (low $ w `unsafeShiftR` (2 * bitCount)) (low $ w `unsafeShiftR` (3 * bitCount)) where low v = fromIntegral (v .&. 0xFFFF) bitCount = 16 instance PackeablePixel PixelCMYK8 where type PackedRepresentation PixelCMYK8 = Word32 {-# INLINE packPixel #-} packPixel (PixelCMYK8 c m y k) = (fi c `unsafeShiftL` (0 * bitCount)) .|. (fi m `unsafeShiftL` (1 * bitCount)) .|. (fi y `unsafeShiftL` (2 * bitCount)) .|. (fi k `unsafeShiftL` (3 * bitCount)) where fi = fromIntegral bitCount = 8 {-# INLINE unpackPixel #-} unpackPixel w = PixelCMYK8 (low w) (low $ w `unsafeShiftR` bitCount) (low $ w `unsafeShiftR` (2 * bitCount)) (low $ w `unsafeShiftR` (3 * bitCount)) where low v = fromIntegral (v .&. 0xFF) bitCount = 8 instance PackeablePixel PixelCMYK16 where type PackedRepresentation PixelCMYK16 = Word64 {-# INLINE packPixel #-} packPixel (PixelCMYK16 c m y k) = (fi c `unsafeShiftL` (0 * bitCount)) .|. (fi m `unsafeShiftL` (1 * bitCount)) .|. (fi y `unsafeShiftL` (2 * bitCount)) .|. (fi k `unsafeShiftL` (3 * bitCount)) where fi = fromIntegral bitCount = 16 {-# INLINE unpackPixel #-} unpackPixel w = PixelCMYK16 (low w) (low $ w `unsafeShiftR` bitCount) (low $ w `unsafeShiftR` (2 * bitCount)) (low $ w `unsafeShiftR` (3 * bitCount)) where low v = fromIntegral (v .&. 0xFFFF) bitCount = 16 instance PackeablePixel PixelYA16 where type PackedRepresentation PixelYA16 = Word32 {-# INLINE packPixel #-} packPixel (PixelYA16 y a) = (fi y `unsafeShiftL` (0 * bitCount)) .|. (fi a `unsafeShiftL` (1 * bitCount)) where fi = fromIntegral bitCount = 16 {-# INLINE unpackPixel #-} unpackPixel w = PixelYA16 (low w) (low $ w `unsafeShiftR` bitCount) where low v = fromIntegral (v .&. 0xFFFF) bitCount = 16 instance PackeablePixel PixelYA8 where type PackedRepresentation PixelYA8 = Word16 {-# INLINE packPixel #-} packPixel (PixelYA8 y a) = (fi y `unsafeShiftL` (0 * bitCount)) .|. (fi a `unsafeShiftL` (1 * bitCount)) where fi = fromIntegral bitCount = 8 {-# INLINE unpackPixel #-} unpackPixel w = PixelYA8 (low w) (low $ w `unsafeShiftR` bitCount) where low v = fromIntegral (v .&. 0xFF) bitCount = 8 -- | This function will fill an image with a simple packeable -- pixel. It will be faster than any unsafeWritePixel. fillImageWith :: ( Pixel px, PackeablePixel px , PrimMonad m , M.Storable (PackedRepresentation px)) => MutableImage (PrimState m) px -> px -> m () fillImageWith img px = M.set converted $ packPixel px where (ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img !packedPtr = castForeignPtr ptr !converted = M.unsafeFromForeignPtr packedPtr s (s2 `div` componentCount px) -- | Fill a packeable pixel between two bounds. unsafeWritePixelBetweenAt :: ( PrimMonad m , Pixel px, PackeablePixel px , M.Storable (PackedRepresentation px)) => MutableImage (PrimState m) px -- ^ Image to write into -> px -- ^ Pixel to write -> Int -- ^ Start index in pixel base component -> Int -- ^ pixel count of pixel to write -> m () unsafeWritePixelBetweenAt img px start count = M.set converted packed where !packed = packPixel px !pixelData = mutableImageData img !toSet = M.slice start count pixelData (ptr, s, s2) = M.unsafeToForeignPtr toSet !packedPtr = castForeignPtr ptr !converted = M.unsafeFromForeignPtr packedPtr s s2 -- | Read a packeable pixel from an image. Equivalent to -- unsafeReadPixel readPackedPixelAt :: forall m px. ( Pixel px, PackeablePixel px , M.Storable (PackedRepresentation px) , PrimMonad m ) => MutableImage (PrimState m) px -- ^ Image to read from -> Int -- ^ Index in (PixelBaseComponent px) count -> m px {-# INLINE readPackedPixelAt #-} readPackedPixelAt img idx = do unpacked <- M.unsafeRead converted (idx `div` compCount) return $ unpackPixel unpacked where !compCount = componentCount (undefined :: px) (ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img !packedPtr = castForeignPtr ptr !converted = M.unsafeFromForeignPtr packedPtr s s2 -- | Write a packeable pixel into an image. equivalent to unsafeWritePixel. writePackedPixelAt :: ( Pixel px, PackeablePixel px , M.Storable (PackedRepresentation px) , PrimMonad m ) => MutableImage (PrimState m) px -- ^ Image to write into -> Int -- ^ Index in (PixelBaseComponent px) count -> px -- ^ Pixel to write -> m () {-# INLINE writePackedPixelAt #-} writePackedPixelAt img idx px = M.unsafeWrite converted (idx `div` compCount) packed where !packed = packPixel px !compCount = componentCount px (ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img !packedPtr = castForeignPtr ptr !converted = M.unsafeFromForeignPtr packedPtr s s2 {-# ANN module "HLint: ignore Reduce duplication" #-}
Chobbes/Juicy.Pixels
src/Codec/Picture/Types.hs
bsd-3-clause
100,337
8
29
33,095
24,338
13,029
11,309
1,683
13
import qualified Data.Map as M import Data.List.Split import System.IO import Control.Monad import System.Exit import System.Posix.Signals import Control.Concurrent import Data.List import Data.Ord (comparing) import System.Process type Database = M.Map String Int main :: IO () main = do putStrLn "Input: " inp <- getLine installHandler keyboardSignal (Catch (do exitSuccess)) Nothing --t1 <- readProcess "python" (["src/twitter.py"] ++ (splitOn " " inp)) "" --print t1 --t2 <- readProcess "sh" (["src/reddit.sh"] ++ (splitOn " " inp)) "" (_, Just so1, _, ph1) <- createProcess (proc "python" (["src/twitter.py"] ++ (splitOn " " inp))){std_out = CreatePipe} (_, Just so2, _, ph2) <- createProcess (proc "sh" (["src/reddit.sh"] ++ (splitOn " " inp))){std_out = CreatePipe} waitForProcess ph1 r1 <- hGetContents so1 r2 <- hGetContents so2 contents1 <- readFile "data/twitter_data.txt" contents2 <- readFile "data/reddit_data.txt" let stringinput = splitOn " " $ contents1 ++ contents2 let s = alterState (M.empty) stringinput mapM_ print $ sortBy (comparing snd) $ M.toList s alterState :: M.Map String Int -> [String] -> M.Map String Int alterState m [] = m alterState m (s:ss) | ((M.lookup s m) == Nothing) = alterState (M.insert s 1 m) ss | otherwise = alterState (M.adjust increment s m) ss increment :: Int -> Int increment a = a + 1 findMax m = go [] Nothing (M.toList m) where go ks _ [] = ks go ks Nothing ((k,v):rest) = go (k:ks) (Just v) rest go ks (Just u) ((k,v):rest) | v < u = go ks (Just u) rest | v > u = go [k] (Just v) rest | otherwise = go (k:ks) (Just v) rest
coghex/bridgemaker
src/Main.hs
bsd-3-clause
1,744
0
15
425
702
354
348
40
3
module Data.Array.Accelerate.BLAS.Internal.Asum where import Data.Array.Accelerate.BLAS.Internal.Common import Data.Array.Accelerate import Data.Array.Accelerate.CUDA.Foreign import qualified Foreign.CUDA.BLAS as BL import Prelude hiding (zipWith, map) cudaAsumF :: Vector Float -> CIO (Scalar Float) cudaAsumF x = do let n = arraySize (arrayShape x) res <- allocScalar xptr <- devVF x resptr <- devSF res liftIO $ BL.withCublas $ \handle -> execute handle n xptr resptr return res where execute h n xp rp = BL.sasum h n xp 1 rp cudaAsumD :: Vector Double -> CIO (Scalar Double) cudaAsumD x = do let n = arraySize (arrayShape x) res <- allocScalar xptr <- devVD x resptr <- devSD res liftIO $ BL.withCublas $ \handle -> execute handle n xptr resptr return res where execute h n xp rp = BL.dasum h n xp 1 rp -- | Returns the sum of the absolute value of the `Float`s -- contained in the vector. sasum :: Acc (Vector Float) -> Acc (Scalar Float) sasum = foreignAcc foreignAsumF pureAsumF where foreignAsumF = CUDAForeignAcc "cudaAsumF" cudaAsumF pureAsumF :: Acc (Vector Float) -> Acc (Scalar Float) pureAsumF = fold (+) 0 . map abs -- | Returns the sum of the absolute value of the `Double`s -- contained in the vector. dasum :: Acc (Vector Double) -> Acc (Scalar Double) dasum = foreignAcc foreignAsumD pureAsumD where foreignAsumD = CUDAForeignAcc "cudaAsumD" cudaAsumD pureAsumD :: Acc (Vector Double) -> Acc (Scalar Double) pureAsumD = fold (+) 0 . map abs
alpmestan/accelerate-blas
src/Data/Array/Accelerate/BLAS/Internal/Asum.hs
bsd-3-clause
1,641
0
12
418
520
262
258
36
1
-- | Folds over the fold family rooted at 'FoldFamily'. module Data.Origami.Internal.Fold( -- * The 'Fold' structure and useful instances Fold(..), idFold, errFold, monadicFold, -- * folding functions foldFoldFamily, foldDataTy, foldDataCase, foldDataField, foldTy ) where import Control.Monad import Data.Origami.Internal.FoldFamily import Language.Haskell.TH ------------------------------------------------------------ -- folds ------------------------------------------------------------ -- | The fold. Bundles up the functions used to replace constructors -- in the fold family. data Fold dataCase dataField dataTy foldFamily ty = Fold { mkAtomic :: ty -> dataField, mkBifunct :: Name -> dataField -> dataField -> dataField, mkDataCase :: Name -> [dataField] -> dataCase, mkDataTy :: Name -> [dataCase] -> dataTy, mkFoldFamily :: [dataTy] -> foldFamily, mkFunct :: Name -> dataField -> dataField, mkNonatomic :: ty -> dataField, mkTrifunct :: Name -> dataField -> dataField -> dataField -> dataField, mkTy :: Name -> ty } -- | The identity 'Fold'. Intended as a base to be modified. idFold :: Fold DataCase DataField DataTy FoldFamily Ty idFold = Fold { mkAtomic = Atomic, mkBifunct = Bifunct, mkDataCase = DataCase, mkDataTy = DataTy, mkFoldFamily = FoldFamily, mkFunct = Funct, mkNonatomic = Nonatomic, mkTrifunct = Trifunct, mkTy = Ty } -- | The error 'Fold'. Intended as a base to be modified. errFold :: String -> Fold dataCase dataField dataTy foldFamily ty errFold str = Fold { mkAtomic = err "mkAtomic", mkBifunct = err "mkBifunct", mkDataCase = err "mkDataCase", mkDataTy = err "mkDataTy", mkFoldFamily = err "mkFoldFamily", mkFunct = err "mkFunct", mkNonatomic = err "mkNonatomic", mkTrifunct = err "mkTrifunct", mkTy = err "mkTy" } where err tag = error (str ++ "." ++ tag) -- | Using the constructors from the base 'Fold', folds monadically in -- a bottom-up, left-to-right manner. monadicFold :: Monad m => Fold dataCase dataField dataTy foldFamily ty -> Fold (m dataCase) (m dataField) (m dataTy) (m foldFamily) (m ty) monadicFold f = Fold { mkAtomic = liftM (mkAtomic f), mkBifunct = liftM2 . mkBifunct f, mkDataCase = \ nm dfs -> do { dfs' <- sequence dfs; return $ mkDataCase f nm dfs' }, mkDataTy = \ nm dcs -> do { dcs' <- sequence dcs; return $ mkDataTy f nm dcs' }, mkFoldFamily = \ dts -> do { dts' <- sequence dts; return $ mkFoldFamily f dts' }, mkFunct = liftM . mkFunct f, mkTrifunct = liftM3 . mkTrifunct f, mkNonatomic = liftM (mkNonatomic f), mkTy = return . mkTy f } ------------------------------------------------------------ -- folds ------------------------------------------------------------ -- | Monadically folds over a 'DataCase' foldDataCase :: Fold dataCase dataField dataTy foldFamily ty -> DataCase -> dataCase foldDataCase f (DataCase nm dfs) = mkDataCase f nm (fmap (foldDataField f) dfs) -- | Monadically folds over a 'DataField' foldDataField :: Fold dataCase dataField dataTy foldFamily ty -> DataField -> dataField foldDataField f (Atomic ty) = mkAtomic f (foldTy f ty) foldDataField f (Nonatomic ty) = mkNonatomic f (foldTy f ty) foldDataField f (Funct nm df) = mkFunct f nm (foldDataField f df) foldDataField f (Bifunct nm df df') = mkBifunct f nm (foldDataField f df) (foldDataField f df') foldDataField f (Trifunct nm df df' df'') = mkTrifunct f nm (foldDataField f df) (foldDataField f df') (foldDataField f df'') -- | Monadically folds over a 'DataTy' foldDataTy :: Fold dataCase dataField dataTy foldFamily ty -> DataTy -> dataTy foldDataTy f (DataTy nm dcs) = mkDataTy f nm (fmap (foldDataCase f) dcs) -- | Monadically folds over a 'FoldFamily' foldFoldFamily :: Fold dataCase dataField dataTy foldFamily ty -> FoldFamily -> foldFamily foldFoldFamily f (FoldFamily dts) = mkFoldFamily f (fmap (foldDataTy f) dts) -- | Monadically folds over a 'FoldTy' foldTy :: Fold dataCase dataField dataTy foldFamily ty -> Ty -> ty foldTy f(Ty nm) = mkTy f nm
nedervold/origami
src/Data/Origami/Internal/Fold.hs
bsd-3-clause
4,617
0
12
1,314
1,159
628
531
88
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} -- -- Safe.hs --- Checked binary packing/unpacking. -- -- Copyright (C) 2015, Galois, Inc. -- All Rights Reserved. -- module Ivory.Serialize.Safe.BigEndian where import Ivory.Language import Ivory.Serialize.Atoms import Ivory.Serialize.PackRep packInto :: (Packable a, ANat len) => Ref s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> ConstRef s2 a -- ^ value -> Ivory ('Effects r b ('Scope s3)) () packInto = packInto' packRep packInto' :: ANat len => PackRep a -- ^ encoding -> Ref s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> ConstRef s2 a -- ^ value -> Ivory ('Effects r b ('Scope s3)) () packInto' rep buf offs val = do assert $ offs + fromIntegral (packSize rep) <=? arrayLen buf packSetBE rep (toCArray buf) offs val packVInto :: (Packable ('Stored a), ANat len, IvoryInit a) => Ref s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> a -- ^ value -> Ivory ('Effects r b ('Scope s2)) () packVInto = packVInto' packRep packVInto' :: (ANat len, IvoryInit a) => PackRep ('Stored a) -- ^ encoding -> Ref s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> a -- ^ value -> Ivory ('Effects r b ('Scope s2)) () packVInto' rep buf offs val = do tmp <- local $ ival val packInto' rep buf offs (constRef tmp) unpackFrom :: (Packable a, ANat len) => ConstRef s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> Ref s2 a -- ^ value -> Ivory ('Effects r b ('Scope s3)) () unpackFrom = unpackFrom' packRep unpackFrom' :: ANat len => PackRep a -- ^ encoding -> ConstRef s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> Ref s2 a -- ^ value -> Ivory ('Effects r b ('Scope s3)) () unpackFrom' rep buf offs val = do assert $ offs + fromIntegral (packSize rep) <=? arrayLen buf packGetBE rep (toCArray buf) offs val unpackVFrom :: (Packable ('Stored a), ANat len, IvoryStore a, IvoryZeroVal a) => ConstRef s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> Ivory ('Effects r b ('Scope s2)) a unpackVFrom = unpackVFrom' packRep unpackVFrom' :: (Packable ('Stored a), ANat len, IvoryStore a, IvoryZeroVal a) => PackRep ('Stored a) -> ConstRef s1 ('Array len ('Stored Uint8)) -- ^ buf -> Uint32 -- ^ offset -> Ivory ('Effects r b ('Scope s2)) a unpackVFrom' rep buf offs = do tmp <- local izero unpackFrom' rep buf offs tmp deref tmp
GaloisInc/ivory
ivory-serialize/src/Ivory/Serialize/Safe/BigEndian.hs
bsd-3-clause
2,794
0
15
839
1,040
525
515
65
1
{-# LANGUAGE DataKinds #-} -- | Inventory management and party cycling. -- TODO: document module Game.LambdaHack.Client.UI.InventoryClient ( Suitability(..) , getGroupItem, getAnyItems, getStoreItem , memberCycle, memberBack, pickLeader , cursorPointerFloor, cursorPointerEnemy , moveCursorHuman, tgtFloorHuman, tgtEnemyHuman, epsIncrHuman, tgtClearHuman , doLook, describeItemC ) where import Prelude () import Prelude.Compat import Control.Exception.Assert.Sugar import Control.Monad (when, void, filterM) import Data.Char (intToDigit) import qualified Data.Char as Char import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import Data.List (findIndex, sortBy, find, nub) import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid import Data.Ord import Data.Text (Text) import qualified Data.Text as T import qualified NLP.Miniutter.English as MU import Game.LambdaHack.Client.CommonClient import Game.LambdaHack.Client.ItemSlot import qualified Game.LambdaHack.Client.Key as K import Game.LambdaHack.Client.MonadClient import Game.LambdaHack.Client.State import Game.LambdaHack.Client.UI.HumanCmd import Game.LambdaHack.Client.UI.KeyBindings import Game.LambdaHack.Client.UI.MonadClientUI import Game.LambdaHack.Client.UI.MsgClient import Game.LambdaHack.Client.UI.WidgetClient import qualified Game.LambdaHack.Common.Ability as Ability import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import Game.LambdaHack.Common.ItemDescription import Game.LambdaHack.Common.ItemStrongest import qualified Game.LambdaHack.Common.Kind as Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.Msg import Game.LambdaHack.Common.Perception import Game.LambdaHack.Common.Point import Game.LambdaHack.Common.Request import Game.LambdaHack.Common.State import Game.LambdaHack.Common.Vector import qualified Game.LambdaHack.Content.ItemKind as IK data ItemDialogState = ISuitable | IAll | INoSuitable | INoAll deriving (Show, Eq) ppItemDialogMode :: ItemDialogMode -> (Text, Text) ppItemDialogMode (MStore cstore) = ppCStore cstore ppItemDialogMode MOwned = ("in", "our possession") ppItemDialogMode MStats = ("among", "strenghts") ppItemDialogModeIn :: ItemDialogMode -> Text ppItemDialogModeIn c = let (tIn, t) = ppItemDialogMode c in tIn <+> t ppItemDialogModeFrom :: ItemDialogMode -> Text ppItemDialogModeFrom c = let (_tIn, t) = ppItemDialogMode c in "from" <+> t storeFromMode :: ItemDialogMode -> CStore storeFromMode c = case c of MStore cstore -> cstore MOwned -> CGround -- needed to decide display mode in textAllAE MStats -> CGround -- needed to decide display mode in textAllAE accessModeBag :: ActorId -> State -> ItemDialogMode -> ItemBag accessModeBag leader s (MStore cstore) = getActorBag leader cstore s accessModeBag leader s MOwned = let fid = bfid $ getActorBody leader s in sharedAllOwnedFid False fid s accessModeBag _ _ MStats = EM.empty -- | Let a human player choose any item from a given group. -- Note that this does not guarantee the chosen item belongs to the group, -- as the player can override the choice. -- Used e.g., for applying and projecting. getGroupItem :: MonadClientUI m => m Suitability -- ^ which items to consider suitable -> Text -- ^ specific prompt for only suitable items -> Text -- ^ generic prompt -> Bool -- ^ whether to enable setting cursor with mouse -> [CStore] -- ^ initial legal modes -> [CStore] -- ^ legal modes after Calm taken into account -> m (SlideOrCmd ((ItemId, ItemFull), ItemDialogMode)) getGroupItem psuit prompt promptGeneric cursor cLegalRaw cLegalAfterCalm = do let dialogState = if cursor then INoSuitable else ISuitable soc <- getFull psuit (\_ _ cCur -> prompt <+> ppItemDialogModeFrom cCur) (\_ _ cCur -> promptGeneric <+> ppItemDialogModeFrom cCur) cursor cLegalRaw cLegalAfterCalm True False dialogState case soc of Left sli -> return $ Left sli Right ([(iid, itemFull)], c) -> return $ Right ((iid, itemFull), c) Right _ -> assert `failure` soc -- | Let the human player choose any item from a list of items -- and let him specify the number of items. -- Used, e.g., for picking up and inventory manipulation. getAnyItems :: MonadClientUI m => m Suitability -- ^ which items to consider suitable -> Text -- ^ specific prompt for only suitable items -> Text -- ^ generic prompt -> [CStore] -- ^ initial legal modes -> [CStore] -- ^ legal modes after Calm taken into account -> Bool -- ^ whether to ask, when the only item -- in the starting mode is suitable -> Bool -- ^ whether to ask for the number of items -> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode)) getAnyItems psuit prompt promptGeneric cLegalRaw cLegalAfterCalm askWhenLone askNumber = do soc <- getFull psuit (\_ _ cCur -> prompt <+> ppItemDialogModeFrom cCur) (\_ _ cCur -> promptGeneric <+> ppItemDialogModeFrom cCur) False cLegalRaw cLegalAfterCalm askWhenLone True ISuitable case soc of Left _ -> return soc Right ([(iid, itemFull)], c) -> do socK <- pickNumber askNumber $ itemK itemFull case socK of Left slides -> return $ Left slides Right k -> return $ Right ([(iid, itemFull{itemK=k})], c) Right _ -> return soc -- | Display all items from a store and let the human player choose any -- or switch to any other store. -- Used, e.g., for viewing inventory and item descriptions. getStoreItem :: MonadClientUI m => (Actor -> [ItemFull] -> ItemDialogMode -> Text) -- ^ how to describe suitable items -> ItemDialogMode -- ^ initial mode -> m (SlideOrCmd ((ItemId, ItemFull), ItemDialogMode)) getStoreItem prompt cInitial = do let allCs = map MStore [CEqp, CInv, CSha] ++ [MOwned] ++ map MStore [CGround, COrgan] ++ [MStats] (pre, rest) = break (== cInitial) allCs post = dropWhile (== cInitial) rest remCs = post ++ pre soc <- getItem (return SuitsEverything) prompt prompt False cInitial remCs True False (cInitial:remCs) ISuitable case soc of Left sli -> return $ Left sli Right ([(iid, itemFull)], c) -> return $ Right ((iid, itemFull), c) Right _ -> assert `failure` soc -- | Let the human player choose a single, preferably suitable, -- item from a list of items. Don't display stores empty for all actors. -- Start with a non-empty store. getFull :: MonadClientUI m => m Suitability -- ^ which items to consider suitable -> (Actor -> [ItemFull] -> ItemDialogMode -> Text) -- ^ specific prompt for only suitable items -> (Actor -> [ItemFull] -> ItemDialogMode -> Text) -- ^ generic prompt -> Bool -- ^ whether to enable setting cursor with mouse -> [CStore] -- ^ initial legal modes -> [CStore] -- ^ legal modes with Calm taken into account -> Bool -- ^ whether to ask, when the only item -- in the starting mode is suitable -> Bool -- ^ whether to permit multiple items as a result -> ItemDialogState -- ^ the dialog state to start in -> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode)) getFull psuit prompt promptGeneric cursor cLegalRaw cLegalAfterCalm askWhenLone permitMulitple initalState = do side <- getsClient sside leader <- getLeaderUI let aidNotEmpty store aid = do bag <- getsState $ getCBag (CActor aid store) return $! not $ EM.null bag partyNotEmpty store = do as <- getsState $ fidActorNotProjAssocs side bs <- mapM (aidNotEmpty store . fst) as return $! or bs mpsuit <- psuit let psuitFun = case mpsuit of SuitsEverything -> const True SuitsNothing _ -> const False SuitsSomething f -> f -- Move the first store that is non-empty for suitable items for this actor -- to the front, if any. getCStoreBag <- getsState $ \s cstore -> getCBag (CActor leader cstore) s let hasThisActor = not . EM.null . getCStoreBag case filter hasThisActor cLegalAfterCalm of [] -> if isNothing (find hasThisActor cLegalRaw) then do let contLegalRaw = map MStore cLegalRaw tLegal = map (MU.Text . ppItemDialogModeIn) contLegalRaw ppLegal = makePhrase [MU.WWxW "nor" tLegal] failWith $ "no items" <+> ppLegal else failSer ItemNotCalm haveThis@(headThisActor : _) -> do itemToF <- itemToFullClient let suitsThisActor store = let bag = getCStoreBag store in any (\(iid, kit) -> psuitFun $ itemToF iid kit) $ EM.assocs bag cThisActor cDef = fromMaybe cDef $ find suitsThisActor haveThis -- Don't display stores totally empty for all actors. cLegal <- filterM partyNotEmpty cLegalRaw let breakStores cInit = let (pre, rest) = break (== cInit) cLegal post = dropWhile (== cInit) rest in (MStore cInit, map MStore $ post ++ pre) -- The last used store may go before even the first nonempty store. lastStore <- getsClient slastStore firstStore <- if lastStore `notElem` cLegalAfterCalm then return $! cThisActor headThisActor else do (itemSlots, organSlots) <- getsClient sslots let lSlots = if lastStore == COrgan then organSlots else itemSlots lastSlot <- getsClient slastSlot case EM.lookup lastSlot lSlots of Nothing -> return $! cThisActor headThisActor Just lastIid -> case EM.lookup lastIid $ getCStoreBag lastStore of Nothing -> return $! cThisActor headThisActor Just kit -> do let lastItemFull = itemToF lastIid kit lastSuits = psuitFun lastItemFull cLast = cThisActor lastStore return $! if lastSuits && cLast /= CGround then lastStore else cLast let (modeFirst, modeRest) = breakStores firstStore getItem psuit prompt promptGeneric cursor modeFirst modeRest askWhenLone permitMulitple (map MStore cLegal) initalState -- | Let the human player choose a single, preferably suitable, -- item from a list of items. getItem :: MonadClientUI m => m Suitability -- ^ which items to consider suitable -> (Actor -> [ItemFull] -> ItemDialogMode -> Text) -- ^ specific prompt for only suitable items -> (Actor -> [ItemFull] -> ItemDialogMode -> Text) -- ^ generic prompt -> Bool -- ^ whether to enable setting cursor with mouse -> ItemDialogMode -- ^ first mode, legal or not -> [ItemDialogMode] -- ^ the (rest of) legal modes -> Bool -- ^ whether to ask, when the only item -- in the starting mode is suitable -> Bool -- ^ whether to permit multiple items as a result -> [ItemDialogMode] -- ^ all legal modes -> ItemDialogState -- ^ the dialog state to start in -> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode)) getItem psuit prompt promptGeneric cursor cCur cRest askWhenLone permitMulitple cLegal initalState = do leader <- getLeaderUI accessCBag <- getsState $ accessModeBag leader let storeAssocs = EM.assocs . accessCBag allAssocs = concatMap storeAssocs (cCur : cRest) case (cRest, allAssocs) of ([], [(iid, k)]) | not askWhenLone -> do itemToF <- itemToFullClient return $ Right ([(iid, itemToF iid k)], cCur) _ -> transition psuit prompt promptGeneric cursor permitMulitple cLegal 0 cCur cRest initalState data DefItemKey m = DefItemKey { defLabel :: Text -- ^ can be undefined if not @defCond@ , defCond :: !Bool , defAction :: K.KM -> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode)) } data Suitability = SuitsEverything | SuitsNothing Msg | SuitsSomething (ItemFull -> Bool) transition :: forall m. MonadClientUI m => m Suitability -> (Actor -> [ItemFull] -> ItemDialogMode -> Text) -> (Actor -> [ItemFull] -> ItemDialogMode -> Text) -> Bool -> Bool -> [ItemDialogMode] -> Int -> ItemDialogMode -> [ItemDialogMode] -> ItemDialogState -> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode)) transition psuit prompt promptGeneric cursor permitMulitple cLegal numPrefix cCur cRest itemDialogState = do let recCall = transition psuit prompt promptGeneric cursor permitMulitple cLegal (itemSlots, organSlots) <- getsClient sslots leader <- getLeaderUI body <- getsState $ getActorBody leader activeItems <- activeItemsClient leader fact <- getsState $ (EM.! bfid body) . sfactionD hs <- partyAfterLeader leader bagAll <- getsState $ \s -> accessModeBag leader s cCur lastSlot <- getsClient slastSlot itemToF <- itemToFullClient Binding{brevMap} <- askBinding mpsuit <- psuit -- when throwing, this sets eps and checks cursor validity (suitsEverything, psuitFun) <- case mpsuit of SuitsEverything -> return (True, const True) SuitsNothing err -> do slides <- promptToSlideshow $ err <+> moreMsg void $ getInitConfirms ColorFull [] $ slides <> toSlideshow Nothing [[]] return (False, const False) -- When throwing, this function takes missile range into accout. SuitsSomething f -> return (False, f) let getSingleResult :: ItemId -> (ItemId, ItemFull) getSingleResult iid = (iid, itemToF iid (bagAll EM.! iid)) getResult :: ItemId -> ([(ItemId, ItemFull)], ItemDialogMode) getResult iid = ([getSingleResult iid], cCur) getMultResult :: [ItemId] -> ([(ItemId, ItemFull)], ItemDialogMode) getMultResult iids = (map getSingleResult iids, cCur) filterP iid kit = psuitFun $ itemToF iid kit bagAllSuit = EM.filterWithKey filterP bagAll isOrgan = cCur == MStore COrgan lSlots = if isOrgan then organSlots else itemSlots bagItemSlotsAll = EM.filter (`EM.member` bagAll) lSlots -- Predicate for slot matching the current prefix, unless the prefix -- is 0, in which case we display all slots, even if they require -- the user to start with number keys to get to them. -- Could be generalized to 1 if prefix 1x exists, etc., but too rare. hasPrefixOpen x _ = slotPrefix x == numPrefix || numPrefix == 0 bagItemSlotsOpen = EM.filterWithKey hasPrefixOpen bagItemSlotsAll hasPrefix x _ = slotPrefix x == numPrefix bagItemSlots = EM.filterWithKey hasPrefix bagItemSlotsOpen bag = EM.fromList $ map (\iid -> (iid, bagAll EM.! iid)) (EM.elems bagItemSlotsOpen) suitableItemSlotsAll = EM.filter (`EM.member` bagAllSuit) lSlots suitableItemSlotsOpen = EM.filterWithKey hasPrefixOpen suitableItemSlotsAll suitableItemSlots = EM.filterWithKey hasPrefix suitableItemSlotsOpen bagSuit = EM.fromList $ map (\iid -> (iid, bagAllSuit EM.! iid)) (EM.elems suitableItemSlotsOpen) (autoDun, autoLvl) = autoDungeonLevel fact multipleSlots = if itemDialogState `elem` [IAll, INoAll] then bagItemSlotsAll else suitableItemSlotsAll keyDefs :: [(K.KM, DefItemKey m)] keyDefs = filter (defCond . snd) $ [ (K.toKM K.NoModifier $ K.Char '?', DefItemKey { defLabel = "?" , defCond = not (EM.null bag) , defAction = \_ -> recCall numPrefix cCur cRest $ case itemDialogState of INoSuitable -> if EM.null bagSuit then IAll else ISuitable ISuitable -> if suitsEverything then INoAll else IAll IAll -> if EM.null bag then INoSuitable else INoAll INoAll -> if suitsEverything then ISuitable else INoSuitable }) , (K.toKM K.NoModifier $ K.Char '/', DefItemKey { defLabel = "/" , defCond = not $ null cRest , defAction = \_ -> do let calmE = calmEnough body activeItems mcCur = filter (`elem` cLegal) [cCur] (cCurAfterCalm, cRestAfterCalm) = case cRest ++ mcCur of c1@(MStore CSha) : c2 : rest | not calmE -> (c2, c1 : rest) [MStore CSha] | not calmE -> assert `failure` cRest c1 : rest -> (c1, rest) [] -> assert `failure` cRest recCall numPrefix cCurAfterCalm cRestAfterCalm itemDialogState }) , (K.toKM K.NoModifier $ K.Char '*', DefItemKey { defLabel = "*" , defCond = permitMulitple && not (EM.null multipleSlots) , defAction = \_ -> let eslots = EM.elems multipleSlots in return $ Right $ getMultResult eslots }) , (K.toKM K.NoModifier K.Return, DefItemKey { defLabel = if lastSlot `EM.member` labelItemSlotsOpen then let l = makePhrase [slotLabel lastSlot] in "RET(" <> l <> ")" -- l is on the screen list else "RET" , defCond = not (EM.null labelItemSlotsOpen) , defAction = \_ -> case EM.lookup lastSlot labelItemSlotsOpen of Just iid -> return $ Right $ getResult iid Nothing -> case EM.minViewWithKey labelItemSlotsOpen of Nothing -> assert `failure` "labelItemSlotsOpen empty" `twith` labelItemSlotsOpen Just ((l, _), _) -> do modifyClient $ \cli -> cli { slastSlot = l , slastStore = storeFromMode cCur } recCall numPrefix cCur cRest itemDialogState }) , let km = M.findWithDefault (K.toKM K.NoModifier K.Tab) MemberCycle brevMap in (km, DefItemKey { defLabel = K.showKM km , defCond = not (cCur == MOwned || autoLvl || not (any (\(_, b) -> blid b == blid body) hs)) , defAction = \_ -> do err <- memberCycle False let !_A = assert (err == mempty `blame` err) () (cCurUpd, cRestUpd) <- legalWithUpdatedLeader cCur cRest recCall numPrefix cCurUpd cRestUpd itemDialogState }) , let km = M.findWithDefault (K.toKM K.NoModifier K.BackTab) MemberBack brevMap in (km, DefItemKey { defLabel = K.showKM km , defCond = not (cCur == MOwned || autoDun || null hs) , defAction = \_ -> do err <- memberBack False let !_A = assert (err == mempty `blame` err) () (cCurUpd, cRestUpd) <- legalWithUpdatedLeader cCur cRest recCall numPrefix cCurUpd cRestUpd itemDialogState }) , let km = M.findWithDefault (K.toKM K.NoModifier (K.KP '/')) TgtFloor brevMap in cursorCmdDef False km tgtFloorHuman , let hackyCmd = Macro "" ["KP_Divide"] -- no keypad, but arrows enough km = M.findWithDefault (K.toKM K.NoModifier K.RightButtonPress) hackyCmd brevMap in cursorCmdDef False km tgtEnemyHuman , let km = M.findWithDefault (K.toKM K.NoModifier (K.KP '*')) TgtEnemy brevMap in cursorCmdDef False km tgtEnemyHuman , let hackyCmd = Macro "" ["KP_Multiply"] -- no keypad, but arrows OK km = M.findWithDefault (K.toKM K.NoModifier K.RightButtonPress) hackyCmd brevMap in cursorCmdDef False km tgtEnemyHuman , let km = M.findWithDefault (K.toKM K.NoModifier K.BackSpace) TgtClear brevMap in cursorCmdDef False km tgtClearHuman ] ++ numberPrefixes ++ [ let plusMinus = K.Char $ if b then '+' else '-' km = M.findWithDefault (K.toKM K.NoModifier plusMinus) (EpsIncr b) brevMap in cursorCmdDef False km (epsIncrHuman b) | b <- [True, False] ] ++ arrows ++ [ let km = M.findWithDefault (K.toKM K.NoModifier K.MiddleButtonPress) CursorPointerEnemy brevMap in cursorCmdDef False km (cursorPointerEnemy False False) , let km = M.findWithDefault (K.toKM K.Shift K.MiddleButtonPress) CursorPointerFloor brevMap in cursorCmdDef False km (cursorPointerFloor False False) , let km = M.findWithDefault (K.toKM K.NoModifier K.RightButtonPress) TgtPointerEnemy brevMap in cursorCmdDef True km (cursorPointerEnemy True True) ] prefixCmdDef d = (K.toKM K.NoModifier $ K.Char (intToDigit d), DefItemKey { defLabel = "" , defCond = True , defAction = \_ -> recCall (10 * numPrefix + d) cCur cRest itemDialogState }) numberPrefixes = map prefixCmdDef [0..9] cursorCmdDef verbose km cmd = (km, DefItemKey { defLabel = "keypad, mouse" , defCond = cursor && EM.null bagFiltered , defAction = \_ -> do look <- cmd when verbose $ void $ getInitConfirms ColorFull [] $ look <> toSlideshow Nothing [[]] recCall numPrefix cCur cRest itemDialogState }) arrows = let kCmds = K.moveBinding False False (`moveCursorHuman` 1) (`moveCursorHuman` 10) in map (uncurry $ cursorCmdDef False) kCmds lettersDef :: DefItemKey m lettersDef = DefItemKey { defLabel = slotRange $ EM.keys labelItemSlots , defCond = True , defAction = \K.KM{key} -> case key of K.Char l -> case EM.lookup (SlotChar numPrefix l) bagItemSlots of Nothing -> assert `failure` "unexpected slot" `twith` (l, bagItemSlots) Just iid -> return $ Right $ getResult iid _ -> assert `failure` "unexpected key:" `twith` K.showKey key } (labelItemSlotsOpen, labelItemSlots, bagFiltered, promptChosen) = case itemDialogState of ISuitable -> (suitableItemSlotsOpen, suitableItemSlots, bagSuit, prompt body activeItems cCur <> ":") IAll -> (bagItemSlotsOpen, bagItemSlots, bag, promptGeneric body activeItems cCur <> ":") INoSuitable -> (suitableItemSlotsOpen, suitableItemSlots, EM.empty, prompt body activeItems cCur <> ":") INoAll -> (bagItemSlotsOpen, bagItemSlots, EM.empty, promptGeneric body activeItems cCur <> ":") io <- case cCur of MStats -> statsOverlay leader -- TODO: describe each stat when selected _ -> itemOverlay (storeFromMode cCur) (blid body) bagFiltered runDefItemKey keyDefs lettersDef io bagItemSlots promptChosen statsOverlay :: MonadClient m => ActorId -> m Overlay statsOverlay aid = do b <- getsState $ getActorBody aid activeItems <- activeItemsClient aid let block n = n + if braced b then 50 else 0 prSlot :: (IK.EqpSlot, Int -> Text) -> Text prSlot (eqpSlot, f) = let fullText t = " " <> makePhrase [ MU.Text $ T.justifyLeft 22 ' ' $ IK.slotName eqpSlot , MU.Text t ] <> " " valueText = f $ sumSlotNoFilter eqpSlot activeItems in fullText valueText -- Some values can be negative, for others 0 is equivalent but shorter. slotList = -- TODO: [IK.EqpSlotAddHurtMelee..IK.EqpSlotAddLight] [ (IK.EqpSlotAddHurtMelee, \t -> tshow t <> "%") -- TODO: not applicable right now, IK.EqpSlotAddHurtRanged , (IK.EqpSlotAddArmorMelee, \t -> "[" <> tshow (block t) <> "%]") , (IK.EqpSlotAddArmorRanged, \t -> "{" <> tshow (block t) <> "%}") , (IK.EqpSlotAddMaxHP, \t -> tshow $ max 0 t) , (IK.EqpSlotAddMaxCalm, \t -> tshow $ max 0 t) , (IK.EqpSlotAddSpeed, \t -> tshow (max 0 t) <> "m/10s") , (IK.EqpSlotAddSight, \t -> tshow (max 0 $ min (fromIntegral $ bcalm b `div` (5 * oneM)) t) <> "m") , (IK.EqpSlotAddSmell, \t -> tshow (max 0 t) <> "m") , (IK.EqpSlotAddLight, \t -> tshow (max 0 t) <> "m") ] skills = sumSkills activeItems -- TODO: are negative total skills meaningful? prAbility :: Ability.Ability -> Text prAbility ability = let fullText t = " " <> makePhrase [ MU.Text $ T.justifyLeft 22 ' ' $ "ability" <+> tshow ability , MU.Text t ] <> " " valueText = tshow $ EM.findWithDefault 0 ability skills in fullText valueText abilityList = [minBound..maxBound] return $! toOverlay $ map prSlot slotList ++ map prAbility abilityList legalWithUpdatedLeader :: MonadClientUI m => ItemDialogMode -> [ItemDialogMode] -> m (ItemDialogMode, [ItemDialogMode]) legalWithUpdatedLeader cCur cRest = do leader <- getLeaderUI let newLegal = cCur : cRest -- not updated in any way yet b <- getsState $ getActorBody leader activeItems <- activeItemsClient leader let calmE = calmEnough b activeItems legalAfterCalm = case newLegal of c1@(MStore CSha) : c2 : rest | not calmE -> (c2, c1 : rest) [MStore CSha] | not calmE -> (MStore CGround, newLegal) c1 : rest -> (c1, rest) [] -> assert `failure` (cCur, cRest) return legalAfterCalm runDefItemKey :: MonadClientUI m => [(K.KM, DefItemKey m)] -> DefItemKey m -> Overlay -> EM.EnumMap SlotChar ItemId -> Text -> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode)) runDefItemKey keyDefs lettersDef io labelItemSlots prompt = do let itemKeys = let slotKeys = map (K.Char . slotChar) (EM.keys labelItemSlots) defKeys = map fst keyDefs in map (K.toKM K.NoModifier) slotKeys ++ defKeys choice = let letterRange = defLabel lettersDef keyLabelsRaw = letterRange : map (defLabel . snd) keyDefs keyLabels = filter (not . T.null) keyLabelsRaw in "[" <> T.intercalate ", " (nub keyLabels) akm <- displayChoiceUI (prompt <+> choice) io itemKeys case akm of Left slides -> failSlides slides Right km -> case lookup km{K.pointer=Nothing} keyDefs of Just keyDef -> defAction keyDef km Nothing -> defAction lettersDef km pickNumber :: MonadClientUI m => Bool -> Int -> m (SlideOrCmd Int) pickNumber askNumber kAll = do let kDefault = kAll if askNumber && kAll > 1 then do let tDefault = tshow kDefault kbound = min 9 kAll kprompt = "Choose number [1-" <> tshow kbound <> ", RET(" <> tDefault <> ")" kkeys = map (K.toKM K.NoModifier) $ map (K.Char . Char.intToDigit) [1..kbound] ++ [K.Return] kkm <- displayChoiceUI kprompt emptyOverlay kkeys case kkm of Left slides -> failSlides slides Right K.KM{key} -> case key of K.Char l -> return $ Right $ Char.digitToInt l K.Return -> return $ Right kDefault _ -> assert `failure` "unexpected key:" `twith` kkm else return $ Right kAll -- | Switches current member to the next on the level, if any, wrapping. memberCycle :: MonadClientUI m => Bool -> m Slideshow memberCycle verbose = do side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD leader <- getLeaderUI body <- getsState $ getActorBody leader hs <- partyAfterLeader leader let autoLvl = snd $ autoDungeonLevel fact case filter (\(_, b) -> blid b == blid body) hs of _ | autoLvl -> failMsg $ showReqFailure NoChangeLvlLeader [] -> failMsg "cannot pick any other member on this level" (np, b) : _ -> do success <- pickLeader verbose np let !_A = assert (success `blame` "same leader" `twith` (leader, np, b)) () return mempty -- | Switches current member to the previous in the whole dungeon, wrapping. memberBack :: MonadClientUI m => Bool -> m Slideshow memberBack verbose = do side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD leader <- getLeaderUI hs <- partyAfterLeader leader let (autoDun, autoLvl) = autoDungeonLevel fact case reverse hs of _ | autoDun -> failMsg $ showReqFailure NoChangeDunLeader _ | autoLvl -> failMsg $ showReqFailure NoChangeLvlLeader [] -> failMsg "no other member in the party" (np, b) : _ -> do success <- pickLeader verbose np let !_A = assert (success `blame` "same leader" `twith` (leader, np, b)) () return mempty partyAfterLeader :: MonadStateRead m => ActorId -> m [(ActorId, Actor)] partyAfterLeader leader = do faction <- getsState $ bfid . getActorBody leader allA <- getsState $ EM.assocs . sactorD let factionA = filter (\(_, body) -> not (bproj body) && bfid body == faction) allA hs = sortBy (comparing keySelected) factionA i = fromMaybe (-1) $ findIndex ((== leader) . fst) hs (lt, gt) = (take i hs, drop (i + 1) hs) return $! gt ++ lt -- | Select a faction leader. False, if nothing to do. pickLeader :: MonadClientUI m => Bool -> ActorId -> m Bool pickLeader verbose aid = do leader <- getLeaderUI stgtMode <- getsClient stgtMode if leader == aid then return False -- already picked else do pbody <- getsState $ getActorBody aid let !_A = assert (not (bproj pbody) `blame` "projectile chosen as the leader" `twith` (aid, pbody)) () -- Even if it's already the leader, give his proper name, not 'you'. let subject = partActor pbody when verbose $ msgAdd $ makeSentence [subject, "picked as a leader"] -- Update client state. s <- getState modifyClient $ updateLeader aid s -- Move the cursor, if active, to the new level. case stgtMode of Nothing -> return () Just _ -> modifyClient $ \cli -> cli {stgtMode = Just $ TgtMode $ blid pbody} -- Inform about items, etc. lookMsg <- lookAt False "" True (bpos pbody) aid "" when verbose $ msgAdd lookMsg return True cursorPointerFloor :: MonadClientUI m => Bool -> Bool -> m Slideshow cursorPointerFloor verbose addMoreMsg = do km <- getsClient slastKM lidV <- viewedLevel Level{lxsize, lysize} <- getLevel lidV case K.pointer km of Just(newPos@Point{..}) | px >= 0 && py >= 0 && px < lxsize && py < lysize -> do let scursor = TPoint lidV newPos modifyClient $ \cli -> cli {scursor, stgtMode = Just $ TgtMode lidV} if verbose then doLook addMoreMsg else do displayPush "" -- flash the targeting line and path displayDelay -- for a bit longer return mempty _ -> do stopPlayBack return mempty cursorPointerEnemy :: MonadClientUI m => Bool -> Bool -> m Slideshow cursorPointerEnemy verbose addMoreMsg = do km <- getsClient slastKM lidV <- viewedLevel Level{lxsize, lysize} <- getLevel lidV case K.pointer km of Just(newPos@Point{..}) | px >= 0 && py >= 0 && px < lxsize && py < lysize -> do bsAll <- getsState $ actorAssocs (const True) lidV let scursor = case find (\(_, m) -> bpos m == newPos) bsAll of Just (im, _) -> TEnemy im True Nothing -> TPoint lidV newPos modifyClient $ \cli -> cli {scursor, stgtMode = Just $ TgtMode lidV} if verbose then doLook addMoreMsg else do displayPush "" -- flash the targeting line and path displayDelay -- for a bit longer return mempty _ -> do stopPlayBack return mempty -- | Move the cursor. Assumes targeting mode. moveCursorHuman :: MonadClientUI m => Vector -> Int -> m Slideshow moveCursorHuman dir n = do leader <- getLeaderUI stgtMode <- getsClient stgtMode let lidV = maybe (assert `failure` leader) tgtLevelId stgtMode Level{lxsize, lysize} <- getLevel lidV lpos <- getsState $ bpos . getActorBody leader scursor <- getsClient scursor cursorPos <- cursorToPos let cpos = fromMaybe lpos cursorPos shiftB pos = shiftBounded lxsize lysize pos dir newPos = iterate shiftB cpos !! n if newPos == cpos then failMsg "never mind" else do let tgt = case scursor of TVector{} -> TVector $ newPos `vectorToFrom` lpos _ -> TPoint lidV newPos modifyClient $ \cli -> cli {scursor = tgt} doLook False -- | Cycle targeting mode. Do not change position of the cursor, -- switch among things at that position. tgtFloorHuman :: MonadClientUI m => m Slideshow tgtFloorHuman = do lidV <- viewedLevel leader <- getLeaderUI lpos <- getsState $ bpos . getActorBody leader cursorPos <- cursorToPos scursor <- getsClient scursor stgtMode <- getsClient stgtMode bsAll <- getsState $ actorAssocs (const True) lidV let cursor = fromMaybe lpos cursorPos tgt = case scursor of _ | isNothing stgtMode -> -- first key press: keep target scursor TEnemy a True -> TEnemy a False TEnemy{} -> TPoint lidV cursor TEnemyPos{} -> TPoint lidV cursor TPoint{} -> TVector $ cursor `vectorToFrom` lpos TVector{} -> -- For projectiles, we pick here the first that would be picked -- by '*', so that all other projectiles on the tile come next, -- without any intervening actors from other tiles. case find (\(_, m) -> Just (bpos m) == cursorPos) bsAll of Just (im, _) -> TEnemy im True Nothing -> TPoint lidV cursor modifyClient $ \cli -> cli {scursor = tgt, stgtMode = Just $ TgtMode lidV} doLook False tgtEnemyHuman :: MonadClientUI m => m Slideshow tgtEnemyHuman = do lidV <- viewedLevel leader <- getLeaderUI lpos <- getsState $ bpos . getActorBody leader cursorPos <- cursorToPos scursor <- getsClient scursor stgtMode <- getsClient stgtMode side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD bsAll <- getsState $ actorAssocs (const True) lidV let ordPos (_, b) = (chessDist lpos $ bpos b, bpos b) dbs = sortBy (comparing ordPos) bsAll pickUnderCursor = -- switch to the actor under cursor, if any let i = fromMaybe (-1) $ findIndex ((== cursorPos) . Just . bpos . snd) dbs in splitAt i dbs (permitAnyActor, (lt, gt)) = case scursor of TEnemy a permit | isJust stgtMode -> -- pick next enemy let i = fromMaybe (-1) $ findIndex ((== a) . fst) dbs in (permit, splitAt (i + 1) dbs) TEnemy a permit -> -- first key press, retarget old enemy let i = fromMaybe (-1) $ findIndex ((== a) . fst) dbs in (permit, splitAt i dbs) TEnemyPos _ _ _ permit -> (permit, pickUnderCursor) _ -> (False, pickUnderCursor) -- the sensible default is only-foes gtlt = gt ++ lt isEnemy b = isAtWar fact (bfid b) && not (bproj b) && bhp b > 0 lf = filter (isEnemy . snd) gtlt tgt | permitAnyActor = case gtlt of (a, _) : _ -> TEnemy a True [] -> scursor -- no actors in sight, stick to last target | otherwise = case lf of (a, _) : _ -> TEnemy a False [] -> scursor -- no seen foes in sight, stick to last target -- Register the chosen enemy, to pick another on next invocation. modifyClient $ \cli -> cli {scursor = tgt, stgtMode = Just $ TgtMode lidV} doLook False -- | Tweak the @eps@ parameter of the targeting digital line. epsIncrHuman :: MonadClientUI m => Bool -> m Slideshow epsIncrHuman b = do stgtMode <- getsClient stgtMode if isJust stgtMode then do modifyClient $ \cli -> cli {seps = seps cli + if b then 1 else -1} return mempty else failMsg "never mind" -- no visual feedback, so no sense tgtClearHuman :: MonadClientUI m => m Slideshow tgtClearHuman = do leader <- getLeaderUI tgt <- getsClient $ getTarget leader case tgt of Just _ -> do modifyClient $ updateTarget leader (const Nothing) return mempty Nothing -> do scursorOld <- getsClient scursor b <- getsState $ getActorBody leader let scursor = case scursorOld of TEnemy _ permit -> TEnemy leader permit TEnemyPos _ _ _ permit -> TEnemy leader permit TPoint{} -> TPoint (blid b) (bpos b) TVector{} -> TVector (Vector 0 0) modifyClient $ \cli -> cli {scursor} doLook False -- | Perform look around in the current position of the cursor. -- Normally expects targeting mode and so that a leader is picked. doLook :: MonadClientUI m => Bool -> m Slideshow doLook addMoreMsg = do Kind.COps{cotile=Kind.Ops{ouniqGroup}} <- getsState scops let unknownId = ouniqGroup "unknown space" stgtMode <- getsClient stgtMode case stgtMode of Nothing -> return mempty Just tgtMode -> do leader <- getLeaderUI let lidV = tgtLevelId tgtMode lvl <- getLevel lidV cursorPos <- cursorToPos per <- getPerFid lidV b <- getsState $ getActorBody leader let p = fromMaybe (bpos b) cursorPos canSee = ES.member p (totalVisible per) inhabitants <- if canSee then getsState $ posToActors p lidV else return [] seps <- getsClient seps mnewEps <- makeLine False b p seps itemToF <- itemToFullClient let aims = isJust mnewEps enemyMsg = case inhabitants of [] -> "" (_, body) : rest -> -- Even if it's the leader, give his proper name, not 'you'. let subjects = map (partActor . snd) inhabitants subject = MU.WWandW subjects verb = "be here" desc = if not (null rest) -- many actors, only list names then "" else case itemDisco $ itemToF (btrunk body) (1, []) of Nothing -> "" -- no details, only show the name Just ItemDisco{itemKind} -> IK.idesc itemKind pdesc = if desc == "" then "" else "(" <> desc <> ")" in makeSentence [MU.SubjectVerbSg subject verb] <+> pdesc vis | lvl `at` p == unknownId = "that is" | not canSee = "you remember" | not aims = "you are aware of" | otherwise = "you see" -- Show general info about current position. lookMsg <- lookAt True vis canSee p leader enemyMsg {- targeting is kind of a menu (or at least mode), so this is menu inside a menu, which is messy, hence disabled until UI overhauled: -- Check if there's something lying around at current position. is <- getsState $ getCBag $ CFloor lidV p if EM.size is <= 2 then promptToSlideshow lookMsg else do msgAdd lookMsg -- TODO: do not add to history floorItemOverlay lidV p -} promptToSlideshow $ lookMsg <+> if addMoreMsg then moreMsg else "" -- | Create a list of item names. _floorItemOverlay :: MonadClientUI m => LevelId -> Point -> m (SlideOrCmd (RequestTimed 'Ability.AbMoveItem)) _floorItemOverlay _lid _p = describeItemC MOwned {-CFloor lid p-} describeItemC :: MonadClientUI m => ItemDialogMode -> m (SlideOrCmd (RequestTimed 'Ability.AbMoveItem)) describeItemC c = do let subject = partActor verbSha body activeItems = if calmEnough body activeItems then "notice" else "paw distractedly" prompt body activeItems c2 = let (tIn, t) = ppItemDialogMode c2 in case c2 of MStore CGround -> -- TODO: variant for actors without (unwounded) feet makePhrase [ MU.Capitalize $ MU.SubjectVerbSg (subject body) "notice" , MU.Text "at" , MU.WownW (MU.Text $ bpronoun body) $ MU.Text "feet" ] MStore CSha -> makePhrase [ MU.Capitalize $ MU.SubjectVerbSg (subject body) (verbSha body activeItems) , MU.Text tIn , MU.Text t ] MStore COrgan -> makePhrase [ MU.Capitalize $ MU.SubjectVerbSg (subject body) "feel" , MU.Text tIn , MU.WownW (MU.Text $ bpronoun body) $ MU.Text t ] MOwned -> makePhrase [ MU.Capitalize $ MU.SubjectVerbSg (subject body) "recall" , MU.Text tIn , MU.Text t ] MStats -> makePhrase [ MU.Capitalize $ MU.SubjectVerbSg (subject body) "estimate" , MU.WownW (MU.Text $ bpronoun body) $ MU.Text t ] _ -> makePhrase [ MU.Capitalize $ MU.SubjectVerbSg (subject body) "see" , MU.Text tIn , MU.WownW (MU.Text $ bpronoun body) $ MU.Text t ] ggi <- getStoreItem prompt c case ggi of Right ((iid, itemFull), c2) -> do leader <- getLeaderUI b <- getsState $ getActorBody leader activeItems <- activeItemsClient leader let calmE = calmEnough b activeItems localTime <- getsState $ getLocalTime (blid b) let io = itemDesc (storeFromMode c2) localTime itemFull case c2 of MStore COrgan -> do let symbol = jsymbol (itemBase itemFull) blurb | symbol == '+' = "drop temporary conditions" | otherwise = "amputate organs" -- TODO: also forbid on the server, except in special cases. Left <$> overlayToSlideshow ("Can't" <+> blurb <> ", but here's the description.") io MStore CSha | not calmE -> Left <$> overlayToSlideshow "Not enough calm to take items from the shared stash, but here's the description." io MStore fromCStore -> do let prompt2 = "Where to move the item?" eqpFree = eqpFreeN b fstores :: [(K.Key, (CStore, Text))] fstores = filter ((/= fromCStore) . fst . snd) $ [ (K.Char 'p', (CInv, "inventory 'p'ack")) ] ++ [ (K.Char 'e', (CEqp, "'e'quipment")) | eqpFree > 0 ] ++ [ (K.Char 's', (CSha, "shared 's'tash")) | calmE ] ++ [ (K.Char 'g', (CGround, "'g'round")) ] choice = "[" <> T.intercalate ", " (map (snd . snd) fstores) keys = map (K.toKM K.NoModifier . K.Char) "epsg" akm <- displayChoiceUI (prompt2 <+> choice) io keys case akm of Left slides -> failSlides slides Right km -> do case lookup (K.key km) fstores of Nothing -> return $ Left mempty -- canceled Just (toCStore, _) -> do let k = itemK itemFull kToPick | toCStore == CEqp = min eqpFree k | otherwise = k socK <- pickNumber True kToPick case socK of Left slides -> return $ Left slides Right kChosen -> return $ Right $ ReqMoveItems [(iid, kChosen, fromCStore, toCStore)] MOwned -> do -- We can't move items from MOwned, because different copies may come -- from different stores and we can't guess player's intentions. found <- getsState $ findIid leader (bfid b) iid let !_A = assert (not (null found) `blame` ggi) () let ppLoc (_, CSha) = MU.Text $ ppCStoreIn CSha <+> "of the party" ppLoc (b2, store) = MU.Text $ ppCStoreIn store <+> "of" <+> bname b2 foundTexts = map ppLoc found prompt2 = makeSentence ["The item is", MU.WWandW foundTexts] Left <$> overlayToSlideshow prompt2 io MStats -> assert `failure` ggi Left slides -> return $ Left slides
beni55/LambdaHack
Game/LambdaHack/Client/UI/InventoryClient.hs
bsd-3-clause
46,219
0
35
14,834
12,572
6,409
6,163
-1
-1
module GroupLens where import Control.Parallel.Strategies import Data.Function (on) import Data.List (groupBy) import qualified Data.Map as M import System.Environment (getArgs) import qualified Data.ByteString.Char8 as B import qualified SlopeTwo as S readRating :: B.ByteString -> (Int, Int, Int) readRating line = maybe (error "impossible") id $ do (userId, a) <- B.readInt line (movieId, b) <- B.readInt (B.drop 2 a) (rating, _) <- B.readInt (B.drop 2 b) return (userId, movieId, rating) newtype Fap k a = Fap {unfap :: M.Map k a} instance NFData (Fap k a) where rnf (Fap m) = rnf (M.size m) main = do (ratingFile:userId:movieIds) <- getArgs contents <- B.readFile ratingFile let rating = {-# SCC "rating" #-} groupBy compareUser . map readRating . B.lines $ contents compareUser (a,_,_) (b,_,_) = a == b asRating (_,b,c) = (b, fromIntegral c) foo = S.update S.empty . parMap rwhnf ( {-# SCC "fl" #-} M.fromList . map asRating) $ rating print (S.size foo)
binesiyu/ifl
examples/ch24/GroupLens.hs
mit
1,075
0
15
267
433
235
198
25
1
instance X => Y where f = g where g = h
itchyny/vim-haskell-indent
test/instance/instance_newline.out.hs
mit
54
0
7
26
24
12
12
-1
-1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Main -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Main (main) where import Test.Tasty import Test.AWS.SDB import Test.AWS.SDB.Internal main :: IO () main = defaultMain $ testGroup "SDB" [ testGroup "tests" tests , testGroup "fixtures" fixtures ]
olorin/amazonka
amazonka-sdb/test/Main.hs
mpl-2.0
522
0
8
103
76
47
29
9
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fa-IR"> <title>Import Urls | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>نمایه</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>جستجو</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>
denniskniep/zap-extensions
addOns/importurls/src/main/javahelp/org/zaproxy/zap/extension/importurls/resources/help_fa_IR/helpset_fa_IR.hs
apache-2.0
981
82
64
159
409
207
202
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module Web.Twitter.Conduit.Types ( TWToken (..) , TWInfo (..) , twitterOAuth , setCredential ) where import Data.Default import Data.Typeable (Typeable) import Web.Authenticate.OAuth import Network.HTTP.Conduit data TWToken = TWToken { twOAuth :: OAuth , twCredential :: Credential } deriving (Show, Read, Eq, Typeable) instance Default TWToken where def = TWToken twitterOAuth (Credential []) data TWInfo = TWInfo { twToken :: TWToken , twProxy :: Maybe Proxy } deriving (Show, Read, Eq, Typeable) instance Default TWInfo where def = TWInfo { twToken = def , twProxy = Nothing } twitterOAuth :: OAuth twitterOAuth = def { oauthServerName = "twitter" , oauthRequestUri = "https://api.twitter.com/oauth/request_token" , oauthAccessTokenUri = "https://api.twitter.com/oauth/access_token" , oauthAuthorizeUri = "https://api.twitter.com/oauth/authorize" , oauthConsumerKey = error "You MUST specify oauthConsumerKey parameter." , oauthConsumerSecret = error "You MUST specify oauthConsumerSecret parameter." , oauthSignatureMethod = HMACSHA1 , oauthCallback = Nothing } -- | set OAuth keys and Credentials to TWInfo. -- -- >>> let proxy = Proxy "localhost" 8080 -- >>> let twinfo = def { twProxy = Just proxy } -- >>> let oauth = twitterOAuth { oauthConsumerKey = "consumer_key", oauthConsumerSecret = "consumer_secret" } -- >>> let credential = Credential [("oauth_token","...")] -- >>> let twinfo2 = setCredential oauth credential twinfo -- >>> oauthConsumerKey . twOAuth . twToken $ twinfo2 -- "consumer_key" -- >>> twProxy twinfo2 == Just proxy -- True setCredential :: OAuth -> Credential -> TWInfo -> TWInfo setCredential oa cred env = TWInfo { twToken = TWToken oa cred , twProxy = twProxy env }
Javran/twitter-conduit
Web/Twitter/Conduit/Types.hs
bsd-2-clause
1,913
0
9
424
322
194
128
39
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ExistentialQuantification #-} -- | -- Module : Numeric.Series -- Copyright : (c) 2016 Alexey Khudyakov -- License : BSD3 -- -- Maintainer : alexey.skladnoy@gmail.com, bos@serpentine.com -- Stability : experimental -- Portability : portable -- -- Functions for working with infinite sequences. In particular -- summation of series and evaluation of continued fractions. module Numeric.Series ( -- * Data type for infinite sequences. Sequence(..) -- * Constructors , enumSequenceFrom , enumSequenceFromStep , scanSequence -- * Summation of series , sumSeries , sumPowerSeries , sequenceToList -- * Evaluation of continued fractions , evalContFractionB ) where import Control.Applicative import Data.List (unfoldr) import Numeric.MathFunctions.Constants (m_epsilon) ---------------------------------------------------------------- -- | Infinite series. It's represented as opaque state and step -- function. data Sequence a = forall s. Sequence s (s -> (a,s)) instance Functor Sequence where fmap f (Sequence s0 step) = Sequence s0 (\s -> let (a,s') = step s in (f a, s')) {-# INLINE fmap #-} instance Applicative Sequence where pure a = Sequence () (\() -> (a,())) Sequence sA fA <*> Sequence sB fB = Sequence (sA,sB) $ \(!sa,!sb) -> let (a,sa') = fA sa (b,sb') = fB sb in (a b, (sa',sb')) {-# INLINE pure #-} {-# INLINE (<*>) #-} -- | Elementwise operations with sequences instance Num a => Num (Sequence a) where (+) = liftA2 (+) (*) = liftA2 (*) (-) = liftA2 (-) {-# INLINE (+) #-} {-# INLINE (*) #-} {-# INLINE (-) #-} abs = fmap abs signum = fmap signum fromInteger = pure . fromInteger {-# INLINE abs #-} {-# INLINE signum #-} {-# INLINE fromInteger #-} -- | Elementwise operations with sequences instance Fractional a => Fractional (Sequence a) where (/) = liftA2 (/) recip = fmap recip fromRational = pure . fromRational {-# INLINE (/) #-} {-# INLINE recip #-} {-# INLINE fromRational #-} ---------------------------------------------------------------- -- Constructors ---------------------------------------------------------------- -- | @enumSequenceFrom x@ generate sequence: -- -- \[ a_n = x + n \] enumSequenceFrom :: Num a => a -> Sequence a enumSequenceFrom i = Sequence i (\n -> (n,n+1)) {-# INLINE enumSequenceFrom #-} -- | @enumSequenceFromStep x d@ generate sequence: -- -- \[ a_n = x + nd \] enumSequenceFromStep :: Num a => a -> a -> Sequence a enumSequenceFromStep n d = Sequence n (\i -> (i,i+d)) {-# INLINE enumSequenceFromStep #-} -- | Analog of 'scanl' for sequence. scanSequence :: (b -> a -> b) -> b -> Sequence a -> Sequence b {-# INLINE scanSequence #-} scanSequence f b0 (Sequence s0 step) = Sequence (b0,s0) $ \(b,s) -> let (a,s') = step s b' = f b a in (b,(b',s')) ---------------------------------------------------------------- -- Evaluation of series ---------------------------------------------------------------- -- | Calculate sum of series -- -- \[ \sum_{i=0}^\infty a_i \] -- -- Summation is stopped when -- -- \[ a_{n+1} < \varepsilon\sum_{i=0}^n a_i \] -- -- where ε is machine precision ('m_epsilon') sumSeries :: Sequence Double -> Double {-# INLINE sumSeries #-} sumSeries (Sequence sInit step) = go x0 s0 where (x0,s0) = step sInit go x s | abs (d/x) >= m_epsilon = go x' s' | otherwise = x' where (d,s') = step s x' = x + d -- | Calculate sum of series -- -- \[ \sum_{i=0}^\infty x^ia_i \] -- -- Calculation is stopped when next value in series is less than -- ε·sum. sumPowerSeries :: Double -> Sequence Double -> Double sumPowerSeries x ser = sumSeries $ liftA2 (*) (scanSequence (*) 1 (pure x)) ser {-# INLINE sumPowerSeries #-} -- | Convert series to infinite list sequenceToList :: Sequence a -> [a] sequenceToList (Sequence s f) = unfoldr (Just . f) s ---------------------------------------------------------------- -- Evaluation of continued fractions ---------------------------------------------------------------- -- | -- Evaluate continued fraction using modified Lentz algorithm. -- Sequence contain pairs (a[i],b[i]) which form following expression: -- -- \[ -- b_0 + \frac{a_1}{b_1+\frac{a_2}{b_2+\frac{a_3}{b_3 + \cdots}}} -- \] -- -- Modified Lentz algorithm is described in Numerical recipes 5.2 -- "Evaluation of Continued Fractions" evalContFractionB :: Sequence (Double,Double) -> Double {-# INLINE evalContFractionB #-} evalContFractionB (Sequence sInit step) = let ((_,b0),s0) = step sInit f0 = maskZero b0 in go f0 f0 0 s0 where tiny = 1e-60 maskZero 0 = tiny maskZero x = x go f c d s | abs (delta - 1) >= m_epsilon = go f' c' d' s' | otherwise = f' where ((a,b),s') = step s d' = recip $ maskZero $ b + a*d c' = maskZero $ b + a/c delta = c'*d' f' = f*delta
bos/math-functions
Numeric/Series.hs
bsd-2-clause
5,101
0
13
1,169
1,193
670
523
89
2
-- | Bomb other users, a fun IRC game {-# LANGUAGE OverloadedStrings #-} module NumberSix.Handlers.Bomb ( handler ) where -------------------------------------------------------------------------------- import Control.Applicative ((<$>)) import Control.Concurrent.MVar import Control.Monad.Trans (liftIO) import Data.Foldable (forM_) import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T -------------------------------------------------------------------------------- import NumberSix.Bang import NumberSix.Handlers.Insult (randomInsult) import NumberSix.Irc import NumberSix.Message import NumberSix.Util import NumberSix.Util.Error import NumberSix.Util.Irc -------------------------------------------------------------------------------- -- | A bomb is assigned through (target, sender) type Bomb = (Text, Text) -------------------------------------------------------------------------------- -- | Bomb state: each channel may have a bomb assigned type BombState = Map Text Bomb -------------------------------------------------------------------------------- handler :: UninitializedHandler handler = makeHandlerWith "Bomb" [bombHook, passHook] $ liftIO $ newMVar M.empty -------------------------------------------------------------------------------- bombHook :: MVar BombState -> Irc () bombHook mvar = onBangCommand "!bomb" $ do updateBomb mvar $ \b -> case b of Just _ -> (write =<< liftIO randomError) >> return b Nothing -> do (target, _) <- breakWord <$> getBangCommandText sender <- getSender nick <- getNick if target == sender || target == nick then do liftIO randomInsult >>= kick sender return Nothing else do forkIrc $ bomb intervals return $ Just (target, sender) where -- Recursively counts down bomb [] = updateBomb mvar $ \b -> do forM_ b $ \(target, _) -> do write $ "The bomb explodes. Pieces of " <> target <> " fly in all directions." kick target "Ka-boom" return Nothing bomb (x : xs) = do updateBomb mvar $ \b -> do forM_ b $ \(target, _) -> write $ "Bomb attached to " <> target <> ", blowing up in " <> T.pack (show $ sum $ x : xs) <> " seconds." return b sleep x bomb xs intervals = [20, 5, 5] -------------------------------------------------------------------------------- -- | Pass the bomb! passHook :: MVar BombState -> Irc () passHook mvar = onBangCommand "!pass" $ do sender <- getSender (text, _) <- breakWord <$> getBangCommandText updateBomb mvar $ \bomb -> case bomb of Nothing -> return Nothing Just (target, attacker) | sender ==? target -> do let newTarget = if T.null text then attacker else text write $ sender <> " passes the bomb to " <> newTarget <> "!" return $ Just (newTarget, sender) -- Nothing changes | otherwise -> return $ Just (target, attacker) -------------------------------------------------------------------------------- -- | Utility, execute a certain action with (target, attacker) updateBomb :: MVar BombState -> (Maybe Bomb -> Irc (Maybe Bomb)) -> Irc () updateBomb mvar f = do m <- liftIO $ takeMVar mvar chan <- getChannel x <- f (M.lookup chan m) liftIO $ putMVar mvar $ case x of Just x' -> M.insert chan x' m Nothing -> M.delete chan m
itkovian/number-six
src/NumberSix/Handlers/Bomb.hs
bsd-3-clause
3,961
0
21
1,234
910
468
442
74
4
{-# LANGUAGE OverloadedStrings #-} import Criterion.Main import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Char8 import Blaze.ByteString.Builder.Enumerator import Data.Monoid import qualified Data.Enumerator as E import Data.Enumerator (($$)) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.IORef import Control.Monad.IO.Class import Control.Monad (foldM) import Data.List (foldl') row = mconcat [ fromByteString "<tr>" , mconcat $ map go [1..100] , fromByteString "</tr>" ] where go i = mconcat [ fromByteString "<td>" , fromString $ show i , fromByteString "</td>" ] table = mconcat [ fromByteString "<table>" , mconcat $ replicate 1000 row , fromByteString "</table>" ] main = defaultMain [ bgroup "ioref" [ bench "pure" $ do x <- newIORef (0 :: Int) let go bs = do x' <- readIORef x writeIORef x $ x' + S.length bs mapM_ go $ L.toChunks $ toLazyByteString table readIORef x , bench "enumeratee" $ do x <- newIORef (0 :: Int) let iter = do mbs <- E.head case mbs of Nothing -> return () Just bs -> do x' <- liftIO $ readIORef x liftIO $ writeIORef x $ x' + S.length bs iter E.run_ $ E.enumList 1 [table] $$ E.joinI $ builderToByteString $$ iter readIORef x ] , bgroup "accum" [ let go i bs = i + S.length bs in bench "pure" $ flip nf table $ foldl' go 0 . L.toChunks . toLazyByteString , bench "enumeratee" $ do let go i bs = i + S.length bs E.run_ $ E.enumList 1 [table] $$ E.joinI $ builderToByteString $$ E.liftFoldL' go 0 :: IO Int ] ]
meiersi/blaze-builder-enumerator
bench/pure-enum.hs
bsd-3-clause
2,016
0
25
766
609
304
305
55
2
{-# LANGUAGE Safe #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE UnboxedTuples #-} module Dep05 where import GHC.Arr bad1 = unsafeArray bad2 = fill bad3 = done bad4 = unsafeThawSTArray
sdiehl/ghc
testsuite/tests/safeHaskell/unsafeLibs/Dep05.hs
bsd-3-clause
204
0
4
35
32
21
11
9
1
module ImportHiding where import ImportList1.A hiding (y) import ImportList1.B hiding (x) main :: Fay () main = do print x print y
beni55/fay
tests/ImportHiding.hs
bsd-3-clause
137
0
7
28
53
29
24
7
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>Import/Export</title> <maps> <homeID>exim</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/exim/src/main/javahelp/help_ur_PK/helpset_ur_PK.hs
apache-2.0
959
77
67
155
408
207
201
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ro-RO"> <title>Reveal | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/reveal/src/main/javahelp/org/zaproxy/zap/extension/reveal/resources/help_ro_RO/helpset_ro_RO.hs
apache-2.0
967
78
66
158
411
208
203
-1
-1
-- | A description of the platform we're compiling for. -- module Platform ( Platform(..), Arch(..), OS(..), ArmISA(..), ArmISAExt(..), ArmABI(..), PPC_64ABI(..), target32Bit, isARM, osElfTarget, osMachOTarget, platformUsesFrameworks, platformBinariesAreStaticLibs, ) where -- | Contains enough information for the native code generator to emit -- code for this platform. data Platform = Platform { platformArch :: Arch, platformOS :: OS, -- Word size in bytes (i.e. normally 4 or 8, -- for 32bit and 64bit platforms respectively) platformWordSize :: {-# UNPACK #-} !Int, platformUnregisterised :: Bool, platformHasGnuNonexecStack :: Bool, platformHasIdentDirective :: Bool, platformHasSubsectionsViaSymbols :: Bool, platformIsCrossCompiling :: Bool } deriving (Read, Show, Eq) -- | Architectures that the native code generator knows about. -- TODO: It might be nice to extend these constructors with information -- about what instruction set extensions an architecture might support. -- data Arch = ArchUnknown | ArchX86 | ArchX86_64 | ArchPPC | ArchPPC_64 { ppc_64ABI :: PPC_64ABI } | ArchSPARC | ArchARM { armISA :: ArmISA , armISAExt :: [ArmISAExt] , armABI :: ArmABI } | ArchARM64 | ArchAlpha | ArchMipseb | ArchMipsel | ArchJavaScript deriving (Read, Show, Eq) isARM :: Arch -> Bool isARM (ArchARM {}) = True isARM ArchARM64 = True isARM _ = False -- | Operating systems that the native code generator knows about. -- Having OSUnknown should produce a sensible default, but no promises. data OS = OSUnknown | OSLinux | OSDarwin | OSiOS | OSSolaris2 | OSMinGW32 | OSFreeBSD | OSDragonFly | OSOpenBSD | OSNetBSD | OSKFreeBSD | OSHaiku | OSOsf3 | OSQNXNTO | OSAndroid deriving (Read, Show, Eq) -- | ARM Instruction Set Architecture, Extensions and ABI -- data ArmISA = ARMv5 | ARMv6 | ARMv7 deriving (Read, Show, Eq) data ArmISAExt = VFPv2 | VFPv3 | VFPv3D16 | NEON | IWMMX2 deriving (Read, Show, Eq) data ArmABI = SOFT | SOFTFP | HARD deriving (Read, Show, Eq) -- | PowerPC 64-bit ABI -- data PPC_64ABI = ELF_V1 | ELF_V2 deriving (Read, Show, Eq) -- | This predicate tells us whether the platform is 32-bit. target32Bit :: Platform -> Bool target32Bit p = platformWordSize p == 4 -- | This predicate tells us whether the OS supports ELF-like shared libraries. osElfTarget :: OS -> Bool osElfTarget OSLinux = True osElfTarget OSFreeBSD = True osElfTarget OSDragonFly = True osElfTarget OSOpenBSD = True osElfTarget OSNetBSD = True osElfTarget OSSolaris2 = True osElfTarget OSDarwin = False osElfTarget OSiOS = False osElfTarget OSMinGW32 = False osElfTarget OSKFreeBSD = True osElfTarget OSHaiku = True osElfTarget OSOsf3 = False -- I don't know if this is right, but as -- per comment below it's safe osElfTarget OSQNXNTO = False osElfTarget OSAndroid = True osElfTarget OSUnknown = False -- Defaulting to False is safe; it means don't rely on any -- ELF-specific functionality. It is important to have a default for -- portability, otherwise we have to answer this question for every -- new platform we compile on (even unreg). -- | This predicate tells us whether the OS support Mach-O shared libraries. osMachOTarget :: OS -> Bool osMachOTarget OSDarwin = True osMachOTarget _ = False osUsesFrameworks :: OS -> Bool osUsesFrameworks OSDarwin = True osUsesFrameworks OSiOS = True osUsesFrameworks _ = False platformUsesFrameworks :: Platform -> Bool platformUsesFrameworks = osUsesFrameworks . platformOS osBinariesAreStaticLibs :: OS -> Bool osBinariesAreStaticLibs OSiOS = True osBinariesAreStaticLibs _ = False platformBinariesAreStaticLibs :: Platform -> Bool platformBinariesAreStaticLibs = osBinariesAreStaticLibs . platformOS
urbanslug/ghc
compiler/utils/Platform.hs
bsd-3-clause
4,498
0
9
1,416
750
444
306
117
1
{-# LANGUAGE PatternGuards #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.StackSet -- Copyright : (c) Don Stewart 2007 -- License : BSD3-style (see LICENSE) -- -- Maintainer : dons@galois.com -- Stability : experimental -- Portability : portable, Haskell 98 -- module XMonad.StackSet ( -- * Introduction -- $intro -- ** The Zipper -- $zipper -- ** Xinerama support -- $xinerama -- ** Master and Focus -- $focus StackSet(..), Workspace(..), Screen(..), Stack(..), RationalRect(..), -- * Construction -- $construction new, view, greedyView, -- * Xinerama operations -- $xinerama lookupWorkspace, screens, workspaces, allWindows, currentTag, -- * Operations on the current stack -- $stackOperations peek, index, integrate, integrate', differentiate, focusUp, focusDown, focusUp', focusDown', focusMaster, focusWindow, tagMember, renameTag, ensureTags, member, findTag, mapWorkspace, mapLayout, -- * Modifying the stackset -- $modifyStackset insertUp, delete, delete', filter, -- * Setting the master window -- $settingMW swapUp, swapDown, swapMaster, shiftMaster, modify, modify', float, sink, -- needed by users -- * Composite operations -- $composite shift, shiftWin, -- for testing abort ) where import Prelude hiding (filter) import Data.Maybe (listToMaybe,isJust,fromMaybe) import qualified Data.List as L (deleteBy,find,splitAt,filter,nub) import Data.List ( (\\) ) import qualified Data.Map as M (Map,insert,delete,empty) -- $intro -- -- The 'StackSet' data type encodes a window manager abstraction. The -- window manager is a set of virtual workspaces. On each workspace is a -- stack of windows. A given workspace is always current, and a given -- window on each workspace has focus. The focused window on the current -- workspace is the one which will take user input. It can be visualised -- as follows: -- -- > Workspace { 0*} { 1 } { 2 } { 3 } { 4 } -- > -- > Windows [1 [] [3* [6*] [] -- > ,2*] ,4 -- > ,5] -- -- Note that workspaces are indexed from 0, windows are numbered -- uniquely. A '*' indicates the window on each workspace that has -- focus, and which workspace is current. -- $zipper -- -- We encode all the focus tracking directly in the data structure, with a 'zipper': -- -- A Zipper is essentially an `updateable' and yet pure functional -- cursor into a data structure. Zipper is also a delimited -- continuation reified as a data structure. -- -- The Zipper lets us replace an item deep in a complex data -- structure, e.g., a tree or a term, without an mutation. The -- resulting data structure will share as much of its components with -- the old structure as possible. -- -- Oleg Kiselyov, 27 Apr 2005, haskell\@, "Zipper as a delimited continuation" -- -- We use the zipper to keep track of the focused workspace and the -- focused window on each workspace, allowing us to have correct focus -- by construction. We closely follow Huet's original implementation: -- -- G. Huet, /Functional Pearl: The Zipper/, -- 1997, J. Functional Programming 75(5):549-554. -- and: -- R. Hinze and J. Jeuring, /Functional Pearl: The Web/. -- -- and Conor McBride's zipper differentiation paper. -- Another good reference is: -- -- The Zipper, Haskell wikibook -- $xinerama -- Xinerama in X11 lets us view multiple virtual workspaces -- simultaneously. While only one will ever be in focus (i.e. will -- receive keyboard events), other workspaces may be passively -- viewable. We thus need to track which virtual workspaces are -- associated (viewed) on which physical screens. To keep track of -- this, 'StackSet' keeps separate lists of visible but non-focused -- workspaces, and non-visible workspaces. -- $focus -- -- Each stack tracks a focused item, and for tiling purposes also tracks -- a 'master' position. The connection between 'master' and 'focus' -- needs to be well defined, particularly in relation to 'insert' and -- 'delete'. -- ------------------------------------------------------------------------ -- | -- A cursor into a non-empty list of workspaces. -- -- We puncture the workspace list, producing a hole in the structure -- used to track the currently focused workspace. The two other lists -- that are produced are used to track those workspaces visible as -- Xinerama screens, and those workspaces not visible anywhere. data StackSet i l a sid sd = StackSet { current :: !(Screen i l a sid sd) -- ^ currently focused workspace , visible :: [Screen i l a sid sd] -- ^ non-focused workspaces, visible in xinerama , hidden :: [Workspace i l a] -- ^ workspaces not visible anywhere , floating :: M.Map a RationalRect -- ^ floating windows } deriving (Show, Read, Eq) -- | Visible workspaces, and their Xinerama screens. data Screen i l a sid sd = Screen { workspace :: !(Workspace i l a) , screen :: !sid , screenDetail :: !sd } deriving (Show, Read, Eq) -- | -- A workspace is just a tag, a layout, and a stack. -- data Workspace i l a = Workspace { tag :: !i, layout :: l, stack :: Maybe (Stack a) } deriving (Show, Read, Eq) -- | A structure for window geometries data RationalRect = RationalRect Rational Rational Rational Rational deriving (Show, Read, Eq) -- | -- A stack is a cursor onto a window list. -- The data structure tracks focus by construction, and -- the master window is by convention the top-most item. -- Focus operations will not reorder the list that results from -- flattening the cursor. The structure can be envisaged as: -- -- > +-- master: < '7' > -- > up | [ '2' ] -- > +--------- [ '3' ] -- > focus: < '4' > -- > dn +----------- [ '8' ] -- -- A 'Stack' can be viewed as a list with a hole punched in it to make -- the focused position. Under the zipper\/calculus view of such -- structures, it is the differentiation of a [a], and integrating it -- back has a natural implementation used in 'index'. -- data Stack a = Stack { focus :: !a -- focused thing in this set , up :: [a] -- clowns to the left , down :: [a] } -- jokers to the right deriving (Show, Read, Eq) -- | this function indicates to catch that an error is expected abort :: String -> a abort x = error $ "xmonad: StackSet: " ++ x -- --------------------------------------------------------------------- -- $construction -- | /O(n)/. Create a new stackset, of empty stacks, with given tags, -- with physical screens whose descriptions are given by 'm'. The -- number of physical screens (@length 'm'@) should be less than or -- equal to the number of workspace tags. The first workspace in the -- list will be current. -- -- Xinerama: Virtual workspaces are assigned to physical screens, starting at 0. -- new :: (Integral s) => l -> [i] -> [sd] -> StackSet i l a s sd new l wids m | not (null wids) && length m <= length wids && not (null m) = StackSet cur visi unseen M.empty where (seen,unseen) = L.splitAt (length m) $ map (\i -> Workspace i l Nothing) wids (cur:visi) = [ Screen i s sd | (i, s, sd) <- zip3 seen [0..] m ] -- now zip up visibles with their screen id new _ _ _ = abort "non-positive argument to StackSet.new" -- | -- /O(w)/. Set focus to the workspace with index \'i\'. -- If the index is out of range, return the original 'StackSet'. -- -- Xinerama: If the workspace is not visible on any Xinerama screen, it -- becomes the current screen. If it is in the visible list, it becomes -- current. view :: (Eq s, Eq i) => i -> StackSet i l a s sd -> StackSet i l a s sd view i s | i == currentTag s = s -- current | Just x <- L.find ((i==).tag.workspace) (visible s) -- if it is visible, it is just raised = s { current = x, visible = current s : L.deleteBy (equating screen) x (visible s) } | Just x <- L.find ((i==).tag) (hidden s) -- must be hidden then -- if it was hidden, it is raised on the xine screen currently used = s { current = (current s) { workspace = x } , hidden = workspace (current s) : L.deleteBy (equating tag) x (hidden s) } | otherwise = s -- not a member of the stackset where equating f = \x y -> f x == f y -- 'Catch'ing this might be hard. Relies on monotonically increasing -- workspace tags defined in 'new' -- -- and now tags are not monotonic, what happens here? -- | -- Set focus to the given workspace. If that workspace does not exist -- in the stackset, the original workspace is returned. If that workspace is -- 'hidden', then display that workspace on the current screen, and move the -- current workspace to 'hidden'. If that workspace is 'visible' on another -- screen, the workspaces of the current screen and the other screen are -- swapped. greedyView :: (Eq s, Eq i) => i -> StackSet i l a s sd -> StackSet i l a s sd greedyView w ws | any wTag (hidden ws) = view w ws | (Just s) <- L.find (wTag . workspace) (visible ws) = ws { current = (current ws) { workspace = workspace s } , visible = s { workspace = workspace (current ws) } : L.filter (not . wTag . workspace) (visible ws) } | otherwise = ws where wTag = (w == ) . tag -- --------------------------------------------------------------------- -- $xinerama -- | Find the tag of the workspace visible on Xinerama screen 'sc'. -- 'Nothing' if screen is out of bounds. lookupWorkspace :: Eq s => s -> StackSet i l a s sd -> Maybe i lookupWorkspace sc w = listToMaybe [ tag i | Screen i s _ <- current w : visible w, s == sc ] -- --------------------------------------------------------------------- -- $stackOperations -- | -- The 'with' function takes a default value, a function, and a -- StackSet. If the current stack is Nothing, 'with' returns the -- default value. Otherwise, it applies the function to the stack, -- returning the result. It is like 'maybe' for the focused workspace. -- with :: b -> (Stack a -> b) -> StackSet i l a s sd -> b with dflt f = maybe dflt f . stack . workspace . current -- | -- Apply a function, and a default value for 'Nothing', to modify the current stack. -- modify :: Maybe (Stack a) -> (Stack a -> Maybe (Stack a)) -> StackSet i l a s sd -> StackSet i l a s sd modify d f s = s { current = (current s) { workspace = (workspace (current s)) { stack = with d f s }}} -- | -- Apply a function to modify the current stack if it isn't empty, and we don't -- want to empty it. -- modify' :: (Stack a -> Stack a) -> StackSet i l a s sd -> StackSet i l a s sd modify' f = modify Nothing (Just . f) -- | -- /O(1)/. Extract the focused element of the current stack. -- Return 'Just' that element, or 'Nothing' for an empty stack. -- peek :: StackSet i l a s sd -> Maybe a peek = with Nothing (return . focus) -- | -- /O(n)/. Flatten a 'Stack' into a list. -- integrate :: Stack a -> [a] integrate (Stack x l r) = reverse l ++ x : r -- | -- /O(n)/ Flatten a possibly empty stack into a list. integrate' :: Maybe (Stack a) -> [a] integrate' = maybe [] integrate -- | -- /O(n)/. Turn a list into a possibly empty stack (i.e., a zipper): -- the first element of the list is current, and the rest of the list -- is down. differentiate :: [a] -> Maybe (Stack a) differentiate [] = Nothing differentiate (x:xs) = Just $ Stack x [] xs -- | -- /O(n)/. 'filter p s' returns the elements of 's' such that 'p' evaluates to -- 'True'. Order is preserved, and focus moves as described for 'delete'. -- filter :: (a -> Bool) -> Stack a -> Maybe (Stack a) filter p (Stack f ls rs) = case L.filter p (f:rs) of f':rs' -> Just $ Stack f' (L.filter p ls) rs' -- maybe move focus down [] -> case L.filter p ls of -- filter back up f':ls' -> Just $ Stack f' ls' [] -- else up [] -> Nothing -- | -- /O(s)/. Extract the stack on the current workspace, as a list. -- The order of the stack is determined by the master window -- it will be -- the head of the list. The implementation is given by the natural -- integration of a one-hole list cursor, back to a list. -- index :: StackSet i l a s sd -> [a] index = with [] integrate -- | -- /O(1), O(w) on the wrapping case/. -- -- focusUp, focusDown. Move the window focus up or down the stack, -- wrapping if we reach the end. The wrapping should model a 'cycle' -- on the current stack. The 'master' window, and window order, -- are unaffected by movement of focus. -- -- swapUp, swapDown, swap the neighbour in the stack ordering, wrapping -- if we reach the end. Again the wrapping model should 'cycle' on -- the current stack. -- focusUp, focusDown, swapUp, swapDown :: StackSet i l a s sd -> StackSet i l a s sd focusUp = modify' focusUp' focusDown = modify' focusDown' swapUp = modify' swapUp' swapDown = modify' (reverseStack . swapUp' . reverseStack) -- | Variants of 'focusUp' and 'focusDown' that work on a -- 'Stack' rather than an entire 'StackSet'. focusUp', focusDown' :: Stack a -> Stack a focusUp' (Stack t (l:ls) rs) = Stack l ls (t:rs) focusUp' (Stack t [] rs) = Stack x xs [] where (x:xs) = reverse (t:rs) focusDown' = reverseStack . focusUp' . reverseStack swapUp' :: Stack a -> Stack a swapUp' (Stack t (l:ls) rs) = Stack t ls (l:rs) swapUp' (Stack t [] rs) = Stack t (reverse rs) [] -- | reverse a stack: up becomes down and down becomes up. reverseStack :: Stack a -> Stack a reverseStack (Stack t ls rs) = Stack t rs ls -- -- | /O(1) on current window, O(n) in general/. Focus the window 'w', -- and set its workspace as current. -- focusWindow :: (Eq s, Eq a, Eq i) => a -> StackSet i l a s sd -> StackSet i l a s sd focusWindow w s | Just w == peek s = s | otherwise = fromMaybe s $ do n <- findTag w s return $ until ((Just w ==) . peek) focusUp (view n s) -- | Get a list of all screens in the 'StackSet'. screens :: StackSet i l a s sd -> [Screen i l a s sd] screens s = current s : visible s -- | Get a list of all workspaces in the 'StackSet'. workspaces :: StackSet i l a s sd -> [Workspace i l a] workspaces s = workspace (current s) : map workspace (visible s) ++ hidden s -- | Get a list of all windows in the 'StackSet' in no particular order allWindows :: Eq a => StackSet i l a s sd -> [a] allWindows = L.nub . concatMap (integrate' . stack) . workspaces -- | Get the tag of the currently focused workspace. currentTag :: StackSet i l a s sd -> i currentTag = tag . workspace . current -- | Is the given tag present in the 'StackSet'? tagMember :: Eq i => i -> StackSet i l a s sd -> Bool tagMember t = elem t . map tag . workspaces -- | Rename a given tag if present in the 'StackSet'. renameTag :: Eq i => i -> i -> StackSet i l a s sd -> StackSet i l a s sd renameTag o n = mapWorkspace rename where rename w = if tag w == o then w { tag = n } else w -- | Ensure that a given set of workspace tags is present by renaming -- existing workspaces and\/or creating new hidden workspaces as -- necessary. ensureTags :: Eq i => l -> [i] -> StackSet i l a s sd -> StackSet i l a s sd ensureTags l allt st = et allt (map tag (workspaces st) \\ allt) st where et [] _ s = s et (i:is) rn s | i `tagMember` s = et is rn s et (i:is) [] s = et is [] (s { hidden = Workspace i l Nothing : hidden s }) et (i:is) (r:rs) s = et is rs $ renameTag r i s -- | Map a function on all the workspaces in the 'StackSet'. mapWorkspace :: (Workspace i l a -> Workspace i l a) -> StackSet i l a s sd -> StackSet i l a s sd mapWorkspace f s = s { current = updScr (current s) , visible = map updScr (visible s) , hidden = map f (hidden s) } where updScr scr = scr { workspace = f (workspace scr) } -- | Map a function on all the layouts in the 'StackSet'. mapLayout :: (l -> l') -> StackSet i l a s sd -> StackSet i l' a s sd mapLayout f (StackSet v vs hs m) = StackSet (fScreen v) (map fScreen vs) (map fWorkspace hs) m where fScreen (Screen ws s sd) = Screen (fWorkspace ws) s sd fWorkspace (Workspace t l s) = Workspace t (f l) s -- | /O(n)/. Is a window in the 'StackSet'? member :: Eq a => a -> StackSet i l a s sd -> Bool member a s = isJust (findTag a s) -- | /O(1) on current window, O(n) in general/. -- Return 'Just' the workspace tag of the given window, or 'Nothing' -- if the window is not in the 'StackSet'. findTag :: Eq a => a -> StackSet i l a s sd -> Maybe i findTag a s = listToMaybe [ tag w | w <- workspaces s, has a (stack w) ] where has _ Nothing = False has x (Just (Stack t l r)) = x `elem` (t : l ++ r) -- --------------------------------------------------------------------- -- $modifyStackset -- | -- /O(n)/. (Complexity due to duplicate check). Insert a new element -- into the stack, above the currently focused element. The new -- element is given focus; the previously focused element is moved -- down. -- -- If the element is already in the stackset, the original stackset is -- returned unmodified. -- -- Semantics in Huet's paper is that insert doesn't move the cursor. -- However, we choose to insert above, and move the focus. -- insertUp :: Eq a => a -> StackSet i l a s sd -> StackSet i l a s sd insertUp a s = if member a s then s else insert where insert = modify (Just $ Stack a [] []) (\(Stack t l r) -> Just $ Stack a l (t:r)) s -- insertDown :: a -> StackSet i l a s sd -> StackSet i l a s sd -- insertDown a = modify (Stack a [] []) $ \(Stack t l r) -> Stack a (t:l) r -- Old semantics, from Huet. -- > w { down = a : down w } -- | -- /O(1) on current window, O(n) in general/. Delete window 'w' if it exists. -- There are 4 cases to consider: -- -- * delete on an 'Nothing' workspace leaves it Nothing -- -- * otherwise, try to move focus to the down -- -- * otherwise, try to move focus to the up -- -- * otherwise, you've got an empty workspace, becomes 'Nothing' -- -- Behaviour with respect to the master: -- -- * deleting the master window resets it to the newly focused window -- -- * otherwise, delete doesn't affect the master. -- delete :: (Ord a, Eq s) => a -> StackSet i l a s sd -> StackSet i l a s sd delete w = sink w . delete' w -- | Only temporarily remove the window from the stack, thereby not destroying special -- information saved in the 'Stackset' delete' :: (Eq a, Eq s) => a -> StackSet i l a s sd -> StackSet i l a s sd delete' w s = s { current = removeFromScreen (current s) , visible = map removeFromScreen (visible s) , hidden = map removeFromWorkspace (hidden s) } where removeFromWorkspace ws = ws { stack = stack ws >>= filter (/=w) } removeFromScreen scr = scr { workspace = removeFromWorkspace (workspace scr) } ------------------------------------------------------------------------ -- | Given a window, and its preferred rectangle, set it as floating -- A floating window should already be managed by the 'StackSet'. float :: Ord a => a -> RationalRect -> StackSet i l a s sd -> StackSet i l a s sd float w r s = s { floating = M.insert w r (floating s) } -- | Clear the floating status of a window sink :: Ord a => a -> StackSet i l a s sd -> StackSet i l a s sd sink w s = s { floating = M.delete w (floating s) } ------------------------------------------------------------------------ -- $settingMW -- | /O(s)/. Set the master window to the focused window. -- The old master window is swapped in the tiling order with the focused window. -- Focus stays with the item moved. swapMaster :: StackSet i l a s sd -> StackSet i l a s sd swapMaster = modify' $ \c -> case c of Stack _ [] _ -> c -- already master. Stack t ls rs -> Stack t [] (xs ++ x : rs) where (x:xs) = reverse ls -- natural! keep focus, move current to the top, move top to current. -- | /O(s)/. Set the master window to the focused window. -- The other windows are kept in order and shifted down on the stack, as if you -- just hit mod-shift-k a bunch of times. -- Focus stays with the item moved. shiftMaster :: StackSet i l a s sd -> StackSet i l a s sd shiftMaster = modify' $ \c -> case c of Stack _ [] _ -> c -- already master. Stack t ls rs -> Stack t [] (reverse ls ++ rs) -- | /O(s)/. Set focus to the master window. focusMaster :: StackSet i l a s sd -> StackSet i l a s sd focusMaster = modify' $ \c -> case c of Stack _ [] _ -> c Stack t ls rs -> Stack x [] (xs ++ t : rs) where (x:xs) = reverse ls -- -- --------------------------------------------------------------------- -- $composite -- | /O(w)/. shift. Move the focused element of the current stack to stack -- 'n', leaving it as the focused element on that stack. The item is -- inserted above the currently focused element on that workspace. -- The actual focused workspace doesn't change. If there is no -- element on the current stack, the original stackSet is returned. -- shift :: (Ord a, Eq s, Eq i) => i -> StackSet i l a s sd -> StackSet i l a s sd shift n s = maybe s (\w -> shiftWin n w s) (peek s) -- | /O(n)/. shiftWin. Searches for the specified window 'w' on all workspaces -- of the stackSet and moves it to stack 'n', leaving it as the focused -- element on that stack. The item is inserted above the currently -- focused element on that workspace. -- The actual focused workspace doesn't change. If the window is not -- found in the stackSet, the original stackSet is returned. shiftWin :: (Ord a, Eq a, Eq s, Eq i) => i -> a -> StackSet i l a s sd -> StackSet i l a s sd shiftWin n w s = case findTag w s of Just from | n `tagMember` s && n /= from -> go from s _ -> s where go from = onWorkspace n (insertUp w) . onWorkspace from (delete' w) onWorkspace :: (Eq i, Eq s) => i -> (StackSet i l a s sd -> StackSet i l a s sd) -> (StackSet i l a s sd -> StackSet i l a s sd) onWorkspace n f s = view (currentTag s) . f . view n $ s
atupal/xmonad-mirror
xmonad/src/XMonad/StackSet.hs
mit
22,645
0
14
5,650
5,114
2,768
2,346
192
4
main = putStrLn (case False of True -> "Hello!" _ -> "Ney!")
seereason/ghcjs
test/fay/caseWildcard.hs
mit
100
0
9
51
28
14
14
3
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Safe #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.OldList -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- This legacy module provides access to the list-specialised operations -- of "Data.List". This module may go away again in future GHC versions and -- is provided as transitional tool to access some of the list-specialised -- operations that had to be generalised due to the implementation of the -- <https://wiki.haskell.org/Foldable_Traversable_In_Prelude Foldable/Traversable-in-Prelude Proposal (FTP)>. -- -- If the operations needed are available in "GHC.List", it's -- recommended to avoid importing this module and use "GHC.List" -- instead for now. -- -- @since 4.8.0.0 ----------------------------------------------------------------------------- module GHC.OldList (module Data.OldList) where import Data.OldList
tolysz/prepare-ghcjs
spec-lts8/base/GHC/OldList.hs
bsd-3-clause
1,120
0
5
160
43
36
7
4
0
module Network.Gazelle.Login ( login, loginRoute ) where import Data.Text (Text) import Network.API.Builder import Network.HTTP.Client import Network.HTTP.Types.Method import Network.Gazelle.Types loginRoute :: Text -> Text -> Route loginRoute user pass = Route { urlPieces = [], urlParams = [ "username" =. user , "password" =. pass ], httpMethod = renderStdMethod POST } login :: Monad m => Text -> Text -> GazelleT m CookieJar login user pass = receiveRoute $ loginRoute user pass instance Receivable CookieJar where receive = return . responseCookieJar
mr/gazelle
src/Network/Gazelle/Login.hs
mit
604
0
8
127
173
98
75
18
1
module Main where import qualified Language.BrainFuck as B import qualified Language.ElementaryArithmetic as E import qualified Language.WhiteSpace as W import System.Environment main :: IO () main = do (lang:filePath:_) <- getArgs let interpFile | lang == "-ws" || lang == "--whitespace" = W.interpFile | lang == "-bf" || lang == "--brainfuck" = B.interpFile | lang == "-ea" || lang == "--arithmetic" = E.interpFile | otherwise = error $ "Invalid language" in interpFile filePath
Alaya-in-Matrix/Anjelica
src/Main.hs
mit
587
0
16
178
162
85
77
13
1
{-# OPTIONS_GHC -Wno-unused-imports #-} {-# OPTIONS_GHC -Wno-dodgy-exports #-} {-# OPTIONS_GHC -Wno-unused-matches #-} {-# OPTIONS_GHC -Wno-orphans #-} {-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} {-# OPTIONS_GHC -Wno-name-shadowing #-} module Capnp.Gen.ById.Xa93fc509624c72d9.New(module Capnp.Gen.Capnp.Schema.New) where import Capnp.Gen.Capnp.Schema.New import qualified Prelude as Std_ import qualified Data.Word as Std_ import qualified Data.Int as Std_ import Prelude ((<$>), (<*>), (>>=))
zenhack/haskell-capnp
gen/lib/Capnp/Gen/ById/Xa93fc509624c72d9/New.hs
mit
505
0
5
49
76
59
17
12
0
-- Taken from Microsoft's Bond module Language.Swift.Util where import Data.Monoid sepEndBy :: (Monoid a, Eq a) => a -> (t -> a) -> [t] -> a sepBeginBy :: (Monoid a, Eq a) => a -> (t -> a) -> [t] -> a sepBy :: (Monoid a, Eq a) => a -> (t -> a) -> [t] -> a sepEndBy _ _ [] = mempty sepEndBy s f (x:xs) | next == mempty = rest | otherwise = next <> s <> rest where next = f x rest = sepEndBy s f xs sepBeginBy _ _ [] = mempty sepBeginBy s f (x:xs) | next == mempty = rest | otherwise = s <> next <> rest where next = f x rest = sepBeginBy s f xs sepBy _ _ [] = mempty sepBy s f (x:xs) | null xs = next | next == mempty = rest | otherwise = next <> sepBeginBy s f xs where next = f x rest = sepBy s f xs optional :: (Monoid m) => (a -> m) -> Maybe a -> m optional = maybe mempty between l r m | m == mempty = mempty | otherwise = l <> m <> r angles m = between "<" ">" m brackets m = between "[" "]" m braces m = between "{" "}" m parens m = between "(" ")" m
CodaFi/language-swift
src/Language/Swift/Util.hs
mit
1,088
0
9
363
539
271
268
33
1
{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} -- NOTE: re-exported from Test.Hspec.Core.Spec module Test.Hspec.Core.Example ( Example (..) , Params (..) , defaultParams , ActionWith , Progress , ProgressCallback , Result(..) , ResultStatus (..) , Location (..) , FailureReason (..) , safeEvaluate , safeEvaluateExample ) where import Prelude () import Test.Hspec.Core.Compat import qualified Test.HUnit.Lang as HUnit import Data.CallStack import Control.Exception import Control.DeepSeq import Data.Typeable (Typeable) import qualified Test.QuickCheck as QC import Test.Hspec.Expectations (Expectation) import qualified Test.QuickCheck.State as QC (numSuccessTests, maxSuccessTests) import qualified Test.QuickCheck.Property as QCP import Test.Hspec.Core.QuickCheckUtil import Test.Hspec.Core.Util import Test.Hspec.Core.Example.Location -- | A type class for examples class Example e where type Arg e type Arg e = () evaluateExample :: e -> Params -> (ActionWith (Arg e) -> IO ()) -> ProgressCallback -> IO Result data Params = Params { paramsQuickCheckArgs :: QC.Args , paramsSmallCheckDepth :: Int } deriving (Show) defaultParams :: Params defaultParams = Params { paramsQuickCheckArgs = QC.stdArgs , paramsSmallCheckDepth = 5 } type Progress = (Int, Int) type ProgressCallback = Progress -> IO () -- | An `IO` action that expects an argument of type @a@ type ActionWith a = a -> IO () -- | The result of running an example data Result = Result { resultInfo :: String , resultStatus :: ResultStatus } deriving (Show, Typeable) data ResultStatus = Success | Pending (Maybe Location) (Maybe String) | Failure (Maybe Location) FailureReason deriving (Show, Typeable) data FailureReason = NoReason | Reason String | ExpectedButGot (Maybe String) String String | Error (Maybe String) SomeException deriving (Show, Typeable) instance NFData FailureReason where rnf reason = case reason of NoReason -> () Reason r -> r `deepseq` () ExpectedButGot p e a -> p `deepseq` e `deepseq` a `deepseq` () Error m e -> m `deepseq` e `seq` () instance Exception ResultStatus safeEvaluateExample :: Example e => e -> Params -> (ActionWith (Arg e) -> IO ()) -> ProgressCallback -> IO Result safeEvaluateExample example params around progress = safeEvaluate $ forceResult <$> evaluateExample example params around progress where forceResult :: Result -> Result forceResult r@(Result info status) = info `deepseq` (forceResultStatus status) `seq` r forceResultStatus :: ResultStatus -> ResultStatus forceResultStatus r = case r of Success -> r Pending _ m -> m `deepseq` r Failure _ m -> m `deepseq` r safeEvaluate :: IO Result -> IO Result safeEvaluate action = do r <- safeTry $ action return $ case r of Left e | Just result <- fromException e -> Result "" result Left e | Just hunit <- fromException e -> Result "" $ hunitFailureToResult Nothing hunit Left e -> Result "" $ Failure Nothing $ Error Nothing e Right result -> result instance Example Result where type Arg Result = () evaluateExample e = evaluateExample (\() -> e) instance Example (a -> Result) where type Arg (a -> Result) = a evaluateExample example _params action _callback = do ref <- newIORef (Result "" Success) action (evaluate . example >=> writeIORef ref) readIORef ref instance Example Bool where type Arg Bool = () evaluateExample e = evaluateExample (\() -> e) instance Example (a -> Bool) where type Arg (a -> Bool) = a evaluateExample p _params action _callback = do ref <- newIORef (Result "" Success) action (evaluate . example >=> writeIORef ref) readIORef ref where example a | p a = Result "" Success | otherwise = Result "" $ Failure Nothing NoReason instance Example Expectation where type Arg Expectation = () evaluateExample e = evaluateExample (\() -> e) hunitFailureToResult :: Maybe String -> HUnit.HUnitFailure -> ResultStatus hunitFailureToResult pre e = case e of HUnit.HUnitFailure mLoc err -> case err of HUnit.Reason reason -> Failure location (Reason $ addPre reason) HUnit.ExpectedButGot preface expected actual -> Failure location (ExpectedButGot (addPreMaybe preface) expected actual) where addPreMaybe :: Maybe String -> Maybe String addPreMaybe xs = case (pre, xs) of (Just x, Just y) -> Just (x ++ "\n" ++ y) _ -> pre <|> xs where location = case mLoc of Nothing -> Nothing Just loc -> Just $ Location (srcLocFile loc) (srcLocStartLine loc) (srcLocStartCol loc) where addPre :: String -> String addPre xs = case pre of Just x -> x ++ "\n" ++ xs Nothing -> xs instance Example (a -> Expectation) where type Arg (a -> Expectation) = a evaluateExample e _ action _ = action e >> return (Result "" Success) instance Example QC.Property where type Arg QC.Property = () evaluateExample e = evaluateExample (\() -> e) instance Example (a -> QC.Property) where type Arg (a -> QC.Property) = a evaluateExample p c action progressCallback = do r <- QC.quickCheckWithResult (paramsQuickCheckArgs c) {QC.chatty = False} (QCP.callback qcProgressCallback $ aroundProperty action p) return $ fromQuickCheckResult r where qcProgressCallback = QCP.PostTest QCP.NotCounterexample $ \st _ -> progressCallback (QC.numSuccessTests st, QC.maxSuccessTests st) fromQuickCheckResult :: QC.Result -> Result fromQuickCheckResult r = case parseQuickCheckResult r of QuickCheckResult _ info (QuickCheckOtherFailure err) -> Result info $ Failure Nothing (Reason err) QuickCheckResult _ info QuickCheckSuccess -> Result info Success QuickCheckResult n info (QuickCheckFailure QCFailure{..}) -> case quickCheckFailureException of Just e | Just result <- fromException e -> Result info result Just e | Just hunit <- fromException e -> Result info $ hunitFailureToResult (Just hunitAssertion) hunit Just e -> failure (uncaughtException e) Nothing -> failure falsifiable where failure = Result info . Failure Nothing . Reason numbers = formatNumbers n quickCheckFailureNumShrinks hunitAssertion :: String hunitAssertion = intercalate "\n" [ "Falsifiable " ++ numbers ++ ":" , indent (unlines quickCheckFailureCounterexample) ] uncaughtException e = intercalate "\n" [ "uncaught exception: " ++ formatException e , numbers , indent (unlines quickCheckFailureCounterexample) ] falsifiable = intercalate "\n" [ quickCheckFailureReason ++ " " ++ numbers ++ ":" , indent (unlines quickCheckFailureCounterexample) ] indent :: String -> String indent = intercalate "\n" . map (" " ++) . lines
hspec/hspec
hspec-core/src/Test/Hspec/Core/Example.hs
mit
7,124
0
19
1,609
2,221
1,152
1,069
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} module Abt.Tutorial where import Abt.Class import Abt.Types import Abt.Concrete.LocallyNameless import Control.Applicative import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Maybe import Control.Monad.Trans.Except import Data.Vinyl import Prelude hiding (pi) -- | We'll start off with a monad in which to manipulate ABTs; we'll need some -- state for fresh variable generation. -- newtype M a = M { _M :: State Int a } deriving (Functor, Applicative, Monad) -- | We'll run an ABT computation by starting the variable counter at @0@. -- runM :: M a -> a runM (M m) = evalState m 0 -- | Check out the source to see fresh variable generation. -- instance MonadVar Var M where fresh = M $ do n <- get let n' = n + 1 put n' return $ Var Nothing n' named a = do v <- fresh return $ v { _varName = Just a } clone v = case _varName v of Just s -> named s _ -> fresh -- | Next, we'll define the operators for a tiny lambda calculus as a datatype -- indexed by arities. -- data Lang ns where LAM :: Lang '[ 'S 'Z] APP :: Lang '[ 'Z, 'Z] PI :: Lang '[ 'Z, 'S 'Z] UNIT :: Lang '[] AX :: Lang '[] instance Show1 Lang where show1 = \case LAM -> "lam" APP -> "ap" PI -> "pi" UNIT -> "unit" AX -> "<>" instance HEq1 Lang where heq1 LAM LAM = Just Refl heq1 APP APP = Just Refl heq1 PI PI = Just Refl heq1 UNIT UNIT = Just Refl heq1 AX AX = Just Refl heq1 _ _ = Nothing lam :: Tm Lang ('S 'Z) -> Tm0 Lang lam e = LAM $$ e :& RNil app :: Tm0 Lang -> Tm0 Lang -> Tm0 Lang app m n = APP $$ m :& n :& RNil ax :: Tm0 Lang ax = AX $$ RNil unit :: Tm0 Lang unit = UNIT $$ RNil pi :: Tm0 Lang -> Tm Lang ('S 'Z) -> Tm0 Lang pi a xb = PI $$ a :& xb :& RNil -- | A monad transformer for small step operational semantics. -- newtype StepT m a = StepT { runStepT :: MaybeT m a } deriving (Monad, Functor, Applicative, Alternative) -- | To indicate that a term is in normal form. -- stepsExhausted :: Applicative m => StepT m a stepsExhausted = StepT . MaybeT $ pure Nothing instance MonadVar Var m => MonadVar Var (StepT m) where fresh = StepT . MaybeT $ Just <$> fresh named str = StepT . MaybeT $ Just <$> named str clone v = StepT . MaybeT $ Just <$> clone v -- | A single evaluation step. -- step :: Tm0 Lang -> StepT M (Tm0 Lang) step tm = out tm >>= \case APP :$ m :& n :& RNil -> out m >>= \case LAM :$ xe :& RNil -> xe // n _ -> app <$> step m <*> pure n <|> app <$> pure m <*> step n PI :$ a :& xb :& RNil -> pi <$> step a <*> pure xb _ -> stepsExhausted -- | The reflexive-transitive closure of a small-step operational semantics. -- star :: Monad m => (a -> StepT m a) -> (a -> m a) star f a = runMaybeT (runStepT $ f a) >>= return a `maybe` star f -- | Evaluate a term to normal form -- eval :: Tm0 Lang -> Tm0 Lang eval = runM . star step newtype JudgeT m a = JudgeT { runJudgeT :: ExceptT String m a } deriving (Monad, Functor, Applicative, Alternative) instance MonadVar Var m => MonadVar Var (JudgeT m) where fresh = JudgeT . ExceptT $ Right <$> fresh named str = JudgeT . ExceptT $ Right <$> named str clone v = JudgeT . ExceptT $ Right <$> clone v type Ctx = [(Var, Tm0 Lang)] raise :: Monad m => String -> JudgeT m a raise = JudgeT . ExceptT . return . Left checkTy :: Ctx -> Tm0 Lang -> Tm0 Lang -> JudgeT M () checkTy g tm ty = do let ntm = eval tm nty = eval ty (,) <$> out ntm <*> out nty >>= \case (LAM :$ xe :& RNil, PI :$ a :& yb :& RNil) -> do z <- fresh ez <- xe // var z bz <- yb // var z checkTy ((z,a):g) ez bz (AX :$ RNil, UNIT :$ RNil) -> return () _ -> do ty' <- inferTy g tm if ty' === nty then return () else raise "Type error" inferTy :: Ctx -> Tm0 Lang -> JudgeT M (Tm0 Lang) inferTy g tm = do out (eval tm) >>= \case V v | Just (eval -> ty) <- lookup v g -> return ty | otherwise -> raise "Ill-scoped variable" APP :$ m :& n :& RNil -> do inferTy g m >>= out >>= \case PI :$ a :& xb :& RNil -> do checkTy g n a eval <$> xb // n _ -> raise "Expected pi type for lambda abstraction" _ -> raise "Only infer neutral terms" -- | @λx.x@ -- identityTm :: M (Tm0 Lang) identityTm = do x <- named "x" return $ lam (x \\ var x) -- | @(λx.x)(λx.x)@ -- appTm :: M (Tm0 Lang) appTm = do tm <- identityTm return $ app tm tm -- | A demonstration of evaluating (and pretty-printing). Output: -- -- @ -- ap[lam[\@2.\@2];lam[\@3.\@3]] ~>* lam[\@4.\@4] -- @ -- main :: IO () main = do -- Try out the type checker either fail print . runM . runExceptT . runJudgeT $ do x <- fresh checkTy [] (lam (x \\ var x)) (pi unit (x \\ unit)) print . runM $ do im <- identityTm imStr <- toString im return imStr print . runM $ do mm <- appTm mmStr <- toString mm mmStr' <- toString $ eval mm return $ mmStr ++ " ~>* " ++ mmStr'
jonsterling/hs-abt
src/Abt/Tutorial.hs
mit
5,337
0
20
1,456
2,008
1,009
999
168
4
import Control.Monad import System.Exit (exitSuccess) import Data.Char (toLower) palindrome :: IO () palindrome = forever $ do line1 <- getLine let normalisedLine = removeSpaces $ map toLower line1 case (normalisedLine == reverse normalisedLine) of True -> putStrLn "It's a palindrome!" False -> do putStrLn "Nope!" exitSuccess where removeSpaces word = filter (/= ' ') word
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter13/palindrome/Palindrome.hs
mit
408
0
13
88
130
64
66
13
2
data Name = NameConstr String data Color = ColorConstr String showInfos :: Name -> Color -> String showInfos (NameConstr name) (ColorConstr color) = "Name: " ++ name ++ ", Color: " ++ color name = NameConstr "Robin" color = ColorConstr "Blue" main = putStrLn $ showInfos name color
duncanfinney/haskell-play
04-types.hs
mit
287
0
7
53
96
49
47
8
1
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------------------- -- File : Cmd -- Author : Alejandro Gómez Londoño -- Date : Sat Jun 27 01:12:12 2015 -- Description : Main handler for api calls -------------------------------------------------------------------------------- -- Change log : -------------------------------------------------------------------------------- module MonadBox.Cmd where import MonadBox.Parser (Cmd(..)) import MonadBox.Types (DBMeta(..),Token) import Data.Text (append,pack) import Control.Lens ((&), (.~), (^.), (?~)) import Network.Wreq (auth,basicAuth,defaults ,getWith,responseBody,oauth2Bearer ,statusCode) import Network.HTTP.Client (HttpException(StatusCodeException)) import Data.Text.Encoding (encodeUtf8) import MonadBox.Util (asJSON) import Control.Exception as E (catch) import qualified MonadBox.URI as URI doCommand ∷ Token → Cmd → IO () doCommand token (List Nothing) = _DBMeta "" token >>= print doCommand token (List (Just path)) = _DBMeta path token >>= print doCommand token _ = undefined _DBMeta ∷ String → Token → IO DBMeta _DBMeta path token = catch request errorHandler where request = do let opts = defaults & auth ?~ oauth2Bearer (encodeUtf8 token) r ← asJSON =<< getWith opts (URI.metadata ++ path) return $ r ^. responseBody errorHandler (StatusCodeException s h _) = case s ^. statusCode of 404 → return . MetaError $ "No such file or directory =(" n → return . MetaError $ "Unknown Error (#: " ++ (show n)
agomezl/MonadBox
src/MonadBox/Cmd.hs
mit
1,737
0
15
368
419
238
181
29
2
{-# LANGUAGE GADTs, ViewPatterns, MultiParamTypeClasses, OverloadedStrings #-} {-# LANGUAGE TypeFamilies, TemplateHaskell, QuasiQuotes, FlexibleContexts #-} module Main where import Yesod import Data.Text as T hiding (zip) import Control.Applicative import Control.Monad (forM) import Yesod.Form import Data.String main :: IO () main = warp 3000 CarApp data CarApp = CarApp instance Yesod CarApp instance RenderMessage CarApp FormMessage where renderMessage _ _ = defaultFormMessage mkYesod "CarApp" [parseRoutes| / HomeR GET |] passwordConfirmField :: Field Handler Text passwordConfirmField = Field { fieldParse = \rawVals _fileVals -> case rawVals of [a, b] | a == b -> return $ Right $ Just a | otherwise -> return $ Left "Passwords don't match" [] -> return $ Right Nothing _ -> return $ Left "You must enter two values" , fieldView = \idAttr nameAttr otherAttrs eResult isReq -> [whamlet| <input id=#{idAttr} name=#{nameAttr} *{otherAttrs} type=password> <div>Confirm: <input id=#{idAttr}-confirm name=#{nameAttr} *{otherAttrs} type=password> |] , fieldEnctype = UrlEncoded } getHomeR :: Handler Html getHomeR = do ((res, widget), enctype) <- runFormGet $ renderDivs $ areq passwordConfirmField "Password" Nothing defaultLayout [whamlet| <p>Result: #{show res} <form enctype=#{enctype}> ^{widget} <input type=submit value="Change password"> |]
cirquit/quizlearner
resources/form/mforms_customfield_2.hs
mit
1,606
0
14
437
310
170
140
34
3
-- Reverse list recursively -- https://www.codewars.com/kata/57a883cfbb9944a97c000088 module ReverseRecursively where revR :: [Int] -> [Int] revR = foldl (flip (:)) []
gafiatulin/codewars
src/8 kyu/ReverseRecursively.hs
mit
170
0
7
22
41
25
16
3
1
{-# LANGUAGE TemplateHaskell #-} module Tak.Types where import qualified Data.Map as Map import qualified Data.Sequence as Seq import qualified Control.Monad.State as St import qualified Data.Text as Text import Control.Lens (makeLenses) type Line = Text.Text type LineIdx = Int type LineSeq = Seq.Seq Line data Buffer = Buffer { lineSeq :: LineSeq } deriving (Show) defaultBuffer = Buffer $ Seq.fromList [Text.empty] data Box = Box { top :: Int, left :: Int, height :: Int, width :: Int } bottom :: Box -> Int bottom box = top box + height box right :: Box -> Int right box = left box + width box data WrapMode = Crop | Wrap data Pos = Pos { line :: Int, row :: Int } deriving (Show, Eq, Ord) defaultPos :: Pos defaultPos = Pos 0 0 data Range = Range { start :: Pos, end :: Pos } data RenderAction = PrintStr Pos String | SetCursor Pos | SetColorPair Int deriving (Show) type RenderActions = [RenderAction] newtype RenderW a = RenderW { execRender :: (a, RenderActions) } instance Monad RenderW where return x = RenderW (x, []) m >>= k = let (a, ras) = execRender m n = k a (b, ras') = execRender n in RenderW (b, ras ++ ras') data Key = KeyChar Char | KeyCtrlChar Char | KeyEscaped Key | KeyUp | KeyDown | KeyLeft | KeyRight | KeyCtrlUp | KeyCtrlDown | KeyCtrlLeft | KeyCtrlRight | KeyEscape | KeyEnter | KeyDel | KeyPageDown | KeyPageUp | KeyHome | KeyEnd | KeyCtrlHome | KeyCtrlEnd deriving (Show, Eq, Ord) data Event = KeyEvent Key | TimeoutEvent | NoEvent deriving (Show, Eq, Ord) class Editor a where render :: a -> Int -> Int -> RenderW () data SelectionState = SelectionState { ranges :: [(Pos, Pos)], openRange :: Maybe Pos } defaultSelectionState = SelectionState [] Nothing data SimpleEditor = SimpleEditor { undoBuffers :: [(Buffer, Pos)], lastSavePtr :: Int, selState :: SelectionState, buffer :: Buffer, cursorPos :: Pos, fileName :: String, lineScroll :: Int, viewHeight :: Int } defaultSimpleEditor :: SimpleEditor defaultSimpleEditor = SimpleEditor [] 0 defaultSelectionState defaultBuffer defaultPos "" 0 24 data InfoLineEditor = InfoLineEditor { infoBuffer :: Buffer } defaultInfoLineEditor = InfoLineEditor defaultBuffer data Mode = Mode { handler :: Event -> GlobalState -> IO GlobalState } defaultMode = Mode (\e g -> return g) data GlobalState = GlobalState { _shouldQuit :: Bool, _needsRepaint :: Bool, _clipboard :: [LineSeq], _editor :: SimpleEditor, _infoLine :: InfoLineEditor, _mode :: Mode } makeLenses ''GlobalState defaultGlobalState = GlobalState False True [] defaultSimpleEditor defaultInfoLineEditor defaultMode
sixohsix/tak
src/Tak/Types.hs
mit
2,994
0
11
865
869
504
365
106
1
module Rebase.GHC.IO.BufferedIO ( module GHC.IO.BufferedIO ) where import GHC.IO.BufferedIO
nikita-volkov/rebase
library/Rebase/GHC/IO/BufferedIO.hs
mit
95
0
5
12
23
16
7
4
0
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE Arrows #-} -- | Renders all object parameters of a scene into the GBuffer. module Yage.Rendering.Pipeline.Deferred.BaseGPass ( GBaseScene , GBaseEntity -- * Material , GBaseMaterial(..) , HasGBaseMaterial(..) , albedo , normalmap , roughness , metallic , defaultGBaseMaterial , gBaseMaterialRes -- * Vertex Attributes , GBaseVertex -- * Pass Output , GBuffer(..) , aChannel , bChannel , cChannel , dChannel , depthChannel -- * Pass , gPass ) where import Yage.Prelude import Yage.Math (m44_to_m33) import Yage.Lens import Yage.GL import Yage.Viewport as GL import Yage.Vertex hiding (Texture) import Yage.Attribute import Yage.Camera import Yage.Material hiding (over, HasPosition, position) import Yage.Scene hiding (Layout) import Yage.Uniform as Uniform import Yage.Rendering.Resources.GL import Yage.Rendering.GL import Yage.Rendering.RenderSystem import Yage.Rendering.RenderTarget import Control.Monad.State.Strict (execStateT) import Foreign.Ptr import Linear import Quine.GL.Uniform import Quine.GL.Attribute import Quine.GL.Program import Quine.GL.Buffer import Quine.GL.VertexArray import Quine.GL.ProgramPipeline import Quine.StateVar import Yage.Rendering.Pipeline.Deferred.Common #include "definitions.h" #include "textureUnits.h" #include "attributes.h" -- * Material data GBaseMaterial t = GBaseMaterial { _gBaseMaterialAlbedo :: Material MaterialColorAlpha (t PixelRGB8) , _gBaseMaterialNormalmap :: Material MaterialColorAlpha (t PixelRGB8) , _gBaseMaterialRoughness :: Material Double (t Pixel8) , _gBaseMaterialMetallic :: Material Double (t Pixel8) } makeClassy ''GBaseMaterial makeFields ''GBaseMaterial -- * Shader -- * Vertex Attributes type GBaseVertex v = (HasPosition v Vec3, HasTexture v Vec2, HasTangentX v Vec3, HasTangentZ v Vec4) -- | Uniform StateVars of the fragment shader data FragmentShader = FragmentShader { albedoMaterial :: UniformVar (Material MaterialColorAlpha (Texture2D PixelRGB8)) , normalMaterial :: UniformVar (Material MaterialColorAlpha (Texture2D PixelRGB8)) , roughnessMaterial :: UniformVar (Material Double (Texture2D Pixel8)) , metallicMaterial :: UniformVar (Material Double (Texture2D Pixel8)) } -- | Uniforms data VertexShader = VertexShader { vPosition :: VertexAttribute , vTexture :: VertexAttribute , vTangentX :: VertexAttribute , vTangentZ :: VertexAttribute , albedoTextureMatrix :: UniformVar Mat4 , normalTextureMatrix :: UniformVar Mat4 , roughnessTextureMatrix :: UniformVar Mat4 , metallicTextureMatrix :: UniformVar Mat4 , viewMatrix :: UniformVar Mat4 , vpMatrix :: UniformVar Mat4 , modelMatrix :: UniformVar Mat4 , normalMatrix :: UniformVar Mat3 } -- * Scene -- type GBaseScene ent env gui = Scene HDRCamera ent env gui -- * Pass Output -- | The output GBuffer of this pass (for encoding see "res/glsl/pass/gbuffer.h") data GBuffer = GBuffer { _aChannel :: Texture2D PixelRGBA8 , _bChannel :: Texture2D PixelRGBA8 , _cChannel :: Texture2D PixelRGB32F , _dChannel :: Texture2D PixelRGB32F , _depthChannel :: Texture2D (DepthComponent32F Float) } deriving (Typeable,Show,Generic) makeLenses ''GBuffer type GBaseEntity ent i v = (HasTransformation ent Double, HasGBaseMaterial ent Texture2D, HasRenderData ent i v, GBaseVertex v) type GBaseScene scene f ent i v = (MonoFoldable (f ent), GBaseEntity (Element (f ent)) i v, HasEntities scene (f ent)) -- * Draw To GBuffer data PassRes = PassRes { vao :: VertexArray , pipe :: Pipeline , frag :: FragmentShader , vert :: VertexShader } type BaseGPass m globalEnv scene = PassGEnv globalEnv PassRes m (RenderTarget GBuffer, scene, Camera) GBuffer gPass :: (MonadIO m, MonadThrow m, HasViewport g Int, GBaseScene scene f ent i v) => YageResource (BaseGPass m g scene) gPass = PassGEnv <$> passRes <*> pure runPass where passRes :: YageResource PassRes passRes = do vao <- glResource boundVertexArray $= vao pipeline <- [ $(embedShaderFile "res/glsl/pass/base.vert") , $(embedShaderFile "res/glsl/pass/base.frag")] `compileShaderPipeline` includePaths Just frag <- traverse fragmentUniforms =<< get (fragmentShader $ pipeline^.pipelineProgram) Just vert <- traverse vertexUniforms =<< get (vertexShader $ pipeline^.pipelineProgram) return $ PassRes vao pipeline frag vert runPass :: (MonadIO m, MonadThrow m, MonadReader (PassEnv g PassRes) m, HasViewport g Int, GBaseScene scene f ent i v) => RenderSystem m (RenderTarget GBuffer, scene, Camera) GBuffer runPass = mkStaticRenderPass $ \(target, scene, cam) -> do PassRes{..} <- view localEnv boundFramebuffer RWFramebuffer $= (target^.framebufferObj) -- some state setting glEnable GL_DEPTH_TEST glDisable GL_BLEND glEnable GL_CULL_FACE glDepthMask GL_TRUE glDepthFunc GL_LESS glFrontFace GL_CCW glCullFace GL_BACK GL.globalViewport $= target^.asRectangle glColorMask GL_TRUE GL_TRUE GL_TRUE GL_TRUE glClearColor 0 0 0 1 glClear $ GL_DEPTH_BUFFER_BIT .|. GL_COLOR_BUFFER_BIT -- set globals {-# SCC boundVertexArray #-} throwWithStack $ boundVertexArray $= vao boundProgramPipeline $= pipe^.pipelineProgram checkPipelineError pipe setupSceneGlobals vert frag cam drawEntities vert frag (scene^.entities) return $ target^.renderTarget setupSceneGlobals :: (MonadReader (PassEnv g l) m, HasViewport g Int, MonadIO m) => VertexShader -> FragmentShader -> Camera -> m () setupSceneGlobals VertexShader{..} FragmentShader{..} cam@Camera{..} = do mainViewport <- view $ globalEnv.viewport viewMatrix $= fmap realToFrac <$> (cam^.cameraMatrix) vpMatrix $= fmap realToFrac <$> viewprojectionM mainViewport where viewprojectionM :: Viewport Int -> M44 Double viewprojectionM vp = projectionMatrix3D _cameraNearZ _cameraFarZ _cameraFovy (fromIntegral <$> vp^.rectangle) !*! (cam^.cameraMatrix) drawEntities :: forall f ent i v m . (MonadIO m, MonoFoldable (f ent), GBaseEntity (Element (f ent)) i v) => VertexShader -> FragmentShader -> (f ent) -> m () drawEntities VertexShader{..} FragmentShader{..} ents = forM_ ents $ \ent -> do -- set entity globals modelMatrix $= fmap realToFrac <$> (ent^.transformationMatrix) normalMatrix $= fmap realToFrac <$> (ent^.inverseTransformation.transformationMatrix.to m44_to_m33) -- setup material albedoMaterial $= ent^.gBaseMaterial.albedo albedoTextureMatrix $= fmap realToFrac <$> (ent^.gBaseMaterial.albedo.transformation.transformationMatrix) normalMaterial $= ent^.gBaseMaterial.normalmap normalTextureMatrix $= fmap realToFrac <$> (ent^.gBaseMaterial.normalmap.transformation.transformationMatrix) roughnessMaterial $= ent^.gBaseMaterial.roughness roughnessTextureMatrix $= fmap realToFrac <$> (ent^.gBaseMaterial.roughness.transformation.transformationMatrix) metallicMaterial $= ent^.gBaseMaterial.metallic metallicTextureMatrix $= fmap realToFrac <$> (ent^.gBaseMaterial.metallic.transformation.transformationMatrix) -- bind vbo boundBufferAt ElementArrayBuffer $= ent^.indexBuffer boundBufferAt ArrayBuffer $= ent^.vertexBuffer vPosition $= Just ((Proxy :: Proxy v)^.positionlayout) vTexture $= Just ((Proxy :: Proxy v)^.texturelayout) vTangentX $= Just ((Proxy :: Proxy v)^.tangentXlayout) vTangentZ $= Just ((Proxy :: Proxy v)^.tangentZlayout) -- vertexLayoutRef $= Just currentLayout {-# SCC glDrawElements #-} throwWithStack $ glDrawElements (ent^.elementMode) (fromIntegral $ ent^.elementCount) (ent^.elementType) nullPtr -- * Default Material instance Default (GBaseMaterial Image) where def = defaultGBaseMaterial defaultGBaseMaterial :: GBaseMaterial Image defaultGBaseMaterial = GBaseMaterial { _gBaseMaterialAlbedo = defaultMaterialSRGB , _gBaseMaterialNormalmap = defaultMaterialSRGB & materialColor .~ rgb 2 2 2 `withOpacity` 0.75 & materialTexture .~ zNormalDummy , _gBaseMaterialRoughness = mkMaterial 1.0 whiteDummy , _gBaseMaterialMetallic = mkMaterial 0.0 whiteDummy } gBaseMaterialRes :: GBaseMaterial Image -> YageResource (GBaseMaterial Texture2D) gBaseMaterialRes GBaseMaterial{..} = GBaseMaterial <$> materialRes _gBaseMaterialAlbedo <*> materialRes _gBaseMaterialNormalmap <*> materialRes _gBaseMaterialRoughness <*> materialRes _gBaseMaterialMetallic -- * Shader Interfaces vertexUniforms :: (MonadIO m, Functor m, Applicative m) => Program -> m VertexShader vertexUniforms prog = do boundAttributeLocation prog "vPosition" $= VPOSITION boundAttributeLocation prog "vTexture" $= VTEXTURE boundAttributeLocation prog "vTangentX" $= VTANGENTX boundAttributeLocation prog "vTangentZ" $= VTANGENTZ VertexShader (setVertexAttribute VPOSITION) (setVertexAttribute VTEXTURE) (setVertexAttribute VTANGENTX) (setVertexAttribute VTANGENTZ) -- wrap the StateVar into a simple SettableStateVar <$> fmap toUniformVar (programUniform programUniformMatrix4f prog "AlbedoTextureMatrix") <*> fmap toUniformVar (programUniform programUniformMatrix4f prog "NormalTextureMatrix") <*> fmap toUniformVar (programUniform programUniformMatrix4f prog "RoughnessTextureMatrix") <*> fmap toUniformVar (programUniform programUniformMatrix4f prog "MetallicTextureMatrix") <*> fmap toUniformVar (programUniform programUniformMatrix4f prog "ViewMatrix") <*> fmap toUniformVar (programUniform programUniformMatrix4f prog "VPMatrix") <*> fmap toUniformVar (programUniform programUniformMatrix4f prog "ModelMatrix") <*> fmap toUniformVar (programUniform programUniformMatrix3f prog "NormalMatrix") fragmentUniforms :: Program -> YageResource FragmentShader fragmentUniforms prog = do albedoSampler <- mkAlbedoSampler normalSampler <- mkNormalSampler roughnessSampler <- mkRoughnessSampler metallicSampler <- mkMetallicSampler FragmentShader <$> materialUniformRGBA prog albedoSampler "AlbedoTexture" "AlbedoColor" <*> materialUniformRGBA prog normalSampler "NormalTexture" "NormalColor" <*> materialUniformIntensity prog roughnessSampler "RoughnessTexture" "RoughnessIntensity" <*> materialUniformIntensity prog metallicSampler "MetallicTexture" "MetallicIntensity" -- * Sampler mkAlbedoSampler :: YageResource (UniformSampler2D px) mkAlbedoSampler = throwWithStack $ sampler2D ALBEDO_UNIT <$> do s <- glResource samplerParameteri s GL_TEXTURE_WRAP_S $= GL_REPEAT samplerParameteri s GL_TEXTURE_WRAP_T $= GL_REPEAT samplerParameteri s GL_TEXTURE_MIN_FILTER $= GL_LINEAR samplerParameteri s GL_TEXTURE_MAG_FILTER $= GL_LINEAR when gl_EXT_texture_filter_anisotropic $ samplerParameterf s GL_TEXTURE_MAX_ANISOTROPY_EXT $= 16 return s mkNormalSampler :: YageResource (UniformSampler2D px) mkNormalSampler = throwWithStack $ sampler2D NORMAL_UNIT <$> do s <- glResource samplerParameteri s GL_TEXTURE_WRAP_S $= GL_REPEAT samplerParameteri s GL_TEXTURE_WRAP_T $= GL_REPEAT samplerParameteri s GL_TEXTURE_MIN_FILTER $= GL_LINEAR samplerParameteri s GL_TEXTURE_MAG_FILTER $= GL_LINEAR when gl_EXT_texture_filter_anisotropic $ samplerParameterf s GL_TEXTURE_MAX_ANISOTROPY_EXT $= 16 return s mkRoughnessSampler :: YageResource (UniformSampler2D px) mkRoughnessSampler = throwWithStack $ sampler2D ROUGHNESS_UNIT <$> do s <- glResource samplerParameteri s GL_TEXTURE_WRAP_S $= GL_REPEAT samplerParameteri s GL_TEXTURE_WRAP_T $= GL_REPEAT samplerParameteri s GL_TEXTURE_MIN_FILTER $= GL_LINEAR samplerParameteri s GL_TEXTURE_MAG_FILTER $= GL_LINEAR when gl_EXT_texture_filter_anisotropic $ samplerParameterf s GL_TEXTURE_MAX_ANISOTROPY_EXT $= 16 return s mkMetallicSampler :: YageResource (UniformSampler2D px) mkMetallicSampler = throwWithStack $ sampler2D METALLIC_UNIT <$> do s <- glResource samplerParameteri s GL_TEXTURE_WRAP_S $= GL_REPEAT samplerParameteri s GL_TEXTURE_WRAP_T $= GL_REPEAT samplerParameteri s GL_TEXTURE_MIN_FILTER $= GL_LINEAR samplerParameteri s GL_TEXTURE_MAG_FILTER $= GL_LINEAR when gl_EXT_texture_filter_anisotropic $ samplerParameterf s GL_TEXTURE_MAX_ANISOTROPY_EXT $= 16 return s instance IsRenderTarget GBuffer where getAttachments GBuffer{..} = ( [ mkAttachment _aChannel , mkAttachment _bChannel , mkAttachment _cChannel , mkAttachment _dChannel ] , Just $ mkAttachment _depthChannel, Nothing) instance GetRectangle GBuffer Int where asRectangle = aChannel.asRectangle instance Resizeable2D GBuffer where resize2D gbuff w h = flip execStateT gbuff $ do aChannel <~ resize2D (gbuff^.aChannel) w h bChannel <~ resize2D (gbuff^.bChannel) w h cChannel <~ resize2D (gbuff^.cChannel) w h dChannel <~ resize2D (gbuff^.dChannel) w h depthChannel <~ resize2D (gbuff^.depthChannel) w h instance HasGBaseMaterial mat Texture2D => HasGBaseMaterial (Entity d mat) Texture2D where gBaseMaterial = materials.gBaseMaterial
MaxDaten/yage
src/Yage/Rendering/Pipeline/Deferred/BaseGPass.hs
mit
14,166
0
17
2,819
3,311
1,689
1,622
-1
-1
module Feature.RangeSpec where import Test.Hspec import Test.Hspec.Wai import Test.Hspec.Wai.JSON import Network.HTTP.Types import Network.Wai.Test (SResponse(simpleHeaders,simpleStatus)) import qualified Data.ByteString.Lazy as BL import SpecHelper import Network.Wai (Application) defaultRange :: BL.ByteString defaultRange = [json| { "min": 0, "max": 15 } |] emptyRange :: BL.ByteString emptyRange = [json| { "min": 2, "max": 2 } |] spec :: SpecWith Application spec = do describe "POST /rpc/getitemrange" $ do context "without range headers" $ do context "with response under server size limit" $ it "returns whole range with status 200" $ post "/rpc/getitemrange" defaultRange `shouldRespondWith` 200 context "when I don't want the count" $ do it "returns range Content-Range with */* for empty range" $ request methodPost "/rpc/getitemrange" [("Prefer", "count=none")] emptyRange `shouldRespondWith` ResponseMatcher { matchBody = Just [json| [] |] , matchStatus = 200 , matchHeaders = ["Content-Range" <:> "*/*"] } it "returns range Content-Range with range/*" $ request methodPost "/rpc/getitemrange" [("Prefer", "count=none")] defaultRange `shouldRespondWith` ResponseMatcher { matchBody = Just [json| [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}] |] , matchStatus = 200 , matchHeaders = ["Content-Range" <:> "0-14/*"] } context "with range headers" $ do context "of acceptable range" $ do it "succeeds with partial content" $ do r <- request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFromTo 0 1) defaultRange liftIO $ do simpleHeaders r `shouldSatisfy` matchHeader "Content-Range" "0-1/15" simpleStatus r `shouldBe` partialContent206 it "understands open-ended ranges" $ request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFrom 0) defaultRange `shouldRespondWith` 200 it "returns an empty body when there are no results" $ request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFromTo 0 1) emptyRange `shouldRespondWith` ResponseMatcher { matchBody = Just "[]" , matchStatus = 200 , matchHeaders = ["Content-Range" <:> "*/0"] } it "allows one-item requests" $ do r <- request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFromTo 0 0) defaultRange liftIO $ do simpleHeaders r `shouldSatisfy` matchHeader "Content-Range" "0-0/15" simpleStatus r `shouldBe` partialContent206 it "handles ranges beyond collection length via truncation" $ do r <- request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFromTo 10 100) defaultRange liftIO $ do simpleHeaders r `shouldSatisfy` matchHeader "Content-Range" "10-14/15" simpleStatus r `shouldBe` partialContent206 context "of invalid range" $ do it "fails with 416 for offside range" $ request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFromTo 1 0) emptyRange `shouldRespondWith` 416 it "refuses a range with nonzero start when there are no items" $ request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFromTo 1 2) emptyRange `shouldRespondWith` ResponseMatcher { matchBody = Nothing , matchStatus = 416 , matchHeaders = ["Content-Range" <:> "*/0"] } it "refuses a range requesting start past last item" $ request methodPost "/rpc/getitemrange" (rangeHdrs $ ByteRangeFromTo 100 199) defaultRange `shouldRespondWith` ResponseMatcher { matchBody = Nothing , matchStatus = 416 , matchHeaders = ["Content-Range" <:> "*/15"] } describe "GET /items" $ do context "without range headers" $ do context "with response under server size limit" $ it "returns whole range with status 200" $ get "/items" `shouldRespondWith` 200 context "when I don't want the count" $ do it "returns range Content-Range with /*" $ request methodGet "/menagerie" [("Prefer", "count=none")] "" `shouldRespondWith` ResponseMatcher { matchBody = Just "[]" , matchStatus = 200 , matchHeaders = ["Content-Range" <:> "*/*"] } it "returns range Content-Range with range/*" $ request methodGet "/items?order=id" [("Prefer", "count=none")] "" `shouldRespondWith` ResponseMatcher { matchBody = Just [json| [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}] |] , matchStatus = 200 , matchHeaders = ["Content-Range" <:> "0-14/*"] } it "returns range Content-Range with range/* even using other filters" $ request methodGet "/items?id=eq.1&order=id" [("Prefer", "count=none")] "" `shouldRespondWith` ResponseMatcher { matchBody = Just [json| [{"id":1}] |] , matchStatus = 200 , matchHeaders = ["Content-Range" <:> "0-0/*"] } context "with range headers" $ do context "of acceptable range" $ do it "succeeds with partial content" $ do r <- request methodGet "/items" (rangeHdrs $ ByteRangeFromTo 0 1) "" liftIO $ do simpleHeaders r `shouldSatisfy` matchHeader "Content-Range" "0-1/15" simpleStatus r `shouldBe` partialContent206 it "understands open-ended ranges" $ request methodGet "/items" (rangeHdrs $ ByteRangeFrom 0) "" `shouldRespondWith` 200 it "returns an empty body when there are no results" $ request methodGet "/menagerie" (rangeHdrs $ ByteRangeFromTo 0 1) "" `shouldRespondWith` ResponseMatcher { matchBody = Just "[]" , matchStatus = 200 , matchHeaders = ["Content-Range" <:> "*/0"] } it "allows one-item requests" $ do r <- request methodGet "/items" (rangeHdrs $ ByteRangeFromTo 0 0) "" liftIO $ do simpleHeaders r `shouldSatisfy` matchHeader "Content-Range" "0-0/15" simpleStatus r `shouldBe` partialContent206 it "handles ranges beyond collection length via truncation" $ do r <- request methodGet "/items" (rangeHdrs $ ByteRangeFromTo 10 100) "" liftIO $ do simpleHeaders r `shouldSatisfy` matchHeader "Content-Range" "10-14/15" simpleStatus r `shouldBe` partialContent206 context "of invalid range" $ do it "fails with 416 for offside range" $ request methodGet "/items" (rangeHdrs $ ByteRangeFromTo 1 0) "" `shouldRespondWith` 416 it "refuses a range with nonzero start when there are no items" $ request methodGet "/menagerie" (rangeHdrs $ ByteRangeFromTo 1 2) "" `shouldRespondWith` ResponseMatcher { matchBody = Nothing , matchStatus = 416 , matchHeaders = ["Content-Range" <:> "*/0"] } it "refuses a range requesting start past last item" $ request methodGet "/items" (rangeHdrs $ ByteRangeFromTo 100 199) "" `shouldRespondWith` ResponseMatcher { matchBody = Nothing , matchStatus = 416 , matchHeaders = ["Content-Range" <:> "*/15"] }
league/postgrest
test/Feature/RangeSpec.hs
mit
8,408
0
23
2,826
1,602
831
771
-1
-1
module Main (main) where import Distribution.Simple import AStar main :: IO () main = defaultMain
Lukx19/Astar-Dijkstra-BFS-Haskell
Setup.hs
mit
99
0
6
16
32
19
13
5
1
module Main ( main ) where -- doctest import qualified Test.DocTest as DocTest main :: IO () main = DocTest.doctest [ "-isrc" , "src/Wholemeal.hs" ]
mauriciofierrom/cis194-homework
homework04/test/examples/Main.hs
mit
172
0
6
48
44
27
17
8
1
module Main (main) where import qualified ColorBench -- HASKELETON: import qualified New.ModuleBench import Criterion.Main (bgroup, defaultMain) main :: IO () main = defaultMain [ bgroup "Color" ColorBench.benchmarks -- HASKELETON: , bgroup "New.Module" New.ModuleBench.benchmarks ]
tcsavage/color
benchmark/Bench.hs
mit
298
0
8
49
56
33
23
6
1
module Event where import Data.Acid import Query import Types import Update makeAcidic ''Database [ 'findUser , 'getUserProfile , 'getEntries , 'register , 'createEntry , 'updateEntry ]
ktvoelker/todo
src/Event.hs
gpl-3.0
205
0
6
45
52
34
18
-1
-1
-- | parse DIMACS format. -- Declarations of no. of variables and clauses are ignored. module Satchmo.Parse where import Satchmo.Form -- import Satchmo.Data import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy.Char8 as BSC import qualified Data.Attoparsec.ByteString.Char8 as A import Data.Foldable ( foldl' ) import Control.Applicative form :: BS.ByteString -> CNF form s = foldl' ( \ f line -> case A.parseOnly ( pline <* A.endOfInput ) $ BSC.toStrict line of Left msg -> f Right ns -> let cl = clause $ map (\ n -> (toEnum $ abs n, n>0) ) $ takeWhile (/= 0) ns in add_clauses [cl] f ) Satchmo.Form.empty $ BSC.lines s pline :: A.Parser [Int] pline = A.many1 $ ( A.signed A.decimal <* A.many' (A.satisfy A.isSpace ) )
jwaldmann/satchmo-solver
src/Satchmo/Parse.hs
gpl-3.0
856
0
23
230
266
147
119
20
2
module Evaluation where import Chromosome import Utility evaluateDataset :: Dataset -> Chromosome -> Double evaluateDataset ds c = mean $ map (\ (d, z) -> sqDist z $ evaluate c d) ds
mrlovre/super-memory
Pro4/src/Evaluation.hs
gpl-3.0
206
0
10
55
68
37
31
5
1
---------------------------------------------- -- This test suite is the most important one for Lambdacula Engine. -- It will check the rules are respected for the given scenario : -- -- a) A world with two rooms. There is a door between the two of them, but it is closed. -- b) The first room contains a test cube. The test cube contains a key. -- c) The key opens the door. -- d) The second room contains a test man. -- e) Talking to test man about tests make the game comes to an end. -- -- To be efficient, we need to test actions before some previous conditions -- are met. For instance, opening the door with the key before retrieving the -- key. -- ----------------------------------------------- -- These are hspec tests. import Test.Hspec import Test.QuickCheck import Control.Monad.State import Control.Lens hiding (Action) import Lambdacula.Action import Lambdacula.World import Lambdacula.GameData import Lambdacula.WorldBuilder import Lambdacula.Flow import Lambdacula.Display import Lambdacula.Reactions import qualified Data.Map as Map import qualified Data.Foldable as Fd import Data.List import System.Console.Haskeline -- Constants -- examineString = "A simple test cube. Look, how pretty !" sayhello = "hello world !" zilchReaction = [Display "Err... no."] openCubeReaction :: [Reaction] openCubeReaction = [ChangeStatus "cube" Opened, Display "You open the cube !"] -- Reaction tuples reactions_tests = [("cube", Take, Just "key", [], [PickFromContainer "cube" "key"]) ,("cube", Examine, Nothing, [], [Display examineString]) ,("cube", Open, Nothing, [], openCubeReaction) ,("cube", Zilch, Nothing, [], zilchReaction) ,("thingamabob", Take, Nothing, [], [PickItem "thingamabob" "You pick a thingamabob !"]) ,("dude", Talk, Nothing, [], [Conversation charatopics charaanswers undefined])] -- Rooms trRooms = [Room "The test room" "You are standing in a non-existant place in a virtual world. This is a very good place to hold existential thoughts. Or test the system. But this is more or less the same thing, innit ?" Nada ,Room "A second room" "You are in a second room. It doesn't exist, like the first one; so really, you moved but you didn't move. I know, I know, this sounds absurd. And to a point, it is." Nada] -- Characters charatopics = [("hello", ["hi", "yo"]), ("endgame", [])] charaanswers = [("hello", sayhello),("endgame", "Just say end to me")] -- Objects trObjects = [Exit (ObjectNames ["A test door", "door"]) "The test room" (RoomObjectDetails Closed "A hermetically locked door" []) (Just (DoorInfo (Just "key"))) "A second room" , makeExit ["south"] "A second room" "A door" "The test room" , RoomObject (ObjectNames ["cube", "the test cube","test cube"]) "The test room" (RoomObjectDetails Closed "There is a nice test cube here." [keyObject]) , RoomObject (ObjectNames ["dude"]) "The test room" (RoomObjectDetails Nada "A dude" [simpleObject ["thing"] "" "A thing to be tested"]) , simpleObject ["thingamabob"] "The test room" "An object used in a test"] keyObject = simpleObject ["key", "a key"] "NOWHERE" "Nothing worth looking at" -- World world = buildWorld "test" trRooms trObjects reactions_tests -- The series of action the player is expected to perform, -- in the proper order, in our test world. properActions = [(Interaction Open "cube") ,(Complex Take "cube" "key") ,(Complex Use "door" "key") ,(Interaction Move "door")] ----- Utilities ----- handleProceed x = case proceed x of Right a -> a Left _ -> error "Proceed did not call a WorldAction !" -- Apply an action, get the first String result testProceed x = head . fst $ runState (handleProceed x) world -- Check re probeReactions :: (String, Action, Maybe String) -> [Reaction] probeReactions trio = fst $ runState (findReactions trio) world -- Test a given reaction testReaction :: Reaction -> (World -> Bool) -> Bool testReaction reaction f = f resultingWorld where resultingWorld = snd $ runState (onlyDo reaction) world -- Test the result of a series of reactions testReactions :: [Reaction] -> (World -> Bool) -> Bool testReactions reactions f = f resultingWorld where resultingWorld = snd $ runState (mapM onlyDo reactions) world -- Do a list of actions. Save the world. Reload the world. -- Applies a checking function on the world to make sure the loaded world -- kept tracks of state-changes. saveLoadAndCheck :: String -> [PlayerAction] -> (World -> Bool) -> IO Bool saveLoadAndCheck filename actions test = do save filename $ snd $ runState (multiProceed actions) world w <- (load trRooms reactions_tests filename) return $ test w -- Apply actions, then apply a boolean function on the world -- to make sure state has changed. checkWorld :: [PlayerAction] -> (World -> Bool) -> Bool checkWorld x t = t . snd $ runState (multiProceed x) world -- Do a series of actions - BLAAAH, UGLY ! Need to refactor this, but it's late. TODO. multiProceed :: [PlayerAction] -> WorldAction multiProceed [] = return [] multiProceed [action] = handleProceed action multiProceed (action:actions) = do handleProceed action multiProceed actions -- Get the string result from an action testFeedback act = fst $ runState (handleProceed act) world -- Get the last string result from a list of actions testFeedbacks acts = last . fst $ runState (multiProceed acts) world ---- Various boolean functions ---- -- Make sure the player has no objects. playerInventoryIsEmpty :: World -> Bool playerInventoryIsEmpty w = length(w^.playerObjects) == 0 -- Make sure the player has a given object. playerInventoryContains :: RoomObject -> World -> Bool playerInventoryContains ro w = ro { _inRoom = playerPockets } `elem` (w^.playerObjects) -- Check the status of an object, make sure it is what we except. checkStatus :: String -- Name of the object -> ObjectStatus -- Status this object should have -> World -- The world -> Bool -- Does the status match ? checkStatus s st w = case find ((==) s . mainName) (_worldObjects w) of Just x -> x^.objectStatus == st Nothing -> error "Test poorly written !" -- Make sure the currentRoom is the one we believe it should be checkCurrentRoom :: String -> World -> Bool checkCurrentRoom s w = view currentRoomName w == s roomContains :: String -> World -> Bool roomContains s w = s `elem` map (mainName) (view fullCurrentObjects w) -- Make sure an item contains something checkItemContains :: String -- Container -> String -- Contained -> World -- Our test world -> Bool checkItemContains container contained w = contained `elem` map (mainName) (view containedObjects getObject) where getObject = case identify container w of [] -> error $ "No object named " ++ container ++ " !" xs -> head xs checkPlayerName :: String -> World -> Bool checkPlayerName s w = s == _player w main :: IO() main = hspec $ do describe "reaction matching" $ do it "Finds the proper reaction when trying to open the cube" $ do probeReactions ("cube", Open, Nothing) `shouldBe` openCubeReaction it "Finds no reaction when trying to move the dude" $ do probeReactions ("dude", Move, Nothing) `shouldBe` [] it "Make sure the Zilch case is used when no other case work" $ do probeReactions ("cube", Eat, Nothing) `shouldBe` zilchReaction describe "reaction processing" $ do it "Check ChangeStatus" $ do testReaction (head openCubeReaction) (checkStatus "cube" Opened) `shouldBe` True it "Check PickFromContainer - when not opened, can't pick" $ do testReaction (PickFromContainer "cube" "key") (playerInventoryIsEmpty) `shouldBe` True it "Check PickFromContainer - when opened, pick" $ do testReactions ([ChangeStatus "cube" Opened, PickFromContainer "cube" "key"]) (playerInventoryIsEmpty) `shouldBe` False it "Check GetFromCharacter" $ do testReaction (GetFromCharacter "dude" "thing") (playerInventoryIsEmpty) `shouldBe` False it "Check pickItem once - should be able to pick an item" $ do testReaction (PickItem "thingamabob" "You pick a thingamabob") (roomContains "thingamabob") `shouldBe` False it "Check pickItem twice - second time should not work" $ do testFeedbacks [Interaction Take "thingamabob", Interaction Take "thingamabob"] `shouldBe` "You already have a thingamabob !" it "Check PutInsideContainer - doesn't have object, container opened - should fail" $ do testReactions ([ChangeStatus "cube" Opened, PutInsideContainer "cube" "thingamabob" ""]) (checkItemContains "cube" "thingamabob") `shouldBe` False it "Check PutInsideContainer - has object, container closed - should fail" $ do testReactions ([PickItem "thingamabob" "", PutInsideContainer "cube" "thingamabob" ""]) (checkItemContains "cube" "thingamabob") `shouldBe` False it "Check PutInsideContainer - has object, container opened - should work" $ do testReactions ([PickItem "thingamabob" "", ChangeStatus "cube" Opened, PutInsideContainer "cube" "thingamabob" ""]) (checkItemContains "cube" "thingamabob") `shouldBe` True describe "String feedback" $ do it "Make sure the proper string is displayed when examining the cube" $ do testFeedback (Interaction Examine "cube") `shouldBe` [examineString] describe "conversation" $ do it "Make sure the proper string is displayed when talking to the dude" $ do testFeedback (Complex Talk "dude" "hello") `shouldBe` ["\"" ++ sayhello ++ "\""] it "Make sure the hello string is displayed when talking with no subject" $ do testFeedback (Interaction Talk "dude") `shouldBe` ["\"" ++ sayhello ++ "\""] it "Make sure the hello string is displayed when using an alias" $ do testFeedback (Complex Talk "dude" "yo") `shouldBe` ["\"" ++ sayhello ++ "\""] describe "scenario" $ do it "Tries to take the key out of the cube but fails, because it is closed" $ do checkWorld ([Complex Take "cube" "key"]) playerInventoryIsEmpty `shouldBe` True it "Tries to go to the new room but fails because the door is closed" $ do checkWorld ([Interaction Move "north"]) (checkCurrentRoom "The test room") `shouldBe` True it "Opens the cube" $ do checkWorld ([Interaction Open "cube"]) (checkStatus "cube" Opened) `shouldBe` True it "Tries to open the door while not having the key" $ do checkWorld ([(properActions !! 0), (properActions !! 2)]) (checkStatus "A test door" Closed) `shouldBe` True it "Tries to pick up the key without opening the cube first and fails" $ do checkWorld ([properActions !! 1]) playerInventoryIsEmpty `shouldBe` True it "Open the cube, takes the key" $ do checkWorld (take 2 properActions) (playerInventoryContains keyObject) `shouldBe` True it "Open the cube, take the key and open the door" $ do checkWorld (take 3 properActions) (checkStatus "A test door" Opened) `shouldBe` True it "Do every action to open the door and cross it" $ do checkWorld (take 4 properActions) (checkCurrentRoom "A second room") `shouldBe` True describe "saving" $ do it "Checks that the world can be saved" $ do saveLoadAndCheck "test.lcdl" (take 4 properActions) (checkCurrentRoom "A second room") >>= (`shouldBe` True) it "Checks that the player name is well read in the savegame" $ do saveLoadAndCheck "test2.lcdl" ([]) (checkPlayerName "test") >>= (`shouldBe` True)
Raveline/lambdacula
test/SpecWorld.hs
gpl-3.0
12,348
0
19
3,044
2,672
1,401
1,271
153
2
{-# LANGUAGE FlexibleContexts , OverloadedStrings , DeriveGeneric #-} module Application where import Imports hiding ((</>)) import Routes import qualified Data.Text as T import Control.Monad.Reader import Control.Monad.Catch import System.Directory import GHC.Generics data AuthRole = NeedsLogin data AuthErr = NeedsAuth deriving (Generic, Show, Eq) instance Exception AuthErr authorize :: ( MonadThrow m ) => Request -> [AuthRole] -> m () -- authorize _ _ = return id -- uncomment to force constant authorization authorize req ss | null ss = return () | otherwise = throwM NeedsAuth securityLayer :: MiddlewareT AppM securityLayer app req resp = do extractAuth authorize req routes app req resp contentLayer :: MiddlewareT AppM contentLayer = route routes staticLayer :: MonadApp m => MiddlewareT m staticLayer app req respond = do let fileRequested = T.unpack . T.intercalate "/" $ pathInfo req basePath <- envStatic <$> ask let file = basePath ++ "/" ++ fileRequested fileExists <- liftIO (doesFileExist file) if fileExists then respond $ responseFile status200 [] file Nothing else app req respond defApp :: Application defApp _ respond = respond $ textOnly "Not Found! :(" status404 []
athanclark/happ-store
src/Application.hs
gpl-3.0
1,327
0
13
315
363
184
179
40
2
-- Copyright (C) 2012 Jonathan Lamothe -- 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 Types ( GameState (..) , Position , Orphanage (..) , BldgPos (..) , Corner (..) , Object (..) , objDraw , Interactive (..) , interHandleEvent , getMapRect , originX , originY ) where import qualified Data.Map as Map import Control.Monad import qualified Graphics.UI.SDL as SDL import qualified System.Random as Rand data GameState = GameState { surface :: SDL.Surface , audio :: Bool , gen :: Rand.StdGen , playerPos :: Position , playerTile :: SDL.Surface , grassTile :: SDL.Surface , bldgTile :: SDL.Surface , roadIntTile :: SDL.Surface , roadHorizTile :: SDL.Surface , roadVertTile :: SDL.Surface , orphanagePic :: SDL.Surface , orphanage :: Orphanage , gameOver :: Bool } deriving Show type Position = (Int, Int) data Orphanage = Orphanage { orphanPos :: BldgPos } deriving Show data BldgPos = BldgPos { bldgIntersection :: Position , bldgCorner :: Corner } deriving Show data Corner = NorthWest | NorthEast | SouthWest | SouthEast deriving (Eq, Show) class Object o where objGetGeom :: GameState -> o -> SDL.Rect objIsVisible :: o -> Bool objIsVisible _ = True objSetVisible :: Bool -> o -> o objSetVisible _ obj = obj objOnDraw :: SDL.Surface -> o -> IO () objOnDraw _ _ = return () objDraw :: Object o => SDL.Surface -> o -> IO Bool objDraw surf obj | objIsVisible obj = objOnDraw surf obj >> return True | otherwise = return False class Object i => Interactive i where interIsEnabled :: i -> Bool interIsEnabled _ = True interSetEnable :: Bool -> i -> i interSetEnable _ obj = obj interWasMouseOver :: i -> Maybe Bool interWasMouseOver _ = Nothing interSetMouseWasOver :: Bool -> i -> i interSetMouseWasOver _ obj = obj interIsPressed :: i -> Maybe Bool interIsPressed obj = Nothing interSetPressed :: Bool -> i -> i interSetPressed _ obj = obj interOnMouseOver :: GameState -> i -> (GameState, i) interOnMouseOver gs obj = (gs, obj) interOnMouseOut :: GameState -> i -> (GameState, i) interOnMouseOut gs obj = (gs, obj) interOnPress :: GameState -> i -> (GameState, i) interOnPress gs obj = (gs, obj) interOnRelease :: GameState -> i -> (GameState, i) interOnRelease gs obj = (gs, obj) interOnClick :: GameState -> i -> (GameState, i) interOnClick gs obj = (gs, obj) interHandleEvent :: Interactive i => GameState -> SDL.Event -> i -> (GameState, i) interHandleEvent gs (SDL.MouseMotion x y _ _) obj | interIsEnabled obj = case interWasMouseOver obj of Just True -> if isInObj gs obj x y then (gs, obj) else interOnMouseOut gs $ interSetMouseWasOver False obj Just False -> if isInObj gs obj x y then interOnMouseOver gs $ interSetMouseWasOver True obj else (gs, obj) Nothing -> (gs, obj) | otherwise = (gs, obj) interHandleEvent gs (SDL.MouseButtonDown x y _) obj | interIsEnabled obj = if isInObj gs obj x y then interOnPress gs $ interSetPressed True obj else (gs, obj) | otherwise = (gs, obj) interHandleEvent gs (SDL.MouseButtonUp x y _) obj | interIsEnabled obj && interIsPressed obj == Just True = if isInObj gs obj y x then interOnClick gs $ interSetPressed False obj else interOnRelease gs $ interSetPressed False obj | otherwise = (gs, obj) interHandleEvent gs _ obj = (gs, obj) isInObj :: (Object o, Integral i) => GameState -> o -> i -> i -> Bool isInObj gs obj x y = isInRect (objGetGeom gs obj) x y isInRect :: Integral i => SDL.Rect -> i -> i -> Bool isInRect (SDL.Rect rX rY w h) x y = x >= x1 && x <= x2 && y >= y1 && y <= y2 where x1 = fromIntegral rX y1 = fromIntegral rY x2 = x1 + fromIntegral w y2 = y1 + fromIntegral h getMapRect :: Integral i => i -> i -> SDL.Rect getMapRect x y = SDL.Rect x' y' 16 16 where x' = fromIntegral $ originX + 16 * x y' = fromIntegral $ originY + 16 * y originX :: Integral i => i originX = (640 - 16) `div` 2 originY :: Integral i => i originY = (480 - 16) `div` 2 -- jl
jlamothe/LD25
Types.hs
gpl-3.0
4,874
0
11
1,253
1,500
812
688
129
7
{-# 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.AndroidEnterprise.Users.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deleted an EMM-managed user. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.users.delete@. module Network.Google.Resource.AndroidEnterprise.Users.Delete ( -- * REST Resource UsersDeleteResource -- * Creating a Request , usersDelete , UsersDelete -- * Request Lenses , udXgafv , udUploadProtocol , udEnterpriseId , udAccessToken , udUploadType , udUserId , udCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.users.delete@ method which the -- 'UsersDelete' request conforms to. type UsersDeleteResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "users" :> Capture "userId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Deleted an EMM-managed user. -- -- /See:/ 'usersDelete' smart constructor. data UsersDelete = UsersDelete' { _udXgafv :: !(Maybe Xgafv) , _udUploadProtocol :: !(Maybe Text) , _udEnterpriseId :: !Text , _udAccessToken :: !(Maybe Text) , _udUploadType :: !(Maybe Text) , _udUserId :: !Text , _udCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UsersDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udXgafv' -- -- * 'udUploadProtocol' -- -- * 'udEnterpriseId' -- -- * 'udAccessToken' -- -- * 'udUploadType' -- -- * 'udUserId' -- -- * 'udCallback' usersDelete :: Text -- ^ 'udEnterpriseId' -> Text -- ^ 'udUserId' -> UsersDelete usersDelete pUdEnterpriseId_ pUdUserId_ = UsersDelete' { _udXgafv = Nothing , _udUploadProtocol = Nothing , _udEnterpriseId = pUdEnterpriseId_ , _udAccessToken = Nothing , _udUploadType = Nothing , _udUserId = pUdUserId_ , _udCallback = Nothing } -- | V1 error format. udXgafv :: Lens' UsersDelete (Maybe Xgafv) udXgafv = lens _udXgafv (\ s a -> s{_udXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). udUploadProtocol :: Lens' UsersDelete (Maybe Text) udUploadProtocol = lens _udUploadProtocol (\ s a -> s{_udUploadProtocol = a}) -- | The ID of the enterprise. udEnterpriseId :: Lens' UsersDelete Text udEnterpriseId = lens _udEnterpriseId (\ s a -> s{_udEnterpriseId = a}) -- | OAuth access token. udAccessToken :: Lens' UsersDelete (Maybe Text) udAccessToken = lens _udAccessToken (\ s a -> s{_udAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). udUploadType :: Lens' UsersDelete (Maybe Text) udUploadType = lens _udUploadType (\ s a -> s{_udUploadType = a}) -- | The ID of the user. udUserId :: Lens' UsersDelete Text udUserId = lens _udUserId (\ s a -> s{_udUserId = a}) -- | JSONP udCallback :: Lens' UsersDelete (Maybe Text) udCallback = lens _udCallback (\ s a -> s{_udCallback = a}) instance GoogleRequest UsersDelete where type Rs UsersDelete = () type Scopes UsersDelete = '["https://www.googleapis.com/auth/androidenterprise"] requestClient UsersDelete'{..} = go _udEnterpriseId _udUserId _udXgafv _udUploadProtocol _udAccessToken _udUploadType _udCallback (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy UsersDeleteResource) mempty
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Users/Delete.hs
mpl-2.0
4,743
0
19
1,181
785
456
329
113
1
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module HLol.Data.Match where import Control.Applicative import Control.Lens import Control.Monad import Data.Aeson import qualified Data.Map as M import Data.Maybe (isJust, fromJust) import Data.Text (pack) data Position = Position { _x :: Int, _y :: Int } deriving (Eq, Show) makeLenses ''Position instance FromJSON Position where parseJSON (Object v) = Position <$> v .: "x"<*> v .: "y" parseJSON _ = mzero data ParticipantFrame = ParticipantFrame { _currentGold :: Int, _jungleMinionsKilled :: Int, _level :: Int, _participantMinionsKilled :: Int, _participantFrameId :: Int, _participantFramePosition :: Maybe Position, _totalGold :: Int, _xp :: Int } deriving (Eq, Show) makeLenses ''ParticipantFrame instance FromJSON ParticipantFrame where parseJSON (Object v) = ParticipantFrame <$> v .: "currentGold"<*> v .: "jungleMinionsKilled"<*> v .: "level"<*> v .: "minionsKilled"<*> v .: "participantId"<*> v .:? "position"<*> v .: "totalGold"<*> v .: "xp" parseJSON _ = mzero data Event = Event { _ascendedType :: Maybe String, _assistingParticipantIds :: Maybe [Int], _buildingType :: Maybe String, _creatorId :: Maybe Int, _eventType :: Maybe String, _itemAfter :: Maybe Int, _itemBefore :: Maybe Int, _itemId :: Maybe Int, _killerId :: Maybe Int, _laneType :: Maybe String, _levelUpType :: Maybe String, _monsterType :: Maybe String, _eventParticipantId :: Maybe Int, _pointCaptured :: Maybe String, _position :: Maybe Position, _skillSlot :: Maybe Int, _eventTeamId :: Maybe Int, _eventTimestamp :: Maybe Int, _towerType :: Maybe String, _victimId :: Maybe Int, _wardType :: Maybe String } deriving (Eq, Show) makeLenses ''Event instance FromJSON Event where parseJSON (Object v) = Event <$> v .:? "ascendedType"<*> v .:? "assistingParticipantIds"<*> v .:? "buildingType"<*> v .:? "creatorId"<*> v .:? "eventType"<*> v .:? "itemAfter"<*> v .:? "itemBefore"<*> v .:? "itemId"<*> v .:? "killerId"<*> v .:? "laneType"<*> v .:? "levelUpType"<*> v .:? "monsterType"<*> v .:? "participantId"<*> v .:? "pointCaptured"<*> v .:? "position"<*> v .:? "skillSlot"<*> v .:? "teamId"<*> v .:? "timestamp"<*> v .:? "towerType"<*> v .:? "victimId"<*> v .:? "wardType" parseJSON _ = mzero data ParticipantTimelineData = ParticipantTimelineData { _tenToTwenty :: Double, _thirtyToEnd :: Maybe Double, _twentyToThirty :: Maybe Double, _zeroToTen :: Double } deriving (Eq, Show) makeLenses ''ParticipantTimelineData instance FromJSON ParticipantTimelineData where parseJSON (Object v) = ParticipantTimelineData <$> v .: "tenToTwenty"<*> v .:? "thirtyToEnd"<*> v .:? "twentyToThirty"<*> v .: "zeroToTen" parseJSON _ = mzero data Frame = Frame { _events :: Maybe [Event], _participantFrames :: M.Map String ParticipantFrame, _timestamp :: Int } deriving (Eq, Show) makeLenses ''Frame instance FromJSON Frame where parseJSON (Object v) = Frame <$> v .:? "events"<*> v .: "participantFrames"<*> v .: "timestamp" parseJSON _ = mzero data BannedChampion = BannedChampion { _champId :: Int, _pickTurn :: Int } deriving (Eq, Show) makeLenses ''BannedChampion instance FromJSON BannedChampion where parseJSON (Object v) = BannedChampion <$> v .: "championId"<*> v .: "pickTurn" parseJSON _ = mzero data Player = Player { _matchHistoryUri :: String, _profileIcon :: Int, _summonerId :: Int, _summonerName :: String } deriving (Eq, Show) makeLenses ''Player instance FromJSON Player where parseJSON (Object v) = Player <$> v .: "matchHistoryUri"<*> v .: "profileIcon"<*> v .: "summonerId"<*> v .: "summonerName" parseJSON _ = mzero data Rune = Rune { _runeRank :: Int, _runeId :: Int } deriving (Eq, Show) makeLenses ''Rune instance FromJSON Rune where parseJSON (Object v) = Rune <$> v .: "rank"<*> v .: "runeId" parseJSON _ = mzero data ParticipantTimeline = ParticipantTimeline { _lane :: String, _role :: String, _timelineData :: M.Map String ParticipantTimelineData } deriving (Eq, Show) makeLenses ''ParticipantTimeline instance FromJSON ParticipantTimeline where parseJSON (Object v) = do l <- v .: "lane" r <- v .: "role" d <- mapM ((v .:?) . pack) ks return $ ParticipantTimeline l r $ M.fromList $ map (\(k, w) -> (k, fromJust w)) $ filter (isJust . snd) $ zip ks d where ks = [ "ancientGolemAssistsPerMinCounts", "ancientGolemKillsPerMinCounts", "assistedLaneDeathsPerMinDeltas", "assistedLaneKillsPerMinDeltas", "baronAssistsPerMinCounts", "baronKillsPerMinCounts", "creepsPerMinDeltas", "csDiffPerMinDeltas", "damageTakenDiffPerMinDeltas", "damageTakenPerMinDeltas", "dragonAssistsPerMinCounts", "dragonKillsPerMinCounts", "elderLizardAssistsPerMinCounts", "elderLizardKillsPerMinCounts", "goldPerMinDeltas", "inhibitorAssistsPerMinCounts", "inhibitorKillsPerMinCounts", "towerAssistsPerMinCounts", "towerKillsPerMinCounts", "towerKillsPerMinDeltas", "vilemawAssistsPerMinCounts", "vilemawKillsPerMinCounts", "wardsPerMinDeltas", "xpDiffPerMinDeltas", "xpPerMinDeltas" ] parseJSON _ = mzero data ParticipantStats = ParticipantStats { _assists :: Int, _champLevel :: Int, _combatPlayerScore :: Int, _deaths :: Int, _doubleKills :: Int, _firstBloodAssist :: Bool, _firstBloodKill :: Bool, _firstInhibitorAssist :: Bool, _firstInhibitorKill :: Bool, _firstTowerAssist :: Bool, _firstTowerKill :: Bool, _goldEarned :: Int, _goldSpent :: Int, _participantInhibitorKills :: Int, _item0 :: Int, _item1 :: Int, _item2 :: Int, _item3 :: Int, _item4 :: Int, _item5 :: Int, _item6 :: Int, _killingSprees :: Int, _kills :: Int, _largestCriticalStrike :: Int, _largestKillingSpree :: Int, _largestMultiKill :: Int, _magicDamageDealt :: Int, _magicDamageDealtToChampions :: Int, _magicDamageTaken :: Int, _minionsKilled :: Int, _neutralMinionsKilled :: Int, _neutralMinionsKilledEnemyJungle :: Int, _neutralMinionsKilledTeamJungle :: Int, _nodeCapture :: Maybe Int, _nodeCaptureAssist :: Maybe Int, _nodeNeutralize :: Maybe Int, _nodeNeutralizeAssist :: Maybe Int, _objectivePlayerScore :: Int, _pentaKills :: Int, _physicalDamageDealt :: Int, _physicalDamageDealtToChampions :: Int, _physicalDamageTaken :: Int, _quadraKills :: Int, _sightWardsBoughtInGame :: Int, _teamObjective :: Maybe Int, _totalDamageDealt :: Int, _totalDamageDealtToChampions :: Int, _totalDamageTaken :: Int, _totalHeal :: Int, _totalPlayerScore :: Int, _totalScoreRank :: Int, _totalTimeCrowdControlDealt :: Int, _totalUnitsHealed :: Int, _participantTowerKills :: Int, _tripleKills :: Int, _trueDamageDealt :: Int, _trueDamageDealtToChampions :: Int, _trueDamageTaken :: Int, _unrealKills :: Int, _visionWardsBoughtInGame :: Int, _wardsKilled :: Int, _wardsPlaced :: Int, _participantWinner :: Bool } deriving (Eq, Show) makeLenses ''ParticipantStats instance FromJSON ParticipantStats where parseJSON (Object v) = ParticipantStats <$> v .: "assists"<*> v .: "champLevel"<*> v .: "combatPlayerScore"<*> v .: "deaths"<*> v .: "doubleKills"<*> v .: "firstBloodAssist"<*> v .: "firstBloodKill"<*> v .: "firstInhibitorAssist"<*> v .: "firstInhibitorKill"<*> v .: "firstTowerAssist"<*> v .: "firstTowerKill"<*> v .: "goldEarned"<*> v .: "goldSpent"<*> v .: "inhibitorKills"<*> v .: "item0"<*> v .: "item1"<*> v .: "item2"<*> v .: "item3"<*> v .: "item4"<*> v .: "item5"<*> v .: "item6"<*> v .: "killingSprees"<*> v .: "kills"<*> v .: "largestCriticalStrike"<*> v .: "largestKillingSpree"<*> v .: "largestMultiKill"<*> v .: "magicDamageDealt"<*> v .: "magicDamageDealtToChampions"<*> v .: "magicDamageTaken"<*> v .: "minionsKilled"<*> v .: "neutralMinionsKilled"<*> v .: "neutralMinionsKilledEnemyJungle"<*> v .: "neutralMinionsKilledTeamJungle"<*> v .:? "nodeCapture"<*> v .:? "nodeCaptureAssist"<*> v .:? "nodeNeutralize"<*> v .:? "nodeNeutralizeAssist"<*> v .: "objectivePlayerScore"<*> v .: "pentaKills"<*> v .: "physicalDamageDealt"<*> v .: "physicalDamageDealtToChampions"<*> v .: "physicalDamageTaken"<*> v .: "quadraKills"<*> v .: "sightWardsBoughtInGame"<*> v .:? "teamObjective"<*> v .: "totalDamageDealt"<*> v .: "totalDamageDealtToChampions"<*> v .: "totalDamageTaken"<*> v .: "totalHeal"<*> v .: "totalPlayerScore"<*> v .: "totalScoreRank"<*> v .: "totalTimeCrowdControlDealt"<*> v .: "totalUnitsHealed"<*> v .: "towerKills"<*> v .: "tripleKills"<*> v .: "trueDamageDealt"<*> v .: "trueDamageDealtToChampions"<*> v .: "trueDamageTaken"<*> v .: "unrealKills"<*> v .: "visionWardsBoughtInGame"<*> v .: "wardsKilled"<*> v .: "wardsPlaced"<*> v .: "winner" parseJSON _ = mzero data Mastery = Mastery { _masteryId :: Int, _masteryRank :: Int } deriving (Eq, Show) makeLenses ''Mastery instance FromJSON Mastery where parseJSON (Object v) = Mastery <$> v .: "masteryId"<*> v .: "rank" parseJSON _ = mzero data Timeline = Timeline { _frameInterval :: Int, _frames :: [Frame] } deriving (Eq, Show) makeLenses ''Timeline instance FromJSON Timeline where parseJSON (Object v) = Timeline <$> v .: "frameInterval"<*> v .: "frames" parseJSON _ = mzero data Team = Team { _bans :: [BannedChampion], _baronKills :: Int, _dominionVictoryScore :: Maybe Int, _dragonKills :: Int, _firstBaron :: Bool, _firstBlood :: Bool, _firstDragon :: Bool, _firstInhibitor :: Bool, _firstTower :: Bool, _inhibitorKills :: Int, _teamId :: Int, _towerKills :: Int, _vilemawKills :: Int, _winner :: Bool } deriving (Eq, Show) makeLenses ''Team instance FromJSON Team where parseJSON (Object v) = Team <$> v .: "bans"<*> v .: "baronKills"<*> v .:? "dominionVictoryScore"<*> v .: "dragonKills"<*> v .: "firstBaron"<*> v .: "firstBlood"<*> v .: "firstDragon"<*> v .: "firstInhibitor"<*> v .: "firstTower"<*> v .: "inhibitorKills"<*> v .: "teamId"<*> v .: "towerKills"<*> v .: "vilemawKills"<*> v .: "winner" parseJSON _ = mzero data ParticipantIdentity = ParticipantIdentity { _pId :: Int, _player :: Player } deriving (Eq, Show) makeLenses ''ParticipantIdentity instance FromJSON ParticipantIdentity where parseJSON (Object v) = ParticipantIdentity <$> v .: "participantId"<*> v .: "player" parseJSON _ = mzero data Participant = Participant { _championId :: Int, _highestAchievedSeasonTier :: String, _masteries :: [Mastery], _participantId :: Int, _runes :: Maybe [Rune], _spell1Id :: Int, _spell2Id :: Int, _stats :: ParticipantStats, _participantTeamId :: Int, _participantTimeline :: ParticipantTimeline } deriving (Eq, Show) makeLenses ''Participant instance FromJSON Participant where parseJSON (Object v) = Participant <$> v .: "championId"<*> v .: "highestAchievedSeasonTier"<*> v .: "masteries"<*> v .: "participantId"<*> v .:? "runes"<*> v .: "spell1Id"<*> v .: "spell2Id"<*> v .: "stats"<*> v .: "teamId"<*> v .: "timeline" parseJSON _ = mzero data MatchDetail = MatchDetail { _mapId :: Int, _matchCreation :: Int, _matchDuration :: Int, _matchId :: Int, _matchMode :: String, _matchType :: String, _matchVersion :: String, _participantIdentities :: [ParticipantIdentity], _participants :: [Participant], _platformId :: String, _queueType :: String, _region :: String, _season :: String, _teams :: [Team], _timeline :: Timeline } deriving (Eq, Show) makeLenses ''MatchDetail instance FromJSON MatchDetail where parseJSON (Object v) = MatchDetail <$> v .: "mapId"<*> v .: "matchCreation"<*> v .: "matchDuration"<*> v .: "matchId"<*> v .: "matchMode"<*> v .: "matchType"<*> v .: "matchVersion"<*> v .: "participantIdentities"<*> v .: "participants"<*> v .: "platformId"<*> v .: "queueType"<*> v .: "region"<*> v .: "season"<*> v .: "teams"<*> v .: "timeline" parseJSON _ = mzero
tetigi/hlol
src/HLol/Data/Match.hs
agpl-3.0
13,467
0
131
3,573
3,496
1,914
1,582
423
0
{- | Module: Postmaster.IO Copyright: (C) 2004-2019 Peter Simons License: GNU AFFERO GPL v3 or later Maintainer: simons@cryp.to Stability: experimental Portability: non-portable -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Postmaster.IO where import Postmaster.Error import Postmaster.Log import Postmaster.Prelude import Control.Exception ( AssertionFailed(..) ) import Network.Socket import qualified Network.Socket.ByteString as Socket data NetworkPeer m = NetworkPeer { _readFromPeer :: Word16 -> m ByteString, _sendToPeer :: ByteString -> m () } makeClassy ''NetworkPeer socketIO :: MonadIO m => Socket -> NetworkPeer m socketIO s = NetworkPeer (liftIO . Socket.recv s . fromIntegral) (liftIO . Socket.sendAll s) type MonadPeer env m = (MonadReader env m, HasNetworkPeer env m) recv :: (MonadPeer env m) => Word16 -> m ByteString recv len = view readFromPeer >>= \f -> f len send :: (MonadPeer env m) => ByteString -> m () send buf = view sendToPeer >>= \f -> f buf type SocketHandler m = (Socket, SockAddr) -> m () listener :: MonadUnliftIO m => (Maybe HostName, ServiceName) -> SocketHandler m -> m () listener (host,port) socketHandler = do let hints = defaultHints { addrFlags = [AI_PASSIVE], addrSocketType = Stream } ais <- liftIO (getAddrInfo (Just hints) host (Just port)) if null ais then throwIO (AssertionFailed ("getAddrInfo " <> show (host,port) <> " returned no result")) else withListenSocket socketHandler (head ais) withListenSocket :: MonadUnliftIO m => SocketHandler m -> AddrInfo -> m () withListenSocket socketHandler ai = errorContext (show (addrAddress ai)) $ bracket (liftIO (socket (addrFamily ai) (addrSocketType ai) (addrProtocol ai))) (liftIO . close) $ \sock -> do liftIO $ do setSocketOption sock ReuseAddr 1 withFdSocket sock setCloseOnExecIfNeeded bind sock (addrAddress ai) listen sock 10 socketHandler (sock, addrAddress ai) acceptor :: (MonadUnliftIO m, MonadLog env m) => SocketHandler m -> SocketHandler m acceptor socketHandler (listenSocket,listenAddr) = enterContext ("listener " <> show listenAddr) $ do logInfo "accepting incoming connections" forever $ bracketOnError (liftIO (accept listenSocket)) (liftIO . close . fst) $ \peer@(connSock, connAddr) -> do logDebug $ "new incoming connection from " <> display connAddr forkIOWithUnmask $ \unmask -> unmask (enterContext (show connAddr) (logUncaughtExceptions (socketHandler peer))) `finally` liftIO (close connSock) -- | Wrap 'getNameInfo' for a more useful interface. Further details are at -- https://github.com/haskell/network/issues/416. resolvePtr :: MonadIO m => SockAddr -> m (Maybe HostName) resolvePtr addr = liftIO $ handleIO (const (return Nothing)) $ fst <$> Network.Socket.getNameInfo [NI_NAMEREQD] True False addr -- | Show a socket's IP address. -- -- >>> showAddress (SockAddrInet defaultPort (tupleToHostAddress (1,2,3,4))) -- "1.2.3.4" -- >>> showAddress (SockAddrInet6 defaultPort 0 (tupleToHostAddress6 (1,2,3,4,5,6,7,8)) 0) -- "1:2:3:4:5:6:7:8" showAddress :: MonadIO m => SockAddr -> m String showAddress addr = liftIO $ getNameInfo [NI_NUMERICHOST] True False addr >>= maybe (throwString ("getNameInfo failed to format SockAddr " <> show addr)) return . fst -- | Show a socket address as an ESMTP address literal. -- -- >>> showAddressLiteral (SockAddrInet defaultPort (tupleToHostAddress (1,2,3,4))) -- "[1.2.3.4]" -- >>> showAddressLiteral (SockAddrInet6 defaultPort 0 (tupleToHostAddress6 (1,2,3,4,5,6,7,8)) 0) -- "[IPv6:1:2:3:4:5:6:7:8]" -- >>> showAddressLiteral (SockAddrInet6 defaultPort 0 (tupleToHostAddress6 (1,2,0,0,0,6,7,8)) 0) -- "[IPv6:1:2::6:7:8]" -- >>> showAddressLiteral (SockAddrInet6 defaultPort 0 (tupleToHostAddress6 (1,2,0,0,5,0,0,8)) 0) -- "[IPv6:1:2::5:0:0:8]" showAddressLiteral :: MonadIO m => SockAddr -> m String showAddressLiteral addr = do x <- showAddress addr let v6prefix = case addr of SockAddrInet6 {} -> "IPv6:" _ -> "" return $ (:) '[' . showString v6prefix . showString x $ "]"
peti/postmaster
src/Postmaster/IO.hs
agpl-3.0
4,453
0
21
836
1,098
565
533
66
2
{-# LANGUAGE DeriveDataTypeable #-} import Control.Concurrent import Control.Exception import Control.Monad import Data.Binary import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.Char (digitToInt) import qualified Data.Vector as V import Data.Word (Word16) import System.Console.CmdArgs.Implicit import System.USB import Text.Printf {- ########################################################################################## -} _SET_REPORT :: Request _SET_REPORT = 0x09 {- ########################################################################################## -} data ApexCommand = CmdEnableExtraKeys -- 0..8 | CmdSetBrightness Word8 -- 0 -> 125 Hz -- 1 -> 250 Hz -- 2 -> 500 Hz -- 3 -> 1000 Hz | CmdSetPollFrequency Word8 | CmdSetColorProfile { colorSouth :: Color , colorEast :: Color , colorNorth :: Color , colorWest :: Color , colorLogo :: Color } deriving (Show) instance Binary ApexCommand where get = undefined put (CmdEnableExtraKeys) = do put32 [0x02, 0x00, 0x02] put (CmdSetBrightness a) = do put32 [0x05, 0x01, a] put c@(CmdSetColorProfile {}) = do put (0x07 :: Word8) put (0x00 :: Word8) put $ colorSouth c put $ colorEast c put $ colorNorth c put $ colorWest c put $ colorLogo c replicateM_ 10 $ put (0x00 :: Word8) put (CmdSetPollFrequency rate) = do put32 [0x04, 0x00, rate] put32 :: [Word8] -> Put put32 words = do forM_ words $ put replicateM_ (32 - length words) $ put (0 :: Word8) {- ########################################################################################## -} data Color = Color Word8 Word8 Word8 Word8 deriving (Data, Show, Typeable) instance Binary Color where get = undefined put (Color r g b a) = do put r put g put b put a instance Read Color where readsPrec _ = \str -> case str of [r0, r1, g0, g1, b0, b1, ':', a0] -> [(Color (toComp2 r0 r1) (toComp2 g0 g1) (toComp2 b0 b1) (toAlpha a0), [])] [r0, r1, g0, g1, b0, b1] -> [(Color (toComp2 r0 r1) (toComp2 g0 g1) (toComp2 b0 b1) 8, [])] [r0, g0, b0, ':', a0] -> [(Color (toComp1 r0) (toComp1 g0) (toComp1 b0) (toAlpha a0), [])] [r0, g0, b0] -> [(Color (toComp1 r0) (toComp1 g0) (toComp1 b0) 8, [])] toComp1 :: Char -> Word8 toComp1 a = fromIntegral $ (digitToInt a) * 0x10 + 0xF toComp2 :: Char -> Char -> Word8 toComp2 a b = fromIntegral $ (digitToInt a) * 0x10 + (digitToInt b) toAlpha :: Char -> Word8 toAlpha alpha = case digitToInt alpha of a | a >= 0 && a <= 8 -> fromIntegral a otherwise -> error "alpha must be between 0 and 8" toBrightness :: Int -> Word8 toBrightness brightness = case brightness of b | b >= 1 && b <= 8 -> fromIntegral b otherwise -> error "brightness must be between 1 and 8" toFrequency :: Int -> Word8 toFrequency 125 = 0 toFrequency 250 = 1 toFrequency 500 = 2 toFrequency 1000 = 3 toFrequency _ = error "frequency must be 125, 250, 500 or 1000" {- ########################################################################################## -} colorCyan = Color 0x00 0xFF 0xFF 0x08 colorGreen = Color 0x00 0xFF 0x00 0x08 colorPurple = Color 0xFF 0x00 0xFF 0x08 colorRed = Color 0xFF 0x00 0x00 0x08 colorWhite = Color 0xFF 0xFF 0xFF 0x08 cp0 = CmdSetColorProfile colorRed colorRed colorRed colorRed colorRed cp1 = CmdSetColorProfile colorCyan colorGreen colorPurple colorRed colorWhite cp2 c = CmdSetColorProfile c c c c c {- ########################################################################################## -} data ApexMode = ModeEnableExtraKeys | ModeSetBrightness { argBrightness :: Int } | ModeSetColorProfile { argSouth :: String , argEast :: String , argNorth :: String , argWest :: String , argLogo :: String } | ModeSetPollFrequency { argFrequency :: Int } deriving (Data, Show, Typeable) apexArgs :: ApexMode apexArgs = modes [ modeEnableExtraKeys , modeSetBrightness , modeSetColorProfile , modeSetPollFrequency ] &= program "apexctl" &= summary "An utility for managing Apex/Apex [RAW] keyboard settings" modeEnableExtraKeys :: ApexMode modeEnableExtraKeys = ModeEnableExtraKeys &= auto &= help "Enable macro keys" &= name "init" modeSetBrightness :: ApexMode modeSetBrightness = ModeSetBrightness { argBrightness = 8 &= argPos 0 &= typ "BRIGHTNESS" } &= help "Set brightness level (1..8)" &= name "br" colorAnnot :: String -> String -> String -> String {-# INLINE colorAnnot #-} colorAnnot name0 name1 desc = "FF0000:8" &= explicit &= name name0 &= name name1 &= help desc &= typ "COLOR" modeSetColorProfile :: ApexMode modeSetColorProfile = ModeSetColorProfile { argSouth = colorAnnot "s" "south" "Color for South zone" , argEast = colorAnnot "e" "east" "Color for East zone" , argNorth = colorAnnot "n" "north" "Color for North zone" , argWest = colorAnnot "w" "west" "Color for West zone" , argLogo = colorAnnot "l" "logo" "Color for Logo zone" } &= help (unlines [ "Change color profile." , "Colors should be specified for all color zones." , "Otherwise unspecified colors will default to red" ]) &= name "colors" modeSetPollFrequency :: ApexMode modeSetPollFrequency = ModeSetPollFrequency { argFrequency = 1000 &= argPos 0 &= typ "FREQUENCY" } &= help "Set polling frequency (125, 250, 500 or 1000)" &= name "freq" modeToCommand :: ApexMode -> ApexCommand modeToCommand m@ModeEnableExtraKeys {} = CmdEnableExtraKeys modeToCommand m@ModeSetBrightness {} = CmdSetBrightness (toBrightness $ argBrightness m) modeToCommand m@ModeSetColorProfile {} = CmdSetColorProfile { colorSouth = read $ argSouth m , colorEast = read $ argEast m , colorNorth = read $ argNorth m , colorWest = read $ argWest m , colorLogo = read $ argLogo m } modeToCommand m@ModeSetPollFrequency {} = CmdSetPollFrequency (toFrequency $ argFrequency m) {- ########################################################################################## -} controlSetup :: ControlSetup controlSetup = ControlSetup { controlSetupRequestType = Class , controlSetupRecipient = ToInterface , controlSetupRequest = _SET_REPORT , controlSetupValue = 0x0200 , controlSetupIndex = 0 } apexCtl :: DeviceHandle -> ByteString -> IO () apexCtl devHndl d = do putStrLn "WRITING SET_REPORT" writeControlExact devHndl controlSetup d noTimeout apexCommand :: Binary b => DeviceHandle -> b -> IO () apexCommand devHndl b = do apexCtl devHndl $ toStrict1 $ encode b threadDelay 10000 apexRet :: DeviceHandle -> IO () apexRet devHndl = do (r, s) <- readControl devHndl controlSetup 32 noTimeout putStrLn $ hex r putStrLn $ show s deviceFilter :: Word16 -> [Word16] -> Device -> IO Bool deviceFilter venId prodIds dev = do devDesc <- getDeviceDesc dev return $ deviceVendorId devDesc == venId && any ((==) $ deviceProductId devDesc) prodIds hex :: BS.ByteString -> String hex = concatMap (printf "%02x") . BS.unpack toStrict1 :: BL.ByteString -> BS.ByteString toStrict1 = BS.concat . BL.toChunks withDevice :: Word16 -> [Word16] -> (Device -> IO a) -> IO () withDevice venId prodIds hnd = do ctx <- newCtx setDebug ctx PrintInfo devs <- getDevices ctx devs1 <- V.filterM (deviceFilter venId prodIds) devs if V.null devs1 then return $ error "Device not found" else V.mapM_ hnd devs1 {- ########################################################################################## -} main :: IO () main = do args <- cmdArgs apexArgs withDevice 0x1038 [0x1200, 0x1202, 0x1208] $ \dev -> do withDeviceHandle dev $ \devHndl -> withDetachedKernelDriver devHndl 0 $ withClaimedInterface devHndl 0 $ do res <- try $ do apexCommand devHndl $ modeToCommand args case res of Left (SomeException a) -> putStrLn $ show a Right _ -> putStrLn "OK" {- ########################################################################################## -}
tuxmark5/ApexCtl
src/Main.hs
lgpl-3.0
8,275
0
21
1,807
2,381
1,235
1,146
-1
-1
module Bind where import Control.Monad (join) bind :: Monad m => (a -> m b) -> m a -> m b bind f mo = join $ fmap f mo
thewoolleyman/haskellbook
18/02/eric/Bind.hs
unlicense
122
0
9
33
69
35
34
4
1
{-# OPTIONS_GHC -Wall #-} module HW02 where import Data.List {-# ANN module ("HLint: ignore Redundant bracket"::String) #-} -- Mastermind ----------------------------------------- -- A peg can be one of six colors data Peg = Red | Green | Blue | Yellow | Orange | Purple deriving (Show, Eq, Ord) -- A code is defined to simply be a list of Pegs type Code = [Peg] -- A move is constructed using a Code and two integers; the number of -- exact matches and the number of regular matches data Move = Move Code Int Int deriving (Show, Eq) -- List containing all of the different Pegs colors :: [Peg] colors = [Red, Green, Blue, Yellow, Orange, Purple] -- Exercise 1 ----------------------------------------- -- Get the number of exact matches between the actual code and the guess exactMatches :: Code -> Code -> Int exactMatches x y = length $ filter (uncurry (==)) $ zip x y -- Exercise 2 ----------------------------------------- -- For each peg in xs, count how many times is occurs in ys countColors :: Code -> [Int] countColors code = map f colors where f x = length $ filter (\y -> x == y) code -- Count number of matches between the actual code and the guess matches :: Code -> Code -> Int matches x y = length $ intersect x y -- Exercise 3 ----------------------------------------- -- Construct a Move from a guess given the actual code -- first code is the secret, and the 2nd is the actual guess getMove :: Code -> Code -> Move getMove secret guess = (Move guess matchCount (matches secret guess - matchCount)) where matchCount = exactMatches secret guess -- Exercise 4 ----------------------------------------- {- if the guess inside the Move has the same number of exact and non-exact matches with the provided Code as it did with the actual secret, then the Code is consistent with the Move -} isConsistent :: Move -> Code -> Bool isConsistent move code = isMovesConsistent move (getConsistentMove move code) where isMovesConsistent (Move _ exact1 regular1) (Move _ exact2 regular2) = (exact1 == exact2) && (regular1 == regular2) getConsistentMove (Move guess _ _) ccode = getMove ccode guess -- Exercise 5 ----------------------------------------- filterCodes :: Move -> [Code] -> [Code] filterCodes move = filter (isConsistent move) -- Exercise 6 ----------------------------------------- {- Generate all codes for n number of colours -} generateAllCodes :: Code -> Int -> [Code] generateAllCodes prefix len | length(prefix) >= len = [prefix] | otherwise = concatMap f colors where f peg = generateAllCodes (peg : prefix) len allCodes :: Int -> [Code] allCodes len = concatMap f colors where f peg = generateAllCodes [peg] len -- Exercise 7 ----------------------------------------- -- getMove creates a move from a secret -> guess -- allCodes gives me allCodes -- filterCodes will filter inconsistent codes from a move -- keeps track of the remaining! consistent guesses solveHelper :: Code -> Code -> [Code] -> [Move] -> [Move] solveHelper secret guess combos result | secret == guess = move : result | otherwise = solveHelper secret newGuess newCombos (move : result) where move = getMove secret guess (newGuess:newCombos) = filterCodes move combos solve :: Code -> [Move] solve secret = solveHelper secret guess combos [] where guess = map (const Red) secret combos = allCodes (length secret) -- Bonus ---------------------------------------------- fiveGuess :: Code -> [Move] fiveGuess = undefined
markmandel/cis194
src/week2/homework/HW02.hs
apache-2.0
3,608
0
11
751
793
428
365
47
1
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} module Main where import Text.Hal import GHC.Generics import Data.Aeson import Data.Aeson.Encode.Pretty import qualified Data.ByteString.Lazy as B data Person = Person { firstName :: String , lastName :: String , age :: Int } deriving (Show, Generic) instance ToJSON Person instance Profile Person where profileOf p = Just "person" main = let p = Person "Mark" "Derricutt" 39 r = represent p "http://localhost/user/mark" `linkTo` (Link "blog" "http://www.theoryinpractice.net" $ Just "website") `linkTo` (Link "podcast" "http://www.illegalargument.com" $ Just "website") in B.putStr $ encodePretty r
talios/haskell-hal
Main.hs
apache-2.0
773
0
13
209
184
102
82
20
1
{-# LANGUAGE ImplicitParams, TemplateHaskell, TypeOperators, ConstraintKinds, NoMonomorphismRestriction #-} import PDESpec -- Example specification spec alpha h = ((d h T) === (alpha * d2 h X)) `withDomain` (X :. T :. Nil) -- Example FCTS implementation impl alpha h' (x, t) | x == 0 = 1 | x == ?nx = h' (x - 1, t) | t == 0 = 0 | otherwise = h' (x, t-1) + r * (h' (x+1, t-1) - 2 * h' (x, t-1) + h' (x-1, t-1)) where r = alpha * (?dt / (?dx * ?dx)) -- Make it fast please Mrs. Haskell: -- implFast :: Float -> (Int, Int) -> Float implFast alpha = arrayMemoFix ((0 :: Int, 0 :: Int), (?nx, ?nt)) (impl alpha) outputLatex = let implTex = let ?nx = mathit $ fromString "nx" ?dx = deltau <> (fromString "x") ?dt = deltau <> (fromString "t") in fixLatexCases "h" (impl alpha) [(0, fromString "t"), (?nx, fromString "t"), (fromString "x", 0), (fromString "x", fromString "t")] specTex = let ?name = "h" ?dx = undefined ?dt = undefined in toLatex (spec (varconst "alpha") (undefined::(Int, Int) -> Float)) in doLatex (noindent <> fromString "Abstract specification : " <> equation specTex <> fromString "Discrete approximation : " <> implTex) "heat" experiment action = let ?dx = 0.05 ?dt = 0.05 :: Float ?nx = 100 :: Int ?nt = 100 :: Int ?name = "h" in let alpha = 0.006 spec' = spec (constant alpha) results = verifyModel Euler spec' (implFast alpha) figureEqn axis xs = plot3d' 1 1 (0, ?nx - 2) (0, ?nt - 1) (show X) (show T) axis xs heatImpl = makePlot "h" (implFast alpha) heatLHS = makePlotAdjust 2 1 (toString $ lhs $ spec' (implFast alpha)) (fst . results) heatRHS = makePlotAdjust 2 1 (toString $ rhs $ spec' (implFast alpha)) (snd . results) heatErr = makePlotAdjust 2 1 "|err|" (abs . uncurry (-) . results) in case action of ShowFigures -> showFigures [heatImpl, heatLHS, heatRHS, heatErr] PNGFigures -> writePNGs [(heatImpl, "heatImpl"), (heatLHS, "heatLHS"), (heatRHS, "heatRHS"), (heatErr, "heatErr")] Latex -> outputLatexSep -- Docs spec' impl CSV -> let outputRow (x, t) = [show x, show t, show . fst $ results (x, t), show . snd $ results (x, t)] csv = map outputRow [(0,0)..(?nx-2, ?nt-1)] in writeFile "data" (printCSV csv) experimentCSV fname = let ?dx = 0.05 in let ?dt = 0.05 :: Float in let ?nx = 20 :: Int in let ?nt = 50 :: Int in let alpha = 0.006 f = check (spec (constant alpha) (implFast alpha)) outputRow (x, t) = [show x, show t, show . fst $ f (x, t), show . snd $ f (x, t)] csv = map outputRow [(0,0)..(?nx-2, ?nt-1)] in writeFile fname (printCSV csv) main = do args <- getArgs if (length args < 5) then putStrLn "usage:\n\t ./testcase [dx] [dt] [nx] [nt] [alpha]" else let ?dx = read $ args !! 0 :: Float ?dt = read $ args !! 1 :: Float ?nx = read $ args !! 2 :: Int ?nt = read $ args !! 3 :: Int ?name = "h" in let alpha = read $ args !! 4 :: Float spec' = spec (constant alpha) (implFast alpha) f = check spec' figureEqn axis xs = plot3d' 1 1 (0, ?nx - 2) (0, ?nt - 1) (show X) (show T) axis xs heatImpl = plot3d' 1 1 (0, ?nx) (0, ?nt) (show X) (show T) (?name) (curry (implFast alpha)) heatLHS = figureEqn (toString $ lhs spec') (curry $ fst . f) heatRHS = figureEqn (toString $ rhs spec') (curry $ snd . f) heatErr = figureEqn "|err|" (\x t -> (abs . uncurry (-)) . f $ (x, t)) outputRow (x, t) = [show x, show t, show . fst $ f (x, t), show . snd $ f (x, t)] csv = map outputRow [(0,0)..(?nx-2, ?nt-1)] in do putStrLn "data.csv" writeFile "data.csv" (printCSV csv) putStrLn "heatImpl.png" writePlotPNG heatImpl "heatImpl" putStrLn "heatLHS.png" writePlotPNG heatLHS "heatLHS" putStrLn "heatRHS.png" writePlotPNG heatRHS "heatRHS" putStrLn "heatErr.png" writePlotPNG heatErr "heatErr" outputLatexSep outputLatexSep = let implTex = let ?nx = mathit $ fromString "nx" ?dx = deltau <> (fromString "x") ?dt = deltau <> (fromString "t") in fixLatexCases "h" (impl alpha) [(0, fromString "t"), (?nx, fromString "t"), (fromString "x", 0), (fromString "x", fromString "t")] specTex = let ?name = "h" ?dx = undefined ?dt = undefined in toLatex (spec (varconst "alpha") (undefined::(Int, Int) -> Float)) in do putStrLn "model.tex" writeFile "model.tex" (unpack . render $ specTex) putStrLn "impl.tex" writeFile "impl.tex" (unpack . render $ implTex) putStrLn "heat.tex" doLatex (noindent <> fromString "Abstract specification : " <> equation specTex <> fromString "Discrete approximation : " <> implTex) "heat"
dorchard/pde-specs
TestCaseCmd.hs
bsd-2-clause
6,792
0
21
3,242
2,051
1,068
983
109
4
module Queens where import CLaSH.Prelude import Data.Maybe mem <~ (i,x) = replace mem i x type Word3 = Unsigned 3 type MbWord3 = Maybe Word3 type Din = Vec 8 (MbWord3) type Dout = Vec 8 Word3 din :: Din din = $(v [ Nothing :: Maybe (Unsigned 3), Just 1, Nothing, Nothing, Just 4, Nothing, Just 6, Just 7 ]) dout0 :: Dout dout0 = 0 :> 0 :> 0 :> 0 :> 0 :> 0 :> 0 :> 0 :> Nil :: Dout ind0 :: Word3 ind0 = 0 mbfilter (dout,ind) din = ((dout',ind'), low) where f (dout,ind) v = case v of Just x -> (dout<~(ind,x), ind+1) Nothing -> (dout, ind) (dout',ind') = foldl f (dout0,ind0) din topEntity :: Signal Din -> Signal Bit topEntity = mbfilter `mealy` (dout0, ind0)
christiaanb/clash-compiler
examples/Queens.hs
bsd-2-clause
814
0
12
287
349
194
155
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {- - Copyright (c) 2015, Peter Lebbing <peter@digitalbrains.com> - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. -} module Simul.Toolbox.Blockram2p_2_16 where import CLaSH.Prelude import Control.Applicative import Debug.Trace import Toolbox.Misc -- Simulation model for `blockram2p d12 d9 d2 d16` blockram2p :: SNat 12 -> SNat 9 -> SNat 2 -> SNat 16 -> SignalP ( Unsigned 12, Unsigned 2, Bool, Unsigned 9 , Unsigned 16, Bool) -> SignalP (Unsigned 2, Unsigned 16) -- Nearly identical to Toolbox.blockram2p; the only difference is that -- blockram2p' no longer takes the first two arguments `an` and `bn`. blockram2p aaw baw aw bw (aAddr, aDIn, aWrEn, bAddr, bDIn, bWrEn) = (qA, qB) where (qAB, qBB) = blockram2p' aaw baw aw bw (aAddrB) (aDInB) aWrEnB (bAddrB) (bDInB) bWrEnB qA = fromBV <$> qAB qB = fromBV <$> qBB aAddrB = toBV <$> aAddr aDInB = toBV <$> aDIn aWrEnB = (\b -> if b then H else L) <$> aWrEn bAddrB = toBV <$> bAddr bDInB = toBV <$> bDIn bWrEnB = (\b -> if b then H else L) <$> bWrEn {- - This should be the simulation model for the general case, but I could not - get the type proven correct. - - It is also quite slow in simulation. - - Registers are in this function, and the bitvectors are converted back to - Unsigneds and Bools. `blockram2p''` does the actual memory - access. -} blockram2p' aaw baw aw bw aAddrB aDInB aWrEnB bAddrB bDInB bWrEnB = oD where aAddr = fromBV <$> aAddrB aWrEn = (== H) <$> aWrEnB bAddr = fromBV <$> bAddrB bWrEn = (== H) <$> bWrEnB iD = ( unpack . register (0, vcopyI L, False, 0, vcopyI L, False) . pack) (aAddr, aDInB, aWrEn, bAddr, bDInB, bWrEn) oD = ( unpack . register (vcopyI L, vcopyI L) . pack) o o = (blockram2p'' aaw baw aw bw <^> vcopyI L) iD {- - Memory is held as a vector of individual bits. These are then aggregrated - into the word size used by the two ports. - - In the FPGA, a write conflict gives undefined behaviour. This simulation - model is defined in such a way that port B data would overwrite port A data - for the part where there is an overlap; but instead of doing that, an error - is thrown. - - Usually, a write conflict is a design error. Even if it is carefully - constructed not to be, the simulation yields a different result (i.e., - deterministic) than the FPGA (i.e., undefined), so throwing an error in the - simulation is definitely the safest thing to do. -} blockram2p'' :: SNat 12 -> SNat 9 -> SNat 2 -> SNat 16 -> Vec 8192 Bit -> (Unsigned 12, Vec 2 Bit, Bool, Unsigned 9, Vec 16 Bit, Bool) -> (Vec 8192 Bit, (Vec 2 Bit, Vec 16 Bit)) blockram2p'' aaw baw aw bw s (aAddr, aDIn, aWrEn, bAddr, bDIn, bWrEn) = (s', (qA, qB)) where sa' | aWrEn = vconcat $ vreplace (vunconcatI s) aAddr aDIn | otherwise = s s' | not bWrEn = sa' | aWrEn && overlap = error ($(showCodeLoc) ++ " blockram2p'': Write conflict") | otherwise = vconcat $ vreplace (vunconcatI sa') bAddr bDIn qA = (vunconcatI s)!aAddr qB = (vunconcatI s)!bAddr astart = (fromIntegral aAddr) * awv aend = astart + awv bstart = (fromIntegral bAddr) * bwv bend = bstart + bwv overlap = (bstart >= astart && bstart < aend) || (astart >= bstart && astart < bend) awv = fromInteger $ natVal aw bwv = fromInteger $ natVal bw
DigitalBrains1/clash-lt24
Simul/Toolbox/Blockram2p_2_16.hs
bsd-2-clause
5,174
0
13
1,417
913
492
421
64
3
{-# LANGUAGE TupleSections #-} module Problem1 where import Data.Char import Data.List import Data.Array import Data.Maybe import Data.Ord import Control.Applicative import System.IO -- Primitive calculator main :: IO () main = hSetBuffering stdin NoBuffering >>= \_ -> nextNum >>= \n -> let (count, solution) = solve n printSize = putStrLn $ show count printList = putStrLn $ intercalate " " $ show <$> solution in printSize >> printList solve :: Int -> (Int, [Int]) solve n = (count lastCell, reconstruct solution n) where lastCell = solution ! n solution = array (1, n) $ (1, Cell 0 1 0) : [ (i, best) | i <- [2..n], let prevCells = catMaybes $ prevCellsF i solution <$> ops (bestCell, bestIndex, op) = head $ sortBy (comparing (count . fst3)) prevCells best = Cell bestIndex (function op $ value bestCell) (count bestCell + 1) ] reconstruct arr n = loop n [] where loop i acc = let Cell prev value _ = arr ! i in if (prev==0) then value : acc else loop prev (value : acc) fst3 (e, _, _) = e prevCellsF i arr op = (\i -> (arr ! i, i, op)) <$> index where index = inverse op i prevCellsF2 i arr op = (, op) <$> prev where inv = inverse op i prev = (arr !) <$> inv data Op = Op {function :: Int -> Int, inverse :: Int -> Maybe Int} data Cell = Cell {prev :: Int, value :: Int, count :: Int} deriving Show ops = [ Op (+1) (Just . (subtract 1)), Op (*3) (invMul 3), Op (*2) (invMul 2) ] invMul times = f where f num = let (d, r) = num `divMod` times in if(r == 0) then Just d else Nothing nextNums :: (Integral a, Read a) => Int -> IO [a] nextNums n = sequence $ replicate n nextNum nextNum :: (Integral a, Read a) => IO a nextNum = nextNum' "" nextNum' n = getChar >>= \char -> if(isDigit char) then nextNum' $ char:n else if(null n) then nextNum' n else pure $ read $ reverse n
msosnicki/algorithms
app/week5/Problem1.hs
bsd-3-clause
1,951
0
18
525
866
466
400
53
3
module Hive.Board ( Board , BoardIndex , initialBoard , boardParity , boardTiles , boardWidth , boardHeight , Parity(..) , Adjacency(..) , (!) , boardWinner , growBoard , occupiedNeighbors , occupiedNeighborIndices , cellsAreAdjacent , cellIsOccupied , cellIsUnoccupied ) where import Mitchell.Prelude import Data.HexBoard import Hive.Bug import Hive.Player import Hive.Tile import Data.List.NonEmpty (NonEmpty(..)) import Data.Vector (Vector) import qualified Data.Set as Set import qualified Data.Vector as Vector type Board = HexBoard Cell initialBoard :: Board initialBoard = HexBoard (pure (pure [])) Even (!) :: Board -> BoardIndex -> Cell board ! i = case preview (ix i) board of Nothing -> error ("Hive.Board.(!): index " ++ show i ++ " out of bounds") Just c -> c -- | Get the winner of this board, if any. Takes an index representing the last -- index that a piece was either moved to or placed at as an optimization, since -- a queen can only possibly be smothered at one of this cell's neighbors. boardWinner :: BoardIndex -> Board -> Maybe Winner boardWinner i0 board = go (catMaybes (map queenSmothered (boardNeighbors i0 board))) where queenSmothered :: (BoardIndex, Cell) -> Maybe Player queenSmothered (i1, cell) | Just (Tile player Queen) <- preview _last cell , length (occupiedNeighbors board i1) == 6 = Just player | otherwise = Nothing go :: [Player] -> Maybe Winner go queens = case (elem P1 queens, elem P2 queens) of (True, True) -> Just Nothing (True, _) -> Just (Just P2) ( _, True) -> Just (Just P1) _ -> Nothing -- Given an index that presumably just had a piece placed on it (or moved -- to), possibly grow the board if that index is on an edge of the board. growBoard :: BoardIndex -> Board -> Board growBoard (row, col) board = let w = boardWidth board h = boardHeight board f0, f1, f2, f3 :: Board -> Board f0 = if row == 0 then prependRow else identity f1 = if row == h-1 then appendRow else identity f2 = if col == 0 then prependCol else identity f3 = if col == w-1 then appendCol else identity in f0 (f1 (f2 (f3 board))) prependRow :: Board -> Board prependRow board = over boardTilesL f board where f :: Vector (Vector [Tile]) -> Vector (Vector [Tile]) f = Vector.cons (Vector.replicate (boardWidth board) []) appendRow :: Board -> Board appendRow board = over boardTilesL f board where f :: Vector (Vector [Tile]) -> Vector (Vector [Tile]) f = flip Vector.snoc (Vector.replicate (boardWidth board) []) prependCol :: Board -> Board prependCol = over (boardTilesL . traverse) (Vector.cons []) . over boardParityL flipParity appendCol :: Board -> Board appendCol = over (boardTilesL . traverse) (flip Vector.snoc []) -- | Get a list of neighbor cells that have at least one tile in them. occupiedNeighbors :: Board -> BoardIndex -> [(BoardIndex, NonEmpty Tile)] occupiedNeighbors board i = catMaybes (map (\(j,c) -> case c of [] -> Nothing (t:ts) -> Just (j, (t :| ts))) (boardNeighbors i board)) occupiedNeighborIndices :: BoardIndex -> Board -> Set BoardIndex occupiedNeighborIndices i board = Set.fromList (map fst (occupiedNeighbors board i)) -- | Two cells are adjacent if one of them is a neighbor of the other. cellsAreAdjacent :: Board -> BoardIndex -> BoardIndex -> Bool cellsAreAdjacent board src dst = dst `elem` map fst (boardNeighbors src board) -- | Is this cell occupied by at least one tile? cellIsOccupied :: Board -> BoardIndex -> Bool cellIsOccupied board i = isJust (preview (ix i . _head) board) -- | Is this cell unoccupied (but still in bounds)? cellIsUnoccupied :: Board -> BoardIndex -> Bool cellIsUnoccupied board i = preview (ix i) board == Just []
mitchellwrosen/hive
hive/src/Hive/Board.hs
bsd-3-clause
3,883
0
16
880
1,216
652
564
94
5
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE DeriveDataTypeable #-} module Frameworks.CoreFoundation.Types ( CFTypeID , CFOptionFlags , CFHashCode , CFIndex , CFTypeRef , CFStringRef, ObjcCFString ) where import Data.Data import Objective.C.Prim import Foreign.Ptr import Foreign.C.Types type CFTypeID = CULong type CFOptionFlags = CULong type CFHashCode = CULong type CFIndex = CLong type CFTypeRef = CId -- toll-free-bridged data ObjcCFString deriving Typeable type CFStringRef = Ptr ObjcCFString
ekmett/objective-c
Frameworks/CoreFoundation/Types.hs
bsd-3-clause
579
0
5
106
101
67
34
-1
-1
{-# LANGUAGE PackageImports #-} import "hashprice" Application (getApplicationDev) import Network.Wai.Handler.Warp (runSettings, defaultSettings, setPort) import Control.Concurrent (forkIO) import System.Directory (doesFileExist, removeFile) import System.Exit (exitSuccess) import Control.Concurrent (threadDelay) main :: IO () main = do putStrLn "Starting devel application" (port, app) <- getApplicationDev forkIO $ runSettings (setPort port defaultSettings) app loop loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "yesod-devel/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess
pirapira/hashprice
devel.hs
bsd-3-clause
680
0
10
104
186
100
86
21
2
{-# LANGUAGE LambdaCase, OverloadedStrings #-} module Mote.Protocol where import Control.Applicative import Control.Monad import Data.Aeson hiding (Error) import qualified Data.Text as T import qualified Data.Vector as V type Pos = (Int, Int) type Span = (Pos, Pos) data ToClient = Replace Span FilePath String | HoleInfoJSON Value | Insert Pos FilePath String | SetInfoWindow String | SetCursor Pos | Ok | Error String | Stop deriving (Show) instance ToJSON ToClient where toJSON = \case Replace sp p t -> tag "Replace" [toJSON sp, toJSON p, toJSON t] SetInfoWindow t -> tag "SetInfoWindow" [toJSON t] SetCursor pos -> tag "SetCursor" [toJSON pos] Ok -> tag "Ok" [] Error t -> tag "Error" [toJSON t] Stop -> tag "Stop" [] Insert pos p t -> tag "Insert" [toJSON pos, toJSON p, toJSON t] HoleInfoJSON v -> tag "HoleInfoJSON" [toJSON v] where tag :: String -> [Value] -> Value tag name values = Array . V.fromList $ toJSON name : values type Var = String data ClientState = ClientState { path :: FilePath, cursorPos :: (Int, Int) } deriving (Show) instance FromJSON ClientState where parseJSON (Object v) = ClientState <$> v .: "path" <*> v .: "cursorPos" parseJSON _ = mzero data HoleInfoOptions = HoleInfoOptions -- If this flag is true, the response to the GetHoleInfo message is -- a json object with the following format -- { "environment" : [ {"name" : String, "type" : String}* ] -- , "suggestions" : [ {"name" : String, "type" : String}* ] -- , "goal" : {"name" : String, "type" : String} -- } { sendOutputAsData :: Bool -- The suggestions field is only present if withSuggestions is true , withSuggestions :: Bool } deriving (Show) instance FromJSON HoleInfoOptions where parseJSON = \case Object v -> HoleInfoOptions <$> v .: "sendOutputAsData" <*> v .: "withSuggestions" _ -> mzero data FromClient = Load FilePath | EnterHole ClientState | NextHole ClientState | PrevHole ClientState | GetHoleInfo ClientState HoleInfoOptions | Refine String ClientState | GetType String | CaseFurther Var ClientState | CaseOn String ClientState | SendStop | Search deriving (Show) instance FromJSON FromClient where parseJSON = \case Array a -> case V.toList a of [String "Load", String path] -> return (Load (T.unpack path)) [String "CaseFurther", String var, state] -> CaseFurther (T.unpack var) <$> parseJSON state [String "CaseOn", String expr, state] -> CaseOn (T.unpack expr) <$> parseJSON state [String "EnterHole", state] -> EnterHole <$> parseJSON state [String "NextHole", state] -> NextHole <$> parseJSON state [String "PrevHole", state] -> PrevHole <$> parseJSON state [String "GetHoleInfo", state, hiOpts] -> GetHoleInfo <$> parseJSON state <*> parseJSON hiOpts [String "Refine", String expr, state] -> Refine (T.unpack expr) <$> parseJSON state [String "GetType", String e] -> return . GetType $ T.unpack e [String "SendStop"] -> return SendStop _ -> mzero _ -> mzero
imeckler/mote
Mote/Protocol.hs
bsd-3-clause
3,431
0
17
1,014
939
494
445
73
0
module StringCompressorKata.Day4Spec (spec) where import Test.Hspec import StringCompressorKata.Day4 (compress) spec = do it "compresses nothing into the nothing" $ do compress Nothing `shouldBe` Nothing it "compresses an empty string into another empty string" $ do compress (Just "") `shouldBe` Just "" it "compress an one character string" $ do compress (Just "a") `shouldBe` Just "1a" it "compress a string of unique characters" $ do compress (Just "abc") `shouldBe` Just "1a1b1c" it "compress a string of doubled characters" $ do compress (Just "aabbcc") `shouldBe` Just "2a2b2c"
Alex-Diez/haskell-tdd-kata
old-katas/test/StringCompressorKata/Day4Spec.hs
bsd-3-clause
703
0
13
203
177
85
92
14
1
{-# LANGUAGE OverloadedStrings #-} import qualified Haquery as Haq import qualified Hakit as H import qualified TooEasy as Too import qualified Data.Text as T import qualified System.Directory as D siteF = "_site" main = do posts <- Too.loadPosts "posts" templ <- Too.loadTemplate "template.html" sitesEx <- D.doesDirectoryExist siteF if sitesEx then return () else D.createDirectory siteF mapM_ (processPost templ) posts where processPost :: Haq.Tag -> (H.Document, Haq.Tag) -> IO () processPost templ post = do let fn = T.unpack . H.getString "fileName" $ fst post fileName = siteF ++ "/" ++ fn body = snd post postTitle = T.unpack . H.getString "title" $ fst post result = Haq.alter ".content" (\_ -> body) $ Haq.alter "title" (\_ -> Haq.text . T.pack $ "example site - " ++ postTitle) templ putStr $ "Writing file " ++ fileName ++ "\n" writeFile fileName . T.unpack $ Haq.render result
crufter/tooeasy
examples/simple/site.hs
bsd-3-clause
1,050
0
19
303
323
167
156
26
2
{-# LANGUAGE DeriveGeneric #-} module Interfaces.Hoogle ( queryHoogle , formatHoogle ) where import Data.Aeson (eitherDecode, FromJSON(..)) import Control.Applicative ((<$>)) import GHC.Generics import Network.Curl import Network.HTTP (urlEncode) import Interfaces.HTML (fetchLazy) -- |URL to Hoogle's API query hoogleJSON :: String hoogleJSON = "http://www.haskell.org/hoogle/?mode=json&start=1&count=3&hoogle=" -- |One set of data we received by parsing the whole JSON reply from -- Hoogle. data HoogleSet = HoogleSet { location :: String -- ^ The URL to the API page , self :: String -- ^ Type definition, etc. , docs :: String -- ^ Short documentation } deriving (Show, Generic) data HoogleReply = HoogleReply { version :: String -- ^ Current version of Hoogle. , results :: [HoogleSet] -- ^ A set of results for a query } deriving (Show, Generic) instance FromJSON HoogleReply instance FromJSON HoogleSet -- |Given a query, compose the request composeQuery :: String -> String composeQuery = (++) hoogleJSON . urlEncode formatSet :: HoogleSet -> String formatSet = self formatHoogle :: HoogleReply -> [String] formatHoogle (HoogleReply _ []) = ["No results found."] formatHoogle (HoogleReply _ l ) = map formatSet l -- |Fetch and decode the JSON file. Results in 'Either String HoogleReply', -- signaling parse status. queryHoogle :: String -> IO (Either String HoogleReply) queryHoogle s = eitherDecode <$> respBody <$> fetchLazy (composeQuery s)
vehk/Indoril
src/Interfaces/Hoogle.hs
bsd-3-clause
1,628
0
9
388
318
185
133
30
1
{-# LANGUAGE DataKinds, GADTs, KindSignatures, TypeOperators #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE AllowAmbiguousTypes #-} module Data.Fin ( Finite (..) ) where import Data.Nat import Data.SNat (Natural) import Data.Type.Equality ((:~:) (Refl)) import Prelude hiding (succ) class Finite fin where zero :: fin (S n) succ :: fin n -> fin (S n) elimFin :: (forall m. p (S m)) -> (forall m. n ~ S m => fin m -> p n) -> fin n -> p n foldFin :: (forall m. p m -> p (S m)) -> (forall m. p (S m)) -> fin n -> p n foldFin f z = elimFin z (\n -> f (foldFin f z n)) weaken :: fin n -> fin (S n) weaken = unSucc . foldFin succer (Succ zero) where succer :: Succ fin n -> Succ fin (S n) succer (Succ n) = Succ (succ n) weakenN :: forall n. forall k. fin k -> fin (k + n) weakenN = unPlus . foldFin plusser (Plus zero) where plusser :: Plus fin n i -> Plus fin n (S i) plusser (Plus i) = Plus (succ i) plus :: fin (S m) -> fin (S n) -> fin (S (m + n)) --times :: pnat (S m) -> pnat (S n) -> pnat (S (m * n)) toIntegral :: forall i. forall n. Integral i => fin n -> i toIntegral = unConst . foldFin plus1 (Const 0) where plus1 :: Const i m -> Const i (S m) plus1 (Const x) = Const (x + 1) newtype Const a (b :: PNat) = Const { unConst :: a } newtype Succ fin n = Succ { unSucc :: fin (S n) } newtype Plus fin n k = Plus { unPlus :: fin (k + n) }
bmsherman/haskell-vect
Data/Fin.hs
bsd-3-clause
1,482
0
14
410
690
364
326
36
0
-- Copyright 2021 Google LLC -- -- Use of this source code is governed by a BSD-style -- license that can be found in the LICENSE file or at -- https://developers.google.com/open-source/licenses/bsd {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wno-orphans #-} module Imp ( toImpFunction, ImpFunctionWithRecon (..) , toImpStandaloneFunction, toImpExportedFunction , PtrBinder, impFunType, getIType) where import Data.Functor import Data.Foldable (toList) import Data.Text.Prettyprint.Doc (Pretty (..), hardline) import Control.Category ((>>>)) import Control.Monad.Identity import Control.Monad.Reader import Control.Monad.State.Class import Control.Monad.Writer.Strict import GHC.Stack import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as M import Err import MTL1 import Name import Builder import Syntax import Type import Simplify import LabeledItems import qualified Algebra as A import Util (enumerate) type AtomRecon = Abs (Nest (NameBinder AtomNameC)) Atom type PtrBinder = IBinder -- TODO: make it purely a function of the type and avoid the AtomRecon toImpFunction :: EnvReader m => Backend -> CallingConvention -> Abs (Nest PtrBinder) Block n -> m n (ImpFunctionWithRecon n) toImpFunction _ cc absBlock = liftImpM $ translateTopLevel cc Nothing absBlock toImpStandaloneFunction :: EnvReader m => NaryLamExpr n -> m n (ImpFunction n) toImpStandaloneFunction lam = liftImpM $ toImpStandaloneFunction' lam toImpStandaloneFunction' :: Imper m => NaryLamExpr o -> m i o (ImpFunction o) toImpStandaloneFunction' lam@(NaryLamExpr bs Pure body) = do ty <- naryLamExprType lam AbsPtrs (Abs ptrBinders argResultDest) ptrsInfo <- makeNaryLamDest ty let ptrHintTys = [("ptr"::NameHint, PtrType baseTy) | DestPtrInfo baseTy _ <- ptrsInfo] dropSubst $ buildImpFunction CInternalFun ptrHintTys \vs -> do argResultDest' <- applySubst (ptrBinders@@>vs) argResultDest (args, resultDest) <- loadArgDests argResultDest' extendSubst (bs @@> map SubstVal args) do void $ translateBlock (Just $ sink resultDest) body return [] toImpStandaloneFunction' (NaryLamExpr _ _ _) = error "effectful functions not implemented" toImpExportedFunction :: EnvReader m => NaryLamExpr n -> (Abs (Nest IBinder) (ListE Block) n) -> m n (ImpFunction n) toImpExportedFunction lam@(NaryLamExpr (NonEmptyNest fb tb) effs body) (Abs baseArgBs argRecons) = liftImpM do case effs of Pure -> return () _ -> throw TypeErr "Can only export pure functions" let bs = Nest fb tb NaryPiType tbs _ resTy <- naryLamExprType lam (resDestAbsArgsPtrs, ptrFormals) <- refreshAbs (Abs tbs resTy) \tbs' resTy' -> do -- WARNING! This ties the makeDest implementation to the C API expected in export. -- In particular, every array has to be backend by a single pointer and pairs -- should be traversed left-to-right. AbsPtrs (Abs ptrBs' resDest') ptrInfo <- makeDest (LLVM, CPU, Unmanaged) resTy' let ptrFormals = ptrInfo <&> \(DestPtrInfo bt _) -> ("res"::NameHint, PtrType bt) return (Abs tbs' (Abs ptrBs' resDest'), ptrFormals) let argFormals = nestToList ((NoHint,) . iBinderType) baseArgBs dropSubst $ buildImpFunction CEntryFun (argFormals ++ ptrFormals) \argsAndPtrs -> do let (args, ptrs) = splitAt (length argFormals) argsAndPtrs resDestAbsPtrs <- applyNaryAbs (sink resDestAbsArgsPtrs) args resDest <- applyNaryAbs resDestAbsPtrs ptrs argAtoms <- extendSubst (baseArgBs @@> map SubstVal (Var <$> args)) $ traverse (translateBlock Nothing) $ fromListE argRecons extendSubst (bs @@> map SubstVal argAtoms) do void $ translateBlock (Just $ sink resDest) body return [] loadArgDests :: (Emits n, ImpBuilder m) => NaryLamDest n -> m n ([Atom n], Dest n) loadArgDests (Abs Empty resultDest) = return ([], resultDest) loadArgDests (Abs (Nest (b:>argDest) bs) resultDest) = do arg <- destToAtom argDest restDest <- applySubst (b@>SubstVal arg) (Abs bs resultDest) (args, resultDest') <- loadArgDests restDest return (arg:args, resultDest') storeArgDests :: (Emits n, ImpBuilder m) => NaryLamDest n -> [Atom n] -> m n (Dest n) storeArgDests (Abs Empty resultDest) [] = return resultDest storeArgDests (Abs (Nest (b:>argDest) bs) resultDest) (x:xs) = do copyAtom argDest x restDest <- applySubst (b@>SubstVal x) (Abs bs resultDest) storeArgDests restDest xs storeArgDests _ _ = error "dest/args mismatch" data ImpFunctionWithRecon n = ImpFunctionWithRecon (ImpFunction n) (AtomRecon n) instance GenericE ImpFunctionWithRecon where type RepE ImpFunctionWithRecon = PairE ImpFunction AtomRecon fromE (ImpFunctionWithRecon fun recon) = PairE fun recon toE (PairE fun recon) = ImpFunctionWithRecon fun recon instance SinkableE ImpFunctionWithRecon instance SubstE Name ImpFunctionWithRecon instance CheckableE ImpFunctionWithRecon where checkE (ImpFunctionWithRecon f recon) = -- TODO: CheckableE instance for the recon too ImpFunctionWithRecon <$> checkE f <*> substM recon instance Pretty (ImpFunctionWithRecon n) where pretty (ImpFunctionWithRecon f recon) = pretty f <> hardline <> "Reconstruction:" <> hardline <> pretty recon -- === ImpM monad === type ImpBuilderEmissions = Nest ImpDecl newtype ImpM (n::S) (a:: *) = ImpM { runImpM' :: ScopedT1 IxCache (WriterT1 (ListE IExpr) (InplaceT Env ImpBuilderEmissions HardFailM)) n a } deriving ( Functor, Applicative, Monad, ScopeReader, Fallible, MonadFail, MonadState (IxCache n)) type SubstImpM = SubstReaderT AtomSubstVal ImpM :: S -> S -> * -> * instance ExtOutMap Env ImpBuilderEmissions where extendOutMap bindings emissions = bindings `extendOutMap` toEnvFrag emissions class ( ImpBuilder2 m, SubstReader AtomSubstVal m , EnvReader2 m, EnvExtender2 m) => Imper (m::MonadKind2) where instance EnvReader ImpM where unsafeGetEnv = ImpM $ lift11 $ lift11 $ getOutMapInplaceT instance EnvExtender ImpM where refreshAbs ab cont = ImpM $ ScopedT1 \s -> lift11 $ liftM (,s) $ refreshAbs ab \b e -> do (result, ptrs) <- runWriterT1 $ flip runScopedT1 (sink s) $ runImpM' $ cont b e case ptrs of ListE [] -> return result _ -> error "shouldn't be able to emit pointers without `Mut`" instance ImpBuilder ImpM where emitMultiReturnInstr instr = do tys <- impInstrTypes instr ListE vs <- ImpM $ ScopedT1 \s -> lift11 do Abs bs vs <- return $ newNames $ map (const "v") tys let impBs = makeImpBinders bs tys let decl = ImpLet impBs instr liftM (,s) $ extendInplaceT $ Abs (Nest decl Empty) vs return $ zipWith IVar vs tys where makeImpBinders :: Nest (NameBinder AtomNameC) n l -> [IType] -> Nest IBinder n l makeImpBinders Empty [] = Empty makeImpBinders (Nest b bs) (ty:tys) = Nest (IBinder b ty) $ makeImpBinders bs tys makeImpBinders _ _ = error "zip error" buildScopedImp cont = ImpM $ ScopedT1 \s -> WriterT1 $ WriterT $ liftM (, ListE []) $ liftM (,s) $ locallyMutableInplaceT do Emits <- fabricateEmitsEvidenceM (result, (ListE ptrs)) <- runWriterT1 $ flip runScopedT1 (sink s) $ runImpM' do Distinct <- getDistinct cont _ <- runWriterT1 $ flip runScopedT1 (sink s) $ runImpM' do forM ptrs \ptr -> emitStatement $ Free ptr return result extendAllocsToFree ptr = ImpM $ lift11 $ tell $ ListE [ptr] instance ImpBuilder m => ImpBuilder (SubstReaderT AtomSubstVal m i) where emitMultiReturnInstr instr = SubstReaderT $ lift $ emitMultiReturnInstr instr buildScopedImp cont = SubstReaderT $ ReaderT \env -> buildScopedImp $ runSubstReaderT (sink env) $ cont extendAllocsToFree ptr = SubstReaderT $ lift $ extendAllocsToFree ptr instance ImpBuilder m => Imper (SubstReaderT AtomSubstVal m) liftImpM :: EnvReader m => SubstImpM n n a -> m n a liftImpM cont = do env <- unsafeGetEnv Distinct <- getDistinct case runHardFail $ runInplaceT env $ runWriterT1 $ flip runScopedT1 mempty $ runImpM' $ runSubstReaderT idSubst $ cont of (Empty, (result, ListE [])) -> return result _ -> error "shouldn't be possible because of `Emits` constraint" -- === the actual pass === -- We don't emit any results when a destination is provided, since they are already -- going to be available through the dest. translateTopLevel :: Imper m => CallingConvention -> MaybeDest o -> Abs (Nest PtrBinder) Block i -> m i o (ImpFunctionWithRecon o) translateTopLevel cc maybeDest (Abs bs body) = do let argTys = nestToList (\b -> (getNameHint b, iBinderType b)) bs ab <- buildImpNaryAbs argTys \vs -> extendSubst (bs @@> map Rename vs) do outDest <- case maybeDest of Nothing -> makeAllocDest Unmanaged =<< getType =<< substM body Just dest -> sinkM dest void $ translateBlock (Just outDest) body destToAtom outDest refreshAbs ab \bs' ab' -> refreshAbs ab' \decls resultAtom -> do (results, recon) <- buildRecon (PairB bs' decls) resultAtom let funImpl = Abs bs' $ ImpBlock decls results let funTy = IFunType cc (nestToList iBinderType bs') (map getIType results) return $ ImpFunctionWithRecon (ImpFunction funTy funImpl) recon buildRecon :: (HoistableB b, EnvReader m) => b n l -> Atom l -> m l ([IExpr l], AtomRecon n) buildRecon b x = do let (vs, recon) = captureClosure b x xs <- forM vs \v -> do ~(BaseTy ty) <- getType $ Var v return $ IVar v ty return (xs, recon) translateBlock :: forall m i o. (Imper m, Emits o) => MaybeDest o -> Block i -> m i o (Atom o) translateBlock dest (Block _ decls result) = translateDeclNest decls $ translateExpr dest result translateDeclNest :: (Imper m, Emits o) => Nest Decl i i' -> m i' o a -> m i o a translateDeclNest Empty cont = cont translateDeclNest (Nest decl rest) cont = translateDecl decl $ translateDeclNest rest cont translateDecl :: (Imper m, Emits o) => Decl i i' -> m i' o a -> m i o a translateDecl (Let b (DeclBinding _ _ expr)) cont = do ans <- translateExpr Nothing expr extendSubst (b @> SubstVal ans) $ cont translateExpr :: (Imper m, Emits o) => MaybeDest o -> Expr i -> m i o (Atom o) translateExpr maybeDest expr = case expr of Hof hof -> toImpHof maybeDest hof App f' xs' -> do f <- substM f' xs <- mapM substM xs' getType f >>= \case TabTy _ _ -> do case fromNaryLam (length xs) f of Just (NaryLamExpr bs _ body) -> do let subst = bs @@> fmap SubstVal xs body' <- applySubst subst body dropSubst $ translateBlock maybeDest body' _ -> notASimpExpr _ -> case f of Var v -> lookupAtomName v >>= \case FFIFunBound _ v' -> do resultTy <- getType $ App f xs scalarArgs <- liftM toList $ mapM fromScalarAtom xs results <- emitMultiReturnInstr $ ICall v' scalarArgs restructureScalarOrPairType resultTy results SimpLamBound piTy _ -> do if length (toList xs') /= numNaryPiArgs piTy then notASimpExpr else do Just fImp <- queryImpCache v result <- emitCall piTy fImp $ toList xs returnVal result _ -> notASimpExpr _ -> notASimpExpr Atom x -> substM x >>= returnVal Op op -> mapM substM op >>= toImpOp maybeDest Case e alts ty _ -> do e' <- substM e case trySelectBranch e' of Just (con, args) -> do Abs bs body <- return $ alts !! con extendSubst (bs @@> map SubstVal args) $ translateBlock maybeDest body Nothing -> case e' of Con (SumAsProd _ tag xss) -> do tag' <- fromScalarAtom tag dest <- allocDest maybeDest =<< substM ty emitSwitch tag' (zip xss alts) $ \(xs, Abs bs body) -> void $ extendSubst (bs @@> map (SubstVal . sink) xs) $ translateBlock (Just $ sink dest) body destToAtom dest _ -> error "not possible" where notASimpExpr = error $ "not a simplified expression: " ++ pprint expr returnVal atom = case maybeDest of Nothing -> return atom Just dest -> copyAtom dest atom >> return atom toImpOp :: forall m i o . (Imper m, Emits o) => MaybeDest o -> PrimOp (Atom o) -> m i o (Atom o) toImpOp maybeDest op = case op of TabCon ~(Pi tabTy) rows -> do let ixTy = piArgType tabTy resultTy <- resultTyM dest <- allocDest maybeDest resultTy forM_ (zip [0..] rows) \(i, row) -> do ithDest <- destGet dest =<< intToIndexImp ixTy (IIdxRepVal i) copyAtom ithDest row destToAtom dest PrimEffect refDest m -> do case m of MAsk -> returnVal =<< destToAtom refDest MExtend (BaseMonoid _ combine) x -> do xTy <- getType x refVal <- destToAtom refDest result <- liftBuilderImpSimplify $ liftMonoidCombine (sink xTy) (sink combine) (sink refVal) (sink x) copyAtom refDest result returnVal UnitVal MPut x -> copyAtom refDest x >> returnVal UnitVal MGet -> do resultTy <- resultTyM dest <- allocDest maybeDest resultTy -- It might be more efficient to implement a specialized copy for dests -- than to go through a general purpose atom. copyAtom dest =<< destToAtom refDest destToAtom dest UnsafeFromOrdinal n i -> returnVal =<< intToIndexImp n =<< fromScalarAtom i IdxSetSize n -> returnVal =<< toScalarAtom =<< indexSetSizeImp n ToOrdinal idx -> case idx of Con (IntRangeVal _ _ i) -> returnVal $ i Con (IndexRangeVal _ _ _ i) -> returnVal $ i _ -> returnVal =<< toScalarAtom =<< indexToIntImp idx Inject e -> case e of Con (IndexRangeVal t low _ restrictIdx) -> do offset <- case low of InclusiveLim a -> indexToIntImp a ExclusiveLim a -> indexToIntImp a >>= iaddI (IIdxRepVal 1) Unlimited -> return (IIdxRepVal 0) restrictIdx' <- fromScalarAtom restrictIdx returnVal =<< intToIndexImp t =<< iaddI restrictIdx' offset Con (ParIndexCon (TC (ParIndexRange realIdxTy _ _)) i) -> do i' <- fromScalarAtom i returnVal =<< intToIndexImp realIdxTy i' _ -> error $ "Unsupported argument to inject: " ++ pprint e IndexRef refDest i -> returnVal =<< destGet refDest i ProjRef i ~(Con (ConRef (ProdCon refs))) -> returnVal $ refs !! i IOAlloc ty n -> do ptr <- emitAlloc (Heap CPU, ty) =<< fromScalarAtom n returnVal =<< toScalarAtom ptr IOFree ptr -> do ptr' <- fromScalarAtom ptr emitStatement $ Free ptr' return UnitVal PtrOffset arr (IdxRepVal 0) -> returnVal arr PtrOffset arr off -> do arr' <- fromScalarAtom arr off' <- fromScalarAtom off buf <- impOffset arr' off' returnVal =<< toScalarAtom buf PtrLoad arr -> returnVal =<< toScalarAtom =<< loadAnywhere =<< fromScalarAtom arr PtrStore ptr x -> do ptr' <- fromScalarAtom ptr x' <- fromScalarAtom x store ptr' x' return UnitVal SliceOffset ~(Con (IndexSliceVal n _ tileOffset)) idx -> do i' <- indexToIntImp idx tileOffset' <- fromScalarAtom tileOffset i <- iaddI tileOffset' i' returnVal =<< intToIndexImp n i SliceCurry ~(Con (IndexSliceVal _ (PairTy _ v) tileOffset)) idx -> do vz <- intToIndexImp v $ IIdxRepVal 0 extraOffset <- indexToIntImp (PairVal idx vz) tileOffset' <- fromScalarAtom tileOffset tileOffset'' <- iaddI tileOffset' extraOffset returnVal =<< toScalarAtom tileOffset'' ThrowError _ -> do resultTy <- resultTyM dest <- allocDest maybeDest resultTy emitStatement IThrowError -- XXX: we'd be reading uninitialized data here but it's ok because control never reaches -- this point since we just threw an error. destToAtom dest CastOp destTy x -> do sourceTy <- getType x case (sourceTy, destTy) of (BaseTy _, BaseTy bt) -> do x' <- fromScalarAtom x returnVal =<< toScalarAtom =<< cast x' bt (TC (IntRange _ _), IdxRepTy) -> do let Con (IntRangeVal _ _ xord) = x returnVal xord (IdxRepTy, TC (IntRange l h)) -> returnVal $ Con $ IntRangeVal l h x (TC (IndexRange _ _ _), IdxRepTy) -> do let Con (IndexRangeVal _ _ _ xord) = x returnVal xord (IdxRepTy, TC (IndexRange t l h)) -> returnVal $ Con $ IndexRangeVal t l h x _ -> error $ "Invalid cast: " ++ pprint sourceTy ++ " -> " ++ pprint destTy Select p x y -> do xTy <- getType x case xTy of BaseTy _ -> do p' <- fromScalarAtom p x' <- fromScalarAtom x y' <- fromScalarAtom y ans <- emitInstr $ IPrimOp $ Select p' x' y' returnVal =<< toScalarAtom ans _ -> do resultTy <- resultTyM dest <- allocDest maybeDest resultTy p' <- fromScalarAtom p p'' <- cast p' tagBT -- XXX: this is `[y, x]` and not `[x, y]`! `Select` gives the first -- element if the predicate is `1` ("true") and the second if it's `0` -- ("false") but the binary case of the n-ary `switch` does the -- opposite. emitSwitch p'' [y, x] (\arg -> copyAtom (sink dest) (sink arg)) destToAtom dest where (BaseTy tagBT) = TagRepTy RecordCons _ _ -> error "Unreachable: should have simplified away" RecordSplit _ _ -> error "Unreachable: should have simplified away" VariantLift _ _ -> error "Unreachable: should have simplified away" VariantSplit _ _ -> error "Unreachable: should have simplified away" DataConTag con -> case con of Con (SumAsProd _ tag _) -> returnVal tag DataCon _ _ _ i _ -> returnVal $ TagRepVal $ fromIntegral i _ -> error $ "Not a data constructor: " ++ pprint con ToEnum ty i -> returnVal =<< case ty of TypeCon _ defName _ -> do DataDef _ _ cons <- lookupDataDef defName return $ Con $ SumAsProd ty i (map (const []) cons) VariantTy (NoExt labeledItems) -> return $ Con $ SumAsProd ty i (map (const [UnitVal]) $ toList labeledItems) SumTy cases -> return $ Con $ SumAsProd ty i $ cases <&> const [UnitVal] _ -> error $ "Not an enum: " ++ pprint ty SumToVariant ~(Con c) -> do ~resultTy@(VariantTy labs) <- resultTyM returnVal $ case c of SumCon _ tag payload -> Variant labs "c" tag payload SumAsProd _ tag payload -> Con $ SumAsProd resultTy tag payload _ -> error $ "Not a sum type: " ++ pprint (Con c) _ -> do instr <- IPrimOp <$> mapM fromScalarAtom op emitInstr instr >>= toScalarAtom >>= returnVal where resultTyM :: m i o (Type o) resultTyM = getType $ Op op returnVal atom = case maybeDest of Nothing -> return atom Just dest -> copyAtom dest atom >> return atom toImpHof :: (Imper m, Emits o) => Maybe (Dest o) -> PrimHof (Atom i) -> m i o (Atom o) toImpHof maybeDest hof = do -- TODO: it's a shame to have to substitute the whole expression just to get its type. -- Laziness *might* save us, but we should check. resultTy <- getType =<< substM (Hof hof) case hof of For (RegularFor d) (Lam (LamExpr b body)) -> do idxTy <- substM $ binderType b case idxTy of _ -> do n <- indexSetSizeImp idxTy dest <- allocDest maybeDest resultTy emitLoop (getNameHint b) d n \i -> do idx <- intToIndexImp (sink idxTy) i ithDest <- destGet (sink dest) idx void $ extendSubst (b @> SubstVal idx) $ translateBlock (Just ithDest) body destToAtom dest While (Lam (LamExpr b body)) -> do body' <- buildBlockImp $ extendSubst (b@>SubstVal UnitVal) do ans <- fromScalarAtom =<< translateBlock Nothing body return [ans] emitStatement $ IWhile body' return UnitVal RunReader r (Lam (BinaryLamExpr h ref body)) -> do r' <- substM r rDest <- alloc =<< getType r' copyAtom rDest r' extendSubst (h @> SubstVal UnitTy <.> ref @> SubstVal rDest) $ translateBlock maybeDest body RunWriter (BaseMonoid e _) (Lam (BinaryLamExpr h ref body)) -> do let PairTy _ accTy = resultTy (aDest, wDest) <- destPairUnpack <$> allocDest maybeDest resultTy e' <- substM e emptyVal <- liftBuilderImp do PairE accTy' e'' <- sinkM $ PairE accTy e' liftMonoidEmpty accTy' e'' copyAtom wDest emptyVal void $ extendSubst (h @> SubstVal UnitTy <.> ref @> SubstVal wDest) $ translateBlock (Just aDest) body PairVal <$> destToAtom aDest <*> destToAtom wDest RunState s (Lam (BinaryLamExpr h ref body)) -> do s' <- substM s (aDest, sDest) <- destPairUnpack <$> allocDest maybeDest resultTy copyAtom sDest s' void $ extendSubst (h @> SubstVal UnitTy <.> ref @> SubstVal sDest) $ translateBlock (Just aDest) body PairVal <$> destToAtom aDest <*> destToAtom sDest RunIO (Lam (LamExpr b body)) -> extendSubst (b@>SubstVal UnitVal) $ translateBlock maybeDest body _ -> error $ "not implemented: " ++ pprint hof -- === Destination builder monad === -- It's shame to have to reimplement so much for this DestM monad. The problem -- is that `makeDestRec` is emitting two sorts of names: (1) decls to compute -- indexing offsets (often under a table lambda) and (2) pointer names, with -- sizes, for the buffers themselves. The emissions are interleaved, but we're -- really dealing with two separate scopes: the pointer binders are always -- hoistable above the decls. Ideally we'd have a system with two scope -- parameters, where you can separately emit into either. The types would then -- look like this: -- makeDestRec :: Idxs n -> Abs IdxNest Type n -> DestM n l (Dest l) -- emitDecl :: Expr l -> DestM n l (AtomName l) -- emitPointer :: Block n -> DestM n l (AtomName n) data DestPtrInfo n = DestPtrInfo PtrType (Block n) type PtrBinders = Nest AtomNameBinder data DestEmissions n l where DestEmissions :: [DestPtrInfo n] -- pointer types and allocation sizes -> PtrBinders n h -- pointer binders for allocations we require -> Nest Decl h l -- decls to compute indexing offsets -> DestEmissions n l instance GenericB DestEmissions where type RepB DestEmissions = LiftB (ListE DestPtrInfo) `PairB` Nest AtomNameBinder `PairB` Nest Decl fromB (DestEmissions ps bs ds) = LiftB (ListE ps) `PairB` bs `PairB` ds toB (LiftB (ListE ps) `PairB` bs `PairB` ds) = DestEmissions ps bs ds instance BindsEnv DestEmissions where toEnvFrag = undefined -- TODO: might need to add pointer types to pointer binders? instance ProvesExt DestEmissions instance BindsNames DestEmissions instance SinkableB DestEmissions instance SubstB Name DestEmissions instance HoistableB DestEmissions instance OutFrag DestEmissions where emptyOutFrag = DestEmissions [] Empty Empty catOutFrags _ (DestEmissions p1 b1 d1) (DestEmissions p2 b2 d2) = ignoreHoistFailure do ListE p2' <- hoist (PairB b1 d1) (ListE p2) PairB b2' d1' <- withSubscopeDistinct d2 $exchangeBs $ PairB d1 b2 return $ DestEmissions (p1 <> p2') (b1 >>> b2') (d1' >>> d2) newtype DestM (n::S) (a:: *) = DestM { runDestM' :: StateT1 IxCache (InplaceT Env DestEmissions (ReaderT AllocInfo HardFailM)) n a } deriving ( Functor, Applicative, Monad, MonadFail , ScopeReader, Fallible, MonadState (IxCache n) ) liftDestM :: forall m n a. EnvReader m => AllocInfo -> IxCache n -> DestM n a -> m n (a, IxCache n) liftDestM allocInfo cache m = do env <- unsafeGetEnv Distinct <- getDistinct let result = runHardFail $ flip runReaderT allocInfo $ runInplaceT env $ flip runStateT1 cache $ runDestM' m case result of (DestEmissions _ Empty Empty, result') -> return result' _ -> error "not implemented" getAllocInfo :: DestM n AllocInfo getAllocInfo = DestM $ lift11 $ lift1 ask introduceNewPtr :: Mut n => NameHint -> PtrType -> Block n -> DestM n (AtomName n) introduceNewPtr hint ptrTy numel = do Abs b v <- newNameM hint let ptrInfo = DestPtrInfo ptrTy numel let emission = DestEmissions [ptrInfo] (Nest b Empty) Empty DestM $ StateT1 \s -> fmap (,s) $ extendInplaceT $ Abs emission v buildLocalDest :: (SinkableE e) => (forall l. (Mut l, DExt n l) => DestM l (e l)) -> DestM n (AbsPtrs e n) buildLocalDest cont = do Abs (DestEmissions ptrInfo ptrBs decls) e <- DestM $ StateT1 \s -> do Abs bs (PairE e s') <- locallyMutableInplaceT $ fmap toPairE $ flip runStateT1 (sink s) $ runDestM' cont s'' <- hoistState s bs s' return $ (Abs bs e, s'') case decls of Empty -> return $ AbsPtrs (Abs ptrBs e) ptrInfo _ -> error "shouldn't have decls without `Emits`" -- TODO: this is mostly copy-paste from Inference buildDeclsDest :: (Mut n, SubstE Name e, SinkableE e) => (forall l. (Emits l, DExt n l) => DestM l (e l)) -> DestM n (Abs (Nest Decl) e n) buildDeclsDest cont = do DestM $ StateT1 \s -> do Abs (DestEmissions ptrInfo ptrBs decls) result <- locallyMutableInplaceT do Emits <- fabricateEmitsEvidenceM toPairE <$> flip runStateT1 (sink s) (runDestM' cont) Abs decls' (PairE e s') <- extendInplaceT $ Abs (DestEmissions ptrInfo ptrBs Empty) $ Abs decls result s'' <- hoistState s decls' s' return (Abs decls' e, s'') buildBlockDest :: Mut n => (forall l. (Emits l, DExt n l) => DestM l (Atom l)) -> DestM n (Block n) buildBlockDest cont = do Abs decls (PairE result ty) <- buildDeclsDest do result <- cont ty <- getType result return $ result `PairE` ty ty' <- liftHoistExcept $ hoist decls ty return $ Block (BlockAnn ty') decls $ Atom result -- TODO: this is mostly copy-paste from Inference buildAbsDest :: (SinkableE e, SubstE Name e, HoistableE e, Color c, ToBinding binding c) => Mut n => NameHint -> binding n -> (forall l. (Mut l, DExt n l) => Name c l -> DestM l (e l)) -> DestM n (Abs (BinderP c binding) e n) buildAbsDest hint binding cont = DestM $ StateT1 \s -> do resultWithEmissions <- withFreshBinder hint binding \b -> do ab <- locallyMutableInplaceT do fmap toPairE $ flip runStateT1 (sink s) $ runDestM' $ cont $ sink $ binderName b refreshAbs ab \emissions result -> do PairB emissions' b' <- liftHoistExcept $ exchangeBs $ PairB b emissions return $ Abs emissions' $ Abs b' result Abs b (PairE e s') <- extendInplaceT resultWithEmissions s'' <- hoistState s b s' return (Abs (b:>binding) e, s'') -- decls emitted at the inner scope are hoisted to the outer scope -- (they must be hoistable, otherwise we'll get a hoisting error) buildAbsHoistingDeclsDest :: (SinkableE e, SubstE Name e, HoistableE e, Color c, ToBinding binding c) => Emits n => NameHint -> binding n -> (forall l. (Emits l, DExt n l) => Name c l -> DestM l (e l)) -> DestM n (Abs (BinderP c binding) e n) buildAbsHoistingDeclsDest hint binding cont = -- XXX: here we're using the fact that `buildAbsDest` doesn't actually check -- that the function produces no decls (it assumes it can't because it doesn't -- give it `Emits`) and so it just hoists all the emissions. buildAbsDest hint binding \v -> do Emits <- fabricateEmitsEvidenceM cont v buildTabLamDest :: Mut n => NameHint -> Type n -> (forall l. (Emits l, DExt n l) => AtomName l -> DestM l (Atom l)) -> DestM n (Atom n) buildTabLamDest hint ty cont = do Abs (b:>_) body <- buildAbsDest hint (LamBinding TabArrow ty) \v -> buildBlockDest $ sinkM v >>= cont return $ Lam $ LamExpr (LamBinder b ty TabArrow Pure) body instance EnvExtender DestM where refreshAbs ab cont = DestM $ StateT1 \s -> do (ans, (Abs b s')) <- refreshAbs ab \b e -> do (ans, s') <- flip runStateT1 (sink s) $ runDestM' $ cont b e return (ans, Abs b s') s'' <- hoistState s b s' return (ans, s'') instance EnvReader DestM where unsafeGetEnv = DestM $ lift11 $ getOutMapInplaceT instance Builder DestM where emitDecl hint ann expr = do ty <- getType expr Abs b v <- newNameM hint let decl = Let b $ DeclBinding ann ty expr let emissions = DestEmissions [] Empty $ Nest decl Empty DestM $ StateT1 \s -> fmap (,s) $ extendInplaceT $ Abs emissions v instance ExtOutMap Env DestEmissions where extendOutMap bindings (DestEmissions ptrInfo ptrs decls) = withSubscopeDistinct decls $ (bindings `extendOutMap` ptrBindersToEnvFrag ptrInfo ptrs) `extendOutMap` decls where ptrBindersToEnvFrag :: Distinct l => [DestPtrInfo n] -> Nest AtomNameBinder n l -> EnvFrag n l ptrBindersToEnvFrag [] Empty = emptyOutFrag ptrBindersToEnvFrag (DestPtrInfo ty _ : rest) (Nest b restBs) = withSubscopeDistinct restBs do let frag1 = toEnvFrag $ b :> PtrTy ty let frag2 = withExtEvidence (toExtEvidence b) $ ptrBindersToEnvFrag (map sink rest) restBs frag1 `catEnvFrags` frag2 ptrBindersToEnvFrag _ _ = error "mismatched indices" instance GenericE DestPtrInfo where type RepE DestPtrInfo = PairE (LiftE PtrType) Block fromE (DestPtrInfo ty n) = PairE (LiftE ty) n toE (PairE (LiftE ty) n) = DestPtrInfo ty n instance SinkableE DestPtrInfo instance HoistableE DestPtrInfo instance SubstE Name DestPtrInfo instance SubstE AtomSubstVal DestPtrInfo -- === Destination builder === type Dest = Atom -- has type `Ref a` for some a type MaybeDest n = Maybe (Dest n) data AbsPtrs e n = AbsPtrs (Abs PtrBinders e n) [DestPtrInfo n] instance GenericE (AbsPtrs e) where type RepE (AbsPtrs e) = PairE (NaryAbs AtomNameC e) (ListE DestPtrInfo) fromE (AbsPtrs ab ptrInfo) = PairE ab (ListE ptrInfo) toE (PairE ab (ListE ptrInfo)) = AbsPtrs ab ptrInfo instance SinkableE e => SinkableE (AbsPtrs e) instance HoistableE e => HoistableE (AbsPtrs e) instance SubstE Name e => SubstE Name (AbsPtrs e) instance SubstE AtomSubstVal e => SubstE AtomSubstVal (AbsPtrs e) -- builds a dest and a list of pointer binders along with their required allocation sizes makeDest :: (ImpBuilder m, EnvReader m) => AllocInfo -> Type n -> m n (AbsPtrs Dest n) makeDest allocInfo ty = do cache <- get (result, cache') <- liftDestM allocInfo cache $ buildLocalDest $ makeSingleDest [] $ sink ty put cache' return result makeSingleDest :: Mut n => [AtomName n] -> Type n -> DestM n (Dest n) makeSingleDest depVars ty = do Abs decls dest <- buildDeclsDest $ makeDestRec (Abs Empty UnitE, []) (map sink depVars) (sink ty) case decls of Empty -> return dest _ -> error $ "shouldn't need to emit decls if we're not working with indices" ++ pprint decls extendIdxsTy :: EnvReader m => DestIdxs n -> Type n -> m n (EmptyAbs IdxNest n) extendIdxsTy (idxsTy, idxs) new = do let newAbs = abstractFreeVarsNoAnn idxs new Abs bs (Abs b UnitE) <- liftBuilder $ buildNaryAbs idxsTy \idxs' -> do ty' <- applyNaryAbs (sink newAbs) idxs' singletonBinderNest NoHint ty' return $ Abs (bs >>> b) UnitE type Idxs n = [AtomName n] type IdxNest = Nest Binder type DestIdxs n = (EmptyAbs IdxNest n, Idxs n) type DepVars n = [AtomName n] -- TODO: make `DestIdxs` a proper E-kinded thing sinkDestIdxs :: DExt n l => DestIdxs n -> DestIdxs l sinkDestIdxs (idxsTy, idxs) = (sink idxsTy, map sink idxs) -- dest for the args and the result -- TODO: de-dup some of the plumbing stuff here with the ordinary makeDest path type NaryLamDest = Abs (Nest (BinderP AtomNameC Dest)) Dest makeNaryLamDest :: (ImpBuilder m, EnvReader m) => NaryPiType n -> m n (AbsPtrs NaryLamDest n) makeNaryLamDest piTy = do cache <- get let allocInfo = (LLVM, CPU, Unmanaged) -- TODO! This is just a placeholder (result, cache') <- liftDestM allocInfo cache $ buildLocalDest do Abs decls dest <- buildDeclsDest $ makeNaryLamDestRec (Abs Empty UnitE, []) [] (sink piTy) case decls of Empty -> return dest _ -> error "shouldn't have decls if we have empty indices" put cache' return result makeNaryLamDestRec :: forall n. Emits n => DestIdxs n -> DepVars n -> NaryPiType n -> DestM n (NaryLamDest n) makeNaryLamDestRec idxs depVars (NaryPiType (NonEmptyNest b bs) Pure resultTy) = do let argTy = binderType b argDest <- makeDestRec idxs depVars argTy Abs (b':>_) (Abs bs' resultDest) <- buildDepDest idxs depVars (getNameHint b) argTy \idxs' depVars' v -> do case bs of Empty -> do resultTy' <- applySubst (b@>v) resultTy Abs Empty <$> makeDestRec idxs' depVars' resultTy' Nest b1 bsRest -> do restPiTy <- applySubst (b@>v) $ NaryPiType (NonEmptyNest b1 bsRest) Pure resultTy makeNaryLamDestRec idxs' depVars' restPiTy return $ Abs (Nest (b':>argDest) bs') resultDest makeNaryLamDestRec _ _ _ = error "effectful functions not implemented" -- TODO: should we put DestIdxs/DepVars in the monad? And maybe it should also -- be a substituting one. buildDepDest :: (SinkableE e, SubstE Name e, HoistableE e, Emits n) => DestIdxs n -> DepVars n -> NameHint -> Type n -> (forall l. (Emits l, DExt n l) => DestIdxs l -> DepVars l -> AtomName l -> DestM l (e l)) -> DestM n (Abs Binder e n) buildDepDest idxs depVars hint ty cont = buildAbsHoistingDeclsDest hint ty \v -> do let depVars' = map sink depVars ++ [v] cont (sinkDestIdxs idxs) depVars' v -- `makeDestRec` builds an array of dests. The curried index type, `EmptyAbs -- IdxNest n`, determines a set of valid indices, `Idxs n`. At each valid value -- of `Idxs n` we should have a distinct dest. The `depVars` are a list of -- variables whose values we won't know until we actually store something. The -- resulting `Dest n` may mention these variables, but the pointer allocation -- sizes can't. makeDestRec :: forall n. Emits n => DestIdxs n -> DepVars n -> Type n -> DestM n (Dest n) makeDestRec idxs depVars ty = case ty of TabTy (PiBinder b iTy _) bodyTy -> do if depVars `areFreeIn` iTy then do AbsPtrs absDest ptrsInfo <- buildLocalDest $ makeSingleDest [] $ sink ty ptrs <- forM ptrsInfo \(DestPtrInfo ptrTy size) -> do ptr <- makeBaseTypePtr idxs (PtrType ptrTy) return (ptr, size) return $ BoxedRef ptrs absDest else do Distinct <- getDistinct idxsTy <- extendIdxsTy idxs iTy Con <$> TabRef <$> buildTabLamDest "i" iTy \v -> do let newIdxVals = map sink (snd idxs) <> [v] bodyTy' <- applyAbs (sink $ Abs b bodyTy) v makeDestRec (sink idxsTy, newIdxVals) (map sink depVars) bodyTy' TypeCon _ defName params -> do def <- lookupDataDef defName dcs <- instantiateDataDef def params case dcs of [] -> error "Void type not allowed" [DataConDef _ dataConBinders] -> do Distinct <- getDistinct dests <- makeDataConDest depVars dataConBinders return $ DataConRef defName params dests where makeDataConDest :: (Emits l, DExt n l) => [AtomName l] -> EmptyAbs (Nest Binder) l -> DestM l (EmptyAbs (Nest DataConRefBinding) l) makeDataConDest depVars' (Abs bs UnitE) = case bs of Empty -> return $ EmptyAbs Empty Nest (b:>bTy) rest -> do dest <- makeDestRec (sinkDestIdxs idxs) depVars' bTy Abs b' (EmptyAbs restDest) <- buildAbsHoistingDeclsDest (getNameHint b) bTy \v -> do let depVars'' = map sink depVars' ++ [v] rest' <- applySubst (b@>v) $ EmptyAbs rest makeDataConDest depVars'' rest' return $ EmptyAbs $ Nest (DataConRefBinding b' dest) restDest _ -> do tag <- rec TagRepTy contents <- forM dcs \dc -> case nonDepDataConTys dc of Nothing -> error "Dependent data constructors only allowed for single-constructor types" Just tys -> mapM (makeDestRec idxs depVars) tys return $ Con $ ConRef $ SumAsProd ty tag contents DepPairTy depPairTy@(DepPairType (lBinder:>lTy) rTy) -> do lDest <- rec lTy rDestAbs <- buildDepDest idxs depVars (getNameHint lBinder) lTy \idxs' depVars' v -> do rTy' <- applySubst (lBinder@>v) rTy makeDestRec idxs' depVars' rTy' return $ DepPairRef lDest rDestAbs depPairTy StaticRecordTy types -> (Con . RecordRef) <$> forM types rec VariantTy (NoExt types) -> recSumType $ toList types TC con -> case con of BaseType b -> do ptr <- makeBaseTypePtr idxs b return $ Con $ BaseTypeRef ptr SumType cases -> recSumType cases ProdType tys -> (Con . ConRef) <$> (ProdCon <$> traverse rec tys) IntRange l h -> do x <- rec IdxRepTy return $ Con $ ConRef $ IntRangeVal l h x IndexRange t l h -> do x <- rec IdxRepTy return $ Con $ ConRef $ IndexRangeVal t l h x _ -> error $ "not implemented: " ++ pprint con _ -> error $ "not implemented: " ++ pprint ty where rec = makeDestRec idxs depVars recSumType cases = do tag <- rec TagRepTy contents <- forM cases rec return $ Con $ ConRef $ SumAsProd ty tag $ map (\x->[x]) contents makeBaseTypePtr :: Emits n => DestIdxs n -> BaseType -> DestM n (Atom n) makeBaseTypePtr (idxsTy, idxs) ty = do offset <- computeOffset idxsTy idxs numel <- buildBlockDest $ computeElemCount (sink idxsTy) allocInfo <- getAllocInfo let addrSpace = chooseAddrSpace allocInfo numel let ptrTy = (addrSpace, ty) ptr <- Var <$> introduceNewPtr "ptr" ptrTy numel ptrOffset ptr offset copyAtom :: (ImpBuilder m, Emits n) => Dest n -> Atom n -> m n () copyAtom topDest topSrc = copyRec topDest topSrc where copyRec :: (ImpBuilder m, Emits n) => Dest n -> Atom n -> m n () copyRec dest src = case (dest, src) of (BoxedRef ptrsSizes absDest, _) -> do -- TODO: load old ptr and free (recursively) ptrs <- forM ptrsSizes \(ptrPtr, sizeBlock) -> do PtrTy (_, (PtrType ptrTy)) <- getType ptrPtr size <- liftBuilderImp $ emitBlock =<< sinkM sizeBlock ptr <- emitAlloc ptrTy =<< fromScalarAtom size ptrPtr' <- fromScalarAtom ptrPtr storeAnywhere ptrPtr' ptr toScalarAtom ptr dest' <- applyNaryAbs absDest (map SubstVal ptrs) copyRec dest' src (DepPairRef lRef rRefAbs _, DepPair l r _) -> do copyAtom lRef l rRef <- applyAbs rRefAbs (SubstVal l) copyAtom rRef r (DataConRef _ _ refs, DataCon _ _ _ _ vals) -> copyDataConArgs refs vals (Con destRefCon, _) -> case (destRefCon, src) of (RecordRef refs, Record vals) | fmap (const ()) refs == fmap (const ()) vals -> do zipWithM_ copyRec (toList refs) (toList vals) (TabRef _, Lam _) -> zipTabDestAtom copyRec dest src (BaseTypeRef ptr, _) -> do ptr' <- fromScalarAtom ptr src' <- fromScalarAtom src storeAnywhere ptr' src' (ConRef (SumAsProd _ tag payload), _) -> case src of DataCon _ _ _ con x -> do copyRec tag $ TagRepVal $ fromIntegral con zipWithM_ copyRec (payload !! con) x Con (SumAsProd _ tagSrc payloadSrc) -> do copyRec tag tagSrc unless (all null payload) do -- optimization tagSrc' <- fromScalarAtom tagSrc emitSwitch tagSrc' (zip payload payloadSrc) \(d, s) -> zipWithM_ copyRec (map sink d) (map sink s) SumVal _ con x -> do copyRec tag $ TagRepVal $ fromIntegral con case payload !! con of [xDest] -> copyRec xDest x _ -> error "Expected singleton payload in SumAsProd" Variant (NoExt types) label i x -> do let LabeledItems ixtypes = enumerate types let index = fst $ (ixtypes M.! label) NE.!! i copyRec tag (TagRepVal $ fromIntegral index) zipWithM_ copyRec (payload !! index) [x] _ -> error "unexpected src/dest pair" (ConRef destCon, Con srcCon) -> zipWithRefConM copyRec destCon srcCon _ -> error "unexpected src/dest pair" _ -> error "unexpected src/dest pair" zipTabDestAtom :: (Emits n, ImpBuilder m) => (forall l. (Emits l, DExt n l) => Dest l -> Atom l -> m l ()) -> Dest n -> Atom n -> m n () zipTabDestAtom f dest src = do Con (TabRef (Lam (LamExpr b _))) <- return dest Lam (LamExpr b' _) <- return src checkAlphaEq (binderType b) (binderType b') let idxTy = binderType b n <- indexSetSizeImp idxTy emitLoop "i" Fwd n \i -> do idx <- intToIndexImp (sink idxTy) i destIndexed <- destGet (sink dest) idx srcIndexed <- runSubstReaderT idSubst $ translateExpr Nothing (App (sink src) (idx:|[])) f destIndexed srcIndexed zipWithRefConM :: Monad m => (Dest n -> Atom n -> m ()) -> Con n -> Con n -> m () zipWithRefConM f destCon srcCon = case (destCon, srcCon) of (ProdCon ds, ProdCon ss) -> zipWithM_ f ds ss (IntRangeVal _ _ iRef, IntRangeVal _ _ i) -> f iRef i (IndexRangeVal _ _ _ iRef, IndexRangeVal _ _ _ i) -> f iRef i _ -> error $ "Unexpected ref/val " ++ pprint (destCon, srcCon) copyDataConArgs :: (ImpBuilder m, Emits n) => EmptyAbs (Nest DataConRefBinding) n -> [Atom n] -> m n () copyDataConArgs (Abs Empty UnitE) [] = return () copyDataConArgs (Abs (Nest (DataConRefBinding b ref) rest) UnitE) (x:xs) = do copyAtom ref x rest' <- applySubst (b@>SubstVal x) (EmptyAbs rest) copyDataConArgs rest' xs copyDataConArgs bindings args = error $ "Mismatched bindings/args: " ++ pprint (bindings, args) loadAnywhere :: (ImpBuilder m, Emits n) => IExpr n -> m n (IExpr n) loadAnywhere ptr = load ptr -- TODO: generalize to GPU backend storeAnywhere :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n () storeAnywhere ptr val = store ptr val store :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n () store dest src = emitStatement $ Store dest src alloc :: (ImpBuilder m, Emits n) => Type n -> m n (Dest n) alloc ty = makeAllocDest Managed ty indexDest :: (Builder m, Emits n) => Dest n -> Atom n -> m n (Dest n) indexDest (Con (TabRef (Lam (LamExpr b body)))) i = do body' <- applyAbs (Abs b body) $ SubstVal i emitBlock body' indexDest dest _ = error $ pprint dest loadDest :: (Builder m, Emits n) => Dest n -> m n (Atom n) loadDest (DataConRef def params bs) = do DataDef _ _ cons <- lookupDataDef def let DataConDef conName _ = cons !! 0 DataCon conName def params 0 <$> loadDataConArgs bs loadDest (DepPairRef lr rra a) = do l <- loadDest lr r <- loadDest =<< applyAbs rra (SubstVal l) return $ DepPair l r a loadDest (BoxedRef ptrsSizes absDest) = do ptrs <- forM ptrsSizes \(ptrPtr, _) -> unsafePtrLoad ptrPtr dest <- applyNaryAbs absDest (map SubstVal ptrs) loadDest dest loadDest (Con dest) = do case dest of BaseTypeRef ptr -> unsafePtrLoad ptr TabRef (Lam (LamExpr b body)) -> liftEmitBuilder $ buildLam (getNameHint b) TabArrow (binderType b) Pure \i -> do body' <- applySubst (b@>i) body result <- emitBlock body' loadDest result RecordRef xs -> Record <$> traverse loadDest xs ConRef con -> Con <$> case con of ProdCon ds -> ProdCon <$> traverse loadDest ds SumAsProd ty tag xss -> SumAsProd ty <$> loadDest tag <*> mapM (mapM loadDest) xss IntRangeVal l h iRef -> IntRangeVal l h <$> loadDest iRef IndexRangeVal t l h iRef -> IndexRangeVal t l h <$> loadDest iRef _ -> error $ "Not a valid dest: " ++ pprint dest _ -> error $ "not implemented" ++ pprint dest loadDest dest = error $ "not implemented" ++ pprint dest loadDataConArgs :: (Builder m, Emits n) => EmptyAbs (Nest DataConRefBinding) n -> m n [Atom n] loadDataConArgs (Abs bs UnitE) = case bs of Empty -> return [] Nest (DataConRefBinding b ref) rest -> do val <- loadDest ref rest' <- applySubst (b @> SubstVal val) $ EmptyAbs rest (val:) <$> loadDataConArgs rest' _emitWhen :: (ImpBuilder m, Emits n) => IExpr n -> (forall l. (Emits l, DExt n l) => m l ()) -> m n () _emitWhen cond doIfTrue = emitSwitch cond [False, True] \case False -> return () True -> doIfTrue -- TODO: Consider targeting LLVM's `switch` instead of chained conditionals. emitSwitch :: forall m n a. (ImpBuilder m, Emits n) => IExpr n -> [a] -> (forall l. (Emits l, DExt n l) => a -> m l ()) -> m n () emitSwitch testIdx args cont = do Distinct <- getDistinct rec 0 args where rec :: forall l. (Emits l, DExt n l) => Int -> [a] -> m l () rec _ [] = error "Shouldn't have an empty list of alternatives" rec _ [arg] = cont arg rec curIdx (arg:rest) = do curTag <- fromScalarAtom $ TagRepVal $ fromIntegral curIdx cond <- emitInstr $ IPrimOp $ ScalarBinOp (ICmp Equal) (sink testIdx) curTag thisCase <- buildBlockImp $ cont arg >> return [] otherCases <- buildBlockImp $ rec (curIdx + 1) rest >> return [] emitStatement $ ICond cond thisCase otherCases emitLoop :: (ImpBuilder m, Emits n) => NameHint -> Direction -> IExpr n -> (forall l. (DExt n l, Emits l) => IExpr l -> m l ()) -> m n () emitLoop hint d n cont = do loopBody <- do withFreshIBinder hint (getIType n) \b@(IBinder _ ty) -> do let i = IVar (binderName b) ty body <- buildBlockImp do cont =<< sinkM i return [] return $ Abs b body emitStatement $ IFor d n loopBody restructureScalarOrPairType :: EnvReader m => Type n -> [IExpr n] -> m n (Atom n) restructureScalarOrPairType ty xs = restructureScalarOrPairTypeRec ty xs >>= \case (atom, []) -> return atom _ -> error "Wrong number of scalars" restructureScalarOrPairTypeRec :: EnvReader m => Type n -> [IExpr n] -> m n (Atom n, [IExpr n]) restructureScalarOrPairTypeRec (PairTy t1 t2) xs = do (atom1, rest1) <- restructureScalarOrPairTypeRec t1 xs (atom2, rest2) <- restructureScalarOrPairTypeRec t2 rest1 return (PairVal atom1 atom2, rest2) restructureScalarOrPairTypeRec (BaseTy _) (x:xs) = do x' <- toScalarAtom x return (x', xs) restructureScalarOrPairTypeRec ty _ = error $ "Not a scalar or pair: " ++ pprint ty buildBlockImp :: ImpBuilder m => (forall l. (Emits l, DExt n l) => m l [IExpr l]) -> m n (ImpBlock n) buildBlockImp cont = do Abs decls (ListE results) <- buildScopedImp $ ListE <$> cont return $ ImpBlock decls results destToAtom :: (ImpBuilder m, Emits n) => Dest n -> m n (Atom n) destToAtom dest = liftBuilderImp $ loadDest =<< sinkM dest destGet :: (ImpBuilder m, Emits n) => Dest n -> Atom n -> m n (Dest n) destGet dest i = liftBuilderImp $ do Distinct <- getDistinct indexDest (sink dest) (sink i) destPairUnpack :: Dest n -> (Dest n, Dest n) destPairUnpack (Con (ConRef (ProdCon [l, r]))) = (l, r) destPairUnpack d = error $ "Not a pair destination: " ++ show d _fromDestConsList :: Dest n -> [Dest n] _fromDestConsList dest = case dest of Con (ConRef (ProdCon [h, t])) -> h : _fromDestConsList t Con (ConRef (ProdCon [])) -> [] _ -> error $ "Not a dest cons list: " ++ pprint dest makeAllocDest :: (ImpBuilder m, Emits n) => AllocType -> Type n -> m n (Dest n) makeAllocDest allocTy ty = fst <$> makeAllocDestWithPtrs allocTy ty backend_TODO_DONT_HARDCODE :: Backend backend_TODO_DONT_HARDCODE = LLVM curDev_TODO_DONT_HARDCODE :: Device curDev_TODO_DONT_HARDCODE = CPU makeAllocDestWithPtrs :: (ImpBuilder m, Emits n) => AllocType -> Type n -> m n (Dest n, [IExpr n]) makeAllocDestWithPtrs allocTy ty = do let backend = backend_TODO_DONT_HARDCODE let curDev = curDev_TODO_DONT_HARDCODE AbsPtrs absDest ptrDefs <- makeDest (backend, curDev, allocTy) ty ptrs <- forM ptrDefs \(DestPtrInfo ptrTy sizeBlock) -> do Distinct <- getDistinct size <- liftBuilderImp $ emitBlock $ sink sizeBlock ptr <- emitAlloc ptrTy =<< fromScalarAtom size case ptrTy of (Heap _, _) | allocTy == Managed -> extendAllocsToFree ptr _ -> return () return ptr ptrAtoms <- mapM toScalarAtom ptrs dest' <- applyNaryAbs absDest $ map SubstVal ptrAtoms return (dest', ptrs) _copyDest :: (ImpBuilder m, Emits n) => Maybe (Dest n) -> Atom n -> m n (Atom n) _copyDest maybeDest atom = case maybeDest of Nothing -> return atom Just dest -> copyAtom dest atom >> return atom allocDest :: (ImpBuilder m, Emits n) => Maybe (Dest n) -> Type n -> m n (Dest n) allocDest maybeDest t = case maybeDest of Nothing -> alloc t Just dest -> return dest type AllocInfo = (Backend, Device, AllocType) data AllocType = Managed | Unmanaged deriving (Show, Eq) chooseAddrSpace :: AllocInfo -> Block n -> AddressSpace chooseAddrSpace (backend, curDev, allocTy) numel = case allocTy of Unmanaged -> Heap mainDev Managed | curDev == mainDev -> if isSmall numel then Stack else Heap mainDev | otherwise -> Heap mainDev where mainDev = case backend of LLVM -> CPU LLVMMC -> CPU LLVMCUDA -> GPU MLIR -> error "Shouldn't be compiling to Imp with MLIR backend" Interpreter -> error "Shouldn't be compiling to Imp with interpreter backend" isSmall :: Block n -> Bool isSmall numel = case numel of Block _ Empty (Atom (Con (Lit l))) | getIntLit l <= 256 -> True _ -> False -- TODO: separate these concepts in IFunType? _deviceFromCallingConvention :: CallingConvention -> Device _deviceFromCallingConvention cc = case cc of CEntryFun -> CPU CInternalFun -> CPU EntryFun _ -> CPU FFIFun -> CPU FFIMultiResultFun -> CPU MCThreadLaunch -> CPU CUDAKernelLaunch -> GPU -- === Determining buffer sizes and offsets using polynomials === type IndexStructure = EmptyAbs IdxNest :: E computeElemCount :: (Emits n, Builder m, MonadIxCache1 m) => IndexStructure n -> m n (Atom n) computeElemCount (EmptyAbs Empty) = -- XXX: this optimization is important because we don't want to emit any decls -- in the case that we don't have any indices. The more general path will -- still compute `1`, but it might emit decls along the way. return $ IdxRepVal 1 computeElemCount idxNest' = do let (idxList, idxNest) = indexStructureSplit idxNest' listSize <- foldM imul (IdxRepVal 1) =<< forM idxList \ty -> do appSimplifiedIxMethod ty simpleIxSize UnitVal nestSize <- A.emitCPoly =<< elemCountCPoly idxNest imul listSize nestSize -- Split the index structure into a prefix of non-dependent index types -- and a trailing nest of indices that can contain inter-dependencies. indexStructureSplit :: IndexStructure n -> ([Type n], IndexStructure n) indexStructureSplit (Abs Empty UnitE) = ([], EmptyAbs Empty) indexStructureSplit s@(Abs (Nest b rest) UnitE) = case hoist b (EmptyAbs rest) of HoistFailure _ -> ([], s) HoistSuccess rest' -> (binderType b:ans1, ans2) where (ans1, ans2) = indexStructureSplit rest' dceApproxBlock :: Block n -> Block n dceApproxBlock block@(Block _ decls expr) = case hoist decls expr of HoistSuccess expr' -> Block NoBlockAnn Empty expr' HoistFailure _ -> block computeOffset :: forall n m. (Emits n, Builder m, MonadIxCache1 m) => IndexStructure n -> [AtomName n] -> m n (Atom n) computeOffset idxNest' idxs = do let (idxList , idxNest ) = indexStructureSplit idxNest' let (listIdxs, nestIdxs) = splitAt (length idxList) idxs nestOffset <- rec idxNest nestIdxs nestSize <- computeElemCount idxNest listOrds <- forM listIdxs \i -> do ty <- getType i appSimplifiedIxMethod ty simpleToOrdinal $ Var i -- We don't compute the first size (which we don't need!) to avoid emitting unnecessary decls. idxListSizes <- case idxList of [] -> return [] _ -> fmap (IdxRepVal (-1):) $ forM (tail idxList) \ty -> do appSimplifiedIxMethod ty simpleIxSize UnitVal listOffset <- fst <$> foldM accumStrided (IdxRepVal 0, nestSize) (reverse $ zip idxListSizes listOrds) iadd listOffset nestOffset where accumStrided (total, stride) (size, i) = (,) <$> (iadd total =<< imul i stride) <*> imul stride size -- Recursively process the dependent part of the nest rec :: IndexStructure n -> [AtomName n] -> m n (Atom n) rec (Abs Empty UnitE) [] = return $ IdxRepVal 0 rec (Abs (Nest b bs) UnitE) (i:is) = do rhsElemCounts <- refreshBinders b \(b':>_) s -> do rest' <- applySubst s $ EmptyAbs bs Abs b' <$> elemCountCPoly rest' significantOffset <- A.emitCPoly $ A.sumC i rhsElemCounts remainingIdxStructure <- applySubst (b@>i) (EmptyAbs bs) otherOffsets <- rec remainingIdxStructure is iadd significantOffset otherOffsets rec _ _ = error "zip error" emitSimplified :: (Emits n, Builder m) => (forall l. (Emits l, DExt n l) => BuilderM l (Atom l)) -> m n (Atom n) emitSimplified m = emitBlock . dceApproxBlock =<< buildBlockSimplified m elemCountCPoly :: (EnvExtender m, EnvReader m, Fallible1 m, MonadIxCache1 m) => IndexStructure n -> m n (A.ClampPolynomial n) elemCountCPoly (Abs bs UnitE) = case bs of Empty -> return $ A.liftPoly $ A.emptyMonomial Nest b rest -> do -- TODO: Use the simplified version here! sizeBlock <- liftBuilder $ buildBlock $ emitSimplified $ indexSetSize $ sink $ binderType b msize <- A.blockAsCPoly sizeBlock case msize of Just size -> do rhsElemCounts <- refreshBinders b \(b':>_) s -> do rest' <- applySubst s $ Abs rest UnitE Abs b' <$> elemCountCPoly rest' withFreshBinder NoHint IdxRepTy \b' -> do let sumPoly = A.sumC (binderName b') (sink rhsElemCounts) return $ A.psubst (Abs b' sumPoly) size _ -> throw NotImplementedErr $ "Algebraic simplification failed to model index computations: " ++ pprint sizeBlock -- === Imp IR builder === class (EnvReader m, EnvExtender m, Fallible1 m, MonadIxCache1 m) => ImpBuilder (m::MonadKind1) where emitMultiReturnInstr :: Emits n => ImpInstr n -> m n [IExpr n] buildScopedImp :: SinkableE e => (forall l. (Emits l, DExt n l) => m l (e l)) -> m n (Abs (Nest ImpDecl) e n) extendAllocsToFree :: Mut n => IExpr n -> m n () type ImpBuilder2 (m::MonadKind2) = forall i. ImpBuilder (m i) withFreshIBinder :: ImpBuilder m => NameHint -> IType -> (forall l. DExt n l => IBinder n l -> m l a) -> m n a withFreshIBinder hint ty cont = do withFreshBinder hint (MiscBound $ BaseTy ty) \b -> cont $ IBinder b ty emitCall :: (Emits n, ImpBuilder m) => NaryPiType n -> ImpFunName n -> [Atom n] -> m n (Atom n) emitCall piTy f xs = do AbsPtrs absDest ptrDefs <- makeNaryLamDest piTy ptrs <- forM ptrDefs \(DestPtrInfo ptrTy sizeBlock) -> do Distinct <- getDistinct size <- liftBuilderImp $ emitBlock $ sink sizeBlock emitAlloc ptrTy =<< fromScalarAtom size ptrAtoms <- mapM toScalarAtom ptrs dest <- applyNaryAbs absDest $ map SubstVal ptrAtoms resultDest <- storeArgDests dest xs _ <- emitMultiReturnInstr $ ICall f ptrs destToAtom resultDest buildImpFunction :: ImpBuilder m => CallingConvention -> [(NameHint, IType)] -> (forall l. (Emits l, DExt n l) => [AtomName l] -> m l [IExpr l]) -> m n (ImpFunction n) buildImpFunction cc argHintsTys body = do Abs bs (Abs decls (ListE results)) <- buildImpNaryAbs argHintsTys \vs -> ListE <$> body vs let resultTys = map getIType results let impFun = IFunType cc (map snd argHintsTys) resultTys return $ ImpFunction impFun $ Abs bs $ ImpBlock decls results buildImpNaryAbs :: (ImpBuilder m, SinkableE e, HasNamesE e, SubstE Name e, HoistableE e) => [(NameHint, IType)] -> (forall l. (Emits l, DExt n l) => [AtomName l] -> m l (e l)) -> m n (Abs (Nest IBinder) (Abs (Nest ImpDecl) e) n) buildImpNaryAbs [] cont = do Distinct <- getDistinct Abs Empty <$> buildScopedImp (cont []) buildImpNaryAbs ((hint,ty) : rest) cont = do withFreshIBinder hint ty \b -> do ab <- buildImpNaryAbs rest \vs -> do v <- sinkM $ binderName b cont (v : vs) Abs bs body <- return ab return $ Abs (Nest b bs) body emitInstr :: (ImpBuilder m, Emits n) => ImpInstr n -> m n (IExpr n) emitInstr instr = do xs <- emitMultiReturnInstr instr case xs of [x] -> return x _ -> error "unexpected numer of return values" emitStatement :: (ImpBuilder m, Emits n) => ImpInstr n -> m n () emitStatement instr = do xs <- emitMultiReturnInstr instr case xs of [] -> return () _ -> error "unexpected numer of return values" emitAlloc :: (ImpBuilder m, Emits n) => PtrType -> IExpr n -> m n (IExpr n) emitAlloc (addr, ty) n = emitInstr $ Alloc addr ty n buildBinOp :: (ImpBuilder m, Emits n) => (forall l. (Emits l, DExt n l) => Atom l -> Atom l -> BuilderM l (Atom l)) -> IExpr n -> IExpr n -> m n (IExpr n) buildBinOp f x y = fromScalarAtom =<< liftBuilderImp do Distinct <- getDistinct x' <- toScalarAtom $ sink x y' <- toScalarAtom $ sink y f x' y' iaddI :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) iaddI = buildBinOp iadd _isubI :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) _isubI = buildBinOp isub _imulI :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) _imulI = buildBinOp imul _idivI :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) _idivI = buildBinOp idiv _iltI :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) _iltI = buildBinOp ilt _ieqI :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) _ieqI = buildBinOp ieq _bandI :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) _bandI x y = emitInstr $ IPrimOp $ ScalarBinOp BAnd x y impOffset :: (ImpBuilder m, Emits n) => IExpr n -> IExpr n -> m n (IExpr n) impOffset ref off = emitInstr $ IPrimOp $ PtrOffset ref off cast :: (ImpBuilder m, Emits n) => IExpr n -> BaseType -> m n (IExpr n) cast x bt = emitInstr $ ICastOp bt x load :: (ImpBuilder m, Emits n) => IExpr n -> m n (IExpr n) load x = emitInstr $ IPrimOp $ PtrLoad x -- === Atom <-> IExpr conversions === fromScalarAtom :: HasCallStack => EnvReader m => Atom n -> m n (IExpr n) fromScalarAtom atom = case atom of Var v -> do ~(BaseTy b) <- getType $ Var v return $ IVar v b Con (Lit x) -> return $ ILit x _ -> error $ "Expected scalar, got: " ++ pprint atom toScalarAtom :: EnvReader m => IExpr n -> m n (Atom n) toScalarAtom ie = case ie of ILit l -> return $ Con $ Lit l IVar v _ -> return $ Var v -- === Type classes === -- TODO: we shouldn't need the rank-2 type here because ImpBuilder and Builder -- are part of the same conspiracy. liftBuilderImp :: (Emits n, ImpBuilder m, SubstE AtomSubstVal e, SinkableE e) => (forall l. (Emits l, DExt n l) => BuilderM l (e l)) -> m n (e n) liftBuilderImp cont = do Abs decls result <- liftBuilder $ buildScoped cont runSubstReaderT idSubst $ translateDeclNest decls $ substM result -- TODO: should we merge this with `liftBuilderImp`? Not much harm in -- simplifying even if it's not needed. liftBuilderImpSimplify :: (Emits n, ImpBuilder m) => (forall l. (Emits l, DExt n l) => BuilderM l (Atom l)) -> m n (Atom n) liftBuilderImpSimplify cont = do block <- dceApproxBlock <$> liftSimplifyM do block <- liftBuilder $ buildBlock cont buildBlock $ simplifyBlock block runSubstReaderT idSubst $ translateBlock Nothing block appSimplifiedIxMethodImp :: (Emits n, ImpBuilder m) => Type n -> (SimpleIxInstance n -> Abs (Nest Decl) LamExpr n) -> Atom n -> m n (Atom n) appSimplifiedIxMethodImp ty method x = do -- TODO: Is this safe? Shouldn't I use x' here? It errors then! Abs decls f <- method <$> simplifiedIxInstance ty let decls' = decls case f of LamExpr fx' fb' -> runSubstReaderT idSubst $ translateDeclNest decls' $ extendSubst (fx'@>SubstVal x) $ translateBlock Nothing fb' intToIndexImp :: (ImpBuilder m, Emits n) => Type n -> IExpr n -> m n (Atom n) intToIndexImp ty i = appSimplifiedIxMethodImp ty simpleUnsafeFromOrdinal =<< toScalarAtom i indexToIntImp :: (ImpBuilder m, Emits n) => Atom n -> m n (IExpr n) indexToIntImp idx = do ty <- getType idx fromScalarAtom =<< appSimplifiedIxMethodImp ty simpleToOrdinal idx indexSetSizeImp :: (ImpBuilder m, Emits n) => Type n -> m n (IExpr n) indexSetSizeImp ty = do fromScalarAtom =<< appSimplifiedIxMethodImp ty simpleIxSize UnitVal -- === type checking imp programs === impFunType :: ImpFunction n -> IFunType impFunType (ImpFunction ty _) = ty impFunType (FFIFunction ty _) = ty getIType :: IExpr n -> IType getIType (ILit l) = litType l getIType (IVar _ ty) = ty impInstrTypes :: EnvReader m => ImpInstr n -> m n [IType] impInstrTypes instr = case instr of IPrimOp op -> return [impOpType op] ICastOp t _ -> return [t] Alloc a ty _ -> return [PtrType (a, ty)] Store _ _ -> return [] Free _ -> return [] IThrowError -> return [] MemCopy _ _ _ -> return [] IFor _ _ _ -> return [] IWhile _ -> return [] ICond _ _ _ -> return [] ILaunch _ _ _ -> return [] ISyncWorkgroup -> return [] IQueryParallelism _ _ -> return [IIdxRepTy, IIdxRepTy] ICall f _ -> do IFunType _ _ resultTys <- impFunType <$> lookupImpFun f return resultTys -- TODO: reuse type rules in Type.hs impOpType :: IPrimOp n -> IType impOpType pop = case pop of ScalarBinOp op x y -> ignoreExcept $ checkBinOp op (getIType x) (getIType y) ScalarUnOp op x -> ignoreExcept $ checkUnOp op (getIType x) VectorBinOp op x y -> ignoreExcept $ checkBinOp op (getIType x) (getIType y) Select _ x _ -> getIType x VectorPack xs -> Vector ty where Scalar ty = getIType $ head xs VectorIndex x _ -> Scalar ty where Vector ty = getIType x PtrLoad ref -> ty where PtrType (_, ty) = getIType ref PtrOffset ref _ -> PtrType (addr, ty) where PtrType (addr, ty) = getIType ref OutputStreamPtr -> hostPtrTy $ hostPtrTy $ Scalar Word8Type where hostPtrTy ty = PtrType (Heap CPU, ty) _ -> unreachable where unreachable = error $ "Not allowed in Imp IR: " ++ show pop instance CheckableE ImpFunction where checkE = substM -- TODO!
google-research/dex-lang
src/lib/Imp.hs
bsd-3-clause
63,217
4
29
15,852
22,760
10,887
11,873
-1
-1
module Main where import qualified Data.Map as Map import REPL main :: IO () main = do putStrLn "Welcome to Erumpo REPL!" repl Map.empty
TerrorJack/erumpo
src/Main.hs
bsd-3-clause
159
0
8
46
44
24
20
6
1
{-| Description : a simple property involving an integral Copyright : (c) Jan Duracz, Michal Konecny License : BSD3 Maintainer : jan@duracz.net Stability : experimental Portability : portable A simple property involving an integral. -} {- There are several ways to invoke PolyPaver on problem defined below: * compile this module and execute it * run the polypaver executable and pass it this file as parameter, eg: polypaver examples/haskell/integral.hs -} module Main where import PolyPaver main = defaultMain problem problem = Problem {box = b ,conjecture = test} b = [(xNum, (0,1), False), (yNum, (0,1), False)] x = termVar xNum "x" y = termVar yNum "y" t = termVar tNum "t" (xNum : yNum : tNum : _) = [0..] test = x + -- /80 + -- uncomment to make it false (y * (y + 2 * x) ) / 2 |<-| -- (plusMinus 0.1) + -- uncomment to make it non-touching integral tNum "t" x (x + y) t
michalkonecny/polypaver
examples/haskell/integral.hs
bsd-3-clause
994
0
12
278
186
108
78
16
1
{-# LANGUAGE ScopedTypeVariables #-} -- | This is a graph widget inspired by the widget of the same name in Awesome -- (the window manager). It plots a series of data points similarly to a bar -- graph. This version must be explicitly fed data with 'graphAddSample'. For a -- more automated version, see "System.Taffybar.Widgets.Generic.PollingGraph". -- -- Like Awesome, this graph can plot multiple data sets in one widget. The data -- sets are plotted in the order provided by the caller. -- -- Note: all of the data fed to this widget should be in the range [0,1]. module System.Taffybar.Widget.Generic.Graph ( -- * Types GraphHandle , GraphConfig(..) , GraphDirection(..) , GraphStyle(..) -- * Functions , graphNew , graphAddSample , defaultGraphConfig ) where import Control.Concurrent import Control.Monad ( when ) import Control.Monad.IO.Class import Data.Default ( Default(..) ) import Data.Foldable ( mapM_ ) import Data.Sequence ( Seq, (<|), viewl, ViewL(..) ) import qualified Data.Sequence as S import qualified Data.Text as T import qualified GI.Cairo.Render as C import GI.Cairo.Render.Connector import qualified GI.Cairo.Render.Matrix as M import qualified GI.Gtk as Gtk import Prelude hiding ( mapM_ ) import System.Taffybar.Util import System.Taffybar.Widget.Util newtype GraphHandle = GH (MVar GraphState) data GraphState = GraphState { graphIsBootstrapped :: Bool , graphHistory :: [Seq Double] , graphCanvas :: Gtk.DrawingArea , graphConfig :: GraphConfig } data GraphDirection = LEFT_TO_RIGHT | RIGHT_TO_LEFT deriving (Eq) -- 'RGBA' represents a color with a transparency. type RGBA = (Double, Double, Double, Double) -- | The style of the graph. Generally, you will want to draw all 'Area' graphs -- first, and then all 'Line' graphs. data GraphStyle = Area -- ^ Thea area below the value is filled | Line -- ^ The values are connected by a line (one pixel wide) -- | The configuration options for the graph. The padding is the number of -- pixels reserved as blank space around the widget in each direction. data GraphConfig = GraphConfig { -- | Number of pixels of padding on each side of the graph widget graphPadding :: Int -- | The background color of the graph (default black) , graphBackgroundColor :: RGBA -- | The border color drawn around the graph (default gray) , graphBorderColor :: RGBA -- | The width of the border (default 1, use 0 to disable the border) , graphBorderWidth :: Int -- | Colors for each data set (default cycles between red, green and blue) , graphDataColors :: [RGBA] -- | How to draw each data point (default @repeat Area@) , graphDataStyles :: [GraphStyle] -- | The number of data points to retain for each data set (default 20) , graphHistorySize :: Int -- | May contain Pango markup (default @Nothing@) , graphLabel :: Maybe T.Text -- | The width (in pixels) of the graph widget (default 50) , graphWidth :: Int -- | The direction in which the graph will move as time passes (default LEFT_TO_RIGHT) , graphDirection :: GraphDirection } defaultGraphConfig :: GraphConfig defaultGraphConfig = GraphConfig { graphPadding = 2 , graphBackgroundColor = (0.0, 0.0, 0.0, 1.0) , graphBorderColor = (0.5, 0.5, 0.5, 1.0) , graphBorderWidth = 1 , graphDataColors = cycle [(1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0)] , graphDataStyles = repeat Area , graphHistorySize = 20 , graphLabel = Nothing , graphWidth = 50 , graphDirection = LEFT_TO_RIGHT } instance Default GraphConfig where def = defaultGraphConfig -- | Add a data point to the graph for each of the tracked data sets. There -- should be as many values in the list as there are data sets. graphAddSample :: GraphHandle -> [Double] -> IO () graphAddSample (GH mv) rawData = do s <- readMVar mv let drawArea = graphCanvas s histSize = graphHistorySize (graphConfig s) histsAndNewVals = zip pcts (graphHistory s) newHists = case graphHistory s of [] -> map S.singleton pcts _ -> map (\(p,h) -> S.take histSize $ p <| h) histsAndNewVals when (graphIsBootstrapped s) $ do modifyMVar_ mv (\s' -> return s' { graphHistory = newHists }) postGUIASync $ Gtk.widgetQueueDraw drawArea where pcts = map (clamp 0 1) rawData clamp :: Double -> Double -> Double -> Double clamp lo hi d = max lo $ min hi d outlineData :: (Double -> Double) -> Double -> Double -> C.Render () outlineData pctToY xStep pct = do (curX,_) <- C.getCurrentPoint C.lineTo (curX + xStep) (pctToY pct) renderFrameAndBackground :: GraphConfig -> Int -> Int -> C.Render () renderFrameAndBackground cfg w h = do let (backR, backG, backB, backA) = graphBackgroundColor cfg (frameR, frameG, frameB, frameA) = graphBorderColor cfg pad = graphPadding cfg fpad = fromIntegral pad fw = fromIntegral w fh = fromIntegral h -- Draw the requested background C.setSourceRGBA backR backG backB backA C.rectangle fpad fpad (fw - 2 * fpad) (fh - 2 * fpad) C.fill -- Draw a frame around the widget area (unless equal to background color, -- which likely means the user does not want a frame) when (graphBorderWidth cfg > 0) $ do let p = fromIntegral (graphBorderWidth cfg) C.setLineWidth p C.setSourceRGBA frameR frameG frameB frameA C.rectangle (fpad + (p / 2)) (fpad + (p / 2)) (fw - 2 * fpad - p) (fh - 2 * fpad - p) C.stroke renderGraph :: [Seq Double] -> GraphConfig -> Int -> Int -> Double -> C.Render () renderGraph hists cfg w h xStep = do renderFrameAndBackground cfg w h C.setLineWidth 0.1 let pad = fromIntegral $ graphPadding cfg let framePad = fromIntegral $ graphBorderWidth cfg -- Make the new origin be inside the frame and then scale the drawing area so -- that all operations in terms of width and height are inside the drawn -- frame. C.translate (pad + framePad) (pad + framePad) let xS = (fromIntegral w - 2 * pad - 2 * framePad) / fromIntegral w yS = (fromIntegral h - 2 * pad - 2 * framePad) / fromIntegral h C.scale xS yS -- If right-to-left direction is requested, apply an horizontal inversion -- transformation with an offset to the right equal to the width of the -- widget. when (graphDirection cfg == RIGHT_TO_LEFT) $ C.transform $ M.Matrix (-1) 0 0 1 (fromIntegral w) 0 let pctToY pct = fromIntegral h * (1 - pct) renderDataSet hist color style | S.length hist <= 1 = return () | otherwise = do let (r, g, b, a) = color originY = pctToY newestSample originX = 0 newestSample :< hist' = viewl hist C.setSourceRGBA r g b a C.moveTo originX originY mapM_ (outlineData pctToY xStep) hist' case style of Area -> do (endX, _) <- C.getCurrentPoint C.lineTo endX (fromIntegral h) C.lineTo 0 (fromIntegral h) C.fill Line -> do C.setLineWidth 1.0 C.stroke sequence_ $ zipWith3 renderDataSet hists (graphDataColors cfg) (graphDataStyles cfg) drawBorder :: MVar GraphState -> Gtk.DrawingArea -> C.Render () drawBorder mv drawArea = do (w, h) <- widgetGetAllocatedSize drawArea s <- liftIO $ readMVar mv let cfg = graphConfig s renderFrameAndBackground cfg w h liftIO $ modifyMVar_ mv (\s' -> return s' { graphIsBootstrapped = True }) return () drawGraph :: MVar GraphState -> Gtk.DrawingArea -> C.Render () drawGraph mv drawArea = do (w, h) <- widgetGetAllocatedSize drawArea drawBorder mv drawArea s <- liftIO $ readMVar mv let hist = graphHistory s cfg = graphConfig s histSize = graphHistorySize cfg -- Subtract 1 here since the first data point doesn't require -- any movement in the X direction xStep = fromIntegral w / fromIntegral (histSize - 1) case hist of [] -> renderFrameAndBackground cfg w h _ -> renderGraph hist cfg w h xStep graphNew :: MonadIO m => GraphConfig -> m (Gtk.Widget, GraphHandle) graphNew cfg = liftIO $ do drawArea <- Gtk.drawingAreaNew mv <- newMVar GraphState { graphIsBootstrapped = False , graphHistory = [] , graphCanvas = drawArea , graphConfig = cfg } Gtk.widgetSetSizeRequest drawArea (fromIntegral $ graphWidth cfg) (-1) _ <- Gtk.onWidgetDraw drawArea $ \ctx -> renderWithContext (drawGraph mv drawArea) ctx >> return True box <- Gtk.boxNew Gtk.OrientationHorizontal 1 Gtk.widgetSetVexpand drawArea True Gtk.widgetSetVexpand box True Gtk.boxPackStart box drawArea True True 0 widget <- case graphLabel cfg of Nothing -> Gtk.toWidget box Just labelText -> do overlay <- Gtk.overlayNew label <- Gtk.labelNew Nothing Gtk.labelSetMarkup label labelText Gtk.containerAdd overlay box Gtk.overlayAddOverlay overlay label Gtk.toWidget overlay Gtk.widgetShowAll widget return (widget, GH mv)
teleshoes/taffybar
src/System/Taffybar/Widget/Generic/Graph.hs
bsd-3-clause
9,225
0
20
2,304
2,365
1,241
1,124
177
2
rotate xs 0 = xs rotate [] _ = [] rotate xs'@(x:xs) n | n < 0 = rotate xs' (length xs' + n) | otherwise = rotate (xs ++ [x]) (n - 1)
bradb/99problems
src/p19.hs
bsd-3-clause
137
0
9
38
101
50
51
5
1
{-# LANGUAGE TemplateHaskell #-} import Data.Generics.TH import Data.String.Utils import Language.Haskell.TH import System.Exit import qualified Data.Set as Set -- This program generates the Data.Generics.TH.VarSet module -- when this module compiles. It is not intended to be run. -- The reason is that Template Haskell can't "reify" under the IO -- monad. Thus we need to be running under GHC's typechecker monad. -- That happens only at compile time. accVarRef :: Exp -> Set.Set Name -> Set.Set Name accVarRef = undefined $(do e <- [d|varSet e = $(everythingForL 'accVarRef [t| Exp |]) e Set.empty|] let fileName = "Data/Generics/TH/VarSet.hs" runIO $ writeFile fileName $ "-- Do not edit. This file is generated by \"util/makeVarSet.hs\".\n" ++ "{-# OPTIONS_GHC -W -Wall #-}\n" ++ "module Data.Generics.TH.VarSet (varSet) where\n" ++ "import Language.Haskell.TH.Syntax\n" ++ "import GHC.Base\n" ++ "import qualified Data.Set as Set\n" ++ "import qualified Data.Maybe\n" ++ "accVarRef :: Exp -> Set.Set Name -> Set.Set Name\n" ++ "accVarRef (VarE n) set = Set.insert n set\n" ++ "accVarRef _ set = set\n" ++ "varSet :: Exp -> Set.Set Name\n" ++ (replace "GHC.Tuple." "" $ replace "GHC.Types." "" $ replace "Main." "" $ replace "Data.Set." "Set." $ (pprint e)) ++ "\n" runIO $ putStrLn $ "Generated " ++ fileName return [] {- Return an empty set of declarations. -}) main = putStrLn "Error: this program is intended to be compiled but not run" >> exitFailure
TomMD/TYB
util/makeVarSet.hs
bsd-3-clause
1,726
29
10
490
237
127
110
31
1
module SLM.Gobble.Gobble where import qualified Data.IntMap as IM import qualified Data.Vector as V import qualified Data.Vector.Mutable as VM import SLM.DataTypes import SLM.Gobble.GobbleDataTypes import SLM.Gobble.GobbleArgs import Control.Applicative import qualified Data.Foldable as F -- PUBLIC INTERFACE gobble :: GobbleArgs -> Bool -> Int -> [[Predictor]] -> [Double] -> [Double] -> GobbleModel gobble args parallel seed xs ys ws = gobbleGobble args parallel seed (map (map (makeGobbleX (bits args))) xs) ys ws -- INTERNAL INTERFACE gobbleGobble :: GobbleArgs -> Bool -> Int -> [[GobbleX]] -> [Double] -> [Double] -> GobbleModel gobbleGobble args parallel seed xs ys ws = F.foldl' f (newGobbleModel (bits args)) xys where xys = zipWith (\x y -> (x,y)) xs ys gradFunc = gobbleGradientLogistic predFunc = gobbleGobblePredictLogistic f inputModel (x,y) = gobbleUpdateOnObs gradFunc predFunc x y inputModel pair :: a -> b -> (a,b) pair x y = (x,y) -- GOBBLE MODEL UPDATE gobbleUpdateOnObs :: GradientFunc -> PredictionFunc -> [GobbleX] -> Double -> GobbleModel -> GobbleModel gobbleUpdateOnObs gradientFunc predictionFunc xs actual inputModel = F.foldl' f inputModel xs where prediction = predictionFunc inputModel xs f model x = gobbleUpdateOnSinglePredictor gradientFunc x actual prediction model alpha = 0.1 power = 0.5 gobbleUpdateOnSinglePredictor :: GradientFunc -> GobbleX -> Double -> Double -> GobbleModel -> GobbleModel gobbleUpdateOnSinglePredictor gradientFunc (GobbleX index x) actual prediction (GobbleModel weightGrads) = GobbleModel (updateWeightGrads weightGrads index newWeightGrad) -- updateGobbleModel inputModel index weightDelta gradientDelta where prevWeightGrad = weightGrads V.! index --IM.findWithDefault (WeightGrad 0.0 0.0) index (weightGrads inputModel) prevSumGradients = 1.0 + (grad prevWeightGrad) gradient = gradientFunc x actual prediction weightDelta = -gradient * alpha / (prevSumGradients ** power) gradientDelta = abs gradient newWeightGrad = incWeightGrad' prevWeightGrad weightDelta gradientDelta -- GOBBLE MODEL newGobbleModel :: Int -> GobbleModel newGobbleModel bits = GobbleModel (V.replicate (2^bits) (WeightGrad 0 0)) data WeightGrad = WeightGrad { weight :: Double , grad :: Double } deriving (Show,Read) incWeightGrad' :: WeightGrad -> Double -> Double -> WeightGrad incWeightGrad' (WeightGrad w1 g1) w2 g2 = WeightGrad (w1+w2) (g1+g2) incWeightGrad :: WeightGrad -> WeightGrad -> WeightGrad incWeightGrad (WeightGrad w1 g1) (WeightGrad w2 g2) = WeightGrad (w1 + w2) (g1 + g2) data GobbleModel = GobbleModel { weightGrads :: !(V.Vector WeightGrad) } deriving (Show,Read) getWeightGrad :: GobbleModel -> Int -> WeightGrad getWeightGrad (GobbleModel wgs) index = wgs V.! index getWeight :: GobbleModel -> Int -> Double getWeight (GobbleModel wgs) index = weight (wgs V.! index) -- (IM.findWithDefault (WeightGrad 0.0 0.0) index (weightGrads model)) -- updateGobbleModel :: GobbleModel -> Int -> Double -> Double -> GobbleModel -- updateGobbleModel (GobbleModel weightGrads) index weightDelta gradDelta = GobbleModel (updateWeightGrads weightGrads index WeightGrad) -- $! (IM.insertWith incWeightGrad index (WeightGrad weightDelta gradDelta) (weightGrads inputModel)) updateWeightGrads :: V.Vector WeightGrad -> Int -> WeightGrad -> V.Vector WeightGrad updateWeightGrads v index w = V.modify (\v -> VM.write v index w) v -- PREDICTION type PredictionFunc = GobbleModel -> [GobbleX] -> Double gobblePredictLogistic :: Int -> GobbleModel -> [Predictor] -> Double gobblePredictLogistic bits model predictors = gobbleGobblePredictLogistic model (map (makeGobbleX bits) predictors) logistic :: Double -> Double logistic z = 1.0 / (1.0 + exp(-z)) inverseLogistic :: Double -> Double inverseLogistic probability = -(log (1.0 / probability - 1)) sum' :: [Double] -> Double sum' xs = F.foldl' (+) 0 xs gobbleGobblePredictLogistic :: GobbleModel -> [GobbleX] -> Double gobbleGobblePredictLogistic model xs = logistic z where weights = map (\x -> getWeight model (xIndex x)) xs xValues = map xValue xs z = sum' ( (*) <$> weights <*> xValues) -- GRADIENTS type GradientFunc = Double -> Double -> Double -> Double gobbleGradientLogistic :: Double -> Double -> Double -> Double gobbleGradientLogistic x actual prediction = (-1) * x * (actual * (actual - prediction) + (1 - actual) * (actual - (1 - prediction)))
timveitch/Gobble
src/SLM/Gobble/Gobble.hs
bsd-3-clause
4,484
0
13
740
1,330
717
613
71
1
module Network.Punch.Peer.Reliable.Types where import Control.Applicative ((<$>), (<*>)) import Control.Concurrent.MVar import Control.Concurrent.Async (Async, async) import Control.Concurrent.STM (STM, TVar) import Control.DeepSeq (NFData, rnf) import qualified Data.ByteString as B import qualified Data.Serialize as S import Data.Time import Data.Bits (testBit, setBit, clearBit) import qualified Data.Map as M import Data.Data (Data) import Data.Typeable (Typeable) import qualified Pipes.Concurrent as P import Text.Printf (printf) -- This should of course be more low-level (like a c-struct). -- However it seems that the strictness annotations in this type seems to -- be not affecting the performance.. data Packet = Packet { pktSeqNo :: !Int, -- ^ DATA packets use it as the sequence No., -- while DATA_ACK packets use it as the acknowledgement No. pktFlags :: ![PacketFlag], -- ^ Bit flags pktPayload :: !B.ByteString -- ^ Currently only valid for DATA packets } deriving (Show, Typeable, Data) -- ^ Invariant: serialized form takes <= 512 bytes. -- That is, payload should be <= 480 bytes. showPacket :: Packet -> String showPacket pkt@(Packet {..}) = printf "<Packet %-5d, %-10s, %5d bytes>" pktSeqNo (show pktFlags) (B.length pktPayload) -- | For the strict map instance NFData Packet where rnf x = x `seq` () data PacketFlag = ACK -- ^ Acks a previously received DATA / FIN packet. | DATA -- ^ Contains a valid payload. Expects a DATA-ACK reply. | FIN -- ^ Starts shutdown, expects a FIN-ACK reply | RST -- ^ Hard reset. deriving (Show, Eq, Ord, Enum, Bounded, Typeable, Data) data ConnOption = ConnOption { optDefaultBackOff :: Int -- ^ In micros , optMaxRetries :: Int , optMaxPayloadSize :: Int , optMaxUnackedPackets :: Int -- ^ Used to avoid congestion , optTxBufferSize :: Int -- ^ Size of the fromApp mailbox size , optRxBufferSize :: Int -- ^ Size of the toApp mailbox size } newtype Mailbox a = Mailbox (P.Output a, P.Input a, STM ()) -- XXX: Shall we call some of them `control blocks` instead? type OutputQueue = M.Map Int Packet type DeliveryQueue = M.Map Int B.ByteString type ResendQueue = M.Map (UTCTime, Int) (Int, Int) -- ^ (resend-time, DATA-seq) => (next-backoff-micros, n-retries) data RcbState = RcbOpen | RcbFinSent | RcbCloseWait | RcbClosed deriving (Show, Eq) data CloseReason = PeerClosed | TooManyRetries | GracefullyShutdown | AlreadyClosed deriving (Show, Eq, Ord, Typeable) -- | Reliable Control Block data Rcb = Rcb { rcbConnOpt :: ConnOption , rcbFromNic :: Mailbox Packet , rcbToNic :: Mailbox Packet , rcbFromApp :: Mailbox (Int, B.ByteString) -- ^ (SeqNo, Payload) -- We link the seqNo early since this makes FIN handling easier. , rcbToApp :: Mailbox B.ByteString -- ^ Used to track the current number of unacked packets. , rcbState :: TVar RcbState , rcbSeqGen :: TVar Int , rcbFinSeq :: TVar Int -- ^ Only available when entering the CloseWait state. -- This is the last DATA seq that we are going to receive. , rcbLastDeliverySeq :: TVar Int -- ^ In case this is connected to any other pipes , rcbOutputQ :: TVar OutputQueue , rcbDeliveryQ :: TVar DeliveryQueue , rcbResendQ :: TVar ResendQueue -- ^ A priority-queue like for the timer thread to use , rcbExtraFinalizers :: TVar [IO ()] } type RcbRef = Rcb -- Serialization putPacket :: Packet -> S.Put putPacket (Packet {..}) = do S.put pktSeqNo S.put $ foldFlags pktFlags S.put pktPayload getPacket :: S.Get Packet getPacket = Packet <$> S.get <*> (unfoldFlags <$> S.get) <*> S.get foldFlags :: Enum a => [a] -> Int foldFlags = foldr (flip setFlag) 0 unfoldFlags :: (Bounded a, Enum a) => Int -> [a] unfoldFlags flag = concatMap check [minBound..maxBound] where check a = if hasFlag flag a then [a] else [] hasFlag :: Enum a => Int -> a -> Bool hasFlag flag a = testBit flag (fromEnum a) setFlag :: Enum a => Int -> a -> Int setFlag flag a = setBit flag (fromEnum a) delFlag :: Enum a => Int -> a -> Int delFlag flag a = clearBit flag (fromEnum a) -- Util
overminder/punch-forward
src/Network/Punch/Peer/Reliable/Types.hs
bsd-3-clause
4,161
0
12
858
1,026
588
438
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.NV.FramebufferMixedSamples -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/NV/framebuffer_mixed_samples.txt NV_framebuffer_mixed_samples> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.NV.FramebufferMixedSamples ( -- * Enums gl_COLOR_SAMPLES_NV, gl_COVERAGE_MODULATION_NV, gl_COVERAGE_MODULATION_TABLE_NV, gl_COVERAGE_MODULATION_TABLE_SIZE_NV, gl_DEPTH_SAMPLES_NV, gl_EFFECTIVE_RASTER_SAMPLES_EXT, gl_MAX_RASTER_SAMPLES_EXT, gl_MIXED_DEPTH_SAMPLES_SUPPORTED_NV, gl_MIXED_STENCIL_SAMPLES_SUPPORTED_NV, gl_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT, gl_RASTER_FIXED_SAMPLE_LOCATIONS_EXT, gl_RASTER_MULTISAMPLE_EXT, gl_RASTER_SAMPLES_EXT, gl_STENCIL_SAMPLES_NV, -- * Functions glCoverageModulationNV, glCoverageModulationTableNV, glGetCoverageModulationTableNV, glRasterSamplesEXT ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/NV/FramebufferMixedSamples.hs
bsd-3-clause
1,301
0
4
136
97
72
25
21
0
{-# LANGUAGE PatternSynonyms, ViewPatterns #-} module Text.Yapan.Patterns (pattern Block, pattern Inline, pattern Str, pattern Emph, pattern Header) where import Text.Yapan.Base import Data.OpenUnion2 pattern Block a <- Block' (prj -> Just a) pattern Inline a <- Inline' (prj -> Just a) pattern Str s <- Inline (Str' s) pattern Emph e <- Inline (Emph' e) pattern Header i hs <- Block (Header' i hs)
konn/yapan
src/Text/Yapan/Patterns.hs
bsd-3-clause
445
0
9
109
158
80
78
14
0
{-#LANGUAGE FlexibleInstances, GADTs, TypeFamilies, UndecidableInstances, TypeOperators, DataKinds, KindSignatures, ScopedTypeVariables, PolyKinds #-} import Text.APEG.Syntax.APEGSyn import qualified Text.APEG.Semantics.APEGSem as Sem import Control.Applicative import Data.Char import Data.Proxy import Data.Singletons.Prelude import Data.Singletons.Prelude.List foo :: PExp '[ '("a", Bool), '("b", Char)] () foo = Set (sing :: Sing "a") True foo' :: PExp '[ '("a", Bool), '("b", Char)] () foo' = Set (sing :: Sing "b") 'a' mytest1 :: APEG '[ '("a", Bool), '("b", Char)] Char mytest1 = APEG (((\_ _ c -> c) <$> foo <*> foo' <*> Get (sing :: Sing "b"))) -- more tests digit :: PExp env Char digit = Sat isDigit number :: PExp env Int number = f <$> Star digit where f = foldl (\a b -> a * 10 + b) 0 . map g g c = ord c - ord '0' pb :: PExp '[ '("x0", Int), '("x1", Int)] () pb = pz <|> po where pz, po :: PExp '[ '("x0", Int), '("x1", Int)] () pz = char '0' *> (set (sing :: Sing "x1") 1) po = char '1' *> (set (sing :: Sing "x1") 1) char c = sat (c ==) pt :: PExp '[ '("x0", Int), '("x1", Int)] () pt = pb <*> get (sing :: Sing "x0") <*> star pb ps :: PExp '[ '("x0", Int), '("x1", Int)] () ps = pt main :: IO () main = do let (r,att) = Sem.runAPEG mytest1 "ab" putStrLn $ show att print r
lives-group/haskell-APEG
test/Spec.hs
bsd-3-clause
1,616
12
12
566
704
371
333
44
1
module Collatz.Plain where -- $Id$ import qualified Collatz.Parameter as P import Collatz.Config import Collatz.Roll import Inter.Types import Inter.Quiz import Autolib.ToDoc import Autolib.Hash import Autolib.Util.Seed import qualified Challenger as C import Data.Typeable import Autolib.Reporter data Collatz_Plain = Collatz_Plain deriving ( Eq, Ord, Show, Read, Typeable ) instance OrderScore Collatz_Plain where scoringOrder _ = None instance C.Partial Collatz_Plain Integer P.Parameter where report Collatz_Plain x = do inform $ vcat [ text "Gesucht sind Länge und maximales Element" , text "der Collatz-Folge mit Startzahl" <+> toDoc x ] initial Collatz_Plain x = P.one total Collatz_Plain x p = do assert ( p == P.compute x ) $ text "angegebene Parameter sind korrekt?" instance C.Measure Collatz_Plain Integer P.Parameter where measure _ _ _ = 1 make :: Make make = direct Collatz_Plain ( 27 :: Integer ) instance Generator Collatz_Plain Config ( Integer, P.Parameter ) where generator p conf key = do seed $ fromIntegral $ hash $ reverse key roll conf instance Project Collatz_Plain ( Integer, P.Parameter ) Integer where project p ( i, _ ) = i qmake :: Make qmake = quiz Collatz_Plain rc
florianpilz/autotool
src/Collatz/Plain.hs
gpl-2.0
1,296
3
14
280
377
199
178
-1
-1
commented = commented -- ^comment 0 -- |comment 1
evolutics/haskell-formatter
testsuite/resources/source/comments/keeps_comments_at_bounds_of_file/end/Output.hs
gpl-3.0
51
0
4
10
8
5
3
1
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="pt-BR"> <title>Regras de varredura passiva - Beta | Extensão ZAP</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Conteúdo</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Índice</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Localizar</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoritos</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/pscanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesBeta/resources/help_pt_BR/helpset_pt_BR.hs
apache-2.0
1,002
90
29
164
413
219
194
-1
-1
{- Copyright 2012-2013 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# Language FlexibleContexts, TypeFamilies #-} {-| This module represents the low level Posix interface. It is mostly a re-export of the interface from the System.Posix module tree. However, all operations in IO are instead exported as versions in (PosixIO m) => m. This enables code to be written to this Posix interface, but then be run in either IO, or in other monads that offer the implementation of Posix, but perhaps, don't actually affect the underlying system. See TestExec. -} module Plush.Run.Posix ( -- * PosixLike monad PosixLike(..), PosixLikeFileStatus(..), -- * Misc -- ** stdJson stdJsonInput, stdJsonOutput, -- * Re-exports -- ** from System.Posix.Types module System.Posix.Types, -- ** from System.Posix.Files stdFileMode, accessModes, -- ** from System.Posix.IO stdInput, stdOutput, stdError, OpenMode(..), OpenFileFlags(..), defaultFileFlags, ) where import Control.Monad.Exception (MonadException) import qualified Data.ByteString.Lazy as L import System.Exit import System.Posix.Files (stdFileMode, accessModes) import System.Posix.IO (stdInput, stdOutput, stdError, OpenMode(..), OpenFileFlags(..), defaultFileFlags) import System.Posix.Types import Plush.Run.Types -- | The low-level operations that make up the Posix interface. -- -- Where named the same as a function in 'System.Posix', see that module for -- documentation. A few operations here are slightly higher, and replace the -- lower level primitives. These are documented here. -- -- These are just the operations needed to implement the shell command language -- and the built-in commands. The shell can operate entirely within a monad -- of this class. See 'TextExec' for one such monad. 'IO' is another. class (Functor m, Monad m, MonadException m, PosixLikeFileStatus (FileStatus m)) => PosixLike m where -- from System.Posix.Directory createDirectory :: FilePath -> FileMode -> m () removeDirectory :: FilePath -> m () -- | Return the entries in a directory, including "." and "..". -- This replaces 'openDirStream' & family, since this is the only use anyone -- ever makes of those functions. getDirectoryContents :: FilePath -> m [FilePath] getWorkingDirectory :: m FilePath changeWorkingDirectory :: FilePath -> m () -- from System.Posix.Env getInitialEnvironment :: m Bindings -- from System.Posix.Files -- | Type of file status values used with an instance of PosixLike type FileStatus m :: * getFileStatus :: FilePath -> m (FileStatus m) getSymbolicLinkStatus :: FilePath -> m (FileStatus m) isExecutable :: FilePath -> m Bool removeLink :: FilePath -> m () setFileTimes :: FilePath -> EpochTime -> EpochTime -> m () touchFile :: FilePath -> m () -- From System.Posix.IO openFd :: FilePath -> OpenMode -> Maybe FileMode -> OpenFileFlags -> m Fd createFile :: FilePath -> FileMode -> m Fd closeFd :: Fd -> m () dupTo :: Fd -> Fd -> m () dupFdCloseOnExec :: Fd -> Fd -> m Fd setCloseOnExec :: Fd -> m () -- ^ Convenience @setCloseOnExec fd -> 'setFdOption' fd 'CloseOnExec' 'True'@ -- | Read all the available input. If the input is a seekable stream, it -- is rewound to the begining, first. Simply returns an empty result if -- the stream is empty. readAll :: Fd -> m L.ByteString -- | Read until the next newline, if any. The newline is included in the -- result. The 'Bool' return value indicates if EOF or other error was -- encountered while reading. -- This operation is on an 'Fd' and so in very inefficient, and may not work -- n pipes correctly. Use sparingly. readLine :: Fd -> m (Bool, L.ByteString) -- | Write to an output. If the output is a seekable stream, it is seeked -- to the end. write :: Fd -> L.ByteString -> m () -- From System.Posix.User -- | A safe lookup of home directory info. See `getUserEntryForName`. getUserHomeDirectoryForName :: String -> m (Maybe FilePath) -- | A check for possibly elivated privledges. Checks that for both the -- user IDs and group IDs, the real and effective versions match. -- See §2.5.3 realAndEffectiveIDsMatch :: m Bool -- From System.Process getProcessID :: m Int execProcess :: FilePath -- ^ Path to exec -> Bindings -- ^ Environment variable bindings -> String -- ^ Command name -> [String] -- ^ Arguments -> m ExitCode -- | Run a computation, and returning what it wrote to stdout captureStdout :: m ExitCode -> m (ExitCode, L.ByteString) -- | A high level primitive that runs each computation in an environment -- with the stdout of each piped to the stdin of next. The original stdin -- is piped to the first, and the stdout of the last is the original stdout. pipeline :: [m ExitCode] -> m ExitCode -- | A high level primitive that returns an open Fd that when read will -- supply the content given. contentFd :: L.ByteString -> m Fd -- | File status data as returned by 'getFileStatus' and 'getSymbolicLinkStatus' class PosixLikeFileStatus s where accessTime :: s -> EpochTime modificationTime :: s -> EpochTime isRegularFile :: s -> Bool isDirectory :: s -> Bool isSymbolicLink :: s -> Bool stdJsonInput, stdJsonOutput :: Fd stdJsonInput = Fd 3 stdJsonOutput = Fd 4
mzero/plush
src/Plush/Run/Posix.hs
apache-2.0
6,087
0
11
1,376
785
455
330
61
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} module RecordSumOfProducts where import CLaSH.Prelude import Control.Applicative data DbState = DbInitDisp (Unsigned 4) | DbWriteRam (Signed 14) (Signed 14) | DbDone deriving (Show, Eq) data DbS = DbS { dbS :: DbState } topEntity = walkState <^> DbS (DbInitDisp 0) walkState :: DbS -> Bit -> (DbS, Bit) walkState (DbS (DbInitDisp n )) i = (DbS (DbInitDisp (n+1) ), 0) walkState s i = (s , i)
ggreif/clash-compiler
tests/shouldwork/Basic/RecordSumOfProducts.hs
bsd-2-clause
546
0
10
169
176
98
78
15
1