code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{- |
Module : $Header$
Description : Types for the Central GUI of Hets
Copyright : (c) Jorina Freya Gerken, Till Mossakowski, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : provisional
Portability : non-portable (imports Logic)
-}
module GUI.GraphTypes
( GInfo (..)
, updateWindowCount
, exitGInfo
, ConvFunc
, LibFunc
, DaVinciGraphTypeSyn
, Colors (..)
, Flags (..)
, getColor
, emptyGInfo
, copyGInfo
, lockGlobal
, unlockGlobal
) where
import GUI.GraphAbstraction (GraphInfo, initGraph)
import GUI.UDGUtils
import Common.LibName
import Common.IRI
import Driver.Options (HetcatsOpts (uncolored), defaultHetcatsOpts)
import Data.IORef
import qualified Data.Map as Map
import Control.Concurrent.MVar
import Control.Monad (when)
import Interfaces.DataTypes
import Interfaces.Utils
data Flags = Flags
{ flagHideNodes :: Bool
, flagHideEdges :: Bool
, flagHideNames :: Bool
}
-- | Global datatype for all GUI functions
data GInfo = GInfo
{ -- Global
intState :: IORef IntState
, hetcatsOpts :: HetcatsOpts
, windowCount :: MVar Int
, exitMVar :: MVar ()
, globalLock :: MVar ()
, functionLock :: MVar ()
, libGraphLock :: MVar ()
, openGraphs :: IORef (Map.Map LibName GInfo)
-- Local
, libName :: LibName
, graphInfo :: GraphInfo
, internalNames :: IORef [(String, (String -> String) -> IO ())]
, options :: IORef Flags
}
updateWindowCount :: GInfo -> (Int -> Int) -> IO ()
updateWindowCount gi f = do
c <- modifyMVar (windowCount gi) (\ a -> let b = f a in return (b, b))
when (c <= 0) $ exitGInfo gi
-- | Returns the exit-function
exitGInfo :: GInfo -> IO ()
exitGInfo gi = putMVar (exitMVar gi) ()
{- | Type of the convertGraph function. Used as type of a parameter of some
functions in GraphMenu and GraphLogic. -}
type ConvFunc = GInfo -> String -> LibFunc -> IO ()
type LibFunc = GInfo -> IO ()
type DaVinciGraphTypeSyn =
Graph DaVinciGraph
DaVinciGraphParms
DaVinciNode
DaVinciNodeType
DaVinciNodeTypeParms
DaVinciArc
DaVinciArcType
DaVinciArcTypeParms
-- | Colors to use.
data Colors = Black
| Blue
| Coral
| Green
| Yellow
| Purple
deriving (Eq, Ord, Show)
-- | Creates an empty GInfo
emptyGInfo :: IO GInfo
emptyGInfo = do
intSt <- newIORef emptyIntState
gi <- initGraph
oGraphs <- newIORef Map.empty
iorIN <- newIORef []
flags <- newIORef Flags { flagHideNodes = True
, flagHideEdges = True
, flagHideNames = True }
gl <- newEmptyMVar
fl <- newEmptyMVar
exit <- newEmptyMVar
lgl <- newEmptyMVar
wc <- newMVar 0
return GInfo { -- Global
intState = intSt
, hetcatsOpts = defaultHetcatsOpts
, windowCount = wc
, exitMVar = exit
, globalLock = gl
, functionLock = fl
, libGraphLock = lgl
, openGraphs = oGraphs
-- Local
, libName = iriLibName nullIRI
, graphInfo = gi
, internalNames = iorIN
, options = flags
}
-- | Creates an empty GInfo
copyGInfo :: GInfo -> LibName -> IO GInfo
copyGInfo gInfo ln = do
gi <- initGraph
iorIN <- newIORef []
flags <- newIORef Flags { flagHideNodes = True
, flagHideEdges = True
, flagHideNames = True }
-- Change local parts
let gInfo' = gInfo { libName = ln
, graphInfo = gi
, internalNames = iorIN
, options = flags
}
ogs = openGraphs gInfo
oGraphs <- readIORef ogs
writeIORef ogs $ Map.insert ln gInfo' oGraphs
return gInfo'
{- | Acquire the global lock. If already locked it waits till it is unlocked
again. -}
lockGlobal :: GInfo -> IO ()
lockGlobal gi = putMVar (globalLock gi) ()
-- | Releases the global lock.
unlockGlobal :: GInfo -> IO ()
unlockGlobal gi =
tryTakeMVar (globalLock gi) >> return ()
-- | Generates the colortable
colors :: Map.Map (Colors, Bool, Bool) (String, String)
colors = Map.fromList
[ ((Black, False, False), ("gray0", "gray0" ))
, ((Black, False, True ), ("gray30", "gray5" ))
, ((Blue, False, False), ("RoyalBlue3", "gray20"))
, ((Blue, False, True ), ("RoyalBlue1", "gray23"))
, ((Blue, True, False), ("SteelBlue3", "gray27"))
, ((Blue, True, True ), ("SteelBlue1", "gray30"))
, ((Coral, False, False), ("coral3", "gray40"))
, ((Coral, False, True ), ("coral1", "gray43"))
, ((Coral, True, False), ("LightSalmon2", "gray47"))
, ((Coral, True, True ), ("LightSalmon", "gray50"))
, ((Green, False, False), ("MediumSeaGreen", "gray60"))
, ((Green, False, True ), ("PaleGreen3", "gray63"))
, ((Green, True, False), ("PaleGreen2", "gray67"))
, ((Green, True, True ), ("LightGreen", "gray70"))
, ((Purple, False, False), ("purple2", "gray74"))
, ((Yellow, False, False), ("gold", "gray78"))
, ((Yellow, False, True ), ("yellow", "gray81"))
, ((Yellow, True, False), ("LightGoldenrod3", "gray85"))
, ((Yellow, True, True ), ("LightGoldenrod", "gray88"))
]
-- | Converts colors to grayscale if needed
getColor :: HetcatsOpts
-> Colors -- ^ Colorname
-> Bool -- ^ Colorvariant
-> Bool -- ^ Lightvariant
-> String
getColor opts c v l = case Map.lookup (c, v, l) colors of
Just (cname, gname) -> if uncolored opts then gname else cname
Nothing -> error $ "Color not defined: "
++ (if v then "alternative " else "")
++ (if l then "light " else "")
++ show c
| mariefarrell/Hets | GUI/GraphTypes.hs | gpl-2.0 | 6,095 | 0 | 15 | 1,912 | 1,631 | 952 | 679 | 145 | 5 |
{-# LANGUAGE FlexibleContexts #-}
{-| Implementation of functions specific to configuration management.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.WConfd.ConfigVerify
( verifyConfig
, verifyConfigErr
) where
import Control.Monad (forM_)
import Control.Monad.Error.Class (MonadError(..))
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.Foldable as F
import qualified Data.Map as M
import qualified Data.Set as S
import Ganeti.Errors
import Ganeti.JSON (GenericContainer(..), Container)
import Ganeti.Objects
import Ganeti.Types
import Ganeti.Utils
import Ganeti.Utils.Validate
-- * Configuration checks
-- | A helper function that returns the key set of a container.
keysSet :: (Ord k) => GenericContainer k v -> S.Set k
keysSet = M.keysSet . fromContainer
-- | Checks that all objects are indexed by their proper UUID.
checkUUIDKeys :: (UuidObject a, Show a)
=> String -> Container a -> ValidationMonad ()
checkUUIDKeys what = mapM_ check . M.toList . fromContainer
where
check (uuid, x) = reportIf (uuid /= UTF8.fromString (uuidOf x))
$ what ++ " '" ++ show x
++ "' is indexed by wrong UUID '"
++ UTF8.toString uuid ++ "'"
-- | Checks that all linked UUID of given objects exist.
checkUUIDRefs :: (UuidObject a, Show a, F.Foldable f)
=> String -> String
-> (a -> [String]) -> f a -> Container b
-> ValidationMonad ()
checkUUIDRefs whatObj whatTarget linkf xs targets = F.mapM_ check xs
where
uuids = keysSet targets
check x = forM_ (linkf x) $ \uuid ->
reportIf (not $ S.member (UTF8.fromString uuid) uuids)
$ whatObj ++ " '" ++ show x ++ "' references a non-existing "
++ whatTarget ++ " UUID '" ++ uuid ++ "'"
-- | Checks consistency of a given configuration.
--
-- TODO: Currently this implements only some very basic checks.
-- Evenually all checks from Python ConfigWriter need to be moved here
-- (see issue #759).
verifyConfig :: ConfigData -> ValidationMonad ()
verifyConfig cd = do
let cluster = configCluster cd
nodes = configNodes cd
nodegroups = configNodegroups cd
instances = configInstances cd
networks = configNetworks cd
disks = configDisks cd
-- global cluster checks
let enabledHvs = clusterEnabledHypervisors cluster
hvParams = clusterHvparams cluster
reportIf (null enabledHvs)
"enabled hypervisors list doesn't have any entries"
-- we don't need to check for invalid HVS as they would fail to parse
let missingHvp = S.fromList enabledHvs S.\\ keysSet hvParams
reportIf (not $ S.null missingHvp)
$ "hypervisor parameters missing for the enabled hypervisor(s) "
++ (commaJoin . map hypervisorToRaw . S.toList $ missingHvp)
let enabledDiskTemplates = clusterEnabledDiskTemplates cluster
reportIf (null enabledDiskTemplates)
"enabled disk templates list doesn't have any entries"
-- we don't need to check for invalid templates as they wouldn't parse
let masterNodeName = clusterMasterNode cluster
reportIf (not $ UTF8.fromString masterNodeName
`S.member` keysSet (configNodes cd))
$ "cluster has invalid primary node " ++ masterNodeName
-- UUIDs
checkUUIDKeys "node" nodes
checkUUIDKeys "nodegroup" nodegroups
checkUUIDKeys "instances" instances
checkUUIDKeys "network" networks
checkUUIDKeys "disk" disks
-- UUID references
checkUUIDRefs "node" "nodegroup" (return . nodeGroup) nodes nodegroups
checkUUIDRefs "instance" "primary node" (maybe [] return . instPrimaryNode)
instances nodes
checkUUIDRefs "instance" "disks" instDisks instances disks
-- | Checks consistency of a given configuration.
-- If there is an error, throw 'ConfigVerifyError'.
verifyConfigErr :: (MonadError GanetiException m) => ConfigData -> m ()
verifyConfigErr cd =
case runValidate $ verifyConfig cd of
(_, []) -> return ()
(_, es) -> throwError $ ConfigVerifyError "Validation failed" es
| leshchevds/ganeti | src/Ganeti/WConfd/ConfigVerify.hs | bsd-2-clause | 5,459 | 0 | 23 | 1,220 | 934 | 480 | 454 | 72 | 2 |
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
module Parse.Declaration where
import Text.Parsec ( (<|>), (<?>), choice, digit, optionMaybe, string, try )
import qualified AST.Declaration as D
import qualified Parse.Expression as Expr
import Parse.Helpers as Help
import qualified Parse.Type as Type
declaration :: IParser D.SourceDecl
declaration =
choice
[ D.Comment <$> Help.docComment
, D.Decl <$> addLocation (typeDecl <|> infixDecl <|> port <|> definition)
]
-- TYPE ANNOTATIONS and DEFINITIONS
definition :: IParser D.SourceDecl'
definition =
D.Definition
<$> (Expr.typeAnnotation <|> Expr.definition)
<?> "a value definition"
-- TYPE ALIAS and UNION TYPES
typeDecl :: IParser D.SourceDecl'
typeDecl =
do try (reserved "type") <?> "a type declaration"
forcedWS
isAlias <- optionMaybe (string "alias" >> forcedWS)
name <- capVar
args <- spacePrefix lowVar
padded equals
case isAlias of
Just _ ->
do tipe <- Type.expr <?> "a type"
return (D.TypeAlias name args tipe)
Nothing ->
do tcs <- pipeSep1 Type.constructor <?> "a constructor for a union type"
return $ D.Datatype name args tcs
-- INFIX
infixDecl :: IParser D.SourceDecl'
infixDecl =
expecting "an infix declaration" $
do assoc <-
choice
[ try (reserved "infixl") >> return D.L
, try (reserved "infixr") >> return D.R
, try (reserved "infix") >> return D.N
]
forcedWS
n <- digit
forcedWS
D.Fixity assoc (read [n]) <$> anyOp
-- PORT
port :: IParser D.SourceDecl'
port =
expecting "a port declaration" $
do try (reserved "port")
whitespace
name <- lowVar
whitespace
choice [ portAnnotation name, portDefinition name ]
where
portAnnotation name =
do try hasType
whitespace
tipe <- Type.expr <?> "a type"
return (D.Port (D.PortAnnotation name tipe))
portDefinition name =
do try equals
whitespace
expr <- Expr.expr
return (D.Port (D.PortDefinition name expr))
| laszlopandy/elm-compiler | src/Parse/Declaration.hs | bsd-3-clause | 2,181 | 0 | 15 | 628 | 630 | 311 | 319 | 62 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Int.BoundedInt.BoundedIntText (
-- * The BoundedIntText Widget
BoundedIntText,
-- * Constructor
mkBoundedIntText) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Data.Aeson
import qualified Data.HashMap.Strict as HM
import Data.IORef (newIORef)
import qualified Data.Scientific as Sci
import Data.Text (Text)
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
-- | 'BoundedIntText' represents an BoundedIntText widget from IPython.html.widgets.
type BoundedIntText = IPythonWidget BoundedIntTextType
-- | Create a new widget
mkBoundedIntText :: IO BoundedIntText
mkBoundedIntText = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetState = WidgetState $ defaultBoundedIntWidget "IntTextView"
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay BoundedIntText where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget BoundedIntText where
getCommUUID = uuid
comm widget (Object dict1) _ = do
let key1 = "sync_data" :: Text
key2 = "value" :: Text
Just (Object dict2) = HM.lookup key1 dict1
Just (Number value) = HM.lookup key2 dict2
setField' widget IntValue (Sci.coefficient value)
triggerChange widget
| artuuge/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Int/BoundedInt/BoundedIntText.hs | mit | 1,875 | 0 | 13 | 418 | 352 | 191 | 161 | 40 | 1 |
-- | "Real" Frontend to the static binary.
module Main (main) where
import Yi.Boot (yiDriver)
import Yi.Config.Default (defaultConfig)
main :: IO ()
main = yiDriver defaultConfig
| atsukotakahashi/wi | src/executable/Main.hs | gpl-2.0 | 182 | 0 | 6 | 29 | 49 | 29 | 20 | 5 | 1 |
-- (c) The University of Glasgow, 1997-2006
{-# LANGUAGE BangPatterns, CPP, DeriveDataTypeable, MagicHash, UnboxedTuples #-}
{-# OPTIONS_GHC -O -funbox-strict-fields #-}
-- We always optimise this, otherwise performance of a non-optimised
-- compiler is severely affected
-- |
-- There are two principal string types used internally by GHC:
--
-- ['FastString']
--
-- * A compact, hash-consed, representation of character strings.
-- * Comparison is O(1), and you can get a 'Unique.Unique' from them.
-- * Generated by 'fsLit'.
-- * Turn into 'Outputable.SDoc' with 'Outputable.ftext'.
--
-- ['LitString']
--
-- * Just a wrapper for the @Addr#@ of a C string (@Ptr CChar@).
-- * Practically no operations.
-- * Outputing them is fast.
-- * Generated by 'sLit'.
-- * Turn into 'Outputable.SDoc' with 'Outputable.ptext'
--
-- Use 'LitString' unless you want the facilities of 'FastString'.
module FastString
(
-- * ByteString
fastStringToByteString,
mkFastStringByteString,
fastZStringToByteString,
unsafeMkByteString,
hashByteString,
-- * FastZString
FastZString,
hPutFZS,
zString,
lengthFZS,
-- * FastStrings
FastString(..), -- not abstract, for now.
-- ** Construction
fsLit,
mkFastString,
mkFastStringBytes,
mkFastStringByteList,
mkFastStringForeignPtr,
mkFastString#,
-- ** Deconstruction
unpackFS, -- :: FastString -> String
bytesFS, -- :: FastString -> [Word8]
-- ** Encoding
zEncodeFS,
-- ** Operations
uniqueOfFS,
lengthFS,
nullFS,
appendFS,
headFS,
tailFS,
concatFS,
consFS,
nilFS,
-- ** Outputing
hPutFS,
-- ** Internal
getFastStringTable,
hasZEncoding,
-- * LitStrings
LitString,
-- ** Construction
sLit,
mkLitString#,
mkLitString,
-- ** Deconstruction
unpackLitString,
-- ** Operations
lengthLS
) where
#include "HsVersions.h"
import Encoding
import FastTypes
import FastFunctions
import Panic
import Util
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Internal as BS
import qualified Data.ByteString.Unsafe as BS
import Foreign.C
import ExtsCompat46
import System.IO
import System.IO.Unsafe ( unsafePerformIO )
import Data.Data
import Data.IORef ( IORef, newIORef, readIORef, atomicModifyIORef )
import Data.Maybe ( isJust )
import Data.Char
import Data.List ( elemIndex )
import GHC.IO ( IO(..), unsafeDupablePerformIO )
#if __GLASGOW_HASKELL__ >= 709
import Foreign
#else
import Foreign.Safe
#endif
#if STAGE >= 2
import GHC.Conc.Sync (sharedCAF)
#endif
import GHC.Base ( unpackCString# )
#define hASH_TBL_SIZE 4091
#define hASH_TBL_SIZE_UNBOXED 4091#
fastStringToByteString :: FastString -> ByteString
fastStringToByteString f = fs_bs f
fastZStringToByteString :: FastZString -> ByteString
fastZStringToByteString (FastZString bs) = bs
-- This will drop information if any character > '\xFF'
unsafeMkByteString :: String -> ByteString
unsafeMkByteString = BSC.pack
hashByteString :: ByteString -> Int
hashByteString bs
= inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) ->
return $ hashStr (castPtr ptr) len
-- -----------------------------------------------------------------------------
newtype FastZString = FastZString ByteString
hPutFZS :: Handle -> FastZString -> IO ()
hPutFZS handle (FastZString bs) = BS.hPut handle bs
zString :: FastZString -> String
zString (FastZString bs) =
inlinePerformIO $ BS.unsafeUseAsCStringLen bs peekCAStringLen
lengthFZS :: FastZString -> Int
lengthFZS (FastZString bs) = BS.length bs
mkFastZStringString :: String -> FastZString
mkFastZStringString str = FastZString (BSC.pack str)
-- -----------------------------------------------------------------------------
{-|
A 'FastString' is an array of bytes, hashed to support fast O(1)
comparison. It is also associated with a character encoding, so that
we know how to convert a 'FastString' to the local encoding, or to the
Z-encoding used by the compiler internally.
'FastString's support a memoized conversion to the Z-encoding via zEncodeFS.
-}
data FastString = FastString {
uniq :: {-# UNPACK #-} !Int, -- unique id
n_chars :: {-# UNPACK #-} !Int, -- number of chars
fs_bs :: {-# UNPACK #-} !ByteString,
fs_ref :: {-# UNPACK #-} !(IORef (Maybe FastZString))
} deriving Typeable
instance Eq FastString where
f1 == f2 = uniq f1 == uniq f2
instance Ord FastString where
-- Compares lexicographically, not by unique
a <= b = case cmpFS a b of { LT -> True; EQ -> True; GT -> False }
a < b = case cmpFS a b of { LT -> True; EQ -> False; GT -> False }
a >= b = case cmpFS a b of { LT -> False; EQ -> True; GT -> True }
a > b = case cmpFS a b of { LT -> False; EQ -> False; GT -> True }
max x y | x >= y = x
| otherwise = y
min x y | x <= y = x
| otherwise = y
compare a b = cmpFS a b
instance Show FastString where
show fs = show (unpackFS fs)
instance Data FastString where
-- don't traverse?
toConstr _ = abstractConstr "FastString"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "FastString"
cmpFS :: FastString -> FastString -> Ordering
cmpFS f1@(FastString u1 _ _ _) f2@(FastString u2 _ _ _) =
if u1 == u2 then EQ else
compare (fastStringToByteString f1) (fastStringToByteString f2)
foreign import ccall unsafe "ghc_memcmp"
memcmp :: Ptr a -> Ptr b -> Int -> IO Int
-- -----------------------------------------------------------------------------
-- Construction
{-
Internally, the compiler will maintain a fast string symbol table, providing
sharing and fast comparison. Creation of new @FastString@s then covertly does a
lookup, re-using the @FastString@ if there was a hit.
The design of the FastString hash table allows for lockless concurrent reads
and updates to multiple buckets with low synchronization overhead.
See Note [Updating the FastString table] on how it's updated.
-}
data FastStringTable =
FastStringTable
{-# UNPACK #-} !(IORef Int) -- the unique ID counter shared with all buckets
(MutableArray# RealWorld (IORef [FastString])) -- the array of mutable buckets
string_table :: FastStringTable
{-# NOINLINE string_table #-}
string_table = unsafePerformIO $ do
uid <- newIORef 603979776 -- ord '$' * 0x01000000
tab <- IO $ \s1# -> case newArray# hASH_TBL_SIZE_UNBOXED (panic "string_table") s1# of
(# s2#, arr# #) ->
(# s2#, FastStringTable uid arr# #)
forM_ [0.. hASH_TBL_SIZE-1] $ \i -> do
bucket <- newIORef []
updTbl tab i bucket
-- use the support wired into the RTS to share this CAF among all images of
-- libHSghc
#if STAGE < 2
return tab
#else
sharedCAF tab getOrSetLibHSghcFastStringTable
-- from the RTS; thus we cannot use this mechanism when STAGE<2; the previous
-- RTS might not have this symbol
foreign import ccall unsafe "getOrSetLibHSghcFastStringTable"
getOrSetLibHSghcFastStringTable :: Ptr a -> IO (Ptr a)
#endif
{-
We include the FastString table in the `sharedCAF` mechanism because we'd like
FastStrings created by a Core plugin to have the same uniques as corresponding
strings created by the host compiler itself. For example, this allows plugins
to lookup known names (eg `mkTcOcc "MySpecialType"`) in the GlobalRdrEnv or
even re-invoke the parser.
In particular, the following little sanity test was failing in a plugin
prototyping safe newtype-coercions: GHC.NT.Type.NT was imported, but could not
be looked up /by the plugin/.
let rdrName = mkModuleName "GHC.NT.Type" `mkRdrQual` mkTcOcc "NT"
putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts
`mkTcOcc` involves the lookup (or creation) of a FastString. Since the
plugin's FastString.string_table is empty, constructing the RdrName also
allocates new uniques for the FastStrings "GHC.NT.Type" and "NT". These
uniques are almost certainly unequal to the ones that the host compiler
originally assigned to those FastStrings. Thus the lookup fails since the
domain of the GlobalRdrEnv is affected by the RdrName's OccName's FastString's
unique.
The old `reinitializeGlobals` mechanism is enough to provide the plugin with
read-access to the table, but it insufficient in the general case where the
plugin may allocate FastStrings. This mutates the supply for the FastStrings'
unique, and that needs to be propagated back to the compiler's instance of the
global variable. Such propagation is beyond the `reinitializeGlobals`
mechanism.
Maintaining synchronization of the two instances of this global is rather
difficult because of the uses of `unsafePerformIO` in this module. Not
synchronizing them risks breaking the rather major invariant that two
FastStrings with the same unique have the same string. Thus we use the
lower-level `sharedCAF` mechanism that relies on Globals.c.
-}
lookupTbl :: FastStringTable -> Int -> IO (IORef [FastString])
lookupTbl (FastStringTable _ arr#) (I# i#) =
IO $ \ s# -> readArray# arr# i# s#
updTbl :: FastStringTable -> Int -> IORef [FastString] -> IO ()
updTbl (FastStringTable _uid arr#) (I# i#) ls = do
(IO $ \ s# -> case writeArray# arr# i# ls s# of { s2# -> (# s2#, () #) })
mkFastString# :: Addr# -> FastString
mkFastString# a# = mkFastStringBytes ptr (ptrStrLength ptr)
where ptr = Ptr a#
{- Note [Updating the FastString table]
The procedure goes like this:
1. Read the relevant bucket and perform a look up of the string.
2. If it exists, return it.
3. Otherwise grab a unique ID, create a new FastString and atomically attempt
to update the relevant bucket with this FastString:
* Double check that the string is not in the bucket. Another thread may have
inserted it while we were creating our string.
* Return the existing FastString if it exists. The one we preemptively
created will get GCed.
* Otherwise, insert and return the string we created.
-}
{- Note [Double-checking the bucket]
It is not necessary to check the entire bucket the second time. We only have to
check the strings that are new to the bucket since the last time we read it.
-}
mkFastStringWith :: (Int -> IO FastString) -> Ptr Word8 -> Int -> IO FastString
mkFastStringWith mk_fs !ptr !len = do
let hash = hashStr ptr len
bucket <- lookupTbl string_table hash
ls1 <- readIORef bucket
res <- bucket_match ls1 len ptr
case res of
Just v -> return v
Nothing -> do
n <- get_uid
new_fs <- mk_fs n
atomicModifyIORef bucket $ \ls2 ->
-- Note [Double-checking the bucket]
let delta_ls = case ls1 of
[] -> ls2
l:_ -> case l `elemIndex` ls2 of
Nothing -> panic "mkFastStringWith"
Just idx -> take idx ls2
-- NB: Might as well use inlinePerformIO, since the call to
-- bucket_match doesn't perform any IO that could be floated
-- out of this closure or erroneously duplicated.
in case inlinePerformIO (bucket_match delta_ls len ptr) of
Nothing -> (new_fs:ls2, new_fs)
Just fs -> (ls2,fs)
where
!(FastStringTable uid _arr) = string_table
get_uid = atomicModifyIORef uid $ \n -> (n+1,n)
mkFastStringBytes :: Ptr Word8 -> Int -> FastString
mkFastStringBytes !ptr !len =
-- NB: Might as well use unsafeDupablePerformIO, since mkFastStringWith is
-- idempotent.
unsafeDupablePerformIO $
mkFastStringWith (copyNewFastString ptr len) ptr len
-- | Create a 'FastString' from an existing 'ForeignPtr'; the difference
-- between this and 'mkFastStringBytes' is that we don't have to copy
-- the bytes if the string is new to the table.
mkFastStringForeignPtr :: Ptr Word8 -> ForeignPtr Word8 -> Int -> IO FastString
mkFastStringForeignPtr ptr !fp len
= mkFastStringWith (mkNewFastString fp ptr len) ptr len
-- | Create a 'FastString' from an existing 'ForeignPtr'; the difference
-- between this and 'mkFastStringBytes' is that we don't have to copy
-- the bytes if the string is new to the table.
mkFastStringByteString :: ByteString -> FastString
mkFastStringByteString bs =
inlinePerformIO $
BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> do
let ptr' = castPtr ptr
mkFastStringWith (mkNewFastStringByteString bs ptr' len) ptr' len
-- | Creates a UTF-8 encoded 'FastString' from a 'String'
mkFastString :: String -> FastString
mkFastString str =
inlinePerformIO $ do
let l = utf8EncodedLength str
buf <- mallocForeignPtrBytes l
withForeignPtr buf $ \ptr -> do
utf8EncodeString ptr str
mkFastStringForeignPtr ptr buf l
-- | Creates a 'FastString' from a UTF-8 encoded @[Word8]@
mkFastStringByteList :: [Word8] -> FastString
mkFastStringByteList str =
inlinePerformIO $ do
let l = Prelude.length str
buf <- mallocForeignPtrBytes l
withForeignPtr buf $ \ptr -> do
pokeArray (castPtr ptr) str
mkFastStringForeignPtr ptr buf l
-- | Creates a Z-encoded 'FastString' from a 'String'
mkZFastString :: String -> FastZString
mkZFastString = mkFastZStringString
bucket_match :: [FastString] -> Int -> Ptr Word8 -> IO (Maybe FastString)
bucket_match [] _ _ = return Nothing
bucket_match (v@(FastString _ _ bs _):ls) len ptr
| len == BS.length bs = do
b <- BS.unsafeUseAsCString bs $ \buf ->
cmpStringPrefix ptr (castPtr buf) len
if b then return (Just v)
else bucket_match ls len ptr
| otherwise =
bucket_match ls len ptr
mkNewFastString :: ForeignPtr Word8 -> Ptr Word8 -> Int -> Int
-> IO FastString
mkNewFastString fp ptr len uid = do
ref <- newIORef Nothing
n_chars <- countUTF8Chars ptr len
return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref)
mkNewFastStringByteString :: ByteString -> Ptr Word8 -> Int -> Int
-> IO FastString
mkNewFastStringByteString bs ptr len uid = do
ref <- newIORef Nothing
n_chars <- countUTF8Chars ptr len
return (FastString uid n_chars bs ref)
copyNewFastString :: Ptr Word8 -> Int -> Int -> IO FastString
copyNewFastString ptr len uid = do
fp <- copyBytesToForeignPtr ptr len
ref <- newIORef Nothing
n_chars <- countUTF8Chars ptr len
return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref)
copyBytesToForeignPtr :: Ptr Word8 -> Int -> IO (ForeignPtr Word8)
copyBytesToForeignPtr ptr len = do
fp <- mallocForeignPtrBytes len
withForeignPtr fp $ \ptr' -> copyBytes ptr' ptr len
return fp
cmpStringPrefix :: Ptr Word8 -> Ptr Word8 -> Int -> IO Bool
cmpStringPrefix ptr1 ptr2 len =
do r <- memcmp ptr1 ptr2 len
return (r == 0)
hashStr :: Ptr Word8 -> Int -> Int
-- use the Addr to produce a hash value between 0 & m (inclusive)
hashStr (Ptr a#) (I# len#) = loop 0# 0#
where
loop h n | n ExtsCompat46.==# len# = I# h
| otherwise = loop h2 (n ExtsCompat46.+# 1#)
where !c = ord# (indexCharOffAddr# a# n)
!h2 = (c ExtsCompat46.+# (h ExtsCompat46.*# 128#)) `remInt#`
hASH_TBL_SIZE#
-- -----------------------------------------------------------------------------
-- Operations
-- | Returns the length of the 'FastString' in characters
lengthFS :: FastString -> Int
lengthFS f = n_chars f
-- | Returns @True@ if this 'FastString' is not Z-encoded but already has
-- a Z-encoding cached (used in producing stats).
hasZEncoding :: FastString -> Bool
hasZEncoding (FastString _ _ _ ref) =
inlinePerformIO $ do
m <- readIORef ref
return (isJust m)
-- | Returns @True@ if the 'FastString' is empty
nullFS :: FastString -> Bool
nullFS f = BS.null (fs_bs f)
-- | Unpacks and decodes the FastString
unpackFS :: FastString -> String
unpackFS (FastString _ _ bs _) =
inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) ->
utf8DecodeString (castPtr ptr) len
-- | Gives the UTF-8 encoded bytes corresponding to a 'FastString'
bytesFS :: FastString -> [Word8]
bytesFS fs = BS.unpack $ fastStringToByteString fs
-- | Returns a Z-encoded version of a 'FastString'. This might be the
-- original, if it was already Z-encoded. The first time this
-- function is applied to a particular 'FastString', the results are
-- memoized.
--
zEncodeFS :: FastString -> FastZString
zEncodeFS fs@(FastString _ _ _ ref) =
inlinePerformIO $ do
m <- readIORef ref
case m of
Just zfs -> return zfs
Nothing -> do
atomicModifyIORef ref $ \m' -> case m' of
Nothing -> let zfs = mkZFastString (zEncodeString (unpackFS fs))
in (Just zfs, zfs)
Just zfs -> (m', zfs)
appendFS :: FastString -> FastString -> FastString
appendFS fs1 fs2 = mkFastStringByteString
$ BS.append (fastStringToByteString fs1)
(fastStringToByteString fs2)
concatFS :: [FastString] -> FastString
concatFS ls = mkFastString (Prelude.concat (map unpackFS ls)) -- ToDo: do better
headFS :: FastString -> Char
headFS (FastString _ 0 _ _) = panic "headFS: Empty FastString"
headFS (FastString _ _ bs _) =
inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr ->
return (fst (utf8DecodeChar (castPtr ptr)))
tailFS :: FastString -> FastString
tailFS (FastString _ 0 _ _) = panic "tailFS: Empty FastString"
tailFS (FastString _ _ bs _) =
inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr ->
do let (_, n) = utf8DecodeChar (castPtr ptr)
return $! mkFastStringByteString (BS.drop n bs)
consFS :: Char -> FastString -> FastString
consFS c fs = mkFastString (c : unpackFS fs)
uniqueOfFS :: FastString -> FastInt
uniqueOfFS (FastString u _ _ _) = iUnbox u
nilFS :: FastString
nilFS = mkFastString ""
-- -----------------------------------------------------------------------------
-- Stats
getFastStringTable :: IO [[FastString]]
getFastStringTable = do
buckets <- forM [0.. hASH_TBL_SIZE-1] $ \idx -> do
bucket <- lookupTbl string_table idx
readIORef bucket
return buckets
-- -----------------------------------------------------------------------------
-- Outputting 'FastString's
-- |Outputs a 'FastString' with /no decoding at all/, that is, you
-- get the actual bytes in the 'FastString' written to the 'Handle'.
hPutFS :: Handle -> FastString -> IO ()
hPutFS handle fs = BS.hPut handle $ fastStringToByteString fs
-- ToDo: we'll probably want an hPutFSLocal, or something, to output
-- in the current locale's encoding (for error messages and suchlike).
-- -----------------------------------------------------------------------------
-- LitStrings, here for convenience only.
-- hmm, not unboxed (or rather FastPtr), interesting
--a.k.a. Ptr CChar, Ptr Word8, Ptr (), hmph. We don't
--really care about C types in naming, where we can help it.
type LitString = Ptr Word8
--Why do we recalculate length every time it's requested?
--If it's commonly needed, we should perhaps have
--data LitString = LitString {-#UNPACK#-}!(FastPtr Word8) {-#UNPACK#-}!FastInt
mkLitString# :: Addr# -> LitString
mkLitString# a# = Ptr a#
--can/should we use FastTypes here?
--Is this likely to be memory-preserving if only used on constant strings?
--should we inline it? If lucky, that would make a CAF that wouldn't
--be computationally repeated... although admittedly we're not
--really intending to use mkLitString when __GLASGOW_HASKELL__...
--(I wonder, is unicode / multi-byte characters allowed in LitStrings
-- at all?)
{-# INLINE mkLitString #-}
mkLitString :: String -> LitString
mkLitString s =
unsafePerformIO (do
p <- mallocBytes (length s + 1)
let
loop :: Int -> String -> IO ()
loop !n [] = pokeByteOff p n (0 :: Word8)
loop n (c:cs) = do
pokeByteOff p n (fromIntegral (ord c) :: Word8)
loop (1+n) cs
loop 0 s
return p
)
unpackLitString :: LitString -> String
unpackLitString p_ = case pUnbox p_ of
p -> unpack (_ILIT(0))
where
unpack n = case indexWord8OffFastPtrAsFastChar p n of
ch -> if ch `eqFastChar` _CLIT('\0')
then [] else cBox ch : unpack (n +# _ILIT(1))
lengthLS :: LitString -> Int
lengthLS = ptrStrLength
-- for now, use a simple String representation
--no, let's not do that right now - it's work in other places
#if 0
type LitString = String
mkLitString :: String -> LitString
mkLitString = id
unpackLitString :: LitString -> String
unpackLitString = id
lengthLS :: LitString -> Int
lengthLS = length
#endif
-- -----------------------------------------------------------------------------
-- under the carpet
foreign import ccall unsafe "ghc_strlen"
ptrStrLength :: Ptr Word8 -> Int
{-# NOINLINE sLit #-}
sLit :: String -> LitString
sLit x = mkLitString x
{-# NOINLINE fsLit #-}
fsLit :: String -> FastString
fsLit x = mkFastString x
{-# RULES "slit"
forall x . sLit (unpackCString# x) = mkLitString# x #-}
{-# RULES "fslit"
forall x . fsLit (unpackCString# x) = mkFastString# x #-}
| forked-upstream-packages-for-ghcjs/ghc | compiler/utils/FastString.hs | bsd-3-clause | 21,604 | 0 | 26 | 4,917 | 4,223 | 2,189 | 2,034 | 328 | 5 |
{-# OPTIONS_GHC -cpp #-}
{-# OPTIONS -fglasgow-exts #-}
{-# LANGUAGE MultiParamTypeClasses, OverlappingInstances, UndecidableInstances, FunctionalDependencies, NoMonomorphismRestriction #-}
{-+
This module defines a number of classes that captures various forms of IO.
This allows code to specify IO operations without being tied directly to
the standard #IO# monad.
Instances for the standard #IO# type as well as for all monad transformers
(for all classes except one) are provided. This allows the IO operations to
be used without explicit lifting in monads that extend the IO monad by
an arbitrary number of monad transformers.
Note that we redefine some functions exported from the #Prelude#. To be able
to use these, you need to refer to them by a qualified name, or exclude the
Prelude functions from the unqualified name space by explicitly importing
the #Prelude# and hiding them (as shown below, for example).
By the way, it *is* annoying that #Functor# isn't a superclass of
#Monad#, isn't it!
-}
module AbstractIO(module AbstractIO,
IOError,ClockTime,S.ExitCode(..)) where
import Prelude hiding (readFile,writeFile, appendFile,
putStr,putStrLn,print,
getLine,readLn,getContents,
catch,ioError,userError)
import qualified Prelude
import qualified System.Directory as D
-- import qualified System as S
import qualified System.Exit as S
import qualified System.Cmd as S
import qualified System.Environment as S
import qualified System.IO as IO
import qualified System.IO.Error as IO
import qualified System.Time as Time
import System.Time(ClockTime,CalendarTime)
import MT(MT(..))
{-+
Reading and writing files
-------------------------
-}
class (Functor io,Monad io) => FileIO io where
readFile :: FilePath -> io String
writeFile :: FilePath -> String -> io ()
appendFile :: FilePath -> String -> io ()
instance FileIO IO where
readFile = Prelude.readFile
writeFile = Prelude.writeFile
appendFile = Prelude.appendFile
instance (MT t,Functor (t m),Monad (t m),FileIO m) => FileIO (t m) where
readFile = lift . readFile
writeFile path = lift . writeFile path
appendFile path = lift . appendFile path
{-+
Standard IO
-----------
(For messages in the terminal window and user input.)
-}
class (Functor io,Monad io) => StdIO io where
putStr,putStrLn,ePutStr,ePutStrLn :: String -> io ()
getLine :: io String -- blocking IO is considered bad by some... :-)
getContents :: io String
putStrLn s = putStr s >> putStr "\n"
ePutStrLn s = ePutStr s >> ePutStr "\n"
print x = putStrLn (show x)
readIO s = case [x | (x,t) <- reads s, ("","") <- lex t] of
[x] -> return x
[] -> ioError (userError "Prelude.readIO: no parse")
_ -> ioError (userError "Prelude.readIO: ambiguous parse")
instance StdIO IO where
putStr = Prelude.putStr
putStrLn = Prelude.putStrLn
ePutStr = IO.hPutStr IO.stderr
ePutStrLn = IO.hPutStrLn IO.stderr
getLine = Prelude.getLine
getContents = Prelude.getContents
instance (MT t,Functor (t m),Monad (t m),StdIO m) => StdIO (t m) where
putStr = lift . putStr
putStrLn = lift . putStrLn
ePutStr = lift . ePutStr
ePutStrLn = lift . ePutStrLn
getLine = lift getLine
getContents = lift getContents
{-+
System interaction
------------------
Operations corresponding to the standard library module #System#.
(Executing shell commands and other interaction with command line shells.)
-}
class (Functor io,Monad io) => SystemIO io where
system :: String -> io S.ExitCode
getEnv :: String -> io String
getProgName :: io String
getArgs :: io [String]
-- ... exitWith
instance SystemIO IO where
system = S.system
getEnv = S.getEnv
getProgName = S.getProgName
getArgs = S.getArgs
instance (MT t,Functor (t m),Monad (t m),SystemIO m) => SystemIO (t m) where
system = lift . system
getEnv = lift . getEnv
getProgName = lift getProgName
getArgs = lift getArgs
{-+
Directory manipulation
----------------------
Operations corresponding to the standard library module #Directory#.
-}
class (Functor io,Monad io) => DirectoryIO io where
createDirectory,removeFile :: FilePath -> io ()
getModificationTime :: FilePath -> io ClockTime
doesFileExist, doesDirectoryExist :: FilePath -> io Bool
getDirectoryContents :: FilePath -> io [FilePath]
-- Base case:
instance DirectoryIO IO where
createDirectory = D.createDirectory
getModificationTime = D.getModificationTime
doesFileExist = D.doesFileExist
doesDirectoryExist = D.doesDirectoryExist . dropFinalSlash
getDirectoryContents = D.getDirectoryContents
removeFile = D.removeFile
-- Quick workaround for a Cygwin problem:
dropFinalSlash = reverse . dropit . reverse
where dropit ('/':s) = s
dropit s = s
-- Inductive case:
instance (MT t,Functor (t m),Monad (t m),DirectoryIO m)
=> DirectoryIO (t m) where
createDirectory = lift . createDirectory
getModificationTime = lift . getModificationTime
doesFileExist = lift . doesFileExist
doesDirectoryExist = lift . doesDirectoryExist
getDirectoryContents = lift . getDirectoryContents
removeFile = lift . removeFile
{-+
Time functions
----------------------
Operations corresponding to the standard library module #Time#.
(Only the subset requiring IO.)
-}
class (Functor m,Monad m) => TimeIO m where
getClockTime :: m ClockTime
toCalendarTime :: ClockTime -> m CalendarTime
instance TimeIO IO where
getClockTime = Time.getClockTime
toCalendarTime = Time.toCalendarTime
instance (MT t,Functor (t m),Monad (t m),TimeIO m) => TimeIO (t m) where
getClockTime = lift getClockTime
toCalendarTime = lift . toCalendarTime
{-+
Catching errors
---------------
This is the only class that lacks a general instance for monad transformers.
(It is probably a good idea to try to survive without relying on error
handlers...)
-}
class (Functor io,Monad io) => CatchIO ioerror io | io->ioerror where
catch :: io a -> (ioerror -> io a) -> io a
ioError :: ioerror -> io a
try m = fmap Right m `catch` (return . Left)
maybeM m = (Just `fmap` m) `catch` const (return Nothing)
bracket before after m =
do x <- before
r <- try (m x)
after x
returnTry r
bracket_ before after m =
do x <- before
r <- try m
after x
returnTry r
tryThen m after =
do r <- try m
after
returnTry r
returnTry r = either ioError return r
instance CatchIO IOError IO where
catch = Prelude.catch
ioError = Prelude.ioError
--instance (MT t,Functor (t m),Monad (t m),CatchIO m) => CatchIO (t m) where
-- !! How do you lift operations with negative occurences of m?
class IOErr ioerror where
userError :: String -> ioerror
isDoesNotExistError,isUserError :: ioerror -> Bool
ioeGetErrorString :: ioerror -> String
-- ..., ioeGetFileName, ...
instance IOErr IOError where
userError = IO.userError
isDoesNotExistError = IO.isDoesNotExistError
isUserError = IO.isUserError
ioeGetErrorString = IO.ioeGetErrorString
| kmate/HaRe | old/tools/base/lib/AbstractIO.hs | bsd-3-clause | 7,035 | 9 | 11 | 1,370 | 1,710 | 916 | 794 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Doc.Extending
-- Copyright : (C) 2007 Andrea Rossato
-- License : BSD3
--
-- Maintainer : andrea.rossato@unibz.it
-- Stability : unstable
-- Portability : portable
--
-- This module documents the xmonad-contrib library and
-- how to use it to extend the capabilities of xmonad.
--
-- Reading this document should not require a deep knowledge of
-- Haskell; the examples are intended to be useful and understandable
-- for those users who do not know Haskell and don't want to have to
-- learn it just to configure xmonad. You should be able to get by
-- just fine by ignoring anything you don't understand and using the
-- provided examples as templates. However, relevant Haskell features
-- are discussed when appropriate, so this document will hopefully be
-- useful for more advanced Haskell users as well.
--
-- Those wishing to be totally hardcore and develop their own xmonad
-- extensions (it's easier than it sounds, we promise!) should read
-- the documentation in "XMonad.Doc.Developing".
--
-- More configuration examples may be found on the Haskell wiki:
--
-- <http://haskell.org/haskellwiki/Xmonad/Config_archive>
--
-----------------------------------------------------------------------------
module XMonad.Doc.Extending
(
-- * The xmonad-contrib library
-- $library
-- ** Actions
-- $actions
-- ** Configurations
-- $configs
-- ** Hooks
-- $hooks
-- ** Layouts
-- $layouts
-- ** Prompts
-- $prompts
-- ** Utilities
-- $utils
-- * Extending xmonad
-- $extending
-- ** Editing key bindings
-- $keys
-- *** Adding key bindings
-- $keyAdding
-- *** Removing key bindings
-- $keyDel
-- *** Adding and removing key bindings
-- $keyAddDel
-- ** Editing mouse bindings
-- $mouse
-- ** Editing the layout hook
-- $layoutHook
-- ** Editing the manage hook
-- $manageHook
-- ** The log hook and external status bars
-- $logHook
) where
--------------------------------------------------------------------------------
--
-- The XmonadContrib Library
--
--------------------------------------------------------------------------------
{- $library
The xmonad-contrib (xmc) library is a set of extension modules
contributed by xmonad hackers and users, which provide additional
xmonad features. Examples include various layout modes (tabbed,
spiral, three-column...), prompts, program launchers, the ability to
manipulate windows and workspaces in various ways, alternate
navigation modes, and much more. There are also \"meta-modules\"
which make it easier to write new modules and extensions.
This is a concise yet complete overview of the xmonad-contrib modules.
For more information about any particular module, just click on its
name to view its Haddock documentation; each module should come with
extensive documentation. If you find a module that could be better
documented, or has incorrect documentation, please report it as a bug
(<http://code.google.com/p/xmonad/issues/list>)!
-}
{- $actions
In the @XMonad.Actions@ namespace you can find modules exporting
various functions that are usually intended to be bound to key
combinations or mouse actions, in order to provide functionality
beyond the standard keybindings provided by xmonad.
See "XMonad.Doc.Extending#Editing_key_bindings" for instructions on how to
edit your key bindings.
* "XMonad.Actions.Commands":
Allows you to run internal xmonad commands (X () actions) using
a dmenu menu in addition to key bindings. Requires dmenu and
the Dmenu XMonad.Actions module.
* "XMonad.Actions.ConstrainedResize":
Lets you constrain the aspect ratio of a floating
window (by, say, holding shift while you resize).
Useful for making a nice circular XClock window.
* "XMonad.Actions.CopyWindow":
Provides bindings to duplicate a window on multiple workspaces,
providing dwm-like tagging functionality.
* "XMonad.Actions.CycleRecentWS":
Provides bindings to cycle through most recently used workspaces
with repeated presses of a single key (as long as modifier key is
held down). This is similar to how many window managers handle
window switching.
* "XMonad.Actions.CycleSelectedLayouts":
This module allows to cycle through the given subset of layouts.
* "XMonad.Actions.CycleWS":
Provides bindings to cycle forward or backward through the list of
workspaces, to move windows between workspaces, and to cycle
between screens. Replaces the former XMonad.Actions.RotView.
* "XMonad.Actions.CycleWindows":
Provides bindings to cycle windows up or down on the current workspace
stack while maintaining focus in place.
* "XMonad.Actions.DeManage":
This module provides a method to cease management of a window
without unmapping it. "XMonad.Hooks.ManageDocks" is a
more automated solution if your panel supports it.
* "XMonad.Actions.DwmPromote":
Dwm-like swap function for xmonad.
Swaps focused window with the master window. If focus is in the
master, swap it with the next window in the stack. Focus stays in the
master.
* "XMonad.Actions.DynamicWorkspaces":
Provides bindings to add and delete workspaces. Note that you may only
delete a workspace that is already empty.
* "XMonad.Actions.FindEmptyWorkspace":
Find an empty workspace.
* "XMonad.Actions.FlexibleManipulate":
Move and resize floating windows without warping the mouse.
* "XMonad.Actions.FlexibleResize":
Resize floating windows from any corner.
* "XMonad.Actions.FloatKeys":
Move and resize floating windows.
* "XMonad.Actions.FloatSnap":
Move and resize floating windows using other windows and the edge of the
screen as guidelines.
* "XMonad.Actions.FocusNth":
Focus the nth window of the current workspace.
* "XMonad.Actions.GridSelect":
GridSelect displays items(e.g. the opened windows) in a 2D grid and lets
the user select from it with the cursor/hjkl keys or the mouse.
* "XMonad.Actions.MessageFeedback":
Alternative to 'XMonad.Operations.sendMessage' that provides knowledge
of whether the message was handled, and utility functions based on
this facility.
* "XMonad.Actions.MouseGestures":
Support for simple mouse gestures.
* "XMonad.Actions.MouseResize":
A layout modifier to resize windows with the mouse by grabbing the
window's lower right corner.
* "XMonad.Actions.NoBorders":
This module provides helper functions for dealing with window borders.
* "XMonad.Actions.OnScreen":
Control workspaces on different screens (in xinerama mode).
* "XMonad.Actions.PerWorkspaceKeys":
Define key-bindings on per-workspace basis.
* "XMonad.Actions.PhysicalScreens":
Manipulate screens ordered by physical location instead of ID
* "XMonad.Actions.Plane":
This module has functions to navigate through workspaces in a bidimensional
manner.
* "XMonad.Actions.Promote":
Alternate promote function for xmonad.
* "XMonad.Actions.RandomBackground":
An action to start terminals with a random background color
* "XMonad.Actions.RotSlaves":
Rotate all windows except the master window and keep the focus in
place.
* "XMonad.Actions.Search":
A module for easily running Internet searches on web sites through xmonad.
Modeled after the handy Surfraw CLI search tools at <https://secure.wikimedia.org/wikipedia/en/wiki/Surfraw>.
* "XMonad.Actions.SimpleDate":
An example external contrib module for XMonad.
Provides a simple binding to dzen2 to print the date as a popup menu.
* "XMonad.Actions.SinkAll":
(Deprecated) Provides a simple binding that pushes all floating windows on the
current workspace back into tiling. Instead, use the more general
"XMonad.Actions.WithAll"
* "XMonad.Actions.SpawnOn":
Provides a way to modify a window spawned by a command(e.g shift it to the workspace
it was launched on) by using the _NET_WM_PID property that most windows set on creation.
* "XMonad.Actions.Submap":
A module that allows the user to create a sub-mapping of key bindings.
* "XMonad.Actions.SwapWorkspaces":
Lets you swap workspace tags, so you can keep related ones next to
each other, without having to move individual windows.
* "XMonad.Actions.TagWindows":
Functions for tagging windows and selecting them by tags.
* "XMonad.Actions.TopicSpace":
Turns your workspaces into a more topic oriented system.
* "XMonad.Actions.UpdateFocus":
Updates the focus on mouse move in unfocused windows.
* "XMonad.Actions.UpdatePointer":
Causes the pointer to follow whichever window focus changes to.
* "XMonad.Actions.Warp":
Warp the pointer to a given window or screen.
* "XMonad.Actions.WindowBringer":
dmenu operations to bring windows to you, and bring you to windows.
That is to say, it pops up a dmenu with window names, in case you forgot
where you left your XChat.
* "XMonad.Actions.WindowGo":
Defines a few convenient operations for raising (traveling to) windows based on XMonad's Query
monad, such as 'runOrRaise'.
* "XMonad.Actions.WindowMenu":
Uses "XMonad.Actions.GridSelect" to display a number of actions related to
window management in the center of the focused window.
* "XMonad.Actions.WindowNavigation":
Experimental rewrite of "XMonad.Layout.WindowNavigation".
* "XMonad.Actions.WithAll":
Provides functions for performing a given action on all windows of
the current workspace.
* "XMonad.Actions.WorkspaceCursors":
Like "XMonad.Actions.Plane" for an arbitrary number of dimensions.
-}
{- $configs
In the @XMonad.Config@ namespace you can find modules exporting the
configurations used by some of the xmonad and xmonad-contrib
developers. You can look at them for examples while creating your own
configuration; you can also simply import them and use them as your
own configuration, possibly with some modifications.
* "XMonad.Config.Arossato"
This module specifies my xmonad defaults.
* "XMonad.Config.Azerty"
Fixes some keybindings for users of French keyboard layouts.
* "XMonad.Config.Desktop"
This module provides core desktop environment settings used
in the Gnome, Kde, and Xfce config configs. It is also useful
for people using other environments such as lxde, or using
tray or panel applications without full desktop environments.
* "XMonad.Config.Gnome"
* "XMonad.Config.Kde"
* "XMonad.Config.Sjanssen"
* "XMonad.Config.Xfce"
-}
{- $hooks
In the @XMonad.Hooks@ namespace you can find modules exporting
hooks. Hooks are actions that xmonad performs when certain events
occur. The two most important hooks are:
* 'XMonad.Core.manageHook': this hook is called when a new window
xmonad must take care of is created. This is a very powerful hook,
since it lets us examine the new window's properties and act
accordingly. For instance, we can configure xmonad to put windows
belonging to a given application in the float layer, not to manage
dock applications, or open them in a given workspace. See
"XMonad.Doc.Extending#Editing_the_manage_hook" for more information on
customizing 'XMonad.Core.manageHook'.
* 'XMonad.Core.logHook': this hook is called when the stack of windows
managed by xmonad has been changed, by calling the
'XMonad.Operations.windows' function. For instance
"XMonad.Hooks.DynamicLog" will produce a string (whose format can be
configured) to be printed to the standard output. This can be used
to display some information about the xmonad state in a status bar.
See "XMonad.Doc.Extending#The_log_hook_and_external_status_bars" for more
information.
* 'XMonad.Core.handleEventHook': this hook is called on all events handled
by xmonad, thus it is extremely powerful. See "Graphics.X11.Xlib.Extras"
and xmonad source and development documentation for more details.
Here is a list of the modules found in @XMonad.Hooks@:
* "XMonad.Hooks.DynamicHooks":
One-shot and permanent ManageHooks that can be updated at runtime.
* "XMonad.Hooks.DynamicLog": for use with 'XMonad.Core.logHook'; send
information about xmonad's state to standard output, suitable for
putting in a status bar of some sort. See
"XMonad.Doc.Extending#The_log_hook_and_external_status_bars".
* "XMonad.Hooks.EwmhDesktops":
Makes xmonad use the EWMH hints to tell panel applications about its
workspaces and the windows therein. It also allows the user to interact
with xmonad by clicking on panels and window lists.
* "XMonad.Hooks.FadeInactive":
Makes XMonad set the _NET_WM_WINDOW_OPACITY atom for inactive windows,
which causes those windows to become slightly translucent if something
like xcompmgr is running
* "XMonad.Hooks.FloatNext":
Hook and keybindings for automatically sending the next
spawned window(s) to the floating layer.
* "XMonad.Hooks.InsertPosition":
Configure where new windows should be added and which window should be
focused.
* "XMonad.Hooks.ManageDocks":
This module provides tools to automatically manage 'dock' type programs,
such as gnome-panel, kicker, dzen, and xmobar.
* "XMonad.Hooks.ManageHelpers": provide helper functions to be used
in @manageHook@.
* "XMonad.Hooks.Minimize":
Handles window manager hints to minimize and restore windows. Use
this with XMonad.Layout.Minimize.
* "XMonad.Hooks.Place":
Automatic placement of floating windows.
* "XMonad.Hooks.RestoreMinimized":
(Deprecated: Use XMonad.Hooks.Minimize) Lets you restore minimized
windows (see "XMonad.Layout.Minimize") by selecting them on a
taskbar (listens for _NET_ACTIVE_WINDOW and WM_CHANGE_STATE).
* "XMonad.Hooks.Script":
Provides a simple interface for running a ~\/.xmonad\/hooks script with the
name of a hook.
* "XMonad.Hooks.ServerMode": Allows sending commands to a running xmonad process.
* "XMonad.Hooks.SetCursor":
Set a default mouse cursor on startup.
* "XMonad.Hooks.SetWMName":
Sets the WM name to a given string, so that it could be detected using
_NET_SUPPORTING_WM_CHECK protocol. May be useful for making Java GUI
programs work.
* "XMonad.Hooks.UrgencyHook":
UrgencyHook lets you configure an action to occur when a window demands
your attention. (In traditional WMs, this takes the form of \"flashing\"
on your \"taskbar.\" Blech.)
* "XMonad.Hooks.WorkspaceByPos":
Useful in a dual-head setup: Looks at the requested geometry of
new windows and moves them to the workspace of the non-focused
screen if necessary.
* "XMonad.Hooks.XPropManage":
A ManageHook matching on XProperties.
-}
{- $layouts
In the @XMonad.Layout@ namespace you can find modules exporting
contributed tiling algorithms, such as a tabbed layout, a circle, a spiral,
three columns, and so on.
You will also find modules which provide facilities for combining
different layouts, such as "XMonad.Layout.Combo", "XMonad.Layout.ComboP",
"XMonad.Layout.LayoutBuilder", "XMonad.Layout.SubLayouts", or
"XMonad.Layout.LayoutCombinators".
Layouts can be also modified with layout modifiers. A general
interface for writing layout modifiers is implemented in
"XMonad.Layout.LayoutModifier".
For more information on using those modules for customizing your
'XMonad.Core.layoutHook' see "XMonad.Doc.Extending#Editing_the_layout_hook".
* "XMonad.Layout.Accordion":
LayoutClass that puts non-focused windows in ribbons at the top and bottom
of the screen.
* "XMonad.Layout.AutoMaster":
Provides layout modifier AutoMaster. It separates screen in two parts -
master and slave. Size of slave area automatically changes depending on
number of slave windows.
* "XMonad.Layout.BorderResize":
This layout modifier will allow to resize windows by dragging their
borders with the mouse. However, it only works in layouts or modified
layouts that react to the SetGeometry message.
"XMonad.Layout.WindowArranger" can be used to create such a setup.
BorderResize is probably most useful in floating layouts.
* "XMonad.Layout.BoringWindows":
BoringWindows is an extension to allow windows to be marked boring
* "XMonad.Layout.CenteredMaster":
Two layout modifiers. centerMaster places master window at center,
on top of all other windows, which are managed by base layout.
topRightMaster is similar, but places master window in top right corner
instead of center.
* "XMonad.Layout.Circle":
Circle is an elliptical, overlapping layout.
* "XMonad.Layout.Column":
Provides Column layout that places all windows in one column. Windows
heights are calculated from equation: H1/H2 = H2/H3 = ... = q, where q is
given. With Shrink/Expand messages you can change the q value.
* "XMonad.Layout.Combo":
A layout that combines multiple layouts.
* "XMonad.Layout.ComboP":
A layout that combines multiple layouts and allows to specify where to put
new windows.
* "XMonad.Layout.Cross":
A Cross Layout with the main window in the center.
* "XMonad.Layout.Decoration":
A layout modifier and a class for easily creating decorated
layouts.
* "XMonad.Layout.DecorationMadness":
A collection of decorated layouts: some of them may be nice, some
usable, others just funny.
* "XMonad.Layout.Dishes":
Dishes is a layout that stacks extra windows underneath the master
windows.
* "XMonad.Layout.DragPane":
Layouts that splits the screen either horizontally or vertically and
shows two windows. The first window is always the master window, and
the other is either the currently focused window or the second window in
layout order. See also "XMonad.Layout.MouseResizableTall"
* "XMonad.Layout.DwmStyle":
A layout modifier for decorating windows in a dwm like style.
* "XMonad.Layout.FixedColumn":
A layout much like Tall, but using a multiple of a window's minimum
resize amount instead of a percentage of screen to decide where to
split. This is useful when you usually leave a text editor or
terminal in the master pane and like it to be 80 columns wide.
* "XMonad.Layout.Gaps":
Create manually-sized gaps along edges of the screen which will not
be used for tiling, along with support for toggling gaps on and
off. You probably want "XMonad.Hooks.ManageDocks".
* "XMonad.Layout.Grid":
A simple layout that attempts to put all windows in a square grid.
* "XMonad.Layout.GridVariants":
Two layouts: one is a variant of the Grid layout that allows the
desired aspect ratio of windows to be specified. The other is like
Tall but places a grid with fixed number of rows and columns in the
master area and uses an aspect-ratio-specified layout for the
slaves.
* "XMonad.Layout.HintedGrid":
A not so simple layout that attempts to put all windows in a square grid
while obeying their size hints.
* "XMonad.Layout.HintedTile":
A gapless tiled layout that attempts to obey window size hints,
rather than simply ignoring them.
* "XMonad.Layout.IM":
Layout modfier suitable for workspace with multi-windowed instant messenger
(like Psi or Tkabber).
* "XMonad.Layout.IndependentScreens":
Utility functions for simulating independent sets of workspaces on
each screen (like dwm's workspace model), using internal tags to
distinguish workspaces associated with each screen.
* "XMonad.Layout.LayoutBuilder":
A layout combinator that sends a specified number of windows to one rectangle
and the rest to another.
* "XMonad.Layout.LayoutCombinators":
The "XMonad.Layout.LayoutCombinators" module provides combinators
for easily combining multiple layouts into one composite layout, as
well as a way to jump directly to any particular layout (say, with
a keybinding) without having to cycle through other layouts to get
to it.
* "XMonad.Layout.LayoutHints":
Make layouts respect size hints.
* "XMonad.Layout.LayoutModifier":
A module for writing easy layout modifiers, which do not define a
layout in and of themselves, but modify the behavior of or add new
functionality to other layouts. If you ever find yourself writing
a layout which takes another layout as a parameter, chances are you
should be writing a LayoutModifier instead!
In case it is not clear, this module is not intended to help you
configure xmonad, it is to help you write other extension modules.
So get hacking!
* "XMonad.Layout.LayoutScreens":
Divide a single screen into multiple screens.
* "XMonad.Layout.LimitWindows":
A layout modifier that limits the number of windows that can be shown.
* "XMonad.Layout.MagicFocus":
Automagically put the focused window in the master area.
* "XMonad.Layout.Magnifier":
Screenshot : <http://caladan.rave.org/magnifier.png>
This is a layout modifier that will make a layout increase the size
of the window that has focus.
* "XMonad.Layout.Master":
Layout modfier that adds a master window to another layout.
* "XMonad.Layout.Maximize":
Temporarily yanks the focused window out of the layout to mostly fill
the screen.
* "XMonad.Layout.MessageControl":
Provides message escaping and filtering facilities which
help control complex nested layouts.
* "XMonad.Layout.Minimize":
Makes it possible to minimize windows, temporarily removing them
from the layout until they are restored.
* "XMonad.Layout.Monitor":
Layout modfier for displaying some window (monitor) above other windows
* "XMonad.Layout.Mosaic":
Based on MosaicAlt, but aspect ratio messages always change the aspect
ratios, and rearranging the window stack changes the window sizes.
* "XMonad.Layout.MosaicAlt":
A layout which gives each window a specified amount of screen space
relative to the others. Compared to the 'Mosaic' layout, this one
divides the space in a more balanced way.
* "XMonad.Layout.MouseResizableTile":
A layout in the spirit of "XMonad.Layout.ResizableTile", but with the option
to use the mouse to adjust the layout.
* "XMonad.Layout.MultiToggle":
Dynamically apply and unapply transformers to your window layout. This can
be used to rotate your window layout by 90 degrees, or to make the
currently focused window occupy the whole screen (\"zoom in\") then undo
the transformation (\"zoom out\").
* "XMonad.Layout.Named":
A module for assigning a name to a given layout.
* "XMonad.Layout.NoBorders":
Make a given layout display without borders. This is useful for
full-screen or tabbed layouts, where you don't really want to waste a
couple of pixels of real estate just to inform yourself that the visible
window has focus.
* "XMonad.Layout.NoFrillsDecoration":
Most basic version of decoration for windows without any additional
modifications. In contrast to "XMonad.Layout.SimpleDecoration" this will
result in title bars that span the entire window instead of being only the
length of the window title.
* "XMonad.Layout.OneBig":
Places one (master) window at top left corner of screen, and other (slave)
windows at the top.
* "XMonad.Layout.PerWorkspace":
Configure layouts on a per-workspace basis: use layouts and apply
layout modifiers selectively, depending on the workspace.
* "XMonad.Layout.Reflect":
Reflect a layout horizontally or vertically.
* "XMonad.Layout.ResizableTile":
More useful tiled layout that allows you to change a width\/height of window.
See also "XMonad.Layout.MouseResizableTile".
* "XMonad.Layout.ResizeScreen":
A layout transformer to have a layout respect a given screen
geometry. Mostly used with "Decoration" (the Horizontal and the
Vertical version will react to SetTheme and change their dimension
accordingly.
* "XMonad.Layout.Roledex":
This is a completely pointless layout which acts like Microsoft's Flip 3D
* "XMonad.Layout.ShowWName":
This is a layout modifier that will show the workspace name
* "XMonad.Layout.SimpleDecoration":
A layout modifier for adding simple decorations to the windows of a
given layout. The decorations are in the form of ion-like tabs
for window titles.
* "XMonad.Layout.SimpleFloat":
A basic floating layout.
* "XMonad.Layout.Simplest":
A very simple layout. The simplest, afaik. Used as a base for
decorated layouts.
* "XMonad.Layout.SimplestFloat":
A basic floating layout like SimpleFloat but without the decoration.
* "XMonad.Layout.Spacing":
Add a configurable amount of space around windows.
* "XMonad.Layout.Spiral":
A spiral tiling layout.
* "XMonad.Layout.Square":
A layout that splits the screen into a square area and the rest of the
screen.
This is probably only ever useful in combination with
"XMonad.Layout.Combo".
It sticks one window in a square region, and makes the rest
of the windows live with what's left (in a full-screen sense).
* "XMonad.Layout.StackTile":
A stacking layout, like dishes but with the ability to resize master pane.
Mostly useful on small screens.
* "XMonad.Layout.SubLayouts":
A layout combinator that allows layouts to be nested.
* "XMonad.Layout.TabBarDecoration":
A layout modifier to add a bar of tabs to your layouts.
* "XMonad.Layout.Tabbed":
A tabbed layout for the Xmonad Window Manager
* "XMonad.Layout.ThreeColumns":
A layout similar to tall but with three columns. With 2560x1600 pixels this
layout can be used for a huge main window and up to six reasonable sized
slave windows.
* "XMonad.Layout.ToggleLayouts":
A module to toggle between two layouts.
* "XMonad.Layout.TwoPane":
A layout that splits the screen horizontally and shows two windows. The
left window is always the master window, and the right is either the
currently focused window or the second window in layout order.
* "XMonad.Layout.WindowArranger":
This is a pure layout modifier that will let you move and resize
windows with the keyboard in any layout.
* "XMonad.Layout.WindowNavigation":
WindowNavigation is an extension to allow easy navigation of a workspace.
See also "XMonad.Actions.WindowNavigation".
* "XMonad.Layout.WorkspaceDir":
WorkspaceDir is an extension to set the current directory in a workspace.
Actually, it sets the current directory in a layout, since there's no way I
know of to attach a behavior to a workspace. This means that any terminals
(or other programs) pulled up in that workspace (with that layout) will
execute in that working directory. Sort of handy, I think.
Note this extension requires the 'directory' package to be installed.
-}
{- $prompts
In the @XMonad.Prompt@ name space you can find modules providing
graphical prompts for getting user input and using it to perform
various actions.
The "XMonad.Prompt" provides a library for easily writing new prompt
modules.
These are the available prompts:
* "XMonad.Prompt.AppLauncher":
A module for launch applicationes that receive parameters in the command
line. The launcher call a prompt to get the parameters.
* "XMonad.Prompt.AppendFile":
A prompt for appending a single line of text to a file. Useful for
keeping a file of notes, things to remember for later, and so on---
using a keybinding, you can write things down just about as quickly
as you think of them, so it doesn't have to interrupt whatever else
you're doing.
Who knows, it might be useful for other purposes as well!
* "XMonad.Prompt.DirExec":
A directory file executables prompt for XMonad. This might be useful if you
don't want to have scripts in your PATH environment variable (same
executable names, different behavior) - otherwise you might want to use
"XMonad.Prompt.Shell" instead - but you want to have easy access to these
executables through the xmonad's prompt.
* "XMonad.Prompt.Directory":
A directory prompt for XMonad
* "XMonad.Prompt.Email":
A prompt for sending quick, one-line emails, via the standard GNU
\'mail\' utility (which must be in your $PATH). This module is
intended mostly as an example of using "XMonad.Prompt.Input" to
build an action requiring user input.
* "XMonad.Prompt.Input":
A generic framework for prompting the user for input and passing it
along to some other action.
* "XMonad.Prompt.Layout":
A layout-selection prompt for XMonad
* "XMonad.Prompt.Man":
A manual page prompt for XMonad window manager.
TODO
* narrow completions by section number, if the one is specified
(like @\/etc\/bash_completion@ does)
* "XMonad.Prompt.RunOrRaise":
A prompt for XMonad which will run a program, open a file,
or raise an already running program, depending on context.
* "XMonad.Prompt.Shell":
A shell prompt for XMonad
* "XMonad.Prompt.Ssh":
A ssh prompt for XMonad
* "XMonad.Prompt.Theme":
A prompt for changing the theme of the current workspace
* "XMonad.Prompt.Window":
xprompt operations to bring windows to you, and bring you to windows.
* "XMonad.Prompt.Workspace":
A workspace prompt for XMonad
* "XMonad.Prompt.XMonad":
A prompt for running XMonad commands
Usually a prompt is called by some key binding. See
"XMonad.Doc.Extending#Editing_key_bindings", which includes examples
of adding some prompts.
-}
{- $utils
In the @XMonad.Util@ namespace you can find modules exporting various
utility functions that are used by the other modules of the
xmonad-contrib library.
There are also utilities for helping in configuring xmonad or using
external utilities.
A non complete list with a brief description:
* "XMonad.Util.Cursor": configure the default cursor/pointer glyph.
* "XMonad.Util.CustomKeys": configure key bindings (see
"XMonad.Doc.Extending#Editing_key_bindings").
* "XMonad.Util.Dmenu":
A convenient binding to dmenu.
Requires the process-1.0 package
* "XMonad.Util.Dzen":
Handy wrapper for dzen. Requires dzen >= 0.2.4.
* "XMonad.Util.EZConfig": configure key bindings easily, including a
parser for writing key bindings in "M-C-x" style.
* "XMonad.Util.Font": A module for abstracting a font facility over
Core fonts and Xft
* "XMonad.Util.Invisible":
A data type to store the layout state
* "XMonad.Util.Loggers":
A collection of simple logger functions and formatting utilities
which can be used in the 'XMonad.Hooks.DynamicLog.ppExtras' field of
a pretty-printing status logger format. See "XMonad.Hooks.DynamicLog"
for more information.
* "XMonad.Util.NamedActions":
A wrapper for keybinding configuration that can list the available
keybindings.
* "XMonad.Util.NamedScratchpad":
Like "XMonad.Util.Scratchpad" toggle windows to and from the current
workspace. Supports several arbitrary applications at the same time.
* "XMonad.Util.NamedWindows":
This module allows you to associate the X titles of windows with
them.
* "XMonad.Util.Paste":
A module for sending key presses to windows. This modules provides generalized
and specialized functions for this task.
* "XMonad.Util.Replace":
Implements a @--replace@ flag outside of core.
* "XMonad.Util.Run":
This modules provides several commands to run an external process.
It is composed of functions formerly defined in "XMonad.Util.Dmenu" (by
Spencer Janssen), "XMonad.Util.Dzen" (by glasser\@mit.edu) and
XMonad.Util.RunInXTerm (by Andrea Rossato).
* "XMonad.Util.Scratchpad":
Very handy hotkey-launched toggleable floating terminal window.
* "XMonad.Util.StringProp":
Internal utility functions for storing Strings with the root window.
Used for global state like IORefs with string keys, but more latency,
persistent between xmonad restarts.
* "XMonad.Util.Themes":
A (hopefully) growing collection of themes for decorated layouts.
* "XMonad.Util.Timer":
A module for setting up timers
* "XMonad.Util.Types":
Miscellaneous commonly used types.
* "XMonad.Util.WindowProperties":
EDSL for specifying window properties; various utilities related to window
properties.
* "XMonad.Util.XSelection":
A module for accessing and manipulating X Window's mouse selection (the buffer used in copy and pasting).
'getSelection' and 'putSelection' are adaptations of Hxsel.hs and Hxput.hs from the XMonad-utils
* "XMonad.Util.XUtils":
A module for painting on the screen
-}
--------------------------------------------------------------------------------
--
-- Extending Xmonad
--
--------------------------------------------------------------------------------
{- $extending
#Extending_xmonad#
Since the @xmonad.hs@ file is just another Haskell module, you may
import and use any Haskell code or libraries you wish, such as
extensions from the xmonad-contrib library, or other code you write
yourself.
-}
{- $keys
#Editing_key_bindings#
Editing key bindings means changing the 'XMonad.Core.XConfig.keys'
field of the 'XMonad.Core.XConfig' record used by xmonad. For
example, you could write:
> import XMonad
>
> main = xmonad $ def { keys = myKeys }
and provide an appropriate definition of @myKeys@, such as:
> myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
> [ ((modm, xK_F12), xmonadPrompt def)
> , ((modm, xK_F3 ), shellPrompt def)
> ]
This particular definition also requires importing "XMonad.Prompt",
"XMonad.Prompt.Shell", "XMonad.Prompt.XMonad", and "Data.Map":
> import qualified Data.Map as M
> import XMonad.Prompt
> import XMonad.Prompt.Shell
> import XMonad.Prompt.XMonad
For a list of the names of particular keys (such as xK_F12, and so
on), see
<http://hackage.haskell.org/packages/archive/X11/latest/doc/html/Graphics-X11-Types.html>
Usually, rather than completely redefining the key bindings, as we did
above, we want to simply add some new bindings and\/or remove existing
ones.
-}
{- $keyAdding
#Adding_key_bindings#
Adding key bindings can be done in different ways. See the end of this
section for the easiest ways. The type signature of
'XMonad.Core.XConfig.keys' is:
> keys :: XConfig Layout -> M.Map (ButtonMask,KeySym) (X ())
In order to add new key bindings, you need to first create an
appropriate 'Data.Map.Map' from a list of key bindings using
'Data.Map.fromList'. This 'Data.Map.Map' of new key bindings then
needs to be joined to a 'Data.Map.Map' of existing bindings using
'Data.Map.union'.
Since we are going to need some of the functions of the "Data.Map"
module, before starting we must first import this modules:
> import qualified Data.Map as M
For instance, if you have defined some additional key bindings like
these:
> myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
> [ ((modm, xK_F12), xmonadPrompt def)
> , ((modm, xK_F3 ), shellPrompt def)
> ]
then you can create a new key bindings map by joining the default one
with yours:
> newKeys x = myKeys x `M.union` keys def x
Finally, you can use @newKeys@ in the 'XMonad.Core.XConfig.keys' field
of the configuration:
> main = xmonad $ def { keys = newKeys }
Alternatively, the '<+>' operator can be used which in this usage does exactly
the same as the explicit usage of 'M.union' and propagation of the config
argument, thanks to appropriate instances in "Data.Monoid".
> main = xmonad $ def { keys = myKeys <+> keys def }
All together, your @~\/.xmonad\/xmonad.hs@ would now look like this:
> module Main (main) where
>
> import XMonad
>
> import qualified Data.Map as M
> import Graphics.X11.Xlib
> import XMonad.Prompt
> import XMonad.Prompt.Shell
> import XMonad.Prompt.XMonad
>
> main :: IO ()
> main = xmonad $ def { keys = myKeys <+> keys def }
>
> myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
> [ ((modm, xK_F12), xmonadPrompt def)
> , ((modm, xK_F3 ), shellPrompt def)
> ]
There are much simpler ways to accomplish this, however, if you are
willing to use an extension module to help you configure your keys.
For instance, "XMonad.Util.EZConfig" and "XMonad.Util.CustomKeys" both
provide useful functions for editing your key bindings; "XMonad.Util.EZConfig" even lets you use emacs-style keybinding descriptions like \"M-C-<F12>\".
-}
{- $keyDel
#Removing_key_bindings#
Removing key bindings requires modifying the 'Data.Map.Map' which
stores the key bindings. This can be done with 'Data.Map.difference'
or with 'Data.Map.delete'.
For example, suppose you want to get rid of @mod-q@ and @mod-shift-q@
(you just want to leave xmonad running forever). To do this you need
to define @newKeys@ as a 'Data.Map.difference' between the default
map and the map of the key bindings you want to remove. Like so:
> newKeys x = keys def x `M.difference` keysToRemove x
>
> keysToRemove :: XConfig Layout -> M.Map (KeyMask, KeySym) (X ())
> keysToRemove x = M.fromList
> [ ((modm , xK_q ), return ())
> , ((modm .|. shiftMask, xK_q ), return ())
> ]
As you can see, it doesn't matter what actions we associate with the
keys listed in @keysToRemove@, so we just use @return ()@ (the
\"null\" action).
It is also possible to simply define a list of keys we want to unbind
and then use 'Data.Map.delete' to remove them. In that case we would
write something like:
> newKeys x = foldr M.delete (keys def x) (keysToRemove x)
>
> keysToRemove :: XConfig Layout -> [(KeyMask, KeySym)]
> keysToRemove x =
> [ (modm , xK_q )
> , (modm .|. shiftMask, xK_q )
> ]
Another even simpler possibility is the use of some of the utilities
provided by the xmonad-contrib library. Look, for instance, at
'XMonad.Util.EZConfig.removeKeys'.
-}
{- $keyAddDel
#Adding_and_removing_key_bindings#
Adding and removing key bindings requires simply combining the steps
for removing and adding. Here is an example from
"XMonad.Config.Arossato":
> defKeys = keys def
> delKeys x = foldr M.delete (defKeys x) (toRemove x)
> newKeys x = foldr (uncurry M.insert) (delKeys x) (toAdd x)
> -- remove some of the default key bindings
> toRemove XConfig{modMask = modm} =
> [ (modm , xK_j )
> , (modm , xK_k )
> , (modm , xK_p )
> , (modm .|. shiftMask, xK_p )
> , (modm .|. shiftMask, xK_q )
> , (modm , xK_q )
> ] ++
> -- I want modm .|. shiftMask 1-9 to be free!
> [(shiftMask .|. modm, k) | k <- [xK_1 .. xK_9]]
> -- These are my personal key bindings
> toAdd XConfig{modMask = modm} =
> [ ((modm , xK_F12 ), xmonadPrompt def )
> , ((modm , xK_F3 ), shellPrompt def )
> ] ++
> -- Use modm .|. shiftMask .|. controlMask 1-9 instead
> [( (m .|. modm, k), windows $ f i)
> | (i, k) <- zip (workspaces x) [xK_1 .. xK_9]
> , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask .|. controlMask)]
> ]
You can achieve the same result using the "XMonad.Util.CustomKeys"
module; take a look at the 'XMonad.Util.CustomKeys.customKeys'
function in particular.
NOTE: modm is defined as the modMask you defined (or left as the default) in
your config.
-}
{- $mouse
#Editing_mouse_bindings#
Most of the previous discussion of key bindings applies to mouse
bindings as well. For example, you could configure button4 to close
the window you click on like so:
> import qualified Data.Map as M
>
> myMouse x = [ (0, button4), (\w -> focus w >> kill) ]
>
> newMouse x = M.union (mouseBindings def x) (M.fromList (myMouse x))
>
> main = xmonad $ def { ..., mouseBindings = newMouse, ... }
Overriding or deleting mouse bindings works similarly. You can also
configure mouse bindings much more easily using the
'XMonad.Util.EZConfig.additionalMouseBindings' and
'XMonad.Util.EZConfig.removeMouseBindings' functions from the
"XMonad.Util.EZConfig" module.
-}
{- $layoutHook
#Editing_the_layout_hook#
When you start an application that opens a new window, when you change
the focused window, or move it to another workspace, or change that
workspace's layout, xmonad will use the 'XMonad.Core.layoutHook' for
reordering the visible windows on the visible workspace(s).
Since different layouts may be attached to different workspaces, and
you can change them, xmonad needs to know which one to use. In this
sense the layoutHook may be thought as the list of layouts that
xmonad will use for laying out windows on the screen(s).
The problem is that the layout subsystem is implemented with an
advanced feature of the Haskell programming language: type classes.
This allows us to very easily write new layouts, combine or modify
existing layouts, create layouts with internal state, etc. See
"XMonad.Doc.Extending#The_LayoutClass" for more information. This
means that we cannot simply have a list of layouts as we used to have
before the 0.5 release: a list requires every member to belong to the
same type!
Instead the combination of layouts to be used by xmonad is created
with a specific layout combinator: 'XMonad.Layout.|||'.
Suppose we want a list with the 'XMonad.Layout.Full',
'XMonad.Layout.Tabbed.tabbed' and
'XMonad.Layout.Accordion.Accordion' layouts. First we import, in our
@~\/.xmonad\/xmonad.hs@, all the needed modules:
> import XMonad
>
> import XMonad.Layout.Tabbed
> import XMonad.Layout.Accordion
Then we create the combination of layouts we need:
> mylayoutHook = Full ||| tabbed shrinkText def ||| Accordion
Now, all we need to do is change the 'XMonad.Core.layoutHook'
field of the 'XMonad.Core.XConfig' record, like so:
> main = xmonad $ def { layoutHook = mylayoutHook }
Thanks to the new combinator, we can apply a layout modifier to a
whole combination of layouts, instead of applying it to each one. For
example, suppose we want to use the
'XMonad.Layout.NoBorders.noBorders' layout modifier, from the
"XMonad.Layout.NoBorders" module (which must be imported):
> mylayoutHook = noBorders (Full ||| tabbed shrinkText def ||| Accordion)
If we want only the tabbed layout without borders, then we may write:
> mylayoutHook = Full ||| noBorders (tabbed shrinkText def) ||| Accordion
Our @~\/.xmonad\/xmonad.hs@ will now look like this:
> import XMonad
>
> import XMonad.Layout.Tabbed
> import XMonad.Layout.Accordion
> import XMonad.Layout.NoBorders
>
> mylayoutHook = Full ||| noBorders (tabbed shrinkText def) ||| Accordion
>
> main = xmonad $ def { layoutHook = mylayoutHook }
That's it!
-}
{- $manageHook
#Editing_the_manage_hook#
The 'XMonad.Core.manageHook' is a very powerful tool for customizing
the behavior of xmonad with regard to new windows. Whenever a new
window is created, xmonad calls the 'XMonad.Core.manageHook', which
can thus be used to perform certain actions on the new window, such as
placing it in a specific workspace, ignoring it, or placing it in the
float layer.
The default 'XMonad.Core.manageHook' causes xmonad to float MPlayer
and Gimp, and to ignore gnome-panel, desktop_window, kicker, and
kdesktop.
The "XMonad.ManageHook" module provides some simple combinators that
can be used to alter the 'XMonad.Core.manageHook' by replacing or adding
to the default actions.
Let's start by analyzing the default 'XMonad.Config.manageHook', defined
in "XMonad.Config":
> manageHook :: ManageHook
> manageHook = composeAll
> [ className =? "MPlayer" --> doFloat
> , className =? "Gimp" --> doFloat
> , resource =? "desktop_window" --> doIgnore
> , resource =? "kdesktop" --> doIgnore ]
'XMonad.ManageHook.composeAll' can be used to compose a list of
different 'XMonad.Config.ManageHook's. In this example we have a list
of 'XMonad.Config.ManageHook's formed by the following commands: the
Mplayer's and the Gimp's windows, whose 'XMonad.ManageHook.className'
are, respectively \"Mplayer\" and \"Gimp\", are to be placed in the
float layer with the 'XMonad.ManageHook.doFloat' function; the windows
whose resource names are respectively \"desktop_window\" and
\kdesktop\" are to be ignored with the 'XMonad.ManageHook.doIgnore'
function.
This is another example of 'XMonad.Config.manageHook', taken from
"XMonad.Config.Arossato":
> myManageHook = composeAll [ resource =? "realplay.bin" --> doFloat
> , resource =? "win" --> doF (W.shift "doc") -- xpdf
> , resource =? "firefox-bin" --> doF (W.shift "web")
> ]
> newManageHook = myManageHook <+> manageHook def
Again we use 'XMonad.ManageHook.composeAll' to compose a list of
different 'XMonad.Config.ManageHook's. The first one will put
RealPlayer on the float layer, the second one will put the xpdf
windows in the workspace named \"doc\", with 'XMonad.ManageHook.doF'
and 'XMonad.StackSet.shift' functions, and the third one will put all
firefox windows on the workspace called "web". Then we use the
'XMonad.ManageHook.<+>' combinator to compose @myManageHook@ with the
default 'XMonad.Config.manageHook' to form @newManageHook@.
Each 'XMonad.Config.ManageHook' has the form:
> property =? match --> action
Where @property@ can be:
* 'XMonad.ManageHook.title': the window's title
* 'XMonad.ManageHook.resource': the resource name
* 'XMonad.ManageHook.className': the resource class name.
* 'XMonad.ManageHook.stringProperty' @somestring@: the contents of the
property @somestring@.
(You can retrieve the needed information using the X utility named
@xprop@; for example, to find the resource class name, you can type
> xprop | grep WM_CLASS
at a prompt, then click on the window whose resource class you want to
know.)
@match@ is the string that will match the property value (for instance
the one you retrieved with @xprop@).
An @action@ can be:
* 'XMonad.ManageHook.doFloat': to place the window in the float layer;
* 'XMonad.ManageHook.doIgnore': to ignore the window;
* 'XMonad.ManageHook.doF': to execute a function with the window as
argument.
For example, suppose we want to add a 'XMonad.Config.manageHook' to
float RealPlayer, which usually has a 'XMonad.ManageHook.resource'
name of \"realplay.bin\".
First we need to import "XMonad.ManageHook":
> import XMonad.ManageHook
Then we create our own 'XMonad.Config.manageHook':
> myManageHook = resource =? "realplay.bin" --> doFloat
We can now use the 'XMonad.ManageHook.<+>' combinator to add our
'XMonad.Config.manageHook' to the default one:
> newManageHook = myManageHook <+> manageHook def
(Of course, if we wanted to completely replace the default
'XMonad.Config.manageHook', this step would not be necessary.) Now,
all we need to do is change the 'XMonad.Core.manageHook' field of the
'XMonad.Core.XConfig' record, like so:
> main = xmonad def { ..., manageHook = newManageHook, ... }
And we are done.
Obviously, we may wish to add more then one
'XMonad.Config.manageHook'. In this case we can use a list of hooks,
compose them all with 'XMonad.ManageHook.composeAll', and add the
composed to the default one.
For instance, if we want RealPlayer to float and thunderbird always
opened in the workspace named "mail", we can do so like this:
> myManageHook = composeAll [ resource =? "realplay.bin" --> doFloat
> , resource =? "thunderbird-bin" --> doF (W.shift "mail")
> ]
Remember to import the module that defines the 'XMonad.StackSet.shift'
function, "XMonad.StackSet", like this:
> import qualified XMonad.StackSet as W
And then we can add @myManageHook@ to the default one to create
@newManageHook@ as we did in the previous example.
One more thing to note about this system is that if
a window matches multiple rules in a 'XMonad.Config.manageHook', /all/
of the corresponding actions will be run (in the order in which they
are defined). This is a change from versions before 0.5, when only
the first rule that matched was run.
Finally, for additional rules and actions you can use in your
manageHook, check out the contrib module "XMonad.Hooks.ManageHelpers".
-}
{- $logHook
#The_log_hook_and_external_status_bars#
When the stack of the windows managed by xmonad changes for any
reason, xmonad will call 'XMonad.Core.logHook', which can be used to
output some information about the internal state of xmonad, such as the
layout that is presently in use, the workspace we are in, the focused
window's title, and so on.
Extracting information about the internal xmonad state can be somewhat
difficult if you are not familiar with the source code. Therefore,
it's usually easiest to use a module that has been designed
specifically for logging some of the most interesting information
about the internal state of xmonad: "XMonad.Hooks.DynamicLog". This
module can be used with an external status bar to print the produced
logs in a convenient way; the most commonly used status bars are dzen
and xmobar.
By default the 'XMonad.Core.logHook' doesn't produce anything. To
enable it you need first to import "XMonad.Hooks.DynamicLog":
> import XMonad.Hooks.DynamicLog
Then you just need to update the 'XMonad.Core.logHook' field of the
'XMonad.Core.XConfig' record with one of the provided functions. For
example:
> main = xmonad def { logHook = dynamicLog }
More interesting configurations are also possible; see the
"XMonad.Hooks.DynamicLog" module for more possibilities.
You may now enjoy your extended xmonad experience.
Have fun!
-}
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Doc/Extending.hs | bsd-2-clause | 50,033 | 0 | 3 | 9,658 | 99 | 96 | 3 | 2 | 0 |
module Layout.D5Simple where
sumSquares (x:xs) = sq x + sumSquares xs
where sq x = x ^pow
pow = 2
sumSquares [] = 0
| RefactoringTools/HaRe | test/testdata/Layout/D5Simple.hs | bsd-3-clause | 133 | 0 | 7 | 41 | 60 | 31 | 29 | 5 | 1 |
{-# LANGUAGE NoImplicitPrelude, BangPatterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.CString
-- Copyright : (c) The University of Glasgow 2011
-- License : see libraries/ghc-prim/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- GHC C strings definitions (previously in GHC.Base).
-- Use GHC.Exts from the base package instead of importing this
-- module directly.
--
-----------------------------------------------------------------------------
module GHC.CString (
unpackCString#, unpackAppendCString#, unpackFoldrCString#,
unpackCStringUtf8#, unpackNBytes#
) where
import GHC.Types
import GHC.Prim
-----------------------------------------------------------------------------
-- Unpacking C strings}
-----------------------------------------------------------------------------
-- This code is needed for virtually all programs, since it's used for
-- unpacking the strings of error messages.
-- Used to be in GHC.Base, but was moved to ghc-prim because the new generics
-- stuff uses Strings in the representation, so to give representations for
-- ghc-prim types we need unpackCString#
unpackCString# :: Addr# -> [Char]
{-# NOINLINE unpackCString# #-}
-- There's really no point in inlining this, ever, as the loop doesn't
-- specialise in an interesting But it's pretty small, so there's a danger
-- that it'll be inlined at every literal, which is a waste
unpackCString# addr
= unpack 0#
where
unpack nh
| isTrue# (ch `eqChar#` '\0'#) = []
| True = C# ch : unpack (nh +# 1#)
where
!ch = indexCharOffAddr# addr nh
unpackAppendCString# :: Addr# -> [Char] -> [Char]
{-# NOINLINE unpackAppendCString# #-}
-- See the NOINLINE note on unpackCString#
unpackAppendCString# addr rest
= unpack 0#
where
unpack nh
| isTrue# (ch `eqChar#` '\0'#) = rest
| True = C# ch : unpack (nh +# 1#)
where
!ch = indexCharOffAddr# addr nh
unpackFoldrCString# :: Addr# -> (Char -> a -> a) -> a -> a
-- Usually the unpack-list rule turns unpackFoldrCString# into unpackCString#
-- It also has a BuiltInRule in PrelRules.lhs:
-- unpackFoldrCString# "foo" c (unpackFoldrCString# "baz" c n)
-- = unpackFoldrCString# "foobaz" c n
{-# NOINLINE unpackFoldrCString# #-}
-- At one stage I had NOINLINE [0] on the grounds that, unlike
-- unpackCString#, there *is* some point in inlining
-- unpackFoldrCString#, because we get better code for the
-- higher-order function call. BUT there may be a lot of
-- literal strings, and making a separate 'unpack' loop for
-- each is highly gratuitous. See nofib/real/anna/PrettyPrint.
unpackFoldrCString# addr f z
= unpack 0#
where
unpack nh
| isTrue# (ch `eqChar#` '\0'#) = z
| True = C# ch `f` unpack (nh +# 1#)
where
!ch = indexCharOffAddr# addr nh
unpackCStringUtf8# :: Addr# -> [Char]
unpackCStringUtf8# addr
= unpack 0#
where
unpack nh
| isTrue# (ch `eqChar#` '\0'#) = []
| isTrue# (ch `leChar#` '\x7F'#) = C# ch : unpack (nh +# 1#)
| isTrue# (ch `leChar#` '\xDF'#) =
C# (chr# (((ord# ch -# 0xC0#) `uncheckedIShiftL#` 6#) +#
(ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#))) :
unpack (nh +# 2#)
| isTrue# (ch `leChar#` '\xEF'#) =
C# (chr# (((ord# ch -# 0xE0#) `uncheckedIShiftL#` 12#) +#
((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#` 6#) +#
(ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#))) :
unpack (nh +# 3#)
| True =
C# (chr# (((ord# ch -# 0xF0#) `uncheckedIShiftL#` 18#) +#
((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#` 12#) +#
((ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#) `uncheckedIShiftL#` 6#) +#
(ord# (indexCharOffAddr# addr (nh +# 3#)) -# 0x80#))) :
unpack (nh +# 4#)
where
!ch = indexCharOffAddr# addr nh
unpackNBytes# :: Addr# -> Int# -> [Char]
unpackNBytes# _addr 0# = []
unpackNBytes# addr len# = unpack [] (len# -# 1#)
where
unpack acc i#
| isTrue# (i# <# 0#) = acc
| True =
case indexCharOffAddr# addr i# of
ch -> unpack (C# ch : acc) (i# -# 1#)
| joelburget/haste-compiler | libraries/ghc-prim/GHC/CString.hs | bsd-3-clause | 4,625 | 0 | 24 | 1,246 | 998 | 532 | 466 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hr-HR">
<title>Active Scan Rules | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | ccgreen13/zap-extensions | src/org/zaproxy/zap/extension/ascanrules/resources/help_hr_HR/helpset_hr_HR.hs | apache-2.0 | 979 | 80 | 66 | 161 | 417 | 211 | 206 | -1 | -1 |
module ShouldSucceed where
class Eq' a where
doubleeq :: a -> a -> Bool
class (Eq' a) => Ord' a where
lt :: a -> a -> Bool
instance Eq' Int where
doubleeq x y = True
instance Ord' Int where
lt x y = True
f x y | lt x 1 = True
| otherwise = False
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/tc054.hs | bsd-3-clause | 261 | 0 | 8 | 74 | 123 | 61 | 62 | 11 | 1 |
module Main where
import System.Environment (getArgs, getProgName)
-- Available/possible sub-commands
data Command = Help | Check deriving Show
-- Parameters for each sub-command to parse and use as options
data CommandParams
= HelpParams { helpKeyword :: Maybe String }
| CheckParams { inputData :: String }
deriving Show
-- This is the verbosity level in general for the application,
-- including sub-commands like help, add, remove and check
data VerboseLevel = Quiet | Verbose | Debug deriving Show
-- These are general options that apply to the top-level of the
-- application and to sub-commands as well
data Opts = Opts { verbose :: VerboseLevel
, command :: Command
, params :: CommandParams
} deriving Show
parseCommandLine :: Opts -> [String] -> Either String Opts
parseCommandLine opts args =
main :: IO ()
main = do args <- getArgs
prog <- getProgName
putStrLn $ "hello" ++ unwords (map show args) ++ "foo" ++ prog
| fredmorcos/attic | projects/pet/archive/pet_haskell_1/Main.hs | isc | 1,024 | 0 | 12 | 251 | 202 | 116 | 86 | -1 | -1 |
{-# Language TypeOperators, ScopedTypeVariables, FlexibleContexts, FlexibleInstances #-}
module AutoBuilder (autoloadFromBuilder) where
import qualified GI.Gtk as Gtk
import qualified Data.Text as Text
import GHC.Generics
import Data.Coerce
import Control.Exception
data AutoloaderFailure
= AutoloaderNoSuchObject String
| AutoloaderBadCast String
deriving Show
instance Exception AutoloaderFailure
autoloadFromBuilder ::
(GLoadBuilder (Rep a), Generic a) => Gtk.Builder -> IO a
autoloadFromBuilder b = to <$> gloadFromBuilder b
class GLoadBuilder f where
gloadFromBuilder :: Gtk.Builder -> IO (f p)
instance GLoadBuilder f => GLoadBuilder (D1 c f) where
gloadFromBuilder b = M1 <$> gloadFromBuilder b
instance GLoadBuilder f => GLoadBuilder (C1 c f) where
gloadFromBuilder b = M1 <$> gloadFromBuilder b
instance GLoadBuilder U1 where
gloadFromBuilder _ = return U1
instance (GLoadBuilder f, GLoadBuilder g) => GLoadBuilder (f :*: g) where
gloadFromBuilder b = (:*:) <$> gloadFromBuilder b <*> gloadFromBuilder b
instance (Gtk.ManagedPtrNewtype o, Gtk.GObject o, Selector s) =>
GLoadBuilder (S1 s (K1 i o)) where
gloadFromBuilder builder =
do let name = selName (M1 Nothing :: S1 s Maybe ())
orFail m err = maybe (throwIO err) return =<< m
o <- Gtk.builderGetObject builder (Text.pack name)
`orFail` AutoloaderNoSuchObject name
p <- Gtk.castTo coerce o
`orFail` AutoloaderBadCast name
return (M1 (K1 p))
| glguy/CookieCalculator | gui/AutoBuilder.hs | isc | 1,547 | 0 | 14 | 336 | 477 | 242 | 235 | 35 | 1 |
module UI where
import Board
import Data.List.Split
import Data.List
import Text.Regex.Posix
import System.IO
import System.Console.ANSI
buildBoardString :: [[(Int , Symbol)]] -> String
buildBoardString board = concat (map rowToString board)
rowToString :: [(Int , Symbol)] -> String
rowToString row = "|_" ++ (concat (intersperse "_|_" (map symbolToString row))) ++ "_|\n"
isValidMoveInput :: String -> Bool
isValidMoveInput userInput = userInput =~ "^[1-9]$"
get :: IO String
get = getLine
clearScreenHome :: String
clearScreenHome = "\ESC[2J\ESC[H"
inputMovePromptMessage :: IO ()
inputMovePromptMessage = putStr "Please choose a space(1-9): "
gameOver :: [[Symbol]] -> IO ()
gameOver board = do
printBoard board
putStrLn (getGameOutcomeString board)
getGameOutcomeString :: [[Symbol]] -> String
getGameOutcomeString board = do
if getWinner board == Board.empty
then "Tie."
else (show (getWinner board)) ++ " Wins!"
thinkingMessage :: String
thinkingMessage = "Computer is thinking!"
inputPrompt :: IO String
inputPrompt = do
inputMovePromptMessage
hFlush stdout
getLine
getUserMoveInput :: [[Symbol]] -> IO String -> IO String
getUserMoveInput board movePrompt = do
input <- movePrompt
if isValidMove board input
then return input
else getUserMoveInput board inputPrompt
printBoard :: [[Symbol]] -> IO ()
printBoard board = do
putStr clearScreenHome
putStr (buildBoardString (addIndices board))
isValidSpace :: [[Symbol]] -> String -> Bool
isValidSpace board space = ((concat board) !! ((read space)-1)) == Board.empty
isValidMove :: [[Symbol]] -> String -> Bool
isValidMove board space = (isValidMoveInput space) && (isValidSpace board space)
addIndices :: [[Symbol]] -> [[(Int , Symbol)]]
addIndices board = chunksOf (length board) (zip [1..] (concat board))
setSymbolToRed :: (Int, Symbol) -> String
setSymbolToRed indexedSymbol = "\x1b[31m" ++ (show (snd indexedSymbol)) ++ "\x1b[0m"
setSymbolToGreen :: (Int, Symbol) -> String
setSymbolToGreen indexedSymbol = "\x1b[32m" ++ (show (snd indexedSymbol)) ++ "\x1b[0m"
symbolToString :: (Int, Symbol) -> String
symbolToString indexedSymbol = do
if (snd indexedSymbol) == Board.empty
then show (fst indexedSymbol)
else do
if (snd indexedSymbol) == x
then setSymbolToRed indexedSymbol
else setSymbolToGreen indexedSymbol
| basilpocklington/haskell-TTT | src/UI.hs | mit | 2,361 | 0 | 13 | 390 | 790 | 416 | 374 | 63 | 3 |
{-# LANGUAGE Arrows #-}
module Game.Client.Objects.Towers where
import FRP.Yampa as Yampa
import FRP.Yampa.Geometry
import Graphics.UI.SDL as SDL
import Graphics.UI.SDL.Events as SDL.Events
import Graphics.UI.SDL.Keysym as SDL.Keysym
import Game.Shared.Types
import Game.Shared.Networking
import Game.Shared.Object
import Game.Shared.Arrows
import Game.Client.Object
import Game.Client.Components.BasicComponents
import Game.Client.Components.Projectiles
import Game.Client.Resources
import Game.Client.Input
import Game.Client.Graphics
import Game.Client.Networking
-- |Game object for a currently active turret
turretObject :: GameObject -- ^Creation time representation of the turret
-> Object
turretObject obj = proc objInput -> do
-- Components
basicComponent <- basicObject obj -< BasicObjectInput {
boiNetwork = oiNetwork objInput
}
statsComponent <- objectStats obj -< ObjectStatsInput {
osiNetwork = oiNetwork objInput
}
let stats = osoStats statsComponent
position = booPosition basicComponent
-- Components
healthbarComponent <- healthbarDisplay 5 (vector2 10 (-12)) 75 6 -< HealthbarDisplayInput {
hdiHealthChangedEvent = osoHealthChanged statsComponent,
hdiObjectPosition = position,
hdiCurrentHealth = stHealth stats,
hdiCurrentMaxHealth = stMaxHealth stats
}
-- Return state
let (x, y) = vectorRoundedComponents position
team = goTeam obj
returnA -< (defaultObjOutput objInput) {
ooKillRequest = lMerge (booObjectDestroyed basicComponent) (osoDeathEvent statsComponent),
ooSpawnRequests = catEvents [osoDeathEvent statsComponent `tag` (turretDeadObject obj)],
ooGraphic = drawAll [draw (turretImage team) (Mask Nothing x y),
hdoHealthbarGraphic healthbarComponent],
ooGraphicLayer = GameLayer 5,
ooGameObject = obj {
goPos = position,
goStats = Just stats
}
}
-- |Game object of a turret that has been destroyed
turretDeadObject :: GameObject -- ^Creation-time representation of the turret
-> Object
turretDeadObject obj = proc objInput -> do
-- Components
basicComponent <- basicObject obj -< BasicObjectInput {
boiNetwork = oiNetwork objInput
}
statsComponent <- objectStats obj -< ObjectStatsInput {
osiNetwork = oiNetwork objInput
}
let stats = osoStats statsComponent
position = booPosition basicComponent
-- Return state
let (x, y) = vectorRoundedComponents position
team = goTeam obj
returnA -< (defaultObjOutput objInput) {
ooKillRequest = booObjectDestroyed basicComponent,
ooGraphic = draw turretDeadImage (Mask Nothing x y),
ooGraphicLayer = GameLayer 5,
ooGameObject = obj {
goPos = position,
goStats = Just stats,
goIsDead = True
}
}
-- |Game object of a projectile fired by a tower
towerProjectile :: GameObject -- ^Creation-time representation of the projectile
-> Object
towerProjectile obj = proc objInput -> do
-- Components
basicComponent <- basicObject obj -< BasicObjectInput {
boiNetwork = oiNetwork objInput
}
statsComponent <- objectStats obj -< ObjectStatsInput {
osiNetwork = oiNetwork objInput
}
let stats = osoStats statsComponent
rec projectileComponent <- trackingProjectile obj 1 -< TrackingProjectileInput {
tpiAllCollisions = oiCollidingWith objInput,
tpiAllObjects = oiAllObjects objInput,
tpiSpeed = fromIntegral (stSpeed stats),
tpiCurrPos = position
}
position <- (^+^ (goPos obj)) ^<< integral -< tpoMoveDelta projectileComponent
-- Return state
let (x, y) = vectorRoundedComponents position
returnA -< (defaultObjOutput objInput) {
ooKillRequest = lMerge (booObjectDestroyed basicComponent) (tpoHitTargetEvent projectileComponent),
ooGraphic = draw turretProjectileImage (Mask Nothing x y),
ooGraphicLayer = GameLayer 6,
ooGameObject = obj {
goPos = position
}
}
| Mattiemus/LaneWars | Game/Client/Objects/Towers.hs | mit | 4,382 | 3 | 16 | 1,216 | 937 | 507 | 430 | 83 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.URL (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.URL
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.URL
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/URL.hs | mit | 322 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
{-# LANGUAGE RankNTypes #-}
module CodeGen where
import CodeGen.AST
import CodeGen.Monad
import CodeGen.BlockGen
import Control.Monad.State
import Control.Lens
import LLVM.General.AST (Module, Named ((:=)))
import qualified LLVM.General.AST as LLVM
import qualified LLVM.General.AST.Global as LLVM
import qualified LLVM.General.AST.CallingConvention as CC
import qualified LLVM.General.AST.Constant as Const
import qualified LLVM.General.PassManager as Opt
import Data.Word
import qualified LLVM.General.Module as Mod
import LLVM.General.Context
import LLVM.General.Target
import Control.Monad.Except
testStuff = compile (runCodeGen test)
test :: CodeGen ()
test = do
program.moduleName .= "Test"
instr <- newName
mainBlock <- runBlockGen buildMainBlock' (LLVM.Name "mainBlock") (instr := LLVM.Ret (Just (LLVM.ConstantOperand (Const.Int 32 0))) [])
n <- newName
newFunction "main" [] (LLVM.IntegerType 32) [mainBlock]
extern "putchar" [LLVM.Parameter (LLVM.IntegerType 8) n []] (LLVM.IntegerType 32)
call fun args = LLVM.Call False CC.C [] fun args [] []
buildMainBlock' = do
x <- newVar (LLVM.IntegerType 8)
y <- newVar (LLVM.IntegerType 8)
assignIntConstant x 20
assignIntConstant y 14
z <- add x y
append $ call
(Right $ LLVM.ConstantOperand (Const.GlobalReference (LLVM.FunctionType (LLVM.IntegerType 32)
[LLVM.IntegerType 8] False) (LLVM.Name "putchar")))
[((LLVM.LocalReference (LLVM.IntegerType 8) z), [])]
buildMainBlock = do
instr1 <- newName
instr2 <- newName
return $ buildBlock "mainBlock"
[instr1 := call
(Right $ LLVM.ConstantOperand (Const.GlobalReference (LLVM.FunctionType (LLVM.IntegerType 32)
[LLVM.IntegerType 8] False) (LLVM.Name "putchar")))
[(LLVM.ConstantOperand (Const.Int 8 33), [])]]
(instr2 := LLVM.Ret (Just (LLVM.ConstantOperand (Const.Int 32 0))) [])
extern s args ret = newFunction s args ret []
newFunction :: String -> [LLVM.Parameter] -> LLVM.Type -> [LLVM.BasicBlock] -> CodeGen ()
newFunction s args ret b = program.moduleDefinitions %= ((:) $ LLVM.GlobalDefinition $ LLVM.functionDefaults
{ LLVM.name = LLVM.Name s
, LLVM.parameters = (args, False)
, LLVM.returnType = ret
, LLVM.basicBlocks = b
})
buildBlock :: String -> [LLVM.Named LLVM.Instruction] -> LLVM.Named LLVM.Terminator -> LLVM.BasicBlock
buildBlock s i t = LLVM.BasicBlock (LLVM.Name s) i t
printAssem mod = withContext $ \c -> runExceptT $ Mod.withModuleFromAST c mod (\m -> optimise m >> Mod.moduleLLVMAssembly m >>= putStrLn)
compile testModule = withContext $ \c -> runExceptT $ Mod.withModuleFromAST c testModule
(\m -> optimise m >> (runExceptT $ withDefaultTargetMachine $ \t -> runExceptT $ Mod.writeObjectToFile t (Mod.File "foo") m))
optimise :: Mod.Module -> IO Bool
optimise m = Opt.withPassManager
(Opt.CuratedPassSetSpec (Just 3) Nothing Nothing (Just True) Nothing Nothing Nothing Nothing Nothing Nothing) (\p -> Opt.runPassManager p m)
| LudvikGalois/CodeGen | src/CodeGen.hs | mit | 2,970 | 0 | 21 | 479 | 1,108 | 581 | 527 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module PostgREST.AppState
( AppState
, getConfig
, getDbStructure
, getIsWorkerOn
, getJsonDbS
, getMainThreadId
, getPgVersion
, getPool
, getTime
, init
, initWithPool
, logWithZTime
, putConfig
, putDbStructure
, putIsWorkerOn
, putJsonDbS
, putPgVersion
, releasePool
, signalListener
, waitListener
) where
import qualified Hasql.Pool as P
import Control.AutoUpdate (defaultUpdateSettings, mkAutoUpdate,
updateAction)
import Data.IORef (IORef, atomicWriteIORef, newIORef,
readIORef)
import Data.Time (ZonedTime, defaultTimeLocale, formatTime,
getZonedTime)
import Data.Time.Clock (UTCTime, getCurrentTime)
import PostgREST.Config (AppConfig (..))
import PostgREST.Config.PgVersion (PgVersion (..), minimumPgVersion)
import PostgREST.DbStructure (DbStructure)
import Protolude hiding (toS)
import Protolude.Conv (toS)
data AppState = AppState
{ statePool :: P.Pool -- | Connection pool, either a 'Connection' or a 'ConnectionError'
, statePgVersion :: IORef PgVersion
-- | No schema cache at the start. Will be filled in by the connectionWorker
, stateDbStructure :: IORef (Maybe DbStructure)
-- | Cached DbStructure in json
, stateJsonDbS :: IORef ByteString
-- | Helper ref to make sure just one connectionWorker can run at a time
, stateIsWorkerOn :: IORef Bool
-- | Binary semaphore used to sync the listener(NOTIFY reload) with the connectionWorker.
, stateListener :: MVar ()
-- | Config that can change at runtime
, stateConf :: IORef AppConfig
-- | Time used for verifying JWT expiration
, stateGetTime :: IO UTCTime
-- | Time with time zone used for worker logs
, stateGetZTime :: IO ZonedTime
-- | Used for killing the main thread in case a subthread fails
, stateMainThreadId :: ThreadId
}
init :: AppConfig -> IO AppState
init conf = do
newPool <- initPool conf
initWithPool newPool conf
initWithPool :: P.Pool -> AppConfig -> IO AppState
initWithPool newPool conf =
AppState newPool
<$> newIORef minimumPgVersion -- assume we're in a supported version when starting, this will be corrected on a later step
<*> newIORef Nothing
<*> newIORef mempty
<*> newIORef False
<*> newEmptyMVar
<*> newIORef conf
<*> mkAutoUpdate defaultUpdateSettings { updateAction = getCurrentTime }
<*> mkAutoUpdate defaultUpdateSettings { updateAction = getZonedTime }
<*> myThreadId
initPool :: AppConfig -> IO P.Pool
initPool AppConfig{..} =
P.acquire (configDbPoolSize, configDbPoolTimeout, toS configDbUri)
getPool :: AppState -> P.Pool
getPool = statePool
releasePool :: AppState -> IO ()
releasePool AppState{..} = P.release statePool >> throwTo stateMainThreadId UserInterrupt
getPgVersion :: AppState -> IO PgVersion
getPgVersion = readIORef . statePgVersion
putPgVersion :: AppState -> PgVersion -> IO ()
putPgVersion = atomicWriteIORef . statePgVersion
getDbStructure :: AppState -> IO (Maybe DbStructure)
getDbStructure = readIORef . stateDbStructure
putDbStructure :: AppState -> DbStructure -> IO ()
putDbStructure appState structure =
atomicWriteIORef (stateDbStructure appState) $ Just structure
getJsonDbS :: AppState -> IO ByteString
getJsonDbS = readIORef . stateJsonDbS
putJsonDbS :: AppState -> ByteString -> IO ()
putJsonDbS appState = atomicWriteIORef (stateJsonDbS appState)
getIsWorkerOn :: AppState -> IO Bool
getIsWorkerOn = readIORef . stateIsWorkerOn
putIsWorkerOn :: AppState -> Bool -> IO ()
putIsWorkerOn = atomicWriteIORef . stateIsWorkerOn
getConfig :: AppState -> IO AppConfig
getConfig = readIORef . stateConf
putConfig :: AppState -> AppConfig -> IO ()
putConfig = atomicWriteIORef . stateConf
getTime :: AppState -> IO UTCTime
getTime = stateGetTime
-- | Log to stderr with local time
logWithZTime :: AppState -> Text -> IO ()
logWithZTime appState txt = do
zTime <- stateGetZTime appState
hPutStrLn stderr $ toS (formatTime defaultTimeLocale "%d/%b/%Y:%T %z: " zTime) <> txt
getMainThreadId :: AppState -> ThreadId
getMainThreadId = stateMainThreadId
-- | As this IO action uses `takeMVar` internally, it will only return once
-- `stateListener` has been set using `signalListener`. This is currently used
-- to syncronize workers.
waitListener :: AppState -> IO ()
waitListener = takeMVar . stateListener
-- tryPutMVar doesn't lock the thread. It should always succeed since
-- the connectionWorker is the only mvar producer.
signalListener :: AppState -> IO ()
signalListener appState = void $ tryPutMVar (stateListener appState) ()
| steve-chavez/postgrest | src/PostgREST/AppState.hs | mit | 4,717 | 0 | 14 | 938 | 999 | 543 | 456 | 102 | 1 |
myShow :: (Show a) => a -> String
myShow = show
| tamasgal/haskell_exercises | Real_World_Haskell/ch06/Monomorphism.hs | mit | 50 | 0 | 6 | 13 | 24 | 13 | 11 | 2 | 1 |
module Handler.NewUpload
( getNewUploadR
, postNewUploadR )
where
import Import
import Control.Exception.Base (bracket)
import Control.Monad.Trans.Resource (runResourceT)
import Data.Conduit
import Data.Conduit.Combinators (sinkHandle)
import qualified Data.Text as Text
import Data.Time.Clock (getCurrentTime)
import qualified Graphics.GD as GD
import System.Directory (canonicalizePath, createDirectoryIfMissing, removeFile)
import System.IO (hClose)
import System.IO.Temp (openTempFile)
fileUploadForm :: Maybe (FileInfo, Text) -> Form (FileInfo, Text)
fileUploadForm x = renderDivs $ (,)
<$> areq fileField (bfs MsgUploadFileField) (fst <$> x)
<*> areq textField (bfs MsgUploadFileDescription) (snd <$> x)
<* bootstrapSubmit (BootstrapSubmit MsgUploadFileSubmit "" [])
getNewUploadR :: Handler Html
getNewUploadR = do
(newUploadWidget, enctype) <- generateFormPost (fileUploadForm Nothing)
defaultLayout $ do
setTitleI MsgNewUploadTitle
$(widgetFile "newupload")
postNewUploadR :: Handler Html
postNewUploadR = do
((res, newUploadWidget), enctype) <- runFormPost (fileUploadForm Nothing)
case res of
FormSuccess (fi, description) -> do
let contentType = fileContentType fi
uploadDir = "uploads"
liftIO $ createDirectoryIfMissing True uploadDir
filePath <-
liftIO $ bracket (openTempFile uploadDir "upload") (\(_, h) -> hClose h) $ \(fp, h) -> do
let source = fileSource fi
runResourceT $ source $$ sinkHandle h
return fp
extra <- getExtra
uploadError <-
liftIO $
case forceImageRatio extra of
Nothing -> return Nothing
Just forceRatio ->
case Text.unpack contentType of
'i':'m':'a':'g':'e':'/':fmt ->
let mLoad =
case fmt of
"jpeg" -> Just GD.loadJpegFile
"png" -> Just GD.loadPngFile
"gif" -> Just GD.loadGifFile
_ -> Nothing
in case mLoad of
Nothing -> return $ Just (MsgUnsupportedImageType contentType)
Just load ->
GD.withImage (load filePath) $ \image -> do
(w, h) <- GD.imageSize image
case (round ((fromIntegral h) * forceRatio)) - w of
0 -> return Nothing
_ ->
return $
Just (MsgWrongAspectRatio forceRatio (fromIntegral w / fromIntegral h))
_ -> return Nothing
case uploadError of
Nothing -> addFileToDatabase filePath description contentType
Just err -> do
liftIO $ removeFile filePath
setMessageI err
defaultLayout $ do
setTitleI MsgNewUploadTitle
$(widgetFile "newupload")
_ -> do
setMessageI MsgFileUploadFailed
defaultLayout $ do
setTitleI MsgNewUploadTitle
$(widgetFile "newupload")
where
addFileToDatabase :: String -> Text -> Text -> Handler Html
addFileToDatabase filePath description contentType = do
now <- lift getCurrentTime
completePath <- liftIO $ canonicalizePath filePath
_ <- runDB $ insert (Upload description (Text.pack completePath) now contentType)
setMessageI MsgUploadSaved
redirect UploadsR
| bholst/blog | Handler/NewUpload.hs | mit | 3,459 | 0 | 38 | 1,077 | 962 | 475 | 487 | 83 | 10 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
module Betfair.APING.Requests.ListMarketCatalogue
( listMarketCatalogue
, marketCatalogue
, jsonRequest
, JsonRequest(..)
, JsonParameters(..)
, defaultJsonParameters
) where
import qualified Data.Aeson as A (encode)
import Data.Aeson.TH (Options (omitNothingFields),
defaultOptions,
deriveJSON)
import Protolude hiding (filter)
import Text.PrettyPrint.GenericPretty
--
import Betfair.APING.API.APIRequest (apiRequest)
import Betfair.APING.API.Context
import Betfair.APING.API.GetResponse (getDecodedResponse)
import Betfair.APING.API.Log (tracePPLog)
import Betfair.APING.Types.MarketCatalogue (MarketCatalogue)
import Betfair.APING.Types.MarketFilter (MarketFilter (marketIds),
defaultMarketFilter)
import Betfair.APING.Types.MarketProjection (MarketProjection (..))
import Betfair.APING.Types.MarketSort (MarketSort (FIRST_TO_START))
import Betfair.APING.Types.ResponseMarketCatalogue (Response (result))
data JsonRequest = JsonRequest
{ jsonrpc :: Text
, method :: Text
, params :: Maybe JsonParameters
, id :: Int
} deriving (Eq, Show, Generic, Pretty)
data JsonParameters = JsonParameters
{ filter :: MarketFilter
, marketProjection :: Maybe [MarketProjection]
, sort :: MarketSort
, maxResults :: Int
, locale :: Maybe Text
} deriving (Eq, Show, Generic, Pretty)
-- The weight of all the below are 0.
-- Hence, I should get the maximum of 1000 markets
defaultJsonParameters :: JsonParameters
defaultJsonParameters =
JsonParameters
defaultMarketFilter
(Just
[ COMPETITION
, EVENT
, EVENT_TYPE
, MARKET_START_TIME
-- , MARKET_DESCRIPTION
, RUNNER_DESCRIPTION
])
-- , RUNNER_METADATA
FIRST_TO_START
1000
Nothing
$(deriveJSON defaultOptions {omitNothingFields = True} ''JsonParameters)
$(deriveJSON defaultOptions {omitNothingFields = True} ''JsonRequest)
jsonRequest :: JsonParameters -> JsonRequest
jsonRequest jp =
JsonRequest "2.0" "SportsAPING/v1.0/listMarketCatalogue" (Just jp) 1
type MarketId = Text
marketIdJsonRequest :: MarketId -> JsonParameters
marketIdJsonRequest mktid =
defaultJsonParameters
{filter = defaultMarketFilter {marketIds = Just [mktid]}}
marketCatalogue :: Context -> MarketId -> IO [MarketCatalogue]
marketCatalogue c mktid = listMarketCatalogue c (marketIdJsonRequest mktid)
listMarketCatalogue :: Context -> JsonParameters -> IO [MarketCatalogue]
listMarketCatalogue c jp =
tracePPLog c =<<
fmap result . getDecodedResponse c =<<
(\r -> tracePPLog c (jsonRequest jp) >> return r) =<<
apiRequest c (A.encode $ jsonRequest jp)
| joe9/betfair-api | src/Betfair/APING/Requests/ListMarketCatalogue.hs | mit | 3,278 | 0 | 12 | 848 | 642 | 380 | 262 | 75 | 1 |
{-# htermination (floatRadixFloat :: Float -> Integer) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Float = Float MyInt MyInt ;
data Integer = Integer MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
fromIntInteger :: MyInt -> Integer
fromIntInteger x = Integer x;
primFloatRadix :: Integer;
primFloatRadix = fromIntInteger (Pos (Succ (Succ Zero)));
floatRadixFloat :: Float -> Integer
floatRadixFloat vv = primFloatRadix;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/floatRadix_1.hs | mit | 519 | 0 | 11 | 105 | 159 | 91 | 68 | 13 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Unison.Names3 where
import Unison.Prelude
import Control.Lens (view, _4)
import Data.List (sort)
import Data.List.Extra (nubOrd)
import Unison.HashQualified (HashQualified)
import qualified Unison.HashQualified as HQ
import qualified Unison.HashQualified' as HQ'
import Unison.Name (Name)
import Unison.Reference as Reference
import Unison.Referent as Referent
import Unison.Util.Relation (Relation)
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Unison.Name as Name
import qualified Unison.Names2
import qualified Unison.Names2 as Names
import qualified Unison.Util.List as List
import qualified Unison.Util.Relation as R
import qualified Unison.ConstructorType as CT
data Names = Names { currentNames :: Names0, oldNames :: Names0 } deriving Show
type Names0 = Unison.Names2.Names0
pattern Names0 terms types = Unison.Names2.Names terms types
data ResolutionFailure v a
= TermResolutionFailure v a (Set Referent)
| TypeResolutionFailure v a (Set Reference)
deriving (Eq,Ord,Show)
type ResolutionResult v a r = Either (Seq (ResolutionFailure v a)) r
filterTypes :: (Name -> Bool) -> Names0 -> Names0
filterTypes = Unison.Names2.filterTypes
-- Simple 2 way diff, has the property that:
-- addedNames (diff0 n1 n2) == removedNames (diff0 n2 n1)
--
-- `addedNames` are names in `n2` but not `n1`
-- `removedNames` are names in `n1` but not `n2`
diff0 :: Names0 -> Names0 -> Diff
diff0 n1 n2 = Diff n1 added removed where
added = Names0 (terms0 n2 `R.difference` terms0 n1)
(types0 n2 `R.difference` types0 n1)
removed = Names0 (terms0 n1 `R.difference` terms0 n2)
(types0 n1 `R.difference` types0 n2)
data Diff =
Diff { originalNames :: Names0
, addedNames :: Names0
, removedNames :: Names0
} deriving Show
isEmptyDiff :: Diff -> Bool
isEmptyDiff d = isEmpty0 (addedNames d) && isEmpty0 (removedNames d)
isEmpty0 :: Names0 -> Bool
isEmpty0 n = R.null (terms0 n) && R.null (types0 n)
-- Add `n1` to `currentNames`, shadowing anything with the same name and
-- moving shadowed definitions into `oldNames` so they can can still be
-- referenced hash qualified.
push :: Names0 -> Names -> Names
push n0 ns = Names (unionLeft0 n1 cur) (oldNames ns <> shadowed) where
n1 = suffixify0 n0
cur = currentNames ns
shadowed = names0 terms' types' where
terms' = R.dom (terms0 n1) R.<| (terms0 cur `R.difference` terms0 n1)
types' = R.dom (types0 n1) R.<| (types0 cur `R.difference` types0 n1)
unionLeft0 :: Names0 -> Names0 -> Names0
unionLeft0 n1 n2 = names0 terms' types' where
terms' = terms0 n1 <> R.subtractDom (R.dom $ terms0 n1) (terms0 n2)
types' = types0 n1 <> R.subtractDom (R.dom $ types0 n1) (types0 n2)
-- For all names in `ns`, (ex: foo.bar.baz), generate the list of suffixes
-- of that name [[foo.bar.baz], [bar.baz], [baz]]. Any suffix which uniquely
-- refers to a single definition is added as an alias
--
-- If `Names` were more like a `[Names0]`, then `push` could just cons
-- onto the list and we could get rid of all this complex logic. The
-- complexity here is that we have to "bake the shadowing" into a single
-- Names0, taking into account suffix-based name resolution.
--
-- We currently have `oldNames`, but that controls an unrelated axis, which
-- is whether names are hash qualified or not.
suffixify0 :: Names0 -> Names0
suffixify0 ns = ns <> suffixNs
where
suffixNs = names0 (R.fromList uniqueTerms) (R.fromList uniqueTypes)
terms = List.multimap [ (n,ref) | (n0,ref) <- R.toList (terms0 ns), n <- Name.suffixes n0 ]
types = List.multimap [ (n,ref) | (n0,ref) <- R.toList (types0 ns), n <- Name.suffixes n0 ]
uniqueTerms = [ (n,ref) | (n, nubOrd -> [ref]) <- Map.toList terms ]
uniqueTypes = [ (n,ref) | (n, nubOrd -> [ref]) <- Map.toList types ]
unionLeft0 :: Names0 -> Names0 -> Names0
unionLeft0 = Unison.Names2.unionLeft
unionLeftName0 :: Names0 -> Names0 -> Names0
unionLeftName0 = Unison.Names2.unionLeftName
map0 :: (Name -> Name) -> Names0 -> Names0
map0 f (Names.Names terms types) = Names.Names terms' types' where
terms' = R.mapDom f terms
types' = R.mapDom f types
names0 :: Relation Name Referent -> Relation Name Reference -> Names0
names0 = Unison.Names2.Names
types0 :: Names0 -> Relation Name Reference
types0 = Names.types
terms0 :: Names0 -> Relation Name Referent
terms0 = Names.terms
-- if I push an existing name, the pushed reference should be the thing
-- if I push a different name for the same thing, i suppose they should coexist
-- thus, `unionLeftName0`.
shadowing :: Names0 -> Names -> Names
shadowing prio (Names current old) =
Names (prio `unionLeftName0` current) (current <> old)
makeAbsolute0:: Names0 -> Names0
makeAbsolute0 = map0 Name.makeAbsolute
-- Find all types whose name has a suffix matching the provided `HashQualified`,
-- returning types with relative names if they exist, and otherwise
-- returning types with absolute names.
lookupRelativeHQType :: HashQualified Name -> Names -> Set Reference
lookupRelativeHQType hq ns@Names{..} = let
rs = lookupHQType hq ns
keep r = any (not . Name.isAbsolute) (R.lookupRan r (Names.types currentNames))
in case Set.filter keep rs of
rs' | Set.null rs' -> rs
| otherwise -> rs'
-- Find all types whose name has a suffix matching the provided `HashQualified`.
lookupHQType :: HashQualified Name -> Names -> Set Reference
lookupHQType hq Names{..} = case hq of
HQ.NameOnly n -> Name.searchBySuffix n (Names.types currentNames)
HQ.HashQualified n sh -> case matches sh (Names.types currentNames) of
s | (not . null) s -> s
| otherwise -> matches sh (Names.types oldNames)
where
matches sh ns =
Set.filter (Reference.isPrefixOf sh) (Name.searchBySuffix n ns)
HQ.HashOnly sh -> case matches sh currentNames of
s | (not . null) s -> s
| otherwise -> matches sh oldNames
where
matches sh ns = Set.filter (Reference.isPrefixOf sh) (R.ran $ Names.types ns)
hasTermNamed :: Name -> Names -> Bool
hasTermNamed n ns = not (Set.null $ lookupHQTerm (HQ.NameOnly n) ns)
hasTypeNamed :: Name -> Names -> Bool
hasTypeNamed n ns = not (Set.null $ lookupHQType (HQ.NameOnly n) ns)
-- Find all terms whose name has a suffix matching the provided `HashQualified`,
-- returning terms with relative names if they exist, and otherwise
-- returning terms with absolute names.
lookupRelativeHQTerm :: HashQualified Name -> Names -> Set Referent
lookupRelativeHQTerm hq ns@Names{..} = let
rs = lookupHQTerm hq ns
keep r = any (not . Name.isAbsolute) (R.lookupRan r (Names.terms currentNames))
in case Set.filter keep rs of
rs' | Set.null rs' -> rs
| otherwise -> rs'
-- Find all terms whose name has a suffix matching the provided `HashQualified`.
lookupHQTerm :: HashQualified Name -> Names -> Set Referent
lookupHQTerm hq Names{..} = case hq of
HQ.NameOnly n -> Name.searchBySuffix n (Names.terms currentNames)
HQ.HashQualified n sh -> case matches sh (Names.terms currentNames) of
s | (not . null) s -> s
| otherwise -> matches sh (Names.terms oldNames)
where
matches sh ns =
Set.filter (Referent.isPrefixOf sh) (Name.searchBySuffix n ns)
HQ.HashOnly sh -> case matches sh currentNames of
s | (not . null) s -> s
| otherwise -> matches sh oldNames
where
matches sh ns = Set.filter (Referent.isPrefixOf sh) (R.ran $ Names.terms ns)
-- If `r` is in "current" names, look up each of its names, and hash-qualify
-- them if they are conflicted names. If `r` isn't in "current" names, look up
-- each of its "old" names and hash-qualify them.
typeName :: Int -> Reference -> Names -> Set (HQ'.HashQualified Name)
typeName length r Names{..} =
if R.memberRan r . Names.types $ currentNames
then Set.map (\n -> if isConflicted n then hq n else HQ'.fromName n)
(R.lookupRan r . Names.types $ currentNames)
else Set.map hq (R.lookupRan r . Names.types $ oldNames)
where hq n = HQ'.take length (HQ'.fromNamedReference n r)
isConflicted n = R.manyDom n (Names.types currentNames)
-- List of names for a referent, longer names (by number of segments) first.
termNamesByLength :: Int -> Referent -> Names -> [HQ'.HashQualified Name]
termNamesByLength length r ns =
sortOn len (toList $ termName length r ns)
where len (HQ'.NameOnly n) = Name.countSegments n
len (HQ'.HashQualified n _) = Name.countSegments n
-- The longest term name (by segment count) for a `Referent`.
longestTermName :: Int -> Referent -> Names -> HQ.HashQualified Name
longestTermName length r ns =
case reverse (termNamesByLength length r ns) of
[] -> HQ.take length (HQ.fromReferent r)
(h : _) -> Name.convert h
termName :: Int -> Referent -> Names -> Set (HQ'.HashQualified Name)
termName length r Names{..} =
if R.memberRan r . Names.terms $ currentNames
then Set.map (\n -> if isConflicted n then hq n else HQ'.fromName n)
(R.lookupRan r . Names.terms $ currentNames)
else Set.map hq (R.lookupRan r . Names.terms $ oldNames)
where hq n = HQ'.take length (HQ'.fromNamedReferent n r)
isConflicted n = R.manyDom n (Names.terms currentNames)
suffixedTypeName :: Int -> Reference -> Names -> [HQ.HashQualified Name]
suffixedTermName :: Int -> Referent -> Names -> [HQ.HashQualified Name]
(suffixedTermName,suffixedTypeName) =
( suffixedName termName (Names.terms . currentNames) HQ'.fromNamedReferent
, suffixedName typeName (Names.types . currentNames) HQ'.fromNamedReference )
where
suffixedName fallback getRel hq' length r ns@(getRel -> rel) =
if R.memberRan r rel
then go $ toList (R.lookupRan r rel)
else sort $ map Name.convert $ Set.toList (fallback length r ns)
where
-- Orders names, using these criteria, in this order:
-- 1. NameOnly comes before HashQualified,
-- 2. Shorter names (in terms of segment count) come before longer ones
-- 3. If same on attributes 1 and 2, compare alphabetically
go :: [Name] -> [HashQualified Name]
go fqns = map (view _4) . sort $ map f fqns where
f fqn = let
n' = Name.shortestUniqueSuffix fqn r rel
isHQ'd = R.manyDom fqn rel -- it is conflicted
hq n = HQ'.take length (hq' n r)
hqn = Name.convert $ if isHQ'd then hq n' else HQ'.fromName n'
in (isHQ'd, Name.countSegments fqn, Name.isAbsolute n', hqn)
-- Set HashQualified -> Branch m -> Action' m v Names
-- Set HashQualified -> Branch m -> Free (Command m i v) Names
-- Set HashQualified -> Branch m -> Command m i v Names
-- populate historical names
lookupHQPattern
:: HQ.HashQualified Name
-> CT.ConstructorType
-> Names
-> Set (Reference, Int)
lookupHQPattern hq ctt names = Set.fromList
[ (r, cid)
| Referent.Con r cid ct <- toList $ lookupHQTerm hq names
, ct == ctt
]
-- Finds all the constructors for the given type in the `Names0`
constructorsForType0 :: Reference -> Names0 -> [(Name,Referent)]
constructorsForType0 r ns = let
-- rather than searching all of names, we use the known possible forms
-- that the constructors can take
possibleDatas = [ Referent.Con r cid CT.Data | cid <- [0..] ]
possibleEffects = [ Referent.Con r cid CT.Effect | cid <- [0..] ]
trim [] = []
trim (h:t) = case R.lookupRan h (terms0 ns) of
s | Set.null s -> []
| otherwise -> [ (n,h) | n <- toList s ] ++ trim t
in trim possibleEffects ++ trim possibleDatas
-- Given a mapping from name to qualified name, update a `Names`,
-- so for instance if the input has [(Some, Optional.Some)],
-- and `Optional.Some` is a constructor in the input `Names`,
-- the alias `Some` will map to that same constructor and shadow
-- anything else that is currently called `Some`.
--
-- Only affects `currentNames`.
importing :: [(Name, Name)] -> Names -> Names
importing shortToLongName ns =
ns { currentNames = importing0 shortToLongName (currentNames ns) }
importing0 :: [(Name, Name)] -> Names0 -> Names0
importing0 shortToLongName ns =
Names.Names
(foldl' go (terms0 ns) shortToLongName)
(foldl' go (types0 ns) shortToLongName)
where
go :: (Ord r) => Relation Name r -> (Name, Name) -> Relation Name r
go m (shortname, qname) = case Name.searchBySuffix qname m of
s | Set.null s -> m
| otherwise -> R.insertManyRan shortname s (R.deleteDom shortname m)
-- Converts a wildcard import into a list of explicit imports, of the form
-- [(suffix, full)]. Example: if `io` contains two functions, `foo` and
-- `bar`, then `expandWildcardImport io` will produce
-- `[(foo, io.foo), (bar, io.bar)]`.
expandWildcardImport :: Name -> Names0 -> [(Name,Name)]
expandWildcardImport prefix ns =
[ (suffix, full) | Just (suffix,full) <- go <$> R.toList (terms0 ns) ] <>
[ (suffix, full) | Just (suffix,full) <- go <$> R.toList (types0 ns) ]
where
go (full, _) = do
-- running example:
-- prefix = Int
-- full = builtin.Int.negate
rem <- Name.suffixFrom prefix full
-- rem = Int.negate
suffix <- Name.stripNamePrefix prefix rem
-- suffix = negate
pure (suffix, full)
-- Deletes from the `n0 : Names0` any definitions whose names
-- share a suffix with a name in `ns`. Does so using logarithmic
-- time lookups, traversing only `ns`.
--
-- See usage in `FileParser` for handling precendence of symbol
-- resolution where local names are preferred to codebase names.
shadowSuffixedTerms0 :: [Name] -> Names0 -> Names0
shadowSuffixedTerms0 ns n0 = names0 terms' (types0 n0)
where
shadowedBy name = Name.searchBySuffix name (terms0 n0)
terms' = R.subtractRan (foldMap shadowedBy ns) (terms0 n0)
| unisonweb/platform | unison-core/src/Unison/Names3.hs | mit | 13,841 | 0 | 18 | 2,783 | 4,038 | 2,103 | 1,935 | 213 | 3 |
-----------------------------------------------------------------------------
-- Copyright : (c) Hanzhong Xu, Meng Meng 2016,
-- License : MIT License
--
-- Maintainer : hanzh.xu@gmail.com
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
-- A simple calculator
-----------------------------------------------------------------------------
-- {-# LANGUAGE Arrows #-}
module Main where
import Control.Arrow
import Control.Monad
import Data.SF
import Data.SF.Draft.IOSF
import Data.Maybe
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.STM.TChan
import Data.IORef
-- import Data.Map (fromList, (!))
data Op = Add | Sub | Mul | Div
deriving (Eq)
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
data Token = Num Int | Op Op | L | R | End
deriving (Eq)
instance Show Token where
show (Num x) = show x
show (Op op) = show op
show L = "("
show R = ")"
show End = ""
-- 3 * (2 - 3) + (4 - 2 * 3)
test1 = [Num 3, Op Mul, L, Num 2, Op Sub, Num 3, R, Op Add, L, Num 4, Op Sub, Num 2, Op Mul, Num 3, R, End]
-- 3 + 4 * 2 / (1 - 5) * 2 + 3
test2 = [Num 3, Op Add, Num 4, Op Mul, Num 2, Op Div, L, Num 1, Op Sub, Num 5, R, Op Mul, Num 2, Op Add, Num 3, End]
-- State machines
trans0 :: [Token] -> Token -> ([Token], [Token])
trans0 xs End = ([End], xs)
trans0 xs (Num x) = (xs, [(Num x)])
trans0 xs L = (L:xs, [])
trans0 xs R = let (x0, x1) = span (L /= ) xs in (tail $ x1, x0)
trans0 xs op =
(op:x1, x0)
where
f0 = (\x -> x == (Op Mul) || x == (Op Div))
(x0, x1) = span f0 xs
-- the SF converting infix to postfix
--
-- Token /---------\ [Token]
-- >----->| in2post |>------->
-- \---------/
--
in2post :: SF Token [Token]
in2post = simpleSF trans0 [End]
post1 = concat $ getRet in2post test1
post2 = concat $ getRet in2post test2
f :: Op -> Int -> Int -> Int
f Add x y = x + y
f Sub x y = x - y
f Mul x y = x * y
f Div x y = quot x y
trans1 :: [Int] -> Token -> ([Int], Maybe Int)
trans1 xs End = if (null xs) then (xs, Just 0) else ([], Just $ head xs)
trans1 xs (Num x) = (x:xs, Nothing)
trans1 (x:y:xs) (Op o) = ((f o y x):xs, Nothing)
-- the SF evaluating postfix expression
--
-- Token /-----------\ Maybe Int
-- >----->| post2ret' |>--------->
-- \-----------/
--
post2ret' :: SF Token (Maybe Int)
post2ret' = simpleSF trans1 []
--
-- [Token] /----------\ [Maybe Int]
-- >------->| post2ret |>----------->
-- \----------/
--
post2ret :: SF [Token] [Maybe Int]
post2ret = execSF post2ret'
-- an example to use Arrow notation
-- the SF composed of in2post and post2ret
--
-- /----------------------------\
-- Token | [Token] | [Maybe Int]
-- >----->| in2post >-------> post2ret |>----------->
-- | |
-- \----------------------------/
-- in2ret
--
in2ret :: SF Token [Maybe Int]
in2ret = in2post >>> post2ret
{-
hg = hideStorage
in2ret :: SFH Token [Maybe Int]
in2ret = hg $ proc x -> do
y <- (hg in2post) -< x
(hg post2ret) -< y
-}
-- Parsing and evaluating
getRet :: SF a b -> [a] -> [b]
getRet sf xs = snd $ sfexec sf xs
calc :: [Token] -> [Int]
calc xs = catMaybes $ concat $ getRet in2ret xs
isNum :: Char -> Bool
isNum x = elem x "0123456789"
-- parseOp x = (fromList $ zip "()+-*/" [L, R, Op Add, Op Sub, Op Mul, Op Div])!x
parseOp :: Char -> Token
parseOp '(' = L
parseOp ')' = R
parseOp '+' = Op Add
parseOp '-' = Op Sub
parseOp '*' = Op Mul
parseOp '/' = Op Div
parseStr :: String -> [Token]
parseStr [] = [End]
parseStr (x:xs) =
if elem x ",\n" then End : (parseStr xs)
else if x == ' ' then parseStr xs
else if isNum x then
let (ys, zs) = span isNum xs in (Num $ read (x:ys)):(parseStr zs)
else if elem x "()+-*/" then
(parseOp x):(parseStr xs)
else
parseStr xs
{-
main = do
getContents >>= (mapM_ putStrLn).(map show).(calc.parseStr)
-}
main = do
s <- getContents
tc <- newBroadcastTChanIO
tf <- newThreadSF in2ret
ret <- tf tc
-- forM_ (parseStr s) (\t -> do (putStrLn.show) t; atomically $ writeTChan tc t; tryOutputTChan ret (putStrLn.show))
forkIO $ outputTChan ret
(\x -> case x of
(Just a) -> putStrLn $ show a
Nothing -> return ()
)
writeList2TChan tc (parseStr s)
-- sequence_ (map (\t -> do atomically $ writeTChan tc t;) (parseStr s))
-- forM_ test1 (\t -> do (putStrLn.show) t; atomically $ writeTChan tc t; tryOutputTChan ret (putStrLn.show))
-- writeList2TChan tc test1
-- input samples
-- 3 * (2 - 3) + (4 - 2 * 3), 3 + 4 * 2 / (1 - 5) * 2 + 3
| PseudoPower/AFSM | examples/SF/RPN.hs | mit | 4,703 | 0 | 15 | 1,140 | 1,479 | 802 | 677 | 88 | 5 |
module Yage.Rendering
( module Mesh
, module LinExport
, module RenderSystem
, module GLTypes
) where
import Linear as LinExport hiding (lerp, slerp)
import Yage.Rendering.Backend.RenderSystem as RenderSystem
import Yage.Rendering.Mesh as Mesh
import Graphics.Rendering.OpenGL.Raw.Types as GLTypes
| MaxDaten/yage-rendering | src/Yage/Rendering.hs | mit | 426 | 0 | 5 | 163 | 65 | 48 | 17 | 9 | 0 |
{-# LANGUAGE BangPatterns #-}
module Utils.Memo (memoList, memoTree, toList) where
-- List Memoization
-- Mutually recursive function that memoizes an operation by storing intermediate results in a list
memoList :: (Integral a) => ((a -> a) -> a -> a) -> a -> a
memoList f = memoList_f
where memoList_f = (memo !!) . fromIntegral
memo = map (f memoList_f) [0..]
-- Usage: (f) is an open-recursive function that uses the provided (mf) for recursion
--
-- f :: (Integer -> Integer) -> Integer -> Integer
-- f mf n = ...
--
-- (faster_f) creates the actual memoized function by passing (f) to (memoList)
--
-- faster_f :: Integer -> Integer
-- faster_f = memoList f
-- Tree Memoization (for when a list just doesn't cut it)
-- Infinite tree data structure (index representation below):
-- 0
-- 1 2
-- 3 4 5 6
-- 7 8 9 10 11 12 13 14
data MemoTree a = MemoTree (MemoTree a) a (MemoTree a)
instance Functor MemoTree where
fmap f (MemoTree l m r) = MemoTree (fmap f l) (f m) (fmap f r)
-- get a value from the tree at a specific index
index :: (Integral a) => MemoTree a -> a -> a
index (MemoTree _ m _) 0 = m
index (MemoTree l _ r) n = case (n - 1) `divMod` 2 of
(q,0) -> index l q
(q,1) -> index r q
-- same as [0..] but for the MemoTree data structure
nats :: (Integral a) => MemoTree a
nats = go 0 1
where
go !n !s = MemoTree (go l s') n (go r s')
where
l = n + s
r = l + s
s' = s * 2
-- convert the tree to a list
toList :: (Integral a) => MemoTree a -> [a]
toList as = map (index as) [0..]
-- Mutually recursive function that memoizes an operation by storing intermediate results in a tree
memoTree :: (Integral a) => ((a -> a) -> a -> a) -> a -> a
memoTree f = memoTree_f
where memoTree_f = index memo
memo = fmap (f memoTree_f) nats
-- Usage: (f) is an open-recursive function that uses the provided (mf) for recursion
--
-- f :: (Integer -> Integer) -> Integer -> Integer
-- f mf n = ...
--
-- (fastest_f) creates the actual memoized function by passing (f) to (memoTree)
--
-- fastest_f :: Integer -> Integer
-- fastest_f = memoTree f | jchitel/ProjectEuler.hs | Problems/Utils/Memo.hs | mit | 2,209 | 0 | 10 | 585 | 542 | 300 | 242 | 26 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
----------------------------------------------------------------------
-- |
-- Module: Licensor
-- Description:
--
--
--
----------------------------------------------------------------------
module Licensor
( LiLicense(..)
, LiPackage(..)
, getDependencies
, getLicenses
, getPackage
, getPackageLicenseFiles
, orderPackagesByLicense
, version
)
where
-- base
import qualified Control.Exception as Exception
import Control.Monad (unless)
import Data.Traversable (for)
import Data.Version (Version)
-- bytestring
import qualified Data.ByteString.Lazy as LBS
-- Cabal
import Distribution.License (License)
import Distribution.Package (PackageIdentifier(..), PackageName, unPackageName)
import Distribution.PackageDescription
(PackageDescription, licenseFiles, packageDescription)
import Distribution.PackageDescription.Parsec
(parseGenericPackageDescriptionMaybe, readGenericPackageDescription)
import Distribution.Pretty (Pretty)
import Distribution.Simple.Utils (comparing, findPackageDesc)
import Distribution.Text (display, simpleParse)
import Distribution.Verbosity (silent)
-- containers
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
-- directory
import System.Directory (getCurrentDirectory)
-- http-client
import Network.HTTP.Client (httpLbs, parseRequest, responseBody)
-- http-client-tls
import Network.HTTP.Client.TLS (getGlobalManager)
-- licensor
import qualified Paths_licensor
-- process
import System.Process (readProcess)
-- tar
import qualified Codec.Archive.Tar as Tar
-- temporary
import qualified System.IO.Temp as Temp
-- zlib
import qualified Codec.Compression.GZip as GZip
-- |
--
--
newtype LiLicense = LiLicense { getLicense :: License }
deriving (Eq, Read, Show, Pretty)
-- |
--
--
instance Ord LiLicense where
compare =
comparing display
-- |
--
--
data LiPackage =
LiPackage
{ liPackageId :: PackageIdentifier
, liPackageDependencies :: Set LiPackage
, liPackageLicense :: License
}
-- |
--
--
getPackage :: IO (Maybe PackageDescription)
getPackage = do
currentDirectory <- getCurrentDirectory
fmap getPackageDescription <$> findPackageDesc currentDirectory
>>= either (const (pure Nothing)) (fmap Just)
-- |
--
--
getPackageDescription :: FilePath -> IO PackageDescription
getPackageDescription =
fmap packageDescription . readGenericPackageDescription silent
-- |
--
--
getDependencies :: IO (Maybe (Set PackageIdentifier))
getDependencies = do
eitherDeps <-
Exception.try $ readProcess "stack" ["ls", "dependencies", "--separator", "-"] ""
case eitherDeps of
Left (_ :: IOError) ->
pure Nothing
Right deps ->
pure $ Set.fromList <$> traverse simpleParse (lines deps)
getLicenses :: IO (Maybe [(PackageName, License)])
getLicenses = do
eitherDeps <-
Exception.try $ readProcess "stack" ["ls", "dependencies", "--license"] ""
case eitherDeps of
Left (_ :: IOError) ->
pure Nothing
Right deps ->
pure $ traverse toNameLicense (lines deps)
where
toNameLicense dep =
case words dep of
[name, license] ->
(,) <$> simpleParse name <*> simpleParse license
_ ->
Nothing
-- |
--
--
getPackageLicense
:: Bool
-> PackageIdentifier
-> [(PackageName, License)]
-> IO (Maybe LiLicense)
getPackageLicense quiet packageIdentifier licenses = do
unless quiet (putStr $ display packageIdentifier ++ "...")
case lookup (pkgName packageIdentifier) licenses of
Just license -> do
unless quiet (putStrLn $ display license)
pure $ Just (LiLicense license)
Nothing ->
pure Nothing
-- |
--
--
orderPackagesByLicense
:: Bool
-> Maybe PackageIdentifier
-> [(PackageName, License)]
-> Set PackageIdentifier
-> IO (Map LiLicense (Set PackageIdentifier), Set PackageIdentifier)
orderPackagesByLicense quiet maybeP licenses =
let
cond =
maybe (const False) (==) maybeP
insertPackage package orderedPackages' = do
maybeLicense <- getPackageLicense quiet package licenses
(orderedPackages, failed) <- orderedPackages'
pure $
if cond package
then
(orderedPackages, failed)
else
case maybeLicense of
Nothing ->
( orderedPackages, Set.insert package failed
)
Just license ->
( Map.insertWith
Set.union
license
(Set.singleton package)
orderedPackages
, failed
)
in
foldr insertPackage (pure (mempty, mempty))
-- |
--
--
version :: Version
version =
Paths_licensor.version
getPackageLicenseFiles :: PackageIdentifier -> IO (Maybe [String])
getPackageLicenseFiles packageIdentifier =
getPackageLicenseFiles'
(unPackageName (pkgName packageIdentifier))
(display packageIdentifier)
getPackageLicenseFiles' :: String -> String -> IO (Maybe [String])
getPackageLicenseFiles' packageName packageId = do
putStrLn ""
putStrLn ("### " <> packageId)
putStrLn ""
manager <- getGlobalManager
genPkgDescrReq <- parseRequest (mkRequest (packageName <> ".cabal"))
genPkgDescr <- LBS.toStrict . responseBody <$> httpLbs genPkgDescrReq manager
let mGenPkgDescr = parseGenericPackageDescriptionMaybe genPkgDescr
case licenseFiles . packageDescription <$> mGenPkgDescr of
Just files -> do
pkgReq <- parseRequest (mkRequest (packageId <> ".tar.gz"))
pkg <- responseBody <$> httpLbs pkgReq manager
let entries = Tar.read (GZip.decompress pkg)
pkgLicenseFiles <-
Temp.withSystemTempDirectory packageId $ \tmpDir -> do
Tar.unpack tmpDir entries
for files $ \file -> do
contents <- readFile (tmpDir <> "/" <> packageId <> "/" <> file)
putStrLn (file <> ":")
putStrLn ""
putStrLn "```"
putStrLn contents
putStrLn "```"
pure file
pure (Just pkgLicenseFiles)
Nothing ->
pure Nothing
where
mkRequest r =
"GET https://hackage.haskell.org/package/" <> packageId <> "/" <> r
| jpvillaisaza/licensor | src/Licensor.hs | mit | 6,365 | 0 | 27 | 1,419 | 1,610 | 865 | 745 | 159 | 3 |
{-# OPTIONS_GHC -Wall -fwarn-tabs -Werror #-}
-------------------------------------------------------------------------------
-- |
-- Module : Graphics.Primitives.Flat
-- Copyright : Copyright (c) 2014 Michael R. Shannon
-- License : GPLv2 or Later
-- Maintainer : mrshannon.aerospace@gmail.com
-- Stability : unstable
-- Portability : portable
--
-- 2D primitives.
-------------------------------------------------------------------------------
module Graphics.Primitives.Flat
( drawCircle
, drawQuad
, drawQuadT
) where
import Data.Word
import Control.Monad
import qualified Graphics.Rendering.OpenGL as GL
import qualified Graphics.OpenGL.Help as GL
import Graphics.Types
-- Draw a cirlce.
drawCircle :: Shading -> Word -> IO ()
drawCircle shading faces
| shading == Wire = drawCircleWire faces
| otherwise = drawCircleSurface shading faces
-- Helper function for drawCircle.
drawCircleWire :: Word -> IO ()
drawCircleWire faces = GL.renderPrimitive GL.LineLoop $ mapM_ loop sVar
where
ds = 2 * pi / fromIntegral faces
sVar = [0.0,ds..2*pi]
loop s = GL.vertex $ GL.vertex2f (cos s) (sin s)
-- Helper function for drawCirlce.
drawCircleSurface :: Shading -> Word -> IO ()
drawCircleSurface _ faces = GL.renderPrimitive GL.TriangleFan $ do
-- Set normal.
GL.normal $ GL.normal3f 0.0 0.0 1.0
-- Draw the center.
GL.texCoord2f 0.5 0.5
GL.vertex $ GL.vertex2f 0.0 0.0
-- Draw the circle.
mapM_ loop sVar
where
ds = 2 * pi / fromIntegral faces
sVar = [0.0,ds..2*pi]
loop s = do
GL.texCoord2f (0.5 + 0.5 * (cos $ s + ds))
(0.5 + 0.5 * (sin $ s + ds))
GL.vertex $ GL.vertex2f (cos s) (sin s)
-- Draw a subdivided quad.
drawQuad :: Shading -> Word -> Word -> IO ()
drawQuad shading xSubs ySubs
| shading == Wire = drawQuadWire xSubs ySubs
| otherwise = drawQuadSurface shading xSubs ySubs
-- Draw a subdivided quad (with texture coordinates).
drawQuadT :: Shading -> Word -> Word -> Float -> IO ()
drawQuadT shading xSubs ySubs textureScale
| shading == Wire = drawQuadWire xSubs ySubs
| otherwise = drawQuadSurfaceT shading xSubs ySubs textureScale
-- Helper function for drawQuad and drawQuadT
drawQuadWire :: Word -> Word -> IO ()
drawQuadWire xSubs ySubs = GL.renderPrimitive GL.Lines $ do
forM_ [-1.0,(-1.0 + dx)..1.0] (\x -> do
GL.vertex $ GL.vertex2f x (-1.0)
GL.vertex $ GL.vertex2f x 1.0
)
forM_ [-1.0,(-1.0 + dy)..1.0] (\y -> do
GL.vertex $ GL.vertex2f (-1.0) y
GL.vertex $ GL.vertex2f 1.0 y
)
where
dx = 2.0 / fromIntegral xSubs
dy = 2.0 / fromIntegral ySubs
-- Helper function for drawQuad
drawQuadSurface :: Shading -> Word -> Word -> IO ()
drawQuadSurface _ xSubs ySubs = do
-- Set normal.
GL.normal $ GL.normal3f 0.0 0.0 1.0
-- Draw the quads.
mapM_ loop coords
where
dx = 2.0 / fromIntegral xSubs
dy = 2.0 / fromIntegral ySubs
xList = [-1.0,(-1.0 + dx)..(1.0 - dx)]
yList = [-1.0,(-1.0 + dy)..(1.0 - dy)]
coords = [(x,y) | x <- xList, y <- yList]
loop (x,y) = GL.renderPrimitive GL.Quads $ do
GL.vertex $ GL.vertex2f x y
GL.vertex $ GL.vertex2f (x + dx) y
GL.vertex $ GL.vertex2f (x + dx) (y + dy)
GL.vertex $ GL.vertex2f x (y + dy)
-- Helper function for drawQuadT
drawQuadSurfaceT :: Shading -> Word -> Word -> Float -> IO ()
drawQuadSurfaceT _ xSubs ySubs textureScale = do
-- Set normal.
GL.normal $ GL.normal3f 0.0 0.0 1.0
-- Draw the quads.
mapM_ loop coords
where
dx = 2.0 / fromIntegral xSubs
dy = 2.0 / fromIntegral ySubs
xList = [-1.0,(-1.0 + dx)..(1.0 - dx)]
yList = [-1.0,(-1.0 + dy)..(1.0 - dy)]
coords = [(x,y) | x <- xList, y <- yList]
setTexCoord x y = GL.texCoord2f (textureScale * 0.5 * (x + 1.0))
(textureScale * 0.5 * (y + 1.0))
loop (x,y) = GL.renderPrimitive GL.Quads $ do
setTexCoord x y
GL.vertex $ GL.vertex2f x y
setTexCoord (x + dx) y
GL.vertex $ GL.vertex2f (x + dx) y
setTexCoord (x + dx) (y + dy)
GL.vertex $ GL.vertex2f (x + dx) (y + dy)
setTexCoord x (y + dy)
GL.vertex $ GL.vertex2f x (y + dy)
| mrshannon/trees | src/Graphics/Primitives/Flat.hs | gpl-2.0 | 4,862 | 0 | 16 | 1,664 | 1,511 | 774 | 737 | 83 | 1 |
module Main where
import Check
import qualified Numeric.Interval.Infinite as Iv
import Control.Applicative
import Data.Bits
import Data.Ix
import Data.Typeable
import qualified Data.Text as Strict
import Data.Word
tenSeconds :: Int
tenSeconds = 10000000
----------------------------------------------------------------------------------------------------
-- | A new integer data type is created where there are only eight possible values, [0..7]. This
-- data type is used to construct 'Dao.Interval.Interval' 'Dao.Interval.Set's that is isomorphic to
-- the 'Data.Word.Word8' data type. It then becomes possible to test operations on
-- 'Dao.Interval.Set's by comparing the result of the set operation to the result of the isomprohic
-- bitwise operation on the 'Data.Word.Word8' data type.
newtype I = I { w2Int :: Int } deriving Typeable
instance Eq I where { (I i) == (I j) = i == j }
instance Ord I where { compare (I i) (I j) = compare i j }
instance Enum I where
fromEnum = w2Int
toEnum i = if 0<=i && i<=7 then I i else error ("(toEnum :: Int -> I) ("++show i++")")
succ (I i) = I (if i >= 7 then error ("succ (I "++show i++") :: I") else i+1)
pred (I i) = I (if i <= 0 then error ("pred (I "++show i++") :: I") else i-1)
instance Bounded I where { minBound = I 0; maxBound = I 7 }
instance Iv.InfBound I where { minBoundInf = Iv.Finite minBound; maxBoundInf = Iv.Finite maxBound }
instance Show I where { show (I i) = take 0x3FFFF $ "I "++show i }
instance Read I where { readsPrec p str = map (\ (i, str) -> (I i, str)) (readsPrec p str) }
instance Ix I where
range (a, b) = if a>b then range (b, a) else
let loop a = a : if a==b then [] else loop (succ a) in loop a
inRange (a, b) i = a <= i && i <= b
index (a, b) i = if a>b then index (b, a) i else
if inRange (a, b) i then fromEnum i - fromEnum a else
error ("Bad index "++show i++" for range "++show (a, b))
rangeSize (a, b) = if a<b then fromEnum b - fromEnum a else rangeSize (b, a)
-- | Converts an 'I' value to a 'Data.Word.Word8' value by evaluating 2 to the power of the integer
-- value of 'I'. This creates a 'Data.Word.Word8', or an octet of bits with only one element in the
-- octet set, and that element is a distance from the start of the octet that is equivalent to the
-- interval distance 'I' would have if it were a member of a 'Dao.Interval.Set'.
i2byte :: I -> Word8
i2byte (I i) = setBit 0 i
----------------------------------------------------------------------------------------------------
-- Defines a new data type that wraps a 'Data.Word.Word8' value, but is intended to be used as a
-- data type that is isomophic to 'Dao.Interval.Set's containing 'I' 'Dao.Interval.Interval's.
newtype ISet = ISet { wSet2Word8 :: Word8 }
instance Eq ISet where { (ISet i) == (ISet j) = i == j }
instance Ord ISet where { compare (ISet i) (ISet j) = compare i j }
instance Num ISet where
(ISet i) + (ISet j) = ISet (i .|. j)
(ISet i) - (ISet j) = ISet (i .&. complement j)
(ISet i) * (ISet j) = ISet (i .&. j)
negate (ISet i) = ISet (complement i)
abs (ISet i) = ISet (abs i)
signum (ISet i) = ISet (signum i)
fromInteger i
| 0 <= i && i < 8 = ISet (toEnum (fromIntegral i))
| otherwise = error "fromInteger :: Integer -> ISet"
instance Bits ISet where
(ISet i) .&. (ISet j) = ISet (i .&. j)
(ISet i) .|. (ISet j) = ISet (i .|. j)
bit n = ISet (bit n)
testBit (ISet i) n = testBit i n
xor (ISet i) (ISet j) = ISet (xor i j)
popCount (ISet i) = popCount i
complement (ISet i) = ISet (complement i)
shiftR (ISet i) n = ISet (max (shiftR i n) 1)
shiftL (ISet i) n = ISet (max (shiftL i n) 0x80)
rotateR (ISet i) n = ISet (rotateR i n)
rotateL (ISet i) n = ISet (rotateL i n)
bitSize (ISet i) = bitSize i
bitSizeMaybe (ISet i) = bitSizeMaybe i
isSigned (ISet i) = isSigned i
instance Bounded ISet where { minBound = ISet 0x00 ; maxBound = ISet 0xFF }
instance Show ISet where { show (ISet i) = take 0x3FFFF $ "ISet "++show8Bits i }
show8Bits :: Word8 -> String
show8Bits w = [0..7] >>= \j -> let i = 7-j in if testBit w i then show i else "_"
everyI :: [I]
everyI = toEnum <$> [0..7]
everyISet :: [ISet]
everyISet = fmap ISet [0..0xFF]
----------------------------------------------------------------------------------------------------
-- | Creates data type of 'Dao.Interval.Set's of 'Dao.Interval.Interval's of 'I's. This data type is
-- isomophric to 'ISet'.
newtype SetOfI = SetOfI { getIntervalSet :: Iv.Set I } deriving (Eq, Typeable)
instance Show SetOfI where { show (SetOfI o) = take 0x3FFFF $ "SetOfI ("++show o++")" }
everySetOfI :: [SetOfI]
everySetOfI = let oi i = [[], [toEnum i]] in do {
o7 <- oi 7; o6 <- oi 6; o5 <- oi 5; o4 <- oi 4; o3 <- oi 3; o2 <- oi 2; o1 <- oi 1; o0 <- oi 0;
[SetOfI $ Iv.fromPoints $ concat [o7, o6, o5, o4, o3, o2, o1, o0]]; }
setOfI2Pairs :: SetOfI -> [(I, I)]
setOfI2Pairs (SetOfI o) = Iv.toBoundedPair <$> Iv.toList o
----------------------------------------------------------------------------------------------------
-- | This data type contains an 'ISet' and a 'SetOfI' which should be equivalent to each other.
-- Whether these values are actually equivalent is a predicate that can be checked by
-- 'checkEqISets'. Operations like set inversion, set intersection, set union, set deletion, and
-- set XOR can be defined that use the bitwise operators on the 'ISet' and the isomorphic
-- 'Dao.Interval.Set' operators operate on the 'SetOfI' at the same time. Once the operation has
-- been completed, 'checkEqISets' can be evaluated to check if the two sets are still equivalent.
data EqISets = EqISets ISet SetOfI deriving (Eq, Typeable)
instance Show EqISets where
show (EqISets i iset) = take 0x3FFFF $ "EqISets ("++show i++" == "++show iset++")"
-- | Checks whether an 'ISet' and a 'SetOfI' contained within a 'EqISets' are indeed equivalent.
-- This is done by iterating over all possible values of 'I', and then testing if 'I' is a member of
-- both 'ISet' and 'SetOfI's. Since an 'ISet' is a 'Data.Word.Word8' value, an 'I' is a member of an
-- 'ISet' if 'i2byte' evaluates to an value that when bitwise-ANDed with the octet contained in the
-- 'ISet' is a non-zero value. The 'I' is a member of the 'SetOfI's if the 'Dao.Interval.member'
-- predicate evaluates to 'Prelude.True' for the 'Dao.Interval.Set' contained within the 'SetOfI's.
checkEqISets :: EqISets -> Bool
checkEqISets (EqISets (ISet a) (SetOfI b)) = and $ do
i <- everyI
return $ Iv.member b i == (0 /= i2byte i .&. a)
binOpEqISets :: (Word8 -> Word8 -> Word8) -> (Iv.Set I -> Iv.Set I -> Iv.Set I) -> EqISets -> EqISets -> EqISets
binOpEqISets onBits onSets (EqISets (ISet isA) (SetOfI soiA)) (EqISets (ISet isB) (SetOfI soiB)) =
EqISets (ISet $ onBits isA isB) (SetOfI $ onSets soiA soiB)
wholeEqISets :: EqISets
wholeEqISets = EqISets (ISet 0xFF) (SetOfI Iv.whole)
emptyEqISets :: EqISets
emptyEqISets = EqISets (ISet 0x00) (SetOfI Iv.empty)
unionEqISets :: EqISets -> EqISets -> EqISets
unionEqISets = binOpEqISets (.|.) (Iv.union)
intersectEqISets :: EqISets -> EqISets -> EqISets
intersectEqISets = binOpEqISets (.&.) (Iv.intersect)
deleteEqISets :: EqISets -> EqISets -> EqISets
deleteEqISets = binOpEqISets (\a b -> xor a (a .&. b)) (Iv.delete)
xorEqISets :: EqISets -> EqISets -> EqISets
xorEqISets = binOpEqISets (\a b -> xor a b) (Iv.exclusive)
invertEqISets :: EqISets -> EqISets
invertEqISets (EqISets (ISet is) (SetOfI soi)) =
EqISets (ISet $ xor is 0xFF) (SetOfI $ Iv.invert soi)
-- | check 'every_EqISets', make sure all generated tests are internally consistent, that is every
-- 'ISet' generated is indeed equivalent to every 'SetOfI's generated, and that the 'checkEqISets'
-- function can verify that this is true.
testSuite_everyEqISets :: TestSuite EqISets EqISets
testSuite_everyEqISets =
TestSuite
{ testSuiteParams =
TestParams
{ timeLimit = 0
, testLabel = Strict.pack "every ISet should have an equivalent SetOfI's"
, testRunner = return
, testCheck = checkEqISets
, testVerbose = Nothing
}
, testSuiteInputs = every_EqISets
, testSuiteRunner = testAll
, testSuiteVerbose = Nothing
, testSuiteShowFailed = Strict.pack . show
}
-- | Runs the 'testParam_everyEqISets' test parameters with 'every_EqISets' as input.
test_EqISets :: IO Bool
test_EqISets = testSingleThread testSuite_everyEqISets
-- | There are 256 possible 'ISet's and 256 possible equivalient 'SetOfI's.
every_EqISets :: [EqISets]
every_EqISets = uncurry EqISets <$> zip everyISet everySetOfI
isetFromPair :: I -> I -> ISet
isetFromPair lo hi = ISet $ foldl (.|.) 0 $ fmap i2byte $ range (lo, hi)
eqISetsFromPair :: I -> I -> EqISets
eqISetsFromPair lo hi = let p = (lo, hi) in
EqISets (isetFromPair lo hi) (SetOfI $ Iv.fromPairs [p])
-- | This function generates every possible 'EqISets' where the 'SetOfI' can be constructed from a
-- single 'Dao.Interval.Interval'. These test cases are simpler and easier to check, and should be
-- checked first to weed out any obvious failures.
every_SetFromPair :: [EqISets]
every_SetFromPair = everyI >>= \hi -> [toEnum 0 .. hi] >>= \lo -> [eqISetsFromPair lo hi]
-- | This test basically checks that 'EqISets' and 'checkEqISets' are functioning appropriately.
-- It should be run first.
params_everySetFromPair :: TestParams EqISets EqISets
params_everySetFromPair =
TestParams
{ timeLimit = tenSeconds
, testLabel = Strict.pack "pre-test"
, testRunner = return
, testCheck = checkEqISets
, testVerbose = Just $ \ _ -> return ()
}
-- | This is the list of every 'EqISet' and it's inverse that is constructed without using
-- 'Dao.Interval.invert', so the 'Dao.Interval.invert' can be tested, as well as other functions,
-- like union and intersection, which should behave predictably when unionining or intersecting
-- disjoint sets. This list only contains 84 elements, so it is great to run tests on these elements
-- first. The purpose of this list of elements is to test if unioning consecutive elements always
-- results in a 'Dao.Interval.Set' with only one 'Dao.Interval.Interval'. This is checked by
-- evaluating 'Dao.Interval.union', calling the 'Dao.Interval.toList', and checking if there is only
-- one element.
every_ConsecutiveISets :: [(EqISets, EqISets)]
every_ConsecutiveISets = do
mid <- take 7 everyI
lo <- [toEnum 0 .. mid]
hi <- [succ mid .. toEnum 7]
[(eqISetsFromPair lo mid, eqISetsFromPair (succ mid) hi)]
testSuite_ConsecutiveISets :: TestSuite (EqISets, EqISets) EqISets
testSuite_ConsecutiveISets =
TestSuite
{ testSuiteParams =
TestParams
{ timeLimit = tenSeconds
, testLabel = Strict.pack $ unwords $
[ "two sets consisting single consecutive intervals should union"
, "to a set consisting of a single consecutive interval"
]
, testRunner = return . uncurry unionEqISets
, testCheck = \ o@(EqISets _ (SetOfI s)) ->
checkEqISets o && (case Iv.toList s of { [_] -> True; _ -> False; })
, testVerbose = Nothing
}
, testSuiteInputs = every_ConsecutiveISets
, testSuiteRunner = testAll
, testSuiteVerbose = Nothing
, testSuiteShowFailed = Strict.pack . show
}
test_ConsecutiveISets :: IO Bool
test_ConsecutiveISets = testSingleThread testSuite_ConsecutiveISets
-- | This is the list of ever 'EqISet' that has an interval starting with @'I' 0@ and is paired with
-- it's inverse. This list contains only 7 elements which can be listed here (using 'ISet's
-- notaion):
-- > [ (_______0, 7654321_)
-- > , (______10, 765432__)
-- > , (_____210, 76543___)
-- > , (____3210, 7654____)
-- > , (___43210, 765_____)
-- > , (__543210, 76______)
-- > , (_6543210, 7_______) ]
-- This list of elements is good for testing properties set operations that operate on sets which
-- are inverses of each other.
every_SplitWholeSet :: [(EqISets, EqISets)]
every_SplitWholeSet =
take 7 everyI >>= \i ->
[ ( EqISets
(isetFromPair (I 0) i)
(SetOfI $ Iv.fromList [Iv.negInfTo i])
, EqISets
(isetFromPair (succ i) (I 7))
(SetOfI $ Iv.fromList [Iv.toPosInf $ succ i])
) ]
-- | Constructs a test suite that can operate on 'every_SplitWholeSet'.
testSuite_everySplitWholeSet
:: Show output
=> String -> (EqISets -> EqISets -> output) -> (output -> Bool) -> TestSuite (EqISets, EqISets) output
testSuite_everySplitWholeSet msg f check =
TestSuite
{ testSuiteParams =
TestParams
{ timeLimit = tenSeconds
, testLabel = Strict.pack msg
, testRunner = return . uncurry f
, testCheck = check
, testVerbose = Just $ \ _ -> return ()
}
, testSuiteInputs = every_SplitWholeSet
, testSuiteRunner = testAll
, testSuiteVerbose = Nothing
, testSuiteShowFailed = Strict.pack . show
}
-- | This is very simple tests that can be run right from the beginning to weed out the most
-- obvious mistakes. It will test the
testSuite_union_intersect_SplitWholeSet :: [TestSuite (EqISets, EqISets) EqISets]
testSuite_union_intersect_SplitWholeSet = let o = testSuite_everySplitWholeSet in
[ o "union of split whole sets should be the infinite set" unionEqISets (==wholeEqISets)
, o "intersection of split whole should be the empty set" intersectEqISets (==emptyEqISets)
]
-- | This is very simple tests that can be run right from the beginning to weed out the most
-- obvious mistakes.
testSuite_delete_invert_SplitWholeSet :: [TestSuite (EqISets, EqISets) (EqISets, EqISets)]
testSuite_delete_invert_SplitWholeSet = let o = testSuite_everySplitWholeSet in
[ o "deletion of left split whole sets with right whole set should equal the left whole set"
(\a b -> (deleteEqISets a b, a)) (uncurry (==))
, o "inversion of left whole set should equal the right whole set"
(\a b -> (invertEqISets a, b)) (uncurry (==))
]
-- | Runs 'testSuite_union_intersect_everySplitWholeSet' and
-- 'testSuite_delete_invert_everySplitWholeSet'.
test_SplitWholeSet :: IO Bool
test_SplitWholeSet = fmap (and . concat) $ sequence $
[ mapM testSingleThread testSuite_union_intersect_SplitWholeSet
, mapM testSingleThread testSuite_delete_invert_SplitWholeSet
]
-- | This is the set of all possible pairs of 'EqISets'. Since there are 256 possible 'EqISets',
-- there are @256^2 == 65536@ pairs in the power set.
powerSet_EqISets :: [(EqISets, EqISets)]
powerSet_EqISets = (,) <$> every_EqISets <*> every_EqISets
testSuite_binaryOperations :: Char -> (EqISets -> EqISets -> EqISets) -> [TestSuite (EqISets, EqISets) EqISets]
testSuite_binaryOperations c op =
(\ (lbl, op) ->
TestSuite
{ testSuiteParams =
TestParams
{ timeLimit = tenSeconds
, testLabel = Strict.pack $
"testing ("++lbl++") for the power set (A x B) of all possible interval sets"
, testRunner = return . uncurry op
, testCheck = checkEqISets
, testVerbose = Nothing
}
, testSuiteInputs = powerSet_EqISets
, testSuiteRunner = testUntilFail
, testSuiteVerbose = Nothing
, testSuiteShowFailed = Strict.pack . show
}
) <$>
[ ("A "++c:" B" , \a b -> op a b)
, ("A "++c:" !B", \a b -> op (invertEqISets a) b)
, ("!A "++c:" B", \a b -> op a (invertEqISets b))
]
testSuite_unionOperations :: [TestSuite (EqISets, EqISets) EqISets]
testSuite_unionOperations = testSuite_binaryOperations '|' unionEqISets
testSuite_intersectionOperations :: [TestSuite (EqISets, EqISets) EqISets]
testSuite_intersectionOperations = testSuite_binaryOperations '&' intersectEqISets
testSuite_deletionOperations :: [TestSuite (EqISets, EqISets) EqISets]
testSuite_deletionOperations = testSuite_binaryOperations '-' deleteEqISets
testSuite_xorOperations :: [TestSuite (EqISets, EqISets) EqISets]
testSuite_xorOperations = testSuite_binaryOperations '^' xorEqISets
test_allBinarySetOperations :: IO Bool
test_allBinarySetOperations = testMultiThread $ concat $
[ testSuite_unionOperations , testSuite_intersectionOperations
, testSuite_deletionOperations, testSuite_xorOperations
]
runTests :: IO Bool
runTests = let and_then a b = a >>= \ok -> if ok then b else return False in
test_EqISets `and_then` test_ConsecutiveISets `and_then` test_SplitWholeSet `and_then`
test_allBinarySetOperations
| RaminHAL9001/inf-interval | tests/Interval.hs | gpl-3.0 | 16,400 | 0 | 15 | 3,225 | 4,208 | 2,270 | 1,938 | 237 | 2 |
-- Copyright John F. Miller 2013-2017
{-# LANGUAGE OverloadedStrings, NamedFieldPuns #-}
module Builtin.Class (classObject, classInit) where
import Data.Maybe
import Object
import Object.Runtime
import Scope (Scope(..),v,o, VariableContext( Local ), Value (..))
import Name
import Err
import Var
import Data.Map.Strict (empty, fromList)
import Control.Monad.State (get, put, modify)
classObject :: PID -> State
classObject objPid = Class {
ivars = empty
, instanceOfClass = undefined
, globalNamespace = objPid
, localNamespace = objPid
, localCache = empty
, superClass = objPid
, methods = bootstrap
, methodCache = empty
, modules = []
, uid = undefined
}
classInit :: Runtime()
classInit = do
Pointer slf <- self
uid <- nextUID
modify (\st->st{instanceOfClass = slf, uid=uid})
bootstrap :: Namespace Fn
bootstrap = fromList [
("new" , Fn new)
, ("spawn" , Fn spawnFn)
]
new vals = do
obj <- newObject
setVar Local "obj" obj
val <- readVar Local "obj"
call val "initialize" vals
fromJust <$> readVar Local "obj" >>= reply . o
spawnFn args = do
obj <- newObject
pid <- spawn obj
send pid "initialize" args Nothing
reply $ Process pid
-- todo write new and spawn for Class itself
newObject :: Scope m => m Object
newObject = do
st <- get
Pointer slf <- self
uid <- nextUID
return $ Object $ Instance {
ivars = empty
, instanceOfClass = slf
, globalNamespace = globalNamespace st
, localNamespace = localNamespace st
, localCache = empty
, primitive = Nothing
, uid = uid
}
{-
to_s [] = do
(VObject Class{properName = s}) <- eval (EVar Self)
replyM_ $ VString $ mkStringLiteral $ s
includeFn:: [Value] -> EvalM()
includeFn mdls = do
val <- eval (EVar Self)
case val of
VObject obj@Class{} -> do
obj' <- loop obj mdls
modifySelf $ const obj'
replyM_ VNil
_ -> throwError $ Err "SystemError" "Tried to include a module in on Objcet that was not a local class" [val]
where
loop obj [] = return obj
loop obj (x:xs) = do
o <- valToObj x
loop (obj{cmodules = (o:(cmodules obj))}) xs
cmodulesFn :: [Value] -> EvalM()
cmodulesFn _ = do
slf <- gets self
replyM_ $ VArray $ fromList $ map VObject $ cmodules slf
instanceMethodsFn :: [Value] -> EvalM()
instanceMethodsFn _ = do -- TODO: for true values move through inheritance chain
slf <- gets self
replyM_ $ VArray $ fromList $ map VAtom $ M.keys $ cvars slf
-}
| antarestrader/sapphire | Builtin/Class.hs | gpl-3.0 | 2,523 | 0 | 11 | 618 | 503 | 278 | 225 | 56 | 1 |
module FragmentParserSpec (spec) where
import Test.Hspec
import Language.Mulang
import Language.Mulang.Analyzer.Analysis hiding (spec)
import Language.Mulang.Analyzer.FragmentParser
import Language.Mulang.Transform.Normalizer
spec :: Spec
spec = do
it "parses well formed expressions" $ do
let fragment = CodeSample Haskell "x = 1"
parseFragment Nothing fragment `shouldBe` Right (Variable "x" (MuNumber 1.0))
it "parses well formed expressions with normalization options" $ do
let convert = Just (unnormalized { convertObjectVariableIntoObject = True })
let keep = Just (unnormalized { convertObjectVariableIntoObject = False })
let asDict = Just (unnormalized { convertObjectIntoDict = True })
let fragment = CodeSample JavaScript "let x = {}"
parseFragment convert fragment `shouldBe` (Right (Object "x" None))
parseFragment keep fragment `shouldBe` (Right (Variable "x" (MuObject None)))
parseFragment asDict fragment `shouldBe` (Right (Variable "x" (MuDict None)))
parseFragment Nothing fragment `shouldBe` (Right (Variable "x" (MuObject None)))
it "parses malformed Haskell expressions" $ do
let fragment = CodeSample Haskell "x 1"
parseFragment Nothing fragment `shouldBe` Left "Parse error"
it "parses malformed Java expressions" $ do
let fragment = CodeSample Java "class Foo { void foo( {} }"
parseFragment Nothing fragment `shouldBe` Left "(line 1, column 25):\nunexpected OpenCurly\nexpecting refType"
it "parses malformed JavaScript expressions" $ do
let fragment = CodeSample Prolog "foo () :- 4 > 5."
parseFragment Nothing fragment `shouldBe` Left "(line 1, column 5):\nunexpected \"(\"\nexpecting space or \":-\""
| mumuki/mulang | spec/FragmentParserSpec.hs | gpl-3.0 | 1,774 | 0 | 16 | 356 | 457 | 227 | 230 | 29 | 1 |
module P25PwStrength where
import Data.Char
main :: IO ()
main = do
putStr "Enter password: "
p <- getLine
case passwordStrength p of
VeryWeak -> putStrLn $ "'" ++ p ++ "' is a very weak password. Loser"
Weak -> putStrLn $ "'" ++ p ++ "' is a weak password. Lame"
Average -> putStrLn $ "'" ++ p ++ "' is an average password. Try harder"
Strong -> putStrLn $ "'" ++ p ++ "' is a strong password. Nice"
VeryStrong -> putStrLn $ "'" ++ p ++ "' is a very strong password. You are scary"
-- because 8 is going to need to change
strongPasswordMinLength :: Int
strongPasswordMinLength = 8
data PasswordStrength = VeryWeak | Weak | Average | Strong | VeryStrong deriving (Show, Ord, Eq)
passwordStrength :: String -> PasswordStrength
passwordStrength ps | length ps >= l && manyLetters ps && manyNumbers ps && manySpecials ps
= VeryStrong
| length ps >= l && hasNumbers ps && manyLetters ps
= Strong
| length ps < l && allLetters ps
= Weak
| length ps < l && allNumbers ps
= VeryWeak
| otherwise
= Average
where
l = strongPasswordMinLength
hasLetters, hasNumbers, hasSpecials, allLetters, allNumbers,
manyLetters, manyNumbers, manySpecials :: String -> Bool
hasLetters = any isLetter
manyLetters = many isLetter
allLetters = all isLetter
hasNumbers = any isNumber
manyNumbers = many isNumber
allNumbers = all isNumber
hasSpecials = any (\x -> isPunctuation x || isSymbol x)
manySpecials = many (\x -> isPunctuation x || isSymbol x)
many :: (a -> Bool) -> [a] -> Bool
many f = (1<) . length . filter f
| ciderpunx/57-exercises-for-programmers | src/P25PwStrength.hs | gpl-3.0 | 1,776 | 0 | 12 | 550 | 494 | 253 | 241 | 39 | 5 |
{-# LANGUAGE DisambiguateRecordFields, TypeFamilies, OverloadedStrings,
StandaloneDeriving, DeriveFunctor, DeriveFoldable, GeneralizedNewtypeDeriving #-}
-------------------------------------------------------------------------------------
-- |
-- Copyright : (c) Hans Hoglund 2012
-- License : BSD-style
-- Maintainer : hans@hanshoglund.se
-- Stability : experimental
-- Portability : GHC
--
-- Parser for the module language, as described in "Language.Modulo".
--
-------------------------------------------------------------------------------------
module Language.Modulo.Parse (
parse,
parseName,
parsePrimType,
parsePrimTypeMaybe,
unsafeParseFile
) where
import Control.Monad
import Control.Arrow
import Data.Monoid
import Data.Default
import Data.Maybe
import qualified Data.List as List
import Control.Applicative hiding ((<|>), optional, many)
import Text.Parsec hiding (parse)
import Text.Parsec.Token
import Text.Parsec.String
import Language.Modulo
import Language.Modulo.Util
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty
-- |
-- Parse a module description, returning an error if unsuccessful.
--
parse :: String -> Either ParseError Module
parse = runParser modParser () ""
-- |
-- Parse a qualified name, returning an error if unsuccessful.
--
parseName :: String -> Either ParseError Name
parseName = runParser nameParser () ""
-- |
-- Parse a primitive type, returning an error if unsuccessful.
--
parsePrimType :: String -> Either ParseError PrimType
parsePrimType = fmap unPrimType . runParser primTypeParser () ""
where
unPrimType (PrimType x) = x
-- |
-- Parse a primitive type, returning an error if unsuccessful.
--
parsePrimTypeMaybe :: String -> Maybe PrimType
parsePrimTypeMaybe = eitherToMaybe . parsePrimType
-- |
-- Parse a module description from the given file, or fail if unsuccessful.
--
-- This unsafe function should not be used in production code.
--
unsafeParseFile :: FilePath -> IO Module
unsafeParseFile path = do
str <- readFile path
case (runParser modParser () path str) of
Left e -> error . show $ e
Right m -> return m
-------------------------------------------------------------------------------------
-- Parser
-------------------------------------------------------------------------------------
modParser :: Parser Module
modParser = do
optional lspace
doc <- fmap (Doc . fromMaybe "") $ optionMaybe docComment
optional lspace
reserved lexer "module"
optStr <- optionMaybe lstr
name <- modNameParser
llex $ char '{'
imps <- many impParser
docDecls <- many docDeclParser
llex $ char '}'
-- TODO use opts
let opt = def {
optTransient = List.isInfixOf "transient" (fromMaybe "" optStr)
}
return $ Module name opt doc imps docDecls
modNameParser :: Parser ModuleName
modNameParser = do
(x:xs) <- identifier lexer `sepBy1` (string ".")
return . ModuleName $ x :| xs
impParser :: Parser (ModuleName, Maybe String)
impParser = do
reserved lexer "import"
conv <- optionMaybe lstr
name <- modNameParser
semi lexer
return (name, conv)
docDeclParser :: Parser (Doc, Decl)
docDeclParser = do
doc <- fmap (Doc . fromMaybe "") $ optionMaybe docComment
optional lspace
decl <- declParser
return $ (doc, decl)
declParser :: Parser Decl
declParser = mzero
<|> typeDeclParser
<|> tagDeclParser
<|> funDeclParser
-- <|> constDeclParser
-- <|> globalDeclParser
typeDeclParser :: Parser Decl
typeDeclParser = do
reserved lexer "type"
name <- unameParser
llex $ char '='
typ <- typeOpaqueParser
semi lexer
return $ TypeDecl name typ
tagDeclParser :: Parser Decl
tagDeclParser = do
reserved lexer "tagname"
typ <- typeParser
semi lexer
return $ TagDecl typ
-- TODO rewrite in declarative style
funDeclParser :: Parser Decl
funDeclParser = do
(name, typ) <- unameTypeParser
semi lexer
case typ of
(FunType func) -> return $ FunctionDecl name func
_ -> unexpected "Expected function type"
constDeclParser :: Parser Decl
constDeclParser = notSupported "Constant parsing"
globalDeclParser :: Parser Decl
globalDeclParser = notSupported "Global parsing"
-------------------------------------------------------------------------------------
typeOpaqueParser :: Parser (Maybe Type)
typeOpaqueParser = (opaqueParser >> return Nothing) <|> fmap Just typeParser
opaqueParser :: Parser ()
opaqueParser = reserved lexer "opaque" >> return ()
-- To parse a type, we first parse all types whose syntax does not involve
-- post-qualifiers (i.e. pointer and function), then parse the modifiers to
-- generate a qualifier, and apply it to the prefix. I.e. in (a -> b) we first
-- parse a, then (-> b), and modify a by applying (-> b).
typeParser :: Parser Type
typeParser = do
typs <- typeStartParser
mods <- typeEndParser
return $ mods typs
typeStartParser :: Parser [(Maybe Name,Type)]
typeStartParser = mzero
<|> parenTypeParser
<|> (single.returnPair) <$> arrayTypeParser
<|> (single.returnPair) <$> enumTypeParser
<|> (single.returnPair) <$> unionTypeParser
<|> (single.returnPair) <$> structTypeParser
<|> (single.returnPair) <$> bitfieldTypeParser
<|> (single.returnPair) <$> primTypeParser
<|> (single.returnPair) <$> aliasTypeParser
returnPair x = (Nothing,x)
typeEndParser :: Parser ([(Maybe Name, Type)] -> Type)
typeEndParser = foldr comp noTypeEnd <$> many (ptr <|> func)
where
ptr = do
llex $ char '*'
return mkPtr
func = do
llex $ string "->"
typ <- typeParser
return $ mkFun typ
noTypeEnd :: [(Maybe Name, Type)] -> Type
noTypeEnd [(_,x)] = x
noTypeEnd _ = error "Unexpected argument head"
mkPtr :: [(Maybe Name, Type)] -> Type
mkPtr [(_,x)] = RefType . Pointer $ x
mkPtr _ = error "Unexpected argument head"
mkFun :: Type -> [(Maybe Name, Type)] -> Type
mkFun r as = FunType $ Function as r
-- TODO is this (=>=) in Control.Comonad ?
comp :: ([(Maybe x,a)] -> b) -> ([(Maybe x,b)] -> c) -> [(Maybe x,a)] -> c
comp g f = f . single . returnPair . g
-- This is not really a type, but the product used to express the argument to an uncurried function.
-- However, if it is just a one-tuple without a name, it will be treated as an ordinary type.
-- That is (A) -> B is the same as A -> B.
-- TODO support named arguments
parenTypeParser :: Parser [(Maybe Name, Type)]
parenTypeParser = do
llex $ char '('
types <- maybeNameTypeParser `sepBy` (llex $ char ',')
llex $ char ')'
return $ types
arrayTypeParser :: Parser Type
arrayTypeParser = do
llex $ char '['
typ <- typeParser
llex $ char 'x'
n <- lnat
llex $ char ']'
return $ RefType $ Array typ (fromInteger n)
enumTypeParser :: Parser Type
enumTypeParser = do
reserved lexer "enum"
llex $ char '{'
(n:ns) <- unameParser `sepBy` (llex $ char ',')
llex $ char '}'
return $ CompType $ Enum (n :| ns)
structTypeParser :: Parser Type
structTypeParser = do
reserved lexer "struct"
llex $ char '{'
(n:ns) <- unameTypeParser `sepBy1` (llex $ char ',')
llex $ char '}'
return $ CompType $ Struct (n :| ns)
unionTypeParser :: Parser Type
unionTypeParser = do
reserved lexer "union"
llex $ char '{'
(n:ns) <- unameTypeParser `sepBy1` (llex $ char ',')
llex $ char '}'
return $ CompType $ Union (n :| ns)
bitfieldTypeParser :: Parser Type
bitfieldTypeParser = do
reserved lexer "bitfield"
notSupported "Bitfield parsing"
primTypeParser :: Parser Type
primTypeParser = mzero
<|> "Int8" ==> Int8
<|> "Int16" ==> Int16
<|> "Int32" ==> Int32
<|> "Int64" ==> Int64
<|> "UInt8" ==> UInt8
<|> "UInt16" ==> UInt16
<|> "UInt32" ==> UInt32
<|> "UInt64" ==> UInt64
<|> "Bool" ==> Bool
<|> "Void" ==> Void
<|> "Size" ==> Size
<|> "Ptrdiff" ==> Ptrdiff
<|> "Intptr" ==> Intptr
<|> "UIntptr" ==> UIntptr
<|> "Char" ==> Char
<|> "Short" ==> Short
<|> "Int" ==> Int
<|> "Long" ==> Long
<|> "LongLong" ==> LongLong
<|> "UChar" ==> UChar
<|> "UShort" ==> UShort
<|> "UInt" ==> UInt
<|> "ULong" ==> ULong
<|> "ULongLong" ==> ULongLong
<|> "Float" ==> Float
<|> "Double" ==> Double
<|> "LongDouble" ==> LongDouble
where
s ==> t = lres s >> return (PrimType t)
aliasTypeParser :: Parser Type
aliasTypeParser = do
name <- nameParser
return $ AliasType name
docComment :: Parser String
docComment = do
string "/**"
manyTill anyChar (try (string "*/"))
-------------------------------------------------------------------------------------
nameParser :: Parser Name
nameParser = do
r <- identifier lexer `sepBy1` (string ".")
return $ case r of
[x] -> Name x
(x:xs) -> QName (ModuleName $ x :| init xs) (last xs)
unameParser :: Parser Name
unameParser = Name <$> lname
unameTypeParser :: Parser (Name, Type)
unameTypeParser = do
name <- unameParser
llex $ char ':'
typ <- typeParser
return $ (name, typ)
maybeNameTypeParser :: Parser (Maybe Name, Type)
maybeNameTypeParser = try (fmap (first Just) unameTypeParser) <|> fmap returnPair typeParser
-- Extra combinators, not exported
occs p = length <$> many p
follow p q = do
a <- p
b <- q
return (a, b)
-- spaceBefore p = optional lspace >> p
-- spaceAfter p = p >> optional lspace
-- spaceAround p = spaceBefore (spaceAfter p)
-------------------------------------------------------------------------------------
-- Lexer
-------------------------------------------------------------------------------------
lexer :: TokenParser ()
lexer = makeTokenParser $ LanguageDef {
commentStart = "/*!",
commentEnd = "*/",
commentLine = "//",
nestedComments = True,
identStart = (letter <|> char '_'),
identLetter = (alphaNum <|> char '_'),
opStart = mzero,
opLetter = mzero,
reservedNames = reservedNames,
reservedOpNames = mzero,
caseSensitive = True
}
where
reservedNames = [
"module", "import", "type", "tagname", "opaque", "enum", "union", "struct", "bitfield",
"Int", "Void", "Size", "Ptrdiff", "Intptr", "UIntptr",
"Char", "Short", "Int", "Long", "LongLong",
"UChar", "UShort", "UInt", "ULong", "ULongLong",
"Float", "Double", "LongDouble",
"Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16", "UInt32", "UInt64" ]
-- Convenient synonyms, not exported
llex = lexeme lexer
lnat = natural lexer
lstr = stringLiteral lexer
lname = identifier lexer
lres = reserved lexer
lspace = whiteSpace lexer
single x = [x]
notSupported x = error $ "Not supported yet: " ++ x
eitherToMaybe (Right x) = Just x
eitherToMaybe (Left _) = Nothing
| hanshoglund/modulo | src/Language/Modulo/Parse.hs | gpl-3.0 | 11,393 | 0 | 58 | 2,828 | 2,952 | 1,525 | 1,427 | 266 | 3 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Sleep (
threadDelayMicroseconds
) where
import Data.Word
threadDelayMicroseconds :: Word32 -> IO ()
threadDelayMicroseconds = c_chThdSleepMilliseconds
foreign import ccall "c_extern.h chThdSleepMilliseconds" c_chThdSleepMilliseconds :: Word32 -> IO ()
| metasepi/chibios-arafura | demos/ARMCM4-STM32F303-DISCOVERY_hs/hs_src/Sleep.hs | gpl-3.0 | 307 | 0 | 8 | 38 | 55 | 31 | 24 | 7 | 1 |
module Foundation where
import Database.Persist.MongoDB hiding (master)
import Import.NoFoundation
import Text.Hamlet (hamletFile)
import Text.Jasmine (minifym)
-- Used only when in "auth-dummy-login" setting is enabled.
import Yesod.Auth.Dummy
import Yesod.Auth.OpenId (authOpenId, IdentifierType (Claimed))
import Yesod.Core.Types (Logger)
import Yesod.Default.Util (addStaticContentExternal)
import qualified Yesod.Core.Unsafe as Unsafe
--import qualified Data.CaseInsensitive as CI
--import qualified Data.Text.Encoding as TE
-- | The foundation datatype for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ appSettings :: AppSettings
, appStatic :: Static -- ^ Settings for static file serving.
, appConnPool :: ConnectionPool -- ^ Database connection pool.
, appHttpManager :: Manager
, appLogger :: Logger
}
data MenuItem = MenuItem
{ menuItemLabel :: Text
, menuItemRoute :: Route App
, menuItemAccessCallback :: Bool
}
data MenuTypes
= NavbarLeft MenuItem
| NavbarRight MenuItem
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- Note that this is really half the story; in Application.hs, mkYesodDispatch
-- generates the rest of the code. Please see the following documentation
-- for an explanation for this split:
-- http://www.yesodweb.com/book/scaffolding-and-the-site-template#scaffolding-and-the-site-template_foundation_and_application_modules
--
-- This function also generates the following type synonyms:
-- type Handler = HandlerT App IO
-- type Widget = WidgetT App IO ()
mkYesodData "App" $(parseRoutesFile "config/routes")
-- | A convenient synonym for creating forms.
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
-- Controls the base of generated URLs. For more information on modifying,
-- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot
approot = ApprootRequest $ \app req ->
case appRoot $ appSettings app of
Nothing -> getApprootText guessApproot app req
Just root -> root
isAuthorized _ False = return Authorized
isAuthorized UsersR _ = checkAuth
isAuthorized (UserR _) _ = checkAuth
isAuthorized (UserAvatarR _) _ = checkAuth
isAuthorized (UserDrawingR _) _ = checkAuth
isAuthorized CategoriesR _ = checkAuth
isAuthorized (CategoryR _) _ = checkAuth
isAuthorized _ _ = return Authorized
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = Just <$> defaultClientSessionBackend
120 -- timeout in minutes
"config/client_session_key.aes"
-- Yesod Middleware allows you to run code before and after each handler function.
-- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks.
-- Some users may also want to add the defaultCsrfMiddleware, which:
-- a) Sets a cookie with a CSRF token in it.
-- b) Validates that incoming write requests include that token in either a header or POST parameter.
-- To add it, chain it together with the defaultMiddleware: yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware
-- For details, see the CSRF documentation in the Yesod.Core.Handler module of the yesod-core package.
yesodMiddleware = defaultYesodMiddleware
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- muser <- maybeAuthPair
mcurrentRoute <- getCurrentRoute
-- Get the breadcrumbs, as defined in the YesodBreadcrumbs instance.
(title, parents) <- breadcrumbs
-- Define the menu items of the header.
let menuItems =
[ NavbarLeft $ MenuItem
{ menuItemLabel = "Home"
, menuItemRoute = HomeR
, menuItemAccessCallback = True
}
]
let navbarLeftMenuItems = [x | NavbarLeft x <- menuItems]
let navbarRightMenuItems = [x | NavbarRight x <- menuItems]
let navbarLeftFilteredMenuItems = [x | x <- navbarLeftMenuItems, menuItemAccessCallback x]
let navbarRightFilteredMenuItems = [x | x <- navbarRightMenuItems, menuItemAccessCallback x]
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
-- pc <- ...
_ <- widgetToPageContent $ do
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- The page to be redirected to when authentication is required.
--authRoute _ = Just $ AuthR LoginR
-- Routes not requiring authentication.
--isAuthorized (StaticR _) _ = return Authorized
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent ext mime content = do
master <- getYesod
let staticDir = appStaticDir $ appSettings master
addStaticContentExternal
minifym
genFileName
staticDir
(StaticR . flip StaticRoute [])
ext
mime
content
where
-- Generate a unique filename based on the content itself
genFileName lbs = "autogen-" ++ base64md5 lbs
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog app _source level =
appShouldLogAll (appSettings app)
|| level == LevelWarn
|| level == LevelError
makeLogger = return . appLogger
checkAuth :: (MonadHandler m) => m AuthResult
checkAuth = do
auth <- lookupBearerAuth
case auth of
Nothing -> return AuthenticationRequired
Just auth' -> do
let token = decrypt "canx_secret_key" auth'
case token of
Nothing -> return $ Unauthorized "Invalid token"
Just _ -> return Authorized
-- Define breadcrumbs.
instance YesodBreadcrumbs App where
breadcrumb HomeR = return ("Home", Nothing)
breadcrumb _ = return ("home", Nothing)
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = MongoContext
runDB action = do
master <- getYesod
runMongoDBPool
(mgAccessMode $ appDatabaseConf $ appSettings master)
action
(appConnPool master)
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = AuthR
-- Where to send a user after logout
logoutDest _ = HomeR
-- Override the above two destinations when a Referer: header is present
redirectToReferer _ = True
authenticate creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Authenticated uid
Nothing -> Authenticated <$> insert User
{ userIdent = credsIdent creds
, userPassword = Nothing
, userEmail = Nothing
, userName = Nothing
, userAvatar = Nothing
}
-- You can add other plugins like Google Email, email or OAuth here
authPlugins app = [authOpenId Claimed []] ++ extraAuthPlugins
-- Enable authDummy login if enabled.
where extraAuthPlugins = [authDummy | appAuthDummyLogin $ appSettings app]
authHttpManager = getHttpManager
-- | Access function to determine if a user is logged in.
isAuthenticated :: Handler AuthResult
isAuthenticated = do
muid <- maybeAuthId
return $ case muid of
Nothing -> Unauthorized "You must login to access this page"
Just _ -> Authorized
instance YesodAuthPersist App
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- Useful when writing code that is re-usable outside of the Handler context.
-- An example is background jobs that send email.
-- This can also be useful for writing code that works across multiple Yesod applications.
instance HasHttpManager App where
getHttpManager = appHttpManager
unsafeHandler :: App -> Handler a -> IO a
unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
-- Note: Some functionality previously present in the scaffolding has been
-- moved to documentation in the Wiki. Following are some hopefully helpful
-- links:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
-- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain
-- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding
| uros-stegic/canx | server/canx-server/Foundation.hs | gpl-3.0 | 9,904 | 1 | 16 | 2,493 | 1,364 | 733 | 631 | -1 | -1 |
module Application.Caffe.ArgsParser where
import Data.List as L
import Data.Maybe
import PetaVision.Data.Pooling
import System.Console.GetOpt
import Text.Parsec
import Text.Parsec.String
import Text.Read
data Flag
= PVPFile String
| LabelFile String
| Thread Int
| C Double
| ModelName String
| FindC
| Pool
| PoolingType String
| BatchSize Int
| PoolingSize [Int]
| TimeStampFile FilePath
| ConcatFlag
| FolderName String
| PadLength Int
deriving (Show)
data Params = Params
{ pvpFile :: [[String]] -- The inner-list is pvpFiles with the same stride
, labelFile :: String
, c :: Double
, numThread :: Int
, modelName :: String
, findC :: Bool
, poolingFlag :: Bool
, poolingType :: PoolingType
, batchSize :: Int
, poolingSize :: [Int]
, timeStampFile :: FilePath
, concatFlag :: Bool
, folderName :: String
, padLength :: Int
} deriving (Show)
options :: [OptDescr Flag]
options =
[ Option
['i']
["pvpfile"]
(ReqArg PVPFile "FILE")
"PVPFile (For concatenation, -i \"file1_batch1 file1_batch2\" ... -i \"file2_batch1 file2_batch2\" ...) colon is necessary."
, Option
['l']
["Label"]
(ReqArg LabelFile "FILE")
"Input either pvp or txt label file"
, Option
['c']
["constrainC"]
(ReqArg (C . readDouble) "Double")
"Set the liblinear parameter c (Default 1)"
, Option
['t']
["thread"]
(ReqArg (Thread . readInt) "INT")
"Set the number of threads as x (\"+RTS -Nx\" should be added at the end of the command)"
, Option
['C']
["findC"]
(NoArg FindC)
"Find parameter C. You may want to specify the initial c value using -c. The default initial c value is 1. Set it to be -1 to let the problem to find a initial value for c"
, Option ['p'] ["poolingFlag"] (NoArg Pool) "Use pooling."
, Option
['P']
["poolingType"]
(ReqArg PoolingType "NAME")
"Set the poolingType. It is either Max or Avg."
, Option
['b']
["batchSize"]
(ReqArg (BatchSize . readInt) "INT")
"Set the batchSize."
, Option
['s']
["poolingSize"]
(ReqArg (PoolingSize . L.map readInt . splitStringbySpace) "INT")
"Set pooling size (Defaule 3)."
, Option ['m'] ["modelName"] (ReqArg ModelName "FILE") "SVM model name"
, Option
['z']
["timeStampFile"]
(ReqArg TimeStampFile "FILE")
"Time stamps file path."
, Option
['z']
["Concat"]
(NoArg ConcatFlag)
"Whether concatnating all layers' acts into one vector or not."
, Option
['z']
["FolderName"]
(ReqArg FolderName "String")
"Folder name for storing HDF5 files."
, Option
['z']
["PadLength"]
(ReqArg (PadLength . readInt) "INT")
"Set the length of padding area."
]
readInt :: String -> Int
readInt str =
fromMaybe
(error $ "\nRead integer error: " ++ str)
(readMaybe str :: Maybe Int)
readDouble :: String -> Double
readDouble str =
fromMaybe
(error $ "\nRead double error: " ++ str)
(readMaybe str :: Maybe Double)
compilerOpts :: [String] -> IO [Flag]
compilerOpts argv =
case getOpt Permute options argv of
(o, [], []) -> return o
(_, nonOpts, []) -> error $ "unrecognized arguments: " ++ unwords nonOpts
(_, _, errs) -> error (concat errs ++ usageInfo header options)
where
header = "Usage: ic [OPTION...] files..."
parseFlag :: [Flag] -> Params
parseFlag flags = go flags defaultFlag
where
defaultFlag =
Params
{ pvpFile = []
, labelFile = ""
, c = 1.0
, numThread = 1
, modelName = "model"
, findC = False
, poolingFlag = False
, poolingType = Avg
, batchSize = 1
, poolingSize = [3]
, timeStampFile = ""
, concatFlag = False
, folderName = ""
, padLength = 0
}
go [] params = params
go (x:xs) params =
case x of
PVPFile str ->
go xs (params {pvpFile = splitStringbySpace str : pvpFile params})
LabelFile str -> go xs (params {labelFile = str})
Thread n -> go xs (params {numThread = n})
C v -> go xs (params {c = v})
ModelName str -> go xs (params {modelName = str})
FindC -> go xs (params {findC = True})
Pool -> go xs (params {poolingFlag = True})
PoolingType str ->
go xs (params {poolingType = read str :: PoolingType})
BatchSize x' -> go xs (params {batchSize = x'})
PoolingSize n -> go xs (params {poolingSize = n})
TimeStampFile str -> go xs (params {timeStampFile = str})
ConcatFlag -> go xs (params {concatFlag = True})
FolderName str -> go xs (params {folderName = str})
PadLength x' -> go xs (params {padLength = x'})
parseArgs :: [String] -> IO Params
parseArgs args = do
flags <- compilerOpts args
return $ parseFlag flags
spaceParser :: Parser [String]
spaceParser = do
spaces
x <- many (noneOf [' '])
if null x
then return []
else do
xs <- spaceParser
return $! x : xs
splitStringbySpace :: String -> [String]
splitStringbySpace xs =
case parse spaceParser "" xs of
Left err -> error $ show err
Right ys -> ys
| XinhuaZhang/PetaVisionHaskell | Application/Caffe/ArgsParser.hs | gpl-3.0 | 5,419 | 0 | 15 | 1,646 | 1,557 | 852 | 705 | 176 | 15 |
module QuranSpec.QRefRng ( qRefRngSpec ) where
import Quran.Internal.QRefRng
import Quran.QRefRng
import Test.Hspec
qRefRngSpec :: Spec
qRefRngSpec = do
-- SPECS FOR INTERNAL
describe "chapterOffset" $ do
it "should sum up the verses of all chapters till 'c'" $
foldr (&&) True $ map (\(c, success) -> success == chapterOffset c) [
(0, 0)
, (1, 0)
, (2, 7)
, (3, 293)
]
describe "versesPerChapter" $ do
it "should contain 114 + 1 elements" $ length versesPerChapter == 114 + 1
it "expects the 9th chapter to have 129 verses" $ versesPerChapter !! 9 == 129
it "expects the 0th chapter to have 0 verses" $ versesPerChapter !! 0 == 0
it "expects the last chapter (114) to have 6 verses" $ versesPerChapter !! 114 == 6
it "expects the total of verses to be 6236" $ sum versesPerChapter == 6236
-- SPECS FOR PUBLIC
describe "qRefRng" $ do
it "should construct a QRefRng type when provided with valid input" $ pending
{- qRefRng 31 (6, 6) == qRefRng_ 31 (6, 6)-}
it "should fail when the chapter number is out of bounds" $ pending
it "should fail when the end verse is smaller then the start verse" $ pending
describe "qRefRngToLineNr" $ do
it "converts references to line numbers" $
-- refToLineNr (114, 6) == 6236
let refEqualsLineNr (r, lineNr) = qRefRngToLineNr r == lineNr
in foldr (&&) True $ map refEqualsLineNr $
[ (qRefRng_ 1 (1, 1), 1)
, (qRefRng_ 2 (1, 1), 8)
, (qRefRng_ 3 (1, 1), 294)
, (qRefRng_ 31 (6, 6), 3475)
, (qRefRng_ 114 (6, 6), 6236)
]
describe "qRefRngToLineNrs" $ do
it "converts a reference range to a list of line numbers" $
let refEqualsLineNrs (r, lineNr) = qRefRngToLineNrs r == lineNr
in foldr (&&) True $ map refEqualsLineNrs $
[ (qRefRng_ 1 (1, 1), [1])
, (qRefRng_ 2 (1, 2), [8, 9])
, (qRefRng_ 3 (1, 3), [294, 295, 296])
, (qRefRng_ 114 (1, 6), [6231..6236])
]
| oqc/hqt | QuranSpec/QRefRng.hs | gpl-3.0 | 2,126 | 0 | 17 | 662 | 609 | 322 | 287 | 40 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
-- Module : Network.AWS.EC2.Types
-- Copyright : (c) 2013 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Network.AWS.EC2.Types where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Monoid
import Data.Text (Text)
import Data.Text.Encoding
import Data.Time
import Network.AWS.Internal
import Text.Read
-- | Currently supported version (2013-07-15) of the EC2 service.
ec2 :: Service
ec2 = Service Regional version2 "ec2" "2013-08-15"
-- | XML namespace to annotate EC2 elements with.
ec2NS :: ByteString
ec2NS = "http://ec2.amazonaws.com/doc/" <> svcVersion ec2 <> "/"
-- | Helper to define EC2 namespaced XML elements.
ec2Elem :: ByteString -> NName ByteString
ec2Elem = mkNName ec2NS
ec2XML :: XMLGeneric a
ec2XML = withNS' ec2NS $ (namespacedXMLOptions ec2NS)
{ xmlFieldModifier = mkNName ec2NS . lowerHead . stripLower
, xmlListElement = mkNName ec2NS "item"
}
ec2ItemXML :: XMLGeneric a
ec2ItemXML = withRootNS' ec2NS "item" $ (namespacedXMLOptions ec2NS)
{ xmlFieldModifier = mkNName ec2NS . lowerHead . stripLower
, xmlListElement = mkNName ec2NS "item"
}
data EC2Error = EC2Error
{ ecCode :: !Text
, ecMessage :: !Text
} deriving (Eq, Ord, Show, Generic)
instance IsXML EC2Error where
xmlPickler = genericXMLPickler $ defaultXMLOptions
{ xmlCtorModifier = mkAnNName . stripPrefix "EC2"
}
instance IsXML [EC2Error] where
xmlPickler = xpElemList (mkAnNName "Error") xmlPickler
data EC2ErrorResponse = EC2ErrorResponse
{ eerErrors :: [EC2Error]
, eerRequestID :: !Text
} deriving (Eq, Ord, Show, Generic)
instance ToError EC2ErrorResponse where
toError = Err . show
instance IsXML EC2ErrorResponse
data Protocol = TCP | UDP | ICMP
deriving (Eq, Ord, Generic)
instance Show Protocol where
show TCP = "tcp"
show UDP = "udp"
show ICMP = "icmp"
instance Read Protocol where
readPrec = readAssocList
[ ("tcp", TCP)
, ("udp", UDP)
, ("icmp", ICMP)
]
instance IsQuery Protocol where
queryPickler = qpPrim
instance IsXML Protocol where
xmlPickler = xpContent xpPrim
data AddressDomain = AddressStandard | AddressVPC
deriving (Eq)
instance Show AddressDomain where
show AddressStandard = "standard"
show AddressVPC = "vpc"
instance Read AddressDomain where
readPrec = readAssocList
[ ("standard", AddressStandard)
, ("vpc", AddressVPC)
]
instance IsQuery AddressDomain where
queryPickler = qpPrim
instance IsXML AddressDomain where
xmlPickler = xpContent xpPrim
data VolumeStatus = Attaching | Attached | Detaching | Detached
deriving (Eq)
instance Show VolumeStatus where
show Attaching = "attaching"
show Attached = "attached"
show Detaching = "detaching"
show Detached = "detached"
instance Read VolumeStatus where
readPrec = readAssocList
[ ("attaching", Attaching)
, ("attached", Attached)
, ("detaching", Detaching)
, ("detached", Detached)
]
instance IsXML VolumeStatus where
xmlPickler = xpContent xpPrim
-- data AccountAttributeSetItemType = AccountAttributeSetItemType
-- { aasitAttributeName :: !Text
-- -- ^ The name of the attribute.
-- , aasitAttributeValueSet :: !AccountAttributeValueSetItemType
-- -- ^ A list of the attribute values, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery AccountAttributeSetItemType
-- instance IsXML AccountAttributeSetItemType where
-- xmlPickler = ec2XML
-- data AccountAttributeValueSetItemType = AccountAttributeValueSetItemType
-- { aavsitAttributeValue :: !Text
-- -- ^ The value of the attribute.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery AccountAttributeValueSetItemType
-- instance IsXML AccountAttributeValueSetItemType where
-- xmlPickler = ec2XML
-- data PrivateIpAddress = PrivateIpAddress
-- { piaPrivateIpAddress :: !Text
-- -- ^ The private IP address.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery AssignPrivateIpAddressesSetItemRequestType
-- instance IsXML AssignPrivateIpAddressesSetItemRequestType where
-- xmlPickler = ec2XML
-- data AttachmentSetItemResponseType = AttachmentSetItemResponseType
-- { asirtVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , asirtInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , asirtDevice :: !Text
-- -- ^ The device name exposed to the instance (for example, /dev/sdh).
-- , asirtStatus :: !Text
-- -- ^ The attachment state.
-- , asirtAttachTime :: !UTCTime
-- -- ^ The time stamp when the attachment initiated.
-- , asirtDeleteOnTermination :: !Bool
-- -- ^ Indicates whether the volume is deleted on instance termination.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery AttachmentSetItemResponseType
-- instance IsXML AttachmentSetItemResponseType where
-- xmlPickler = ec2XML
data Attachment = Attachment
{ atVpcId :: !Text
-- ^ The ID of the VPC.
, atState :: !Text
-- ^ The current state of the attachment.
} deriving (Eq, Ord, Show, Generic)
instance IsXML Attachment where
xmlPickler = ec2XML
data AvailabilityZoneItemType = AvailabilityZoneItemType
{ azitZoneName :: !AvailabilityZone
-- ^ The name of the Availability Zone.
, azitZoneState :: !Text
-- ^ The state of the Availability Zone.
-- FIXME: Should be - available | impaired | unavailable
, azitRegionName :: !Region
-- ^ The name of the region.
, azitMessageSet :: [AvailabilityZoneMessageType]
-- ^ Any messages about the Availability Zone.
} deriving (Eq, Ord, Show, Generic)
-- instance IsQuery AvailabilityZoneItemType
instance IsXML AvailabilityZoneItemType where
xmlPickler = ec2ItemXML
data AvailabilityZoneMessageType = AvailabilityZoneMessageType
{ azmtMessage :: !Text
-- ^ The message about the Availability Zone.
} deriving (Eq, Ord, Show, Generic)
-- instance IsQuery AvailabilityZoneMessageType
instance IsXML AvailabilityZoneMessageType where
xmlPickler = ec2ItemXML
data BlockDeviceMappingItemType = BlockDeviceMappingItemType
{ bdmitDeviceName :: !Text
-- ^ The device name exposed to the instance (for example, /dev/sdh).
, bdmitVirtualName :: Maybe Text
-- ^ The virtual device name.
, bdmitEbs :: Maybe EbsBlockDeviceType
-- ^ Parameters used to automatically set up Amazon EBS volumes when
-- the instance is launched.
, bdmitNoDevice :: Maybe Text
-- ^ Include this empty element to suppress the specified device
-- included in the block device mapping of the AMI.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery BlockDeviceMappingItemType
instance IsXML BlockDeviceMappingItemType where
xmlPickler = ec2ItemXML
data BundleInstanceS3Storage = BundleInstanceS3Storage
{ bissAwsAccessKeyId :: !Text
-- ^ The access key ID of the owner of the bucket.
, bissBucket :: !Text
-- ^ The bucket in which to store the AMI. You can specify a bucket
-- that you already own or a new bucket that Amazon EC2 creates on
-- your behalf. If you specify a bucket that belongs to someone
-- else, Amazon EC2 returns an error.
, bissPrefix :: !Text
-- ^ The beginning of the file name of the AMI.
, bissUploadPolicy :: !Text
-- ^ A Base64-encoded Amazon S3 upload policy that gives Amazon EC2
-- permission to upload items into Amazon S3 on the user's behalf.
, bissUploadPolicySignature :: !Text
-- ^ The signature of the Base64 encoded JSON document.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery BundleInstanceS3Storage
instance IsXML BundleInstanceS3Storage where
xmlPickler = ec2XML
data BundleInstanceTaskStorage = BundleInstanceTaskStorage
{ bitsS3 :: !BundleInstanceS3Storage
-- ^ An Amazon S3 storage location.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery BundleInstanceTaskStorage
instance IsXML BundleInstanceTaskStorage where
xmlPickler = ec2XML
data BundleInstanceTaskError = BundleInstanceTaskError
{ biteCode :: !Text
-- ^ The error code.
, biteMessage :: !Text
-- ^ The error message.
} deriving (Eq, Ord, Show, Generic)
instance IsXML BundleInstanceTaskError where
xmlPickler = ec2XML
data BundleInstanceState
= Pending
| WaitingForShutdown --waiting-for-shutdown
| Bundling
| Storing
| Cancelling
| Complete
| Failed
deriving (Eq, Ord)
instance Show BundleInstanceState where
show st = case st of
Pending -> "pending"
WaitingForShutdown -> "waiting-for-shutdown"
Bundling -> "bundling"
Storing -> "storing"
Cancelling -> "cancelling"
Complete -> "complete"
Failed -> "failed"
instance Read BundleInstanceState where
readPrec = readAssocList
[ ("pending", Pending)
, ("waiting-for-shutdown", WaitingForShutdown)
, ("bundling", Bundling)
, ("storing", Storing)
, ("cancelling", Cancelling)
, ("complete", Complete)
, ("failed", Failed)
]
instance IsXML BundleInstanceState where
xmlPickler = xpContent xpPrim
data BundleInstanceTask = BundleInstanceTask
{ bitInstanceId :: !Text
-- ^ The ID of the instance associated with this bundle task.
, bitBundleId :: !Text
-- ^ The ID for this bundle task.
, bitState :: !BundleInstanceState
-- ^ The state of the task.
, bitStartTime :: !UTCTime
-- ^ The time this task started.
, bitUpdateTime :: !UTCTime
-- ^ The time of the most recent update for the task.
, bitStorage :: !BundleInstanceTaskStorage
-- ^ The Amazon S3 storage locations.
, bitProgress :: !Text
-- ^ The level of task completion, as a percent (for example, 20%).
, bitError :: Maybe BundleInstanceTaskError
-- ^ If the task fails, a description of the error.
} deriving (Eq, Ord, Show, Generic)
instance IsXML BundleInstanceTask where
xmlPickler = ec2XML
data CancelSpotInstanceRequestsResponseSetItemType = CancelSpotInstanceRequestsResponseSetItemType
{ csirrsitSpotInstanceRequestId :: !Text
-- ^ The ID of the Spot Instance request.
, csirrsitState :: !Text
-- ^ The state of the Spot Instance request.
} deriving (Eq, Ord, Show, Generic)
instance IsXML CancelSpotInstanceRequestsResponseSetItemType where
xmlPickler = ec2XML
-- data ConversionTaskType = ConversionTaskType
-- { cttConversionTaskId :: !Text
-- -- ^ The ID of the conversion task
-- , cttExpirationTime :: !Text
-- -- ^ The time when the task expires. If the upload isn't complete
-- -- before the expiration time, we automatically cancel the task.
-- , cttImportVolume :: !ImportVolumeTaskDetailsType
-- -- ^ If the task is for importing a volume, this contains information
-- -- about the import volume task.
-- , cttImportInstance :: !ImportInstanceTaskDetailsType
-- -- ^ If the task is for importing an instance, this contains
-- -- information about the import instance task.
-- , cttState :: !Text
-- -- ^ The state of the conversion task.
-- , cttStatusMessage :: !Text
-- -- ^ The status message related to the conversion task.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ConversionTaskType
-- instance IsXML ConversionTaskType where
-- xmlPickler = ec2XML
-- data CreateVolumePermissionItemType = CreateVolumePermissionItemType
-- { cvpitUserId :: !Text
-- -- ^ The ID of an AWS account that can create volumes from the
-- -- snapshot.
-- , cvpitGroup :: !Text
-- -- ^ The group that is allowed to create volumes from the snapshot.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery CreateVolumePermissionItemType
-- instance IsXML CreateVolumePermissionItemType where
-- xmlPickler = ec2XML
-- data CustomerGatewayType = CustomerGatewayType
-- { cgtCustomerGatewayId :: !Text
-- -- ^ The ID of the customer gateway.
-- , cgtState :: !Text
-- -- ^ The current state of the customer gateway.
-- , cgtType :: !Text
-- -- ^ The type of VPN connection the customer gateway supports.
-- , cgtIpAddress :: !Text
-- -- ^ The Internet-routable IP address of the customer gateway's
-- -- outside interface.
-- , cgtBgpAsn :: !Integer
-- -- ^ The customer gateway's Border Gateway Protocol (BGP) Autonomous
-- -- System Number (ASN).
-- , cgtTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery CustomerGatewayType
-- instance IsXML CustomerGatewayType where
-- xmlPickler = ec2XML
-- data DescribeAddressesResponseItemType = DescribeAddressesResponseItemType
-- { daritPublicIp :: !Text
-- -- ^ The public IP address.
-- , daritAllocationId :: !Text
-- -- ^ The ID representing the allocation of the address for use with
-- -- EC2-VPC.
-- , daritDomain :: !Text
-- -- ^ Indicates whether this Elastic IP address is for instances in
-- -- EC2-Classic or EC2-VPC.
-- , daritInstanceId :: !Text
-- -- ^ The ID of the instance the address is associated with (if any).
-- , daritAssociationId :: !Text
-- -- ^ The ID representing the association of an Elastic IP address with
-- -- an instance in a VPC.
-- , daritNetworkInterfaceId :: !Text
-- -- ^ The ID of the network interface.
-- , daritNetworkInterfaceOwnerId :: !Text
-- -- ^ The ID of the AWS account that owns the network interface.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeAddressesResponseItemType
-- instance IsXML DescribeAddressesResponseItemType where
-- xmlPickler = ec2XML
data DescribeImagesResponseItemType = DescribeImagesResponseItemType
{ diritImageId :: !Text
-- ^ The ID of the AMI.
, diritImageLocation :: !Text
-- ^ The location of the AMI.
, diritImageState :: !Text
-- ^ Current state of the AMI. If the operation returns available, the
-- image is successfully registered and available for launching.
, diritImageOwnerId :: !Text
-- ^ AWS account ID of the image owner.
, diritIsPublic :: !Bool
-- ^ Indicates whether the image has public launch permissions. The
-- value is true if this image has public launch permissions or
-- false if it has only implicit and explicit launch permissions.
, diritProductCodes :: [ProductCodesSetItemType]
-- ^ Any product codes associated with the AMI.
, diritArchitecture :: !Text
-- ^ The architecture of the image.
, diritImageType :: !Text
-- ^ The type of image.
, diritKernelId :: Maybe Text
-- ^ The kernel associated with the image, if any.
-- Only applicable for machine images.
, diritRamdiskId :: Maybe Text
-- ^ The RAM disk associated with the image, if any.
-- Only applicable for machine images.
, diritPlatform :: Maybe Text
-- ^ The value is Windows for Windows AMIs; otherwise blank.
, diritStateReason :: Maybe StateReasonType
-- ^ The reason for the state change.
, diritImageOwnerAlias :: Maybe Text
-- ^ The AWS account alias (for example, amazon, self, etc.) or AWS
-- account ID that owns the AMI.
, diritName :: !Text
-- ^ The name of the AMI that was provided during image creation.
, diritDescription :: Maybe Text
-- ^ The description of the AMI that was provided during image creation.
, diritRootDeviceType :: !Text
-- ^ The type of root device used by the AMI. The AMI can use an
-- Amazon EBS volume or an instance store volume.
, diritRootDeviceName :: Maybe Text
-- ^ The device name of the root device (for example, /dev/sda1 or
-- xvda).
, diritBlockDeviceMapping :: [BlockDeviceMappingItemType]
-- ^ Any block device mapping entries.
, diritVirtualizationType :: !Text
-- ^ The type of virtualization of the AMI.
, diritTagSet :: [ResourceTagSetItemType]
-- ^ Any tags assigned to the resource.
, diritHypervisor :: !Text
-- ^ The image's hypervisor type.
} deriving (Eq, Ord, Show, Generic)
instance IsXML DescribeImagesResponseItemType where
xmlPickler = ec2ItemXML
data DescribeKeyPairsResponseItemType = DescribeKeyPairsResponseItemType
{ dkpritKeyName :: !Text
-- ^ The name of the key pair.
, dkpritKeyFingerprint :: !Text
-- ^ If you used CreateKeyPair to create the key pair, this is the
-- SHA-1 digest of the DER encoded private key. If you used
-- ImportKeyPair to provide AWS the public key, this is the MD5
-- public key fingerprint as specified in section 4 of RFC4716.
} deriving (Eq, Ord, Show, Generic)
instance IsXML DescribeKeyPairsResponseItemType where
xmlPickler = ec2ItemXML
data DescribeReservedInstancesListingsResponseSetItemType = DescribeReservedInstancesListingsResponseSetItemType
{ drilrsitReservedInstancesListingId :: !Text
-- ^ The ID of the Reserved Instance listing.
, drilrsitReservedInstancesId :: !Text
-- ^ The ID of the Reserved Instance.
, drilrsitCreateDate :: !UTCTime
-- ^ The time the listing was created.
, drilrsitUpdateDate :: !UTCTime
-- ^ The last modified timestamp of the listing.
, drilrsitStatus :: !Text
-- ^ The status of the Reserved Instance listing.
, drilrsitStatusMessage :: !Text
-- ^ The reason for the current status of the Reserved Instance
-- listing. The response can be blank.
, drilrsitInstanceCounts :: [InstanceCountsSetItemType]
-- ^ The number of instances in this state.
, drilrsitPriceSchedules :: [PriceScheduleSetItemType]
-- ^ The price of the Reserved Instance listing.
, drilrsitTagSet :: [ResourceTagSetItemType]
-- ^ The tags assigned to the resource. Each tag's information is
-- wrapped in an item element.
, drilrsitClientToken :: !Text
-- ^ The idempotency token you provided when you created the listing.
} deriving (Eq, Ord, Show, Generic)
instance IsXML DescribeReservedInstancesListingsResponseSetItemType where
xmlPickler = ec2ItemXML
-- data DescribeReservedInstancesListingSetItemType = DescribeReservedInstancesListingSetItemType
-- { drilsitReservedInstancesListingId :: !Text
-- -- ^ The ID of the Reserved Instance listing.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeReservedInstancesListingSetItemType
-- instance IsXML DescribeReservedInstancesListingSetItemType where
-- xmlPickler = ec2XML
-- data DescribeReservedInstancesOfferingsResponseSetItemType = DescribeReservedInstancesOfferingsResponseSetItemType
-- { driorsitReservedInstancesOfferingId :: !Text
-- -- ^ The ID of the Reserved Instance offering.
-- , driorsitInstanceType :: !Text
-- -- ^ The instance type on which the Reserved Instance can be used.
-- , driorsitAvailabilityZone :: !Text
-- -- ^ The Availability Zone in which the Reserved Instance can be used.
-- , driorsitDuration :: !Integer
-- -- ^ The duration of the Reserved Instance, in seconds.
-- , driorsitFixedPrice :: !Double
-- -- ^ The purchase price of the Reserved Instance.
-- , driorsitUsagePrice :: !Double
-- -- ^ The usage price of the Reserved Instance, per hour.
-- , driorsitProductDescription :: !Text
-- -- ^ The Reserved Instance description.
-- , driorsitInstanceTenancy :: !Text
-- -- ^ The tenancy of the reserved instance.
-- , driorsitCurrencyCode :: !Text
-- -- ^ The currency of the Reserved Instance offering you are
-- -- purchasing. It's specified using ISO 4217 standard currency
-- -- codes. At this time, the only supported currency is USD.
-- , driorsitOfferingType :: !Text
-- -- ^ The Reserved Instance offering type.
-- , driorsitRecurringCharges :: !RecurringChargesSetItemType
-- -- ^ The recurring charge tag assigned to the resource.
-- , driorsitMarketplace :: !Bool
-- -- ^ Indicates whether the offering is available through the Reserved
-- -- Instance Marketplace (resale) or AWS. Returns true if it is a
-- -- Marketplace offering.
-- , driorsitPricingDetailsSet :: !PricingDetailsSetItemType
-- -- ^ The pricing details of the Reserved Instance offering wrapped in
-- -- an item element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeReservedInstancesOfferingsResponseSetItemType
-- instance IsXML DescribeReservedInstancesOfferingsResponseSetItemType where
-- xmlPickler = ec2XML
-- data DescribeReservedInstancesOfferingsResponseType = DescribeReservedInstancesOfferingsResponseType
-- { driortRequestId :: !Text
-- -- ^ The ID of the Reserved Instance offering request.
-- , driortReservedInstancesOfferingsSet :: !DescribeReservedInstancesOfferingsResponseSetItemType
-- -- ^ The instance type on which the Reserved Instance can be used.
-- , driortNextToken :: !Text
-- -- ^ The next paginated set of results to return.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeReservedInstancesOfferingsResponseType
-- instance IsXML DescribeReservedInstancesOfferingsResponseType where
-- xmlPickler = ec2XML
-- data DescribeReservedInstancesResponseSetItemType = DescribeReservedInstancesResponseSetItemType
-- { drirsitReservedInstancesId :: !Text
-- -- ^ The ID of the Reserved Instance.
-- , drirsitInstanceType :: !Text
-- -- ^ The instance type on which the Reserved Instance can be used.
-- , drirsitAvailabilityZone :: !Text
-- -- ^ The Availability Zone in which the Reserved Instance can be used.
-- , drirsitStart :: !UTCTime
-- -- ^ The date and time the Reserved Instance started.
-- , drirsitDuration :: !Integer
-- -- ^ The duration of the Reserved Instance, in seconds.
-- , drirsitFixedPrice :: !Double
-- -- ^ The purchase price of the Reserved Instance.
-- , drirsitUsagePrice :: !Double
-- -- ^ The usage price of the Reserved Instance, per hour.
-- , drirsitInstanceCount :: !Integer
-- -- ^ The number of Reserved Instances purchased.
-- , drirsitProductDescription :: !Text
-- -- ^ The Reserved Instance description.
-- , drirsitState :: !Text
-- -- ^ The state of the Reserved Instance purchase.
-- , drirsitTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- , drirsitInstanceTenancy :: !Text
-- -- ^ The tenancy of the reserved instance.
-- , drirsitCurrencyCode :: !Text
-- -- ^ The currency of the Reserved Instance. It's specified using ISO
-- -- 4217 standard currency codes. At this time, the only supported
-- -- currency is USD.
-- , drirsitOfferingType :: !Text
-- -- ^ The Reserved Instance offering type.
-- , drirsitRecurringCharges :: !RecurringChargesSetItemType
-- -- ^ The recurring charge tag assigned to the resource.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeReservedInstancesResponseSetItemType
-- instance IsXML DescribeReservedInstancesResponseSetItemType where
-- xmlPickler = ec2XML
-- data DescribeReservedInstancesSetItemType = DescribeReservedInstancesSetItemType
-- { drisitReservedInstancesId :: !Text
-- -- ^ The ID of the Reserved Instance.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeReservedInstancesSetItemType
-- instance IsXML DescribeReservedInstancesSetItemType where
-- xmlPickler = ec2XML
-- data DescribeSnapshotsSetItemResponseType = DescribeSnapshotsSetItemResponseType
-- { dssirtSnapshotId :: !Text
-- -- ^ The ID of the snapshot.
-- , dssirtVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , dssirtStatus :: !Text
-- -- ^ The snapshot state.
-- , dssirtStartTime :: !UTCTime
-- -- ^ The time stamp when the snapshot was initiated.
-- , dssirtProgress :: !Text
-- -- ^ The progress of the snapshot, as a percentage.
-- , dssirtOwnerId :: !Text
-- -- ^ The ID of the AWS account that owns the snapshot.
-- , dssirtVolumeSize :: !Text
-- -- ^ The size of the volume, in GiB.
-- , dssirtDescription :: !Text
-- -- ^ The description of the snapshot.
-- , dssirtOwnerAlias :: !Text
-- -- ^ The AWS account alias (for example, amazon, self) or AWS account
-- -- ID that owns the AMI.
-- , dssirtTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeSnapshotsSetItemResponseType
-- instance IsXML DescribeSnapshotsSetItemResponseType where
-- xmlPickler = ec2XML
-- data DescribeVolumesSetItemResponseType = DescribeVolumesSetItemResponseType
-- { dvsirtVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , dvsirtSize :: !Text
-- -- ^ The size of the volume, in GiBs.
-- , dvsirtSnapshotId :: !Text
-- -- ^ The snapshot from which the volume was created (optional).
-- , dvsirtAvailabilityZone :: !Text
-- -- ^ The Availability Zone in which the volume was created.
-- , dvsirtStatus :: !Text
-- -- ^ The state of the volume.
-- , dvsirtCreateTime :: !UTCTime
-- -- ^ The time stamp when volume creation was initiated.
-- , dvsirtAttachmentSet :: !AttachmentSetItemResponseType
-- -- ^ Any volumes attached, each one wrapped in an item element.
-- , dvsirtTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- , dvsirtVolumeType :: !Text
-- -- ^ The volume type.
-- , dvsirtIops :: !Integer
-- -- ^ The number of I/O operations per second (IOPS) that the volume
-- -- supports.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DescribeVolumesSetItemResponseType
-- instance IsXML DescribeVolumesSetItemResponseType where
-- xmlPickler = ec2XML
-- data DhcpConfigurationItemType = DhcpConfigurationItemType
-- { dcitKey :: !Text
-- -- ^ The name of a DHCP option.
-- , dcitValueSet :: !DhcpValueType
-- -- ^ Any values for a DHCP option, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DhcpConfigurationItemType
-- instance IsXML DhcpConfigurationItemType where
-- xmlPickler = ec2XML
-- data DhcpOptionsType = DhcpOptionsType
-- { dotDhcpOptionsId :: !Text
-- -- ^ The ID of the set of DHCP options.
-- , dotDhcpConfigurationSet :: !DhcpConfigurationItemType
-- -- ^ The DHCP options in the set. Each option's key and set of values
-- -- are wrapped in an item element.
-- , dotTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DhcpOptionsType
-- instance IsXML DhcpOptionsType where
-- xmlPickler = ec2XML
-- data DhcpValueType = DhcpValueType
-- { dvtValue :: !Text
-- -- ^ A value for the DHCP option.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DhcpValueType
-- instance IsXML DhcpValueType where
-- xmlPickler = ec2XML
-- data DiskImageDescriptionType = DiskImageDescriptionType
-- { didtFormat :: !Text
-- -- ^ The disk image format.
-- , didtSize :: !Integer
-- -- ^ The size of the disk image.
-- , didtImportManifestUrl :: !Text
-- -- ^ A presigned URL for the import manifest stored in Amazon S3. For
-- -- information about creating a presigned URL for an Amazon S3
-- -- object, read the "Query String Request Authentication
-- -- Alternative" section of the Authenticating REST Requests topic in
-- -- the Amazon Simple Storage Service Developer Guide.
-- , didtChecksum :: !Text
-- -- ^ The checksum computed for the disk image.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DiskImageDescriptionType
-- instance IsXML DiskImageDescriptionType where
-- xmlPickler = ec2XML
-- data DiskImageVolumeDescriptionType = DiskImageVolumeDescriptionType
-- { divdtSize :: !Integer
-- -- ^ The size of the volume.
-- , divdtId :: !Text
-- -- ^ The volume identifier.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery DiskImageVolumeDescriptionType
-- instance IsXML DiskImageVolumeDescriptionType where
-- xmlPickler = ec2XML
data EbsBlockDeviceType = EbsBlockDeviceType
{ ebdtSnapshotId :: !Text
-- ^ The ID of the snapshot.
, ebdtVolumeSize :: !Integer
-- ^ The size of the volume, in GiB.
, ebdtDeleteOnTermination :: !Bool
-- ^ Indicates whether the Amazon EBS volume is deleted on instance termination.
, ebdtVolumeType :: !Text
-- ^ The volume type.
, ebdtIops :: Maybe Integer
-- ^ The number of I/O operations per second (IOPS) that the volume
-- supports.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery EbsBlockDeviceType
instance IsXML EbsBlockDeviceType where
xmlPickler = ec2XML
data EbsInstanceBlockDeviceMappingResponseType = EbsInstanceBlockDeviceMappingResponseType
{ eibdmrtVolumeId :: !Text
-- ^ The ID of the Amazon EBS volume.
, eibdmrtStatus :: !Text
-- ^ The attachment state.
, eibdmrtAttachTime :: !UTCTime
-- ^ The time stamp when the attachment initiated.
, eibdmrtDeleteOnTermination :: !Bool
-- ^ Indicates whether the volume is deleted on instance termination.
} deriving (Eq, Ord, Show, Generic)
instance IsXML EbsInstanceBlockDeviceMappingResponseType where
xmlPickler = ec2ItemXML
-- data ExportToS3Task = ExportToS3Task
-- { etstDiskImageFormat :: Maybe Text
-- , etstContainerFormat :: Maybe Text
-- , etstS3Bucket :: !Text
-- , etstS3Prefix :: !Text
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ExportToS3Task
-- instance IsXML ExportToS3Task where
-- xmlPickler = ec2XML
-- data ExportTaskResponseType = ExportTaskResponseType
-- { etrtExportTaskId :: !Text
-- -- ^ The ID of the export task.
-- , etrtDescription :: !Text
-- -- ^ A description of the resource being exported.
-- , etrtState :: !Text
-- -- ^ The state of the conversion task.
-- , etrtStatusMessage :: !Text
-- -- ^ The status message related to the export task.
-- , etrtInstanceExport :: !InstanceExportTaskResponseType
-- -- ^ The instance being exported.
-- , etrtExportToS3 :: !ExportToS3TaskResponseType
-- -- ^ The destination Amazon S3 bucket.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ExportTaskResponseType
-- instance IsXML ExportTaskResponseType where
-- xmlPickler = ec2XML
-- data ExportToS3TaskResponseType = ExportToS3TaskResponseType
-- { etstrtDiskImageFormat :: !Text
-- -- ^ The format for the exported image.
-- , etstrtContainerFormat :: !Text
-- -- ^ The container format used to combine disk images with metadata
-- -- (such as OVF).
-- , etstrtS3Bucket :: !Text
-- -- ^ The Amazon S3 bucket for the destination image.
-- , etstrtS3Key :: !Text
-- -- ^ The image written to a single object in s3bucket at the S3 key
-- -- s3prefix + exportTaskId + '.' +diskImageFormat.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ExportToS3TaskResponseType
-- instance IsXML ExportToS3TaskResponseType where
-- xmlPickler = ec2XML
data GroupItemType = GroupItemType
{ gitGroupId :: !Text
-- ^ The ID of the security group.
, gitGroupName :: !Text
-- ^ The name of the security group.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery GroupItemType
instance IsXML GroupItemType where
xmlPickler = ec2ItemXML
data IamInstanceProfileRequestType = IamInstanceProfileRequestType
{ iiprtArn :: Maybe Text
-- ^ The Amazon Resource Name (ARN) of the instance profile.
, iiprtName :: Maybe Text
-- ^ The name of the instance profile.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery IamInstanceProfileRequestType
-- instance IsXML IamInstanceProfileRequestType where
-- xmlPickler = ec2XML
data IamInstanceProfileResponseType = IamInstanceProfileResponseType
{ iipruArn :: !Text
-- ^ The Amazon Resource Name (ARN) of the instance profile.
, iipruId :: !Text
-- ^ The ID of the instance profile.
} deriving (Eq, Ord, Show, Generic)
instance IsXML IamInstanceProfileResponseType where
xmlPickler = ec2XML
-- data IcmpType = IcmpType
-- { itctCode :: !Integer
-- -- ^ The ICMP code. A value of -1 means all codes for the specified
-- -- ICMP type.
-- , itctType :: !Integer
-- -- ^ The ICMP type. A value of -1 means all types.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery IcmpTypeCodeType
-- instance IsXML IcmpTypeCodeType where
-- xmlPickler = ec2XML
-- data InstancePlacement = InstancePlacement
-- { ipAvailabilityZone :: !Maybe Text
-- , ipGroupName :: !Maybe Text
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstancePlacement
-- instance IsXML InstancePlacement where
-- xmlPickler = ec2XML
-- data ImportInstanceLaunchSpecification = ImportInstanceLaunchSpecification
-- { iilsArchitecture :: !Text
-- , iilsGroupSet :: Members GroupItemType
-- , iilsUserData :: Maybe UserDataType
-- , iilsInstance :: !Text
-- , iilsPlacement :: Maybe InstancePlacementType
-- , iilsMonitoring :: Maybe MonitoringInstanceType
-- , iilsSubnetId :: Maybe Text
-- , iilsInstanceInitiatedShutdownBehavior :: Maybe Text
-- , iilsPrivateIpAddress :: Maybe Text
-- } deriving (Show)
-- data ImportInstanceTaskDetailsType = ImportInstanceTaskDetailsType
-- { iitdtVolumes :: !ImportInstanceVolumeDetailItemType
-- -- ^ Any instance volumes for import, each one wrapped in an item
-- -- element.
-- , iitdtInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , iitdtPlatform :: !Text
-- -- ^ The value is Windows for Windows AMIs; otherwise blank.
-- , iitdtDescription :: !Text
-- -- ^ An optional description of the instance.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ImportInstanceTaskDetailsType
-- instance IsXML ImportInstanceTaskDetailsType where
-- xmlPickler = ec2XML
-- data ImportInstanceVolumeDetailItemType = ImportInstanceVolumeDetailItemType
-- { iivditBytesConverted :: !Integer
-- -- ^ The number of bytes converted so far.
-- , iivditAvailabilityZone :: !Text
-- -- ^ The Availability Zone where the resulting instance will reside.
-- , iivditImage :: !DiskImageDescriptionType
-- -- ^ The image.
-- , iivditDescription :: !Text
-- -- ^ The description you provided when starting the import instance
-- -- task.
-- , iivditVolume :: !DiskImageVolumeDescriptionType
-- -- ^ The volume.
-- , iivditStatus :: !Text
-- -- ^ The status of the import of this particular disk image.
-- , iivditStatusMessage :: !Text
-- -- ^ The status information or errors related to the disk image.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ImportInstanceVolumeDetailItemType
-- instance IsXML ImportInstanceVolumeDetailItemType where
-- xmlPickler = ec2XML
-- data ImportVolumeTaskDetailsType = ImportVolumeTaskDetailsType
-- { ivtdtBytesConverted :: !Integer
-- -- ^ The number of bytes converted so far.
-- , ivtdtAvailabilityZone :: !Text
-- -- ^ The Availability Zone where the resulting volume will reside.
-- , ivtdtDescription :: !Text
-- -- ^ The description you provided when starting the import volume
-- -- task.
-- , ivtdtImage :: !DiskImageDescriptionType
-- -- ^ The image.
-- , ivtdtVolume :: !DiskImageVolumeDescriptionType
-- -- ^ The volume.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ImportVolumeTaskDetailsType
-- instance IsXML ImportVolumeTaskDetailsType where
-- xmlPickler = ec2XML
data InstanceBlockDeviceMappingItemType = InstanceBlockDeviceMappingItemType
{ ibdmitDeviceName :: !Text
-- ^ The device name exposed to the instance (for example, /dev/sdh or
-- xvdh).
, ibdmitVirtualName :: !Text
-- ^ The virtual device name.
, ibdmitEbs :: !InstanceEbsBlockDeviceType
-- ^ Parameters used to automatically set up Amazon EBS volumes when
-- the instance is launched.
, ibdmitNoDevice :: !Text
-- ^ Include this empty element to suppress the specified device
-- included in the block device mapping of the AMI.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery InstanceBlockDeviceMappingItemType
-- instance IsXML InstanceBlockDeviceMappingItemType where
-- xmlPickler = ec2XML
data InstanceBlockDeviceMappingResponseItemType = InstanceBlockDeviceMappingResponseItemType
{ ibdmritDeviceName :: !Text
-- ^ The device name exposed to the instance (for example, /dev/sdh, or xvdh).
, ibdmritEbs :: !EbsInstanceBlockDeviceMappingResponseType
-- ^ Parameters used to automatically set up Amazon EBS volumes when
-- the instance is launched.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceBlockDeviceMappingResponseItemType where
xmlPickler = ec2ItemXML
data InstanceCountsSetItemType = InstanceCountsSetItemType
{ icsitState :: !Text
-- ^ The states of the listed Reserved Instances.
, icsitInstanceCount :: !Integer
-- ^ The number of listed Reserved Instances in the state specified by
-- the state.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceCountsSetItemType where
xmlPickler = ec2XML
data InstanceEbsBlockDeviceType = InstanceEbsBlockDeviceType
{ iebdtDeleteOnTermination :: !Bool
-- ^ Indicates whether the volume is deleted on instance termination.
, iebdtVolumeId :: !Text
-- ^ The ID of the volume.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery InstanceEbsBlockDeviceType
-- instance IsXML InstanceEbsBlockDeviceType where
-- xmlPickler = ec2XML
-- data InstanceExportTaskResponseType = InstanceExportTaskResponseType
-- { ietrtInstanceId :: !Text
-- -- ^ The ID of the resource being exported.
-- , ietrtTargetEnvironment :: !Text
-- -- ^ The target virtualization environment.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceExportTaskResponseType
-- instance IsXML InstanceExportTaskResponseType where
-- xmlPickler = ec2XML
data InstanceMonitoringStateType = InstanceMonitoringStateType
{ imstState :: !Text
-- ^ The state of monitoring for the instance.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceMonitoringStateType where
xmlPickler = ec2XML
data InstanceNetworkInterfaceAssociationType = InstanceNetworkInterfaceAssociationType
{ iniatPublicIp :: !Text
-- ^ The address of the Elastic IP address bound to the network interface.
, iniatPublicDnsName :: !Text
-- ^ The public DNS name.
, iniatIpOwnerId :: !Text
-- ^ The ID of the owner of the Elastic IP address.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceNetworkInterfaceAssociationType where
xmlPickler = ec2XML
data InstanceNetworkInterfaceAttachmentType = InstanceNetworkInterfaceAttachmentType
{ iniatAttachmentID :: !Text
-- ^ The ID of the network interface attachment.
, iniatDeviceIndex :: !Integer
-- ^ The index of the device on the instance for the network interface attachment.
, iniatStatus :: !Text
-- ^ The attachment state.
, iniatAttachTime :: !UTCTime
-- ^ The time stamp when the attachment initiated.
, iniatDeleteOnTermination :: !Bool
-- ^ Indicates whether the network interface is deleted when the
-- instance is terminated.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceNetworkInterfaceAttachmentType where
xmlPickler = ec2XML
-- data InstanceNetworkInterfaceSetItemRequestType = InstanceNetworkInterfaceSetItemRequestType
-- { inisirtNetworkInterfaceId :: !Text
-- -- ^ The ID of the network interface.
-- , inisirtDeviceIndex :: !Integer
-- -- ^ Required. The index of the device on the instance for the network
-- -- interface attachment.
-- , inisirtSubnetId :: !Text
-- -- ^ The ID of the subnet associated with the network string.
-- , inisirtDescription :: !Text
-- -- ^ The description of the network interface.
-- , inisirtPrivateIpAddress :: !Text
-- -- ^ The private IP address of the network interface.
-- , inisirtGroupSet :: !SecurityGroupIdSetItemType
-- -- ^ The IDs of the security groups for use by the network interface.
-- , inisirtDeleteOnTermination :: !Bool
-- -- ^ If set to true, the interface is deleted when the instance is
-- -- terminated.
-- , inisirtPrivateIpAddressesSet :: !PrivateIpAddressesSetItemRequestType
-- -- ^ The list of IP addresses to assign to the network interface.
-- , inisirtSecondaryPrivateIpAddressCount :: !Integer
-- -- ^ The number of secondary private IP addresses. You cannot specify
-- -- this option with privateIpAddressSet.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceNetworkInterfaceSetItemRequestType
-- instance IsXML InstanceNetworkInterfaceSetItemRequestType where
-- xmlPickler = ec2XML
data InstanceNetworkInterfaceSetItemType = InstanceNetworkInterfaceSetItemType
{ inisitNetworkInterfaceId :: !Text
-- ^ The ID of the network interface.
, inisitSubnetId :: !Text
-- ^ The ID of the subnet.
, inisitVpcId :: !Text
-- ^ The ID of the VPC.
, inisitDescription :: !Text
-- ^ The description.
, inisitOwnerId :: !Text
-- ^ The ID of the customer who created the network interface.
, inisitStatus :: !Text
-- ^ The status of the network interface.
, inisitMacAddress :: !Text
-- ^ The MAC address.
, inisitPrivateIpAddress :: !Text
-- ^ The IP address of the network interface within the subnet.
, inisitPrivateDnsName :: !Text
-- ^ The private DNS name.
, inisitSourceDestCheck :: !Bool
-- ^ Indicates whether to validate network traffic to or from this
-- network interface.
, inisitGroupSet :: [GroupItemType]
-- ^ A security group.
, inisitAttachment :: !InstanceNetworkInterfaceAttachmentType
-- ^ The network interface attachment.
, inisitAssociation :: !InstanceNetworkInterfaceAssociationType
-- ^ The association information for an Elastic IP associated with the
-- network interface.
, inisitPrivateIpAddressesSet :: [InstancePrivateIpAddressesSetItemType]
-- ^ The private IP addresses associated with the network interface.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceNetworkInterfaceSetItemType where
xmlPickler = ec2XML
data InstancePrivateIpAddressesSetItemType = InstancePrivateIpAddressesSetItemType
{ ipiasitPrivateIpAddress :: !Text
-- ^ The private IP address of the network interface
, ipiasitPrivateDnsName :: !Text
-- ^ The private DNS name.
, ipiasitPrimary :: !Bool
-- ^ Indicates whether this IP address is the primary private IP
-- address of the network interface.
, ipiasitAssociation :: !InstanceNetworkInterfaceAssociationType
-- ^ The association information for an Elastic IP address associated
-- with the network interface.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstancePrivateIpAddressesSetItemType where
xmlPickler = ec2XML
data InstanceStateChangeType = InstanceStateChangeType
{ isctInstanceId :: !Text
-- ^ The instance ID.
, isctCurrentState :: !InstanceStateType
-- ^ The current state of the instance.
, isctPreviousState :: !InstanceStateType
-- ^ The previous state of the instance.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceStateChangeType where
xmlPickler = ec2ItemXML
data InstanceStateType = InstanceStateType
{ istCode :: !Integer
-- ^ The low byte represents the state. The high byte is an opaque
-- internal value and should be ignored.
, istName :: !Text
-- ^ The current state of the instance.
} deriving (Eq, Ord, Show, Generic)
instance IsXML InstanceStateType where
xmlPickler = ec2XML
-- data InstanceStatusDetailsSetType = InstanceStatusDetailsSetType
-- { isdstName :: !Text
-- -- ^ The type of instance status detail.
-- , isdstStatus :: !Text
-- -- ^ The status.
-- , isdstImpairedSince :: !UTCTime
-- -- ^ The time when a status check failed. For an instance that was
-- -- launched and impaired, this is the time when the instance was
-- -- launched.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceStatusDetailsSetType
-- instance IsXML InstanceStatusDetailsSetType where
-- xmlPickler = ec2XML
-- data InstanceStatusEventsSetType = InstanceStatusEventsSetType
-- { isest[:: !InstanceStatusEventType]
-- -- ^ The scheduled events for the instance.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceStatusEventsSetType
-- instance IsXML InstanceStatusEventsSetType where
-- xmlPickler = ec2XML
-- data InstanceStatusEventType = InstanceStatusEventType
-- { isetCode :: !Text
-- -- ^ The associated code of the event.
-- , isetDescription :: !Text
-- -- ^ A description of the event.
-- , isetNotBefore :: !UTCTime
-- -- ^ The earliest scheduled start time for the event.
-- , isetNotAfter :: !UTCTime
-- -- ^ The latest scheduled end time for the event.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceStatusEventType
-- instance IsXML InstanceStatusEventType where
-- xmlPickler = ec2XML
-- data InstanceStatusItemType = InstanceStatusItemType
-- { isitInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , isitAvailabilityZone :: !Text
-- -- ^ The Availability Zone of the instance.
-- , isitEventsSet :: !InstanceStatusEventsSetType
-- -- ^ Extra information regarding events associated with the instance.
-- , isitInstanceState :: !InstanceStateType
-- -- ^ The intended state of the instance. Calls to
-- -- DescribeInstanceStatus require that an instance be in the running
-- -- state.
-- , isitSystemStatus :: !InstanceStatusType
-- -- ^ Reports impaired functionality that stems from issues related to
-- -- the systems that support an instance, such as hardware failures
-- -- and network connectivity problems.
-- , isitInstanceStatus :: !InstanceStatusType
-- -- ^ Reports impaired functionality that arises from problems internal
-- -- to the instance. The DescribeInstanceStatus response elements
-- -- report such problems as impaired reachability.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceStatusItemType
-- instance IsXML InstanceStatusItemType where
-- xmlPickler = ec2XML
-- data InstanceStatusSetType = InstanceStatusSetType
-- { isst[:: !InstanceStatusItemType]
-- -- ^ The status of the instance.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceStatusSetType
-- instance IsXML InstanceStatusSetType where
-- xmlPickler = ec2XML
-- data InstanceStatusType = InstanceStatusType
-- { istStatus :: !Text
-- -- ^ The status.
-- , istDetails :: !InstanceStatusDetailsSetType
-- -- ^ The system instance health or application instance health.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InstanceStatusType
-- instance IsXML InstanceStatusType where
-- xmlPickler = ec2XML
-- data InternetGatewayAttachmentType = InternetGatewayAttachmentType
-- { igatVpcId :: !Text
-- -- ^ The ID of the VPC.
-- , igatState :: !Text
-- -- ^ The current state of the attachment.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InternetGatewayAttachmentType
-- instance IsXML InternetGatewayAttachmentType where
-- xmlPickler = ec2XML
-- data InternetGatewayType = InternetGatewayType
-- { igtInternetGatewayId :: !Text
-- -- ^ The ID of the Internet gateway.
-- , igtAttachmentSet :: !InternetGatewayAttachmentType
-- -- ^ Any VPCs attached to the Internet gateway, each one wrapped in an
-- -- item element.
-- , igtTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery InternetGatewayType
-- instance IsXML InternetGatewayType where
-- xmlPickler = ec2XML
data UserIdGroupPair = UserIdGroupPair
{ uigUserId :: Maybe Text
-- ^ The ID of an AWS account. Cannot be used when specifying a CIDR
-- IP address range.
, uigGroupId :: Maybe Text
-- ^ The ID of the security group in the specified AWS account.
-- Cannot be used when specifying a CIDR IP address range.
, uigGroupName :: Maybe Text
-- ^ The name of the security group in the specified AWS account.
-- Cannot be used when specifying a CIDR IP address range.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery UserIdGroupPair
instance IsXML UserIdGroupPair where
xmlPickler = ec2ItemXML
data IpPermissionType = IpPermissionType
{ iptIpProtocol :: !Protocol
-- ^ The protocol.
, iptFromPort :: !Integer
-- ^ The start of port range for the ICMP and UDP protocols, or an ICMP
-- type number. A value of -1 indicates all ICMP types.
, iptToPort :: !Integer
-- ^ The end of port range for the ICMP and UDP protocols, or an ICMP
-- code. A value of -1 indicates all ICMP codes for the given ICMP type.
, iptGroups :: [UserIdGroupPair]
-- ^ A list of security group and AWS account ID pairs.
, iptIpRanges :: [IpRange]
-- ^ A list of IP ranges.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery IpPermissionType
instance IsXML IpPermissionType where
xmlPickler = ec2ItemXML
data IpRange = IpRange
{ irCidrIp :: !Text
-- ^ The CIDR range. You can either specify a CIDR range or a source
-- security group, not both.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery IpRange
instance IsXML IpRange where
xmlPickler = ec2ItemXML
-- data LaunchPermissionItemType = LaunchPermissionItemType
-- { lpitGroup :: !Text
-- -- ^ The name of the group.
-- , lpitUserId :: !Text
-- -- ^ The AWS account ID.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery LaunchPermissionItemType
-- instance IsXML LaunchPermissionItemType where
-- xmlPickler = ec2XML
-- data LaunchSpecificationRequestType = LaunchSpecificationRequestType
-- { lsrtImageId :: !Text
-- -- ^ The AMI ID.
-- , lsrtKeyName :: !Text
-- -- ^ The name of the key pair.
-- , lsrtGroupSet :: !GroupItemType
-- -- ^ A list of security groups. Each group is wrapped in an item
-- -- element.
-- , lsrtUserData :: !UserDataType
-- -- ^ Base64-encoded MIME user data made available to the instance(s)
-- -- in the reservation.
-- , lsrtInstanceType :: !Text
-- -- ^ The instance type.
-- , lsrtPlacement :: !PlacementRequestType
-- -- ^ The placement information for the instance.
-- , lsrtKernelId :: !Text
-- -- ^ The ID of the kernel to select.
-- , lsrtRamdiskId :: !Text
-- -- ^ The ID of the RAM disk to select. Some kernels require additional
-- -- drivers at launch. Check the kernel requirements for information
-- -- on whether you need to specify a RAM disk and search for the
-- -- kernel ID.
-- , lsrtBlockDeviceMapping :: !BlockDeviceMappingItemType
-- -- ^ Any block device mapping entries for the instance. Each entry is
-- -- wrapped in an item element.
-- , lsrtMonitoring :: !MonitoringInstanceType
-- -- ^ The monitoring information for the instance.
-- , lsrtSubnetId :: !Text
-- -- ^ The ID of the subnet.
-- , lsrtNetworkInterfaceSet :: !InstanceNetworkInterfaceSetItemRequestType
-- -- ^ The network interfaces associated with the instance.
-- , lsrtIamInstanceProfile :: !IamInstanceProfileRequestType
-- -- ^ The IAM Instance Profile (IIP) associated with the instance.
-- , lsrtEbsOptimized :: !Bool
-- -- ^ Indicates whether the instance is optimized for EBS I/O. This
-- -- optimization provides dedicated throughput to Amazon EBS and an
-- -- optimized configuration stack to provide optimal EBS I/O
-- -- performance. This optimization isn't available with all instance
-- -- types. Additional usage charges apply when using an EBS Optimized
-- -- instance.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery LaunchSpecificationRequestType
-- instance IsXML LaunchSpecificationRequestType where
-- xmlPickler = ec2XML
-- data LaunchSpecificationResponseType = LaunchSpecificationResponseType
-- { lsruImageId :: !Text
-- -- ^ The AMI ID.
-- , lsruKeyName :: !Text
-- -- ^ The name of the key pair.
-- , lsruGroupSet :: !GroupItemType
-- -- ^ A list of security groups. Each group is wrapped in an item
-- -- element.
-- , lsruInstanceType :: !Text
-- -- ^ The instance type.
-- , lsruPlacement :: !PlacementRequestType
-- -- ^ The placement information for the instance.
-- , lsruKernelId :: !Text
-- -- ^ The ID of the kernel to select.
-- , lsruRamdiskId :: !Text
-- -- ^ The ID of the RAM disk to select. Some kernels require additional
-- -- drivers at launch. Check the kernel requirements for information
-- -- on whether you need to specify a RAM disk and search for the
-- -- kernel ID.
-- , lsruBlockDeviceMapping :: !BlockDeviceMappingItemType
-- -- ^ Any block device mapping entries for the instance. Each entry is
-- -- wrapped in an item element.
-- , lsruMonitoring :: !MonitoringInstanceType
-- -- ^ The monitoring information for the instance.
-- , lsruSubnetId :: !Text
-- -- ^ The ID of the subnet.
-- , lsruNetworkInterfaceSet :: !InstanceNetworkInterfaceSetItemRequestType
-- -- ^ The network interfaces for the instance.
-- , lsruIamInstanceProfile :: !IamInstanceProfileRequestType
-- -- ^ The IAM Instance Profile (IIP) associated with the instance.
-- , lsruEbsOptimized :: !Bool
-- -- ^ Indicates whether the instance is optimized for EBS I/O. This
-- -- optimization provides dedicated throughput to Amazon EBS and an
-- -- optimized configuration stack to provide optimal EBS I/O
-- -- performance. This optimization isn't available with all instance
-- -- types. Additional usage charges apply when using an EBS Optimized
-- -- instance.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery LaunchSpecificationResponseType
-- instance IsXML LaunchSpecificationResponseType where
-- xmlPickler = ec2XML
data MonitoringInstanceType = MonitoringInstanceType
{ mitEnabled :: !Bool
-- ^ Indicates whether monitoring is enabled for the instance.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery MonitoringInstanceType
-- instance IsXML MonitoringInstanceType where
-- xmlPickler = ec2XML
-- data MonitorInstancesResponseSetItemType = MonitorInstancesResponseSetItemType
-- { mirsitInstanceId :: !Text
-- -- ^ The instance ID.
-- , mirsitMonitoring :: !InstanceMonitoringStateType
-- -- ^ The monitoring information.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery MonitorInstancesResponseSetItemType
-- instance IsXML MonitorInstancesResponseSetItemType where
-- xmlPickler = ec2XML
-- data NetworkAclAssociationType = NetworkAclAssociationType
-- { naatNetworkAclAssociationId :: !Text
-- -- ^ An identifier representing the association between a network ACL
-- -- and a subnet.
-- , naatNetworkAclId :: !Text
-- -- ^ The ID of the network ACL.
-- , naatSubnetId :: !Text
-- -- ^ The ID of the subnet.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery NetworkAclAssociationType
-- instance IsXML NetworkAclAssociationType where
-- xmlPickler = ec2XML
-- data NetworkAclEntryType = NetworkAclEntryType
-- { naetRuleNumber :: !Integer
-- -- ^ The rule number for the entry. ACL entries are processed in
-- -- ascending order by rule number.
-- , naetProtocol :: !Integer
-- -- ^ The protocol. A value of -1 means all protocols.
-- , naetRuleAction :: !Text
-- -- ^ Indicates whether to allow or deny the traffic that matches the
-- -- rule.
-- , naetEgress :: !Bool
-- -- ^ Indicates an egress rule (rule is applied to traffic leaving the
-- -- subnet). Value of true indicates egress.
-- , naetCidrBlock :: !Text
-- -- ^ The network range to allow or deny, in CIDR notation.
-- , naetIcmpTypeCode :: !IcmpTypeCodeType
-- -- ^ ICMP protocol: The ICMP type and code.
-- , naetPortRange :: !PortRangeType
-- -- ^ ICMP or UDP protocols: The range of ports the rule applies to.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery NetworkAclEntryType
-- instance IsXML NetworkAclEntryType where
-- xmlPickler = ec2XML
-- data NetworkAclType = NetworkAclType
-- { natNetworkAclId :: !Text
-- -- ^ The ID of the network ACL.
-- , natVpcId :: !Text
-- -- ^ The ID of the VPC for the network ACL.
-- , natDefault :: !Bool
-- -- ^ Indicates whether this is the default network ACL for the VPC.
-- , natEntrySet :: !NetworkAclEntryType
-- -- ^ A list of entries (rules) in the network ACL. Each entry is
-- -- wrapped in an item element.
-- , natAssociationSet :: !NetworkAclAssociationType
-- -- ^ A list of associations between the network ACL and one or more
-- -- subnets. Each association is wrapped in an item element.
-- , natTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery NetworkAclType
-- instance IsXML NetworkAclType where
-- xmlPickler = ec2XML
data NetworkInterfaceAssociationType = NetworkInterfaceAssociationType
{ niatPublicIp :: !Text
-- ^ The address of the Elastic IP address bound to the network
-- interface.
, niatPublicDnsName :: !Text
-- ^ The public DNS name.
, niatIpOwnerId :: !Text
-- ^ The ID of the Elastic IP address owner.
, niatAllocationID :: !Text
-- ^ The allocation ID.
, niatAssociationID :: !Text
-- ^ The association ID.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery NetworkInterfaceAssociationType
-- instance IsXML NetworkInterfaceAssociationType where
-- xmlPickler = ec2XML
data NetworkInterfaceAttachmentType = NetworkInterfaceAttachmentType
{ niatAttachmentID :: !Text
-- ^ The ID of the network interface attachment.
, niatInstanceID :: !Text
-- ^ The ID of the instance.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery NetworkInterfaceAttachmentType
-- instance IsXML NetworkInterfaceAttachmentType where
-- xmlPickler = ec2XML
data NetworkInterfacePrivateIpAddressesSetItemType = NetworkInterfacePrivateIpAddressesSetItemType
{ nipiasitPrivateIpAddress :: !Text
-- ^ The private IP address of the network interface.
, nipiasitPrivateDnsName :: !Text
-- ^ The private DNS name.
, nipiasitPrimary :: !Bool
-- ^ Indicates whether this IP address is the primary private IP
-- address of the network interface.
, nipiasitAssociation :: !NetworkInterfaceAssociationType
-- ^ The association information for an Elastic IP address associated
-- with the network interface.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery NetworkInterfacePrivateIpAddressesSetItemType
-- instance IsXML NetworkInterfacePrivateIpAddressesSetItemType where
-- xmlPickler = ec2XML
data NetworkInterfaceType = NetworkInterfaceType
{ nitNetworkInterfaceId :: !Text
-- ^ The ID of the network interface.
, nitSubnetId :: !Text
-- ^ The ID of the subnet.
, niuNetworkInterfaceId :: !Text
-- ^ The ID of the network interface.
, niuSubnetId :: !Text
-- ^ The ID of the subnet.
, niuVpcId :: !Text
-- ^ The ID of the VPC.
, niuAvailabilityZone :: !Text
-- ^ The Availability Zone.
, niuDescription :: !Text
-- ^ A description.
, niuOwnerId :: !Text
-- ^ The ID of the customer who created the interface.
, niuRequesterId :: !Text
-- ^ The ID of the entity that launched the instance on your behalf
-- (for example, AWS Management Console or Auto Scaling)
, niuRequesterManaged :: !Text
-- ^ Indicates whether the network interface is being managed by AWS.
, niuStatus :: !Text
-- ^ The status of the network interface.
, niuMacAddress :: !Text
-- ^ The MAC address.
, niuPrivateIpAddress :: !Text
-- ^ The IP address of the network interface within the subnet.
, niuPrivateDnsName :: !Text
-- ^ The private DNS name.
, niuSourceDestCheck :: !Bool
-- ^ Indicates whether traffic to or from the instance is validated.
, niuGroupSet :: !GroupItemType
-- ^ The security group.
, niuAttachment :: !NetworkInterfaceAttachmentType
-- ^ The network interface attachment.
, niuAssociation :: !NetworkInterfaceAssociationType
-- ^ The association information for an Elastic IP associated with the
-- network interface.
, niuTagSet :: !ResourceTagSetItemType
-- ^ The tags assigned to the resource.
, niuPrivateIpAddressesSet :: !NetworkInterfacePrivateIpAddressesSetItemType
-- ^ The private IP addresses associated with the network interface.
-- [are returned in a set.]
} deriving (Eq, Ord, Show, Generic)
instance IsQuery NetworkInterfaceType
-- instance IsXML NetworkInterfaceType where
-- xmlPickler = ec2XML
-- data PlacementGroupInfoType = PlacementGroupInfoType
-- { pgitGroupName :: !Text
-- -- ^ The name of the placement group.
-- , pgitStrategy :: !Text
-- -- ^ The placement strategy.
-- , pgitState :: !Text
-- -- ^ The status of the placement group.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PlacementGroupInfoType
-- instance IsXML PlacementGroupInfoType where
-- xmlPickler = ec2XML
-- data PlacementRequestType = PlacementRequestType
-- { prtAvailabilityZone :: !Text
-- -- ^ The Availability Zone for the instance.
-- , prtGroupName :: !Text
-- -- ^ The name of a placement group for the instance.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PlacementRequestType
-- instance IsXML PlacementRequestType where
-- xmlPickler = ec2XML
-- FIXME: is the corresponding request type now irrelavant?
data PlacementType = PlacementType
{ pruAvailabilityZone :: Maybe AvailabilityZone
-- ^ The Availability Zone of the instance.
, pruGroupName :: Maybe Text
-- ^ The name of the placement group the instance is in
-- (for cluster compute instances).
, pruTenancy :: Maybe Text
-- ^ The tenancy of the instance (if the instance is running within a -- VPC).
-- FIXME: switch to enum default | dedicated
} deriving (Eq, Ord, Show, Generic)
instance IsQuery PlacementType
instance IsXML PlacementType where
xmlPickler = ec2XML
-- data PortRangeType = PortRangeType
-- { prtFrom :: !Integer
-- -- ^ The first port in the range.
-- , prtTo :: !Integer
-- -- ^ The last port in the range.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PortRangeType
-- instance IsXML PortRangeType where
-- xmlPickler = ec2XML
-- data PriceScheduleRequestSetItemType = PriceScheduleRequestSetItemType
-- { psrsitTerm :: !Integer
-- -- ^ The number of months remaining in the reservation. For example, 2
-- -- is the second to the last month before the capacity reservation
-- -- expires.
-- , psrsitPrice :: !Double
-- -- ^ The fixed price for the term.
-- , psrsitCurrencyCode :: !Text
-- -- ^ The currency for transacting the Reserved Instance resale. At
-- -- this time, the only supported currency is USD.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PriceScheduleRequestSetItemType
-- instance IsXML PriceScheduleRequestSetItemType where
-- xmlPickler = ec2XML
data PriceScheduleSetItemType = PriceScheduleSetItemType
{ pssitTerm :: !Integer
-- ^ The number of months remaining in the reservation. For example, 2
-- is the second to the last month before the capacity reservation
-- expires.
, pssitPrice :: !Double
-- ^ The fixed price for the term.
, pssitCurrencyCode :: !Text
-- ^ The currency for transacting the Reserved Instance resale. At
-- this time, the only supported currency is USD.
, pssitActive :: !Bool
-- ^ The current price schedule, as determined by the term remaining
-- for the Reserved Instance in the listing.
} deriving (Eq, Ord, Show, Generic)
instance IsXML PriceScheduleSetItemType where
xmlPickler = ec2XML
-- data PriceScheduleSetType = PriceScheduleSetType
-- { psst[:: !PriceScheduleSetItemType]
-- -- ^ The Reserved Instance listing price schedule item.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PriceScheduleSetType
-- instance IsXML PriceScheduleSetType where
-- xmlPickler = ec2XML
-- data PricingDetailsSetItemType = PricingDetailsSetItemType
-- { pdsitPrice :: !Integer
-- -- ^ The price per instance.
-- , pdsitCount :: !Integer
-- -- ^ The number of instances available for the price.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PricingDetailsSetItemType
-- instance IsXML PricingDetailsSetItemType where
-- xmlPickler = ec2XML
-- data PrivateIpAddressesSetItemRequestType = PrivateIpAddressesSetItemRequestType
-- { piasirtPrivateIpAddressesSet :: !AssignPrivateIpAddressesSetItemRequestType
-- -- ^ The list of private IP addresses.
-- , piasirtPrimary :: !Bool
-- -- ^ Indicates whether the private IP address is the primary private
-- -- IP address.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PrivateIpAddressesSetItemRequestType
-- instance IsXML PrivateIpAddressesSetItemRequestType where
-- xmlPickler = ec2XML
-- data ProductCodeItemType = ProductCodeItemType
-- { pcitProductCode :: !Text
-- -- ^ The product code.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ProductCodeItemType
-- instance IsXML ProductCodeItemType where
-- xmlPickler = ec2XML
data ProductCodesSetItemType = ProductCodesSetItemType
{ pcsitProductCode :: !Text
-- ^ The product code.
, pcsitType :: !Text
-- ^ The type of product code.
} deriving (Eq, Ord, Show, Generic)
instance IsXML ProductCodesSetItemType where
xmlPickler = ec2ItemXML
-- data ProductDescriptionSetItemType = ProductDescriptionSetItemType
-- { pdsitProductDescription :: !Text
-- -- ^ The description of the AMI.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ProductDescriptionSetItemType
-- instance IsXML ProductDescriptionSetItemType where
-- xmlPickler = ec2XML
-- data PropagatingVgwType = PropagatingVgwType
-- { pvtGatewayID :: !Text
-- -- ^ The ID of the virtual private gateway (VGW).
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery PropagatingVgwType
-- instance IsXML PropagatingVgwType where
-- xmlPickler = ec2XML
-- data RecurringChargesSetItemType = RecurringChargesSetItemType
-- { rcsitFrequency :: !Text
-- -- ^ The frequency of the recurring charge.
-- , rcsitAmount :: !Double
-- -- ^ The amount of the recurring charge.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery RecurringChargesSetItemType
-- instance IsXML RecurringChargesSetItemType where
-- xmlPickler = ec2XML
data RegionItemType = RegionItemType
{ ritRegionName :: !Text
-- ^ The name of the region.
, ritRegionEndpoint :: !Text
-- ^ The region service endpoint.
} deriving (Eq, Ord, Show, Generic)
instance IsXML RegionItemType where
xmlPickler = ec2ItemXML
data ReservationInfoType = ReservationInfoType
{ ritReservationId :: !Text
-- ^ The ID of the reservation.
, ritOwnerId :: !Text
-- ^ The ID of the AWS account that owns the reservation.
, ritGroupSet :: [GroupItemType]
-- ^ A list of security groups.
, ritInstancesSet :: [RunningInstancesItemType]
-- ^ A list of instances.
, ritRequesterId :: Maybe Text
-- ^ The ID of the requester that launched the instances on your
-- behalf (for example, AWS Management Console or Auto Scaling).
} deriving (Eq, Ord, Show, Generic)
instance IsXML ReservationInfoType where
xmlPickler = ec2ItemXML
-- data ReservedInstanceLimitPriceType = ReservedInstanceLimitPriceType
-- { rilptAmount :: !Double
-- -- ^ Used for Reserved Instance Marketplace offerings. Specifies the
-- -- limit price on the total order (instanceCount * price).
-- , rilptCurrencyCode :: !Double
-- -- ^ Currency in which the limitPrice amount is specified. At this
-- -- time, the only supported currency is USD.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery ReservedInstanceLimitPriceType
-- instance IsXML ReservedInstanceLimitPriceType where
-- xmlPickler = ec2XML
data ResourceTagSetItemType = ResourceTagSetItemType
{ rtsitKey :: !Text
-- ^ The tag key.
, rtsitValue :: !Text
-- ^ The tag value.
} deriving (Eq, Ord, Show, Generic)
instance IsQuery ResourceTagSetItemType
instance IsXML ResourceTagSetItemType where
xmlPickler = ec2ItemXML
-- data RouteTableAssociationType = RouteTableAssociationType
-- { rtatRouteTableAssociationId :: !Text
-- -- ^ An identifier representing the association between a route table
-- -- and a subnet.
-- , rtatRouteTableId :: !Text
-- -- ^ The ID of the route table.
-- , rtatSubnetId :: !Text
-- -- ^ The ID of the subnet.
-- , rtatMain :: !Bool
-- -- ^ Indicates whether this is the main route table.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery RouteTableAssociationType
-- instance IsXML RouteTableAssociationType where
-- xmlPickler = ec2XML
-- data RouteTableType = RouteTableType
-- { rttRouteTableId :: !Text
-- -- ^ The route table's ID.
-- , rttVpcId :: !Text
-- -- ^ The ID of the VPC for the route table.
-- , rttRouteSet :: !RouteType
-- -- ^ A list of routes in the route table. Each route is wrapped in an
-- -- item element.
-- , rttAssociationSet :: !RouteTableAssociationType
-- -- ^ A list of associations between the route table and one or more
-- -- subnets. Each association is wrapped in an item element.
-- , rttPropagatingVgwSet :: !PropagatingVgwType
-- -- ^ The IDs of any virtual private gateways (VGW) propagating routes,
-- -- each route wrapped in an item element.
-- , rttTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery RouteTableType
-- instance IsXML RouteTableType where
-- xmlPickler = ec2XML
-- data RouteType = RouteType
-- { rtDestinationCidrBlock :: !Text
-- -- ^ The CIDR address block used for the destination match.
-- , rtGatewayId :: !Text
-- -- ^ The ID of a gateway attached to your VPC.
-- , rtInstanceId :: !Text
-- -- ^ The ID of a NAT instance in your VPC.
-- , rtInstanceOwnerId :: !Text
-- -- ^ The owner of the instance.
-- , rtNetworkInterfaceId :: !Text
-- -- ^ The network interface ID.
-- , rtState :: !Text
-- -- ^ The state of the route. The blackhole state indicates that the
-- -- route's target isn't available (for example, the specified
-- -- gateway isn't attached to the VPC, or the specified NAT instance
-- -- has been terminated).
-- , rtOrigin :: !Text
-- -- ^ Describes how the route was created.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery RouteType
-- instance IsXML RouteType where
-- xmlPickler = ec2XML
data RunningInstancesItemType = RunningInstancesItemType
{ riitInstanceId :: !Text
-- ^ The ID of the instance launched.
, riitImageId :: !Text
-- ^ The ID of the AMI used to launch the instance.
, riitInstanceState :: !InstanceStateType
-- ^ The current state of the instance.
, riitPrivateDnsName :: Maybe Text
-- ^ The private DNS name assigned to the instance. This DNS name can
-- only be used inside the Amazon EC2 network. This element remains
-- empty until the instance enters the running state.
, riitDnsName :: Maybe Text
-- ^ The public DNS name assigned to the instance. This element
-- remains empty until the instance enters the running state.
, riitReason :: Maybe Text
-- ^ The reason for the most recent state transition.
-- This might be an empty string.
, riitKeyName :: !Text
-- ^ The key pair name, if this instance was launched with an
-- associated key pair.
, riitAmiLaunchIndex :: !Text
-- ^ The AMI launch index, which can be used to find this instance in
-- the launch group.
, riitProductCodes :: [ProductCodesSetItemType]
-- ^ The product codes attached to this instance.
, riitInstanceType :: InstanceType
-- ^ The instance type.
, riitLaunchTime :: !UTCTime
-- ^ The time the instance was launched.
, riitPlacement :: !PlacementType
-- ^ The location where the instance launched.
, riitKernelId :: Maybe Text
-- ^ The kernel associated with this instance.
, riitRamdiskId :: Maybe Text
-- ^ The RAM disk associated with this instance.
, riitPlatform :: Maybe Text
-- ^ The value is Windows for Windows AMIs; otherwise blank.
, riitMonitoring :: !InstanceMonitoringStateType
-- ^ The monitoring information for the instance.
, riitSubnetId :: Maybe Text
-- ^ The ID of the subnet in which the instance is running.
, riitVpcId :: Maybe Text
-- ^ The ID of the VPC in which the instance is running.
, riitPrivateIpAddress :: Maybe Text
-- ^ The private IP address assigned to the instance.
, riitIpAddress :: Maybe Text
-- ^ The IP address of the instance.
, riitSourceDestCheck :: Maybe Bool
-- ^ Specifies whether to enable an instance launched in a VPC to
-- perform NAT. This controls whether source/destination checking is
-- enabled on the instance. A value of true means checking is
-- enabled, and false means checking is disabled. The value must be
-- false for the instance to perform NAT. For more information, go
-- to NAT Instances in the Amazon Virtual Private Cloud User Guide.
, riitGroupSet :: [GroupItemType]
-- ^ A list of the security groups for the instance.
, riitStateReason :: Maybe StateReasonType
-- ^ The reason for the most recent state transition. See
-- StateReasonType for a listing of supported state change codes.
, riitArchitecture :: !Text
-- ^ The architecture of the image.
, riitRootDeviceType :: !Text
-- ^ The root device type used by the AMI. The AMI can use an Amazon
-- EBS or instance store root device.
, riitRootDeviceName :: Maybe Text
-- ^ The root device name (for example, /dev/sda1).
, riitBlockDeviceMapping :: [InstanceBlockDeviceMappingResponseItemType]
-- ^ Any block device mapping entries for the instance.
, riitInstanceLifecycle :: Maybe Text
-- ^ Indicates whether this is a Spot Instance.
, riitSpotInstanceRequestId :: Maybe Text
-- ^ The ID of the Spot Instance request.
, riitVirtualizationType :: !Text
-- ^ The instance's virtualization type.
, riitClientToken :: Maybe Text
-- ^ The idempotency token you provided when you launched the instance.
, riitTagSet :: [ResourceTagSetItemType]
-- ^ Any tags assigned to the resource.
, riitHypervisor :: !Text
-- ^ The instance's hypervisor type.
, riitNetworkInterfaceSet :: [InstanceNetworkInterfaceSetItemType]
-- ^ The network interfaces for the instance.
, riitIamInstanceProfile :: Maybe IamInstanceProfileResponseType
-- ^ The IAM Instance Profile (IIP) associated with the instance.
, riitEbsOptimized :: !Bool
-- ^ Indicates whether the instance is optimized for EBS I/O.
} deriving (Eq, Ord, Show, Generic)
instance IsXML RunningInstancesItemType where
xmlPickler = ec2ItemXML
-- data SecurityGroupIdSetItemType = SecurityGroupIdSetItemType
-- { sgisitGroupId :: !Text
-- -- ^ The ID of the security group associated with the network
-- -- interface.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery SecurityGroupIdSetItemType
-- instance IsXML SecurityGroupIdSetItemType where
-- xmlPickler = ec2XML
data SecurityGroupItemType = SecurityGroupItemType
{ sgitOwnerId :: !Text
-- ^ The AWS account ID of the owner of the security group.
, sgitGroupId :: !Text
-- ^ The ID of the security group.
, sgitGroupName :: !Text
-- ^ The name of the security group.
, sgitGroupDescription :: !Text
-- ^ A description of the security group.
, sgitVpcId :: Maybe Text
-- ^ [EC2-VPC] The ID of the VPC for the security group.
, sgitIpPermissions :: [IpPermissionType]
-- ^ A list of inbound rules associated with the security group.
, sgitIpPermissionsEgress :: [IpPermissionType]
-- ^ [EC2-VPC] A list of outbound rules associated with the security group.
-- , sgitTagSet :: [ResourceTagSetItemType]
-- -- ^ Any tags assigned to the resource, each one wrapped in an item element.
} deriving (Eq, Ord, Show, Generic)
instance IsXML SecurityGroupItemType where
xmlPickler = ec2ItemXML
-- data SpotDatafeedSubscriptionType = SpotDatafeedSubscriptionType
-- { sdstOwnerId :: !Text
-- -- ^ The AWS account ID of the account.
-- , sdstBucket :: !Text
-- -- ^ The Amazon S3 bucket where the Spot Instance datafeed is located.
-- , sdstPrefix :: !Text
-- -- ^ The prefix that is prepended to datafeed files.
-- , sdstState :: !Text
-- -- ^ The state of the Spot Instance datafeed subscription.
-- , sdstFault :: !SpotInstanceStateFaultType
-- -- ^ The fault codes for the Spot Instance request, if any.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery SpotDatafeedSubscriptionType
-- instance IsXML SpotDatafeedSubscriptionType where
-- xmlPickler = ec2XML
-- data SpotInstanceRequestSetItemType = SpotInstanceRequestSetItemType
-- { sirsitSpotInstanceRequestId :: !Text
-- -- ^ The ID of the Spot Instance request.
-- , sirsitSpotPrice :: !Text
-- -- ^ The maximum hourly price for any Spot Instance launched to
-- -- fulfill the request.
-- , sirsitType :: !Text
-- -- ^ The Spot Instance request type.
-- , sirsitState :: !Text
-- -- ^ The state of the Spot Instance request. Spot bid status
-- -- information can help you track your Spot Instance requests. For
-- -- information, see Tracking Spot Requests with Bid Status Codes in
-- -- the Amazon Elastic Compute Cloud User Guide.
-- , sirsitFault :: !SpotInstanceStateFaultType
-- -- ^ The fault codes for the Spot Instance request, if any.
-- , sirsitStatus :: !SpotInstanceStatusMessageType
-- -- ^ The status code and status message describing the Spot Instance
-- -- request.
-- , sirsitValidFrom :: !UTCTime
-- -- ^ The start date of the request. If this is a one-time request, the
-- -- request becomes active at this date and time and remains active
-- -- until all instances launch, the request expires, or the request
-- -- is canceled. If the request is persistent, the request becomes
-- -- active at this date and time and remains active until it expires
-- -- or is canceled.
-- , sirsitValidUntil :: !UTCTime
-- -- ^ The end date of the request. If this is a one-time request, the
-- -- request remains active until all instances launch, the request is
-- -- canceled, or this date is reached. If the request is persistent,
-- -- it remains active until it is canceled or this date is reached.
-- , sirsitLaunchGroup :: !Text
-- -- ^ The instance launch group. Launch groups are Spot Instances that
-- -- launch together and terminate together.
-- , sirsitAvailabilityZoneGroup :: !Text
-- -- ^ The Availability Zone group. If you specify the same Availability
-- -- Zone group for all Spot Instance requests, all Spot Instances are
-- -- launched in the same Availability Zone.
-- , sirsitLaunchedAvailabilityZone :: !Text
-- -- ^ The Availability Zone in which the bid is launched.
-- , sirsitLaunchSpecification :: !LaunchSpecificationResponseType
-- -- ^ Additional information for launching instances.
-- , sirsitInstanceId :: !Text
-- -- ^ The instance ID, if an instance has been launched to fulfill the
-- -- Spot Instance request.
-- , sirsitCreateTime :: !UTCTime
-- -- ^ The time stamp when the Spot Instance request was created.
-- , sirsitProductDescription :: !Text
-- -- ^ The product description associated with the Spot Instance.
-- , sirsitTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery SpotInstanceRequestSetItemType
-- instance IsXML SpotInstanceRequestSetItemType where
-- xmlPickler = ec2XML
-- data SpotInstanceStateFaultType = SpotInstanceStateFaultType
-- { sisftCode :: !Text
-- -- ^ The reason code for the Spot Instance state change.
-- , sisftMessage :: !Text
-- -- ^ The message for the Spot Instance state change.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery SpotInstanceStateFaultType
-- instance IsXML SpotInstanceStateFaultType where
-- xmlPickler = ec2XML
-- data SpotInstanceStatusMessageType = SpotInstanceStatusMessageType
-- { sismtCode :: !Text
-- -- ^ The status code of the request.
-- , sismtUpdateTime :: !UTCTime
-- -- ^ The time of the most recent status update.
-- , sismtMessage :: !Text
-- -- ^ The description for the status code for the Spot request.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery SpotInstanceStatusMessageType
-- instance IsXML SpotInstanceStatusMessageType where
-- xmlPickler = ec2XML
-- data SpotPriceHistorySetItemType = SpotPriceHistorySetItemType
-- { sphsitInstanceType :: !Text
-- -- ^ The instance type.
-- , sphsitProductDescription :: !Text
-- -- ^ A general description of the AMI.
-- , sphsitSpotPrice :: !Text
-- -- ^ The maximum price you will pay to launch one or more Spot
-- -- Instances.
-- , sphsitTimestamp :: !UTCTime
-- -- ^ The date and time the request was created.
-- , sphsitAvailabilityZone :: !Text
-- -- ^ The Availability Zone.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery SpotPriceHistorySetItemType
-- instance IsXML SpotPriceHistorySetItemType where
-- xmlPickler = ec2XML
data StateReasonType = StateReasonType
{ srtCode :: !Text
-- ^ The reason code for the state change.
, srtMessage :: !Text
-- ^ The message for the state change.
} deriving (Eq, Ord, Show, Generic)
instance IsXML StateReasonType where
xmlPickler = ec2XML
-- data SubnetType = SubnetType
-- { stSubnetId :: !Text
-- -- ^ The ID of the subnet.
-- , stState :: !Text
-- -- ^ The current state of the subnet.
-- , stVpcId :: !Text
-- -- ^ The ID of the VPC the subnet is in.
-- , stCidrBlock :: !Text
-- -- ^ The CIDR block assigned to the subnet.
-- , stAvailableIpAddressCount :: !Integer
-- -- ^ The number of unused IP addresses in the subnet (the IP addresses
-- -- for any stopped instances are considered unavailable).
-- , stAvailabilityZone :: !Text
-- -- ^ The Availability Zone of the subnet.
-- , stDefaultForAz :: !Bool
-- -- ^ Indicates whether this is the default subnet for the Availability
-- -- Zone.
-- , stMapPublicIpOnLaunch :: !Bool
-- -- ^ Indicates whether instances launched in this subnet receive a
-- -- public IP address.
-- , stTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery SubnetType
-- instance IsXML SubnetType where
-- xmlPickler = ec2XML
data TagSetItemType = TagSetItemType
{ tsitResourceId :: !Text
-- ^ The ID of the resource. For example, ami-1a2b3c4d.
, tsitResourceType :: !Text
-- ^ The type of resource.
, tsitKey :: !Text
-- ^ The key of the tag.
, tsitValue :: !Text
-- ^ The value of the tag.
} deriving (Eq, Ord, Show, Generic)
instance IsXML TagSetItemType where
xmlPickler = ec2ItemXML
-- data UserDataType = UserDataType
-- { udtData :: !Text
-- -- ^ The Base64-encoded MIME user data made available to the
-- -- instance(s) in the reservation.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery UserDataType
-- instance IsXML UserDataType where
-- xmlPickler = ec2XML
-- data VolumeStatusItemType = VolumeStatusItemType
-- { vsitVolumeId :: !Text
-- -- ^ The volume ID.
-- , vsitAvailabilityZone :: !Text
-- -- ^ The Availability Zone of the volume.
-- , vsitVolumeStatus :: !VolumeStatusInfoType
-- -- ^ The volume status. The status of each volume is wrapped in an
-- -- item element.
-- , vsitEventSet :: !VolumeStatusEventItemType
-- -- ^ A list of events associated with the volume. Each event is
-- -- wrapped in an item element.
-- , vsitActionSet :: !VolumeStatusActionItemType
-- -- ^ The details of the action. Each action detail is wrapped in an
-- -- item element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VolumeStatusItemType
-- instance IsXML VolumeStatusItemType where
-- xmlPickler = ec2XML
-- data VolumeStatusInfoType = VolumeStatusInfoType
-- { vsitStatus :: !Text
-- -- ^ The status of the volume.
-- , vsitDetails :: !VolumeStatusDetailsItemType
-- -- ^ The details of the volume status. Each volume status detail is
-- -- wrapped in an item type.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VolumeStatusInfoType
-- instance IsXML VolumeStatusInfoType where
-- xmlPickler = ec2XML
-- data VolumeStatusDetailsItemType = VolumeStatusDetailsItemType
-- { vsditName :: !Text
-- -- ^ The name of the volume status.
-- , vsditStatus :: !Text
-- -- ^ The intended status of the volume status.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VolumeStatusDetailsItemType
-- instance IsXML VolumeStatusDetailsItemType where
-- xmlPickler = ec2XML
-- data VolumeStatusEventItemType = VolumeStatusEventItemType
-- { vseitEventType :: !Text
-- -- ^ The type of this event.
-- , vseitEventId :: !Text
-- -- ^ The ID of this event.
-- , vseitDescription :: !Text
-- -- ^ A description of the event.
-- , vseitNotBefore :: !UTCTime
-- -- ^ The earliest start time of the event.
-- , vseitNotAfter :: !UTCTime
-- -- ^ The latest end time of the event.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VolumeStatusEventItemType
-- instance IsXML VolumeStatusEventItemType where
-- xmlPickler = ec2XML
-- data VolumeStatusActionItemType = VolumeStatusActionItemType
-- { vsaitCode :: !Text
-- -- ^ The code identifying the action, for example, enable-volume-io.
-- , vsaitEventType :: !Text
-- -- ^ The event type associated with this action.
-- , vsaitEventId :: !Text
-- -- ^ The ID of the event associated with this action.
-- , vsaitDescription :: !Text
-- -- ^ A description of the action.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VolumeStatusActionItemType
-- instance IsXML VolumeStatusActionItemType where
-- xmlPickler = ec2XML
-- data VpcType = VpcType
-- { vtVpcId :: !Text
-- -- ^ The ID of the VPC.
-- , vtState :: !Text
-- -- ^ The current state of the VPC.
-- , vtCidrBlock :: !Text
-- -- ^ The CIDR block for the VPC.
-- , vtDhcpOptionsId :: !Text
-- -- ^ The ID of the set of DHCP options you've associated with the VPC
-- -- (or default if the default options are associated with the VPC).
-- , vtTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- , vtInstanceTenancy :: !Text
-- -- ^ The allowed tenancy of instances launched into the VPC.
-- , vtIsDefault :: !Bool
-- -- ^ Indicates whether the VPC is the default VPC.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VpcType
-- instance IsXML VpcType where
-- xmlPickler = ec2XML
-- data VpnConnectionOptions = VpnConnectionOptions
-- { vcortStaticRoutesOnly :: !Bool
-- -- ^ Indicates whether the VPN connection uses static routes only.
-- -- Static routes must be used for devices that don't support BGP.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VpnConnectionOptionsResponseType
-- instance IsXML VpnConnectionOptionsResponseType where
-- xmlPickler = ec2XML
-- data VpnConnectionType = VpnConnectionType
-- { vctVpnConnectionId :: !Text
-- -- ^ The ID of the VPN connection.
-- , vctState :: !Text
-- -- ^ The current state of the VPN connection.
-- , vctCustomerGatewayConfiguration :: !Text
-- -- ^ The configuration information for the VPN connection's customer
-- -- gateway (in the native XML format). This element is always
-- -- present in the CreateVpnConnection response; however, it's
-- -- present in the DescribeVpnConnections response only if the VPN
-- -- connection is in the pending or available state.
-- , vctType :: !Text
-- -- ^ The type of VPN connection.
-- , vctCustomerGatewayId :: !Text
-- -- ^ The ID of the customer gateway at your end of the VPN connection.
-- , vctVpnGatewayId :: !Text
-- -- ^ The ID of the virtual private gateway at the AWS side of the VPN
-- -- connection.
-- , vctTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- , vctVgwTelemetry :: !VpnTunnelTelemetryType
-- -- ^ The virtual private gateway. Each gateway is wrapped in an item
-- -- element.
-- , vctOptions :: !VpnConnectionOptionsResponseType
-- -- ^ The option set describing the VPN connection.
-- , vctRoutes :: !VpnStaticRouteType
-- -- ^ The set of static routes associated with a VPN connection.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VpnConnectionType
-- instance IsXML VpnConnectionType where
-- xmlPickler = ec2XML
-- data VpnGatewayType = VpnGatewayType
-- { vgtVpnGatewayId :: !Text
-- -- ^ The ID of the virtual private gateway.
-- , vgtState :: !Text
-- -- ^ The current state of the virtual private gateway.
-- , vgtType :: !Text
-- -- ^ The type of VPN connection the virtual private gateway supports.
-- , vgtAvailabilityZone :: !Text
-- -- ^ The Availability Zone where the virtual private gateway was
-- -- created.
-- , vgtAttachments :: !AttachmentType
-- -- ^ Any VPCs attached to the virtual private gateway, each one
-- -- wrapped in an item element.
-- , vgtTagSet :: !ResourceTagSetItemType
-- -- ^ Any tags assigned to the resource, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VpnGatewayType
-- instance IsXML VpnGatewayType where
-- xmlPickler = ec2XML
-- data VpnStaticRouteType = VpnStaticRouteType
-- { vsrtDestinationCidrBlock :: !Text
-- -- ^ The CIDR block associated with the local subnet of the customer
-- -- data center.
-- , vsrtSource :: !Text
-- -- ^ Indicates how the routes were provided.
-- , vsrtState :: !Text
-- -- ^ The current state of the static route.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VpnStaticRouteType
-- instance IsXML VpnStaticRouteType where
-- xmlPickler = ec2XML
-- data VpnTunnelTelemetryType = VpnTunnelTelemetryType
-- { vtttOutsideIpAddress :: !Text
-- -- ^ The Internet-routable IP address of the virtual private gateway's
-- -- outside interface.
-- , vtttStatus :: !Text
-- -- ^ The status of the VPN tunnel.
-- , vtttLastStatusChange :: !UTCTime
-- -- ^ The date and time of the last change in status.
-- , vtttStatusMessage :: !Text
-- -- ^ If an error occurs, a description of the error.
-- , vtttAcceptedRouteCount :: !Integer
-- -- ^ The number of accepted routes.
-- } deriving (Eq, Ord, Show, Generic)
-- instance IsQuery VpnTunnelTelemetryType
-- instance IsXML VpnTunnelTelemetryType where
-- xmlPickler = ec2XML
data Filter = Filter
{ filterName :: !Text
, filterValue :: [Text]
} deriving (Eq, Ord, Show, Generic)
instance IsQuery Filter
newtype Filters a = Filters { unFilters :: [a] }
deriving (Eq, Ord, Show, Generic)
instance IsQuery a => IsQuery (Filters a)
data TagResourceType
= CustomerGateway
| DhcpOptions
| Image
| Instance
| InternetGateway
| NetworkAcl
| NetworkInterface
| ReservedInstances
| RouteTable
| SecurityGroup
| Snapshot
| SpotInstancesRequest
| Subnet
| Volume
| Vpc
| VpnConnection
| VpnGateway
deriving (Eq, Ord, Read, Generic)
instance Show TagResourceType where
show t = case t of
CustomerGateway -> "customer-gateway"
DhcpOptions -> "dhcp-options"
Image -> "image"
Instance -> "instance"
InternetGateway -> "internet-gateway"
NetworkAcl -> "network-acl"
NetworkInterface -> "network-interface"
ReservedInstances -> "reserved-instances"
RouteTable -> "route-table"
SecurityGroup -> "security-group"
Snapshot -> "snapshot"
SpotInstancesRequest -> "spot-instances-request"
Subnet -> "subnet"
Volume -> "volume"
Vpc -> "vpc"
VpnConnection -> "vpn-connection"
VpnGateway -> "vpn-gateway"
instance IsQuery TagResourceType where
queryPickler = qpPrim
-- = customer-gateway
-- | dhcp-options
-- | image
-- | instance
-- | internet-gateway
-- | network-acl
-- | network-interface
-- | reserved-instances
-- | route-table
-- | security-group
-- | snapshot
-- | spot-instances-request
-- | subnet
-- | volume
-- | vpc
-- | vpn-connection
-- | vpn-gateway
data TagFilter
= TagKey [Text]
-- ^ The tag key.
| TagResourceId [Text]
-- ^ The resource ID.
| TagResourceType [TagResourceType]
-- ^ The resource type.
| TagValue [Text]
-- ^ The tag value.
deriving (Eq, Ord, Show, Generic)
instance IsQuery TagFilter where
queryPickler = QueryPU p u
where
p (TagKey ks) = List $ Pair "Name" (Value "key") : map enc ks
p (TagResourceId is) = List $ Pair "Name" (Value "resource-id") : map enc is
p (TagResourceType ts) = List $ Pair "Name" (Value "resource-type") : map enc' ts
p (TagValue vs) = List $ Pair "Name" (Value "value") : map enc vs
u = undefined
enc = Pair "Value" . Value . encodeUtf8
enc' = Pair "Value" . Value . BS.pack . show
| brendanhay/amazonka-limited | src/Network/AWS/EC2/Types.hs | mpl-2.0 | 102,577 | 0 | 12 | 27,145 | 6,734 | 4,411 | 2,323 | 933 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Instances.SetDeletionProtection
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets deletion protection on the instance.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.setDeletionProtection@.
module Network.Google.Resource.Compute.Instances.SetDeletionProtection
(
-- * REST Resource
InstancesSetDeletionProtectionResource
-- * Creating a Request
, instancesSetDeletionProtection
, InstancesSetDeletionProtection
-- * Request Lenses
, isdpRequestId
, isdpDeletionProtection
, isdpProject
, isdpZone
, isdpResource
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instances.setDeletionProtection@ method which the
-- 'InstancesSetDeletionProtection' request conforms to.
type InstancesSetDeletionProtectionResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instances" :>
Capture "resource" Text :>
"setDeletionProtection" :>
QueryParam "requestId" Text :>
QueryParam "deletionProtection" Bool :>
QueryParam "alt" AltJSON :> Post '[JSON] Operation
-- | Sets deletion protection on the instance.
--
-- /See:/ 'instancesSetDeletionProtection' smart constructor.
data InstancesSetDeletionProtection =
InstancesSetDeletionProtection'
{ _isdpRequestId :: !(Maybe Text)
, _isdpDeletionProtection :: !Bool
, _isdpProject :: !Text
, _isdpZone :: !Text
, _isdpResource :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstancesSetDeletionProtection' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'isdpRequestId'
--
-- * 'isdpDeletionProtection'
--
-- * 'isdpProject'
--
-- * 'isdpZone'
--
-- * 'isdpResource'
instancesSetDeletionProtection
:: Text -- ^ 'isdpProject'
-> Text -- ^ 'isdpZone'
-> Text -- ^ 'isdpResource'
-> InstancesSetDeletionProtection
instancesSetDeletionProtection pIsdpProject_ pIsdpZone_ pIsdpResource_ =
InstancesSetDeletionProtection'
{ _isdpRequestId = Nothing
, _isdpDeletionProtection = True
, _isdpProject = pIsdpProject_
, _isdpZone = pIsdpZone_
, _isdpResource = pIsdpResource_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
isdpRequestId :: Lens' InstancesSetDeletionProtection (Maybe Text)
isdpRequestId
= lens _isdpRequestId
(\ s a -> s{_isdpRequestId = a})
-- | Whether the resource should be protected against deletion.
isdpDeletionProtection :: Lens' InstancesSetDeletionProtection Bool
isdpDeletionProtection
= lens _isdpDeletionProtection
(\ s a -> s{_isdpDeletionProtection = a})
-- | Project ID for this request.
isdpProject :: Lens' InstancesSetDeletionProtection Text
isdpProject
= lens _isdpProject (\ s a -> s{_isdpProject = a})
-- | The name of the zone for this request.
isdpZone :: Lens' InstancesSetDeletionProtection Text
isdpZone = lens _isdpZone (\ s a -> s{_isdpZone = a})
-- | Name or id of the resource for this request.
isdpResource :: Lens' InstancesSetDeletionProtection Text
isdpResource
= lens _isdpResource (\ s a -> s{_isdpResource = a})
instance GoogleRequest InstancesSetDeletionProtection
where
type Rs InstancesSetDeletionProtection = Operation
type Scopes InstancesSetDeletionProtection =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient InstancesSetDeletionProtection'{..}
= go _isdpProject _isdpZone _isdpResource
_isdpRequestId
(Just _isdpDeletionProtection)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy ::
Proxy InstancesSetDeletionProtectionResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Instances/SetDeletionProtection.hs | mpl-2.0 | 5,543 | 0 | 19 | 1,243 | 630 | 374 | 256 | 99 | 1 |
{- ORMOLU_DISABLE -}
-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)
-- Copyright (C) 2014 2015, Julia Longtin (julial@turinglace.com)
-- Copyright (C) 2015 2016, Mike MacHenry (mike.machenry@gmail.com)
-- Released under the GNU AGPLV3+, see LICENSE
-- Allow us to use real types in the type constraints.
{-# LANGUAGE FlexibleContexts #-}
module Graphics.Implicit.Export (writeObject, formatObject, writeSVG, writeSTL, writeBinSTL, writeOBJ, writeTHREEJS, writeGCodeHacklabLaser, writeDXF2, writeSCAD2, writeSCAD3, writePNG) where
import Prelude (FilePath, IO, (.), ($))
-- The types of our objects (before rendering), and the type of the resolution to render with.
import Graphics.Implicit.Definitions (SymbolicObj2, SymbolicObj3, ℝ, Polyline, TriangleMesh, NormedTriangleMesh)
-- functions for outputing a file, and one of the types.
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy.IO as LT (writeFile)
import qualified Data.ByteString.Lazy as LBS (writeFile)
-- Import instances of DiscreteApproxable...
import Graphics.Implicit.Export.DiscreteAproxable (DiscreteAproxable, discreteAprox)
-- Output file formats.
import qualified Graphics.Implicit.Export.PolylineFormats as PolylineFormats (svg, hacklabLaserGCode, dxf2)
import qualified Graphics.Implicit.Export.TriangleMeshFormats as TriangleMeshFormats (stl, binaryStl, jsTHREE)
import qualified Graphics.Implicit.Export.NormedTriangleMeshFormats as NormedTriangleMeshFormats (obj)
import qualified Graphics.Implicit.Export.SymbolicFormats as SymbolicFormats (scad2, scad3)
import qualified Codec.Picture as ImageFormatCodecs (DynamicImage, savePngImage)
-- | Write an object to a file with LazyText IO, using the given format writer function.
writeObject :: (DiscreteAproxable obj aprox)
=> ℝ -- ^ Resolution
-> (aprox -> Text) -- ^ File Format Writer (Function that formats)
-> FilePath -- ^ File Name
-> obj -- ^ Object to render
-> IO () -- ^ Writing Action!
writeObject res formatWriter filename obj =
let
aprox = formatObject res formatWriter obj
in LT.writeFile filename aprox
-- | Serialize an object using the given format writer, which takes the filename and writes to it..
writeObject' :: (DiscreteAproxable obj aprox)
=> ℝ -- ^ Resolution
-> (FilePath -> aprox -> IO ()) -- ^ File Format writer
-> FilePath -- ^ File Name
-> obj -- ^ Object to render
-> IO () -- ^ Writing Action!
writeObject' res formatWriter filename obj =
formatWriter filename (discreteAprox res obj)
-- | Serialize an object using the given format writer. No file target is implied.
formatObject :: (DiscreteAproxable obj aprox)
=> ℝ -- ^ Resolution
-> (aprox -> Text) -- ^ File Format Writer (Function that formats)
-> obj -- ^ Object to render
-> Text -- ^ Result
formatObject res formatWriter = formatWriter . discreteAprox res
writeSVG :: DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()
writeSVG res = writeObject res PolylineFormats.svg
writeDXF2 :: DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()
writeDXF2 res = writeObject res PolylineFormats.dxf2
writeSTL :: DiscreteAproxable obj TriangleMesh => ℝ -> FilePath -> obj -> IO ()
writeSTL res = writeObject res TriangleMeshFormats.stl
writeBinSTL :: DiscreteAproxable obj TriangleMesh => ℝ -> FilePath -> obj -> IO ()
writeBinSTL res file obj = LBS.writeFile file $ TriangleMeshFormats.binaryStl $ discreteAprox res obj
writeOBJ :: DiscreteAproxable obj NormedTriangleMesh => ℝ -> FilePath -> obj -> IO ()
writeOBJ res = writeObject res NormedTriangleMeshFormats.obj
writeTHREEJS :: DiscreteAproxable obj TriangleMesh => ℝ -> FilePath -> obj -> IO ()
writeTHREEJS res = writeObject res TriangleMeshFormats.jsTHREE
writeGCodeHacklabLaser :: DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()
writeGCodeHacklabLaser res = writeObject res PolylineFormats.hacklabLaserGCode
writeSCAD3 :: ℝ -> FilePath -> SymbolicObj3 -> IO ()
writeSCAD3 res filename obj = LT.writeFile filename $ SymbolicFormats.scad3 res obj
writeSCAD2 :: ℝ -> FilePath -> SymbolicObj2 -> IO ()
writeSCAD2 res filename obj = LT.writeFile filename $ SymbolicFormats.scad2 res obj
writePNG :: DiscreteAproxable obj ImageFormatCodecs.DynamicImage => ℝ -> FilePath -> obj -> IO ()
writePNG res = writeObject' res ImageFormatCodecs.savePngImage
| colah/ImplicitCAD | Graphics/Implicit/Export.hs | agpl-3.0 | 4,549 | 0 | 12 | 818 | 977 | 540 | 437 | 57 | 1 |
{-# LANGUAGE DataKinds, DeriveFunctor, FlexibleInstances, GADTs, GeneralizedNewtypeDeriving, MultiParamTypeClasses, ScopedTypeVariables, StandaloneDeriving, TypeFamilies #-}
module Math.Topology.KnotTh.Tangle.TangleDef
( Tangle
, AsTangle(..)
, Tangle'
, Tangle0
, Tangle2
, Tangle4
, Tangle6
, Surgery(..)
, CablingSurgery(..)
, glueToBorder
, emptyPropagatorTangle
, lonerPropagatorTangle
, loopTangle
, zeroTangle
, infinityTangle
, lonerTangle
, lonerProjection
, lonerOverCrossing
, lonerUnderCrossing
, chainTangle
, zipTangles
, zipKTangles
, conwaySum
, tangle'
, OrientedTangle
, OrientedTangle'
) where
import Control.DeepSeq (NFData(..))
import Control.Monad (filterM, foldM, foldM_, forM, forM_, guard, when, (>=>))
import Control.Monad.IfElse (unlessM)
import qualified Control.Monad.ST as ST
import qualified Control.Monad.Reader as Reader
import Data.Bits ((.&.), complement, shiftL, shiftR)
import Data.List (nub, sort, foldl', find)
import qualified Data.Map.Strict as Map
import Data.Proxy (Proxy(..))
import qualified Data.Set as Set
import Data.STRef (STRef, modifySTRef', newSTRef, readSTRef)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Unboxed.Mutable as UMV
import qualified Data.Vector.Primitive as PV
import qualified Data.Vector.Primitive.Mutable as PMV
import GHC.TypeLits (Nat, KnownNat, natVal, CmpNat)
import Text.Printf (printf)
import Math.Topology.KnotTh.Algebra.Dihedral.D4
import Math.Topology.KnotTh.Knotted
import Math.Topology.KnotTh.Knotted.Crossings.Projection
import Math.Topology.KnotTh.Knotted.Crossings.Diagram
import Math.Topology.KnotTh.Knotted.Threads
import Math.Topology.KnotTh.Moves.ModifyDSL
import Math.Topology.KnotTh.Tangle.RootCode
data Tangle a =
Tangle
{ loopsN :: {-# UNPACK #-} !Int
, vertexN :: {-# UNPACK #-} !Int
, involArr :: {-# UNPACK #-} !(PV.Vector Int)
, crossArr :: {-# UNPACK #-} !(V.Vector a)
, legsN :: {-# UNPACK #-} !Int
}
deriving (Functor)
class AsTangle t where
toTangle :: t a -> Tangle a
instance AsTangle Tangle where
toTangle t = t
newtype Tangle' :: Nat -> * -> * where
T :: Tangle a -> Tangle' k a
deriving ( Show
, Functor
, NFData
, AsTangle
, MirrorAction
, TransposeAction
, DartDiagram
, VertexDiagram
, LeggedDiagram
, Knotted
, KnottedDiagram
, Surgery
)
deriving instance (CmpNat 0 k ~ 'LT) => RotationAction (Tangle' k a)
instance DartDiagram' (Tangle' k) where
newtype Dart (Tangle' k) a = D (Dart Tangle a)
instance VertexDiagram' (Tangle' k) where
newtype Vertex (Tangle' k) a = V (Vertex Tangle a)
instance Show (Dart (Tangle' k) a) where
show (D d) = show d
instance (Show a) => Show (Vertex (Tangle' k) a) where
show (V d) = show d
instance CablingSurgery (Tangle' 0) where
cablingSurgery k (T t) = T $ cablingSurgery k t
instance ExplodeKnotted (Tangle' 0) where
type ExplodeType (Tangle' 0) a = (Int, [([(Int, Int)], a)])
explode (T t) = let (f, [], l) = explode t in (f, l)
implode (f, l) = T (implode (f, [], l))
instance (Crossing a) => KnotWithPrimeTest (Tangle' 0) a where
isPrime (T t) = isPrime t
instance (MirrorAction a) => GroupAction D4 (Tangle' 4 a) where
transform g t | reflection g = mirrorIt $ rotateBy (rotation g) t
| otherwise = rotateBy (rotation g) t
type Tangle0 = Tangle' 0
type Tangle2 = Tangle' 2
type Tangle4 = Tangle' 4
type Tangle6 = Tangle' 6
instance (NFData a) => NFData (Tangle a) where
rnf t = rnf (crossArr t) `seq` t `seq` ()
instance (Show a) => Show (Tangle a) where
show = printf "implode %s" . show . explode
instance RotationAction (Tangle a) where
rotationOrder = legsN
rotateByUnchecked !rot tangle =
tangle
{ involArr = PV.create $ do
let l = legsN tangle
n = 4 * vertexN tangle
a = involArr tangle
modify i | i < n = i
| otherwise = n + mod (i - n + rot) l
a' <- PMV.new (n + l)
forM_ [0 .. n - 1] $ \ !i ->
PMV.unsafeWrite a' i $ modify (a `PV.unsafeIndex` i)
forM_ [0 .. l - 1] $ \ !i ->
PMV.unsafeWrite a' (n + mod (i + rot) l) $ modify (a `PV.unsafeIndex` (n + i))
return a'
}
instance (MirrorAction a) => MirrorAction (Tangle a) where
mirrorIt tangle =
tangle
{ involArr = PV.create $ do
let l = legsN tangle
n = 4 * vertexN tangle
a = involArr tangle
modify i | i < n = (i .&. complement 3) + ((-i) .&. 3)
| otherwise = n + mod (n - i) l
a' <- PMV.new (n + l)
forM_ [0 .. n + l - 1] $ \ !i ->
PMV.unsafeWrite a' (modify i) $ modify (a `PV.unsafeIndex` i)
return a'
, crossArr = mirrorIt `fmap` crossArr tangle
}
instance (TransposeAction a) => TransposeAction (Tangle a) where
transposeIt = fmap transposeIt
instance DartDiagram' Tangle where
data Dart Tangle a = Dart !(Tangle a) {-# UNPACK #-} !Int
instance (NFData a) => NFData (Dart Tangle a) where
rnf (Dart t i) = rnf t `seq` rnf i
instance DartDiagram Tangle where
dartOwner (Dart t _) = t
dartIndex (Dart _ i) = i
opposite (Dart t d) = Dart t (involArr t `PV.unsafeIndex` d)
nextCCW (Dart t d) | d >= n = Dart t (n + (d - n + 1) `mod` legsN t)
| otherwise = Dart t ((d .&. complement 3) + ((d + 1) .&. 3))
where n = vertexN t `shiftL` 2
nextCW (Dart t d) | d >= n = Dart t (n + (d - n - 1) `mod` legsN t)
| otherwise = Dart t ((d .&. complement 3) + ((d - 1) .&. 3))
where n = vertexN t `shiftL` 2
nextBy delta (Dart t d) | d >= n = Dart t (n + (d - n + delta) `mod` legsN t)
| otherwise = Dart t ((d .&. complement 3) + ((d + delta) .&. 3))
where n = vertexN t `shiftL` 2
numberOfDarts t = PV.length (involArr t)
numberOfEdges t = PV.length (involArr t) `shiftR` 1
nthDart t i | i < 0 || i >= b = error $ printf "Tangle.nthDart: index %i is out of bounds [0, %i)" i b
| otherwise = Dart t i
where b = PV.length (involArr t)
allDarts t = map (Dart t) [0 .. PV.length (involArr t) - 1]
allEdges t =
foldl' (\ !es !i ->
let j = involArr t `PV.unsafeIndex` i
in if i < j
then (Dart t i, Dart t j) : es
else es
) [] [0 .. PV.length (involArr t) - 1]
dartIndicesRange t = (0, numberOfDarts t - 1)
instance LeggedDiagram Tangle where
numberOfLegs = legsN
nthLeg t i | l == 0 = error "Tangle.nthLeg: tangle has no legs"
| otherwise = Dart t (n + i `mod` l)
where
l = legsN t
n = vertexN t `shiftL` 2
allLegs t =
let n = vertexN t `shiftL` 2
l = legsN t
in map (Dart t) [n .. n + l - 1]
legPlace d@(Dart t i) | isLeg d = i - 4 * vertexN t
| otherwise = error $ printf "Tangle.legPlace: taken from non-leg %s" $ show d
isLeg (Dart t i) = i >= (vertexN t `shiftL` 2)
instance VertexDiagram' Tangle where
data Vertex Tangle a = Vertex !(Tangle a) {-# UNPACK #-} !Int
instance (NFData a) => NFData (Vertex Tangle a) where
rnf (Vertex t i) = rnf t `seq` rnf i
instance VertexDiagram Tangle where
vertexContent (Vertex t i) = crossArr t `V.unsafeIndex` i
mapVertices f t =
t { crossArr =
V.generate (numberOfVertices t) $ \ !i ->
f (nthVertex t $! i + 1)
}
vertexOwner (Vertex t _) = t
vertexIndex (Vertex _ i) = i + 1
vertexDegree _ = 4
numberOfVertices = vertexN
nthVertex t i | i < 1 || i > b = error $ printf "Tangle.nthVertex: index %i is out of bounds [1, %i]" i b
| otherwise = Vertex t (i - 1)
where b = numberOfVertices t
allVertices t = map (Vertex t) [0 .. numberOfVertices t - 1]
nthOutcomingDart (Vertex t c) i = Dart t ((c `shiftL` 2) + (i .&. 3))
outcomingDarts c = map (nthOutcomingDart c) [0 .. 3]
maybeBeginVertex (Dart t d) | d >= n = Nothing
| otherwise = Just $! Vertex t (d `shiftR` 2)
where n = vertexN t `shiftL` 2
beginVertex (Dart t d) | d >= n = error $ printf "Tangle.beginVertex: taken from %i-th leg" (d - n)
| otherwise = Vertex t (d `shiftR` 2)
where n = vertexN t `shiftL` 2
beginPlace (Dart t d) | d >= n = error $ printf "Tangle.beginPlace: taken from %i-th leg" (d - n)
| otherwise = d .&. 3
where n = vertexN t `shiftL` 2
beginPair' d | isDart d = (vertexIndex $ beginVertex d, beginPlace d)
| otherwise = (0, legPlace d)
isDart (Dart t i) = i < (vertexN t `shiftL` 2)
instance Knotted Tangle where
unrootedHomeomorphismInvariant tangle =
totalRootCode (numberOfVertices tangle)
(numberOfLegs tangle)
(numberOfFreeLoops tangle)
(globalTransformations tangle)
(involArr tangle)
(crossArr tangle)
isConnected tangle
| numberOfEdges tangle == 0 && numberOfFreeLoops tangle <= 1 = True
| numberOfFreeLoops tangle /= 0 = False
| otherwise = all (\ (a, b) -> Set.member a con && Set.member b con) edges
where
edges = allEdges tangle
con = dfs Set.empty $ fst $ head edges
dfs vis c | Set.member c vis = vis
| otherwise = foldl' dfs (Set.insert c vis) neigh
where
neigh | isLeg c = [opposite c]
| otherwise = [opposite c, nextCCW c, nextCW c]
numberOfFreeLoops = loopsN
changeNumberOfFreeLoops loops t | loops >= 0 = t { loopsN = loops }
| otherwise = error $ printf "Tangle.changeNumberOfFreeLoops: number of free loops %i is negative" loops
instance ExplodeKnotted Tangle where
type ExplodeType Tangle a = (Int, [(Int, Int)], [([(Int, Int)], a)])
explode tangle =
( numberOfFreeLoops tangle
, map endPair' $ allLegs tangle
, map (\ v -> (map endPair' $ outcomingDarts v, vertexContent v)) $ allVertices tangle
)
implode (loops, brd, list) = ST.runST $ do
when (loops < 0) $
error $ printf "Tangle.implode: number of free loops %i is negative" loops
let l = length brd
when (odd l) $
error $ printf "Tangle.implode: number of legs %i must be even" l
let n = length list
inv <- PMV.new (4 * n + l)
st <- MV.new n
let {-# INLINE write #-}
write !a !c !p = do
let b | c == 0 && p >= 0 && p < l = 4 * n + p
| c == 0 = error $ printf "Tangle.implode: leg index %i is out of bounds [0, %i)" p l
| c < 1 || c > n = error $ printf "Tangle.implode: crossing index %i is out of bounds [1 .. %i]" c n
| p < 0 || p > 3 = error $ printf "Tangle.implode: place index %i is out of bounds [0 .. 3]" p
| otherwise = 4 * (c - 1) + p
when (a == b) $ error $ printf "Tangle.implode: (%i, %i) connected to itself" c p
PMV.unsafeWrite inv a b
when (b < a) $ do
x <- PMV.unsafeRead inv b
when (x /= a) $ error $ printf "Tangle.implode: (%i, %i) points to unconsistent position" c p
forM_ (list `zip` [0 ..]) $ \ ((!ns, !cs), !i) -> do
MV.unsafeWrite st i cs
case ns of
[p0, p1, p2, p3] ->
forM_ [(p0, 0), (p1, 1), (p2, 2), (p3, 3)] $ \ ((!c, !p), !j) ->
write (4 * i + j) c p
_ ->
error $ printf "Tangle.implode: there must be 4 neighbours for every crossing, but found %i for %i-th"
(length ns) (i + 1)
forM_ (brd `zip` [0 ..]) $ \ ((!c, !p), !i) ->
write (4 * n + i) c p
inv' <- PV.unsafeFreeze inv
st' <- V.unsafeFreeze st
return Tangle
{ loopsN = loops
, vertexN = n
, involArr = inv'
, crossArr = st'
, legsN = l
}
instance Show (Dart Tangle a) where
show d | isLeg d = printf "(Leg %i)" $ legPlace d
| otherwise = let (c, p) = beginPair' d
in printf "(Dart %i %i)" c p
instance (Show a) => Show (Vertex Tangle a) where
show v =
printf "(Crossing %i %s [ %s ])"
(vertexIndex v)
(show $ vertexContent v)
(unwords $ map (show . opposite) $ outcomingDarts v)
instance TensorProduct (Tangle a) where
a ⊗ b = horizontalComposition 0 (a, 0) (b, 0)
instance PlanarAlgebra (Tangle a) where
planarDegree = numberOfLegs
planarEmpty = planarLoop 0
planarLoop = toTangle . loopTangle
planarPropagator n | n < 0 = error $ printf "Tangle.planarPropagator: parameter must be non-negative, but %i passed" n
| otherwise =
Tangle
{ loopsN = 0
, vertexN = 0
, involArr = PV.generate (2 * n) (\ i -> 2 * n - 1 - i)
, crossArr = V.empty
, legsN = 2 * n
}
horizontalCompositionUnchecked gl (!tangleA, !posA) (!tangleB, !posB) =
ST.runST $ do
let legsA = numberOfLegs tangleA
legsB = numberOfLegs tangleB
when (gl < 0 || gl > min legsA legsB) $
fail $ printf "Tangle.horizontalComposition: number of legs to glue %i is out of bound" gl
let nA = numberOfVertices tangleA
nB = numberOfVertices tangleB
newL = legsA + legsB - 2 * gl
newC = nA + nB
visited <- UMV.replicate gl False
inv <- do
let {-# INLINE convertA #-}
convertA !x | x < 4 * nA = return $! x
| ml >= gl = return $! 4 * newC + ml - gl
| otherwise = do
UMV.unsafeWrite visited ml True
let ml' = (4 * nB) + ((posB + gl - 1 - ml) `mod` legsB)
convertB $! involArr tangleB `PV.unsafeIndex` ml'
where ml = (x - 4 * nA - posA) `mod` legsA
{-# INLINE convertB #-}
convertB !x | x < 4 * nB = return $! (4 * nA) + x
| ml >= gl = return $! (4 * newC) + (legsA - gl) + (ml - gl)
| otherwise = do
UMV.unsafeWrite visited (gl - 1 - ml) True
let ml' = (4 * nA) + ((posA + gl - 1 - ml) `mod` legsA)
convertA $! involArr tangleA `PV.unsafeIndex` ml'
where ml = (x - 4 * nB - posB) `mod` legsB
cr <- PMV.new (4 * newC + newL)
forM_ [0 .. 4 * nA - 1] $ \ !i ->
convertA (involArr tangleA `PV.unsafeIndex` i)
>>= PMV.unsafeWrite cr i
forM_ [0 .. 4 * nB - 1] $ \ !i ->
convertB (involArr tangleB `PV.unsafeIndex` i)
>>= PMV.unsafeWrite cr (4 * nA + i)
forM_ [0 .. legsA - gl - 1] $ \ !i ->
let i' = (4 * nA) + (posA + gl + i) `mod` legsA
j = (4 * newC) + i
in convertA (involArr tangleA `PV.unsafeIndex` i') >>= PMV.unsafeWrite cr j
forM_ [0 .. legsB - gl - 1] $ \ !i ->
let i' = (4 * nB) + (posB + gl + i) `mod` legsB
j = (4 * newC) + (legsA - gl) + i
in convertB (involArr tangleB `PV.unsafeIndex` i') >>= PMV.unsafeWrite cr j
PV.unsafeFreeze cr
extraLoops <- do
let markA !x =
unlessM (UMV.unsafeRead visited x) $ do
UMV.unsafeWrite visited x True
let xi = (4 * nA) + (posA + x) `mod` legsA
yi = involArr tangleA `PV.unsafeIndex` xi
markB $ (yi - (4 * nA) - posA) `mod` legsA
markB !x =
unlessM (UMV.unsafeRead visited x) $ do
UMV.unsafeWrite visited x True
let xi = (4 * nB) + (posB + gl - 1 - x) `mod` legsB
yi = involArr tangleB `PV.unsafeIndex` xi
markA $ gl - 1 - ((yi - (4 * nB) - posB) `mod` legsB)
foldM (\ !s !i -> do
vis <- UMV.unsafeRead visited i
if vis then return $! s
else markA i >> (return $! s + 1)
) 0 [0 .. gl - 1]
return $!
Tangle
{ loopsN = loopsN tangleA + loopsN tangleB + extraLoops
, vertexN = newC
, involArr = inv
, crossArr = crossArr tangleA V.++ crossArr tangleB
, legsN = newL
}
instance KnottedDiagram Tangle where
isReidemeisterReducible =
any (\ ab ->
let ba = opposite ab
ac = nextCCW ab
in (ac == ba) || (isDart ba && isPassingOver ab == isPassingOver ba && opposite ac == nextCW ba)
) . allOutcomingDarts
tryReduceReidemeisterI tangle = do
d <- find (\ d -> opposite d == nextCCW d) (allOutcomingDarts tangle)
return $! modifyKnot tangle $ do
let ac = nextCW d
ab = nextCW ac
ba = opposite ab
substituteC [(ba, ac)]
maskC [beginVertex d]
tryReduceReidemeisterII tangle = do
abl <- find (\ abl ->
let bal = opposite abl
abr = nextCCW abl
in isDart bal && isPassingOver abl == isPassingOver bal && opposite abr == nextCW bal
) (allOutcomingDarts tangle)
return $! modifyKnot tangle $ do
let bal = opposite abl
ap = threadContinuation abl
aq = nextCW abl
br = nextCCW bal
bs = threadContinuation bal
pa = opposite ap
qa = opposite aq
rb = opposite br
sb = opposite bs
if qa == ap || rb == bs
then if qa == ap && rb == bs
then emitLoopsC 1
else do
when (qa /= ap) $ connectC [(pa, qa)]
when (rb /= bs) $ connectC [(rb, sb)]
else do
if qa == br
then emitLoopsC 1
else connectC [(qa, rb)]
if pa == bs
then emitLoopsC 1
else connectC [(pa, sb)]
maskC [beginVertex abl, beginVertex bal]
reidemeisterIII tangle = do
ab <- allOutcomingDarts tangle
-- \sc /rb \sc /rb
-- \ / \ /
-- cs\ cb bc /br ac\ /ab
-- --------------- /
-- ca\c b/ba ap/a\aq
-- \ / --> / \
-- ac\ /ab cs/c b\br
-- / ---------------
-- ap/a\aq ca/ cb bc \ba
-- / \ / \
-- pa/ \qa /pa \qa
guard $ isDart ab
let ac = nextCCW ab
ba = opposite ab
ca = opposite ac
guard $ isDart ba && isDart ca
let bc = nextCW ba
cb = nextCCW ca
guard $ bc == opposite cb
let a = beginVertex ab
b = beginVertex ba
c = beginVertex ca
guard $ (a /= b) && (a /= c) && (b /= c)
guard $ isPassingOver bc == isPassingOver cb
guard $ let altRoot | isPassingOver ab == isPassingOver ba = ca
| otherwise = bc
in ab < altRoot
let ap = threadContinuation ab
aq = nextCW ab
br = nextCW bc
cs = nextCCW cb
return $! modifyKnot tangle $ do
substituteC [(ca, ap), (ba, aq), (ab, br), (ac, cs)]
connectC [(br, aq), (cs, ap)]
instance (Crossing a) => KnotWithPrimeTest Tangle a where
isPrime tangle = connections == nub connections
where
idm = let faces = directedPathsDecomposition (nextCW, nextCCW)
in Map.fromList $ concatMap (\ (face, i) -> zip face $ repeat i) $ zip faces [(0 :: Int) ..]
connections =
let getPair (da, db) =
let a = idm Map.! da
b = idm Map.! db
in (min a b, max a b)
in sort $ map getPair $ allEdges tangle
directedPathsDecomposition continue =
let processDart (paths, s) d
| Set.member d s = (paths, s)
| otherwise =
let path = containingDirectedPath continue d
nextS = foldl' (flip Set.insert) s path
in (path : paths, nextS)
in fst $ foldl' processDart ([], Set.empty) $ allDarts tangle
containingDirectedPath (adjForward, adjBackward) start =
let walkForward d
| isLeg opp = ([d], False)
| start == nxt = ([d], True)
| otherwise = (d : nextPath, nextCycle)
where
opp = opposite d
nxt = adjForward opp
(nextPath, nextCycle) = walkForward nxt
in case walkForward start of
(forward, True) -> forward
(forward, False) ->
let walkBackward (d, path) | isLeg d = path
| otherwise = let prev = opposite $ adjBackward d
in walkBackward (prev, prev : path)
in walkBackward (start, forward)
class (Knotted k) => Surgery k where
surgery :: Tangle' 4 a -> Vertex k a -> k a
multiSurgery :: k (Tangle' 4 a) -> k a
instance Surgery Tangle where
surgery (T sub) v =
ST.runST $ do
let tangle = vertexOwner v
legs = legsN tangle
nEx = vertexN tangle
nIn = vertexN sub
idx = vertexIndex v - 1
newC = nEx + nIn - 1
visited <- UMV.replicate 4 False
inv <- do
let convertExt !x | x >= 4 * nEx = return $! 4 * (nIn - 1) + x
| x >= 4 * (idx + 1) = return $! x - 4
| x >= 4 * idx = do
let t = x .&. 3
UMV.unsafeWrite visited t True
convertInt $! involArr sub `PV.unsafeIndex` ((4 * nIn) + t)
| otherwise = return $! x
convertInt !x | x >= 4 * nIn = do
let t = x .&. 3
UMV.unsafeWrite visited t True
convertExt $! involArr tangle `PV.unsafeIndex` ((4 * idx) + t)
| otherwise = return $! 4 * (nEx - 1) + x
cr <- PMV.new (4 * newC + legs)
forM_ [0 .. 4 * idx - 1] $ \ !i ->
convertExt (involArr tangle `PV.unsafeIndex` i)
>>= PMV.unsafeWrite cr i
forM_ [4 * (idx + 1) .. 4 * nEx - 1] $ \ !i ->
convertExt (involArr tangle `PV.unsafeIndex` i)
>>= PMV.unsafeWrite cr (i - 4)
forM_ [0 .. 4 * nIn - 1] $ \ !i ->
convertInt (involArr sub `PV.unsafeIndex` i)
>>= PMV.unsafeWrite cr (i + 4 * nEx - 4)
forM_ [0 .. legs - 1] $ \ !leg ->
convertExt (involArr sub `PV.unsafeIndex` ((4 * nEx) + leg))
>>= PMV.unsafeWrite cr ((4 * newC) + leg)
PV.unsafeFreeze cr
extraLoops <- do
let markExt !x =
unlessM (UMV.unsafeRead visited x) $ do
UMV.unsafeWrite visited x True
markInt $ (involArr tangle `PV.unsafeIndex` (4 * idx + x)) .&. 3
markInt !x =
unlessM (UMV.unsafeRead visited x) $ do
UMV.unsafeWrite visited x True
markExt $ (involArr sub `PV.unsafeIndex` (4 * nIn + x)) .&. 3
foldM (\ !s !i -> do
vis <- UMV.unsafeRead visited i
if vis then return $! s
else markExt i >> (return $! s + 1)
) 0 [0 .. 3]
return $!
Tangle
{ loopsN = loopsN tangle + loopsN sub + extraLoops
, vertexN = newC
, involArr = inv
, crossArr = let cr = crossArr tangle
in V.concat [V.take idx cr, V.drop (idx + 1) cr, crossArr sub]
, legsN = legs
}
multiSurgery tangle =
implode
( numberOfFreeLoops tangle
, map oppositeExt $ allLegs tangle
, do
b <- allVertices tangle
c <- allVertices $ vertexContent b
let nb = map (oppositeInt b) $ outcomingDarts c
return (nb, vertexContent c)
)
where
offset = UV.prescanl' (+) 0 $
UV.generate (numberOfVertices tangle) $ \ !i ->
numberOfVertices $ vertexContent $ nthVertex tangle (i + 1)
oppositeInt b u | isLeg v = oppositeExt $ nthOutcomingDart b (legPlace v)
| otherwise = (w, beginPlace v)
where v = opposite u
c = beginVertex v
w = (offset UV.! (vertexIndex b - 1)) + vertexIndex c
oppositeExt u | isLeg v = (0, legPlace v)
| otherwise = oppositeInt c $ nthLeg (vertexContent $ beginVertex v) (beginPlace v)
where v = opposite u
c = beginVertex v
class (Surgery k) => CablingSurgery k where
cablingSurgery :: Int -> k (Tangle a) -> k a
instance CablingSurgery Tangle where
cablingSurgery k tangle = implode (k * numberOfFreeLoops tangle, border, body)
where
n = numberOfVertices tangle
crossSubst =
let substList = do
v <- allVertices tangle
let t = vertexContent v
when (numberOfLegs t /= 4 * k) $
fail "Tangle.tensorSubst: bad number of legs"
return $! t
in V.fromListN (n + 1) $ undefined : substList
crossOffset = UV.fromListN (n + 1) $
0 : scanl (\ !p !i -> p + numberOfVertices (crossSubst V.! i)) 0 [1 .. n]
resolveInCrossing !v !d
| isLeg d =
let p = legPlace d
in resolveOutside (opposite $ nthOutcomingDart v $ p `div` k) (p `mod` k)
| otherwise =
let (c, p) = beginPair' d
in ((crossOffset UV.! vertexIndex v) + c, p)
resolveOutside !d !i
| isLeg d = (0, k * legPlace d + i)
| otherwise =
let (c, p) = beginPair d
in resolveInCrossing c $ opposite $
nthLeg (crossSubst V.! vertexIndex c) (k * p + k - 1 - i)
border = do
d <- allLegOpposites tangle
i <- [0 .. k - 1]
return $! resolveOutside d $ k - 1 - i
body = do
c <- allVertices tangle
let t = crossSubst V.! vertexIndex c
c' <- allVertices t
return (map (resolveInCrossing c) $ incomingDarts c', vertexContent c')
-- | edgesToGlue = 1 edgesToGlue = 2 edgesToGlue = 3
-- ........| ........| ........|
-- (leg+1)-|---------------3 (leg+1)-|---------------2 (leg+1)-|---------------1
-- | +=========+ | +=========+ | +=========+
-- (leg)--|--|-0-\ /-3-|--2 (leg)--|--|-0-\ /-3-|--1 (leg)--|--|-0-\ /-3-|--0
-- ........| | * | | | * | | | * |
-- ........| | / \-2-|--1 (leg-1)-|--|-1-/ \-2-|--0 (leg-1)-|--|-1-/ \ |
-- ........| | 1 | ........| +=========+ | | 2 |
-- ........| | \-----|--0 ........| (leg-2)-|--|-----/ |
-- ........| +=========+ ........| ........| +=========+
glueToBorder :: (AsTangle t) => Int -> (t a, Int) -> a -> Vertex Tangle a
glueToBorder !gl (!tangle0, !lp) !cr | gl < 0 || gl > 4 = error $ printf "glueToBorder: legsToGlue must be in [0 .. 4], but %i found" gl
| gl > oldL = error $ printf "glueToBorder: not enough legs to glue (l = %i, gl = %i)" oldL gl
| otherwise =
flip nthVertex newC $!
Tangle
{ loopsN = numberOfFreeLoops tangle
, vertexN = newC
, involArr = PV.create $ do
inv <- PMV.new (4 * newC + newL)
let {-# INLINE copyModified #-}
copyModified !index !index' =
let y | x < 4 * oldC = x
| ml < oldL - gl = (4 * newC) + 4 - gl + ml
| otherwise = (4 * newC) - 5 + oldL - ml
where
x = involArr tangle `PV.unsafeIndex` index'
ml = (x - 4 * oldC - lp - 1) `mod` oldL
in PMV.unsafeWrite inv index y
forM_ [0 .. 4 * oldC - 1] $ \ !i ->
copyModified i i
forM_ [0 .. gl - 1] $ \ !i ->
copyModified (4 * (newC - 1) + i) (4 * oldC + ((lp - i) `mod` oldL))
forM_ [0 .. 3 - gl] $ \ !i -> do
let a = 4 * (newC - 1) + gl + i
b = 4 * newC + i
PMV.unsafeWrite inv a b
PMV.unsafeWrite inv b a
forM_ [0 .. oldL - 1 - gl] $ \ !i ->
copyModified (4 * newC + i + 4 - gl) (4 * oldC + ((lp + 1 + i) `mod` oldL))
return inv
, crossArr = V.snoc (crossArr tangle) cr
, legsN = newL
}
where tangle = toTangle tangle0
oldL = numberOfLegs tangle
oldC = numberOfVertices tangle
newC = oldC + 1
newL = oldL + 4 - 2 * gl
loopTangle :: Int -> Tangle' 0 a
loopTangle n | n < 0 = error "loopTangle: negative number of loops"
| otherwise =
T Tangle
{ loopsN = n
, vertexN = 0
, involArr = PV.empty
, crossArr = V.empty
, legsN = 0
}
-- TODO: better name?
emptyPropagatorTangle :: Tangle' 2 a
emptyPropagatorTangle =
T Tangle
{ loopsN = 0
, vertexN = 0
, involArr = PV.fromList [1, 0]
, crossArr = V.empty
, legsN = 2
}
-- TODO: better name?
lonerPropagatorTangle :: a -> Tangle' 2 a
lonerPropagatorTangle cr =
T Tangle
{ loopsN = 0
, vertexN = 1
, involArr = PV.fromList [4, 5, 3, 2, 0, 1]
, crossArr = V.singleton cr
, legsN = 2
}
zeroTangle :: Tangle' 4 a
zeroTangle =
T Tangle
{ loopsN = 0
, vertexN = 0
, involArr = PV.fromList [3, 2, 1, 0]
, crossArr = V.empty
, legsN = 4
}
infinityTangle :: Tangle' 4 a
infinityTangle =
T Tangle
{ loopsN = 0
, vertexN = 0
, involArr = PV.fromList [1, 0, 3, 2]
, crossArr = V.empty
, legsN = 4
}
lonerTangle :: a -> Tangle' 4 a
lonerTangle cr =
T Tangle
{ loopsN = 0
, vertexN = 1
, involArr = PV.fromList [4, 5, 6, 7, 0, 1, 2, 3]
, crossArr = V.singleton cr
, legsN = 4
}
lonerProjection :: Tangle' 4 ProjectionCrossing
lonerProjection = lonerTangle ProjectionCrossing
lonerOverCrossing, lonerUnderCrossing :: Tangle' 4 DiagramCrossing
lonerOverCrossing = lonerTangle OverCrossing
lonerUnderCrossing = lonerTangle UnderCrossing
chainTangle :: V.Vector a -> Tangle' 4 a
chainTangle cs | n == 0 = zeroTangle
| otherwise =
T Tangle
{ loopsN = 0
, vertexN = n
, involArr = PV.create $ do
inv <- PMV.new $ 4 * (n + 1)
let connect !a !b = PMV.write inv a b >> PMV.write inv b a
connect 0 (4 * n)
connect 1 (4 * n + 1)
connect (4 * (n - 1) + 2) (4 * n + 2)
connect (4 * (n - 1) + 3) (4 * n + 3)
forM_ [0 .. n - 2] $ \ !i -> do
let c = 4 * i
connect (c + 3) (c + 4)
connect (c + 2) (c + 5)
return inv
, crossArr = cs
, legsN = 4
}
where n = V.length cs
zipTangles :: forall k a. (KnownNat k) => Tangle' k a -> Tangle' k a -> Tangle' 0 a
zipTangles (T a) (T b) =
let l = fromIntegral $ natVal (Proxy :: Proxy k)
in T $ horizontalComposition l (a, 0) (b, 1)
zipKTangles :: Tangle a -> Tangle a -> Tangle' 0 a
zipKTangles a b | l /= l' = error $ printf "zipTangles: arguments must have same number of legs, but %i and %i provided" l l'
| otherwise = T $ horizontalComposition l (a, 0) (b, 1)
where l = numberOfLegs a
l' = numberOfLegs b
-- See http://www.mi.sanu.ac.rs/vismath/sl/l14.htm
conwaySum :: Tangle' 4 a -> Tangle' 4 a -> Tangle' 4 a
conwaySum (T a) (T b) = T $ horizontalComposition 2 (a, 2) (b, 0)
{-# INLINE tangle' #-}
tangle' :: forall k a. (KnownNat k) => Tangle a -> Tangle' k a
tangle' t | l == l' = T t
| otherwise = error $ printf "tangle': tangle expected to have %i legs, but %i presented" l' l
where l = numberOfLegs t
l' = fromIntegral $ natVal (Proxy :: Proxy k)
data CrossingFlag a = Direct !a | Flipped !a | Masked
data MoveState s a =
MoveState
{ stateSource :: !(Tangle a)
, stateMask :: !(MV.STVector s (CrossingFlag a))
, stateCircles :: !(STRef s Int)
, stateConnections :: !(MV.STVector s (Dart Tangle a))
}
{-# INLINE withState #-}
withState :: (MoveState s a -> ST.ST s x) -> ModifyM Tangle a s x
withState f = ModifyTangleM $ do
st <- Reader.ask
Reader.lift (f st)
readMaskST :: MoveState s a -> Vertex Tangle a -> ST.ST s (CrossingFlag a)
readMaskST st c = MV.read (stateMask st) (vertexIndex c)
writeMaskST :: MoveState s a -> Vertex Tangle a -> CrossingFlag a -> ST.ST s ()
writeMaskST st c = MV.write (stateMask st) (vertexIndex c)
reconnectST :: MoveState s a -> [(Dart Tangle a, Dart Tangle a)] -> ST.ST s ()
reconnectST st connections =
forM_ connections $ \ (!a, !b) -> do
when (a == b) $ fail $ printf "reconnect: %s connect to itself" (show a)
MV.write (stateConnections st) (dartIndex a) b
MV.write (stateConnections st) (dartIndex b) a
instance ModifyDSL Tangle where
newtype ModifyM Tangle a s x = ModifyTangleM { unM :: Reader.ReaderT (MoveState s a) (ST.ST s) x }
deriving (Functor, Applicative, Monad)
modifyKnot tangle modification = ST.runST $ do
st <- do
connections <- MV.new (numberOfDarts tangle)
forM_ (allEdges tangle) $ \ (!a, !b) -> do
MV.write connections (dartIndex a) b
MV.write connections (dartIndex b) a
mask <- MV.new (numberOfVertices tangle + 1)
forM_ (allVertices tangle) $ \ v ->
MV.write mask (vertexIndex v) (Direct $ vertexContent v)
circlesCounter <- newSTRef $ numberOfFreeLoops tangle
return MoveState
{ stateSource = tangle
, stateMask = mask
, stateCircles = circlesCounter
, stateConnections = connections
}
Reader.runReaderT (unM modification) st
do
offset <- UMV.new (numberOfVertices tangle + 1)
foldM_ (\ !x !c -> do
msk <- readMaskST st c
case msk of
Masked -> return x
_ -> UMV.write offset (vertexIndex c) x >> (return $! x + 1)
) 1 (allVertices tangle)
let pair d | isLeg d = return $! (,) 0 $! legPlace d
| otherwise = do
let i = beginVertexIndex d
msk <- MV.read (stateMask st) i
off <- UMV.read offset i
case msk of
Direct _ -> return (off, beginPlace d)
Flipped _ -> return (off, 3 - beginPlace d)
Masked -> fail $ printf "Tangle.modifyKnot: %s is touching masked crossing %i at:\n%s" (show d) i (show $ stateSource st)
let opp d = MV.read (stateConnections st) (dartIndex d)
border <- forM (allLegs tangle) (opp >=> pair)
connections <- do
alive <- flip filterM (allVertices tangle) $ \ !c -> do
msk <- readMaskST st c
return $! case msk of
Masked -> False
_ -> True
forM alive $ \ !c -> do
msk <- readMaskST st c
con <- mapM (opp >=> pair) $ outcomingDarts c
return $! case msk of
Direct s -> (con, s)
Flipped s -> (reverse con, s)
Masked -> error "internal error"
circles <- readSTRef (stateCircles st)
return $! implode (circles, border, connections)
aliveCrossings = do
tangle <- withState (return . stateSource)
filterM (fmap not . isMaskedC) $ allVertices tangle
emitLoopsC dn =
withState $ \ !st ->
modifySTRef' (stateCircles st) (+ dn)
oppositeC d = do
when (isDart d) $ do
masked <- isMaskedC $ beginVertex d
when masked $
fail $ printf "Tangle.oppositeC: touching masked crossing when taking from %s" (show d)
withState $ \ s ->
MV.read (stateConnections s) (dartIndex d)
passOverC d =
withState $ \ !st -> do
when (isLeg d) $ fail $ printf "Tangle.passOverC: leg %s passed" (show d)
msk <- readMaskST st $ beginVertex d
case msk of
Masked -> fail $ printf "Tangle.passOverC: touching masked crossing when taking from %s" (show d)
Direct t -> return $! isPassingOver' t (beginPlace d)
Flipped t -> return $! isPassingOver' t (3 - beginPlace d)
maskC crossings =
withState $ \ !st ->
forM_ crossings $ \ !c ->
writeMaskST st c Masked
isMaskedC c =
withState $ \ !st -> do
msk <- readMaskST st c
return $! case msk of
Masked -> True
_ -> False
modifyC needFlip f crossings =
withState $ \ !st ->
forM_ crossings $ \ !c -> do
msk <- readMaskST st c
writeMaskST st c $
case msk of
Direct s | needFlip -> Flipped $ f s
| otherwise -> Direct $ f s
Flipped s | needFlip -> Direct $ f s
| otherwise -> Flipped $ f s
Masked -> error $ printf "Tangle.modifyC: flipping masked crossing %s" (show c)
connectC connections =
withState $ \ !st ->
reconnectST st connections
substituteC substitutions = do
reconnections <- mapM (\ (a, b) -> (,) a `fmap` oppositeC b) substitutions
withState $ \ !st -> do
let source = stateSource st
arr <- MV.new (numberOfDarts source)
forM_ (allEdges source) $ \ (!a, !b) -> do
MV.write arr (dartIndex a) a
MV.write arr (dartIndex b) b
forM_ substitutions $ \ (a, b) ->
if a == b
then modifySTRef' (stateCircles st) (+ 1)
else MV.write arr (dartIndex b) a
(reconnectST st =<<) $ forM reconnections $ \ (a, b) ->
(,) a `fmap` MV.read arr (dartIndex b)
data OrientedTangle a = OrientedTangle !(Tangle a) (Int, UV.Vector Int)
deriving (Functor)
instance DartDiagram' OrientedTangle where
data Dart OrientedTangle a = OrientedDart !(OrientedTangle a) !(Dart Tangle a)
instance DartDiagram OrientedTangle where
dartOwner (OrientedDart t _) = t
dartIndex (OrientedDart _ d) = dartIndex d
opposite (OrientedDart t d) = OrientedDart t (opposite d)
nextCCW (OrientedDart t d) = OrientedDart t (nextCCW d)
nextCW (OrientedDart t d) = OrientedDart t (nextCW d)
nextBy k (OrientedDart t d) = OrientedDart t (nextBy k d)
numberOfDarts (OrientedTangle t _) = numberOfDarts t
numberOfEdges (OrientedTangle t _) = numberOfEdges t
nthDart t@(OrientedTangle t' _) n = OrientedDart t (nthDart t' n)
allDarts t@(OrientedTangle t' _) = map (OrientedDart t) $ allDarts t'
dartIndicesRange (OrientedTangle t _) = dartIndicesRange t
instance Show (Dart OrientedTangle a) where
show (OrientedDart _ d) = show d
instance VertexDiagram' OrientedTangle where
data Vertex OrientedTangle a = OrientedVertex !(OrientedTangle a) !(Vertex Tangle a)
instance VertexDiagram OrientedTangle where
vertexContent (OrientedVertex _ v) = vertexContent v
mapVertices f t@(OrientedTangle t' orient) =
OrientedTangle (mapVertices (f . OrientedVertex t) t') orient
vertexOwner (OrientedVertex t _) = t
vertexIndex (OrientedVertex _ v) = vertexIndex v
vertexDegree _ = 4
nthOutcomingDart (OrientedVertex t v) n = OrientedDart t (nthOutcomingDart v n)
nthIncomingDart (OrientedVertex t v) n = OrientedDart t (nthIncomingDart v n)
numberOfVertices (OrientedTangle t _) = numberOfVertices t
nthVertex t@(OrientedTangle t' _) n = OrientedVertex t (nthVertex t' n)
allVertices t@(OrientedTangle t' _) = map (OrientedVertex t) $ allVertices t'
maybeBeginVertex (OrientedDart t d) = OrientedVertex t `fmap` maybeBeginVertex d
maybeEndVertex (OrientedDart t d) = OrientedVertex t `fmap` maybeEndVertex d
beginVertex (OrientedDart t d) = OrientedVertex t (beginVertex d)
endVertex (OrientedDart t d) = OrientedVertex t (endVertex d)
beginVertexIndex (OrientedDart _ d) = beginVertexIndex d
endVertexIndex (OrientedDart _ d) = endVertexIndex d
beginPlace (OrientedDart _ d) = beginPlace d
endPlace (OrientedDart _ d) = endPlace d
--beginPair :: Dart d a -> (Vertex d a, Int)
--endPair :: Dart d a -> (Vertex d a, Int)
--beginPair' :: Dart d a -> (Int, Int)
--endPair' :: Dart d a -> (Int, Int)
outcomingDarts (OrientedVertex t v) = map (OrientedDart t) $ outcomingDarts v
incomingDarts (OrientedVertex t v) = map (OrientedDart t) $ incomingDarts v
isDart (OrientedDart _ d) = isDart d
instance (Show a) => Show (Vertex OrientedTangle a) where
show (OrientedVertex _ v) = show v
instance Knotted OrientedTangle where
unrootedHomeomorphismInvariant (OrientedTangle t _) =
unrootedHomeomorphismInvariant t
numberOfFreeLoops (OrientedTangle t _) = numberOfFreeLoops t
changeNumberOfFreeLoops n (OrientedTangle t orient) =
OrientedTangle (changeNumberOfFreeLoops n t) orient
isConnected (OrientedTangle t _) = isConnected t
instance OrientedKnotted OrientedTangle Tangle where
dropOrientation (OrientedTangle t _) = t
arbitraryOrientation tangle =
let orientation = ST.runST $ do
visited <- UMV.replicate (numberOfDarts tangle) 0
n <- foldM (\ !sid (!startA, !startB) -> do
let cont d | isLeg d = Nothing
| otherwise = let (v, p) = beginPair d
in Just $! nthOutcomingDart v $! strandContinuation (vertexContent v) p
traceBackward !b = do
let a = opposite b
UMV.write visited (dartIndex a) sid
UMV.write visited (dartIndex b) (-sid)
case cont a of
Nothing -> return True
Just b' | b' == startB -> return False
| otherwise -> traceBackward b'
traceForward !b' =
case cont b' of
Nothing -> return ()
Just a -> do
let b = opposite a
UMV.write visited (dartIndex a) sid
UMV.write visited (dartIndex b) (-sid)
traceForward b
v <- UMV.read visited (dartIndex startA)
if v /= 0
then return $! sid
else do
t <- traceBackward startB
when t $ traceForward startB
return $! sid + 1
) 1 (allEdges tangle)
visited' <- UV.unsafeFreeze visited
return (n - 1, visited')
in OrientedTangle tangle orientation
numberOfStrands (OrientedTangle _ (n, _)) = n
dartOrientation (OrientedDart (OrientedTangle _ (_, x)) d) =
let p = x UV.! dartIndex d
in p > 0
dartStrandIndex (OrientedDart (OrientedTangle _ (_, x)) d) =
let p = x UV.! dartIndex d
in abs p - 1
newtype OrientedTangle' :: Nat -> * -> * where
OT :: OrientedTangle a -> OrientedTangle' k a
deriving ( Functor
{- MirrorAction, TransposeAction, -}
, DartDiagram
, VertexDiagram
, Knotted
)
instance DartDiagram' (OrientedTangle' k) where
newtype Dart (OrientedTangle' k) a = OD (Dart OrientedTangle a)
instance VertexDiagram' (OrientedTangle' k) where
newtype Vertex (OrientedTangle' k) a = OV (Vertex OrientedTangle a)
instance OrientedKnotted (OrientedTangle' k) (Tangle' k) where
dropOrientation (OT t) = T $ dropOrientation t
arbitraryOrientation (T t) = OT $ arbitraryOrientation t
numberOfStrands (OT t) = numberOfStrands t
dartOrientation (OD d) = dartOrientation d
dartStrandIndex (OD d) = dartStrandIndex d
instance (Show a) => Show (Vertex (OrientedTangle' k) a) where
show (OV v) = show v
instance Show (Dart (OrientedTangle' k) a) where
show (OD d) = show d
| mishun/tangles | src/Math/Topology/KnotTh/Tangle/TangleDef.hs | lgpl-3.0 | 49,917 | 745 | 32 | 20,972 | 14,652 | 7,730 | 6,922 | -1 | -1 |
module Type where
import Language.Haskell.Her.HaLay
import ListUtils
import Data.Maybe (mapMaybe, isJust)
import Data.List.Split (splitOn)
import Text.ParserCombinators.Parsec (parse, manyTill, anyChar, try, string, manyTill)
import Data.List (intersperse, isPrefixOf)
import TokenUtils
import Data.Char
type Identifier = String
type Layout = String
type Parameter = (String, Maybe String)
type Type = (Identifier, Layout, [Parameter])
type Data = (Type, [Type])
unwrapType :: String -> Maybe Type
unwrapType [] = Nothing
unwrapType str = unwrapTypeToks $ concat $ ready "" str
unwrapTypeToks :: [Tok] -> Maybe Type
unwrapTypeToks ts = if isInfixCons stripped then toTypeInfix stripped else toType stripped
where
stripped = trimSpaceToken ts
isInfixCons [] = False
isInfixCons (Sym t : ts) = True
isInfixCons (t:ts) = isInfixCons ts
{-|
Convert a token stream to a Type
This function can fail
-}
toType :: [Tok] -> Maybe Type
toType [] = Nothing
toType ts = Just (iden toks, concat (layout toks), (maybeZipNames (params toks) (mapParams (toksOut toks))))
where
-- Zip default names into the type, if they types and names lists have the same length
maybeZipNames ps ns = if length ps == length ns then zipParamNames ps ns else ps
zipParamNames [] [] = []
zipParamNames ((name, _): ps) (n:ns) = (name, (Just n)) : zipParamNames ps ns
-- Attempt to extract default names for variabls
mapParams [] = []
mapParams ('{':'-':xs) = (toEndCom xs) : mapParams xs
mapParams (t:ts) = mapParams ts
toEndCom [] = []
toEndCom ('-':'}':_) = []
toEndCom (t:ts) = t : toEndCom ts
toks = trimSpaceToken ts
-- Grab the types identifier, its an Uppercase string at the start of a data definition
iden (Uid idn : ts) = idn
iden ts = filter (not . isSpace) $ concat $ filter (/="{?}") $ layout (trimSpaceToken ts)
-- Get the layout
-- Some types start with an Uppercase constructor name so we pull that first
layout [] = []
layout (Uid cName : ts) = cName : toLayout ts
layout ts = toLayout ts
-- Then process the rest of the laout by replacing the Upper & Lowecase
-- identifiers with {?}
toLayout [] = []
toLayout (B Sqr ts : tss) = ["["] ++ toLayout ts ++ ["]"] ++ toLayout tss
toLayout (B Rnd ts : tss) = ["("] ++ toLayout ts ++ [")"] ++ toLayout tss
toLayout (T Ty ts : tss) = toLayout ts ++ toLayout tss
toLayout (Lid a : ts) = "{?}" : toLayout ts
toLayout (Uid a : ts) = "{?}" : toLayout (takeLid ts) -- Sometimes UId's are followed by type arguments
toLayout (Com _ : ts) = toLayout ts
toLayout (NL _ : ts) = toLayout ts
toLayout (KW "deriving" : _) = []
toLayout (KW "instance" : _) = []
toLayout (t:ts) = tokOut t : toLayout ts
-- Strip Lowercase identifiers & spaces
takeLid [] = []
takeLid (Lid _ : ts) = takeLid ts
takeLid (Spc _ : ts) = takeLid ts
takeLid ts = ts
-- Extract paramaters from a type string
params (Uid _ : ts) = toParams ts
params ts = toParams ts
toParams [] = []
toParams (KW "deriving" : _) = []
toParams (KW "instance" : _) = []
toParams (B _ ts : tss) = toParams ts ++ toParams tss
toParams (Lid a : ts) = (a, Nothing) : toParams ts
toParams (Com n : Lid a : ts) = (a, Just n) : toParams ts
toParams (Uid a : ts) = (a, Nothing) : toParams ts
toParams (Com n : Uid a : ts) = (a, Just n) : toParams ts
toParams (T Ty ts : tss) = toParams ts ++ toParams tss
toParams (Com _ : ts) = toParams ts
toParams (t:ts) = toParams ts
{-|
Convert a token stream with an inline constructor to a Type
This function can fail
-}
toTypeInfix :: [Tok] -> Maybe Type
toTypeInfix [] = Nothing
toTypeInfix ts = case getInfixCons ts of
Nothing -> Nothing
Just i -> Just (i, "{?} " ++ i ++ " {?}", params i (trimSpaceToken ts))
where
getInfixCons [] = Nothing
getInfixCons (Sym t : ts) = Just t
getInfixCons (t:ts) = getInfixCons ts
params i ts = map toParam $ splitOn [Sym i] ts
toParam t = (trimString (toksOut t), Nothing)
{-|
Convert a constructor, either from ghci or internal, to Data
-}
toData :: [Tok] -> Maybe Data
toData [] = Nothing
toData ts = case left ts of
Nothing -> Nothing
Just (iden, layout, ps) -> Just ((iden, layout, ps), right ts)
where
left ts = unwrapTypeToks $ trimSpaceToken $ seekToDef $ head $ splitEq ts
right ts = mapMaybe (unwrapTypeToks . trimSpaceToken) (splitSym $ concat $ tail $ splitEq ts)
splitEq = splitOn [Sym "="]
splitSym = splitOn [Sym "|"]
seekToDef (KW _ : ts) = seekToDef ts
seekToDef (T Ty ts : _) = ts
seekToDef (Spc _ : ts) = seekToDef ts
seekToDef ts = ts
{-|
Process a constructor received from GHCI
-}
toDataFromGhci :: String -> Maybe Data
toDataFromGhci str = toData $ concat $ ready "" (clean str)
where
clean ss = concat $ map dropDashDash $ filter (not . (isPrefixOf "instance")) $ lines ss
dropDashDash [] = []
dropDashDash ('-' : '-' : _) = []
dropDashDash (t:ts) = t : dropDashDash ts
toDataFromTokens :: [[Tok]] -> Maybe Data
toDataFromTokens toks = undefined
lookupType :: Type -> Maybe Data
lookupType t = lookupType' t dataLib
lookupType' :: Type -> [Data] -> Maybe Data
lookupType' _ [] = Nothing
lookupType' i (t:ts) = if getId i == getIdFromType t then Just t else lookupType' i ts
where
getId (i, _, _) = i
getType (t, _) = t
getIdFromType d = getId (getType d)
{-|
Standard library of common data types
-}
dataLib :: [Data]
dataLib = mapMaybe toDataFromGhci [
"data [] a = [] | {-x-}a : {-xs-}[a]",
"data Bool = False | True",
"data Either a b = Left {-l-}a | Right {-r-}b",
"data Maybe a = Nothing | Just {-x-}a"
]
| DarrenMowat/blackbox | src/Type.hs | unlicense | 6,155 | 59 | 28 | 1,777 | 2,192 | 1,130 | 1,062 | 114 | 34 |
import Control.Monad (replicateM)
import Data.List (foldl1')
import qualified Data.Vector as V
readData n = replicateM n readRow
where
readRow = fmap ((take n) . (map read) . words) getLine
toVectors :: [[Integer]] -> [V.Vector Integer]
toVectors = map V.fromList
diagonalDiff n =
let indices = take n $ zip [n-1,n-2..] [0..]
ixs = zipWith collect indices
collect (i, i2) v = (v V.! i, v V.! i2)
psum (x, y) (a, b) = (x + a, y + b)
pdiff (a, b) = b - a
in abs . pdiff . (foldl1' psum) . ixs
main = do
n <- readLn
xs <- fmap toVectors (readData n)
print $ diagonalDiff n xs
| itsbruce/hackerrank | alg/warmup/diagonalDiff.hs | unlicense | 647 | 1 | 12 | 186 | 320 | 167 | 153 | 18 | 1 |
f :: Int -> String
f = undefined
g :: String -> Char
g = undefined
h :: Int -> Char
h a = g (f a)
data A
data B
data C
q :: A -> B
q = undefined
w :: B -> C
w = undefined
e :: A -> C
e a = w (q a)
data X
data Y
data Z
xz :: X -> Z
xz = undefined
yz :: Y -> Z
yz = undefined
xform :: (X, Y) -> (Z, Z)
xform (a, b) = (xz a, yz b)
-- Mash Until No Good
data W
ywz :: Y -> (W, Z)
ywz = undefined
xy :: X -> Y
xy = undefined
munge :: (x -> y) -> (y -> (w, z)) -> x -> w
munge xy ywz x = fst (ywz (xy x))
divideThenAdd :: Fractional a => a -> a -> a
divideThenAdd x y = (x / y) + 1
| dmvianna/haskellbook | src/Ch05Ex-types-2.hs | unlicense | 597 | 0 | 9 | 184 | 411 | 203 | 208 | -1 | -1 |
class Borked a where
bork :: a -> String
instance Borked Int where
bork = show
instance Borked (Int, Int) where
bork (a, b) = bork a ++ ", " ++ bork b
instance (Borked a, Borked b) => Borked (a, b) where
bork (a, b) = ">>" ++ bork a ++ " " ++ bork b ++ "<<"
| EricYT/Haskell | src/real_haskell/chapter-6/Overlap.hs | apache-2.0 | 280 | 0 | 10 | 81 | 139 | 72 | 67 | 8 | 0 |
module Step
( step
) where
-- 台阶有 N 阶, 每次 1-3 步,总共有多少种走法
step :: Int -> Int
step 1 = 1
step 2 = 2
step 3 = 4
step n = step (n - 1) + step (n - 2) + step (n - 3)
| EricYT/Haskell | src/step.hs | apache-2.0 | 194 | 0 | 9 | 48 | 89 | 47 | 42 | 7 | 1 |
import Data.List.Split (splitOn)
import Data.Ix (inRange)
data Direction =
North
| South
| East
| West
getTurnAndDistance :: String -> (Char, Int)
getTurnAndDistance (dir:distance) = (dir, read distance :: Int)
updatePosition :: (Int, Int) -> Direction -> Int -> (Int, Int)
updatePosition (x, y) North distance = (x, y + distance)
updatePosition (x, y) South distance = (x, y - distance)
updatePosition (x, y) East distance = (x + distance, y)
updatePosition (x, y) West distance = (x - distance, y)
updateDir :: Direction -> Char -> Direction
updateDir North 'R' = East
updateDir North 'L' = West
updateDir East 'R' = South
updateDir East 'L' = North
updateDir South 'R' = West
updateDir South 'L' = East
updateDir West 'R' = North
updateDir West 'L' = South
blocksAway :: (Int, Int) -> Direction -> [String] -> Int
blocksAway (x, y) _ [] = sum $ map abs [x, y]
blocksAway position direction (x:xs) =
let
(turn, distance) = getTurnAndDistance x
newDir = updateDir direction turn
newPos = updatePosition position newDir distance
in
blocksAway newPos newDir xs
type X = Int
type Y = Int
type CoOrd = (X, Y)
isBetween :: Int -> Int -> Int -> Bool
isBetween p1 p2 x = inRange (p1, p2) x || inRange (p2, p1) x
getIntersectionCoordinates :: X -> X -> X -> Y -> Y -> Y -> Maybe CoOrd
getIntersectionCoordinates x1 x2 x y1 y2 y =
if isBetween x1 x2 x && isBetween y1 y2 y
then Just (x, y)
else Nothing
getIntersection :: CoOrd -> CoOrd -> (CoOrd, CoOrd) -> Maybe CoOrd
getIntersection (x1, y1) (x2, y2) ((px1, py1), (px2, py2))
| x1 == x2 && py1 == py2 = getIntersectionCoordinates px1 px2 x1 y1 y2 py1
| y1 == y2 && px1 == px2 = getIntersectionCoordinates x1 x2 px1 py1 py2 y1
| otherwise = Nothing
getIntersectionFromList :: CoOrd -> CoOrd -> [(CoOrd, CoOrd)] -> Maybe CoOrd
getIntersectionFromList start end [] = Nothing
getIntersectionFromList start end (x:xs) =
case getIntersection start end x of
Nothing -> getIntersectionFromList start end xs
Just pos -> Just pos
blocksAwayOfCross :: CoOrd -> Direction -> [(CoOrd, CoOrd)] -> [String] -> Int
blocksAwayOfCross position direction paths (x:xs) =
let
(turn, distance) = getTurnAndDistance x
newDir = updateDir direction turn
newPos = updatePosition position newDir distance
in
case getIntersectionFromList position newPos $ drop 2 paths of
Nothing -> blocksAwayOfCross newPos newDir ((position, newPos):paths) xs
Just (x, y) -> sum $ map abs [x, y]
main1 :: IO()
main1 = do
str <- getLine
putStrLn . show $ blocksAway (0,0) North $ splitOn ", " str
main2 :: IO()
main2 = do
str <- getLine
putStrLn . show $ blocksAwayOfCross (0,0) North [] $ splitOn ", " str
| craigbilner/advent-of-code-2016 | day-1.hs | apache-2.0 | 2,867 | 6 | 13 | 713 | 1,143 | 599 | 544 | 69 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Control.Exception as E
import Control.Lens
import Data.Aeson.Lens
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Lazy.Builder as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import HTMLEntities.Decoder
import Network.HTTP.Client hiding (responseBody)
import Network.HTTP.Types (urlEncode)
import Network.SimpleIRC
import Network.SimpleIRC.Messages.Lens
import Network.Wreq
encodePath :: String -> String
encodePath = B.unpack . urlEncode False . B.pack
translate :: String -> String -> String -> IO (Maybe B.ByteString)
translate f t p = do
resp <- E.try $ get ("https://glosbe.com/gapi/translate?from=" ++ encodePath f ++ "&dest=" ++ encodePath t ++ "&format=json&phrase=" ++ encodePath p ++ "&pretty=true") :: IO (Either E.SomeException (Response BL.ByteString))
case resp of
Left err -> return (Just ("An error occurred while contacting the API: " <> (B.pack . show $ err)))
Right resp' -> do
let body = resp' ^. responseBody . to BL.toStrict
word1 = body ^? key "tuc" . nth 0 . key "phrase" . key "text" . _String . to T.encodeUtf8
defn1 = body ^.. key "tuc" . nth 0 . key "meanings" . values . key "text" . _String . to T.encodeUtf8
defnitionTuple = T.encodeUtf8 . TL.toStrict . T.toLazyText . htmlEncodedText . T.pack . show . zip [(1 :: Integer)..] $ defn1
return $ fmap (\x -> x <> " " <> defnitionTuple) word1
onMessage :: EventFunc
onMessage s m = genResponse (m ^. msg . to B.unpack)
where
listToTuple (x:y:zs) = Just (x, y, zs)
listToTuple _ = Nothing
genResponse (stripPrefix ":translate " -> Just (listToTuple . words -> Just (fromLang, toLang, unwords -> phrase))) =
generateTranslation fromLang toLang phrase
genResponse (stripPrefix ":tr " -> Just (listToTuple . words -> Just (fromLang, toLang, unwords -> phrase))) =
generateTranslation fromLang toLang phrase
genResponse _ = return ()
generateTranslation fromLang toLang phrase = do
translation <- translate fromLang toLang phrase
case translation of
Just t -> sendMsg s (fromJust . mChan $ m) t
Nothing -> sendMsg s (fromJust . mChan $ m) "Either an error occurred or no translation was found."
ircEvents :: [IrcEvent]
ircEvents = [(Privmsg onMessage)]
freenode :: IrcConfig
freenode = (mkDefaultConfig "195.154.200.232" "traductor") { cChannels = ["#dagd", "#qsolog"]
, cEvents = ircEvents
}
main :: IO (Either IOError MIrc)
main = connect freenode False True
| relrod/traductor | src/Main.hs | bsd-2-clause | 2,865 | 0 | 22 | 637 | 907 | 482 | 425 | -1 | -1 |
-- |
-- Module : Prose.Segmentation.Words
-- Copyright : (c) 2014–2015 Antonio Nikishaev
--
-- License : BSD-style
-- Maintainer : me@lelf.lu
-- Stability : experimental
--
--
{-# LANGUAGE TypeOperators, DeriveFunctor, FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
module Prose.Segmentation.Words where
import Prose.CharSet as CSet
import Prose.CharSet (CharSet)
import qualified Data.CharSet.Unicode as Unicode
import Prose.Segmentation.Common
import Data.Attoparsec.Text hiding (Result)
import Data.Attoparsec.Combinator
import Control.Applicative
import Control.Arrow
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Internal as TI
import Data.List
import Data.Function
import Data.Either (rights)
import Data.Ord (comparing)
import Data.Monoid
import Control.Monad
import qualified Data.Attoparsec.Internal.Types as A
import Prose.Internal.Missings (hebrewLetter,numeric,aLetter,
midNum,katakana,graphemeExtend)
-- UAX#29, Unicode 8.0.0
data RuleTerm = [CharSet] :× [CharSet] -- do not break
| [CharSet] :÷ [CharSet] -- do break
infix 0 :×,:÷
newline = (⊙)['\x000B','\x000C','\x0085','\x2028','\x2029']
midNumLet = (⊙)['\x002E','\x2018','\x2019','\x2024','\xFE52','\xFF07','\xFF0E']
midLetter = (⊙)['\x00B7','\x0387','\x05F4','\x2027','\x003A',
'\xFE13','\xFE55','\xFF1A','\x02D7']
singleQuote = CSet.singleton '\x0027'
doubleQuote = CSet.singleton '\x0022'
ahLetter = aLetter ∪ hebrewLetter
midNumLetQ = midNumLet ∪ singleQuote
extendNumLet = Unicode.connectorPunctuation
regionalIndicator = (⊙)['\x1F1E6'..'\x1F1FF']
charOf :: CharSet -> Parser Char
charOf = satisfy . flip CSet.member
{-
data ExtendedParser a = ExtendedParser { unExtendedParser :: Parser a,
aux :: Parser a }
deriving Functor
extend :: Parser Char -> ExtendedParser Char
extend p = ExtendedParser p (char 'x')
instance Applicative (ExtendedParser) where
ExtendedParser f m <*> ExtendedParser p n = ExtendedParser (f <*> (n *> p *> n)) (m<*>n)
-- ExtendedParser f m *> ExtendedParser p n = ExtendedParser (f *> n *> p *> n) n
pure v = ExtendedParser (pure v) (aux (pure v))
-}
-- UAX#29 4.1.1
data Rule a = SimpleRule a
| ExtendedRule a -- those have to be extended as per UAX#29:6.2 (see rule WB4 below)
rulesSimple = map SimpleRule [
-- sot :÷ -- WB1
-- :÷ eot -- WB2
[cr] :× [lf], -- WB3li
[newline ∪ cr ∪ lf] :÷ [whatever], -- WB3a
[whatever] :÷ [newline ∪ cr ∪ lf], -- WB3b
[(¬)sep] :× [aux] -- WB4 X (Extend ∪ Format)* → X
]
rulesExtended = map ExtendedRule [
[ahLetter] :× [ahLetter], -- WB5
[ahLetter] :× [midLetter ∪ midNumLetQ, ahLetter], -- WB6
[ahLetter, midLetter ∪ midNumLetQ] :× [ahLetter], -- WB7
[hebrewLetter] :× [singleQuote], -- WB7a
[hebrewLetter] :× [doubleQuote, hebrewLetter], -- WB7b
[hebrewLetter, doubleQuote] :× [hebrewLetter], -- WB7c
[numeric] :× [numeric], -- WB8
[ahLetter] :× [numeric], -- WB9
[numeric] :× [ahLetter], -- WB10
[numeric, midNum ∪ midNumLetQ] :× [numeric], -- WB11
[numeric] :× [midNum ∪ midNumLetQ, numeric], -- WB12
[katakana] :× [katakana], -- WB13
[ahLetter ∪ numeric
∪ katakana ∪ extendNumLet] :× [extendNumLet], -- WB13a
[extendNumLet] :× [ahLetter ∪ numeric ∪ katakana], -- WB13b
[regionalIndicator] :× [regionalIndicator], -- WB13c
[whatever] :÷ [whatever] -- WB14
]
rulesWord = rulesSimple <> rulesExtended
aux = extend ∪ format
where format = Unicode.format ∖ (⊙)['\x200B','\x200C','\x200D']
extend = graphemeExtend ∪ Unicode.spacingCombiningMark
auxRule = charOf aux
sep = (⊙)['\x0085','\x2028','\x2029']
-- | Current parser position (in 16-bit words, NOT in code points).
getPos :: Parser Int
getPos = A.Parser $ \t pos more _ succ -> succ t pos more (A.fromPos pos)
data Result = Break | Don'tBreak deriving (Show,Eq)
isBreak :: [Result] -> Bool
isBreak brks | (Break:_) <- brks = True
| otherwise = False
-- split :: Text -> [Int] -> [Text]
-- split txt [] = [txt]
-- split txt (s:ss) = t : split rest (map (subtract s) ss)
-- where (t,rest) = T.splitAt s txt
-- | >>> split "abc🐧" [1,3]
-- ["a","bc","\128039"]
split :: Text -> [Int] -> [Text]
split t ss = split0 t (0:ss)
split0 txt@(TI.Text a _ end) [s] = [TI.Text a s (end-s)]
split0 txt@(TI.Text a _ _) (s1:s2:ss) = t : split0 txt (s2:ss)
where t = TI.Text a s1 (s2-s1)
segment :: [Char] -> [[Char]]
segment = map T.unpack . segmentT . T.pack
segmentT :: Text -> [Text]
segmentT str = split str -- split on
. map fst -- indeces where there’s a break
. filter snd
. map (second isBreak) -- (Int, break here? :: Bool)
. map (\gr@((_,i):_) -> (i, map fst gr)) -- (Int, results in order :: [Result])
. groupBy ((==) `on` snd)
. sortBy (comparing snd) -- sort and group on
$ concat [ map (fmap (+i)) $ look str' -- stream of (Result,Int)
-- (not necessary in order)
| str' @(TI.Text _ i _) <- T.tails str ] -- going code point by code point
-- | Results of all rules that’s matched (at the beginning of the string)
look str = rights . map (lookRule str) $ rulesWord
-- | Apply the specific rule at the beginning of the string
lookRule :: Text -> Rule RuleTerm -> Either String (Result,Int)
lookRule str rule = parseOnly (toParser rule) str
where toParser0 f (a :× b) = (Don'tBreak,) <$> parserOf (lsParser f a) (lsParser f b)
toParser0 f (a :÷ b) = (Break,) <$> parserOf (lsParser f a) (lsParser f b)
toParser (SimpleRule r) = toParser0 simParser r
toParser (ExtendedRule r) = toParser0 augParser r
parserOf pa pb = pa *> lookAhead pb *> getPos
lsParser f = foldr1 (*>) . map f
simParser c = charOf c
augParser c = charOf c <* many auxRule -- WB4
| llelf/prose | Prose/Segmentation/Words.hs | bsd-3-clause | 7,183 | 1 | 15 | 2,471 | 1,604 | 921 | 683 | 103 | 3 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 711
{-# LANGUAGE PatternSynonyms #-}
#endif
#ifndef MIN_VERSION_binary
#define MIN_VERSION_binary(x, y, z) 0
#endif
module Distribution.Compat.Binary
( decodeOrFailIO
#if __GLASGOW_HASKELL__ >= 708 || MIN_VERSION_binary(0,7,0)
, module Data.Binary
#else
, Binary(..)
, decode, encode
#endif
) where
#if __GLASGOW_HASKELL__ < 706
import Prelude hiding (catch)
#endif
import Control.Exception (catch, evaluate)
#if __GLASGOW_HASKELL__ >= 711
import Control.Exception (pattern ErrorCall)
#else
import Control.Exception (ErrorCall(..))
#endif
import Data.ByteString.Lazy (ByteString)
#if __GLASGOW_HASKELL__ >= 708 || MIN_VERSION_binary(0,7,0)
import Data.Binary
#else
import Data.Binary.Get
import Data.Binary.Put
import Distribution.Compat.Binary.Class
import Distribution.Compat.Binary.Generic ()
-- | Decode a value from a lazy ByteString, reconstructing the original structure.
--
decode :: Binary a => ByteString -> a
decode = runGet get
-- | Encode a value using binary serialisation to a lazy ByteString.
--
encode :: Binary a => a -> ByteString
encode = runPut . put
{-# INLINE encode #-}
#endif
decodeOrFailIO :: Binary a => ByteString -> IO (Either String a)
decodeOrFailIO bs =
catch (evaluate (decode bs) >>= return . Right)
$ \(ErrorCall str) -> return $ Left str
| sopvop/cabal | Cabal/Distribution/Compat/Binary.hs | bsd-3-clause | 1,374 | 0 | 12 | 229 | 166 | 100 | 66 | 22 | 1 |
{-# LANGUAGE ExistentialQuantification, ViewPatterns, OverloadedStrings, NoMonomorphismRestriction, ScopedTypeVariables #-}
module RPC (Connection, Handler,
newConnectionHandles, newConnectionCommand,
registerMethodHandler, callMethod) where
import qualified Data.Aeson as A
import qualified Data.HashTable as H
import qualified Control.Concurrent.MVar as MV
import qualified Control.Exception as E
import qualified System.Process as P
import Control.Monad (when)
import System.IO (hPutStrLn, stderr)
import Control.Concurrent (forkIO)
import Data.Hashable (Hashable(hash))
import Control.Applicative (Alternative((<|>)))
import Control.Monad (guard)
import GHC.IO.Handle (Handle)
import RPC.Internal.IO (mkHandler)
import RPC.Internal.Types (Response(Response), Request(Request), Notification(Notification), parseM)
data Connection = Connection { conn_send :: A.Value -> IO (),
conn_pending :: H.HashTable A.Value (A.Value -> IO ()),
conn_counter :: IO Integer,
conn_methods :: H.HashTable String Handler}
data Handler = forall a b . (A.FromJSON a, A.ToJSON b) => Handler (a -> IO b)
registerMethodHandler :: (A.FromJSON a, A.ToJSON b) => Connection -> String -> (a -> IO b) -> IO ()
registerMethodHandler conn name handler = H.insert (conn_methods conn) name (Handler handler)
callMethod :: (A.FromJSON a, A.ToJSON b) => Connection -> String -> b -> IO a
callMethod conn name a =
do
idNum <- (conn_counter conn)
let id = A.toJSON idNum
var <- MV.newEmptyMVar
E.bracket_
(H.insert (conn_pending conn) id (MV.putMVar var))
(H.delete (conn_pending conn) id)
(do
conn_send conn (A.toJSON (Request (A.toJSON id) name [a]))
response <- MV.takeMVar var
-- TODO: make error reporting more thorough
-- current view is for tutoring only
parseM ((do
Response _ A.Null result <- A.parseJSON response
return (return result))
<|> (do
Response _ error A.Null <- A.parseJSON response
guard (error /= A.Null)
return (fail ("Service failed: " ++ show error))
<|> (fail ("Cannot recognize response: " ++ show response)))))
newConnectionHandles :: Bool -> Handle -> Handle -> IO Connection
newConnectionHandles debug input output =
do
let (handle, send, close) = mkHandler input output
pending <- H.new (==) (fromInteger . toInteger . hash)
methods <- H.new (==) (fromInteger . toInteger . hash)
writeVar <- MV.newEmptyMVar
counter <- MV.newMVar 0
let
writer =
do
value <- MV.takeMVar writeVar
when debug $ hPutStrLn stderr ("Writing: " ++ show value)
send value
when debug $ hPutStrLn stderr ("Written")
writer
reader =
do
handle (\v -> do
when debug $ hPutStrLn stderr ("Read: " ++ show v)
dispatch conn v)
conn = Connection {
conn_send = (MV.putMVar writeVar),
conn_pending = pending,
conn_counter = MV.modifyMVar counter (\v -> return (v + 1, v)),
conn_methods = methods }
forkIO reader
forkIO writer
return conn
newConnectionCommand :: Bool -> P.CmdSpec -> IO Connection
newConnectionCommand debug cmdSpec =
do
(Just inH, Just outH, Nothing, process) <- P.createProcess $ P.CreateProcess {
P.cmdspec = cmdSpec,
P.cwd = Nothing,
P.env = Nothing,
P.std_in = P.CreatePipe,
P.std_out = P.CreatePipe,
P.std_err = P.Inherit,
P.close_fds = True,
P.create_group = False}
newConnectionHandles debug outH inH
dispatch conn value =
parseM ((do
Notification val <- A.parseJSON value
(fail "notifications not supported"))
<|> (do
Request id name [paramValue] <- A.parseJSON value
return (do
handlerMb <- H.lookup (conn_methods conn) name
case handlerMb of
Just (Handler handler) -> E.catch (handle id paramValue handler) (\err -> sendError id (show (err :: E.SomeException)))
Nothing -> sendError id ("Method \"" ++ name ++ "\" not found")))
<|> (do
Response id _ (_ :: A.Value) <- A.parseJSON value
return (do
rhMb <- H.lookup (conn_pending conn) id
case rhMb of
Just rh -> rh value
Nothing -> fail ("Unknown request id:" ++ show id))))
where
sendError id err = conn_send conn (A.toJSON (Response id (A.toJSON err) A.Null))
handle id paramValue handler =
parseM (do
param <- A.parseJSON paramValue
return (do
result <- handler param
conn_send conn (A.toJSON (Response id A.Null result))))
{-
_test1 r w = do
c <- newConnection False r w
registerMethodHandler c "m1" (undefined :: Int -> IO String)
registerMethodHandler c "m2" (undefined :: String -> IO Int)
m3 <- (getMethod c "m3" :: IO (Int -> IO String))
m4 <- (getMethod c "m4" :: IO (String -> IO Int))
return c
-}
| max630/json-exec | RPC.hs | bsd-3-clause | 5,552 | 0 | 26 | 1,838 | 1,621 | 832 | 789 | 112 | 3 |
module Git
( gitExec
, gitExec_
) where
import Control.Concurrent
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import System.Exit
import System.IO
import System.Process
------------------------------------------------------------------------
-- | Runs a git command on a repository and returns the stdout
gitExec :: FilePath -> [ByteString] -> IO ByteString
gitExec repo args = do
result <- process repo "git" args
case result of
(ExitSuccess, out, _) -> return out
(ExitFailure code, out, err) -> error (errMsg code out err)
where
errMsg = formatErrorMsg $ "git " ++ (unwords $ map B.unpack args)
gitExec_ :: FilePath -> [ByteString] -> IO ()
gitExec_ repo args = gitExec repo args >> return ()
------------------------------------------------------------------------
-- | Formats and error message based on the exit code, stdout and stderr
-- from a process execution
formatErrorMsg :: String -> Int -> B.ByteString -> B.ByteString -> String
formatErrorMsg cmd code out err = concat
[ "$ ", cmd, "\n"
, B.unpack out
, B.unpack err
, "(exit code was ", show code, ")" ]
------------------------------------------------------------------------
-- Process interaction
-- | Exit code, stdout, stderr
type ProcessOutput = (ExitCode, ByteString, ByteString)
-- | Runs a process and reads the output
process :: FilePath -- ^ working directory
-> FilePath -- ^ command to run
-> [ByteString] -- ^ any arguments
-> IO ProcessOutput
process wd cmd args = do
(Just inH, Just outH, Just errH, pid) <-
createProcess (proc cmd $ map B.unpack args)
{ cwd = Just wd
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe }
outM <- forkGetContents outH
errM <- forkGetContents errH
hClose inH
ex <- waitForProcess pid
out <- readMVar outM
err <- readMVar errM
return (ex, out, err)
forkGetContents :: Handle -> IO (MVar ByteString)
forkGetContents h = do
m <- newEmptyMVar
forkIO $ do
bs <- B.hGetContents h
putMVar m bs
return m
| jystic/mothership | src/Git.hs | bsd-3-clause | 2,242 | 0 | 13 | 577 | 580 | 303 | 277 | 50 | 2 |
{-# OPTIONS -cpp #-}
------------------------------------------------------------------
-- A primop-table mangling program --
------------------------------------------------------------------
module Main where
import Parser
import Syntax
import Data.Char
import Data.List
import Data.Maybe ( catMaybes )
import System.Environment ( getArgs )
vecOptions :: Entry -> [(String,String,Int)]
vecOptions i =
concat [vecs | OptionVector vecs <- opts i]
desugarVectorSpec :: Entry -> [Entry]
desugarVectorSpec i@(Section {}) = [i]
desugarVectorSpec i = case vecOptions i of
[] -> [i]
vos -> map genVecEntry vos
where
genVecEntry :: (String,String,Int) -> Entry
genVecEntry (con,repCon,n) =
case i of
PrimOpSpec {} ->
PrimVecOpSpec { cons = "(" ++ concat (intersperse " " [cons i, vecCat, show n, vecWidth]) ++ ")"
, name = name'
, prefix = pfx
, veclen = n
, elemrep = con ++ "ElemRep"
, ty = desugarTy (ty i)
, cat = cat i
, desc = desc i
, opts = opts i
}
PrimTypeSpec {} ->
PrimVecTypeSpec { ty = desugarTy (ty i)
, prefix = pfx
, veclen = n
, elemrep = con ++ "ElemRep"
, desc = desc i
, opts = opts i
}
_ ->
error "vector options can only be given for primops and primtypes"
where
vecCons = con++"X"++show n++"#"
vecCat = conCat con
vecWidth = conWidth con
pfx = lowerHead con++"X"++show n
vecTyName = pfx++"PrimTy"
name' | Just pre <- splitSuffix (name i) "Array#" = pre++vec++"Array#"
| Just pre <- splitSuffix (name i) "OffAddr#" = pre++vec++"OffAddr#"
| Just pre <- splitSuffix (name i) "ArrayAs#" = pre++con++"ArrayAs"++vec++"#"
| Just pre <- splitSuffix (name i) "OffAddrAs#" = pre++con++"OffAddrAs"++vec++"#"
| otherwise = init (name i)++vec ++"#"
where
vec = con++"X"++show n
splitSuffix :: Eq a => [a] -> [a] -> Maybe [a]
splitSuffix s suf
| drop len s == suf = Just (take len s)
| otherwise = Nothing
where
len = length s - length suf
lowerHead s = toLower (head s) : tail s
desugarTy :: Ty -> Ty
desugarTy (TyF s d) = TyF (desugarTy s) (desugarTy d)
desugarTy (TyC s d) = TyC (desugarTy s) (desugarTy d)
desugarTy (TyApp SCALAR []) = TyApp (TyCon repCon) []
desugarTy (TyApp VECTOR []) = TyApp (VecTyCon vecCons vecTyName) []
desugarTy (TyApp VECTUPLE []) = TyUTup (replicate n (TyApp (TyCon repCon) []))
desugarTy (TyApp tycon ts) = TyApp tycon (map desugarTy ts)
desugarTy t@(TyVar {}) = t
desugarTy (TyUTup ts) = TyUTup (map desugarTy ts)
conCat :: String -> String
conCat "Int8" = "IntVec"
conCat "Int16" = "IntVec"
conCat "Int32" = "IntVec"
conCat "Int64" = "IntVec"
conCat "Word8" = "WordVec"
conCat "Word16" = "WordVec"
conCat "Word32" = "WordVec"
conCat "Word64" = "WordVec"
conCat "Float" = "FloatVec"
conCat "Double" = "FloatVec"
conCat con = error $ "conCat: unknown type constructor " ++ con ++ "\n"
conWidth :: String -> String
conWidth "Int8" = "W8"
conWidth "Int16" = "W16"
conWidth "Int32" = "W32"
conWidth "Int64" = "W64"
conWidth "Word8" = "W8"
conWidth "Word16" = "W16"
conWidth "Word32" = "W32"
conWidth "Word64" = "W64"
conWidth "Float" = "W32"
conWidth "Double" = "W64"
conWidth con = error $ "conWidth: unknown type constructor " ++ con ++ "\n"
main :: IO ()
main = getArgs >>= \args ->
if length args /= 1 || head args `notElem` known_args
then error ("usage: genprimopcode command < primops.txt > ...\n"
++ " where command is one of\n"
++ unlines (map (" "++) known_args)
)
else
do s <- getContents
case parse s of
Left err -> error ("parse error at " ++ (show err))
Right p_o_specs@(Info _ _)
-> seq (sanityTop p_o_specs) (
case head args of
"--data-decl"
-> putStr (gen_data_decl p_o_specs)
"--has-side-effects"
-> putStr (gen_switch_from_attribs
"has_side_effects"
"primOpHasSideEffects" p_o_specs)
"--out-of-line"
-> putStr (gen_switch_from_attribs
"out_of_line"
"primOpOutOfLine" p_o_specs)
"--commutable"
-> putStr (gen_switch_from_attribs
"commutable"
"commutableOp" p_o_specs)
"--code-size"
-> putStr (gen_switch_from_attribs
"code_size"
"primOpCodeSize" p_o_specs)
"--can-fail"
-> putStr (gen_switch_from_attribs
"can_fail"
"primOpCanFail" p_o_specs)
"--strictness"
-> putStr (gen_switch_from_attribs
"strictness"
"primOpStrictness" p_o_specs)
"--fixity"
-> putStr (gen_switch_from_attribs
"fixity"
"primOpFixity" p_o_specs)
"--primop-primop-info"
-> putStr (gen_primop_info p_o_specs)
"--primop-tag"
-> putStr (gen_primop_tag p_o_specs)
"--primop-list"
-> putStr (gen_primop_list p_o_specs)
"--primop-vector-uniques"
-> putStr (gen_primop_vector_uniques p_o_specs)
"--primop-vector-tys"
-> putStr (gen_primop_vector_tys p_o_specs)
"--primop-vector-tys-exports"
-> putStr (gen_primop_vector_tys_exports p_o_specs)
"--primop-vector-tycons"
-> putStr (gen_primop_vector_tycons p_o_specs)
"--make-haskell-wrappers"
-> putStr (gen_wrappers p_o_specs)
"--make-haskell-source"
-> putStr (gen_hs_source p_o_specs)
"--make-latex-doc"
-> putStr (gen_latex_doc p_o_specs)
_ -> error "Should not happen, known_args out of sync?"
)
known_args :: [String]
known_args
= [ "--data-decl",
"--has-side-effects",
"--out-of-line",
"--commutable",
"--code-size",
"--can-fail",
"--strictness",
"--fixity",
"--primop-primop-info",
"--primop-tag",
"--primop-list",
"--primop-vector-uniques",
"--primop-vector-tys",
"--primop-vector-tys-exports",
"--primop-vector-tycons",
"--make-haskell-wrappers",
"--make-haskell-source",
"--make-latex-doc"
]
------------------------------------------------------------------
-- Code generators -----------------------------------------------
------------------------------------------------------------------
gen_hs_source :: Info -> String
gen_hs_source (Info defaults entries) =
"{-\n"
++ "This is a generated file (generated by genprimopcode).\n"
++ "It is not code to actually be used. Its only purpose is to be\n"
++ "consumed by haddock.\n"
++ "-}\n"
++ "\n"
++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness
++ "-- |\n"
++ "-- Module : GHC.Prim\n"
++ "-- \n"
++ "-- Maintainer : ghc-devs@haskell.org\n"
++ "-- Stability : internal\n"
++ "-- Portability : non-portable (GHC extensions)\n"
++ "--\n"
++ "-- GHC\'s primitive types and operations.\n"
++ "-- Use GHC.Exts from the base package instead of importing this\n"
++ "-- module directly.\n"
++ "--\n"
++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness
++ "{-# LANGUAGE Unsafe #-}\n"
++ "{-# LANGUAGE MagicHash #-}\n"
++ "{-# LANGUAGE MultiParamTypeClasses #-}\n"
++ "{-# LANGUAGE NoImplicitPrelude #-}\n"
++ "{-# LANGUAGE UnboxedTuples #-}\n"
++ "{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}\n"
-- We generate a binding for coerce, like
-- coerce :: Coercible a b => a -> b
-- coerce = let x = x in x
-- and we don't want a complaint that the constraint is redundant
-- Remember, this silly file is only for Haddock's consumption
++ "module GHC.Prim (\n"
++ unlines (map ((" " ++) . hdr) entries')
++ ") where\n"
++ "\n"
++ "{-\n"
++ unlines (map opt defaults)
++ "-}\n"
++ "import GHC.Types (Coercible)\n"
++ "default ()" -- If we don't say this then the default type include Integer
-- so that runs off and loads modules that are not part of
-- pacakge ghc-prim at all. And that in turn somehow ends up
-- with Declaration for $fEqMaybe:
-- attempting to use module ‘GHC.Classes’
-- (libraries/ghc-prim/./GHC/Classes.hs) which is not loaded
-- coming from LoadIface.homeModError
-- I'm not sure precisely why; but I *am* sure that we don't need
-- any type-class defaulting; and it's clearly wrong to need
-- the base package when haddocking ghc-prim
-- Now the main payload
++ unlines (concatMap ent entries') ++ "\n\n\n"
where entries' = concatMap desugarVectorSpec entries
opt (OptionFalse n) = n ++ " = False"
opt (OptionTrue n) = n ++ " = True"
opt (OptionString n v) = n ++ " = { " ++ v ++ "}"
opt (OptionInteger n v) = n ++ " = " ++ show v
opt (OptionVector _) = ""
opt (OptionFixity mf) = "fixity" ++ " = " ++ show mf
hdr s@(Section {}) = sec s
hdr (PrimOpSpec { name = n }) = wrapOp n ++ ","
hdr (PrimVecOpSpec { name = n }) = wrapOp n ++ ","
hdr (PseudoOpSpec { name = n }) = wrapOp n ++ ","
hdr (PrimTypeSpec { ty = TyApp (TyCon n) _ }) = wrapTy n ++ ","
hdr (PrimTypeSpec {}) = error $ "Illegal type spec"
hdr (PrimVecTypeSpec { ty = TyApp (VecTyCon n _) _ }) = wrapTy n ++ ","
hdr (PrimVecTypeSpec {}) = error $ "Illegal type spec"
ent (Section {}) = []
ent o@(PrimOpSpec {}) = spec o
ent o@(PrimVecOpSpec {}) = spec o
ent o@(PrimTypeSpec {}) = spec o
ent o@(PrimVecTypeSpec {}) = spec o
ent o@(PseudoOpSpec {}) = spec o
sec s = "\n-- * " ++ escape (title s) ++ "\n"
++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ desc s) ++ "\n"
spec o = comm : decls
where decls = case o of
PrimOpSpec { name = n, ty = t, opts = options } ->
[ pprFixity fixity n | OptionFixity (Just fixity) <- options ]
++
[ wrapOp n ++ " :: " ++ pprTy t,
wrapOp n ++ " = let x = x in x" ]
PrimVecOpSpec { name = n, ty = t, opts = options } ->
[ pprFixity fixity n | OptionFixity (Just fixity) <- options ]
++
[ wrapOp n ++ " :: " ++ pprTy t,
wrapOp n ++ " = let x = x in x" ]
PseudoOpSpec { name = n, ty = t } ->
[ wrapOp n ++ " :: " ++ pprTy t,
wrapOp n ++ " = let x = x in x" ]
PrimTypeSpec { ty = t } ->
[ "data " ++ pprTy t ]
PrimVecTypeSpec { ty = t } ->
[ "data " ++ pprTy t ]
Section { } -> []
comm = case (desc o) of
[] -> ""
d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d)
wrapOp nm | isAlpha (head nm) = nm
| otherwise = "(" ++ nm ++ ")"
wrapTy nm | isAlpha (head nm) = nm
| otherwise = "(" ++ nm ++ ")"
unlatex s = case s of
'\\':'t':'e':'x':'t':'t':'t':'{':cs -> markup "@" "@" cs
'{':'\\':'t':'t':cs -> markup "@" "@" cs
'{':'\\':'i':'t':cs -> markup "/" "/" cs
c : cs -> c : unlatex cs
[] -> []
markup s t xs = s ++ mk (dropWhile isSpace xs)
where mk "" = t
mk ('\n':cs) = ' ' : mk cs
mk ('}':cs) = t ++ unlatex cs
mk (c:cs) = c : mk cs
escape = concatMap (\c -> if c `elem` special then '\\':c:[] else c:[])
where special = "/'`\"@<"
pprFixity (Fixity i d) n = pprFixityDir d ++ " " ++ show i ++ " " ++ n
pprTy :: Ty -> String
pprTy = pty
where
pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2
pty t = pbty t
pbty (TyApp tc ts) = show tc ++ concat (map (' ' :) (map paty ts))
pbty (TyUTup ts) = "(# "
++ concat (intersperse "," (map pty ts))
++ " #)"
pbty t = paty t
paty (TyVar tv) = tv
paty t = "(" ++ pty t ++ ")"
gen_latex_doc :: Info -> String
gen_latex_doc (Info defaults entries)
= "\\primopdefaults{"
++ mk_options defaults
++ "}\n"
++ (concat (map mk_entry entries))
where mk_entry (PrimOpSpec {cons=constr,name=n,ty=t,cat=c,desc=d,opts=o}) =
"\\primopdesc{"
++ latex_encode constr ++ "}{"
++ latex_encode n ++ "}{"
++ latex_encode (zencode n) ++ "}{"
++ latex_encode (show c) ++ "}{"
++ latex_encode (mk_source_ty t) ++ "}{"
++ latex_encode (mk_core_ty t) ++ "}{"
++ d ++ "}{"
++ mk_options o
++ "}\n"
mk_entry (PrimVecOpSpec {}) =
""
mk_entry (Section {title=ti,desc=d}) =
"\\primopsection{"
++ latex_encode ti ++ "}{"
++ d ++ "}\n"
mk_entry (PrimTypeSpec {ty=t,desc=d,opts=o}) =
"\\primtypespec{"
++ latex_encode (mk_source_ty t) ++ "}{"
++ latex_encode (mk_core_ty t) ++ "}{"
++ d ++ "}{"
++ mk_options o
++ "}\n"
mk_entry (PrimVecTypeSpec {}) =
""
mk_entry (PseudoOpSpec {name=n,ty=t,desc=d,opts=o}) =
"\\pseudoopspec{"
++ latex_encode (zencode n) ++ "}{"
++ latex_encode (mk_source_ty t) ++ "}{"
++ latex_encode (mk_core_ty t) ++ "}{"
++ d ++ "}{"
++ mk_options o
++ "}\n"
mk_source_ty typ = pty typ
where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2
pty t = pbty t
pbty (TyApp tc ts) = show tc ++ (concat (map (' ':) (map paty ts)))
pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
pbty t = paty t
paty (TyVar tv) = tv
paty t = "(" ++ pty t ++ ")"
mk_core_ty typ = foralls ++ (pty typ)
where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2
pty t = pbty t
pbty (TyApp tc ts) = (zencode (show tc)) ++ (concat (map (' ':) (map paty ts)))
pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts))))
pbty t = paty t
paty (TyVar tv) = zencode tv
paty (TyApp tc []) = zencode (show tc)
paty t = "(" ++ pty t ++ ")"
utuplenm 1 = "(# #)"
utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)"
foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars)
tvars = tvars_of typ
tbinds [] = ". "
tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs)
tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs)
tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2
tvars_of (TyC t1 t2) = tvars_of t1 `union` tvars_of t2
tvars_of (TyApp _ ts) = foldl union [] (map tvars_of ts)
tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts)
tvars_of (TyVar tv) = [tv]
mk_options o =
"\\primoptions{"
++ mk_has_side_effects o ++ "}{"
++ mk_out_of_line o ++ "}{"
++ mk_commutable o ++ "}{"
++ mk_needs_wrapper o ++ "}{"
++ mk_can_fail o ++ "}{"
++ mk_fixity o ++ "}{"
++ latex_encode (mk_strictness o) ++ "}{"
++ "}"
mk_has_side_effects o = mk_bool_opt o "has_side_effects" "Has side effects." "Has no side effects."
mk_out_of_line o = mk_bool_opt o "out_of_line" "Implemented out of line." "Implemented in line."
mk_commutable o = mk_bool_opt o "commutable" "Commutable." "Not commutable."
mk_needs_wrapper o = mk_bool_opt o "needs_wrapper" "Needs wrapper." "Needs no wrapper."
mk_can_fail o = mk_bool_opt o "can_fail" "Can fail." "Cannot fail."
mk_bool_opt o opt_name if_true if_false =
case lookup_attrib opt_name o of
Just (OptionTrue _) -> if_true
Just (OptionFalse _) -> if_false
Just (OptionString _ _) -> error "String value for boolean option"
Just (OptionInteger _ _) -> error "Integer value for boolean option"
Just (OptionFixity _) -> error "Fixity value for boolean option"
Just (OptionVector _) -> error "vector template for boolean option"
Nothing -> ""
mk_strictness o =
case lookup_attrib "strictness" o of
Just (OptionString _ s) -> s -- for now
Just _ -> error "Wrong value for strictness"
Nothing -> ""
mk_fixity o = case lookup_attrib "fixity" o of
Just (OptionFixity (Just (Fixity i d)))
-> pprFixityDir d ++ " " ++ show i
_ -> ""
zencode xs =
case maybe_tuple xs of
Just n -> n -- Tuples go to Z2T etc
Nothing -> concat (map encode_ch xs)
where
maybe_tuple "(# #)" = Just("Z1H")
maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
(n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
_ -> Nothing
maybe_tuple "()" = Just("Z0T")
maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
(n, ')' : _) -> Just ('Z' : shows (n+1) "T")
_ -> Nothing
maybe_tuple _ = Nothing
count_commas :: Int -> String -> (Int, String)
count_commas n (',' : cs) = count_commas (n+1) cs
count_commas n cs = (n,cs)
unencodedChar :: Char -> Bool -- True for chars that don't need encoding
unencodedChar 'Z' = False
unencodedChar 'z' = False
unencodedChar c = isAlphaNum c
encode_ch :: Char -> String
encode_ch c | unencodedChar c = [c] -- Common case first
-- Constructors
encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
encode_ch ')' = "ZR" -- For symmetry with (
encode_ch '[' = "ZM"
encode_ch ']' = "ZN"
encode_ch ':' = "ZC"
encode_ch 'Z' = "ZZ"
-- Variables
encode_ch 'z' = "zz"
encode_ch '&' = "za"
encode_ch '|' = "zb"
encode_ch '^' = "zc"
encode_ch '$' = "zd"
encode_ch '=' = "ze"
encode_ch '>' = "zg"
encode_ch '#' = "zh"
encode_ch '.' = "zi"
encode_ch '<' = "zl"
encode_ch '-' = "zm"
encode_ch '!' = "zn"
encode_ch '+' = "zp"
encode_ch '\'' = "zq"
encode_ch '\\' = "zr"
encode_ch '/' = "zs"
encode_ch '*' = "zt"
encode_ch '_' = "zu"
encode_ch '%' = "zv"
encode_ch c = 'z' : shows (ord c) "U"
latex_encode [] = []
latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs)
latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs)
latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs)
latex_encode (c:cs) = c:(latex_encode cs)
gen_wrappers :: Info -> String
gen_wrappers (Info _ entries)
= "{-# LANGUAGE MagicHash, NoImplicitPrelude, UnboxedTuples #-}\n"
-- Dependencies on Prelude must be explicit in libraries/base, but we
-- don't need the Prelude here so we add NoImplicitPrelude.
++ "module GHC.PrimopWrappers where\n"
++ "import qualified GHC.Prim\n"
++ "import GHC.Tuple ()\n"
++ "import GHC.Prim (" ++ types ++ ")\n"
++ unlines (concatMap f specs)
where
specs = filter (not.dodgy) $
filter (not.is_llvm_only) $
filter is_primop entries
tycons = foldr union [] $ map (tyconsIn . ty) specs
tycons' = filter (`notElem` [TyCon "()", TyCon "Bool"]) tycons
types = concat $ intersperse ", " $ map show tycons'
f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
src_name = wrap (name spec)
lhs = src_name ++ " " ++ unwords args
rhs = "(GHC.Prim." ++ name spec ++ ") " ++ unwords args
in ["{-# NOINLINE " ++ src_name ++ " #-}",
src_name ++ " :: " ++ pprTy (ty spec),
lhs ++ " = " ++ rhs]
wrap nm | isLower (head nm) = nm
| otherwise = "(" ++ nm ++ ")"
dodgy spec
= name spec `elem`
[-- tagToEnum# is really magical, and can't have
-- a wrapper since its implementation depends on
-- the type of its result
"tagToEnum#"
]
is_llvm_only :: Entry -> Bool
is_llvm_only entry =
case lookup_attrib "llvm_only" (opts entry) of
Just (OptionTrue _) -> True
_ -> False
gen_primop_list :: Info -> String
gen_primop_list (Info _ entries)
= unlines (
[ " [" ++ cons first ]
++
map (\p -> " , " ++ cons p) rest
++
[ " ]" ]
) where (first:rest) = concatMap desugarVectorSpec (filter is_primop entries)
mIN_VECTOR_UNIQUE :: Int
mIN_VECTOR_UNIQUE = 300
gen_primop_vector_uniques :: Info -> String
gen_primop_vector_uniques (Info _ entries)
= unlines $
concatMap mkVecUnique (specs `zip` [mIN_VECTOR_UNIQUE..])
where
specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries))
mkVecUnique :: (Entry, Int) -> [String]
mkVecUnique (i, unique) =
[ key_id ++ " :: Unique"
, key_id ++ " = mkPreludeTyConUnique " ++ show unique
]
where
key_id = prefix i ++ "PrimTyConKey"
gen_primop_vector_tys :: Info -> String
gen_primop_vector_tys (Info _ entries)
= unlines $
concatMap mkVecTypes specs
where
specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries))
mkVecTypes :: Entry -> [String]
mkVecTypes i =
[ name_id ++ " :: Name"
, name_id ++ " = mkPrimTc (fsLit \"" ++ pprTy (ty i) ++ "\") " ++ key_id ++ " " ++ tycon_id
, ty_id ++ " :: Type"
, ty_id ++ " = mkTyConTy " ++ tycon_id
, tycon_id ++ " :: TyCon"
, tycon_id ++ " = pcPrimTyCon0 " ++ name_id ++
" (VecRep " ++ show (veclen i) ++ " " ++ elemrep i ++ ")"
]
where
key_id = prefix i ++ "PrimTyConKey"
name_id = prefix i ++ "PrimTyConName"
ty_id = prefix i ++ "PrimTy"
tycon_id = prefix i ++ "PrimTyCon"
gen_primop_vector_tys_exports :: Info -> String
gen_primop_vector_tys_exports (Info _ entries)
= unlines $
map mkVecTypes specs
where
specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries))
mkVecTypes :: Entry -> String
mkVecTypes i =
" " ++ ty_id ++ ", " ++ tycon_id ++ ","
where
ty_id = prefix i ++ "PrimTy"
tycon_id = prefix i ++ "PrimTyCon"
gen_primop_vector_tycons :: Info -> String
gen_primop_vector_tycons (Info _ entries)
= unlines $
map mkVecTypes specs
where
specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries))
mkVecTypes :: Entry -> String
mkVecTypes i =
" , " ++ tycon_id
where
tycon_id = prefix i ++ "PrimTyCon"
gen_primop_tag :: Info -> String
gen_primop_tag (Info _ entries)
= unlines (max_def_type : max_def :
tagOf_type : zipWith f primop_entries [1 :: Int ..])
where
primop_entries = concatMap desugarVectorSpec $ filter is_primop entries
tagOf_type = "tagOf_PrimOp :: PrimOp -> FastInt"
f i n = "tagOf_PrimOp " ++ cons i ++ " = _ILIT(" ++ show n ++ ")"
max_def_type = "maxPrimOpTag :: Int"
max_def = "maxPrimOpTag = " ++ show (length primop_entries)
gen_data_decl :: Info -> String
gen_data_decl (Info _ entries) =
"data PrimOp\n = " ++ head conss ++ "\n"
++ unlines (map (" | "++) (tail conss))
where
conss = map genCons (filter is_primop entries)
genCons :: Entry -> String
genCons entry =
case vecOptions entry of
[] -> cons entry
_ -> cons entry ++ " PrimOpVecCat Length Width"
gen_switch_from_attribs :: String -> String -> Info -> String
gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
= let defv = lookup_attrib attrib_name defaults
alternatives = catMaybes (map mkAlt (filter is_primop entries))
getAltRhs (OptionFalse _) = "False"
getAltRhs (OptionTrue _) = "True"
getAltRhs (OptionInteger _ i) = show i
getAltRhs (OptionString _ s) = s
getAltRhs (OptionVector _) = "True"
getAltRhs (OptionFixity mf) = show mf
mkAlt po
= case lookup_attrib attrib_name (opts po) of
Nothing -> Nothing
Just xx -> case vecOptions po of
[] -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
_ -> Just (fn_name ++ " (" ++ cons po ++ " _ _ _) = " ++ getAltRhs xx)
in
case defv of
Nothing -> error ("gen_switch_from: " ++ attrib_name)
Just xx
-> unlines alternatives
++ fn_name ++ " _ = " ++ getAltRhs xx ++ "\n"
------------------------------------------------------------------
-- Create PrimOpInfo text from PrimOpSpecs -----------------------
------------------------------------------------------------------
gen_primop_info :: Info -> String
gen_primop_info (Info _ entries)
= unlines (map mkPOItext (concatMap desugarVectorSpec (filter is_primop entries)))
mkPOItext :: Entry -> String
mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
mkPOI_LHS_text :: Entry -> String
mkPOI_LHS_text i
= "primOpInfo " ++ cons i ++ " = "
mkPOI_RHS_text :: Entry -> String
mkPOI_RHS_text i
= case cat i of
Compare
-> case ty i of
TyF t1 (TyF _ _)
-> "mkCompare " ++ sl_name i ++ ppType t1
_ -> error "Type error in comparison op"
Monadic
-> case ty i of
TyF t1 _
-> "mkMonadic " ++ sl_name i ++ ppType t1
_ -> error "Type error in monadic op"
Dyadic
-> case ty i of
TyF t1 (TyF _ _)
-> "mkDyadic " ++ sl_name i ++ ppType t1
_ -> error "Type error in dyadic op"
GenPrimOp
-> let (argTys, resTy) = flatTys (ty i)
tvs = nub (tvsIn (ty i))
in
"mkGenPrimOp " ++ sl_name i ++ " "
++ listify (map ppTyVar tvs) ++ " "
++ listify (map ppType argTys) ++ " "
++ "(" ++ ppType resTy ++ ")"
sl_name :: Entry -> String
sl_name i = "(fsLit \"" ++ name i ++ "\") "
ppTyVar :: String -> String
ppTyVar "a" = "alphaTyVar"
ppTyVar "b" = "betaTyVar"
ppTyVar "c" = "gammaTyVar"
ppTyVar "s" = "deltaTyVar"
ppTyVar "o" = "openAlphaTyVar"
ppTyVar _ = error "Unknown type var"
ppType :: Ty -> String
ppType (TyApp (TyCon "Any") []) = "anyTy"
ppType (TyApp (TyCon "Bool") []) = "boolTy"
ppType (TyApp (TyCon "Int#") []) = "intPrimTy"
ppType (TyApp (TyCon "Int32#") []) = "int32PrimTy"
ppType (TyApp (TyCon "Int64#") []) = "int64PrimTy"
ppType (TyApp (TyCon "Char#") []) = "charPrimTy"
ppType (TyApp (TyCon "Word#") []) = "wordPrimTy"
ppType (TyApp (TyCon "Word32#") []) = "word32PrimTy"
ppType (TyApp (TyCon "Word64#") []) = "word64PrimTy"
ppType (TyApp (TyCon "Addr#") []) = "addrPrimTy"
ppType (TyApp (TyCon "Float#") []) = "floatPrimTy"
ppType (TyApp (TyCon "Double#") []) = "doublePrimTy"
ppType (TyApp (TyCon "ByteArray#") []) = "byteArrayPrimTy"
ppType (TyApp (TyCon "RealWorld") []) = "realWorldTy"
ppType (TyApp (TyCon "ThreadId#") []) = "threadIdPrimTy"
ppType (TyApp (TyCon "ForeignObj#") []) = "foreignObjPrimTy"
ppType (TyApp (TyCon "BCO#") []) = "bcoPrimTy"
ppType (TyApp (TyCon "()") []) = "unitTy" -- unitTy is TysWiredIn's name for ()
ppType (TyVar "a") = "alphaTy"
ppType (TyVar "b") = "betaTy"
ppType (TyVar "c") = "gammaTy"
ppType (TyVar "s") = "deltaTy"
ppType (TyVar "o") = "openAlphaTy"
ppType (TyApp (TyCon "State#") [x]) = "mkStatePrimTy " ++ ppType x
ppType (TyApp (TyCon "MutVar#") [x,y]) = "mkMutVarPrimTy " ++ ppType x
++ " " ++ ppType y
ppType (TyApp (TyCon "MutableArray#") [x,y]) = "mkMutableArrayPrimTy " ++ ppType x
++ " " ++ ppType y
ppType (TyApp (TyCon "MutableArrayArray#") [x]) = "mkMutableArrayArrayPrimTy " ++ ppType x
ppType (TyApp (TyCon "SmallMutableArray#") [x,y]) = "mkSmallMutableArrayPrimTy " ++ ppType x
++ " " ++ ppType y
ppType (TyApp (TyCon "MutableByteArray#") [x]) = "mkMutableByteArrayPrimTy "
++ ppType x
ppType (TyApp (TyCon "Array#") [x]) = "mkArrayPrimTy " ++ ppType x
ppType (TyApp (TyCon "ArrayArray#") []) = "mkArrayArrayPrimTy"
ppType (TyApp (TyCon "SmallArray#") [x]) = "mkSmallArrayPrimTy " ++ ppType x
ppType (TyApp (TyCon "Weak#") [x]) = "mkWeakPrimTy " ++ ppType x
ppType (TyApp (TyCon "StablePtr#") [x]) = "mkStablePtrPrimTy " ++ ppType x
ppType (TyApp (TyCon "StableName#") [x]) = "mkStableNamePrimTy " ++ ppType x
ppType (TyApp (TyCon "MVar#") [x,y]) = "mkMVarPrimTy " ++ ppType x
++ " " ++ ppType y
ppType (TyApp (TyCon "TVar#") [x,y]) = "mkTVarPrimTy " ++ ppType x
++ " " ++ ppType y
ppType (TyApp (VecTyCon _ pptc) []) = pptc
ppType (TyUTup ts) = "(mkTupleTy UnboxedTuple "
++ listify (map ppType ts) ++ ")"
ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
ppType (TyC s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
ppType other
= error ("ppType: can't handle: " ++ show other ++ "\n")
pprFixityDir :: FixityDirection -> String
pprFixityDir InfixN = "infix"
pprFixityDir InfixL = "infixl"
pprFixityDir InfixR = "infixr"
listify :: [String] -> String
listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
flatTys :: Ty -> ([Ty],Ty)
flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
flatTys (TyC t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
flatTys other = ([],other)
tvsIn :: Ty -> [TyVar]
tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2
tvsIn (TyC t1 t2) = tvsIn t1 ++ tvsIn t2
tvsIn (TyApp _ tys) = concatMap tvsIn tys
tvsIn (TyVar tv) = [tv]
tvsIn (TyUTup tys) = concatMap tvsIn tys
tyconsIn :: Ty -> [TyCon]
tyconsIn (TyF t1 t2) = tyconsIn t1 `union` tyconsIn t2
tyconsIn (TyC t1 t2) = tyconsIn t1 `union` tyconsIn t2
tyconsIn (TyApp tc tys) = foldr union [tc] $ map tyconsIn tys
tyconsIn (TyVar _) = []
tyconsIn (TyUTup tys) = foldr union [] $ map tyconsIn tys
arity :: Ty -> Int
arity = length . fst . flatTys
| christiaanb/ghc | utils/genprimopcode/Main.hs | bsd-3-clause | 35,915 | 0 | 39 | 14,524 | 9,914 | 4,992 | 4,922 | 688 | 74 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module BCalib.SV1 where
import Control.Applicative (ZipList (..))
import Data.Map.Strict as M
import GHC.Float
import GHC.Generics hiding (to)
import BCalib.Imports
data SV1Info =
SV1Info
{ _sv1MSV :: Double
, _sv1NGTJet :: Int
, _sv1NGTSV :: Int
, _sv1Efrac :: Double
, _sv1LLR :: Double
, _sv1Pu :: Double
, _sv1Pc :: Double
, _sv1Pb :: Double
} deriving (Generic, Show)
-- TODO
-- profiles
sv1Hs :: Fill SV1Info
sv1Hs = M.unions <$> sequenceA
[ hist1DDef (binD 0 50 10) "SV1 SV mass [GeV]" (dsigdXpbY "m" gev) "/sv1msv"
<$$= sv1MSV
-- , fillH1L (sv1NGTJet.integralL) "/sv1ngtj" $ yodaHist 10 0 10 "SV1 Jet NGT" (dsigdXpbY "n" "1")
, hist1DDef (binD 0 10 10) "SV1 SV NGT" (dsigdXpbY "n" "1") "/sv1ngtsv"
<$$= (sv1NGTSV.integralL)
, hist1DDef (binD 0 50 1) "SV1 energy fraction" (dsigdXpbY "\\mathrm{fraction}" "1") "/sv1efrac"
<$$= sv1Efrac
-- , fillH1L sv1LLR "/sv1llr" $ yodaHist 50 (-5) 15 "SV1 LLR" (dsigdXpbY "\\mathrm{LLR}" "1")
-- , fillH1L sv1Pu "/sv1pu" $ yodaHist 50 0 1 "SV1 P(light)" (dsigdXpbY "P" "1")
-- , fillH1L sv1Pc "/sv1pc" $ yodaHist 50 0 1 "SV1 P(charm)" (dsigdXpbY "P" "1")
-- , fillH1L sv1Pb "/sv1pb" $ yodaHist 50 0 1 "SV1 P(bottom)" (dsigdXpbY "P" "1")
]
where
-- don't know why this is necessary...
integralL = to fromIntegral
readSV1s :: MonadIO m => TR m (ZipList SV1Info)
readSV1s = do
msv <- fmap (/ 1e3) <$> readD "jetsSV1_masssvx"
ngtjet <- readI "jetsSV1_NGTinJet"
ngtsv <- readI "jetsSV1_NGTinSvx"
efrac <- readD "jetsSV1_efracsvx"
llr <- readD "jetsSV1_loglikelihoodratio"
pu <- readD "jetsSV1_pu"
pc <- readD "jetsSV1_pc"
pb <- readD "jetsSV1_pb"
return $ SV1Info
<$> msv
<*> ngtjet
<*> ngtsv
<*> efrac
<*> llr
<*> pu
<*> pc
<*> pb
where
readD n = fmap float2Double <$> readBranch n
readI n = fmap (fromEnum :: CInt -> Int) <$> readBranch n
-- TODO
-- can't get TH working with external libs (e.g. root)
sv1Efrac :: Lens' SV1Info Double
sv1Efrac
f_ajgB
(SV1Info x1_ajgC
x2_ajgD
x3_ajgE
x4_ajgF
x5_ajgG
x6_ajgH
x7_ajgI
x8_ajgJ)
= fmap
(\ y1_ajgK
-> SV1Info
x1_ajgC x2_ajgD x3_ajgE y1_ajgK x5_ajgG x6_ajgH x7_ajgI x8_ajgJ)
(f_ajgB x4_ajgF)
{-# INLINE sv1Efrac #-}
sv1LLR :: Lens' SV1Info Double
sv1LLR
f_ajgL
(SV1Info x1_ajgM
x2_ajgN
x3_ajgO
x4_ajgP
x5_ajgQ
x6_ajgR
x7_ajgS
x8_ajgT)
= fmap
(\ y1_ajgU
-> SV1Info
x1_ajgM x2_ajgN x3_ajgO x4_ajgP y1_ajgU x6_ajgR x7_ajgS x8_ajgT)
(f_ajgL x5_ajgQ)
{-# INLINE sv1LLR #-}
sv1MSV :: Lens' SV1Info Double
sv1MSV
f_ajgV
(SV1Info x1_ajgW
x2_ajgX
x3_ajgY
x4_ajgZ
x5_ajh0
x6_ajh1
x7_ajh2
x8_ajh3)
= fmap
(\ y1_ajh4
-> SV1Info
y1_ajh4 x2_ajgX x3_ajgY x4_ajgZ x5_ajh0 x6_ajh1 x7_ajh2 x8_ajh3)
(f_ajgV x1_ajgW)
{-# INLINE sv1MSV #-}
sv1NGTJet :: Lens' SV1Info Int
sv1NGTJet
f_ajh5
(SV1Info x1_ajh6
x2_ajh7
x3_ajh8
x4_ajh9
x5_ajha
x6_ajhb
x7_ajhc
x8_ajhd)
= fmap
(\ y1_ajhe
-> SV1Info
x1_ajh6 y1_ajhe x3_ajh8 x4_ajh9 x5_ajha x6_ajhb x7_ajhc x8_ajhd)
(f_ajh5 x2_ajh7)
{-# INLINE sv1NGTJet #-}
sv1NGTSV :: Lens' SV1Info Int
sv1NGTSV
f_ajhf
(SV1Info x1_ajhg
x2_ajhh
x3_ajhi
x4_ajhj
x5_ajhk
x6_ajhl
x7_ajhm
x8_ajhn)
= fmap
(\ y1_ajho
-> SV1Info
x1_ajhg x2_ajhh y1_ajho x4_ajhj x5_ajhk x6_ajhl x7_ajhm x8_ajhn)
(f_ajhf x3_ajhi)
{-# INLINE sv1NGTSV #-}
sv1Pb :: Lens' SV1Info Double
sv1Pb
f_ajhp
(SV1Info x1_ajhq
x2_ajhr
x3_ajhs
x4_ajht
x5_ajhu
x6_ajhv
x7_ajhw
x8_ajhx)
= fmap
(\ y1_ajhy
-> SV1Info
x1_ajhq x2_ajhr x3_ajhs x4_ajht x5_ajhu x6_ajhv x7_ajhw y1_ajhy)
(f_ajhp x8_ajhx)
{-# INLINE sv1Pb #-}
sv1Pc :: Lens' SV1Info Double
sv1Pc
f_ajhz
(SV1Info x1_ajhA
x2_ajhB
x3_ajhC
x4_ajhD
x5_ajhE
x6_ajhF
x7_ajhG
x8_ajhH)
= fmap
(\ y1_ajhI
-> SV1Info
x1_ajhA x2_ajhB x3_ajhC x4_ajhD x5_ajhE x6_ajhF y1_ajhI x8_ajhH)
(f_ajhz x7_ajhG)
{-# INLINE sv1Pc #-}
sv1Pu :: Lens' SV1Info Double
sv1Pu
f_ajhJ
(SV1Info x1_ajhK
x2_ajhL
x3_ajhM
x4_ajhN
x5_ajhO
x6_ajhP
x7_ajhQ
x8_ajhR)
= fmap
(\ y1_ajhS
-> SV1Info
x1_ajhK x2_ajhL x3_ajhM x4_ajhN x5_ajhO y1_ajhS x7_ajhQ x8_ajhR)
(f_ajhJ x6_ajhP)
{-# INLINE sv1Pu #-}
| cspollard/bcalib | src/BCalib/SV1.hs | bsd-3-clause | 5,209 | 0 | 15 | 1,851 | 1,091 | 564 | 527 | 186 | 1 |
module Main where
import Control.Monad.IO.Class (liftIO)
import System.Environment (getArgs)
import Ping.GenTypes
import Vintage
app :: Session ()
app = do
msg <- send Ping
liftIO $ putStrLn (show (msg :: Ping))
return ()
server :: Ping -> IO Pong
server Ping = return Pong
main :: IO ()
main = getArgs >>= \args -> case args of
["client"] -> runClient "localhost" 9090 app
["server"] -> runServer 9090 server
_ -> putStrLn "Usage: pingtest [client|server]"
| luciferous/vintage | tests/Ping.hs | bsd-3-clause | 497 | 0 | 11 | 113 | 179 | 93 | 86 | 17 | 3 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.ES.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = ES}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 1)
[ "1"
, "uno"
, "una"
]
, examples (NumeralValue 11)
[ "once"
]
, examples (NumeralValue 16)
[ "dieciséis"
, "dieciseis"
, "Diesiseis"
, "diez y seis"
]
, examples (NumeralValue 21)
[ "veintiuno"
, "veinte y uno"
]
, examples (NumeralValue 23)
[ "veintitrés"
, "veinte y tres"
]
, examples (NumeralValue 70)
[ "setenta"
]
, examples (NumeralValue 78)
[ "Setenta y ocho"
]
, examples (NumeralValue 80)
[ "ochenta"
]
, examples (NumeralValue 33)
[ "33"
, "treinta y tres"
, "treinta y 3"
]
, examples (NumeralValue 1.1)
[ "1,1"
, "1,10"
, "01,10"
]
, examples (NumeralValue 0.77)
[ "0,77"
, ",77"
]
, examples (NumeralValue 100000)
[ "100.000"
, "100000"
, "100K"
, "100k"
]
, examples (NumeralValue 300)
[ "trescientos"
]
, examples (NumeralValue 243)
[ "243"
]
, examples (NumeralValue 3000000)
[ "3M"
, "3000K"
, "3000000"
, "3.000.000"
]
, examples (NumeralValue 1200000)
[ "1.200.000"
, "1200000"
, "1,2M"
, "1200K"
, ",0012G"
]
, examples (NumeralValue (-1200000))
[ "- 1.200.000"
, "-1200000"
, "menos 1.200.000"
, "-1,2M"
, "-1200K"
, "-,0012G"
]
, examples (NumeralValue 1.5)
[ "1 punto cinco"
, "una punto cinco"
, "1,5"
]
]
| rfranek/duckling | Duckling/Numeral/ES/Corpus.hs | bsd-3-clause | 2,692 | 0 | 11 | 1,186 | 488 | 282 | 206 | 78 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: TODO
-- Copyright: (c) 2014 Peter Trsko
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: DeriveDataGeneric, DeriveDataTypeable, NoImplicitPrelude
--
-- TODO
module Skeletos.Type.Define
(
-- * Data Types
Defines(..)
, Define(..)
, Value(..)
-- * Lenses
, defines
, name
, value
-- * Prisms
, boolValue
, textValue
, intValue
, wordValue
)
where
import Data.Bool (Bool)
import Data.Data (Data)
import Data.Function (($))
import Data.Int (Int)
import Data.Maybe (Maybe(Just, Nothing))
import Data.Typeable (Typeable)
import Data.Word (Word)
import GHC.Generics (Generic)
import Text.Read (Read)
import Text.Show (Show)
import Data.Text (Text)
import qualified Data.Text as Text (empty)
import Control.Lens (Lens', Prism', prism')
import qualified Data.Maybe.Strict as Strict (Maybe(Nothing))
import Data.Default.Class (Default(def))
import Skeletos.Internal.Utils ((<$$>))
-- {{{ Value ------------------------------------------------------------------
data Value
= BoolValue !Bool
| TextValue !Text
| IntValue !Int
| WordValue !Word
deriving (Data, Generic, Read, Show, Typeable)
boolValue :: Prism' Value Bool
boolValue = prism' BoolValue $ \v -> case v of
BoolValue x -> Just x
_ -> Nothing
textValue :: Prism' Value Text
textValue = prism' TextValue $ \v -> case v of
TextValue x -> Just x
_ -> Nothing
intValue :: Prism' Value Int
intValue = prism' IntValue $ \v -> case v of
IntValue x -> Just x
_ -> Nothing
wordValue :: Prism' Value Word
wordValue = prism' WordValue $ \v -> case v of
WordValue x -> Just x
_ -> Nothing
-- }}} Value ------------------------------------------------------------------
-- {{{ Define -----------------------------------------------------------------
data Define = Define
{ _name :: !Text
, _value :: Strict.Maybe Value
}
deriving (Data, Generic, Read, Show, Typeable)
-- | Defined as:
--
-- @
-- 'def' = 'Define'
-- { '_name' = 'Text.empty'
-- , '_value' = 'Strict.Nothing'
-- }
-- @
instance Default Define where
def = Define
{ _name = Text.empty
, _value = Strict.Nothing
}
name :: Lens' Define Text
name f s@Define{_name = a} = f a <$$> \b -> s{_name = b}
value :: Lens' Define (Strict.Maybe Value)
value f s@Define{_value = a} = f a <$$> \b -> s{_value = b}
-- }}} Define -----------------------------------------------------------------
-- {{{ Defines ----------------------------------------------------------------
newtype Defines = Defines [Define]
deriving (Data, Generic, Read, Show, Typeable)
instance Default Defines where
def = Defines []
defines :: Lens' Defines [Define]
defines f (Defines ds) = f ds <$$> Defines
-- }}} Defines ----------------------------------------------------------------
| trskop/skeletos | src/Skeletos/Type/Define.hs | bsd-3-clause | 3,097 | 0 | 10 | 663 | 803 | 463 | 340 | 81 | 2 |
{--
--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location.
However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present?
For example:
> delivers presents to 2 houses: one at the starting location, and one to the east.
^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location.
^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the same starting house), then take turns moving based on instructions from the elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa goes south.
^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up back where they started.
^v^v^v^v^v now delivers presents to 11 houses, with Santa going one direction and Robo-Santa going the other.
-}
module Day3
( answers
) where
import qualified Data.Set as Set
type Coordinate = (Int, Int)
charToCoord :: Char -> Coordinate -> Coordinate
charToCoord '^' (x, y) = (x, y + 1)
charToCoord 'v' (x, y) = (x, y - 1)
charToCoord '>' (x, y) = (x + 1, y)
charToCoord '<' (x, y) = (x - 1, y)
charToCoord _ coord = coord
moveUntilFinish :: String -> Set.Set Coordinate -> Coordinate -> Set.Set Coordinate
moveUntilFinish [] location _ = location
moveUntilFinish (m:ms) location coord = let newCoord = charToCoord m coord
newLocation = Set.insert newCoord location
in moveUntilFinish ms newLocation newCoord
moveUntilFinishWithRobot :: String -> Set.Set Coordinate -> Set.Set Coordinate -> Coordinate -> Coordinate -> Set.Set Coordinate
moveUntilFinishWithRobot [] santaLocation robotLocation _ _ =
Set.union santaLocation robotLocation
moveUntilFinishWithRobot (sm:[]) santaLocation robotLocation santaCoord _ =
let newSantaCoord = charToCoord sm santaCoord
newSantaLocation = Set.insert newSantaCoord santaLocation
in Set.union newSantaLocation robotLocation
moveUntilFinishWithRobot (sm:rm:ms) santaLocation robotLocation santaCoord robotCoord =
let newSantaCoord = charToCoord sm santaCoord
newSantaLocation = Set.insert newSantaCoord santaLocation
newRobotCoord = charToCoord rm robotCoord
newRobotLocation = Set.insert newRobotCoord robotLocation
in moveUntilFinishWithRobot ms newSantaLocation newRobotLocation newSantaCoord newRobotCoord
howManyHousesSantaVisited :: String -> Int
howManyHousesSantaVisited movements = let initialCoord = (0,0)
initialHouse = Set.singleton initialCoord
visits = moveUntilFinish movements initialHouse initialCoord
in Set.size visits
howManyHousesSantaAndRobotVisited :: String -> Int
howManyHousesSantaAndRobotVisited movements = let initialCoord = (0,0)
initialHouse = Set.singleton initialCoord
visits = moveUntilFinishWithRobot movements initialHouse initialHouse initialCoord initialCoord
in Set.size visits
answers :: String -> IO ()
answers movements = do
putStrLn $ "day 3 part 1 = " ++ show (howManyHousesSantaVisited movements)
putStrLn $ "day 3 part 2 = " ++ show (howManyHousesSantaAndRobotVisited movements)
| hlmerscher/advent-of-code-2015 | src/Day3.hs | bsd-3-clause | 4,356 | 0 | 11 | 1,065 | 653 | 335 | 318 | 42 | 1 |
{-# LANGUAGE RecordWildCards #-}
module SimpleAbstractor.Parser (
reservedNames,
reservedOps,
typeDecl,
decl,
binExpr,
ctrlExpr
) where
import Control.Applicative
import Text.Parsec hiding ((<|>), many)
import Text.Parsec.String
import Text.Parsec.Expr
import qualified Text.Parsec.Token as T
import Text.Parsec.Language
import SimpleAbstractor.AST
import SimpleAbstractor.Predicate hiding (Pred)
--The lexer
reservedNames = ["case", "true", "false", "else", "abs", "conc", "uint", "bool"]
reservedOps = ["!", "&&", "||", "->", "!=", "==", ":=", "<="]
--Variable types
boolTyp t@T.TokenParser{..} = BoolType <$ reserved "bool"
intTyp t@T.TokenParser{..} = IntType <$ reserved "uint" <*> angles (fromIntegral <$> natural)
enumTyp t@T.TokenParser{..} = EnumType <$> braces (sepBy identifier comma)
typ t@T.TokenParser{..} = boolTyp t <|> intTyp t <|> enumTyp t
tp t@T.TokenParser{..} = (Right <$> typ t) <|> (Left <$> identifier)
--Type declarations
typeDecl t@T.TokenParser{..} = (,) <$> identifier <* colon <*> typ t
--Variable declarations
absTyp t@T.TokenParser{..} = Abs <$ reserved "abs"
nonAbsTyp t@T.TokenParser{..} = NonAbs <$ reserved "conc"
absTypes t@T.TokenParser{..} = absTyp t <|> nonAbsTyp t
decl t@T.TokenParser{..} = Decl <$> sepBy identifier comma <* colon <*> absTypes t <*> tp t
--Expressions
--The Bin expression parser
binExpr t@T.TokenParser{..} = buildExpressionParser (table t) (term t)
<?> "expression"
predicate t@T.TokenParser{..} = try (ASTEqPred Eq <$> valExpr t <* reservedOp "==" <*> valExpr t)
<|> try (ASTEqPred Neq <$> valExpr t <* reservedOp "!=" <*> valExpr t)
term t@T.TokenParser{..} = parens (binExpr t)
<|> TrueE <$ (reserved "true" <|> reserved "else")
<|> FalseE <$ reserved "false"
<|> try (Pred <$> predicate t)
<?> "simple expression"
table t@T.TokenParser{..} = [[prefix t "!" Not]
,[binary t "&&" (Bin And) AssocLeft]
,[binary t "||" (Bin Or) AssocLeft]
,[binary t "->" (Bin Imp) AssocLeft]
]
binary t@T.TokenParser{..} name fun assoc = Infix (fun <$ reservedOp name) assoc
prefix t@T.TokenParser{..} name fun = Prefix (fun <$ reservedOp name)
--Control expressions
assign t@T.TokenParser{..} = Assign <$> identifier <* reservedOp ":=" <*> valExpr t
ccase t@T.TokenParser{..} = CaseC <$ reserved "case" <*> braces (sepEndBy ((,) <$> binExpr t <* colon <*> ctrlExpr t) semi)
conj t@T.TokenParser{..} = Conj <$> braces (sepEndBy (ctrlExpr t) semi)
ctrlExpr t@T.TokenParser{..} = conj t <|> ccase t <|> try (assign t)
--Value expressions
slice t@T.TokenParser{..} = brackets $ f <$> integer <*> optionMaybe (colon *> integer)
where
f start Nothing = (fromIntegral start, fromIntegral start)
f start (Just end) = (fromIntegral start, fromIntegral end)
slicedVar t@T.TokenParser{..} = (,) <$> identifier <*> optionMaybe (slice t)
lit t@T.TokenParser{..} = Lit <$> ((Left <$> slicedVar t) <|> ((Right . fromIntegral) <$> integer))
vcase t@T.TokenParser{..} = CaseV <$ reserved "case" <*> braces (sepEndBy ((,) <$> binExpr t <* colon <*> valExpr t) semi)
valExpr t@T.TokenParser{..} = vcase t <|> lit t
| termite2/simple-abstractor | SimpleAbstractor/Parser.hs | bsd-3-clause | 3,521 | 0 | 13 | 905 | 1,336 | 693 | 643 | 54 | 2 |
-- Reduces lambdas that are immediately applied.
-- Evaluates `(\x -> f x) (g 3)` to `f (g 3)`
module FunVM.Transformations.ReduceLambdaApplication
( transform
, bindEval
, typeEval
, valBindEval
, valEval
, exprEval
, groupEval
, moduleEval
) where
import Data.Function
import Data.List
import Data.Maybe
import FunVM.Core
type Env = [(Id, Expr)]
mnm :: String
mnm = "FunVM.Transformations.SimplePartialEvaluator"
transform :: Module -> Module
transform = moduleEval []
bindEval :: Env -> Bind -> Bind
bindEval env (TermPat x t) = TermPat x (typeEval env t)
bindEval _ (TypePat x k) = TypePat x k
typeEval :: Env -> Type -> Type
typeEval _ (Base b) = Base b
typeEval env (TyVar nm) = maybe (TyVar nm) unLit $ lookup nm env
where
unLit (Val (Lit (Type t))) = t
unLit e = error $ mnm ++ ".typeEval: can't use `" ++ show e ++ "' as type"
typeEval env (Fun bs ts) = Fun (map (bindEval env) bs)
(map (typeEval $ map bindId bs `removeEnv` env) ts)
typeEval env (Lazy ts) = Lazy (map (typeEval env) ts)
typeEval _ Any = Any
valBindEval :: Env -> ValBind -> ValBind
valBindEval env (Bind b v) = Bind (bindEval env b) (valEval env v)
valEval :: Env -> Val -> Val
valEval _ (Lit l) = Lit l
valEval env (Lam bs e) = Lam (map (bindEval env) bs)
(exprEval (map bindId bs `removeEnv` env) e)
valEval env (Delay e) = Delay (exprEval env e)
valEval env (Prim s t) = Prim s (typeEval env t)
exprEval :: Env -> Expr -> Expr
exprEval env (Val (Lam bs e))
| applicable = exprEval env e
where
applicable = all (`elem` nms) (map bindId bs)
nms = map fst env
exprEval env (Val v) = Val (valEval env v)
exprEval env (Var nm) = fromMaybe (Var nm) $ lookup nm env
exprEval env (App e1 e2) =
case (binds e1, vals $ exprEval env e2) of
(bs:_, es)
| length bs == length es -> exprEval (zip (map bindId $ bs) es ++ env) e1
_ -> App (exprEval env e1) (exprEval env e2)
exprEval env (Multi es) = Multi (map (exprEval env) es)
exprEval env (Force e) = Force (exprEval env e)
exprEval env (Let bs e1 e2) = Let (map (bindEval env) bs)
(exprEval env e1)
(exprEval (map bindId bs `removeEnv` env) e2)
exprEval env (LetRec vbs e) = LetRec (groupEval env vbs)
(exprEval env' e)
where
env' = map valBindId vbs `removeEnv` env
binds :: Expr -> [[Bind]]
binds (Val (Lam bs e)) = bs : binds e
binds (App e1 _) = drop 1 (binds e1)
binds _ = []
vals :: Expr -> [Expr]
vals (Multi es) = concatMap vals es
vals e = [e]
groupEval :: Env -> Group -> Group
groupEval env vbs = map (valBindEval env') vbs
where
env' = map valBindId vbs `removeEnv` env
moduleEval :: Env -> Module -> Module
moduleEval env (Module nm is bgs) = Module nm is (map (groupEval env) bgs)
removeEnv :: [Id] -> Env -> Env
removeEnv ids env = foldr (\x env' -> deleteBy ((==) `on` fst) (x, undefined) env') env ids
| tomlokhorst/FunVM | src/FunVM/Transformations/ReduceLambdaApplication.hs | bsd-3-clause | 3,156 | 0 | 15 | 942 | 1,351 | 690 | 661 | 72 | 2 |
import Data.Tree (Tree(..))
tree1 = Node 'a' []
| YoshikuniJujo/funpaala | samples/24_adt_module/adtGoodImport1.hs | bsd-3-clause | 49 | 0 | 6 | 9 | 27 | 15 | 12 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- System grade imports
-- import qualified Data.ByteString as B
-- import qualified Data.ByteString.Builder as Bu
-- import Data.ByteString.Char8 (pack)
-- import qualified Data.ByteString.Lazy as BL
import Data.Foldable (find)
import Data.Monoid
import Text.Printf (printf)
-- import System.Directory
-- import System.FilePath
import Control.Exception (catch)
--
--
import System.Environment (getEnvironment)
import System.IO
-- import System.Process
import Options.Applicative
-- Logging utilities
import System.Log.Formatter (simpleLogFormatter)
import System.Log.Handler (setFormatter, LogHandler)
import System.Log.Handler.Simple
import System.Log.Handler.Syslog (Facility (..), Option (..), openlog)
import System.Log.Logger
-- Imports from other parts of the program
import Rede.MainLoop.ConfigHelp (mimicDataDir)
import Rede.Research.Main (research)
import Rede.MainLoop.OpenSSL_TLS (ConnectionIOError(..))
-- What is the program going to do?
data ProgramAction =
ResearchUrl_PA -- Wait for a POST request from the browser
actionStrToAction :: String -> ProgramAction
actionStrToAction "research" = ResearchUrl_PA
actionStrToAction _ = error "Action doesn't exist"
data Program = Program {
action :: ProgramAction
-- ,harFileName :: String
}
programParser :: Parser Program
programParser = Program <$> (
actionStrToAction <$>
strOption
( long "action"
<> metavar "ACTION"
<> help "What's the program going to do: only \"research\" is supported now." )
)
main :: IO ()
main = do
env_vars <- getEnvironment
case find (\ (name, _) -> name == "MIMIC_CONSOLE_LOGGER") env_vars of
Nothing -> configureLoggingToSyslog
Just (_, x) | not $ (length x) == 0 || x == "0" -> configureLoggingToConsole
| otherwise -> configureLoggingToSyslog
mimic_dir <- mimicDataDir
infoM "RehMimic" $ printf "Mimic dir: \"%s\"" mimic_dir
prg <- execParser opts_metadata
catch
(case Main.action prg of
ResearchUrl_PA -> do
research mimic_dir
)
(\ (ConnectionIOError msg) -> errorM "HTTP2.Session" ("ConnectionIOError: " ++ msg)
)
where
opts_metadata = info
( helper <*> programParser )
( fullDesc
<> progDesc
( "Mimics web servers. Use environmnet variables MIMIC_DATA_DIR to point to where the scratch directory" ++
"of the server is. Use the variable MIMIC_CONSOLE_LOGGER with value 1 to log messages to console; otherwise " ++
"they are going to syslog. " )
<> header "reh-mimic"
)
configureLoggingToConsole :: IO ()
configureLoggingToConsole = do
s <- streamHandler stderr DEBUG >>=
\lh -> return $ setFormatter lh (simpleLogFormatter "[$time : $loggername : $prio] $msg")
setLoggerLevels s
configureLoggingToSyslog :: IO ()
configureLoggingToSyslog = do
s <- openlog "RehMimic" [PID] DAEMON INFO >>=
\lh -> return $ setFormatter lh (simpleLogFormatter "[$time : $loggername : $prio] $msg")
setLoggerLevels s
setLoggerLevels :: (LogHandler s) => s -> IO ()
setLoggerLevels s = do
updateGlobalLogger rootLoggerName removeHandler
updateGlobalLogger "HTTP2.Session" (
setHandlers [s] . -- Remember that composition works in reverse...
setLevel INFO
)
updateGlobalLogger "OpenSSL" (
setHandlers [s] . -- Remember that composition works in reverse...
setLevel INFO
)
updateGlobalLogger "HarWorker" (
setHandlers [s] . -- Remember that composition works in reverse...
setLevel DEBUG
)
updateGlobalLogger "ResearchWorker" (
setHandlers [s] . -- Remember that composition works in reverse...
setLevel DEBUG
) | loadimpact/http2-test | hs-src/reh-mimic.hs | bsd-3-clause | 4,321 | 0 | 18 | 1,359 | 777 | 411 | 366 | 78 | 2 |
module HaskellEditor.Gui.Components
where
import Graphics.UI.Gtk
import HaskQuery
import Control.Concurrent.STM
import HaskellEditor.Types
import HaskellEditor.Dynamic
import HaskellEditor.Gui.Util
mainWindowRef :: WidgetRef Window
mainWindowRef = widgetReference "mainWindow"
buttonBarRef :: WidgetRef HBox
buttonBarRef = widgetReference "buttonBar"
editorPane :: WidgetRef VPaned
editorPane = widgetReference "editorPane"
makeButtonBar :: TVar(Widgets) -> HaskQuery.Relation (Named (IO ())) b -> IO (Widgets)
makeButtonBar widgetTVar buttonCallbacks = do
buttonBar <- hBoxNew False 0
buttonBarButtons <- makeButtons widgetTVar buttonCallbacks
_ <- HaskQuery.runQueryM $ do
namedWidget <- HaskQuery.selectM (_widgets buttonBarButtons)
button <- HaskQuery.selectDynamicWithTypeM buttonProxy (_content namedWidget)
_ <- HaskQuery.executeM (boxPackStart buttonBar button PackNatural 0)
return ()
widgetShowAll buttonBar
let buttonBarRelation = emptyWidgets { _widgets = HaskQuery.insert (_widgets emptyWidgets) $ namedDynamic (_identifier buttonBarRef) buttonBar}
insertWidgets widgetTVar buttonBarRelation
return buttonBarRelation
makeButtons :: TVar(Widgets) -> HaskQuery.Relation (Named (IO ())) b -> IO (Widgets)
makeButtons widgetTVar buttonCallbacks = do
openProjectButton <- fmap (namedDynamic "openProjectButton") $ buttonNewWithLabel "Open Project"
saveButton <- fmap (namedDynamic "saveProjectButton") $ buttonNewWithMnemonic "_Save Files"
refreshButton <- fmap (namedDynamic "refreshProjectButton") $ buttonNewWithMnemonic "S_ynchronize Folders"
let buttons = emptyWidgets { _widgets = HaskQuery.insertRows (_widgets emptyWidgets) [openProjectButton, saveButton, refreshButton]}
insertWidgets widgetTVar buttons
_ <- HaskQuery.runQueryM $ do
widgets <- getWidgets widgetTVar
callback <- HaskQuery.selectM buttonCallbacks
button <- selectWidget widgets (_identifier callback) buttonProxy
_ <- HaskQuery.executeM $ onClicked button (_content callback)
return ()
return buttons
newFileChooser :: (FilePath -> IO t) -> IO ()
newFileChooser handleChoice = do
window <- windowNew
set window [windowDefaultWidth := 800, windowDefaultHeight := 600]
fch <- fileChooserWidgetNew FileChooserActionOpen
containerAdd window fch
_ <- on fch fileActivated $
do filePath <- fileChooserGetFilename fch
case filePath of
Just dpath -> do
_ <- handleChoice dpath
widgetDestroy window
Nothing -> return ()
_ <- fileChooserSetCurrentFolder fch "."
widgetShowAll fch
widgetShowAll window
return ()
createMainWindow :: TVar (Widgets) -> IO()
createMainWindow widgetTVar = do
window <- windowNew
set window [windowDefaultWidth := 800, windowDefaultHeight := 500]
_ <- onDestroy window mainQuit
insertWidget mainWindowRef window widgetTVar
return ()
| stevechy/haskellEditor | src/HaskellEditor/Gui/Components.hs | bsd-3-clause | 3,104 | 0 | 17 | 679 | 844 | 392 | 452 | 64 | 2 |
module Intel.ArBB.Backend.Scalar where
data BEScalar a = BEScalar {beScalarID :: Integer}
-- for now, this is taken care of by specialized code in Backend.ArBB
--class Scalar a where
-- mkScalar :: BackendMonad m => a -> m (BEScalar a)
| svenssonjoel/EmbArBB | Intel/ArBB/Backend/Scalar.hs | bsd-3-clause | 252 | 0 | 8 | 55 | 27 | 19 | 8 | 2 | 0 |
{-# LANGUAGE RecordWildCards #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.List
import Data.Maybe
import Distribution.PackageDescription.Parse
import Distribution.Text
import Distribution.System
import Distribution.Package
import Distribution.PackageDescription hiding (options)
import Distribution.Verbosity
import System.Console.GetOpt
import System.Environment
import System.Directory
import System.IO.Error
import System.Process
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Zip as Zip
import qualified Codec.Compression.GZip as GZip
import Data.Aeson
import qualified Data.CaseInsensitive as CI
import Data.Conduit
import qualified Data.Conduit.Combinators as CC
import Data.List.Extra
import qualified Data.Text as T
import Development.Shake
import Development.Shake.FilePath
import Network.HTTP.Conduit
import Network.HTTP.Types
import Network.Mime
import Prelude -- Silence AMP warning
-- | Entrypoint.
main :: IO ()
main =
shakeArgsWith
shakeOptions { shakeFiles = releaseDir
, shakeVerbosity = Chatty
, shakeChange = ChangeModtimeAndDigestInput }
options $
\flags args -> do
gStackPackageDescription <-
packageDescription <$> readPackageDescription silent "stack.cabal"
gGithubAuthToken <- lookupEnv githubAuthTokenEnvVar
gGitRevCount <- length . lines <$> readProcess "git" ["rev-list", "HEAD"] ""
gGitSha <- trim <$> readProcess "git" ["rev-parse", "HEAD"] ""
gHomeDir <- getHomeDirectory
let gGpgKey = "0x575159689BEFB442"
gAllowDirty = False
gGithubReleaseTag = Nothing
Platform arch _ = buildPlatform
gArch = arch
gBinarySuffix = ""
gUploadLabel = Nothing
gTestHaddocks = True
gProjectRoot = "" -- Set to real value velow.
gBuildArgs = []
global0 = foldl (flip id) Global{..} flags
-- Need to get paths after options since the '--arch' argument can effect them.
projectRoot' <- getStackPath global0 "project-root"
let global = global0
{ gProjectRoot = projectRoot' }
return $ Just $ rules global args
where
getStackPath global path = do
out <- readProcess stackProgName (stackArgs global ++ ["path", "--" ++ path]) ""
return $ trim $ fromMaybe out $ stripPrefix (path ++ ":") out
-- | Additional command-line options.
options :: [OptDescr (Either String (Global -> Global))]
options =
[ Option "" [gpgKeyOptName]
(ReqArg (\v -> Right $ \g -> g{gGpgKey = v}) "USER-ID")
"GPG user ID to sign distribution package with."
, Option "" [allowDirtyOptName] (NoArg $ Right $ \g -> g{gAllowDirty = True})
"Allow a dirty working tree for release."
, Option "" [githubAuthTokenOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubAuthToken = Just v}) "TOKEN")
("Github personal access token (defaults to " ++
githubAuthTokenEnvVar ++
" environment variable).")
, Option "" [githubReleaseTagOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubReleaseTag = Just v}) "TAG")
"Github release tag to upload to."
, Option "" [archOptName]
(ReqArg
(\v -> case simpleParse v of
Nothing -> Left $ "Unknown architecture in --arch option: " ++ v
Just arch -> Right $ \g -> g{gArch = arch})
"ARCHITECTURE")
"Architecture to build (e.g. 'i386' or 'x86_64')."
, Option "" [binaryVariantOptName]
(ReqArg (\v -> Right $ \g -> g{gBinarySuffix = v}) "SUFFIX")
"Extra suffix to add to binary executable archive filename."
, Option "" [uploadLabelOptName]
(ReqArg (\v -> Right $ \g -> g{gUploadLabel = Just v}) "LABEL")
"Label to give the uploaded release asset"
, Option "" [noTestHaddocksOptName] (NoArg $ Right $ \g -> g{gTestHaddocks = False})
"Disable testing building haddocks."
, Option "" [buildArgsOptName]
(ReqArg
(\v -> Right $ \g -> g{gBuildArgs = words v})
"\"ARG1 ARG2 ...\"")
"Additional arguments to pass to 'stack build'."
]
-- | Shake rules.
rules :: Global -> [String] -> Rules ()
rules global@Global{..} args = do
case args of
[] -> error "No wanted target(s) specified."
_ -> want args
phony releasePhony $ do
need [checkPhony]
need [uploadPhony]
phony cleanPhony $
removeFilesAfter releaseDir ["//*"]
phony checkPhony $
need [releaseCheckDir </> binaryExeFileName]
phony uploadPhony $
mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryPkgFileNames
phony buildPhony $
mapM_ (\f -> need [releaseDir </> f]) binaryPkgFileNames
distroPhonies ubuntuDistro ubuntuVersions debPackageFileName
distroPhonies debianDistro debianVersions debPackageFileName
distroPhonies centosDistro centosVersions rpmPackageFileName
distroPhonies fedoraDistro fedoraVersions rpmPackageFileName
releaseDir </> "*" <.> uploadExt %> \out -> do
let srcFile = dropExtension out
mUploadLabel =
if takeExtension srcFile == ascExt
then fmap (++ " (GPG signature)") gUploadLabel
else gUploadLabel
uploadToGithubRelease global srcFile mUploadLabel
copyFileChanged srcFile out
releaseCheckDir </> binaryExeFileName %> \out -> do
need [releaseBinDir </> binaryName </> stackExeFileName]
Stdout dirty <- cmd "git status --porcelain"
when (not gAllowDirty && not (null (trim dirty))) $
error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.")
withTempDir $ \tmpDir -> do
let cmd0 = cmd (releaseBinDir </> binaryName </> stackExeFileName)
(stackArgs global)
gBuildArgs
["--local-bin-path=" ++ tmpDir]
() <- cmd0 $ concat $ concat
[["install --pedantic --no-haddock-deps"], [" --haddock" | gTestHaddocks]]
() <- cmd0 "install --resolver=lts-6.0 cabal-install"
let cmd' = cmd (AddPath [tmpDir] []) stackProgName (stackArgs global) gBuildArgs
() <- cmd' "test --pedantic --flag stack:integration-tests"
return ()
copyFileChanged (releaseBinDir </> binaryName </> stackExeFileName) out
releaseDir </> binaryPkgZipFileName %> \out -> do
stageFiles <- getBinaryPkgStageFiles
putNormal $ "zip " ++ out
liftIO $ do
entries <- forM stageFiles $ \stageFile -> do
Zip.readEntry
[Zip.OptLocation
(dropDirectoryPrefix (releaseStageDir </> binaryName) stageFile)
False]
stageFile
let archive = foldr Zip.addEntryToArchive Zip.emptyArchive entries
L8.writeFile out (Zip.fromArchive archive)
releaseDir </> binaryPkgTarGzFileName %> \out -> do
stageFiles <- getBinaryPkgStageFiles
writeTarGz out releaseStageDir stageFiles
releaseStageDir </> binaryName </> stackExeFileName %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
releaseStageDir </> (binaryName ++ "//*") %> \out -> do
copyFileChanged
(dropDirectoryPrefix (releaseStageDir </> binaryName) out)
out
releaseDir </> binaryExeFileName %> \out -> do
need [releaseBinDir </> binaryName </> stackExeFileName]
(Stdout versionOut) <- cmd (releaseBinDir </> binaryName </> stackExeFileName) "--version"
when (not gAllowDirty && "dirty" `isInfixOf` lower versionOut) $
error ("Refusing continue because 'stack --version' reports dirty. Use --" ++
allowDirtyOptName ++ " option to continue anyway.")
case platformOS of
Windows -> do
-- Windows doesn't have or need a 'strip' command, so skip it.
-- Instead, we sign the executable
liftIO $ copyFile (releaseBinDir </> binaryName </> stackExeFileName) out
actionOnException
(command_ [] "c:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\signtool.exe"
["sign"
,"/v"
,"/d", synopsis gStackPackageDescription
,"/du", homepage gStackPackageDescription
,"/n", "FP Complete, Corporation"
,"/t", "http://timestamp.verisign.com/scripts/timestamp.dll"
,out])
(removeFile out)
Linux ->
cmd "strip -p --strip-unneeded --remove-section=.comment -o"
[out, releaseBinDir </> binaryName </> stackExeFileName]
_ ->
cmd "strip -o"
[out, releaseBinDir </> binaryName </> stackExeFileName]
releaseDir </> binaryPkgSignatureFileName %> \out -> do
need [out -<.> ""]
_ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out)
cmd ("gpg " ++ gpgOptions ++ " --detach-sig --armor")
[ "-u", gGpgKey
, dropExtension out ]
releaseBinDir </> binaryName </> stackExeFileName %> \out -> do
alwaysRerun
actionOnException
(cmd stackProgName
(stackArgs global)
gBuildArgs
["--local-bin-path=" ++ takeDirectory out]
"install --pedantic")
(removeFile out)
debDistroRules ubuntuDistro ubuntuVersions
debDistroRules debianDistro debianVersions
rpmDistroRules centosDistro centosVersions
rpmDistroRules fedoraDistro fedoraVersions
where
debDistroRules debDistro0 debVersions = do
let anyVersion0 = anyDistroVersion debDistro0
distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 <.> uploadExt %> \out -> do
let DistroVersion{..} = distroVersionFromPath out debVersions
pkgFile = dropExtension out
need [pkgFile]
() <- cmd "deb-s3 upload --preserve-versions --bucket download.fpcomplete.com"
[ "--sign=" ++ gGpgKey
, "--gpg-options=" ++ replace "-" "\\-" gpgOptions
, "--prefix=" ++ dvDistro
, "--codename=" ++ dvCodeName
, pkgFile ]
-- Also upload to the old, incorrect location for people who still have their systems
-- configured with it.
() <- cmd "deb-s3 upload --preserve-versions --bucket download.fpcomplete.com"
[ "--sign=" ++ gGpgKey
, "--gpg-options=" ++ replace "-" "\\-" gpgOptions
, "--prefix=" ++ dvDistro ++ "/" ++ dvCodeName
, pkgFile ]
copyFileChanged pkgFile out
distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 %> \out -> do
docFiles <- getDocFiles
let dv@DistroVersion{..} = distroVersionFromPath out debVersions
inputFiles = concat
[[debStagedExeFile dv
,debStagedBashCompletionFile dv]
,map (debStagedDocDir dv </>) docFiles]
need inputFiles
cmd "fpm -f -s dir -t deb"
"--deb-recommends git --deb-recommends gnupg"
"-d g++ -d gcc -d libc6-dev -d libffi-dev -d libgmp-dev -d make -d xz-utils -d zlib1g-dev"
["-n", stackProgName
,"-C", debStagingDir dv
,"-v", debPackageVersionStr dv
,"-p", out
,"-m", maintainer gStackPackageDescription
,"--description", synopsis gStackPackageDescription
,"--license", display (license gStackPackageDescription)
,"--url", homepage gStackPackageDescription]
(map (dropDirectoryPrefix (debStagingDir dv)) inputFiles)
debStagedExeFile anyVersion0 %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
debStagedBashCompletionFile anyVersion0 %> \out -> do
let dv = distroVersionFromPath out debVersions
writeBashCompletion (debStagedExeFile dv) out
debStagedDocDir anyVersion0 ++ "//*" %> \out -> do
let dv@DistroVersion{..} = distroVersionFromPath out debVersions
origFile = dropDirectoryPrefix (debStagedDocDir dv) out
copyFileChanged origFile out
rpmDistroRules rpmDistro0 rpmVersions = do
let anyVersion0 = anyDistroVersion rpmDistro0
distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 <.> uploadExt %> \out -> do
let DistroVersion{..} = distroVersionFromPath out rpmVersions
pkgFile = dropExtension out
need [pkgFile]
let rpmmacrosFile = gHomeDir </> ".rpmmacros"
rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile
when rpmmacrosExists $
error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.")
actionFinally
(do writeFileLines rpmmacrosFile
[ "%_signature gpg"
, "%_gpg_name " ++ gGpgKey ]
() <- cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com"
[ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion
, pkgFile ]
return ())
(liftIO $ removeFile rpmmacrosFile)
copyFileChanged pkgFile out
distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 %> \out -> do
docFiles <- getDocFiles
let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions
inputFiles = concat
[[rpmStagedExeFile dv
,rpmStagedBashCompletionFile dv]
,map (rpmStagedDocDir dv </>) docFiles]
need inputFiles
cmd "fpm -s dir -t rpm"
"-d perl -d make -d automake -d gcc -d gmp-devel -d libffi -d zlib -d xz -d tar"
["-n", stackProgName
,"-C", rpmStagingDir dv
,"-v", rpmPackageVersionStr dv
,"--iteration", rpmPackageIterationStr dv
,"-p", out
,"-m", maintainer gStackPackageDescription
,"--description", synopsis gStackPackageDescription
,"--license", display (license gStackPackageDescription)
,"--url", homepage gStackPackageDescription]
(map (dropDirectoryPrefix (rpmStagingDir dv)) inputFiles)
rpmStagedExeFile anyVersion0 %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
rpmStagedBashCompletionFile anyVersion0 %> \out -> do
let dv = distroVersionFromPath out rpmVersions
writeBashCompletion (rpmStagedExeFile dv) out
rpmStagedDocDir anyVersion0 ++ "//*" %> \out -> do
let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions
origFile = dropDirectoryPrefix (rpmStagedDocDir dv) out
copyFileChanged origFile out
writeBashCompletion stagedStackExeFile out = do
need [stagedStackExeFile]
(Stdout bashCompletionScript) <- cmd [stagedStackExeFile] "--bash-completion-script" [stackProgName]
writeFileChanged out bashCompletionScript
getBinaryPkgStageFiles = do
docFiles <- getDocFiles
let stageFiles = concat
[[releaseStageDir </> binaryName </> stackExeFileName]
,map ((releaseStageDir </> binaryName) </>) docFiles]
need stageFiles
return stageFiles
getDocFiles = getDirectoryFiles "." ["LICENSE", "*.md", "doc//*.md"]
distroVersionFromPath path versions =
let path' = dropDirectoryPrefix releaseDir path
version = takeDirectory1 (dropDirectory1 path')
in DistroVersion (takeDirectory1 path') version (lookupVersionCodeName version versions)
distroPhonies distro0 versions0 makePackageFileName =
forM_ versions0 $ \(version0,_) -> do
let dv@DistroVersion{..} = DistroVersion distro0 version0 (lookupVersionCodeName version0 versions0)
phony (distroUploadPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv <.> uploadExt]
phony (distroBuildPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv]
lookupVersionCodeName version versions =
fromMaybe (error $ "lookupVersionCodeName: could not find " ++ show version ++ " in " ++ show versions) $
lookup version versions
releasePhony = "release"
checkPhony = "check"
uploadPhony = "upload"
cleanPhony = "clean"
buildPhony = "build"
distroUploadPhony DistroVersion{..} = "upload-" ++ dvDistro ++ "-" ++ dvVersion
distroBuildPhony DistroVersion{..} = "build-" ++ dvDistro ++ "-" ++ dvVersion
releaseCheckDir = releaseDir </> "check"
releaseStageDir = releaseDir </> "stage"
releaseBinDir = releaseDir </> "bin"
distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion
binaryPkgFileNames = [binaryPkgFileName, binaryPkgSignatureFileName]
binaryPkgSignatureFileName = binaryPkgFileName <.> ascExt
binaryPkgFileName =
case platformOS of
Windows -> binaryPkgZipFileName
_ -> binaryPkgTarGzFileName
binaryPkgZipFileName = binaryName <.> zipExt
binaryPkgTarGzFileName = binaryName <.> tarGzExt
binaryExeFileName = binaryName <.> exe
binaryName =
concat
[ stackProgName
, "-"
, stackVersionStr global
, "-"
, display platformOS
, "-"
, display gArch
, if null gBinarySuffix then "" else "-" ++ gBinarySuffix ]
stackExeFileName = stackProgName <.> exe
debStagedDocDir dv = debStagingDir dv </> "usr/share/doc" </> stackProgName
debStagedBashCompletionFile dv = debStagingDir dv </> "etc/bash_completion.d/stack"
debStagedExeFile dv = debStagingDir dv </> "usr/bin/stack"
debStagingDir dv = distroVersionDir dv </> debPackageName dv
debPackageFileName dv = debPackageName dv <.> debExt
debPackageName dv = stackProgName ++ "_" ++ debPackageVersionStr dv ++ "_amd64"
debPackageVersionStr DistroVersion{..} = stackVersionStr global ++ "-0~" ++ dvCodeName
rpmStagedDocDir dv = rpmStagingDir dv </> "usr/share/doc" </> (stackProgName ++ "-" ++ rpmPackageVersionStr dv)
rpmStagedBashCompletionFile dv = rpmStagingDir dv </> "etc/bash_completion.d/stack"
rpmStagedExeFile dv = rpmStagingDir dv </> "usr/bin/stack"
rpmStagingDir dv = distroVersionDir dv </> rpmPackageName dv
rpmPackageFileName dv = rpmPackageName dv <.> rpmExt
rpmPackageName dv = stackProgName ++ "-" ++ rpmPackageVersionStr dv ++ "-" ++ rpmPackageIterationStr dv ++ ".x86_64"
rpmPackageIterationStr DistroVersion{..} = "0." ++ dvCodeName
rpmPackageVersionStr _ = stackVersionStr global
ubuntuVersions =
[ ("12.04", "precise")
, ("14.04", "trusty")
, ("14.10", "utopic")
, ("15.04", "vivid")
, ("15.10", "wily")
, ("16.04", "xenial") ]
debianVersions =
[ ("7", "wheezy")
, ("8", "jessie") ]
centosVersions =
[ ("7", "el7")
, ("6", "el6") ]
fedoraVersions =
[ ("22", "fc22")
, ("23", "fc23") ]
ubuntuDistro = "ubuntu"
debianDistro = "debian"
centosDistro = "centos"
fedoraDistro = "fedora"
anyDistroVersion distro = DistroVersion distro "*" "*"
zipExt = ".zip"
tarGzExt = tarExt <.> gzExt
gzExt = ".gz"
tarExt = ".tar"
ascExt = ".asc"
uploadExt = ".upload"
debExt = ".deb"
rpmExt = ".rpm"
-- | Upload file to Github release.
uploadToGithubRelease :: Global -> FilePath -> Maybe String -> Action ()
uploadToGithubRelease global@Global{..} file mUploadLabel = do
need [file]
putNormal $ "Uploading to Github: " ++ file
GithubRelease{..} <- getGithubRelease
resp <- liftIO $ callGithubApi global
[(CI.mk $ S8.pack "Content-Type", defaultMimeLookup (T.pack file))]
(Just file)
(replace
"{?name,label}"
("?name=" ++ urlEncodeStr (takeFileName file) ++
(case mUploadLabel of
Nothing -> ""
Just uploadLabel -> "&label=" ++ urlEncodeStr uploadLabel))
relUploadUrl)
case eitherDecode resp of
Left e -> error ("Could not parse Github asset upload response (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right (GithubReleaseAsset{..}) ->
when (assetState /= "uploaded") $
error ("Invalid asset state after Github asset upload: " ++ assetState)
where
urlEncodeStr = S8.unpack . urlEncode True . S8.pack
getGithubRelease = do
releases <- getGithubReleases
let tag = fromMaybe ("v" ++ stackVersionStr global) gGithubReleaseTag
return $ fromMaybe
(error ("Could not find Github release with tag '" ++ tag ++ "'.\n" ++
"Use --" ++ githubReleaseTagOptName ++ " option to specify a different tag."))
(find (\r -> relTagName r == tag) releases)
getGithubReleases :: Action [GithubRelease]
getGithubReleases = do
resp <- liftIO $ callGithubApi global
[] Nothing "https://api.github.com/repos/commercialhaskell/stack/releases"
case eitherDecode resp of
Left e -> error ("Could not parse Github releases (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right r -> return r
-- | Make a request to the Github API and return the response.
callGithubApi :: Global -> RequestHeaders -> Maybe FilePath -> String -> IO L8.ByteString
callGithubApi Global{..} headers mpostFile url = do
req0 <- parseUrl url
let authToken =
fromMaybe
(error $
"Github auth token required.\n" ++
"Use " ++ githubAuthTokenEnvVar ++ " environment variable\n" ++
"or --" ++ githubAuthTokenOptName ++ " option to specify.")
gGithubAuthToken
req1 =
req0
{ checkStatus = \_ _ _ -> Nothing
, requestHeaders =
[ (CI.mk $ S8.pack "Authorization", S8.pack $ "token " ++ authToken)
, (CI.mk $ S8.pack "User-Agent", S8.pack "commercialhaskell/stack") ] ++
headers }
req <- case mpostFile of
Nothing -> return req1
Just postFile -> do
lbs <- L8.readFile postFile
return $ req1
{ method = S8.pack "POST"
, requestBody = RequestBodyLBS lbs }
manager <- newManager tlsManagerSettings
runResourceT $ do
res <- http req manager
responseBody res $$+- CC.sinkLazy
-- | Create a .tar.gz files from files. The paths should be absolute, and will
-- be made relative to the base directory in the tarball.
writeTarGz :: FilePath -> FilePath -> [FilePath] -> Action ()
writeTarGz out baseDir inputFiles = liftIO $ do
content <- Tar.pack baseDir $ map (dropDirectoryPrefix baseDir) inputFiles
L8.writeFile out $ GZip.compress $ Tar.write content
-- | Drops a directory prefix from a path. The prefix automatically has a path
-- separator character appended. Fails if the path does not begin with the prefix.
dropDirectoryPrefix :: FilePath -> FilePath -> FilePath
dropDirectoryPrefix prefix path =
case stripPrefix (toStandard prefix ++ "/") (toStandard path) of
Nothing -> error ("dropDirectoryPrefix: cannot drop " ++ show prefix ++ " from " ++ show path)
Just stripped -> stripped
-- | String representation of stack package version.
stackVersionStr :: Global -> String
stackVersionStr =
display . pkgVersion . package . gStackPackageDescription
-- | Current operating system.
platformOS :: OS
platformOS =
let Platform _ os = buildPlatform
in os
-- | Directory in which to store build and intermediate files.
releaseDir :: FilePath
releaseDir = "_release"
-- | @GITHUB_AUTH_TOKEN@ environment variale name.
githubAuthTokenEnvVar :: String
githubAuthTokenEnvVar = "GITHUB_AUTH_TOKEN"
-- | @--github-auth-token@ command-line option name.
githubAuthTokenOptName :: String
githubAuthTokenOptName = "github-auth-token"
-- | @--github-release-tag@ command-line option name.
githubReleaseTagOptName :: String
githubReleaseTagOptName = "github-release-tag"
-- | @--gpg-key@ command-line option name.
gpgKeyOptName :: String
gpgKeyOptName = "gpg-key"
-- | @--allow-dirty@ command-line option name.
allowDirtyOptName :: String
allowDirtyOptName = "allow-dirty"
-- | @--arch@ command-line option name.
archOptName :: String
archOptName = "arch"
-- | @--binary-variant@ command-line option name.
binaryVariantOptName :: String
binaryVariantOptName = "binary-variant"
-- | @--upload-label@ command-line option name.
uploadLabelOptName :: String
uploadLabelOptName = "upload-label"
-- | @--no-test-haddocks@ command-line option name.
noTestHaddocksOptName :: String
noTestHaddocksOptName = "no-test-haddocks"
buildArgsOptName :: String
buildArgsOptName = "build-args"
-- | Arguments to pass to all 'stack' invocations.
stackArgs :: Global -> [String]
stackArgs Global{..} = ["--install-ghc", "--arch=" ++ display gArch]
-- | Name of the 'stack' program.
stackProgName :: FilePath
stackProgName = "stack"
-- | Options to pass to invocations of gpg
gpgOptions :: String
gpgOptions = "--digest-algo=sha512"
-- | Linux distribution/version combination.
data DistroVersion = DistroVersion
{ dvDistro :: !String
, dvVersion :: !String
, dvCodeName :: !String }
-- | A Github release, as returned by the Github API.
data GithubRelease = GithubRelease
{ relUploadUrl :: !String
, relTagName :: !String }
deriving (Show)
instance FromJSON GithubRelease where
parseJSON = withObject "GithubRelease" $ \o ->
GithubRelease
<$> o .: T.pack "upload_url"
<*> o .: T.pack "tag_name"
-- | A Github release asset, as returned by the Github API.
data GithubReleaseAsset = GithubReleaseAsset
{ assetState :: !String }
deriving (Show)
instance FromJSON GithubReleaseAsset where
parseJSON = withObject "GithubReleaseAsset" $ \o ->
GithubReleaseAsset
<$> o .: T.pack "state"
-- | Global values and options.
data Global = Global
{ gStackPackageDescription :: !PackageDescription
, gGpgKey :: !String
, gAllowDirty :: !Bool
, gGithubAuthToken :: !(Maybe String)
, gGithubReleaseTag :: !(Maybe String)
, gGitRevCount :: !Int
, gGitSha :: !String
, gProjectRoot :: !FilePath
, gHomeDir :: !FilePath
, gArch :: !Arch
, gBinarySuffix :: !String
, gUploadLabel :: (Maybe String)
, gTestHaddocks :: !Bool
, gBuildArgs :: [String] }
deriving (Show)
| sjakobi/stack | etc/scripts/release.hs | bsd-3-clause | 27,543 | 0 | 25 | 7,757 | 6,147 | 3,143 | 3,004 | 586 | 7 |
{-Obsolete-}
{-# LANGUAGE DeriveFunctor #-}
module Andromeda.ControlEnvironment.Language where
import qualified Data.Vector as V
import qualified Data.Map as M
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS
import Control.Monad.Free
import Hardware.Scheme
data Condition = Condition
data Controller = Controller
data Action a
= LoadScheme Scheme a
| Wait Float a
| Periodic Float a
| InitController Hardware (Controller -> a)
| DeinitController Controller a
| Save Parameter Value a
deriving (Functor)
type ControlProgram = Free Action
data SchemeHint = SchemeHint
data HardwareHint = HardwareHint
scheme = ProfileHint
hardware = HardwareHint
load :: SchemeHint -> Scheme -> ControlProgram ()
load _ s = liftF (LoadScheme s ())
get :: HardwareHint -> Address -> ControlProgram Descriptor
get _ addr = liftF (GetHardware addr id)
init :: Descriptor -> ControlProgram Controller
init h = liftF (InitController h id)
deinit :: Controller -> ControlProgram ()
deinit controller = liftF (DeinitController controller)
wait :: Float -> ControlProgram ()
wait time = liftF (Wait time ())
save :: Parameter -> Value -> ControlProgram ()
save p v = liftF (Save p v ())
status = Status
temperature = Temperature
start = Start
stop = Stop
power = Power
float = FloatValue
int = BoolValue
| graninas/Andromeda | trash/Language.hs | bsd-3-clause | 1,358 | 0 | 8 | 244 | 416 | 229 | 187 | 42 | 1 |
{-# LANGUAGE PatternGuards #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Delaborate (annName, bugaddr, delab, delab', delabMV, delabTy, delabTy', fancifyAnnots, pprintDelab, pprintDelabTy, pprintErr) where
-- Convert core TT back into high level syntax, primarily for display
-- purposes.
import Util.Pretty
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Docstrings (overview, renderDocstring, renderDocTerm)
import Idris.ErrReverse
import Prelude hiding ((<$>))
import Data.Maybe (mapMaybe)
import Data.List (intersperse, nub)
import qualified Data.Text as T
import Control.Monad.State
import Debug.Trace
bugaddr = "https://github.com/idris-lang/Idris-dev/issues"
delab :: IState -> Term -> PTerm
delab i tm = delab' i tm False False
delabMV :: IState -> Term -> PTerm
delabMV i tm = delab' i tm False True
delabTy :: IState -> Name -> PTerm
delabTy i n
= case lookupTy n (tt_ctxt i) of
(ty:_) -> case lookupCtxt n (idris_implicits i) of
(imps:_) -> delabTy' i imps ty False False
_ -> delabTy' i [] ty False False
[] -> error "delabTy: got non-existing name"
delab' :: IState -> Term -> Bool -> Bool -> PTerm
delab' i t f mvs = delabTy' i [] t f mvs
delabTy' :: IState -> [PArg] -- ^ implicit arguments to type, if any
-> Term
-> Bool -- ^ use full names
-> Bool -- ^ Don't treat metavariables specially
-> PTerm
delabTy' ist imps tm fullname mvs = de [] imps tm
where
un = fileFC "(val)"
de env _ (App _ f a) = resugarApp env $ deFn env f [a]
de env _ (V i) | i < length env = PRef un (snd (env!!i))
| otherwise = PRef un (sUN ("v" ++ show i ++ ""))
de env _ (P _ n _) | n == unitTy = PTrue un IsType
| n == unitCon = PTrue un IsTerm
| Just n' <- lookup n env = PRef un n'
| otherwise
= case lookup n (idris_metavars ist) of
Just (Just _, mi, _) -> mkMVApp n []
_ -> PRef un n
de env _ (Bind n (Lam ty) sc)
= PLam un n NoFC (de env [] ty) (de ((n,n):env) [] sc)
de env is (Bind n (Pi (Just impl) ty _) sc)
| tcinstance impl
= PPi constraint n NoFC (de env [] ty) (de ((n,n):env) is sc)
| otherwise
= PPi (Imp [] Dynamic False (Just impl)) n NoFC (de env [] ty) (de ((n,n):env) is sc)
de env ((PImp { argopts = opts }):is) (Bind n (Pi _ ty _) sc)
= PPi (Imp opts Dynamic False Nothing) n NoFC (de env [] ty) (de ((n,n):env) is sc)
de env (PConstraint _ _ _ _:is) (Bind n (Pi _ ty _) sc)
= PPi constraint n NoFC (de env [] ty) (de ((n,n):env) is sc)
de env (PTacImplicit _ _ _ tac _:is) (Bind n (Pi _ ty _) sc)
= PPi (tacimpl tac) n NoFC (de env [] ty) (de ((n,n):env) is sc)
de env (plic:is) (Bind n (Pi _ ty _) sc)
= PPi (Exp (argopts plic) Dynamic False)
n NoFC
(de env [] ty)
(de ((n,n):env) is sc)
de env [] (Bind n (Pi _ ty _) sc)
= PPi expl n NoFC (de env [] ty) (de ((n,n):env) [] sc)
de env imps (Bind n (Let ty val) sc)
| isCaseApp sc
, (P _ cOp _, args) <- unApply sc
, Just caseblock <- delabCase env imps n val cOp args = caseblock
| otherwise =
PLet un n NoFC (de env [] ty) (de env [] val) (de ((n,n):env) [] sc)
de env _ (Bind n (Hole ty) sc) = de ((n, sUN "[__]"):env) [] sc
de env _ (Bind n (Guess ty val) sc) = de ((n, sUN "[__]"):env) [] sc
de env plic (Bind n bb sc) = de ((n,n):env) [] sc
de env _ (Constant i) = PConstant NoFC i
de env _ (Proj _ _) = error "Delaboration got run-time-only Proj!"
de env _ Erased = Placeholder
de env _ Impossible = Placeholder
de env _ (TType i) = PType un
de env _ (UType u) = PUniverse u
dens x | fullname = x
dens ns@(NS n _) = case lookupCtxt n (idris_implicits ist) of
[_] -> n -- just one thing
[] -> n -- metavariables have no implicits
_ -> ns
dens n = n
deFn env (App _ f a) args = deFn env f (a:args)
deFn env (P _ n _) [l,r]
| n == pairTy = PPair un IsType (de env [] l) (de env [] r)
| n == sUN "lazy" = de env [] r -- TODO: Fix string based matching
deFn env (P _ n _) [ty, Bind x (Lam _) r]
| n == sigmaTy
= PDPair un IsType (PRef un x) (de env [] ty)
(de ((x,x):env) [] (instantiate (P Bound x ty) r))
deFn env (P _ n _) [lt,rt,l,r]
| n == pairCon = PPair un IsTerm (de env [] l) (de env [] r)
| n == sigmaCon = PDPair un IsTerm (de env [] l) Placeholder
(de env [] r)
deFn env f@(P _ n _) args
| n `elem` map snd env
= PApp un (de env [] f) (map pexp (map (de env []) args))
deFn env (P _ n _) args
| not mvs = case lookup n (idris_metavars ist) of
Just (Just _, mi, _) ->
mkMVApp n (drop mi (map (de env []) args))
_ -> mkPApp n (map (de env []) args)
| otherwise = mkPApp n (map (de env []) args)
deFn env f args = PApp un (de env [] f) (map pexp (map (de env []) args))
mkMVApp n []
= PMetavar NoFC n
mkMVApp n args
= PApp un (PMetavar NoFC n) (map pexp args)
mkPApp n args
| Just imps <- lookupCtxtExact n (idris_implicits ist)
= PApp un (PRef un n) (zipWith imp (imps ++ repeat (pexp undefined)) args)
| otherwise = PApp un (PRef un n) (map pexp args)
imp (PImp p m l n _) arg = PImp p m l n arg
imp (PExp p l n _) arg = PExp p l n arg
imp (PConstraint p l n _) arg = PConstraint p l n arg
imp (PTacImplicit p l n sc _) arg = PTacImplicit p l n sc arg
isCaseApp tm | P _ n _ <- fst (unApply tm) = isCN n
| otherwise = False
where isCN (NS n _) = isCN n
isCN (SN (CaseN _)) = True
isCN _ = False
resugarApp env (PApp _ (PRef _ n) args)
| [c, t, f] <- mapMaybe explicitTerm args
, basename n == sUN "ifThenElse"
= PIfThenElse un c (dedelay t) (dedelay f)
where dedelay (PApp _ (PRef _ delay) [_, _, obj])
| delay == sUN "Delay" = getTm obj
dedelay x = x
explicitTerm (PExp {getTm = tm}) = Just tm
explicitTerm _ = Nothing
resugarApp env tm = tm
delabCase :: [(Name, Name)] -> [PArg] -> Name -> Term -> Name -> [Term] -> Maybe PTerm
delabCase env imps scvar scrutinee caseName caseArgs =
do cases <- case lookupCtxt caseName (idris_patdefs ist) of
[(cases, _)] -> return cases
_ -> Nothing
return $ PCase un (de env imps scrutinee)
[ (de (env ++ map (\n -> (n, n)) vars) imps (splitArg lhs),
de (env ++ map (\n -> (n, n)) vars) imps rhs)
| (vars, lhs, rhs) <- cases
]
where splitArg tm | (_, args) <- unApply tm = nonVar (reverse args)
| otherwise = tm
nonVar [] = error "Tried to delaborate empty case list"
nonVar [x] = x
nonVar (x@(App _ _ _) : _) = x
nonVar (x@(P (DCon _ _ _) _ _) : _) = x
nonVar (x:xs) = nonVar xs
-- | How far to indent sub-errors
errorIndent :: Int
errorIndent = 8
-- | Actually indent a sub-error - no line at end because a newline can end
-- multiple layers of indent
indented :: Doc a -> Doc a
indented = nest errorIndent . (line <>)
-- | Pretty-print a core term using delaboration
pprintDelab :: IState -> Term -> Doc OutputAnnotation
pprintDelab ist tm = annotate (AnnTerm [] tm)
(prettyIst ist (delab ist tm))
-- | Pretty-print the type of some name
pprintDelabTy :: IState -> Name -> Doc OutputAnnotation
pprintDelabTy i n
= case lookupTy n (tt_ctxt i) of
(ty:_) -> annotate (AnnTerm [] ty) . prettyIst i $
case lookupCtxt n (idris_implicits i) of
(imps:_) -> delabTy' i imps ty False False
_ -> delabTy' i [] ty False False
[] -> error "pprintDelabTy got a name that doesn't exist"
pprintTerm :: IState -> PTerm -> Doc OutputAnnotation
pprintTerm ist = pprintTerm' ist []
pprintTerm' :: IState -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
pprintTerm' ist bnd tm = pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) tm
pprintProv :: IState -> [(Name, Term)] -> Provenance -> Doc OutputAnnotation
pprintProv i e ExpectedType = text "Expected type"
pprintProv i e InferredVal = text "Inferred value"
pprintProv i e GivenVal = text "Given value"
pprintProv i e (SourceTerm tm)
= text "Type of " <>
annotate (AnnTerm (zip (map fst e) (repeat False)) tm)
(pprintTerm' i (zip (map fst e) (repeat False)) (delab i tm))
pprintProv i e (TooManyArgs tm)
= text "Is " <>
annotate (AnnTerm (zip (map fst e) (repeat False)) tm)
(pprintTerm' i (zip (map fst e) (repeat False)) (delab i tm))
<> text " applied to too many arguments?"
pprintErr :: IState -> Err -> Doc OutputAnnotation
pprintErr i err = pprintErr' i (fmap (errReverse i) err)
pprintErr' i (Msg s) = text s
pprintErr' i (InternalMsg s) =
vsep [ text "INTERNAL ERROR:" <+> text s,
text "This is probably a bug, or a missing error message.",
text ("Please consider reporting at " ++ bugaddr)
]
pprintErr' i (CantUnify _ (x_in, xprov) (y_in, yprov) e sc s) =
let (x_ns, y_ns, nms) = renameMNs x_in y_in
(x, y) = addImplicitDiffs (delab i x_ns) (delab i y_ns) in
text "Can't unify" <> indented (annTm x_ns
(pprintTerm' i (map (\ (n, b) -> (n, False)) sc
++ zip nms (repeat False)) x))
<> case xprov of
Nothing -> empty
Just t -> text " (" <> pprintProv i sc t <> text ")"
<$>
text "with" <> indented (annTm y_ns
(pprintTerm' i (map (\ (n, b) -> (n, False)) sc
++ zip nms (repeat False)) y))
<> case yprov of
Nothing -> empty
Just t -> text " (" <> pprintProv i sc t <> text ")"
<>
case e of
Msg "" -> empty
-- if the specific error is the same as the one we just printed,
-- there's no need to print it
CantUnify _ (x_in', _) (y_in',_) _ _ _ | x_in == x_in' && y_in == y_in' -> empty
_ -> line <> line <> text "Specifically:" <>
indented (pprintErr' i e) <>
if (opt_errContext (idris_options i)) then showSc i sc else empty
pprintErr' i (CantConvert x_in y_in env) =
let (x_ns, y_ns, nms) = renameMNs x_in y_in
(x, y) = addImplicitDiffs (delab i (flagUnique x_ns))
(delab i (flagUnique y_ns)) in
text "Can't convert" <>
indented (annTm x_ns (pprintTerm' i (map (\ (n, b) -> (n, False)) env)
x)) <$>
text "with" <>
indented (annTm y_ns (pprintTerm' i (map (\ (n, b) -> (n, False)) env)
y)) <>
if (opt_errContext (idris_options i)) then line <> showSc i env else empty
where flagUnique (Bind n (Pi i t k@(UType u)) sc)
= App Complete (P Ref (sUN (show u)) Erased)
(Bind n (Pi i (flagUnique t) k) (flagUnique sc))
flagUnique (App s f a) = App s (flagUnique f) (flagUnique a)
flagUnique (Bind n b sc) = Bind n (fmap flagUnique b) (flagUnique sc)
flagUnique t = t
pprintErr' i (CantSolveGoal x env) =
text "Can't solve goal " <>
indented (annTm x (pprintTerm' i (map (\ (n, b) -> (n, False)) env) (delab i x))) <>
if (opt_errContext (idris_options i)) then line <> showSc i env else empty
pprintErr' i (UnifyScope n out tm env) =
text "Can't unify" <> indented (annName n) <+>
text "with" <> indented (annTm tm (pprintTerm' i (map (\ (n, b) -> (n, False)) env) (delab i tm))) <+>
text "as" <> indented (annName out) <> text "is not in scope" <>
if (opt_errContext (idris_options i)) then line <> showSc i env else empty
pprintErr' i (CantInferType t) = text "Can't infer type for" <+> text t
pprintErr' i (NonFunctionType f ty) =
annTm f (pprintTerm i (delab i f)) <+>
text "does not have a function type" <+>
parens (pprintTerm i (delab i ty))
pprintErr' i (NotEquality tm ty) =
annTm tm (pprintTerm i (delab i tm)) <+>
text "does not have an equality type" <+>
annTm ty (parens (pprintTerm i (delab i ty)))
pprintErr' i (TooManyArguments f) = text "Too many arguments for" <+> annName f
pprintErr' i (CantIntroduce ty) =
text "Can't use lambda here: type is" <+> annTm ty (pprintTerm i (delab i ty))
pprintErr' i (InfiniteUnify x tm env) =
text "Unifying" <+> annName' x (showbasic x) <+> text "and" <+>
annTm tm (pprintTerm' i (map (\ (n, b) -> (n, False)) env) (delab i tm)) <+>
text "would lead to infinite value" <>
if (opt_errContext (idris_options i)) then line <> showSc i env else empty
pprintErr' i (NotInjective p x y) =
text "Can't verify injectivity of" <+> annTm p (pprintTerm i (delab i p)) <+>
text " when unifying" <+> annTm x (pprintTerm i (delab i x)) <+> text "and" <+>
annTm y (pprintTerm i (delab i y))
pprintErr' i (CantResolve _ c) = text "Can't resolve type class" <+> pprintTerm i (delab i c)
pprintErr' i (InvalidTCArg n t)
= annTm t (pprintTerm i (delab i t)) <+> text " cannot be a parameter of "
<> annName n <$>
text "(Type class arguments must be injective)"
pprintErr' i (CantResolveAlts as) = text "Can't disambiguate name:" <+>
align (cat (punctuate (comma <> space) (map (fmap (fancifyAnnots i True) . annName) as)))
pprintErr' i (NoTypeDecl n) = text "No type declaration for" <+> annName n
pprintErr' i (NoSuchVariable n) = text "No such variable" <+> annName n
pprintErr' i (WithFnType ty) =
text "Can't match on a function: type is" <+> annTm ty (pprintTerm i (delab i ty))
pprintErr' i (CantMatch t) =
text "Can't match on" <+> annTm t (pprintTerm i (delab i t))
pprintErr' i (IncompleteTerm t) = text "Incomplete term" <+> annTm t (pprintTerm i (delab i t))
pprintErr' i (NoEliminator s t)
= text "No " <> text s <> text " for type " <+>
annTm t (pprintTerm i (delab i t)) <$>
text "Please note that 'induction' is experimental." <$>
text "Only types declared with '%elim' can be used." <$>
text "Consider writing a pattern matching definition instead."
pprintErr' i (UniverseError fc uexp old new suspects) =
text "Universe inconsistency." <>
(indented . vsep) [ text "Working on:" <+> text (show uexp)
, text "Old domain:" <+> text (show old)
, text "New domain:" <+> text (show new)
, text "Involved constraints:" <+>
(indented . vsep) (map (text . show) suspects)
]
pprintErr' i (UniqueError NullType n)
= text "Borrowed name" <+> annName' n (showbasic n)
<+> text "must not be used on RHS"
pprintErr' i (UniqueError _ n) = text "Unique name" <+> annName' n (showbasic n)
<+> text "is used more than once"
pprintErr' i (UniqueKindError k n) = text "Constructor" <+> annName' n (showbasic n)
<+> text ("has a " ++ show k ++ ",")
<+> text "but the data type does not"
pprintErr' i ProgramLineComment = text "Program line next to comment"
pprintErr' i (Inaccessible n) = annName n <+> text "is not an accessible pattern variable"
pprintErr' i (UnknownImplicit n f) = annName n <+> text "is not an implicit argument of" <+> annName f
pprintErr' i (NonCollapsiblePostulate n) = text "The return type of postulate" <+>
annName n <+> text "is not collapsible"
pprintErr' i (AlreadyDefined n) = annName n<+>
text "is already defined"
pprintErr' i (ProofSearchFail e) = pprintErr' i e
pprintErr' i (NoRewriting tm) = text "rewrite did not change type" <+> annTm tm (pprintTerm i (delab i tm))
pprintErr' i (At f e) = annotate (AnnFC f) (text (show f)) <> colon <> pprintErr' i e
pprintErr' i (Elaborating s n e) = text "When elaborating" <+> text s <>
annName' n (showqual i n) <> colon <$>
pprintErr' i e
pprintErr' i (ElaboratingArg f x _ e)
| isInternal f = pprintErr' i e
| isUN x =
text "When elaborating argument" <+>
annotate (AnnBoundName x False) (text (showbasic x)) <+> -- TODO check plicity
-- Issue #1591 on the issue tracker: https://github.com/idris-lang/Idris-dev/issues/1591
text "to" <+> whatIsName <> annName f <> colon <>
indented (pprintErr' i e)
| otherwise =
text "When elaborating an application of" <+> whatIsName <>
annName f <> colon <> indented (pprintErr' i e)
where whatIsName = let ctxt = tt_ctxt i
in if isTConName f ctxt
then text "type constructor" <> space
else if isDConName f ctxt
then text "constructor" <> space
else if isFnName f ctxt
then text "function" <> space
else empty
isInternal (MN _ _) = True
isInternal (UN n) = T.isPrefixOf (T.pack "__") n
isInternal (NS n _) = isInternal n
isInternal _ = True
pprintErr' i (ProviderError msg) = text ("Type provider error: " ++ msg)
pprintErr' i (LoadingFailed fn e) = text "Loading" <+> text fn <+> text "failed:" <+> pprintErr' i e
pprintErr' i (ReflectionError parts orig) =
let parts' = map (fillSep . map showPart) parts in
align (fillSep parts') <>
if (opt_origerr (idris_options i))
then line <> line <> text "Original error:" <$> indented (pprintErr' i orig)
else empty
where showPart :: ErrorReportPart -> Doc OutputAnnotation
showPart (TextPart str) = fillSep . map text . words $ str
showPart (NamePart n) = annName n
showPart (TermPart tm) = pprintTerm i (delab i tm)
showPart (SubReport rs) = indented . hsep . map showPart $ rs
pprintErr' i (ReflectionFailed msg err) =
text "When attempting to perform error reflection, the following internal error occurred:" <>
indented (pprintErr' i err) <>
text ("This is probably a bug. Please consider reporting it at " ++ bugaddr)
pprintErr' i (ElabScriptDebug msg tm holes) =
text "Elaboration halted." <>
maybe empty (indented . text) msg <>
line <> line <>
text "Holes:" <>
indented (vsep (map ppHole holes)) <> line <> line <>
text "Term: " <> indented (pprintTT [] tm)
where ppHole :: (Name, Type, Env) -> Doc OutputAnnotation
ppHole (hn, goal, env) =
ppAssumptions [] (reverse env) <>
text "----------------------------------" <> line <>
bindingOf hn False <+> text ":" <+>
pprintTT (map fst (reverse env)) goal <> line
ppAssumptions :: [Name] -> Env -> Doc OutputAnnotation
ppAssumptions ns [] = empty
ppAssumptions ns ((n, b) : rest) =
bindingOf n False <+>
text ":" <+>
pprintTT ns (binderTy b) <>
line <>
ppAssumptions (n:ns) rest
pprintErr' i (ElabScriptStuck tm) =
text "Can't run" <+> pprintTT [] tm <+> text "as an elaborator script." <$>
text "Is it a stuck term?"
-- | Make sure the machine invented names are shown helpfully to the user, so
-- that any names which differ internally also differ visibly
renameMNs :: Term -> Term -> (Term, Term, [Name])
renameMNs x y = let ns = nub $ allTTNames x ++ allTTNames y
newnames = evalState (getRenames [] ns) 1 in
(rename newnames x, rename newnames y, map snd newnames)
where
getRenames :: [(Name, Name)] -> [Name] -> State Int [(Name, Name)]
getRenames acc [] = return acc
getRenames acc (n@(MN i x) : xs) | rpt x xs
= do idx <- get
put (idx + 1)
let x' = sUN (str x ++ show idx)
getRenames ((n, x') : acc) xs
getRenames acc (n@(UN x) : xs) | rpt x xs
= do idx <- get
put (idx + 1)
let x' = sUN (str x ++ show idx)
getRenames ((n, x') : acc) xs
getRenames acc (x : xs) = getRenames acc xs
rpt x [] = False
rpt x (UN y : xs) | x == y = True
rpt x (MN i y : xs) | x == y = True
rpt x (_ : xs) = rpt x xs
rename :: [(Name, Name)] -> Term -> Term
rename ns (P nt x t) | Just x' <- lookup x ns = P nt x' t
rename ns (App s f a) = App s (rename ns f) (rename ns a)
rename ns (Bind x b sc)
= let b' = fmap (rename ns) b
sc' = rename ns sc in
case lookup x ns of
Just x' -> Bind x' b' sc'
Nothing -> Bind x b' sc'
rename ns x = x
-- If the two terms only differ in their implicits, mark the implicits which
-- differ as AlwaysShow so that they appear in errors
addImplicitDiffs :: PTerm -> PTerm -> (PTerm, PTerm)
addImplicitDiffs x y
= if (x `expLike` y) then addI x y else (x, y)
where
addI :: PTerm -> PTerm -> (PTerm, PTerm)
addI (PApp fc f as) (PApp gc g bs)
= let (as', bs') = addShows as bs in
(PApp fc f as', PApp gc g bs')
where addShows [] [] = ([], [])
addShows (a:as) (b:bs)
= let (as', bs') = addShows as bs
(a', b') = addI (getTm a) (getTm b) in
if (not (a' `expLike` b'))
then (a { argopts = AlwaysShow : argopts a,
getTm = a' } : as',
b { argopts = AlwaysShow : argopts b,
getTm = b' } : bs')
else (a { getTm = a' } : as',
b { getTm = b' } : bs')
addShows xs ys = (xs, ys)
addI (PLam fc n nfc a b) (PLam fc' n' nfc' c d)
= let (a', c') = addI a c
(b', d') = addI b d in
(PLam fc n nfc a' b', PLam fc' n' nfc' c' d')
addI (PPi p n fc a b) (PPi p' n' fc' c d)
= let (a', c') = addI a c
(b', d') = addI b d in
(PPi p n fc a' b', PPi p' n' fc' c' d')
addI (PPair fc pi a b) (PPair fc' pi' c d)
= let (a', c') = addI a c
(b', d') = addI b d in
(PPair fc pi a' b', PPair fc' pi' c' d')
addI (PDPair fc pi a t b) (PDPair fc' pi' c u d)
= let (a', c') = addI a c
(t', u') = addI t u
(b', d') = addI b d in
(PDPair fc pi a' t' b', PDPair fc' pi' c' u' d')
addI x y = (x, y)
-- Just the ones which appear desugared in errors
expLike (PRef _ n) (PRef _ n') = n == n'
expLike (PApp _ f as) (PApp _ f' as')
= expLike f f' && length as == length as' &&
and (zipWith expLike (getExps as) (getExps as'))
expLike (PPi _ n fc s t) (PPi _ n' fc' s' t')
= n == n' && expLike s s' && expLike t t'
expLike (PLam _ n _ s t) (PLam _ n' _ s' t')
= n == n' && expLike s s' && expLike t t'
expLike (PPair _ _ x y) (PPair _ _ x' y') = expLike x x' && expLike y y'
expLike (PDPair _ _ x _ y) (PDPair _ _ x' _ y') = expLike x x' && expLike y y'
expLike x y = x == y
-- Issue #1589 on the issue tracker
-- https://github.com/idris-lang/Idris-dev/issues/1589
--
-- Figure out why MNs are getting rewritte to UNs for top-level
-- pattern-matching functions
isUN :: Name -> Bool
isUN (UN n) = not $ T.isPrefixOf (T.pack "__") n -- TODO
isUN (NS n _) = isUN n
isUN _ = False
annName :: Name -> Doc OutputAnnotation
annName n = annName' n (showbasic n)
annName' :: Name -> String -> Doc OutputAnnotation
annName' n str = annotate (AnnName n Nothing Nothing Nothing) (text str)
annTm :: Term -> Doc OutputAnnotation -> Doc OutputAnnotation
annTm tm = annotate (AnnTerm [] tm)
-- | Add extra metadata to an output annotation, optionally marking metavariables.
fancifyAnnots :: IState -> Bool -> OutputAnnotation -> OutputAnnotation
fancifyAnnots ist meta annot@(AnnName n _ _ _) =
do let ctxt = tt_ctxt ist
docs = docOverview ist n
ty = Just (getTy ist n)
case () of
_ | isDConName n ctxt -> AnnName n (Just DataOutput) docs ty
_ | isFnName n ctxt -> AnnName n (Just FunOutput) docs ty
_ | isTConName n ctxt -> AnnName n (Just TypeOutput) docs ty
_ | isMetavarName n ist -> if meta
then AnnName n (Just MetavarOutput) docs ty
else AnnName n (Just FunOutput) docs ty
_ | isPostulateName n ist -> AnnName n (Just PostulateOutput) docs ty
_ | otherwise -> annot
where docOverview :: IState -> Name -> Maybe String -- pretty-print first paragraph of docs
docOverview ist n = do docs <- lookupCtxtExact n (idris_docstrings ist)
let o = overview (fst docs)
norm = normaliseAll (tt_ctxt ist) []
-- TODO make width configurable
-- Issue #1588 on the Issue Tracker
-- https://github.com/idris-lang/Idris-dev/issues/1588
out = displayS . renderPretty 1.0 50 $
renderDocstring (renderDocTerm (pprintDelab ist)
norm) o
return (out "")
getTy :: IState -> Name -> String -- fails if name not already extant!
getTy ist n = let theTy = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist) $
delabTy ist n
in (displayS . renderPretty 1.0 50 $ theTy) ""
fancifyAnnots _ _ annot = annot
showSc :: IState -> [(Name, Term)] -> Doc OutputAnnotation
showSc i [] = empty
showSc i xs = line <> line <> text "In context:" <>
indented (vsep (reverse (showSc' [] xs)))
where showSc' bnd [] = []
showSc' bnd ((n, ty):ctxt) =
let this = bindingOf n False <+> colon <+> pprintTerm' i bnd (delab i ty)
in this : showSc' ((n,False):bnd) ctxt
showqual :: IState -> Name -> String
showqual i n = showName (Just i) [] (ppOptionIst i) { ppopt_impl = False } False (dens n)
where
dens ns@(NS n _) = case lookupCtxt n (idris_implicits i) of
[_] -> n -- just one thing
_ -> ns
dens n = n
showbasic :: Name -> String
showbasic n@(UN _) = show n
showbasic (MN _ s) = str s
showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
showbasic (SN s) = show s
showbasic n = show n
| BartAdv/Idris-dev | src/Idris/Delaborate.hs | bsd-3-clause | 27,468 | 0 | 23 | 9,228 | 11,057 | 5,490 | 5,567 | 508 | 46 |
module Cases.FullTypeInferenceTest where
import Language.Haskell.Exts
import Utils.ErrMsg
import Main
-- this module runs the full algorithm over a
-- specified file.
fulltitest1 = fulltitest test1
fulltitest2 = fulltitest test2
fulltitest3 = fulltitest test3
fulltitest f
= do
r <- parseFileWithExts exts f
parseResult startCompilation parserErrMsg r
test1 = "/home/rodrigo/git/doutorado/mptc/src/Libs/PreludeBuiltIn.hs"
test2 = "/home/rodrigo/git/doutorado/mptc/src/Libs/PreludeBase.hs"
test3 = "/home/rodrigo/git/doutorado/mptc/src/Libs/PreludeList.hs"
| rodrigogribeiro/mptc | test/Cases/FullTypeInferenceTest.hs | bsd-3-clause | 603 | 0 | 8 | 102 | 91 | 49 | 42 | 14 | 1 |
{-|
Module : Devel.Build
Description : Attempts to compile the WAI application.
Copyright : (c) 2015 Njagi Mwaniki
License : MIT
Maintainer : njagi@urbanslug.com
Stability : experimental
Portability : POSIX
compile compiles the app to give:
Either a list of source errors or an ide-backend session.
-}
module Devel.Types where
type SourceError' = String
type GhcExtension = String
data FileChange =
Addition FilePath
| Modification FilePath
| Removal FilePath
| NoChange
deriving (Show, Eq)
type PATH = String
type PACKAGEDB = String
type Config = (PATH, PACKAGEDB)
| urbanslug/yesod-devel | src/Devel/Types.hs | gpl-3.0 | 610 | 0 | 6 | 131 | 76 | 48 | 28 | 12 | 0 |
-------------------------------------------------------------------------------
-- Efficient functional queue by means of two lists (used as stacks)
--
-- Data Structures. Grado en Informática. UMA.
-- Pepe Gallardo, 2012
-------------------------------------------------------------------------------
module DataStructures.Queue.TwoListsQueue
( Queue
, empty
, isEmpty
, enqueue
, first
, dequeue
) where
import Data.List(intercalate)
import Test.QuickCheck
data Queue a = Q [a] [a]
empty :: Queue a
empty = Q [] []
mkValid :: [a] -> [a] -> Queue a
mkValid [] ys = Q (reverse ys) []
mkValid xs ys = Q xs ys
isEmpty :: Queue a -> Bool
isEmpty (Q [] _) = True
isEmpty _ = False
enqueue :: a -> Queue a -> Queue a
enqueue x (Q xs ys) = mkValid xs (x:ys)
first :: Queue a -> a
first (Q [] _) = error "first on empty queue"
first (Q (x:xs) ys) = x
dequeue :: Queue a -> Queue a
dequeue (Q [] _) = error "dequeue on empty queue"
dequeue (Q (x:xs) ys) = mkValid xs ys
toList :: Queue a -> [a]
toList (Q xs ys) = xs ++ reverse ys
-- Showing a queue
instance (Show a) => Show (Queue a) where
show q = "TwoListsQueue(" ++ intercalate "," [show x | x <- toList q] ++ ")"
-- Queue equality
instance (Eq a) => Eq (Queue a) where
q == q' = toList q == toList q'
-- This instance is used by QuickCheck to generate random queues
instance (Arbitrary a) => Arbitrary (Queue a) where
arbitrary = do
xs <- listOf arbitrary
return (foldr enqueue empty xs)
| Saeron/haskell | data.structures/haskell/DataStructures/Queue/TwoListsQueue.hs | apache-2.0 | 1,579 | 0 | 12 | 402 | 557 | 287 | 270 | 36 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Data.YamlSpec (main, spec) where
import qualified Text.Libyaml as Y
import qualified Data.ByteString.Char8 as B8
import Test.HUnit hiding (Test, path)
import qualified Data.Conduit as C
import qualified Control.Monad.Trans.Resource as C
import qualified Data.Conduit.List as CL
import Control.Monad
import Control.Exception (try, SomeException)
import Test.Hspec
import Data.Either.Compat
import Test.Mockery.Directory
import qualified Data.Yaml as D
import qualified Data.Yaml.Pretty as Pretty
import Data.Yaml (object, array, (.=))
import Data.Maybe
import qualified Data.HashMap.Strict as M
import qualified Data.Text as T
import Data.Aeson.TH
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
data TestJSON = TestJSON
{ string :: Text
, number :: Int
, anArray :: Vector Text
, hash :: HashMap Text Text
, extrastring :: Text
} deriving (Show, Eq)
deriveJSON defaultOptions ''TestJSON
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "streaming" $ do
it "count scalars with anchor" caseCountScalarsWithAnchor
it "count sequences with anchor" caseCountSequencesWithAnchor
it "count mappings with anchor" caseCountMappingsWithAnchor
it "count aliases" caseCountAliases
it "count scalars" caseCountScalars
it "largest string" caseLargestString
it "encode/decode" caseEncodeDecode
it "encode/decode file" caseEncodeDecodeFile
it "interleaved encode/decode" caseInterleave
it "decode invalid document (without segfault)" caseDecodeInvalidDocument
describe "Data.Yaml" $ do
it "encode/decode" caseEncodeDecodeData
it "encode/decode file" caseEncodeDecodeFileData
it "encode/decode strings" caseEncodeDecodeStrings
it "decode invalid file" caseDecodeInvalid
it "processes datatypes" caseDataTypes
describe "Data.Yaml.Pretty" $ do
it "encode/decode" caseEncodeDecodeDataPretty
it "encode/decode strings" caseEncodeDecodeStringsPretty
it "processes datatypes" caseDataTypesPretty
describe "Data.Yaml aliases" $ do
it "simple scalar alias" caseSimpleScalarAlias
it "simple sequence alias" caseSimpleSequenceAlias
it "simple mapping alias" caseSimpleMappingAlias
it "mapping alias before anchor" caseMappingAliasBeforeAnchor
it "mapping alias inside anchor" caseMappingAliasInsideAnchor
it "scalar alias overriding" caseScalarAliasOverriding
describe "Data.Yaml merge keys" $ do
it "test uniqueness of keys" caseAllKeysShouldBeUnique
it "test mapping merge" caseSimpleMappingMerge
it "test sequence of mappings merging" caseMergeSequence
describe "numbers" $ do
it "parses as string when quoted" caseQuotedNumber
it "parses as number when unquoted" caseUnquotedNumber
it "parses as number !!str is present" caseAttribNumber
it "integers have no decimals" caseIntegerDecimals
describe "booleans" $ do
it "parses when all lowercase" caseLowercaseBool
it "parses when all uppercase" caseUppercaseBool
it "parses when titlecase" caseTitlecaseBool
describe "empty input" $ do
it "doesn't crash" caseEmptyInput
describe "alias stripping" $ do
it "works" caseStripAlias
describe "nulls" $ do
checkNull "null"
checkNull "Null"
checkNull "NULL"
checkNull "~"
checkNull ""
describe "pretty output" $ do
it "simple nulls" $ D.encode (object ["foo" .= D.Null]) `shouldBe` "foo: null\n"
it "simple numbers" $ D.encode (object ["foo" .= (4 :: Int)]) `shouldBe` "foo: 4\n"
it "True" $ D.encode (object ["foo" .= True]) `shouldBe` "foo: true\n"
it "False" $ D.encode (object ["foo" .= False]) `shouldBe` "foo: false\n"
it "simple string" $ D.encode (object ["foo" .= ("bar" :: T.Text)]) `shouldBe` "foo: bar\n"
describe "special keys" $ do
let tester key = it (T.unpack key) $
let value = object [key .= True]
in D.decode (D.encode value) `shouldBe` Just value
mapM_ tester specialStrings
describe "special values" $ do
let tester value = it (T.unpack value) $
let value' = object ["foo" .= value]
in D.decode (D.encode value') `shouldBe` Just value'
mapM_ tester specialStrings
describe "decodeFileEither" $ do
it "loads YAML through JSON into Haskell data" $ do
tj <- either (error . show) id `fmap` D.decodeFileEither "test/json.yaml"
tj `shouldBe` TestJSON
{ string = "str"
, number = 2
, anArray = V.fromList ["a", "b"]
, hash = HM.fromList [("key1", "value1"), ("key2", "value2")]
, extrastring = "1234-foo"
}
context "when file does not exist" $ do
it "returns Left" $ do
(D.decodeFileEither "./does_not_exist.yaml" :: IO (Either D.ParseException D.Value)) >>= (`shouldSatisfy` isLeft)
describe "round-tripping of special scalars" $ do
let special = words "y Y On ON false 12345 12345.0 12345a 12e3"
forM_ special $ \w -> it w $
let v = object ["word" .= w]
in D.decode (D.encode v) `shouldBe` Just v
it "no tags" $ D.encode (object ["word" .= ("true" :: String)]) `shouldBe` "word: 'true'\n"
it "aliases in keys #49" caseIssue49
it "serialization of +123 #64" $ do
D.decode (D.encode ("+123" :: String)) `shouldBe` Just ("+123" :: String)
specialStrings :: [T.Text]
specialStrings =
[ "fo\"o"
, "fo\'o"
, "fo\\'o"
, "fo: o"
, "foo\nbar\nbaz\n"
]
counter :: Monad m => (Y.Event -> Bool) -> C.Sink Y.Event m Int
counter pred' =
CL.fold (\cnt e -> (if pred' e then 1 else 0) + cnt) 0
caseHelper :: String
-> (Y.Event -> Bool)
-> Int
-> Assertion
caseHelper yamlString pred' expRes = do
res <- C.runResourceT $ Y.decode (B8.pack yamlString) C.$$ counter pred'
res @?= expRes
caseCountScalarsWithAnchor :: Assertion
caseCountScalarsWithAnchor =
caseHelper yamlString isScalarA 1
where
yamlString = "foo:\n - &anchor bin1\n - bin2\n - bin3"
isScalarA (Y.EventScalar _ _ _ (Just _)) = True
isScalarA _ = False
caseCountSequencesWithAnchor :: Assertion
caseCountSequencesWithAnchor =
caseHelper yamlString isSequenceStartA 1
where
yamlString = "foo: &anchor\n - bin1\n - bin2\n - bin3"
isSequenceStartA (Y.EventSequenceStart (Just _)) = True
isSequenceStartA _ = False
caseCountMappingsWithAnchor :: Assertion
caseCountMappingsWithAnchor =
caseHelper yamlString isMappingA 1
where
yamlString = "foo: &anchor\n key1: bin1\n key2: bin2\n key3: bin3"
isMappingA (Y.EventMappingStart (Just _)) = True
isMappingA _ = False
caseCountAliases :: Assertion
caseCountAliases =
caseHelper yamlString isAlias 1
where
yamlString = "foo: &anchor\n key1: bin1\n key2: bin2\n key3: bin3\nboo: *anchor"
isAlias Y.EventAlias{} = True
isAlias _ = False
caseCountScalars :: Assertion
caseCountScalars = do
res <- C.runResourceT $ Y.decode yamlBS C.$$ CL.fold adder accum
res @?= (7, 1, 2)
where
yamlString = "foo:\n baz: [bin1, bin2, bin3]\nbaz: bazval"
yamlBS = B8.pack yamlString
adder (s, l, m) (Y.EventScalar{}) = (s + 1, l, m)
adder (s, l, m) (Y.EventSequenceStart{}) = (s, l + 1, m)
adder (s, l, m) (Y.EventMappingStart{}) = (s, l, m + 1)
adder a _ = a
accum = (0, 0, 0) :: (Int, Int, Int)
caseLargestString :: Assertion
caseLargestString = do
res <- C.runResourceT $ Y.decodeFile filePath C.$$ CL.fold adder accum
res @?= (length expected, expected)
where
expected = "this one is just a little bit bigger than the others"
filePath = "test/largest-string.yaml"
adder (i, s) (Y.EventScalar bs _ _ _) =
let s' = B8.unpack bs
i' = length s'
in if i' > i then (i', s') else (i, s)
adder acc _ = acc
accum = (0, "no strings found")
newtype MyEvent = MyEvent Y.Event deriving Show
instance Eq MyEvent where
(MyEvent (Y.EventScalar s t _ _)) == (MyEvent (Y.EventScalar s' t' _ _)) =
s == s' && t == t'
MyEvent e1 == MyEvent e2 = e1 == e2
caseEncodeDecode :: Assertion
caseEncodeDecode = do
eList <- C.runResourceT $ Y.decode yamlBS C.$$ CL.consume
bs <- C.runResourceT $ CL.sourceList eList C.$$ Y.encode
eList2 <- C.runResourceT $ Y.decode bs C.$$ CL.consume
map MyEvent eList @=? map MyEvent eList2
where
yamlString = "foo: bar\nbaz:\n - bin1\n - bin2\n"
yamlBS = B8.pack yamlString
caseEncodeDecodeFile :: Assertion
caseEncodeDecodeFile = withFile "" $ \tmpPath -> do
eList <- C.runResourceT $ Y.decodeFile filePath C.$$ CL.consume
C.runResourceT $ CL.sourceList eList C.$$ Y.encodeFile tmpPath
eList2 <- C.runResourceT $ Y.decodeFile filePath C.$$ CL.consume
map MyEvent eList @=? map MyEvent eList2
where
filePath = "test/largest-string.yaml"
caseInterleave :: Assertion
caseInterleave = withFile "" $ \tmpPath -> withFile "" $ \tmpPath2 -> do
() <- C.runResourceT $ Y.decodeFile filePath C.$$ Y.encodeFile tmpPath
() <- C.runResourceT $ Y.decodeFile tmpPath C.$$ Y.encodeFile tmpPath2
f1 <- readFile tmpPath
f2 <- readFile tmpPath2
f1 @=? f2
where
filePath = "test/largest-string.yaml"
caseDecodeInvalidDocument :: Assertion
caseDecodeInvalidDocument = do
x <- try $ C.runResourceT $ Y.decode yamlBS C.$$ CL.sinkNull
case x of
Left (_ :: SomeException) -> return ()
Right y -> do
putStrLn $ "bad return value: " ++ show y
assertFailure "expected parsing exception, but got no errors"
where
yamlString = " - foo\n - baz\nbuz"
yamlBS = B8.pack yamlString
mkScalar :: String -> D.Value
mkScalar = mkStrScalar
mkStrScalar :: String -> D.Value
mkStrScalar = D.String . T.pack
mappingKey :: D.Value-> String -> D.Value
mappingKey (D.Object m) k = (fromJust . M.lookup (T.pack k) $ m)
mappingKey _ _ = error "expected Object"
decodeYaml :: String -> Maybe D.Value
decodeYaml s = D.decode $ B8.pack s
sample :: D.Value
sample = array
[ D.String "foo"
, object
[ ("bar1", D.String "bar2")
, ("bar3", D.String "")
]
, D.String ""
]
caseEncodeDecodeData :: Assertion
caseEncodeDecodeData = do
let out = D.decode $ D.encode sample
out @?= Just sample
caseEncodeDecodeDataPretty :: Assertion
caseEncodeDecodeDataPretty = do
let out = D.decode $ Pretty.encodePretty Pretty.defConfig sample
out @?= Just sample
caseEncodeDecodeFileData :: Assertion
caseEncodeDecodeFileData = withFile "" $ \fp -> do
D.encodeFile fp sample
out <- D.decodeFile fp
out @?= Just sample
caseEncodeDecodeStrings :: Assertion
caseEncodeDecodeStrings = do
let out = D.decode $ D.encode sample
out @?= Just sample
caseEncodeDecodeStringsPretty :: Assertion
caseEncodeDecodeStringsPretty = do
let out = D.decode $ Pretty.encodePretty Pretty.defConfig sample
out @?= Just sample
caseDecodeInvalid :: Assertion
caseDecodeInvalid = do
let invalid = B8.pack "\tthis is 'not' valid :-)"
Nothing @=? (D.decode invalid :: Maybe D.Value)
caseSimpleScalarAlias :: Assertion
caseSimpleScalarAlias = do
let maybeRes = decodeYaml "- &anch foo\n- baz\n- *anch"
isJust maybeRes @? "decoder should return Just YamlObject but returned Nothing"
let res = fromJust maybeRes
res @?= array [(mkScalar "foo"), (mkScalar "baz"), (mkScalar "foo")]
caseSimpleSequenceAlias :: Assertion
caseSimpleSequenceAlias = do
let maybeRes = decodeYaml "seq: &anch\n - foo\n - baz\nseq2: *anch"
isJust maybeRes @? "decoder should return Just YamlObject but returned Nothing"
let res = fromJust maybeRes
res @?= object [("seq", array [(mkScalar "foo"), (mkScalar "baz")]), ("seq2", array [(mkScalar "foo"), (mkScalar "baz")])]
caseSimpleMappingAlias :: Assertion
caseSimpleMappingAlias = do
let maybeRes = decodeYaml "map: &anch\n key1: foo\n key2: baz\nmap2: *anch"
isJust maybeRes @? "decoder should return Just YamlObject but returned Nothing"
let res = fromJust maybeRes
res @?= object [(T.pack "map", object [("key1", mkScalar "foo"), ("key2", (mkScalar "baz"))]), (T.pack "map2", object [("key1", (mkScalar "foo")), ("key2", mkScalar "baz")])]
caseMappingAliasBeforeAnchor :: Assertion
caseMappingAliasBeforeAnchor = do
let res = decodeYaml "map: *anch\nmap2: &anch\n key1: foo\n key2: baz"
isNothing res @? "decode should return Nothing due to unknown alias"
caseMappingAliasInsideAnchor :: Assertion
caseMappingAliasInsideAnchor = do
let res = decodeYaml "map: &anch\n key1: foo\n key2: *anch"
isNothing res @? "decode should return Nothing due to unknown alias"
caseScalarAliasOverriding :: Assertion
caseScalarAliasOverriding = do
let maybeRes = decodeYaml "- &anch foo\n- baz\n- *anch\n- &anch boo\n- buz\n- *anch"
isJust maybeRes @? "decoder should return Just YamlObject but returned Nothing"
let res = fromJust maybeRes
res @?= array [(mkScalar "foo"), (mkScalar "baz"), (mkScalar "foo"), (mkScalar "boo"), (mkScalar "buz"), (mkScalar "boo")]
caseAllKeysShouldBeUnique :: Assertion
caseAllKeysShouldBeUnique = do
let maybeRes = decodeYaml "foo1: foo\nfoo2: baz\nfoo1: buz"
isJust maybeRes @? "decoder should return Just YamlObject but returned Nothing"
let res = fromJust maybeRes
mappingKey res "foo1" @?= (mkScalar "buz")
caseSimpleMappingMerge :: Assertion
caseSimpleMappingMerge = do
let maybeRes = decodeYaml "foo1: foo\nfoo2: baz\n<<:\n foo1: buz\n foo3: fuz"
isJust maybeRes @? "decoder should return Just YamlObject but returned Nothing"
let res = fromJust maybeRes
mappingKey res "foo1" @?= (mkScalar "foo")
mappingKey res "foo3" @?= (mkScalar "fuz")
caseMergeSequence :: Assertion
caseMergeSequence = do
let maybeRes = decodeYaml "m1: &m1\n k1: !!str 1\n k2: !!str 2\nm2: &m2\n k1: !!str 3\n k3: !!str 4\nfoo1: foo\n<<: [ *m1, *m2 ]"
isJust maybeRes @? "decoder should return Just YamlObject but returned Nothing"
let res = fromJust maybeRes
mappingKey res "foo1" @?= (mkScalar "foo")
mappingKey res "k1" @?= (D.String "1")
mappingKey res "k2" @?= (D.String "2")
mappingKey res "k3" @?= (D.String "4")
caseDataTypes :: Assertion
caseDataTypes =
D.decode (D.encode val) @?= Just val
where
val = object
[ ("string", D.String "foo")
, ("int", D.Number 5)
, ("float", D.Number 4.3)
, ("true", D.Bool True)
, ("false", D.Bool False)
, ("null", D.Null)
]
caseDataTypesPretty :: Assertion
caseDataTypesPretty =
D.decode (Pretty.encodePretty Pretty.defConfig val) @?= Just val
where
val = object
[ ("string", D.String "foo")
, ("int", D.Number 5)
, ("float", D.Number 4.3)
, ("true", D.Bool True)
, ("false", D.Bool False)
, ("null", D.Null)
]
caseQuotedNumber, caseUnquotedNumber, caseAttribNumber, caseIntegerDecimals :: Assertion
caseQuotedNumber = D.decode "foo: \"1234\"" @?= Just (object [("foo", D.String "1234")])
caseUnquotedNumber = D.decode "foo: 1234" @?= Just (object [("foo", D.Number 1234)])
caseAttribNumber = D.decode "foo: !!str 1234" @?= Just (object [("foo", D.String "1234")])
caseIntegerDecimals = D.encode (1 :: Int) @?= "1\n...\n"
obj :: Maybe D.Value
obj = Just (object [("foo", D.Bool False), ("bar", D.Bool True), ("baz", D.Bool True)])
caseLowercaseBool, caseUppercaseBool, caseTitlecaseBool :: Assertion
caseLowercaseBool = D.decode "foo: off\nbar: y\nbaz: true" @?= obj
caseUppercaseBool = D.decode "foo: FALSE\nbar: Y\nbaz: ON" @?= obj
caseTitlecaseBool = D.decode "foo: No\nbar: Yes\nbaz: True" @?= obj
caseEmptyInput :: Assertion
caseEmptyInput = D.decode B8.empty @?= (Nothing :: Maybe D.Value)
checkNull :: T.Text -> Spec
checkNull x =
it ("null recognized: " ++ show x) assertion
where
assertion = Just (object [("foo", D.Null)]) @=? D.decode (B8.pack $ "foo: " ++ T.unpack x)
caseStripAlias :: Assertion
caseStripAlias =
D.decode src @?= Just (object
[ "Default" .= object
[ "foo" .= (1 :: Int)
, "bar" .= (2 :: Int)
]
, "Obj" .= object
[ "foo" .= (1 :: Int)
, "bar" .= (2 :: Int)
, "key" .= (3 :: Int)
]
])
where
src = "Default: &def\n foo: 1\n bar: 2\nObj:\n <<: *def\n key: 3\n"
caseIssue49 :: Assertion
caseIssue49 =
D.decodeEither src @?= Right (object
[ "a" .= object [ "value" .= (1.0 :: Double) ]
, "b" .= object [ "value" .= (1.2 :: Double) ]
])
where
src = "---\na:\n &id5 value: 1.0\nb:\n *id5: 1.2"
| bitonic/yaml | test/Data/YamlSpec.hs | bsd-2-clause | 17,426 | 400 | 21 | 4,184 | 4,619 | 2,495 | 2,124 | 380 | 4 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.Luxi (testLuxi) where
import Test.HUnit
import Test.QuickCheck
import Test.QuickCheck.Monadic (monadicIO, run, stop)
import Data.List
import Control.Concurrent (forkIO)
import Control.Exception (bracket)
import qualified Text.JSON as J
import Test.Ganeti.OpCodes ()
import Test.Ganeti.Query.Language (genFilter)
import Test.Ganeti.TestCommon
import Test.Ganeti.TestHelper
import Test.Ganeti.Types (genReasonTrail)
import Ganeti.BasicTypes
import qualified Ganeti.Luxi as Luxi
import qualified Ganeti.UDSServer as US
{-# ANN module "HLint: ignore Use camelCase" #-}
-- * Luxi tests
$(genArbitrary ''Luxi.LuxiReq)
instance Arbitrary Luxi.LuxiOp where
arbitrary = do
lreq <- arbitrary
case lreq of
Luxi.ReqQuery -> Luxi.Query <$> arbitrary <*> genFields <*> genFilter
Luxi.ReqQueryFields -> Luxi.QueryFields <$> arbitrary <*> genFields
Luxi.ReqQueryNodes -> Luxi.QueryNodes <$> listOf genFQDN <*>
genFields <*> arbitrary
Luxi.ReqQueryGroups -> Luxi.QueryGroups <$> arbitrary <*>
arbitrary <*> arbitrary
Luxi.ReqQueryNetworks -> Luxi.QueryNetworks <$> arbitrary <*>
arbitrary <*> arbitrary
Luxi.ReqQueryInstances -> Luxi.QueryInstances <$> listOf genFQDN <*>
genFields <*> arbitrary
Luxi.ReqQueryFilters -> Luxi.QueryFilters <$> arbitrary <*> genFields
Luxi.ReqReplaceFilter -> Luxi.ReplaceFilter <$> genMaybe genUUID <*>
arbitrary <*> arbitrary <*> arbitrary <*>
genReasonTrail
Luxi.ReqDeleteFilter -> Luxi.DeleteFilter <$> genUUID
Luxi.ReqQueryJobs -> Luxi.QueryJobs <$> arbitrary <*> genFields
Luxi.ReqQueryExports -> Luxi.QueryExports <$>
listOf genFQDN <*> arbitrary
Luxi.ReqQueryConfigValues -> Luxi.QueryConfigValues <$> genFields
Luxi.ReqQueryClusterInfo -> pure Luxi.QueryClusterInfo
Luxi.ReqQueryTags -> do
kind <- arbitrary
Luxi.QueryTags kind <$> genLuxiTagName kind
Luxi.ReqSubmitJob -> Luxi.SubmitJob <$> resize maxOpCodes arbitrary
Luxi.ReqSubmitJobToDrainedQueue -> Luxi.SubmitJobToDrainedQueue <$>
resize maxOpCodes arbitrary
Luxi.ReqSubmitManyJobs -> Luxi.SubmitManyJobs <$>
resize maxOpCodes arbitrary
Luxi.ReqWaitForJobChange -> Luxi.WaitForJobChange <$> arbitrary <*>
genFields <*> pure J.JSNull <*>
pure J.JSNull <*> arbitrary
Luxi.ReqPickupJob -> Luxi.PickupJob <$> arbitrary
Luxi.ReqArchiveJob -> Luxi.ArchiveJob <$> arbitrary
Luxi.ReqAutoArchiveJobs -> Luxi.AutoArchiveJobs <$> arbitrary <*>
arbitrary
Luxi.ReqCancelJob -> Luxi.CancelJob <$> arbitrary <*> arbitrary
Luxi.ReqChangeJobPriority -> Luxi.ChangeJobPriority <$> arbitrary <*>
arbitrary
Luxi.ReqSetDrainFlag -> Luxi.SetDrainFlag <$> arbitrary
Luxi.ReqSetWatcherPause -> Luxi.SetWatcherPause <$> arbitrary
-- | Simple check that encoding/decoding of LuxiOp works.
prop_CallEncoding :: Luxi.LuxiOp -> Property
prop_CallEncoding op =
(US.parseCall (US.buildCall (Luxi.strOfOp op) (Luxi.opToArgs op))
>>= uncurry Luxi.decodeLuxiCall) ==? Ok op
-- | Server ping-pong helper.
luxiServerPong :: Luxi.Client -> IO ()
luxiServerPong c = do
msg <- Luxi.recvMsgExt c
case msg of
Luxi.RecvOk m -> Luxi.sendMsg c m >> luxiServerPong c
_ -> return ()
-- | Client ping-pong helper.
luxiClientPong :: Luxi.Client -> [String] -> IO [String]
luxiClientPong c =
mapM (\m -> Luxi.sendMsg c m >> Luxi.recvMsg c)
-- | Monadic check that, given a server socket, we can connect via a
-- client to it, and that we can send a list of arbitrary messages and
-- get back what we sent.
prop_ClientServer :: [[DNSChar]] -> Property
prop_ClientServer dnschars = monadicIO $ do
let msgs = map (map dnsGetChar) dnschars
fpath <- run $ getTempFileName "luxitest"
-- we need to create the server first, otherwise (if we do it in the
-- forked thread) the client could try to connect to it before it's
-- ready
server <- run $ Luxi.getLuxiServer False fpath
-- fork the server responder
_ <- run . forkIO $
bracket
(Luxi.acceptClient server)
(\c -> Luxi.closeClient c >> Luxi.closeServer server)
luxiServerPong
replies <- run $
bracket
(Luxi.getLuxiClient fpath)
Luxi.closeClient
(`luxiClientPong` msgs)
_ <- stop $ replies ==? msgs
return ()
-- | Check that Python and Haskell define the same Luxi requests list.
case_AllDefined :: Assertion
case_AllDefined = do
py_stdout <- runPython "from ganeti import luxi\n\
\print('\\n'.join(luxi.REQ_ALL))" "" >>=
checkPythonResult
let py_ops = sort $ lines py_stdout
hs_ops = Luxi.allLuxiCalls
extra_py = py_ops \\ hs_ops
extra_hs = hs_ops \\ py_ops
assertBool ("Luxi calls missing from Haskell code:\n" ++
unlines extra_py) (null extra_py)
assertBool ("Extra Luxi calls in the Haskell code:\n" ++
unlines extra_hs) (null extra_hs)
testSuite "Luxi"
[ 'prop_CallEncoding
, 'prop_ClientServer
, 'case_AllDefined
]
| ganeti/ganeti | test/hs/Test/Ganeti/Luxi.hs | bsd-2-clause | 6,874 | 0 | 16 | 1,631 | 1,229 | 630 | 599 | 111 | 2 |
{-# LANGUAGE TupleSections, TemplateHaskell, CPP, UndecidableInstances,
MultiParamTypeClasses, TypeFamilies, GeneralizedNewtypeDeriving,
ImpredicativeTypes #-}
{-| Functions of the metadata daemon exported for RPC
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Metad.ConfigCore where
import Control.Concurrent.MVar.Lifted
import Control.Monad.Base
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Language.Haskell.TH (Name)
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Errors
import qualified Ganeti.JSON as J
import Ganeti.Logging as L
import Ganeti.Metad.Config as Config
import Ganeti.Metad.Types (InstanceParams)
-- * The monad in which all the Metad functions execute
data MetadHandle = MetadHandle
{ mhInstParams :: MVar InstanceParams
}
-- | A type alias for easier referring to the actual content of the monad
-- when implementing its instances.
type MetadMonadIntType = ReaderT MetadHandle IO
-- | The internal part of the monad without error handling.
newtype MetadMonadInt a = MetadMonadInt
{ getMetadMonadInt :: MetadMonadIntType a }
deriving ( Functor, Applicative, Monad, MonadIO, MonadBase IO
, L.MonadLog )
instance MonadBaseControl IO MetadMonadInt where
#if MIN_VERSION_monad_control(1,0,0)
-- Needs Undecidable instances
type StM MetadMonadInt b = StM MetadMonadIntType b
liftBaseWith f = MetadMonadInt $ liftBaseWith
$ \r -> f (r . getMetadMonadInt)
restoreM = MetadMonadInt . restoreM
#else
newtype StM MetadMonadInt b = StMMetadMonadInt
{ runStMMetadMonadInt :: StM MetadMonadIntType b }
liftBaseWith f = MetadMonadInt . liftBaseWith
$ \r -> f (liftM StMMetadMonadInt . r . getMetadMonadInt)
restoreM = MetadMonadInt . restoreM . runStMMetadMonadInt
#endif
-- | Runs the internal part of the MetadMonad monad on a given daemon
-- handle.
runMetadMonadInt :: MetadMonadInt a -> MetadHandle -> IO a
runMetadMonadInt (MetadMonadInt k) = runReaderT k
-- | The complete monad with error handling.
type MetadMonad = ResultT GanetiException MetadMonadInt
-- * Basic functions in the monad
metadHandle :: MetadMonad MetadHandle
metadHandle = lift . MetadMonadInt $ ask
instParams :: MetadMonad InstanceParams
instParams = readMVar . mhInstParams =<< metadHandle
modifyInstParams :: (InstanceParams -> MetadMonad (InstanceParams, a))
-> MetadMonad a
modifyInstParams f = do
h <- metadHandle
modifyMVar (mhInstParams h) f
-- * Functions available to the RPC module
-- Just a debugging function
echo :: String -> MetadMonad String
echo = return
-- | Update the configuration with the received instance parameters.
updateConfig :: J.JSValue -> MetadMonad ()
updateConfig input = do
(name, m'instanceParams) <- J.fromJResultE "Could not get instance parameters"
$ Config.getInstanceParams input
case m'instanceParams of
Nothing -> L.logInfo $ "No communication NIC for instance " ++ name
++ ", skipping"
Just instanceParams -> do
cfg' <- modifyInstParams $ \cfg ->
let cfg' = mergeConfig cfg instanceParams
in return (cfg', cfg')
L.logInfo $
"Updated instance " ++ name ++ " configuration"
L.logDebug $ "Instance configuration: " ++ show cfg'
-- * The list of all functions exported to RPC.
exportedFunctions :: [Name]
exportedFunctions = [ 'echo
, 'updateConfig
]
| mbakke/ganeti | src/Ganeti/Metad/ConfigCore.hs | bsd-2-clause | 4,792 | 1 | 23 | 917 | 613 | 340 | 273 | 61 | 2 |
module Name.Id(
Id(),
IdMap(),
IdNameT(),
IdSet(),
anonymous,
va1,va2,va3,va4,va5,
addBoundNamesIdMap,
addBoundNamesIdSet,
addNamesIdSet,
idMapToIdSet,
anonymousIds,
sillyId,
etherealIds,
isEtherealId,
isInvalidId,
isEmptyId,
idSetToIdMap,
mapMaybeIdMap,
idSetFromList,
idToInt,
idSetFromDistinctAscList,
idMapFromList,
idMapFromDistinctAscList,
idSetToList,
idMapToList,
emptyId,
newIds,
newId,
mixInt,
mixInt3,
toId,
fromId,
candidateIds,
runIdNameT
)where
import Control.Monad.Reader
import Control.Monad.State
import Data.Bits
import Data.Int
import Data.Monoid
import qualified Data.Binary as B
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Doc.DocLike
import Doc.PPrint
import Name.Name
import StringTable.Atom
import Util.HasSize
import Util.Inst()
import Util.NameMonad
import Util.SetLike as S
{-
- An Id is an opaque type with equality and ordering, Its range is split into the following categories
- all the following categories are disjoint.
-
- the unique empty id, called 'emptyId'
-
- for every Atom there is a unique cooresponding Id.
-
- a set of anonymous ids, indexed by positive numbers.
-
- a set of epheremal Ids presented as the list 'epheremalIds'. these are
- generally used as placeholders for unification algorithms.
-
- In general, only atomic and anonymous ids are used as values, and the empty id is used to indicate
- an usused binding site. epheremal and silly ids are used internally in certain algorithms and have no
- meaning outside of said context. They never escape the code that uses them.
-
-}
newtype Id = Id Int
deriving(Eq,Ord)
anonymous :: Int -> Id
anonymous x | x <= 0 = error "invalid anonymous id"
| otherwise = Id (2*x)
-- | some convinience anonymous ids
va1,va2,va3,va4,va5 :: Id
va1 = anonymous 1
va2 = anonymous 2
va3 = anonymous 3
va4 = anonymous 4
va5 = anonymous 5
-- IdSet
instance Intjection Id where
toIntjection i = (Id i)
fromIntjection (Id i) = i
type IdSet = IntjectionSet Id
--type instance GSet Id = IdSet
{-
newtype IdSet = IdSet IS.IntSet
deriving(Typeable,Monoid,HasSize,SetLike,IsEmpty,Eq,Ord)
instance BuildSet Id IdSet where
fromList = idSetFromList
fromDistinctAscList = idSetFromDistinctAscList
insert (Id x) (IdSet b) = IdSet $ IS.insert x b
singleton (Id x) = IdSet $ IS.singleton x
instance ModifySet Id IdSet where
toList = idSetToList
delete (Id x) (IdSet b) = IdSet $ IS.delete x b
member (Id x) (IdSet b) = IS.member x b
sfilter f (IdSet s) = IdSet $ IS.filter (f . Id) s
-}
idSetToList :: IdSet -> [Id]
idSetToList = S.toList
idMapToList :: IdMap a -> [(Id,a)]
idMapToList = S.toList
idToInt :: Id -> Int
idToInt (Id x) = x
mapMaybeIdMap :: (a -> Maybe b) -> IdMap a -> IdMap b
mapMaybeIdMap fn (IntjectionMap m) = IntjectionMap (IM.mapMaybe fn m)
type IdMap = IntjectionMap Id
--type instance GMap Id = IdMap
{-
newtype IdMap a = IdMap (IM.IntMap a)
deriving(Typeable,Monoid,HasSize,SetLike,Functor,Traversable,Foldable,IsEmpty,Eq,Ord)
instance BuildSet (Id,a) (IdMap a) where
fromList = idMapFromList
fromDistinctAscList = idMapFromDistinctAscList
insert (Id x,y) (IdMap b) = IdMap $ IM.insert x y b
singleton (Id x,y) = IdMap $ IM.singleton x y
instance MapLike Id a (IdMap a) where
melems (IdMap m) = IM.elems m
mdelete (Id x) (IdMap m) = IdMap $ IM.delete x m
mmember (Id x) (IdMap m) = IM.member x m
mlookup (Id x) (IdMap m) = IM.lookup x m
massocs (IdMap m) = [ (Id x,y) | (x,y) <- IM.assocs m ]
mkeys (IdMap m) = [ Id x | x <- IM.keys m ]
mmapWithKey f (IdMap m) = IdMap $ IM.mapWithKey (\k v -> f (Id k) v) m
mfilter f (IdMap m) = IdMap $ IM.filter f m
mpartitionWithKey f (IdMap m) = case IM.partitionWithKey (\k v -> f (Id k) v) m of (x,y) -> (IdMap x,IdMap y)
munionWith f (IdMap m1) (IdMap m2) = IdMap $ IM.unionWith f m1 m2
mfilterWithKey f (IdMap m) = IdMap $ IM.filterWithKey (\k v -> f (Id k) v) m
-}
--instance GMapSet Id where
-- toSet (IntjectionMap im) = IntjectionSet $ IM.keysSet im
-- toMap f (IntjectionSet is) = IntjectionMap $ IM.fromDistinctAscList [ (x,f (Id x)) | x <- IS.toAscList is]
--deriving instance MapLike Int a (IM.IntMap a) => MapLike Id a (IdMap a)
idSetToIdMap :: (Id -> a) -> IdSet -> IdMap a
--idSetToIdMap f (IdSet is) = IdMap $ IM.fromDistinctAscList [ (x,f (Id x)) | x <- IS.toAscList is]
idSetToIdMap f (IntjectionSet is) = IntjectionMap $ IM.fromDistinctAscList [ (x,f (Id x)) | x <- IS.toAscList is]
idMapToIdSet :: IdMap a -> IdSet
idMapToIdSet (IntjectionMap im) = IntjectionSet $ IM.keysSet im
--idMapToIdSet (IdMap im) = IdSet $ (IM.keysSet im)
-- | Name monad transformer.
newtype IdNameT m a = IdNameT (StateT (IdSet, IdSet) m a)
deriving(Monad, MonadTrans, Functor, MonadFix, MonadPlus, MonadIO)
instance (MonadReader r m) => MonadReader r (IdNameT m) where
ask = lift ask
local f (IdNameT m) = IdNameT $ local f m
-- | Run the name monad transformer.
runIdNameT :: (Monad m) => IdNameT m a -> m (a,IdSet)
runIdNameT (IdNameT x) = do
(r,(used,bound)) <- runStateT x (mempty,mempty)
return (r,bound)
fromIdNameT (IdNameT x) = x
instance Monad m => NameMonad Id (IdNameT m) where
addNames ns = IdNameT $ do
modify (\ (used,bound) -> (fromList ns `union` used, bound) )
addBoundNames ns = IdNameT $ do
let nset = fromList ns
modify (\ (used,bound) -> (nset `union` used, nset `union` bound) )
uniqueName n = IdNameT $ do
(used,bound) <- get
if n `member` bound then fromIdNameT newName else put (insert n used,insert n bound) >> return n
newNameFrom vs = IdNameT $ do
(used,bound) <- get
let f (x:xs)
| x `member` used = f xs
| otherwise = x
f [] = error "newNameFrom: finite list!"
nn = f vs
put (insert nn used, insert nn bound)
return nn
newName = IdNameT $ do
(used,bound) <- get
fromIdNameT $ newNameFrom (candidateIds (size used `mixInt` size bound))
addNamesIdSet nset = IdNameT $ do
modify (\ (used,bound) -> (nset `union` used, bound) )
addBoundNamesIdSet nset = IdNameT $ do
modify (\ (used,bound) -> (nset `union` used, nset `union` bound) )
addBoundNamesIdMap nmap = IdNameT $ do
modify (\ (used,bound) -> (nset `union` used, nset `union` bound) ) where
nset = idMapToIdSet nmap
idSetFromDistinctAscList :: [Id] -> IdSet
idSetFromDistinctAscList ids = IntjectionSet (IS.fromDistinctAscList [ x | Id x <- ids] )
idSetFromList :: [Id] -> IdSet
idSetFromList ids = fromList ids
idMapFromList :: [(Id,a)] -> IdMap a
idMapFromList ids = fromList ids
idMapFromDistinctAscList :: [(Id,a)] -> IdMap a
idMapFromDistinctAscList ids = IntjectionMap (IM.fromDistinctAscList [ (x,y) | (Id x,y) <- ids ] )
instance Show Id where
showsPrec _ (Id 0) = showChar '_'
showsPrec _ (Id x) = maybe (showString ('x':show (x `div` 2))) shows (fromId $ Id x)
instance Show IdSet where
showsPrec n is = showsPrec n (idSetToList is)
instance Show v => Show (IdMap v) where
showsPrec n is = showsPrec n (idMapToList is)
anonymousIds :: [Id]
anonymousIds = map anonymous [1 .. ]
etherealIds :: [Id]
etherealIds = map Id [-4, -6 .. ]
isEmptyId x = x == emptyId
isEtherealId id = id < emptyId
-- | id isn't anonymous or atom-mapped
isInvalidId id = id <= emptyId
-- | A occasionally useful random ethereal id
sillyId :: Id
sillyId = Id $ -2
emptyId :: Id
emptyId = Id 0
-- | find some temporary ids that are not members of the set,
-- useful for generating a small number of local unique names.
newIds :: IdSet -> [Id]
newIds (IntjectionSet ids) = ans where
ans = if sids == 0 then candidateIds 42 else [ Id i | Id i <- candidates, i `notMember` ids ]
sids = size ids
candidates = candidateIds (mixInt3 sids (IS.findMin ids) (IS.findMax ids))
newId :: Int -- ^ a seed value, useful for speeding up finding a unique id
-> (Id -> Bool) -- ^ whether an Id is acceptable
-> Id -- ^ your new Id
newId seed check = head $ filter check (candidateIds seed)
-- generate a list of candidate anonymous ids based on a seed value
candidateIds :: Int -> [Id]
candidateIds !seed = f (2 + (mask $ hashInt seed)) where
mask x = x .&. 0x0FFFFFFE
f !x = Id x:f (x + 2)
--mask x = trace ("candidate " ++ show seed) $ Id $ x .&. 0x0FFFFFFE
toId :: Name -> Id
toId x = Id $ fromAtom (toAtom x)
instance FromAtom Id where
fromAtom x = Id $ fromAtom x
fromId :: Monad m => Id -> m Name
fromId (Id i) = case intToAtom i of
Just a -> return $ fromAtom a
Nothing -> fail $ "Name.fromId: not a name " ++ show (Id i)
instance DocLike d => PPrint d Id where
pprint x = tshow x
instance GenName Id where
genNames = candidateIds
instance B.Binary Id where
put (Id x) = case intToAtom x of
Just a -> do B.putWord8 128 >> B.put a
Nothing | x >= 0 && x < 128 -> B.putWord8 (fromIntegral x)
| otherwise -> do
B.putWord8 129
B.put (fromIntegral x :: Int32)
get = do
x <- B.getWord8
case x of
128 -> do
a <- B.get
return (toId $ fromAtom a)
129 -> do
v <- B.get
return (Id $ fromIntegral (v :: Int32))
_ -> return (Id $ fromIntegral x)
| m-alvarez/jhc | src/Name/Id.hs | mit | 9,606 | 0 | 17 | 2,381 | 2,501 | 1,328 | 1,173 | -1 | -1 |
{-# LANGUAGE MagicHash #-}
{- |
Module : $Header$
Description : the abstract syntax of shared ATerms and their lookup table
Copyright : (c) Klaus Luettich, C. Maeder, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable(imports System.Mem.StableName and GHC.Prim)
the data types 'ShATerm' and 'ATermTable' plus some utilities
-}
module ATerm.AbstractSyntax
(ShATerm (..),
ATermTable,
emptyATermTable,
addATerm,
getATerm, toReadonlyATT,
getTopIndex,
getATerm', setATerm', getShATerm,
Key, getKey, setKey, mkKey,
getATermByIndex1, str2Char, integer2Int
) where
import qualified Data.Map as Map
import qualified Data.Map as IntMap
import Data.Dynamic
import Data.Array
import System.Mem.StableName
import GHC.Prim
import qualified Data.List as List
import Data.Maybe
data ShATerm =
ShAAppl String [Int] [Int]
| ShAList [Int] [Int]
| ShAInt Integer [Int]
deriving (Show, Eq, Ord)
data IntMap =
Updateable !(IntMap.Map Int ShATerm)
| Readonly !(Array Int ShATerm)
empty :: IntMap
empty = Updateable IntMap.empty
insert :: Int -> ShATerm -> IntMap -> IntMap
insert i s t = case t of
Updateable m -> Updateable $ IntMap.insert i s m
_ -> error "ATerm.insert"
find :: Int -> IntMap -> ShATerm
find i t = case t of
Updateable m -> IntMap.findWithDefault (ShAInt (-1) []) i m
Readonly a -> a ! i
data EqKey = EqKey (StableName ()) TypeRep deriving Eq
data Key = Key Int EqKey
mkKey :: Typeable a => a -> IO Key
mkKey t = do
s <- makeStableName t
return $ Key (hashStableName s) $ EqKey (unsafeCoerce # s) $ typeOf t
data ATermTable = ATT
(IntMap.Map Int [(EqKey, Int)])
!(Map.Map ShATerm Int) !IntMap Int
!(IntMap.Map Int [Dynamic])
toReadonlyATT :: ATermTable -> ATermTable
toReadonlyATT (ATT h s t i dM) = ATT h s
(case t of
Updateable m -> Readonly $ listArray (0, i) $ IntMap.elems m
_ -> t ) i dM
emptyATermTable :: ATermTable
emptyATermTable = ATT IntMap.empty Map.empty empty (-1) IntMap.empty
addATermNoFullSharing :: ShATerm -> ATermTable -> (ATermTable, Int)
addATermNoFullSharing t (ATT h a_iDFM i_aDFM i1 dM) = let j = i1 + 1 in
(ATT h (Map.insert t j a_iDFM) (insert j t i_aDFM) j dM, j)
addATerm :: ShATerm -> ATermTable -> (ATermTable, Int)
addATerm t at@(ATT _ a_iDFM _ _ _) =
case Map.lookup t a_iDFM of
Nothing -> addATermNoFullSharing t at
Just i -> (at, i)
setKey :: Key -> Int -> ATermTable -> IO (ATermTable, Int)
setKey (Key h e) i (ATT t s l m d) =
return (ATT (IntMap.insertWith (++) h [(e, i)] t) s l m d, i)
getKey :: Key -> ATermTable -> IO (Maybe Int)
getKey (Key h k) (ATT t _ _ _ _) =
return $ List.lookup k $ IntMap.findWithDefault [] h t
getATerm :: ATermTable -> ShATerm
getATerm (ATT _ _ i_aFM i _) = find i i_aFM
getShATerm :: Int -> ATermTable -> ShATerm
getShATerm i (ATT _ _ i_aFM _ _) = find i i_aFM
getTopIndex :: ATermTable -> Int
getTopIndex (ATT _ _ _ i _) = i
getATermByIndex1 :: Int -> ATermTable -> ATermTable
getATermByIndex1 i (ATT h a_iDFM i_aDFM _ dM) = ATT h a_iDFM i_aDFM i dM
getATerm' :: Typeable t => Int -> ATermTable -> Maybe t
getATerm' i (ATT _ _ _ _ dM) =
listToMaybe $ mapMaybe fromDynamic $ IntMap.findWithDefault [] i dM
setATerm' :: Typeable t => Int -> t -> ATermTable -> ATermTable
setATerm' i t (ATT h a_iDFM i_aDFM m dM) =
ATT h a_iDFM i_aDFM m $ IntMap.insertWith (++) i [toDyn t] dM
-- | conversion of a string in double quotes to a character
str2Char :: String -> Char
str2Char str = case str of
'\"' : sr@(_ : _) -> conv' (init sr) where
conv' r = case r of
[x] -> x
['\\', x] -> case x of
'n' -> '\n'
't' -> '\t'
'r' -> '\r'
'\"' -> '\"'
_ -> error "ATerm.AbstractSyntax: unexpected escape sequence"
_ -> error "ATerm.AbstractSyntax: String not convertible to Char"
_ -> error "ATerm.AbstractSyntax: String doesn't begin with '\"'"
-- | conversion of an unlimited integer to a machine int
integer2Int :: Integer -> Int
integer2Int x = if toInteger ((fromInteger :: Integer -> Int) x) == x
then fromInteger x else
error $ "ATerm.AbstractSyntax: Integer to big for Int: " ++ show x
| keithodulaigh/Hets | atermlib/src/ATerm/AbstractSyntax.hs | gpl-2.0 | 4,334 | 0 | 16 | 1,000 | 1,520 | 792 | 728 | 109 | 8 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fa-IR">
<title>Advanced SQLInjection Scanner</title>
<maps>
<homeID>sqliplugin</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/sqliplugin/src/main/javahelp/help_fa_IR/helpset_fa_IR.hs | apache-2.0 | 981 | 77 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="id-ID">
<title>ToDo-List</title>
<maps>
<homeID>todo</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/todo/src/main/javahelp/help_id_ID/helpset_id_ID.hs | apache-2.0 | 955 | 77 | 67 | 155 | 408 | 207 | 201 | -1 | -1 |
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Utils where
import Idris.AbsSyntax
import Idris.Error
import Idris.DeepSeq
import Idris.Delaborate
import Idris.Docstrings
import Idris.Output
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Typecheck
import Util.Pretty
import Control.Applicative hiding (Const)
import Control.Monad.State
import Control.Monad
import Data.List
import Data.Maybe
import qualified Data.Traversable as Traversable
import Debug.Trace
import qualified Data.Map as Map
recheckC = recheckC_borrowing False True []
recheckC_borrowing uniq_check addConstrs bs fc mkerr env t
= do -- t' <- applyOpts (forget t) (doesn't work, or speed things up...)
ctxt <- getContext
t' <- case safeForget t of
Just ft -> return ft
Nothing -> tclift $ tfail $ mkerr (At fc (IncompleteTerm t))
(tm, ty, cs) <- tclift $ case recheck_borrowing uniq_check bs ctxt env t' t of
Error e -> tfail (At fc (mkerr e))
OK x -> return x
logLvl 6 $ "CONSTRAINTS ADDED: " ++ show (tm, ty, cs)
when addConstrs $ addConstraints fc cs
mapM_ (checkDeprecated fc) (allTTNames tm)
mapM_ (checkDeprecated fc) (allTTNames ty)
return (tm, ty)
checkDeprecated :: FC -> Name -> Idris ()
checkDeprecated fc n
= do r <- getDeprecated n
case r of
Nothing -> return ()
Just r -> do iWarn fc $ text "Use of deprecated name " <> annName n
<> case r of
"" -> Util.Pretty.empty
_ -> line <> text r
iderr :: Name -> Err -> Err
iderr _ e = e
checkDef :: FC -> (Name -> Err -> Err) -> [(Name, (Int, Maybe Name, Type, [Name]))]
-> Idris [(Name, (Int, Maybe Name, Type, [Name]))]
checkDef fc mkerr ns = checkAddDef False True fc mkerr ns
checkAddDef :: Bool -> Bool -> FC -> (Name -> Err -> Err)
-> [(Name, (Int, Maybe Name, Type, [Name]))]
-> Idris [(Name, (Int, Maybe Name, Type, [Name]))]
checkAddDef add toplvl fc mkerr [] = return []
checkAddDef add toplvl fc mkerr ((n, (i, top, t, psns)) : ns)
= do ctxt <- getContext
logLvl 5 $ "Rechecking deferred name " ++ show (n, t)
(t', _) <- recheckC fc (mkerr n) [] t
when add $ do addDeferred [(n, (i, top, t, psns, toplvl))]
addIBC (IBCDef n)
ns' <- checkAddDef add toplvl fc mkerr ns
return ((n, (i, top, t', psns)) : ns')
-- | Get the list of (index, name) of inaccessible arguments from an elaborated
-- type
inaccessibleImps :: Int -> Type -> [Bool] -> [(Int, Name)]
inaccessibleImps i (Bind n (Pi _ t _) sc) (inacc : ins)
| inacc = (i, n) : inaccessibleImps (i + 1) sc ins
| otherwise = inaccessibleImps (i + 1) sc ins
inaccessibleImps _ _ _ = []
-- | Get the list of (index, name) of inaccessible arguments from the type.
inaccessibleArgs :: Int -> PTerm -> [(Int, Name)]
inaccessibleArgs i (PPi plicity n _ ty t)
| InaccessibleArg `elem` pargopts plicity
= (i,n) : inaccessibleArgs (i+1) t -- an .{erased : Implicit}
| otherwise
= inaccessibleArgs (i+1) t -- a {regular : Implicit}
inaccessibleArgs _ _ = []
elabCaseBlock :: ElabInfo -> FnOpts -> PDecl -> Idris ()
elabCaseBlock info opts d@(PClauses f o n ps)
= do addIBC (IBCDef n)
logLvl 5 $ "CASE BLOCK: " ++ show (n, d)
let opts' = nub (o ++ opts)
-- propagate totality assertion to the new definitions
when (AssertTotal `elem` opts) $ setFlags n [AssertTotal]
rec_elabDecl info EAll info (PClauses f opts' n ps )
-- | Check that the result of type checking matches what the programmer wrote
-- (i.e. - if we inferred any arguments that the user provided, make sure
-- they are the same!)
checkInferred :: FC -> PTerm -> PTerm -> Idris ()
checkInferred fc inf user =
do logLvl 6 $ "Checked to\n" ++ showTmImpls inf ++ "\n\nFROM\n\n" ++
showTmImpls user
logLvl 10 $ "Checking match"
i <- getIState
tclift $ case matchClause' True i user inf of
_ -> return ()
-- Left (x, y) -> tfail $ At fc
-- (Msg $ "The type-checked term and given term do not match: "
-- ++ show x ++ " and " ++ show y)
logLvl 10 $ "Checked match"
-- ++ "\n" ++ showImp True inf ++ "\n" ++ showImp True user)
-- | Return whether inferred term is different from given term
-- (as above, but return a Bool)
inferredDiff :: FC -> PTerm -> PTerm -> Idris Bool
inferredDiff fc inf user =
do i <- getIState
logLvl 6 $ "Checked to\n" ++ showTmImpls inf ++ "\n" ++
showTmImpls user
tclift $ case matchClause' True i user inf of
Right vs -> return False
Left (x, y) -> return True
-- | Check a PTerm against documentation and ensure that every documented
-- argument actually exists. This must be run _after_ implicits have been
-- found, or it will give spurious errors.
checkDocs :: FC -> [(Name, Docstring a)] -> PTerm -> Idris ()
checkDocs fc args tm = cd (Map.fromList args) tm
where cd as (PPi _ n _ _ sc) = cd (Map.delete n as) sc
cd as _ | Map.null as = return ()
| otherwise = ierror . At fc . Msg $
"There is documentation for argument(s) "
++ (concat . intersperse ", " . map show . Map.keys) as
++ " but they were not found."
decorateid decorate (PTy doc argdocs s f o n nfc t) = PTy doc argdocs s f o (decorate n) nfc t
decorateid decorate (PClauses f o n cs)
= PClauses f o (decorate n) (map dc cs)
where dc (PClause fc n t as w ds) = PClause fc (decorate n) (dappname t) as w ds
dc (PWith fc n t as w pn ds)
= PWith fc (decorate n) (dappname t) as w pn
(map (decorateid decorate) ds)
dappname (PApp fc (PRef fc' hl n) as) = PApp fc (PRef fc' hl (decorate n)) as
dappname t = t
-- if 't' is a type class application, assume its arguments are injective
pbinds :: IState -> Term -> ElabD ()
pbinds i (Bind n (PVar t) sc)
= do attack; patbind n
env <- get_env
case unApply (normalise (tt_ctxt i) env t) of
(P _ c _, args) -> case lookupCtxt c (idris_classes i) of
[] -> return ()
_ -> -- type class, set as injective
mapM_ setinjArg args
_ -> return ()
pbinds i sc
where setinjArg (P _ n _) = setinj n
setinjArg _ = return ()
pbinds i tm = return ()
pbty (Bind n (PVar t) sc) tm = Bind n (PVTy t) (pbty sc tm)
pbty _ tm = tm
getPBtys (Bind n (PVar t) sc) = (n, t) : getPBtys sc
getPBtys (Bind n (PVTy t) sc) = (n, t) : getPBtys sc
getPBtys _ = []
psolve (Bind n (PVar t) sc) = do solve; psolve sc
psolve tm = return ()
pvars ist (Bind n (PVar t) sc) = (n, delab ist t) : pvars ist sc
pvars ist _ = []
getFixedInType i env (PExp _ _ _ _ : is) (Bind n (Pi _ t _) sc)
= nub $ getFixedInType i env [] t ++
getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
++ case unApply t of
(P _ n _, _) -> if n `elem` env then [n] else []
_ -> []
getFixedInType i env (_ : is) (Bind n (Pi _ t _) sc)
= getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
getFixedInType i env is tm@(App _ f a)
| (P _ tn _, args) <- unApply tm
= case lookupCtxtExact tn (idris_datatypes i) of
Just t -> nub $ paramNames args env (param_pos t) ++
getFixedInType i env is f ++
getFixedInType i env is a
Nothing -> nub $ getFixedInType i env is f ++
getFixedInType i env is a
| otherwise = nub $ getFixedInType i env is f ++
getFixedInType i env is a
getFixedInType i _ _ _ = []
getFlexInType i env ps (Bind n (Pi _ t _) sc)
= nub $ (if (not (n `elem` ps)) then getFlexInType i env ps t else []) ++
getFlexInType i (n : env) ps (instantiate (P Bound n t) sc)
getFlexInType i env ps tm@(App _ f a)
| (P nt tn _, args) <- unApply tm, nt /= Bound
= case lookupCtxtExact tn (idris_datatypes i) of
Just t -> nub $ paramNames args env [x | x <- [0..length args],
not (x `elem` param_pos t)]
++ getFlexInType i env ps f ++
getFlexInType i env ps a
Nothing -> let ppos = case lookupCtxtExact tn (idris_fninfo i) of
Just fi -> fn_params fi
Nothing -> []
in nub $ paramNames args env [x | x <- [0..length args],
not (x `elem` ppos)]
++ getFlexInType i env ps f ++
getFlexInType i env ps a
| otherwise = nub $ getFlexInType i env ps f ++
getFlexInType i env ps a
getFlexInType i _ _ _ = []
-- | Treat a name as a parameter if it appears in parameter positions in
-- types, and never in a non-parameter position in a (non-param) argument type.
getParamsInType :: IState -> [Name] -> [PArg] -> Type -> [Name]
getParamsInType i env ps t = let fix = getFixedInType i env ps t
flex = getFlexInType i env fix t in
[x | x <- fix, not (x `elem` flex)]
getTCinj i (Bind n (Pi _ t _) sc)
= getTCinj i t ++ getTCinj i (instantiate (P Bound n t) sc)
getTCinj i ap@(App _ f a)
| (P _ n _, args) <- unApply ap,
isTCName n = mapMaybe getInjName args
| otherwise = []
where
isTCName n = case lookupCtxtExact n (idris_classes i) of
Just _ -> True
_ -> False
getInjName t | (P _ x _, _) <- unApply t = Just x
| otherwise = Nothing
getTCinj _ _ = []
getTCParamsInType :: IState -> [Name] -> [PArg] -> Type -> [Name]
getTCParamsInType i env ps t = let params = getParamsInType i env ps t
tcs = nub $ getTCinj i t in
filter (flip elem tcs) params
paramNames args env [] = []
paramNames args env (p : ps)
| length args > p = case args!!p of
P _ n _ -> if n `elem` env
then n : paramNames args env ps
else paramNames args env ps
_ -> paramNames args env ps
| otherwise = paramNames args env ps
getUniqueUsed :: Context -> Term -> [Name]
getUniqueUsed ctxt tm = execState (getUniq [] [] tm) []
where
getUniq :: Env -> [(Name, Bool)] -> Term -> State [Name] ()
getUniq env us (Bind n b sc)
= let uniq = case check ctxt env (forgetEnv (map fst env) (binderTy b)) of
OK (_, UType UniqueType) -> True
OK (_, UType NullType) -> True
OK (_, UType AllTypes) -> True
_ -> False in
do getUniqB env us b
getUniq ((n,b):env) ((n, uniq):us) sc
getUniq env us (App _ f a) = do getUniq env us f; getUniq env us a
getUniq env us (V i)
| i < length us = if snd (us!!i) then use (fst (us!!i)) else return ()
getUniq env us (P _ n _)
| Just u <- lookup n us = if u then use n else return ()
getUniq env us _ = return ()
use n = do ns <- get; put (n : ns)
getUniqB env us (Let t v) = getUniq env us v
getUniqB env us (Guess t v) = getUniq env us v
-- getUniqB env us (Pi t v) = do getUniq env us t; getUniq env us v
getUniqB env us (NLet t v) = getUniq env us v
getUniqB env us b = return () -- getUniq env us (binderTy b)
-- In a functional application, return the names which are used
-- directly in a static position
getStaticNames :: IState -> Term -> [Name]
getStaticNames ist (Bind n (PVar _) sc)
= getStaticNames ist (instantiate (P Bound n Erased) sc)
getStaticNames ist tm
| (P _ fn _, args) <- unApply tm
= case lookupCtxtExact fn (idris_statics ist) of
Just stpos -> getStatics args stpos
_ -> []
where
getStatics (P _ n _ : as) (True : ss) = n : getStatics as ss
getStatics (_ : as) (_ : ss) = getStatics as ss
getStatics _ _ = []
getStaticNames _ _ = []
getStatics :: [Name] -> Term -> [Bool]
getStatics ns (Bind n (Pi _ _ _) t)
| n `elem` ns = True : getStatics ns t
| otherwise = False : getStatics ns t
getStatics _ _ = []
mkStatic :: [Name] -> PDecl -> PDecl
mkStatic ns (PTy doc argdocs syn fc o n nfc ty)
= PTy doc argdocs syn fc o n nfc (mkStaticTy ns ty)
mkStatic ns t = t
mkStaticTy :: [Name] -> PTerm -> PTerm
mkStaticTy ns (PPi p n fc ty sc)
| n `elem` ns = PPi (p { pstatic = Static }) n fc ty (mkStaticTy ns sc)
| otherwise = PPi p n fc ty (mkStaticTy ns sc)
mkStaticTy ns t = t
| mrmonday/Idris-dev | src/Idris/Elab/Utils.hs | bsd-3-clause | 13,576 | 3 | 20 | 4,832 | 5,089 | 2,551 | 2,538 | 253 | 13 |
{-# LANGUAGE TypeFamilies, DataKinds, PolyKinds, UndecidableInstances #-}
module T6018failclosed where
-- Id is injective...
type family IdClosed a = result | result -> a where
IdClosed a = a
-- ...but despite that we disallow a call to Id
type family IdProxyClosed (a :: *) = r | r -> a where
IdProxyClosed a = IdClosed a
data N = Z | S N
-- PClosed is not injective, although the user declares otherwise. This
-- should be rejected on the grounds of calling a type family in the
-- RHS.
type family PClosed (a :: N) (b :: N) = (r :: N) | r -> a b where
PClosed Z m = m
PClosed (S n) m = S (PClosed n m)
-- this is not injective - not all injective type variables mentioned
-- on LHS are mentioned on RHS
type family JClosed a b c = r | r -> a b where
JClosed Int b c = Char
-- this is not injective - not all injective type variables mentioned
-- on LHS are mentioned on RHS (tyvar is now nested inside a tycon)
type family KClosed (a :: N) (b :: N) = (r :: N) | r -> a b where
KClosed (S n) m = S m
-- hiding a type family application behind a type synonym should be rejected
type MaybeSynClosed a = IdClosed a
type family LClosed a = r | r -> a where
LClosed a = MaybeSynClosed a
type family FClosed a b c = (result :: *) | result -> a b c where
FClosed Int Char Bool = Bool
FClosed Char Bool Int = Int
FClosed Bool Int Char = Int
type family IClosed a b c = r | r -> a b where
IClosed Int Char Bool = Bool
IClosed Int Int Int = Bool
IClosed Bool Int Int = Int
type family E2 (a :: Bool) = r | r -> a where
E2 False = True
E2 True = False
E2 a = False
-- This exposed a subtle bug in the implementation during development. After
-- unifying the RHS of (1) and (2) the LHS substitution was done only in (2)
-- which made it look like an overlapped equation. This is not the case and this
-- definition should be rejected. The first two equations are here to make sure
-- that the internal implementation does list indexing corrcectly (this is a bit
-- tricky because the list is kept in reverse order).
type family F a b = r | r -> a b where
F Float IO = Float
F Bool IO = Bool
F a IO = IO a -- (1)
F Char b = b Int -- (2)
-- This should fail because there is no way to determine a, b and k from the RHS
type family Gc (a :: k) (b :: k) = r | r -> k where
Gc a b = Int
| wxwxwwxxx/ghc | testsuite/tests/typecheck/should_fail/T6018failclosed.hs | bsd-3-clause | 2,408 | 0 | 8 | 637 | 544 | 340 | 204 | 36 | 0 |
import Module (message)
import Distribution.Simple
main = putStrLn ("Setup.hs: " ++ message) >> defaultMain
| mydaum/cabal | cabal-testsuite/PackageTests/BuildTargets/UseLocalPackageForSetup/pkg/Setup.hs | bsd-3-clause | 109 | 0 | 8 | 15 | 33 | 18 | 15 | 3 | 1 |
-- !!! Infix decls w/ infix data constructors
-- GHC used to barf on this...
module ShouldCompile where
infix 2 |-, |+
ps |- q:qs = undefined
ps |+ p:q:qs = undefined
| siddhanathan/ghc | testsuite/tests/parser/should_compile/read030.hs | bsd-3-clause | 177 | 0 | 7 | 42 | 48 | 26 | 22 | -1 | -1 |
import Drawing
import Geometry
main = drawPicture myPicture
myPicture points =
coordinates &
drawPoints [a,b] &
drawLabels [a,b] ["A","B"] &
drawSegment (a,b) &
message ("length AB = "++ show (dist a b))
where [a,b] = [(25,10),(50,16)]
| alphalambda/k12math | contrib/MHills/GeometryLessons/code/teacher/key_lesson3N2.hs | mit | 268 | 0 | 11 | 68 | 127 | 70 | 57 | 10 | 1 |
module Rebase.Control.Monad.RWS.Class
(
module Control.Monad.RWS.Class
)
where
import Control.Monad.RWS.Class
| nikita-volkov/rebase | library/Rebase/Control/Monad/RWS/Class.hs | mit | 113 | 0 | 5 | 12 | 26 | 19 | 7 | 4 | 0 |
module Ai (
DoTurn
, doTurn
) where
import Control.Applicative
import Control.Monad (join)
import Data.List ((\\))
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import qualified Data.Set as S
import Data.Graph.AStar
import Point
import Protocol
import Search
import Tore
import Util
import World
type DoTurn = GameState -> IO (GameState, Orders)
type AntPoints = Points
type Tactic = GameState -> AntPoints -> Orders
exploreDist = 10
foodDist = 9
areaDist = 17
doTurn :: DoTurn
doTurn gs = do
mapM_ putStrLn $ _showMissions keptMissions blue
mapM_ putStrLn $ _showMissions newMissions red
mapM_ putStrLn $ _showPoints (S.toList (borderSet gs3)) green
return (gs3, finalOrders)
where gs2 = updateMystery gs
(orders, antPoints) = strategy [foodTactic, exploreTactic] gs2
(keptMissions, newMissions) = borderMissions gs2 antPoints
missions = keptMissions ++ newMissions
missionOrders = mapMaybe missionOrder missions
allOrders = orders ++ missionOrders
finalOrders = preventCollisions (world gs2) allOrders
updatedMissions = updateMissions missions finalOrders
gs3 = gs2 {gameMissions = updatedMissions}
missionOrder :: Mission -> Maybe Order
missionOrder (_, []) = Nothing
missionOrder ((from, _), next:_) = Just $ moveToOrder (from, next)
-- path excludes starting and ending points
pathTo :: World -> Point -> Point -> Maybe Points
pathTo w from to = init <$> nextPath
where nextPath = aStar neighbors close (heur to) (== to) from
neighbors = S.fromList . pointOpenNeighbors w
close _ _ = 1
heur = manhattan (toreBound w)
updateMissions :: Missions -> Orders -> Missions
updateMissions missions orders = updateMission <$> missions
where updateMission mission@(_, []) = mission
updateMission mission@((from, to), next:path)
| any ((== from) . fst) orders = ((next, to), path)
| otherwise = mission
borderMissions :: GameState -> AntPoints -> (Missions, Missions)
borderMissions gs antPoints = (kepts, news)
where w = world gs
kepts = filter keepMission (gameMissions gs)
keepMission (_, []) = False
keepMission ((from, to), _) = from `elem` antPoints && pointIsOpenAndFree w to
freeAps = antPoints \\ ((fst . fst) <$> kepts)
news = mapMaybe (antMission . point) freeAps
antMission a = do
dest <- bfsClosestInSet w (borderSet gs) a
path <- pathTo w a dest
return ((a, dest), path)
borderSet :: GameState -> S.Set Point
borderSet gs = bfsBorderSet (world gs) areaDist $ gameAnts gs
strategy :: [Tactic] -> GameState -> (Orders, AntPoints)
strategy fs gs = runTactics (($ gs) <$> fs) myAntPoints
where myAntPoints = point <$> (isMine `filter` gameAnts gs)
runTactics [] ants = ([], ants)
runTactics _ [] = ([], [])
runTactics (t:ts) ants = (orders ++ nextOrders, nextAnts)
where (nextOrders, nextAnts) = runTactics ts remainingAnts
orders = t ants
remainingAnts = ants \\ (fst <$> orders)
exploreTactic :: Tactic
exploreTactic gs = mapMaybe exploreAnt
where w = world gs
exploreAnt a = (,) a <$> bfsMysteriousDir w exploreDist (w %! a)
foodTactic :: Tactic
foodTactic gs ants = (moveToOrder . fst) <$> foodTargets
where w = world gs
foodTargets = collectFoods ((w %!) <$> gameFoods gs) ants
collectFoods = bfsMovesTo w foodDist
preventCollisions :: World -> [Order] -> [Order]
preventCollisions w orders = M.elems orderMap
where orderMap = M.fromList $ (\o -> (uncurry (toreMove w) o, o)) <$> orders
updateMystery :: GameState -> GameState
updateMystery gs = gs { world = exploration <$> w }
where w = world gs
allReachableTiles = bfsTilesFroms w exploreDist (tileOf w <$> myAnts)
myAnts = filter isMine (gameAnts gs)
increment t = t { mystery = mystery t + 1 }
reachable = flip S.member allReachableTiles
exploration t = if reachable t then t {mystery = 0} else increment t
_showTargets :: [(Move, Point)] -> String -> [String]
_showTargets targets color = lineColor color : (targets >>= showTarget)
where showTarget ((a, b), c) = drawArrow a <$> [b, c]
_showDirBorders :: GameState -> Direction -> String -> [String]
_showDirBorders gs dir color = fillColor color : showTiles
where w = world gs
antTiles = tileOf w <$> filter isMine (gameAnts gs)
borderTiles = join $ bfsDirBorders w exploreDist dir <$> antTiles
showTiles = showTile <$> borderTiles
showTile = drawPoint . point
_showPoints :: [Point] -> String -> [String]
_showPoints points color = fillColor color : (drawPoint <$> points)
_showMissions :: [Mission] -> String -> [String]
_showMissions missions color = lineColor color : (showMission <$> missions)
where showMission ((a, b), _) = drawArrow a b
| ornicar/haskant | src/Ai.hs | mit | 5,049 | 0 | 14 | 1,272 | 1,718 | 924 | 794 | 110 | 3 |
{-# LANGUAGE TemplateHaskell #-}
module Ffs.Options where
import Control.Lens
import Control.Lens.TH
import Data.Time.Calendar
import Data.Text
import Data.Time.LocalTime (TimeZone)
import Network.URI
import System.Log.Logger as Log
import System.FilePath
import Text.ParserCombinators.ReadPrec hiding (choice)
import Text.ParserCombinators.ReadP as ReadP
import Text.Read hiding (choice)
import Ffs.Time
data Grouping
= Issue
| Field Text
| Epic
deriving (Eq, Show)
instance Read Grouping where
readPrec = lift $ choice [parseIssue, parseGroup, parseEpic]
where
parseIssue = do
ReadP.string "issue"
ReadP.eof
return Issue
parseGroup = do
ReadP.string "field:"
name <- ReadP.munch (const True)
return $! Field $ (strip . pack) name
parseEpic = do
ReadP.string "epic"
ReadP.eof
return Epic
data FfsOptions = FfsOptions
{ _optUsername :: Text
, _optPassword :: Text
, _optLogLevel :: Log.Priority
, _optJiraHost :: URI
, _optUseInsecureTLS :: Bool
, _optLastDayOfWeek :: DayOfWeek
, _optGroupBy :: Grouping
, _optTargetUser :: Maybe Text
, _optRollUpSubTasks :: Bool
, _optTimeZone :: Maybe TimeZone
, _optDateRange :: Maybe DateRange
, _optCsvFile :: Maybe FilePath
} deriving (Show, Eq)
makeLenses ''FfsOptions
defaultOptions =
FfsOptions
{ _optUsername = ""
, _optPassword = ""
, _optLogLevel = Log.INFO
, _optJiraHost = nullURI
, _optUseInsecureTLS = False
, _optLastDayOfWeek = Sunday
, _optGroupBy = Issue
, _optTargetUser = Nothing
, _optRollUpSubTasks = False
, _optTimeZone = Nothing
, _optDateRange = Nothing
, _optCsvFile = Nothing
}
| tcsc/ffs | src/Ffs/Options.hs | mit | 1,709 | 0 | 13 | 379 | 446 | 258 | 188 | 62 | 1 |
import Data.List.Split
import Data.List
import System.IO
transposta :: [[a]] -> [[a]]
transposta ([]:_) = []
transposta x = (map head x) : transposta (map tail x)
maior [x,y,z]
| (x>=y) && (x>=z) = x
| (y>=x) && (y>=z) = y
| otherwise = z
argmax t = do
let (x,y) = foldl (\ (x,i) (y,j) -> if x>y then (x,i) else (y,j) ) (-1,-1) (zip t [0..6])
y+1
maiorCaloria t = argmax $ map maior t
acimaMedia t medias = map ( filter (\(x,y) -> y>x) ) (map (zip medias) t)
main = do
linhas1 <- readFile "calorias.csv"
let matrizStr x = map (splitOn ";") (lines x)
calorias = map (map read) (matrizStr linhas1) :: [[Float]]
mediaPeriodo = map (foldl (\acc x -> acc + x/7.0) 0) calorias
mediaDia = map (foldl (\acc x -> acc + x/3.0) 0) (transposta calorias)
tabela = zipWith (\x y -> x ++ [y]) calorias mediaPeriodo
tabelaStr = zipWith (:) ["Manhã","Tarde","Noite"] (map (map show) tabela)
acima = acimaMedia (transposta tabela) mediaPeriodo
putStrLn "\tSeg.\tTer.\tQua.\tQui.\tSex.\tSab.\tDom.\tMedia"
putStrLn $ (unlines (map (intercalate "\t") tabelaStr))
putStrLn $ "\t" ++ (intercalate "\t" (map show mediaDia))
putStrLn $ "Dia de maior caloria: " ++ (show (maiorCaloria (transposta tabela)))
--putStrLn $ show (acimaMedia (transposta tabela) mediaPeriodo)
let texto = filter (\(x,y) -> not (null x)) (zip (map (\t -> if null t then "" else " acima da média" ) acima) [1..7])
putStrLn $ unlines (map (\(x,y) -> "Dia " ++ (show y) ++ x) texto)
| folivetti/PI-UFABC | AULA_07/Haskell/Dieta.hs | mit | 1,623 | 2 | 18 | 433 | 794 | 416 | 378 | 30 | 2 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
module Parser.Ast where
import GlobalAst (SourceRange(..), TSize(..), BinOp(..), UnOp(..), TerminatorType(..), Source, location, Inline(..))
import Data.Generics.Uniplate.Direct
type SourceFile = SourceFileT String
data SourceFileT v = SourceFile
{ typeDefinitions :: [TypeDefT v]
, callableDefinitions :: [CallableDefT v]
, cImportDefinitions :: [RequestT Type v]
, cExportDefinitions :: [RequestT Type v]
}
type Request = RequestT Type String
data RequestT t v = Request v String t deriving (Eq, Ord, Show)
data HiddenIdentifiers = HideAll | HideSome [String] deriving Show
type Replacement v = (Maybe (ExpressionT v), ExpressionT v)
type TypeDef = TypeDefT String
data TypeDefT v = NewType
{ typeName :: String
, typeParams :: [String]
, hiddenIdentifiers :: HiddenIdentifiers
, introducedIdentifiers :: [(String, Replacement v)]
, bracketPatterns :: [([BracketTokenT v], Replacement v)]
, wrappedType :: Type
, typeRange :: SourceRange
}
| Alias
{ typeName :: String
, typeParams :: [String]
, wrappedType :: Type
, typeRange :: SourceRange
}
data BracketTokenT v = BrId v (Maybe (ExpressionT v))
| BrOp String
instance Show v => Show (BracketTokenT v) where
show (BrId v me) = maybe "" (const "optional ") me ++ show v
show (BrOp o) = show o
type CallableDef = CallableDefT String
data CallableDefT v = FuncDef
{ callableName :: String
, intypes :: [Type]
, outtype :: Type
, inargs :: [v]
, outarg :: v
, callableBody :: StatementT v
, callableRange :: SourceRange
}
| ProcDef
{ callableName :: String
, intypes :: [Type]
, outtypes :: [Type]
, inargs :: [v]
, outargs :: [v]
, callableBody :: StatementT v
, callableRange :: SourceRange
}
data Type = IntT TSize SourceRange
| UIntT TSize SourceRange
| FloatT TSize SourceRange
| BoolT SourceRange
| NamedT String [Type] SourceRange
| TypeVar String SourceRange
| PointerT Type SourceRange
| StructT [(String, Type)] SourceRange
| ProcT [Type] [Type] SourceRange
| FuncT [Type] Type SourceRange
| UnknownT SourceRange
deriving (Show, Eq, Ord)
instance Uniplate Type where
uniplate (IntT s r) = plate IntT |- s |- r
uniplate (UIntT s r) = plate IntT |- s |- r
uniplate (FloatT s r) = plate FloatT |- s |- r
uniplate (BoolT r) = plate BoolT |- r
uniplate (NamedT n ts r) = plate NamedT |- n ||* ts |- r
uniplate (TypeVar n r) = plate TypeVar |- n |- r
uniplate (PointerT t r) = plate PointerT |* t |- r
uniplate (StructT ps r) = plate StructT ||+ ps |- r
uniplate (ProcT is os r) = plate ProcT ||* is ||* os |- r
uniplate (FuncT is o r) = plate FuncT ||* is |* o |- r
instance Biplate (String, Type) Type where
biplate (s, t) = plate (,) |- s |* t
instance Biplate [Type] Type where
biplate [] = plate []
biplate (t:ts) = plate (:) |* t ||* ts
type Statement = StatementT String
data StatementT v = ProcCall Inline (ExpressionT v) [ExpressionT v] [Either (StatementT v) (ExpressionT v)] SourceRange
| Defer (StatementT v) SourceRange
| ShallowCopy (ExpressionT v) (ExpressionT v) SourceRange
| If (ExpressionT v) (StatementT v) (Maybe (StatementT v)) SourceRange
| While (ExpressionT v) (StatementT v) SourceRange
| Scope [StatementT v] SourceRange
| Terminator TerminatorType SourceRange
| VarInit Bool v (Maybe Type) (Maybe (ExpressionT v)) SourceRange
deriving Show
type Expression = ExpressionT String
data ExpressionT v = Bin BinOp (ExpressionT v) (ExpressionT v) SourceRange
| Un UnOp (ExpressionT v) SourceRange
| MemberAccess (ExpressionT v) String SourceRange
| Subscript (ExpressionT v) [Either String (ExpressionT v)] SourceRange
| Variable v SourceRange
| FuncCall Inline (ExpressionT v) [ExpressionT v] SourceRange
| ExprLit (LiteralT v)
| TypeAssertion (ExpressionT v) Type SourceRange
| NewTypeConversion (ExpressionT v) String SourceRange
deriving Show
type Literal = LiteralT String
data LiteralT v = ILit Integer SourceRange
| FLit Double SourceRange
| BLit Bool SourceRange
| Null SourceRange
| Undef SourceRange
| StructLit [(String, ExpressionT v)] SourceRange
| StructTupleLit [ExpressionT v] SourceRange
deriving Show
instance Source (TypeDefT v) where
location = typeRange
instance Source (CallableDefT v) where
location = callableRange
instance Source Type where
location (IntT _ r) = r
location (UIntT _ r) = r
location (FloatT _ r) = r
location (BoolT r) = r
location (NamedT _ _ r) = r
location (PointerT _ r) = r
location (StructT _ r) = r
instance Source (StatementT v) where
location (ProcCall _ _ _ _ r) = r
location (Defer _ r) = r
location (ShallowCopy _ _ r) = r
location (If _ _ _ r) = r
location (While _ _ r) = r
location (Scope _ r) = r
location (Terminator _ r) = r
location (VarInit _ _ _ _ r) = r
instance Source (ExpressionT v) where
location (Bin _ _ _ r) = r
location (Un _ _ r) = r
location (MemberAccess _ _ r) = r
location (Subscript _ _ r) = r
location (Variable _ r) = r
location (FuncCall _ _ _ r) = r
location (ExprLit l) = location l
location (TypeAssertion _ _ r) = r
location (NewTypeConversion _ _ r) = r
instance Source (LiteralT v) where
location (ILit _ r) = r
location (FLit _ r) = r
location (BLit _ r) = r
location (Null r) = r
location (Undef r) = r
location (StructTupleLit _ r) = r
location (StructLit _ r) = r
| elegios/datalang | src/Parser/Ast.hs | mit | 6,487 | 0 | 12 | 2,186 | 2,164 | 1,166 | 998 | 147 | 0 |
{-# LANGUAGE GADTs #-}
data Eql a b where
Refl :: Eql a a
sym :: Eql a b -> Eql b a
sym Refl = Refl
cong :: Eql a b -> Eql (f a) (f b)
cong Refl = Refl
trans :: Eql a b -> Eql b c -> Eql a c
trans Refl Refl = Refl
cast :: Eql a b -> a -> b
cast Refl = id
| riwsky/wiwinwlh | src/equal.hs | mit | 262 | 0 | 8 | 80 | 165 | 78 | 87 | 11 | 1 |
module Language.Haskell.GhcEdit where
testAdder :: Int -> Int -> Int
testAdder = (+)
| HanStolpo/ghc-edit | Language/Haskell/GhcEdit.hs | mit | 87 | 0 | 6 | 15 | 27 | 17 | 10 | 3 | 1 |
-- This is a demo of guards.
-- Since July 21 2013.
module Main where
main = do
return ()
comparison x y
| x < y = "The first is less"
| x > y = "The second is less"
| otherwise = "They are equal"
| fossilet/yaht | guards.hs | mit | 232 | 1 | 10 | 82 | 59 | 30 | 29 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid((<>))
import Control.Applicative
import Data.Attoparsec.Text
import Data.Text
import qualified Data.Text.Lazy.Builder as B
import qualified Data.Text.Lazy.Builder.Int as B
import qualified Data.Text.Lazy.Builder.RealFloat as B
data Person = Person { firstName :: String, lastName :: String }
deriving (Show, Ord, Eq)
data Client i = GovOrg { clientId :: i, clientName :: String }
| Company { clientId :: i, clientName :: String , person :: Person, duty :: String }
| Individual { clientId :: i, person :: Person }
deriving (Show, Ord, Eq)
data Product = Product { id :: Int, name :: String, price :: Double, descr :: String } deriving (Show, Ord, Eq)
data Purchase = Purchase { client :: Client Int, products :: [Product] } deriving (Show, Ord, Eq)
escapeString :: String -> Text
escapeString = replace "\n" "\\n" . replace "," "\\," . replace "(" "\\(" .
replace ")" "\\)" . pack
personToText :: Person -> B.Builder
personToText (Person f l) =
"person(" <> B.fromText (escapeString f) <> B.singleton ','
<> B.fromText (escapeString l) <> B.singleton ')'
clientToText :: Client Int -> B.Builder
clientToText (GovOrg i n) =
"client(gov," <> B.decimal i <> B.singleton ',' <> B.fromText (escapeString n) <> B.singleton ')'
clientToText (Company i n p d) =
"client(com," <> B.decimal i <> B.singleton ',' <> B.fromText (escapeString n) <> B.singleton ','
<> personToText p <> B.singleton ',' <> B.fromText (escapeString d) <> B.singleton ')'
clientToText (Individual i p) =
"client(ind," <> B.decimal i <> B.singleton ',' <> personToText p <> B.singleton ')'
aChar :: Parser Char
aChar = (const ',') <$> (string "\\,") <|> (const '\n') <$> (string "\\n")
<|> (const '(') <$> (string "\\(") <|> (const ')') <$> (string "\\)")
<|> satisfy (notInClass ",\n()")
aString :: Parser String
-- aString = ((:) <$> aChar <*> aString) <|> (pure "")
aString = many aChar
aPerson :: Parser Person
aPerson = Person <$ string "person(" <*> aString <* char ',' <*> aString <* char ')'
aClient :: Parser (Client Int)
aClient = GovOrg <$ string "client(gov," <*> decimal <* char ',' <*> aString <* char ')'
<|> Company <$ string "client(com," <*> decimal <* char ',' <*> aString <* char ','
<*> aPerson <* char ',' <*> aString <* char ')'
<|> Individual <$ string "client(ind," <*> decimal <* char ',' <*> aPerson <* char ')'
| hnfmr/beginning_haskell | chapter10/parseClients.hs | mit | 2,573 | 0 | 26 | 599 | 917 | 478 | 439 | 44 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
module Free where
import Control.Monad ( ap )
import Control.Monad.Fix
import Subtype
data Free f r = Free (f (Free f r)) | Pure r
instance Functor f => Functor (Free f) where
-- fmap :: (a -> b) -> (Free f a -> Free f b)
fmap f (Pure x) = Pure (f x) -- since x :: a
fmap f (Free fa) = Free ((fmap . fmap) f fa)
instance (Functor f, f :<: g) => Free f :<: Free g where
inject (Pure x) = Pure x
inject (Free f) = Free $ inject $ fmap inject f
instance Functor f => Applicative (Free f) where
pure = Pure
(<*>) = ap
instance Functor f => Monad (Free f) where
return = Pure
(Pure x) >>= k = k x
(Free f) >>= k = Free (fmap (>>= k) f)
instance Functor f => MonadFix (Free f) where
-- mfix :: (a -> Free f a) -> Free f a
mfix f = a where
a = f (impure a)
impure (Pure x) = x
impure (Free _) = error "mfix: Free"
-- | Promotes a functor into its associated free monad.
liftF :: Functor f => f r -> Free f r
liftF f = Free (fmap Pure f)
foldF :: Functor f => (f r -> r) -> Free f r -> r
foldF _ (Pure x) = x
foldF extract (Free f) = extract (fmap (foldF extract) f)
-- | Tear down a free monad monadically, reinterpreting it in another monad.
foldFM :: (Monad m, Functor f) => (f (m r) -> m r) -> Free f r -> m r
foldFM _ (Pure x) = return x
foldFM extract (Free f) = extract (fmap (foldFM extract) f)
($>) :: Functor f => f a -> b -> f b
f $> x = fmap (const x) f
| djeik/fuckdown2 | src/Free.hs | mit | 1,625 | 0 | 11 | 431 | 691 | 348 | 343 | 38 | 1 |
module Euler.E10 where
import Euler.Lib (primes)
euler10 :: Integer -> Integer
euler10 n = sum $ takeWhile (<n) $ primes
main :: IO ()
main = print $ euler10 2000000
| D4r1/project-euler | Euler/E10.hs | mit | 169 | 0 | 8 | 33 | 70 | 38 | 32 | 6 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Pianola.Protocol.IO (
RunInIOError(..),
Endpoint(..),
runProtocol
) where
import Prelude hiding (catch,(.))
import System.IO
import qualified Data.Text as T
import Network
import Data.Functor.Compose
import Data.Bifunctor
import Control.Applicative
import Control.Category
import Control.Exception
import Control.Monad.Logic
import Control.Monad.Free
import Control.Monad.Reader
import Control.Monad.State.Strict
import Data.Functor.Identity
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Pianola.Protocol
import Data.MessagePack
import Pipes.ByteString
import Pipes.Attoparsec
import Control.Monad.Error
data RunInIOError = CommError IOException
| ParseError T.Text
deriving Show
-- Spurious error instance. would putting and error here be too awful?
instance Error RunInIOError where
noMsg = ParseError T.empty
data Endpoint = Endpoint {
hostName::HostName,
portID::PortID
}
runFree:: (MonadIO m, MonadReader r m) => (r -> Endpoint) -> Free ProtocolF a -> ErrorT RunInIOError m a
runFree lens ( Free (Compose (b,parser)) ) = do
endpoint <- lift $ asks lens
let rpcCall :: Endpoint -> (Handle -> IO b) -> IO b
rpcCall endpointoint what2do = withSocketsDo $ do
bracket (connectTo (hostName endpointoint) (portID endpointoint))
hClose
what2do
handler h = do
mapM_ (BL.hPutStr h) b
hFlush h
evalStateT (parse parser) (fromHandle h)
ioErrHandler = \(ex :: IOException) -> return . Left . CommError $ ex
parseErrHandler = ParseError . T.pack . show
nextFree <- ErrorT . liftIO $
catches (bimap parseErrHandler snd <$> rpcCall endpoint handler)
[Handler ioErrHandler]
runFree lens nextFree
runFree _ ( Pure a ) = return a
-- | Runs a sequence of RPC calls in a base monad which has access to an
-- 'Endpoint' value which identifies the server. An accessor function must be
-- provided to extract the Endpoint from the base monad's environment, which
-- may be more general.
runProtocol :: (MonadIO m, MonadReader r m) => (r -> Endpoint) -> Protocol a -> ErrorT ServerError (ErrorT RunInIOError m) a
runProtocol lens = ErrorT . runFree lens . runErrorT
| danidiaz/pianola | src/Pianola/Protocol/IO.hs | mit | 2,424 | 0 | 17 | 594 | 623 | 340 | 283 | 55 | 1 |
module ClaimsSpec (spec) where
import Protolude
import qualified Data.HashMap.Strict as M
import Test.Hspec
import Data.Aeson (Value (..), toJSON)
import Data.Time.Clock
import PostgresWebsockets.Claims
secret :: ByteString
secret = "reallyreallyreallyreallyverysafe"
spec :: Spec
spec =
describe "validate claims" $ do
it "should invalidate an expired token" $ do
time <- getCurrentTime
validateClaims Nothing secret
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoiciIsImNoYW5uZWwiOiJ0ZXN0IiwiZXhwIjoxfQ.4rDYiMZFR2WHB7Eq4HMdvDP_BQZVtHIfyJgy0NshbHY" time
`shouldReturn` Left "Token expired"
it "request any channel from a token that does not have channels or channel claims should succeed" $ do
time <- getCurrentTime
validateClaims (Just "test") secret
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoiciJ9.jL5SsRFegNUlbBm8_okhHSujqLcKKZdDglfdqNl1_rY" time
`shouldReturn` Right (["test"], "r", M.fromList[("mode",String "r")])
it "requesting a channel that is set by and old style channel claim should work" $ do
time <- getCurrentTime
validateClaims (Just "test") secret
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoiciIsImNoYW5uZWwiOiJ0ZXN0In0.1d4s-at2kWj8OSabHZHTbNh1dENF7NWy_r0ED3Rwf58" time
`shouldReturn` Right (["test"], "r", M.fromList[("mode",String "r"),("channel",String "test")])
it "no requesting channel should return all channels in the token" $ do
time <- getCurrentTime
validateClaims Nothing secret
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoiciIsImNoYW5uZWxzIjpbInRlc3QiLCJhbm90aGVyIHRlc3QiXX0.b9N8J8tPOPIxxFj5WJ7sWrmcL8ib63i8eirsRZTM9N0" time
`shouldReturn` Right (["test", "another test"], "r", M.fromList[("mode",String "r"),("channels", toJSON["test"::Text, "another test"::Text] ) ])
it "requesting a channel from the channels claim shoud return only the requested channel" $ do
time <- getCurrentTime
validateClaims (Just "test") secret
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoiciIsImNoYW5uZWxzIjpbInRlc3QiLCJ0ZXN0MiJdfQ.MumdJ5FpFX4Z6SJD3qsygVF0r9vqxfqhj5J30O32N0k" time
`shouldReturn` Right (["test"], "r", M.fromList[("mode",String "r"),("channels", toJSON ["test"::Text, "test2"] )])
it "requesting a channel not from the channels claim shoud error" $ do
time <- getCurrentTime
validateClaims (Just "notAllowed") secret
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoiciIsImNoYW5uZWxzIjpbInRlc3QiLCJ0ZXN0MiJdfQ.MumdJ5FpFX4Z6SJD3qsygVF0r9vqxfqhj5J30O32N0k" time
`shouldReturn` Left "No allowed channels"
it "requesting a channel with no mode fails" $ do
time <- getCurrentTime
validateClaims (Just "test") secret
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjaGFubmVscyI6WyJ0ZXN0IiwidGVzdDIiXX0.akC1PEYk2DEZtLP2XjC6qXOGZJejmPx49qv-VeEtQYQ" time
`shouldReturn` Left "Missing mode"
| diogob/postgrest-ws | test/ClaimsSpec.hs | mit | 3,021 | 0 | 18 | 537 | 553 | 290 | 263 | 47 | 1 |
-- construct complete binary tree
-- and iscompletetree function
data Tree a = Empty | Branch a (Tree a) (Tree a) deriving Show
p63 :: Int -> Tree Char
p63 n = p63' 1 where
p63' x
| x > n = Empty
| otherwise = Branch 'x' (p63' (2*x)) (p63' (2*x+1))
-- iscompletetree
p63' :: Tree a -> Bool
p63' t = equal t (p63 (nodes t)) where
nodes Empty = 0
nodes (Branch _ l r) = 1 + nodes l + nodes r
equal Empty Empty = True
equal (Branch _ l1 r1) (Branch _ l2 r2) = (equal l1 l2) && (equal r1 r2)
equal _ _ = False
| yalpul/CENG242 | H99/61-69/p63.hs | gpl-3.0 | 591 | 0 | 13 | 198 | 274 | 137 | 137 | 13 | 4 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Hledger.Web.Application (
withApp
,withDevelAppPort
)
where
import Data.Dynamic (Dynamic, toDyn)
import Network.Wai (Application)
import Network.Wai.Middleware.Debug (debugHandle)
import Yesod.Core hiding (AppConfig,loadConfig,appPort)
import Yesod.Logger (makeLogger, flushLogger, Logger, logLazyText, logString)
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.HashDB
import Database.Persist.Sqlite
import Hledger.Web.Foundation
import Hledger.Web.Handlers
import Hledger.Web.Options
import Hledger.Web.Settings
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in App.hs. Please see
-- the comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
withApp :: AppConfig -> Logger -> WebOpts -> (Application -> IO a) -> IO a
withApp conf logger opts f = withSqlitePool "test.db3" 10 $ \pool -> do
#ifdef PRODUCTION
putStrLn $ "Production mode, using embedded web files"
let s = $(embed staticDir)
#else
putStrLn $ "Not in production mode, using web files from " ++ staticDir ++ "/"
s <- staticDevel staticDir
#endif
runSqlPool (runMigration migrateUsers) pool
--runSqlPool (insert $ User "chris" "67c3decf6d75f4000a2dcbb62da6e24f9c4ca674" "NACL") pool
let a = App {settings=conf
,getLogger=logger
,getStatic=s
,appOpts=opts
,appConn=pool
}
toWaiApp a >>= f
-- for yesod devel
withDevelAppPort :: Dynamic
withDevelAppPort =
toDyn go
where
go :: ((Int, Application) -> IO ()) -> IO ()
go f = do
conf <- loadConfig Development
let port = appPort conf
logger <- makeLogger
logString logger $ "Devel application launched with default options, listening on port " ++ show port
withApp conf logger defwebopts $ \app -> f (port, debugHandle (logHandle logger) app)
flushLogger logger
where
logHandle logger msg = logLazyText logger msg >> flushLogger logger
| Lainepress/hledger | hledger-web/Hledger/Web/Application.hs | gpl-3.0 | 2,494 | 0 | 15 | 543 | 480 | 263 | 217 | 45 | 1 |
{-# LANGUAGE QuasiQuotes #-}
-- | Attoparsec example
-- Data is created from a pdf with : pdftotex -layout
-- After reading the data, we count identical entries
-- Structure :
-- ID NAME PLACE BOSS
-- ID = a letter followed by 3 digits
-- name = a set of characters up to a place
-- place = search into a list of places *and* 2 spaces after (importsant !)
-- boss = everything else
module JobParser where
import Control.Applicative
import Data.Either
import Data.Attoparsec.Text
import Data.Attoparsec.Combinator
import qualified Data.Text.IO as TIO
import qualified Data.Text as T
import Data.List as L
import Text.Printf
import Text.RawString.QQ
data Job = Job {id :: T.Text
, unit :: T.Text
, place :: T.Text
, boss :: T.Text}
deriving (Show)
instance Eq Job where
(==) (Job _ u _ _) (Job _ u' _ _) = u == u'
instance Ord Job where
(compare) (Job _ u _ _) (Job _ u' _ _) = compare u u'
countIdentical :: [Job] -> [(Job, Int)]
countIdentical x = map (\l -> (head l, length l)) (L.group . L.sort $ x)
-- Print a Job with padding and the number of occurences
-- Compatible with uniq output
printEntryCSV :: (Job, Int) -> T.Text
printEntryCSV (x, y) = T.pack $ printf "%7d %s" y (unit x)
-- Print a Job with padding and the number of occurences
-- Compatible for latex
printEntryLATEX :: (Job, Int) -> T.Text
printEntryLATEX (x, y) = T.pack $ printf "%s & %7d\\\\" (unit x) y
parseID :: Parser T.Text
parseID = do
id1 <- letter
id2 <- decimal
return $ T.concat [T.singleton id1, T.pack . show $ id2]
listPlaces = ["C.C.E.G."
, "C.H."
, "C.H.G."
, "C.H.R."
, "C.H.S."
, "C.P.N."
, "Cabinet médical"
, "Cabinet médfical" -- yes....
, "cabinet médical"
, "Cabinetmédical"
, "cabinetmédical"
, "Jury" -- Hack : pole 6 do not have a place
, "Bel Air"
, "H.B."
, "H.C."
, "H.E."
, "H.M.M."
, "I.C.L."
, "I.R.R."
, "Mat"
, "S.J."
, "St-Charles"]
-- Always two spaces after the place (otherwise the name can co)
isPlace = choice $ map string l
where l = map (\x -> T.append (T.pack x) (T.pack " ")) listPlaces
parseJob :: Parser Job
parseJob = do
id <- parseID
space *> many1 space
-- spaces are important
s <- manyTill anyChar (lookAhead isPlace)
let s' = T.strip . T.pack $ s
place <- isPlace
space *> many1 space
boss <- many1 (letter <|> char '?')
return $ Job id s' place (T.strip . T.pack $ boss)
-- If a line is not a job (i.e reading a Job fails), this allows us to continue
skipTill :: (Alternative f) => f a -> f b -> f b
skipTill skippedAction nextAction =
nextAction
<|> skippedAction *> skipTill skippedAction nextAction
skipLine = takeTill isEndOfLine <* endOfLine
-- We cannot read line by line as some Jobs are multi-line.....
parseAllJobs = many (skipLine `skipTill` parseJob)
getAllJobs :: T.Text -> [Job]
getAllJobs = fromRight [] . (parseOnly parseAllJobs)
parseData f = do
file <- TIO.readFile f
-- We cannot read line by line as some Jobs are multi-line.....
return $ countIdentical $ fromRight [] $ parseOnly parseAllJobs file
printCSV f all = do
-- Count identical entries
let output = map printEntryCSV all
TIO.writeFile f $ T.unlines output
header :: String
header = [r|\documentclass{article}
\usepackage[margin=5pt, left=15pt]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xtab}
% \usepackage{pgfplotstable,filecontents}
\begin{document}
\twocolumn
\begin{xtabular}{p{8cm}c}
\shrinkheight{-2in} % hack for less page|]
footer :: String
footer = [r| \end{xtabular}
\end{document}|]
printLATEX f all = do
-- Count identical entries
let output = map printEntryLATEX all
TIO.writeFile f $ T.unlines $ (T.pack header) : output ++ [T.pack footer]
| alexDarcy/shelly-examples | stages/src/JobParser.hs | gpl-3.0 | 3,968 | 1 | 13 | 986 | 1,024 | 554 | 470 | 86 | 1 |
module TypeBug9 where
infixl 6 <*!>
infixl 7 <$!>
type Parser symbol result = [symbol] -> [(result,[symbol])]
(<*!>) :: Parser s (a -> b) -> Parser s a -> Parser s b
(<$!>) :: (a -> b) -> Parser s a -> Parser s b
(<*!>) = undefined
(<$!>) = undefined
many :: Parser s a -> Parser s [a]
many = undefined
chainr :: Parser s a -> Parser s (a -> a -> a) -> Parser s a
chainr pe po = h <$!> many (j <$!> pe <*!> po) <*!> pe
where j x op = (x `op`)
h fs x = foldr ($) fs x
| Helium4Haskell/helium | test/typeerrors/Examples/TypeBug9.hs | gpl-3.0 | 492 | 0 | 10 | 134 | 259 | 143 | 116 | 14 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.