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 CommandsSpec (spec) where
import Test.Hspec
import Commands (parse, Command(..))
import LambdaWithSynonyms
spec :: SpecWith ()
spec = describe "Commands" $
describe "parse" $ do
it "should parse :help to Help" $ do
parse ":help" `shouldBe` Right Help
parse ":help " `shouldBe` Right Help
parse " :help" `shouldBe` Right Help
it "should parse :step expr to step" $ do
parse ":step (\\x.x)" `shouldBe` Right (Step (L' 'x' (V' 'x')))
parse ":step (\\x.x)" `shouldBe` Right (Step (L' 'x' (V' 'x')))
parse " :step (\\x.x) " `shouldBe` Right (Step (L' 'x' (V' 'x')))
it "should parse :steps expr to steps" $ do
parse ":steps (\\x.x)" `shouldBe` Right (Steps (L' 'x' (V' 'x')))
parse ":steps (\\x.x)" `shouldBe` Right (Steps (L' 'x' (V' 'x')))
parse " :steps (\\x.x) " `shouldBe` Right (Steps (L' 'x' (V' 'x')))
it "should parse :quit to quit" $ do
parse ":quit" `shouldBe` Right Quit
parse " :quit " `shouldBe` Right Quit
it "should parse :let to be a let" $
parse ":let I (\\x.x)" `shouldBe` Right (Let 'I' (L' 'x' (V' 'x')))
it "should parse :synonyms to be a synonyms" $
parse ":synonyms" `shouldBe` Right ShowSynonyms
it "should parse expr to expr" $ do
parse "(\\x.x)" `shouldBe` Right (Eval (L' 'x' (V' 'x')))
parse " (\\x.x)" `shouldBe` Right (Eval (L' 'x' (V' 'x')))
parse "(\\x.x) " `shouldBe` Right (Eval (L' 'x' (V' 'x')))
it "should parse unrecognised" $ do
parse ":foobar" `shouldBe` Right (Unrecognised ":foobar")
parse ":stepss" `shouldBe` Right (Unrecognised ":stepss")
| hughfdjackson/abattoir | test/CommandsSpec.hs | mit | 1,658 | 0 | 18 | 413 | 619 | 298 | 321 | 33 | 1 |
module IRC.Commands where
import Control.Monad.Reader (asks)
import Data (Bot, BotState(..))
import Net (write)
import IRC.Parser (Message(..), Sender(nick))
import Config (Config(..))
privmsg :: String -> String -> Bot ()
privmsg to text = write $ "PRIVMSG " ++ to ++ " :" ++ text
respond' :: Message -> String -> Config -> (String, String)
respond' m reply cfg = (sendTo, text)
where
senderNick = (IRC.Parser.nick (sender m))
sendTo = if location m == (Config.nick cfg)
then senderNick
else location m
text = if location m == (Config.nick cfg)
then reply
else senderNick ++ ": " ++ reply
respond :: Message -> String -> Bot ()
respond m r = do
cfg <- asks config
uncurry privmsg $ respond' m r cfg
respondMany :: Message -> [String] -> Bot ()
respondMany _ [] = return ()
respondMany m xs = respond m x >> respondMany m xs'
where
x = head xs
xs' = take 4 $ tail xs
| jdiez17/HaskellHawk | IRC/Commands.hs | mit | 993 | 0 | 11 | 283 | 389 | 207 | 182 | 26 | 3 |
module QCheckSpec where
import SpecHelper
-- import Test.Hspec
-- import Test.QuickCheck
-- `main` is here so that this module can be run from GHCi on its own. It is
-- not needed for automatic spec discovery.
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "read" $ do
it "is inverse to show" $ property $
\x -> (read . show) x == (x :: Int)
| akimichi/haskell-labo | test/QCheckSpec.hs | mit | 386 | 0 | 15 | 99 | 88 | 48 | 40 | 9 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Generics.K
-- Copyright : (c) David Lazar, 2011
-- License : MIT
--
-- Maintainer : lazar6@illinois.edu
-- Stability : experimental
-- Portability : unknown
--
-- Convert K terms to and from 'Data' values.
-----------------------------------------------------------------------------
module Data.Generics.K
( toK
, fromK
) where
import Data.Generics.K.ToK (toK)
import Data.Generics.K.FromK (fromK)
| davidlazar/generic-k | src/Data/Generics/K.hs | mit | 533 | 0 | 5 | 90 | 51 | 38 | 13 | 5 | 0 |
module Import (
module Import
) where
import Happstack.Server as Import (toResponse, ok)
import Web.Routes as Import (showURL)
import Web.Routes.Happstack as Import ()
import Template as Import (layout)
import Sitemap as Import
| akru/happsite | Import.hs | mit | 323 | 0 | 5 | 127 | 63 | 44 | 19 | 7 | 0 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Provides some quasiquoters that mimic Ruby's percent-letter syntax.
module RubyQQ (
-- * Shell exec
x, xx
-- * Splitting on whitespace
, w, ww
-- * Strings
, q, qq
-- * Regular expressions
, r, ri, rx, rix, (=~)
) where
import Control.Applicative
import Control.Monad
import Data.ByteString.Char8 (ByteString, pack)
import Data.Char
import Data.Function
import Data.Monoid
import Language.Haskell.Exts (parseExp, ParseResult(..))
import Language.Haskell.Meta hiding (parseExp)
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import System.Process
import System.IO
import Prelude hiding (lex)
import Text.ParserCombinators.ReadP (readP_to_S)
import Text.Read.Lex
import Text.Regex.PCRE.Light
import Text.Trifecta
class Stringable a where asString :: a -> String
class Stringable' flag a where asString' :: flag -> a -> String
instance (StringPred flag a, Stringable' flag a) => Stringable a where
asString = asString' (undefined :: flag)
class StringPred flag a | a -> flag where {}
instance StringPred HString String
instance (flag ~ HShowable) => StringPred flag a
instance Stringable' HString String where asString' _ = id
instance Show a => Stringable' HShowable a where asString' _ = show
data HString
data HShowable
expQuoter :: (String -> Q Exp) -> QuasiQuoter
expQuoter lam = QuasiQuoter
lam
(error "this quoter cannot be used in pattern context")
(error "this quoter cannot be used in type context")
(error "this quoter cannot be used in declaration context")
-- | @[x|script|]@ executes @script@ and returns @(stdout,stderr)@. It has type @'IO' ('String','String')@.
--
-- >>> [x|ls -a | wc -l|]
-- (" 8\n","")
--
-- >>> [x|echo >&2 "Hello, world!"|]
-- ("","Hello, world!\n")
x :: QuasiQuoter
x = expQuoter $
\str -> [|do
(_, Just h, Just he, _) <- createProcess (shell $(stringE str))
{ std_out = CreatePipe, std_err = CreatePipe }
(liftM2 (,) `on` hGetContents) h he|]
-- | @[xx|script|]@ spawns a shell process running @script@ and returns
-- @(hndl_stdin, hndl_stdout, hndl_stderr)@. It has type @'IO'
-- ('Handle','Handle','Handle')@.
--
-- >>> [xx|ls|]
-- ({handle: fd:8},{handle: fd:9},{handle: fd:11})
xx :: QuasiQuoter
xx = expQuoter $
\str -> [|do
(Just hi, Just h, Just he, _) <- createProcess (shell $(stringE str))
{ std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }
return (hi, h, he)|]
-- | @[w|input|]@ is a list containing @input@ split on all whitespace
-- characters.
--
-- Note that no escape expansion occurs:
--
-- >>> [w|hello\n world!|]
-- ["hello\\n","world!"]
w :: QuasiQuoter
w = expQuoter $
\str -> case parseString safeWords mempty (' ':str) of
Success strs -> listE $ map stringE strs
n -> error $ show n
-- | @[ww|input|]@ is a list containing @input@ split on all whitespace
-- characters, with some extra features:
--
-- * Ruby-style interpolation is supported.
--
-- >>> [ww|foo bar #{ reverse "zab" }|]
-- ["foo","bar","baz"]
--
-- /This feature uses some typeclass magic to convert input into the/
-- /friendliest possible String format. If you encounter errors like "No/
-- /instance for (Stringable' flag [a0])", add a type signature to your/
-- /input./
--
-- * All escape sequences are interpreted.
--
-- >>> [ww|Here\n are\SOH some\x123 special\1132 characters\\!|]
-- ["Here\n","are\SOH","some\291","special\1132","characters\\!"]
ww :: QuasiQuoter
ww = expQuoter $
\str -> case parseString interpWords mempty (' ':str) of
Success strs -> listE strs
Failure n -> error $ show n
-- | @[q|input|]@ is @input@. This quoter is essentially the identity
-- function. It is however a handy shortcut for multiline strings.
q :: QuasiQuoter
q = expQuoter stringE
-- | @[qq|input|]@ is @input@, with interpolation and escape sequences
-- expanded.
--
-- >>> let name = "Brian" in [qq|Hello, #{name}!|]
-- "Hello, Brian!"
qq :: QuasiQuoter
qq = expQuoter interpStr'
-- | @[r|pat|]@ is a regular expression defined by @pat@.
r :: QuasiQuoter
r = expQuoter $ \s -> [|compile (pack $(stringE s)) []|]
-- | @[ri|pat|]@ is @[r|pat|]@, but is case-insensitive.
ri :: QuasiQuoter
ri = expQuoter $ \s -> [|compile (pack $(stringE s)) [caseless]|]
-- | @[rx|pat|]@ is @[r|pat|]@, but ignores whitespace and comments in the
-- regex body.
rx :: QuasiQuoter
rx = expQuoter $ \s -> [|compile (pack $(stringE s)) [extended]|]
-- | @[rix|pat|]@ is a combination of @ri@ and @rx@.
rix :: QuasiQuoter
rix = expQuoter $ \s -> [|compile (pack $(stringE s)) [extended, caseless]|]
-- | @(=~)@ is an infix synonym for 'Text.Regex.PCRE.Light.match', with no
-- exec options provided.
--
-- >>> (pack "foobar") =~ [r|((.)\2)b|]
-- Just ["oob", "oo", "o"]
(=~) :: ByteString -> Regex -> Maybe [ByteString]
s =~ re = Text.Regex.PCRE.Light.match re s []
safeWords :: Parser [String]
safeWords = filter (not . null) <$> many1 (many1 (satisfy isSpace) *> word) where
word = many $ try ('\\' <$ string "\\\\")
<|> try (char '\\' *> satisfy isSpace)
<|> satisfy (not . isSpace)
interpWords :: Parser [Q Exp]
interpWords = many1 (many1 (satisfy isSpace) *> (try (fst <$> expq) <|> word)) where
word = fmap (stringE . unString . concat) $
many $ try (string "\\\\")
<|> try (char '\\' *> string "#")
<|> try (fmap return $ char '\\' *> satisfy isSpace)
<|> fmap return (satisfy (not . isSpace))
interpStr' :: String -> Q Exp
interpStr' m = [|concat $(listE (go [] m)) :: String|] where
go n [] = [stringE n]
go acc y@('#':'{':_) = case parseString expq mempty y of
Success (qqq,s) -> stringE acc:qqq:go [] s
Failure _ -> error "failure"
go acc ('\\':'#':xs) = go (acc ++ "#") xs
go acc s = case readLitChar s of
[(y,xs)] -> go (acc ++ [y]) xs
_ -> error $ "could not read character literal in " ++ s
interpStr :: Parser [Q Exp]
interpStr = many1 (try (fst <$> expq) <|> word) where
word = stringE <$> many1 (notChar '\\')
expq :: Parser (Q Exp, String)
expq = do
_ <- string "#{"
ex <- expBody ""
_ <- char '}'
m <- many anyChar
return (ex, m)
where
expBody s = do
till <- many (notChar '}')
let conc = s ++ till
case parseExp conc of
ParseOk e -> let m = return $ toExp e in return [e|asString $(m)|]
_ -> char '}' *> expBody (conc ++ "}")
unString :: String -> String
unString s' = case readP_to_S lex $ '"' : concatMap escape s' ++ "\"" of
[(String str,"")] -> str
_ -> error $ "Invalid string literal \"" ++ s' ++ "\" (possibly a bad escape sequence)"
where escape '"' = "\\\""
escape m' = [m']
many1 :: Alternative f => f a -> f [a]
many1 f = liftA2 (:) f (many f)
| pikajude/ruby-qq | src/RubyQQ.hs | mit | 7,327 | 0 | 17 | 1,712 | 1,677 | 918 | 759 | -1 | -1 |
{-# LANGUAGE
UndecidableInstances, OverlappingInstances #-}
module GUI (
MonadGUI(..),
Output(..) )
where
import ClassyPrelude hiding (getLine)
import Control.Monad.Trans
import Control.Monad.Base
class Monad m => MonadGUI m where
getLine :: Text → m Text
getLine' :: Text → m (Maybe Text)
setPrompt :: Text → m ()
output :: Output → m ()
setTitle :: Text → m ()
setInput :: (Text, Text) → m ()
finishGUI :: m ()
instance (MonadTrans t, Monad (t m), MonadGUI m) =>
MonadGUI (t m) where
getLine x = lift $ getLine x
getLine' x = lift $ getLine' x
setPrompt x = lift $ setPrompt x
output x = lift $ output x
setTitle x = lift $ setTitle x
setInput x = lift $ setInput x
finishGUI = lift $ finishGUI
instance (MonadBase b m, MonadGUI b) =>
MonadGUI m where
getLine x = liftBase $ getLine x
getLine' x = liftBase $ getLine' x
setPrompt x = liftBase $ setPrompt x
output x = liftBase $ output x
setTitle x = liftBase $ setTitle x
setInput x = liftBase $ setInput x
finishGUI = liftBase $ finishGUI
data Output =
OutText Text |
OutMany [Output] |
Info Output |
NumberedList [Output]
| aelve/Jane | GUI.hs | mit | 1,283 | 0 | 10 | 394 | 454 | 234 | 220 | -1 | -1 |
--
-- Copyright (c) 2012 Citrix Systems, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE PatternGuards #-}
module Vm.Templates
( exportTemplate
, getNewVmTemplate
, getServiceVmTemplate
, getChildServiceVmTemplate
, getAnyVmTemplate
, nullTemplate
, templateFromString
, enumTemplateTags
, enumUiTemplates
, enumServiceVmTags
, enumChildServiceVmTags
, getUuidInTemplate
, getSlotInTemplate
, applyChildTemplateToVm
, mergeTemplates
) where
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.List
import Data.String
import System.IO
import System.FilePath
import Tools.JSONTrees
import Tools.Misc
import Tools.File
import Tools.Log
import Tools.Text
import Vm.Types
import XenMgr.Db
import XenMgr.Config
import XenMgr.Rpc
import Paths_xenmgr
data ConfigTemplate = ConfigTemplate JSValue
ndvmDefaultMode = "hvm"
getNdvmMode :: Rpc String
getNdvmMode =
do mode <- dbReadWithDefault ndvmDefaultMode "/xenmgr/ndvm-mode"
return $ mode
readJSONFile :: FilePath -> IO JSValue
readJSONFile path = do
contents <- readFile path
case decodeStrict $ contents of
Error msg -> error $ "malformed JSON file: " ++ msg
Ok json -> return json
getTemplateDir :: IO FilePath
getTemplateDir =
do flavour <- appGetPlatformFlavour
getDataFileName ("templates" </> flavour)
getTemplateFile :: String -> IO FilePath
getTemplateFile name =
do dir <- getTemplateDir
return $ dir </> name
getNewVmTemplate :: IO ConfigTemplate
getNewVmTemplate = getAnyVmTemplate "new-vm"
getServiceVmTemplate :: String -> IO ConfigTemplate
getServiceVmTemplate tag = getAnyVmTemplate ("service-" ++ tag)
getChildServiceVmTemplate :: String -> IO ConfigTemplate
getChildServiceVmTemplate tag = getAnyVmTemplate ("child-" ++ tag)
getAnyVmTemplate :: String -> IO ConfigTemplate
getAnyVmTemplate tag =
do fname <- getTemplateFile tag
ConfigTemplate <$> readJSONFile fname
nullTemplate :: ConfigTemplate
nullTemplate = ConfigTemplate . JSObject . toJSObject $ []
templateFromString :: String -> ConfigTemplate
templateFromString s = case strip s of
"" -> nullTemplate
s -> case decode s of
Error msg -> error $ "malformed JSON: " ++ msg
Ok json -> ConfigTemplate json
enumTemplateTags :: IO [String]
enumTemplateTags =
do template_dir <- getTemplateDir
tags <- catMaybes . map get_tag <$> filesInDir template_dir
return $ tags
where
get_tag f = case takeBaseName f of
's':'e':'r':'v':'i':'c':'e':'-':tag -> Nothing
tag -> Just tag
-- UI selectable templates
enumUiTemplates :: IO [(String, String)]
enumUiTemplates = do
tags <- enumTemplateTags
templates <- zip tags <$> mapM getAnyVmTemplate tags
return $ map mk $ filter isUI templates
where
isUI (tag, template) = getStringInTemplate template "/ui-selectable" == Just "true"
mk (tag, template) = (tag, descr) where
descr = case getStringInTemplate template "/description" of
Nothing -> ""
Just d -> d
enumServiceVmTags :: Rpc [String]
enumServiceVmTags =
do tags <- catMaybes . map get_tag <$> template_files
ndvm_mode <- getNdvmMode
info $ "ndvm mode " ++ ndvm_mode ++ " tags: " ++ ( intercalate " " tags )
return $ filter ( filt_ndvm ndvm_mode ) tags
where
template_files = liftIO $ do template_dir <- getTemplateDir
filesInDir template_dir
get_tag f = case takeBaseName f of
's':'e':'r':'v':'i':'c':'e':'-':tag -> Just tag
_ -> Nothing
filt_ndvm ndvm_mode f = case f of
'n':'d':'v':'m':'-':mode -> mode == ndvm_mode
_ -> True
enumChildServiceVmTags :: IO [String]
enumChildServiceVmTags =
do template_dir <- getTemplateDir
tags <- catMaybes . map get_tag <$> filesInDir template_dir
return $ tags
where
get_tag f = case takeBaseName f of
'c':'h':'i':'l':'d':'-':tag -> Just tag
_ -> Nothing
data StoredKey = StoredKey String String
--
-- Write a configuration template to database
--
exportTemplate :: MonadRpc e m => Maybe Uuid -> ConfigTemplate -> m Uuid
exportTemplate maybe_uuid (ConfigTemplate json_) =
let uuid = case maybe_uuid of
Just uuid -> uuid
Nothing -> case jsGet "/uuid" json_ of
Just s -> fromString . jsUnboxString $ s
Nothing -> error "uuid required, but template does not specify uuid"
json = jsSet "/uuid" (jsBoxString . show $ uuid) json_
in do csums <- get_disk_csums uuid
let json' = foldr set json csums
set (StoredKey k v) j = jsSet k (jsBoxString v) j
str = encode json'
dbInject (vmDbPath uuid) str
return uuid
where
get_disk_csums uuid = do
paths <- map (\p -> "/config/disk/" ++ p ++ "/sha1sum") <$> dbList disk_path
values <- mapM (\p -> dbMaybeRead (vmDbPath uuid ++ "/" ++ p)) paths
return $ foldr conv [] $ zip paths values
where
disk_path = vmDbPath uuid ++ "/config/disk"
conv (_, Nothing) acc = acc
conv (p, Just v ) acc = StoredKey p v : acc
-- overrides the parent configuration with data found in
-- override section within template
applyChildTemplateToVm :: MonadRpc e m => (ConfigTemplate,Uuid) -> Uuid -> m Bool
applyChildTemplateToVm (ConfigTemplate t, child_uuid) vm_uuid =
case jsGet "/parent-override" t of
Nothing -> return True -- no override sect
Just ov ->
let ov_t = substituteVars
(ConfigTemplate ov)
(SubstVars { subParentUuid = vm_uuid
, subUuid = child_uuid } )
in
templatedModifyVm (\vm_t -> mergeTemplates vm_t ov_t) vm_uuid
-- merge two templates (values in template 2 take precedence)
mergeTemplates :: ConfigTemplate -> ConfigTemplate -> ConfigTemplate
mergeTemplates (ConfigTemplate a) (ConfigTemplate b)
= ConfigTemplate (merge a b)
where
-- (o1 - o2) + (o2 - o1) + (o2 x o1) where 'x' - intersection retaining first operand values
merge (JSObject a) (JSObject b) = merge_objs a b
merge _ x = x
merge_objs a b =
let tuples_a = fromJSObject a
tuples_b = fromJSObject b in
JSObject $ toJSObject $
(tuples_a `minusT` tuples_b) `plusT`
(tuples_b `minusT` tuples_a) `plusT`
(tuples_a `intersectT` tuples_b)
plusT = (++)
a `minusT` b = filter (not . contained_in b) a
a `intersectT` b = foldr f [] a where
f (k, v) xs
| Just (_,v') <- find ((== k). fst) b = (k, merge v v') : xs
| otherwise = xs
contained_in b x = fst x `elem` map fst b
-- map f x over atomic values in template
mapTemplate :: (JSValue -> JSValue) -> ConfigTemplate -> ConfigTemplate
mapTemplate f (ConfigTemplate t) = ConfigTemplate (aux t) where
aux (JSArray xs) = JSArray $ map aux xs
aux (JSObject o) = JSObject . toJSObject $ map g (fromJSObject o) where g (name,v) = (name, aux v)
aux other = f other
data SubstVars = SubstVars { subParentUuid :: Uuid
, subUuid :: Uuid }
substituteVars :: ConfigTemplate -> SubstVars -> ConfigTemplate
substituteVars t sv =
mapTemplate f t where
f (JSString s) = JSString . toJSString $
"${PARENT_UUID}" `replace` (show $ subParentUuid sv) $
"${UUID}" `replace` (show $ subUuid sv) $
fromJSString s
f x = x
readVmAsTemplate :: MonadRpc e m => Uuid -> m (Maybe ConfigTemplate)
readVmAsTemplate uuid =
fmap ConfigTemplate <$> dbDump (vmDbPath uuid)
templatedModifyVm :: MonadRpc e m => (ConfigTemplate -> ConfigTemplate) -> Uuid -> m Bool
templatedModifyVm f uuid =
do modified <- fmap f <$> readVmAsTemplate uuid
case modified of
Nothing -> return False
Just t -> exportTemplate (Just uuid) t >> return True
getUuidInTemplate :: ConfigTemplate -> Maybe Uuid
getUuidInTemplate (ConfigTemplate json) =
case jsGet "/uuid" json of
Just s -> Just . fromString . jsUnboxString $ s
Nothing -> Nothing
getSlotInTemplate :: ConfigTemplate -> Maybe Int
getSlotInTemplate t = join . fmap maybeRead $ (getStringInTemplate t "/slot")
getStringInTemplate :: ConfigTemplate -> String -> Maybe String
getStringInTemplate (ConfigTemplate json) path =
case jsGet path json of
Just s -> Just . jsUnboxString $ s
Nothing-> Nothing
-- A path to database from given VM
vmDbPath :: Uuid -> String
vmDbPath uuid = "/vm/" ++ show uuid
| OpenXT/manager | xenmgr/Vm/Templates.hs | gpl-2.0 | 9,647 | 0 | 17 | 2,642 | 2,604 | 1,314 | 1,290 | 201 | 4 |
module Shared.Drawing (
withBlankScreen
) where
import qualified Graphics.UI.SDL as SDL
import Control.Monad
withBlankScreen :: SDL.Renderer -> IO a -> IO ()
withBlankScreen renderer operation = do
clearScreen renderer
_ <- operation
drawToScreen renderer
clearScreen :: SDL.Renderer -> IO ()
clearScreen renderer = do
_ <- SDL.setRenderDrawColor renderer 0xFF 0xFF 0xFF 0xFF
_ <- SDL.renderClear renderer
return ()
drawToScreen :: SDL.Renderer -> IO ()
drawToScreen renderer = void $ SDL.renderPresent renderer
| ShigekiKarita/haskellSDL2Examples | src/Shared/Drawing.hs | gpl-2.0 | 546 | 0 | 9 | 105 | 174 | 85 | 89 | 16 | 1 |
module Fixer.VMap(
VMap(),
Proxy(..),
vmapSingleton,
vmapArgSingleton,
vmapArg,
vmapValue,
vmapMember,
vmapProxyIndirect,
vmapPlaceholder,
vmapDropArgs,
vmapHeads
)where
import Data.Monoid(Monoid(..))
import Data.Typeable
import List(intersperse)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Doc.DocLike
import Fixer.Fixer
import GenUtil
-- | General data type for finding the fixpoint of a general tree-like structure.
data VMap p n = VMap {
vmapArgs :: Map.Map (n,Int) (VMap p n),
vmapNodes :: Either (Proxy p) (Set.Set n)
}
deriving(Typeable)
data Proxy p = Proxy p | DepthExceeded
deriving(Eq,Ord,Typeable)
instance Show p => Show (Proxy p) where
showsPrec n (Proxy p) = showsPrec n p
showsPrec n DepthExceeded = ('*':)
emptyVMap :: (Ord p, Ord n) => VMap p n
emptyVMap = VMap { vmapArgs = mempty, vmapNodes = Right mempty }
vmapSingleton :: (Ord p, Ord n) => n -> VMap p n
vmapSingleton n = emptyVMap { vmapNodes = Right $ Set.singleton n }
vmapArgSingleton :: (Ord p,Ord n,Show p,Show n) => n -> Int -> VMap p n -> VMap p n
vmapArgSingleton n i v
| isBottom v = emptyVMap
| otherwise = pruneVMap $ emptyVMap { vmapArgs = Map.singleton (n,i) v }
vmapArg :: (Ord p,Ord n,Show p,Show n) => n -> Int -> VMap p n -> VMap p n
vmapArg n i vm@VMap { vmapArgs = map } = case Map.lookup (n,i) map of
Just x -> x `lub` vmapProxyIndirect i vm
Nothing -> vmapProxyIndirect i vm
vmapProxyIndirect :: (Show p,Show n,Ord p,Ord n,Fixable (VMap p n)) => Int -> VMap p n -> VMap p n
vmapProxyIndirect _ VMap { vmapNodes = Left l } = emptyVMap { vmapNodes = Left l }
vmapProxyIndirect _ _ = emptyVMap
vmapValue :: (Show p,Show n,Ord p,Ord n) => n -> [VMap p n] -> VMap p n
vmapValue n xs = pruneVMap VMap { vmapArgs = Map.fromAscList (zip (zip (repeat n) [0..]) xs), vmapNodes = Right $ Set.singleton n }
vmapPlaceholder :: (Show p,Show n,Ord p,Ord n) => p -> VMap p n
vmapPlaceholder p = emptyVMap { vmapNodes = Left (Proxy p) }
vmapDropArgs :: Ord n => VMap p n -> VMap p n
vmapDropArgs vm = vm { vmapArgs = mempty }
vmapHeads :: Monad m => VMap p n -> m [n]
vmapHeads VMap { vmapNodes = Left _ } = fail "vmapHeads: VMap is unknown"
vmapHeads VMap { vmapNodes = Right set } = return $ Set.toList set
vmapMember :: Ord n => n -> VMap p n -> Bool
vmapMember n VMap { vmapNodes = Left _ } = True
vmapMember n VMap { vmapNodes = Right set } = n `Set.member` set
pruneVMap :: (Ord n,Ord p,Show n,Show p) => VMap p n -> VMap p n
pruneVMap vmap = f (7::Int) vmap where
f 0 _ = emptyVMap { vmapNodes = Left DepthExceeded }
f _ VMap { vmapNodes = Left p} = emptyVMap {vmapNodes = Left p}
f n VMap { vmapArgs = map, vmapNodes = set} = VMap {vmapArgs = map', vmapNodes = set} where
map' = Map.filter g (Map.map (f (n - 1)) map)
g vs = not $ isBottom vs
instance (Ord p,Ord n,Show p,Show n) => Show (VMap p n) where
showsPrec n VMap { vmapNodes = Left p } = showsPrec n p
showsPrec _ VMap { vmapArgs = n, vmapNodes = Right s } = braces (hcat (intersperse (char ',') $ (map f $ snub $ (fsts $ Map.keys n) ++ Set.toList s) )) where
f a = (if a `Set.member` s then tshow a else char '#' <> tshow a) <> (if null (g a) then empty else tshow (g a))
g a = sortUnder fst [ (i,v) | ((a',i),v) <- Map.toList n, a' == a ]
instance (Show p,Show n,Ord p,Ord n) => Fixable (VMap p n) where
bottom = emptyVMap
isBottom VMap { vmapArgs = m, vmapNodes = Right s } = Map.null m && Set.null s
isBottom _ = False
lub x y | x `lte` y = y
lub x y | y `lte` x = x
lub VMap { vmapNodes = Left p } _ = emptyVMap { vmapNodes = Left p }
lub _ VMap { vmapNodes = Left p } = emptyVMap { vmapNodes = Left p }
lub VMap { vmapArgs = as, vmapNodes = Right ns } VMap { vmapArgs = as', vmapNodes = Right ns'} = pruneVMap $ VMap {vmapArgs = Map.unionWith lub as as', vmapNodes = Right $ Set.union ns ns' }
minus _ VMap { vmapNodes = Left _ } = bottom
minus x@VMap { vmapNodes = Left _ } _ = x
minus VMap { vmapArgs = n1, vmapNodes = Right w1} VMap { vmapArgs = n2, vmapNodes = Right w2 } = pruneVMap $ VMap { vmapArgs = Map.fromAscList $ [
case Map.lookup (a,i) n2 of
Just v' -> ((a,i),v `minus` v')
Nothing -> ((a,i),v)
| ((a,i),v) <- Map.toAscList n1 ], vmapNodes = Right (w1 Set.\\ w2) }
lte _ VMap { vmapNodes = Left _ } = True
lte VMap { vmapNodes = Left _ } _ = False
lte x@VMap { vmapArgs = as, vmapNodes = Right ns } y@VMap { vmapArgs = as', vmapNodes = Right ns'} = (Set.null (ns Set.\\ ns') && (Map.null $ Map.differenceWith (\a b -> if a `lte` b then Nothing else Just undefined) as as'))
showFixable x = show x
instance (Show p,Show n,Ord p,Ord n) => Monoid (VMap p n) where
mempty = bottom
mappend = lub
| dec9ue/jhc_copygc | src/Fixer/VMap.hs | gpl-2.0 | 4,880 | 0 | 17 | 1,210 | 2,320 | 1,222 | 1,098 | -1 | -1 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bits
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- This module defines bitwise operations for signed and unsigned
-- integers. Instances of the class 'Bits' for the 'Int' and
-- 'Integer' types are available from this module, and instances for
-- explicitly sized integral types are available from the
-- "Data.Int" and "Data.Word" modules.
--
-----------------------------------------------------------------------------
module Data.Bits (
Bits(
(.&.), (.|.), xor, -- :: a -> a -> a
complement, -- :: a -> a
shift, -- :: a -> Int -> a
rotate, -- :: a -> Int -> a
bit, -- :: Int -> a
setBit, -- :: a -> Int -> a
clearBit, -- :: a -> Int -> a
complementBit, -- :: a -> Int -> a
testBit, -- :: a -> Int -> Bool
bitSize, -- :: a -> Int
isSigned, -- :: a -> Bool
shiftL, shiftR, -- :: a -> Int -> a
rotateL, rotateR -- :: a -> Int -> a
)
-- instance Bits Int
-- instance Bits Integer
) where
-- Defines the @Bits@ class containing bit-based operations.
-- See library document for details on the semantics of the
-- individual operations.
import Hugs.Bits
infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR`
infixl 7 .&.
infixl 6 `xor`
infixl 5 .|.
{-|
The 'Bits' class defines bitwise operations over integral types.
* Bits are numbered from 0 with bit 0 being the least
significant bit.
Minimal complete definition: '.&.', '.|.', 'xor', 'complement',
('shift' or ('shiftL' and 'shiftR')), ('rotate' or ('rotateL' and 'rotateR')),
'bitSize' and 'isSigned'.
-}
class Num a => Bits a where
-- | Bitwise \"and\"
(.&.) :: a -> a -> a
-- | Bitwise \"or\"
(.|.) :: a -> a -> a
-- | Bitwise \"xor\"
xor :: a -> a -> a
{-| Reverse all the bits in the argument -}
complement :: a -> a
{-| Shift the argument left by the specified number of bits.
Right shifts (signed) are specified by giving a negative value.
An instance can define either this unified 'shift' or 'shiftL' and
'shiftR', depending on which is more convenient for the type in
question. -}
shift :: a -> Int -> a
x `shift` i | i<0 = x `shiftR` (-i)
| i==0 = x
| i>0 = x `shiftL` i
{-| Rotate the argument left by the specified number of bits.
Right rotates are specified by giving a negative value.
For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'.
An instance can define either this unified 'rotate' or 'rotateL' and
'rotateR', depending on which is more convenient for the type in
question. -}
rotate :: a -> Int -> a
x `rotate` i | i<0 = x `rotateR` (-i)
| i==0 = x
| i>0 = x `rotateL` i
{-
-- Rotation can be implemented in terms of two shifts, but care is
-- needed for negative values. This suggested implementation assumes
-- 2's-complement arithmetic. It is commented out because it would
-- require an extra context (Ord a) on the signature of 'rotate'.
x `rotate` i | i<0 && isSigned x && x<0
= let left = i+bitSize x in
((x `shift` i) .&. complement ((-1) `shift` left))
.|. (x `shift` left)
| i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x))
| i==0 = x
| i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x))
-}
-- | @bit i@ is a value with the @i@th bit set
bit :: Int -> a
-- | @x \`setBit\` i@ is the same as @x .|. bit i@
setBit :: a -> Int -> a
-- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@
clearBit :: a -> Int -> a
-- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@
complementBit :: a -> Int -> a
-- | Return 'True' if the @n@th bit of the argument is 1
testBit :: a -> Int -> Bool
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. The function 'bitSize' is
undefined for types that do not have a fixed bitsize, like 'Integer'.
-}
bitSize :: a -> Int
{-| Return 'True' if the argument is a signed type. The actual
value of the argument is ignored -}
isSigned :: a -> Bool
bit i = 1 `shiftL` i
x `setBit` i = x .|. bit i
x `clearBit` i = x .&. complement (bit i)
x `complementBit` i = x `xor` bit i
x `testBit` i = (x .&. bit i) /= 0
{-| Shift the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'shiftR' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftL :: a -> Int -> a
x `shiftL` i = x `shift` i
{-| Shift the argument right (signed) by the specified number of bits
(which must be non-negative).
An instance can define either this and 'shiftL' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftR :: a -> Int -> a
x `shiftR` i = x `shift` (-i)
{-| Rotate the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateR' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateL :: a -> Int -> a
x `rotateL` i = x `rotate` i
{-| Rotate the argument right by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateL' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateR :: a -> Int -> a
x `rotateR` i = x `rotate` (-i)
instance Bits Int where
(.&.) = primAndInt
(.|.) = primOrInt
xor = primXorInt
complement = primComplementInt
shift = primShiftInt
bit = primBitInt
testBit = primTestInt
bitSize _ = 4*8
x `rotate` i
| i<0 && x<0 = let left = i+bitSize x in
((x `shift` i) .&. complement ((-1) `shift` left))
.|. (x `shift` left)
| i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x))
| i==0 = x
| i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x))
isSigned _ = True
instance Bits Integer where
-- reduce bitwise binary operations to special cases we can handle
x .&. y | x<0 && y<0 = complement (complement x `posOr` complement y)
| otherwise = x `posAnd` y
x .|. y | x<0 || y<0 = complement (complement x `posAnd` complement y)
| otherwise = x `posOr` y
x `xor` y | x<0 && y<0 = complement x `posXOr` complement y
| x<0 = complement (complement x `posXOr` y)
| y<0 = complement (x `posXOr` complement y)
| otherwise = x `posXOr` y
-- assuming infinite 2's-complement arithmetic
complement a = -1 - a
shift x i | i >= 0 = x * 2^i
| otherwise = x `div` 2^(-i)
rotate x i = shift x i -- since an Integer never wraps around
bitSize _ = error "Data.Bits.bitSize(Integer)"
isSigned _ = True
-- Crude implementation of bitwise operations on Integers: convert them
-- to finite lists of Ints (least significant first), zip and convert
-- back again.
-- posAnd requires at least one argument non-negative
-- posOr and posXOr require both arguments non-negative
posAnd, posOr, posXOr :: Integer -> Integer -> Integer
posAnd x y = fromInts $ zipWith (.&.) (toInts x) (toInts y)
posOr x y = fromInts $ longZipWith (.|.) (toInts x) (toInts y)
posXOr x y = fromInts $ longZipWith xor (toInts x) (toInts y)
longZipWith :: (a -> a -> a) -> [a] -> [a] -> [a]
longZipWith f xs [] = xs
longZipWith f [] ys = ys
longZipWith f (x:xs) (y:ys) = f x y:longZipWith f xs ys
toInts :: Integer -> [Int]
toInts n
| n == 0 = []
| otherwise = mkInt (n `mod` numInts):toInts (n `div` numInts)
where mkInt n | n > toInteger(maxBound::Int) = fromInteger (n-numInts)
| otherwise = fromInteger n
fromInts :: [Int] -> Integer
fromInts = foldr catInt 0
where catInt d n = (if d<0 then n+1 else n)*numInts + toInteger d
numInts = toInteger (maxBound::Int) - toInteger (minBound::Int) + 1
| kaoskorobase/mescaline | resources/hugs/packages/base/Data/Bits.hs | gpl-3.0 | 11,877 | 11 | 17 | 5,702 | 1,628 | 942 | 686 | 107 | 2 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module BioInf.RNAdesign.CandidateChain where
import Control.Arrow (first)
import Control.Monad (foldM)
import Control.Monad.Primitive
import Control.Monad.Primitive.Class
import Data.Function (on)
import qualified Data.Vector as V
import qualified Data.Vector.Fusion.Stream.Monadic as SM
import qualified Data.Vector.Unboxed as VU
import System.Random.MWC.Monad
import Biobase.Primary
import Biobase.Secondary.Diagrams
import Biobase.Vienna
import BioInf.RNAdesign.Assignment (Assignment(..))
-- | A single candidate, with its sequence and the score, this sequence
-- receives. Candidates are ordered by their scores.
data Candidate = Candidate
{ candidate :: Primary
, score :: Score
} deriving (Eq,Show)
instance Ord Candidate where
(<=) = (<=) `on` score
-- | The likelihood score we get.
--
-- TODO replace Score Likelihood / LogLikelihood (once we switch to the more
-- generic MCMC library)
newtype Score = Score { unScore :: Double }
deriving (Eq,Ord,Show,Read)
-- | This structure defines a "design problem"
data DesignProblem = DesignProblem
{ structures :: [D1Secondary]
, assignments :: [Assignment]
} deriving (Eq,Read,Show)
-- | Create an initial, legal, candidate.
mkInitial :: (MonadPrim m, PrimMonad m) => (Primary -> Score) -> Int -> DesignProblem -> Rand m Candidate
mkInitial scoring l dp = do
let z = VU.replicate l nA
foldM (mutateOneAssignmentWith scoring (\_ _ -> return True)) (Candidate z (scoring z)) $ assignments dp
-- | Create a stream of 'Candidate's from an initial candidate.
unfoldStream
:: forall m . (MonadPrim m, PrimMonad m)
=> Int -> Int -> Int -> (Primary -> Score) -> (Candidate -> Candidate -> Rand m Bool) -> DesignProblem -> Candidate
-> SM.Stream (Rand m) Candidate
unfoldStream burnin number thin score f dp = go where
go s = SM.map snd -- remove remaining indices from stream
. SM.take number -- take the number of sequences we want
. SM.filter ((==0) . flip mod thin . fst) -- keep only every thin'th sequence
. SM.indexed -- add index
. SM.drop burnin -- drop the burnin sequences
. SM.drop 1 -- drop original input
. SM.scanlM' (mutateOneAssignmentWith score f) s -- starting with 's', mutate s further and further using cycled assignments
$ SM.unfoldr (Just . first head . splitAt 1)
(cycle $ assignments dp) -- create inifinite cycled assignments
-- | Mutate the current (or "old") sequence under the possible 'assignment's as
-- prescribed by 'Assignment'. The modifying assignment is selected uniformly.
-- The monadic @old -> new -> Rand m Bool@ function chooses between the old and
-- the new candidate. It can be used to, e.g., allow always choosing "new" if
-- it is better, but choosing "new" as well if some stochastic value (hence
-- dependence on @Rand m@) indicates so.
mutateOneAssignmentWith
:: (MonadPrim m, PrimMonad m)
=> (Primary -> Score) -- ^ the likelihood function, gives a sequence a score
-> (Candidate -> Candidate -> Rand m Bool) -- ^ choose between old and new sequence (monadic, stochastic)
-> Candidate -- ^ "old" / current sequence
-> Assignment -- ^ possible assignments for the sequence
-> Rand m Candidate -- ^ the "new" sequence
mutateOneAssignmentWith score f old Assignment{..} = do
i <- uniformR (0,V.length assignment -1) -- inclusive range for Int
let cs = VU.zip columns (assignment V.! i)
let nw = VU.update (candidate old) cs
let new = Candidate nw (score nw)
b <- f old new
return $ if b then new else old
| choener/RNAdesign | BioInf/RNAdesign/CandidateChain.hs | gpl-3.0 | 4,062 | 0 | 17 | 1,111 | 843 | 467 | 376 | 61 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators #-}
-- | This module exposes a low-level Servant-built API for the LXD daemon.
--
-- You can query this API using Servant functions and a client created
-- from "Network.LXD.Client".
--
-- You probably want to use the commands exposed in
-- "Network.LXD.Client.Commands" instead.
module Network.LXD.Client.API (
-- * API
FailureResponse(..)
-- ** Information
, supportedVersions
, apiConfig
, trustedCertificates
-- ** Containers
-- *** Querying informaiton
, containerNames
, containerCreate
, container
, containerDelete
-- *** Configuration
, containerPut
, containerPatch
, containerRename
-- *** State
, containerState
, containerPutState
-- *** Executing commands
, containerExecImmediate
, containerExecWebsocketInteractive
, containerExecWebsocketNonInteractive
-- *** Working with files
, WriteMode(..)
, containerGetPath
, containerPostPath
, containerDeletePath
-- ** Images
, imageIds
, imageCreate
, imageAliases
, imageAlias
, image
, imageDelete
-- ** Networks
, networkList
, networkCreate
, network
, networkPut
, networkPatch
, networkDelete
-- ** Profiles
, profileList
, profileCreate
, profile
, profilePut
, profilePatch
, profileDelete
-- ** Storage
, poolList
, poolCreate
, pool
, poolPut
, poolPatch
, poolDelete
-- * Volumes
, volumeList
, volumeCreate
, volume
, volumePut
, volumePatch
, volumeDelete
-- ** Operations
, operationIds
, operation
, operationCancel
, operationWait
, operationWebSocket
-- ** WebSocket communciations
, readAllWebSocket
, writeAllWebSocket
-- * Helpers
, ExecClient
) where
import Network.LXD.Client.Internal.Prelude
import Control.Concurrent (MVar, takeMVar)
import Control.Exception (Exception, catch, throwIO)
import Control.Monad.Reader (asks)
import Data.Aeson (FromJSON, Value, eitherDecode)
import Data.ByteString.Lazy (ByteString, toStrict)
import Data.List (find)
import Data.Maybe (catMaybes)
import Data.Proxy
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as Char8
import qualified Network.HTTP.Client as Client
import qualified Network.HTTP.Types.Header as HTTP
import qualified Network.HTTP.Types.Status as HTTP
import qualified Network.WebSockets as WS
import Servant.API
#if MIN_VERSION_servant(0, 12, 0)
import Servant.Client hiding (Response, FailureResponse)
#else
import Servant.Client hiding (FailureResponse)
#endif
import Web.HttpApiData (FromHttpApiData, ToHttpApiData, toHeader, parseHeader)
import Network.LXD.Client.Types
import Network.LXD.Client.Internal.Compatibility (compat)
import qualified Network.LXD.Client.Internal.Compatibility.WebSockets as WSC
type API = Get '[JSON] (Response [ApiVersion])
:<|> "1.0" :> Get '[JSON] (Response ApiConfig)
:<|> "1.0" :> "certificates" :> Get '[JSON] (Response [CertificateHash])
:<|> "1.0" :> "containers" :> Get '[JSON] (Response [ContainerName])
:<|> "1.0" :> "containers" :> ReqBody '[JSON] ContainerCreateRequest :> Post '[JSON] (AsyncResponse Value)
:<|> "1.0" :> "containers" :> Capture "name" ContainerName :> Get '[JSON] (Response Container)
:<|> "1.0" :> "containers" :> Capture "name" ContainerName :> ReqBody '[JSON] ContainerDeleteRequest :> Delete '[JSON] (AsyncResponse Value)
:<|> "1.0" :> "containers" :> Capture "name" ContainerName :> ReqBody '[JSON] ContainerPut :> Put '[JSON] (AsyncResponse Value)
:<|> "1.0" :> "containers" :> Capture "name" ContainerName :> ReqBody '[JSON] ContainerPatch :> Patch '[JSON] (Response Value)
:<|> "1.0" :> "containers" :> Capture "name" ContainerName :> ReqBody '[JSON] ContainerRename :> Post '[JSON] (AsyncResponse Value)
:<|> "1.0" :> "containers" :> Capture "name" ContainerName :> "state" :> Get '[JSON] (Response ContainerState)
:<|> "1.0" :> "containers" :> Capture "name" ContainerName :> "state" :> ReqBody '[JSON] ContainerPutState :> Put '[JSON] (AsyncResponse Value)
:<|> ExecAPI 'ExecImmediate
:<|> ExecAPI 'ExecWebsocketInteractive
:<|> ExecAPI 'ExecWebsocketNonInteractive
:<|> "1.0" :> "images" :> Get '[JSON] (Response [ImageId])
:<|> "1.0" :> "images" :> ReqBody '[JSON] ImageCreateRequest :> Post '[JSON] (AsyncResponse Value)
:<|> "1.0" :> "images" :> "aliases" :> Get '[JSON] (Response [ImageAliasName])
:<|> "1.0" :> "images" :> "aliases" :> Capture "name" ImageAliasName :> Get '[JSON] (Response ImageAlias)
:<|> "1.0" :> "images" :> Capture "id" ImageId :> Get '[JSON] (Response Image)
:<|> "1.0" :> "images" :> Capture "id" ImageId :> ReqBody '[JSON] ImageDeleteRequest :> Delete '[JSON] (AsyncResponse Value)
:<|> "1.0" :> "networks" :> Get '[JSON] (Response [NetworkName])
:<|> "1.0" :> "networks" :> ReqBody '[JSON] NetworkCreateRequest :> Post '[JSON] (Response Value)
:<|> "1.0" :> "networks" :> Capture "name" NetworkName :> Get '[JSON] (Response Network)
:<|> "1.0" :> "networks" :> Capture "name" NetworkName :> ReqBody '[JSON] NetworkConfigRequest :> Put '[JSON] (Response Value)
:<|> "1.0" :> "networks" :> Capture "name" NetworkName :> ReqBody '[JSON] NetworkConfigRequest :> Patch '[JSON] (Response Value)
:<|> "1.0" :> "networks" :> Capture "name" NetworkName :> Delete '[JSON] (Response Value)
:<|> "1.0" :> "profiles" :> Get '[JSON] (Response [ProfileName])
:<|> "1.0" :> "profiles" :> ReqBody '[JSON] ProfileCreateRequest :> Post '[JSON] (Response Value)
:<|> "1.0" :> "profiles" :> Capture "name" ProfileName :> Get '[JSON] (Response Profile)
:<|> "1.0" :> "profiles" :> Capture "name" ProfileName :> ReqBody '[JSON] ProfileConfigRequest :> Put '[JSON] (Response Value)
:<|> "1.0" :> "profiles" :> Capture "name" ProfileName :> ReqBody '[JSON] ProfileConfigRequest :> Patch '[JSON] (Response Value)
:<|> "1.0" :> "profiles" :> Capture "name" ProfileName :> Delete '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Get '[JSON] (Response [PoolName])
:<|> "1.0" :> "storage-pools" :> ReqBody '[JSON] PoolCreateRequest :> Post '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Capture "name" PoolName :> Get '[JSON] (Response Pool)
:<|> "1.0" :> "storage-pools" :> Capture "name" PoolName :> ReqBody '[JSON] PoolConfigRequest :> Put '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Capture "name" PoolName :> ReqBody '[JSON] PoolConfigRequest :> Patch '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Capture "name" PoolName :> Delete '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Capture "pool" PoolName :> "volumes" :> Get '[JSON] (Response [VolumeName])
:<|> "1.0" :> "storage-pools" :> Capture "pool" PoolName :> "volumes" :> ReqBody '[JSON] VolumeCreateRequest :> Post '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Capture "pool" PoolName :> "volumes" :> Capture "type" VolumeType :> Capture "volume" VolumeName :> Get '[JSON] (Response Volume)
:<|> "1.0" :> "storage-pools" :> Capture "pool" PoolName :> "volumes" :> Capture "type" VolumeType :> Capture "volume" VolumeName :> ReqBody '[JSON] VolumeConfigRequest :> Put '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Capture "pool" PoolName :> "volumes" :> Capture "type" VolumeType :> Capture "volume" VolumeName :> ReqBody '[JSON] VolumeConfigRequest :> Patch '[JSON] (Response Value)
:<|> "1.0" :> "storage-pools" :> Capture "pool" PoolName :> "volumes" :> Capture "type" VolumeType :> Capture "volume" VolumeName :> Delete '[JSON] (Response Value)
:<|> "1.0" :> "operations" :> Get '[JSON] (Response AllOperations)
:<|> "1.0" :> "operations" :> Capture "uuid" OperationId :> Get '[JSON] (Response Operation)
:<|> "1.0" :> "operations" :> Capture "uuid" OperationId :> Delete '[JSON] (Response Value)
:<|> "1.0" :> "operations" :> Capture "uuid" OperationId :> "wait" :> Get '[JSON] (Response Operation)
api :: Proxy API
api = Proxy
supportedVersions :: ClientM (Response [ApiVersion])
apiConfig :: ClientM (Response ApiConfig)
trustedCertificates :: ClientM (Response [CertificateHash])
containerNames :: ClientM (Response [ContainerName])
containerCreate :: ContainerCreateRequest -> ClientM (AsyncResponse Value)
container :: ContainerName -> ClientM (Response Container)
containerDelete :: ContainerName -> ContainerDeleteRequest -> ClientM (AsyncResponse Value)
containerPut :: ContainerName -> ContainerPut -> ClientM (AsyncResponse Value)
containerPatch :: ContainerName -> ContainerPatch -> ClientM (Response Value)
containerRename :: ContainerName -> ContainerRename -> ClientM (AsyncResponse Value)
containerState :: ContainerName -> ClientM (Response ContainerState)
containerPutState :: ContainerName -> ContainerPutState -> ClientM (AsyncResponse Value)
containerExecImmediate :: ExecClient 'ExecImmediate
containerExecWebsocketInteractive :: ExecClient 'ExecWebsocketInteractive
containerExecWebsocketNonInteractive :: ExecClient 'ExecWebsocketNonInteractive
imageIds :: ClientM (Response [ImageId])
imageCreate :: ImageCreateRequest -> ClientM (AsyncResponse Value)
imageAliases :: ClientM (Response [ImageAliasName])
imageAlias :: ImageAliasName -> ClientM (Response ImageAlias)
image :: ImageId -> ClientM (Response Image)
imageDelete :: ImageId -> ImageDeleteRequest -> ClientM (AsyncResponse Value)
networkList :: ClientM (Response [NetworkName])
networkCreate :: NetworkCreateRequest -> ClientM (Response Value)
network :: NetworkName -> ClientM (Response Network)
networkPut :: NetworkName -> NetworkConfigRequest -> ClientM (Response Value)
networkPatch :: NetworkName -> NetworkConfigRequest -> ClientM (Response Value)
networkDelete :: NetworkName -> ClientM (Response Value)
profileList :: ClientM (Response [ProfileName])
profileCreate :: ProfileCreateRequest -> ClientM (Response Value)
profile :: ProfileName -> ClientM (Response Profile)
profilePut :: ProfileName -> ProfileConfigRequest -> ClientM (Response Value)
profilePatch :: ProfileName -> ProfileConfigRequest -> ClientM (Response Value)
profileDelete :: ProfileName -> ClientM (Response Value)
poolList :: ClientM (Response [PoolName])
poolCreate :: PoolCreateRequest -> ClientM (Response Value)
pool :: PoolName -> ClientM (Response Pool)
poolPut :: PoolName -> PoolConfigRequest -> ClientM (Response Value)
poolPatch :: PoolName -> PoolConfigRequest -> ClientM (Response Value)
poolDelete :: PoolName -> ClientM (Response Value)
volumeList :: PoolName -> ClientM (Response [VolumeName])
volumeCreate :: PoolName -> VolumeCreateRequest -> ClientM (Response Value)
volume' :: PoolName -> VolumeType -> VolumeName -> ClientM (Response Volume)
volumePut' :: PoolName -> VolumeType -> VolumeName -> VolumeConfigRequest -> ClientM (Response Value)
volumePatch' :: PoolName -> VolumeType -> VolumeName -> VolumeConfigRequest -> ClientM (Response Value)
volumeDelete' :: PoolName -> VolumeType -> VolumeName -> ClientM (Response Value)
operationIds :: ClientM (Response AllOperations)
operation :: OperationId -> ClientM (Response Operation)
operationCancel :: OperationId -> ClientM (Response Value)
operationWait :: OperationId -> ClientM (Response Operation)
supportedVersions :<|>
apiConfig :<|>
trustedCertificates :<|>
containerNames :<|>
containerCreate :<|>
container :<|>
containerDelete :<|>
containerPut :<|>
containerPatch :<|>
containerRename :<|>
containerState :<|>
containerPutState :<|>
containerExecImmediate :<|>
containerExecWebsocketInteractive :<|>
containerExecWebsocketNonInteractive :<|>
imageIds :<|>
imageCreate :<|>
imageAliases :<|>
imageAlias :<|>
image :<|>
imageDelete :<|>
networkList :<|>
networkCreate :<|>
network :<|>
networkPut :<|>
networkPatch :<|>
networkDelete :<|>
profileList :<|>
profileCreate :<|>
profile :<|>
profilePut :<|>
profilePatch :<|>
profileDelete :<|>
poolList :<|>
poolCreate :<|>
pool :<|>
poolPut :<|>
poolPatch :<|>
poolDelete :<|>
volumeList :<|>
volumeCreate :<|>
volume' :<|>
volumePut' :<|>
volumePatch' :<|>
volumeDelete' :<|>
operationIds :<|>
operation :<|>
operationCancel :<|>
operationWait
= client api
volume :: PoolName -> VolumeName -> ClientM (Response Volume)
volume p v@(VolumeName t _) = volume' p t v
volumePut :: PoolName -> VolumeName -> VolumeConfigRequest -> ClientM (Response Value)
volumePut p v@(VolumeName t _) = volumePut' p t v
volumePatch :: PoolName -> VolumeName -> VolumeConfigRequest -> ClientM (Response Value)
volumePatch p v@(VolumeName t _) = volumePatch' p t v
volumeDelete :: PoolName -> VolumeName -> ClientM (Response Value)
volumeDelete p v@(VolumeName t _) = volumeDelete' p t v
containerGetPath :: ContainerName -> FilePath -> ClientM PathResponse
containerGetPath name fp = do
req <- pathRequest name fp
res <- performRequest req
let lookupHdr :: FromHttpApiData a => HTTP.HeaderName -> ClientM a
lookupHdr n = lookupHdr' n (Client.responseHeaders res)
hType <- lookupHdr "X-LXD-Type"
hUid <- lookupHdr "X-LXD-Uid"
hGid <- lookupHdr "X-LXD-Gid"
hMode <- lookupHdr "X-LXD-Mode"
case fileResponse hType (Client.responseBody res) of
Left err -> error' $ "Could not decode " ++ show hType ++ ": " ++ err
Right file -> return PathResponse {
pathUid = hUid
, pathGid = hGid
, pathMode = hMode
, pathType = hType
, getFile = file
}
where
lookupHdr' :: FromHttpApiData a => HTTP.HeaderName -> [HTTP.Header] -> ClientM a
lookupHdr' n xs = case find ((== n) . fst) xs of
Nothing -> error' $ "Missing header in response: " ++ show n
Just (_, v) -> case parseHeader v of
Left err -> error' $ "Could not decode header " ++ show n
++ " with value " ++ show v ++ ": " ++ show err
Right v' -> return v'
error' = liftIO . throwIO . DecodeError
data WriteMode = ModeOverwrite | ModeAppend deriving (Show)
containerPostPath :: ContainerName
-> FilePath
-> Maybe Uid
-> Maybe Gid
-> Maybe FileMode
-> FileType
-> Maybe WriteMode
-> ByteString
-> ClientM (Response Value)
containerPostPath name fp uid gid perm ftype mode body = do
req <- pathRequest name fp
let hdrs = catMaybes [ hdr "X-LXD-Uid" <$> uid
, hdr "X-LXD-Gid" <$> gid
, hdr "X-LXD-Mode" <$> perm
, hdr "X-LXD-Type" <$> Just ftype
, hdr "X-LXD-Write" . mode' <$> mode ]
let req' = req { Client.method = "POST"
, Client.requestHeaders = hdrs
, Client.requestBody = Client.RequestBodyLBS body }
performJsonRequest req'
where
mode' ModeOverwrite = "overwrite" :: Text
mode' ModeAppend = "append"
hdr :: ToHttpApiData v => HTTP.HeaderName -> v -> HTTP.Header
hdr n v = (n, toHeader v)
containerDeletePath :: ContainerName -> FilePath -> ClientM (Response Value)
containerDeletePath name fp = do
res <- pathRequest name fp
performJsonRequest $ res { Client.method = "DELETE" }
operationWebSocket :: OperationId -> Secret -> String
operationWebSocket (OperationId oid) (Secret secret) =
"/1.0/operations/" ++ oid ++ "/websocket?secret=" ++ secret
readAllWebSocket :: (ByteString -> IO ()) -> WS.ClientApp ()
readAllWebSocket f con = do
m <- (Just . compat <$> WS.receiveDataMessage con) `catch` handle'
case m of Nothing -> return ()
Just (WSC.Text _) -> WS.sendClose con BL.empty
Just (WSC.Binary bs) -> f bs
>> readAllWebSocket f con
where
handle' (WS.CloseRequest _ _) = return Nothing
handle' e = throwIO e
writeAllWebSocket :: MVar (Maybe ByteString) -> WS.ClientApp ()
writeAllWebSocket input con = do
i <- takeMVar input
case i of
Nothing -> WS.sendClose con BL.empty
Just bs -> WS.sendBinaryData con bs
>> writeAllWebSocket input con
type ExecAPI a = "1.0" :> "containers" :> Capture "name" ContainerName :> "exec" :> ReqBody '[JSON] (ExecRequest a) :> Post '[JSON] (AsyncResponse (ExecResponseMetadata a))
type ExecClient a = ContainerName -> ExecRequest a -> ClientM (AsyncResponse (ExecResponseMetadata a))
pathRequest :: ContainerName -> FilePath -> ClientM Client.Request
pathRequest (ContainerName name) fp = do
BaseUrl{..} <- askBaseUrl
return Client.defaultRequest {
Client.method = "GET"
, Client.host = fromString baseUrlHost
, Client.port = baseUrlPort
, Client.path = toStrict $ fromString baseUrlPath <> "/1.0/containers/" <> Char8.pack name <> "/files"
, Client.queryString = toStrict $ "?path=" <> Char8.pack fp
}
performRequest :: Client.Request -> ClientM (Client.Response ByteString)
performRequest req = do
m <- askManager
r <- liftIO $ Client.httpLbs req m
let status = Client.responseStatus r
statusCode' = HTTP.statusCode status
unless (statusCode' >= 200 && statusCode' < 300) $
liftIO . throwIO $ FailureResponse req r
return r
performJsonRequest :: FromJSON a => Client.Request -> ClientM a
performJsonRequest req = do
res <- performRequest req
case eitherDecode (Client.responseBody res) of
Left err -> liftIO . throwIO . DecodeError $ "Could not decode JSON body: " ++ err
Right v -> return v
-- | Exception thrown in 'containerGetPath', 'containerDeletePath' and
-- 'containerPostPath'.
data FailureResponse = FailureResponse Client.Request (Client.Response ByteString) deriving (Show)
instance Exception FailureResponse where
-- | Exception thrown in 'containerGetPath', 'containerDeletePath' and
-- 'containerPostPath'.
newtype DecodeError = DecodeError String deriving (Show)
instance Exception DecodeError where
askBaseUrl :: ClientM BaseUrl
askBaseUrl = asks getBaseUrl
where
getBaseUrl :: ClientEnv -> BaseUrl
#if MIN_VERSION_servant(0, 12, 0)
getBaseUrl = baseUrl
#else
getBaseUrl (ClientEnv _ url) = url
#endif
askManager :: ClientM Client.Manager
askManager = asks getManager
where
getManager :: ClientEnv -> Client.Manager
#if MIN_VERSION_servant(0, 12, 0)
getManager = manager
#else
getManager (ClientEnv mgr _) = mgr
#endif
| hverr/haskell-lxd-client | src/Network/LXD/Client/API.hs | gpl-3.0 | 21,223 | 0 | 214 | 6,125 | 5,489 | 2,814 | 2,675 | 358 | 4 |
{-# LANGUAGE FlexibleContexts #-}
module TestWait (
testWait
) where
import Data.Maybe (isJust)
import Test.Framework (Test, buildTest, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertEqual)
import Utils (assertConstantMemory, testLogsOfMatch, runAppWithoutLogging)
import Control.Concurrent.Longrun as Longrun
testWait :: Test
testWait = testGroup "Test task sleep"
[ testTimeout
, testMem
, testWriteQueueTimeout
]
procTimeout :: Process ()
procTimeout = do
logM INFO "start"
(writeEnd, readEnd) <- newBoundedQueue1
_ <- spawnTask $ do
sleep 0.1
logM INFO "awoke"
writeQueueBlocking writeEnd "hello"
logM INFO "spawned"
msg <- withTimeout 0.2 $ readQueueBlocking readEnd
logM INFO $ show msg
testTimeout :: Test
testTimeout = testLogsOfMatch "timeout" DEBUG procTimeout
[ (INFO,"start")
, (INFO, "spawned")
, (INFO, "awoke")
, (INFO, "Just \"hello\"")
]
procMem :: Process ()
procMem = do
-- case false
do
(writeEnd, readEnd) <- newBoundedQueue1
t <- spawnTask $ do
sleep 0.004
writeQueueBlocking writeEnd "hello"
msg <- withTimeout 0.003 $ readQueueBlocking readEnd
_ <- stop t
logM INFO $ show msg
-- case true
do
(writeEnd, readEnd) <- newBoundedQueue1
t <- spawnTask $ do
sleep 0.002
writeQueueBlocking writeEnd "hello"
msg <- withTimeout 0.003 $ readQueueBlocking readEnd
_ <- stop t
logM INFO $ show msg
testMem :: Test
testMem = buildTest $
fmap (testCase "queue timeout memory leak") $
runAppWithoutLogging $ assertConstantMemory 100 1.2 procMem
procWriteQueueTimeout :: Process [Bool]
procWriteQueueTimeout = do
(writeEnd, _) <- newBoundedQueue 2
sequence $ replicate 4 $ fmap isJust $ withTimeout 0.01 $
writeQueueBlocking writeEnd ()
testWriteQueueTimeout :: Test
testWriteQueueTimeout = buildTest $
fmap (testCase "write to queue with timeout") $ do
pattern <- runAppWithoutLogging procWriteQueueTimeout
return $ assertEqual "write" [True, True, False, False] pattern
| zoranbosnjak/longrun | test/TestWait.hs | gpl-3.0 | 2,215 | 0 | 13 | 559 | 613 | 307 | 306 | 63 | 1 |
module Sara.Semantic.TypeCheckerTest (typeCheckerGroup) where
import Control.Monad.Except
import Sara.TestUtils.AstGenUtils()
import Sara.TestUtils.AstTestUtils
import Sara.Semantic.TypeChecker
import Sara.Ast.Meta
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
prop_addsTypes :: TypeCheckerProgram -> Property
prop_addsTypes p = check input expected actual
where input = clearTypes p
expected = return p
actual = liftM clearSymbols $ liftM clearPureness $ checkWithoutMain input
typeCheckerGroup :: Test
typeCheckerGroup = testGroup "TypeCheckerTests" [ testProperty "adds types" prop_addsTypes ]
| Lykos/Sara | tests/Sara/Semantic/TypeCheckerTest.hs | gpl-3.0 | 662 | 0 | 9 | 86 | 149 | 84 | 65 | 16 | 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.Container.Projects.Zones.Clusters.NodePools.Create
-- 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)
--
-- Creates a node pool for a cluster.
--
-- /See:/ <https://cloud.google.com/container-engine/ Google Container Engine API Reference> for @container.projects.zones.clusters.nodePools.create@.
module Network.Google.Resource.Container.Projects.Zones.Clusters.NodePools.Create
(
-- * REST Resource
ProjectsZonesClustersNodePoolsCreateResource
-- * Creating a Request
, projectsZonesClustersNodePoolsCreate
, ProjectsZonesClustersNodePoolsCreate
-- * Request Lenses
, pzcnpcXgafv
, pzcnpcUploadProtocol
, pzcnpcPp
, pzcnpcAccessToken
, pzcnpcUploadType
, pzcnpcZone
, pzcnpcPayload
, pzcnpcBearerToken
, pzcnpcClusterId
, pzcnpcProjectId
, pzcnpcCallback
) where
import Network.Google.Container.Types
import Network.Google.Prelude
-- | A resource alias for @container.projects.zones.clusters.nodePools.create@ method which the
-- 'ProjectsZonesClustersNodePoolsCreate' request conforms to.
type ProjectsZonesClustersNodePoolsCreateResource =
"v1" :>
"projects" :>
Capture "projectId" Text :>
"zones" :>
Capture "zone" Text :>
"clusters" :>
Capture "clusterId" Text :>
"nodePools" :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] CreateNodePoolRequest :>
Post '[JSON] Operation
-- | Creates a node pool for a cluster.
--
-- /See:/ 'projectsZonesClustersNodePoolsCreate' smart constructor.
data ProjectsZonesClustersNodePoolsCreate = ProjectsZonesClustersNodePoolsCreate'
{ _pzcnpcXgafv :: !(Maybe Text)
, _pzcnpcUploadProtocol :: !(Maybe Text)
, _pzcnpcPp :: !Bool
, _pzcnpcAccessToken :: !(Maybe Text)
, _pzcnpcUploadType :: !(Maybe Text)
, _pzcnpcZone :: !Text
, _pzcnpcPayload :: !CreateNodePoolRequest
, _pzcnpcBearerToken :: !(Maybe Text)
, _pzcnpcClusterId :: !Text
, _pzcnpcProjectId :: !Text
, _pzcnpcCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProjectsZonesClustersNodePoolsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pzcnpcXgafv'
--
-- * 'pzcnpcUploadProtocol'
--
-- * 'pzcnpcPp'
--
-- * 'pzcnpcAccessToken'
--
-- * 'pzcnpcUploadType'
--
-- * 'pzcnpcZone'
--
-- * 'pzcnpcPayload'
--
-- * 'pzcnpcBearerToken'
--
-- * 'pzcnpcClusterId'
--
-- * 'pzcnpcProjectId'
--
-- * 'pzcnpcCallback'
projectsZonesClustersNodePoolsCreate
:: Text -- ^ 'pzcnpcZone'
-> CreateNodePoolRequest -- ^ 'pzcnpcPayload'
-> Text -- ^ 'pzcnpcClusterId'
-> Text -- ^ 'pzcnpcProjectId'
-> ProjectsZonesClustersNodePoolsCreate
projectsZonesClustersNodePoolsCreate pPzcnpcZone_ pPzcnpcPayload_ pPzcnpcClusterId_ pPzcnpcProjectId_ =
ProjectsZonesClustersNodePoolsCreate'
{ _pzcnpcXgafv = Nothing
, _pzcnpcUploadProtocol = Nothing
, _pzcnpcPp = True
, _pzcnpcAccessToken = Nothing
, _pzcnpcUploadType = Nothing
, _pzcnpcZone = pPzcnpcZone_
, _pzcnpcPayload = pPzcnpcPayload_
, _pzcnpcBearerToken = Nothing
, _pzcnpcClusterId = pPzcnpcClusterId_
, _pzcnpcProjectId = pPzcnpcProjectId_
, _pzcnpcCallback = Nothing
}
-- | V1 error format.
pzcnpcXgafv :: Lens' ProjectsZonesClustersNodePoolsCreate (Maybe Text)
pzcnpcXgafv
= lens _pzcnpcXgafv (\ s a -> s{_pzcnpcXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pzcnpcUploadProtocol :: Lens' ProjectsZonesClustersNodePoolsCreate (Maybe Text)
pzcnpcUploadProtocol
= lens _pzcnpcUploadProtocol
(\ s a -> s{_pzcnpcUploadProtocol = a})
-- | Pretty-print response.
pzcnpcPp :: Lens' ProjectsZonesClustersNodePoolsCreate Bool
pzcnpcPp = lens _pzcnpcPp (\ s a -> s{_pzcnpcPp = a})
-- | OAuth access token.
pzcnpcAccessToken :: Lens' ProjectsZonesClustersNodePoolsCreate (Maybe Text)
pzcnpcAccessToken
= lens _pzcnpcAccessToken
(\ s a -> s{_pzcnpcAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pzcnpcUploadType :: Lens' ProjectsZonesClustersNodePoolsCreate (Maybe Text)
pzcnpcUploadType
= lens _pzcnpcUploadType
(\ s a -> s{_pzcnpcUploadType = a})
-- | The name of the Google Compute Engine
-- [zone](\/compute\/docs\/zones#available) in which the cluster resides.
pzcnpcZone :: Lens' ProjectsZonesClustersNodePoolsCreate Text
pzcnpcZone
= lens _pzcnpcZone (\ s a -> s{_pzcnpcZone = a})
-- | Multipart request metadata.
pzcnpcPayload :: Lens' ProjectsZonesClustersNodePoolsCreate CreateNodePoolRequest
pzcnpcPayload
= lens _pzcnpcPayload
(\ s a -> s{_pzcnpcPayload = a})
-- | OAuth bearer token.
pzcnpcBearerToken :: Lens' ProjectsZonesClustersNodePoolsCreate (Maybe Text)
pzcnpcBearerToken
= lens _pzcnpcBearerToken
(\ s a -> s{_pzcnpcBearerToken = a})
-- | The name of the cluster.
pzcnpcClusterId :: Lens' ProjectsZonesClustersNodePoolsCreate Text
pzcnpcClusterId
= lens _pzcnpcClusterId
(\ s a -> s{_pzcnpcClusterId = a})
-- | The Google Developers Console [project ID or project
-- number](https:\/\/developers.google.com\/console\/help\/new\/#projectnumber).
pzcnpcProjectId :: Lens' ProjectsZonesClustersNodePoolsCreate Text
pzcnpcProjectId
= lens _pzcnpcProjectId
(\ s a -> s{_pzcnpcProjectId = a})
-- | JSONP
pzcnpcCallback :: Lens' ProjectsZonesClustersNodePoolsCreate (Maybe Text)
pzcnpcCallback
= lens _pzcnpcCallback
(\ s a -> s{_pzcnpcCallback = a})
instance GoogleRequest
ProjectsZonesClustersNodePoolsCreate where
type Rs ProjectsZonesClustersNodePoolsCreate =
Operation
type Scopes ProjectsZonesClustersNodePoolsCreate =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsZonesClustersNodePoolsCreate'{..}
= go _pzcnpcProjectId _pzcnpcZone _pzcnpcClusterId
_pzcnpcXgafv
_pzcnpcUploadProtocol
(Just _pzcnpcPp)
_pzcnpcAccessToken
_pzcnpcUploadType
_pzcnpcBearerToken
_pzcnpcCallback
(Just AltJSON)
_pzcnpcPayload
containerService
where go
= buildClient
(Proxy ::
Proxy ProjectsZonesClustersNodePoolsCreateResource)
mempty
| rueshyna/gogol | gogol-container/gen/Network/Google/Resource/Container/Projects/Zones/Clusters/NodePools/Create.hs | mpl-2.0 | 7,777 | 0 | 24 | 1,894 | 1,099 | 637 | 462 | 167 | 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.SimulateMaintenanceEvent
-- 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)
--
-- Simulates a maintenance event on the instance.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.simulateMaintenanceEvent@.
module Network.Google.Resource.Compute.Instances.SimulateMaintenanceEvent
(
-- * REST Resource
InstancesSimulateMaintenanceEventResource
-- * Creating a Request
, instancesSimulateMaintenanceEvent
, InstancesSimulateMaintenanceEvent
-- * Request Lenses
, ismeProject
, ismeZone
, ismeInstance
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instances.simulateMaintenanceEvent@ method which the
-- 'InstancesSimulateMaintenanceEvent' request conforms to.
type InstancesSimulateMaintenanceEventResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instances" :>
Capture "instance" Text :>
"simulateMaintenanceEvent" :>
QueryParam "alt" AltJSON :> Post '[JSON] Operation
-- | Simulates a maintenance event on the instance.
--
-- /See:/ 'instancesSimulateMaintenanceEvent' smart constructor.
data InstancesSimulateMaintenanceEvent =
InstancesSimulateMaintenanceEvent'
{ _ismeProject :: !Text
, _ismeZone :: !Text
, _ismeInstance :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstancesSimulateMaintenanceEvent' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ismeProject'
--
-- * 'ismeZone'
--
-- * 'ismeInstance'
instancesSimulateMaintenanceEvent
:: Text -- ^ 'ismeProject'
-> Text -- ^ 'ismeZone'
-> Text -- ^ 'ismeInstance'
-> InstancesSimulateMaintenanceEvent
instancesSimulateMaintenanceEvent pIsmeProject_ pIsmeZone_ pIsmeInstance_ =
InstancesSimulateMaintenanceEvent'
{ _ismeProject = pIsmeProject_
, _ismeZone = pIsmeZone_
, _ismeInstance = pIsmeInstance_
}
-- | Project ID for this request.
ismeProject :: Lens' InstancesSimulateMaintenanceEvent Text
ismeProject
= lens _ismeProject (\ s a -> s{_ismeProject = a})
-- | The name of the zone for this request.
ismeZone :: Lens' InstancesSimulateMaintenanceEvent Text
ismeZone = lens _ismeZone (\ s a -> s{_ismeZone = a})
-- | Name of the instance scoping this request.
ismeInstance :: Lens' InstancesSimulateMaintenanceEvent Text
ismeInstance
= lens _ismeInstance (\ s a -> s{_ismeInstance = a})
instance GoogleRequest
InstancesSimulateMaintenanceEvent
where
type Rs InstancesSimulateMaintenanceEvent = Operation
type Scopes InstancesSimulateMaintenanceEvent =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient InstancesSimulateMaintenanceEvent'{..}
= go _ismeProject _ismeZone _ismeInstance
(Just AltJSON)
computeService
where go
= buildClient
(Proxy ::
Proxy InstancesSimulateMaintenanceEventResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Instances/SimulateMaintenanceEvent.hs | mpl-2.0 | 4,113 | 0 | 17 | 929 | 467 | 278 | 189 | 78 | 1 |
{-
FCA - A generator of a Formal Concept Analysis Lattice
Copyright (C) 2014 Raymond Racine
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Data.Fca.CElem where
import Data.Hashable (Hashable)
import Data.Text (Text)
class (Eq t, Hashable t, Ord t, Show t) => CElem t
instance CElem Text
| RayRacine/hsfca | src/Data/Fca/CElem.hs | agpl-3.0 | 973 | 0 | 6 | 237 | 69 | 38 | 31 | -1 | -1 |
{-
Created : 2014 Dec 27 (Sat) 14:38:17 by Harold Carr.
Last Modified : 2014 Dec 29 (Mon) 00:11:55 by Harold Carr.
-}
module Lab6 where
import Prelude as P
import Test.HUnit as T
import Test.HUnit.Util as U
------------------------------------------------------------------------------------------------------------------------------
-- ROSE TREES, FUNCTORS, MONOIDS, FOLDABLES
------------------------------------------------------------------------------------------------------------------------------
data Rose a = a :> [Rose a] deriving (Eq, Show)
-- ===================================
-- Ex. 0-2
-- ===================================
root :: Rose a -> a
root (a :> _) = a
children :: Rose a -> [Rose a]
children (_ :> as) = as
e0a :: [Test]
e0a = U.t "e0a"
(root (1 :> [2 :> [], 3 :> []]))
1
e0b:: [Test]
e0b = U.t "e0b"
(root ('a' :> []))
'a'
e0c:: [Test]
e0c = U.t "e0c"
(children (1 :> [2 :> [], 3 :> []]))
[2 :> [], 3 :> []]
e0d:: [Test]
e0d = U.t "e0d"
(children ('a' :> []))
[]
e03tree = 'x' :> map (flip (:>) []) ['a'..'x']
e0e:: [Test]
e0e = U.t "e0e"
(length $ children e03tree)
24
e1tree = 'x' :> map (\c -> c :> []) ['a'..'A']
e1 :: [Test]
e1 = U.t "e1"
(length (children e1tree))
0
xs = 0 :> [1 :> [2 :> [3 :> [4 :> [], 5 :> []]]], 6 :> [], 7 :> [8 :> [9 :> [10 :> []], 11 :> []], 12 :> [13 :> []]]]
ex2 = root . head . children . head . children . head . drop 2 $ children xs
e2 :: [Test]
e2 = U.t "e2"
ex2
9
-- ===================================
-- Ex. 3-7
-- ===================================
size :: Rose a -> Int
size (_ :> []) = 1
size (_ :> (x:xs)) = 1 + size x + (sum (map size xs))
leaves :: Rose a -> Int
leaves (_ :> []) = 1
leaves (_ :> (x:[])) = leaves x
leaves (a :> (x:xs)) = leaves x + (leaves (a :> xs))
e3tree = 1 :> map (\c -> c :> []) [1..5]
e3 :: [Test]
e3 = U.t "e3"
(size e3tree)
6
e4tree = 1 :> map (\c -> c :> []) [1..5]
e4 :: [Test]
e4 = U.t "e4"
(size . head . children $ e4tree)
1
e5tree = 1 :> map (\c -> c :> []) [1..5]
e5 :: [Test]
e5 = U.t "e5"
(leaves e5tree)
5
e6tree = 1 :> map (\c -> c :> []) [1..5]
e6 :: [Test]
e6 = U.t "e6"
(product (map leaves (children e6tree)))
1
ex7 = (*) (leaves . head . children . head . children $ xs) (product . map size . children . head . drop 2 . children $ xs)
e7 :: [Test]
e7 = U.t "e7"
ex7
16
-- ===================================
-- Ex. 8-10
-- ===================================
instance Functor Rose where
fmap f (a :> []) = (f a) :> []
fmap f (a :> xs) = (f a) :> (map (\x -> fmap f x) xs)
e8a :: [Test]
e8a = U.t "e8a"
(fmap (*2) (1 :> [2 :> [], 3 :> []]))
(2 :> [4 :> [], 6 :> []])
e8b :: [Test]
e8b = U.t "e8b"
(fmap (+1) (1 :> []))
(2 :> [])
e8tree = 1 :> map (\c -> c :> []) [1..5]
e8 :: [Test]
e8 = U.t "e8"
(size (fmap leaves (fmap (:> []) e8tree)))
6
e9f :: Rose a -> Rose a
e9f r = fmap head $ fmap (\x -> [x]) r
ex10 = round . root . head . children . fmap (\x -> if x > 0.5 then x else 0) $ fmap (\x -> sin(fromIntegral x)) xs
e10 :: [Test]
e10 = U.t "e10"
ex10
1
-- ===================================
-- Ex. 11-13
-- ===================================
class Monoid m where
mempty :: m
mappend :: m -> m -> m
newtype Sum a = Sum a deriving (Eq, Show)
newtype Product a = Product a deriving (Eq, Show)
instance Num a => Monoid (Sum a) where
mempty = (Sum 0)
mappend (Sum x) (Sum y) = (Sum $ x + y)
instance Num a => Monoid (Product a) where
mempty = (Product 1)
mappend (Product x) (Product y) = (Product $ x * y)
unSum :: Sum a -> a
unSum (Sum a) = a
unProduct :: Product a -> a
unProduct (Product a) = a
e11 :: [Test]
e11 = U.t "e11"
(unProduct (Product 6 `mappend` (Product . unSum $ Sum 3 `mappend` Sum 4)))
42
-- e12 :: Num num => Sum (unSum num)
-- e12 :: Int int => Sum int
e12 :: Num string => Sum string
e12 = Sum 3 `mappend` Sum 4
num1 = mappend (mappend (Sum 2) (mappend (mappend mempty (Sum 1)) mempty)) (mappend (Sum 2) (Sum 1))
num2 = mappend (Sum 3) (mappend mempty (mappend (mappend (mappend (Sum 2) mempty) (Sum (-1))) (Sum 3)))
ex13 = unSum (mappend (Sum 5) (Sum (unProduct (mappend (Product (unSum num2)) (mappend (Product (unSum num1)) (mappend mempty (mappend (Product 2) (Product 3))))))))
e13 :: [Test]
e13 = U.t "e13"
ex13
257
-- ===================================
-- Ex. 14-15
-- ===================================
newtype Endo a = Endo { appEndo :: a -> a }
instance Monoid (Endo a) where
mempty = Endo id
Endo f `mappend` Endo g = Endo (f . g)
class Functor f => Foldable f where
fold :: Monoid m => f m -> m
fold = foldMap id
foldMap :: Monoid m => (a -> m) -> f a -> m
foldMap f0 = Lab6.foldr (mappend . f0) mempty
foldr :: (a -> b -> b) -> b -> f a -> b
foldr f1 z f = appEndo (foldMap (Endo . f1) f) z
instance Foldable [] where
foldr = P.foldr
instance Foldable Rose where
foldMap f (x :> xs0) = f x `mappend` foldMap (foldMap f) xs0
e14tree = 1 :> [2 :> [], 3 :> [4 :> []]]
e14tree' = fmap Product e14tree
e14 :: [Test]
e14 = U.t "e14"
(unProduct $ fold e14tree')
24
sumxs = Sum 0 :> [Sum 13 :> [Sum 26 :> [Sum (-31) :> [Sum (-45) :> [], Sum 23 :> []]]], Sum 27 :> [], Sum 9 :> [Sum 15 :> [Sum 3 :> [Sum (-113) :> []], Sum 1 :> []], Sum 71 :> [Sum 55 :> []]]]
ex15 = unSum (mappend (mappend (fold sumxs) (mappend (fold . head . drop 2 . children $ sumxs) (Sum 30))) (fold . head . children $ sumxs))
e15 :: [Test]
e15 = U.t "e15"
ex15
111
-- ===================================
-- Ex. 16-18
-- ===================================
e16tree = 42 :> [3 :> [2:> [], 1 :> [0 :> []]]]
e16 :: [Test]
e16 = U.t "e16"
(unSum $ foldMap Sum e16tree)
48
ex17 = unSum (mappend (mappend (foldMap (\x -> Sum x) xs) (mappend (foldMap (\x -> Sum x) . head . drop 2 . children $ xs) (Sum 30))) (foldMap (\x -> Sum x) . head . children $ xs))
e17 :: [Test]
e17 = U.t "e17"
ex17
206
ex18 = unSum (mappend (mappend (foldMap (\x -> Sum x) xs) (Sum (unProduct (mappend (foldMap (\x -> Product x) . head . drop 2 . children $ xs) (Product 3))))) (foldMap (\x -> Sum x) . head . children $ xs))
e18 :: [Test]
e18 = U.t "e18"
ex18
25946026
-- ===================================
-- Ex. 19-21
-- ===================================
fproduct, fsum :: (Foldable f, Num a) => f a -> a
fsum fa = unSum $ fold (fmap Sum fa)
fproduct fa = unProduct $ fold (fmap Product fa)
e19 :: [Test]
e19 = U.t "e19"
(fsum xs)
91
e20 :: [Test]
e20 = U.t "e20"
(fproduct xs)
0
ex21 = ((fsum . head . drop 1 . children $ xs) + (fproduct . head . children . head . children . head . drop 2 . children $ xs)) - (fsum . head . children . head . children $ xs)
e21 :: [Test]
e21 = U.t "e21"
ex21
82
------------------------------------------------------------------------------
main :: IO Counts
main =
T.runTestTT $ T.TestList $ e0a ++ e0b ++ e0c ++ e0d ++ e0e ++ e1 ++ e2 ++ e3 ++
e4 ++ e5 ++ e6 ++ e7 ++
e8a ++ e8b ++ e8 ++ e10 ++
e11 ++ e13 ++ e14 ++ e15 ++ e16 ++
e17 ++ e18 ++ e19 ++ e20 ++ e21
-- End of file.
| haroldcarr/learn-haskell-coq-ml-etc | haskell/course/2014-10-edx-delft-fp101x-intro-to-fp-erik-meijer/lab6.hs | unlicense | 7,544 | 0 | 32 | 2,115 | 3,614 | 1,914 | 1,700 | 189 | 2 |
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE RecordWildCards #-}
module Mechanics where
import Types
import Debug.Trace as D
--import Data.Foldable
intersects :: Line → Line → Bool
intersects ((x1,y1), (x2,y2)) ((x3,y3), (x4,y4)) =
isCrossing || isSameLine
where isSameLine = (denominator == 0) && (numerator1 == 0) && (numerator2 == 0)
isCrossing = denominator /= 0 && (0 <= u1 && u1 <= 1) && (0 <= u2 && u2 <= 1)
denominator = (y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)
numerator1 = (x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)
numerator2 = (x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)
u1 = numerator1 / denominator
u2 = numerator2 / denominator
completes :: CarState -> Point -> Track -> Bool
completes (start,_) end Track{..} =
intersects (start,end) finishLine
crashes :: CarState -> Point -> Track -> Bool
crashes (start,_) end Track{..} =
D.trace ("start end " ++ show (start,end))
any (intersects (start,end)) boundaries
| nrolland/racetrack | src/Mechanics.hs | apache-2.0 | 1,008 | 0 | 12 | 244 | 448 | 252 | 196 | 22 | 1 |
module Github.Review.Filters
( sortByCommitDate
, getCommitDate
, ascending
, descending
, offsetByDays
, spanAfter
, getAfterOrMinimum
) where
import Data.List (sortBy)
import Data.Ord
import Data.Time
import Github.Data
import Github.Review.Types
sortByCommitDate :: [RepoCommit] -> [RepoCommit]
sortByCommitDate = sortBy (descending (comparing (getCommitDate . snd)))
getCommitDate :: Commit -> UTCTime
getCommitDate = fromGithubDate
. gitUserDate
. gitCommitCommitter
. commitGitCommit
ascending :: (a -> b -> c) -> a -> b -> c
ascending = id
descending :: (a -> b -> c) -> b -> a -> c
descending = flip
offsetByDays :: Integer -> UTCTime -> UTCTime
offsetByDays days from =
fromInteger (days * 60 * 60 * 24) `addUTCTime` from
spanAfter :: (a -> UTCTime) -> UTCTime -> [a] -> ([a], [a])
spanAfter getter breakOn = span ((breakOn <=) . getter)
getAfterOrMinimum :: (a -> UTCTime) -> UTCTime -> Int -> [a] -> [a]
getAfterOrMinimum getter breakOn minLength xs =
if length after >= minLength
then after
else take minLength xs
where after = fst $ spanAfter getter breakOn xs
| erochest/gitreview-core | Github/Review/Filters.hs | apache-2.0 | 1,200 | 0 | 11 | 295 | 391 | 218 | 173 | 35 | 2 |
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeOperators #-}
-- | K3 Program constructor
module Language.K3.Parser.ProgramBuilder (
defaultRoleName,
processInitsAndRoles,
endpointMethods,
bindSource,
mkRunSourceE,
mkRunSinkE,
declareBuiltins,
resolveFn
) where
import Control.Applicative
import Data.List
import Data.Tree
import Debug.Trace
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Declaration
import Language.K3.Core.Expression
import Language.K3.Core.Type
import Language.K3.Core.Utils
import qualified Language.K3.Core.Constructor.Type as TC
import qualified Language.K3.Core.Constructor.Expression as EC
import qualified Language.K3.Core.Constructor.Declaration as DC
-- | Type synonyms, copied from the parser.
type EndpointInfo = (EndpointSpec, Maybe [Identifier], Identifier, Maybe (K3 Expression))
{- Names -}
defaultRoleName :: Identifier
defaultRoleName = "__global"
myId :: Identifier
myId = "me"
peersId :: Identifier
peersId = "peers"
argsId :: Identifier
argsId = "args"
myAddr :: K3 Expression
myAddr = EC.variable myId
chrName :: Identifier -> Identifier
chrName n = n++"HasRead"
crName :: Identifier -> Identifier
crName n = n++"Read"
chwName :: Identifier -> Identifier
chwName n = n++"HasWrite"
cwName :: Identifier -> Identifier
cwName n = n++"Write"
ciName :: Identifier -> Identifier
ciName n = n++"Init"
csName :: Identifier -> Identifier
csName n = n++"Start"
cpName :: Identifier -> Identifier
cpName n = n++"Process"
ccName :: Identifier -> Identifier
ccName n = n++"Controller"
{- Runtime functions -}
openBuiltinFn :: K3 Expression
openBuiltinFn = EC.variable "openBuiltin"
openFileFn :: K3 Expression
openFileFn = EC.variable "openFile"
openSocketFn :: K3 Expression
openSocketFn = EC.variable "openSocket"
closeFn :: K3 Expression
closeFn = EC.variable "close"
{- -- Unused
registerFileDataTriggerFn :: K3 Expression
registerFileDataTriggerFn = EC.variable "registerFileDataTrigger"
registerFileCloseTriggerFn :: K3 Expression
registerFileCloseTriggerFn = EC.variable "registerFileCloseTrigger"
registerSocketAcceptTriggerFn :: K3 Expression
registerSocketAcceptTriggerFn = EC.variable "registerSocketAcceptTrigger"
registerSocketCloseTriggerFn :: K3 Expression
registerSocketCloseTriggerFn = EC.variable "registerSocketCloseTrigger"
-}
registerSocketDataTriggerFn :: K3 Expression
registerSocketDataTriggerFn = EC.variable "registerSocketDataTrigger"
resolveFn :: K3 Expression
resolveFn = EC.variable "resolve"
{- Top-level functions -}
roleId :: Identifier
roleId = "role"
roleVar :: K3 Expression
roleVar = EC.variable roleId
roleFnId :: Identifier
roleFnId = "processRole"
roleFn :: K3 Expression
roleFn = EC.variable roleFnId
{- Declaration construction -}
builtinGlobal :: Identifier -> K3 Type -> Maybe (K3 Expression) -> K3 Declaration
builtinGlobal n t eOpt = (DC.global n t eOpt) @+ (DSpan $ GeneratedSpan "builtin")
builtinTrigger :: Identifier -> K3 Type -> K3 Expression -> K3 Declaration
builtinTrigger n t e = (DC.trigger n t e) @+ (DSpan $ GeneratedSpan "builtin")
{- Type qualification -}
qualifyT :: K3 Type -> K3 Type
qualifyT t = if null $ filter isTQualified $ annotations t then t @+ TImmutable else t
qualifyE :: K3 Expression -> K3 Expression
qualifyE e = if null $ filter isEQualified $ annotations e then e @+ EImmutable else e
{- Desugaring methods -}
-- TODO: replace with Template Haskell
processInitsAndRoles :: K3 Declaration -> [(Identifier, EndpointInfo)] -> [(Identifier, Identifier)]
-> K3 Declaration
processInitsAndRoles (Node t c) endpointBQGs roleDefaults = Node t $ c ++ initializerFns
where
(sinkEndpoints, sourceEndpoints) = partition matchSink endpointBQGs
matchSink (_,(_, Nothing, _, _)) = True
matchSink _ = False
initializerFns =
[ builtinGlobal roleFnId (qualifyT unitFnT)
$ Just . qualifyE $ mkRoleBody sourceEndpoints sinkEndpoints roleDefaults ]
sinkInitE acc (_,(_, Nothing, _, Just e)) = acc ++ [e]
sinkInitE acc _ = acc
mkRoleBody sources sinks defaults =
EC.lambda "_" $ EC.block $
(trace ("Sinks " ++ show sinks) $ foldl sinkInitE [] sinks) ++
[uncurry (foldl dispatchId) $ defaultAndRestIds sources defaults]
defaultAndRestIds sources defaults = (defaultE sources $ lookup "" defaults, sources)
dispatchId elseE (n,(_,_,y,goE)) = EC.ifThenElse (eqRole y) (runE n goE) elseE
eqRole n = EC.binop OEqu roleVar (EC.constant $ CString n)
runE _ (Just goE) = goE
runE n Nothing = EC.applyMany (EC.variable $ cpName n) [EC.unit]
defaultE s (Just x) = case find ((x ==) . third . snd) s of
Just (n,(_,_,_,goE)) -> runE n goE
Nothing -> EC.unit
defaultE _ Nothing = EC.unit
third (_,_,x,_) = x
unitFnT = TC.function TC.unit TC.unit
{- Code generation methods-}
-- TODO: replace with Template Haskell
endpointMethods :: Bool -> EndpointSpec -> K3 Expression -> K3 Expression -> Identifier -> K3 Type
-> (EndpointSpec, Maybe (K3 Expression), [K3 Declaration])
endpointMethods isSource eSpec argE formatE n t =
if isSource then sourceDecls else sinkDecls
where
sourceDecls = (eSpec, Nothing,) $
(map mkMethod [mkInit, mkStart, mkFinal, sourceHasRead, sourceRead])
++ [sourceController]
sinkDecls = (eSpec, Just sinkImpl, map mkMethod [mkInit, mkFinal, sinkHasWrite, sinkWrite])
mkMethod (m, argT, retT, eOpt) =
builtinGlobal (n++m) (qualifyT $ TC.function argT retT)
$ maybe Nothing (Just . qualifyE) eOpt
mkInit = ("Init", TC.unit, TC.unit, Just $ EC.lambda "_" $ openEndpointE)
mkStart = ("Start", TC.unit, TC.unit, Just $ EC.lambda "_" $ startE)
mkFinal = ("Final", TC.unit, TC.unit, Just $ EC.lambda "_" $ EC.applyMany closeFn [sourceId n])
sourceController = builtinTrigger (ccName n) TC.unit $
EC.lambda "_"
(EC.ifThenElse
(EC.applyMany (EC.variable $ chrName n) [EC.unit])
(controlE $ EC.applyMany (EC.variable $ cpName n) [EC.unit])
EC.unit)
sinkImpl =
EC.lambda "__msg"
(EC.ifThenElse
(EC.applyMany (EC.variable $ chwName n) [EC.unit])
(EC.applyMany (EC.variable $ cwName n) [EC.variable "__msg"])
(EC.unit))
-- External functions
cleanT = stripTUIDSpan t
sourceHasRead = ("HasRead", TC.unit, TC.bool, Nothing)
sourceRead = ("Read", TC.unit, cleanT, Nothing)
sinkHasWrite = ("HasWrite", TC.unit, TC.bool, Nothing)
sinkWrite = ("Write", cleanT, TC.unit, Nothing)
openEndpointE = case eSpec of
BuiltinEP _ _ -> EC.applyMany openBuiltinFn [sourceId n, argE, formatE]
FileEP _ _ -> openFnE openFileFn
NetworkEP _ _ -> openFnE openSocketFn
_ -> error "Invalid endpoint argument"
openFnE openFn = EC.applyMany openFn [sourceId n, argE, formatE, modeE]
modeE = EC.constant . CString $ if isSource then "r" else "w"
startE = case eSpec of
BuiltinEP _ _ -> fileStartE
FileEP _ _ -> fileStartE
NetworkEP _ _ -> EC.applyMany registerSocketDataTriggerFn [sourceId n, EC.variable $ ccName n]
_ -> error "Invalid endpoint argument"
fileStartE = EC.send (EC.variable (ccName n)) myAddr EC.unit
controlE processE = case eSpec of
BuiltinEP _ _ -> fileControlE processE
FileEP _ _ -> fileControlE processE
NetworkEP _ _ -> processE
_ -> error "Invalid endpoint argument"
fileControlE processE =
EC.block [processE, (EC.send (EC.variable $ ccName n) myAddr EC.unit)]
sourceId n' = EC.constant $ CString n'
-- | Rewrites a source declaration's process method to access and
-- dispatch the next available event to all its bindings.
bindSource :: [(Identifier, Identifier)] -> K3 Declaration -> (K3 Declaration, [K3 Declaration])
bindSource bindings d
| DGlobal src t eOpt <- tag d
, TSource <- tag t
= (d, [mkProcessFn src eOpt])
| otherwise = (d, [])
where
-- | Constructs a dispatch function declaration for a source.
mkProcessFn n eOpt =
builtinGlobal (cpName n) (qualifyT unitFnT) (Just . qualifyE $ body n eOpt)
body n eOpt = EC.lambda "_" $ EC.applyMany (processFnE n) [nextE n eOpt]
processFnE n = EC.lambda "next" $ EC.block $
map (\(_,dest) -> sendNextE dest) $ filter ((n ==) . fst) bindings
nextE _ (Just e) = stripEUIDSpan e
nextE n Nothing = EC.applyMany (EC.variable $ crName n) [EC.unit]
sendNextE dest = EC.send (EC.variable dest) myAddr (EC.variable "next")
unitFnT = TC.function TC.unit TC.unit
-- | Constructs an "atInit" expression for initializing and starting sources.
mkRunSourceE :: Identifier -> K3 Expression
mkRunSourceE n = EC.block [EC.applyMany (EC.variable $ ciName n) [EC.unit],
EC.applyMany (EC.variable $ csName n) [EC.unit]]
-- | Constructs an "atInit" expression for initializing sinks.
mkRunSinkE :: Identifier -> K3 Expression
mkRunSinkE n = EC.applyMany (EC.variable $ ciName n) [EC.unit]
-- TODO: at_exit function body
declareBuiltins :: K3 Declaration -> K3 Declaration
declareBuiltins d
| DRole n <- tag d, n == defaultRoleName = replaceCh d new_children
| otherwise = d
where new_children = runtimeDecls ++ peerDecls ++ (children d)
runtimeDecls = [
mkGlobal "registerFileDataTrigger" (mkCurriedFnT [idT, TC.trigger TC.unit, TC.unit]) Nothing,
mkGlobal "registerFileCloseTrigger" (mkCurriedFnT [idT, TC.trigger TC.unit, TC.unit]) Nothing,
mkGlobal "registerSocketAcceptTrigger" (mkCurriedFnT [idT, TC.trigger TC.unit, TC.unit]) Nothing,
mkGlobal "registerSocketDataTrigger" (mkCurriedFnT [idT, TC.trigger TC.unit, TC.unit]) Nothing,
mkGlobal "registerSocketCloseTrigger" (mkCurriedFnT [idT, TC.trigger TC.unit, TC.unit]) Nothing ]
peerDecls = [
mkGlobal myId TC.address Nothing,
mkGlobal peersId peersT Nothing,
mkGlobal argsId progArgT Nothing,
mkGlobal roleId TC.string Nothing]
idT = TC.string
progArgT = TC.tuple [qualifyT argT, qualifyT paramsT]
peersT = mkCollection [("addr", TC.address)]
argT = mkCollection [("arg", TC.string)]
paramsT = mkCollection [("key", TC.string), ("value", TC.string)]
mkGlobal n t eOpt = builtinGlobal n (qualifyT t) $ maybe Nothing (Just . qualifyE) eOpt
mkCurriedFnT tl = foldr1 TC.function tl
--mkAUnitFnT at = TC.function at TC.unit
--mkRUnitFnT rt = TC.function TC.unit rt
unitFnT = TC.function TC.unit TC.unit
mkCollection fields = (TC.collection $ TC.record $ map (qualifyT <$>) fields) @+ TAnnotation "Collection"
| yliu120/K3 | src/Language/K3/Parser/ProgramBuilder.hs | apache-2.0 | 11,059 | 0 | 16 | 2,473 | 3,368 | 1,780 | 1,588 | 203 | 12 |
module Main where
mapcolors = ["red", "green", "blue"]
mapcoloring = [(a, m, g, t, f) | a <- mapcolors, m <- mapcolors, g <- mapcolors, t <- mapcolors, f <- mapcolors, m /= t, m /= a, a /= t, a /= m, a /= g, a /= f, g /= f, g /= t] | frankiesardo/seven-languages-in-seven-weeks | src/main/haskell/day1/mapcoloring.hs | apache-2.0 | 240 | 0 | 7 | 63 | 145 | 79 | 66 | 3 | 1 |
{-| Node freeing scheduler
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Program.Hsqueeze
(main
, options
, arguments
) where
import Control.Applicative
import Control.Lens (over)
import Control.Monad
import Data.Function
import Data.List
import Data.Maybe
import qualified Data.IntMap as IntMap
import Text.Printf (printf)
import Ganeti.BasicTypes
import Ganeti.Common
import qualified Ganeti.HTools.AlgorithmParams as Alg
import Ganeti.HTools.CLI
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Cluster as Cluster
import qualified Ganeti.HTools.Cluster.Metrics as Metrics
import Ganeti.HTools.ExtLoader
import qualified Ganeti.HTools.Instance as Instance
import Ganeti.HTools.Loader
import qualified Ganeti.HTools.Node as Node
import Ganeti.HTools.Tags (hasStandbyTag, standbyAuto)
import Ganeti.HTools.Types
import Ganeti.JQueue (currentTimestamp, reasonTrailTimestamp)
import Ganeti.JQueue.Objects (Timestamp)
import qualified Ganeti.Jobs as Jobs
import Ganeti.OpCodes
import Ganeti.OpCodes.Lens (metaParamsL, opReasonL)
import Ganeti.Utils
import Ganeti.Version (version)
-- | Options list and functions.
options :: IO [OptType]
options = do
luxi <- oLuxiSocket
return
[ luxi
, oDataFile
, oExecJobs
, oMinResources
, oTargetResources
, oSaveCluster
, oPrintCommands
, oVerbose
, oNoHeaders
]
-- | The list of arguments supported by the program.
arguments :: [ArgCompletion]
arguments = []
-- | Wraps an 'OpCode' in a 'MetaOpCode' while also adding a comment
-- about what generated the opcode.
annotateOpCode :: Timestamp -> String -> Jobs.Annotator
annotateOpCode ts comment =
over (metaParamsL . opReasonL)
(++ [("hsqueeze"
, "hsqueeze " ++ version ++ " called"
, reasonTrailTimestamp ts
)])
. setOpComment (comment ++ " " ++ version)
. wrapOpCode
-- | Within a cluster configuration, decide if the node hosts only
-- externally-mirrored instances.
onlyExternal :: (Node.List, Instance.List) -> Node.Node -> Bool
onlyExternal (_, il) nd =
not
. any (Instance.usesLocalStorage . flip Container.find il)
$ Node.pList nd
-- | Predicate of not being secondary node for any instance
noSecondaries :: Node.Node -> Bool
noSecondaries = null . Node.sList
-- | Predicate whether, in a configuration, all running instances are on
-- online nodes.
allInstancesOnOnlineNodes :: (Node.List, Instance.List) -> Bool
allInstancesOnOnlineNodes (nl, il) =
all (not . Node.offline . flip Container.find nl . Instance.pNode)
. IntMap.elems
$ il
-- | Predicate whether, in a configuration, each node has enough resources
-- to additionally host the given instance.
allNodesCapacityFor :: Instance.Instance -> (Node.List, Instance.List) -> Bool
allNodesCapacityFor inst (nl, _) =
all (isOk . flip Node.addPri inst) . IntMap.elems $ nl
-- | Balance a configuration, possible for 0 steps, till no further improvement
-- is possible.
balance :: (Node.List, Instance.List)
-> ((Node.List, Instance.List), [MoveJob])
balance (nl, il) =
let ini_cv = Metrics.compCV nl
ini_tbl = Cluster.Table nl il ini_cv []
balanceStep = Cluster.tryBalance
(Alg.defaultOptions { Alg.algMinGain = 0.0
, Alg.algMinGainLimit = 0.0})
bTables = map fromJust . takeWhile isJust
$ iterate (>>= balanceStep) (Just ini_tbl)
(Cluster.Table nl' il' _ _) = last bTables
moves = zip bTables (drop 1 bTables) >>= Cluster.getMoves
in ((nl', il'), reverse moves)
-- | In a configuration, mark a node as online or offline.
onlineOfflineNode :: Bool -> (Node.List, Instance.List) -> Ndx ->
(Node.List, Instance.List)
onlineOfflineNode offline (nl, il) ndx =
let nd = Container.find ndx nl
nd' = Node.setOffline nd offline
nl' = Container.add ndx nd' nl
in (nl', il)
-- | Offline or online a list nodes, and return the state after a balancing
-- attempt together with the sequence of moves that lead there.
onlineOfflineNodes :: Bool -> [Ndx] -> (Node.List, Instance.List)
-> ((Node.List, Instance.List), [MoveJob])
onlineOfflineNodes offline ndxs conf =
let conf' = foldl (onlineOfflineNode offline) conf ndxs
in balance conf'
-- | Offline a list of nodes, and return the state after balancing with
-- the sequence of moves that lead there.
offlineNodes :: [Ndx] -> (Node.List, Instance.List)
-> ((Node.List, Instance.List), [MoveJob])
offlineNodes = onlineOfflineNodes True
-- | Online a list of nodes, and return the state after balancing with
-- the sequence of moves that lead there.
onlineNodes :: [Ndx] -> (Node.List, Instance.List)
-> ((Node.List, Instance.List), [MoveJob])
onlineNodes = onlineOfflineNodes False
-- | Predicate on whether a list of nodes can be offlined or onlined
-- simultaneously in a given configuration, while still leaving enough
-- capacity on every node for the given instance.
canOnlineOffline :: Bool -> Instance.Instance -> (Node.List, Instance.List)
-> [Node.Node] ->Bool
canOnlineOffline offline inst conf nds =
let conf' = fst $ onlineOfflineNodes offline (map Node.idx nds) conf
in allInstancesOnOnlineNodes conf' && allNodesCapacityFor inst conf'
-- | Predicate on whether a list of nodes can be offlined simultaneously.
canOffline :: Instance.Instance -> (Node.List, Instance.List) ->
[Node.Node] -> Bool
canOffline = canOnlineOffline True
-- | Predicate on whether onlining a list of nodes suffices to get enough
-- free resources for given instance.
sufficesOnline :: Instance.Instance -> (Node.List, Instance.List)
-> [Node.Node] -> Bool
sufficesOnline = canOnlineOffline False
-- | Greedily offline the nodes, starting from the last element, and return
-- the list of nodes that could simultaneously be offlined, while keeping
-- the resources specified by an instance.
greedyOfflineNodes :: Instance.Instance -> (Node.List, Instance.List)
-> [Node.Node] -> [Node.Node]
greedyOfflineNodes _ _ [] = []
greedyOfflineNodes inst conf (nd:nds) =
let nds' = greedyOfflineNodes inst conf nds
in if canOffline inst conf (nd:nds') then nd:nds' else nds'
-- | Try to provide enough resources by onlining an initial segment of
-- a list of nodes. Return Nothing, if even onlining all of them is not
-- enough.
tryOnline :: Instance.Instance -> (Node.List, Instance.List) -> [Node.Node]
-> Maybe [Node.Node]
tryOnline inst conf = listToMaybe . filter (sufficesOnline inst conf) . inits
-- | From a specification, name, and factor create an instance that uses that
-- factor times the specification, rounded down.
instanceFromSpecAndFactor :: String -> Double -> ISpec -> Instance.Instance
instanceFromSpecAndFactor name f spec =
Instance.create name
(floor (f * fromIntegral (iSpecMemorySize spec)))
0 []
(floor (f * fromIntegral (iSpecCpuCount spec)))
Running [] False Node.noSecondary Node.noSecondary DTExt
(floor (f * fromIntegral (iSpecSpindleUse spec)))
[]
False
-- | Get opcodes for the given move job.
getMoveOpCodes :: Node.List
-> Instance.List
-> [JobSet]
-> Result [([[OpCode]], String)]
getMoveOpCodes nl il js = return $ zip (map opcodes js) (map descr js)
where opcodes = map (\(_, idx, move, _) ->
Cluster.iMoveToJob nl il idx move)
descr job = "Moving instances " ++ commaJoin
(map (\(_, idx, _, _) -> Container.nameOf il idx) job)
-- | Get opcodes for tagging nodes with standby.
getTagOpCodes :: [Node.Node] -> Result [([[OpCode]], String)]
getTagOpCodes nl = return $ zip (map opCode nl) (map descr nl)
where
opCode node = [[Node.genAddTagsOpCode node [standbyAuto]]]
descr node = "Tagging node " ++ Node.name node ++ " with standby"
-- | Get opcodes for powering off nodes
getPowerOffOpCodes :: [Node.Node] -> Result [([[OpCode]], String)]
getPowerOffOpCodes nl = do
opcodes <- Node.genPowerOffOpCodes nl
return [([opcodes], "Powering off nodes")]
-- | Get opcodes for powering on nodes
getPowerOnOpCodes :: [Node.Node] -> Result [([[OpCode]], String)]
getPowerOnOpCodes nl = do
opcodes <- Node.genPowerOnOpCodes nl
return [([opcodes], "Powering on nodes")]
maybeExecJobs :: Options
-> String
-> Result [([[OpCode]], String)]
-> IO (Result ())
maybeExecJobs opts comment opcodes =
if optExecJobs opts
then (case optLuxi opts of
Nothing ->
return $ Bad "Execution of commands possible only on LUXI"
Just master -> do
ts <- currentTimestamp
let annotator = maybe id setOpPriority (optPriority opts) .
annotateOpCode ts comment
case opcodes of
Bad msg -> error msg
Ok codes -> Jobs.execWithCancel annotator master codes)
else return $ Ok ()
-- | Main function.
main :: Options -> [String] -> IO ()
main opts args = do
unless (null args) $ exitErr "This program doesn't take any arguments."
let verbose = optVerbose opts
targetf = optTargetResources opts
minf = optMinResources opts
ini_cdata@(ClusterData _ nlf ilf _ ipol) <- loadExternalData opts
maybeSaveData (optSaveCluster opts) "original" "before hsqueeze run" ini_cdata
let nodelist = IntMap.elems nlf
offlineCandidates =
sortBy (flip compare `on` length . Node.pList)
. filter (foldl (liftA2 (&&)) (const True)
[ not . Node.offline
, not . Node.isMaster
, noSecondaries
, onlyExternal (nlf, ilf)
])
$ nodelist
onlineCandidates =
filter (liftA2 (&&) Node.offline hasStandbyTag) nodelist
conf = (nlf, ilf)
std = iPolicyStdSpec ipol
targetInstance = instanceFromSpecAndFactor "targetInstance" targetf std
minInstance = instanceFromSpecAndFactor "targetInstance" minf std
toOffline = greedyOfflineNodes targetInstance conf offlineCandidates
((fin_off_nl, fin_off_il), off_mvs) =
offlineNodes (map Node.idx toOffline) conf
final_off_cdata =
ini_cdata { cdNodes = fin_off_nl, cdInstances = fin_off_il }
off_jobs = Cluster.splitJobs off_mvs
off_opcodes = liftM concat $ sequence
[ getMoveOpCodes nlf ilf off_jobs
, getTagOpCodes toOffline
, getPowerOffOpCodes toOffline
]
off_cmd =
Cluster.formatCmds off_jobs
++ "\necho Tagging Commands\n"
++ (toOffline >>= (printf " gnt-node add-tags %s %s\n"
`flip` standbyAuto)
. Node.alias)
++ "\necho Power Commands\n"
++ (toOffline >>= printf " gnt-node power -f off %s\n" . Node.alias)
toOnline = tryOnline minInstance conf onlineCandidates
nodesToOnline = fromMaybe onlineCandidates toOnline
((fin_on_nl, fin_on_il), on_mvs) =
onlineNodes (map Node.idx nodesToOnline) conf
final_on_cdata =
ini_cdata { cdNodes = fin_on_nl, cdInstances = fin_on_il }
on_jobs = Cluster.splitJobs on_mvs
on_opcodes = liftM2 (++) (getPowerOnOpCodes nodesToOnline)
(getMoveOpCodes nlf ilf on_jobs)
on_cmd =
"echo Power Commands\n"
++ (nodesToOnline >>= printf " gnt-node power -f on %s\n" . Node.alias)
++ Cluster.formatCmds on_jobs
when (verbose > 1) . putStrLn
$ "Offline candidates: " ++ commaJoin (map Node.name offlineCandidates)
when (verbose > 1) . putStrLn
$ "Online candidates: " ++ commaJoin (map Node.name onlineCandidates)
if not (allNodesCapacityFor minInstance conf)
then do
unless (optNoHeaders opts) $
putStrLn "'Nodes to online'"
mapM_ (putStrLn . Node.name) nodesToOnline
when (verbose > 1 && isNothing toOnline) . putStrLn $
"Onlining all nodes will not yield enough capacity"
maybeSaveCommands "Commands to run:" opts on_cmd
let comment = printf "expanding by %d nodes" (length nodesToOnline)
exitIfBad "hsqueeze" =<< maybeExecJobs opts comment on_opcodes
maybeSaveData (optSaveCluster opts)
"squeezed" "after hsqueeze expansion" final_on_cdata
else
if null toOffline
then do
unless (optNoHeaders opts) $
putStrLn "'No action'"
maybeSaveCommands "Commands to run:" opts "echo Nothing to do"
maybeSaveData (optSaveCluster opts)
"squeezed" "after hsqueeze doing nothing" ini_cdata
else do
unless (optNoHeaders opts) $
putStrLn "'Nodes to offline'"
mapM_ (putStrLn . Node.name) toOffline
maybeSaveCommands "Commands to run:" opts off_cmd
let comment = printf "condensing by %d nodes" (length toOffline)
exitIfBad "hsqueeze" =<< maybeExecJobs opts comment off_opcodes
maybeSaveData (optSaveCluster opts)
"squeezed" "after hsqueeze run" final_off_cdata
| dimara/ganeti | src/Ganeti/HTools/Program/Hsqueeze.hs | bsd-2-clause | 14,540 | 0 | 18 | 3,422 | 3,312 | 1,770 | 1,542 | -1 | -1 |
module PregenKeys where
import qualified Crypto.PubKey.RSA as RSA
import qualified Crypto.PubKey.DSA as DSA
import qualified Crypto.PubKey.DH as DH
import qualified Crypto.PubKey.ECC.ECDSA as ECDSA
import qualified Crypto.Types.PubKey.ECC as ECC
rsaPrivatekey = RSA.PrivateKey
{ RSA.private_pub = rsaPublickey
, RSA.private_d = 133764127300370985476360382258931504810339098611363623122953018301285450176037234703101635770582297431466449863745848961134143024057267778947569638425565153896020107107895924597628599677345887446144410702679470631826418774397895304952287674790343620803686034122942606764275835668353720152078674967983573326257
, RSA.private_p = 12909745499610419492560645699977670082358944785082915010582495768046269235061708286800087976003942261296869875915181420265794156699308840835123749375331319
, RSA.private_q = 10860278066550210927914375228722265675263011756304443428318337179619069537063135098400347475029673115805419186390580990519363257108008103841271008948795129
, RSA.private_dP = 5014229697614831746694710412330921341325464081424013940131184365711243776469716106024020620858146547161326009604054855316321928968077674343623831428796843
, RSA.private_dQ = 3095337504083058271243917403868092841421453478127022884745383831699720766632624326762288333095492075165622853999872779070009098364595318242383709601515849
, RSA.private_qinv = 11136639099661288633118187183300604127717437440459572124866697429021958115062007251843236337586667012492941414990095176435990146486852255802952814505784196
}
rsaPublickey = RSA.PublicKey
{ RSA.public_size = 128
, RSA.public_n = 140203425894164333410594309212077886844966070748523642084363106504571537866632850620326769291612455847330220940078873180639537021888802572151020701352955762744921926221566899281852945861389488419179600933178716009889963150132778947506523961974222282461654256451508762805133855866018054403911588630700228345151
, RSA.public_e = 65537
}
dsaParams = DSA.Params { DSA.params_p = p, DSA.params_g = g, DSA.params_q = q }
where
p = 0x00a8c44d7d0bbce69a39008948604b9c7b11951993a5a1a1fa995968da8bb27ad9101c5184bcde7c14fb79f7562a45791c3d80396cefb328e3e291932a17e22edd
g = 0x0bf9fe6c75d2367b88912b2252d20fdcad06b3f3a234b92863a1e30a96a123afd8e8a4b1dd953e6f5583ef8e48fc7f47a6a1c8f24184c76dba577f0fec2fcd1c
q = 0x0096674b70ef58beaaab6743d6af16bb862d18d119
dsaPrivatekey = DSA.PrivateKey
{ DSA.private_params = dsaParams
, DSA.private_x = 0x229bac7aa1c7db8121bfc050a3426eceae23fae8
}
dsaPublickey = DSA.PublicKey
{ DSA.public_params = dsaParams
, DSA.public_y = 0x4fa505e86e32922f1fa1702a120abdba088bb4be801d4c44f7fc6b9094d85cd52c429cbc2b39514e30909b31e2e2e0752b0fc05c1a7d9c05c3e52e49e6edef4c
}
ecdsaCurveP = ECC.getCurveByName ECC.SEC_p160r1
ecdsaPrivatekeyP = ECDSA.PrivateKey ecdsaCurveP 971761939728640320549601132085879836204587084162
ecdsaPublickeyP = ECDSA.PublicKey
ecdsaCurveP
(ECC.Point 466448783855397898016055842232266600516272889280
1110706324081757720403272427311003102474457754220)
ecdsaCurveB = ECC.getCurveByName ECC.SEC_t163k1
ecdsaPrivatekeyB = ECDSA.PrivateKey ecdsaCurveB 5321230001203043918714616464614664646674949479949
ecdsaPublickeyB = ECDSA.PublicKey
ecdsaCurveB
(ECC.Point 0x37d529fa37e42195f10111127ffb2bb38644806bc
0x447026eee8b34157f3eb51be5185d2be0249ed776)
| vincenthz/hs-crypto-pubkey | Benchs/PregenKeys.hs | bsd-2-clause | 3,444 | 0 | 8 | 343 | 341 | 206 | 135 | 40 | 1 |
------------------------------------------------------------------------
-- |
-- Module : WaiMiddlewareThrottleSpec
-- Description : WAI Request Throttling Middleware
-- Copyright : (c) 2015 Christopher Reichert
-- License : BSD3
-- Maintainer : Christopher Reichert <creichert07@gmail.com>
-- Stability : unstable
-- Portability : POSIX
--
{-# LANGUAGE OverloadedStrings #-}
module WaiMiddlewareThrottleSpec (
spec
) where
import Control.Monad.IO.Class
import Network.HTTP.Types
import Network.HTTP.Types.Status
import Network.Wai
import Network.Wai.Test
import Test.Hspec
import Test.HUnit hiding (Test)
import Network.Wai.Middleware.Throttle
spec :: Spec
spec = describe "Network.Wai.Middleware.Throttle" $
it "throttles requests" caseThrottle
-- | Simple Hmac Middleware App
--
-- This app has preloaded api keys to simulate
-- some database or service which can access the
-- private keys.
throttleApp :: WaiThrottle -> Application
throttleApp st = throttle defaultThrottleSettings st
$ \_ f -> f response
where
payload = "{ \"api\", \"return data\" }"
response = responseLBS status200 [] payload
defReq :: Request
defReq = defaultRequest
{ requestMethod = "GET"
, requestHeaders = [ ("Content-Type", "application/json") ]
}
-- | Test Hmac Authentication
caseThrottle :: Assertion
caseThrottle = do
st <- liftIO initThrottler
statuses <- flip runSession (throttleApp st) $ do
responses <- mapM (const (request defReq)) [ 1 .. 100 :: Integer ]
mapM (return . simpleStatus) responses
let msg = "Verifying some of the requests were throttled"
assertBool msg $ elem status429 statuses
| circuithub/wai-middleware-throttle | test/WaiMiddlewareThrottleSpec.hs | bsd-3-clause | 1,810 | 0 | 16 | 438 | 306 | 174 | 132 | 31 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
PatternGuards #-}
module Core.Typecheck where
import Control.Monad.State
import Debug.Trace
import qualified Data.Vector.Unboxed as V (length)
import Core.TT
import Core.Evaluate
-- To check conversion, normalise each term wrt the current environment.
-- Since we haven't converted everything to de Bruijn indices yet, we'll have to
-- deal with alpha conversion - we do this by making each inner term de Bruijn
-- indexed with 'finalise'
convertsC :: Context -> Env -> Term -> Term -> StateT UCs TC ()
convertsC ctxt env x y
= do c1 <- convEq ctxt x y
if c1 then return ()
else
do c2 <- convEq ctxt (finalise (normalise ctxt env x))
(finalise (normalise ctxt env y))
if c2 then return ()
else lift $ tfail (CantConvert
(finalise (normalise ctxt env x))
(finalise (normalise ctxt env y)) (errEnv env))
converts :: Context -> Env -> Term -> Term -> TC ()
converts ctxt env x y
= case convEq' ctxt x y of
OK True -> return ()
_ -> case convEq' ctxt (finalise (normalise ctxt env x))
(finalise (normalise ctxt env y)) of
OK True -> return ()
_ -> tfail (CantConvert
(finalise (normalise ctxt env x))
(finalise (normalise ctxt env y)) (errEnv env))
errEnv = map (\(x, b) -> (x, binderTy b))
isType :: Context -> Env -> Term -> TC ()
isType ctxt env tm = isType' (normalise ctxt env tm)
where isType' (TType _) = return ()
isType' tm = fail (showEnv env tm ++ " is not a TType")
recheck :: Context -> Env -> Raw -> Term -> TC (Term, Type, UCs)
recheck ctxt env tm orig
= let v = next_tvar ctxt in
case runStateT (check' False ctxt env tm) (v, []) of -- holes banned
Error (IncompleteTerm _) -> Error $ IncompleteTerm orig
Error e -> Error e
OK ((tm, ty), constraints) ->
return (tm, ty, constraints)
check :: Context -> Env -> Raw -> TC (Term, Type)
check ctxt env tm = evalStateT (check' True ctxt env tm) (0, []) -- Holes allowed
check' :: Bool -> Context -> Env -> Raw -> StateT UCs TC (Term, Type)
check' holes ctxt env top = chk env top where
chk env (Var n)
| Just (i, ty) <- lookupTyEnv n env = return (P Bound n ty, ty)
| (P nt n' ty : _) <- lookupP n ctxt = return (P nt n' ty, ty)
| otherwise = do lift $ tfail $ NoSuchVariable n
chk env (RApp f a)
= do (fv, fty) <- chk env f
(av, aty) <- chk env a
let fty' = case uniqueBinders (map fst env) (finalise fty) of
ty@(Bind x (Pi s) t) -> ty
_ -> uniqueBinders (map fst env)
$ case hnf ctxt env fty of
ty@(Bind x (Pi s) t) -> ty
_ -> normalise ctxt env fty
case fty' of
Bind x (Pi s) t ->
-- trace ("Converting " ++ show aty ++ " and " ++ show s ++
-- " from " ++ show fv ++ " : " ++ show fty) $
do convertsC ctxt env aty s
-- let apty = normalise initContext env
-- (Bind x (Let aty av) t)
let apty = simplify initContext env
(Bind x (Let aty av) t)
return (App fv av, apty)
t -> lift $ tfail $ NonFunctionType fv fty -- "Can't apply a non-function type"
-- This rather unpleasant hack is needed because during incomplete
-- proofs, variables are locally bound with an explicit name. If we just
-- make sure bound names in function types are locally unique, machine
-- generated names, we'll be fine.
-- NOTE: now replaced with 'uniqueBinders' above
where renameBinders i (Bind x (Pi s) t) = Bind (MN i "binder") (Pi s)
(renameBinders (i+1) t)
renameBinders i sc = sc
chk env RType
| holes = return (TType (UVal 0), TType (UVal 0))
| otherwise = do (v, cs) <- get
let c = ULT (UVar v) (UVar (v+1))
put (v+2, (c:cs))
return (TType (UVar v), TType (UVar (v+1)))
chk env (RConstant Forgot) = return (Erased, Erased)
chk env (RConstant c) = return (Constant c, constType c)
where constType (I _) = Constant (AType (ATInt ITNative))
constType (BI _) = Constant (AType (ATInt ITBig))
constType (Fl _) = Constant (AType ATFloat)
constType (Ch _) = Constant (AType (ATInt ITChar))
constType (Str _) = Constant StrType
constType (B8 _) = Constant (AType (ATInt (ITFixed IT8)))
constType (B16 _) = Constant (AType (ATInt (ITFixed IT16)))
constType (B32 _) = Constant (AType (ATInt (ITFixed IT32)))
constType (B64 _) = Constant (AType (ATInt (ITFixed IT64)))
constType (B8V a) = Constant (AType (ATInt (ITVec IT8 (V.length a))))
constType (B16V a) = Constant (AType (ATInt (ITVec IT16 (V.length a))))
constType (B32V a) = Constant (AType (ATInt (ITVec IT32 (V.length a))))
constType (B64V a) = Constant (AType (ATInt (ITVec IT64 (V.length a))))
constType Forgot = Erased
constType _ = TType (UVal 0)
chk env (RForce t) = do (_, ty) <- chk env t
return (Erased, ty)
chk env (RBind n (Pi s) t)
= do (sv, st) <- chk env s
(tv, tt) <- chk ((n, Pi sv) : env) t
(v, cs) <- get
let TType su = normalise ctxt env st
let TType tu = normalise ctxt env tt
when (not holes) $ put (v+1, ULE su (UVar v):ULE tu (UVar v):cs)
return (Bind n (Pi (uniqueBinders (map fst env) sv))
(pToV n tv), TType (UVar v))
chk env (RBind n b sc)
= do b' <- checkBinder b
(scv, sct) <- chk ((n, b'):env) sc
discharge n b' (pToV n scv) (pToV n sct)
where checkBinder (Lam t)
= do (tv, tt) <- chk env t
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
lift $ isType ctxt env tt'
return (Lam tv)
checkBinder (Pi t)
= do (tv, tt) <- chk env t
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
lift $ isType ctxt env tt'
return (Pi tv)
checkBinder (Let t v)
= do (tv, tt) <- chk env t
(vv, vt) <- chk env v
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
convertsC ctxt env vt tv
lift $ isType ctxt env tt'
return (Let tv vv)
checkBinder (NLet t v)
= do (tv, tt) <- chk env t
(vv, vt) <- chk env v
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
convertsC ctxt env vt tv
lift $ isType ctxt env tt'
return (NLet tv vv)
checkBinder (Hole t)
| not holes = lift $ tfail (IncompleteTerm undefined)
| otherwise
= do (tv, tt) <- chk env t
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
lift $ isType ctxt env tt'
return (Hole tv)
checkBinder (GHole t)
= do (tv, tt) <- chk env t
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
lift $ isType ctxt env tt'
return (GHole tv)
checkBinder (Guess t v)
| not holes = lift $ tfail (IncompleteTerm undefined)
| otherwise
= do (tv, tt) <- chk env t
(vv, vt) <- chk env v
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
convertsC ctxt env vt tv
lift $ isType ctxt env tt'
return (Guess tv vv)
checkBinder (PVar t)
= do (tv, tt) <- chk env t
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
lift $ isType ctxt env tt'
return (PVar tv)
checkBinder (PVTy t)
= do (tv, tt) <- chk env t
let tv' = normalise ctxt env tv
let tt' = normalise ctxt env tt
lift $ isType ctxt env tt'
return (PVTy tv)
discharge n (Lam t) scv sct
= return (Bind n (Lam t) scv, Bind n (Pi t) sct)
discharge n (Pi t) scv sct
= return (Bind n (Pi t) scv, sct)
discharge n (Let t v) scv sct
= return (Bind n (Let t v) scv, Bind n (Let t v) sct)
discharge n (NLet t v) scv sct
= return (Bind n (NLet t v) scv, Bind n (Let t v) sct)
discharge n (Hole t) scv sct
= return (Bind n (Hole t) scv, sct)
discharge n (GHole t) scv sct
= return (Bind n (GHole t) scv, sct)
discharge n (Guess t v) scv sct
= return (Bind n (Guess t v) scv, sct)
discharge n (PVar t) scv sct
= return (Bind n (PVar t) scv, Bind n (PVTy t) sct)
discharge n (PVTy t) scv sct
= return (Bind n (PVTy t) scv, sct)
checkProgram :: Context -> RProgram -> TC Context
checkProgram ctxt [] = return ctxt
checkProgram ctxt ((n, RConst t) : xs)
= do (t', tt') <- trace (show n) $ check ctxt [] t
isType ctxt [] tt'
checkProgram (addTyDecl n Ref t' ctxt) xs
checkProgram ctxt ((n, RFunction (RawFun ty val)) : xs)
= do (ty', tyt') <- trace (show n) $ check ctxt [] ty
(val', valt') <- check ctxt [] val
isType ctxt [] tyt'
converts ctxt [] ty' valt'
checkProgram (addToCtxt n val' ty' ctxt) xs
checkProgram ctxt ((n, RData (RDatatype _ ty cons)) : xs)
= do (ty', tyt') <- trace (show n) $ check ctxt [] ty
isType ctxt [] tyt'
-- add the tycon temporarily so we can check constructors
let ctxt' = addDatatype (Data n 0 ty' []) ctxt
cons' <- mapM (checkCon ctxt') cons
checkProgram (addDatatype (Data n 0 ty' cons') ctxt) xs
where checkCon ctxt (n, cty) = do (cty', ctyt') <- check ctxt [] cty
return (n, cty')
| christiaanb/Idris-dev | src/Core/Typecheck.hs | bsd-3-clause | 10,860 | 26 | 24 | 4,321 | 3,480 | 1,788 | 1,692 | 208 | 42 |
-- http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_C
-- Spreadsheet
-- input:
-- 4 5
-- 1 1 3 4 5
-- 2 2 2 4 5
-- 3 3 0 1 1
-- 2 3 4 4 6
-- output:
-- 1 1 3 4 5 14
-- 2 2 2 4 5 15
-- 3 3 0 1 1 8
-- 2 3 4 4 6 19
-- 8 9 9 13 17 56
import Control.Applicative ((<$>))
import qualified Control.Monad as Monad (forM, replicateM)
type Row = [Int]
type Spreadsheet = [Row]
main = do
[r,c] <- getLine'
xs <- Monad.replicateM r $ getLine'
mapM_ (putStrLn . printFormat) =<< newSpreadsheet (c+1) xs
getLine' :: IO [Int]
getLine' = map read . words <$> getLine
printFormat :: Row -> String
printFormat xs = unwords $ show <$> xs
newSpreadsheet :: Int -> Spreadsheet -> IO Spreadsheet
newSpreadsheet n xs = do
let xs' = zipWith (++) xs $ rowSums xs
return $ xs' ++ columnSums n xs'
rowSums :: Spreadsheet -> Spreadsheet
rowSums = map $ (:[]) . sum
columnSums :: (Monad m) =>Int -> Spreadsheet -> m Row
columnSums n xs = Monad.forM [0..(n-1)] $ \i -> return $ sum $ map (!! i) xs
| ku00/aoj-haskell | src/ITP1_7_C.hs | bsd-3-clause | 1,012 | 0 | 11 | 231 | 347 | 191 | 156 | 20 | 1 |
module Network.Checksum (inChecksum) where
import Data.Bits (complement, shiftL, shiftR, (.|.), (.&.))
import Data.Word (Word8, Word16, Word32)
inChecksum :: [Word8] -> Word16
inChecksum ws = fromIntegral . complement . twice addHi16ToLow16 $ ws'
where
ws' = sum . map fromIntegral . packWord16 $ ws
packWord16 :: [Word8] -> [Word16]
packWord16 [] = []
packWord16 [w0] = packWord16 [w0,0]
packWord16 (w0:w1:ws) = word8ToWord16 w0 w1 : packWord16 ws
word8ToWord16 :: Word8 -> Word8 -> Word16
word8ToWord16 high low = high' .|. low'
where
high' = (fromIntegral high) `shiftL` 8
low' = fromIntegral low
addHi16ToLow16 :: Word32 -> Word32
addHi16ToLow16 n = (n `shiftR` 16) + (n .&. 0xffff)
twice :: (a -> a) -> a -> a
twice f a = f (f a)
| ymmtmsys/checksum | Network/Checksum.hs | bsd-3-clause | 773 | 0 | 10 | 160 | 318 | 175 | 143 | 18 | 1 |
module Text.New.NumberToText
(
numberToText,
digitToText,
numberToEnglish,
digitToEnglish
) where
import Data.List.Split
import Data.Char
import qualified Data.List.Split.Internals as SI
import Data.String.Utils
-- | useless later
-- | given an Integer n, show its words in English
-- | it works for minus numbers
numberToText :: Integer -> String
numberToText n
| n < 0 = "minus " ++ numberToText (-n)
| t == 1 = toText1 n
| t == 2 = toText2 n
| t == 3 = toText3 n
| n > (10^3006) = fail "too long number"
| otherwise = toText (toTriples t) n
where t = bitWidth n
-- | useless later
-- | number of digits
bitWidth n = length $ show n
-- | one digit number
toText1 n
| n == 0 = "zero"
| n == 1 = "one"
| n == 2 = "two"
| n == 3 = "three"
| n == 4 = "four"
| n == 5 = "five"
| n == 6 = "six"
| n == 7 = "seven"
| n == 8 = "eight"
| n == 9 = "nine"
-- | two digit number
toText2 n
| n < 10 = toText1 n
| n == 10 = "ten"
| n == 11 = "eleven"
| n == 12 = "twelve"
| n == 13 = "thirteen"
| n == 14 = "fourteen"
| n == 15 = "fifteen"
| n == 16 = "sixteen"
| n == 17 = "seventeen"
| n == 18 = "eighteen"
| n == 19 = "nighteen"
| n == 20 = "twenty"
| n == 30 = "thirty"
| n == 40 = "forty"
| n == 50 = "fifty"
| n == 60 = "sixty"
| n == 70 = "seventy"
| n == 80 = "eighty"
| n == 90 = "ninety"
| otherwise = toText2 (n - (mod n 10)) ++ "-" ++ toText1 (mod n 10)
-- | three digit number
toText3 n
| n < 100 = toText2 n
| mod n 100 == 0 = toText1 (div n 100) ++ " hundred"
| otherwise = toText3 (n - (mod n 100)) ++ " and " ++ toText2 (mod n 100)
-- | useless later
toText bit n
| bit == 3 = toText3 n
| n < 10^(bit - 3) = toText (bit - 3) n
| (mod n $ 10^(bit - 3)) == 0 = toText 3 (div n $ 10^(bit - 3)) ++ " " ++ numText (bit - 3)
| otherwise = toText bit (n - (mod n $ 10^(bit - 3))) ++ ", " ++ toText (bit - 3) (mod n $ 10^(bit - 3))
-- | useless later
numText bit
| t == 0 = "thousand"
| t == 1 = "million"
| t == 2 = "billion"
| t == 3 = "trillion"
| t == 4 = "quadrillion"
| t == 5 = "quintillion"
| t == 6 = "sextillion"
| t == 7 = "septillion"
| t == 8 = "octillion"
| t == 9 = "nonillion"
| t == 1000 = "milliatillion"
| t > 1000 = fail "too large number"
| otherwise = afix !! a ++ cfix !! c ++ bfix !! b ++ xfix !! c
where t = quot (bit - 3) 3
-- | a of 134 == 1
a = div t 100
-- | c of 134 == 4
c = mod t 10
-- | b of 134 == 3
b = mod (div t 10) 10
afix = ["", "cen", "duocen", "trecen", "quadringen", "quingen", "sescen", "septingen", "octingen", "nongen"]
cfix = ["", "un", "duo", "tre", "quattuor", "quin", "sex", "septen", "octo", "novem"]
bfix = ["", "dec", "vigin", "trigin", "quadragin", "quinquagin", "sexagin", "septuagin", "octogin", "nonagin"]
xfix = ["", "illion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion"]
-- | useless later
-- | toTriples 5 = 6
-- | toTriples 6 = 6
toTriples n
| mod n 3 == 0 = n
| otherwise = n + 3 - (mod n 3)
------------------------------------------------------------
------------------------------------------------------------
-- | given a float number, show its words in English
-- | also works for minus float
digitToText :: String -> String
digitToText d
| head d == '-' = "minus " ++ digitToText (tail d)
| not $ elem '.' d = numberToText a
| otherwise = numberToText a ++ " point " ++ digitsText b
where a = read (head $ splitOn "." d) :: Integer
b = last $ splitOn "." d
-- | given a string with all digits, output a string
digitsText :: String -> String
digitsText b = putTogether s
where s = map (numberToText . toInteger . (\x -> x-48) . ord) b
-- | put together all the words separated with a space
putTogether :: [String] -> String
putTogether [] = []
putTogether [x] = x
putTogether (x:xs) = x ++ " " ++ putTogether xs
------------------------------------------------------------
------------------------------------------------------------
numberToEnglish :: String -> String
numberToEnglish word = replace ", zero" "" $ numberToEnglish1 word
numberToEnglish1 :: String -> String
numberToEnglish1 word
| head word == '-' = "minus " ++ numberToEnglish1 (tail word)
| length word1 == 0 = "zero"
| length word1 <= 3 = toText3 $ readInt1 word1
| otherwise = helper1 n (head words) ++ numberToEnglish1 (concat $ tail words)
where words = splitWord word1
word1 = dropWhile (=='0') word
n = length words - 1
helper1 n w
| w == "000" = ""
| otherwise = toText3 (readInt1 w) ++ " " ++ thousandEnglish n ++ ", "
splitWord :: String -> [String]
splitWord word = map reverse $ reverse $ (SI.chunksOf 3) $ reverse word
-- | ["123", "456"] to Integer [123, 456]
readInt1 :: String -> Int
readInt1 s = read s
-- | ["123", "456"] to Integer [123, 456]
readInts :: [String] -> [Int]
readInts s = map read s
thousandEnglish t
| t <= 1000 = thousandEnglish1 t
| t > 1000 = thousandEnglish2 t
thousandEnglish1 t
| t == 0 = ""
| t == 1 = "thousand"
| t == 2 = "million"
| t == 3 = "billion"
| t == 4 = "trillion"
| t == 5 = "quadrillion"
| t == 6 = "quintillion"
| t == 7 = "sextillion"
| t == 8 = "septillion"
| t == 9 = "octillion"
| t == 10 = "nonillion"
| t == 1000 = "milliatillion"
| t < 100 = afix !! a ++ cfix !! c ++ bfix !! b ++ xfix !! b
| otherwise = afix !! a ++ cfix !! c ++ bfix !! b ++ xfix1 !! b
where
-- | a of 134 == 1
a = div t 100
-- | c of 134 == 4
c = mod t 10
-- | b of 134 == 3
b = mod (div t 10) 10
afix = ["", "cen", "duocen", "trecen", "quadringen", "quingen", "sescen", "septingen", "octingen", "nongen"]
cfix = ["", "un", "duo", "tre", "quattuor", "quin", "sex", "septen", "octo", "novem"]
bfix = ["", "dec", "vigin", "trigin", "quadragin", "quinquagin", "sexagin", "septuagin", "octogin", "nonagin"]
xfix = ["", "illion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion"]
xfix1 = ["tillion", "illion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion"]
thousandEnglish2 t = (concat $ zipWith helper2 aa indexes) ++ "tillion"
where aa = zipWith (-) (repeat kk) [0..kk]
kk = length indexes - 1
indexes = readInts $ splitWord $ show t
-- | k times "millia", n < 1000
helper2 k n = afix !! a ++ cfix !! c ++ bfix !! b ++ rep k
where
-- | a of 134 == 1
a = div n 100
-- | c of 134 == 4
c = mod n 10
-- | b of 134 == 3
b = mod (div n 10) 10
afix = ["", "cen", "duocen", "trecen", "quadringen", "quingen", "sescen", "septingen", "octingen", "nongen"]
cfix = ["", "un", "duo", "tre", "quattuor", "quin", "sex", "septen", "octo", "novem"]
bfix = ["", "dec", "vigin", "trigin", "quadragin", "quinquagin", "sexagin", "septuagin", "octogin", "nonagin"]
--xfix = ["", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion", "tillion"]
thou = "millia"
rep t = concat $ replicate t thou
-- | given a float String, show its words in English
-- | also works for minus float String
digitToEnglish :: String -> String
digitToEnglish d
| head d == '-' = "minus " ++ digitToText (tail d)
| not $ elem '.' d = numberToEnglish a
| otherwise = numberToEnglish a ++ " point " ++ digitsText b
where a = head $ splitOn "." d
b = last $ splitOn "." d
| eccstartup/numberToText | src/Text/New/NumberToText.hs | bsd-3-clause | 7,829 | 0 | 14 | 2,230 | 2,911 | 1,491 | 1,420 | 166 | 1 |
module SLD (sld) where
import Data.List
import qualified Data.Set as S
import Control.Monad
import Control.Applicative
import Term
import Unify
import Parse
import Text.Parsec
testProg =
[ Clause (Fun "conn" [Fun "berlin" [],Fun "moscow" []]) []
, Clause (Fun "conn" [Fun "berlin" [],Fun "bonn" []]) []
, Clause (Fun "conn" [Fun "moscow" [],Fun "paris" []]) []
, Clause (Fun "path" [Var "X",Var "X"]) []
, Clause (Fun "path" [Var "X",Var "Y"]) [Fun "conn" [Var "X",Var "Z"],Fun "path" [Var "Z",Var "Y"]]
]
sld :: Program -> Query -> [Subst]
sld cs qs = prove cs epsilon freeVars qs
where
freeVars = map (\n -> '_' : show n) [1..]
prove :: Program -> Subst -> [Name] -> Query -> [Subst]
prove cs theta ns [] = return theta
prove cs theta ns (q:qs) = do
(gamma, ns', ts) <- usable q (map (uniqueVariant ns) cs)
prove cs (theta >=> gamma) ns' (map (>>= gamma) (ts ++ qs))
uniqueVariant :: [Name] -> Clause -> ([Name], Clause)
uniqueVariant ns c@(Clause h bs) = (ns', Clause (h >>= theta) (map (>>= theta) bs))
where
usedVars = S.toList $ vars c
(trans,ns') = splitAt (length usedVars) ns
theta = foldl' (>=>) epsilon $ zipWith elemSubst usedVars (map Var ns)
usable :: LTerm -> [([Name], Clause)] -> [(Subst, [Name], Query)]
usable t = foldr f []
where
f (ns, c@(Clause h bs)) xs = ((\gamma -> (gamma,ns,bs)) <$> mgu t h) ++ xs
| ziman/simple-prolog | SLD.hs | bsd-3-clause | 1,408 | 0 | 12 | 319 | 731 | 392 | 339 | 31 | 1 |
module Main (main) where
import Prelude (IO)
import qualified Guide.Main
main :: IO ()
main = Guide.Main.main
| aelve/guide | back/src/site/Main.hs | bsd-3-clause | 113 | 0 | 6 | 20 | 41 | 25 | 16 | 5 | 1 |
{-# LANGUAGE CPP, GADTs #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- ----------------------------------------------------------------------------
-- | Handle conversion of CmmProc to LLVM code.
--
module LlvmCodeGen.CodeGen ( genLlvmProc ) where
#include "HsVersions.h"
import Llvm
import LlvmCodeGen.Base
import LlvmCodeGen.Regs
import BlockId
import CodeGen.Platform ( activeStgRegs, callerSaves )
import CLabel
import Cmm
import PprCmm
import CmmUtils
import CmmSwitch
import Hoopl
import DynFlags
import FastString
import ForeignCall
import Outputable hiding (panic, pprPanic)
import qualified Outputable
import Platform
import OrdList
import UniqSupply
import Unique
import Util
import Control.Monad.Trans.Class
import Control.Monad.Trans.Writer
#if __GLASGOW_HASKELL__ > 710
import Data.Semigroup ( Semigroup )
import qualified Data.Semigroup as Semigroup
#endif
import Data.List ( nub )
import Data.Maybe ( catMaybes )
type Atomic = Bool
type LlvmStatements = OrdList LlvmStatement
-- -----------------------------------------------------------------------------
-- | Top-level of the LLVM proc Code generator
--
genLlvmProc :: RawCmmDecl -> LlvmM [LlvmCmmDecl]
genLlvmProc (CmmProc infos lbl live graph) = do
let blocks = toBlockListEntryFirstFalseFallthrough graph
(lmblocks, lmdata) <- basicBlocksCodeGen live blocks
let info = mapLookup (g_entry graph) infos
proc = CmmProc info lbl live (ListGraph lmblocks)
return (proc:lmdata)
genLlvmProc _ = panic "genLlvmProc: case that shouldn't reach here!"
-- -----------------------------------------------------------------------------
-- * Block code generation
--
-- | Generate code for a list of blocks that make up a complete
-- procedure. The first block in the list is exepected to be the entry
-- point and will get the prologue.
basicBlocksCodeGen :: LiveGlobalRegs -> [CmmBlock]
-> LlvmM ([LlvmBasicBlock], [LlvmCmmDecl])
basicBlocksCodeGen _ [] = panic "no entry block!"
basicBlocksCodeGen live (entryBlock:cmmBlocks)
= do (prologue, prologueTops) <- funPrologue live (entryBlock:cmmBlocks)
-- Generate code
(BasicBlock bid entry, entryTops) <- basicBlockCodeGen entryBlock
(blocks, topss) <- fmap unzip $ mapM basicBlockCodeGen cmmBlocks
-- Compose
let entryBlock = BasicBlock bid (fromOL prologue ++ entry)
return (entryBlock : blocks, prologueTops ++ entryTops ++ concat topss)
-- | Generate code for one block
basicBlockCodeGen :: CmmBlock -> LlvmM ( LlvmBasicBlock, [LlvmCmmDecl] )
basicBlockCodeGen block
= do let (_, nodes, tail) = blockSplit block
id = entryLabel block
(mid_instrs, top) <- stmtsToInstrs $ blockToList nodes
(tail_instrs, top') <- stmtToInstrs tail
let instrs = fromOL (mid_instrs `appOL` tail_instrs)
return (BasicBlock id instrs, top' ++ top)
-- -----------------------------------------------------------------------------
-- * CmmNode code generation
--
-- A statement conversion return data.
-- * LlvmStatements: The compiled LLVM statements.
-- * LlvmCmmDecl: Any global data needed.
type StmtData = (LlvmStatements, [LlvmCmmDecl])
-- | Convert a list of CmmNode's to LlvmStatement's
stmtsToInstrs :: [CmmNode e x] -> LlvmM StmtData
stmtsToInstrs stmts
= do (instrss, topss) <- fmap unzip $ mapM stmtToInstrs stmts
return (concatOL instrss, concat topss)
-- | Convert a CmmStmt to a list of LlvmStatement's
stmtToInstrs :: CmmNode e x -> LlvmM StmtData
stmtToInstrs stmt = case stmt of
CmmComment _ -> return (nilOL, []) -- nuke comments
CmmTick _ -> return (nilOL, [])
CmmUnwind {} -> return (nilOL, [])
CmmAssign reg src -> genAssign reg src
CmmStore addr src -> genStore addr src
CmmBranch id -> genBranch id
CmmCondBranch arg true false _ -- TODO: likely annotation
-> genCondBranch arg true false
CmmSwitch arg ids -> genSwitch arg ids
-- Foreign Call
CmmUnsafeForeignCall target res args
-> genCall target res args
-- Tail call
CmmCall { cml_target = arg,
cml_args_regs = live } -> genJump arg live
_ -> panic "Llvm.CodeGen.stmtToInstrs"
-- | Wrapper function to declare an instrinct function by function type
getInstrinct2 :: LMString -> LlvmType -> LlvmM ExprData
getInstrinct2 fname fty@(LMFunction funSig) = do
let fv = LMGlobalVar fname fty (funcLinkage funSig) Nothing Nothing Constant
fn <- funLookup fname
tops <- case fn of
Just _ ->
return []
Nothing -> do
funInsert fname fty
un <- runUs getUniqueM
let lbl = mkAsmTempLabel un
return [CmmData (Section Data lbl) [([],[fty])]]
return (fv, nilOL, tops)
getInstrinct2 _ _ = error "getInstrinct2: Non-function type!"
-- | Declares an instrinct function by return and parameter types
getInstrinct :: LMString -> LlvmType -> [LlvmType] -> LlvmM ExprData
getInstrinct fname retTy parTys =
let funSig = LlvmFunctionDecl fname ExternallyVisible CC_Ccc retTy
FixedArgs (tysToParams parTys) Nothing
fty = LMFunction funSig
in getInstrinct2 fname fty
-- | Memory barrier instruction for LLVM >= 3.0
barrier :: LlvmM StmtData
barrier = do
let s = Fence False SyncSeqCst
return (unitOL s, [])
-- | Foreign Calls
genCall :: ForeignTarget -> [CmmFormal] -> [CmmActual]
-> LlvmM StmtData
-- Write barrier needs to be handled specially as it is implemented as an LLVM
-- intrinsic function.
genCall (PrimTarget MO_WriteBarrier) _ _ = do
platform <- getLlvmPlatform
if platformArch platform `elem` [ArchX86, ArchX86_64, ArchSPARC]
then return (nilOL, [])
else barrier
genCall (PrimTarget MO_Touch) _ _
= return (nilOL, [])
genCall (PrimTarget (MO_UF_Conv w)) [dst] [e] = runStmtsDecls $ do
dstV <- getCmmRegW (CmmLocal dst)
let ty = cmmToLlvmType $ localRegType dst
width = widthToLlvmFloat w
castV <- lift $ mkLocalVar ty
ve <- exprToVarW e
statement $ Assignment castV $ Cast LM_Uitofp ve width
statement $ Store castV dstV
genCall (PrimTarget (MO_UF_Conv _)) [_] args =
panic $ "genCall: Too many arguments to MO_UF_Conv. " ++
"Can only handle 1, given" ++ show (length args) ++ "."
-- Handle prefetching data
genCall t@(PrimTarget (MO_Prefetch_Data localityInt)) [] args
| 0 <= localityInt && localityInt <= 3 = runStmtsDecls $ do
let argTy = [i8Ptr, i32, i32, i32]
funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible
CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing
let (_, arg_hints) = foreignTargetHints t
let args_hints' = zip args arg_hints
argVars <- arg_varsW args_hints' ([], nilOL, [])
fptr <- liftExprData $ getFunPtr funTy t
argVars' <- castVarsW $ zip argVars argTy
doTrashStmts
let argSuffix = [mkIntLit i32 0, mkIntLit i32 localityInt, mkIntLit i32 1]
statement $ Expr $ Call StdCall fptr (argVars' ++ argSuffix) []
| otherwise = panic $ "prefetch locality level integer must be between 0 and 3, given: " ++ (show localityInt)
-- Handle PopCnt, Clz, Ctz, and BSwap that need to only convert arg
-- and return types
genCall t@(PrimTarget (MO_PopCnt w)) dsts args =
genCallSimpleCast w t dsts args
genCall t@(PrimTarget (MO_Clz w)) dsts args =
genCallSimpleCast w t dsts args
genCall t@(PrimTarget (MO_Ctz w)) dsts args =
genCallSimpleCast w t dsts args
genCall t@(PrimTarget (MO_BSwap w)) dsts args =
genCallSimpleCast w t dsts args
genCall (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = runStmtsDecls $ do
addrVar <- exprToVarW addr
nVar <- exprToVarW n
let targetTy = widthToLlvmInt width
ptrExpr = Cast LM_Inttoptr addrVar (pLift targetTy)
ptrVar <- doExprW (pLift targetTy) ptrExpr
dstVar <- getCmmRegW (CmmLocal dst)
let op = case amop of
AMO_Add -> LAO_Add
AMO_Sub -> LAO_Sub
AMO_And -> LAO_And
AMO_Nand -> LAO_Nand
AMO_Or -> LAO_Or
AMO_Xor -> LAO_Xor
retVar <- doExprW targetTy $ AtomicRMW op ptrVar nVar SyncSeqCst
statement $ Store retVar dstVar
genCall (PrimTarget (MO_AtomicRead _)) [dst] [addr] = runStmtsDecls $ do
dstV <- getCmmRegW (CmmLocal dst)
v1 <- genLoadW True addr (localRegType dst)
statement $ Store v1 dstV
genCall (PrimTarget (MO_Cmpxchg _width))
[dst] [addr, old, new] = runStmtsDecls $ do
addrVar <- exprToVarW addr
oldVar <- exprToVarW old
newVar <- exprToVarW new
let targetTy = getVarType oldVar
ptrExpr = Cast LM_Inttoptr addrVar (pLift targetTy)
ptrVar <- doExprW (pLift targetTy) ptrExpr
dstVar <- getCmmRegW (CmmLocal dst)
retVar <- doExprW (LMStructU [targetTy,i1])
$ CmpXChg ptrVar oldVar newVar SyncSeqCst SyncSeqCst
retVar' <- doExprW targetTy $ ExtractV retVar 0
statement $ Store retVar' dstVar
genCall (PrimTarget (MO_AtomicWrite _width)) [] [addr, val] = runStmtsDecls $ do
addrVar <- exprToVarW addr
valVar <- exprToVarW val
let ptrTy = pLift $ getVarType valVar
ptrExpr = Cast LM_Inttoptr addrVar ptrTy
ptrVar <- doExprW ptrTy ptrExpr
statement $ Expr $ AtomicRMW LAO_Xchg ptrVar valVar SyncSeqCst
-- Handle memcpy function specifically since llvm's intrinsic version takes
-- some extra parameters.
genCall t@(PrimTarget op) [] args
| Just align <- machOpMemcpyishAlign op = runStmtsDecls $ do
dflags <- getDynFlags
let isVolTy = [i1]
isVolVal = [mkIntLit i1 0]
argTy | MO_Memset _ <- op = [i8Ptr, i8, llvmWord dflags, i32] ++ isVolTy
| otherwise = [i8Ptr, i8Ptr, llvmWord dflags, i32] ++ isVolTy
funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible
CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing
let (_, arg_hints) = foreignTargetHints t
let args_hints = zip args arg_hints
argVars <- arg_varsW args_hints ([], nilOL, [])
fptr <- getFunPtrW funTy t
argVars' <- castVarsW $ zip argVars argTy
doTrashStmts
let alignVal = mkIntLit i32 align
arguments = argVars' ++ (alignVal:isVolVal)
statement $ Expr $ Call StdCall fptr arguments []
-- We handle MO_U_Mul2 by simply using a 'mul' instruction, but with operands
-- twice the width (we first zero-extend them), e.g., on 64-bit arch we will
-- generate 'mul' on 128-bit operands. Then we only need some plumbing to
-- extract the two 64-bit values out of 128-bit result.
genCall (PrimTarget (MO_U_Mul2 w)) [dstH, dstL] [lhs, rhs] = runStmtsDecls $ do
let width = widthToLlvmInt w
bitWidth = widthInBits w
width2x = LMInt (bitWidth * 2)
-- First zero-extend the operands ('mul' instruction requires the operands
-- and the result to be of the same type). Note that we don't use 'castVars'
-- because it tries to do LM_Sext.
lhsVar <- exprToVarW lhs
rhsVar <- exprToVarW rhs
lhsExt <- doExprW width2x $ Cast LM_Zext lhsVar width2x
rhsExt <- doExprW width2x $ Cast LM_Zext rhsVar width2x
-- Do the actual multiplication (note that the result is also 2x width).
retV <- doExprW width2x $ LlvmOp LM_MO_Mul lhsExt rhsExt
-- Extract the lower bits of the result into retL.
retL <- doExprW width $ Cast LM_Trunc retV width
-- Now we right-shift the higher bits by width.
let widthLlvmLit = LMLitVar $ LMIntLit (fromIntegral bitWidth) width
retShifted <- doExprW width2x $ LlvmOp LM_MO_LShr retV widthLlvmLit
-- And extract them into retH.
retH <- doExprW width $ Cast LM_Trunc retShifted width
dstRegL <- getCmmRegW (CmmLocal dstL)
dstRegH <- getCmmRegW (CmmLocal dstH)
statement $ Store retL dstRegL
statement $ Store retH dstRegH
-- MO_U_QuotRem2 is another case we handle by widening the registers to double
-- the width and use normal LLVM instructions (similarly to the MO_U_Mul2). The
-- main difference here is that we need to combine two words into one register
-- and then use both 'udiv' and 'urem' instructions to compute the result.
genCall (PrimTarget (MO_U_QuotRem2 w))
[dstQ, dstR] [lhsH, lhsL, rhs] = runStmtsDecls $ do
let width = widthToLlvmInt w
bitWidth = widthInBits w
width2x = LMInt (bitWidth * 2)
-- First zero-extend all parameters to double width.
let zeroExtend expr = do
var <- exprToVarW expr
doExprW width2x $ Cast LM_Zext var width2x
lhsExtH <- zeroExtend lhsH
lhsExtL <- zeroExtend lhsL
rhsExt <- zeroExtend rhs
-- Now we combine the first two parameters (that represent the high and low
-- bits of the value). So first left-shift the high bits to their position
-- and then bit-or them with the low bits.
let widthLlvmLit = LMLitVar $ LMIntLit (fromIntegral bitWidth) width
lhsExtHShifted <- doExprW width2x $ LlvmOp LM_MO_Shl lhsExtH widthLlvmLit
lhsExt <- doExprW width2x $ LlvmOp LM_MO_Or lhsExtHShifted lhsExtL
-- Finally, we can call 'udiv' and 'urem' to compute the results.
retExtDiv <- doExprW width2x $ LlvmOp LM_MO_UDiv lhsExt rhsExt
retExtRem <- doExprW width2x $ LlvmOp LM_MO_URem lhsExt rhsExt
-- And since everything is in 2x width, we need to truncate the results and
-- then return them.
let narrow var = doExprW width $ Cast LM_Trunc var width
retDiv <- narrow retExtDiv
retRem <- narrow retExtRem
dstRegQ <- lift $ getCmmReg (CmmLocal dstQ)
dstRegR <- lift $ getCmmReg (CmmLocal dstR)
statement $ Store retDiv dstRegQ
statement $ Store retRem dstRegR
-- Handle the MO_{Add,Sub}IntC separately. LLVM versions return a record from
-- which we need to extract the actual values.
genCall t@(PrimTarget (MO_AddIntC w)) [dstV, dstO] [lhs, rhs] =
genCallWithOverflow t w [dstV, dstO] [lhs, rhs]
genCall t@(PrimTarget (MO_SubIntC w)) [dstV, dstO] [lhs, rhs] =
genCallWithOverflow t w [dstV, dstO] [lhs, rhs]
-- Similar to MO_{Add,Sub}IntC, but MO_Add2 expects the first element of the
-- return tuple to be the overflow bit and the second element to contain the
-- actual result of the addition. So we still use genCallWithOverflow but swap
-- the return registers.
genCall t@(PrimTarget (MO_Add2 w)) [dstO, dstV] [lhs, rhs] =
genCallWithOverflow t w [dstV, dstO] [lhs, rhs]
genCall t@(PrimTarget (MO_SubWordC w)) [dstV, dstO] [lhs, rhs] =
genCallWithOverflow t w [dstV, dstO] [lhs, rhs]
-- Handle all other foreign calls and prim ops.
genCall target res args = runStmtsDecls $ do
dflags <- getDynFlags
-- parameter types
let arg_type (_, AddrHint) = i8Ptr
-- cast pointers to i8*. Llvm equivalent of void*
arg_type (expr, _) = cmmToLlvmType $ cmmExprType dflags expr
-- ret type
let ret_type [] = LMVoid
ret_type [(_, AddrHint)] = i8Ptr
ret_type [(reg, _)] = cmmToLlvmType $ localRegType reg
ret_type t = panic $ "genCall: Too many return values! Can only handle"
++ " 0 or 1, given " ++ show (length t) ++ "."
-- extract Cmm call convention, and translate to LLVM call convention
platform <- lift $ getLlvmPlatform
let lmconv = case target of
ForeignTarget _ (ForeignConvention conv _ _ _) ->
case conv of
StdCallConv -> case platformArch platform of
ArchX86 -> CC_X86_Stdcc
ArchX86_64 -> CC_X86_Stdcc
_ -> CC_Ccc
CCallConv -> CC_Ccc
CApiConv -> CC_Ccc
PrimCallConv -> panic "LlvmCodeGen.CodeGen.genCall: PrimCallConv"
JavaScriptCallConv -> panic "LlvmCodeGen.CodeGen.genCall: JavaScriptCallConv"
PrimTarget _ -> CC_Ccc
{-
CC_Ccc of the possibilities here are a worry with the use of a custom
calling convention for passing STG args. In practice the more
dangerous combinations (e.g StdCall + llvmGhcCC) don't occur.
The native code generator only handles StdCall and CCallConv.
-}
-- call attributes
let fnAttrs | never_returns = NoReturn : llvmStdFunAttrs
| otherwise = llvmStdFunAttrs
never_returns = case target of
ForeignTarget _ (ForeignConvention _ _ _ CmmNeverReturns) -> True
_ -> False
-- fun type
let (res_hints, arg_hints) = foreignTargetHints target
let args_hints = zip args arg_hints
let ress_hints = zip res res_hints
let ccTy = StdCall -- tail calls should be done through CmmJump
let retTy = ret_type ress_hints
let argTy = tysToParams $ map arg_type args_hints
let funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible
lmconv retTy FixedArgs argTy (llvmFunAlign dflags)
argVars <- arg_varsW args_hints ([], nilOL, [])
fptr <- getFunPtrW funTy target
let doReturn | ccTy == TailCall = statement $ Return Nothing
| never_returns = statement $ Unreachable
| otherwise = return ()
doTrashStmts
-- make the actual call
case retTy of
LMVoid -> do
statement $ Expr $ Call ccTy fptr argVars fnAttrs
_ -> do
v1 <- doExprW retTy $ Call ccTy fptr argVars fnAttrs
-- get the return register
let ret_reg [reg] = reg
ret_reg t = panic $ "genCall: Bad number of registers! Can only handle"
++ " 1, given " ++ show (length t) ++ "."
let creg = ret_reg res
vreg <- getCmmRegW (CmmLocal creg)
if retTy == pLower (getVarType vreg)
then do
statement $ Store v1 vreg
doReturn
else do
let ty = pLower $ getVarType vreg
let op = case ty of
vt | isPointer vt -> LM_Bitcast
| isInt vt -> LM_Ptrtoint
| otherwise ->
panic $ "genCall: CmmReg bad match for"
++ " returned type!"
v2 <- doExprW ty $ Cast op v1 ty
statement $ Store v2 vreg
doReturn
-- | Generate a call to an LLVM intrinsic that performs arithmetic operation
-- with overflow bit (i.e., returns a struct containing the actual result of the
-- operation and an overflow bit). This function will also extract the overflow
-- bit and zero-extend it (all the corresponding Cmm PrimOps represent the
-- overflow "bit" as a usual Int# or Word#).
genCallWithOverflow
:: ForeignTarget -> Width -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData
genCallWithOverflow t@(PrimTarget op) w [dstV, dstO] [lhs, rhs] = do
-- So far this was only tested for the following four CallishMachOps.
let valid = op `elem` [ MO_Add2 w
, MO_AddIntC w
, MO_SubIntC w
, MO_SubWordC w
]
MASSERT(valid)
let width = widthToLlvmInt w
-- This will do most of the work of generating the call to the intrinsic and
-- extracting the values from the struct.
(value, overflowBit, (stmts, top)) <-
genCallExtract t w (lhs, rhs) (width, i1)
-- value is i<width>, but overflowBit is i1, so we need to cast (Cmm expects
-- both to be i<width>)
(overflow, zext) <- doExpr width $ Cast LM_Zext overflowBit width
dstRegV <- getCmmReg (CmmLocal dstV)
dstRegO <- getCmmReg (CmmLocal dstO)
let storeV = Store value dstRegV
storeO = Store overflow dstRegO
return (stmts `snocOL` zext `snocOL` storeV `snocOL` storeO, top)
genCallWithOverflow _ _ _ _ =
panic "genCallExtract: wrong ForeignTarget or number of arguments"
-- | A helper function for genCallWithOverflow that handles generating the call
-- to the LLVM intrinsic and extracting the result from the struct to LlvmVars.
genCallExtract
:: ForeignTarget -- ^ PrimOp
-> Width -- ^ Width of the operands.
-> (CmmActual, CmmActual) -- ^ Actual arguments.
-> (LlvmType, LlvmType) -- ^ LLLVM types of the returned sturct.
-> LlvmM (LlvmVar, LlvmVar, StmtData)
genCallExtract target@(PrimTarget op) w (argA, argB) (llvmTypeA, llvmTypeB) = do
let width = widthToLlvmInt w
argTy = [width, width]
retTy = LMStructU [llvmTypeA, llvmTypeB]
-- Process the arguments.
let args_hints = zip [argA, argB] (snd $ foreignTargetHints target)
(argsV1, args1, top1) <- arg_vars args_hints ([], nilOL, [])
(argsV2, args2) <- castVars $ zip argsV1 argTy
-- Get the function and make the call.
fname <- cmmPrimOpFunctions op
(fptr, _, top2) <- getInstrinct fname retTy argTy
-- We use StdCall for primops. See also the last case of genCall.
(retV, call) <- doExpr retTy $ Call StdCall fptr argsV2 []
-- This will result in a two element struct, we need to use "extractvalue"
-- to get them out of it.
(res1, ext1) <- doExpr llvmTypeA (ExtractV retV 0)
(res2, ext2) <- doExpr llvmTypeB (ExtractV retV 1)
let stmts = args1 `appOL` args2 `snocOL` call `snocOL` ext1 `snocOL` ext2
tops = top1 ++ top2
return (res1, res2, (stmts, tops))
genCallExtract _ _ _ _ =
panic "genCallExtract: unsupported ForeignTarget"
-- Handle simple function call that only need simple type casting, of the form:
-- truncate arg >>= \a -> call(a) >>= zext
--
-- since GHC only really has i32 and i64 types and things like Word8 are backed
-- by an i32 and just present a logical i8 range. So we must handle conversions
-- from i32 to i8 explicitly as LLVM is strict about types.
genCallSimpleCast :: Width -> ForeignTarget -> [CmmFormal] -> [CmmActual]
-> LlvmM StmtData
genCallSimpleCast w t@(PrimTarget op) [dst] args = do
let width = widthToLlvmInt w
dstTy = cmmToLlvmType $ localRegType dst
fname <- cmmPrimOpFunctions op
(fptr, _, top3) <- getInstrinct fname width [width]
dstV <- getCmmReg (CmmLocal dst)
let (_, arg_hints) = foreignTargetHints t
let args_hints = zip args arg_hints
(argsV, stmts2, top2) <- arg_vars args_hints ([], nilOL, [])
(argsV', stmts4) <- castVars $ zip argsV [width]
(retV, s1) <- doExpr width $ Call StdCall fptr argsV' []
([retV'], stmts5) <- castVars [(retV,dstTy)]
let s2 = Store retV' dstV
let stmts = stmts2 `appOL` stmts4 `snocOL`
s1 `appOL` stmts5 `snocOL` s2
return (stmts, top2 ++ top3)
genCallSimpleCast _ _ dsts _ =
panic ("genCallSimpleCast: " ++ show (length dsts) ++ " dsts")
-- | Create a function pointer from a target.
getFunPtrW :: (LMString -> LlvmType) -> ForeignTarget
-> WriterT LlvmAccum LlvmM LlvmVar
getFunPtrW funTy targ = liftExprData $ getFunPtr funTy targ
-- | Create a function pointer from a target.
getFunPtr :: (LMString -> LlvmType) -> ForeignTarget
-> LlvmM ExprData
getFunPtr funTy targ = case targ of
ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do
name <- strCLabel_llvm lbl
getHsFunc' name (funTy name)
ForeignTarget expr _ -> do
(v1, stmts, top) <- exprToVar expr
dflags <- getDynFlags
let fty = funTy $ fsLit "dynamic"
cast = case getVarType v1 of
ty | isPointer ty -> LM_Bitcast
ty | isInt ty -> LM_Inttoptr
ty -> panic $ "genCall: Expr is of bad type for function"
++ " call! (" ++ showSDoc dflags (ppr ty) ++ ")"
(v2,s1) <- doExpr (pLift fty) $ Cast cast v1 (pLift fty)
return (v2, stmts `snocOL` s1, top)
PrimTarget mop -> do
name <- cmmPrimOpFunctions mop
let fty = funTy name
getInstrinct2 name fty
-- | Conversion of call arguments.
arg_varsW :: [(CmmActual, ForeignHint)]
-> ([LlvmVar], LlvmStatements, [LlvmCmmDecl])
-> WriterT LlvmAccum LlvmM [LlvmVar]
arg_varsW xs ys = do
(vars, stmts, decls) <- lift $ arg_vars xs ys
tell $ LlvmAccum stmts decls
return vars
-- | Conversion of call arguments.
arg_vars :: [(CmmActual, ForeignHint)]
-> ([LlvmVar], LlvmStatements, [LlvmCmmDecl])
-> LlvmM ([LlvmVar], LlvmStatements, [LlvmCmmDecl])
arg_vars [] (vars, stmts, tops)
= return (vars, stmts, tops)
arg_vars ((e, AddrHint):rest) (vars, stmts, tops)
= do (v1, stmts', top') <- exprToVar e
dflags <- getDynFlags
let op = case getVarType v1 of
ty | isPointer ty -> LM_Bitcast
ty | isInt ty -> LM_Inttoptr
a -> panic $ "genCall: Can't cast llvmType to i8*! ("
++ showSDoc dflags (ppr a) ++ ")"
(v2, s1) <- doExpr i8Ptr $ Cast op v1 i8Ptr
arg_vars rest (vars ++ [v2], stmts `appOL` stmts' `snocOL` s1,
tops ++ top')
arg_vars ((e, _):rest) (vars, stmts, tops)
= do (v1, stmts', top') <- exprToVar e
arg_vars rest (vars ++ [v1], stmts `appOL` stmts', tops ++ top')
-- | Cast a collection of LLVM variables to specific types.
castVarsW :: [(LlvmVar, LlvmType)]
-> WriterT LlvmAccum LlvmM [LlvmVar]
castVarsW vars = do
(vars, stmts) <- lift $ castVars vars
tell $ LlvmAccum stmts mempty
return vars
-- | Cast a collection of LLVM variables to specific types.
castVars :: [(LlvmVar, LlvmType)]
-> LlvmM ([LlvmVar], LlvmStatements)
castVars vars = do
done <- mapM (uncurry castVar) vars
let (vars', stmts) = unzip done
return (vars', toOL stmts)
-- | Cast an LLVM variable to a specific type, panicing if it can't be done.
castVar :: LlvmVar -> LlvmType -> LlvmM (LlvmVar, LlvmStatement)
castVar v t | getVarType v == t
= return (v, Nop)
| otherwise
= do dflags <- getDynFlags
let op = case (getVarType v, t) of
(LMInt n, LMInt m)
-> if n < m then LM_Sext else LM_Trunc
(vt, _) | isFloat vt && isFloat t
-> if llvmWidthInBits dflags vt < llvmWidthInBits dflags t
then LM_Fpext else LM_Fptrunc
(vt, _) | isInt vt && isFloat t -> LM_Sitofp
(vt, _) | isFloat vt && isInt t -> LM_Fptosi
(vt, _) | isInt vt && isPointer t -> LM_Inttoptr
(vt, _) | isPointer vt && isInt t -> LM_Ptrtoint
(vt, _) | isPointer vt && isPointer t -> LM_Bitcast
(vt, _) | isVector vt && isVector t -> LM_Bitcast
(vt, _) -> panic $ "castVars: Can't cast this type ("
++ showSDoc dflags (ppr vt) ++ ") to (" ++ showSDoc dflags (ppr t) ++ ")"
doExpr t $ Cast op v t
-- | Decide what C function to use to implement a CallishMachOp
cmmPrimOpFunctions :: CallishMachOp -> LlvmM LMString
cmmPrimOpFunctions mop = do
dflags <- getDynFlags
let intrinTy1 = "p0i8.p0i8." ++ showSDoc dflags (ppr $ llvmWord dflags)
intrinTy2 = "p0i8." ++ showSDoc dflags (ppr $ llvmWord dflags)
unsupported = panic ("cmmPrimOpFunctions: " ++ show mop
++ " not supported here")
return $ case mop of
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Sqrt -> fsLit "llvm.sqrt.f32"
MO_F32_Pwr -> fsLit "llvm.pow.f32"
MO_F32_Sin -> fsLit "llvm.sin.f32"
MO_F32_Cos -> fsLit "llvm.cos.f32"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Sqrt -> fsLit "llvm.sqrt.f64"
MO_F64_Pwr -> fsLit "llvm.pow.f64"
MO_F64_Sin -> fsLit "llvm.sin.f64"
MO_F64_Cos -> fsLit "llvm.cos.f64"
MO_F64_Tan -> fsLit "tan"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_Memcpy _ -> fsLit $ "llvm.memcpy." ++ intrinTy1
MO_Memmove _ -> fsLit $ "llvm.memmove." ++ intrinTy1
MO_Memset _ -> fsLit $ "llvm.memset." ++ intrinTy2
(MO_PopCnt w) -> fsLit $ "llvm.ctpop." ++ showSDoc dflags (ppr $ widthToLlvmInt w)
(MO_BSwap w) -> fsLit $ "llvm.bswap." ++ showSDoc dflags (ppr $ widthToLlvmInt w)
(MO_Clz w) -> fsLit $ "llvm.ctlz." ++ showSDoc dflags (ppr $ widthToLlvmInt w)
(MO_Ctz w) -> fsLit $ "llvm.cttz." ++ showSDoc dflags (ppr $ widthToLlvmInt w)
(MO_Prefetch_Data _ )-> fsLit "llvm.prefetch"
MO_AddIntC w -> fsLit $ "llvm.sadd.with.overflow."
++ showSDoc dflags (ppr $ widthToLlvmInt w)
MO_SubIntC w -> fsLit $ "llvm.ssub.with.overflow."
++ showSDoc dflags (ppr $ widthToLlvmInt w)
MO_Add2 w -> fsLit $ "llvm.uadd.with.overflow."
++ showSDoc dflags (ppr $ widthToLlvmInt w)
MO_SubWordC w -> fsLit $ "llvm.usub.with.overflow."
++ showSDoc dflags (ppr $ widthToLlvmInt w)
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
-- We support MO_U_Mul2 through ordinary LLVM mul instruction, see the
-- appropriate case of genCall.
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
MO_UF_Conv _ -> unsupported
MO_AtomicRead _ -> unsupported
MO_AtomicRMW _ _ -> unsupported
MO_AtomicWrite _ -> unsupported
MO_Cmpxchg _ -> unsupported
-- | Tail function calls
genJump :: CmmExpr -> [GlobalReg] -> LlvmM StmtData
-- Call to known function
genJump (CmmLit (CmmLabel lbl)) live = do
(vf, stmts, top) <- getHsFunc live lbl
(stgRegs, stgStmts) <- funEpilogue live
let s1 = Expr $ Call TailCall vf stgRegs llvmStdFunAttrs
let s2 = Return Nothing
return (stmts `appOL` stgStmts `snocOL` s1 `snocOL` s2, top)
-- Call to unknown function / address
genJump expr live = do
fty <- llvmFunTy live
(vf, stmts, top) <- exprToVar expr
dflags <- getDynFlags
let cast = case getVarType vf of
ty | isPointer ty -> LM_Bitcast
ty | isInt ty -> LM_Inttoptr
ty -> panic $ "genJump: Expr is of bad type for function call! ("
++ showSDoc dflags (ppr ty) ++ ")"
(v1, s1) <- doExpr (pLift fty) $ Cast cast vf (pLift fty)
(stgRegs, stgStmts) <- funEpilogue live
let s2 = Expr $ Call TailCall v1 stgRegs llvmStdFunAttrs
let s3 = Return Nothing
return (stmts `snocOL` s1 `appOL` stgStmts `snocOL` s2 `snocOL` s3,
top)
-- | CmmAssign operation
--
-- We use stack allocated variables for CmmReg. The optimiser will replace
-- these with registers when possible.
genAssign :: CmmReg -> CmmExpr -> LlvmM StmtData
genAssign reg val = do
vreg <- getCmmReg reg
(vval, stmts2, top2) <- exprToVar val
let stmts = stmts2
let ty = (pLower . getVarType) vreg
dflags <- getDynFlags
case ty of
-- Some registers are pointer types, so need to cast value to pointer
LMPointer _ | getVarType vval == llvmWord dflags -> do
(v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty
let s2 = Store v vreg
return (stmts `snocOL` s1 `snocOL` s2, top2)
LMVector _ _ -> do
(v, s1) <- doExpr ty $ Cast LM_Bitcast vval ty
let s2 = Store v vreg
return (stmts `snocOL` s1 `snocOL` s2, top2)
_ -> do
let s1 = Store vval vreg
return (stmts `snocOL` s1, top2)
-- | CmmStore operation
genStore :: CmmExpr -> CmmExpr -> LlvmM StmtData
-- First we try to detect a few common cases and produce better code for
-- these then the default case. We are mostly trying to detect Cmm code
-- like I32[Sp + n] and use 'getelementptr' operations instead of the
-- generic case that uses casts and pointer arithmetic
genStore addr@(CmmReg (CmmGlobal r)) val
= genStore_fast addr r 0 val
genStore addr@(CmmRegOff (CmmGlobal r) n) val
= genStore_fast addr r n val
genStore addr@(CmmMachOp (MO_Add _) [
(CmmReg (CmmGlobal r)),
(CmmLit (CmmInt n _))])
val
= genStore_fast addr r (fromInteger n) val
genStore addr@(CmmMachOp (MO_Sub _) [
(CmmReg (CmmGlobal r)),
(CmmLit (CmmInt n _))])
val
= genStore_fast addr r (negate $ fromInteger n) val
-- generic case
genStore addr val
= do other <- getTBAAMeta otherN
genStore_slow addr val other
-- | CmmStore operation
-- This is a special case for storing to a global register pointer
-- offset such as I32[Sp+8].
genStore_fast :: CmmExpr -> GlobalReg -> Int -> CmmExpr
-> LlvmM StmtData
genStore_fast addr r n val
= do dflags <- getDynFlags
(gv, grt, s1) <- getCmmRegVal (CmmGlobal r)
meta <- getTBAARegMeta r
let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8)
case isPointer grt && rem == 0 of
True -> do
(vval, stmts, top) <- exprToVar val
(ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix]
-- We might need a different pointer type, so check
case pLower grt == getVarType vval of
-- were fine
True -> do
let s3 = MetaStmt meta $ Store vval ptr
return (stmts `appOL` s1 `snocOL` s2
`snocOL` s3, top)
-- cast to pointer type needed
False -> do
let ty = (pLift . getVarType) vval
(ptr', s3) <- doExpr ty $ Cast LM_Bitcast ptr ty
let s4 = MetaStmt meta $ Store vval ptr'
return (stmts `appOL` s1 `snocOL` s2
`snocOL` s3 `snocOL` s4, top)
-- If its a bit type then we use the slow method since
-- we can't avoid casting anyway.
False -> genStore_slow addr val meta
-- | CmmStore operation
-- Generic case. Uses casts and pointer arithmetic if needed.
genStore_slow :: CmmExpr -> CmmExpr -> [MetaAnnot] -> LlvmM StmtData
genStore_slow addr val meta = do
(vaddr, stmts1, top1) <- exprToVar addr
(vval, stmts2, top2) <- exprToVar val
let stmts = stmts1 `appOL` stmts2
dflags <- getDynFlags
case getVarType vaddr of
-- sometimes we need to cast an int to a pointer before storing
LMPointer ty@(LMPointer _) | getVarType vval == llvmWord dflags -> do
(v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty
let s2 = MetaStmt meta $ Store v vaddr
return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2)
LMPointer _ -> do
let s1 = MetaStmt meta $ Store vval vaddr
return (stmts `snocOL` s1, top1 ++ top2)
i@(LMInt _) | i == llvmWord dflags -> do
let vty = pLift $ getVarType vval
(vptr, s1) <- doExpr vty $ Cast LM_Inttoptr vaddr vty
let s2 = MetaStmt meta $ Store vval vptr
return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2)
other ->
pprPanic "genStore: ptr not right type!"
(PprCmm.pprExpr addr <+> text (
"Size of Ptr: " ++ show (llvmPtrBits dflags) ++
", Size of var: " ++ show (llvmWidthInBits dflags other) ++
", Var: " ++ showSDoc dflags (ppr vaddr)))
-- | Unconditional branch
genBranch :: BlockId -> LlvmM StmtData
genBranch id =
let label = blockIdToLlvm id
in return (unitOL $ Branch label, [])
-- | Conditional branch
genCondBranch :: CmmExpr -> BlockId -> BlockId -> LlvmM StmtData
genCondBranch cond idT idF = do
let labelT = blockIdToLlvm idT
let labelF = blockIdToLlvm idF
-- See Note [Literals and branch conditions].
(vc, stmts, top) <- exprToVarOpt i1Option cond
if getVarType vc == i1
then do
let s1 = BranchIf vc labelT labelF
return (stmts `snocOL` s1, top)
else do
dflags <- getDynFlags
panic $ "genCondBranch: Cond expr not bool! (" ++ showSDoc dflags (ppr vc) ++ ")"
{- Note [Literals and branch conditions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is important that whenever we generate branch conditions for
literals like '1', they are properly narrowed to an LLVM expression of
type 'i1' (for bools.) Otherwise, nobody is happy. So when we convert
a CmmExpr to an LLVM expression for a branch conditional, exprToVarOpt
must be certain to return a properly narrowed type. genLit is
responsible for this, in the case of literal integers.
Often, we won't see direct statements like:
if(1) {
...
} else {
...
}
at this point in the pipeline, because the Glorious Code Generator
will do trivial branch elimination in the sinking pass (among others,)
which will eliminate the expression entirely.
However, it's certainly possible and reasonable for this to occur in
hand-written C-- code. Consider something like:
#ifndef SOME_CONDITIONAL
#define CHECK_THING(x) 1
#else
#define CHECK_THING(x) some_operation((x))
#endif
f() {
if (CHECK_THING(xyz)) {
...
} else {
...
}
}
In such an instance, CHECK_THING might result in an *expression* in
one case, and a *literal* in the other, depending on what in
particular was #define'd. So we must be sure to properly narrow the
literal in this case to i1 as it won't be eliminated beforehand.
For a real example of this, see ./rts/StgStdThunks.cmm
-}
-- | Switch branch
genSwitch :: CmmExpr -> SwitchTargets -> LlvmM StmtData
genSwitch cond ids = do
(vc, stmts, top) <- exprToVar cond
let ty = getVarType vc
let labels = [ (mkIntLit ty ix, blockIdToLlvm b)
| (ix, b) <- switchTargetsCases ids ]
-- out of range is undefined, so let's just branch to first label
let defLbl | Just l <- switchTargetsDefault ids = blockIdToLlvm l
| otherwise = snd (head labels)
let s1 = Switch vc defLbl labels
return $ (stmts `snocOL` s1, top)
-- -----------------------------------------------------------------------------
-- * CmmExpr code generation
--
-- | An expression conversion return data:
-- * LlvmVar: The var holding the result of the expression
-- * LlvmStatements: Any statements needed to evaluate the expression
-- * LlvmCmmDecl: Any global data needed for this expression
type ExprData = (LlvmVar, LlvmStatements, [LlvmCmmDecl])
-- | Values which can be passed to 'exprToVar' to configure its
-- behaviour in certain circumstances.
--
-- Currently just used for determining if a comparison should return
-- a boolean (i1) or a word. See Note [Literals and branch conditions].
newtype EOption = EOption { i1Expected :: Bool }
-- XXX: EOption is an ugly and inefficient solution to this problem.
-- | i1 type expected (condition scrutinee).
i1Option :: EOption
i1Option = EOption True
-- | Word type expected (usual).
wordOption :: EOption
wordOption = EOption False
-- | Convert a CmmExpr to a list of LlvmStatements with the result of the
-- expression being stored in the returned LlvmVar.
exprToVar :: CmmExpr -> LlvmM ExprData
exprToVar = exprToVarOpt wordOption
exprToVarOpt :: EOption -> CmmExpr -> LlvmM ExprData
exprToVarOpt opt e = case e of
CmmLit lit
-> genLit opt lit
CmmLoad e' ty
-> genLoad False e' ty
-- Cmmreg in expression is the value, so must load. If you want actual
-- reg pointer, call getCmmReg directly.
CmmReg r -> do
(v1, ty, s1) <- getCmmRegVal r
case isPointer ty of
True -> do
-- Cmm wants the value, so pointer types must be cast to ints
dflags <- getDynFlags
(v2, s2) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint v1 (llvmWord dflags)
return (v2, s1 `snocOL` s2, [])
False -> return (v1, s1, [])
CmmMachOp op exprs
-> genMachOp opt op exprs
CmmRegOff r i
-> do dflags <- getDynFlags
exprToVar $ expandCmmReg dflags (r, i)
CmmStackSlot _ _
-> panic "exprToVar: CmmStackSlot not supported!"
-- | Handle CmmMachOp expressions
genMachOp :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData
-- Unary Machop
genMachOp _ op [x] = case op of
MO_Not w ->
let all1 = mkIntLit (widthToLlvmInt w) (-1)
in negate (widthToLlvmInt w) all1 LM_MO_Xor
MO_S_Neg w ->
let all0 = mkIntLit (widthToLlvmInt w) 0
in negate (widthToLlvmInt w) all0 LM_MO_Sub
MO_F_Neg w ->
let all0 = LMLitVar $ LMFloatLit (-0) (widthToLlvmFloat w)
in negate (widthToLlvmFloat w) all0 LM_MO_FSub
MO_SF_Conv _ w -> fiConv (widthToLlvmFloat w) LM_Sitofp
MO_FS_Conv _ w -> fiConv (widthToLlvmInt w) LM_Fptosi
MO_SS_Conv from to
-> sameConv from (widthToLlvmInt to) LM_Trunc LM_Sext
MO_UU_Conv from to
-> sameConv from (widthToLlvmInt to) LM_Trunc LM_Zext
MO_FF_Conv from to
-> sameConv from (widthToLlvmFloat to) LM_Fptrunc LM_Fpext
MO_VS_Neg len w ->
let ty = widthToLlvmInt w
vecty = LMVector len ty
all0 = LMIntLit (-0) ty
all0s = LMLitVar $ LMVectorLit (replicate len all0)
in negateVec vecty all0s LM_MO_Sub
MO_VF_Neg len w ->
let ty = widthToLlvmFloat w
vecty = LMVector len ty
all0 = LMFloatLit (-0) ty
all0s = LMLitVar $ LMVectorLit (replicate len all0)
in negateVec vecty all0s LM_MO_FSub
-- Handle unsupported cases explicitly so we get a warning
-- of missing case when new MachOps added
MO_Add _ -> panicOp
MO_Mul _ -> panicOp
MO_Sub _ -> panicOp
MO_S_MulMayOflo _ -> panicOp
MO_S_Quot _ -> panicOp
MO_S_Rem _ -> panicOp
MO_U_MulMayOflo _ -> panicOp
MO_U_Quot _ -> panicOp
MO_U_Rem _ -> panicOp
MO_Eq _ -> panicOp
MO_Ne _ -> panicOp
MO_S_Ge _ -> panicOp
MO_S_Gt _ -> panicOp
MO_S_Le _ -> panicOp
MO_S_Lt _ -> panicOp
MO_U_Ge _ -> panicOp
MO_U_Gt _ -> panicOp
MO_U_Le _ -> panicOp
MO_U_Lt _ -> panicOp
MO_F_Add _ -> panicOp
MO_F_Sub _ -> panicOp
MO_F_Mul _ -> panicOp
MO_F_Quot _ -> panicOp
MO_F_Eq _ -> panicOp
MO_F_Ne _ -> panicOp
MO_F_Ge _ -> panicOp
MO_F_Gt _ -> panicOp
MO_F_Le _ -> panicOp
MO_F_Lt _ -> panicOp
MO_And _ -> panicOp
MO_Or _ -> panicOp
MO_Xor _ -> panicOp
MO_Shl _ -> panicOp
MO_U_Shr _ -> panicOp
MO_S_Shr _ -> panicOp
MO_V_Insert _ _ -> panicOp
MO_V_Extract _ _ -> panicOp
MO_V_Add _ _ -> panicOp
MO_V_Sub _ _ -> panicOp
MO_V_Mul _ _ -> panicOp
MO_VS_Quot _ _ -> panicOp
MO_VS_Rem _ _ -> panicOp
MO_VU_Quot _ _ -> panicOp
MO_VU_Rem _ _ -> panicOp
MO_VF_Insert _ _ -> panicOp
MO_VF_Extract _ _ -> panicOp
MO_VF_Add _ _ -> panicOp
MO_VF_Sub _ _ -> panicOp
MO_VF_Mul _ _ -> panicOp
MO_VF_Quot _ _ -> panicOp
where
negate ty v2 negOp = do
(vx, stmts, top) <- exprToVar x
(v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx
return (v1, stmts `snocOL` s1, top)
negateVec ty v2 negOp = do
(vx, stmts1, top) <- exprToVar x
([vx'], stmts2) <- castVars [(vx, ty)]
(v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx'
return (v1, stmts1 `appOL` stmts2 `snocOL` s1, top)
fiConv ty convOp = do
(vx, stmts, top) <- exprToVar x
(v1, s1) <- doExpr ty $ Cast convOp vx ty
return (v1, stmts `snocOL` s1, top)
sameConv from ty reduce expand = do
x'@(vx, stmts, top) <- exprToVar x
let sameConv' op = do
(v1, s1) <- doExpr ty $ Cast op vx ty
return (v1, stmts `snocOL` s1, top)
dflags <- getDynFlags
let toWidth = llvmWidthInBits dflags ty
-- LLVM doesn't like trying to convert to same width, so
-- need to check for that as we do get Cmm code doing it.
case widthInBits from of
w | w < toWidth -> sameConv' expand
w | w > toWidth -> sameConv' reduce
_w -> return x'
panicOp = panic $ "LLVM.CodeGen.genMachOp: non unary op encountered"
++ "with one argument! (" ++ show op ++ ")"
-- Handle GlobalRegs pointers
genMachOp opt o@(MO_Add _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]
= genMachOp_fast opt o r (fromInteger n) e
genMachOp opt o@(MO_Sub _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]
= genMachOp_fast opt o r (negate . fromInteger $ n) e
-- Generic case
genMachOp opt op e = genMachOp_slow opt op e
-- | Handle CmmMachOp expressions
-- This is a specialised method that handles Global register manipulations like
-- 'Sp - 16', using the getelementptr instruction.
genMachOp_fast :: EOption -> MachOp -> GlobalReg -> Int -> [CmmExpr]
-> LlvmM ExprData
genMachOp_fast opt op r n e
= do (gv, grt, s1) <- getCmmRegVal (CmmGlobal r)
dflags <- getDynFlags
let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8)
case isPointer grt && rem == 0 of
True -> do
(ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix]
(var, s3) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint ptr (llvmWord dflags)
return (var, s1 `snocOL` s2 `snocOL` s3, [])
False -> genMachOp_slow opt op e
-- | Handle CmmMachOp expressions
-- This handles all the cases not handle by the specialised genMachOp_fast.
genMachOp_slow :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData
-- Element extraction
genMachOp_slow _ (MO_V_Extract l w) [val, idx] = runExprData $ do
vval <- exprToVarW val
vidx <- exprToVarW idx
[vval'] <- castVarsW [(vval, LMVector l ty)]
doExprW ty $ Extract vval' vidx
where
ty = widthToLlvmInt w
genMachOp_slow _ (MO_VF_Extract l w) [val, idx] = runExprData $ do
vval <- exprToVarW val
vidx <- exprToVarW idx
[vval'] <- castVarsW [(vval, LMVector l ty)]
doExprW ty $ Extract vval' vidx
where
ty = widthToLlvmFloat w
-- Element insertion
genMachOp_slow _ (MO_V_Insert l w) [val, elt, idx] = runExprData $ do
vval <- exprToVarW val
velt <- exprToVarW elt
vidx <- exprToVarW idx
[vval'] <- castVarsW [(vval, ty)]
doExprW ty $ Insert vval' velt vidx
where
ty = LMVector l (widthToLlvmInt w)
genMachOp_slow _ (MO_VF_Insert l w) [val, elt, idx] = runExprData $ do
vval <- exprToVarW val
velt <- exprToVarW elt
vidx <- exprToVarW idx
[vval'] <- castVarsW [(vval, ty)]
doExprW ty $ Insert vval' velt vidx
where
ty = LMVector l (widthToLlvmFloat w)
-- Binary MachOp
genMachOp_slow opt op [x, y] = case op of
MO_Eq _ -> genBinComp opt LM_CMP_Eq
MO_Ne _ -> genBinComp opt LM_CMP_Ne
MO_S_Gt _ -> genBinComp opt LM_CMP_Sgt
MO_S_Ge _ -> genBinComp opt LM_CMP_Sge
MO_S_Lt _ -> genBinComp opt LM_CMP_Slt
MO_S_Le _ -> genBinComp opt LM_CMP_Sle
MO_U_Gt _ -> genBinComp opt LM_CMP_Ugt
MO_U_Ge _ -> genBinComp opt LM_CMP_Uge
MO_U_Lt _ -> genBinComp opt LM_CMP_Ult
MO_U_Le _ -> genBinComp opt LM_CMP_Ule
MO_Add _ -> genBinMach LM_MO_Add
MO_Sub _ -> genBinMach LM_MO_Sub
MO_Mul _ -> genBinMach LM_MO_Mul
MO_U_MulMayOflo _ -> panic "genMachOp: MO_U_MulMayOflo unsupported!"
MO_S_MulMayOflo w -> isSMulOK w x y
MO_S_Quot _ -> genBinMach LM_MO_SDiv
MO_S_Rem _ -> genBinMach LM_MO_SRem
MO_U_Quot _ -> genBinMach LM_MO_UDiv
MO_U_Rem _ -> genBinMach LM_MO_URem
MO_F_Eq _ -> genBinComp opt LM_CMP_Feq
MO_F_Ne _ -> genBinComp opt LM_CMP_Fne
MO_F_Gt _ -> genBinComp opt LM_CMP_Fgt
MO_F_Ge _ -> genBinComp opt LM_CMP_Fge
MO_F_Lt _ -> genBinComp opt LM_CMP_Flt
MO_F_Le _ -> genBinComp opt LM_CMP_Fle
MO_F_Add _ -> genBinMach LM_MO_FAdd
MO_F_Sub _ -> genBinMach LM_MO_FSub
MO_F_Mul _ -> genBinMach LM_MO_FMul
MO_F_Quot _ -> genBinMach LM_MO_FDiv
MO_And _ -> genBinMach LM_MO_And
MO_Or _ -> genBinMach LM_MO_Or
MO_Xor _ -> genBinMach LM_MO_Xor
MO_Shl _ -> genBinMach LM_MO_Shl
MO_U_Shr _ -> genBinMach LM_MO_LShr
MO_S_Shr _ -> genBinMach LM_MO_AShr
MO_V_Add l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Add
MO_V_Sub l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Sub
MO_V_Mul l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Mul
MO_VS_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SDiv
MO_VS_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SRem
MO_VU_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_UDiv
MO_VU_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_URem
MO_VF_Add l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FAdd
MO_VF_Sub l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FSub
MO_VF_Mul l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FMul
MO_VF_Quot l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FDiv
MO_Not _ -> panicOp
MO_S_Neg _ -> panicOp
MO_F_Neg _ -> panicOp
MO_SF_Conv _ _ -> panicOp
MO_FS_Conv _ _ -> panicOp
MO_SS_Conv _ _ -> panicOp
MO_UU_Conv _ _ -> panicOp
MO_FF_Conv _ _ -> panicOp
MO_V_Insert {} -> panicOp
MO_V_Extract {} -> panicOp
MO_VS_Neg {} -> panicOp
MO_VF_Insert {} -> panicOp
MO_VF_Extract {} -> panicOp
MO_VF_Neg {} -> panicOp
where
binLlvmOp ty binOp = runExprData $ do
vx <- exprToVarW x
vy <- exprToVarW y
if getVarType vx == getVarType vy
then do
doExprW (ty vx) $ binOp vx vy
else do
-- Error. Continue anyway so we can debug the generated ll file.
dflags <- getDynFlags
let style = mkCodeStyle CStyle
toString doc = renderWithStyle dflags doc style
cmmToStr = (lines . toString . PprCmm.pprExpr)
statement $ Comment $ map fsLit $ cmmToStr x
statement $ Comment $ map fsLit $ cmmToStr y
doExprW (ty vx) $ binOp vx vy
binCastLlvmOp ty binOp = runExprData $ do
vx <- exprToVarW x
vy <- exprToVarW y
[vx', vy'] <- castVarsW [(vx, ty), (vy, ty)]
doExprW ty $ binOp vx' vy'
-- | Need to use EOption here as Cmm expects word size results from
-- comparisons while LLVM return i1. Need to extend to llvmWord type
-- if expected. See Note [Literals and branch conditions].
genBinComp opt cmp = do
ed@(v1, stmts, top) <- binLlvmOp (\_ -> i1) (Compare cmp)
dflags <- getDynFlags
if getVarType v1 == i1
then case i1Expected opt of
True -> return ed
False -> do
let w_ = llvmWord dflags
(v2, s1) <- doExpr w_ $ Cast LM_Zext v1 w_
return (v2, stmts `snocOL` s1, top)
else
panic $ "genBinComp: Compare returned type other then i1! "
++ (showSDoc dflags $ ppr $ getVarType v1)
genBinMach op = binLlvmOp getVarType (LlvmOp op)
genCastBinMach ty op = binCastLlvmOp ty (LlvmOp op)
-- | Detect if overflow will occur in signed multiply of the two
-- CmmExpr's. This is the LLVM assembly equivalent of the NCG
-- implementation. Its much longer due to type information/safety.
-- This should actually compile to only about 3 asm instructions.
isSMulOK :: Width -> CmmExpr -> CmmExpr -> LlvmM ExprData
isSMulOK _ x y = runExprData $ do
vx <- exprToVarW x
vy <- exprToVarW y
dflags <- getDynFlags
let word = getVarType vx
let word2 = LMInt $ 2 * (llvmWidthInBits dflags $ getVarType vx)
let shift = llvmWidthInBits dflags word
let shift1 = toIWord dflags (shift - 1)
let shift2 = toIWord dflags shift
if isInt word
then do
x1 <- doExprW word2 $ Cast LM_Sext vx word2
y1 <- doExprW word2 $ Cast LM_Sext vy word2
r1 <- doExprW word2 $ LlvmOp LM_MO_Mul x1 y1
rlow1 <- doExprW word $ Cast LM_Trunc r1 word
rlow2 <- doExprW word $ LlvmOp LM_MO_AShr rlow1 shift1
rhigh1 <- doExprW word2 $ LlvmOp LM_MO_AShr r1 shift2
rhigh2 <- doExprW word $ Cast LM_Trunc rhigh1 word
doExprW word $ LlvmOp LM_MO_Sub rlow2 rhigh2
else
panic $ "isSMulOK: Not bit type! (" ++ showSDoc dflags (ppr word) ++ ")"
panicOp = panic $ "LLVM.CodeGen.genMachOp_slow: unary op encountered"
++ "with two arguments! (" ++ show op ++ ")"
-- More then two expression, invalid!
genMachOp_slow _ _ _ = panic "genMachOp: More then 2 expressions in MachOp!"
-- | Handle CmmLoad expression.
genLoad :: Atomic -> CmmExpr -> CmmType -> LlvmM ExprData
-- First we try to detect a few common cases and produce better code for
-- these then the default case. We are mostly trying to detect Cmm code
-- like I32[Sp + n] and use 'getelementptr' operations instead of the
-- generic case that uses casts and pointer arithmetic
genLoad atomic e@(CmmReg (CmmGlobal r)) ty
= genLoad_fast atomic e r 0 ty
genLoad atomic e@(CmmRegOff (CmmGlobal r) n) ty
= genLoad_fast atomic e r n ty
genLoad atomic e@(CmmMachOp (MO_Add _) [
(CmmReg (CmmGlobal r)),
(CmmLit (CmmInt n _))])
ty
= genLoad_fast atomic e r (fromInteger n) ty
genLoad atomic e@(CmmMachOp (MO_Sub _) [
(CmmReg (CmmGlobal r)),
(CmmLit (CmmInt n _))])
ty
= genLoad_fast atomic e r (negate $ fromInteger n) ty
-- generic case
genLoad atomic e ty
= do other <- getTBAAMeta otherN
genLoad_slow atomic e ty other
-- | Handle CmmLoad expression.
-- This is a special case for loading from a global register pointer
-- offset such as I32[Sp+8].
genLoad_fast :: Atomic -> CmmExpr -> GlobalReg -> Int -> CmmType
-> LlvmM ExprData
genLoad_fast atomic e r n ty = do
dflags <- getDynFlags
(gv, grt, s1) <- getCmmRegVal (CmmGlobal r)
meta <- getTBAARegMeta r
let ty' = cmmToLlvmType ty
(ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8)
case isPointer grt && rem == 0 of
True -> do
(ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix]
-- We might need a different pointer type, so check
case grt == ty' of
-- were fine
True -> do
(var, s3) <- doExpr ty' (MExpr meta $ loadInstr ptr)
return (var, s1 `snocOL` s2 `snocOL` s3,
[])
-- cast to pointer type needed
False -> do
let pty = pLift ty'
(ptr', s3) <- doExpr pty $ Cast LM_Bitcast ptr pty
(var, s4) <- doExpr ty' (MExpr meta $ loadInstr ptr')
return (var, s1 `snocOL` s2 `snocOL` s3
`snocOL` s4, [])
-- If its a bit type then we use the slow method since
-- we can't avoid casting anyway.
False -> genLoad_slow atomic e ty meta
where
loadInstr ptr | atomic = ALoad SyncSeqCst False ptr
| otherwise = Load ptr
-- | Handle Cmm load expression.
-- Generic case. Uses casts and pointer arithmetic if needed.
genLoad_slow :: Atomic -> CmmExpr -> CmmType -> [MetaAnnot] -> LlvmM ExprData
genLoad_slow atomic e ty meta = runExprData $ do
iptr <- exprToVarW e
dflags <- getDynFlags
case getVarType iptr of
LMPointer _ -> do
doExprW (cmmToLlvmType ty) (MExpr meta $ loadInstr iptr)
i@(LMInt _) | i == llvmWord dflags -> do
let pty = LMPointer $ cmmToLlvmType ty
ptr <- doExprW pty $ Cast LM_Inttoptr iptr pty
doExprW (cmmToLlvmType ty) (MExpr meta $ loadInstr ptr)
other -> do pprPanic "exprToVar: CmmLoad expression is not right type!"
(PprCmm.pprExpr e <+> text (
"Size of Ptr: " ++ show (llvmPtrBits dflags) ++
", Size of var: " ++ show (llvmWidthInBits dflags other) ++
", Var: " ++ showSDoc dflags (ppr iptr)))
where
loadInstr ptr | atomic = ALoad SyncSeqCst False ptr
| otherwise = Load ptr
-- | Handle CmmReg expression. This will return a pointer to the stack
-- location of the register. Throws an error if it isn't allocated on
-- the stack.
getCmmReg :: CmmReg -> LlvmM LlvmVar
getCmmReg (CmmLocal (LocalReg un _))
= do exists <- varLookup un
dflags <- getDynFlags
case exists of
Just ety -> return (LMLocalVar un $ pLift ety)
Nothing -> fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr un) ++ " was not allocated!"
-- This should never happen, as every local variable should
-- have been assigned a value at some point, triggering
-- "funPrologue" to allocate it on the stack.
getCmmReg (CmmGlobal g)
= do onStack <- checkStackReg g
dflags <- getDynFlags
if onStack
then return (lmGlobalRegVar dflags g)
else fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr g) ++ " not stack-allocated!"
-- | Return the value of a given register, as well as its type. Might
-- need to be load from stack.
getCmmRegVal :: CmmReg -> LlvmM (LlvmVar, LlvmType, LlvmStatements)
getCmmRegVal reg =
case reg of
CmmGlobal g -> do
onStack <- checkStackReg g
dflags <- getDynFlags
if onStack then loadFromStack else do
let r = lmGlobalRegArg dflags g
return (r, getVarType r, nilOL)
_ -> loadFromStack
where loadFromStack = do
ptr <- getCmmReg reg
let ty = pLower $ getVarType ptr
(v, s) <- doExpr ty (Load ptr)
return (v, ty, unitOL s)
-- | Allocate a local CmmReg on the stack
allocReg :: CmmReg -> (LlvmVar, LlvmStatements)
allocReg (CmmLocal (LocalReg un ty))
= let ty' = cmmToLlvmType ty
var = LMLocalVar un (LMPointer ty')
alc = Alloca ty' 1
in (var, unitOL $ Assignment var alc)
allocReg _ = panic $ "allocReg: Global reg encountered! Global registers should"
++ " have been handled elsewhere!"
-- | Generate code for a literal
genLit :: EOption -> CmmLit -> LlvmM ExprData
genLit opt (CmmInt i w)
-- See Note [Literals and branch conditions].
= let width | i1Expected opt = i1
| otherwise = LMInt (widthInBits w)
-- comm = Comment [ fsLit $ "EOption: " ++ show opt
-- , fsLit $ "Width : " ++ show w
-- , fsLit $ "Width' : " ++ show (widthInBits w)
-- ]
in return (mkIntLit width i, nilOL, [])
genLit _ (CmmFloat r w)
= return (LMLitVar $ LMFloatLit (fromRational r) (widthToLlvmFloat w),
nilOL, [])
genLit opt (CmmVec ls)
= do llvmLits <- mapM toLlvmLit ls
return (LMLitVar $ LMVectorLit llvmLits, nilOL, [])
where
toLlvmLit :: CmmLit -> LlvmM LlvmLit
toLlvmLit lit = do
(llvmLitVar, _, _) <- genLit opt lit
case llvmLitVar of
LMLitVar llvmLit -> return llvmLit
_ -> panic "genLit"
genLit _ cmm@(CmmLabel l)
= do var <- getGlobalPtr =<< strCLabel_llvm l
dflags <- getDynFlags
let lmty = cmmToLlvmType $ cmmLitType dflags cmm
(v1, s1) <- doExpr lmty $ Cast LM_Ptrtoint var (llvmWord dflags)
return (v1, unitOL s1, [])
genLit opt (CmmLabelOff label off) = do
dflags <- getDynFlags
(vlbl, stmts, stat) <- genLit opt (CmmLabel label)
let voff = toIWord dflags off
(v1, s1) <- doExpr (getVarType vlbl) $ LlvmOp LM_MO_Add vlbl voff
return (v1, stmts `snocOL` s1, stat)
genLit opt (CmmLabelDiffOff l1 l2 off) = do
dflags <- getDynFlags
(vl1, stmts1, stat1) <- genLit opt (CmmLabel l1)
(vl2, stmts2, stat2) <- genLit opt (CmmLabel l2)
let voff = toIWord dflags off
let ty1 = getVarType vl1
let ty2 = getVarType vl2
if (isInt ty1) && (isInt ty2)
&& (llvmWidthInBits dflags ty1 == llvmWidthInBits dflags ty2)
then do
(v1, s1) <- doExpr (getVarType vl1) $ LlvmOp LM_MO_Sub vl1 vl2
(v2, s2) <- doExpr (getVarType v1 ) $ LlvmOp LM_MO_Add v1 voff
return (v2, stmts1 `appOL` stmts2 `snocOL` s1 `snocOL` s2,
stat1 ++ stat2)
else
panic "genLit: CmmLabelDiffOff encountered with different label ty!"
genLit opt (CmmBlock b)
= genLit opt (CmmLabel $ infoTblLbl b)
genLit _ CmmHighStackMark
= panic "genStaticLit - CmmHighStackMark unsupported!"
-- -----------------------------------------------------------------------------
-- * Misc
--
-- | Find CmmRegs that get assigned and allocate them on the stack
--
-- Any register that gets written needs to be allcoated on the
-- stack. This avoids having to map a CmmReg to an equivalent SSA form
-- and avoids having to deal with Phi node insertion. This is also
-- the approach recommended by LLVM developers.
--
-- On the other hand, this is unecessarily verbose if the register in
-- question is never written. Therefore we skip it where we can to
-- save a few lines in the output and hopefully speed compilation up a
-- bit.
funPrologue :: LiveGlobalRegs -> [CmmBlock] -> LlvmM StmtData
funPrologue live cmmBlocks = do
trash <- getTrashRegs
let getAssignedRegs :: CmmNode O O -> [CmmReg]
getAssignedRegs (CmmAssign reg _) = [reg]
-- Calls will trash all registers. Unfortunately, this needs them to
-- be stack-allocated in the first place.
getAssignedRegs (CmmUnsafeForeignCall _ rs _) = map CmmGlobal trash ++ map CmmLocal rs
getAssignedRegs _ = []
getRegsBlock (_, body, _) = concatMap getAssignedRegs $ blockToList body
assignedRegs = nub $ concatMap (getRegsBlock . blockSplit) cmmBlocks
isLive r = r `elem` alwaysLive || r `elem` live
dflags <- getDynFlags
stmtss <- flip mapM assignedRegs $ \reg ->
case reg of
CmmLocal (LocalReg un _) -> do
let (newv, stmts) = allocReg reg
varInsert un (pLower $ getVarType newv)
return stmts
CmmGlobal r -> do
let reg = lmGlobalRegVar dflags r
arg = lmGlobalRegArg dflags r
ty = (pLower . getVarType) reg
trash = LMLitVar $ LMUndefLit ty
rval = if isLive r then arg else trash
alloc = Assignment reg $ Alloca (pLower $ getVarType reg) 1
markStackReg r
return $ toOL [alloc, Store rval reg]
return (concatOL stmtss, [])
-- | Function epilogue. Load STG variables to use as argument for call.
-- STG Liveness optimisation done here.
funEpilogue :: LiveGlobalRegs -> LlvmM ([LlvmVar], LlvmStatements)
funEpilogue live = do
-- Have information and liveness optimisation is enabled?
let liveRegs = alwaysLive ++ live
isSSE (FloatReg _) = True
isSSE (DoubleReg _) = True
isSSE (XmmReg _) = True
isSSE (YmmReg _) = True
isSSE (ZmmReg _) = True
isSSE _ = False
-- Set to value or "undef" depending on whether the register is
-- actually live
dflags <- getDynFlags
let loadExpr r = do
(v, _, s) <- getCmmRegVal (CmmGlobal r)
return (Just $ v, s)
loadUndef r = do
let ty = (pLower . getVarType $ lmGlobalRegVar dflags r)
return (Just $ LMLitVar $ LMUndefLit ty, nilOL)
platform <- getDynFlag targetPlatform
loads <- flip mapM (activeStgRegs platform) $ \r -> case () of
_ | r `elem` liveRegs -> loadExpr r
| not (isSSE r) -> loadUndef r
| otherwise -> return (Nothing, nilOL)
let (vars, stmts) = unzip loads
return (catMaybes vars, concatOL stmts)
-- | A series of statements to trash all the STG registers.
--
-- In LLVM we pass the STG registers around everywhere in function calls.
-- So this means LLVM considers them live across the entire function, when
-- in reality they usually aren't. For Caller save registers across C calls
-- the saving and restoring of them is done by the Cmm code generator,
-- using Cmm local vars. So to stop LLVM saving them as well (and saving
-- all of them since it thinks they're always live, we trash them just
-- before the call by assigning the 'undef' value to them. The ones we
-- need are restored from the Cmm local var and the ones we don't need
-- are fine to be trashed.
getTrashStmts :: LlvmM LlvmStatements
getTrashStmts = do
regs <- getTrashRegs
stmts <- flip mapM regs $ \ r -> do
reg <- getCmmReg (CmmGlobal r)
let ty = (pLower . getVarType) reg
return $ Store (LMLitVar $ LMUndefLit ty) reg
return $ toOL stmts
getTrashRegs :: LlvmM [GlobalReg]
getTrashRegs = do plat <- getLlvmPlatform
return $ filter (callerSaves plat) (activeStgRegs plat)
-- | Get a function pointer to the CLabel specified.
--
-- This is for Haskell functions, function type is assumed, so doesn't work
-- with foreign functions.
getHsFunc :: LiveGlobalRegs -> CLabel -> LlvmM ExprData
getHsFunc live lbl
= do fty <- llvmFunTy live
name <- strCLabel_llvm lbl
getHsFunc' name fty
getHsFunc' :: LMString -> LlvmType -> LlvmM ExprData
getHsFunc' name fty
= do fun <- getGlobalPtr name
if getVarType fun == fty
then return (fun, nilOL, [])
else do (v1, s1) <- doExpr (pLift fty)
$ Cast LM_Bitcast fun (pLift fty)
return (v1, unitOL s1, [])
-- | Create a new local var
mkLocalVar :: LlvmType -> LlvmM LlvmVar
mkLocalVar ty = do
un <- runUs getUniqueM
return $ LMLocalVar un ty
-- | Execute an expression, assigning result to a var
doExpr :: LlvmType -> LlvmExpression -> LlvmM (LlvmVar, LlvmStatement)
doExpr ty expr = do
v <- mkLocalVar ty
return (v, Assignment v expr)
-- | Expand CmmRegOff
expandCmmReg :: DynFlags -> (CmmReg, Int) -> CmmExpr
expandCmmReg dflags (reg, off)
= let width = typeWidth (cmmRegType dflags reg)
voff = CmmLit $ CmmInt (fromIntegral off) width
in CmmMachOp (MO_Add width) [CmmReg reg, voff]
-- | Convert a block id into a appropriate Llvm label
blockIdToLlvm :: BlockId -> LlvmVar
blockIdToLlvm bid = LMLocalVar (getUnique bid) LMLabel
-- | Create Llvm int Literal
mkIntLit :: Integral a => LlvmType -> a -> LlvmVar
mkIntLit ty i = LMLitVar $ LMIntLit (toInteger i) ty
-- | Convert int type to a LLvmVar of word or i32 size
toI32 :: Integral a => a -> LlvmVar
toI32 = mkIntLit i32
toIWord :: Integral a => DynFlags -> a -> LlvmVar
toIWord dflags = mkIntLit (llvmWord dflags)
-- | Error functions
panic :: String -> a
panic s = Outputable.panic $ "LlvmCodeGen.CodeGen." ++ s
pprPanic :: String -> SDoc -> a
pprPanic s d = Outputable.pprPanic ("LlvmCodeGen.CodeGen." ++ s) d
-- | Returns TBAA meta data by unique
getTBAAMeta :: Unique -> LlvmM [MetaAnnot]
getTBAAMeta u = do
mi <- getUniqMeta u
return [MetaAnnot tbaa (MetaNode i) | let Just i = mi]
-- | Returns TBAA meta data for given register
getTBAARegMeta :: GlobalReg -> LlvmM [MetaAnnot]
getTBAARegMeta = getTBAAMeta . getTBAA
-- | A more convenient way of accumulating LLVM statements and declarations.
data LlvmAccum = LlvmAccum LlvmStatements [LlvmCmmDecl]
#if __GLASGOW_HASKELL__ > 710
instance Semigroup LlvmAccum where
LlvmAccum stmtsA declsA <> LlvmAccum stmtsB declsB =
LlvmAccum (stmtsA Semigroup.<> stmtsB) (declsA Semigroup.<> declsB)
#endif
instance Monoid LlvmAccum where
mempty = LlvmAccum nilOL []
LlvmAccum stmtsA declsA `mappend` LlvmAccum stmtsB declsB =
LlvmAccum (stmtsA `mappend` stmtsB) (declsA `mappend` declsB)
liftExprData :: LlvmM ExprData -> WriterT LlvmAccum LlvmM LlvmVar
liftExprData action = do
(var, stmts, decls) <- lift action
tell $ LlvmAccum stmts decls
return var
statement :: LlvmStatement -> WriterT LlvmAccum LlvmM ()
statement stmt = tell $ LlvmAccum (unitOL stmt) []
doExprW :: LlvmType -> LlvmExpression -> WriterT LlvmAccum LlvmM LlvmVar
doExprW a b = do
(var, stmt) <- lift $ doExpr a b
statement stmt
return var
exprToVarW :: CmmExpr -> WriterT LlvmAccum LlvmM LlvmVar
exprToVarW = liftExprData . exprToVar
runExprData :: WriterT LlvmAccum LlvmM LlvmVar -> LlvmM ExprData
runExprData action = do
(var, LlvmAccum stmts decls) <- runWriterT action
return (var, stmts, decls)
runStmtsDecls :: WriterT LlvmAccum LlvmM () -> LlvmM (LlvmStatements, [LlvmCmmDecl])
runStmtsDecls action = do
LlvmAccum stmts decls <- execWriterT action
return (stmts, decls)
getCmmRegW :: CmmReg -> WriterT LlvmAccum LlvmM LlvmVar
getCmmRegW = lift . getCmmReg
genLoadW :: Atomic -> CmmExpr -> CmmType -> WriterT LlvmAccum LlvmM LlvmVar
genLoadW atomic e ty = liftExprData $ genLoad atomic e ty
doTrashStmts :: WriterT LlvmAccum LlvmM ()
doTrashStmts = do
stmts <- lift getTrashStmts
tell $ LlvmAccum stmts mempty
| gridaphobe/ghc | compiler/llvmGen/LlvmCodeGen/CodeGen.hs | bsd-3-clause | 71,533 | 0 | 25 | 21,030 | 19,433 | 9,599 | 9,834 | 1,235 | 64 |
module Reader (
ask
, asks
, local
, Reader
, runReader
)
where
newtype Reader a b = Reader { runReader :: a -> b }
instance Functor (Reader a) where
fmap f (Reader g) = Reader $ f . g
instance Applicative (Reader a) where
pure = Reader . const
(Reader rf) <*> (Reader rv) = Reader (\e -> rf e $ rv e)
instance Monad (Reader a) where
return = Reader . const
(Reader a) >>= k = Reader $ \x ->
let (Reader f) = k . a $ x in f x
ask :: Reader a a
ask = Reader id
asks :: (a -> b) -> Reader a b
asks f = fmap f ask
local :: (a -> b) -> Reader b c -> Reader a c
local f (Reader r) = Reader $ r . f
| pcrama/message-compiler | src/Reader.hs | bsd-3-clause | 617 | 0 | 13 | 168 | 329 | 170 | 159 | 22 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.ProvokingVertex
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/provoking_vertex.txt ARB_provoking_vertex> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.ProvokingVertex (
-- * Enums
gl_FIRST_VERTEX_CONVENTION,
gl_LAST_VERTEX_CONVENTION,
gl_PROVOKING_VERTEX,
gl_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION,
-- * Functions
glProvokingVertex
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/ProvokingVertex.hs | bsd-3-clause | 851 | 0 | 4 | 97 | 58 | 46 | 12 | 8 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module Azure.DocDB.ETag (
ETag(..),
ETagged(..),
ifMatch,
ifNoneMatch,
) where
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Network.HTTP.Types.Header (Header, hIfMatch, hIfNoneMatch)
import Web.HttpApiData (ToHttpApiData(..))
-- | An Entity Tag
newtype ETag = ETag T.Text deriving (Eq, Ord, Show)
instance ToHttpApiData ETag where
toUrlPiece (ETag t) = t
toHeader (ETag t) = T.encodeUtf8 t
-- | A value which may have an associated entity tag
data ETagged a = ETagged (Maybe ETag) a deriving (Eq, Ord, Show)
etagMerge :: Eq t => Maybe t -> Maybe t -> Maybe t
etagMerge Nothing x = x
etagMerge x Nothing = x
etagMerge x y | x == y = x
etagMerge _ _ = Nothing
instance Functor ETagged where
fmap f (ETagged t a) = ETagged t (f a)
instance Applicative ETagged where
pure = ETagged Nothing
(ETagged t1 f) <*> (ETagged t2 v) = ETagged (etagMerge t1 t2) (f v)
instance Monad ETagged where
(ETagged t1 a) >>= f = ETagged (etagMerge t1 t2) n
where
(ETagged t2 n) = f a
-- TODO: These functions could be made into lenses, allowing for both retrieval
-- and setting an ETag header.
-- :: (Eq a, ToHttpApiData b, FromHttpApiData b) => Lens' [(a, b)] (Maybe b)
ifMatch :: ETag -> Header
ifMatch tag = (hIfMatch, toHeader tag)
ifNoneMatch :: ETag -> Header
ifNoneMatch tag = (hIfNoneMatch, toHeader tag)
| jnonce/azure-docdb | lib/Azure/DocDB/ETag.hs | bsd-3-clause | 1,462 | 0 | 9 | 303 | 474 | 255 | 219 | 33 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module ViewDataApi
( viewDataAPI
, OxygenClientInfo(..)
, OxygenClientToken(..)
, OSSObjectPolicy(..)
, OSSBucketInfo(..)
, OSSObjectInfo(..)
, getServerAccessToken
, createOSSBucket
, tokenHeaderValue
, ossUploadFile
, registerViewingService
, checkViewingServiceStatus
, downloadViewingServiceObjectThumbnail
) where
import Control.Applicative as A
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Except
import qualified Data.Aeson as J
import Data.Aeson.TH
import Data.Monoid
import Data.Proxy
import Data.Typeable
import Data.Text (Text)
import Data.ByteString.Base64 (encode)
import qualified Data.ByteString.Char8 as BLS
import qualified Network.HTTP.Media as M
import GHC.Generics
import Servant.API
import Servant.Client
import Network.HTTP.Client (Manager)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as BS
import System.FilePath.Posix
import System.Directory
import qualified Data.Text as T
import qualified Data.Text.IO as T
-- 1. Auth API
data OxygenClientInfo = OxygenClientInfo{
oxygenClientId :: Text
, oxygenClientSecret :: Text
} deriving (Eq, Show, Generic)
instance J.FromJSON OxygenClientInfo
instance J.ToJSON OxygenClientInfo
instance ToFormUrlEncoded OxygenClientInfo where
toFormUrlEncoded clientInfo = [("client_id", oxygenClientId clientInfo), ("client_secret", oxygenClientSecret clientInfo), ("grant_type", "client_credentials")]
data OxygenClientToken = OxygenClientToken{
token_type :: String
, expires_in :: Int
, access_token :: String
}deriving (Eq, Show, Generic)
instance J.FromJSON OxygenClientToken
instance J.ToJSON OxygenClientToken
tokenHeaderValue :: OxygenClientToken -> String
tokenHeaderValue token = token_type token ++ " " ++ access_token token
-- 2. OSS Create bucket
data OSSObjectPolicy = Transient | Temporary | Persistent
deriving (Eq, Show)
instance J.ToJSON OSSObjectPolicy where
toJSON Transient = J.String "transient"
toJSON Temporary = J.String "temporary"
toJSON Persistent = J.String "persistent"
instance J.FromJSON OSSObjectPolicy where
parseJSON (J.String "transient") = return Transient
parseJSON (J.String "temporary") = return Temporary
parseJSON (J.String "persistent") = return Persistent
parseJSON _ = A.empty
data OSSBucketInfo = OSSBucketInfo{
bucketKey :: String
, policyKey :: OSSObjectPolicy
}deriving (Eq, Show, Generic)
instance J.ToJSON OSSBucketInfo
instance J.FromJSON OSSBucketInfo
data OSSObjectInfo = OSSObjectInfo{
ossBucketKey :: String
, ossObjectId :: String
, ossObjectKey :: String
, ossObjectSize :: Int
, ossObjectLocation :: String
}deriving (Eq, Show, Generic)
ossObjectInfoFieldMapping "ossBucketKey" = "bucketKey"
ossObjectInfoFieldMapping "ossObjectId" = "objectId"
ossObjectInfoFieldMapping "ossObjectKey" = "objectKey"
ossObjectInfoFieldMapping "ossObjectSize" = "size"
ossObjectInfoFieldMapping "ossObjectLocation" = "location"
ossObjectInfoFieldMapping s = s
instance J.FromJSON OSSObjectInfo where
parseJSON = J.genericParseJSON (J.defaultOptions { fieldLabelModifier = ossObjectInfoFieldMapping })
data Base64OSSObjectURNJSON = Base64OSSObjectURNJSON{
urn :: String
}deriving (Eq, Show, Generic)
instance J.ToJSON Base64OSSObjectURNJSON
data PNG deriving Typeable
instance MimeUnrender PNG BL.ByteString where
mimeUnrender _ = Right . id
-- | @Right . toStrict@
instance MimeUnrender PNG BS.ByteString where
mimeUnrender _ = Right . BL.toStrict
-- We declare what MIME type it represents using the great 'Network.HTTP.Media'
-- package
instance Accept PNG where
contentType _ = "image" M.// "png"
---------------------------
-- API Declaration
---------------------------
type OxygenAuth = "authentication" :> "v1" :> "authenticate" :> ReqBody '[FormUrlEncoded] OxygenClientInfo :> Post '[JSON] OxygenClientToken
type OSSCreateBucket = "oss" :> "v2" :> "buckets" :> Header "Authorization" String :> ReqBody '[JSON] OSSBucketInfo :> Post '[JSON] OSSBucketInfo
type OSSUpload = "oss" :> "v2" :> "buckets" :> Capture "bucketKey" String :> "objects" :> Capture "objectName" String :> Header "Authorization" String :> ReqBody '[OctetStream] BL.ByteString :> Put '[JSON] OSSObjectInfo
type RegisterViewingService = "viewingservice" :> "v1" :> "register" :> Header "Authorization" String :> ReqBody '[JSON] Base64OSSObjectURNJSON :> PostNoContent '[JSON] NoContent
type CheckViewingServiceStatus = "viewingservice" :> "v1" :> Capture "base64ObjectURN" String :> "status" :> Header "Authorization" String :> GetNoContent '[JSON] J.Object
type GetViewingServiceObjectThumbnail = "viewingservice" :> "v1" :> "thumbnails" :> Capture "base64ObjectURN" String :> Header "Authorization" String :> Get '[PNG] BL.ByteString
type ViewDataAPI = OxygenAuth :<|> OSSCreateBucket :<|> OSSUpload :<|> RegisterViewingService
:<|> CheckViewingServiceStatus :<|> GetViewingServiceObjectThumbnail
viewDataAPI :: Proxy ViewDataAPI
viewDataAPI = Proxy
getServerAccessToken :: OxygenClientInfo -> Manager -> BaseUrl -> ExceptT ServantError IO OxygenClientToken
createOSSBucket :: Maybe String -> OSSBucketInfo -> Manager -> BaseUrl -> ExceptT ServantError IO OSSBucketInfo
ossUpload :: String -> String -> Maybe String -> BL.ByteString -> Manager -> BaseUrl -> ExceptT ServantError IO OSSObjectInfo
registerViewingServiceRaw :: Maybe String -> Base64OSSObjectURNJSON -> Manager -> BaseUrl -> ExceptT ServantError IO NoContent
checkViewingServiceStatusRaw :: String -> Maybe String -> Manager -> BaseUrl -> ExceptT ServantError IO J.Object
getViewingServiceObjectThumbnailRaw :: String -> Maybe String -> Manager -> BaseUrl -> ExceptT ServantError IO BL.ByteString
getServerAccessToken :<|> createOSSBucket :<|> ossUpload :<|> registerViewingServiceRaw
:<|> checkViewingServiceStatusRaw :<|> getViewingServiceObjectThumbnailRaw = client viewDataAPI
ossUploadFile :: OxygenClientToken -> String -> FilePath -> Manager -> BaseUrl -> ExceptT ServantError IO OSSObjectInfo
ossUploadFile token bucketKey filePath manager url = do
filecontent <- liftIO . BL.readFile $ filePath
ossUpload bucketKey (takeFileName filePath) (Just $ tokenHeaderValue token) filecontent manager url
toBase64 :: String -> String
toBase64 = BLS.unpack . encode . BLS.pack
toBase64OSSObjectURNJSON :: String -> Base64OSSObjectURNJSON
toBase64OSSObjectURNJSON = Base64OSSObjectURNJSON . toBase64
registerViewingService :: OxygenClientToken -> String -> Manager -> BaseUrl -> ExceptT ServantError IO NoContent
registerViewingService token ossURN = registerViewingServiceRaw (Just $ tokenHeaderValue token) $ toBase64OSSObjectURNJSON ossURN
checkViewingServiceStatus :: OxygenClientToken -> String -> Manager -> BaseUrl -> ExceptT ServantError IO J.Object
checkViewingServiceStatus token ossURN = checkViewingServiceStatusRaw (toBase64 ossURN) (Just $ tokenHeaderValue token)
downloadViewingServiceObjectThumbnail :: OxygenClientToken -> String -> FilePath -> Manager -> BaseUrl -> ExceptT ServantError IO ()
downloadViewingServiceObjectThumbnail token ossURN path manager url = getViewingServiceObjectThumbnailRaw (toBase64 ossURN) (Just $ tokenHeaderValue token) manager url >>= liftIO . BL.writeFile path
| chainone/HForgeAPIClient | src/ViewDataApi.hs | bsd-3-clause | 7,560 | 0 | 15 | 1,086 | 1,818 | 976 | 842 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Day5 where
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString as S
import Data.ByteString (ByteString)
import qualified Data.IntMap.Strict as IntMap
import Data.IntMap.Strict (IntMap)
import Control.Monad.State
import Numeric
import Crypto.Hash
import Data.List
import Debug.Trace
numDigits x
| x == 0 = 0
| x < 10 = 1
| x >= 10 = 1 + numDigits (x `div` 10)
nextHelper :: Integer -> ByteString -> (Char, Integer)
nextHelper i s
| "00000" `isPrefixOf` m = (head . drop 5 $ m, i)
| otherwise = nextHelper (1+i) s
where
t = C.concat [s, pad, C.pack (show i)]
pad = C.replicate (5 - numDigits i) '0'
h = (hash t :: Digest MD5)
m = show h
next :: (String, Integer) -> ByteString -> (String, Integer)
next (z, i) s = (z ++ [c], 1+i')
where (c, i') = nextHelper i s
next' r i s
| not ("00000" `isPrefixOf` msg) = next' r (1+i) s
| IntMap.size r == 8 = r
| pos `IntMap.member` r || pos >= 8 = next' r (1+i) s
| pos `IntMap.notMember` r = next' (IntMap.insert pos ch r) (1+i) s
where
t = C.concat [s, pad, C.pack (show i)]
pad = C.replicate (5 - numDigits i) '0'
h = (hash t :: Digest MD5)
msg = show h
(pos_:ch:_) = drop 5 msg
pos = fst . head . readHex . pure $ pos_
password :: ByteString -> ByteString
password = C.pack . fst . foldl next ([], 0) . replicate 8
password' :: ByteString -> ByteString
password' = C.pack . IntMap.elems . next' IntMap.empty 0
| cl04/advent2016 | src/Day5.hs | bsd-3-clause | 1,533 | 0 | 11 | 381 | 714 | 382 | 332 | 42 | 1 |
module System.FTDI
( -- *Devices
Device
, ChipType(..)
, getChipType
, setChipType
, fromUSBDevice
, guessChipType
-- *Interfaces
, Interface(..)
-- *Device handles
, DeviceHandle
, resetUSB
, getTimeout
, setTimeout
, openDevice
, closeDevice
, withDeviceHandle
-- *Interface handles
, InterfaceHandle
, getDeviceHandle
, getInterface
, openInterface
, closeInterface
, withInterfaceHandle
-- *Data transfer
, ChunkedReaderT
, runChunkedReaderT
, readData
-- **Low level bulk transfers
-- |These are low-level functions and as such they ignores things like:
--
-- * Max packet size
--
-- * Latency timer
--
-- * Modem status bytes
--
-- USB timeouts are not ignored, but they will prevent the request from
-- being completed.
, readBulk
, writeBulk
-- *Control requests
, reset
, purgeReadBuffer
, purgeWriteBuffer
, getLatencyTimer
, setLatencyTimer
, BitMode(..)
, setBitMode
-- **Line properties
, Parity(..)
, BitDataFormat(..)
, StopBits(..)
, setLineProperty
, BaudRate(..)
, nearestBaudRate
, setBaudRate
-- **Modem status
, ModemStatus(..)
, pollModemStatus
-- *Flow control
, FlowCtrl(..)
, setFlowControl
, setDTR
, setRTS
, setEventCharacter
, setErrorCharacter
-- *Defaults
, defaultTimeout
) where
import System.FTDI.Internal
| roelvandijk/ftdi | System/FTDI.hs | bsd-3-clause | 1,579 | 0 | 5 | 519 | 215 | 153 | 62 | 51 | 0 |
{-# LANGUAGE TypeFamilies #-}
module EFA2.Interpreter.Interpreter where
import qualified Data.Map as M
import qualified Data.List as L
import qualified EFA2.Signal.Index as Idx
import qualified EFA2.Signal.Signal as S
import qualified EFA2.Signal.Data as D
import qualified EFA2.Signal.Base as Base
import qualified EFA2.Report.Format as Format
import EFA2.Signal.Signal (toConst, (.+), (.*))
import EFA2.Signal.Typ (Typ, UT)
import EFA2.Solver.Equation (AbsAssign(GivenIdx, (::=)), EqTerm, Term(..), formatTerm)
import EFA2.Interpreter.InTerm (InRhs(..), InEquation(..))
import EFA2.Interpreter.Env as Env
import EFA2.Utils.Utils (safeLookup)
eqToInTerm :: Show a => Envs rec a -> AbsAssign -> InEquation a
eqToInTerm envs (GivenIdx t) =
InEqual t $
case t of
Energy idx -> InGiven (energyMap envs `safeLookup` idx)
DEnergy idx -> InGiven (denergyMap envs `safeLookup` idx)
Power idx -> InGiven (powerMap envs `safeLookup` idx)
DPower idx -> InGiven (dpowerMap envs `safeLookup` idx)
FEta idx -> InFunc (fetaMap envs `safeLookup` idx)
DEta idx -> InFunc (detaMap envs `safeLookup` idx)
{-
(DEta idx := ((FEta x) :+ (Minus (FEta y)))) -> InEqual (DEta idx) (InFunc (\z -> fx z .- fy z))
where fx = fetaMap envs `safeLookup` x
fy = fetaMap envs `safeLookup` y
-}
DTime idx -> InGiven (dtimeMap envs `safeLookup` idx)
X idx -> InGiven (xMap envs `safeLookup` idx)
DX idx -> InGiven (dxMap envs `safeLookup` idx)
Var idx -> InGiven (varMap envs `safeLookup` idx)
Store idx -> InGiven (storageMap envs `safeLookup` idx)
eqToInTerm _envs (x ::= y) =
InEqual x $ InTerm y
showInRhs :: (Show a) => InRhs a -> String
showInRhs (InTerm t) = Format.unUnicode $ formatTerm t
showInRhs (InGiven xs) = "given " ++ show xs
showInRhs (InFunc _) = "given <function>"
showInEquation :: (Show a) => InEquation a -> String
showInEquation (InEqual s t) =
Format.unUnicode (Format.index s) ++ " = " ++ showInRhs t
type Signal s c a = S.TC s (Typ UT UT UT) (D.Data c a)
interpretRhs ::
(Show v, v ~ D.Apply c a, D.ZipWith c,
D.Storage c a, S.Const s c, S.Arith s s ~ s,
Fractional a, Base.DArith0 a, Base.BSum a, Base.BProd a a) =>
Int ->
Envs rec (Signal s c a) ->
InRhs (Signal s c a) ->
Signal s c a
interpretRhs len envs rhs =
case rhs of
InGiven x -> x
InTerm term -> interpretTerm len envs term
interpretTerm ::
(Show v, v ~ D.Apply c a, D.ZipWith c,
D.Storage c a, S.Const s c, S.Arith s s ~ s,
Fractional a, Base.DArith0 a, Base.BSum a, Base.BProd a a) =>
Int ->
Envs rec (Signal s c a) ->
EqTerm ->
Signal s c a
interpretTerm len envs = go
where
go term =
case term of
-- Const x -> S.fromVal len [x] -- Wichtig für delta Rechnung?
-- InGiven xs -> S.map (:[]) xs
-- Const x -> S.fromVal len x
Const x -> toConst len $ fromRational x
-- Const x -> toScalar (Const x)
Atom i ->
case i of
Energy idx -> energyMap envs `safeLookup` idx
DEnergy idx -> denergyMap envs `safeLookup` idx
Power idx -> powerMap envs `safeLookup` idx
DPower idx -> dpowerMap envs `safeLookup` idx
FEta idx@(Idx.FEta r f t) -> (fetaMap envs `safeLookup` idx) (powerMap envs `safeLookup` pidx)
where pidx = Idx.Power r f t
-- DEta idx -> detaMap envs `safeLookup` idx
DEta idx@(Idx.DEta r f t) -> (detaMap envs `safeLookup` idx) (powerMap envs `safeLookup` pidx)
where pidx = Idx.Power r f t
DTime idx -> dtimeMap envs `safeLookup` idx
X idx -> xMap envs `safeLookup` idx
DX idx -> dxMap envs `safeLookup` idx
Var idx -> varMap envs `safeLookup` idx
Store idx -> storageMap envs `safeLookup` idx
Minus t -> S.neg (go t)
Recip (Atom (FEta idx@(Idx.FEta r f t))) ->
S.rec $ (fetaMap envs `safeLookup` idx) pval
where pidx = Idx.Power r t f
pval = powerMap envs `safeLookup` pidx
Recip t -> S.rec $ go t
s :+ t -> go s .+ go t
s :* t -> go s .* go t
insert ::
(Ord k, Show v, v ~ D.Apply c a, D.ZipWith c,
D.Storage c a, S.Const s c, S.Arith s s ~ s,
Fractional a, Base.DArith0 a, Base.BSum a, Base.BProd a a) =>
Int ->
k ->
Envs rec (Signal s c a) ->
InRhs (Signal s c a) ->
M.Map k (Signal s c a) ->
M.Map k (Signal s c a)
insert len idx envs rhs m = M.insert idx (interpretRhs len envs rhs) m
interpretEq ::
(Show v, v ~ D.Apply c a, D.ZipWith c,
D.Storage c a, S.Const s c, S.Arith s s ~ s,
Fractional a, Base.DArith0 a, Base.BSum a, Base.BProd a a) =>
Int ->
Envs rec (Signal s c a) ->
InEquation (Signal s c a) ->
Envs rec (Signal s c a)
interpretEq len envs eq =
case eq of
(InEqual (Energy idx) rhs) -> envs { energyMap = insert len idx envs rhs (energyMap envs) }
(InEqual (DEnergy idx) rhs) -> envs { denergyMap = insert len idx envs rhs (denergyMap envs) }
(InEqual (Power idx) rhs) -> envs { powerMap = insert len idx envs rhs (powerMap envs) }
(InEqual (DPower idx) rhs) -> envs { dpowerMap = insert len idx envs rhs (dpowerMap envs) }
(InEqual (FEta idx) (InFunc feta)) -> envs { fetaMap = M.insert idx feta (fetaMap envs) }
{-
(InEqual (FEta idx@(Idx.FEta r f t) _) ((Recip (Power pidx1)) :* (Power pidx2))) -> envs''
where envs' = envs { fetaMap = M.insert idx (mkEtaFunc pts) (fetaMap envs) }
envs'' = envs' { fetaMap = M.insert (Idx.FEta s r t f) (mkEtaFunc (reversePts pts)) (fetaMap envs') }
p1 = powerMap envs M.! pidx1
p2 = powerMap envs M.! pidx2
pts = Pt p2 (p2 ./ p1)
-}
-- (InEqual (DEta idx) rhs) -> envs { detaMap = insert len idx envs rhs (detaMap envs) }
(InEqual (DEta idx) (InFunc deta)) -> envs { detaMap = M.insert idx deta (detaMap envs) }
(InEqual (DTime idx) rhs) -> envs { dtimeMap = insert len idx envs rhs (dtimeMap envs) }
(InEqual (X idx) rhs) -> envs { xMap = insert len idx envs rhs (xMap envs) }
(InEqual (DX idx) rhs) -> envs { dxMap = insert len idx envs rhs (dxMap envs) }
(InEqual (Var idx) rhs) -> envs { varMap = insert len idx envs rhs (varMap envs) }
(InEqual (Store idx) rhs) -> envs { storageMap = insert len idx envs rhs (storageMap envs) }
t -> error ("interpretEq: " ++ show t)
-- _ -> error ("interpretEq: " ++ showInEquation eq)
interpretFromScratch ::
(Show v, v ~ D.Apply c a, D.ZipWith c,
D.Storage c a, S.Const s c, S.Arith s s ~ s,
Fractional a, Base.DArith0 a, Base.BSum a, Base.BProd a a) =>
rec ->
Int ->
[InEquation (Signal s c a)] ->
Envs rec (Signal s c a)
interpretFromScratch rec len ts =
(L.foldl' (interpretEq len) emptyEnv ts) { recordNumber = rec }
| energyflowanalysis/efa-2.1 | attic/src/EFA2/Interpreter/Interpreter.hs | bsd-3-clause | 7,047 | 0 | 18 | 2,001 | 2,666 | 1,372 | 1,294 | 130 | 17 |
--
-- Insert Documentation here :-)
--
module Reactive.Banana.BOGRE.OGRE where
import Reactive.Banana
import Reactive.Banana.Frameworks (
Frameworks,
AddHandler,
fromAddHandler,
newAddHandler
)
import Control.Concurrent (
forkIO
)
import System.Exit
import Control.Monad
import Graphics.Ogre.HOgre
import Graphics.Ogre.Types
import BB.Workarounds
type Position = (Float,Float,Float)
data World = World {
worldObject :: SceneNode,
worldObjectPosition :: Position
}
data DisplaySystem = DisplaySystem {
window :: RenderWindow,
root :: Root,
sceneManager :: SceneManager
}
createDisplaySystem :: IO(DisplaySystem)
createDisplaySystem = do
-- construct Ogre::Root
root <- root_new "plugins.cfg" "ogre.cfg" "Ogre.log"
-- setup resources
root_addResourceLocation root "../Media" "FileSystem" "Group" True
-- configure
-- show the configuration dialog and initialise the system
restored <- root_restoreConfig root
when (not restored) $ do
configured <- root_showConfigDialog root
when (not configured) $ exitWith (ExitFailure 1)
window <- root_initialise root True "Render Window" ""
-- set default mipmap level (some APIs ignore this)
root_getTextureManager root >>= \tmgr -> textureManager_setDefaultNumMipmaps tmgr 5
-- initialise all resource groups
resourceGroupManager_getSingletonPtr >>= resourceGroupManager_initialiseAllResourceGroups
-- create the scene manager, here a generic one
smgr <- root_createSceneManager_RootPcharPcharP root "DefaultSceneManager" "Scene Manager"
-- create and position the camera
cam <- sceneManager_createCamera smgr "PlayerCam"
frustum_setNearClipDistance (toFrustum cam) 5
-- create one viewport, entire window
vp <- renderTarget_addViewport (toRenderTarget window) cam 0 0 0 1 1
colourValue_with 0 0 0 1 $ viewport_setBackgroundColour vp
-- Alter the camera aspect ratio to match the viewport
vpw <- viewport_getActualWidth vp
vph <- viewport_getActualHeight vp
frustum_setAspectRatio (toFrustum cam) (fromIntegral vpw / fromIntegral vph)
-- AddHandler for the render Event
(renderAH, fireRenderEvent) <- newAddHandler
return DisplaySystem {
window = window,
root = root,
sceneManager = smgr
}
closeDisplaySystem :: DisplaySystem -> IO ()
closeDisplaySystem = root_delete . root
nullHandler :: Root -> Float -> () -> IO ((), Bool)
nullHandler _ _ _ = return ((), True)
addEntity :: DisplaySystem -> String -> IO (Entity, SceneNode)
addEntity ds mesh = do
let smgr = sceneManager ds
ent <- sceneManager_createEntity_SceneManagerPcharP smgr mesh
rootNode <- sceneManager_getRootSceneNode smgr
node <- sceneManager_createSceneNode_SceneManagerP smgr
node_addChild (toNode rootNode) (toNode node)
sceneNode_attachObject node (toMovableObject ent)
return (ent, node)
getPosition :: SceneNode -> IO (Float, Float, Float)
getPosition sn = do
pos <- node_getPosition (toNode sn)
x <- getVector3X pos
y <- getVector3Y pos
z <- getVector3Z pos
return (x,y,z)
setPosition :: SceneNode -> (Float, Float, Float) -> IO ()
setPosition sn (x,y,z) = node_setPosition (toNode sn) x y z
setPositionRelative :: SceneNode -> (Float, Float, Float) -> IO ()
setPositionRelative sn (x,y,z) = node_translate_NodePfloatfloatfloatNodeTransformSpace (toNode sn) x y z TS_WORLD
render :: RenderWindow -> Root -> a -> (Root -> Float -> Float -> a -> IO (a, Bool)) -> IO a
render win root value fun = do
timer <- root_getTimer root
time <- timer_getMicroseconds timer
render' time win root value fun
render' :: Int -> RenderWindow -> Root -> a -> (Root -> Float -> Float -> a -> IO (a, Bool)) -> IO a
render' time win root value fun =
do windowEventUtilities_messagePump
closed <- renderWindow_isClosed win
if closed
then return value
else do
success <- root_renderOneFrame_RootP root
timer <- root_getTimer root
time' <- timer_getMicroseconds timer
let tiF = (fromIntegral (time)) / 1000000
let tfF = (fromIntegral (time')) / 1000000
(value', cont) <- fun root tiF tfF value
if success && cont
then render' time' win root value' fun
else return value'
{-
create3DWindow :: Int -> IO (InputSystem)
create3DWindow hwnd = do
im <- inputManager_createInputSystem_size_t hwnd
-- get mouse and keyboard objects
-- unsafeCoerce instead of static_cast
mouse <- unsafeCoerce $ inputManager_createInputObject im OISMouse True ""
keyboard <- unsafeCoerce $ inputManager_createInputObject im OISKeyboard True ""
-- create the addhandlers
mouseNewAddHandler <- newAddHandler
keyboardNewAddHandler <- newAddHandler
-- done, package into a InputSystem
return ((keyboard, keyboardNewAddHandler), (mouse, mouseNewAddHandler)) -}
instance Eq SceneNode where
(SceneNode a) == (SceneNode b) = a == b
| DavidEichmann/boger-banana | src/Reactive/Banana/BOGRE/OGRE.hs | bsd-3-clause | 5,607 | 0 | 16 | 1,640 | 1,240 | 625 | 615 | 93 | 3 |
{-# OPTIONS_HADDOCK show-extensions #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Network.Syncthing.Session
-- Copyright : (c) 2014 Jens Thomas
--
-- License : BSD-style
-- Maintainer : jetho@gmx.de
-- Stability : experimental
-- Portability : GHC
--
-- This module provides functions for manual session handling.
--
-- __/Example Usage:/__
--
-- @
-- \{\-\# LANGUAGE OverloadedStrings \#\-\}
--
-- import "Control.Lens" (('Control.Lens.&'), ('Control.Lens..~'))
-- import "Network.Syncthing"
-- import qualified "Network.Syncthing.Get" as Get
--
-- \-\- Customized configuration.
-- settings1 = 'defaultConfig' 'Control.Lens.&' 'Network.Syncthing.pServer' 'Control.Lens..~' \"192.168.0.10:8080\"
--
-- session1 = do
-- session <- 'newSyncSession' settings1
-- p <- 'runSyncSession' session Get.'Network.Syncthing.Get.ping'
-- v <- 'runSyncSession' session Get.'Network.Syncthing.Get.version'
-- 'closeSyncSession' session
-- return (p, v)
--
-- \-\- Customized configuration with disabled SSL certificate verification.
-- settings2 = 'defaultConfig' 'Control.Lens.&' 'Network.Syncthing.pHttps' 'Control.Lens..~' True
-- 'Control.Lens.&' 'Network.Syncthing.pManager' 'Control.Lens..~' Left 'Network.Syncthing.noSSLVerifyManagerSettings'
--
-- session2 = do
-- session <- 'newSyncSession' settings2
-- p <- 'runSyncSession' session Get.'Network.Syncthing.Get.ping'
-- v <- 'runSyncSession' session Get.'Network.Syncthing.Get.version'
-- 'closeSyncSession' session
-- return (p, v)
-- @
module Network.Syncthing.Session
(
-- * Types
SyncSession
-- * Session Management
, newSyncSession
, closeSyncSession
, withSyncSession
-- * Running requests
, runSyncSession
) where
import Control.Exception (bracket)
import Control.Lens ((&), (.~), (^.))
import Network.HTTP.Client (closeManager, newManager)
import Network.Syncthing.Internal.Config
import Network.Syncthing.Internal.Monad
-- | Holds the session configuration and the connection manager.
newtype SyncSession = SyncSession { getConfig :: SyncConfig }
-- | Create a new Syncthing session for with provided configuration. You should
-- reuse the session whenever possible because of connection sharing.
newSyncSession :: SyncConfig -> IO SyncSession
newSyncSession config = do
mgr <- createManager $ config ^. pManager
return . SyncSession $ config & pManager .~ Right mgr
where
createManager (Left settings) = newManager settings
createManager (Right mgr) = return mgr
-- | Close a Syncthing session.
closeSyncSession :: SyncSession -> IO ()
closeSyncSession session = either doNothing closeManager mgr
where
doNothing = const $ return ()
mgr = getConfig session ^. pManager
-- | Run a Syncthing request using connection sharing within a session.
runSyncSession :: SyncSession -> SyncM IO a -> IO (SyncResult a)
runSyncSession = syncthingM . getConfig
-- | Create a new session using the provided configuration, run the
-- action and close the session.
--
-- /Examples:/
--
-- @
-- 'withSyncSession' 'defaultConfig' $ \\session ->
-- 'runSyncSession' session $ 'Control.Monad.liftM2' (,) Get.'Network.Syncthing.Get.ping' Get.'Network.Syncthing.Get.version'
-- @
-- @
-- import qualified "Network.Wreq" as Wreq
--
-- let cfg = 'defaultConfig' 'Control.Lens.&' 'pHttps' 'Control.Lens..~' True
-- 'Control.Lens.&' 'pAuth' 'Control.Lens.?~' Wreq.'Network.Wreq.basicAuth' \"user\" \"pass\"
-- 'Control.Lens.&' 'pApiKey' 'Control.Lens.?~' \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"
-- 'withSyncSession' cfg $ \\session ->
-- 'runSyncSession' session $ 'Control.Monad.liftM2' (,) Get.'Network.Syncthing.Get.ping' Get.'Network.Syncthing.Get.version'
-- @
withSyncSession :: SyncConfig -> (SyncSession -> IO a) -> IO a
withSyncSession config = bracket (newSyncSession config) closeSyncSession
| jetho/syncthing-hs | Network/Syncthing/Session.hs | bsd-3-clause | 4,105 | 0 | 10 | 827 | 397 | 247 | 150 | 29 | 2 |
module Language.XHaskell.Target where
import Language.Haskell.TH as TH
import qualified Language.Haskell.Exts.Syntax as HSX
import qualified Data.Map as M
import Control.Monad.State.Lazy
import Data.List
import Language.XHaskell.TypeSpec
import Language.XHaskell.Error
import Language.XHaskell.Subtype
-- | return all the type variable names from the type
typeVars :: Type -> [Name]
typeVars = nub . sort . typeVars'
typeVars' :: Type -> [Name]
typeVars' (VarT n) = [n]
typeVars' (ForallT tyVarBnds cxt t) =
let inScoped = map (\b -> case b of {PlainTV n -> n; KindedTV n k -> n}) tyVarBnds
free = typeVars' t
in filter (\n -> not (n `elem` inScoped)) free
typeVars' (ConT _) = []
typeVars' (TupleT _) = []
typeVars' ArrowT = []
typeVars' ListT = []
typeVars' (AppT t1 t2) = typeVars' t1 ++ typeVars' t2
typeVars' (SigT t k) = typeVars' t
-- | return all the co-variant type variable names from the type
coTypeVars :: Type -> [Name]
coTypeVars = nub. sort . coTypeVars'
coTypeVars' :: Type -> [Name]
coTypeVars' (VarT n) = [n]
coTypeVars' (ForallT tyVarBnds cxt t) =
let inScoped = map (\b -> case b of {PlainTV n -> n; KindedTV n k -> n}) tyVarBnds
free = coTypeVars' t
in filter (\n -> not (n `elem` inScoped)) free
coTypeVars' (ConT _) = []
coTypeVars' (TupleT _) = []
coTypeVars' ArrowT = []
coTypeVars' ListT = []
coTypeVars' (AppT (AppT ArrowT t1) t2) = coTypeVars' t2
coTypeVars' (AppT t1 t2) = coTypeVars' t1 ++ coTypeVars' t2
coTypeVars' (SigT t k) = coTypeVars' t
-- | return all the contra-variant type variable names from the type
contraTypeVars :: Type -> [Name]
contraTypeVars = nub. sort . contraTypeVars'
contraTypeVars' :: Type -> [Name]
contraTypeVars' (VarT n) = [n]
contraTypeVars' (ForallT tyVarBnds cxt t) =
let inScoped = map (\b -> case b of {PlainTV n -> n; KindedTV n k -> n}) tyVarBnds
free = contraTypeVars' t
in filter (\n -> not (n `elem` inScoped)) free
contraTypeVars' (ConT _) = []
contraTypeVars' (TupleT _) = []
contraTypeVars' ArrowT = []
contraTypeVars' ListT = []
contraTypeVars' (AppT (AppT ArrowT t1) t2) = contraTypeVars' t1
contraTypeVars' (AppT t1 t2) = contraTypeVars' t1 ++ contraTypeVars' t2
contraTypeVars' (SigT t k) = contraTypeVars' t
-- | create fresh names of the variables for poly type
renameVars :: Type -> Q Type
renameVars (ForallT tvbs ctxt t) = do
{ let vars = map getTvFromTvb tvbs
; ps <- mapM (\n -> do
{ n' <- newName (nameBase n)
; return (n, n')
}) vars
; let subst = M.fromList (map (\(f,s) -> (f, VarT s)) ps)
tvb' = map (PlainTV . snd) ps
; return (ForallT tvb' (applySubst subst ctxt) (applySubst subst t))
}
renameVars t = return t
-- | test isomorphism among two types
isomorphic :: Type -> Type -> Bool
isomorphic t1 t2 =
case (t1,t2) of
{ (ForallT tvb1 cxt1 t1', ForallT tvb2 cxt2 t2') ->
if (not ((length tvb1) == (length tvb2)))
then False
else
let tv1 = map getTvFromTvb tvb1
tv2 = map getTvFromTvb tvb2
subst2 = M.fromList (zip tv2 (map VarT tv1))
in ( cxt1 == (applySubst subst2 cxt2) ) &&
( t1' == (applySubst subst2 t2') )
; (_,_) -> t1 == t2
}
-- | test whether a type is monomorphic
isMono :: Type -> Bool
isMono (ForallT tyVarBnds cxt ty) = null tyVarBnds
isMono t = True -- null (typeVars t)
isPoly :: Type -> Bool
isPoly = not . isMono
-- | return variable names from type variable binder
getTvFromTvb :: TyVarBndr -> Name
getTvFromTvb (PlainTV n) = n
getTvFromTvb (KindedTV n _ ) = n
-- | type substitution mapping names to types
type Subst = M.Map Name Type
-- | state evironment
data Env = Env { freeVars :: [Name]
, subst :: Subst
}
isFree :: Name -> Env -> Bool
isFree n env = n `elem` (freeVars env)
-- | lookup the type from the type substitution
getSubst :: Name -> Env -> Maybe Type
getSubst n env = M.lookup n (subst env)
addSubst :: Name -> Type -> Env -> Env
addSubst n t env = env{subst = M.insert n t (subst env)}
findSubst :: Type -- ^ poly type
-> Type -- ^ mono type
-> Maybe Subst
findSubst (ForallT tyVarBnds cxt t) t' =
case runState (findSubst' t t') (Env fvs M.empty) of
(True, env) -> Just (subst env)
(False, _ ) -> Nothing
where fvs = map getTvFromTvb tyVarBnds
-- this type looks a bit weird, maybe a maybe monad will work
findSubst' :: Type -> Type -> State Env Bool
findSubst' (VarT n) t = do
{ env <- get
; if n `isFree` env
then case (getSubst n env) of
{ Just t' -> return (t' == t)
; Nothing -> let env' = addSubst n t env
in do { put env
; return True
}
}
else case t of
{ VarT n' -> return (n == n')
; _ -> return False
}
}
findSubst' (ConT n1) (ConT n2) = return (nameBase n1 == nameBase n2) -- todo: incorporate the qualifier.
findSubst' (TupleT i) (TupleT j) = return (i == j)
findSubst' ArrowT ArrowT = return True
findSubst' ListT ListT = return True
findSubst' (AppT t1 t2) (AppT t3 t4) = do
{ bool <- findSubst' t1 t3
; if bool
then findSubst' t2 t4
else return False
}
findSubst' _ _ = return False
-- | apply the substitution to a type or a context
class Substitutable a where
applySubst :: Subst -> a -> a
instance Substitutable Type where
applySubst subst (VarT n) =
case M.lookup n subst of
{ Nothing -> VarT n
; Just t -> t
}
applySubst subst (ConT n) = ConT n
applySubst subst (TupleT i) = TupleT i
applySubst subst ArrowT = ArrowT
applySubst subst ListT = ListT
applySubst subst (AppT t1 t2) = AppT (applySubst subst t1) (applySubst subst t2)
applySubst subst (ForallT tyVarBnds cxt t) =
let dom = M.keys subst
tvbs = filter (\tyVarBnd -> case tyVarBnd of
{ PlainTV n -> not (n `elem` dom)
; KindedTV n k -> not (n `elem` dom)
}) tyVarBnds
in ForallT tvbs (applySubst subst cxt) (applySubst subst t)
instance Substitutable a => Substitutable [a] where
applySubst s xs = map (applySubst s) xs
-- | apply Substition to context and build a set of constraints
{- obsolete since Template Haskell ver 2.10.0.0
instance Substitutable Pred where
applySubst s (ClassP name ts) = ClassP name (map (applySubst s) ts)
applySubst s (EqualP t1 t2) = EqualP (applySubst s t1) (applySubst s t2)
-}
-- t is a func type like t1 -> t2 -> ... -> tn
-- ts is a list of types t1, t2, ... , tn-1
-- matches ts with t returning tn
lineUpTypes :: HSX.SrcLoc -> Type -> [Type] -> Q Type
lineUpTypes srcLoc t [] = return t
lineUpTypes srcLoc (ForallT tvb cxt t) ts = lineUpTypesP srcLoc tvb t ts
lineUpTypes srcLoc t@(AppT (AppT ArrowT t1) t2) ts = -- mono
let ts' = argsTypes (AppT (AppT ArrowT t1) t2)
in if length ts' == length ts
then do
{ succ <- lineUpTypesM srcLoc ts' ts
; if succ
then return t2
else failWithSrcLoc srcLoc $ "unable to line up arg types '" ++ pprint ts' ++ "' with types '" ++ pprint ts ++ "'"
}
else failWithSrcLoc srcLoc $ "unable to line up arg types '" ++ pprint ts' ++ "' with types '" ++ pprint ts ++ "'"
lineUpTypes srcLoc t ts = failWithSrcLoc srcLoc $ "unable to line up type " ++ pprint t ++ " with types " ++ pprint ts
lineUpTypesM :: HSX.SrcLoc -> [Type] -> [Type] -> Q Bool
lineUpTypesM srcLoc [] [] = return True
lineUpTypesM srcLoc (t:ts) (r:rs) | t == r = lineUpTypesM srcLoc ts rs
| otherwise = do { u <- ucast srcLoc r t
; lineUpTypesM srcLoc ts rs
}
lineUpTypesP :: HSX.SrcLoc -> [TyVarBndr] -> Type -> [Type] -> Q Type
lineUpTypesP srcLoc tvbs t_@(AppT (AppT ArrowT t1) t2) ts@(_:_) =
let fvs = map getTvFromTvb tvbs
t1' = foldl1 (\ta tb -> AppT (AppT ArrowT ta) tb) ts
in case runState (findSubst' t1 t1') (Env fvs M.empty) of
(True, env) -> let s = subst env
in return $ applySubst s t2
(False, _ ) -> failWithSrcLoc srcLoc $ "unable to line up type ." ++ show t_ ++ show ts
-- t1 -> t2 -> ... -> tn ~> [t1,t2,...,tn-1]
argsTypes :: Type -> [Type]
argsTypes (AppT (AppT ArrowT t1) t2) = argsTypes' t1
argsTypes t = [] -- e.g. Nil :: List a
argsTypes' :: Type -> [Type]
argsTypes' (AppT (AppT ArrowT t1) t2) = argsTypes' t1 ++ [t2]
argsTypes' t = [t]
-- t1 -> t2 -> ... -> tn ~> tn
resultType :: Type -> Type
resultType (AppT (AppT ArrowT t1) t2) = t2
resultType t2 = t2 -- e.g Nil :: List a
-- remove the structure of the nested function application
-- (((f e1) e2) 3) ===> [f,e1,e2,e3]
flatten :: Exp -> [Exp]
flatten (AppE e e') = (flatten e) ++ [e']
flatten e = [e]
-- break type based on the given integer n,
-- t1 -> t2 -> ... -> tn and 3 ~> ([t1,t2,t3], t4 -> ... -> tn)
breakFuncType :: Type -> Int -> ([Type],Type)
breakFuncType t 0 = ([],t)
breakFuncType (AppT (AppT ArrowT t1) t2) n =
let (ts,t) = breakFuncType t2 (n-1)
in (t1:ts,t)
breakFuncType t _ = ([],t)
--
newNames :: Int -> String -> Q [Name]
newNames 0 _ = return []
newNames i s = do
{ n <- newName s
; ns <- newNames (i-1) s
; return (n:ns)
}
-- | translate XHaskell type in TH representation to Haskell in TH representation
xhTyToHsTy :: TH.Type -> TH.Type
xhTyToHsTy (TH.ForallT tVarBindings ctxt t) = TH.ForallT tVarBindings ctxt $ xhTyToHsTy t
xhTyToHsTy (TH.VarT n) = TH.VarT n
xhTyToHsTy (TH.ConT n) | TH.nameBase n == "Star" = TH.ListT
| TH.nameBase n == "Choice" = TH.ConT (TH.mkName "Either")
-- | TH.nameBase n == "Eps" = TH.TupleT 0 -- todo: or TH.ConT (TH.mkName "()") -- Eps never appears in the source language
| otherwise = TH.ConT n
xhTyToHsTy (TH.TupleT i) = TH.TupleT i
xhTyToHsTy TH.ArrowT = TH.ArrowT
xhTyToHsTy TH.ListT = TH.ListT
xhTyToHsTy (TH.AppT t1 t2) = TH.AppT (xhTyToHsTy t1) (xhTyToHsTy t2)
xhTyToHsTy (TH.SigT t k) = TH.SigT (xhTyToHsTy t) k
| luzhuomi/xhaskell | Language/XHaskell/Target.hs | bsd-3-clause | 10,442 | 0 | 18 | 2,977 | 3,652 | 1,879 | 1,773 | 205 | 5 |
----------------------------------------------------------------
-- Модуль приложения
-- Графический интерфейс (UI)
-- Тема ГИП: Solarized
----------------------------------------------------------------
module WebUI.Themes.SolarizedUITheme
( SolarizedTh (..)
, thC_03
, thC_02
, thC_01
, thC_00
, thC_0
, thC_1
, thC_2
, thC_3
, thC_Yl
, thC_Or
, thC_Rd
, thC_Mg
, thC_Vl
, thC_Bl
, thC_Cn
, thC_Gr
, thC
) where
-- Импорт модулей
import WebUI.Themes.UITheme
-- Тип темы
data SolarizedTh = SolarizedTh
instance CUITheme SolarizedTh where
isTheme _ = True
rndTh SolarizedTh ThC_03 = "#002b36"
rndTh SolarizedTh ThC_02 = "#073642"
rndTh SolarizedTh ThC_01 = "#586e75"
rndTh SolarizedTh ThC_00 = "#657b83"
rndTh SolarizedTh ThC_0 = "#839496"
rndTh SolarizedTh ThC_1 = "#93a1a1"
rndTh SolarizedTh ThC_2 = "#eee8d5"
rndTh SolarizedTh ThC_3 = "#fdf6e3"
rndTh SolarizedTh ThC_Yl = "#b58900"
rndTh SolarizedTh ThC_Or = "#cb4b16"
rndTh SolarizedTh ThC_Mg = "#dc322f"
rndTh SolarizedTh ThC_Rd = "#d33682"
rndTh SolarizedTh ThC_Vl = "#6c71c4"
rndTh SolarizedTh ThC_Bl = "#268bd2"
rndTh SolarizedTh ThC_Cn = "#2aa198"
rndTh SolarizedTh ThC_Gr = "#859900"
rndTh SolarizedTh (ThC txt) = "#" ++ txt
-- | Текущая тема UI
currentTheme = SolarizedTh
rndThCur = rndTh currentTheme
-- | Цвета
thC_03 = rndThCur ThC_03
thC_02 = rndThCur ThC_02
thC_01 = rndThCur ThC_01
thC_00 = rndThCur ThC_00
thC_0 = rndThCur ThC_0
thC_1 = rndThCur ThC_1
thC_2 = rndThCur ThC_2
thC_3 = rndThCur ThC_3
thC_Yl = rndThCur ThC_Yl
thC_Or = rndThCur ThC_Or
thC_Rd = rndThCur ThC_Rd
thC_Mg = rndThCur ThC_Mg
thC_Vl = rndThCur ThC_Vl
thC_Bl = rndThCur ThC_Bl
thC_Cn = rndThCur ThC_Cn
thC_Gr = rndThCur ThC_Gr
thC = rndThCur . ThC
| iqsf/HFitUI | src/WebUI/Themes/SolarizedUITheme.hs | bsd-3-clause | 2,021 | 0 | 8 | 501 | 435 | 236 | 199 | 59 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Types where
import Data.Aeson (ToJSON(..), object, (.=))
import Data.Int (Int64)
import Data.Text (Text)
import Database.SQLite.Simple
import Database.SQLite.Simple.FromRow
import Database.SQLite.Simple.FromField
import Database.SQLite.Simple.ToField
import Database.SQLite.Simple.Internal (Field(Field))
import Database.SQLite.Simple.Ok
import Database.SQLite.Simple.Types
import Snap.Snaplet.Auth (UserId)
-- | Type for name of the database.
type DBName = String
type PersonId = Int
-- | A user is a person with credentials for authentication.
data User = User
{ usrId :: Int -- ^ Id of the user in DB
, usrAuthId :: UserId -- ^ Id of the user within authentication
, usrFName :: Text -- ^ first name of the user
, usrLName :: Text -- ^ last name of the user
, usrEmail :: Text -- ^ email adress of the user
, usrLogin :: Text -- ^ login user
, usrRole :: Role -- ^ role of user
} deriving Show
-- | The person is responsible for saving a reservation.
-- For single games there will be two persons and on a double game
-- there will be four. If the game is a training or a championship the
-- person is the contact person of the game.
data Person = Person
{ perId :: PersonId -- ^ Id of the person
, perFName :: Text -- ^ first name of the person
, perLName :: Text -- ^ last name of the person
} deriving (Show)
-- | Get a person from a list of persons if the given person-id is the same.
getPerson :: [Person] -> PersonId -> Maybe Person
getPerson ps n = case filter (\p -> perId p == n) ps of
[] -> Nothing
x:_ -> Just x
-- | Defines on which court the user will play.
data Court = CourtOne -- ^ court #1
| CourtTwo -- ^ court #2
| CourtThree -- ^ court #3
| CourtFour -- ^ court #4
instance Show Court where
show CourtOne = "1"
show CourtTwo = "2"
show CourtThree = "3"
show CourtFour = "4"
courtToInt :: Court -> Int
courtToInt CourtOne = 1
courtToInt CourtTwo = 2
courtToInt CourtThree = 3
courtToInt CourtFour = 4
intToCourt :: Int -> Court
intToCourt 1 = CourtOne
intToCourt 2 = CourtTwo
intToCourt 3 = CourtThree
intToCourt 4 = CourtFour
data Role = SuperUser
| Admin
| Member
| Trainer
| Youth
instance Show Role where
show SuperUser = "0"
show Admin = "1"
show Member = "2"
show Trainer = "3"
show Youth = "4"
roleToInt :: Role -> Int
roleToInt SuperUser = 0
roleToInt Admin = 1
roleToInt Member = 2
roleToInt Trainer = 3
roleToInt Youth = 4
roleFromInt :: Int -> Role
roleFromInt 0 = SuperUser
roleFromInt 1 = Admin
roleFromInt 2 = Member
roleFromInt 3 = Trainer
roleFromInt 4 = Youth
instance FromField Role where
fromField (Field (SQLInteger n) _) = case n of
0 -> Ok $ SuperUser
1 -> Ok $ Admin
2 -> Ok $ Member
3 -> Ok $ Trainer
4 -> Ok $ Youth
data FreeCourts = FreeCourts
{ fcMsg :: Text
, fcStatus :: Int
, fcCourts :: [Int]
} deriving Show
-- | Reservation main datastructure.
data Reservation = Reservation
{ resId :: Integer -- ^ ID of the reservation in DB
, resDate :: String -- TODO: use datetime
, resStartTime :: String -- TODO: use datetime
, resStopTime :: String -- TODO: use datetime
, resUser :: UserId
, resPersons :: [Person] -- ^ all players w/ this reservation
, resCourt :: Court -- ^ court where players are playing
, resType :: Int -- 0 (single), 1 (double), 2 (training), 4 (championship)
, resComment :: String
} deriving Show
instance ToJSON Person where
toJSON (Person{..}) =
object [ "fname" .= perFName
, "lname" .= perLName
]
instance ToJSON User where
toJSON (User{..}) =
object [ "id" .= usrId
, "authId" .= usrAuthId
, "fname" .= usrFName
, "lname" .= usrLName
, "email" .= usrEmail
, "login" .= usrLogin
, "role" .= case usrRole of
SuperUser -> 0 :: Int
Admin -> 1 :: Int
Member -> 2 :: Int
Trainer -> 3 :: Int
Youth -> 4 :: Int
]
instance ToJSON Reservation where
toJSON (Reservation{..}) =
object [ "id" .= resId
, "persons" .= resPersons
, "date" .= resDate
, "startTime" .= resStartTime
, "stopTime" .= resStopTime
, "court" .= case resCourt of
CourtOne -> 1 :: Int
CourtTwo -> 2 :: Int
CourtThree -> 3 :: Int
CourtFour -> 4 :: Int
, "type" .= resType
, "comment" .= resComment
]
instance ToJSON FreeCourts where
toJSON (FreeCourts{..}) =
object [ "msg" .= fcMsg
, "status" .= fcStatus
, "courts" .= fcCourts
]
| odi/tcl-reservation | src/Types.hs | bsd-3-clause | 5,165 | 0 | 11 | 1,661 | 1,151 | 662 | 489 | 137 | 2 |
{-# LANGUAGE DataKinds #-}
module LDrive.Calibration.Inductance where
import Ivory.Language
import Ivory.Stdlib
import Ivory.Tower
import LDrive.Types
import LDrive.Control.Modulation
import LDrive.Ivory.Types.CalI
import LDrive.Ivory.Types.Calibration
import LDrive.Ivory.Types.Adc
phaseInductanceTower :: IFloat
-> ChanOutput ('Struct "calibration")
-> PWMInput
-> Tower e (
ChanInput ('Struct "adc")
, ChanOutput ('Struct "calibration"))
phaseInductanceTower measPeriod calOut timingsIn = do
adcChan <- channel
calResult <- channel
monitor "cal_phase_inductance" $ do
pwmout <- stateInit "pwmout" $ iarray [ival 0, ival 0, ival 0]
cyclesElapsed <- stateInit "cyclesElapsed" $ ival (0 :: Uint16)
stateLow <- stateInit "inductanceLow" $ ival true
calib <- state "calib"
handler calOut "cal_phase_resistance" $ do
callback $ refCopy calib
handler (snd adcChan) "adc_phase_inductance" $ do
timings <- emitter timingsIn 1
result <- emitter (fst calResult) 1
callback $ \adc -> do
bus <- adc ~>* vbus
pbI <- adc ~>* phase_b
pcI <- adc ~>* phase_c
tvl <- calib ~> calI ~>* testVoltageLow
tvh <- calib ~> calI ~>* testVoltageHigh
isStateLow <- deref stateLow
ifte_ isStateLow
(do
store stateLow false
ca <- calib ~> calI ~>* alphasLow
store (calib ~> calI ~> alphasLow) (ca + (-pbI - pcI))
voltage_modulation bus tvl 0.0 pwmout
emit timings (constRef pwmout)
)
(do
store stateLow true
ca <- calib ~> calI ~>* alphasHigh
store (calib ~> calI ~> alphasHigh) (ca + (-pbI - pcI))
voltage_modulation bus tvh 0.0 pwmout
emit timings (constRef pwmout)
)
maxc <- calib ~> calI ~>* cycles
elapsed <- deref cyclesElapsed
when (elapsed >=? maxc * 2) $ do
al <- calib ~> calI ~>* alphasLow
ah <- calib ~> calI ~>* alphasHigh
let vL = ((tvh - tvl) / 2)
dIbydT = (ah - al) / (measPeriod * (safeCast maxc))
res = vL / dIbydT
store (calib ~> calI ~> inductance) res
emit result $ constRef calib
cyclesElapsed %= (+1)
return (fst adcChan, snd calResult)
| sorki/odrive | src/LDrive/Calibration/Inductance.hs | bsd-3-clause | 2,477 | 0 | 27 | 842 | 774 | 372 | 402 | 61 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module HLearn.Data.Image
( CIELab
, RGB
, rgb2cielab
, ColorSig
, loadColorSig
)
where
import SubHask
import SubHask.Compatibility.Vector
import SubHask.TemplateHaskell.Deriving
import qualified Data.Vector as V
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Generic as VG
import System.IO
import System.IO.Unsafe
import Foreign.C
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Marshal.Array
import qualified Prelude as P
--------------------------------------------------------------------------------
-- | An alternative way to represent colors than RGB that is closer to how humans actually perceive color.
--
-- See wikipedia on <https://en.wikipedia.org/wiki/Color_difference color difference>
data CIELab a = CIELab
{ l :: !a
, a :: !a
, b :: !a
}
deriving (Show)
type instance Scalar (CIELab a) = a
type instance Logic (CIELab a) = Logic a
instance ValidEq a => Eq_ (CIELab a) where
c1==c2 = l c1 == l c2
&& a c1 == a c2
&& b c1 == b c2
instance NFData a => NFData (CIELab a) where
rnf c = deepseq (l c)
$ deepseq (a c)
$ rnf (b c)
instance Storable a => Storable (CIELab a) where
sizeOf _ = 3*sizeOf (undefined::a)
alignment _ = alignment (undefined::a)
peek p = do
l <- peek $ plusPtr p $ 0*sizeOf (undefined::a)
a <- peek $ plusPtr p $ 1*sizeOf (undefined::a)
b <- peek $ plusPtr p $ 2*sizeOf (undefined::a)
return $ CIELab l a b
poke p (CIELab l a b) = do
poke (plusPtr p $ 0*sizeOf (undefined::a)) l
poke (plusPtr p $ 1*sizeOf (undefined::a)) a
poke (plusPtr p $ 2*sizeOf (undefined::a)) b
-- | Implements formulas taken from the opencv page:
-- http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor
--
-- FIXME:
-- We should either:
-- * implement all of the color differences
-- * use the haskell package
-- * use opencv
--
rgb2cielab :: (ClassicalLogic a, Ord a, Floating a) => RGB a -> CIELab a
rgb2cielab (RGB r g b) = CIELab l_ a_ b_
where
x = 0.412453*r + 0.357580*g + 0.180423*b
y = 0.212671*r + 0.715160*g + 0.072169*b
z = 0.019334*r + 0.119193*g + 0.950227*b
x' = x / 0.950456
z' = z / 1.088754
l_ = if y > 0.008856
then 116*y**(1/3)-16
else 903.3*y
a_ = 500*(f x' - f y ) + delta
b_ = 200*(f y - f z') + delta
f t = if t > 0.008856
then t**(1/3)
else 7.787*t+16/116
delta=0
instance Metric (CIELab Float) where
{-# INLINABLE distance #-}
distance c1 c2 = sqrt $ (l c1-l c2)*(l c1-l c2)
+ (a c1-a c2)*(a c1-a c2)
+ (b c1-b c2)*(b c1-b c2)
--------------------------------------------------------------------------------
-- | The standard method for representing colors on most computer monitors and display formats.
data RGB a = RGB
{ red :: !a
, green :: !a
, blue :: !a
}
deriving (Show)
type instance Scalar (RGB a) = a
type instance Logic (RGB a) = Logic a
instance ValidEq a => Eq_ (RGB a) where
c1==c2 = red c1 == red c2
&& green c1 == green c2
&& blue c1 == blue c2
instance NFData a => NFData (RGB a) where
rnf c = deepseq (red c)
$ deepseq (green c)
$ rnf (blue c)
instance Storable a => Storable (RGB a) where
sizeOf _ = 3*sizeOf (undefined::a)
alignment _ = alignment (undefined::a)
peek p = do
r <- peek $ plusPtr p $ 0*sizeOf (undefined::a)
g <- peek $ plusPtr p $ 1*sizeOf (undefined::a)
b <- peek $ plusPtr p $ 2*sizeOf (undefined::a)
return $ RGB r g b
poke p (RGB r g b) = do
poke (plusPtr p $ 0*sizeOf (undefined::a)) r
poke (plusPtr p $ 1*sizeOf (undefined::a)) g
poke (plusPtr p $ 2*sizeOf (undefined::a)) b
instance Metric (RGB Float) where
distance c1 c2 = sqrt $ (red c1-red c2)*(red c1-red c2)
+ (green c1-green c2)*(green c1-green c2)
+ (blue c1-blue c2)*(blue c1-blue c2)
--------------------------------------------------------------------------------
-- | A signature is sparse representation of a histogram.
-- This is used to implement the earth mover distance between images.
data ColorSig a = ColorSig
{ rgbV :: !(StorableArray (CIELab a))
, weightV :: !(StorableArray a)
}
deriving (Show)
type instance Scalar (ColorSig a) = Scalar a
type instance Logic (ColorSig a) = Logic a
instance NFData a => NFData (ColorSig a) where
rnf a = deepseq (rgbV a)
$ rnf (weightV a)
instance Eq_ (ColorSig Float) where
sig1==sig2 = rgbV sig1 == rgbV sig2
&& weightV sig1 == weightV sig2
loadColorSig ::
(
) => Bool -- ^ print debug info?
-> FilePath -- ^ path of signature file
-> IO (ColorSig Float)
loadColorSig debug filepath = {-# SCC loadColorSig #-} do
filedata <- liftM P.lines $ readFile filepath
let (rgbs,ws) = P.unzip
$ map (\[b,g,r,v] -> (rgb2cielab $ RGB r g b, v))
$ map (read.(\x->"["+x+"]")) filedata
let totalWeight = sum ws
ws' = map (/totalWeight) ws
let ret = ColorSig
{ rgbV = fromList rgbs
, weightV = fromList ws'
}
when debug $ do
putStrLn $ "filepath="++show filepath
putStrLn $ " filedata="++show filedata
putStrLn $ "signature length=" ++ show (length filedata)
deepseq ret $ return ret
instance Metric (ColorSig Float) where
distance = emd_float
distanceUB = lb2distanceUB emlb_float
foreign import ccall unsafe "emd_float" emd_float_
:: Ptr Float -> Int -> Ptr Float -> Int -> Ptr Float -> IO Float
{-# INLINABLE emd_float #-}
emd_float :: ColorSig Float -> ColorSig Float -> Float
emd_float (ColorSig rgbV1 (ArrayT weightV1)) (ColorSig rgbV2 (ArrayT weightV2))
= {-# SCC emd_float #-} unsafeDupablePerformIO $
withForeignPtr fp1 $ \p1 ->
withForeignPtr fp2 $ \p2 ->
withForeignPtr fpcost $ \pcost ->
emd_float_ p1 n1 p2 n2 pcost
where
(fp1,n1) = VS.unsafeToForeignPtr0 weightV1
(fp2,n2) = VS.unsafeToForeignPtr0 weightV2
vcost = {-# SCC vcost #-} VS.generate (n1*n2) $ \i -> distance
(rgbV1 `VG.unsafeIndex` (i`div`n2))
(rgbV2 `VG.unsafeIndex` (i`mod`n2))
(fpcost,_) = VS.unsafeToForeignPtr0 vcost
emlb_float :: ColorSig Float -> ColorSig Float -> Float
emlb_float sig1 sig2 = distance (centroid sig1) (centroid sig2)
centroid :: ColorSig Float -> CIELab Float
centroid (ColorSig rgbV weightV) = go (VG.length rgbV-1) (CIELab 0 0 0)
where
go (-1) tot = tot
go i tot = go (i-1) $ CIELab
{ l = l tot + l (rgbV `VG.unsafeIndex` i) * (weightV `VG.unsafeIndex` i)
, a = a tot + a (rgbV `VG.unsafeIndex` i) * (weightV `VG.unsafeIndex` i)
, b = b tot + b (rgbV `VG.unsafeIndex` i) * (weightV `VG.unsafeIndex` i)
}
| ehlemur/HLearn | src/HLearn/Data/Image.hs | bsd-3-clause | 7,208 | 1 | 17 | 2,050 | 2,705 | 1,387 | 1,318 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module YesodCoreTest.ParameterizedSite
( parameterizedSiteTest
) where
import Data.ByteString.Lazy (ByteString)
import Network.Wai.Test (runSession, request, defaultRequest, assertBodyContains)
import Test.Hspec (Spec, describe, it)
import Yesod.Core (YesodDispatch)
import Yesod.Core.Dispatch (toWaiApp)
import YesodCoreTest.ParameterizedSite.PolyAny (PolyAny (..))
import YesodCoreTest.ParameterizedSite.PolyShow (PolyShow (..))
import YesodCoreTest.ParameterizedSite.Compat (Compat (..))
-- These are actually tests for template haskell. So if it compiles, it works
parameterizedSiteTest :: Spec
parameterizedSiteTest = describe "Polymorphic Yesod sites" $ do
it "Polymorphic unconstrained stub" $ runStub (PolyAny ())
it "Polymorphic stub with Show" $ runStub' "1337" (PolyShow 1337)
it "Polymorphic unconstrained stub, old-style" $ runStub (Compat () ())
runStub :: YesodDispatch a => a -> IO ()
runStub stub =
let actions = do
res <- request defaultRequest
assertBodyContains "Stub" res
in toWaiApp stub >>= runSession actions
runStub' :: YesodDispatch a => ByteString -> a -> IO ()
runStub' body stub =
let actions = do
res <- request defaultRequest
assertBodyContains "Stub" res
assertBodyContains body res
in toWaiApp stub >>= runSession actions
| geraldus/yesod | yesod-core/test/YesodCoreTest/ParameterizedSite.hs | mit | 1,392 | 0 | 12 | 261 | 360 | 186 | 174 | 29 | 1 |
module Ditto.Expand
( expand
, expands
, expandBind
, deltaForm
, metaForm
) where
import Ditto.Syntax
import Ditto.Monad
import Ditto.Sub
----------------------------------------------------------------------
type Form = [Expansion]
data Expansion = XDelta | XBeta | XMeta | XGuard
deriving (Show, Read, Eq)
deltaForm = [XDelta, XBeta, XMeta, XGuard]
metaForm = [XBeta, XMeta, XGuard]
----------------------------------------------------------------------
expand :: Form -> Exp -> TCM Exp
expand form EType = return EType
expand form (EInfer m) = EInfer <$> return m
expand form (EPi i _A _B) = EPi i <$> expand form _A <*> expandBind form i _A _B
expand form (ELam i _A b) = ELam i <$> expand form _A <*> expandBind form i _A b
expand form (EApp i f a) = expand form f >>= \case
ELam _ _ bnd_b | elem XBeta form -> do
(x, b) <- unbind bnd_b
expand form =<< sub1 (x , a) b
f -> EApp i f <$> expand form a
expand form (EForm x as) = EForm x <$> expands form as
expand form (ECon _X x as) = ECon _X x <$> expands form as
expand form (ERed x []) = eleM XDelta form (lookupDeltaClause x) >>= \case
Just a -> expand form a
Nothing -> return (ERed x [])
expand form (ERed x as) = ERed x <$> expands form as
expand form (EMeta x as) = eleM XMeta form (lookupSol x) >>= \case
Just a -> expand form (apps a as)
Nothing -> EMeta x <$> expands form as
expand form (EGuard x) = eleM XGuard form (lookupGuard x) >>= \case
Just a -> expand form a
Nothing -> return (EGuard x)
expand form (EVar x) = eleM XDelta form (lookupDef x) >>= \case
Just a -> expand form a
Nothing -> return (EVar x)
expands :: Form -> Args -> TCM Args
expands form = mapM (\(i, a) -> (i,) <$> expand form a)
expandBind :: Form -> Icit -> Exp -> Bind -> TCM Bind
expandBind form i _A bnd_b = do
(x, b) <- unbind bnd_b
Bind x <$> expand form b
eleM :: Expansion -> Form -> TCM (Maybe Exp) -> TCM (Maybe Exp)
eleM x xs m = if elem x xs then m else return Nothing
----------------------------------------------------------------------
| ditto/ditto | src/Ditto/Expand.hs | gpl-3.0 | 2,048 | 0 | 14 | 427 | 923 | 457 | 466 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
module Nirum.Docs.ReStructuredTextSpec where
import Test.Hspec.Meta
import Text.InterpolatedString.Perl6 (q)
import Nirum.Docs.ReStructuredText (ReStructuredText, render)
import Nirum.DocsSpec (sampleDocument)
expectedRst :: ReStructuredText
expectedRst = [q|Hello
=====
Tight list\:
- List test
- test2
Loose list\:
1. a
2. b
A `complex link <http://nirum.org/>`_\.
|]
spec :: Spec
spec =
describe "Docs.ReStructuredText" $
specify "render" $
render sampleDocument `shouldBe` expectedRst
| spoqa/nirum | test/Nirum/Docs/ReStructuredTextSpec.hs | gpl-3.0 | 552 | 0 | 8 | 93 | 96 | 59 | 37 | 13 | 1 |
module Distribution.Simple.GHCJS (
configure, getInstalledPackages, getPackageDBContents,
buildLib, buildExe,
replLib, replExe,
startInterpreter,
installLib, installExe,
libAbiHash,
hcPkgInfo,
registerPackage,
componentGhcOptions,
getLibDir,
isDynamic,
getGlobalPackageDB,
runCmd
) where
import Distribution.Simple.GHC.ImplInfo
import qualified Distribution.Simple.GHC.Internal as Internal
import Distribution.PackageDescription as PD
import Distribution.InstalledPackageInfo
import Distribution.Package
import Distribution.Simple.PackageIndex ( InstalledPackageIndex )
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.LocalBuildInfo
import qualified Distribution.Simple.Hpc as Hpc
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Simple.Program
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import qualified Distribution.Simple.Program.Ar as Ar
import qualified Distribution.Simple.Program.Ld as Ld
import qualified Distribution.Simple.Program.Strip as Strip
import Distribution.Simple.Program.GHC
import Distribution.Simple.Setup hiding ( Flag )
import qualified Distribution.Simple.Setup as Cabal
import Distribution.Simple.Compiler hiding ( Flag )
import Distribution.Version
import Distribution.System
import Distribution.Verbosity
import Distribution.Utils.NubList
import Distribution.Text
import Language.Haskell.Extension
import Control.Monad ( unless, when )
import Data.Char ( isSpace )
import qualified Data.Map as M ( fromList )
import Data.Monoid as Mon ( Monoid(..) )
import System.Directory ( doesFileExist )
import System.FilePath ( (</>), (<.>), takeExtension,
takeDirectory, replaceExtension,
splitExtension )
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration
-> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity hcPath hcPkgPath conf0 = do
(ghcjsProg, ghcjsVersion, conf1) <-
requireProgramVersion verbosity ghcjsProgram
(orLaterVersion (Version [0,1] []))
(userMaybeSpecifyPath "ghcjs" hcPath conf0)
Just ghcjsGhcVersion <- findGhcjsGhcVersion verbosity (programPath ghcjsProg)
let implInfo = ghcjsVersionImplInfo ghcjsVersion ghcjsGhcVersion
-- This is slightly tricky, we have to configure ghcjs first, then we use the
-- location of ghcjs to help find ghcjs-pkg in the case that the user did not
-- specify the location of ghc-pkg directly:
(ghcjsPkgProg, ghcjsPkgVersion, conf2) <-
requireProgramVersion verbosity ghcjsPkgProgram {
programFindLocation = guessGhcjsPkgFromGhcjsPath ghcjsProg
}
anyVersion (userMaybeSpecifyPath "ghcjs-pkg" hcPkgPath conf1)
Just ghcjsPkgGhcjsVersion <- findGhcjsPkgGhcjsVersion
verbosity (programPath ghcjsPkgProg)
when (ghcjsVersion /= ghcjsPkgGhcjsVersion) $ die $
"Version mismatch between ghcjs and ghcjs-pkg: "
++ programPath ghcjsProg ++ " is version " ++ display ghcjsVersion ++ " "
++ programPath ghcjsPkgProg ++ " is version " ++ display ghcjsPkgGhcjsVersion
when (ghcjsGhcVersion /= ghcjsPkgVersion) $ die $
"Version mismatch between ghcjs and ghcjs-pkg: "
++ programPath ghcjsProg
++ " was built with GHC version " ++ display ghcjsGhcVersion ++ " "
++ programPath ghcjsPkgProg
++ " was built with GHC version " ++ display ghcjsPkgVersion
-- be sure to use our versions of hsc2hs, c2hs, haddock and ghc
let hsc2hsProgram' =
hsc2hsProgram { programFindLocation =
guessHsc2hsFromGhcjsPath ghcjsProg }
c2hsProgram' =
c2hsProgram { programFindLocation =
guessC2hsFromGhcjsPath ghcjsProg }
haddockProgram' =
haddockProgram { programFindLocation =
guessHaddockFromGhcjsPath ghcjsProg }
conf3 = addKnownPrograms [ hsc2hsProgram', c2hsProgram', haddockProgram' ] conf2
languages <- Internal.getLanguages verbosity implInfo ghcjsProg
extensions <- Internal.getExtensions verbosity implInfo ghcjsProg
ghcInfo <- Internal.getGhcInfo verbosity implInfo ghcjsProg
let ghcInfoMap = M.fromList ghcInfo
let comp = Compiler {
compilerId = CompilerId GHCJS ghcjsVersion,
compilerAbiTag = AbiTag $
"ghc" ++ intercalate "_" (map show . versionBranch $ ghcjsGhcVersion),
compilerCompat = [CompilerId GHC ghcjsGhcVersion],
compilerLanguages = languages,
compilerExtensions = extensions,
compilerProperties = ghcInfoMap
}
compPlatform = Internal.targetPlatform ghcInfo
-- configure gcc and ld
let conf4 = if ghcjsNativeToo comp
then Internal.configureToolchain implInfo
ghcjsProg ghcInfoMap conf3
else conf3
return (comp, compPlatform, conf4)
ghcjsNativeToo :: Compiler -> Bool
ghcjsNativeToo = Internal.ghcLookupProperty "Native Too"
guessGhcjsPkgFromGhcjsPath :: ConfiguredProgram -> Verbosity
-> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
guessGhcjsPkgFromGhcjsPath = guessToolFromGhcjsPath ghcjsPkgProgram
guessHsc2hsFromGhcjsPath :: ConfiguredProgram -> Verbosity
-> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
guessHsc2hsFromGhcjsPath = guessToolFromGhcjsPath hsc2hsProgram
guessC2hsFromGhcjsPath :: ConfiguredProgram -> Verbosity
-> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
guessC2hsFromGhcjsPath = guessToolFromGhcjsPath c2hsProgram
guessHaddockFromGhcjsPath :: ConfiguredProgram -> Verbosity
-> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
guessHaddockFromGhcjsPath = guessToolFromGhcjsPath haddockProgram
guessToolFromGhcjsPath :: Program -> ConfiguredProgram
-> Verbosity -> ProgramSearchPath
-> IO (Maybe (FilePath, [FilePath]))
guessToolFromGhcjsPath tool ghcjsProg verbosity searchpath
= do let toolname = programName tool
path = programPath ghcjsProg
dir = takeDirectory path
versionSuffix = takeVersionSuffix (dropExeExtension path)
guessNormal = dir </> toolname <.> exeExtension
guessGhcjsVersioned = dir </> (toolname ++ "-ghcjs" ++ versionSuffix)
<.> exeExtension
guessGhcjs = dir </> (toolname ++ "-ghcjs")
<.> exeExtension
guessVersioned = dir </> (toolname ++ versionSuffix) <.> exeExtension
guesses | null versionSuffix = [guessGhcjs, guessNormal]
| otherwise = [guessGhcjsVersioned,
guessGhcjs,
guessVersioned,
guessNormal]
info verbosity $ "looking for tool " ++ toolname
++ " near compiler in " ++ dir
exists <- mapM doesFileExist guesses
case [ file | (file, True) <- zip guesses exists ] of
-- If we can't find it near ghc, fall back to the usual
-- method.
[] -> programFindLocation tool verbosity searchpath
(fp:_) -> do info verbosity $ "found " ++ toolname ++ " in " ++ fp
let lookedAt = map fst
. takeWhile (\(_file, exist) -> not exist)
$ zip guesses exists
return (Just (fp, lookedAt))
where takeVersionSuffix :: FilePath -> String
takeVersionSuffix = reverse . takeWhile (`elem ` "0123456789.-") .
reverse
dropExeExtension :: FilePath -> FilePath
dropExeExtension filepath =
case splitExtension filepath of
(filepath', extension) | extension == exeExtension -> filepath'
| otherwise -> filepath
-- | Given a single package DB, return all installed packages.
getPackageDBContents :: Verbosity -> PackageDB -> ProgramConfiguration
-> IO InstalledPackageIndex
getPackageDBContents verbosity packagedb conf = do
pkgss <- getInstalledPackages' verbosity [packagedb] conf
toPackageIndex verbosity pkgss conf
-- | Given a package DB stack, return all installed packages.
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity packagedbs conf = do
checkPackageDbEnvVar
checkPackageDbStack packagedbs
pkgss <- getInstalledPackages' verbosity packagedbs conf
index <- toPackageIndex verbosity pkgss conf
return $! index
toPackageIndex :: Verbosity
-> [(PackageDB, [InstalledPackageInfo])]
-> ProgramConfiguration
-> IO InstalledPackageIndex
toPackageIndex verbosity pkgss conf = do
-- On Windows, various fields have $topdir/foo rather than full
-- paths. We need to substitute the right value in so that when
-- we, for example, call gcc, we have proper paths to give it.
topDir <- getLibDir' verbosity ghcjsProg
let indices = [ PackageIndex.fromList (map (Internal.substTopDir topDir) pkgs)
| (_, pkgs) <- pkgss ]
return $! (mconcat indices)
where
Just ghcjsProg = lookupProgram ghcjsProgram conf
checkPackageDbEnvVar :: IO ()
checkPackageDbEnvVar =
Internal.checkPackageDbEnvVar "GHCJS" "GHCJS_PACKAGE_PATH"
checkPackageDbStack :: PackageDBStack -> IO ()
checkPackageDbStack (GlobalPackageDB:rest)
| GlobalPackageDB `notElem` rest = return ()
checkPackageDbStack rest
| GlobalPackageDB `notElem` rest =
die $ "With current ghc versions the global package db is always used "
++ "and must be listed first. This ghc limitation may be lifted in "
++ "future, see http://hackage.haskell.org/trac/ghc/ticket/5977"
checkPackageDbStack _ =
die $ "If the global package db is specified, it must be "
++ "specified first and cannot be specified multiple times"
getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration
-> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' verbosity packagedbs conf =
sequence
[ do pkgs <- HcPkg.dump (hcPkgInfo conf) verbosity packagedb
return (packagedb, pkgs)
| packagedb <- packagedbs ]
getLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath
getLibDir verbosity lbi =
(reverse . dropWhile isSpace . reverse) `fmap`
rawSystemProgramStdoutConf verbosity ghcjsProgram
(withPrograms lbi) ["--print-libdir"]
getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath
getLibDir' verbosity ghcjsProg =
(reverse . dropWhile isSpace . reverse) `fmap`
rawSystemProgramStdout verbosity ghcjsProg ["--print-libdir"]
-- | Return the 'FilePath' to the global GHC package database.
getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath
getGlobalPackageDB verbosity ghcjsProg =
(reverse . dropWhile isSpace . reverse) `fmap`
rawSystemProgramStdout verbosity ghcjsProg ["--print-global-package-db"]
toJSLibName :: String -> String
toJSLibName lib
| takeExtension lib `elem` [".dll",".dylib",".so"]
= replaceExtension lib "js_so"
| takeExtension lib == ".a" = replaceExtension lib "js_a"
| otherwise = lib <.> "js_a"
buildLib, replLib :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription
-> LocalBuildInfo -> Library -> ComponentLocalBuildInfo
-> IO ()
buildLib = buildOrReplLib False
replLib = buildOrReplLib True
buildOrReplLib :: Bool -> Verbosity -> Cabal.Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildOrReplLib forRepl verbosity numJobs _pkg_descr lbi lib clbi = do
let libName = componentUnitId clbi
libTargetDir = buildDir lbi
whenVanillaLib forceVanilla =
when (not forRepl && (forceVanilla || withVanillaLib lbi))
whenProfLib = when (not forRepl && withProfLib lbi)
whenSharedLib forceShared =
when (not forRepl && (forceShared || withSharedLib lbi))
whenGHCiLib = when (not forRepl && withGHCiLib lbi && withVanillaLib lbi)
ifReplLib = when forRepl
comp = compiler lbi
implInfo = getImplInfo comp
nativeToo = ghcjsNativeToo comp
(ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi)
let runGhcjsProg = runGHC verbosity ghcjsProg comp
libBi = libBuildInfo lib
isGhcjsDynamic = isDynamic comp
dynamicTooSupported = supportsDynamicToo comp
doingTH = EnableExtension TemplateHaskell `elem` allExtensions libBi
forceVanillaLib = doingTH && not isGhcjsDynamic
forceSharedLib = doingTH && isGhcjsDynamic
-- TH always needs default libs, even when building for profiling
-- Determine if program coverage should be enabled and if so, what
-- '-hpcdir' should be.
let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi
-- Component name. Not 'libName' because that has the "HS" prefix
-- that GHC gives Haskell libraries.
cname = display $ PD.package $ localPkgDescr lbi
distPref = fromFlag $ configDistPref $ configFlags lbi
hpcdir way
| isCoverageEnabled = toFlag $ Hpc.mixDir distPref way cname
| otherwise = Mon.mempty
createDirectoryIfMissingVerbose verbosity True libTargetDir
-- TODO: do we need to put hs-boot files into place for mutually recursive
-- modules?
let cObjs = map (`replaceExtension` objExtension) (cSources libBi)
jsSrcs = jsSources libBi
baseOpts = componentGhcOptions verbosity lbi libBi clbi libTargetDir
linkJsLibOpts = mempty {
ghcOptExtra = toNubListR $
[ "-link-js-lib" , getHSLibraryName libName
, "-js-lib-outputdir", libTargetDir ] ++
concatMap (\x -> ["-js-lib-src",x]) jsSrcs
}
vanillaOptsNoJsLib = baseOpts `mappend` mempty {
ghcOptMode = toFlag GhcModeMake,
ghcOptNumJobs = numJobs,
ghcOptInputModules = toNubListR $ libModules lib,
ghcOptHPCDir = hpcdir Hpc.Vanilla
}
vanillaOpts = vanillaOptsNoJsLib `mappend` linkJsLibOpts
profOpts = adjustExts "p_hi" "p_o" vanillaOpts `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptExtra = toNubListR $
ghcjsProfOptions libBi,
ghcOptHPCDir = hpcdir Hpc.Prof
}
sharedOpts = adjustExts "dyn_hi" "dyn_o" vanillaOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptExtra = toNubListR $
ghcjsSharedOptions libBi,
ghcOptHPCDir = hpcdir Hpc.Dyn
}
linkerOpts = mempty {
ghcOptLinkOptions = toNubListR $ PD.ldOptions libBi,
ghcOptLinkLibs = toNubListR $ extraLibs libBi,
ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi,
ghcOptLinkFrameworks = toNubListR $ PD.frameworks libBi,
ghcOptInputFiles =
toNubListR $ [libTargetDir </> x | x <- cObjs] ++ jsSrcs
}
replOpts = vanillaOptsNoJsLib {
ghcOptExtra = overNubListR
Internal.filterGhciFlags
(ghcOptExtra vanillaOpts),
ghcOptNumJobs = mempty
}
`mappend` linkerOpts
`mappend` mempty {
ghcOptMode = toFlag GhcModeInteractive,
ghcOptOptimisation = toFlag GhcNoOptimisation
}
vanillaSharedOpts = vanillaOpts `mappend`
mempty {
ghcOptDynLinkMode = toFlag GhcStaticAndDynamic,
ghcOptDynHiSuffix = toFlag "dyn_hi",
ghcOptDynObjSuffix = toFlag "dyn_o",
ghcOptHPCDir = hpcdir Hpc.Dyn
}
unless (forRepl || (null (libModules lib) && null jsSrcs && null cObjs)) $
do let vanilla = whenVanillaLib forceVanillaLib (runGhcjsProg vanillaOpts)
shared = whenSharedLib forceSharedLib (runGhcjsProg sharedOpts)
useDynToo = dynamicTooSupported &&
(forceVanillaLib || withVanillaLib lbi) &&
(forceSharedLib || withSharedLib lbi) &&
null (ghcjsSharedOptions libBi)
if useDynToo
then do
runGhcjsProg vanillaSharedOpts
case (hpcdir Hpc.Dyn, hpcdir Hpc.Vanilla) of
(Cabal.Flag dynDir, Cabal.Flag vanillaDir) -> do
-- When the vanilla and shared library builds are done
-- in one pass, only one set of HPC module interfaces
-- are generated. This set should suffice for both
-- static and dynamically linked executables. We copy
-- the modules interfaces so they are available under
-- both ways.
copyDirectoryRecursive verbosity dynDir vanillaDir
_ -> return ()
else if isGhcjsDynamic
then do shared; vanilla
else do vanilla; shared
whenProfLib (runGhcjsProg profOpts)
-- build any C sources
unless (null (cSources libBi) || not nativeToo) $ do
info verbosity "Building C Sources..."
sequence_
[ do let vanillaCcOpts =
(Internal.componentCcGhcOptions verbosity implInfo
lbi libBi clbi libTargetDir filename)
profCcOpts = vanillaCcOpts `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptObjSuffix = toFlag "p_o"
}
sharedCcOpts = vanillaCcOpts `mappend` mempty {
ghcOptFPic = toFlag True,
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptObjSuffix = toFlag "dyn_o"
}
odir = fromFlag (ghcOptObjDir vanillaCcOpts)
createDirectoryIfMissingVerbose verbosity True odir
runGhcjsProg vanillaCcOpts
whenSharedLib forceSharedLib (runGhcjsProg sharedCcOpts)
whenProfLib (runGhcjsProg profCcOpts)
| filename <- cSources libBi]
-- TODO: problem here is we need the .c files built first, so we can load them
-- with ghci, but .c files can depend on .h files generated by ghc by ffi
-- exports.
unless (null (libModules lib)) $
ifReplLib (runGhcjsProg replOpts)
-- link:
when (nativeToo && not forRepl) $ do
info verbosity "Linking..."
let cProfObjs = map (`replaceExtension` ("p_" ++ objExtension))
(cSources libBi)
cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension))
(cSources libBi)
cid = compilerId (compiler lbi)
vanillaLibFilePath = libTargetDir </> mkLibName libName
profileLibFilePath = libTargetDir </> mkProfLibName libName
sharedLibFilePath = libTargetDir </> mkSharedLibName cid libName
ghciLibFilePath = libTargetDir </> Internal.mkGHCiLibName libName
hObjs <- Internal.getHaskellObjects implInfo lib lbi
libTargetDir objExtension True
hProfObjs <-
if (withProfLib lbi)
then Internal.getHaskellObjects implInfo lib lbi
libTargetDir ("p_" ++ objExtension) True
else return []
hSharedObjs <-
if (withSharedLib lbi)
then Internal.getHaskellObjects implInfo lib lbi
libTargetDir ("dyn_" ++ objExtension) False
else return []
unless (null hObjs && null cObjs) $ do
let staticObjectFiles =
hObjs
++ map (libTargetDir </>) cObjs
profObjectFiles =
hProfObjs
++ map (libTargetDir </>) cProfObjs
ghciObjFiles =
hObjs
++ map (libTargetDir </>) cObjs
dynamicObjectFiles =
hSharedObjs
++ map (libTargetDir </>) cSharedObjs
-- After the relocation lib is created we invoke ghc -shared
-- with the dependencies spelled out as -package arguments
-- and ghc invokes the linker with the proper library paths
ghcSharedLinkArgs =
mempty {
ghcOptShared = toFlag True,
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptInputFiles = toNubListR dynamicObjectFiles,
ghcOptOutputFile = toFlag sharedLibFilePath,
ghcOptNoAutoLinkPackages = toFlag True,
ghcOptPackageDBs = withPackageDB lbi,
ghcOptPackages = toNubListR $
Internal.mkGhcOptPackages clbi,
ghcOptLinkLibs = toNubListR $ extraLibs libBi,
ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi
}
whenVanillaLib False $ do
Ar.createArLibArchive verbosity lbi vanillaLibFilePath staticObjectFiles
whenProfLib $ do
Ar.createArLibArchive verbosity lbi profileLibFilePath profObjectFiles
whenGHCiLib $ do
(ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi)
Ld.combineObjectFiles verbosity ldProg
ghciLibFilePath ghciObjFiles
whenSharedLib False $
runGhcjsProg ghcSharedLinkArgs
-- | Start a REPL without loading any source files.
startInterpreter :: Verbosity -> ProgramConfiguration -> Compiler
-> PackageDBStack -> IO ()
startInterpreter verbosity conf comp packageDBs = do
let replOpts = mempty {
ghcOptMode = toFlag GhcModeInteractive,
ghcOptPackageDBs = packageDBs
}
checkPackageDbStack packageDBs
(ghcjsProg, _) <- requireProgram verbosity ghcjsProgram conf
runGHC verbosity ghcjsProg comp replOpts
buildExe, replExe :: Verbosity -> Cabal.Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe = buildOrReplExe False
replExe = buildOrReplExe True
buildOrReplExe :: Bool -> Verbosity -> Cabal.Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildOrReplExe forRepl verbosity numJobs _pkg_descr lbi
exe@Executable { exeName = exeName', modulePath = modPath } clbi = do
(ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi)
let comp = compiler lbi
implInfo = getImplInfo comp
runGhcjsProg = runGHC verbosity ghcjsProg comp
exeBi = buildInfo exe
-- exeNameReal, the name that GHC really uses (with .exe on Windows)
let exeNameReal = exeName' <.>
(if takeExtension exeName' /= ('.':exeExtension)
then exeExtension
else "")
let targetDir = (buildDir lbi) </> exeName'
let exeDir = targetDir </> (exeName' ++ "-tmp")
createDirectoryIfMissingVerbose verbosity True targetDir
createDirectoryIfMissingVerbose verbosity True exeDir
-- TODO: do we need to put hs-boot files into place for mutually recursive
-- modules? FIX: what about exeName.hi-boot?
-- Determine if program coverage should be enabled and if so, what
-- '-hpcdir' should be.
let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi
distPref = fromFlag $ configDistPref $ configFlags lbi
hpcdir way
| isCoverageEnabled = toFlag $ Hpc.mixDir distPref way exeName'
| otherwise = mempty
-- build executables
srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath
let isGhcjsDynamic = isDynamic comp
dynamicTooSupported = supportsDynamicToo comp
buildRunner = case clbi of
ExeComponentLocalBuildInfo {} -> False
_ -> True
isHaskellMain = elem (takeExtension srcMainFile) [".hs", ".lhs"]
jsSrcs = jsSources exeBi
cSrcs = cSources exeBi ++ [srcMainFile | not isHaskellMain]
cObjs = map (`replaceExtension` objExtension) cSrcs
nativeToo = ghcjsNativeToo comp
baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir)
`mappend` mempty {
ghcOptMode = toFlag GhcModeMake,
ghcOptInputFiles = toNubListR $
[ srcMainFile | isHaskellMain],
ghcOptInputModules = toNubListR $
[ m | not isHaskellMain, m <- exeModules exe],
ghcOptExtra =
if buildRunner then toNubListR ["-build-runner"]
else mempty
}
staticOpts = baseOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcStaticOnly,
ghcOptHPCDir = hpcdir Hpc.Vanilla
}
profOpts = adjustExts "p_hi" "p_o" baseOpts `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptExtra = toNubListR $ ghcjsProfOptions exeBi,
ghcOptHPCDir = hpcdir Hpc.Prof
}
dynOpts = adjustExts "dyn_hi" "dyn_o" baseOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptExtra = toNubListR $
ghcjsSharedOptions exeBi,
ghcOptHPCDir = hpcdir Hpc.Dyn
}
dynTooOpts = adjustExts "dyn_hi" "dyn_o" staticOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcStaticAndDynamic,
ghcOptHPCDir = hpcdir Hpc.Dyn
}
linkerOpts = mempty {
ghcOptLinkOptions = toNubListR $ PD.ldOptions exeBi,
ghcOptLinkLibs = toNubListR $ extraLibs exeBi,
ghcOptLinkLibPath = toNubListR $ extraLibDirs exeBi,
ghcOptLinkFrameworks = toNubListR $ PD.frameworks exeBi,
ghcOptInputFiles = toNubListR $
[exeDir </> x | x <- cObjs] ++ jsSrcs
}
replOpts = baseOpts {
ghcOptExtra = overNubListR
Internal.filterGhciFlags
(ghcOptExtra baseOpts)
}
-- For a normal compile we do separate invocations of ghc for
-- compiling as for linking. But for repl we have to do just
-- the one invocation, so that one has to include all the
-- linker stuff too, like -l flags and any .o files from C
-- files etc.
`mappend` linkerOpts
`mappend` mempty {
ghcOptMode = toFlag GhcModeInteractive,
ghcOptOptimisation = toFlag GhcNoOptimisation
}
commonOpts | withProfExe lbi = profOpts
| withDynExe lbi = dynOpts
| otherwise = staticOpts
compileOpts | useDynToo = dynTooOpts
| otherwise = commonOpts
withStaticExe = (not $ withProfExe lbi) && (not $ withDynExe lbi)
-- For building exe's that use TH with -prof or -dynamic we actually have
-- to build twice, once without -prof/-dynamic and then again with
-- -prof/-dynamic. This is because the code that TH needs to run at
-- compile time needs to be the vanilla ABI so it can be loaded up and run
-- by the compiler.
-- With dynamic-by-default GHC the TH object files loaded at compile-time
-- need to be .dyn_o instead of .o.
doingTH = EnableExtension TemplateHaskell `elem` allExtensions exeBi
-- Should we use -dynamic-too instead of compiling twice?
useDynToo = dynamicTooSupported && isGhcjsDynamic
&& doingTH && withStaticExe && null (ghcjsSharedOptions exeBi)
compileTHOpts | isGhcjsDynamic = dynOpts
| otherwise = staticOpts
compileForTH
| forRepl = False
| useDynToo = False
| isGhcjsDynamic = doingTH && (withProfExe lbi || withStaticExe)
| otherwise = doingTH && (withProfExe lbi || withDynExe lbi)
linkOpts = commonOpts `mappend`
linkerOpts `mappend` mempty {
ghcOptLinkNoHsMain = toFlag (not isHaskellMain)
}
-- Build static/dynamic object files for TH, if needed.
when compileForTH $
runGhcjsProg compileTHOpts { ghcOptNoLink = toFlag True
, ghcOptNumJobs = numJobs }
unless forRepl $
runGhcjsProg compileOpts { ghcOptNoLink = toFlag True
, ghcOptNumJobs = numJobs }
-- build any C sources
unless (null cSrcs || not nativeToo) $ do
info verbosity "Building C Sources..."
sequence_
[ do let opts = (Internal.componentCcGhcOptions verbosity implInfo lbi exeBi
clbi exeDir filename) `mappend` mempty {
ghcOptDynLinkMode = toFlag (if withDynExe lbi
then GhcDynamicOnly
else GhcStaticOnly),
ghcOptProfilingMode = toFlag (withProfExe lbi)
}
odir = fromFlag (ghcOptObjDir opts)
createDirectoryIfMissingVerbose verbosity True odir
runGhcjsProg opts
| filename <- cSrcs ]
-- TODO: problem here is we need the .c files built first, so we can load them
-- with ghci, but .c files can depend on .h files generated by ghc by ffi
-- exports.
when forRepl $ runGhcjsProg replOpts
-- link:
unless forRepl $ do
info verbosity "Linking..."
runGhcjsProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> exeNameReal) }
-- |Install for ghc, .hi, .a and, if --with-ghci given, .o
installLib :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^install location
-> FilePath -- ^install location for dynamic libraries
-> FilePath -- ^Build location
-> PackageDescription
-> Library
-> ComponentLocalBuildInfo
-> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do
whenVanilla $ copyModuleFiles "js_hi"
whenProf $ copyModuleFiles "js_p_hi"
whenShared $ copyModuleFiles "js_dyn_hi"
whenVanilla $ installOrdinary builtDir targetDir $ toJSLibName vanillaLibName
whenProf $ installOrdinary builtDir targetDir $ toJSLibName profileLibName
whenShared $ installShared builtDir dynlibTargetDir $ toJSLibName sharedLibName
when (ghcjsNativeToo $ compiler lbi) $ do
-- copy .hi files over:
whenVanilla $ copyModuleFiles "hi"
whenProf $ copyModuleFiles "p_hi"
whenShared $ copyModuleFiles "dyn_hi"
-- copy the built library files over:
whenVanilla $ installOrdinary builtDir targetDir vanillaLibName
whenProf $ installOrdinary builtDir targetDir profileLibName
whenGHCi $ installOrdinary builtDir targetDir ghciLibName
whenShared $ installShared builtDir dynlibTargetDir sharedLibName
where
install isShared srcDir dstDir name = do
let src = srcDir </> name
dst = dstDir </> name
createDirectoryIfMissingVerbose verbosity True dstDir
if isShared
then installExecutableFile verbosity src dst
else installOrdinaryFile verbosity src dst
when (stripLibs lbi) $ Strip.stripLib verbosity
(hostPlatform lbi) (withPrograms lbi) dst
installOrdinary = install False
installShared = install True
copyModuleFiles ext =
findModuleFiles [builtDir] [ext] (libModules lib)
>>= installOrdinaryFiles verbosity targetDir
cid = compilerId (compiler lbi)
libName = componentUnitId clbi
vanillaLibName = mkLibName libName
profileLibName = mkProfLibName libName
ghciLibName = Internal.mkGHCiLibName libName
sharedLibName = (mkSharedLibName cid) libName
hasLib = not $ null (libModules lib)
&& null (cSources (libBuildInfo lib))
whenVanilla = when (hasLib && withVanillaLib lbi)
whenProf = when (hasLib && withProfLib lbi)
whenGHCi = when (hasLib && withGHCiLib lbi)
whenShared = when (hasLib && withSharedLib lbi)
installExe :: Verbosity
-> LocalBuildInfo
-> InstallDirs FilePath -- ^Where to copy the files to
-> FilePath -- ^Build location
-> (FilePath, FilePath) -- ^Executable (prefix,suffix)
-> PackageDescription
-> Executable
-> IO ()
installExe verbosity lbi installDirs buildPref
(progprefix, progsuffix) _pkg exe = do
let binDir = bindir installDirs
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = exeName exe
fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix
installBinary dest = do
rawSystemProgramConf verbosity ghcjsProgram (withPrograms lbi) $
[ "--install-executable"
, buildPref </> exeName exe </> exeFileName
, "-o", dest
] ++
case (stripExes lbi, lookupProgram stripProgram $ withPrograms lbi) of
(True, Just strip) -> ["-strip-program", programPath strip]
_ -> []
installBinary (binDir </> fixedExeBaseName)
libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO String
libAbiHash verbosity _pkg_descr lbi lib clbi = do
let
libBi = libBuildInfo lib
comp = compiler lbi
vanillaArgs =
(componentGhcOptions verbosity lbi libBi clbi (buildDir lbi))
`mappend` mempty {
ghcOptMode = toFlag GhcModeAbiHash,
ghcOptInputModules = toNubListR $ PD.exposedModules lib
}
profArgs = adjustExts "js_p_hi" "js_p_o" vanillaArgs `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptExtra = toNubListR (ghcjsProfOptions libBi)
}
ghcArgs = if withVanillaLib lbi then vanillaArgs
else if withProfLib lbi then profArgs
else error "libAbiHash: Can't find an enabled library way"
--
(ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi)
getProgramInvocationOutput verbosity (ghcInvocation ghcjsProg comp ghcArgs)
adjustExts :: String -> String -> GhcOptions -> GhcOptions
adjustExts hiSuf objSuf opts =
opts `mappend` mempty {
ghcOptHiSuffix = toFlag hiSuf,
ghcOptObjSuffix = toFlag objSuf
}
registerPackage :: Verbosity
-> ProgramConfiguration
-> Bool
-> PackageDBStack
-> InstalledPackageInfo
-> IO ()
registerPackage verbosity progdb multiInstance packageDbs installedPkgInfo
| multiInstance
= HcPkg.registerMultiInstance (hcPkgInfo progdb) verbosity
packageDbs installedPkgInfo
| otherwise
= HcPkg.reregister (hcPkgInfo progdb) verbosity
packageDbs (Right installedPkgInfo)
componentGhcOptions :: Verbosity -> LocalBuildInfo
-> BuildInfo -> ComponentLocalBuildInfo -> FilePath
-> GhcOptions
componentGhcOptions verbosity lbi bi clbi odir =
let opts = Internal.componentGhcOptions verbosity lbi bi clbi odir
in opts { ghcOptExtra = ghcOptExtra opts `mappend` toNubListR
(hcOptions GHCJS bi)
}
ghcjsProfOptions :: BuildInfo -> [String]
ghcjsProfOptions bi =
hcProfOptions GHC bi `mappend` hcProfOptions GHCJS bi
ghcjsSharedOptions :: BuildInfo -> [String]
ghcjsSharedOptions bi =
hcSharedOptions GHC bi `mappend` hcSharedOptions GHCJS bi
isDynamic :: Compiler -> Bool
isDynamic = Internal.ghcLookupProperty "GHC Dynamic"
supportsDynamicToo :: Compiler -> Bool
supportsDynamicToo = Internal.ghcLookupProperty "Support dynamic-too"
findGhcjsGhcVersion :: Verbosity -> FilePath -> IO (Maybe Version)
findGhcjsGhcVersion verbosity pgm =
findProgramVersion "--numeric-ghc-version" id verbosity pgm
findGhcjsPkgGhcjsVersion :: Verbosity -> FilePath -> IO (Maybe Version)
findGhcjsPkgGhcjsVersion verbosity pgm =
findProgramVersion "--numeric-ghcjs-version" id verbosity pgm
-- -----------------------------------------------------------------------------
-- Registering
hcPkgInfo :: ProgramConfiguration -> HcPkg.HcPkgInfo
hcPkgInfo conf = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = ghcjsPkgProg
, HcPkg.noPkgDbStack = False
, HcPkg.noVerboseFlag = False
, HcPkg.flagPackageConf = False
, HcPkg.supportsDirDbs = True
, HcPkg.requiresDirDbs = v >= [7,10]
, HcPkg.nativeMultiInstance = v >= [7,10]
, HcPkg.recacheMultiInstance = True
}
where
v = versionBranch ver
Just ghcjsPkgProg = lookupProgram ghcjsPkgProgram conf
Just ver = programVersion ghcjsPkgProg
-- | Get the JavaScript file name and command and arguments to run a
-- program compiled by GHCJS
-- the exe should be the base program name without exe extension
runCmd :: ProgramConfiguration -> FilePath
-> (FilePath, FilePath, [String])
runCmd conf exe =
( script
, programPath ghcjsProg
, programDefaultArgs ghcjsProg ++ programOverrideArgs ghcjsProg ++ ["--run"]
)
where
script = exe <.> "jsexe" </> "all" <.> "js"
Just ghcjsProg = lookupProgram ghcjsProgram conf
| edsko/cabal | Cabal/src/Distribution/Simple/GHCJS.hs | bsd-3-clause | 39,801 | 0 | 23 | 12,888 | 7,845 | 4,054 | 3,791 | 680 | 6 |
import Database.HaskellDB.FlatDB
import RunTests
opts = [("filepath","flatdb-test.db")]
main = dbTestMain $ Conn {
dbLabel = "flat",
dbConn = connect driver opts
}
| m4dc4p/haskelldb | test/test-flat.hs | bsd-3-clause | 246 | 0 | 8 | 104 | 52 | 31 | 21 | 6 | 1 |
main :: IO ()
main = getContents >>= putStrLn
| rahulmutt/ghcvm | tests/suite/basic/run/Echo.hs | bsd-3-clause | 46 | 0 | 6 | 9 | 20 | 10 | 10 | 2 | 1 |
{-#LANGUAGE NoImplicitPrelude #-}
{-#LANGUAGE OverloadedStrings #-}
{-#LANGUAGE TypeFamilies #-}
{-#LANGUAGE MultiParamTypeClasses #-}
{-#LANGUAGE FlexibleInstances #-}
{-#LANGUAGE FlexibleContexts #-}
{-#LANGUAGE LambdaCase #-}
-- | Literal backend loader
module Web.Sprinkles.Backends.Loader.LiteralLoader
( literalLoader
)
where
import Web.Sprinkles.Prelude
import Web.Sprinkles.Backends.Data
( BackendData (..)
, BackendMeta (..)
, BackendSource (..)
, Verification (..)
, Items (..)
, reduceItems
, RawBytes (..)
, rawFromLBS
)
import Web.Sprinkles.Logger (LogLevel (..))
import Data.Aeson as JSON
import Data.Aeson.TH as JSON
import Data.Yaml as YAML
import Web.Sprinkles.Backends.Loader.Type
literalLoader :: JSON.Value -> Loader
literalLoader body writeLog _ fetchMode fetchOrder = do
let (mimeType, rawBodyBytes) = case body of
String txt -> ( "text/plain;charset=utf8"
, fromStrict (encodeUtf8 txt)
)
_ -> ( "application/json"
, JSON.encode body
)
rawBody = rawFromLBS rawBodyBytes
let meta = BackendMeta
{ bmMimeType = mimeType
, bmMTime = Nothing
, bmName = "literal"
, bmPath = "literal"
, bmSize = Just . fromIntegral $ length rawBodyBytes
}
return [ BackendSource meta rawBody Trusted ]
| tdammers/templar | src/Web/Sprinkles/Backends/Loader/LiteralLoader.hs | bsd-3-clause | 1,479 | 0 | 16 | 433 | 294 | 180 | 114 | 39 | 2 |
-- file test/Spec.hs
{-# OPTIONS_GHC -F -pgmF hspec-discover #-} | mwotton/datomic-peer | test/Spec.hs | bsd-3-clause | 64 | 0 | 2 | 8 | 4 | 3 | 1 | 1 | 0 |
bar f = (f, f f)
| bitemyapp/tandoori | input/occurs.hs | bsd-3-clause | 17 | 0 | 6 | 6 | 18 | 9 | 9 | 1 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Graphics.UI.Gtk
import Data.Text (Text)
-- A function like this can be used to tag string literals for i18n.
-- It also avoids a lot of type annotations.
__ :: Text -> Text
__ = id -- Replace with getText from the hgettext package in localised versions
uiDef =
"<ui>\
\ <menubar>\
\ <menu name=\"File\" action=\"FileAction\">\
\ <menuitem name=\"New\" action=\"NewAction\" />\
\ <menuitem name=\"Open\" action=\"OpenAction\" />\
\ <menuitem name=\"Save\" action=\"SaveAction\" />\
\ <menuitem name=\"SaveAs\" action=\"SaveAsAction\" />\
\ <separator/>\
\ <menuitem name=\"Exit\" action=\"ExitAction\"/>\
\ <placeholder name=\"FileMenuAdditions\" />\
\ </menu>\
\ <menu name=\"Edit\" action=\"EditAction\">\
\ <menuitem name=\"Cut\" action=\"CutAction\"/>\
\ <menuitem name=\"Copy\" action=\"CopyAction\"/>\
\ <menuitem name=\"Paste\" action=\"PasteAction\"/>\
\ </menu>\
\ </menubar>\
\ <toolbar>\
\ <placeholder name=\"FileToolItems\">\
\ <separator/>\
\ <toolitem name=\"New\" action=\"NewAction\"/>\
\ <toolitem name=\"Open\" action=\"OpenAction\"/>\
\ <toolitem name=\"Save\" action=\"SaveAction\"/>\
\ <separator/>\
\ </placeholder>\
\ <placeholder name=\"EditToolItems\">\
\ <separator/>\
\ <toolitem name=\"Cut\" action=\"CutAction\"/>\
\ <toolitem name=\"Copy\" action=\"CopyAction\"/>\
\ <toolitem name=\"Paste\" action=\"PasteAction\"/>\
\ <separator/>\
\ </placeholder>\
\ </toolbar>\
\</ui>" :: Text
main = do
initGUI
-- Create the menus
fileAct <- actionNew "FileAction" (__"File") Nothing Nothing
editAct <- actionNew "EditAction" (__"Edit") Nothing Nothing
-- Create menu items
newAct <- actionNew "NewAction" (__"New")
(Just (__"Clear the spreadsheet area."))
(Just stockNew)
on newAct actionActivated $ putStrLn "New activated."
openAct <- actionNew "OpenAction" (__"Open")
(Just (__"Open an existing spreadsheet."))
(Just stockOpen)
on openAct actionActivated $ putStrLn "Open activated."
saveAct <- actionNew "SaveAction" (__"Save")
(Just (__"Save the current spreadsheet."))
(Just stockSave)
on saveAct actionActivated $ putStrLn "Save activated."
saveAsAct <- actionNew "SaveAsAction" (__"SaveAs")
(Just (__"Save spreadsheet under new name."))
(Just stockSaveAs)
on saveAsAct actionActivated $ putStrLn "SaveAs activated."
exitAct <- actionNew "ExitAction" (__"Exit")
(Just (__"Exit this application."))
(Just stockSaveAs)
on exitAct actionActivated $ mainQuit
cutAct <- actionNew "CutAction" (__"Cut")
(Just (__"Cut out the current selection."))
(Just stockCut)
on cutAct actionActivated $ putStrLn "Cut activated."
copyAct <- actionNew "CopyAction" (__"Copy")
(Just (__"Copy the current selection."))
(Just stockCopy)
on copyAct actionActivated $ putStrLn "Copy activated."
pasteAct <- actionNew "PasteAction" (__"Paste")
(Just (__"Paste the current selection."))
(Just stockPaste)
on pasteAct actionActivated $ putStrLn "Paste activated."
standardGroup <- actionGroupNew ("standard"::Text)
mapM_ (actionGroupAddAction standardGroup) [fileAct, editAct]
mapM_ (\act -> actionGroupAddActionWithAccel standardGroup act (Nothing::Maybe Text))
[newAct, openAct, saveAct, saveAsAct, exitAct, cutAct, copyAct, pasteAct]
ui <- uiManagerNew
mid <- uiManagerAddUiFromString ui uiDef
uiManagerInsertActionGroup ui standardGroup 0
win <- windowNew
on win objectDestroy mainQuit
on win sizeRequest $ return (Requisition 200 100)
(Just menuBar) <- uiManagerGetWidget ui ("/ui/menubar"::Text)
(Just toolBar) <- uiManagerGetWidget ui ("/ui/toolbar"::Text)
edit <- textViewNew
vBox <- vBoxNew False 0
set vBox [boxHomogeneous := False]
boxPackStart vBox menuBar PackNatural 0
boxPackStart vBox toolBar PackNatural 0
boxPackStart vBox edit PackGrow 0
containerAdd win vBox
widgetShowAll win
mainGUI
| mimi1vx/gtk2hs | gtk/demo/actionMenu/ActionMenu.hs | gpl-3.0 | 4,268 | 0 | 12 | 925 | 831 | 392 | 439 | 66 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Path.Metafont
-- Copyright : (c) 2013 Daniel Bergey
-- License : BSD-style (see LICENSE)
-- Maintainer : bergey@alum.mit.edu
--
-- Define Diagrams Paths by specifying points and
-- optionally directions and tension. Calculate control points to
-- maintain smooth curvature at each point, following rules
-- implemented in Donald Knuth's /Metafont/.
--
-- This module is intended to be imported qualified.
-----------------------------------------------------------------------------
module Diagrams.TwoD.Path.Metafont
(
module Diagrams.TwoD.Path.Metafont.Combinators
, module Diagrams.TwoD.Path.Metafont
, metafontParser
)
where
import Control.Lens hiding (at, ( # ))
import Data.Either
import Data.Text (Text)
import Text.Parsec (ParseError, parse)
import Diagrams.Prelude hiding (view)
import Diagrams.TwoD.Path.Metafont.Combinators
import Diagrams.TwoD.Path.Metafont.Internal
import Diagrams.TwoD.Path.Metafont.Parser
import Diagrams.TwoD.Path.Metafont.Types
-- | MF.fromString parses a Text value in MetaFont syntax, and
-- attempts to return a TrailLike. Only a subset of Metafont is
-- supported; see the tutorial for details.
fromString :: (TrailLike t, V t ~ V2, N t ~ n, Read n, RealFloat n) => Text -> Either ParseError t
fromString s = case parse metafontParser "" s of
(Left err) -> Left err -- with different type
(Right p) -> Right . fromPath $ p
-- | fromStrings takes a list of MetaFont strings, and returns either
-- all errors, or, if there are no parsing errors, a TrailLike for
-- each string. fromStrings is provided as a convenience because the
-- MetaFont &-join is not supported. 'mconcat' ('<>') on the TrailLike is
-- equivalent, with clearer semantics.
fromStrings :: (TrailLike t, V t ~ V2, N t ~ n, Read n, RealFloat n) => [Text] -> Either [ParseError] [t]
fromStrings ss = case partitionEithers . map fromString $ ss of
([],ts) -> Right ts
(es,_) -> Left es
-- | Should you wish to construct the MFPath in some other fashion,
-- fromPath makes a TrailLike directly from the MFPath
fromPath :: (TrailLike t, V t ~ V2, N t ~ n, RealFloat n) => MFP n -> t
fromPath = trailLike . locatedTrail . over (segs.mapped) computeControls . solve
-- | flex ps draws a Trail through the points ps, such that at every
-- point p ∊ ps except the endpoints, the Trail is parallel to the
-- line from the first to the last point. This is the same as the
-- flex command defined in plain MetaFont.
flex :: (TrailLike t, V t ~ V2, N t ~ n, RealFloat n) => [P2 n] -> t
flex ps = fromPath . MFP False $ (s0:rest) where
tj = Left (TJ (TensionAmt 1) (TensionAmt 1))
jj = PJ Nothing tj Nothing
s0 = MFS (head ps) jj (head.tail $ ps)
d = Just . PathDirDir . direction $ last ps .-. head ps
seg z1 z2 = MFS z1 (PJ d tj Nothing) z2
rest = zipWith seg (init . tail $ ps) (tail . tail $ ps)
-- | metafont converts a path defined in the Metafont combinator synax into a
-- native Diagrams TrailLike.
metafont :: (TrailLike t, V t ~ V2, N t ~ n, RealFloat n) => MFPathData P n -> t
metafont = fromPath . mfPathToSegments
| wherkendell/diagrams-contrib | src/Diagrams/TwoD/Path/Metafont.hs | bsd-3-clause | 3,512 | 0 | 11 | 853 | 753 | 416 | 337 | 36 | 2 |
<?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="sr-CS">
<title>>Run Applications | ZAP Extensions</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/invoke/src/main/javahelp/org/zaproxy/zap/extension/invoke/resources/help_sr_CS/helpset_sr_CS.hs | apache-2.0 | 982 | 76 | 55 | 159 | 419 | 211 | 208 | -1 | -1 |
{-# OPTIONS_GHC -XTransformListComp #-}
module Foo where
import List
import GHC.Exts
foo = [ ()
| x <- [1..10]
, then take 5
, then sortWith by x
, then group by x
, then group using inits
, then group by x using groupWith
]
| hvr/jhc | regress/tests/0_parse/2_pass/ghc/read062.hs | mit | 287 | 2 | 8 | 108 | 76 | 42 | 34 | 11 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.HelloWorld
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability : unstable
-- Portability : unportable
--
-- A plugin example for Xmobar, a text based status bar
--
-----------------------------------------------------------------------------
module Plugins.HelloWorld where
import Plugins
data HelloWorld = HelloWorld
deriving (Read, Show)
instance Exec HelloWorld where
alias HelloWorld = "helloWorld"
run HelloWorld = return "<fc=red>Hello World!!</fc>"
| dragosboca/xmobar | samples/Plugins/HelloWorld.hs | bsd-3-clause | 682 | 0 | 6 | 114 | 67 | 42 | 25 | 7 | 0 |
-- A second test for trac #3001, which segfaults when compiled by
-- GHC 6.10.1 and run with +RTS -hb. Most of the code is from the
-- binary 0.4.4 package.
{-# LANGUAGE CPP, FlexibleInstances, FlexibleContexts, MagicHash #-}
module Main (main) where
import Data.Monoid
import Data.ByteString.Internal (inlinePerformIO)
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Internal as L
import GHC.Exts
import GHC.Word
import Control.Monad
import Foreign
import System.IO.Unsafe
import System.IO
import Data.Char (chr,ord)
main :: IO ()
main = do
encodeFile "test.bin" $ replicate 10000 'x'
print =<< (decodeFile "test.bin" :: IO String)
class Binary t where
put :: t -> Put
get :: Get t
encodeFile :: Binary a => FilePath -> a -> IO ()
encodeFile f v = L.writeFile f $ runPut $ put v
decodeFile :: Binary a => FilePath -> IO a
decodeFile f = do
s <- L.readFile f
return $ runGet (do v <- get
m <- isEmpty
m `seq` return v) s
instance Binary Word8 where
put = putWord8
get = getWord8
instance Binary Word32 where
put = putWord32be
get = getWord32be
instance Binary Int32 where
put i = put (fromIntegral i :: Word32)
get = liftM fromIntegral (get :: Get Word32)
instance Binary Int where
put i = put (fromIntegral i :: Int32)
get = liftM fromIntegral (get :: Get Int32)
instance Binary Char where
put a = put (ord a)
get = do w <- get
return $! chr w
instance Binary a => Binary [a] where
put l = put (length l) >> mapM_ put l
get = do n <- get
replicateM n get
data PairS a = PairS a !Builder
sndS :: PairS a -> Builder
sndS (PairS _ b) = b
newtype PutM a = Put { unPut :: PairS a }
type Put = PutM ()
instance Functor PutM where
fmap f m = Put $ let PairS a w = unPut m in PairS (f a) w
instance Monad PutM where
return a = Put $ PairS a mempty
m >>= k = Put $
let PairS a w = unPut m
PairS b w' = unPut (k a)
in PairS b (w `mappend` w')
m >> k = Put $
let PairS _ w = unPut m
PairS b w' = unPut k
in PairS b (w `mappend` w')
tell :: Builder -> Put
tell b = Put $ PairS () b
runPut :: Put -> L.ByteString
runPut = toLazyByteString . sndS . unPut
putWord8 :: Word8 -> Put
putWord8 = tell . singletonB
putWord32be :: Word32 -> Put
putWord32be = tell . putWord32beB
-----
newtype Get a = Get { unGet :: S -> (a, S) }
data S = S {-# UNPACK #-} !S.ByteString -- current chunk
L.ByteString -- the rest of the input
{-# UNPACK #-} !Int64 -- bytes read
runGet :: Get a -> L.ByteString -> a
runGet m str = case unGet m (initState str) of (a, _) -> a
isEmpty :: Get Bool
isEmpty = do
S s ss _ <- getZ
return (S.null s && L.null ss)
initState :: L.ByteString -> S
initState xs = mkState xs 0
getWord32be :: Get Word32
getWord32be = do
s <- readN 4 id
return $! (fromIntegral (s `S.index` 0) `shiftl_w32` 24) .|.
(fromIntegral (s `S.index` 1) `shiftl_w32` 16) .|.
(fromIntegral (s `S.index` 2) `shiftl_w32` 8) .|.
(fromIntegral (s `S.index` 3) )
getWord8 :: Get Word8
getWord8 = getPtr (sizeOf (undefined :: Word8))
mkState :: L.ByteString -> Int64 -> S
mkState l = case l of
L.Empty -> S S.empty L.empty
L.Chunk x xs -> S x xs
readN :: Int -> (S.ByteString -> a) -> Get a
readN n f = fmap f $ getBytes n
shiftl_w32 :: Word32 -> Int -> Word32
shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i)
getPtr :: Storable a => Int -> Get a
getPtr n = do
(fp,o,_) <- readN n S.toForeignPtr
return . S.inlinePerformIO $ withForeignPtr fp $ \p -> peek (castPtr $ p `plusPtr` o)
getBytes :: Int -> Get S.ByteString
getBytes n = do
S s ss bytes <- getZ
if n <= S.length s
then do let (consume,rest) = S.splitAt n s
putZ $! S rest ss (bytes + fromIntegral n)
return $! consume
else
case L.splitAt (fromIntegral n) (s `joinZ` ss) of
(consuming, rest) ->
do let now = S.concat . L.toChunks $ consuming
putZ $! mkState rest (bytes + fromIntegral n)
-- forces the next chunk before this one is returned
if (S.length now < n)
then
fail "too few bytes"
else
return now
joinZ :: S.ByteString -> L.ByteString -> L.ByteString
joinZ bb lb
| S.null bb = lb
| otherwise = L.Chunk bb lb
instance Monad Get where
return a = Get (\s -> (a, s))
{-# INLINE return #-}
m >>= k = Get (\s -> let (a, s') = unGet m s
in unGet (k a) s')
{-# INLINE (>>=) #-}
fail = error "failDesc"
getZ :: Get S
getZ = Get (\s -> (s, s))
putZ :: S -> Get ()
putZ s = Get (\_ -> ((), s))
instance Functor Get where
fmap f m = Get (\s -> case unGet m s of
(a, s') -> (f a, s'))
-----
singletonB :: Word8 -> Builder
singletonB = writeN 1 . flip poke
writeN :: Int -> (Ptr Word8 -> IO ()) -> Builder
writeN n f = ensureFree n `append` unsafeLiftIO (writeNBuffer n f)
unsafeLiftIO :: (Buffer -> IO Buffer) -> Builder
unsafeLiftIO f = Builder $ \ k buf -> inlinePerformIO $ do
buf' <- f buf
return (k buf')
append :: Builder -> Builder -> Builder
append (Builder f) (Builder g) = Builder (f . g)
writeNBuffer :: Int -> (Ptr Word8 -> IO ()) -> Buffer -> IO Buffer
writeNBuffer n f (Buffer fp o u l) = do
withForeignPtr fp (\p -> f (p `plusPtr` (o+u)))
return (Buffer fp o (u+n) (l-n))
newtype Builder = Builder {
-- Invariant (from Data.ByteString.Lazy):
-- The lists include no null ByteStrings.
runBuilder :: (Buffer -> [S.ByteString]) -> Buffer -> [S.ByteString]
}
data Buffer = Buffer {-# UNPACK #-} !(ForeignPtr Word8)
{-# UNPACK #-} !Int -- offset
{-# UNPACK #-} !Int -- used bytes
{-# UNPACK #-} !Int -- length left
toLazyByteString :: Builder -> L.ByteString
toLazyByteString m = L.fromChunks $ unsafePerformIO $ do
buf <- newBuffer defaultSize
return (runBuilder (m `append` flush) (const []) buf)
ensureFree :: Int -> Builder
ensureFree n = n `seq` withSize $ \ l ->
if n <= l then empty else
flush `append` unsafeLiftIO (const (newBuffer (max n defaultSize)))
withSize :: (Int -> Builder) -> Builder
withSize f = Builder $ \ k buf@(Buffer _ _ _ l) ->
runBuilder (f l) k buf
defaultSize :: Int
defaultSize = 32 * k - overhead
where k = 1024
overhead = 2 * sizeOf (undefined :: Int)
newBuffer :: Int -> IO Buffer
newBuffer size = do
fp <- S.mallocByteString size
return $! Buffer fp 0 0 size
putWord32beB :: Word32 -> Builder
putWord32beB w = writeN 4 $ \p -> do
poke p (fromIntegral (shiftr_w32 w 24) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 16) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 8) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (w) :: Word8)
shiftr_w32 :: Word32 -> Int -> Word32
shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
flush :: Builder
flush = Builder $ \ k buf@(Buffer p o u l) ->
if u == 0
then k buf
else S.PS p o u : k (Buffer p (o+u) 0 l)
empty :: Builder
empty = Builder id
instance Monoid Builder where
mempty = empty
mappend = append
| frantisekfarka/ghc-dsi | testsuite/tests/profiling/should_run/T3001-2.hs | bsd-3-clause | 7,830 | 0 | 18 | 2,456 | 3,012 | 1,557 | 1,455 | 199 | 3 |
import Prelude hiding (catch)
import Data.Ord (comparing)
import Data.Char (toUpper,toLower)
import Data.List
import Data.Time
import Data.Maybe
import Control.Arrow (first)
import Control.Monad
import Control.Monad.Error
import Control.Exception (catch, finally, SomeException(..))
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan
import System (getArgs)
import System.IO
import System.IO.Unsafe (unsafeInterleaveIO)
import System.INotify
import System.Locale (defaultTimeLocale)
import System.Timeout
import System.Directory
import System.Console.GetOpt
import Data.ByteString.UTF8 (fromString, toString)
import Numeric.Search.Range (searchFromTo)
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.ByteString as BS
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import qualified System.FilePath as FP
import qualified System.FilePath.FilePather.Find as FP
import qualified System.FilePath.FilePather.FilterPredicate as FP
import qualified System.FilePath.FilePather.FileType as FP
import qualified System.FilePath.FilePather.RecursePredicate as FP
import qualified Codec.MIME.String as MIME
import qualified System.Posix.FileLock as FL
-- Some utilities to get useful dates from Codec.MIME.String
months :: [MIME.Month]
months = [MIME.Jan, MIME.Feb, MIME.Mar, MIME.Apr, MIME.May, MIME.Jun, MIME.Jul, MIME.Aug, MIME.Sep, MIME.Oct, MIME.Nov, MIME.Dec]
instance Enum MIME.Month where
fromEnum MIME.Jan = 01
fromEnum MIME.Feb = 02
fromEnum MIME.Mar = 03
fromEnum MIME.Apr = 04
fromEnum MIME.May = 05
fromEnum MIME.Jun = 06
fromEnum MIME.Jul = 07
fromEnum MIME.Aug = 08
fromEnum MIME.Sep = 09
fromEnum MIME.Oct = 10
fromEnum MIME.Nov = 11
fromEnum MIME.Dec = 12
toEnum x = months !! (x - 1)
fullDate2UTCTime :: MIME.FullDate -> UTCTime
fullDate2UTCTime (MIME.FullDate _
(MIME.Date day month year)
(MIME.Time (MIME.TimeOfDay hour minute msecond) mtimezone)) =
UTCTime (fromGregorian (toInteger year) (fromEnum month) day)
(secondsToDiffTime $ toInteger $
(60*60*hour) + (60*(minute+timezone)) + second)
where
second = fromMaybe 0 msecond
-- Gross hack because timezone is an int, but the last two digits are in minutes
timezone = (tzhour*60) + tzmin
tzmin = read $ reverse $ take 2 $ reverse $ show mtimezone
tzhour = mtimezone `div` 100
-- Other utilities
-- Run in background
forkIO_ :: IO a -> IO ()
forkIO_ x = forkIO (x >> return ()) >> return ()
strftime :: (FormatTime t) => String -> t -> String
strftime = formatTime defaultTimeLocale
textToInt :: Text -> Int
textToInt t = let (Right (x,_)) = T.decimal t in x
realDirectoryContents :: Bool -> FilePath -> IO [FilePath]
realDirectoryContents fullPath path = (maybeFullPath .
filter (\p -> p `notElem` [".",".."] && not ("." `isPrefixOf` p)))
`fmap` getDirectoryContents path
where
maybeFullPath
| fullPath = map (\p -> FP.joinPath [path,p])
| otherwise = id
-- WARNING: only use this if you *know* no one else is reading the Chan
drainChan :: Chan a -> IO [a]
drainChan chan = do
empty <- isEmptyChan chan
if empty then return [] else do
v <- readChan chan
rest <- drainChan chan
return (v : rest)
binHandle :: Handle -> IO Handle
binHandle handle = do
hSetBinaryMode handle True
hSetBuffering handle NoBuffering
return handle
txtHandle :: Handle -> IO Handle
txtHandle handle = do
hSetEncoding handle utf8
hSetNewlineMode handle NewlineMode { inputNL = CRLF, outputNL = CRLF }
hSetBuffering handle LineBuffering
return handle
taggedItemT :: Char -> [Text] -> Text
taggedItemT _ [] = error "No such item"
taggedItemT c (w:ws)
| T.null w = taggedItemT c ws
| T.head w == c = T.tail w
| otherwise = taggedItemT c ws
stripFlags :: String -> String
stripFlags pth
| ':' `elem` pth = init $ dropWhileEnd (/=':') pth
| otherwise = pth
where
-- From newer base Data.List
dropWhileEnd p =
foldr (\x xs -> if p x && null xs then [] else x : xs) []
stripFlagsT :: Text -> Text
stripFlagsT pth
| isJust $ T.find (==':') pth = T.init $ T.dropWhileEnd (/=':') pth
| otherwise = pth
getFlags :: String -> [String]
getFlags pth =
foldr (\f acc -> case f of
'R' -> "\\Answered" : acc
'S' -> "\\Seen" : acc
'T' -> "\\Deleted" : acc
'D' -> "\\Draft" : acc
'F' -> "\\Flagged" : acc
_ -> acc
) [] (takeWhile (/=':') $ reverse pth)
syncCall :: Chan b -> (Chan a -> b) -> IO a
syncCall chan msg = do
r <- newChan
writeChan chan (msg r)
readChan r
-- (not `oo` (||)) for IO
(|/|) :: IO Bool -> IO Bool -> IO Bool
x |/| y = do
xv <- x
if xv then return False else fmap not y
safeTail :: [a] -> [a]
safeTail [] = []
safeTail (_:tl) = tl
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:_) = Just x
maybeErr :: (Monad m) => String -> Maybe a -> m a
maybeErr msg Nothing = fail msg
maybeErr _ (Just x) = return x
stp :: Char -> Char -> String -> String
stp _ _ [] = []
stp lead trail (l:str) | l == lead = stpTrail str
| otherwise = stpTrail (l:str)
where
stpTrail [] = []
stpTrail s | last s == trail = init s
stpTrail s = s
-- Sequence numbers, UIDs, and ranges
-- SeqNum and UID are numbers from 1, but we use them as indexes from 0
newtype UID = UID Int deriving (Eq, Ord)
instance Enum UID where
fromEnum (UID i) = i-1
toEnum i = UID (i+1)
instance Show UID where
show (UID i) = show i
instance Read UID where
readsPrec p s = map (first UID) $ readsPrec p s
newtype SeqNum = SeqNum Int deriving (Eq, Ord)
instance Enum SeqNum where
fromEnum (SeqNum i) = i-1
toEnum i = SeqNum (i+1)
instance Show SeqNum where
show (SeqNum i) = show i
instance Read SeqNum where
readsPrec p s = map (first SeqNum) $ readsPrec p s
data SelectNum = SelectNum Int | SelectNumStar deriving (Eq)
instance Read SelectNum where
readsPrec _ ('*':s) = [(SelectNumStar,s)]
readsPrec i s = map (first SelectNum) (readsPrec i s)
data MessageSelector =
SelectMessage SelectNum | SelectMessageRange SelectNum SelectNum
deriving (Eq)
instance Show MessageSelector where
show (SelectMessage (SelectNum x)) = show x
show (SelectMessage SelectNumStar) = "*"
show (SelectMessageRange (SelectNum s) (SelectNum e)) =
show s ++ ":" ++ show e
show (SelectMessageRange (SelectNum s) SelectNumStar) =
show s ++ ":*"
show (SelectMessageRange SelectNumStar (SelectNum e)) =
"*:" ++ show e
show (SelectMessageRange SelectNumStar SelectNumStar) =
"*:*"
showList ms t = intercalate "," (map show ms) ++ t
instance Read MessageSelector where
-- Parse 1,5:12,6 into [1, 5-12, 6]
-- Currently pancakes errors, this may not be the desired behaviour
readsPrec _ sel
| ':' `elem` this =
case (start,end) of
(Just s, Just e) ->
[(SelectMessageRange s e, rest)]
_ -> []
| otherwise =
case thisAsN of
Just x -> [(SelectMessage x, rest)]
Nothing -> []
where
start = fmap fst $ safeHead $ reads start'
end = fmap fst $ safeHead $ reads $ tail end'
(start',end') = span (/=':') this
thisAsN = fmap fst $ safeHead $ reads this
rest = safeTail rest'
(this,rest') = span (/=',') sel
readList "" = [([],"")]
readList sel = case safeHead $ reads sel of
Just (s,rest) -> [(s : fst (head $ readList rest), "")]
Nothing -> [([],"")]
-- WARNING: only call this on proper sequence numbers
selectToSeq :: SelectNum -> SeqNum -> SeqNum
selectToSeq (SelectNum i) _ = SeqNum i
selectToSeq SelectNumStar highest = highest
-- Path Server manages SeqNum <-> UID <-> FilePath mappings
data PthMsg =
MsgAll FilePath (Chan (Vector (UID,FilePath))) |
MsgCount FilePath (Chan Int) |
MsgPath FilePath SeqNum (Chan FilePath) |
MsgUID FilePath SeqNum (Chan UID) |
MsgSeq FilePath UID Bool (Chan SeqNum) |
UIDValidity FilePath (Chan Int) |
UIDNext FilePath (Chan UID) |
MsgMbox (Maybe FilePath) | -- For which async notifications to generate
MsgNew FilePath FilePath |
MsgDelFlush (Chan ()) |
MsgFinish (Chan ())
parseUidlist :: FilePath -> IO (Int, UID, Map Text UID)
parseUidlist mbox = do
uidlist <- fmap T.lines $ T.readFile (FP.joinPath [mbox,"uidlist"])
let header = T.words $ T.drop 2 (head uidlist)
let uids = map ((\(uid:meta) ->
(stripFlagsT $ taggedItemT ':' meta, UID $ textToInt uid)
) . T.words) (tail uidlist)
return (
textToInt $ taggedItemT 'V' header,
UID $ textToInt $ taggedItemT 'N' header,
Map.fromList uids
)
updateUidlist :: (Int, UID, Map Text UID) -> FilePath -> IO (Int, UID, [(UID,FilePath)])
updateUidlist (valid, nuid, uids) mbox = do
-- Just move all new mail to cur with no flags
new <- realDirectoryContents True $ FP.joinPath [mbox, "new"]
mapM_ (\pth ->
let basename = FP.takeFileName pth
flagname = stripFlags basename ++ ":2," in
renameFile pth (FP.joinPath [mbox, "cur", flagname])
) new
cur <- realDirectoryContents False $ FP.joinPath [mbox, "cur"]
let (nuid',unsorted) = foldl' (\(nuid,acc) m ->
case Map.lookup (stripFlagsT $ T.pack m) uids of
Just uid -> (nuid,(uid,m):acc)
Nothing -> (succ nuid,(nuid,m):acc)
) (nuid,[]) cur
let sorted = sortBy (comparing fst) unsorted
writeUidlist (valid, nuid', sorted) mbox
return (valid, nuid', sorted)
-- WARNING: this function must *only* be called on a sorted list!
writeUidlist :: (Int, UID, [(UID,FilePath)]) -> FilePath -> IO ()
writeUidlist (valid, nuid, sorted) mbox = do
(tmpth, uidlst) <- openTempFile (FP.joinPath [mbox,"tmp"]) "uidlist"
-- Write header
hPutStrLn uidlst $ "3 V" ++ show valid ++ " N" ++ show nuid
-- Write content
mapM_ (\(uid,pth) ->
hPutStrLn uidlst (show uid ++ " :" ++ pth)
) sorted
hClose uidlst
renameFile tmpth (FP.joinPath [mbox,"uidlist"])
pthServer :: FilePath -> Maybe Int -> Chan PthMsg -> Chan BS.ByteString -> Chan WriterMsg -> IO ()
pthServer root limit chan stdoutChan writerChan = withINotify (\inotify -> do
mboxes <- maildirFind (const True) (const True) root >>=
filterM (\pth -> doesDirectoryExist $ FP.joinPath [pth,"cur"])
dC <- newChan -- Channel to store pending deletes
maps <- mapM (\mbox ->
uidlistFromFile mbox >>= updateUidlistAndWatch inotify dC mbox
) mboxes
pthServer' (Map.fromList maps) Nothing dC 0
)
where
uidlistFromFile mbox =
FL.withLock (FP.joinPath [mbox,"uidlist.lock"]) FL.ReadLock $ do
exist <- doesFileExist (FP.joinPath [mbox,"uidlist"])
time <- fmap (strftime "%s") getCurrentTime
if exist then parseUidlist mbox else
return (read time, UID 1, Map.empty)
updateUidlistAndWatch i dC mbox ms =
FL.withLock (FP.joinPath [mbox,"uidlist.lock"]) FL.WriteLock $ do
(valid,nuid,sorted) <- updateUidlist ms mbox
-- TODO: Should MoveOut not followed by MoveIn be Delete?
_ <- addWatch i [Create,MoveIn,Delete] (FP.joinPath [mbox,"cur"])
(handleINotify mbox dC)
return (mbox, (valid,nuid,Vector.fromList sorted))
handleINotify mbox _ (Created { isDirectory = False,filePath = pth }) =
writeChan chan (MsgNew mbox pth)
handleINotify mbox _ (MovedIn { isDirectory = False,filePath = pth }) =
writeChan chan (MsgNew mbox pth)
handleINotify mbox dC (Deleted { filePath = pth }) =
writeChan dC (mbox, pth)
handleINotify _ _ _ = return () -- Ignore other events
pthServer' maps selec dC lOff = do
let maybeFromIndex' = maybeFromIndex lOff
let maybeIndexIn' = maybeIndexIn lOff
msg <- readChan chan
case msg of
(MsgAll mbox r) -> writeChan r $ maybeTail lOff $
trd3 $ getMbox mbox maps
(MsgCount mbox r) -> writeChan r $
maybeLimit lOff $ Vector.length $ trd3 $ getMbox mbox maps
(MsgUID mbox s r) -> let m = trd3 $ getMbox mbox maps in
writeChan r $ fst $ (Vector.!) m (s `maybeIndexIn'` m)
(MsgSeq mbox uid fuzzy r) -> let m = trd3 $ getMbox mbox maps in
writeChan r $
case findUID fuzzy m uid of
Just i -> i `maybeFromIndex'` m
Nothing -> error ("UID " ++ show uid ++ "out of range")
(MsgPath mbox s r) -> let m = trd3 $ getMbox mbox maps in
writeChan r $ snd $ (Vector.!) m (s `maybeIndexIn'` m)
(UIDValidity mbox r) ->
writeChan r (fst3 $ getMbox mbox maps)
(UIDNext mbox r) ->
writeChan r (snd3 $ getMbox mbox maps)
(MsgMbox sel) ->
pthServer' maps sel dC 0
(MsgNew mbox pth) ->
-- If we already know about the unique part of this path,
-- it is a rename. Else it is a new message
let u = stripFlags pth
(v,n,m) = getMbox mbox maps in
case Vector.findIndex (\(_,mp) -> u == stripFlags mp) m of
Just i -> do -- rename, flags changed
let x = (v, n,
(Vector.//) m [(i,(fst $ (Vector.!) m i,pth))])
let s = i `maybeFromIndex'` m
when (isSelected mbox selec) (printFlags s pth)
writeChan writerChan (Write mbox x)
pthServer' (Map.adjust (const x) mbox maps)
selec dC lOff
Nothing -> do
let x = (v, succ n, Vector.snoc m (n,pth))
when (isSelected mbox selec) (writeChan stdoutChan $
fromString $ "* " ++ show (maybeLimit (succ lOff) $
Vector.length m) ++ " EXISTS\r\n")
writeChan writerChan (Write mbox x)
-- Message added, increase soft cap
pthServer' (Map.adjust (const x) mbox maps)
selec dC (succ lOff)
(MsgDelFlush r) -> do
dels <- drainChan dC
maps' <- foldM (\maps' (mbox,pth) -> do
let (v,n,m) = getMbox mbox maps
let (l,a) = Vector.break (\(_,fp) -> fp == pth) m
when (isSelected mbox selec) (writeChan stdoutChan $
fromString $ "* " ++ show ((1 + Vector.length l)
`maybeFromIndex'` m) ++ " EXPUNGE\r\n")
return $ Map.adjust (const
(v, n, (Vector.++) l (Vector.tail a))) mbox maps'
) maps dels
when (not $ null dels) (rewriteUidlists maps')
writeChan r ()
pthServer' maps' selec dC lOff
(MsgFinish r) ->
-- If we got this message, then we have processed the whole Q
writeChan r ()
pthServer' maps selec dC lOff
maybeFromIndex lOff i x = case limit of
(Just l) -> let v = i - (Vector.length x - (l+lOff)) in
(toEnum $ max 0 v) :: SeqNum
Nothing -> toEnum i :: SeqNum
maybeIndexIn lOff s x = let s' = (fromEnum (s :: SeqNum)) in
case limit of
(Just l) -> s' + (Vector.length x - (l+lOff))
Nothing -> s'
maybeTail lOff x = case limit of
(Just l) -> Vector.drop (Vector.length x - (l+lOff)) x
Nothing -> x
maybeLimit lOff x = case limit of
(Just l) -> min x (l+lOff)
Nothing -> x
fst3 (v,_,_) = v
snd3 (_,n,_) = n
trd3 (_,_,m) = m
getMbox mbox maps = fromMaybe (error ("No mailbox " ++ mbox)) $
Map.lookup mbox maps
isSelected mbox selected = fromMaybe False (fmap (==mbox) selected)
findUID False sequence uid = findUID' False sequence uid
findUID True sequence uid =
case findUID' True sequence uid of
(Just i) -> Just i
Nothing -> Just (Vector.length sequence - 1)
findUID' fuzzy sequence uid = do
let (l,h) = (0, Vector.length sequence - 1)
k <- searchFromTo (\i -> fst ((Vector.!) sequence i) >= uid) l h
guard (fuzzy || fst ((Vector.!) sequence k) == uid)
return k
printFlags i pth = writeChan stdoutChan $ fromString $ "* " ++
show i ++ " FETCH (FLAGS (" ++ unwords (getFlags pth) ++ "))\r\n"
rewriteUidlists maps = mapM_
(\(mbox,x) -> writeChan writerChan (Write mbox x)) (Map.toList maps)
-- writerServer handles writing to uidlist files
-- NOTE: pthServer calls updateUidlist before it starts with messages
-- this is safe, because that one is protected/flushed by MsgFinish
data WriterMsg = Write String (Int,UID,Vector (UID,FilePath)) | WriterFinish (Chan ())
writerServer :: Chan WriterMsg -> IO ()
writerServer chan = forever $ do
msg <- readChan chan
case msg of
(Write mbox (v,n,m)) ->
FL.withLock (FP.joinPath [mbox,"uidlist.lock"]) FL.WriteLock $
writeUidlist (v,n,Vector.toList m) mbox
(WriterFinish r) -> writeChan r ()
-- stdinServer handles the incoming IMAP commands
token :: (Eq a) => a -> a -> [a] -> ([a], [a])
token _ _ [] = ([],[]) -- Should this be an error?
token delim _ (x:xs) | x == delim = ([],xs)
token delim escape (x:str) = token' x str [x]
where
-- Should this be an error?
token' _ [] acc = (reverse acc, [])
token' prev (cur:rest) acc
| cur == delim && prev /= escape = (reverse acc,rest)
| cur == escape && prev /= escape = token' cur rest acc
| otherwise = token' cur rest (cur:acc)
wildcardMatch :: [String] -> Bool -> [String] -> Bool
wildcardMatch [] _ [] = True
wildcardMatch (p:[]) prefix [] = prefix || p `elem` ["*", "%"]
wildcardMatch _ prefix [] = prefix
wildcardMatch [] _ _ = False
wildcardMatch ("%":ps) prefix (_:xs) =
wildcardMatch ps prefix xs
wildcardMatch ("*":ps) prefix xs =
any (wildcardMatch ps prefix) (tails xs)
wildcardMatch (p:ps) prefix (x:xs)
| p == x = wildcardMatch ps prefix xs
| otherwise = False
-- Convert selectors over UIDs to a selector over SeqNums
selectUIDs :: Chan PthMsg -> FilePath -> [MessageSelector] -> IO [MessageSelector]
selectUIDs getpth mbox mselectors =
mapM (\x -> case x of
(SelectMessage (SelectNum m)) ->
fmap (SelectMessage . sq2sl) $
syncCall getpth (MsgSeq mbox (UID m) False)
(SelectMessageRange (SelectNum s) (SelectNum e)) ->
liftM2 SelectMessageRange
(fmap sq2sl $
syncCall getpth (MsgSeq mbox (UID s) True))
(fmap sq2sl $
syncCall getpth (MsgSeq mbox (UID e) True))
(SelectMessageRange (SelectNum s) SelectNumStar) ->
fmap ((`SelectMessageRange` SelectNumStar) . sq2sl)
(syncCall getpth (MsgSeq mbox (UID s) True))
(SelectMessageRange SelectNumStar (SelectNum e)) ->
fmap (SelectMessageRange SelectNumStar . sq2sl)
(syncCall getpth (MsgSeq mbox (UID e) True))
_ -> return x
) mselectors
where
sq2sl (SeqNum i) = SelectNum i
-- Take the items from the list as specified by MessageSelector
selectMsgs :: Vector a -> [MessageSelector] -> [(SeqNum,a)]
selectMsgs _ [] = []
selectMsgs xs (SelectMessageRange s e : rest) =
let highest = toEnum $ Vector.length xs - 1
(start, end) = (selectToSeq s highest, selectToSeq e highest)
(s',e') = (fromEnum start, fromEnum end) in
zip [start..] (Vector.toList $ Vector.slice s' (e'-s'+1) xs) ++
selectMsgs xs rest
selectMsgs xs (SelectMessage x : rest) =
let x' = selectToSeq x (toEnum $ Vector.length xs - 1) in
(x',(Vector.!) xs (fromEnum x')) : selectMsgs xs rest
imapSearch :: Chan PthMsg -> FilePath -> Vector (UID, FilePath) -> [String] -> IO [(UID,SeqNum)]
imapSearch _ _ _ [] = return []
imapSearch getpth mbox xs (q:a:_) | map toUpper q == "UID" =
-- a is a message selector, but with UIDs
-- TODO: we are ignoring the rest of the query here
fmap (map (\(s,(u,_)) -> (u,s)) . selectMsgs xs)
(selectUIDs getpth mbox (read a))
imapSearch _ _ xs (q:_) =
-- try SeqNum message set as last resort?
return $ (map (\(s,(u,_)) -> (u,s)) . selectMsgs xs) (read q)
--imapSearch _ _ _ _ = error "Unsupported IMAP search query"
maildirFind :: ([String] -> Bool) -> ([String] -> Bool) -> FilePath -> IO [FilePath]
maildirFind fpred rpred mbox = FP.findp
(FP.filterPredicate (\x t -> FP.isDirectory t && normPred fpred x))
(FP.recursePredicate (normPred rpred))
mbox
where
normPred pred x =
let s = FP.splitDirectories $ FP.normalise x in
last s `notElem` ["new","cur","tmp"] &&
not ("." `isPrefixOf` last s) && pred s
squishBody :: [String] -> [String]
squishBody = squishBody' [] Nothing
where
squishBody' (a:acc) (Just ']') (w:ws)
| last w == ']' =
if join (fmap safeHead (safeHead ws)) == Just '<' then
squishBody' ((a ++ " " ++ w) : acc) (Just '>') ws
else
squishBody' ((a ++ " " ++ w) : acc) Nothing ws
| otherwise = squishBody' ((a ++ " " ++ w) : acc) (Just ']') ws
squishBody' (a:acc) (Just '>') (w:ws)
| last w == '>' = squishBody' ((a ++ " " ++ w) : acc) Nothing ws
| otherwise = squishBody' ((a ++ " " ++ w) : acc) (Just '>') ws
squishBody' acc Nothing (w:ws)
| "BODY" `isPrefixOf` w = squishBody' (w:acc) (Just ']') ws
| otherwise = squishBody' (w:acc) Nothing ws
squishBody' acc _ [] = reverse acc
squishBody' _ _ _ = error "programmer error"
astring :: (MonadIO m) => (String -> IO ()) -> [String] -> m (Either String (BS.ByteString, [String]))
astring _ [] = runErrorT $ fail "Empty argument?"
astring _ (('"':hd):rest) = runErrorT $
let (t,r) = token '"' '\\' (unwords $ hd:rest) in
return (fromString t, words r)
astring putS (('{':hd):_) = runErrorT $ do -- rest is garbage or []
(nBytes,_) <- maybeErr "Invalid number in literal" $
safeHead $ reads hd
_ <- liftIO $ binHandle stdin
liftIO $ putS "+ Ready for additional command text\r\n"
bytes <- liftIO $ BS.hGet stdin nBytes
_ <- liftIO $ txtHandle stdin
-- We only read exactly the right amount, so rest
-- is empty
return (bytes,[])
astring _ (hd:rest) = runErrorT $ return (fromString hd, rest)
stdinServer :: Chan BS.ByteString -> Chan PthMsg -> FilePath -> Maybe FilePath -> IO ()
stdinServer out getpth maildir selected = do
line <- fmap words getLine
case line of
(tag:cmd:rest) -> do
let cmd' = map toUpper cmd
when (cmd' `notElem` ["FETCH","STORE","SEARCH","UID","LOGOUT"]) (
syncCall getpth MsgDelFlush
)
command tag (map toUpper cmd') rest
`catch` (\(SomeException ex) ->
putS (tag ++ " BAD " ++ show ex ++ "\r\n")
)
_ -> putS "* BAD unknown command\r\n"
next selected
where
next sel = (hIsClosed stdin |/| hIsEOF stdin) >>=
(`when` stdinServer out getpth maildir sel)
command tag "CAPABILITY" _ =
putS ("* CAPABILITY " ++ capabilities ++ "\r\n" ++
tag ++ " OK CAPABILITY completed\r\n")
command tag "NOOP" _ = noop tag
command tag "CHECK" _ = noop tag
command tag "LOGOUT" _ = do
putS $ "* BYE logout\r\n" ++ tag ++ " OK LOGOUT completed\r\n"
hClose stdin
-- If the client was expecting to need to send more data
-- it may get confused when we just say "OK"
command tag "LOGIN" _ = putS (tag ++ " OK LOGIN completed\r\n")
command tag "LIST" args =
pastring args >>= handleErr tag (\(arg1,args) ->
case args of
[] -> handleErr tag (list tag arg1) =<<
pastring =<< fmap words getLine
_ -> handleErr tag (list tag arg1) =<< pastring args
)
command tag "LSUB" _ = noop tag -- XXX: We don't support subs
command tag "SELECT" args =
pastring args >>= handleErr tag (\arg1 -> do
let mbox = toString $ fst arg1
let mbox' = if map toUpper mbox == "INBOX" then maildir else
FP.joinPath [maildir, mbox]
putS "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n"
exists <- syncCall getpth (MsgCount mbox')
putS $ "* " ++ show exists ++ " EXISTS\r\n"
putS "* 0 RECENT\r\n" -- We move everything to cur
uidvalidity <- syncCall getpth (UIDValidity mbox')
putS $ "* OK [UIDVALIDITY " ++ show uidvalidity ++ "]\r\n"
uidnext <- syncCall getpth (UIDNext mbox')
putS $ "* OK [UIDNEXT " ++ show uidnext ++ "]\r\n"
-- XXX: Read only because we have no writing commands yet
putS $ tag ++ " OK [READ-ONLY] SELECT completed\r\n"
writeChan getpth (MsgMbox (Just mbox'))
next (Just mbox')
)
command tag "FETCH" args = fetch_cmd False tag args
command tag "SEARCH" _ = putS $ tag ++ " NO unsupported query\r\n"
command tag "UID" (cmd:args) =
case map toUpper cmd of
"FETCH" -> fetch_cmd True tag args
"SEARCH" ->
case selected of
(Just mbox) -> do
msgs <- syncCall getpth (MsgAll mbox)
r <- imapSearch getpth mbox msgs args
putS $ "* SEARCH " ++ unwords (map (show.fst) r) ++ "\r\n"
putS $ tag ++ " OK search done\r\n"
Nothing -> putS $ tag ++ " NO select mailbox\r\n"
_ -> putS (tag ++ " BAD uid command\r\n")
command tag "IDLE" _ = do
putS $ "+ idling\r\n"
idleUntilDone
putS $ tag ++ " OK IDLE terminated\r\n"
command tag _ _ = putS (tag ++ " BAD unknown command\r\n")
list tag ctx (box,_) =
let pattern = FP.splitDirectories $ FP.normalise
(FP.joinPath [maildir, toString ctx, toString box])
in do
matches <- maildirFind (wildcardMatch pattern False)
(wildcardMatch pattern True) maildir
list <- mapM (\x -> let dir = FP.makeRelative maildir x in
doesDirectoryExist (FP.joinPath [x,"cur"]) >>= (\isDir ->
if isDir then
if FP.equalFilePath x maildir
then return ("INBOX","")
else return (dir,"")
else
return (dir,"\\Noselect")
)
) matches
putS $ concatMap (\(dir,attr) -> "* LIST (" ++ attr ++ ") " ++
show [FP.pathSeparator] ++ " " ++ dir ++ "\r\n"
) list ++ (tag ++ " OK LIST completed\r\n")
fetch_cmd useUID tag args =
case selected of
(Just mbox) ->
pastring args >>= handleErr tag (\(msgs,rest) -> do
-- If it was a literal, get more, strip ()
rest' <- fmap (words . map toUpper . stp '(' ')' . unwords)
(if null rest then fmap words getLine else return rest)
let selectors = nub ("UID" : squishBody rest')
let mselectors = read (toString msgs)
mselectors' <- if not useUID then return mselectors else
selectUIDs getpth mbox mselectors
allm <- syncCall getpth (MsgAll mbox)
mapM_ (\(SeqNum seq,(muid,pth)) -> do
content <- unsafeInterleaveIO $
BS.readFile $ FP.joinPath [mbox, "cur", pth]
let m = MIME.parse $ toString content
let f = fromString $ unwords ["*",show seq,"FETCH ("]
let b = fromString ")\r\n"
let bsunwords = BS.intercalate (fromString " ")
put $ BS.concat [f,bsunwords $ map (\sel ->
bsunwords [fromString (stripPeek sel),
fetch sel muid pth content m]
) selectors,b]
) (selectMsgs allm mselectors')
putS (tag ++ " OK fetch complete\r\n")
)
Nothing -> putS (tag ++ " NO select mailbox\r\n")
fetch "UID" uid _ _ _ = fromString $ show uid
fetch "INTERNALDATE" _ _ _ m = fromString $
strftime "\"%d-%b-%Y %H:%M:%S %z\"" $ fullDate2UTCTime $
fromMaybe MIME.epochDate $ -- epoch if no Date header
MIME.mi_date $ MIME.m_message_info m
fetch "RFC822.SIZE" _ _ raw _ = fromString $ show $ BS.length raw
fetch "FLAGS" _ pth _ _ = fromString $
'(' : unwords (getFlags pth) ++ ")"
fetch sel _ _ raw m | "BODY.PEEK" `isPrefixOf` sel =
body (drop 9 sel) raw m
fetch sel _ _ raw m | "BODY" `isPrefixOf` sel =
-- TODO: set \Seen on ms
body (drop 4 sel) raw m
fetch _ _ _ _ _ = BS.empty
body ('[':sel) raw m = let (section,partial) = span (/=']') sel in
case section of
[] -> BS.concat (
map fromString ["{",show (BS.length raw),"}\r\n"] ++ [raw])
_ | "HEADER.FIELDS" `isPrefixOf` section ->
let
headers = words $ init $ drop 15 section
str = (intercalate "\r\n" (
foldr (\header acc ->
let hn = map toLower header ++ ":" in
case find (\hdata -> MIME.h_name hdata == hn)
(MIME.mi_headers $ MIME.m_message_info m) of
Just hd -> MIME.h_raw_header hd ++ acc
Nothing -> acc
) [] headers) ++ "\r\n")
bstr = fromString str
l = fromString ("{" ++ show (BS.length bstr) ++ "}\r\n")
in
BS.append l bstr
_ -> BS.empty -- TODO
body _ _ _= BS.empty -- TODO
idleUntilDone = do
line <- timeout 500000 getLine
case line of
(Just s) | map toUpper s == "DONE" -> return ()
_ -> syncCall getpth MsgDelFlush >> idleUntilDone
handleErr tag _ (Left err) =
putS (tag ++ " BAD " ++ err ++ "\r\n")
handleErr _ f (Right x) = f x
noop tag = putS (tag ++ " OK noop\r\n")
pastring = astring putS
stripPeek str | "BODY.PEEK" `isPrefixOf` str = "BODY" ++ drop 9 str
stripPeek str = str
putS = put . fromString
put x = writeChan out $! x
-- stdoutServer synchronises output
stdoutServer :: Chan BS.ByteString -> IO ()
stdoutServer chan = forever $ do
bytes <- readChan chan
BS.putStr bytes
-- It all starts here
data Flag = AuthForce | Help | Limit Int deriving (Show, Read, Eq)
flags :: [OptDescr Flag]
flags = [
Option ['A'] ["auth-force"] (NoArg AuthForce)
"Force client to authenticate. Some clients need this.",
Option ['L'] ["limit"] (ReqArg (Limit . read) "LIMIT")
"Limit the number of messages display from any mailbox.",
Option ['h'] ["help"] (NoArg Help)
"Show this help text."
]
usage :: [String] -> IO ()
usage errors = do
mapM_ putStrLn errors
putStrLn $ usageInfo "imapmd [-A] MAILDIR" flags
capabilities :: String
capabilities = "IMAP4rev1 IDLE"
main :: IO ()
main = do
(flags, args, errors) <- liftM (getOpt RequireOrder flags) getArgs
if length args /= 1 || Help `elem` flags || (not . null) errors
then usage errors else do
let maildir = head args
let limit = join $ find isJust $ map getLimit flags
_ <- txtHandle stdin -- stdin is text for commands, may switch
_ <- binHandle stdout
if AuthForce `elem` flags then putStr "* OK " else
putStr "* PREAUTH "
putStr $ capabilities ++ " ready\r\n"
stdoutChan <- newChan
pthChan <- newChan
writerChan <- newChan
forkIO_ $ writerServer writerChan
forkIO_ $ pthServer maildir limit pthChan stdoutChan writerChan
forkIO_ $ stdoutServer stdoutChan
stdinServer stdoutChan pthChan maildir Nothing
-- Ensure pthServer is done
`finally` syncCall pthChan MsgFinish
`finally` syncCall writerChan WriterFinish
where
getLimit (Limit x) = Just x
getLimit _ = Nothing
| singpolyma/imapmd | imapmd.hs | isc | 29,079 | 1,071 | 28 | 6,253 | 12,023 | 6,332 | 5,691 | 683 | 37 |
{-# LANGUAGE TypeApplications #-}
module Main
( main
) where
import qualified Data.ByteString as BS
import Data.Bits
import System.IO
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Par.Class
import Control.Monad.Par.IO
-- some random task to perform. in this case
-- we fetch some random bytes from /dev/urandom.
performTask :: a -> IO (a, Integer)
performTask n = do
r <- withBinaryFile "/dev/urandom" ReadMode $
\h -> BS.hGet h 4
let [a,b,c,d] = fromIntegral @_ @Integer <$> BS.unpack r
pure (n, a .|. shiftL b 8 .|. shiftL c 16 .|. shiftL d 24)
tasks :: [] Char
tasks = ['0' .. '9'] <> ['A' .. 'Z'] <> ['a' .. 'z']
work :: ParIO [(Char, Integer)]
work = do
start <- new
end <- new
taskVars <- zipWithM const (repeat new) tasks
forM_ (zip tasks taskVars) $ \(t,tv) -> fork $ do
_ <- get start
u <- liftIO (performTask t)
put tv u
fork $ do
ys <- mapM get taskVars
put end ys
fork $ put start ()
get end
main :: IO ()
main = runParIO work >>= print
| Javran/misc | monad-par-playground/src/Main.hs | mit | 1,028 | 0 | 15 | 231 | 422 | 217 | 205 | 34 | 1 |
module AbsJasm where
newtype Ident = Ident String deriving (Eq,Ord,Show)
data JProgram =
Prog Ident [JFun]
deriving (Eq,Ord,Show)
data JFun =
Fun JType Ident [JArg] [JStm]
deriving (Eq,Ord,Show)
data JType =
TVoid
| TInt
| TDbl
| TString
| TArray JType
deriving (Eq,Ord,Show)
data JBranchType =
BLt
| BLeq
| BGt
| BGeq
| BEq
| BEqZ
| BNeq
| BNeqZ
deriving (Eq,Ord,Show)
data JDCmpType =
BDCmpG
| BDCmpL
deriving (Eq,Ord,Show)
data JArg =
Arg JType Ident
deriving (Eq,Ord,Show)
data JValue = VInt Integer | VDbl Double | VString String
deriving (Eq,Ord,Show)
data JStm =
SPush JValue
| SPop JType
| SDup2
| SSwap
| SCall Ident JType [JType]
| SStore JType Ident
| SDec JType Ident
| SLoad JType Ident
| SBStart
| SBEnd
| SCmp JBranchType String
| SCmpD
| SGoto String
| SLabel String
| SMul JType
| SDiv JType
| SAdd JType
| SSub JType
| SMod JType
| SOr
| SAnd
| SReturn JType
| SNewA JType
| SALoad JType
| SAStore JType
| SALen
deriving (Eq,Ord,Show)
| davidsundelius/JLC | src/AbsJasm.hs | mit | 1,034 | 0 | 7 | 253 | 404 | 234 | 170 | 62 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
module Tinc.Install (
installDependencies
#ifdef TEST
, cabalInstallPlan
, cabalDryInstall
, copyFreezeFile
, generateCabalFile
#endif
) where
import Control.Monad.Catch
import Control.Monad
import Control.Monad.IO.Class
import Data.List
import System.Directory hiding (getDirectoryContents)
import System.IO.Temp
import System.FilePath
import Control.Exception (IOException)
import qualified Hpack.Config as Hpack
import Tinc.Cabal
import Tinc.Cache
import Tinc.Config
import Tinc.Fail
import Tinc.Freeze
import Tinc.GhcInfo
import qualified Tinc.Hpack as Hpack
import qualified Tinc.AddSource as AddSource
import Tinc.Package
import Tinc.Process
import Tinc.Sandbox
import Tinc.AddSource
import Tinc.Facts
import Tinc.Types
import qualified Tinc.Nix as Nix
import Tinc.RecentCheck
import Util
installDependencies :: Bool -> Facts -> IO ()
installDependencies dryRun facts@Facts{..} = do
solveDependencies facts >>= if factsUseNix
then doNix
else doCabal
where
doCabal =
createInstallPlan factsGhcInfo factsCache
>=> tee printInstallPlan
>=> unless dryRun . (
realizeInstallPlan factsCache factsAddSourceCache
>=> \() -> markRecent factsGhcInfo
)
where
printInstallPlan :: InstallPlan -> IO ()
printInstallPlan (InstallPlan reusable missing) = do
mapM_ (putStrLn . ("Reusing " ++) . showPackage) (map cachedPackageName reusable)
mapM_ (putStrLn . ("Installing " ++) . showPackage) missing
doNix =
tee printInstallPlan
>=> unless dryRun . (
tee writeFreezeFile -- Write the freeze file before generating the nix expressions, so that our recency check works properly
>=> Nix.createDerivations facts
)
where
printInstallPlan :: [Package] -> IO ()
printInstallPlan packages = do
mapM_ (putStrLn . ("Using " ++) . showPackage) packages
data InstallPlan = InstallPlan {
_installPlanReusable :: [CachedPackage]
, _installPlanMissing :: [Package]
} deriving (Eq, Show)
createInstallPlan :: GhcInfo -> Path CacheDir -> [Package] -> IO InstallPlan
createInstallPlan ghcInfo cacheDir installPlan = do
cache <- readCache ghcInfo cacheDir
let reusable = findReusablePackages cache installPlan
missing = installPlan \\ map cachedPackageName reusable
return (InstallPlan reusable missing)
solveDependencies :: Facts -> IO [Package]
solveDependencies facts@Facts{..} = do
additionalDeps <- getAdditionalDependencies
addSourceDependencies <- AddSource.extractAddSourceDependencies factsGitCache factsAddSourceCache additionalDeps
cabalInstallPlan facts additionalDeps addSourceDependencies
cabalInstallPlan :: (MonadIO m, MonadMask m, Fail m, MonadProcess m) => Facts -> [Hpack.Dependency] -> [AddSourceWithVersion] -> m [Package]
cabalInstallPlan facts@Facts{..} additionalDeps addSourceDependenciesWithVersions = withSystemTempDirectory "tinc" $ \dir -> do
liftIO $ copyFreezeFile dir
cabalFile <- liftIO (generateCabalFile additionalDeps)
constraints <- liftIO (readFreezeFile addSourceDependencies)
withCurrentDirectory dir $ do
liftIO $ uncurry writeFile cabalFile
_ <- initSandbox (map (addSourcePath factsAddSourceCache) addSourceDependencies) []
installPlan <- cabalDryInstall facts args constraints
return $ markAddSourceDependencies installPlan
where
addSourceDependencies = map fst addSourceDependenciesWithVersions
addSourceConstraints = map addSourceConstraint addSourceDependenciesWithVersions
args = ["--only-dependencies", "--enable-tests"] ++ addSourceConstraints
markAddSourceDependencies = map addAddSourceHash
addAddSourceHash :: Package -> Package
addAddSourceHash p@(Package name version) = case lookup name addSourceHashes of
Just rev -> Package name version {versionAddSourceHash = Just rev}
Nothing -> p
addSourceHashes = [(name, rev) | AddSource name rev <- addSourceDependencies]
cabalDryInstall :: (MonadIO m, Fail m, MonadProcess m, MonadCatch m) => Facts -> [String] -> [Constraint] -> m [Package]
cabalDryInstall facts args constraints = go >>= parseInstallPlan
where
install xs = uncurry readProcessM (cabal facts ("install" : "--dry-run" : xs)) ""
go = do
r <- try $ install (args ++ constraints)
case r of
Left _ | (not . null) constraints -> install args
Left err -> throwM (err :: IOException)
Right s -> return s
copyFreezeFile :: FilePath -> IO ()
copyFreezeFile dst = do
exists <- doesFileExist cabalFreezeFile
when exists $ do
copyFile cabalFreezeFile (dst </> cabalFreezeFile)
where
cabalFreezeFile = "cabal.config"
generateCabalFile :: [Hpack.Dependency] -> IO (FilePath, String)
generateCabalFile additionalDeps = do
hasHpackConfig <- Hpack.doesConfigExist
cabalFiles <- getCabalFiles "."
case cabalFiles of
_ | hasHpackConfig -> renderHpack
[] | not (null additionalDeps) -> return generated
[cabalFile] -> reuseExisting cabalFile
[] -> die "No cabal file found."
_ -> die "Multiple cabal files found."
where
renderHpack :: IO (FilePath, String)
renderHpack = Hpack.render <$> Hpack.readConfig additionalDeps
generated :: (FilePath, String)
generated = Hpack.render (Hpack.mkPackage additionalDeps)
reuseExisting :: FilePath -> IO (FilePath, String)
reuseExisting file = (,) file <$> readFile file
realizeInstallPlan :: Path CacheDir -> Path AddSourceCache -> InstallPlan -> IO ()
realizeInstallPlan cacheDir addSourceCache (InstallPlan reusable missing) = do
packages <- populateCache cacheDir addSourceCache missing reusable
writeFreezeFile (missing ++ map cachedPackageName reusable) -- Write the freeze file before creating the sandbox, so that our recency check works properly
void . initSandbox [] $ map cachedPackageConfig packages
mapM cachedExecutables packages >>= mapM_ linkExecutable . concat
where
linkExecutable :: FilePath -> IO ()
linkExecutable name = linkFile name cabalSandboxBinDirectory
| robbinch/tinc | src/Tinc/Install.hs | mit | 6,425 | 0 | 17 | 1,345 | 1,647 | 840 | 807 | -1 | -1 |
module Moz.Linkscape
( urlMetrics
, runMozT
) where
import Control.Monad.Trans (MonadIO)
import qualified Data.ByteString.Char8 as C8
import Moz.Client (MozT, mozGet, runMozT)
import Moz.Linkscape.URLMetrics (URLMetrics(..), URLMetricCol(..), sumUrlMetricCols)
urlMetrics :: MonadIO m => String -> [URLMetricCol] -> MozT m URLMetrics
urlMetrics url metrics = mozGet ["linkscape", "url-metrics", url] [("Cols", cols)]
where cols = C8.pack . show . sumUrlMetricCols $ metrics
| ags/hs-moz | src/Moz/Linkscape.hs | mit | 486 | 0 | 10 | 70 | 157 | 94 | 63 | 10 | 1 |
let add = \a -> \b -> a + b
in
add 3 4
(\a -> (\b -> a + b)) 3 4
(\b -> 3 + b) 4
3 + 4
7
let ad = (let add a b = a + b in add 3) in ad 4
| CindyLinz/Tutor-Haskell | start/lambda.hs | mit | 150 | 2 | 14 | 63 | 134 | 63 | 71 | -1 | -1 |
module HAD
( check
, checkSolution
, checkCurrent
, edit
, editCurrent
, readExercise
, readSolution
, readCurrentExercise
)
where
import Data.List (intercalate)
import Data.Time
import Text.Printf (printf)
import Test.DocTest (doctest)
import System.FilePath.Posix (joinPath)
import System.Cmd (rawSystem)
-- Runs the doctest of Exercise.hs file of te given date module.
-- Example:
--
-- checkByDate 2014 02 24
check :: Int -> Int -> Int -> IO ()
check = checkFile "Exercise"
-- Check the solution of a given Day
checkSolution :: Int -> Int -> Int -> IO ()
checkSolution = checkFile "Solution"
-- Runs the doctest of today's Exercise.hs file.
-- Example:
--
-- checkByDate 2014 02 24
checkCurrent :: IO ()
checkCurrent = runToday check
-- Read an exercise content
readExercise :: Int -> Int -> Int -> IO ()
readExercise y m d = do
s <- readFile $ exercisePath y m d
putStrLn $ '\n':s
-- Read an exercise content
readSolution :: Int -> Int -> Int -> IO ()
readSolution y m d = do
s <- readFile $ solutionPath y m d
putStrLn $ '\n':s
-- Read the exercise of the day
readCurrentExercise :: IO ()
readCurrentExercise = runToday readExercise
-- Edit the exercise of a given day
edit :: String -- Editor
-> Int -- Year of the exercise
-> Int -- Month
-> Int -- Day
-> IO ()
edit ed y m d = do
rawSystem ed $ return $ exercisePath y m d
return ()
-- Edit today's exercise
editCurrent :: String -- Editor
-> IO ()
editCurrent = runToday . edit
-- helper build a solution FilePath
solutionPath :: Int -> Int -> Int -> FilePath
solutionPath = elementPath "Solution.hs"
-- helper build an exercise FilePath
exercisePath :: Int -> Int -> Int -> FilePath
exercisePath = elementPath "Exercise.hs"
-- Helper to access a file in an exercise directory
elementPath :: String -> Int -> Int -> Int -> FilePath
elementPath name y m d =
joinPath . ("exercises":) . (++ [name]) $ modules y m d
-- helper to run a function on the given day exercise
runToday :: (Int -> Int -> Int -> IO ()) -> IO ()
runToday f = do
(y, m, d) <- getCurrentDay
f (fromInteger y) m d
-- Check the given file in the directory that corespond to the given day
checkFile :: String -> Int -> Int -> Int -> IO ()
checkFile fn y m d = let
modules2module = intercalate "." . (++ [fn])
in checkModule . modules2module $ modules y m d
-- Runs the doctest of the Exercise.hs file of a given module.
-- A bit painful to write, it's easier to use checkByDate.
-- Example:
--
-- check "HAD.Y2014.M02.D24"
checkModule :: String -> IO ()
checkModule = doctest . ("-iexercises":) . return
-- Helper that get current Day
getCurrentDay :: IO (Integer, Int, Int)
getCurrentDay = fmap (toGregorian . utctDay) getCurrentTime
-- helper that build modules list
modules :: Int -> Int -> Int -> [String]
modules y m d = "HAD": zipWith printf ["Y%4d", "M%02d", "D%02d"] [y,m,d]
| Raveline/1HAD | src/HAD.hs | mit | 2,905 | 0 | 11 | 609 | 826 | 445 | 381 | 63 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module DataStructures.Arrays where
import qualified Data.Map.Lazy as M
import qualified Data.List as L
import Data.Maybe
import Control.Exception
import Data.Typeable
type Array a = (M.Map Int a, Int)
data ArraysException = IndexOutOfRange Int
deriving (Show, Typeable)
instance Exception ArraysException
-- array length
len::Array a -> Int
len = snd
-- Ask for the element in a position
get::Array a -> Int -> a
get a i = if isNothing e then throw (IndexOutOfRange i) else fromJust e
where e = M.lookup i (fst a)
-- Set an element in a position
set::Array a -> Int -> a -> Array a
set a i v = if i>=0 && i<(snd a) then (M.insert i v (fst a), snd a) else throw (IndexOutOfRange i)
-- True if sorted subarray (in ascending order)
sorted_sub::Ord a => Array a -> Int -> Int -> Bool
sorted_sub a l u = if l>=(snd a) then throw (IndexOutOfRange l) else
if u>(snd a) then throw (IndexOutOfRange u) else sorted_aux (L.take (u-l) (L.drop l (M.elems (fst a))))
where
sorted_aux [] = True
sorted_aux [x] = True
sorted_aux (a:b:xs) = a<=b && sorted_aux (b:xs)
-- True if sorted array (in ascending order)
sorted::Ord a => Array a -> Bool
sorted a = sorted_sub a 0 (snd a)
-- Subarrays equality
array_eq_sub::Eq a => Array a -> Array a -> Int -> Int -> Bool
array_eq_sub a1 a2 l u = if l>=(snd a1) || l>=(snd a2) then throw (IndexOutOfRange l) else
if u>(snd a1) || u>(snd a2) then throw (IndexOutOfRange u) else M.null (M.differenceWithKey f (fst a1) (fst a2))
where f k a b = if (k<l) || (k>=u) || (a==b) then Nothing else Just a
-- Arrays equality
array_eq::Eq a => Array a -> Array a -> Bool
array_eq a1 a2 = (snd a1) == (snd a2) && array_eq_sub a1 a2 0 (snd a1)
-- Equality of subarrays except for two positions that have the elements exchanged
exchange::Eq a => Array a -> Array a -> Int -> Int -> Int -> Int -> Bool
exchange a1 a2 l u i j = if l>=(snd a1) || l>=(snd a2) then throw (IndexOutOfRange l) else
if u>(snd a1) || u>(snd a2) then throw (IndexOutOfRange u) else if i<l || i>=u then throw (IndexOutOfRange i) else
if j<l || j>=u then throw (IndexOutOfRange j) else exchange_aux l1 l2 i j (get a1 i) (get a2 i)
where
l1 = L.take (u-l) (L.drop l (M.toAscList (fst a1)))
l2 = L.take (u-l) (L.drop l (M.toAscList (fst a2)))
exchange_aux [] [] _ _ _ _ = True
exchange_aux ((k,s1):ss1) ((_,s2):ss2) i j x1 x2
|k==i = exchange_aux ss1 ss2 i j x1 x2
|k==j = (s1==x2) && (s2==x1) && exchange_aux ss1 ss2 i j x1 x2
|otherwise = (s1==s2) && exchange_aux ss1 ss2 i j x1 x2
-- Sum of the elements of an integer's subarray
sum::Array Int -> Int -> Int -> Int
sum a l u = if l>=(snd a) then throw (IndexOutOfRange l) else
if u>(snd a) then throw (IndexOutOfRange u) else M.foldrWithKey f 0 (fst a)
where f k a b = if (l<=k) && (k<u) then (a+b) else b
-- Number of occurrences of an element in the subarray
numof::Eq a => Array a -> a -> Int -> Int -> Int
numof a x l u = if l>=(snd a) then throw (IndexOutOfRange l) else
if u>(snd a) then throw (IndexOutOfRange u) else M.foldrWithKey f 0 (fst a)
where f k a b = if (l<=k) && (k<u) && (a==x) then (b+1) else b
-- Permutation of subarrays
permut::Ord a => Array a -> Array a -> Int -> Int -> Bool
permut a1 a2 l u = if l>=(snd a1) || l>=(snd a2) then throw (IndexOutOfRange l) else
if u>(snd a1) || u>(snd a2) then throw (IndexOutOfRange u) else (snd a1) == (snd a2) && l1 == l2
where l1 = L.sort (L.take (u-l) (L.drop l (M.elems (fst a1))))
l2 = L.sort (L.take (u-l) (L.drop l (M.elems (fst a2))))
-- Permutation of subarrays and equality of the rest of the arrays
permut_sub::Ord a => Array a -> Array a -> Int -> Int -> Bool
permut_sub a1 a2 l u = if l>=(snd a1) || l>=(snd a2) then throw (IndexOutOfRange l) else
if u>(snd a1) || u>(snd a2) then throw (IndexOutOfRange u) else (L.take l l1) == (L.take l l2) &&
(L.drop u l1) == (L.drop u l2) && (L.sort (L.take (u-l) (L.drop l l1))) == (L.sort (L.take (u-l) (L.drop l l2)))
where l1 = M.elems (fst a1)
l2 = M.elems (fst a2)
-- Permutation of arrays
permut_all::Ord a => Array a -> Array a -> Bool
permut_all a1 a2 = (snd a1) == (snd a2) && permut a1 a2 0 (snd a1)
| ricardopenyamari/ir2haskell | clir-parser-haskell-master/src/DataStructures/Arrays.hs | gpl-2.0 | 4,393 | 0 | 15 | 1,092 | 2,230 | 1,141 | 1,089 | 64 | 6 |
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright (C) 2014 Matthew Pickering <matthewtpickering@gmail.com>
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
-}
{- |
HTML entity definitions as provided by W3C.
The mapping matches the version from 10th April 2014.
The original source can be downloaded from <http://www.w3.org/TR/2014/REC-xml-entity-names-20140410/>.
Note: I have made one alteration, switching epsilon and varepsilon,
because the meanings of these names in HTML is different from the meanings
in MathML+LaTeX. See http://www.w3.org/2003/entities/2007doc/#epsilon.
-}
module Text.TeXMath.Readers.MathML.EntityMap (getUnicode) where
import qualified Data.Map as M
import qualified Data.Text as T
-- | Translates MathML entity reference to the corresponding Unicode string.
getUnicode :: T.Text -> Maybe T.Text
getUnicode = flip M.lookup entityList
entityList :: M.Map T.Text T.Text
entityList = M.fromList
[ ("AElig","\198")
, ("AMP","&")
, ("Aacute","\193")
, ("Abreve","\258")
, ("Acirc","\194")
, ("Acy","\1040")
, ("Afr","\120068")
, ("Agrave","\192")
, ("Alpha","\913")
, ("Amacr","\256")
, ("And","\10835")
, ("Aogon","\260")
, ("Aopf","\120120")
, ("ApplyFunction","\8289")
, ("Aring","\197")
, ("Ascr","\119964")
, ("Assign","\8788")
, ("Atilde","\195")
, ("Auml","\196")
, ("Backslash","\8726")
, ("Barv","\10983")
, ("Barwed","\8966")
, ("Bcy","\1041")
, ("Because","\8757")
, ("Bernoullis","\8492")
, ("Beta","\914")
, ("Bfr","\120069")
, ("Bopf","\120121")
, ("Breve","\728")
, ("Bscr","\8492")
, ("Bumpeq","\8782")
, ("CHcy","\1063")
, ("COPY","\169")
, ("Cacute","\262")
, ("Cap","\8914")
, ("CapitalDifferentialD","\8517")
, ("Cayleys","\8493")
, ("Ccaron","\268")
, ("Ccedil","\199")
, ("Ccirc","\264")
, ("Cconint","\8752")
, ("Cdot","\266")
, ("Cedilla","\184")
, ("CenterDot","\183")
, ("Cfr","\8493")
, ("Chi","\935")
, ("CircleDot","\8857")
, ("CircleMinus","\8854")
, ("CirclePlus","\8853")
, ("CircleTimes","\8855")
, ("ClockwiseContourIntegral","\8754")
, ("CloseCurlyDoubleQuote","\8221")
, ("CloseCurlyQuote","\8217")
, ("Colon","\8759")
, ("Colone","\10868")
, ("Congruent","\8801")
, ("Conint","\8751")
, ("ContourIntegral","\8750")
, ("Copf","\8450")
, ("Coproduct","\8720")
, ("CounterClockwiseContourIntegral","\8755")
, ("Cross","\10799")
, ("Cscr","\119966")
, ("Cup","\8915")
, ("CupCap","\8781")
, ("DD","\8517")
, ("DDotrahd","\10513")
, ("DJcy","\1026")
, ("DScy","\1029")
, ("DZcy","\1039")
, ("Dagger","\8225")
, ("Darr","\8609")
, ("Dashv","\10980")
, ("Dcaron","\270")
, ("Dcy","\1044")
, ("Del","\8711")
, ("Delta","\916")
, ("Dfr","\120071")
, ("DiacriticalAcute","\180")
, ("DiacriticalDot","\729")
, ("DiacriticalDoubleAcute","\733")
, ("DiacriticalGrave","`")
, ("DiacriticalTilde","\732")
, ("Diamond","\8900")
, ("DifferentialD","\8518")
, ("Dopf","\120123")
, ("Dot","\168")
, ("DotDot"," \8412")
, ("DotEqual","\8784")
, ("DoubleContourIntegral","\8751")
, ("DoubleDot","\168")
, ("DoubleDownArrow","\8659")
, ("DoubleLeftArrow","\8656")
, ("DoubleLeftRightArrow","\8660")
, ("DoubleLeftTee","\10980")
, ("DoubleLongLeftArrow","\10232")
, ("DoubleLongLeftRightArrow","\10234")
, ("DoubleLongRightArrow","\10233")
, ("DoubleRightArrow","\8658")
, ("DoubleRightTee","\8872")
, ("DoubleUpArrow","\8657")
, ("DoubleUpDownArrow","\8661")
, ("DoubleVerticalBar","\8741")
, ("DownArrow","\8595")
, ("DownArrowBar","\10515")
, ("DownArrowUpArrow","\8693")
, ("DownBreve"," \785")
, ("DownLeftRightVector","\10576")
, ("DownLeftTeeVector","\10590")
, ("DownLeftVector","\8637")
, ("DownLeftVectorBar","\10582")
, ("DownRightTeeVector","\10591")
, ("DownRightVector","\8641")
, ("DownRightVectorBar","\10583")
, ("DownTee","\8868")
, ("DownTeeArrow","\8615")
, ("Downarrow","\8659")
, ("Dscr","\119967")
, ("Dstrok","\272")
, ("ENG","\330")
, ("ETH","\208")
, ("Eacute","\201")
, ("Ecaron","\282")
, ("Ecirc","\202")
, ("Ecy","\1069")
, ("Edot","\278")
, ("Efr","\120072")
, ("Egrave","\200")
, ("Element","\8712")
, ("Emacr","\274")
, ("EmptySmallSquare","\9723")
, ("EmptyVerySmallSquare","\9643")
, ("Eogon","\280")
, ("Eopf","\120124")
, ("Epsilon","\917")
, ("Equal","\10869")
, ("EqualTilde","\8770")
, ("Equilibrium","\8652")
, ("Escr","\8496")
, ("Esim","\10867")
, ("Eta","\919")
, ("Euml","\203")
, ("Exists","\8707")
, ("ExponentialE","\8519")
, ("Fcy","\1060")
, ("Ffr","\120073")
, ("FilledSmallSquare","\9724")
, ("FilledVerySmallSquare","\9642")
, ("Fopf","\120125")
, ("ForAll","\8704")
, ("Fouriertrf","\8497")
, ("Fscr","\8497")
, ("GJcy","\1027")
, ("GT",">")
, ("Gamma","\915")
, ("Gammad","\988")
, ("Gbreve","\286")
, ("Gcedil","\290")
, ("Gcirc","\284")
, ("Gcy","\1043")
, ("Gdot","\288")
, ("Gfr","\120074")
, ("Gg","\8921")
, ("Gopf","\120126")
, ("GreaterEqual","\8805")
, ("GreaterEqualLess","\8923")
, ("GreaterFullEqual","\8807")
, ("GreaterGreater","\10914")
, ("GreaterLess","\8823")
, ("GreaterSlantEqual","\10878")
, ("GreaterTilde","\8819")
, ("Gscr","\119970")
, ("Gt","\8811")
, ("HARDcy","\1066")
, ("Hacek","\711")
, ("Hat","^")
, ("Hcirc","\292")
, ("Hfr","\8460")
, ("HilbertSpace","\8459")
, ("Hopf","\8461")
, ("HorizontalLine","\9472")
, ("Hscr","\8459")
, ("Hstrok","\294")
, ("HumpDownHump","\8782")
, ("HumpEqual","\8783")
, ("IEcy","\1045")
, ("IJlig","\306")
, ("IOcy","\1025")
, ("Iacute","\205")
, ("Icirc","\206")
, ("Icy","\1048")
, ("Idot","\304")
, ("Ifr","\8465")
, ("Igrave","\204")
, ("Im","\8465")
, ("Imacr","\298")
, ("ImaginaryI","\8520")
, ("Implies","\8658")
, ("Int","\8748")
, ("Integral","\8747")
, ("Intersection","\8898")
, ("InvisibleComma","\8291")
, ("InvisibleTimes","\8290")
, ("Iogon","\302")
, ("Iopf","\120128")
, ("Iota","\921")
, ("Iscr","\8464")
, ("Itilde","\296")
, ("Iukcy","\1030")
, ("Iuml","\207")
, ("Jcirc","\308")
, ("Jcy","\1049")
, ("Jfr","\120077")
, ("Jopf","\120129")
, ("Jscr","\119973")
, ("Jsercy","\1032")
, ("Jukcy","\1028")
, ("KHcy","\1061")
, ("KJcy","\1036")
, ("Kappa","\922")
, ("Kcedil","\310")
, ("Kcy","\1050")
, ("Kfr","\120078")
, ("Kopf","\120130")
, ("Kscr","\119974")
, ("LJcy","\1033")
, ("LT","<")
, ("Lacute","\313")
, ("Lambda","\923")
, ("Lang","\10218")
, ("Laplacetrf","\8466")
, ("Larr","\8606")
, ("Lcaron","\317")
, ("Lcedil","\315")
, ("Lcy","\1051")
, ("LeftAngleBracket","\10216")
, ("LeftArrow","\8592")
, ("LeftArrowBar","\8676")
, ("LeftArrowRightArrow","\8646")
, ("LeftCeiling","\8968")
, ("LeftDoubleBracket","\10214")
, ("LeftDownTeeVector","\10593")
, ("LeftDownVector","\8643")
, ("LeftDownVectorBar","\10585")
, ("LeftFloor","\8970")
, ("LeftRightArrow","\8596")
, ("LeftRightVector","\10574")
, ("LeftTee","\8867")
, ("LeftTeeArrow","\8612")
, ("LeftTeeVector","\10586")
, ("LeftTriangle","\8882")
, ("LeftTriangleBar","\10703")
, ("LeftTriangleEqual","\8884")
, ("LeftUpDownVector","\10577")
, ("LeftUpTeeVector","\10592")
, ("LeftUpVector","\8639")
, ("LeftUpVectorBar","\10584")
, ("LeftVector","\8636")
, ("LeftVectorBar","\10578")
, ("Leftarrow","\8656")
, ("Leftrightarrow","\8660")
, ("LessEqualGreater","\8922")
, ("LessFullEqual","\8806")
, ("LessGreater","\8822")
, ("LessLess","\10913")
, ("LessSlantEqual","\10877")
, ("LessTilde","\8818")
, ("Lfr","\120079")
, ("Ll","\8920")
, ("Lleftarrow","\8666")
, ("Lmidot","\319")
, ("LongLeftArrow","\10229")
, ("LongLeftRightArrow","\10231")
, ("LongRightArrow","\10230")
, ("Longleftarrow","\10232")
, ("Longleftrightarrow","\10234")
, ("Longrightarrow","\10233")
, ("Lopf","\120131")
, ("LowerLeftArrow","\8601")
, ("LowerRightArrow","\8600")
, ("Lscr","\8466")
, ("Lsh","\8624")
, ("Lstrok","\321")
, ("Lt","\8810")
, ("Map","\10501")
, ("Mcy","\1052")
, ("MediumSpace","\8287")
, ("Mellintrf","\8499")
, ("Mfr","\120080")
, ("MinusPlus","\8723")
, ("Mopf","\120132")
, ("Mscr","\8499")
, ("Mu","\924")
, ("NJcy","\1034")
, ("Nacute","\323")
, ("Ncaron","\327")
, ("Ncedil","\325")
, ("Ncy","\1053")
, ("NegativeMediumSpace","\8203")
, ("NegativeThickSpace","\8203")
, ("NegativeThinSpace","\8203")
, ("NegativeVeryThinSpace","\8203")
, ("NestedGreaterGreater","\8811")
, ("NestedLessLess","\8810")
, ("NewLine","\n")
, ("Nfr","\120081")
, ("NoBreak","\8288")
, ("NonBreakingSpace","\160")
, ("Nopf","\8469")
, ("Not","\10988")
, ("NotCongruent","\8802")
, ("NotCupCap","\8813")
, ("NotDoubleVerticalBar","\8742")
, ("NotElement","\8713")
, ("NotEqual","\8800")
, ("NotEqualTilde","\8770\824")
, ("NotExists","\8708")
, ("NotGreater","\8815")
, ("NotGreaterEqual","\8817")
, ("NotGreaterFullEqual","\8807\824")
, ("NotGreaterGreater","\8811\824")
, ("NotGreaterLess","\8825")
, ("NotGreaterSlantEqual","\10878\824")
, ("NotGreaterTilde","\8821")
, ("NotHumpDownHump","\8782\824")
, ("NotHumpEqual","\8783\824")
, ("NotLeftTriangle","\8938")
, ("NotLeftTriangleBar","\10703\824")
, ("NotLeftTriangleEqual","\8940")
, ("NotLess","\8814")
, ("NotLessEqual","\8816")
, ("NotLessGreater","\8824")
, ("NotLessLess","\8810\824")
, ("NotLessSlantEqual","\10877\824")
, ("NotLessTilde","\8820")
, ("NotNestedGreaterGreater","\10914\824")
, ("NotNestedLessLess","\10913\824")
, ("NotPrecedes","\8832")
, ("NotPrecedesEqual","\10927\824")
, ("NotPrecedesSlantEqual","\8928")
, ("NotReverseElement","\8716")
, ("NotRightTriangle","\8939")
, ("NotRightTriangleBar","\10704\824")
, ("NotRightTriangleEqual","\8941")
, ("NotSquareSubset","\8847\824")
, ("NotSquareSubsetEqual","\8930")
, ("NotSquareSuperset","\8848\824")
, ("NotSquareSupersetEqual","\8931")
, ("NotSubset","\8834\8402")
, ("NotSubsetEqual","\8840")
, ("NotSucceeds","\8833")
, ("NotSucceedsEqual","\10928\824")
, ("NotSucceedsSlantEqual","\8929")
, ("NotSucceedsTilde","\8831\824")
, ("NotSuperset","\8835\8402")
, ("NotSupersetEqual","\8841")
, ("NotTilde","\8769")
, ("NotTildeEqual","\8772")
, ("NotTildeFullEqual","\8775")
, ("NotTildeTilde","\8777")
, ("NotVerticalBar","\8740")
, ("Nscr","\119977")
, ("Ntilde","\209")
, ("Nu","\925")
, ("OElig","\338")
, ("Oacute","\211")
, ("Ocirc","\212")
, ("Ocy","\1054")
, ("Odblac","\336")
, ("Ofr","\120082")
, ("Ograve","\210")
, ("Omacr","\332")
, ("Omega","\937")
, ("Omicron","\927")
, ("Oopf","\120134")
, ("OpenCurlyDoubleQuote","\8220")
, ("OpenCurlyQuote","\8216")
, ("Or","\10836")
, ("Oscr","\119978")
, ("Oslash","\216")
, ("Otilde","\213")
, ("Otimes","\10807")
, ("Ouml","\214")
, ("OverBar","\8254")
, ("OverBrace","\9182")
, ("OverBracket","\9140")
, ("OverParenthesis","\9180")
, ("PartialD","\8706")
, ("Pcy","\1055")
, ("Pfr","\120083")
, ("Phi","\934")
, ("Pi","\928")
, ("PlusMinus","\177")
, ("Poincareplane","\8460")
, ("Popf","\8473")
, ("Pr","\10939")
, ("Precedes","\8826")
, ("PrecedesEqual","\10927")
, ("PrecedesSlantEqual","\8828")
, ("PrecedesTilde","\8830")
, ("Prime","\8243")
, ("Product","\8719")
, ("Proportion","\8759")
, ("Proportional","\8733")
, ("Pscr","\119979")
, ("Psi","\936")
, ("QUOT","\"")
, ("Qfr","\120084")
, ("Qopf","\8474")
, ("Qscr","\119980")
, ("RBarr","\10512")
, ("REG","\174")
, ("Racute","\340")
, ("Rang","\10219")
, ("Rarr","\8608")
, ("Rarrtl","\10518")
, ("Rcaron","\344")
, ("Rcedil","\342")
, ("Rcy","\1056")
, ("Re","\8476")
, ("ReverseElement","\8715")
, ("ReverseEquilibrium","\8651")
, ("ReverseUpEquilibrium","\10607")
, ("Rfr","\8476")
, ("Rho","\929")
, ("RightAngleBracket","\10217")
, ("RightArrow","\8594")
, ("RightArrowBar","\8677")
, ("RightArrowLeftArrow","\8644")
, ("RightCeiling","\8969")
, ("RightDoubleBracket","\10215")
, ("RightDownTeeVector","\10589")
, ("RightDownVector","\8642")
, ("RightDownVectorBar","\10581")
, ("RightFloor","\8971")
, ("RightTee","\8866")
, ("RightTeeArrow","\8614")
, ("RightTeeVector","\10587")
, ("RightTriangle","\8883")
, ("RightTriangleBar","\10704")
, ("RightTriangleEqual","\8885")
, ("RightUpDownVector","\10575")
, ("RightUpTeeVector","\10588")
, ("RightUpVector","\8638")
, ("RightUpVectorBar","\10580")
, ("RightVector","\8640")
, ("RightVectorBar","\10579")
, ("Rightarrow","\8658")
, ("Ropf","\8477")
, ("RoundImplies","\10608")
, ("Rrightarrow","\8667")
, ("Rscr","\8475")
, ("Rsh","\8625")
, ("RuleDelayed","\10740")
, ("SHCHcy","\1065")
, ("SHcy","\1064")
, ("SOFTcy","\1068")
, ("Sacute","\346")
, ("Sc","\10940")
, ("Scaron","\352")
, ("Scedil","\350")
, ("Scirc","\348")
, ("Scy","\1057")
, ("Sfr","\120086")
, ("ShortDownArrow","\8595")
, ("ShortLeftArrow","\8592")
, ("ShortRightArrow","\8594")
, ("ShortUpArrow","\8593")
, ("Sigma","\931")
, ("SmallCircle","\8728")
, ("Sopf","\120138")
, ("Sqrt","\8730")
, ("Square","\9633")
, ("SquareIntersection","\8851")
, ("SquareSubset","\8847")
, ("SquareSubsetEqual","\8849")
, ("SquareSuperset","\8848")
, ("SquareSupersetEqual","\8850")
, ("SquareUnion","\8852")
, ("Sscr","\119982")
, ("Star","\8902")
, ("Sub","\8912")
, ("Subset","\8912")
, ("SubsetEqual","\8838")
, ("Succeeds","\8827")
, ("SucceedsEqual","\10928")
, ("SucceedsSlantEqual","\8829")
, ("SucceedsTilde","\8831")
, ("SuchThat","\8715")
, ("Sum","\8721")
, ("Sup","\8913")
, ("Superset","\8835")
, ("SupersetEqual","\8839")
, ("Supset","\8913")
, ("THORN","\222")
, ("TRADE","\8482")
, ("TSHcy","\1035")
, ("TScy","\1062")
, ("Tab","\t")
, ("Tau","\932")
, ("Tcaron","\356")
, ("Tcedil","\354")
, ("Tcy","\1058")
, ("Tfr","\120087")
, ("Therefore","\8756")
, ("Theta","\920")
, ("ThickSpace","\8287\8202")
, ("ThinSpace","\8201")
, ("Tilde","\8764")
, ("TildeEqual","\8771")
, ("TildeFullEqual","\8773")
, ("TildeTilde","\8776")
, ("Topf","\120139")
, ("TripleDot"," \8411")
, ("Tscr","\119983")
, ("Tstrok","\358")
, ("Uacute","\218")
, ("Uarr","\8607")
, ("Uarrocir","\10569")
, ("Ubrcy","\1038")
, ("Ubreve","\364")
, ("Ucirc","\219")
, ("Ucy","\1059")
, ("Udblac","\368")
, ("Ufr","\120088")
, ("Ugrave","\217")
, ("Umacr","\362")
, ("UnderBar","_")
, ("UnderBrace","\9183")
, ("UnderBracket","\9141")
, ("UnderParenthesis","\9181")
, ("Union","\8899")
, ("UnionPlus","\8846")
, ("Uogon","\370")
, ("Uopf","\120140")
, ("UpArrow","\8593")
, ("UpArrowBar","\10514")
, ("UpArrowDownArrow","\8645")
, ("UpDownArrow","\8597")
, ("UpEquilibrium","\10606")
, ("UpTee","\8869")
, ("UpTeeArrow","\8613")
, ("Uparrow","\8657")
, ("Updownarrow","\8661")
, ("UpperLeftArrow","\8598")
, ("UpperRightArrow","\8599")
, ("Upsi","\978")
, ("Upsilon","\933")
, ("Uring","\366")
, ("Uscr","\119984")
, ("Utilde","\360")
, ("Uuml","\220")
, ("VDash","\8875")
, ("Vbar","\10987")
, ("Vcy","\1042")
, ("Vdash","\8873")
, ("Vdashl","\10982")
, ("Vee","\8897")
, ("Verbar","\8214")
, ("Vert","\8214")
, ("VerticalBar","\8739")
, ("VerticalLine","|")
, ("VerticalSeparator","\10072")
, ("VerticalTilde","\8768")
, ("VeryThinSpace","\8202")
, ("Vfr","\120089")
, ("Vopf","\120141")
, ("Vscr","\119985")
, ("Vvdash","\8874")
, ("Wcirc","\372")
, ("Wedge","\8896")
, ("Wfr","\120090")
, ("Wopf","\120142")
, ("Wscr","\119986")
, ("Xfr","\120091")
, ("Xi","\926")
, ("Xopf","\120143")
, ("Xscr","\119987")
, ("YAcy","\1071")
, ("YIcy","\1031")
, ("YUcy","\1070")
, ("Yacute","\221")
, ("Ycirc","\374")
, ("Ycy","\1067")
, ("Yfr","\120092")
, ("Yopf","\120144")
, ("Yscr","\119988")
, ("Yuml","\376")
, ("ZHcy","\1046")
, ("Zacute","\377")
, ("Zcaron","\381")
, ("Zcy","\1047")
, ("Zdot","\379")
, ("ZeroWidthSpace","\8203")
, ("Zeta","\918")
, ("Zfr","\8488")
, ("Zopf","\8484")
, ("Zscr","\119989")
, ("aacute","\225")
, ("abreve","\259")
, ("ac","\8766")
, ("acE","\8766\819")
, ("acd","\8767")
, ("acirc","\226")
, ("acute","\180")
, ("acy","\1072")
, ("aelig","\230")
, ("af","\8289")
, ("afr","\120094")
, ("agrave","\224")
, ("alefsym","\8501")
, ("aleph","\8501")
, ("alpha","\945")
, ("amacr","\257")
, ("amalg","\10815")
, ("amp","&")
, ("and","\8743")
, ("andand","\10837")
, ("andd","\10844")
, ("andslope","\10840")
, ("andv","\10842")
, ("ang","\8736")
, ("ange","\10660")
, ("angle","\8736")
, ("angmsd","\8737")
, ("angmsdaa","\10664")
, ("angmsdab","\10665")
, ("angmsdac","\10666")
, ("angmsdad","\10667")
, ("angmsdae","\10668")
, ("angmsdaf","\10669")
, ("angmsdag","\10670")
, ("angmsdah","\10671")
, ("angrt","\8735")
, ("angrtvb","\8894")
, ("angrtvbd","\10653")
, ("angsph","\8738")
, ("angst","\197")
, ("angzarr","\9084")
, ("aogon","\261")
, ("aopf","\120146")
, ("ap","\8776")
, ("apE","\10864")
, ("apacir","\10863")
, ("ape","\8778")
, ("apid","\8779")
, ("apos","'")
, ("approx","\8776")
, ("approxeq","\8778")
, ("aring","\229")
, ("ascr","\119990")
, ("ast","*")
, ("asymp","\8776")
, ("asympeq","\8781")
, ("atilde","\227")
, ("auml","\228")
, ("awconint","\8755")
, ("awint","\10769")
, ("bNot","\10989")
, ("backcong","\8780")
, ("backepsilon","\1014")
, ("backprime","\8245")
, ("backsim","\8765")
, ("backsimeq","\8909")
, ("barvee","\8893")
, ("barwed","\8965")
, ("barwedge","\8965")
, ("bbrk","\9141")
, ("bbrktbrk","\9142")
, ("bcong","\8780")
, ("bcy","\1073")
, ("bdquo","\8222")
, ("becaus","\8757")
, ("because","\8757")
, ("bemptyv","\10672")
, ("bepsi","\1014")
, ("bernou","\8492")
, ("beta","\946")
, ("beth","\8502")
, ("between","\8812")
, ("bfr","\120095")
, ("bigcap","\8898")
, ("bigcirc","\9711")
, ("bigcup","\8899")
, ("bigodot","\10752")
, ("bigoplus","\10753")
, ("bigotimes","\10754")
, ("bigsqcup","\10758")
, ("bigstar","\9733")
, ("bigtriangledown","\9661")
, ("bigtriangleup","\9651")
, ("biguplus","\10756")
, ("bigvee","\8897")
, ("bigwedge","\8896")
, ("bkarow","\10509")
, ("blacklozenge","\10731")
, ("blacksquare","\9642")
, ("blacktriangle","\9652")
, ("blacktriangledown","\9662")
, ("blacktriangleleft","\9666")
, ("blacktriangleright","\9656")
, ("blank","\9251")
, ("blk12","\9618")
, ("blk14","\9617")
, ("blk34","\9619")
, ("block","\9608")
, ("bne","=\8421")
, ("bnequiv","\8801\8421")
, ("bnot","\8976")
, ("bopf","\120147")
, ("bot","\8869")
, ("bottom","\8869")
, ("bowtie","\8904")
, ("boxDL","\9559")
, ("boxDR","\9556")
, ("boxDl","\9558")
, ("boxDr","\9555")
, ("boxH","\9552")
, ("boxHD","\9574")
, ("boxHU","\9577")
, ("boxHd","\9572")
, ("boxHu","\9575")
, ("boxUL","\9565")
, ("boxUR","\9562")
, ("boxUl","\9564")
, ("boxUr","\9561")
, ("boxV","\9553")
, ("boxVH","\9580")
, ("boxVL","\9571")
, ("boxVR","\9568")
, ("boxVh","\9579")
, ("boxVl","\9570")
, ("boxVr","\9567")
, ("boxbox","\10697")
, ("boxdL","\9557")
, ("boxdR","\9554")
, ("boxdl","\9488")
, ("boxdr","\9484")
, ("boxh","\9472")
, ("boxhD","\9573")
, ("boxhU","\9576")
, ("boxhd","\9516")
, ("boxhu","\9524")
, ("boxminus","\8863")
, ("boxplus","\8862")
, ("boxtimes","\8864")
, ("boxuL","\9563")
, ("boxuR","\9560")
, ("boxul","\9496")
, ("boxur","\9492")
, ("boxv","\9474")
, ("boxvH","\9578")
, ("boxvL","\9569")
, ("boxvR","\9566")
, ("boxvh","\9532")
, ("boxvl","\9508")
, ("boxvr","\9500")
, ("bprime","\8245")
, ("breve","\728")
, ("brvbar","\166")
, ("bscr","\119991")
, ("bsemi","\8271")
, ("bsim","\8765")
, ("bsime","\8909")
, ("bsol","\\")
, ("bsolb","\10693")
, ("bsolhsub","\10184")
, ("bull","\8226")
, ("bullet","\8226")
, ("bump","\8782")
, ("bumpE","\10926")
, ("bumpe","\8783")
, ("bumpeq","\8783")
, ("cacute","\263")
, ("cap","\8745")
, ("capand","\10820")
, ("capbrcup","\10825")
, ("capcap","\10827")
, ("capcup","\10823")
, ("capdot","\10816")
, ("caps","\8745\65024")
, ("caret","\8257")
, ("caron","\711")
, ("ccaps","\10829")
, ("ccaron","\269")
, ("ccedil","\231")
, ("ccirc","\265")
, ("ccups","\10828")
, ("ccupssm","\10832")
, ("cdot","\267")
, ("cedil","\184")
, ("cemptyv","\10674")
, ("cent","\162")
, ("centerdot","\183")
, ("cfr","\120096")
, ("chcy","\1095")
, ("check","\10003")
, ("checkmark","\10003")
, ("chi","\967")
, ("cir","\9675")
, ("cirE","\10691")
, ("circ","\710")
, ("circeq","\8791")
, ("circlearrowleft","\8634")
, ("circlearrowright","\8635")
, ("circledR","\174")
, ("circledS","\9416")
, ("circledast","\8859")
, ("circledcirc","\8858")
, ("circleddash","\8861")
, ("cire","\8791")
, ("cirfnint","\10768")
, ("cirmid","\10991")
, ("cirscir","\10690")
, ("clubs","\9827")
, ("clubsuit","\9827")
, ("colon",":")
, ("colone","\8788")
, ("coloneq","\8788")
, ("comma",",")
, ("commat","@")
, ("comp","\8705")
, ("compfn","\8728")
, ("complement","\8705")
, ("complexes","\8450")
, ("cong","\8773")
, ("congdot","\10861")
, ("conint","\8750")
, ("copf","\120148")
, ("coprod","\8720")
, ("copy","\169")
, ("copysr","\8471")
, ("crarr","\8629")
, ("cross","\10007")
, ("cscr","\119992")
, ("csub","\10959")
, ("csube","\10961")
, ("csup","\10960")
, ("csupe","\10962")
, ("ctdot","\8943")
, ("cudarrl","\10552")
, ("cudarrr","\10549")
, ("cuepr","\8926")
, ("cuesc","\8927")
, ("cularr","\8630")
, ("cularrp","\10557")
, ("cup","\8746")
, ("cupbrcap","\10824")
, ("cupcap","\10822")
, ("cupcup","\10826")
, ("cupdot","\8845")
, ("cupor","\10821")
, ("cups","\8746\65024")
, ("curarr","\8631")
, ("curarrm","\10556")
, ("curlyeqprec","\8926")
, ("curlyeqsucc","\8927")
, ("curlyvee","\8910")
, ("curlywedge","\8911")
, ("curren","\164")
, ("curvearrowleft","\8630")
, ("curvearrowright","\8631")
, ("cuvee","\8910")
, ("cuwed","\8911")
, ("cwconint","\8754")
, ("cwint","\8753")
, ("cylcty","\9005")
, ("dArr","\8659")
, ("dHar","\10597")
, ("dagger","\8224")
, ("daleth","\8504")
, ("darr","\8595")
, ("dash","\8208")
, ("dashv","\8867")
, ("dbkarow","\10511")
, ("dblac","\733")
, ("dcaron","\271")
, ("dcy","\1076")
, ("dd","\8518")
, ("ddagger","\8225")
, ("ddarr","\8650")
, ("ddotseq","\10871")
, ("deg","\176")
, ("delta","\948")
, ("demptyv","\10673")
, ("dfisht","\10623")
, ("dfr","\120097")
, ("dharl","\8643")
, ("dharr","\8642")
, ("diam","\8900")
, ("diamond","\8900")
, ("diamondsuit","\9830")
, ("diams","\9830")
, ("die","\168")
, ("digamma","\989")
, ("disin","\8946")
, ("div","\247")
, ("divide","\247")
, ("divideontimes","\8903")
, ("divonx","\8903")
, ("djcy","\1106")
, ("dlcorn","\8990")
, ("dlcrop","\8973")
, ("dollar","$")
, ("dopf","\120149")
, ("dot","\729")
, ("doteq","\8784")
, ("doteqdot","\8785")
, ("dotminus","\8760")
, ("dotplus","\8724")
, ("dotsquare","\8865")
, ("doublebarwedge","\8966")
, ("downarrow","\8595")
, ("downdownarrows","\8650")
, ("downharpoonleft","\8643")
, ("downharpoonright","\8642")
, ("drbkarow","\10512")
, ("drcorn","\8991")
, ("drcrop","\8972")
, ("dscr","\119993")
, ("dscy","\1109")
, ("dsol","\10742")
, ("dstrok","\273")
, ("dtdot","\8945")
, ("dtri","\9663")
, ("dtrif","\9662")
, ("duarr","\8693")
, ("duhar","\10607")
, ("dwangle","\10662")
, ("dzcy","\1119")
, ("dzigrarr","\10239")
, ("eDDot","\10871")
, ("eDot","\8785")
, ("eacute","\233")
, ("easter","\10862")
, ("ecaron","\283")
, ("ecir","\8790")
, ("ecirc","\234")
, ("ecolon","\8789")
, ("ecy","\1101")
, ("edot","\279")
, ("ee","\8519")
, ("efDot","\8786")
, ("efr","\120098")
, ("eg","\10906")
, ("egrave","\232")
, ("egs","\10902")
, ("egsdot","\10904")
, ("el","\10905")
, ("elinters","\9191")
, ("ell","\8467")
, ("els","\10901")
, ("elsdot","\10903")
, ("emacr","\275")
, ("empty","\8709")
, ("emptyset","\8709")
, ("emptyv","\8709")
, ("emsp","\8195")
, ("emsp13","\8196")
, ("emsp14","\8197")
, ("eng","\331")
, ("ensp","\8194")
, ("eogon","\281")
, ("eopf","\120150")
, ("epar","\8917")
, ("eparsl","\10723")
, ("eplus","\10865")
, ("epsi","\949")
, ("epsilon","\1013")
, ("epsiv","\1013")
, ("eqcirc","\8790")
, ("eqcolon","\8789")
, ("eqsim","\8770")
, ("eqslantgtr","\10902")
, ("eqslantless","\10901")
, ("equals","=")
, ("equest","\8799")
, ("equiv","\8801")
, ("equivDD","\10872")
, ("eqvparsl","\10725")
, ("erDot","\8787")
, ("erarr","\10609")
, ("escr","\8495")
, ("esdot","\8784")
, ("esim","\8770")
, ("eta","\951")
, ("eth","\240")
, ("euml","\235")
, ("euro","\8364")
, ("excl","!")
, ("exist","\8707")
, ("expectation","\8496")
, ("exponentiale","\8519")
, ("fallingdotseq","\8786")
, ("fcy","\1092")
, ("female","\9792")
, ("ffilig","\64259")
, ("fflig","\64256")
, ("ffllig","\64260")
, ("ffr","\120099")
, ("filig","\64257")
, ("fjlig","fj")
, ("flat","\9837")
, ("fllig","\64258")
, ("fltns","\9649")
, ("fnof","\402")
, ("fopf","\120151")
, ("forall","\8704")
, ("fork","\8916")
, ("forkv","\10969")
, ("fpartint","\10765")
, ("frac12","\189")
, ("frac13","\8531")
, ("frac14","\188")
, ("frac15","\8533")
, ("frac16","\8537")
, ("frac18","\8539")
, ("frac23","\8532")
, ("frac25","\8534")
, ("frac34","\190")
, ("frac35","\8535")
, ("frac38","\8540")
, ("frac45","\8536")
, ("frac56","\8538")
, ("frac58","\8541")
, ("frac78","\8542")
, ("frasl","\8260")
, ("frown","\8994")
, ("fscr","\119995")
, ("gE","\8807")
, ("gEl","\10892")
, ("gacute","\501")
, ("gamma","\947")
, ("gammad","\989")
, ("gap","\10886")
, ("gbreve","\287")
, ("gcirc","\285")
, ("gcy","\1075")
, ("gdot","\289")
, ("ge","\8805")
, ("gel","\8923")
, ("geq","\8805")
, ("geqq","\8807")
, ("geqslant","\10878")
, ("ges","\10878")
, ("gescc","\10921")
, ("gesdot","\10880")
, ("gesdoto","\10882")
, ("gesdotol","\10884")
, ("gesl","\8923\65024")
, ("gesles","\10900")
, ("gfr","\120100")
, ("gg","\8811")
, ("ggg","\8921")
, ("gimel","\8503")
, ("gjcy","\1107")
, ("gl","\8823")
, ("glE","\10898")
, ("gla","\10917")
, ("glj","\10916")
, ("gnE","\8809")
, ("gnap","\10890")
, ("gnapprox","\10890")
, ("gne","\10888")
, ("gneq","\10888")
, ("gneqq","\8809")
, ("gnsim","\8935")
, ("gopf","\120152")
, ("grave","`")
, ("gscr","\8458")
, ("gsim","\8819")
, ("gsime","\10894")
, ("gsiml","\10896")
, ("gt",">")
, ("gtcc","\10919")
, ("gtcir","\10874")
, ("gtdot","\8919")
, ("gtlPar","\10645")
, ("gtquest","\10876")
, ("gtrapprox","\10886")
, ("gtrarr","\10616")
, ("gtrdot","\8919")
, ("gtreqless","\8923")
, ("gtreqqless","\10892")
, ("gtrless","\8823")
, ("gtrsim","\8819")
, ("gvertneqq","\8809\65024")
, ("gvnE","\8809\65024")
, ("hArr","\8660")
, ("hairsp","\8202")
, ("half","\189")
, ("hamilt","\8459")
, ("hardcy","\1098")
, ("harr","\8596")
, ("harrcir","\10568")
, ("harrw","\8621")
, ("hbar","\8463")
, ("hcirc","\293")
, ("hearts","\9829")
, ("heartsuit","\9829")
, ("hellip","\8230")
, ("hercon","\8889")
, ("hfr","\120101")
, ("hksearow","\10533")
, ("hkswarow","\10534")
, ("hoarr","\8703")
, ("homtht","\8763")
, ("hookleftarrow","\8617")
, ("hookrightarrow","\8618")
, ("hopf","\120153")
, ("horbar","\8213")
, ("hscr","\119997")
, ("hslash","\8463")
, ("hstrok","\295")
, ("hybull","\8259")
, ("hyphen","\8208")
, ("iacute","\237")
, ("ic","\8291")
, ("icirc","\238")
, ("icy","\1080")
, ("iecy","\1077")
, ("iexcl","\161")
, ("iff","\8660")
, ("ifr","\120102")
, ("igrave","\236")
, ("ii","\8520")
, ("iiiint","\10764")
, ("iiint","\8749")
, ("iinfin","\10716")
, ("iiota","\8489")
, ("ijlig","\307")
, ("imacr","\299")
, ("image","\8465")
, ("imagline","\8464")
, ("imagpart","\8465")
, ("imath","\305")
, ("imof","\8887")
, ("imped","\437")
, ("in","\8712")
, ("incare","\8453")
, ("infin","\8734")
, ("infintie","\10717")
, ("inodot","\305")
, ("int","\8747")
, ("intcal","\8890")
, ("integers","\8484")
, ("intercal","\8890")
, ("intlarhk","\10775")
, ("intprod","\10812")
, ("iocy","\1105")
, ("iogon","\303")
, ("iopf","\120154")
, ("iota","\953")
, ("iprod","\10812")
, ("iquest","\191")
, ("iscr","\119998")
, ("isin","\8712")
, ("isinE","\8953")
, ("isindot","\8949")
, ("isins","\8948")
, ("isinsv","\8947")
, ("isinv","\8712")
, ("it","\8290")
, ("itilde","\297")
, ("iukcy","\1110")
, ("iuml","\239")
, ("jcirc","\309")
, ("jcy","\1081")
, ("jfr","\120103")
, ("jmath","\567")
, ("jopf","\120155")
, ("jscr","\119999")
, ("jsercy","\1112")
, ("jukcy","\1108")
, ("kappa","\954")
, ("kappav","\1008")
, ("kcedil","\311")
, ("kcy","\1082")
, ("kfr","\120104")
, ("kgreen","\312")
, ("khcy","\1093")
, ("kjcy","\1116")
, ("kopf","\120156")
, ("kscr","\120000")
, ("lAarr","\8666")
, ("lArr","\8656")
, ("lAtail","\10523")
, ("lBarr","\10510")
, ("lE","\8806")
, ("lEg","\10891")
, ("lHar","\10594")
, ("lacute","\314")
, ("laemptyv","\10676")
, ("lagran","\8466")
, ("lambda","\955")
, ("lang","\10216")
, ("langd","\10641")
, ("langle","\10216")
, ("lap","\10885")
, ("laquo","\171")
, ("larr","\8592")
, ("larrb","\8676")
, ("larrbfs","\10527")
, ("larrfs","\10525")
, ("larrhk","\8617")
, ("larrlp","\8619")
, ("larrpl","\10553")
, ("larrsim","\10611")
, ("larrtl","\8610")
, ("lat","\10923")
, ("latail","\10521")
, ("late","\10925")
, ("lates","\10925\65024")
, ("lbarr","\10508")
, ("lbbrk","\10098")
, ("lbrace","{")
, ("lbrack","[")
, ("lbrke","\10635")
, ("lbrksld","\10639")
, ("lbrkslu","\10637")
, ("lcaron","\318")
, ("lcedil","\316")
, ("lceil","\8968")
, ("lcub","{")
, ("lcy","\1083")
, ("ldca","\10550")
, ("ldquo","\8220")
, ("ldquor","\8222")
, ("ldrdhar","\10599")
, ("ldrushar","\10571")
, ("ldsh","\8626")
, ("le","\8804")
, ("leftarrow","\8592")
, ("leftarrowtail","\8610")
, ("leftharpoondown","\8637")
, ("leftharpoonup","\8636")
, ("leftleftarrows","\8647")
, ("leftrightarrow","\8596")
, ("leftrightarrows","\8646")
, ("leftrightharpoons","\8651")
, ("leftrightsquigarrow","\8621")
, ("leftthreetimes","\8907")
, ("leg","\8922")
, ("leq","\8804")
, ("leqq","\8806")
, ("leqslant","\10877")
, ("les","\10877")
, ("lescc","\10920")
, ("lesdot","\10879")
, ("lesdoto","\10881")
, ("lesdotor","\10883")
, ("lesg","\8922\65024")
, ("lesges","\10899")
, ("lessapprox","\10885")
, ("lessdot","\8918")
, ("lesseqgtr","\8922")
, ("lesseqqgtr","\10891")
, ("lessgtr","\8822")
, ("lesssim","\8818")
, ("lfisht","\10620")
, ("lfloor","\8970")
, ("lfr","\120105")
, ("lg","\8822")
, ("lgE","\10897")
, ("lhard","\8637")
, ("lharu","\8636")
, ("lharul","\10602")
, ("lhblk","\9604")
, ("ljcy","\1113")
, ("ll","\8810")
, ("llarr","\8647")
, ("llcorner","\8990")
, ("llhard","\10603")
, ("lltri","\9722")
, ("lmidot","\320")
, ("lmoust","\9136")
, ("lmoustache","\9136")
, ("lnE","\8808")
, ("lnap","\10889")
, ("lnapprox","\10889")
, ("lne","\10887")
, ("lneq","\10887")
, ("lneqq","\8808")
, ("lnsim","\8934")
, ("loang","\10220")
, ("loarr","\8701")
, ("lobrk","\10214")
, ("longleftarrow","\10229")
, ("longleftrightarrow","\10231")
, ("longmapsto","\10236")
, ("longrightarrow","\10230")
, ("looparrowleft","\8619")
, ("looparrowright","\8620")
, ("lopar","\10629")
, ("lopf","\120157")
, ("loplus","\10797")
, ("lotimes","\10804")
, ("lowast","\8727")
, ("lowbar","_")
, ("loz","\9674")
, ("lozenge","\9674")
, ("lozf","\10731")
, ("lpar","(")
, ("lparlt","\10643")
, ("lrarr","\8646")
, ("lrcorner","\8991")
, ("lrhar","\8651")
, ("lrhard","\10605")
, ("lrm","\8206")
, ("lrtri","\8895")
, ("lsaquo","\8249")
, ("lscr","\120001")
, ("lsh","\8624")
, ("lsim","\8818")
, ("lsime","\10893")
, ("lsimg","\10895")
, ("lsqb","[")
, ("lsquo","\8216")
, ("lsquor","\8218")
, ("lstrok","\322")
, ("lt","<")
, ("ltcc","\10918")
, ("ltcir","\10873")
, ("ltdot","\8918")
, ("lthree","\8907")
, ("ltimes","\8905")
, ("ltlarr","\10614")
, ("ltquest","\10875")
, ("ltrPar","\10646")
, ("ltri","\9667")
, ("ltrie","\8884")
, ("ltrif","\9666")
, ("lurdshar","\10570")
, ("luruhar","\10598")
, ("lvertneqq","\8808\65024")
, ("lvnE","\8808\65024")
, ("mDDot","\8762")
, ("macr","\175")
, ("male","\9794")
, ("malt","\10016")
, ("maltese","\10016")
, ("map","\8614")
, ("mapsto","\8614")
, ("mapstodown","\8615")
, ("mapstoleft","\8612")
, ("mapstoup","\8613")
, ("marker","\9646")
, ("mcomma","\10793")
, ("mcy","\1084")
, ("mdash","\8212")
, ("measuredangle","\8737")
, ("mfr","\120106")
, ("mho","\8487")
, ("micro","\181")
, ("mid","\8739")
, ("midast","*")
, ("midcir","\10992")
, ("middot","\183")
, ("minus","\8722")
, ("minusb","\8863")
, ("minusd","\8760")
, ("minusdu","\10794")
, ("mlcp","\10971")
, ("mldr","\8230")
, ("mnplus","\8723")
, ("models","\8871")
, ("mopf","\120158")
, ("mp","\8723")
, ("mscr","\120002")
, ("mstpos","\8766")
, ("mu","\956")
, ("multimap","\8888")
, ("mumap","\8888")
, ("nGg","\8921\824")
, ("nGt","\8811\8402")
, ("nGtv","\8811\824")
, ("nLeftarrow","\8653")
, ("nLeftrightarrow","\8654")
, ("nLl","\8920\824")
, ("nLt","\8810\8402")
, ("nLtv","\8810\824")
, ("nRightarrow","\8655")
, ("nVDash","\8879")
, ("nVdash","\8878")
, ("nabla","\8711")
, ("nacute","\324")
, ("nang","\8736\8402")
, ("nap","\8777")
, ("napE","\10864\824")
, ("napid","\8779\824")
, ("napos","\329")
, ("napprox","\8777")
, ("natur","\9838")
, ("natural","\9838")
, ("naturals","\8469")
, ("nbsp","\160")
, ("nbump","\8782\824")
, ("nbumpe","\8783\824")
, ("ncap","\10819")
, ("ncaron","\328")
, ("ncedil","\326")
, ("ncong","\8775")
, ("ncongdot","\10861\824")
, ("ncup","\10818")
, ("ncy","\1085")
, ("ndash","\8211")
, ("ne","\8800")
, ("neArr","\8663")
, ("nearhk","\10532")
, ("nearr","\8599")
, ("nearrow","\8599")
, ("nedot","\8784\824")
, ("nequiv","\8802")
, ("nesear","\10536")
, ("nesim","\8770\824")
, ("nexist","\8708")
, ("nexists","\8708")
, ("nfr","\120107")
, ("ngE","\8807\824")
, ("nge","\8817")
, ("ngeq","\8817")
, ("ngeqq","\8807\824")
, ("ngeqslant","\10878\824")
, ("nges","\10878\824")
, ("ngsim","\8821")
, ("ngt","\8815")
, ("ngtr","\8815")
, ("nhArr","\8654")
, ("nharr","\8622")
, ("nhpar","\10994")
, ("ni","\8715")
, ("nis","\8956")
, ("nisd","\8954")
, ("niv","\8715")
, ("njcy","\1114")
, ("nlArr","\8653")
, ("nlE","\8806\824")
, ("nlarr","\8602")
, ("nldr","\8229")
, ("nle","\8816")
, ("nleftarrow","\8602")
, ("nleftrightarrow","\8622")
, ("nleq","\8816")
, ("nleqq","\8806\824")
, ("nleqslant","\10877\824")
, ("nles","\10877\824")
, ("nless","\8814")
, ("nlsim","\8820")
, ("nlt","\8814")
, ("nltri","\8938")
, ("nltrie","\8940")
, ("nmid","\8740")
, ("nopf","\120159")
, ("not","\172")
, ("notin","\8713")
, ("notinE","\8953\824")
, ("notindot","\8949\824")
, ("notinva","\8713")
, ("notinvb","\8951")
, ("notinvc","\8950")
, ("notni","\8716")
, ("notniva","\8716")
, ("notnivb","\8958")
, ("notnivc","\8957")
, ("npar","\8742")
, ("nparallel","\8742")
, ("nparsl","\11005\8421")
, ("npart","\8706\824")
, ("npolint","\10772")
, ("npr","\8832")
, ("nprcue","\8928")
, ("npre","\10927\824")
, ("nprec","\8832")
, ("npreceq","\10927\824")
, ("nrArr","\8655")
, ("nrarr","\8603")
, ("nrarrc","\10547\824")
, ("nrarrw","\8605\824")
, ("nrightarrow","\8603")
, ("nrtri","\8939")
, ("nrtrie","\8941")
, ("nsc","\8833")
, ("nsccue","\8929")
, ("nsce","\10928\824")
, ("nscr","\120003")
, ("nshortmid","\8740")
, ("nshortparallel","\8742")
, ("nsim","\8769")
, ("nsime","\8772")
, ("nsimeq","\8772")
, ("nsmid","\8740")
, ("nspar","\8742")
, ("nsqsube","\8930")
, ("nsqsupe","\8931")
, ("nsub","\8836")
, ("nsubE","\10949\824")
, ("nsube","\8840")
, ("nsubset","\8834\8402")
, ("nsubseteq","\8840")
, ("nsubseteqq","\10949\824")
, ("nsucc","\8833")
, ("nsucceq","\10928\824")
, ("nsup","\8837")
, ("nsupE","\10950\824")
, ("nsupe","\8841")
, ("nsupset","\8835\8402")
, ("nsupseteq","\8841")
, ("nsupseteqq","\10950\824")
, ("ntgl","\8825")
, ("ntilde","\241")
, ("ntlg","\8824")
, ("ntriangleleft","\8938")
, ("ntrianglelefteq","\8940")
, ("ntriangleright","\8939")
, ("ntrianglerighteq","\8941")
, ("nu","\957")
, ("num","#")
, ("numero","\8470")
, ("numsp","\8199")
, ("nvDash","\8877")
, ("nvHarr","\10500")
, ("nvap","\8781\8402")
, ("nvdash","\8876")
, ("nvge","\8805\8402")
, ("nvgt",">\8402")
, ("nvinfin","\10718")
, ("nvlArr","\10498")
, ("nvle","\8804\8402")
, ("nvlt","<\8402")
, ("nvltrie","\8884\8402")
, ("nvrArr","\10499")
, ("nvrtrie","\8885\8402")
, ("nvsim","\8764\8402")
, ("nwArr","\8662")
, ("nwarhk","\10531")
, ("nwarr","\8598")
, ("nwarrow","\8598")
, ("nwnear","\10535")
, ("oS","\9416")
, ("oacute","\243")
, ("oast","\8859")
, ("ocir","\8858")
, ("ocirc","\244")
, ("ocy","\1086")
, ("odash","\8861")
, ("odblac","\337")
, ("odiv","\10808")
, ("odot","\8857")
, ("odsold","\10684")
, ("oelig","\339")
, ("ofcir","\10687")
, ("ofr","\120108")
, ("ogon","\731")
, ("ograve","\242")
, ("ogt","\10689")
, ("ohbar","\10677")
, ("ohm","\937")
, ("oint","\8750")
, ("olarr","\8634")
, ("olcir","\10686")
, ("olcross","\10683")
, ("oline","\8254")
, ("olt","\10688")
, ("omacr","\333")
, ("omega","\969")
, ("omicron","\959")
, ("omid","\10678")
, ("ominus","\8854")
, ("oopf","\120160")
, ("opar","\10679")
, ("operp","\10681")
, ("oplus","\8853")
, ("or","\8744")
, ("orarr","\8635")
, ("ord","\10845")
, ("order","\8500")
, ("orderof","\8500")
, ("ordf","\170")
, ("ordm","\186")
, ("origof","\8886")
, ("oror","\10838")
, ("orslope","\10839")
, ("orv","\10843")
, ("oscr","\8500")
, ("oslash","\248")
, ("osol","\8856")
, ("otilde","\245")
, ("otimes","\8855")
, ("otimesas","\10806")
, ("ouml","\246")
, ("ovbar","\9021")
, ("par","\8741")
, ("para","\182")
, ("parallel","\8741")
, ("parsim","\10995")
, ("parsl","\11005")
, ("part","\8706")
, ("pcy","\1087")
, ("percnt","%")
, ("period",".")
, ("permil","\8240")
, ("perp","\8869")
, ("pertenk","\8241")
, ("pfr","\120109")
, ("phi","\966")
, ("phiv","\981")
, ("phmmat","\8499")
, ("phone","\9742")
, ("pi","\960")
, ("pitchfork","\8916")
, ("piv","\982")
, ("planck","\8463")
, ("planckh","\8462")
, ("plankv","\8463")
, ("plus","+")
, ("plusacir","\10787")
, ("plusb","\8862")
, ("pluscir","\10786")
, ("plusdo","\8724")
, ("plusdu","\10789")
, ("pluse","\10866")
, ("plusmn","\177")
, ("plussim","\10790")
, ("plustwo","\10791")
, ("pm","\177")
, ("pointint","\10773")
, ("popf","\120161")
, ("pound","\163")
, ("pr","\8826")
, ("prE","\10931")
, ("prap","\10935")
, ("prcue","\8828")
, ("pre","\10927")
, ("prec","\8826")
, ("precapprox","\10935")
, ("preccurlyeq","\8828")
, ("preceq","\10927")
, ("precnapprox","\10937")
, ("precneqq","\10933")
, ("precnsim","\8936")
, ("precsim","\8830")
, ("prime","\8242")
, ("primes","\8473")
, ("prnE","\10933")
, ("prnap","\10937")
, ("prnsim","\8936")
, ("prod","\8719")
, ("profalar","\9006")
, ("profline","\8978")
, ("profsurf","\8979")
, ("prop","\8733")
, ("propto","\8733")
, ("prsim","\8830")
, ("prurel","\8880")
, ("pscr","\120005")
, ("psi","\968")
, ("puncsp","\8200")
, ("qfr","\120110")
, ("qint","\10764")
, ("qopf","\120162")
, ("qprime","\8279")
, ("qscr","\120006")
, ("quaternions","\8461")
, ("quatint","\10774")
, ("quest","?")
, ("questeq","\8799")
, ("quot","\"")
, ("rAarr","\8667")
, ("rArr","\8658")
, ("rAtail","\10524")
, ("rBarr","\10511")
, ("rHar","\10596")
, ("race","\8765\817")
, ("racute","\341")
, ("radic","\8730")
, ("raemptyv","\10675")
, ("rang","\10217")
, ("rangd","\10642")
, ("range","\10661")
, ("rangle","\10217")
, ("raquo","\187")
, ("rarr","\8594")
, ("rarrap","\10613")
, ("rarrb","\8677")
, ("rarrbfs","\10528")
, ("rarrc","\10547")
, ("rarrfs","\10526")
, ("rarrhk","\8618")
, ("rarrlp","\8620")
, ("rarrpl","\10565")
, ("rarrsim","\10612")
, ("rarrtl","\8611")
, ("rarrw","\8605")
, ("ratail","\10522")
, ("ratio","\8758")
, ("rationals","\8474")
, ("rbarr","\10509")
, ("rbbrk","\10099")
, ("rbrace","}")
, ("rbrack","]")
, ("rbrke","\10636")
, ("rbrksld","\10638")
, ("rbrkslu","\10640")
, ("rcaron","\345")
, ("rcedil","\343")
, ("rceil","\8969")
, ("rcub","}")
, ("rcy","\1088")
, ("rdca","\10551")
, ("rdldhar","\10601")
, ("rdquo","\8221")
, ("rdquor","\8221")
, ("rdsh","\8627")
, ("real","\8476")
, ("realine","\8475")
, ("realpart","\8476")
, ("reals","\8477")
, ("rect","\9645")
, ("reg","\174")
, ("rfisht","\10621")
, ("rfloor","\8971")
, ("rfr","\120111")
, ("rhard","\8641")
, ("rharu","\8640")
, ("rharul","\10604")
, ("rho","\961")
, ("rhov","\1009")
, ("rightarrow","\8594")
, ("rightarrowtail","\8611")
, ("rightharpoondown","\8641")
, ("rightharpoonup","\8640")
, ("rightleftarrows","\8644")
, ("rightleftharpoons","\8652")
, ("rightrightarrows","\8649")
, ("rightsquigarrow","\8605")
, ("rightthreetimes","\8908")
, ("ring","\730")
, ("risingdotseq","\8787")
, ("rlarr","\8644")
, ("rlhar","\8652")
, ("rlm","\8207")
, ("rmoust","\9137")
, ("rmoustache","\9137")
, ("rnmid","\10990")
, ("roang","\10221")
, ("roarr","\8702")
, ("robrk","\10215")
, ("ropar","\10630")
, ("ropf","\120163")
, ("roplus","\10798")
, ("rotimes","\10805")
, ("rpar",")")
, ("rpargt","\10644")
, ("rppolint","\10770")
, ("rrarr","\8649")
, ("rsaquo","\8250")
, ("rscr","\120007")
, ("rsh","\8625")
, ("rsqb","]")
, ("rsquo","\8217")
, ("rsquor","\8217")
, ("rthree","\8908")
, ("rtimes","\8906")
, ("rtri","\9657")
, ("rtrie","\8885")
, ("rtrif","\9656")
, ("rtriltri","\10702")
, ("ruluhar","\10600")
, ("rx","\8478")
, ("sacute","\347")
, ("sbquo","\8218")
, ("sc","\8827")
, ("scE","\10932")
, ("scap","\10936")
, ("scaron","\353")
, ("sccue","\8829")
, ("sce","\10928")
, ("scedil","\351")
, ("scirc","\349")
, ("scnE","\10934")
, ("scnap","\10938")
, ("scnsim","\8937")
, ("scpolint","\10771")
, ("scsim","\8831")
, ("scy","\1089")
, ("sdot","\8901")
, ("sdotb","\8865")
, ("sdote","\10854")
, ("seArr","\8664")
, ("searhk","\10533")
, ("searr","\8600")
, ("searrow","\8600")
, ("sect","\167")
, ("semi",";")
, ("seswar","\10537")
, ("setminus","\8726")
, ("setmn","\8726")
, ("sext","\10038")
, ("sfr","\120112")
, ("sfrown","\8994")
, ("sharp","\9839")
, ("shchcy","\1097")
, ("shcy","\1096")
, ("shortmid","\8739")
, ("shortparallel","\8741")
, ("shy","\173")
, ("sigma","\963")
, ("sigmaf","\962")
, ("sigmav","\962")
, ("sim","\8764")
, ("simdot","\10858")
, ("sime","\8771")
, ("simeq","\8771")
, ("simg","\10910")
, ("simgE","\10912")
, ("siml","\10909")
, ("simlE","\10911")
, ("simne","\8774")
, ("simplus","\10788")
, ("simrarr","\10610")
, ("slarr","\8592")
, ("smallsetminus","\8726")
, ("smashp","\10803")
, ("smeparsl","\10724")
, ("smid","\8739")
, ("smile","\8995")
, ("smt","\10922")
, ("smte","\10924")
, ("smtes","\10924\65024")
, ("softcy","\1100")
, ("sol","/")
, ("solb","\10692")
, ("solbar","\9023")
, ("sopf","\120164")
, ("spades","\9824")
, ("spadesuit","\9824")
, ("spar","\8741")
, ("sqcap","\8851")
, ("sqcaps","\8851\65024")
, ("sqcup","\8852")
, ("sqcups","\8852\65024")
, ("sqsub","\8847")
, ("sqsube","\8849")
, ("sqsubset","\8847")
, ("sqsubseteq","\8849")
, ("sqsup","\8848")
, ("sqsupe","\8850")
, ("sqsupset","\8848")
, ("sqsupseteq","\8850")
, ("squ","\9633")
, ("square","\9633")
, ("squarf","\9642")
, ("squf","\9642")
, ("srarr","\8594")
, ("sscr","\120008")
, ("ssetmn","\8726")
, ("ssmile","\8995")
, ("sstarf","\8902")
, ("star","\9734")
, ("starf","\9733")
, ("straightepsilon","\1013")
, ("straightphi","\981")
, ("strns","\175")
, ("sub","\8834")
, ("subE","\10949")
, ("subdot","\10941")
, ("sube","\8838")
, ("subedot","\10947")
, ("submult","\10945")
, ("subnE","\10955")
, ("subne","\8842")
, ("subplus","\10943")
, ("subrarr","\10617")
, ("subset","\8834")
, ("subseteq","\8838")
, ("subseteqq","\10949")
, ("subsetneq","\8842")
, ("subsetneqq","\10955")
, ("subsim","\10951")
, ("subsub","\10965")
, ("subsup","\10963")
, ("succ","\8827")
, ("succapprox","\10936")
, ("succcurlyeq","\8829")
, ("succeq","\10928")
, ("succnapprox","\10938")
, ("succneqq","\10934")
, ("succnsim","\8937")
, ("succsim","\8831")
, ("sum","\8721")
, ("sung","\9834")
, ("sup","\8835")
, ("sup1","\185")
, ("sup2","\178")
, ("sup3","\179")
, ("supE","\10950")
, ("supdot","\10942")
, ("supdsub","\10968")
, ("supe","\8839")
, ("supedot","\10948")
, ("suphsol","\10185")
, ("suphsub","\10967")
, ("suplarr","\10619")
, ("supmult","\10946")
, ("supnE","\10956")
, ("supne","\8843")
, ("supplus","\10944")
, ("supset","\8835")
, ("supseteq","\8839")
, ("supseteqq","\10950")
, ("supsetneq","\8843")
, ("supsetneqq","\10956")
, ("supsim","\10952")
, ("supsub","\10964")
, ("supsup","\10966")
, ("swArr","\8665")
, ("swarhk","\10534")
, ("swarr","\8601")
, ("swarrow","\8601")
, ("swnwar","\10538")
, ("szlig","\223")
, ("target","\8982")
, ("tau","\964")
, ("tbrk","\9140")
, ("tcaron","\357")
, ("tcedil","\355")
, ("tcy","\1090")
, ("tdot"," \8411")
, ("telrec","\8981")
, ("tfr","\120113")
, ("there4","\8756")
, ("therefore","\8756")
, ("theta","\952")
, ("thetasym","\977")
, ("thetav","\977")
, ("thickapprox","\8776")
, ("thicksim","\8764")
, ("thinsp","\8201")
, ("thkap","\8776")
, ("thksim","\8764")
, ("thorn","\254")
, ("tilde","\732")
, ("times","\215")
, ("timesb","\8864")
, ("timesbar","\10801")
, ("timesd","\10800")
, ("tint","\8749")
, ("toea","\10536")
, ("top","\8868")
, ("topbot","\9014")
, ("topcir","\10993")
, ("topf","\120165")
, ("topfork","\10970")
, ("tosa","\10537")
, ("tprime","\8244")
, ("trade","\8482")
, ("triangle","\9653")
, ("triangledown","\9663")
, ("triangleleft","\9667")
, ("trianglelefteq","\8884")
, ("triangleq","\8796")
, ("triangleright","\9657")
, ("trianglerighteq","\8885")
, ("tridot","\9708")
, ("trie","\8796")
, ("triminus","\10810")
, ("triplus","\10809")
, ("trisb","\10701")
, ("tritime","\10811")
, ("trpezium","\9186")
, ("tscr","\120009")
, ("tscy","\1094")
, ("tshcy","\1115")
, ("tstrok","\359")
, ("twixt","\8812")
, ("twoheadleftarrow","\8606")
, ("twoheadrightarrow","\8608")
, ("uArr","\8657")
, ("uHar","\10595")
, ("uacute","\250")
, ("uarr","\8593")
, ("ubrcy","\1118")
, ("ubreve","\365")
, ("ucirc","\251")
, ("ucy","\1091")
, ("udarr","\8645")
, ("udblac","\369")
, ("udhar","\10606")
, ("ufisht","\10622")
, ("ufr","\120114")
, ("ugrave","\249")
, ("uharl","\8639")
, ("uharr","\8638")
, ("uhblk","\9600")
, ("ulcorn","\8988")
, ("ulcorner","\8988")
, ("ulcrop","\8975")
, ("ultri","\9720")
, ("umacr","\363")
, ("uml","\168")
, ("uogon","\371")
, ("uopf","\120166")
, ("uparrow","\8593")
, ("updownarrow","\8597")
, ("upharpoonleft","\8639")
, ("upharpoonright","\8638")
, ("uplus","\8846")
, ("upsi","\965")
, ("upsih","\978")
, ("upsilon","\965")
, ("upuparrows","\8648")
, ("urcorn","\8989")
, ("urcorner","\8989")
, ("urcrop","\8974")
, ("uring","\367")
, ("urtri","\9721")
, ("uscr","\120010")
, ("utdot","\8944")
, ("utilde","\361")
, ("utri","\9653")
, ("utrif","\9652")
, ("uuarr","\8648")
, ("uuml","\252")
, ("uwangle","\10663")
, ("vArr","\8661")
, ("vBar","\10984")
, ("vBarv","\10985")
, ("vDash","\8872")
, ("vangrt","\10652")
, ("varepsilon","\949")
, ("varkappa","\1008")
, ("varnothing","\8709")
, ("varphi","\981")
, ("varpi","\982")
, ("varpropto","\8733")
, ("varr","\8597")
, ("varrho","\1009")
, ("varsigma","\962")
, ("varsubsetneq","\8842\65024")
, ("varsubsetneqq","\10955\65024")
, ("varsupsetneq","\8843\65024")
, ("varsupsetneqq","\10956\65024")
, ("vartheta","\977")
, ("vartriangleleft","\8882")
, ("vartriangleright","\8883")
, ("vcy","\1074")
, ("vdash","\8866")
, ("vee","\8744")
, ("veebar","\8891")
, ("veeeq","\8794")
, ("vellip","\8942")
, ("verbar","|")
, ("vert","|")
, ("vfr","\120115")
, ("vltri","\8882")
, ("vnsub","\8834\8402")
, ("vnsup","\8835\8402")
, ("vopf","\120167")
, ("vprop","\8733")
, ("vrtri","\8883")
, ("vscr","\120011")
, ("vsubnE","\10955\65024")
, ("vsubne","\8842\65024")
, ("vsupnE","\10956\65024")
, ("vsupne","\8843\65024")
, ("vzigzag","\10650")
, ("wcirc","\373")
, ("wedbar","\10847")
, ("wedge","\8743")
, ("wedgeq","\8793")
, ("weierp","\8472")
, ("wfr","\120116")
, ("wopf","\120168")
, ("wp","\8472")
, ("wr","\8768")
, ("wreath","\8768")
, ("wscr","\120012")
, ("xcap","\8898")
, ("xcirc","\9711")
, ("xcup","\8899")
, ("xdtri","\9661")
, ("xfr","\120117")
, ("xhArr","\10234")
, ("xharr","\10231")
, ("xi","\958")
, ("xlArr","\10232")
, ("xlarr","\10229")
, ("xmap","\10236")
, ("xnis","\8955")
, ("xodot","\10752")
, ("xopf","\120169")
, ("xoplus","\10753")
, ("xotime","\10754")
, ("xrArr","\10233")
, ("xrarr","\10230")
, ("xscr","\120013")
, ("xsqcup","\10758")
, ("xuplus","\10756")
, ("xutri","\9651")
, ("xvee","\8897")
, ("xwedge","\8896")
, ("yacute","\253")
, ("yacy","\1103")
, ("ycirc","\375")
, ("ycy","\1099")
, ("yen","\165")
, ("yfr","\120118")
, ("yicy","\1111")
, ("yopf","\120170")
, ("yscr","\120014")
, ("yucy","\1102")
, ("yuml","\255")
, ("zacute","\378")
, ("zcaron","\382")
, ("zcy","\1079")
, ("zdot","\380")
, ("zeetrf","\8488")
, ("zeta","\950")
, ("zfr","\120119")
, ("zhcy","\1078")
, ("zigrarr","\8669")
, ("zopf","\120171")
, ("zscr","\120015")
, ("zwj","\8205")
, ("zwnj","\8204")]
| jgm/texmath | src/Text/TeXMath/Readers/MathML/EntityMap.hs | gpl-2.0 | 52,339 | 0 | 7 | 8,745 | 19,213 | 12,803 | 6,410 | 2,133 | 1 |
{- |
Module : $Header$
Description : utilitary functions used throughout the CMDL interface
Copyright : uni-bremen and DFKI
License : GPLv2 or higher, see LICENSE.txt
Maintainer : r.pascanu@jacobs-university.de
Stability : provisional
Portability : portable
CMDL.Utils contains different basic functions that are
used throughout the CMDL interface and could not be found in
Prelude
-}
module CMDL.Utils
( decomposeIntoGoals
, obtainNodeList
, createEdgeNames
, obtainEdgeList
, obtainGoalEdgeList
, finishedNames
, stripComments
, lastChar
, lastString
, safeTail
, fileFilter
, fileExtend
, prettyPrintErrList
, edgeContainsGoals
, isOpenConsEdge
, checkIntString
, delExtension
, checkPresenceProvers
, arrowLink
) where
import Data.List
import Data.Maybe
import Data.Char (isDigit)
import Data.Graph.Inductive.Graph (LNode, LEdge)
import System.Directory
import System.FilePath
import Static.DevGraph
import Static.DgUtils
import Common.Utils
-- a any version of function that supports IO
anyIO :: (a -> IO Bool) -> [a] -> IO Bool
anyIO fn ls = case ls of
[] -> return False
e : l -> do
result <- fn e
if result then return True else anyIO fn l
{- checks if provers in the prover list are availabe on
the current machine -}
checkPresenceProvers :: [String] -> IO [String]
checkPresenceProvers ls = case ls of
[] -> return []
s@"SPASS" : l -> do
path <- getEnvDef "PATH" ""
path2 <- getEnvDef "Path" ""
let lsPaths = map trim $ splitPaths path ++ splitPaths path2
completePath x = x </> s
result <- anyIO (doesFileExist . completePath)
lsPaths
if result then do
contd <- checkPresenceProvers l
return (s : contd)
else checkPresenceProvers l
x : l -> do
contd <- checkPresenceProvers l
return (x : contd)
{- removes the extension of the file find in the
name of the prompter ( it delets everything
after the last . and assumes a prompter length of 2 ) -}
delExtension :: String -> String
delExtension str = let rstr = reverse str in
reverse $ safeTail $ case dropWhile (/= '.') rstr of
"" -> safeTail rstr
dstr -> dstr
-- | Checks if a string represents a int or not
checkIntString :: String -> Bool
checkIntString = not . any (not . isDigit)
localArr :: String
localArr = "..>"
globalArr :: String
globalArr = "->"
padBlanks :: String -> String
padBlanks s = ' ' : s ++ " "
-- | Generates a string representing the type of link
arrowLink :: DGLinkLab -> String
arrowLink edgLab = padBlanks $ if isLocalEdge $ dgl_type edgLab
then localArr
else globalArr
-- | Checks if the string starts with an arrow
checkArrowLink :: String -> Maybe (String, String)
checkArrowLink str = case find snd
$ map (\ s -> (s, isPrefixOf s str)) [localArr, globalArr] of
Nothing -> Nothing
Just (a, _) -> Just (padBlanks a, drop (length a) str)
{- | Given a string inserts spaces before and after an
arrow -}
spacesAroundArrows :: String -> String
spacesAroundArrows s = case s of
[] -> []
hd : tl -> case checkArrowLink $ trimLeft s of
Just (arr, rs) -> arr ++ spacesAroundArrows rs
Nothing -> hd : spacesAroundArrows tl
{- | Given a string the function decomposes it into 4 lists,
one for node goals, the other for edges, the third for
numbered edges and the last for names that could not be
processed due to errors -}
decomposeIntoGoals :: String -> ([String], [String], [String], [String])
decomposeIntoGoals input = let
{- the new input where words and arrows are separated
by exactly one space -}
nwInput = words $ spacesAroundArrows input
{- function to parse the input and decompose it into
the three goal list -}
parse info nbOfArrows word sw listNode listEdge listNbEdge listError =
case info of
[] -> case nbOfArrows :: Integer of
0 -> (word : listNode, listEdge, listNbEdge, listError)
1 -> (listNode, word : listEdge, listNbEdge, listError)
2 -> (listNode, listEdge, word : listNbEdge, listError)
_ -> (listNode, listEdge, listNbEdge, word : listError)
x : l -> case checkArrowLink x of
Just (arr, _) ->
case word of
[] -> (listNode, listEdge, listNbEdge, word : listError)
_ -> parse l (nbOfArrows + 1) (word ++ arr) True
listNode listEdge listNbEdge listError
Nothing ->
if sw
then parse l nbOfArrows (word ++ x) False
listNode listEdge listNbEdge listError
else
case nbOfArrows of
0 -> parse l 0 x False
(word : listNode) listEdge listNbEdge listError
1 -> parse l 0 x False
listNode (word : listEdge) listNbEdge listError
2 -> parse l 0 x False
listNode listEdge (word : listNbEdge) listError
_ -> parse l 0 x False
listNode listEdge listNbEdge (word : listError)
(ns, es, les, errs) = parse nwInput 0 [] True [] [] [] []
in (reverse ns, reverse es, reverse les, reverse errs)
{- | mapAndSplit maps a function to a list. If the function can not
be applied to an element it is stored in a different list for
producing error message later on -}
mapAndSplit :: (a -> Maybe b) -> [a] -> ([a], [b])
mapAndSplit fn ls =
let ps = zip ls $ map fn ls
(oks, errs) = partition (isJust . snd) ps
in (map fst errs, mapMaybe snd oks)
{- | concatMapAndSplit is similar to mapAndSplit, just that it behaves
in a similar manner to concatMap (i.e. sums up lists produced by
the function -}
concatMapAndSplit :: (a -> [b]) -> [a] -> ([a], [b])
concatMapAndSplit fn ls =
let ps = zip ls $ map fn ls
(errs, oks) = partition (null . snd) ps
in (map fst errs, concatMap snd oks)
{- | Given a list of node names and the list of all nodes
the function returns all the nodes that have their name
in the name list -}
obtainNodeList :: [String] -> [LNode DGNodeLab] -> ([String], [LNode DGNodeLab])
obtainNodeList lN allNodes = mapAndSplit
(\ x -> find (\ (_, label) -> getDGNodeName label == x) allNodes) lN
-- | Given an edge decides if it contains goals or not
edgeContainsGoals :: LEdge DGLinkLab -> Bool
edgeContainsGoals (_, _, l) = case thmLinkStatus $ dgl_type l of
Just LeftOpen -> True
_ -> False
-- | Given an edge: does it contain an open conservativity goal or not
isOpenConsEdge :: LEdge DGLinkLab -> Bool
isOpenConsEdge (_, _, l) = hasOpenConsStatus False $ getEdgeConsStatus l
{- | Given a list of edges and the complete list of all
edges computes not only the names of edges but also the
numbered name of edges -}
createEdgeNames :: [LNode DGNodeLab] -> [LEdge DGLinkLab]
-> [(String, LEdge DGLinkLab)]
createEdgeNames lsN lsE = let
-- function that returns the name of a node given its number
nameOf x ls = case lookup x ls of
Nothing -> "Unknown node"
Just nlab -> getDGNodeName nlab
ordFn (x1, x2, _) (y1, y2, _) = compare (x1, x2) (y1, y2)
-- sorted and grouped list of edges
edgs = groupBy ( \ x y -> ordFn x y == EQ) $ sortBy ordFn lsE
in concatMap (\ l -> case l of
[el@(x, y, edgLab)] -> [(nameOf x lsN ++
arrowLink edgLab ++
nameOf y lsN, el)]
_ -> map (\ el@(x, y, edgLab) ->
(nameOf x lsN ++
arrowLink edgLab ++
showEdgeId (dgl_id edgLab)
++ arrowLink edgLab
++ nameOf y lsN, el)) l) edgs
{- | Given a list of edge names and numbered edge names
and the list of all nodes and edges the function
identifies the edges that appear in the name lists -}
obtainEdgeList :: [String] -> [String] -> [LNode DGNodeLab]
-> [LEdge DGLinkLab] -> ([String], [LEdge DGLinkLab])
obtainEdgeList lsEdge lsNbEdge allNodes allEdges = let
{- function that searches through a list of nodes to
find the node number for a given name. -}
getNodeNb s ls =
case find ( \ (_, label) ->
getDGNodeName label == s) ls of
Nothing -> Nothing
Just (nb, _) -> Just nb
-- compute the list of all edges from source node to target
l1 = concatMapAndSplit
(\ nme -> case words nme of
[src, _, tar] -> let
node1 = getNodeNb src allNodes
node2 = getNodeNb tar allNodes
in case node1 of
Nothing -> []
Just x ->
case node2 of
Nothing -> []
Just y ->
filter (\ (x1, y1, _) -> x == x1 && y == y1) allEdges
_ -> error "CMDL.Utils.obtainEdgeList1"
) lsEdge
-- compute the list of all numbered edges
l2 = mapAndSplit
(\ nme -> case words nme of
[src, _, numb, _, tar] -> let
node1 = getNodeNb src allNodes
node2 = getNodeNb tar allNodes
mnb = readMaybe numb
in case node1 of
Nothing -> Nothing
Just x -> case node2 of
Nothing -> Nothing
Just y -> case mnb of
Nothing -> Nothing
Just nb -> let
ls = filter (\ (x1, y1, elab) -> x == x1 && y == y1 &&
dgl_id elab == EdgeId nb) allEdges
in case ls of
[] -> Nothing
els : _ -> Just els
_ -> error "CMDL.Utils.obtainEdgeList2") lsNbEdge
in (fst l1 ++ fst l2, snd l1 ++ snd l2)
{- | Giben a listof edgenamesand numbered edge names and
the list of all nodes and edges the function identifies
the edges that appearin the name list and are also goals -}
obtainGoalEdgeList :: [String] -> [String] -> [LNode DGNodeLab]
-> [LEdge DGLinkLab] -> ([String], [LEdge DGLinkLab])
obtainGoalEdgeList ls1 ls2 ls3 ls4 =
let (l1, l2) = obtainEdgeList ls1 ls2 ls3 ls4
in (l1, filter edgeContainsGoals l2)
{- | Function that given a string removes comments contained
in the string -}
stripComments :: String -> String
stripComments input =
let fn ls = case ls of
'#' : _ -> []
'%' : ll ->
case ll of
'%' : _ -> []
'{' : _ -> []
_ -> '%' : fn ll
[] -> []
l : ll -> l : fn ll
in trim $ fn input
-- | check if edges are to be completed in the presence of nodes
finishedNames :: [String] -> String -> ([String], String)
finishedNames ns i =
let e@(fs, r) = fNames ns i in
if not (null r) && any (isPrefixOf r) [localArr, globalArr] then
case reverse fs of
lt : ei : ar : sr : fr | elem ar [localArr, globalArr]
-> (reverse fr, unwords [sr, ar, ei, lt, r])
lt : fr -> (reverse fr, unwords [lt, r])
_ -> e
else e
fNames :: [String] -> String -> ([String], String)
fNames ns input = let i = trimLeft input in
case filter (isJust . snd) $ zip ns
$ map ((`stripPrefix` i) . (++ " ")) ns of
(n, Just r) : _ -> let (fs, s) = fNames ns r in (n : fs, s)
_ -> ([], i)
{- | Given a list of files and folders the function filters
only directory names and files ending in extenstion
.casl or .het -}
fileFilter :: String -> [String] -> [String] -> IO [String]
fileFilter lPath ls cons = case ls of
[] -> return cons
x : l -> do
-- check if current element is a directory
b <- doesDirectoryExist (lPath </> x)
fileFilter lPath l $ if b
-- if it is,then add "/" to indicate is a folder
then addTrailingPathSeparator x : cons
{- if it is not a folder then it must be a file
so check the extension -}
else if elem (takeExtensions x) [".casl", ".het" ]
then x : cons else cons
{- | Given a list of files and folders the function expands
the list adding the content of all folders in the list -}
fileExtend :: String -> [String] -> [String] -> IO [String]
fileExtend lPath ls cons = case ls of
[] -> return cons
x : l -> do
-- check if current element is a directory
let lPathx = lPath </> x
b <- doesDirectoryExist lPathx
if b then
-- if it is a folder add its content
do ll <- getDirectoryContents lPathx
nll <- fileFilter lPathx ll []
let nll' = map (x </>) nll
fileExtend lPath l (nll' ++ cons)
-- if it is not then leave the file alone
else fileExtend lPath l (x : cons)
{- | The function behaves exactly as tail just that
in the case of empty list returns an empty list
instead of an error -}
safeTail :: [a] -> [a]
safeTail = drop 1
safeLast :: a -> [a] -> a
safeLast d l = if null l then d else last l
{- | The function behaves exactly like last just that
in case of an empty list returns the space
character (it works only for lists of chars) -}
lastChar :: String -> Char
lastChar = safeLast ' '
{- | The function behaves exactly like last just that
in case of an empty list returns the empty string
(it is meant only for list of strings) -}
lastString :: [String] -> String
lastString = safeLast ""
-- | The function nicely outputs a list of errors
prettyPrintErrList :: [String] -> String
prettyPrintErrList = intercalate "\n"
. map (\ x -> "Input " ++ x ++ " could not be processed")
| nevrenato/HetsAlloy | CMDL/Utils.hs | gpl-2.0 | 14,171 | 113 | 31 | 4,708 | 3,636 | 1,940 | 1,696 | 255 | 11 |
{- |
Module : $Header$
Copyright : (c) T.Mossakowski, W.Herding, C.Maeder, Uni Bremen 2004-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : provisional
Portability : portable
Abstract syntax for hybrid logic extension of CASL
Only the added syntax is specified
-}
module Hybrid.AS_Hybrid where
import Common.Id
import Common.AS_Annotation
import CASL.AS_Basic_CASL
-- DrIFT command
{-! global: GetRange !-}
type H_BASIC_SPEC = BASIC_SPEC H_BASIC_ITEM H_SIG_ITEM H_FORMULA
type AnHybFORM = Annoted (FORMULA H_FORMULA)
data H_BASIC_ITEM = Simple_mod_decl [Annoted SIMPLE_ID] [AnHybFORM] Range
| Term_mod_decl [Annoted SORT] [AnHybFORM] Range
| Simple_nom_decl [Annoted SIMPLE_ID] [AnHybFORM] Range
deriving Show
data RIGOR = Rigid | Flexible deriving Show
data H_SIG_ITEM =
Rigid_op_items RIGOR [Annoted (OP_ITEM H_FORMULA)] Range
-- pos: op, semi colons
| Rigid_pred_items RIGOR [Annoted (PRED_ITEM H_FORMULA)] Range
-- pos: pred, semi colons
deriving Show
data MODALITY = Simple_mod SIMPLE_ID | Term_mod (TERM H_FORMULA)
deriving (Eq, Ord, Show)
data NOMINAL = Simple_nom SIMPLE_ID
deriving (Eq, Ord, Show)
data H_FORMULA = At NOMINAL (FORMULA H_FORMULA) Range
| BoxOrDiamond Bool MODALITY (FORMULA H_FORMULA) Range
| Here NOMINAL Range
| Univ NOMINAL (FORMULA H_FORMULA) Range
| Exist NOMINAL (FORMULA H_FORMULA) Range
deriving (Eq, Ord, Show)
| nevrenato/HetsAlloy | Hybrid/AS_Hybrid.der.hs | gpl-2.0 | 1,651 | 0 | 10 | 441 | 324 | 180 | 144 | 25 | 0 |
{-# OPTIONS -fno-warn-unused-do-bind #-}
{-# LANGUAGE GeneralizedNewtypeDeriving
, TupleSections
, NamedFieldPuns #-}
module Testing.QuickGen.ExpGen
( ExpGen
, EGState
, generate
, match
) where
import Control.Applicative
import Control.Monad.State
import Data.Char (chr, ord)
import qualified Data.Map as M
import Data.Maybe (catMaybes, listToMaybe)
import System.Random
import Testing.QuickGen.Types
type NextLambda = Nat
type NextType = Nat
-- TODO: Make this a data type and derive lenses instead of using i.e.
-- _1 or pattern matching and the whole state when using get.
data EGState = S { nextLambda :: NextLambda
, nextType :: NextType
, contexts :: [Context]
, stdGen :: StdGen
, guesses :: Substitution
, classEnv :: ClassEnv
}
newtype ExpGen a = EG { unEG :: State EGState a }
deriving (Functor, Monad, Applicative, MonadState EGState)
generate :: Language -> Type -> Seed -> Maybe (Exp, Type)
generate lang t seed = (, applys guesses t) <$> e
where
(e, S { guesses }) = runEG seed lang $ do
t' <- bindForall <$> uniqueTypes t
generate' t'
generate' :: Type -> ExpGen (Maybe Exp)
generate' (Type qs cxt (FunT (t:ts))) = do
let -- TODO: clean up qs and cxt?
ts' = map (Type qs cxt) ts
t' = Type qs cxt t
(ns', ret) <- localLambda ts' (generate' t')
return (LamE (reverse ns') <$> ret)
generate' t = replicateM 3 p >>= return . listToMaybe . catMaybes
where
p = do
m <- randomMatching t
case m of
Nothing -> return Nothing
Just (i, (n, Type qs cxt st), s) -> do
S { contexts, guesses } <- get
let u' = maybe (error "should not happen") id (guesses `unionSubst` s)
modify (\s -> s { guesses = u' })
decUses i
case st of
FunT (_:ts) -> do
let go [] args = return . Just $ foldl AppE (ConE n) args
go (t':ts') args = do
ret <- generate' (Type qs cxt t')
case ret of
Nothing -> do
modify (\s -> s { contexts = contexts
, guesses = guesses })
return Nothing
Just a -> go ts' (a:args)
go ts []
_ -> return (Just (ConE n))
randomMatching :: Type -> ExpGen (Maybe (Id, Constructor, Substitution))
randomMatching goalType = do
guesses <- getGuesses
let gt = applys guesses goalType
f i (mu, (n, t)) acc
-- If number of uses is a Just and less than 1 then
-- discard this constructor. TODO: maybe remove
-- constructor from the context instead when decreasing
-- uses?
| maybe False (< 1) mu = acc
| otherwise = do
t' <- uniqueTypes (applys guesses t)
case runStateT (match gt t') emptySubst of
Just (newT, s) -> (:) <$> pure (i, (n, newT), s) <*> acc
Nothing -> acc
ctxs <- getContexts
matches <- fmap concat . forM ctxs $ foldrContext f (return [])
case matches of
[] -> return Nothing
_ -> Just . (matches !!) <$> getRandomR (0, length matches - 1)
-- | Given a type replaces all `Forall' bound variables in that type
-- with unique type variables. Updates the EGState with the next free
-- type variable id.
uniqueTypes :: Type -> ExpGen Type
uniqueTypes t@(Type vs _ _) = do
td <- getNextType
let subst = toSubst [ (n, let v = (i, Forall) in ([v], VarT v))
| (i, (n, Forall)) <- zip [td..] vs
]
modify (\s -> s { nextType = sizeSubst subst + (nextType s) })
return (apply subst t)
runEG :: Seed -> Language -> ExpGen a -> (a, EGState)
runEG seed (L env cs) g = runState g' (S 0 0 [] gen emptySubst env)
where
g' = unEG $ pushContext cs >> g
gen = snd . next . mkStdGen $ seed
-- | Pushes a list of constructors to the context stack. Returns the
-- new depth and the number of constructors added.
pushContext :: [Constructor] -> ExpGen (Depth, Int)
pushContext cs = do
S { nextLambda } <- get
let uses = 7 -- FIXME: arbitrarily chosen
getUses (_, t)
| isSimple t = Nothing
| otherwise = Just (max 1 (uses - numArgs t))
ctx = M.fromList [ (i, (getUses c, c))
| (i, c) <- zip [nextLambda..] cs
] :: Context
len = M.size ctx
nextLambda' = nextLambda + len
modify (\s -> s { nextLambda = nextLambda', contexts = ctx : contexts s})
return (nextLambda', len)
popContext :: ExpGen ()
popContext = modify (\s -> s { contexts = tail (contexts s)})
getNextLambda :: ExpGen NextLambda
getNextLambda = nextLambda <$> get
getNextType :: ExpGen NextType
getNextType = nextType <$> get
getContexts :: ExpGen [Context]
getContexts = contexts <$> get
getGuesses :: ExpGen Substitution
getGuesses = guesses <$> get
getEnv :: ExpGen ClassEnv
getEnv = classEnv <$> get
getRandomR :: (Int, Int) -> ExpGen Int
getRandomR p = do
g <- stdGen <$> get
let (a, g') = randomR p g
modify (\s -> s { stdGen = g' } )
return a
localLambda :: [Type] -> ExpGen a -> ExpGen ([Name], a)
localLambda ts eg = do
n <- getNextLambda
let cs = map constr (zip [n..] ts)
ns = map fst cs
pushContext cs
a <- eg
popContext
return (ns, a)
where
-- FIXME: might capture variable names
constr (i, t) = let (n, c) = i `divMod` 26
in (mkName ("_lam_" ++ chr (c + ord 'a') : '_' : show n), t)
modContext :: ([Context] -> [Context]) -> ExpGen ()
modContext f = modify (\s -> s { contexts = f (contexts s) })
decUses :: Id -> ExpGen ()
decUses i = modContext (findAndUpdate f i)
where
f a@(Nothing, _) = a
f (Just u, c)
| u <= 0 = error "decUses: The impossible happened!"
| otherwise = (Just (pred u), c)
findAndUpdate :: ((Uses, Constructor) -> (Uses, Constructor)) -> Id -> [Context] -> [Context]
findAndUpdate f i = go
where
f' _ a = Just (f a)
go [] = []
go (c:cs) = case M.updateLookupWithKey f' i c of
(Nothing, _) -> c : go cs
(Just _, c') -> c' : cs
match :: (Applicative m, Monad m) => Type -> Type -> StateT Substitution m Type
match t1@(Type ns1 _ _) t2 = do
s <- match' t1 t2
-- FIXME: I'm basically doing exactly what forallToUndecided does
-- here but for a Type instead of a SType. Need to generalize.
let t2'@(Type ns2 _ _) = applys s t2
subst = toSubst [ (n, let n' = (n, Undecided) in ([n'], VarT n'))
| (n, Forall) <- ns2
]
return (applys subst t2')
match' :: Monad m => Type -> Type -> StateT Substitution m Substitution
match' t1@(Type _ _ (FunT _)) _ = error $ "match: Unexpected function type " ++ show t1
match' t1 (Type ns cxt (FunT (t2 : _))) = match' t1 (Type ns cxt t2)
match' ta@(Type _ _ st1) tb@(Type _ _ st2) = go st1 st2
where
go :: Monad m => SType -> SType -> StateT Substitution m Substitution
go t1@(VarT (_, Forall)) t2 = error $ "t1 = " ++ show t1 ++ " | t2 = " ++ show t2
go t1 (VarT (n2, Forall)) = return (n2 |-> t1)
go t1@(VarT (n1, Undecided)) (VarT (n2, Undecided))
| n1 == n2 = return emptySubst
go t1 (VarT v@(n2, Undecided))
| v `elem` getVars t1 = fail "No match"
| otherwise = get >>= \s -> case lookupSubst n2 s of
Just (_, t2') -> go t1 t2'
_ -> do
let ret = (n2 |-> t1)
case unionSubst s ret of
Just s' -> put s'
Nothing -> error "ExpGen.match': The impossible happened!"
return emptySubst
go (VarT v@(n1, Undecided)) t2
| v `elem` (getVars t2) = fail "No match"
| otherwise = get >>= \s -> case lookupSubst n1 s of
Just (_, t1') -> go t1' t2
_ -> do
let t2' = forallToUndecided t2
case unionSubst s (n1 |-> t2') of
Just s' -> put s'
Nothing -> error "ExpGen.match': The impossible happened!"
return emptySubst
go (ListT t1) (ListT t2) = go t1 t2
go (ListT _) _ = noMatch
go _ (ListT _) = noMatch
go (ConT n1 as1) (ConT n2 as2)
| n1 /= n2 = noMatch
| otherwise = unionsSubst =<< zipWithM go as1 as2
go (ConT _ _) _ = noMatch
go _ (ConT _ _) = noMatch
go _ _ = error $ "match: Not matched " ++ show ta ++ " | " ++ show tb
noMatch :: Monad m => m a
noMatch = fail $ "Types don't match: " ++ show ta ++ " | " ++ show tb
-- TODO: Remove need for this by doing something smarter in
-- substitution.
applys :: Substitution -> Type -> Type
applys s t = t'
where
ts = iterate (apply s) t
t' = fst . head . dropWhile (uncurry (/=)) $ zip ts (tail ts)
| solarus/quickgen | src/Testing/QuickGen/ExpGen.hs | gpl-3.0 | 9,358 | 0 | 33 | 3,298 | 3,387 | 1,739 | 1,648 | 197 | 16 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE GADTs #-}
import Prelude hiding (pred)
import Data.List (intercalate, partition)
import Control.Monad.State
type Object = String
type Prop = String
data Gender where
Male :: Gender
Female :: Gender
Neutral :: Gender
Unknown :: Gender
deriving (Eq,Show)
data Number where
Singular :: Number
Plural :: Number
deriving (Eq,Show)
data Role where
Subject :: Role
Other :: Role
deriving (Eq,Show)
first :: (t2 -> t1) -> (t2, t) -> (t1, t)
first f (x,y) = (f x,y)
second :: forall t t1 t2. (t2 -> t1) -> (t, t2) -> (t, t1)
second f (x,y) = (x,f y)
data Descriptor = Descriptor {dGender :: Gender
,dNumber :: Number
,dRole :: Role} deriving Show
type ObjQuery = Descriptor -> Bool
type ObjEnv = [(Descriptor,NP)]
type NounEnv = [CN]
clearRole :: Env -> Env
clearRole Env{..} = Env{objEnv = map (first (\d -> d {dRole = Other})) objEnv,..}
type VPEnv = VP
-- Just remember the last VP; could be more fine-grained because we have "does", "is", "has" as placehodlers in English.
data Env = Env {vpEnv :: VPEnv
,vp2Env :: NP -> VP
,objEnv :: ObjEnv
,cnEnv :: NounEnv
,freshVars :: [String]}
-- deriving Show
allVars :: [String]
allVars = map (:[]) ['a'..'z'] ++ cycle (map (:[]) ['α'..'ω'])
type Disc a = State Env a
type Effect = Disc Row
-- Env -> (Prop, Env)
type Row = [(String,String)]
mkRec :: Row -> Prop
-- mkRec row = "[" ++ intercalate " ; " ++ map showField row ++ "]"
mkRec row = intercalate " × " (map showField row)
telescope :: String -> Row -> String
telescope implicationSymbol [f] = showField f ++ " " ++ implicationSymbol ++ " "
telescope implicationSymbol row = "(" ++ mkRec row ++ ") " ++ implicationSymbol ++ " "
-- this definition has the effect of confusing some people:
-- telescope implicationSymbol row = concat $ [showField f ++ " " ++ implicationSymbol ++ " " | f <- row]
-- but it is better because it clearly brings the right variables into scope.
showField :: (String, Prop) -> String
showField ("_",p) = p
showField (field,typ) = "(" ++ field ++ " : " ++ typ ++ ")"
mkPred :: String -> Object -> Prop
mkPred p x = p ++ "(" ++ x ++ ")"
mkRel2 :: String -> Object -> Object -> Prop
mkRel2 p x y = p ++ "(" ++ x ++ "," ++ y ++ ")"
assumedPred :: String -> Object -> Effect
assumedPred predName x = do
return (prop (mkPred predName x))
assumedVP :: VPEnv
assumedVP = assumedPred "assumedVP"
assumedCN :: CN
assumedCN = (assumedPred "assumedCN",Unknown,Singular)
assumedV2 :: NP -> VP
assumedV2 dobj subj = dobj Other $ \x -> return (prop (mkRel2 "assumedV2" subj x))
assumed :: Env
assumed = Env assumedVP assumedV2 [] [assumedCN] allVars
_TRUE :: Effect -> Prop
_TRUE x = mkRec $ evalState x assumed
_ENV :: Effect -> Env
_ENV x = execState x assumed
type S = Effect
type VP = Object -> Effect -- FIXME: attempt to change to Disc (Object -> Prop)
type CN = (Object -> Effect,Gender,Number)
type CN2 = Object -> CN
type NP = Role -> VP -> Effect
(!) :: NP -> VP -> Effect
np ! vp = do
x <- np Subject vp
modify clearRole -- Once the sentence is complete, accusative pronouns can refer to the subject. (see example9)
return x
instance Show VP where
show vp = "λω. " ++ mkRec (evalState (vp "ω") assumed)
instance Show NP where
show np = mkRec (evalState (np Other $ \x -> return [("_",x)]) assumed)
isNeutral :: Descriptor -> Bool
isNeutral = (== Neutral) . dGender
isMale :: Descriptor -> Bool
isMale = (== Male) . dGender
isFemale :: Descriptor -> Bool
isFemale = (== Female) . dGender
isSingular :: Descriptor -> Bool
isSingular = (== Singular) . dNumber
isPlural :: Descriptor -> Bool
isPlural = (== Plural) . dNumber
isNotSubject :: Descriptor -> Bool
isNotSubject = (/= Subject) . dRole
pushNP :: Descriptor -> NP -> Env -> Env
pushNP d obj Env{..} = Env{objEnv = (d,obj):objEnv,..}
pushVP :: VP -> Env -> Env
pushVP vp Env{..} = Env{vpEnv=vp,..}
pushV2 :: (NP -> VP) -> Env -> Env
pushV2 vp2 Env{..} = Env{vp2Env=vp2,..}
pushCN :: CN -> Env -> Env
pushCN cn Env{..} = Env{cnEnv=cn:cnEnv,..}
getCN :: Env -> CN
getCN Env{cnEnv=cn:_} = cn
getCN _ = (assumedPred "assumedCN",Unknown,Singular)
getNP' :: ObjQuery -> Env -> NP
getNP' _ Env{objEnv=[]} = \_ vp -> vp "assumedObj"
getNP' q Env{objEnv=((d,o):os),..} = if q d then o else getNP' q Env{objEnv=os,..}
getNP :: ObjQuery -> Disc NP
getNP q = gets (getNP' q)
-- Some debugging function
getNthNP :: Int -> Env -> NP
getNthNP _ Env{objEnv=[]} = \_ vp -> vp "assumedObj"
getNthNP 0 Env{objEnv=((_,o):_),..} = o
getNthNP n Env{objEnv=((d,o):os),..} = getNthNP (n-1) Env{objEnv=((d,o):os),..}
purePN :: Object -> Gender -> NP
purePN o dGender dRole vp = do
modify (pushNP (Descriptor{..} ) (purePN o dGender))
vp o
where dNumber = Singular
maryNP :: NP
maryNP = purePN "MARY" Female
johnNP :: NP
johnNP = purePN "JOHN" Male
billNP :: NP
billNP = purePN "BILL" Male
all' :: [a -> Bool] -> a -> Bool
all' fs x = all ($ x) fs
pron :: ObjQuery -> NP
pron q role vp = do
np <- getNP q
np role vp
sheNP :: NP
sheNP = pron (all' [isFemale, isSingular])
himNP :: NP
himNP = pron (all' [isMale, isSingular, isNotSubject])
heNP :: NP
heNP = pron (all' [isMale, isSingular])
himSelfNP :: NP
himSelfNP = heNP
theySingNP :: NP -- as in everyone owns their book
theySingNP = pron (isSingular)
themSingNP :: NP -- as in everyone owns their book
themSingNP = pron (all' [isSingular, isNotSubject])
itNP :: NP
itNP = pron (all' [isNeutral, isSingular])
-- nthNP :: Int -> Role -> VP -> Env -> (Prop, Env)
-- nthNP n = \role vp ρ -> (getNthNP n ρ) role vp ρ
theyPlNP :: NP
theyPlNP = pron isPlural
his :: CN2 -> NP
his cn2 role vp = heNP role $ \x -> the (cn2 x) Other vp
its :: CN2 -> NP
its cn2 role vp = itNP role $ \x -> the (cn2 x) Other vp
getFresh :: Disc String
getFresh = do
(x:_) <- gets freshVars
modify (\Env{freshVars=_:freshVars,..} -> Env{..})
return x
the :: CN -> NP
the (cn,gender,number) role vp = do
modify (pushNP (Descriptor gender number role) (the (cn,gender,number)))
v <- getFresh
p <- cn v
vp ("(THE " ++ v ++ ". " ++ mkRec p ++")")
-- FIXME: variable may escape its scope
prop :: Prop -> Row
prop x = [("_",x)]
(<==), (~~>) :: Effect -> Effect -> Effect
a <== b = do
a' <- a
b' <- b
let (props::Row,binders::Row) = partition (\(x,_) -> x == "_") a'
return (binders ++ prop (telescope "->" b' ++ mkRec props)) -- TODO: currify
imply :: Monad m => String -> m Row -> m Row -> m Row
imply implicationSymbol a b = do
a' <- a
b' <- b
return (prop (telescope implicationSymbol a' ++ mkRec b'))
(==>) :: Effect -> Effect -> Effect
(==>) = imply "->"
(-->) :: Prop -> Prop -> Prop
x --> y = x ++ " → " ++ y
(~~>) = imply "~>"
not' :: Effect -> Effect
not' a = do
x <- a
return (prop (mkPred "NOT" (mkRec x)))
(###) :: Effect -> Effect -> Effect
(###) = (∧)
(∧) :: Effect -> Effect -> Effect
(∧) = liftM2 (++)
pureVP :: (Object -> Prop) -> VP
pureVP v x = do
modify (pushVP (pureVP v))
return (prop (v x))
-- pushes itself in the env for reference
pureCN :: (Object -> Prop) -> Gender -> Number -> CN
pureCN cn gender number = (\x -> do
modify (pushCN (pureCN cn gender number))
return (prop (cn x))
,gender,number)
pureCN2 :: (Object -> Object -> Prop) -> Gender -> Number -> CN2
pureCN2 v gender number x = pureCN (v x) gender number
leavesVP :: VP
leavesVP = pureVP (mkPred "LEAVES")
isTiredVP :: VP
isTiredVP = pureVP (mkPred "IS_TIRED")
-- (* EXAMPLE:: john leaves if he is tired *)
example0 :: Prop
example0 = _TRUE ((johnNP ! leavesVP) <== (heNP ! isTiredVP))
{-> putStrLn example0
IS_TIRED(JOHN) -> LEAVES(JOHN)
-}
doesTooVP :: VP
doesTooVP x = do
vp <- gets vpEnv
vp x
-- (* EXAMPLE:: john leaves if mary does [too] *)
example1 :: Prop
example1 = _TRUE ((johnNP ! leavesVP) <== (maryNP ! doesTooVP))
{-> putStrLn example1
LEAVES(MARY) -> LEAVES(JOHN)
-}
_ADMIT_V :: Prop -> Object -> Prop
_ADMIT_V = mkRel2 "ADMIT"
admitVP :: Effect -> VP
admitVP p x = do
p' <- p
modify (pushVP (admitVP p))
return (prop (_ADMIT_V (mkRec p') x))
_PERSON :: Object -> Prop
_PERSON = mkPred "PERSON"
_FORALL :: String -> Prop -> Prop
_FORALL var f = "(Π("++var++" : i). " ++ f ++")"
pureObj :: Object -> NP
pureObj x _role vp = vp x
everyone :: NP
everyone = every (pureCN (mkPred "PERSON") Unknown Singular)
hide :: State s x -> State s x
hide a = do
s <- get
x <- a
put s
return x
unbound :: String
unbound = "<unbound>"
that :: CN -> VP -> CN
that (cn,gender,number) vp = (\x -> cn x ∧ vp x,gender,number)
every :: CN -> NP
every cn0@(cn,gender,Singular) role vp = do
x <- getFresh
p' <- hide $ do
modify (pushNP (Descriptor gender Singular Subject) (pureObj x))
cn x ==> vp x
_ <- cn unbound ==> vp unbound -- the things that we talk about in the CN/VP can be referred to anyway! (see example8).
-- If we end up with references to the unbound variable we have not felicitous sentences
-- Alternatively, we could demand that such variables re-introduce the quantification:
-- modify (pushNP (Descriptor gender Singular Subject) (every cn0 Other))
-- _ <- IT ! (\x -> cn x ==> vp x)
when (role == Subject) (modify (pushVP vp)) -- see example5c for why the guard is needed.
modify (pushNP (Descriptor Unknown Plural role) (every (cn0 `that` vp))) -- "e-type" referent
return (prop (_FORALL x (mkRec p')))
-- The referents pushed within the FORALL scope cannot escape to the top level
-- the bound variable is still referrable within the scope. It is pushed there
-- (with the appropriate descriptor)
some :: CN -> NP
some cn0@(cn,gender,Singular) role vp = do
x <- getFresh
modify (pushNP (Descriptor gender Singular Subject) (pureObj x))
p' <- cn x ∧ vp x
modify (pushNP (Descriptor Unknown Plural role) (the (cn0 `that` vp)))
return ((x,"i"):p')
few :: CN -> NP
few cn0@(cn,gender,Plural) role vp = do
x <- getFresh
p' <- hide $ do
modify (pushNP (Descriptor gender Singular Subject) (pureObj x)) -- Attn: the number is doubtful here; in the examples I've used singular pronouns.
cn x ~~> not' (vp x)
_ <- cn unbound ~~> vp unbound -- the things that we talk about in the CN/VP can be referred to anyway! (see example8)
modify (pushVP vp)
modify (pushNP (Descriptor Unknown Plural role) (every (cn0 `that` vp))) -- "e-type" referent
return (prop (_FORALL x (mkRec p')))
-- EXAMPLE:: everyone admits that they are tired
example2 :: Prop
example2 = _TRUE (everyone ! (admitVP (theySingNP ! isTiredVP)))
{-> putStrLn example2
(Π(a : i). PERSON(a) -> ADMIT(IS_TIRED(a),a))
-}
-- EXAMPLE:: everyone admits that they are tired. Mary does too
example3 :: Prop
example3 = _TRUE ((everyone ! (admitVP (theySingNP ! isTiredVP))) ### (maryNP ! doesTooVP))
{-> putStrLn example3
(Π(a : i). PERSON(a) -> ADMIT(IS_TIRED(a),a)) × ADMIT(IS_TIRED(MARY),MARY)
-}
married :: CN2
married = pureCN2 (mkRel2 "MARRIED") Unknown Singular
hisSpouseNP :: NP
hisSpouseNP = his married
lovesVP :: NP -> VP
lovesVP directObject subject = directObject Other $ \x -> pureVP (mkRel2 "LOVE" x) subject
-- (* EXAMPLE:: john loves his wife. Bill does too. *)
example4 :: Prop
example4 = _TRUE (johnNP ! (lovesVP hisSpouseNP) ### (billNP ! doesTooVP) )
-- Note what happens here.
-- lovesVP calls the directObject, ("hisSpouseNP"), which has the effect of resolving the anaphora.
-- Only then, 'pureVP' is called and the vp is pushed onto the environment
{-> putStrLn example4
LOVE((THE a. MARRIED(JOHN,a)),JOHN) × LOVE((THE a. MARRIED(JOHN,a)),BILL)
-}
pureV2' :: (Object -> Object -> Prop) -> NP -> VP
pureV2' v2 directObject subject = do
modify (pushV2 (pureV2' v2)) -- note that the direct object can in fact refer to the V2
directObject Other $ \x -> do
modify (pushVP (pureV2' v2 directObject))
return (prop (v2 x subject))
lovesVP' :: NP -> VP
lovesVP' = pureV2' (mkRel2 "LOVE")
-- (* EXAMPLE:: john leaves his wife. Bill does too. [second reading] *)
example5b :: Effect
example5b = johnNP ! (lovesVP' hisSpouseNP) ### (billNP ! doesTooVP)
-- With the above version of "love", the direct object is re-evaluated after it is being referred to.
{-> eval example5b
LOVE((THE a. MARRIED(JOHN,a)),JOHN) × LOVE((THE b. MARRIED(BILL,b)),BILL)
-}
lawyerCN = pureCN (mkPred "lawyer") Unknown Singular
auditorCN = pureCN (mkPred "auditor") Unknown Singular
reportCN = pureCN (mkPred "report") Neutral Singular
signV2 = pureV2' (mkRel2 "sign")
-- A lawyer signed every report, and so did an auditor.
example5c :: Effect
example5c = (aDet lawyerCN ! signV2 (every reportCN)) ### (aDet auditorCN ! doesTooVP)
{-
Analysis: in S := PN VP, the VP can refer to the subject. So the VP
must be evaluated in a context where the subject (which may be a
variable bound by a quantifier from the NP) is pushed in the
environment. Thus, the NP must take care of evaluating the VP. A
side-effect of this evaluation is that the VP itself is pushed in the
environment by the NP
Yet, as in the above example, we have (V2 NP). In this situation V2 is
not a proper noun phrase. If we push the VP argument in the NP we get
nonsense.
A possible solution would be to separate the updates and the lookup in
the environment:
type VP = (Env -> Env, Env -> Object -> Prop)
The first component woud be evaluated "once per lexical occurence",
while the second component would be evaluated "according to the
semantic context". Yet, if we were to be doing something like this, it
would preclude "strict" readings, as in example4.
-}
{-> eval example5c
(a : i) × lawyer(a) × (Π(b : i). report(b) -> sign(b,a)) × (c : i) × auditor(c) × (Π(d : i). report(d) -> sign(d,c))
-}
-- (* EXAMPLE:: john leaves his spouse. Mary does too. *)
example6 :: Prop
example6 = _TRUE (johnNP ! (lovesVP' hisSpouseNP) ### (maryNP ! doesTooVP) )
-- Because "his" is looking for a masculine object, the re-evaluation
-- in the "does too" points back to John anyway.
{-> putStrLn example6
LOVE((THE a. MARRIED(JOHN,a)),JOHN) × LOVE((THE b. MARRIED(JOHN,b)),MARY)
-}
congressmen :: CN
congressmen = pureCN (mkPred "CONGRESSMEN") Male Plural
example7 :: Prop
example7 = _TRUE ((few congressmen ! (lovesVP billNP)) ### (theyPlNP ! isTiredVP))
-- (* EXAMPLE:: Few congressmen love bill. They are tired. *)
{-> putStrLn example7
(∀ a. CONGRESSMAN(a) ~> NOT(LOVE(BILL,a))) × (∀ b. CONGRESSMAN(b) × LOVE(BILL,b) -> IS_TIRED(b))
-}
example8 :: Prop
example8 = _TRUE ((few congressmen ! (lovesVP billNP)) ### (heNP ! isTiredVP))
-- (* EXAMPLE:: Few congressmen love bill. He is tired. *) -- The e-type referent is plural.
{-> putStrLn example8
(∀ a. CONGRESSMAN(a) ~> NOT(LOVE(BILL,a))) × IS_TIRED(BILL)
-}
example9 :: Prop
example9 = _TRUE ((johnNP ! isTiredVP) ### (billNP ! (lovesVP himNP)))
-- John is tired. Bill loves him. -- (Bill loves John, not himself.)
{-> putStrLn example9
IS_TIRED(JOHN) × LOVE(JOHN,BILL)
-}
example9b :: Effect
example9b = (johnNP ! isTiredVP) ### (billNP ! (lovesVP himSelfNP))
-- John is tired. Bill loves himself.
{-> eval example9b
IS_TIRED(JOHN) × LOVE(BILL,BILL)
-}
man :: CN
man = pureCN (mkPred "MAN") Male Singular
men :: CN
men = pureCN (mkPred "MAN") Male Plural
beatV2 :: NP -> VP
beatV2 = pureV2' (mkRel2 "BEAT")
example10 :: Prop
example10 = _TRUE ((few (men `that` (lovesVP hisSpouseNP))) ! (beatV2 themSingNP))
-- (* EXAMPLE:: Few men that love their wife beat them.
{-> putStrLn example10
(Π(a : i). MAN(a) × LOVE((THE b. MARRIED(a,b)),a) ~> NOT(BEAT((THE c. MARRIED(a,c)),a)))
-}
donkey :: CN
donkey = pureCN (mkPred "DONKEY") Neutral Singular
own :: NP -> VP
own = pureV2' (mkRel2 "OWN")
aDet :: CN -> NP
aDet (cn,gender,number) role vp = do
x <- getFresh {- note that this isn't a quantifier, 'x' is not accessible in the CN nor the VP -}
p' <- (cn x ∧ vp x)
modify (pushNP (Descriptor gender number role) (pureObj x))
return ((x,"i"):p')
example11a :: Effect
example11a = (((aDet donkey) ! isTiredVP) ### (itNP ! leavesVP))
eval :: Effect -> IO ()
eval = putStrLn . _TRUE
-- A donkey is tired. It leaves.
{-> eval example11a
(a : i) × DONKEY(a) × IS_TIRED(a) × LEAVES(a)
-}
example11b :: Effect
example11b = (((aDet donkey) ! leavesVP) <== (itNP ! isTiredVP))
-- Some donkey leaves if it is tired.
{-> eval example11b
(a : i) × IS_TIRED(a) -> DONKEY(a) × LEAVES(a)
-}
example11c :: Effect
example11c = (aDet (man `that` own (aDet donkey)) ! (beatV2 itNP))
-- A man that owns a donkey beats it.
{-> eval example11c
(a : i) × (b : i) × MAN(a) × DONKEY(b) × OWN(b,a) × BEAT(b,a)
-}
example11d :: Effect
example11d = ((billNP ! (own (aDet donkey))) ### (heNP ! (beatV2 itNP)))
-- Bill owns a donkey. He beats it.
{-> eval example11d
(a : i) × DONKEY(a) × OWN(a,BILL) × BEAT(a,BILL)
-}
example11 :: Effect
example11 = (every (man `that` own (aDet donkey)) ! (beatV2 itNP))
-- Every man that owns a donkey beat it.
{-> eval example11
(Π(a : i). (MAN(a) × (b : i) × DONKEY(b) × OWN(b,a)) -> BEAT(b,a))
-}
example12 :: Effect
example12 = (aDet man ! own (aDet donkey)) ==> (heNP ! (beatV2 itNP))
-- If a man owns a donkey, he beats it.
{-> eval example12
((a : i) × MAN(a) × (b : i) × DONKEY(b) × OWN(b,a)) -> BEAT(b,a)
-}
example13 :: Effect
example13 = billNP ! (own (aDet (donkey `that` (\x -> heNP ! (beatV2 (pureObj x))))))
-- Bill owns a donkey that he beats.
{-> eval example13
(a : i) × DONKEY(a) × BEAT(a,BILL) × OWN(a,BILL)
-}
oneToo :: NP
oneToo role vp = do
cn <- gets getCN
aDet cn role vp
example14 :: Effect
example14 = (billNP ! own (aDet donkey)) ### (johnNP ! (own oneToo))
{-> eval example14
(a : i) × DONKEY(a) × OWN(a,BILL) × (b : i) × DONKEY(b) × OWN(b,JOHN)
-}
commitee :: CN
commitee = pureCN (mkPred "commitee") Neutral Singular
chairman :: CN
chairman = pureCN (mkPred "chairman") Male Singular
members :: CN2
members = pureCN2 (mkRel2 "members") Unknown Plural
has :: NP -> VP
has = pureV2' (mkRel2 "have")
isAppointedBy :: NP -> VP
isAppointedBy = pureV2' (mkRel2 "appoint")
example15 :: Effect
example15 = every commitee ! has (aDet chairman) ### (heNP ! (isAppointedBy (its members)))
-- every man owns a donkey. He beats it. #?!
-- every commitee has a chairman. He is appointed by its members. #?
-- every man own a donkey. It helps him. #?!
-- every man has a wife. She helps him. #?!
-- every commitee has a chairman. Its members appoint him. #?
{-> eval example15
(Π(a : i). commitee(a) -> (b : i) × chairman(b) × have(b,a)) × appoint((THE c. members(assumedObj,c)),b)
-}
example16 :: Effect
example16 = every man ! (beatV2 (every (donkey `that` (\x -> own heNP x))))
-- every man beats every donkey that he owns.
{-> eval example16
(Π(a : i). MAN(a) -> (Π(b : i). DONKEY(b) × OWN(a,b) -> BEAT(b,a)))
-}
doTooV2 :: NP -> VP
doTooV2 np subject = do
v2 <- gets vp2Env
v2 np subject
-- ACH (antecedent-contained ellipsis)
example17 :: Effect
example17 = maryNP ! beatV2 (every (donkey `that` (\x -> doTooV2 johnNP x)))
-- mary beat every donkey that john did
-- Mary read every book that John did
{-> eval example17
(Π(a : i). (DONKEY(a) × BEAT(JOHN,a)) -> BEAT(a,MARY))
-}
-- TODO: Mary read every book that John did
-- TODO: The man who gave his paycheck to his wife was wiser than the one who gave it to his mistress.
-- If a man is from Athens, he (always) likes ouzo.
-- If a drummer lives in an apartment complex, it is usually half empty.
| GU-CLASP/FraCoq | AnaphoraProto0/AnaMon.hs | gpl-3.0 | 19,793 | 1 | 18 | 4,064 | 5,832 | 3,132 | 2,700 | 370 | 2 |
module Equ.Exercise.Conf where
import Equ.Theories (Grouped)
import Equ.Proof hiding (Simple, Focus, Cases)
import qualified Data.Set as S (Set, empty)
import Control.Applicative ((<$>), (<*>))
import Data.Serialize (Serialize, get, getWord8, put, putWord8)
{- Auto: se hace automáticamente al parsear
Manual: no se infiere nada, se hace a mano.
Infer: se puede usar el botón “Inferir” en la caja del árbol.
-}
data TypeCheck = Auto
| Manual
| Infer
deriving (Enum, Eq)
instance Show TypeCheck where
show Auto = "Inferencia de tipos al parsear"
show Manual = "Ingreso de tipos por estudiante"
show Infer = "Inferencia de tipos después de parsear"
instance Serialize TypeCheck where
put = putWord8 . toEnum . fromEnum
get = getWord8 >>= \tag ->
if tag < 3 then return . toEnum . fromEnum $ tag
else fail $ "SerializeErr TypeCheck " ++ show tag
-- Tipo de re-escritura.
data RewriteMode = Simple -- ^ Directa.
| List -- ^ Se puede ver la lista de resultados.
| Focus -- ^ Se debe decir dónde se debe aplicar la regla.
deriving (Enum, Eq)
instance Show RewriteMode where
show Simple = "Se usa la regla para comprobar un paso"
show List = "Se puede ver la lista de resultados al aplicar una regla"
show Focus = "Se debe indicar dónde aplicar la regla"
instance Serialize RewriteMode where
put = putWord8 . toEnum . fromEnum
get = getWord8 >>= \tag ->
if tag < 3 then return . toEnum . fromEnum $ tag
else fail $ "SerializeErr RewriteMode " ++ show tag
-- Tipo de prueba.
data TypeProof = Direct -- ^ Prueba directa.
| Cases -- ^ Prueba por casos.
| Induction -- ^ Prueba por inducción.
| Deduction -- ^ Usando metateorema de la deducción.
deriving (Enum, Eq)
instance Show TypeProof where
show Direct = "Prueba directa"
show Cases = "Prueba distinguiendo casos"
show Induction = "Prueba por inducción"
show Deduction = "Prueba con el meta-teorema de la deducción"
instance Serialize TypeProof where
put = putWord8 . toEnum . fromEnum
get = getWord8 >>= \tag ->
if tag < 3 then return . toEnum . fromEnum $ tag
else fail $ "SerializeErr TypeProof " ++ show tag
data Explicit = Initial
| Relation
| Final
deriving (Show, Eq, Ord, Enum)
instance Serialize Explicit where
put = putWord8 . toEnum . fromEnum
get = getWord8 >>= \tag ->
if tag < 3 then return . toEnum . fromEnum $ tag
else fail $ "SerializeErr Explicit " ++ show tag
-- Conjunto de informacion a mostar relacionada con el objetivo del ejercicio.
type ExplicitInfo = S.Set Explicit
-- Configuracion de un ejercicio.
data ExerciseConf = ExerciseConf { eConfTypeProof :: TypeProof
, eConfExplicit :: ExplicitInfo
, eConfRewriteMode :: RewriteMode
, eConfTypeCheck :: TypeCheck
, eConfAvaibleTheories :: Grouped Axiom
}
instance Show ExerciseConf where
show exerConf = show (eConfTypeProof exerConf) ++ " " ++
show (eConfRewriteMode exerConf) ++ " " ++
show (eConfTypeCheck exerConf) ++ " " ++
show (eConfExplicit exerConf) ++ " " ++
show (map (fst) $ eConfAvaibleTheories exerConf)
instance Serialize ExerciseConf where
put (ExerciseConf tp ei rw tc ga) = put tp >> put ei >> put rw >>
put tc >> put ga
get = ExerciseConf <$> get <*> get <*> get <*> get <*> get
createExerciseConf :: ExerciseConf
createExerciseConf = ExerciseConf Direct S.empty Simple Auto []
typeCheckOptionList :: [TypeCheck]
typeCheckOptionList = [Auto, Manual, Infer]
rewriteModeOptionList :: [RewriteMode]
rewriteModeOptionList = [Simple, List, Focus]
typeProofOptionList :: [TypeProof]
typeProofOptionList = [Direct, Cases, Induction, Deduction]
explicitOptionList :: [Explicit]
explicitOptionList = [Initial, Relation, Final]
| miguelpagano/equ | Equ/Exercise/Conf.hs | gpl-3.0 | 4,228 | 0 | 16 | 1,241 | 950 | 526 | 424 | 82 | 1 |
module Ampersand.Prototype.ValidateEdit where
import Ampersand.Basics
import Ampersand.Classes
import Ampersand.ADL1
import Ampersand.FSpec
import Ampersand.FSpec.SQL
import qualified Ampersand.Misc.Options as Opts
import Ampersand.Prototype.PHP
import Data.List
import Data.Maybe
import System.FilePath hiding (isValid)
validateEditScript :: FSpec -> [Population] -> [Population] -> String -> IO Bool
validateEditScript fSpec beforePops afterPops editScriptPath =
do { mFileContents <- readUTF8File editScriptPath
; case mFileContents of
Left err -> error $ "ERROR reading file " ++ editScriptPath ++ ":\n" ++ err
Right editScript ->
do { --putStrLn $ "Population before edit operations:\n" ++ show beforePops
; --putStrLn $ "Expected population after edit operations:\n" ++ show afterPops
; putStrLn $ "Edit script:\n" ++ editScript
; result <- createTempDatabase fSpec beforePops
; let phpDir = Opts.dirPrototype (getOpts fSpec) </> "php"
; let phpScript = "ValidateEdit.php"
; putStrLn $ "Executing php script "++ phpDir </> phpScript
; _ <- executePHP (Just phpDir) phpScript [editScript] -- TODO: escape
; let expectedConceptTables = [ (c,map showValSQL atoms) | ACptPopu c atoms <- afterPops ]
; let expectedRelationTables = [ (d,map showValsSQL pairs) | ARelPopu{popdcl=d,popps=pairs} <- afterPops ]
; let actualConcepts = [ c | c<- concs fSpec, c /= ONE, name c /= "SESSION" ] -- TODO: are these the right concepts and decls?
; let actualRelations = vrels fSpec --
; actualConceptTables <- mapM (getSqlConceptTable fSpec) actualConcepts
; actualRelationTables <- mapM (getSqlRelationTable fSpec) actualRelations
; let commonConcepts = getCommons expectedConceptTables actualConceptTables
; let commonRelations = getCommons expectedRelationTables actualRelationTables
; putStrLn ""
; putStrLn "--- Validation results ---"
; putStrLn ""
; putStrLn "Actual concept tables:"
; putStrLn $ unlines [ name c ++ ": " ++ show atoms | (c,atoms) <- actualConceptTables ]
; putStrLn $ "Actual relations:\n" ++ unlines [ name d ++ ": " ++ show pairs | (d,pairs) <- actualRelationTables ]
; putStrLn $ "Expected concept tables:\n" ++ unlines [ name c ++ ": " ++ show atoms | (c,atoms) <- expectedConceptTables ]
; putStrLn $ "Expected relations:\n" ++ unlines [ name d ++ ": " ++ show pairs | (d,pairs) <- expectedRelationTables ]
; let conceptDiffs = showDiff "Actual population" "concepts" (map fst expectedConceptTables) (map fst actualConceptTables)
; let relationDiffs = showDiff "Actual population" "relations" (map fst expectedRelationTables) (map fst actualRelationTables)
; let commonConceptDiffs = concat [ showDiff (name c) "atoms" expAtoms resAtoms | (c, expAtoms, resAtoms) <- commonConcepts ]
; let commonRelationDiffs = concat [ showDiff (name r) "pairs" expPairs resPairs | (r, expPairs, resPairs) <- commonRelations ]
; putStrLn ""
; putStrLn "--- Validation summary ---"
; putStrLn ""
; if null conceptDiffs
then putStrLn "Expected and actual populations contain the same concepts"
else putStrLn . unlines $ conceptDiffs
; putStrLn ""
; if null relationDiffs
then putStrLn "Expected and actual populations contain the same relations"
else putStrLn . unlines $ relationDiffs
; putStrLn ""
; if null commonConceptDiffs
then putStrLn "Common concepts are equal"
else putStrLn . unlines $ "Differences for common concepts:" : commonConceptDiffs
; putStrLn ""
; if null commonRelationDiffs
then putStrLn "Common relations are equal"
else putStrLn $ unlines $ "Differences for common relations:" : commonRelationDiffs
; let isValid = null $ conceptDiffs ++ relationDiffs ++ commonConceptDiffs ++ commonRelationDiffs
; putStrLn $ "\nValidation " ++ if isValid then "was successful." else "failed."
; return isValid
}
}
where showValsSQL p = ((showValSQL.apLeft) p, (showValSQL.apRight) p)
getSqlConceptTable :: FSpec -> A_Concept -> IO (A_Concept, [String])
getSqlConceptTable fSpec c =
do { -- to prevent needing a unary query function, we add a dummy NULL column and use `src` and `tgt` as column names (in line with what performQuery expects)
let query = case lookupCpt fSpec c of
[] -> fatal ("No concept table for concept \"" ++ name c ++ "\"")
(table,conceptAttribute):_ -> "SELECT DISTINCT `" ++ attName conceptAttribute ++ "` as `src`, NULL as `tgt`"++
" FROM `" ++ name table ++ "`" ++
" WHERE `" ++ attName conceptAttribute ++ "` IS NOT NULL"
--; putStrLn $ "Query for concept " ++ name c ++ ":" ++ query
; atomsDummies <- performQuery (getOpts fSpec) (tempDbName (getOpts fSpec)) query
; return (c, map fst atomsDummies)
}
getSqlRelationTable :: FSpec -> Relation -> IO (Relation, [(String,String)])
getSqlRelationTable fSpec d =
do { let query = prettySQLQuery False fSpec 0 d
--; putStrLn $ "Query for decl " ++ name d ++ ":" ++ query
; pairs <- performQuery (getOpts fSpec) (tempDbName (getOpts fSpec)) query
; return (d, pairs)
}
-- TODO: are we going to use this data type?
type EditScript = [SQLEditOp]
data SQLEditOp = SQLAddToConcept { atomNm :: String, conceptNm :: String }
| SQLDelete { relationNm :: String, relationIsFlipped :: Bool
, parentAtomNm :: String, childAtomNm :: String }
| SQLUpdate { relationNm :: String, relationIsFlipped :: Bool
, parentAtomNm :: String, parentConceptNm ::String
, childAtomNm :: String, childConceptNm ::String
, parentOrChild :: ParentOrChild, originalAtomNm :: String
}
data ParentOrChild = Parent | Child deriving Show
{- JSON for edit commands from Database.PHP:
{ dbCmd: 'addToConcept', atom:atom, concept:concept }
{ dbCmd: 'update', relation:relation, isFlipped:relationIsFlipped
, parentAtom:parentAtom, parentConcept:parentConcept
, childAtom:childAtom, childConcept:childConcept
, parentOrChild:parentOrChild, originalAtom:originalAtom
}
{ dbCmd: 'delete', relation:relation, isFlipped:relationIsFlipped
, parentAtom:parentAtom, childAtom:childAtom
}
-}
-- Utils
getCommons :: Eq a => [(a,bs)] -> [(a,bs)] -> [(a,bs,bs)]
getCommons elts1 elts2 = catMaybes
[ case find (\(a',_)-> a' == a) elts2 of
Just (_,bs2) -> Just (a, bs1, bs2)
Nothing -> Nothing
| (a,bs1) <- elts1
]
showDiff :: (Eq a, Show a) => String -> String -> [a] -> [a] -> [String]
showDiff entityStr elementsStr expected actual =
let unexpected = actual \\ expected
missing = expected \\ actual
in [ "!! " ++ entityStr ++ " is missing expected " ++ elementsStr ++ ": " ++ show missing | not . null $ missing ] ++
[ "!! " ++ entityStr ++ " has unexpected " ++ elementsStr ++ ": " ++ show unexpected | not . null $ unexpected ]
| AmpersandTarski/ampersand | src/Ampersand/Prototype/ValidateEdit.hs | gpl-3.0 | 7,774 | 2 | 21 | 2,279 | 1,823 | 958 | 865 | 102 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Routes.Products
( ProductAPI
, productRoutes
) where
import Control.Monad (when)
import Control.Monad.Trans (lift)
import Data.Aeson ((.=), (.:), (.:?), ToJSON(..), FromJSON(..), object, withObject)
import Data.Char (isAlpha)
import Data.Maybe (listToMaybe)
import Database.Persist ((==.), Entity(..), selectList, get, getBy)
import Servant ((:>), (:<|>)(..), Capture, QueryParam, ReqBody, Get, Post, JSON, throwError, err404)
import Models
import Server
import Routes.CommonData
import Routes.Utils (paginatedSelect)
import qualified Data.Text as T
import qualified Database.Esqueleto as E
type ProductAPI =
"search" :> ProductsSearchRoute
:<|> "details" :> ProductDetailsRoute
type ProductRoutes =
(Maybe T.Text -> Maybe Int -> Maybe Int -> ProductsSearchParameters -> App ProductsSearchData)
:<|> (T.Text -> App ProductDetailsData)
productRoutes :: ProductRoutes
productRoutes =
productsSearchRoute
:<|> productDetailsRoute
-- DETAILS
data ProductDetailsData =
ProductDetailsData
{ pddProduct :: BaseProductData
, pddVariants :: [VariantData]
, pddSeedAttribute :: Maybe (Entity SeedAttribute)
, pddCategories :: [CategoryData]
, pddPredecessors :: [PredecessorCategory]
} deriving (Show)
instance ToJSON ProductDetailsData where
toJSON productData =
object [ "product" .= toJSON (pddProduct productData)
, "variants" .= toJSON (pddVariants productData)
, "seedAttribute" .= toJSON (pddSeedAttribute productData)
, "categories" .= toJSON (pddCategories productData)
, "predecessors" .= toJSON (pddPredecessors productData)
]
type ProductDetailsRoute =
Capture "slug" T.Text :> Get '[JSON] ProductDetailsData
-- TODO: Use Esqueleto library to make 1 query instead of 4
productDetailsRoute :: T.Text -> App ProductDetailsData
productDetailsRoute slug = do
maybeProduct <- runDB . getBy $ UniqueProductSlug slug
case maybeProduct of
Nothing ->
throwError err404
Just e@(Entity productId prod) -> runDB $ do
extraCategories <- getAdditionalCategories productId
baseData <- lift $ makeBaseProductData e extraCategories
(variants, maybeAttribute, category) <-
(,,)
<$> (selectList
[ ProductVariantProductId ==. productId
, ProductVariantIsActive ==. True
] []
>>= applySalesToVariants e
)
<*> getBy (UniqueAttribute productId)
<*> selectList [CategoryId ==. productMainCategory prod] []
when (null variants) $ throwError err404
predecessors <- lift $ concat . (category :)
<$> mapM (getParentCategories . entityKey) category
categoryData <- lift $ mapM makeCategoryData category
return . ProductDetailsData baseData variants maybeAttribute categoryData
$ map categoryToPredecessor predecessors
-- SEARCH
data ProductsSearchParameters =
ProductsSearchParameters
{ pspQuery :: T.Text
, pspSearchDescription :: Bool
, pspFilterOrganic :: Bool
, pspFilterHeirloom :: Bool
, pspFilterRegional :: Bool
, pspFilterSmallGrower :: Bool
, pspCategoryId :: Maybe CategoryId
} deriving (Show)
instance FromJSON ProductsSearchParameters where
parseJSON =
withObject "ProductsSearchParameters" $ \v ->
ProductsSearchParameters
<$> v .: "query"
<*> v .: "searchDescription"
<*> v .: "filterOrganic"
<*> v .: "filterHeirloom"
<*> v .: "filterRegional"
<*> v .: "filterSmallGrower"
<*> v .:? "category"
data ProductsSearchData =
ProductsSearchData
{ psdProductData :: [ProductData]
, psdTotalProducts :: Int
, psdCategoryName :: Maybe T.Text
} deriving (Show)
instance ToJSON ProductsSearchData where
toJSON searchData =
object [ "products" .= toJSON (psdProductData searchData)
, "total" .= toJSON (psdTotalProducts searchData)
, "categoryName" .= toJSON (psdCategoryName searchData)
]
type ProductsSearchRoute =
QueryParam "sortBy" T.Text
:> QueryParam "page" Int
:> QueryParam "perPage" Int
:> ReqBody '[JSON] ProductsSearchParameters
:> Post '[JSON] ProductsSearchData
productsSearchRoute :: Maybe T.Text -> Maybe Int -> Maybe Int -> ProductsSearchParameters -> App ProductsSearchData
productsSearchRoute maybeSort maybePage maybePerPage parameters = runDB $ do
let queryFilters p
| pspQuery parameters /= "" && pspSearchDescription parameters =
foldl1 (E.&&.) . map (nameOrDescriptionOrSku p) . T.words $ pspQuery parameters
| pspQuery parameters /= "" =
foldl1 (E.&&.) . map (nameOrSku p) . T.words $ pspQuery parameters
| otherwise =
E.val True
organicFilter =
attributeFilter pspFilterOrganic SeedAttributeIsOrganic
heirloomFilter =
attributeFilter pspFilterHeirloom SeedAttributeIsHeirloom
regionalFilter =
attributeFilter pspFilterRegional SeedAttributeIsRegional
growerFilter =
attributeFilter pspFilterSmallGrower SeedAttributeIsSmallGrower
(categoryFilter, catName) <- case pspCategoryId parameters of
Nothing ->
return (const $ E.val True, Nothing)
Just cId -> do
name <- fmap categoryName <$> get cId
categories <- getChildCategoryIds cId
return (\p -> p E.^. ProductMainCategory `E.in_` E.valList categories, name)
(products, productsCount) <- paginatedSelect
maybeSort maybePage maybePerPage
(\p sa _ -> queryFilters p E.&&. organicFilter sa E.&&. heirloomFilter sa E.&&.
regionalFilter sa E.&&. growerFilter sa E.&&.
categoryFilter p)
searchData <- mapM (getProductData . truncateDescription) products
return $ ProductsSearchData searchData productsCount catName
where fuzzyILike f s =
f `E.ilike` ((E.%) E.++. E.val s E.++. (E.%))
maybeFuzzyILike f =
maybe (E.val False) (f `fuzzyILike`)
numericSku =
listToMaybe . filter (/= "") . T.split isAlpha
nameOrDescriptionOrSku p w =
(p E.^. ProductName) `fuzzyILike` w E.||.
(p E.^. ProductLongDescription) `fuzzyILike` w E.||.
(p E.^. ProductBaseSku) `maybeFuzzyILike` numericSku w E.||.
(p E.^. ProductKeywords) `fuzzyILike` w
nameOrSku p w =
(p E.^. ProductName) `fuzzyILike` w E.||.
(p E.^. ProductBaseSku) `maybeFuzzyILike` numericSku w E.||.
(p E.^. ProductKeywords) `fuzzyILike` w
attributeFilter selector attribute sa =
if selector parameters then
sa E.?. attribute E.==. E.just (E.val True)
else
E.val True
| Southern-Exposure-Seed-Exchange/southernexposure.com | server/src/Routes/Products.hs | gpl-3.0 | 7,522 | 0 | 21 | 2,304 | 1,856 | 981 | 875 | 158 | 3 |
module LiName.ParsersSpec where
import LiName.Types
import LiName.Parsers
import Data.Either
import Test.Hspec
import Text.ParserCombinators.Parsec.Error
fn = "<HSpec>"
spec :: Spec
spec = do
describe "parseEntry" $ do
it "Rename" $ do
parseEntry fn "023\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) (DoRename "CAT"))
parseEntry fn "023\t\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) (DoRename "\tCAT"))
parseEntry fn "023\t CAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) (DoRename " CAT"))
it "Copy" $ do
parseEntry fn "=023\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) (DoCopy "CAT"))
parseEntry fn "=023\t\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) (DoCopy "\tCAT"))
parseEntry fn "=023\t CAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) (DoCopy " CAT"))
it "Trash" $ do
parseEntry fn "!023\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) DoTrash)
parseEntry fn "!023\t\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) DoTrash)
parseEntry fn "!023\t CAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) DoTrash)
it "Delete" $ do
parseEntry fn "!!023\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) DoDelete)
parseEntry fn "!!023\t\tCAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) DoDelete)
parseEntry fn "!!023\t CAT" `shouldBe` (Right $ LiNameEntry (LiNameKey 23) DoDelete)
it "ParseError" $ do
parseEntry fn "!! 023\tCAT" `shouldSatisfy` isLeft
parseEntry fn "\tCAT" `shouldSatisfy` isLeft
parseEntry fn "a\tCAT" `shouldSatisfy` isLeft
parseEntry fn "123\t" `shouldSatisfy` isLeft
| anekos/liname-hs | test/LiName/ParsersSpec.hs | gpl-3.0 | 1,714 | 0 | 18 | 368 | 584 | 292 | 292 | 31 | 1 |
module Exponential
( exponentialPDF
, exponentialAltPDF
, exponentialCDF
, exponentialQuantile
, exponentialValGen
) where
import StatUtils
-- The following two functions are the different parameterisations
-- of the exponential PDF. The test function of their equivalence
-- will pass through 100 sets of test values only SOME of the time.
-- The failures occur with very small small values of x or lambda.
-- Failures usually include a lambda value < 1e-307. For now, input
-- should be kept to much higher values due to these rounding errors.
exponentialPDF :: (Num a, Ord a, Floating a) => a -> a -> a
exponentialPDF x lambda
| x <= 0 = 0
| lambda <= 0 = 0
| otherwise = lambda * exp (-1 * lambda * x)
exponentialAltPDF :: (Num a, Ord a, Floating a) => a -> a -> a
exponentialAltPDF x beta
| x <= 0 = 0
| beta <= 0 = 0
| otherwise = (1 / beta) * exp (-1 * (x / beta))
exponentialCDF :: (Num a, Floating a) => a -> a -> a
exponentialCDF x lambda = 1 - exp(-1 * lambda * x)
exponentialQuantile :: (Num a, Floating a) => a -> a -> a
exponentialQuantile x lambda = (-1 * log (1-x)) / lambda
exponentialValGen :: (Num a, Floating a) => a -> a -> a
exponentialValGen u lambda = exponentialQuantile u lambda -- u ~ Unif(0, 1)
exexex
| R-Morgan/hasStat | Exponential.hs | gpl-3.0 | 1,280 | 0 | 11 | 290 | 398 | 208 | 190 | -1 | -1 |
module Configuration where
import Data.Word
import Network
udpPort :: PortNumber
udpPort = 9909
maxline :: Int
maxline = 1500
-- |Lights in format of (logical channel, DMX start channel). FIXME stupid types.
lights = [(0,1)
,(1,26)
,(2,11)
,(3,6)
,(4,42)
,(5,31)
,(6,16)
,(7,36)
,(8,64)
,(9,(64+8))
,(10,(64+16))
,(11,(64+32))
,(12,(64+36))
]
-- |Values are initially zeros.
initialValues :: [(Int, Word8)]
initialValues = [(31,34) -- wash 1 positions
,(32,50)
,(33,77)
,(34,50)
,(49,255) -- wash 1 dimmer
,(51,34) -- wash 2 positions
,(52,50)
,(53,77)
,(54,50)
,(69,255) -- wash 2 dimmer
,(71,34) -- wash 3 positions
,(72,50)
,(73,77)
,(74,50)
,(89,255) -- wash 3 dimmer
,(91,34) -- wash 4 positions
,(92,50)
,(93,77)
,(94,50)
,(109,34) --wash 4 positions
]
| zouppen/valo | Configuration.hs | gpl-3.0 | 1,202 | 0 | 8 | 554 | 391 | 259 | 132 | 41 | 1 |
{-# LANGUAGE OverloadedStrings, FlexibleInstances #-}
module System.DevUtils.Redis.Helpers.CommandStats.Run (
run'commandStats,
run'commandStats'List
) where
import System.DevUtils.Redis.Helpers.CommandStats.Include
import System.DevUtils.Redis.Helpers.CommandStats.Marshall
import qualified Data.ByteString as B
import Database.Redis
import Data.Maybe
instance RedisResult [CommandStat] where
decode o@(Bulk r) =
case r of
Nothing -> Left o
(Just r') -> let un = unMarshall'List r' in case un of
Nothing -> Left o
(Just commands) -> Right commands
decode r = Left r
run'commandStats :: Redis (Either Reply CommandStats)
run'commandStats = sendRequest ["INFO", "COMMANDSTATS"]
run'commandStats'List :: Connection -> IO (Maybe CommandStats)
run'commandStats'List conn = do
either <- runRedis conn run'commandStats
case either of
(Left err) -> return Nothing
(Right cs) -> return $ Just cs
| adarqui/DevUtils-Redis | src/System/DevUtils/Redis/Helpers/CommandStats/Run.hs | gpl-3.0 | 920 | 0 | 15 | 140 | 270 | 144 | 126 | 25 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.FireStore.Projects.Databases.Documents.Rollback
-- 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)
--
-- Rolls back a transaction.
--
-- /See:/ <https://cloud.google.com/firestore Cloud Firestore API Reference> for @firestore.projects.databases.documents.rollback@.
module Network.Google.Resource.FireStore.Projects.Databases.Documents.Rollback
(
-- * REST Resource
ProjectsDatabasesDocumentsRollbackResource
-- * Creating a Request
, projectsDatabasesDocumentsRollback
, ProjectsDatabasesDocumentsRollback
-- * Request Lenses
, pddrXgafv
, pddrUploadProtocol
, pddrDatabase
, pddrAccessToken
, pddrUploadType
, pddrPayload
, pddrCallback
) where
import Network.Google.FireStore.Types
import Network.Google.Prelude
-- | A resource alias for @firestore.projects.databases.documents.rollback@ method which the
-- 'ProjectsDatabasesDocumentsRollback' request conforms to.
type ProjectsDatabasesDocumentsRollbackResource =
"v1" :>
Capture "database" Text :>
"documents:rollback" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] RollbackRequest :> Post '[JSON] Empty
-- | Rolls back a transaction.
--
-- /See:/ 'projectsDatabasesDocumentsRollback' smart constructor.
data ProjectsDatabasesDocumentsRollback =
ProjectsDatabasesDocumentsRollback'
{ _pddrXgafv :: !(Maybe Xgafv)
, _pddrUploadProtocol :: !(Maybe Text)
, _pddrDatabase :: !Text
, _pddrAccessToken :: !(Maybe Text)
, _pddrUploadType :: !(Maybe Text)
, _pddrPayload :: !RollbackRequest
, _pddrCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsDatabasesDocumentsRollback' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pddrXgafv'
--
-- * 'pddrUploadProtocol'
--
-- * 'pddrDatabase'
--
-- * 'pddrAccessToken'
--
-- * 'pddrUploadType'
--
-- * 'pddrPayload'
--
-- * 'pddrCallback'
projectsDatabasesDocumentsRollback
:: Text -- ^ 'pddrDatabase'
-> RollbackRequest -- ^ 'pddrPayload'
-> ProjectsDatabasesDocumentsRollback
projectsDatabasesDocumentsRollback pPddrDatabase_ pPddrPayload_ =
ProjectsDatabasesDocumentsRollback'
{ _pddrXgafv = Nothing
, _pddrUploadProtocol = Nothing
, _pddrDatabase = pPddrDatabase_
, _pddrAccessToken = Nothing
, _pddrUploadType = Nothing
, _pddrPayload = pPddrPayload_
, _pddrCallback = Nothing
}
-- | V1 error format.
pddrXgafv :: Lens' ProjectsDatabasesDocumentsRollback (Maybe Xgafv)
pddrXgafv
= lens _pddrXgafv (\ s a -> s{_pddrXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pddrUploadProtocol :: Lens' ProjectsDatabasesDocumentsRollback (Maybe Text)
pddrUploadProtocol
= lens _pddrUploadProtocol
(\ s a -> s{_pddrUploadProtocol = a})
-- | Required. The database name. In the format:
-- \`projects\/{project_id}\/databases\/{database_id}\`.
pddrDatabase :: Lens' ProjectsDatabasesDocumentsRollback Text
pddrDatabase
= lens _pddrDatabase (\ s a -> s{_pddrDatabase = a})
-- | OAuth access token.
pddrAccessToken :: Lens' ProjectsDatabasesDocumentsRollback (Maybe Text)
pddrAccessToken
= lens _pddrAccessToken
(\ s a -> s{_pddrAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pddrUploadType :: Lens' ProjectsDatabasesDocumentsRollback (Maybe Text)
pddrUploadType
= lens _pddrUploadType
(\ s a -> s{_pddrUploadType = a})
-- | Multipart request metadata.
pddrPayload :: Lens' ProjectsDatabasesDocumentsRollback RollbackRequest
pddrPayload
= lens _pddrPayload (\ s a -> s{_pddrPayload = a})
-- | JSONP
pddrCallback :: Lens' ProjectsDatabasesDocumentsRollback (Maybe Text)
pddrCallback
= lens _pddrCallback (\ s a -> s{_pddrCallback = a})
instance GoogleRequest
ProjectsDatabasesDocumentsRollback
where
type Rs ProjectsDatabasesDocumentsRollback = Empty
type Scopes ProjectsDatabasesDocumentsRollback =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/datastore"]
requestClient ProjectsDatabasesDocumentsRollback'{..}
= go _pddrDatabase _pddrXgafv _pddrUploadProtocol
_pddrAccessToken
_pddrUploadType
_pddrCallback
(Just AltJSON)
_pddrPayload
fireStoreService
where go
= buildClient
(Proxy ::
Proxy ProjectsDatabasesDocumentsRollbackResource)
mempty
| brendanhay/gogol | gogol-firestore/gen/Network/Google/Resource/FireStore/Projects/Databases/Documents/Rollback.hs | mpl-2.0 | 5,620 | 0 | 17 | 1,213 | 784 | 458 | 326 | 117 | 1 |
-- | Put all CSS for these widgets in templates/project_feed.cassius
module View.SnowdriftEvent where
import Import
import Model.Comment
import Model.Comment.ActionPermissions
import Model.Comment.Routes
import Model.Currency
import Model.User
import View.Comment
import View.Time
import qualified Data.Map as M
import qualified Data.Text as T
renderCommentPostedEvent
:: CommentId
-> Comment
-> Maybe UserId
-> Text
-> Map DiscussionId DiscussionOn
-> ActionPermissionsMap
-> Map CommentId [CommentClosing]
-> Map CommentId [CommentRetracting]
-> Map UserId User
-> Map CommentId CommentClosing
-> Map CommentId CommentRetracting
-> Map CommentId (Entity Ticket)
-> Map CommentId TicketClaiming
-> Map CommentId (CommentFlagging, [FlagReason])
-> Widget
renderCommentPostedEvent
comment_id
comment
mviewer_id
project_handle
discussion_map
action_permissions_map
earlier_closures_map
earlier_retracts_map
user_map
closure_map
retract_map
ticket_map
claim_map
flag_map = do
let action_permissions = lookupErr "renderCommentPostedEvent: comment id missing from permissions map"
comment_id
action_permissions_map
user = lookupErr "renderCommentPostedEvent: comment user missing from user map"
(commentUser comment)
user_map
discussion = lookupErr "renderCommentPostedEvent: discussion id not found in map"
(commentDiscussion comment)
discussion_map
(routes, feed_item_widget) = case discussion of
DiscussionOnProject (Entity _ Project{..}) ->
(projectCommentRoutes projectHandle, [whamlet|
<div .event>
On
<a href=@{ProjectDiscussionR projectHandle}>#{projectName}#
:
^{comment_widget}
|])
DiscussionOnWikiPage (Entity _ WikiTarget{..}) ->
(wikiPageCommentRoutes project_handle wikiTargetLanguage wikiTargetTarget, [whamlet|
<div .event>
On the
<a href=@{WikiDiscussionR project_handle wikiTargetLanguage wikiTargetTarget}>#{wikiTargetTarget}
wiki page:
^{comment_widget}
|])
DiscussionOnUser (Entity user_id _) ->
(userCommentRoutes user_id, [whamlet|
<div .event>
On your user discussion page:
^{comment_widget}
|])
DiscussionOnBlogPost (Entity _ BlogPost{..}) ->
(blogPostCommentRoutes project_handle blogPostHandle, [whamlet|
<div .event>
On blog post
<a href=@{BlogPostDiscussionR project_handle blogPostHandle}>#{blogPostTitle}
:
^{comment_widget}
|])
comment_widget =
commentWidget
(Entity comment_id comment)
mviewer_id
routes
action_permissions
(M.findWithDefault [] comment_id earlier_closures_map)
(M.findWithDefault [] comment_id earlier_retracts_map)
user
(M.lookup comment_id closure_map)
(M.lookup comment_id retract_map)
(M.lookup comment_id ticket_map)
(M.lookup comment_id claim_map)
(M.lookup comment_id flag_map)
False
mempty
feed_item_widget
renderCommentPendingEvent :: CommentId -> Comment -> UserMap -> Widget
renderCommentPendingEvent comment_id comment user_map = do
let poster = lookupErr "renderCommentPendingEvent: poster not found in user map" (commentUser comment) user_map
[whamlet|
<div .event>
^{renderTime $ commentCreatedTs comment}
<a href=@{UserR (commentUser comment)}> #{userDisplayName (Entity (commentUser comment) poster)}
posted a
<a href=@{CommentDirectLinkR comment_id}> comment
awaiting moderator approval: #{commentText comment}
|]
renderCommentRethreadedEvent :: Rethread -> UserMap -> Widget
renderCommentRethreadedEvent Rethread{..} user_map = do
langs <- handlerToWidget getLanguages
(Just old_route, Just new_route) <- handlerToWidget $ runDB $ (,)
<$> makeCommentRouteDB langs rethreadOldComment
<*> makeCommentRouteDB langs rethreadNewComment
let user = lookupErr "renderCommentRethreadedEvent: rethreader not found in user map" rethreadModerator user_map
[whamlet|
<div .event>
^{renderTime rethreadTs}
<a href=@{UserR rethreadModerator}> #{userDisplayName (Entity rethreadModerator user)}
rethreaded a comment from
<del>@{old_route}
to
<a href=@{new_route}>@{new_route}#
: #{rethreadReason}
|]
renderCommentClosedEvent :: CommentClosing -> UserMap -> Map CommentId (Entity Ticket) -> Widget
renderCommentClosedEvent CommentClosing{..} user_map ticket_map = do
let user = lookupErr "renderCommentClosedEvent: closing user not found in user map" commentClosingClosedBy user_map
case M.lookup commentClosingComment ticket_map of
Just (Entity ticket_id Ticket{..}) -> do
let ticket_str = case toPersistValue ticket_id of
PersistInt64 tid -> T.pack $ show tid
_ -> "<malformed key>"
[whamlet|
<div .event>
^{renderTime commentClosingTs}
<a href=@{UserR commentClosingClosedBy}> #{userDisplayName (Entity commentClosingClosedBy user)}
closed ticket
<a href=@{CommentDirectLinkR commentClosingComment}>
<div .ticket-title>SD-#{ticket_str}: #{ticketName}
|]
Nothing ->
[whamlet|
<div .event>
^{renderTime commentClosingTs}
<a href=@{UserR commentClosingClosedBy}> #{userDisplayName (Entity commentClosingClosedBy user)}
closed
<a href=@{CommentDirectLinkR commentClosingComment}>
comment thread
|]
renderTicketClaimedEvent :: Either (TicketClaimingId, TicketClaiming) (TicketOldClaimingId, TicketOldClaiming) -> UserMap -> Map CommentId (Entity Ticket) -> Widget
renderTicketClaimedEvent (Left (_, TicketClaiming{..})) user_map ticket_map = do
let user = lookupErr "renderTicketClaimedEvent: claiming user not found in user map" ticketClaimingUser user_map
Entity ticket_id Ticket{..} = lookupErr "renderTicketClaimedEvent: ticket not found in map" ticketClaimingTicket ticket_map
ticket_str = case toPersistValue ticket_id of
PersistInt64 tid -> T.pack $ show tid
_ -> "<malformed key>"
[whamlet|
<div .event>
^{renderTime ticketClaimingTs}
<a href=@{UserR ticketClaimingUser}> #{userDisplayName (Entity ticketClaimingUser user)}
claimed ticket
<a href=@{CommentDirectLinkR ticketClaimingTicket}>
<div .ticket-title>SD-#{ticket_str}: #{ticketName}
|]
renderTicketClaimedEvent (Right (_, TicketOldClaiming{..})) user_map ticket_map = do
let user = lookupErr "renderTicketClaimedEvent: claiming user not found in user map" ticketOldClaimingUser user_map
Entity ticket_id Ticket{..} = lookupErr "renderTicketClaimedEvent: ticket not found in map" ticketOldClaimingTicket ticket_map
ticket_str = case toPersistValue ticket_id of
PersistInt64 tid -> T.pack $ show tid
_ -> "<malformed key>"
[whamlet|
<div .event>
^{renderTime ticketOldClaimingClaimTs}
<a href=@{UserR ticketOldClaimingUser}> #{userDisplayName (Entity ticketOldClaimingUser user)}
claimed ticket
<a href=@{CommentDirectLinkR ticketOldClaimingTicket}>
<div .ticket-title>SD-#{ticket_str}: #{ticketName}
|]
renderTicketUnclaimedEvent :: TicketOldClaiming -> UserMap -> Map CommentId (Entity Ticket) -> Widget
renderTicketUnclaimedEvent TicketOldClaiming{..} _ ticket_map = do
let Entity ticket_id Ticket{..} = lookupErr "renderTicketUnclaimedEvent: ticket not found in map" ticketOldClaimingTicket ticket_map
ticket_str = case toPersistValue ticket_id of
PersistInt64 tid -> T.pack $ show tid
_ -> "<malformed key>"
[whamlet|
<div .event>
^{renderTime ticketOldClaimingClaimTs}
Claim released, ticket available:
<a href=@{CommentDirectLinkR ticketOldClaimingTicket}>
<div .ticket-title>SD-#{ticket_str}: #{ticketName}
|]
renderWikiPageEvent :: Text -> WikiPageId -> WikiPage -> UserMap -> Widget
renderWikiPageEvent project_handle wiki_page_id wiki_page _ = do
-- TODO(aaron)
-- The commented stuff here (and in the whamlet commented part)
-- is because there's no wikiPageUser and the
-- user_map is also not needed until that is active--
-- let editor = fromMaybe
-- (error "renderWikiPageEvent: wiki editor not found in user map")
-- (M.lookup (wikiPageUser wiki_page) user_map)
--perhaps instead of a wikiPageUser, we should just figure out how to pull
--the user from the first wiki edit for the event of new pages
-- TODO: pick language correctly
[Entity _ wiki_target] <- runDB $ select $ from $ \wt -> do
where_ $ wt ^. WikiTargetPage ==. val wiki_page_id
limit 1
return wt
[whamlet|
<div .event>
^{renderTime $ wikiPageCreatedTs wiki_page}
<!--
<a href=@{UserR (wikiPageUser wiki_page)}>
#{userDisplayName (Entity (wikiPageUser wiki_page) editor)}
-->
made a new wiki page: #
<a href=@{WikiR project_handle (wikiTargetLanguage wiki_target) (wikiTargetTarget wiki_target)}>#{wikiTargetTarget wiki_target}
|]
renderWikiEditEvent :: Text -> WikiEditId -> WikiEdit -> Map WikiPageId WikiTarget -> UserMap -> Widget
renderWikiEditEvent project_handle edit_id wiki_edit wiki_target_map user_map = do
let editor = lookupErr "renderWikiEditEvent: wiki editor not found in user map" (wikiEditUser wiki_edit) user_map
wiki_target = lookupErr "renderWikiEditEvent: wiki page id not found in wiki target map" (wikiEditPage wiki_edit) wiki_target_map
[whamlet|
<div .event>
^{renderTime $ wikiEditTs wiki_edit}
<a href=@{UserR (wikiEditUser wiki_edit)}>
#{userDisplayName (Entity (wikiEditUser wiki_edit) editor)}
edited the
<a href=@{WikiR project_handle (wikiTargetLanguage wiki_target) (wikiTargetTarget wiki_target)}> #{wikiTargetTarget wiki_target}
wiki page: #
$maybe comment <- wikiEditComment wiki_edit
#{comment}
<br>
<a href=@{WikiEditR project_handle (wikiTargetLanguage wiki_target) (wikiTargetTarget wiki_target) edit_id}>
see this edit version <!-- TODO: make this link to the diff instead -->
|]
renderBlogPostEvent :: BlogPost -> Widget
renderBlogPostEvent (BlogPost {..}) = do
maybe_project <- handlerToWidget $ runYDB $ get blogPostProject
[whamlet|
<div .event>
^{renderTime blogPostTs}
New blog post: #
$maybe Project{projectHandle = project_handle} <- maybe_project
<a href=@{BlogPostR project_handle blogPostHandle}>
#{blogPostTitle}
$nothing
#{blogPostTitle}
|]
renderNewPledgeEvent :: SharesPledgedId -> SharesPledged -> UserMap -> Widget
renderNewPledgeEvent _ SharesPledged{..} user_map = do
let pledger = lookupErr "renderNewPledgeEvent: pledger not found in user map" sharesPledgedUser user_map
mills = millMilray sharesPledgedShares
[whamlet|
<div .event>
^{renderTime sharesPledgedTs}
<a href=@{UserR sharesPledgedUser}> #{userDisplayName (Entity sharesPledgedUser pledger)}
made a new pledge of #{show mills} per patron!
|]
renderUpdatedPledgeEvent :: Int64 -> SharesPledgedId -> SharesPledged -> UserMap -> Widget
renderUpdatedPledgeEvent old_shares _ SharesPledged{..} user_map = do
let pledger = lookupErr "renderUpdatedPledgeEvent: pledger not found in user map" sharesPledgedUser user_map
(verb, punc) = if old_shares < sharesPledgedShares
then ("increased", "!")
else ("decreased", ".") :: (Text, Text)
old_mills = millMilray old_shares
new_mills = millMilray sharesPledgedShares
[whamlet|
<div .event>
^{renderTime sharesPledgedTs}
<a href=@{UserR sharesPledgedUser}> #{userDisplayName (Entity sharesPledgedUser pledger)}
#{verb} their pledge from #{show old_mills} to #{show new_mills} per patron#{punc}
|]
renderDeletedPledgeEvent :: UTCTime -> UserId -> Int64 -> UserMap -> Widget
renderDeletedPledgeEvent ts user_id shares user_map = do
let pledger = lookupErr "renderDeletedPledgeEvent: pledger not found in user map" user_id user_map
mills = millMilray shares
[whamlet|
<div .event>
^{renderTime ts}
<a href=@{UserR user_id}>#{userDisplayName (Entity user_id pledger)}
withdrew their #{show mills} per patron pledge.
|]
| akegalj/snowdrift | View/SnowdriftEvent.hs | agpl-3.0 | 14,104 | 0 | 21 | 4,261 | 1,789 | 923 | 866 | -1 | -1 |
module Tokenizer where
import Debug.Trace
import Text.Regex.Posix
data Token =
FTok Float
| ITok Int
| Finit
| Iinit
| PrintTok
| PlusTok
| MinusTok
| AssignTok
| IdentifierTok Char
deriving (Show, Eq)
type Tokens = [Token]
type PartialInt = (String, String)
type PartialFloat = (String, String)
tokenize :: String -> Tokens
tokenize [] = []
tokenize (c:cs) =
if c == 'f' then Finit:(tokenize cs)
else if c == 'i' then Iinit:(tokenize cs)
else if c == 'p' then PrintTok:(tokenize cs)
else if c == '+' then PlusTok:(tokenize cs)
else if c == '-' then MinusTok:(tokenize cs)
else if c == '=' then AssignTok:(tokenize cs)
else if (c:[]) =~ "^[a-eghj-oq-zA-Z]" then (IdentifierTok c):tokenize cs
else if (c:cs) =~ "^[0-9]+\\.[0-9]+" then
let (ftok, ts) = buildFloat $ fTokenize (c:cs)
in (FTok ftok):(tokenize ts)
else if (c:cs) =~ "^[0-9]+" then
let (itok, ts) = buildInt $ iTokenize (c:cs)
in (ITok itok):(tokenize ts)
else if c == ' ' then tokenize cs else trace ("Skipping invalid character: " ++ c:[]) $ tokenize cs
fTokenize :: String -> (String, String)
fTokenize [] = ([],[])
fTokenize (c:[]) = (c:[],[])
fTokenize (c:cs) =
if (c:[]) =~ "[0-9.]" then floatBuilder c (fTokenize cs)
else ([], c:cs)
floatBuilder :: Char -> (String, String) -> (String, String)
floatBuilder c (cs, remaining) = (c:cs, remaining)
buildFloat :: PartialFloat -> (Float, String)
buildFloat (fstr, cs) = (read fstr, cs)
iTokenize :: String -> (String, String)
iTokenize [] = ([],[])
iTokenize (c:[]) = (c:[],[])
iTokenize (c:cs) =
if (c:[]) =~ "[0-9]" then intBuilder c (iTokenize cs)
else ([], c:cs)
intBuilder :: Char -> (String, String) -> PartialInt
intBuilder c (cs, remaining) = (c:cs, remaining)
buildInt :: PartialInt -> (Int, String)
buildInt (istr, cs) = (read istr, cs)
| gik0geck0/ac_dc_compiler | tokenizer.hs | unlicense | 1,903 | 0 | 21 | 429 | 892 | 497 | 395 | 54 | 11 |
{-# LANGUAGE OverloadedStrings #-}
module Erd.Parse
( loadER
)
where
import Erd.ER
import Control.Exception (bracket_)
import Control.Monad (when,unless)
import Data.List (find)
import Data.Maybe
import Data.Text.Lazy hiding (find, map, reverse)
import Data.Text.Lazy.IO
import System.IO (Handle,hIsTerminalDevice,hSetEncoding,
hGetEncoding,utf8)
import Text.Parsec
import Text.Parsec.Erd.Parser (AST (..), GlobalOptions (..), document)
import Text.Printf (printf)
loadER :: String -> Handle -> IO (Either String ER)
loadER fpath f = do
Just initialEncoding <- hGetEncoding f
isTerminalDevice <- hIsTerminalDevice f
let setEncodingIfNeeded = unless isTerminalDevice . hSetEncoding f
bracket_
(setEncodingIfNeeded utf8)
(setEncodingIfNeeded initialEncoding)
(do
s <- hGetContents f
case parse (do { (opts, ast) <- document; return $ toER opts ast}) fpath s of
Left err -> return $ Left $ show err
Right err@(Left _) -> return err
Right (Right er) -> return $ Right er
)
-- | Converts a list of syntactic categories in an entity-relationship
-- description to an ER representation. If there was a problem with the
-- conversion, an error is reported. This includes checking that each
-- relationship contains only valid entity names.
--
-- This preserves the ordering of the syntactic elements in the original
-- description.
toER :: GlobalOptions -> [AST] -> Either String ER
toER gopts = toER' (ER [] [] erTitle)
where erTitle = gtoptions gopts `mergeOpts` defaultTitleOpts
toER' :: ER -> [AST] -> Either String ER
toER' er [] = Right (reversed er) >>= validRels
toER' ER { entities = [] } (A a:_) =
let fieldName = show (field a)
in Left $ printf "Attribute '%s' comes before first entity." fieldName
toER' er@ER { entities = e':es } (A a:xs) = do
let e = e' { attribs = a:attribs e' }
toER' (er { entities = e:es }) xs
toER' er@ER { entities = es } (E e:xs) = do
let opts = eoptions e
`mergeOpts` geoptions gopts
`mergeOpts` defaultEntityOpts
let hopts = eoptions e
`mergeOpts` ghoptions gopts
`mergeOpts` defaultHeaderOpts
toER' (er { entities = e { eoptions = opts, hoptions = hopts }:es}) xs
toER' er@ER { rels = rs } (R r:xs) = do
let opts = roptions r
`mergeOpts` groptions gopts
`mergeOpts` defaultRelOpts
toER' (er { rels = r { roptions = opts }:rs }) xs
reversed :: ER -> ER
reversed er@ER { entities = es, rels = rs } =
let es' = map (\e -> e { attribs = reverse (attribs e) }) es
in er { entities = reverse es', rels = reverse rs }
validRels :: ER -> Either String ER
validRels er = validRels' (rels er) er
validRels' :: [Relation] -> ER -> Either String ER
validRels' [] er = return er
validRels' (r:_) er = do
let r1 = find (\e -> name e == entity1 r) (entities er)
let r2 = find (\e -> name e == entity2 r) (entities er)
let err getter = Left
$ printf "Unknown entity '%s' in relationship."
$ unpack $ getter r
when (isNothing r1) (err entity1)
when (isNothing r2) (err entity2)
return er
| BurntSushi/erd | src/Erd/Parse.hs | unlicense | 3,662 | 0 | 18 | 1,254 | 1,167 | 606 | 561 | 70 | 6 |
-- Copyright (c) 2015 Jonathan M. Lange <jml@mumak.net>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Hazard.Games ( GameCreationError(..)
, GameCreationRequest(reqNumPlayers, reqTurnTimeout)
, Validated(..)
, GameError(..)
, GameID
, GameSlot
, Game(Pending, InProgress)
, JoinError(..)
, PlayError(..)
, RoundID
, Seconds
, SlotAction
, runSlotAction
, runSlotActionT
, creator
, createGame
, currentPlayer
, gameState
, getAllRounds
, getCurrentRound
, getRound
, getPlayers
, joinSlot
, numPlayers
, players
, playSlot
, requestGame
, roundToJSON
, turnTimeout
, validateCreationRequest
, validatePlayRequest
) where
import BasicPrelude hiding (round)
import Control.Error
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.State
import Data.Aeson (FromJSON(..), ToJSON(..), object, (.=), (.:), (.:?), Value(..))
import qualified Data.Map as Map
import qualified Data.Text as Text
import Web.Spock.Safe (renderRoute)
import qualified Hazard.Routes as Route
import Hazard.Users (UserID, toJSONKey)
import Haverer (
Card(..),
FullDeck,
Event(..),
Play(..),
Player,
Result(..),
Round,
currentPlayer,
currentTurn,
getDiscards,
getPlayers,
getPlayerMap,
getHand,
isProtected,
PlayerSet,
PlayerSetError,
toPlayers,
toPlayerSet,
viewAction
)
import qualified Haverer.Game as H
import qualified Haverer.Round as Round
data GameError a = GameNotFound Int
| OtherError a
deriving (Show)
data JoinError = AlreadyStarted
| InvalidPlayers (PlayerSetError UserID)
| AlreadyFinished
deriving (Eq, Show)
data PlayError = NotStarted
| PlayNotSpecified
| RoundFinished
| BadAction (Round.BadAction UserID)
| NotYourTurn UserID UserID
| NotInGame UserID
| RoundNotFound Int
| RoundNotActive
deriving (Show)
type GameID = Int
type RoundID = Int
type Seconds = Int
data Validated = Unchecked | Valid
data GameCreationError = InvalidNumberOfPlayers Int
| InvalidTurnTimeout Seconds
deriving (Eq, Show)
data GameCreationRequest (a :: Validated) = GameCreationRequest {
reqNumPlayers :: Int,
reqTurnTimeout :: Seconds
} deriving (Eq, Show)
instance ToJSON (GameCreationRequest a) where
toJSON r = object [ "numPlayers" .= reqNumPlayers r
, "turnTimeout" .= reqTurnTimeout r
]
instance FromJSON (GameCreationRequest 'Unchecked) where
parseJSON (Object v) = requestGame <$> v .: "numPlayers" <*> v .: "turnTimeout"
parseJSON _ = mzero
requestGame :: Int -> Seconds -> GameCreationRequest 'Unchecked
requestGame = GameCreationRequest
validateCreationRequest :: MonadError GameCreationError m => GameCreationRequest 'Unchecked -> m (GameCreationRequest 'Valid)
validateCreationRequest (GameCreationRequest { .. })
| reqTurnTimeout <= 0 = throwError $ InvalidTurnTimeout reqTurnTimeout
| reqNumPlayers < 2 = throwError $ InvalidNumberOfPlayers reqNumPlayers
| reqNumPlayers > 4 = throwError $ InvalidNumberOfPlayers reqNumPlayers
| otherwise = return $ GameCreationRequest reqNumPlayers reqTurnTimeout
data PlayRequest (a :: Validated) = PlayRequest Card (Play UserID) deriving (Eq, Show)
instance FromJSON (PlayRequest 'Unchecked) where
parseJSON (Object v) = do
-- XXX: Find out how to do this all in one line into a tuple using
-- applicative functor
card <- v .: "card"
target <- v .:? "target"
guess <- v .:? "guess"
PlayRequest card <$> case (target, guess) of
(Nothing, Nothing) -> return NoEffect
(Just player, Nothing) -> return $ Attack player
(Just player, Just guess') -> return $ Guess player guess'
_ -> mzero
parseJSON _ = mzero
validatePlayRequest :: UserID -> Int -> Maybe (PlayRequest 'Unchecked) -> SlotAction PlayError (Maybe (PlayRequest 'Valid))
validatePlayRequest player roundId request = do
game <- gameState <$> get
round <- liftEither $ getRound game roundId ?? RoundNotFound roundId
unless (player `elem` getPlayers round) (throwOtherError (NotInGame player))
current <- liftEither $ currentPlayer round ?? RoundNotActive
unless (player == current) (throwOtherError (NotYourTurn player current))
(return . fmap validCopy) request
where validCopy (PlayRequest card play) = PlayRequest card play
-- | Represents a single game.
--
-- Pretty much all of the interesting state about the game is in 'Game'.
data GameSlot = GameSlot {
gameID :: GameID,
turnTimeout :: Seconds,
creator :: UserID,
gameState :: Game
} deriving (Show)
data Game = Pending { _numPlayers :: Int
, _players :: [UserID]
}
| Ready { _playerSet :: PlayerSet UserID }
| InProgress { game :: H.Game UserID
, rounds :: [Round UserID]
}
| Finished { _outcome :: H.Outcome UserID
, rounds :: [Round UserID]
}
deriving (Show)
instance ToJSON GameSlot where
toJSON slot =
object (specificFields ++ commonFields)
where
specificFields =
case gameState slot of
Pending {} -> ["state" .= ("pending" :: Text)]
Ready {} -> ["state" .= ("pending" :: Text)]
InProgress {..} -> [ "state" .= ("in-progress" :: Text)
, "currentRound" .= renderRoute Route.round (gameID slot) (length rounds - 1)
]
Finished {..} -> [ "state" .= ("finished" :: Text)
, "winners" .= H.winners _outcome
]
commonFields = [ "turnTimeout" .= turnTimeout slot
, "creator" .= creator slot
, "numPlayers" .= numPlayers slot
, "players" .= Map.mapKeys toJSONKey (getScores (gameState slot))
]
instance (Ord a, ToJSON a) => ToJSON (Round a) where
toJSON = roundToJSON Nothing
roundToJSON :: (Ord a, ToJSON a) => Maybe a -> Round a -> Value
roundToJSON someone round =
object $ [ "players" .= (map playerToJSON' . Map.assocs . getPlayerMap) round
, "currentPlayer" .= currentPlayer round
] ++ msum [("dealtCard" .=) <$> justZ getDealt
,("winners" .=) <$> justZ getWinners]
where
playerToJSON' = uncurry (playerToJSON someone)
getDealt = do
(pid, (dealt, _)) <- justZ (currentTurn round)
viewer <- someone
guard (viewer == pid)
return dealt
getWinners = Round.getWinners <$> Round.victory round
playerToJSON :: (Eq a, ToJSON a) => Maybe a -> a -> Player -> Value
playerToJSON someone pid player =
case someone of
Nothing -> object commonFields
Just viewer
| viewer == pid -> object $ ("hand" .= getHand player):commonFields
| otherwise -> playerToJSON Nothing pid player
where commonFields =
[ "id" .= pid
, "active" .= (isJust . getHand) player
, "protected" .= isProtected player
, "discards" .= getDiscards player
]
instance ToJSON Card where
toJSON = toJSON . show
instance ToJSON a => ToJSON (Round.Result a) where
toJSON (Round.BustedOut playerId dealt hand) =
object [ "result" .= ("busted" :: Text)
, "id" .= playerId
, "dealt" .= dealt
, "hand" .= hand
]
toJSON (Round.Played action event) =
object $ [ "result" .= ("played" :: Text) ] ++ actions ++ events
where
actions =
let (pid, card, play) = viewAction action in
[ "id" .= pid, "card" .= card ] ++
case play of
NoEffect -> []
Attack target -> ["target" .= target]
Guess target guess -> ["target" .= target, "guess" .= guess]
events = case event of
NoChange -> [ "result" .= ("no-change" :: Text) ]
Protected pid -> [ "result" .= ("protected" :: Text)
, "protected" .= pid
]
SwappedHands tgt src -> [ "result" .= ("swapped-hands" :: Text)
, "swapped-hands" .= [src, tgt]
]
Eliminated pid -> [ "result" .= ("eliminated" :: Text)
, "eliminated" .= pid ]
ForcedDiscard {} -> [ "result" .= ("forced-discard" :: Text) ]
ForcedReveal src tgt _ -> [ "result" .= ("forced-reveal" :: Text)
, "forced-reveal" .= [src, tgt]
]
instance FromJSON Card where
parseJSON (String s) =
case Text.toLower s of
"soldier" -> return Soldier
"clown" -> return Clown
"knight" -> return Knight
"priestess" -> return Priestess
"wizard" -> return Wizard
"general" -> return General
"minister" -> return Minister
"prince" -> return Prince
_ -> mzero
parseJSON _ = mzero
createGame :: UserID -> GameID -> GameCreationRequest 'Valid -> GameSlot
createGame userId gameId request =
GameSlot { gameID = gameId
, turnTimeout = reqTurnTimeout request
, creator = userId
, gameState = Pending { _numPlayers = reqNumPlayers request
, _players = [userId]
}
}
numPlayers :: GameSlot -> Int
numPlayers =
numPlayers' . gameState
where numPlayers' (Pending { _numPlayers = _numPlayers }) = _numPlayers
numPlayers' (Ready { _playerSet = _playerSet }) = (length . toPlayers) _playerSet
numPlayers' (InProgress { game = game' }) = (length . toPlayers . H.players) game'
numPlayers' (Finished { _outcome = outcome }) = (length . H.finalScores) outcome
players :: GameSlot -> [UserID]
players = players' . gameState
players' :: Game -> [UserID]
players' (Pending { _players = _players }) = _players
players' (Ready { _playerSet = _playerSet }) = toPlayers _playerSet
players' (InProgress { game = game }) = (toPlayers . H.players) game
players' (Finished { _outcome = outcome }) = map fst . H.finalScores $ outcome
getRound :: Game -> Int -> Maybe (Round UserID)
getRound InProgress { rounds = rounds } i = atMay rounds i
getRound Finished { rounds = rounds } i = atMay rounds i
getRound _ _ = Nothing
getAllRounds :: GameSlot -> [(RoundID, Round UserID)]
getAllRounds slot =
case gameState slot of
InProgress { rounds = rounds } -> zip [0..] rounds
Finished { rounds = rounds } -> zip [0..] rounds
_ -> []
getCurrentRound :: GameSlot -> Maybe (RoundID, Round UserID)
getCurrentRound slot =
case gameState slot of
InProgress {} -> Just $ last (getAllRounds slot)
_ -> Nothing
getScores :: Game -> Map UserID (Maybe Int)
getScores game =
Map.fromList $ case game of
Pending {} -> zip (players' game) (repeat Nothing)
Ready {} -> zip (players' game) (repeat (Just 0))
InProgress { game = game' } -> map (second Just) (H.scores game')
Finished { _outcome = outcome } -> map (second Just) (H.finalScores outcome)
type SlotActionT e m a = StateT GameSlot (ExceptT (GameError e) m) a
type SlotAction e a = SlotActionT e Identity a
runSlotActionT :: SlotActionT e m a -> GameSlot -> m (Either (GameError e) (a, GameSlot))
runSlotActionT action slot = runExceptT (runStateT action slot)
runSlotAction :: SlotAction e a -> GameSlot -> Either (GameError e) (a, GameSlot)
runSlotAction action slot = runIdentity $ runSlotActionT action slot
liftEither :: (Monad m, MonadTrans t) => ExceptT e m a -> t (ExceptT (GameError e) m) a
liftEither = lift . fmapLT OtherError
throwOtherError :: MonadError (GameError e) m => e -> m a
throwOtherError = throwError . OtherError
modifyGame :: Monad m => (Game -> ExceptT (GameError e) m Game) -> SlotActionT e m ()
modifyGame f = do
slot <- get
let game = gameState slot
game'' <- (lift . f) game
put (slot { gameState = game'' })
joinSlot :: FullDeck -> UserID -> SlotAction JoinError ()
joinSlot deck p = modifyGame $ \game ->
do
game' <- (fmapLT OtherError . hoistEither . joinGame p) game
case game' of
Ready playerSet -> return $ makeGame deck playerSet
_ -> return game'
joinGame :: UserID -> Game -> Either JoinError Game
joinGame _ (InProgress {}) = throwError AlreadyStarted
joinGame _ (Ready {}) = throwError AlreadyStarted
joinGame _ (Finished {}) = throwError AlreadyFinished
joinGame p g@(Pending {..})
| p `elem` _players = return g
| numNewPlayers == _numPlayers =
Ready <$> fmapL InvalidPlayers (toPlayerSet newPlayers)
| otherwise = return Pending { _numPlayers = _numPlayers
, _players = newPlayers }
where newPlayers = _players ++ [p]
numNewPlayers = length newPlayers
makeGame :: FullDeck -> PlayerSet UserID -> Game
makeGame deck playerSet = do
let game = H.makeGame playerSet
let round = H.newRound' game deck
InProgress { game = game, rounds = pure round }
playSlot :: FullDeck -> Maybe (PlayRequest 'Valid) -> SlotAction PlayError (Result UserID)
playSlot deck playRequest = do
currentState <- gameState <$> get
case currentState of
Pending {} -> throwOtherError NotStarted
Ready {} -> throwOtherError NotStarted
Finished {} -> throwOtherError RoundFinished
InProgress {} -> do
let round = last . rounds $ currentState
(result, round') <- playTurnOn round playRequest
modify $ \s -> s { gameState = (gameState s) { rounds = init (rounds . gameState $ s) ++ [round'] } }
case Round.victory round' of
Nothing -> return ()
Just victory -> do
game' <- game . gameState <$> get
case H.playersWon game' (Round.getWinners victory) of
Left outcome ->
modify $ \s -> s { gameState = Finished outcome (rounds (gameState s)) }
Right game'' -> do
modify $ \s -> s { gameState = (gameState s) { game = game'' } }
modify $ \s -> s { gameState = addRound (H.newRound' (game . gameState $ s) deck) (gameState s) }
return result
where
requestToPlay (PlayRequest card p) = (card, p)
playTurnOn round = liftEither . fmapLT BadAction . hoistEither . Round.playTurn' round . fmap requestToPlay
addRound round toState = toState { rounds = rounds toState ++ [round] }
| jml/hazard | lib/Hazard/Games.hs | apache-2.0 | 15,913 | 0 | 31 | 4,725 | 4,569 | 2,421 | 2,148 | 344 | 6 |
{-|
Module : Pulsar.Output
Description : Manage file handles and general output.
Copyright : (c) Jesse Haber-Kucharsky, 2014
License : Apache-2.0
-}
{-# LANGUAGE OverloadedStrings #-}
module Pulsar.Output
(withHandle
,writeImage
,writeHexDump
,writeListing)
where
import Prelude hiding (words)
import Pulsar.Ast
import Pulsar.Encode (EncodedProgram (..),
EncodedStatement (..))
import qualified Pulsar.Output.Assembly as Output.Asm
import Control.Exception (bracket)
import Control.Monad
import Data.Binary.Put
import qualified Data.ByteString.Lazy as LBS
import Data.IORef
import Data.Monoid ((<>))
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Text.Lazy (toStrict)
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as Vec
import System.IO
import Text.Printf (hPrintf, printf)
-- | Do something with an appropriate Handle. If Nothing is provided as the
-- path, then stdout is assumed. The handle is closed once the callback
-- terminates.
withHandle :: Maybe FilePath -> (Handle -> IO ()) -> IO ()
withHandle maybePath =
bracket
getHandle
(\h -> when (h /= stdout) $ hClose h)
where
getHandle =
case maybePath of
Just path -> openFile path WriteMode
Nothing -> return stdout
writeImage :: Handle -> Vector Word16 -> IO ()
writeImage h img = LBS.hPut h bs
where
bs = runPut . Vec.mapM_ putWord16be $ img
writeHexDump :: Handle -> Vector Word16 -> IO ()
writeHexDump h img =
-- Bah. Mutable state.
do indexRef <- newIORef (0 :: Word)
forM_ (groupsOf 4 (Vec.toList img)) $ \wordGroup ->
do index <- readIORef indexRef
hPrintf h "[%04x] " index :: IO ()
mapM_ (\w -> hPrintf h "%04x " w :: IO ()) wordGroup
hPutStr h "\n"
modifyIORef indexRef (+ 4)
writeListing :: Handle -> EncodedProgram -> IO ()
writeListing h enc =
let numSpaces numWords =
if numWords == 0
then wordsColumnSize
else wordsColumnSize - (4 * numWords) - (numWords - 1)
in forM_ (statements enc) $ \statement ->
case groupsOf 4 (words statement) of
[] ->
do put . formatSpaces $ wordsColumnSize
put . formatLoc . startLoc $ statement
put formatSep
putLn . formatStatement $ statement
firstWords : otherWords ->
do put . formatManyWords $ firstWords
put . formatSpaces . numSpaces $ length firstWords
put . formatLoc . startLoc $ statement
put formatSep
putLn . formatStatement $ statement
forM_ otherWords $ \partialWords ->
putLn . formatManyWords $ partialWords
where
put = Text.hPutStr h
putLn = Text.hPutStrLn h
formatWord v = Text.pack $ printf "%04x" v
formatLoc v = Text.singleton '[' <> formatWord v <> Text.singleton ']'
formatSep = " "
formatSpaces n = Text.replicate n (Text.singleton ' ')
formatManyWords = Text.unwords . map formatWord
formatStatement = toStrict . Output.Asm.statement . originalContext
wordsColumnSize = 20
groupsOf :: Int -> [a] -> [[a]]
groupsOf n xs
| n <= 0 = []
| otherwise =
case splitAt n xs of
(group, []) -> [group]
(group, xs') -> group : groupsOf n xs'
| hakuch/Pulsar | src/Pulsar/Output.hs | apache-2.0 | 3,535 | 0 | 17 | 1,067 | 992 | 518 | 474 | 82 | 3 |
module Haggis.Types where
data Type = TInt
| TReal
| TStr
| TBool
| TArr Type
| TGuiIn
| TGuiOut
| TVoid deriving Eq
instance Show Type where
show t = case t of
TInt -> "integer"
TReal -> "real number"
TStr -> "string"
TBool -> "boolean"
TArr e -> "array of " ++ show e ++ "s"
TGuiIn -> "input stream"
TGuiOut -> "output stream" | sivawashere/haggis | src/Haggis/Types.hs | bsd-2-clause | 432 | 0 | 11 | 169 | 115 | 62 | 53 | 18 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionToolBar.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QStyleOptionToolBar (
QStyleOptionToolBarStyleOptionType
, QStyleOptionToolBarStyleOptionVersion
, ToolBarPosition, ToolBarPositions, fBeginning, fMiddle, fEnd, fOnlyOne
, ToolBarFeature, ToolBarFeatures, eMovable, fMovable
)
where
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CQStyleOptionToolBarStyleOptionType a = CQStyleOptionToolBarStyleOptionType a
type QStyleOptionToolBarStyleOptionType = QEnum(CQStyleOptionToolBarStyleOptionType Int)
ieQStyleOptionToolBarStyleOptionType :: Int -> QStyleOptionToolBarStyleOptionType
ieQStyleOptionToolBarStyleOptionType x = QEnum (CQStyleOptionToolBarStyleOptionType x)
instance QEnumC (CQStyleOptionToolBarStyleOptionType Int) where
qEnum_toInt (QEnum (CQStyleOptionToolBarStyleOptionType x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionToolBarStyleOptionType x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionToolBarStyleOptionType -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeType QStyleOptionToolBarStyleOptionType where
eType
= ieQStyleOptionToolBarStyleOptionType $ 16
data CQStyleOptionToolBarStyleOptionVersion a = CQStyleOptionToolBarStyleOptionVersion a
type QStyleOptionToolBarStyleOptionVersion = QEnum(CQStyleOptionToolBarStyleOptionVersion Int)
ieQStyleOptionToolBarStyleOptionVersion :: Int -> QStyleOptionToolBarStyleOptionVersion
ieQStyleOptionToolBarStyleOptionVersion x = QEnum (CQStyleOptionToolBarStyleOptionVersion x)
instance QEnumC (CQStyleOptionToolBarStyleOptionVersion Int) where
qEnum_toInt (QEnum (CQStyleOptionToolBarStyleOptionVersion x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionToolBarStyleOptionVersion x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionToolBarStyleOptionVersion -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeVersion QStyleOptionToolBarStyleOptionVersion where
eVersion
= ieQStyleOptionToolBarStyleOptionVersion $ 1
data CToolBarPosition a = CToolBarPosition a
type ToolBarPosition = QEnum(CToolBarPosition Int)
ieToolBarPosition :: Int -> ToolBarPosition
ieToolBarPosition x = QEnum (CToolBarPosition x)
instance QEnumC (CToolBarPosition Int) where
qEnum_toInt (QEnum (CToolBarPosition x)) = x
qEnum_fromInt x = QEnum (CToolBarPosition x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> ToolBarPosition -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
data CToolBarPositions a = CToolBarPositions a
type ToolBarPositions = QFlags(CToolBarPositions Int)
ifToolBarPositions :: Int -> ToolBarPositions
ifToolBarPositions x = QFlags (CToolBarPositions x)
instance QFlagsC (CToolBarPositions Int) where
qFlags_toInt (QFlags (CToolBarPositions x)) = x
qFlags_fromInt x = QFlags (CToolBarPositions x)
withQFlagsResult x
= do
ti <- x
return $ qFlags_fromInt $ fromIntegral ti
withQFlagsListResult x
= do
til <- x
return $ map qFlags_fromInt til
instance Qcs (QObject c -> ToolBarPositions -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qFlags_fromInt hint)
return ()
instance QeBeginning ToolBarPosition where
eBeginning
= ieToolBarPosition $ 0
instance QeMiddle ToolBarPosition where
eMiddle
= ieToolBarPosition $ 1
instance QeEnd ToolBarPosition where
eEnd
= ieToolBarPosition $ 2
instance QeOnlyOne ToolBarPosition where
eOnlyOne
= ieToolBarPosition $ 3
fBeginning :: ToolBarPositions
fBeginning
= ifToolBarPositions $ 0
fMiddle :: ToolBarPositions
fMiddle
= ifToolBarPositions $ 1
fEnd :: ToolBarPositions
fEnd
= ifToolBarPositions $ 2
fOnlyOne :: ToolBarPositions
fOnlyOne
= ifToolBarPositions $ 3
data CToolBarFeature a = CToolBarFeature a
type ToolBarFeature = QEnum(CToolBarFeature Int)
ieToolBarFeature :: Int -> ToolBarFeature
ieToolBarFeature x = QEnum (CToolBarFeature x)
instance QEnumC (CToolBarFeature Int) where
qEnum_toInt (QEnum (CToolBarFeature x)) = x
qEnum_fromInt x = QEnum (CToolBarFeature x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> ToolBarFeature -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
data CToolBarFeatures a = CToolBarFeatures a
type ToolBarFeatures = QFlags(CToolBarFeatures Int)
ifToolBarFeatures :: Int -> ToolBarFeatures
ifToolBarFeatures x = QFlags (CToolBarFeatures x)
instance QFlagsC (CToolBarFeatures Int) where
qFlags_toInt (QFlags (CToolBarFeatures x)) = x
qFlags_fromInt x = QFlags (CToolBarFeatures x)
withQFlagsResult x
= do
ti <- x
return $ qFlags_fromInt $ fromIntegral ti
withQFlagsListResult x
= do
til <- x
return $ map qFlags_fromInt til
instance Qcs (QObject c -> ToolBarFeatures -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qFlags_fromInt hint)
return ()
instance QeNone ToolBarFeature where
eNone
= ieToolBarFeature $ 0
eMovable :: ToolBarFeature
eMovable
= ieToolBarFeature $ 1
instance QfNone ToolBarFeatures where
fNone
= ifToolBarFeatures $ 0
fMovable :: ToolBarFeatures
fMovable
= ifToolBarFeatures $ 1
| uduki/hsQt | Qtc/Enums/Gui/QStyleOptionToolBar.hs | bsd-2-clause | 11,915 | 0 | 18 | 2,645 | 3,218 | 1,566 | 1,652 | 275 | 1 |
module LOGL.Application
(
runAppLoop, runAppLoopEx, runAppLoopEx2,
reactWithContext,
module LOGL.Application.Window,
module LOGL.Application.Context
)
where
import LOGL.Application.Window
import LOGL.Application.Context
import Reactive.Banana.Frameworks
import LOGL.FRP
import Graphics.UI.GLFW as GLFW
import Control.Monad.Loops
import Reactive.Banana hiding (empty)
import Control.Monad.Reader
runAppLoopEx2 :: AppWindow -> AppContext -> MomentIO () -> IO ()
runAppLoopEx2 win context net = do
let networkDesc :: MomentIO ()
networkDesc = do
-- close windw on ESC
keyE <- keyEvent win
let escE = filterKeyPressE keyE Key'Escape
reactimate $ setWindowShouldClose (window win) True <$ escE
initWindowResize win
net
network <- compile networkDesc
actuate network
fireCtx win context
whileM_ (not <$> windowShouldClose (window win)) $ do
Just startTime <- getTime
fireIdle win ()
Just endTime <- getTime
let fps = 1.0 / (endTime - startTime)
setWindowTitle (window win) (title win ++ "(" ++ show fps ++ " fps)")
pause network
runAppLoopEx :: AppWindow -> MomentIO () -> IO ()
runAppLoopEx win = runAppLoopEx2 win emptyContext
runAppLoop :: AppWindow -> IO () -> IO ()
runAppLoop win loop = do
let networkDesc :: MomentIO ()
networkDesc = do
idleE <- idleEvent win
reactimate $ loop <$ idleE
runAppLoopEx win networkDesc
-- | functions for the application context
reactWithContext :: AppWindow -> Event (ReaderT AppContext IO ()) -> MomentIO ()
reactWithContext win event = do
ctxE <- ctxEvent win
contextB <- stepper emptyContext ctxE
reactimate $ (doInContext <$> contextB) <@> event
where
doInContext ctx action = runReaderT action ctx
| atwupack/LearnOpenGL | src/LOGL/Application.hs | bsd-3-clause | 1,864 | 0 | 16 | 461 | 561 | 274 | 287 | 48 | 1 |
module Turing where
import qualified Data.Map as Map
type Move = Ordering
type TMMap q s = Map.Map (q, s) (q, s, Move)
-- The Turing Machine's tape is implemented as a list-zipper. The head of the
-- machine is positioned on the first element of the "after" list; stepping
-- forward moves that symbol into the "before" list, and stepping backward will
-- move a symbol from the "before" list back into the after list. The blank
-- symbol provides a default for when either of the lists is empty.
data Tape s = Tape {
blank :: s
, before :: [s]
, after :: [s]
} deriving (Eq)
showSymbol :: Show s => s -> String
showSymbol s = let str = show s
quoted = head str `elem` ['\'', '"'] && head str == last str
in if quoted then tail (init str) else str
-- Show the elements on the tape as a space-separated list
showAfter :: Show s => Tape s -> String
showAfter (Tape b _ r) = unwords $ map showSymbol r
-- if null r
-- then show b
-- else unwords $ map show r
-- The elements in the "before" list are in reversed order
showBefore :: Show s => Tape s -> String
showBefore (Tape b l _) = unwords . reverse $ map showSymbol l
-- if null l
-- then show b
-- else unwords . reverse $ map show l
instance Show s => Show (Tape s) where
show tp = if null $ before tp
then "[" ++ showAfter tp ++ "]"
else "[" ++ showBefore tp ++ " " ++ showAfter tp ++ "]"
-- Construct an empty tape, containing only the blank symbol
blankTape :: s -> Tape s
blankTape blankSym = Tape blankSym [] []
-- Construct a tape containing the given string of symbols
inputTape :: s -> [s] -> Tape s
inputTape blankSym input = Tape blankSym [] input
-- Convert the tape into a linear string of symbols
outputTape :: Tape s -> [s]
outputTape (Tape _ l r) = foldl (flip (:)) r l
-- Convert the tape to a string of symbols, but strip off the leading and
-- trailing blank symbols
outputTape' :: Eq s => Tape s -> [s]
outputTape' (Tape b l r) =
let strip x lst = if null lst && x == b then [] else x:lst
right = foldr strip [] r
left = foldr strip [] l
in foldl (flip (:)) right left
-- Get the length of the tape
tapeLength :: Tape s -> Int
tapeLength (Tape _ l r) = length l + length r
-- Get the symbol at the head of the tape
readTape :: Tape s -> s
readTape tp
| null $ after tp = blank tp
| otherwise = head $ after tp
-- Replace the symbol at the head of the tape with a new one
printTape :: s -> Tape s -> Tape s
printTape s (Tape b l []) = Tape b l [s]
printTape s (Tape b l (_:rs)) = Tape b l (s:rs)
-- Move the tape right by moving the symbol at the head of the tape to the
-- "before" list
moveRight :: Tape s -> Tape s
moveRight (Tape b l []) = Tape b (b : l) []
moveRight (Tape b l (r:rs)) = Tape b (r:l) rs
-- Move the tape left by moving the head of the "before" list back to the head
-- of the "after" list
moveLeft :: Tape s -> Tape s
moveLeft (Tape b [] r) = Tape b [] (b : r)
moveLeft (Tape b (l:ls) r) = Tape b ls (l:r)
-- Move the tape in the given direction
moveTape :: Move -> Tape s -> Tape s
moveTape LT = moveLeft
moveTape EQ = id
moveTape GT = moveRight
-- A Turing machine consists of a tape, a transition function, and its current
-- state. Based on the current state and the symbol it reads off the tape, the
-- transition function returns a new state, a symbol to print on the tape, and a
-- direction in which to move the tape. When the transition function returns the
-- "halt" state, it indicates that the machine should stop
data TuringMachine q s = TM {
halt :: q
, state :: q
, tape :: Tape s
, transition :: q -> s -> (q, s, Move)
}
-- Draw the head of the tape like " [this> "
showHead :: Show q => TuringMachine q s -> String
showHead tm = " [" ++ showSymbol (state tm) ++ "> "
-- Show the tape with the head pointing to the scanned symbol on the tape
instance (Show q, Show s) => Show (TuringMachine q s) where
show tm = let tp = tape tm
in "[" ++ showBefore tp ++ showHead tm ++ showAfter tp ++ "]"
-- Get the result of a Turing machine's transition function by looking it up
-- from a Map of inputs to outputs. Use the machine's halting state to produce a
-- default value, so the machine will halt when the given inputs are not found
-- in the transition table
tmLookup :: (Ord q, Ord s) => TMMap q s -> q -> q -> s -> (q, s, Move)
tmLookup table hlt cur sym = Map.findWithDefault stop input table
where input = (cur, sym)
stop = (hlt, sym, EQ)
-- Construct a turing machine from a transition map, as well as a set halting
-- state, start state, and blank tape symbol
fromTable :: (Ord q, Ord s) => TMMap q s -> q -> q -> s -> TuringMachine q s
fromTable table hlt start b = TM hlt start tp control
where tp = blankTape b
control = tmLookup table hlt
-- Get the result of the machine's transition function given its current state
-- and the symbol at the head of the tape
nextMove :: Eq q => TuringMachine q s -> (q, s, Move)
nextMove (TM hlt cur input func)
| cur == hlt = (hlt, (readTape input), EQ)
| otherwise = func cur (readTape input)
-- Advance the state of the Turing machine by a single iteration
step :: Eq q => TuringMachine q s -> TuringMachine q s
step tm = let (next, sym, dir) = nextMove tm
tp = moveTape dir . printTape sym $ tape tm
in tm {state = next, tape = tp}
-- Run the Turing machine until it halts, generating a list of the intermediate
-- states of the machine as it goes
run :: Eq q => TuringMachine q s -> [TuringMachine q s]
run tm | state tm == halt tm = [tm]
| otherwise = tm : (run $ step tm)
| kebertx/Automata | src/Turing.hs | bsd-3-clause | 5,829 | 0 | 12 | 1,553 | 1,679 | 874 | 805 | 81 | 2 |
module HaskellCraft.Block where
import qualified Text.Show as S (Show)
import qualified Text.Show.Text as T (Show)
import Text.Show.Text hiding (Show)
import Text.Show.Text.TH (deriveShow)
import Text.Show.Text.Data.Char
data Block = Air | Stone | Grass | Dirt | Cobblestone | Wood_planks | Sapling |
Bedrock | Water_flowing | Water | Water_stationary | Lava_flowing | Lava |
Lava_stationary | Sand | Gravel | Gold_ore | Iron_ore | Coal_ore | Wood |
Leaves | Sponge | Glass | Lapis_lazuli_ore | Lapis_lazuli_block |
Sandstone | Bed | Powered_rail | Cobweb | Grass_tall | Dead_bush | Wool |
Flower_yellow | Flower_cyan | Mushroom_brown | Mushroom_red | Gold_block |
Iron_block | Stone_slab_double | Stone_slab | Brick_block | Tnt |
Bookshelf | Moss_stone | Obsidian | Torch | Fire | Stairs_wood | Chest |
Diamond_ore | Diamond_block | Crafting_table | Seeds | Farmland |
Furnace_inactive | Furnace_active | Sign_post | Door_wood | Ladder | Rail |
Stairs_cobblestone | Wall_sign | Door_iron | Redstone_ore |
Glowing_redstone_ore | Snow | Ice | Snow_block | Cactus | Clay |
Sugar_cane | Fence | Pumpkin | Netherrack | Glowstone_block |
Jack_o_lantern | Cake_block | Bedrock_invisible | Trapdoor | Stone_brick |
Glass_pane | Melon | Pumpkin_stem | Melon_seeds | Fence_gate |
Stairs_brick | Stairs_stone_brick | Nether_brick | Stairs_nether_brick |
Stairs_sandstone | Emerald_ore | Stairs_spruce_wood | Stairs_birch_wood |
Stairs_jungle_wood | Cobblestone_wall | Carrots | Potato | Quartz_block |
Stairs_quartz | Wooden_double_slab | Wooden_slab | Hay_block | Carpet |
Block_of_coal | Beetroot | Stone_cutter | Glowing_obsidian |
Nether_reactor_core | Unknown Int
deriving (Eq,Ord,Show)
instance T.Show Block where
showb a = showbString $ Prelude.show a
instance Enum Block where
toEnum 0 = Air
toEnum 1 = Stone
toEnum 2 = Grass
toEnum 3 = Dirt
toEnum 4 = Cobblestone
toEnum 5 = Wood_planks
toEnum 6 = Sapling
toEnum 7 = Bedrock
toEnum 8 = Water_flowing
toEnum 9 = Water_stationary
toEnum 10 = Lava_flowing
toEnum 11 = Lava_stationary
toEnum 12 = Sand
toEnum 13 = Gravel
toEnum 14 = Gold_ore
toEnum 15 = Iron_ore
toEnum 16 = Coal_ore
toEnum 17 = Wood
toEnum 18 = Leaves
toEnum 19 = Sponge
toEnum 20 = Glass
toEnum 21 = Lapis_lazuli_ore
toEnum 22 = Lapis_lazuli_block
toEnum 24 = Sandstone
toEnum 26 = Bed
toEnum 27 = Powered_rail
toEnum 30 = Cobweb
toEnum 31 = Grass_tall
toEnum 32 = Dead_bush
toEnum 35 = Wool
toEnum 37 = Flower_yellow
toEnum 38 = Flower_cyan
toEnum 39 = Mushroom_brown
toEnum 40 = Mushroom_red
toEnum 41 = Gold_block
toEnum 42 = Iron_block
toEnum 43 = Stone_slab_double
toEnum 44 = Stone_slab
toEnum 45 = Brick_block
toEnum 46 = Tnt
toEnum 47 = Bookshelf
toEnum 48 = Moss_stone
toEnum 49 = Obsidian
toEnum 50 = Torch
toEnum 51 = Fire
toEnum 53 = Stairs_wood
toEnum 54 = Chest
toEnum 56 = Diamond_ore
toEnum 57 = Diamond_block
toEnum 58 = Crafting_table
toEnum 59 = Seeds
toEnum 60 = Farmland
toEnum 61 = Furnace_inactive
toEnum 62 = Furnace_active
toEnum 63 = Sign_post
toEnum 64 = Door_wood
toEnum 65 = Ladder
toEnum 66 = Rail
toEnum 67 = Stairs_cobblestone
toEnum 68 = Wall_sign
toEnum 71 = Door_iron
toEnum 73 = Redstone_ore
toEnum 74 = Glowing_redstone_ore
toEnum 78 = Snow
toEnum 79 = Ice
toEnum 80 = Snow_block
toEnum 81 = Cactus
toEnum 82 = Clay
toEnum 83 = Sugar_cane
toEnum 85 = Fence
toEnum 86 = Pumpkin
toEnum 87 = Netherrack
toEnum 89 = Glowstone_block
toEnum 91 = Jack_o_lantern
toEnum 92 = Cake_block
toEnum 95 = Bedrock_invisible
toEnum 96 = Trapdoor
toEnum 98 = Stone_brick
toEnum 102 = Glass_pane
toEnum 103 = Melon
toEnum 104 = Pumpkin_stem
toEnum 105 = Melon_seeds
toEnum 107 = Fence_gate
toEnum 108 = Stairs_brick
toEnum 109 = Stairs_stone_brick
toEnum 112 = Nether_brick
toEnum 114 = Stairs_nether_brick
toEnum 128 = Stairs_sandstone
toEnum 129 = Emerald_ore
toEnum 134 = Stairs_spruce_wood
toEnum 135 = Stairs_birch_wood
toEnum 136 = Stairs_jungle_wood
toEnum 139 = Cobblestone_wall
toEnum 141 = Carrots
toEnum 142 = Potato
toEnum 155 = Quartz_block
toEnum 156 = Stairs_quartz
toEnum 157 = Wooden_double_slab
toEnum 158 = Wooden_slab
toEnum 170 = Hay_block
toEnum 171 = Carpet
toEnum 173 = Block_of_coal
toEnum 244 = Beetroot
toEnum 245 = Stone_cutter
toEnum 246 = Glowing_obsidian
toEnum 247 = Nether_reactor_core
toEnum i = Unknown i
fromEnum Air = 0
fromEnum Stone = 1
fromEnum Grass = 2
fromEnum Dirt = 3
fromEnum Cobblestone = 4
fromEnum Wood_planks = 5
fromEnum Sapling = 6
fromEnum Bedrock = 7
fromEnum Water_flowing = 8
fromEnum Water = 8
fromEnum Water_stationary = 9
fromEnum Lava_flowing = 10
fromEnum Lava = 10
fromEnum Lava_stationary = 11
fromEnum Sand = 12
fromEnum Gravel = 13
fromEnum Gold_ore = 14
fromEnum Iron_ore = 15
fromEnum Coal_ore = 16
fromEnum Wood = 17
fromEnum Leaves = 18
fromEnum Sponge = 19
fromEnum Glass = 20
fromEnum Lapis_lazuli_ore = 21
fromEnum Lapis_lazuli_block = 22
fromEnum Sandstone = 24
fromEnum Bed = 26
fromEnum Powered_rail = 27
fromEnum Cobweb = 30
fromEnum Grass_tall = 31
fromEnum Dead_bush = 32
fromEnum Wool = 35
fromEnum Flower_yellow = 37
fromEnum Flower_cyan = 38
fromEnum Mushroom_brown = 39
fromEnum Mushroom_red = 40
fromEnum Gold_block = 41
fromEnum Iron_block = 42
fromEnum Stone_slab_double = 43
fromEnum Stone_slab = 44
fromEnum Brick_block = 45
fromEnum Tnt = 46
fromEnum Bookshelf = 47
fromEnum Moss_stone = 48
fromEnum Obsidian = 49
fromEnum Torch = 50
fromEnum Fire = 51
fromEnum Stairs_wood = 53
fromEnum Chest = 54
fromEnum Diamond_ore = 56
fromEnum Diamond_block = 57
fromEnum Crafting_table = 58
fromEnum Seeds = 59
fromEnum Farmland = 60
fromEnum Furnace_inactive = 61
fromEnum Furnace_active = 62
fromEnum Door_wood = 64
fromEnum Sign_post = 63
fromEnum Ladder = 65
fromEnum Rail = 66
fromEnum Wall_sign = 68
fromEnum Stairs_cobblestone = 67
fromEnum Door_iron = 71
fromEnum Redstone_ore = 73
fromEnum Glowing_redstone_ore = 74
fromEnum Snow = 78
fromEnum Ice = 79
fromEnum Snow_block = 80
fromEnum Cactus = 81
fromEnum Clay = 82
fromEnum Sugar_cane = 83
fromEnum Fence = 85
fromEnum Pumpkin = 86
fromEnum Netherrack = 87
fromEnum Glowstone_block = 89
fromEnum Jack_o_lantern = 91
fromEnum Cake_block = 92
fromEnum Bedrock_invisible = 95
fromEnum Trapdoor = 96
fromEnum Stone_brick = 98
fromEnum Glass_pane = 102
fromEnum Melon = 103
fromEnum Pumpkin_stem = 104
fromEnum Melon_seeds = 105
fromEnum Fence_gate = 107
fromEnum Stairs_brick = 108
fromEnum Stairs_stone_brick = 109
fromEnum Nether_brick = 112
fromEnum Stairs_nether_brick = 114
fromEnum Stairs_sandstone = 128
fromEnum Emerald_ore = 129
fromEnum Stairs_spruce_wood = 134
fromEnum Stairs_birch_wood = 135
fromEnum Stairs_jungle_wood = 136
fromEnum Cobblestone_wall = 139
fromEnum Carrots = 141
fromEnum Potato = 142
fromEnum Quartz_block = 155
fromEnum Stairs_quartz = 156
fromEnum Wooden_double_slab = 157
fromEnum Wooden_slab = 158
fromEnum Hay_block = 170
fromEnum Carpet = 171
fromEnum Block_of_coal = 173
fromEnum Beetroot = 244
fromEnum Stone_cutter = 245
fromEnum Glowing_obsidian = 246
fromEnum Nether_reactor_core = 247
fromEnum (Unknown i) = i
| markgrebe/haskell-craft | HaskellCraft/Block.hs | bsd-3-clause | 9,287 | 0 | 8 | 3,392 | 2,185 | 1,159 | 1,026 | 247 | 0 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE OverloadedStrings #-}
module Parse where
import qualified Text.XML.Cursor as TXC
import qualified Data.Text.Lazy as TL
import qualified Data.Text as T
import qualified Data.Maybe as M
import qualified Data.ByteString.Lazy as LBS
import Text.XML as TX
import Text.XML.Cursor (Cursor, ($//), (>=>))
import Data.Default as DD
import Control.Applicative ((<$>))
import Control.Exception
import Definition
import Language
listToEither :: a -> [b] -> Either a b
listToEither exception ls = maybe (Left exception) Right elM
where elM = M.listToMaybe ls
cursorFor :: LBS.ByteString -> Either SomeException Cursor
cursorFor = fmap TXC.fromDocument . TX.parseLBS DD.def
findTextNode :: Cursor -> Either SomeException T.Text
findTextNode cursor = listToEither noTextException $ cursor $// textContentAxis
where textContentAxis = TXC.element "text" >=> TXC.child >=> TXC.content
noTextException = toException $ IndexOutOfBounds "no text element found"
wikiContentCursorFor :: Cursor -> Either SomeException Cursor
wikiContentCursorFor cursor = fmap TXC.fromDocument documentE
where wrapRoot x = T.append (T.pack "<root>") $ T.append x (T.pack "</root>")
textNodeE = wrapRoot <$> findTextNode cursor
documentE = TX.parseText DD.def . TL.fromStrict =<< textNodeE
cursorHeadElEquals :: String -> Cursor -> Bool
cursorHeadElEquals name cursor = name == elName
where node = TXC.node cursor
elName :: String
elName = case node of
NodeElement el -> T.unpack . nameLocalName $ elementName el
_ -> ""
definitionContentCursor :: Language -> Language -> Cursor -> [Cursor]
definitionContentCursor sourceLang destLang cursor = takeWhile notH2 afterCursors
where afterCursors = cursor $// TXC.attributeIs "id" (Language.heading sourceLang destLang)
>=> TXC.parent
>=> TXC.followingSibling
notH2 = not . cursorHeadElEquals "h2"
definitionList :: [Cursor] -> [T.Text]
definitionList = map formatDefinition . getListElements . getOrderedLists
where getOrderedLists = filter (cursorHeadElEquals "ol")
getListElements = filter (cursorHeadElEquals "li") . concatMap TXC.child
formatDefinition :: Cursor -> T.Text
formatDefinition cursor = T.append " * " . T.concat . filter (/= "\n") $ cursor $// TXC.content
getSections :: [Cursor] -> [(T.Text, [T.Text])]
getSections [] = []
getSections xs = let notH3 = not . cursorHeadElEquals "h3"
-- TODO this must be made safe
(h3el:h3start) = dropWhile notH3 xs
title = getSectionTitle h3el
(part, rest) = span notH3 h3start
definitions = definitionList part
in if null definitions then getSections rest
else (title, definitions) : getSections rest
getSectionTitle :: Cursor -> T.Text
getSectionTitle cursor =
let headline = cursor $// TXC.attributeIs "class" "mw-headline"
>=> TXC.child
>=> TXC.content
in M.fromMaybe "Word" $ M.listToMaybe headline
pageToDefinition :: LBS.ByteString -> T.Text -> Language -> Language -> Either SomeException Definition
pageToDefinition page word sourceLang destLang =
do cursor <- cursorFor page
contentCursor <- wikiContentCursorFor cursor
let defContent = definitionContentCursor sourceLang destLang contentCursor
let wordPartSections = getSections defContent
return Definition { word = word
, sourceLang = sourceLang
, definitionLang = destLang
, partOfSpeechList = wordPartSections
}
| aupiff/def | src/Parse.hs | bsd-3-clause | 3,886 | 0 | 13 | 1,033 | 1,005 | 528 | 477 | 73 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.TextureRectangle
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/texture_rectangle.txt ARB_texture_rectangle> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.TextureRectangle (
-- * Enums
gl_MAX_RECTANGLE_TEXTURE_SIZE_ARB,
gl_PROXY_TEXTURE_RECTANGLE_ARB,
gl_TEXTURE_BINDING_RECTANGLE_ARB,
gl_TEXTURE_RECTANGLE_ARB
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/TextureRectangle.hs | bsd-3-clause | 776 | 0 | 4 | 87 | 46 | 37 | 9 | 6 | 0 |
{-# LANGUAGE CPP #-}
-- | Phantom State Transformer type and functions.
module Control.Applicative.PhantomState (
PhantomStateT
, PhantomState
, useState
, changeState
, useAndChangeState
, runPhantomStateT
, runPhantomState
) where
import Control.Applicative
import Data.Functor.Identity
-- Conditional imports
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid (..))
#endif
#if MIN_VERSION_base(4,9,0)
import Data.Semigroup (Semigroup (..))
#endif
-- | The Phantom State Transformer is like the
-- State Monad Transformer, but it does not hold
-- any value. Therefore, it automatically discards
-- the result of any computation. Only changes in
-- the state and effects will remain. This transformer
-- produces a new 'Applicative' functor from any 'Monad'.
-- The primitive operations in this functor are:
--
-- * 'useState': Performs effects. State is unchanged.
-- * 'changeState': Changes state. No effect is performed.
-- * 'useAndChangeState': Changes state and performs effects.
--
-- Although 'useState' and 'changeState' are defined in
-- terms of 'useAndChangeState':
--
-- > useState f = useAndChangeState (\s -> f s *> pure s)
-- > changeState f = useAndChangeState (pure . f)
--
-- So 'useAndChangeState' is the only actual primitive.
--
-- Use 'runPhantomStateT' (or 'runPhantomState') to get
-- the result of a phantom state computation.
--
newtype PhantomStateT s m a = PhantomStateT (s -> m s)
-- | Type synonym of 'PhantomStateT' where the underlying 'Monad' is the 'Identity' monad.
type PhantomState s = PhantomStateT s Identity
-- | Perform an applicative action using the current state, leaving
-- the state unchanged. The result will be discarded, so only the
-- effect will remain.
useState :: Applicative m => (s -> m a) -> PhantomStateT s m ()
{-# INLINE useState #-}
useState f = useAndChangeState $ \s -> f s *> pure s
-- | Modify the state using a pure function. No effect will be produced,
-- only the state will be modified.
changeState :: Applicative m => (s -> s) -> PhantomStateT s m ()
{-# INLINE changeState #-}
changeState f = useAndChangeState $ \s -> pure (f s)
-- | Combination of 'useState' and 'changeState'. It allows you to change the state while
-- performing any effects. The new state will be the result of applying the argument
-- function to the old state. The following equations hold:
--
-- > useState f *> changeState g }
-- > } = useAndChangeState (\s -> f s *> g s)
-- > changeState g *> useState f }
--
useAndChangeState :: (s -> m s) -> PhantomStateT s m ()
{-# INLINE useAndChangeState #-}
useAndChangeState = PhantomStateT
-- | Perform a phantom state computation by setting an initial state
-- and running all the actions from there.
runPhantomStateT :: PhantomStateT s m a -- ^ Phantom state computation
-> s -- ^ Initial state
-> m s -- ^ Final result
{-# INLINE runPhantomStateT #-}
runPhantomStateT (PhantomStateT f) x = f x
-- | Specialized version of 'runPhantomStateT' where the underlying
-- 'Monad' is the 'Identity' monad.
runPhantomState :: PhantomState s a -- ^ Phantom state computation
-> s -- ^ Initial state
-> s -- ^ Final result
{-# INLINE runPhantomState #-}
runPhantomState f = runIdentity . runPhantomStateT f
-- Instances
instance Functor (PhantomStateT s m) where
{-# INLINE fmap #-}
fmap _ (PhantomStateT f) = PhantomStateT f
instance Monad m => Applicative (PhantomStateT s m) where
{-# INLINE pure #-}
pure _ = PhantomStateT return
{-# INLINE (<*>) #-}
PhantomStateT f <*> PhantomStateT g = PhantomStateT (\x -> f x >>= g)
{-# INLINE (*>) #-}
PhantomStateT f *> PhantomStateT g = PhantomStateT (\x -> f x >>= g)
{-# INLINE (<*) #-}
PhantomStateT f <* PhantomStateT g = PhantomStateT (\x -> f x >>= g)
instance (Monad m, Alternative m) => Alternative (PhantomStateT s m) where
{-# INLINE empty #-}
empty = PhantomStateT (const empty)
{-# INLINE (<|>) #-}
PhantomStateT f <|> PhantomStateT g = PhantomStateT (\x -> f x <|> g x)
instance Monad m => Monoid (PhantomStateT s m a) where
{-# INLINE mempty #-}
mempty = pure undefined
{-# INLINE mappend #-}
mappend = (*>)
#if MIN_VERSION_base(4,9,0)
instance Monad m => Semigroup (PhantomStateT s m a) where
{-# INLINE (<>) #-}
(<>) = (*>)
#endif
| Daniel-Diaz/phantom-state | Control/Applicative/PhantomState.hs | bsd-3-clause | 4,401 | 0 | 10 | 917 | 733 | 410 | 323 | 55 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Module: $HEADER$
-- Description: Type class MonadEff.
-- Copyright: (c) 2016-2017 Peter Trško
-- License: BSD3
--
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Type class 'MonadEff' is inspired by its namesake from PureScript (see
-- <https://github.com/purescript/purescript-eff purescript-eff>).
module Control.Monad.Freer.Class
(
-- * MonadEff
MonadEff(..)
, liftEffP
, weakenEff
)
where
import Control.Monad (Monad)
import Data.Function ((.), id)
import Data.Monoid (Monoid)
import Control.Monad.Freer (Eff)
import qualified Control.Monad.Freer.Internal as Internal (Eff(E, Val), qComp)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.List (ListT)
import Control.Monad.Trans.Maybe (MaybeT)
import Control.Monad.Trans.Reader (ReaderT)
import qualified Control.Monad.Trans.RWS.Lazy as Lazy (RWST)
import qualified Control.Monad.Trans.RWS.Strict as Strict (RWST)
import qualified Control.Monad.Trans.State.Lazy as Lazy (StateT)
import qualified Control.Monad.Trans.State.Strict as Strict (StateT)
import qualified Control.Monad.Trans.Writer.Lazy as Lazy (WriterT)
import qualified Control.Monad.Trans.Writer.Strict as Strict (WriterT)
import Data.FTCQueue (tsingleton)
import Data.OpenUnion (weaken)
-- | This class captures the notion that 'Eff' monad can be used as a base of a
-- monadic stack.
--
-- Example of a monadic stack where 'Eff' is used as a base monad:
--
-- @
-- type Aff effs a = 'ExceptT' err ('ContT' () ('Eff' effs)) a
-- @
--
-- In the above example 'liftEff' can be used to lift 'Eff' computation in to
-- 'Aff' computation.
--
-- Dual situation, to having 'Eff' on the bottom of monadic stack, is when
-- 'Eff' is used on top of a monadic stack. For details on how to handle such
-- situations see module "Control.Monad.Freer.Base".
class Monad m => MonadEff effs m | m -> effs where
-- | Lift 'Eff' monad in to a monad that natively supports specified
-- effects @effs :: [* -> *]@.
--
-- Sometimes the value of @effs :: [* -> *]@ is not known at the moment of
-- usage of this function. In such cases it is useful to use
-- *ScopedTypeVariables* langauge extension and pass the value of @effs ::
-- [* -> *]@ explicitly. There are two ways of doing this:
--
-- * On GHC >=8 we can use *TypeApplications* language extension to pass
-- value of @effs :: [* -> *]@ directly as @'liftEff' \@effs@ where
-- @effs@ type variable must be in scope.
--
-- * On older GHC, or when we already have a @'Proxy' effs@ type available,
-- then we can use 'liftEffP'. See its documentation for details.
liftEff :: Eff effs a -> m a
-- | Variant of 'liftEff' which allows effects to be specified explicitly using
-- a proxy type. This is useful in cases when type inference would fail without
-- explicitly knowing the exact type of @effs :: [* -> *]@.
--
-- >>> :set -XDataKinds -XTypeApplications
-- >>> import Data.Proxy
-- >>> :t liftEffP (Proxy @'[Reader Int, IO])
-- liftEffP (Proxy @'[Reader Int, IO])
-- :: MonadEff '[Reader Int, IO] m => Eff '[Reader Int, IO] a -> m a
liftEffP :: MonadEff effs m => proxy effs -> Eff effs a -> m a
liftEffP _proxy = liftEff
-- | 'Eff' monad can be embedded in to itself.
--
-- @
-- 'liftEff' = 'id'
-- @
instance MonadEff effs (Eff effs) where
liftEff = id
-- | 'Eff' monad with less effects can be injected in to an 'Eff' with strictly
-- more effects.
weakenEff :: Eff effs a -> Eff (eff ': effs) a
weakenEff = \case
Internal.Val x -> Internal.Val x
Internal.E u q -> Internal.E (weaken u) (tsingleton k)
where
k = q `Internal.qComp` weakenEff
{-# INLINEABLE weakenEff #-}
-- {{{ Monad Transformers -----------------------------------------------------
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (ContT e m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (ExceptT e m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (IdentityT m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (ListT m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (MaybeT m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance (MonadEff eff m, Monoid w) => MonadEff eff (Lazy.RWST r w s m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance (MonadEff eff m, Monoid w) => MonadEff eff (Strict.RWST r w s m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (ReaderT r m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (Lazy.StateT s m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance MonadEff eff m => MonadEff eff (Strict.StateT s m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance (MonadEff eff m, Monoid w) => MonadEff eff (Lazy.WriterT w m) where
liftEff = lift . liftEff
-- | @'liftEff' = 'lift' . 'liftEff'@
instance (MonadEff eff m, Monoid w) => MonadEff eff (Strict.WriterT w m) where
liftEff = lift . liftEff
-- }}} Monad Transformers -----------------------------------------------------
| trskop/freer-extra | src/Control/Monad/Freer/Class.hs | bsd-3-clause | 5,948 | 0 | 10 | 1,134 | 1,053 | 626 | 427 | 69 | 2 |
-- Copyright (c) 2008 Stephen C. Harris.
-- See COPYING file at the root of this distribution for copyright information.
module HMQ.Metadata.Sqlite3 where
import Control.Monad
import Control.Exception
import Text.Regex
import Data.Maybe
import Database.HDBC
import qualified Database.HDBC.Sqlite3 as S3
import qualified HMQ.Metadata.IConnectionEx as IC
import HMQ.Metadata.TableMetadata
import qualified HMQ.Metadata.TableMetadata as TMD
import HMQ.Utils.Strings
instance IC.IConnectionEx S3.Connection where
getTableIdentifiers = getTableIdentifiers
getFieldMetadatas = getFieldMetadatas
getForeignKeyConstraints = getForeignKeyConstraints
getPrimaryKeyFieldNames = getPrimaryKeyFieldNames
-- The schema name is ignored as Sqlite does not support namespaces for table names within a database.
getTableIdentifiers :: S3.Connection -> Maybe SchemaName -> IO [TableIdentifier]
getTableIdentifiers conn mSchema =
do
tableNames <- getTables conn
return $ map (TableIdentifier Nothing) tableNames
getFieldMetadatas :: S3.Connection -> TableIdentifier -> IO [FieldMetadata]
getFieldMetadatas conn tableId =
undefined -- argh!! This and the rest require parsing the contents of sqlite_master.sql column (which is the full CREATE TABLE text).
getForeignKeyConstraints :: S3.Connection -> TableIdentifier -> IO [ForeignKeyConstraint]
getForeignKeyConstraints conn tableId =
undefined
getPrimaryKeyFieldNames :: S3.Connection -> TableIdentifier -> IO [FieldName]
getPrimaryKeyFieldNames conn tableId =
undefined
| scharris/hmq | Metadata/Sqlite3_TODO.hs | bsd-3-clause | 1,641 | 0 | 10 | 308 | 262 | 148 | 114 | 30 | 1 |
import System.Environment (getArgs)
import Data.List (sort)
import Data.Bits (shiftL)
numCards :: Int
numCards = 5
cardval :: Char -> Int
cardval '2' = 2
cardval '3' = 3
cardval '4' = 4
cardval '5' = 5
cardval '6' = 6
cardval '7' = 7
cardval '8' = 8
cardval '9' = 9
cardval 'T' = 10
cardval 'J' = 11
cardval 'Q' = 12
cardval 'K' = 13
cardval 'A' = 14
cardval _ = -1
wheel :: [Int] -> [Int]
wheel [2, 3, 4, 5, 14] = [1, 2, 3, 4, 5]
wheel xs = xs
rank :: Int -> [Int] -> Int
rank x [] = x
rank x ys = rank (shiftL x 4 + last ys) (init ys)
cranks :: [String] -> [Int]
cranks xs = wheel (sort [cardval (head x) | x <- xs])
cardranks :: [String] -> Int
cardranks xs = rank 0 (cranks xs)
straight :: Int -> Bool
straight x = x0 + 1 == x1 && x1 + 1 == x2 && x2 + 1 == x3 && x3 + 1 == x4
where x0 = mod x 16
x1 = mod (div x 16) 16
x2 = mod (div x 256) 16
x3 = mod (div x 4096) 16
x4 = div x 65536
flush :: [String] -> Bool
flush [xs, ys] | last xs == last ys = True
| otherwise = False
flush (x:xs) | last x /= last (head xs) = False
| otherwise = flush xs
count :: (Eq a) => a -> [a] -> Int
count x ys = length (filter (== x) ys)
kind :: Int -> [Int] -> Int
kind x ys | x > length ys = 0
| x == c = y
| otherwise = kind x (drop c ys)
where y = head ys
c = count y ys
twopair :: Int -> Int
twopair x | x0 == x1 && x2 == x3 && x0 /= x2 && x0 /= x4 && x2 /= x4 = x0
| x0 == x1 && x3 == x4 && x0 /= x3 && x0 /= x2 && x2 /= x3 = x0
| x1 == x2 && x3 == x4 && x1 /= x3 && x0 /= x1 && x0 /= x3 = x1
| otherwise = 0
where x0 = mod x 16
x1 = mod (div x 16) 16
x2 = mod (div x 256) 16
x3 = mod (div x 4096) 16
x4 = div x 65536
handrank :: [String] -> Int
handrank hand | straight ranks && flush hand = shiftL 8 24 + ranks
| kind 4 crnks > 0 = shiftL 7 24 + shiftL (kind 4 crnks) 4 + kind 1 crnks
| kind 3 crnks > 0 && kind 2 crnks > 0 = shiftL 6 24 + shiftL (kind 3 crnks) 4 + kind 2 crnks
| flush hand = shiftL 5 24 + ranks
| straight ranks = shiftL 4 24 + ranks
| kind 3 crnks > 0 = shiftL 3 24 + shiftL (kind 3 crnks) 20 + ranks
| twopair ranks > 0 = shiftL 2 24 + shiftL (twopair ranks) 4 + kind 1 crnks
| kind 2 crnks > 0 = shiftL 1 24 + shiftL (kind 2 crnks) 20 + ranks
| otherwise = ranks
where ranks = cardranks hand
crnks = cranks hand
poker :: [String] -> String
poker xs | x > y = "left"
| x < y = "right"
| otherwise = "none"
where x = handrank (take numCards xs)
y = handrank (drop numCards xs)
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (poker . words) $ lines input
| nikai3d/ce-challenges | hard/poker_hands.hs | bsd-3-clause | 3,318 | 13 | 16 | 1,434 | 1,560 | 746 | 814 | 83 | 1 |
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Distributed.Process.Platform.Call
-- Copyright : (c) Parallel Scientific (Jeff Epstein) 2012
-- License : BSD3 (see the file LICENSE)
--
-- Maintainers : Jeff Epstein, Tim Watson
-- Stability : experimental
-- Portability : non-portable (requires concurrency)
--
-- This module provides a facility for Remote Procedure Call (rpc) style
-- interactions with Cloud Haskell processes.
--
-- Clients make synchronous calls to a running process (i.e., server) using the
-- 'callAt', 'callTimeout' and 'multicall' functions. Processes acting as the
-- server are constructed using Cloud Haskell's 'receive' family of primitives
-- and the 'callResponse' family of functions in this module.
-----------------------------------------------------------------------------
module Control.Distributed.Process.Platform.Call
( -- client API
callAt
, callTimeout
, multicall
-- server API
, callResponse
, callResponseIf
, callResponseDefer
, callResponseDeferIf
, callForward
, callResponseAsync
) where
import Control.Distributed.Process
import Control.Distributed.Process.Serializable (Serializable)
import Control.Monad (forM, forM_, join)
import Data.List (delete)
import qualified Data.Map as M
import Data.Maybe (listToMaybe)
import Data.Binary (Binary,get,put)
import Data.Typeable (Typeable)
import Control.Distributed.Process.Platform hiding (monitor, send)
import Control.Distributed.Process.Platform.Time
----------------------------------------------
-- * Multicall
----------------------------------------------
-- | Sends a message of type a to the given process, to be handled by a
-- corresponding callResponse... function, which will send back a message of
-- type b. The tag is per-process unique identifier of the transaction. If the
-- timeout expires or the target process dies, Nothing will be returned.
callTimeout :: (Serializable a, Serializable b)
=> ProcessId -> a -> Tag -> Timeout -> Process (Maybe b)
callTimeout pid msg tag time =
do res <- multicall [pid] msg tag time
return $ join (listToMaybe res)
-- | Like 'callTimeout', but with no timeout.
-- Returns Nothing if the target process dies.
callAt :: (Serializable a, Serializable b)
=> ProcessId -> a -> Tag -> Process (Maybe b)
callAt pid msg tag = callTimeout pid msg tag infiniteWait
-- | Like 'callTimeout', but sends the message to multiple
-- recipients and collects the results.
multicall :: forall a b.(Serializable a, Serializable b)
=> [ProcessId] -> a -> Tag -> Timeout -> Process [Maybe b]
multicall nodes msg tag time =
do caller <- getSelfPid
receiver <- spawnLocal $
do receiver_pid <- getSelfPid
mon_caller <- monitor caller
() <- expect
monitortags <- forM nodes monitor
forM_ nodes $ \node -> send node (Multicall, node,
receiver_pid, tag, msg)
maybeTimeout time tag receiver_pid
results <- recv nodes monitortags mon_caller
send caller (MulticallResponse,tag,results)
mon_receiver <- monitor receiver
send receiver ()
receiveWait [
matchIf (\(MulticallResponse,mtag,_) -> mtag == tag)
(\(MulticallResponse,_,val) -> return val),
matchIf (\(ProcessMonitorNotification ref _pid reason)
-> ref == mon_receiver && reason /= DiedNormal)
(\_ -> error "multicall: unexpected termination of worker")
]
where
recv nodes' monitortags mon_caller = do
resultmap <- recv1 mon_caller
(nodes', monitortags, M.empty) :: Process (M.Map ProcessId b)
return $ ordered nodes' resultmap
ordered [] _ = []
ordered (x:xs) m = M.lookup x m : ordered xs m
recv1 _ ([],_,results) = return results
recv1 _ (_,[],results) = return results
recv1 ref (nodesleft,monitortagsleft,results) =
receiveWait [
matchIf (\(ProcessMonitorNotification ref' _ _)
-> ref' == ref)
(\_ -> return Nothing)
, matchIf (\(ProcessMonitorNotification ref' pid reason) ->
ref' `elem` monitortagsleft &&
pid `elem` nodesleft
&& reason /= DiedNormal)
(\(ProcessMonitorNotification ref' pid _reason) ->
return $ Just (delete pid nodesleft,
delete ref' monitortagsleft, results))
, matchIf (\(MulticallResponse, mtag, _, _) -> mtag == tag)
(\(MulticallResponse, _, responder, msgx) ->
return $ Just (delete responder nodesleft,
monitortagsleft,
M.insert responder (msgx :: b) results))
, matchIf (\(TimeoutNotification mtag) -> mtag == tag )
(\_ -> return Nothing)
]
>>= maybe (return results) (recv1 ref)
data MulticallResponseType a =
MulticallAccept
| MulticallForward ProcessId a
| MulticallReject deriving Eq
callResponseImpl :: (Serializable a,Serializable b)
=> (a -> MulticallResponseType c) ->
(a -> (b -> Process())-> Process c) -> Match c
callResponseImpl cond proc =
matchIf (\(Multicall,_responder,_,_,msg) ->
case cond msg of
MulticallReject -> False
_ -> True)
(\wholemsg@(Multicall,responder,sender,tag,msg) ->
case cond msg of
-- TODO: sender should get a ProcessMonitorNotification if
-- our target dies, or we should link to it (?)
MulticallForward target ret -> send target wholemsg >> return ret
-- TODO: use `die Reason` when issue #110 is resolved
MulticallReject -> error "multicallResponseImpl: Indecisive condition"
MulticallAccept ->
let resultSender tosend =
send sender (MulticallResponse,
tag::Tag,
responder::ProcessId,
tosend)
in proc msg resultSender)
-- | Produces a Match that can be used with the 'receiveWait' family of
-- message-receiving functions. @callResponse@ will respond to a message of
-- type a sent by 'callTimeout', and will respond with a value of type b.
callResponse :: (Serializable a,Serializable b)
=> (a -> Process (b,c)) -> Match c
callResponse = callResponseIf (const True)
callResponseDeferIf :: (Serializable a,Serializable b)
=> (a -> Bool)
-> (a -> (b -> Process()) -> Process c)
-> Match c
callResponseDeferIf cond =
callResponseImpl (\msg ->
if cond msg
then MulticallAccept
else MulticallReject)
callResponseDefer :: (Serializable a,Serializable b)
=> (a -> (b -> Process())-> Process c) -> Match c
callResponseDefer = callResponseDeferIf (const True)
-- | Produces a Match that can be used with the 'receiveWait' family of
-- message-receiving functions. When calllForward receives a message of type
-- from from 'callTimeout' (and similar), it will forward the message to another
-- process, who will be responsible for responding to it. It is the user's
-- responsibility to ensure that the forwarding process is linked to the
-- destination process, so that if it fails, the sender will be notified.
callForward :: Serializable a => (a -> (ProcessId, c)) -> Match c
callForward proc =
callResponseImpl
(\msg -> let (pid, ret) = proc msg
in MulticallForward pid ret )
(\_ sender ->
(sender::(() -> Process ())) `mention`
error "multicallForward: Indecisive condition")
-- | The message handling code is started in a separate thread. It's not
-- automatically linked to the calling thread, so if you want it to be
-- terminated when the message handling thread dies, you'll need to call
-- link yourself.
callResponseAsync :: (Serializable a,Serializable b)
=> (a -> Maybe c) -> (a -> Process b) -> Match c
callResponseAsync cond proc =
callResponseImpl
(\msg ->
case cond msg of
Nothing -> MulticallReject
Just _ -> MulticallAccept)
(\msg sender ->
do _ <- spawnLocal $ -- TODO linkOnFailure to spawned procss
do val <- proc msg
sender val
case cond msg of
Nothing -> error "multicallResponseAsync: Indecisive condition"
Just ret -> return ret )
callResponseIf :: (Serializable a,Serializable b)
=> (a -> Bool) -> (a -> Process (b,c)) -> Match c
callResponseIf cond proc =
callResponseImpl
(\msg ->
case cond msg of
True -> MulticallAccept
False -> MulticallReject)
(\msg sender ->
do (tosend,toreturn) <- proc msg
sender tosend
return toreturn)
maybeTimeout :: Timeout -> Tag -> ProcessId -> Process ()
maybeTimeout Nothing _ _ = return ()
maybeTimeout (Just time) tag p = timeout time tag p
----------------------------------------------
-- * Private types
----------------------------------------------
mention :: a -> b -> b
mention _a b = b
data Multicall = Multicall
deriving (Typeable)
instance Binary Multicall where
get = return Multicall
put _ = return ()
data MulticallResponse = MulticallResponse
deriving (Typeable)
instance Binary MulticallResponse where
get = return MulticallResponse
put _ = return ()
| haskell-distributed/distributed-process-platform | src/Control/Distributed/Process/Platform/Call.hs | bsd-3-clause | 10,089 | 0 | 17 | 2,995 | 2,210 | 1,183 | 1,027 | 168 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.