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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE RecordWildCards, PatternGuards, ScopedTypeVariables #-}
module Text.HTML.TagSoup.Implementation where
import Text.HTML.TagSoup.Type
import Text.HTML.TagSoup.Options
import Text.StringLike as Str
import Numeric
import Data.Char
import Data.Ix
import Control.Exception(assert)
import Control.Arrow
---------------------------------------------------------------------
-- BOTTOM LAYER
data Out
= Char Char
| Tag -- <
| TagShut -- </
| AttName
| AttVal
| TagEnd -- >
| TagEndClose -- />
| Comment -- <!--
| CommentEnd -- -->
| EntityName -- &
| EntityNum -- &#
| EntityHex -- &#x
| EntityEnd Bool -- Attributed followed by ; for True, missing ; for False
| Warn String
| Pos Position
deriving (Show,Eq)
errSeen x = Warn $ "Unexpected " ++ show x
errWant x = Warn $ "Expected " ++ show x
data S = S
{s :: S
,tl :: S
,hd :: Char
,eof :: Bool
,next :: String -> Maybe S
,pos :: [Out] -> [Out]
}
expand :: Position -> String -> S
expand p text = res
where res = S{s = res
,tl = expand (positionChar p (head text)) (tail text)
,hd = if null text then '\0' else head text
,eof = null text
,next = next p text
,pos = (Pos p:)
}
next p (t:ext) (s:tr) | t == s = next (positionChar p t) ext tr
next p text [] = Just $ expand p text
next _ _ _ = Nothing
infixr &
class Outable a where (&) :: a -> [Out] -> [Out]
instance Outable Char where (&) = ampChar
instance Outable Out where (&) = ampOut
ampChar x y = Char x : y
ampOut x y = x : y
state :: String -> S
state s = expand nullPosition s
---------------------------------------------------------------------
-- TOP LAYER
output :: forall str . StringLike str => ParseOptions str -> [Out] -> [Tag str]
output ParseOptions{..} x = (if optTagTextMerge then tagTextMerge else id) $ go ((nullPosition,[]),x)
where
-- main choice loop
go :: ((Position,[Tag str]),[Out]) -> [Tag str]
go ((p,ws),xs) | p `seq` False = [] -- otherwise p is a space leak when optTagPosition == False
go ((p,ws),xs) | not $ null ws = (if optTagWarning then (reverse ws++) else id) $ go ((p,[]),xs)
go ((p,ws),Pos p2:xs) = go ((p2,ws),xs)
go x | isChar x = pos x $ TagText a : go y
where (y,a) = charsStr x
go x | isTag x = pos x $ TagOpen a b : (if isTagEndClose z then pos x $ TagClose a : go (next z) else go (skip isTagEnd z))
where (y,a) = charsStr $ next x
(z,b) = atts y
go x | isTagShut x = pos x $ (TagClose a:) $
(if not (null b) then warn x "Unexpected attributes in close tag" else id) $
if isTagEndClose z then warn x "Unexpected self-closing in close tag" $ go (next z) else go (skip isTagEnd z)
where (y,a) = charsStr $ next x
(z,b) = atts y
go x | isComment x = pos x $ TagComment a : go (skip isCommentEnd y)
where (y,a) = charsStr $ next x
go x | isEntityName x = poss x ((if optTagWarning then id else filter (not . isTagWarning)) $ optEntityData (a, getEntityEnd y)) ++ go (skip isEntityEnd y)
where (y,a) = charsStr $ next x
go x | isEntityNumHex x = pos x $ TagText (fromChar $ entityChr x a) : go (skip isEntityEnd y)
where (y,a) = chars $ next x
go x | Just a <- fromWarn x = if optTagWarning then pos x $ TagWarning (fromString a) : go (next x) else go (next x)
go x | isEof x = []
atts :: ((Position,[Tag str]),[Out]) -> ( ((Position,[Tag str]),[Out]) , [(str,str)] )
atts x | isAttName x = second ((a,b):) $ atts z
where (y,a) = charsStr (next x)
(z,b) = if isAttVal y then charsEntsStr (next y) else (y, empty)
atts x | isAttVal x = second ((empty,a):) $ atts y
where (y,a) = charsEntsStr (next x)
atts x = (x, [])
-- chars
chars x = charss False x
charsStr x = (id *** fromString) $ chars x
charsEntsStr x = (id *** fromString) $ charss True x
-- loop round collecting characters, if the b is set including entity
charss :: Bool -> ((Position,[Tag str]),[Out]) -> ( ((Position,[Tag str]),[Out]) , String)
charss t x | Just a <- fromChr x = (y, a:b)
where (y,b) = charss t (next x)
charss t x | t, isEntityName x = second (toString n ++) $ charss t $ addWarns m z
where (y,a) = charsStr $ next x
b = getEntityEnd y
z = skip isEntityEnd y
(n,m) = optEntityAttrib (a,b)
charss t x | t, isEntityNumHex x = second (entityChr x a:) $ charss t z
where (y,a) = chars $ next x
z = skip isEntityEnd y
charss t ((_,w),Pos p:xs) = charss t ((p,w),xs)
charss t x | Just a <- fromWarn x = charss t $ (if optTagWarning then addWarns [TagWarning $ fromString a] else id) $ next x
charss t x = (x, [])
-- utility functions
next x = second (drop 1) x
skip f x = assert (isEof x || f x) (next x)
addWarns ws x@((p,w),y) = ((p, reverse (poss x ws) ++ w), y)
pos ((p,_),_) rest = if optTagPosition then tagPosition p : rest else rest
warn x s rest = if optTagWarning then pos x $ TagWarning (fromString s) : rest else rest
poss x = concatMap (\w -> pos x [w])
entityChr x s | isEntityNum x = chr_ $ read s
| isEntityHex x = chr_ $ fst $ head $ readHex s
where chr_ x | inRange (toInteger $ ord minBound, toInteger $ ord maxBound) x = chr $ fromInteger x
| otherwise = '?'
isEof (_,[]) = True; isEof _ = False
isChar (_,Char{}:_) = True; isChar _ = False
isTag (_,Tag{}:_) = True; isTag _ = False
isTagShut (_,TagShut{}:_) = True; isTagShut _ = False
isAttName (_,AttName{}:_) = True; isAttName _ = False
isAttVal (_,AttVal{}:_) = True; isAttVal _ = False
isTagEnd (_,TagEnd{}:_) = True; isTagEnd _ = False
isTagEndClose (_,TagEndClose{}:_) = True; isTagEndClose _ = False
isComment (_,Comment{}:_) = True; isComment _ = False
isCommentEnd (_,CommentEnd{}:_) = True; isCommentEnd _ = False
isEntityName (_,EntityName{}:_) = True; isEntityName _ = False
isEntityNumHex (_,EntityNum{}:_) = True; isEntityNumHex (_,EntityHex{}:_) = True; isEntityNumHex _ = False
isEntityNum (_,EntityNum{}:_) = True; isEntityNum _ = False
isEntityHex (_,EntityHex{}:_) = True; isEntityHex _ = False
isEntityEnd (_,EntityEnd{}:_) = True; isEntityEnd _ = False
isWarn (_,Warn{}:_) = True; isWarn _ = False
fromChr (_,Char x:_) = Just x ; fromChr _ = Nothing
fromWarn (_,Warn x:_) = Just x ; fromWarn _ = Nothing
getEntityEnd (_,EntityEnd b:_) = b
-- Merge all adjacent TagText bits
tagTextMerge :: StringLike str => [Tag str] -> [Tag str]
tagTextMerge (TagText x:xs) = TagText (strConcat (x:a)) : tagTextMerge b
where
(a,b) = f xs
-- additional brackets on 3 lines to work around HSE 1.3.2 bugs with pattern fixities
f (TagText x:xs) = (x:a,b)
where (a,b) = f xs
f (TagPosition{}:(x@TagText{}:xs)) = f $ x : xs
f x = g x id x
g o op (p@TagPosition{}:(w@TagWarning{}:xs)) = g o (op . (p:) . (w:)) xs
g o op (w@TagWarning{}:xs) = g o (op . (w:)) xs
g o op (p@TagPosition{}:(x@TagText{}:xs)) = f $ p : x : op xs
g o op (x@TagText{}:xs) = f $ x : op xs
g o op _ = ([], o)
tagTextMerge (x:xs) = x : tagTextMerge xs
tagTextMerge [] = []
|
silkapp/tagsoup
|
Text/HTML/TagSoup/Implementation.hs
|
bsd-3-clause
| 7,682 | 0 | 16 | 2,301 | 3,571 | 1,884 | 1,687 | 146 | 29 |
module Main where
import Criterion.Types
import Criterion.Main
import Control.DeepSeq
import Data.List
import Data.Maybe
import qualified Data.HashMap.Strict as M
import qualified Data.LinkedHashSet as LS
import qualified Data.LinkedHashMap.Seq as LM1
import qualified Data.LinkedHashMap.IntMap as LM2
deep :: NFData a => a -> a
deep a = deepseq a a
keys :: [Int]
keys = reverse $ take 100000 $ [0..]
rkeys :: [Int]
rkeys = reverse $ keys
intIntPairs :: [(Int, Int)]
intIntPairs = deep $ zip keys [0..]
insertAll :: (Int -> Int -> m -> m) -> [(Int, Int)] -> m -> m
insertAll ins kvs m0 = foldl' (\m (k, v) -> ins k v m) m0 kvs
deleteAll :: (Int -> m -> m) -> [Int] -> m -> m
deleteAll del ks m0 = foldl' (\m k -> del k m) m0 ks
lookupAll :: (Int -> m -> Maybe Int) -> [Int] -> m -> [Int]
lookupAll look ks m0 = map (\k -> fromJust $ look k m0) ks
setInsertAll :: (Int -> s -> s) -> [Int] -> s -> s
setInsertAll ins ks s0 = foldl' (\s k -> ins k s) s0 ks
setLookupAll :: [Int] -> LS.LinkedHashSet Int -> [Bool]
setLookupAll ks s0 = map (\k -> LS.member k s0) ks
benchmarks :: [Benchmark]
benchmarks = [bgroup "fromList" [
bench "HashMap.Strict" $ nf M.fromList intIntPairs,
bench "LinkedHashMap.Seq" $ nf LM1.fromList intIntPairs,
bench "LinkedHashMap.IntMap" $ nf LM2.fromList intIntPairs,
bench "LinkedHashSet" $ nf LS.fromList keys
],
bgroup "insert" [
bench "HashMap.Strict" $ nf (insertAll M.insert intIntPairs) M.empty,
bench "LinkedHashMap.Seq" $ nf (insertAll LM1.insert intIntPairs) LM1.empty,
bench "LinkedHashMap.IntMap" $ nf (insertAll LM2.insert intIntPairs) LM2.empty,
bench "LinkedHashSet" $ nf (setInsertAll LS.insert keys) LS.empty
],
bgroup "toList" [
bench "HashMap.Strict" $ nf M.toList m0,
bench "LinkedHashMap.Seq" $ nf LM1.toList m1,
bench "LinkedHashMap.IntMap" $ nf LM2.toList m2,
bench "LinkedHashSet" $ nf LS.toList s1
],
bgroup "lookup" [
bench "HashMap.Strict" $ nf (lookupAll M.lookup rkeys) m0,
bench "LinkedHashMap.Seq" $ nf (lookupAll LM1.lookup rkeys) m1,
bench "LinkedHashMap.IntMap" $ nf (lookupAll LM2.lookup rkeys) m2,
bench "LinkedHashSet" $ nf (setLookupAll rkeys) s1
],
bgroup "delete" [
bench "HashMap.Strict" $ nf (deleteAll M.delete rkeys) m0,
bench "LinkedHashMap.Seq" $ nf (deleteAll LM1.delete rkeys) m1,
bench "LinkedHashMap.IntMap" $ nf (deleteAll LM2.delete rkeys) m2,
bench "LinkedHashSet" $ nf (deleteAll LS.delete rkeys) s1
]
]
where
m0 = deep $ M.fromList intIntPairs
m1 = deep $ LM1.fromList intIntPairs
m2 = deep $ LM2.fromList intIntPairs
s1 = deep $ LS.fromList keys
myConfig :: Config
myConfig = defaultConfig {
resamples = 1000,
reportFile = Just "report.html"
}
report :: IO ()
report = defaultMainWith myConfig benchmarks
main :: IO ()
main = defaultMain benchmarks
|
abasko/linkedhashmap
|
benchmarks/Main.hs
|
bsd-3-clause
| 3,569 | 0 | 12 | 1,278 | 1,122 | 582 | 540 | 66 | 1 |
module Network.Webmachine.Resource where
|
SaneApp/webmachine
|
src/Network/Webmachine/Resource.hs
|
bsd-3-clause
| 41 | 0 | 3 | 3 | 7 | 5 | 2 | 1 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{- |
This module has its own /internal exception type/ that it hides from you.
All "Control.Exception"-like functions here only work with that type;
'try' only catches exceptions of that type;
'throw' only throws exceptions of that type.
-}
module Error where
import qualified Control.Exception as Ex
import qualified Control.Monad as M
import qualified Control.Error as E
import qualified Error_internal as Ei
-- * Catching
{- |
This is a specialization of 'Ex.try' in "Control.Exception"
that only catches this module's internal exception type.
-}
try :: IO a -> IO (Either String a)
try = fmap (either (Left . Ei.un_exc) Right) . Ex.try
{- |
This is like 'Ex.handle' but this uses 'Ex.try'
instead of 'Ex.catch', and
this only catches exceptions whose type is
this module's internal exception type.
-}
handle_try :: (String -> IO a) -> IO a -> IO a
handle_try h = try M.>=> either h return
{- |
This is like 'handle_try' but this ignores return values.
-}
handle_try_ :: (String -> IO a) -> IO b -> IO ()
handle_try_ h = try M.>=> either (M.void . h) (M.void . return)
-- * Throwing
{- |
This uses 'Ex.throwIO' (not 'Ex.throw') from "Control.Exception".
This throws an exception whose type is this module's internal exception type.
-}
class Throw e where
throw :: e -> IO a
-- | overlappable
instance {-# OVERLAPPABLE #-} (Show e) => Throw e where
throw = Ex.throwIO . Ei.Mk_exc . show
instance Throw String where
throw = Ex.throwIO . Ei.Mk_exc
-- * Rethrowing
{- |
Modify the error message.
If @x@ throws error message @e@,
then @map_error f x@ throws error message @f e@.
-}
map_error :: (String -> String) -> IO a -> IO a
map_error f = try M.>=> either (throw . f) return
{- |
Prepend a string to every error message thrown by the given computation.
@
prepend str = 'map_error' (str '++')
@
You can get something similar to a stack trace.
For example, this should print @a: b: c: message@
@
main = 'handle_try_' 'putStrLn' a
a = prepend \"a: \" b
b = prepend \"b: \" c
c = prepend \"c: \" '$' 'throw' \"message\"
@
You can also show some arguments to help you debug the program later.
@
e_div x y =
prepend (\"e_div \" '++' 'show' x '++' 'show' y) '$' f x y
where
f x 0 = 'throw' \"division by zero\"
f x y = 'div' x y
@
-}
prepend :: String -> IO a -> IO a
prepend str = map_error (str ++)
{- |
Convert certain exceptions thrown by the computation
to this module's internal exception type.
For example,
when working with the @http-conduit@ package,
you may want to use this:
@
gulp (\\ e -> 'show' (e :: HttpException)) computation
@
If the computation throws several types of exception,
you will need many @gulp@s.
You need one for each type of exception
that the computation can throw.
@
gulp (\\ e -> 'show' (e :: Exception0))
'$' gulp (\\ e -> 'show' (e :: Exception1))
'$' ...
'$' gulp (\\ e -> 'show' (e :: ExceptionM))
'$' computation
@
The code is slightly unsightly but not much can be done about it
because we cannot pass a type as an argument
to a value-level function in Haskell.
(We can do that in Template Haskell though.)
-}
gulp :: (Ex.Exception e) => (e -> String) -> IO a -> IO a
gulp format = Ex.try M.>=> either (throw . format) return
-- * Interoperation
{- $
This is for working with other failure-indicating
and error-handling mechanisms.
-}
{- |
The 'transform' function converts between implicit
and explicit style of indicating failures
by inserting 'try' and 'throw' as appropriate.
Remember that this function only works
with this module's internal exception type.
Example of implicit style (type does not have error type):
@
'IO' a
@
Example of explicit style (type has error type):
@
'IO' ('Either' 'String' a)
'E.ExceptT' 'String' 'IO' a
@
-}
class Transform a b where
transform :: a -> b
-- explicit to implicit
-- Either e a -> IO a
-- | overlappable
instance {-# OVERLAPPABLE #-} (Show e) => Transform (Either e a) (IO a) where
transform = either (throw . show) return
instance Transform (Either String a) (IO a) where
transform = either throw return
-- IO (Either e a) -> IO a
-- | overlappable
instance {-# OVERLAPPABLE #-} (Show e) => Transform (IO (Either e a)) (IO a) where
transform = M.join . fmap (either (throw . show) return)
instance Transform (IO (Either String a)) (IO a) where
transform = M.join . fmap (either throw return)
-- ExceptT e IO a -> IO a
instance {-# OVERLAPPABLE #-} (Show e) => Transform (E.ExceptT e IO a) (IO a) where
transform = E.runExceptT M.>=> either (throw . show) return
instance Transform (E.ExceptT String IO a) (IO a) where
transform = E.runExceptT M.>=> either throw return
-- implicit to explicit
-- IO a -> IO (Either String a)
instance Transform (IO a) (IO (Either String a)) where
transform = try
-- IO a -> ExceptT String IO a
instance Transform (IO a) (E.ExceptT String IO a) where
transform = E.ExceptT . try
|
edom/pragmatic
|
src/Error.hs
|
bsd-3-clause
| 5,034 | 0 | 11 | 1,008 | 868 | 463 | 405 | 44 | 1 |
--------------------------------------------------------------------
-- |
-- Module : XMonad.Util.EZConfig
-- Copyright : Devin Mullins <[email protected]>
-- Brent Yorgey <[email protected]> (key parsing)
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Devin Mullins <[email protected]>
--
-- Useful helper functions for amending the default configuration, and for
-- parsing keybindings specified in a special (emacs-like) format.
--
-- (See also "XMonad.Util.CustomKeys" in xmonad-contrib.)
--
--------------------------------------------------------------------
module XMonad.Util.EZConfig (
-- * Usage
-- $usage
-- * Adding or removing keybindings
additionalKeys, additionalKeysP,
removeKeys, removeKeysP,
additionalMouseBindings, removeMouseBindings,
-- * Emacs-style keybinding specifications
mkKeymap, checkKeymap,
mkNamedKeymap,
parseKey -- used by XMonad.Util.Paste
) where
import XMonad
import XMonad.Actions.Submap
import XMonad.Util.NamedActions
import qualified Data.Map as M
import Data.List (foldl', sortBy, groupBy, nub)
import Data.Ord (comparing)
import Data.Maybe
import Control.Arrow (first, (&&&))
import Text.ParserCombinators.ReadP
-- $usage
-- To use this module, first import it into your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Util.EZConfig
--
-- Then, use one of the provided functions to modify your
-- configuration. You can use 'additionalKeys', 'removeKeys',
-- 'additionalMouseBindings', and 'removeMouseBindings' to easily add
-- and remove keybindings or mouse bindings. You can use 'mkKeymap'
-- to create a keymap using emacs-style keybinding specifications
-- like @\"M-x\"@ instead of @(modMask, xK_x)@, or 'additionalKeysP'
-- and 'removeKeysP' to easily add or remove emacs-style keybindings.
-- If you use emacs-style keybindings, the 'checkKeymap' function is
-- provided, suitable for adding to your 'startupHook', which can warn
-- you of any parse errors or duplicate bindings in your keymap.
--
-- For more information and usage examples, see the documentation
-- provided with each exported function, and check the xmonad config
-- archive (<http://haskell.org/haskellwiki/Xmonad/Config_archive>)
-- for some real examples of use.
-- |
-- Add or override keybindings from the existing set. Example use:
--
-- > main = xmonad $ def { terminal = "urxvt" }
-- > `additionalKeys`
-- > [ ((mod1Mask, xK_m ), spawn "echo 'Hi, mom!' | dzen2 -p 4")
-- > , ((mod1Mask, xK_BackSpace), withFocused hide) -- N.B. this is an absurd thing to do
-- > ]
--
-- This overrides the previous definition of mod-m.
--
-- Note that, unlike in xmonad 0.4 and previous, you can't use modMask to refer
-- to the modMask you configured earlier. You must specify mod1Mask (or
-- whichever), or add your own @myModMask = mod1Mask@ line.
additionalKeys :: XConfig a -> [((KeyMask, KeySym), X ())] -> XConfig a
additionalKeys conf keyList =
conf { keys = \cnf -> M.union (M.fromList keyList) (keys conf cnf) }
-- | Like 'additionalKeys', except using short @String@ key
-- descriptors like @\"M-m\"@ instead of @(modMask, xK_m)@, as
-- described in the documentation for 'mkKeymap'. For example:
--
-- > main = xmonad $ def { terminal = "urxvt" }
-- > `additionalKeysP`
-- > [ ("M-m", spawn "echo 'Hi, mom!' | dzen2 -p 4")
-- > , ("M-<Backspace>", withFocused hide) -- N.B. this is an absurd thing to do
-- > ]
additionalKeysP :: XConfig l -> [(String, X ())] -> XConfig l
additionalKeysP conf keyList =
conf { keys = \cnf -> M.union (mkKeymap cnf keyList) (keys conf cnf) }
-- |
-- Remove standard keybindings you're not using. Example use:
--
-- > main = xmonad $ def { terminal = "urxvt" }
-- > `removeKeys` [(mod1Mask .|. shiftMask, n) | n <- [xK_1 .. xK_9]]
removeKeys :: XConfig a -> [(KeyMask, KeySym)] -> XConfig a
removeKeys conf keyList =
conf { keys = \cnf -> keys conf cnf `M.difference` M.fromList (zip keyList $ repeat ()) }
-- | Like 'removeKeys', except using short @String@ key descriptors
-- like @\"M-m\"@ instead of @(modMask, xK_m)@, as described in the
-- documentation for 'mkKeymap'. For example:
--
-- > main = xmonad $ def { terminal = "urxvt" }
-- > `removeKeysP` ["M-S-" ++ [n] | n <- ['1'..'9']]
removeKeysP :: XConfig l -> [String] -> XConfig l
removeKeysP conf keyList =
conf { keys = \cnf -> keys conf cnf `M.difference` mkKeymap cnf (zip keyList $ repeat (return ())) }
-- | Like 'additionalKeys', but for mouse bindings.
additionalMouseBindings :: XConfig a -> [((ButtonMask, Button), Window -> X ())] -> XConfig a
additionalMouseBindings conf mouseBindingsList =
conf { mouseBindings = \cnf -> M.union (M.fromList mouseBindingsList) (mouseBindings conf cnf) }
-- | Like 'removeKeys', but for mouse bindings.
removeMouseBindings :: XConfig a -> [(ButtonMask, Button)] -> XConfig a
removeMouseBindings conf mouseBindingList =
conf { mouseBindings = \cnf -> mouseBindings conf cnf `M.difference`
M.fromList (zip mouseBindingList $ repeat ()) }
--------------------------------------------------------------
-- Keybinding parsing ---------------------------------------
--------------------------------------------------------------
-- | Given a config (used to determine the proper modifier key to use)
-- and a list of @(String, X ())@ pairs, create a key map by parsing
-- the key sequence descriptions contained in the Strings. The key
-- sequence descriptions are \"emacs-style\": @M-@, @C-@, @S-@, and
-- @M\#-@ denote mod, control, shift, and mod1-mod5 (where @\#@ is
-- replaced by the appropriate number) respectively. Note that if
-- you want to make a keybinding using \'alt\' even though you use a
-- different key (like the \'windows\' key) for \'mod\', you can use
-- something like @\"M1-x\"@ for alt+x (check the output of @xmodmap@
-- to see which mod key \'alt\' is bound to). Some special keys can
-- also be specified by enclosing their name in angle brackets.
--
-- For example, @\"M-C-x\"@ denotes mod+ctrl+x; @\"S-\<Escape\>\"@
-- denotes shift-escape; @\"M1-C-\<Delete\>\"@ denotes alt+ctrl+delete
-- (assuming alt is bound to mod1, which is common).
--
-- Sequences of keys can also be specified by separating the key
-- descriptions with spaces. For example, @\"M-x y \<Down\>\"@ denotes the
-- sequence of keys mod+x, y, down. Submaps (see
-- "XMonad.Actions.Submap") will be automatically generated to
-- correctly handle these cases.
--
-- So, for example, a complete key map might be specified as
--
-- > keys = \c -> mkKeymap c $
-- > [ ("M-S-<Return>", spawn $ terminal c)
-- > , ("M-x w", spawn "xmessage 'woohoo!'") -- type mod+x then w to pop up 'woohoo!'
-- > , ("M-x y", spawn "xmessage 'yay!'") -- type mod+x then y to pop up 'yay!'
-- > , ("M-S-c", kill)
-- > ]
--
-- Alternatively, you can use 'additionalKeysP' to automatically
-- create a keymap and add it to your config.
--
-- Here is a complete list of supported special keys. Note that a few
-- keys, such as the arrow keys, have synonyms. If there are other
-- special keys you would like to see supported, feel free to submit a
-- patch, or ask on the xmonad mailing list; adding special keys is
-- quite simple.
--
-- > <Backspace>
-- > <Tab>
-- > <Return>
-- > <Pause>
-- > <Scroll_lock>
-- > <Sys_Req>
-- > <Print>
-- > <Escape>, <Esc>
-- > <Delete>
-- > <Home>
-- > <Left>, <L>
-- > <Up>, <U>
-- > <Right>, <R>
-- > <Down>, <D>
-- > <Page_Up>
-- > <Page_Down>
-- > <End>
-- > <Insert>
-- > <Break>
-- > <Space>
-- > <F1>-<F24>
-- > <KP_Space>
-- > <KP_Tab>
-- > <KP_Enter>
-- > <KP_F1>
-- > <KP_F2>
-- > <KP_F3>
-- > <KP_F4>
-- > <KP_Home>
-- > <KP_Left>
-- > <KP_Up>
-- > <KP_Right>
-- > <KP_Down>
-- > <KP_Prior>
-- > <KP_Page_Up>
-- > <KP_Next>
-- > <KP_Page_Down>
-- > <KP_End>
-- > <KP_Begin>
-- > <KP_Insert>
-- > <KP_Delete>
-- > <KP_Equal>
-- > <KP_Multiply>
-- > <KP_Add>
-- > <KP_Separator>
-- > <KP_Subtract>
-- > <KP_Decimal>
-- > <KP_Divide>
-- > <KP_0>-<KP_9>
--
-- Long list of multimedia keys. Please note that not all keys may be
-- present in your particular setup although most likely they will do.
--
-- > <XF86ModeLock>
-- > <XF86MonBrightnessUp>
-- > <XF86MonBrightnessDown>
-- > <XF86KbdLightOnOff>
-- > <XF86KbdBrightnessUp>
-- > <XF86KbdBrightnessDown>
-- > <XF86Standby>
-- > <XF86AudioLowerVolume>
-- > <XF86AudioMute>
-- > <XF86AudioRaiseVolume>
-- > <XF86AudioPlay>
-- > <XF86AudioStop>
-- > <XF86AudioPrev>
-- > <XF86AudioNext>
-- > <XF86HomePage>
-- > <XF86Mail>
-- > <XF86Start>
-- > <XF86Search>
-- > <XF86AudioRecord>
-- > <XF86Calculator>
-- > <XF86Memo>
-- > <XF86ToDoList>
-- > <XF86Calendar>
-- > <XF86PowerDown>
-- > <XF86ContrastAdjust>
-- > <XF86RockerUp>
-- > <XF86RockerDown>
-- > <XF86RockerEnter>
-- > <XF86Back>
-- > <XF86Forward>
-- > <XF86Stop>
-- > <XF86Refresh>
-- > <XF86PowerOff>
-- > <XF86WakeUp>
-- > <XF86Eject>
-- > <XF86ScreenSaver>
-- > <XF86WWW>
-- > <XF86Sleep>
-- > <XF86Favorites>
-- > <XF86AudioPause>
-- > <XF86AudioMedia>
-- > <XF86MyComputer>
-- > <XF86VendorHome>
-- > <XF86LightBulb>
-- > <XF86Shop>
-- > <XF86History>
-- > <XF86OpenURL>
-- > <XF86AddFavorite>
-- > <XF86HotLinks>
-- > <XF86BrightnessAdjust>
-- > <XF86Finance>
-- > <XF86Community>
-- > <XF86AudioRewind>
-- > <XF86XF86BackForward>
-- > <XF86Launch0>-<XF86Launch9>, <XF86LaunchA>-<XF86LaunchF>
-- > <XF86ApplicationLeft>
-- > <XF86ApplicationRight>
-- > <XF86Book>
-- > <XF86CD>
-- > <XF86Calculater>
-- > <XF86Clear>
-- > <XF86Close>
-- > <XF86Copy>
-- > <XF86Cut>
-- > <XF86Display>
-- > <XF86DOS>
-- > <XF86Documents>
-- > <XF86Excel>
-- > <XF86Explorer>
-- > <XF86Game>
-- > <XF86Go>
-- > <XF86iTouch>
-- > <XF86LogOff>
-- > <XF86Market>
-- > <XF86Meeting>
-- > <XF86MenuKB>
-- > <XF86MenuPB>
-- > <XF86MySites>
-- > <XF86New>
-- > <XF86News>
-- > <XF86OfficeHome>
-- > <XF86Open>
-- > <XF86Option>
-- > <XF86Paste>
-- > <XF86Phone>
-- > <XF86Q>
-- > <XF86Reply>
-- > <XF86Reload>
-- > <XF86RotateWindows>
-- > <XF86RotationPB>
-- > <XF86RotationKB>
-- > <XF86Save>
-- > <XF86ScrollUp>
-- > <XF86ScrollDown>
-- > <XF86ScrollClick>
-- > <XF86Send>
-- > <XF86Spell>
-- > <XF86SplitScreen>
-- > <XF86Support>
-- > <XF86TaskPane>
-- > <XF86Terminal>
-- > <XF86Tools>
-- > <XF86Travel>
-- > <XF86UserPB>
-- > <XF86User1KB>
-- > <XF86User2KB>
-- > <XF86Video>
-- > <XF86WheelButton>
-- > <XF86Word>
-- > <XF86Xfer>
-- > <XF86ZoomIn>
-- > <XF86ZoomOut>
-- > <XF86Away>
-- > <XF86Messenger>
-- > <XF86WebCam>
-- > <XF86MailForward>
-- > <XF86Pictures>
-- > <XF86Music>
-- > <XF86TouchpadToggle>
-- > <XF86AudioMicMute>
-- > <XF86_Switch_VT_1>-<XF86_Switch_VT_12>
-- > <XF86_Ungrab>
-- > <XF86_ClearGrab>
-- > <XF86_Next_VMode>
-- > <XF86_Prev_VMode>
mkKeymap :: XConfig l -> [(String, X ())] -> M.Map (KeyMask, KeySym) (X ())
mkKeymap c = M.fromList . mkSubmaps . readKeymap c
mkNamedKeymap :: XConfig l -> [(String, NamedAction)] -> [((KeyMask, KeySym), NamedAction)]
mkNamedKeymap c = mkNamedSubmaps . readKeymap c
-- | Given a list of pairs of parsed key sequences and actions,
-- group them into submaps in the appropriate way.
mkNamedSubmaps :: [([(KeyMask, KeySym)], NamedAction)] -> [((KeyMask, KeySym), NamedAction)]
mkNamedSubmaps = mkSubmaps' submapName
mkSubmaps :: [ ([(KeyMask,KeySym)], X ()) ] -> [((KeyMask, KeySym), X ())]
mkSubmaps = mkSubmaps' $ submap . M.fromList
mkSubmaps' :: (Ord a) => ([(a, c)] -> c) -> [([a], c)] -> [(a, c)]
mkSubmaps' subm binds = map combine gathered
where gathered = groupBy fstKey
. sortBy (comparing fst)
$ binds
combine [([k],act)] = (k,act)
combine ks = (head . fst . head $ ks,
subm . mkSubmaps' subm $ map (first tail) ks)
fstKey = (==) `on` (head . fst)
on :: (a -> a -> b) -> (c -> a) -> c -> c -> b
op `on` f = \x y -> f x `op` f y
-- | Given a configuration record and a list of (key sequence
-- description, action) pairs, parse the key sequences into lists of
-- @(KeyMask,KeySym)@ pairs. Key sequences which fail to parse will
-- be ignored.
readKeymap :: XConfig l -> [(String, t)] -> [([(KeyMask, KeySym)], t)]
readKeymap c = mapMaybe (maybeKeys . first (readKeySequence c))
where maybeKeys (Nothing,_) = Nothing
maybeKeys (Just k, act) = Just (k, act)
-- | Parse a sequence of keys, returning Nothing if there is
-- a parse failure (no parse, or ambiguous parse).
readKeySequence :: XConfig l -> String -> Maybe [(KeyMask, KeySym)]
readKeySequence c = listToMaybe . parses
where parses = map fst . filter (null.snd) . readP_to_S (parseKeySequence c)
-- | Parse a sequence of key combinations separated by spaces, e.g.
-- @\"M-c x C-S-2\"@ (mod+c, x, ctrl+shift+2).
parseKeySequence :: XConfig l -> ReadP [(KeyMask, KeySym)]
parseKeySequence c = sepBy1 (parseKeyCombo c) (many1 $ char ' ')
-- | Parse a modifier-key combination such as "M-C-s" (mod+ctrl+s).
parseKeyCombo :: XConfig l -> ReadP (KeyMask, KeySym)
parseKeyCombo c = do mods <- many (parseModifier c)
k <- parseKey
return (foldl' (.|.) 0 mods, k)
-- | Parse a modifier: either M- (user-defined mod-key),
-- C- (control), S- (shift), or M#- where # is an integer
-- from 1 to 5 (mod1Mask through mod5Mask).
parseModifier :: XConfig l -> ReadP KeyMask
parseModifier c = (string "M-" >> return (modMask c))
+++ (string "C-" >> return controlMask)
+++ (string "S-" >> return shiftMask)
+++ do _ <- char 'M'
n <- satisfy (`elem` ['1'..'5'])
_ <- char '-'
return $ indexMod (read [n] - 1)
where indexMod = (!!) [mod1Mask,mod2Mask,mod3Mask,mod4Mask,mod5Mask]
-- | Parse an unmodified basic key, like @\"x\"@, @\"<F1>\"@, etc.
parseKey :: ReadP KeySym
parseKey = parseRegular +++ parseSpecial
-- | Parse a regular key name (represented by itself).
parseRegular :: ReadP KeySym
parseRegular = choice [ char s >> return k
| (s,k) <- zip ['!' .. '~' ] -- ASCII
[xK_exclam .. xK_asciitilde]
++ zip ['\xa0' .. '\xff' ] -- Latin1
[xK_nobreakspace .. xK_ydiaeresis]
]
-- | Parse a special key name (one enclosed in angle brackets).
parseSpecial :: ReadP KeySym
parseSpecial = do _ <- char '<'
key <- choice [ string name >> return k
| (name,k) <- keyNames
]
_ <- char '>'
return key
-- | A list of all special key names and their associated KeySyms.
keyNames :: [(String, KeySym)]
keyNames = functionKeys ++ specialKeys ++ multimediaKeys
-- | A list pairing function key descriptor strings (e.g. @\"<F2>\"@) with
-- the associated KeySyms.
functionKeys :: [(String, KeySym)]
functionKeys = [ ('F' : show n, k)
| (n,k) <- zip ([1..24] :: [Int]) [xK_F1..] ]
-- | A list of special key names and their corresponding KeySyms.
specialKeys :: [(String, KeySym)]
specialKeys = [ ("Backspace" , xK_BackSpace)
, ("Tab" , xK_Tab)
, ("Return" , xK_Return)
, ("Pause" , xK_Pause)
, ("Scroll_lock", xK_Scroll_Lock)
, ("Sys_Req" , xK_Sys_Req)
, ("Print" , xK_Print)
, ("Escape" , xK_Escape)
, ("Esc" , xK_Escape)
, ("Delete" , xK_Delete)
, ("Home" , xK_Home)
, ("Left" , xK_Left)
, ("Up" , xK_Up)
, ("Right" , xK_Right)
, ("Down" , xK_Down)
, ("L" , xK_Left)
, ("U" , xK_Up)
, ("R" , xK_Right)
, ("D" , xK_Down)
, ("Page_Up" , xK_Page_Up)
, ("Page_Down" , xK_Page_Down)
, ("End" , xK_End)
, ("Insert" , xK_Insert)
, ("Break" , xK_Break)
, ("Space" , xK_space)
, ("KP_Space" , xK_KP_Space)
, ("KP_Tab" , xK_KP_Tab)
, ("KP_Enter" , xK_KP_Enter)
, ("KP_F1" , xK_KP_F1)
, ("KP_F2" , xK_KP_F2)
, ("KP_F3" , xK_KP_F3)
, ("KP_F4" , xK_KP_F4)
, ("KP_Home" , xK_KP_Home)
, ("KP_Left" , xK_KP_Left)
, ("KP_Up" , xK_KP_Up)
, ("KP_Right" , xK_KP_Right)
, ("KP_Down" , xK_KP_Down)
, ("KP_Prior" , xK_KP_Prior)
, ("KP_Page_Up" , xK_KP_Page_Up)
, ("KP_Next" , xK_KP_Next)
, ("KP_Page_Down", xK_KP_Page_Down)
, ("KP_End" , xK_KP_End)
, ("KP_Begin" , xK_KP_Begin)
, ("KP_Insert" , xK_KP_Insert)
, ("KP_Delete" , xK_KP_Delete)
, ("KP_Equal" , xK_KP_Equal)
, ("KP_Multiply", xK_KP_Multiply)
, ("KP_Add" , xK_KP_Add)
, ("KP_Separator", xK_KP_Separator)
, ("KP_Subtract", xK_KP_Subtract)
, ("KP_Decimal" , xK_KP_Decimal)
, ("KP_Divide" , xK_KP_Divide)
, ("KP_0" , xK_KP_0)
, ("KP_1" , xK_KP_1)
, ("KP_2" , xK_KP_2)
, ("KP_3" , xK_KP_3)
, ("KP_4" , xK_KP_4)
, ("KP_5" , xK_KP_5)
, ("KP_6" , xK_KP_6)
, ("KP_7" , xK_KP_7)
, ("KP_8" , xK_KP_8)
, ("KP_9" , xK_KP_9)
]
-- | List of multimedia keys. If X server does not know about some
-- | keysym it's omitted from list. (stringToKeysym returns noSymbol in this case)
multimediaKeys :: [(String, KeySym)]
multimediaKeys = filter ((/= noSymbol) . snd) . map (id &&& stringToKeysym) $
[ "XF86ModeLock"
, "XF86MonBrightnessUp"
, "XF86MonBrightnessDown"
, "XF86KbdLightOnOff"
, "XF86KbdBrightnessUp"
, "XF86KbdBrightnessDown"
, "XF86Standby"
, "XF86AudioLowerVolume"
, "XF86AudioMute"
, "XF86AudioRaiseVolume"
, "XF86AudioPlay"
, "XF86AudioStop"
, "XF86AudioPrev"
, "XF86AudioNext"
, "XF86HomePage"
, "XF86Mail"
, "XF86Start"
, "XF86Search"
, "XF86AudioRecord"
, "XF86Calculator"
, "XF86Memo"
, "XF86ToDoList"
, "XF86Calendar"
, "XF86PowerDown"
, "XF86ContrastAdjust"
, "XF86RockerUp"
, "XF86RockerDown"
, "XF86RockerEnter"
, "XF86Back"
, "XF86Forward"
, "XF86Stop"
, "XF86Refresh"
, "XF86PowerOff"
, "XF86WakeUp"
, "XF86Eject"
, "XF86ScreenSaver"
, "XF86WWW"
, "XF86Sleep"
, "XF86Favorites"
, "XF86AudioPause"
, "XF86AudioMedia"
, "XF86MyComputer"
, "XF86VendorHome"
, "XF86LightBulb"
, "XF86Shop"
, "XF86History"
, "XF86OpenURL"
, "XF86AddFavorite"
, "XF86HotLinks"
, "XF86BrightnessAdjust"
, "XF86Finance"
, "XF86Community"
, "XF86AudioRewind"
, "XF86BackForward"
, "XF86Launch0"
, "XF86Launch1"
, "XF86Launch2"
, "XF86Launch3"
, "XF86Launch4"
, "XF86Launch5"
, "XF86Launch6"
, "XF86Launch7"
, "XF86Launch8"
, "XF86Launch9"
, "XF86LaunchA"
, "XF86LaunchB"
, "XF86LaunchC"
, "XF86LaunchD"
, "XF86LaunchE"
, "XF86LaunchF"
, "XF86ApplicationLeft"
, "XF86ApplicationRight"
, "XF86Book"
, "XF86CD"
, "XF86Calculater"
, "XF86Clear"
, "XF86Close"
, "XF86Copy"
, "XF86Cut"
, "XF86Display"
, "XF86DOS"
, "XF86Documents"
, "XF86Excel"
, "XF86Explorer"
, "XF86Game"
, "XF86Go"
, "XF86iTouch"
, "XF86LogOff"
, "XF86Market"
, "XF86Meeting"
, "XF86MenuKB"
, "XF86MenuPB"
, "XF86MySites"
, "XF86New"
, "XF86News"
, "XF86OfficeHome"
, "XF86Open"
, "XF86Option"
, "XF86Paste"
, "XF86Phone"
, "XF86Q"
, "XF86Reply"
, "XF86Reload"
, "XF86RotateWindows"
, "XF86RotationPB"
, "XF86RotationKB"
, "XF86Save"
, "XF86ScrollUp"
, "XF86ScrollDown"
, "XF86ScrollClick"
, "XF86Send"
, "XF86Spell"
, "XF86SplitScreen"
, "XF86Support"
, "XF86TaskPane"
, "XF86Terminal"
, "XF86Tools"
, "XF86Travel"
, "XF86UserPB"
, "XF86User1KB"
, "XF86User2KB"
, "XF86Video"
, "XF86WheelButton"
, "XF86Word"
, "XF86Xfer"
, "XF86ZoomIn"
, "XF86ZoomOut"
, "XF86Away"
, "XF86Messenger"
, "XF86WebCam"
, "XF86MailForward"
, "XF86Pictures"
, "XF86Music"
, "XF86TouchpadToggle"
, "XF86AudioMicMute"
, "XF86_Switch_VT_1"
, "XF86_Switch_VT_2"
, "XF86_Switch_VT_3"
, "XF86_Switch_VT_4"
, "XF86_Switch_VT_5"
, "XF86_Switch_VT_6"
, "XF86_Switch_VT_7"
, "XF86_Switch_VT_8"
, "XF86_Switch_VT_9"
, "XF86_Switch_VT_10"
, "XF86_Switch_VT_11"
, "XF86_Switch_VT_12"
, "XF86_Ungrab"
, "XF86_ClearGrab"
, "XF86_Next_VMode"
, "XF86_Prev_VMode" ]
-- | Given a configuration record and a list of (key sequence
-- description, action) pairs, check the key sequence descriptions
-- for validity, and warn the user (via a popup xmessage window) of
-- any unparseable or duplicate key sequences. This function is
-- appropriate for adding to your @startupHook@, and you are highly
-- encouraged to do so; otherwise, duplicate or unparseable
-- keybindings will be silently ignored.
--
-- For example, you might do something like this:
--
-- > main = xmonad $ myConfig
-- >
-- > myKeymap = [("S-M-c", kill), ...]
-- > myConfig = def {
-- > ...
-- > keys = \c -> mkKeymap c myKeymap
-- > startupHook = return () >> checkKeymap myConfig myKeymap
-- > ...
-- > }
--
-- NOTE: the @return ()@ in the example above is very important!
-- Otherwise, you might run into problems with infinite mutual
-- recursion: the definition of myConfig depends on the definition of
-- startupHook, which depends on the definition of myConfig, ... and
-- so on. Actually, it's likely that the above example in particular
-- would be OK without the @return ()@, but making @myKeymap@ take
-- @myConfig@ as a parameter would definitely lead to
-- problems. Believe me. It, uh, happened to my friend. In... a
-- dream. Yeah. In any event, the @return () >>@ introduces enough
-- laziness to break the deadlock.
--
checkKeymap :: XConfig l -> [(String, a)] -> X ()
checkKeymap conf km = warn (doKeymapCheck conf km)
where warn ([],[]) = return ()
warn (bad,dup) = spawn $ "xmessage 'Warning:\n"
++ msg "bad" bad ++ "\n"
++ msg "duplicate" dup ++ "'"
msg _ [] = ""
msg m xs = m ++ " keybindings detected: " ++ showBindings xs
showBindings = unwords . map (("\""++) . (++"\""))
-- | Given a config and a list of (key sequence description, action)
-- pairs, check the key sequence descriptions for validity,
-- returning a list of unparseable key sequences, and a list of
-- duplicate key sequences.
doKeymapCheck :: XConfig l -> [(String,a)] -> ([String], [String])
doKeymapCheck conf km = (bad,dups)
where ks = map ((readKeySequence conf &&& id) . fst) km
bad = nub . map snd . filter (isNothing . fst) $ ks
dups = map (snd . head)
. filter ((>1) . length)
. groupBy ((==) `on` fst)
. sortBy (comparing fst)
. map (first fromJust)
. filter (isJust . fst)
$ ks
|
f1u77y/xmonad-contrib
|
XMonad/Util/EZConfig.hs
|
bsd-3-clause
| 26,286 | 0 | 16 | 8,532 | 3,713 | 2,297 | 1,416 | 331 | 3 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
module Web.Scotty.Action
( addHeader
, body
, file
, files
, html
, json
, jsonData
, next
, param
, params
, raise
, raw
, readEither
, redirect
, reqHeader
, request
, rescue
, setHeader
, source
, status
, text
, Param
, Parsable(..)
-- private to Scotty
, runAction
) where
import Blaze.ByteString.Builder (Builder, fromLazyByteString)
import Control.Monad.Error
import Control.Monad.Reader
import qualified Control.Monad.State as MS
import qualified Data.Aeson as A
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.CaseInsensitive as CI
import Data.Conduit (Flush, Source)
import Data.Default (def)
import Data.Monoid (mconcat)
import qualified Data.Text as ST
import qualified Data.Text.Lazy as T
import Data.Text.Lazy.Encoding (encodeUtf8)
import Network.HTTP.Types
import Network.Wai
import Web.Scotty.Types
import Web.Scotty.Util
-- Nothing indicates route failed (due to Next) and pattern matching should continue.
-- Just indicates a successful response.
runAction :: (ScottyError e, Monad m) => ErrorHandler e m -> ActionEnv -> ActionT e m () -> m (Maybe Response)
runAction h env action = do
(e,r) <- flip MS.runStateT def
$ flip runReaderT env
$ runErrorT
$ runAM
$ action `catchError` (defH h)
return $ either (const Nothing) (const $ Just $ mkResponse r) e
-- | Default error handler for all actions.
defH :: (ScottyError e, Monad m) => ErrorHandler e m -> ActionError e -> ActionT e m ()
defH _ (Redirect url) = do
status status302
setHeader "Location" url
defH Nothing (ActionError e) = do
status status500
html $ mconcat ["<h1>500 Internal Server Error</h1>", showError e]
defH h@(Just f) (ActionError e) = f e `catchError` (defH h) -- so handlers can throw exceptions themselves
defH _ Next = next
-- | Throw an exception, which can be caught with 'rescue'. Uncaught exceptions
-- turn into HTTP 500 responses.
raise :: (ScottyError e, Monad m) => e -> ActionT e m a
raise = throwError . ActionError
-- | Abort execution of this action and continue pattern matching routes.
-- Like an exception, any code after 'next' is not executed.
--
-- As an example, these two routes overlap. The only way the second one will
-- ever run is if the first one calls 'next'.
--
-- > get "/foo/:bar" $ do
-- > w :: Text <- param "bar"
-- > unless (w == "special") next
-- > text "You made a request to /foo/special"
-- >
-- > get "/foo/:baz" $ do
-- > w <- param "baz"
-- > text $ "You made a request to: " <> w
next :: (ScottyError e, Monad m) => ActionT e m a
next = throwError Next
-- | Catch an exception thrown by 'raise'.
--
-- > raise "just kidding" `rescue` (\msg -> text msg)
rescue :: (ScottyError e, Monad m) => ActionT e m a -> (e -> ActionT e m a) -> ActionT e m a
rescue action h = catchError action $ \e -> case e of
ActionError err -> h err -- handle errors
other -> throwError other -- rethrow internal error types
-- | Redirect to given URL. Like throwing an uncatchable exception. Any code after the call to redirect
-- will not be run.
--
-- > redirect "http://www.google.com"
--
-- OR
--
-- > redirect "/foo/bar"
redirect :: (ScottyError e, Monad m) => T.Text -> ActionT e m a
redirect = throwError . Redirect
-- | Get the 'Request' object.
request :: (ScottyError e, Monad m) => ActionT e m Request
request = ActionT $ liftM getReq ask
-- | Get list of uploaded files.
files :: (ScottyError e, Monad m) => ActionT e m [File]
files = ActionT $ liftM getFiles ask
-- | Get a request header. Header name is case-insensitive.
reqHeader :: (ScottyError e, Monad m) => T.Text -> ActionT e m (Maybe T.Text)
reqHeader k = do
hs <- liftM requestHeaders request
return $ fmap strictByteStringToLazyText $ lookup (CI.mk (lazyTextToStrictByteString k)) hs
-- | Get the request body.
body :: (ScottyError e, Monad m) => ActionT e m BL.ByteString
body = ActionT $ liftM getBody ask
-- | Parse the request body as a JSON object and return it. Raises an exception if parse is unsuccessful.
jsonData :: (A.FromJSON a, ScottyError e, Monad m) => ActionT e m a
jsonData = do
b <- body
maybe (raise $ stringError $ "jsonData - no parse: " ++ BL.unpack b) return $ A.decode b
-- | Get a parameter. First looks in captures, then form data, then query parameters.
--
-- * Raises an exception which can be caught by 'rescue' if parameter is not found.
--
-- * If parameter is found, but 'read' fails to parse to the correct type, 'next' is called.
-- This means captures are somewhat typed, in that a route won't match if a correctly typed
-- capture cannot be parsed.
param :: (Parsable a, ScottyError e, Monad m) => T.Text -> ActionT e m a
param k = do
val <- ActionT $ liftM (lookup k . getParams) ask
case val of
Nothing -> raise $ stringError $ "Param: " ++ T.unpack k ++ " not found!"
Just v -> either (const next) return $ parseParam v
-- | Get all parameters from capture, form and query (in that order).
params :: (ScottyError e, Monad m) => ActionT e m [Param]
params = ActionT $ liftM getParams ask
-- | Minimum implemention: 'parseParam'
class Parsable a where
-- | Take a 'T.Text' value and parse it as 'a', or fail with a message.
parseParam :: T.Text -> Either T.Text a
-- | Default implementation parses comma-delimited lists.
--
-- > parseParamList t = mapM parseParam (T.split (== ',') t)
parseParamList :: T.Text -> Either T.Text [a]
parseParamList t = mapM parseParam (T.split (== ',') t)
-- No point using 'read' for Text, ByteString, Char, and String.
instance Parsable T.Text where parseParam = Right
instance Parsable ST.Text where parseParam = Right . T.toStrict
instance Parsable B.ByteString where parseParam = Right . lazyTextToStrictByteString
-- | Overrides default 'parseParamList' to parse String.
instance Parsable Char where
parseParam t = case T.unpack t of
[c] -> Right c
_ -> Left "parseParam Char: no parse"
parseParamList = Right . T.unpack -- String
-- | Checks if parameter is present and is null-valued, not a literal '()'.
-- If the URI requested is: '/foo?bar=()&baz' then 'baz' will parse as (), where 'bar' will not.
instance Parsable () where
parseParam t = if T.null t then Right () else Left "parseParam Unit: no parse"
instance (Parsable a) => Parsable [a] where parseParam = parseParamList
instance Parsable Bool where parseParam = readEither
instance Parsable Double where parseParam = readEither
instance Parsable Float where parseParam = readEither
instance Parsable Int where parseParam = readEither
instance Parsable Integer where parseParam = readEither
-- | Useful for creating 'Parsable' instances for things that already implement 'Read'. Ex:
--
-- > instance Parsable Int where parseParam = readEither
readEither :: (Read a) => T.Text -> Either T.Text a
readEither t = case [ x | (x,"") <- reads (T.unpack t) ] of
[x] -> Right x
[] -> Left "readEither: no parse"
_ -> Left "readEither: ambiguous parse"
-- | Set the HTTP response status. Default is 200.
status :: (ScottyError e, Monad m) => Status -> ActionT e m ()
status = ActionT . MS.modify . setStatus
-- | Add to the response headers. Header names are case-insensitive.
addHeader :: (ScottyError e, Monad m) => T.Text -> T.Text -> ActionT e m ()
addHeader k v = ActionT . MS.modify $ setHeaderWith $ add (CI.mk $ lazyTextToStrictByteString k) (lazyTextToStrictByteString v)
-- | Set one of the response headers. Will override any previously set value for that header.
-- Header names are case-insensitive.
setHeader :: (ScottyError e, Monad m) => T.Text -> T.Text -> ActionT e m ()
setHeader k v = ActionT . MS.modify $ setHeaderWith $ replace (CI.mk $ lazyTextToStrictByteString k) (lazyTextToStrictByteString v)
-- | Set the body of the response to the given 'T.Text' value. Also sets \"Content-Type\"
-- header to \"text/plain\".
text :: (ScottyError e, Monad m) => T.Text -> ActionT e m ()
text t = do
setHeader "Content-Type" "text/plain"
raw $ encodeUtf8 t
-- | Set the body of the response to the given 'T.Text' value. Also sets \"Content-Type\"
-- header to \"text/html\".
html :: (ScottyError e, Monad m) => T.Text -> ActionT e m ()
html t = do
setHeader "Content-Type" "text/html"
raw $ encodeUtf8 t
-- | Send a file as the response. Doesn't set the \"Content-Type\" header, so you probably
-- want to do that on your own with 'setHeader'.
file :: (ScottyError e, Monad m) => FilePath -> ActionT e m ()
file = ActionT . MS.modify . setContent . ContentFile
-- | Set the body of the response to the JSON encoding of the given value. Also sets \"Content-Type\"
-- header to \"application/json\".
json :: (A.ToJSON a, ScottyError e, Monad m) => a -> ActionT e m ()
json v = do
setHeader "Content-Type" "application/json"
raw $ A.encode v
-- | Set the body of the response to a Source. Doesn't set the
-- \"Content-Type\" header, so you probably want to do that on your
-- own with 'setHeader'.
source :: (ScottyError e, Monad m) => Source IO (Flush Builder) -> ActionT e m ()
source = ActionT . MS.modify . setContent . ContentSource
-- | Set the body of the response to the given 'BL.ByteString' value. Doesn't set the
-- \"Content-Type\" header, so you probably want to do that on your
-- own with 'setHeader'.
raw :: (ScottyError e, Monad m) => BL.ByteString -> ActionT e m ()
raw = ActionT . MS.modify . setContent . ContentBuilder . fromLazyByteString
|
xich/scotty
|
Web/Scotty/Action.hs
|
bsd-3-clause
| 9,788 | 0 | 14 | 2,105 | 2,346 | 1,255 | 1,091 | 142 | 3 |
{-# LANGUAGE DeriveDataTypeable, TypeSynonymInstances, GeneralizedNewtypeDeriving, PatternGuards, FlexibleInstances #-}
-- | Compilation top-level staging tools
module Stage
( Stage(..), stageNames
-- * Error messages
, msg, locMsg, stageMsg
-- ** Raising errors
, fatal, fatalIO
-- ** Catching errors
, runStage
-- * Stack traces
, CallStack
, CallFrame(..)
, mapStackArgs
, StackMsg(..)
) where
import Control.Exception
import Control.Monad.Trans
import Data.Typeable
import System.Exit
import Util
import Pretty
import SrcLoc
import Var
data Stage
= StageParse
| StageIr
| StageLir
| StageLink
| StageInfer
| StageExec
deriving (Eq, Ord, Enum, Bounded)
-- used for both arguments and printing; should be made more friendly at some point
stageNames :: [String]
stageNames =
["parse"
,"code"
,"lift"
,"link"
,"type"
,"runtime"
]
instance Pretty Stage where
pretty = pretty . (stageNames !!) . fromEnum
-- |To Err is human; to report anatine.
newtype Msg = Msg Doc
deriving (Pretty, Typeable)
instance Show Msg where
showsPrec p (Msg m) = showsPrec p m
instance Exception Msg
msg :: Pretty s => s -> Msg
msg = Msg . pretty
locMsg :: Pretty s => SrcLoc -> s -> Msg
locMsg l = msg . nestedPunct ':' l
stageMsg :: Pretty s => Stage -> SrcLoc -> s -> Msg
stageMsg st l m = locMsg l (st <+> "error" <:> m)
stageExitval :: Stage -> Int
stageExitval StageExec = 3
stageExitval _ = 1
fatal :: Pretty s => s -> a
fatal = throw . Msg . pretty
fatalIO :: (MonadIO m, Pretty s) => s -> m a
fatalIO = liftIO . throwIO . Msg . pretty
dieStageErr :: Stage -> Msg -> IO a
dieStageErr s e = die (stageExitval s) $ show e
isUnexpected :: SomeException -> Maybe SomeException
isUnexpected e | Just _ <- fromException e :: Maybe ExitCode = Nothing
| otherwise = Just e
dieUnexpected :: Stage -> SomeException -> IO a
dieUnexpected s e = die 7 $ pout s++": internal error: "++show e
runStage :: Stage -> IO a -> IO a
runStage s = handleJust isUnexpected (dieUnexpected s) . handle (dieStageErr s)
-- |Represents a single function call with the given type of arguments.
data CallFrame a = CallFrame
{ callFunction :: Var
, callArgs :: [a]
, callLoc :: SrcLoc
}
type CallStack a = [CallFrame a]
instance Functor CallFrame where
fmap f c = c { callArgs = map f (callArgs c) }
instance Pretty a => Pretty (CallStack a) where
pretty' s = vcat $ map p s where
p (CallFrame f args loc) = loc <:> "in" <+> prettyap f args <+> "..."
mapStackArgs :: (a -> b) -> CallStack a -> CallStack b
mapStackArgs f = map $ fmap f
data StackMsg a = StackMsg
{ msgStack :: CallStack a -- ^ This should be in call order: outside to in
, stackMsg :: Msg
}
instance Pretty a => Pretty (StackMsg a) where
pretty' (StackMsg s m) = s $$ m
|
girving/duck
|
duck/Stage.hs
|
bsd-3-clause
| 2,828 | 1 | 10 | 629 | 915 | 489 | 426 | 80 | 1 |
{-# LANGUAGE FlexibleInstances, PatternGuards #-}
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <[email protected]>
-- 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.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS 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 Core2Kindle(core2kindle, c2kTEnv, cATEnv, cValTEnv, cScheme) where
{- -}
import Monad
import Common
import Core
import Name
import PP
import qualified Decls
import qualified Env
import qualified Kindle
-- =========================================================================================
-- Translation of Core modules into back-end Kindle format
-- =========================================================================================
core2kindle e2 e3 m = localStore (cModule e2 e3 m)
-- =========================================================================================
-- The FType format
-- =========================================================================================
-- This datatype is used to distinguish the types of known functions that can be called directly,
-- from those that are anonymous and thus must be translated as closures. Furthermore, the type
-- arguments of FType constructors are supposed to be on a semi-Kindle form, where several primitive
-- type constructors have been replaced by their corresponding Kindle implementations. These types
-- are still expressed using Core.Type syntax during the translation process, though, to facilitate
-- tracking of instantiation of type variables by means of unification.
data Result a = ValR a
| FunR ([Kindle.Exp] -> a) [Kindle.AType]
instance Show a => Show (Result a) where
show (ValR a) = "ValR (" ++ show a ++ ")"
show (FunR f ts) = "FunR _ " ++ show ts
rcomp f (ValR c) = ValR (f c)
rcomp f (FunR g ts) = FunR (f . g) ts
-- =========================================================================================
-- Translation environment
-- =========================================================================================
data Env = Env { mname :: Maybe String,
decls :: Kindle.Decls,
tenv :: Kindle.TEnv,
selfN :: Maybe Name,
tArgs :: [Kindle.AType] }
env0 = Env { mname = Nothing,
decls = [],
tenv = [],
selfN = Nothing,
tArgs = [] }
setMName m env = env { mname = Just (str m) }
addDecls ds env = env { decls = ds ++ decls env }
addTEnv te env = env { tenv = te ++ tenv env }
addATEnv te env = env { tenv = mapSnd Kindle.ValT te ++ tenv env }
pushSelf x env = env { selfN = Just x }
self env = fromJust (selfN env)
setTArgs env ts = env { tArgs = ts }
findDecl env k
| isTuple k = Kindle.tupleDecl k
| otherwise = lookup' (decls env) k
splitClosureType env 0 t0 = ([], t0)
splitClosureType env n t0
| n' >= 0 = (ts:tss, t1)
| otherwise = ([], t0)
where ([],ts,t) = Kindle.openClosureType t0
n' = n - length ts
(tss,t1) = splitClosureType env n' t
-- =========================================================================================
-- Translation entry point
-- =========================================================================================
-- Translate a Core.Module into a Kindle.Module
cModule e2 e3 (Module m ns xs es ds ws bss)
= do bs <- cBindsList (addTEnv te1 env1) bss
ds2 <- currentStore
let (dsQ,dsNQ) = partition (isPublic . fst) (reverse ds2)
dsThis = ds1 ++ filter (isQual m . fst) dsQ
ds3 = dsThis ++ dsNQ
--let fromCurrent n = not (isQualified n)|| isQual m n
-- ds3 = ds1++reverse (filter (fromCurrent . fst) ds2)
return (Kindle.Module m (map snd ns) te1 ds3 bs,dsThis)
where env = addDecls e3 (setMName m (addTEnv Kindle.primTEnv (addDecls Kindle.primDecls env0)))
ds1 = cDecls ds
env1 = addTEnv (tenvImp e2) (addDecls ds1 env)
te1 = cTEnv (extsMap es)
-- Compute the imported type environment
tenvImp (Module _ _ _ es _ _ [bs]) = cTEnv (tsigsOf bs ++ extsMap es)
-- =========================================================================================
-- Translating Core type declarations into Kindle.Decls
-- =========================================================================================
cDecls (Types ke ds) = concat (map cDecl ds)
where cDecl (n,DRec _ vs [] ss) = [(n, Kindle.Struct vs (cTEnv ss) Kindle.Top)]
cDecl (n,DType vs t) = []
cDecl (n,DData vs [] cs) = (n, Kindle.Struct vs [] Kindle.Union) : map (cCon n vs) cs
cCon n vs (c,Constr ts ps ke)
= (injectCon c, Kindle.Struct (vs++vs') (cValTEnv te) (Kindle.Extends n (map Kindle.tVar vs) vs'))
where te = abcSupply `zip` (ps++ts)
vs' = dom ke
injectCon (Name s t m a) = Name ('_':s) t m a
injectCon n = n
-- =========================================================================================
-- Translating schemes and types into Kindle form
-- =========================================================================================
-- Translate a Core.Scheme into an Kindle.Type on basis of arity and polymorphism
cScheme (Scheme rh ps ke) = case (dom ke, ts' ++ ts) of -- concatenate witness params with ts
([],[]) -> Kindle.ValT t
(vs,ts) -> Kindle.FunT vs ts t
where (ts,t) = cRho rh
ts' = map cAScheme ps
-- Translate a Core.Rho type
cRho (F scs rh) = (map cAScheme scs ++ ts, t) -- concatenate scs with monadic params
where (ts,t) = cRho' rh
cRho (R t) = cType t
-- Translate a Core.Rho type but treat function types as closures
cRho' (R t) = cType' (tFlat t)
cRho' rh = ([], cAScheme (Scheme rh [] []))
-- Translate a Core.Type
cType (TFun ts t) = (map cAType ts ++ ts', t') -- concatenate ts with monadic params
where (ts',t') = cType' (tFlat t)
cType t = cType' (tFlat t)
-- Translate a Core.Type but treat function types as closures
cType' (TId (Prim Action _), []) = ([Kindle.tTime,Kindle.tTime], Kindle.tMsg)
cType' (TId (Prim Request _), [t]) = ([Kindle.tInt], cAType t)
cType' (TId (Prim Class _), [t]) = ([Kindle.tInt], cAType t)
cType' (TId (Prim Cmd _), [s,t]) = ([Kindle.tRef (cAType s)], cAType t)
cType' (TId (Prim PMC _), [t]) = ([], cAType t)
cType' (TId n, ts) | isVar n = ([], Kindle.TVar n (map cAType ts))
cType' (TId n, ts) = ([], Kindle.TCon n (map cAType ts))
cType' (Tvar n, []) = ([], Kindle.tInt) -- arbitrary choice, e.g. the type of
-- the list in "fst (False,[])"
cType' (Tvar n, ts) = ([], Kindle.TCon (tuple (length ts)) (map cAType ts))
cType' (t, _) = ([], cAType t)
-- Translate a Core.Type unconditionally into a Kindle.AType
cAType t0
| null ts = t
| otherwise = Kindle.tClos t ts
where (ts, t) = cType t0
-- Translate a Core.Scheme unconditionally into a Kindle.AType
cAScheme sc = case cScheme sc of
Kindle.ValT t -> t
Kindle.FunT vs ts t -> Kindle.tClos2 vs t ts
-- Translate a Core.Scheme unconditionally into a ValT variant of a Kindle.Type
cValScheme sc = Kindle.ValT (cAScheme sc)
-- Translate a Core.TEnv into an Kindle.TEnv
cTEnv te = xs `zip` map cScheme scs
where (xs,scs) = unzip te
-- Translate a Core.TEnv into an Kindle.ATEnv
cATEnv te = xs `zip` map cAScheme scs
where (xs,scs) = unzip te
-- Translate a Core.TEnv into an Kindle.TEnv with only ValT types
cValTEnv te = xs `zip` map cValScheme scs
where (xs,scs) = unzip te
-- =========================================================================================
-- Translating bindings
-- =========================================================================================
-- Translate a list of strongly connected Core binding groups into a list of Kindle bindings
cBindsList env [] = return []
cBindsList env (bs:bss) = do (te,bf) <- cBinds env bs
bs <- cBindsList (addTEnv te env) bss
return (Kindle.flatBinds bf ++ bs)
-- Translate a list of (mutually recursive) Core bindings into a Kindle.CBind on basis of declared type
cBinds env (Binds r te eqs)
| not r || all Kindle.okRec (rng te') = do (bf,bs) <- cEqs (addTEnv te' env) te' eqs
return (te', comb r bf bs)
| otherwise = errorIds "Illegal value recursion" (dom te')
where comb False bf bs = bf . Kindle.CBind False bs
comb True bf bs = Kindle.CBind True (Kindle.flatBinds bf ++ bs)
te' = cTEnv te
-- Translate a list of Core equations into a list of Kindle bindings on basis of declared type
cEqs env te eqs = do (bfs,bs) <- fmap unzip (mapM (cEq env te) eqs)
return (foldr (.) id bfs, bs)
cEq env te (x,e) = case lookup' te x of
Kindle.ValT t0 -> do
(bf,e) <- cValExpT env t0 e
return (bf, (x, Kindle.Val t0 e))
Kindle.FunT vs0 ts0 t0 -> do
(bf,vs,te,t,c) <- cFunT env vs0 ts0 t0 e
return (bf, (x, Kindle.Fun vs t te c))
-- Translate a Core.Exp with a known type into a Kindle.Exp
cValExpT env s e = do (bf,t,e') <- cValExp env e
f <- adaptVal env [] s [] t
return (bf, f e')
cValExpTs env [] [] = return (id, [])
cValExpTs env (s:ss) (e:es) = do (bf,e) <- cValExpT env s e
(bf',es) <- cValExpTs env ss es
return (bf . bf', e:es)
adaptVars env [] [] = return []
adaptVars env (t0:ts) ((x,t1):te) = do f <- adaptVal env [] t0 [] t1
es <- adaptVars env ts te
return (f (Kindle.EVar x) : es)
where (xs,ts') = unzip te
adaptVal env [] s [] t
| s == t = return id -- A
adaptVal env se s [] t = adaptVal env se s ts t1 -- B
where ([],ts,t1) = Kindle.openClosureType t
adaptVal env se s ts t
| l_se >= l_ts = do es <- adaptVars env ts se1
f <- adaptVal env se2 s [] t
return (\e -> f (Kindle.enter e [] es)) -- C
| otherwise {- l_se < l_ts -} = do se' <- newEnv paramSym ss
f <- adaptVal env (se++se') s1 ts t
return (\e -> Kindle.closure s1 se' (Kindle.CRet (f e))) -- D
where l_se = length se
l_ts = length ts
(se1,se2) = splitAt l_ts se
([],ss,s1) = Kindle.openClosureType s
adaptVals env [] [] = return id
adaptVals env (s:ss) (t:ts) = do f <- adaptVal env [] s [] t
g <- adaptVals env ss ts
return (\(e:es) -> f e : g es)
{-
f :: S1 -> S2 -> T f' = g(e)
f = g e ==> f(x1,x2) { return f'.enter(x1,x2) }
-----------
f :: \/a . S1 -> S2 -> T
f = /\a -> g e ==> f[a](x,x2) { return g(e).enter(x1,x2) }
-----------
f :: \/a . S1 -> S2 -> T
f = /\a -> \x -> g e ==> f[a](x,x2) { return g(e).enter(x2) }
-}
-- Translate a Core.Exp into a Kindle command, a return type, a type abstraction, and an argument list of given length
cFunT env vs0 ts0 t0 e = do (vs,te,t,c) <- cFun0 env e
let s = vs0 `zip` map Kindle.tVar vs
cFunT' env vs (subst s ts0) (subst s t0) te t c
cFunT' env [] ss s [] t (Kindle.CRet e) = do x <- newName tempSym
(te',t',c') <- adaptFun env ss s [] t (Kindle.CRet (Kindle.EVar x))
return (Kindle.cBind [(x,Kindle.Val t e)], [], te', t', c')
cFunT' env [] ss s [] t c = do f <- newName functionSym
(bf,vs,te',t',c') <- cFunT' env [] ss s [] t (Kindle.CRet (Kindle.ECall f [] []))
return (Kindle.cBind [(f,Kindle.Fun [] t [] c)] . bf, vs, te', t', c')
cFunT' env vs ss s te t c = do (te',t',c') <- adaptFun env ss s te t c
return (id, vs, te', t', c')
adaptFun env ss s te t c
| s:ss == t:rng te = return (te, t, c)
| l_ss >= l_te = do te' <- newEnv paramSym (concat tss)
(bf,se) <- adaptEnv env ss (te++te')
f <- adaptVal env [] s [] t'
return (se, s, bf (Kindle.cmap (f . Kindle.multiEnter tss (map Kindle.EVar (dom te'))) c))
| otherwise {- l_ss < l_te -} = do let (te1,te2) = splitAt l_ss te
t1 = Kindle.tClos t (rng te2)
adaptFun env ss s te1 t1 (Kindle.CRet (Kindle.closure t te2 c))
where l_ss = length ss
l_te = length te
(tss,t') = splitClosureType env (l_ss - l_te) t
adaptEnv env [] [] = return (id, [])
adaptEnv env (s:ss) ((x,t):te)
| s == t = do (bf,se) <- adaptEnv env ss te
return (bf, (x,s):se)
| otherwise = do y <- newName tempSym
f <- adaptVal env [] t [] s
-- tr ("** adapting " ++ render (pr s) ++ " *to* " ++ render (pr t))
(bf,se) <- adaptEnv env ss te
return (Kindle.cBind [(x,Kindle.Val t (f (Kindle.EVar y)))] . bf, (y,s):se)
-- [] (s1 -> s2 -> s3) [] (t1 t2 -> t3) e ^ B
-- [] (s1 -> s2 -> s3) t1 t2 t3 e C (s1 x1) D
-- x1 (s2 -> s3) t1 t2 t3 e C (s2 x2) D
-- x1 x2 s3 t1 t2 t3 e->C(x1,x2) ^ C
-- [] s3 [] t3 e->C(x1,x2) ^ A
-- [] (s1 s2 s3 -> s4 -> s5 -> s0) [] (t1 t2 -> t3 t4 t5 -> t0) e = B
-- [] (s1 s2 s3 -> s4 -> s5 -> s0) t1 t2 (t3 t4 t5 -> t0) e C (s1 x1, s2 x2, s3 x3) = D
-- x1 x2 x3 (s4 -> s5 -> s0) t1 t2 (t3 t4 t5 -> t0) e = C
-- x3 (s4 -> s5 -> s0) [] (t3 t4 t5 -> t0) e->C(x1,x2) = B
-- x3 (s4 -> s5 -> s0) t3 t4 t5 t0 e->C(x1,x2) C (s4 x4) = D
-- x3 x4 (s5 -> s0) t3 t4 t5 t0 e->C(x1,x2) C (s5 x5) = D
-- x3 x4 x5 s0 t3 t4 t5 t0 e->C(x1,x2)->C(x3,x4,x5) = C
-- [] s0 [] t0 e->C(x1,x2)->C(x3,x4,x5) = A
-- new Code (s1 x1, s2 x2, s3 x3) { ret new Code (s4 x4) { ret new Code (s5 x5) { ret e->Code(x1,x2)->Code(x3,x4,x5) }}}
-- [] (s1 s2 -> s3 s4 s5 -> s0) [] (t1 t2 t3 -> t4 -> t5 -> t0) e = B
-- [] (s1 s2 -> s3 s4 s5 -> s0) t1 t2 t3 (t4 -> t5 -> t0) e C (s1 x1, s2 x2) = D
-- x1 x2 (s3 s4 s5 -> s0) t1 t2 t3 (t4 -> t5 -> t0) e C (s3 x3, s4 x4, s5 x5) = D
-- x1 .. x5 s0 t1 t2 t3 (t4 -> t5 -> t0) e = C
-- x4 x5 s0 [] (t4 -> t5 -> t0) e->C(x1,x2,x3) = B
-- x4 x5 s0 t4 (t5 -> t0) e->C(x1,x2,x3) = C
-- x5 s0 [] (t5 -> t0) e->C(x1,x2,x3)->C(x4) = B
-- x5 s0 t5 t0 e->C(x1,x2,x3)->C(x4) = C
-- [] s0 [] t0 e->C(x1,x2,x3)->C(x4)->C(x5) = A
-- s1 s2 -> s3 s4 s5 -> s0 || t1 t2 t3 -> t4 -> t5 -> t0
-- new Code (s1 x1, s2 x2) { ret new Code (s3 x3, s4 x4 s5 x5) { ret e->Code(x1, x2, x3)->Code(x4)->Code(x5) }}
-- =========================================================================================
-- Translating abstractions
-- =========================================================================================
-- Convert a Core.Exp into a type abstraction, a parameter list and a Kindle.Cmd
cFun0 env (ELet bs e)
| isTAbsEncoding bs = do (te,t,c) <- cFun env e
return (tAbsVars bs, te, t, c)
cFun0 env e = do (te,t,c) <- cFun env e
return ([], te, t, c)
-- Convert a Core.Exp into a parameter list and a Kindle.Cmd
cFun env (ELam te0 e) = do (te',t,c) <- cFun (addATEnv te env) e
return (te ++ te', t, c)
where te = cATEnv te0
cFun env (EReq e (EDo x tx0 c)) = do (bf,e) <- cValExpT env tx e
(t,c) <- cCmd (pushSelf x (addATEnv [(x,tx)] env)) c
let bf' = Kindle.cBind [(x,Kindle.Val tx (Kindle.lock tx e))]
y <- newName dummySym
return ([(y,Kindle.tInt)], t, bf (bf' (Kindle.unlock x c)))
where tx = Kindle.tRef (cAType tx0)
cFun env (EReq e e') = do (bf,tx,e) <- cValExp env e
x <- newName selfSym
(t,c) <- cCmdExp (pushSelf x (addATEnv [(x,tx)] env)) e'
y <- newName dummySym
let bf' = Kindle.cBind [(x,Kindle.Val tx (Kindle.lock tx e))]
return ([(y,Kindle.tInt)], t, bf (bf' (Kindle.unlock x c)))
cFun env e@(EAct _ _) = cAct env id id e
cFun env e@(EAp e0 _)
| isPrim After e0 || isPrim Before e0 = cAct env id id e
cFun env (ETempl x tx0 te0 c) = do (t,c) <- cCmd (pushSelf x (addATEnv [(x,Kindle.tRef tx)] (addTEnv te env))) c
store <- currentStore
if n `elem` dom store then return () else
addToStore (n, Kindle.Struct vs te Kindle.Top)
y <- newName dummySym
let e = Kindle.ENew (prim Ref) [tx] [(prim STATE, Kindle.Val tx (Kindle.ENew n ts []))]
return ([(y,Kindle.tInt)], t, Kindle.cBind [(x,Kindle.Val (Kindle.tRef tx) e)] c)
where tx@(Kindle.TCon n []) = cAType tx0 -- Type-checker guarantees tx is a struct type name
te = cValTEnv te0
vs = nub (tyvars te)
ts = map Kindle.tVar vs
cFun env (EDo x tx0 c) = do (t,c) <- cCmd (pushSelf x (addATEnv [(x,tx)] env)) c
return ([(x,tx)], t, c)
where tx = Kindle.tRef (cAType tx0)
cFun env e = do (t,r) <- cBody env e
case r of
FunR f ts -> do xs <- newNames paramSym (length ts)
return (xs `zip` ts, t, f (map Kindle.EVar xs))
ValR c -> return ([], t, c)
-- Translate an action expression into a Core.Cmd
cAct env fa fb (EAp e0 [e,e'])
| isPrim After e0 = do (bf,e1) <- cValExpT env Kindle.tTime e
(te,t,c) <- cAct env (sum e1 . fa) fb e'
return (te, t, bf c)
| isPrim Before e0 = do (bf,e1) <- cValExpT env Kindle.tTime e
(te,t,c) <- cAct env fa (min e1 . fb) e'
return (te, t, bf c)
where sum (Kindle.EVar (Prim Inherit _)) a = a
sum e1 a = Kindle.ECall (prim TimePlus) [] [e1,a]
min (Kindle.EVar (Prim Inherit _)) a = a
min e1 b = Kindle.ECall (prim TimeMin) [] [e1,b]
cAct env fa fb (EAct e e') = do (_,_,c) <- cFun env (EReq e e')
-- Ignore returned te (must be unused) and result type (will be replaced below)
a <- newName paramSym
b <- newName paramSym
m <- newName tempSym
let c1 = Kindle.cBind bs (Kindle.CRun e1 (Kindle.CRet (Kindle.EVar m)))
c2 = Kindle.cmap (\_ -> Kindle.unit) c
bs = [(m, Kindle.Val Kindle.tMsg (Kindle.ENew (prim Msg) [] bs'))]
bs' = [(prim Code, Kindle.Fun [] Kindle.tUNIT [] c2)]
es = [Kindle.EVar m, fa (Kindle.EVar a), fb (Kindle.EVar b)]
e1 = Kindle.ECall (prim ASYNC) [] es
return ([(a,Kindle.tTime),(b,Kindle.tTime)], Kindle.tMsg, c1)
cAct env fa fb e = do (bf,t0,f,[ta,tb]) <- cFunExp env e
a <- newName paramSym
b <- newName paramSym
let c = bf (Kindle.CRet (f [fa (Kindle.EVar a), fb (Kindle.EVar b)]))
return ([(a,Kindle.tTime), (b,Kindle.tTime)], Kindle.tMsg, c)
-- =========================================================================================
-- Translating let- and case expressions
-- =========================================================================================
-- Translate a Core (Pat,Exp) pair into a Kindle.Alt result
cAlt cBdy env (Alt (PLit l) e) = do (t1,r) <- cBdy env e
return (t1, rcomp (Kindle.ALit l) r)
cAlt cBdy env (Alt PWild e) = do (t1,r) <- cBdy env e
return (t1, rcomp Kindle.AWild r)
cAlt cBdy env (Alt (PCon k te) e) = do (vs,te,t,r) <- cRhs0 cBdy env (length te0) (eLam te e)
return (t, rcomp (Kindle.ACon (injectCon k) vs te) r)
where Kindle.Struct _ te0 _ = findDecl env k
-- Translate a Core right-hand-side into a Kindle.Cmd result, a binding, and a type abstraction
cRhs0 cBdy env n (ELet bs e)
| isTAbsEncoding bs = do (te,t,r) <- cRhs cBdy env n [] e
return (tAbsVars bs, te, t, r)
cRhs0 cBdy env n e = do (te,t,r) <- cRhs cBdy env n [] e
return ([], te, t, r)
-- Translate a Core right-hand-side into a Kindle.Cmd result and a binding
cRhs cBdy env n te (ELam te0 e) = cRhs cBdy (addATEnv te1 env) n (te++te1) e
where te1 = cATEnv te0
cRhs cBdy env n te e
| n == l_te = do (t,r) <- cBdy env e
return (te, t, r)
| n < l_te = do (t,r) <- cBdy env e
let t' = Kindle.tClos t (rng te2)
return (te1, t', rcomp (Kindle.CRet . Kindle.closure t te2) r)
| n > l_te = do (t,r) <- cBdy env e
let (tss,t') = splitClosureType env (n - l_te) t
te' <- newEnv paramSym (concat tss)
let f = Kindle.multiEnter tss (map Kindle.EVar (dom te'))
return (te++te', t', rcomp (Kindle.cmap f) r)
where l_te = length te
(te1,te2) = splitAt n te
-- Translate a Core.Exp into a Kindle.Cmd result
cBody env (ELet bs e)
| not (isEncoding bs) = do (te,bf) <- cBinds env bs
(t,r) <- cBody (addTEnv te env) e
return (t, rcomp bf r)
cBody env (ECase e alts) = cCase cBody env e alts
cBody env (EAp e0 [e])
| isPrim Match e0 = do (t,r) <- cPMC cBody cExpFail env e
return (t, rcomp (\c -> Kindle.CSeq c (Kindle.CRaise (Kindle.ELit (lInt 1)))) r)
cBody env e = do (bf,t,h) <- cExp env e
case h of
ValR e -> return (t, ValR (bf (Kindle.CRet e)))
FunR f ts -> return (t, FunR (bf . Kindle.CRet . f) ts)
-- Note: we don't really handle PMC terms as first class citizens, rather like constructors in a small grammar
-- of pattern-matching expressions:
-- e ::= ... | Match pm
-- pm ::= Commit e | Fail | Fatbar pm pm | case e of {p -> pm} pm | let bs in pm
-- This syntax is followed when PMC terms are introduced in module Match, and is also respected by Termred.
--
-- However, should we for some reason want to allow abstraction over PMC terms, as in (\e -> Commit e),
-- the translation below will need to be complemented with a concrete implementation of the PMC type constructor
-- (using Maybe, for example), and corresponding general implementations of Match, Commit, Fail & Fatbar.
-- Translate a Core.Exp corresponding to a PMC term into a Kindle.Cmd result
cPMC cE cF env (ELet bs e)
| not (isEncoding bs) = do (te,bf) <- cBinds env bs
(t,r) <- cPMC cE cF (addTEnv te env) e
return (t, rcomp bf r)
cPMC cE cF env (ECase e alts) = cCase (cPMC cE cF) env e alts
cPMC cE cF env (EAp e0 [e1,e2])
| isPrim Fatbar e0 = do r1 <- cPMC cE cF env e1
r2 <- cPMC cE cF env e2
let r = maxR [r1, r2]
r1 <- adaptR env r r1
r2 <- adaptR env r r2
return (mkSeq r1 r2)
cPMC cE cF env (EAp e0 [e])
| isPrim Commit e0 = cE env e
cPMC cE cF env e0
| isPrim Fail e0 = cF env e0
cPMC cE cF env e = internalError "PMC syntax violated in Core2Kindle" e
cExpFail env e0 = do [t] <- cTArgs env e0
return (t, ValR Kindle.CBreak)
cCmdFail env e0 = do [t] <- cTArgs env e0
let ([],[_],t') = Kindle.openClosureType t
return (t', ValR Kindle.CBreak)
-- Translate the parts of a case expression into a Kindle.Cmd result
cCase cE env e (Alt (PCon k te) e':_)
| isTuple k = do (bf,_,e) <- cValExp env e
(te,t1,r) <- cRhs cE env (width k) [] (eLam te e')
let (xs,ts) = unzip te
bs = mkBinds xs ts (map (Kindle.ESel e) (take (width k) abcSupply))
return (t1, rcomp (bf . Kindle.cBind bs) r)
cCase cE env e alts = do (bf,t0,e0) <- cValExp env e
rs <- mapM (cAlt cE env) alts
let r = maxR rs
rs <- mapM (adaptR env r) rs
return (mkSwitch bf rs e0)
adaptR env (s,ValR _) (t,ValR c)
| s == t = return (s, ValR c)
| otherwise = do f <- adaptVal env [] s [] t
return (s, ValR (Kindle.cmap f c))
adaptR env (s,FunR _ ss) (t, FunR f ts)
| s:ss == t:ts = return (s, FunR f ss)
| l_ss >= l_ts = do g <- adaptVals env (ts ++ concat tss) ss
h <- adaptVal env [] s [] t'
return (s, FunR (sat g h tss) ss)
where l_ss = length ss
l_ts = length ts
(tss,t') = splitClosureType env (l_ss - l_ts) t
sat g h tss es = let (es1,es2) = splitAt l_ts (g es)
in Kindle.cmap (h . Kindle.multiEnter tss es2) (f es1)
adaptR env (s,FunR _ ss) (t,ValR c) = do g <- adaptVals env (concat tss) ss
h <- adaptVal env [] s [] t'
return (s, FunR (sat g h tss) ss)
where (tss,t') = splitClosureType env (length ss) t
sat g h tss es = Kindle.cmap (h . Kindle.multiEnter tss (g es)) c
maxR (r:rs) = max (arity r) r rs
where arity (_,ValR _) = 0
arity (_,FunR _ ts) = length ts
max n0 r0 [] = r0
max n0 r0 (r:rs)
| n > n0 = max n r rs
| otherwise = max n0 r0 rs
where n = arity r
mkSwitch bf ((t,ValR c):rs) e0 = (t, ValR (bf (Kindle.CSwitch e0 alts)))
where alts = c : [ alt | (_,ValR alt) <- rs ]
mkSwitch bf ((t,FunR g ts):rs) e0 = (t, FunR (\es -> bf (Kindle.CSwitch e0 (map ($es) (g:gs)))) ts)
where gs = [ g | (_,FunR g _) <- rs ]
mkSeq (t1,ValR c1) (t2,ValR c2) = (t1, ValR (Kindle.CSeq c1 c2))
mkSeq (t1,FunR g1 ts1) (t2,FunR g2 ts2) = (t1, FunR (\es -> Kindle.CSeq (g1 es) (g2 es)) ts1)
-- =========================================================================================
-- Translating commands
-- =========================================================================================
-- Translate a Core.Cmd into a Kindle.Cmd
cCmd env (CRet e) = do (bf,te,e) <- freezeState env e
(bf',t,e) <- cValExp (addTEnv te env) e
if Kindle.simpleExp e then -- No state references or non-termination in e
return (t, bf (bf' (Kindle.CRet e))) -- Can be ignored (see CGen alternative)
else do
x <- newName tempSym
let bf'' = Kindle.cBind [(x, Kindle.Val t e)]
return (t, bf (bf' (bf'' (Kindle.CRet (Kindle.EVar x)))))
cCmd env (CAss x e c) = do (bf,te,e) <- freezeState env e
(bf',e) <- cValExpT (addTEnv te env) tx e
(t,c) <- cCmd env c
return (t, bf (bf' (Kindle.CUpdS (stateRef env) x e c)))
where Kindle.ValT tx = lookup' (tenv env) x
cCmd env (CLet bs c) = do (bf,te,bs) <- freezeState env bs
(te',bf') <- cBinds (addTEnv te env) bs
(t,c) <- cCmd (addTEnv te' env) c
return (t, bf (bf' c))
cCmd env (CGen x tx (ECase e alts) c)
| isDummy x && null alts' = cCmd env c
| isDummy x = do (_,ValR c1) <- cCase cValCmdExp env e alts'
(t,c2) <- cCmd env c
return (t, Kindle.CSeq (Kindle.cMap (\_ -> Kindle.CBreak) c1) c2)
where alts' = filter useful alts
useful (Alt _ (EDo _ _ (CRet e)))= e /= eUnit
useful _ = True
cCmd env (CGen x tx0 e c) = do (bf,te,e) <- freezeState env e
(bf',e) <- cValExpT (addTEnv te env) tx (EAp e [EVar (self env)])
(t,c) <- cCmd (addATEnv [(x,tx)] env) c
return (t, bf (bf' (Kindle.cBind [(x,Kindle.Val tx e)] c)))
where tx = cAType tx0
cCmd env (CExp e) = cCmdExp env e
-- Translate a Core.Exp in the monadic execution path into a Kindle.Cmd
cCmdExp env (ELet bs e)
| not (isEncoding bs) = do (bf,te,bs) <- freezeState env bs
(te',bf') <- cBinds (addTEnv te env) bs
(t,c) <- cCmdExp (addTEnv te' env) e
return (t, bf (bf' c))
cCmdExp env (EAp e0 [e])
-- | isPrim ReqToCmd e0 = ...
| isPrim Raise e0 = do (bf,te,e) <- freezeState env e
(bf',_,e') <- cValExp (addTEnv te env) e
[t] <- cTArgs env e0
let ([],[_],t') = Kindle.openClosureType t
return (t', bf (bf' (Kindle.CRaise e')))
| isPrim Match e0 = do (bf,te,e) <- freezeState env e
(t,ValR c) <- cPMC cValCmdExp cCmdFail (addTEnv te env) e
return (t, bf (Kindle.CSeq c (Kindle.CRaise (Kindle.ELit (lInt 1)))))
cCmdExp env (EDo x tx0 c) = do (t,c) <- cCmd (pushSelf x (addATEnv [(x,Kindle.tRef tx)] env)) c
return (t, Kindle.cBind [(x,Kindle.Val (Kindle.tRef tx) (Kindle.EVar (self env)))] c)
where tx = cAType tx0
cCmdExp env (ECase e alts) = do (bf,te,e) <- freezeState env e
(t,ValR c) <- cCase cValCmdExp (addTEnv te env) e alts
return (t, bf c)
cCmdExp env e = do (bf,te,e) <- freezeState env e
(bf',t,e) <- cValExp (addTEnv te env) (EAp e [EVar (self env)])
x <- newName tempSym
let bf'' = Kindle.cBind [(x, Kindle.Val t e)]
return (t, bf (bf' (bf'' (Kindle.CRet (Kindle.EVar x)))))
cValCmdExp env e = do (t,c) <- cCmdExp env e
return (t, ValR c)
-- State variables are normally translated into field selections from the current "self". For example,
-- x := 7; result (x + 1)
-- gets translated into
-- self->x := 7; result (self->x + 1)
-- However, closure values, which may be invoked long after they are defined, must not be sensitive to state
-- mutations. This means that "self" dereferencing operations for any contained state variables must be done
-- when the closure is defined, not when it is invoked. Here's a challenging example:
-- x := 7; f = \y->x+y; x := 2; result (f 1);
-- If we naively translate the x reference in f to self->x, we end up with the wrong behavior:
-- self->x := 7; int f(int y) { return self->x + y }; self->x := 2; return f(1); -- gives 3, not 8
--
-- A correct translation can instead be obtained if we make sure that no state variables are ever referenced
-- from within a lambda abstraction, as in the equivalent example
-- x := 7; x' = x; f = \y->x'+y; x := 2; return (f 1); (for some fresh variable x')
-- Achieving this is the job of function freezeState below. It takes an expression e and returns a renaming
-- of e with the "fragile" free variables (i.e., state vars inside lambdas) replaced by fresh variables,
-- together with a type environment and Kindle bindings for the new variables. For the example above,
-- input (\y->x+y) results in output (\y->x'+y) together with the Kindle binding (int x' = self->x). When
-- composed with the rest of the translation process, the full output becomes
-- self->x := 7; int x' = self->x; int f(int y) { return x'+y }; self->x := 2; return f(1);
-- This form is perfectly valid as input to the subsequent lambda-lifting pass, whose result will be
-- int f(int x'', int y) { return x'' + y }
-- self->x := 7; int x' = self->x; self->x := 2; return f(x',1);
class Fragile a where
fragile :: a -> [Name]
instance Fragile Exp where
fragile (ELam _ e) = filter isState (idents e)
fragile (EAp e es) = concatMap fragile (e:es)
fragile (ESel e l) = fragile e
fragile (ERec c eqs) = concatMap fragile (rng eqs)
fragile (ELet bs e) = fragile bs ++ fragile e
fragile (ECase e alts) = fragile e ++ concatMap fragile alts
fragile _ = []
instance Fragile (Alt Exp) where
fragile (Alt _ (ELam te e)) = fragile e
fragile (Alt _ e) = fragile e
instance Fragile Binds where
fragile bs = concatMap fragile (rng (eqnsOf bs))
freezeState env xx
| null vs = return (id, [], xx)
| otherwise = do vs' <- newNames paramSym (length vs)
return (Kindle.cBind (zipWith3 f vs' ts vs), vs' `zip` ts, subst (vs `zip` map EVar vs') xx)
where vs = nub (fragile xx)
ts = map (lookup' (tenv env)) vs
f v' (Kindle.ValT t) v = (v', Kindle.Val t (Kindle.ESel (stateRef env) v))
-- Return a Kindle expression identifying the current state struct
stateRef env = Kindle.ESel (Kindle.EVar (self env)) (prim STATE)
-- =========================================================================================
-- Translating expressions
-- =========================================================================================
rename1 (Binds r te eqs) e = do s <- mapM f xs
let s' = mapSnd EVar s
return (Binds r (rng s `zip` ts) (subst s ys `zip` subst s' es), subst s' e)
where (xs,ts) = unzip te
(ys,es) = unzip eqs
f x = do n <- newNum
return (x, x {tag = n})
-- Translate a Core.Exp into an expression result that is either a value or a function,
-- overflowing into a list of Kindle.Binds if necessary
cExp env (ELet bs e)
| isTAppEncoding bs = cExp (setTArgs env (map cAType (tAppTypes bs))) e
| not (isTAbsEncoding bs) = do (bs,e) <- rename1 bs e
(te,bf) <- cBinds env bs
(bf',t,h) <- cExp (addTEnv te env) e
return (bf . bf', t, h)
cExp env (ELit l) = return (id, Kindle.litType l, ValR (Kindle.ELit l))
cExp env (ERec c eqs) = do (bf,bs) <- cEqs (setTArgs env []) te' eqs
return (bf, Kindle.TCon c ts, ValR (Kindle.ENew c ts bs))
where ts = tArgs env
Kindle.Struct vs te _ = findDecl env c
te' = subst (vs `zip` ts) te
cExp env (EAp e0 [e])
| isPrim ActToCmd e0 = do (bf,t,e) <- cValExp env (EAp e [EVar (prim Inherit), EVar (prim Inherit)])
[t1] <- cTArgs env e0
return (bf, t, FunR (\_ -> e) [Kindle.tRef t1])
| isPrim ReqToCmd e0 = do (bf,t,e) <- cValExp env (EAp e [ELit (lInt 0)])
[t1,t2] <- cTArgs env e0
return (bf, t, FunR (\_ -> e) [Kindle.tRef t2])
| Just t <- isCastPrim e0 = do (bf,_,e') <- cExp env e
return (bf, t, rcomp (Kindle.ECast t) e')
| isPrim RefToOID e0 = do (bf,t,e) <- cExp env e
return (bf, Kindle.tOID, rcomp (Kindle.ECast Kindle.tOID) e)
| isPrim New e0 = cExp env (EAp e [ELit (lInt 0)]) -- Can't occur but in CBind rhs, syntactic restriction
cExp env (EAp e0 [e,e'])
| isPrim After e0 = do (bf,e1) <- cValExpT env Kindle.tTime e
(bf',t,f,ts) <- cFunExp env e'
return (bf . bf', t, FunR (\[a,b] -> f [sum a e1, b]) ts)
| isPrim Before e0 = do (bf,e1) <- cValExpT env Kindle.tTime e
(bf',t,f,ts) <- cFunExp env e'
return (bf . bf', t, FunR (\[a,b] -> f [a, min b e1]) ts)
where sum a e1 = Kindle.ECall (prim TimePlus) [] [a,e1]
min b e1 = Kindle.ECall (prim TimeMin) [] [b,e1]
cExp env (EAp e es)
| not (isPrim Match e) = do (bf,t,f,ts) <- cFunExp env e
appFun env bf t f ts es
where appFun env bf t f ts es
| l_ts < l_es = do (bf',es1) <- cValExpTs env ts es1
let ([],ts',t') = Kindle.openClosureType t
appFun env (bf . bf') t' (Kindle.enter (f es1) []) ts' es2
| l_ts == l_es = do (bf',es) <- cValExpTs env ts es
return (bf . bf', t, ValR (f es))
| l_ts > l_es = do (bf',es) <- cValExpTs env ts1 es
return (bf . bf', t, FunR (f . (es++)) ts2)
where l_ts = length ts
l_es = length es
(ts1,ts2) = splitAt l_es ts
(es1,es2) = splitAt l_ts es
cExp env (EVar x) = case lookup' (tenv env) x of
Kindle.ValT t
| null ts -> return (id, t, ValR e)
| null ts' -> return (id, subst s t', ValR (Kindle.enter e ts []))
| otherwise -> return (id, subst s t', FunR (Kindle.enter e ts) (subst s ts'))
where (vs,ts',t') = Kindle.openClosureType t
s = vs `zip` ts
Kindle.FunT vs ts' t
| null ts' -> return (id, subst s t, ValR (Kindle.ECall x ts []))
| otherwise -> return (id, subst s t, FunR (Kindle.ECall x ts) (subst s ts'))
where s = vs `zip` ts
where e = if stateVar (annot x) then Kindle.ESel (stateRef env) x else Kindle.EVar x
ts = tArgs env
cExp env (ESel e l) = do (bf,e) <- cValExpT (setTArgs env []) (Kindle.TCon k ts0) e
case subst (vs0 `zip` ts0) rhstype of
Kindle.ValT t -> return (bf, t, ValR (Kindle.ESel e l))
Kindle.FunT vs ts t -> return (bf, subst s t, FunR (Kindle.EEnter e l ts1) (subst s ts))
where s = vs `zip` ts1
where (k,vs0,rhstype) = Kindle.typeOfSel (decls env) l
(ts0,ts1) = splitAt (length vs0) (tArgs env) -- tArgs lists *full* instantiation, not just local quantification
cExp env (ECon k)
| isTuple k = case ts of
[] -> return (id, Kindle.TCon k [], ValR (Kindle.ENew k [] []))
_ -> return (id, Kindle.TCon k ts, FunR (Kindle.ENew k ts . mkBinds abcSupply ts) ts)
| otherwise = case te of
[] -> return (id, t0, ValR (newK []))
_ -> return (id, t0, FunR (newK . mkBinds abcSupply ts') ts')
where ts = tArgs env
Kindle.Struct vs te (Kindle.Extends k0 ts0 _) = findDecl env k
s = vs `zip` ts
ts' = subst s (map Kindle.rngType (rng te))
t0 = Kindle.TCon k0 (subst s ts0)
newK = Kindle.ECast t0 . Kindle.ENew (injectCon k) ts
cExp env e = do (vs,te,t,c) <- cFun0 env e
case (vs,te) of
([],[]) -> do
x <- newName tempSym
return (Kindle.cBind [(x, Kindle.Fun [] t [] c)], t, ValR (Kindle.ECall x [] []))
_ -> return (id, t', ValR (Kindle.closure2 vs t te c))
where t' = Kindle.tClos2 vs t (rng te)
-- Translate a Core.Exp into a Kindle value expression
cValExp env e = do (bf,t,h) <- cExp env e
case h of
ValR e ->
return (bf, t, e)
FunR f ts -> do
xs <- newNames paramSym (length ts)
let t' = Kindle.tClos t ts
es = map Kindle.EVar xs
te = xs `zip` ts
return (bf, t', Kindle.closure t te (Kindle.CRet (f es)))
-- Translate a Core.Exp into a Kindle function
cFunExp env e = do (bf,t,h) <- cExp env e
case h of
FunR f ts -> return (bf, t, f, ts)
ValR e' -> return (bf, t', Kindle.enter e' [], ts)
where ([],ts,t') = Kindle.openClosureType t
-- Map a Kindle.ATEnv (unzipped) and a list of Kindle.Exps into a list of Kindle.Binds
mkBinds xs ts es = zipWith3 f xs ts es
where f x t e = (x, Kindle.Val t e)
-- Check if expression is a primitive, possibly applied to type arguments
isPrim p (ELet bs e)
| isTAppEncoding bs = isPrim p e
isPrim p (EVar (Prim p' _))
| p == p' = True
isPrim p e = False
isCastPrim (EVar (Prim p _))
| p `elem` intCasts = Just Kindle.tInt
| p == IntToChar = Just Kindle.tChar
| p == IntToBITS8 = Just Kindle.tBITS8
| p == IntToBITS16 = Just Kindle.tBITS16
| p == IntToBITS32 = Just Kindle.tBITS32
where intCasts = [CharToInt,BITS8ToInt,BITS16ToInt,BITS32ToInt]
isCastPrim _ = Nothing
-- Extract type arguments from expression
cTArgs env (ELet bs e)
| isTAppEncoding bs = return (map cAType (tAppTypes bs))
cTArgs env e = return []
-- Additional entry point for translating imported environments
c2kTEnv ds te = return (cTEnv te)
|
mattias-lundell/timber-llvm
|
src/Core2Kindle.hs
|
bsd-3-clause
| 55,845 | 0 | 21 | 27,035 | 15,106 | 7,657 | 7,449 | 570 | 7 |
module App where
import Types
primWC :: Prim
primWC -- TODO
|
wuxb45/eval
|
Eval/low/App.hs
|
bsd-3-clause
| 62 | 0 | 4 | 13 | 16 | 10 | 6 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.BasicTypes
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module corresponds to section 2.3 (GL Command Sytax) of the OpenGL 1.5
-- specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.BasicTypes (
GLenum, GLboolean, GLbitfield, GLbyte, GLshort, GLint, GLintptr, GLubyte,
GLushort, GLuint, GLsizei, GLsizeiptr, GLfloat, GLclampf, GLdouble, GLclampd,
Capability(..)
) where
--------------------------------------------------------------------------------
import Data.Int
import Data.Word
--------------------------------------------------------------------------------
#include "HsOpenGLConfig.h"
--------------------------------------------------------------------------------
-- | Enumerated binary integer value (min. 32 bits)
type GLenum = HTYPE_GLENUM
-- | Boolean (min. 1 bit)
type GLboolean = HTYPE_GLBOOLEAN
-- | Bit field (min. 32 bits)
type GLbitfield = HTYPE_GLBITFIELD
-- | Signed 2\'s complement binary integer (min. 8 bits)
type GLbyte = HTYPE_GLBYTE
-- | Signed 2\'s complement binary integer (min. 16 bits)
type GLshort = HTYPE_GLSHORT
-- | Signed 2\'s complement binary integer (min. 32 bits)
type GLint = HTYPE_GLINT
-- | Signed 2\'s complement binary integer (sufficiently large enough to hold
-- any address)
type GLintptr = Int32 -- TODO: Use autoconf stuff for this!
-- | Unsigned binary integer (min. 8 bits)
type GLubyte = HTYPE_GLUBYTE
-- | Unsigned binary integer (min. 16 bits)
type GLushort = HTYPE_GLUSHORT
-- | Unsigned binary integer (min. 32 bits)
type GLuint = HTYPE_GLUINT
-- | Non-negatitve binary integer size (min. 32 bits)
type GLsizei = HTYPE_GLSIZEI
-- | Non-negatitve binary integer size (sufficiently large enough to hold any
-- address)
type GLsizeiptr = Int32 -- TODO: Use autoconf stuff for this!
-- | Floating-point value (min. 32 bits)
type GLfloat = HTYPE_GLFLOAT
-- | Floating-point value clamped to [0,1] (min. 32 bits)
type GLclampf = HTYPE_GLCLAMPF
-- | Floating-point value (min. 64 bits)
type GLdouble = HTYPE_GLDOUBLE
-- | Floating-point value clamped to [0,1] (min. 64 bits)
type GLclampd = HTYPE_GLCLAMPD
--------------------------------------------------------------------------------
data Capability =
Disabled
| Enabled
deriving ( Eq, Ord, Show )
|
FranklinChen/hugs98-plus-Sep2006
|
packages/OpenGL/Graphics/Rendering/OpenGL/GL/BasicTypes.hs
|
bsd-3-clause
| 2,632 | 0 | 6 | 389 | 236 | 168 | 68 | 26 | 0 |
module XMonad.Libs.Prompts (
switchPrompt
) where
import XMonad
import XMonad.Prompt
import XMonad.Prompt.Input
statusPrompt :: XPConfig -> String -> Bool -> String -> X ()
statusPrompt config prompt notify run = do
inputPromptWithCompl config prompt cFun ?+ action notify
where
comps = switchComps run
cFun = mkComplFunFromList' comps
run' = switchExec run
not' = "msg=`" ++ run' ++ " status` && twmnc -c \"$msg\""
action n s | n = spawn $ run' ++ " " ++ s ++ " && " ++ not'
| otherwise = spawn $ run' ++ " " ++ s
-- Hier sind alle Programme die nach dem Schema definiert sind aufgelistet.
-- Diese Programme sind in ~/bin zu finden. Alle diese Programme müssen zumindest
-- 3 Argumente annehmen. Das sind: 'on', 'off' und 'status'. 'on' aktiviert
-- diesen Switch, 'off' deaktiviert diesen Switch und 'status' wird für die
-- Notification-Message verwendet. Für die Notification-Message ist es wichtig
-- das 'twmnd' läuft.
switchProgs :: [((String,String),[String])]
switchProgs = [ (("mouse", "mouse.sh"), ["on","off","toggle"])
, (("monitor", "monitor.sh"), ["on","off"])
]
switchProgNames :: [String]
switchProgNames = map (fst . fst) switchProgs
switchExec :: String -> String
switchExec name = chkList $ execList name
where
execList n = filter ((==n) . fst . fst) switchProgs
chkList [] = ""
chkList ls = (snd . fst) $ head ls
switchComps :: String -> [String]
switchComps = chkList . execList
where
execList n = filter ((==n) . fst . fst) switchProgs
chkList [] = []
chkList ls = snd $ head ls
switchPrompt :: XPConfig -> Bool -> X ()
switchPrompt config notify = do
inputPromptWithCompl config "Switch" cFun ?+
statusPrompt config "status" notify
where
cFun = mkComplFunFromList' switchProgNames
|
odi/xmonad-ext
|
src/XMonad/Libs/Prompts.hs
|
bsd-3-clause
| 1,855 | 0 | 12 | 420 | 506 | 272 | 234 | 34 | 2 |
module Main where
import Text.Read
import System.Random
import Control.Monad.State
import HigherLower.Game
main :: IO ()
main = do
g <- createGame
evalStateT playGame g
createGame :: IO Game
createGame = do
low <- retryPrompt "Not a number" (promptInt "Give a lower bound")
high <- retryPrompt "Not a number" (promptInt "Give an upper bound")
turns <- retryPrompt "Not a number" (promptInt "How many tries do you get?")
secret <- getStdRandom (randomR (low, high))
return (Game (low, high) secret (Active turns))
playGame :: StateT Game IO ()
playGame = do
i <- liftIO $ retryPrompt "Not a number" (promptInt "Your guess:")
result <- checkGuess i
case result of
Nothing -> liftIO (putStrLn "This game was already played.")
Just r -> do
case r of
LT -> liftIO (putStrLn "Getting closer; your guess was too low.") >> playGame
GT -> liftIO (putStrLn "Getting closer; your guess was too high.") >> playGame
EQ -> liftIO (putStrLn "YOU WIN!")
promptInt :: String -> IO (Maybe Int)
promptInt q = do
putStrLn q
readMaybe <$> getLine
retryPrompt :: String -> IO (Maybe a) -> IO a
retryPrompt f p = do
res <- p
case res of
Just x -> return x
Nothing -> do
putStrLn f
retryPrompt f p
|
fydio/HigherLower
|
src/Main.hs
|
bsd-3-clause
| 1,270 | 0 | 18 | 300 | 434 | 206 | 228 | 39 | 4 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
module Ling.Reduce where
import Data.Char
import Ling.Fwd
import Ling.Norm
import Ling.Prelude hiding (subst1)
import Ling.Print
import Ling.Proc
import Ling.Rename
import Ling.Scoped
import Ling.Session.Core
-- This `strong` mode is not really useful. Ling.Subst is already
-- implementing the strong reductfuse semantics so Ling.Reduce
-- can be kept as the lazy/weak version.
strong :: Bool
strong = False
newtype Reduced a = Reduced { _reduced :: Scoped a }
deriving (Eq, Show, Monoid, Functor, Applicative)
makePrisms ''Reduced
makeLenses ''Reduced
instance Print a => Print (Reduced a) where
prt i = prt i . view reduced
type Reduce a b = Scoped a -> Reduced b
type Reduce' a = Reduce a a
class HasReduce a b where
reduce :: Reduce a b
type HasReduce' a = HasReduce a a
traceReduce :: (Print a, Print b, Show a, Show b)
=> String -> Scoped a -> Reduced b -> Reduced b
traceReduce _ _ = id
--traceReduce msg x y = trace (msg ++ ":\n" ++ pretty (x ^. scoped)) (y `seq` trace ("---> " ++ pretty (y ^. reduced . scoped)) y)
--traceReduce msg x y = trace (msg ++ ":\n" ++ ppShow (x ^. scoped)) (y `seq` trace ("---> " ++ ppShow (y ^. reduced . scoped)) y)
--traceReduce msg x y = trace (msg ++ ":\n" ++ ppShow (x & gdefs .~ ø)) (y `seq` trace ("---> " ++ ppShow (y & reduced . gdefs .~ ø)) y)
--traceReduce msg x y = trace (msg ++ ":\n" ++ ppShow x) (y `seq` trace ("---> " ++ ppShow y) y)
alreadyReduced :: Scoped a -> Reduced a
alreadyReduced s = pure $ s ^. scoped
reducedOrReduce :: HasReduce' a => Scoped a -> Reduced a
reducedOrReduce
| strong = reduce
| otherwise = alreadyReduced
reduceApp :: Scoped Term -> [Term] -> Reduced Term
reduceApp st0 = \case
[] -> Reduced (st0 & gdefs .~ ø) *> rt1
(u:us) ->
traceReduce "reduceApp" st1 $
case st1 ^. scoped of
Lam (Arg x mty) t2 -> reduceApp (st0 *> st1 *> subst1 (x, Ann mty u) t2) us
Def k d es -> reduceDef (st0 *> st1 $> (k, d, es ++ u : us))
_ -> error "Ling.Reduce.reduceApp: IMPOSSIBLE"
where
rt1 = reduce st0
st1 = rt1 ^. reduced
-- st1 might have less (or even no) defs than st0.
reduceCase :: Scoped Term -> [Branch] -> Reduced Term
reduceCase st0 brs =
traceReduce "reduceCase" st0 $
case st1 ^. reduced . scoped of
Con con
| Just rhs <- lookup con brs -> reduce (st0 $> rhs)
| otherwise -> error "reduceCase: IMPOSSIBLE"
_ | strong -> mkCase <$> st1 <*> reduce (st0 $> brs)
| otherwise -> (`Case` brs) <$> st1
-- ^ no need for mkCase here since:
-- * the scrutinee is not a constructor
-- * the branches have not changed
-- * mkCase would not do anything useful
where st1 = reduce st0
mkBool :: Bool -> Term
mkBool False = Con (Name "false")
mkBool True = Con (Name "true")
reducePrim :: Name -> [Term] -> Maybe Term
reducePrim (Name sd) es
| sd == "ccall"
, (_:Lit (LString s):rs) <- es
, Just ls <- rs ^? below _Lit = reduceRawC s ls
| Just ls <- es ^? below _Lit = redLit sd ls
| otherwise = Nothing
where
-- TODO: No CD rules
-- The resulting Term should be in normal form.
redLit :: String -> [Literal] -> Maybe Term
redLit "_+_" [LInteger x, LInteger y] = Just . Lit . LInteger $ x + y
redLit "_-_" [LInteger x, LInteger y] = Just . Lit . LInteger $ x - y
redLit "_*_" [LInteger x, LInteger y] = Just . Lit . LInteger $ x * y
redLit "_/_" [LInteger x, LInteger y] = Just . Lit . LInteger $ x `div` y
redLit "_%_" [LInteger x, LInteger y] = Just . Lit . LInteger $ x `mod` y
redLit "pow" [LInteger x, LInteger y] = Just . Lit . LInteger $ x ^ y
redLit "_+D_" [LDouble x, LDouble y] = Just . Lit . LDouble $ x + y
redLit "_-D_" [LDouble x, LDouble y] = Just . Lit . LDouble $ x - y
redLit "_*D_" [LDouble x, LDouble y] = Just . Lit . LDouble $ x * y
redLit "_/D_" [LDouble x, LDouble y] = Just . Lit . LDouble $ x / y
redLit "powD" [LDouble x, LDouble y] = Just . Lit . LDouble $ x ** y
redLit "_++S_" [LString x, LString y] = Just . Lit . LString $ x ++ y
redLit "showInt" [LInteger x] = Just . Lit . LString $ show x
redLit "showDouble" [LDouble x] = Just . Lit . LString $ show x
redLit "showChar" [LChar x] = Just . Lit . LString $ show x
redLit "showString" [LString x] = Just . Lit . LString $ show x
redLit "_==I_" [LInteger x, LInteger y] = Just . mkBool $ x == y
redLit "_==D_" [LDouble x, LDouble y] = Just . mkBool $ x == y
redLit "_==C_" [LChar x, LChar y] = Just . mkBool $ x == y
redLit "_==S_" [LString x, LString y] = Just . mkBool $ x == y
redLit "_<=I_" [LInteger x, LInteger y] = Just . mkBool $ x <= y
redLit "_<=D_" [LDouble x, LDouble y] = Just . mkBool $ x <= y
redLit "_<=C_" [LChar x, LChar y] = Just . mkBool $ x <= y
redLit "_>=I_" [LInteger x, LInteger y] = Just . mkBool $ x >= y
redLit "_>=D_" [LDouble x, LDouble y] = Just . mkBool $ x >= y
redLit "_>=C_" [LChar x, LChar y] = Just . mkBool $ x >= y
redLit "_>I_" [LInteger x, LInteger y] = Just . mkBool $ x > y
redLit "_>D_" [LDouble x, LDouble y] = Just . mkBool $ x > y
redLit "_>C_" [LChar x, LChar y] = Just . mkBool $ x > y
redLit "_<I_" [LInteger x, LInteger y] = Just . mkBool $ x < y
redLit "_<D_" [LDouble x, LDouble y] = Just . mkBool $ x < y
redLit "_<C_" [LChar x, LChar y] = Just . mkBool $ x < y
redLit _ _ = Nothing
reduceRawC :: String -> [Literal] -> Maybe Term
reduceRawC "(double)" [LInteger x] = Just . Lit . LDouble $ fromInteger x
reduceRawC "(int)" [LChar x] = Just . Lit . LInteger . toInteger $ ord x
reduceRawC _ _ = Nothing
reduceDef :: Scoped (DefKind, Name, [Term]) -> Reduced Term
reduceDef sdef =
-- traceReduce "reduceDef" sdef $
case sdef ^. scoped of
(k, d, es) ->
case k of
Defined
| Just st <- scopedName (sdef $> d) -> reduceApp st es
Undefined
| Just e <- reducePrim d (es' ^. reduced . scoped) -> pure e
_ -> Def k d <$> es'
where
es' = reduce (sdef $> es)
instance HasReduce a b => HasReduce (Maybe a) (Maybe b) where reduce = reduceEach
instance HasReduce a b => HasReduce [a] [b] where reduce = reduceEach
instance HasReduce a b => HasReduce (Arg a) (Arg b) where reduce = reduceEach
instance (HasReduce a b, HasReduce a' b') => HasReduce (a, a') (b, b') where
reduce sxy = bitraverse (reduce . (sxy $>)) (reduce . (sxy $>)) (sxy ^. scoped)
-- Only needed for ConName
instance HasReduce Name Name where reduce = alreadyReduced
instance HasReduce Session Session where
reduce s0 =
case s0 ^. scoped of
TermS p t1 -> (view (from tSession) . sessionOp p) <$> reduce (s0 $> t1)
Array k ss -> whenStrong $ Array k <$> reduce (s0 $> ss)
IO rw vd s -> whenStrong $ IO rw <$> reduce (s0 $> vd) <*> reduce (s0 $> s)
where
whenStrong s | strong = s
| otherwise = alreadyReduced s0
instance HasReduce RFactor RFactor where
reduce = reduce_ rterm
instance HasReduce RSession RSession where
reduce rs0 =
case rs0 ^. scoped of
s `Repl` r -> Repl <$> reduce (rs0 $> s) <*> reduce (rs0 $> r)
instance HasReduce ChanDec ChanDec where
reduce scd =
case scd ^. scoped of
ChanDec c r os -> ChanDec c <$> reduce (scd $> r) <*> reduce (scd $> os)
instance HasReduce Term Term where
reduce st0 =
-- traceReduce "reduceTerm" st0 $
case t0 of
Let defs t -> Reduced (Scoped ø defs ()) *> reduce (st0 *> Scoped defs ø () $> t)
Def k d es -> reduceDef (st0 $> (k, d, es))
Case t brs -> reduceCase (st0 $> t) brs
Lit{} -> pure t0
TTyp -> pure t0
Con{} -> pure t0
Proc cds p -> whenStrong $ Proc <$> reduce (st0 $> cds) <*> reduce (st0 $> p)
Lam arg t -> whenStrong $ Lam <$> reduce (st0 $> arg) <*> reduce (st0 $> t)
TFun arg t -> whenStrong $ TFun <$> reduce (st0 $> arg) <*> reduce (st0 $> t)
TSig arg t -> whenStrong $ TSig <$> reduce (st0 $> arg) <*> reduce (st0 $> t)
TProto ss -> whenStrong $ TProto <$> reduce (st0 $> ss)
TSession s0 -> view tSession <$> reduce (st0 $> s0)
where
t0 = st0 ^. scoped
whenStrong s | strong = s
| otherwise = alreadyReduced st0
-- TODO assumptions!!!
reduce_ :: HasReduce a b => Traversal s t a b -> Reduce s t
reduce_ trv ss = trv (reduce . (ss $>)) (ss ^. scoped)
reduceEach :: (Each s t a b, HasReduce a b) => Reduce s t
reduceEach = reduce_ each
flatRSession :: Scoped RSession -> [Scoped RSession]
flatRSession ssr
| Just n <- r1 ^? litR . integral = replicate n (pure $ oneS s)
| Just (rL,rR) <- r1 ^? addR = flatRSession (sr1 $> s `Repl` rL)
++ flatRSession (sr1 $> s `Repl` rR)
| otherwise = [ssr]
where sr1 = reduce_ rterm (ssr $> r0) ^. reduced
s = ssr ^. scoped . rsession
r0 = ssr ^. scoped . rfactor
r1 = sr1 ^. scoped
flatRSessions :: Scoped Sessions -> [Scoped RSession]
flatRSessions sss = sss ^. scoped . _Sessions >>= flatRSession . (sss $>)
instance HasReduce Sessions Sessions where
reduce = Reduced . fmap Sessions . sequenceA . flatRSessions
-- Prism valid up to the reduction rules
_ActAt :: Prism' Proc (Term, CPatt)
_ActAt = prism con pat
where
con (t, p) =
-- (\proc0 -> trace ("_ActAt (" ++ ppShow t ++ ", " ++ ppShow p ++ ") = " ++ ppShow proc0) proc0) $
case t of
Proc cs0 proc0 ->
case cPattAsArrayChanDecs p of
Just (k, cs') | Just (pref1, cs1, proc1) <- matchChanDecs k (id, cs0, proc0)
, length cs1 == length cs' -> pref1 $ renProc (zip cs1 cs') proc1
| k == ParK
, length cs0 == length cs' -> renProc (zip cs0 cs') proc0
_ -> p0
_ -> p0
where
p0 = Act (At t p)
pat (Act (At t p)) = Right (t, p)
pat proc0 = Left proc0
renProc bs = renameI r
where
l = bs & each . both %~ view cdChan
m = l2m l
r = Ren (\_ _ x -> pure $ m ^. at x ?| x) ø ø
-- Prism valid up to the reduction rules
__Act :: Prism' Proc Act
__Act = prism con pat
where
con act = Act act & _ActAt %~ id
& expandFwd
pat (Act act) = Right act
pat proc0 = Left proc0
-- This is not really about some sort of Weak Head Normal Form.
-- What matters is:
-- * To reduce the At constructor:
-- @(proc(Γ) P){Γ} -> P
-- * Push LetP
instance HasReduce Proc Proc where
reduce sp =
case sp ^. scoped of
Act act -> reduce_ (_ActAt . _1) (sp $> Act act)
proc0 `Dot` proc1 -> (dotP :: Op2 Proc) <$> reduce (sp $> proc0) <*> reduce (sp $> proc1)
LetP defs proc0 ->
reduce (sp *> Scoped defs ø () $> proc0) & reduced . scoped %~ LetP defs
Replicate k r n p ->
mkReplicate k <$> reducedOrReduce (sp $> r) <*> pure n <*> reduce (sp $> p)
Procs procs -> procs ^. each . to (reduce . (sp $>))
|
np/ling
|
Ling/Reduce.hs
|
bsd-3-clause
| 11,822 | 0 | 18 | 3,714 | 4,349 | 2,183 | 2,166 | -1 | -1 |
module Web.ChatWork.Endpoints.Base (
baseURL,
ChatWorkAPI
) where
import Web.ChatWork.Internal
type ChatWorkAPI a = (Maybe RateLimit, a)
baseURL :: String
baseURL = "https://api.chatwork.com/v1"
|
eiel/haskell-chatwork
|
src/Web/ChatWork/Endpoints/Base.hs
|
bsd-3-clause
| 203 | 0 | 6 | 30 | 48 | 31 | 17 | 7 | 1 |
{-# OPTIONS #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Python.Version2.Lexer
-- Copyright : (c) 2009 Bernie Pope
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : ghc
--
-- Lexical analysis for Python version 2.x programs.
-- See: <http://www.python.org/doc/2.6/reference/lexical_analysis.html>.
-----------------------------------------------------------------------------
module Language.Python.Version2.Lexer (
-- * Lexical analysis
lex,
lexOneToken) where
import Prelude hiding (lex)
import Language.Python.Version2.Parser.Lexer (lexToken, initStartCodeStack)
import Language.Python.Common.Token as Token
import Language.Python.Common.SrcLocation (initialSrcLocation)
import Language.Python.Common.ParserMonad
(ParseState (input), P, runParser, execParser, ParseError, initialState)
-- | Parse a string into a list of Python Tokens, or return an error.
lex :: String -- ^ The input stream (python source code).
-> String -- ^ The name of the python source (filename or input device).
-> Either ParseError [Token] -- ^ An error or a list of tokens.
lex input srcName =
execParser lexer state
where
initLoc = initialSrcLocation srcName
state = initialState initLoc input initStartCodeStack
-- | Try to lex the first token in an input string. Return either a parse error
-- or a pair containing the next token and the rest of the input after the token.
lexOneToken :: String -- ^ The input stream (python source code).
-> String -- ^ The name of the python source (filename or input device).
-> Either ParseError (Token, String) -- ^ An error or the next token and the rest of the input after the token.
lexOneToken source srcName =
case runParser lexToken state of
Left err -> Left err
Right (tok, state) -> Right (tok, input state)
where
initLoc = initialSrcLocation srcName
state = initialState initLoc source initStartCodeStack
lexer :: P [Token]
lexer = loop []
where
loop toks = do
tok <- lexToken
case tok of
EOFToken {} -> return (reverse toks)
other -> loop (tok:toks)
|
jml/language-python
|
src/Language/Python/Version2/Lexer.hs
|
bsd-3-clause
| 2,246 | 0 | 14 | 436 | 358 | 207 | 151 | 33 | 2 |
module Core.Types where
type Number = Integer
data Expr a = EVar Name
| ENum Number
| EConstr Number Number
| EAp (Expr a) (Expr a)
| ELet IsRec [(a, Expr a)] (Expr a)
| ECase (Expr a) [Alter a]
| ELam [a] (Expr a)
deriving Show
type CoreExpr = Expr Name
type Name = String
type IsRec = Bool
type Alter a = (Number, [a], Expr a)
type CoreAlt = Alter Name
type Program a = [ScDefn a]
type CoreProgram = Program String
type ScDefn a = (Name, [a], Expr a)
type CoreScDefn = ScDefn String
type Iseq = IseqRep
data IseqRep = INil
| IStr [Char]
| IAppend IseqRep IseqRep
| IIndent IseqRep
| INewline
deriving Show
type Token = [Char]
|
Fuuzetsu/hcore
|
src/Core/Types.hs
|
bsd-3-clause
| 791 | 0 | 9 | 286 | 271 | 161 | 110 | 27 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module SMACCMPilot.GCS.Commsec
( BaseId(..)
, SecureContext_HS(..)
, Context
, secPkgInit_HS
, secPkgEncInPlace_HS
, secPkgDec_HS
) where
import Data.Word
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Crypto.Cipher.AES -- Vincent's GCM routine
import Crypto.Cipher.Types
import Data.IORef
import Data.Serialize
--------------------------------------------------------------------------------
--Types
-- BaseId includes the UAV.
newtype BaseId = BaseId Word32
deriving (Eq, Ord, Show, Num)
instance Serialize BaseId where
get = BaseId `fmap` getWord32be
put (BaseId x) = putWord32be x
-- Key, salt, station ID, counter
type OutContext = (AES, Word32, BaseId, Word32)
-- You can have many senders, so we have a list of id/counter pairs.
type InContext = (AES, Word32, [(BaseId,Word32)])
data SecureContext_HS = SC { inContext :: InContext
, outContext :: OutContext
}
type Context = IORef SecureContext_HS
-- Decryption failures
data Failure = CntrTooBig
| CntTooOld
| UnknownId
| BadTag B.ByteString B.ByteString
| CommsecTooShort Int
deriving (Read, Eq)
instance Show Failure where
show failure = commsecErr (msg failure)
where
msg CntrTooBig = "Counter has overflowed!"
msg CntTooOld = "Counter is stale!"
msg UnknownId = "Unknown sender!"
msg (BadTag tag tag') = "Incorrect authentication tag! rx tag: "
++ show (B.unpack tag) ++ " computed tag "
++ show (B.unpack tag')
msg (CommsecTooShort len) = "Commsec too short: received length: "
++ show len
----------------------------------------------------------------------
commsecPkg :: OutContext -> ByteString
-> (OutContext, Maybe (ByteString,ByteString,ByteString))
commsecPkg ctx@(key,salt,bid,ctr) pt
| ctr == maxBound = (ctx, Nothing)
| otherwise =
let iv = runPut (putWord32be salt >> put bid >> putWord32be ctr)
new = (key,salt,bid,ctr+1)
aad = B.empty
(ct, AuthTag tag) = encryptGCM key iv aad pt
tagLen = 8
header = runPut (put bid >> putWord32be ctr)
in (new, Just (header, ct, B.take tagLen tag))
secPkgEnc_HS :: Context -> ByteString
-> IO (Maybe (ByteString,ByteString,ByteString))
secPkgEnc_HS rc pt = do
atomicModifyIORef' rc $ \(SC _in outbound') ->
let (newOut,res) = commsecPkg outbound' pt in
(SC _in newOut,res)
commsecErr :: String -> String
commsecErr err = "Commsec error: " ++ err
dec :: InContext -> ByteString -> Either Failure (InContext, ByteString)
dec (key,salt,bidList) pkg =
either (const $ Left $ CommsecTooShort $ B.length pkg)
go
parseMsg
where
aad = B.empty
parseMsg =
runGet (do bid' <- get
newCtr' <- getWord32be
pt' <- getByteString . (subtract 8) =<< remaining
tag' <- getByteString =<< remaining
return (bid',newCtr',pt',tag')
) pkg
go (bid,newCtr,ct,tag) =
-- Serialize the salt I have with the sent baseID and updated counter.
let iv = runPut (putWord32be salt >> put bid >> putWord32be newCtr) in
-- Replace the BaseID/Counter pair in the list with the updated pair.
let newBids = (bid,newCtr) : filter ((/= bid) . fst) bidList in
let new = (key, salt, newBids) in
-- Decrypt the message. I get the sent message and auth. tag, if all
-- goes well.
let (pt, AuthTag decTag) = decryptGCM key iv aad ct in
let decTag' = B.take (B.length tag) decTag in
case lookup bid bidList of
Nothing -> Left UnknownId
Just cnt
-- Counter is too high.
| cnt == maxBound -> Left CntrTooBig
-- Counter is too old.
| cnt >= newCtr -> Left CntTooOld
-- Return my updated inContext with the decrypted message.
| decTag' == tag -> Right (new, pt)
-- Bad tag.
| otherwise -> Left (BadTag tag decTag')
initOutContext :: ByteString -> Word32 -> BaseId -> OutContext
initOutContext key salt bid = (initAES key, salt, bid, 1)
initInContext :: ByteString -> Word32 -> InContext
initInContext key salt
= (initAES key, salt, zip (map BaseId [0..]) (replicate 16 0))
--------------------------------------------------------------------------------
-- Main interface functions
-- | Initialize a package returning a context. Takes your ID, salt and key for
-- others to send to you, and salt and key for sending to others. Returns an
-- updated context.
secPkgInit_HS :: BaseId -> Word32 -> ByteString -> Word32 -> ByteString
-> IO Context
secPkgInit_HS b dsalt dkey esalt ekey
= newIORef (SC (initInContext dkey dsalt)
(initOutContext ekey esalt b))
-- | Decrypt a package given a context. Returns the decrypted message, if
-- successful.
secPkgDec_HS :: Context
-> ByteString
-> IO (Either Failure ByteString)
secPkgDec_HS rc pkg =
atomicModifyIORef' rc $ \sc@(SC inbound' _out) ->
let resOrFail = dec inbound' pkg in
case resOrFail of
-- Threw away the message; keep the context the same.
Left err -> (sc, Left err)
Right (newIn, res) -> (SC newIn _out, Right res)
-- | Encrypt a message given a context. Returns the concatenated header
-- (including the sender's ID and message counter), the encrypted message, and
-- the authentication tag.
secPkgEncInPlace_HS :: Context -> ByteString -> IO (Maybe ByteString)
secPkgEncInPlace_HS rc pt = do
r <- secPkgEnc_HS rc pt
return $ fmap (\(a,b,c) -> B.concat [a,b,c]) r
|
GaloisInc/smaccmpilot-gcs-gateway
|
SMACCMPilot/GCS/Commsec.hs
|
bsd-3-clause
| 5,756 | 0 | 23 | 1,470 | 1,550 | 826 | 724 | 110 | 2 |
-- Bombard a 'Clock' with 'clockGetTime' calls, to make sure this does not
-- degrade its accuracy.
import System.Time.Monotonic
import Control.Concurrent (forkOS)
import Control.Monad (forever)
main :: IO ()
main = do
clock <- newClock
putStrLn $ "Using " ++ clockDriverName clock
_ <- forkOS $ forever $ clockGetTime clock
_ <- forkOS $ forever $ clockGetTime clock
_ <- forkOS $ forever $ clockGetTime clock
forever $ do
print =<< clockGetTime clock
_ <- getLine
return ()
|
joeyadams/haskell-system-time-monotonic
|
testing/bombard.hs
|
bsd-3-clause
| 543 | 0 | 11 | 145 | 151 | 72 | 79 | 14 | 1 |
module Parse.Expression (term, typeAnnotation, definition, expr) where
import Control.Applicative ((<$>), (<*>))
import qualified Data.List as List
import Text.Parsec hiding (newline, spaces)
import Text.Parsec.Indent (block, withPos)
import qualified Parse.Binop as Binop
import Parse.Helpers
import qualified Parse.Helpers as Help
import qualified Parse.Literal as Literal
import qualified Parse.Pattern as Pattern
import qualified Parse.Type as Type
import qualified AST.Expression.General as E
import qualified AST.Expression.Source as Source
import qualified AST.Literal as L
import qualified AST.Pattern as P
import qualified AST.Variable as Var
import qualified Reporting.Annotation as A
-------- Basic Terms --------
varTerm :: IParser Source.Expr'
varTerm =
toVar <$> var
toVar :: String -> Source.Expr'
toVar v =
case v of
"True" ->
E.Literal (L.Boolean True)
"False" ->
E.Literal (L.Boolean False)
_ ->
E.rawVar v
accessor :: IParser Source.Expr'
accessor =
do (start, lbl, end) <- located (try (string "." >> rLabel))
let ann value =
A.at start end value
return $
E.Lambda
(ann (P.Var "_"))
(ann (E.Access (ann (E.rawVar "_")) lbl))
negative :: IParser Source.Expr'
negative =
do (start, nTerm, end) <-
located $ try $
do char '-'
notFollowedBy (char '.' <|> char '-')
term
let ann e =
A.at start end e
return $
E.Binop
(Var.Raw "-")
(ann (E.Literal (L.IntNum 0)))
nTerm
-------- Complex Terms --------
listTerm :: IParser Source.Expr'
listTerm =
shader' <|> braces (try range <|> E.ExplicitList <$> commaSep expr)
where
range =
do lo <- expr
padded (string "..")
E.Range lo <$> expr
shader' =
do pos <- getPosition
let uid = show (sourceLine pos) ++ ":" ++ show (sourceColumn pos)
(rawSrc, tipe) <- Help.shader
return $ E.GLShader uid (filter (/='\r') rawSrc) tipe
parensTerm :: IParser Source.Expr
parensTerm =
choice
[ try (parens opFn)
, parens (tupleFn <|> parened)
]
where
lambda start end x body =
A.at start end (E.Lambda (A.at start end (P.Var x)) body)
var start end x =
A.at start end (E.rawVar x)
opFn =
do (start, op, end) <- located anyOp
return $
lambda start end "x" $
lambda start end "y" $
A.at start end $
E.Binop (Var.Raw op) (var start end "x") (var start end "y")
tupleFn =
do (start, commas, end) <-
located (comma >> many (whitespace >> comma))
let vars = map (('v':) . show) [ 0 .. length commas + 1 ]
return $
foldr
(lambda start end)
(A.at start end (E.tuple (map (var start end) vars)))
vars
parened =
do (start, expressions, end) <- located (commaSep expr)
return $
case expressions of
[expression] ->
expression
_ ->
A.at start end (E.tuple expressions)
recordTerm :: IParser Source.Expr
recordTerm =
addLocation $ brackets $ choice $
[ do starter <- try (addLocation rLabel)
whitespace
choice
[ update starter
, literal starter
]
, return (E.Record [])
]
where
update (A.A ann starter) =
do try (string "|")
whitespace
fields <- commaSep1 field
return (E.Update (A.A ann (E.rawVar starter)) fields)
literal (A.A _ starter) =
do try equals
whitespace
value <- expr
whitespace
choice
[ do try comma
whitespace
fields <- commaSep field
return (E.Record ((starter, value) : fields))
, return (E.Record [(starter, value)])
]
field =
do key <- rLabel
padded equals
value <- expr
return (key, value)
term :: IParser Source.Expr
term =
addLocation (choice [ E.Literal <$> Literal.literal, listTerm, accessor, negative ])
<|> accessible (addLocation varTerm <|> parensTerm <|> recordTerm)
<?> "an expression"
-------- Applications --------
appExpr :: IParser Source.Expr
appExpr =
expecting "an expression" $
do t <- term
ts <- constrainedSpacePrefix term $ \str ->
if null str then notFollowedBy (char '-') else return ()
return $
case ts of
[] -> t
_ -> List.foldl' (\f x -> A.merge f x $ E.App f x) t ts
-------- Normal Expressions --------
expr :: IParser Source.Expr
expr =
addLocation (choice [ letExpr, caseExpr, ifExpr ])
<|> lambdaExpr
<|> binaryExpr
<?> "an expression"
binaryExpr :: IParser Source.Expr
binaryExpr =
Binop.binops appExpr lastExpr anyOp
where
lastExpr =
addLocation (choice [ letExpr, caseExpr, ifExpr ])
<|> lambdaExpr
<?> "an expression"
ifExpr :: IParser Source.Expr'
ifExpr =
ifHelp []
ifHelp :: [(Source.Expr, Source.Expr)] -> IParser Source.Expr'
ifHelp branches =
do try (reserved "if")
whitespace
condition <- expr
padded (reserved "then")
thenBranch <- expr
whitespace <?> "an 'else' branch"
reserved "else" <?> "an 'else' branch"
whitespace
let newBranches = (condition, thenBranch) : branches
choice
[ ifHelp newBranches
, E.If (reverse newBranches) <$> expr
]
lambdaExpr :: IParser Source.Expr
lambdaExpr =
do char '\\' <|> char '\x03BB' <?> "an anonymous function"
whitespace
args <- spaceSep1 Pattern.term
padded rightArrow
body <- expr
return (makeFunction args body)
caseExpr :: IParser Source.Expr'
caseExpr =
do try (reserved "case")
e <- padded expr
reserved "of"
whitespace
E.Case e <$> (with <|> without)
where
case_ =
do p <- Pattern.expr
padded rightArrow
(,) p <$> expr
with =
brackets (semiSep1 (case_ <?> "cases { x -> ... }"))
without =
block (do c <- case_ ; whitespace ; return c)
-- LET
letExpr :: IParser Source.Expr'
letExpr =
do try (reserved "let")
whitespace
defs <-
block $
do def <- typeAnnotation <|> definition
whitespace
return def
padded (reserved "in")
E.Let defs <$> expr
-- TYPE ANNOTATION
typeAnnotation :: IParser Source.Def
typeAnnotation =
addLocation (Source.TypeAnnotation <$> try start <*> Type.expr)
where
start =
do v <- lowVar <|> parens symOp
padded hasType
return v
-- DEFINITION
definition :: IParser Source.Def
definition =
addLocation $
withPos $
do (name:args) <- defStart
padded equals
body <- expr
return . Source.Definition name $ makeFunction args body
makeFunction :: [P.RawPattern] -> Source.Expr -> Source.Expr
makeFunction args body@(A.A ann _) =
foldr (\arg body' -> A.A ann $ E.Lambda arg body') body args
defStart :: IParser [P.RawPattern]
defStart =
choice
[ do pattern <- try Pattern.term
infics pattern <|> func pattern
, do opPattern <- addLocation (P.Var <$> parens symOp)
func opPattern
]
<?> "the definition of a variable (x = ...)"
where
func pattern =
case pattern of
A.A _ (P.Var _) ->
(pattern:) <$> spacePrefix Pattern.term
_ ->
return [pattern]
infics p1 =
do (start, o:p, end) <- try (whitespace >> located anyOp)
p2 <- (whitespace >> Pattern.term)
let opName =
if o == '`' then takeWhile (/='`') p else o:p
return [ A.at start end (P.Var opName), p1, p2 ]
|
pairyo/elm-compiler
|
src/Parse/Expression.hs
|
bsd-3-clause
| 8,033 | 0 | 18 | 2,651 | 2,715 | 1,354 | 1,361 | 244 | 3 |
module Idris.Imports where
import Idris.AbsSyntax
import Idris.Core.TT
import Paths_idris
import System.FilePath
import System.Directory
import Control.Monad.State.Strict
data IFileType = IDR FilePath | LIDR FilePath | IBC FilePath IFileType
deriving (Show, Eq)
srcPath :: FilePath -> FilePath
srcPath fp = let (n, ext) = splitExtension fp in
case ext of
".idr" -> fp
_ -> fp ++ ".idr"
lsrcPath :: FilePath -> FilePath
lsrcPath fp = let (n, ext) = splitExtension fp in
case ext of
".lidr" -> fp
_ -> fp ++ ".lidr"
-- Get name of byte compiled version of an import
ibcPath :: FilePath -> Bool -> FilePath -> FilePath
ibcPath ibcsd use_ibcsd fp = let (d_fp, n_fp) = splitFileName fp
d = if (not use_ibcsd) || ibcsd == ""
then d_fp
else d_fp </> ibcsd
n = dropExtension n_fp
in d </> n <.> "ibc"
ibcPathWithFallback :: FilePath -> FilePath -> IO FilePath
ibcPathWithFallback ibcsd fp = do let ibcp = ibcPath ibcsd True fp
ibc <- doesFileExist ibcp
return (if ibc
then ibcp
else ibcPath ibcsd False fp)
ibcPathNoFallback :: FilePath -> FilePath -> FilePath
ibcPathNoFallback ibcsd fp = ibcPath ibcsd True fp
findImport :: [FilePath] -> FilePath -> FilePath -> IO IFileType
findImport [] ibcsd fp = fail $ "Can't find import " ++ fp
findImport (d:ds) ibcsd fp = do let fp_full = d </> fp
ibcp <- ibcPathWithFallback ibcsd fp_full
let idrp = srcPath fp_full
let lidrp = lsrcPath fp_full
ibc <- doesFileExist ibcp
idr <- doesFileExist idrp
lidr <- doesFileExist lidrp
-- when idr $ putStrLn $ idrp ++ " ok"
-- when lidr $ putStrLn $ lidrp ++ " ok"
-- when ibc $ putStrLn $ ibcp ++ " ok"
let isrc = if lidr
then LIDR lidrp
else IDR idrp
if ibc
then return (IBC ibcp isrc)
else if (idr || lidr)
then return isrc
else findImport ds ibcsd fp
-- find a specific filename somewhere in a path
findInPath :: [FilePath] -> FilePath -> IO FilePath
findInPath [] fp = fail $ "Can't find file " ++ fp
findInPath (d:ds) fp = do let p = d </> fp
e <- doesFileExist p
if e then return p else findInPath ds fp
|
ctford/Idris-Elba-dev
|
src/Idris/Imports.hs
|
bsd-3-clause
| 3,075 | 0 | 13 | 1,450 | 704 | 355 | 349 | 56 | 4 |
{-# LANGUAGE MultiWayIf #-}
module Main where
import Control.Monad (when, unless)
import Data.Char (toUpper)
import Data.Maybe (fromMaybe)
import qualified ZipMenu as M
import ZipMenu (Menu (..), WithStatus, MenuStatus (..))
main :: IO ()
main = do
let loop z = do
print z
-- putStrLn $ M.drawMenu . M.toMenu $ z
putChar '\n'
putStrLn $ filter (/= '"') . M.drawMenu . M.toMenuWithInfo $ z
putChar '\n'
putStrLn "# Menu Tree"
renderTest . M.toMenuWithInfo $ z
putChar '\n'
putStrLn "# cursor"
print $ M.cursor z
putChar '\n'
putStrLn "# path"
print $ M.path z
putChar '\n'
putStrLn "# siblings"
print $ M.siblings z
putChar '\n'
putStrLn "== Move cursor by =="
putStrLn " [w] : prev"
putStrLn " [s] : next"
putStrLn " [a] : up"
putStrLn " [d] : down, action"
putChar '\n'
putStrLn " [ ] : top"
putStrLn "===================="
putStrLn " "
a <- getChar
putChar '\n'
let z' = manipulate a z
quit = case M.path z' of
(Yes True:Exit:_) -> True
_ -> False
unless quit $
loop $ adjust z'
loop $ fromMaybe z0 $ M.down z0
where
z0 = M.fromMenu myMenu
manipulate a z = func z
where
safe = fromMaybe z
func = case a of
'w' -> fromMaybe (M.rightMost z) . M.left
's' -> fromMaybe (M.leftMost z) . M.right
'd' -> fromMaybe (action z) . down'
'a' -> safe . M.up
' ' -> M.upmost
_ -> id
adjust z = unselect $
case M.cursor z of
No True -> fromMaybe z $ M.up z
_ -> z
unselect = M.zmap work
where
work (Yes _) = Yes False
work (No _) = No False
work t = t
action = M.modify work
where
work (Switch a) = Switch $ not a
work (Counter a) = Counter $ a + 1
work (Yes _) = Yes True
work (No _) = No True
work item = item
down' z
| M.cursor z == Exit = M.downTo isNo z
| otherwise = M.down z
where
isNo (No _) = True
isNo _ = False
data MyItem
= Root
| Start
| Option
| OptA
| OptB
| Switch Bool
| Counter Int
| OptC
| Credit
| Exit
--
| Yes Bool
| No Bool
deriving (Show, Eq)
myMenu :: Menu MyItem
myMenu =
Sub Root
[ Item Start
, Sub Option
[ Item OptA
, Sub OptB
[ Item (Switch False)
, Item (Counter 0)
]
, Item OptC
]
, Item Credit
, Sub Exit
[ Item (Yes False)
, Item (No False)
]
]
renderTest :: Menu (WithStatus MyItem) -> IO ()
renderTest = go 0
where
go depth m = do
putStrLn $ indent ++ cursor ++ mark:' ':show a
case m of
(Item _) -> return ()
(Sub _ ts) -> when (mInfo == Just OpenSub) $ mapM_ (go (depth + 1)) ts
where
isSub = case m of
(Sub _ _) -> True
_ -> False
(mInfo,a) = M.contentOf m
indent = replicate (2*depth) ' '
cursor = if mInfo == Just Focus
then "> "
else " "
mark = if | mInfo == Just OpenSub -> '-'
| isSub -> '+'
| otherwise -> '.'
|
masatoko/zip-menu
|
example/Main.hs
|
bsd-3-clause
| 3,513 | 0 | 20 | 1,501 | 1,238 | 597 | 641 | 119 | 15 |
{-- snippet module --}
import Control.Concurrent (forkIO)
import Control.Exception (handle)
import Control.Monad (forever)
import qualified Data.ByteString.Lazy as L
import System.Console.Readline (readline)
-- Provided by the 'zlib' package on http://hackage.haskell.org/
import Codec.Compression.GZip (compress)
main = do
maybeLine <- readline "Enter a file to compress> "
case maybeLine of
Nothing -> return () -- user entered EOF
Just "" -> return () -- treat no name as "want to quit"
Just name -> do
handle print $ do
content <- L.readFile name
forkIO (compressFile name content)
return ()
main
where compressFile path = L.writeFile (path ++ ".gz") . compress
{-- /snippet module --}
|
binesiyu/ifl
|
examples/ch24/Compressor.hs
|
mit
| 791 | 0 | 17 | 202 | 196 | 101 | 95 | 18 | 3 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
|
evolutics/haskell-formatter
|
testsuite/resources/source/handles_options_ghc_pragma/Output.hs
|
gpl-3.0
| 49 | 0 | 2 | 4 | 3 | 2 | 1 | 1 | 0 |
module Main where
import Control.Monad
import HROOT
main :: IO ()
main = do
tcanvas <- newTCanvas "Test" "Test" 640 480
h1 <- newTH1F "test" "test" 100 (-5.0) 5.0
tRandom <- newTRandom 65535
let generator = gaus tRandom 0 2
let go n | n < 0 = return ()
| otherwise = do
histfill generator h1
go (n-1)
go 1000000
draw h1 ""
saveAs tcanvas "random1d.pdf" ""
saveAs tcanvas "random1d.jpg" ""
saveAs tcanvas "random1d.png" ""
delete h1
delete tcanvas
histfill :: IO Double -> TH1F -> IO ()
histfill gen hist = do
x <- gen
fill1 hist x
return ()
|
wavewave/HROOT
|
HROOT-generate/template/HROOT-math/example/random1d.hs
|
gpl-3.0
| 634 | 0 | 15 | 195 | 259 | 114 | 145 | 25 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EMR.Types.Sum
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.EMR.Types.Sum where
import Network.AWS.Prelude
data ActionOnFailure
= CancelAndWait
| Continue
| TerminateCluster
| TerminateJobFlow
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ActionOnFailure where
parser = takeLowerText >>= \case
"cancel_and_wait" -> pure CancelAndWait
"continue" -> pure Continue
"terminate_cluster" -> pure TerminateCluster
"terminate_job_flow" -> pure TerminateJobFlow
e -> fromTextError $ "Failure parsing ActionOnFailure from value: '" <> e
<> "'. Accepted values: CANCEL_AND_WAIT, CONTINUE, TERMINATE_CLUSTER, TERMINATE_JOB_FLOW"
instance ToText ActionOnFailure where
toText = \case
CancelAndWait -> "CANCEL_AND_WAIT"
Continue -> "CONTINUE"
TerminateCluster -> "TERMINATE_CLUSTER"
TerminateJobFlow -> "TERMINATE_JOB_FLOW"
instance Hashable ActionOnFailure
instance ToByteString ActionOnFailure
instance ToQuery ActionOnFailure
instance ToHeader ActionOnFailure
instance ToJSON ActionOnFailure where
toJSON = toJSONText
instance FromJSON ActionOnFailure where
parseJSON = parseJSONText "ActionOnFailure"
data ClusterState
= CSBootstrapping
| CSRunning
| CSStarting
| CSTerminated
| CSTerminatedWithErrors
| CSTerminating
| CSWaiting
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ClusterState where
parser = takeLowerText >>= \case
"bootstrapping" -> pure CSBootstrapping
"running" -> pure CSRunning
"starting" -> pure CSStarting
"terminated" -> pure CSTerminated
"terminated_with_errors" -> pure CSTerminatedWithErrors
"terminating" -> pure CSTerminating
"waiting" -> pure CSWaiting
e -> fromTextError $ "Failure parsing ClusterState from value: '" <> e
<> "'. Accepted values: BOOTSTRAPPING, RUNNING, STARTING, TERMINATED, TERMINATED_WITH_ERRORS, TERMINATING, WAITING"
instance ToText ClusterState where
toText = \case
CSBootstrapping -> "BOOTSTRAPPING"
CSRunning -> "RUNNING"
CSStarting -> "STARTING"
CSTerminated -> "TERMINATED"
CSTerminatedWithErrors -> "TERMINATED_WITH_ERRORS"
CSTerminating -> "TERMINATING"
CSWaiting -> "WAITING"
instance Hashable ClusterState
instance ToByteString ClusterState
instance ToQuery ClusterState
instance ToHeader ClusterState
instance ToJSON ClusterState where
toJSON = toJSONText
instance FromJSON ClusterState where
parseJSON = parseJSONText "ClusterState"
data ClusterStateChangeReasonCode
= CSCRCAllStepsCompleted
| CSCRCBootstrapFailure
| CSCRCInstanceFailure
| CSCRCInternalError
| CSCRCStepFailure
| CSCRCUserRequest
| CSCRCValidationError
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ClusterStateChangeReasonCode where
parser = takeLowerText >>= \case
"all_steps_completed" -> pure CSCRCAllStepsCompleted
"bootstrap_failure" -> pure CSCRCBootstrapFailure
"instance_failure" -> pure CSCRCInstanceFailure
"internal_error" -> pure CSCRCInternalError
"step_failure" -> pure CSCRCStepFailure
"user_request" -> pure CSCRCUserRequest
"validation_error" -> pure CSCRCValidationError
e -> fromTextError $ "Failure parsing ClusterStateChangeReasonCode from value: '" <> e
<> "'. Accepted values: ALL_STEPS_COMPLETED, BOOTSTRAP_FAILURE, INSTANCE_FAILURE, INTERNAL_ERROR, STEP_FAILURE, USER_REQUEST, VALIDATION_ERROR"
instance ToText ClusterStateChangeReasonCode where
toText = \case
CSCRCAllStepsCompleted -> "ALL_STEPS_COMPLETED"
CSCRCBootstrapFailure -> "BOOTSTRAP_FAILURE"
CSCRCInstanceFailure -> "INSTANCE_FAILURE"
CSCRCInternalError -> "INTERNAL_ERROR"
CSCRCStepFailure -> "STEP_FAILURE"
CSCRCUserRequest -> "USER_REQUEST"
CSCRCValidationError -> "VALIDATION_ERROR"
instance Hashable ClusterStateChangeReasonCode
instance ToByteString ClusterStateChangeReasonCode
instance ToQuery ClusterStateChangeReasonCode
instance ToHeader ClusterStateChangeReasonCode
instance FromJSON ClusterStateChangeReasonCode where
parseJSON = parseJSONText "ClusterStateChangeReasonCode"
data InstanceGroupState
= Arrested
| Bootstrapping
| Ended
| Provisioning
| Resizing
| Running
| ShuttingDown
| Suspended
| Terminated
| Terminating
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText InstanceGroupState where
parser = takeLowerText >>= \case
"arrested" -> pure Arrested
"bootstrapping" -> pure Bootstrapping
"ended" -> pure Ended
"provisioning" -> pure Provisioning
"resizing" -> pure Resizing
"running" -> pure Running
"shutting_down" -> pure ShuttingDown
"suspended" -> pure Suspended
"terminated" -> pure Terminated
"terminating" -> pure Terminating
e -> fromTextError $ "Failure parsing InstanceGroupState from value: '" <> e
<> "'. Accepted values: ARRESTED, BOOTSTRAPPING, ENDED, PROVISIONING, RESIZING, RUNNING, SHUTTING_DOWN, SUSPENDED, TERMINATED, TERMINATING"
instance ToText InstanceGroupState where
toText = \case
Arrested -> "ARRESTED"
Bootstrapping -> "BOOTSTRAPPING"
Ended -> "ENDED"
Provisioning -> "PROVISIONING"
Resizing -> "RESIZING"
Running -> "RUNNING"
ShuttingDown -> "SHUTTING_DOWN"
Suspended -> "SUSPENDED"
Terminated -> "TERMINATED"
Terminating -> "TERMINATING"
instance Hashable InstanceGroupState
instance ToByteString InstanceGroupState
instance ToQuery InstanceGroupState
instance ToHeader InstanceGroupState
instance FromJSON InstanceGroupState where
parseJSON = parseJSONText "InstanceGroupState"
data InstanceGroupStateChangeReasonCode
= ClusterTerminated
| InstanceFailure
| InternalError
| ValidationError
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText InstanceGroupStateChangeReasonCode where
parser = takeLowerText >>= \case
"cluster_terminated" -> pure ClusterTerminated
"instance_failure" -> pure InstanceFailure
"internal_error" -> pure InternalError
"validation_error" -> pure ValidationError
e -> fromTextError $ "Failure parsing InstanceGroupStateChangeReasonCode from value: '" <> e
<> "'. Accepted values: CLUSTER_TERMINATED, INSTANCE_FAILURE, INTERNAL_ERROR, VALIDATION_ERROR"
instance ToText InstanceGroupStateChangeReasonCode where
toText = \case
ClusterTerminated -> "CLUSTER_TERMINATED"
InstanceFailure -> "INSTANCE_FAILURE"
InternalError -> "INTERNAL_ERROR"
ValidationError -> "VALIDATION_ERROR"
instance Hashable InstanceGroupStateChangeReasonCode
instance ToByteString InstanceGroupStateChangeReasonCode
instance ToQuery InstanceGroupStateChangeReasonCode
instance ToHeader InstanceGroupStateChangeReasonCode
instance FromJSON InstanceGroupStateChangeReasonCode where
parseJSON = parseJSONText "InstanceGroupStateChangeReasonCode"
data InstanceGroupType
= Core
| Master
| Task
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText InstanceGroupType where
parser = takeLowerText >>= \case
"core" -> pure Core
"master" -> pure Master
"task" -> pure Task
e -> fromTextError $ "Failure parsing InstanceGroupType from value: '" <> e
<> "'. Accepted values: CORE, MASTER, TASK"
instance ToText InstanceGroupType where
toText = \case
Core -> "CORE"
Master -> "MASTER"
Task -> "TASK"
instance Hashable InstanceGroupType
instance ToByteString InstanceGroupType
instance ToQuery InstanceGroupType
instance ToHeader InstanceGroupType
instance ToJSON InstanceGroupType where
toJSON = toJSONText
instance FromJSON InstanceGroupType where
parseJSON = parseJSONText "InstanceGroupType"
data InstanceRoleType
= IRTCore
| IRTMaster
| IRTTask
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText InstanceRoleType where
parser = takeLowerText >>= \case
"core" -> pure IRTCore
"master" -> pure IRTMaster
"task" -> pure IRTTask
e -> fromTextError $ "Failure parsing InstanceRoleType from value: '" <> e
<> "'. Accepted values: CORE, MASTER, TASK"
instance ToText InstanceRoleType where
toText = \case
IRTCore -> "CORE"
IRTMaster -> "MASTER"
IRTTask -> "TASK"
instance Hashable InstanceRoleType
instance ToByteString InstanceRoleType
instance ToQuery InstanceRoleType
instance ToHeader InstanceRoleType
instance ToJSON InstanceRoleType where
toJSON = toJSONText
data InstanceState
= ISAwaitingFulfillment
| ISBootstrapping
| ISProvisioning
| ISRunning
| ISTerminated
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText InstanceState where
parser = takeLowerText >>= \case
"awaiting_fulfillment" -> pure ISAwaitingFulfillment
"bootstrapping" -> pure ISBootstrapping
"provisioning" -> pure ISProvisioning
"running" -> pure ISRunning
"terminated" -> pure ISTerminated
e -> fromTextError $ "Failure parsing InstanceState from value: '" <> e
<> "'. Accepted values: AWAITING_FULFILLMENT, BOOTSTRAPPING, PROVISIONING, RUNNING, TERMINATED"
instance ToText InstanceState where
toText = \case
ISAwaitingFulfillment -> "AWAITING_FULFILLMENT"
ISBootstrapping -> "BOOTSTRAPPING"
ISProvisioning -> "PROVISIONING"
ISRunning -> "RUNNING"
ISTerminated -> "TERMINATED"
instance Hashable InstanceState
instance ToByteString InstanceState
instance ToQuery InstanceState
instance ToHeader InstanceState
instance FromJSON InstanceState where
parseJSON = parseJSONText "InstanceState"
data InstanceStateChangeReasonCode
= ISCRCBootstrapFailure
| ISCRCClusterTerminated
| ISCRCInstanceFailure
| ISCRCInternalError
| ISCRCValidationError
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText InstanceStateChangeReasonCode where
parser = takeLowerText >>= \case
"bootstrap_failure" -> pure ISCRCBootstrapFailure
"cluster_terminated" -> pure ISCRCClusterTerminated
"instance_failure" -> pure ISCRCInstanceFailure
"internal_error" -> pure ISCRCInternalError
"validation_error" -> pure ISCRCValidationError
e -> fromTextError $ "Failure parsing InstanceStateChangeReasonCode from value: '" <> e
<> "'. Accepted values: BOOTSTRAP_FAILURE, CLUSTER_TERMINATED, INSTANCE_FAILURE, INTERNAL_ERROR, VALIDATION_ERROR"
instance ToText InstanceStateChangeReasonCode where
toText = \case
ISCRCBootstrapFailure -> "BOOTSTRAP_FAILURE"
ISCRCClusterTerminated -> "CLUSTER_TERMINATED"
ISCRCInstanceFailure -> "INSTANCE_FAILURE"
ISCRCInternalError -> "INTERNAL_ERROR"
ISCRCValidationError -> "VALIDATION_ERROR"
instance Hashable InstanceStateChangeReasonCode
instance ToByteString InstanceStateChangeReasonCode
instance ToQuery InstanceStateChangeReasonCode
instance ToHeader InstanceStateChangeReasonCode
instance FromJSON InstanceStateChangeReasonCode where
parseJSON = parseJSONText "InstanceStateChangeReasonCode"
data MarketType
= OnDemand
| Spot
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText MarketType where
parser = takeLowerText >>= \case
"on_demand" -> pure OnDemand
"spot" -> pure Spot
e -> fromTextError $ "Failure parsing MarketType from value: '" <> e
<> "'. Accepted values: ON_DEMAND, SPOT"
instance ToText MarketType where
toText = \case
OnDemand -> "ON_DEMAND"
Spot -> "SPOT"
instance Hashable MarketType
instance ToByteString MarketType
instance ToQuery MarketType
instance ToHeader MarketType
instance ToJSON MarketType where
toJSON = toJSONText
instance FromJSON MarketType where
parseJSON = parseJSONText "MarketType"
data StepState
= SSCancelled
| SSCompleted
| SSFailed
| SSInterrupted
| SSPending
| SSRunning
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText StepState where
parser = takeLowerText >>= \case
"cancelled" -> pure SSCancelled
"completed" -> pure SSCompleted
"failed" -> pure SSFailed
"interrupted" -> pure SSInterrupted
"pending" -> pure SSPending
"running" -> pure SSRunning
e -> fromTextError $ "Failure parsing StepState from value: '" <> e
<> "'. Accepted values: CANCELLED, COMPLETED, FAILED, INTERRUPTED, PENDING, RUNNING"
instance ToText StepState where
toText = \case
SSCancelled -> "CANCELLED"
SSCompleted -> "COMPLETED"
SSFailed -> "FAILED"
SSInterrupted -> "INTERRUPTED"
SSPending -> "PENDING"
SSRunning -> "RUNNING"
instance Hashable StepState
instance ToByteString StepState
instance ToQuery StepState
instance ToHeader StepState
instance ToJSON StepState where
toJSON = toJSONText
instance FromJSON StepState where
parseJSON = parseJSONText "StepState"
data StepStateChangeReasonCode =
None
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText StepStateChangeReasonCode where
parser = takeLowerText >>= \case
"none" -> pure None
e -> fromTextError $ "Failure parsing StepStateChangeReasonCode from value: '" <> e
<> "'. Accepted values: NONE"
instance ToText StepStateChangeReasonCode where
toText = \case
None -> "NONE"
instance Hashable StepStateChangeReasonCode
instance ToByteString StepStateChangeReasonCode
instance ToQuery StepStateChangeReasonCode
instance ToHeader StepStateChangeReasonCode
instance FromJSON StepStateChangeReasonCode where
parseJSON = parseJSONText "StepStateChangeReasonCode"
|
fmapfmapfmap/amazonka
|
amazonka-emr/gen/Network/AWS/EMR/Types/Sum.hs
|
mpl-2.0
| 14,839 | 0 | 12 | 3,192 | 2,737 | 1,376 | 1,361 | 356 | 0 |
module Hailstorm.Topology
( Topology(..)
, ProcessorAddress
) where
import Hailstorm.Payload
import Hailstorm.Processor
type ProcessorHost = String
type ProcessorPort = String
type ProcessorAddress = (ProcessorHost, ProcessorPort)
class Topology t where
-- | Returns a list of processor nodes (of various types).
spouts :: t -> [ProcessorNode]
bolts :: t -> [ProcessorNode]
sinks :: t -> [ProcessorNode]
lookupProcessor :: ProcessorName -> t -> Maybe ProcessorNode
lookupProcessorWithFailure :: ProcessorName -> t -> ProcessorNode
downstreamAddresses :: t
-> ProcessorName
-> Payload
-> [ProcessorAddress]
addressFor :: t -> ProcessorId -> ProcessorAddress
numProcessors :: t -> Int
|
hailstorm-hs/hailstorm
|
src/Hailstorm/Topology.hs
|
apache-2.0
| 802 | 0 | 10 | 210 | 169 | 98 | 71 | 20 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ViewPatterns #-}
-- | Extra Path utilities.
module Path.Extra
(toFilePathNoTrailingSep
,dropRoot
,parseCollapsedAbsDir
,parseCollapsedAbsFile
,concatAndColapseAbsDir
,rejectMissingFile
,rejectMissingDir
,pathToByteString
,pathToLazyByteString
,pathToText
,tryGetModificationTime
) where
import Data.Bool (bool)
import Data.Time (UTCTime)
import Path
import Path.IO
import Path.Internal (Path(..))
import Stack.Prelude
import System.IO.Error (isDoesNotExistError)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified System.FilePath as FP
-- | Convert to FilePath but don't add a trailing slash.
toFilePathNoTrailingSep :: Path loc Dir -> FilePath
toFilePathNoTrailingSep = FP.dropTrailingPathSeparator . toFilePath
-- | Collapse intermediate "." and ".." directories from path, then parse
-- it with 'parseAbsDir'.
-- (probably should be moved to the Path module)
parseCollapsedAbsDir :: MonadThrow m => FilePath -> m (Path Abs Dir)
parseCollapsedAbsDir = parseAbsDir . collapseFilePath
-- | Collapse intermediate "." and ".." directories from path, then parse
-- it with 'parseAbsFile'.
-- (probably should be moved to the Path module)
parseCollapsedAbsFile :: MonadThrow m => FilePath -> m (Path Abs File)
parseCollapsedAbsFile = parseAbsFile . collapseFilePath
-- | Add a relative FilePath to the end of a Path
-- We can't parse the FilePath first because we need to account for ".."
-- in the FilePath (#2895)
concatAndColapseAbsDir :: MonadThrow m => Path Abs Dir -> FilePath -> m (Path Abs Dir)
concatAndColapseAbsDir base rel = parseCollapsedAbsDir (toFilePath base FP.</> rel)
-- | Collapse intermediate "." and ".." directories from a path.
--
-- > collapseFilePath "./foo" == "foo"
-- > collapseFilePath "/bar/../baz" == "/baz"
-- > collapseFilePath "/../baz" == "/../baz"
-- > collapseFilePath "parent/foo/baz/../bar" == "parent/foo/bar"
-- > collapseFilePath "parent/foo/baz/../../bar" == "parent/bar"
-- > collapseFilePath "parent/foo/.." == "parent"
-- > collapseFilePath "/parent/foo/../../bar" == "/bar"
--
-- (adapted from @Text.Pandoc.Shared@)
collapseFilePath :: FilePath -> FilePath
collapseFilePath = FP.joinPath . reverse . foldl' go [] . FP.splitDirectories
where
go rs "." = rs
go r@(p:rs) ".." = case p of
".." -> "..":r
(checkPathSeparator -> True) -> "..":r
_ -> rs
go _ (checkPathSeparator -> True) = [[FP.pathSeparator]]
go rs x = x:rs
checkPathSeparator [x] = FP.isPathSeparator x
checkPathSeparator _ = False
-- | Drop the root (either @\/@ on POSIX or @C:\\@, @D:\\@, etc. on
-- Windows).
dropRoot :: Path Abs t -> Path Rel t
dropRoot (Path l) = Path (FP.dropDrive l)
-- | If given file in 'Maybe' does not exist, ensure we have 'Nothing'. This
-- is to be used in conjunction with 'forgivingAbsence' and
-- 'resolveFile'.
--
-- Previously the idiom @forgivingAbsence (relsoveFile …)@ alone was used,
-- which relied on 'canonicalizePath' throwing 'isDoesNotExistError' when
-- path does not exist. As it turns out, this behavior is actually not
-- intentional and unreliable, see
-- <https://github.com/haskell/directory/issues/44>. This was “fixed” in
-- version @1.2.3.0@ of @directory@ package (now it never throws). To make
-- it work with all versions, we need to use the following idiom:
--
-- > forgivingAbsence (resolveFile …) >>= rejectMissingFile
rejectMissingFile :: MonadIO m
=> Maybe (Path Abs File)
-> m (Maybe (Path Abs File))
rejectMissingFile Nothing = return Nothing
rejectMissingFile (Just p) = bool Nothing (Just p) `liftM` doesFileExist p
-- | See 'rejectMissingFile'.
rejectMissingDir :: MonadIO m
=> Maybe (Path Abs Dir)
-> m (Maybe (Path Abs Dir))
rejectMissingDir Nothing = return Nothing
rejectMissingDir (Just p) = bool Nothing (Just p) `liftM` doesDirExist p
-- | Convert to a lazy ByteString using toFilePath and UTF8.
pathToLazyByteString :: Path b t -> BSL.ByteString
pathToLazyByteString = BSL.fromStrict . pathToByteString
-- | Convert to a ByteString using toFilePath and UTF8.
pathToByteString :: Path b t -> BS.ByteString
pathToByteString = T.encodeUtf8 . pathToText
pathToText :: Path b t -> T.Text
pathToText = T.pack . toFilePath
tryGetModificationTime :: MonadIO m => Path Abs File -> m (Either () UTCTime)
tryGetModificationTime = liftIO . tryJust (guard . isDoesNotExistError) . getModificationTime
|
MichielDerhaeg/stack
|
src/Path/Extra.hs
|
bsd-3-clause
| 4,696 | 0 | 11 | 866 | 872 | 482 | 390 | 65 | 7 |
-----------------------------------------------------------------------------
--
-- GHCi's :ctags and :etags commands
--
-- (c) The GHC Team 2005-2007
--
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module GhciTags (
createCTagsWithLineNumbersCmd,
createCTagsWithRegExesCmd,
createETagsFileCmd
) where
import Exception
import GHC
import GhciMonad
import Outputable
-- ToDo: figure out whether we need these, and put something appropriate
-- into the GHC API instead
import Name (nameOccName)
import OccName (pprOccName)
import MonadUtils
import Data.Function
import Data.Maybe
import Data.Ord
import Panic
import Data.List
import Control.Monad
import System.IO
import System.IO.Error
-----------------------------------------------------------------------------
-- create tags file for currently loaded modules.
createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd,
createETagsFileCmd :: String -> GHCi ()
createCTagsWithLineNumbersCmd "" =
ghciCreateTagsFile CTagsWithLineNumbers "tags"
createCTagsWithLineNumbersCmd file =
ghciCreateTagsFile CTagsWithLineNumbers file
createCTagsWithRegExesCmd "" =
ghciCreateTagsFile CTagsWithRegExes "tags"
createCTagsWithRegExesCmd file =
ghciCreateTagsFile CTagsWithRegExes file
createETagsFileCmd "" = ghciCreateTagsFile ETags "TAGS"
createETagsFileCmd file = ghciCreateTagsFile ETags file
data TagsKind = ETags | CTagsWithLineNumbers | CTagsWithRegExes
ghciCreateTagsFile :: TagsKind -> FilePath -> GHCi ()
ghciCreateTagsFile kind file = do
createTagsFile kind file
-- ToDo:
-- - remove restriction that all modules must be interpreted
-- (problem: we don't know source locations for entities unless
-- we compiled the module.
--
-- - extract createTagsFile so it can be used from the command-line
-- (probably need to fix first problem before this is useful).
--
createTagsFile :: TagsKind -> FilePath -> GHCi ()
createTagsFile tagskind tagsFile = do
graph <- GHC.getModuleGraph
mtags <- mapM listModuleTags (map GHC.ms_mod graph)
either_res <- liftIO $ collateAndWriteTags tagskind tagsFile $ concat mtags
case either_res of
Left e -> liftIO $ hPutStrLn stderr $ ioeGetErrorString e
Right _ -> return ()
listModuleTags :: GHC.Module -> GHCi [TagInfo]
listModuleTags m = do
is_interpreted <- GHC.moduleIsInterpreted m
-- should we just skip these?
when (not is_interpreted) $
let mName = GHC.moduleNameString (GHC.moduleName m) in
ghcError (CmdLineError ("module '" ++ mName ++ "' is not interpreted"))
mbModInfo <- GHC.getModuleInfo m
case mbModInfo of
Nothing -> return []
Just mInfo -> do
dflags <- getDynFlags
mb_print_unqual <- GHC.mkPrintUnqualifiedForModule mInfo
let unqual = fromMaybe GHC.alwaysQualify mb_print_unqual
let names = fromMaybe [] $GHC.modInfoTopLevelScope mInfo
let localNames = filter ((m==) . nameModule) names
mbTyThings <- mapM GHC.lookupName localNames
return $! [ tagInfo dflags unqual exported kind name realLoc
| tyThing <- catMaybes mbTyThings
, let name = getName tyThing
, let exported = GHC.modInfoIsExportedName mInfo name
, let kind = tyThing2TagKind tyThing
, let loc = srcSpanStart (nameSrcSpan name)
, RealSrcLoc realLoc <- [loc]
]
where
tyThing2TagKind (AnId _) = 'v'
tyThing2TagKind (ADataCon _) = 'd'
tyThing2TagKind (ATyCon _) = 't'
tyThing2TagKind (ACoAxiom _) = 'x'
data TagInfo = TagInfo
{ tagExported :: Bool -- is tag exported
, tagKind :: Char -- tag kind
, tagName :: String -- tag name
, tagFile :: String -- file name
, tagLine :: Int -- line number
, tagCol :: Int -- column number
, tagSrcInfo :: Maybe (String,Integer) -- source code line and char offset
}
-- get tag info, for later translation into Vim or Emacs style
tagInfo :: DynFlags -> PrintUnqualified -> Bool -> Char -> Name -> RealSrcLoc
-> TagInfo
tagInfo dflags unqual exported kind name loc
= TagInfo exported kind
(showSDocForUser dflags unqual $ pprOccName (nameOccName name))
(showSDocForUser dflags unqual $ ftext (srcLocFile loc))
(srcLocLine loc) (srcLocCol loc) Nothing
collateAndWriteTags :: TagsKind -> FilePath -> [TagInfo] -> IO (Either IOError ())
-- ctags style with the Ex exresion being just the line number, Vim et al
collateAndWriteTags CTagsWithLineNumbers file tagInfos = do
let tags = unlines $ sort $ map showCTag tagInfos
tryIO (writeFile file tags)
-- ctags style with the Ex exresion being a regex searching the line, Vim et al
collateAndWriteTags CTagsWithRegExes file tagInfos = do -- ctags style, Vim et al
tagInfoGroups <- makeTagGroupsWithSrcInfo tagInfos
let tags = unlines $ sort $ map showCTag $concat tagInfoGroups
tryIO (writeFile file tags)
collateAndWriteTags ETags file tagInfos = do -- etags style, Emacs/XEmacs
tagInfoGroups <- makeTagGroupsWithSrcInfo $filter tagExported tagInfos
let tagGroups = map processGroup tagInfoGroups
tryIO (writeFile file $ concat tagGroups)
where
processGroup [] = ghcError (CmdLineError "empty tag file group??")
processGroup group@(tagInfo:_) =
let tags = unlines $ map showETag group in
"\x0c\n" ++ tagFile tagInfo ++ "," ++ show (length tags) ++ "\n" ++ tags
makeTagGroupsWithSrcInfo :: [TagInfo] -> IO [[TagInfo]]
makeTagGroupsWithSrcInfo tagInfos = do
let groups = groupBy ((==) `on` tagFile) $ sortBy (comparing tagFile) tagInfos
mapM addTagSrcInfo groups
where
addTagSrcInfo [] = ghcError (CmdLineError "empty tag file group??")
addTagSrcInfo group@(tagInfo:_) = do
file <- readFile $tagFile tagInfo
let sortedGroup = sortBy (comparing tagLine) group
return $ perFile sortedGroup 1 0 $ lines file
perFile allTags@(tag:tags) cnt pos allLs@(l:ls)
| tagLine tag > cnt =
perFile allTags (cnt+1) (pos+fromIntegral(length l)) ls
| tagLine tag == cnt =
tag{ tagSrcInfo = Just(l,pos) } : perFile tags cnt pos allLs
perFile _ _ _ _ = []
-- ctags format, for Vim et al
showCTag :: TagInfo -> String
showCTag ti =
tagName ti ++ "\t" ++ tagFile ti ++ "\t" ++ tagCmd ++ ";\"\t" ++
tagKind ti : ( if tagExported ti then "" else "\tfile:" )
where
tagCmd =
case tagSrcInfo ti of
Nothing -> show $tagLine ti
Just (srcLine,_) -> "/^"++ foldr escapeSlashes [] srcLine ++"$/"
where
escapeSlashes '/' r = '\\' : '/' : r
escapeSlashes '\\' r = '\\' : '\\' : r
escapeSlashes c r = c : r
-- etags format, for Emacs/XEmacs
showETag :: TagInfo -> String
showETag TagInfo{ tagName = tag, tagLine = lineNo, tagCol = colNo,
tagSrcInfo = Just (srcLine,charPos) }
= take (colNo - 1) srcLine ++ tag
++ "\x7f" ++ tag
++ "\x01" ++ show lineNo
++ "," ++ show charPos
showETag _ = ghcError (CmdLineError "missing source file info in showETag")
|
hvr/ghci-ng
|
ghc/GhciTags.hs
|
bsd-3-clause
| 7,151 | 0 | 20 | 1,563 | 1,864 | 939 | 925 | 136 | 5 |
module Reddit.Routes.Captcha where
import Reddit.Types.Captcha
import Network.API.Builder.Routes
needsCaptcha :: Route
needsCaptcha = Route [ "api", "needs_captcha.json" ]
[ ]
"GET"
newCaptcha :: Route
newCaptcha = Route [ "api", "new_captcha" ]
[ ]
"POST"
getCaptcha :: CaptchaID -> Route
getCaptcha (CaptchaID c) =
Route [ "captcha", c ]
[ ]
"GET"
|
intolerable/reddit
|
src/Reddit/Routes/Captcha.hs
|
bsd-2-clause
| 453 | 0 | 7 | 153 | 108 | 62 | 46 | 16 | 1 |
{-# LANGUAGE OverlappingInstances, FlexibleInstances, DeriveDataTypeable #-}
module Happstack.Server.UDP
( UDPConfig(..)
, Request(..)
, udpServer
, sendUDPMessage -- :: HostAddress -> PortNumber -> BS.ByteString -> IO ()
) where
import Control.Concurrent
import Control.Exception as E
import Control.Monad (liftM,foldM)
import Data.Typeable
import Foreign
import Foreign.Marshal
import Happstack.Util.Common ( readM )
import Network.Socket hiding (listen)
import System.IO ( IOMode(WriteMode),hClose )
import System.Log.Logger
import qualified Data.ByteString as BS
udpServer :: (Request -> IO ()) -> UDPConfig -> Handler st
udpServer fn conf = IoH $ listen conf fn
-- | UDP configuration
data UDPConfig = UDPConfig
{ bodyLimit :: Int -- ^ Limit on the number of bytes accepted for Requests. Default 2k.
, port :: Int -- ^ Port for the server to listen on. Default 9000.
}
nullUDPConfig = UDPConfig { bodyLimit = 2 * 1024
, port = 9000
}
data Request = Request { udpMsg :: BS.ByteString, udpAddr :: SockAddr} deriving Typeable
instance Show Request where
showsPrec n (Request bs (SockAddrInet port ip)) = showsPrec n (bs, port, ip)
-- FIXME: support SockAddrUnix.
instance Read Request where
readsPrec n str = do ((bs, port, ip),rest) <- readsPrec n str
return (Request bs (SockAddrInet (fromIntegral port) ip), rest)
listen :: UDPConfig -> (Request -> IO ()) -> IO ()
listen conf hand = do
s <- socket AF_INET Datagram 0
bindSocket s (SockAddrInet (fromIntegral $ port conf) iNADDR_ANY)
let work (bs, addr) = hand $ Request bs addr -- hand . uncurry Request
maxInput = 1024*2
loop = recvBSFrom s maxInput >>= forkIO . work >> loop
pe e = logM "Happstack.Server.UDP" ERROR ("ERROR in accept thread: "++show e)
infi = loop `E.catch` pe >> infi
infi
recvBSFrom :: Socket -> Int -> IO (BS.ByteString, SockAddr)
recvBSFrom sock maxLength
= do ptr <- mallocBytes maxLength
(len, sockAddr) <- recvBufFrom sock ptr maxLength
bs <- BS.packCStringLen (ptr,len)
return (bs, sockAddr)
sendUDPMessage :: HostAddress -> PortNumber -> BS.ByteString -> IO ()
sendUDPMessage ip port msg =
do fd <- socket AF_INET Datagram 0
let target = (SockAddrInet (fromIntegral port) ip)
connect fd target
handle <- socketToHandle fd WriteMode
BS.hPut handle msg
hClose handle
|
arybczak/happstack-server
|
src/Happstack/Server/UDP.hs
|
bsd-3-clause
| 2,507 | 0 | 14 | 608 | 754 | 402 | 352 | 54 | 1 |
module PGIP.Output.Mime where
textC :: String
textC = "text/plain"
xmlC :: String
xmlC = "application/xml"
jsonC :: String
jsonC = "application/json"
pdfC :: String
pdfC = "application/pdf"
dotC :: String
dotC = "text/vnd.graphviz"
svgC :: String
svgC = "image/svg+xml"
htmlC :: String
htmlC = "text/html"
|
keithodulaigh/Hets
|
PGIP/Output/Mime.hs
|
gpl-2.0
| 313 | 0 | 4 | 52 | 77 | 47 | 30 | 15 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Provide ability to upload tarballs to Hackage.
module Stack.Upload
( -- * Upload
mkUploader
, Uploader
, upload
, UploadSettings
, defaultUploadSettings
, setUploadUrl
, setGetManager
, setCredsSource
, setSaveCreds
-- * Credentials
, HackageCreds
, loadCreds
, saveCreds
, FromFile
-- ** Credentials source
, HackageCredsSource
, fromAnywhere
, fromPrompt
, fromFile
, fromMemory
) where
import Control.Applicative ((<$>), (<*>))
import Control.Exception (bracket)
import qualified Control.Exception as E
import Control.Monad (when)
import Data.Aeson (FromJSON (..),
ToJSON (..),
eitherDecode', encode,
object, withObject,
(.:), (.=))
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy as L
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import qualified Data.Text.IO as TIO
import Data.Typeable (Typeable)
import Network.HTTP.Client (BodyReader, Manager,
Response,
applyBasicAuth, brRead,
checkStatus, newManager,
parseUrl,
requestHeaders,
responseBody,
responseStatus,
withResponse)
import Network.HTTP.Client.MultipartFormData (formDataBody, partFile)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types (statusCode)
import Path (toFilePath)
import Stack.Types
import System.Directory (createDirectoryIfMissing,
doesDirectoryExist,
doesFileExist,
getDirectoryContents,
removeFile)
import System.Exit (ExitCode (ExitSuccess))
import System.FilePath (takeExtension, (</>))
import System.IO (hClose, hFlush,
hGetEcho, hSetEcho,
stdin, stdout)
import System.IO.Temp (withSystemTempDirectory)
import System.Process (StdStream (CreatePipe),
createProcess, cwd,
proc, std_in,
waitForProcess)
-- | Username and password to log into Hackage.
--
-- Since 0.1.0.0
data HackageCreds = HackageCreds
{ hcUsername :: !Text
, hcPassword :: !Text
}
deriving Show
instance ToJSON HackageCreds where
toJSON (HackageCreds u p) = object
[ "username" .= u
, "password" .= p
]
instance FromJSON HackageCreds where
parseJSON = withObject "HackageCreds" $ \o -> HackageCreds
<$> o .: "username"
<*> o .: "password"
-- | A source for getting Hackage credentials.
--
-- Since 0.1.0.0
newtype HackageCredsSource = HackageCredsSource
{ getCreds :: IO (HackageCreds, FromFile)
}
-- | Whether the Hackage credentials were loaded from a file.
--
-- This information is useful since, typically, you only want to save the
-- credentials to a file if it wasn't already loaded from there.
--
-- Since 0.1.0.0
type FromFile = Bool
-- | Load Hackage credentials from the given source.
--
-- Since 0.1.0.0
loadCreds :: HackageCredsSource -> IO (HackageCreds, FromFile)
loadCreds = getCreds
-- | Save the given credentials to the credentials file.
--
-- Since 0.1.0.0
saveCreds :: Config -> HackageCreds -> IO ()
saveCreds config creds = do
fp <- credsFile config
L.writeFile fp $ encode creds
-- | Load the Hackage credentials from the prompt, asking the user to type them
-- in.
--
-- Since 0.1.0.0
fromPrompt :: HackageCredsSource
fromPrompt = HackageCredsSource $ do
putStr "Hackage username: "
hFlush stdout
username <- TIO.getLine
password <- promptPassword
return (HackageCreds
{ hcUsername = username
, hcPassword = password
}, False)
credsFile :: Config -> IO FilePath
credsFile config = do
let dir = toFilePath (configStackRoot config) </> "upload"
createDirectoryIfMissing True dir
return $ dir </> "credentials.json"
-- | Load the Hackage credentials from the JSON config file.
--
-- Since 0.1.0.0
fromFile :: Config -> HackageCredsSource
fromFile config = HackageCredsSource $ do
fp <- credsFile config
lbs <- L.readFile fp
case eitherDecode' lbs of
Left e -> E.throwIO $ Couldn'tParseJSON fp e
Right creds -> return (creds, True)
-- | Load the Hackage credentials from the given arguments.
--
-- Since 0.1.0.0
fromMemory :: Text -> Text -> HackageCredsSource
fromMemory u p = HackageCredsSource $ return (HackageCreds
{ hcUsername = u
, hcPassword = p
}, False)
data HackageCredsExceptions = Couldn'tParseJSON FilePath String
deriving (Show, Typeable)
instance E.Exception HackageCredsExceptions
-- | Try to load the credentials from the config file. If that fails, ask the
-- user to enter them.
--
-- Since 0.1.0.0
fromAnywhere :: Config -> HackageCredsSource
fromAnywhere config = HackageCredsSource $
getCreds (fromFile config) `E.catches`
[ E.Handler $ \(_ :: E.IOException) -> getCreds fromPrompt
, E.Handler $ \(_ :: HackageCredsExceptions) -> getCreds fromPrompt
]
-- | Lifted from cabal-install, Distribution.Client.Upload
promptPassword :: IO Text
promptPassword = do
putStr "Hackage password: "
hFlush stdout
-- save/restore the terminal echoing status
passwd <- bracket (hGetEcho stdin) (hSetEcho stdin) $ \_ -> do
hSetEcho stdin False -- no echoing for entering the password
fmap T.pack getLine
putStrLn ""
return passwd
-- | Turn the given settings into an @Uploader@.
--
-- Since 0.1.0.0
mkUploader :: Config -> UploadSettings -> IO Uploader
mkUploader config us = do
manager <- usGetManager us
(creds, fromFile') <- loadCreds $ usCredsSource us config
when (not fromFile' && usSaveCreds us) $ saveCreds config creds
req0 <- parseUrl $ usUploadUrl us
let req1 = req0
{ requestHeaders = [("Accept", "text/plain")]
, checkStatus = \_ _ _ -> Nothing
}
return Uploader
{ upload_ = \fp0 -> withTarball fp0 $ \fp -> do
let formData = [partFile "package" fp]
req2 <- formDataBody formData req1
let req3 = applyBasicAuth
(encodeUtf8 $ hcUsername creds)
(encodeUtf8 $ hcPassword creds)
req2
putStr $ "Uploading " ++ fp ++ "... "
hFlush stdout
withResponse req3 manager $ \res ->
case statusCode $ responseStatus res of
200 -> putStrLn "done!"
401 -> do
putStrLn "authentication failure"
cfp <- credsFile config
handleIO (const $ return ()) (removeFile cfp)
error $ "Authentication failure uploading to server"
403 -> do
putStrLn "forbidden upload"
putStrLn "Usually means: you've already uploaded this package/version combination"
putStrLn "Ignoring error and continuing, full message from Hackage below:\n"
printBody res
503 -> do
putStrLn "service unavailable"
putStrLn "This error some times gets sent even though the upload succeeded"
putStrLn "Check on Hackage to see if your pacakge is present"
printBody res
code -> do
putStrLn $ "unhandled status code: " ++ show code
printBody res
error $ "Upload failed on " ++ fp
}
-- | Given either a file, return it. Given a directory, run @cabal sdist@ and
-- get the resulting tarball.
withTarball :: FilePath -> (FilePath -> IO a) -> IO a
withTarball fp0 inner = do
isFile <- doesFileExist fp0
if isFile then inner fp0 else withSystemTempDirectory "stackage-upload-tarball" $ \dir -> do
isDir <- doesDirectoryExist fp0
when (not isDir) $ error $ "Invalid argument: " ++ fp0
(Just h, Nothing, Nothing, ph) <-
-- The insanity: the Cabal library seems to sometimes generate tarballs
-- in the wrong format. For now, just falling back to cabal-install.
-- Sigh.
createProcess $ (proc "cabal"
[ "sdist"
, "--builddir=" ++ dir
])
{ cwd = Just fp0
, std_in = CreatePipe
}
hClose h
ec <- waitForProcess ph
when (ec /= ExitSuccess) $
error $ "Could not create tarball for " ++ fp0
contents <- getDirectoryContents dir
case filter ((== ".gz") . takeExtension) contents of
[x] -> inner (dir </> x)
_ -> error $ "Unexpected directory contents after cabal sdist: " ++ show contents
printBody :: Response BodyReader -> IO ()
printBody res =
loop
where
loop = do
bs <- brRead $ responseBody res
when (not $ S.null bs) $ do
S.hPut stdout bs
loop
-- | The computed value from a @UploadSettings@.
--
-- Typically, you want to use this with 'upload'.
--
-- Since 0.1.0.0
data Uploader = Uploader
{ upload_ :: !(FilePath -> IO ())
}
-- | Upload a single tarball with the given @Uploader@.
--
-- Since 0.1.0.0
upload :: Uploader -> FilePath -> IO ()
upload = upload_
-- | Settings for creating an @Uploader@.
--
-- Since 0.1.0.0
data UploadSettings = UploadSettings
{ usUploadUrl :: !String
, usGetManager :: !(IO Manager)
, usCredsSource :: !(Config -> HackageCredsSource)
, usSaveCreds :: !Bool
}
-- | Default value for @UploadSettings@.
--
-- Use setter functions to change defaults.
--
-- Since 0.1.0.0
defaultUploadSettings :: UploadSettings
defaultUploadSettings = UploadSettings
{ usUploadUrl = "https://hackage.haskell.org/packages/"
, usGetManager = newManager tlsManagerSettings
, usCredsSource = fromAnywhere
, usSaveCreds = True
}
-- | Change the upload URL.
--
-- Default: "https://hackage.haskell.org/packages/"
--
-- Since 0.1.0.0
setUploadUrl :: String -> UploadSettings -> UploadSettings
setUploadUrl x us = us { usUploadUrl = x }
-- | How to get an HTTP connection manager.
--
-- Default: @newManager tlsManagerSettings@
--
-- Since 0.1.0.0
setGetManager :: IO Manager -> UploadSettings -> UploadSettings
setGetManager x us = us { usGetManager = x }
-- | How to get the Hackage credentials.
--
-- Default: @fromAnywhere@
--
-- Since 0.1.0.0
setCredsSource :: (Config -> HackageCredsSource) -> UploadSettings -> UploadSettings
setCredsSource x us = us { usCredsSource = x }
-- | Save new credentials to the config file.
--
-- Default: @True@
--
-- Since 0.1.0.0
setSaveCreds :: Bool -> UploadSettings -> UploadSettings
setSaveCreds x us = us { usSaveCreds = x }
handleIO :: (E.IOException -> IO a) -> IO a -> IO a
handleIO = E.handle
|
CRogers/stack
|
src/Stack/Upload.hs
|
bsd-3-clause
| 12,633 | 0 | 26 | 4,662 | 2,319 | 1,263 | 1,056 | 241 | 5 |
{-# LANGUAGE TypeFamilies, KindSignatures, TypeInType #-}
module BadUnboxedTuple where
import GHC.Exts
type family F :: TYPE UnboxedTupleRep
foo :: F -> ()
foo _ = ()
|
tjakway/ghcjvm
|
testsuite/tests/typecheck/should_fail/BadUnboxedTuple.hs
|
bsd-3-clause
| 171 | 0 | 6 | 30 | 42 | 24 | 18 | -1 | -1 |
{-# LANGUAGE DisambiguateRecordFields #-}
module Main where
import T15149B
import T15149C
main = do print (AnDouble{an=1}, AnInt{an=1})
|
sdiehl/ghc
|
testsuite/tests/rename/should_compile/T15149.hs
|
bsd-3-clause
| 136 | 0 | 10 | 17 | 44 | 27 | 17 | 5 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Backend.Internal.SDLWrap (textureDimensions, loadTexture, loadString, loadRect
,renderTexture
,update
,Texture, SDL, runSDL, clear) where
import Control.Applicative
import Control.Exception (IOException)
import Control.Lens
import Control.Monad.Catch hiding (catchIOError,finally)
import Control.Monad.Cont
import Control.Monad.Reader
import qualified Control.Monad.State as S
import qualified Data.Binary as B
import Data.IORef
import Data.List (genericIndex, genericLength)
import qualified Data.Map as M
import qualified Foreign as C
import qualified Foreign.C.Types as C
import qualified SDL.Raw.Enum as SDL
import qualified SDL.Raw.Video as SDL (queryTexture,renderCopyEx)
import qualified SDL.Raw.Types as SDL
import Philed.Control.Monad.Except
import Philed.Control.Monad.Record
import qualified Philed.Data.NNeg as N
import Philed.Data.Rect
import Philed.Data.Vector
import System.IO.Error
import qualified SDLM.Main as SDL
import qualified SDLM.Types as SDL
import qualified SDLM.Video as SDL
-------------------------------------------------------------------------------------
data TextureSpec = TextureSpec { _texture :: SDL.Texture
, _textureWidth :: Word
, _textureHeight :: Word
}
newtype Texture = Texture Word deriving (B.Binary, Eq, Show)
data Cache = Cache { _getTextures :: [TextureSpec]
, _knownTextures :: M.Map FilePath Texture
, _knownStrings ::
M.Map (String, Int, String, SDL.Colour) Texture
, _knownRects :: M.Map (Vec Word, SDL.Colour) Texture
}
makeLenses ''TextureSpec
makeLenses ''Cache
instance Monoid Cache where
mempty = Cache mempty mempty mempty mempty
mappend (Cache texs tm sm rm) (Cache texs' tm' sm' rm') =
Cache
(texs `mappend` texs')
(tm `mappend` tm')
(sm `mappend` sm')
(rm `mappend` rm')
data SDLState = SDLState { _renderer :: SDL.Renderer, _window :: SDL.Window }
makeLenses ''SDLState
newtype SDL e m a =
SDL { unSDL :: ReaderT (IORef (SDLState,Cache)) m a }
deriving (Applicative,Functor,Monad,MonadCatch,MonadMask,MonadThrow,
MonadError e,MonadIO,MonadTrans)
instance MonadIO m => S.MonadState SDLState (SDL e m) where
get = (^. _1) <$> (SDL ask >>= liftIO . readIORef)
put x = SDL ask >>= liftIO . (`modifyIORef` (_1 .~ x))
instance MonadIO m => MonadRecord Cache (SDL e m) where
get = (^. _2) <$> (SDL ask >>= liftIO . readIORef)
record x = SDL ask >>= liftIO . (`modifyIORef` (_2 %~ (`mappend` x)))
-------------------------------------------------------------------------------------
acquire :: MonadRecord s m => Getter s a -> m a
acquire l = (^. l) <$> get
textureSpec :: MonadIO m => Texture -> SDL e m TextureSpec
textureSpec (Texture index) = (`genericIndex` index) <$> acquire getTextures
-------------------------------------------------------------------------------------
runSDL :: (MonadIO m, MonadError e m, SDL.FromSDLError e) =>
Vec Word -> Word -> Word -> SDL e m a -> m ()
runSDL bottomLeft w h sdl = flip finally SDL.quit $ do
SDL.init
(window, renderer) <- SDL.createWindow bottomLeft (fromIntegral w) (fromIntegral h)
ioRef <- liftIO $ newIORef (SDLState renderer window, mempty)
flip finally (SDL.destroyWindow window) $ runReaderT (unSDL sdl) ioRef
update :: (MonadIO m, MonadError e m, SDL.FromSDLError e) => SDL e m ()
update = SDL.update =<< use renderer
clear :: (MonadIO m, MonadError e m, SDL.FromSDLError e) => SDL e m ()
clear = SDL.clear =<< use renderer
texDimensions :: (MonadIO m, MonadError e m, SDL.FromSDLError e)
=> SDL.Texture -> SDL e m (C.CInt, C.CInt)
texDimensions tex = sdlCont $ do
-- Pointers to be filled by query
(wPtr,hPtr) <- liftA2 (,) alloca alloca
(SDL.queryTexture tex
<$> alloca <*> alloca <*> pure wPtr <*> pure hPtr)
>>= SDL.safeSDL_
liftA2 (,) (peek wPtr) (peek hPtr)
loadTexture :: (MonadError e m, MonadIO m, SDL.FromSDLError e)
=> FilePath -> SDL e m Texture
loadTexture file = do
renderer <- use renderer
preloaded <- M.lookup file <$> acquire knownTextures
case preloaded of
Just tex -> return tex
Nothing -> do
tex <- SDL.loadTexture renderer file
index <- genericLength <$> acquire getTextures
(w,h) <- texDimensions tex
let texture = Texture index
record $ Cache
[TextureSpec tex (fromIntegral w) (fromIntegral h)]
(M.singleton file texture)
mempty
mempty
return texture
loadString
:: (MonadIO m, MonadError e m, SDL.FromSDLError e) =>
FilePath -> Int -> String -> SDL.Colour -> SDL e m Texture
loadString fontFile ptSize string colour = do
renderer <- use renderer
preloaded <- M.lookup (fontFile,ptSize,string,colour) <$> acquire knownStrings
case preloaded of
Just tex -> return tex
Nothing -> do
font <- SDL.safeSDL (SDL.loadFont fontFile ptSize)
tex <- SDL.stringTexture renderer font string colour
index <- genericLength <$> acquire getTextures
(w,h) <- texDimensions tex
let texture = Texture index
record $ Cache
[TextureSpec tex (fromIntegral w) (fromIntegral h)]
mempty
(M.singleton (fontFile,ptSize,string,colour) texture)
mempty
return texture
loadRect
:: (MonadIO m, MonadError e m, SDL.FromSDLError e) =>
Vec Word -> SDL.Colour -> SDL e m Texture
loadRect wh colour = do
renderer <- use renderer
window <- use window
preloaded <- M.lookup (wh,colour) <$> acquire knownRects
case preloaded of
Just tex -> return tex
Nothing -> do
tex <- SDL.rectTexture renderer wh colour
index <- genericLength <$> acquire getTextures
(w,h) <- texDimensions tex
let texture = Texture index
record $ Cache
[TextureSpec tex (fromIntegral w) (fromIntegral h)]
mempty
mempty
(M.singleton (wh,colour) texture)
return texture
textureDimensions :: MonadIO m => Texture -> SDL e m (Word, Word)
textureDimensions tex = do
texSpec <- textureSpec tex
return (texSpec ^. textureWidth, texSpec ^. textureHeight)
nFromIntegral :: Num a => N.NNeg Word -> a
nFromIntegral = fromIntegral . N.extract
renderTexture :: (MonadIO m, MonadError e m, SDL.FromSDLError e)
=> Texture -> Rect Word -> Rect Word -> Vec C.CInt -> Double -> Bool
-> SDL e m ()
renderTexture tex srcRect destRect (cx,cy) angle flip = do
texSpec <- textureSpec tex
renderer <- use renderer
sdlCont $ do
sdlSrcRect <- alloca
let srcW = fromIntegral . N.extract . width $ srcRect
let srcH = fromIntegral . N.extract . height $ srcRect
poke sdlSrcRect $ SDL.Rect
(fromIntegral . left $ srcRect)
(fromIntegral . bottom $ srcRect)
srcW
srcH
sdlDestRect <- alloca
let destW = fromIntegral . N.extract . width $ destRect
let destH = fromIntegral . N.extract . height $ destRect
poke sdlDestRect $ SDL.Rect
(fromIntegral . left $ destRect)
(fromIntegral . bottom $ destRect)
destW
destH
sdlPoint <- alloca
poke sdlPoint $ SDL.Point cx cy
SDL.safeSDL_ $ SDL.renderCopyEx
renderer
(texSpec ^. texture)
sdlSrcRect
sdlDestRect
(realToFrac angle)
sdlPoint
(if flip then SDL.SDL_FLIP_HORIZONTAL else SDL.SDL_FLIP_NONE)
-------------------------------------------------------------------------------------
newtype SDLCont r a =
SDLCont { unSDLCont :: ContT r IO a }
deriving (Functor, Applicative, Monad, MonadIO)
runSDLCont :: SDLCont r a -> (a -> IO r) -> IO r
runSDLCont = runContT . unSDLCont
peek :: (MonadIO m, C.Storable a) => C.Ptr a -> m a
peek = liftIO . C.peek
poke :: (MonadIO m, C.Storable a) => C.Ptr a -> a -> m ()
poke ptr = liftIO . C.poke ptr
malloc :: (MonadIO m, C.Storable a) => m (C.Ptr a)
malloc = liftIO C.malloc
alloca :: C.Storable a => SDLCont r (C.Ptr a)
alloca = SDLCont $ ContT C.alloca
instance MonadError IOException (SDLCont r) where
throwError e = liftIO (ioError e)
catchError (SDLCont c) handler =
SDLCont (ContT (\k -> catchIOError (runContT c k)
(\e -> runSDLCont (handler e) k )))
sdlCont :: (MonadError e m, MonadIO m, SDL.FromSDLError e)
=> SDLCont a a -> SDL e m a
sdlCont x = lift $ join $ liftIO $
catchIOError sdl
(\err -> let errMsg = ioeGetErrorString err
in return (throwError (SDL.fromSDLError errMsg)))
where sdl = return <$> runSDLCont x return
|
Chattered/guis
|
Backend/Internal/SDLWrap.hs
|
mit
| 9,160 | 0 | 17 | 2,335 | 3,054 | 1,582 | 1,472 | 212 | 2 |
module ProjectEuler.Problem017 (solve) where
import Data.Char
toWords :: Int -> String
toWords 00 = "zero"
toWords 01 = "one"
toWords 02 = "two"
toWords 03 = "three"
toWords 04 = "four"
toWords 05 = "five"
toWords 06 = "six"
toWords 07 = "seven"
toWords 08 = "eight"
toWords 09 = "nine"
toWords 10 = "ten"
toWords 11 = "eleven"
toWords 12 = "twelve"
toWords 13 = "thirteen"
toWords 14 = "fourteen"
toWords 15 = "fifteen"
toWords 16 = "sixteen"
toWords 17 = "seventeen"
toWords 18 = "eighteen"
toWords 19 = "nineteen"
toWords 20 = "twenty"
toWords 30 = "thirty"
toWords 40 = "forty"
toWords 50 = "fifty"
toWords 60 = "sixty"
toWords 70 = "seventy"
toWords 80 = "eighty"
toWords 90 = "ninety"
toWords n = if b == 0 then toWords a ++ f
else toWords c ++ e ++ toWords b
where
a = n `div` d
b = n `mod` d
c = n - b
d | n < 100 = 10
| n < 1000 = 100
| n < 10000 = 1000
| otherwise = undefined
e | n < 100 = " "
| n < 1000 = " and "
| n < 10000 = " "
| otherwise = undefined
f | n < 1000 = " hundred"
| n < 10000 = " thousand"
| otherwise = undefined
countLetters :: String -> Int
countLetters = length . filter isLetter
solve :: [Int] -> Int
solve = countLetters . concatMap toWords
|
hachibu/project-euler
|
src/ProjectEuler/Problem017.hs
|
mit
| 1,285 | 0 | 10 | 358 | 505 | 254 | 251 | 51 | 2 |
main = print getProblem30Value
getProblem30Value :: Integer
getProblem30Value = sum $ filter isEqualToSumOfFifthPowersOfDigits [10..999999]
isEqualToSumOfFifthPowersOfDigits :: Integer -> Bool
isEqualToSumOfFifthPowersOfDigits num = num == (sum $ map ((^5) . read . (:[])) $ show num)
|
jchitel/ProjectEuler.hs
|
Problems/Problem0030.hs
|
mit
| 287 | 0 | 13 | 37 | 92 | 49 | 43 | 5 | 1 |
module Jolly.Types.System
( TVar(..)
, Type(..)
, Scheme(..)
, typeInt
, typeBool
) where
newtype TVar =
TV String
deriving (Show, Eq, Ord)
data Type
= TVar TVar
| TCon String
| TArr Type
Type
deriving (Show, Eq, Ord)
infixr `TArr`
typeInt, typeBool :: Type
typeInt = TCon "Int"
typeBool = TCon "Bool"
data Scheme =
Forall [TVar]
Type
deriving (Show, Eq, Ord)
|
jchildren/jolly
|
src/Jolly/Types/System.hs
|
mit
| 412 | 0 | 7 | 115 | 152 | 91 | 61 | 23 | 1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_secret_handshake (
version,
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [1,0,0,3] []
bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/c19/Documents/projects/exercism/haskell/haskell/secret-handshake/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/bin"
libdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/secret-handshake/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/lib/x86_64-osx-ghc-8.0.2/secret-handshake-1.0.0.3-Bnb30w7QkPrF3tHymFPWTf"
dynlibdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/secret-handshake/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/lib/x86_64-osx-ghc-8.0.2"
datadir = "/Users/c19/Documents/projects/exercism/haskell/haskell/secret-handshake/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/share/x86_64-osx-ghc-8.0.2/secret-handshake-1.0.0.3"
libexecdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/secret-handshake/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/libexec"
sysconfdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/secret-handshake/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/etc"
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "secret_handshake_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "secret_handshake_libdir") (\_ -> return libdir)
getDynLibDir = catchIO (getEnv "secret_handshake_dynlibdir") (\_ -> return dynlibdir)
getDataDir = catchIO (getEnv "secret_handshake_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "secret_handshake_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "secret_handshake_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
|
c19/Exercism-Haskell
|
secret-handshake/.stack-work/dist/x86_64-osx/Cabal-1.24.2.0/build/autogen/Paths_secret_handshake.hs
|
mit
| 2,491 | 0 | 10 | 239 | 410 | 238 | 172 | 33 | 1 |
module Main (main) where
import qualified Haskeleton.TestBench
-- HASKELETON: import qualified New.ModuleBench
import Criterion.Main (bgroup, defaultMain)
main :: IO ()
main = defaultMain
[ bgroup "Haskeleton.Test" Haskeleton.TestBench.benchmarks
-- HASKELETON: , bgroup "New.Module" New.ModuleBench.benchmarks
]
|
Moredread/haskeleton-test
|
benchmark/Bench.hs
|
mit
| 328 | 0 | 8 | 49 | 59 | 35 | 24 | 6 | 1 |
-----------------------------------------------------------------------------
--
-- Module : PhyQ.Test.Common
-- Copyright :
-- License : MIT
--
-- Maintainer : -
-- Stability :
-- Portability :
--
-- |
--
{-# LANGUAGE GADTs, PolyKinds #-}
module PhyQ.Test.Common(
correct, mistake
, B(..)
, module Test.Hspec
) where
import Test.Hspec
-----------------------------------------------------------------------------
data B (b :: Bool) = B
correct :: (expr ~ True) => c expr -> Expectation
correct _ = return ()
mistake :: (expr ~ False) => c expr -> Expectation
mistake _ = return ()
|
fehu/PhysicalQuantities
|
test/PhyQ/Test/Common.hs
|
mit
| 614 | 0 | 7 | 116 | 133 | 81 | 52 | -1 | -1 |
-- Example for GA package
-- see http://hackage.haskell.org/package/GA
--
-- Evolve the string "Hello World!"
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Main where
import Data.Char (chr,ord)
import Data.List (foldl')
import System.Random (mkStdGen, random, randoms)
import System.IO (IOMode(..), hClose, hGetContents, openFile)
import GA (Entity(..), GAConfig(..),
evolveVerbose, randomSearch)
-- efficient sum
sum' :: (Num a) => [a] -> a
sum' = foldl' (+) 0
--
-- GA TYPE CLASS IMPLEMENTATION
--
type Sentence = String
type Target = String
type Letter = Char
-- data to score
-- entity
-- representing | pool of random
-- an entitiy score | entities monad
-- | | | | |
instance Entity Sentence Double Target [Letter] IO where
-- generate a random entity, i.e. a random string
-- assumption: max. 100 chars, only 'printable' ASCII (first 128)
genRandom pool seed = return $ take n $ map ((!!) pool) is
where
g = mkStdGen seed
n = (fst $ random g) `mod` 101
k = length pool
is = map (flip mod k) $ randoms g
-- crossover operator: mix (and trim to shortest entity)
crossover _ _ seed e1 e2 = return $ Just e
where
g = mkStdGen seed
cps = zipWith (\x y -> [x,y]) e1 e2
picks = map (flip mod 2) $ randoms g
e = zipWith (!!) cps picks
-- mutation operator: use next or previous letter randomly and add random characters (max. 9)
mutation pool p seed e = return $ Just $ (zipWith replace tweaks e)
++ addChars
where
g = mkStdGen seed
k = round (1 / p) :: Int
tweaks = randoms g :: [Int]
replace i x = if (i `mod` k) == 0
then if even i
then if x > (minBound :: Char) then pred x else succ x
else if x < (maxBound :: Char) then succ x else pred x
else x
is = map (flip mod $ length pool) $ randoms g
addChars = take (seed `mod` 10) $ map ((!!) pool) is
-- score: distance between current string and target
-- sum of 'distances' between letters, large penalty for additional/short letters
-- NOTE: lower is better
score fn e = do
h <- openFile fn ReadMode
x <- hGetContents h
length x `seq` hClose h
let e' = map ord e
x' = map ord x
d = sum' $ map abs $ zipWith (-) e' x'
l = abs $ (length x) - (length e)
return $ Just $ fromIntegral $ d + 100*l
-- whether or not a scored entity is perfect
isPerfect (_,s) = s == 0.0
main :: IO()
main = do
let cfg = GAConfig
100 -- population size
25 -- archive size (best entities to keep track of)
300 -- maximum number of generations
0.8 -- crossover rate (% of entities by crossover)
0.2 -- mutation rate (% of entities by mutation)
0.0 -- parameter for crossover (not used here)
0.2 -- parameter for mutation (% of replaced letters)
False -- whether or not to use checkpointing
False -- don't rescore archive in each generation
g = mkStdGen 0 -- random generator
-- pool of characters to pick from: printable ASCII characters
charsPool = map chr [32..126]
fileName = "goal.txt"
-- write string to file, pretend that we don't know what it is
-- goal is to let genetic algorithm evolve this string
writeFile fileName "Hello World!"
-- Do the evolution!
-- Note: if either of the last two arguments is unused, just use () as a value
es <- evolveVerbose g cfg charsPool fileName
let e = snd $ head es :: String
putStrLn $ "best entity (GA): " ++ (show e)
-- Compare with random search with large budget
-- 100k random entities, equivalent to 1000 generations of GA
es' <- randomSearch g 100000 charsPool fileName
let e' = snd $ head es' :: String
putStrLn $ "best entity (random search): " ++ (show e')
|
cirquit/Personal-Repository
|
Haskell/GeneticAlgorithms/ga-testing/app/Main.hs
|
mit
| 4,300 | 0 | 14 | 1,452 | 971 | 530 | 441 | 70 | 1 |
module DBus
(
-- * Connection management
DBusConnection
, ConnectionType(..)
, connectClient
, connectClientWithAuth
, makeServer
, connectBus
, MethodCallHandler
, SignalHandler
, checkAlive
, waitFor
, close
-- * Message handling
, objectRoot
, ignore
-- * Signals
, MatchRule(..)
, Signal(..)
, SignalDescription(..)
, SomeSignalDescription(..)
, matchAll
, matchSignal
, addMatch
, removeMatch
, addSignalHandler
, signalChan
, handleSignal
-- * Representable Types
, Representable(..)
, FlattenRepType
, makeRepresentable
, makeRepresentableTuple
-- * DBus specific types
-- ** DBus Types
-- $Types
, DBusSimpleType(..)
, DBusType(..)
, Signature(..)
, typeOf
-- ** DBus Values
, DBusValue(..)
, castDBV
, DBusStruct(..)
, SomeDBusValue(..)
, dbusValue
, fromVariant
-- ** Objects
, Object(..)
, Interface(..)
, ObjectPath
, objectPath
, objectPathToText
, stripObjectPrefix
, isPathPrefix
, isRoot
, isEmpty
-- * Methods
, Method(..)
, MethodWrapper(..)
, ArgumentDescription(..)
, repMethod
, callMethod
, callMethod'
, call
, callAsync
, fromResponse
, MsgError(..)
, MethodError(..)
, MethodHandlerT(..)
, MethodDescription(..)
, SomeMethodDescription(..)
-- * Properties
, Property (..)
, SomeProperty(..)
, PropertyEmitsChangedSignal(..)
, RemoteProperty(..)
, propertyChanged
, emitPropertyChanged
, getProperty
, setProperty
, handlePropertyChanged
, mkProperty
, mkTVarProperty
-- * Introspection
, addIntrospectable
-- * Message Bus
, requestName
, RequestNameFlag(..)
, RequestNameReply(..)
, releaseName
, ReleaseNameReply (..)
, listQueuedOwners
, listNames
, listActivatableNames
, nameHasOwner
, startServiceByName
, getNameOwner
, getConnectionUnixUser
, getConnectionProcessID
, getID
-- * Scaffolding
, module DBus.Scaffold
-- * Re-exports
, SingI (..)
) where
import qualified Data.ByteString as BS
import DBus.Auth
import DBus.Introspect
import DBus.MainLoop
import DBus.Message
import DBus.MessageBus
import DBus.Method
import DBus.Property
import DBus.Scaffold
import DBus.Signal
import DBus.TH
import DBus.Types
import Data.Default (def)
import Data.Singletons
-- | Ignore all incoming messages/signals
ignore :: Monad m => a -> b -> c -> m ()
ignore _ _ _ = return ()
-- | Connect to a message bus as a client, using the @EXTERNAL@ auth mechanism.
connectClient :: ConnectionType -> IO DBusConnection
connectClient bus = connectBus bus ignore ignore
-- | Connect to a message bus as a client with a custom auth mechanism.
connectClientWithAuth :: ConnectionType -> SASL BS.ByteString -> IO DBusConnection
connectClientWithAuth bus auth = connectBusWithAuth bus auth ignore ignore
-- $types
--
-- DBus has it's own type system, described here
-- <https://dbus.freedesktop.org/doc/dbus-specification.html#type-system>
--
-- Types are divided into basic types, represented in this library by
-- 'DBusSimpleType', and composite types, represented by 'DBusType'. Only simple
-- types can be the keys in a dictionary
|
Philonous/d-bus
|
src/DBus.hs
|
mit
| 3,446 | 0 | 10 | 909 | 613 | 402 | 211 | 111 | 1 |
{-# LANGUAGE MultiWayIf #-}
module Data.Bitsplit.Test.Types where
import Data.Bitsplit.Types
import Data.Natural
import Data.Ratio
import Data.List (genericLength)
import Control.Applicative ((<$>))
import Test.QuickCheck
addresses = ["1LizTeRZKA2MhdjjzCcFpvqfSRYSunrCsW",
"1HxoFaq36tAvAsXMzwcmRDoBK6CTZiek4C",
"1F34duy2eeMz5mSrvFepVzy7Y1rBsnAyWC",
"16g2TW2hbFoov3DThSRBdnETaS94bFvq5v",
"1FpqQnKQCgDkJFMC94JL8FpRyHTZ3uRVZ1",
"1f1miYFQWTzdLiCBxtHHnNiW7WAWPUccr",
"1vFzbs8hN4Y8EtgcKpfTUuSQVoq2MApQ6",
"1BfCR6RdQ7x3FLgZZfrW6dgpLuqnKqarGo",
"1LiWe7QnM4vgQZJV5cL5yPiebWXFgynu9a",
"13D5DVAyC2tH9P7ab9UonNCUXjbAxKVWMb",
"1PxJE5jxUp8BsTb819k6Qbqk5crWF6HMMK",
"1PYwPRCdYHtbHbpkDdRFToo1GKCgAXbGvL",
"1PqSXncpDgVZhYmKbLTC9ZZAqJYkE1SfJD",
"15vbwgCa9dFqbCfSCg1iMKFFqMpyKa482a",
"1BrzsWUf6L2BLaGs7YGsM6n2zdeRhWtjyU",
"1Ct9r9piNCbzvWtM4UFZhKFFriNYLt4r64",
"1HGZdSdtWSgPMFsBy7QuFamV2TPSawfbxA",
"1C4JhThVN6ZSHwbMmtTJ1oPFdv4JSLTc6d",
"15f5xWsQ8iXYEMu7fHZP95hzNYyHFF8yo1",
"12yyaqLdWdmMjFee47zQ68zqzX8ry9BfDm"]
unsafeUnpack :: Maybe a -> a
unsafeUnpack (Just value) = value
instance Arbitrary Natural where
arbitrary = fromInteger <$> (choose (0, 999999))
instance Arbitrary Address where
arbitrary = elements $ (unsafeUnpack . mkAddress) <$> addresses
newtype ArbPosRatio = ArbPosRatio (Ratio Natural)
instance Arbitrary ArbPosRatio where
arbitrary = do
nat1 <- arbitrary
nat2 <- arbitrary
let least = min nat1 nat2
most = max nat1 nat2
return $ ArbPosRatio (least % most)
newtype ArbOneVec = ArbOneVec [Ratio Natural]
accumulateRatios times ratios = do
(ArbPosRatio new) <- arbitrary
let newList = new : ratios
total = sum newList
if | total == 1 -> return $ ArbOneVec newList
| times >= 2 -> (return . ArbOneVec) $ (1 - (sum ratios)) : ratios
| total < 1 -> accumulateRatios (times + 1) newList
| otherwise -> accumulateRatios (times + 1) ratios
instance Arbitrary ArbOneVec where
arbitrary = accumulateRatios 0 []
shrink (ArbOneVec []) = []
shrink (ArbOneVec [_]) = []
shrink (ArbOneVec numbers) =
let least = foldl min 1 numbers
rest = filter (not . (== least)) numbers
remaining = genericLength rest
in if remaining == 0 then []
else [ArbOneVec (fmap (+ least / remaining) rest)]
newtype ArbPreSplit = ArbPreSplit [(Address, Ratio Natural)]
instance Arbitrary ArbPreSplit where
arbitrary = do
addr <- arbitrary
(ArbPosRatio ratio) <- arbitrary
(ArbOneVec one) <- arbitrary
let tuple = return (addr, ratio)
randomList = (listOf tuple)
addressList = (unsafeUnpack . mkAddress) <$> addresses
goodList = return $ zip addressList one
ArbPreSplit <$> oneof [randomList, goodList]
isRight :: Either a b -> Bool
isRight (Left _) = False
isRight (Right _) = True
instance Arbitrary Split where
arbitrary = let maybeSplit = make <$> arbitrary
resolveSplit = suchThat maybeSplit isRight
in unpack <$> resolveSplit
where make (ArbPreSplit ps) = mkSplit ps
unpack (Right unsafe) = unsafe
|
micmarsh/bitsplit-hs
|
src/Data/Bitsplit/Test/Types.hs
|
mit
| 3,768 | 0 | 14 | 1,248 | 862 | 454 | 408 | 81 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Eventful.Store.PostgresqlSpec (spec) where
import Control.Monad.Reader (ask)
import Data.ByteString (ByteString)
import qualified Data.ByteString.UTF8 as UTF8
import Data.Maybe (maybe)
import Data.Monoid ((<>))
import Data.Text (Text, intercalate)
import Database.Persist.Postgresql
import System.Environment (lookupEnv)
import Test.Hspec
import Eventful.Store.Postgresql
import Eventful.TestHelpers
spec :: Spec
spec = do
describe "Postgres event store" $ do
eventStoreSpec postgresStoreRunner
globalStreamEventStoreSpec postgresStoreGlobalRunner
makeStore
:: (MonadIO m)
=> m ( VersionedEventStoreWriter (SqlPersistT m) CounterEvent
, VersionedEventStoreReader (SqlPersistT m) CounterEvent
, ConnectionPool)
makeStore = do
let
makeConnString host port user pass db = (
"host=" <> host
<> " port=" <> port
<> " user=" <> user
<> " dbname=" <> db
<> " password=" <> pass)
writer = serializedEventStoreWriter jsonStringSerializer $
postgresqlEventStoreWriter defaultSqlEventStoreConfig
reader = serializedVersionedEventStoreReader jsonStringSerializer $
sqlEventStoreReader defaultSqlEventStoreConfig
connString <- makeConnString
<$> getEnvDef "POSTGRES_HOST" "localhost"
<*> getEnvDef "POSTGRES_PORT" "5432"
<*> getEnvDef "POSTGRES_USER" "postgres"
<*> getEnvDef "POSTGRES_PASSWORD" "password"
<*> getEnvDef "POSTGRES_DBNAME" "eventful_test"
pool <- liftIO $ runNoLoggingT (createPostgresqlPool connString 1)
liftIO $ flip runSqlPool pool $ do
void $ runMigrationSilent migrateSqlEvent
truncateTables
return (writer, reader, pool)
getEnvDef :: (MonadIO m) => String -> ByteString -> m ByteString
getEnvDef name def = liftIO $ maybe def UTF8.fromString <$> lookupEnv name
getTables :: MonadIO m => SqlPersistT m [Text]
getTables = do
tables <-
rawSql
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE';"
[]
return $ map unSingle tables
truncateTables :: MonadIO m => SqlPersistT m ()
truncateTables = do
tables <- getTables
sqlBackend <- ask
let
escapedTables = map (connEscapeName sqlBackend . DBName) tables
query = "TRUNCATE TABLE " <> intercalate ", " escapedTables <> " RESTART IDENTITY CASCADE"
rawExecute query []
postgresStoreRunner :: EventStoreRunner (SqlPersistT IO)
postgresStoreRunner = EventStoreRunner $ \action -> do
(writer, reader, pool) <- makeStore
runSqlPool (action writer reader) pool
postgresStoreGlobalRunner :: GlobalStreamEventStoreRunner (SqlPersistT IO)
postgresStoreGlobalRunner = GlobalStreamEventStoreRunner $ \action -> do
(writer, _, pool) <- makeStore
let
globalReader = serializedGlobalEventStoreReader jsonStringSerializer (sqlGlobalEventStoreReader defaultSqlEventStoreConfig)
runSqlPool (action writer globalReader) pool
|
jdreaver/eventful
|
eventful-postgresql/tests/Eventful/Store/PostgresqlSpec.hs
|
mit
| 2,966 | 0 | 19 | 527 | 736 | 372 | 364 | 73 | 1 |
-- |
-- Module : Control.Auto
-- Description : Main entry point to the /auto/ library.
-- Copyright : (c) Justin Le 2015
-- License : MIT
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : portable
--
-- This module serves as the main entry point for the library; these are
-- all basically re-exports. The re-exports are chosen so you can start
-- doing "normal things" off the bat, including all of the types used in
-- this library.
--
-- Conspicuously missing are the most of the tools for working with
-- 'Interval', 'Blip' streams, switches, and the "collection" autos; those
-- are all pretty heavy, and if you do end up working with any of those
-- tools, simply importing the appropriate module should give you all you
-- need.
--
-- See the <https://github.com/mstksg/auto/blob/master/tutorial/tutorial.md tutorial>
-- if you need help getting started!
--
module Control.Auto (
-- * Types
-- ** Auto
Auto
, Auto'
-- ** Misc
, Blip
, Interval
, Interval'
-- * Working with 'Auto'
-- ** Running
, stepAuto
, stepAuto'
, evalAuto
, evalAuto'
, streamAuto
, streamAuto'
, stepAutoN
, stepAutoN'
-- ** Serializing
-- | See the header of the "serializing" section of "Control.Auto.Core"
-- for more detail on how these work.
, encodeAuto
, decodeAuto
, readAuto
, writeAuto
, unserialize
-- ** Strictness
, forcer
, seqer
-- ** Internal monad
, hoistA
, generalizeA
-- * Auto constructors
, arrM
, arrD
-- ** from Accumulators
-- *** Result-first
, accum
, accum_
, accumM
, accumM_
-- *** Initial accumulator-first
, accumD
, accumD_
, accumMD
, accumMD_
-- ** from State transformers
, mkState
, mkStateM
, mkState_
, mkStateM_
-- ** Generators
-- *** Effects
, effect
-- , exec
-- *** Iterators
, iterator
, iterator_
, iteratorM
, iteratorM_
-- * Common 'Auto's and combinators
-- ** Processes
, sumFrom
, sumFrom_
, sumFromD
, sumFromD_
, productFrom
, productFrom_
, mappender
, mappender_
, mappendFrom
, lastVal
, lastVal_
, delay
, delay_
, count
-- ** Switches
, (-->)
, (-?>)
-- ** Blips
, emitJusts
, emitOn
, fromBlips
, fromBlipsWith
, holdWith
, holdWith_
, perBlip
, never
, immediately
-- ** Intervals
, onFor
, during
, off
, toOn
, fromInterval
-- * Running
, interactAuto
, interactRS
, streamAutoEffects
, toEffectStream
-- * Re-exports
, module Control.Applicative
, module Control.Arrow
, module Control.Category
, module Data.Functor.Identity
, module Data.Semigroup
) where
import Control.Applicative
import Control.Arrow hiding (loop)
import Control.Auto.Blip
import Control.Auto.Core
import Control.Auto.Effects
import Control.Auto.Generate
import Control.Auto.Interval
import Control.Auto.Process
import Control.Auto.Run
import Control.Auto.Serialize
import Control.Auto.Switch
import Control.Auto.Time
import Control.Category
import Data.Functor.Identity
import Data.Semigroup
|
mstksg/auto
|
src/Control/Auto.hs
|
mit
| 3,065 | 0 | 5 | 688 | 409 | 289 | 120 | 96 | 0 |
{-# LANGUAGE TupleSections #-}
module PureScript.Ide.Reexports where
import Data.List (union)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import PureScript.Ide.Types
getReexports :: Module -> [ExternDecl]
getReexports (mn, decls)= concatMap getExport decls
where getExport d
| (Export mn') <- d
, mn /= mn' = replaceExportWithAliases decls mn'
| otherwise = []
dependencyToExport :: ExternDecl -> ExternDecl
dependencyToExport (Dependency m _ _) = Export m
dependencyToExport decl = decl
replaceExportWithAliases :: [ExternDecl] -> ModuleIdent -> [ExternDecl]
replaceExportWithAliases decls ident =
case filter isMatch decls of
[] -> [Export ident]
aliases -> map dependencyToExport aliases
where isMatch d
| Dependency _ _ (Just alias) <- d
, alias == ident = True
| otherwise = False
replaceReexport :: ExternDecl -> Module -> Module -> Module
replaceReexport e@(Export _) (m, decls) (_, newDecls) =
(m, filter (/= e) decls `union` newDecls)
replaceReexport _ _ _ = error "Should only get Exports here."
emptyModule :: Module
emptyModule = ("Empty", [])
isExport :: ExternDecl -> Bool
isExport (Export _) = True
isExport _ = False
removeExportDecls :: Module -> Module
removeExportDecls = fmap (filter (not . isExport))
replaceReexports :: Module -> Map ModuleIdent [ExternDecl] -> Module
replaceReexports m db = result
where reexports = getReexports m
result = foldl go (removeExportDecls m) reexports
go :: Module -> ExternDecl -> Module
go m' re@(Export name) = replaceReexport re m' (getModule name)
go _ _ = error "partiality! woohoo"
getModule :: ModuleIdent -> Module
getModule name = clean res
where res = fromMaybe emptyModule $ (name , ) <$> Map.lookup name db
-- we have to do this because keeping self exports in will result in
-- infinite loops
clean (mn, decls) = (mn,) (filter (/= Export mn) decls)
resolveReexports :: Map ModuleIdent [ExternDecl] -> Module -> Module
resolveReexports modules m = do
let replaced = replaceReexports m modules
if null . getReexports $ replaced
then replaced
else resolveReexports modules replaced
|
kRITZCREEK/psc-ide
|
src/PureScript/Ide/Reexports.hs
|
mit
| 2,359 | 0 | 13 | 600 | 717 | 376 | 341 | 53 | 2 |
import Data.List
import Data.Tuple
data Context = Context Int
tagItems :: ([a], Context) -> ([(a, Int)], Context)
tagItems (ys, ctx) = swap $ mapAccumL f ctx ys
where f (Context x) y = (Context (x + 1), (y, x))
main :: IO ()
main = do
let ctx = Context 1000
(items, ctx') = tagItems (["one", "two", "three"], ctx)
putStrLn $ show items
-- Yields: [("one",1000),("two",1001),("three",1002)]
|
rcook/seahug-slides
|
snippets/folds-part-2.hs
|
mit
| 406 | 0 | 12 | 82 | 186 | 103 | 83 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Lib where
import Web.Scotty
import Control.Monad.IO.Class
import Data.Aeson (FromJSON, ToJSON, object, encode)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToField
import GHC.Generics
import VizTree
server :: Connection -> ScottyM()
server conn = do
post "/SumAPI/addNumber" $ do
item <- jsonData :: ActionM SumNum
newItem <- liftIO (sumNumber conn item updateNumberQuery)
json newItem
get "/SumAPI/showNumber" $ do
items <- liftIO (query_ conn selectNumberQuery :: IO [SumNum])
json items
get "/SumAPI/resetNumber" $ do
item <- liftIO (sumNumber conn (SumNum (Just 0)) resetNumberQuery)
json item
get "/VizTree/:l1/:l2/:r1/:r2" $ do
l1 <- param "l1"
l2 <- param "l2"
r1 <- param "r1"
r2 <- param "r2"
_ <- liftIO (viz [[(read l1 :: Int)..(read l2 :: Int)],[(read r1 :: Int)..(read r2 :: Int)::Int]])
file "tree.dot"
updateNumberQuery = "UPDATE sumNumber SET number = number + ? WHERE id = 1 returning number"
resetNumberQuery = "UPDATE sumNumber SET number = ? WHERE id = 1 returning number"
selectNumberQuery = "SELECT number FROM sumNumber"
sumNumber :: Connection -> SumNum -> Query -> IO SumNum
sumNumber conn item qString = do
[Only number] <- query conn qString item
return item { number = number }
data SumNum = SumNum { number :: Maybe Int } deriving (Show, Generic, Eq)
instance FromRow SumNum where
fromRow = SumNum <$> field
instance ToRow SumNum where
toRow c = [toField $ number c]
instance ToJSON SumNum
instance FromJSON SumNum
|
craynafinal/cs557_functional_languages
|
project/haskell-rest-api/src/Lib.hs
|
mit
| 1,700 | 0 | 17 | 314 | 532 | 269 | 263 | 45 | 1 |
module Expr where
data Value = IntVal Integer
| BoolVal Bool
deriving (Eq, Show)
data Unary = UNeg | UNot deriving (Eq, Show)
evalUnary :: Unary -> Value -> Value
evalUnary UNeg (IntVal n) = IntVal (-n)
evalUnary UNot (BoolVal b) = BoolVal (not b)
evalUnary _ _ = undefined
data Binop = BAdd | BSub | BMul | BDiv
| BAnd | BOr
| BLt | BLte | BEq
deriving (Eq, Show)
evalBinary :: Binop -> Value -> Value -> Value
evalBinary BAdd (IntVal n1) (IntVal n2) = IntVal (n1 + n2)
evalBinary BSub (IntVal n1) (IntVal n2) = IntVal (n1 - n2)
evalBinary BMul (IntVal n1) (IntVal n2) = IntVal (n1 * n2)
evalBinary BDiv (IntVal n1) (IntVal n2) = IntVal (n1 `div` n2)
evalBinary BAnd (BoolVal b1) (BoolVal b2) = BoolVal (b1 && b2)
evalBinary BOr (BoolVal b1) (BoolVal b2) = BoolVal (b1 || b2)
data Expr v = Val Value
| Var v
| Unary Unary (Expr v)
| Binop Binop (Expr v) (Expr v)
deriving (Eq, Show)
eval :: Expr v -> (v -> Value) -> Value
eval (Val val) _ = val
eval (Var x) env = env x
eval (Unary op e) env = evalUnary op (eval e env)
eval (Binop op e1 e2) env = evalBinary op (eval e1 env) (eval e2 env)
|
ghulette/logic
|
src/Expr.hs
|
mit
| 1,248 | 0 | 8 | 377 | 579 | 302 | 277 | 30 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Javelin.Lib.Structures where
import qualified Data.Array.IArray as Array
import qualified Data.Int as Int
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import qualified Data.Word as Word
import qualified Data.Function as Function
import qualified Data.Maybe as Maybe
import Control.Lens ((%~), (&), (^.), (^?), _1, _2, _Right, ix, makeLenses)
import Data.Either.Utils (maybeToEither)
import Javelin.Lib.ByteCode.Data
import Javelin.Lib.ByteCode.DescSign
data Runtime =
Runtime
{ _classPathLayout :: ClassPathLayout
, _loadedClasses :: Map.Map ClassId (Either VMError LoadedClass)
, _classResolving :: Map.Map ClassId ClassRes
, _classPrepared :: Map.Map ClassId Bool --todo change Bool to error as in ClassRes
, _heap :: (Int, Array.Array Int JObject)
, _threads :: [Thread]
}
deriving (Show, Eq)
data ClassId =
ClassId
{ getInitCL :: ClassLoader
, getName :: ClassName
}
deriving (Show, Eq, Ord)
data ClassRes
= ClassResOk
{ _resolvedFields :: Map.Map ClassPartReference ClassPartRes
, _resolvedMethods :: Map.Map ClassPartReference ClassPartRes
}
| ClassResFail
{ resolvingFailure :: VMError
}
deriving (Show, Eq)
data ClassPartReference =
ClassPartReference
{ _part :: PartReference
, _ownerName :: String
}
deriving (Show, Eq, Ord)
data PartReference =
PartReference
{ _name :: String
, _descriptor :: String
}
deriving (Show, Eq, Ord)
data ClassPartRes
= ClassPartResOk
| ClassPartResFail VMError
deriving (Show, Eq)
data Class =
Class
{ symTable :: SymTable
, className :: String
, superName :: Maybe String
, classInterfaces :: [String]
, sourceFile :: String
, classVisibility :: ClassAccess
, _fieldsList :: [Field]
, methodsList :: [Method]
}
deriving (Show, Eq)
data ClassAccess =
ClassAccess
{ isClassPublic :: Bool
, isClassFinal :: Bool
, isClassTreatSuperSpecially :: Bool
, isClassInterface :: Bool
, isClassAbstract :: Bool
, isClassSynthetic :: Bool
, isClassAnnotation :: Bool
, isClassEnum :: Bool
}
deriving (Show, Eq)
data Method =
Method
{ methodName :: String
, methodDescriptor :: String
, methodAccess :: MethodAccess
, stackSize :: Word.Word16
, localsSize :: Word.Word16
, instructions :: [Instruction]
, exceptions :: [Exception]
, methodParameters :: [MethodParameter2]
}
deriving (Show, Eq)
-- methodCode :: [String], --todo
-- methodExceptions :: [String], --todo
data MethodParameter2 =
MethodParameter2
{ parameterName :: Maybe String
, isParameterFinal :: Bool
, isParameterSynthetic :: Bool
, isParameterMandated :: Bool
}
deriving (Show, Eq)
data MethodAccess =
MethodAccess
{ isMethodPublic :: Bool
, isMethodPrivate :: Bool
, isMethodProtected :: Bool
, isMethodStatic :: Bool
, isMethodFinal :: Bool
, isMethodSynchronized :: Bool
, isMethodBridge :: Bool
, isMethodVarargs :: Bool
, isMethodNative :: Bool
, isMethodAbstract :: Bool
, isMethodStrict :: Bool
, isMethodSynthetic :: Bool
}
deriving (Show, Eq)
data Field =
Field
{ fieldName :: String
, fieldDescriptor :: String
, fieldType :: FieldType
, constantValue :: Maybe ConstantValue
, fieldAccess :: FieldAccess
, staticValue :: Maybe JValue
}
deriving (Show, Eq)
data ConstantValue
= ConstantLong Word.Word64
| ConstantFloat Float
| ConstantDouble Double
| ConstantInteger Word.Word32
| ConstantString String
deriving (Show, Eq)
data FieldAccess =
FieldAccess
{ isFieldPublic :: Bool
, isFieldPrivate :: Bool
, isFieldProtected :: Bool
, isFieldStatic :: Bool
, isFieldFinal :: Bool
, isFieldVolatile :: Bool
, isFieldTransient :: Bool
, isFieldSynthetic, isFieldEum :: Bool
}
deriving (Show, Eq)
data LoadedClass
= LoadedClass
{ _defining :: ClassLoader
, _initiating :: ClassLoader
, _runtimePackage :: (String, ClassLoader)
, _classInfo :: Class
}
| LoadedArrayClass
{ _defining :: ClassLoader
, _initiating :: ClassLoader
, _runtimePackage :: (String, ClassLoader)
, _dimensions :: Int
}
deriving (Show, Eq)
data ClassPathLayout =
ClassPathLayout
{ _classes :: Map.Map ClassName ClassSource
, _classPath :: [String]
}
deriving (Eq)
instance Show ClassPathLayout where
show cpl@(ClassPathLayout classes classPath) =
"== Classpath ==\n" ++ show classPath ++ "\n\n" ++ "== Loaded classes ==\n" ++
(classes |> Map.toList |> map (\(c, p) -> c ++ "\n" ++ show p) |>
List.intersperse "\n\n" |>
List.concat)
where (|>) = (Function.&)
type ClassName = String
data ClassSource
= JarFile
{ getPath :: FilePath
}
| ClassFile
{ getPath :: FilePath
}
deriving (Show, Eq)
-- ClassLoading Info
data ClassLoader
= BootstrapClassLoader
| UserDefinedClassLoader
{ instanceReference :: Integer
}
deriving (Show, Eq, Ord)
data InternalLoadingError
= ClassLoaderNotFound
| OnlyClassObjectHasNoSuperClass String
| ClassObjectHasNoSuperClasses
| CouldNotFindAccessFlags String
| InterfaceMustHaveObjectAsSuperClass
| SymTableHasNoProperEntryAtIndex
| CustomError String
| SpecifyMeError
deriving (Show, Eq)
data LinkageError
= LinkageError
| ClassFormatError
| UnsupportedClassVersionError
| NoClassDefFoundClassNotFoundError
{ notFound :: VMError
}
| NoClassDefFoundError String
| IncompatibleClassChangeError
| AbstractMethodError
| IllegalAccessError
| InstantiationError
| NoSuchFieldError
| NoSuchMethodError
| ClassCircularityError
| ExceptionInInitializerError
deriving (Show, Eq)
data VMError
= InternalError
{ rt :: Runtime
, reason :: InternalLoadingError
}
| Linkage
{ rt :: Runtime
, le :: LinkageError
}
| ClassNotFoundException
{ notFoundClass :: String
}
deriving (Show, Eq)
data Thread =
Thread
{ frames :: FrameStack
, runtime :: Runtime
}
deriving (Show, Eq)
type ProgramCounter = Int
type FrameStack = [Frame]
data Frame =
Frame
{ pc :: ProgramCounter
, currentClass :: ClassId
, currentMethod :: Int
, locals :: Locals
, operands :: [StackElement]
}
deriving (Show, Eq)
newtype StackElement =
StackElement
{ stackElement :: Word.Word64
}
deriving (Show, Eq)
newtype Locals =
Locals
{ vars :: Array.Array Int Word.Word32
}
deriving (Show, Eq)
type Ref = Int
type JObject = Map.Map String JValue
data JValue
= JInt
{ getInt :: Int.Int32
}
| JLong
{ getLong :: Int.Int64
}
| JBoolean
{ getBoolean :: Int.Int32
}
| JShort
{ getShort :: Int.Int16
}
| JByte
{ getByte :: Int.Int8
}
| JChar
{ getChar :: Word.Word8
}
| JDouble
{ getDouble :: Double
}
| JFloat
{ getFloat :: Float
}
| JReference
{ getReference :: Integer
}
deriving (Show, Eq)
type SymTable = [SymbolicReference]
data SymbolicReference
= ClassOrInterface
{ classOrInterfaceName :: String
}
| FieldReference
{ field :: ClassPartReference
}
| ClassMethodReference
{ classMethod :: ClassPartReference
}
| InterfaceMethodReference
{ interfaceMethod :: ClassPartReference
}
| MethodHandleReference
| MethodTypeReference
{ typeReference :: String
}
| CallSiteSpecifierReference
| StringLiteral
{ string :: String
}
| DoubleLiteral
{ double :: Double
}
| FloatLiteral
{ float :: Float
}
| IntegerLiteral
{ integer :: Int.Int32
}
| LongLiteral
{ long :: Int.Int64
}
| EmptyLiteral
deriving (Show, Eq)
makeLenses ''Runtime
makeLenses ''ClassRes
makeLenses ''ClassPartReference
makeLenses ''LoadedClass
makeLenses ''Class
makeLenses ''ClassPathLayout
-- Querying class info
getSuperInterfaces :: Runtime -> ClassId -> Either VMError [String]
getSuperInterfaces rt classId = classInterfaces <$> getClass rt classId
isInterface :: Runtime -> ClassId -> Either VMError Bool
isInterface rt classId =
isClassInterface <$> classVisibility <$> getClass rt classId
getSuperClass :: Runtime -> ClassId -> Either VMError (Maybe String)
getSuperClass rt classId = superName <$> getClass rt classId
getMethodByIndex :: Runtime -> ClassId -> Int -> Either VMError Method
getMethodByIndex rt classId index = do
classMethods <- methodsList <$> getClass rt classId
return $ classMethods !! index
getMethodBySignature ::
Runtime -> ClassId -> PartReference -> Either VMError (Int, Method)
getMethodBySignature rt classId partRef = do
classMethods <- methodsList <$> getClass rt classId
case List.findIndex (\m -> methodName m == _name partRef) classMethods of
Just idx -> Right (fromIntegral idx, classMethods !! idx)
Nothing ->
Left $ InternalError rt $ CustomError $ "Cant find method" ++ show partRef
getClass :: Runtime -> ClassId -> Either VMError Class
getClass rt classId = _classInfo <$> getLoadedClass rt classId
getLoadedClass :: Runtime -> ClassId -> Either VMError LoadedClass
getLoadedClass rt classId =
maybe (Left $ InternalError rt SpecifyMeError) id (findLoadedClass rt classId)
findLoadedClass :: Runtime -> ClassId -> Maybe (Either VMError LoadedClass)
findLoadedClass rt classId = rt ^? loadedClasses . ix classId
getDefiningClassLoader :: Runtime -> ClassId -> Either VMError ClassLoader
getDefiningClassLoader rt classId = _defining <$> getLoadedClass rt classId
getStringLiteral :: SymTable -> Word.Word16 -> Either VMError String
getStringLiteral t i =
maybeToEither undefined $ do
let elem = t !! fromIntegral i
case elem of
StringLiteral x -> return x
_ -> Nothing
-- Updating class info
newRuntime :: ClassPathLayout -> Runtime
newRuntime layout =
let emptyThreads = []
loadedClassesInfo = Map.fromList []
in Runtime
layout
loadedClassesInfo
(Map.fromList [])
(Map.fromList [])
(0, Array.array (0, 0) [(0, Map.fromList [("", JReference 0)])])
emptyThreads
addLoadedClass :: ClassId -> LoadedClass -> Runtime -> Runtime
addLoadedClass classId loadedClass rt =
rt & loadedClasses %~ Map.insert classId (Right loadedClass)
markClassPrepared :: ClassId -> Runtime -> Runtime
markClassPrepared classId rt = rt & classPrepared %~ Map.insert classId True
isClassPrepared :: ClassId -> Runtime -> Bool
isClassPrepared classId rt = Maybe.fromMaybe False (_classPrepared rt Map.!? classId)
updateClassFields :: ClassId -> Runtime -> ([Field] -> [Field]) -> Runtime
updateClassFields classId rt update =
rt & loadedClasses . ix classId . _Right . classInfo . fieldsList %~ update
addResolvedClassField :: ClassId -> ClassPartReference -> Runtime -> Runtime
addResolvedClassField classId classPartRef rt =
rt & classResolving . ix classId . resolvedFields %~
Map.insert classPartRef ClassPartResOk
addResolvedClassMethod :: ClassId -> ClassPartReference -> Runtime -> Runtime
addResolvedClassMethod classId classPartRef rt =
rt & classResolving . ix classId . resolvedMethods %~
Map.insert classPartRef ClassPartResOk
classDefinesField :: ClassId -> ClassPartReference -> Runtime -> Bool
classDefinesField classId partRef rt =
let fieldResStatus =
rt ^? classResolving . ix classId . resolvedFields . ix partRef
in Maybe.isJust fieldResStatus
-- Heap contents
newThread :: Frame -> ClassPathLayout -> Thread
newThread frame = Thread [frame] . newRuntime
malloc :: Runtime -> (Runtime, Ref)
malloc rt =
let old = rt ^. heap . _1
in (rt & heap . _1 %~ (+ 1), old)
getField :: Runtime -> Ref -> String -> Either VMError JValue
getField rt ref name =
let h = rt ^. heap . _2
in if ref < (snd . Array.bounds) h
then maybeToEither (InternalError rt SpecifyMeError) $
Map.lookup name ((Array.!) h ref)
else Left $ InternalError rt SpecifyMeError
writeField :: Runtime -> Ref -> (String, JValue) -> Either VMError Runtime
writeField rt@Runtime {_heap = (s, h)} ref (name, value) = do
let jobject = (Array.!) h ref
newObject = Map.insert name value jobject
return $ rt & heap . _2 %~ ( (flip (Array.//)) [(ref, newObject)])
-- LLI ClassPath
nullReference = JReference (-1)
baseDefaultValues :: Map.Map BaseType JValue
baseDefaultValues =
Map.fromList
[ (ByteT, JByte 0)
, (CharT, JChar 0)
, (DoubleT, JDouble 0)
, (FloatT, JFloat 0)
, (IntT, JInt 0)
, (LongT, JLong 0)
, (ShortT, JShort 0)
, (BooleanT, JBoolean 0)
]
|
antonlogvinenko/javelin
|
src/Javelin/Lib/Structures.hs
|
mit
| 12,838 | 0 | 15 | 2,978 | 3,516 | 1,979 | 1,537 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable #-}
module Robots.Config
( Config -- abstract
, c_hull, cluster_of
, showing_hull, show_hull
, breit
, make, make_with_hull, geschichte
, move, remove, addZug
, look, robots, inhalt
, positions, goals
, valid
, bounds, area
)
where
-- $Id$
import Robots.Data
import Robots.Exact
import Autolib.FiniteMap
import Autolib.Set
import Autolib.ToDoc
import Autolib.Hash
import Autolib.Reader
import Autolib.Size
import Autolib.Set
import Autolib.FiniteMap
import Autolib.Xml
import Autolib.Reporter
import Data.List (partition)
import Control.Monad ( guard )
import Data.Maybe ( isJust, maybeToList, fromMaybe )
import Data.Typeable
import Data.Int
data Config = Config { c_hash :: Int32
, inhalt :: FiniteMap String Robot
, breit :: Integer
, geschichte :: [ Zug ]
, c_hull :: Set Position
, c_clusters :: FiniteMap Position Int
, show_hull :: Bool
}
deriving ( Typeable )
cluster_of k p = lookupFM ( c_clusters k ) p
make :: [ Robot ] -> Config
make rs =
let i = listToFM $ do
r <- rs
return ( name r, r )
in hulled $ Config
{ c_hash = hash i
, inhalt = i
, breit = maximum $ do
r <- rs
let (x,y) = position r
map abs [x,y]
, geschichte = []
, show_hull = False
}
make_with_hull :: [ Robot ] -> Config
make_with_hull rs = showing_hull $ make rs
-- | recompute hull (from scratch)
hulled k =
let ps = mkSet $ map position $ robots k
fm = listToFM $ do
( i, cl ) <- zip [ 0 .. ] $ clusters ps
p <- setToList cl
return ( p, i )
in k { c_hull = exact_hull_points ps
, c_clusters = fm
}
showing_hull k = k { show_hull = True }
bounds k =
let ps = do r <- robots k ; return $ position r
xs = map fst ps ; ys = map snd ps
in ( ( minimum xs, minimum ys )
, ( maximum xs, maximum ys )
)
area k =
let ((a,b),(c,d)) = bounds k
in (c-a +1) * (d-b+1)
-- | fort damit (into outer space)
remove :: String -> Config -> Config
remove n k =
let i = delFromFM (inhalt k) n
in hulled $ k { inhalt = i
, c_hash = hash i
}
-- | auf neue position
move :: (String, Position) -> Config -> Config
move (n, p) k =
let i = inhalt k
j = addToFM i n
$ let r = fromMaybe ( error "Robots.Move.move" ) ( lookupFM i n )
in r { position = p }
in hulled $ k { inhalt = j
, c_hash = hash j
}
addZug :: Zug -> Config -> Config
addZug z k = k { geschichte = z : geschichte k }
instance ToDoc Config where
toDoc k = text "make" <+> toDoc ( robots k )
instance Reader Config where
atomic_readerPrec p = do
guard $ p < 9
my_reserved "make"
arg <- reader
return $ make arg
instance Container Config [ Robot ] where
label _ = "Config"
pack = robots
unpack = make
instance Hash Config where hash = c_hash
-- | die mit ziel werden echt verglichen,
-- | von den anderen nur die positionen
essence :: Config -> ( Int32, Set Robot, Set Position )
essence k =
let rs = robots k
(zs, ns) = partition ( isJust . ziel ) rs
in (hash k, mkSet zs, mkSet $ map position ns)
instance Ord Config where
compare k l = compare (essence k) (essence l)
instance Eq Config where
(==) k l = (==) (essence k) (essence l)
instance Size Config where
size = fromIntegral . area
-----------------------------------------------------------------
look :: Config -> String -> Maybe Robot
look c n = lookupFM (inhalt c) n
robots :: Config -> [ Robot ]
robots c = eltsFM (inhalt c)
positions :: Config -> [ Position ]
positions = map position . robots
goals :: Config -> [ Position ]
goals k = do r <- robots k ; maybeToList ( ziel r )
valid :: Config -> Reporter ()
valid k = do
let mappe = addListToFM_C (++) emptyFM $ do
r <- robots k
return ( position r, [ name r ] )
let mehrfach = do
( p, rs ) <- fmToList mappe
guard $ length rs > 1
return ( p , rs )
inform $ text "Stehen alle Roboter auf verschiedenen Positionen?"
if ( null mehrfach )
then inform $ text "Ja."
else reject $ text "Nein, diese nicht:" <+> toDoc mehrfach
|
Erdwolf/autotool-bonn
|
src/Robots/Config.hs
|
gpl-2.0
| 4,255 | 36 | 26 | 1,194 | 1,597 | 836 | 761 | 131 | 2 |
module Rewriting.SRS.Steps where
import Rewriting.SRS.Step
import Rewriting.SRS.Raw
import Autolib.TES.Rule
import Autolib.Symbol
import Autolib.Reporter
import Autolib.ToDoc
import Autolib.Multilingual
import Data.List ( inits, tails )
import Data.Maybe
-- | list all possible rewrite steps
-- starting from given term
steps :: ( Symbol c )
=> SRS c
-> [c]
-> [ Step c ]
steps rs w = do
( p, rest ) <- zip [0..] $ tails w
( k, r ) <- zip [ 0 .. ] $ rules rs
let ( pre, post ) = splitAt ( length $ lhs r ) rest
guard $ lhs r == pre
return $ Step
{ rule_number = k
, position = p
}
-- | execute one rewrite step
exec :: ( Symbol c )
=> SRS c
-> [ c ]
-> Step c
-> Reporter [ c ]
exec srs w step = do
inform $ vcat
[ multitext [(DE, "Anwenden des Ersetzungsschrittes")
,(UK, "apply step")
]
, nest 4 $ toDoc step
, multitext [(DE, "auf das Wort")
,(UK, "to word")
]
, nest 4 $ toDoc w
]
let k = rule_number step
inform $ multitext [(DE, "die Regel Nummer")
,(UK, "the rule number")
]
<+> toDoc k
rule <- if k < length ( rules srs )
then do
let rule = rules srs !! k
inform $ multitext [(DE, "ist"), (UK, "is")]
<+> toDoc rule
return rule
else reject $ multitext [(DE, "existiert nicht.")
,(UK, "does not exist.")
]
let p = position step
( pre, midpost ) = splitAt p w
inform $ multitext [(DE, "das Teilwort an Position")
,(UK, "the subword at position")
]
<+> toDoc p
if p > length w
then reject $ multitext [(DE, "existiert nicht")
,(UK, "does not exist")
]
else inform $ multitext [(DE, "ist"), (UK, "is")]
<+> toDoc midpost
let ( mid, post ) = splitAt ( length $ lhs rule ) midpost
assert ( mid == lhs rule )
$ multitext [(DE, "linke Regelseite ist Präfix des Teilwortes an Position?")
,(UK, "lhs is prefix of subword at position?")
]
inform $ multitext [(DE, "Suffix ist"), (UK, "suffix is")]
<+> toDoc post
let res = pre ++ rhs rule ++ post
inform $ multitext [(DE, "resultierendes Wort ist")
,(UK, "the resulting word is")
]
$$ ( nest 4 $ toDoc res )
return res
|
marcellussiegburg/autotool
|
collection/src/Rewriting/SRS/Steps.hs
|
gpl-2.0
| 2,450 | 22 | 16 | 871 | 857 | 454 | 403 | 68 | 3 |
module Sdk where
import Data.List
import Control.Monad (msum, forM_)
testCase :: [[Int]]
testCase = [[1, 2, 3, 4, 5, 6, 7, 8, 9],
[4, 5, 6, 7, 8, 9, 1, 2, 3],
[7, 8, 9, 1, 2, 3, 4, 5, 6],
[2, 3, 4, 5, 6, 7, 8, 9, 1],
[5, 6, 7, 8, 9, 1, 2, 3, 4],
[8, 9, 1, 2, 3, 4, 5, 6, 7],
[3, 4, 5, 6, 7, 8, 9, 1, 2],
[6, 7, 8, 9, 1, 2, 3, 4, 5],
[9, 1, 2, 3, 4, 5, 6, 7, 8]]
testCase2 :: [[Int]]
testCase2 = [[1, 2, 0, 4, 5, 6, 7, 8, 9],
[4, 5, 0, 7, 8, 9, 1, 0, 3],
[7, 8, 9, 1, 2, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7, 8, 0, 1],
[5, 6, 7, 0, 9, 0, 2, 3, 4],
[0, 9, 1, 0, 3, 4, 5, 0, 0],
[0, 4, 0, 0, 7, 8, 9, 1, 2],
[6, 7, 8, 0, 1, 0, 3, 0, 5],
[0, 1, 0, 0, 4, 5, 6, 7, 8]]
testCase3 :: [[Int]]
testCase3 = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
testCase4 :: [[Int]]
testCase4 = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]]
row :: [[Int]] -> (Int, Int) -> [Int]
row lst (i, _) = lst !! i
col :: [[Int]] -> (Int, Int) -> [Int]
col lst (_, j) = map (!! j) lst
grp :: [[Int]] -> (Int, Int) -> [Int]
grp lst (i, j) = concatMap (take 3 . drop jj) rows
where rows = take 3 $ drop ii lst
ii = 3 * div i 3
jj = 3 * div j 3
rcg :: [[Int]] -> (Int, Int) -> [Int]
rcg lst pos = union g $ union r c
where r = row lst pos
c = col lst pos
g = grp lst pos
possible :: [[Int]] -> (Int, Int) -> [Int]
possible lst pos = [1..9] \\ rcg lst pos
value :: [[Int]] -> (Int, Int) -> Int
value lst (i, j) = (lst !! i) !! j
permuteZip :: [a] -> [b] -> [(a, b)]
permuteZip l1 l2 = concatMap (\v1 -> map (\v2 -> (v1, v2)) l2) l1
emptyPositions :: [[Int]] -> [(Int, Int)]
emptyPositions lst = filter ((== 0) . value lst) allPos
where allPos = permuteZip [0..8] [0..8]
setValue :: [[Int]] -> (Int, Int) -> Int -> [[Int]]
setValue lst (i, j) newVal = pre ++ [newRow] ++ post
where pre = take i lst
post = drop (i + 1) lst
oldRow = lst !! i
newRow = take j oldRow ++ [newVal] ++ drop (j + 1) oldRow
firstSomething :: [Maybe a] -> Maybe a
firstSomething = msum
solve :: [[Int]] -> Maybe [[Int]]
solve lst =
case emptyPos of
[] -> Just lst -- no empty place, meaning the puzzle is solved
(firstEmptyPos:_) -> firstSomething $
map (solve . setValue lst firstEmptyPos) possibleNewValues
where possibleNewValues = possible lst firstEmptyPos
-- if possibleNewValues is empty, then solve returns Nothing
where emptyPos = emptyPositions lst
printNicely :: Maybe [[Int]] -> IO ()
printNicely Nothing = putStrLn "No solution."
printNicely (Just lst) = forM_ lst print
|
cetinkaya/sdkhs
|
Sdk.hs
|
gpl-3.0
| 3,474 | 0 | 12 | 1,305 | 2,021 | 1,240 | 781 | 85 | 2 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback is free software: you can redistribute it and/or modify it under |
| the terms of the GNU General Public License as published by the Free |
| Software Foundation, either version 3 of the License, or (at your option) |
| any later version. |
| |
| Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.Scenario.Areas
(areaEntrance, areaLinks, areaLocation, areaTerrain, enterPartyIntoArea)
where
import qualified Data.Map as Map
import qualified Data.Set as Set
import Fallback.Control.Error (IOEO, onlyIO)
import Fallback.Data.Clock (initClock)
import qualified Fallback.Data.Grid as Grid (empty)
import Fallback.Data.Point (IPoint, Point(Point), Position, half, pSub)
import qualified Fallback.Data.SparseMap as SM (make)
import Fallback.Scenario.Triggers
import Fallback.State.Area (AreaCommonState(..), TownEffect)
import Fallback.State.Camera (makeCameraWithCenter)
import Fallback.State.Creature (CreatureAnim(NoAnim), CreaturePose(..))
import Fallback.State.Doodad (emptyDoodads)
import Fallback.State.Minimap (newMinimapFromTerrain)
import Fallback.State.Party (Party(partyCurrentArea), partyExploredMap)
import Fallback.State.Resources (Resources)
import Fallback.State.Simple (MarkKey, deltaFaceDir)
import Fallback.State.Tags (AreaTag(..))
import Fallback.State.Terrain
import Fallback.State.Town
import Fallback.State.Trigger (Trigger, makeUnfiredTriggers)
-------------------------------------------------------------------------------
areaEntrance :: AreaTag -> AreaTag -> MarkKey
areaEntrance = getAreaEntrance scenarioTriggers
areaLinks :: AreaTag -> Set.Set AreaTag
areaLinks = getAreaLinks scenarioTriggers
areaLocation :: AreaTag -> IPoint
areaLocation MountainPath = Point 314 293
areaLocation Corenglen = Point 389 348
areaLocation FrozenPass = Point 110 130
areaLocation Holmgare = Point 175 170
areaLocation SewerCaves = Point 175 130
areaLocation PerilousRoad = Point 255 255
areaLocation StoneBridge = Point 303 328
areaLocation Tragorda = Point 412 335
areaLocation WhistlingWoods = Point 386 261
areaLocation IcyConfluence = Point 340 215
areaLocation Marata = Point 332 164
areaLocation IronMine = Point 351 100
areaLocation NorthernTundra = Point 406 162
areaLocation Duskwood = Point 473 261
areaLocation Icehold = Point 532 184
areaLocation _ = Point 100 100 -- FIXME
areaTerrain :: Party -> AreaTag -> String
areaTerrain = getAreaTerrain scenarioTriggers
areaTriggers :: AreaTag -> [Trigger TownState TownEffect]
areaTriggers = getAreaTriggers scenarioTriggers
-------------------------------------------------------------------------------
enterPartyIntoArea :: Resources -> Party -> AreaTag -> Either Position MarkKey
-> IOEO TownState
enterPartyIntoArea resources origParty tag destination = do
let party = origParty { partyCurrentArea = tag }
tmap <- loadTerrainMap resources (areaTerrain party tag)
position <- do
case destination of
Left pos -> return pos
Right mark -> do
case Set.toList $ tmapLookupMark mark tmap of
[pos] -> return pos
_ -> fail ("No such entrance mark: " ++ show mark)
let terrain = Terrain { terrainMap = tmap, terrainOverrides = Map.empty }
let mapCenter = fmap half $ uncurry Point $ terrainSize terrain
minimap <- onlyIO $ newMinimapFromTerrain terrain $
partyExploredMap terrain party
onlyIO $ updateTownVisibility $ TownState
{ tsActiveCharacter = minBound,
tsCommon = AreaCommonState
{ acsCamera = makeCameraWithCenter (positionCenter position),
acsClock = initClock,
acsDevices = Grid.empty,
acsDoodads = emptyDoodads,
acsFields = Map.empty,
acsMessage = Nothing,
acsMinimap = minimap,
acsMonsters = Grid.empty,
acsParty = party,
acsRemains = SM.make [],
acsResources = resources,
acsTerrain = terrain,
acsVisible = Set.empty },
tsPartyPose = CreaturePose
{ cpAlpha = 255, cpAnim = NoAnim,
cpFaceDir = deltaFaceDir (mapCenter `pSub` position) },
tsPartyPosition = position,
tsPhase = WalkingPhase,
tsTriggers = makeUnfiredTriggers (areaTriggers tag) }
-------------------------------------------------------------------------------
|
mdsteele/fallback
|
src/Fallback/Scenario/Areas.hs
|
gpl-3.0
| 5,437 | 0 | 21 | 1,386 | 1,026 | 571 | 455 | 85 | 3 |
-- Copyright : (c) Nikolay Orlyuk 2012
-- License : GNU GPLv3 (see COPYING)
module FRP.Yampa.FieldTrip.Adapter
( Anim, Anim2, Anim3
, anim2, anim3, liftAction
) where
import Control.Arrow
import Data.Monoid
import Graphics.FieldTrip hiding (frustum)
import Graphics.UI.GLUT
import FRP.Yampa (SF)
import FRP.Yampa.Event
import FRP.Yampa.GLUT.Adapter
-- | Interactive animation
type Anim a = SF (Event UI) a
-- | Interactive 2D animation
type Anim2 = Anim Geometry2
-- | Interactive 3D animation
type Anim3 = Anim Geometry3
-- | Present a 2D animation.
anim2 :: Anim2 -> IO ()
anim2 anim = adaptSimple "Yampa + FieldTrip 2D" leaveMainLoop sf
where
sf = mconcat [(redisplay &&& anim) >>> arr (uncurry tag) >>> liftAction render
, reshaped >>> liftAction reshape2
]
render = glwrap . renderWith2 gc
gc = defaultGC { gcErr = 0.005 }
-- | Present a 3D animation.
anim3 :: Anim3 -> IO ()
anim3 anim = adaptSimple "Yampa + FieldTrip 3D" leaveMainLoop sf
where
sf = mconcat [(redisplay &&& anim) >>> arr (uncurry tag) >>> liftAction render
, reshaped >>> liftAction reshape3
]
render = glwrap . renderWith3 gc
gc = defaultGC { gcErr = 0.005 }
-- | Wrap an OpenGL rendering action, to clear the frame-buffer before
-- swap buffers afterward.
glwrap :: IO () -> IO ()
glwrap f = do
clear [ ColorBuffer, DepthBuffer ]
f
swapBuffers
-- | Attach IO function to Event
liftAction :: (a -> IO ()) -> SF (Event a) (Event Action)
liftAction f = arr (fmap (actionIO . f))
-- | Handles reshape event for 2D scene
reshape2 :: Size -> IO ()
reshape2 (Size w 0) = reshape3 (Size w 1) -- prevent divide by zero
reshape2 s@(Size w h) = do
let b = fromIntegral (w `min` h)
w' = fromIntegral w / b
h' = fromIntegral h / b
viewport $= (Position 0 0, s)
matrixMode $= Projection
loadIdentity
ortho (-w') w' (-h') h' (-1) 1
matrixMode $= Modelview 0
-- loadIdentity
-- | Handles reshape event for 3D scene
reshape3 :: Size -> IO ()
reshape3 (Size w 0) = reshape3 (Size w 1) -- prevent divide by zero
reshape3 s@(Size w h) = do
{-
let aspect = realToFrac w / realToFrac h
viewport $= (Position 0 0, s)
matrixMode $= Projection
loadIdentity
perspective 75 aspect 0.001 100
matrixMode $= Modelview 0
loadIdentity
-}
let b = fromIntegral (w `min` h) * 2
w' = fromIntegral w / b
h' = fromIntegral h / b
viewport $= (Position 0 0, s)
matrixMode $= Projection
loadIdentity
frustum (-w') w' (-h') h' 2 100
matrixMode $= Modelview 0
loadIdentity
translate (Vector3 0 0 (-4 :: GLfloat))
|
ony/yampa-fieldtrip
|
FRP/Yampa/FieldTrip/Adapter.hs
|
gpl-3.0
| 2,779 | 0 | 13 | 770 | 819 | 429 | 390 | 56 | 1 |
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction #-}
module Main where
import Control.Monad
import Control.Monad.Identity
import Control.Monad.State
import Data.Char
import Data.List ((\\))
import Text.Megaparsec
import Text.Megaparsec.Expr
import Text.Megaparsec.Perm
import Text.Megaparsec.String
{-
Let us look at parsing a few simple formal languages.
Our goal is to first recognize them and then,
if possible, extract useful information out of them.
Some of them are specified formally in eBNf while
others are just given an informal description.
Those in eBNf share the following common productions.
space = " " | "\t" | "\n" | "\v" | "\f" | "\r" ;
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
uppercase = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J"
| "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T"
| "U" | "V" | "W" | "X" | "Y" | "Z" ;
We shall be working with Megaparsec, a descendant of Parsec.
It is a convenient parser combinator library built on top of
the basic applicative, monadic and alternative type classes.
A simple example of parsing natural numbers follows.
-}
-- natural :: ParsecT String Identity _
-- natural :: Parsec String _
-- natural :: Parser _
natural =
read <$> some digitChar
<?> "natural number"
{-
Our first case study is the regular language of Canadian postal codes.
postalCode = forwardSortationArea , [ space ]
, localDeliveryUnit ;
forwardSortationArea = postalDistrict , region , section ;
localDeliveryUnit = digit , trailingLetter , digit ;
postalDistrict = initialLetter ;
region = rural | urban ;
section = trailingLetter ;
rural = "0" ;
urban = digit - rural ;
trailingLetter = uppercase - ( "D" | "F" | "I" | "O" | "Q" | "U" ) ;
initialLetter = trailingLetter - "W" | "Z" ;
We would like to convert them into Haskell data structures.
type PostalCode = ((Char, Int, Char), (Int, Char, Int))
-}
type PostalCode = ((Char, Int, Char), (Int, Char, Int))
postalCode =
(,) <$> forwardSortationArea <* optional spaceChar <*> localDeliveryUnit
<?> "postal code"
forwardSortationArea =
(,,) <$> postalDistrict <*> region <*> section
<?> "forward sortation area"
localDeliveryUnit =
(,,) <$> digit <*> trailingLetter <*> digit
<?> "local delivery unit"
postalDistrict = initialLetter <?> "postal district letter"
region = rural <|> urban <?> "region number"
section = trailingLetter <?> "section letter"
digit = digitToInt <$> digitChar
rural = digitToInt <$> char '0'
urban = digitToInt <$> oneOf ['1' .. '9']
trailingLetter = satisfy (`elem` ['A' .. 'Z'] \\ "DFIOQU")
initialLetter = notFollowedBy (oneOf "WZ") *> trailingLetter
testPostalCode :: String
testPostalCode = "P0N1E5"
{-
Since we are dealing with parser combinators,
we can also parametrize parsers in terms of other parsers.
Let us do just that by implementing the following context-free language of
keyed recursive listings and extracting the items appropriately.
listing p = entry p | group p ;
group p = "[" , listing p , "]" ;
entry p = identifier , ":" , p ;
identifier = digit , { digit } ;
-}
data Listing a = Entry Int a | Group [Listing a]
deriving (Read, Show)
listing p = entry p <|> group p <?> "group or entry"
group p =
Group <$> (char '[' *> listing p `sepBy1` char ',' <* char ']')
<?> "group"
entry p =
Entry <$> natural <* char ':' <*> p
<?> "entry"
testListing :: String
testListing = "[[1:P0N1E5],2:E4T1N6,[3:S7R0N6,4:T0X1N5]]"
{-
Consider a small variation of the listing grammar that
may also contain references to previously identified items.
Such a change makes the language context-sensitive.
-}
data ListingT a = EntryT Int a | RefT Int | GroupT [ListingT a]
deriving (Read, Show)
listingT p = label "group or entry" $
entryT p <|> groupT p
groupT p = label "group" $
do _ <- char '['
xs <- listingT p `sepBy1` char ','
_ <- char ']'
return $ GroupT xs
entryT p = label "entry" $
do i <- natural
_ <- char ':'
is <- get
if i `elem` is then
return $ RefT i else
do x <- p
put $ i : is
return $ EntryT i x
testListingT :: String
testListingT = "[[1:P0N1E5],2:E4T1N6,[3:S7R0N6,1:,4:T0X1N5]]"
{-
We now have the tools and knowledge to
parse all decidable languages that admit a left-recursive parser.
However our journey does not end here.
Practical languages are usually regular or context-free.
Even those categories have two popular subcategories that
deserve special attention.
Flags like options given as arguments to programs or
file permission lists form a permutation language.
xw
-}
permissions = makePermParser flags <?> "permission flags"
flags =
(,,) <$?> (False, True <$ char 'r')
<|?> (False, True <$ char 'w')
<|?> (False, True <$ char 'x')
testPermissions :: String
testPermissions = "xw"
{-
Hierarchies like trees or
simple algebraic expressions form a nested word language.
-1+2*3-4+5*(-6)+(-7)
-}
expression = makeExprParser term operators <?> "expression"
term = between (char '(') (char ')') expression <|> natural <?> "term"
operators =
[[unary '-' negate, unary '+' id],
[binary '^' (^)],
[binary '*' (*)],
[binary '+' (+), binary '-' (-)]]
unary x f = Prefix $ f <$ char x
binary x f = InfixL $ f <$ char x
testExpression :: String
testExpression = "-1+2*3-(4+5*(-6))+(-7)"
{-
It might seem that we can parse all but the most pathological of languages.
Unfortunately some of them are rather tricky to work with.
Try the context-free language of palindromes for example.
palindrome = "A" | ... | "A" , { palindrome } , "A" | ... ;
-}
main :: IO ()
main =
do print $ runParser postalCode "" testPostalCode
print $ runParser (listing postalCode) "" testListing
print $ runParserT (listingT postalCode) "" testListingT `evalState` []
print $ runParser permissions "" testPermissions
print $ runParser expression "" testExpression
|
Tuplanolla/ties341-parsing
|
Parsenator.hs
|
gpl-3.0
| 6,075 | 0 | 12 | 1,333 | 1,044 | 555 | 489 | 90 | 2 |
-- | Auxiliary operations related to numbers.
module Data.Extra.Num where
-- | Ensure that a number is positive. Negates it if
-- negative.
--
-- Same as abs, except that it does not change the number
-- if it is already positive.
--
-- TODO: any difference in speed?
ensurePos :: (Eq a, Num a) => a -> a
ensurePos e = if signum e == (-1) then negate e else e
-- | Ensure that a number is negative. Negates it if
-- positive.
--
-- Same as @(negate . abs)@, except that it does not change the number
-- if it is already negative.
--
-- TODO: any difference in speed?
ensureNeg :: (Eq a, Num a) => a -> a
ensureNeg e = if signum e == 1 then negate e else e
-- | Class to capture margins of error for different number formats.
class Similar a where
-- | Margin of error. Any number smaller will be considered negligible.
sigma :: a -- margin of error
-- | For the purposes of this game, differences below 0.01 are considered
-- negligible.
instance Similar Float where
sigma = 0.01
-- | For the purposes of this game, differences below 0.01 are considered
-- negligible.
instance Similar Double where
sigma = 0.01
-- | Similarity relation. Two numbers are similar if their distance is
-- smaller than the margin of error for the type.
(=~) :: (Num a, Ord a, Similar a) => a -> a -> Bool
x =~ y = abs (x - y) < sigma
|
keera-studios/pang-a-lambda
|
src/Data/Extra/Num.hs
|
gpl-3.0
| 1,351 | 0 | 8 | 298 | 237 | 137 | 100 | 13 | 2 |
module Main where
import Scheme
import Repl
import System.Environment
import Control.Monad.Except
main :: IO ()
main = do
args <- getArgs
case length args of
0 -> Repl.runRepl
1 -> Repl.evalAndPrint $ args !! 0
otherwise -> putStrLn "Program takes 0 or 1 argument"
|
jdcannon/hascheme
|
app/Main.hs
|
gpl-3.0
| 313 | 0 | 12 | 92 | 86 | 45 | 41 | 12 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.GamesConfiguration.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.GamesConfiguration.Types.Product where
import Network.Google.GamesConfiguration.Types.Sum
import Network.Google.Prelude
-- | This is a JSON template for an image configuration resource.
--
-- /See:/ 'imageConfiguration' smart constructor.
data ImageConfiguration = ImageConfiguration'
{ _icResourceId :: !(Maybe Text)
, _icKind :: !Text
, _icURL :: !(Maybe Text)
, _icImageType :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ImageConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'icResourceId'
--
-- * 'icKind'
--
-- * 'icURL'
--
-- * 'icImageType'
imageConfiguration
:: ImageConfiguration
imageConfiguration =
ImageConfiguration'
{ _icResourceId = Nothing
, _icKind = "gamesConfiguration#imageConfiguration"
, _icURL = Nothing
, _icImageType = Nothing
}
-- | The resource ID of resource which the image belongs to.
icResourceId :: Lens' ImageConfiguration (Maybe Text)
icResourceId
= lens _icResourceId (\ s a -> s{_icResourceId = a})
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string gamesConfiguration#imageConfiguration.
icKind :: Lens' ImageConfiguration Text
icKind = lens _icKind (\ s a -> s{_icKind = a})
-- | The url for this image.
icURL :: Lens' ImageConfiguration (Maybe Text)
icURL = lens _icURL (\ s a -> s{_icURL = a})
-- | The image type for the image.
icImageType :: Lens' ImageConfiguration (Maybe Text)
icImageType
= lens _icImageType (\ s a -> s{_icImageType = a})
instance FromJSON ImageConfiguration where
parseJSON
= withObject "ImageConfiguration"
(\ o ->
ImageConfiguration' <$>
(o .:? "resourceId") <*>
(o .:? "kind" .!=
"gamesConfiguration#imageConfiguration")
<*> (o .:? "url")
<*> (o .:? "imageType"))
instance ToJSON ImageConfiguration where
toJSON ImageConfiguration'{..}
= object
(catMaybes
[("resourceId" .=) <$> _icResourceId,
Just ("kind" .= _icKind), ("url" .=) <$> _icURL,
("imageType" .=) <$> _icImageType])
-- | This is a JSON template for a ListConfigurations response.
--
-- /See:/ 'leaderboardConfigurationListResponse' smart constructor.
data LeaderboardConfigurationListResponse = LeaderboardConfigurationListResponse'
{ _lclrNextPageToken :: !(Maybe Text)
, _lclrKind :: !Text
, _lclrItems :: !(Maybe [LeaderboardConfiguration])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LeaderboardConfigurationListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lclrNextPageToken'
--
-- * 'lclrKind'
--
-- * 'lclrItems'
leaderboardConfigurationListResponse
:: LeaderboardConfigurationListResponse
leaderboardConfigurationListResponse =
LeaderboardConfigurationListResponse'
{ _lclrNextPageToken = Nothing
, _lclrKind = "gamesConfiguration#leaderboardConfigurationListResponse"
, _lclrItems = Nothing
}
-- | The pagination token for the next page of results.
lclrNextPageToken :: Lens' LeaderboardConfigurationListResponse (Maybe Text)
lclrNextPageToken
= lens _lclrNextPageToken
(\ s a -> s{_lclrNextPageToken = a})
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string games#leaderboardConfigurationListResponse.
lclrKind :: Lens' LeaderboardConfigurationListResponse Text
lclrKind = lens _lclrKind (\ s a -> s{_lclrKind = a})
-- | The leaderboard configurations.
lclrItems :: Lens' LeaderboardConfigurationListResponse [LeaderboardConfiguration]
lclrItems
= lens _lclrItems (\ s a -> s{_lclrItems = a}) .
_Default
. _Coerce
instance FromJSON
LeaderboardConfigurationListResponse where
parseJSON
= withObject "LeaderboardConfigurationListResponse"
(\ o ->
LeaderboardConfigurationListResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "kind" .!=
"gamesConfiguration#leaderboardConfigurationListResponse")
<*> (o .:? "items" .!= mempty))
instance ToJSON LeaderboardConfigurationListResponse
where
toJSON LeaderboardConfigurationListResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lclrNextPageToken,
Just ("kind" .= _lclrKind),
("items" .=) <$> _lclrItems])
-- | This is a JSON template for a number affix resource.
--
-- /See:/ 'gamesNumberAffixConfiguration' smart constructor.
data GamesNumberAffixConfiguration = GamesNumberAffixConfiguration'
{ _gnacFew :: !(Maybe LocalizedStringBundle)
, _gnacOther :: !(Maybe LocalizedStringBundle)
, _gnacTwo :: !(Maybe LocalizedStringBundle)
, _gnacOne :: !(Maybe LocalizedStringBundle)
, _gnacZero :: !(Maybe LocalizedStringBundle)
, _gnacMany :: !(Maybe LocalizedStringBundle)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'GamesNumberAffixConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gnacFew'
--
-- * 'gnacOther'
--
-- * 'gnacTwo'
--
-- * 'gnacOne'
--
-- * 'gnacZero'
--
-- * 'gnacMany'
gamesNumberAffixConfiguration
:: GamesNumberAffixConfiguration
gamesNumberAffixConfiguration =
GamesNumberAffixConfiguration'
{ _gnacFew = Nothing
, _gnacOther = Nothing
, _gnacTwo = Nothing
, _gnacOne = Nothing
, _gnacZero = Nothing
, _gnacMany = Nothing
}
-- | When the language requires special treatment of \"small\" numbers (as
-- with 2, 3, and 4 in Czech; or numbers ending 2, 3, or 4 but not 12, 13,
-- or 14 in Polish).
gnacFew :: Lens' GamesNumberAffixConfiguration (Maybe LocalizedStringBundle)
gnacFew = lens _gnacFew (\ s a -> s{_gnacFew = a})
-- | When the language does not require special treatment of the given
-- quantity (as with all numbers in Chinese, or 42 in English).
gnacOther :: Lens' GamesNumberAffixConfiguration (Maybe LocalizedStringBundle)
gnacOther
= lens _gnacOther (\ s a -> s{_gnacOther = a})
-- | When the language requires special treatment of numbers like two (as
-- with 2 in Welsh, or 102 in Slovenian).
gnacTwo :: Lens' GamesNumberAffixConfiguration (Maybe LocalizedStringBundle)
gnacTwo = lens _gnacTwo (\ s a -> s{_gnacTwo = a})
-- | When the language requires special treatment of numbers like one (as
-- with the number 1 in English and most other languages; in Russian, any
-- number ending in 1 but not ending in 11 is in this class).
gnacOne :: Lens' GamesNumberAffixConfiguration (Maybe LocalizedStringBundle)
gnacOne = lens _gnacOne (\ s a -> s{_gnacOne = a})
-- | When the language requires special treatment of the number 0 (as in
-- Arabic).
gnacZero :: Lens' GamesNumberAffixConfiguration (Maybe LocalizedStringBundle)
gnacZero = lens _gnacZero (\ s a -> s{_gnacZero = a})
-- | When the language requires special treatment of \"large\" numbers (as
-- with numbers ending 11-99 in Maltese).
gnacMany :: Lens' GamesNumberAffixConfiguration (Maybe LocalizedStringBundle)
gnacMany = lens _gnacMany (\ s a -> s{_gnacMany = a})
instance FromJSON GamesNumberAffixConfiguration where
parseJSON
= withObject "GamesNumberAffixConfiguration"
(\ o ->
GamesNumberAffixConfiguration' <$>
(o .:? "few") <*> (o .:? "other") <*> (o .:? "two")
<*> (o .:? "one")
<*> (o .:? "zero")
<*> (o .:? "many"))
instance ToJSON GamesNumberAffixConfiguration where
toJSON GamesNumberAffixConfiguration'{..}
= object
(catMaybes
[("few" .=) <$> _gnacFew,
("other" .=) <$> _gnacOther, ("two" .=) <$> _gnacTwo,
("one" .=) <$> _gnacOne, ("zero" .=) <$> _gnacZero,
("many" .=) <$> _gnacMany])
-- | This is a JSON template for a ListConfigurations response.
--
-- /See:/ 'achievementConfigurationListResponse' smart constructor.
data AchievementConfigurationListResponse = AchievementConfigurationListResponse'
{ _aclrNextPageToken :: !(Maybe Text)
, _aclrKind :: !Text
, _aclrItems :: !(Maybe [AchievementConfiguration])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AchievementConfigurationListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aclrNextPageToken'
--
-- * 'aclrKind'
--
-- * 'aclrItems'
achievementConfigurationListResponse
:: AchievementConfigurationListResponse
achievementConfigurationListResponse =
AchievementConfigurationListResponse'
{ _aclrNextPageToken = Nothing
, _aclrKind = "gamesConfiguration#achievementConfigurationListResponse"
, _aclrItems = Nothing
}
-- | The pagination token for the next page of results.
aclrNextPageToken :: Lens' AchievementConfigurationListResponse (Maybe Text)
aclrNextPageToken
= lens _aclrNextPageToken
(\ s a -> s{_aclrNextPageToken = a})
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string games#achievementConfigurationListResponse.
aclrKind :: Lens' AchievementConfigurationListResponse Text
aclrKind = lens _aclrKind (\ s a -> s{_aclrKind = a})
-- | The achievement configurations.
aclrItems :: Lens' AchievementConfigurationListResponse [AchievementConfiguration]
aclrItems
= lens _aclrItems (\ s a -> s{_aclrItems = a}) .
_Default
. _Coerce
instance FromJSON
AchievementConfigurationListResponse where
parseJSON
= withObject "AchievementConfigurationListResponse"
(\ o ->
AchievementConfigurationListResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "kind" .!=
"gamesConfiguration#achievementConfigurationListResponse")
<*> (o .:? "items" .!= mempty))
instance ToJSON AchievementConfigurationListResponse
where
toJSON AchievementConfigurationListResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _aclrNextPageToken,
Just ("kind" .= _aclrKind),
("items" .=) <$> _aclrItems])
-- | This is a JSON template for an leaderboard configuration resource.
--
-- /See:/ 'leaderboardConfiguration' smart constructor.
data LeaderboardConfiguration = LeaderboardConfiguration'
{ _lcScoreMax :: !(Maybe (Textual Int64))
, _lcKind :: !Text
, _lcPublished :: !(Maybe LeaderboardConfigurationDetail)
, _lcToken :: !(Maybe Text)
, _lcScoreMin :: !(Maybe (Textual Int64))
, _lcDraft :: !(Maybe LeaderboardConfigurationDetail)
, _lcId :: !(Maybe Text)
, _lcScoreOrder :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LeaderboardConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcScoreMax'
--
-- * 'lcKind'
--
-- * 'lcPublished'
--
-- * 'lcToken'
--
-- * 'lcScoreMin'
--
-- * 'lcDraft'
--
-- * 'lcId'
--
-- * 'lcScoreOrder'
leaderboardConfiguration
:: LeaderboardConfiguration
leaderboardConfiguration =
LeaderboardConfiguration'
{ _lcScoreMax = Nothing
, _lcKind = "gamesConfiguration#leaderboardConfiguration"
, _lcPublished = Nothing
, _lcToken = Nothing
, _lcScoreMin = Nothing
, _lcDraft = Nothing
, _lcId = Nothing
, _lcScoreOrder = Nothing
}
-- | Maximum score that can be posted to this leaderboard.
lcScoreMax :: Lens' LeaderboardConfiguration (Maybe Int64)
lcScoreMax
= lens _lcScoreMax (\ s a -> s{_lcScoreMax = a}) .
mapping _Coerce
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string gamesConfiguration#leaderboardConfiguration.
lcKind :: Lens' LeaderboardConfiguration Text
lcKind = lens _lcKind (\ s a -> s{_lcKind = a})
-- | The read-only published data of the leaderboard.
lcPublished :: Lens' LeaderboardConfiguration (Maybe LeaderboardConfigurationDetail)
lcPublished
= lens _lcPublished (\ s a -> s{_lcPublished = a})
-- | The token for this resource.
lcToken :: Lens' LeaderboardConfiguration (Maybe Text)
lcToken = lens _lcToken (\ s a -> s{_lcToken = a})
-- | Minimum score that can be posted to this leaderboard.
lcScoreMin :: Lens' LeaderboardConfiguration (Maybe Int64)
lcScoreMin
= lens _lcScoreMin (\ s a -> s{_lcScoreMin = a}) .
mapping _Coerce
-- | The draft data of the leaderboard.
lcDraft :: Lens' LeaderboardConfiguration (Maybe LeaderboardConfigurationDetail)
lcDraft = lens _lcDraft (\ s a -> s{_lcDraft = a})
-- | The ID of the leaderboard.
lcId :: Lens' LeaderboardConfiguration (Maybe Text)
lcId = lens _lcId (\ s a -> s{_lcId = a})
-- | The type of the leaderboard. Possible values are: - \"LARGER_IS_BETTER\"
-- - Larger scores posted are ranked higher. - \"SMALLER_IS_BETTER\" -
-- Smaller scores posted are ranked higher.
lcScoreOrder :: Lens' LeaderboardConfiguration (Maybe Text)
lcScoreOrder
= lens _lcScoreOrder (\ s a -> s{_lcScoreOrder = a})
instance FromJSON LeaderboardConfiguration where
parseJSON
= withObject "LeaderboardConfiguration"
(\ o ->
LeaderboardConfiguration' <$>
(o .:? "scoreMax") <*>
(o .:? "kind" .!=
"gamesConfiguration#leaderboardConfiguration")
<*> (o .:? "published")
<*> (o .:? "token")
<*> (o .:? "scoreMin")
<*> (o .:? "draft")
<*> (o .:? "id")
<*> (o .:? "scoreOrder"))
instance ToJSON LeaderboardConfiguration where
toJSON LeaderboardConfiguration'{..}
= object
(catMaybes
[("scoreMax" .=) <$> _lcScoreMax,
Just ("kind" .= _lcKind),
("published" .=) <$> _lcPublished,
("token" .=) <$> _lcToken,
("scoreMin" .=) <$> _lcScoreMin,
("draft" .=) <$> _lcDraft, ("id" .=) <$> _lcId,
("scoreOrder" .=) <$> _lcScoreOrder])
-- | This is a JSON template for an achievement configuration resource.
--
-- /See:/ 'achievementConfiguration' smart constructor.
data AchievementConfiguration = AchievementConfiguration'
{ _acAchievementType :: !(Maybe Text)
, _acStepsToUnlock :: !(Maybe (Textual Int32))
, _acKind :: !Text
, _acPublished :: !(Maybe AchievementConfigurationDetail)
, _acToken :: !(Maybe Text)
, _acInitialState :: !(Maybe Text)
, _acDraft :: !(Maybe AchievementConfigurationDetail)
, _acId :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AchievementConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acAchievementType'
--
-- * 'acStepsToUnlock'
--
-- * 'acKind'
--
-- * 'acPublished'
--
-- * 'acToken'
--
-- * 'acInitialState'
--
-- * 'acDraft'
--
-- * 'acId'
achievementConfiguration
:: AchievementConfiguration
achievementConfiguration =
AchievementConfiguration'
{ _acAchievementType = Nothing
, _acStepsToUnlock = Nothing
, _acKind = "gamesConfiguration#achievementConfiguration"
, _acPublished = Nothing
, _acToken = Nothing
, _acInitialState = Nothing
, _acDraft = Nothing
, _acId = Nothing
}
-- | The type of the achievement. Possible values are: - \"STANDARD\" -
-- Achievement is either locked or unlocked. - \"INCREMENTAL\" -
-- Achievement is incremental.
acAchievementType :: Lens' AchievementConfiguration (Maybe Text)
acAchievementType
= lens _acAchievementType
(\ s a -> s{_acAchievementType = a})
-- | Steps to unlock. Only applicable to incremental achievements.
acStepsToUnlock :: Lens' AchievementConfiguration (Maybe Int32)
acStepsToUnlock
= lens _acStepsToUnlock
(\ s a -> s{_acStepsToUnlock = a})
. mapping _Coerce
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string gamesConfiguration#achievementConfiguration.
acKind :: Lens' AchievementConfiguration Text
acKind = lens _acKind (\ s a -> s{_acKind = a})
-- | The read-only published data of the achievement.
acPublished :: Lens' AchievementConfiguration (Maybe AchievementConfigurationDetail)
acPublished
= lens _acPublished (\ s a -> s{_acPublished = a})
-- | The token for this resource.
acToken :: Lens' AchievementConfiguration (Maybe Text)
acToken = lens _acToken (\ s a -> s{_acToken = a})
-- | The initial state of the achievement. Possible values are: - \"HIDDEN\"
-- - Achievement is hidden. - \"REVEALED\" - Achievement is revealed. -
-- \"UNLOCKED\" - Achievement is unlocked.
acInitialState :: Lens' AchievementConfiguration (Maybe Text)
acInitialState
= lens _acInitialState
(\ s a -> s{_acInitialState = a})
-- | The draft data of the achievement.
acDraft :: Lens' AchievementConfiguration (Maybe AchievementConfigurationDetail)
acDraft = lens _acDraft (\ s a -> s{_acDraft = a})
-- | The ID of the achievement.
acId :: Lens' AchievementConfiguration (Maybe Text)
acId = lens _acId (\ s a -> s{_acId = a})
instance FromJSON AchievementConfiguration where
parseJSON
= withObject "AchievementConfiguration"
(\ o ->
AchievementConfiguration' <$>
(o .:? "achievementType") <*> (o .:? "stepsToUnlock")
<*>
(o .:? "kind" .!=
"gamesConfiguration#achievementConfiguration")
<*> (o .:? "published")
<*> (o .:? "token")
<*> (o .:? "initialState")
<*> (o .:? "draft")
<*> (o .:? "id"))
instance ToJSON AchievementConfiguration where
toJSON AchievementConfiguration'{..}
= object
(catMaybes
[("achievementType" .=) <$> _acAchievementType,
("stepsToUnlock" .=) <$> _acStepsToUnlock,
Just ("kind" .= _acKind),
("published" .=) <$> _acPublished,
("token" .=) <$> _acToken,
("initialState" .=) <$> _acInitialState,
("draft" .=) <$> _acDraft, ("id" .=) <$> _acId])
-- | This is a JSON template for a localized string resource.
--
-- /See:/ 'localizedString' smart constructor.
data LocalizedString = LocalizedString'
{ _lsKind :: !Text
, _lsLocale :: !(Maybe Text)
, _lsValue :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LocalizedString' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lsKind'
--
-- * 'lsLocale'
--
-- * 'lsValue'
localizedString
:: LocalizedString
localizedString =
LocalizedString'
{ _lsKind = "gamesConfiguration#localizedString"
, _lsLocale = Nothing
, _lsValue = Nothing
}
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string gamesConfiguration#localizedString.
lsKind :: Lens' LocalizedString Text
lsKind = lens _lsKind (\ s a -> s{_lsKind = a})
-- | The locale string.
lsLocale :: Lens' LocalizedString (Maybe Text)
lsLocale = lens _lsLocale (\ s a -> s{_lsLocale = a})
-- | The string value.
lsValue :: Lens' LocalizedString (Maybe Text)
lsValue = lens _lsValue (\ s a -> s{_lsValue = a})
instance FromJSON LocalizedString where
parseJSON
= withObject "LocalizedString"
(\ o ->
LocalizedString' <$>
(o .:? "kind" .!=
"gamesConfiguration#localizedString")
<*> (o .:? "locale")
<*> (o .:? "value"))
instance ToJSON LocalizedString where
toJSON LocalizedString'{..}
= object
(catMaybes
[Just ("kind" .= _lsKind),
("locale" .=) <$> _lsLocale,
("value" .=) <$> _lsValue])
-- | This is a JSON template for a number format resource.
--
-- /See:/ 'gamesNumberFormatConfiguration' smart constructor.
data GamesNumberFormatConfiguration = GamesNumberFormatConfiguration'
{ _gnfcSuffix :: !(Maybe GamesNumberAffixConfiguration)
, _gnfcCurrencyCode :: !(Maybe Text)
, _gnfcNumberFormatType :: !(Maybe Text)
, _gnfcNumDecimalPlaces :: !(Maybe (Textual Int32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'GamesNumberFormatConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gnfcSuffix'
--
-- * 'gnfcCurrencyCode'
--
-- * 'gnfcNumberFormatType'
--
-- * 'gnfcNumDecimalPlaces'
gamesNumberFormatConfiguration
:: GamesNumberFormatConfiguration
gamesNumberFormatConfiguration =
GamesNumberFormatConfiguration'
{ _gnfcSuffix = Nothing
, _gnfcCurrencyCode = Nothing
, _gnfcNumberFormatType = Nothing
, _gnfcNumDecimalPlaces = Nothing
}
-- | An optional suffix for the NUMERIC format type. These strings follow the
-- same plural rules as all Android string resources.
gnfcSuffix :: Lens' GamesNumberFormatConfiguration (Maybe GamesNumberAffixConfiguration)
gnfcSuffix
= lens _gnfcSuffix (\ s a -> s{_gnfcSuffix = a})
-- | The curreny code string. Only used for CURRENCY format type.
gnfcCurrencyCode :: Lens' GamesNumberFormatConfiguration (Maybe Text)
gnfcCurrencyCode
= lens _gnfcCurrencyCode
(\ s a -> s{_gnfcCurrencyCode = a})
-- | The formatting for the number. Possible values are: - \"NUMERIC\" -
-- Numbers are formatted to have no digits or a fixed number of digits
-- after the decimal point according to locale. An optional custom unit can
-- be added. - \"TIME_DURATION\" - Numbers are formatted to hours, minutes
-- and seconds. - \"CURRENCY\" - Numbers are formatted to currency
-- according to locale.
gnfcNumberFormatType :: Lens' GamesNumberFormatConfiguration (Maybe Text)
gnfcNumberFormatType
= lens _gnfcNumberFormatType
(\ s a -> s{_gnfcNumberFormatType = a})
-- | The number of decimal places for number. Only used for NUMERIC format
-- type.
gnfcNumDecimalPlaces :: Lens' GamesNumberFormatConfiguration (Maybe Int32)
gnfcNumDecimalPlaces
= lens _gnfcNumDecimalPlaces
(\ s a -> s{_gnfcNumDecimalPlaces = a})
. mapping _Coerce
instance FromJSON GamesNumberFormatConfiguration
where
parseJSON
= withObject "GamesNumberFormatConfiguration"
(\ o ->
GamesNumberFormatConfiguration' <$>
(o .:? "suffix") <*> (o .:? "currencyCode") <*>
(o .:? "numberFormatType")
<*> (o .:? "numDecimalPlaces"))
instance ToJSON GamesNumberFormatConfiguration where
toJSON GamesNumberFormatConfiguration'{..}
= object
(catMaybes
[("suffix" .=) <$> _gnfcSuffix,
("currencyCode" .=) <$> _gnfcCurrencyCode,
("numberFormatType" .=) <$> _gnfcNumberFormatType,
("numDecimalPlaces" .=) <$> _gnfcNumDecimalPlaces])
-- | This is a JSON template for a leaderboard configuration detail.
--
-- /See:/ 'leaderboardConfigurationDetail' smart constructor.
data LeaderboardConfigurationDetail = LeaderboardConfigurationDetail'
{ _lcdKind :: !Text
, _lcdScoreFormat :: !(Maybe GamesNumberFormatConfiguration)
, _lcdSortRank :: !(Maybe (Textual Int32))
, _lcdName :: !(Maybe LocalizedStringBundle)
, _lcdIconURL :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LeaderboardConfigurationDetail' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcdKind'
--
-- * 'lcdScoreFormat'
--
-- * 'lcdSortRank'
--
-- * 'lcdName'
--
-- * 'lcdIconURL'
leaderboardConfigurationDetail
:: LeaderboardConfigurationDetail
leaderboardConfigurationDetail =
LeaderboardConfigurationDetail'
{ _lcdKind = "gamesConfiguration#leaderboardConfigurationDetail"
, _lcdScoreFormat = Nothing
, _lcdSortRank = Nothing
, _lcdName = Nothing
, _lcdIconURL = Nothing
}
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string gamesConfiguration#leaderboardConfigurationDetail.
lcdKind :: Lens' LeaderboardConfigurationDetail Text
lcdKind = lens _lcdKind (\ s a -> s{_lcdKind = a})
-- | The score formatting for the leaderboard.
lcdScoreFormat :: Lens' LeaderboardConfigurationDetail (Maybe GamesNumberFormatConfiguration)
lcdScoreFormat
= lens _lcdScoreFormat
(\ s a -> s{_lcdScoreFormat = a})
-- | The sort rank of this leaderboard. Writes to this field are ignored.
lcdSortRank :: Lens' LeaderboardConfigurationDetail (Maybe Int32)
lcdSortRank
= lens _lcdSortRank (\ s a -> s{_lcdSortRank = a}) .
mapping _Coerce
-- | Localized strings for the leaderboard name.
lcdName :: Lens' LeaderboardConfigurationDetail (Maybe LocalizedStringBundle)
lcdName = lens _lcdName (\ s a -> s{_lcdName = a})
-- | The icon url of this leaderboard. Writes to this field are ignored.
lcdIconURL :: Lens' LeaderboardConfigurationDetail (Maybe Text)
lcdIconURL
= lens _lcdIconURL (\ s a -> s{_lcdIconURL = a})
instance FromJSON LeaderboardConfigurationDetail
where
parseJSON
= withObject "LeaderboardConfigurationDetail"
(\ o ->
LeaderboardConfigurationDetail' <$>
(o .:? "kind" .!=
"gamesConfiguration#leaderboardConfigurationDetail")
<*> (o .:? "scoreFormat")
<*> (o .:? "sortRank")
<*> (o .:? "name")
<*> (o .:? "iconUrl"))
instance ToJSON LeaderboardConfigurationDetail where
toJSON LeaderboardConfigurationDetail'{..}
= object
(catMaybes
[Just ("kind" .= _lcdKind),
("scoreFormat" .=) <$> _lcdScoreFormat,
("sortRank" .=) <$> _lcdSortRank,
("name" .=) <$> _lcdName,
("iconUrl" .=) <$> _lcdIconURL])
-- | This is a JSON template for an achievement configuration detail.
--
-- /See:/ 'achievementConfigurationDetail' smart constructor.
data AchievementConfigurationDetail = AchievementConfigurationDetail'
{ _acdKind :: !Text
, _acdSortRank :: !(Maybe (Textual Int32))
, _acdName :: !(Maybe LocalizedStringBundle)
, _acdPointValue :: !(Maybe (Textual Int32))
, _acdIconURL :: !(Maybe Text)
, _acdDescription :: !(Maybe LocalizedStringBundle)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AchievementConfigurationDetail' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdKind'
--
-- * 'acdSortRank'
--
-- * 'acdName'
--
-- * 'acdPointValue'
--
-- * 'acdIconURL'
--
-- * 'acdDescription'
achievementConfigurationDetail
:: AchievementConfigurationDetail
achievementConfigurationDetail =
AchievementConfigurationDetail'
{ _acdKind = "gamesConfiguration#achievementConfigurationDetail"
, _acdSortRank = Nothing
, _acdName = Nothing
, _acdPointValue = Nothing
, _acdIconURL = Nothing
, _acdDescription = Nothing
}
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string gamesConfiguration#achievementConfigurationDetail.
acdKind :: Lens' AchievementConfigurationDetail Text
acdKind = lens _acdKind (\ s a -> s{_acdKind = a})
-- | The sort rank of this achievement. Writes to this field are ignored.
acdSortRank :: Lens' AchievementConfigurationDetail (Maybe Int32)
acdSortRank
= lens _acdSortRank (\ s a -> s{_acdSortRank = a}) .
mapping _Coerce
-- | Localized strings for the achievement name.
acdName :: Lens' AchievementConfigurationDetail (Maybe LocalizedStringBundle)
acdName = lens _acdName (\ s a -> s{_acdName = a})
-- | Point value for the achievement.
acdPointValue :: Lens' AchievementConfigurationDetail (Maybe Int32)
acdPointValue
= lens _acdPointValue
(\ s a -> s{_acdPointValue = a})
. mapping _Coerce
-- | The icon url of this achievement. Writes to this field are ignored.
acdIconURL :: Lens' AchievementConfigurationDetail (Maybe Text)
acdIconURL
= lens _acdIconURL (\ s a -> s{_acdIconURL = a})
-- | Localized strings for the achievement description.
acdDescription :: Lens' AchievementConfigurationDetail (Maybe LocalizedStringBundle)
acdDescription
= lens _acdDescription
(\ s a -> s{_acdDescription = a})
instance FromJSON AchievementConfigurationDetail
where
parseJSON
= withObject "AchievementConfigurationDetail"
(\ o ->
AchievementConfigurationDetail' <$>
(o .:? "kind" .!=
"gamesConfiguration#achievementConfigurationDetail")
<*> (o .:? "sortRank")
<*> (o .:? "name")
<*> (o .:? "pointValue")
<*> (o .:? "iconUrl")
<*> (o .:? "description"))
instance ToJSON AchievementConfigurationDetail where
toJSON AchievementConfigurationDetail'{..}
= object
(catMaybes
[Just ("kind" .= _acdKind),
("sortRank" .=) <$> _acdSortRank,
("name" .=) <$> _acdName,
("pointValue" .=) <$> _acdPointValue,
("iconUrl" .=) <$> _acdIconURL,
("description" .=) <$> _acdDescription])
-- | This is a JSON template for a localized string bundle resource.
--
-- /See:/ 'localizedStringBundle' smart constructor.
data LocalizedStringBundle = LocalizedStringBundle'
{ _lsbKind :: !Text
, _lsbTranslations :: !(Maybe [LocalizedString])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LocalizedStringBundle' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lsbKind'
--
-- * 'lsbTranslations'
localizedStringBundle
:: LocalizedStringBundle
localizedStringBundle =
LocalizedStringBundle'
{ _lsbKind = "gamesConfiguration#localizedStringBundle"
, _lsbTranslations = Nothing
}
-- | Uniquely identifies the type of this resource. Value is always the fixed
-- string gamesConfiguration#localizedStringBundle.
lsbKind :: Lens' LocalizedStringBundle Text
lsbKind = lens _lsbKind (\ s a -> s{_lsbKind = a})
-- | The locale strings.
lsbTranslations :: Lens' LocalizedStringBundle [LocalizedString]
lsbTranslations
= lens _lsbTranslations
(\ s a -> s{_lsbTranslations = a})
. _Default
. _Coerce
instance FromJSON LocalizedStringBundle where
parseJSON
= withObject "LocalizedStringBundle"
(\ o ->
LocalizedStringBundle' <$>
(o .:? "kind" .!=
"gamesConfiguration#localizedStringBundle")
<*> (o .:? "translations" .!= mempty))
instance ToJSON LocalizedStringBundle where
toJSON LocalizedStringBundle'{..}
= object
(catMaybes
[Just ("kind" .= _lsbKind),
("translations" .=) <$> _lsbTranslations])
|
rueshyna/gogol
|
gogol-games-configuration/gen/Network/Google/GamesConfiguration/Types/Product.hs
|
mpl-2.0
| 32,839 | 0 | 18 | 7,938 | 5,894 | 3,390 | 2,504 | 646 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Script.Types
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Script.Types
(
-- * Service Configuration
scriptService
-- * OAuth Scopes
, mailGoogleComScope
, m8FeedsScope
, adminDirectoryUserScope
, userInfoEmailScope
, formsCurrentOnlyScope
, driveScope
, adminDirectoryGroupScope
, calendarFeedsScope
, formsScope
, spreadsheetsScope
, groupsScope
-- * Status
, Status
, status
, sDetails
, sCode
, sMessage
-- * Operation
, Operation
, operation
, oDone
, oError
, oResponse
, oName
, oMetadata
-- * ExecutionRequest
, ExecutionRequest
, executionRequest
, erFunction
, erSessionState
, erDevMode
, erParameters
-- * StatusDetailsItem
, StatusDetailsItem
, statusDetailsItem
, sdiAddtional
-- * ScriptStackTraceElement
, ScriptStackTraceElement
, scriptStackTraceElement
, ssteFunction
, ssteLineNumber
-- * ExecutionError
, ExecutionError
, executionError
, eeScriptStackTraceElements
, eeErrorType
, eeErrorMessage
-- * OperationMetadata
, OperationMetadata
, operationMetadata
, omAddtional
-- * OperationResponse
, OperationResponse
, operationResponse
, orAddtional
-- * ExecutionResponse
, ExecutionResponse
, executionResponse
, erStatus
, erResult
) where
import Network.Google.Prelude
import Network.Google.Script.Types.Product
import Network.Google.Script.Types.Sum
-- | Default request referring to version 'v1' of the Google Apps Script Execution API. This contains the host and root path used as a starting point for constructing service requests.
scriptService :: ServiceConfig
scriptService
= defaultService (ServiceId "script:v1")
"script.googleapis.com"
-- | View and manage your mail
mailGoogleComScope :: Proxy '["https://mail.google.com/"]
mailGoogleComScope = Proxy;
-- | Manage your contacts
m8FeedsScope :: Proxy '["https://www.google.com/m8/feeds"]
m8FeedsScope = Proxy;
-- | View and manage the provisioning of users on your domain
adminDirectoryUserScope :: Proxy '["https://www.googleapis.com/auth/admin.directory.user"]
adminDirectoryUserScope = Proxy;
-- | View your email address
userInfoEmailScope :: Proxy '["https://www.googleapis.com/auth/userinfo.email"]
userInfoEmailScope = Proxy;
-- | View and manage forms that this application has been installed in
formsCurrentOnlyScope :: Proxy '["https://www.googleapis.com/auth/forms.currentonly"]
formsCurrentOnlyScope = Proxy;
-- | View and manage the files in your Google Drive
driveScope :: Proxy '["https://www.googleapis.com/auth/drive"]
driveScope = Proxy;
-- | View and manage the provisioning of groups on your domain
adminDirectoryGroupScope :: Proxy '["https://www.googleapis.com/auth/admin.directory.group"]
adminDirectoryGroupScope = Proxy;
-- | Manage your calendars
calendarFeedsScope :: Proxy '["https://www.google.com/calendar/feeds"]
calendarFeedsScope = Proxy;
-- | View and manage your forms in Google Drive
formsScope :: Proxy '["https://www.googleapis.com/auth/forms"]
formsScope = Proxy;
-- | View and manage your spreadsheets in Google Drive
spreadsheetsScope :: Proxy '["https://www.googleapis.com/auth/spreadsheets"]
spreadsheetsScope = Proxy;
-- | View and manage your Google Groups
groupsScope :: Proxy '["https://www.googleapis.com/auth/groups"]
groupsScope = Proxy;
|
rueshyna/gogol
|
gogol-script/gen/Network/Google/Script/Types.hs
|
mpl-2.0
| 3,966 | 0 | 7 | 782 | 455 | 296 | 159 | 89 | 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.Script.Projects.Deployments.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates a deployment of an Apps Script project.
--
-- /See:/ <https://developers.google.com/apps-script/api/ Apps Script API Reference> for @script.projects.deployments.update@.
module Network.Google.Resource.Script.Projects.Deployments.Update
(
-- * REST Resource
ProjectsDeploymentsUpdateResource
-- * Creating a Request
, projectsDeploymentsUpdate
, ProjectsDeploymentsUpdate
-- * Request Lenses
, pduDeploymentId
, pduXgafv
, pduUploadProtocol
, pduAccessToken
, pduUploadType
, pduPayload
, pduScriptId
, pduCallback
) where
import Network.Google.Prelude
import Network.Google.Script.Types
-- | A resource alias for @script.projects.deployments.update@ method which the
-- 'ProjectsDeploymentsUpdate' request conforms to.
type ProjectsDeploymentsUpdateResource =
"v1" :>
"projects" :>
Capture "scriptId" Text :>
"deployments" :>
Capture "deploymentId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] UpdateDeploymentRequest :>
Put '[JSON] Deployment
-- | Updates a deployment of an Apps Script project.
--
-- /See:/ 'projectsDeploymentsUpdate' smart constructor.
data ProjectsDeploymentsUpdate =
ProjectsDeploymentsUpdate'
{ _pduDeploymentId :: !Text
, _pduXgafv :: !(Maybe Xgafv)
, _pduUploadProtocol :: !(Maybe Text)
, _pduAccessToken :: !(Maybe Text)
, _pduUploadType :: !(Maybe Text)
, _pduPayload :: !UpdateDeploymentRequest
, _pduScriptId :: !Text
, _pduCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsDeploymentsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pduDeploymentId'
--
-- * 'pduXgafv'
--
-- * 'pduUploadProtocol'
--
-- * 'pduAccessToken'
--
-- * 'pduUploadType'
--
-- * 'pduPayload'
--
-- * 'pduScriptId'
--
-- * 'pduCallback'
projectsDeploymentsUpdate
:: Text -- ^ 'pduDeploymentId'
-> UpdateDeploymentRequest -- ^ 'pduPayload'
-> Text -- ^ 'pduScriptId'
-> ProjectsDeploymentsUpdate
projectsDeploymentsUpdate pPduDeploymentId_ pPduPayload_ pPduScriptId_ =
ProjectsDeploymentsUpdate'
{ _pduDeploymentId = pPduDeploymentId_
, _pduXgafv = Nothing
, _pduUploadProtocol = Nothing
, _pduAccessToken = Nothing
, _pduUploadType = Nothing
, _pduPayload = pPduPayload_
, _pduScriptId = pPduScriptId_
, _pduCallback = Nothing
}
-- | The deployment ID for this deployment.
pduDeploymentId :: Lens' ProjectsDeploymentsUpdate Text
pduDeploymentId
= lens _pduDeploymentId
(\ s a -> s{_pduDeploymentId = a})
-- | V1 error format.
pduXgafv :: Lens' ProjectsDeploymentsUpdate (Maybe Xgafv)
pduXgafv = lens _pduXgafv (\ s a -> s{_pduXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pduUploadProtocol :: Lens' ProjectsDeploymentsUpdate (Maybe Text)
pduUploadProtocol
= lens _pduUploadProtocol
(\ s a -> s{_pduUploadProtocol = a})
-- | OAuth access token.
pduAccessToken :: Lens' ProjectsDeploymentsUpdate (Maybe Text)
pduAccessToken
= lens _pduAccessToken
(\ s a -> s{_pduAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pduUploadType :: Lens' ProjectsDeploymentsUpdate (Maybe Text)
pduUploadType
= lens _pduUploadType
(\ s a -> s{_pduUploadType = a})
-- | Multipart request metadata.
pduPayload :: Lens' ProjectsDeploymentsUpdate UpdateDeploymentRequest
pduPayload
= lens _pduPayload (\ s a -> s{_pduPayload = a})
-- | The script project\'s Drive ID.
pduScriptId :: Lens' ProjectsDeploymentsUpdate Text
pduScriptId
= lens _pduScriptId (\ s a -> s{_pduScriptId = a})
-- | JSONP
pduCallback :: Lens' ProjectsDeploymentsUpdate (Maybe Text)
pduCallback
= lens _pduCallback (\ s a -> s{_pduCallback = a})
instance GoogleRequest ProjectsDeploymentsUpdate
where
type Rs ProjectsDeploymentsUpdate = Deployment
type Scopes ProjectsDeploymentsUpdate =
'["https://www.googleapis.com/auth/script.deployments"]
requestClient ProjectsDeploymentsUpdate'{..}
= go _pduScriptId _pduDeploymentId _pduXgafv
_pduUploadProtocol
_pduAccessToken
_pduUploadType
_pduCallback
(Just AltJSON)
_pduPayload
scriptService
where go
= buildClient
(Proxy :: Proxy ProjectsDeploymentsUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-script/gen/Network/Google/Resource/Script/Projects/Deployments/Update.hs
|
mpl-2.0
| 5,708 | 0 | 19 | 1,334 | 858 | 499 | 359 | 127 | 1 |
{-# LANGUAGE FlexibleContexts, RankNTypes #-}
module Math.Topology.KnotTh.Enumeration.EquivalenceClasses
( equivalenceClasses
) where
import Control.Monad (when, unless, forM_)
import qualified Control.Monad.State.Strict as State
import Data.Function (fix)
import qualified Data.IntDisjointSet as DS
import qualified Data.IntMap as IM
import qualified Data.Map.Strict as Map
import Math.Topology.KnotTh.Knotted
import Math.Topology.KnotTh.Enumeration.DiagramInfo
data State k v =
St { set :: !DS.IntDisjointSet
, keys :: !(Map.Map k Int)
, vals :: !(IM.IntMap v)
}
equivalenceClasses
:: (KnotWithPrimeTest k a, DiagramInfo info)
=> [k a -> [k a]] -> (forall m. (Monad m) => (k a -> m ()) -> m ()) -> [info (k a)]
equivalenceClasses moves enumerateDiagrams =
IM.elems $ vals $ flip State.execState St {set = DS.empty, keys = Map.empty, vals = IM.empty} $ do
let declareEquivalent !a !b = do
eq <- do
!st <- State.get
let ai = keys st Map.! a
let bi = keys st Map.! b
let (result, nextDS) = DS.equivalent ai bi $ set st
State.put $! st { set = nextDS }
return $! result
unless eq $ do
!st <- State.get
let ds0 = set st
let (Just !ai, !ds1) = DS.lookup (keys st Map.! a) ds0
let (Just !bi, !ds2) = DS.lookup (keys st Map.! b) ds1
let !ds3 = DS.union ai bi ds2
let (Just !resi, !ds4) = DS.lookup ai ds3
let !result = merge (vals st IM.! bi) $ vals st IM.! ai
State.put $! st { set = ds4, vals = IM.insert resi result $ IM.delete bi $ IM.delete ai $ vals st }
let insert !code !current = do
!st <- State.get
let ds = set st
case Map.lookup code $ keys st of
Nothing -> do
let !rootId = DS.size ds
State.put $! st
{ set = DS.insert rootId ds
, keys = Map.insert code rootId $ keys st
, vals = IM.insert rootId current $ vals st
}
return True
Just elId -> do
let (Just rootId, ds') = DS.lookup elId ds
State.put $! st { set = ds', vals = IM.insertWith' merge rootId current $ vals st }
return False
enumerateDiagrams $
flip fix Nothing $ \ dfs !prevCode !diagram -> do
let code = unrootedHomeomorphismInvariant diagram
inserted <- insert code $ wrap diagram
maybe (return ()) (declareEquivalent code) prevCode
when inserted $
forM_ (concatMap ($ diagram) moves) (dfs $ Just code)
|
mishun/tangles
|
src/Math/Topology/KnotTh/Enumeration/EquivalenceClasses.hs
|
lgpl-3.0
| 3,014 | 0 | 24 | 1,222 | 1,022 | 501 | 521 | -1 | -1 |
{-
Copyright 2016, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish
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.
-}
{- This module collects together stubs that connect analysis/transformations
with the input -> output procedures -}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Camfort.Functionality
(
-- * Datatypes
AnnotationType(..)
, CamfortEnv(..)
-- * Commands
, ast
, countVarDecls
-- ** Stencil Analysis
, stencilsCheck
, stencilsInfer
, stencilsSynth
-- ** Unit Analysis
, unitsCriticals
, unitsCheck
, unitsInfer
, unitsCompile
, unitsSynth
-- ** Invariants Analysis
, invariantsCheck
-- ** Refactorings
, common
, dead
, equivalences
-- ** Project Management
, camfortInitialize
) where
import Control.Arrow (first, second)
import Data.List (intersperse)
import Data.Void (Void)
import qualified Data.ByteString as B
import System.Directory (doesDirectoryExist, createDirectoryIfMissing,
getCurrentDirectory)
import System.FilePath (takeDirectory,
(</>), replaceExtension)
import Control.Lens
import Control.Monad.Reader.Class
import Control.Monad (forM_)
import qualified Language.Fortran.AST as F
import qualified Language.Fortran.Util.ModFile as FM
import Camfort.Analysis
import Camfort.Analysis.Annotations (Annotation)
import Camfort.Analysis.Logger
import Camfort.Analysis.ModFile (MFCompiler,
getModFiles,
genModFiles,
readParseSrcDir,
simpleCompiler)
import Camfort.Analysis.Simple
import Camfort.Input
import qualified Camfort.Specification.Stencils as Stencils
import Camfort.Specification.Stencils.Analysis (compileStencils)
import qualified Camfort.Specification.Units as LU
import Camfort.Specification.Units.Analysis (compileUnits)
import Camfort.Specification.Units.Analysis.Consistent (checkUnits)
import Camfort.Specification.Units.Analysis.Criticals (inferCriticalVariables)
import Camfort.Specification.Units.Analysis.Infer (inferUnits)
import Camfort.Specification.Units.Monad (runUnitAnalysis,
unitOpts0)
import Camfort.Specification.Units.MonadTypes (LiteralsOpt,
UnitAnalysis,
UnitEnv (..),
UnitOpts (..))
import qualified Camfort.Specification.Hoare as Hoare
import Camfort.Transformation.CommonBlockElim
import Camfort.Transformation.DeadCode
import Camfort.Transformation.EquivalenceElim
import Camfort.Helpers (FileOrDir,
Filename)
data AnnotationType = ATDefault | Doxygen | Ford
-- | Retrieve the marker character compatible with the given
-- type of annotation.
markerChar :: AnnotationType -> Char
markerChar Doxygen = '<'
markerChar Ford = '!'
markerChar ATDefault = '='
data CamfortEnv =
CamfortEnv
{ ceInputSources :: FileOrDir
, ceIncludeDir :: Maybe FileOrDir
, ceExcludeFiles :: [Filename]
, ceLogLevel :: LogLevel
}
--------------------------------------------------------------------------------
-- * Running Functionality
runWithOutput
:: (Describe e, Describe w)
=> String
-- ^ Functionality desription
-> AnalysisProgram e w IO a b
-- ^ Analysis program
-> (FileOrDir -> FilePath -> AnalysisRunner e w IO a b r)
-- ^ Analysis runner
-> MFCompiler i IO
-- ^ Mod file compiler
-> i
-- ^ Mod file input
-> FilePath
-> CamfortEnv
-> IO r
runWithOutput description program runner mfCompiler mfInput outSrc env =
let runner' = runner (ceInputSources env) outSrc
in runFunctionality description program runner' mfCompiler mfInput env
runFunctionality
:: (Describe e, Describe w)
=> String
-- ^ Functionality desription
-> AnalysisProgram e w IO a b
-- ^ Analysis program
-> AnalysisRunner e w IO a b r
-- ^ Analysis runner
-> MFCompiler i IO
-- ^ Mod file compiler
-> i
-- ^ Mod file input
-> CamfortEnv
-> IO r
runFunctionality description program runner mfCompiler mfInput env = do
putStrLn $ description ++ " '" ++ ceInputSources env ++ "'"
incDir' <- maybe getCurrentDirectory pure (ceIncludeDir env)
isDir <- doesDirectoryExist incDir'
let incDir | isDir = incDir'
| otherwise = takeDirectory incDir'
-- Previously...
--modFiles <- genModFiles mfCompiler mfInput incDir (ceExcludeFiles env)
-- ...instead for now, just get the mod files
modFiles <- getModFiles incDir
pfsTexts <- readParseSrcDir modFiles (ceInputSources env) (ceExcludeFiles env)
runner program (logOutputStd True) (ceLogLevel env) modFiles pfsTexts
--------------------------------------------------------------------------------
-- * Wrappers on all of the features
ast :: CamfortEnv -> IO ()
ast env = do
incDir' <- maybe getCurrentDirectory pure (ceIncludeDir env)
modFiles <- getModFiles incDir'
xs <- readParseSrcDir modFiles (ceInputSources env) (ceExcludeFiles env)
print . fmap fst $ xs
countVarDecls :: CamfortEnv -> IO ()
countVarDecls =
runFunctionality
"Counting variable declarations in"
(generalizePureAnalysis . countVariableDeclarations)
(describePerFileAnalysis "count variable declarations")
simpleCompiler ()
dead :: FileOrDir -> CamfortEnv -> IO ()
dead =
runWithOutput
"Eliminating dead code in"
(fmap generalizePureAnalysis . perFileRefactoring $ deadCode False)
(doRefactor "dead code elimination")
simpleCompiler ()
common :: FileOrDir -> CamfortEnv -> IO ()
common outSrc =
runWithOutput
"Refactoring common blocks in"
(generalizePureAnalysis . commonElimToModules (takeDirectory outSrc ++ "/"))
(doRefactorAndCreate "common block refactoring")
simpleCompiler ()
outSrc
equivalences :: FileOrDir -> CamfortEnv -> IO ()
equivalences =
runWithOutput
"Refactoring equivalences blocks in"
(fmap generalizePureAnalysis . perFileRefactoring $ refactorEquivalences)
(doRefactor "equivalence block refactoring")
simpleCompiler ()
{- Units feature -}
runUnitsFunctionality
:: (Describe e, Describe w)
=> String
-> (UnitOpts -> AnalysisProgram e w IO a b)
-> AnalysisRunner e w IO a b r
-> LiteralsOpt
-> CamfortEnv
-> IO r
runUnitsFunctionality description unitsProgram runner opts =
let uo = optsToUnitOpts opts
in runFunctionality description (unitsProgram uo) runner compileUnits uo
optsToUnitOpts :: LiteralsOpt -> UnitOpts
optsToUnitOpts m = o1
where o1 = unitOpts0 { uoLiterals = m
}
singlePfUnits
:: UnitAnalysis a -> UnitOpts
-> AnalysisProgram () () IO ProgramFile a
singlePfUnits unitAnalysis opts pf =
let ue = UnitEnv
{ unitOpts = opts
, unitProgramFile = pf
}
in runUnitAnalysis ue unitAnalysis
-- slight hack to make doRefactorAndCreate happy
singlePfUnits'
:: UnitAnalysis a -> UnitOpts
-> AnalysisProgram () () IO [ProgramFile] a
singlePfUnits' unitAnalysis opts (pf:_) =
let ue = UnitEnv
{ unitOpts = opts
, unitProgramFile = pf
}
in runUnitAnalysis ue unitAnalysis
multiPfUnits
:: (Describe a)
=> UnitAnalysis (Either e (a, b))
-> UnitOpts
-> AnalysisProgram () () IO [ProgramFile] (Text, [Either e b])
multiPfUnits unitAnalysis opts pfs = do
let ue pf = UnitEnv
{ unitOpts = opts
, unitProgramFile = pf
}
results <- traverse (\pf -> runUnitAnalysis (ue pf) unitAnalysis) pfs
let (rs, ps) = traverse (traverse (\(x, y) -> ([x], y))) results
rs' = mconcat . intersperse "\n" . map describe $ rs
return (rs', ps)
unitsCheck :: LiteralsOpt -> CamfortEnv -> IO ()
unitsCheck =
runUnitsFunctionality
"Checking units for"
(singlePfUnits checkUnits)
(describePerFileAnalysis "unit checking")
unitsInfer :: LiteralsOpt -> CamfortEnv -> IO ()
unitsInfer =
runUnitsFunctionality
"Inferring units for"
(singlePfUnits inferUnits)
(describePerFileAnalysis "unit inference")
{- TODO: remove if not needed
unitsCompile :: FileOrDir -> LiteralsOpt -> CamfortEnv -> IO ()
unitsCompile outSrc opts env =
runUnitsFunctionality
"Compiling units for"
(singlePfUnits inferAndCompileUnits)
(compilePerFile "unit compilation" (ceInputSources env) outSrc)
opts
env
-}
-- Previously...
--modFiles <- genModFiles mfCompiler mfInput incDir (ceExcludeFiles env)
-- ...instead for now, just get the mod files
unitsCompile :: LiteralsOpt -> CamfortEnv -> IO ()
unitsCompile opts env = do
let uo = optsToUnitOpts opts
let description = "Compiling units for"
putStrLn $ description ++ " '" ++ ceInputSources env ++ "'"
incDir' <- maybe getCurrentDirectory pure (ceIncludeDir env)
isDir <- doesDirectoryExist incDir'
let incDir | isDir = incDir'
| otherwise = takeDirectory incDir'
modFiles <- getModFiles incDir
-- Run the gen mod file routine directly on the input source
modFiles <- genModFiles modFiles compileUnits uo (ceInputSources env) (ceExcludeFiles env)
-- Write the mod files out
forM_ modFiles $ \modFile -> do
let mfname = replaceExtension (FM.moduleFilename modFile) FM.modFileSuffix
B.writeFile mfname (FM.encodeModFile modFile)
unitsSynth :: AnnotationType -> FileOrDir -> LiteralsOpt -> CamfortEnv -> IO ()
unitsSynth annType outSrc opts env =
runUnitsFunctionality
"Synthesising units for"
(multiPfUnits $ LU.synthesiseUnits (markerChar annType))
(doRefactor "unit synthesis" (ceInputSources env) outSrc)
opts
env
unitsCriticals :: LiteralsOpt -> CamfortEnv -> IO ()
unitsCriticals =
runUnitsFunctionality
"Suggesting variables to annotate with unit specifications in"
(singlePfUnits inferCriticalVariables)
(describePerFileAnalysis "unit critical variable analysis")
{- Stencils feature -}
stencilsCheck :: CamfortEnv -> IO ()
stencilsCheck =
runFunctionality
"Checking stencil specs for"
(generalizePureAnalysis . Stencils.check)
(describePerFileAnalysis "stencil checking")
compileStencils ()
stencilsInfer :: Bool -> CamfortEnv -> IO ()
stencilsInfer useEval =
runFunctionality
"Inferring stencil specs for"
(generalizePureAnalysis . Stencils.infer useEval '=')
(describePerFileAnalysis "stencil inference")
compileStencils ()
stencilsSynth :: AnnotationType -> FileOrDir -> CamfortEnv -> IO ()
stencilsSynth annType =
let
program :: AnalysisProgram () () IO [ProgramFile] ((), [Either () ProgramFile])
program pfs = generalizePureAnalysis $ do
pfs' <- Stencils.synth (markerChar annType) pfs
return ((), map Right pfs')
in runWithOutput
"Synthesising stencil specs for"
program
(doRefactor "stencil synthesis")
compileStencils ()
{- Invariants Feature-}
invariantsCheck :: Hoare.PrimReprOption -> CamfortEnv -> IO ()
invariantsCheck pro =
runFunctionality
"Checking invariants in"
(Hoare.check pro)
(describePerFileAnalysis "invariant checking")
simpleCompiler ()
-- | Initialize Camfort for the given project.
camfortInitialize :: FilePath -> IO ()
camfortInitialize projectDir =
createDirectoryIfMissing False (projectDir </> ".camfort")
|
dorchard/camfort
|
src/Camfort/Functionality.hs
|
apache-2.0
| 12,879 | 0 | 17 | 3,421 | 2,544 | 1,349 | 1,195 | 263 | 1 |
module ProductBroken where
mult :: a -> a -> a
mult = (*) -- this is point-free notation
|
OCExercise/haskellbook-solutions
|
chapters/chapter06/scratch/product_broken.hs
|
bsd-2-clause
| 90 | 0 | 6 | 19 | 25 | 16 | 9 | 3 | 1 |
module Text.Protocol.NMEA0183.Parsers.Sentence where
import Control.Applicative
import Data.Char
import qualified Data.Text as T
import Text.Protocol.NMEA0183.Types.Talker
import Text.Parser.Char
import Text.Parser.Combinators
parseTalkerId :: (Monad m, CharParsing m) => m TalkerIdentifier
parseTalkerId = parseU <|> parseNormal
where
parseU = do
_ <- char 'U'
n <- digit
-- This 'read' is bad (partial), but we are relying on "parsers" indeed
-- giving us a digit back (the parser should/will fail otherwise).
-- Nevertheless, we should possibly 'readMay' and fail ourselves.
return (U (read [n]))
parseNormal = do
x <- count 2 upper
return $ case x of
"AB" -> AB
"AD" -> AD
"AG" -> AG
"AP" -> AP
"BN" -> BN
"CC" -> CC
"CD" -> CD
"CM" -> CM
"CS" -> CS
"CT" -> CT
"CV" -> CV
"CX" -> CX
"DE" -> DE
"DF" -> DF
"DU" -> DU
"EC" -> EC
"EP" -> EP
"ER" -> ER
"GP" -> GP
"HC" -> HC
"HE" -> HE
"HN" -> HN
"II" -> II
"IN" -> IN
"LA" -> LA
"LC" -> LC
"MP" -> MP
"NL" -> NL
"OM" -> OM
"OS" -> OS
"RA" -> RA
"SD" -> SD
"SN" -> SN
"SS" -> SS
"TI" -> TI
"TR" -> TR
"UP" -> UP
"VD" -> VD
"DM" -> DM
"VW" -> VW
"WI" -> WI
"YC" -> YC
"YD" -> YD
"YF" -> YF
"YL" -> YL
"YP" -> YP
"YR" -> YR
"YT" -> YT
"YV" -> YV
"YX" -> YX
"ZA" -> ZA
"ZC" -> ZC
"ZQ" -> ZQ
"ZV" -> ZV
parseSentenceIdentifier :: CharParsing m => m T.Text
parseSentenceIdentifier = T.pack <$> count 3 upper
parseChecksum :: (CharParsing m, Monad m) => m (Char, Char)
parseChecksum = do
_ <- char ','
_ <- char '*'
(,) <$> upperHexDigit <*> upperHexDigit
where
upperHexDigit =
satisfy (\c -> (isHexDigit c && isUpper c) || isDigit c)
<?> "uppercase hexadecimal digit"
-- | Parse a NMEA 0183 sentence. The idea is to use this like
-- @parseSentence parseGGA :: Parser (TalkerSentence GGA)@
parseSentence :: (CharParsing m, Monad m) => m a -> m (TalkerSentence a)
parseSentence f = do
_ <- char '$'
talkerId <- parseTalkerId
sentenceIdentifier <- parseSentenceIdentifier
_ <- char ','
dataFields <- f
checksum <- optional parseChecksum
_ <- char '\r'
_ <- char '\n'
TalkerSentence <$> pure talkerId
<*> pure sentenceIdentifier
<*> pure dataFields
<*> pure checksum
|
noexc/nmea0183
|
src/Text/Protocol/NMEA0183/Parsers/Sentence.hs
|
bsd-2-clause
| 2,696 | 0 | 14 | 981 | 770 | 386 | 384 | 94 | 54 |
module Yesod.Internal.Session
( encodeSession
, decodeSession
) where
import qualified Web.ClientSession as CS
import Data.Serialize
import Data.Time
import Data.ByteString (ByteString)
import Control.Monad (guard)
import Data.Text (Text, pack, unpack)
import Control.Arrow (first)
import Control.Applicative ((<$>))
encodeSession :: CS.Key
-> CS.IV
-> UTCTime -- ^ expire time
-> ByteString -- ^ remote host
-> [(Text, ByteString)] -- ^ session
-> ByteString -- ^ cookie value
encodeSession key iv expire rhost session' =
CS.encrypt key iv $ encode $ SessionCookie expire rhost session'
decodeSession :: CS.Key
-> UTCTime -- ^ current time
-> ByteString -- ^ remote host field
-> ByteString -- ^ cookie value
-> Maybe [(Text, ByteString)]
decodeSession key now rhost encrypted = do
decrypted <- CS.decrypt key encrypted
SessionCookie expire rhost' session' <-
either (const Nothing) Just $ decode decrypted
guard $ expire > now
guard $ rhost' == rhost
return session'
data SessionCookie = SessionCookie UTCTime ByteString [(Text, ByteString)]
deriving (Show, Read)
instance Serialize SessionCookie where
put (SessionCookie a b c) = putTime a >> put b >> put (map (first unpack) c)
get = do
a <- getTime
b <- get
c <- map (first pack) <$> get
return $ SessionCookie a b c
putTime :: Putter UTCTime
putTime t@(UTCTime d _) = do
put $ toModifiedJulianDay d
let ndt = diffUTCTime t $ UTCTime d 0
put $ toRational ndt
getTime :: Get UTCTime
getTime = do
d <- get
ndt <- get
return $ fromRational ndt `addUTCTime` UTCTime (ModifiedJulianDay d) 0
|
chreekat/yesod
|
yesod-core/Yesod/Internal/Session.hs
|
bsd-2-clause
| 1,785 | 0 | 12 | 489 | 562 | 289 | 273 | 50 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : PFSandbox
-- Note : Beispiele und Platz zum Spielen und Probieren
--
-- Diese Sandbox ist zum testen von PrimeFields gedacht.
--
-- Die main Funktion enthält Hspec unit tests.
--
--------------------------------------------------------------------------------
{-# LANGUAGE TemplateHaskell #-}
module GalFld.Sandbox.PFSandbox
where
import GalFld.Core.PrimeFields
|
maximilianhuber/softwareProjekt
|
src/GalFld/Sandbox/PFSandbox.hs
|
bsd-3-clause
| 479 | 0 | 4 | 65 | 24 | 20 | 4 | 3 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Opaleye.Array where
import Opaleye.Constant (Constant,constant)
import Opaleye.Internal.Column (Column(Column),unColumn)
import Opaleye.PGTypes (PGArray,PGBool)
import Data.Profunctor.Product.Default (Default)
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
arrayContains :: Column (PGArray a) -> Column (PGArray a) -> Column PGBool
arrayContains a b = Column (HPQ.BinExpr HPQ.OpContains (unColumn a) (unColumn b))
pgArray :: forall a b. Default Constant a (Column b) => [a] -> Column (PGArray b)
pgArray = Column . HPQ.ArrayExpr . fmap ( unColumn . (constant :: a -> Column b))
|
benkolera/haskell-opaleye
|
src/Opaleye/Array.hs
|
bsd-3-clause
| 674 | 0 | 11 | 87 | 229 | 128 | 101 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad.Remote.JSON
import Network.Wreq
import Data.Aeson
import Control.Lens ((^.))
import Control.Monad (void)
session :: Session
session = defaultSession Strong (\v -> do
r <- asJSON =<< post "http://129.237.120.52:3000/" v
return $ r ^. responseBody)
(\v -> do
void $ post "http://129.237.120.52:3000/" v
return ())
main = do t<- send session $ do
notification "say" [String "Hello"]
notification "say" [String "Howdy"]
notification "say" [String "GoodDay"]
method "temperature" []
print t
|
roboguy13/remote-json
|
example/Strong/ScottyClient.hs
|
bsd-3-clause
| 783 | 0 | 13 | 314 | 198 | 98 | 100 | 19 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Test.Handshakes where
import Crypto.Hash
import Crypto.PubKey.Curve25519
import Crypto.PubKey.RSA
import Crypto.PubKey.RSA.Types
import Control.Applicative
import Control.Monad
import Crypto.Random
import Data.ByteArray(convert,eq)
import Data.ByteString(ByteString,pack)
import qualified Data.ByteString as BS
import Data.Word
import Hexdump
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck hiding (generate)
import Test.Standard
import Tor.State.Credentials
import Tor.HybridCrypto
import Tor.Circuit
import Tor.RouterDesc
import Tor.DataFormat.TorCell
import Tor.RNG
import Debug.Trace
data RouterTAP = RouterTAP RouterDesc PrivateKey
deriving (Show)
instance Arbitrary RouterTAP where
arbitrary =
do g <- arbitrary :: Gen TorRNG
let ((pub, priv), _) = withDRG g (generate (1024 `div` 8) 65537)
desc = blankRouterDesc{ routerOnionKey = pub }
return (RouterTAP desc priv)
instance Arbitrary TorRNG where
arbitrary = drgNewTest `fmap` arbitrary
instance Show TorRNG where
show _ = "TorRNG"
instance Eq (Context SHA1) where
a == b = a `eq` b
instance Show (Context SHA1) where
show x = simpleHex (convert x)
data RouterNTor = RouterNTor RouterDesc SecretKey
deriving (Show)
instance Arbitrary RouterNTor where
arbitrary =
do g0 <- arbitrary :: Gen TorRNG
let ((pub, priv), g1) = withDRG g0 generate25519
(fprint, g2) = withRandomBytes g1 20 id
desc = blankRouterDesc{ routerFingerprint = fprint
, routerNTorOnionKey = Just pub
}
return (RouterNTor desc priv)
tapHandshakeCheck :: Word32 -> RouterTAP -> TorRNG -> Bool
tapHandshakeCheck circId (RouterTAP myRouter priv) g0 =
let (g1, (privX, cbody)) = startTAPHandshake myRouter g0
(g2, (dcell, fenc, benc)) = advanceTAPHandshake priv circId cbody g1
Created circIdD dbody = dcell
in case completeTAPHandshake privX dbody of
Left err ->
False
Right (fenc', benc') ->
(circId == circIdD) && (fenc == fenc') && (benc == benc')
ntorHandshakeCheck :: Word32 -> RouterNTor -> TorRNG -> Bool
ntorHandshakeCheck circId (RouterNTor router littleB) g0 =
case startNTorHandshake router g0 of
(_, Nothing) ->
False
(g1, Just (pair, cbody)) ->
case advanceNTorHandshake router littleB circId cbody g1 of
(_, Left err) ->
False
(_, Right (Created2 _ dbody, fenc, benc)) ->
case completeNTorHandshake router pair dbody of
Left err ->
False
Right (fenc', benc') ->
(fenc == fenc') && (benc == benc')
handshakeTests :: Test
handshakeTests =
testGroup "Handshakes" [
testProperty "TAP Handshake" tapHandshakeCheck
, testProperty "NTor Handshake" ntorHandshakeCheck
]
|
GaloisInc/haskell-tor
|
test/Test/Handshakes.hs
|
bsd-3-clause
| 2,960 | 0 | 16 | 693 | 883 | 480 | 403 | 82 | 4 |
module Interpreter where
data List a = Nil | Cons a (List a)
single x = Cons x Nil
cons = Cons
|
rolph-recto/liquidhaskell
|
tests/todo/NativeFixCrash.hs
|
bsd-3-clause
| 105 | 0 | 8 | 32 | 43 | 24 | 19 | 4 | 1 |
-- Main.hs
-- by alemedeiros <alexandre.n.medeiros _at_ gmail.com>
--
-- Main file for musicdb, a MusicBrainz based artist information database
-- application
-- | A small project for artist/music information database using MusicBrainz as
-- a source of information (Individual Project for QMUL's ECS713 - Functional
-- Programming Module).
--
-- The project code can be found on github: https://github.com/alemedeiros/musicdb
module Main where
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import MusicBrainz
import System.Environment
-- |The main function provides 5 different functionalities:
--
-- [@init@]
-- Initialize local database
--
-- [@add artist@]
-- Download the artist information with it's releases and add to local database
--
-- [@search artist@]
-- Search MusicBrainz database for the given artist and print the top results
--
-- [@query artist album@]
-- Query the local database for the specified album
--
-- [@recommend artist album@]
-- Generate a recommendation list of similar artists (with the computed score)
-- from the local database, starting with the given album/artist
main :: IO ()
main = do args <- getArgs
case args of
("init":opt) -> do
let
optMap = optParse opt
dbFile = fromJust $ Map.lookup "dbfile" optMap
createDB dbFile
("add":art:opt) -> do
let
optMap = optParse opt
lim = read . fromJust $ Map.lookup "lim" optMap
dbFile = fromJust $ Map.lookup "dbfile" optMap
byID = read . fromJust $ Map.lookup "id" optMap
artInfo <- if byID
then getArtistInfoByID dbFile art
else getArtistInfo dbFile art lim
putStrLn artInfo
("search":art:opt) -> do
let
optMap = optParse opt
lim = read . fromJust $ Map.lookup "lim" optMap
artSearch <- searchArtist art lim
-- Check result and print it
case artSearch of
[] -> printError "no artist found"
_ -> mapM_ (\(i,n) -> putStrLn (i ++ "\t" ++ n)) artSearch
("query":art:alb:opt) -> do
let
optMap = optParse opt
dbFile = fromJust $ Map.lookup "dbfile" optMap
info <- queryLocalDB dbFile art alb
putStr info
("recommend":art:alb:opt) -> do
let
optMap = optParse opt
dbFile = fromJust $ Map.lookup "dbfile" optMap
lim = read . fromJust $ Map.lookup "lim" optMap
thr = read . fromJust $ Map.lookup "threshold" optMap
recommendations <- recommend dbFile lim thr art alb
case recommendations of
[] -> printError "problems computing recommendations"
_ -> putStrLn $ concatMap (\(s,a) -> show s ++ "\t" ++ artName a ++ "\n") recommendations
-- Help commands
("help":_) -> printHelp
("usage":_) -> printHelp
-- Command errors
[] -> do
printError "missing command"
suggestHelp
_ -> do
printError $ "undefided arguments -- " ++ show args
suggestHelp
{- Command-line parsing -}
-- |Parse options arguments
optParse :: [String] -> Map String String
optParse = fillDefaultOpt defaultOptions . optParseAux
where
optParseAux [] = Map.empty
optParseAux ("--id":opt) = Map.insert "id" "True" $ optParseAux opt
optParseAux ("-i":opt) = Map.insert "id" "True" $ optParseAux opt
optParseAux ("--lim":lim:opt) = Map.insert "lim" lim $ optParseAux opt
optParseAux ("-l":lim:opt) = Map.insert "lim" lim $ optParseAux opt
optParseAux ("--dbfile":file:opt) = Map.insert "dbfile" file $ optParseAux opt
optParseAux ("-f":file:opt) = Map.insert "dbfile" file $ optParseAux opt
optParseAux ("--threshold":file:opt) = Map.insert "threshold" file $ optParseAux opt
optParseAux ("-t":file:opt) = Map.insert "threshold" file $ optParseAux opt
optParseAux opt = error $ "couldn't parse arguments -- " ++ show opt
-- |Fill the option map with the 'defaultOption' for options not specified by
-- the user
fillDefaultOpt :: [(String,String)] -> Map String String -> Map String String
fillDefaultOpt [] opt = opt
fillDefaultOpt ((k,v):def) opt
| Map.notMember k opt = Map.insert k v $ fillDefaultOpt def opt
| otherwise = fillDefaultOpt def opt
-- |Default options definition
defaultOptions :: [(String, String)]
defaultOptions = [ ("id", "False"), ("lim", "4") , ("dbfile", "music.db"), ("threshold", "100") ]
|
alemedeiros/musicdb
|
src/Main.hs
|
bsd-3-clause
| 5,517 | 0 | 22 | 2,144 | 1,172 | 601 | 571 | 75 | 12 |
{-# LANGUAGE FlexibleContexts #-}
module Cloud.AWS.EC2.KeyPair
( describeKeyPairs
, createKeyPair
, deleteKeyPair
, importKeyPair
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Base64 as BASE
import Data.Text (Text)
import Data.Conduit
import Control.Applicative
import Control.Monad.Trans.Resource (MonadThrow, MonadResource, MonadBaseControl)
import Cloud.AWS.Lib.Parser.Unordered (XmlElement, (.<))
import Cloud.AWS.EC2.Internal
import Cloud.AWS.EC2.Types
import Cloud.AWS.EC2.Query
describeKeyPairs
:: (MonadResource m, MonadBaseControl IO m)
=> [Text] -- ^ PublicIps
-> [Filter] -- ^ Filters
-> EC2 m (ResumableSource m KeyPair)
describeKeyPairs names filters =
ec2QuerySource "DescribeKeyPairs" params path $
itemConduit keyPairConv
where
path = itemsPath "keySet"
params =
[ "KeyName" |.#= names
, filtersParam filters
]
keyPairConv :: (MonadThrow m, Applicative m) => XmlElement -> m KeyPair
keyPairConv xml = KeyPair
<$> xml .< "keyName"
<*> xml .< "keyFingerprint"
createKeyPair
:: (MonadResource m, MonadBaseControl IO m)
=> Text -- ^ KeyName
-> EC2 m (KeyPair, Text) -- ^ KeyPair and KeyMaterial
createKeyPair name =
ec2Query "CreateKeyPair" ["KeyName" |= name] $ \xml ->
(,) <$> keyPairConv xml <*> xml .< "keyMaterial"
deleteKeyPair
:: (MonadResource m, MonadBaseControl IO m)
=> Text -- ^ KeyName
-> EC2 m Bool
deleteKeyPair = ec2Delete "DeleteKeyPair" "KeyName"
importKeyPair
:: (MonadResource m, MonadBaseControl IO m)
=> Text -- ^ KeyName
-> ByteString -- ^ PublicKeyMaterial
-> EC2 m KeyPair
importKeyPair name material =
ec2Query "ImportKeyPair" params keyPairConv
where
params =
[ "KeyName" |= name
, "PublicKeyMaterial" |= BASE.encode material
]
|
worksap-ate/aws-sdk
|
Cloud/AWS/EC2/KeyPair.hs
|
bsd-3-clause
| 1,884 | 0 | 10 | 408 | 481 | 271 | 210 | 54 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Api.Projects where
import Control.Monad.IO.Class (liftIO)
import Data.Proxy
import qualified Data.Text as T
import GHC.Generics
import Servant
import Api.Projects.TacoShop (NameType (..), makeBertosName)
import Types
data Project = Project {
name :: !T.Text
, result :: !T.Text
} deriving (Eq, Show, Generic)
type ProjectApi =
"tacoshop" :> "random" :> Capture "len" Int :> Get '[JSON] Project
-- "fifty-two-trees" :> "trees" :> Get '[JSON] Project
projectHandlers :: ServerT ProjectApi SimpleHandler
projectHandlers = bertosH
bertosH :: Int -> SimpleHandler Project
bertosH n = do
value <- if n < 6
then pure "bertos"
else liftIO $ makeBertosName n
pure $ Project (T.pack $ show RandomCharacter) value
projectApi :: Proxy ProjectApi
projectApi = Proxy
|
pellagic-puffbomb/simpleservantblog
|
src/Api/Projects.hs
|
bsd-3-clause
| 1,008 | 0 | 11 | 255 | 241 | 135 | 106 | 32 | 2 |
{-# LANGUAGE DeriveGeneric, UndecidableInstances #-}
{-# LANGUAGE TypeFamilies, BangPatterns #-}
{-# LANGUAGE RankNTypes, AllowAmbiguousTypes #-}
{-|
Immutable GPU multi-dimensional dense numeric arrays.
-}
module DeepBanana.Tensor (
Tensor(..)
-- * Basic manipulations
, dtype
, zeros
, zeros'
, ones
, ones'
-- * Shape manipulations
, reshape
, reshape'
, shapeConvert
, liftFixed1
, liftFixed2
, broadcast
, broadcast'
-- * Device manipulations
, deviceConvert
-- * Converting from/to mutable tensors
, unsafeFreeze
, unsafeThaw
-- * Converting from/to lists
, tensorFromList
, tensorFromList'
, tensorToList
-- * Converting from/to storable vectors
, fromVector
, fromVector'
, toVector
-- * Utilities
, tconcat
, tconcat'
, tsplitAt
, tsplitAt'
, elementwiseMax
, flatten
-- * Re-exports
, module DeepBanana.Tensor.Shape
, module DeepBanana.Tensor.Exception
, module DeepBanana.Tensor.TensorScalar
) where
import Data.Serialize (Serialize)
import qualified Data.Serialize as S
import qualified Data.Vector.Storable as SV
import qualified Data.Vector.Storable.Mutable as SMV
import System.IO.Unsafe
import Unsafe.Coerce
import DeepBanana.Device
import qualified DeepBanana.Device.CuDNN as CuDNN
import qualified DeepBanana.Device.CUDA as CUDA
import DeepBanana.Exception
import DeepBanana.Prelude
import DeepBanana.Tensor.Exception
import qualified DeepBanana.Tensor.Mutable as MT
import DeepBanana.Tensor.Mutable (MTensor)
import DeepBanana.Tensor.Shape
import DeepBanana.Tensor.TensorScalar
import DeepBanana.Weights
-- | An immutable, dense numerical array stored on GPU device @d@, with shape @s@ and
-- scalar datatype @a@.
-- As long as the shape and device datatypes are fixed at the type level, it is an
-- instance of all standard numeric type classes in an elementwise fashion.
data Tensor d s a = Tensor {
device :: d
, shape :: s
, dataptr :: !(ForeignPtr a)
}
instance (Shape s, Device d, TensorScalar a, Eq a) => Eq (Tensor d s a) where
t1 == t2 = device t1 == device t2
&& tensorToList t1 == tensorToList t2
&& shape t1 == shape t2
instance (Device d, Shape s, TensorScalar a)
=> Serialize (Tensor d s a) where
put t = do
S.put $ device t
S.put $ shape t
S.put $ tensorToList t
get = do
dev <- S.get
shp <- S.get
tlist <- S.get
return $ tensorFromList' dev shp tlist
instance (NFData d, NFData s) => NFData (Tensor d s a) where
rnf (Tensor d s _) = rnf (s, d)
instance (Device d, Shape s, TensorScalar a, Show a)
=> Show (Tensor d s a) where
show t = "Tensor " ++ show (device t) ++ " " ++ show (shape t)
++ " " ++ show (take 10 $ tensorToList t)
-- | Reshaping. Throws an @'IncompatibleSize'@ exception when the desired size and the
-- input size do not correspond.
reshape :: (Shape s1, Shape s2, TensorScalar a,
MonadError t m, Variant t IncompatibleSize)
=> s2 -> Tensor d s1 a -> m (Tensor d s2 a)
reshape newshp t@(Tensor dev oldshp dataptr) = do
when (size newshp /= size oldshp) $ throwVariant $ incompatibleSize $
"Couldn't reshape tensor from shape " ++ show oldshp ++ " to shape " ++ show newshp ++ ": incompatible sizes " ++ show (size oldshp) ++ " and " ++ show (size newshp)
return $ Tensor dev newshp dataptr
-- | Unsafe reshaping. Throws an imprecise exception when the desired size and the
-- input size do not correspond.
reshape' :: forall d s1 s2 a
. (Shape s1, Shape s2, TensorScalar a)
=> s2 -> Tensor d s1 a -> Tensor d s2 a
reshape' newshp t =
unsafeRunExcept (reshape newshp t :: Either IncompatibleSize (Tensor d s2 a))
-- | Shape conversion. This differs from @'reshape'@ in that the desired shape and
-- input shape must have exactly the same dimensions. This is useful when converting
-- between dynamic and fixed shape datatypes. Throws an @'IncompatibleShape'@ exception
-- when the 2 shapes dimensions differ.
shapeConvert :: forall s1 s2 d l a m t
. (MonadError t m, Shape s1, Shape s2, Variant t IncompatibleShape)
=> s2 -> Tensor d s1 a -> m (Tensor d s2 a)
shapeConvert outshp (Tensor dev shp datafptr) = do
when (dimensions outshp /= dimensions shp) $ throwVariant $ incompatibleShape $
"Cannot convert tensor from shape " ++ show shp ++ " to shape " ++ show outshp
return $ Tensor dev outshp datafptr
-- | Device conversion. This differs from @'transfer'@ in that the desired device and
-- input device must actually refer to the same device. This is useful when converting
-- between dynamic and fixed device datatypes. Throws an @'IncompatibleDevice'@
-- exception when the 2 devices differ.
deviceConvert :: (MonadError t m, Device d, Device d', Variant t IncompatibleDevice)
=> d' -> Tensor d s a -> m (Tensor d' s a)
deviceConvert outDev (Tensor inpDev shp datafptr) = do
when (deviceId outDev /= deviceId inpDev) $ throwVariant $ incompatibleDevice $
"Cannot convert tensor from device " ++ show inpDev ++ " to device " ++ show outDev
return $ Tensor outDev shp datafptr
-- | Lifts an unary function on fixed shape tensors to work on any tensor. Useful to
-- apply unary numeric functions such as @'log'@ or @'exp'@ to dynamic shape tensors
-- in a type safe fashion.
liftFixed1 :: forall d s a
. (Shape s, Device d)
=> (forall s' d' . (IsFixed s', ValidUniqueDevice d')
=> Tensor d' s' a -> Tensor d' s' a)
-> Tensor d s a -> Tensor d s a
liftFixed1 f x = unsafeRunExcept eres
where
eres :: Either (Coproduct '[IncompatibleShape, IncompatibleDevice]) (Tensor d s a)
eres = do
case toAnyFixed $ shape x of
AnyFixed fshp -> do
fx <- shapeConvert fshp x
withValidUniqueDevice (device x) $ \dev' -> do
dfx <- deviceConvert dev' fx
dfy <- shapeConvert (shape x) $ f dfx
deviceConvert (device x) dfy
instance (Device d, Shape s, TensorScalar a)
=> FixShape (Tensor d s a) where
type FixScalar (Tensor d s a) = a
liftVec = liftFixed2
-- | Lifts a binary function on fixed shape tensors to work on any tensor. Throws
-- an @'IncompatibleShape'@ exception when the input tensors do not have the same
-- shape. Useful to apply binary numeric functions such as @'(+)'@ and @'(*)'@ to
-- dynamic shape tensors in a type safe fashion.
liftFixed2 :: (Device d, Shape s, MonadError t m, Variant t IncompatibleShape,
Variant t IncompatibleDevice)
=> (forall d' s' . (ValidUniqueDevice d', IsFixed s')
=> Tensor d' s' a -> Tensor d' s' a -> Tensor d' s' a)
-> Tensor d s a -> Tensor d s a -> m (Tensor d s a)
liftFixed2 g x1 x2 = do
case toAnyFixed $ shape x1 of
AnyFixed fshp -> do
fx1 <- shapeConvert fshp x1
fx2 <- shapeConvert fshp x2
withValidUniqueDevice (device x1) $ \dev' -> do
dfx1 <- deviceConvert dev' fx1
dfx2 <- deviceConvert dev' fx2
dfy <- shapeConvert (shape x1) $ g dfx1 dfx2
deviceConvert (device x1) dfy
instance (Device d, Device d', TensorScalar a, Shape s)
=> DeviceTransfer (Tensor d s a) d' where
type Transferred (Tensor d s a) d' = Tensor d' s a
transfer dev t = embedExcept $ runST $ runExceptT $ do
mt <- unsafeThaw t
mt' <- MT.copy dev mt
unsafeFreeze mt'
-- | Returns the CuDNN datatype of a tensor.
dtype :: forall d s a . (TensorScalar a) => Tensor d s a -> CuDNN.DataType
dtype _ = datatype (Proxy :: Proxy a)
-- | Converts a mutable tensor into an immutable one in O(1) time. The data is not
-- copied, so one should make sure the input mutable tensor is not modified after the
-- the conversion. Unsafe.
unsafeFreeze :: (PrimMonad m) => MTensor (PrimState m) d s a -> m (Tensor d s a)
unsafeFreeze (MT.MTensor dev shp ptr) = return $ Tensor dev shp ptr
-- | Converts an immutable tensor into a mutable one in O(1) time. The data is not
-- copied, so one should make sure the input immutable tensor is not used after the
-- conversion. Unsafe.
unsafeThaw :: (PrimMonad m) => Tensor d s a -> m (MTensor (PrimState m) d s a)
unsafeThaw (Tensor dev shp ptr) = return $ MT.MTensor dev shp ptr
-- | Returns a tensor with all zero coefficients. Throws an @'OutOfMemory'@ exception
-- when the desired device is out of memory.
zeros :: (Device d, Shape s, TensorScalar a, MonadError t m,
Variant t OutOfMemory)
=> d -> s -> m (Tensor d s a)
zeros dev shp = do
embedExcept $ runST $ runExceptT $ MT.zeros dev shp >>= unsafeFreeze
-- | Returns a tensor with all zero coefficients. Throws an imprecise exception when
-- the desired device is out of memory.
zeros' :: forall d s a
. (Device d, Shape s, TensorScalar a)
=> d -> s -> Tensor d s a
zeros' dev shp = unsafeRunExcept (zeros dev shp :: Either OutOfMemory (Tensor d s a))
-- | Initializes a tensor with all ones. Throws an @'OutOfMemory'@ exception
-- when the desired device is out of memory.
ones :: (Device d, Shape s, TensorScalar a, MonadError t m,
Variant t OutOfMemory)
=> d -> s -> m (Tensor d s a)
ones dev shp = do
embedExcept $ runST $ runExceptT $ MT.ones dev shp >>= unsafeFreeze
-- | Returns a tensor with all one coefficients. Throws an imprecise exception when
-- the desired device is out of memory.
ones' :: forall d s a
. (Device d, Shape s, TensorScalar a)
=> d -> s -> Tensor d s a
ones' dev shp = unsafeRunExcept (ones dev shp :: Either OutOfMemory (Tensor d s a))
-- | Initializes a tensor from list data. If the length of the list does not correspond
-- to the size of the desired shape, throws an exception at run time.
tensorFromList :: (Device d, Shape s, TensorScalar a, MonadError t m,
Variant t IncompatibleSize, Variant t OutOfMemory)
=> d -> s -> [a] -> m (Tensor d s a)
tensorFromList dev shape value = do
embedExcept $ runST $ runExceptT $ MT.tensorFromList dev shape value >>= unsafeFreeze
-- | Unsafe version of @'tensorFromList'@, throws imprecise exceptions.
tensorFromList' :: forall d s a
. (Device d, Shape s, TensorScalar a)
=> d -> s -> [a] -> Tensor d s a
tensorFromList' dev shape value =
unsafeRunExcept (tensorFromList dev shape value
:: Either (Coproduct '[IncompatibleSize, OutOfMemory]) (Tensor d s a))
-- | Converts a tensor to a list.
tensorToList :: (Shape s, Device d, TensorScalar a) => Tensor d s a -> [a]
tensorToList t = runST $ unsafeThaw t >>= MT.tensorToList
-- | Converts a storable vector to an immutable tensor. Throws an error at runtime
-- when the input's length does not correspond to the desired output size. Runs in
-- O(n) time.
fromVector :: forall t m d s a
. (Device d, Shape s, TensorScalar a, MonadError t m,
Variant t OutOfMemory, Variant t IncompatibleSize)
=> d -> s -> SVector a -> m (Tensor d s a)
fromVector dev shp value = do
when (length value /= size shp) $ throwVariant $ incompatibleSize $
"fromVector: Incompatible sizes\n\tinput vector: "
++ show (length value) ++ "\n\trequired output shape: "
++ show shp
++ ", size " ++ show (size shp)
embedExcept $ unsafePerformIO $ runExceptT $ do
res <- MT.emptyTensor dev shp
liftIO $ SV.unsafeWith value $ \vptr -> do
MT.withDevicePtr res $ \resptr -> do
runDeviceM dev $ CUDA.pokeArray (size shp) vptr resptr
unsafeFreeze res
-- | Unsafe version of @'fromVector'@, throws imprecise exceptions.
fromVector' :: forall d s a
. (Device d, Shape s, TensorScalar a)
=> d -> s -> SVector a -> Tensor d s a
fromVector' dev shp value =
unsafeRunExcept (fromVector dev shp value
:: Either (Coproduct '[OutOfMemory, IncompatibleSize]) (Tensor d s a))
-- | Converts a tensor to a storable vector. Runs in O(n) time.
toVector :: forall d s a
. (Device d, Shape s, TensorScalar a) => Tensor d s a -> SVector a
toVector t = unsafePerformIO $ do
res <- SMV.new $ size $ shape t
mt <- unsafeThaw t
SMV.unsafeWith res $ \resptr -> do
MT.withDevicePtr mt $ \mtptr -> do
runDeviceM (device t) $ CUDA.peekArray (size $ shape t) mtptr resptr
SV.unsafeFreeze res
-- | Concatenates two 1-dimensional tensors. Inverse of tsplit. Runs in O(n+m) time.
tconcat :: forall t d m a
. (Device d, TensorScalar a, MonadError t m, Variant t OutOfMemory)
=> Tensor d (Dim 1) a -> Tensor d (Dim 1) a -> m (Tensor d (Dim 1) a)
tconcat t1 t2 = do
embedExcept $ unsafePerformIO $ runExceptT $ do
let t1sz = size $ shape t1
t2sz = size $ shape t2
out <- MT.emptyTensor (device t1) $ (t1sz + t2sz) :. Z
mt1 <- unsafeThaw t1
mt2 <- unsafeThaw t2
liftIO $ MT.withDevicePtr mt1 $ \t1ptr -> do
MT.withDevicePtr mt2 $ \t2ptr -> do
MT.withDevicePtr out $ \outptr -> runDeviceM (device t1) $ do
CUDA.copyArray t1sz t1ptr outptr
CUDA.copyArray t2sz t2ptr
(CUDA.DevicePtr
$ plusPtr
(CUDA.useDevicePtr outptr)
(mySizeOf (Proxy :: Proxy a) * fromIntegral t1sz))
unsafeFreeze out
-- | Unsafe version of @'tconcat'@, throws imprecise exceptions.
tconcat' :: forall d a
. (Device d, TensorScalar a)
=> Tensor d (Dim 1) a -> Tensor d (Dim 1) a -> Tensor d (Dim 1) a
tconcat' t1 t2 =
unsafeRunExcept (tconcat t1 t2 :: Either OutOfMemory (Tensor d (Dim 1) a))
-- | Splits a 1-dimensional tensor into 2 parts. Inverse of tconcat. Runs in O(n+m) time.
tsplitAt :: forall t d m a
. (Device d, TensorScalar a, MonadError t m, Variant t OutOfMemory,
Variant t IncompatibleSize)
=> Int -> Tensor d (Dim 1) a -> m (Tensor d (Dim 1) a, Tensor d (Dim 1) a)
tsplitAt t1sz t = do
let t2sz = size (shape t) - t1sz
when (t2sz < 0) $ throwVariant $ incompatibleSize $
"Couldn't split the a vector of size " ++ show (size (shape t)) ++ " at point " ++ show t1sz ++ " : the input vector is too small."
embedExcept $ unsafePerformIO $ runExceptT $ do
mt1 <- MT.emptyTensor (device t) $ t1sz :. Z
mt2 <- MT.emptyTensor (device t) $ t2sz :. Z
mt <- unsafeThaw t
liftIO $ MT.withDevicePtr mt1 $ \t1ptr -> do
MT.withDevicePtr mt2 $ \t2ptr -> do
MT.withDevicePtr mt $ \tptr -> runDeviceM (device t) $ do
CUDA.copyArray t1sz tptr t1ptr
let offsetPtr =
CUDA.DevicePtr
$ plusPtr
(CUDA.useDevicePtr tptr)
(mySizeOf (Proxy :: Proxy a) * fromIntegral t1sz)
CUDA.copyArray t2sz offsetPtr t2ptr
pure (,) <*> unsafeFreeze mt1 <*> unsafeFreeze mt2
-- | Unsafe version of @'tSplit'@, throws imprecise exceptions.
tsplitAt' :: forall d a
. (Device d, TensorScalar a)
=> Int -> Tensor d (Dim 1) a -> (Tensor d (Dim 1) a, Tensor d (Dim 1) a)
tsplitAt' t1sz t = unsafeRunExcept (tsplitAt t1sz t :: Either (Coproduct '[OutOfMemory,IncompatibleSize]) (Tensor d (Dim 1) a, Tensor d (Dim 1) a))
-- | Flattens a tensor into a 1-dimensional vector.
flatten :: forall s d a
. (Shape s, TensorScalar a)
=> Tensor d s a -> Tensor d (Dim 1) a
flatten t =
case reshape (size (shape t) :. Z) t
:: Either IncompatibleSize (Tensor d (Dim 1) a) of
Left err -> error $ "Couldn't flatten a tensor. This shouldn't happen.\n" ++ show err
Right res -> res
-- | Type-safe broadcasting. See the documentation for @'broadcastable'@ for the
-- broadcasting rules. This throws an @'IncompatibleShape'@ exception when the shape
-- of the tensor is not broadcastable to the desired shape. Note that, unlike numpy,
-- this currently makes a full copy of the tensor in memory.
broadcast :: forall d t s1 s2 m a
. (Device d, Shape s1, Shape s2, TensorScalar a, MonadError t m,
Variant t IncompatibleShape, Variant t OutOfMemory)
=> s2 -> Tensor d s1 a -> m (Tensor d s2 a)
broadcast outshp inp = do
when (not $ broadcastable (shape inp) outshp) $ throwVariant $ incompatibleShape $
"Couldn't broadcast shape " ++ show (shape inp) ++ " to shape " ++ show outshp
let inp_shape =
fmap fromIntegral
$ take (nbdim outshp - nbdim (shape inp)) (repeat 1)
++ dimensions (shape inp)
out_shape = fmap fromIntegral $ dimensions outshp
inp_size = fromIntegral $ size $ shape inp
out_size = fromIntegral $ size outshp
out_nbdim = fromIntegral $ nbdim outshp
-- We avoid copying when the size doesn't change.
if out_size == inp_size
then return $ reshape' outshp inp
else embedExcept $ unsafePerformIO $ runExceptT $ do
minp <- unsafeThaw inp
mout <- MT.emptyTensor (device inp) outshp
liftIO $ MT.withDevicePtr minp $ \inpptr -> do
MT.withDevicePtr mout $ \outptr -> runDeviceM (device inp) $ do
inp_shapeptr <- CUDA.newListArray inp_shape
out_shapeptr <- CUDA.newListArray out_shape
broadcast_copy out_nbdim out_size inpptr inp_shapeptr outptr out_shapeptr
CUDA.free inp_shapeptr
CUDA.free out_shapeptr
unsafeFreeze mout
-- | Unsafe version of @'broadcast'@, throws imprecise exceptions.
broadcast' :: forall s1 s2 d a
. (Device d, Shape s1, Shape s2, TensorScalar a)
=> s2 -> Tensor d s1 a -> Tensor d s2 a
broadcast' outshp inp =
unsafeRunExcept (broadcast outshp inp
:: Either (Coproduct '[IncompatibleShape, OutOfMemory]) (Tensor d s2 a))
-- | Broadcast two tensors to the same shape, if either of them is broadcastable to
-- to the other. Throws an @'IncompatibleShape'@ exception otherwise.
bin_broadcast :: forall s d t m a
. (Device d, Shape s, TensorScalar a, MonadError t m,
Variant t IncompatibleShape, Variant t OutOfMemory)
=> Tensor d s a -> Tensor d s a -> m (Tensor d s a, Tensor d s a)
bin_broadcast t1 t2 =
case (broadcast (shape t2) t1, broadcast (shape t1) t2) of
(Left err1, Left err2) -> throwError err1 >> throwError err2
(Right t1', Left err) -> return (t1', t2)
(Left err, Right t2') -> return (t1, t2')
_ -> return (t1, t2)
-- | Unsafe version of @'bin_broadcast'@, throws imprecise exceptions.
bin_broadcast' :: forall d s a
. (Device d, Shape s, TensorScalar a)
=> Tensor d s a -> Tensor d s a -> (Tensor d s a, Tensor d s a)
bin_broadcast' t1 t2 =
unsafeRunExcept (bin_broadcast t1 t2
:: Either (Coproduct '[IncompatibleShape, OutOfMemory]) (Tensor d s a, Tensor d s a))
instance forall d s a
. (ValidUniqueDevice d, IsFixed s, TensorScalar a)
=> Num (Tensor d s a) where
t1 + t2 = let
eres = unsafePerformIO $ runExceptT $ do
t1' <- unsafeThaw t1
t2' <- unsafeThaw t2
t3' <- MT.copy (device t1) t2'
liftIO $ MT.withDevicePtr t1' $ \t1ptr -> do
MT.withDevicePtr t3' $ \t3ptr -> runDeviceM (device t1) $ do
MT.rawAdd t1ptr t3ptr
$ fromIntegral $ size $ shape t1
unsafeFreeze t3' in unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
t1 * t2 = let
eres = unsafePerformIO $ runExceptT $ do
t1' <- unsafeThaw t1
t2' <- unsafeThaw t2
t3' <- MT.copy (device t1) t2'
liftIO $ MT.withDevicePtr t1' $ \t1ptr -> do
MT.withDevicePtr t3' $ \t3ptr -> runDeviceM (device t1) $ do
MT.rawMul t1ptr t3ptr
$ fromIntegral $ size $ shape t1
unsafeFreeze t3' in unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
t1 - t2 = let
eres = unsafePerformIO $ runExceptT $ do
t1' <- unsafeThaw t1
t2' <- unsafeThaw t2
t3' <- MT.copy (device t1) t2'
liftIO $ MT.withDevicePtr t1' $ \t1ptr -> do
MT.withDevicePtr t3' $ \t3ptr -> runDeviceM (device t1) $ do
MT.rawSubtract t1ptr t3ptr
$ fromIntegral $ size $ shape t1
unsafeFreeze t3' in unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
negate t = let eres = unsafePerformIO $ runExceptT $ do
res <- unsafeThaw t >>= MT.copy (device t)
liftIO $ MT.withDevicePtr res $ \resptr -> runDeviceM (device t) $ do
MT.rawNegate resptr
$ fromIntegral $ size $ shape t
unsafeFreeze res in
unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
signum t = let eres = unsafePerformIO $ runExceptT $ do
res <- unsafeThaw t >>= MT.copy (device t)
liftIO $ MT.withDevicePtr res $ \resptr -> runDeviceM (device t) $ do
MT.rawSignum resptr
$ fromIntegral $ size $ shape t
unsafeFreeze res in
unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
fromInteger i = fromInteger i *^ ones' validUniqueDevice scalarShape
instance forall d s a
. (ValidUniqueDevice d, IsFixed s, TensorScalar a)
=> Fractional (Tensor d s a) where
recip x = let eres = unsafePerformIO $ runExceptT $ do
res <- unsafeThaw x >>= MT.copy (device x)
liftIO $ MT.inv res
unsafeFreeze res in
unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
fromRational r = fromInteger (numerator r) / fromInteger (denominator r)
-- | Computes the elementwise maximum of 2 tensors.
elementwiseMax :: forall d s a t m
. (ValidUniqueDevice d, IsFixed s, TensorScalar a, MonadError t m,
Variant t OutOfMemory, Variant t IncompatibleShape)
=> Tensor d s a -> Tensor d s a
-> m (Tensor d s a)
elementwiseMax _x _y = do
(x,y) <- bin_broadcast _x _y
embedExcept $ unsafePerformIO $ runExceptT $ do
mx <- unsafeThaw x
my <- unsafeThaw y >>= MT.copy (device x)
liftIO $ MT.withDevicePtr mx $ \pmx -> do
MT.withDevicePtr my $ \pmy -> runDeviceM (device x) $ do
MT.rawMax pmx pmy (fromIntegral $ size $ shape x)
unsafeFreeze my
fromRaw :: forall d s a
. (Device d, IsFixed s, TensorScalar a)
=> (CUDA.DevicePtr a -> CSize -> DeviceM d ())
-> Tensor d s a -> Tensor d s a
fromRaw action x =
let eres = unsafePerformIO $ runExceptT $ do
mx <- unsafeThaw x
res <- MT.copy (device x) mx
liftIO $ MT.withDevicePtr res $ \resptr -> runDeviceM (device x) $ do
action resptr $ fromIntegral $ size $ shape x
unsafeFreeze res
in unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
instance forall d s a
. (ValidUniqueDevice d, IsFixed s, TensorScalar a)
=> Floating (Tensor d s a) where
pi = pi *^ ones' validUniqueDevice scalarShape
exp = fromRaw MT.rawExp
log = fromRaw MT.rawLog
sqrt = fromRaw MT.rawSqrt
sin = fromRaw MT.rawSin
cos = fromRaw MT.rawCos
tan = fromRaw MT.rawTan
asin = fromRaw MT.rawAsin
acos = fromRaw MT.rawAcos
atan = fromRaw MT.rawAtan
sinh = fromRaw MT.rawSinh
cosh = fromRaw MT.rawCosh
tanh = fromRaw MT.rawTanh
asinh = fromRaw MT.rawAsinh
acosh = fromRaw MT.rawAcosh
atanh = fromRaw MT.rawAtanh
x**y = let
eres = unsafePerformIO $ runExceptT $ do
mx <- unsafeThaw x
my <- unsafeThaw y >>= MT.copy (device x)
liftIO $ MT.withDevicePtr mx $ \pmx -> do
MT.withDevicePtr my $ \pmy -> runDeviceM (device x) $ do
MT.rawPow pmx pmy
$ fromIntegral $ size $ shape x
unsafeFreeze my
in unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
-- Vector space instance for Tensors.
instance (ValidUniqueDevice d, IsFixed s, TensorScalar a)
=> AdditiveGroup (Tensor d s a) where
zeroV = fromInteger 0
t1 ^+^ t2 = t1 + t2
negateV t = negate t
instance forall d s a
. (ValidUniqueDevice d, IsFixed s, TensorScalar a)
=> VectorSpace (Tensor d s a) where
type Scalar (Tensor d s a) = a
x *^ t = let eres = unsafePerformIO $ runExceptT $ do
res <- unsafeThaw t >>= MT.copy (device t)
liftIO $ MT.withDevicePtr res $ \resptr -> runDeviceM (device t) $ do
MT.rawScale x resptr
$ fromIntegral $ size $ shape t
unsafeFreeze res
in unsafeRunExcept (eres :: Either OutOfMemory (Tensor d s a))
instance (ValidUniqueDevice d, IsFixed s, TensorScalar a)
=> InnerSpace (Tensor d s a) where
t1 <.> t2 = foldr (+) 0 $ fmap (\(x1,x2) -> x1 * x2) $ zip (tensorToList t1) (tensorToList t2)
|
alexisVallet/deep-banana
|
src/DeepBanana/Tensor.hs
|
bsd-3-clause
| 24,605 | 19 | 32 | 6,474 | 7,897 | 3,937 | 3,960 | -1 | -1 |
module OpenCV.Internal.C.PlacementNew ( PlacementNew(..) ) where
import "base" Foreign.Ptr ( Ptr )
--------------------------------------------------------------------------------
-- | Copy source to destination using C++'s placement new feature
class PlacementNew a where
-- | Copy source to destination using C++'s placement new feature
--
-- This method is intended for types that are proxies for actual
-- types in C++.
--
-- > new(dst) CType(*src)
--
-- The copy should be performed by constructing a new object in
-- the memory pointed to by @dst@. The new object is initialised
-- using the value of @src@. This design allow underlying
-- structures to be shared depending on the implementation of
-- @CType@.
placementNew
:: Ptr a -- ^ Source
-> Ptr a -- ^ Destination
-> IO ()
placementDelete
:: Ptr a
-> IO ()
|
Cortlandd/haskell-opencv
|
src/OpenCV/Internal/C/PlacementNew.hs
|
bsd-3-clause
| 920 | 0 | 10 | 231 | 94 | 58 | 36 | -1 | -1 |
module Chat.Bot.Hangman where
import Chat.Bot.Answer.Hangman
import Chat.Bot.Misc.Hangman
import Chat.Data
{-
LEVEL: Medium
USAGE: /hangman [guess]
Guess a number of characters, or nothing to print out the current state.
EXAMPLE:
> /hangman
____ ____ []
> /hangman e
____ ____ [e]
> /hangman z
__zz __zz [e]
> /hangman a
__zz __zz [ae]
> /hangman b
__zz b_zz [ae]
-}
-- $setup
-- >>> let word = "fizz buzz"
-- |
-- >>> hangmanGuess 'u' word
-- HangmanRight 'u'
-- >>> hangmanGuess 'o' word
-- HangmanWrong 'o'
--
-- HINTS:
-- elem :: Char -> String -> Bool
--
hangmanGuess :: Char -> String -> HangmanGuess
hangmanGuess char word=
notImplemented "Hangman.hangmanGuess" (hangmanGuessAnswer char word)
-- |
-- >>> hangmanGuesses word "z"
-- [HangmanRight 'z']
-- >>> hangmanGuesses word "xz"
-- [HangmanWrong 'x',HangmanRight 'z']
--
-- HINTS:
-- map :: (Char -> HangmanGuess) -> [Char] -> [HangmanGuess]
--
hangmanGuesses :: String -> [Char] -> [HangmanGuess]
hangmanGuesses word guesses =
notImplemented "Hangman.hangmanGuesses" (hangmanGuessesAnswer word guesses)
-- |
-- >>> hangmanHasWon word (hangmanGuesses word "z")
-- False
-- >>> hangmanHasWon word (hangmanGuesses word "ibfz")
-- False
-- >>> hangmanHasWon word (hangmanGuesses word "uibfz")
-- True
--
-- HINTS:
-- elem :: Char -> String -> Bool
-- map :: (HangmanGuess -> Char) -> [HangmanGuess] -> [Char]
-- filter :: (Char -> Bool) -> String -> String
hangmanHasWon :: String -> [HangmanGuess] -> Bool
hangmanHasWon word guesses =
notImplemented "Hangman.hangmanHasWon" (hangmanHasWonAnswer word guesses)
-- |
-- >>> hangmanWrongGuesses (hangmanGuesses word "z")
-- ""
-- >>> hangmanWrongGuesses (hangmanGuesses word "uxibmfpz")
-- "xmp"
--
-- HINTS:
-- filter :: (HangmanGuess -> Bool) -> [HangmanGuess] -> [HangmanGuess]
-- map :: (HangmanGuess -> Char) -> [HangmanGuess] -> [Char]
hangmanWrongGuesses :: [HangmanGuess] -> [Char]
hangmanWrongGuesses guesses =
notImplemented "Hangman.hangmanWrongGuesses" (hangmanWrongGuessesAnswer guesses)
-- |
-- >>> hangmanRender word (hangmanGuesses word "z")
-- "__zz __zz []"
-- >>> hangmanRender word (hangmanGuesses word "xiuz")
-- "_izz _uzz [x]"
-- >>> hangmanRender word (hangmanGuesses word "bxiuz")
-- "_izz buzz [x]"
--
-- HINTS:
-- elem :: Char -> String -> Bool
-- map :: (Char -> Char) -> String -> String
--
hangmanRender :: String -> [HangmanGuess] -> String
hangmanRender word guesses =
notImplemented "Hangman.hangmanRender" (hangmanRenderAnswer word guesses)
-- See Misc/Hangman.hs
{-
data HangmanGuess =
HangmanRight Char
| HangmanWrong Char
deriving (Eq, Show)
-}
hangmanWords :: [String]
hangmanWords = [
"hello world"
, "fizz buzz"
, "women who code"
]
|
charleso/haskell-in-haste
|
src/Chat/Bot/Hangman.hs
|
bsd-3-clause
| 2,816 | 0 | 7 | 534 | 294 | 186 | 108 | 24 | 1 |
{-# LANGUAGE TypeFamilies, EmptyDataDecls, ScopedTypeVariables, TypeOperators, UndecidableInstances #-}
import Data.Monoid
type family ftag :% a :: *
data Parametric0Tag (a :: *)
type instance Parametric0Tag a :% () = a
data Parametric1Tag (f :: * -> *)
type instance Parametric1Tag f :% a = f a
data Parametric3Tag (f :: * -> * -> * -> *)
type instance Parametric3Tag f :% (a, b, c) = f a b c
type Force a = a :% ()
newtype VarF var term value = AVar { unVar :: String }
data TermF var term value
= Var (Force var)
| App (Force term) (Force var)
| Value (Force value)
| Add (Force term) (Force term)
data ValueF var term value
= Literal Int
| Lambda String (Force term)
data SyntaxAlgebra var term value = SyntaxAlgebra {
varAlgebra :: VarF var term value -> Force var,
termAlgebra :: TermF var term value -> Force term,
valueAlgebra :: ValueF var term value -> Force value
}
type Fix3_1 f g h = f :% (FixTag3_1 f g h, FixTag3_2 f g h, FixTag3_3 f g h) -- Using :% here requires UndecidableInstances -- fair enough!
type Fix3_2 f g h = g :% (FixTag3_1 f g h, FixTag3_2 f g h, FixTag3_3 f g h)
type Fix3_3 f g h = h :% (FixTag3_1 f g h, FixTag3_2 f g h, FixTag3_3 f g h)
data FixTag3_1 f g h
data FixTag3_2 f g h
data FixTag3_3 f g h
type instance FixTag3_1 f g h :% () = Fix3_1 f g h
type instance FixTag3_2 f g h :% () = Fix3_2 f g h
type instance FixTag3_3 f g h :% () = Fix3_3 f g h
type Var = Fix3_1 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF)
type Term = Fix3_2 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF)
type Value = Fix3_3 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF)
-- TODO: try doing this as a functor category?
fmap3VarF :: (Force var -> Force var')
-> (Force term -> Force term')
-> (Force value -> Force value')
-> VarF var term value
-> VarF var' term' value'
fmap3VarF _var _term _value x = case x of
AVar x -> AVar x
fmap3TermF :: (Force var -> Force var')
-> (Force term -> Force term')
-> (Force value -> Force value')
-> TermF var term value
-> TermF var' term' value'
fmap3TermF var term value e = case e of
Var x -> Var (var x)
App e x -> App (term e) (var x)
Value v -> Value (value v)
Add e1 e2 -> Add (term e1) (term e2)
fmap3ValueF :: (Force var -> Force var')
-> (Force term -> Force term')
-> (Force value -> Force value')
-> ValueF var term value
-> ValueF var' term' value'
fmap3ValueF _var term _value v = case v of
Literal l -> Literal l
Lambda x e -> Lambda x (term e)
foldMap3VarF :: Monoid m
=> (Force var -> m)
-> (Force term -> m)
-> (Force value -> m)
-> VarF var term value
-> m
foldMap3VarF _var _term _value x = case x of
AVar _ -> mempty
foldMap3TermF :: Monoid m
=> (Force var -> m)
-> (Force term -> m)
-> (Force value -> m)
-> TermF var term value
-> m
foldMap3TermF var term value e = case e of
Var x -> var x
App e x -> term e `mappend` var x
Value v -> value v
Add e1 e2 -> term e1 `mappend` term e2
foldMap3ValueF :: Monoid m
=> (Force var -> m)
-> (Force term -> m)
-> (Force value -> m)
-> ValueF var term value
-> m
foldMap3ValueF _var term _value v = case v of
Literal _ -> mempty
Lambda _ e -> term e
example :: Value
example = Lambda "x" $ Add (Value (Literal 1)) (Var (AVar "x")) `App` AVar "x"
-- fixAlgebra :: SyntaxAlgebra var term value -> SyntaxAlgebra (Fix3_1 var term value) (Fix3_2 var term value) (Fix3_3 var term value)
-- fixAlgebra alg = undefined
applyAlgebra :: forall var term value.
SyntaxAlgebra var term value
-> Term -> Force term
-- -> SyntaxAlgebra (FixTag3_1 VarF TermF ValueF) (FixTag3_2 VarF TermF ValueF) (FixTag3_3 VarF TermF ValueF)
applyAlgebra alg = {- SyntaxAlgebra var term value -- -} term
where
var :: Var -> Force var
var = varAlgebra alg . fmap3VarF var term value
term :: Term -> Force term
term = termAlgebra alg . fmap3TermF var term value
value :: Value -> Force value
value = valueAlgebra alg . fmap3ValueF var term value
applyHomAlgebra :: SyntaxAlgebra (Parametric0Tag Var) (Parametric0Tag Term) (Parametric0Tag Value)
-> Term -> Term
applyHomAlgebra alg = term
where
var :: Var -> Var
var = varAlgebra alg . fmap3VarF var term value
term :: Term -> Term
term = termAlgebra alg . fmap3TermF var term value
value :: Value -> Value
value = valueAlgebra alg . fmap3ValueF var term value
data IdTag
type instance IdTag :% a = a
data ComposeTag f g
type instance ComposeTag f g :% a = f :% (g :% a)
data Annotated ann a = Ann { annotation :: ann, annee :: a }
instance Functor (Annotated ann) where
fmap f (Ann ann x) = Ann ann (f x)
type AnnVar annftag = Fix3_1 (ComposeTag annftag (Parametric3Tag VarF)) (ComposeTag annftag (Parametric3Tag TermF)) (ComposeTag annftag (Parametric3Tag ValueF))
type AnnTerm annftag = Fix3_2 (ComposeTag annftag (Parametric3Tag VarF)) (ComposeTag annftag (Parametric3Tag TermF)) (ComposeTag annftag (Parametric3Tag ValueF))
type AnnValue annftag = Fix3_3 (ComposeTag annftag (Parametric3Tag VarF)) (ComposeTag annftag (Parametric3Tag TermF)) (ComposeTag annftag (Parametric3Tag ValueF))
annotateWithAlgebra :: forall ann.
SyntaxAlgebra ann ann ann
-> Term -> AnnTerm (Parametric1Tag (Annotated (Force ann)))
annotateWithAlgebra alg = term
where
foo :: VarF ann ann ann -> Force ann
foo = varAlgebra alg
-- Var == Fix3_1 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF)
-- == Parametric3Tag VarF :% (FixTag3_1 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF),
-- FixTag3_2 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF),
-- FixTag3_3 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF))
-- == VarF (FixTag3_1 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF))
-- (FixTag3_2 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF))
-- (FixTag3_3 (Parametric3Tag VarF) (Parametric3Tag TermF) (Parametric3Tag ValueF))
var :: Var -> AnnVar (Parametric1Tag (Annotated (Force ann)))
var x = Ann (varAlgebra alg (fmap3VarF annotation annotation annotation x')) x'
where x' = fmap3VarF var term value x
term :: Term -> AnnTerm (Parametric1Tag (Annotated (Force ann)))
term e = Ann (termAlgebra alg (fmap3TermF annotation annotation annotation e')) e'
where e' = fmap3TermF var term value e
value :: Value -> AnnValue (Parametric1Tag (Annotated (Force ann)))
value v = Ann (valueAlgebra alg (fmap3ValueF annotation annotation annotation v')) v'
where v' = fmap3ValueF var term value v
instance Monoid Int where
mempty = 0
mappend = (+)
main = do
print result
print (annotation example_annotated)
where
result = applyAlgebra alg (Value example)
example_annotated = annotateWithAlgebra alg (Value example)
alg :: SyntaxAlgebra (Parametric0Tag Int) (Parametric0Tag Int) (Parametric0Tag Int)
alg = SyntaxAlgebra var term value
var x = 1 + foldMap3VarF id id id x
term e = 1 + foldMap3TermF id id id e
value v = 1 + foldMap3ValueF id id id v
|
batterseapower/haskell-kata
|
Generics2.hs
|
bsd-3-clause
| 7,763 | 32 | 14 | 2,116 | 2,512 | 1,293 | 1,219 | -1 | -1 |
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module Feldspar.Compiler.Frontend.CommandLine.API.Options where
import qualified Feldspar.Compiler.Backend.C.Options as CompilerCoreOptions
import qualified Feldspar.Compiler.Compiler as CompilerCore
import qualified Feldspar.Compiler.Frontend.CommandLine.API.Library as StandaloneLib
import Feldspar.Compiler.Backend.C.Platforms
import Data.List
import Data.Char
import Data.Maybe (fromMaybe)
import System.Console.GetOpt
import System.Exit
import System.IO
availablePlatformsStrRep :: String
availablePlatformsStrRep = StandaloneLib.formatStringList $
map (StandaloneLib.upperFirst . CompilerCoreOptions.name) availablePlatforms
data StandaloneMode = SingleFunction String | MultiFunction
data FrontendOptions = FrontendOptions
{ optStandaloneMode :: StandaloneMode
, optOutputFileName :: Maybe String
, optCompilerMode :: CompilerCoreOptions.Options
}
-- | Default options
startOptions :: FrontendOptions
startOptions = FrontendOptions
{ optStandaloneMode = MultiFunction
, optOutputFileName = Nothing
, optCompilerMode = CompilerCore.defaultOptions
}
helpHeader :: String
helpHeader = "Standalone Feldspar Compiler\nUsage: feldspar [options] inputfile\n" ++
"Notes: \n" ++
" * When no output file name is specified, the input file's name with .c extension is used\n" ++
" * The inputfile parameter is always needed, even in single-function mode\n" ++
"\nAvailable options: \n"
-- | Option descriptions for getOpt
optionDescriptors :: [ OptDescr (FrontendOptions -> IO FrontendOptions) ]
optionDescriptors =
[ Option "f" ["singlefunction"]
(ReqArg
(\arg opt -> return opt { optStandaloneMode = SingleFunction arg })
"FUNCTION")
"Enables single-function compilation"
, Option "o" ["output"]
(ReqArg
(\arg opt -> return opt { optOutputFileName = Just arg })
"outputfile")
"Overrides the file names for the generated output code"
, Option "p" ["platform"]
(ReqArg
(\arg opt -> return opt { optCompilerMode = (optCompilerMode opt)
{ CompilerCoreOptions.platform = decodePlatform arg } })
"<platform>")
("Overrides the target platform " ++ availablePlatformsStrRep)
, Option "h" ["help"]
(NoArg
(\_ -> do
--prg <- getProgName
hPutStrLn stderr (usageInfo helpHeader optionDescriptors)
exitSuccess))
"Show this help message"
]
-- ==============================================================================
-- == Option Decoders
-- ==============================================================================
findPlatformByName :: String -> Maybe CompilerCoreOptions.Platform
findPlatformByName platformName = -- Finds a platform by name using case-insensitive comparison
find (\platform -> map toLower platformName == map toLower (CompilerCoreOptions.name platform))
availablePlatforms
decodePlatform :: String -> CompilerCoreOptions.Platform
decodePlatform s = fromMaybe (error $ "Invalid platform specified. Valid platforms are: " ++ availablePlatformsStrRep)
$ findPlatformByName s
parseInt :: String -> String -> Int
parseInt arg message = case reads arg of
[(x, "")] -> x
_ -> error message
|
emwap/feldspar-compiler
|
src/Feldspar/Compiler/Frontend/CommandLine/API/Options.hs
|
bsd-3-clause
| 5,143 | 0 | 16 | 1,184 | 643 | 375 | 268 | 65 | 2 |
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}
import Control.Monad
import qualified Data.ByteString as B
import Data.Csv.Incremental
import System.Exit
import System.IO
main :: IO ()
main = withFile "salaries.csv" ReadMode $ \ csvFile -> do
let loop !_ (Fail _ errMsg) = putStrLn errMsg >> exitFailure
loop acc (Partial k) = loop acc =<< feed k
loop acc (Some rs k) = loop (acc + sumSalaries rs) =<< feed k
loop acc (Done rs) = putStrLn $ "Total salaries: " ++
show (sumSalaries rs + acc)
feed k = do
isEof <- hIsEOF csvFile
if isEof
then return $ k B.empty
else k `fmap` B.hGetSome csvFile 4096
loop 0 (decode NoHeader)
where
sumSalaries rs = sum [salary | Right (_ :: String, salary :: Int) <- rs]
|
mikeizbicki/cassava
|
examples/IncrementalIndexedBasedDecode.hs
|
bsd-3-clause
| 855 | 0 | 17 | 274 | 298 | 148 | 150 | 20 | 5 |
{-# LANGUAGE TemplateHaskell #-}
module Drawer (Drawer(Drawer),
handleDrawerEvent,
drawDrawer) where
import Control.Lens
import Brick.Widgets.Core
import Brick.Widgets.Border
import qualified Brick.Types as T
import Window
data Drawer =
Drawer { _value :: FilePath
, _options :: [String]
, _index :: Integer
, _scroll :: Integer
}
makeLenses ''Drawer
handleDrawerEvent state = state
drawDrawer n (Just drawer) focusRing =
showCursor DrawerID (T.Location (length (drawer^.value), 0)) $
str (drawer^.value)
|
JacksonGariety/earthmacs-hs
|
src/Drawer.hs
|
bsd-3-clause
| 582 | 0 | 12 | 142 | 161 | 94 | 67 | 22 | 1 |
-- http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_D
-- Matrix Multiplication
-- input:
-- 3 2 3
-- 1 2
-- 0 3
-- 4 5
-- 1 2 1
-- 0 3 2
-- output:
-- 1 8 5
-- 0 9 6
-- 4 23 14
import Control.Applicative ((<$>), (<*>))
import qualified Control.Monad as Monad (replicateM)
import qualified Data.List as List (transpose)
import qualified Data.List.Split as Split (chunksOf)
type Row = [Int]
type Matrix = [Row]
main = do
[n,m,l] <- getLine'
a <- Monad.replicateM n getLine'
b <- Monad.replicateM m getLine'
let result = toMatrix l $ dotProduct <$> a <*> List.transpose b
mapM_ (putStrLn . printFormat) result
getLine' :: IO [Int]
getLine' = map (read :: String -> Int) . words <$> getLine
printFormat :: Row -> String
printFormat xs = unwords $ show <$> xs
toMatrix :: Int -> [Int] -> Matrix
toMatrix n xs = Split.chunksOf n xs
dotProduct :: Row -> Row -> Int
dotProduct xs ys = sum $ zipWith (*) xs ys
|
ku00/aoj-haskell
|
src/ITP1_7_D.hs
|
bsd-3-clause
| 945 | 0 | 13 | 194 | 313 | 178 | 135 | 20 | 1 |
{-# LANGUAGE LambdaCase, Rank2Types, TypeOperators, TypeSynonymInstances, FlexibleInstances #-}
-- ref.) https://jtobin.io/promorphisms-pre-post
module Promorphism where
import Prelude hiding (sum, Functor, fmap, map)
import Data.Bool (bool)
import FixPrime
data ListF a x = Nil | Cons a x deriving Show
type List a = Fix (ListF a)
nil :: List a
nil = In Nil
cons :: a -> List a -> List a
cons x xs = In (Cons x xs)
instance Show a => Show (List a) where
show x = "(" ++ show (out x) ++ ")"
instance Bifunctor ListF where
bimap (f, g) Nil = Nil
bimap (f, g) (Cons a x) = Cons (f a) (g x)
instance Functor (ListF a) where
fmap f = bimap (id, f)
genList :: Integer -> List Integer
genList = ana psi
where
psi n = if n <= 0 then Nil else Cons n (n - 1)
idAlg :: ListF a (List a) -> List a
idAlg = \case
Cons h t -> cons h t
Nil -> nil
sumAlg :: Num a => ListF a a -> a
sumAlg = \case
Cons h t -> h + t
Nil -> 0
lenAlg :: ListF a Int -> Int
lenAlg = \case
Cons h t -> 1 + t
Nil -> 0
sum :: Num a => List a -> a
sum = cata sumAlg
len :: List a -> Int
len = cata lenAlg
smallSumAlg :: (Ord a, Num a) => ListF a a -> a
smallSumAlg = \case
Cons h t -> if h <= 10 then h + t else t
Nil -> 0
smallLenAlg :: (Ord a, Num a) => ListF a a -> a
smallLenAlg = \case
Cons h t -> if h <= 10 then 1 + t else t
Nil -> 0
-- natural transform. Cons 9 :~> Cons 9, Cons 10 :~> Cons 10, Cons 11 :~> Nil and so on.
small :: (Ord a, Num a) => ListF a :~> ListF a
small = \case
Cons h t | h <= 10 -> Cons h t
| otherwise -> Nil
Nil -> Nil
takeTo :: (a -> Bool) -> ListF a :~> ListF a
takeTo pred = \case
Cons h t | pred h -> Cons h t
| otherwise -> Nil
Nil -> Nil
-- prepro double sumAlg $ cons 1 nil => 1
-- 1 + (0 * 2) => 1
-- prepro double sumAlg $ cons 1 (cons 2 nil) => 5
-- 1 + (2 * 2) + (0 * 2 * 2) => 5
-- prepro double sumAlg $ cons 1 (cons 2 (cons 3 nil)) => 17
-- 1 + (2 * 2) + (3 * 2 * 2) + (0 * 2 * 2 * 2) => 17
--
-- cata (In . double) $ cons 2 nil => Cons 4 Nil
-- cata (In . double) $ cons 2 (cons 3 nil) => Cons 4 (Cons 6 Nil)
-- cata (In . double) $ cons 2 (cons 3 (cons 4 nil)) => Cons 4 (Cons 6 (Cons 8 Nil))
--
--
-- ψx <= double
-- X F(X) ---------> G(X)
-- | | |
-- f| F(f)| |G(f)
-- | | |
-- v v v
-- Y F(Y) ---------> G(Y)
-- ψy <= double
--
double :: Num a => ListF a x -> ListF a x
double = bimap ((*2),id)
smallSum :: (Ord a, Num a) => List a -> a
smallSum = prepro small sumAlg
smallLen :: (Ord a, Num a) => List a -> Int
smallLen = prepro small lenAlg
streamCoalg :: Enum a => a -> ListF a a
streamCoalg n = Cons n (succ n)
smallStream :: (Ord a, Num a, Enum a) => a -> List a
smallStream = postpro small streamCoalg
range :: (Enum a, Ord a, Num a) => a -> a -> List a
range from to = postpro (takeTo (<(to+1))) streamCoalg from
|
cutsea110/aop
|
src/Promorphism.hs
|
bsd-3-clause
| 3,034 | 0 | 11 | 961 | 1,100 | 571 | 529 | 67 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Hakit.Db (
Db(..),
Specials(..),
specials,
docToSpecials,
toDocStyleSort,
-- * Oid/dbRef
dbRef,
oid,
idToStr,
idOf,
idOf',
collOf,
collOf',
dbRefToStr,
strToDbRef,
strToId,
isDbRef,
isId,
) where
import Hakit
import qualified Data.List as List
import qualified Data.Function as F
import qualified Data.Text as T
import qualified Data.Map as M
import qualified Data.Ord as O
import qualified Safe
{--------------------------------------------------------------------
These functions are useful when you implement the Db class.
--------------------------------------------------------------------}
-- | find, findOne and iterate Selectors may contain the following fields which have special meaning:
specialKeys :: M.Map T.Text ()
specialKeys = let sp = ["sort", "limit", "skip", "page", "location"] in
M.fromList $ map (\x -> (x, ())) sp
-- | Extracts the special fields out of a Document. First is the specials.
specials :: Document -> (Document, Document)
specials doc = M.partitionWithKey (\k _ -> M.member k specialKeys) doc
-- |
data Specials = Specials {
sort :: [T.Text], -- Example: ["x", "-y"]
limit, skip, page :: Integer,
loc :: Document -- Example: ["server" .- "main", "db" .- "testDb", "coll" .- "testCollection"]
}
-- ["x", "-y"] -> ["x" .- 1, "y" .- (-1)]
toDocStyleSort :: [T.Text] -> Document
toDocStyleSort a =
let f x = if T.isInfixOf "-" x
then (T.tail x) .- (-1::Integer)
else x .- (1::Integer)
in M.fromList $ map f a
docToSpecials doc =
let spec = fst (specials doc) -- Just to decrease algorightmic complexity.
sort = dvToStrList (get "sort" spec)
lim = dvToI (get "limit" spec)
skip = dvToI (get "skip" spec)
page = dvToI (get "page" spec)
loc = dvToM (get "location" spec)
dvToStr docval = case docval of
DocString s -> s
otherwise -> "" -- This is kind of a strange default.
dvToStrList docval = case docval of
DocList l -> map dvToStr l
otherwise -> []
dvToI docval = case docval of
DocInt i -> i
otherwise -> 0
dvToM docval = case docval of
DocMap m -> m
otherwise -> M.empty
in Specials sort lim skip page loc
{--------------------------------------------------------------------
A farily simple database class.
--------------------------------------------------------------------}
-- | Database connection class.
-- A full location is ["server" .- "serveraddr.com:27017", db .- "dbName", coll .- "users"]
-- But a location can be partial too (eg a server only, or a server and a db).
-- You can specify a location in a Selector, by providing the field ["location" .- ...], or to avoid repetition,
-- you can set the default location for the given db connection with the @setLocation@ method.
class Db db where
-- | Connects to a db server. Can be connected to multiple servers. Querying a server which the db handle has no connection with will cause
-- a temporal connection to take place.
-- In the input document d, if you specify "user" and "password" fields, it will try to authenticate the connection.
-- Exception will be thrown if the authentication is tried but fails.
-- Authentication happens against a database, so a database must be specified.
connect :: DocLike d => db -> d -> IO db
-- TODO: auth function.
-- | List of server addresses the given db handle is connected to.
servers :: db -> [T.Text]
-- | Get location.
location :: db -> Document
-- | Sets default location.
setLocation :: DocLike d => db -> d -> db
-- | Drop a database.
dropDb :: DocLike d => db -> d -> IO ()
-- Drop the current database.
dropCurrent :: db -> IO ()
-- Insert a document. Returned string is the Id of the freshly inserted document. If a document already has an "id" field, that will be used.
insert :: DocLike d => db -> d -> IO T.Text
-- Insert multiple documents at once, return their Ids.
insertAll :: DocLike d => db -> [d] -> IO [T.Text]
-- Find all documents in selection.
find :: DocLike s => db -> s -> IO [Document]
-- Find the first document in selection.
findOne :: DocLike s => db -> s -> IO (Maybe Document)
-- Update (modify) the document in selection.
update :: (DocLike s, DocLike mod) => db -> s -> mod -> IO ()
-- Count the documents in selection.
count :: DocLike s => db -> s -> IO Integer
-- Delete all documents in selection.
delete :: DocLike s => db -> s -> IO ()
-- Delete first document in selection.
deleteOne :: DocLike s => db -> s -> IO ()
-- Replace first document in selection with given document.
replace :: DocLike s => db -> s -> Document -> IO ()
-- Iterate over documents in selection. Useful for batch processing.
iterate :: DocLike s => db -> s -> (Document -> IO ()) -> IO ()
-- Maybe add something like iterateBatch :: DocLike s => db -> s ([Document] -> IO ()) -> IO ()
-- Resolve all dbRefs in given set of documents.
resolve :: db -> [Document] -> IO [Document]
resolve db docs = resolveDbRefs db docs
{--------------------------------------------------------------------
Implementation of the resolve method.
--------------------------------------------------------------------}
-- find documents, then [Document] -> [("id-collname", Document)] so we can build a map out of it easily.
toCollIdPairs db (grouperStr, location, idList) = do
docs <- find (setLocation db location) $ dm ["_id" .- ["$in" .- idList]]
return $ map (\dc -> (T.concat [idToStr (get "id" dc), "-", grouperStr], dc)) docs
docValToDoc x = case x of
DocMap x -> x;
otherwise -> error "DocVal is not a DocMap"
resolveDbRefs :: Db a => a -> [Document] -> IO [Document]
resolveDbRefs db docs = do
let refs = List.concat $ map (\x -> filt isDbRef (d x)) docs
triples = gr' $ map (\ref -> (locationToStr $ toM ref, unsetId $ toM ref, strToId $ idOf' ref)) refs
toM x = case x of
DocTyped DTyped{typ="dbRef",val=DocMap m} -> m;
otherwise -> error "Location should be a Document."
unsetId x = unset "id" x
locationToStr x = dbRefToStr $ unsetId x
nestedPairs <- mapM (toCollIdPairs db) triples
let idcMap = M.fromList $ List.concat nestedPairs
lookup x = case M.lookup x idcMap of Just z -> z; Nothing -> M.empty
swapper :: DocVal -> DocVal
swapper x = if isDbRef x
then d . lookup $ T.concat [idOf' x, "-", locationToStr (toM x)]
else x
return $ map (\x -> docValToDoc (ma swapper (d x))) docs
grBy :: Ord a1 => (a -> a1) -> [a] -> [[a]]
grBy f l = List.groupBy ((==) `F.on` f) $ List.sortBy (O.comparing f) l
-- | Same as gr but with a 3-tuple.
gr' :: Ord a => [(a, t, b)] -> [(a, t, [b])]
gr' l = map (\l -> (e1 . head $ l, e2 . head $ l, map e3 l)) $ grBy e1 l
{--------------------------------------------------------------------
Oid/dbRef helpers.
--------------------------------------------------------------------}
-- | Converts a text into an Object Id.
oid :: T.Text -> DocVal
oid x = DocTyped $ DTyped "id" (DocString x)
idToStr :: DocVal -> T.Text
idToStr x = case x of
DocTyped DTyped{typ="id", val=v} -> case v of
DocString s -> s
otherwise -> error $ "Bad id format " ++ show v
otherwise -> error $ "Not an id " ++ show x
refSep = " "
idKey = "id"
refType = "dbRef"
idType = "id"
regexpType = "regexp"
idLen = 24
dbRef :: DocLike dc => dc -> DocVal
dbRef doc = DocTyped $ DTyped "dbRef" (d (toDoc doc))
unpackDbRef :: DTyped -> Document
unpackDbRef x = case x of
DTyped{typ="dbRef", val=DocMap m} -> m
otherwise -> error "Can't convert DTyped to a dbRef."
-- | Returns the id part of a dbRef.
idOf :: DTyped -> T.Text
idOf x = getString "id" $ unpackDbRef x
-- | Same as oid.
strToId :: T.Text -> DocVal
strToId str = oid str
dbRefMustBe = "A dbRef must be of type DTyped"
-- | Returns the id part of a DocVal dbRef if the DocVal
-- is a meta DocVal, raises error otherwise.
idOf' :: DocVal -> T.Text
idOf' x = case x of
DocTyped d -> idOf d
otherwise -> error dbRefMustBe
-- | Return the collection part of a meta DocVal.
collOf :: DTyped -> T.Text
collOf x = getString "coll" $ unpackDbRef x
-- | Returns the collection part of a DocVal dbRef if the DocVal
-- is a meta DocVal, raises error otherwise.
collOf' :: DocVal -> T.Text
collOf' x = case x of
DocTyped d -> collOf d
otherwise -> error dbRefMustBe
isXTyped t x = case x of
DocTyped d -> typ d == t;
otherwise -> False
-- | Returns True of a given DocVal is a DbRef.
isDbRef :: DocVal -> Bool
isDbRef x = isXTyped "dbRef" x
-- | Returns True if a given DocVal is an Id.
isId :: DocVal -> Bool
isId x = isXTyped "id" x
dbRefToStr doc = T.intercalate ";" $ map (\(a, b) -> T.concat [toString b, "|", a]) $ List.sortBy (O.comparing fst) (M.toList doc)
strToDbRef str = DocTyped $ DTyped "dbRef" $ DocMap $ M.fromList $
map (\x -> let xs = T.splitOn "|" x in (Safe.atNote "strToDbRef 1" xs 1, d $ Safe.atNote "strToDbRef 0" xs 0)) (T.splitOn ";" str)
|
crufter/hakit
|
src/hakit/db.hs
|
bsd-3-clause
| 9,528 | 0 | 17 | 2,454 | 2,488 | 1,312 | 1,176 | 152 | 5 |
{-|
Compiled splices are similar to the original Heist (interpreted) splices, but
without the high performance costs of traversing a DOM at runtime. Compiled
splices do all of their DOM processing at load time. They are compiled to
produce a runtime computation that generates a ByteString Builder. This
preserves the ability to write splices that access runtime information from
the HTTP request, database, etc.
If you import both this module and "Heist.Interpreted" in the same file, then
you will need to import them qualified.
-}
module Heist.Compiled
(
-- * High level compiled splice API
Splice
, renderTemplate
, codeGen
, runChildren
-- * Functions for manipulating lists of compiled splices
, mapSnd
, applySnd
, textSplices
, nodeSplices
, pureSplices
, textSplice
, nodeSplice
, pureSplice
, mapInputPromise
, defer
, deferMany
, withSplices
, manyWithSplices
, withPureSplices
-- * Old compiled splice API
, mapPromises
, promiseChildren
, promiseChildrenWith
, promiseChildrenWithTrans
, promiseChildrenWithText
, promiseChildrenWithNodes
-- * Constructing Chunks
-- $yieldOverview
, yieldPure
, yieldRuntime
, yieldRuntimeEffect
, yieldPureText
, yieldRuntimeText
, yieldLater
, addSplices
, withLocalSplices
-- * Lower level promise functions
, Promise
, newEmptyPromise
, getPromise
, putPromise
, adjustPromise
-- * Running nodes and splices
, runNodeList
, runNode
, runAttributes
, callTemplate
) where
import Heist.Compiled.Internal
-- $yieldOverview
-- The internals of the Chunk data type are deliberately not exported because
-- we want to hide the underlying implementation as much as possible. The
-- @yield...@ functions give you lower lever construction of Chunks and DLists
-- of Chunks.
|
silkapp/heist
|
src/Heist/Compiled.hs
|
bsd-3-clause
| 1,834 | 0 | 4 | 374 | 150 | 104 | 46 | 44 | 0 |
-------------------------------------------------------------------------------
---- |
---- Module : RSL.Sema
---- Copyright : (c) Syoyo Fujita
---- License : Modified BSD
----
---- Maintainer : [email protected]
---- Stability : experimental
---- Portability : GHC 6.8
----
---- RSLParser : Semantic analysis module for RenderMan SL.
---- This module is interoperated with RSL.Parser.
----
-------------------------------------------------------------------------------
{-
List of builtin varibles and functions based on RI spec 3.2
-}
module RSL.Sema where
import RSL.AST
--
-- | List of RSL builtin variables
--
builtinShaderVariables :: [Symbol]
builtinShaderVariables =
[ (SymVar "Ci" TyColor Varying KindBuiltinVariable)
, (SymVar "Oi" TyColor Varying KindBuiltinVariable)
, (SymVar "Cs" TyColor Varying KindBuiltinVariable)
, (SymVar "Os" TyColor Varying KindBuiltinVariable)
, (SymVar "P" TyPoint Varying KindBuiltinVariable)
, (SymVar "dPdu" TyVector Varying KindBuiltinVariable)
, (SymVar "dPdv" TyVector Varying KindBuiltinVariable)
, (SymVar "Ps" TyPoint Varying KindBuiltinVariable)
, (SymVar "I" TyVector Varying KindBuiltinVariable)
, (SymVar "E" TyPoint Uniform KindBuiltinVariable)
, (SymVar "L" TyVector Uniform KindBuiltinVariable)
, (SymVar "N" TyNormal Varying KindBuiltinVariable)
, (SymVar "Ng" TyNormal Varying KindBuiltinVariable)
, (SymVar "Ns" TyNormal Varying KindBuiltinVariable)
, (SymVar "Cl" TyColor Varying KindBuiltinVariable)
, (SymVar "Ol" TyColor Varying KindBuiltinVariable)
, (SymVar "s" TyFloat Varying KindBuiltinVariable)
, (SymVar "t" TyFloat Varying KindBuiltinVariable)
, (SymVar "u" TyFloat Varying KindBuiltinVariable)
, (SymVar "v" TyFloat Varying KindBuiltinVariable)
, (SymVar "du" TyFloat Varying KindBuiltinVariable)
, (SymVar "dv" TyFloat Varying KindBuiltinVariable)
, (SymVar "ncompos" TyFloat Uniform KindBuiltinVariable)
, (SymVar "time" TyFloat Uniform KindBuiltinVariable)
, (SymVar "dtime" TyFloat Uniform KindBuiltinVariable)
, (SymVar "dPdtime" TyVector Varying KindBuiltinVariable)
-- extension for lucille.
, (SymVar "x" TyFloat Varying KindBuiltinVariable)
, (SymVar "y" TyFloat Varying KindBuiltinVariable)
, (SymVar "z" TyFloat Varying KindBuiltinVariable)
, (SymVar "w" TyFloat Varying KindBuiltinVariable)
, (SymVar "sx" TyInt Varying KindBuiltinVariable)
, (SymVar "sy" TyInt Varying KindBuiltinVariable)
-- Constant
, (SymVar "PI" TyFloat Uniform KindBuiltinVariable)
] -- More is TODO
builtinOutputShaderVariables :: [Symbol]
builtinOutputShaderVariables =
[ (SymVar "Ci" TyColor Varying KindBuiltinVariable)
, (SymVar "Oi" TyColor Varying KindBuiltinVariable)
]
builtinShaderFunctions :: [Symbol]
builtinShaderFunctions =
[
-- [15.1] Mathematical Functions
(SymBuiltinFunc "radians" f [f] Nothing)
, (SymBuiltinFunc "degrees" f [f] Nothing)
, (SymBuiltinFunc "sin" f [f] Nothing)
, (SymBuiltinFunc "asin" f [f] Nothing)
, (SymBuiltinFunc "cos" f [f] Nothing)
, (SymBuiltinFunc "acos" f [f] Nothing)
, (SymBuiltinFunc "tan" f [f] Nothing)
, (SymBuiltinFunc "atan" f [f] Nothing)
, (SymBuiltinFunc "atan" f [f, f] Nothing)
, (SymBuiltinFunc "pow" f [f, f] Nothing)
, (SymBuiltinFunc "exp" f [f] Nothing)
, (SymBuiltinFunc "sqrt" f [f] Nothing)
, (SymBuiltinFunc "inversesqrt" f [f] Nothing)
, (SymBuiltinFunc "log" f [f] Nothing)
, (SymBuiltinFunc "log" f [f, f] Nothing)
, (SymBuiltinFunc "mod" f [f, f] Nothing)
, (SymBuiltinFunc "abs" f [f] Nothing)
, (SymBuiltinFunc "sign" f [f] Nothing)
-- TODO: float, point, vector, normal, color
, (SymBuiltinFunc "min" f [f, f] Nothing)
-- TODO: float, point, vector, normal, color
, (SymBuiltinFunc "max" f [f, f] Nothing)
-- TODO: float, point, vector, normal, color
, (SymBuiltinFunc "clamp" f [f, f] Nothing)
-- float, point, vector, normal, color
, (SymBuiltinFunc "mix" f [f, f, f] Nothing)
, (SymBuiltinFunc "floor" f [f] Nothing)
, (SymBuiltinFunc "ceil" f [f] Nothing)
, (SymBuiltinFunc "round" f [f] Nothing)
, (SymBuiltinFunc "step" f [f, f] Nothing)
, (SymBuiltinFunc "smoothstep" f [f, f, f] Nothing)
, (SymBuiltinFunc "spline" f [f] (Just f))
-- TODO...
, (SymBuiltinFunc "random" f [] Nothing)
, (SymBuiltinFunc "random" c [] Nothing)
, (SymBuiltinFunc "random" p [] Nothing)
, (SymBuiltinFunc "noise" f [f] Nothing)
, (SymBuiltinFunc "noise" f [p] Nothing)
, (SymBuiltinFunc "noise" f [v] Nothing)
, (SymBuiltinFunc "noise" f [n] Nothing)
, (SymBuiltinFunc "noise" f [f, f] Nothing)
-- TODO...
-- [15.2] Geometric Functions
, (SymBuiltinFunc "xcomp" f [v] Nothing)
, (SymBuiltinFunc "xcomp" f [p] Nothing)
, (SymBuiltinFunc "xcomp" f [n] Nothing)
, (SymBuiltinFunc "ycomp" f [v] Nothing)
, (SymBuiltinFunc "ycomp" f [p] Nothing)
, (SymBuiltinFunc "ycomp" f [n] Nothing)
, (SymBuiltinFunc "zcomp" f [v] Nothing)
, (SymBuiltinFunc "zcomp" f [p] Nothing)
, (SymBuiltinFunc "zcomp" f [n] Nothing)
-- , (SymFunc "setxcomp" f [n] [])
-- , (SymFunc "setycomp" f [n] [])
-- , (SymFunc "setzcomp" f [n] [])
, (SymBuiltinFunc "length" f [v] Nothing)
, (SymBuiltinFunc "length" f [p] Nothing)
, (SymBuiltinFunc "length" f [n] Nothing)
, (SymBuiltinFunc "normalize" v [v] Nothing)
, (SymBuiltinFunc "normalize" v [n] Nothing)
, (SymBuiltinFunc "distance" f [p, p] Nothing)
-- , (SymFunc "ptlined" f [p, p] [])
-- , (SymFunc "rotate" f [p, p] [])
, (SymBuiltinFunc "area" f [p] Nothing)
, (SymBuiltinFunc "faceforward" v [v, v] Nothing) -- has opt arg
, (SymBuiltinFunc "faceforward" v [n, v] Nothing) -- has opt arg
, (SymBuiltinFunc "faceforward" v [n, p] Nothing) -- has opt arg
, (SymBuiltinFunc "faceforward" v [v, p] Nothing) -- has opt arg
, (SymBuiltinFunc "reflect" v [v, v] Nothing)
, (SymBuiltinFunc "reflect" v [v, n] Nothing)
, (SymBuiltinFunc "reflect" v [v, p] Nothing)
, (SymBuiltinFunc "refract" v [v, v, f] Nothing)
, (SymBuiltinFunc "refract" v [v, n, f] Nothing)
, (SymBuiltinFunc "fresnel" v [v, v, f, f, f] Nothing) -- TODO
, (SymBuiltinFunc "transform" p [s, p] Nothing)
, (SymBuiltinFunc "transform" p [s, s, p] Nothing)
, (SymBuiltinFunc "transform" p [m, p] Nothing)
, (SymBuiltinFunc "transform" p [s, m, p] Nothing)
, (SymBuiltinFunc "transform" v [s, v] Nothing)
, (SymBuiltinFunc "transform" v [s, s, v] Nothing)
, (SymBuiltinFunc "transform" v [m, v] Nothing)
, (SymBuiltinFunc "transform" v [s, m, v] Nothing)
, (SymBuiltinFunc "transform" n [s, n] Nothing)
, (SymBuiltinFunc "transform" n [s, s, n] Nothing)
, (SymBuiltinFunc "transform" n [m, n] Nothing)
, (SymBuiltinFunc "transform" n [s, m, n] Nothing)
, (SymBuiltinFunc "vtransform" v [s, s, v] Nothing)
, (SymBuiltinFunc "depth" f [p] Nothing)
, (SymBuiltinFunc "depth" f [p] Nothing)
-- [15.3] Color Functions
, (SymBuiltinFunc "comp" f [c, f] Nothing)
-- , (SymBuiltinFunc "setcomp" void [c, f, f] [])
, (SymBuiltinFunc "mix" c [c, c, f] Nothing)
, (SymBuiltinFunc "Du" f [f] Nothing)
, (SymBuiltinFunc "Du" c [c] Nothing)
, (SymBuiltinFunc "Du" v [p] Nothing)
, (SymBuiltinFunc "Du" v [v] Nothing)
, (SymBuiltinFunc "Dv" f [f] Nothing)
, (SymBuiltinFunc "Dv" c [c] Nothing)
, (SymBuiltinFunc "Dv" v [p] Nothing)
, (SymBuiltinFunc "Dv" v [v] Nothing)
, (SymBuiltinFunc "Deriv" f [f, f] Nothing)
, (SymBuiltinFunc "Deriv" c [c, f] Nothing)
, (SymBuiltinFunc "Deriv" p [p, f] Nothing)
, (SymBuiltinFunc "Deriv" v [v, f] Nothing)
-- [15.5] String Functions
--
-- FIXME: Need a special treatment for string functions.
--
, (SymBuiltinFunc "printf" void [s] Nothing)
-- [15.6] Shading and Lighting Functions
, (SymBuiltinFunc "ambient" c [] Nothing)
, (SymBuiltinFunc "diffuse" c [n] Nothing)
, (SymBuiltinFunc "diffuse" c [p] Nothing)
, (SymBuiltinFunc "diffuse" c [v] Nothing)
, (SymBuiltinFunc "specular" c [n, v, f] Nothing)
, (SymBuiltinFunc "specular" c [p, p, f] Nothing)
, (SymBuiltinFunc "specularbrdf" c [v, n, v, f] Nothing)
, (SymBuiltinFunc "phong" c [n, v, f] Nothing)
, (SymBuiltinFunc "trace" c [p, p] Nothing)
, (SymBuiltinFunc "trace" c [p, v] Nothing)
-- [15.7] Texture Mapping Functions
, (SymBuiltinFunc "texture" c [s] Nothing)
, (SymBuiltinFunc "environment" c [s] Nothing)
, (SymBuiltinFunc "environment" c [s, v] Nothing)
-- extension for lucille
, (SymBuiltinFunc "save_cache" void [i, i, i, c] Nothing)
, (SymBuiltinFunc "save_cache" void [i, i, i, f] Nothing)
, (SymBuiltinFunc "load_cache" c [i, i, i] Nothing)
, (SymBuiltinFunc "load_cache" f [i, i, i] Nothing)
, (SymBuiltinFunc "turb" c [p] Nothing)
, (SymBuiltinFunc "occlusion" f [p, n] Nothing)
, (SymBuiltinFunc "occlusion" f [p, n, f] Nothing)
] -- More is TODO
where
f = TyFloat
c = TyColor
v = TyVector
p = TyPoint
n = TyNormal
s = TyString
m = TyMatrix
i = TyInt
void = TyVoid
lookupVariable :: [Symbol] -> String -> [Symbol]
lookupVariable syms name = filter (\(SymVar sname _ _ _) -> sname == name) syms
lookupBuiltinFunc :: [Symbol] -> String -> [Symbol]
lookupBuiltinFunc syms name = filter (\(SymBuiltinFunc fname _ _ _) -> fname == name) syms
checkArgTy (SymBuiltinFunc name _ fargTys Nothing) argTys = (fargTys == argTys)
-- Check signature of a function with vaargs.
checkArgTy (SymBuiltinFunc name _ fargTys (Just vaTy)) argTys
| n > m = False -- Insufficient # of args.
| n == m = (fargTys == argTys)
| n < m = let (fTys, vaTys) = splitAt n argTys in
(fTys == fargTys) && ((replicate (m-n) vaTy) == vaTys)
where
n = length fargTys
m = length argTys
lookupBuiltinFuncWithArgumentSignature :: [Symbol] -> String -> [Type] -> [Symbol]
lookupBuiltinFuncWithArgumentSignature syms name argTys =
filter (\sym@(SymBuiltinFunc fname _ tys _) -> (fname == name) && (checkArgTy sym argTys ) ) syms
-- filter (\(SymBuiltinFunc fname _ tys _) -> (fname == name) && (tys == argTys) ) syms
|
chiyama/lucille
|
rnd/HaskellRSLCompiler/RSL/Sema.hs
|
bsd-3-clause
| 11,675 | 0 | 14 | 3,498 | 3,310 | 1,867 | 1,443 | 180 | 1 |
module Main where
import System.Console.GetOpt
import System.Environment
import System.IO
import System.Exit
import Network.Socket (withSocketsDo)
import Network.BSD
import Scurry.Peer
import Scurry.Comm
-- import Scurry.Management.Config
-- import Scurry.Management.Tracker
import Scurry.State
import Scurry.Util(inet_addr)
import Scurry.Network
import Scurry.Types.Network
import Data.Word
import Data.Maybe
data ScurryOpts = ScurryOpts {
vpnAddr :: Maybe ScurryAddress,
vpnMask :: Maybe ScurryMask,
bindAddr :: ScurryAddress,
bindPort :: ScurryPort,
userName :: String,
peers :: [EndPoint]
} deriving (Show)
data ScurryOpt = SOVAddr ScurryAddress
| SOVMask ScurryMask
| SOBAddr ScurryAddress
| SOBPort ScurryPort
| SOUName String
deriving (Show)
defaultPort :: ScurryPort
defaultPort = ScurryPort 24999
readPort :: String -> ScurryPort
readPort [] = error "I need some numbers!"
readPort s = let w = read s :: Word16
in (ScurryPort . fromIntegral) w
lookupName :: String -> IO EndPoint
lookupName ep = do
let name = takeWhile (/=':') ep
port = case drop 1 $ dropWhile (/=':') ep of
[] -> defaultPort
x -> readPort x
HostEntry { hostAddresses = as } <- getHostByName name
return $ EndPoint (ScurryAddress (as !! 0)) port
parseScurryOpts :: [String] -> IO (Either String ScurryOpts)
parseScurryOpts args = let def_opt = ScurryOpts { vpnAddr = Nothing
, vpnMask = Nothing
, bindAddr = ScurryAddress 0
, bindPort = ScurryPort 24999
, userName = "ScurryUser"
, peers = [] }
va_t = SOVAddr . fromJust . inet_addr
vm_t = SOVMask . fromJust . inet_addr
ba_t = SOBAddr . fromJust . inet_addr
bp_t = SOBPort . readPort
un_t = SOUName
options = [ Option "a" ["vpn-addr"] (ReqArg va_t "VPN_ADDRESS") "VPN IP Address."
, Option "m" ["vpn-mask"] (ReqArg vm_t "VPN_NETMASK") "VPN Netmask."
, Option "b" ["bind-addr"] (ReqArg ba_t "BIND_ADDRESS") "Address to bind for tunnels."
, Option "p" ["bind-port"] (ReqArg bp_t "BIND_PORT") "Port to bind for tunnels."
, Option "n" ["user-name"] (ReqArg un_t "USER_NAME") "Name of the connection user." ]
(m,o,_) = getOpt RequireOrder options args -- ignore errors for now
u = Left (usageInfo "How to use scurry." options)
opt' = foldr rplcOpts def_opt m
in case args of
["-h"] -> return u
["--help"] -> return u
_ -> do ps <- mapM lookupName o
return $ Right (opt' { peers = ps })
where rplcOpts (SOVAddr a) sos = sos { vpnAddr = Just a }
rplcOpts (SOVMask m) sos = sos { vpnMask = Just m }
rplcOpts (SOBAddr a) sos = sos { bindAddr = a }
rplcOpts (SOBPort p) sos = sos { bindPort = p }
rplcOpts (SOUName n) sos = sos { userName = n }
main :: IO ()
main = withSocketsDo $ do
args <- getArgs
opts_ <- parseScurryOpts args
-- let (configPath:trackerPath:_) = args
opts <- case opts_ of
(Left msg) -> putStrLn msg >> exitFailure
(Right p) -> return p
-- (Just config) <- load_scurry_config_file configPath
-- (Just tracker) <- load_tracker_file trackerPath
-- let (Scurry (VpnConfig tapIp tapMask) (NetworkConfig mySockAddr)) = config
-- trackerEndPoints = filter (/= mySockAddr) $ map tToS tracker
let initState = ScurryState {
scurryPeers = [],
scurryEndPoint = EndPoint (bindAddr opts) (bindPort opts),
scurryNetwork = ScurryNetwork {
scurryMask = vpnMask opts
},
scurryMyRecord = PeerRecord {
peerMAC = Nothing,
peerEndPoint = EndPoint (ScurryAddress 0) (ScurryPort 0),
peerVPNAddr = vpnAddr opts,
peerLocalPort = bindPort opts -- (\(EndPoint _ p) -> p) mySockAddr
}
}
tapNet = (vpnAddr opts, vpnMask opts)
local <- prepEndPoint (scurryEndPoint initState) -- mySockAddr
startCom tapNet local initState (peers opts)
{-
where
tToS (ScurryPeer ip port) = EndPoint ip port
-}
{-
getAddress :: Socket -> [EndPoint] -> IO (ScurryAddress, ScurryMask)
getAddress sock (t:trackers) = do
let msg = SAddrRequest
cmd = sendToAddr sock msg
putStrLn "Requesting address..."
cmd t
where
delayRead = do
threadDelay (sToMs 1.5)
-}
|
dmagyar/scurry
|
src/scurry.hs
|
bsd-3-clause
| 5,244 | 0 | 17 | 2,005 | 1,141 | 612 | 529 | 93 | 7 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Serials.Link.Import where
import Prelude hiding (null)
import Control.Lens ((^.))
import Control.Applicative
import Data.Data
import Data.ByteString.Lazy (ByteString)
import Data.Maybe (fromMaybe, fromJust)
import Data.Text (unpack, Text, null, isInfixOf)
import qualified Data.Text.Lazy as TL
import Data.Text.Lazy (toStrict, fromStrict)
import Data.Text.Lazy.Encoding (decodeUtf8, encodeUtf8, decodeLatin1)
import GHC.Generics (Generic)
import Network.Wreq hiding (Link)
--import Serials.Link.Scrape
import Serials.Link.Menu
import Serials.Link.TOC
import Serials.Link.Link
import Serials.Link.Soup
import Text.HTML.Scalpel hiding (URL)
import Text.HTML.TagSoup hiding (Tag, select)
import Text.Regex.PCRE
data ImportSettings =
MenuSettings {
menuBase :: URL,
menuOpen :: Text
} |
TOCSettings {
tocSelector :: Text,
titleSelector :: Text
}
deriving (Show, Eq, Generic)
menuContent :: URL -> CSSSelector -> CSSSelector -> URL -> IO [Content]
menuContent base start end url = parseMenuContent base start end <$> downloadTags url
-- if it's empty, then don't select the text...
tocContent :: CSSSelector -> Maybe CSSSelector -> URL -> IO [Content]
tocContent root title url = parseToc url root title <$> downloadTags url
-- yeah, because you need to map a source to an IO action
importContent :: URL -> ImportSettings -> IO [Content]
importContent url set = fetchLinks set url
where
fetchLinks (MenuSettings base open) = menuContent base (css open) (css "select")
fetchLinks (TOCSettings root title) = tocContent (css root) (emptySelector title)
emptySelector t = if null t then Nothing else Just (css t)
-- baby steps:
-- don't require a root selector
-- only have the admin see them
-- set it to "body" and "blank", then go in an clean it up yourself? But then it'll suck...
-- don't have them specify chapters at all. Just put in the url, the title, etc, and it submits. Then I can clean it up.
-- guesses the import method based on the url and other content
-- make better algorithms for figuring it out
--urlContent :: URL -> IO [Content]
--urlContent url = do
--if unpack url =~ "fanfiction.net" :: Bool
--then
--else if unpack url =~ "fanfiction.net"
guessMethod :: URL -> IO [Content]
guessMethod url
| isFanfictionNet url = fanfictionNetContent url
| otherwise = tocContent (css "body") Nothing url
fanfictionNetContent :: URL -> IO [Content]
fanfictionNetContent url = menuContent url (css "#chap_select") (css "select") url
isFanfictionNet :: URL -> Bool
isFanfictionNet url =
"fanfiction.net" `isInfixOf` url
|| "fimfiction.net" `isInfixOf` url
-- How can I identify a table of contents on a page?
-- the links are all going to be next to each other, they don't have a lot of text in between them. They are usually entirely links. I don't want to MISS them though.
-- it would be so cool if I could train it...
-- identify what each one is
-- then it gets smarter about it over time.
----------------------------------------------------------
downloadTags :: URL -> IO [Tag]
downloadTags url = parseTags <$> downloadBody url
downloadBody :: URL -> IO Text
downloadBody url = toStrict <$> downloadBodyLazy url
downloadBodyLazy :: URL -> IO TL.Text
downloadBodyLazy url = do
r <- get (unpack url)
let body = r ^. responseBody :: ByteString
return $ decodeUtf8 body
-----------------------------------------------------------
--testTwig = mapM_ print =<< menuContent "https://twigserial.wordpress.com/donate/" "https://twigserial.wordpress.com/?cat=" (css "#cat") (css "select")
--testGinny = mapM_ print =<< menuContent "http://fanfiction.net/s/11117811/" "http://fanfiction.net/s/11117811/" (css "#chap_select") (css "select")
--testPact = mapM_ print =<< tocContent "https://pactwebserial.wordpress.com/table-of-contents/" (css ".entry-content") (Just $ css "strong")
--testWorm = mapM_ print =<< tocContent "https://parahumans.wordpress.com/table-of-contents/" (css ".entry-content") (Just $ css "strong")
--testHPMOR = mapM_ print =<< tocContent "http://hpmor.com/" (css ".toclist") Nothing
--testFriendship = mapM_ print =<< tocContent "http://www.fimfiction.net/story/62074/friendship-is-optimal" (css ".chapters") Nothing
--------------------------------------------------------------
-- Test some stuff!
|
seanhess/serials
|
server/Serials/Link/Import.hs
|
mit
| 4,405 | 0 | 10 | 692 | 779 | 437 | 342 | 58 | 3 |
import Test.Hspec
import Control.Exception (evaluate)
import Control.DeepSeq
main :: IO ()
main = hspec $ do
describe "div" $ do
it "throws an exception if the second argument is 0" $ do
evaluate (1 `div` 0 :: Int) `shouldThrow` anyArithException
describe "evaluate" $ do
it "forces exceptions" $ do
evaluate ('a' : undefined) `shouldThrow` anyErrorCall
describe "evaluate . force" $ do
it "forces exceptions" $ do
(evaluate . force) ('a' : undefined) `shouldThrow` anyErrorCall
|
hspec/hspec
|
doc/_includes/ExceptionsFromPureCode.hs
|
mit
| 518 | 0 | 17 | 113 | 169 | 84 | 85 | 14 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash, UnboxedTuples,
NamedFieldPuns, BangPatterns #-}
{-# OPTIONS_HADDOCK prune #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-- |
-- Module : Data.ByteString
-- Copyright : (c) The University of Glasgow 2001,
-- (c) David Roundy 2003-2005,
-- (c) Simon Marlow 2005,
-- (c) Bjorn Bringert 2006,
-- (c) Don Stewart 2005-2008,
-- (c) Duncan Coutts 2006-2013
-- License : BSD-style
--
-- Maintainer : [email protected], [email protected]
-- Stability : stable
-- Portability : portable
--
-- A time- and space-efficient implementation of byte vectors using
-- packed Word8 arrays, suitable for high performance use, both in terms
-- of large data quantities and high speed requirements. Byte vectors
-- are encoded as strict 'Word8' arrays of bytes, held in a 'ForeignPtr',
-- and can be passed between C and Haskell with little effort.
--
-- The recomended way to assemble ByteStrings from smaller parts
-- is to use the builder monoid from "Data.ByteString.Builder".
--
-- This module is intended to be imported @qualified@, to avoid name
-- clashes with "Prelude" functions. eg.
--
-- > import qualified Data.ByteString as B
--
-- Original GHC implementation by Bryan O\'Sullivan.
-- Rewritten to use 'Data.Array.Unboxed.UArray' by Simon Marlow.
-- Rewritten to support slices and use 'ForeignPtr' by David Roundy.
-- Rewritten again and extended by Don Stewart and Duncan Coutts.
--
module Data.ByteString (
-- * The @ByteString@ type
ByteString, -- abstract, instances: Eq, Ord, Show, Read, Data, Typeable, Monoid
-- * Introducing and eliminating 'ByteString's
empty, -- :: ByteString
singleton, -- :: Word8 -> ByteString
pack, -- :: [Word8] -> ByteString
unpack, -- :: ByteString -> [Word8]
-- * Basic interface
cons, -- :: Word8 -> ByteString -> ByteString
snoc, -- :: ByteString -> Word8 -> ByteString
append, -- :: ByteString -> ByteString -> ByteString
head, -- :: ByteString -> Word8
uncons, -- :: ByteString -> Maybe (Word8, ByteString)
unsnoc, -- :: ByteString -> Maybe (ByteString, Word8)
last, -- :: ByteString -> Word8
tail, -- :: ByteString -> ByteString
init, -- :: ByteString -> ByteString
null, -- :: ByteString -> Bool
length, -- :: ByteString -> Int
-- * Transforming ByteStrings
map, -- :: (Word8 -> Word8) -> ByteString -> ByteString
reverse, -- :: ByteString -> ByteString
intersperse, -- :: Word8 -> ByteString -> ByteString
intercalate, -- :: ByteString -> [ByteString] -> ByteString
transpose, -- :: [ByteString] -> [ByteString]
-- * Reducing 'ByteString's (folds)
foldl, -- :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl', -- :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldl1', -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr, -- :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr', -- :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr1', -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
-- ** Special folds
concat, -- :: [ByteString] -> ByteString
concatMap, -- :: (Word8 -> ByteString) -> ByteString -> ByteString
any, -- :: (Word8 -> Bool) -> ByteString -> Bool
all, -- :: (Word8 -> Bool) -> ByteString -> Bool
maximum, -- :: ByteString -> Word8
minimum, -- :: ByteString -> Word8
-- * Building ByteStrings
-- ** Scans
scanl, -- :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanl1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
scanr, -- :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanr1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
-- ** Accumulating maps
mapAccumL, -- :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
mapAccumR, -- :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
-- ** Generating and unfolding ByteStrings
replicate, -- :: Int -> Word8 -> ByteString
unfoldr, -- :: (a -> Maybe (Word8, a)) -> a -> ByteString
unfoldrN, -- :: Int -> (a -> Maybe (Word8, a)) -> a -> (ByteString, Maybe a)
-- * Substrings
-- ** Breaking strings
take, -- :: Int -> ByteString -> ByteString
drop, -- :: Int -> ByteString -> ByteString
splitAt, -- :: Int -> ByteString -> (ByteString, ByteString)
takeWhile, -- :: (Word8 -> Bool) -> ByteString -> ByteString
dropWhile, -- :: (Word8 -> Bool) -> ByteString -> ByteString
span, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
spanEnd, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
break, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
breakEnd, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
group, -- :: ByteString -> [ByteString]
groupBy, -- :: (Word8 -> Word8 -> Bool) -> ByteString -> [ByteString]
inits, -- :: ByteString -> [ByteString]
tails, -- :: ByteString -> [ByteString]
stripPrefix, -- :: ByteString -> ByteString -> Maybe ByteString
stripSuffix, -- :: ByteString -> ByteString -> Maybe ByteString
-- ** Breaking into many substrings
split, -- :: Word8 -> ByteString -> [ByteString]
splitWith, -- :: (Word8 -> Bool) -> ByteString -> [ByteString]
-- * Predicates
isPrefixOf, -- :: ByteString -> ByteString -> Bool
isSuffixOf, -- :: ByteString -> ByteString -> Bool
isInfixOf, -- :: ByteString -> ByteString -> Bool
-- ** Search for arbitrary substrings
breakSubstring, -- :: ByteString -> ByteString -> (ByteString,ByteString)
findSubstring, -- :: ByteString -> ByteString -> Maybe Int
findSubstrings, -- :: ByteString -> ByteString -> [Int]
-- * Searching ByteStrings
-- ** Searching by equality
elem, -- :: Word8 -> ByteString -> Bool
notElem, -- :: Word8 -> ByteString -> Bool
-- ** Searching with a predicate
find, -- :: (Word8 -> Bool) -> ByteString -> Maybe Word8
filter, -- :: (Word8 -> Bool) -> ByteString -> ByteString
partition, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
-- * Indexing ByteStrings
index, -- :: ByteString -> Int -> Word8
elemIndex, -- :: Word8 -> ByteString -> Maybe Int
elemIndices, -- :: Word8 -> ByteString -> [Int]
elemIndexEnd, -- :: Word8 -> ByteString -> Maybe Int
findIndex, -- :: (Word8 -> Bool) -> ByteString -> Maybe Int
findIndices, -- :: (Word8 -> Bool) -> ByteString -> [Int]
count, -- :: Word8 -> ByteString -> Int
-- * Zipping and unzipping ByteStrings
zip, -- :: ByteString -> ByteString -> [(Word8,Word8)]
zipWith, -- :: (Word8 -> Word8 -> c) -> ByteString -> ByteString -> [c]
unzip, -- :: [(Word8,Word8)] -> (ByteString,ByteString)
-- * Ordered ByteStrings
sort, -- :: ByteString -> ByteString
-- * Low level conversions
-- ** Copying ByteStrings
copy, -- :: ByteString -> ByteString
-- ** Packing 'CString's and pointers
packCString, -- :: CString -> IO ByteString
packCStringLen, -- :: CStringLen -> IO ByteString
-- ** Using ByteStrings as 'CString's
useAsCString, -- :: ByteString -> (CString -> IO a) -> IO a
useAsCStringLen, -- :: ByteString -> (CStringLen -> IO a) -> IO a
-- * I\/O with 'ByteString's
-- ** Standard input and output
getLine, -- :: IO ByteString
getContents, -- :: IO ByteString
putStr, -- :: ByteString -> IO ()
putStrLn, -- :: ByteString -> IO ()
interact, -- :: (ByteString -> ByteString) -> IO ()
-- ** Files
readFile, -- :: FilePath -> IO ByteString
writeFile, -- :: FilePath -> ByteString -> IO ()
appendFile, -- :: FilePath -> ByteString -> IO ()
-- ** I\/O with Handles
hGetLine, -- :: Handle -> IO ByteString
hGetContents, -- :: Handle -> IO ByteString
hGet, -- :: Handle -> Int -> IO ByteString
hGetSome, -- :: Handle -> Int -> IO ByteString
hGetNonBlocking, -- :: Handle -> Int -> IO ByteString
hPut, -- :: Handle -> ByteString -> IO ()
hPutNonBlocking, -- :: Handle -> ByteString -> IO ByteString
hPutStr, -- :: Handle -> ByteString -> IO ()
hPutStrLn, -- :: Handle -> ByteString -> IO ()
breakByte
) where
import qualified Prelude as P
import Prelude hiding (reverse,head,tail,last,init,null
,length,map,lines,foldl,foldr,unlines
,concat,any,take,drop,splitAt,takeWhile
,dropWhile,span,break,elem,filter,maximum
,minimum,all,concatMap,foldl1,foldr1
,scanl,scanl1,scanr,scanr1
,readFile,writeFile,appendFile,replicate
,getContents,getLine,putStr,putStrLn,interact
,zip,zipWith,unzip,notElem
#if !MIN_VERSION_base(4,6,0)
,catch
#endif
)
#if MIN_VERSION_base(4,7,0)
import Data.Bits (finiteBitSize, shiftL, (.|.), (.&.))
#else
import Data.Bits (bitSize, shiftL, (.|.), (.&.))
#endif
import Data.ByteString.Internal
import Data.ByteString.Unsafe
import qualified Data.List as List
import Data.Word (Word8)
import Data.Maybe (isJust)
import Control.Exception (IOException, catch, finally, assert, throwIO)
import Control.Monad (when)
import Foreign.C.String (CString, CStringLen)
import Foreign.C.Types (CSize)
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr, touchForeignPtr)
#if MIN_VERSION_base(4,5,0)
import Foreign.ForeignPtr.Unsafe(unsafeForeignPtrToPtr)
#else
import Foreign.ForeignPtr (unsafeForeignPtrToPtr)
#endif
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Array (allocaArray)
import Foreign.Ptr
import Foreign.Storable (Storable(..))
-- hGetBuf and hPutBuf not available in yhc or nhc
import System.IO (stdin,stdout,hClose,hFileSize
,hGetBuf,hPutBuf,hGetBufNonBlocking
,hPutBufNonBlocking,withBinaryFile
,IOMode(..))
import System.IO.Error (mkIOError, illegalOperationErrorType)
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (Monoid(..))
#endif
#if MIN_VERSION_base(4,3,0)
import System.IO (hGetBufSome)
#else
import System.IO (hWaitForInput, hIsEOF)
#endif
import Data.IORef
import GHC.IO.Handle.Internals
import GHC.IO.Handle.Types
import GHC.IO.Buffer
import GHC.IO.BufferedIO as Buffered
import GHC.IO (unsafePerformIO, unsafeDupablePerformIO)
import Data.Char (ord)
import Foreign.Marshal.Utils (copyBytes)
import GHC.Prim (Word#)
import GHC.Base (build)
import GHC.Word hiding (Word8)
#if !(MIN_VERSION_base(4,7,0))
finiteBitSize = bitSize
#endif
-- -----------------------------------------------------------------------------
-- Introducing and eliminating 'ByteString's
-- | /O(1)/ The empty 'ByteString'
empty :: ByteString
empty = PS nullForeignPtr 0 0
-- | /O(1)/ Convert a 'Word8' into a 'ByteString'
singleton :: Word8 -> ByteString
singleton c = unsafeCreate 1 $ \p -> poke p c
{-# INLINE [1] singleton #-}
-- Inline [1] for intercalate rule
--
-- XXX The use of unsafePerformIO in allocating functions (unsafeCreate) is critical!
--
-- Otherwise:
--
-- singleton 255 `compare` singleton 127
--
-- is compiled to:
--
-- case mallocByteString 2 of
-- ForeignPtr f internals ->
-- case writeWord8OffAddr# f 0 255 of _ ->
-- case writeWord8OffAddr# f 0 127 of _ ->
-- case eqAddr# f f of
-- False -> case compare (GHC.Prim.plusAddr# f 0)
-- (GHC.Prim.plusAddr# f 0)
--
--
-- | /O(n)/ Convert a @['Word8']@ into a 'ByteString'.
--
-- For applications with large numbers of string literals, 'pack' can be a
-- bottleneck. In such cases, consider using 'unsafePackAddress' (GHC only).
pack :: [Word8] -> ByteString
pack = packBytes
-- | /O(n)/ Converts a 'ByteString' to a @['Word8']@.
unpack :: ByteString -> [Word8]
unpack bs = build (unpackFoldr bs)
{-# INLINE unpack #-}
--
-- Have unpack fuse with good list consumers
--
unpackFoldr :: ByteString -> (Word8 -> a -> a) -> a -> a
unpackFoldr bs k z = foldr k z bs
{-# INLINE [0] unpackFoldr #-}
{-# RULES
"ByteString unpack-list" [1] forall bs .
unpackFoldr bs (:) [] = unpackBytes bs
#-}
-- ---------------------------------------------------------------------
-- Basic interface
-- | /O(1)/ Test whether a ByteString is empty.
null :: ByteString -> Bool
null (PS _ _ l) = assert (l >= 0) $ l <= 0
{-# INLINE null #-}
-- ---------------------------------------------------------------------
-- | /O(1)/ 'length' returns the length of a ByteString as an 'Int'.
length :: ByteString -> Int
length (PS _ _ l) = assert (l >= 0) l
{-# INLINE length #-}
------------------------------------------------------------------------
infixr 5 `cons` --same as list (:)
infixl 5 `snoc`
-- | /O(n)/ 'cons' is analogous to (:) for lists, but of different
-- complexity, as it requires making a copy.
cons :: Word8 -> ByteString -> ByteString
cons c (PS x s l) = unsafeCreate (l+1) $ \p -> withForeignPtr x $ \f -> do
poke p c
memcpy (p `plusPtr` 1) (f `plusPtr` s) (fromIntegral l)
{-# INLINE cons #-}
-- | /O(n)/ Append a byte to the end of a 'ByteString'
snoc :: ByteString -> Word8 -> ByteString
snoc (PS x s l) c = unsafeCreate (l+1) $ \p -> withForeignPtr x $ \f -> do
memcpy p (f `plusPtr` s) (fromIntegral l)
poke (p `plusPtr` l) c
{-# INLINE snoc #-}
-- todo fuse
-- | /O(1)/ Extract the first element of a ByteString, which must be non-empty.
-- An exception will be thrown in the case of an empty ByteString.
head :: ByteString -> Word8
head (PS x s l)
| l <= 0 = errorEmptyList "head"
| otherwise = accursedUnutterablePerformIO $ withForeignPtr x $ \p -> peekByteOff p s
{-# INLINE head #-}
-- | /O(1)/ Extract the elements after the head of a ByteString, which must be non-empty.
-- An exception will be thrown in the case of an empty ByteString.
tail :: ByteString -> ByteString
tail (PS p s l)
| l <= 0 = errorEmptyList "tail"
| otherwise = PS p (s+1) (l-1)
{-# INLINE tail #-}
-- | /O(1)/ Extract the head and tail of a ByteString, returning Nothing
-- if it is empty.
uncons :: ByteString -> Maybe (Word8, ByteString)
uncons (PS x s l)
| l <= 0 = Nothing
| otherwise = Just (accursedUnutterablePerformIO $ withForeignPtr x
$ \p -> peekByteOff p s,
PS x (s+1) (l-1))
{-# INLINE uncons #-}
-- | /O(1)/ Extract the last element of a ByteString, which must be finite and non-empty.
-- An exception will be thrown in the case of an empty ByteString.
last :: ByteString -> Word8
last ps@(PS x s l)
| null ps = errorEmptyList "last"
| otherwise = accursedUnutterablePerformIO $
withForeignPtr x $ \p -> peekByteOff p (s+l-1)
{-# INLINE last #-}
-- | /O(1)/ Return all the elements of a 'ByteString' except the last one.
-- An exception will be thrown in the case of an empty ByteString.
init :: ByteString -> ByteString
init ps@(PS p s l)
| null ps = errorEmptyList "init"
| otherwise = PS p s (l-1)
{-# INLINE init #-}
-- | /O(1)/ Extract the 'init' and 'last' of a ByteString, returning Nothing
-- if it is empty.
unsnoc :: ByteString -> Maybe (ByteString, Word8)
unsnoc (PS x s l)
| l <= 0 = Nothing
| otherwise = Just (PS x s (l-1),
accursedUnutterablePerformIO $
withForeignPtr x $ \p -> peekByteOff p (s+l-1))
{-# INLINE unsnoc #-}
-- | /O(n)/ Append two ByteStrings
append :: ByteString -> ByteString -> ByteString
append = mappend
{-# INLINE append #-}
-- ---------------------------------------------------------------------
-- Transformations
-- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each
-- element of @xs@.
map :: (Word8 -> Word8) -> ByteString -> ByteString
map f (PS fp s len) = unsafeDupablePerformIO $ withForeignPtr fp $ \a ->
create len $ map_ 0 (a `plusPtr` s)
where
map_ :: Int -> Ptr Word8 -> Ptr Word8 -> IO ()
map_ !n !p1 !p2
| n >= len = return ()
| otherwise = do
x <- peekByteOff p1 n
pokeByteOff p2 n (f x)
map_ (n+1) p1 p2
{-# INLINE map #-}
-- | /O(n)/ 'reverse' @xs@ efficiently returns the elements of @xs@ in reverse order.
reverse :: ByteString -> ByteString
reverse (PS x s l) = unsafeCreate l $ \p -> withForeignPtr x $ \f ->
c_reverse p (f `plusPtr` s) (fromIntegral l)
-- | /O(n)/ The 'intersperse' function takes a 'Word8' and a
-- 'ByteString' and \`intersperses\' that byte between the elements of
-- the 'ByteString'. It is analogous to the intersperse function on
-- Lists.
intersperse :: Word8 -> ByteString -> ByteString
intersperse c ps@(PS x s l)
| length ps < 2 = ps
| otherwise = unsafeCreate (2*l-1) $ \p -> withForeignPtr x $ \f ->
c_intersperse p (f `plusPtr` s) (fromIntegral l) c
-- | The 'transpose' function transposes the rows and columns of its
-- 'ByteString' argument.
transpose :: [ByteString] -> [ByteString]
transpose ps = P.map pack . List.transpose . P.map unpack $ ps
-- ---------------------------------------------------------------------
-- Reducing 'ByteString's
-- | 'foldl', applied to a binary operator, a starting value (typically
-- the left-identity of the operator), and a ByteString, reduces the
-- ByteString using the binary operator, from left to right.
--
foldl :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl f z (PS fp off len) =
let p = unsafeForeignPtrToPtr fp
in go (p `plusPtr` (off+len-1)) (p `plusPtr` (off-1))
where
-- not tail recursive; traverses array right to left
go !p !q | p == q = z
| otherwise = let !x = accursedUnutterablePerformIO $ do
x' <- peek p
touchForeignPtr fp
return x'
in f (go (p `plusPtr` (-1)) q) x
{-# INLINE foldl #-}
-- | 'foldl'' is like 'foldl', but strict in the accumulator.
--
foldl' :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl' f v (PS fp off len) =
accursedUnutterablePerformIO $ withForeignPtr fp $ \p ->
go v (p `plusPtr` off) (p `plusPtr` (off+len))
where
-- tail recursive; traverses array left to right
go !z !p !q | p == q = return z
| otherwise = do x <- peek p
go (f z x) (p `plusPtr` 1) q
{-# INLINE foldl' #-}
-- | 'foldr', applied to a binary operator, a starting value
-- (typically the right-identity of the operator), and a ByteString,
-- reduces the ByteString using the binary operator, from right to left.
foldr :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr k z (PS fp off len) =
let p = unsafeForeignPtrToPtr fp
in go (p `plusPtr` off) (p `plusPtr` (off+len))
where
-- not tail recursive; traverses array left to right
go !p !q | p == q = z
| otherwise = let !x = accursedUnutterablePerformIO $ do
x' <- peek p
touchForeignPtr fp
return x'
in k x (go (p `plusPtr` 1) q)
{-# INLINE foldr #-}
-- | 'foldr'' is like 'foldr', but strict in the accumulator.
foldr' :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr' k v (PS fp off len) =
accursedUnutterablePerformIO $ withForeignPtr fp $ \p ->
go v (p `plusPtr` (off+len-1)) (p `plusPtr` (off-1))
where
-- tail recursive; traverses array right to left
go !z !p !q | p == q = return z
| otherwise = do x <- peek p
go (k x z) (p `plusPtr` (-1)) q
{-# INLINE foldr' #-}
-- | 'foldl1' is a variant of 'foldl' that has no starting value
-- argument, and thus must be applied to non-empty 'ByteStrings'.
-- An exception will be thrown in the case of an empty ByteString.
foldl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldl1 f ps
| null ps = errorEmptyList "foldl1"
| otherwise = foldl f (unsafeHead ps) (unsafeTail ps)
{-# INLINE foldl1 #-}
-- | 'foldl1'' is like 'foldl1', but strict in the accumulator.
-- An exception will be thrown in the case of an empty ByteString.
foldl1' :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldl1' f ps
| null ps = errorEmptyList "foldl1'"
| otherwise = foldl' f (unsafeHead ps) (unsafeTail ps)
{-# INLINE foldl1' #-}
-- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
-- and thus must be applied to non-empty 'ByteString's
-- An exception will be thrown in the case of an empty ByteString.
foldr1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr1 f ps
| null ps = errorEmptyList "foldr1"
| otherwise = foldr f (unsafeLast ps) (unsafeInit ps)
{-# INLINE foldr1 #-}
-- | 'foldr1'' is a variant of 'foldr1', but is strict in the
-- accumulator.
foldr1' :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr1' f ps
| null ps = errorEmptyList "foldr1"
| otherwise = foldr' f (unsafeLast ps) (unsafeInit ps)
{-# INLINE foldr1' #-}
-- ---------------------------------------------------------------------
-- Special folds
-- | /O(n)/ Concatenate a list of ByteStrings.
concat :: [ByteString] -> ByteString
concat = mconcat
-- | Map a function over a 'ByteString' and concatenate the results
concatMap :: (Word8 -> ByteString) -> ByteString -> ByteString
concatMap f = concat . foldr ((:) . f) []
-- foldr (append . f) empty
-- | /O(n)/ Applied to a predicate and a ByteString, 'any' determines if
-- any element of the 'ByteString' satisfies the predicate.
any :: (Word8 -> Bool) -> ByteString -> Bool
any _ (PS _ _ 0) = False
any f (PS x s l) = accursedUnutterablePerformIO $ withForeignPtr x $ \ptr ->
go (ptr `plusPtr` s) (ptr `plusPtr` (s+l))
where
go !p !q | p == q = return False
| otherwise = do c <- peek p
if f c then return True
else go (p `plusPtr` 1) q
{-# INLINE any #-}
-- todo fuse
-- | /O(n)/ Applied to a predicate and a 'ByteString', 'all' determines
-- if all elements of the 'ByteString' satisfy the predicate.
all :: (Word8 -> Bool) -> ByteString -> Bool
all _ (PS _ _ 0) = True
all f (PS x s l) = accursedUnutterablePerformIO $ withForeignPtr x $ \ptr ->
go (ptr `plusPtr` s) (ptr `plusPtr` (s+l))
where
go !p !q | p == q = return True -- end of list
| otherwise = do c <- peek p
if f c
then go (p `plusPtr` 1) q
else return False
{-# INLINE all #-}
------------------------------------------------------------------------
-- | /O(n)/ 'maximum' returns the maximum value from a 'ByteString'
-- This function will fuse.
-- An exception will be thrown in the case of an empty ByteString.
maximum :: ByteString -> Word8
maximum xs@(PS x s l)
| null xs = errorEmptyList "maximum"
| otherwise = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
c_maximum (p `plusPtr` s) (fromIntegral l)
{-# INLINE maximum #-}
-- | /O(n)/ 'minimum' returns the minimum value from a 'ByteString'
-- This function will fuse.
-- An exception will be thrown in the case of an empty ByteString.
minimum :: ByteString -> Word8
minimum xs@(PS x s l)
| null xs = errorEmptyList "minimum"
| otherwise = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
c_minimum (p `plusPtr` s) (fromIntegral l)
{-# INLINE minimum #-}
------------------------------------------------------------------------
-- | The 'mapAccumL' function behaves like a combination of 'map' and
-- 'foldl'; it applies a function to each element of a ByteString,
-- passing an accumulating parameter from left to right, and returning a
-- final value of this accumulator together with the new list.
mapAccumL :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
mapAccumL f acc (PS fp o len) = unsafeDupablePerformIO $ withForeignPtr fp $ \a -> do
gp <- mallocByteString len
acc' <- withForeignPtr gp $ \p -> mapAccumL_ acc 0 (a `plusPtr` o) p
return (acc', PS gp 0 len)
where
mapAccumL_ !s !n !p1 !p2
| n >= len = return s
| otherwise = do
x <- peekByteOff p1 n
let (s', y) = f s x
pokeByteOff p2 n y
mapAccumL_ s' (n+1) p1 p2
{-# INLINE mapAccumL #-}
-- | The 'mapAccumR' function behaves like a combination of 'map' and
-- 'foldr'; it applies a function to each element of a ByteString,
-- passing an accumulating parameter from right to left, and returning a
-- final value of this accumulator together with the new ByteString.
mapAccumR :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
mapAccumR f acc (PS fp o len) = unsafeDupablePerformIO $ withForeignPtr fp $ \a -> do
gp <- mallocByteString len
acc' <- withForeignPtr gp $ \p -> mapAccumR_ acc (len-1) (a `plusPtr` o) p
return $! (acc', PS gp 0 len)
where
mapAccumR_ !s !n !p !q
| n < 0 = return s
| otherwise = do
x <- peekByteOff p n
let (s', y) = f s x
pokeByteOff q n y
mapAccumR_ s' (n-1) p q
{-# INLINE mapAccumR #-}
-- ---------------------------------------------------------------------
-- Building ByteStrings
-- | 'scanl' is similar to 'foldl', but returns a list of successive
-- reduced values from the left. This function will fuse.
--
-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--
-- Note that
--
-- > last (scanl f z xs) == foldl f z xs.
--
scanl :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanl f v (PS fp s len) = unsafeDupablePerformIO $ withForeignPtr fp $ \a ->
create (len+1) $ \q -> do
poke q v
scanl_ v 0 (a `plusPtr` s) (q `plusPtr` 1)
where
scanl_ !z !n !p !q
| n >= len = return ()
| otherwise = do
x <- peekByteOff p n
let z' = f z x
pokeByteOff q n z'
scanl_ z' (n+1) p q
{-# INLINE scanl #-}
-- n.b. haskell's List scan returns a list one bigger than the
-- input, so we need to snoc here to get some extra space, however,
-- it breaks map/up fusion (i.e. scanl . map no longer fuses)
-- | 'scanl1' is a variant of 'scanl' that has no starting value argument.
-- This function will fuse.
--
-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
scanl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
scanl1 f ps
| null ps = empty
| otherwise = scanl f (unsafeHead ps) (unsafeTail ps)
{-# INLINE scanl1 #-}
-- | scanr is the right-to-left dual of scanl.
scanr :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanr f v (PS fp s len) = unsafeDupablePerformIO $ withForeignPtr fp $ \a ->
create (len+1) $ \q -> do
poke (q `plusPtr` len) v
scanr_ v (len-1) (a `plusPtr` s) q
where
scanr_ !z !n !p !q
| n < 0 = return ()
| otherwise = do
x <- peekByteOff p n
let z' = f x z
pokeByteOff q n z'
scanr_ z' (n-1) p q
{-# INLINE scanr #-}
-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
scanr1 :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
scanr1 f ps
| null ps = empty
| otherwise = scanr f (unsafeLast ps) (unsafeInit ps)
{-# INLINE scanr1 #-}
-- ---------------------------------------------------------------------
-- Unfolds and replicates
-- | /O(n)/ 'replicate' @n x@ is a ByteString of length @n@ with @x@
-- the value of every element. The following holds:
--
-- > replicate w c = unfoldr w (\u -> Just (u,u)) c
--
-- This implemenation uses @memset(3)@
replicate :: Int -> Word8 -> ByteString
replicate w c
| w <= 0 = empty
| otherwise = unsafeCreate w $ \ptr ->
memset ptr c (fromIntegral w) >> return ()
-- | /O(n)/, where /n/ is the length of the result. The 'unfoldr'
-- function is analogous to the List \'unfoldr\'. 'unfoldr' builds a
-- ByteString from a seed value. The function takes the element and
-- returns 'Nothing' if it is done producing the ByteString or returns
-- 'Just' @(a,b)@, in which case, @a@ is the next byte in the string,
-- and @b@ is the seed value for further production.
--
-- Examples:
--
-- > unfoldr (\x -> if x <= 5 then Just (x, x + 1) else Nothing) 0
-- > == pack [0, 1, 2, 3, 4, 5]
--
unfoldr :: (a -> Maybe (Word8, a)) -> a -> ByteString
unfoldr f = concat . unfoldChunk 32 64
where unfoldChunk n n' x =
case unfoldrN n f x of
(s, Nothing) -> s : []
(s, Just x') -> s : unfoldChunk n' (n+n') x'
{-# INLINE unfoldr #-}
-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a ByteString from a seed
-- value. However, the length of the result is limited by the first
-- argument to 'unfoldrN'. This function is more efficient than 'unfoldr'
-- when the maximum length of the result is known.
--
-- The following equation relates 'unfoldrN' and 'unfoldr':
--
-- > fst (unfoldrN n f s) == take n (unfoldr f s)
--
unfoldrN :: Int -> (a -> Maybe (Word8, a)) -> a -> (ByteString, Maybe a)
unfoldrN i f x0
| i < 0 = (empty, Just x0)
| otherwise = unsafePerformIO $ createAndTrim' i $ \p -> go p x0 0
where
go !p !x !n
| n == i = return (0, n, Just x)
| otherwise = case f x of
Nothing -> return (0, n, Nothing)
Just (w,x') -> do poke p w
go (p `plusPtr` 1) x' (n+1)
{-# INLINE unfoldrN #-}
-- ---------------------------------------------------------------------
-- Substrings
-- | /O(1)/ 'take' @n@, applied to a ByteString @xs@, returns the prefix
-- of @xs@ of length @n@, or @xs@ itself if @n > 'length' xs@.
take :: Int -> ByteString -> ByteString
take n ps@(PS x s l)
| n <= 0 = empty
| n >= l = ps
| otherwise = PS x s n
{-# INLINE take #-}
-- | /O(1)/ 'drop' @n xs@ returns the suffix of @xs@ after the first @n@
-- elements, or @[]@ if @n > 'length' xs@.
drop :: Int -> ByteString -> ByteString
drop n ps@(PS x s l)
| n <= 0 = ps
| n >= l = empty
| otherwise = PS x (s+n) (l-n)
{-# INLINE drop #-}
-- | /O(1)/ 'splitAt' @n xs@ is equivalent to @('take' n xs, 'drop' n xs)@.
splitAt :: Int -> ByteString -> (ByteString, ByteString)
splitAt n ps@(PS x s l)
| n <= 0 = (empty, ps)
| n >= l = (ps, empty)
| otherwise = (PS x s n, PS x (s+n) (l-n))
{-# INLINE splitAt #-}
-- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@,
-- returns the longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@.
takeWhile :: (Word8 -> Bool) -> ByteString -> ByteString
takeWhile f ps = unsafeTake (findIndexOrEnd (not . f) ps) ps
{-# INLINE takeWhile #-}
-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
dropWhile :: (Word8 -> Bool) -> ByteString -> ByteString
dropWhile f ps = unsafeDrop (findIndexOrEnd (not . f) ps) ps
{-# INLINE dropWhile #-}
-- instead of findIndexOrEnd, we could use memchr here.
-- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
--
-- Under GHC, a rewrite rule will transform break (==) into a
-- call to the specialised breakByte:
--
-- > break ((==) x) = breakByte x
-- > break (==x) = breakByte x
--
break :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
break p ps = case findIndexOrEnd p ps of n -> (unsafeTake n ps, unsafeDrop n ps)
{-# INLINE [1] break #-}
-- See bytestring #70
#if MIN_VERSION_base(4,9,0)
{-# RULES
"ByteString specialise break (x ==)" forall x.
break (x `eqWord8`) = breakByte x
"ByteString specialise break (== x)" forall x.
break (`eqWord8` x) = breakByte x
#-}
#else
{-# RULES
"ByteString specialise break (x ==)" forall x.
break (x ==) = breakByte x
"ByteString specialise break (== x)" forall x.
break (== x) = breakByte x
#-}
#endif
-- INTERNAL:
-- | 'breakByte' breaks its ByteString argument at the first occurence
-- of the specified byte. It is more efficient than 'break' as it is
-- implemented with @memchr(3)@. I.e.
--
-- > break (=='c') "abcd" == breakByte 'c' "abcd"
--
breakByte :: Word8 -> ByteString -> (ByteString, ByteString)
breakByte c p = case elemIndex c p of
Nothing -> (p,empty)
Just n -> (unsafeTake n p, unsafeDrop n p)
{-# INLINE breakByte #-}
{-# DEPRECATED breakByte "It is an internal function and should never have been exported. Use 'break (== x)' instead. (There are rewrite rules that handle this special case of 'break'.)" #-}
-- | 'breakEnd' behaves like 'break' but from the end of the 'ByteString'
--
-- breakEnd p == spanEnd (not.p)
breakEnd :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
breakEnd p ps = splitAt (findFromEndUntil p ps) ps
-- | 'span' @p xs@ breaks the ByteString into two segments. It is
-- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
span :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
span p ps = break (not . p) ps
{-# INLINE [1] span #-}
-- | 'spanByte' breaks its ByteString argument at the first
-- occurence of a byte other than its argument. It is more efficient
-- than 'span (==)'
--
-- > span (=='c') "abcd" == spanByte 'c' "abcd"
--
spanByte :: Word8 -> ByteString -> (ByteString, ByteString)
spanByte c ps@(PS x s l) =
accursedUnutterablePerformIO $
withForeignPtr x $ \p ->
go (p `plusPtr` s) 0
where
go !p !i | i >= l = return (ps, empty)
| otherwise = do c' <- peekByteOff p i
if c /= c'
then return (unsafeTake i ps, unsafeDrop i ps)
else go p (i+1)
{-# INLINE spanByte #-}
-- See bytestring #70
#if MIN_VERSION_base(4,9,0)
{-# RULES
"ByteString specialise span (x ==)" forall x.
span (x `eqWord8`) = spanByte x
"ByteString specialise span (== x)" forall x.
span (`eqWord8` x) = spanByte x
#-}
#else
{-# RULES
"ByteString specialise span (x ==)" forall x.
span (x ==) = spanByte x
"ByteString specialise span (== x)" forall x.
span (== x) = spanByte x
#-}
#endif
-- | 'spanEnd' behaves like 'span' but from the end of the 'ByteString'.
-- We have
--
-- > spanEnd (not.isSpace) "x y z" == ("x y ","z")
--
-- and
--
-- > spanEnd (not . isSpace) ps
-- > ==
-- > let (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x)
--
spanEnd :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
spanEnd p ps = splitAt (findFromEndUntil (not.p) ps) ps
-- | /O(n)/ Splits a 'ByteString' into components delimited by
-- separators, where the predicate returns True for a separator element.
-- The resulting components do not contain the separators. Two adjacent
-- separators result in an empty component in the output. eg.
--
-- > splitWith (=='a') "aabbaca" == ["","","bb","c",""]
-- > splitWith (=='a') [] == []
--
splitWith :: (Word8 -> Bool) -> ByteString -> [ByteString]
splitWith _pred (PS _ _ 0) = []
splitWith pred_ (PS fp off len) = splitWith0 pred# off len fp
where pred# c# = pred_ (W8# c#)
splitWith0 !pred' !off' !len' !fp' =
accursedUnutterablePerformIO $
withForeignPtr fp $ \p ->
splitLoop pred' p 0 off' len' fp'
splitLoop :: (Word# -> Bool)
-> Ptr Word8
-> Int -> Int -> Int
-> ForeignPtr Word8
-> IO [ByteString]
splitLoop pred' p idx' off' len' fp'
| idx' >= len' = return [PS fp' off' idx']
| otherwise = do
w <- peekElemOff p (off'+idx')
if pred' (case w of W8# w# -> w#)
then return (PS fp' off' idx' :
splitWith0 pred' (off'+idx'+1) (len'-idx'-1) fp')
else splitLoop pred' p (idx'+1) off' len' fp'
{-# INLINE splitWith #-}
-- | /O(n)/ Break a 'ByteString' into pieces separated by the byte
-- argument, consuming the delimiter. I.e.
--
-- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
-- > split 'a' "aXaXaXa" == ["","X","X","X",""]
-- > split 'x' "x" == ["",""]
--
-- and
--
-- > intercalate [c] . split c == id
-- > split == splitWith . (==)
--
-- As for all splitting functions in this library, this function does
-- not copy the substrings, it just constructs new 'ByteStrings' that
-- are slices of the original.
--
split :: Word8 -> ByteString -> [ByteString]
split _ (PS _ _ 0) = []
split w (PS x s l) = loop 0
where
loop !n =
let q = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
memchr (p `plusPtr` (s+n))
w (fromIntegral (l-n))
in if q == nullPtr
then [PS x (s+n) (l-n)]
else let i = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
return (q `minusPtr` (p `plusPtr` s))
in PS x (s+n) (i-n) : loop (i+1)
{-# INLINE split #-}
-- | The 'group' function takes a ByteString and returns a list of
-- ByteStrings such that the concatenation of the result is equal to the
-- argument. Moreover, each sublist in the result contains only equal
-- elements. For example,
--
-- > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
--
-- It is a special case of 'groupBy', which allows the programmer to
-- supply their own equality test. It is about 40% faster than
-- /groupBy (==)/
group :: ByteString -> [ByteString]
group xs
| null xs = []
| otherwise = ys : group zs
where
(ys, zs) = spanByte (unsafeHead xs) xs
-- | The 'groupBy' function is the non-overloaded version of 'group'.
groupBy :: (Word8 -> Word8 -> Bool) -> ByteString -> [ByteString]
groupBy k xs
| null xs = []
| otherwise = unsafeTake n xs : groupBy k (unsafeDrop n xs)
where
n = 1 + findIndexOrEnd (not . k (unsafeHead xs)) (unsafeTail xs)
-- | /O(n)/ The 'intercalate' function takes a 'ByteString' and a list of
-- 'ByteString's and concatenates the list after interspersing the first
-- argument between each element of the list.
intercalate :: ByteString -> [ByteString] -> ByteString
intercalate s = concat . List.intersperse s
{-# INLINE [1] intercalate #-}
{-# RULES
"ByteString specialise intercalate c -> intercalateByte" forall c s1 s2 .
intercalate (singleton c) [s1, s2] = intercalateWithByte c s1 s2
#-}
-- | /O(n)/ intercalateWithByte. An efficient way to join to two ByteStrings
-- with a char. Around 4 times faster than the generalised join.
--
intercalateWithByte :: Word8 -> ByteString -> ByteString -> ByteString
intercalateWithByte c f@(PS ffp s l) g@(PS fgp t m) = unsafeCreate len $ \ptr ->
withForeignPtr ffp $ \fp ->
withForeignPtr fgp $ \gp -> do
memcpy ptr (fp `plusPtr` s) (fromIntegral l)
poke (ptr `plusPtr` l) c
memcpy (ptr `plusPtr` (l + 1)) (gp `plusPtr` t) (fromIntegral m)
where
len = length f + length g + 1
{-# INLINE intercalateWithByte #-}
-- ---------------------------------------------------------------------
-- Indexing ByteStrings
-- | /O(1)/ 'ByteString' index (subscript) operator, starting from 0.
index :: ByteString -> Int -> Word8
index ps n
| n < 0 = moduleError "index" ("negative index: " ++ show n)
| n >= length ps = moduleError "index" ("index too large: " ++ show n
++ ", length = " ++ show (length ps))
| otherwise = ps `unsafeIndex` n
{-# INLINE index #-}
-- | /O(n)/ The 'elemIndex' function returns the index of the first
-- element in the given 'ByteString' which is equal to the query
-- element, or 'Nothing' if there is no such element.
-- This implementation uses memchr(3).
elemIndex :: Word8 -> ByteString -> Maybe Int
elemIndex c (PS x s l) = accursedUnutterablePerformIO $ withForeignPtr x $ \p -> do
let p' = p `plusPtr` s
q <- memchr p' c (fromIntegral l)
return $! if q == nullPtr then Nothing else Just $! q `minusPtr` p'
{-# INLINE elemIndex #-}
-- | /O(n)/ The 'elemIndexEnd' function returns the last index of the
-- element in the given 'ByteString' which is equal to the query
-- element, or 'Nothing' if there is no such element. The following
-- holds:
--
-- > elemIndexEnd c xs ==
-- > (-) (length xs - 1) `fmap` elemIndex c (reverse xs)
--
elemIndexEnd :: Word8 -> ByteString -> Maybe Int
elemIndexEnd ch (PS x s l) = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
go (p `plusPtr` s) (l-1)
where
go !p !i | i < 0 = return Nothing
| otherwise = do ch' <- peekByteOff p i
if ch == ch'
then return $ Just i
else go p (i-1)
{-# INLINE elemIndexEnd #-}
-- | /O(n)/ The 'elemIndices' function extends 'elemIndex', by returning
-- the indices of all elements equal to the query element, in ascending order.
-- This implementation uses memchr(3).
elemIndices :: Word8 -> ByteString -> [Int]
elemIndices w (PS x s l) = loop 0
where
loop !n = let q = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
memchr (p `plusPtr` (n+s))
w (fromIntegral (l - n))
in if q == nullPtr
then []
else let i = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
return (q `minusPtr` (p `plusPtr` s))
in i : loop (i+1)
{-# INLINE elemIndices #-}
-- | count returns the number of times its argument appears in the ByteString
--
-- > count = length . elemIndices
--
-- But more efficiently than using length on the intermediate list.
count :: Word8 -> ByteString -> Int
count w (PS x s m) = accursedUnutterablePerformIO $ withForeignPtr x $ \p ->
fmap fromIntegral $ c_count (p `plusPtr` s) (fromIntegral m) w
{-# INLINE count #-}
-- | The 'findIndex' function takes a predicate and a 'ByteString' and
-- returns the index of the first element in the ByteString
-- satisfying the predicate.
findIndex :: (Word8 -> Bool) -> ByteString -> Maybe Int
findIndex k (PS x s l) = accursedUnutterablePerformIO $ withForeignPtr x $ \f -> go (f `plusPtr` s) 0
where
go !ptr !n | n >= l = return Nothing
| otherwise = do w <- peek ptr
if k w
then return (Just n)
else go (ptr `plusPtr` 1) (n+1)
{-# INLINE findIndex #-}
-- | The 'findIndices' function extends 'findIndex', by returning the
-- indices of all elements satisfying the predicate, in ascending order.
findIndices :: (Word8 -> Bool) -> ByteString -> [Int]
findIndices p ps = loop 0 ps
where
loop !n !qs | null qs = []
| p (unsafeHead qs) = n : loop (n+1) (unsafeTail qs)
| otherwise = loop (n+1) (unsafeTail qs)
-- ---------------------------------------------------------------------
-- Searching ByteStrings
-- | /O(n)/ 'elem' is the 'ByteString' membership predicate.
elem :: Word8 -> ByteString -> Bool
elem c ps = case elemIndex c ps of Nothing -> False ; _ -> True
{-# INLINE elem #-}
-- | /O(n)/ 'notElem' is the inverse of 'elem'
notElem :: Word8 -> ByteString -> Bool
notElem c ps = not (elem c ps)
{-# INLINE notElem #-}
-- | /O(n)/ 'filter', applied to a predicate and a ByteString,
-- returns a ByteString containing those characters that satisfy the
-- predicate.
filter :: (Word8 -> Bool) -> ByteString -> ByteString
filter k ps@(PS x s l)
| null ps = ps
| otherwise = unsafePerformIO $ createAndTrim l $ \p -> withForeignPtr x $ \f -> do
t <- go (f `plusPtr` s) p (f `plusPtr` (s + l))
return $! t `minusPtr` p -- actual length
where
go !f !t !end | f == end = return t
| otherwise = do
w <- peek f
if k w
then poke t w >> go (f `plusPtr` 1) (t `plusPtr` 1) end
else go (f `plusPtr` 1) t end
{-# INLINE filter #-}
{-
--
-- | /O(n)/ A first order equivalent of /filter . (==)/, for the common
-- case of filtering a single byte. It is more efficient to use
-- /filterByte/ in this case.
--
-- > filterByte == filter . (==)
--
-- filterByte is around 10x faster, and uses much less space, than its
-- filter equivalent
--
filterByte :: Word8 -> ByteString -> ByteString
filterByte w ps = replicate (count w ps) w
{-# INLINE filterByte #-}
{-# RULES
"ByteString specialise filter (== x)" forall x.
filter ((==) x) = filterByte x
"ByteString specialise filter (== x)" forall x.
filter (== x) = filterByte x
#-}
-}
-- | /O(n)/ The 'find' function takes a predicate and a ByteString,
-- and returns the first element in matching the predicate, or 'Nothing'
-- if there is no such element.
--
-- > find f p = case findIndex f p of Just n -> Just (p ! n) ; _ -> Nothing
--
find :: (Word8 -> Bool) -> ByteString -> Maybe Word8
find f p = case findIndex f p of
Just n -> Just (p `unsafeIndex` n)
_ -> Nothing
{-# INLINE find #-}
-- | /O(n)/ The 'partition' function takes a predicate a ByteString and returns
-- the pair of ByteStrings with elements which do and do not satisfy the
-- predicate, respectively; i.e.,
--
-- > partition p bs == (filter p xs, filter (not . p) xs)
--
partition :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
partition f s = unsafeDupablePerformIO $
do fp' <- mallocByteString len
withForeignPtr fp' $ \p ->
do let end = p `plusPtr` (len - 1)
mid <- sep 0 p end
rev mid end
let i = mid `minusPtr` p
return (PS fp' 0 i,
PS fp' i (len - i))
where
len = length s
incr = (`plusPtr` 1)
decr = (`plusPtr` (-1))
sep !i !p1 !p2
| i == len = return p1
| f w = do poke p1 w
sep (i + 1) (incr p1) p2
| otherwise = do poke p2 w
sep (i + 1) p1 (decr p2)
where
w = s `unsafeIndex` i
rev !p1 !p2
| p1 >= p2 = return ()
| otherwise = do a <- peek p1
b <- peek p2
poke p1 b
poke p2 a
rev (incr p1) (decr p2)
-- --------------------------------------------------------------------
-- Sarching for substrings
-- |/O(n)/ The 'isPrefixOf' function takes two ByteStrings and returns 'True'
-- if the first is a prefix of the second.
isPrefixOf :: ByteString -> ByteString -> Bool
isPrefixOf (PS x1 s1 l1) (PS x2 s2 l2)
| l1 == 0 = True
| l2 < l1 = False
| otherwise = accursedUnutterablePerformIO $ withForeignPtr x1 $ \p1 ->
withForeignPtr x2 $ \p2 -> do
i <- memcmp (p1 `plusPtr` s1) (p2 `plusPtr` s2) (fromIntegral l1)
return $! i == 0
-- | /O(n)/ The 'stripPrefix' function takes two ByteStrings and returns 'Just'
-- the remainder of the second iff the first is its prefix, and otherwise
-- 'Nothing'.
--
-- @since 0.10.8.0
stripPrefix :: ByteString -> ByteString -> Maybe ByteString
stripPrefix bs1@(PS _ _ l1) bs2
| bs1 `isPrefixOf` bs2 = Just (unsafeDrop l1 bs2)
| otherwise = Nothing
-- | /O(n)/ The 'isSuffixOf' function takes two ByteStrings and returns 'True'
-- iff the first is a suffix of the second.
--
-- The following holds:
--
-- > isSuffixOf x y == reverse x `isPrefixOf` reverse y
--
-- However, the real implemenation uses memcmp to compare the end of the
-- string only, with no reverse required..
isSuffixOf :: ByteString -> ByteString -> Bool
isSuffixOf (PS x1 s1 l1) (PS x2 s2 l2)
| l1 == 0 = True
| l2 < l1 = False
| otherwise = accursedUnutterablePerformIO $ withForeignPtr x1 $ \p1 ->
withForeignPtr x2 $ \p2 -> do
i <- memcmp (p1 `plusPtr` s1) (p2 `plusPtr` s2 `plusPtr` (l2 - l1)) (fromIntegral l1)
return $! i == 0
-- | /O(n)/ The 'stripSuffix' function takes two ByteStrings and returns 'Just'
-- the remainder of the second iff the first is its suffix, and otherwise
-- 'Nothing'.
stripSuffix :: ByteString -> ByteString -> Maybe ByteString
stripSuffix bs1@(PS _ _ l1) bs2@(PS _ _ l2)
| bs1 `isSuffixOf` bs2 = Just (unsafeTake (l2 - l1) bs2)
| otherwise = Nothing
-- | Check whether one string is a substring of another. @isInfixOf
-- p s@ is equivalent to @not (null (findSubstrings p s))@.
isInfixOf :: ByteString -> ByteString -> Bool
isInfixOf p s = isJust (findSubstring p s)
-- | Break a string on a substring, returning a pair of the part of the
-- string prior to the match, and the rest of the string.
--
-- The following relationships hold:
--
-- > break (== c) l == breakSubstring (singleton c) l
--
-- and:
--
-- > findSubstring s l ==
-- > if null s then Just 0
-- > else case breakSubstring s l of
-- > (x,y) | null y -> Nothing
-- > | otherwise -> Just (length x)
--
-- For example, to tokenise a string, dropping delimiters:
--
-- > tokenise x y = h : if null t then [] else tokenise x (drop (length x) t)
-- > where (h,t) = breakSubstring x y
--
-- To skip to the first occurence of a string:
--
-- > snd (breakSubstring x y)
--
-- To take the parts of a string before a delimiter:
--
-- > fst (breakSubstring x y)
--
-- Note that calling `breakSubstring x` does some preprocessing work, so
-- you should avoid unnecessarily duplicating breakSubstring calls with the same
-- pattern.
--
breakSubstring :: ByteString -- ^ String to search for
-> ByteString -- ^ String to search in
-> (ByteString,ByteString) -- ^ Head and tail of string broken at substring
breakSubstring pat =
case lp of
0 -> \src -> (empty,src)
1 -> breakByte (unsafeHead pat)
_ -> if lp * 8 <= finiteBitSize (0 :: Word)
then shift
else karpRabin
where
unsafeSplitAt i s = (unsafeTake i s, unsafeDrop i s)
lp = length pat
karpRabin :: ByteString -> (ByteString, ByteString)
karpRabin src
| length src < lp = (src,empty)
| otherwise = search (rollingHash $ unsafeTake lp src) lp
where
k = 2891336453 :: Word32
rollingHash = foldl' (\h b -> h * k + fromIntegral b) 0
hp = rollingHash pat
m = k ^ lp
get = fromIntegral . unsafeIndex src
search !hs !i
| hp == hs && pat == unsafeTake lp b = u
| length src <= i = (src,empty) -- not found
| otherwise = search hs' (i + 1)
where
u@(_, b) = unsafeSplitAt (i - lp) src
hs' = hs * k +
get i -
m * get (i - lp)
{-# INLINE karpRabin #-}
shift :: ByteString -> (ByteString, ByteString)
shift !src
| length src < lp = (src,empty)
| otherwise = search (intoWord $ unsafeTake lp src) lp
where
intoWord :: ByteString -> Word
intoWord = foldl' (\w b -> (w `shiftL` 8) .|. fromIntegral b) 0
wp = intoWord pat
mask = (1 `shiftL` (8 * lp)) - 1
search !w !i
| w == wp = unsafeSplitAt (i - lp) src
| length src <= i = (src, empty)
| otherwise = search w' (i + 1)
where
b = fromIntegral (unsafeIndex src i)
w' = mask .&. ((w `shiftL` 8) .|. b)
{-# INLINE shift #-}
-- | Get the first index of a substring in another string,
-- or 'Nothing' if the string is not found.
-- @findSubstring p s@ is equivalent to @listToMaybe (findSubstrings p s)@.
findSubstring :: ByteString -- ^ String to search for.
-> ByteString -- ^ String to seach in.
-> Maybe Int
findSubstring pat src
| null pat && null src = Just 0
| null b = Nothing
| otherwise = Just (length a)
where (a, b) = breakSubstring pat src
{-# DEPRECATED findSubstring "findSubstring is deprecated in favour of breakSubstring." #-}
-- | Find the indexes of all (possibly overlapping) occurences of a
-- substring in a string.
--
findSubstrings :: ByteString -- ^ String to search for.
-> ByteString -- ^ String to seach in.
-> [Int]
findSubstrings pat src
| null pat = [0 .. ls]
| otherwise = search 0
where
lp = length pat
ls = length src
search !n
| (n > ls - lp) || null b = []
| otherwise = let k = n + length a
in k : search (k + lp)
where
(a, b) = breakSubstring pat (unsafeDrop n src)
{-# DEPRECATED findSubstrings "findSubstrings is deprecated in favour of breakSubstring." #-}
-- ---------------------------------------------------------------------
-- Zipping
-- | /O(n)/ 'zip' takes two ByteStrings and returns a list of
-- corresponding pairs of bytes. If one input ByteString is short,
-- excess elements of the longer ByteString are discarded. This is
-- equivalent to a pair of 'unpack' operations.
zip :: ByteString -> ByteString -> [(Word8,Word8)]
zip ps qs
| null ps || null qs = []
| otherwise = (unsafeHead ps, unsafeHead qs) : zip (unsafeTail ps) (unsafeTail qs)
-- | 'zipWith' generalises 'zip' by zipping with the function given as
-- the first argument, instead of a tupling function. For example,
-- @'zipWith' (+)@ is applied to two ByteStrings to produce the list of
-- corresponding sums.
zipWith :: (Word8 -> Word8 -> a) -> ByteString -> ByteString -> [a]
zipWith f ps qs
| null ps || null qs = []
| otherwise = f (unsafeHead ps) (unsafeHead qs) : zipWith f (unsafeTail ps) (unsafeTail qs)
{-# NOINLINE [1] zipWith #-}
--
-- | A specialised version of zipWith for the common case of a
-- simultaneous map over two bytestrings, to build a 3rd. Rewrite rules
-- are used to automatically covert zipWith into zipWith' when a pack is
-- performed on the result of zipWith.
--
zipWith' :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
zipWith' f (PS fp s l) (PS fq t m) = unsafeDupablePerformIO $
withForeignPtr fp $ \a ->
withForeignPtr fq $ \b ->
create len $ zipWith_ 0 (a `plusPtr` s) (b `plusPtr` t)
where
zipWith_ :: Int -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO ()
zipWith_ !n !p1 !p2 !r
| n >= len = return ()
| otherwise = do
x <- peekByteOff p1 n
y <- peekByteOff p2 n
pokeByteOff r n (f x y)
zipWith_ (n+1) p1 p2 r
len = min l m
{-# INLINE zipWith' #-}
{-# RULES
"ByteString specialise zipWith" forall (f :: Word8 -> Word8 -> Word8) p q .
zipWith f p q = unpack (zipWith' f p q)
#-}
-- | /O(n)/ 'unzip' transforms a list of pairs of bytes into a pair of
-- ByteStrings. Note that this performs two 'pack' operations.
unzip :: [(Word8,Word8)] -> (ByteString,ByteString)
unzip ls = (pack (P.map fst ls), pack (P.map snd ls))
{-# INLINE unzip #-}
-- ---------------------------------------------------------------------
-- Special lists
-- | /O(n)/ Return all initial segments of the given 'ByteString', shortest first.
inits :: ByteString -> [ByteString]
inits (PS x s l) = [PS x s n | n <- [0..l]]
-- | /O(n)/ Return all final segments of the given 'ByteString', longest first.
tails :: ByteString -> [ByteString]
tails p | null p = [empty]
| otherwise = p : tails (unsafeTail p)
-- less efficent spacewise: tails (PS x s l) = [PS x (s+n) (l-n) | n <- [0..l]]
-- ---------------------------------------------------------------------
-- ** Ordered 'ByteString's
-- | /O(n)/ Sort a ByteString efficiently, using counting sort.
sort :: ByteString -> ByteString
sort (PS input s l) = unsafeCreate l $ \p -> allocaArray 256 $ \arr -> do
_ <- memset (castPtr arr) 0 (256 * fromIntegral (sizeOf (undefined :: CSize)))
withForeignPtr input (\x -> countOccurrences arr (x `plusPtr` s) l)
let go 256 !_ = return ()
go i !ptr = do n <- peekElemOff arr i
when (n /= 0) $ memset ptr (fromIntegral i) n >> return ()
go (i + 1) (ptr `plusPtr` fromIntegral n)
go 0 p
where
-- | Count the number of occurrences of each byte.
-- Used by 'sort'
--
countOccurrences :: Ptr CSize -> Ptr Word8 -> Int -> IO ()
countOccurrences !counts !str !len = go 0
where
go !i | i == len = return ()
| otherwise = do k <- fromIntegral `fmap` peekElemOff str i
x <- peekElemOff counts k
pokeElemOff counts k (x + 1)
go (i + 1)
-- ---------------------------------------------------------------------
-- Low level constructors
-- | /O(n) construction/ Use a @ByteString@ with a function requiring a
-- null-terminated @CString@. The @CString@ is a copy and will be freed
-- automatically; it must not be stored or used after the
-- subcomputation finishes.
useAsCString :: ByteString -> (CString -> IO a) -> IO a
useAsCString (PS fp o l) action =
allocaBytes (l+1) $ \buf ->
withForeignPtr fp $ \p -> do
memcpy buf (p `plusPtr` o) (fromIntegral l)
pokeByteOff buf l (0::Word8)
action (castPtr buf)
-- | /O(n) construction/ Use a @ByteString@ with a function requiring a @CStringLen@.
-- As for @useAsCString@ this function makes a copy of the original @ByteString@.
-- It must not be stored or used after the subcomputation finishes.
useAsCStringLen :: ByteString -> (CStringLen -> IO a) -> IO a
useAsCStringLen p@(PS _ _ l) f = useAsCString p $ \cstr -> f (cstr,l)
------------------------------------------------------------------------
-- | /O(n)./ Construct a new @ByteString@ from a @CString@. The
-- resulting @ByteString@ is an immutable copy of the original
-- @CString@, and is managed on the Haskell heap. The original
-- @CString@ must be null terminated.
packCString :: CString -> IO ByteString
packCString cstr = do
len <- c_strlen cstr
packCStringLen (cstr, fromIntegral len)
-- | /O(n)./ Construct a new @ByteString@ from a @CStringLen@. The
-- resulting @ByteString@ is an immutable copy of the original @CStringLen@.
-- The @ByteString@ is a normal Haskell value and will be managed on the
-- Haskell heap.
packCStringLen :: CStringLen -> IO ByteString
packCStringLen (cstr, len) | len >= 0 = create len $ \p ->
memcpy p (castPtr cstr) (fromIntegral len)
packCStringLen (_, len) =
moduleErrorIO "packCStringLen" ("negative length: " ++ show len)
------------------------------------------------------------------------
-- | /O(n)/ Make a copy of the 'ByteString' with its own storage.
-- This is mainly useful to allow the rest of the data pointed
-- to by the 'ByteString' to be garbage collected, for example
-- if a large string has been read in, and only a small part of it
-- is needed in the rest of the program.
--
copy :: ByteString -> ByteString
copy (PS x s l) = unsafeCreate l $ \p -> withForeignPtr x $ \f ->
memcpy p (f `plusPtr` s) (fromIntegral l)
-- ---------------------------------------------------------------------
-- Line IO
-- | Read a line from stdin.
getLine :: IO ByteString
getLine = hGetLine stdin
-- | Read a line from a handle
hGetLine :: Handle -> IO ByteString
hGetLine h =
wantReadableHandle_ "Data.ByteString.hGetLine" h $
\ h_@Handle__{haByteBuffer} -> do
flushCharReadBuffer h_
buf <- readIORef haByteBuffer
if isEmptyBuffer buf
then fill h_ buf 0 []
else haveBuf h_ buf 0 []
where
fill h_@Handle__{haByteBuffer,haDevice} buf !len xss = do
(r,buf') <- Buffered.fillReadBuffer haDevice buf
if r == 0
then do writeIORef haByteBuffer buf{ bufR=0, bufL=0 }
if len > 0
then mkBigPS len xss
else ioe_EOF
else haveBuf h_ buf' len xss
haveBuf h_@Handle__{haByteBuffer}
buf@Buffer{ bufRaw=raw, bufR=w, bufL=r }
len xss =
do
off <- findEOL r w raw
let new_len = len + off - r
xs <- mkPS raw r off
-- if eol == True, then off is the offset of the '\n'
-- otherwise off == w and the buffer is now empty.
if off /= w
then do if w == off + 1
then writeIORef haByteBuffer buf{ bufL=0, bufR=0 }
else writeIORef haByteBuffer buf{ bufL = off + 1 }
mkBigPS new_len (xs:xss)
else fill h_ buf{ bufL=0, bufR=0 } new_len (xs:xss)
-- find the end-of-line character, if there is one
findEOL r w raw
| r == w = return w
| otherwise = do
c <- readWord8Buf raw r
if c == fromIntegral (ord '\n')
then return r -- NB. not r+1: don't include the '\n'
else findEOL (r+1) w raw
mkPS :: RawBuffer Word8 -> Int -> Int -> IO ByteString
mkPS buf start end =
create len $ \p ->
withRawBuffer buf $ \pbuf -> copyBytes p (pbuf `plusPtr` start) len
where
len = end - start
mkBigPS :: Int -> [ByteString] -> IO ByteString
mkBigPS _ [ps] = return ps
mkBigPS _ pss = return $! concat (P.reverse pss)
-- ---------------------------------------------------------------------
-- Block IO
-- | Outputs a 'ByteString' to the specified 'Handle'.
hPut :: Handle -> ByteString -> IO ()
hPut _ (PS _ _ 0) = return ()
hPut h (PS ps s l) = withForeignPtr ps $ \p-> hPutBuf h (p `plusPtr` s) l
-- | Similar to 'hPut' except that it will never block. Instead it returns
-- any tail that did not get written. This tail may be 'empty' in the case that
-- the whole string was written, or the whole original string if nothing was
-- written. Partial writes are also possible.
--
-- Note: on Windows and with Haskell implementation other than GHC, this
-- function does not work correctly; it behaves identically to 'hPut'.
--
hPutNonBlocking :: Handle -> ByteString -> IO ByteString
hPutNonBlocking h bs@(PS ps s l) = do
bytesWritten <- withForeignPtr ps $ \p-> hPutBufNonBlocking h (p `plusPtr` s) l
return $! drop bytesWritten bs
-- | A synonym for @hPut@, for compatibility
hPutStr :: Handle -> ByteString -> IO ()
hPutStr = hPut
-- | Write a ByteString to a handle, appending a newline byte
hPutStrLn :: Handle -> ByteString -> IO ()
hPutStrLn h ps
| length ps < 1024 = hPut h (ps `snoc` 0x0a)
| otherwise = hPut h ps >> hPut h (singleton (0x0a)) -- don't copy
-- | Write a ByteString to stdout
putStr :: ByteString -> IO ()
putStr = hPut stdout
-- | Write a ByteString to stdout, appending a newline byte
putStrLn :: ByteString -> IO ()
putStrLn = hPutStrLn stdout
{-# DEPRECATED hPutStrLn
"Use Data.ByteString.Char8.hPutStrLn instead. (Functions that rely on ASCII encodings belong in Data.ByteString.Char8)"
#-}
{-# DEPRECATED putStrLn
"Use Data.ByteString.Char8.putStrLn instead. (Functions that rely on ASCII encodings belong in Data.ByteString.Char8)"
#-}
------------------------------------------------------------------------
-- Low level IO
-- | Read a 'ByteString' directly from the specified 'Handle'. This
-- is far more efficient than reading the characters into a 'String'
-- and then using 'pack'. First argument is the Handle to read from,
-- and the second is the number of bytes to read. It returns the bytes
-- read, up to n, or 'empty' if EOF has been reached.
--
-- 'hGet' is implemented in terms of 'hGetBuf'.
--
-- If the handle is a pipe or socket, and the writing end
-- is closed, 'hGet' will behave as if EOF was reached.
--
hGet :: Handle -> Int -> IO ByteString
hGet h i
| i > 0 = createAndTrim i $ \p -> hGetBuf h p i
| i == 0 = return empty
| otherwise = illegalBufferSize h "hGet" i
-- | hGetNonBlocking is similar to 'hGet', except that it will never block
-- waiting for data to become available, instead it returns only whatever data
-- is available. If there is no data available to be read, 'hGetNonBlocking'
-- returns 'empty'.
--
-- Note: on Windows and with Haskell implementation other than GHC, this
-- function does not work correctly; it behaves identically to 'hGet'.
--
hGetNonBlocking :: Handle -> Int -> IO ByteString
hGetNonBlocking h i
| i > 0 = createAndTrim i $ \p -> hGetBufNonBlocking h p i
| i == 0 = return empty
| otherwise = illegalBufferSize h "hGetNonBlocking" i
-- | Like 'hGet', except that a shorter 'ByteString' may be returned
-- if there are not enough bytes immediately available to satisfy the
-- whole request. 'hGetSome' only blocks if there is no data
-- available, and EOF has not yet been reached.
--
hGetSome :: Handle -> Int -> IO ByteString
hGetSome hh i
#if MIN_VERSION_base(4,3,0)
| i > 0 = createAndTrim i $ \p -> hGetBufSome hh p i
#else
| i > 0 = let
loop = do
s <- hGetNonBlocking hh i
if not (null s)
then return s
else do eof <- hIsEOF hh
if eof then return s
else hWaitForInput hh (-1) >> loop
-- for this to work correctly, the
-- Handle should be in binary mode
-- (see GHC ticket #3808)
in loop
#endif
| i == 0 = return empty
| otherwise = illegalBufferSize hh "hGetSome" i
illegalBufferSize :: Handle -> String -> Int -> IO a
illegalBufferSize handle fn sz =
ioError (mkIOError illegalOperationErrorType msg (Just handle) Nothing)
--TODO: System.IO uses InvalidArgument here, but it's not exported :-(
where
msg = fn ++ ": illegal ByteString size " ++ showsPrec 9 sz []
-- | Read a handle's entire contents strictly into a 'ByteString'.
--
-- This function reads chunks at a time, increasing the chunk size on each
-- read. The final string is then reallocated to the appropriate size. For
-- files > half of available memory, this may lead to memory exhaustion.
-- Consider using 'readFile' in this case.
--
-- The Handle is closed once the contents have been read,
-- or if an exception is thrown.
--
hGetContents :: Handle -> IO ByteString
hGetContents hnd = do
bs <- hGetContentsSizeHint hnd 1024 2048
`finally` hClose hnd
-- don't waste too much space for small files:
if length bs < 900
then return $! copy bs
else return bs
hGetContentsSizeHint :: Handle
-> Int -- ^ first read size
-> Int -- ^ initial buffer size increment
-> IO ByteString
hGetContentsSizeHint hnd =
readChunks []
where
readChunks chunks sz sz' = do
fp <- mallocByteString sz
readcount <- withForeignPtr fp $ \buf -> hGetBuf hnd buf sz
let chunk = PS fp 0 readcount
-- We rely on the hGetBuf behaviour (not hGetBufSome) where it reads up
-- to the size we ask for, or EOF. So short reads indicate EOF.
if readcount < sz && sz > 0
then return $! concat (P.reverse (chunk : chunks))
else readChunks (chunk : chunks) sz' ((sz+sz') `min` 32752)
-- we grow the buffer sizes, but not too huge
-- we concatenate in the end anyway
-- | getContents. Read stdin strictly. Equivalent to hGetContents stdin
-- The 'Handle' is closed after the contents have been read.
--
getContents :: IO ByteString
getContents = hGetContents stdin
-- | The interact function takes a function of type @ByteString -> ByteString@
-- as its argument. The entire input from the standard input device is passed
-- to this function as its argument, and the resulting string is output on the
-- standard output device.
--
interact :: (ByteString -> ByteString) -> IO ()
interact transformer = putStr . transformer =<< getContents
-- | Read an entire file strictly into a 'ByteString'.
--
readFile :: FilePath -> IO ByteString
readFile f =
withBinaryFile f ReadMode $ \h -> do
-- hFileSize fails if file is not regular file (like
-- /dev/null). Catch exception and try reading anyway.
filesz <- catch (hFileSize h) useZeroIfNotRegularFile
let readsz = (fromIntegral filesz `max` 0) + 1
hGetContentsSizeHint h readsz (readsz `max` 255)
-- Our initial size is one bigger than the file size so that in the
-- typical case we will read the whole file in one go and not have
-- to allocate any more chunks. We'll still do the right thing if the
-- file size is 0 or is changed before we do the read.
where
useZeroIfNotRegularFile :: IOException -> IO Integer
useZeroIfNotRegularFile _ = return 0
modifyFile :: IOMode -> FilePath -> ByteString -> IO ()
modifyFile mode f txt = withBinaryFile f mode (`hPut` txt)
-- | Write a 'ByteString' to a file.
writeFile :: FilePath -> ByteString -> IO ()
writeFile = modifyFile WriteMode
-- | Append a 'ByteString' to a file.
appendFile :: FilePath -> ByteString -> IO ()
appendFile = modifyFile AppendMode
-- ---------------------------------------------------------------------
-- Internal utilities
-- | 'findIndexOrEnd' is a variant of findIndex, that returns the length
-- of the string if no element is found, rather than Nothing.
findIndexOrEnd :: (Word8 -> Bool) -> ByteString -> Int
findIndexOrEnd k (PS x s l) =
accursedUnutterablePerformIO $
withForeignPtr x $ \f ->
go (f `plusPtr` s) 0
where
go !ptr !n | n >= l = return l
| otherwise = do w <- peek ptr
if k w
then return n
else go (ptr `plusPtr` 1) (n+1)
{-# INLINE findIndexOrEnd #-}
-- Common up near identical calls to `error' to reduce the number
-- constant strings created when compiled:
errorEmptyList :: String -> a
errorEmptyList fun = moduleError fun "empty ByteString"
{-# NOINLINE errorEmptyList #-}
moduleError :: String -> String -> a
moduleError fun msg = error (moduleErrorMsg fun msg)
{-# NOINLINE moduleError #-}
moduleErrorIO :: String -> String -> IO a
moduleErrorIO fun msg = throwIO . userError $ moduleErrorMsg fun msg
{-# NOINLINE moduleErrorIO #-}
moduleErrorMsg :: String -> String -> String
moduleErrorMsg fun msg = "Data.ByteString." ++ fun ++ ':':' ':msg
-- Find from the end of the string using predicate
findFromEndUntil :: (Word8 -> Bool) -> ByteString -> Int
findFromEndUntil f ps@(PS x s l)
| null ps = 0
| f (unsafeLast ps) = l
| otherwise = findFromEndUntil f (PS x s (l - 1))
|
CloudI/CloudI
|
src/api/haskell/external/bytestring-0.10.10.0/Data/ByteString.hs
|
mit
| 73,893 | 0 | 20 | 21,422 | 15,007 | 7,989 | 7,018 | 974 | 7 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.TextEditor.Tests
-- Copyright : 2007-2013 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL Nothing
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.TextEditor.Tests (
testEditors
) where
import Graphics.UI.Gtk
(mainQuit, postGUIAsync, windowSetPosition, windowSetDefaultSize,
mainGUI, widgetShowAll, containerAdd, uiManagerNew, widgetSetName,
windowNew)
import IDE.TextEditor
(CodeMirror(..), Yi(..), GtkSourceView(..), TextEditor(..))
import IDE.Core.Types
(IDEM, KeymapI, Prefs(..), IDE(..), IDEState(..))
import qualified Data.Map as Map (empty)
import Graphics.UI.Frame.Panes
(PaneLayout(..), FrameState(..))
import IDE.SourceCandy (parseCandy)
import IDE.Utils.FileUtils (getConfigFilePathForLoad)
import IDE.Utils.Utils
(leksahKeymapFileExtension, leksahCandyFileExtension)
import IDE.Preferences (defaultPrefs)
import IDE.Keymap (Keymap(..))
import IDE.Command (mkActions)
import qualified IDE.YiConfig as Yi (start)
import IDE.YiConfig (defaultYiConfig)
import Data.IORef (newIORef)
import IDE.Core.State (getDataDir, reflectIDE)
import Control.Monad.IO.Class (MonadIO(..))
import Graphics.UI.Gtk.General.Enums (WindowPosition(..))
import System.Log.Logger (debugM)
import Control.Concurrent (takeMVar, putMVar, newEmptyMVar)
import Test.QuickCheck.Monadic (assert, run, monadicIO)
import Test.QuickCheck.All (quickCheckAll)
import Graphics.UI.Frame.ViewFrame (getWindows)
import Test.QuickCheck (Property)
import Control.Monad.Loops (allM)
import System.IO (stderr, stdout, hFlush)
import Data.Text (Text)
import Data.Monoid ((<>))
import qualified Data.Text as T (unpack, pack)
import Data.Sequence (empty)
testIDE :: IDEM Bool -> IO Bool
testIDE f = do
result <- newEmptyMVar
Yi.start defaultYiConfig $ \yiControl -> do
uiManager <- uiManagerNew
dataDir <- getDataDir
candyPath <- getConfigFilePathForLoad
(case sourceCandy defaultPrefs of
(_,name) -> T.unpack name <> leksahCandyFileExtension) Nothing dataDir
candySt <- parseCandy candyPath
-- keystrokes
keysPath <- getConfigFilePathForLoad (T.unpack (keymapName defaultPrefs) <> leksahKeymapFileExtension) Nothing dataDir
keyMap <- parseKeymap keysPath
let accelActions = setKeymap (keyMap :: KeymapI) mkActions
specialKeys <- buildSpecialKeys keyMap accelActions
win <- windowNew
windowSetDefaultSize win 900 600
windowSetPosition win WinPosCenter
widgetSetName win "Leksah Main Window"
let fs = FrameState
{ windows = [win]
, uiManager = uiManager
, panes = Map.empty
, activePane = Nothing
, paneMap = Map.empty
, layout = TerminalP Map.empty Nothing (-1) Nothing Nothing
, panePathFromNB = Map.empty
}
ide = IDE
{ frameState = fs
, recentPanes = []
, specialKeys = specialKeys
, specialKey = Nothing
, candy = candySt
, prefs = defaultPrefs
, workspace = Nothing
, activePack = Nothing
, activeExe = Nothing
, bufferProjCache = Map.empty
, allLogRefs = empty
, currentHist = 0
, currentEBC = (Nothing, Nothing, Nothing)
, systemInfo = Nothing
, packageInfo = Nothing
, workspaceInfo = Nothing
, workspInfoCache = Map.empty
, handlers = Map.empty
, currentState = IsStartingUp
, guiHistory = (False,[],-1)
, findbar = (False,Nothing)
, toolbar = (True,Nothing)
, recentFiles = []
, recentWorkspaces = []
, runningTool = Nothing
, debugState = Nothing
, completion = ((750,400),Nothing)
, yiControl = yiControl
, server = Nothing
, vcsData = (Map.empty, Nothing)
, logLaunches = Map.empty
, autoCommand = return ()
, autoURI = Nothing
, hlintQueue = Nothing
, serverQueue = Nothing
}
ideR <- newIORef ide
(`reflectIDE` ideR) f >>= putMVar result
takeMVar result
allEditors :: (forall editor. TextEditor editor
=> ( Maybe FilePath
-> Text
-> IDEM (EditorBuffer editor))
-> IDEM Bool)
-> IO Bool
allEditors test = allM id
[ doTest GtkSourceView
#ifdef MIN_VERSION_yi
, doTest Yi
#endif
, doTest CodeMirror]
where
doTest :: forall editor. (TextEditor editor, Show editor) => editor -> IO Bool
doTest editor = do
hFlush stdout
hFlush stderr
debugM "leksah" $ show editor
testIDE $ test (newBuffer :: Maybe FilePath -> Text -> IDEM (EditorBuffer editor))
prop_test :: String -> Property
prop_test s = monadicIO $ do
let input = filter (not . flip elem "\NUL\r") s
result <- run $ allEditors (\buf -> do
(win:_) <- getWindows
buffer <- buf Nothing (T.pack "")
view <- newView buffer (Just $ T.pack "monospace")
sw <- getScrolledWindow view
liftIO $ containerAdd win sw
setText buffer (T.pack input)
first <- getStartIter buffer
last <- getEndIter buffer
out <- getText buffer first last True
return $ T.pack input == out)
assert result
-- workaround for issue with $quickcheckall
-- see https://hackage.haskell.org/package/QuickCheck-2.4.2/docs/Test-QuickCheck-All.html
return []
testEditors :: IO Bool
testEditors = do
result <- newEmptyMVar
postGUIAsync $ do
$quickCheckAll >>= putMVar result
mainQuit
mainGUI
takeMVar result
|
ChrisLane/leksah
|
tests/IDE/TextEditor/Tests.hs
|
gpl-2.0
| 6,711 | 0 | 20 | 2,218 | 1,579 | 889 | 690 | 146 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Module : Test.AWS.MachineLearning
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Test.AWS.MachineLearning
( tests
, fixtures
) where
import Network.AWS.MachineLearning
import Test.AWS.Gen.MachineLearning
import Test.Tasty
tests :: [TestTree]
tests = []
fixtures :: [TestTree]
fixtures = []
|
fmapfmapfmap/amazonka
|
amazonka-ml/test/Test/AWS/MachineLearning.hs
|
mpl-2.0
| 772 | 0 | 5 | 201 | 73 | 50 | 23 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -Wall #-}
module Taygeta.Parser.Treebank
( treebank
) where
import Data.Bifunctor (first)
import Data.Foldable (foldl')
import qualified Data.Text as T
import Data.Text.ICU (MatchOption (..), Regex, regex)
import Data.Text.ICU.Replace
import Taygeta.Parser.Utils
import Taygeta.Types
treebank :: PlainTokenizer
treebank = T.words
. foldRepl (stage2 ++ contractions)
. flip (joinEnds ' ') ' '
. foldRepl stage1
reOpts :: [MatchOption]
reOpts = [CaseInsensitive]
foldRepl :: [(T.Text, Replace)] -> T.Text -> T.Text
foldRepl res t = foldl' rall t $ map (first (regex reOpts)) res
rall :: T.Text -> (Regex, Replace) -> T.Text
rall t (re, r) = replaceAll re r t
contractions, stage1, stage2 :: [(T.Text, Replace)]
contractions = map (, " $1 $2 ") [ "\\b(can)(not)\\b"
, "\\b(d)('ye)\\b"
, "\\b(gim)(me)\\b"
, "\\b(gon)(na)\\b"
, "\\b(got)(ta)\\b"
, "\\b(lem)(me)\\b"
, "\\b(mor)('n)\\b"
, "\\b(wan)(na)\\b"
, " ('t)(is)\\b"
, " ('t)(wa)\\b"
, "\\b(whad)(dd)(ya)\\b"
, "\\b(wha)(t)(cha)\\b"
-- Commented out in the original:
, "\\b(whad)(dd)(ya)\\b"
, "\\b(wha)(t)(cha)\\b"
]
stage1 = [ ("^\"", "``") -- starting quotes
, ("(``)", " $1 ")
, ("([ (\\[{])\"", "$1 `` ")
, ("([:,])([^\\d])", " $1 $2 ") -- punctuation
, ("\\.\\.\\.", " ... ")
, ("[;@#$%&]", " $0 ")
, ("([^\\.])(\\.)([\\]\\)}>\"']*)\\s*$", "$1 $2$3")
, ("[?!]", " $0 ")
, ("([^'])' ", "$1 ' ")
, ("[\\]\\[\\(\\)\\{\\}\\<\\>]", " $0 ") -- brackets
, ("--", " -- ")
]
stage2 = [ ("\"", " '' ")
, ("(\\S)('')", "$1 $2 ")
, ("([^' ])('[sS]|'[mM]|'[dD]|') ", "$1 $2 ")
, ("([^' ])('ll|'LL|'re|'RE|'ve|'VE|n't|N'T) ", "$1 $2 ")
]
|
erochest/taygeta-icu
|
src/Taygeta/Parser/Treebank.hs
|
apache-2.0
| 2,464 | 0 | 10 | 1,049 | 481 | 297 | 184 | 53 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStatusTipEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStatusTipEvent (
QqStatusTipEvent(..)
,QqStatusTipEvent_nf(..)
,tip
,qStatusTipEvent_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStatusTipEvent x1 where
qStatusTipEvent :: x1 -> IO (QStatusTipEvent ())
instance QqStatusTipEvent ((QStatusTipEvent t1)) where
qStatusTipEvent (x1)
= withQStatusTipEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStatusTipEvent cobj_x1
foreign import ccall "qtc_QStatusTipEvent" qtc_QStatusTipEvent :: Ptr (TQStatusTipEvent t1) -> IO (Ptr (TQStatusTipEvent ()))
instance QqStatusTipEvent ((String)) where
qStatusTipEvent (x1)
= withQStatusTipEventResult $
withCWString x1 $ \cstr_x1 ->
qtc_QStatusTipEvent1 cstr_x1
foreign import ccall "qtc_QStatusTipEvent1" qtc_QStatusTipEvent1 :: CWString -> IO (Ptr (TQStatusTipEvent ()))
class QqStatusTipEvent_nf x1 where
qStatusTipEvent_nf :: x1 -> IO (QStatusTipEvent ())
instance QqStatusTipEvent_nf ((QStatusTipEvent t1)) where
qStatusTipEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStatusTipEvent cobj_x1
instance QqStatusTipEvent_nf ((String)) where
qStatusTipEvent_nf (x1)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
qtc_QStatusTipEvent1 cstr_x1
tip :: QStatusTipEvent a -> (()) -> IO (String)
tip x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStatusTipEvent_tip cobj_x0
foreign import ccall "qtc_QStatusTipEvent_tip" qtc_QStatusTipEvent_tip :: Ptr (TQStatusTipEvent a) -> IO (Ptr (TQString ()))
qStatusTipEvent_delete :: QStatusTipEvent a -> IO ()
qStatusTipEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStatusTipEvent_delete cobj_x0
foreign import ccall "qtc_QStatusTipEvent_delete" qtc_QStatusTipEvent_delete :: Ptr (TQStatusTipEvent a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QStatusTipEvent.hs
|
bsd-2-clause
| 2,418 | 0 | 12 | 371 | 572 | 304 | 268 | 52 | 1 |
module Propellor.Property.Reboot where
import Propellor
now :: Property NoInfo
now = cmdProperty "reboot" []
`describe` "reboot now"
-- | Schedules a reboot at the end of the current propellor run.
--
-- The Result code of the endire propellor run can be checked;
-- the reboot proceeds only if the function returns True.
--
-- The reboot can be forced to run, which bypasses the init system. Useful
-- if the init system might not be running for some reason.
atEnd :: Bool -> (Result -> Bool) -> Property NoInfo
atEnd force resultok = property "scheduled reboot at end of propellor run" $ do
endAction "rebooting" atend
return NoChange
where
atend r
| resultok r = liftIO $ toResult
<$> boolSystem "reboot" rebootparams
| otherwise = do
warningMessage "Not rebooting, due to status of propellor run."
return FailedChange
rebootparams
| force = [Param "--force"]
| otherwise = []
|
sjfloat/propellor
|
src/Propellor/Property/Reboot.hs
|
bsd-2-clause
| 907 | 2 | 10 | 175 | 180 | 89 | 91 | 18 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Natural
-- Copyright : (C) 2014 Herbert Valerio Riedel,
-- (C) 2011 Edward Kmett
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The arbitrary-precision 'Natural' number type.
--
-- __Note__: This is an internal GHC module with an API subject to
-- change. It's recommended use the "Numeric.Natural" module to import
-- the 'Natural' type.
--
-- @since 4.8.0.0
-----------------------------------------------------------------------------
module GHC.Natural
( -- * The 'Natural' number type
--
-- | __Warning__: The internal implementation of 'Natural'
-- (i.e. which constructors are available) depends on the
-- 'Integer' backend used!
Natural(..)
, mkNatural
, isValidNatural
-- * Arithmetic
, plusNatural
, minusNatural
, minusNaturalMaybe
, timesNatural
, negateNatural
, signumNatural
, quotRemNatural
, quotNatural
, remNatural
, gcdNatural
, lcmNatural
-- * Bits
, andNatural
, orNatural
, xorNatural
, bitNatural
, testBitNatural
, popCountNatural
, shiftLNatural
, shiftRNatural
-- * Conversions
, naturalToInteger
, naturalToWord
, naturalToInt
, naturalFromInteger
, wordToNatural
, intToNatural
, naturalToWordMaybe
, wordToNatural#
, wordToNaturalBase
-- * Modular arithmetic
, powModNatural
) where
#include "MachDeps.h"
import GHC.Classes
import GHC.Maybe
import GHC.Types
import GHC.Prim
import {-# SOURCE #-} GHC.Exception.Type (underflowException, divZeroException)
#if defined(MIN_VERSION_integer_gmp)
import GHC.Integer.GMP.Internals
#else
import GHC.Integer
#endif
default ()
-- Most high-level operations need to be marked `NOINLINE` as
-- otherwise GHC doesn't recognize them and fails to apply constant
-- folding to `Natural`-typed expression.
--
-- To this end, the CPP hack below allows to write the pseudo-pragma
--
-- {-# CONSTANT_FOLDED plusNatural #-}
--
-- which is simply expanded into a
--
-- {-# NOINLINE plusNatural #-}
--
--
-- TODO: Note that some functions have commented CONSTANT_FOLDED annotations,
-- that's because the Integer counter-parts of these functions do actually have
-- a builtinRule in PrelRules, where the Natural functions do not. The plan is
-- to eventually also add builtin rules for those functions on Natural.
#define CONSTANT_FOLDED NOINLINE
-------------------------------------------------------------------------------
-- Arithmetic underflow
-------------------------------------------------------------------------------
-- We put them here because they are needed relatively early
-- in the libraries before the Exception type has been defined yet.
{-# NOINLINE underflowError #-}
underflowError :: a
underflowError = raise# underflowException
{-# NOINLINE divZeroError #-}
divZeroError :: a
divZeroError = raise# divZeroException
-------------------------------------------------------------------------------
-- Natural type
-------------------------------------------------------------------------------
#if defined(MIN_VERSION_integer_gmp)
-- TODO: if saturated arithmetic is to used, replace 'underflowError' by '0'
-- | Type representing arbitrary-precision non-negative integers.
--
-- >>> 2^100 :: Natural
-- 1267650600228229401496703205376
--
-- Operations whose result would be negative @'Control.Exception.throw'
-- ('Control.Exception.Underflow' :: 'Control.Exception.ArithException')@,
--
-- >>> -1 :: Natural
-- *** Exception: arithmetic underflow
--
-- @since 4.8.0.0
data Natural = NatS# GmpLimb# -- ^ in @[0, maxBound::Word]@
| NatJ# {-# UNPACK #-} !BigNat -- ^ in @]maxBound::Word, +inf[@
--
-- __Invariant__: 'NatJ#' is used
-- /iff/ value doesn't fit in
-- 'NatS#' constructor.
-- NB: Order of constructors *must*
-- coincide with 'Ord' relation
deriving ( Eq -- ^ @since 4.8.0.0
, Ord -- ^ @since 4.8.0.0
)
zero, one :: Natural
zero = NatS# 0##
one = NatS# 1##
-- | Test whether all internal invariants are satisfied by 'Natural' value
--
-- This operation is mostly useful for test-suites and/or code which
-- constructs 'Integer' values directly.
--
-- @since 4.8.0.0
isValidNatural :: Natural -> Bool
isValidNatural (NatS# _) = True
isValidNatural (NatJ# bn) = isTrue# (isValidBigNat# bn)
-- A 1-limb BigNat could fit into a NatS#, so we
-- require at least 2 limbs.
&& isTrue# (sizeofBigNat# bn ># 1#)
signumNatural :: Natural -> Natural
signumNatural (NatS# 0##) = zero
signumNatural _ = one
-- {-# CONSTANT_FOLDED signumNatural #-}
negateNatural :: Natural -> Natural
negateNatural (NatS# 0##) = zero
negateNatural _ = underflowError
-- {-# CONSTANT_FOLDED negateNatural #-}
-- | @since 4.10.0.0
naturalFromInteger :: Integer -> Natural
naturalFromInteger (S# i#)
| isTrue# (i# >=# 0#) = NatS# (int2Word# i#)
naturalFromInteger (Jp# bn) = bigNatToNatural bn
naturalFromInteger _ = underflowError
{-# CONSTANT_FOLDED naturalFromInteger #-}
-- | Compute greatest common divisor.
gcdNatural :: Natural -> Natural -> Natural
gcdNatural (NatS# 0##) y = y
gcdNatural x (NatS# 0##) = x
gcdNatural (NatS# 1##) _ = one
gcdNatural _ (NatS# 1##) = one
gcdNatural (NatJ# x) (NatJ# y) = bigNatToNatural (gcdBigNat x y)
gcdNatural (NatJ# x) (NatS# y) = NatS# (gcdBigNatWord x y)
gcdNatural (NatS# x) (NatJ# y) = NatS# (gcdBigNatWord y x)
gcdNatural (NatS# x) (NatS# y) = NatS# (gcdWord x y)
-- | Compute least common multiple.
lcmNatural :: Natural -> Natural -> Natural
-- Make sure we are strict in all arguments (#17499)
lcmNatural (NatS# 0##) !_ = zero
lcmNatural _ (NatS# 0##) = zero
lcmNatural (NatS# 1##) y = y
lcmNatural x (NatS# 1##) = x
lcmNatural x y = (x `quotNatural` (gcdNatural x y)) `timesNatural` y
----------------------------------------------------------------------------
quotRemNatural :: Natural -> Natural -> (Natural, Natural)
-- Make sure we are strict in all arguments (#17499)
quotRemNatural !_ (NatS# 0##) = divZeroError
quotRemNatural n (NatS# 1##) = (n,zero)
quotRemNatural n@(NatS# _) (NatJ# _) = (zero, n)
quotRemNatural (NatS# n) (NatS# d) = case quotRemWord# n d of
(# q, r #) -> (NatS# q, NatS# r)
quotRemNatural (NatJ# n) (NatS# d) = case quotRemBigNatWord n d of
(# q, r #) -> (bigNatToNatural q, NatS# r)
quotRemNatural (NatJ# n) (NatJ# d) = case quotRemBigNat n d of
(# q, r #) -> (bigNatToNatural q, bigNatToNatural r)
-- {-# CONSTANT_FOLDED quotRemNatural #-}
quotNatural :: Natural -> Natural -> Natural
-- Make sure we are strict in all arguments (#17499)
quotNatural !_ (NatS# 0##) = divZeroError
quotNatural n (NatS# 1##) = n
quotNatural (NatS# _) (NatJ# _) = zero
quotNatural (NatS# n) (NatS# d) = NatS# (quotWord# n d)
quotNatural (NatJ# n) (NatS# d) = bigNatToNatural (quotBigNatWord n d)
quotNatural (NatJ# n) (NatJ# d) = bigNatToNatural (quotBigNat n d)
-- {-# CONSTANT_FOLDED quotNatural #-}
remNatural :: Natural -> Natural -> Natural
-- Make sure we are strict in all arguments (#17499)
remNatural !_ (NatS# 0##) = divZeroError
remNatural _ (NatS# 1##) = zero
remNatural n@(NatS# _) (NatJ# _) = n
remNatural (NatS# n) (NatS# d) = NatS# (remWord# n d)
remNatural (NatJ# n) (NatS# d) = NatS# (remBigNatWord n d)
remNatural (NatJ# n) (NatJ# d) = bigNatToNatural (remBigNat n d)
-- {-# CONSTANT_FOLDED remNatural #-}
-- | @since 4.12.0.0
naturalToInteger :: Natural -> Integer
naturalToInteger (NatS# w) = wordToInteger w
naturalToInteger (NatJ# bn) = Jp# bn
{-# CONSTANT_FOLDED naturalToInteger #-}
andNatural :: Natural -> Natural -> Natural
andNatural (NatS# n) (NatS# m) = NatS# (n `and#` m)
andNatural (NatS# n) (NatJ# m) = NatS# (n `and#` bigNatToWord m)
andNatural (NatJ# n) (NatS# m) = NatS# (bigNatToWord n `and#` m)
andNatural (NatJ# n) (NatJ# m) = bigNatToNatural (andBigNat n m)
-- {-# CONSTANT_FOLDED andNatural #-}
orNatural :: Natural -> Natural -> Natural
orNatural (NatS# n) (NatS# m) = NatS# (n `or#` m)
orNatural (NatS# n) (NatJ# m) = NatJ# (orBigNat (wordToBigNat n) m)
orNatural (NatJ# n) (NatS# m) = NatJ# (orBigNat n (wordToBigNat m))
orNatural (NatJ# n) (NatJ# m) = NatJ# (orBigNat n m)
-- {-# CONSTANT_FOLDED orNatural #-}
xorNatural :: Natural -> Natural -> Natural
xorNatural (NatS# n) (NatS# m) = NatS# (n `xor#` m)
xorNatural (NatS# n) (NatJ# m) = NatJ# (xorBigNat (wordToBigNat n) m)
xorNatural (NatJ# n) (NatS# m) = NatJ# (xorBigNat n (wordToBigNat m))
xorNatural (NatJ# n) (NatJ# m) = bigNatToNatural (xorBigNat n m)
-- {-# CONSTANT_FOLDED xorNatural #-}
bitNatural :: Int# -> Natural
bitNatural i#
| isTrue# (i# <# WORD_SIZE_IN_BITS#) = NatS# (1## `uncheckedShiftL#` i#)
| True = NatJ# (bitBigNat i#)
-- {-# CONSTANT_FOLDED bitNatural #-}
testBitNatural :: Natural -> Int -> Bool
testBitNatural (NatS# w) (I# i#)
| isTrue# (i# <# WORD_SIZE_IN_BITS#) =
isTrue# ((w `and#` (1## `uncheckedShiftL#` i#)) `neWord#` 0##)
| True = False
testBitNatural (NatJ# bn) (I# i#) = testBitBigNat bn i#
-- {-# CONSTANT_FOLDED testBitNatural #-}
popCountNatural :: Natural -> Int
popCountNatural (NatS# w) = I# (word2Int# (popCnt# w))
popCountNatural (NatJ# bn) = I# (popCountBigNat bn)
-- {-# CONSTANT_FOLDED popCountNatural #-}
shiftLNatural :: Natural -> Int -> Natural
shiftLNatural n (I# 0#) = n
shiftLNatural (NatS# 0##) _ = zero
shiftLNatural (NatS# 1##) (I# i#) = bitNatural i#
shiftLNatural (NatS# w) (I# i#)
= bigNatToNatural (shiftLBigNat (wordToBigNat w) i#)
shiftLNatural (NatJ# bn) (I# i#)
= bigNatToNatural (shiftLBigNat bn i#)
-- {-# CONSTANT_FOLDED shiftLNatural #-}
shiftRNatural :: Natural -> Int -> Natural
shiftRNatural n (I# 0#) = n
shiftRNatural (NatS# w) (I# i#)
| isTrue# (i# >=# WORD_SIZE_IN_BITS#) = zero
| True = NatS# (w `uncheckedShiftRL#` i#)
shiftRNatural (NatJ# bn) (I# i#) = bigNatToNatural (shiftRBigNat bn i#)
-- {-# CONSTANT_FOLDED shiftRNatural #-}
----------------------------------------------------------------------------
-- | 'Natural' Addition
plusNatural :: Natural -> Natural -> Natural
plusNatural (NatS# 0##) y = y
plusNatural x (NatS# 0##) = x
plusNatural (NatS# x) (NatS# y)
= case plusWord2# x y of
(# 0##, l #) -> NatS# l
(# h, l #) -> NatJ# (wordToBigNat2 h l)
plusNatural (NatS# x) (NatJ# y) = NatJ# (plusBigNatWord y x)
plusNatural (NatJ# x) (NatS# y) = NatJ# (plusBigNatWord x y)
plusNatural (NatJ# x) (NatJ# y) = NatJ# (plusBigNat x y)
{-# CONSTANT_FOLDED plusNatural #-}
-- | 'Natural' multiplication
timesNatural :: Natural -> Natural -> Natural
-- Make sure we are strict in all arguments (#17499)
timesNatural !_ (NatS# 0##) = zero
timesNatural (NatS# 0##) _ = zero
timesNatural x (NatS# 1##) = x
timesNatural (NatS# 1##) y = y
timesNatural (NatS# x) (NatS# y) = case timesWord2# x y of
(# 0##, 0## #) -> NatS# 0##
(# 0##, xy #) -> NatS# xy
(# h , l #) -> NatJ# (wordToBigNat2 h l)
timesNatural (NatS# x) (NatJ# y) = NatJ# (timesBigNatWord y x)
timesNatural (NatJ# x) (NatS# y) = NatJ# (timesBigNatWord x y)
timesNatural (NatJ# x) (NatJ# y) = NatJ# (timesBigNat x y)
{-# CONSTANT_FOLDED timesNatural #-}
-- | 'Natural' subtraction. May @'Control.Exception.throw'
-- 'Control.Exception.Underflow'@.
minusNatural :: Natural -> Natural -> Natural
minusNatural x (NatS# 0##) = x
minusNatural (NatS# x) (NatS# y) = case subWordC# x y of
(# l, 0# #) -> NatS# l
_ -> underflowError
minusNatural (NatS# _) (NatJ# _) = underflowError
minusNatural (NatJ# x) (NatS# y)
= bigNatToNatural (minusBigNatWord x y)
minusNatural (NatJ# x) (NatJ# y)
= bigNatToNatural (minusBigNat x y)
{-# CONSTANT_FOLDED minusNatural #-}
-- | 'Natural' subtraction. Returns 'Nothing's for non-positive results.
--
-- @since 4.8.0.0
minusNaturalMaybe :: Natural -> Natural -> Maybe Natural
-- Make sure we are strict in all arguments (#17499)
minusNaturalMaybe !x (NatS# 0##) = Just x
minusNaturalMaybe (NatS# x) (NatS# y) = case subWordC# x y of
(# l, 0# #) -> Just (NatS# l)
_ -> Nothing
minusNaturalMaybe (NatS# _) (NatJ# _) = Nothing
minusNaturalMaybe (NatJ# x) (NatS# y)
= Just (bigNatToNatural (minusBigNatWord x y))
minusNaturalMaybe (NatJ# x) (NatJ# y)
| isTrue# (isNullBigNat# res) = Nothing
| True = Just (bigNatToNatural res)
where
res = minusBigNat x y
-- | Convert 'BigNat' to 'Natural'.
-- Throws 'Control.Exception.Underflow' if passed a 'nullBigNat'.
bigNatToNatural :: BigNat -> Natural
bigNatToNatural bn
| isTrue# (sizeofBigNat# bn ==# 1#) = NatS# (bigNatToWord bn)
| isTrue# (isNullBigNat# bn) = underflowError
| True = NatJ# bn
naturalToBigNat :: Natural -> BigNat
naturalToBigNat (NatS# w#) = wordToBigNat w#
naturalToBigNat (NatJ# bn) = bn
naturalToWord :: Natural -> Word
naturalToWord (NatS# w#) = W# w#
naturalToWord (NatJ# bn) = W# (bigNatToWord bn)
naturalToInt :: Natural -> Int
naturalToInt (NatS# w#) = I# (word2Int# w#)
naturalToInt (NatJ# bn) = I# (bigNatToInt bn)
----------------------------------------------------------------------------
-- | Convert a Word# into a Natural
--
-- Built-in rule ensures that applications of this function to literal Word# are
-- lifted into Natural literals.
wordToNatural# :: Word# -> Natural
wordToNatural# w# = NatS# w#
{-# CONSTANT_FOLDED wordToNatural# #-}
-- | Convert a Word# into a Natural
--
-- In base we can't use wordToNatural# as built-in rules transform some of them
-- into Natural literals. Use this function instead.
wordToNaturalBase :: Word# -> Natural
wordToNaturalBase w# = NatS# w#
#else /* !defined(MIN_VERSION_integer_gmp) */
----------------------------------------------------------------------------
-- Use wrapped 'Integer' as fallback; taken from Edward Kmett's nats package
-- | Type representing arbitrary-precision non-negative integers.
--
-- Operations whose result would be negative @'Control.Exception.throw'
-- ('Control.Exception.Underflow' :: 'Control.Exception.ArithException')@.
--
-- @since 4.8.0.0
newtype Natural = Natural Integer -- ^ __Invariant__: non-negative 'Integer'
deriving (Eq,Ord)
-- | Test whether all internal invariants are satisfied by 'Natural' value
--
-- This operation is mostly useful for test-suites and/or code which
-- constructs 'Natural' values directly.
--
-- @since 4.8.0.0
isValidNatural :: Natural -> Bool
isValidNatural (Natural i) = i >= wordToInteger 0##
-- | Convert a 'Word#' into a 'Natural'
--
-- Built-in rule ensures that applications of this function to literal 'Word#'
-- are lifted into 'Natural' literals.
wordToNatural# :: Word# -> Natural
wordToNatural# w## = Natural (wordToInteger w##)
{-# CONSTANT_FOLDED wordToNatural# #-}
-- | Convert a 'Word#' into a Natural
--
-- In base we can't use wordToNatural# as built-in rules transform some of them
-- into Natural literals. Use this function instead.
wordToNaturalBase :: Word# -> Natural
wordToNaturalBase w## = Natural (wordToInteger w##)
-- | @since 4.10.0.0
naturalFromInteger :: Integer -> Natural
naturalFromInteger n
| n >= wordToInteger 0## = Natural n
| True = underflowError
{-# INLINE naturalFromInteger #-}
-- | Compute greatest common divisor.
gcdNatural :: Natural -> Natural -> Natural
gcdNatural (Natural n) (Natural m) = Natural (n `gcdInteger` m)
-- | Compute lowest common multiple.
lcmNatural :: Natural -> Natural -> Natural
lcmNatural (Natural n) (Natural m) = Natural (n `lcmInteger` m)
-- | 'Natural' subtraction. Returns 'Nothing's for non-positive results.
--
-- @since 4.8.0.0
minusNaturalMaybe :: Natural -> Natural -> Maybe Natural
minusNaturalMaybe (Natural x) (Natural y)
| x >= y = Just (Natural (x `minusInteger` y))
| True = Nothing
shiftLNatural :: Natural -> Int -> Natural
shiftLNatural (Natural n) (I# i) = Natural (n `shiftLInteger` i)
-- {-# CONSTANT_FOLDED shiftLNatural #-}
shiftRNatural :: Natural -> Int -> Natural
shiftRNatural (Natural n) (I# i) = Natural (n `shiftRInteger` i)
-- {-# CONSTANT_FOLDED shiftRNatural #-}
plusNatural :: Natural -> Natural -> Natural
plusNatural (Natural x) (Natural y) = Natural (x `plusInteger` y)
{-# CONSTANT_FOLDED plusNatural #-}
minusNatural :: Natural -> Natural -> Natural
minusNatural (Natural x) (Natural y)
= if z `ltInteger` wordToInteger 0## then underflowError else Natural z
where z = x `minusInteger` y
{-# CONSTANT_FOLDED minusNatural #-}
timesNatural :: Natural -> Natural -> Natural
timesNatural (Natural x) (Natural y) = Natural (x `timesInteger` y)
{-# CONSTANT_FOLDED timesNatural #-}
orNatural :: Natural -> Natural -> Natural
orNatural (Natural x) (Natural y) = Natural (x `orInteger` y)
-- {-# CONSTANT_FOLDED orNatural #-}
xorNatural :: Natural -> Natural -> Natural
xorNatural (Natural x) (Natural y) = Natural (x `xorInteger` y)
-- {-# CONSTANT_FOLDED xorNatural #-}
andNatural :: Natural -> Natural -> Natural
andNatural (Natural x) (Natural y) = Natural (x `andInteger` y)
-- {-# CONSTANT_FOLDED andNatural #-}
naturalToInt :: Natural -> Int
naturalToInt (Natural i) = I# (integerToInt i)
naturalToWord :: Natural -> Word
naturalToWord (Natural i) = W# (integerToWord i)
naturalToInteger :: Natural -> Integer
naturalToInteger (Natural i) = i
{-# CONSTANT_FOLDED naturalToInteger #-}
testBitNatural :: Natural -> Int -> Bool
testBitNatural (Natural n) (I# i) = testBitInteger n i
-- {-# CONSTANT_FOLDED testBitNatural #-}
popCountNatural :: Natural -> Int
popCountNatural (Natural n) = I# (popCountInteger n)
bitNatural :: Int# -> Natural
bitNatural i#
| isTrue# (i# <# WORD_SIZE_IN_BITS#) = wordToNaturalBase (1## `uncheckedShiftL#` i#)
| True = Natural (1 `shiftLInteger` i#)
-- {-# CONSTANT_FOLDED bitNatural #-}
quotNatural :: Natural -> Natural -> Natural
quotNatural n@(Natural x) (Natural y)
| y == wordToInteger 0## = divZeroError
| y == wordToInteger 1## = n
| True = Natural (x `quotInteger` y)
-- {-# CONSTANT_FOLDED quotNatural #-}
remNatural :: Natural -> Natural -> Natural
remNatural (Natural x) (Natural y)
| y == wordToInteger 0## = divZeroError
| y == wordToInteger 1## = wordToNaturalBase 0##
| True = Natural (x `remInteger` y)
-- {-# CONSTANT_FOLDED remNatural #-}
quotRemNatural :: Natural -> Natural -> (Natural, Natural)
quotRemNatural n@(Natural x) (Natural y)
| y == wordToInteger 0## = divZeroError
| y == wordToInteger 1## = (n,wordToNaturalBase 0##)
| True = case quotRemInteger x y of
(# k, r #) -> (Natural k, Natural r)
-- {-# CONSTANT_FOLDED quotRemNatural #-}
signumNatural :: Natural -> Natural
signumNatural (Natural x)
| x == wordToInteger 0## = wordToNaturalBase 0##
| True = wordToNaturalBase 1##
-- {-# CONSTANT_FOLDED signumNatural #-}
negateNatural :: Natural -> Natural
negateNatural (Natural x)
| x == wordToInteger 0## = wordToNaturalBase 0##
| True = underflowError
-- {-# CONSTANT_FOLDED negateNatural #-}
#endif
-- | Construct 'Natural' from 'Word' value.
--
-- @since 4.8.0.0
wordToNatural :: Word -> Natural
wordToNatural (W# w#) = wordToNatural# w#
-- | Try downcasting 'Natural' to 'Word' value.
-- Returns 'Nothing' if value doesn't fit in 'Word'.
--
-- @since 4.8.0.0
naturalToWordMaybe :: Natural -> Maybe Word
#if defined(MIN_VERSION_integer_gmp)
naturalToWordMaybe (NatS# w#) = Just (W# w#)
naturalToWordMaybe (NatJ# _) = Nothing
#else
naturalToWordMaybe (Natural i)
| i < maxw = Just (W# (integerToWord i))
| True = Nothing
where
maxw = 1 `shiftLInteger` WORD_SIZE_IN_BITS#
#endif
-- | \"@'powModNatural' /b/ /e/ /m/@\" computes base @/b/@ raised to
-- exponent @/e/@ modulo @/m/@.
--
-- @since 4.8.0.0
powModNatural :: Natural -> Natural -> Natural -> Natural
#if defined(MIN_VERSION_integer_gmp)
-- Make sure we are strict in all arguments (#17499)
powModNatural !_ !_ (NatS# 0##) = divZeroError
powModNatural _ _ (NatS# 1##) = zero
powModNatural _ (NatS# 0##) _ = one
powModNatural (NatS# 0##) _ _ = zero
powModNatural (NatS# 1##) _ _ = one
powModNatural (NatS# b) (NatS# e) (NatS# m) = NatS# (powModWord b e m)
powModNatural b e (NatS# m)
= NatS# (powModBigNatWord (naturalToBigNat b) (naturalToBigNat e) m)
powModNatural b e (NatJ# m)
= bigNatToNatural (powModBigNat (naturalToBigNat b) (naturalToBigNat e) m)
#else
-- Portable reference fallback implementation
powModNatural (Natural b0) (Natural e0) (Natural m)
| m == wordToInteger 0## = divZeroError
| m == wordToInteger 1## = wordToNaturalBase 0##
| e0 == wordToInteger 0## = wordToNaturalBase 1##
| b0 == wordToInteger 0## = wordToNaturalBase 0##
| b0 == wordToInteger 1## = wordToNaturalBase 1##
| True = go b0 e0 (wordToInteger 1##)
where
go !b e !r
| e `testBitInteger` 0# = go b' e' ((r `timesInteger` b) `modInteger` m)
| e == wordToInteger 0## = naturalFromInteger r
| True = go b' e' r
where
b' = (b `timesInteger` b) `modInteger` m
e' = e `shiftRInteger` 1# -- slightly faster than "e `div` 2"
#endif
-- | Construct 'Natural' value from list of 'Word's.
--
-- This function is used by GHC for constructing 'Natural' literals.
mkNatural :: [Word] -- ^ value expressed in 32 bit chunks, least
-- significant first
-> Natural
mkNatural [] = wordToNaturalBase 0##
mkNatural (W# i : is') = wordToNaturalBase (i `and#` 0xffffffff##) `orNatural`
shiftLNatural (mkNatural is') 32
{-# CONSTANT_FOLDED mkNatural #-}
-- | Convert 'Int' to 'Natural'.
-- Throws 'Control.Exception.Underflow' when passed a negative 'Int'.
intToNatural :: Int -> Natural
intToNatural (I# i#)
| isTrue# (i# <# 0#) = underflowError
| True = wordToNaturalBase (int2Word# i#)
|
sdiehl/ghc
|
libraries/base/GHC/Natural.hs
|
bsd-3-clause
| 22,987 | 0 | 12 | 4,947 | 4,086 | 2,146 | 1,940 | 159 | 2 |
-- Copyright (c) 2016, Emil Axelsson, Peter Jonsson, Anders Persson and
-- Josef Svenningsson
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-- | Indexable FIFO queues
module Feldspar.Data.Queue
( Queue (..)
, initQueueFromBuffer
, initQueue
, newQueue
, initQueueFromBuffer2
, initQueue2
, newQueue2
) where
import Prelude ()
import Feldspar
import Feldspar.Data.Vector
-- | Indexable FIFO queue
data Queue a = Queue
{ indexQ :: forall m . MonadComp m => Data Index -> m a
, putQ :: forall m . MonadComp m => a -> m ()
, withQ :: forall m b . (Syntax b, MonadComp m) => (Pull a -> m b) -> m b
}
-- Another option would be to represent a queue as its state (the counter and
-- the array), but the above representation leaves room for other
-- implementations.
-- | Create a new cyclic queue using an existing array as buffer. The length of
-- the array determines the queue size.
initQueueFromBuffer :: forall m a . (Syntax a, MonadComp m) =>
Arr a -> m (Queue a)
initQueueFromBuffer buf = do
ir <- initRef 0
let indexQ :: forall m2 . MonadComp m2 => Data Index -> m2 a
indexQ j = do
i <- unsafeFreezeRef ir
getArr buf $ calcIndex i j
putQ :: forall m2 . MonadComp m2 => a -> m2 ()
putQ a = do
i <- unsafeFreezeRef ir
setArr buf i a
setRef ir ((i+1) `mod` len)
withQ :: forall m2 b . (Syntax b, MonadComp m2) => (Pull a -> m2 b) -> m2 b
withQ f = do
i <- unsafeFreezeRef ir
vec <- unsafeFreezeArr buf
f $ backPermute (\_ -> calcIndex i) vec
return Queue {..}
where
len = length buf
calcIndex i j = (len+i-j-1) `mod` len
-- | Create a new cyclic queue initialized by the given vector (which also
-- determines the size)
initQueue :: (Manifestable m vec a, Finite vec, Syntax a, MonadComp m)
=> vec -- ^ Initial content (also determines the queue size)
-> m (Queue a)
initQueue init = do
buf <- newArr $ length init
manifestStore buf init
initQueueFromBuffer buf
-- | Create a new cyclic queue of the given length without initialization
newQueue :: (Syntax a, MonadComp m) => Data Length -> m (Queue a)
newQueue l = newArr l >>= initQueueFromBuffer
initQueueFromBuffer2 :: forall m a . (Syntax a, MonadComp m)
=> Data Length -- ^ Queue size, must be <= half the buffer size
-> Arr a -- ^ Buffer
-> m (Queue a)
initQueueFromBuffer2 len buf = do
ir <- initRef 0
let indexQ :: forall m2 . MonadComp m2 => Data Index -> m2 a
indexQ j = do
i <- unsafeFreezeRef ir
getArr buf (len+i-j-1)
putQ :: forall m2 . MonadComp m2 => a -> m2 ()
putQ a = do
i <- unsafeFreezeRef ir
setArr buf i a
setArr buf (i+len) a
setRef ir ((i+1) `mod` len)
withQ :: forall m2 b . (Syntax b, MonadComp m2) => (Pull a -> m2 b) -> m2 b
withQ f = do
i <- unsafeFreezeRef ir
vec <- unsafeFreezeArr buf
f $ reverse $ take len $ drop i vec
return Queue {..}
-- | Create a new cyclic queue. This implementation uses a buffer twice as long
-- as the queue size to avoid modulus operations when accessing the elements.
initQueue2 :: (Pushy m vec a, Finite vec, Syntax a, MonadComp m)
=> vec -- ^ Initial content (also determines the queue size)
-> m (Queue a)
initQueue2 init = do
buf <- newArr (2*len)
manifestStore buf (init++init)
initQueueFromBuffer2 len buf
where
len = length init
-- | Create a new cyclic queue. This implementation uses a buffer twice as long
-- as the queue size to avoid modulus operations when accessing the elements.
newQueue2 :: (Syntax a, MonadComp m)
=> Data Length -- ^ Queue size
-> m (Queue a)
newQueue2 l = do
buf <- newArr (2*l)
initQueueFromBuffer2 l buf
|
kmate/raw-feldspar
|
src/Feldspar/Data/Queue.hs
|
bsd-3-clause
| 5,407 | 0 | 16 | 1,394 | 1,213 | 621 | 592 | -1 | -1 |
{- Joel Svensson 2012 -}
module Obsidian.Globs where
import Data.Word
---------------------------------------------------------------------------
-- Aliases
type Name = String
type NumThreads = Word32
|
svenssonjoel/ObsidianGFX
|
Obsidian/Globs.hs
|
bsd-3-clause
| 210 | 0 | 4 | 29 | 26 | 18 | 8 | 4 | 0 |
{- |
Module : Control.Monad.Identity
Copyright : (c) Andy Gill 2001,
(c) Oregon Graduate Institute of Science and Technology 2001,
(c) Jeff Newbern 2003-2006,
(c) Andriy Palamarchuk 2006
License : BSD-style (see the file LICENSE)
Maintainer : [email protected]
Stability : experimental
Portability : portable
[Computation type:] Simple function application.
[Binding strategy:] The bound function is applied to the input value.
@'Identity' x >>= f == f x@
[Useful for:] Monads can be derived from monad transformers applied to the
'Identity' monad.
[Zero and plus:] None.
[Example type:] @'Identity' a@
The @Identity@ monad is a monad that does not embody any computational strategy.
It simply applies the bound function to its input without any modification.
Computationally, there is no reason to use the @Identity@ monad
instead of the much simpler act of simply applying functions to their arguments.
The purpose of the @Identity@ monad is its fundamental role in the theory
of monad transformers.
Any monad transformer applied to the @Identity@ monad yields a non-transformer
version of that monad.
-}
module Control.Monad.Identity (
module Data.Functor.Identity,
module Control.Monad.Trans.Identity,
module Control.Monad,
module Control.Monad.Fix,
) where
import Data.Functor.Identity
import Control.Monad.Trans.Identity
import Control.Monad
import Control.Monad.Fix
|
ekmett/mtl
|
Control/Monad/Identity.hs
|
bsd-3-clause
| 1,472 | 0 | 5 | 285 | 63 | 44 | 19 | 9 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.