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 : Data.Functor.Constant -- Copyright : (c) Ross Paterson 2010 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ross@soi.city.ac.uk -- Stability : experimental -- Portability : portable -- -- The constant functor. module Data.Functor.Constant ( Constant(..), ) where import Control.Applicative import Data.Foldable (Foldable(foldMap)) import Data.Monoid (Monoid(..)) import Data.Traversable (Traversable(traverse)) -- | Constant functor. newtype Constant a b = Constant { getConstant :: a } instance Functor (Constant a) where fmap f (Constant x) = Constant x instance Foldable (Constant a) where foldMap f (Constant x) = mempty instance Traversable (Constant a) where traverse f (Constant x) = pure (Constant x) instance (Monoid a) => Applicative (Constant a) where pure _ = Constant mempty Constant x <*> Constant y = Constant (x `mappend` y)
technogeeky/d-A
src/Data/Functor/d-Constant.hs
gpl-3.0
929
0
8
184
255
145
110
16
0
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="en-GB"> <title>Script Console</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>
zapbot/zap-extensions
addOns/scripts/src/main/javahelp/org/zaproxy/zap/extension/scripts/resources/help/helpset.hs
apache-2.0
972
81
67
169
417
213
204
-1
-1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module Wrap0 () where import Language.Haskell.Liquid.Prelude (liquidError, liquidAssertB) import Data.Function (on) import Data.Ord (comparing) data WrapType b a = WrapType {getVect :: b, getVal :: a} instance Eq (WrapType [Double] a) where (==) = (==) `on` getVect instance Ord (WrapType [Double] a) where compare = comparing getVect {-@ assert flibXs :: a -> Bool @-} flibXs x = prop1 (WrapType [x, x, x] x) prop1 (WrapType [] _) = liquidError "no!" prop1 (WrapType _ _) = True {-@ assert nflibXs :: Int -> a -> Bool @-} nflibXs n x = prop2 n (WrapType nxs x) where nxs = replicate n x prop2 n (WrapType xs _) = liquidAssertB (n > length xs)
mightymoose/liquidhaskell
tests/neg/wrap1.hs
bsd-3-clause
772
0
8
189
260
145
115
16
1
{-# LANGUAGE CPP #-} {-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, TemplateHaskell #-} module Data.TarIndex ( TarIndex, TarIndexEntry(..), TarEntryOffset, lookup, construct, #ifdef TESTS prop_lookup, prop, #endif ) where import Data.SafeCopy (base, deriveSafeCopy) import Data.Typeable (Typeable) import Codec.Archive.Tar (Entry(..), EntryContent(..), Entries(..), entryPath) import qualified Data.StringTable as StringTable import Data.StringTable (StringTable) import qualified Data.IntTrie as IntTrie import Data.IntTrie (IntTrie) import qualified System.FilePath.Posix as FilePath import Prelude hiding (lookup) #ifdef TESTS import qualified Prelude #endif import Distribution.Server.Framework.MemSize -- | An index of the entries in a tar file. This lets us look up a filename -- within the tar file and find out where in the tar file (ie the file offset) -- that entry occurs. -- data TarIndex = TarIndex -- As an example of how the mapping works, consider these example files: -- "foo/bar.hs" at offset 0 -- "foo/baz.hs" at offset 1024 -- -- We split the paths into components and enumerate them. -- { "foo" -> TokenId 0, "bar.hs" -> TokenId 1, "baz.hs" -> TokenId 2 } -- -- We convert paths into sequences of 'TokenId's, i.e. -- "foo/bar.hs" becomes [PathComponentId 0, PathComponentId 1] -- "foo/baz.hs" becomes [PathComponentId 0, PathComponentId 2] -- -- We use a trie mapping sequences of 'PathComponentId's to the entry offset: -- { [PathComponentId 0, PathComponentId 1] -> offset 0 -- , [PathComponentId 0, PathComponentId 2] -> offset 1024 } -- | The mapping of filepath components as strings to ids. !(StringTable PathComponentId) -- Mapping of sequences of filepath component ids to tar entry offsets. !(IntTrie PathComponentId TarEntryOffset) deriving (Show, Typeable) data TarIndexEntry = TarFileEntry !TarEntryOffset | TarDir [(FilePath, TarIndexEntry)] deriving (Show, Typeable) newtype PathComponentId = PathComponentId Int deriving (Eq, Ord, Enum, Show, Typeable) type TarEntryOffset = Int $(deriveSafeCopy 0 'base ''TarIndex) $(deriveSafeCopy 0 'base ''PathComponentId) $(deriveSafeCopy 0 'base ''TarIndexEntry) instance MemSize TarIndex where memSize (TarIndex a b) = memSize2 a b -- | Look up a given filepath in the index. It may return a 'TarFileEntry' -- containing the offset and length of the file within the tar file, or if -- the filepath identifies a directory then it returns a 'TarDir' containing -- the list of files within that directory. -- lookup :: TarIndex -> FilePath -> Maybe TarIndexEntry lookup (TarIndex pathTable pathTrie) path = do fpath <- toComponentIds pathTable path tentry <- IntTrie.lookup pathTrie fpath return (mkIndexEntry tentry) where mkIndexEntry (IntTrie.Entry offset) = TarFileEntry offset mkIndexEntry (IntTrie.Completions entries) = TarDir [ (fromComponentId pathTable key, mkIndexEntry entry) | (key, entry) <- entries ] data IndexBuilder = IndexBuilder [(FilePath, TarEntryOffset)] {-# UNPACK #-} !TarEntryOffset initialIndexBuilder :: IndexBuilder initialIndexBuilder = IndexBuilder [] 0 accumIndexBuilder :: Entry -> IndexBuilder -> IndexBuilder accumIndexBuilder entry (IndexBuilder acc nextOffset) = IndexBuilder ((entryPath entry, nextOffset):acc) nextOffset' where nextOffset' = nextOffset + 1 + case entryContent entry of NormalFile _ size -> blocks size OtherEntryType _ _ size -> blocks size _ -> 0 blocks size = 1 + ((fromIntegral size - 1) `div` 512) finaliseIndexBuilder :: IndexBuilder -> TarIndex finaliseIndexBuilder (IndexBuilder pathsOffsets _) = TarIndex pathTable pathTrie where pathComponents = concatMap (FilePath.splitDirectories . fst) pathsOffsets pathTable = StringTable.construct pathComponents pathTrie = IntTrie.construct [ (cids, offset) | (path, offset) <- pathsOffsets , let Just cids = toComponentIds pathTable path ] -- | Construct a 'TarIndex' from a sequence of tar 'Entries'. The 'Entries' are -- assumed to start at offset @0@ within a file. -- construct :: Entries e -> Either e TarIndex construct = go initialIndexBuilder where go builder (Next e es) = go (accumIndexBuilder e builder) es go builder Done = Right $! finaliseIndexBuilder builder go _ (Fail err) = Left err toComponentIds :: StringTable PathComponentId -> FilePath -> Maybe [PathComponentId] toComponentIds table = lookupComponents [] . FilePath.splitDirectories where lookupComponents cs' [] = Just (reverse cs') lookupComponents cs' (c:cs) = case StringTable.lookup table c of Nothing -> Nothing Just cid -> lookupComponents (cid:cs') cs fromComponentId :: StringTable PathComponentId -> PathComponentId -> FilePath fromComponentId table = StringTable.index table #ifdef TESTS -- properties of a finite mapping... prop_lookup :: [(FilePath, TarEntryOffset)] -> FilePath -> Bool prop_lookup xs x = case (lookup (construct xs) x, Prelude.lookup x xs) of (Nothing, Nothing) -> True (Just (TarFileEntry offset), Just offset') -> offset == offset' _ -> False prop :: [(FilePath, TarEntryOffset)] -> Bool prop paths | not $ StringTable.prop pathbits = error "TarIndex: bad string table" | not $ IntTrie.prop intpaths = error "TarIndex: bad int trie" | not $ prop' = error "TarIndex: bad prop" | otherwise = True where index@(TarIndex pathTable _) = construct paths pathbits = concatMap (FilePath.splitDirectories . fst) paths intpaths = [ (cids, offset) | (path, offset) <- paths , let Just cids = toComponentIds pathTable path ] prop' = flip all paths $ \(file, offset) -> case lookup index file of Just (TarFileEntry offset') -> offset' == offset _ -> False example0 :: [(FilePath, Int)] example0 = [("foo-1.0/foo-1.0.cabal", 512) -- tar block 1 ,("foo-1.0/LICENSE", 2048) -- tar block 4 ,("foo-1.0/Data/Foo.hs", 4096)] -- tar block 8 #endif
ocharles/hackage-server
Data/TarIndex.hs
bsd-3-clause
6,444
0
14
1,531
1,451
783
668
83
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -Wno-name-shadowing #-} -- The code in Java here has been copied from the benchmark wizzardo-http -- in -- https://github.com/TechEmpower/FrameworkBenchmarks/blob/master/frameworks/wizzardo-http module DbHandler (createDbHandler) where import Control.Monad.IO.Class.Linear (MonadIO) import qualified Control.Monad.Linear.Builder as Linear import Data.Aeson (ToJSON(..), encode, object, (.=)) import Data.ByteString.Lazy (toStrict) import Data.Int (Int32) import Data.String (fromString) import Foreign.JNI.Safe (newGlobalRef_) import qualified Language.Java as NonLinear import Language.Java.Inline.Safe import Language.Java.Function (createIntIntToObjFunction) import Language.Java.Safe (J, JType(..), type (<>)) import Wizzardo.Http.Handler (JHandler, createHandler) import Prelude (IO, Show, fromInteger, ($)) import Prelude.Linear (Unrestricted(..)) import qualified System.IO.Linear as Linear imports "java.util.concurrent.ThreadLocalRandom" imports "com.wizzardo.epoll.*" imports "com.wizzardo.http.*" imports "com.wizzardo.http.framework.*" imports "com.wizzardo.http.request.*" imports "com.wizzardo.http.response.*" imports "io.reactiverse.pgclient.*" imports "io.reactiverse.pgclient.impl.*" createDbHandler :: MonadIO m => m JHandler createDbHandler = let Linear.Builder{..} = Linear.monadBuilder in do encodeDbResponse <- createIntIntToObjFunction encodeDbResponseAsJSON Unrestricted jGlobalEncodeDbResponse <- newGlobalRef_ encodeDbResponse byteBufferProviderThreadLocal <- createThreadLocalByteBufferProvider Unrestricted jGlobalByteBufferProviderThreadLocal <- newGlobalRef_ byteBufferProviderThreadLocal poolRef <- createPgPoolRef Unrestricted jGlobalPoolRef <- newGlobalRef_ poolRef createHandler $ \req resp -> Linear.withLinearIO $ do let uPoolRef = Unrestricted jGlobalPoolRef uByteBufferProviderThreadLocal = Unrestricted jGlobalByteBufferProviderThreadLocal uEncodeDbResponse = Unrestricted jGlobalEncodeDbResponse [java| { int genWorldId = 1 + ThreadLocalRandom.current().nextInt(10000); $resp.async(); $uPoolRef.get().preparedQuery("SELECT * FROM World WHERE id=$1", Tuple.of(genWorldId), dbRes -> { if (dbRes.succeeded()) { PgIterator resultSet = dbRes.result().iterator(); if (!resultSet.hasNext()) { $resp.status(Status._404); } else { Tuple row = resultSet.next(); $resp.appendHeader(Header.KV_CONTENT_TYPE_APPLICATION_JSON); $resp.setBody($uEncodeDbResponse.apply(row.getInteger(0), row.getInteger(1))); } } else { dbRes.cause().printStackTrace(); $resp.status(Status._500).body(dbRes.cause().getMessage()); } // commit async response ByteBufferProvider bufferProvider = $uByteBufferProviderThreadLocal.get(); HttpConnection connection = $req.connection(); $resp.commit(connection, bufferProvider); connection.flush(bufferProvider); $resp.reset(); }); } |] return (Unrestricted ()) data World = World { worldId :: Int32, worldRandomNumber :: Int32 } deriving Show instance ToJSON World where toJSON w = object ["id" .= worldId w, "randomNumber" .= worldRandomNumber w] createThreadLocalByteBufferProvider :: MonadIO m => m (J ('Class "java.lang.ThreadLocal" <> '[ 'Iface "com.wizzardo.epoll.ByteBufferProvider"] ) ) createThreadLocalByteBufferProvider = [java| new ThreadLocal<ByteBufferProvider>() { @Override public ByteBufferProvider initialValue() { ByteBufferWrapper wrapper = new ByteBufferWrapper(64 * 1024); return () -> wrapper; } } |] createPgPoolRef :: MonadIO m => m (J ('Class "java.lang.ThreadLocal" <> '[ 'Class "io.reactiverse.pgclient.PgPool"])) createPgPoolRef = [java| new ThreadLocal() { @Override public PgPool initialValue() { WizzardoPgPoolOptions options = new WizzardoPgPoolOptions(); options.setDatabase("hello_world"); options.setHost("tfb-database"); options.setPort(5432); options.setUser("benchmarkdbuser"); options.setPassword("benchmarkdbpass"); options.setCachePreparedStatements(true); options.setMaxSize(1); return new WizzardoPgPool(options); } } |] encodeDbResponseAsJSON :: Int32 -> Int32 -> IO (NonLinear.J ('Array ('Prim "byte"))) encodeDbResponseAsJSON rowId rowRandomInt = NonLinear.reflect $ toStrict $ encode $ World rowId rowRandomInt
greenlaw110/FrameworkBenchmarks
frameworks/Haskell/wizzardo-inline/wizzardo-http-benchmark/src/main/haskell/DbHandler.hs
bsd-3-clause
5,006
0
17
991
677
371
306
-1
-1
module ShouldFail where class Foo o where (:+) :: o -> o -> o
ryantm/ghc
testsuite/tests/parser/should_fail/readFail031.hs
bsd-3-clause
69
4
5
21
29
16
13
-1
-1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Sindre.Lib -- License : MIT-style (see LICENSE) -- -- Stability : provisional -- Portability : portable -- -- Library routines and helper functions for the Sindre programming -- language. -- ----------------------------------------------------------------------------- module Sindre.Lib ( stdFunctions , ioFunctions , ioGlobals , LiftFunction(..) , KeyLike(..) ) where import Sindre.Sindre import Sindre.Compiler import Sindre.Runtime import Sindre.Util import System.Environment import System.Exit import System.IO import System.Process hiding (env) import Text.Regex.PCRE import Control.Monad import Control.Monad.Trans import Data.Char import Data.List import qualified Data.Map as M import qualified Data.Set as S lengthFun :: Value -> Integer lengthFun (Dict m) = fi $ M.size m lengthFun v = maybe 0 genericLength (mold v :: Maybe String) builtin :: LiftFunction im m a => a -> Compiler im ([Value] -> m im Value) builtin f = return $ function f -- | A set of pure functions that can work with any Sindre backend. -- Includes the functions @abs@, @atan2@, @cos@, @sin@, @exp@, @log@, -- @int@, @sqrt@, @length@, @substr@, @index@, @match@, @sub@, @gsub@, -- @tolower@, and @toupper@. stdFunctions :: forall im. MonadBackend im => FuncMap im stdFunctions = M.fromList [ ("abs" , builtin $ return' . (abs :: Int -> Int)) , ("atan2", builtin $ \(x::Double) (y::Double) -> return' $ atan2 x y) , ("cos", builtin $ return' . (cos :: Double -> Double)) , ("sin", builtin $ return' . (sin :: Double -> Double)) , ("exp", builtin $ return' . (exp :: Double -> Double)) , ("log", builtin $ return' . (log :: Double -> Double)) , ("int", builtin $ return' . (floor :: Double -> Integer)) , ("sqrt", builtin $ return' . (sqrt :: Double -> Double)) , ("length", builtin $ return' . lengthFun) , ("substr", builtin $ \(s::String) m n -> return' $ take n $ drop (m-1) s) , ("index", builtin $ \(s::String) t -> return' $ maybe 0 (1+) $ findIndex (isPrefixOf t) $ tails s) , ("match", do rstart <- setValue "RSTART" rlength <- setValue "RLENGTH" return $ function $ \(s::String) (r::String) -> do let (stt, len) = s =~ r :: (Int, Int) execute_ $ do rstart $ unmold (stt+1) rlength $ unmold len return' $ unmold (stt+1)) , ("sub", builtin sub) , ("gsub", builtin gsub) , ("tolower", builtin $ return' . map toLower) , ("toupper", builtin $ return' . map toUpper) ] where return' :: Mold a => a -> Sindre im a return' = return sub (r::String) t (s::String) = case s =~ r of (-1,_) -> return' s (i,n) -> return' $ take i s ++ t ++ drop (i+n) s gsub (r::String) t (s::String) = case s =~ r of (-1,_) -> return' s (i,n) -> do s' <- gsub r t $ drop (i+n) s return' $ take i s ++ t ++ s' -- | A set of impure functions that only work in IO backends. -- Includes the @system@ function. ioFunctions :: (MonadIO m, MonadBackend m) => FuncMap m ioFunctions = M.fromList [ ("system", do exitval <- setValue "EXITVAL" builtin $ \s -> do c <- io $ system s let v = case c of ExitSuccess -> 0 ExitFailure e -> e execute_ $ exitval $ unmold v return' v) , ("osystem", do exitval <- setValue "EXITVAL" return $ function $ \s -> do (Just inh, Just outh, _, pid) <- io $ createProcess (shell s) { std_in = CreatePipe, std_out = CreatePipe, std_err = Inherit } io $ hClose inh output <- io $ hGetContents outh ex <- io $ waitForProcess pid execute_ $ exitval $ unmold $ case ex of ExitSuccess -> 0 ExitFailure r -> r return' output) ] where return' :: Mold a => a -> Sindre im a return' = return -- | Global variables that require an IO backend. Includes the -- @ENVIRON@ global. ioGlobals :: MonadIO im => M.Map Identifier (im Value) ioGlobals = M.fromList [("ENVIRON", do env <- io getEnvironment let f (k, s) = (unmold k, unmold s) return $ Dict $ M.fromList $ map f env) ] -- | A class making it easy to adapt Haskell functions as Sindre -- functions that take and return 'Value's. class (MonadBackend im, MonadSindre im m) => LiftFunction im m a where function :: a -> [Value] -> m im Value -- ^ @function f@ is a monadic function that accepts a list of -- 'Value's and returns a 'Value'. If the list does not contain the -- number, or type, of arguments expected by @f@, 'fail' will be -- called with an appropriate error message. instance (Mold a, MonadSindre im m) => LiftFunction im m (m im a) where function x [] = liftM unmold x function _ _ = fail "Too many arguments" instance (Mold a, LiftFunction im m b, MonadSindre im m) => LiftFunction im m (a -> b) where function f (x:xs) = case mold x of Nothing -> fail "Cannot mold argument" Just x' -> f x' `function` xs function _ [] = fail "Not enough arguments" -- | Convenience class for writing 'Chord' values. class KeyLike a where chord :: [KeyModifier] -> a -> Chord -- ^ Given a list of modifiers and either a 'char' or a 'String', -- yield a 'Chord'. If given a character, the Chord will contain a -- 'CharKey', if given a string, it will contain a 'CtrlKey'. instance KeyLike Char where chord ms c = (S.fromList ms, CharKey c) instance KeyLike String where chord ms s = (S.fromList ms, CtrlKey s)
Athas/Sindre
Sindre/Lib.hs
mit
6,827
0
20
2,445
1,846
984
862
117
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-sqlapplicationconfiguration.html module Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationSqlApplicationConfiguration where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationInput -- | Full data type definition for -- KinesisAnalyticsV2ApplicationSqlApplicationConfiguration. See -- 'kinesisAnalyticsV2ApplicationSqlApplicationConfiguration' for a more -- convenient constructor. data KinesisAnalyticsV2ApplicationSqlApplicationConfiguration = KinesisAnalyticsV2ApplicationSqlApplicationConfiguration { _kinesisAnalyticsV2ApplicationSqlApplicationConfigurationInputs :: Maybe [KinesisAnalyticsV2ApplicationInput] } deriving (Show, Eq) instance ToJSON KinesisAnalyticsV2ApplicationSqlApplicationConfiguration where toJSON KinesisAnalyticsV2ApplicationSqlApplicationConfiguration{..} = object $ catMaybes [ fmap (("Inputs",) . toJSON) _kinesisAnalyticsV2ApplicationSqlApplicationConfigurationInputs ] -- | Constructor for -- 'KinesisAnalyticsV2ApplicationSqlApplicationConfiguration' containing -- required fields as arguments. kinesisAnalyticsV2ApplicationSqlApplicationConfiguration :: KinesisAnalyticsV2ApplicationSqlApplicationConfiguration kinesisAnalyticsV2ApplicationSqlApplicationConfiguration = KinesisAnalyticsV2ApplicationSqlApplicationConfiguration { _kinesisAnalyticsV2ApplicationSqlApplicationConfigurationInputs = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-sqlapplicationconfiguration.html#cfn-kinesisanalyticsv2-application-sqlapplicationconfiguration-inputs kavasacInputs :: Lens' KinesisAnalyticsV2ApplicationSqlApplicationConfiguration (Maybe [KinesisAnalyticsV2ApplicationInput]) kavasacInputs = lens _kinesisAnalyticsV2ApplicationSqlApplicationConfigurationInputs (\s a -> s { _kinesisAnalyticsV2ApplicationSqlApplicationConfigurationInputs = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsV2ApplicationSqlApplicationConfiguration.hs
mit
2,192
0
12
159
176
105
71
23
1
mean :: Fractional a => [a] -> a mean list = sum(list) / fromIntegral(length(list))
iduhetonas/haskell-projects
HelloWorld/mean.hs
mit
84
0
9
14
50
25
25
2
1
-- How Many Numbers? -- http://www.codewars.com/kata/55d8aa568dec9fb9e200004a module Codewars.G964.Howmany where import Data.Char (digitToInt) import Data.List (sort, group) selNumber :: Int -> Int -> Int selNumber n d = length . filter (((== xs) . map head . group . sort $ xs) && (all (<= d) . zipWith (-) (tail xs) $ xs)) . map (map digitToInt . show) $ [10 .. n]
gafiatulin/codewars
src/6 kyu/Howmany.hs
mit
370
0
16
65
153
85
68
5
1
{-# LANGUAGE OverloadedStrings #-} module Y2021.M02.D19.Exercise where {-- Okay, we have our ~120k wine-reviews uploaded, great! Did we do it correctly? Hm. Today's Haskell problem. We've verified before (Y2021.M02.D04.Solution) that wine-labels and wineries weren't redundant, and, if they were, we eliminated those redundancies, by simply pouring all of the nodes of a type into a name-ids map. The duplicates find themselves. For relations, it's a bit harder than that, and, that, on a couple of dimensions, for, a wine-reviewer can write more than one review of a particular wine. Also, a relation is not its name (it has none), and its id is not useful, either. The identifier of a relation is (start-node-id, end-node-id) but that is not unique (enough). We also need the wine-review-text, itself, to check for redundancy. AND we need the relation id to distinguish between the non-unique reviews. Ugh. This is a big ball of work, but, so it goes. --} import Data.Map (Map) import Data.Set (Set) import qualified Data.Set as Set import Data.Aeson (Value) import Data.Text (Text) import qualified Data.Text as T import Graph.Query import Graph.JSON.Cypher import qualified Graph.JSON.Cypher.Read.Rows as RR import Y2021.M01.D21.Solution (Idx) import Control.Map (snarf) type Vertices = (Idx, Idx) type EdgeRels rel = Map Vertices (Set rel) getWineRelationsQuery :: Cypher getWineRelationsQuery = T.concat ["MATCH (t:Taster)-[r:RATES_WINE]->(w:Wine) ", "RETURN id(t) as taster_id, id(w) as wine_id, ", "id(r) as rel_id, r.review as review"] data WineRel = WineRel { wrIx :: Idx, review :: Text } deriving (Eq, Ord, Show) -- This function helps convert from a QueryResult to a (Vertices, WineRel) row toPair :: [Value] -> Maybe (Vertices, WineRel) toPair [a,b,c,d] = undefined -- which means we can do this: wineRels :: Endpoint -> IO (EdgeRels WineRel) wineRels url = undefined {-- >>> graphEndpoint >>= wineRels ... >>> let winrevs = it How many wine-relations do you have from your graph store? --} -- Now that you have the relations, you must go into each set of Vertices -- and find the duplicate relations. dupeWinRels :: EdgeRels WineRel -> Set Idx dupeWinRels winRels = undefined -- What may be helpful is this function that finds dupes in a set of WinRels: dupeWinRels' :: Set WineRel -> Set Idx dupeWinRels' winRels = undefined -- remember: 'dupe,' in this case, is: different idx but same review -- How many dupes do we have? {-- >>> let dupes = dupeWinRels winrevs --} -- Okay, so, now we have ids of duplicate wine review relations. -- Let's delete these duplicates (DUPLICATES, NOT ORIGINALS!) deleteWineReviewsQuery :: Set Idx -> Cypher deleteWineReviewsQuery ixs = T.pack (unwords ["MATCH (:Taster)-[r:RATES_WINE]->(:Wine) WHERE id(r) in", show (Set.toList ixs), "DELETE r"]) -- DOIT! TOIT! {-- >>> graphEndpoint >>= flip getGraphResponse [deleteWineReviewsQuery dupes] "{\"results\":[{\"columns\":[],\"data\":[]}],\"errors\":[]}" --}
geophf/1HaskellADay
exercises/HAD/Y2021/M02/D19/Exercise.hs
mit
3,055
0
12
549
377
225
152
34
1
{- | Intro screen module implementation The game shows this screen during startup. It contains some information about your system like available memory, inputs and sound devices installed. The base image stored into SIGNON.OBJ file and contains empty boxes and title "One moment.." at the bottom. When resources loaded it changes to "Press a key" and after input acknowlegment processes to title screens. We will fill all blanks as 'available' here. -} module Game.Intro ( signonScreen , introScreen , finishSignon ) where import Control.Monad (forM_) import Control.Monad.Trans.State import Control.Monad.Trans (liftIO) import Graphics.UI.SDL -- Internal modules import import Game.Graphics import Game.Input import Game.State import Game.Text import Resources introMainColor, introEMSColor, introXMSColor, introFillColor :: GameColor introMainColor = 0x6C introEMSColor = 0x6C introXMSColor = 0x6C introFillColor = 14 txtBgColor :: GameColor txtBgColor = 41 -- obtained from bg picture -- | Draw blank signon screen -- signonScreen :: StateT GameState IO () signonScreen = do gstate <- get signon <- liftIO $ loadSignon -- draw background image liftIO $ setSurfaceData (screen gstate) signon -- | Fill signon with system information -- introScreen :: StateT GameState IO () introScreen = do -- get current game state gstate <- get -- Fill the boxes in the signon screen -- Of course we have a lot of memory, especially the -- ..Main one, forM_ [0..9] (\i -> vwbBar (Rect 49 (163 - 8 * i) 6 5) introMainColor) -- EMS.., forM_ [0..9] (\i -> vwbBar (Rect 89 (163 - 8 * i) 6 5) introEMSColor) -- ..and XMS for sure. forM_ [0..9] (\i -> vwbBar (Rect 129 (163 - 8 * i) 6 5) introXMSColor) -- mouse is present vwbBar (Rect 164 82 12 2) introFillColor -- joystick is present vwbBar (Rect 164 105 12 2) introFillColor -- AdLib is present vwbBar (Rect 164 128 12 2) introFillColor -- SoundBlaster is present vwbBar (Rect 164 151 12 2) introFillColor -- SoundSource is present vwbBar (Rect 164 174 12 2) introFillColor -- | Finish signon screen and wait for user input -- finishSignon :: StateT GameState IO () finishSignon = do gstate <- get modify (\s -> s { windowX = 0 -- @todo setWindowRect ? , windowW = 320 }) -- clear the "One moment.." text vwbBar (Rect 0 189 300 11) txtBgColor setFontColor (14, 4) setTextPos (Point 0 190) usCPrint "Press a key" -- TODO: check for `noWait` inAck -- clear text again vwbBar (Rect 0 189 300 11) txtBgColor setFontColor (10, 4) setTextPos (Point 0 190) usCPrint "Working..." setFontColor ( 0, 15)
vTurbine/w3dhs
src/Game/Intro.hs
mit
2,801
0
15
688
641
340
301
51
1
-- The fusc function -- Part 1 -- https://www.codewars.com/kata/570409d3d80ec699af001bf9 module Fusc where fusc :: Int -> Int fusc 0 = 0 fusc 1 = 1 fusc n | even n = fusc (n `div` 2) | otherwise = fusc (n `div` 2) + fusc (1 + (n `div` 2))
gafiatulin/codewars
src/7 kyu/Fusc.hs
mit
248
0
11
58
104
56
48
6
1
{-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Language.LSP.Types.WorkspaceEdit where import Control.Monad (unless) import Data.Aeson import Data.Aeson.TH import qualified Data.HashMap.Strict as H import Data.Maybe (catMaybes) import Data.Text (Text) import qualified Data.Text as T import Data.Hashable import Language.LSP.Types.Common import Language.LSP.Types.Location import Language.LSP.Types.TextDocument import Language.LSP.Types.Uri import Language.LSP.Types.Utils -- --------------------------------------------------------------------- data TextEdit = TextEdit { _range :: Range , _newText :: Text } deriving (Show,Read,Eq) deriveJSON lspOptions ''TextEdit -- --------------------------------------------------------------------- {-| Additional information that describes document changes. @since 3.16.0 -} data ChangeAnnotation = ChangeAnnotation { -- | A human-readable string describing the actual change. The string -- is rendered prominent in the user interface. _label :: Text -- | A flag which indicates that user confirmation is needed -- before applying the change. , _needsConfirmation :: Maybe Bool -- | A human-readable string which is rendered less prominent in -- the user interface. , _description :: Maybe Text } deriving (Show, Read, Eq) deriveJSON lspOptions ''ChangeAnnotation {-| An identifier referring to a change annotation managed by a workspace edit. @since 3.16.0 -} newtype ChangeAnnotationIdentifier = ChangeAnnotationIdentifierId Text deriving (Show, Read, Eq, FromJSON, ToJSON, ToJSONKey, FromJSONKey, Hashable) makeExtendingDatatype "AnnotatedTextEdit" [''TextEdit] [("_annotationId", [t| ChangeAnnotationIdentifier |]) ] deriveJSON lspOptions ''AnnotatedTextEdit -- --------------------------------------------------------------------- data TextDocumentEdit = TextDocumentEdit { _textDocument :: VersionedTextDocumentIdentifier , _edits :: List (TextEdit |? AnnotatedTextEdit) } deriving (Show, Read, Eq) deriveJSON lspOptions ''TextDocumentEdit -- --------------------------------------------------------------------- -- | Options to create a file. data CreateFileOptions = CreateFileOptions { -- | Overwrite existing file. Overwrite wins over `ignoreIfExists` _overwrite :: Maybe Bool -- | Ignore if exists. , _ignoreIfExists :: Maybe Bool } deriving (Show, Read, Eq) deriveJSON lspOptions ''CreateFileOptions -- | Create file operation data CreateFile = CreateFile { -- | The resource to create. _uri :: Uri -- | Additional options , _options :: Maybe CreateFileOptions -- | An optional annotation identifer describing the operation. -- -- @since 3.16.0 , _annotationId :: Maybe ChangeAnnotationIdentifier } deriving (Show, Read, Eq) instance ToJSON CreateFile where toJSON CreateFile{..} = object $ catMaybes [ Just $ "kind" .= ("create" :: Text) , Just $ "uri" .= _uri , ("options" .=) <$> _options , ("annotationId" .=) <$> _annotationId ] instance FromJSON CreateFile where parseJSON = withObject "CreateFile" $ \o -> do kind <- o .: "kind" unless (kind == ("create" :: Text)) $ fail $ "Expected kind \"create\" but got " ++ show kind _uri <- o .: "uri" _options <- o .:? "options" _annotationId <- o .:? "annotationId" pure CreateFile{..} -- Rename file options data RenameFileOptions = RenameFileOptions { -- | Overwrite target if existing. Overwrite wins over `ignoreIfExists` _overwrite :: Maybe Bool -- | Ignores if target exists. , _ignoreIfExists :: Maybe Bool } deriving (Show, Read, Eq) deriveJSON lspOptions ''RenameFileOptions -- | Rename file operation data RenameFile = RenameFile { -- | The old (existing) location. _oldUri :: Uri -- | The new location. , _newUri :: Uri -- | Rename options. , _options :: Maybe RenameFileOptions -- | An optional annotation identifer describing the operation. -- -- @since 3.16.0 , _annotationId :: Maybe ChangeAnnotationIdentifier } deriving (Show, Read, Eq) instance ToJSON RenameFile where toJSON RenameFile{..} = object $ catMaybes [ Just $ "kind" .= ("rename" :: Text) , Just $ "oldUri" .= _oldUri , Just $ "newUri" .= _newUri , ("options" .=) <$> _options , ("annotationId" .=) <$> _annotationId ] instance FromJSON RenameFile where parseJSON = withObject "RenameFile" $ \o -> do kind <- o .: "kind" unless (kind == ("rename" :: Text)) $ fail $ "Expected kind \"rename\" but got " ++ show kind _oldUri <- o .: "oldUri" _newUri <- o .: "newUri" _options <- o .:? "options" _annotationId <- o .:? "annotationId" pure RenameFile{..} -- Delete file options data DeleteFileOptions = DeleteFileOptions { -- | Delete the content recursively if a folder is denoted. _recursive :: Maybe Bool -- | Ignore the operation if the file doesn't exist. , _ignoreIfNotExists :: Maybe Bool } deriving (Show, Read, Eq) deriveJSON lspOptions ''DeleteFileOptions -- | Delete file operation data DeleteFile = DeleteFile { -- | The file to delete. _uri :: Uri -- | Delete options. , _options :: Maybe DeleteFileOptions -- | An optional annotation identifer describing the operation. -- -- @since 3.16.0 , _annotationId :: Maybe ChangeAnnotationIdentifier } deriving (Show, Read, Eq) instance ToJSON DeleteFile where toJSON DeleteFile{..} = object $ catMaybes [ Just $ "kind" .= ("delete" :: Text) , Just $ "uri" .= _uri , ("options" .=) <$> _options , ("annotationId" .=) <$> _annotationId ] instance FromJSON DeleteFile where parseJSON = withObject "DeleteFile" $ \o -> do kind <- o .: "kind" unless (kind == ("delete" :: Text)) $ fail $ "Expected kind \"delete\" but got " ++ show kind _uri <- o .: "uri" _options <- o .:? "options" _annotationId <- o .:? "annotationId" pure DeleteFile{..} -- --------------------------------------------------------------------- -- | `TextDocumentEdit |? CreateFile |? RenameFile |? DeleteFile` is a bit mouthful, here's the synonym type DocumentChange = TextDocumentEdit |? CreateFile |? RenameFile |? DeleteFile -- --------------------------------------------------------------------- type WorkspaceEditMap = H.HashMap Uri (List TextEdit) type ChangeAnnotationMap = H.HashMap ChangeAnnotationIdentifier ChangeAnnotation data WorkspaceEdit = WorkspaceEdit { -- | Holds changes to existing resources. _changes :: Maybe WorkspaceEditMap -- | Depending on the client capability -- `workspace.workspaceEdit.resourceOperations` document changes are either -- an array of `TextDocumentEdit`s to express changes to n different text -- documents where each text document edit addresses a specific version of -- a text document. Or it can contain above `TextDocumentEdit`s mixed with -- create, rename and delete file / folder operations. -- -- Whether a client supports versioned document edits is expressed via -- `workspace.workspaceEdit.documentChanges` client capability. -- -- If a client neither supports `documentChanges` nor -- `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s -- using the `changes` property are supported. , _documentChanges :: Maybe (List DocumentChange) -- | A map of change annotations that can be referenced in -- `AnnotatedTextEdit`s or create, rename and delete file / folder -- operations. -- -- Whether clients honor this property depends on the client capability -- `workspace.changeAnnotationSupport`. -- -- @since 3.16.0 , _changeAnnotations :: Maybe ChangeAnnotationMap } deriving (Show, Read, Eq) instance Semigroup WorkspaceEdit where (WorkspaceEdit a b c) <> (WorkspaceEdit a' b' c') = WorkspaceEdit (a <> a') (b <> b') (c <> c') instance Monoid WorkspaceEdit where mempty = WorkspaceEdit Nothing Nothing Nothing deriveJSON lspOptions ''WorkspaceEdit -- ------------------------------------- data ResourceOperationKind = ResourceOperationCreate -- ^ Supports creating new files and folders. | ResourceOperationRename -- ^ Supports renaming existing files and folders. | ResourceOperationDelete -- ^ Supports deleting existing files and folders. deriving (Read, Show, Eq) instance ToJSON ResourceOperationKind where toJSON ResourceOperationCreate = String "create" toJSON ResourceOperationRename = String "rename" toJSON ResourceOperationDelete = String "delete" instance FromJSON ResourceOperationKind where parseJSON (String "create") = pure ResourceOperationCreate parseJSON (String "rename") = pure ResourceOperationRename parseJSON (String "delete") = pure ResourceOperationDelete parseJSON _ = fail "ResourceOperationKind" data FailureHandlingKind = FailureHandlingAbort -- ^ Applying the workspace change is simply aborted if one of the changes provided fails. All operations executed before the failing operation stay executed. | FailureHandlingTransactional -- ^ All operations are executed transactional. That means they either all succeed or no changes at all are applied to the workspace. | FailureHandlingTextOnlyTransactional -- ^ If the workspace edit contains only textual file changes they are executed transactional. If resource changes (create, rename or delete file) are part of the change the failure handling strategy is abort. | FailureHandlingUndo -- ^ The client tries to undo the operations already executed. But there is no guarantee that this is succeeding. deriving (Read, Show, Eq) instance ToJSON FailureHandlingKind where toJSON FailureHandlingAbort = String "abort" toJSON FailureHandlingTransactional = String "transactional" toJSON FailureHandlingTextOnlyTransactional = String "textOnlyTransactional" toJSON FailureHandlingUndo = String "undo" instance FromJSON FailureHandlingKind where parseJSON (String "abort") = pure FailureHandlingAbort parseJSON (String "transactional") = pure FailureHandlingTransactional parseJSON (String "textOnlyTransactional") = pure FailureHandlingTextOnlyTransactional parseJSON (String "undo") = pure FailureHandlingUndo parseJSON _ = fail "FailureHandlingKind" data WorkspaceEditChangeAnnotationClientCapabilities = WorkspaceEditChangeAnnotationClientCapabilities { -- | Whether the client groups edits with equal labels into tree nodes, -- for instance all edits labelled with "Changes in Strings" would -- be a tree node. groupsOnLabel :: Maybe Bool } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkspaceEditChangeAnnotationClientCapabilities data WorkspaceEditClientCapabilities = WorkspaceEditClientCapabilities { _documentChanges :: Maybe Bool -- ^The client supports versioned document -- changes in 'WorkspaceEdit's -- | The resource operations the client supports. Clients should at least -- support @create@, @rename@ and @delete@ files and folders. , _resourceOperations :: Maybe (List ResourceOperationKind) -- | The failure handling strategy of a client if applying the workspace edit -- fails. , _failureHandling :: Maybe FailureHandlingKind -- | Whether the client normalizes line endings to the client specific -- setting. -- -- If set to `true` the client will normalize line ending characters -- in a workspace edit to the client specific new line character(s). -- -- @since 3.16.0 , _normalizesLineEndings :: Maybe Bool -- | Whether the client in general supports change annotations on text edits, -- create file, rename file and delete file changes. -- -- @since 3.16.0 , _changeAnnotationSupport :: Maybe WorkspaceEditChangeAnnotationClientCapabilities } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkspaceEditClientCapabilities -- --------------------------------------------------------------------- data ApplyWorkspaceEditParams = ApplyWorkspaceEditParams { -- | An optional label of the workspace edit. This label is -- presented in the user interface for example on an undo -- stack to undo the workspace edit. _label :: Maybe Text -- | The edits to apply , _edit :: WorkspaceEdit } deriving (Show, Read, Eq) deriveJSON lspOptions ''ApplyWorkspaceEditParams data ApplyWorkspaceEditResponseBody = ApplyWorkspaceEditResponseBody { -- | Indicates whether the edit was applied or not. _applied :: Bool -- | An optional textual description for why the edit was not applied. -- This may be used may be used by the server for diagnostic -- logging or to provide a suitable error for a request that -- triggered the edit. , _failureReason :: Maybe Text -- | Depending on the client's failure handling strategy `failedChange` -- might contain the index of the change that failed. This property is -- only available if the client signals a `failureHandling` strategy -- in its client capabilities. , _failedChange :: Maybe UInt } deriving (Show, Read, Eq) deriveJSON lspOptions ''ApplyWorkspaceEditResponseBody -- --------------------------------------------------------------------- -- | Applies a 'TextEdit' to some 'Text'. -- >>> applyTextEdit (TextEdit (Range (Position 0 1) (Position 0 2)) "i") "foo" -- "fio" applyTextEdit :: TextEdit -> Text -> Text applyTextEdit (TextEdit (Range sp ep) newText) oldText = let (_, afterEnd) = splitAtPos ep oldText (beforeStart, _) = splitAtPos sp oldText in mconcat [beforeStart, newText, afterEnd] where splitAtPos :: Position -> Text -> (Text, Text) splitAtPos (Position sl sc) t = -- If we are looking for a line beyond the end of the text, this will give us an index -- past the end. Fortunately, T.splitAt is fine with this, and just gives us the whole -- string and an empty string, which is what we want. let index = sc + startLineIndex sl t in T.splitAt (fromIntegral index) t -- The index of the first character of line 'line' startLineIndex :: UInt -> Text -> UInt startLineIndex 0 _ = 0 startLineIndex line t' = case T.findIndex (== '\n') t' of Just i -> fromIntegral i + 1 + startLineIndex (line - 1) (T.drop (i + 1) t') -- i != 0, and there are no newlines, so this is a line beyond the end of the text. -- In this case give the "start index" as the end, so we will at least append the text. Nothing -> fromIntegral $ T.length t' -- | 'editTextEdit' @outer@ @inner@ applies @inner@ to the text inside @outer@. editTextEdit :: TextEdit -> TextEdit -> TextEdit editTextEdit (TextEdit origRange origText) innerEdit = let newText = applyTextEdit innerEdit origText in TextEdit origRange newText
wz1000/haskell-lsp
lsp-types/src/Language/LSP/Types/WorkspaceEdit.hs
mit
15,912
0
16
3,766
2,453
1,345
1,108
222
3
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- import Control.Monad import Data.Maybe import qualified Data.Map as Map type DictMap = Map.Map String String isMultiCast :: String -> Bool isMultiCast = (`elem` "13579bdf") . (!! 1) isUniCast :: String -> Bool isUniCast = not . isMultiCast macLearning :: DictMap -> String -> String -> String -> (String, DictMap) macLearning dict pin dadd sadd = let ndict = Map.insert sadd pin dict pout = Map.lookup dadd ndict pout' = fromMaybe "" pout in if isMultiCast sadd then ("drop", dict) else if isMultiCast dadd || pout == Nothing then ("flood", ndict) else if pin == pout' then ("drop", ndict) else (pout', ndict) runTests :: DictMap -> Int -> IO (DictMap) runTests dict 0 = return dict runTests dict _ = do ip <- getLine let [pstr, dadd, sadd] = words ip let (opstr, odict) = macLearning dict pstr dadd sadd putStrLn opstr return odict main :: IO () main = do nstr <- getLine let dict = Map.empty let n = read nstr foldM_ runTests dict [n, (n-1)..0]
cbrghostrider/Hacking
HackerRank/Companies/VMWare/macLearning.hs
mit
1,516
0
11
384
410
218
192
34
4
module ProjectEuler.Problem110 ( problem , pickInOrder' ) where import Petbox import qualified Data.List.Match as LMatch import ProjectEuler.Types {- This is basically the more difficult version of Problem108, my plan is to revisit that problem first and come back with perhaps some more insights. By the same insight we get from Problem108, we know `product (take 14 primes) = 13082761331670030` is a solution, but now problem lies in how to narrow this down: so far we are trying to reach 4000000 * 2 through powers of 3, but actually we should take product of numbers of odd numbers greater than 1, [3,5,7...] and see which of those are minimal. -} problem :: Problem problem = pureProblem 110 Solved result minCount :: Int minCount = 4000000 recover :: [Int] -> Integer recover xs = product $ zipWith pow (reverse xs) primes' where primes' = LMatch.take xs primes pow x p = p ^! (x `quot` 2) search :: [Int] -> Int -> [] [Int] search odds acc = do (x,odds') <- pickInOrder' odds let acc' = acc*x if acc' >= minCount*2 then pure [x] else (x:) <$> search odds' acc' {- this finds a working solution but not necessarily the minimum solution. update: found (take 14) by trial and error, this give us: (8000001,[3,3,67,13267]) -- doesn't feel right to me as the last one is a bit too large. Current problem: for now we don't really know what are we searching: if we just want to minimize a product larger by as close to 8,000,000 as possible, we get the answer above, but this gives us a number too large to be an answer to the final question. So the following attempt actually solves the problem: Given that if the power number is too larger, we'll end up with some very large numbers that won't fit into answer bar, so it make sense to limit candidate numbers to a smaller set and see if we can have any luck there. Now the idea becomes finding a sequence of numbers exceeding 8,000,000, and recover the number the problem is asking for (see `recover` function), namely zip in primes in backward order and take the production. After this is done, we can simply find the minimum number recovered and that's our final answer. -} result :: Integer result = minimum $ recover <$> search [3,5..11] 1
Javran/Project-Euler
src/ProjectEuler/Problem110.hs
mit
2,310
0
10
506
266
146
120
23
2
{-# LANGUAGE GeneralizedNewtypeDeriving , MultiParamTypeClasses , DeriveGeneric , DeriveDataTypeable , OverloadedStrings #-} module Veva.Types.NewUser ( NewUser(..) , Email(..) , Password(..) ) where import Data.JSON.Schema import Hasql.Postgres (Postgres) import Data.Typeable (Typeable) import Hasql.Backend (CxValue(..)) import GHC.Generics (Generic) import Data.Aeson (FromJSON, ToJSON) import Data.Text (Text) import qualified Veva.Types.User as User newtype Email = Email { unEmail :: User.Email } deriving ( Eq , Show , Generic , Typeable , FromJSON , ToJSON , JSONSchema , CxValue Postgres ) newtype Password = Password { unPassword :: Text } deriving ( Eq , Show , Generic , Typeable , FromJSON , ToJSON , JSONSchema , CxValue Postgres ) data NewUser = NewUser { email :: Email , password :: Password } deriving (Eq, Show, Generic, Typeable) instance FromJSON NewUser instance ToJSON NewUser instance JSONSchema NewUser where schema = gSchema
L8D/veva
lib/Veva/Types/NewUser.hs
mit
1,251
0
8
434
282
167
115
43
0
{-# LANGUAGE OverloadedStrings #-} module Main (main) where -------------------------------------------------------------------------------- import Control.Concurrent (forkIO) import Control.Monad (forever, unless) import Control.Monad.Trans (liftIO) import Network.Socket (withSocketsDo) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Network.WebSockets as WS -------------------------------------------------------------------------------- app :: WS.ClientApp () app conn = do putStrLn "Connected!" -- Fork a thread that writes WS data to stdout _ <- forkIO $ forever $ do msg <- WS.receiveData conn liftIO $ T.putStrLn msg -- Read from stdin and write to WS let loop = do line <- T.getLine T.putStrLn line unless (T.null line) $ WS.sendTextData conn line >> loop loop WS.sendClose conn ("Bye!" :: Text) -------------------------------------------------------------------------------- main :: IO () main = withSocketsDo $ WS.runClient "localhost" 8000 "/" app
joshcough/Scrabble
web/client/Main.hs
mit
1,127
0
17
226
263
141
122
24
1
module Hiker where import Data.List bookPrice = 8.0 discount 2 = 2 * bookPrice * 0.95 discount 3 = 3 * bookPrice * 0.9 discountPrice' :: [Double] -> Double discountPrice' [nbBooks] = bookPrice * nbBooks discountPrice' (0:books) = discountPrice' books discountPrice' [x, y] = (discount 2) + discountPrice' [x-1, y-1] --discountPrice' [x, y] = (x * bookPrice * (discount 2)) + discountPrice' [y-x] --discountPrice' (x:books) = (x * bookPrice * (discount (length books) + 1)) + discountPrice' (books - 1) discountPrice' [x, y, z] = (discount 3) + discountPrice' [x-1, y-1, z-1] discountPrice = discountPrice' . sort split :: [Int] -> [[Int]] split [] = [[]] split [nbBooks] = [[nbBooks]] split (head:books) = (head:books)::
murex/murex-coding-dojo
Paris/2015/2015-03-05-KataPotter-Haskell-Randori/hiker.hs
mit
724
1
9
117
267
148
119
-1
-1
module Network.Skype.API.Carbon ( Connection, connect ) where import Control.Applicative import Control.Concurrent (ThreadId, forkIO) import Control.Concurrent.STM.TChan (TChan, newBroadcastTChanIO, writeTChan) import Control.Concurrent.STM.TMVar import Control.Monad (when) import Control.Monad.Error (Error, strMsg) import Control.Monad.Error.Class (MonadError, throwError) import Control.Monad.Reader (ReaderT, asks) import Control.Monad.STM (atomically) import Control.Monad.Trans (MonadIO, liftIO) import Data.Maybe import Foreign hiding (addForeignPtrFinalizer) import Foreign.Concurrent (addForeignPtrFinalizer) import Network.Skype.API.Carbon.CFBase import Network.Skype.API.Carbon.CFDictionary import Network.Skype.API.Carbon.CFNotificationCenter import Network.Skype.API.Carbon.CFNumber import Network.Skype.API.Carbon.CFString import Network.Skype.API.Carbon.CarbonEventsCore import Network.Skype.Core type ClientID = Int type ClientName = CFString data Connection = Connection { skypeClientID :: TMVar ClientID , skypeNotificationChan :: TChan Notification , skypeNotificationCenter :: NotificationCenter , skypeThread :: ThreadId } instance MonadIO m => MonadSkype (ReaderT Connection m) where sendCommand command = do center <- asks skypeNotificationCenter clientID <- asks skypeClientID >>= liftIO . atomically . readTMVar liftIO $ sendTo center clientID command getNotificationChan = asks skypeNotificationChan connect :: (Error e, MonadIO m, MonadError e m) => ApplicationName -> m Connection connect appName = do connection <- liftIO $ newConnection appName clientID <- liftIO $ atomically $ readTMVar $ skypeClientID connection when (clientID <= 0) $ throwError $ strMsg "Couldn't connect to Skype client." liftIO $ addForeignPtrFinalizer (getNotificationCenter $ skypeNotificationCenter connection) (disconnectFrom (skypeNotificationCenter connection) clientID) return connection newConnection :: ApplicationName -> IO Connection newConnection appName = do clientName <- newCFString appName >>= newForeignPtr p_CFRelease clientIDVar <- newEmptyTMVarIO notificatonChan <- newBroadcastTChanIO center <- getDistributedCenter clientName addObserver center "SKSkypeAPINotification" $ notificationCallback clientIDVar notificatonChan addObserver center "SKSkypeAttachResponse" $ attachResponseCallback clientIDVar clientName threadID <- forkIO $ c_RunCurrentEventLoop eventDurationForever attachTo center clientName return Connection { skypeClientID = clientIDVar , skypeNotificationChan = notificatonChan , skypeNotificationCenter = center , skypeThread = threadID } disconnectFrom :: NotificationCenter -> ClientID -> IO () disconnectFrom center clientID = withNotificationCenter center $ \center_ptr -> withCFNumber clientID $ \clientID_ptr -> do userInfo <- newCFDictionary [ ("SKYPE_API_CLIENT_ID" :: CFStringRef, castPtr clientID_ptr) ] c_CFNotificationCenterPostNotification center_ptr "SKSkypeAPIDetachRequest" nullPtr userInfo True c_CFRelease userInfo attachTo :: NotificationCenter -> ForeignPtr ClientName -> IO () attachTo center clientName = withNotificationCenter center $ \center_ptr -> withForeignPtr clientName $ \clientName_ptr -> c_CFNotificationCenterPostNotification center_ptr "SKSkypeAPIAttachRequest" clientName_ptr nullPtr True sendTo :: NotificationCenter -> ClientID -> Command -> IO () sendTo center clientID command = withNotificationCenter center $ \center_ptr -> withCFString command $ \command_ptr -> withCFNumber clientID $ \clientID_ptr -> do userInfo <- newCFDictionary [ ("SKYPE_API_COMMAND" :: CFStringRef, castPtr command_ptr) , ("SKYPE_API_CLIENT_ID", castPtr clientID_ptr) ] c_CFNotificationCenterPostNotification center_ptr "SKSkypeAPICommand" nullPtr userInfo True c_CFRelease userInfo notificationCallback :: TMVar ClientID -> TChan Notification -> CFNotificationCallback observer object CFString value notificationCallback clientIDVar notificatonChan _ _ _ _ userInfo = do maybeClientID <- atomically $ tryReadTMVar clientIDVar case maybeClientID of Just clientID -> do otherClientID <- getClientID when (clientID == otherClientID) $ getNotification >>= atomically . writeTChan notificatonChan Nothing -> return () where getClientID = c_CFDictionaryGetValue userInfo "SKYPE_API_CLIENT_ID" >>= fromCFNumber . castPtr getNotification = c_CFDictionaryGetValue userInfo "SKYPE_API_NOTIFICATION_STRING" >>= fromCFString . castPtr attachResponseCallback :: TMVar ClientID -> ForeignPtr ClientName -> CFNotificationCallback observer object CFString value attachResponseCallback clientIDVar clientName _ _ _ _ userInfo = do comparisonResult <- withForeignPtr clientName $ \clientName_ptr -> do otherClientName <- getClientName c_CFStringCompare clientName_ptr otherClientName compareDefault when (comparisonResult == compareEqualTo) $ do maybeClientID <- getClientID atomically $ putTMVar clientIDVar $ fromMaybe 0 maybeClientID where getClientName = castPtr <$> c_CFDictionaryGetValue userInfo "SKYPE_API_CLIENT_NAME" getClientID = do clientID_ptr <- c_CFDictionaryGetValue userInfo "SKYPE_API_ATTACH_RESPONSE" if clientID_ptr == nullPtr then pure Nothing else Just <$> fromCFNumber (castPtr clientID_ptr)
emonkak/skype4hs
src/Network/Skype/API/Carbon.hs
mit
5,674
0
17
1,058
1,288
658
630
131
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Qwu.DB.Table.Post where import Qwu.DB.Table.Account (AccountId) import GHC.Generics import Control.Lens (makeLenses) import Data.Aeson import Data.Default import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Text import Data.Time (defaultTimeLocale, parseTimeM, UTCTime) import Data.UUID as U import Data.UUID.Aeson import Opaleye ( Column , optional , required , PGInt4 , PGText , PGTimestamptz , PGUuid , Table(Table) ) type PostId = Int type Body = Text type Ts = UTCTime data Post' a b c d = Post { _postId :: a , _body :: b , _ts :: c , _accountId :: d } deriving (Eq, Show, Generic) makeLenses ''Post' type Post = Post' PostId Body Ts AccountId instance ToJSON Post instance Default Post where def = Post 0 "a post body" timestamp U.nil where Just timestamp = parseTimeM True defaultTimeLocale "%c" "Thu Jan 1 00:00:10 UTC 1970" :: Maybe UTCTime $(makeAdaptorAndInstance "pPost" ''Post') -- type signature format: -- someTable :: Table <writes> -- <reads> type ColumnW = Post' (Maybe (Column PGInt4)) (Column PGText) (Column PGTimestamptz) (Column PGUuid) type ColumnR = Post' (Column PGInt4) (Column PGText) (Column PGTimestamptz) (Column PGUuid) table :: Table ColumnW ColumnR table = Table "postTable" ( pPost Post { _postId = optional "postId" , _body = required "body" , _ts = required "ts" , _accountId = required "accountId" })
bryangarza/qwu
src/Qwu/DB/Table/Post.hs
mit
1,744
0
10
431
444
255
189
50
1
-- Copyright 2013 Thomas Szczarkowski import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as Char8 import qualified Data.ByteString.Base64 as Base64 import Data.Char import Data.Function import Data.Array.IArray import Data.List import Data.Bits import Data.Word import Control.Monad import Text.Printf import SymmetricCiphers main = p1 >> p2 >> p3 >> p4 >> p5 >> p6 >> p7 >> p8 p1 = do putStrLn "\n==Problem 1==\n" let x = decodeHex "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" let y = encodeB64 x let x' = decodeB64 y [encodeHex x, y, encodeHex x'] `each` putStrLn each xs f = sequence $ map f xs infixl 1 `each` decodeHex (x:y:rest) = (read ("0x" ++ [x,y])) : decodeHex rest decodeHex _ = [] encodeHex = concat . (map (\x -> printf "%02x" x)) decodeB64 = BS.unpack . Base64.decodeLenient . Char8.pack encodeB64 = Char8.unpack . Base64.encode . BS.pack fromAscii = BS.unpack . Char8.pack toAscii = Char8.unpack . BS.pack p2 = do putStrLn "\n==Problem 2==\n" let x = decodeHex "1c0111001f010100061a024b53535009181c" let y = decodeHex "686974207468652062756c6c277320657965" let z = xorBuffers x y [x,y,z] `each` putStrLn . encodeHex xorBuffers = zipWith xor p3 = do putStrLn "\n==Problem 3==\n" let cipherText = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" let (Decryption key plainText score) = bruteForceXor1 $ decodeHex cipherText putStrLn $ encodeHex key putStrLn $ toAscii plainText putStrLn $ printf "log10(likelihood ratio): %0.3f\n" (logLikelihoodRatio plainText) -- XOR cipher with repeating key xorCrypt text key = xorBuffers text (concat (repeat key)) -- struct representing a a possible decryption data Decryption = Decryption { decryptKey :: [Word8], decryptPlaintext :: [Word8], decryptScore :: Float } deriving Show -- brute-force a one-byte key bruteForceXor1 cipherText = head $ sortBy (compare `on` negate.decryptScore) $ [try byte | (byte :: Word8) <- [0..255]] where try byte = let key = [byte] plaintext = xorCrypt cipherText key score = sum $ map (logByteFreqs !) plaintext in Decryption key plaintext score -- English letter frequencies: (case-insensitive) -- https://en.wikipedia.org/wiki/Letter_frequency#Relative_frequencies_of_letters_in_the_English_language freqAZ = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] -- extension to byte frequencies -- (I made up these numbers, nothing empirical here) byteFreqs :: Array Word8 Float -- sums to 1.0 byteFreqs = let lc = zip ['a'..'z'] $ map (0.80*) freqAZ uc = zip ['A'..'Z'] $ map (0.03*) freqAZ spc = [(' ', 0.15)] punc = zip "!@#$%^&*()?/,.:;'\"" $ repeat (0.019 / 18.0) rest = zip (map chr [0..255]) $ repeat (0.001 / 256.0) in accumArray (+) 0 (0,255) $ map (\(c,f) -> (fromIntegral $ ord c, f)) $ concat [lc,uc,spc,punc,rest] -- (easier to work logarithmically) logByteFreqs = amap log byteFreqs :: Array Word8 Float -- scoring function logLikelihoodRatio text = let language = sum $ map (logByteFreqs !) text randomNoise = -(fromIntegral $ length text) * log 256 in (1/(log 10)) * (language - randomNoise) p4 = do putStrLn "\n==Problem 4==\n" ciphers <- liftM ((map decodeHex) . words) $ readFile "gistfile-p4.txt" let candidates = filter ((> 0.0) . logLikelihoodRatio . decryptPlaintext) $ map bruteForceXor1 ciphers putStrLn "probable decryptions:" putStrLn "log10(likelihood ratio) | plaintext" sortBy (compare `on` negate.decryptScore) candidates `each` display where display x = putStrLn $ printf "%.3f\t\t%s" (logLikelihoodRatio $ decryptPlaintext x) (toAscii $ decryptPlaintext x) bruteForceXor cipher = head $ sortBy (compare `on` negate.decryptScore) $ [_knownKeySize cipher sz | sz <- [2..40]] _knownKeySize cipher sz = let slices = slice cipher sz -- one slice per key byte; -- contains the ciphertext bytes that key byte encrypts sub = map bruteForceXor1 slices key = concat $ map decryptKey sub plaintext = unslice $ map decryptPlaintext sub score = sum $ map decryptScore sub in Decryption key plaintext score slice list stride = map (map (list !!)) $ [[j, j+stride .. length list - 1] | j <- [0..stride-1]] unslice = concat . transpose p5 = do putStrLn "\n==Problem 5==\n" let plainText = fromAscii "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" let key = fromAscii "ICE" let cipherText = xorCrypt plainText key putStrLn $ encodeHex cipherText p6 = do putStrLn "\n==Problem 6==\n" cipherText <- liftM (decodeB64 . concat . words) $ readFile "gistfile-p6.txt" let decrypt = bruteForceXor cipherText ["key: ", encodeHex $ decryptKey decrypt, toAscii $ decryptKey decrypt, "\nplaintext: ", toAscii $ decryptPlaintext decrypt] `each` putStrLn p7 = do putStrLn "\n==Problem 7==\n" -- FFI wrapping to OpenSSL cipher <- SymmetricCiphers.findCipher "aes-128-ecb" let key = Char8.pack "YELLOW SUBMARINE" let iv = Char8.pack ['\0' | _ <- [1..16]] cipherText <- liftM (BS.pack . decodeB64 . concat . words) $ readFile "gistfile-p7.txt" plainText <- SymmetricCiphers.decrypt cipher key iv cipherText putStrLn $ Char8.unpack plainText p8 = do putStrLn "\n==Problem 8==\n" cipherTexts <- liftM (map decodeHex . words) $ readFile "gistfile-p8.txt" -- secure modes won't have repeating blocks (expected rate 2^-128) let maybeECB = filter (hasDuplicates . blocks 16) cipherTexts maybeECB `each` putStrLn . encodeHex hasDuplicates x = (x /= nub x) blocks sz text | null text = [] | otherwise = let (b,bs) = splitAt sz text in b : blocks sz bs
tom-szczarkowski/matasano-crypto-puzzles-solutions
set1/Solutions.hs
mit
6,384
0
15
1,562
1,909
985
924
-1
-1
module Apriori where import FileIO import HasseTree main path file minSupport = do dataSet <- importData path file let frequents = apriori dataSet minSupport exportResult path file $ toString frequents -- return $ frequents apriori :: [ItemSet] -> Int -> HasseTree apriori dataSet minSupport = apriori' dataSet (singletons dataSet minSupport) minSupport 1 apriori' :: [ItemSet] -> HasseTree -> Int -> Int -> HasseTree apriori' dataSet hasseTree minSupport k -- k = level of iteration | k > (maxDepth hasseTree) = hasseTree | otherwise = apriori' dataSet postPruned minSupport (k + 1) where postPruned = (posteriorPrune dataSet aprioriPruned minSupport (k + 1)) aprioriPruned = (genCandidates hasseTree hasseTree k []) -- generates viable (i.e. according to a priori property) candidates genCandidates :: HasseTree -> HasseTree -> Int -> ItemSet -> HasseTree genCandidates [] _ _ _ = [] -- stop when we are at end of list genCandidates (htH@(HasseLeafNode itm n):htT) reference k cand -- cand for candidate | k == 1 = ((HasseTreeNode itm n (nextLevel (reverse (itm:cand)) htT reference)):nextSameLine) -- front: node with old item and support counter, and pointer to newly generated child node | k > 1 = htH:nextSameLine where nextSameLine = (genCandidates htT reference k cand) genCandidates ((HasseTreeNode itm n child):htT) reference k cand = (HasseTreeNode itm n (genCandidates child reference (k - 1) (itm:cand))):(genCandidates htT reference k cand) nextLevel :: ItemSet -> HasseTree -> HasseTree -> HasseTree nextLevel _ [] _ = [] nextLevel cand ((HasseLeafNode itm n):hlT) reference = -- hl for Hasse Leaves case any (True==) $ aprioriPrune (cand ++ [itm]) reference of True -> nextLevel cand hlT reference False -> (HasseLeafNode itm 0):(nextLevel cand hlT reference) -- generates a list of Bool which indicate whether the supports of the subsets of a candidate itemSet are smaller than -- the minimum support, based on a previously generated HasseTree aprioriPrune :: ItemSet -> HasseTree -> [Bool] aprioriPrune (itmSetH:itmSetT) reference = aprioriPrune' [] [itmSetH] itmSetT reference aprioriPrune' :: ItemSet -> ItemSet -> ItemSet -> HasseTree -> [Bool] aprioriPrune' _ _ [] _ = [False] -- this means we are omitting the last element, which is generated from an already frequent subset (neighbor) aprioriPrune' prev omit tail@(tailH:tailT) reference = (notSupported (prev ++ tail) reference):(aprioriPrune' (prev ++ omit) [tailH] tailT reference) -- gives True when the candidate is not in the HasseTree, i.e. the support is too small notSupported :: ItemSet -> HasseTree -> Bool notSupported cand [] = True notSupported [lst] (htH:htT) | lst == item htH = False | lst > item htH = notSupported [lst] htT notSupported (candH:_) (htH:_) | candH < (item htH) = True -- we've passed the point of no return, there is no way to still find the candidate in the tree notSupported cand@(candH:_) ((HasseLeafNode itm _):htT) | candH == itm = True -- guaranteed that the Leaf Node is not on the last layer, i.e. supersets are infrequent, because of earlier pattern matching | candH > itm = notSupported cand htT -- otherwise iterate through to find the node on which to go down notSupported cand@(candH:candT) ((HasseTreeNode itm _ nxtLevel):htT) | candH == itm = notSupported candT nxtLevel -- go down to the next level, omit first element of candidate | candH > itm = notSupported cand htT posteriorPrune :: [ItemSet] -> HasseTree -> Int -> Int -> HasseTree posteriorPrune dataSet hasseTree minSupport k = removeInfrequent minSupport (addDataSet dataSet hasseTree k) k -- counts and adds all sets of size k addDataSet :: [ItemSet] -> HasseTree -> Int -> HasseTree addDataSet [] ht _ = ht addDataSet (dsH:dsT) ht k = addDataSet dsT (addItemSet dsH ht k) k addItemSet :: ItemSet -> HasseTree -> Int -> HasseTree addItemSet [] ht _ = ht addItemSet _ [] _ = [] addItemSet is@(isH:isT) ht@(htH:htT) 1 | isH == item htH = (incCount htH):(addItemSet isT htT 1) | isH > item htH = htH:(addItemSet is htT 1) | isH < item htH = addItemSet isT ht 1 addItemSet is (htH@(HasseLeafNode _ _):htT) k = htH:(addItemSet is htT k) addItemSet is@(isH:isT) ht@(htH@(HasseTreeNode itm n child):htT) k | isH == item htH = (HasseTreeNode itm n (addItemSet isT child (k - 1))):(addItemSet isT htT k) | isH > item htH = htH:(addItemSet is htT k) | isH < item htH = addItemSet isT ht k
gaetjen/FunFreakyPatMan
src/Apriori.hs
mit
4,518
0
15
865
1,513
772
741
64
2
module DTS.Toolkit (DTSToolkit(..), fileToKit, getProperty, getNodeCompatibles) where import DTS import Control.Applicative hiding ((<|>), many) import Data.List import Data.MultiMap (MultiMap) import qualified Data.MultiMap as MultiMap import System.FilePath.Posix import Text.ParserCombinators.Parsec data DTSToolkit = Kit { tree :: [DTS] , getNodeByHandle :: String -> Maybe DTS , nodesByCompatible :: MultiMap [String] DTS } -- similar to nub, but leaves the last element instead of the first unique :: (Eq a) => [a] -> [a] unique = reverse . nub . reverse parseFile :: FilePath -> IO [DTS] parseFile f = do content <- readFile f case parse dts f content of Right d -> checkIncl d Left _ -> return [] where parseOther p = parseFile (replaceFileName f p) checkIncl :: [DTS] -> IO [DTS] checkIncl [] = return [] checkIncl ((Include p):xs) = do { x <- parseOther p ; checkIncl (x ++ xs) } checkIncl (x:xs) = (:) <$> pure x <*> checkIncl xs mergeDTS dt = (unique not_blocks) ++ mergeDTS' (sort blocks) where is_block (Block _ _) = True is_block _ = False (blocks, not_blocks) = partition is_block dt mergeDTS' (xb@(Block x xc):yb@(Block y yc):xs) | x == y = mergeDTS' ((Block x (mergeDTS (xc ++ yc))) : xs) | otherwise = xb : (mergeDTS' (yb:xs)) mergeDTS' x = x findLabels x = findLabelsMap [] x where findLabelsMap p c = concat $ map (findLabels' p) c findLabels' path (Block ('&' : label) c) = [] findLabels' path (Block n c) = findLabelsMap (path ++ [n]) c findLabels' path (Label label (Block n c)) = (label, path ++ [n]) : findLabelsMap (path ++ [n]) c findLabels' path _ = [] replaceAlias x = cleanTreeMap x ++ findAliasMap x where labels = findLabels x findAliasMap c = concat $ map findAlias c findAlias (Block ('&' : label) c) = maybe [] (\p -> generateFillerBlocks p c) (lookup label labels) ++ findAliasMap c findAlias (Block n c) = findAliasMap c findAlias _ = [] cleanTreeMap c = concat $ map cleanTree c cleanTree (Block ('&' : label) _) = [] cleanTree (Label _ c) = cleanTree c cleanTree (Block n c) = [Block n (cleanTreeMap c)] cleanTree (Define _) = [] cleanTree x = [x] generateFillerBlocks (x:xs) e = [Block x (generateFillerBlocks xs e)] generateFillerBlocks [] e = e loadDTS :: FilePath -> IO ([DTS], [(String, [String])]) loadDTS f = (,) <$> clean_dts <*> labels where raw_dts = parseFile f clean_dts = (mergeDTS . replaceAlias) <$> raw_dts labels = findLabels <$> raw_dts getNode :: [DTS] -> [String] -> Maybe DTS getNode ((Block t v):ts) [x] | t == x = Just (Block t v) | otherwise = getNode ts [x] getNode ((Block t v):ts) (x:xs) | t == x = getNode v xs | otherwise = getNode ts (x:xs) getNode (_:ts) x = getNode ts x getNode [] _ = Nothing getProperty :: DTS -> String -> Maybe [PropertyValue] getProperty (Block _ props) name = if length value == 0 then Nothing else Just v where is_property_named name (Property k _) = k == name is_property_named _ _ = False value = filter (is_property_named name) props (Property _ v) = head value getNodeCompatibles :: DTS -> [String] getNodeCompatibles node = value_to_list compat_value where compat_value = maybe [] id (getProperty node "compatible") value_to_list val = map (\(String s) -> s) val compatibleMultiMap :: [DTS] -> MultiMap [String] DTS compatibleMultiMap tree = foldl traverse_and_add MultiMap.empty tree where traverse_and_add t b@(Block _ v) = MultiMap.insert (getNodeCompatibles b) b $ foldl traverse_and_add t v traverse_and_add t _ = t fileToKit :: FilePath -> IO DTSToolkit fileToKit path = do (nodes, labels) <- loadDTS path return $ Kit nodes (get_node_by_name nodes labels) (compatibleMultiMap nodes) where get_node_by_name nodes labels n = lookup n labels >>= (getNode nodes)
elopez/dtschecker
DTS/Toolkit.hs
gpl-2.0
4,196
2
16
1,148
1,676
864
812
80
8
module Cake.Process (processIO, Cake.Process.system) where import Cake.Core import System.IO import Control.Applicative import Control.Monad.Trans import System.Process as P import Data.List import System.Exit import Control.Monad quote :: String -> String quote = show maybeM :: Applicative m => (a -> m Handle) -> Maybe a -> m StdStream maybeM f Nothing = pure Inherit maybeM f (Just x) = UseHandle <$> f x processIO' :: FilePath -> [String] -> Maybe FilePath -> Maybe FilePath -> Act ExitCode processIO' cmd args inp out = do debug $ "running: "++ cmd ++ " " ++ intercalate " " args liftIO $ do o <- maybeM (flip openFile WriteMode) out i <- maybeM (flip openFile ReadMode) inp (_,_,_,p) <- createProcess $ (shell (intercalate " " $ map quote (cmd:args))) {std_in = i, std_out = o} waitForProcess p system' :: [String] -> Act ExitCode system' (x:xs) = processIO' x xs Nothing Nothing succeed :: Act ExitCode -> Act () succeed act = do code <- act when (code /= ExitSuccess) $ throwError $ ProcessError code system xs = succeed $ system' xs processIO c a i o = succeed $ processIO' c a i o
jyp/Cake
Cake/Process.hs
gpl-2.0
1,131
0
19
228
472
239
233
30
1
{-| Implementation of cluster-wide logic. This module holds all pure cluster-logic; I\/O related functionality goes into the /Main/ module for the individual binaries. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.HTools.Cluster ( -- * Types AllocSolution(..) , EvacSolution(..) , Table(..) , CStats(..) , AllocNodes , AllocResult , AllocMethod , AllocSolutionList -- * Generic functions , totalResources , computeAllocationDelta -- * First phase functions , computeBadItems -- * Second phase functions , printSolutionLine , formatCmds , involvedNodes , getMoves , splitJobs -- * Display functions , printNodes , printInsts -- * Balacing functions , checkMove , doNextBalance , tryBalance , compCV , compCVNodes , compDetailedCV , printStats , iMoveToJob -- * IAllocator functions , genAllocNodes , tryAlloc , tryMGAlloc , tryNodeEvac , tryChangeGroup , collapseFailures , allocList -- * Allocation functions , iterateAlloc , tieredAlloc -- * Node group functions , instanceGroup , findSplitInstances , splitCluster ) where import Control.Applicative (liftA2) import Control.Arrow ((&&&)) import qualified Data.IntSet as IntSet import Data.List import Data.Maybe (fromJust, fromMaybe, isJust, isNothing) import Data.Ord (comparing) import Text.Printf (printf) import Ganeti.BasicTypes import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Nic as Nic import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Group as Group import Ganeti.HTools.Types import Ganeti.Compat import qualified Ganeti.OpCodes as OpCodes import Ganeti.Utils import Ganeti.Types (EvacMode(..), mkNonEmpty) -- * Types -- | Allocation\/relocation solution. data AllocSolution = AllocSolution { asFailures :: [FailMode] -- ^ Failure counts , asAllocs :: Int -- ^ Good allocation count , asSolution :: Maybe Node.AllocElement -- ^ The actual allocation result , asLog :: [String] -- ^ Informational messages } -- | Node evacuation/group change iallocator result type. This result -- type consists of actual opcodes (a restricted subset) that are -- transmitted back to Ganeti. data EvacSolution = EvacSolution { esMoved :: [(Idx, Gdx, [Ndx])] -- ^ Instances moved successfully , esFailed :: [(Idx, String)] -- ^ Instances which were not -- relocated , esOpCodes :: [[OpCodes.OpCode]] -- ^ List of jobs } deriving (Show) -- | Allocation results, as used in 'iterateAlloc' and 'tieredAlloc'. type AllocResult = (FailStats, Node.List, Instance.List, [Instance.Instance], [CStats]) -- | Type alias for easier handling. type AllocSolutionList = [(Instance.Instance, AllocSolution)] -- | A type denoting the valid allocation mode/pairs. -- -- For a one-node allocation, this will be a @Left ['Ndx']@, whereas -- for a two-node allocation, this will be a @Right [('Ndx', -- ['Ndx'])]@. In the latter case, the list is basically an -- association list, grouped by primary node and holding the potential -- secondary nodes in the sub-list. type AllocNodes = Either [Ndx] [(Ndx, [Ndx])] -- | The empty solution we start with when computing allocations. emptyAllocSolution :: AllocSolution emptyAllocSolution = AllocSolution { asFailures = [], asAllocs = 0 , asSolution = Nothing, asLog = [] } -- | The empty evac solution. emptyEvacSolution :: EvacSolution emptyEvacSolution = EvacSolution { esMoved = [] , esFailed = [] , esOpCodes = [] } -- | The complete state for the balancing solution. data Table = Table Node.List Instance.List Score [Placement] deriving (Show) -- | Cluster statistics data type. data CStats = CStats { csFmem :: Integer -- ^ Cluster free mem , csFdsk :: Integer -- ^ Cluster free disk , csFspn :: Integer -- ^ Cluster free spindles , csAmem :: Integer -- ^ Cluster allocatable mem , csAdsk :: Integer -- ^ Cluster allocatable disk , csAcpu :: Integer -- ^ Cluster allocatable cpus , csMmem :: Integer -- ^ Max node allocatable mem , csMdsk :: Integer -- ^ Max node allocatable disk , csMcpu :: Integer -- ^ Max node allocatable cpu , csImem :: Integer -- ^ Instance used mem , csIdsk :: Integer -- ^ Instance used disk , csIspn :: Integer -- ^ Instance used spindles , csIcpu :: Integer -- ^ Instance used cpu , csTmem :: Double -- ^ Cluster total mem , csTdsk :: Double -- ^ Cluster total disk , csTspn :: Double -- ^ Cluster total spindles , csTcpu :: Double -- ^ Cluster total cpus , csVcpu :: Integer -- ^ Cluster total virtual cpus , csNcpu :: Double -- ^ Equivalent to 'csIcpu' but in terms of -- physical CPUs, i.e. normalised used phys CPUs , csXmem :: Integer -- ^ Unnacounted for mem , csNmem :: Integer -- ^ Node own memory , csScore :: Score -- ^ The cluster score , csNinst :: Int -- ^ The total number of instances } deriving (Show) -- | A simple type for allocation functions. type AllocMethod = Node.List -- ^ Node list -> Instance.List -- ^ Instance list -> Maybe Int -- ^ Optional allocation limit -> Instance.Instance -- ^ Instance spec for allocation -> AllocNodes -- ^ Which nodes we should allocate on -> [Instance.Instance] -- ^ Allocated instances -> [CStats] -- ^ Running cluster stats -> Result AllocResult -- ^ Allocation result -- | A simple type for the running solution of evacuations. type EvacInnerState = Either String (Node.List, Instance.Instance, Score, Ndx) -- * Utility functions -- | Verifies the N+1 status and return the affected nodes. verifyN1 :: [Node.Node] -> [Node.Node] verifyN1 = filter Node.failN1 {-| Computes the pair of bad nodes and instances. The bad node list is computed via a simple 'verifyN1' check, and the bad instance list is the list of primary and secondary instances of those nodes. -} computeBadItems :: Node.List -> Instance.List -> ([Node.Node], [Instance.Instance]) computeBadItems nl il = let bad_nodes = verifyN1 $ getOnline nl bad_instances = map (`Container.find` il) . sort . nub $ concatMap (\ n -> Node.sList n ++ Node.pList n) bad_nodes in (bad_nodes, bad_instances) -- | Extracts the node pairs for an instance. This can fail if the -- instance is single-homed. FIXME: this needs to be improved, -- together with the general enhancement for handling non-DRBD moves. instanceNodes :: Node.List -> Instance.Instance -> (Ndx, Ndx, Node.Node, Node.Node) instanceNodes nl inst = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_p = Container.find old_pdx nl old_s = Container.find old_sdx nl in (old_pdx, old_sdx, old_p, old_s) -- | Zero-initializer for the CStats type. emptyCStats :: CStats emptyCStats = CStats 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -- | Update stats with data from a new node. updateCStats :: CStats -> Node.Node -> CStats updateCStats cs node = let CStats { csFmem = x_fmem, csFdsk = x_fdsk, csAmem = x_amem, csAcpu = x_acpu, csAdsk = x_adsk, csMmem = x_mmem, csMdsk = x_mdsk, csMcpu = x_mcpu, csImem = x_imem, csIdsk = x_idsk, csIcpu = x_icpu, csTmem = x_tmem, csTdsk = x_tdsk, csTcpu = x_tcpu, csVcpu = x_vcpu, csNcpu = x_ncpu, csXmem = x_xmem, csNmem = x_nmem, csNinst = x_ninst, csFspn = x_fspn, csIspn = x_ispn, csTspn = x_tspn } = cs inc_amem = Node.fMem node - Node.rMem node inc_amem' = if inc_amem > 0 then inc_amem else 0 inc_adsk = Node.availDisk node inc_imem = truncate (Node.tMem node) - Node.nMem node - Node.xMem node - Node.fMem node inc_icpu = Node.uCpu node inc_idsk = truncate (Node.tDsk node) - Node.fDsk node inc_ispn = Node.tSpindles node - Node.fSpindles node inc_vcpu = Node.hiCpu node inc_acpu = Node.availCpu node inc_ncpu = fromIntegral (Node.uCpu node) / iPolicyVcpuRatio (Node.iPolicy node) in cs { csFmem = x_fmem + fromIntegral (Node.fMem node) , csFdsk = x_fdsk + fromIntegral (Node.fDsk node) , csFspn = x_fspn + fromIntegral (Node.fSpindles node) , csAmem = x_amem + fromIntegral inc_amem' , csAdsk = x_adsk + fromIntegral inc_adsk , csAcpu = x_acpu + fromIntegral inc_acpu , csMmem = max x_mmem (fromIntegral inc_amem') , csMdsk = max x_mdsk (fromIntegral inc_adsk) , csMcpu = max x_mcpu (fromIntegral inc_acpu) , csImem = x_imem + fromIntegral inc_imem , csIdsk = x_idsk + fromIntegral inc_idsk , csIspn = x_ispn + fromIntegral inc_ispn , csIcpu = x_icpu + fromIntegral inc_icpu , csTmem = x_tmem + Node.tMem node , csTdsk = x_tdsk + Node.tDsk node , csTspn = x_tspn + fromIntegral (Node.tSpindles node) , csTcpu = x_tcpu + Node.tCpu node , csVcpu = x_vcpu + fromIntegral inc_vcpu , csNcpu = x_ncpu + inc_ncpu , csXmem = x_xmem + fromIntegral (Node.xMem node) , csNmem = x_nmem + fromIntegral (Node.nMem node) , csNinst = x_ninst + length (Node.pList node) } -- | Compute the total free disk and memory in the cluster. totalResources :: Node.List -> CStats totalResources nl = let cs = foldl' updateCStats emptyCStats . Container.elems $ nl in cs { csScore = compCV nl } -- | Compute the delta between two cluster state. -- -- This is used when doing allocations, to understand better the -- available cluster resources. The return value is a triple of the -- current used values, the delta that was still allocated, and what -- was left unallocated. computeAllocationDelta :: CStats -> CStats -> AllocStats computeAllocationDelta cini cfin = let CStats {csImem = i_imem, csIdsk = i_idsk, csIcpu = i_icpu, csNcpu = i_ncpu, csIspn = i_ispn } = cini CStats {csImem = f_imem, csIdsk = f_idsk, csIcpu = f_icpu, csTmem = t_mem, csTdsk = t_dsk, csVcpu = f_vcpu, csNcpu = f_ncpu, csTcpu = f_tcpu, csIspn = f_ispn, csTspn = t_spn } = cfin rini = AllocInfo { allocInfoVCpus = fromIntegral i_icpu , allocInfoNCpus = i_ncpu , allocInfoMem = fromIntegral i_imem , allocInfoDisk = fromIntegral i_idsk , allocInfoSpn = fromIntegral i_ispn } rfin = AllocInfo { allocInfoVCpus = fromIntegral (f_icpu - i_icpu) , allocInfoNCpus = f_ncpu - i_ncpu , allocInfoMem = fromIntegral (f_imem - i_imem) , allocInfoDisk = fromIntegral (f_idsk - i_idsk) , allocInfoSpn = fromIntegral (f_ispn - i_ispn) } runa = AllocInfo { allocInfoVCpus = fromIntegral (f_vcpu - f_icpu) , allocInfoNCpus = f_tcpu - f_ncpu , allocInfoMem = truncate t_mem - fromIntegral f_imem , allocInfoDisk = truncate t_dsk - fromIntegral f_idsk , allocInfoSpn = truncate t_spn - fromIntegral f_ispn } in (rini, rfin, runa) -- | The names and weights of the individual elements in the CV list. detailedCVInfo :: [(Double, String)] detailedCVInfo = [ (1, "free_mem_cv") , (1, "free_disk_cv") , (1, "n1_cnt") , (1, "reserved_mem_cv") , (4, "offline_all_cnt") , (16, "offline_pri_cnt") , (1, "vcpu_ratio_cv") , (1, "cpu_load_cv") , (1, "mem_load_cv") , (1, "disk_load_cv") , (1, "net_load_cv") , (2, "pri_tags_score") , (1, "spindles_cv") ] -- | Holds the weights used by 'compCVNodes' for each metric. detailedCVWeights :: [Double] detailedCVWeights = map fst detailedCVInfo -- | Compute the mem and disk covariance. compDetailedCV :: [Node.Node] -> [Double] compDetailedCV all_nodes = let (offline, nodes) = partition Node.offline all_nodes mem_l = map Node.pMem nodes dsk_l = map Node.pDsk nodes -- metric: memory covariance mem_cv = stdDev mem_l -- metric: disk covariance dsk_cv = stdDev dsk_l -- metric: count of instances living on N1 failing nodes n1_score = fromIntegral . sum . map (\n -> length (Node.sList n) + length (Node.pList n)) . filter Node.failN1 $ nodes :: Double res_l = map Node.pRem nodes -- metric: reserved memory covariance res_cv = stdDev res_l -- offline instances metrics offline_ipri = sum . map (length . Node.pList) $ offline offline_isec = sum . map (length . Node.sList) $ offline -- metric: count of instances on offline nodes off_score = fromIntegral (offline_ipri + offline_isec)::Double -- metric: count of primary instances on offline nodes (this -- helps with evacuation/failover of primary instances on -- 2-node clusters with one node offline) off_pri_score = fromIntegral offline_ipri::Double cpu_l = map Node.pCpuEff nodes -- metric: covariance of effective vcpu/pcpu ratio cpu_cv = stdDev cpu_l -- metrics: covariance of cpu, memory, disk and network load (c_load, m_load, d_load, n_load) = unzip4 $ map (\n -> let DynUtil c1 m1 d1 n1 = Node.utilLoad n DynUtil c2 m2 d2 n2 = Node.utilPool n in (c1/c2, m1/m2, d1/d2, n1/n2)) nodes -- metric: conflicting instance count pri_tags_inst = sum $ map Node.conflictingPrimaries nodes pri_tags_score = fromIntegral pri_tags_inst::Double -- metric: spindles % spindles_cv = map (\n -> Node.instSpindles n / Node.hiSpindles n) nodes in [ mem_cv, dsk_cv, n1_score, res_cv, off_score, off_pri_score, cpu_cv , stdDev c_load, stdDev m_load , stdDev d_load, stdDev n_load , pri_tags_score, stdDev spindles_cv ] -- | Compute the /total/ variance. compCVNodes :: [Node.Node] -> Double compCVNodes = sum . zipWith (*) detailedCVWeights . compDetailedCV -- | Wrapper over 'compCVNodes' for callers that have a 'Node.List'. compCV :: Node.List -> Double compCV = compCVNodes . Container.elems -- | Compute online nodes from a 'Node.List'. getOnline :: Node.List -> [Node.Node] getOnline = filter (not . Node.offline) . Container.elems -- * Balancing functions -- | Compute best table. Note that the ordering of the arguments is important. compareTables :: Table -> Table -> Table compareTables a@(Table _ _ a_cv _) b@(Table _ _ b_cv _ ) = if a_cv > b_cv then b else a -- | Applies an instance move to a given node list and instance. applyMove :: Node.List -> Instance.Instance -> IMove -> OpResult (Node.List, Instance.Instance, Ndx, Ndx) -- Failover (f) applyMove nl inst Failover = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst new_nl = do -- Maybe monad new_p <- Node.addPriEx (Node.offline old_p) int_s inst new_s <- Node.addSec int_p inst old_sdx let new_inst = Instance.setBoth inst old_sdx old_pdx return (Container.addTwo old_pdx new_s old_sdx new_p nl, new_inst, old_sdx, old_pdx) in new_nl -- Failover to any (fa) applyMove nl inst (FailoverToAny new_pdx) = do let (old_pdx, old_sdx, old_pnode, _) = instanceNodes nl inst new_pnode = Container.find new_pdx nl force_failover = Node.offline old_pnode new_pnode' <- Node.addPriEx force_failover new_pnode inst let old_pnode' = Node.removePri old_pnode inst inst' = Instance.setPri inst new_pdx nl' = Container.addTwo old_pdx old_pnode' new_pdx new_pnode' nl return (nl', inst', new_pdx, old_sdx) -- Replace the primary (f:, r:np, f) applyMove nl inst (ReplacePrimary new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p new_nl = do -- Maybe monad -- check that the current secondary can host the instance -- during the migration tmp_s <- Node.addPriEx force_p int_s inst let tmp_s' = Node.removePri tmp_s inst new_p <- Node.addPriEx force_p tgt_n inst new_s <- Node.addSecEx force_p tmp_s' inst new_pdx let new_inst = Instance.setPri inst new_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx int_p old_sdx new_s nl, new_inst, new_pdx, old_sdx) in new_nl -- Replace the secondary (r:ns) applyMove nl inst (ReplaceSecondary new_sdx) = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_s = Container.find old_sdx nl tgt_n = Container.find new_sdx nl int_s = Node.removeSec old_s inst force_s = Node.offline old_s new_inst = Instance.setSec inst new_sdx new_nl = Node.addSecEx force_s tgt_n inst old_pdx >>= \new_s -> return (Container.addTwo new_sdx new_s old_sdx int_s nl, new_inst, old_pdx, new_sdx) in new_nl -- Replace the secondary and failover (r:np, f) applyMove nl inst (ReplaceAndFailover new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_s = Node.offline old_s new_nl = do -- Maybe monad new_p <- Node.addPri tgt_n inst new_s <- Node.addSecEx force_s int_p inst new_pdx let new_inst = Instance.setBoth inst new_pdx old_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx new_s old_sdx int_s nl, new_inst, new_pdx, old_pdx) in new_nl -- Failver and replace the secondary (f, r:ns) applyMove nl inst (FailoverAndReplace new_sdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_sdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p new_nl = do -- Maybe monad new_p <- Node.addPriEx force_p int_s inst new_s <- Node.addSecEx force_p tgt_n inst old_sdx let new_inst = Instance.setBoth inst old_sdx new_sdx return (Container.add new_sdx new_s $ Container.addTwo old_sdx new_p old_pdx int_p nl, new_inst, old_sdx, new_sdx) in new_nl -- | Tries to allocate an instance on one given node. allocateOnSingle :: Node.List -> Instance.Instance -> Ndx -> OpResult Node.AllocElement allocateOnSingle nl inst new_pdx = let p = Container.find new_pdx nl new_inst = Instance.setBoth inst new_pdx Node.noSecondary in do Instance.instMatchesPolicy inst (Node.iPolicy p) (Node.exclStorage p) new_p <- Node.addPri p inst let new_nl = Container.add new_pdx new_p nl new_score = compCV new_nl return (new_nl, new_inst, [new_p], new_score) -- | Tries to allocate an instance on a given pair of nodes. allocateOnPair :: Node.List -> Instance.Instance -> Ndx -> Ndx -> OpResult Node.AllocElement allocateOnPair nl inst new_pdx new_sdx = let tgt_p = Container.find new_pdx nl tgt_s = Container.find new_sdx nl in do Instance.instMatchesPolicy inst (Node.iPolicy tgt_p) (Node.exclStorage tgt_p) new_p <- Node.addPri tgt_p inst new_s <- Node.addSec tgt_s inst new_pdx let new_inst = Instance.setBoth inst new_pdx new_sdx new_nl = Container.addTwo new_pdx new_p new_sdx new_s nl return (new_nl, new_inst, [new_p, new_s], compCV new_nl) -- | Tries to perform an instance move and returns the best table -- between the original one and the new one. checkSingleStep :: Table -- ^ The original table -> Instance.Instance -- ^ The instance to move -> Table -- ^ The current best table -> IMove -- ^ The move to apply -> Table -- ^ The final best table checkSingleStep ini_tbl target cur_tbl move = let Table ini_nl ini_il _ ini_plc = ini_tbl tmp_resu = applyMove ini_nl target move in case tmp_resu of Bad _ -> cur_tbl Ok (upd_nl, new_inst, pri_idx, sec_idx) -> let tgt_idx = Instance.idx target upd_cvar = compCV upd_nl upd_il = Container.add tgt_idx new_inst ini_il upd_plc = (tgt_idx, pri_idx, sec_idx, move, upd_cvar):ini_plc upd_tbl = Table upd_nl upd_il upd_cvar upd_plc in compareTables cur_tbl upd_tbl -- | Given the status of the current secondary as a valid new node and -- the current candidate target node, generate the possible moves for -- a instance. possibleMoves :: MirrorType -- ^ The mirroring type of the instance -> Bool -- ^ Whether the secondary node is a valid new node -> Bool -- ^ Whether we can change the primary node -> (Bool, Bool) -- ^ Whether migration is restricted and whether -- the instance primary is offline -> Ndx -- ^ Target node candidate -> [IMove] -- ^ List of valid result moves possibleMoves MirrorNone _ _ _ _ = [] possibleMoves MirrorExternal _ False _ _ = [] possibleMoves MirrorExternal _ True _ tdx = [ FailoverToAny tdx ] possibleMoves MirrorInternal _ False _ tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal _ _ (True, False) tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal True True (False, _) tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , ReplacePrimary tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal True True (True, True) tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal False True _ tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx ] -- | Compute the best move for a given instance. checkInstanceMove :: [Ndx] -- ^ Allowed target node indices -> Bool -- ^ Whether disk moves are allowed -> Bool -- ^ Whether instance moves are allowed -> Bool -- ^ Whether migration is restricted -> Table -- ^ Original table -> Instance.Instance -- ^ Instance to move -> Table -- ^ Best new table for this instance checkInstanceMove nodes_idx disk_moves inst_moves rest_mig ini_tbl@(Table nl _ _ _) target = let opdx = Instance.pNode target osdx = Instance.sNode target bad_nodes = [opdx, osdx] nodes = filter (`notElem` bad_nodes) nodes_idx mir_type = Instance.mirrorType target use_secondary = elem osdx nodes_idx && inst_moves aft_failover = if mir_type == MirrorInternal && use_secondary -- if drbd and allowed to failover then checkSingleStep ini_tbl target ini_tbl Failover else ini_tbl primary_drained = Node.offline . flip Container.find nl $ Instance.pNode target all_moves = if disk_moves then concatMap (possibleMoves mir_type use_secondary inst_moves (rest_mig, primary_drained)) nodes else [] in -- iterate over the possible nodes for this instance foldl' (checkSingleStep ini_tbl target) aft_failover all_moves -- | Compute the best next move. checkMove :: [Ndx] -- ^ Allowed target node indices -> Bool -- ^ Whether disk moves are allowed -> Bool -- ^ Whether instance moves are allowed -> Bool -- ^ Whether migration is restricted -> Table -- ^ The current solution -> [Instance.Instance] -- ^ List of instances still to move -> Table -- ^ The new solution checkMove nodes_idx disk_moves inst_moves rest_mig ini_tbl victims = let Table _ _ _ ini_plc = ini_tbl -- we're using rwhnf from the Control.Parallel.Strategies -- package; we don't need to use rnf as that would force too -- much evaluation in single-threaded cases, and in -- multi-threaded case the weak head normal form is enough to -- spark the evaluation tables = parMap rwhnf (checkInstanceMove nodes_idx disk_moves inst_moves rest_mig ini_tbl) victims -- iterate over all instances, computing the best move best_tbl = foldl' compareTables ini_tbl tables Table _ _ _ best_plc = best_tbl in if length best_plc == length ini_plc then ini_tbl -- no advancement else best_tbl -- | Check if we are allowed to go deeper in the balancing. doNextBalance :: Table -- ^ The starting table -> Int -- ^ Remaining length -> Score -- ^ Score at which to stop -> Bool -- ^ The resulting table and commands doNextBalance ini_tbl max_rounds min_score = let Table _ _ ini_cv ini_plc = ini_tbl ini_plc_len = length ini_plc in (max_rounds < 0 || ini_plc_len < max_rounds) && ini_cv > min_score -- | Run a balance move. tryBalance :: Table -- ^ The starting table -> Bool -- ^ Allow disk moves -> Bool -- ^ Allow instance moves -> Bool -- ^ Only evacuate moves -> Bool -- ^ Restrict migration -> Score -- ^ Min gain threshold -> Score -- ^ Min gain -> Maybe Table -- ^ The resulting table and commands tryBalance ini_tbl disk_moves inst_moves evac_mode rest_mig mg_limit min_gain = let Table ini_nl ini_il ini_cv _ = ini_tbl all_inst = Container.elems ini_il all_nodes = Container.elems ini_nl (offline_nodes, online_nodes) = partition Node.offline all_nodes all_inst' = if evac_mode then let bad_nodes = map Node.idx offline_nodes in filter (any (`elem` bad_nodes) . Instance.allNodes) all_inst else all_inst reloc_inst = filter (\i -> Instance.movable i && Instance.autoBalance i) all_inst' node_idx = map Node.idx online_nodes fin_tbl = checkMove node_idx disk_moves inst_moves rest_mig ini_tbl reloc_inst (Table _ _ fin_cv _) = fin_tbl in if fin_cv < ini_cv && (ini_cv > mg_limit || ini_cv - fin_cv >= min_gain) then Just fin_tbl -- this round made success, return the new table else Nothing -- * Allocation functions -- | Build failure stats out of a list of failures. collapseFailures :: [FailMode] -> FailStats collapseFailures flst = map (\k -> (k, foldl' (\a e -> if e == k then a + 1 else a) 0 flst)) [minBound..maxBound] -- | Compares two Maybe AllocElement and chooses the best score. bestAllocElement :: Maybe Node.AllocElement -> Maybe Node.AllocElement -> Maybe Node.AllocElement bestAllocElement a Nothing = a bestAllocElement Nothing b = b bestAllocElement a@(Just (_, _, _, ascore)) b@(Just (_, _, _, bscore)) = if ascore < bscore then a else b -- | Update current Allocation solution and failure stats with new -- elements. concatAllocs :: AllocSolution -> OpResult Node.AllocElement -> AllocSolution concatAllocs as (Bad reason) = as { asFailures = reason : asFailures as } concatAllocs as (Ok ns) = let -- Choose the old or new solution, based on the cluster score cntok = asAllocs as osols = asSolution as nsols = bestAllocElement osols (Just ns) nsuc = cntok + 1 -- Note: we force evaluation of nsols here in order to keep the -- memory profile low - we know that we will need nsols for sure -- in the next cycle, so we force evaluation of nsols, since the -- foldl' in the caller will only evaluate the tuple, but not the -- elements of the tuple in nsols `seq` nsuc `seq` as { asAllocs = nsuc, asSolution = nsols } -- | Sums two 'AllocSolution' structures. sumAllocs :: AllocSolution -> AllocSolution -> AllocSolution sumAllocs (AllocSolution aFails aAllocs aSols aLog) (AllocSolution bFails bAllocs bSols bLog) = -- note: we add b first, since usually it will be smaller; when -- fold'ing, a will grow and grow whereas b is the per-group -- result, hence smaller let nFails = bFails ++ aFails nAllocs = aAllocs + bAllocs nSols = bestAllocElement aSols bSols nLog = bLog ++ aLog in AllocSolution nFails nAllocs nSols nLog -- | Given a solution, generates a reasonable description for it. describeSolution :: AllocSolution -> String describeSolution as = let fcnt = asFailures as sols = asSolution as freasons = intercalate ", " . map (\(a, b) -> printf "%s: %d" (show a) b) . filter ((> 0) . snd) . collapseFailures $ fcnt in case sols of Nothing -> "No valid allocation solutions, failure reasons: " ++ (if null fcnt then "unknown reasons" else freasons) Just (_, _, nodes, cv) -> printf ("score: %.8f, successes %d, failures %d (%s)" ++ " for node(s) %s") cv (asAllocs as) (length fcnt) freasons (intercalate "/" . map Node.name $ nodes) -- | Annotates a solution with the appropriate string. annotateSolution :: AllocSolution -> AllocSolution annotateSolution as = as { asLog = describeSolution as : asLog as } -- | Reverses an evacuation solution. -- -- Rationale: we always concat the results to the top of the lists, so -- for proper jobset execution, we should reverse all lists. reverseEvacSolution :: EvacSolution -> EvacSolution reverseEvacSolution (EvacSolution f m o) = EvacSolution (reverse f) (reverse m) (reverse o) -- | Generate the valid node allocation singles or pairs for a new instance. genAllocNodes :: Group.List -- ^ Group list -> Node.List -- ^ The node map -> Int -- ^ The number of nodes required -> Bool -- ^ Whether to drop or not -- unallocable nodes -> Result AllocNodes -- ^ The (monadic) result genAllocNodes gl nl count drop_unalloc = let filter_fn = if drop_unalloc then filter (Group.isAllocable . flip Container.find gl . Node.group) else id all_nodes = filter_fn $ getOnline nl all_pairs = [(Node.idx p, [Node.idx s | s <- all_nodes, Node.idx p /= Node.idx s, Node.group p == Node.group s]) | p <- all_nodes] in case count of 1 -> Ok (Left (map Node.idx all_nodes)) 2 -> Ok (Right (filter (not . null . snd) all_pairs)) _ -> Bad "Unsupported number of nodes, only one or two supported" -- | Try to allocate an instance on the cluster. tryAlloc :: (Monad m) => Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> AllocNodes -- ^ The allocation targets -> m AllocSolution -- ^ Possible solution list tryAlloc _ _ _ (Right []) = fail "Not enough online nodes" tryAlloc nl _ inst (Right ok_pairs) = let psols = parMap rwhnf (\(p, ss) -> foldl' (\cstate -> concatAllocs cstate . allocateOnPair nl inst p) emptyAllocSolution ss) ok_pairs sols = foldl' sumAllocs emptyAllocSolution psols in return $ annotateSolution sols tryAlloc _ _ _ (Left []) = fail "No online nodes" tryAlloc nl _ inst (Left all_nodes) = let sols = foldl' (\cstate -> concatAllocs cstate . allocateOnSingle nl inst ) emptyAllocSolution all_nodes in return $ annotateSolution sols -- | Given a group/result, describe it as a nice (list of) messages. solutionDescription :: (Group.Group, Result AllocSolution) -> [String] solutionDescription (grp, result) = case result of Ok solution -> map (printf "Group %s (%s): %s" gname pol) (asLog solution) Bad message -> [printf "Group %s: error %s" gname message] where gname = Group.name grp pol = allocPolicyToRaw (Group.allocPolicy grp) -- | From a list of possibly bad and possibly empty solutions, filter -- only the groups with a valid result. Note that the result will be -- reversed compared to the original list. filterMGResults :: [(Group.Group, Result AllocSolution)] -> [(Group.Group, AllocSolution)] filterMGResults = foldl' fn [] where unallocable = not . Group.isAllocable fn accu (grp, rasol) = case rasol of Bad _ -> accu Ok sol | isNothing (asSolution sol) -> accu | unallocable grp -> accu | otherwise -> (grp, sol):accu -- | Sort multigroup results based on policy and score. sortMGResults :: [(Group.Group, AllocSolution)] -> [(Group.Group, AllocSolution)] sortMGResults sols = let extractScore (_, _, _, x) = x solScore (grp, sol) = (Group.allocPolicy grp, (extractScore . fromJust . asSolution) sol) in sortBy (comparing solScore) sols -- | Removes node groups which can't accommodate the instance filterValidGroups :: [(Group.Group, (Node.List, Instance.List))] -> Instance.Instance -> ([(Group.Group, (Node.List, Instance.List))], [String]) filterValidGroups [] _ = ([], []) filterValidGroups (ng:ngs) inst = let (valid_ngs, msgs) = filterValidGroups ngs inst hasNetwork nic = case Nic.network nic of Just net -> net `elem` Group.networks (fst ng) Nothing -> True hasRequiredNetworks = all hasNetwork (Instance.nics inst) in if hasRequiredNetworks then (ng:valid_ngs, msgs) else (valid_ngs, ("group " ++ Group.name (fst ng) ++ " is not connected to a network required by instance " ++ Instance.name inst):msgs) -- | Finds the best group for an instance on a multi-group cluster. -- -- Only solutions in @preferred@ and @last_resort@ groups will be -- accepted as valid, and additionally if the allowed groups parameter -- is not null then allocation will only be run for those group -- indices. findBestAllocGroup :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Maybe [Gdx] -- ^ The allowed groups -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result (Group.Group, AllocSolution, [String]) findBestAllocGroup mggl mgnl mgil allowed_gdxs inst cnt = let groups_by_idx = splitCluster mgnl mgil groups = map (\(gid, d) -> (Container.find gid mggl, d)) groups_by_idx groups' = maybe groups (\gs -> filter ((`elem` gs) . Group.idx . fst) groups) allowed_gdxs (groups'', filter_group_msgs) = filterValidGroups groups' inst sols = map (\(gr, (nl, il)) -> (gr, genAllocNodes mggl nl cnt False >>= tryAlloc nl il inst)) groups''::[(Group.Group, Result AllocSolution)] all_msgs = filter_group_msgs ++ concatMap solutionDescription sols goodSols = filterMGResults sols sortedSols = sortMGResults goodSols in case sortedSols of [] -> Bad $ if null groups' then "no groups for evacuation: allowed groups was" ++ show allowed_gdxs ++ ", all groups: " ++ show (map fst groups) else intercalate ", " all_msgs (final_group, final_sol):_ -> return (final_group, final_sol, all_msgs) -- | Try to allocate an instance on a multi-group cluster. tryMGAlloc :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result AllocSolution -- ^ Possible solution list tryMGAlloc mggl mgnl mgil inst cnt = do (best_group, solution, all_msgs) <- findBestAllocGroup mggl mgnl mgil Nothing inst cnt let group_name = Group.name best_group selmsg = "Selected group: " ++ group_name return $ solution { asLog = selmsg:all_msgs } -- | Calculate the new instance list after allocation solution. updateIl :: Instance.List -- ^ The original instance list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Instance.List -- ^ The updated instance list updateIl il Nothing = il updateIl il (Just (_, xi, _, _)) = Container.add (Container.size il) xi il -- | Extract the the new node list from the allocation solution. extractNl :: Node.List -- ^ The original node list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Node.List -- ^ The new node list extractNl nl Nothing = nl extractNl _ (Just (xnl, _, _, _)) = xnl -- | Try to allocate a list of instances on a multi-group cluster. allocList :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> [(Instance.Instance, Int)] -- ^ The instance to allocate -> AllocSolutionList -- ^ Possible solution list -> Result (Node.List, Instance.List, AllocSolutionList) -- ^ The final solution list allocList _ nl il [] result = Ok (nl, il, result) allocList gl nl il ((xi, xicnt):xies) result = do ares <- tryMGAlloc gl nl il xi xicnt let sol = asSolution ares nl' = extractNl nl sol il' = updateIl il sol allocList gl nl' il' xies ((xi, ares):result) -- | Function which fails if the requested mode is change secondary. -- -- This is useful since except DRBD, no other disk template can -- execute change secondary; thus, we can just call this function -- instead of always checking for secondary mode. After the call to -- this function, whatever mode we have is just a primary change. failOnSecondaryChange :: (Monad m) => EvacMode -> DiskTemplate -> m () failOnSecondaryChange ChangeSecondary dt = fail $ "Instances with disk template '" ++ diskTemplateToRaw dt ++ "' can't execute change secondary" failOnSecondaryChange _ _ = return () -- | Run evacuation for a single instance. -- -- /Note:/ this function should correctly execute both intra-group -- evacuations (in all modes) and inter-group evacuations (in the -- 'ChangeAll' mode). Of course, this requires that the correct list -- of target nodes is passed. nodeEvacInstance :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTDiskless}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTPlain}) _ _ = fail "Instances of type plain cannot be relocated" nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTFile}) _ _ = fail "Instances of type file cannot be relocated" nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTSharedFile}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTBlock}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTRbd}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTExt}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTGluster}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il ChangePrimary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) _ _ = do (nl', inst', _, _) <- opToResult $ applyMove nl inst Failover let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx Failover return (nl', il', ops) nodeEvacInstance nl il ChangeSecondary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = evacOneNodeOnly nl il inst gdx avail_nodes -- The algorithm for ChangeAll is as follows: -- -- * generate all (primary, secondary) node pairs for the target groups -- * for each pair, execute the needed moves (r:s, f, r:s) and compute -- the final node list state and group score -- * select the best choice via a foldl that uses the same Either -- String solution as the ChangeSecondary mode nodeEvacInstance nl il ChangeAll inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = do let no_nodes = Left "no nodes available" node_pairs = [(p,s) | p <- avail_nodes, s <- avail_nodes, p /= s] (nl', il', ops, _) <- annotateResult "Can't find any good nodes for relocation" . eitherToResult $ foldl' (\accu nodes -> case evacDrbdAllInner nl il inst gdx nodes of Bad msg -> case accu of Right _ -> accu -- we don't need more details (which -- nodes, etc.) as we only selected -- this group if we can allocate on -- it, hence failures will not -- propagate out of this fold loop Left _ -> Left $ "Allocation failed: " ++ msg Ok result@(_, _, _, new_cv) -> let new_accu = Right result in case accu of Left _ -> new_accu Right (_, _, _, old_cv) -> if old_cv < new_cv then accu else new_accu ) no_nodes node_pairs return (nl', il', ops) -- | Generic function for changing one node of an instance. -- -- This is similar to 'nodeEvacInstance' but will be used in a few of -- its sub-patterns. It folds the inner function 'evacOneNodeInner' -- over the list of available nodes, which results in the best choice -- for relocation. evacOneNodeOnly :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) evacOneNodeOnly nl il inst gdx avail_nodes = do op_fn <- case Instance.mirrorType inst of MirrorNone -> Bad "Can't relocate/evacuate non-mirrored instances" MirrorInternal -> Ok ReplaceSecondary MirrorExternal -> Ok FailoverToAny (nl', inst', _, ndx) <- annotateResult "Can't find any good node" . eitherToResult $ foldl' (evacOneNodeInner nl inst gdx op_fn) (Left "no nodes available") avail_nodes let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx (op_fn ndx) return (nl', il', ops) -- | Inner fold function for changing one node of an instance. -- -- Depending on the instance disk template, this will either change -- the secondary (for DRBD) or the primary node (for shared -- storage). However, the operation is generic otherwise. -- -- The running solution is either a @Left String@, which means we -- don't have yet a working solution, or a @Right (...)@, which -- represents a valid solution; it holds the modified node list, the -- modified instance (after evacuation), the score of that solution, -- and the new secondary node index. evacOneNodeInner :: Node.List -- ^ Cluster node list -> Instance.Instance -- ^ Instance being evacuated -> Gdx -- ^ The group index of the instance -> (Ndx -> IMove) -- ^ Operation constructor -> EvacInnerState -- ^ Current best solution -> Ndx -- ^ Node we're evaluating as target -> EvacInnerState -- ^ New best solution evacOneNodeInner nl inst gdx op_fn accu ndx = case applyMove nl inst (op_fn ndx) of Bad fm -> let fail_msg = "Node " ++ Container.nameOf nl ndx ++ " failed: " ++ show fm in either (const $ Left fail_msg) (const accu) accu Ok (nl', inst', _, _) -> let nodes = Container.elems nl' -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes new_accu = Right (nl', inst', new_cv, ndx) in case accu of Left _ -> new_accu Right (_, _, old_cv, _) -> if old_cv < new_cv then accu else new_accu -- | Compute result of changing all nodes of a DRBD instance. -- -- Given the target primary and secondary node (which might be in a -- different group or not), this function will 'execute' all the -- required steps and assuming all operations succceed, will return -- the modified node and instance lists, the opcodes needed for this -- and the new group score. evacDrbdAllInner :: Node.List -- ^ Cluster node list -> Instance.List -- ^ Cluster instance list -> Instance.Instance -- ^ The instance to be moved -> Gdx -- ^ The target group index -- (which can differ from the -- current group of the -- instance) -> (Ndx, Ndx) -- ^ Tuple of new -- primary\/secondary nodes -> Result (Node.List, Instance.List, [OpCodes.OpCode], Score) evacDrbdAllInner nl il inst gdx (t_pdx, t_sdx) = do let primary = Container.find (Instance.pNode inst) nl idx = Instance.idx inst -- if the primary is offline, then we first failover (nl1, inst1, ops1) <- if Node.offline primary then do (nl', inst', _, _) <- annotateResult "Failing over to the secondary" . opToResult $ applyMove nl inst Failover return (nl', inst', [Failover]) else return (nl, inst, []) let (o1, o2, o3) = (ReplaceSecondary t_pdx, Failover, ReplaceSecondary t_sdx) -- we now need to execute a replace secondary to the future -- primary node (nl2, inst2, _, _) <- annotateResult "Changing secondary to new primary" . opToResult $ applyMove nl1 inst1 o1 let ops2 = o1:ops1 -- we now execute another failover, the primary stays fixed now (nl3, inst3, _, _) <- annotateResult "Failing over to new primary" . opToResult $ applyMove nl2 inst2 o2 let ops3 = o2:ops2 -- and finally another replace secondary, to the final secondary (nl4, inst4, _, _) <- annotateResult "Changing secondary to final secondary" . opToResult $ applyMove nl3 inst3 o3 let ops4 = o3:ops3 il' = Container.add idx inst4 il ops = concatMap (iMoveToJob nl4 il' idx) $ reverse ops4 let nodes = Container.elems nl4 -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes return (nl4, il', ops, new_cv) -- | Computes the nodes in a given group which are available for -- allocation. availableGroupNodes :: [(Gdx, [Ndx])] -- ^ Group index/node index assoc list -> IntSet.IntSet -- ^ Nodes that are excluded -> Gdx -- ^ The group for which we -- query the nodes -> Result [Ndx] -- ^ List of available node indices availableGroupNodes group_nodes excl_ndx gdx = do local_nodes <- maybe (Bad $ "Can't find group with index " ++ show gdx) Ok (lookup gdx group_nodes) let avail_nodes = filter (not . flip IntSet.member excl_ndx) local_nodes return avail_nodes -- | Updates the evac solution with the results of an instance -- evacuation. updateEvacSolution :: (Node.List, Instance.List, EvacSolution) -> Idx -> Result (Node.List, Instance.List, [OpCodes.OpCode]) -> (Node.List, Instance.List, EvacSolution) updateEvacSolution (nl, il, es) idx (Bad msg) = (nl, il, es { esFailed = (idx, msg):esFailed es}) updateEvacSolution (_, _, es) idx (Ok (nl, il, opcodes)) = (nl, il, es { esMoved = new_elem:esMoved es , esOpCodes = opcodes:esOpCodes es }) where inst = Container.find idx il new_elem = (idx, instancePriGroup nl inst, Instance.allNodes inst) -- | Node-evacuation IAllocator mode main function. tryNodeEvac :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide, not per group) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryNodeEvac _ ini_nl ini_il mode idxs = let evac_ndx = nodesToEvacuate ini_il mode idxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) evac_ndx offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let gdx = instancePriGroup nl inst pdx = Instance.pNode inst in updateEvacSolution state (Instance.idx inst) $ availableGroupNodes group_ndx (IntSet.insert pdx excl_ndx) gdx >>= nodeEvacInstance nl il mode inst gdx ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Change-group IAllocator mode main function. -- -- This is very similar to 'tryNodeEvac', the only difference is that -- we don't choose as target group the current instance group, but -- instead: -- -- 1. at the start of the function, we compute which are the target -- groups; either no groups were passed in, in which case we choose -- all groups out of which we don't evacuate instance, or there were -- some groups passed, in which case we use those -- -- 2. for each instance, we use 'findBestAllocGroup' to choose the -- best group to hold the instance, and then we do what -- 'tryNodeEvac' does, except for this group instead of the current -- instance group. -- -- Note that the correct behaviour of this function relies on the -- function 'nodeEvacInstance' to be able to do correctly both -- intra-group and inter-group moves when passed the 'ChangeAll' mode. tryChangeGroup :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> [Gdx] -- ^ Target groups; if empty, any -- groups not being evacuated -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryChangeGroup gl ini_nl ini_il gdxs idxs = let evac_gdxs = nub $ map (instancePriGroup ini_nl . flip Container.find ini_il) idxs target_gdxs = (if null gdxs then Container.keys gl else gdxs) \\ evac_gdxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) IntSet.empty offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let solution = do let ncnt = Instance.requiredNodes $ Instance.diskTemplate inst (grp, _, _) <- findBestAllocGroup gl nl il (Just target_gdxs) inst ncnt let gdx = Group.idx grp av_nodes <- availableGroupNodes group_ndx excl_ndx gdx nodeEvacInstance nl il ChangeAll inst gdx av_nodes in updateEvacSolution state (Instance.idx inst) solution ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Standard-sized allocation method. -- -- This places instances of the same size on the cluster until we're -- out of space. The result will be a list of identically-sized -- instances. iterateAlloc :: AllocMethod iterateAlloc nl il limit newinst allocnodes ixes cstats = let depth = length ixes newname = printf "new-%d" depth::String newidx = Container.size il newi2 = Instance.setIdx (Instance.setName newinst newname) newidx newlimit = fmap (flip (-) 1) limit in case tryAlloc nl il newi2 allocnodes of Bad s -> Bad s Ok (AllocSolution { asFailures = errs, asSolution = sols3 }) -> let newsol = Ok (collapseFailures errs, nl, il, ixes, cstats) in case sols3 of Nothing -> newsol Just (xnl, xi, _, _) -> if limit == Just 0 then newsol else iterateAlloc xnl (Container.add newidx xi il) newlimit newinst allocnodes (xi:ixes) (totalResources xnl:cstats) -- | Predicate whether shrinking a single resource can lead to a valid -- allocation. sufficesShrinking :: (Instance.Instance -> AllocSolution) -> Instance.Instance -> FailMode -> Maybe Instance.Instance sufficesShrinking allocFn inst fm = case dropWhile (isNothing . asSolution . fst) . takeWhile (liftA2 (||) (elem fm . asFailures . fst) (isJust . asSolution . fst)) . map (allocFn &&& id) $ iterateOk (`Instance.shrinkByType` fm) inst of x:_ -> Just . snd $ x _ -> Nothing -- | Tiered allocation method. -- -- This places instances on the cluster, and decreases the spec until -- we can allocate again. The result will be a list of decreasing -- instance specs. tieredAlloc :: AllocMethod tieredAlloc nl il limit newinst allocnodes ixes cstats = case iterateAlloc nl il limit newinst allocnodes ixes cstats of Bad s -> Bad s Ok (errs, nl', il', ixes', cstats') -> let newsol = Ok (errs, nl', il', ixes', cstats') ixes_cnt = length ixes' (stop, newlimit) = case limit of Nothing -> (False, Nothing) Just n -> (n <= ixes_cnt, Just (n - ixes_cnt)) sortedErrs = map fst $ sortBy (comparing snd) errs suffShrink = sufficesShrinking (fromMaybe emptyAllocSolution . flip (tryAlloc nl' il') allocnodes) newinst bigSteps = filter isJust . map suffShrink . reverse $ sortedErrs in if stop then newsol else case bigSteps of Just newinst':_ -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' _ -> case Instance.shrinkByType newinst . last $ sortedErrs of Bad _ -> newsol Ok newinst' -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' -- * Formatting functions -- | Given the original and final nodes, computes the relocation description. computeMoves :: Instance.Instance -- ^ The instance to be moved -> String -- ^ The instance name -> IMove -- ^ The move being performed -> String -- ^ New primary -> String -- ^ New secondary -> (String, [String]) -- ^ Tuple of moves and commands list; moves is containing -- either @/f/@ for failover or @/r:name/@ for replace -- secondary, while the command list holds gnt-instance -- commands (without that prefix), e.g \"@failover instance1@\" computeMoves i inam mv c d = case mv of Failover -> ("f", [mig]) FailoverToAny _ -> (printf "fa:%s" c, [mig_any]) FailoverAndReplace _ -> (printf "f r:%s" d, [mig, rep d]) ReplaceSecondary _ -> (printf "r:%s" d, [rep d]) ReplaceAndFailover _ -> (printf "r:%s f" c, [rep c, mig]) ReplacePrimary _ -> (printf "f r:%s f" c, [mig, rep c, mig]) where morf = if Instance.isRunning i then "migrate" else "failover" mig = printf "%s -f %s" morf inam::String mig_any = printf "%s -f -n %s %s" morf c inam::String rep n = printf "replace-disks -n %s %s" n inam::String -- | Converts a placement to string format. printSolutionLine :: Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Int -- ^ Maximum node name length -> Int -- ^ Maximum instance name length -> Placement -- ^ The current placement -> Int -- ^ The index of the placement in -- the solution -> (String, [String]) printSolutionLine nl il nmlen imlen plc pos = let pmlen = (2*nmlen + 1) (i, p, s, mv, c) = plc old_sec = Instance.sNode inst inst = Container.find i il inam = Instance.alias inst npri = Node.alias $ Container.find p nl nsec = Node.alias $ Container.find s nl opri = Node.alias $ Container.find (Instance.pNode inst) nl osec = Node.alias $ Container.find old_sec nl (moves, cmds) = computeMoves inst inam mv npri nsec -- FIXME: this should check instead/also the disk template ostr = if old_sec == Node.noSecondary then printf "%s" opri::String else printf "%s:%s" opri osec::String nstr = if s == Node.noSecondary then printf "%s" npri::String else printf "%s:%s" npri nsec::String in (printf " %3d. %-*s %-*s => %-*s %12.8f a=%s" pos imlen inam pmlen ostr pmlen nstr c moves, cmds) -- | Return the instance and involved nodes in an instance move. -- -- Note that the output list length can vary, and is not required nor -- guaranteed to be of any specific length. involvedNodes :: Instance.List -- ^ Instance list, used for retrieving -- the instance from its index; note -- that this /must/ be the original -- instance list, so that we can -- retrieve the old nodes -> Placement -- ^ The placement we're investigating, -- containing the new nodes and -- instance index -> [Ndx] -- ^ Resulting list of node indices involvedNodes il plc = let (i, np, ns, _, _) = plc inst = Container.find i il in nub . filter (>= 0) $ [np, ns] ++ Instance.allNodes inst -- | From two adjacent cluster tables get the list of moves that transitions -- from to the other getMoves :: (Table, Table) -> [MoveJob] getMoves (Table _ initial_il _ initial_plc, Table final_nl _ _ final_plc) = let plctoMoves (plc@(idx, p, s, mv, _)) = let inst = Container.find idx initial_il inst_name = Instance.name inst affected = involvedNodes initial_il plc np = Node.alias $ Container.find p final_nl ns = Node.alias $ Container.find s final_nl (_, cmds) = computeMoves inst inst_name mv np ns in (affected, idx, mv, cmds) in map plctoMoves . reverse . drop (length initial_plc) $ reverse final_plc -- | Inner function for splitJobs, that either appends the next job to -- the current jobset, or starts a new jobset. mergeJobs :: ([JobSet], [Ndx]) -> MoveJob -> ([JobSet], [Ndx]) mergeJobs ([], _) n@(ndx, _, _, _) = ([[n]], ndx) mergeJobs (cjs@(j:js), nbuf) n@(ndx, _, _, _) | null (ndx `intersect` nbuf) = ((n:j):js, ndx ++ nbuf) | otherwise = ([n]:cjs, ndx) -- | Break a list of moves into independent groups. Note that this -- will reverse the order of jobs. splitJobs :: [MoveJob] -> [JobSet] splitJobs = fst . foldl mergeJobs ([], []) -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatJob :: Int -> Int -> (Int, MoveJob) -> [String] formatJob jsn jsl (sn, (_, _, _, cmds)) = let out = printf " echo job %d/%d" jsn sn: printf " check": map (" gnt-instance " ++) cmds in if sn == 1 then ["", printf "echo jobset %d, %d jobs" jsn jsl] ++ out else out -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatCmds :: [JobSet] -> String formatCmds = unlines . concatMap (\(jsn, js) -> concatMap (formatJob jsn (length js)) (zip [1..] js)) . zip [1..] -- | Print the node list. printNodes :: Node.List -> [String] -> String printNodes nl fs = let fields = case fs of [] -> Node.defaultFields "+":rest -> Node.defaultFields ++ rest _ -> fs snl = sortBy (comparing Node.idx) (Container.elems nl) (header, isnum) = unzip $ map Node.showHeader fields in printTable "" header (map (Node.list fields) snl) isnum -- | Print the instance list. printInsts :: Node.List -> Instance.List -> String printInsts nl il = let sil = sortBy (comparing Instance.idx) (Container.elems il) helper inst = [ if Instance.isRunning inst then "R" else " " , Instance.name inst , Container.nameOf nl (Instance.pNode inst) , let sdx = Instance.sNode inst in if sdx == Node.noSecondary then "" else Container.nameOf nl sdx , if Instance.autoBalance inst then "Y" else "N" , printf "%3d" $ Instance.vcpus inst , printf "%5d" $ Instance.mem inst , printf "%5d" $ Instance.dsk inst `div` 1024 , printf "%5.3f" lC , printf "%5.3f" lM , printf "%5.3f" lD , printf "%5.3f" lN ] where DynUtil lC lM lD lN = Instance.util inst header = [ "F", "Name", "Pri_node", "Sec_node", "Auto_bal" , "vcpu", "mem" , "dsk", "lCpu", "lMem", "lDsk", "lNet" ] isnum = False:False:False:False:False:repeat True in printTable "" header (map helper sil) isnum -- | Shows statistics for a given node list. printStats :: String -> Node.List -> String printStats lp nl = let dcvs = compDetailedCV $ Container.elems nl (weights, names) = unzip detailedCVInfo hd = zip3 (weights ++ repeat 1) (names ++ repeat "unknown") dcvs header = [ "Field", "Value", "Weight" ] formatted = map (\(w, h, val) -> [ h , printf "%.8f" val , printf "x%.2f" w ]) hd in printTable lp header formatted $ False:repeat True -- | Convert a placement into a list of OpCodes (basically a job). iMoveToJob :: Node.List -- ^ The node list; only used for node -- names, so any version is good -- (before or after the operation) -> Instance.List -- ^ The instance list; also used for -- names only -> Idx -- ^ The index of the instance being -- moved -> IMove -- ^ The actual move to be described -> [OpCodes.OpCode] -- ^ The list of opcodes equivalent to -- the given move iMoveToJob nl il idx move = let inst = Container.find idx il iname = Instance.name inst lookNode n = case mkNonEmpty (Container.nameOf nl n) of -- FIXME: convert htools codebase to non-empty strings Bad msg -> error $ "Empty node name for idx " ++ show n ++ ": " ++ msg ++ "??" Ok ne -> Just ne opF = OpCodes.OpInstanceMigrate { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opMigrationMode = Nothing -- default , OpCodes.opOldLiveMode = Nothing -- default as well , OpCodes.opTargetNode = Nothing -- this is drbd , OpCodes.opTargetNodeUuid = Nothing , OpCodes.opAllowRuntimeChanges = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opMigrationCleanup = False , OpCodes.opIallocator = Nothing , OpCodes.opAllowFailover = True } opFA n = opF { OpCodes.opTargetNode = lookNode n } -- not drbd opR n = OpCodes.OpInstanceReplaceDisks { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opEarlyRelease = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opReplaceDisksMode = OpCodes.ReplaceNewSecondary , OpCodes.opReplaceDisksList = [] , OpCodes.opRemoteNode = lookNode n , OpCodes.opRemoteNodeUuid = Nothing , OpCodes.opIallocator = Nothing } in case move of Failover -> [ opF ] FailoverToAny np -> [ opFA np ] ReplacePrimary np -> [ opF, opR np, opF ] ReplaceSecondary ns -> [ opR ns ] ReplaceAndFailover np -> [ opR np, opF ] FailoverAndReplace ns -> [ opF, opR ns ] -- * Node group functions -- | Computes the group of an instance. instanceGroup :: Node.List -> Instance.Instance -> Result Gdx instanceGroup nl i = let sidx = Instance.sNode i pnode = Container.find (Instance.pNode i) nl snode = if sidx == Node.noSecondary then pnode else Container.find sidx nl pgroup = Node.group pnode sgroup = Node.group snode in if pgroup /= sgroup then fail ("Instance placed accross two node groups, primary " ++ show pgroup ++ ", secondary " ++ show sgroup) else return pgroup -- | Computes the group of an instance per the primary node. instancePriGroup :: Node.List -> Instance.Instance -> Gdx instancePriGroup nl i = let pnode = Container.find (Instance.pNode i) nl in Node.group pnode -- | Compute the list of badly allocated instances (split across node -- groups). findSplitInstances :: Node.List -> Instance.List -> [Instance.Instance] findSplitInstances nl = filter (not . isOk . instanceGroup nl) . Container.elems -- | Splits a cluster into the component node groups. splitCluster :: Node.List -> Instance.List -> [(Gdx, (Node.List, Instance.List))] splitCluster nl il = let ngroups = Node.computeGroups (Container.elems nl) in map (\(gdx, nodes) -> let nidxs = map Node.idx nodes nodes' = zip nidxs nodes instances = Container.filter ((`elem` nidxs) . Instance.pNode) il in (gdx, (Container.fromList nodes', instances))) ngroups -- | Compute the list of nodes that are to be evacuated, given a list -- of instances and an evacuation mode. nodesToEvacuate :: Instance.List -- ^ The cluster-wide instance list -> EvacMode -- ^ The evacuation mode we're using -> [Idx] -- ^ List of instance indices being evacuated -> IntSet.IntSet -- ^ Set of node indices nodesToEvacuate il mode = IntSet.delete Node.noSecondary . foldl' (\ns idx -> let i = Container.find idx il pdx = Instance.pNode i sdx = Instance.sNode i dt = Instance.diskTemplate i withSecondary = case dt of DTDrbd8 -> IntSet.insert sdx ns _ -> ns in case mode of ChangePrimary -> IntSet.insert pdx ns ChangeSecondary -> withSecondary ChangeAll -> IntSet.insert pdx withSecondary ) IntSet.empty
kawamuray/ganeti
src/Ganeti/HTools/Cluster.hs
gpl-2.0
73,805
1
23
23,395
15,964
8,647
7,317
1,200
7
{-# LANGUAGE RecordWildCards #-} module Capture.X11 where import Data import Graphics.X11 import Graphics.X11.Xlib.Extras import Control.Monad import Control.Exception (bracket) import System.IO.Error (catchIOError) import Control.Applicative import Data.Maybe import Data.Time.Clock import System.IO import qualified Data.MyText as T import System.Locale.SetLocale import Graphics.X11.XScreenSaver (getXIdleTime, compiledWithXScreenSaver) setupCapture :: IO () setupCapture = do loc <- supportsLocale unless loc $ hPutStrLn stderr "arbtt [Warning]: locale unsupported" dpy <- openDisplay "" xSetErrorHandler let rwin = defaultRootWindow dpy a <- internAtom dpy "_NET_CLIENT_LIST" False p <- getWindowProperty32 dpy a rwin when (isNothing p) $ do hPutStrLn stderr "arbtt: ERROR: No _NET_CLIENT_LIST set for the root window" closeDisplay dpy captureData :: IO CaptureData captureData = do dpy <- openDisplay "" xSetErrorHandler let rwin = defaultRootWindow dpy -- Desktop desktop <- getDesktops dpy current_desktop <- desktop <$> getDesktop "_NET_CURRENT_DESKTOP" dpy rwin -- Windows a <- internAtom dpy "_NET_CLIENT_LIST" False p <- getWindowProperty32 dpy a rwin wins <- case p of Just wins -> filterM (isInteresting dpy) (map fromIntegral wins) Nothing -> return [] (fsubwin,_) <- getInputFocus dpy fwin <- followTreeUntil dpy (`elem` wins) fsubwin winData <- forM wins $ \w -> do let wActive = w == fwin wHidden <- isHidden dpy w wTitle <- T.pack <$> getWindowTitle dpy w wProgram <- T.pack <$> getProgramName dpy w wDesktop <- T.pack . desktop <$> getDesktop "_NET_WM_DESKTOP" dpy w return WindowData{..} it <- fromIntegral `fmap` getXIdleTime dpy closeDisplay dpy return $ CaptureData winData it (T.pack current_desktop) getWindowTitle :: Display -> Window -> IO String getWindowTitle dpy = myFetchName dpy getProgramName :: Display -> Window -> IO String getProgramName dpy = fmap resName . getClassHint dpy -- Returns a parent of a window or zero. getParent :: Display -> Window -> IO Window getParent dpy w = do (_, parent, _) <- queryTree dpy w `catchIOError` (const $ return (0,0,[])) return parent -- | Follows the tree of windows up until the condition is met or the root -- window is reached. followTreeUntil :: Display -> (Window -> Bool) -> Window -> IO Window followTreeUntil dpy cond = go where go w | cond w = return w | otherwise = do p <- getParent dpy w if p == 0 then return w else go p -- | Ignore, for example, Desktop and Docks windows isInteresting :: Display -> Window -> IO Bool isInteresting d w = do a <- internAtom d "_NET_WM_WINDOW_TYPE" False dock <- internAtom d "_NET_WM_WINDOW_TYPE_DOCK" False desk <- internAtom d "_NET_WM_WINDOW_TYPE_DESKTOP" False mbr <- getWindowProperty32 d a w case mbr of Just [r] -> return $ fromIntegral r `notElem` [dock, desk] _ -> return True -- | better than fetchName from X11, as it supports _NET_WM_NAME and unicode -- -- Code taken from XMonad.Managehook.title myFetchName :: Display -> Window -> IO String myFetchName d w = do let getProp = (internAtom d "_NET_WM_NAME" False >>= getTextProperty d w) `catchIOError` (\_ -> getTextProperty d w wM_NAME) extract prop = do l <- wcTextPropertyToTextList d prop return $ if null l then "" else head l bracket getProp (xFree . tp_value) extract `catchIOError` \_ -> return "" getDesktops :: Display -> IO (Maybe Int -> String) getDesktops dpy = do desktops <- flip catchIOError (\_ -> return []) $ do a <- internAtom dpy "_NET_DESKTOP_NAMES" False tp <- getTextProperty dpy (defaultRootWindow dpy) a dropTailNull <$> wcTextPropertyToTextList dpy tp let name n | 0 <= n && n < length desktops = desktops !! n | otherwise = show n return $ maybe "" name where -- _NET_DESKTOP_NAMES is a list of NULL-terminated strings but -- wcTextPropertyToTextList treats NULL as a separator, -- so we need to drop the final empty string dropTailNull [""] = [] dropTailNull (x:xs) = x : dropTailNull xs getDesktop :: String -> Display -> Window -> IO (Maybe Int) getDesktop prop dpy w = flip catchIOError (\_ -> return Nothing) $ do a <- internAtom dpy prop False p <- getWindowProperty32 dpy a w return $ do {[d] <- p; return (fromIntegral d)} isHidden :: Display -> Window -> IO Bool isHidden dpy w = flip catchIOError (\_ -> return False) $ do a <- internAtom dpy "WM_STATE" False Just (state:_) <- getWindowProperty32 dpy a w return $ fromIntegral state /= normalState
nomeata/darcs-mirror-arbtt
src/Capture/X11.hs
gpl-2.0
5,089
0
15
1,412
1,505
730
775
105
2
{- Piffle, Copyright (C) 2007, Jaap Weel. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} -- COMPILER MONAD ---------------------------------------------------- {- This module does various sorts of behind-the-scenes heavy lifting in the form of a monad in which all compiler passes are run. This includes including logging, keeping track of the position in the source, and recording error messages. -} module Compiler ( runCompiler, prettyFaultWithQuote, prettyLogMessages, Compiler, fault, die, logMessage, thisPosition, whatPosition, getConfig ) where import Control.Monad.Error import Control.Monad.Identity import Control.Monad.Writer import Control.Monad.Reader import Control.Monad.State import Text.ParserCombinators.Parsec.Error import Position import Configure import PrettyUtil import PrettyPP -- ERROR MONAD ------------------------------------------------------- type LoggingT = WriterT [LogEntry] type FaultyT = ErrorT Fault type PositionalT = StateT Pos type ConfiguredT = ReaderT Config type Compiler a = ConfiguredT (PositionalT (FaultyT (LoggingT Identity))) a runCompiler :: Pos -> Config -> Compiler a -> (Either Fault a, [LogEntry]) runCompiler initialPos config compiler = let configured = runReaderT compiler config in let positional = runStateT configured initialPos in let faulty = runErrorT positional in let logging = runWriterT faulty in let (output, log) = runIdentity logging in (either Left (Right . fst) output, log) data Fault = Fault { pos :: Maybe Pos, msg :: [String] } instance Error Fault where noMsg = Fault { pos = Nothing, msg = [] } strMsg s = Fault { pos = Nothing, msg = [s] } thisPosition :: Pos -> Compiler () thisPosition = put whatPosition :: Compiler Pos whatPosition = get logMessage :: Integer -> [Doc] -> Compiler () logMessage i ss = tell (LogEntry i `map` ss) getConfig :: Compiler Config getConfig = ask -- die :: String -> Compiler () die str = do f <- fault str throwError f -- CREATING ERRORS --------------------------------------------------- class Faultable e where fault :: e -> Compiler Fault instance Faultable ParseError where fault e = return (Fault { pos = Just (errorPos e), msg = tail (lines (show e)) }) instance Faultable String where fault s = do p <- whatPosition return (Fault { pos = Just p, msg = [s] }) -- DISPLAYING ERROR MESSAGES ----------------------------------------- instance Show Fault where show = pp instance Pretty Fault where pretty (Fault { pos = Nothing, msg = ss }) = colored 31 (text "pfc:" </> align (vcat (text `map` ss))) pretty (Fault { pos = Just p, msg = ss }) = colored 31 (pretty p <> colon </> align (vcat (text `map` ss))) {- Given the full text of a source file, and an error, print the error along with a quote from the textfile and a little arrow-like thing pointing at the trouble spot. -} prettyFaultWithQuote :: String -> Fault -> Doc prettyFaultWithQuote _ f@(Fault { pos = Nothing }) = pretty f <> line prettyFaultWithQuote t f@(Fault { pos = Just p }) = pretty f <$> case posToXY p of (0,0) -> empty (x,y) -> indent 2 (align (text (lines t !! y) <$> indent x (colored 31 $ text "^"))) <> line -- LOG MESSAGES ------------------------------------------------------ data LogEntry = LogEntry Integer Doc prettyLogMessages :: Integer -> [LogEntry] -> Doc prettyLogMessages i ms = vjam (showLogMessage i `map` ms) where showLogMessage i (LogEntry j s) | i < j = s | otherwise = empty
jaapweel/piffle
src/Compiler.hs
gpl-2.0
4,643
0
18
1,270
1,040
557
483
96
2
-------------------------------------------------------------------------------- -- | -- Module : Web.Pandoc -- Copyright : (C) 2014 Yorick Laupa -- License : (see the file LICENSE) -- -- Maintainer : Yorick Laupa <yo.eight@gmail.com> -- Stability : provisional -- Portability : non-portable -- -------------------------------------------------------------------------------- module Web.Pandoc where -------------------------------------------------------------------------------- import Data.ByteString.Char8 (pack) import Text.Blaze.Html (Html, unsafeByteString) import Text.Highlighting.Kate (haddock, styleToCss) import Text.Pandoc -------------------------------------------------------------------------------- readGithubMarkdown :: String -> Pandoc readGithubMarkdown = readMarkdown readerOpts -------------------------------------------------------------------------------- readerOpts :: ReaderOptions readerOpts = def { readerExtensions = githubMarkdownExtensions } -------------------------------------------------------------------------------- writerOpts :: WriterOptions writerOpts = def { writerHighlight = True , writerHighlightStyle = haddock } -------------------------------------------------------------------------------- writePandocHtml :: Pandoc -> Html writePandocHtml = writeHtml writerOpts -------------------------------------------------------------------------------- syntaxHighlightingCss :: Html syntaxHighlightingCss = unsafeByteString $ pack $ styleToCss haddock
YoEight/personal-site
Web/Pandoc.hs
gpl-3.0
1,540
0
6
160
164
104
60
16
1
functionC x y = case (x > y) of True -> x False -> y ifEvenAdd2 n = case even n of True -> n + 2 False -> n nums x = case compare x 0 of LT -> -1 GT -> 1 _ -> 0
dkensinger/haskell
haskellbook/casepractice.hs
gpl-3.0
201
0
8
87
102
50
52
13
3
{- What is a Project? -} import Data.Time.Calendar class DatePeriod p where startDay:: p -> Day startDay = diffDays endDay durationDays endDay:: p -> Day endDay = addDays startDay durationDays durationDays:: p -> Day durationDays = diffDays endDay startDay
FiskerLars/scorg
src/ProjectLogic.hs
gpl-3.0
277
0
7
59
74
39
35
8
0
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} module Database.Design.Ampersand.Output.ToPandoc.ChapterNatLangReqs ( chpNatLangReqs ) where import Data.Char hiding (Space) import Data.List import Data.List.Split import Data.Maybe --import Database.Design.Ampersand.Basics import Database.Design.Ampersand.Output.ToPandoc.SharedAmongChapters chpNatLangReqs :: Int -> FSpec -> Blocks chpNatLangReqs lev fSpec = -- *** Header *** chptHeader (fsLang fSpec) SharedLang <> -- *** Intro *** case fsLang fSpec of Dutch -> para ( "Dit hoofdstuk beschrijft een natuurlijke taal, waarin functionele eisen ten behoeve van " <> (singleQuoted.str.name) fSpec <> " kunnen worden besproken en uitgedrukt. " <> "Hiermee wordt beoogd dat verschillende belanghebbenden hun afspraken op dezelfde manier begrijpen. " <> "De taal van " <> (singleQuoted. str. name) fSpec <> " bestaat uit begrippen en basiszinnen, " <> "waarin afspraken worden uitgedrukt. " <> "Wanneer alle belanghebbenden afspreken dat zij deze basiszinnen gebruiken, " <> "althans voor zover het " <> (singleQuoted. str. name) fSpec <> " betreft, " <> "delen zij precies voldoende taal om afspraken op dezelfde manier te begrijpen. " <> "Alle definities zijn genummerd omwille van de traceerbaarheid. " ) English -> para ( "This chapter defines the natural language, in which functional requirements of " <> (singleQuoted.str.name) fSpec <> " can be discussed and expressed. " <> "The purpose of this chapter is to create shared understanding among stakeholders. " <> "The language of " <> (singleQuoted.str.name) fSpec <> " consists of concepts and basic sentences. " <> "All functional requirements are expressed in these terms. " <> "When stakeholders can agree upon this language, " <> "at least within the scope of " <> (singleQuoted.str.name) fSpec <> ", they share precisely enough language to have meaningful discussions about functional requirements. " <> "All definitions have been numbered for the sake of traceability. " ) <> -- *** Requirements *** (mconcat . map printOneTheme . orderingByTheme) fSpec <> -- *** Legal Refs *** if genLegalRefs (getOpts fSpec) then legalRefs else mempty where -- shorthand for easy localizing l :: LocalizedStr -> String l lstr = localize (fsLang fSpec) lstr legalRefs :: Blocks legalRefs = (header (lev+2) sectionTitle) <> table caption' [(AlignLeft,1/4),(AlignLeft,3/4)] [plain lawHeader, plain articleHeader] --headers [ [(para.str.aOlLaw) art , (para.str.unscanRef.aOlArt) art] | art <-(sort.nub.concatMap getArticlesOfLaw.getRefs) fSpec ] where (sectionTitle, lawHeader, articleHeader, caption') = case fsLang fSpec of Dutch -> ("Referentietabel", "Wet", "Artikel", "Referentietabel van de wetsartikelen") English -> ("Reference table", "Law", "Article", "Reference table of articles of law") getRefs ::FSpec -> [LawRef] getRefs f = concatMap catMaybes ((map (map toLawRef).map explRefIds.explanations) f) -- | printOneTheme tells the story in natural language of a single theme. -- For this purpose, Ampersand authors should take care in composing explanations. -- Each explanation should state the purpose (and nothing else). printOneTheme :: ThemeContent -> Blocks printOneTheme tc | (not . null . themes) fSpec && (isNothing . patOfTheme) tc = mempty -- The document is partial (because themes have been defined), so we don't print loose ends. | otherwise = -- *** Header of the theme: *** headerWithLabel (XRefNaturalLanguageTheme (patOfTheme tc)) (lev+2) (case (patOfTheme tc,fsLang fSpec) of (Nothing, Dutch ) -> "Losse eindjes..." (Nothing, English) -> "Loose ends..." (Just pat, _ ) -> text (name pat) ) <> -- *** Purpose of the theme: *** (case patOfTheme tc of Nothing -> (para.str.l) (NL "Deze paragraaf beschrijft de relaties en concepten die niet in voorgaande secties zijn beschreven." ,EN "This paragraph shows remaining artifacts that have not been described in previous paragraphs." ) Just pat -> case purposesDefinedIn fSpec (fsLang fSpec) pat of [] -> printIntro (cptsOfTheme tc) purps -> purposes2Blocks (getOpts fSpec) purps ) <> (mconcat . map printConcept . cptsOfTheme ) tc <> (mconcat . map printRel . dclsOfTheme ) tc <> (mconcat . map printRule . rulesOfTheme) tc where -- The following paragraph produces an introduction of one theme (i.e. pattern or process). printIntro :: [Numbered CptCont] -> Blocks printIntro [] = mempty printIntro nCpts = case patOfTheme tc of Nothing -> mempty Just pat -> ((para ((str.l) (NL "In het volgende wordt de taal geïntroduceerd ten behoeve van " ,EN "The sequel introduces the language of ") <> (str.name) pat <> ".") )<> ( case nCpts of [] -> fatal 136 "Unexpected. There should be at least one concept to introduce." [x] -> para( (str.l) (NL "Nu volgt de definitie van het begrip " ,EN "At this point, the definition of ") <> (showCpt x) <> (str.l) (NL "." ,EN " is given.") ) _ -> para( (str.l) (NL "Nu volgen definities van de begrippen " ,EN "At this point, the definitions of ") <> commaPandocAnd (fsLang fSpec) (map showCpt (sortWith theNr nCpts)) <> (str.l) (NL "." ,EN " are given.") ) )<> ( case filter hasMultipleDefs nCpts of [] -> mempty [x] -> para( (str.l) (NL "Het begrip " ,EN "Concept ") <> showCpt x <> (str.l) (NL " heeft meerdere definities." ,EN " is multiple defined.") ) multipleDefineds -> para( (str.l) (NL "De begrippen " ,EN "Concepts ") <> commaPandocAnd (fsLang fSpec) (map showCpt multipleDefineds) <> (str.l) (NL " hebben meerdere definities." ,EN " are multiple defined.") ) ) ) where showCpt :: Numbered CptCont -> Inlines showCpt = emph.text.name.cCpt.theLoad hasMultipleDefs :: Numbered CptCont -> Bool hasMultipleDefs x = case cCptDefs (theLoad x) of (_:_:_) -> True _ -> False printConcept :: Numbered CptCont -> Blocks printConcept nCpt = -- Purposes: (printPurposes . cCptPurps . theLoad) nCpt <> case (cCptDefs.theLoad) nCpt of [] -> mempty -- There is no definition of the concept [cd] -> printCDef cd Nothing cds -> mconcat [printCDef cd (Just ("."++ [suffx])) |(cd,suffx) <- zip cds ['a' ..] -- There are multiple definitions. Which one is the correct one? ] where printCDef :: ConceptDef -- the definition to print -> Maybe String -- when multiple definitions exist of a single concept, this is to distinguish -> Blocks printCDef cDef suffx = definitionList [( str (l (NL"Definitie " ,EN "Definition ")) <> case fspecFormat (getOpts fSpec) of FLatex -> (str . show .theNr) nCpt _ -> (str . name) cDef <> str (fromMaybe "" suffx) <> ":" , [para ( newGlossaryEntry (name cDef++fromMaybe "" suffx) (cddef cDef) <> (case fspecFormat (getOpts fSpec) of FLatex -> rawInline "latex" ("~\\marge{\\gls{"++escapeNonAlphaNum (name cDef++fromMaybe "" suffx)++"}}") _ -> mempty) <> str (cddef cDef) <> if null (cdref cDef) then mempty else str (" ["++cdref cDef++"]") ) ] ) ] printRel :: Numbered DeclCont -> Blocks printRel nDcl = (printPurposes . cDclPurps . theLoad) nDcl <> case (cDclMeaning . theLoad) nDcl of Just m -> definitionList [( definitionListItemLabel (XRefNaturalLanguageDeclaration dcl) (l (NL "Afspraak ", EN "Agreement ")++show(theNr nDcl) ++if development (getOpts fSpec) then (" ("++name nDcl++")") else "" ) , [printMeaning m] )] _ -> mempty <> case samples of [] -> mempty [_] -> plain ((str.l) (NL "Een frase die hiermee gemaakt kan worden is bijvoorbeeld:" ,EN "A phrase that can be formed is for instance:") ) _ -> plain ((str.l) (NL "Frasen die hiermee gemaakt kunnen worden zijn bijvoorbeeld:" ,EN "Phrases that can be made are for instance:") ) <> if null samples then mempty else bulletList [ plain $ mkPhrase dcl sample | sample <- samples] where dcl = cDcl . theLoad $ nDcl samples = take 3 . cDclPairs . theLoad $ nDcl printRule :: Numbered RuleCont -> Blocks printRule nRul = (printPurposes . cRulPurps . theLoad) nRul <> case (cRulMeaning . theLoad) nRul of Nothing -> mempty Just m -> definitionList [(definitionListItemLabel (XRefNaturalLanguageRule . cRul . theLoad $ nRul) ((case fsLang fSpec of Dutch -> "Afspraak " English -> "Agreement " )++ show (theNr nRul)++ if development (getOpts fSpec) then (" ("++name nRul++")") else "" ) , [printMeaning m] ) ] mkPhrase :: Declaration -> AAtomPair -> Inlines mkPhrase decl pair -- srcAtom tgtAtom = case decl of Sgn{} | null (prL++prM++prR) -> (atomShow . upCap) srcAtom <> devShow (source decl) <> (pragmaShow.l) (NL " correspondeert met ", EN " corresponds to ") <> atomShow tgtAtom <> devShow (target decl) <> (pragmaShow.l) (NL " in de relatie ",EN " in relation ") <> atomShow (name decl) <> "." | otherwise -> (if null prL then mempty else pragmaShow (upCap prL) <> " ") <> devShow (source decl) <> atomShow srcAtom <> " " <> (if null prM then mempty else pragmaShow prM <> " ") <> devShow (target decl) <> atomShow tgtAtom <> (if null prR then mempty else " " <> pragmaShow prR) <> "." Isn{} -> fatal 299 "Isn is not supposed to be here expected here." Vs{} -> fatal 300 "Vs is not supposed to be here expected here." where srcAtom = showValADL (apLeft pair) tgtAtom = showValADL (apRight pair) prL = decprL decl prM = decprM decl prR = decprR decl atomShow = str pragmaShow = emph . str devShow c = if (development (getOpts fSpec)) then "("<> (str.name) c <> ")" else mempty data LawRef = LawRef { lawRef :: String} data ArticleOfLaw = ArticleOfLaw { aOlLaw :: String , aOlArt :: [Either String Int] } deriving Eq toLawRef:: String -> Maybe LawRef toLawRef s = case s of [] -> Nothing _ -> (Just . LawRef) s -- the article is everything but the law (and we also drop any trailing commas) getArticlesOfLaw :: LawRef -> [ArticleOfLaw] getArticlesOfLaw ref = map buildLA ((splitOn ", ".unwords.init.words.lawRef) ref) where buildLA art = ArticleOfLaw ((last.words.lawRef) ref) (scanRef art) where -- group string in number and text sequences, so "Art 12" appears after "Art 2" when sorting (unlike in normal lexicographic string sort) scanRef :: String -> [Either String Int] scanRef "" = [] scanRef str'@(c:_) | isDigit c = scanRefInt str' | otherwise = scanRefTxt str' scanRefTxt "" = [] scanRefTxt str' = let (txt, rest) = break isDigit str' in Left txt : scanRefInt rest scanRefInt "" = [] scanRefInt str' = let (digits, rest) = break (not . isDigit) str' in Right (read digits) : scanRefTxt rest instance Ord ArticleOfLaw where compare a b = case compare (aOlLaw a) (aOlLaw b) of EQ -> compare (aOlArt a) (aOlArt b) ord' -> ord' unscanRef :: [Either String Int] -> String unscanRef scannedRef = concat $ map (either id show) scannedRef printPurposes :: [Purpose] -> Blocks printPurposes = fromList . concat . map (amPandoc . explMarkup) printMeaning :: A_Markup -> Blocks printMeaning = fromList . amPandoc
4ZP6Capstone2015/ampersand
src/Database/Design/Ampersand/Output/ToPandoc/ChapterNatLangReqs.hs
gpl-3.0
15,901
5
31
6,976
3,355
1,706
1,649
269
34
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE UnicodeSyntax #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Main -- License : GPL-3 -- Copyright : © Mateusz Kowalczyk, 2014 -- Maintainer : fuuzetsu@fuuzetsu.co.uk -- Stability : experimental -- Portability : portable -- -- Main entry point to free-taiko module Main where import qualified Data.List.PointedList as PL import qualified Data.List.PointedList.Circular as C import Control.Lens import Control.Monad.State.Strict import Data.Default import Data.Monoid import qualified Data.Text as T import FreeGame import Game.Osu.FreeTaiko.Menu import Game.Osu.FreeTaiko.SongScreen import Game.Osu.FreeTaiko.Types import Game.Osu.OszLoader.Types import System.Exit import System.FilePath ((</>)) run ∷ Game a → IO (Maybe a) run = runGame (def ^. windowMode) (def ^. resolution . unR) dir ∷ FilePath dir = "/home/shana/oszs" fontdir ∷ FilePath fontdir = "/home/shana/programming/free-taiko/data/fonts/VL-PGothic-Regular.ttf" imgdir ∷ FilePath imgdir = "/home/shana/programming/free-taiko/data/images" loadImages ∷ MonadIO m ⇒ m Images loadImages = do sb ← readBitmap $ imgdir </> "small_blue.png" sr ← readBitmap $ imgdir </> "small_red.png" bb ← readBitmap $ imgdir </> "big_blue.png" br ← readBitmap $ imgdir </> "big_red.png" gl ← readBitmap $ imgdir </> "goal.png" oR ← readBitmap $ imgdir </> "outer_right_pressed.png" ol ← readBitmap $ imgdir </> "outer_left_pressed.png" ir ← readBitmap $ imgdir </> "inner_right_pressed.png" il ← readBitmap $ imgdir </> "inner_left_pressed.png" bg ← readBitmap $ imgdir </> "bg_1080p.png" bt ← readBitmap $ imgdir </> "belt.png" dr ← readBitmap $ imgdir </> "drum.png" hgl ← readBitmap $ imgdir </> "hit_greatL.png" hgs ← readBitmap $ imgdir </> "hit_greatS.png" hgl' ← readBitmap $ imgdir </> "hit_goodL.png" hgs' ← readBitmap $ imgdir </> "hit_goodS.png" hm ← readBitmap $ imgdir </> "hit_miss.png" let mkNum x = readBitmap $ imgdir </> "default-" ++ show x ++ ".png" nums ← mapM mkNum [0 .. 9 ∷ Integer] return $ Images { _smallBlue = sb , _smallRed = sr , _bigBlue = bb , _bigRed = br , _goal = gl , _innerRightPressed = ir , _innerLeftPressed = il , _outerRightPressed = oR , _outerLeftPressed = ol , _bg1080p = bg , _belt = bt , _drum = dr , _hitGreatL = hgl , _hitGreatS = hgs , _hitGoodL = hgl' , _hitGoodS = hgs' , _hitMiss = hm , _numbers = nums } loadRes ∷ MonadIO m ⇒ m Resources loadRes = do fnt ← loadFont fontdir img ← loadImages return $ Res { _font = fnt , _images = img } renderResult ∷ (Picture2D m, FromFinalizer m, MonadIO m) ⇒ Double -- ^ font size → Double -- ^ spacing between each line → Font -- ^ Font to use → PL.PointedList (FilePath, Either T.Text TaikoData) → m () renderResult fs spacing fnt (PL.PointedList b c a) = zipWithM_ offset positions (reverse (map rend b) ++ [rendFocus c] ++ map rend a) where positions ∷ [Double] positions = map (\x → x * fs + spacing) [2 .. ] offset ∷ (MonadIO m, Affine m) ⇒ Double → m a → m a offset = translate . V2 10 rend ∷ (FromFinalizer m, Picture2D m, MonadIO m) ⇒ (FilePath, Either T.Text TaikoData) → m () rend (p, Left _) = color red $ text fnt fs p rend (_, Right x) = color green $ text fnt fs (mkTitle x) rendFocus ∷ (FromFinalizer m, Picture2D m, MonadIO m) ⇒ (FilePath, Either T.Text TaikoData) → m () rendFocus (p, Left _) = color yellow $ text fnt fs p rendFocus (_, Right x) = color yellow $ text fnt fs (mkTitle x) mkTitle ∷ TaikoData → String mkTitle x = let x' = x ^. tdMetadata in case _titleUnicode x' of Nothing → (T.unpack . _title $ x') <> creator Just t → T.unpack t <> creator where creator = " -- " <> (T.unpack . _creator $ x ^. tdMetadata) main ∷ IO () main = void . run $ do setFPS 60 setTitle "free-taiko" clearColor $ Color 0 0 0 0 runMenu dir >>= \case Nothing → liftIO $ print "No songs" Just m → do ss ← loadRes >>= return . mkMenu m s ← evalStateT menuLoop ss evalStateT songLoop (ss & screenState .~ s) where menuLoop ∷ MenuLoop SongState menuLoop = do bmaps ← use (screenState . maps) uset ← use userSettings whenM (keyPress $ uset ^. quitKey) $ quit .= True whenM (keyPress KeyUp) $ screenState . maps %= C.previous whenM (keyPress KeyDown) $ screenState . maps %= C.next whenM (keyPress KeyEnter) $ case PL._focus bmaps of (_, Left _) → return () (p, Right x) → screenState . picked .= Just (p, x) use (screenState . picked) >>= \case Just s → toSS s >>= return Nothing → do fnt ← use (resources . font) renderResult 15 2 fnt bmaps fps ← getFPS color (Color 255 0 0 255) $ translate (V2 5 5) $ text fnt 5 (show fps) q ← use quit tick >> if q then liftIO exitSuccess else menuLoop
Fuuzetsu/free-taiko
src/Main.hs
gpl-3.0
5,661
0
19
1,746
1,739
894
845
-1
-1
{-# LANGUAGE TupleSections #-} -- ----------------------------------------------------------------------------- import Control.Arrow( second ) import Control.Monad( void ) import Data.Array( Array, listArray, assocs, elems, indices, (//), (!) ) import Data.Char( digitToInt ) import Data.List( nub, sort, group, foldl', union ) import qualified Data.Map.Strict as M -- ----------------------------------------------------------------------------- type SudokuCell = [Int] type Sudoku = Array (Int,Int) SudokuCell -- ----------------------------------------------------------------------------- mkEmptyCell :: SudokuCell mkEmptyCell = [] mkFullCell :: SudokuCell mkFullCell = [1..9] {-| Make an Sudoku cell from a fixed value or zero. >>> mkSudokuCell 1 [1] >>> mkSudokuCell 0 [1,2,3,4,5,6,7,8,9] -} mkSudokuCell :: Integral a => a -> SudokuCell mkSudokuCell x | x == 0 = mkFullCell | x >= 1 && x <= 9 = [fromIntegral x] | otherwise = mkEmptyCell mkEmptySudoku :: Sudoku mkEmptySudoku = listArray ((1,1),(9,9)) $ repeat mkEmptyCell mkFullSudoku :: Sudoku mkFullSudoku = listArray ((1,1),(9,9)) $ repeat mkFullCell -- ----------------------------------------------------------------------------- initial01 :: Array (Int, Int) Int initial01 = listArray ((1,1),(9,9)) [ 3,0,0, 0,0,8, 0,0,0, 0,9,0, 0,6,2, 7,8,0, 5,0,0, 0,0,0, 6,0,0, 0,0,0, 0,7,0, 3,5,0, 0,0,0, 6,0,9, 0,0,0, 0,1,7, 0,5,0, 0,0,0, 0,0,2, 0,0,0, 0,0,4, 0,6,4, 7,9,0, 0,2,0, 0,0,0, 4,0,0, 0,0,6 ] ex01, ex01' :: Sudoku ex01 = sudokuFromInitial initial01 ex01' = fullIterate ex01 ex03:: Sudoku ex03 = mkFullSudoku // [ ((2,2),[3,4]), ((2,3),[3,4]), ((1,2),[6,4]) ] -- ----------------------------------------------------------------------------- sudokuFromInitial :: Integral a => Array (Int,Int) a -> Sudoku sudokuFromInitial = (mkEmptySudoku //) . changes where changes = fmap (second mkSudokuCell) . assocs -- ----------------------------------------------------------------------------- sudokuFromString :: String -> Sudoku sudokuFromString = sudokuFromInitial . listArray ((1,1),(9,9)) . take (9*9) . (++ repeat 0) . map digitToInt -- ----------------------------------------------------------------------------- showLine :: String showLine = replicate (4 * 9 + 1) '-' showSudokuCell :: SudokuCell -> String showSudokuCell [] = " " showSudokuCell [x] = " " ++ show x ++ " " showSudokuCell [x,y] = show x ++ " " ++ show y showSudokuCell [x,y,z] = show x ++ show y ++ show z showSudokuCell _ = "..." showSudokuLine :: [SudokuCell] -> String showSudokuLine = ("|" ++) . concat . fmap ((++"|") . showSudokuCell) showSudoku :: Sudoku -> [String] showSudoku = (showLine :) . (++ [showLine]) . fmap showSudokuLine . split9 . elems split9 :: [a] -> [[a]] split9 [] = [] split9 xs = y : split9 ys where (y,ys) = splitAt 9 xs printSudoku :: Sudoku -> IO () printSudoku = mapM_ putStrLn . showSudoku -- ----------------------------------------------------------------------------- boxIdx :: Int -> Int boxIdx n = ((n - 1) `div` 3) + 1 lowerIdx :: Int -> Int lowerIdx n = boxIdx n * 3 - 2 horizontalIndices :: (Int, Int) -> [(Int, Int)] horizontalIndices (y,x) = [(y,i) | i <- [1..9], i /= x ] verticalIndices :: (Int, Int) -> [(Int, Int)] verticalIndices (y,x) = [(j,x) | j <- [1..9], j /= y ] boxIndices :: (Int, Int) -> [(Int, Int)] boxIndices (y,x) = [(j,i) | j <- [ly .. ly + 2], i <- [lx .. lx + 2] , (j,i) /= (y,x) ] where ly = lowerIdx y lx = lowerIdx x -- ----------------------------------------------------------------------------- uniques :: Ord a => [a] -> [a] uniques = nub . sort filterLen :: Int -> [[a]] -> [[a]] filterLen n = filter ((==n) . length) groupCells :: [SudokuCell] -> [[SudokuCell]] groupCells = group . sort . fmap sort getSingletons :: Sudoku -> [(Int, Int)] -> [Int] getSingletons sudoku = uniques . concat . filterLen 1 . fmap (sudoku!) getPairs :: Sudoku -> [(Int, Int)] -> [Int] getPairs sudoku = uniques . concat . fmap head . filterLen 2 . groupCells . filterLen 2 . fmap (sudoku!) appendUnion :: [Int] -> [Int] -> [[Int]] -> [[Int]] appendUnion new key old = if key `union` new == key then new:old else old getTriples :: Sudoku -> [(Int, Int)] -> [Int] getTriples sudoku xs = uniques . concat . concat . filterLen 3 . M.elems $ fillupBuckets where cells = fmap (sudoku!) $ xs initialBuckets = M.fromList . fmap ((,[]) . head) . groupCells . filterLen 3 $ cells bucketElems = fmap sort . filter ((\a -> a>=2 && a <=3) . length) $ cells fillupBuckets = foldl' (\buckets x -> M.mapWithKey (appendUnion x) buckets) initialBuckets $ bucketElems getUniques :: Sudoku -> [(Int, Int)] -> [Int] getUniques sudoku xs = uniques $ singletons ++ pairs ++ triples where singletons = getSingletons sudoku xs pairs = getPairs sudoku xs triples = getTriples sudoku xs getUniquesCell :: Sudoku -> (Int, Int) -> [Int] getUniquesCell sudoku idx = uniques $ hUniques ++ vUniques ++ bUniques where hUniques = getUniques sudoku (horizontalIndices idx) vUniques = getUniques sudoku (verticalIndices idx) bUniques = getUniques sudoku (boxIndices idx) removeUniquesCell :: Sudoku -> (Int, Int) -> Sudoku removeUniquesCell sudoku idx = sudoku // [(idx, filter filterFun $ sudoku ! idx)] where filterFun = (`notElem` getUniquesCell sudoku idx) -- ----------------------------------------------------------------------------- getLikely :: Sudoku -> [(Int, Int)] -> SudokuCell getLikely sudoku = uniques . concat . fmap (sudoku!) getOwnCell :: Sudoku -> (Int, Int) -> SudokuCell getOwnCell sudoku idx = take 1 $ gethOwn ++ getvOwn ++ getbOwn where owns = sudoku ! idx gethOwn = filter (`notElem` getLikely sudoku (horizontalIndices idx)) owns getvOwn = filter (`notElem` getLikely sudoku (verticalIndices idx)) owns getbOwn = filter (`notElem` getLikely sudoku (boxIndices idx)) owns setOwnCell :: Sudoku -> (Int, Int) -> Sudoku setOwnCell sudoku idx = sudoku // fmap (\x -> (idx,[x])) own where own = getOwnCell sudoku idx -- ----------------------------------------------------------------------------- iterateRemove :: Sudoku -> Sudoku iterateRemove sudoku = foldl' removeUniquesCell sudoku (indices sudoku) iterateLikely :: Sudoku -> Sudoku iterateLikely sudoku = foldl' setOwnCell sudoku (indices sudoku) fullIterate :: Sudoku -> Sudoku fullIterate sudoku | newSudoku == sudoku = newSudoku | otherwise = fullIterate newSudoku where newSudoku = iterateLikely . iterateRemove $ sudoku -- ----------------------------------------------------------------------------- showFullIterate :: Sudoku -> IO Sudoku showFullIterate sudoku = do printSudoku sudoku if newSudoku /= sudoku then showFullIterate newSudoku else return newSudoku where newSudoku = iterateLikely . iterateRemove $ sudoku -- ----------------------------------------------------------------------------- main :: IO () main = void . showFullIterate $ ex01 -- -----------------------------------------------------------------------------
zhensydow/ljcsandbox
lang/haskell/sudoku/main.hs
gpl-3.0
7,478
0
16
1,596
2,669
1,505
1,164
-1
-1
import TSSP import Plot import Data.Complex import Graphics.Gnuplot.Simple import Graphics.Gnuplot.Value.Tuple import File import System.Process import Text.Printf main :: IO () main = harmOszSphere -- main = hydrogen -- main = harmOsz harmOszSphere :: IO () harmOszSphere = do let m = 7.43 -- 2.6 m_e a = 0.1 :: Double -- µeV µm² -- a = 0 :: Double -- µeV µm² g = 5*10**(-4) :: Double -- µeV µm³ -- g = 0 :: Double -- µeV µm³ testng u x = a*x**2 -- harm int = (0,10) sys = System int m u g sigma = 0.5 mu = 2 -- psi0 x = 1/sqrt(2*pi*sigma**2) * exp(-(x-mu)**2/(2*sigma**2)) :+ 0 psi0 x = 1/sqrt(sqrt pi*sigma) * exp(-(x-mu)**2/(2*sigma**2)) :+ 0 dx = 0.01 dt = 0.25 waveT = takeTil 40 $ tsspSphere sys psi0 dx dt title = "harmpot_sphere/data_norm_coupl_dx" ++ printf "%.4f" dx ++ "_dt" ++ printf "%.3f" dt -- putStr $ unlines $ map show list -- putStr $ unlines $ map show densT _ <- createProcess $ shell $ "mkdir -p output/" ++ title plotWaveset waveT $ title ++ "/" writeWaveset waveT $ "output/" ++ title ++ ".dat" return () -- hydrogen :: IO () -- hydrogen = do -- let m = 1/0.351764 -- 2.6 m_e -- g = 5*10**(-4) :: Double -- µeV µm³ -- e0 = 2.8372*10**(-24) :: Double -- e = 1.6022*10**(-10) :: Double -- u x = e/(4*pi*e0 * x**2) -- int = (0,10**(-4)) -- system = System int m u g -- -- -- sigma = 10 -- -- mu = 100 -- -- psi0 x = 1/sqrt(2*pi*sigma**2) * exp(-(x-mu)**2/(2*sigma**2)) :+ 0 -- a0 = 5.29*10**(-5) -- -- psi0 x = 1/sqrt(sqrt pi*sigma) * exp(-(x-mu)**2/(2*sigma**2)) :+ 0 -- psi0 x = sqrt(1/(pi*a0**3)) * exp(-x/a0) :+ 0 -- 1 0 0 -- -- psi0 x = sqrt(2/a0) * exp(-x/a0) :+ 0 -- 2 0 0 -- -- dx = 10**(-7) -- dt = 0.001 -- -- waveT = tsspSphere system psi0 dx dt -- list = wsetWaves waveT -- densT = map ( (*dx) . sum . map ((**2) . magnitude) ) list -- -- putStr $ unlines $ map show list -- -- putStr $ unlines $ map show densT -- plotWaveset waveT "hydrogen/" -- return () -- -- harmOsz :: IO () -- harmOsz = do -- let m = 7.4 -- 2.6 m_e -- a = 0.1 :: Double -- µeV µm² -- -- a = 0 -- g = 5*10**(-4) :: Double -- µeV µm³ -- u x = a*x**2 -- harm -- int = (-40,40) -- system = System int m u g -- -- sigma = 0.5 -- mu = 10 -- psi0 x = 1/sqrt(2*pi*sigma**2) * exp(-(x-mu)**2/(2*sigma**2)) :+ 0 -- -- dx = 0.05 -- dt = 1 -- -- waveT = tssp system psi0 dx dt -- list = wsetWaves waveT -- densT = map ( (*dx) . sum . map ((**2) . magnitude) ) list -- -- putStr $ unlines $ map show list -- plotWaveset waveT "harmpot/" -- -- putStr $ unlines $ map show densT -- return () plotWaveset :: (Graphics.Gnuplot.Value.Tuple.C a, RealFloat a, Num a,PrintfArg a) => Waveset a -> String -> IO () plotWaveset set fname = do let list = wsetWaves set dt = wsetDt set dx = wsetDx set x0 = wsetX0 set plotManyComplex [XLabel "x/um",YLabel "|psi|^2",XRange (-0,5),YRange (-0.1,2.1)] fname list x0 dt dx -- plotManyComplex [XLabel "x/um",YLabel "|psi|^2"] fname list x0 dt dx densityList :: RealFloat a => Waveset a -> [(a,a)] densityList wset = addPar (wsetDt wset) 0 $ map ( (* wsetDx wset) . sum . map ( (**2) . magnitude) ) $ wsetWaves wset
KiNaudiz/bachelor
TSSP/test.hs
gpl-3.0
4,058
0
18
1,606
654
370
284
42
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Instances.GetShieldedInstanceIdentity -- 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) -- -- Returns the Shielded Instance Identity of an instance -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.getShieldedInstanceIdentity@. module Network.Google.Resource.Compute.Instances.GetShieldedInstanceIdentity ( -- * REST Resource InstancesGetShieldedInstanceIdentityResource -- * Creating a Request , instancesGetShieldedInstanceIdentity , InstancesGetShieldedInstanceIdentity -- * Request Lenses , igsiiProject , igsiiZone , igsiiInstance ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.instances.getShieldedInstanceIdentity@ method which the -- 'InstancesGetShieldedInstanceIdentity' request conforms to. type InstancesGetShieldedInstanceIdentityResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "instances" :> Capture "instance" Text :> "getShieldedInstanceIdentity" :> QueryParam "alt" AltJSON :> Get '[JSON] ShieldedInstanceIdentity -- | Returns the Shielded Instance Identity of an instance -- -- /See:/ 'instancesGetShieldedInstanceIdentity' smart constructor. data InstancesGetShieldedInstanceIdentity = InstancesGetShieldedInstanceIdentity' { _igsiiProject :: !Text , _igsiiZone :: !Text , _igsiiInstance :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InstancesGetShieldedInstanceIdentity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'igsiiProject' -- -- * 'igsiiZone' -- -- * 'igsiiInstance' instancesGetShieldedInstanceIdentity :: Text -- ^ 'igsiiProject' -> Text -- ^ 'igsiiZone' -> Text -- ^ 'igsiiInstance' -> InstancesGetShieldedInstanceIdentity instancesGetShieldedInstanceIdentity pIgsiiProject_ pIgsiiZone_ pIgsiiInstance_ = InstancesGetShieldedInstanceIdentity' { _igsiiProject = pIgsiiProject_ , _igsiiZone = pIgsiiZone_ , _igsiiInstance = pIgsiiInstance_ } -- | Project ID for this request. igsiiProject :: Lens' InstancesGetShieldedInstanceIdentity Text igsiiProject = lens _igsiiProject (\ s a -> s{_igsiiProject = a}) -- | The name of the zone for this request. igsiiZone :: Lens' InstancesGetShieldedInstanceIdentity Text igsiiZone = lens _igsiiZone (\ s a -> s{_igsiiZone = a}) -- | Name or id of the instance scoping this request. igsiiInstance :: Lens' InstancesGetShieldedInstanceIdentity Text igsiiInstance = lens _igsiiInstance (\ s a -> s{_igsiiInstance = a}) instance GoogleRequest InstancesGetShieldedInstanceIdentity where type Rs InstancesGetShieldedInstanceIdentity = ShieldedInstanceIdentity type Scopes InstancesGetShieldedInstanceIdentity = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient InstancesGetShieldedInstanceIdentity'{..} = go _igsiiProject _igsiiZone _igsiiInstance (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy InstancesGetShieldedInstanceIdentityResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Instances/GetShieldedInstanceIdentity.hs
mpl-2.0
4,399
0
17
1,005
470
280
190
84
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.DialogFlow.Projects.Locations.Agents.Flows.Patch -- 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) -- -- Updates the specified flow. Note: You should always train a flow prior -- to sending it queries. See the [training -- documentation](https:\/\/cloud.google.com\/dialogflow\/cx\/docs\/concept\/training). -- -- /See:/ <https://cloud.google.com/dialogflow/ Dialogflow API Reference> for @dialogflow.projects.locations.agents.flows.patch@. module Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Flows.Patch ( -- * REST Resource ProjectsLocationsAgentsFlowsPatchResource -- * Creating a Request , projectsLocationsAgentsFlowsPatch , ProjectsLocationsAgentsFlowsPatch -- * Request Lenses , plafpXgafv , plafpLanguageCode , plafpUploadProtocol , plafpUpdateMask , plafpAccessToken , plafpUploadType , plafpPayload , plafpName , plafpCallback ) where import Network.Google.DialogFlow.Types import Network.Google.Prelude -- | A resource alias for @dialogflow.projects.locations.agents.flows.patch@ method which the -- 'ProjectsLocationsAgentsFlowsPatch' request conforms to. type ProjectsLocationsAgentsFlowsPatchResource = "v3" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "languageCode" Text :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GoogleCloudDialogflowCxV3Flow :> Patch '[JSON] GoogleCloudDialogflowCxV3Flow -- | Updates the specified flow. Note: You should always train a flow prior -- to sending it queries. See the [training -- documentation](https:\/\/cloud.google.com\/dialogflow\/cx\/docs\/concept\/training). -- -- /See:/ 'projectsLocationsAgentsFlowsPatch' smart constructor. data ProjectsLocationsAgentsFlowsPatch = ProjectsLocationsAgentsFlowsPatch' { _plafpXgafv :: !(Maybe Xgafv) , _plafpLanguageCode :: !(Maybe Text) , _plafpUploadProtocol :: !(Maybe Text) , _plafpUpdateMask :: !(Maybe GFieldMask) , _plafpAccessToken :: !(Maybe Text) , _plafpUploadType :: !(Maybe Text) , _plafpPayload :: !GoogleCloudDialogflowCxV3Flow , _plafpName :: !Text , _plafpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsAgentsFlowsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plafpXgafv' -- -- * 'plafpLanguageCode' -- -- * 'plafpUploadProtocol' -- -- * 'plafpUpdateMask' -- -- * 'plafpAccessToken' -- -- * 'plafpUploadType' -- -- * 'plafpPayload' -- -- * 'plafpName' -- -- * 'plafpCallback' projectsLocationsAgentsFlowsPatch :: GoogleCloudDialogflowCxV3Flow -- ^ 'plafpPayload' -> Text -- ^ 'plafpName' -> ProjectsLocationsAgentsFlowsPatch projectsLocationsAgentsFlowsPatch pPlafpPayload_ pPlafpName_ = ProjectsLocationsAgentsFlowsPatch' { _plafpXgafv = Nothing , _plafpLanguageCode = Nothing , _plafpUploadProtocol = Nothing , _plafpUpdateMask = Nothing , _plafpAccessToken = Nothing , _plafpUploadType = Nothing , _plafpPayload = pPlafpPayload_ , _plafpName = pPlafpName_ , _plafpCallback = Nothing } -- | V1 error format. plafpXgafv :: Lens' ProjectsLocationsAgentsFlowsPatch (Maybe Xgafv) plafpXgafv = lens _plafpXgafv (\ s a -> s{_plafpXgafv = a}) -- | The language of the following fields in \`flow\`: * -- \`Flow.event_handlers.trigger_fulfillment.messages\` * -- \`Flow.event_handlers.trigger_fulfillment.conditional_cases\` * -- \`Flow.transition_routes.trigger_fulfillment.messages\` * -- \`Flow.transition_routes.trigger_fulfillment.conditional_cases\` If not -- specified, the agent\'s default language is used. [Many -- languages](https:\/\/cloud.google.com\/dialogflow\/cx\/docs\/reference\/language) -- are supported. Note: languages must be enabled in the agent before they -- can be used. plafpLanguageCode :: Lens' ProjectsLocationsAgentsFlowsPatch (Maybe Text) plafpLanguageCode = lens _plafpLanguageCode (\ s a -> s{_plafpLanguageCode = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plafpUploadProtocol :: Lens' ProjectsLocationsAgentsFlowsPatch (Maybe Text) plafpUploadProtocol = lens _plafpUploadProtocol (\ s a -> s{_plafpUploadProtocol = a}) -- | Required. The mask to control which fields get updated. If -- \`update_mask\` is not specified, an error will be returned. plafpUpdateMask :: Lens' ProjectsLocationsAgentsFlowsPatch (Maybe GFieldMask) plafpUpdateMask = lens _plafpUpdateMask (\ s a -> s{_plafpUpdateMask = a}) -- | OAuth access token. plafpAccessToken :: Lens' ProjectsLocationsAgentsFlowsPatch (Maybe Text) plafpAccessToken = lens _plafpAccessToken (\ s a -> s{_plafpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plafpUploadType :: Lens' ProjectsLocationsAgentsFlowsPatch (Maybe Text) plafpUploadType = lens _plafpUploadType (\ s a -> s{_plafpUploadType = a}) -- | Multipart request metadata. plafpPayload :: Lens' ProjectsLocationsAgentsFlowsPatch GoogleCloudDialogflowCxV3Flow plafpPayload = lens _plafpPayload (\ s a -> s{_plafpPayload = a}) -- | The unique identifier of the flow. Format: -- \`projects\/\/locations\/\/agents\/\/flows\/\`. plafpName :: Lens' ProjectsLocationsAgentsFlowsPatch Text plafpName = lens _plafpName (\ s a -> s{_plafpName = a}) -- | JSONP plafpCallback :: Lens' ProjectsLocationsAgentsFlowsPatch (Maybe Text) plafpCallback = lens _plafpCallback (\ s a -> s{_plafpCallback = a}) instance GoogleRequest ProjectsLocationsAgentsFlowsPatch where type Rs ProjectsLocationsAgentsFlowsPatch = GoogleCloudDialogflowCxV3Flow type Scopes ProjectsLocationsAgentsFlowsPatch = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/dialogflow"] requestClient ProjectsLocationsAgentsFlowsPatch'{..} = go _plafpName _plafpXgafv _plafpLanguageCode _plafpUploadProtocol _plafpUpdateMask _plafpAccessToken _plafpUploadType _plafpCallback (Just AltJSON) _plafpPayload dialogFlowService where go = buildClient (Proxy :: Proxy ProjectsLocationsAgentsFlowsPatchResource) mempty
brendanhay/gogol
gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Locations/Agents/Flows/Patch.hs
mpl-2.0
7,514
0
18
1,535
954
560
394
141
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Mirror.Types.Product -- 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) -- module Network.Google.Mirror.Types.Product where import Network.Google.Mirror.Types.Sum import Network.Google.Prelude -- | Controls how notifications for a timeline item are presented to the -- user. -- -- /See:/ 'notificationConfig' smart constructor. data NotificationConfig = NotificationConfig' { _ncDeliveryTime :: !(Maybe DateTime') , _ncLevel :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'NotificationConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ncDeliveryTime' -- -- * 'ncLevel' notificationConfig :: NotificationConfig notificationConfig = NotificationConfig' { _ncDeliveryTime = Nothing , _ncLevel = Nothing } -- | The time at which the notification should be delivered. ncDeliveryTime :: Lens' NotificationConfig (Maybe UTCTime) ncDeliveryTime = lens _ncDeliveryTime (\ s a -> s{_ncDeliveryTime = a}) . mapping _DateTime -- | Describes how important the notification is. Allowed values are: - -- DEFAULT - Notifications of default importance. A chime will be played to -- alert users. ncLevel :: Lens' NotificationConfig (Maybe Text) ncLevel = lens _ncLevel (\ s a -> s{_ncLevel = a}) instance FromJSON NotificationConfig where parseJSON = withObject "NotificationConfig" (\ o -> NotificationConfig' <$> (o .:? "deliveryTime") <*> (o .:? "level")) instance ToJSON NotificationConfig where toJSON NotificationConfig'{..} = object (catMaybes [("deliveryTime" .=) <$> _ncDeliveryTime, ("level" .=) <$> _ncLevel]) -- | A single menu command that is part of a Contact. -- -- /See:/ 'command' smart constructor. newtype Command = Command' { _cType :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Command' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cType' command :: Command command = Command' { _cType = Nothing } -- | The type of operation this command corresponds to. Allowed values are: - -- TAKE_A_NOTE - Shares a timeline item with the transcription of user -- speech from the \"Take a note\" voice menu command. - POST_AN_UPDATE - -- Shares a timeline item with the transcription of user speech from the -- \"Post an update\" voice menu command. cType :: Lens' Command (Maybe Text) cType = lens _cType (\ s a -> s{_cType = a}) instance FromJSON Command where parseJSON = withObject "Command" (\ o -> Command' <$> (o .:? "type")) instance ToJSON Command where toJSON Command'{..} = object (catMaybes [("type" .=) <$> _cType]) -- | A list of Locations. This is the response from the server to GET -- requests on the locations collection. -- -- /See:/ 'locationsListResponse' smart constructor. data LocationsListResponse = LocationsListResponse' { _llrKind :: !Text , _llrItems :: !(Maybe [Location]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LocationsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'llrKind' -- -- * 'llrItems' locationsListResponse :: LocationsListResponse locationsListResponse = LocationsListResponse' { _llrKind = "mirror#locationsList" , _llrItems = Nothing } -- | The type of resource. This is always mirror#locationsList. llrKind :: Lens' LocationsListResponse Text llrKind = lens _llrKind (\ s a -> s{_llrKind = a}) -- | The list of locations. llrItems :: Lens' LocationsListResponse [Location] llrItems = lens _llrItems (\ s a -> s{_llrItems = a}) . _Default . _Coerce instance FromJSON LocationsListResponse where parseJSON = withObject "LocationsListResponse" (\ o -> LocationsListResponse' <$> (o .:? "kind" .!= "mirror#locationsList") <*> (o .:? "items" .!= mempty)) instance ToJSON LocationsListResponse where toJSON LocationsListResponse'{..} = object (catMaybes [Just ("kind" .= _llrKind), ("items" .=) <$> _llrItems]) -- | A geographic location that can be associated with a timeline item. -- -- /See:/ 'location' smart constructor. data Location = Location' { _lKind :: !Text , _lLatitude :: !(Maybe (Textual Double)) , _lAddress :: !(Maybe Text) , _lDisplayName :: !(Maybe Text) , _lId :: !(Maybe Text) , _lAccuracy :: !(Maybe (Textual Double)) , _lLongitude :: !(Maybe (Textual Double)) , _lTimestamp :: !(Maybe DateTime') } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Location' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lKind' -- -- * 'lLatitude' -- -- * 'lAddress' -- -- * 'lDisplayName' -- -- * 'lId' -- -- * 'lAccuracy' -- -- * 'lLongitude' -- -- * 'lTimestamp' location :: Location location = Location' { _lKind = "mirror#location" , _lLatitude = Nothing , _lAddress = Nothing , _lDisplayName = Nothing , _lId = Nothing , _lAccuracy = Nothing , _lLongitude = Nothing , _lTimestamp = Nothing } -- | The type of resource. This is always mirror#location. lKind :: Lens' Location Text lKind = lens _lKind (\ s a -> s{_lKind = a}) -- | The latitude, in degrees. lLatitude :: Lens' Location (Maybe Double) lLatitude = lens _lLatitude (\ s a -> s{_lLatitude = a}) . mapping _Coerce -- | The full address of the location. lAddress :: Lens' Location (Maybe Text) lAddress = lens _lAddress (\ s a -> s{_lAddress = a}) -- | The name to be displayed. This may be a business name or a user-defined -- place, such as \"Home\". lDisplayName :: Lens' Location (Maybe Text) lDisplayName = lens _lDisplayName (\ s a -> s{_lDisplayName = a}) -- | The ID of the location. lId :: Lens' Location (Maybe Text) lId = lens _lId (\ s a -> s{_lId = a}) -- | The accuracy of the location fix in meters. lAccuracy :: Lens' Location (Maybe Double) lAccuracy = lens _lAccuracy (\ s a -> s{_lAccuracy = a}) . mapping _Coerce -- | The longitude, in degrees. lLongitude :: Lens' Location (Maybe Double) lLongitude = lens _lLongitude (\ s a -> s{_lLongitude = a}) . mapping _Coerce -- | The time at which this location was captured, formatted according to RFC -- 3339. lTimestamp :: Lens' Location (Maybe UTCTime) lTimestamp = lens _lTimestamp (\ s a -> s{_lTimestamp = a}) . mapping _DateTime instance FromJSON Location where parseJSON = withObject "Location" (\ o -> Location' <$> (o .:? "kind" .!= "mirror#location") <*> (o .:? "latitude") <*> (o .:? "address") <*> (o .:? "displayName") <*> (o .:? "id") <*> (o .:? "accuracy") <*> (o .:? "longitude") <*> (o .:? "timestamp")) instance ToJSON Location where toJSON Location'{..} = object (catMaybes [Just ("kind" .= _lKind), ("latitude" .=) <$> _lLatitude, ("address" .=) <$> _lAddress, ("displayName" .=) <$> _lDisplayName, ("id" .=) <$> _lId, ("accuracy" .=) <$> _lAccuracy, ("longitude" .=) <$> _lLongitude, ("timestamp" .=) <$> _lTimestamp]) -- | A notification delivered by the API. -- -- /See:/ 'notification' smart constructor. data Notification = Notification' { _nOperation :: !(Maybe Text) , _nItemId :: !(Maybe Text) , _nCollection :: !(Maybe Text) , _nUserActions :: !(Maybe [UserAction]) , _nVerifyToken :: !(Maybe Text) , _nUserToken :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Notification' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nOperation' -- -- * 'nItemId' -- -- * 'nCollection' -- -- * 'nUserActions' -- -- * 'nVerifyToken' -- -- * 'nUserToken' notification :: Notification notification = Notification' { _nOperation = Nothing , _nItemId = Nothing , _nCollection = Nothing , _nUserActions = Nothing , _nVerifyToken = Nothing , _nUserToken = Nothing } -- | The type of operation that generated the notification. nOperation :: Lens' Notification (Maybe Text) nOperation = lens _nOperation (\ s a -> s{_nOperation = a}) -- | The ID of the item that generated the notification. nItemId :: Lens' Notification (Maybe Text) nItemId = lens _nItemId (\ s a -> s{_nItemId = a}) -- | The collection that generated the notification. nCollection :: Lens' Notification (Maybe Text) nCollection = lens _nCollection (\ s a -> s{_nCollection = a}) -- | A list of actions taken by the user that triggered the notification. nUserActions :: Lens' Notification [UserAction] nUserActions = lens _nUserActions (\ s a -> s{_nUserActions = a}) . _Default . _Coerce -- | The secret verify token provided by the service when it subscribed for -- notifications. nVerifyToken :: Lens' Notification (Maybe Text) nVerifyToken = lens _nVerifyToken (\ s a -> s{_nVerifyToken = a}) -- | The user token provided by the service when it subscribed for -- notifications. nUserToken :: Lens' Notification (Maybe Text) nUserToken = lens _nUserToken (\ s a -> s{_nUserToken = a}) instance FromJSON Notification where parseJSON = withObject "Notification" (\ o -> Notification' <$> (o .:? "operation") <*> (o .:? "itemId") <*> (o .:? "collection") <*> (o .:? "userActions" .!= mempty) <*> (o .:? "verifyToken") <*> (o .:? "userToken")) instance ToJSON Notification where toJSON Notification'{..} = object (catMaybes [("operation" .=) <$> _nOperation, ("itemId" .=) <$> _nItemId, ("collection" .=) <$> _nCollection, ("userActions" .=) <$> _nUserActions, ("verifyToken" .=) <$> _nVerifyToken, ("userToken" .=) <$> _nUserToken]) -- | A person or group that can be used as a creator or a contact. -- -- /See:/ 'contact' smart constructor. data Contact = Contact' { _conAcceptCommands :: !(Maybe [Command]) , _conSharingFeatures :: !(Maybe [Text]) , _conImageURLs :: !(Maybe [Text]) , _conPriority :: !(Maybe (Textual Word32)) , _conKind :: !Text , _conAcceptTypes :: !(Maybe [Text]) , _conPhoneNumber :: !(Maybe Text) , _conDisplayName :: !(Maybe Text) , _conSource :: !(Maybe Text) , _conId :: !(Maybe Text) , _conType :: !(Maybe Text) , _conSpeakableName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Contact' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'conAcceptCommands' -- -- * 'conSharingFeatures' -- -- * 'conImageURLs' -- -- * 'conPriority' -- -- * 'conKind' -- -- * 'conAcceptTypes' -- -- * 'conPhoneNumber' -- -- * 'conDisplayName' -- -- * 'conSource' -- -- * 'conId' -- -- * 'conType' -- -- * 'conSpeakableName' contact :: Contact contact = Contact' { _conAcceptCommands = Nothing , _conSharingFeatures = Nothing , _conImageURLs = Nothing , _conPriority = Nothing , _conKind = "mirror#contact" , _conAcceptTypes = Nothing , _conPhoneNumber = Nothing , _conDisplayName = Nothing , _conSource = Nothing , _conId = Nothing , _conType = Nothing , _conSpeakableName = Nothing } -- | A list of voice menu commands that a contact can handle. Glass shows up -- to three contacts for each voice menu command. If there are more than -- that, the three contacts with the highest priority are shown for that -- particular command. conAcceptCommands :: Lens' Contact [Command] conAcceptCommands = lens _conAcceptCommands (\ s a -> s{_conAcceptCommands = a}) . _Default . _Coerce -- | A list of sharing features that a contact can handle. Allowed values -- are: - ADD_CAPTION conSharingFeatures :: Lens' Contact [Text] conSharingFeatures = lens _conSharingFeatures (\ s a -> s{_conSharingFeatures = a}) . _Default . _Coerce -- | Set of image URLs to display for a contact. Most contacts will have a -- single image, but a \"group\" contact may include up to 8 image URLs and -- they will be resized and cropped into a mosaic on the client. conImageURLs :: Lens' Contact [Text] conImageURLs = lens _conImageURLs (\ s a -> s{_conImageURLs = a}) . _Default . _Coerce -- | Priority for the contact to determine ordering in a list of contacts. -- Contacts with higher priorities will be shown before ones with lower -- priorities. conPriority :: Lens' Contact (Maybe Word32) conPriority = lens _conPriority (\ s a -> s{_conPriority = a}) . mapping _Coerce -- | The type of resource. This is always mirror#contact. conKind :: Lens' Contact Text conKind = lens _conKind (\ s a -> s{_conKind = a}) -- | A list of MIME types that a contact supports. The contact will be shown -- to the user if any of its acceptTypes matches any of the types of the -- attachments on the item. If no acceptTypes are given, the contact will -- be shown for all items. conAcceptTypes :: Lens' Contact [Text] conAcceptTypes = lens _conAcceptTypes (\ s a -> s{_conAcceptTypes = a}) . _Default . _Coerce -- | Primary phone number for the contact. This can be a fully-qualified -- number, with country calling code and area code, or a local number. conPhoneNumber :: Lens' Contact (Maybe Text) conPhoneNumber = lens _conPhoneNumber (\ s a -> s{_conPhoneNumber = a}) -- | The name to display for this contact. conDisplayName :: Lens' Contact (Maybe Text) conDisplayName = lens _conDisplayName (\ s a -> s{_conDisplayName = a}) -- | The ID of the application that created this contact. This is populated -- by the API conSource :: Lens' Contact (Maybe Text) conSource = lens _conSource (\ s a -> s{_conSource = a}) -- | An ID for this contact. This is generated by the application and is -- treated as an opaque token. conId :: Lens' Contact (Maybe Text) conId = lens _conId (\ s a -> s{_conId = a}) -- | The type for this contact. This is used for sorting in UIs. Allowed -- values are: - INDIVIDUAL - Represents a single person. This is the -- default. - GROUP - Represents more than a single person. conType :: Lens' Contact (Maybe Text) conType = lens _conType (\ s a -> s{_conType = a}) -- | Name of this contact as it should be pronounced. If this contact\'s name -- must be spoken as part of a voice disambiguation menu, this name is used -- as the expected pronunciation. This is useful for contact names with -- unpronounceable characters or whose display spelling is otherwise not -- phonetic. conSpeakableName :: Lens' Contact (Maybe Text) conSpeakableName = lens _conSpeakableName (\ s a -> s{_conSpeakableName = a}) instance FromJSON Contact where parseJSON = withObject "Contact" (\ o -> Contact' <$> (o .:? "acceptCommands" .!= mempty) <*> (o .:? "sharingFeatures" .!= mempty) <*> (o .:? "imageUrls" .!= mempty) <*> (o .:? "priority") <*> (o .:? "kind" .!= "mirror#contact") <*> (o .:? "acceptTypes" .!= mempty) <*> (o .:? "phoneNumber") <*> (o .:? "displayName") <*> (o .:? "source") <*> (o .:? "id") <*> (o .:? "type") <*> (o .:? "speakableName")) instance ToJSON Contact where toJSON Contact'{..} = object (catMaybes [("acceptCommands" .=) <$> _conAcceptCommands, ("sharingFeatures" .=) <$> _conSharingFeatures, ("imageUrls" .=) <$> _conImageURLs, ("priority" .=) <$> _conPriority, Just ("kind" .= _conKind), ("acceptTypes" .=) <$> _conAcceptTypes, ("phoneNumber" .=) <$> _conPhoneNumber, ("displayName" .=) <$> _conDisplayName, ("source" .=) <$> _conSource, ("id" .=) <$> _conId, ("type" .=) <$> _conType, ("speakableName" .=) <$> _conSpeakableName]) -- -- /See:/ 'authToken' smart constructor. data AuthToken = AuthToken' { _atAuthToken :: !(Maybe Text) , _atType :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AuthToken' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'atAuthToken' -- -- * 'atType' authToken :: AuthToken authToken = AuthToken' { _atAuthToken = Nothing , _atType = Nothing } atAuthToken :: Lens' AuthToken (Maybe Text) atAuthToken = lens _atAuthToken (\ s a -> s{_atAuthToken = a}) atType :: Lens' AuthToken (Maybe Text) atType = lens _atType (\ s a -> s{_atType = a}) instance FromJSON AuthToken where parseJSON = withObject "AuthToken" (\ o -> AuthToken' <$> (o .:? "authToken") <*> (o .:? "type")) instance ToJSON AuthToken where toJSON AuthToken'{..} = object (catMaybes [("authToken" .=) <$> _atAuthToken, ("type" .=) <$> _atType]) -- | A list of Attachments. This is the response from the server to GET -- requests on the attachments collection. -- -- /See:/ 'attachmentsListResponse' smart constructor. data AttachmentsListResponse = AttachmentsListResponse' { _alrKind :: !Text , _alrItems :: !(Maybe [Attachment]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AttachmentsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alrKind' -- -- * 'alrItems' attachmentsListResponse :: AttachmentsListResponse attachmentsListResponse = AttachmentsListResponse' { _alrKind = "mirror#attachmentsList" , _alrItems = Nothing } -- | The type of resource. This is always mirror#attachmentsList. alrKind :: Lens' AttachmentsListResponse Text alrKind = lens _alrKind (\ s a -> s{_alrKind = a}) -- | The list of attachments. alrItems :: Lens' AttachmentsListResponse [Attachment] alrItems = lens _alrItems (\ s a -> s{_alrItems = a}) . _Default . _Coerce instance FromJSON AttachmentsListResponse where parseJSON = withObject "AttachmentsListResponse" (\ o -> AttachmentsListResponse' <$> (o .:? "kind" .!= "mirror#attachmentsList") <*> (o .:? "items" .!= mempty)) instance ToJSON AttachmentsListResponse where toJSON AttachmentsListResponse'{..} = object (catMaybes [Just ("kind" .= _alrKind), ("items" .=) <$> _alrItems]) -- | A custom menu item that can be presented to the user by a timeline item. -- -- /See:/ 'menuItem' smart constructor. data MenuItem = MenuItem' { _miValues :: !(Maybe [MenuValue]) , _miRemoveWhenSelected :: !(Maybe Bool) , _miAction :: !(Maybe Text) , _miPayload :: !(Maybe Text) , _miContextualCommand :: !(Maybe Text) , _miId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'MenuItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'miValues' -- -- * 'miRemoveWhenSelected' -- -- * 'miAction' -- -- * 'miPayload' -- -- * 'miContextualCommand' -- -- * 'miId' menuItem :: MenuItem menuItem = MenuItem' { _miValues = Nothing , _miRemoveWhenSelected = Nothing , _miAction = Nothing , _miPayload = Nothing , _miContextualCommand = Nothing , _miId = Nothing } -- | For CUSTOM items, a list of values controlling the appearance of the -- menu item in each of its states. A value for the DEFAULT state must be -- provided. If the PENDING or CONFIRMED states are missing, they will not -- be shown. miValues :: Lens' MenuItem [MenuValue] miValues = lens _miValues (\ s a -> s{_miValues = a}) . _Default . _Coerce -- | If set to true on a CUSTOM menu item, that item will be removed from the -- menu after it is selected. miRemoveWhenSelected :: Lens' MenuItem (Maybe Bool) miRemoveWhenSelected = lens _miRemoveWhenSelected (\ s a -> s{_miRemoveWhenSelected = a}) -- | Controls the behavior when the user picks the menu option. Allowed -- values are: - CUSTOM - Custom action set by the service. When the user -- selects this menuItem, the API triggers a notification to your -- callbackUrl with the userActions.type set to CUSTOM and the -- userActions.payload set to the ID of this menu item. This is the default -- value. - Built-in actions: - REPLY - Initiate a reply to the timeline -- item using the voice recording UI. The creator attribute must be set in -- the timeline item for this menu to be available. - REPLY_ALL - Same -- behavior as REPLY. The original timeline item\'s recipients will be -- added to the reply item. - DELETE - Delete the timeline item. - SHARE - -- Share the timeline item with the available contacts. - READ_ALOUD - Read -- the timeline item\'s speakableText aloud; if this field is not set, read -- the text field; if none of those fields are set, this menu item is -- ignored. - GET_MEDIA_INPUT - Allow users to provide media payloads to -- Glassware from a menu item (currently, only transcribed text from voice -- input is supported). Subscribe to notifications when users invoke this -- menu item to receive the timeline item ID. Retrieve the media from the -- timeline item in the payload property. - VOICE_CALL - Initiate a phone -- call using the timeline item\'s creator.phoneNumber attribute as -- recipient. - NAVIGATE - Navigate to the timeline item\'s location. - -- TOGGLE_PINNED - Toggle the isPinned state of the timeline item. - -- OPEN_URI - Open the payload of the menu item in the browser. - -- PLAY_VIDEO - Open the payload of the menu item in the Glass video -- player. - SEND_MESSAGE - Initiate sending a message to the timeline -- item\'s creator: - If the creator.phoneNumber is set and Glass is -- connected to an Android phone, the message is an SMS. - Otherwise, if -- the creator.email is set, the message is an email. miAction :: Lens' MenuItem (Maybe Text) miAction = lens _miAction (\ s a -> s{_miAction = a}) -- | A generic payload whose meaning changes depending on this MenuItem\'s -- action. - When the action is OPEN_URI, the payload is the URL of the -- website to view. - When the action is PLAY_VIDEO, the payload is the -- streaming URL of the video - When the action is GET_MEDIA_INPUT, the -- payload is the text transcription of a user\'s speech input miPayload :: Lens' MenuItem (Maybe Text) miPayload = lens _miPayload (\ s a -> s{_miPayload = a}) -- | The ContextualMenus.Command associated with this MenuItem (e.g. -- READ_ALOUD). The voice label for this command will be displayed in the -- voice menu and the touch label will be displayed in the touch menu. Note -- that the default menu value\'s display name will be overriden if you -- specify this property. Values that do not correspond to a -- ContextualMenus.Command name will be ignored. miContextualCommand :: Lens' MenuItem (Maybe Text) miContextualCommand = lens _miContextualCommand (\ s a -> s{_miContextualCommand = a}) -- | The ID for this menu item. This is generated by the application and is -- treated as an opaque token. miId :: Lens' MenuItem (Maybe Text) miId = lens _miId (\ s a -> s{_miId = a}) instance FromJSON MenuItem where parseJSON = withObject "MenuItem" (\ o -> MenuItem' <$> (o .:? "values" .!= mempty) <*> (o .:? "removeWhenSelected") <*> (o .:? "action") <*> (o .:? "payload") <*> (o .:? "contextual_command") <*> (o .:? "id")) instance ToJSON MenuItem where toJSON MenuItem'{..} = object (catMaybes [("values" .=) <$> _miValues, ("removeWhenSelected" .=) <$> _miRemoveWhenSelected, ("action" .=) <$> _miAction, ("payload" .=) <$> _miPayload, ("contextual_command" .=) <$> _miContextualCommand, ("id" .=) <$> _miId]) -- | A setting for Glass. -- -- /See:/ 'setting' smart constructor. data Setting = Setting' { _sKind :: !Text , _sValue :: !(Maybe Text) , _sId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Setting' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sKind' -- -- * 'sValue' -- -- * 'sId' setting :: Setting setting = Setting' { _sKind = "mirror#setting" , _sValue = Nothing , _sId = Nothing } -- | The type of resource. This is always mirror#setting. sKind :: Lens' Setting Text sKind = lens _sKind (\ s a -> s{_sKind = a}) -- | The setting value, as a string. sValue :: Lens' Setting (Maybe Text) sValue = lens _sValue (\ s a -> s{_sValue = a}) -- | The setting\'s ID. The following IDs are valid: - locale - The key to -- the user’s language\/locale (BCP 47 identifier) that Glassware should -- use to render localized content. - timezone - The key to the user’s -- current time zone region as defined in the tz database. Example: -- America\/Los_Angeles. sId :: Lens' Setting (Maybe Text) sId = lens _sId (\ s a -> s{_sId = a}) instance FromJSON Setting where parseJSON = withObject "Setting" (\ o -> Setting' <$> (o .:? "kind" .!= "mirror#setting") <*> (o .:? "value") <*> (o .:? "id")) instance ToJSON Setting where toJSON Setting'{..} = object (catMaybes [Just ("kind" .= _sKind), ("value" .=) <$> _sValue, ("id" .=) <$> _sId]) -- | Represents media content, such as a photo, that can be attached to a -- timeline item. -- -- /See:/ 'attachment' smart constructor. data Attachment = Attachment' { _aContentURL :: !(Maybe Text) , _aId :: !(Maybe Text) , _aIsProcessingContent :: !(Maybe Bool) , _aContentType :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Attachment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aContentURL' -- -- * 'aId' -- -- * 'aIsProcessingContent' -- -- * 'aContentType' attachment :: Attachment attachment = Attachment' { _aContentURL = Nothing , _aId = Nothing , _aIsProcessingContent = Nothing , _aContentType = Nothing } -- | The URL for the content. aContentURL :: Lens' Attachment (Maybe Text) aContentURL = lens _aContentURL (\ s a -> s{_aContentURL = a}) -- | The ID of the attachment. aId :: Lens' Attachment (Maybe Text) aId = lens _aId (\ s a -> s{_aId = a}) -- | Indicates that the contentUrl is not available because the attachment -- content is still being processed. If the caller wishes to retrieve the -- content, it should try again later. aIsProcessingContent :: Lens' Attachment (Maybe Bool) aIsProcessingContent = lens _aIsProcessingContent (\ s a -> s{_aIsProcessingContent = a}) -- | The MIME type of the attachment. aContentType :: Lens' Attachment (Maybe Text) aContentType = lens _aContentType (\ s a -> s{_aContentType = a}) instance FromJSON Attachment where parseJSON = withObject "Attachment" (\ o -> Attachment' <$> (o .:? "contentUrl") <*> (o .:? "id") <*> (o .:? "isProcessingContent") <*> (o .:? "contentType")) instance ToJSON Attachment where toJSON Attachment'{..} = object (catMaybes [("contentUrl" .=) <$> _aContentURL, ("id" .=) <$> _aId, ("isProcessingContent" .=) <$> _aIsProcessingContent, ("contentType" .=) <$> _aContentType]) -- | Represents an account passed into the Account Manager on Glass. -- -- /See:/ 'account' smart constructor. data Account = Account' { _aAuthTokens :: !(Maybe [AuthToken]) , _aUserData :: !(Maybe [UserData]) , _aPassword :: !(Maybe Text) , _aFeatures :: !(Maybe [Text]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Account' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aAuthTokens' -- -- * 'aUserData' -- -- * 'aPassword' -- -- * 'aFeatures' account :: Account account = Account' { _aAuthTokens = Nothing , _aUserData = Nothing , _aPassword = Nothing , _aFeatures = Nothing } aAuthTokens :: Lens' Account [AuthToken] aAuthTokens = lens _aAuthTokens (\ s a -> s{_aAuthTokens = a}) . _Default . _Coerce aUserData :: Lens' Account [UserData] aUserData = lens _aUserData (\ s a -> s{_aUserData = a}) . _Default . _Coerce aPassword :: Lens' Account (Maybe Text) aPassword = lens _aPassword (\ s a -> s{_aPassword = a}) aFeatures :: Lens' Account [Text] aFeatures = lens _aFeatures (\ s a -> s{_aFeatures = a}) . _Default . _Coerce instance FromJSON Account where parseJSON = withObject "Account" (\ o -> Account' <$> (o .:? "authTokens" .!= mempty) <*> (o .:? "userData" .!= mempty) <*> (o .:? "password") <*> (o .:? "features" .!= mempty)) instance ToJSON Account where toJSON Account'{..} = object (catMaybes [("authTokens" .=) <$> _aAuthTokens, ("userData" .=) <$> _aUserData, ("password" .=) <$> _aPassword, ("features" .=) <$> _aFeatures]) -- -- /See:/ 'userData' smart constructor. data UserData = UserData' { _udValue :: !(Maybe Text) , _udKey :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UserData' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udValue' -- -- * 'udKey' userData :: UserData userData = UserData' { _udValue = Nothing , _udKey = Nothing } udValue :: Lens' UserData (Maybe Text) udValue = lens _udValue (\ s a -> s{_udValue = a}) udKey :: Lens' UserData (Maybe Text) udKey = lens _udKey (\ s a -> s{_udKey = a}) instance FromJSON UserData where parseJSON = withObject "UserData" (\ o -> UserData' <$> (o .:? "value") <*> (o .:? "key")) instance ToJSON UserData where toJSON UserData'{..} = object (catMaybes [("value" .=) <$> _udValue, ("key" .=) <$> _udKey]) -- | Represents an action taken by the user that triggered a notification. -- -- /See:/ 'userAction' smart constructor. data UserAction = UserAction' { _uaPayload :: !(Maybe Text) , _uaType :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UserAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uaPayload' -- -- * 'uaType' userAction :: UserAction userAction = UserAction' { _uaPayload = Nothing , _uaType = Nothing } -- | An optional payload for the action. For actions of type CUSTOM, this is -- the ID of the custom menu item that was selected. uaPayload :: Lens' UserAction (Maybe Text) uaPayload = lens _uaPayload (\ s a -> s{_uaPayload = a}) -- | The type of action. The value of this can be: - SHARE - the user shared -- an item. - REPLY - the user replied to an item. - REPLY_ALL - the user -- replied to all recipients of an item. - CUSTOM - the user selected a -- custom menu item on the timeline item. - DELETE - the user deleted the -- item. - PIN - the user pinned the item. - UNPIN - the user unpinned the -- item. - LAUNCH - the user initiated a voice command. In the future, -- additional types may be added. UserActions with unrecognized types -- should be ignored. uaType :: Lens' UserAction (Maybe Text) uaType = lens _uaType (\ s a -> s{_uaType = a}) instance FromJSON UserAction where parseJSON = withObject "UserAction" (\ o -> UserAction' <$> (o .:? "payload") <*> (o .:? "type")) instance ToJSON UserAction where toJSON UserAction'{..} = object (catMaybes [("payload" .=) <$> _uaPayload, ("type" .=) <$> _uaType]) -- | A list of timeline items. This is the response from the server to GET -- requests on the timeline collection. -- -- /See:/ 'timelineListResponse' smart constructor. data TimelineListResponse = TimelineListResponse' { _tlrNextPageToken :: !(Maybe Text) , _tlrKind :: !Text , _tlrItems :: !(Maybe [TimelineItem]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TimelineListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tlrNextPageToken' -- -- * 'tlrKind' -- -- * 'tlrItems' timelineListResponse :: TimelineListResponse timelineListResponse = TimelineListResponse' { _tlrNextPageToken = Nothing , _tlrKind = "mirror#timeline" , _tlrItems = Nothing } -- | The next page token. Provide this as the pageToken parameter in the -- request to retrieve the next page of results. tlrNextPageToken :: Lens' TimelineListResponse (Maybe Text) tlrNextPageToken = lens _tlrNextPageToken (\ s a -> s{_tlrNextPageToken = a}) -- | The type of resource. This is always mirror#timeline. tlrKind :: Lens' TimelineListResponse Text tlrKind = lens _tlrKind (\ s a -> s{_tlrKind = a}) -- | Items in the timeline. tlrItems :: Lens' TimelineListResponse [TimelineItem] tlrItems = lens _tlrItems (\ s a -> s{_tlrItems = a}) . _Default . _Coerce instance FromJSON TimelineListResponse where parseJSON = withObject "TimelineListResponse" (\ o -> TimelineListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "mirror#timeline") <*> (o .:? "items" .!= mempty)) instance ToJSON TimelineListResponse where toJSON TimelineListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _tlrNextPageToken, Just ("kind" .= _tlrKind), ("items" .=) <$> _tlrItems]) -- | A list of Contacts representing contacts. This is the response from the -- server to GET requests on the contacts collection. -- -- /See:/ 'contactsListResponse' smart constructor. data ContactsListResponse = ContactsListResponse' { _clrKind :: !Text , _clrItems :: !(Maybe [Contact]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ContactsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'clrKind' -- -- * 'clrItems' contactsListResponse :: ContactsListResponse contactsListResponse = ContactsListResponse' { _clrKind = "mirror#contacts" , _clrItems = Nothing } -- | The type of resource. This is always mirror#contacts. clrKind :: Lens' ContactsListResponse Text clrKind = lens _clrKind (\ s a -> s{_clrKind = a}) -- | Contact list. clrItems :: Lens' ContactsListResponse [Contact] clrItems = lens _clrItems (\ s a -> s{_clrItems = a}) . _Default . _Coerce instance FromJSON ContactsListResponse where parseJSON = withObject "ContactsListResponse" (\ o -> ContactsListResponse' <$> (o .:? "kind" .!= "mirror#contacts") <*> (o .:? "items" .!= mempty)) instance ToJSON ContactsListResponse where toJSON ContactsListResponse'{..} = object (catMaybes [Just ("kind" .= _clrKind), ("items" .=) <$> _clrItems]) -- | A single value that is part of a MenuItem. -- -- /See:/ 'menuValue' smart constructor. data MenuValue = MenuValue' { _mvState :: !(Maybe Text) , _mvDisplayName :: !(Maybe Text) , _mvIconURL :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'MenuValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mvState' -- -- * 'mvDisplayName' -- -- * 'mvIconURL' menuValue :: MenuValue menuValue = MenuValue' { _mvState = Nothing , _mvDisplayName = Nothing , _mvIconURL = Nothing } -- | The state that this value applies to. Allowed values are: - DEFAULT - -- Default value shown when displayed in the menuItems list. - PENDING - -- Value shown when the menuItem has been selected by the user but can -- still be cancelled. - CONFIRMED - Value shown when the menuItem has been -- selected by the user and can no longer be cancelled. mvState :: Lens' MenuValue (Maybe Text) mvState = lens _mvState (\ s a -> s{_mvState = a}) -- | The name to display for the menu item. If you specify this property for -- a built-in menu item, the default contextual voice command for that menu -- item is not shown. mvDisplayName :: Lens' MenuValue (Maybe Text) mvDisplayName = lens _mvDisplayName (\ s a -> s{_mvDisplayName = a}) -- | URL of an icon to display with the menu item. mvIconURL :: Lens' MenuValue (Maybe Text) mvIconURL = lens _mvIconURL (\ s a -> s{_mvIconURL = a}) instance FromJSON MenuValue where parseJSON = withObject "MenuValue" (\ o -> MenuValue' <$> (o .:? "state") <*> (o .:? "displayName") <*> (o .:? "iconUrl")) instance ToJSON MenuValue where toJSON MenuValue'{..} = object (catMaybes [("state" .=) <$> _mvState, ("displayName" .=) <$> _mvDisplayName, ("iconUrl" .=) <$> _mvIconURL]) -- | A subscription to events on a collection. -- -- /See:/ 'subscription' smart constructor. data Subscription = Subscription' { _subCallbackURL :: !(Maybe Text) , _subOperation :: !(Maybe [Text]) , _subNotification :: !(Maybe Notification) , _subKind :: !Text , _subCollection :: !(Maybe Text) , _subVerifyToken :: !(Maybe Text) , _subUserToken :: !(Maybe Text) , _subId :: !(Maybe Text) , _subUpdated :: !(Maybe DateTime') } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Subscription' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'subCallbackURL' -- -- * 'subOperation' -- -- * 'subNotification' -- -- * 'subKind' -- -- * 'subCollection' -- -- * 'subVerifyToken' -- -- * 'subUserToken' -- -- * 'subId' -- -- * 'subUpdated' subscription :: Subscription subscription = Subscription' { _subCallbackURL = Nothing , _subOperation = Nothing , _subNotification = Nothing , _subKind = "mirror#subscription" , _subCollection = Nothing , _subVerifyToken = Nothing , _subUserToken = Nothing , _subId = Nothing , _subUpdated = Nothing } -- | The URL where notifications should be delivered (must start with -- https:\/\/). subCallbackURL :: Lens' Subscription (Maybe Text) subCallbackURL = lens _subCallbackURL (\ s a -> s{_subCallbackURL = a}) -- | A list of operations that should be subscribed to. An empty list -- indicates that all operations on the collection should be subscribed to. -- Allowed values are: - UPDATE - The item has been updated. - INSERT - A -- new item has been inserted. - DELETE - The item has been deleted. - -- MENU_ACTION - A custom menu item has been triggered by the user. subOperation :: Lens' Subscription [Text] subOperation = lens _subOperation (\ s a -> s{_subOperation = a}) . _Default . _Coerce -- | Container object for notifications. This is not populated in the -- Subscription resource. subNotification :: Lens' Subscription (Maybe Notification) subNotification = lens _subNotification (\ s a -> s{_subNotification = a}) -- | The type of resource. This is always mirror#subscription. subKind :: Lens' Subscription Text subKind = lens _subKind (\ s a -> s{_subKind = a}) -- | The collection to subscribe to. Allowed values are: - timeline - Changes -- in the timeline including insertion, deletion, and updates. - locations -- - Location updates. - settings - Settings updates. subCollection :: Lens' Subscription (Maybe Text) subCollection = lens _subCollection (\ s a -> s{_subCollection = a}) -- | A secret token sent to the subscriber in notifications so that it can -- verify that the notification was generated by Google. subVerifyToken :: Lens' Subscription (Maybe Text) subVerifyToken = lens _subVerifyToken (\ s a -> s{_subVerifyToken = a}) -- | An opaque token sent to the subscriber in notifications so that it can -- determine the ID of the user. subUserToken :: Lens' Subscription (Maybe Text) subUserToken = lens _subUserToken (\ s a -> s{_subUserToken = a}) -- | The ID of the subscription. subId :: Lens' Subscription (Maybe Text) subId = lens _subId (\ s a -> s{_subId = a}) -- | The time at which this subscription was last modified, formatted -- according to RFC 3339. subUpdated :: Lens' Subscription (Maybe UTCTime) subUpdated = lens _subUpdated (\ s a -> s{_subUpdated = a}) . mapping _DateTime instance FromJSON Subscription where parseJSON = withObject "Subscription" (\ o -> Subscription' <$> (o .:? "callbackUrl") <*> (o .:? "operation" .!= mempty) <*> (o .:? "notification") <*> (o .:? "kind" .!= "mirror#subscription") <*> (o .:? "collection") <*> (o .:? "verifyToken") <*> (o .:? "userToken") <*> (o .:? "id") <*> (o .:? "updated")) instance ToJSON Subscription where toJSON Subscription'{..} = object (catMaybes [("callbackUrl" .=) <$> _subCallbackURL, ("operation" .=) <$> _subOperation, ("notification" .=) <$> _subNotification, Just ("kind" .= _subKind), ("collection" .=) <$> _subCollection, ("verifyToken" .=) <$> _subVerifyToken, ("userToken" .=) <$> _subUserToken, ("id" .=) <$> _subId, ("updated" .=) <$> _subUpdated]) -- | Each item in the user\'s timeline is represented as a TimelineItem JSON -- structure, described below. -- -- /See:/ 'timelineItem' smart constructor. data TimelineItem = TimelineItem' { _tiCreator :: !(Maybe Contact) , _tiDisplayTime :: !(Maybe DateTime') , _tiEtag :: !(Maybe Text) , _tiIsDeleted :: !(Maybe Bool) , _tiPinScore :: !(Maybe (Textual Int32)) , _tiAttachments :: !(Maybe [Attachment]) , _tiLocation :: !(Maybe Location) , _tiMenuItems :: !(Maybe [MenuItem]) , _tiNotification :: !(Maybe NotificationConfig) , _tiText :: !(Maybe Text) , _tiKind :: !Text , _tiCreated :: !(Maybe DateTime') , _tiSpeakableText :: !(Maybe Text) , _tiIsBundleCover :: !(Maybe Bool) , _tiSpeakableType :: !(Maybe Text) , _tiBundleId :: !(Maybe Text) , _tiCanonicalURL :: !(Maybe Text) , _tiSelfLink :: !(Maybe Text) , _tiIsPinned :: !(Maybe Bool) , _tiSourceItemId :: !(Maybe Text) , _tiId :: !(Maybe Text) , _tiHTML :: !(Maybe Text) , _tiUpdated :: !(Maybe DateTime') , _tiRecipients :: !(Maybe [Contact]) , _tiTitle :: !(Maybe Text) , _tiInReplyTo :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TimelineItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiCreator' -- -- * 'tiDisplayTime' -- -- * 'tiEtag' -- -- * 'tiIsDeleted' -- -- * 'tiPinScore' -- -- * 'tiAttachments' -- -- * 'tiLocation' -- -- * 'tiMenuItems' -- -- * 'tiNotification' -- -- * 'tiText' -- -- * 'tiKind' -- -- * 'tiCreated' -- -- * 'tiSpeakableText' -- -- * 'tiIsBundleCover' -- -- * 'tiSpeakableType' -- -- * 'tiBundleId' -- -- * 'tiCanonicalURL' -- -- * 'tiSelfLink' -- -- * 'tiIsPinned' -- -- * 'tiSourceItemId' -- -- * 'tiId' -- -- * 'tiHTML' -- -- * 'tiUpdated' -- -- * 'tiRecipients' -- -- * 'tiTitle' -- -- * 'tiInReplyTo' timelineItem :: TimelineItem timelineItem = TimelineItem' { _tiCreator = Nothing , _tiDisplayTime = Nothing , _tiEtag = Nothing , _tiIsDeleted = Nothing , _tiPinScore = Nothing , _tiAttachments = Nothing , _tiLocation = Nothing , _tiMenuItems = Nothing , _tiNotification = Nothing , _tiText = Nothing , _tiKind = "mirror#timelineItem" , _tiCreated = Nothing , _tiSpeakableText = Nothing , _tiIsBundleCover = Nothing , _tiSpeakableType = Nothing , _tiBundleId = Nothing , _tiCanonicalURL = Nothing , _tiSelfLink = Nothing , _tiIsPinned = Nothing , _tiSourceItemId = Nothing , _tiId = Nothing , _tiHTML = Nothing , _tiUpdated = Nothing , _tiRecipients = Nothing , _tiTitle = Nothing , _tiInReplyTo = Nothing } -- | The user or group that created this item. tiCreator :: Lens' TimelineItem (Maybe Contact) tiCreator = lens _tiCreator (\ s a -> s{_tiCreator = a}) -- | The time that should be displayed when this item is viewed in the -- timeline, formatted according to RFC 3339. This user\'s timeline is -- sorted chronologically on display time, so this will also determine -- where the item is displayed in the timeline. If not set by the service, -- the display time defaults to the updated time. tiDisplayTime :: Lens' TimelineItem (Maybe UTCTime) tiDisplayTime = lens _tiDisplayTime (\ s a -> s{_tiDisplayTime = a}) . mapping _DateTime -- | ETag for this item. tiEtag :: Lens' TimelineItem (Maybe Text) tiEtag = lens _tiEtag (\ s a -> s{_tiEtag = a}) -- | When true, indicates this item is deleted, and only the ID property is -- set. tiIsDeleted :: Lens' TimelineItem (Maybe Bool) tiIsDeleted = lens _tiIsDeleted (\ s a -> s{_tiIsDeleted = a}) -- | For pinned items, this determines the order in which the item is -- displayed in the timeline, with a higher score appearing closer to the -- clock. Note: setting this field is currently not supported. tiPinScore :: Lens' TimelineItem (Maybe Int32) tiPinScore = lens _tiPinScore (\ s a -> s{_tiPinScore = a}) . mapping _Coerce -- | A list of media attachments associated with this item. As a convenience, -- you can refer to attachments in your HTML payloads with the attachment -- or cid scheme. For example: - attachment: -- <<attachment:attachment_index >> where attachment_index is the 0-based -- index of this array. - cid: <<cid:attachment_id >> where attachment_id -- is the ID of the attachment. tiAttachments :: Lens' TimelineItem [Attachment] tiAttachments = lens _tiAttachments (\ s a -> s{_tiAttachments = a}) . _Default . _Coerce -- | The geographic location associated with this item. tiLocation :: Lens' TimelineItem (Maybe Location) tiLocation = lens _tiLocation (\ s a -> s{_tiLocation = a}) -- | A list of menu items that will be presented to the user when this item -- is selected in the timeline. tiMenuItems :: Lens' TimelineItem [MenuItem] tiMenuItems = lens _tiMenuItems (\ s a -> s{_tiMenuItems = a}) . _Default . _Coerce -- | Controls how notifications for this item are presented on the device. If -- this is missing, no notification will be generated. tiNotification :: Lens' TimelineItem (Maybe NotificationConfig) tiNotification = lens _tiNotification (\ s a -> s{_tiNotification = a}) -- | Text content of this item. tiText :: Lens' TimelineItem (Maybe Text) tiText = lens _tiText (\ s a -> s{_tiText = a}) -- | The type of resource. This is always mirror#timelineItem. tiKind :: Lens' TimelineItem Text tiKind = lens _tiKind (\ s a -> s{_tiKind = a}) -- | The time at which this item was created, formatted according to RFC -- 3339. tiCreated :: Lens' TimelineItem (Maybe UTCTime) tiCreated = lens _tiCreated (\ s a -> s{_tiCreated = a}) . mapping _DateTime -- | The speakable version of the content of this item. Along with the -- READ_ALOUD menu item, use this field to provide text that would be -- clearer when read aloud, or to provide extended information to what is -- displayed visually on Glass. Glassware should also specify the -- speakableType field, which will be spoken before this text in cases -- where the additional context is useful, for example when the user -- requests that the item be read aloud following a notification. tiSpeakableText :: Lens' TimelineItem (Maybe Text) tiSpeakableText = lens _tiSpeakableText (\ s a -> s{_tiSpeakableText = a}) -- | Whether this item is a bundle cover. If an item is marked as a bundle -- cover, it will be the entry point to the bundle of items that have the -- same bundleId as that item. It will be shown only on the main timeline — -- not within the opened bundle. On the main timeline, items that are shown -- are: - Items that have isBundleCover set to true - Items that do not -- have a bundleId In a bundle sub-timeline, items that are shown are: - -- Items that have the bundleId in question AND isBundleCover set to false tiIsBundleCover :: Lens' TimelineItem (Maybe Bool) tiIsBundleCover = lens _tiIsBundleCover (\ s a -> s{_tiIsBundleCover = a}) -- | A speakable description of the type of this item. This will be announced -- to the user prior to reading the content of the item in cases where the -- additional context is useful, for example when the user requests that -- the item be read aloud following a notification. This should be a short, -- simple noun phrase such as \"Email\", \"Text message\", or \"Daily -- Planet News Update\". Glassware are encouraged to populate this field -- for every timeline item, even if the item does not contain speakableText -- or text so that the user can learn the type of the item without looking -- at the screen. tiSpeakableType :: Lens' TimelineItem (Maybe Text) tiSpeakableType = lens _tiSpeakableType (\ s a -> s{_tiSpeakableType = a}) -- | The bundle ID for this item. Services can specify a bundleId to group -- many items together. They appear under a single top-level item on the -- device. tiBundleId :: Lens' TimelineItem (Maybe Text) tiBundleId = lens _tiBundleId (\ s a -> s{_tiBundleId = a}) -- | A canonical URL pointing to the canonical\/high quality version of the -- data represented by the timeline item. tiCanonicalURL :: Lens' TimelineItem (Maybe Text) tiCanonicalURL = lens _tiCanonicalURL (\ s a -> s{_tiCanonicalURL = a}) -- | A URL that can be used to retrieve this item. tiSelfLink :: Lens' TimelineItem (Maybe Text) tiSelfLink = lens _tiSelfLink (\ s a -> s{_tiSelfLink = a}) -- | When true, indicates this item is pinned, which means it\'s grouped -- alongside \"active\" items like navigation and hangouts, on the opposite -- side of the home screen from historical (non-pinned) timeline items. You -- can allow the user to toggle the value of this property with the -- TOGGLE_PINNED built-in menu item. tiIsPinned :: Lens' TimelineItem (Maybe Bool) tiIsPinned = lens _tiIsPinned (\ s a -> s{_tiIsPinned = a}) -- | Opaque string you can use to map a timeline item to data in your own -- service. tiSourceItemId :: Lens' TimelineItem (Maybe Text) tiSourceItemId = lens _tiSourceItemId (\ s a -> s{_tiSourceItemId = a}) -- | The ID of the timeline item. This is unique within a user\'s timeline. tiId :: Lens' TimelineItem (Maybe Text) tiId = lens _tiId (\ s a -> s{_tiId = a}) -- | HTML content for this item. If both text and html are provided for an -- item, the html will be rendered in the timeline. Allowed HTML elements - -- You can use these elements in your timeline cards. - Headers: h1, h2, -- h3, h4, h5, h6 - Images: img - Lists: li, ol, ul - HTML5 semantics: -- article, aside, details, figure, figcaption, footer, header, nav, -- section, summary, time - Structural: blockquote, br, div, hr, p, span - -- Style: b, big, center, em, i, u, s, small, strike, strong, style, sub, -- sup - Tables: table, tbody, td, tfoot, th, thead, tr Blocked HTML -- elements: These elements and their contents are removed from HTML -- payloads. - Document headers: head, title - Embeds: audio, embed, -- object, source, video - Frames: frame, frameset - Scripting: applet, -- script Other elements: Any elements that aren\'t listed are removed, but -- their contents are preserved. tiHTML :: Lens' TimelineItem (Maybe Text) tiHTML = lens _tiHTML (\ s a -> s{_tiHTML = a}) -- | The time at which this item was last modified, formatted according to -- RFC 3339. tiUpdated :: Lens' TimelineItem (Maybe UTCTime) tiUpdated = lens _tiUpdated (\ s a -> s{_tiUpdated = a}) . mapping _DateTime -- | A list of users or groups that this item has been shared with. tiRecipients :: Lens' TimelineItem [Contact] tiRecipients = lens _tiRecipients (\ s a -> s{_tiRecipients = a}) . _Default . _Coerce -- | The title of this item. tiTitle :: Lens' TimelineItem (Maybe Text) tiTitle = lens _tiTitle (\ s a -> s{_tiTitle = a}) -- | If this item was generated as a reply to another item, this field will -- be set to the ID of the item being replied to. This can be used to -- attach a reply to the appropriate conversation or post. tiInReplyTo :: Lens' TimelineItem (Maybe Text) tiInReplyTo = lens _tiInReplyTo (\ s a -> s{_tiInReplyTo = a}) instance FromJSON TimelineItem where parseJSON = withObject "TimelineItem" (\ o -> TimelineItem' <$> (o .:? "creator") <*> (o .:? "displayTime") <*> (o .:? "etag") <*> (o .:? "isDeleted") <*> (o .:? "pinScore") <*> (o .:? "attachments" .!= mempty) <*> (o .:? "location") <*> (o .:? "menuItems" .!= mempty) <*> (o .:? "notification") <*> (o .:? "text") <*> (o .:? "kind" .!= "mirror#timelineItem") <*> (o .:? "created") <*> (o .:? "speakableText") <*> (o .:? "isBundleCover") <*> (o .:? "speakableType") <*> (o .:? "bundleId") <*> (o .:? "canonicalUrl") <*> (o .:? "selfLink") <*> (o .:? "isPinned") <*> (o .:? "sourceItemId") <*> (o .:? "id") <*> (o .:? "html") <*> (o .:? "updated") <*> (o .:? "recipients" .!= mempty) <*> (o .:? "title") <*> (o .:? "inReplyTo")) instance ToJSON TimelineItem where toJSON TimelineItem'{..} = object (catMaybes [("creator" .=) <$> _tiCreator, ("displayTime" .=) <$> _tiDisplayTime, ("etag" .=) <$> _tiEtag, ("isDeleted" .=) <$> _tiIsDeleted, ("pinScore" .=) <$> _tiPinScore, ("attachments" .=) <$> _tiAttachments, ("location" .=) <$> _tiLocation, ("menuItems" .=) <$> _tiMenuItems, ("notification" .=) <$> _tiNotification, ("text" .=) <$> _tiText, Just ("kind" .= _tiKind), ("created" .=) <$> _tiCreated, ("speakableText" .=) <$> _tiSpeakableText, ("isBundleCover" .=) <$> _tiIsBundleCover, ("speakableType" .=) <$> _tiSpeakableType, ("bundleId" .=) <$> _tiBundleId, ("canonicalUrl" .=) <$> _tiCanonicalURL, ("selfLink" .=) <$> _tiSelfLink, ("isPinned" .=) <$> _tiIsPinned, ("sourceItemId" .=) <$> _tiSourceItemId, ("id" .=) <$> _tiId, ("html" .=) <$> _tiHTML, ("updated" .=) <$> _tiUpdated, ("recipients" .=) <$> _tiRecipients, ("title" .=) <$> _tiTitle, ("inReplyTo" .=) <$> _tiInReplyTo]) -- | A list of Subscriptions. This is the response from the server to GET -- requests on the subscription collection. -- -- /See:/ 'subscriptionsListResponse' smart constructor. data SubscriptionsListResponse = SubscriptionsListResponse' { _slrKind :: !Text , _slrItems :: !(Maybe [Subscription]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'SubscriptionsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slrKind' -- -- * 'slrItems' subscriptionsListResponse :: SubscriptionsListResponse subscriptionsListResponse = SubscriptionsListResponse' { _slrKind = "mirror#subscriptionsList" , _slrItems = Nothing } -- | The type of resource. This is always mirror#subscriptionsList. slrKind :: Lens' SubscriptionsListResponse Text slrKind = lens _slrKind (\ s a -> s{_slrKind = a}) -- | The list of subscriptions. slrItems :: Lens' SubscriptionsListResponse [Subscription] slrItems = lens _slrItems (\ s a -> s{_slrItems = a}) . _Default . _Coerce instance FromJSON SubscriptionsListResponse where parseJSON = withObject "SubscriptionsListResponse" (\ o -> SubscriptionsListResponse' <$> (o .:? "kind" .!= "mirror#subscriptionsList") <*> (o .:? "items" .!= mempty)) instance ToJSON SubscriptionsListResponse where toJSON SubscriptionsListResponse'{..} = object (catMaybes [Just ("kind" .= _slrKind), ("items" .=) <$> _slrItems])
rueshyna/gogol
gogol-mirror/gen/Network/Google/Mirror/Types/Product.hs
mpl-2.0
60,822
0
36
16,033
11,481
6,653
4,828
1,235
1
module Handler.Info.About where import Import ------------------------------------------------------------------------ getAboutR :: Handler Html getAboutR = defaultLayout $ do setTitle "Betty : About" $(widgetFile "info.about") ------------------------------------------------------------------------
sajith/betty-web
Handler/Info/About.hs
agpl-3.0
313
0
10
34
45
24
21
6
1
{- Copyright (C) 2009 Andrejs Sisojevs <andrejs.sisojevs@nextmail.ru> All rights reserved. For license and copyright information, see the file COPYRIGHT -} -------------------------------------------------------------------------- -------------------------------------------------------------------------- module Database.PCLT (module Database.PCLT.UpdatableCatalog, module Database.PCLT.InterfaceWithDB) where import Database.PCLT.InterfaceWithDB import Database.PCLT.UpdatableCatalog
Andrey-Sisoyev/PCLT-DB
Database/PCLT.hs
lgpl-2.1
504
0
5
51
37
26
11
3
0
import Prelude as P import Data.Map as M import Data.PQueue.Prio.Min as Q import Data.List import Data.Tuple import Data.Maybe main :: IO () main = do text <- getLine let pmf = P.map swap . M.toList $ pmfs text let chars = P.map fst . M.toList $ countChars text let emptyCode = M.fromList . zip chars $ cycle [""] let code = huffCode (Q.fromList pmf) emptyCode let encode = huffEncode code let decode = huffDecode code print $ entropy $ P.map fst pmf print code print . encode $ text print . decode . encode $ text print $ (decode . encode) text == text entropy :: [Double] -> Double entropy ps = (-1) * sum (P.map (\p -> p * logBase 2 p) ps) huffEncode :: Map Char String -> String -> String huffEncode m s = concatMap (\c -> m ! c) s huffDecode :: Map Char String -> String -> String huffDecode m s = huffDecode' s mDecode [] where mDecode = M.fromList (P.map swap (M.toList m)) huffDecode' :: String -> Map String Char -> String -> String huffDecode' [] m a = a huffDecode' s m a = huffDecode' (P.drop (length key) s) m (a ++ [m ! key]) where key = fromJust . find (`isPrefixOf` s) $ M.keys m huffCode :: MinPQueue Double String -> Map Char String -> Map Char String huffCode pq cd | Q.size pq == 1 = cd | otherwise = huffCode newPQ newCD where p = pop2 pq newPQ = uncurry updateQ p newCD = M.unionsWith (++) [ls, rs, cd] where ls = addCodeChar '0' (snd ((fst p) !! 0)) M.empty rs = addCodeChar '1' (snd ((fst p) !! 1)) M.empty countChars :: String -> Map Char Integer countChars s = fromListWith (+) [(c, 1) | c <- s] pmfs :: String -> Map String Double pmfs s = M.map (\c -> (fromIntegral c) / total) counts where total = fromIntegral $ length s counts = M.fromList $ P.map (\c -> ([fst c], snd c)) (M.toList (countChars s)) pop2 :: (Ord a) => MinPQueue a b -> ([(a, b)], MinPQueue a b) pop2 pq = (iterate popNext ([], pq)) !! 2 updateQ :: [(Double, String)] -> MinPQueue Double String -> MinPQueue Double String updateQ l pq = Q.insert (fst tuple) (snd tuple) pq where catTup (v1, s1) (v2, s2) = (v1 + v2, s1 ++ s2) tuple = foldl1 catTup l -- foldl? addCodeChar :: Char -> String -> Map Char String -> Map Char String addCodeChar c [] m = m addCodeChar c s m = addCodeChar c (tail s) $ M.insertWith (++) (head s) [c] m popNext :: (Ord a) => ([(a, b)], MinPQueue a b) -> ([(a, b)], MinPQueue a b) popNext p = (vs ++ newV, newQ) where vs = fst p q = snd p newQ = Q.deleteMin q newV = [fromJust (Q.getMin q)]
dpohanlon/Huffman
huffman.hs
lgpl-3.0
2,682
0
15
748
1,279
657
622
61
1
-- vim: ts=2 sw=2 et : {- | Provides the 'HistoryItem' data type, representing an entry in ghci's history listing. -} module GHCi.History where -- | Represents a position in a source file, line and column, -- counting from 1. (Just as GHCi @:history@ output does.) data FilePos = FilePos { lineNum :: Int, colNum :: Int } deriving (Eq, Show) -- | the type of an item in @ghci's@ history. data HistoryItem = HistoryItem { histStepNum :: Int , funcName :: String , fileName :: String , startPos :: FilePos , endPos :: FilePos } deriving (Eq, Show) -- | same as @lineNum . startPos@ startLine = lineNum . startPos -- | same as @colNum . startPos@ startCol = colNum . startPos -- | same as @lineNum . endPos@ endLine = lineNum . endPos -- | same as @colNum . endPos@ endCol = colNum . endPos
phlummox/ghci-history-parser
src/GHCi/History.hs
unlicense
828
0
8
187
133
83
50
14
1
module Main where import Test.Framework (defaultMain, testGroup) import CardsTest (tests) import OpeningBidsTest (tests) import OpeningResponsesTest (tests) main :: IO () main = defaultMain allTests where allTests = [ testGroup "Cards.Tests" CardsTest.tests , testGroup "OpeningBids.Tests" OpeningBidsTest.tests , testGroup "OpeningResponses.Tests" OpeningResponsesTest.tests ]
derekmcloughlin/BridgeBuddyServer
test/TestSuite.hs
apache-2.0
498
0
9
160
96
54
42
13
1
-- Copyright 2018-2021 Google LLC -- -- 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. -- | Provides an analog of 'Applicative' over arity-1 type constructors. {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Data.Ten.Applicative ( Applicative10(..), (<*!), (*>!) , liftA310 , (:->:)(Arr10, runArr10) , pure10C, liftA210C, liftA310C ) where import Control.Applicative (liftA2) import Data.Proxy (Proxy(..)) import GHC.Generics ( Generic1(..) , (:.:)(..), (:*:)(..) , K1(..), M1(..), Rec1(..), U1(..) ) import Data.Wrapped (Wrapped1(..)) import Data.Ten.Ap (Ap10(..)) import Data.Ten.Entails (Entails) import Data.Ten.Functor (Functor10, (<$>!)) import Data.Ten.Functor.WithIndex (Index10, Functor10WithIndex, fmap10C) infixl 4 <*>! -- | 'Applicative' over arity-1 type constructors. -- -- See also 'Functor10' and 'Data.Ten.Foldable.Foldable10'. class Functor10 f => Applicative10 f where {-# MINIMAL pure10, ((<*>!) | liftA210) #-} -- | Lift a parametric @m@ value into an @f m@. pure10 :: (forall a. m a) -> f m -- | ('<*>') for 'Applicative10': zip two @f@s with 'runArr10'. (<*>!) :: f (m :->: n) -> f m -> f n (<*>!) = liftA210 (\ (Arr10 f') x' -> f' x') -- | 'Control.Applicative.liftA2' for 'Applicative10': zip two @f@s with a -- parametric function. liftA210 :: (forall a. m a -> n a -> o a) -> f m -> f n -> f o liftA210 f x y = (Arr10 . f) <$>! x <*>! y instance (Generic1 f, Applicative10 (Rep1 f)) => Applicative10 (Wrapped1 Generic1 f) where pure10 x = Wrapped1 $ to1 $ pure10 x liftA210 f (Wrapped1 x) (Wrapped1 y) = Wrapped1 $ to1 $ liftA210 f (from1 x) (from1 y) instance Applicative10 (Ap10 a) where pure10 x = Ap10 x liftA210 f (Ap10 x) (Ap10 y) = Ap10 $ f x y instance Monoid a => Applicative10 (K1 i a) where pure10 _ = K1 mempty liftA210 _ (K1 x) (K1 y) = K1 (x <> y) -- no instance Applicative10 V1: V1 is uninhabited instance Applicative10 U1 where pure10 _ = U1 liftA210 _ U1 U1 = U1 deriving instance Applicative10 f => Applicative10 (Rec1 f) deriving instance Applicative10 f => Applicative10 (M1 i c f) -- no instance (Applicative10 f, Applicative10 g) => Applicative10 (f :+: g) instance (Applicative10 f, Applicative10 g) => Applicative10 (f :*: g) where pure10 x = pure10 x :*: pure10 x liftA210 f (xl :*: xr) (yl :*: yr) = liftA210 f xl yl :*: liftA210 f xr yr instance (Applicative f, Applicative10 g) => Applicative10 (f :.: g) where pure10 x = Comp1 $ pure (pure10 x) liftA210 f (Comp1 x) (Comp1 y) = Comp1 $ liftA2 (liftA210 f) x y -- | A function @m a -> n a@ wrapped in a newtype for use as a type parameter. -- -- This is used to represent the partially-applied functions in the left side -- of ('<*>!'). newtype (m :->: n) a = Arr10 { runArr10 :: m a -> n a } -- | 'Control.Applicative.liftA3' for 'Applicative10'. liftA310 :: Applicative10 f => (forall a. m a -> n a -> o a -> p a) -> f m -> f n -> f o -> f p liftA310 f xs ys zs = (\x -> Arr10 (Arr10 . f x)) <$>! xs <*>! ys <*>! zs infixl 4 <*! -- | ('<*') for 'Applicative10'. (<*!) :: Applicative10 f => f m -> f n -> f m (<*!) = liftA210 const infixl 4 *>! -- | ('*>') for 'Applicative10'. (*>!) :: Applicative10 f => f m -> f n -> f n (*>!) = liftA210 (const id) -- | 'pure10' with access to an instance for every element. pure10C :: forall c f m . (Entails (Index10 f) c, Applicative10 f, Functor10WithIndex f) => (forall a. c a => m a) -> f m pure10C x = fmap10C @c (const x) (pure10 Proxy) -- | 'liftA210' with access to an instance for every element. liftA210C :: forall c f m n o . (Entails (Index10 f) c, Applicative10 f, Functor10WithIndex f) => (forall a. c a => m a -> n a -> o a) -> f m -> f n -> f o liftA210C f x y = fmap10C @c (Arr10 . f) x <*>! y -- | 'liftA310' with access to an instance for every element. liftA310C :: forall c f m n o p . (Entails (Index10 f) c, Applicative10 f, Functor10WithIndex f) => (forall a. c a => m a -> n a -> o a -> p a) -> f m -> f n -> f o -> f p liftA310C f x y z = liftA210C @c (fmap Arr10 . f) x y <*>! z
google/hs-ten
ten/src/Data/Ten/Applicative.hs
apache-2.0
5,023
2
14
1,082
1,537
833
704
90
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module DockerFu where import CI.Docker import qualified CI.Docker.Parse as Docker import CI.Filesystem (Path, Filesystem) import qualified CI.Filesystem as FS import Options.Applicative import Data.Char (isSpace) import Data.Monoid import Data.Maybe (mapMaybe) import Data.Text(Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Debug.Trace as DT import Control.Monad.Eff import Control.Monad.Eff.Lift import Control.Monad.Eff.Exception import Control.Monad.Eff.Trace import Control.Monad (forM) import Text.Printf -- | program options (environment in the bash script) data Args = Args { argRegistry :: Text -- ^ docker registry , argManifest :: FilePath -- ^ build.manifest path -- timestamp effect pending implementation -- , argTimestamp :: Eff r Text -- ^ effect returning a timestamp , argCommand :: Command } deriving (Show, Eq) data Command = CmdPull -- ^ pull: pulls all required base images for the build | CmdBuild -- ^ build: builds all specified images | CmdPush -- ^ pushes all specified images (assumes they have been built) | CmdClean -- ^ removes all images that should have been built, and unnamed images | CmdInfo -- ^ prints out information about all specified images deriving (Show, Eq) parseArgs :: Parser Args parseArgs = Args <$> option (str >>= return . T.pack) (long "registry" <> short 'r' <> metavar "REGISTRY" <> help "use REGISTRY as internal docker registry" <> value "omnia.docker.dev.cba" ) <*> strOption (long "manifest" <> metavar "MANIFEST" <> help "use MANIFEST as manifest file (default ./build.manifest)" <> value "build.manifest" ) -- timestamp effect pending implementation -- <*> option (str >>= return . T.pack) -- (long "with-timestamp" -- <> metavar "TIMESTAMP" -- <> help "use TIMESTAMP in place of a build timestamp" -- <> value getTimestamp) <*> subparser (cmdParse "pull" CmdPull "pull required base images" <> cmdParse "build" CmdBuild "build all specified images" <> cmdParse "push" CmdPush "push all images that were built" <> cmdParse "clean" CmdClean "clean all images (may fail)" <> cmdParse "info" CmdInfo "print information about all images" ) cmdParse :: String -> Command -> String -> Mod CommandFields Command cmdParse name cmd descr = command name (info (pure cmd) (progDesc descr)) -- | parser with usage and help strings parse :: ParserInfo Args parse = info (helper <*> parseArgs) (fullDesc <> progDesc "has docker fu" <> header "docker-fu: build magic for the awesome enterprise" ) dockerTodo :: (Member Trace r) => Args -> Eff r () dockerTodo args = do trace "running program on build.manifest" trace (show args) {- -------------------------------------------------- -- TODO should probably be provided by the library? runAll = runLift . runTrace -- runExeception . runGit . -- runException . runDocker . -- runException . runFs -} -------------------------------------------------- -- types coming from Docker and FS -- data Task = Task { taskTag :: Image , taskDir :: Path , taskDockerfile :: Dockerfile } data Dockerfile = Dockerfile { dfFrom :: Image , dfLines :: Int } {- -- | prepares the worklist from the manifest in the given path worklist :: (Member Filesystem r) => FilePath -> Eff r [Task] worklist manifest = undefined -- TODO -- the workhorse function: iterate over all lines in the manifest forManifest :: (Member Filesystem r) => Args -> Eff r () forManifest Args{..} = do tasks <- worklist argManifest case argCommand of CmdPull -> doPull tasks -- TODO other -> forM (job other) tasks -- TODO -} ------------------------------------------------------------------------------- -- * Read manifest and extract Dockerfile information data DockerFuException = DockerFuFailed deriving (Eq, Show) parseDockerfile :: Text -> Maybe Dockerfile parseDockerfile t = let s = T.unpack t in case Docker.parseString s of Right df -> case Docker.getFroms df of [Docker.TaggedImage i t] -> Just Dockerfile { dfFrom = Image (T.pack i) (Tag . T.pack $ t) , dfLines = length df } _ -> Nothing Left _ -> Nothing readAndParseDockerfile :: ( Member Filesystem r , Member (Exception DockerFuException) r ) => Path -> Eff r Dockerfile readAndParseDockerfile path = do fileContents <- T.decodeUtf8 <$> FS.read path case parseDockerfile fileContents of Just df -> return df Nothing -> throwException DockerFuFailed -- TODO readTasks :: ( Member Filesystem r , Member (Exception DockerFuException) r ) => Path -> Eff r [Task] readTasks path = do manifestFile <- T.decodeUtf8 <$> FS.read path -- TODO: handle errors case parseManifest manifestFile of Nothing -> return [] Just mfLines -> forM mfLines $ \mfLine -> do df <- readAndParseDockerfile (mfPath mfLine) return $ Task (mfImage mfLine) (mfPath mfLine) df ------------------------------------------------------------------------------- -- * Parsing manifest data ManifestLine = ManifestLine { mfImage :: Image , mfPath :: Path } deriving (Show) -- TODO: better parsing parseManifest :: Text -> Maybe [ManifestLine] -- TODO: better errors parseManifest txt = do sequence (fmap parseLine filteredLines) where filteredLines :: [Text] filteredLines = ( filter (not . T.null . T.strip) . fmap (T.takeWhile (/= '#')) . T.lines ) txt parseLine :: Text -> Maybe ManifestLine parseLine t = case filter (not . T.null) (map T.strip (T.split isSpace t)) of [imgTxt, pathTxt] -> do img <- parseImage (T.strip imgTxt) let path = FS.textToPath FS.unixSeparator (T.strip pathTxt) return $ ManifestLine img path _ -> Nothing parseImage :: Text -> Maybe Image parseImage txt = do case T.split (== ':') txt of [name, tag] -> do if ((not . T.null) name) && ((not . T.null) tag) then Just $ Image name (Tag tag) else Nothing _ -> Nothing
lancelet/bored-robot
app/DockerFu.hs
apache-2.0
7,852
0
20
2,793
1,410
753
657
134
4
module SSync.JSVectorM (Vector, VectorMonad, (!), write, set, new) where import Control.Monad (forM_) import qualified GHCJS.Types as T import SSync.JSVector.Internal type Vector = T.JSRef () foreign import javascript unsafe "$1[$2]" idx :: Vector -> Int -> IO Int foreign import javascript unsafe "$1[$2] = $3" update :: Vector -> Int -> Int -> IO () foreign import javascript unsafe "new Int32Array($1)" newRaw :: Int -> IO Vector foreign import javascript unsafe "$1.length" vLen :: Vector -> IO Int (!) :: Vector -> Int -> VectorMonad Int v ! i = VectorMonad $ idx v i {-# INLINE (!) #-} write :: Vector -> Int -> Int -> VectorMonad () write v i x = VectorMonad $ update v i x {-# INLINE write #-} set :: Vector -> Int -> VectorMonad () set v x = VectorMonad $ do -- Wow, JS typed arrays don't have a "fill"? (well, FF >=37 does, but nothing else) len <- vLen v forM_ [1..len-1] $ \i -> runVectorMonad $ write v i x {-# INLINE set #-} new :: Int -> VectorMonad Vector new len = VectorMonad $ newRaw len {-# INLINE new #-}
socrata-platform/ssync
src/main/haskell/SSync/JSVectorM.hs
apache-2.0
1,038
1
11
202
354
189
165
23
1
{-# LANGUAGE ScopedTypeVariables #-} module Tct.Trs.Encoding.Interpretation where import Data.Maybe (fromMaybe) import Control.Monad (liftM) import qualified Data.Foldable as F import qualified Data.Map.Strict as M import Data.Monoid ((<>)) import qualified Data.Traversable as F import qualified Data.Rewriting.Rule as R import Data.Rewriting.Term (Term (..)) import qualified Tct.Core.Data as T import qualified Tct.Core.Common.Pretty as PP import qualified Tct.Core.Common.Xml as Xml import Tct.Common.SMT as SMT (zero, (.&&), (.=>), (.>)) import qualified Tct.Common.SMT as SMT import Tct.Trs.Data import qualified Tct.Trs.Data.Problem as Prob import qualified Tct.Trs.Data.RuleSelector as RS import qualified Tct.Trs.Data.Signature as Sig import qualified Tct.Trs.Data.Rules as RS import qualified Tct.Trs.Encoding.ArgumentFiltering as AFEnc import qualified Tct.Trs.Encoding.UsablePositions as UPEnc import qualified Tct.Trs.Encoding.UsableRules as UREnc -- | @interpret fun var term@ interprets @term@. interpretTerm :: (fun -> [a] -> a) -> (var -> a) -> Term fun var -> a interpretTerm ifun ivar (Fun f ts) = ifun f (interpretTerm ifun ivar `fmap` ts) interpretTerm _ ivar (Var a) = ivar a newtype Interpretation f a = Interpretation { interpretations :: M.Map f a } deriving (Show, Functor, F.Foldable, F.Traversable) instance (SMT.Decode m c a) => SMT.Decode m (Interpretation fun c) (Interpretation fun a) where decode (Interpretation m) = Interpretation `liftM` F.traverse SMT.decode m -- instance (Applicative m, Monad m) => SMT.Decode m (UPEnc.UsablePositions f) (UPEnc.UsablePositions f) where -- decode = return instance (PP.Pretty f, PP.Pretty c) => PP.Pretty (Interpretation f c) where pretty pint = PP.table [(PP.AlignRight, as), (PP.AlignLeft, bs), (PP.AlignLeft,cs)] where (as,bs,cs) = unzip3 $ map k (M.toList $ interpretations pint) k (f,p) = (PP.text "p" <> PP.parens (PP.pretty f), PP.text " = ", PP.pretty p) -- | Indicates wether strict oriented rules should be shifted to the weak components or wether all strict rules should be oriented strictly. -- In the latter case the complexity problem is already solved. -- @All = Just (selAny selStricts)@ but the encoding is cheaper data Shift = Shift (ExpressionSelector F V) | All deriving Show -- FIXME: MS: clean up proof construction; usable args returns empty if not set instead of all data InterpretationProof a b = InterpretationProof { sig_ :: Signature F , inter_ :: Interpretation F a , uargs_ :: UPEnc.UsablePositions F , ufuns_ :: Maybe (Symbols F) , useURules_ :: Bool , shift_ :: Shift , strictDPs_ :: [(R.Rule F V, (b, b))] , strictTrs_ :: [(R.Rule F V, (b, b))] , weakDPs_ :: [(R.Rule F V, (b, b))] , weakTrs_ :: [(R.Rule F V, (b, b))] } deriving Show instance Monad m => SMT.Decode m (InterpretationProof a b) (InterpretationProof a b) where decode = return -- MS: formally this is not so nice as in tct2; some extra work would be necessary -- on the other hand we now have an abstract orient function for interpretations -- see Tct.RS.Method.Poly.NaturalPI for an example class AbstractInterpretation i where type (A i) :: * type (B i) :: * type (C i) :: * encode :: i -> A i -> SMT.SmtSolverSt Int (B i) setMonotone :: i -> B i -> [Int] -> SMT.Formula Int setInFilter :: i -> B i -> (Int -> SMT.Formula Int) -> SMT.Formula Int interpret :: i -> Interpretation F (B i) -> R.Term F V -> C i addConstant :: i -> C i -> SMT.IExpr Int -> C i gte :: i -> C i -> C i -> SMT.Formula Int type ForceAny = [R.Rule F V] -> SMT.Formula Int orient :: AbstractInterpretation i => i -> Trs -> Interpretation F (A i) -> Shift -> Bool -- TODO: MS: Use Types -> Bool -> SMT.SmtSolverSt Int (InterpretationProof () (), Interpretation F (B i), Maybe (UREnc.UsableEncoder F Int)) orient inter prob absi mselector useUP useUR = do SMT.setLogic SMT.QF_NIA -- encode abstract interpretation ebsi <- F.mapM (encode inter) absi let usablePositions = UPEnc.usableArgsWhereApplicable prob (Prob.isDTProblem prob) useUP monotoneConstraints = SMT.bigAnd [ setMonotone inter (interpretations ebsi `find` f) is | (f,is) <- UPEnc.usablePositions usablePositions ] where find m f = error ("Interpretation.monotonConstraints: not found:" ++ show f) `fromMaybe` M.lookup f m -- encode usable rules modulo argument filtering usenc <- if allowUR then Just `liftM` UREnc.usableEncoder prob else return Nothing ifenc <- if allowAF then Just `liftM` AFEnc.inFilterEncoder prob else return Nothing let usable r = case usenc of Nothing -> SMT.top Just us -> UREnc.usable us r inFilter f i = case ifenc of Nothing -> SMT.top Just af -> AFEnc.inFilter af f i usableRulesConstraints | allowUR = UREnc.validUsableRules trs usable inFilter | otherwise = SMT.top filteringConstraints | allowAF = SMT.bigAnd $ k `M.mapWithKey` interpretations ebsi | otherwise = SMT.top where k f fi = setInFilter inter fi (inFilter f) -- encode strict vars strictVarEncoder <- M.fromList `fmap` F.mapM (\r -> SMT.nvarM' >>= \v -> return (r,v)) rules let find f = error "Interpretation.strictVar: not found" `fromMaybe` M.lookup f strictVarEncoder strict = find interpretf = interpret inter ebsi (.>=.) = gte inter (.+.) = addConstant inter wOrderConstraints = SMT.bigAnd [ usable r .=> wOrder r | r <- wrules ] where wOrder r = interpretf (R.lhs r) .>=. interpretf (R.rhs r) sOrderConstraints = SMT.bigAnd [ usable r .=> sOrder r | r <- srules ] where sOrder r = interpretf (R.lhs r) .>=. (interpretf (R.rhs r) .+. strict r) forceAny rs | null rs = SMT.bot | otherwise = SMT.bigOr [ usable r .&& strict r .> zero | r <- rs ] rulesConstraints = forceAny srules .&& forceSel where forceSel = case mselector of All -> SMT.bigAnd [ usable r .=> strict r .> zero | r <- srules ] Shift sel -> orientSelected (RS.rsSelect sel prob) orientSelected (RS.SelectDP r) = strict r .> zero orientSelected (RS.SelectTrs r) = strict r .> zero orientSelected (RS.BigAnd es) = SMT.bigAnd (orientSelected `fmap` es) orientSelected (RS.BigOr es) = SMT.bigOr (orientSelected `fmap` es) SMT.assert wOrderConstraints SMT.assert sOrderConstraints SMT.assert rulesConstraints SMT.assert monotoneConstraints SMT.assert usableRulesConstraints SMT.assert filteringConstraints return (proof usablePositions, ebsi, usenc) where trs = Prob.allComponents prob rules = RS.toList trs srules = RS.toList (Prob.strictComponents prob) wrules = RS.toList (Prob.weakComponents prob) allowUR = useUR && Prob.isRCProblem prob && Prob.isInnermostProblem prob allowAF = allowUR proof uposs = InterpretationProof { sig_ = Prob.signature prob , inter_ = Interpretation M.empty , uargs_ = uposs , ufuns_ = Nothing , useURules_ = allowUR , shift_ = mselector , strictDPs_ = [] , strictTrs_ = [] , weakDPs_ = [] , weakTrs_ = [] } -- toTree :: (T.Processor p, T.In p ~ T.Out p) => p -> T.In p -> T.Result p -> T.ProofTree (T.Out p) -- toTree p prob (T.Fail po) = T.NoProgress (T.ProofNode p prob po) (T.Open prob) -- toTree p prob (T.Success probs po certfn) = T.Progress (T.ProofNode p prob po) certfn (T.Open `fmap` probs) newProblem :: Trs -> InterpretationProof a b -> T.Optional T.Id Trs newProblem prob proof = case shift_ proof of All -> T.Null Shift _ -> T.Opt . T.Id $ newProblem' prob proof newProblem' :: Problem F V -> InterpretationProof a b -> Problem F V newProblem' prob proof = Prob.sanitiseDPGraph $ prob { Prob.strictDPs = Prob.strictDPs prob `RS.difference` sDPs , Prob.strictTrs = Prob.strictTrs prob `RS.difference` sTrs , Prob.weakDPs = Prob.weakDPs prob `RS.union` sDPs , Prob.weakTrs = Prob.weakTrs prob `RS.union` sTrs } where rules = RS.fromList . fst . unzip sDPs = rules (strictDPs_ proof) sTrs = rules (strictTrs_ proof) instance (PP.Pretty a, PP.Pretty b) => PP.Pretty (InterpretationProof a b) where pretty proof = PP.vcat [ if uargs_ proof /= UPEnc.fullWithSignature (sig_ proof) then PP.vcat [ PP.text "The following argument positions are considered usable:" , PP.indent 2 $ PP.pretty (uargs_ proof) , PP.empty ] else PP.empty , PP.text "Following symbols are considered usable:" , PP.indent 2 $ maybe (PP.text "all") PP.set' (ufuns_ proof) , PP.text "TcT has computed the following interpretation:" , PP.indent 2 (PP.pretty (inter_ proof)) , PP.empty , PP.text "Following rules are strictly oriented:" , ppproof (PP.text " > ") (strictDPs_ proof ++ strictTrs_ proof) , PP.text "" , PP.text "Following rules are (at-least) weakly oriented:" , ppproof (PP.text " >= ") (weakDPs_ proof ++ weakTrs_ proof) ] where ppproof ppOrd rs = PP.table [(PP.AlignRight, as), (PP.AlignLeft, bs), (PP.AlignLeft, cs)] where (as,bs,cs) = unzip3 $ concatMap ppRule rs ppRule (R.Rule l r,(lhs,rhs)) = [ (PP.pretty l, PP.text " = ", PP.pretty lhs) , (PP.empty , ppOrd , PP.pretty rhs) , (PP.empty , PP.text " = ", PP.pretty r) , (PP.empty , PP.empty , PP.empty) ] xmlProof :: Xml.Xml a => InterpretationProof a b -> Xml.XmlContent -> Xml.XmlContent xmlProof proof itype = Xml.elt "ruleShifting" [ orderingConstraintProof , Xml.elt "trs" [Xml.toXml $ RS.fromList trs] -- strict part -- ceta complains if usableRules are set for non-innermost; even if all rules are given , if useURules_ proof then Xml.elt "usableRules" [Xml.toXml $ RS.fromList usr] -- usable part else Xml.empty -- akin to tct2 we allow interpretations to be the base case of our proof -- though ceTA requires to use ruleShifting; in this case we append the proof for the empty problem , case shift_ proof of -- Tct.Core.Processor.Empty.toXml Emptyproblem == </closed>, but toXml is not used in practice All -> Xml.elt "complexityProof" [Xml.elt "rIsEmpty" []] Shift _ -> Xml.empty ] where orderingConstraintProof = Xml.elt "orderingConstraintProof" [ Xml.elt "redPair" [Xml.elt "interpretation" (itype :xinters)]] xinters = map xinter . M.toList . interpretations $ inter_ proof xinter (f,p) = Xml.elt "interpret" [ Xml.toXml f , Xml.elt "arity" [Xml.int $ sig_ proof `Sig.arity` f] , Xml.toXml p ] -- , Xml.elt "polynomial" [Xml.toXml p]] trs = map fst $ strictTrs_ proof ++ strictDPs_ proof usr = (trs ++) . map fst $ weakTrs_ proof ++ weakDPs_ proof
ComputationWithBoundedResources/tct-trs
src/Tct/Trs/Encoding/Interpretation.hs
bsd-3-clause
11,302
0
19
2,862
3,457
1,840
1,617
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.NV.FragmentProgram2 -- 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/fragment_program2.txt NV_fragment_program2> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.NV.FragmentProgram2 ( -- * Enums gl_MAX_PROGRAM_CALL_DEPTH_NV, gl_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV, gl_MAX_PROGRAM_IF_DEPTH_NV, gl_MAX_PROGRAM_LOOP_COUNT_NV, gl_MAX_PROGRAM_LOOP_DEPTH_NV ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/NV/FragmentProgram2.hs
bsd-3-clause
802
0
4
90
49
39
10
7
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.SGIS.Texture4D -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/SGIS/texture4D.txt SGIS_texture4D> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.SGIS.Texture4D ( -- * Enums gl_MAX_4D_TEXTURE_SIZE_SGIS, gl_PACK_IMAGE_DEPTH_SGIS, gl_PACK_SKIP_VOLUMES_SGIS, gl_PROXY_TEXTURE_4D_SGIS, gl_TEXTURE_4DSIZE_SGIS, gl_TEXTURE_4D_BINDING_SGIS, gl_TEXTURE_4D_SGIS, gl_TEXTURE_WRAP_Q_SGIS, gl_UNPACK_IMAGE_DEPTH_SGIS, gl_UNPACK_SKIP_VOLUMES_SGIS, -- * Functions glTexImage4DSGIS, glTexSubImage4DSGIS ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/SGIS/Texture4D.hs
bsd-3-clause
1,003
0
4
118
79
60
19
15
0
module Control.Monad.Trans.Wrap ( WrappedMonadT (..) ) where import Control.Applicative import Control.Monad import Control.Monad.Trans newtype WrappedMonadT m a = WrapMonadT { unwrapMonadT :: m a } instance Monad m => Functor (WrappedMonadT m) where fmap = liftM instance Monad m => Applicative (WrappedMonadT m) where pure = return (<*>) = ap instance Monad m => Monad (WrappedMonadT m) where return = WrapMonadT . return m >>= k = WrapMonadT $ unwrapMonadT m >>= unwrapMonadT . k m >> n = WrapMonadT $ unwrapMonadT m >> unwrapMonadT n fail = WrapMonadT . fail instance MonadTrans WrappedMonadT where lift = WrapMonadT instance MonadIO m => MonadIO (WrappedMonadT m) where liftIO = lift . liftIO
sonyandy/unify
src/Control/Monad/Trans/Wrap.hs
bsd-3-clause
754
0
9
167
243
130
113
21
0
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.BuildPaths -- Copyright : Isaac Jones 2003-2004, -- Duncan Coutts 2008 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- A bunch of dirs, paths and file names used for intermediate build steps. -- module Distribution.Simple.BuildPaths ( defaultDistPref, srcPref, hscolourPref, haddockPref, autogenModulesDir, autogenModuleName, cppHeaderName, haddockName, mkLibName, mkProfLibName, mkSharedLibName, exeExtension, objExtension, dllExtension, ) where import Distribution.Package import Distribution.ModuleName as ModuleName import Distribution.Compiler import Distribution.PackageDescription import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Setup import Distribution.Text import Distribution.System import System.FilePath ((</>), (<.>)) -- --------------------------------------------------------------------------- -- Build directories and files srcPref :: FilePath -> FilePath srcPref distPref = distPref </> "src" hscolourPref :: FilePath -> PackageDescription -> FilePath hscolourPref = haddockPref haddockPref :: FilePath -> PackageDescription -> FilePath haddockPref distPref pkg_descr = distPref </> "doc" </> "html" </> display (packageName pkg_descr) -- |The directory in which we put auto-generated modules autogenModulesDir :: LocalBuildInfo -> String autogenModulesDir lbi = buildDir lbi </> "autogen" cppHeaderName :: String cppHeaderName = "cabal_macros.h" -- |The name of the auto-generated module associated with a package autogenModuleName :: PackageDescription -> ModuleName autogenModuleName pkg_descr = ModuleName.fromString $ "Paths_" ++ map fixchar (display (packageName pkg_descr)) where fixchar '-' = '_' fixchar c = c haddockName :: PackageDescription -> FilePath haddockName pkg_descr = display (packageName pkg_descr) <.> "haddock" -- --------------------------------------------------------------------------- -- Library file names mkLibName :: UnitId -> String mkLibName lib = "lib" ++ getHSLibraryName lib <.> "a" mkProfLibName :: UnitId -> String mkProfLibName lib = "lib" ++ getHSLibraryName lib ++ "_p" <.> "a" -- Implement proper name mangling for dynamical shared objects -- libHS<packagename>-<compilerFlavour><compilerVersion> -- e.g. libHSbase-2.1-ghc6.6.1.so mkSharedLibName :: CompilerId -> UnitId -> String mkSharedLibName (CompilerId compilerFlavor compilerVersion) lib = "lib" ++ getHSLibraryName lib ++ "-" ++ comp <.> dllExtension where comp = display compilerFlavor ++ display compilerVersion -- ------------------------------------------------------------ -- * Platform file extensions -- ------------------------------------------------------------ -- | Default extension for executable files on the current platform. -- (typically @\"\"@ on Unix and @\"exe\"@ on Windows or OS\/2) exeExtension :: String exeExtension = case buildOS of Windows -> "exe" _ -> "" -- | Extension for object files. For GHC the extension is @\"o\"@. objExtension :: String objExtension = "o" -- | Extension for dynamically linked (or shared) libraries -- (typically @\"so\"@ on Unix and @\"dll\"@ on Windows) dllExtension :: String dllExtension = case buildOS of Windows -> "dll" OSX -> "dylib" _ -> "so"
garetxe/cabal
Cabal/Distribution/Simple/BuildPaths.hs
bsd-3-clause
3,551
0
10
635
546
311
235
60
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} module Data.Geodetic.LLH( LLH(..) , HasLLH(..) ) where import Data.Geodetic.HasDoubles(HasDoubles(doubles)) import Data.Geodetic.LL(HasLL(lL), LL) import Papa data LLH = LLH { ll :: LL , _height :: Double } deriving (Eq, Ord, Show) makeClassy ''LLH instance HasLL LLH where lL = lens ll (\(LLH _ h) l -> LLH l h) instance HasDoubles LLH where doubles f (LLH l h) = LLH <$> doubles f l <*> f h
NICTA/coordinate
src/Data/Geodetic/LLH.hs
bsd-3-clause
527
0
10
141
188
107
81
26
0
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Pretty-printing assembly language -- -- (c) The University of Glasgow 1993-2005 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} module X86.Ppr ( pprNatCmmDecl, pprBasicBlock, pprSectionHeader, pprData, pprInstr, pprSize, pprImm, pprDataItem, ) where #include "HsVersions.h" #include "nativeGen/NCG.h" import X86.Regs import X86.Instr import X86.Cond import Instruction import Size import Reg import PprBase import BlockId import BasicTypes (Alignment) import DynFlags import Cmm hiding (topInfoTable) import CLabel import Unique ( pprUnique, Uniquable(..) ) import Platform import FastString import Outputable import Data.Word import Data.Bits -- ----------------------------------------------------------------------------- -- Printing this stuff out pprNatCmmDecl :: NatCmmDecl (Alignment, CmmStatics) Instr -> SDoc pprNatCmmDecl (CmmData section dats) = pprSectionHeader section $$ pprDatas dats pprNatCmmDecl proc@(CmmProc top_info lbl _ (ListGraph blocks)) = case topInfoTable proc of Nothing -> case blocks of [] -> -- special case for split markers: pprLabel lbl blocks -> -- special case for code without info table: pprSectionHeader Text $$ pprLabel lbl $$ -- blocks guaranteed not null, so label needed vcat (map (pprBasicBlock top_info) blocks) $$ pprSizeDecl lbl Just (Statics info_lbl _) -> sdocWithPlatform $ \platform -> (if platformHasSubsectionsViaSymbols platform then pprSectionHeader Text $$ ppr (mkDeadStripPreventer info_lbl) <> char ':' else empty) $$ vcat (map (pprBasicBlock top_info) blocks) $$ -- above: Even the first block gets a label, because with branch-chain -- elimination, it might be the target of a goto. (if platformHasSubsectionsViaSymbols platform then -- If we are using the .subsections_via_symbols directive -- (available on recent versions of Darwin), -- we have to make sure that there is some kind of reference -- from the entry code to a label on the _top_ of of the info table, -- so that the linker will not think it is unreferenced and dead-strip -- it. That's why the label is called a DeadStripPreventer (_dsp). text "\t.long " <+> ppr info_lbl <+> char '-' <+> ppr (mkDeadStripPreventer info_lbl) else empty) $$ pprSizeDecl info_lbl -- | Output the ELF .size directive. pprSizeDecl :: CLabel -> SDoc pprSizeDecl lbl = sdocWithPlatform $ \platform -> if osElfTarget (platformOS platform) then ptext (sLit "\t.size") <+> ppr lbl <> ptext (sLit ", .-") <> ppr lbl else empty pprBasicBlock :: BlockEnv CmmStatics -> NatBasicBlock Instr -> SDoc pprBasicBlock info_env (BasicBlock blockid instrs) = maybe_infotable $$ pprLabel (mkAsmTempLabel (getUnique blockid)) $$ vcat (map pprInstr instrs) where maybe_infotable = case mapLookup blockid info_env of Nothing -> empty Just (Statics info_lbl info) -> pprSectionHeader Text $$ vcat (map pprData info) $$ pprLabel info_lbl pprDatas :: (Alignment, CmmStatics) -> SDoc pprDatas (align, (Statics lbl dats)) = vcat (pprAlign align : pprLabel lbl : map pprData dats) -- TODO: could remove if align == 1 pprData :: CmmStatic -> SDoc pprData (CmmString str) = pprASCII str pprData (CmmUninitialised bytes) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then ptext (sLit ".space ") <> int bytes else ptext (sLit ".skip ") <> int bytes pprData (CmmStaticLit lit) = pprDataItem lit pprGloblDecl :: CLabel -> SDoc pprGloblDecl lbl | not (externallyVisibleCLabel lbl) = empty | otherwise = ptext (sLit ".globl ") <> ppr lbl pprTypeAndSizeDecl :: CLabel -> SDoc pprTypeAndSizeDecl lbl = sdocWithPlatform $ \platform -> if osElfTarget (platformOS platform) && externallyVisibleCLabel lbl then ptext (sLit ".type ") <> ppr lbl <> ptext (sLit ", @object") else empty pprLabel :: CLabel -> SDoc pprLabel lbl = pprGloblDecl lbl $$ pprTypeAndSizeDecl lbl $$ (ppr lbl <> char ':') pprASCII :: [Word8] -> SDoc pprASCII str = vcat (map do1 str) $$ do1 0 where do1 :: Word8 -> SDoc do1 w = ptext (sLit "\t.byte\t") <> int (fromIntegral w) pprAlign :: Int -> SDoc pprAlign bytes = sdocWithPlatform $ \platform -> ptext (sLit ".align ") <> int (alignment platform) where alignment platform = if platformOS platform == OSDarwin then log2 bytes else bytes log2 :: Int -> Int -- cache the common ones log2 1 = 0 log2 2 = 1 log2 4 = 2 log2 8 = 3 log2 n = 1 + log2 (n `quot` 2) -- ----------------------------------------------------------------------------- -- pprInstr: print an 'Instr' instance Outputable Instr where ppr instr = pprInstr instr pprReg :: Size -> Reg -> SDoc pprReg s r = case r of RegReal (RealRegSingle i) -> sdocWithPlatform $ \platform -> if target32Bit platform then ppr32_reg_no s i else ppr64_reg_no s i RegReal (RealRegPair _ _) -> panic "X86.Ppr: no reg pairs on this arch" RegVirtual (VirtualRegI u) -> text "%vI_" <> pprUnique u RegVirtual (VirtualRegHi u) -> text "%vHi_" <> pprUnique u RegVirtual (VirtualRegF u) -> text "%vF_" <> pprUnique u RegVirtual (VirtualRegD u) -> text "%vD_" <> pprUnique u RegVirtual (VirtualRegSSE u) -> text "%vSSE_" <> pprUnique u where ppr32_reg_no :: Size -> Int -> SDoc ppr32_reg_no II8 = ppr32_reg_byte ppr32_reg_no II16 = ppr32_reg_word ppr32_reg_no _ = ppr32_reg_long ppr32_reg_byte i = ptext (case i of { 0 -> sLit "%al"; 1 -> sLit "%bl"; 2 -> sLit "%cl"; 3 -> sLit "%dl"; _ -> sLit "very naughty I386 byte register" }) ppr32_reg_word i = ptext (case i of { 0 -> sLit "%ax"; 1 -> sLit "%bx"; 2 -> sLit "%cx"; 3 -> sLit "%dx"; 4 -> sLit "%si"; 5 -> sLit "%di"; 6 -> sLit "%bp"; 7 -> sLit "%sp"; _ -> sLit "very naughty I386 word register" }) ppr32_reg_long i = ptext (case i of { 0 -> sLit "%eax"; 1 -> sLit "%ebx"; 2 -> sLit "%ecx"; 3 -> sLit "%edx"; 4 -> sLit "%esi"; 5 -> sLit "%edi"; 6 -> sLit "%ebp"; 7 -> sLit "%esp"; _ -> ppr_reg_float i }) ppr64_reg_no :: Size -> Int -> SDoc ppr64_reg_no II8 = ppr64_reg_byte ppr64_reg_no II16 = ppr64_reg_word ppr64_reg_no II32 = ppr64_reg_long ppr64_reg_no _ = ppr64_reg_quad ppr64_reg_byte i = ptext (case i of { 0 -> sLit "%al"; 1 -> sLit "%bl"; 2 -> sLit "%cl"; 3 -> sLit "%dl"; 4 -> sLit "%sil"; 5 -> sLit "%dil"; -- new 8-bit regs! 6 -> sLit "%bpl"; 7 -> sLit "%spl"; 8 -> sLit "%r8b"; 9 -> sLit "%r9b"; 10 -> sLit "%r10b"; 11 -> sLit "%r11b"; 12 -> sLit "%r12b"; 13 -> sLit "%r13b"; 14 -> sLit "%r14b"; 15 -> sLit "%r15b"; _ -> sLit "very naughty x86_64 byte register" }) ppr64_reg_word i = ptext (case i of { 0 -> sLit "%ax"; 1 -> sLit "%bx"; 2 -> sLit "%cx"; 3 -> sLit "%dx"; 4 -> sLit "%si"; 5 -> sLit "%di"; 6 -> sLit "%bp"; 7 -> sLit "%sp"; 8 -> sLit "%r8w"; 9 -> sLit "%r9w"; 10 -> sLit "%r10w"; 11 -> sLit "%r11w"; 12 -> sLit "%r12w"; 13 -> sLit "%r13w"; 14 -> sLit "%r14w"; 15 -> sLit "%r15w"; _ -> sLit "very naughty x86_64 word register" }) ppr64_reg_long i = ptext (case i of { 0 -> sLit "%eax"; 1 -> sLit "%ebx"; 2 -> sLit "%ecx"; 3 -> sLit "%edx"; 4 -> sLit "%esi"; 5 -> sLit "%edi"; 6 -> sLit "%ebp"; 7 -> sLit "%esp"; 8 -> sLit "%r8d"; 9 -> sLit "%r9d"; 10 -> sLit "%r10d"; 11 -> sLit "%r11d"; 12 -> sLit "%r12d"; 13 -> sLit "%r13d"; 14 -> sLit "%r14d"; 15 -> sLit "%r15d"; _ -> sLit "very naughty x86_64 register" }) ppr64_reg_quad i = ptext (case i of { 0 -> sLit "%rax"; 1 -> sLit "%rbx"; 2 -> sLit "%rcx"; 3 -> sLit "%rdx"; 4 -> sLit "%rsi"; 5 -> sLit "%rdi"; 6 -> sLit "%rbp"; 7 -> sLit "%rsp"; 8 -> sLit "%r8"; 9 -> sLit "%r9"; 10 -> sLit "%r10"; 11 -> sLit "%r11"; 12 -> sLit "%r12"; 13 -> sLit "%r13"; 14 -> sLit "%r14"; 15 -> sLit "%r15"; _ -> ppr_reg_float i }) ppr_reg_float :: Int -> LitString ppr_reg_float i = case i of 16 -> sLit "%fake0"; 17 -> sLit "%fake1" 18 -> sLit "%fake2"; 19 -> sLit "%fake3" 20 -> sLit "%fake4"; 21 -> sLit "%fake5" 24 -> sLit "%xmm0"; 25 -> sLit "%xmm1" 26 -> sLit "%xmm2"; 27 -> sLit "%xmm3" 28 -> sLit "%xmm4"; 29 -> sLit "%xmm5" 30 -> sLit "%xmm6"; 31 -> sLit "%xmm7" 32 -> sLit "%xmm8"; 33 -> sLit "%xmm9" 34 -> sLit "%xmm10"; 35 -> sLit "%xmm11" 36 -> sLit "%xmm12"; 37 -> sLit "%xmm13" 38 -> sLit "%xmm14"; 39 -> sLit "%xmm15" _ -> sLit "very naughty x86 register" pprSize :: Size -> SDoc pprSize x = ptext (case x of II8 -> sLit "b" II16 -> sLit "w" II32 -> sLit "l" II64 -> sLit "q" FF32 -> sLit "ss" -- "scalar single-precision float" (SSE2) FF64 -> sLit "sd" -- "scalar double-precision float" (SSE2) FF80 -> sLit "t" ) pprSize_x87 :: Size -> SDoc pprSize_x87 x = ptext $ case x of FF32 -> sLit "s" FF64 -> sLit "l" FF80 -> sLit "t" _ -> panic "X86.Ppr.pprSize_x87" pprCond :: Cond -> SDoc pprCond c = ptext (case c of { GEU -> sLit "ae"; LU -> sLit "b"; EQQ -> sLit "e"; GTT -> sLit "g"; GE -> sLit "ge"; GU -> sLit "a"; LTT -> sLit "l"; LE -> sLit "le"; LEU -> sLit "be"; NE -> sLit "ne"; NEG -> sLit "s"; POS -> sLit "ns"; CARRY -> sLit "c"; OFLO -> sLit "o"; PARITY -> sLit "p"; NOTPARITY -> sLit "np"; ALWAYS -> sLit "mp"}) pprImm :: Imm -> SDoc pprImm (ImmInt i) = int i pprImm (ImmInteger i) = integer i pprImm (ImmCLbl l) = ppr l pprImm (ImmIndex l i) = ppr l <> char '+' <> int i pprImm (ImmLit s) = s pprImm (ImmFloat _) = ptext (sLit "naughty float immediate") pprImm (ImmDouble _) = ptext (sLit "naughty double immediate") pprImm (ImmConstantSum a b) = pprImm a <> char '+' <> pprImm b pprImm (ImmConstantDiff a b) = pprImm a <> char '-' <> lparen <> pprImm b <> rparen pprAddr :: AddrMode -> SDoc pprAddr (ImmAddr imm off) = let pp_imm = pprImm imm in if (off == 0) then pp_imm else if (off < 0) then pp_imm <> int off else pp_imm <> char '+' <> int off pprAddr (AddrBaseIndex base index displacement) = sdocWithPlatform $ \platform -> let pp_disp = ppr_disp displacement pp_off p = pp_disp <> char '(' <> p <> char ')' pp_reg r = pprReg (archWordSize (target32Bit platform)) r in case (base, index) of (EABaseNone, EAIndexNone) -> pp_disp (EABaseReg b, EAIndexNone) -> pp_off (pp_reg b) (EABaseRip, EAIndexNone) -> pp_off (ptext (sLit "%rip")) (EABaseNone, EAIndex r i) -> pp_off (comma <> pp_reg r <> comma <> int i) (EABaseReg b, EAIndex r i) -> pp_off (pp_reg b <> comma <> pp_reg r <> comma <> int i) _ -> panic "X86.Ppr.pprAddr: no match" where ppr_disp (ImmInt 0) = empty ppr_disp imm = pprImm imm pprSectionHeader :: Section -> SDoc pprSectionHeader seg = sdocWithPlatform $ \platform -> case platformOS platform of OSDarwin | target32Bit platform -> case seg of Text -> ptext (sLit ".text\n\t.align 2") Data -> ptext (sLit ".data\n\t.align 2") ReadOnlyData -> ptext (sLit ".const\n.align 2") RelocatableReadOnlyData -> ptext (sLit ".const_data\n.align 2") UninitialisedData -> ptext (sLit ".data\n\t.align 2") ReadOnlyData16 -> ptext (sLit ".const\n.align 4") OtherSection _ -> panic "X86.Ppr.pprSectionHeader: unknown section" | otherwise -> case seg of Text -> ptext (sLit ".text\n.align 3") Data -> ptext (sLit ".data\n.align 3") ReadOnlyData -> ptext (sLit ".const\n.align 3") RelocatableReadOnlyData -> ptext (sLit ".const_data\n.align 3") UninitialisedData -> ptext (sLit ".data\n\t.align 3") ReadOnlyData16 -> ptext (sLit ".const\n.align 4") OtherSection _ -> panic "PprMach.pprSectionHeader: unknown section" _ | target32Bit platform -> case seg of Text -> ptext (sLit ".text\n\t.align 4,0x90") Data -> ptext (sLit ".data\n\t.align 4") ReadOnlyData -> ptext (sLit ".section .rodata\n\t.align 4") RelocatableReadOnlyData -> ptext (sLit ".section .data\n\t.align 4") UninitialisedData -> ptext (sLit ".section .bss\n\t.align 4") ReadOnlyData16 -> ptext (sLit ".section .rodata\n\t.align 16") OtherSection _ -> panic "X86.Ppr.pprSectionHeader: unknown section" | otherwise -> case seg of Text -> ptext (sLit ".text\n\t.align 8") Data -> ptext (sLit ".data\n\t.align 8") ReadOnlyData -> ptext (sLit ".section .rodata\n\t.align 8") RelocatableReadOnlyData -> ptext (sLit ".section .data\n\t.align 8") UninitialisedData -> ptext (sLit ".section .bss\n\t.align 8") ReadOnlyData16 -> ptext (sLit ".section .rodata.cst16\n\t.align 16") OtherSection _ -> panic "PprMach.pprSectionHeader: unknown section" pprDataItem :: CmmLit -> SDoc pprDataItem lit = sdocWithDynFlags $ \dflags -> pprDataItem' dflags lit pprDataItem' :: DynFlags -> CmmLit -> SDoc pprDataItem' dflags lit = vcat (ppr_item (cmmTypeSize $ cmmLitType dflags lit) lit) where platform = targetPlatform dflags imm = litToImm lit -- These seem to be common: ppr_item II8 _ = [ptext (sLit "\t.byte\t") <> pprImm imm] ppr_item II16 _ = [ptext (sLit "\t.word\t") <> pprImm imm] ppr_item II32 _ = [ptext (sLit "\t.long\t") <> pprImm imm] ppr_item FF32 (CmmFloat r _) = let bs = floatToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item FF64 (CmmFloat r _) = let bs = doubleToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item II64 _ = case platformOS platform of OSDarwin | target32Bit platform -> case lit of CmmInt x _ -> [ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral x :: Word32)), ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral (x `shiftR` 32) :: Word32))] _ -> panic "X86.Ppr.ppr_item: no match for II64" | otherwise -> [ptext (sLit "\t.quad\t") <> pprImm imm] _ | target32Bit platform -> [ptext (sLit "\t.quad\t") <> pprImm imm] | otherwise -> -- x86_64: binutils can't handle the R_X86_64_PC64 -- relocation type, which means we can't do -- pc-relative 64-bit addresses. Fortunately we're -- assuming the small memory model, in which all such -- offsets will fit into 32 bits, so we have to stick -- to 32-bit offset fields and modify the RTS -- appropriately -- -- See Note [x86-64-relative] in includes/rts/storage/InfoTables.h -- case lit of -- A relative relocation: CmmLabelDiffOff _ _ _ -> [ptext (sLit "\t.long\t") <> pprImm imm, ptext (sLit "\t.long\t0")] _ -> [ptext (sLit "\t.quad\t") <> pprImm imm] ppr_item _ _ = panic "X86.Ppr.ppr_item: no match" pprInstr :: Instr -> SDoc pprInstr (COMMENT _) = empty -- nuke 'em {- pprInstr (COMMENT s) = ptext (sLit "# ") <> ftext s -} pprInstr (DELTA d) = pprInstr (COMMENT (mkFastString ("\tdelta = " ++ show d))) pprInstr (NEWBLOCK _) = panic "PprMach.pprInstr: NEWBLOCK" pprInstr (LDATA _ _) = panic "PprMach.pprInstr: LDATA" {- pprInstr (SPILL reg slot) = hcat [ ptext (sLit "\tSPILL"), char ' ', pprUserReg reg, comma, ptext (sLit "SLOT") <> parens (int slot)] pprInstr (RELOAD slot reg) = hcat [ ptext (sLit "\tRELOAD"), char ' ', ptext (sLit "SLOT") <> parens (int slot), comma, pprUserReg reg] -} pprInstr (MOV size src dst) = pprSizeOpOp (sLit "mov") size src dst pprInstr (MOVZxL II32 src dst) = pprSizeOpOp (sLit "mov") II32 src dst -- 32-to-64 bit zero extension on x86_64 is accomplished by a simple -- movl. But we represent it as a MOVZxL instruction, because -- the reg alloc would tend to throw away a plain reg-to-reg -- move, and we still want it to do that. pprInstr (MOVZxL sizes src dst) = pprSizeOpOpCoerce (sLit "movz") sizes II32 src dst -- zero-extension only needs to extend to 32 bits: on x86_64, -- the remaining zero-extension to 64 bits is automatic, and the 32-bit -- instruction is shorter. pprInstr (MOVSxL sizes src dst) = sdocWithPlatform $ \platform -> pprSizeOpOpCoerce (sLit "movs") sizes (archWordSize (target32Bit platform)) src dst -- here we do some patching, since the physical registers are only set late -- in the code generation. pprInstr (LEA size (OpAddr (AddrBaseIndex (EABaseReg reg1) (EAIndex reg2 1) (ImmInt 0))) dst@(OpReg reg3)) | reg1 == reg3 = pprSizeOpOp (sLit "add") size (OpReg reg2) dst pprInstr (LEA size (OpAddr (AddrBaseIndex (EABaseReg reg1) (EAIndex reg2 1) (ImmInt 0))) dst@(OpReg reg3)) | reg2 == reg3 = pprSizeOpOp (sLit "add") size (OpReg reg1) dst pprInstr (LEA size (OpAddr (AddrBaseIndex (EABaseReg reg1) EAIndexNone displ)) dst@(OpReg reg3)) | reg1 == reg3 = pprInstr (ADD size (OpImm displ) dst) pprInstr (LEA size src dst) = pprSizeOpOp (sLit "lea") size src dst pprInstr (ADD size (OpImm (ImmInt (-1))) dst) = pprSizeOp (sLit "dec") size dst pprInstr (ADD size (OpImm (ImmInt 1)) dst) = pprSizeOp (sLit "inc") size dst pprInstr (ADD size src dst) = pprSizeOpOp (sLit "add") size src dst pprInstr (ADC size src dst) = pprSizeOpOp (sLit "adc") size src dst pprInstr (SUB size src dst) = pprSizeOpOp (sLit "sub") size src dst pprInstr (IMUL size op1 op2) = pprSizeOpOp (sLit "imul") size op1 op2 {- A hack. The Intel documentation says that "The two and three operand forms [of IMUL] may also be used with unsigned operands because the lower half of the product is the same regardless if (sic) the operands are signed or unsigned. The CF and OF flags, however, cannot be used to determine if the upper half of the result is non-zero." So there. -} pprInstr (AND size src dst) = pprSizeOpOp (sLit "and") size src dst pprInstr (OR size src dst) = pprSizeOpOp (sLit "or") size src dst pprInstr (XOR FF32 src dst) = pprOpOp (sLit "xorps") FF32 src dst pprInstr (XOR FF64 src dst) = pprOpOp (sLit "xorpd") FF64 src dst pprInstr (XOR size src dst) = pprSizeOpOp (sLit "xor") size src dst pprInstr (POPCNT size src dst) = pprOpOp (sLit "popcnt") size src (OpReg dst) pprInstr (PREFETCH NTA size src ) = pprSizeOp_ (sLit "prefetchnta") size src pprInstr (PREFETCH Lvl0 size src) = pprSizeOp_ (sLit "prefetcht0") size src pprInstr (PREFETCH Lvl1 size src) = pprSizeOp_ (sLit "prefetcht1") size src pprInstr (PREFETCH Lvl2 size src) = pprSizeOp_ (sLit "prefetcht2") size src pprInstr (NOT size op) = pprSizeOp (sLit "not") size op pprInstr (BSWAP size op) = pprSizeOp (sLit "bswap") size (OpReg op) pprInstr (NEGI size op) = pprSizeOp (sLit "neg") size op pprInstr (SHL size src dst) = pprShift (sLit "shl") size src dst pprInstr (SAR size src dst) = pprShift (sLit "sar") size src dst pprInstr (SHR size src dst) = pprShift (sLit "shr") size src dst pprInstr (BT size imm src) = pprSizeImmOp (sLit "bt") size imm src pprInstr (CMP size src dst) | is_float size = pprSizeOpOp (sLit "ucomi") size src dst -- SSE2 | otherwise = pprSizeOpOp (sLit "cmp") size src dst where -- This predicate is needed here and nowhere else is_float FF32 = True is_float FF64 = True is_float FF80 = True is_float _ = False pprInstr (TEST size src dst) = pprSizeOpOp (sLit "test") size src dst pprInstr (PUSH size op) = pprSizeOp (sLit "push") size op pprInstr (POP size op) = pprSizeOp (sLit "pop") size op -- both unused (SDM): -- pprInstr PUSHA = ptext (sLit "\tpushal") -- pprInstr POPA = ptext (sLit "\tpopal") pprInstr NOP = ptext (sLit "\tnop") pprInstr (CLTD II32) = ptext (sLit "\tcltd") pprInstr (CLTD II64) = ptext (sLit "\tcqto") pprInstr (SETCC cond op) = pprCondInstr (sLit "set") cond (pprOperand II8 op) pprInstr (JXX cond blockid) = pprCondInstr (sLit "j") cond (ppr lab) where lab = mkAsmTempLabel (getUnique blockid) pprInstr (JXX_GBL cond imm) = pprCondInstr (sLit "j") cond (pprImm imm) pprInstr (JMP (OpImm imm) _) = ptext (sLit "\tjmp ") <> pprImm imm pprInstr (JMP op _) = sdocWithPlatform $ \platform -> ptext (sLit "\tjmp *") <> pprOperand (archWordSize (target32Bit platform)) op pprInstr (JMP_TBL op _ _ _) = pprInstr (JMP op []) pprInstr (CALL (Left imm) _) = ptext (sLit "\tcall ") <> pprImm imm pprInstr (CALL (Right reg) _) = sdocWithPlatform $ \platform -> ptext (sLit "\tcall *") <> pprReg (archWordSize (target32Bit platform)) reg pprInstr (IDIV sz op) = pprSizeOp (sLit "idiv") sz op pprInstr (DIV sz op) = pprSizeOp (sLit "div") sz op pprInstr (IMUL2 sz op) = pprSizeOp (sLit "imul") sz op -- x86_64 only pprInstr (MUL size op1 op2) = pprSizeOpOp (sLit "mul") size op1 op2 pprInstr (MUL2 size op) = pprSizeOp (sLit "mul") size op pprInstr (FDIV size op1 op2) = pprSizeOpOp (sLit "div") size op1 op2 pprInstr (CVTSS2SD from to) = pprRegReg (sLit "cvtss2sd") from to pprInstr (CVTSD2SS from to) = pprRegReg (sLit "cvtsd2ss") from to pprInstr (CVTTSS2SIQ sz from to) = pprSizeSizeOpReg (sLit "cvttss2si") FF32 sz from to pprInstr (CVTTSD2SIQ sz from to) = pprSizeSizeOpReg (sLit "cvttsd2si") FF64 sz from to pprInstr (CVTSI2SS sz from to) = pprSizeOpReg (sLit "cvtsi2ss") sz from to pprInstr (CVTSI2SD sz from to) = pprSizeOpReg (sLit "cvtsi2sd") sz from to -- FETCHGOT for PIC on ELF platforms pprInstr (FETCHGOT reg) = vcat [ ptext (sLit "\tcall 1f"), hcat [ ptext (sLit "1:\tpopl\t"), pprReg II32 reg ], hcat [ ptext (sLit "\taddl\t$_GLOBAL_OFFSET_TABLE_+(.-1b), "), pprReg II32 reg ] ] -- FETCHPC for PIC on Darwin/x86 -- get the instruction pointer into a register -- (Terminology note: the IP is called Program Counter on PPC, -- and it's a good thing to use the same name on both platforms) pprInstr (FETCHPC reg) = vcat [ ptext (sLit "\tcall 1f"), hcat [ ptext (sLit "1:\tpopl\t"), pprReg II32 reg ] ] -- ----------------------------------------------------------------------------- -- i386 floating-point -- Simulating a flat register set on the x86 FP stack is tricky. -- you have to free %st(7) before pushing anything on the FP reg stack -- so as to preclude the possibility of a FP stack overflow exception. pprInstr g@(GMOV src dst) | src == dst = empty | otherwise = pprG g (hcat [gtab, gpush src 0, gsemi, gpop dst 1]) -- GLD sz addr dst ==> FLDsz addr ; FSTP (dst+1) pprInstr g@(GLD sz addr dst) = pprG g (hcat [gtab, text "fld", pprSize_x87 sz, gsp, pprAddr addr, gsemi, gpop dst 1]) -- GST sz src addr ==> FLD dst ; FSTPsz addr pprInstr g@(GST sz src addr) | src == fake0 && sz /= FF80 -- fstt instruction doesn't exist = pprG g (hcat [gtab, text "fst", pprSize_x87 sz, gsp, pprAddr addr]) | otherwise = pprG g (hcat [gtab, gpush src 0, gsemi, text "fstp", pprSize_x87 sz, gsp, pprAddr addr]) pprInstr g@(GLDZ dst) = pprG g (hcat [gtab, text "fldz ; ", gpop dst 1]) pprInstr g@(GLD1 dst) = pprG g (hcat [gtab, text "fld1 ; ", gpop dst 1]) pprInstr (GFTOI src dst) = pprInstr (GDTOI src dst) pprInstr g@(GDTOI src dst) = pprG g (vcat [ hcat [gtab, text "subl $8, %esp ; fnstcw 4(%esp)"], hcat [gtab, gpush src 0], hcat [gtab, text "movzwl 4(%esp), ", reg, text " ; orl $0xC00, ", reg], hcat [gtab, text "movl ", reg, text ", 0(%esp) ; fldcw 0(%esp)"], hcat [gtab, text "fistpl 0(%esp)"], hcat [gtab, text "fldcw 4(%esp) ; movl 0(%esp), ", reg], hcat [gtab, text "addl $8, %esp"] ]) where reg = pprReg II32 dst pprInstr (GITOF src dst) = pprInstr (GITOD src dst) pprInstr g@(GITOD src dst) = pprG g (hcat [gtab, text "pushl ", pprReg II32 src, text " ; fildl (%esp) ; ", gpop dst 1, text " ; addl $4,%esp"]) pprInstr g@(GDTOF src dst) = pprG g (vcat [gtab <> gpush src 0, gtab <> text "subl $4,%esp ; fstps (%esp) ; flds (%esp) ; addl $4,%esp ;", gtab <> gpop dst 1]) {- Gruesome swamp follows. If you're unfortunate enough to have ventured this far into the jungle AND you give a Rat's Ass (tm) what's going on, here's the deal. Generate code to do a floating point comparison of src1 and src2, of kind cond, and set the Zero flag if true. The complications are to do with handling NaNs correctly. We want the property that if either argument is NaN, then the result of the comparison is False ... except if we're comparing for inequality, in which case the answer is True. Here's how the general (non-inequality) case works. As an example, consider generating the an equality test: pushl %eax -- we need to mess with this <get src1 to top of FPU stack> fcomp <src2 location in FPU stack> and pop pushed src1 -- Result of comparison is in FPU Status Register bits -- C3 C2 and C0 fstsw %ax -- Move FPU Status Reg to %ax sahf -- move C3 C2 C0 from %ax to integer flag reg -- now the serious magic begins setpo %ah -- %ah = if comparable(neither arg was NaN) then 1 else 0 sete %al -- %al = if arg1 == arg2 then 1 else 0 andb %ah,%al -- %al &= %ah -- so %al == 1 iff (comparable && same); else it holds 0 decb %al -- %al == 0, ZeroFlag=1 iff (comparable && same); else %al == 0xFF, ZeroFlag=0 -- the zero flag is now set as we desire. popl %eax The special case of inequality differs thusly: setpe %ah -- %ah = if incomparable(either arg was NaN) then 1 else 0 setne %al -- %al = if arg1 /= arg2 then 1 else 0 orb %ah,%al -- %al = if (incomparable || different) then 1 else 0 decb %al -- if (incomparable || different) then (%al == 0, ZF=1) else (%al == 0xFF, ZF=0) -} pprInstr g@(GCMP cond src1 src2) | case cond of { NE -> True; _ -> False } = pprG g (vcat [ hcat [gtab, text "pushl %eax ; ",gpush src1 0], hcat [gtab, text "fcomp ", greg src2 1, text "; fstsw %ax ; sahf ; setpe %ah"], hcat [gtab, text "setne %al ; ", text "orb %ah,%al ; decb %al ; popl %eax"] ]) | otherwise = pprG g (vcat [ hcat [gtab, text "pushl %eax ; ",gpush src1 0], hcat [gtab, text "fcomp ", greg src2 1, text "; fstsw %ax ; sahf ; setpo %ah"], hcat [gtab, text "set", pprCond (fix_FP_cond cond), text " %al ; ", text "andb %ah,%al ; decb %al ; popl %eax"] ]) where {- On the 486, the flags set by FP compare are the unsigned ones! (This looks like a HACK to me. WDP 96/03) -} fix_FP_cond :: Cond -> Cond fix_FP_cond GE = GEU fix_FP_cond GTT = GU fix_FP_cond LTT = LU fix_FP_cond LE = LEU fix_FP_cond EQQ = EQQ fix_FP_cond NE = NE fix_FP_cond _ = panic "X86.Ppr.fix_FP_cond: no match" -- there should be no others pprInstr g@(GABS _ src dst) = pprG g (hcat [gtab, gpush src 0, text " ; fabs ; ", gpop dst 1]) pprInstr g@(GNEG _ src dst) = pprG g (hcat [gtab, gpush src 0, text " ; fchs ; ", gpop dst 1]) pprInstr g@(GSQRT sz src dst) = pprG g (hcat [gtab, gpush src 0, text " ; fsqrt"] $$ hcat [gtab, gcoerceto sz, gpop dst 1]) pprInstr g@(GSIN sz l1 l2 src dst) = pprG g (pprTrigOp "fsin" False l1 l2 src dst sz) pprInstr g@(GCOS sz l1 l2 src dst) = pprG g (pprTrigOp "fcos" False l1 l2 src dst sz) pprInstr g@(GTAN sz l1 l2 src dst) = pprG g (pprTrigOp "fptan" True l1 l2 src dst sz) -- In the translations for GADD, GMUL, GSUB and GDIV, -- the first two cases are mere optimisations. The otherwise clause -- generates correct code under all circumstances. pprInstr g@(GADD _ src1 src2 dst) | src1 == dst = pprG g (text "\t#GADD-xxxcase1" $$ hcat [gtab, gpush src2 0, text " ; faddp %st(0),", greg src1 1]) | src2 == dst = pprG g (text "\t#GADD-xxxcase2" $$ hcat [gtab, gpush src1 0, text " ; faddp %st(0),", greg src2 1]) | otherwise = pprG g (hcat [gtab, gpush src1 0, text " ; fadd ", greg src2 1, text ",%st(0)", gsemi, gpop dst 1]) pprInstr g@(GMUL _ src1 src2 dst) | src1 == dst = pprG g (text "\t#GMUL-xxxcase1" $$ hcat [gtab, gpush src2 0, text " ; fmulp %st(0),", greg src1 1]) | src2 == dst = pprG g (text "\t#GMUL-xxxcase2" $$ hcat [gtab, gpush src1 0, text " ; fmulp %st(0),", greg src2 1]) | otherwise = pprG g (hcat [gtab, gpush src1 0, text " ; fmul ", greg src2 1, text ",%st(0)", gsemi, gpop dst 1]) pprInstr g@(GSUB _ src1 src2 dst) | src1 == dst = pprG g (text "\t#GSUB-xxxcase1" $$ hcat [gtab, gpush src2 0, text " ; fsubrp %st(0),", greg src1 1]) | src2 == dst = pprG g (text "\t#GSUB-xxxcase2" $$ hcat [gtab, gpush src1 0, text " ; fsubp %st(0),", greg src2 1]) | otherwise = pprG g (hcat [gtab, gpush src1 0, text " ; fsub ", greg src2 1, text ",%st(0)", gsemi, gpop dst 1]) pprInstr g@(GDIV _ src1 src2 dst) | src1 == dst = pprG g (text "\t#GDIV-xxxcase1" $$ hcat [gtab, gpush src2 0, text " ; fdivrp %st(0),", greg src1 1]) | src2 == dst = pprG g (text "\t#GDIV-xxxcase2" $$ hcat [gtab, gpush src1 0, text " ; fdivp %st(0),", greg src2 1]) | otherwise = pprG g (hcat [gtab, gpush src1 0, text " ; fdiv ", greg src2 1, text ",%st(0)", gsemi, gpop dst 1]) pprInstr GFREE = vcat [ ptext (sLit "\tffree %st(0) ;ffree %st(1) ;ffree %st(2) ;ffree %st(3)"), ptext (sLit "\tffree %st(4) ;ffree %st(5)") ] -- Atomics pprInstr LOCK = ptext (sLit "\tlock") pprInstr (XADD size src dst) = pprSizeOpOp (sLit "xadd") size src dst pprInstr (CMPXCHG size src dst) = pprSizeOpOp (sLit "cmpxchg") size src dst pprInstr _ = panic "X86.Ppr.pprInstr: no match" pprTrigOp :: String -> Bool -> CLabel -> CLabel -> Reg -> Reg -> Size -> SDoc pprTrigOp op -- fsin, fcos or fptan isTan -- we need a couple of extra steps if we're doing tan l1 l2 -- internal labels for us to use src dst sz = -- We'll be needing %eax later on hcat [gtab, text "pushl %eax;"] $$ -- tan is going to use an extra space on the FP stack (if isTan then hcat [gtab, text "ffree %st(6)"] else empty) $$ -- First put the value in %st(0) and try to apply the op to it hcat [gpush src 0, text ("; " ++ op)] $$ -- Now look to see if C2 was set (overflow, |value| >= 2^63) hcat [gtab, text "fnstsw %ax"] $$ hcat [gtab, text "test $0x400,%eax"] $$ -- If we were in bounds then jump to the end hcat [gtab, text "je " <> ppr l1] $$ -- Otherwise we need to shrink the value. Start by -- loading pi, doubleing it (by adding it to itself), -- and then swapping pi with the value, so the value we -- want to apply op to is in %st(0) again hcat [gtab, text "ffree %st(7); fldpi"] $$ hcat [gtab, text "fadd %st(0),%st"] $$ hcat [gtab, text "fxch %st(1)"] $$ -- Now we have a loop in which we make the value smaller, -- see if it's small enough, and loop if not (ppr l2 <> char ':') $$ hcat [gtab, text "fprem1"] $$ -- My Debian libc uses fstsw here for the tan code, but I can't -- see any reason why it should need to be different for tan. hcat [gtab, text "fnstsw %ax"] $$ hcat [gtab, text "test $0x400,%eax"] $$ hcat [gtab, text "jne " <> ppr l2] $$ hcat [gtab, text "fstp %st(1)"] $$ hcat [gtab, text op] $$ (ppr l1 <> char ':') $$ -- Pop the 1.0 tan gave us (if isTan then hcat [gtab, text "fstp %st(0)"] else empty) $$ -- Restore %eax hcat [gtab, text "popl %eax;"] $$ -- And finally make the result the right size hcat [gtab, gcoerceto sz, gpop dst 1] -------------------------- -- coerce %st(0) to the specified size gcoerceto :: Size -> SDoc gcoerceto FF64 = empty gcoerceto FF32 = empty --text "subl $4,%esp ; fstps (%esp) ; flds (%esp) ; addl $4,%esp ; " gcoerceto _ = panic "X86.Ppr.gcoerceto: no match" gpush :: Reg -> RegNo -> SDoc gpush reg offset = hcat [text "fld ", greg reg offset] gpop :: Reg -> RegNo -> SDoc gpop reg offset = hcat [text "fstp ", greg reg offset] greg :: Reg -> RegNo -> SDoc greg reg offset = text "%st(" <> int (gregno reg - firstfake+offset) <> char ')' gsemi :: SDoc gsemi = text " ; " gtab :: SDoc gtab = char '\t' gsp :: SDoc gsp = char ' ' gregno :: Reg -> RegNo gregno (RegReal (RealRegSingle i)) = i gregno _ = --pprPanic "gregno" (ppr other) 999 -- bogus; only needed for debug printing pprG :: Instr -> SDoc -> SDoc pprG fake actual = (char '#' <> pprGInstr fake) $$ actual pprGInstr :: Instr -> SDoc pprGInstr (GMOV src dst) = pprSizeRegReg (sLit "gmov") FF64 src dst pprGInstr (GLD sz src dst) = pprSizeAddrReg (sLit "gld") sz src dst pprGInstr (GST sz src dst) = pprSizeRegAddr (sLit "gst") sz src dst pprGInstr (GLDZ dst) = pprSizeReg (sLit "gldz") FF64 dst pprGInstr (GLD1 dst) = pprSizeReg (sLit "gld1") FF64 dst pprGInstr (GFTOI src dst) = pprSizeSizeRegReg (sLit "gftoi") FF32 II32 src dst pprGInstr (GDTOI src dst) = pprSizeSizeRegReg (sLit "gdtoi") FF64 II32 src dst pprGInstr (GITOF src dst) = pprSizeSizeRegReg (sLit "gitof") II32 FF32 src dst pprGInstr (GITOD src dst) = pprSizeSizeRegReg (sLit "gitod") II32 FF64 src dst pprGInstr (GDTOF src dst) = pprSizeSizeRegReg (sLit "gdtof") FF64 FF32 src dst pprGInstr (GCMP co src dst) = pprCondRegReg (sLit "gcmp_") FF64 co src dst pprGInstr (GABS sz src dst) = pprSizeRegReg (sLit "gabs") sz src dst pprGInstr (GNEG sz src dst) = pprSizeRegReg (sLit "gneg") sz src dst pprGInstr (GSQRT sz src dst) = pprSizeRegReg (sLit "gsqrt") sz src dst pprGInstr (GSIN sz _ _ src dst) = pprSizeRegReg (sLit "gsin") sz src dst pprGInstr (GCOS sz _ _ src dst) = pprSizeRegReg (sLit "gcos") sz src dst pprGInstr (GTAN sz _ _ src dst) = pprSizeRegReg (sLit "gtan") sz src dst pprGInstr (GADD sz src1 src2 dst) = pprSizeRegRegReg (sLit "gadd") sz src1 src2 dst pprGInstr (GSUB sz src1 src2 dst) = pprSizeRegRegReg (sLit "gsub") sz src1 src2 dst pprGInstr (GMUL sz src1 src2 dst) = pprSizeRegRegReg (sLit "gmul") sz src1 src2 dst pprGInstr (GDIV sz src1 src2 dst) = pprSizeRegRegReg (sLit "gdiv") sz src1 src2 dst pprGInstr _ = panic "X86.Ppr.pprGInstr: no match" pprDollImm :: Imm -> SDoc pprDollImm i = ptext (sLit "$") <> pprImm i pprOperand :: Size -> Operand -> SDoc pprOperand s (OpReg r) = pprReg s r pprOperand _ (OpImm i) = pprDollImm i pprOperand _ (OpAddr ea) = pprAddr ea pprMnemonic_ :: LitString -> SDoc pprMnemonic_ name = char '\t' <> ptext name <> space pprMnemonic :: LitString -> Size -> SDoc pprMnemonic name size = char '\t' <> ptext name <> pprSize size <> space pprSizeImmOp :: LitString -> Size -> Imm -> Operand -> SDoc pprSizeImmOp name size imm op1 = hcat [ pprMnemonic name size, char '$', pprImm imm, comma, pprOperand size op1 ] pprSizeOp_ :: LitString -> Size -> Operand -> SDoc pprSizeOp_ name size op1 = hcat [ pprMnemonic_ name , pprOperand size op1 ] pprSizeOp :: LitString -> Size -> Operand -> SDoc pprSizeOp name size op1 = hcat [ pprMnemonic name size, pprOperand size op1 ] pprSizeOpOp :: LitString -> Size -> Operand -> Operand -> SDoc pprSizeOpOp name size op1 op2 = hcat [ pprMnemonic name size, pprOperand size op1, comma, pprOperand size op2 ] pprOpOp :: LitString -> Size -> Operand -> Operand -> SDoc pprOpOp name size op1 op2 = hcat [ pprMnemonic_ name, pprOperand size op1, comma, pprOperand size op2 ] pprSizeReg :: LitString -> Size -> Reg -> SDoc pprSizeReg name size reg1 = hcat [ pprMnemonic name size, pprReg size reg1 ] pprSizeRegReg :: LitString -> Size -> Reg -> Reg -> SDoc pprSizeRegReg name size reg1 reg2 = hcat [ pprMnemonic name size, pprReg size reg1, comma, pprReg size reg2 ] pprRegReg :: LitString -> Reg -> Reg -> SDoc pprRegReg name reg1 reg2 = sdocWithPlatform $ \platform -> hcat [ pprMnemonic_ name, pprReg (archWordSize (target32Bit platform)) reg1, comma, pprReg (archWordSize (target32Bit platform)) reg2 ] pprSizeOpReg :: LitString -> Size -> Operand -> Reg -> SDoc pprSizeOpReg name size op1 reg2 = sdocWithPlatform $ \platform -> hcat [ pprMnemonic name size, pprOperand size op1, comma, pprReg (archWordSize (target32Bit platform)) reg2 ] pprCondRegReg :: LitString -> Size -> Cond -> Reg -> Reg -> SDoc pprCondRegReg name size cond reg1 reg2 = hcat [ char '\t', ptext name, pprCond cond, space, pprReg size reg1, comma, pprReg size reg2 ] pprSizeSizeRegReg :: LitString -> Size -> Size -> Reg -> Reg -> SDoc pprSizeSizeRegReg name size1 size2 reg1 reg2 = hcat [ char '\t', ptext name, pprSize size1, pprSize size2, space, pprReg size1 reg1, comma, pprReg size2 reg2 ] pprSizeSizeOpReg :: LitString -> Size -> Size -> Operand -> Reg -> SDoc pprSizeSizeOpReg name size1 size2 op1 reg2 = hcat [ pprMnemonic name size2, pprOperand size1 op1, comma, pprReg size2 reg2 ] pprSizeRegRegReg :: LitString -> Size -> Reg -> Reg -> Reg -> SDoc pprSizeRegRegReg name size reg1 reg2 reg3 = hcat [ pprMnemonic name size, pprReg size reg1, comma, pprReg size reg2, comma, pprReg size reg3 ] pprSizeAddrReg :: LitString -> Size -> AddrMode -> Reg -> SDoc pprSizeAddrReg name size op dst = hcat [ pprMnemonic name size, pprAddr op, comma, pprReg size dst ] pprSizeRegAddr :: LitString -> Size -> Reg -> AddrMode -> SDoc pprSizeRegAddr name size src op = hcat [ pprMnemonic name size, pprReg size src, comma, pprAddr op ] pprShift :: LitString -> Size -> Operand -> Operand -> SDoc pprShift name size src dest = hcat [ pprMnemonic name size, pprOperand II8 src, -- src is 8-bit sized comma, pprOperand size dest ] pprSizeOpOpCoerce :: LitString -> Size -> Size -> Operand -> Operand -> SDoc pprSizeOpOpCoerce name size1 size2 op1 op2 = hcat [ char '\t', ptext name, pprSize size1, pprSize size2, space, pprOperand size1 op1, comma, pprOperand size2 op2 ] pprCondInstr :: LitString -> Cond -> SDoc -> SDoc pprCondInstr name cond arg = hcat [ char '\t', ptext name, pprCond cond, space, arg]
frantisekfarka/ghc-dsi
compiler/nativeGen/X86/Ppr.hs
bsd-3-clause
42,504
0
28
13,159
12,559
6,253
6,306
815
97
-------------------------------------------------------------------------------- -- | -- Module : GalFld.Core.FiniteFields -- Note : Allgemeine implementierung endlicher Körper -- -- -- -------------------------------------------------------------------------------- module GalFld.Core.FiniteFields ( FFElem (..), listFFElem , aggF , charOfP, charRootP , module X ) where import Data.Maybe import Data.List import Control.Exception import Data.Binary import Control.Monad import Data.Ord (Ordering (..)) import Control.DeepSeq import GalFld.Core.FiniteField as X import GalFld.Core.PrimeFields as X import GalFld.Core.Polynomials import GalFld.Core.ShowTex -------------------------------------------------------------------------------- -- Definition -- Ein Element im Körper ist repräsentiert durch ein Paar von Polynomen. Das -- erste beschreibt das Element, das zweite das Minimalpolynom -- und damit den Erweiterungskörper. -- Zusätzlich ist auch die kanonische Inklusion aus dem Grundkörper durch -- FFKonst implementiert. data FFElem a = FFElem (Polynom a) (Polynom a) | FFKonst a aggF :: (Show a, Eq a, Fractional a) => FFElem a -> FFElem a aggF (FFKonst x) = FFKonst x aggF (FFElem f p) = FFElem (modByP f p) p listFFElem m = map (`FFElem` m) -------------------------------------------------------------------------------- -- Instanzen instance (Show a, Num a, Eq a, Fractional a) => Eq (FFElem a) where (FFKonst x) == (FFKonst y) = x==y (FFElem f p) == (FFKonst y) = isNullP $ f - pKonst y (FFKonst x) == (FFElem g p) = isNullP $ g - pKonst x (FFElem f p) == (FFElem g q) | p==q = isNullP $ f-g | otherwise = error "Not the same mod" instance (Show a, Num a, Eq a) => Show (FFElem a) where show (FFKonst x) = "(" ++ show x ++ " mod ...)" show (FFElem f p) | isNullP f = "(0 mod " ++ show p ++ ")" | otherwise = "(" ++ show f ++ " mod " ++ show p ++")" instance (ShowTex a, Num a, Eq a) => ShowTex (FFElem a) where showTex (FFKonst x) = showTex x showTex (FFElem f p) | isNullP f = "\\left(\\underline{0}_{mod~" ++ showTex p ++ "}\\right)" | otherwise = "\\left(\\underline{" ++ showTex f ++ "}_{mod~" ++ showTex p ++"}\\right)" instance (Show a, Num a, Eq a, Fractional a) => Num (FFElem a) where fromInteger i = FFKonst (fromInteger i) {-# INLINE (+) #-} (FFKonst x) + (FFKonst y) = FFKonst (x+y) (FFElem f p) + (FFKonst x) = FFElem (f + pKonst x) p (FFKonst x) + (FFElem f p) = FFElem (f + pKonst x) p (FFElem f p) + (FFElem g q) | p==q = aggF $ FFElem (f+g) p | otherwise = error "Not the same mod" {-# INLINE (*) #-} (FFKonst x) * (FFKonst y) = FFKonst (x*y) (FFElem f p) * (FFKonst x) = FFElem (f * pKonst x) p (FFKonst x) * (FFElem f p) = FFElem (f * pKonst x) p (FFElem f p) * (FFElem g q) | p==q = aggF $ FFElem (f*g) p | otherwise = error "Not the same mod" {-# INLINE negate #-} negate (FFKonst x) = FFKonst (negate x) negate (FFElem f p) = FFElem (negate f) p abs _ = error "Prelude.Num.abs: inappropriate abstraction" signum _ = error "Prelude.Num.signum: inappropriate abstraction" instance (Show a, Eq a, Fractional a) => Fractional (FFElem a) where fromRational _ = error "inappropriate abstraction" {-# INLINE recip #-} recip (FFKonst x) = FFKonst (recip x) recip (FFElem f p) | isNullP f = error "Division by zero" | otherwise = FFElem s p where (_,s,_) = eekP f p instance (Show a, Eq a, Num a, Fractional a, FiniteField a) => FiniteField (FFElem a) where zero = FFKonst zero one = FFKonst one elems = elems' {-# INLINE charakteristik #-} charakteristik (FFElem _ m) = charakteristik $ getReprP m charakteristik (FFKonst x) = charakteristik x elemCount (FFKonst _) = error "Insufficient information in FFKonst" elemCount (FFElem _ m) = elemCount (getReprP m) ^ uDegP m {-# INLINE getReprP #-} getReprP = getReprP' instance (Num a, Eq a, NFData a) => NFData (FFElem a) where rnf (FFElem f p) = rnf (f,p) rnf (FFKonst x) = rnf x -- |Nimmt ein Element aus einem Endlichen Körper und gibt eine Liste aller -- anderen Elemente zurrück. -- Diese Funktion benötigt ein FFElem, ein FFKonst ist zu universell und -- enthält deswegen zu wenig Information, über den Körper in dem es lebt. elems' :: (Show a, Num a, Fractional a, FiniteField a) => FFElem a -> [FFElem a] elems' (FFKonst x) = error "Insufficient information in FFKonst" elems' elm@(FFElem f p) = map (`FFElem` p) (nullP : getAllP (elems e) (uDegP p -1)) where e = getReprP p {-# INLINE getReprP' #-} getReprP' f = getReprP'' $ p2Tup f getReprP'' [] = error "Insufficient information in this Polynomial" getReprP'' ((i,FFKonst _):ms) = getReprP'' ms getReprP'' ((i,FFElem f p): ms) = FFElem 0 p instance (Num a, Binary a) => Binary (FFElem a) where put (FFKonst f) = do put (0 :: Word8) put f put (FFElem f p) = do put (1 :: Word8) put f put p get = do t <- get :: Get Word8 case t of 0 -> liftM FFKonst get 1 -> liftM2 FFElem get get _ -> undefined -------------------------------------------------------------------------------- -- Funktionen auf Polynomen über Endlichen Körpern {-# INLINE charOfP #-} -- |Gibt die Charakteristik der Koeffizienten eines Polynoms charOfP :: (Eq a, FiniteField a, Num a) => Polynom a -> Int charOfP f = charakteristik $ getReprP f {-# INLINE charRootP #-} -- |Zieht die p-te Wurzel aus einem Polynom, wobei p die Charakteristik ist charRootP :: (Show a, FiniteField a, Num a) => Polynom a -> Polynom a charRootP f | isNullP f = nullP | f == pKonst 1 = pKonst 1 | otherwise = pTupUnsave [(i `quot` p,m^l) | (i,m) <- p2Tup f] where p = charOfP f q = elemCount $ getReprP f l = max (quot q p) 1 hasNSInFF :: (Eq a, Num a, FiniteField a) => Polynom a -> Bool hasNSInFF f = not (null [f | e <- elems (getReprP f), evalP e f == 0])
maximilianhuber/softwareProjekt
src/GalFld/Core/FiniteFields.hs
bsd-3-clause
6,503
0
13
1,828
2,230
1,121
1,109
112
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE QuantifiedConstraints #-} {-# LANGUAGE TypeFamilies #-} module T17202 where type family F a class C1 a class (forall c. C1 c) => C2 a class (forall b. (b ~ F a) => C2 a) => C3 a data Dict c = c => Dict foo :: forall a. C3 a => Dict (C1 a) foo = Dict bar :: forall a. C3 a => Dict (C1 a) bar = Dict :: C2 a => Dict (C1 a)
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T17202.hs
bsd-3-clause
364
0
10
90
170
90
80
-1
-1
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, FlexibleInstances #-} module Curve where import Data.Functor.Classes import qualified Data.List as List import qualified Data.Set as Set data Name = Local Int | Global String deriving (Eq, Ord) data Expression term = Type | Implicit | Variable Name | Lambda Int term term | Application term term deriving (Show, Eq, Functor, Foldable, Traversable) data Term f = Term { out :: f (Term f) } type Term' = Term Expression data Unification f = Unification (f (Unification f)) | Conflict (Term f) (Term f) type Unification' = Unification Expression -- DSL for constructing terms type' :: Term' type' = Term Type implicit :: Term' implicit = Term Implicit variable :: Name -> Term' variable = Term . Variable local :: Int -> Term' local = variable . Local global :: String -> Term' global = variable . Global infixl 9 `apply` apply :: Term' -> Term' -> Term' apply a = Term . Application a infixr `lambda` lambda :: Term' -> (Term' -> Term') -> Term' lambda t f = Term $ Lambda i t body where i = maybe 0 succ $ maxBoundVariable body body = f (Term $ Variable $ Local i) infixr --> (-->) :: Term' -> Term' -> Term' a --> b = a `lambda` const b infixr `pi` pi :: Term' -> (Term' -> Term') -> Term' pi = lambda -- Unifications into :: Functor f => Term f -> Unification f into term = Unification $ into <$> out term unified :: Unification' -> Maybe Term' unified (Unification expression) = Term <$> traverse unified expression unified (Conflict _ _) = Nothing -- Binding rename :: Int -> Int -> Term' -> Term' rename old new term | old == new = term rename old new term = Term $ case out term of Variable (Local name) | name == old -> Variable $ Local new Lambda name t b -> if name == old then Lambda name (rename old new t) b else Lambda name (rename old new t) (rename old new b) Application a b -> Application (rename old new a) (rename old new b) other -> other substitute :: Int -> Term' -> Term' -> Term' substitute name withTerm inScope = case out inScope of Variable (Local n) | n == name -> withTerm Lambda n inType inBody -> if n == name then Term $ Lambda n (substitute name withTerm inType) inBody else Term $ Lambda n (substitute name withTerm inType) (substitute name withTerm inBody) Application inA inB -> Term $ Application (substitute name withTerm inA) (substitute name withTerm inB) _ -> inScope unify :: Term' -> Term' -> Unification' unify expected actual = case (out expected, out actual) of (_, Implicit) -> into expected (Implicit, _) -> into actual (Type, Type) -> into expected (Variable n1, Variable n2) | n1 == n2 -> Unification $ Variable n2 (Application a1 b1, Application a2 b2) -> Unification $ Application (unify a1 a2) (unify b1 b2) (Lambda i1 a1 b1, Lambda i2 a2 b2) | i1 == i2 -> Unification $ Lambda i2 (unify a1 a2) (unify b1 b2) _ -> Conflict expected actual freeVariables :: Term' -> Set.Set Name freeVariables = cata inExpression where inExpression expression = case expression of Variable name -> Set.singleton name Lambda i t b -> Set.delete (Local i) b `Set.union` t Application a b -> a `Set.union` b _ -> mempty maxBoundVariable :: Term' -> Maybe Int maxBoundVariable = cata (\ expression -> case expression of Lambda n t _ -> max (Just n) t Application a b -> max a b _ -> Nothing) -- Recursion schemes cata :: Functor f => (f a -> a) -> Term f -> a cata f = f . fmap (cata f) . out para :: Functor f => (f (Term f, a) -> a) -> Term f -> a para f = f . fmap fanout . out where fanout a = (a, para f a) -- Numerals digits :: Integral a => a -> a -> [a] digits base i = fst $ foldr nextDigit ([], i) (replicate (fromIntegral $ countDigits base i) ()) where nextDigit _ (list, prev) | (next, remainder) <- prev `divMod` base = (remainder : list, next) countDigits :: Integral a => a -> a -> a countDigits base i = 1 + floor (logBase (fromIntegral base) (fromIntegral $ abs i) :: Double) showNumeral :: Integral i => String -> i -> String showNumeral "" _ = "" showNumeral alphabet i = List.genericIndex alphabet <$> digits (List.genericLength alphabet) i -- Instances instance Show Name where show (Local i) = showNumeral ['a'..'z'] i show (Global s) = s instance Eq1 Expression where eq1 = (==) instance Show Term' where showsPrec = showsLevelPrec False showsLevelPrec :: Bool -> Int -> Term' -> ShowS showsLevelPrec isType n term = case out term of Variable name -> shows name Type -> showString "Type" Implicit -> showString "_" Application a b -> showParen (n > prec) (showsLevelPrec isType prec a . showString " " . showsLevelPrec isType (prec + 1) b) where prec = 10 Lambda i t body | Set.member (Local i) (freeVariables body) -> if isType then showString "(" . shows (Local i) . showString " : " . showsType t . showString ") → " . showsType body else showString "λ " . shows (Local i) . showString " : " . showsType t . showString " . " . showsLevel isType body Lambda _ t body -> showParen (n > 0) $ if isType then showsLevelPrec True 1 t . showString " → " . showsType body else showString "λ _ : " . showsType t . showString " . " . showsLevel isType body showsLevel :: Bool -> Term' -> ShowS showsLevel level = showsLevelPrec level 0 showsType :: Term' -> ShowS showsType = showsLevel True instance Eq1 f => Eq (Term f) where a == b = out a `eq1` out b instance Eq1 f => Eq (Unification f) where Unification a == Unification b = a `eq1` b Conflict a1 b1 == Conflict a2 b2 = a1 == a2 && b1 == b2 _ == _ = False instance Show Unification' where show (Unification out) = show out show (Conflict a b) = "Expected: " ++ show a ++ "\n" ++ " Actual: " ++ show b ++ "\n"
antitypical/Curve
src/Curve.hs
bsd-3-clause
5,838
0
17
1,320
2,436
1,220
1,216
134
8
module ReaderPractice where import Control.Applicative import Data.Maybe x :: [Integer] x = [1, 2, 3] y :: [Integer] y = [4, 5, 6] z :: [Integer] z = [7, 8, 9] xs :: Maybe Integer xs = lookup 3 $ zip x y ys :: Maybe Integer ys = lookup 6 $ zip y z zs :: Maybe Integer zs = lookup 4 $ zip x y z' :: Integer -> Maybe Integer z' n = lookup n $ zip x y x1 :: Maybe (Integer, Integer) x1 = (,) <$> xs <*> ys x2 :: Maybe (Integer, Integer) x2 = (,) <$> ys <*> zs x3 :: Integer -> Maybe (Integer, Integer) x3 n = (,) <$> z' n <*> z' n summed :: Num c => (c, c) -> c summed = uncurry (+) bolt :: Integer -> Bool bolt = (&&) <$> (>3) <*> (<8) sequA :: Integral a => a -> [Bool] sequA = sequenceA [(>3), (<8), even] s' :: Maybe Integer s' = summed <$> ((,) <$> xs <*> ys) main :: IO () main = do print $ and (sequA 4)
actionshrimp/haskell-book
src/ReaderPractice.hs
bsd-3-clause
826
0
10
205
460
254
206
34
1
{-# OPTIONS_GHC -fno-warn-unused-matches -fno-warn-unused-binds #-} module Ling.Fmt.Benjamin.Layout where import Ling.Fmt.Benjamin.Lex import Data.Maybe (isNothing, fromJust) -- Generated by the BNF Converter -- local parameters topLayout :: Bool topLayout = True layoutWords, layoutStopWords :: [String] layoutWords = ["of"] layoutStopWords = [] -- layout separators layoutOpen, layoutClose, layoutSep :: String layoutOpen = "{" layoutClose = "}" layoutSep = "," -- | Replace layout syntax with explicit layout tokens. resolveLayout :: Bool -- ^ Whether to use top-level layout. -> [Token] -> [Token] resolveLayout tp = res Nothing [if tl then Implicit 1 else Explicit] where -- Do top-level layout if the function parameter and the grammar say so. tl = tp && topLayout res :: Maybe Token -- ^ The previous token, if any. -> [Block] -- ^ A stack of layout blocks. -> [Token] -> [Token] -- The stack should never be empty. res _ [] ts = error $ "Layout error: stack empty. Tokens: " ++ show ts res _ st (t0:ts) -- We found an open brace in the input, -- put an explicit layout block on the stack. -- This is done even if there was no layout word, -- to keep opening and closing braces. | isLayoutOpen t0 = moveAlong (Explicit:st) [t0] ts -- We are in an implicit layout block res pt st@(Implicit n:ns) (t0:ts) -- End of implicit block by a layout stop word | isStop t0 = -- Exit the current block and all implicit blocks -- more indented than the current token let (ebs,ns') = span (`moreIndent` column t0) ns moreIndent (Implicit x) y = x > y moreIndent Explicit _ = False -- the number of blocks exited b = 1 + length ebs bs = replicate b layoutClose -- Insert closing braces after the previous token. (ts1,ts2) = splitAt (1+b) $ addTokens (afterPrev pt) bs (t0:ts) in moveAlong ns' ts1 ts2 -- End of an implicit layout block | newLine pt t0 && column t0 < n = -- Insert a closing brace after the previous token. let b:t0':ts' = addToken (afterPrev pt) layoutClose (t0:ts) -- Repeat, with the current block removed from the stack in moveAlong ns [b] (t0':ts') res pt st (t0:ts) -- Start a new layout block if the first token is a layout word | isLayout t0 = case ts of -- Explicit layout, just move on. The case above -- will push an explicit layout block. t1:_ | isLayoutOpen t1 -> moveAlong st [t0] ts -- at end of file, the start column doesn't matter _ -> let col = if null ts then column t0 else column (head ts) -- insert an open brace after the layout word b:ts' = addToken (nextPos t0) layoutOpen ts -- save the start column st' = Implicit col:st in -- Do we have to insert an extra layoutSep? case st of Implicit n:_ | newLine pt t0 && column t0 == n && not (isNothing pt || isTokenIn [layoutSep,layoutOpen] (fromJust pt)) -> let b':t0':b'':ts'' = addToken (afterPrev pt) layoutSep (t0:b:ts') in moveAlong st' [b',t0',b''] ts' _ -> moveAlong st' [t0,b] ts' -- If we encounter a closing brace, exit the first explicit layout block. | isLayoutClose t0 = let st' = drop 1 (dropWhile isImplicit st) in if null st' then error $ "Layout error: Found " ++ layoutClose ++ " at (" ++ show (line t0) ++ "," ++ show (column t0) ++ ") without an explicit layout block." else moveAlong st' [t0] ts -- Insert separator if necessary. res pt st@(Implicit n:ns) (t0:ts) -- Encounted a new line in an implicit layout block. | newLine pt t0 && column t0 == n = -- Insert a semicolon after the previous token. -- unless we are the beginning of the file, -- or the previous token is a semicolon or open brace. if isNothing pt || isTokenIn [layoutSep,layoutOpen] (fromJust pt) then moveAlong st [t0] ts else let b:t0':ts' = addToken (afterPrev pt) layoutSep (t0:ts) in moveAlong st [b,t0'] ts' -- Nothing to see here, move along. res _ st (t:ts) = moveAlong st [t] ts -- At EOF: skip explicit blocks. res (Just t) (Explicit:bs) [] | null bs = [] | otherwise = res (Just t) bs [] -- If we are using top-level layout, insert a semicolon after -- the last token, if there isn't one already res (Just t) [Implicit _n] [] | isTokenIn [layoutSep] t = [] | otherwise = addToken (nextPos t) layoutSep [] -- At EOF in an implicit, non-top-level block: close the block res (Just t) (Implicit _n:bs) [] = let c = addToken (nextPos t) layoutClose [] in moveAlong bs c [] -- This should only happen if the input is empty. res Nothing _st [] = [] -- | Move on to the next token. moveAlong :: [Block] -- ^ The layout stack. -> [Token] -- ^ Any tokens just processed. -> [Token] -- ^ the rest of the tokens. -> [Token] moveAlong _ [] _ = error $ "Layout error: moveAlong got [] as old tokens" moveAlong st ot ts = ot ++ res (Just $ last ot) st ts newLine :: Maybe Token -> Token -> Bool newLine pt t0 = case pt of Nothing -> True Just t -> line t /= line t0 data Block = Implicit Int -- ^ An implicit layout block with its start column. | Explicit deriving Show type Position = Posn -- | Check if s block is implicit. isImplicit :: Block -> Bool isImplicit (Implicit _) = True isImplicit _ = False -- | Insert a number of tokens at the begninning of a list of tokens. addTokens :: Position -- ^ Position of the first new token. -> [String] -- ^ Token symbols. -> [Token] -- ^ The rest of the tokens. These will have their -- positions updated to make room for the new tokens . -> [Token] addTokens p ss ts = foldr (addToken p) ts ss -- | Insert a new symbol token at the begninning of a list of tokens. addToken :: Position -- ^ Position of the new token. -> String -- ^ Symbol in the new token. -> [Token] -- ^ The rest of the tokens. These will have their -- positions updated to make room for the new token. -> [Token] addToken p s ts = sToken p s : map (incrGlobal p (length s)) ts -- | Get the position immediately to the right of the given token. -- If no token is given, gets the first position in the file. afterPrev :: Maybe Token -> Position afterPrev = maybe (Pn 0 1 1) nextPos -- | Get the position immediately to the right of the given token. nextPos :: Token -> Position nextPos t = Pn (g + s) l (c + s + 1) where Pn g l c = position t s = tokenLength t -- | Add to the global and column positions of a token. -- The column position is only changed if the token is on -- the same line as the given position. incrGlobal :: Position -- ^ If the token is on the same line -- as this position, update the column position. -> Int -- ^ Number of characters to add to the position. -> Token -> Token incrGlobal (Pn _ l0 _) i (PT (Pn g l c) t) = if l /= l0 then PT (Pn (g + i) l c) t else PT (Pn (g + i) l (c + i)) t incrGlobal _ _ p = error $ "cannot add token at " ++ show p -- | Create a symbol token. sToken :: Position -> String -> Token sToken p s = PT p (TS s i) where i = case s of "!" -> 1 "(" -> 2 ")" -> 3 "**" -> 4 "," -> 5 "->" -> 6 "-o" -> 7 "." -> 8 ":" -> 9 ":*" -> 10 ":]" -> 11 ";" -> 12 "<" -> 13 "<-" -> 14 "<=" -> 15 "=" -> 16 ">" -> 17 "?" -> 18 "@" -> 19 "Type" -> 20 "[" -> 21 "[:" -> 22 "\\" -> 23 "]" -> 24 "^" -> 25 "`" -> 26 "as" -> 27 "assert" -> 28 "case" -> 29 "data" -> 30 "end" -> 31 "fwd" -> 32 "in" -> 33 "let" -> 34 "new" -> 35 "new/" -> 36 "of" -> 37 "parallel" -> 38 "proc" -> 39 "recv" -> 40 "send" -> 41 "sequence" -> 42 "slice" -> 43 "split" -> 44 "with" -> 45 "{" -> 46 "|" -> 47 "}" -> 48 "~" -> 49 _ -> error $ "not a reserved word: " ++ show s -- | Get the position of a token. position :: Token -> Position position t = case t of PT p _ -> p Err p -> p -- | Get the line number of a token. line :: Token -> Int line t = case position t of Pn _ l _ -> l -- | Get the column number of a token. column :: Token -> Int column t = case position t of Pn _ _ c -> c -- | Check if a token is one of the given symbols. isTokenIn :: [String] -> Token -> Bool isTokenIn ts t = case t of PT _ (TS r _) | elem r ts -> True _ -> False -- | Check if a word is a layout start token. isLayout :: Token -> Bool isLayout = isTokenIn layoutWords -- | Check if a token is a layout stop token. isStop :: Token -> Bool isStop = isTokenIn layoutStopWords -- | Check if a token is the layout open token. isLayoutOpen :: Token -> Bool isLayoutOpen = isTokenIn [layoutOpen] -- | Check if a token is the layout close token. isLayoutClose :: Token -> Bool isLayoutClose = isTokenIn [layoutClose] -- | Get the number of characters in the token. tokenLength :: Token -> Int tokenLength t = length $ prToken t
np/ling
Ling/Fmt/Benjamin/Layout.hs
bsd-3-clause
9,839
0
25
3,215
2,543
1,319
1,224
189
50
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Data.GraphQL.Parser where import Prelude hiding (takeWhile) #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>), (<*>), (*>), (<*), (<$), pure) import Data.Monoid (Monoid, mempty) #endif import Control.Applicative ((<|>), empty, many, optional) import Control.Monad (when) import Data.Char (isDigit, isSpace) import Data.Foldable (traverse_) import Data.Text (Text, append) import Data.Attoparsec.Text ( Parser , (<?>) , anyChar , decimal , double , endOfLine , inClass , many1 , manyTill , option , peekChar , sepBy1 , signed , takeWhile , takeWhile1 ) import Data.GraphQL.AST -- * Name name :: Parser Name name = tok $ append <$> takeWhile1 isA_z <*> takeWhile ((||) <$> isDigit <*> isA_z) where -- `isAlpha` handles many more Unicode Chars isA_z = inClass $ '_' : ['A'..'Z'] ++ ['a'..'z'] -- * Document document :: Parser Document document = whiteSpace *> (Document <$> many1 definition) -- Try SelectionSet when no definition <|> (Document . pure . DefinitionOperation . Query . Node mempty empty empty <$> selectionSet) <?> "document error!" definition :: Parser Definition definition = DefinitionOperation <$> operationDefinition <|> DefinitionFragment <$> fragmentDefinition <|> DefinitionType <$> typeDefinition <?> "definition error!" operationDefinition :: Parser OperationDefinition operationDefinition = Query <$ tok "query" <*> node <|> Mutation <$ tok "mutation" <*> node <?> "operationDefinition error!" node :: Parser Node node = Node <$> name <*> optempty variableDefinitions <*> optempty directives <*> selectionSet variableDefinitions :: Parser [VariableDefinition] variableDefinitions = parens (many1 variableDefinition) variableDefinition :: Parser VariableDefinition variableDefinition = VariableDefinition <$> variable <* tok ":" <*> type_ <*> optional defaultValue defaultValue :: Parser DefaultValue defaultValue = tok "=" *> value variable :: Parser Variable variable = Variable <$ tok "$" <*> name selectionSet :: Parser SelectionSet selectionSet = braces $ many1 selection selection :: Parser Selection selection = SelectionField <$> field -- Inline first to catch `on` case <|> SelectionInlineFragment <$> inlineFragment <|> SelectionFragmentSpread <$> fragmentSpread <?> "selection error!" field :: Parser Field field = Field <$> optempty alias <*> name <*> optempty arguments <*> optempty directives <*> optempty selectionSet alias :: Parser Alias alias = name <* tok ":" arguments :: Parser [Argument] arguments = parens $ many1 argument argument :: Parser Argument argument = Argument <$> name <* tok ":" <*> value -- * Fragments fragmentSpread :: Parser FragmentSpread -- TODO: Make sure it fails when `... on`. -- See https://facebook.github.io/graphql/#FragmentSpread fragmentSpread = FragmentSpread <$ tok "..." <*> name <*> optempty directives -- InlineFragment tried first in order to guard against 'on' keyword inlineFragment :: Parser InlineFragment inlineFragment = InlineFragment <$ tok "..." <* tok "on" <*> typeCondition <*> optempty directives <*> selectionSet fragmentDefinition :: Parser FragmentDefinition fragmentDefinition = FragmentDefinition <$ tok "fragment" <*> name <* tok "on" <*> typeCondition <*> optempty directives <*> selectionSet typeCondition :: Parser TypeCondition typeCondition = namedType -- * Values -- This will try to pick the first type it can parse. If you are working with -- explicit types use the `typedValue` parser. value :: Parser Value value = ValueVariable <$> variable -- TODO: Handle maxBound, Int32 in spec. <|> ValueInt <$> tok (signed decimal) <|> ValueFloat <$> tok (signed double) <|> ValueBoolean <$> booleanValue <|> ValueString <$> stringValue -- `true` and `false` have been tried before <|> ValueEnum <$> name <|> ValueList <$> listValue <|> ValueObject <$> objectValue <?> "value error!" booleanValue :: Parser Bool booleanValue = True <$ tok "true" <|> False <$ tok "false" -- TODO: Escape characters. Look at `jsstring_` in aeson package. stringValue :: Parser StringValue stringValue = StringValue <$> quotes (takeWhile (/= '"')) -- Notice it can be empty listValue :: Parser ListValue listValue = ListValue <$> brackets (many value) -- Notice it can be empty objectValue :: Parser ObjectValue objectValue = ObjectValue <$> braces (many objectField) objectField :: Parser ObjectField objectField = ObjectField <$> name <* tok ":" <*> value -- * Directives directives :: Parser [Directive] directives = many1 directive directive :: Parser Directive directive = Directive <$ tok "@" <*> name <*> optempty arguments -- * Type Reference type_ :: Parser Type type_ = TypeList <$> listType <|> TypeNonNull <$> nonNullType <|> TypeNamed <$> namedType <?> "type_ error!" namedType :: Parser NamedType namedType = NamedType <$> name listType :: Parser ListType listType = ListType <$> brackets type_ nonNullType :: Parser NonNullType nonNullType = NonNullTypeNamed <$> namedType <* tok "!" <|> NonNullTypeList <$> listType <* tok "!" <?> "nonNullType error!" -- * Type Definition typeDefinition :: Parser TypeDefinition typeDefinition = TypeDefinitionObject <$> objectTypeDefinition <|> TypeDefinitionInterface <$> interfaceTypeDefinition <|> TypeDefinitionUnion <$> unionTypeDefinition <|> TypeDefinitionScalar <$> scalarTypeDefinition <|> TypeDefinitionEnum <$> enumTypeDefinition <|> TypeDefinitionInputObject <$> inputObjectTypeDefinition <|> TypeDefinitionTypeExtension <$> typeExtensionDefinition <?> "typeDefinition error!" objectTypeDefinition :: Parser ObjectTypeDefinition objectTypeDefinition = ObjectTypeDefinition <$ tok "type" <*> name <*> optempty interfaces <*> fieldDefinitions interfaces :: Parser Interfaces interfaces = tok "implements" *> many1 namedType fieldDefinitions :: Parser [FieldDefinition] fieldDefinitions = braces $ many1 fieldDefinition fieldDefinition :: Parser FieldDefinition fieldDefinition = FieldDefinition <$> name <*> optempty argumentsDefinition <* tok ":" <*> type_ argumentsDefinition :: Parser ArgumentsDefinition argumentsDefinition = parens $ many1 inputValueDefinition interfaceTypeDefinition :: Parser InterfaceTypeDefinition interfaceTypeDefinition = InterfaceTypeDefinition <$ tok "interface" <*> name <*> fieldDefinitions unionTypeDefinition :: Parser UnionTypeDefinition unionTypeDefinition = UnionTypeDefinition <$ tok "union" <*> name <* tok "=" <*> unionMembers unionMembers :: Parser [NamedType] unionMembers = namedType `sepBy1` tok "|" scalarTypeDefinition :: Parser ScalarTypeDefinition scalarTypeDefinition = ScalarTypeDefinition <$ tok "scalar" <*> name enumTypeDefinition :: Parser EnumTypeDefinition enumTypeDefinition = EnumTypeDefinition <$ tok "enum" <*> name <*> enumValueDefinitions enumValueDefinitions :: Parser [EnumValueDefinition] enumValueDefinitions = braces $ many1 enumValueDefinition enumValueDefinition :: Parser EnumValueDefinition enumValueDefinition = EnumValueDefinition <$> name inputObjectTypeDefinition :: Parser InputObjectTypeDefinition inputObjectTypeDefinition = InputObjectTypeDefinition <$ tok "input" <*> name <*> inputValueDefinitions inputValueDefinitions :: Parser [InputValueDefinition] inputValueDefinitions = braces $ many1 inputValueDefinition inputValueDefinition :: Parser InputValueDefinition inputValueDefinition = InputValueDefinition <$> name <* tok ":" <*> type_ <*> optional defaultValue typeExtensionDefinition :: Parser TypeExtensionDefinition typeExtensionDefinition = TypeExtensionDefinition <$ tok "extend" <*> objectTypeDefinition -- * Internal tok :: Parser a -> Parser a tok p = p <* whiteSpace parens :: Parser a -> Parser a parens = between "(" ")" braces :: Parser a -> Parser a braces = between "{" "}" quotes :: Parser a -> Parser a quotes = between "\"" "\"" brackets :: Parser a -> Parser a brackets = between "[" "]" between :: Parser Text -> Parser Text -> Parser a -> Parser a between open close p = tok open *> p <* tok close -- `empty` /= `pure mempty` for `Parser`. optempty :: Monoid a => Parser a -> Parser a optempty = option mempty -- ** WhiteSpace -- whiteSpace :: Parser () whiteSpace = peekChar >>= traverse_ (\c -> if isSpace c || c == ',' then anyChar *> whiteSpace else when (c == '#') $ manyTill anyChar endOfLine *> whiteSpace)
timmytofu/graphql-haskell
Data/GraphQL/Parser.hs
bsd-3-clause
9,103
0
21
1,975
2,068
1,077
991
240
2
module PlaybackState ( onChange , elapsedTime ) where import Prelude hiding (mapM_) import Data.Foldable (mapM_) import Control.Monad (when, forever) import Control.Applicative import Control.Monad.State.Strict (liftIO, evalStateT, gets, modify) import Data.Default import Data.Maybe (fromMaybe) import qualified Network.MPD as MPD hiding (withMPD) import Network.MPD (MPD(), Seconds, Song) import qualified Network.MPD.Applicative as MPDA import Timer import Instances () data State = State { timer :: Maybe Timer , currentSong :: Maybe Song } instance Default State where def = State def def elapsedTime :: MPD.Status -> (Seconds, Seconds) elapsedTime s = case MPD.stTime s of Just (c, t) -> (truncate c, t); _ -> (0, 0) -- | Execute given actions on changes. onChange :: IO () -> (Maybe Song -> IO ()) -> (Maybe Song -> MPD.Status -> IO ()) -> MPD () onChange plChanged songChanged statusChanged = evalStateT (updatePlaylist >> updateTimerAndCurrentSong >> idle) def where -- Wait for changes. idle = forever $ do r <- MPD.idle [MPD.PlaylistS, MPD.PlayerS, MPD.OptionsS, MPD.UpdateS, MPD.MixerS] if (MPD.PlaylistS `elem` r) then do -- If the playlist changed, we have to run both, `updatePlaylist` and -- `updateTimerAndCurrentSong`. -- -- `updateTimerAndCurrentSong` is necessary to emit -- EvCurrentSongChanged. This is necessary even if the song did not -- really change, because it's position within the playlist may have -- changed; and we only use a position to mark the current element of -- a ListWidget (say the currently played song here). updatePlaylist updateTimerAndCurrentSong else do -- MPD.PlayerS | MPD.OptionsS | MPD.UpdateS | MPD.MixerS updateTimerAndCurrentSong -- Call `plChanged` action. updatePlaylist = liftIO plChanged -- Query MPD's status and call `statusChanged`, and if current song changed -- `songChanged`. If a song is currently being played, start a timer, that -- repeatedly updates the elapsed time and calls `statusChanged`. updateTimerAndCurrentSong = do -- stop old timer (if any) gets timer >>= mapM_ (liftIO . stopTimer) modify (\st -> st {timer = Nothing}) -- query status and call `statusChanged` (song, status) <- MPDA.runCommand $ (,) <$> MPDA.currentSong <*> MPDA.status liftIO (statusChanged song status) -- call `songChanged` if necessary oldSong <- gets currentSong when (oldSong /= song) $ do modify (\st -> st {currentSong = song}) liftIO (songChanged song) -- start timer, if playing when (MPD.stState status == MPD.Playing) $ do t0 <- liftIO getPOSIXTime let (s0, _) = fromMaybe (0, 0) (MPD.stTime status) t <- liftIO . startTimer t0 s0 $ \elapsed -> do statusChanged song (updateElapsedTime status elapsed) modify (\st -> st {timer = Just t}) -- | Set elapsed time of given status to given seconds. updateElapsedTime :: MPD.Status -> Double -> MPD.Status updateElapsedTime st seconds = st {MPD.stTime = Just (seconds, timeTotal)} where (_, timeTotal) = fromMaybe (0, 0) (MPD.stTime st)
haasn/vimus
src/PlaybackState.hs
mit
3,389
0
19
888
820
447
373
52
2
-- | -- Provides a typeclass for a general concept of a path into -- a treelike structure. We have a root or empty path, paths -- may be concatenated, and a pair of paths may be factored into -- paths relative to their lowest common ancestor in the tree. module Unison.Path where import Control.Applicative -- | Satisfies: -- * `extend root p == p` and `extend p root == p` -- * `extend` is associative, `extend (extend p1 p2) p3 == extend p1 (extend p2 p3)` -- * `lca root p == root` and `lca p root == root` -- * `case factor p p2 of (r,p',p2') -> extend r p' == p && extend r p2' == p2` class Path p where -- | The root or empty path root :: p -- | Concatenate two paths extend :: p -> p -> p -- | Extract the lowest common ancestor and the path from the LCA to each argument factor :: p -> p -> (p,(p,p)) -- | Satisfies `factor (parent p) p == (parent p, (root, tl)` and -- `extend (parent p) tl == p` parent :: p -> p -- | Compute the lowest common ancestor of two paths lca :: Path p => p -> p -> p lca p p2 = fst (factor p p2) -- | `isSubpath p1 p2` is true if `p2 == extend p1 x` for some `x` isSubpath :: (Eq p, Path p) => p -> p -> Bool isSubpath p1 p2 = lca p1 p2 == p1 instance Eq a => Path (Maybe a) where root = Nothing extend = (<|>) parent _ = Nothing factor p1 p2 | p1 == p2 = (p1, (Nothing, Nothing)) factor p1 p2 = (Nothing, (p1,p2)) instance Eq a => Path [a] where root = [] extend = (++) parent p | null p = [] parent p = init p factor p1 p2 = (take shared p1, (drop shared p1, drop shared p2)) where shared = length (takeWhile id $ zipWith (==) p1 p2) instance Path () where root = () parent _ = () extend _ _ = () factor u _ = (u,(u,u))
nightscape/platform
shared/src/Unison/Path.hs
mit
1,728
0
11
432
461
252
209
29
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.Rank1 where import Numeric.Natural import Numeric.Natural.QuickCheck () import Data.Typeable import Data.Name import Data.Prop data Rank1 p a = Forall [a] (p a) deriving (Eq, Ord, Show, Read, Functor) instance Typeable1 p => Typeable1 (Rank1 p) where typeOf1 _ = mkTyConApp (mkTyCon3 "" "Data.Rank1" "Rank1") [typeOf1 (undefined :: p ())] type Rank1PropS = Rank1 Prop Name type Rank1PropI = Rank1 Prop Natural alphaReduce :: (Eq a, Eq (p a), Functor p) => a -> a -> Rank1 p a -> Rank1 p a alphaReduce a b = fmap (\ x -> if x == a then b else x) readRank1PropS :: String -> Rank1PropS readRank1PropS = read readRank1PropI :: String -> Rank1PropI readRank1PropI = read cutDangling :: Eq a => Rank1 Prop a -> Rank1 Prop a cutDangling (Forall xs p) = Forall (filter (`elem` atoms p) xs) p
kmyk/proof-haskell
Data/Rank1.hs
mit
876
0
11
158
344
184
160
21
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} module Text.Render ( Render(..), Indenter, indented, wrapIndented, inNewLine, renderIndented, renderIndentedStartingAt, renderTicks ) where import ClassyPrelude import qualified Prelude as P import Control.Monad.Trans (MonadIO(..)) import Control.Monad.Reader (ReaderT(..), MonadReader(..), (<=<), (>=>), ask, asks, runReaderT) import Control.Monad.Writer (WriterT(..), MonadWriter(..), runWriterT) import Control.Monad.State.Strict (MonadState, StateT, State, get, gets, modify, put, liftM, liftIO, runState, runStateT, execState, execStateT, evalState, evalStateT) import Data.Text (Text) import qualified Data.Text as T import Text.Parsec (ParseError) type Name = Text -- | A class for pretty printing, and in general, for "showing" as a `Text`. class Show a => Render a where -- | Render the object as a `Text`. render :: a -> Text render = T.pack . P.show -- | Many types of objects need to be rendered in parentheses. renderParens :: a -> Text renderParens = render -- | Render in the `IO` monad. Useful for objects containing IORefs. renderIO :: MonadIO m => a -> m Text renderIO = return . render renderI :: a -> Indenter renderI = tell . render instance Render Int instance Render Bool instance Render Integer instance Render Double instance Render Text instance Render ParseError instance (Render a, Render b) => Render (a, b) where render (a, b) = "(" <> render a <> ", " <> render b <> ")" instance Render a => Render [a] where render list = "[" <> T.intercalate ", " (map render list) <> "]" -- | Renders and surrounds in backticks. Useful for printing user input. renderTicks :: Render a => a -> Text renderTicks x = "`" <> render x <> "`" type Indenter = ReaderT Int (WriterT Text (State Int)) () indented :: Indenter -> Indenter indented action = do c <- get put (c+1) action put c inNewLine :: Indenter -> Indenter inNewLine action = do ilevel <- ask current <- get tell $ "\n" <> T.replicate (ilevel * current) " " action wrapIndented :: Render a => Text -> Text -> [a] -> Indenter wrapIndented start finish things = do tell start indented $ mapM_ (inNewLine . renderI) things inNewLine $ tell finish renderIndented :: Render a => Int -> a -> Text renderIndented = renderIndentedStartingAt 0 renderIndentedStartingAt :: Render a => Int -> Int -> a -> Text renderIndentedStartingAt start level e = snd $ evalState (runWriterT (runReaderT (renderI e) level)) start
adnelson/simple-nix
src/Text/Render.hs
mit
2,667
0
12
606
811
441
370
65
1
{-# LANGUAGE OverloadedStrings #-} module Views.Common (pageT, inp, sel) where import Data.Text.Lazy (Text) import Text.Blaze.Html5 hiding (option) import qualified Text.Blaze.Html5 as H import Text.Blaze.Html5.Attributes hiding (name) import qualified Text.Blaze.Html5.Attributes as A inp :: Text -> Text -> Html inp name ph = H.input ! A.type_ "text" ! A.placeholder (toValue ph) ! A.id (toValue name) ! A.name (toValue name) sel :: Text -> [Text] -> Html sel name options = H.select ! A.name (toValue name) ! A.id (toValue name) $ mapM_ optToHtml options where optToHtml option = H.option ! A.value (toValue option) $ toHtml option pageT :: Text -> Html -> Html pageT t cont = docTypeHtml ! lang "en" $ do H.head $ do H.title (toHtml t) meta ! A.name "viewport" ! content "width=device-width, initial-scale=1" -- Latest compiled and minified CSS link ! rel "stylesheet" ! href "/static/css/bootstrap.min.css" -- Optional theme link ! rel "stylesheet" ! href "/static/css/bootstrap-theme.min.css" -- My own CSS file link ! rel "stylesheet" ! href "/static/css/style.css" -- required js files script ! A.type_ "text/javascript" ! src "/static/js/jquery.min.js" $ mempty script ! A.type_ "text/javascript" ! src "/static/js/jquery.color.min.js" $ mempty script ! A.type_ "text/javascript" ! src "/static/js/bootstrap.min.js" $ mempty script ! A.type_ "text/javascript" ! src "/static/js/longtable.js" $ mempty script ! A.type_ "text/javascript" ! src "/static/js/jquery.jeditable.min.js" $ mempty script ! A.type_ "text/javascript" ! src "/static/js/utils.js" $ mempty body $ do H.div ! A.class_ "navbar navbar-inverse navbar-fixed-top" $ H.div ! A.class_ "container" $ do -- header for the navbar H.div ! A.class_ "navbar-header" $ do H.button ! A.type_ "button" ! A.class_ "navbar-toggle" ! dataAttribute "toggle" "collapse" ! dataAttribute "target" ".navbar-collapse" $ do H.span ! A.class_ "sr-only" $ "Toggle navigation" H.span ! A.class_ "icon-bar" $ mempty H.span ! A.class_ "icon-bar" $ mempty H.span ! A.class_ "icon-bar" $ mempty H.a ! A.class_ "navbar-brand" ! A.href "/" $ "sproxy-web" H.div ! A.class_ "collapse navbar-collapse" $ do H.ul ! A.class_ "nav navbar-nav" $ do H.li ! A.id "animat-gr" $ H.a ! A.href "/groups" $ "Groups and users" H.li ! A.id "animat-do" $ H.a ! A.href "/domains" $ "Domains and privileges" H.form ! A.id "searchform" ! A.class_ "navbar-form navbar-right" ! A.method "POST" ! A.action "/search" $ H.input ! A.type_ "text" ! A.name "search_query" ! A.class_ "form-control" ! A.placeholder "Search an email" H.div ! class_ "container content" $ do H.div ! A.class_ "page-header text-center" $ H.h1 $ toHtml t cont
zalora/sproxy-web
src/Views/Common.hs
mit
3,496
0
27
1,227
956
452
504
59
1
{- SkateBackendCode: The C code backend for Skate Part of Skate: a Schema specification languge Copyright (c) 2017, ETH Zurich. All rights reserved. This file is distributed under the terms in the attached LICENSE file. If you do not find this file, copies can be found by writing to: ETH Zurich D-INFK, Universit\"atstr. 6, CH-8092 Zurich. Attn: Systems Group. -} module SkateBackendCode where import Data.Char import Data.List import Data.Char import Text.ParserCombinators.Parsec.Pos import qualified CAbsSyntax as C import SkateParser import SkateSchema import SkateTypes import SkateBackendCommon import qualified SkateTypeTable as TT compile :: String -> String -> SchemaRecord -> String compile infile outfile s = unlines $ C.pp_unit $ (skate_c_body s infile) skate_c_body :: SchemaRecord -> String -> C.Unit skate_c_body sr infile = let Schema n d decls imps sp = (schema sr) in C.UnitList [ (skate_c_preamble n d infile), C.Blank, C.Blank, skate_c_includes n, C.Blank, C.Blank, C.MultiComment [ "====================================================================", "Flags", "====================================================================" ], C.Blank, C.UnitList $ (skate_c_code_defs (flags sr) (types sr)), C.Blank, C.Blank, C.MultiComment [ "====================================================================", "Constants", "====================================================================" ], C.Blank, C.UnitList $ (skate_c_code_defs (constants sr) (types sr)), C.Blank, C.Blank, C.MultiComment [ "====================================================================", "Enumerations", "====================================================================" ], C.Blank, C.UnitList $ (skate_c_code_defs (enumerations sr) (types sr)), C.Blank, C.Blank, C.MultiComment [ "====================================================================", "Facts", "====================================================================" ], C.Blank, C.UnitList $ (skate_c_code_defs (facts sr) (types sr)), C.Blank, C.Blank] skate_c_includes :: String -> C.Unit skate_c_includes sr = C.UnitList [ C.Include C.Standard "barrelfish/barrelfish.h", C.Include C.Standard "skb/skb.h", C.Include C.Standard (skate_c_includepath sr) ] {------------------------------------------------------------------------------ Function Add ------------------------------------------------------------------------------} skate_c_vardecl :: C.TypeSpec -> String -> Maybe C.Expr -> C.Stmt skate_c_vardecl t s e = C.VarDecl C.NoScope C.NonConst t s e skate_c_vardecl_err :: C.Stmt skate_c_vardecl_err = skate_c_vardecl (C.TypeName "errval_t") "err" Nothing skate_c_errvar :: C.Expr skate_c_errvar = C.Variable "err" skate_c_code_add :: Declaration -> [TT.TTEntry] -> [C.Unit] skate_c_code_add def@(Fact i d attrib sp) ttbl = skate_c_fn_defs_facts i attrib [ skate_c_vardecl_err, C.SBlank, C.SComment "TODO: Add some checks.", C.SBlank, C.Ex $ C.Assignment skate_c_errvar (C.Call "skb_add_fact" [ C.DefineExpr fmt, C.Call (make_format_name_extract_all cname) [C.Variable "fact"] ] ), C.If (C.Call "err_is_fail" [skate_c_errvar]) [ C.SComment "TODO: Add some good error message", C.Return skate_c_errvar] [], C.SBlank, C.Return skate_c_errvar ] where cname = identifier_to_cname i fmt = make_format_name_fields_pr cname {----------------------------------------------------------------------------- - Facts ------------------------------------------------------------------------------} skate_c_code_fact :: Declaration -> [TT.TTEntry] -> [C.Unit] skate_c_code_fact def@(Fact i d attrib sp) ttbl = [ (skate_c_type_comment "fact" d i sp), C.Blank] ++ (skate_c_code_add def ttbl) skate_c_code_one_def :: Declaration -> [TT.TTEntry] -> [ C.Unit ] skate_c_code_one_def de@(Fact i d a sp) tt = skate_c_code_fact de tt skate_c_code_one_def de@(Flags i d w f sp) _ = [] --skate_c_header_flags i d w f sp skate_c_code_one_def de@(Constants i d t f sp) _ = [] --skate_c_header_const i d t f sp skate_c_code_one_def de@(Enumeration i d f sp) _ = [] --skate_c_header_enum i d f sp skate_c_code_one_def _ _ = [] skate_c_code_defs :: [Declaration] -> [TT.TTEntry] -> [ C.Unit ] skate_c_code_defs decls ttbl = [C.UnitList $ skate_c_code_one_def d ttbl | d <- decls]
kishoredbn/barrelfish
tools/skate/SkateBackendCode.hs
mit
4,806
0
15
1,041
1,106
594
512
92
1
{-# OPTIONS_GHC -F -pgmF inlitpp #-} # Test document Hello from my test document! ```haskell hide top import Data.Time ``` ```haskell do now <- getCurrentTime ``` ```haskell do let later :: UTCTime later = addUTCTime 100 now ``` ```haskell top f :: Int -> Int f x = x - 7 ``` ```haskell eval f (2+2) ``` ```haskell eval [100000::Int .. ] ``` and lets have another question ```haskell eval (now, later) ``` Goodbye!
diffusionkinetics/open
inliterate/TestInliteratePreProc.hs
mit
442
8
6
101
102
81
21
-1
-1
{- | Module : Environment Description : REPL environment Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt) License : BSD3 Maintainer : Boya Peng <u3502350@connect.hku.hk> Stability : stable Portability : portable -} module Environment where import Data.List.Split import Parser import Src import Text.PrettyPrint.ANSI.Leijen type Env = [(String, Exp)] type Exp = (String, Src.ParsedExpr) empty :: Env empty = [] insert :: (String, String) -> Env -> Env insert (var, exp) env = case Parser.parseExpr exp of ParseOk expr -> (var, (exp, expr)) : env ParseError error -> env createExp :: [String] -> String createExp [] = "" createExp (x:xs) = x ++ " " ++ createExp xs -- y is "=" -- Sample input: ["x", "=", "y" , "+", "2"] -- Sample output: splitOn ["="] xs ~> [["x"], ["y", "+", "2"]] -- Sample output: ("x", "y+2") createPair :: [String] -> (String, String) createPair xs = (var, exp) where var = ((splitOn ["="] xs) !! 0) !! 0 exp = createExp ((splitOn ["="] xs) !! 1) reverseEnv :: Env -> Env reverseEnv = reverse createBindEnv :: Env -> String createBindEnv [] = "" createBindEnv ((var,(str,expr)) : xs) = "let " ++ var ++ " = " ++ str ++ " in " ++ createBindEnv xs searchEnv :: String -> Env -> Bool searchEnv var env = case lookup var env of Nothing -> False Just exp -> True showPrettyEnv :: Env -> String showPrettyEnv [] = "" showPrettyEnv ((var, (_, expr)) : xs) = "(" ++ show var ++ ", " ++ show (pretty expr) ++ "); " ++ showPrettyEnv xs
zhiyuanshi/fcore
repl/Environment.hs
bsd-2-clause
1,721
0
12
507
493
273
220
36
2
module Graphics.VR.Pal (module Exports) where import Graphics.VR.Pal.Hands as Exports import Graphics.VR.Pal.Movement as Exports import Graphics.VR.Pal.Types as Exports import Graphics.VR.Pal.Window as Exports import Graphics.VR.Pal.SDLUtils as Exports
lukexi/game-pal
src/Graphics/VR/Pal.hs
bsd-3-clause
262
0
4
34
58
44
14
6
0
-- | Constants describing the DWARF format. Most of this simply -- mirrors /usr/include/dwarf.h. module Dwarf.Constants where import FastString import Platform import Outputable import Reg import X86.Regs import Data.Word -- | Language ID used for Haskell. dW_LANG_Haskell :: Word dW_LANG_Haskell = 0x18 -- Thanks to Nathan Howell for getting us our very own language ID! -- * Dwarf tags dW_TAG_compile_unit, dW_TAG_subroutine_type, dW_TAG_file_type, dW_TAG_subprogram, dW_TAG_lexical_block, dW_TAG_base_type, dW_TAG_structure_type, dW_TAG_pointer_type, dW_TAG_array_type, dW_TAG_subrange_type, dW_TAG_typedef, dW_TAG_variable, dW_TAG_arg_variable, dW_TAG_auto_variable :: Word dW_TAG_array_type = 1 dW_TAG_lexical_block = 11 dW_TAG_pointer_type = 15 dW_TAG_compile_unit = 17 dW_TAG_structure_type = 19 dW_TAG_typedef = 22 dW_TAG_subroutine_type = 32 dW_TAG_subrange_type = 33 dW_TAG_base_type = 36 dW_TAG_file_type = 41 dW_TAG_subprogram = 46 dW_TAG_variable = 52 dW_TAG_auto_variable = 256 dW_TAG_arg_variable = 257 -- * Dwarf attributes dW_AT_name, dW_AT_stmt_list, dW_AT_low_pc, dW_AT_high_pc, dW_AT_language, dW_AT_comp_dir, dW_AT_producer, dW_AT_external, dW_AT_frame_base, dW_AT_use_UTF8, dW_AT_MIPS_linkage_name :: Word dW_AT_name = 0x03 dW_AT_stmt_list = 0x10 dW_AT_low_pc = 0x11 dW_AT_high_pc = 0x12 dW_AT_language = 0x13 dW_AT_comp_dir = 0x1b dW_AT_producer = 0x25 dW_AT_external = 0x3f dW_AT_frame_base = 0x40 dW_AT_use_UTF8 = 0x53 dW_AT_MIPS_linkage_name = 0x2007 -- * Abbrev declaration dW_CHILDREN_no, dW_CHILDREN_yes :: Word8 dW_CHILDREN_no = 0 dW_CHILDREN_yes = 1 dW_FORM_addr, dW_FORM_data4, dW_FORM_string, dW_FORM_flag, dW_FORM_block1, dW_FORM_ref4, dW_FORM_flag_present :: Word dW_FORM_addr = 0x01 dW_FORM_data4 = 0x06 dW_FORM_string = 0x08 dW_FORM_flag = 0x0c dW_FORM_block1 = 0x0a dW_FORM_ref4 = 0x13 dW_FORM_flag_present = 0x19 -- * Dwarf native types dW_ATE_address, dW_ATE_boolean, dW_ATE_float, dW_ATE_signed, dW_ATE_signed_char, dW_ATE_unsigned, dW_ATE_unsigned_char :: Word dW_ATE_address = 1 dW_ATE_boolean = 2 dW_ATE_float = 4 dW_ATE_signed = 5 dW_ATE_signed_char = 6 dW_ATE_unsigned = 7 dW_ATE_unsigned_char = 8 -- * Call frame information dW_CFA_set_loc, dW_CFA_undefined, dW_CFA_same_value, dW_CFA_def_cfa, dW_CFA_def_cfa_offset, dW_CFA_def_cfa_expression, dW_CFA_expression, dW_CFA_offset_extended_sf, dW_CFA_def_cfa_offset_sf, dW_CFA_def_cfa_sf, dW_CFA_val_offset, dW_CFA_val_expression, dW_CFA_offset :: Word8 dW_CFA_set_loc = 0x01 dW_CFA_undefined = 0x07 dW_CFA_same_value = 0x08 dW_CFA_def_cfa = 0x0c dW_CFA_def_cfa_offset = 0x0e dW_CFA_def_cfa_expression = 0x0f dW_CFA_expression = 0x10 dW_CFA_offset_extended_sf = 0x11 dW_CFA_def_cfa_sf = 0x12 dW_CFA_def_cfa_offset_sf = 0x13 dW_CFA_val_offset = 0x14 dW_CFA_val_expression = 0x16 dW_CFA_offset = 0x80 -- * Operations dW_OP_deref, dW_OP_consts, dW_OP_minus, dW_OP_mul, dW_OP_plus, dW_OP_lit0, dW_OP_breg0, dW_OP_call_frame_cfa :: Word8 dW_OP_deref = 0x06 dW_OP_consts = 0x11 dW_OP_minus = 0x1c dW_OP_mul = 0x1e dW_OP_plus = 0x22 dW_OP_lit0 = 0x30 dW_OP_breg0 = 0x70 dW_OP_call_frame_cfa = 0x9c -- * Dwarf section declarations dwarfInfoSection, dwarfAbbrevSection, dwarfLineSection, dwarfFrameSection, dwarfGhcSection, dwarfARangesSection :: SDoc dwarfInfoSection = dwarfSection "info" dwarfAbbrevSection = dwarfSection "abbrev" dwarfLineSection = dwarfSection "line" dwarfFrameSection = dwarfSection "frame" dwarfGhcSection = dwarfSection "ghc" dwarfARangesSection = dwarfSection "aranges" dwarfSection :: String -> SDoc dwarfSection name = sdocWithPlatform $ \plat -> ftext $ mkFastString $ case platformOS plat of os | osElfTarget os -> "\t.section .debug_" ++ name ++ ",\"\",@progbits" | osMachOTarget os -> "\t.section __DWARF,__debug_" ++ name ++ ",regular,debug" | otherwise -> "\t.section .debug_" ++ name ++ ",\"dr\"" -- * Dwarf section labels dwarfInfoLabel, dwarfAbbrevLabel, dwarfLineLabel, dwarfFrameLabel :: LitString dwarfInfoLabel = sLit ".Lsection_info" dwarfAbbrevLabel = sLit ".Lsection_abbrev" dwarfLineLabel = sLit ".Lsection_line" dwarfFrameLabel = sLit ".Lsection_frame" -- | Mapping of registers to DWARF register numbers dwarfRegNo :: Platform -> Reg -> Word8 dwarfRegNo p r = case platformArch p of ArchX86 | r == eax -> 0 | r == ecx -> 1 -- yes, no typo | r == edx -> 2 | r == ebx -> 3 | r == esp -> 4 | r == ebp -> 5 | r == esi -> 6 | r == edi -> 7 ArchX86_64 | r == rax -> 0 | r == rdx -> 1 -- this neither. The order GCC allocates registers in? | r == rcx -> 2 | r == rbx -> 3 | r == rsi -> 4 | r == rdi -> 5 | r == rbp -> 6 | r == rsp -> 7 | r == r8 -> 8 | r == r9 -> 9 | r == r10 -> 10 | r == r11 -> 11 | r == r12 -> 12 | r == r13 -> 13 | r == r14 -> 14 | r == r15 -> 15 | r == xmm0 -> 17 | r == xmm1 -> 18 | r == xmm2 -> 19 | r == xmm3 -> 20 | r == xmm4 -> 21 | r == xmm5 -> 22 | r == xmm6 -> 23 | r == xmm7 -> 24 | r == xmm8 -> 25 | r == xmm9 -> 26 | r == xmm10 -> 27 | r == xmm11 -> 28 | r == xmm12 -> 29 | r == xmm13 -> 30 | r == xmm14 -> 31 | r == xmm15 -> 32 _other -> error "dwarfRegNo: Unsupported platform or unknown register!" -- | Virtual register number to use for return address. dwarfReturnRegNo :: Platform -> Word8 dwarfReturnRegNo p -- We "overwrite" IP with our pseudo register - that makes sense, as -- when using this mechanism gdb already knows the IP anyway. Clang -- does this too, so it must be safe. = case platformArch p of ArchX86 -> 8 -- eip ArchX86_64 -> 16 -- rip _other -> error "dwarfReturnRegNo: Unsupported platform!"
AlexanderPankiv/ghc
compiler/nativeGen/Dwarf/Constants.hs
bsd-3-clause
6,141
0
14
1,484
1,331
755
576
165
3
{-# LANGUAGE BangPatterns #-} module Main where import Control.DeepSeq import Control.Exception (evaluate) import Control.Monad.Trans (liftIO) import Criterion.Config import Criterion.Main import Data.List (foldl') import qualified Data.Map as M import Data.Maybe (fromMaybe) import Prelude hiding (lookup) main = do let m = M.fromAscList elems :: M.Map Int Int m_even = M.fromAscList elems_even :: M.Map Int Int m_odd = M.fromAscList elems_odd :: M.Map Int Int defaultMainWith defaultConfig (liftIO . evaluate $ rnf [m, m_even, m_odd]) [ bench "lookup absent" $ whnf (lookup evens) m_odd , bench "lookup present" $ whnf (lookup evens) m_even , bench "insert absent" $ whnf (ins elems_even) m_odd , bench "insert present" $ whnf (ins elems_even) m_even , bench "insertWith absent" $ whnf (insWith elems_even) m_odd , bench "insertWith present" $ whnf (insWith elems_even) m_even , bench "insertWith' absent" $ whnf (insWith' elems_even) m_odd , bench "insertWith' present" $ whnf (insWith' elems_even) m_even , bench "insertWithKey absent" $ whnf (insWithKey elems_even) m_odd , bench "insertWithKey present" $ whnf (insWithKey elems_even) m_even , bench "insertWithKey' absent" $ whnf (insWithKey' elems_even) m_odd , bench "insertWithKey' present" $ whnf (insWithKey' elems_even) m_even , bench "insertLookupWithKey absent" $ whnf (insLookupWithKey elems_even) m_odd , bench "insertLookupWithKey present" $ whnf (insLookupWithKey elems_even) m_even , bench "insertLookupWithKey' absent" $ whnf (insLookupWithKey' elems_even) m_odd , bench "insertLookupWithKey' present" $ whnf (insLookupWithKey' elems_even) m_even , bench "map" $ whnf (M.map (+ 1)) m , bench "mapWithKey" $ whnf (M.mapWithKey (+)) m , bench "foldlWithKey" $ whnf (ins elems) m -- , bench "foldlWithKey'" $ whnf (M.foldlWithKey' sum 0) m , bench "foldrWithKey" $ whnf (M.foldrWithKey consPair []) m , bench "delete absent" $ whnf (del evens) m_odd , bench "delete present" $ whnf (del evens) m , bench "update absent" $ whnf (upd Just evens) m_odd , bench "update present" $ whnf (upd Just evens) m_even , bench "update delete" $ whnf (upd (const Nothing) evens) m , bench "updateLookupWithKey absent" $ whnf (upd' Just evens) m_odd , bench "updateLookupWithKey present" $ whnf (upd' Just evens) m_even , bench "updateLookupWithKey delete" $ whnf (upd' (const Nothing) evens) m , bench "alter absent" $ whnf (alt id evens) m_odd , bench "alter insert" $ whnf (alt (const (Just 1)) evens) m_odd , bench "alter update" $ whnf (alt id evens) m_even , bench "alter delete" $ whnf (alt (const Nothing) evens) m , bench "mapMaybe" $ whnf (M.mapMaybe maybeDel) m , bench "mapMaybeWithKey" $ whnf (M.mapMaybeWithKey (const maybeDel)) m , bench "lookupIndex" $ whnf (lookupIndex keys) m , bench "union" $ whnf (M.union m_even) m_odd , bench "difference" $ whnf (M.difference m) m_even , bench "intersection" $ whnf (M.intersection m) m_even , bench "split" $ whnf (M.split (bound `div` 2)) m , bench "fromList" $ whnf M.fromList elems , bench "fromList-desc" $ whnf M.fromList (reverse elems) , bench "fromAscList" $ whnf M.fromAscList elems , bench "fromDistinctAscList" $ whnf M.fromDistinctAscList elems ] where bound = 2^12 elems = zip keys values elems_even = zip evens evens elems_odd = zip odds odds keys = [1..bound] evens = [2,4..bound] odds = [1,3..bound] values = [1..bound] sum k v1 v2 = k + v1 + v2 consPair k v xs = (k, v) : xs add3 :: Int -> Int -> Int -> Int add3 x y z = x + y + z {-# INLINE add3 #-} lookup :: [Int] -> M.Map Int Int -> Int lookup xs m = foldl' (\n k -> fromMaybe n (M.lookup k m)) 0 xs lookupIndex :: [Int] -> M.Map Int Int -> Int lookupIndex xs m = foldl' (\n k -> fromMaybe n (M.lookupIndex k m)) 0 xs ins :: [(Int, Int)] -> M.Map Int Int -> M.Map Int Int ins xs m = foldl' (\m (k, v) -> M.insert k v m) m xs insWith :: [(Int, Int)] -> M.Map Int Int -> M.Map Int Int insWith xs m = foldl' (\m (k, v) -> M.insertWith (+) k v m) m xs insWithKey :: [(Int, Int)] -> M.Map Int Int -> M.Map Int Int insWithKey xs m = foldl' (\m (k, v) -> M.insertWithKey add3 k v m) m xs insWith' :: [(Int, Int)] -> M.Map Int Int -> M.Map Int Int insWith' xs m = foldl' (\m (k, v) -> M.insertWith' (+) k v m) m xs insWithKey' :: [(Int, Int)] -> M.Map Int Int -> M.Map Int Int insWithKey' xs m = foldl' (\m (k, v) -> M.insertWithKey' add3 k v m) m xs data PairS a b = PS !a !b insLookupWithKey :: [(Int, Int)] -> M.Map Int Int -> (Int, M.Map Int Int) insLookupWithKey xs m = let !(PS a b) = foldl' f (PS 0 m) xs in (a, b) where f (PS n m) (k, v) = let !(n', m') = M.insertLookupWithKey add3 k v m in PS (fromMaybe 0 n' + n) m' insLookupWithKey' :: [(Int, Int)] -> M.Map Int Int -> (Int, M.Map Int Int) insLookupWithKey' xs m = let !(PS a b) = foldl' f (PS 0 m) xs in (a, b) where f (PS n m) (k, v) = let !(n', m') = M.insertLookupWithKey' add3 k v m in PS (fromMaybe 0 n' + n) m' del :: [Int] -> M.Map Int Int -> M.Map Int Int del xs m = foldl' (\m k -> M.delete k m) m xs upd :: (Int -> Maybe Int) -> [Int] -> M.Map Int Int -> M.Map Int Int upd f xs m = foldl' (\m k -> M.update f k m) m xs upd' :: (Int -> Maybe Int) -> [Int] -> M.Map Int Int -> M.Map Int Int upd' f xs m = foldl' (\m k -> snd $ M.updateLookupWithKey (\_ a -> f a) k m) m xs alt :: (Maybe Int -> Maybe Int) -> [Int] -> M.Map Int Int -> M.Map Int Int alt f xs m = foldl' (\m k -> M.alter f k m) m xs maybeDel :: Int -> Maybe Int maybeDel n | n `mod` 3 == 0 = Nothing | otherwise = Just n
DavidAlphaFox/ghc
libraries/containers/benchmarks/Map.hs
bsd-3-clause
5,969
0
16
1,537
2,593
1,311
1,282
112
1
-- | -- Copyright : (c) 2010, 2011 Benedikt Schmidt -- License : GPL v3 (see LICENSE) -- -- Maintainer : Benedikt Schmidt <beschmi@gmail.com> -- Portability : GHC only -- module Theory.UnitTests where import Term.Builtin.Convenience import Theory.Tools.IntruderRules {- -- EquationStore ---------------------------------------------------------------------- testsEquationStore :: Test testsEquationStore = TestLabel "Tests for EquationStore" $ TestList [ -- testEqual "filterMostGeneral" (filterMostGeneral [s1,s2,s3]) [s1,s3] -- testTrue "Simplification" test_eqstore_0 testEqual "" emptyEqStore (evalFresh (execStateT (whileTrue $ simp1) (EqStore emptySubstVFree (Conj [Disj [substFromList VFresh [(lx1, x3)]]]))) (freshFromUsed [])) , uncurry (testEqual "Simplification") test_eqstore_1 , uncurry (testEqual "Simplification") test_eqstore_2 , uncurry (testEqual "Simplification") test_eqstore_3 ] where -- s1 = substFromList VFresh [(lv1, p1 # v4), (lv2, v3)] -- s2 = substFromList VFresh [(lv1, p2 # p1 # p6), (lv2, p3)] -- subsumed by s1 mod AC -- s3 = substFromList VFresh [(lv1, v5 # v4 # p6), (lv2, p4)] -- not subsumed -- Equation Store ---------------------------------------------------------------------- {- test_eqstore_0 :: Bool test_eqstore_0 = all snd $ map (\(s0,s') -> let s = restrict (dom s') (s0 `composeVFresh` csubst) in ((s,s'),s1 `eqSubstSubs` s')) $ zip substs [s1,s2,s3] where s1 = substFromList VFresh [(lx1, pair(pair(x1,x2),f1)), (lx2, x6), (lx3, x6), (lx5, x6) , (lx7, expo(pair(x1,x2),f1))] s2 = substFromList VFresh [(lx1, pair(pair(f1,p1),f2)), (lx2, x5), (lx3, x5), (lx4, x5) , (lx7, expo(pair(x1,x2),f1))] s3 = substFromList VFresh [(lx1, pair(pair(p1,f1),f2)), (lx2, x7), (lx3, x7), (lx6, x7) , (lx7, expo(pair(x1,x2),f1))] EqStore csubst (Conj [Disj substs]) = evalFresh (simp (EqStore emptySubstFree (Conj [Disj [s1,s2,s3]]))) (freshFromUsed (lvars [s1,s2,s3])) -} test_eqstore_1 :: (EqStore, EqStore) test_eqstore_1 = ( EqStore csubst (Conj [Disj [s1',s2',s3']]) , evalFresh (execStateT (whileTrue $ simp1) (EqStore emptySubstVFree (Conj [Disj [s1,s2,s3]]))) (freshFromUsed (lvars [s1,s2,s3]))) -- abstract the common pair x1, identify x2 and x3 where s1 = substFromList VFresh [(lx1, pair(pair(x1,x2),f1)), (lx2, x6), (lx3, x6), (lx5, x6) ] s2 = substFromList VFresh [(lx1, pair(p1,f2)), (lx2, x5), (lx3, x5), (lx4, x5) ] s3 = substFromList VFresh [(lx1, pair(p1,f2)), (lx2, x7), (lx3, x7), (lx6, x7) ] s1' = substFromList VFresh [(lx8, pair(x16,x17)), (lx5,x15), (lx9, f1), (lx11, x15) ] s2' = substFromList VFresh [(lx8, p1), (lx9, f2), (lx4, x13), (lx11, x13) ] s3' = substFromList VFresh [(lx8, p1), (lx9, f2), (lx6, x13), (lx11, x13) ] csubst = substFromList VFree [(lx1, pair(x8, x9)), (lx2, varTerm $ LVar "x" 11), (lx3, varTerm $ LVar "x" 11) ] [x13,_x14,x15,x16,x17] = [ varTerm $ LVar "x" i | i <- [13..17]] lx11 = LVar "x" 11 test_eqstore_2 :: ([LSubst VFree], [LSubst VFree]) test_eqstore_2 = ( [substFromList VFree [(lx1, pair(x2,x3))], substFromList VFree [(lx2,f1)]] , evalFresh (simpAbstract (Disj [s1,s2])) (freshFromUsed [lx1])) where s1 = substFromList VFresh [(lx1, pair(pair(x1,x2),f1)), (lx2, f1), (lx3,x3)] s2 = substFromList VFresh [(lx1, pair(p1,f2)), (lx2, f1), (lx3, x3)] test_eqstore_3 :: ([LSubst VFree], [LSubst VFree]) test_eqstore_3 = ([substFromList VFree [(lx2,x8), (lx3,x8)]] , evalFresh (simpIdentify (Disj [s1,s2,s3])) (freshFromUsed (lvars [s1,s2,s3]))) where s1 = substFromList VFresh [(lx1, pair(pair(x1,x2),f1)), (lx2, x6), (lx3, x6), (lx5, x6) ] s2 = substFromList VFresh [(lx1, pair(p1,f2)), (lx2, x5), (lx3, x5), (lx4, x5) ] s3 = substFromList VFresh [(lx1, pair(p1,f2)), (lx2, x7), (lx3, x7), (lx6, x7) ] -- Rule Variants ---------------------------------------------------------------------- testProtoRule :: ProtoRule testProtoRule = Rule (NProtoRuleInfo (ProtoRule "Proto1") []) [ Fact (ProtoFact "Foo") [hash( expo (p1, (fr x1) # y1) ) , pubTerm "u"], Fact (ProtoFact "Bar") [varTerm (LVar "z" 2), freshTerm "freshname"], Fact FreshFact [x1], Fact FreshFact [y1]] [] {- iso_I_3: [ iso_I_2( I, R, ni, hkr ) ] --> [ iso_I_3( I, R, ni, hkr ), SeKeyI( hkr^fr(ni), <pb(I), pb(R), 'g'^fr(ni), hkr> ), Send( <pb(I), encA{<hkr, 'g'^fr(ni), pb(R)>}sk(pb(I))> ) ] -} testProtoRule2 :: ProtoRule testProtoRule2 = Rule (NProtoRuleInfo (ProtoRule "Proto1") []) [ Fact (ProtoFact "SeKeyI") [ x3 , expo(vhkr, hash(x1) ) ], Fact (ProtoFact "iso_I_2") [vhkr]] [] where vhkr = varTerm $ LVar "hkr" 0 test_rulevariants_1 :: IO () test_rulevariants_1 = do putStrLn $ render $ prettyProtoRule $ testProtoRule2 putStrLn $ render $ prettyProofRule $ variantsProtoRule testProtoRule2 {- -- | Test for simpCommonEquations, first and third equation should be removed from both. -- TODO: remove norm after deciding on how to handle normaliztion wrt. AC testDisj_Common_1 :: Disj LSubst testDisj_Common_1 = Disj $ map normSubst [ substFromList [(lv1, p1), (lv2, p2), (lv3, p4 # p5)] , substFromList [(lv1, p1), (lv2, p3), (lv3, p5 # p4)] ] test_factorSubstDisjunction_1 :: Maybe (LSubst, Disj LSubst) test_factorSubstDisjunction_1 = factorSubstDisjunction testDisj_Common_1 -- | Test for simpCommonEquations, first and third equation should be removed from both. -- TODO: remove norm after deciding on how to handle normaliztion wrt. AC testRemoveRenamings_Common_1 :: Disj LSubst testRemoveRenamings_Common_1 = Disj $ map substFromList [ [(lv1, v4), (lv2, v5), (lv3, p4 # p5)] , [(lv1, v4), (lv2, v5), (lv3, p6 # p4)] ] test_RemoveRenamings_1 :: Maybe (LSubst, Disj LSubst) test_RemoveRenamings_1 = factorSubstDisjunction testRemoveRenamings_Common_1 -- | There is no common renaming, so nothing should be removed --test_RemoveRenamings_2 :: Bool test_RemoveRenamings_2 = simpRemoveCommonRenamings disj == Nothing where disj = Disj $ map substFromList [ [(lv1, v4), (lv2, v4), (lv3, v4)], [(lv1, v4), (lv2, v4), (lv3, v5)], [(lv1, v4), (lv2, v4), (lv3, p1)] ] -- | Test for variable identification, v1 and v2 should be -- identified. testDisj_Identify_1 :: Maybe (LSubst, Disj LSubst) testDisj_Identify_1 = factorSubstDisjunction $ substDisjIdentify testDisj_Identify_2 :: Maybe (LSubst, Disj LSubst) testDisj_Identify_2 = simpIdentifyVars $ substDisjIdentify substDisjIdentify :: Disj (Subst Name LVar) substDisjIdentify = Disj $ map substFromList [ [(lv1, v4), (lv2, v4), (lv3, v4)], [(lv1, v4), (lv2, v4), (lv3, v5)], [(lv1, v4), (lv2, v4), (lv3, p1)] ] -- | Test for abstraction, factor out assignment for "y" testDisj_AbstractOuterMost :: Disj LSubst testDisj_AbstractOuterMost = Disj $ map substFromList [ [(lv1, p1 # p2), (lv2, p1 # p2)], [(lv1, p3 # p4), (lv2, p3 # p4)], [(lv1, expo (p1,p5)), (lv2, p5 # (p6 # p7))]] -} -} -- Tests/Experiments ---------------------------------------------------------------------- {- m2 m1 m2 ---------- hash ---------- pair h(m2) <m1,m2> ------------------------ encS encS(<m1,m2>,m2) -} test_recipe_2 :: Bool test_recipe_2 = (encTerm (hashTerm y1) (pairTerm y0 y1)) == reci where encTerm k m = Op2 EncS k m pairTerm a b = Op2 Pair a b hashTerm a = Op1 Hash a m1 = varTerm (LVar "m1" LSortMsg 0) m2 = varTerm (LVar "m2" LSortMsg 0) hm2 = hashTerm m2 pm1m2 = pairTerm m1 m2 hRule = Rule (IntrRuleACStandard (hashTerm y0) Constr) [msgFact m2] [msgFact hm2] pRule = Rule (IntrRuleACStandard (pairTerm y0 y1) Constr) [msgFact m1, msgFact m2] [msgFact pm1m2] eRule = Rule (IntrRuleACStandard (encTerm y0 y1) Constr) [msgFact hm2, msgFact pm1m2] [msgFact (encTerm hm2 pm1m2)] reci = recipe eRule [(pRule, 1, eRule), (hRule, 0, eRule)] {- <m1,m2> <m1,m2> -------------- hash ---------- fst h(<m1,m2>) m1 ------------------------------ encS encS(<m1,m2>,m1) <m1,m2> message premise for both hash and fst. But hash premise must come from Pair and fst premises cannot come from Pair => we cannot identify the two by using the same variable. -} test_recipe_3 :: Bool test_recipe_3 = encTerm (hashTerm y1) (fstTerm y0) == reci where m1 = varTerm (LVar "m1" LSortMsg 0) m2 = varTerm (LVar "m2" LSortMsg 0) encTerm k m = Op2 EncS k m pairTerm a b = Op2 Pair a b hashTerm a = Op1 Hash a fstTerm a = Op1 Fst a h = hashTerm pm1m2 pm1m2 = pairTerm m1 m2 hRule = Rule (IntrRuleACStandard (hashTerm y0) Constr) [msgFact pm1m2] [msgFact h] fstRule = Rule (IntrRuleACStandard (fstTerm y0) Constr) [msgFact pm1m2] [msgFact m1] eRule = Rule (IntrRuleACStandard (encTerm y0 y1) Constr) [msgFact h, msgFact m1] [msgFact (encTerm h m1)] reci = recipe eRule [(fstRule, 1, eRule), (hRule, 0, eRule)]
rsasse/tamarin-prover
lib/theory/src/Theory/UnitTests.hs
gpl-3.0
9,454
0
11
2,187
652
341
311
30
1
module LiftToToplevel.WhereIn1 where --A definition can be lifted from a where or let to the top level binding group. --Lifting a definition widens the scope of the definition. --In this example, lift 'sq' in 'sumSquares' --This example aims to test add parameters to 'sq'. sumSquares x y = sq x + sq y where sq 0 = 0 sq z = z^pow pow=2 anotherFun 0 y = sq y where sq x = x^2
kmate/HaRe
test/testdata/LiftToToplevel/WhereIn1.hs
bsd-3-clause
450
0
7
148
84
44
40
7
2
{-# LANGUAGE TypeFamilies, LiberalTypeSynonyms #-} -- ^ crucial for exercising the code paths to be -- tested here module ShouldCompile where import Data.Kind (Type) type family Element c :: Type f :: x -> Element x f x = undefined
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/Simple19.hs
bsd-3-clause
292
0
6
100
46
28
18
-1
-1
{-# LANGUAGE CPP #-} -- | Computing fingerprints of values serializeable with GHC's "Binary" module. module BinFingerprint ( -- * Computing fingerprints fingerprintBinMem , computeFingerprint , putNameLiterally ) where #include "HsVersions.h" import GhcPrelude import Fingerprint import Binary import Name import Panic import Util fingerprintBinMem :: BinHandle -> IO Fingerprint fingerprintBinMem bh = withBinBuffer bh f where f bs = -- we need to take care that we force the result here -- lest a reference to the ByteString may leak out of -- withBinBuffer. let fp = fingerprintByteString bs in fp `seq` return fp computeFingerprint :: (Binary a) => (BinHandle -> Name -> IO ()) -> a -> IO Fingerprint computeFingerprint put_nonbinding_name a = do bh <- fmap set_user_data $ openBinMem (3*1024) -- just less than a block put_ bh a fp <- fingerprintBinMem bh return fp where set_user_data bh = setUserData bh $ newWriteState put_nonbinding_name putNameLiterally putFS -- | Used when we want to fingerprint a structure without depending on the -- fingerprints of external Names that it refers to. putNameLiterally :: BinHandle -> Name -> IO () putNameLiterally bh name = ASSERT( isExternalName name ) do put_ bh $! nameModule name put_ bh $! nameOccName name
ezyang/ghc
compiler/iface/BinFingerprint.hs
bsd-3-clause
1,418
0
11
356
289
146
143
-1
-1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE PolyKinds #-} module Tc269 where import GHC.Types {- -- We'd like this to kind check, but it doesn't today, -- see Note [Missed opportunity to retain higher-rank kinds] -- TSyn is in an SCC of its own, so we can read off the -- kind directly. data T (p :: forall k. k -> Type) = T type TSyn = T -} -- S and SSyn are in an SCC, so we do kind inference for -- everything. Need an explicit type signature. data K (a :: k) = K data S (p :: forall k. k -> Type) = S (SSyn K) type SSyn = (S :: (forall k. k -> Type) -> Type)
sdiehl/ghc
testsuite/tests/typecheck/should_compile/tc269.hs
bsd-3-clause
565
1
10
126
89
55
34
-1
-1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} import Control.Applicative import Control.Monad import Data.List hiding (and,or) import Data.Set (Set) import qualified Data.Set as Set import Data.Word import System.Environment import Text.Printf import Prelude hiding (and,or) import MiniSat import Formula import Aiger import Interpolation ------------------------------------------------------------------------------ main :: IO () main = do args <- getArgs let file = args !! 0 sys = if length args > 1 then read (args !! 1) else McMillan printf "Interpolation system: %s\n" (show sys) parseAiger file >>= \case Left err -> print err Right aag -> do checkAiger aag sys >>= \case Fixpoint -> putStrLn $ "OK" Counterexample k -> putStrLn $ "FAIL @ k=" ++ (show k) ------------------------------------------------------------------------------ data CheckResult = Fixpoint | Counterexample Int deriving (Show) checkAiger :: Aiger -> System -> IO CheckResult checkAiger aag sys = do let (ls0,gs0,o0,_) = unwind aag 0 sat (fromCNF $ [o0] : gs0 ++ ls0) >>= \case True -> return (Counterexample 0) False -> do let (ls1,gs1,o1,n1) = unwind aag 1 q0 = fromCNF $ ls0 t1 = fromCNF $ ls1 ++ gs0 b1 = mkClauseSet gs1 bLits1 = mkLitSet gs1 check aag sys q0 t1 b1 bLits1 [o1] n1 1 check :: Aiger -> System -> Formula -> Formula -> ClauseSet -> LitSet -> Clause -> Var -> Int -> IO CheckResult check aag sys q0 t1 b bLits p n k = do let a = q0 `and` t1 interpolate sys a b bLits p n >>= \case Satisfiable -> return (Counterexample k) Unsatisfiable i -> do let i' = mapFormula (rewind aag) i q0' = i' `or` q0 fix aag sys q0' t1 b bLits p n >>= \case True -> return Fixpoint False -> do let (ls,gs,o,n') = unwind aag (k+1) b' = clauseSetUnionCNF b (gs ++ ls) bLits' = litSetUnionCNF bLits (gs ++ ls) check aag sys q0 t1 b' bLits (o:p) n' (k+1) fix :: Aiger -> System -> Formula -> Formula -> ClauseSet -> LitSet -> Clause -> Var -> IO Bool fix aag sys q t1 b bLits p n = do let a = q `and` t1 interpolate sys a b bLits p n >>= \case Satisfiable -> return False Unsatisfiable i -> do let i' = mapFormula (rewind aag) i let q' = i' `or` q q' `implies` q >>= \case True -> return True False -> fix aag sys q' t1 b bLits p n ------------------------------------------------------------------------------ data InterpolationResult = Satisfiable | Unsatisfiable Formula deriving (Show) interpolate :: System -> Formula -> ClauseSet -> LitSet -> Clause -> Var -> IO InterpolationResult interpolate sys a b bLits p n = do let (a', n1) = toCNF a (n+1) aLits = mkLitSet a' b' = clauseSetInsert p b bLits' = litSetUnionCNF bLits [p] i <- newInterpolation aLits bLits' b' sys ok <- runSolverWithProof (mkProofLogger i) $ do replicateM_ (fromIntegral n1) newVar addUnit (Neg 0) mapM_ addClause a' forClauses_ b' addClause solve isOkay if ok then return Satisfiable else Unsatisfiable <$> extractInterpolant i implies :: Formula -> Formula -> IO Bool implies q' q = not <$> sat (q' `and` Not q) sat :: Formula -> IO Bool sat f = runSolver $ do let n = 1 + Formula.maxVar f -- TODO: eliminate (f', n') = toCNF f n replicateM_ (fromIntegral n') newVar addUnit (Neg 0) mapM_ addClause f' solve isOkay
mcschroeder/smc
Main.hs
mit
3,911
0
24
1,286
1,341
670
671
106
4
{-# Language RecordWildCards #-} -- | Paths whose values are monitroed. module Galua.Debugger.WatchList where import           Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Galua.Debugger.ValuePath data WatchList = WatchList { wlNextId :: !Int , wlItems :: !(IntMap ValuePath) } watchListEmpty :: WatchList watchListEmpty = WatchList { wlNextId = 0, wlItems = IntMap.empty } watchListToList :: WatchList -> [(Int,ValuePath)] watchListToList WatchList { .. } = IntMap.toList wlItems watchListExtend :: ValuePath -> WatchList -> (Int,WatchList) watchListExtend vp WatchList { .. } = (wlNextId, WatchList { wlNextId = 1 + wlNextId , wlItems = IntMap.insert wlNextId vp wlItems }) watchListRemove :: Int -> WatchList -> WatchList watchListRemove n WatchList { .. } = WatchList { wlItems = IntMap.delete n wlItems, .. }
GaloisInc/galua
galua-dbg/src/Galua/Debugger/WatchList.hs
mit
926
0
11
205
240
138
102
23
1
module Y2016.M10.D19.Exercise where import Data.Map (Map) import Analytics.Trading.Data.Row (Symbol) -- http://lpaste.net/109658 import Analytics.Trading.Scan.Top5s -- http://lpaste.net/1443717939034324992 -- Below imports are available from 1HaskellADay git repository import Data.Bag {-- Let's continue our analyses that we started yesterday on the stock top5s, recorded at: https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2016/M10/D17/top5s.csv One way to find patterns in data is to look for specific things in the data, as we did yesterday, where we saw the patterns of losers-then-leaders and leaders-then-losers in the Price category. Another way to find patterns is by clustering. We've looked at K-means clustering before, back in March of this year: http://lpaste.net/3576182129349885952 We're NOT going to be doing clustering today, because what we have is a 'morass' of data, not a set of ScoreCards, or vectors of attributes. So, today, let's turn the morass of data that we do have into a set of ScoreCards, or a set of vectors of attributes. Today is Step 1 of that. Today. We won't look at adjacency at all. For each stock, count the number of shows in each category: Price, Market Capitalization, and Volume, further distinguishing the stock by losers and leaders in the appropriate categories. So, a ScoreCard for AAPL might look like: SC "AAPL" [(Price Leaders, ... Well, what does it look like? That entails quite a bit of work, so let's break it down even further. Today's Haskell problem is even simpler than creating score cards. Today: load in the top5s.csv from the URL above Then, count all occurrences of all stocks for each category. --} data LeadersLosers = Leader Top5Kind | Loser Top5Kind deriving (Eq, Ord, Show) countsInCategories :: FilePath -> Map LeadersLosers (Bag Symbol) countsInCategories top5sfile = undefined -- hint: use top5sHistory to load in the history file. -- n.b.: Volume Top5Kind has only leaders, not losers. -- Tomorrow we'll look at generating score cards from these category counts
geophf/1HaskellADay
exercises/HAD/Y2016/M10/D19/Exercise.hs
mit
2,098
0
8
339
106
65
41
9
1
a +#= b = c
chreekat/vim-haskell-syntax
test/golden/toplevel/infix-punct.hs
mit
12
0
5
5
12
5
7
1
1
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.YarnProtos.ContainerTypeProto (ContainerTypeProto(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data ContainerTypeProto = APPLICATION_MASTER | TASK deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable ContainerTypeProto instance Prelude'.Bounded ContainerTypeProto where minBound = APPLICATION_MASTER maxBound = TASK instance P'.Default ContainerTypeProto where defaultValue = APPLICATION_MASTER toMaybe'Enum :: Prelude'.Int -> P'.Maybe ContainerTypeProto toMaybe'Enum 1 = Prelude'.Just APPLICATION_MASTER toMaybe'Enum 2 = Prelude'.Just TASK toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum ContainerTypeProto where fromEnum APPLICATION_MASTER = 1 fromEnum TASK = 2 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Hadoop.Protos.YarnProtos.ContainerTypeProto") . toMaybe'Enum succ APPLICATION_MASTER = TASK succ _ = Prelude'.error "hprotoc generated code: succ failure for type Hadoop.Protos.YarnProtos.ContainerTypeProto" pred TASK = APPLICATION_MASTER pred _ = Prelude'.error "hprotoc generated code: pred failure for type Hadoop.Protos.YarnProtos.ContainerTypeProto" instance P'.Wire ContainerTypeProto where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB ContainerTypeProto instance P'.MessageAPI msg' (msg' -> ContainerTypeProto) ContainerTypeProto where getVal m' f' = f' m' instance P'.ReflectEnum ContainerTypeProto where reflectEnum = [(1, "APPLICATION_MASTER", APPLICATION_MASTER), (2, "TASK", TASK)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".hadoop.yarn.ContainerTypeProto") ["Hadoop", "Protos"] ["YarnProtos"] "ContainerTypeProto") ["Hadoop", "Protos", "YarnProtos", "ContainerTypeProto.hs"] [(1, "APPLICATION_MASTER"), (2, "TASK")] instance P'.TextType ContainerTypeProto where tellT = P'.tellShow getT = P'.getRead
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/YarnProtos/ContainerTypeProto.hs
mit
2,581
0
11
385
601
327
274
50
1
module Language.Paradocs.RuleEnv where import Control.Applicative import Control.Monad import Control.Lens import qualified Data.HashSet as HashSet import qualified Data.HashMap.Strict as HashMap import qualified Language.Paradocs.RuleName as RuleName import qualified Language.Paradocs.Rule as Rule import Language.Paradocs.Rule(ancestors) type RuleEnv = HashMap.HashMap RuleName.AbsoluteRuleName Rule.Rule isCycle :: RuleName.AbsoluteRuleName -> RuleEnv -> Bool isCycle = flip $ go HashSet.empty where go :: HashSet.HashSet RuleName.AbsoluteRuleName -> RuleEnv -> RuleName.AbsoluteRuleName -> Bool go cycleGird e ruleName | HashSet.member ruleName cycleGird = True | otherwise = do case e ^. at ruleName of Nothing -> False Just rule -> do let newCycleGird = HashSet.union (HashSet.singleton ruleName) cycleGird rule ^. ancestors . to (any (go newCycleGird e)) allAncestors :: RuleName.AbsoluteRuleName -> RuleEnv -> [RuleName.AbsoluteRuleName] allAncestors ruleName e | isCycle ruleName e = error "be cyclic" | otherwise = go e ruleName where go e' ruleName' = case HashMap.lookup ruleName' e' of Just rule -> rule ^. ancestors . to (map ((:) <*> go e')) . to join Nothing -> []
pasberth/paradocs
Language/Paradocs/RuleEnv.hs
mit
1,340
0
21
315
391
202
189
-1
-1
{-# LANGUAGE MultiParamTypeClasses, TemplateHaskell, FlexibleInstances, UndecidableInstances, ViewPatterns, TupleSections #-} import Prelude hiding (pi) import Unbound.LocallyNameless import Unbound.LocallyNameless.Fresh import Unbound.LocallyNameless.Ops (unsafeUnbind) import Control.Monad.Trans.Reader (mapReaderT) import Control.Monad.Trans.Either import Control.Monad.Except hiding (fix) import Control.Monad.Morph (MFunctor, hoist, generalize) -- # Data Types -- ## Terms - representation that can be type checked -- TODO: "Inferable" is spelled wrong. data CheckableTerm = TInferrable InferrableTerm | TLambda (Bind (TermName) CheckableTerm) | TFix (Bind (TermName) CheckableTerm) deriving Show type CheckableType = CheckableTerm data InferrableTerm = TStar | TAnnotation CheckableTerm CheckableType | TPi (Bind (TermName, Embed CheckableType) CheckableType) | TVariable (TermName) | TApplication InferrableTerm CheckableTerm | TLet (Bind (TermName, Embed InferrableTerm) InferrableTerm) deriving Show type TermName = Name InferrableTerm $(derive [''CheckableTerm, ''InferrableTerm]) instance Alpha CheckableTerm instance Alpha InferrableTerm instance Subst InferrableTerm CheckableTerm where instance Subst InferrableTerm InferrableTerm where isvar (TVariable v) = Just (SubstName v) isvar _ = Nothing -- ### Conveniences lambda :: String -> CheckableTerm -> CheckableTerm lambda varName body = TLambda $ bind boundName body where boundName = string2Name varName letIn :: String -> InferrableTerm -> InferrableTerm -> InferrableTerm letIn varName var body = TLet (bind (string2Name varName, embed var) body) letIn' :: String -> CheckableType -> CheckableTerm -> InferrableTerm -> InferrableTerm letIn' varName varType var body = letIn varName (TAnnotation var varType) body pi :: String -> CheckableTerm -> CheckableTerm -> InferrableTerm pi varName varType bodyType = TPi $ bind boundName bodyType where boundName = (string2Name varName, embed varType) fix :: String -> CheckableTerm -> CheckableTerm fix funcName body = TFix (bind (string2Name funcName) body) (-->) :: CheckableTerm -> CheckableTerm -> InferrableTerm (-->) = pi "_" infix 1 --> var :: String -> InferrableTerm var = TVariable . string2Name (@@) :: InferrableTerm -> CheckableTerm -> InferrableTerm (@@) = TApplication infixl 9 @@ inf :: InferrableTerm -> CheckableTerm inf = TInferrable -- ### Program --data Scope = Empty | Cons (Bind (TermName, Embed InferrableTerm) Scope) --data TermProgram = TermProgram (TRec [(TermName, Embed InferrableTerm)]) --data ExprProgram = ExprProgram (TRec [(Name Expr, Embed Expr)]) -- ## Expressions - representation that can be evaluated data Expr = EStar | EPi (Bind (Name Expr, Embed TypeExpr) TypeExpr) | ELambda (Bind (Name Expr) Expr) | EVariable (Name Expr) | EApplication Expr Expr | EFix (Bind (Name Expr) Expr) | ELet (Bind (Name Expr, Embed Expr) Expr) type TypeExpr = Expr $(derive [''Expr]) instance Alpha Expr instance Subst Expr Expr where isvar (EVariable v) = Just (SubstName v) isvar _ = Nothing instance Show Expr where show = runLFreshM . show' where show' :: LFresh m => Expr -> m String show' EStar = return "*" show' (EPi term) = lunbind term $ \((varName, unembed -> varType), bodyType) -> do varTypeString <- show' varType bodyTypeString <- show' bodyType if containsFree varName bodyType then return $ "(" ++ name2String varName ++ ":" ++ varTypeString ++ ") -> " ++ bodyTypeString else return $ "(" ++ varTypeString ++ ")" ++ " -> " ++ bodyTypeString show' (EVariable name) = return $ name2String name show' (EApplication func arg) = do funcString <- show' func argString <- show' arg return $ "(" ++ funcString ++ ")" ++ " " ++ "(" ++ argString ++ ")" show' (ELambda term) = lunbind term $ \(varName, body) -> do bodyString <- show' body return $ "λ" ++ name2String varName ++ "." ++ bodyString show' (EFix func) = lunbind func $ \(funcName, body) -> do bodyString <- show' body return $ "fix(λ" ++ name2String funcName ++ "." ++ bodyString ++ ")" show' (ELet term) = lunbind term $ \((varName, unembed -> var), body) -> do varString <- show' var bodyString <- show' body return $ "(let " ++ name2String varName ++ " = " ++ varString ++ " in " ++ bodyString ++ ")" containsFree :: Name Expr -> Expr -> Bool containsFree name term = name `elem` (fv term :: [Name Expr]) -- ## Values - representation that cannot be further evaluated data Value = VStar | VPi (Bind (Name Expr, Embed TypeExpr) TypeExpr) | VLambda (Bind (Name Expr) Expr) | VNeutral NeutralValue | VFix (Bind (Name Expr) Expr) data NeutralValue = VVariable (Name Value) | VApplication NeutralValue Value type TypeValue = Value $(derive [''Value, ''NeutralValue]) instance Alpha Value instance Alpha NeutralValue --instance Subst Expr Value where -- isvar (EVariable v) = Just (SubstName v) -- isvar _ = Nothing instance Show Value where show = show . expr instance Show NeutralValue where show = show . VNeutral -- # Small-Step Evaluation instance (LFresh m) => LFresh (EitherT a m) where lfresh = lift . lfresh avoid = mapEitherT . avoid getAvoids = lift getAvoids evaluate :: Expr -> LFreshM Value evaluate = evaluate' True where evaluate' :: {- followLoops: -} Bool -> Expr -> LFreshM Value evaluate' _ EStar = return $ VStar evaluate' _ (EPi func) = lunbind func $ \((varName, unembed -> varType), bodyType) -> do bodyType <- evaluate' False bodyType return $ VPi $ bind (translate varName, embed varType) (expr bodyType) evaluate' _ (ELambda func) = lunbind func $ \(varName, body) -> do body <- evaluate' False body return $ VLambda $ bind (translate varName) (expr body) evaluate' _ (EVariable var) = return $ VNeutral $ VVariable $ translate var evaluate' _ (EApplication func arg) = do func <- evaluate func arg <- evaluate arg case func of VPi func -> lunbind func $ \((varName, _), bodyType) -> do evaluate $ subst varName (expr arg) bodyType VLambda func -> lunbind func $ \(varName, body) -> do evaluate $ subst varName (expr arg) body VNeutral func -> return $ VNeutral $ VApplication func arg _ -> error "precondition failure" evaluate' False (EFix func) = return $ VFix func evaluate' True (EFix func) = lunbind func $ \(funcName, body) -> do self <- evaluate (EFix func) evaluate $ subst funcName (expr self) body evaluate' _ (ELet term) = lunbind term $ \((varName, unembed -> var), body) -> do var <- evaluate var evaluate $ subst varName (expr var) body -- ((a -> b) -> (a -> b)) -> (a -> b) instance MFunctor LFreshMT where hoist f = LFreshMT . (mapReaderT f) . unLFreshMT mapBound :: (Alpha t, Alpha v) => (t -> v) -> Bind (Name t) t -> Bind (Name v) v mapBound f (unsafeUnbind -> (name, value)) = bind (translate name) (f value) expr :: Value -> Expr expr VStar = EStar expr (VPi func) = EPi func expr (VLambda func) = ELambda func expr (VNeutral value) = expr' value where expr' :: NeutralValue -> Expr expr' (VVariable var) = EVariable (translate var) expr' (VApplication func arg) = EApplication (expr' func) (expr arg) expr (VFix value) = EFix value -- # Type Checking type Context = [(TermName, TypeValue)] type ExpectedType = TypeValue type FoundType = TypeValue data TypeError = TypeMismatchFoundPiType ExpectedType Context | TypeMismatch FoundType ExpectedType | TypesNotEqual FoundType FoundType | ApplicationToNonPiType Expr CheckableTerm FoundType | FixReturnsNonPiType FoundType | VariableNotInScope String | UnableToDeduceHoleFromContext instance Show TypeError where show (TypeMismatchFoundPiType expectedType context) = "Type mismatch: expected " ++ show expectedType ++ " but found pi type in context " ++ show context show (TypeMismatch foundType expectedType) = "Type mismatch: expected " ++ show expectedType ++ " but found " ++ show foundType show (TypesNotEqual firstType secondType) = "Type mismatch: expected " ++ show firstType ++ " and " ++ show secondType ++ " to match" show (ApplicationToNonPiType func arg foundType) = "Function application of " ++ show func ++ " to " ++ show arg ++ " requires function to be pi type, not " ++ show foundType show (FixReturnsNonPiType foundType) = "Fix expression must be a function type, but expected " ++ show foundType show (VariableNotInScope name) = "Variable named " ++ show name ++ " is not in scope" show UnableToDeduceHoleFromContext = "Unable to deduce hole value from context" elseThrowError :: Maybe a -> TypeError -> Except TypeError a elseThrowError (Just x) _ = return x elseThrowError Nothing error = throwError error checkEvalType :: Context -> CheckableType -> LFreshMT (Except TypeError) TypeValue checkEvalType context termType = check context termType VStar >>= hoist generalize . evaluate infer :: Context -> InferrableTerm -> LFreshMT (Except TypeError) (Expr, TypeValue) infer _ TStar = return (EStar, VStar) infer context (TAnnotation term termType) = do termType <- checkEvalType context termType term <- check context term termType return (term, termType) infer context (TPi term) = lunbind term $ \((varName, unembed -> varType), bodyType) -> do varType <- checkEvalType context varType bodyType <- check ((varName, varType):context) bodyType VStar return (EPi $ bind (translate varName, (embed . expr) varType) bodyType, VStar) infer context (TVariable name) = lift $ do varType <- lookup name context `elseThrowError` VariableNotInScope (name2String name) return (EVariable (translate name), varType) infer context (TApplication func arg) = do (func, funcType) <- infer context func case funcType of VPi funcType -> lunbind funcType $ \((varName, unembed -> varType), body) -> do varType <- hoist generalize (evaluate varType) arg <- check context arg varType let bodyType = subst varName arg body bodyType <- hoist generalize (evaluate bodyType) return (EApplication func arg, bodyType) actualType -> throwError $ ApplicationToNonPiType func arg actualType infer context (TLet term) = lunbind term $ \((varName, unembed -> var), body) -> do (var', _) <- infer context var -- FIXME: Duplicate work inferring var multiple times after subst. (body, bodyType) <- infer context (subst varName var body) return (ELet $ bind (translate varName, embed var') body, bodyType) check :: Context -> CheckableTerm -> TypeValue -> LFreshMT (Except TypeError) Expr check context (TInferrable term) expectedType = do (elab, actualType) <- infer context term unless (expectedType `aeq` actualType) $ throwError $ TypeMismatch actualType expectedType return elab check context (TLambda term) (VPi termType) = lunbind termType $ \((piVarName, unembed -> varType), bodyType) -> lunbind term $ \(lambdaVarName, body) -> do varType <- hoist generalize (evaluate varType) let rename = subst piVarName (EVariable $ translate lambdaVarName) bodyType <- hoist generalize (evaluate $ rename bodyType) body <- check ((lambdaVarName, varType):context) body bodyType return $ ELambda $ bind (translate lambdaVarName) body check context (TLambda _) expectedType = throwError $ TypeMismatchFoundPiType expectedType context check context (TFix func) expectedType = lunbind func $ \(funcName, body) -> do body <- check ((funcName, expectedType):context) body expectedType return $ EFix $ bind (translate funcName) body check' :: Context -> CheckableTerm -> CheckableType -> LFreshMT (Except TypeError) Expr check' context term typeTerm = checkEvalType context typeTerm >>= check context term run :: InferrableTerm -> LFreshMT (Except TypeError) (Value, TypeValue) run term = do (expr, typ) <- infer [] term value <- hoist generalize (evaluate expr) return (value, typ) -- # Examples withCore :: InferrableTerm -> InferrableTerm withCore term = letIn "unit" TStar $ letIn' "id" (inf $ pi "T" (inf TStar) $ inf $ inf (var "T") --> inf (var "T")) (lambda "T" $ lambda "x" $ inf (var "x")) $ letIn' "const" (inf $ pi "T" (inf TStar) $ inf $ pi "V" (inf TStar) $ inf $ inf (var "T") --> inf (inf (var "V") --> inf (var "T"))) (lambda "T" $ lambda "V" $ lambda "x" $ lambda "y" $ inf (var "x")) $ letIn' "seq" (inf $ pi "T" (inf TStar) $ inf $ pi "V" (inf TStar) $ inf $ inf (var "T") --> inf (inf (var "V") --> inf (var "V"))) (lambda "T" $ lambda "V" $ lambda "x" $ lambda "y" $ inf (var "y")) $ letIn "bool" (pi "T" (inf TStar) $ inf $ inf (var "T") --> inf (inf (var "T") --> inf (var "T"))) $ letIn' "true" (inf $ var "bool") (lambda "T" $ inf $ var "const" @@ inf (var "T") @@ inf (var "T")) $ letIn' "false" (inf $ var "bool") (lambda "T" $ inf $ var "seq" @@ inf (var "T") @@ inf (var "T")) $ letIn' "not" (inf $ inf (var "bool") --> inf (var "bool")) (lambda "b" $ lambda "T" $ lambda "t" $ lambda "f" $ inf $ var "b" @@ inf (var "T") @@ inf (var "f") @@ inf (var "t")) $ letIn' "if" (inf $ pi "T" (inf TStar) $ inf $ pi "cond" (inf $ var "bool") $ inf $ inf (inf (var "unit") --> inf (var "T")) --> inf ( inf (inf (var "unit") --> inf (var "T")) --> inf ( var "T"))) (lambda "T" $ lambda "cond" $ lambda "trueCond" $ lambda "falseCond" $ inf $ (var "cond" @@ inf (inf (var "unit") --> inf (var "T")) @@ inf (var "trueCond") @@ inf (var "falseCond")) @@ inf (var "unit")) $ letIn "nat" (pi "A" (inf TStar) $ inf $ inf (inf (var "A") --> inf (var "A")) --> inf (inf (var "A") --> inf (var "A"))) $ letIn' "zero" (inf $ var "nat") (lambda "T" $ lambda "succ" $ lambda "zero" $ inf $ var "zero") $ letIn' "succ" (inf $ inf (var "nat") --> inf (var "nat")) (lambda "n" $ lambda "T" $ lambda "succ" $ lambda "zero" $ inf $ var "succ" @@ inf (var "n" @@ inf (var "T") @@ inf (var "succ") @@ inf (var "zero"))) $ letIn' "isZero" (inf $ inf (var "nat") --> inf (var "bool")) (lambda "n" $ inf $ var "n" @@ inf (var "bool") @@ (lambda "_" $ inf $ var "false") @@ inf (var "true")) $ letIn' "absurd" (inf $ pi "A" (inf TStar) $ (inf $ var "A")) (lambda "A" $ fix "x" $ inf $ var "x") $ letIn' "pair" (inf $ pi "A" (inf TStar) $ inf $ pi "B" (inf TStar) $ inf TStar) (lambda "A" $ lambda "B" $ inf $ pi "C" (inf TStar) $ inf $ (inf $ (inf $ var "A") --> inf ((inf $ var "B") --> (inf $ var "C"))) --> inf ( var "C")) $ letIn' "makePair" (inf $ pi "A" (inf TStar) $ inf $ pi "B" (inf TStar) $ inf $ inf (var "A") --> inf ( inf (var "B") --> inf ( var "pair" @@ inf (var "A") @@ inf (var "B")))) (lambda "A" $ lambda "B" $ lambda "x" $ lambda "y" $ lambda "C" $ lambda "f" $ inf $ var "f" @@ inf (var "x") @@ inf (var "y")) $ letIn' "first" (inf $ pi "A" (inf TStar) $ inf $ pi "B" (inf TStar) $ inf $ (inf $ var "pair" @@ inf (var "A") @@ inf (var "B")) --> inf (var "A")) (lambda "A" $ lambda "B" $ lambda "p" $ inf $ var "p" @@ inf (var "A") @@ inf (var "const" @@ inf (var "A") @@ inf (var "B"))) $ letIn' "second" (inf $ pi "A" (inf TStar) $ inf $ pi "B" (inf TStar) $ inf $ (inf $ var "pair" @@ inf (var "A") @@ inf (var "B")) --> inf (var "B")) (lambda "A" $ lambda "B" $ lambda "p" $ inf $ var "p" @@ inf (var "B") @@ inf (var "seq" @@ inf (var "A") @@ inf (var "B"))) $ term --typecheckCore = (runLFreshMT $ run $ withCore $ TStar) >> return () --program = withCore $ (var "if" @@ inf (var "bool") -- @@ inf (var "false") -- @@ (lambda "_" $ inf $ var "false") -- @@ (lambda "_" $ inf $ var "true")) --program = withCore $ var "succ" @@ (inf ((var "succ") @@ inf (var "zero"))) --program = withCore $ (var "absurd") @@ inf TStar --program = withCore $ (var "absurd") --program = withCore $ -- letIn' "test" (inf $ pi "A" (inf TStar) $ (inf TStar)) -- (lambda "A" $ fix " x" $ inf $ TStar) $ -- var "test" @@ inf TStar
JadenGeller/Tart
Sources/Tart.hs
mit
18,826
0
32
6,098
6,129
3,035
3,094
313
11
{-# LANGUAGE OverloadedStrings, TypeOperators, FlexibleContexts #-} module Wf.Control.Eff.Run.SessionSpec ( sessionSpec ) where import Control.Eff (Eff, (:>), Member, SetMember, handleRelay) import qualified Wf.Control.Eff.Kvs as Kvs (Kvs(..), get) import Control.Eff.Lift (Lift, runLift) import Control.Eff.Exception (Exc, runExc, throwExc) import Control.Eff.State.Strict (State, get, put, evalState, runState) import Control.Eff.Reader.Strict (Reader, runReader) import Wf.Control.Eff.Logger (LogLevel(..), runLoggerStdIO) import Control.Exception (SomeException) import qualified Data.Binary as Bin (encode) import qualified Data.Map as M (Map, fromList, empty, member, null) import qualified Data.HashMap.Strict as HM (fromList) import qualified Data.ByteString as B (ByteString) import qualified Data.ByteString.Char8 as B (pack) import qualified Data.ByteString.Lazy as L (ByteString, fromStrict, toStrict) import qualified Data.ByteString.Lazy.Char8 as L (pack) import Web.Cookie (SetCookie, renderCookies) import Blaze.ByteString.Builder (toByteString) import Wf.Application.Logger (Logger, logDebug) import Wf.Control.Eff.Run.Kvs.Map (runKvsMap) import Wf.Application.Exception (Exception(..)) import Wf.Session.Kvs (Session(..), defaultSessionSettings, sget, sput, sttl, sdestroy, getSessionId, SessionKvs(..), SessionError(..), SessionState(..), SessionData(..), SessionSettings(..), defaultSessionState, defaultSessionData, runSessionKvs) import Wf.Control.Eff.Run.Session (runSession) import Wf.Application.Time (Time, getCurrentTime, addSeconds) import qualified Network.Wai as Wai (Request(..), defaultRequest) import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy) import qualified Test.Hspec.QuickCheck as Q import qualified Test.QuickCheck.Property as Q sessionSpec :: Spec sessionSpec = describe "session" $ do it "start automatically" $ do t <- getCurrentTime let key = "state" :: B.ByteString let val = "hello" :: B.ByteString let code = do sput key val sttl 10 getSessionId Right (s, sid) <- runTest "SID" t Wai.defaultRequest M.empty code shouldSatisfy s (M.member sid) it "restore automatically" $ do let name = "SID" let sid = "testSessionId000" let cookies = [(name, sid)] let headers = [("Cookie", toByteString . renderCookies $ cookies)] let request = Wai.defaultRequest { Wai.requestHeaders = headers } let key = "hello" let val = ("world", 1, [3]) :: (String, Integer, [Integer]) let sval = HM.fromList [(key, Bin.encode val)] t <- getCurrentTime let expireDate = addSeconds t 10 let sd = Bin.encode SessionData { sessionValue = sval, sessionStartDate = t, sessionExpireDate = expireDate } let sessionState = M.fromList [(sid, sd)] let code = do v <- sget key sid' <- getSessionId return (v, sid') Right (_, result) <- runTest name t request sessionState code result `shouldBe` (Just val, sid) it "destroy" $ do t <- getCurrentTime let key = "state" :: B.ByteString let val = "hello" :: B.ByteString let code = do sput key val before <- getSessionId sdestroy after <- getSessionId return (before, after) Right (s, (_, afterId)) <- runTest "SID" t Wai.defaultRequest M.empty code afterId `shouldBe` "" shouldSatisfy s M.null runTest :: B.ByteString -> Time -> Wai.Request -> M.Map B.ByteString L.ByteString -> Eff ( Session :> Reader Wai.Request :> Kvs.Kvs SessionKvs :> State (M.Map B.ByteString L.ByteString) :> Exception :> Logger :> Lift IO :> ()) a -> IO (Either SomeException (M.Map B.ByteString L.ByteString, a)) runTest name t request s a = do let ssettings = defaultSessionSettings { sessionName = name } runLift . runLoggerStdIO DEBUG . runExc . runState s . runKvsMap . flip runReader request . runSessionKvs ssettings t $ a
bigsleep/Wf
wf-session/test/Wf/Control/Eff/Run/SessionSpec.hs
mit
4,352
0
19
1,149
1,333
749
584
96
1
module Main(main) where main = interact id
rockdragon/julia-programming
code/haskell/Interact.hs
mit
44
0
5
8
17
10
7
2
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} module Tracking.Database where import Database.Persist.TH import Data.ByteString import Data.Time.Clock share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Entry time UTCTime msg ByteString |] deriving instance Show Entry
schell/xybish
src/Tracking/Database.hs
mit
507
0
7
83
62
39
23
14
0
{-# language MagicHash, BangPatterns, CPP, RankNTypes, RoleAnnotations, UnboxedTuples, ScopedTypeVariables #-} {-# options_ghc -fno-full-laziness -fno-warn-name-shadowing #-} module Data.TrieVector ( Vector(..) , (|>) , (!#) , (!) , snoc , Data.TrieVector.foldr , Data.TrieVector.foldl' , rfoldr , rfoldl' , Data.TrieVector.map , modify , unsafeModify , modify# , unsafeModify# , noCopyModify'# , singleton , empty , Data.TrieVector.length , fromList , snocFromList , pop , Data.TrieVector.reverse , Data.TrieVector.inits , revTails ) where import qualified Data.Foldable as F import GHC.Prim import GHC.Types import Data.List import Data.TrieVector.Array (Array) import qualified Data.TrieVector.Array as A import Data.TrieVector.ArrayArray (AArray) import qualified Data.TrieVector.ArrayArray as AA import Debug.Trace #define NODE_WIDTH 16# #define KEY_BITS 4# #define KEY_MASK 15# type role Vector nominal data Vector a = Vector { _size, _level :: Int#, _init :: AArray, _tail :: Array a} instance Functor Vector where fmap = Data.TrieVector.map {-# inline fmap #-} instance Show a => Show (Vector a) where show v = show (F.toList v) instance F.Foldable Vector where foldr = Data.TrieVector.foldr {-# inline foldr #-} foldr' f = Data.TrieVector.rfoldl' (flip f) {-# inline foldr' #-} foldl f = Data.TrieVector.rfoldr (flip f) {-# inline foldl #-} foldl' = Data.TrieVector.foldl' {-# inline foldl' #-} length = Data.TrieVector.length {-# inline length #-} null v = Data.TrieVector.length v == 0 {-# inline null #-} instance Monoid (Vector a) where mempty = empty mappend = Data.TrieVector.foldl' snoc {-# inline mappend #-} instance Traversable Vector where traverse f = fmap fromList . traverse f . F.toList {-# inline traverse #-} (|>) :: Vector a -> a -> Vector a (|>) = snoc infixl 5 |> {-# inline (|>) #-} infixl 5 ! (!) :: forall a. Vector a -> Int -> a (!) v (I# i) = v !# i {-# inline (!) #-} (!#) :: forall a. Vector a -> Int# -> a (!#) (Vector size level init tail) i = case i >=# 0# of 1# -> let tailSize = andI# size KEY_MASK initSize = size -# tailSize indexAA 0# init = A.index (aa2a init) (index i 0#) indexAA level init = indexAA (next level) (AA.index init (index i level)) in case i <# initSize of 1# -> case level of 0# -> A.index (aa2a init) (index i level) _ -> let l2 = next level i2 = AA.index init (index i level) in case l2 of 0# -> A.index (aa2a i2) (index i l2) _ -> let l3 = next l2 i3 = AA.index i2 (index i l2) in case l3 of 0# -> A.index (aa2a i3) (index i l3) _ -> let l4 = next l3 i4 = AA.index i3 (index i l3) in case l4 of 0# -> A.index (aa2a i4) (index i l4) _ -> let l5 = next l4 i5 = AA.index i4 (index i l4) in case l5 of 0# -> A.index (aa2a i5) (index i l5) _ -> let l6 = next l5 i6 = AA.index i5 (index i l5) in case l6 of 0# -> A.index (aa2a i6) (index i l6) _ -> let l7 = next l6 i7 = AA.index i6 (index i l6) in indexAA l7 i7 _ -> case i <# size of 1# -> A.index tail (i -# initSize) _ -> boundsError _ -> boundsError {-# inline (!#) #-} snocAA :: AArray -> Int# -> Int# -> Int# -> AArray -> AArray snocAA arr _ _ 0# _ = arr snocAA arr mask i level init = case andI# i mask of 0# -> init1AA (snocAA arr (nextMask mask) i (next level) (_init empty)) _ -> AA.modify NODE_WIDTH init (index i level) (snocAA arr (nextMask mask) i (next level)) snoc :: forall a. Vector a -> a -> Vector a snoc (Vector size level init tail) v = let tailSize = andI# size KEY_MASK initSize = size -# tailSize size' = size +# 1# tail' = A.update NODE_WIDTH tail tailSize v in case tailSize of KEY_MASK -> let prevLevel = level +# KEY_BITS maxSize = uncheckedIShiftL# 1# prevLevel mask = maxSize -# 1# init' = snocAA (a2aa tail') mask initSize level init in case initSize ==# maxSize of 1# -> Vector size' prevLevel (init2AA init init') (_tail empty) _ -> Vector size' level init' (_tail empty) _ -> Vector size' level init tail' {-# inline snoc #-} popArray :: Int# -> Int# -> Int# -> AArray -> (# Array a, AArray #) popArray mask i level init = case level of 0# -> (# aa2a init, _init empty #) _ -> case popArray (nextMask mask) i (next level) (AA.index init ix) of (# popped, newElem #) -> case andI# i mask of 0# -> (# popped, _init empty #) _ -> (# popped, AA.update width init ix newElem #) where ix = index i level width = NODE_WIDTH {-# inline popArray #-} pop :: forall a. Vector a -> (Vector a, a) pop (Vector 0# _ _ _ ) = popError pop (Vector size level init tail) = let tailSize = andI# size KEY_MASK size' = size -# 1# width = NODE_WIDTH in case tailSize of 0# -> let prevLevel = level +# KEY_BITS mask = (uncheckedIShiftL# 1# prevLevel) -# 1# (# popped, init' #) = popArray mask size' level init in case index size' level of 0# -> (Vector size' (next level) (AA.index init' 0#) popped, A.index popped (width -# 1#)) _ -> (Vector size' level init' popped, A.index popped (width -# 1#)) _ -> let lasti = tailSize -# 1# in (Vector size' level init (A.update width tail lasti undefElem), A.index tail lasti) {-# inline pop #-} snocFromList :: [a] -> Vector a snocFromList = Data.List.foldl' snoc empty {-# inline snocFromList #-} snocArr :: forall a. Vector a -> Array a -> Vector a snocArr (Vector size level init tail) arr = let width = NODE_WIDTH size' = size +# width prevLevel = level +# KEY_BITS maxSize = uncheckedIShiftL# 1# prevLevel mask = maxSize -# 1# init' = snocAA (a2aa arr) mask size level init in case size ==# maxSize of 1# -> Vector size' prevLevel (init2AA init init') tail _ -> Vector size' level init' tail {-# inline snocArr #-} fromList :: [a] -> Vector a fromList = go empty where width = NODE_WIDTH go acc@(Vector size level init _) xs = case A.fromList' width undefElem xs of (# arr, xs, consumed #) -> case consumed of NODE_WIDTH -> go (snocArr acc arr) xs _ -> Vector (size +# consumed) level init arr {-# inline fromList #-} foldr :: forall a b. (a -> b -> b) -> b -> Vector a -> b foldr f z (Vector size level arr tail) = case initSize of 0# -> tailRes _ -> notfull (initSize -# 1#) level arr tailRes where tailSize = andI# size KEY_MASK initSize = size -# tailSize tailRes = A.foldr tailSize f z tail notfull :: Int# -> Int# -> AArray -> b -> b notfull _ 0# arr z = A.foldr NODE_WIDTH f z (aa2a arr) notfull lasti level arr z = AA.foldr lasti' (full level') (notfull lasti level' (AA.index arr lasti') z) arr where lasti' = index lasti level level' = next level full :: Int# -> AArray -> b -> b full 0# arr z = A.foldr NODE_WIDTH f z (aa2a arr) full level arr z = AA.foldr NODE_WIDTH (full (next level)) z arr {-# inline foldr #-} rfoldr :: forall a b. (a -> b -> b) -> b -> Vector a -> b rfoldr f z (Vector size level init tail) = case initSize of 0# -> A.rfoldr tailSize f z tail _ -> A.rfoldr tailSize f (notfull (initSize -# 1#) level init z) tail where tailSize = andI# size KEY_MASK initSize = size -# tailSize notfull :: Int# -> Int# -> AArray -> b -> b notfull lasti level arr z = case level of 0# -> A.rfoldr NODE_WIDTH f z (aa2a arr) _ -> notfull lasti level' (AA.index arr lasti') (AA.rfoldr lasti' (full level') z arr) where lasti' = index lasti level level' = next level full :: Int# -> AArray -> b -> b full 0# arr z = A.rfoldr NODE_WIDTH f z (aa2a arr) full level arr z = AA.rfoldr NODE_WIDTH (full (next level)) z arr {-# inline rfoldr #-} foldl' :: forall a b. (b -> a -> b) -> b -> Vector a -> b foldl' f z (Vector size level init tail) = case initSize of 0# -> A.foldl' tailSize f z tail _ -> A.foldl' tailSize f (notfull (initSize -# 1#) level init z) tail where tailSize = andI# size KEY_MASK initSize = size -# tailSize notfull :: Int# -> Int# -> AArray -> b -> b notfull lasti level arr z = case level of 0# -> A.foldl' width f z (aa2a arr) _ -> notfull lasti level' (AA.index arr lasti') (AA.foldl' lasti' (full level') z arr) where lasti' = index lasti level level' = next level width = NODE_WIDTH full :: Int# -> b -> AArray -> b full level z arr = case level of 0# -> A.foldl' width f z (aa2a arr) _ -> AA.foldl' width (full (next level)) z arr where width = NODE_WIDTH {-# inline foldl' #-} rfoldl' :: forall a b. (b -> a -> b) -> b -> Vector a -> b rfoldl' f z (Vector size level init tail) = case initSize of 0# -> A.rfoldl' tailSize f z tail _ -> notfull (initSize -# 1#) level init (A.rfoldl' tailSize f z tail) where tailSize = andI# size KEY_MASK initSize = size -# tailSize notfull :: Int# -> Int# -> AArray -> b -> b notfull lasti level arr z = case level ># 0# of 1# -> AA.rfoldl' lasti' (full level') (notfull lasti level' (AA.index arr lasti') z) arr _ -> A.rfoldl' width f z (aa2a arr) where lasti' = index lasti level level' = next level width = NODE_WIDTH full :: Int# -> b -> AArray -> b full level z arr = case level ># 0# of 1# -> AA.rfoldl' width (full (next level)) z arr _ -> A.rfoldl' width f z (aa2a arr) where width = NODE_WIDTH {-# inline rfoldl' #-} map :: forall a b. (a -> b) -> Vector a -> Vector b map _ s@(Vector 0# _ _ _ ) = unsafeCoerce# s map f (Vector size level init tail) = Vector size level init' tail' where tailSize = andI# size KEY_MASK initSize = size -# tailSize init' = notfull (initSize -# 1#) level init tail' = A.map tailSize f tail notfull :: Int# -> Int# -> AArray -> AArray notfull lasti level arr = case level of 0# -> a2aa (A.map NODE_WIDTH f (aa2a arr)) _ -> AA.mapInitLast lasti' (full level') (notfull lasti level') arr where lasti' = index lasti level level' = next level full :: Int# -> AArray -> AArray full 0# arr = a2aa (A.map NODE_WIDTH f (aa2a arr)) full level arr = AA.map NODE_WIDTH (full (next level)) arr {-# inline map #-} modify# :: forall a. Vector a -> Int# -> (a -> a) -> Vector a modify# (Vector size level init tail) i f = case i >=# 0# of 1# -> let modifyAA 0# arr = a2aa (A.modify NODE_WIDTH (aa2a arr) (index i 0#) f) modifyAA level arr = AA.modify NODE_WIDTH arr (index i level) (modifyAA (next level)) tailSize = andI# size KEY_MASK initSize = size -# tailSize in case i <# initSize of 1# -> Vector size level (modifyAA level init) tail _ -> case i <# size of 1# -> Vector size level init (A.modify NODE_WIDTH tail (i -# initSize) f) _ -> boundsError _ -> boundsError {-# inline modify# #-} unsafeModify# :: forall a. Vector a -> Int# -> (a -> a) -> Vector a unsafeModify# (Vector size level init tail) i f = let modifyAA 0# arr = a2aa (A.modify NODE_WIDTH (aa2a arr) (index i 0#) f) modifyAA level arr = AA.modify NODE_WIDTH arr (index i level) (modifyAA (next level)) tailSize = andI# size KEY_MASK initSize = size -# tailSize in case i <# initSize of 1# -> Vector size level (modifyAA level init) tail _ -> Vector size level init (A.modify NODE_WIDTH tail (i -# initSize) f) {-# inline unsafeModify# #-} modify :: forall a. Vector a -> Int -> (a -> a) -> Vector a modify v (I# i) f = modify# v i f {-# inline modify #-} unsafeModify :: forall a. Vector a -> Int -> (a -> a) -> Vector a unsafeModify v (I# i) f = unsafeModify# v i f {-# inline unsafeModify #-} noCopyModify'# :: forall a. Vector a -> Int# -> (a -> a) -> Vector a noCopyModify'# v@(Vector size level init tail) i f = case i >=# 0# of 1# -> let width = NODE_WIDTH modifyAA 0# arr = a2aa (A.noCopyModify' width (aa2a arr) (index i 0#) f) modifyAA level arr = AA.noCopyModify width arr (index i level) (modifyAA (next level)) tailSize = andI# size KEY_MASK initSize = size -# tailSize in case i <# initSize of 1# -> let init' = modifyAA level init in case AA.ptrEq init init' of 1# -> v _ -> Vector size level init' tail _ -> case i <# size of 1# -> let tail' = A.noCopyModify' width tail (i -# initSize) f in case AA.ptrEq (a2aa tail) (a2aa tail') of 1# -> v _ -> Vector size level init tail' _ -> boundsError _ -> boundsError {-# inline noCopyModify'# #-} reverse :: Vector a -> Vector a reverse v = rfoldl' snoc empty v {-# inline reverse #-} -- | Note: lists inits in reversed order compared to Data.List.inits ! inits :: Vector a -> [Vector a] inits = go where go v | F.null v = [v] go v = v : go (fst $ pop v) {-# inline inits #-} revTails :: Vector a -> [Vector a] revTails = Data.TrieVector.inits . Data.TrieVector.reverse where {-# inline revTails #-} empty :: forall a. Vector a empty = Vector 0# 0# (AA.new 0# undefElem) (A.new NODE_WIDTH undefElem) {-# noinline empty #-} singleton :: a -> Vector a singleton a = Vector 1# 0# (_init empty) (init1A a) {-# inline singleton #-} length :: Vector a -> Int length (Vector size _ _ _) = I# size {-# inline length #-} -- Low-level fiddling -------------------------------------------------------------------------------- next :: Int# -> Int# next level = level -# KEY_BITS {-# inline next #-} nextMask :: Int# -> Int# nextMask mask = uncheckedIShiftRL# mask KEY_BITS {-# inline nextMask #-} index :: Int# -> Int# -> Int# index i level = andI# (uncheckedIShiftRL# i level) KEY_MASK {-# inline index #-} aa2a :: AArray -> Array a aa2a = unsafeCoerce# {-# inline aa2a #-} a2aa :: Array a -> AArray a2aa = unsafeCoerce# {-# inline a2aa #-} boundsError :: a boundsError = error "TrieVector: index out of bounds" {-# noinline boundsError #-} undefElem :: a undefElem = error "Vector: undefined element" {-# noinline undefElem #-} popError :: a popError = error "TrieVector: can't pop from empty vector" {-# noinline popError #-} init1A :: a -> Array a init1A a = A.init1 NODE_WIDTH a undefElem {-# inline init1A #-} init1AA :: AArray -> AArray init1AA a = AA.init1 NODE_WIDTH a (_tail empty) {-# inline init1AA #-} init2AA :: AArray -> AArray -> AArray init2AA a1 a2 = AA.init2 NODE_WIDTH a1 a2 (_tail empty) {-# inline init2AA #-} nFields :: Addr# -> Int# -> [Int] nFields addr n = go 0# where go i = case i ==# n of 1# -> [] _ -> (I# (indexIntOffAddr# addr i)) : go (i +# 1#) {-# inline nFields #-} #undef NODE_WIDTH #undef KEY_BITS #undef KEY_MASK #undef NODE_SIZE
AndrasKovacs/trie-vector
Data/TrieVector.hs
mit
16,616
368
31
5,560
5,401
2,863
2,538
394
11
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-} module Haste.JSArray where import Control.Applicative hiding ((<*>), pure) import qualified Control.Applicative as Ap ((<*>), pure) import Control.DeepSeq (NFData, force) import Control.Monad (liftM, mapM_) import Data.List (foldl') import Haste.Foreign import Haste.Prim import Prelude hiding ((!), (++), concat, concatMap, drop, fmap, length) import qualified Prelude as P (fmap, return) import System.IO.Unsafe (unsafePerformIO) newtype JSArray a = JSArray JSAny deriving (Pack, Unpack) newJSArray::IO (JSArray a) newJSArray = ffi "(function() {return [];})" (++)::JSArray a->JSArray a->JSArray a (++) a b = unsafePerformIO $ plus a b where plus :: JSArray a->JSArray a->IO (JSArray a) plus = ffi "(function(a, b) {return a.concat(b);})" head::Pack a=>JSArray a->IO (Maybe a) head arr = do len <- length arr case len of 0 -> return Nothing _ -> Just <$> arr ! 0 last::Pack a=>JSArray a->IO (Maybe a) last arr = do len <- length arr case len of 0 -> return Nothing _ -> Just <$> arr ! (len - 1) tail::JSArray a->JSArray a tail = drop 1 init::JSArray a->JSArray a init = slice 0 (negate 1) null::JSArray a->IO Bool null = liftM (0==) . length length::JSArray a->IO Int length = ffi "(function(arr) {return arr.length;})" fmap::(Pack a, Unpack b, NFData a)=>(a->b)->JSArray a->JSArray b fmap f xs = fromList . P.fmap f . toList $ xs reverse::JSArray a->JSArray a reverse = unsafePerformIO . ffi "(function(arr) {var result = arr.slice();result.reverse();return result;})" foldl::(Pack a, Pack b, Unpack b)=>(b->a->b)->b->JSArray a->b foldl f x0 arr = unsafePerformIO $ foldl_ (\x y -> return $ f x y) x0 arr where foldl_::(Pack a, Pack b, Unpack b)=>(b->a->IO b)->b->JSArray a->IO b foldl_ = ffi "(function(f, x0, arr) {return arr.reduce(function(cumulant, cur) {return f(cumulant, cur);});})" concat::JSArray (JSArray a)->JSArray a concat = unsafePerformIO . ffi "(function(arrs) {return Array.prototype.concat.apply([], arrs);})" concat'::[JSArray a]->JSArray a concat' = foldl' (++) (unsafePerformIO newJSArray) concatMap::(Pack a, NFData a)=>(a->JSArray b)->JSArray a->JSArray b concatMap f = concat . fmap f concatMap'::(Pack a, Unpack b, NFData a)=>(a->[b])->JSArray a->JSArray b concatMap' f = concatMap (fromList . f) replicate::Unpack a=>Int->a->JSArray a replicate n x = unsafePerformIO $ replicate' n x where replicate'::Unpack a=>Int->a->IO (JSArray a) replicate' = ffi "(function(n, x) {var result = [];for(var i = 0;i < n; ++i) {result.push(x)};return result;})" slice::Int->Int->JSArray a->JSArray a slice begin end arr = unsafePerformIO $ slice' begin end arr where slice'::Int->Int->JSArray a->IO (JSArray a) slice' = ffi "(function(begin, end, arr) {return arr.slice(begin, end);})" take::Int->JSArray a->JSArray a take = slice 0 drop::Int->JSArray a->JSArray a drop n arr = slice n (unsafePerformIO $ length arr) arr push::Unpack a=>JSArray a->a->IO () push = ffi "(function(arr, val) {arr.push(val);})" pop::Pack a=>JSArray a->IO a pop = ffi "(function(arr) {return arr.pop();})" (!)::Pack a=>JSArray a->Int->IO a (!) = ffi "(function(arr, idx) {return arr[idx];})" zipWith::(Pack a, Pack b, Unpack c)=>(a->b->c)->JSArray a->JSArray b->JSArray c zipWith f xs ys = unsafePerformIO $ zipWith' (\x y -> return $ f x y) xs ys where zipWith'::(Pack a, Pack b, Unpack c)=>(a->b->IO c)->JSArray a->JSArray b->IO (JSArray c) zipWith' = ffi "(function(f, xs, ys) {var result = [];for (var i = 0;i < Math.min(xs.length, ys.length); ++i) {result.push(f(xs[i], ys[i]));};return result})" fromList::Unpack a=>[a]->JSArray a fromList vals = unsafePerformIO $ do arr <- newJSArray mapM_ (push arr) vals return arr toList::(Pack a, NFData a)=>JSArray a->[a] toList arr = force $ P.fmap (unsafePerformIO . (arr !)) [0..(unsafePerformIO . length $ arr) - 1]
klarh/haste-jsarray
src/Haste/JSArray.hs
mit
3,944
0
13
658
1,655
843
812
85
2
data Doggies a = Husky a | Mastiff a deriving (Eq, Show) data DogueDeBordeaux doge = DogueDeBordeaux doge -- 1 - Doggies is a type constructor -- 2 - :kind Doggies :: * -> * -- 3 - :kind Doggies String :: * -- 4 - :type Husky 10 :: Num a => Doggies a -- 5 - :type Husky (10 :: Integer) :: Doggies Integer -- 6 - :type Mastiff "Scooby Doo" :: Doggies String -- 7 - DogueDeBordeaux is a type constructor and a data constructor -- 8 - :type DogueDeBordeaux :: doge -> DogueDeBordeaux doge -- 9 - :type DogueDeBordeaux "doggie!" :: DogueDeBordeaux String
ashnikel/haskellbook
ch11/ch11.5_ex.hs
mit
564
0
6
120
46
30
16
6
0
{-# htermination delListFromFM :: Ord a => FiniteMap (Maybe a) b -> [(Maybe a)] -> FiniteMap (Maybe a) b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_delListFromFM_9.hs
mit
126
0
3
22
5
3
2
1
0
{-# LANGUAGE NoImplicitPrelude #-} module Prelude.Source.GHC.Num ( Num((+), (-), (*), negate, abs, signum, fromInteger), subtract, ) where import Prelude ( Num((+), (-), (*), negate, abs, signum, fromInteger), subtract, )
scott-fleischman/cafeteria-prelude
src/Prelude/Source/GHC/Num.hs
mit
244
0
6
51
74
63
11
10
0
-- Зачем это всё? -- {-# LANGUAGE MultiParamTypeClasses #-} -- {-# LANGUAGE FunctionalDependencies #-} -- {-# LANGUAGE FlexibleInstances #-} import Prelude hiding (lookup) import qualified Data.Map as M import qualified Data.List as L -- (5 баллов) -- 1. Определить класс MapLike типов, похожих на Map. -- В нем должны быть функции empty, lookup, insert, delete, fromList с типами как в Data.Map. -- Напишите реализацию по умолчанию для fromList. class MapLike m where empty :: m k v lookup :: Ord k => k -> m k v -> Maybe v insert :: Ord k => k -> v -> m k v -> m k v delete :: Ord k => k -> m k v -> m k v fromList :: Ord k => [(k, v)] -> m k v fromList [] = empty fromList ((k, v):xs) = insert k v (fromList xs) -- 2. Определить instance MapLike для Data.Map, ListMap и ArrMap -- Можно использовать любые стандартные функции. newtype ListMap k v = ListMap { toList :: [(k,v)] } newtype ArrMap k v = ArrMap (k -> Maybe v) instance MapLike M.Map where empty = M.empty lookup = M.lookup insert = M.insert delete = M.delete fromList = M.fromList instance MapLike ListMap where empty = ListMap [] lookup k (ListMap []) = Nothing lookup k (ListMap ((x, y):xs)) | x == k = Just y | otherwise = lookup k (ListMap xs) insert k v (ListMap []) = ListMap [(k, v)] insert k v (ListMap ((x, y):xs)) | x == k = ListMap ((k, v):xs) | otherwise = ListMap ((x, y):toList (insert k v (ListMap xs))) delete k (ListMap []) = ListMap [] delete k (ListMap ((x, y):xs)) | x == k = ListMap xs | otherwise = ListMap ((x, y):toList (delete k (ListMap xs))) fromList = ListMap instance MapLike ArrMap where empty = ArrMap (const Nothing) lookup k (ArrMap f) = f k insert k v (ArrMap f) = ArrMap (\x -> if x == k then Just v else f x) delete k (ArrMap f) = ArrMap (\x -> if x == k then Nothing else f x) -- 3. Написать instace Functor для ListMap k и ArrMap k. instance Functor (ArrMap k) where fmap f (ArrMap map_f) = ArrMap (\k -> fmap f (map_f k)) {- new_f f map_f k = case map_f k of -- Да это же fmap! Nothing -> Nothing Just v -> Just (f v) -} instance Functor (ListMap k) where fmap f (ListMap []) = empty fmap f (ListMap ((x, y):xs)) = ListMap ((x, f y):toList (fmap f (ListMap xs)))
SergeyKrivohatskiy/fp_haskell
hw07/MapLike.hs
mit
2,624
0
14
704
934
490
444
41
0
module GenCNF_Queen where import Data.List -- It generates CNF file which taken by zChaff tool. -- CNF file contains constraints for queen problem as clause norm form p2i (x, y) width = width * (x - 1) + y atLeastOneQueenInEachRow width = map (\clause -> intercalate " " $ map show $ map (\p -> p2i p width) clause) clauses where clauses = [clauses | n <- [1..width], clauses <- [[clause | clause <- zip (replicate width n) [1..width]]]] noMoreThanOneQueenInEachRow width = map (\(p1,p2) -> show (-1 * (p2i p1 width)) ++ " " ++ show (-1 * (p2i p2 width))) [((x,y1),(x,y2)) | y1<-[1..width], y2<-[y1+1..width], x <-[1..width], y1 /= y2] noMoreThanOneQueenInEachColumn width = map (\(p1,p2) -> show (-1 * (p2i p1 width)) ++ " " ++ show (-1 * (p2i p2 width))) [((x1,y),(x2,y)) | x1<-[1..width], x2<-[x1+1..width], y <-[1..width], x1 /= x2] -- (1,2) (2,1) == 2 5 noMoreThanOneQueenInDiagonal width = map (\(p1,p2) -> show (-1 * (p2i p1 width)) ++ " " ++ show (-1 * (p2i p2 width))) [((x1,y1),(x2,y2)) | x1 <- [1..width], y1 <- [1..width], n <- [-width+1..width-1], x2 <- [x1 + n, x1 - n], y2 <- [y1 + n, y1 - n], x1 /= x2, y1 /= y2, x2 >= 1 && x2 <= width, y2 >= 1 && y2 <= width] appendsZero:: String -> String appendsZero clause = clause ++ " 0"
zlqhem/course2013-ModelChecking
SAT_problem/GenCNF_Queen.hs
mit
1,456
0
16
439
711
384
327
24
1
module Chattp.PersistencePg.Config where import qualified Data.ByteString.Char8 as BS import System.Directory import System.Environment (getEnv) import System.IO.Error (catchIOError) import Database.PostgreSQL.Simple import Network.Socket defaultConnString :: String defaultConnString = "dbname='chattp' user='chattp' password='chattp_default'" getConnString :: IO String getConnString = catchIOError (getEnv "CHATTP_POSTGRES_CONNECTION") (const (return defaultConnString)) pgConnection :: IO Connection pgConnection = getConnString >>= connectPostgreSQL . BS.pack makePersistenceSocket :: IO Socket makePersistenceSocket = do raw_fam <- getEnv "CHATTP_PERSISTENCE_LAYER_FAMILY" raw_addr <- getEnv "CHATTP_PERSISTENCE_LAYER_ADDR" case raw_fam of "UNIX" -> do catchIOError (removeFile raw_addr) (const $ return ()) sock <- socket AF_UNIX Datagram defaultProtocol bind sock (SockAddrUnix raw_addr) return sock "INET" -> do raw_port <- getEnv "CHATTP_PERSISTENCE_LAYER_PORT" (ai:_) <- getAddrInfo (Just $ defaultHints { addrFamily = AF_UNSPEC, addrFlags = [AI_PASSIVE] }) (Just raw_addr) (Just raw_port) sock <- socket (addrFamily ai) Datagram defaultProtocol bind sock (addrAddress ai) return sock [] -> ioError $ userError "No address family has been provided." _ -> ioError $ userError "An invalid address family has been provided." makeBrokerSockAddr :: IO SockAddr makeBrokerSockAddr = do raw_fam <- getEnv "CHATTP_PERSISTENCE_LAYER_FAMILY" raw_addr <- getEnv "CHATTP_MSGBROKER_PERSISTENCE_BIND_ADDR" case raw_fam of "UNIX" -> return $ SockAddrUnix raw_addr "INET" -> do raw_port <- getEnv "CHATTP_MSGBROKER_PERSISTENCE_BIND_PORT" (ai:_) <- getAddrInfo (Just $ defaultHints { addrFamily = AF_UNSPEC }) (Just raw_addr) (Just raw_port) return (addrAddress ai) [] -> ioError $ userError "No address family has been provided" _ -> ioError $ userError "An invalid address family has been provided"
Spheniscida/cHaTTP
persistence-pg/Chattp/PersistencePg/Config.hs
mit
2,140
0
18
469
526
260
266
43
4
module Observable.Measure where import Control.Monad.Free (iterM) import Measurable.Core (Measure) import qualified Measurable.Measures as Measurable import Observable.Core -- | Forward-mode measure interpreter. Produces a measure over the model's -- predictive distribution, measure :: Model a -> Measure a measure = iterM alg where alg (BinomialF n p next) = Measurable.binomial n p >>= next alg (BetaF a b next) = Measurable.beta a b >>= next alg (GammaF a b next) = Measurable.gamma a b >>= next alg (StandardF next) = Measurable.standard >>= next alg (NormalF a b next) = Measurable.normal a b >>= next alg _ = error "measure: distribution not supported"
jtobin/observable
Observable/Measure.hs
mit
692
0
9
133
214
111
103
13
6
module Bonawitz_3_7 where import Blaze -- Replicating instance of Bonawitz 3.7 sr :: State sr = collectStates dummyState [sp, sa, sb, sx] sp :: State sp = mkDoubleParam "p" 0.3 sa :: State sa = mkDoubleParam "alpha" 9.5 sb :: State sb = mkDoubleParam "beta" 9.5 sx :: State sx = mkIntData 1 dr :: Density dr = productDensity [dbeta, dbin] dbeta :: Density dbeta = mkDensity [] [["p"]] [["alpha"], ["beta"]] beta dbin :: Density dbin = mkDensity [] [[""]] [["p"]] bernoulli main = print $ density sr dr
othercriteria/blaze
Bonawitz_3_7.hs
mit
523
0
7
110
198
113
85
19
1
module Euler.Roman ( roman, unroman ) where import Data.Word roman :: Word64 -> String roman 1000 = "M" roman 900 = "CM" roman 500 = "D" roman 400 = "CD" roman 100 = "C" roman 90 = "XC" roman 50 = "L" roman 40 = "XL" roman 10 = "X" roman 9 = "IX" roman 5 = "V" roman 4 = "IV" roman 1 = "I" roman x | x > 1000 = 'M' : roman (x - 1000) | x > 900 = 'C' : 'M' : roman (x - 900) | x > 500 = 'D' : roman (x - 500) | x > 400 = 'C' : 'M' : roman (x - 400) | x > 100 = 'C' : roman (x - 100) | x > 90 = 'C' : 'M' : roman (x - 90) | x > 50 = 'L' : roman (x - 50) | x > 40 = 'X' : 'L' : roman (x - 40) | x > 10 = 'X' : roman (x - 10) | x > 9 = 'I' : 'X' : roman (x - 9) | x > 5 = 'V' : roman (x - 5) | x > 4 = 'I' : 'V' : roman (x - 4) | otherwise = 'I' : roman (x - 1) unroman :: String -> Word64 unroman [] = 0 unroman ('M' : x) = 1000 + unroman x unroman ('C' : 'M' : x) = 900 + unroman x unroman ('D' : x) = 500 + unroman x unroman ('C' : 'D' : x) = 400 + unroman x unroman ('C' : x) = 100 + unroman x unroman ('X' : 'C' : x) = 90 + unroman x unroman ('L' : x) = 50 + unroman x unroman ('X' : 'L' : x) = 40 + unroman x unroman ('X' : x) = 10 + unroman x unroman ('I' : 'X' : x) = 9 + unroman x unroman ('V' : x) = 5 + unroman x unroman ('I' : 'V' : x) = 4 + unroman x unroman ('I' : x) = 1 + unroman x unroman _ = error "unroman: invalid numeral"
Undeterminant/euler-haskell
Euler/Roman.hs
cc0-1.0
1,521
2
9
548
850
421
429
47
1
import Control.Applicative import Data.Unfoldable import Data.Unfolder import Data.Maybe import System.Random data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) deriving Show instance Unfoldable Tree where unfold fa = choose [ pure Empty , Leaf <$> fa , Node <$> unfold fa <*> fa <*> unfold fa ] tree7 :: Tree Int tree7 = fromJust $ fromList [0..6] treeShapes :: [Tree ()] treeShapes = take 10 unfoldBF_ randomTree :: IO (Tree Bool) randomTree = getStdRandom randomDefault
technogeeky/centered
include/unfoldable-0.5.0/examples/tree.hs
gpl-3.0
507
0
11
110
186
98
88
17
1
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, GeneralizedNewtypeDeriving, FlexibleContexts, TypeFamilies,BangPatterns,MultiParamTypeClasses, StandaloneDeriving, NoMonomorphismRestriction, TemplateHaskell, ViewPatterns, FlexibleInstances #-} {-# OPTIONS -Wall -fno-warn-orphans #-} module Tetrahedron.Triangle( module Tetrahedron.Edge, -- * Plain Triangle, tBCD,tACD,tABD,tABC, allTriangles,allTriangles', -- ** Construction MakeTriangle(..), triangleByDualVertex, ascVerticesToTriangle, trianglesContainingVertex, trianglesContainingEdge, verticesToTriangle, triangleByVertices, joinVertexAndEdge, -- ** Properties verticesOfTriangle, edgesOfTriangle, oEdgesOfTriangle, edgeByOppositeVertexAndTriangle, vertexByOppositeEdge, triangleDualVertex, isVertexOfTriangle, isEdgeOfTriangle, triangleMemo, -- * Ordered OTriangle, -- ** Properties oTriangleDualVertex, -- ** Construction MakeOTriangle(..), oTriangleByVertices, verticesToOTriangle, allOTriangles, -- * Indexed ITriangle, -- ** Properties iTriangleDualVertex, iVerticesOfTriangle, -- ** Construction MakeITriangle(..), iTriangleByVertices, iVerticesToITriangle, iVerticesToTriangle, verticesToITriangle, iTriangleByDualVertex, joinIVertexAndEdge, joinIVertexAndIEdge, -- * Ordered and indexed OITriangle, -- ** Properties oiTriangleDualVertex, -- ** Construction MakeOITriangle(..), oiTriangleByVertices, verticesToOITriangle, iVerticesToOITriangle, -- * Misc triangleNu, oTriangleNu, ) where import Control.Applicative import Control.DeepSeq import Control.DeepSeq.TH import Control.Exception import Control.Monad import Data.Binary import Data.Binary.Derive import Data.Numbering import EitherC import Element import GHC.Generics(Generic) import HomogenousTuples import Language.Haskell.TH.Syntax as Syntax import Math.Groups.S3 import OrderableFace import PrettyUtil import Quote import ShortShow import Simplicial.DeltaSet3 import Test.QuickCheck import Tetrahedron.Edge import Util import Data.Typeable import FileLocation -- | Triangle of an abstract tetrahedron (vertices unordered) newtype Triangle = Triangle { triangleDualVertex :: Vertex } deriving (Eq,Binary,NFData,Typeable) triangleByDualVertex :: Vertex -> Triangle triangleByDualVertex = Triangle instance Show Triangle where show (verticesOfTriangle -> (v0,v1,v2)) = show v0 ++ show v1 ++ show v2 -- | By 'triangleDualVertex' (= descending lexicographic by 'verticesOfTriangle') deriving instance Ord Triangle -- | Must remain in @allTriangles'@-compatible order!! instance Enum Triangle where toEnum n = triangleByDualVertex (toEnum (3-n) :: Vertex) fromEnum t = 3 - fromEnum (triangleDualVertex t) -- | Must remain in @Enum Triangle@-compatible order!! allTriangles' :: (Triangle, Triangle, Triangle, Triangle) allTriangles' = ( tABC , tABD , tACD , tBCD ) instance Bounded Triangle where minBound = tABC maxBound = tBCD -- | Memoize a triangle-consuming function triangleMemo :: (Triangle -> c) -> Triangle -> c triangleMemo f = vertexMemo (f . Triangle) . triangleDualVertex -- | Vertices contained in a given triangle, ascending verticesOfTriangle :: Triangle -> (Triple Vertex) verticesOfTriangle = otherVertices . triangleDualVertex tABC, tABD, tACD, tBCD :: Triangle tABC = triangleByDualVertex vD tABD = triangleByDualVertex vC tACD = triangleByDualVertex vB tBCD = triangleByDualVertex vA allTriangles :: [Triangle] allTriangles = asList allTriangles' trianglePrettyColor :: Doc -> Doc trianglePrettyColor = cyan instance Pretty Triangle where pretty = trianglePrettyColor . text . show class MakeTriangle a where triangle :: a -> Triangle -- | The vertices must be strictly ascending ascVerticesToTriangle :: Asc3 Vertex -> Triangle ascVerticesToTriangle vs = triangleByDualVertex . unviewVertex $ case unAsc3 vs of (B,C,D) -> A (A,C,D) -> B (A,B,D) -> C (A,B,C) -> D _ -> error ("ascVerticesToTriangle "++show vs) -- | The vertices must be distinct (but needn't be ordered) verticesToTriangle :: (Triple Vertex) -> Triangle verticesToTriangle = ascVerticesToTriangle . $unEitherC "verticesToTriangle" . asc3total -- | = 'verticesToTriangle' triangleByVertices :: (Triple Vertex) -> Triangle triangleByVertices = verticesToTriangle -- | = 'verticesToTriangle' instance MakeTriangle (Triple Vertex) where triangle = verticesToTriangle -- | Construct a triangle containing the two edges instance MakeTriangle (Pair Edge) where triangle (e1,e2) = case intersectEdges (oppositeEdge e1) (oppositeEdge e2) of Just (Right v) -> triangleByDualVertex v _ -> error ("triangle "++show (e1,e2)) isVertexOfTriangle :: Vertex -> Triangle -> Bool isVertexOfTriangle v t = v /= triangleDualVertex t isEdgeOfTriangle :: Edge -> Triangle -> Bool isEdgeOfTriangle e t = isVertexOfEdge (triangleDualVertex t) (oppositeEdge e) instance Arbitrary Triangle where arbitrary = elements allTriangles instance Lift Triangle where lift (Triangle t) = [| triangleByDualVertex $(Syntax.lift t) |] instance Finite Triangle instance Quote Triangle where quotePrec _ t = "t" ++ show t -- | A 'Triangle' with a tetrahedron index attached to it data ITriangle = ITriangle {-# UNPACK #-} !TIndex !Triangle deriving (Eq,Ord,Generic,Typeable) instance Binary ITriangle where put = derivePut get = deriveGet instance HasTIndex ITriangle Triangle where viewI (ITriangle i x) = I i x (./) = ITriangle instance Enum ITriangle where toEnum (toEnum -> I i x) = (./) i x fromEnum = fromEnum . viewI instance Show ITriangle where show = show . viewI instance Quote ITriangle where quotePrec prec = quotePrec prec . viewI instance Pretty ITriangle where pretty = pretty . viewI instance ShortShow ITriangle where shortShow = shortShow . viewI -- | Triangle of an abstract tetrahedron, with ordered vertices data OTriangle = OTriangle !Triangle !S3 deriving(Eq,Ord,Generic,Typeable) instance Binary OTriangle where put = derivePut get = deriveGet class MakeOTriangle a where otriangle :: a -> OTriangle instance MakeOTriangle Triangle where otriangle = toOrderedFace instance MakeOTriangle (Triangle,S3) where otriangle = uncurry packOrderedFace instance Lift OTriangle where lift (OTriangle g x) = [| packOrderedFace $(Syntax.lift g) $(Syntax.lift x) |] -- | An 'OTriangle' with a tetrahedron index attached to it type OITriangle = I OTriangle trivialHasTIndexInstance [t|OTriangle|] trivialHasTIndexInstance [t|Pair OTriangle|] instance OrderableFace ITriangle OITriangle where type VertexSymGroup ITriangle = S3 unpackOrderedFace = defaultUnpackOrderedFaceI packOrderedFace = defaultPackOrderedFaceI instance RightAction S3 OITriangle where (*.) = defaultRightActionForOrderedFace instance OrderableFace Triangle OTriangle where type VertexSymGroup Triangle = S3 unpackOrderedFace (OTriangle x g) = (x,g) packOrderedFace = OTriangle instance RightAction S3 OTriangle where (*.) = defaultRightActionForOrderedFace -- | Ordered edges contained in a given triangle, in order instance Edges OTriangle where type Eds OTriangle = Triple OEdge edges = oEdgesOfTriangle instance MakeOTriangle (Triple Vertex) where otriangle = oTriangleByVertices -- | Inverse function to @vertices :: O (Triangle) -> Triple Vertex@ oTriangleByVertices :: (Triple Vertex) -> OTriangle oTriangleByVertices vs = case $(unEitherC) "oTriangleByVertices" (sort3WithPermutation' vs) of (vs',g) -> packOrderedFace (ascVerticesToTriangle vs') g trianglesContainingEdge :: Edge -> (Pair Triangle) trianglesContainingEdge e = -- generated from: \e -> fromList2 ( filter4 (e `isEdgeOfTriangle`) allTriangles' ) case vertices e of (A,B) -> (tABC,tABD) (A,C) -> (tABC,tACD) (A,D) -> (tABD,tACD) (B,C) -> (tABC,tBCD) (B,D) -> (tABD,tBCD) (C,D) -> (tACD,tBCD) _ -> $err' ("trianglesContainingEdge "++show e) gedgesOfTriangle :: (Vertices t, Verts t ~ Triple v) => ((v, v) -> e) -> t -> Triple e gedgesOfTriangle f t = map3 f ((v0,v1),(v1,v2),(v2,v0)) where (v0,v1,v2) = vertices t gedgesOfTriangle_lex :: (Vertices t, Verts t ~ Triple v) => ((v, v) -> e) -> t -> Triple e gedgesOfTriangle_lex f t = map3 f ((v0,v1),(v0,v2),(v1,v2)) where (v0,v1,v2) = vertices t -- | Edges contained in a given triangle edgesOfTriangle :: (Vertices t, Verts t ~ Triple v, MakeEdge (v, v)) => t -> Triple Edge edgesOfTriangle = gedgesOfTriangle_lex edge -- | Ordered edges contained in a given triangle (result is a cycle) oEdgesOfTriangle :: (Vertices t, Verts t ~ Triple Vertex) => t -> Triple OEdge oEdgesOfTriangle = gedgesOfTriangle verticesToOEdge -- | = 'edgesOfTriangle' instance Edges Triangle where type Eds Triangle = Triple Edge edges = edgesOfTriangle instance SatisfiesSimplicialIdentities2 Triangle -- | = 'verticesOfTriangle' instance Vertices Triangle where type Verts Triangle = Triple Vertex vertices = verticesOfTriangle -- | Vertices contained in a given ordered facet (in order) -- -- > vertices (OTriangle g x) = g .* vertices x instance Vertices OTriangle where type Verts OTriangle = Triple Vertex vertices = defaultVerticesForOrderedFace instance Show OTriangle where show = vertexTripleToString . vertices instance Arbitrary OTriangle where arbitrary = liftM2 packOrderedFace arbitrary arbitrary instance Pretty OTriangle where pretty = abstractTetrahedronColor . text . show instance Enum OTriangle where toEnum n = case toEnum n of EnumPair a b -> OTriangle a b fromEnum (OTriangle a b) = fromEnum (EnumPair a b) instance Bounded OTriangle where minBound = OTriangle minBound minBound maxBound = OTriangle maxBound maxBound iVerticesOfTriangle :: (Vertices a, Verts a ~ Triple b, HasTIndex ia a, HasTIndex ib b) => ia -> Triple ib iVerticesOfTriangle = traverseI map3 vertices instance Finite OTriangle -- | = 'iVerticesOfTriangle' instance Vertices ITriangle where type Verts ITriangle = Triple IVertex vertices = iVerticesOfTriangle -- | = 'iVerticesOfTriangle' instance Vertices OITriangle where type Verts OITriangle = Triple IVertex vertices = iVerticesOfTriangle instance Edges OITriangle where type Eds OITriangle = Triple OIEdge edges (viewI -> I i t) = map3 (i ./) (edges t) instance Edges ITriangle where type Eds ITriangle = Triple IEdge edges (viewI -> I i t) = map3 (i ./) (edges t) instance SatisfiesSimplicialIdentities2 ITriangle -- | Triangles containing a given vertex trianglesContainingVertex :: Vertex -> Triple Triangle trianglesContainingVertex = map3 triangleByDualVertex . otherVertices -- | Gets the edge which is contained in the given triangle and does /not/ contain the given vertex. -- -- The vertex must be contained in the triangle. -- -- Example: @edgeByOppositeVertexAndTriangle 'B' 'ABD' = 'AD'@ edgeByOppositeVertexAndTriangle :: Vertex -> Triangle -> Edge edgeByOppositeVertexAndTriangle v t = case filter3 (\e -> not (isVertexOfEdge v e)) (edges t) of [e0] -> e0 _ -> error ("edgeByOppositeVertexAndTriangle is not defined for args "++show v++", "++show t) -- | = 'edgeByOppositeVertexAndTriangle' instance Link Vertex Triangle Edge where link = edgeByOppositeVertexAndTriangle -- | 'getTIndex's must be equal instance Link IVertex ITriangle IEdge where link (viewI -> I i v) (viewI -> I i' t) = assert (i==i') (i ./ link v t) vertexByOppositeEdge :: (Show a, Vertices a, Verts a ~ Triple Vertex) => Edge -> a -> Vertex vertexByOppositeEdge e t = case filter3 (\v -> not (isVertexOfEdge v e)) (vertices t) of [v0] -> v0 _ -> error ("vertexByOppositeEdge is not defined for args "++show e++", "++show t) -- | = 'vertexByOppositeEdge' instance Link Edge Triangle Vertex where link = vertexByOppositeEdge -- | 'getTIndex's must be equal instance Link IEdge ITriangle IVertex where link = withTIndexEqualC link instance Triangles TIndex where type Tris TIndex = Quadruple ITriangle triangles z = map4 (z ./) allTriangles' instance SatisfiesSimplicialIdentities3 TIndex instance OEdges OTriangle where type OEds OTriangle = Triple OEdge oedges (vertices -> (v0,v1,v2)) = (oedge (v0,v1), oedge (v1,v2), oedge(v2,v0)) -- | 'getTIndex's must be equal oiTriangleByVertices :: Triple IVertex -> OITriangle oiTriangleByVertices (map3 viewI -> (I i0 v0, I i1 v1, I i2 v2)) = assert (i1 == i0) $ assert (i2 == i0) $ i0 ./ otriangle (v0,v1,v2) instance Arbitrary ITriangle where arbitrary = (./) <$> arbitrary <*> arbitrary instance Quote OTriangle where quotePrec _ ot = "o"++show ot oTriangleDualVertex :: OTriangle -> Vertex oTriangleDualVertex = triangleDualVertex . forgetVertexOrder iTriangleDualVertex :: ITriangle -> IVertex iTriangleDualVertex = mapI triangleDualVertex oiTriangleDualVertex :: I OTriangle -> IVertex oiTriangleDualVertex = mapI oTriangleDualVertex iTriangleByDualVertex :: IVertex -> ITriangle iTriangleByDualVertex = mapI triangleByDualVertex instance Star Vertex (OneSkeleton Triangle) (Pair Edge) where star v (OneSkeleton t) = case link v t of (vertices -> (v0,v1)) -> (edge (v,v0), edge (v,v1)) -- | 'getTIndex's must be equal instance Star IVertex (OneSkeleton ITriangle) (Pair IEdge) where star (viewI -> I i v) (OneSkeleton (viewI -> I i' t)) = assert (i==i') (map2 (i ./) (star v (OneSkeleton t))) instance ShortShow Triangle where shortShow = show instance ShortShow OTriangle where shortShow = show -- | 'getTIndex's must be equal iTriangleByVertices :: Triple IVertex -> ITriangle iTriangleByVertices = forgetVertexOrder . oiTriangleByVertices -- | = 'triangleDualVertex' instance Dual Triangle Vertex where dual = triangleDualVertex -- | = 'triangleDualVertex' instance Dual Vertex Triangle where dual = triangleByDualVertex allOTriangles :: [OTriangle] allOTriangles = [minBound..maxBound] joinVertexAndEdge :: (Vertices edge, Verts edge ~ (Pair Vertex)) => Vertex -> edge -> Triangle joinVertexAndEdge v0 (vertices -> (v1,v2)) = verticesToTriangle (v0,v1,v2) joinIVertexAndEdge :: (Vertices edge, Verts edge ~ (Pair Vertex)) => IVertex -> edge -> ITriangle joinIVertexAndEdge = traverseI (.) joinVertexAndEdge -- | 'getTIndex's must be equal joinIVertexAndIEdge :: (Vertices edge, HasTIndex iedge edge, Verts edge ~ (Pair Vertex)) => IVertex -> iedge -> ITriangle joinIVertexAndIEdge = withTIndexEqualC joinVertexAndEdge -- | = 'iTriangleByVertices' iVerticesToITriangle :: Triple IVertex -> ITriangle iVerticesToITriangle = iTriangleByVertices -- | = 'iTriangleByVertices' iVerticesToTriangle :: Triple IVertex -> ITriangle iVerticesToTriangle = iTriangleByVertices -- | = 'iTriangleByVertices' verticesToITriangle :: Triple IVertex -> ITriangle verticesToITriangle = iTriangleByVertices -- | = 'oTriangleByVertices' verticesToOTriangle :: Triple Vertex -> OTriangle verticesToOTriangle = oTriangleByVertices -- | = 'oiTriangleByVertices' verticesToOITriangle :: Triple IVertex -> OITriangle verticesToOITriangle = oiTriangleByVertices -- | = 'oiTriangleByVertices' iVerticesToOITriangle :: Triple IVertex -> OITriangle iVerticesToOITriangle = oiTriangleByVertices class MakeITriangle a where iTriangle :: a -> ITriangle -- | = 'iTriangleByVertices' instance MakeITriangle (Triple IVertex) where iTriangle = iTriangleByVertices -- | = 'forgetVertexOrder' instance MakeITriangle (OITriangle) where iTriangle = forgetVertexOrder class MakeOITriangle a where oiTriangle :: a -> OITriangle -- | = 'oiTriangleByVertices' instance MakeOITriangle (Triple IVertex) where oiTriangle = oiTriangleByVertices -- | @uncurry 'packOrderedFace'@ instance MakeOITriangle (ITriangle,S3) where oiTriangle = uncurry packOrderedFace triangleNu :: Numbering Triangle triangleNu = finiteTypeNu oTriangleNu :: Numbering OTriangle oTriangleNu = finiteTypeNu instance Lift ITriangle where lift (viewI -> I x y) = [| x ./ y |] mapTIndicesFromHasTIndex [t|ITriangle|] deriveNFData ''ITriangle deriveNFData ''OTriangle instance SimplicialTriangle Triangle where sTriangleAscTotal = return . ascVerticesToTriangle sTriangleVerts = asc3 . vertices -- could skip check instance SimplicialTriangle ITriangle where sTriangleAscTotal = return . iTriangleByVertices . unAsc3 sTriangleVerts = asc3 . vertices -- could skip check instance Show a => Show (Triangle -> a) where show = showFiniteFunc "t" instance Show a => Show (OTriangle -> a) where show = showFiniteFunc "t" instance QuoteConstPat Triangle where quoteConstPat (triangleDualVertex -> v) = quoteConstPat v quoteConstPat_view _ x = "triangleDualVertex " ++ x
DanielSchuessler/hstri
Tetrahedron/Triangle.hs
gpl-3.0
17,303
0
13
3,310
4,340
2,352
1,988
373
7
module CppWriter ( render ) where import ModuleParser (DataType(..), Param(..), ModuleDef(..)) import ListManip (strToLower, allButLast) import Control.Monad.Writer (Writer, execWriter, tell) import Control.Monad (mapM_, liftM) type StringWriter = Writer String () -- | Wrap the Writer monad render :: [ModuleDef] -> (String, String) render moduleDef = (,) "Main.cc" $ (execWriter . renderCpp) moduleDef renderCpp :: [ModuleDef] -> StringWriter renderCpp (ModuleDecl moduleName:moduleBody) = do mapM_ renderInclude [moduleName ++ ".hh" , "ErlComm.hh" , "ei.h" , "erl_interface.h" , "cstring" , "cassert"] tell "\n" renderBufSize renderPrologue mapM_ renderMsgReception moduleBody renderEpilogue renderInclude :: String -> StringWriter renderInclude i = tell $ "#include <" ++ i ++ ">\n" renderBufSize :: StringWriter renderBufSize = tell "static const int BufSize = 1024;\n\n" renderPrologue :: StringWriter renderPrologue = do tell "// Communication between Erlang and this program is through\n" tell "// stdin and stdout. If tracing is needed from this program it\n" tell "// must be written to stderr or a separate file.\n" tell "int main() {\n" tell " erl_init(NULL, 0);\n" tell " ErlComm::Byte buf[BufSize];\n" tell " // Receive loop of messages from Erlang\n" tell " while (ErlComm::receive(buf) > 0) {\n\n" tell " // Decode the message tuple\n" tell " ETERM *tuple = erl_decode(buf);\n" tell " assert(ERL_IS_TUPLE(tuple));\n\n" tell " // Pick the first element of the tuple - the function to execute\n" tell " ETERM *func = erl_element(1, tuple);\n" tell " assert(ERL_IS_ATOM(func));\n\n" tell " " renderMsgReception :: ModuleDef -> StringWriter renderMsgReception moduleDef = let f = funcName moduleDef -- f will be lower case as = drop 1 $ allButLast $ params moduleDef rt = returnType moduleDef in do tell $ "if (ErlComm::atomEqualsTo(func, \"" ++ f ++ "\")) {\n" renderMsgComment moduleDef maybeRenderObjPtrAssignment moduleDef maybeRenderReturnValueAssignment rt renderCallSite moduleDef renderFormalArguments as renderReturnMessage rt tell " } else " renderMsgComment :: ModuleDef -> StringWriter renderMsgComment def = tell $ " // " ++ show def ++ "\n" maybeRenderObjPtrAssignment :: ModuleDef -> StringWriter maybeRenderObjPtrAssignment (MethodDecl _ ps) = let t = ps !! 0 s = typeAsStr t in tell $ " " ++ s ++ "obj = ErlComm::ptrFromIntegral<" ++ s ++ ">(erl_element(2, tuple));\n" maybeRenderObjPtrAssignment _ = return () maybeRenderReturnValueAssignment :: Param -> StringWriter maybeRenderReturnValueAssignment (Value Void) = tell " " maybeRenderReturnValueAssignment p = tell $ " " ++ typeAsStr p ++ " ret = " renderCallSite :: ModuleDef -> StringWriter renderCallSite (StaticDecl m f _) = tell $ m ++ "::" ++ f renderCallSite (MethodDecl f _) = tell $ "obj->" ++ f renderFormalArguments :: [Param] -> StringWriter renderFormalArguments [] = tell "();\n" renderFormalArguments [a] = tell $ "(" ++ depictArgument 3 a ++ ");\n" renderFormalArguments (a:as) = tell $ "(" ++ (snd $ foldl appendArgument (4, depictArgument 3 a) as) ++ ");\n" where appendArgument (n, s) p = (n+1, s ++ ", " ++ depictArgument n p) depictArgument :: Int -> Param -> String depictArgument n t@(Ptr _) = "ErlComm::ptrFromIntegral<" ++ typeAsStr t ++ ">(erl_element(" ++ show n ++ ", tuple))" depictArgument n (Value String) = "ErlComm::fromBinary(erl_element(" ++ show n ++ ", tuple))" depictArgument _ _ = error "Cannot handle this type" renderReturnMessage :: Param -> StringWriter renderReturnMessage (Value Void) = do tell " ETERM *ok = erl_mk_atom(\"ok\");\n" renderReturnMessageEpilogue "ok" renderReturnMessage (Value Integer) = do tell " ETERM *anInt = erl_mk_int(ret);\n" renderReturnMessageEpilogue "anInt" renderReturnMessage (Value _) = error "Cannot handle this type" renderReturnMessage (Ptr _) = do tell " ETERM *ptr =\n" tell " erl_mk_ulonglong(reinterpret_cast<unsigned long long>(ret));\n" renderReturnMessageEpilogue "ptr" renderReturnMessageEpilogue :: String -> StringWriter renderReturnMessageEpilogue t = do tell $ " erl_encode(" ++ t ++ ", buf);\n" tell $ " ErlComm::send(buf, erl_term_len(" ++ t ++ "));\n" tell $ " erl_free_term(" ++ t ++ ");\n" renderEpilogue :: StringWriter renderEpilogue = do tell " {\n" -- This parentesis just will follow an if {} else tell " // Unknown message\n" tell " assert(false);\n" tell " }\n\n" tell " erl_free_compound(tuple);\n" tell " erl_free_term(func);\n" tell " }\n" tell " return 0;\n" tell "}\n" funcName :: ModuleDef -> String funcName (MethodDecl funcName _) = strToLower funcName funcName (StaticDecl _ funcName _) = strToLower funcName params :: ModuleDef -> [Param] params (MethodDecl _ p) = p params (StaticDecl _ _ p) = p returnType :: ModuleDef -> Param returnType (MethodDecl _ p) = last p returnType (StaticDecl _ _ p) = last p typeAsStr :: Param -> String typeAsStr (Value t) = case t of Integer -> "int" String -> "std::string" Void -> "void" UserDef u -> u typeAsStr (Ptr t) = case t of Integer -> "int *" String -> "char *" Void -> "void *" UserDef u -> u ++ " *"
SneakingCat/proper-play-gen
src/CppWriter.hs
gpl-3.0
5,644
0
11
1,350
1,426
692
734
140
7
module TCPPingServer ( runServer ) where import Network.Socket import Control.Exception import Control.Concurrent runServer :: IO () runServer = do sock <- socket AF_INET Stream 0 setSocketOption sock ReuseAddr 1 bindSocket sock $ SockAddrInet 4242 iNADDR_ANY listen sock 2 serverLoop sock serverLoop :: Socket -> IO () serverLoop sock = do conn <- accept sock forkIO $ serve conn serverLoop sock serve :: (Socket, SockAddr) -> IO () serve (sock, addr) = do req <- try $ recv sock 1024 :: IO (Either IOException String) case req of Left ex -> do putStrLn "connection closed" sClose sock Right req -> do if req == "ping!" then do putStrLn req send sock "pong!" else return 0 serve (sock, addr)
ConnorDillon/haskell-experiments
TCPPingServer.hs
gpl-3.0
871
0
15
295
285
133
152
31
3