code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan, writeList2Chan)
import Control.Exception (catch, IOException)
import Control.Monad (forever, forM_, when)
--import Debug.Trace (traceIO)
import Network.HTTP.Client (BodyReader, defaultManagerSettings, HttpException, Manager, managerConnCount, managerResponseTimeout, parseUrl, Request, Response, responseBody, withManager, withResponse)
import qualified Data.ByteString.Lazy as ByteStringLazy
import qualified Data.ByteString as ByteStringStrict
import System.IO (withFile, IOMode(WriteMode))
import Text.Printf (printf)
-------------------------------------------------------------------
-- Constants
-------------------------------------------------------------------
siteUrl :: String
siteUrl = "http://museudaimigracao.org.br/acervodigital/livros.php?pesq=1&nome=&sobrenome=&chegada=&vapor=&nacionalidade=&pagina="
start :: Int
start = 1
total :: Int
total = 132028
allRequestNumbers :: [Int]
allRequestNumbers = [start .. total]
--allRequestNumbers = [ 001708
-- , 001709
-- , 001710
-- , 001711
-- , 026100
-- , 026101
-- , 026102
-- , 026103
-- , 032079
-- , 032080
-- , 032081
-- , 044379
-- , 044380
-- , 044381
-- , 047975
-- , 047976
-- , 047977
-- , 050686
-- , 050687
-- , 050688
-- , 050689
-- , 050690
-- , 059745
-- , 061557
-- , 071152
-- , 071153
-- , 071154
-- , 086170
-- , 086172
-- , 086177
-- , 086178
-- , 086181
-- , 086182
-- , 086183
-- , 086184
-- , 086185
-- , 086186
-- , 086188
-- , 086190
-- , 086191
-- , 086193
-- , 086194
-- , 086195
-- , 086196
-- , 086197
-- , 086198
-- , 086199
-- , 086200
-- , 086202
-- , 086203
-- , 086205
-- , 086216
-- , 086217
-- , 086219
-- , 086224
-- , 086226
-- , 086227
-- , 086229
-- , 086232
-- , 086236
-- , 086237
-- , 086238
-- , 086239
-- , 086240
-- , 086241
-- , 086242
-- , 086243
-- , 086247
-- , 095215
-- , 100764
-- , 105081
-- , 105082
-- , 105083
-- , 105084
-- , 105273
-- , 106132
-- , 106133
-- , 107832
-- , 107833
-- , 107834
-- , 107835
-- , 107836
-- , 107837
-- , 107838
-- , 107842
-- , 107843
-- , 109297
-- , 118011
-- , 118012
-- , 118013
-- , 118014 ]
printStatusEvery :: Int
printStatusEvery = 500
downloadLimitBytes :: Int
downloadLimitBytes = 50000
concurrentConnectionCount :: Int
concurrentConnectionCount = 3
responseTimeoutSeconds :: Int
responseTimeoutSeconds = 120
threadSleepSeconds :: Int
threadSleepSeconds = 10
-------------------------------------------------------------------
-- Helper functions
-------------------------------------------------------------------
outFilePath :: Int -> FilePath
outFilePath = printf "output/site/%06d.html"
errFilePath :: Int -> FilePath
errFilePath = printf "output/err/%06d.html"
request :: Int -> IO Request
request pageNum = parseUrl $ siteUrl ++ show pageNum
brReadSome :: BodyReader -> Int -> IO ByteStringLazy.ByteString
brReadSome brRead =
loop id
where
loop front remainder
| remainder <= 0 = return $ ByteStringLazy.fromChunks $ front []
| otherwise = do
bs <- brRead
if ByteStringStrict.null bs
then return $ ByteStringLazy.fromChunks $ front []
else loop (front . (bs:)) (remainder - ByteStringStrict.length bs)
threadPoolIO :: Int -> (a -> IO ()) -> IO (Chan a, Chan ())
threadPoolIO nr mutator = do
inputChan <- newChan
outputChan <- newChan
forM_ [1..nr] $
\_ -> forkIO (forever $ do
threadDelay $ threadSleepSeconds * 1000000
i <- readChan inputChan
o <- mutator i
writeChan outputChan o)
return (inputChan, outputChan)
-------------------------------------------------------------------
-- file downloading functions
-------------------------------------------------------------------
doResponse :: Int -> Response BodyReader -> IO ()
doResponse reqNum response =
catch (doResponse' >> printStatus) errHandler
where
printStatus :: IO ()
printStatus = when (reqNum `mod` printStatusEvery == 0) $ print reqNum
doResponse' :: IO ()
doResponse' = withFile (outFilePath reqNum) WriteMode $ \fileHandle -> do
let lazybody = responseBody response
body <- brReadSome lazybody downloadLimitBytes
ByteStringLazy.hPut fileHandle body
ByteStringLazy.hPut fileHandle "\n"
errHandler :: IOException -> IO ()
errHandler err = writeFile (errFilePath reqNum) $ show err ++ "\n"
doRequest :: (Manager, Int) -> IO ()
doRequest (manager, reqNum) = do
req <- request reqNum
catch (withResponse req manager $ doResponse reqNum)
(\err -> writeFile (errFilePath reqNum) $ show (err::HttpException) ++ "\n")
doRequestsThreadPool :: Manager -> IO ()
doRequestsThreadPool manager = do
(inputChan, outputChan) <- threadPoolIO concurrentConnectionCount doRequest
_ <- writeList2Chan inputChan $ zip (repeat manager) allRequestNumbers
mapM_ (\_ -> readChan outputChan) allRequestNumbers
-------------------------------------------------------------------
-- main
-------------------------------------------------------------------
main :: IO ()
main = do
let managerSettings = defaultManagerSettings
{ managerConnCount = concurrentConnectionCount
, managerResponseTimeout = Just $ responseTimeoutSeconds * 1000000
}
withManager managerSettings doRequestsThreadPool
| cdepillabout/brazile-web-scraper | src/Search-Results-Main.hs | gpl-2.0 | 7,214 | 4 | 15 | 2,767 | 1,220 | 664 | 556 | 84 | 2 |
-- FINISHED
groupCheck :: String -> Bool
groupCheck input =
let subs = iterate removeSubformula input in
stableTail subs == ""
removeSubformula :: String -> String
removeSubformula = helper ""
where
helper acc str =
case str of
"" -> acc
'(' : ')' : rest -> acc ++ rest
'[' : ']' : rest -> acc ++ rest
'{' : '}' : rest -> acc ++ rest
x : rest -> helper (acc ++ [x]) rest
-- | Unsafe.
stableTail :: Eq a => [a] -> a
stableTail (x : y : ys) =
if x == y
then x
else stableTail (y : ys)
main :: IO ()
main = print (test groupCheck groupCheckTests)
test :: Eq b => (a -> b) -> [(a, b)] -> [Bool]
test f = map (\(x, y) -> f x == y)
groupCheckTests :: [(String, Bool)]
groupCheckTests =
[ ("{()[]}", True)
, ("{([)]}", False)
, ("[()[]]", True)
]
| friedbrice/codewars | haskell/GroupCheck.hs | gpl-3.0 | 822 | 0 | 11 | 238 | 389 | 200 | 189 | 27 | 5 |
import Control.Monad
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.UTF8 as BUL
import Data.List
import Data.Maybe
import Hellnet
import Hellnet.Crypto
import Hellnet.Files
import Hellnet.FileTree
import Hellnet.Meta
import Hellnet.Network
import Hellnet.Storage
import Hellnet.URI
import Hellnet.Utils
import Safe
import System.Console.GetOpt
import System.Environment (getArgs)
import System.FilePath
import System.FilePath.Glob as Glob
import System.Directory
import System.Time
import qualified System.Directory.Tree as Tree
import Text.HJson as JSON
import Text.JSON.JPath
import Text.Printf
data Opts = Opts {
encrypt :: Bool,
encKey :: Maybe Key,
updateMeta :: Bool,
encryptMeta :: Bool,
metaEncKey :: Maybe Key,
verbose :: Bool,
dryRun :: Bool,
indexChunks :: Bool,
forceInsert :: Bool
}
options :: [OptDescr (Opts -> Opts)]
options = [
Option ['m'] ["meta-encryption"]
(OptArg (\s o -> o {encryptMeta = True, metaEncKey = maybe (Nothing) (Just . decrockford) s}) "key") "Use encryption on meta (optionally (if encrypting) with specified key)",
Option ['e'] ["encrypt"]
(OptArg (\s o -> o {encrypt = True, encKey = maybe (Nothing) (Just . decrockford) s}) "key") "Encrypt content (optionally with specified key)",
Option ['u'] ["update-meta"]
(NoArg (\o -> o {updateMeta = True})) "Automatically update meta before retrieval",
Option ['v'] ["verbose"]
(NoArg (\o -> o {verbose = True})) "Be verbose",
Option ['d'] ["dry-run"]
(NoArg (\o -> o {dryRun = True})) "Do not actually touch anything",
Option ['i'] ["index"]
(NoArg (\o -> o {indexChunks = True})) "Index files instead of inserting",
Option ['f'] ["forec"]
(NoArg (\o -> o {forceInsert = True})) "Force updating files"
]
defaultOptions = Opts {
encrypt = False,
encKey = Nothing,
updateMeta = False,
encryptMeta = False,
metaEncKey = Nothing,
verbose = False,
dryRun = False,
indexChunks = False,
forceInsert = False
}
convertTree :: [FilePath] -> Tree.DirTree a -> IO (Maybe FileTree)
convertTree fs d@(Tree.Dir{}) = do
let fs' = fs ++ [Tree.name d]
modTime <- getModificationTime $ joinPath (fs')
let TOD i _ = modTime
let treeToPair d = do
convM <- convertTree fs' d
return $ fmap (\conv -> (Tree.name d, conv)) convM
conts <- mapM (treeToPair) (Tree.contents d) >>= return . catMaybes
return $ Just $ Dir i $ Map.fromList conts
convertTree fs d@(Tree.File{}) = do
modTime <- getModificationTime $ joinPath (fs ++ [Tree.name d])
let TOD i _ = modTime
return $ Just $ File i ""
convertTree _ _ = return Nothing
pullTreeWalker ignores opts cpath (Dir rmtime rfiles) (Just (File _ _)) = do
printf "File %s exists, but it should be a directory; deleting\n" $ joinPath cpath
when (not $ dryRun opts) $ removeFile $ joinPath cpath
pullTreeWalker ignores opts cpath (Dir rmtime rfiles) Nothing
pullTreeWalker ignores opts cpath (Dir rmtime rfiles) (Just (Dir lmtime lfiles)) = do
when (verbose opts) $ printf "Traversing directory %s\n" $ joinPath cpath
mapM_ (\(name, tree) -> pullTreeWalker ignores opts (cpath ++ [name]) tree $ Map.lookup name lfiles) $ Map.toList rfiles
pullTreeWalker ignores opts cpath (Dir rmtime rfiles) Nothing = do
printf "Creating directory %s\n" $ joinPath cpath
when (not $ dryRun opts) $ createDirectoryIfMissing True $ joinPath cpath
mapM_ (\(name, tree) -> pullTreeWalker ignores opts (cpath ++ [name]) tree Nothing) $ Map.toList rfiles
-- File cases
pullTreeWalker ignores opts cpath (File rmtime link) (Just (Dir lmtime lfiles)) = do
printf "Directory %s exists, but it should be a file instead; rm-r'ing\n" $ joinPath cpath
when (not $ dryRun opts) $ removeDirectoryRecursive $ joinPath cpath
pullTreeWalker ignores opts cpath (File rmtime link) Nothing
pullTreeWalker ignores opts cpath (File rmtime link) (Just (File lmtime llink)) = do
if rmtime == lmtime && not (forceInsert opts) then do
when (verbose opts) $ printf "File %s is as new as remote one; skipping\n" $ joinPath cpath
return ()
else do
when (not $ dryRun opts) $ removeFile $ joinPath cpath
pullTreeWalker ignores opts cpath (File rmtime link) Nothing
pullTreeWalker ignores opts cpath (File rmtime link) Nothing = do
printf "Updating file %s\n" $ joinPath cpath
mBsl <- findURI $ fromMaybe (error "bad link") $ parseHellnetURI link
case mBsl of
Nothing -> error ("URI " ++ link ++ " not found!")
Just conts -> when (not $ dryRun opts) $ BSL.writeFile (joinPath cpath) conts
pushTreeWalker ignores opts cpath (Dir lmtime lfiles) (Just (File _ _)) = do
printf "File %s exists, but it should be a directory; deleting\n" $ joinPath cpath
removeFile $ joinPath cpath
pushTreeWalker ignores opts cpath (Dir lmtime lfiles) Nothing
pushTreeWalker ignores opts cpath (Dir lmtime lfiles) (Just (Dir rmtime rfiles)) = do
when (verbose opts) $ printf "Traversing directory %s\n" $ joinPath cpath
lfiles' <- mapM (\(name, tree) -> do
let path' = cpath ++ [name]
let ignoredpath = zipWith ($) (map (Glob.match) ignores) $ repeat $ joinPath $ tail path'
let ignoredfile = zipWith ($) (map (Glob.match) ignores) $ repeat name
if or (ignoredpath ++ ignoredfile) then do
when (verbose opts) $ printf "Omitting entry %s\n" $ joinPath path'
return Nothing
else do
tree' <- pushTreeWalker ignores opts (path') tree $ Map.lookup name rfiles
return $ Just (name, tree')
) $ Map.toList lfiles
return $ Dir lmtime $ Map.fromList $ catMaybes lfiles'
pushTreeWalker ignores opts cpath (Dir lmtime lfiles) Nothing = do
printf "Creating directory %s\n" $ joinPath cpath
lfiles' <- mapM (\(name, tree) -> do
let path' = cpath ++ [name]
let ignoredpath = zipWith ($) (map (Glob.match) ignores) $ repeat $ joinPath $ tail path'
let ignoredfile = zipWith ($) (map (Glob.match) ignores) $ repeat name
if or (ignoredpath ++ ignoredfile) then do
when (verbose opts) $ printf "Omitting entry %s\n" $ joinPath path'
return Nothing
else do
tree' <- pushTreeWalker ignores opts (cpath ++ [name]) tree Nothing
return $ Just (name, tree')
) $ Map.toList $ lfiles
return $ Dir lmtime $ Map.fromList $ catMaybes lfiles'
-- File cases
pushTreeWalker ignores opts cpath (File lmtime link) (Just (File rmtime rlink)) = do
if rmtime == lmtime && not (forceInsert opts) then do
when (verbose opts) $ printf "File %s is as new as local one; skipping\n" $ joinPath cpath
return $ File rmtime rlink
else do
pushTreeWalker ignores opts cpath (File lmtime link) Nothing
pushTreeWalker ignores opts cpath (File lmtime _) _ = do
printf "Updating file %s\n" $ joinPath cpath
url <- if indexChunks opts then
indexData Nothing (joinPath cpath)
else
insertData Nothing =<< BSL.readFile (joinPath cpath)
return (File lmtime $ show url)
getIgnores dir = do
let fpath = joinPath [dir, ".helldirignore"]
exists <- doesFileExist fpath
if exists then do
cont <- readFile fpath
return $ map (Glob.compile) $ lines cont
else
return []
main = do
argz <- getArgs
let (optz, args, errs) = getOpt Permute options argz
let preOpts = processOptions defaultOptions optz
let (args', opts) = case (length args > 2, parseHellnetURI (args !! 2)) of
(True, Just (MetaURI keyid mnameM mpath encKey _)) -> do
let
namepath = case (mnameM, mpath) of
(Just mname, []) -> [mname]
(Just mname, mp) -> [mname, mp]
otherwise -> [];
opts' = case encKey of
Just k -> preOpts {encryptMeta = True, metaEncKey = Just k}
otherwise -> preOpts
in (take 2 args ++ crockford keyid : namepath, opts')
otherwise -> (args, preOpts)
theKey <- if encrypt opts then
(return . Just) =<< (maybe (genKey) (return) $ encKey opts)
else
return Nothing
theMetaKey <- if encryptMeta opts then
(return . Just) =<< (maybe (genKey) (return) $ metaEncKey opts)
else
return Nothing
let ensureSuppliedMetaKey = when (isNothing (metaEncKey opts) && encryptMeta opts) (fail "You can't decrypt with random key!")
let announceMetaKey = when (isNothing (metaEncKey opts) && encryptMeta opts) $ printf "Your meta key will be %s" (crockford $ fromMaybe (error "Meta key is going to be used but wasn't generated") theMetaKey)
case args' of
["pull", dirName, metaKey, mName] -> do
keyid <- resolveKeyName metaKey
ignores <- getIgnores dirName
when (updateMeta opts) (fetchMeta keyid mName >> return ())
ensureSuppliedMetaKey
putStrLn "Synchronizing local tree with remote"
contM <- findMetaContentByName theMetaKey keyid mName ""
let remoteTree = fromMaybe (error "Couldn't parse tree") $ fromJson $ fromMaybe (error "Couldn't get content") $ headMay $ fromMaybe (error "Couldn't get content") $ contM
putStrLn "Reading directory tree..."
dirTree <- Tree.readDirectoryWith (const $ return ()) dirName
currentTreeM <- convertTree [dirName] $ Tree.free dirTree
let currentTree = fromMaybe (error "Couldn't traverse local tree") currentTreeM
currentTree' <- (pullTreeWalker ignores opts [dirName] remoteTree $ Just currentTree)
putStrLn "All done"
announceMetaKey
["push", dirName, metaKey, mName] -> do
keyid <- resolveKeyName metaKey
when (updateMeta opts) (fetchMeta keyid mName >> return ())
ignores <- getIgnores dirName
putStrLn "Synchronizing remote tree with local"
metaM <- findMeta keyid mName
when (isJust metaM) (ensureSuppliedMetaKey)
when (isNothing metaM) $ putStrLn "Warning: Meta not found. Creating new one."
let meta = fromMaybe (emptyMeta {keyID = keyid, metaName = mName}) metaM
contM <- findMetaContent theMetaKey meta ""
let remoteTree = case contM of
Nothing -> Nothing
Just [] -> Nothing
Just (js:_) -> fromJson js
putStrLn "Reading directory tree..."
dirTree <- Tree.readDirectoryWith (const $ return ()) dirName
currentTreeM <- convertTree [] $ Tree.free dirTree
let currentTree = fromMaybe (error "Couldn't traverse local tree") currentTreeM
putStrLn "Updating index..."
remoteTree' <- pushTreeWalker ignores opts [dirName] currentTree remoteTree
when (not $ dryRun opts) $ do
putStrLn "Updating meta..."
link' <- insertData theKey $ maybe (id) (encryptSym) theMetaKey $ BUL.fromString $ JSON.toString $ toJson remoteTree'
newMetaM <- regenMeta $ meta {contentURI = link'}
case newMetaM of
Nothing -> error "Failed to sign meta"
Just newMeta -> do
storeMeta newMeta
putStrLn "Success"
announceMetaKey
otherwise -> do
let usageStrings = [
"push <path> <key id> <meta name> -- Update meta to match file structure in <path>",
"pull <path> <key id> <meta name> -- Update file structure to match one in meta"
] in error $ usageInfo (intercalate "\n" $ map ("hell-dir "++) usageStrings) options ++ concat errs | Voker57/hellnet | hell-dir.hs | gpl-3.0 | 11,052 | 612 | 10 | 2,307 | 3,200 | 1,898 | 1,302 | 231 | 12 |
{-# LANGUAGE CPP #-}
-- |
-- Module : Commands.Install
-- Copyright : (C) 2012-2020 Jens Petersen
--
-- Maintainer : Jens Petersen <[email protected]>
-- Stability : alpha
-- Portability : portable
--
-- Explanation: installs rpms of package and dependencies
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
module Commands.Install (
install
) where
import Commands.RpmBuild (rpmBuild, rpmBuild_)
import Dependencies (notInstalled, pkgInstallMissing)
import FileUtils (withTempDirectory)
import PackageUtils (checkForSpecFile, rpmInstall, RpmStage (..))
import SysCmd (rpmEval)
import Types
import SimpleCabal(PackageName)
import SimpleCmd (cmd_, (+-+))
import SimpleCmd.Rpm (rpmspec)
#if (defined(MIN_VERSION_base) && MIN_VERSION_base(4,8,0))
#else
--import Control.Applicative ((<$>))
#endif
import Control.Monad (unless, when)
import Distribution.Text (display)
import System.FilePath ((</>))
install :: Flags -> PackageType -> Bool -> Maybe PackageVersionSpecifier -> IO ()
install flags pkgtype subpackage mpvs = do
stillMissing <- pkgInstallMissing flags mpvs
unless (null stillMissing) $ do
putStrLn $ "Missing:" +-+ unwords (map display stillMissing)
mapM_ cblrpmInstallMissing stillMissing
mspec <- checkForSpecFile (pvsPackage =<< mpvs)
case mspec of
Nothing ->
withTempDirectory $ \ _ -> do
spec <- rpmBuild Binary False flags pkgtype subpackage mpvs
rpmdir <- rpmEval "%{_rpmdir}"
rpmspec [] (fmap (</> "%{arch}/%{name}-%{version}-%{release}.%{arch}.rpm") rpmdir) spec >>= rpmInstall False
Just spec -> do
rpmBuild_ Binary False flags pkgtype subpackage mpvs
rpmdir <- rpmEval "%{_rpmdir}"
rpmspec [] (fmap (</> "%{arch}/%{name}-%{version}-%{release}.%{arch}.rpm") rpmdir) spec >>= rpmInstall False
cblrpmInstallMissing :: PackageName -> IO ()
cblrpmInstallMissing pkg = do
noPkg <- notInstalled $ RpmHsLib Prof pkg
when noPkg $ do
let dep = display pkg
withTempDirectory $ \ _ -> do
putStrLn $ "Running cabal-rpm install" +-+ dep
cmd_ "cabal-rpm" ["install", dep]
| juhp/cabal-rpm | src/Commands/Install.hs | gpl-3.0 | 2,310 | 0 | 18 | 412 | 519 | 273 | 246 | 40 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-- | This module exports definitions for some most used classes and methods from standard Java java.io package.
module Java2js.Java.IO where
import Data.String
import Java2js.JVM.Common () -- import instances only
import Java2js.JVM.ClassFile
import qualified Java2js.Java.Lang
-- | java.io.PrintStream class name
printStream :: IsString s => s
printStream = "java/io/PrintStream"
-- | java.io.PrintStream class as field type
printStreamClass :: FieldType
printStreamClass = ObjectType printStream
println :: NameType (Method Direct)
println = NameType "println" $ MethodSignature [Java2js.Java.Lang.stringClass] ReturnsVoid
out :: NameType (Field Direct)
out = NameType "out" printStreamClass
printf :: NameType (Method Direct)
printf =
NameType "printf" $ MethodSignature [Java2js.Java.Lang.stringClass,
Array Nothing Java2js.Java.Lang.objectClass] (Returns printStreamClass)
| ledyba/java.js | lib/Java2js/Java/IO.hs | gpl-3.0 | 964 | 0 | 9 | 158 | 187 | 106 | 81 | 18 | 1 |
main = putStr "Hello, World!\n"
| jmahler/shootout | hello/haskell/hello.hs | gpl-3.0 | 33 | 1 | 4 | 6 | 12 | 4 | 8 | 1 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
-- Module : Network.AWS.EC2
-- Copyright : (c) 2013 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
-- | Amazon Elastic Compute Cloud provides resizable computing
-- capacity in the Amazon Web Services cloud.
module Network.AWS.EC2
(
-- * Actions
-- ** AllocateAddress
AllocateAddress (..)
, AllocateAddressResponse (..)
-- ** AssignPrivateIpAddresses
, AssignPrivateIpAddresses (..)
, AssignPrivateIpAddressesResponse (..)
-- ** AssociateAddress
, AssociateAddress (..)
, AssociateAddressResponse (..)
-- ** AssociateDhcpOptions
, AssociateDhcpOptions (..)
, AssociateDhcpOptionsResponse (..)
-- ** AssociateRouteTable
, AssociateRouteTable (..)
, AssociateRouteTableResponse (..)
-- ** AttachInternetGateway
, AttachInternetGateway (..)
, AttachInternetGatewayResponse (..)
-- ** AttachNetworkInterface
, AttachNetworkInterface (..)
, AttachNetworkInterfaceResponse (..)
-- ** AttachVolume
, AttachVolume (..)
, AttachVolumeResponse (..)
-- ** AttachVpnGateway
, AttachVpnGateway (..)
, AttachVpnGatewayResponse (..)
-- ** AuthorizeSecurityGroupEgress
, AuthorizeSecurityGroupEgress (..)
, AuthorizeSecurityGroupEgressResponse (..)
-- ** AuthorizeSecurityGroupIngress
, AuthorizeSecurityGroupIngress (..)
, AuthorizeSecurityGroupIngressResponse (..)
-- ** BundleInstance
, BundleInstance (..)
, BundleInstanceResponse (..)
-- ** CancelBundleTask
, CancelBundleTask (..)
, CancelBundleTaskResponse (..)
-- ** CancelConversionTask
, CancelConversionTask (..)
, CancelConversionTaskResponse (..)
-- ** CancelExportTask
, CancelExportTask (..)
, CancelExportTaskResponse (..)
-- ** CancelReservedInstancesListing
, CancelReservedInstancesListing (..)
, CancelReservedInstancesListingResponse (..)
-- ** CancelSpotInstanceRequests
, CancelSpotInstanceRequests (..)
, CancelSpotInstanceRequestsResponse (..)
-- -- ** ConfirmProductInstance
-- , ConfirmProductInstance (..)
-- -- ** CopyImage
-- , CopyImage (..)
-- -- ** CopySnapshot
-- , CopySnapshot (..)
-- -- ** CreateCustomerGateway
-- , CreateCustomerGateway (..)
-- -- ** CreateDhcpOptions
-- , CreateDhcpOptions (..)
-- ** CreateImage
, CreateImage (..)
, CreateImageResponse (..)
-- -- ** CreateInstanceExportTask
-- , CreateInstanceExportTask (..)
-- -- ** CreateInternetGateway
-- , CreateInternetGateway (..)
-- ** CreateKeyPair
, CreateKeyPair (..)
, CreateKeyPairResponse (..)
-- -- ** CreateNetworkAcl
-- , CreateNetworkAcl (..)
-- -- ** CreateNetworkAclEntry
-- , CreateNetworkAclEntry (..)
-- -- ** CreateNetworkInterface
-- , CreateNetworkInterface (..)
-- -- ** CreatePlacementGroup
-- , CreatePlacementGroup (..)
-- -- ** CreateReservedInstancesListing
-- , CreateReservedInstancesListing (..)
-- -- ** CreateRoute
-- , CreateRoute (..)
-- -- ** CreateRouteTable
-- , CreateRouteTable (..)
-- ** CreateSecurityGroup
, CreateSecurityGroup (..)
, CreateSecurityGroupResponse (..)
-- -- ** CreateSnapshot
-- , CreateSnapshot (..)
-- -- ** CreateSpotDatafeedSubscription
-- , CreateSpotDatafeedSubscription (..)
-- -- ** CreateSubnet
-- , CreateSubnet (..)
-- ** CreateTags
, CreateTags (..)
, CreateTagsResponse (..)
-- -- ** CreateVolume
-- , CreateVolume (..)
-- -- ** CreateVpc
-- , CreateVpc (..)
-- -- ** CreateVpnConnection
-- , CreateVpnConnection (..)
-- -- ** CreateVpnConnectionRoute
-- , CreateVpnConnectionRoute (..)
-- -- ** CreateVpnGateway
-- , CreateVpnGateway (..)
-- -- ** DeleteCustomerGateway
-- , DeleteCustomerGateway (..)
-- -- ** DeleteDhcpOptions
-- , DeleteDhcpOptions (..)
-- -- ** DeleteInternetGateway
-- , DeleteInternetGateway (..)
-- -- ** DeleteKeyPair
-- , DeleteKeyPair (..)
-- -- ** DeleteNetworkAcl
-- , DeleteNetworkAcl (..)
-- -- ** DeleteNetworkAclEntry
-- , DeleteNetworkAclEntry (..)
-- -- ** DeleteNetworkInterface
-- , DeleteNetworkInterface (..)
-- -- ** DeletePlacementGroup
-- , DeletePlacementGroup (..)
-- -- ** DeleteRoute
-- , DeleteRoute (..)
-- -- ** DeleteRouteTable
-- , DeleteRouteTable (..)
-- ** DeleteSecurityGroup
, DeleteSecurityGroup (..)
, DeleteSecurityGroupResponse (..)
-- -- ** DeleteSnapshot
-- , DeleteSnapshot (..)
-- -- ** DeleteSpotDatafeedSubscription
-- , DeleteSpotDatafeedSubscription (..)
-- -- ** DeleteSubnet
-- , DeleteSubnet (..)
-- -- ** DeleteTags
-- , DeleteTags (..)
-- -- ** DeleteVolume
-- , DeleteVolume (..)
-- -- ** DeleteVpc
-- , DeleteVpc (..)
-- -- ** DeleteVpnConnection
-- , DeleteVpnConnection (..)
-- -- ** DeleteVpnConnectionRoute
-- , DeleteVpnConnectionRoute (..)
-- -- ** DeleteVpnGateway
-- , DeleteVpnGateway (..)
-- -- ** DeregisterImage
-- , DeregisterImage (..)
-- -- ** DescribeAccountAttributes
-- , DescribeAccountAttributes (..)
-- -- ** DescribeAddresses
-- , DescribeAddresses (..)
-- ** DescribeAvailabilityZones
, DescribeAvailabilityZones (..)
, DescribeAvailabilityZonesResponse (..)
-- -- ** DescribeBundleTasks
-- , DescribeBundleTasks (..)
-- -- ** DescribeConversionTasks
-- , DescribeConversionTasks (..)
-- -- ** DescribeCustomerGateways
-- , DescribeCustomerGateways (..)
-- -- ** DescribeDhcpOptions
-- , DescribeDhcpOptions (..)
-- -- ** DescribeExportTasks
-- , DescribeExportTasks (..)
-- -- ** DescribeImageAttribute
-- , DescribeImageAttribute (..)
-- ** DescribeImages
, DescribeImages (..)
, DescribeImagesResponse (..)
-- -- ** DescribeInstanceAttribute
-- , DescribeInstanceAttribute (..)
-- ** DescribeInstances
, DescribeInstances (..)
, DescribeInstancesResponse (..)
-- -- ** DescribeInstanceStatus
-- , DescribeInstanceStatus (..)
-- -- ** DescribeInternetGateways
-- , DescribeInternetGateways (..)
-- ** DescribeKeyPairs
, DescribeKeyPairs (..)
, DescribeKeyPairsResponse (..)
-- -- ** DescribeNetworkAcls
-- , DescribeNetworkAcls (..)
-- -- ** DescribeNetworkInterfaceAttribute
-- , DescribeNetworkInterfaceAttribute (..)
-- -- ** DescribeNetworkInterfaces
-- , DescribeNetworkInterfaces (..)
-- -- ** DescribePlacementGroups
-- , DescribePlacementGroups (..)
-- ** DescribeRegions
, DescribeRegions (..)
, DescribeRegionsResponse (..)
-- -- ** DescribeReservedInstances
-- , DescribeReservedInstances (..)
-- -- ** DescribeReservedInstancesListings
-- , DescribeReservedInstancesListings (..)
-- -- ** DescribeReservedInstancesOfferings
-- , DescribeReservedInstancesOfferings (..)
-- -- ** DescribeRouteTables
-- , DescribeRouteTables (..)
-- ** DescribeSecurityGroups
, DescribeSecurityGroups (..)
, DescribeSecurityGroupsResponse (..)
-- -- ** DescribeSnapshotAttribute
-- , DescribeSnapshotAttribute (..)
-- -- ** DescribeSnapshots
-- , DescribeSnapshots (..)
-- -- ** DescribeSpotDatafeedSubscription
-- , DescribeSpotDatafeedSubscription (..)
-- -- ** DescribeSpotInstanceRequests
-- , DescribeSpotInstanceRequests (..)
-- -- ** DescribeSpotPriceHistory
-- , DescribeSpotPriceHistory (..)
-- -- ** DescribeSubnets
-- , DescribeSubnets (..)
-- ** DescribeTags
, DescribeTags (..)
, DescribeTagsResponse (..)
-- -- ** DescribeVolumeAttribute
-- , DescribeVolumeAttribute (..)
-- -- ** DescribeVolumes
-- , DescribeVolumes (..)
-- -- ** DescribeVolumeStatus
-- , DescribeVolumeStatus (..)
-- -- ** DescribeVpcAttribute
-- , DescribeVpcAttribute (..)
-- ** DescribeVpcs
, DescribeVpcs (..)
, DescribeVpcsResponse (..)
-- -- ** DescribeVpnConnections
-- , DescribeVpnConnections (..)
-- -- ** DescribeVpnGateways
-- , DescribeVpnGateways (..)
-- -- ** DetachInternetGateway
-- , DetachInternetGateway (..)
-- -- ** DetachNetworkInterface
-- , DetachNetworkInterface (..)
-- -- ** DetachVolume
-- , DetachVolume (..)
-- -- ** DetachVpnGateway
-- , DetachVpnGateway (..)
-- -- ** DisableVgwRoutePropagation
-- , DisableVgwRoutePropagation (..)
-- -- ** DisassociateAddress
-- , DisassociateAddress (..)
-- -- ** DisassociateRouteTable
-- , DisassociateRouteTable (..)
-- -- ** EnableVgwRoutePropagation
-- , EnableVgwRoutePropagation (..)
-- -- ** EnableVolumeIO
-- , EnableVolumeIO (..)
-- -- ** GetConsoleOutput
-- , GetConsoleOutput (..)
-- -- ** GetPasswordData
-- , GetPasswordData (..)
-- -- ** ImportInstance
-- , ImportInstance (..)
-- -- ** ImportKeyPair
-- , ImportKeyPair (..)
-- -- ** ImportVolume
-- , ImportVolume (..)
-- -- ** ModifyImageAttribute
-- , ModifyImageAttribute (..)
-- -- ** ModifyInstanceAttribute
-- , ModifyInstanceAttribute (..)
-- -- ** ModifyNetworkInterfaceAttribute
-- , ModifyNetworkInterfaceAttribute (..)
-- -- ** ModifySnapshotAttribute
-- , ModifySnapshotAttribute (..)
-- -- ** ModifyVolumeAttribute
-- , ModifyVolumeAttribute (..)
-- -- ** ModifyVpcAttribute
-- , ModifyVpcAttribute (..)
-- -- ** MonitorInstances
-- , MonitorInstances (..)
-- -- ** PurchaseReservedInstancesOffering
-- , PurchaseReservedInstancesOffering (..)
-- -- ** RebootInstances
-- , RebootInstances (..)
-- -- ** RegisterImage
-- , RegisterImage (..)
-- -- ** ReleaseAddress
-- , ReleaseAddress (..)
-- -- ** ReplaceNetworkAclAssociation
-- , ReplaceNetworkAclAssociation (..)
-- -- ** ReplaceNetworkAclEntry
-- , ReplaceNetworkAclEntry (..)
-- -- ** ReplaceRoute
-- , ReplaceRoute (..)
-- -- ** ReplaceRouteTableAssociation
-- , ReplaceRouteTableAssociation (..)
-- -- ** ReportInstanceStatus
-- , ReportInstanceStatus (..)
-- -- ** RequestSpotInstances
-- , RequestSpotInstances (..)
-- -- ** ResetImageAttribute
-- , ResetImageAttribute (..)
-- -- ** ResetInstanceAttribute
-- , ResetInstanceAttribute (..)
-- -- ** ResetNetworkInterfaceAttribute
-- , ResetNetworkInterfaceAttribute (..)
-- -- ** ResetSnapshotAttribute
-- , ResetSnapshotAttribute (..)
-- ** RevokeSecurityGroupEgress
, RevokeSecurityGroupEgress (..)
, RevokeSecurityGroupEgressResponse (..)
-- ** RevokeSecurityGroupIngress
, RevokeSecurityGroupIngress (..)
, RevokeSecurityGroupIngressResponse (..)
-- ** RunInstances
, RunInstances (..)
, RunInstancesResponse (..)
-- -- ** StartInstances
-- , StartInstances (..)
-- , StartInstancesResponse (..)
-- -- ** StopInstances
-- , StopInstances (..)
-- , StopInstancesResponse (..)
-- ** TerminateInstances
, TerminateInstances (..)
, TerminateInstancesResponse (..)
-- -- ** UnassignPrivateIpAddresses
-- , UnassignPrivateIpAddresses (..)
-- -- ** UnmonitorInstances
-- , UnmonitorInstances (..)
-- * Data Types
, module Network.AWS.EC2.Types
-- * Common
, module Network.AWS
) where
import Data.Text (Text)
import Data.Time
import Network.AWS
import Network.AWS.EC2.Types
import Network.AWS.Internal
import Network.HTTP.Types.Method
-- | Acquires an Elastic IP address.An Elastic IP address is for use either in
-- the EC2-Classic platform or in a VPC.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AllocateAddress.html>
data AllocateAddress = AllocateAddress
{ aaDomain :: Maybe AddressDomain
-- ^ Set to vpc to allocate the address for use with instances in a
-- VPC.
} deriving (Eq, Show, Generic)
instance IsQuery AllocateAddress
instance Rq AllocateAddress where
type Er AllocateAddress = EC2ErrorResponse
type Rs AllocateAddress = AllocateAddressResponse
request = query4 ec2 GET "AllocateAddress"
data AllocateAddressResponse = AllocateAddressResponse
{ aarRequestId :: !Text
-- ^ The ID of the request.
, aarPublicIp :: !Text
-- ^ The Elastic IP address.
, aarDomain :: !AddressDomain
-- ^ Indicates whether this Elastic IP address is for use with
-- instances in EC2-Classic (standaard) or instances in a VPC (vpc).
, aarAllocationId :: Maybe Text
-- ^ [EC2-VPC] The ID that AWS assigns to represent the allocation of
-- the Elastic IP address for use with a VPC.
} deriving (Eq, Show, Generic)
instance IsXML AllocateAddressResponse where
xmlPickler = ec2XML
-- | Assigns one or more secondary private IP addresses to the specified network
-- interface.
--
-- You can specify one or more specific secondary IP addresses, or
-- you can specify the number of secondary IP addresses to be automatically
-- assigned within the subnet's CIDR block range.
--
-- The number of secondary IP
-- addresses that you can assign to an instance varies by instance type.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssignPrivateIpAddresses.html>
data AssignPrivateIpAddresses = AssignPrivateIpAddresses
{ apiaNetworkInterfaceId :: !Text
-- ^ The ID of the network interface.
, apiaPrivateIpAddress :: [Text]
-- ^ The IP addresses to be assigned as a secondary private IP address
-- to the network interface.
, apiaSecondaryPrivateIpAddressCount :: Maybe Integer
-- ^ The number of secondary IP addresses to assign to the network
-- interface.
, apiaAllowReassignment :: Maybe Bool
-- ^ Specifies whether to allow an IP address that is already assigned
-- to another network interface or instance to be reassigned to the
-- specified network interface.
} deriving (Eq, Show, Generic)
instance IsQuery AssignPrivateIpAddresses
instance Rq AssignPrivateIpAddresses where
type Er AssignPrivateIpAddresses = EC2ErrorResponse
type Rs AssignPrivateIpAddresses = AssignPrivateIpAddressesResponse
request = query4 ec2 GET "AssignPrivateIpAddresses"
data AssignPrivateIpAddressesResponse = AssignPrivateIpAddressesResponse
{ apiaRequestId :: !Text
-- ^ The ID of the request.
, apiaReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an
-- error.
} deriving (Eq, Show, Generic)
instance IsXML AssignPrivateIpAddressesResponse where
xmlPickler = withRootNS ec2NS "AssignPrivateIpAddresses"
-- | Associates an Elastic IP address with an instance or a network interface.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateAddress.html>
data AssociateAddress = AssociateAddress
{ abPublicIp :: !Text
-- ^ The Elastic IP address.
, abInstanceId :: !Text
-- ^ The ID of the instance. The operation fails if you specify an
-- instance ID unless exactly one network interface is attached.
, abAllocationId :: Maybe Text
-- ^ [EC2-VPC] The allocation ID.
, abNetworkInterfaceId :: Maybe Text
-- ^ [EC2-VPC] The ID of the network interface.
, abPrivateIpAddress :: Maybe Text
-- ^ [EC2-VPC] The primary or secondary private IP address to
-- associate with the Elastic IP address. If no private IP address
-- is specified, the Elastic IP address is associated with the
-- primary private IP address.
, abAllowReassociation :: Maybe Bool
-- ^ [EC2-VPC] Allows an Elastic IP address that is already associated
-- with an instance or network interface to be re-associated with
-- the specified instance or network interface. Otherwise, the
-- operation fails.
} deriving (Eq, Show, Generic)
instance IsQuery AssociateAddress
instance Rq AssociateAddress where
type Er AssociateAddress = EC2ErrorResponse
type Rs AssociateAddress = AssociateAddressResponse
request = query4 ec2 GET "AssociateAddress"
data AssociateAddressResponse = AssociateAddressResponse
{ abrRequestId :: !Text
-- ^ The ID of the request.
, abrReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
, abrAssociationId :: Maybe Text
-- ^ [EC2-VPC] The ID that represents the association of the Elastic
-- IP address with an instance.
} deriving (Eq, Show, Generic)
instance IsXML AssociateAddressResponse where
xmlPickler = ec2XML
-- | Associates a set of DHCP options (that you've previously created) with the
-- specified VPC, or associates no DHCP options with the VPC.
--
-- After you associate the options with the VPC, any existing instances and all new
-- instances that you launch in that VPC use the options. You don't need to
-- restart or relaunch the instances. They automatically pick up the changes
-- within a few hours, depending on how frequently the instance renews its
-- DHCP lease. You can explicitly renew the lease using the operating system
-- on the instance.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateDhcpOptions.html>
data AssociateDhcpOptions = AssociateDhcpOptions
{ adoDhcpOptionsId :: !Text
-- ^ The ID of the DHCP options set, or default to associate no DHCP
-- options with the VPC.
, adoVpcId :: !Text
-- ^ The ID of the VPC.
} deriving (Eq, Show, Generic)
instance IsQuery AssociateDhcpOptions
instance Rq AssociateDhcpOptions where
type Er AssociateDhcpOptions = EC2ErrorResponse
type Rs AssociateDhcpOptions = AssociateDhcpOptionsResponse
request = query4 ec2 GET "AssociateDhcpOptions"
data AssociateDhcpOptionsResponse = AssociateDhcpOptionsResponse
{ adorRequestId :: !Text
-- ^ The ID of the request.
, adorReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an
-- error.
} deriving (Eq, Show, Generic)
instance IsXML AssociateDhcpOptionsResponse where
xmlPickler = ec2XML
-- | Associates a subnet with a route table.
--
-- The subnet and route table must be in the same VPC.
-- This association causes traffic originating from the
-- subnet to be routed according to the routes in the route table. The action
-- returns an association ID, which you need in order to disassociate the
-- route table from the subnet later. A route table can be associated with
-- multiple subnets.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateRouteTable.html>
data AssociateRouteTable = AssociateRouteTable
{ artRouteTableId :: !Text
-- ^ The ID of the route table.
, artSubnetId :: !Text
-- ^ The ID of the subnet.
} deriving (Eq, Show, Generic)
instance IsQuery AssociateRouteTable
instance Rq AssociateRouteTable where
type Er AssociateRouteTable = EC2ErrorResponse
type Rs AssociateRouteTable = AssociateRouteTableResponse
request = query4 ec2 GET "AssociateRouteTable"
data AssociateRouteTableResponse = AssociateRouteTableResponse
{ artrRequestId :: !Text
-- ^ The ID of the request.
, artrAssociationId :: !Text
-- ^ The route table association ID (needed to disassociate the route table).
} deriving (Eq, Show, Generic)
instance IsXML AssociateRouteTableResponse where
xmlPickler = ec2XML
-- | Attaches an Internet gateway to a VPC, enabling connectivity between the
-- Internet and the VPC.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachInternetGateway.html>
data AttachInternetGateway = AttachInternetGateway
{ aigInternetGatewayId :: !Text
-- ^ The ID of the Internet gateway.
, aigVpcId :: !Text
-- ^ The ID of the VPC.
} deriving (Eq, Show, Generic)
instance IsQuery AttachInternetGateway
instance Rq AttachInternetGateway where
type Er AttachInternetGateway = EC2ErrorResponse
type Rs AttachInternetGateway = AttachInternetGatewayResponse
request = query4 ec2 GET "AttachInternetGateway"
data AttachInternetGatewayResponse = AttachInternetGatewayResponse
{ aigrRequestId :: !Text
-- ^ The ID of the request.
, aigrReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
} deriving (Eq, Show, Generic)
instance IsXML AttachInternetGatewayResponse where
xmlPickler = ec2XML
-- | Attaches a network interface to an instance.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachNetworkInterface.html>
data AttachNetworkInterface = AttachNetworkInterface
{ aniNetworkInterfaceId :: !Text
-- ^ The ID of the network interface.
, aniInstanceId :: !Text
-- ^ The ID of the instance.
, aniDeviceIndex :: !Integer
-- ^ The index of the device for the network interface attachment.
} deriving (Eq, Show, Generic)
instance IsQuery AttachNetworkInterface
instance Rq AttachNetworkInterface where
type Er AttachNetworkInterface = EC2ErrorResponse
type Rs AttachNetworkInterface = AttachNetworkInterfaceResponse
request = query4 ec2 GET "AttachNetworkInterface"
data AttachNetworkInterfaceResponse = AttachNetworkInterfaceResponse
{ anirRequestId :: !Text
-- ^ The ID of the attachment request.
, anirAttachmentId :: !Text
-- ^ The ID of the network interface attachment.
} deriving (Eq, Show, Generic)
instance IsXML AttachNetworkInterfaceResponse where
xmlPickler = ec2XML
-- | Attaches an Amazon EBS volume to a running or stopped instance and exposes
-- it to the instance with the specified device name.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachVolume.html>
data AttachVolume = AttachVolume
{ avVolumeId :: !Text
-- ^ The ID of the Amazon EBS volume. The volume and instance must be
-- within the same Availability Zone.
, avInstanceId :: !Text
-- ^ The ID of the instance.
, avDevice :: !Text
-- ^ The device name to expose to the instance (for example, /dev/sdh
-- or xvdh).
} deriving (Eq, Show, Generic)
instance IsQuery AttachVolume
instance Rq AttachVolume where
type Er AttachVolume = EC2ErrorResponse
type Rs AttachVolume = AttachVolumeResponse
request = query4 ec2 GET "AttachVolume"
data AttachVolumeResponse = AttachVolumeResponse
{ avrRequestId :: !Text
-- ^ The ID of the request.
, avrVolumeId :: !Text
-- ^ The ID of the volume.
, avrInstanceId :: !Text
-- ^ The ID of the instance.
, avrDevice :: !Text
-- ^ The device name.
, avrStatus :: !VolumeStatus
-- ^ The attachment state of the volume.
, avrAttachTime :: !UTCTime
-- ^ The time stamp when the attachment initiated.
} deriving (Eq, Show, Generic)
instance IsXML AttachVolumeResponse where
xmlPickler = ec2XML
-- | Attaches a virtual private gateway to a VPC.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachVpnGateway.html>
data AttachVpnGateway = AttachVpnGateway
{ avgVpnGatewayId :: !Text
-- ^ The ID of the virtual private gateway.
, avgVpcId :: !Text
-- ^ The ID of the VPC.
} deriving (Eq, Show, Generic)
instance IsQuery AttachVpnGateway
instance Rq AttachVpnGateway where
type Er AttachVpnGateway = EC2ErrorResponse
type Rs AttachVpnGateway = AttachVpnGatewayResponse
request = query4 ec2 GET "AttachVpnGateway"
data AttachVpnGatewayResponse = AttachVpnGatewayResponse
{ avgrRequestId :: !Text
-- ^ The ID of the request.
, avgrAttachment :: !Attachment
-- ^ Information about the attachment.
} deriving (Eq, Show, Generic)
instance IsXML AttachVpnGatewayResponse where
xmlPickler = ec2XML
-- | Adds one or more egress rules to a security group for use with a VPC.
--
-- Specifically, this action permits instances to send traffic to one or more
-- destination CIDR IP address ranges, or to one or more destination security
-- groups for the same VPC.
--
-- This action doesn't apply to security groups for use in EC2-Classic.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AuthorizeSecurityGroupEgress.html>
data AuthorizeSecurityGroupEgress = AuthorizeSecurityGroupEgress
{ asgeGroupId :: !Text
-- ^ The ID of the security group to modify.
, asgeIpPermissions :: [IpPermissionType]
-- ^ The IP protocol name or number (see Protocol Numbers).
} deriving (Eq, Show, Generic)
instance IsQuery AuthorizeSecurityGroupEgress
instance Rq AuthorizeSecurityGroupEgress where
type Er AuthorizeSecurityGroupEgress = EC2ErrorResponse
type Rs AuthorizeSecurityGroupEgress = AuthorizeSecurityGroupEgressResponse
request = query4 ec2 GET "AuthorizeSecurityGroupEgress"
data AuthorizeSecurityGroupEgressResponse = AuthorizeSecurityGroupEgressResponse
{ asgerRequestId :: !Text
-- ^ The ID of the request.
, asgerReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an
-- error.
} deriving (Eq, Show, Generic)
instance IsXML AuthorizeSecurityGroupEgressResponse where
xmlPickler = ec2XML
-- | Adds one or more ingress rules to a security group.
--
-- Rule changes are propagated to instances within the security group as quickly as possible.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AuthorizeSecurityGroupIngress.html>
data AuthorizeSecurityGroupIngress = AuthorizeSecurityGroupIngress
{ asgiGroupId :: Maybe Text
-- ^ The ID of the security group to modify. The security group must
-- belong to your account.
, asgiGroupName :: Maybe Text
-- ^ The name of the security group to modify.
, asgiIpPermissions :: [IpPermissionType]
-- ^ The IP protocol name or number (see Protocol Numbers). For
-- EC2-Classic, security groups can have rules only for TCP, UDP,
-- and ICMP. For EC2-VPC, security groups can have rules assigned to
-- any protocol number.
} deriving (Eq, Show, Generic)
instance IsQuery AuthorizeSecurityGroupIngress
instance Rq AuthorizeSecurityGroupIngress where
type Er AuthorizeSecurityGroupIngress = EC2ErrorResponse
type Rs AuthorizeSecurityGroupIngress = AuthorizeSecurityGroupIngressResponse
request = query4 ec2 GET "AuthorizeSecurityGroupIngress"
data AuthorizeSecurityGroupIngressResponse = AuthorizeSecurityGroupIngressResponse
{ asgirRequestId :: !Text
-- ^ The ID of the request.
, asgirReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an
-- error.
} deriving (Eq, Show, Generic)
instance IsXML AuthorizeSecurityGroupIngressResponse where
xmlPickler = ec2XML
-- | Bundles an Amazon instance store-backed Windows instance.During bundling,
-- only the root device volume (C:\) is bundled. Data on other instance store
-- volumes is not preserved.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-BundleInstance.html>
data BundleInstance = BundleInstance
{ biInstanceId :: !Text
-- ^ The ID of the instance to bundle.
, biStorage :: !BundleInstanceTaskStorage
-- ^ Bundle storage instructions.
} deriving (Eq, Show, Generic)
instance IsQuery BundleInstance
instance Rq BundleInstance where
type Er BundleInstance = EC2ErrorResponse
type Rs BundleInstance = BundleInstanceResponse
request = query4 ec2 GET "BundleInstance"
data BundleInstanceResponse = BundleInstanceResponse
{ birRequestId :: !Text
-- ^ The ID of the request.
, birBundleInstanceTask :: !BundleInstanceTask
-- ^ The bundle task.
} deriving (Eq, Show, Generic)
instance IsXML BundleInstanceResponse where
xmlPickler = ec2XML
-- | Cancels a bundling operation for an instance store-backed Windows instance.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CancelBundleTask.html>
data CancelBundleTask = CancelBundleTask
{ cbtBundleId :: !Text
-- ^ The ID of the bundle task.
} deriving (Eq, Show, Generic)
instance IsQuery CancelBundleTask
instance Rq CancelBundleTask where
type Er CancelBundleTask = EC2ErrorResponse
type Rs CancelBundleTask = CancelBundleTaskResponse
request = query4 ec2 GET "CancelBundleTask"
data CancelBundleTaskResponse = CancelBundleTaskResponse
{ cbtRequestId :: !Text
-- ^ The ID of the request.
, cbtBundleInstanceTask :: !BundleInstanceTask
-- ^ The bundle task.
} deriving (Eq, Show, Generic)
instance IsXML CancelBundleTaskResponse where
xmlPickler = ec2XML
-- | Cancels an active conversion task.
--
-- The task can be the import of an
-- instance or volume. The action removes all artifacts of the conversion,
-- including a partially uploaded volume or instance. If the conversion is
-- complete or is in the process of transferring the final disk image, the
-- command fails and returns an exception.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CancelConversionTask.html>
data CancelConversionTask = CancelConversionTask
{ cctConversionTaskId :: !Text
-- ^ The ID of the conversion task.
} deriving (Eq, Show, Generic)
instance IsQuery CancelConversionTask
instance Rq CancelConversionTask where
type Er CancelConversionTask = EC2ErrorResponse
type Rs CancelConversionTask = CancelConversionTaskResponse
request = query4 ec2 GET "CancelConversionTask"
data CancelConversionTaskResponse = CancelConversionTaskResponse
{ cctRequestId :: !Text
-- ^ The ID of the request.
, cctReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an
-- error.
} deriving (Eq, Show, Generic)
instance IsXML CancelConversionTaskResponse where
xmlPickler = ec2XML
-- | Cancels an active export task. The request removes all artifacts of the
-- export, including any partially created Amazon S3 objects. If the export
-- task is complete or is in the process of transferring the final disk image,
-- the command fails and returns an error.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CancelExportTask.html>
data CancelExportTask = CancelExportTask
{ cetExportTaskId :: !Text
-- ^ The ID of the export task. This is the ID returned by
-- CreateInstanceExportTask.
} deriving (Eq, Show, Generic)
instance IsQuery CancelExportTask
instance Rq CancelExportTask where
type Er CancelExportTask = EC2ErrorResponse
type Rs CancelExportTask = CancelExportTaskResponse
request = query4 ec2 GET "CancelExportTask"
data CancelExportTaskResponse = CancelExportTaskResponse
{ cetRequestId :: !Text
-- ^ The ID of the request.
, cetReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
} deriving (Eq, Show, Generic)
instance IsXML CancelExportTaskResponse where
xmlPickler = ec2XML
-- | Cancels the specified Reserved Instance listing in the Reserved Instance Marketplace.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CancelReservedInstancesListing.html>
data CancelReservedInstancesListing = CancelReservedInstancesListing
{ crilReservedInstancesListingId :: !Text
-- ^ The ID of the Reserved Instance listing to be canceled.
} deriving (Eq, Show, Generic)
instance IsQuery CancelReservedInstancesListing
instance Rq CancelReservedInstancesListing where
type Er CancelReservedInstancesListing = EC2ErrorResponse
type Rs CancelReservedInstancesListing = CancelReservedInstancesListingResponse
request = query4 ec2 GET "CancelReservedInstancesListing"
data CancelReservedInstancesListingResponse = CancelReservedInstancesListingResponse
{ crilRequestId :: !Text
-- ^ The ID of the request.
, crilReservedInstancesListingsSet :: !DescribeReservedInstancesListingsResponseSetItemType
-- ^ The Reserved Instance listing for cancellation.
} deriving (Eq, Show, Generic)
instance IsXML CancelReservedInstancesListingResponse where
xmlPickler = ec2XML
-- | Cancels one or more Spot Instance requests.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CancelSpotInstanceRequests.html>
data CancelSpotInstanceRequests = CancelSpotInstanceRequests
{ csirSpotInstanceRequestId :: [Text]
-- ^ One or more Spot Instance request IDs.
} deriving (Eq, Show, Generic)
instance IsQuery CancelSpotInstanceRequests
instance Rq CancelSpotInstanceRequests where
type Er CancelSpotInstanceRequests = EC2ErrorResponse
type Rs CancelSpotInstanceRequests = CancelSpotInstanceRequestsResponse
request = query4 ec2 GET "CancelSpotInstanceRequests"
data CancelSpotInstanceRequestsResponse = CancelSpotInstanceRequestsResponse
{ csirRequestId :: !Text
-- ^ The ID of the request.
, csirSpotInstanceRequestSet :: [CancelSpotInstanceRequestsResponseSetItemType]
-- ^ A list of Spot Instance requests. Each request is wrapped in an
-- item element.
} deriving (Eq, Show, Generic)
instance IsXML CancelSpotInstanceRequestsResponse where
xmlPickler = ec2XML
-- -- | Determines whether a product code is associated with an instance. This
-- -- action can only be used by the owner of the product code. It is useful when
-- -- a product code owner needs to verify whether another user's instance is
-- -- eligible for support.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ConfirmProductInstance.html>
-- data ConfirmProductInstance = ConfirmProductInstance
-- { cpiProductCode :: !Text
-- -- ^ The product code. This must be an Amazon DevPay product code that
-- -- you own.
-- , cpiInstanceId :: !Text
-- -- ^ The instance.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ConfirmProductInstance
-- instance IsXML ConfirmProductInstance where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ConfirmProductInstance ConfirmProductInstanceResponse where
-- request = query4 ec2 GET "ConfirmProductInstance"
-- data ConfirmProductInstanceResponse = ConfirmProductInstanceResponse
-- { cpiRequestId :: !Text
-- -- ^ The ID of the request.
-- , cpiReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- , cpiOwnerId :: !Text
-- -- ^ The instance owner's account ID. Only present if the product code
-- -- is attached to the instance.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ConfirmProductInstanceResponse where
-- xmlPickler = ec2XML
-- -- | Initiates the copy of an AMI from the specified source region to the region
-- -- in which the request was made.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CopyImage.html>
-- data CopyImage = CopyImage
-- { ciSourceRegion :: !Text
-- -- ^ The name of the region that contains the AMI to be copied
-- -- (source).
-- , ciSourceImageId :: !Text
-- -- ^ The ID of the AMI to copy.
-- , ciName :: Maybe Text
-- -- ^ The name of the new AMI in the destination region.
-- , ciDescription :: Maybe Text
-- -- ^ A description for the new AMI in the destination region.
-- , ciClientToken :: Maybe Text
-- -- ^ Unique, case-sensitive identifier you provide to ensure
-- -- idempotency of the request.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CopyImage
-- instance IsXML CopyImage where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 CopyImage CopyImageResponse where
-- request = query4 ec2 GET "CopyImage"
-- data CopyImageResponse = CopyImageResponse
-- { ciRequestId :: !Text
-- -- ^ The ID of the request.
-- , ciImageId :: !Text
-- -- ^ The ID of the new AMI.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CopyImageResponse where
-- xmlPickler = ec2XML
-- -- | Copies a point-in-time snapshot of an Amazon Elastic Block Store (Amazon
-- -- EBS) volume and stores it in Amazon Simple Storage Service (Amazon S3). You
-- -- can copy the snapshot within the same region or from one region to another.
-- -- You can use the snapshot to create Amazon EBS volumes or Amazon Machine
-- -- Images (AMIs).For more information about Amazon EBS, see Amazon Elastic
-- -- Block Store (Amazon EBS).
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CopySnapshot.html>
-- data CopySnapshot = CopySnapshot
-- { csSourceRegion :: !Text
-- -- ^ The ID of the region that contains the snapshot to be copied.
-- , csSourceSnapshotId :: !Text
-- -- ^ The ID of the Amazon EBS snapshot to copy.
-- , csDescription :: Maybe Text
-- -- ^ A description for the new Amazon EBS snapshot.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CopySnapshot
-- instance AWSRequest EC2 CopySnapshot CopySnapshotResponse where
-- request = query4 ec2 GET "CopySnapshot"
-- data CopySnapshotResponse = CopySnapshotResponse
-- { csRequestId :: !Text
-- -- ^ The ID of the request.
-- , csSnapshotId :: !Text
-- -- ^ The ID of the new snapshot.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CopySnapshotResponse where
-- xmlPickler = ec2XML
-- -- | Provides information to AWS about your VPN customer gateway device. The
-- -- customer gateway is the appliance at your end of the VPN connection. (The
-- -- device on the AWS side of the VPN connection is the virtual private
-- -- gateway.) You must provide the Internet-routable IP address of the customer
-- -- gateway's external interface. The IP address must be static and can't be
-- -- behind a device performing network address translation (NAT).You must
-- -- provide the Internet-routable IP address of the customer gateway's external
-- -- interface. The IP address must be static and can't be behind a device
-- -- performing network address translation (NAT).For devices that use Border
-- -- Gateway Protocol (BGP), you can also provide the device's BGP Autonomous
-- -- System Number (ASN). You can use an existing ASN assigned to your network.
-- -- If you don't have an ASN already, you can use a private ASN (in the 64512 -
-- -- 65534 range).For more information about ASNs, see the Wikipedia article.For
-- -- more information about VPN customer gateways, see Adding a Hardware Virtual
-- -- Private Gateway to Your VPC in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateCustomerGateway.html>
-- data CreateCustomerGateway = CreateCustomerGateway
-- { ccgType :: !Text
-- -- ^ The type of VPN connection this customer gateway supports.
-- , ccgIpAddress :: !Text
-- -- ^ The Internet-routable IP address for the customer gateway's
-- -- outside interface. The address must be static.
-- , ccgBgpAsn :: Maybe Integer
-- -- ^ For devices that support BGP, the customer gateway's Border
-- -- Gateway Protocol (BGP) Autonomous System Number (ASN).
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateCustomerGateway
-- instance AWSRequest EC2 CreateCustomerGateway CreateCustomerGatewayResponse where
-- request = query4 ec2 GET "CreateCustomerGateway"
-- data CreateCustomerGatewayResponse = CreateCustomerGatewayResponse
-- { ccgRequestId :: !Text
-- -- ^ The ID of the request.
-- , ccgCustomerGateway :: !CustomerGatewayType
-- -- ^ Information about the customer gateway.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateCustomerGatewayResponse where
-- xmlPickler = ec2XML
-- -- | Creates a set of DHCP options for your VPC. After creating the set, you
-- -- must associate it with the VPC, causing all existing and new instances that
-- -- you launch in the VPC to use this set of DHCP options. The following are
-- -- the individual DHCP options you can specify. For more information about the
-- -- options, see RFC 2132.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateDhcpOptions.html>
-- data CreateDhcpOptions = CreateDhcpOptions
-- { cdoDhcpConfiguration :: Members DhcConfigurationItemType
-- -- ^ A list of dhcp configurations.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateDhcpOptions
-- instance AWSRequest EC2 CreateDhcpOptions CreateDhcpOptionsResponse where
-- request = query4 ec2 GET "CreateDhcpOptions"
-- data CreateDhcpOptionsResponse = CreateDhcpOptionsResponse
-- { cdoRequestId :: !Text
-- -- ^ The ID of the request.
-- , cdoDhcpOptions :: !DhcpOptionsType
-- -- ^ A set of DHCP options.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateDhcpOptionsResponse where
-- xmlPickler = ec2XML
-- | Creates an Amazon EBS-backed AMI from an Amazon EBS-backed instance that is
-- either running or stopped.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateImage.html>
data CreateImage = CreateImage
{ ciInstanceId :: !Text
-- ^ The ID of the instance.
, cjName :: !Text
-- ^ A name for the new image.
, cjDescription :: Maybe Text
-- ^ A description for the new image.
, cjNoReboot :: Maybe Bool
-- ^ By default this parameter is set to false, which means Amazon EC2
-- attempts to cleanly shut down the instance before image creation
-- and then reboots the instance. When the parameter is set to true,
-- Amazon EC2 doesn't shut down the instance before creating the
-- image. When this option is used, file system integrity on the
-- created image can't be guaranteed.
, cjBlockDeviceMapping :: [BlockDeviceMappingItemType]
-- ^ The device name exposed to the instance (for example, /dev/sdh or xvdh).
} deriving (Eq, Show, Generic)
instance IsQuery CreateImage
instance IsXML CreateImage where
xmlPickler = ec2XML
instance Rq CreateImage where
type Er CreateImage = EC2ErrorResponse
type Rs CreateImage = CreateImageResponse
request = query4 ec2 GET "CreateImage"
data CreateImageResponse = CreateImageResponse
{ cjRequestId :: !Text
-- ^ The ID of the request.
, cjImageId :: !Text
-- ^ The ID of the new AMI.
} deriving (Eq, Show, Generic)
instance IsXML CreateImageResponse where
xmlPickler = ec2XML
-- -- | Exports a running or stopped instance to an Amazon S3 bucket.For
-- -- information about the supported operating systems, image formats, and known
-- -- limitations for the types of instances you can export, see Exporting EC2
-- -- Instances in the Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateInstanceExportTask.html>
-- data CreateInstanceExportTask = CreateInstanceExportTask
-- { cietDescription :: Maybe Text
-- -- ^ A description for the conversion task or the resource being
-- -- exported. The maximum length is 255 bytes.
-- , cietInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , cietTargetEnvironment :: !Text
-- -- ^ The target virtualization environment.
-- , cietExportToS3 :: Maybe ExportToS3Task
-- -- ^ The format for the exported image.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateInstanceExportTask
-- instance AWSRequest EC2 CreateInstanceExportTask CreateInstanceExportTaskResponse where
-- request = query4 ec2 GET "CreateInstanceExportTask"
-- data CreateInstanceExportTaskResponse = CreateInstanceExportTaskResponse
-- { cietRequestId :: !Text
-- -- ^ The ID of the request.
-- , cietExportTask :: !ExportTaskResponseType
-- -- ^ The details of the created ExportVM task.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateInstanceExportTaskResponse where
-- xmlPickler = ec2XML
-- -- | Creates an Internet gateway for use with a VPC. After creating the Internet
-- -- gateway, you attach it to a VPC using AttachInternetGateway.For more
-- -- information about your VPC and Internet gateway, see the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateInternetGateway.html>
-- data CreateInternetGateway = CreateInternetGateway
-- deriving (Eq, Read, Show, Generic)
-- instance IsQuery CreateInternetGateway
-- instance IsXML CreateInternetGateway where
-- xmlPickler = xpEmpty $ Just ec2NS
-- instance AWSRequest EC2 CreateInternetGateway CreateInternetGatewayResponse where
-- request = query4 ec2 GET "CreateInternetGateway"
-- data CreateInternetGatewayResponse = CreateInternetGatewayResponse
-- { cigRequestId :: !Text
-- -- ^ The ID of the request.
-- , cigInternetGateway :: !InternetGatewayType
-- -- ^ Information about the Internet gateway
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateInternetGatewayResponse where
-- xmlPickler = ec2XML
-- | Creates a 2048-bit RSA key pair with the specified name. Amazon EC2 stores
-- the public key and displays the private key for you to save to a file. The
-- private key is returned as an unencrypted PEM encoded PKCS#8 private key.
-- If a key with the specified name already exists, Amazon EC2 returns an
-- error. You can have up to five thousand key pairs per region.For more
-- information about key pairs, see Key Pairs in the Amazon Elastic Compute
-- Cloud User Guide.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateKeyPair.html>
data CreateKeyPair = CreateKeyPair
{ ckpKeyName :: !Text
-- ^ A unique name for the key pair.
} deriving (Eq, Show, Generic)
instance IsQuery CreateKeyPair
instance Rq CreateKeyPair where
type Er CreateKeyPair = EC2ErrorResponse
type Rs CreateKeyPair = CreateKeyPairResponse
request = query4 ec2 GET "CreateKeyPair"
data CreateKeyPairResponse = CreateKeyPairResponse
{ ckpRequestId :: !Text
-- ^ The ID of the request.
, ckqKeyName :: !Text
-- ^ The name of the key pair name.
, ckqKeyFingerprint :: !Text
-- ^ A SHA-1 digest of the DER encoded private key.
, ckqKeyMaterial :: !Text
-- ^ An unencrypted PEM encoded RSA private key.
} deriving (Eq, Show, Generic)
instance IsXML CreateKeyPairResponse where
xmlPickler = ec2XML
-- -- | Creates a network ACL in a VPC. Network ACLs provide an optional layer of
-- -- security (on top of security groups) for the instances in your VPC.For more
-- -- information about network ACLs, see Network ACLs in the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkAcl.html>
-- data CreateNetworkAcl = CreateNetworkAcl
-- { cnaVpcId :: !Text
-- -- ^ The ID of the VPC.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateNetworkAcl
-- instance AWSRequest EC2 CreateNetworkAcl CreateNetworkAclResponse where
-- request = query4 ec2 GET "CreateNetworkAcl"
-- data CreateNetworkAclResponse = CreateNetworkAclResponse
-- { cnaRequestId :: !Text
-- -- ^ The ID of the request.
-- , cnaNetworkAcl :: !NetworkAclType
-- -- ^ Information about the new network ACL.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateNetworkAclResponse where
-- xmlPickler = ec2XML
-- -- | Creates an entry (a rule) in a network ACL with the specified rule number.
-- -- Each network ACL has a set of numbered ingress rules and a separate set of
-- -- numbered egress rules. When determining whether a packet should be allowed
-- -- in or out of a subnet associated with the ACL, we process the entries in
-- -- the ACL according to the rule numbers, in ascending order. Each network ACL
-- -- has a set of ingress rules and a separate set of egress rules.After you add
-- -- an entry, you can't modify it; you must either replace it, or create a new
-- -- entry and delete the old one.For more information about network ACLs, see
-- -- Network ACLs in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkAclEntry.html>
-- data CreateNetworkAclEntry = CreateNetworkAclEntry
-- { cnaeNetworkAclId :: !Text
-- -- ^ The ID of the ACL.
-- , cnaeRuleNumber :: !Integer
-- -- ^ The rule number to assign to the entry (for example, 100). ACL
-- -- entries are processed in ascending order by rule number.
-- , cnaeProtocol :: !Integer
-- -- ^ The IP protocol the rule applies to. You can use -1 to mean all
-- -- protocols.
-- , cnaeRuleAction :: !Text
-- -- ^ Indicates whether to allow or deny traffic that matches the rule.
-- , cnaeEgress :: Maybe Bool
-- -- ^ Indicates whether this rule applies to egress traffic from the
-- -- subnet (true) or ingress traffic to the subnet (false).
-- , cnaeCidrBlock :: !Text
-- -- ^ The CIDR range to allow or deny, in CIDR notation (for example,
-- -- 172.16.0.0/24).
-- , cnaeIcmp :: Maybe IcmpType
-- -- ^ For the ICMP protocol, the ICMP code and type.
-- , cnaePortRange :: Maybe PortRangeType
-- -- ^ The first port in the range.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateNetworkAclEntry
-- instance AWSRequest EC2 CreateNetworkAclEntry CreateNetworkAclEntryResponse where
-- request = query4 ec2 GET "CreateNetworkAclEntry"
-- data CreateNetworkAclEntryResponse = CreateNetworkAclEntryResponse
-- { cnaeRequestId :: !Text
-- -- ^ The ID of the request.
-- , cnaeReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateNetworkAclEntryResponse where
-- xmlPickler = ec2XML
-- -- | Creates a network interface in the specified subnet.For more information
-- -- about network interfaces, see Elastic Network Interfaces in the Amazon
-- -- Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkInterface.html>
-- data CreateNetworkInterface = CreateNetworkInterface
-- { cniSubnetId :: !Text
-- -- ^ The ID of the subnet to associate with the network interface.
-- , cniPrivateIpAddress :: Maybe Text
-- -- ^ The primary private IP address of the network interface. If you
-- -- don't specify an IP address, Amazon EC2 will select one for you
-- -- from the subnet range.
-- , cniPrivateIpAddresses :: Members PrivateIpAddresses
-- -- ^ The private IP address of the specified network interface. You
-- -- can use this parameter multiple times to specify explicit private
-- -- IP addresses for a network interface, but only one private IP
-- -- address can be designated as primary.
-- , cniSecondaryPrivateIpAddressCount :: Maybe Integer
-- -- ^ The number of secondary private IP addresses to assign to a
-- -- network interface. When you specify a number of secondary IP
-- -- addresses, Amazon EC2 selects these IP addresses within the
-- -- subnet range.
-- , cniDescription :: Maybe Text
-- -- ^ A description for the network interface.
-- , cniSecurityGroupId :: Members SecurityGroupIdSetItemType
-- -- ^ The list of security group IDs for the network interface.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateNetworkInterface
-- instance IsXML CreateNetworkInterface where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 CreateNetworkInterface CreateNetworkInterfaceResponse where
-- request = query4 ec2 GET "CreateNetworkInterface"
-- data CreateNetworkInterfaceResponse = CreateNetworkInterfaceResponse
-- { cniRequestId :: !Text
-- -- ^ The ID of the request.
-- , cniNetworkInterface :: !NetworkInterfaceType
-- -- ^ The network interface that was created.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateNetworkInterfaceResponse where
-- xmlPickler = ec2XML
-- -- | Creates a placement group that you launch cluster instances into. You must
-- -- give the group a name unique within the scope of your account.For more
-- -- information about placement groups and cluster instances, see Cluster
-- -- Instances in the Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreatePlacementGroup.html>
-- data CreatePlacementGroup = CreatePlacementGroup
-- { cpgGroupName :: !Text
-- -- ^ A name for the placement group.
-- , cpgStrategy :: !Text
-- -- ^ The placement strategy.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreatePlacementGroup
-- instance AWSRequest EC2 CreatePlacementGroup CreatePlacementGroupResponse where
-- request = query4 ec2 GET "CreatePlacementGroup"
-- data CreatePlacementGroupResponse = CreatePlacementGroupResponse
-- { cpgRequestId :: !Text
-- -- ^ The ID of the request.
-- , cpgReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreatePlacementGroupResponse where
-- xmlPickler = ec2XML
-- -- | Creates a listing for Amazon EC2 Reserved Instances that will be sold in
-- -- the Reserved Instance Marketplace. You can submit one Reserved Instance
-- -- listing at a time.The Reserved Instance Marketplace matches sellers who
-- -- want to resell Reserved Instance capacity that they no longer need with
-- -- buyers who want to purchase additional capacity. Reserved Instances bought
-- -- and sold through the Reserved Instance Marketplace work like any other
-- -- Reserved Instances.If you want to sell your Reserved Instances, you must
-- -- first register as a Seller in the Reserved Instance Marketplace. After
-- -- completing the registration process, you can create a Reserved Instance
-- -- Marketplace listing of some or all of your Reserved Instances, and specify
-- -- the upfront price you want to receive for them. Your Reserved Instance
-- -- listings then become available for purchase.For more information about
-- -- Reserved Instance Marketplace, see Reserved Instance Marketplace in the
-- -- Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateReservedInstancesListing.html>
-- data CreateReservedInstancesListing = CreateReservedInstancesListing
-- { crilReservedInstancesId :: !Text
-- -- ^ The ID of the active Reserved Instance.
-- , crilInstanceCount :: !Integer
-- -- ^ The number of instances that are a part of a Reserved Instance
-- -- account that will be listed in the Reserved Instance Marketplace.
-- -- This number should be less than or equal to the instance count
-- -- associated with the Reserved Instance ID specified in this call.
-- , crilPriceSchedules :: !PriceScheduleRequestSetItemType
-- -- ^ A list specifying the price of the Reserved Instance for each
-- -- month remaining in the Reserved Instance term.
-- , crilClientToken :: !Text
-- -- ^ Unique, case-sensitive identifier you provide to ensure
-- -- idempotency of your listings. This helps avoid duplicate
-- -- listings.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateReservedInstancesListing
-- instance AWSRequest EC2 CreateReservedInstancesListing CreateReservedInstancesListingResponse where
-- request = query4 ec2 GET "CreateReservedInstancesListing"
-- data CreateReservedInstancesListingResponse = CreateReservedInstancesListingResponse
-- { crimRequestId :: !Text
-- -- ^ The ID of the request.
-- , crimReservedInstancesListingSet :: !DescribeReservedInstancesListingsResponseSetItemType
-- -- ^ The Reserved Instances listing that was created. The listing
-- -- information is wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateReservedInstancesListingResponse where
-- xmlPickler = ec2XML
-- -- | Creates a route in a route table within a VPC. The route's target can be
-- -- either a gateway attached to the VPC or a NAT instance in the VPC.When
-- -- determining how to route traffic, we use the route with the most specific
-- -- match. For example, let's say the traffic is destined for 192.0.2.3, and
-- -- the route table includes the following two routes: Both routes apply to the
-- -- traffic destined for 192.0.2.3. However, the second route in the list
-- -- covers a smaller number of IP addresses and is therefore more specific, so
-- -- we use that route to determine where to target the traffic.For more
-- -- information about route tables, see Route Tables in the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRoute.html>
-- data CreateRoute = CreateRoute
-- { crRouteTableId :: !Text
-- -- ^ The ID of the route table for the route.
-- , crDestinationCidrBlock :: !Text
-- -- ^ The CIDR address block used for the destination match. Routing
-- -- decisions are based on the most specific match.
-- , crGatewayId :: !Text
-- -- ^ The ID of an Internet gateway attached to your VPC.
-- , crInstanceId :: !Text
-- -- ^ The ID of a NAT instance in your VPC. The operation fails if you
-- -- specify an instance ID unless exactly one network interface is
-- -- attached.
-- , crNetworkInterfaceId :: !Text
-- -- ^ The ID of a network interface.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateRoute
-- instance IsXML CreateRoute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 CreateRoute CreateRouteResponse where
-- request = query4 ec2 GET "CreateRoute"
-- data CreateRouteResponse = CreateRouteResponse
-- { crRequestId :: !Text
-- -- ^ The ID of the request.
-- , crReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateRouteResponse where
-- xmlPickler = ec2XML
-- -- | Creates a route table for the specified VPC. After you create a route
-- -- table, you can add routes and associate the table with a subnet.For more
-- -- information about route tables, see Route Tables in the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRouteTable.html>
-- data CreateRouteTable = CreateRouteTable
-- { crtVpcId :: !Text
-- -- ^ The ID of the VPC.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateRouteTable
-- instance IsXML CreateRouteTable where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 CreateRouteTable CreateRouteTableResponse where
-- request = query4 ec2 GET "CreateRouteTable"
-- data CreateRouteTableResponse = CreateRouteTableResponse
-- { crtRequestId :: !Text
-- -- ^ The ID of the request.
-- , crtRouteTable :: !RouteTableType
-- -- ^ Information about the newly created route table.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateRouteTableResponse where
-- xmlPickler = ec2XML
-- | Creates a security group.
--
-- A security group is for use with instances either in the EC2-Classic platform
-- or in a specific VPC.
--
-- When you create a security group, you specify a friendly name of your
-- choice. You can have a security group for use in EC2-Classic with the same
-- name as a security group for use in a VPC. However, you can't have two
-- security groups for use in EC2-Classic with the same name or two security
-- groups for use in a VPC with the same name.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSecurityGroup.html>
data CreateSecurityGroup = CreateSecurityGroup
{ csgGroupName :: !Text
-- ^ The name of the security group.
, csgGroupDescription :: !Text
-- ^ A description for the security group. This is informational only.
, csgVpcId :: Maybe Text
-- ^ [EC2-VPC] The ID of the VPC.
} deriving (Eq, Show, Generic)
instance IsQuery CreateSecurityGroup
instance Rq CreateSecurityGroup where
type Er CreateSecurityGroup = EC2ErrorResponse
type Rs CreateSecurityGroup = CreateSecurityGroupResponse
request = query4 ec2 GET "CreateSecurityGroup"
data CreateSecurityGroupResponse = CreateSecurityGroupResponse
{ csgrRequestId :: !Text
-- ^ The ID of the request.
, csgrReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
, csgrGroupId :: !Text
-- ^ The ID of the new security group.
} deriving (Eq, Show, Generic)
instance IsXML CreateSecurityGroupResponse where
xmlPickler = ec2XML
-- -- | Creates a snapshot of an Amazon EBS volume and stores it in Amazon S3. You
-- -- can use snapshots for backups, to make copies of instance store volumes,
-- -- and to save data before shutting down an instance.When a snapshot is
-- -- created, any AWS Marketplace product codes from the volume are propagated
-- -- to the snapshot.You can take a snapshot of an attached volume that is in
-- -- use. However, snapshots only capture data that has been written to your
-- -- Amazon EBS volume at the time the snapshot command is issued. This may
-- -- exclude any data that has been cached by any applications or the operating
-- -- system. If you can pause any file writes to the volume long enough to take
-- -- a snapshot, your snapshot should be complete. However, if you can't pause
-- -- all file writes to the volume, you should unmount the volume from within
-- -- the instance, issue the snapshot command, and then remount the volume to
-- -- ensure a consistent and complete snapshot. You may remount and use your
-- -- volume while the snapshot status is pending.To create a snapshot for Amazon
-- -- EBS volumes that serve as root devices, you should stop the instance before
-- -- taking the snapshot.To unmount the volume in Linux/UNIX, use the following
-- -- command:Where device_name is the device name (for example, /dev/sdh).To
-- -- unmount the volume in Windows, open Disk Management, right-click the volume
-- -- to unmount, and select Change Drive Letter and Path. Select the mount point
-- -- to remove, and then click Remove.For more information about Amazon EBS, see
-- -- Amazon Elastic Block Store in the Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSnapshot.html>
-- data CreateSnapshot = CreateSnapshot
-- { csVolumeId :: !Text
-- -- ^ The ID of the Amazon EBS volume.
-- , ctDescription :: Maybe Text
-- -- ^ A description for the snapshot.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateSnapshot
-- instance AWSRequest EC2 CreateSnapshot CreateSnapshotResponse where
-- request = query4 ec2 GET "CreateSnapshot"
-- data CreateSnapshotResponse = CreateSnapshotResponse
-- { ctRequestId :: !Text
-- -- ^ The ID of the request.
-- , ctSnapshotId :: !Text
-- -- ^ The ID of the snapshot.
-- , ctVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , ctStatus :: !Text
-- -- ^ The snapshot state.
-- , ctStartTime :: !UTCTime
-- -- ^ The time stamp when the snapshot was initiated.
-- , ctProgress :: !Text
-- -- ^ The progress of the snapshot, as a percentage.
-- , ctOwnerId :: !Text
-- -- ^ The AWS account ID of the Amazon EBS snapshot owner.
-- , ctVolumeSize :: !Text
-- -- ^ The size of the volume, in GiB.
-- , cuDescription :: !Text
-- -- ^ The description for the snapshot.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateSnapshotResponse where
-- xmlPickler = ec2XML
-- -- | Creates the datafeed for Spot Instances, enabling you to view Spot Instance
-- -- usage logs. You can create one data feed per account. For more information
-- -- about Spot Instances, see Spot Instances in the Amazon Elastic Compute
-- -- Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSpotDatafeedSubscription.html>
-- data CreateSpotDatafeedSubscription = CreateSpotDatafeedSubscription
-- { csdsBucket :: !Text
-- -- ^ The Amazon S3 bucket in which to store the Spot Instance
-- -- datafeed.
-- , csdsPrefix :: Maybe Text
-- -- ^ A prefix for the datafeed file names.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateSpotDatafeedSubscription
-- instance AWSRequest EC2 CreateSpotDatafeedSubscription CreateSpotDatafeedSubscriptionResponse where
-- request = query4 ec2 GET "CreateSpotDatafeedSubscription"
-- data CreateSpotDatafeedSubscriptionResponse = CreateSpotDatafeedSubscriptionResponse
-- { csdsRequestId :: !Text
-- -- ^ The ID of the request.
-- , csdsSpotDatafeedSubscription :: !SpotDatafeedSubscriptionType
-- -- ^ Type: SpotDatafeedSubscriptionType
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateSpotDatafeedSubscriptionResponse where
-- xmlPickler = ec2XML
-- -- | Creates a subnet in an existing VPC.When you create each subnet, you
-- -- provide the VPC ID and the CIDR block you want for the subnet. After you
-- -- create a subnet, you can't change its CIDR block. The subnet's CIDR block
-- -- can be the same as the VPC's CIDR block (assuming you want only a single
-- -- subnet in the VPC), or a subset of the VPC's CIDR block. If you create more
-- -- than one subnet in a VPC, the subnets' CIDR blocks must not overlap. The
-- -- smallest subnet (and VPC) you can create uses a /28 netmask (16 IP
-- -- addresses), and the largest uses a /16 netmask (65,536 IP addresses).If you
-- -- add more than one subnet to a VPC, they're set up in a star topology with a
-- -- logical router in the middle. By default, you can create up to 20 subnets
-- -- in a VPC. If you need more than 20 subnets, you can request more by going
-- -- to Request to Increase Amazon VPC Limits.If you launch an instance in a VPC
-- -- using an Amazon EBS-backed AMI, the IP address doesn't change if you stop
-- -- and restart the instance (unlike a similar instance launched outside a VPC,
-- -- which gets a new IP address when restarted). It's therefore possible to
-- -- have a subnet with no running instances (they're all stopped), but no
-- -- remaining IP addresses available. For more information about Amazon
-- -- EBS-backed AMIs, see AMI Basics in the Amazon Elastic Compute Cloud User
-- -- Guide. For more information about subnets, see Your VPC and Subnets in the
-- -- Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSubnet.html>
-- data CreateSubnet = CreateSubnet
-- { csVpcId :: !Text
-- -- ^ The ID of the VPC.
-- , csCidrBlock :: !Text
-- -- ^ The CIDR block for the subnet. For example, 10.0.0.0/24.
-- , csAvailabilityZone :: Maybe Text
-- -- ^ The Availability Zone for the subnet.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateSubnet
-- instance AWSRequest EC2 CreateSubnet CreateSubnetResponse where
-- request = query4 ec2 GET "CreateSubnet"
-- data CreateSubnetResponse = CreateSubnetResponse
-- { cuRequestId :: !Text
-- -- ^ The ID of the request.
-- , cuSubnet :: !SubnetType
-- -- ^ Information about the subnet.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateSubnetResponse where
-- xmlPickler = ec2XML
-- | Adds or overwrites one or more tags for the specified EC2 resource or
-- resources. Each resource can have a maximum of 10 tags. Each tag consists
-- of a key and optional value. Tag keys must be unique per resource.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateTags.html>
data CreateTags = CreateTags
{ ctResourceId :: [Text]
-- ^ The IDs of one or more resources to tag. For example, ami-1a2b3c4d.
, ctTag :: [ResourceTagSetItemType]
-- ^ The key for a tag.
} deriving (Eq, Show, Generic)
instance IsQuery CreateTags
instance Rq CreateTags where
type Er CreateTags = EC2ErrorResponse
type Rs CreateTags = CreateTagsResponse
request = query4 ec2 GET "CreateTags"
data CreateTagsResponse = CreateTagsResponse
{ cvRequestId :: !Text
-- ^ The ID of the request.
, cvReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
} deriving (Eq, Show, Generic)
instance IsXML CreateTagsResponse where
xmlPickler = ec2XML
-- -- | Creates an Amazon EBS volume that can be attached to any instance in the
-- -- same Availability Zone.Any AWS Marketplace product codes from the snapshot
-- -- are propagated to the volume.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html>
-- data CreateVolume = CreateVolume
-- { cvSize :: Maybe Text
-- -- ^ The size of the volume, in GiBs.
-- , cvSnapshotId :: !Text
-- -- ^ The snapshot from which to create the volume.
-- , cvAvailabilityZone :: !Text
-- -- ^ The Availability Zone in which to create the volume. Use
-- -- DescribeAvailabilityZones to list the Availability Zones that are
-- -- currently available to you.
-- , cvVolumeType :: Maybe Text
-- -- ^ The volume type.
-- , cvIops :: !Integer
-- -- ^ The number of I/O operations per second (IOPS) that the volume
-- -- supports.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateVolume
-- instance IsXML CreateVolume where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 CreateVolume CreateVolumeResponse where
-- request = query4 ec2 GET "CreateVolume"
-- data CreateVolumeResponse = CreateVolumeResponse
-- { cwRequestId :: !Text
-- -- ^ The ID of the request.
-- , cwVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , cwSize :: !Text
-- -- ^ The size of the volume, in GiBs.
-- , cwSnapshotId :: !Text
-- -- ^ The snapshot from which the volume was created, if applicable.
-- , cwAvailabilityZone :: !Text
-- -- ^ The Availability Zone for the volume.
-- , cwStatus :: !Text
-- -- ^ The volume state.
-- , cwCreateTime :: !UTCTime
-- -- ^ The time stamp when volume creation was initiated.
-- , cwVolumeType :: !Text
-- -- ^ The volume type.
-- , cwIops :: !Integer
-- -- ^ The number of I/O operations per second (IOPS) that the volume
-- -- supports.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateVolumeResponse where
-- xmlPickler = ec2XML
-- -- | Creates a VPC with the specified CIDR block.The smallest VPC you can create
-- -- uses a /28 netmask (16 IP addresses), and the largest uses a /16 netmask
-- -- (65,536 IP addresses). To help you decide how big to make your VPC, see
-- -- Your VPC and Subnets in the Amazon Virtual Private Cloud User Guide.By
-- -- default, each instance you launch in the VPC has the default DHCP options,
-- -- which includes only a default DNS server that we provide
-- -- (AmazonProvidedDNS).For more information about DHCP options, see DHCP
-- -- Options Sets in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpc.html>
-- data CreateVpc = CreateVpc
-- { cvCidrBlock :: !Text
-- -- ^ The CIDR block for the VPC (for example, 10.0.0.0/16).
-- , cvInstanceTenancy :: Maybe Text
-- -- ^ The supported tenancy options for instances launched into the
-- -- VPC. A value of default means that instances can be launched with
-- -- any tenancy; a value of dedicated means all instances launched
-- -- into the VPC are launched as dedicated tenancy instances
-- -- regardless of the tenancy assigned to the instance at launch.
-- -- Dedicated tenancy instances runs on single-tenant hardware.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateVpc
-- instance AWSRequest EC2 CreateVpc CreateVpcResponse where
-- request = query4 ec2 GET "CreateVpc"
-- data CreateVpcResponse = CreateVpcResponse
-- { cxRequestId :: !Text
-- -- ^ The ID of the request.
-- , cxVpc :: !VpcType
-- -- ^ Information about the VPC.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateVpcResponse where
-- xmlPickler = ec2XML
-- -- | Creates a VPN connection between an existing virtual private gateway and a
-- -- VPN customer gateway. The only supported connection type is ipsec.1. The
-- -- response includes information that you need to give to your network
-- -- administrator to configure your customer gateway. We recommend that you use
-- -- the command line version of this operation (ec2-create-vpn-connection),
-- -- which lets you get the configuration information formatted in a friendlier
-- -- way. For information about the command, see ec2-create-vpn-connection in
-- -- the Amazon Elastic Compute Cloud Command Line Reference.If you decide to
-- -- shut down your VPN connection for any reason and later create a new VPN
-- -- connection, you must reconfigure your customer gateway with the new
-- -- information returned from this call.For more information about VPN
-- -- connections, see Adding a Hardware Virtual Private Gateway to Your VPC in
-- -- the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnConnection.html>
-- data CreateVpnConnection = CreateVpnConnection
-- { cvcType :: !Text
-- -- ^ The type of VPN connection.
-- , cvcCustomerGatewayId :: !Text
-- -- ^ The ID of the customer gateway.
-- , cvcVpnGatewayId :: !Text
-- -- ^ The ID of the virtual private gateway.
-- , cvcOptions :: Maybe VpnConnectionOptions
-- -- ^ Indicates whether the VPN connection requires static routes. If
-- -- you are creating a VPN connection for a device that does not
-- -- support BGP, you must specify true.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateVpnConnection
-- instance AWSRequest EC2 CreateVpnConnection CreateVpnConnectionResponse where
-- request = query4 ec2 GET "CreateVpnConnection"
-- data CreateVpnConnectionResponse = CreateVpnConnectionResponse
-- { cvcRequestId :: !Text
-- -- ^ The ID of the request.
-- , cvcVpnConnection :: !VpnConnectionType
-- -- ^ Information about the VPN connection.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateVpnConnectionResponse where
-- xmlPickler = ec2XML
-- -- | Creates a static route associated with a VPN connection between an existing
-- -- virtual private gateway and a VPN customer gateway. The static route allows
-- -- traffic to be routed from the virtual private gateway to the VPN customer
-- -- gateway.For more information about VPN connections, see Adding a Hardware
-- -- Virtual Private Gateway to Your VPC in the Amazon Virtual Private Cloud
-- -- User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnConnectionRoute.html>
-- data CreateVpnConnectionRoute = CreateVpnConnectionRoute
-- { cvcrDestinationCidrBlock :: !Text
-- -- ^ The CIDR block associated with the local subnet of the customer
-- -- network.
-- , cvcrVpnConnectionId :: !Text
-- -- ^ The ID of the VPN connection.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateVpnConnectionRoute
-- instance IsXML CreateVpnConnectionRoute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 CreateVpnConnectionRoute CreateVpnConnectionRouteResponse where
-- request = query4 ec2 GET "CreateVpnConnectionRoute"
-- data CreateVpnConnectionRouteResponse = CreateVpnConnectionRouteResponse
-- { cvcrRequestId :: !Text
-- -- ^ The ID of the request.
-- , cvcrReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateVpnConnectionRouteResponse where
-- xmlPickler = ec2XML
-- -- | Creates a virtual private gateway. A virtual private gateway is the
-- -- VPC-side endpoint for your VPN connection. You can create a virtual private
-- -- gateway before creating the VPC itself. For more information about virtual
-- -- private gateways, see Adding a Hardware Virtual Private Gateway to Your VPC
-- -- in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnGateway.html>
-- data CreateVpnGateway = CreateVpnGateway
-- { cvgType :: !Text
-- -- ^ The type of VPN connection this virtual private gateway supports.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery CreateVpnGateway
-- instance AWSRequest EC2 CreateVpnGateway CreateVpnGatewayResponse where
-- request = query4 ec2 GET "CreateVpnGateway"
-- data CreateVpnGatewayResponse = CreateVpnGatewayResponse
-- { cvgRequestId :: !Text
-- -- ^ The ID of the request.
-- , cvgVpnGateway :: !VpnGatewayType
-- -- ^ Information about the virtual private gateway.
-- } deriving (Eq, Show, Generic)
-- instance IsXML CreateVpnGatewayResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified VPN customer gateway. You must delete the VPN
-- -- connection before you can delete the customer gateway.For more information
-- -- about VPN customer gateways, see Adding a Hardware Virtual Private Gateway
-- -- to Your VPC in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteCustomerGateway.html>
-- data DeleteCustomerGateway = DeleteCustomerGateway
-- { dcgCustomerGatewayId :: !Text
-- -- ^ The ID of the customer gateway.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteCustomerGateway
-- instance AWSRequest EC2 DeleteCustomerGateway DeleteCustomerGatewayResponse where
-- request = query4 ec2 GET "DeleteCustomerGateway"
-- data DeleteCustomerGatewayResponse = DeleteCustomerGatewayResponse
-- { dcgRequestId :: !Text
-- -- ^ The ID of the request.
-- , dcgReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteCustomerGatewayResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified set of DHCP options. You must disassociate the set of
-- -- DHCP options before you can delete it. You can disassociate the set of DHCP
-- -- options by associating either a new set of options or the default set of
-- -- options with the VPC. For more information about DHCP options sets, see
-- -- DHCP Options Sets in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteDhcpOptions.html>
-- data DeleteDhcpOptions = DeleteDhcpOptions
-- { ddoDhcpOptionsId :: !Text
-- -- ^ The ID of the DHCP options set.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteDhcpOptions
-- instance AWSRequest EC2 DeleteDhcpOptions DeleteDhcpOptionsResponse where
-- request = query4 ec2 GET "DeleteDhcpOptions"
-- data DeleteDhcpOptionsResponse = DeleteDhcpOptionsResponse
-- { ddoRequestId :: !Text
-- -- ^ The ID of the request.
-- , ddoReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteDhcpOptionsResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified Internet gateway. You must detach the Internet
-- -- gateway from the VPC before you can delete it. For more information about
-- -- your VPC and Internet gateway, see the Amazon Virtual Private Cloud User
-- -- Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteInternetGateway.html>
-- data DeleteInternetGateway = DeleteInternetGateway
-- { digInternetGatewayId :: !Text
-- -- ^ The ID of the Internet gateway.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteInternetGateway
-- instance AWSRequest EC2 DeleteInternetGateway DeleteInternetGatewayResponse where
-- request = query4 ec2 GET "DeleteInternetGateway"
-- data DeleteInternetGatewayResponse = DeleteInternetGatewayResponse
-- { digRequestId :: !Text
-- -- ^ The ID of the request.
-- , digReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteInternetGatewayResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified key pair, by removing the public key from Amazon EC2.
-- -- You must own the key pair.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteKeyPair.html>
-- data DeleteKeyPair = DeleteKeyPair
-- { dkpKeyName :: !Text
-- -- ^ The name of the key pair.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteKeyPair
-- instance AWSRequest EC2 DeleteKeyPair DeleteKeyPairResponse where
-- request = query4 ec2 GET "DeleteKeyPair"
-- data DeleteKeyPairResponse = DeleteKeyPairResponse
-- { dkpRequestId :: !Text
-- -- ^ The ID of the request.
-- , dkpReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteKeyPairResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified network ACL. You can't delete the ACL if it's
-- -- associated with any subnets. You can't delete the default network ACL. For
-- -- more information about network ACLs, see Network ACLs in the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkAcl.html>
-- data DeleteNetworkAcl = DeleteNetworkAcl
-- { dnaNetworkAclId :: !Text
-- -- ^ The ID of the network ACL.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteNetworkAcl
-- instance AWSRequest EC2 DeleteNetworkAcl DeleteNetworkAclResponse where
-- request = query4 ec2 GET "DeleteNetworkAcl"
-- data DeleteNetworkAclResponse = DeleteNetworkAclResponse
-- { dnaRequestId :: !Text
-- -- ^ The ID of the request.
-- , dnaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteNetworkAclResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified ingress or egress entry (rule) from the specified
-- -- network ACL. For more information about network ACLs, see Network ACLs in
-- -- the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkAclEntry.html>
-- data DeleteNetworkAclEntry = DeleteNetworkAclEntry
-- { dnaeNetworkAclId :: !Text
-- -- ^ The ID of the network ACL.
-- , dnaeRuleNumber :: !Integer
-- -- ^ The rule number for the entry to delete.
-- , dnaeEgress :: Maybe Bool
-- -- ^ Indicates whether the rule is an egress rule (true) or ingress
-- -- rule (false).
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteNetworkAclEntry
-- instance AWSRequest EC2 DeleteNetworkAclEntry DeleteNetworkAclEntryResponse where
-- request = query4 ec2 GET "DeleteNetworkAclEntry"
-- data DeleteNetworkAclEntryResponse = DeleteNetworkAclEntryResponse
-- { dnaeRequestId :: !Text
-- -- ^ The ID of the request.
-- , dnaeReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteNetworkAclEntryResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified network interface. You must detach the network
-- -- interface before you can delete it.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkInterface.html>
-- data DeleteNetworkInterface = DeleteNetworkInterface
-- { dniNetworkInterfaceId :: !Text
-- -- ^ The ID of the network interface.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteNetworkInterface
-- instance IsXML DeleteNetworkInterface where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DeleteNetworkInterface DeleteNetworkInterfaceResponse where
-- request = query4 ec2 GET "DeleteNetworkInterface"
-- data DeleteNetworkInterfaceResponse = DeleteNetworkInterfaceResponse
-- { dniRequestId :: !Text
-- -- ^ The ID of the request.
-- , dniReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteNetworkInterfaceResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified placement group. You must terminate all instances in
-- -- the placement group before you can delete the placement group. For more
-- -- information about placement groups and cluster instances, see Cluster
-- -- Instances in the Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeletePlacementGroup.html>
-- data DeletePlacementGroup = DeletePlacementGroup
-- { dpgGroupName :: !Text
-- -- ^ The name of the placement group.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeletePlacementGroup
-- instance AWSRequest EC2 DeletePlacementGroup DeletePlacementGroupResponse where
-- request = query4 ec2 GET "DeletePlacementGroup"
-- data DeletePlacementGroupResponse = DeletePlacementGroupResponse
-- { dpgRequestId :: !Text
-- -- ^ The ID of the request.
-- , dpgReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeletePlacementGroupResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified route from the specified route table. For more
-- -- information about route tables, see Route Tables in the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteRoute.html>
-- data DeleteRoute = DeleteRoute
-- { drRouteTableId :: !Text
-- -- ^ The ID of the route table.
-- , drDestinationCidrBlock :: !Text
-- -- ^ The CIDR range for the route. The value you specify must match
-- -- the CIDR for the route exactly.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteRoute
-- instance IsXML DeleteRoute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DeleteRoute DeleteRouteResponse where
-- request = query4 ec2 GET "DeleteRoute"
-- data DeleteRouteResponse = DeleteRouteResponse
-- { drRequestId :: !Text
-- -- ^ The ID of the request.
-- , drReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteRouteResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified route table. You must disassociate the route table
-- -- from any subnets before you can delete it. You can't delete the main route
-- -- table. For more information about route tables, see Route Tables in the
-- -- Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteRouteTable.html>
-- data DeleteRouteTable = DeleteRouteTable
-- { drtRouteTableId :: !Text
-- -- ^ The ID of the route table.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteRouteTable
-- instance IsXML DeleteRouteTable where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DeleteRouteTable DeleteRouteTableResponse where
-- request = query4 ec2 GET "DeleteRouteTable"
-- data DeleteRouteTableResponse = DeleteRouteTableResponse
-- { drtRequestId :: !Text
-- -- ^ The ID of the request.
-- , drtReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteRouteTableResponse where
-- xmlPickler = ec2XML
-- | Deletes a security group.A security group is for use with instances either
-- in the EC2-Classic platform or in a specific VPC.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSecurityGroup.html>
data DeleteSecurityGroup = DeleteSecurityGroup
{ dsgGroupName :: Maybe Text
-- ^ The name of the security group.
, dsgGroupId :: Maybe Text
-- ^ The ID of the security group.
} deriving (Eq, Show, Generic)
instance IsQuery DeleteSecurityGroup
instance Rq DeleteSecurityGroup where
type Er DeleteSecurityGroup = EC2ErrorResponse
type Rs DeleteSecurityGroup = DeleteSecurityGroupResponse
request = query4 ec2 GET "DeleteSecurityGroup"
data DeleteSecurityGroupResponse = DeleteSecurityGroupResponse
{ dsgrRequestId :: !Text
-- ^ The ID of the request.
, dsgrReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
} deriving (Eq, Show, Generic)
instance IsXML DeleteSecurityGroupResponse where
xmlPickler = ec2XML
-- -- | Deletes the specified snapshot.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSnapshot.html>
-- data DeleteSnapshot = DeleteSnapshot
-- { dsSnapshotId :: !Text
-- -- ^ The ID of the Amazon EBS snapshot.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteSnapshot
-- instance AWSRequest EC2 DeleteSnapshot DeleteSnapshotResponse where
-- request = query4 ec2 GET "DeleteSnapshot"
-- data DeleteSnapshotResponse = DeleteSnapshotResponse
-- { dsRequestId :: !Text
-- -- ^ The ID of the request.
-- , dsReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteSnapshotResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the datafeed for Spot Instances. For more information about Spot
-- -- Instances, see Spot Instances in the Amazon Elastic Compute Cloud User
-- -- Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSpotDatafeedSubscription.html>
-- data DeleteSpotDatafeedSubscription = DeleteSpotDatafeedSubscription
-- deriving (Eq, Read, Show, Generic)
-- instance IsQuery DeleteSpotDatafeedSubscription
-- instance IsXML DeleteSpotDatafeedSubscription where
-- xmlPickler = xpEmpty $ Just ec2NS
-- instance AWSRequest EC2 DeleteSpotDatafeedSubscription DeleteSpotDatafeedSubscriptionResponse where
-- request = query4 ec2 GET "DeleteSpotDatafeedSubscription"
-- data DeleteSpotDatafeedSubscriptionResponse = DeleteSpotDatafeedSubscriptionResponse
-- { dsdsRequestId :: !Text
-- -- ^ The ID of the request.
-- , dsdsReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteSpotDatafeedSubscriptionResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified subnet. You must terminate all running instances in
-- -- the subnet before you can delete the subnet.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSubnet.html>
-- data DeleteSubnet = DeleteSubnet
-- { dsSubnetId :: !Text
-- -- ^ The ID of the subnet.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteSubnet
-- instance AWSRequest EC2 DeleteSubnet DeleteSubnetResponse where
-- request = query4 ec2 GET "DeleteSubnet"
-- data DeleteSubnetResponse = DeleteSubnetResponse
-- { dtRequestId :: !Text
-- -- ^ The ID of the request.
-- , dtReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteSubnetResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified set of tags from the specified set of resources. This
-- -- call is designed to follow a DescribeTags call.For more information about
-- -- tags, see Tagging Your Resources in the Amazon Elastic Compute Cloud User
-- -- Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteTags.html>
-- data DeleteTags = DeleteTags
-- { dtResourceId :: Members Text
-- -- ^ The ID of the resource. For example, ami-1a2b3c4d. You can
-- -- specify more than one resource ID.
-- , dtTag :: Members TagType
-- -- ^ The tag's key. You can specify more than one tag to delete.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteTags
-- instance AWSRequest EC2 DeleteTags DeleteTagsResponse where
-- request = query4 ec2 GET "DeleteTags"
-- data DeleteTagsResponse = DeleteTagsResponse
-- { duRequestId :: !Text
-- -- ^ The ID of the request.
-- , duReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteTagsResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified Amazon EBS volume. The volume must be in the
-- -- available state (not attached to an instance). For more information about
-- -- Amazon EBS, see Amazon Elastic Block Store in the Amazon Elastic Compute
-- -- Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVolume.html>
-- data DeleteVolume = DeleteVolume
-- { dvVolumeId :: !Text
-- -- ^ The ID of the volume.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteVolume
-- instance IsXML DeleteVolume where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DeleteVolume DeleteVolumeResponse where
-- request = query4 ec2 GET "DeleteVolume"
-- data DeleteVolumeResponse = DeleteVolumeResponse
-- { dvRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteVolumeResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified VPC. You must detach or delete all gateways and
-- -- resources that are associated with the VPC before you can delete it. For
-- -- example, you must terminate all instances running in the VPC, delete all
-- -- security groups associated with the VPC (except the default one), delete
-- -- all route tables associated with the VPC (except the default one), and so
-- -- on.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpc.html>
-- data DeleteVpc = DeleteVpc
-- { dvVpcId :: !Text
-- -- ^ The ID of the VPC.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteVpc
-- instance AWSRequest EC2 DeleteVpc DeleteVpcResponse where
-- request = query4 ec2 GET "DeleteVpc"
-- data DeleteVpcResponse = DeleteVpcResponse
-- { dwRequestId :: !Text
-- -- ^ The ID of the request.
-- , dwReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteVpcResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified VPN connection.If you're deleting the VPC and its
-- -- associated components, we recommend that you detach the virtual private
-- -- gateway from the VPC and delete the VPC before deleting the VPN
-- -- connection.Another reason to use this command is if you believe that the
-- -- tunnel credentials for your VPN connection have been compromised. In that
-- -- situation, you can delete the VPN connection and create a new one that has
-- -- new keys, without needing to delete the VPC or virtual private gateway. If
-- -- you create a new VPN connection, you must reconfigure the customer gateway
-- -- using the new configuration information returned with the new VPN
-- -- connection ID.For more information about VPN connections, see Adding a
-- -- Hardware Virtual Private Gateway to Your VPC in the Amazon Virtual Private
-- -- Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpnConnection.html>
-- data DeleteVpnConnection = DeleteVpnConnection
-- { dvcVpnConnectionId :: !Text
-- -- ^ The ID of the VPN connection.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteVpnConnection
-- instance AWSRequest EC2 DeleteVpnConnection DeleteVpnConnectionResponse where
-- request = query4 ec2 GET "DeleteVpnConnection"
-- data DeleteVpnConnectionResponse = DeleteVpnConnectionResponse
-- { dvcRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvcReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteVpnConnectionResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified static route associated with a VPN connection between
-- -- an existing virtual private gateway and a VPN customer gateway. The static
-- -- route allows traffic to be routed from the virtual private gateway to the
-- -- VPN customer gateway.For more information about VPN connections, see Adding
-- -- a Hardware Virtual Private Gateway to Your VPC in the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpnConnectionRoute.html>
-- data DeleteVpnConnectionRoute = DeleteVpnConnectionRoute
-- { dvcrDestinationCidrBlock :: !Text
-- -- ^ The CIDR block associated with the local subnet of the customer
-- -- network.
-- , dvcrVpnConnectionId :: !Text
-- -- ^ The ID of the VPN connection.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteVpnConnectionRoute
-- instance IsXML DeleteVpnConnectionRoute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DeleteVpnConnectionRoute DeleteVpnConnectionRouteResponse where
-- request = query4 ec2 GET "DeleteVpnConnectionRoute"
-- data DeleteVpnConnectionRouteResponse = DeleteVpnConnectionRouteResponse
-- { dvcrRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvcrReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteVpnConnectionRouteResponse where
-- xmlPickler = ec2XML
-- -- | Deletes the specified virtual private gateway. We recommend that before you
-- -- delete a virtual private gateway, you detach it from the VPC and delete the
-- -- VPN connection. Note that you don't need to delete the virtual private
-- -- gateway if you plan to delete and recreate the VPN connection between your
-- -- VPC and your network.For more information about virtual private gateways,
-- -- see Adding a Hardware Virtual Private Gateway to Your VPC in the Amazon
-- -- Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpnGateway.html>
-- data DeleteVpnGateway = DeleteVpnGateway
-- { dvgVpnGatewayId :: !Text
-- -- ^ The ID of the virtual private gateway.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeleteVpnGateway
-- instance AWSRequest EC2 DeleteVpnGateway DeleteVpnGatewayResponse where
-- request = query4 ec2 GET "DeleteVpnGateway"
-- data DeleteVpnGatewayResponse = DeleteVpnGatewayResponse
-- { dvgRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvgReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeleteVpnGatewayResponse where
-- xmlPickler = ec2XML
-- -- | Deregisters the specified AMI. After you deregister an AMI, it can't be
-- -- used to launch new instances.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeregisterImage.html>
-- data DeregisterImage = DeregisterImage
-- { diImageId :: !Text
-- -- ^ The ID of the AMI.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DeregisterImage
-- instance IsXML DeregisterImage where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DeregisterImage DeregisterImageResponse where
-- request = query4 ec2 GET "DeregisterImage"
-- data DeregisterImageResponse = DeregisterImageResponse
-- { diRequestId :: !Text
-- -- ^ The ID of the request.
-- , diReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DeregisterImageResponse where
-- xmlPickler = ec2XML
-- -- | Describes the specified attribute of your AWS account.The following are the
-- -- supported account attributes.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAccountAttributes.html>
-- data DescribeAccountAttributes = DescribeAccountAttributes
-- { daaAttributeName :: Members Text
-- -- ^ One or more account attribute names.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeAccountAttributes
-- instance AWSRequest EC2 DescribeAccountAttributes DescribeAccountAttributesResponse where
-- request = query4 ec2 GET "DescribeAccountAttributes"
-- data DescribeAccountAttributesResponse = DescribeAccountAttributesResponse
-- { daaRequestId :: !Text
-- -- ^ The ID of the request.
-- , daaAccountAttributeSet :: !AccountAttributeSetItemType
-- -- ^ A list of the names and values of the requested attributes, each
-- -- one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeAccountAttributesResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your Elastic IP addresses.An Elastic IP address is
-- -- for use in either the EC2-Classic platform or in a VPC. For more
-- -- information, see Elastic IP Addresses in the Amazon Elastic Compute Cloud
-- -- User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAddresses.html>
-- -- data AddressFilter =
-- -- , daDomain :: !Text
-- -- -- ^ Indicates whether the address is for use in a VPC.
-- -- , daInstance-id :: !Text
-- -- -- ^ The instance the address is associated with (if any).
-- -- , daPublic-ip :: !Text
-- -- -- ^ The Elastic IP address.
-- -- , daAllocation-id :: !Text
-- -- -- ^ The allocation ID for the address (VPC only).
-- -- , daAssociation-id :: !Text
-- -- -- ^ The association ID for the address (VPC only).
-- -- , daNetwork-interface-id :: !Text
-- -- -- ^ The network interface (if any) that the address is associated
-- -- -- with (VPC only).
-- -- , daNetwork-interface-owner-id :: !Text
-- -- -- ^ The owner IID.
-- -- , daPrivate-ip-address :: !Text
-- -- -- ^ The private IP address associated with the Elastic IP address
-- -- -- (VPC only).
-- data DescribeAddresses = DescribeAddresses
-- { daPublicIp :: Members Text
-- -- ^ [EC2-Classic] One or more Elastic IP addresses.
-- , daAllocationId :: Members Text
-- -- ^ [EC2-VPC] One or more allocation IDs.
-- , daFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeAddresses
-- instance AWSRequest EC2 DescribeAddresses DescribeAddressesResponse where
-- request = query4 ec2 GET "DescribeAddresses"
-- data DescribeAddressesResponse = DescribeAddressesResponse
-- { daRequestId :: !Text
-- -- ^ The ID of the request.
-- , daAddressesSet :: !DescribeAddressesResponseItemType
-- -- ^ A list of Elastic IP addresses, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeAddressesResponse where
-- xmlPickler = ec2XML
-- | Describes one or more of the Availability Zones that are available to you.
-- The results include zones only for the region you're currently using.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAvailabilityZones.html>
data DescribeAvailabilityZones = DescribeAvailabilityZones
{ dazZoneName :: [Text]
-- ^ One or more Availability Zone names.
, dazFilter :: [Filter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
-- data AvailabilityZoneFilter
-- , dazMessage :: !Text
-- -- ^ Information about the Availability Zone.
-- , dazRegion-name :: !Text
-- -- ^ The region for the Availability Zone (for example, us-east-1).
-- , dazState :: !Text
-- -- ^ The state of the Availability Zone
-- , dazZone-name :: !Text
-- -- ^ The name of the zone.
instance IsQuery DescribeAvailabilityZones
instance Rq DescribeAvailabilityZones where
type Er DescribeAvailabilityZones = EC2ErrorResponse
type Rs DescribeAvailabilityZones = DescribeAvailabilityZonesResponse
request = query4 ec2 GET "DescribeAvailabilityZones"
data DescribeAvailabilityZonesResponse = DescribeAvailabilityZonesResponse
{ dazrRequestId :: !Text
-- ^ The ID of the request.
, dazrAvailabilityZoneInfo :: [AvailabilityZoneItemType]
-- ^ A list of Availability Zones.
} deriving (Eq, Show, Generic)
instance IsXML DescribeAvailabilityZonesResponse where
xmlPickler = ec2XML
-- -- | Describes one or more of your bundling tasks.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeBundleTasks.html>
-- -- data BundleFilter
-- -- , dbtBundle-id :: !Text
-- -- -- ^ The ID of the bundle task.
-- -- , dbtError-code :: !Text
-- -- -- ^ If the task failed, the error code returned.
-- -- , dbtError-message :: !Text
-- -- -- ^ If the task failed, the error message returned.
-- -- , dbtInstance-id :: !Text
-- -- -- ^ The ID of the instance that was bundled.
-- -- , dbtProgress :: !Text
-- -- -- ^ The level of task completion, as a percentage (for example, 20%).
-- -- , dbtS3-bucket :: !Text
-- -- -- ^ The Amazon S3 bucket to store the AMI.
-- -- , dbtS3-prefix :: !Text
-- -- -- ^ The beginning of the AMI name.
-- -- , dbtStart-time :: !UTCTime
-- -- -- ^ The time the task started (for example,
-- -- -- 2008-09-15T17:15:20.000Z).
-- -- , dbtState :: !Text
-- -- -- ^ The state of the task.
-- -- , dbtUpdate-time :: !UTCTime
-- -- -- ^ The time of the most recent update for the task (for example,
-- -- -- 2008-09-15T17:15:20.000Z).
-- data DescribeBundleTasks = DescribeBundleTasks
-- { dbtBundleId :: Members Text
-- -- ^ One or more bundle task IDs.
-- , dbtFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeBundleTasks
-- instance AWSRequest EC2 DescribeBundleTasks DescribeBundleTasksResponse where
-- request = query4 ec2 GET "DescribeBundleTasks"
-- data DescribeBundleTasksResponse = DescribeBundleTasksResponse
-- { dbtRequestId :: !Text
-- -- ^ The ID of the request.
-- , dbtBundleInstanceTasksSet :: !BundleInstanceTaskType
-- -- ^ A list of bundle tasks, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeBundleTasksResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your conversion tasks.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeConversionTasks.html>
-- data DescribeConversionTasks = DescribeConversionTasks
-- { dctConversionTaskId :: Members Text
-- -- ^ One or more conversion task IDs.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeConversionTasks
-- instance AWSRequest EC2 DescribeConversionTasks DescribeConversionTasksResponse where
-- request = query4 ec2 GET "DescribeConversionTasks"
-- data DescribeConversionTasksResponse = DescribeConversionTasksResponse
-- { dctConversionTasks :: !ConversionTaskType
-- -- ^ A list of conversion tasks, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeConversionTasksResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your VPN customer gateways.For more information
-- -- about VPN customer gateways, see Adding a Hardware Virtual Private Gateway
-- -- to Your VPC in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeCustomerGateways.html>
-- -- data GatewayFilter
-- -- , dchBgp-asn :: !Text
-- -- -- ^ The customer gateway's Border Gateway Protocol (BGP) Autonomous
-- -- -- System Number (ASN).
-- -- , dchCustomer-gateway-id :: !Text
-- -- -- ^ The ID of the customer gateway.
-- -- , dchIp-address :: !Text
-- -- -- ^ The IP address of the customer gateway's Internet-routable
-- -- -- external interface (for example, 12.1.2.3).
-- -- , dchState :: !Text
-- -- -- ^ The state of the customer gateway.
-- -- , dchType :: !Text
-- -- -- ^ The type of customer gateway. Currently the only supported type
-- -- -- is ipsec.1.
-- -- , dchTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dchTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dchTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dchKey :: !Text
-- -- -- ^
-- data DescribeCustomerGateways = DescribeCustomerGateways
-- { dchCustomerGatewayId :: Members Text
-- -- ^ One or more customer gateway IDs.
-- , dchFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeCustomerGateways
-- instance AWSRequest EC2 DescribeCustomerGateways DescribeCustomerGatewaysResponse where
-- request = query4 ec2 GET "DescribeCustomerGateways"
-- data DescribeCustomerGatewaysResponse = DescribeCustomerGatewaysResponse
-- { dchRequestId :: !Text
-- -- ^ The ID of the request.
-- , dchCustomerGatewaySet :: !CustomerGatewayType
-- -- ^ A list of customer gateways, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeCustomerGatewaysResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your DHCP options sets.For more information about
-- -- DHCP options sets, see DHCP Options Sets in the Amazon Virtual Private
-- -- Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeDhcpOptions.html>
-- -- data DhcpFilter
-- -- , ddpDhcp-options-id :: !Text
-- -- -- ^ The ID of a set of DHCP options.
-- -- , ddpKey :: !Text
-- -- -- ^ The key for one of the options (for example, domain-name).
-- -- , ddpValue :: !Text
-- -- -- ^ The value for one of the options.
-- -- , ddpTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , ddpTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , ddpTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , ddqKey :: !Text
-- -- -- ^
-- data DescribeDhcpOptions = DescribeDhcpOptions
-- { ddpDhcpOptionsId :: Members Text
-- -- ^ The IDs of one or more DHCP options sets.
-- , ddpFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeDhcpOptions
-- instance AWSRequest EC2 DescribeDhcpOptions DescribeDhcpOptionsResponse where
-- request = query4 ec2 GET "DescribeDhcpOptions"
-- data DescribeDhcpOptionsResponse = DescribeDhcpOptionsResponse
-- { ddqRequestId :: !Text
-- -- ^ The ID of the request.
-- , ddqDhcpOptionsSet :: !DhcpOptionsType
-- -- ^ A list of DHCP options sets, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeDhcpOptionsResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your export tasks.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeExportTasks.html>
-- data DescribeExportTasks = DescribeExportTasks
-- { detExportTaskId :: Members Text
-- -- ^ One or more export task IDs.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeExportTasks
-- instance AWSRequest EC2 DescribeExportTasks DescribeExportTasksResponse where
-- request = query4 ec2 GET "DescribeExportTasks"
-- data DescribeExportTasksResponse = DescribeExportTasksResponse
-- { detRequestId :: !Text
-- -- ^ The ID of the request.
-- , detExportTaskSet :: !ExportTaskResponseType
-- -- ^ A list of export tasks, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeExportTasksResponse where
-- xmlPickler = ec2XML
-- -- | Describes an attributes of an AMI. You can specify only one attribute at a
-- -- time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImageAttribute.html>
-- data DescribeImageAttribute = DescribeImageAttribute
-- { diaImageId :: !Text
-- -- ^ The ID of the AMI.
-- , diaAttribute :: !Text
-- -- ^ The AMI attribute.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeImageAttribute
-- instance IsXML DescribeImageAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DescribeImageAttribute DescribeImageAttributeResponse where
-- request = query4 ec2 GET "DescribeImageAttribute"
-- data DescribeImageAttributeResponse = DescribeImageAttributeResponse
-- { diaRequestId :: !Text
-- -- ^ The ID of the request.
-- , dibImageId :: !Text
-- -- ^ The ID of the AMI.
-- , dibLaunchPermission :: !LaunchPermissionItemType
-- -- ^ A list of launch permissions, each one wrapped in an item
-- -- element.
-- , dibProductCodes :: !ProductCodeItemType
-- -- ^ A list of product codes, each one wrapped in an item element that
-- -- contains a product code and a product code type.
-- , dibKernel :: !Text
-- -- ^ The kernel ID, wrapped in a value element.
-- , dibRamdisk :: !Text
-- -- ^ The RAM disk ID, wrapped in a value element.
-- , dibDescription :: !Text
-- -- ^ A user-created description for the AMI, wrapped in a value
-- -- element.
-- , dibBlockDeviceMapping :: !BlockDeviceMappingItemType
-- -- ^ One or more block device mapping entries, each one wrapped in an
-- -- item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeImageAttributeResponse where
-- xmlPickler = ec2XML
-- | Describes one or more of the images (AMIs, AKIs, and ARIs) available to
-- you. Images available to you include public images, private images that you
-- own, and private images owned by other AWS accounts but for which you have
-- explicit launch permissions.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html>
data DescribeImages = DescribeImages
{ djExecutableBy :: [Text]
-- ^ Describes the images for which the specified user has explicit
-- launch permissions. The user ID can be an AWS account ID, self to
-- return images for which the sender of the request has explicit
-- launch permissions, or all to return AMIs with public launch permissions.
, djImageId :: [Text]
-- ^ One or more image IDs.
, djOwner :: [Text]
-- ^ Describes images owned by the specified owners. Use the IDs
-- amazon, aws-marketplace, and self to describe images owned by
-- Amazon, AWS Marketplace, or you, respectively.
, djFilter :: [Filter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeImages
instance Rq DescribeImages where
type Er DescribeImages = EC2ErrorResponse
type Rs DescribeImages = DescribeImagesResponse
request = query4 ec2 GET "DescribeImages"
data DescribeImagesResponse = DescribeImagesResponse
{ djRequestId :: !Text
-- ^ The ID of the request.
, djImagesSet :: [DescribeImagesResponseItemType]
-- ^ A list of images.
} deriving (Eq, Show, Generic)
instance IsXML DescribeImagesResponse where
xmlPickler = ec2XML
-- -- | Describes an attribute of the specified instance. You can specify only one
-- -- attribute at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceAttribute.html>
-- data DescribeInstanceAttribute = DescribeInstanceAttribute
-- { diaInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , dibAttribute :: !Text
-- -- ^ The instance attribute.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeInstanceAttribute
-- instance IsXML DescribeInstanceAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DescribeInstanceAttribute DescribeInstanceAttributeResponse where
-- request = query4 ec2 GET "DescribeInstanceAttribute"
-- data DescribeInstanceAttributeResponse = DescribeInstanceAttributeResponse
-- { dibRequestId :: !Text
-- -- ^ The ID of the request.
-- , dibInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , dicBlockDeviceMapping :: !InstanceBlockDeviceMappingResponseItemType
-- -- ^ The block device mapping of the instance.
-- , dicDisableApiTermination :: !Bool
-- -- ^ If the value is true, you can't terminate the instance through
-- -- the Amazon EC2 console, CLI, or API; otherwise, you can.
-- , dicEbsOptimized :: !Bool
-- -- ^ Indicates whether the instance is optimized for EBS I/O.
-- , dicGroupSet :: !GroupItemType
-- -- ^ The security groups associated with the instance.
-- , dicInstanceInitiatedShutdownBehavior :: !Text
-- -- ^ Indicates whether an instance stops or terminates when you
-- -- initiate shutdown from the instance (using the operating system
-- -- command for system shutdown).
-- , dicInstanceType :: !Text
-- -- ^ The instance type.
-- , dicKernel :: !Text
-- -- ^ The kernel ID.
-- , dicProductCodes :: !ProductCodesSetItemType
-- -- ^ A list of product codes.
-- , dicRamdisk :: !Text
-- -- ^ The RAM disk ID.
-- , dicRootDeviceName :: !Text
-- -- ^ The name of the root device (for example, /dev/sda1).
-- , dicSourceDestCheck :: !Bool
-- -- ^ Indicates whether source/destination checking is enabled. A value
-- -- of true means checking is enabled, and false means checking is
-- -- disabled. This value must be false for a NAT instance to perform
-- -- NAT.
-- , dicUserData :: !Text
-- -- ^ The Base64-encoded MIME user data.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeInstanceAttributeResponse where
-- xmlPickler = ec2XML
-- | Describes one or more of your instances.
--
-- * If you specify one or more instance IDs, Amazon EC2 returns information
-- for those instances.
--
-- * If you do not specify instance IDs, Amazon EC2 returns information for all
-- relevant instances.
--
-- * If you specify an invalid instance ID, an error is returned.
--
-- * If you specify an instance that you do not own, it is not included in the
-- returned results.
--
-- * Recently terminated instances might appear in the returned
-- results. This interval is usually less than one hour.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html>
data DescribeInstances = DescribeInstances
{ diInstanceId :: [Text]
-- ^ One or more instance IDs.
, diFilter :: [Filter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeInstances
instance Rq DescribeInstances where
type Er DescribeInstances = EC2ErrorResponse
type Rs DescribeInstances = DescribeInstancesResponse
request = query4 ec2 GET "DescribeInstances"
data DescribeInstancesResponse = DescribeInstancesResponse
{ dirRequestId :: !Text
-- ^ The ID of the request.
, dirReservationSet :: [ReservationInfoType]
-- ^ A list of reservations, each one wrapped in an item element.
} deriving (Eq, Show, Generic)
instance IsXML DescribeInstancesResponse where
xmlPickler = ec2XML
-- -- | Describes the status of one or more instances, including any scheduled
-- -- events.Instance status has two main components: Instance status provides
-- -- information about four types of scheduled events for an instance that may
-- -- require your attention: When your instance is retired, it will either be
-- -- terminated (if its root device type is the instance-store) or stopped (if
-- -- its root device type is an EBS volume). Instances stopped due to retirement
-- -- will not be restarted, but you can do so manually. You can also avoid
-- -- retirement of EBS-backed instances by manually restarting your instance
-- -- when its event code is instance-retirement. This ensures that your instance
-- -- is started on a different underlying host.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceStatus.html>
-- -- data InstanceStatusFilter
-- -- , disAvailability-zone :: !Text
-- -- -- ^ The Availability Zone of the instance.
-- -- , disEvent :: Members eventType
-- -- -- ^ The code identifying the type of event.
-- -- , disInstance-state-name :: !Text
-- -- -- ^ The state of the instance.
-- -- , disInstance-state-code :: !Integer
-- -- -- ^ A code representing the state of the instance. The high byte is
-- -- -- an opaque internal value and should be ignored. The low byte is
-- -- -- set based on the state represented
-- -- , disSystem-status :: Members system-statusType
-- -- -- ^ The system status of the instance.
-- -- , disInstance-status :: Members instance-statusType
-- -- -- ^ The status of the instance.
-- data DescribeInstanceStatus = DescribeInstanceStatus
-- { disInstanceId :: Maybe Text
-- -- ^ One or more instance IDs.
-- , disIncludeAllInstances :: Maybe Bool
-- -- ^ When true, includes the health status for all instances. When
-- -- false, includes the health status for running instances only.
-- , disMaxResults :: Maybe Integer
-- -- ^ The maximum number of paginated instance items per response.
-- , disNextToken :: Maybe Text
-- -- ^ The next paginated set of results to return.
-- , disFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeInstanceStatus
-- instance AWSRequest EC2 DescribeInstanceStatus DescribeInstanceStatusResponse where
-- request = query4 ec2 GET "DescribeInstanceStatus"
-- data DescribeInstanceStatusResponse = DescribeInstanceStatusResponse
-- { disRequestId :: !Text
-- -- ^ The ID of the request.
-- , disInstanceStatusSet :: !InstanceStatusItemType
-- -- ^ A list of instances status descriptions, each one wrapped in an
-- -- item element.
-- , ditNextToken :: !Text
-- -- ^ The next paginated set of results to return.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeInstanceStatusResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your Internet gateways.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInternetGateways.html>
-- -- data GatewayFilter
-- -- , dihAttachment :: Members attachmentType
-- -- -- ^ The current state of the attachment between the gateway and the
-- -- -- VPC. Returned only if a VPC is attached.
-- -- , dihInternet-gateway-id :: !Text
-- -- -- ^ The ID of the Internet gateway.
-- -- , dihTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dihTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dihTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dihKey :: !Text
-- -- -- ^
-- data DescribeInternetGateways = DescribeInternetGateways
-- { dihInternetGatewayId :: Members Text
-- -- ^ One or more Internet gateway IDs.
-- , dihFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeInternetGateways
-- instance AWSRequest EC2 DescribeInternetGateways DescribeInternetGatewaysResponse where
-- request = query4 ec2 GET "DescribeInternetGateways"
-- data DescribeInternetGatewaysResponse = DescribeInternetGatewaysResponse
-- { dihRequestId :: !Text
-- -- ^ The ID of the request.
-- , dihInternetGatewaySet :: !InternetGatewayType
-- -- ^ A list of Internet gateways, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeInternetGatewaysResponse where
-- xmlPickler = ec2XML
-- -- data KeyPairFilter
-- -- , dkqFingerprint :: !Text
-- -- -- ^ The fingerprint of the key pair.
-- -- , dkqKey-name :: !Text
-- -- -- ^ The name of the key pair.
-- | Describes one or more of your key pairs.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html>
data DescribeKeyPairs = DescribeKeyPairs
{ dkqKeyName :: [Text]
-- ^ One or more key pair names.
, dkqFilter :: [Filter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeKeyPairs
instance Rq DescribeKeyPairs where
type Er DescribeKeyPairs = EC2ErrorResponse
type Rs DescribeKeyPairs = DescribeKeyPairsResponse
request = query4 ec2 GET "DescribeKeyPairs"
data DescribeKeyPairsResponse = DescribeKeyPairsResponse
{ dkqRequestId :: !Text
-- ^ The ID of the request.
, dkqKeySet :: [DescribeKeyPairsResponseItemType]
-- ^ A list of key pairs.
} deriving (Eq, Show, Generic)
instance IsXML DescribeKeyPairsResponse where
xmlPickler = ec2XML
-- -- | Describes one or more of your network ACLs.For more information about
-- -- network ACLs, see Network ACLs in the Amazon Virtual Private Cloud User
-- -- Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkAcls.html>
-- -- data NetworkAclFilter
-- -- , dnbAssociation :: Members associationType
-- -- -- ^ The ID of an association ID for the ACL.
-- -- , dnbDefault :: !Bool
-- -- -- ^ Indicates whether the ACL is the default network ACL for the VPC.
-- -- , dnbEntry :: Members entryType
-- -- -- ^ The CIDR range specified in the entry.
-- -- , dnbNetwork-acl-id :: !Text
-- -- -- ^ The ID of the network ACL.
-- -- , dnbTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dnbTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dnbTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dnbKey :: !Text
-- -- -- ^ The ID of the VPC for the network ACL.
-- -- , dnbVpc-id :: !Text
-- -- -- ^
-- data DescribeNetworkAcls = DescribeNetworkAcls
-- { dnbNetworkAclId :: Members Text
-- -- ^ One or more network ACL IDs.
-- , dnbFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeNetworkAcls
-- instance AWSRequest EC2 DescribeNetworkAcls DescribeNetworkAclsResponse where
-- request = query4 ec2 GET "DescribeNetworkAcls"
-- data DescribeNetworkAclsResponse = DescribeNetworkAclsResponse
-- { dnbRequestId :: !Text
-- -- ^ The ID of the request.
-- , dnbNetworkAclSet :: !NetworkAclType
-- -- ^ A list of network ACLs, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeNetworkAclsResponse where
-- xmlPickler = ec2XML
-- -- | Describes a network interface attribute. You can specify only one attribute
-- -- at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkInterfaceAttribute.html>
-- data DescribeNetworkInterfaceAttribute = DescribeNetworkInterfaceAttribute
-- { dniaNetworkInterfaceId :: !Text
-- -- ^ The ID of the network interface.
-- , dniaAttribute :: !Text
-- -- ^ The attribute of the network interface.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeNetworkInterfaceAttribute
-- instance IsXML DescribeNetworkInterfaceAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DescribeNetworkInterfaceAttribute DescribeNetworkInterfaceAttributeResponse where
-- request = query4 ec2 GET "DescribeNetworkInterfaceAttribute"
-- data DescribeNetworkInterfaceAttributeResponse = DescribeNetworkInterfaceAttributeResponse
-- { dniaRequestId :: !Text
-- -- ^ The ID of the request.
-- , dnibNetworkInterfaceId :: !Text
-- -- ^ The ID of the network interface.
-- , dnibDescription :: !Text
-- -- ^ The description of the network interface.
-- , dnibSourceDestCheck :: !Bool
-- -- ^ Indicates whether source/destination checking is enabled.
-- , dnibGroupSet :: !GroupItemType
-- -- ^ The security groups associated with the network interface.
-- , dnibAttachment :: !NetworkInterfaceAttachmentType
-- -- ^ The attachment (if any) of the network interface.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeNetworkInterfaceAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your network interfaces.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkInterfaces.html>
-- -- data NetworkInterfaceFilter
-- -- , dnjAddresses :: Members addressesType
-- -- -- ^ The private IP addresses associated with the network interface.
-- -- , dnjAssociation :: Members associationType
-- -- -- ^ The association ID returned when the network interface was
-- -- -- associated with an IP address.
-- -- , dnjAttachment :: Members attachmentType
-- -- -- ^ The ID of the interface attachment.
-- -- , dnjAvailability-zone :: !Text
-- -- -- ^ The Availability Zone of the network interface.
-- -- , dnjDescription :: !Text
-- -- -- ^ The description of the network interface.
-- -- , dnjGroup-id :: !Text
-- -- -- ^ The ID of a security group associated with the network interface.
-- -- , dnjGroup-name :: !Text
-- -- -- ^ The name of a security group associated with the network
-- -- -- interface.
-- -- , dnjMac-address :: !Text
-- -- -- ^ The MAC address of the network interface.
-- -- , dnjNetwork-interface-id :: !Text
-- -- -- ^ The ID of the network interface.
-- -- , dnjOwner-id :: !Text
-- -- -- ^ The AWS account ID of the network interface owner.
-- -- , dnjPrivate-ip-address :: !Text
-- -- -- ^ The private IP address or addresses of the network interface.
-- -- , dnjPrivate-dns-name :: !Text
-- -- -- ^ The private DNS name of the network interface.
-- -- , dnjRequester-id :: !Text
-- -- -- ^ The ID of the entity that launched the instance on your behalf
-- -- -- (for example, AWS Management Console, Auto Scaling, and so on).
-- -- , dnjRequester-managed :: !Bool
-- -- -- ^ Indicates whether the network interface is being managed by an
-- -- -- AWS service (for example, AWS Management Console, Auto Scaling,
-- -- -- and so on).
-- -- , dnjSource-dest-check :: !Bool
-- -- -- ^ Indicates whether the network interface performs
-- -- -- source/destination checking. A value of true means checking is
-- -- -- enabled, and false means checking is disabled. The value must be
-- -- -- false for the network interface to perform Network Address
-- -- -- Translation (NAT) in your VPC.
-- -- , dnjStatus :: !Text
-- -- -- ^ The status of the network interface. If the network interface is
-- -- -- not attached to an instance, the status shows available; if a
-- -- -- network interface is attached to an instance the status shows
-- -- -- in-use.
-- -- , dnjSubnet-id :: !Text
-- -- -- ^ The ID of the subnet for the network interface.
-- -- , dnjTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dnjTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dnjTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dnjKey :: !Text
-- -- -- ^ The ID of the VPC for the network interface.
-- -- , dnjVpc-id :: !Text
-- -- -- ^
-- data DescribeNetworkInterfaces = DescribeNetworkInterfaces
-- { dnjNetworkInterfaceId :: Members Text
-- -- ^ One or more network interface IDs.
-- , dnjFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeNetworkInterfaces
-- instance AWSRequest EC2 DescribeNetworkInterfaces DescribeNetworkInterfacesResponse where
-- request = query4 ec2 GET "DescribeNetworkInterfaces"
-- data DescribeNetworkInterfacesResponse = DescribeNetworkInterfacesResponse
-- { dnjRequestId :: !Text
-- -- ^ The ID of the request.
-- , dnjNetworkInterfaceSet :: !NetworkInterfaceType
-- -- ^ Information about the network interfaces, each one wrapped in an
-- -- item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeNetworkInterfacesResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your placement groups. For more information about
-- -- placement groups and cluster instances, see Cluster Instances in the Amazon
-- -- Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribePlacementGroups.html>
-- -- data PlacementGroupFilter
-- -- , dphGroup-name :: !Text
-- -- -- ^ The name of the placement group.
-- -- , dphState :: !Text
-- -- -- ^ The state of the placement group.
-- -- , dphStrategy :: !Text
-- -- -- ^ The strategy of the placement group.
-- data DescribePlacementGroups = DescribePlacementGroups
-- { dphGroupName :: Members Text
-- -- ^ One or more placement group names.
-- , dphFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribePlacementGroups
-- instance AWSRequest EC2 DescribePlacementGroups DescribePlacementGroupsResponse where
-- request = query4 ec2 GET "DescribePlacementGroups"
-- data DescribePlacementGroupsResponse = DescribePlacementGroupsResponse
-- { dphRequestId :: !Text
-- -- ^ The ID of the request.
-- , dphPlacementGroupSet :: !PlacementGroupInfoType
-- -- ^ A list of placement groups, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribePlacementGroupsResponse where
-- xmlPickler = ec2XML
-- -- data RegionFilter
-- -- , drEndpoint :: !Text
-- -- -- ^ The endpoint of the region (for example,
-- -- -- ec2.us-east-1.amazonaws.com).
-- -- , drRegion-name :: !Text
-- -- -- ^ The name of the region.
-- | Describes one or more regions that are currently available to you.For a
-- list of the regions supported by Amazon EC2, see Regions and Endpoints.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRegions.html>
data DescribeRegions = DescribeRegions
{ drRegionName :: [Region]
-- ^ One or more region names.
, drFilter :: [Filter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeRegions
instance Rq DescribeRegions where
type Er DescribeRegions = EC2ErrorResponse
type Rs DescribeRegions = DescribeRegionsResponse
request = query4 ec2 GET "DescribeRegions"
data DescribeRegionsResponse = DescribeRegionsResponse
{ drrRequestId :: !Text
-- ^ The ID of the request.
, drrRegionInfo :: [RegionItemType]
-- ^ A list of regions, each one wrapped in an item element.
} deriving (Eq, Show, Generic)
instance IsXML DescribeRegionsResponse where
xmlPickler = ec2XML
-- -- | Describes one or more of the Reserved Instances that you purchased.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstances.html>
-- -- data ReservedInstanceFilter
-- -- , driAvailability-zone :: !Text
-- -- -- ^ The Availability Zone where the Reserved Instance can be used.
-- -- , driDuration :: !Integer
-- -- -- ^ The duration of the Reserved Instance (one year or three years),
-- -- -- in seconds.
-- -- , driFixed-price :: !Double
-- -- -- ^ The purchase price of the Reserved Instance (for example, 9800.0)
-- -- , driInstance-type :: !Text
-- -- -- ^ The instance type on which the Reserved Instance can be used.
-- -- , driProduct-description :: !Text
-- -- -- ^ The product description of the Reserved Instance.
-- -- , driReserved-instances-id :: !Text
-- -- -- ^ The ID of the Reserved Instance.
-- -- , driStart :: !UTCTime
-- -- -- ^ The time at which the Reserved Instance purchase request was
-- -- -- placed (for example, 2010-08-07T11:54:42.000Z).
-- -- , driState :: !Text
-- -- -- ^ The state of the Reserved Instance.
-- -- , driTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , driTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , driTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , driKey :: !Double
-- -- -- ^ The usage price of the Reserved Instance, per hour (for example,
-- -- -- 0.84)
-- -- , driUsage-price :: !Text
-- -- -- ^
-- data DescribeReservedInstances = DescribeReservedInstances
-- { driReservedInstancesId :: Members Text
-- -- ^ One or more Reserved Instance IDs.
-- , driOfferingType :: Maybe Text
-- -- ^ The Reserved Instance offering type.
-- , driFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeReservedInstances
-- instance AWSRequest EC2 DescribeReservedInstances DescribeReservedInstancesResponse where
-- request = query4 ec2 GET "DescribeReservedInstances"
-- data DescribeReservedInstancesResponse = DescribeReservedInstancesResponse
-- { driRequestId :: !Text
-- -- ^ The ID of the request.
-- , driReservedInstancesSet :: !DescribeReservedInstancesResponseSetItemType
-- -- ^ A list of Reserved Instances, each one wrapped in an item
-- -- element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeReservedInstancesResponse where
-- xmlPickler = ec2XML
-- -- | Describes your account's Reserved Instance listings in the Reserved
-- -- Instance Marketplace. This call returns information, such as the ID of the
-- -- Reserved Instance to which a listing is associated.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstancesListings.html>
-- -- data ReservedInstanceFilter
-- -- , drilStatus :: !Text
-- -- -- ^ Status of the Reserved Instance listing.
-- -- , drilStatus-message :: !Text
-- -- -- ^ Reason for the status.
-- -- , drilReserved-instances-listing-id :: !Text
-- -- -- ^ The ID of the Reserved Instances listing.
-- -- , drilReserved-instances-id :: !Text
-- -- -- ^ The ID of the Reserved Instances.
-- data DescribeReservedInstancesListings = DescribeReservedInstancesListings
-- { drilReservedInstancesListingId :: Members DescribeReservedInstancesListingSetItemType
-- -- ^ The information about the Reserved Instance listing wrapped in an
-- -- item element.
-- , drilReservedInstancesId :: Members DescribeReservedInstancesSetItemType
-- -- ^ The set of Reserved Instances IDs which are used to see
-- -- associated listings.
-- , drilFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeReservedInstancesListings
-- instance AWSRequest EC2 DescribeReservedInstancesListings DescribeReservedInstancesListingsResponse where
-- request = query4 ec2 GET "DescribeReservedInstancesListings"
-- data DescribeReservedInstancesListingsResponse = DescribeReservedInstancesListingsResponse
-- { drilRequestId :: !Text
-- -- ^ The ID of the request.
-- , drilReservedInstancesListingsSet :: !DescribeReservedInstancesListingsResponseSetItemType
-- -- ^ The Reserved Instance listing information wrapped in an item
-- -- element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeReservedInstancesListingsResponse where
-- xmlPickler = ec2XML
-- -- | Describes Reserved Instance offerings that are available for purchase.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstancesOfferings.html>
-- data ReservedInstancesOfferingFilter
-- -- , drioInstanceTenancy :: Maybe Text
-- -- -- ^ The tenancy of the Reserved Instance offering. A Reserved
-- -- -- Instance with tenancy of dedicated will run on single-tenant
-- -- -- hardware and can only be launched within a VPC.
-- -- , drioOfferingType :: Maybe Text
-- -- -- ^ The Reserved Instance offering type.
-- -- , drioIncludeMarketplace :: Maybe Bool
-- -- -- ^ Include Marketplace offerings in the response.
-- -- , drioMinDuration :: Maybe Integer
-- -- -- ^ Minimum duration (in seconds) to filter when searching for
-- -- -- offerings.
-- -- , drioMaxDuration :: Maybe Integer
-- -- -- ^ Maximum duration (in seconds) to filter when searching for
-- -- -- offerings.
-- -- , drioMaxInstanceCount :: Maybe Integer
-- -- -- ^ Maximum number of instances to filter when searching for
-- -- -- offerings.
-- -- , drioNextToken :: Maybe Text
-- -- -- ^ Token to use when requesting the next paginated set of offerings.
-- -- , drioMaxResults :: Maybe Integer
-- -- -- ^ Maximum number of offerings to return.
-- -- , drioAvailability-zone :: !Text
-- -- -- ^ The Availability Zone where the Reserved Instance can be used.
-- -- , drioDuration :: !Integer
-- -- -- ^ The duration of the Reserved Instance (for example, one year or
-- -- -- three years), in seconds.
-- -- , drioFixed-price :: !Double
-- -- -- ^ The purchase price of the Reserved Instance (for example, 9800.0)
-- -- , drioInstance-type :: !Text
-- -- -- ^ The Amazon EC2 instance type on which the Reserved Instance can
-- -- -- be used.
-- -- , drioMarketplace :: !Bool
-- -- -- ^ Set to true to show only Reserved Instance Marketplace offerings.
-- -- -- When this filter is not used, which is the default behavior, all
-- -- -- offerings from AWS and Reserved Instance Marketplace are listed.
-- -- , drioProduct-description :: !Text
-- -- -- ^ The description of the Reserved Instance.
-- -- , drioReserved-instances-offering-id :: !Text
-- -- -- ^ The Reserved Instances offering ID.
-- -- , drioUsage-price :: !Double
-- -- -- ^ The usage price of the Reserved Instance, per hour (for example,
-- -- -- 0.84)
-- data DescribeReservedInstancesOfferings = DescribeReservedInstancesOfferings
-- { drioReservedInstancesOfferingId :: Members Text
-- -- ^ One or more Reserved Instances offering IDs.
-- , drioInstanceType :: Maybe Text
-- -- ^ The Amazon EC2 instance type on which the Reserved Instance can
-- -- be used. See Available Instance Types for more information.
-- , drioAvailabilityZone :: Maybe Text
-- -- ^ The Availability Zone in which the Reserved Instance can be used.
-- , drioProductDescription :: Maybe Text
-- -- ^ The Reserved Instance description. Instances that include (Amazon
-- -- VPC) in the description are for use with Amazon VPC.
-- , drioFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeReservedInstancesOfferings
-- instance AWSRequest EC2 DescribeReservedInstancesOfferings DescribeReservedInstancesOfferingsResponse where
-- request = query4 ec2 GET "DescribeReservedInstancesOfferings"
-- data DescribeReservedInstancesOfferingsResponse = DescribeReservedInstancesOfferingsResponse
-- { drioRequestId :: !Text
-- -- ^ The ID of the request.
-- , drioReservedInstancesOfferingsSet :: !DescribeReservedInstancesOfferingsResponseSetItemType
-- -- ^ A list of Reserved Instances offerings. Each offering's
-- -- information is wrapped in an item element.
-- , dripNextToken :: !Text
-- -- ^ The next paginated set of results to return.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeReservedInstancesOfferingsResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your route tables.For more information about route
-- -- tables, see Route Tables in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRouteTables.html>
-- -- data RouteTableFilter
-- -- , druAssociation :: Members associationType
-- -- -- ^ The ID of an association ID for the route table.
-- -- , druRoute-table-id :: !Text
-- -- -- ^ The ID of the route table.
-- -- , druRoute :: Members routeType
-- -- -- ^ The CIDR range specified in a route in the table.
-- -- , druTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , druTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , druTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , druKey :: !Text
-- -- -- ^ The ID of the VPC for the route table.
-- -- , druVpc-id :: !Text
-- -- -- ^
-- data DescribeRouteTables = DescribeRouteTables
-- { druRouteTableId :: Members Text
-- -- ^ One or more route table IDs.
-- , druFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeRouteTables
-- instance AWSRequest EC2 DescribeRouteTables DescribeRouteTablesResponse where
-- request = query4 ec2 GET "DescribeRouteTables"
-- data DescribeRouteTablesResponse = DescribeRouteTablesResponse
-- { druRequestId :: !Text
-- -- ^ The ID of the request.
-- , druRouteTableSet :: !RouteTableType
-- -- ^ A list of route tables, each one wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeRouteTablesResponse where
-- xmlPickler = ec2XML
-- | A security group is for use with instances either in the EC2-Classic
-- platform or in a specific VPC.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSecurityGroups.html>
data DescribeSecurityGroups = DescribeSecurityGroups
{ dshGroupName :: [Text]
-- ^ A list of group names.
-- NB: doesn't work for non-default VPCs, use 'dshFilter' instead.
, dshGroupId :: [Text]
-- ^ A list of group ids.
, dshFilter :: [Filter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeSecurityGroups
instance Rq DescribeSecurityGroups where
type Er DescribeSecurityGroups = EC2ErrorResponse
type Rs DescribeSecurityGroups = DescribeSecurityGroupsResponse
request = query4 ec2 GET "DescribeSecurityGroups"
data DescribeSecurityGroupsResponse = DescribeSecurityGroupsResponse
{ dshrRequestId :: !Text
-- ^ The ID of the request.
, dshrSecurityGroupInfo :: [SecurityGroupItemType]
-- ^ A list of security groups.
} deriving (Eq, Show, Generic)
instance IsXML DescribeSecurityGroupsResponse where
xmlPickler = ec2XML
-- -- | Describes an attribute of the specified snapshot. You can specify only one
-- -- attribute at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshotAttribute.html>
-- data DescribeSnapshotAttribute = DescribeSnapshotAttribute
-- { dsaSnapshotId :: !Text
-- -- ^ The ID of the Amazon EBS snapshot.
-- , dsaAttribute :: !Text
-- -- ^ The snapshot attribute.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeSnapshotAttribute
-- instance IsXML DescribeSnapshotAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DescribeSnapshotAttribute DescribeSnapshotAttributeResponse where
-- request = query4 ec2 GET "DescribeSnapshotAttribute"
-- data DescribeSnapshotAttributeResponse = DescribeSnapshotAttributeResponse
-- { dsaRequestId :: !Text
-- -- ^ The ID of the request.
-- , dsbSnapshotId :: !Text
-- -- ^ The ID of the Amazon EBS snapshot.
-- , dsbCreateVolumePermission :: !CreateVolumePermissionItemType
-- -- ^ A list of permissions for creating volumes from the snapshot.
-- -- Each permission is wrapped in an item element.
-- , dsbProductCodes :: !ProductCodesSetItemType
-- -- ^ A list of product codes. Each product code is wrapped in an item
-- -- element type that contains a product code and a type.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeSnapshotAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of the Amazon EBS snapshots available to you.
-- -- Snapshots available to you include public snapshots available for any AWS
-- -- account to launch, private snapshots you own, and private snapshots owned
-- -- by another AWS account but for which you've been given explicit create
-- -- volume permissions.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html>
-- -- data SnapshotFilter
-- -- , dtOwner-alias :: !Text
-- -- -- ^ The AWS account alias (for example, amazon) that owns the
-- -- -- snapshot.
-- -- , dtOwner-id :: !Text
-- -- -- ^ The ID of the AWS account that owns the snapshot.
-- -- , dtProgress :: !Text
-- -- -- ^ The progress of the snapshot, as a percentage (for example, 80%).
-- -- , dtSnapshot-id :: !Text
-- -- -- ^ The snapshot ID.
-- -- , dtStart-time :: !UTCTime
-- -- -- ^ The time stamp when the snapshot was initiated.
-- -- , dtStatus :: !Text
-- -- -- ^ The status of the snapshot.
-- -- , dtTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dtTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dtTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dtKey :: !Text
-- -- -- ^ The ID of the volume the snapshot is for.
-- -- , dtVolume-id :: !Text
-- -- -- ^ The size of the volume, in GiB (for example, 20).
-- -- , dtVolume-size :: !Text
-- -- -- ^
-- data DescribeSnapshots = DescribeSnapshots
-- { dtSnapshotId :: Members Text
-- -- ^ One or more snapshot IDs.
-- , dtOwner :: Members Text
-- -- ^ Returns the snapshots owned by the specified owner. Multiple
-- -- owners can be specified.
-- , dtRestorableBy :: Members Text
-- -- ^ One or more AWS accounts IDs that can create volumes from the
-- -- snapshot.
-- , dtFilter :: Members Text
-- -- ^ The name of a filter.
-- , dtDescription :: !Text
-- -- ^ A description of the snapshot.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeSnapshots
-- instance AWSRequest EC2 DescribeSnapshots DescribeSnapshotsResponse where
-- request = query4 ec2 GET "DescribeSnapshots"
-- data DescribeSnapshotsResponse = DescribeSnapshotsResponse
-- { dyRequestId :: !Text
-- -- ^ The ID of the request.
-- , dySnapshotSet :: !DescribeSnapshotsSetItemResponseType
-- -- ^ A list of snapshots. Each snapshot is wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeSnapshotsResponse where
-- xmlPickler = ec2XML
-- -- | Describes the datafeed for Spot Instances. For more information about Spot
-- -- Instances, see Spot Instances in the Amazon Elastic Compute Cloud User
-- -- Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotDatafeedSubscription.html>
-- data DescribeSpotDatafeedSubscription = DescribeSpotDatafeedSubscription
-- deriving (Eq, Read, Show, Generic)
-- instance IsQuery DescribeSpotDatafeedSubscription
-- instance IsXML DescribeSpotDatafeedSubscription where
-- xmlPickler = xpEmpty $ Just ec2NS
-- instance AWSRequest EC2 DescribeSpotDatafeedSubscription DescribeSpotDatafeedSubscriptionResponse where
-- request = query4 ec2 GET "DescribeSpotDatafeedSubscription"
-- data DescribeSpotDatafeedSubscriptionResponse = DescribeSpotDatafeedSubscriptionResponse
-- { dsdtRequestId :: !Text
-- -- ^ The ID of the request.
-- , dsdtSpotDatafeedSubscription :: !SpotDatafeedSubscriptionType
-- -- ^ The Spot Instance datafeed subscription.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeSpotDatafeedSubscriptionResponse where
-- xmlPickler = ec2XML
-- -- | Describes the Spot Instance requests that belong to your account. Spot
-- -- Instances are instances that Amazon EC2 starts on your behalf when the
-- -- maximum price that you specify exceeds the current Spot Price. Amazon EC2
-- -- periodically sets the Spot Price based on available Spot Instance capacity
-- -- and current Spot Instance requests.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotInstanceRequests.html>
-- -- data SpotInstanceFilter
-- -- , dsirAvailability-zone-group :: !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.
-- -- , dsirCreate-time :: !Text
-- -- -- ^ The time stamp when the Spot Instance request was created.
-- -- , dsirFault-code :: !Text
-- -- -- ^ The fault code related to the request.
-- -- , dsirFault-message :: !Text
-- -- -- ^ The fault message related to the request.
-- -- , dsirInstance-id :: !Text
-- -- -- ^ The ID of the instance that fulfilled the request.
-- -- , dsirLaunch-group :: !Text
-- -- -- ^ The Spot Instance launch group. Launch groups are Spot Instances
-- -- -- that launch together and terminate together.
-- -- , dsirLaunch :: Members launchType
-- -- -- ^ Whether the Amazon EBS volume is deleted on instance termination.
-- -- , dsirProduct-description :: !Text
-- -- -- ^ The product description associated with the instance.
-- -- , dsirSpot-instance-request-id :: !Text
-- -- -- ^ The Spot Instance request ID.
-- -- , dsirSpot-price :: !Text
-- -- -- ^ The maximum hourly price for any Spot Instance launched to
-- -- -- fulfill the request.
-- -- , dsirState :: !Text
-- -- -- ^ The state of the Spot Instance request. Spot bid status
-- -- -- information can help you track your Amazon EC2 Spot Instance
-- -- -- requests. For information, see Tracking Spot Requests with Bid
-- -- -- Status Codes in the Amazon Elastic Compute Cloud User Guide.
-- -- , dsirStatus-code :: !Text
-- -- -- ^ The short code describing the most recent evaluation of your Spot
-- -- -- Instance request.
-- -- , dsirStatus-message :: !Text
-- -- -- ^ The message explaining the status of the Spot Instance request.
-- -- , dsirTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dsirTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dsirTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dsirKey :: !Text
-- -- -- ^ The type of Spot Instance request.
-- -- , dsirType :: !Text
-- -- -- ^ The Availability Zone in which the bid is launched.
-- -- , dsirLaunched-availability-zone :: !UTCTime
-- -- -- ^ The start date of the request.
-- -- , dsirValid-from :: !UTCTime
-- -- -- ^ The end date of the request.
-- -- , dsirValid-until :: !Text
-- -- -- ^
-- data DescribeSpotInstanceRequests = DescribeSpotInstanceRequests
-- { dsirSpotInstanceRequestId :: Members Text
-- -- ^ One or more Spot Instance request IDs.
-- , dsirFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeSpotInstanceRequests
-- instance AWSRequest EC2 DescribeSpotInstanceRequests DescribeSpotInstanceRequestsResponse where
-- request = query4 ec2 GET "DescribeSpotInstanceRequests"
-- data DescribeSpotInstanceRequestsResponse = DescribeSpotInstanceRequestsResponse
-- { dsirRequestId :: !Text
-- -- ^ The ID of the request.
-- , dsirSpotInstanceRequestSet :: !SpotInstanceRequestSetItemType
-- -- ^ A list of Spot Instance requests. Each request is wrapped in an
-- -- item element.
-- , dsirNetworkInterfaceSet :: !InstanceNetworkInterfaceSetItemRequestType
-- -- ^ Information about the network interface.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeSpotInstanceRequestsResponse where
-- xmlPickler = ec2XML
-- -- | Describes the Spot Price history.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotPriceHistory.html>
-- -- data SpotPriceFilter
-- -- , dsphInstance-type :: !Text
-- -- -- ^ The type of instance (for example, m1.small).
-- -- , dsphProduct-description :: !Text
-- -- -- ^ The product description for the Spot Price.
-- -- , dsphSpot-price :: !Text
-- -- -- ^ The Spot Price. The value must match exactly (or use wildcards;
-- -- -- greater than or less than comparison is not supported).
-- -- , dsphAvailability-zone :: !Text
-- -- -- ^ The Availability Zone for which prices should be returned.
-- -- , dsphTimestamp :: !UTCTime
-- -- -- ^ The timestamp of the Spot Price history (for example,
-- -- -- 2010-08-16T05:06:11.000Z). You can use wildcards (* and ?).
-- -- -- Greater than or less than comparison is not supported.
-- data DescribeSpotPriceHistory = DescribeSpotPriceHistory
-- { dsphStartTime :: Maybe UTCTime
-- -- ^ The start date and time of the Spot Instance price history data.
-- , dsphEndTime :: Maybe UTCTime
-- -- ^ The end date and time of the Spot Instance price history data.
-- , dsphInstanceType :: Members Text
-- -- ^ The instance type to return.
-- , dsphProductDescription :: Members Text
-- -- ^ Filters the results by basic product description.
-- , dsphFilter :: Members Text
-- -- ^ The name of a filter.
-- , dsphAvailabilityZone :: Maybe Text
-- -- ^ Filters the results by availability zone.
-- , dsphMaxResults :: Maybe Integer
-- -- ^ The number of rows to return.
-- , dsphNextToken :: Maybe Text
-- -- ^ The next set of rows to return.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeSpotPriceHistory
-- instance AWSRequest EC2 DescribeSpotPriceHistory DescribeSpotPriceHistoryResponse where
-- request = query4 ec2 GET "DescribeSpotPriceHistory"
-- data DescribeSpotPriceHistoryResponse = DescribeSpotPriceHistoryResponse
-- { dsphRequestId :: !Text
-- -- ^ The ID of the request.
-- , dsphSpotPriceHistorySet :: !SpotPriceHistorySetItemType
-- -- ^ A list of historical Spot Prices. Each price is wrapped in an
-- -- item element.
-- , dspiNextToken :: !Text
-- -- ^ The string marking the next set of results returned. Displays
-- -- empty if there are no more results to be returned.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeSpotPriceHistoryResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your subnets.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html>
-- -- data SubnetFilter
-- -- , duAvailability-zone :: !Text
-- -- -- ^ The Availability Zone for the subnet.
-- -- , duAvailable-ip-address-count :: !Text
-- -- -- ^ The number of IP addresses in the subnet that are available.
-- -- , duCidr :: !Text
-- -- -- ^ The CIDR block of the subnet. The CIDR block you specify must
-- -- -- exactly match the subnet's CIDR block for information to be
-- -- -- returned for the subnet.
-- -- , duDefaultForAz :: !Bool
-- -- -- ^ Indicates whether this is the default subnet for the Availability
-- -- -- Zone.
-- -- , duState :: !Text
-- -- -- ^ The state of the subnet.
-- -- , duSubnet-id :: !Text
-- -- -- ^ The ID of the subnet.
-- -- , duTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , duTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , duTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , duKey :: !Text
-- -- -- ^ The ID of the VPC for the subnet.
-- -- , duVpc-id :: !Text
-- -- -- ^
-- data DescribeSubnets = DescribeSubnets
-- { dtSubnetId :: Members Text
-- -- ^ One or more subnet IDs.
-- , duFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeSubnets
-- instance AWSRequest EC2 DescribeSubnets DescribeSubnetsResponse where
-- request = query4 ec2 GET "DescribeSubnets"
-- data DescribeSubnetsResponse = DescribeSubnetsResponse
-- { dzRequestId :: !Text
-- -- ^ The ID of the request.
-- , dzSubnetSet :: !SubnetType
-- -- ^ A list of subnets. Each subnet is wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeSubnetsResponse where
-- xmlPickler = ec2XML
-- | Describes one or more of the tags for your EC2 resources.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html>
data DescribeTags = DescribeTags
{ dtagsFilter :: [TagFilter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeTags
instance Rq DescribeTags where
type Er DescribeTags = EC2ErrorResponse
type Rs DescribeTags = DescribeTagsResponse
request = query4 ec2 GET "DescribeTags"
data DescribeTagsResponse = DescribeTagsResponse
{ dtagsrRequestId :: !Text
-- ^ The ID of the request.
, dtagsrTagSet :: [TagSetItemType]
-- ^ A list of tags.
} deriving (Eq, Show, Generic)
instance IsXML DescribeTagsResponse where
xmlPickler = ec2XML
-- -- | Describes the specified attribute of the specified volume. You can specify
-- -- only one attribute at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumeAttribute.html>
-- data DescribeVolumeAttribute = DescribeVolumeAttribute
-- { dvaVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , dvaAttribute :: !Text
-- -- ^ The instance attribute.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeVolumeAttribute
-- instance IsXML DescribeVolumeAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DescribeVolumeAttribute DescribeVolumeAttributeResponse where
-- request = query4 ec2 GET "DescribeVolumeAttribute"
-- data DescribeVolumeAttributeResponse = DescribeVolumeAttributeResponse
-- { dvaRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvbVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , dvbAutoEnableIO :: Maybe Bool
-- -- ^ The state of autoEnableIO attribute.
-- , dvbProductCodes :: !ProductCodesSetItemType
-- -- ^ A list of product codes. Each product code is wrapped in an item
-- -- element that contains a product code and a type.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeVolumeAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Describes the specified Amazon EBS volumes.For more information about
-- -- Amazon EBS, see Amazon Elastic Block Store in the Amazon Elastic Compute
-- -- Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html>
-- -- data VolumeFilter
-- -- , dwAttachment :: Members AttachmentType
-- -- -- ^ The time stamp when the attachment initiated.
-- -- , dwAvailability-zone :: !Text
-- -- -- ^ The Availability Zone in which the volume was created.
-- -- , dwCreate-time :: !UTCTime
-- -- -- ^ The time stamp when the volume was created.
-- -- , dwSize :: !Text
-- -- -- ^ The size of the volume, in GiB (for example, 20).
-- -- , dwSnapshot-id :: !Text
-- -- -- ^ The snapshot from which the volume was created.
-- -- , dwStatus :: !Text
-- -- -- ^ The status of the volume.
-- -- , dwTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dwTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dwTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dwKey :: !Text
-- -- -- ^ The volume ID.
-- -- , dwVolume-id :: !Text
-- -- -- ^ The Amazon EBS volume type. If the volume is an io1 volume, the
-- -- -- response includes the IOPS as well.
-- -- , dwVolume-type :: !Text
-- -- -- ^
-- data DescribeVolumes = DescribeVolumes
-- { dwVolumeId :: Members Text
-- -- ^ One or more volume IDs.
-- , dwFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeVolumes
-- instance AWSRequest EC2 DescribeVolumes DescribeVolumesResponse where
-- request = query4 ec2 GET "DescribeVolumes"
-- data DescribeVolumesResponse = DescribeVolumesResponse
-- { ebRequestId :: !Text
-- -- ^ The ID of the request.
-- , ebVolumeSet :: !DescribeVolumesSetItemResponseType
-- -- ^ A list of volumes. Each volume is wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeVolumesResponse where
-- xmlPickler = ec2XML
-- -- | Describes the status of the specified volumes. Volume status provides the
-- -- result of the checks performed on your volumes to determine events that can
-- -- impair the performance of your volumes.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumeStatus.html>
-- -- data VolumeFilter
-- -- , dvsAvailability-zone :: !Text
-- -- -- ^ The Availability Zone of the instance.
-- -- , dvsVolume-status :: Members volume-statusType
-- -- -- ^ The status of the volume.
-- -- , dvsEvent :: Members eventType
-- -- -- ^ A description of the event.
-- -- , dvsAction :: Members actionType
-- data DescribeVolumeStatus = DescribeVolumeStatus
-- { dvsVolumeId :: Members Text
-- -- ^ One or more volume IDs.
-- , dvsFilter :: Members Text
-- -- ^ The name of a filter.
-- , dvsMaxResults :: Maybe Integer
-- -- ^ The maximum number of paginated volume items per response.
-- , dvsNextToken :: Maybe Text
-- -- ^ A string specifying the next paginated set of results to return
-- -- using the pagination token returned by a previous call to this
-- -- API.
-- -- ^ The action code for the event, for example, enable-volume-io
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeVolumeStatus
-- instance AWSRequest EC2 DescribeVolumeStatus DescribeVolumeStatusResponse where
-- request = query4 ec2 GET "DescribeVolumeStatus"
-- data DescribeVolumeStatusResponse = DescribeVolumeStatusResponse
-- { dvsRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvsVolumeStatusSet :: !VolumeStatusItemType
-- -- ^ A list of volumes. Each volume is wrapped in an item element.
-- , dvtNextToken :: !Text
-- -- ^ A string specifying the next paginated set of results to return.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeVolumeStatusResponse where
-- xmlPickler = ec2XML
-- -- | Describes the specified attribute of the specified VPC. You can specify
-- -- only one attribute at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpcAttribute.html>
-- data DescribeVpcAttribute = DescribeVpcAttribute
-- { dvaVpcId :: !Text
-- -- ^ The ID of the VPC.
-- , dvbAttribute :: !Text
-- -- ^ The VPC attribute.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeVpcAttribute
-- instance IsXML DescribeVpcAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DescribeVpcAttribute DescribeVpcAttributeResponse where
-- request = query4 ec2 GET "DescribeVpcAttribute"
-- data DescribeVpcAttributeResponse = DescribeVpcAttributeResponse
-- { dvbRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvbEnableDnsSupport :: !Bool
-- -- ^ Indicates whether DNS resolution is enabled for the VPC. If this
-- -- attribute is true, the Amazon DNS server resolves DNS hostnames
-- -- for your instances to their corresponding IP addresses;
-- -- otherwise, it does not.
-- , dvbEnableDnsHostnames :: !Bool
-- -- ^ Indicates whether the instances launched in the VPC get DNS
-- -- hostnames. If this attribute is true, instances in the VPC get
-- -- DNS hostnames; otherwise, they do not.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeVpcAttributeResponse where
-- xmlPickler = ec2XML
-- | Describes one or more of your VPCs.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpcs.html>
-- -- data VpcFilter
-- -- , dxCidr :: !Text
-- -- -- ^ The CIDR block of the VPC. The CIDR block you specify must
-- -- -- exactly match the VPC's CIDR block for information to be returned
-- -- -- for the VPC.
-- -- , dxDhcp-options-id :: !Text
-- -- -- ^ The ID of a set of DHCP options.
-- -- , dxIsDefault :: !Bool
-- -- -- ^ Indicates whether the VPC is the default VPC.
-- -- , dxState :: !Text
-- -- -- ^ The state of the VPC.
-- -- , dxTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dxTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dxTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dxKey :: !Text
-- -- -- ^ The ID of the VPC.
-- -- , dxVpc-id :: !Text
-- -- -- ^
data DescribeVpcs = DescribeVpcs
{ dvVpcId :: [Text]
-- ^ One or more VPC IDs.
, dvFilter :: [Filter]
-- ^ The name of a filter.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeVpcs
instance Rq DescribeVpcs where
type Er DescribeVpcs = EC2ErrorResponse
type Rs DescribeVpcs = DescribeVpcsResponse
request = query4 ec2 GET "DescribeVpcs"
data DescribeVpcsResponse = DescribeVpcsResponse
{ dvrRequestId :: !Text
-- ^ The ID of the request.
, dvrVpcSet :: ![VpcItemType]
-- ^ A list of VPCs.
} deriving (Eq, Show, Generic)
instance IsXML DescribeVpcsResponse where
xmlPickler = ec2XML
-- -- | Describes one or more of your VPN connections.For more information about
-- -- VPN connections, see Adding a Hardware Virtual Private Gateway to Your VPC
-- -- in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpnConnections.html>
-- -- data VpcConnectionFilter
-- -- , dvdCustomer-gateway-configuration :: !Text
-- -- -- ^ The configuration information for the customer gateway.
-- -- , dvdCustomer-gateway-id :: !Text
-- -- -- ^ The ID of a customer gateway associated with the VPN connection.
-- -- , dvdState :: !Text
-- -- -- ^ The state of the VPN connection.
-- -- , dvdOption :: Members optionType
-- -- -- ^ Indicates whether the connection has static routes only. Used for
-- -- -- devices that do not support Border Gateway Protocol (BGP).
-- -- , dvdRoute :: Members routeType
-- -- -- ^ The destination CIDR block. This corresponds to the subnet used
-- -- -- in a customer data center.
-- -- , dvdBgp-asn :: !Integer
-- -- -- ^ The BGP Autonomous System Number (ASN) associated with a BGP
-- -- -- device.
-- -- , dvdTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dvdTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dvdTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dvdKey :: !Text
-- -- -- ^ The type of VPN connection. Currently the only supported type is
-- -- -- ipsec.1.
-- -- , dvdType :: !Text
-- -- -- ^ The ID of the VPN connection.
-- -- , dvdVpn-connection-id :: !Text
-- -- -- ^ The ID of a virtual private gateway associated with the VPN
-- -- -- connection.
-- -- , dvdVpn-gateway-id :: !Text
-- -- -- ^
-- data DescribeVpnConnections = DescribeVpnConnections
-- { dvdVpnConnectionId :: Members Text
-- -- ^ One or more VPN connection IDs.
-- , dvdFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeVpnConnections
-- instance AWSRequest EC2 DescribeVpnConnections DescribeVpnConnectionsResponse where
-- request = query4 ec2 GET "DescribeVpnConnections"
-- data DescribeVpnConnectionsResponse = DescribeVpnConnectionsResponse
-- { dvdRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvdVpnConnectionSet :: !VpnConnectionType
-- -- ^ A list of VPN connections. Each VPN connection is wrapped in an
-- -- item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeVpnConnectionsResponse where
-- xmlPickler = ec2XML
-- -- | Describes one or more of your virtual private gateways. For more
-- -- information about virtual private gateways, see Adding an IPsec Hardware
-- -- VPN to Your VPC in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpnGateways.html>
-- -- data VpnGatewayFilter
-- -- , dvhAttachment :: Members AttachmentType
-- -- -- ^ The current state of the attachment between the gateway and the VPC.
-- -- , dvhAvailability-zone :: !Text
-- -- -- ^ The Availability Zone for the virtual private gateway.
-- -- , dvhState :: !Text
-- -- -- ^ The state of the virtual private gateway.
-- -- , dvhTag-key :: !Text
-- -- -- ^ The key of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-value filter. For example, if you use both
-- -- -- the filter "tag-key=Purpose" and the filter "tag-value=X", you
-- -- -- get any resources assigned both the tag key Purpose (regardless
-- -- -- of what the tag's value is), and the tag value X (regardless of
-- -- -- what the tag's key is). If you want to list only resources where
-- -- -- Purpose is X, see the tag:key filter.
-- -- , dvhTag-value :: !Text
-- -- -- ^ The value of a tag assigned to the resource. This filter is
-- -- -- independent of the tag-key filter.
-- -- , dvhTag: :: !Text
-- -- -- ^ Filters the response based on a specific tag/value combination.
-- -- , dvhKey :: !Text
-- -- -- ^ The type of virtual private gateway. Currently the only supported
-- -- -- type is ipsec.1.
-- -- , dvhType :: !Text
-- -- -- ^ The ID of the virtual private gateway.
-- -- , dvhVpn-gateway-id :: !Text
-- -- -- ^
-- data DescribeVpnGateways = DescribeVpnGateways
-- { dvhVpnGatewayId :: Members Text
-- -- ^ One or more virtual private gateway IDs.
-- , dvhFilter :: Members Text
-- -- ^ The name of a filter.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DescribeVpnGateways
-- instance AWSRequest EC2 DescribeVpnGateways DescribeVpnGatewaysResponse where
-- request = query4 ec2 GET "DescribeVpnGateways"
-- data DescribeVpnGatewaysResponse = DescribeVpnGatewaysResponse
-- { dvhRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvhVpnGatewaySet :: !VpnGatewayType
-- -- ^ A list of virtual private gateways. Each virtual private gateway
-- -- is wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DescribeVpnGatewaysResponse where
-- xmlPickler = ec2XML
-- -- | Detaches an Internet gateway from a VPC, disabling connectivity between the
-- -- Internet and the VPC. The VPC must not contain any running instances with
-- -- Elastic IP addresses.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DetachInternetGateway.html>
-- data DetachInternetGateway = DetachInternetGateway
-- { diiInternetGatewayId :: !Text
-- -- ^ The ID of the Internet gateway.
-- , diiVpcId :: !Text
-- -- ^ The ID of the VPC.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DetachInternetGateway
-- instance AWSRequest EC2 DetachInternetGateway DetachInternetGatewayResponse where
-- request = query4 ec2 GET "DetachInternetGateway"
-- data DetachInternetGatewayResponse = DetachInternetGatewayResponse
-- { diiRequestId :: !Text
-- -- ^ The ID of the request.
-- , diiReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DetachInternetGatewayResponse where
-- xmlPickler = ec2XML
-- -- | Detaches a network interface from an instance.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DetachNetworkInterface.html>
-- data DetachNetworkInterface = DetachNetworkInterface
-- { dniAttachmentId :: !Text
-- -- ^ The ID of the attachment.
-- , dniForce :: Maybe Bool
-- -- ^ Set to true to force a detachment.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DetachNetworkInterface
-- instance IsXML DetachNetworkInterface where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DetachNetworkInterface DetachNetworkInterfaceResponse where
-- request = query4 ec2 GET "DetachNetworkInterface"
-- data DetachNetworkInterfaceResponse = DetachNetworkInterfaceResponse
-- { dnkRequestId :: !Text
-- -- ^ The ID of the request.
-- , dnkReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DetachNetworkInterfaceResponse where
-- xmlPickler = ec2XML
-- -- | Detaches an Amazon EBS volume from an instance. Make sure to unmount any
-- -- file systems on the device within your operating system before detaching
-- -- the volume. Failure to do so will result in the volume being stuck in
-- -- "busy" state while detaching. For more information about Amazon EBS, see
-- -- Amazon Elastic Block Store in the Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DetachVolume.html>
-- data DetachVolume = DetachVolume
-- { dxVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , dxInstanceId :: Maybe Text
-- -- ^ The ID of the instance.
-- , dxDevice :: Maybe Text
-- -- ^ The device name.
-- , dxForce :: Maybe Bool
-- -- ^ Forces detachment if the previous detachment attempt did not
-- -- occur cleanly (logging into an instance, unmounting the volume,
-- -- and detaching normally). This option can lead to data loss or a
-- -- corrupted file system. Use this option only as a last resort to
-- -- detach a volume from a failed instance. The instance won't have
-- -- an opportunity to flush file system caches or file system
-- -- metadata. If you use this option, you must perform file system
-- -- check and repair procedures.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DetachVolume
-- instance IsXML DetachVolume where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DetachVolume DetachVolumeResponse where
-- request = query4 ec2 GET "DetachVolume"
-- data DetachVolumeResponse = DetachVolumeResponse
-- { edRequestId :: !Text
-- -- ^ The ID of the request.
-- , edVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , edInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , edDevice :: !Text
-- -- ^ The device name exposed to the instance.
-- , edStatus :: !Text
-- -- ^ The attachment state.
-- , edAttachTime :: !UTCTime
-- -- ^ The time stamp when the attachment initiated.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DetachVolumeResponse where
-- xmlPickler = ec2XML
-- -- | Detaches a virtual private gateway from a VPC. You do this if you're
-- -- planning to turn off the VPC and not use it anymore. You can confirm a
-- -- virtual private gateway has been completely detached from a VPC by
-- -- describing the virtual private gateway (any attachments to the virtual
-- -- private gateway are also described).
-- --
-- -- You must wait for the attachment's state to switch to detached before you
-- -- can delete the VPC or attach a different VPC to the virtual private gateway.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DetachVpnGateway.html>
-- data DetachVpnGateway = DetachVpnGateway
-- { dviVpnGatewayId :: !Text
-- -- ^ The ID of the virtual private gateway.
-- , dviVpcId :: !Text
-- -- ^ The ID of the VPC.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DetachVpnGateway
-- instance AWSRequest EC2 DetachVpnGateway DetachVpnGatewayResponse where
-- request = query4 ec2 GET "DetachVpnGateway"
-- data DetachVpnGatewayResponse = DetachVpnGatewayResponse
-- { dviRequestId :: !Text
-- -- ^ The ID of the request.
-- , dviReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DetachVpnGatewayResponse where
-- xmlPickler = ec2XML
-- -- | Disables a virtual private gateway (VGW) from propagating routes to the
-- -- routing tables of a VPC.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DisableVgwRoutePropagation.html>
-- data DisableVgwRoutePropagation = DisableVgwRoutePropagation
-- { dvrpRouteTableId :: !Text
-- -- ^ The ID of the routing table.
-- , dvrpGatewayId :: !Text
-- -- ^ The ID of the virtual private gateway.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DisableVgwRoutePropagation
-- instance AWSRequest EC2 DisableVgwRoutePropagation DisableVgwRoutePropagationResponse where
-- request = query4 ec2 GET "DisableVgwRoutePropagation"
-- data DisableVgwRoutePropagationResponse = DisableVgwRoutePropagationResponse
-- { dvrpRequestId :: !Text
-- -- ^ The ID of the request.
-- , dvrpReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DisableVgwRoutePropagationResponse where
-- xmlPickler = ec2XML
-- -- | Disassociates an Elastic IP address from the instance or network interface
-- -- it's associated with. An Elastic IP address is for use in either the
-- -- EC2-Classic platform or in a VPC.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DisassociateAddress.html>
-- data DisassociateAddress = DisassociateAddress
-- { dbPublicIp :: !Text
-- -- ^ [EC2-Classic] The Elastic IP address.
-- , dbAssociationId :: !Text
-- -- ^ [EC2-VPC] The association ID.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DisassociateAddress
-- instance AWSRequest EC2 DisassociateAddress DisassociateAddressResponse where
-- request = query4 ec2 GET "DisassociateAddress"
-- data DisassociateAddressResponse = DisassociateAddressResponse
-- { dbRequestId :: !Text
-- -- ^ The ID of the request.
-- , dbReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DisassociateAddressResponse where
-- xmlPickler = ec2XML
-- -- | Disassociates a subnet from a route table.After you perform this action,
-- -- the subnet no longer uses the routes in the route table. Instead, it uses
-- -- the routes in the VPC's main route table. For more information about route
-- -- tables, see Route Tables in the Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DisassociateRouteTable.html>
-- data DisassociateRouteTable = DisassociateRouteTable
-- { drtAssociationId :: !Text
-- -- ^ The association ID representing the current association between
-- -- the route table and subnet.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery DisassociateRouteTable
-- instance IsXML DisassociateRouteTable where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 DisassociateRouteTable DisassociateRouteTableResponse where
-- request = query4 ec2 GET "DisassociateRouteTable"
-- data DisassociateRouteTableResponse = DisassociateRouteTableResponse
-- { drvRequestId :: !Text
-- -- ^ The ID of the request.
-- , drvReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML DisassociateRouteTableResponse where
-- xmlPickler = ec2XML
-- -- | Enables a virtual private gateway (VGW) to propagate routes to the routing
-- -- tables of a VPC.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-EnableVgwRoutePropagation.html>
-- data EnableVgwRoutePropagation = EnableVgwRoutePropagation
-- { evrpRouteTableId :: !Text
-- -- ^ The ID of the routing table.
-- , evrpGatewayId :: !Text
-- -- ^ The ID of the virtual private gateway.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery EnableVgwRoutePropagation
-- instance AWSRequest EC2 EnableVgwRoutePropagation EnableVgwRoutePropagationResponse where
-- request = query4 ec2 GET "EnableVgwRoutePropagation"
-- data EnableVgwRoutePropagationResponse = EnableVgwRoutePropagationResponse
-- { evrpRequestId :: !Text
-- -- ^ The ID of the request.
-- , evrpReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML EnableVgwRoutePropagationResponse where
-- xmlPickler = ec2XML
-- -- | Enables I/O operations for a volume that had I/O operations disabled
-- -- because the data on the volume was potentially inconsistent.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-EnableVolumeIO.html>
-- data EnableVolumeIO = EnableVolumeIO
-- { evioVolumeId :: !Text
-- -- ^ The ID of the volume.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery EnableVolumeIO
-- instance AWSRequest EC2 EnableVolumeIO EnableVolumeIOResponse where
-- request = query4 ec2 GET "EnableVolumeIO"
-- data EnableVolumeIOResponse = EnableVolumeIOResponse
-- { evioRequestId :: !Text
-- -- ^ The ID of the request.
-- , evioReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML EnableVolumeIOResponse where
-- xmlPickler = ec2XML
-- -- | Gets the console output for the specified instance. Instances do not have a
-- -- physical monitor through which you can view their console output. They also
-- -- lack physical controls that allow you to power up, reboot, or shut them
-- -- down. To allow these actions, we provide them through the Amazon EC2 API
-- -- and command line interface.Instance console output is buffered and posted
-- -- shortly after instance boot, reboot, and termination. Amazon EC2 preserves
-- -- the most recent 64 KB output which will be available for at least one hour
-- -- after the most recent post.For Linux/UNIX instances, the instance console
-- -- output displays the exact console output that would normally be displayed
-- -- on a physical monitor attached to a machine. This output is buffered
-- -- because the instance produces it and then posts it to a store where the
-- -- instance's owner can retrieve it.For Windows instances, the instance
-- -- console output displays the last three system event log errors.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-GetConsoleOutput.html>
-- data GetConsoleOutput = GetConsoleOutput
-- { gcoInstanceId :: !Text
-- -- ^ The ID of the instance.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery GetConsoleOutput
-- instance AWSRequest EC2 GetConsoleOutput GetConsoleOutputResponse where
-- request = query4 ec2 GET "GetConsoleOutput"
-- data GetConsoleOutputResponse = GetConsoleOutputResponse
-- { gcoRequestId :: !Text
-- -- ^ The ID of the request.
-- , gcpInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , gcpTimestamp :: !UTCTime
-- -- ^ The time the output was last updated.
-- , gcpOutput :: !Text
-- -- ^ The console output, Base64 encoded.
-- } deriving (Eq, Show, Generic)
-- instance IsXML GetConsoleOutputResponse where
-- xmlPickler = ec2XML
-- -- | Retrieves the encrypted administrator password for an instance running
-- -- Windows.The Windows password is only generated the first time an AMI is
-- -- launched. It is not generated for rebundled AMIs or after the password is
-- -- changed on an instance.The password is encrypted using the key pair that
-- -- you specified when you launched the instance. You must provide the
-- -- corresponding key pair file.Password generation and encryption takes a few
-- -- moments. Please wait up to 15 minutes after launching an instance before
-- -- trying to retrieve the generated password.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-GetPasswordData.html>
-- data GetPasswordData = GetPasswordData
-- { gpdInstanceId :: !Text
-- -- ^ The ID of a Windows instance.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery GetPasswordData
-- instance AWSRequest EC2 GetPasswordData GetPasswordDataResponse where
-- request = query4 ec2 GET "GetPasswordData"
-- data GetPasswordDataResponse = GetPasswordDataResponse
-- { gpdRequestId :: !Text
-- -- ^ The ID of the request.
-- , gpeInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , gpeTimestamp :: !UTCTime
-- -- ^ The time the data was last updated.
-- , gpePasswordData :: !Text
-- -- ^ The password of the instance.
-- } deriving (Eq, Show, Generic)
-- instance IsXML GetPasswordDataResponse where
-- xmlPickler = ec2XML
-- -- | Creates an import instance task using metadata from the specified disk
-- -- image. After importing the image, you then upload it using the
-- -- ec2-upload-disk-image command in the EC2 command line tools. For more
-- -- information, see Using the Command Line Tools to Import Your Virtual
-- -- Machine to Amazon EC2 in the Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ImportInstance.html>
-- data ImportInstance = ImportInstance
-- { iiDescription :: Maybe Text
-- -- ^ A description for the instance being imported.
-- , iiLaunchSpecification :: Members LaunchSpecificationType
-- -- ^ The architecture of the instance.
-- , iiDiskImage :: Members DiskImageType
-- -- ^ The file format of the disk image.
-- , iiPlatform :: Maybe Text
-- -- ^ The instance operating system.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ImportInstance
-- instance IsXML ImportInstance where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ImportInstance ImportInstanceResponse where
-- request = query4 ec2 GET "ImportInstance"
-- data ImportInstanceResponse = ImportInstanceResponse
-- { iiConversionTask :: !ConversionTaskType
-- -- ^ Information about the import instance task.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ImportInstanceResponse where
-- xmlPickler = ec2XML
-- -- | Imports the public key from an RSA key pair that you created with a
-- -- third-party tool. Compare this with CreateKeyPair, in which AWS creates the
-- -- key pair and gives the keys to you (AWS keeps a copy of the public key).
-- -- With ImportKeyPair, you create the key pair and give AWS just the public
-- -- key. The private key is never transferred between you and AWS.You can
-- -- easily create an RSA key pair on Windows and Linux using the ssh-keygen
-- -- command line tool (provided with the standard OpenSSH installation).
-- -- Standard library support for RSA key pair creation is also available in
-- -- Java, Ruby, Python, and many other programming languages.Supported
-- -- formats:DSA keys are not supported. Make sure your key generator is set up
-- -- to create RSA keys.Supported lengths: 1024, 2048, and 4096.Note that you
-- -- can have up to five thousand key pairs per region.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ImportKeyPair.html>
-- data ImportKeyPair = ImportKeyPair
-- { ikpKeyName :: !Text
-- -- ^ A unique name for the key pair.
-- , ikpPublicKeyMaterial :: !Text
-- -- ^ The public key. You must base64 encode the public key material
-- -- before sending it to AWS.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ImportKeyPair
-- instance AWSRequest EC2 ImportKeyPair ImportKeyPairResponse where
-- request = query4 ec2 GET "ImportKeyPair"
-- data ImportKeyPairResponse = ImportKeyPairResponse
-- { ikpRequestId :: !Text
-- -- ^ The ID of the request.
-- , ikqKeyName :: !Text
-- -- ^ The key pair name you provided.
-- , ikqKeyFingerprint :: !Text
-- -- ^ The MD5 public key fingerprint as specified in section 4 of
-- -- RFC4716.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ImportKeyPairResponse where
-- xmlPickler = ec2XML
-- -- | Creates an import volume task using metadata from the specified disk image.
-- -- After importing the image, you then upload it using the
-- -- ec2-upload-disk-image command in the EC2 command line tools. For more
-- -- information, see Using the Command Line Tools to Import Your Virtual
-- -- Machine to Amazon EC2 in the Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ImportVolume.html>
-- data ImportVolume = ImportVolume
-- { ivAvailabilityZone :: !Text
-- -- ^ The Availability Zone for the resulting Amazon EBS volume.
-- , ivImage :: Members ImageType
-- -- ^ The file format of the disk image.
-- , ivDescription :: Maybe Text
-- -- ^ An optional description for the volume being imported.
-- , ivVolume :: Members VolumeType
-- -- ^ The size, in GB (2^30 bytes), of an Amazon EBS volume to hold the
-- -- converted image.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ImportVolume
-- instance IsXML ImportVolume where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ImportVolume ImportVolumeResponse where
-- request = query4 ec2 GET "ImportVolume"
-- data ImportVolumeResponse = ImportVolumeResponse
-- { ivConversionTask :: !ConversionTaskType
-- -- ^ Information about the import volume task.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ImportVolumeResponse where
-- xmlPickler = ec2XML
-- -- | Modifies the specified attribute of the specified AMI. You can specify only
-- -- one attribute at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyImageAttribute.html>
-- data ModifyImageAttribute = ModifyImageAttribute
-- { miaImageId :: !Text
-- -- ^ The ID of the AMI.
-- , miaLaunchPermission :: Members LaunchPermissionType
-- -- ^ Adds the specified AWS account ID to the AMI's list of launch
-- -- permissions.
-- , miaProductCode :: Members Text
-- -- ^ Adds the specified product code to the specified instance
-- -- store-backed AMI. After you add a product code to an AMI, it
-- -- can't be removed.
-- , miaDescription :: Members DescriptionType
-- -- ^ Changes the AMI's description to the specified value.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ModifyImageAttribute
-- instance IsXML ModifyImageAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ModifyImageAttribute ModifyImageAttributeResponse where
-- request = query4 ec2 GET "ModifyImageAttribute"
-- data ModifyImageAttributeResponse = ModifyImageAttributeResponse
-- { miaRequestId :: !Text
-- -- ^ The ID of the request.
-- , miaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ModifyImageAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Modifies the specified attribute of the specified instance. You can specify
-- -- only one attribute at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html>
-- data ModifyInstanceAttribute = ModifyInstanceAttribute
-- { miaInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , miaInstanceType :: Maybe InstanceType
-- -- ^ Changes the instance type to the specified value. See Available
-- -- Instance Types for more information. An
-- -- InvalidInstanceAttributeValue error will be returned if the
-- -- instance type is not valid.
-- , miaKernel :: Maybe Text
-- -- ^ Changes the instance's kernel to the specified value.
-- , miaRamdisk :: Maybe Text
-- -- ^ Changes the instance's RAM disk to the specified value.
-- , miaUserData :: Maybe Text
-- -- ^ Changes the instance's user data to the specified value.
-- , miaDisableApiTermination :: Maybe Bool
-- -- ^ If the value is true, you can't terminate the instance using the
-- -- Amazon EC2 console, CLI, or API; otherwise you can.
-- , miaInstanceInitiatedShutdownBehavior :: Maybe Text
-- -- ^ Indicates whether an instance stops or terminates when you
-- -- initiate shutdown from the instance (using the operating system
-- -- command for system shutdown).
-- , miaBlockDeviceMapping :: Members InstanceBlockDeviceMappingItemType
-- -- ^ Modifies the DeleteOnTermination attribute for volumes that are
-- -- currently attached. The volume must be owned by the caller. If no
-- -- value is specified for DeleteOnTermination, the default is true
-- -- and the volume is deleted when the instance is terminated.
-- , miaSourceDestCheck :: Maybe Bool
-- -- ^ Indicates whether source/destination checking is enabled. A value
-- -- of true means checking is enabled, and false means checking is
-- -- disabled. This value must be false for a NAT instance to perform
-- -- NAT.
-- , miaGroupId :: Members Text
-- -- ^ [EC2-VPC] Changes the instance's security group. You must specify
-- -- at least one security group, even if it's just the default
-- -- security group for the VPC. You must specify the security group
-- -- ID, not the security group name.
-- , miaEbsOptimized :: Maybe 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, Show, Generic)
-- instance IsQuery ModifyInstanceAttribute
-- instance IsXML ModifyInstanceAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ModifyInstanceAttribute ModifyInstanceAttributeResponse where
-- request = query4 ec2 GET "ModifyInstanceAttribute"
-- data ModifyInstanceAttributeResponse = ModifyInstanceAttributeResponse
-- { mibRequestId :: !Text
-- -- ^ The ID of the request.
-- , mibReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ModifyInstanceAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Modifies the specified network interface attribute. You can specify only
-- -- one attribute at a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyNetworkInterfaceAttribute.html>
-- data ModifyNetworkInterfaceAttribute = ModifyNetworkInterfaceAttribute
-- { mniaNetworkInterfaceId :: !Text
-- -- ^ The ID of the network interface.
-- , mniaDescription :: Members DescriptionType
-- -- ^ A description for the network interface.
-- , mniaSecurityGroupId :: Members Text
-- -- ^ Changes the security groups that a network interface is in. The
-- -- new set of groups you specify replaces the current set. You must
-- -- specify at least one group, even if it's just the default
-- -- security group in the VPC. You must specify the group ID and not
-- -- the group name.
-- , mniaSourceDestCheck :: Members SourceDestCheckType
-- -- ^ Indicates whether source/destination checking is enabled. A value
-- -- of true means checking is enabled, and false means checking is
-- -- disabled. This value must be false for a NAT instance to perform
-- -- NAT.
-- , mniaAttachment :: Members AttachmentType
-- -- ^ The ID of the interface attachment.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ModifyNetworkInterfaceAttribute
-- instance IsXML ModifyNetworkInterfaceAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ModifyNetworkInterfaceAttribute ModifyNetworkInterfaceAttributeResponse where
-- request = query4 ec2 GET "ModifyNetworkInterfaceAttribute"
-- data ModifyNetworkInterfaceAttributeResponse = ModifyNetworkInterfaceAttributeResponse
-- { mniaRequestId :: !Text
-- -- ^ The ID of the request.
-- , mniaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ModifyNetworkInterfaceAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Adds or remove permission settings for the specified snapshot.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ModifySnapshotAttribute.html>
-- data ModifySnapshotAttribute = ModifySnapshotAttribute
-- { msaSnapshotId :: !Text
-- -- ^ The ID of the snapshot.
-- , msaCreateVolumePermission :: Members CreateVolumePermissionType
-- -- ^ Adds the specified AWS account ID to the volume's list of create
-- -- volume permissions.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ModifySnapshotAttribute
-- instance IsXML ModifySnapshotAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ModifySnapshotAttribute ModifySnapshotAttributeResponse where
-- request = query4 ec2 GET "ModifySnapshotAttribute"
-- data ModifySnapshotAttributeResponse = ModifySnapshotAttributeResponse
-- { msaRequestId :: !Text
-- -- ^ The ID of the request.
-- , msaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ModifySnapshotAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Modifies a volume attribute.By default, all I/O operations for the volume
-- -- are suspended when the data on the volume is determined to be potentially
-- -- inconsistent, to prevent undetectable, latent data corruption. The I/O
-- -- access to the volume can be resumed by first calling EnableVolumeIO action
-- -- to enable I/O access and then checking the data consistency on your
-- -- volume.You can change the default behavior to resume I/O operations without
-- -- calling EnableVolumeIO action by setting the AutoEnableIO attribute of the
-- -- volume to true. We recommend that you change this attribute only for
-- -- volumes that are stateless, or disposable, or for boot volumes.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyVolumeAttribute.html>
-- data ModifyVolumeAttribute = ModifyVolumeAttribute
-- { mvaVolumeId :: !Text
-- -- ^ The ID of the volume.
-- , mvaAutoEnableIO :: Members AutoEnableIOType
-- -- ^ Specifies whether the volume should be auto-enabled for I/O
-- -- operations.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ModifyVolumeAttribute
-- instance IsXML ModifyVolumeAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ModifyVolumeAttribute ModifyVolumeAttributeResponse where
-- request = query4 ec2 GET "ModifyVolumeAttribute"
-- data ModifyVolumeAttributeResponse = ModifyVolumeAttributeResponse
-- { mvaRequestId :: !Text
-- -- ^ The ID of the request.
-- , mvaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ModifyVolumeAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Modifies the specified attribute of the specified VPC.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyVpcAttribute.html>
-- data ModifyVpcAttribute = ModifyVpcAttribute
-- { mvaVpcId :: !Text
-- -- ^ The ID of the VPC.
-- , mvaEnableDnsSupport :: Maybe Bool
-- -- ^ Specifies whether DNS resolution is supported for the VPC. If
-- -- this attribute is true, the Amazon DNS server resolves DNS
-- -- hostnames for your instances to their corresponding IP addresses;
-- -- otherwise, it does not.
-- , mvaEnableDnsHostnames :: Maybe Bool
-- -- ^ Specifies whether the instances launched in the VPC get DNS
-- -- hostnames. If this attribute is true, instances in the VPC get
-- -- DNS hostnames; otherwise, they do not.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ModifyVpcAttribute
-- instance IsXML ModifyVpcAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ModifyVpcAttribute ModifyVpcAttributeResponse where
-- request = query4 ec2 GET "ModifyVpcAttribute"
-- data ModifyVpcAttributeResponse = ModifyVpcAttributeResponse
-- { mvbRequestId :: !Text
-- -- ^ The ID of the request.
-- , mvbReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ModifyVpcAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Enables monitoring for a running instance. For more information about
-- -- monitoring instances, see Monitoring Your Instances and Volumes in the
-- -- Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-MonitorInstances.html>
-- data MonitorInstances = MonitorInstances
-- { miInstanceId :: Members Text
-- -- ^ One or more instance IDs.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery MonitorInstances
-- instance AWSRequest EC2 MonitorInstances MonitorInstancesResponse where
-- request = query4 ec2 GET "MonitorInstances"
-- data MonitorInstancesResponse = MonitorInstancesResponse
-- { miRequestId :: !Text
-- -- ^ The ID of the request.
-- , miInstancesSet :: !MonitorInstancesResponseSetItemType
-- -- ^ A list of instances. Each instance is wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML MonitorInstancesResponse where
-- xmlPickler = ec2XML
-- -- | Purchases a Reserved Instance for use with your account. With Amazon EC2
-- -- Reserved Instances, you obtain a capacity reservation for a certain
-- -- instance configuration over a specified period of time. You pay a lower
-- -- usage rate than with On-Demand instances for the time that you actually use
-- -- the capacity reservation. Starting with the 2011-11-01 API version, AWS
-- -- expanded its offering of Reserved Instances to address a range of projected
-- -- instance usage. There are three types of Reserved Instances based on
-- -- customer utilization levels: Heavy Utilization, Medium Utilization, and
-- -- Light Utilization.The Medium Utilization offering type is equivalent to the
-- -- Reserved Instance offering available before API version 2011-11-01. If you
-- -- are using tools that predate the 2011-11-01 API version,
-- -- DescribeReservedInstancesOfferings will only list information about the
-- -- Medium Utilization Reserved Instance offering type.For information about
-- -- Reserved Instance pricing tiers, go to Understanding Reserved Instance
-- -- pricing tiers in the Amazon Elastic Compute Cloud User Guide. For more
-- -- information about Reserved Instances, go to Reserved Instances also in the
-- -- Amazon Elastic Compute Cloud User Guide.You determine the type of the
-- -- Reserved Instances offerings by including the optional offeringType
-- -- parameter when calling DescribeReservedInstancesOfferings. After you've
-- -- identified the Reserved Instance with the offering type you want, specify
-- -- its ReservedInstancesOfferingId when you call
-- -- PurchaseReservedInstancesOffering. Starting with the 2012-08-15 API
-- -- version, you can also purchase Reserved Instances from the Reserved
-- -- Instance Marketplace. The Reserved Instance Marketplace matches sellers who
-- -- want to resell Reserved Instance capacity that they no longer need with
-- -- buyers who want to purchase additional capacity. Reserved Instances bought
-- -- and sold through the Reserved Instance Marketplace work like any other
-- -- Reserved Instances.By default, with the 2012-08-15 API version,
-- -- DescribeReservedInstancesOfferings returns information about Amazon EC2
-- -- Reserved Instances available directly from AWS, plus instance offerings
-- -- available on the Reserved Instance Marketplace. If you are using tools that
-- -- predate the 2012-08-15 API version, the DescribeReservedInstancesOfferings
-- -- action will only list information about Amazon EC2 Reserved Instances
-- -- available directly from AWS.For more information about the Reserved
-- -- Instance Marketplace, go to Reserved Instance Marketplace in the Amazon
-- -- Elastic Compute Cloud User Guide. You determine the Reserved Instance
-- -- Marketplace offerings by specifying true for the optional
-- -- includeMarketplace parameter when calling
-- -- DescribeReservedInstancesOfferings. After you've identified the Reserved
-- -- Instance with the offering type you want, specify its
-- -- reservedInstancesOfferingId when you call
-- -- PurchaseReservedInstancesOffering.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-PurchaseReservedInstancesOffering.html>
-- data PurchaseReservedInstancesOffering = PurchaseReservedInstancesOffering
-- { prioReservedInstancesOfferingId :: !Text
-- -- ^ The ID of the Reserved Instance offering you want to purchase.
-- , prioInstanceCount :: !Integer
-- -- ^ The number of Reserved Instances to purchase.
-- , prioLimitPrice :: Maybe ReservedInstanceLimitPriceType
-- -- ^ Specified for Reserved Instance Marketplace offerings to limit
-- -- the total order and ensure that the Reserved Instances are not
-- -- purchased at unexpected prices.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery PurchaseReservedInstancesOffering
-- instance AWSRequest EC2 PurchaseReservedInstancesOffering PurchaseReservedInstancesOfferingResponse where
-- request = query4 ec2 GET "PurchaseReservedInstancesOffering"
-- data PurchaseReservedInstancesOfferingResponse = PurchaseReservedInstancesOfferingResponse
-- { prioRequestId :: !Text
-- -- ^ The ID of the request.
-- , prioReservedInstancesId :: !Text
-- -- ^ The IDs of the purchased Reserved Instances.
-- } deriving (Eq, Show, Generic)
-- instance IsXML PurchaseReservedInstancesOfferingResponse where
-- xmlPickler = ec2XML
-- -- | Requests a reboot of one or more instances. This operation is asynchronous;
-- -- it only queues a request to reboot the specified instance(s). The operation
-- -- will succeed if the instances are valid and belong to you. Requests to
-- -- reboot terminated instances are ignored.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RebootInstances.html>
-- data RebootInstances = RebootInstances
-- { riInstanceId :: Members Text
-- -- ^ One or more instance IDs.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery RebootInstances
-- instance AWSRequest EC2 RebootInstances RebootInstancesResponse where
-- request = query4 ec2 GET "RebootInstances"
-- data RebootInstancesResponse = RebootInstancesResponse
-- { riRequestId :: !Text
-- -- ^ The ID of the request.
-- , riReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML RebootInstancesResponse where
-- xmlPickler = ec2XML
-- -- | Registers an AMI. When you're creating an AMI, this is the final step you
-- -- must complete before you can launch an instance from the AMI. For more
-- -- information about creating AMIs, see Creating Your Own AMIs in the Amazon
-- -- Elastic Compute Cloud User Guide.You can also use the RegisterImage action
-- -- to create an EBS-backed AMI from a snapshot of a root device volume. For
-- -- more information, see Launching an Instance from a Snapshot in the Amazon
-- -- Elastic Compute Cloud User Guide.If needed, you can deregister an AMI at
-- -- any time. Any modifications you make to an AMI backed by instance store
-- -- invalidates its registration. If you make changes to an image, deregister
-- -- the previous image and register the new image.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RegisterImage.html>
-- data RegisterImage = RegisterImage
-- { riImageLocation :: !Text
-- -- ^ The full path to your AMI manifest in Amazon S3 storage.
-- , riName :: !Text
-- -- ^ A name for your AMI.
-- , riDescription :: Maybe Text
-- -- ^ A description for your AMI.
-- , riArchitecture :: Maybe Text
-- -- ^ The architecture of the image.
-- , riKernelId :: Maybe Text
-- -- ^ The ID of the kernel.
-- , riRamdiskId :: Maybe Text
-- -- ^ The ID of the RAM disk.
-- , riVirtualizationType :: Maybe Text
-- -- ^ The type of virtualization.
-- , riRootDeviceName :: !Text
-- -- ^ The name of the root device (for example, /dev/sda1, or xvda).
-- , riBlockDeviceMapping :: Members BlockDeviceMappingType
-- -- ^ The device name exposed to the instance (for example, /dev/sdh or
-- -- xvdh).
-- } deriving (Eq, Show, Generic)
-- instance IsQuery RegisterImage
-- instance IsXML RegisterImage where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 RegisterImage RegisterImageResponse where
-- request = query4 ec2 GET "RegisterImage"
-- data RegisterImageResponse = RegisterImageResponse
-- { rjRequestId :: !Text
-- -- ^ The ID of the request.
-- , rjImageId :: !Text
-- -- ^ The ID of the newly registered AMI.
-- } deriving (Eq, Show, Generic)
-- instance IsXML RegisterImageResponse where
-- xmlPickler = ec2XML
-- -- | Releases the specified Elastic IP address. An Elastic IP address is for use
-- -- either in the EC2-Classic platform or in a VPC.[EC2-Classic, default VPC] Releasing an Elastic IP address
-- -- automatically disassociates it from any instance that it's associated with.
-- -- To disassociate an Elastic IP address without releasing it, use the
-- -- ec2-disassociate-address command. [Nondefault VPC] You must use the
-- -- ec2-disassociate-address command to disassociate the Elastic IP address
-- -- before you try to release it. Otherwise, Amazon EC2 returns an error
-- -- (InvalidIPAddress.InUse).
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReleaseAddress.html>
-- data ReleaseAddress = ReleaseAddress
-- { raPublicIp :: !Text
-- -- ^ [EC2-Classic] The Elastic IP address.
-- , raAllocationId :: !Text
-- -- ^ [EC2-VPC] The allocation ID.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ReleaseAddress
-- instance AWSRequest EC2 ReleaseAddress ReleaseAddressResponse where
-- request = query4 ec2 GET "ReleaseAddress"
-- data ReleaseAddressResponse = ReleaseAddressResponse
-- { raRequestId :: !Text
-- -- ^ The ID of the request.
-- , raReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ReleaseAddressResponse where
-- xmlPickler = ec2XML
-- -- | Changes which network ACL a subnet is associated with. By default when you
-- -- create a subnet, it's automatically associated with the default network
-- -- ACL. For more information about network ACLs, see Network ACLs in the
-- -- Amazon Virtual Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceNetworkAclAssociation.html>
-- data ReplaceNetworkAclAssociation = ReplaceNetworkAclAssociation
-- { rnaaAssociationId :: !Text
-- -- ^ The ID representing the current association between the original
-- -- network ACL and the subnet.
-- , rnaaNetworkAclId :: !Text
-- -- ^ The ID of the new ACL to associate with the subnet.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ReplaceNetworkAclAssociation
-- instance AWSRequest EC2 ReplaceNetworkAclAssociation ReplaceNetworkAclAssociationResponse where
-- request = query4 ec2 GET "ReplaceNetworkAclAssociation"
-- data ReplaceNetworkAclAssociationResponse = ReplaceNetworkAclAssociationResponse
-- { rnaaRequestId :: !Text
-- -- ^ The ID of the request.
-- , rnaaNewAssociationId :: !Text
-- -- ^ The ID of the new association.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ReplaceNetworkAclAssociationResponse where
-- xmlPickler = ec2XML
-- -- | Replaces an entry (rule) in a network ACL. For more information about
-- -- network ACLs, see Network ACLs in the Amazon Virtual Private Cloud User
-- -- Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceNetworkAclEntry.html>
-- data ReplaceNetworkAclEntry = ReplaceNetworkAclEntry
-- { rnaeNetworkAclId :: !Text
-- -- ^ The ID of the ACL.
-- , rnaeRuleNumber :: !Integer
-- -- ^ The rule number of the entry to replace.
-- , rnaeProtocol :: !Integer
-- -- ^ The IP protocol the rule applies to. You can use -1 to mean all
-- -- protocols.
-- , rnaeRuleAction :: !Text
-- -- ^ Indicates whether to allow or deny traffic that matches the rule.
-- , rnaeEgress :: Maybe Bool
-- -- ^ Indicates whether this rule applies to egress traffic from the
-- -- subnet (true) or ingress traffic to the subnet (false).
-- , rnaeCidrBlock :: !Text
-- -- ^ The CIDR range to allow or deny, in CIDR notation (for example,
-- -- 172.16.0.0/24).
-- , rnaeIcmp :: Members IcmpType
-- -- ^ For the ICMP protocol, the ICMP code. You can use -1 to specify
-- -- all ICMP codes for the given ICMP type.
-- , rnaePortRange :: Members PortRangeType
-- -- ^ The first port in the range.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ReplaceNetworkAclEntry
-- instance AWSRequest EC2 ReplaceNetworkAclEntry ReplaceNetworkAclEntryResponse where
-- request = query4 ec2 GET "ReplaceNetworkAclEntry"
-- data ReplaceNetworkAclEntryResponse = ReplaceNetworkAclEntryResponse
-- { rnaeRequestId :: !Text
-- -- ^ The ID of the request.
-- , rnaeReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ReplaceNetworkAclEntryResponse where
-- xmlPickler = ec2XML
-- -- | Replaces an existing route within a route table in a VPC. For more
-- -- information about route tables, see Route Tables in the Amazon Virtual
-- -- Private Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRoute.html>
-- data ReplaceRoute = ReplaceRoute
-- { rrRouteTableId :: !Text
-- -- ^ The ID of the route table.
-- , rrDestinationCidrBlock :: !Text
-- -- ^ The CIDR address block used for the destination match. The value
-- -- you provide must match the CIDR of an existing route in the
-- -- table.
-- , rrGatewayId :: !Text
-- -- ^ The ID of a gateway attached to your VPC.
-- , rrInstanceId :: !Text
-- -- ^ The ID of a NAT instance in your VPC.
-- , rrNetworkInterfaceId :: !Text
-- -- ^ Allows routing to network interface attachments.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ReplaceRoute
-- instance IsXML ReplaceRoute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ReplaceRoute ReplaceRouteResponse where
-- request = query4 ec2 GET "ReplaceRoute"
-- data ReplaceRouteResponse = ReplaceRouteResponse
-- { rrRequestId :: !Text
-- -- ^ The ID of the request.
-- , rrReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ReplaceRouteResponse where
-- xmlPickler = ec2XML
-- -- | Changes the route table associated with a given subnet in a VPC. After you
-- -- execute this action, the subnet uses the routes in the new route table it's
-- -- associated with. For more information about route tables, see Route Tables
-- -- in the Amazon Virtual Private Cloud User Guide.You can also use this action
-- -- to change which table is the main route table in the VPC. You just specify
-- -- the main route table's association ID and the route table that you want to
-- -- be the new main route table.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRouteTableAssociation.html>
-- data ReplaceRouteTableAssociation = ReplaceRouteTableAssociation
-- { rrtaAssociationId :: !Text
-- -- ^ The association ID.
-- , rrtaRouteTableId :: !Text
-- -- ^ The ID of the new route table to associate with the subnet.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ReplaceRouteTableAssociation
-- instance AWSRequest EC2 ReplaceRouteTableAssociation ReplaceRouteTableAssociationResponse where
-- request = query4 ec2 GET "ReplaceRouteTableAssociation"
-- data ReplaceRouteTableAssociationResponse = ReplaceRouteTableAssociationResponse
-- { rrtaRequestId :: !Text
-- -- ^ The ID of the request.
-- , rrtaNewAssociationId :: !Text
-- -- ^ The ID of the new association.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ReplaceRouteTableAssociationResponse where
-- xmlPickler = ec2XML
-- -- | Use this action to submit feedback about an instance's status. This action
-- -- works only for instances that are in the running state. If your experience
-- -- with the instance differs from the instance status returned by the
-- -- DescribeInstanceStatus action, use ReportInstanceStatus to report your
-- -- experience with the instance. Amazon EC2 collects this information to
-- -- improve the accuracy of status checks. To report an instance's status,
-- -- specify an instance ID with the InstanceId.n parameter and a reason code
-- -- with the ReasonCode.n parameter that applies to that instance. The
-- -- following table contains descriptions of all available reason codes.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReportInstanceStatus.html>
-- data ReportInstanceStatus = ReportInstanceStatus
-- { risInstanceId :: Members Text
-- -- ^ One or more instance IDs.
-- , risStatus :: !Text
-- -- ^ The status of all instances listed in the InstanceId.n parameter.
-- , risStartTime :: Maybe UTCTime
-- -- ^ The time at which the reported instance health state began.
-- , risEndTime :: Maybe UTCTime
-- -- ^ The time at which the reported instance health state ended.
-- , risReasonCode :: Members Text
-- -- ^ A reason code that describes a specific instance's health state.
-- -- Each code you supply corresponds to an instance ID that you
-- -- supply with the InstanceId.n parameter. See the Description
-- -- section for descriptions of each reason code.
-- , risDescription :: Maybe Text
-- -- ^ Descriptive text about the instance health state.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ReportInstanceStatus
-- instance AWSRequest EC2 ReportInstanceStatus ReportInstanceStatusResponse where
-- request = query4 ec2 GET "ReportInstanceStatus"
-- data ReportInstanceStatusResponse = ReportInstanceStatusResponse
-- { risRequestId :: !Text
-- -- ^ The ID of the request.
-- , risReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ReportInstanceStatusResponse where
-- xmlPickler = ec2XML
-- -- | Creates a Spot Instance request. Spot Instances are instances that Amazon
-- -- EC2 starts on your behalf when the maximum price that you specify exceeds
-- -- the current Spot Price. Amazon EC2 periodically sets the Spot Price based
-- -- on available Spot Instance capacity and current Spot Instance requests. For
-- -- more information about Spot Instances, see Spot Instances in the Amazon
-- -- Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RequestSpotInstances.html>
-- data RequestSpotInstances = RequestSpotInstances
-- { rsiSpotPrice :: !Text
-- -- ^ The maximum hourly price for any Spot Instance launched to
-- -- fulfill the request.
-- , rsiInstanceCount :: Maybe Integer
-- -- ^ The maximum number of Spot Instances to launch.
-- , rsiType :: Maybe Text
-- -- ^ The Spot Instance request type.
-- , rsiValidFrom :: Maybe 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.
-- , rsiValidUntil :: Maybe 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 and time is
-- -- reached.
-- , rsiLaunchGroup :: Maybe Text
-- -- ^ The instance launch group. Launch groups are Spot Instances that
-- -- launch together and terminate together.
-- , rsiAvailabilityZoneGroup :: Maybe Text
-- -- ^ The user-specified name for a logical grouping of bids.
-- , rsiLaunchSpecification :: Members LaunchSpecificationType
-- -- ^ The ID of the AMI.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery RequestSpotInstances
-- instance AWSRequest EC2 RequestSpotInstances RequestSpotInstancesResponse where
-- request = query4 ec2 GET "RequestSpotInstances"
-- data RequestSpotInstancesResponse = RequestSpotInstancesResponse
-- { rsiRequestId :: !Text
-- -- ^ The ID of the request.
-- , rsiSpotInstanceRequestSet :: !SpotInstanceRequestSetItemType
-- -- ^ Information about the Spot Instance request, wrapped in an item
-- -- element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML RequestSpotInstancesResponse where
-- xmlPickler = ec2XML
-- -- | Resets an attribute of an AMI to its default value.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ResetImageAttribute.html>
-- data ResetImageAttribute = ResetImageAttribute
-- { riaImageId :: !Text
-- -- ^ The ID of the AMI.
-- , riaAttribute :: !Text
-- -- ^ The attribute to reset (currently you can only reset the launch
-- -- permission attribute).
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ResetImageAttribute
-- instance IsXML ResetImageAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ResetImageAttribute ResetImageAttributeResponse where
-- request = query4 ec2 GET "ResetImageAttribute"
-- data ResetImageAttributeResponse = ResetImageAttributeResponse
-- { riaRequestId :: !Text
-- -- ^ The ID of the request.
-- , riaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ResetImageAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Resets an attribute of an instance to its default value. To reset the
-- -- kernel or RAM disk, the instance must be in a stopped state. To reset the
-- -- SourceDestCheck, the instance can be either running or stopped. The
-- -- SourceDestCheck attribute controls whether source/destination checking is
-- -- enabled. The default value is true, which means checking is enabled. This
-- -- value must be false for a NAT instance to perform NAT. For more
-- -- information, see NAT Instances in the Amazon Virtual Private Cloud User
-- -- Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ResetInstanceAttribute.html>
-- data ResetInstanceAttribute = ResetInstanceAttribute
-- { riaInstanceId :: !Text
-- -- ^ The ID of the instance.
-- , ribAttribute :: !Text
-- -- ^ The attribute to reset.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ResetInstanceAttribute
-- instance IsXML ResetInstanceAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ResetInstanceAttribute ResetInstanceAttributeResponse where
-- request = query4 ec2 GET "ResetInstanceAttribute"
-- data ResetInstanceAttributeResponse = ResetInstanceAttributeResponse
-- { ribRequestId :: !Text
-- -- ^ The ID of the request.
-- , ribReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ResetInstanceAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Resets a network interface attribute. You can specify only one attribute at
-- -- a time.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ResetNetworkInterfaceAttribute.html>
-- data ResetNetworkInterfaceAttribute = ResetNetworkInterfaceAttribute
-- { rniaNetworkInterfaceId :: !Text
-- -- ^ The ID of the network interface.
-- , rniaAttribute :: !Text
-- -- ^ The name of the attribute to reset.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ResetNetworkInterfaceAttribute
-- instance IsXML ResetNetworkInterfaceAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ResetNetworkInterfaceAttribute ResetNetworkInterfaceAttributeResponse where
-- request = query4 ec2 GET "ResetNetworkInterfaceAttribute"
-- data ResetNetworkInterfaceAttributeResponse = ResetNetworkInterfaceAttributeResponse
-- { rniaRequestId :: !Text
-- -- ^ The ID of the request.
-- , rniaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ResetNetworkInterfaceAttributeResponse where
-- xmlPickler = ec2XML
-- -- | Resets permission settings for the specified snapshot.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ResetSnapshotAttribute.html>
-- data ResetSnapshotAttribute = ResetSnapshotAttribute
-- { rsaSnapshotId :: !Text
-- -- ^ The ID of the snapshot.
-- , rsaAttribute :: !Text
-- -- ^ The attribute to reset (currently only the attribute for
-- -- permission to create volumes can be reset)
-- } deriving (Eq, Show, Generic)
-- instance IsQuery ResetSnapshotAttribute
-- instance IsXML ResetSnapshotAttribute where
-- xmlPickler = ec2XML
-- instance AWSRequest EC2 ResetSnapshotAttribute ResetSnapshotAttributeResponse where
-- request = query4 ec2 GET "ResetSnapshotAttribute"
-- data ResetSnapshotAttributeResponse = ResetSnapshotAttributeResponse
-- { rsaRequestId :: !Text
-- -- ^ The ID of the request.
-- , rsaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML ResetSnapshotAttributeResponse where
-- xmlPickler = ec2XML
-- | Removes one or more egress rules from a security group for EC2-VPC.
--
-- The values that you specify in the revoke request (for example, ports) must
-- match the existing rule's values for the rule to be revoked.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RevokeSecurityGroupEgress.html>
data RevokeSecurityGroupEgress = RevokeSecurityGroupEgress
{ rsgeGroupId :: !Text
-- ^ The ID of the security group to modify.
, rsgeIpPermissions :: [IpPermissionType]
-- ^ The IP protocol name or number (see Protocol Numbers).
} deriving (Eq, Show, Generic)
instance IsQuery RevokeSecurityGroupEgress
instance Rq RevokeSecurityGroupEgress where
type Er RevokeSecurityGroupEgress = EC2ErrorResponse
type Rs RevokeSecurityGroupEgress = RevokeSecurityGroupEgressResponse
request = query4 ec2 GET "RevokeSecurityGroupEgress"
data RevokeSecurityGroupEgressResponse = RevokeSecurityGroupEgressResponse
{ rsgerRequestId :: !Text
-- ^ The ID of the request.
, rsgerReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
} deriving (Eq, Show, Generic)
instance IsXML RevokeSecurityGroupEgressResponse where
xmlPickler = ec2XML
-- | Removes one or more ingress rules from a security group.
--
-- The values that you specify in the revoke request (for example, ports) must
-- match the existing rule's values for the rule to be removed.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RevokeSecurityGroupIngress.html>
data RevokeSecurityGroupIngress = RevokeSecurityGroupIngress
{ rsgiGroupId :: Maybe Text
-- ^ The ID of the security group to modify. The security group must
-- belong to your account.
, rsgiGroupName :: Maybe Text
-- ^ The name of the security group to modify.
, rsgiIpPermissions :: [IpPermissionType]
-- ^ The IP protocol name or number (see Protocol Numbers). For
-- EC2-Classic, security groups can have rules only for TCP, UDP,
-- and ICMP. For EC2-VPC, security groups can have rules assigned to
-- any protocol number.
} deriving (Eq, Show, Generic)
instance IsQuery RevokeSecurityGroupIngress
instance Rq RevokeSecurityGroupIngress where
type Er RevokeSecurityGroupIngress = EC2ErrorResponse
type Rs RevokeSecurityGroupIngress = RevokeSecurityGroupIngressResponse
request = query4 ec2 GET "RevokeSecurityGroupIngress"
data RevokeSecurityGroupIngressResponse = RevokeSecurityGroupIngressResponse
{ rsgirRequestId :: !Text
-- ^ The ID of the request.
, rsgirReturn :: !Bool
-- ^ Returns true if the request succeeds. Otherwise, returns an error.
} deriving (Eq, Show, Generic)
instance IsXML RevokeSecurityGroupIngressResponse where
xmlPickler = ec2XML
-- | Launches the specified number of instances of an AMI for which you have
-- permissions.When you launch an instance, it enters the pending state. After
-- the instance is ready for you, it enters the running state. To check the
-- state of your instance, call DescribeInstances.If you don't specify a
-- security group when launching an instance, Amazon EC2 uses the default
-- security group.Linux instances have access to the public
-- key of the key pair at boot. You can use this key to provide secure access
-- to the instance. Amazon EC2 public images use this feature to provide
-- secure access without passwords.You can provide optional user data
-- when launching an instance.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RunInstances.html>
data RunInstances = RunInstances
{ riImageId :: !Text
-- ^ The ID of the AMI, which you can get by calling DescribeImages.
, riMinCount :: !Integer
-- ^ The minimum number of instances to launch. If you specify a
-- minimum that is more instances than Amazon EC2 can launch in the
-- target Availability Zone, Amazon EC2 launches no instances.
, riMaxCount :: !Integer
-- ^ The maximum number of instances to launch. If you specify more
-- instances than Amazon EC2 can launch in the target Availability
-- Zone, Amazon EC2 launches the largest possible number of
-- instances above MinCount.
, riKeyName :: Maybe Text
-- ^ The name of the key pair. You can create a key pair using
-- CreateKeyPair or ImportKeyPair.
, riSecurityGroupId :: [Text]
-- ^ One or more security group IDs. You can create a security group
-- using CreateSecurityGroup.
, riSecurityGroup :: [Text]
-- ^ [EC2-Classic, default VPC] One or more security group names. For
-- a nondefault VPC, you must use SecurityGroupId.
, riUserData :: Maybe Text
-- ^ The Base64-encoded MIME user data for the instances.
, riInstanceType :: Maybe InstanceType
-- ^ The instance type. Defaults to m1.small if absent.
, riPlacement :: Maybe PlacementType
-- ^ The Availability Zone for the instance.
, rjKernelId :: Maybe Text
-- ^ The ID of the kernel.
, rjRamdiskId :: Maybe Text
-- ^ The ID of the RAM disk.
, rjBlockDeviceMapping :: [InstanceBlockDeviceMappingItemType]
-- ^ The device name exposed to the instance (for example, /dev/sdh or xvdh).
, rjMonitoring :: Maybe MonitoringInstanceType
-- ^ Enables monitoring for the instance.
, rjSubnetId :: Maybe Text
-- ^ [EC2-VPC] The ID of the subnet to launch the instance into.
, rjDisableApiTermination :: Maybe Bool
-- ^ If you set this parameter to true, you can't terminate the
-- instance using the Amazon EC2 console, CLI, or API; otherwise,
-- you can. If you set this parameter to true and then later want to
-- be able to terminate the instance, you must first change the
-- value of the disableApiTermination attribute to false using
-- ModifyInstanceAttribute. Alternatively, if you set
-- InstanceInitiatedShutdownBehavior to terminate, you can terminate
-- the instance by running the shutdown command from the instance.
, rjInstanceInitiatedShutdownBehavior :: Maybe Text -- FIXME: Should be stop | terminate
-- ^ Indicates whether an instance stops or terminates when you
-- initiate shutdown from the instance (using the operating system
-- command for system shutdown).
, rjPrivateIpAddress :: Maybe Text
-- ^ [EC2-VPC] The primary IP address. You must specify a value from
-- the IP address range of the subnet.
, rjClientToken :: Maybe Text
-- ^ Unique, case-sensitive identifier you provide to ensure
-- idempotency of the request.
, rjNetworkInterface :: [NetworkInterfaceType]
-- ^ An existing interface to attach to a single instance. Requires
-- n=1 instances.
, rjIamInstanceProfile :: [IamInstanceProfileRequestType]
-- ^ The Amazon Resource Name (ARN) of the IAM instance profile to
-- associate with the instances.
, rjEbsOptimized :: Maybe 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 Amazon 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, Show, Generic)
instance IsQuery RunInstances
instance Rq RunInstances where
type Er RunInstances = EC2ErrorResponse
type Rs RunInstances = RunInstancesResponse
request = query4 ec2 GET "RunInstances"
data RunInstancesResponse = RunInstancesResponse
{ rirRequestId :: !Text
-- ^ The ID of the request.
, rirReservationId :: !Text
-- ^ The ID of the reservation.
, rirOwnerId :: !Text
-- ^ The ID of the AWS account that owns the reservation.
, rirGroupSet :: [GroupItemType]
-- ^ A list of security groups the instance belongs to. Each group is
-- wrapped in an item element.
, rirInstancesSet :: [RunningInstancesItemType]
-- ^ A list of instances. Each instance is wrapped in an item element.
, rirRequesterId :: Maybe Text
-- ^ The ID of the requester that launched the instances on your
-- behalf (for example, AWS Management Console, Auto Scaling).
} deriving (Eq, Show, Generic)
instance IsXML RunInstancesResponse where
xmlPickler = ec2XML
-- -- | Starts an Amazon EBS-backed AMI that you've previously stopped. Instances
-- -- that use Amazon EBS volumes as their root devices can be quickly stopped
-- -- and started. When an instance is stopped, the compute resources are
-- -- released and you are not billed for hourly instance usage. However, your
-- -- root partition Amazon EBS volume remains, continues to persist your data,
-- -- and you are charged for Amazon EBS volume usage. You can restart your
-- -- instance at any time. Each time you transition an instance from stopped to
-- -- started, we charge a full instance hour, even if transitions happen
-- -- multiple times within a single hour. Before stopping an instance, make sure
-- -- it is in a state from which it can be restarted. Stopping an instance does
-- -- not preserve data stored in RAM. Performing this operation on an instance
-- -- that uses an instance store as its root device returns an error.For more
-- -- information, see Stopping Instances in the Amazon Elastic Compute Cloud
-- -- User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-StartInstances.html>
-- data StartInstances = StartInstances
-- { siInstanceId :: Members Text
-- -- ^ One or more instance IDs.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery StartInstances
-- instance AWSRequest EC2 StartInstances StartInstancesResponse where
-- request = query4 ec2 GET "StartInstances"
-- data StartInstancesResponse = StartInstancesResponse
-- { siRequestId :: !Text
-- -- ^ The ID of the request.
-- , siInstancesSet :: !InstanceStateChangeType
-- -- ^ A list of instance state changes. Each change is wrapped in an
-- -- item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML StartInstancesResponse where
-- xmlPickler = ec2XML
-- -- | Stops an Amazon EBS-backed instance. Each time you transition an instance
-- -- from stopped to started, we charge a full instance hour, even if
-- -- transitions happen multiple times within a single hour.You can't start or
-- -- stop Spot Instances.Instances that use Amazon EBS volumes as their root
-- -- devices can be quickly stopped and started. When an instance is stopped,
-- -- the compute resources are released and you are not billed for hourly
-- -- instance usage. However, your root partition Amazon EBS volume remains,
-- -- continues to persist your data, and you are charged for Amazon EBS volume
-- -- usage. You can restart your instance at any time. Before stopping an
-- -- instance, make sure it is in a state from which it can be restarted.
-- -- Stopping an instance does not preserve data stored in RAM. Performing this
-- -- operation on an instance that uses an instance store as its root device
-- -- returns an error.You can stop, start, and terminate EBS-backed instances.
-- -- You can only terminate S3-backed instances. What happens to an instance
-- -- differs if you stop it or terminate it. For example, when you stop an
-- -- instance, the root device and any other devices attached to the instance
-- -- persist. When you terminate an instance, the root device and any other
-- -- devices attached during the instance launch are automatically deleted. For
-- -- more information about the differences between stopping and terminating
-- -- instances, see Stopping Instances in the Amazon Elastic Compute Cloud User
-- -- Guide
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-StopInstances.html>
-- data StopInstances = StopInstances
-- { sjInstanceId :: Members Text
-- -- ^ One or more instance IDs.
-- , sjForce :: Maybe Bool
-- -- ^ Forces the instances to stop. The instances will not have an
-- -- opportunity to flush file system caches or file system metadata.
-- -- If you use this option, you must perform file system check and
-- -- repair procedures. This option is not recommended for Windows
-- -- instances.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery StopInstances
-- instance AWSRequest EC2 StopInstances StopInstancesResponse where
-- request = query4 ec2 GET "StopInstances"
-- data StopInstancesResponse = StopInstancesResponse
-- { sjRequestId :: !Text
-- -- ^ The ID of the request.
-- , sjInstancesSet :: !InstanceStateChangeType
-- -- ^ A list of instance state changes. Each change is wrapped in an
-- -- item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML StopInstancesResponse where
-- xmlPickler = ec2XML
-- | Shuts down one or more instances. This operation is idempotent; if you
-- terminate an instance more than once, each call will succeed. Terminated
-- instances will remain visible after termination (approximately one
-- hour).You can stop, start, and terminate EBS-backed instances. You can only
-- terminate S3-backed instances. What happens to an instance differs if you
-- stop it or terminate it. For example, when you stop an instance, the root
-- device and any other devices attached to the instance persist. When you
-- terminate an instance, the root device and any other devices attached
-- during the instance launch are automatically deleted. For more information
-- about the differences between stopping and terminating instances, see
-- Stopping Instances in the Amazon Elastic Compute Cloud User Guide
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-TerminateInstances.html>
data TerminateInstances = TerminateInstances
{ tiInstanceId :: [Text]
-- ^ One or more instance IDs.
} deriving (Eq, Show, Generic)
instance IsQuery TerminateInstances
instance Rq TerminateInstances where
type Er TerminateInstances = EC2ErrorResponse
type Rs TerminateInstances = TerminateInstancesResponse
request = query4 ec2 GET "TerminateInstances"
data TerminateInstancesResponse = TerminateInstancesResponse
{ tiRequestId :: !Text
-- ^ The ID of the request.
, tiInstancesSet :: [InstanceStateChangeType]
-- ^ A list of instance state changes. Each change is wrapped in an
-- item element.
} deriving (Eq, Show, Generic)
instance IsXML TerminateInstancesResponse where
xmlPickler = ec2XML
-- instance IsXML TerminateInstancesResponse where
-- xmlPickler = ec2XML
-- -- | Unassigns one or more secondary private IP addresses from a network
-- -- interface.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-UnassignPrivateIpAddresses.html>
-- data UnassignPrivateIpAddresses = UnassignPrivateIpAddresses
-- { upiaNetworkInterfaceId :: !Text
-- -- ^ The network interface from which the secondary private IP address
-- -- will be unassigned.
-- , upiaPrivateIpAddress :: Members AssignPrivateIpAddressesSetItemRequestType
-- -- ^ The secondary private IP addresses that you want to unassign from
-- -- the network interface. You can specify this option multiple times
-- -- to unassign more than one IP address.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery UnassignPrivateIpAddresses
-- instance AWSRequest EC2 UnassignPrivateIpAddresses UnassignPrivateIpAddressesResponse where
-- request = query4 ec2 GET "UnassignPrivateIpAddresses"
-- data UnassignPrivateIpAddressesResponse = UnassignPrivateIpAddressesResponse
-- { upiaRequestId :: !Text
-- -- ^ The ID of the request.
-- , upiaReturn :: !Bool
-- -- ^ Returns true if the request succeeds. Otherwise, returns an
-- -- error.
-- } deriving (Eq, Show, Generic)
-- instance IsXML UnassignPrivateIpAddressesResponse where
-- xmlPickler = ec2XML
-- -- | Disables monitoring for a running instance. For more information about
-- -- monitoring instances, see Monitoring Your Instances and Volumes in the
-- -- Amazon Elastic Compute Cloud User Guide.
-- --
-- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-UnmonitorInstances.html>
-- data UnmonitorInstances = UnmonitorInstances
-- { uiInstanceId :: Members Text
-- -- ^ One or more instance IDs.
-- } deriving (Eq, Show, Generic)
-- instance IsQuery UnmonitorInstances
-- instance AWSRequest EC2 UnmonitorInstances UnmonitorInstancesResponse where
-- request = query4 ec2 GET "UnmonitorInstances"
-- data UnmonitorInstancesResponse = UnmonitorInstancesResponse
-- { uiRequestId :: !Text
-- -- ^ The ID of the request.
-- , uiInstancesSet :: !MonitorInstancesResponseSetItemType
-- -- ^ A list of monitoring information for one or more instances. Each
-- -- set of information is wrapped in an item element.
-- } deriving (Eq, Show, Generic)
-- instance IsXML UnmonitorInstancesResponse where
-- xmlPickler = ec2XML
| zinfra/khan | amazonka-limited/src/Network/AWS/EC2.hs | mpl-2.0 | 270,992 | 0 | 10 | 63,474 | 10,152 | 7,722 | 2,430 | 836 | 0 |
{-# 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.RegionInstanceGroupManagers.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified managed instance group and all of the instances in
-- that group.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionInstanceGroupManagers.delete@.
module Network.Google.Resource.Compute.RegionInstanceGroupManagers.Delete
(
-- * REST Resource
RegionInstanceGroupManagersDeleteResource
-- * Creating a Request
, regionInstanceGroupManagersDelete
, RegionInstanceGroupManagersDelete
-- * Request Lenses
, rigmdRequestId
, rigmdProject
, rigmdInstanceGroupManager
, rigmdRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.regionInstanceGroupManagers.delete@ method which the
-- 'RegionInstanceGroupManagersDelete' request conforms to.
type RegionInstanceGroupManagersDeleteResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"instanceGroupManagers" :>
Capture "instanceGroupManager" Text :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Operation
-- | Deletes the specified managed instance group and all of the instances in
-- that group.
--
-- /See:/ 'regionInstanceGroupManagersDelete' smart constructor.
data RegionInstanceGroupManagersDelete =
RegionInstanceGroupManagersDelete'
{ _rigmdRequestId :: !(Maybe Text)
, _rigmdProject :: !Text
, _rigmdInstanceGroupManager :: !Text
, _rigmdRegion :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegionInstanceGroupManagersDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rigmdRequestId'
--
-- * 'rigmdProject'
--
-- * 'rigmdInstanceGroupManager'
--
-- * 'rigmdRegion'
regionInstanceGroupManagersDelete
:: Text -- ^ 'rigmdProject'
-> Text -- ^ 'rigmdInstanceGroupManager'
-> Text -- ^ 'rigmdRegion'
-> RegionInstanceGroupManagersDelete
regionInstanceGroupManagersDelete pRigmdProject_ pRigmdInstanceGroupManager_ pRigmdRegion_ =
RegionInstanceGroupManagersDelete'
{ _rigmdRequestId = Nothing
, _rigmdProject = pRigmdProject_
, _rigmdInstanceGroupManager = pRigmdInstanceGroupManager_
, _rigmdRegion = pRigmdRegion_
}
-- | 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).
rigmdRequestId :: Lens' RegionInstanceGroupManagersDelete (Maybe Text)
rigmdRequestId
= lens _rigmdRequestId
(\ s a -> s{_rigmdRequestId = a})
-- | Project ID for this request.
rigmdProject :: Lens' RegionInstanceGroupManagersDelete Text
rigmdProject
= lens _rigmdProject (\ s a -> s{_rigmdProject = a})
-- | Name of the managed instance group to delete.
rigmdInstanceGroupManager :: Lens' RegionInstanceGroupManagersDelete Text
rigmdInstanceGroupManager
= lens _rigmdInstanceGroupManager
(\ s a -> s{_rigmdInstanceGroupManager = a})
-- | Name of the region scoping this request.
rigmdRegion :: Lens' RegionInstanceGroupManagersDelete Text
rigmdRegion
= lens _rigmdRegion (\ s a -> s{_rigmdRegion = a})
instance GoogleRequest
RegionInstanceGroupManagersDelete
where
type Rs RegionInstanceGroupManagersDelete = Operation
type Scopes RegionInstanceGroupManagersDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient RegionInstanceGroupManagersDelete'{..}
= go _rigmdProject _rigmdRegion
_rigmdInstanceGroupManager
_rigmdRequestId
(Just AltJSON)
computeService
where go
= buildClient
(Proxy ::
Proxy RegionInstanceGroupManagersDeleteResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/RegionInstanceGroupManagers/Delete.hs | mpl-2.0 | 5,453 | 0 | 17 | 1,157 | 554 | 332 | 222 | 91 | 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.GamesManagement.Quests.ResetMultipleForAllPlayers
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Resets quests with the given IDs for all players. This method is only
-- available to user accounts for your developer console. Only draft quests
-- may be reset.
--
-- /See:/ <https://developers.google.com/games/services Google Play Game Services Management API Reference> for @gamesManagement.quests.resetMultipleForAllPlayers@.
module Network.Google.Resource.GamesManagement.Quests.ResetMultipleForAllPlayers
(
-- * REST Resource
QuestsResetMultipleForAllPlayersResource
-- * Creating a Request
, questsResetMultipleForAllPlayers
, QuestsResetMultipleForAllPlayers
-- * Request Lenses
, qrmfapPayload
) where
import Network.Google.GamesManagement.Types
import Network.Google.Prelude
-- | A resource alias for @gamesManagement.quests.resetMultipleForAllPlayers@ method which the
-- 'QuestsResetMultipleForAllPlayers' request conforms to.
type QuestsResetMultipleForAllPlayersResource =
"games" :>
"v1management" :>
"quests" :>
"resetMultipleForAllPlayers" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] QuestsResetMultipleForAllRequest :>
Post '[JSON] ()
-- | Resets quests with the given IDs for all players. This method is only
-- available to user accounts for your developer console. Only draft quests
-- may be reset.
--
-- /See:/ 'questsResetMultipleForAllPlayers' smart constructor.
newtype QuestsResetMultipleForAllPlayers =
QuestsResetMultipleForAllPlayers'
{ _qrmfapPayload :: QuestsResetMultipleForAllRequest
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'QuestsResetMultipleForAllPlayers' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'qrmfapPayload'
questsResetMultipleForAllPlayers
:: QuestsResetMultipleForAllRequest -- ^ 'qrmfapPayload'
-> QuestsResetMultipleForAllPlayers
questsResetMultipleForAllPlayers pQrmfapPayload_ =
QuestsResetMultipleForAllPlayers' {_qrmfapPayload = pQrmfapPayload_}
-- | Multipart request metadata.
qrmfapPayload :: Lens' QuestsResetMultipleForAllPlayers QuestsResetMultipleForAllRequest
qrmfapPayload
= lens _qrmfapPayload
(\ s a -> s{_qrmfapPayload = a})
instance GoogleRequest
QuestsResetMultipleForAllPlayers
where
type Rs QuestsResetMultipleForAllPlayers = ()
type Scopes QuestsResetMultipleForAllPlayers =
'["https://www.googleapis.com/auth/games"]
requestClient QuestsResetMultipleForAllPlayers'{..}
= go (Just AltJSON) _qrmfapPayload
gamesManagementService
where go
= buildClient
(Proxy ::
Proxy QuestsResetMultipleForAllPlayersResource)
mempty
| brendanhay/gogol | gogol-games-management/gen/Network/Google/Resource/GamesManagement/Quests/ResetMultipleForAllPlayers.hs | mpl-2.0 | 3,661 | 0 | 13 | 756 | 316 | 195 | 121 | 54 | 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.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified HL7v2 store and removes all messages that it
-- contains.
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.hl7V2Stores.delete@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.Delete
(
-- * REST Resource
ProjectsLocationsDataSetsHl7V2StoresDeleteResource
-- * Creating a Request
, projectsLocationsDataSetsHl7V2StoresDelete
, ProjectsLocationsDataSetsHl7V2StoresDelete
-- * Request Lenses
, pldshvsdXgafv
, pldshvsdUploadProtocol
, pldshvsdAccessToken
, pldshvsdUploadType
, pldshvsdName
, pldshvsdCallback
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.hl7V2Stores.delete@ method which the
-- 'ProjectsLocationsDataSetsHl7V2StoresDelete' request conforms to.
type ProjectsLocationsDataSetsHl7V2StoresDeleteResource
=
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes the specified HL7v2 store and removes all messages that it
-- contains.
--
-- /See:/ 'projectsLocationsDataSetsHl7V2StoresDelete' smart constructor.
data ProjectsLocationsDataSetsHl7V2StoresDelete =
ProjectsLocationsDataSetsHl7V2StoresDelete'
{ _pldshvsdXgafv :: !(Maybe Xgafv)
, _pldshvsdUploadProtocol :: !(Maybe Text)
, _pldshvsdAccessToken :: !(Maybe Text)
, _pldshvsdUploadType :: !(Maybe Text)
, _pldshvsdName :: !Text
, _pldshvsdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsHl7V2StoresDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldshvsdXgafv'
--
-- * 'pldshvsdUploadProtocol'
--
-- * 'pldshvsdAccessToken'
--
-- * 'pldshvsdUploadType'
--
-- * 'pldshvsdName'
--
-- * 'pldshvsdCallback'
projectsLocationsDataSetsHl7V2StoresDelete
:: Text -- ^ 'pldshvsdName'
-> ProjectsLocationsDataSetsHl7V2StoresDelete
projectsLocationsDataSetsHl7V2StoresDelete pPldshvsdName_ =
ProjectsLocationsDataSetsHl7V2StoresDelete'
{ _pldshvsdXgafv = Nothing
, _pldshvsdUploadProtocol = Nothing
, _pldshvsdAccessToken = Nothing
, _pldshvsdUploadType = Nothing
, _pldshvsdName = pPldshvsdName_
, _pldshvsdCallback = Nothing
}
-- | V1 error format.
pldshvsdXgafv :: Lens' ProjectsLocationsDataSetsHl7V2StoresDelete (Maybe Xgafv)
pldshvsdXgafv
= lens _pldshvsdXgafv
(\ s a -> s{_pldshvsdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldshvsdUploadProtocol :: Lens' ProjectsLocationsDataSetsHl7V2StoresDelete (Maybe Text)
pldshvsdUploadProtocol
= lens _pldshvsdUploadProtocol
(\ s a -> s{_pldshvsdUploadProtocol = a})
-- | OAuth access token.
pldshvsdAccessToken :: Lens' ProjectsLocationsDataSetsHl7V2StoresDelete (Maybe Text)
pldshvsdAccessToken
= lens _pldshvsdAccessToken
(\ s a -> s{_pldshvsdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldshvsdUploadType :: Lens' ProjectsLocationsDataSetsHl7V2StoresDelete (Maybe Text)
pldshvsdUploadType
= lens _pldshvsdUploadType
(\ s a -> s{_pldshvsdUploadType = a})
-- | The resource name of the HL7v2 store to delete.
pldshvsdName :: Lens' ProjectsLocationsDataSetsHl7V2StoresDelete Text
pldshvsdName
= lens _pldshvsdName (\ s a -> s{_pldshvsdName = a})
-- | JSONP
pldshvsdCallback :: Lens' ProjectsLocationsDataSetsHl7V2StoresDelete (Maybe Text)
pldshvsdCallback
= lens _pldshvsdCallback
(\ s a -> s{_pldshvsdCallback = a})
instance GoogleRequest
ProjectsLocationsDataSetsHl7V2StoresDelete
where
type Rs ProjectsLocationsDataSetsHl7V2StoresDelete =
Empty
type Scopes
ProjectsLocationsDataSetsHl7V2StoresDelete
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsHl7V2StoresDelete'{..}
= go _pldshvsdName _pldshvsdXgafv
_pldshvsdUploadProtocol
_pldshvsdAccessToken
_pldshvsdUploadType
_pldshvsdCallback
(Just AltJSON)
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsHl7V2StoresDeleteResource)
mempty
| brendanhay/gogol | gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/Hl7V2Stores/Delete.hs | mpl-2.0 | 5,654 | 0 | 15 | 1,186 | 699 | 410 | 289 | 111 | 1 |
module Main where
import qualified Snap.Assets as A
import Snap.Core
import Snap.Http.Server
import System.Directory
import Control.Applicative
assets :: [ A.Asset ]
assets =
[ A.Asset "frameworks.js" $ A.concatBuilder
[ "frameworks/jquery-1.7.1.js"
, "frameworks/backbone.js"
, "frameworks/jquery.plugin-foo.js"
]
, A.Asset "test.js" $ A.concatBuilder [ "test.js" ]
]
main :: IO ()
main = do
config0 <- A.defaultConfig
let config = config0 { A.assetDefinitions = assets }
manifest <- A.compileAssets config "output"
putStrLn $ show manifest
| wereHamster/snap-assets | src/CLI.hs | unlicense | 607 | 0 | 11 | 137 | 161 | 87 | 74 | 19 | 1 |
-- Copyright 2016 TensorFlow authors.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
-- We use UndecidableInstances for type families with recursive definitions
-- like "\\". Those instances will terminate since each equation unwraps one
-- cons cell of a type-level list.
{-# LANGUAGE UndecidableInstances #-}
module TensorFlow.Types
( TensorType(..)
, TensorData(..)
, TensorDataType(..)
, Scalar(..)
, Shape(..)
, protoShape
, Attribute(..)
, DataType(..)
, ResourceHandle
, Variant
-- * Lists
, ListOf(..)
, List
, (/:/)
, TensorTypeProxy(..)
, TensorTypes(..)
, TensorTypeList
, fromTensorTypeList
, fromTensorTypes
-- * Type constraints
, OneOf
, type (/=)
, OneOfs
-- ** Implementation of constraints
, TypeError
, ExcludedCase
, NoneOf
, type (\\)
, Delete
, AllTensorTypes
) where
import Data.ProtoLens.Message(defMessage)
import Data.Functor.Identity (Identity(..))
import Data.Complex (Complex)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Maybe (fromMaybe)
import Data.ProtoLens.TextFormat (showMessageShort)
import Data.Proxy (Proxy(..))
import Data.String (IsString)
import Data.Word (Word8, Word16, Word32, Word64)
import Foreign.Storable (Storable)
import GHC.Exts (Constraint, IsList(..))
import Lens.Family2 (Lens', view, (&), (.~), (^..), under)
import Lens.Family2.Unchecked (adapter)
import Text.Printf (printf)
import qualified Data.Attoparsec.ByteString as Atto
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.ByteString.Builder (Builder)
import qualified Data.ByteString.Builder as Builder
import qualified Data.ByteString.Lazy as L
import qualified Data.Vector as V
import qualified Data.Vector.Storable as S
import Proto.Tensorflow.Core.Framework.AttrValue
( AttrValue
, AttrValue'ListValue
)
import Proto.Tensorflow.Core.Framework.AttrValue_Fields
( b
, f
, i
, s
, list
, type'
, shape
, tensor
)
import Proto.Tensorflow.Core.Framework.ResourceHandle
(ResourceHandleProto)
import Proto.Tensorflow.Core.Framework.Tensor as Tensor
(TensorProto)
import Proto.Tensorflow.Core.Framework.Tensor_Fields as Tensor
( boolVal
, doubleVal
, floatVal
, intVal
, int64Val
, resourceHandleVal
, stringVal
, uint32Val
, uint64Val
)
import Proto.Tensorflow.Core.Framework.TensorShape
(TensorShapeProto)
import Proto.Tensorflow.Core.Framework.TensorShape_Fields
( dim
, size
, unknownRank
)
import Proto.Tensorflow.Core.Framework.Types (DataType(..))
import TensorFlow.Internal.VarInt (getVarInt, putVarInt)
import qualified TensorFlow.Internal.FFI as FFI
type ResourceHandle = ResourceHandleProto
-- | Dynamic type.
-- TensorFlow variants aren't supported yet. This type acts a placeholder to
-- simplify op generation.
data Variant
-- | The class of scalar types supported by tensorflow.
class TensorType a where
tensorType :: a -> DataType
tensorRefType :: a -> DataType
tensorVal :: Lens' TensorProto [a]
instance TensorType Float where
tensorType _ = DT_FLOAT
tensorRefType _ = DT_FLOAT_REF
tensorVal = floatVal
instance TensorType Double where
tensorType _ = DT_DOUBLE
tensorRefType _ = DT_DOUBLE_REF
tensorVal = doubleVal
instance TensorType Int32 where
tensorType _ = DT_INT32
tensorRefType _ = DT_INT32_REF
tensorVal = intVal
instance TensorType Int64 where
tensorType _ = DT_INT64
tensorRefType _ = DT_INT64_REF
tensorVal = int64Val
integral :: Integral a => Lens' [Int32] [a]
integral = under (adapter (fmap fromIntegral) (fmap fromIntegral))
instance TensorType Word8 where
tensorType _ = DT_UINT8
tensorRefType _ = DT_UINT8_REF
tensorVal = intVal . integral
instance TensorType Word16 where
tensorType _ = DT_UINT16
tensorRefType _ = DT_UINT16_REF
tensorVal = intVal . integral
instance TensorType Word32 where
tensorType _ = DT_UINT32
tensorRefType _ = DT_UINT32_REF
tensorVal = uint32Val
instance TensorType Word64 where
tensorType _ = DT_UINT64
tensorRefType _ = DT_UINT64_REF
tensorVal = uint64Val
instance TensorType Int16 where
tensorType _ = DT_INT16
tensorRefType _ = DT_INT16_REF
tensorVal = intVal . integral
instance TensorType Int8 where
tensorType _ = DT_INT8
tensorRefType _ = DT_INT8_REF
tensorVal = intVal . integral
instance TensorType ByteString where
tensorType _ = DT_STRING
tensorRefType _ = DT_STRING_REF
tensorVal = stringVal
instance TensorType Bool where
tensorType _ = DT_BOOL
tensorRefType _ = DT_BOOL_REF
tensorVal = boolVal
instance TensorType (Complex Float) where
tensorType _ = DT_COMPLEX64
tensorRefType _ = DT_COMPLEX64
tensorVal = error "TODO (Complex Float)"
instance TensorType (Complex Double) where
tensorType _ = DT_COMPLEX128
tensorRefType _ = DT_COMPLEX128
tensorVal = error "TODO (Complex Double)"
instance TensorType ResourceHandle where
tensorType _ = DT_RESOURCE
tensorRefType _ = DT_RESOURCE_REF
tensorVal = resourceHandleVal
instance TensorType Variant where
tensorType _ = DT_VARIANT
tensorRefType _ = DT_VARIANT_REF
tensorVal = error "TODO Variant"
-- | Tensor data with the correct memory layout for tensorflow.
newtype TensorData a = TensorData { unTensorData :: FFI.TensorData }
-- | Types that can be converted to and from 'TensorData'.
--
-- 'S.Vector' is the most efficient to encode/decode for most element types.
class TensorType a => TensorDataType s a where
-- | Decode the bytes of a 'TensorData' into an 's'.
decodeTensorData :: TensorData a -> s a
-- | Encode an 's' into a 'TensorData'.
--
-- The values should be in row major order, e.g.,
--
-- element 0: index (0, ..., 0)
-- element 1: index (0, ..., 1)
-- ...
encodeTensorData :: Shape -> s a -> TensorData a
-- All types, besides ByteString and Bool, are encoded as simple arrays and we
-- can use Vector.Storable to encode/decode by type casting pointers.
-- TODO(fmayle): Assert that the data type matches the return type.
simpleDecode :: Storable a => TensorData a -> S.Vector a
simpleDecode = S.unsafeCast . FFI.tensorDataBytes . unTensorData
simpleEncode :: forall a . (TensorType a, Storable a)
=> Shape -> S.Vector a -> TensorData a
simpleEncode (Shape xs) v =
if product xs /= fromIntegral (S.length v)
then error $ printf
"simpleEncode: bad vector length for shape %v: expected=%d got=%d"
(show xs) (product xs) (S.length v)
else TensorData (FFI.TensorData xs dt (S.unsafeCast v))
where
dt = tensorType (undefined :: a)
instance TensorDataType S.Vector Float where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
instance TensorDataType S.Vector Double where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
instance TensorDataType S.Vector Int8 where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
instance TensorDataType S.Vector Int16 where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
instance TensorDataType S.Vector Int32 where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
instance TensorDataType S.Vector Int64 where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
instance TensorDataType S.Vector Word8 where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
instance TensorDataType S.Vector Word16 where
decodeTensorData = simpleDecode
encodeTensorData = simpleEncode
-- TODO: Haskell and tensorflow use different byte sizes for bools, which makes
-- encoding more expensive. It may make sense to define a custom boolean type.
instance TensorDataType S.Vector Bool where
decodeTensorData =
S.convert . S.map (/= 0) . FFI.tensorDataBytes . unTensorData
encodeTensorData (Shape xs) =
TensorData . FFI.TensorData xs DT_BOOL . S.map fromBool . S.convert
where
fromBool x = if x then 1 else 0 :: Word8
instance {-# OVERLAPPABLE #-} (Storable a, TensorDataType S.Vector a, TensorType a)
=> TensorDataType V.Vector a where
decodeTensorData = (S.convert :: S.Vector a -> V.Vector a) . decodeTensorData
encodeTensorData x = encodeTensorData x . (S.convert :: V.Vector a -> S.Vector a)
instance {-# OVERLAPPING #-} TensorDataType V.Vector (Complex Float) where
decodeTensorData = error "TODO (Complex Float)"
encodeTensorData = error "TODO (Complex Float)"
instance {-# OVERLAPPING #-} TensorDataType V.Vector (Complex Double) where
decodeTensorData = error "TODO (Complex Double)"
encodeTensorData = error "TODO (Complex Double)"
instance {-# OVERLAPPING #-} TensorDataType V.Vector ByteString where
-- Encoded data layout (described in third_party/tensorflow/c/c_api.h):
-- table offsets for each element :: [Word64]
-- at each element offset:
-- string length :: VarInt64
-- string data :: [Word8]
decodeTensorData tensorData =
either (\err -> error $ "Malformed TF_STRING tensor; " ++ err) id $
if expected /= count
then Left $ "decodeTensorData for ByteString count mismatch " ++
show (expected, count)
else V.mapM decodeString (S.convert offsets)
where
expected = S.length offsets
count = fromIntegral $ product $ FFI.tensorDataDimensions
$ unTensorData tensorData
bytes = FFI.tensorDataBytes $ unTensorData tensorData
offsets = S.take count $ S.unsafeCast bytes :: S.Vector Word64
dataBytes = B.pack $ S.toList $ S.drop (count * 8) bytes
decodeString :: Word64 -> Either String ByteString
decodeString offset =
let stringDataStart = B.drop (fromIntegral offset) dataBytes
in Atto.eitherResult $ Atto.parse stringParser stringDataStart
stringParser :: Atto.Parser ByteString
stringParser = getVarInt >>= Atto.take . fromIntegral
encodeTensorData (Shape xs) vec =
TensorData $ FFI.TensorData xs dt byteVector
where
dt = tensorType (undefined :: ByteString)
-- Add a string to an offset table and data blob.
addString :: (Builder, Builder, Word64)
-> ByteString
-> (Builder, Builder, Word64)
addString (table, strings, offset) str =
( table <> Builder.word64LE offset
, strings <> lengthBytes <> Builder.byteString str
, offset + lengthBytesLen + strLen
)
where
strLen = fromIntegral $ B.length str
lengthBytes = putVarInt $ fromIntegral $ B.length str
lengthBytesLen =
fromIntegral $ L.length $ Builder.toLazyByteString lengthBytes
-- Encode all strings.
(table', strings', _) = V.foldl' addString (mempty, mempty, 0) vec
-- Concat offset table with data.
bytes = table' <> strings'
-- Convert to Vector Word8.
byteVector = S.fromList $ L.unpack $ Builder.toLazyByteString bytes
newtype Scalar a = Scalar {unScalar :: a}
deriving (Show, Eq, Ord, Num, Fractional, Floating, Real, RealFloat,
RealFrac, IsString)
instance (TensorDataType V.Vector a, TensorType a) => TensorDataType Scalar a where
decodeTensorData = Scalar . headFromSingleton . decodeTensorData
encodeTensorData x (Scalar y) = encodeTensorData x (V.fromList [y])
headFromSingleton :: V.Vector a -> a
headFromSingleton x
| V.length x == 1 = V.head x
| otherwise = error $
"Unable to extract singleton from tensor of length "
++ show (V.length x)
-- | Shape (dimensions) of a tensor.
--
-- TensorFlow supports shapes of unknown rank, which are represented as
-- @Nothing :: Maybe Shape@ in Haskell.
newtype Shape = Shape [Int64] deriving Show
instance IsList Shape where
type Item Shape = Int64
fromList = Shape . fromList
toList (Shape ss) = toList ss
protoShape :: Lens' TensorShapeProto Shape
protoShape = under (adapter protoToShape shapeToProto)
where
protoToShape p = fromMaybe (error msg) (view protoMaybeShape p)
where msg = "Can't convert TensorShapeProto with unknown rank to Shape: "
++ showMessageShort p
shapeToProto s' = defMessage & protoMaybeShape .~ Just s'
protoMaybeShape :: Lens' TensorShapeProto (Maybe Shape)
protoMaybeShape = under (adapter protoToShape shapeToProto)
where
protoToShape :: TensorShapeProto -> Maybe Shape
protoToShape p =
if view unknownRank p
then Nothing
else Just (Shape (p ^.. dim . traverse . size))
shapeToProto :: Maybe Shape -> TensorShapeProto
shapeToProto Nothing =
defMessage & unknownRank .~ True
shapeToProto (Just (Shape ds)) =
defMessage & dim .~ fmap (\d -> defMessage & size .~ d) ds
class Attribute a where
attrLens :: Lens' AttrValue a
instance Attribute Float where
attrLens = f
instance Attribute ByteString where
attrLens = s
instance Attribute Int64 where
attrLens = i
instance Attribute DataType where
attrLens = type'
instance Attribute TensorProto where
attrLens = tensor
instance Attribute Bool where
attrLens = b
instance Attribute Shape where
attrLens = shape . protoShape
instance Attribute (Maybe Shape) where
attrLens = shape . protoMaybeShape
-- TODO(gnezdo): support generating list(Foo) from [Foo].
instance Attribute AttrValue'ListValue where
attrLens = list
instance Attribute [DataType] where
attrLens = list . type'
instance Attribute [Int64] where
attrLens = list . i
-- | A heterogeneous list type.
data ListOf f as where
Nil :: ListOf f '[]
(:/) :: f a -> ListOf f as -> ListOf f (a ': as)
infixr 5 :/
type family All f as :: Constraint where
All f '[] = ()
All f (a ': as) = (f a, All f as)
type family Map f as where
Map f '[] = '[]
Map f (a ': as) = f a ': Map f as
instance All Eq (Map f as) => Eq (ListOf f as) where
Nil == Nil = True
(x :/ xs) == (y :/ ys) = x == y && xs == ys
-- Newer versions of GHC use the GADT to tell that the previous cases are
-- exhaustive.
#if __GLASGOW_HASKELL__ < 800
_ == _ = False
#endif
instance All Show (Map f as) => Show (ListOf f as) where
showsPrec _ Nil = showString "Nil"
showsPrec d (x :/ xs) = showParen (d > 10)
$ showsPrec 6 x . showString " :/ "
. showsPrec 6 xs
type List = ListOf Identity
-- | Equivalent of ':/' for lists.
(/:/) :: a -> List as -> List (a ': as)
(/:/) = (:/) . Identity
infixr 5 /:/
-- | A 'Constraint' specifying the possible choices of a 'TensorType'.
--
-- We implement a 'Constraint' like @OneOf '[Double, Float] a@ by turning the
-- natural representation as a conjunction, i.e.,
--
-- @
-- a == Double || a == Float
-- @
--
-- into a disjunction like
--
-- @
-- a \/= Int32 && a \/= Int64 && a \/= ByteString && ...
-- @
--
-- using an enumeration of all the possible 'TensorType's.
type OneOf ts a
-- Assert `TensorTypes' ts` to make error messages a little better.
= (TensorType a, TensorTypes' ts, NoneOf (AllTensorTypes \\ ts) a)
type OneOfs ts as = (TensorTypes as, TensorTypes' ts,
NoneOfs (AllTensorTypes \\ ts) as)
type family NoneOfs ts as :: Constraint where
NoneOfs ts '[] = ()
NoneOfs ts (a ': as) = (NoneOf ts a, NoneOfs ts as)
data TensorTypeProxy a where
TensorTypeProxy :: TensorType a => TensorTypeProxy a
type TensorTypeList = ListOf TensorTypeProxy
fromTensorTypeList :: TensorTypeList ts -> [DataType]
fromTensorTypeList Nil = []
fromTensorTypeList ((TensorTypeProxy :: TensorTypeProxy t) :/ ts)
= tensorType (undefined :: t) : fromTensorTypeList ts
fromTensorTypes :: forall as . TensorTypes as => Proxy as -> [DataType]
fromTensorTypes _ = fromTensorTypeList (tensorTypes :: TensorTypeList as)
class TensorTypes (ts :: [*]) where
tensorTypes :: TensorTypeList ts
instance TensorTypes '[] where
tensorTypes = Nil
-- | A constraint that the input is a list of 'TensorTypes'.
instance (TensorType t, TensorTypes ts) => TensorTypes (t ': ts) where
tensorTypes = TensorTypeProxy :/ tensorTypes
-- | A simpler version of the 'TensorTypes' class, that doesn't run
-- afoul of @-Wsimplifiable-class-constraints@.
--
-- In more detail: the constraint @OneOf '[Double, Float] a@ leads
-- to the constraint @TensorTypes' '[Double, Float]@, as a safety-check
-- to give better error messages. However, if @TensorTypes'@ were a class,
-- then GHC 8.2.1 would complain with the above warning unless @NoMonoBinds@
-- were enabled. So instead, we use a separate type family for this purpose.
-- For more details: https://ghc.haskell.org/trac/ghc/ticket/11948
type family TensorTypes' (ts :: [*]) :: Constraint where
-- Specialize this type family when `ts` is a long list, to avoid deeply
-- nested tuples of constraints. Works around a bug in ghc-8.0:
-- https://ghc.haskell.org/trac/ghc/ticket/12175
TensorTypes' (t1 ': t2 ': t3 ': t4 ': ts)
= (TensorType t1, TensorType t2, TensorType t3, TensorType t4
, TensorTypes' ts)
TensorTypes' (t1 ': t2 ': t3 ': ts)
= (TensorType t1, TensorType t2, TensorType t3, TensorTypes' ts)
TensorTypes' (t1 ': t2 ': ts)
= (TensorType t1, TensorType t2, TensorTypes' ts)
TensorTypes' (t ': ts) = (TensorType t, TensorTypes' ts)
TensorTypes' '[] = ()
-- | A constraint checking that two types are different.
type family a /= b :: Constraint where
a /= a = TypeError a ~ ExcludedCase
a /= b = ()
-- | Helper types to produce a reasonable type error message when the Constraint
-- "a /= a" fails.
-- TODO(judahjacobson): Use ghc-8's CustomTypeErrors for this.
data TypeError a
data ExcludedCase
-- | An enumeration of all valid 'TensorType's.
type AllTensorTypes =
-- NOTE: This list should be kept in sync with
-- TensorFlow.OpGen.dtTypeToHaskell.
-- TODO: Add support for Complex Float/Double.
'[ Float
, Double
, Int8
, Int16
, Int32
, Int64
, Word8
, Word16
, ByteString
, Bool
]
-- | Removes a type from the given list of types.
type family Delete a as where
Delete a '[] = '[]
Delete a (a ': as) = Delete a as
Delete a (b ': as) = b ': Delete a as
-- | Takes the difference of two lists of types.
type family as \\ bs where
as \\ '[] = as
as \\ (b ': bs) = Delete b as \\ bs
-- | A constraint that the type @a@ doesn't appear in the type list @ts@.
-- Assumes that @a@ and each of the elements of @ts@ are 'TensorType's.
type family NoneOf ts a :: Constraint where
-- Specialize this type family when `ts` is a long list, to avoid deeply
-- nested tuples of constraints. Works around a bug in ghc-8.0:
-- https://ghc.haskell.org/trac/ghc/ticket/12175
NoneOf (t1 ': t2 ': t3 ': t4 ': ts) a
= (a /= t1, a /= t2, a /= t3, a /= t4, NoneOf ts a)
NoneOf (t1 ': t2 ': t3 ': ts) a = (a /= t1, a /= t2, a /= t3, NoneOf ts a)
NoneOf (t1 ': t2 ': ts) a = (a /= t1, a /= t2, NoneOf ts a)
NoneOf (t1 ': ts) a = (a /= t1, NoneOf ts a)
NoneOf '[] a = ()
| tensorflow/haskell | tensorflow/src/TensorFlow/Types.hs | apache-2.0 | 20,476 | 0 | 14 | 4,724 | 4,739 | 2,631 | 2,108 | -1 | -1 |
import Data.List
mark = ["R", "G", "B"]
f [] = True
f a@(h:t) = (r1 && (f (a \\ [h,h,h]))) || (r2 && (f (a \\ [h,h+1,h+2])))
where
nh = length $ filter (== h) a
r1 = nh >= 3
r2 = (elem (h+1) a) && (elem (h+2) a)
tst c =
let n = sort $ map snd c
in
f n
ans' c =
let cc = map (\m -> filter (\cc -> m == (fst cc)) c) mark
r = and $ map tst cc
in
if r then 1 else 0
ans [] = []
ans (n:m:r) =
let n' = map read n :: [Int]
z = zip m n'
in
(ans' z):(ans r)
main = do
_ <- getLine
c <- getContents
let i = map words $ lines c
o = ans i
mapM_ print o
| a143753/AOJ | 2102.hs | apache-2.0 | 616 | 16 | 17 | 218 | 466 | 223 | 243 | 25 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Trustworthy #-}
-- |
-- Module : Criterion.Report
-- Copyright : (c) 2009-2014 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- Reporting functions.
module Criterion.Report
(
formatReport
, report
, tidyTails
-- * Rendering helper functions
, TemplateException(..)
, loadTemplate
, includeFile
, getTemplateDir
, vector
, vector2
) where
import Control.Exception (Exception, IOException, throwIO)
import Control.Monad (mplus)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Control.Monad.Reader (ask)
import Criterion.Monad (Criterion)
import Criterion.Types
import Data.Aeson (ToJSON (..), Value(..), object, (.=), Value)
import Data.Aeson.Text (encodeToLazyText)
import Data.Data (Data, Typeable)
import Data.Foldable (forM_)
import GHC.Generics (Generic)
import Paths_criterion (getDataFileName)
import Statistics.Function (minMax)
import System.Directory (doesFileExist)
import System.FilePath ((</>), (<.>), isPathSeparator)
import System.IO (hPutStrLn, stderr)
import Text.Microstache (Key (..), Node (..), Template (..),
compileMustacheText, displayMustacheWarning, renderMustacheW)
import Prelude ()
import Prelude.Compat
import qualified Control.Exception as E
import qualified Data.Text as T
#if defined(EMBED)
import qualified Data.Text.Lazy.Encoding as TLE
#endif
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.IO as TL
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
#if defined(EMBED)
import Criterion.EmbeddedData (dataFiles, chartContents)
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text.Encoding as TE
#else
import qualified Language.Javascript.Chart as Chart
#endif
#if MIN_VERSION_aeson(2,0,0)
import qualified Data.Aeson.Key as Key
#endif
-- | Trim long flat tails from a KDE plot.
tidyTails :: KDE -> KDE
tidyTails KDE{..} = KDE { kdeType = kdeType
, kdeValues = G.slice front winSize kdeValues
, kdePDF = G.slice front winSize kdePDF
}
where tiny = uncurry subtract (minMax kdePDF) * 0.005
omitTiny = G.length . G.takeWhile ((<= tiny) . abs)
front = omitTiny kdePDF
back = omitTiny . G.reverse $ kdePDF
winSize = G.length kdePDF - front - back
-- | Return the path to the template and other files used for
-- generating reports.
--
-- When the @-fembed-data-files@ @Cabal@ flag is enabled, this simply
-- returns the empty path.
getTemplateDir :: IO FilePath
#if defined(EMBED)
getTemplateDir = pure ""
#else
getTemplateDir = getDataFileName "templates"
#endif
-- | Write out a series of 'Report' values to a single file, if
-- configured to do so.
report :: [Report] -> Criterion ()
report reports = do
Config{..} <- ask
forM_ reportFile $ \name -> liftIO $ do
td <- getTemplateDir
tpl <- loadTemplate [td,"."] template
TL.writeFile name =<< formatReport reports tpl
-- | Escape JSON string aimed to be embedded in an HTML <script> tag. Notably
-- < and > are replaced with their unicode escape sequences such that closing
-- the <script> tag from within the JSON data is disallowed, i.e, the character
-- sequence "</" is made impossible.
--
-- Moreover, & is escaped to avoid HTML character references (&<code>;), + is
-- escaped to avoid UTF-7 attacks (should only affect old versions of IE), and
-- \0 is escaped to allow it to be represented in JSON, as the NUL character is
-- disallowed in JSON but valid in Haskell characters.
--
-- The following characters are replaced with their unicode escape sequences
-- (\uXXXX):
-- <, >, &, +, \x2028 (line separator), \x2029 (paragraph separator), and \0
-- (null terminator)
--
-- Other characters are such as \\ (backslash) and \n (newline) are not escaped
-- as the JSON serializer @encodeToLazyText@ already escapes them when they
-- occur inside JSON strings and they cause no issues with respect to HTML
-- safety when used outside of strings in the JSON-encoded payload.
--
-- If the resulting JSON-encoded Text is embedded in an HTML attribute, extra
-- care is required to also escape quotes with character references in the
-- final JSON payload.
-- See <https://html.spec.whatwg.org/multipage/syntax.html#syntax-attributes>
-- for details on how to escape attribute values.
escapeJSON :: Char -> TL.Text
escapeJSON '<' = "\\u003c" -- ban closing of the script tag by making </ impossible
escapeJSON '>' = "\\u003e" -- encode tags with unicode escape sequences
escapeJSON '\x2028' = "\\u2028" -- line separator
escapeJSON '\x2029' = "\\u2029" -- paragraph separator
escapeJSON '&' = "\\u0026" -- avoid HTML entities
escapeJSON '+' = "\\u002b" -- + can be used in UTF-7 escape sequences
escapeJSON '\0' = "\\u0000" -- make null characters explicit
escapeJSON c = TL.singleton c
-- | Format a series of 'Report' values using the given Mustache template.
formatReport :: [Report]
-> TL.Text -- ^ Mustache template.
-> IO TL.Text
formatReport reports templateName = do
template0 <- case compileMustacheText "tpl" templateName of
Left err -> fail (show err) -- TODO: throw a template exception?
Right x -> return x
criterionJS <- readDataFile "criterion.js"
criterionCSS <- readDataFile "criterion.css"
chartJS <- chartFileContents
-- includes, only top level
templates <- getTemplateDir
template <- includeTemplate (includeFile [templates]) template0
let context = object
[ "json" .= reportsJSON reports
, "js-criterion" .= criterionJS
, "js-chart" .= chartJS
, "criterion-css" .= criterionCSS
]
let (warnings, formatted) = renderMustacheW template context
-- If there were any issues during mustache template rendering, make sure
-- to inform the user. See #127.
forM_ warnings $ \warning -> do
criterionWarning $ displayMustacheWarning warning
return formatted
where
reportsJSON :: [Report] -> T.Text
reportsJSON = TL.toStrict . TL.concatMap escapeJSON . encodeToLazyText
chartFileContents :: IO T.Text
#if defined(EMBED)
chartFileContents = pure $ TE.decodeUtf8 chartContents
#else
chartFileContents = T.readFile =<< Chart.file Chart.Chart
#endif
readDataFile :: FilePath -> IO T.Text
readDataFile fp =
(T.readFile =<< getDataFileName ("templates" </> fp))
#if defined(EMBED)
`E.catch` \(e :: IOException) ->
maybe (throwIO e)
(pure . TE.decodeUtf8)
(lookup fp dataFiles)
#endif
includeTemplate :: (FilePath -> IO T.Text) -> Template -> IO Template
includeTemplate f Template {..} = fmap
(Template templateActual)
(traverse (traverse (includeNode f)) templateCache)
includeNode :: (FilePath -> IO T.Text) -> Node -> IO Node
includeNode f (Section (Key ["include"]) [TextBlock fp]) =
fmap TextBlock (f (T.unpack fp))
includeNode _ n = return n
criterionWarning :: String -> IO ()
criterionWarning msg =
hPutStrLn stderr $ unlines
[ "criterion: warning:"
, " " ++ msg
]
-- | Render the elements of a vector.
--
-- It will substitute each value in the vector for @x@ in the
-- following Mustache template:
--
-- > {{#foo}}
-- > {{x}}
-- > {{/foo}}
vector :: (G.Vector v a, ToJSON a) =>
T.Text -- ^ Name to use when substituting.
-> v a
-> Value
{-# SPECIALIZE vector :: T.Text -> U.Vector Double -> Value #-}
vector name v = toJSON . map val . G.toList $ v where
val i = object [ toKey name .= i ]
-- | Render the elements of two vectors.
vector2 :: (G.Vector v a, G.Vector v b, ToJSON a, ToJSON b) =>
T.Text -- ^ Name for elements from the first vector.
-> T.Text -- ^ Name for elements from the second vector.
-> v a -- ^ First vector.
-> v b -- ^ Second vector.
-> Value
{-# SPECIALIZE vector2 :: T.Text -> T.Text -> U.Vector Double -> U.Vector Double
-> Value #-}
vector2 name1 name2 v1 v2 = toJSON $ zipWith val (G.toList v1) (G.toList v2) where
val i j = object
[ toKey name1 .= i
, toKey name2 .= j
]
#if MIN_VERSION_aeson(2,0,0)
toKey :: T.Text -> Key.Key
toKey = Key.fromText
#else
toKey :: T.Text -> T.Text
toKey = id
#endif
-- | Attempt to include the contents of a file based on a search path.
-- Returns 'B.empty' if the search fails or the file could not be read.
--
-- Intended for preprocessing Mustache files, e.g. replacing sections
--
-- @
-- {{#include}}file.txt{{/include}
-- @
--
-- with file contents.
includeFile :: (MonadIO m) =>
[FilePath] -- ^ Directories to search.
-> FilePath -- ^ Name of the file to search for.
-> m T.Text
{-# SPECIALIZE includeFile :: [FilePath] -> FilePath -> IO T.Text #-}
includeFile searchPath name = liftIO $ foldr go (return T.empty) searchPath
where go dir next = do
let path = dir </> name
T.readFile path `E.catch` \(_::IOException) -> next
-- | A problem arose with a template.
data TemplateException =
TemplateNotFound FilePath -- ^ The template could not be found.
deriving (Eq, Read, Show, Typeable, Data, Generic)
instance Exception TemplateException
-- | Load a Mustache template file.
--
-- If the name is an absolute or relative path, the search path is
-- /not/ used, and the name is treated as a literal path.
--
-- If the @-fembed-data-files@ @Cabal@ flag is enabled, this also checks
-- the embedded @data-files@ from @criterion.cabal@.
--
-- This function throws a 'TemplateException' if the template could
-- not be found, or an 'IOException' if no template could be loaded.
loadTemplate :: [FilePath] -- ^ Search path.
-> FilePath -- ^ Name of template file.
-> IO TL.Text
loadTemplate paths name
| any isPathSeparator name = readFileCheckEmbedded name
| otherwise = go Nothing paths
where go me (p:ps) = do
let cur = p </> name <.> "tpl"
x <- doesFileExist' cur
if x
then readFileCheckEmbedded cur `E.catch` \e -> go (me `mplus` Just e) ps
else go me ps
go (Just e) _ = throwIO (e::IOException)
go _ _ = throwIO . TemplateNotFound $ name
doesFileExist' :: FilePath -> IO Bool
doesFileExist' fp = do
e <- doesFileExist fp
pure $ e
#if defined(EMBED)
|| (fp `elem` map fst dataFiles)
#endif
-- A version of 'readFile' that falls back on the embedded 'dataFiles'
-- from @criterion.cabal@.
readFileCheckEmbedded :: FilePath -> IO TL.Text
readFileCheckEmbedded fp =
TL.readFile fp
#if defined(EMBED)
`E.catch` \(e :: IOException) ->
maybe (throwIO e)
(pure . TLE.decodeUtf8 . fromStrict)
(lookup fp dataFiles)
where
# if MIN_VERSION_bytestring(0,10,0)
fromStrict = BL.fromStrict
# else
fromStrict x = BL.fromChunks [x]
# endif
#endif
| bos/criterion | Criterion/Report.hs | bsd-2-clause | 11,556 | 0 | 15 | 2,772 | 2,236 | 1,254 | 982 | 169 | 4 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.FragmentShader
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All tokens from the ARB_fragment_shader extension, see
-- <http://www.opengl.org/registry/specs/ARB/fragment_shader.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.FragmentShader (
-- * Tokens
gl_FRAGMENT_SHADER,
gl_MAX_FRAGMENT_UNIFORM_COMPONENTS,
gl_MAX_TEXTURE_COORDS,
gl_MAX_TEXTURE_IMAGE_UNITS,
gl_FRAGMENT_SHADER_DERIVATIVE_HINT
) where
import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility
import Graphics.Rendering.OpenGL.Raw.Core32
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/FragmentShader.hs | bsd-3-clause | 871 | 0 | 4 | 103 | 59 | 47 | 12 | 8 | 0 |
import Music.Prelude
rh :: Music
rh = [((1/2) <-> (3/4),e)^.event,((3/4) <-> (15/16),cs')^.event,((15/16) <-> 1,d')^.event,(1 <-> (5/4),d)^.event,(1 <->
(5/4),gs)^.event,(1 <-> (5/4),b)^.event,((5/4) <-> (3/2),d)^.event,((5/4) <-> (3/2),gs)^.event,((5/4) <->
(3/2),b)^.event,((3/2) <-> 2,d)^.event,((3/2) <-> 2,gs)^.event,((3/2) <-> 2,b)^.event,(2 <-> (9/4),d')^.event,(2 <->
(9/4),fs')^.event,((9/4) <-> (39/16),bs)^.event,((9/4) <-> (39/16),ds')^.event,((39/16) <-> (5/2),cs')^.event,((39/16) <->
(5/2),e')^.event,((5/2) <-> (11/4),cs')^.event,((5/2) <-> (11/4),a')^.event,((11/4) <-> 3,cs')^.event,((11/4) <->
3,a')^.event,(3 <-> (7/2),cs')^.event,(3 <-> (7/2),a')^.event,((7/2) <-> (15/4),e)^.event,((7/2) <->
(15/4),cs')^.event,((15/4) <-> (63/16),cs)^.event,((15/4) <-> (63/16),as)^.event,((63/16) <-> 4,d)^.event,((63/16) <->
4,b)^.event,(4 <-> (17/4),fs)^.event,(4 <-> (17/4),d')^.event,((17/4) <-> (9/2),fs)^.event,((17/4) <->
(9/2),d')^.event,((9/2) <-> 5,fs)^.event,((9/2) <-> 5,d')^.event,(5 <-> (21/4),d)^.event,(5 <-> (21/4),gs)^.event,((21/4)
<-> (87/16),d)^.event,((21/4) <-> (87/16),gs)^.event,((87/16) <-> (11/2),cs)^.event,((87/16) <-> (11/2),a)^.event,((11/2)
<-> (23/4),cs)^.event,((11/2) <-> (23/4),cs')^.event,((23/4) <-> 6,cs)^.event,((23/4) <-> 6,cs')^.event,(6 <->
(13/2),cs)^.event,(6 <-> (13/2),cs')^.event]^.score
lh :: Music
lh = [((3/4) <-> 1,e__)^.event,(1 <-> (5/4),e_)^.event,(1 <-> (5/4),e)^.event,((5/4) <-> (3/2),e_)^.event,((5/4) <->
(3/2),e)^.event,((3/2) <-> 2,e_)^.event,((3/2) <-> 2,e)^.event,((9/4) <-> (5/2),a__)^.event,((5/2) <->
(11/4),a_)^.event,((5/2) <-> (11/4),e)^.event,((11/4) <-> 3,a_)^.event,((11/4) <-> 3,e)^.event,(3 <-> (7/2),a_)^.event,(3
<-> (7/2),e)^.event,((15/4) <-> 4,e__)^.event,(4 <-> (17/4),e_)^.event,(4 <-> (17/4),b_)^.event,((17/4) <->
(9/2),e_)^.event,((17/4) <-> (9/2),b_)^.event,((9/2) <-> 5,e_)^.event,((9/2) <-> 5,b_)^.event,((21/4) <->
(11/2),a___)^.event,((11/2) <-> (23/4),e_)^.event,((11/2) <-> (23/4),a_)^.event,((11/2) <-> (23/4),e)^.event,((23/4) <->
6,e_)^.event,((23/4) <-> 6,a_)^.event,((23/4) <-> 6,e)^.event,(6 <-> (13/2),e_)^.event,(6 <-> (13/2),a_)^.event,(6 <->
(13/2),e)^.event]^.score
music = timeSignature (3/4) $ lh <> rh
main = open music | music-suite/music-preludes | examples/chopin.hs | bsd-3-clause | 2,272 | 2 | 11 | 223 | 2,218 | 1,279 | 939 | 25 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Gfx.TextRendering
( createTextRenderer
, renderText
, renderTextToBuffer
, addCodeTextureToLib
, resizeTextRendererScreen
, changeTextColour
, TextRenderer
) where
import Control.Monad (foldM_)
import Data.Maybe (listToMaybe)
import Foreign.Marshal.Array (withArray)
import Foreign.Marshal.Utils (fromBool, with)
import Foreign.Ptr (castPtr, nullPtr)
import Foreign.Storable (sizeOf)
import Data.FileEmbed (embedFile)
import Gfx.FontHandling (Character (..), Font (..),
getCharacter, loadFont)
import Gfx.LoadShaders (ShaderInfo (..), ShaderSource (..),
loadShaders)
import Gfx.OpenGL (colToGLCol, printErrors)
import Gfx.Types (Colour (..))
import Gfx.VertexBuffers (VBO (..), createVBO, drawVBO,
setAttribPointer)
import qualified Graphics.GL as GLRaw
import Graphics.Rendering.OpenGL (AttribLocation (..),
BlendEquation (FuncAdd),
BlendingFactor (One, OneMinusSrcAlpha, SrcAlpha, Zero),
BufferTarget (ArrayBuffer),
BufferUsage (DynamicDraw),
Capability (Enabled),
ClearBuffer (ColorBuffer),
FramebufferTarget (Framebuffer),
GLfloat, PrimitiveMode (Triangles),
Program,
ShaderType (FragmentShader, VertexShader),
TextureTarget2D (Texture2D),
TextureUnit (..),
TransferDirection (WriteToBuffer),
UniformLocation (..), ($=))
import qualified Graphics.Rendering.OpenGL as GL
import Gfx.PostProcessing (Savebuffer (..),
createTextDisplaybuffer,
deleteSavebuffer)
import Gfx.Textures (TextureLibrary, addTexture)
import Linear.Matrix ( M44
, (!*!)
)
import Gfx.Matrices (orthographicMat, translateMat)
import Configuration (ImprovizConfig)
import qualified Configuration as C
import qualified Configuration.Font as FC
import qualified Configuration.Screen as CS
import Lens.Simple ((^.))
data TextRenderer = TextRenderer
{ textFont :: Font
, textAreaHeight :: Int
, pMatrix :: M44 GLfloat
, textprogram :: Program
, bgprogram :: Program
, characterQuad :: VBO
, characterBGQuad :: VBO
, textColour :: Colour
, textBGColour :: Colour
, outbuffer :: Savebuffer
} deriving (Show)
textCoordMatrix :: Floating f => f -> f -> f -> f -> f -> f -> M44 f
textCoordMatrix left right top bottom near far =
let o = orthographicMat left right top bottom near far
t = translateMat (-1) 1 0
in t !*! o
createCharacterTextQuad :: IO VBO
createCharacterTextQuad =
let vertexSize = fromIntegral $ sizeOf (0 :: GLfloat)
posVSize = 2
texVSize = 2
numVertices = 6
firstPosIndex = 0
firstTexIndex = posVSize * vertexSize
vPosition = AttribLocation 0
vTexCoord = AttribLocation 1
numElements = numVertices * (posVSize + texVSize)
size = fromIntegral (numElements * vertexSize)
stride = fromIntegral ((posVSize + texVSize) * vertexSize)
quadConfig = do
GL.bufferData ArrayBuffer $= (size, nullPtr, DynamicDraw)
setAttribPointer vPosition posVSize stride firstPosIndex
setAttribPointer vTexCoord texVSize stride firstTexIndex
in createVBO [quadConfig] Triangles firstPosIndex numVertices
createCharacterBGQuad :: IO VBO
createCharacterBGQuad =
let vertexSize = fromIntegral $ sizeOf (0 :: GLfloat)
posVSize = 2
numVertices = 6
firstPosIndex = 0
vPosition = AttribLocation 0
numElements = numVertices * posVSize
size = fromIntegral (numElements * vertexSize)
stride = 0
quadConfig = do
GL.bufferData ArrayBuffer $= (size, nullPtr, DynamicDraw)
setAttribPointer vPosition posVSize stride firstPosIndex
in createVBO [quadConfig] Triangles firstPosIndex numVertices
createTextRenderer :: ImprovizConfig -> Int -> Int -> Float -> IO TextRenderer
createTextRenderer config width height scaling =
let front = config ^. C.screen . CS.front
back = config ^. C.screen . CS.back
in do cq <- createCharacterTextQuad
cbq <- createCharacterBGQuad
tprogram <-
loadShaders
[ ShaderInfo
VertexShader
(ByteStringSource
$(embedFile "src/assets/shaders/textrenderer.vert"))
, ShaderInfo
FragmentShader
(ByteStringSource
$(embedFile "src/assets/shaders/textrenderer.frag"))
]
bgshaderprogram <-
loadShaders
[ ShaderInfo
VertexShader
(ByteStringSource
$(embedFile "src/assets/shaders/textrenderer-bg.vert"))
, ShaderInfo
FragmentShader
(ByteStringSource
$(embedFile "src/assets/shaders/textrenderer-bg.frag"))
]
font <-
loadFont
(config ^. C.fontConfig . FC.filepath)
(round (fromIntegral (config ^. C.fontConfig . FC.size) / scaling))
let projectionMatrix =
textCoordMatrix
0
(fromIntegral width)
0
(fromIntegral height)
front
back
buffer <-
createTextDisplaybuffer (fromIntegral width) (fromIntegral height)
return $
TextRenderer
font
height
projectionMatrix
tprogram
bgshaderprogram
cq
cbq
(config ^. C.fontConfig . FC.fgColour)
(config ^. C.fontConfig . FC.bgColour)
buffer
addCodeTextureToLib :: TextRenderer -> TextureLibrary -> TextureLibrary
addCodeTextureToLib tr tlib =
let (Savebuffer _ text _ _ _) = outbuffer tr
in addTexture tlib "code" text
resizeTextRendererScreen ::
ImprovizConfig -> Int -> Int -> TextRenderer -> IO TextRenderer
resizeTextRendererScreen config width height trender =
let front = config ^. C.screen . CS.front
back = config ^. C.screen . CS.back
projectionMatrix =
textCoordMatrix
0
(fromIntegral width)
0
(fromIntegral height)
front
back
in do deleteSavebuffer $ outbuffer trender
nbuffer <-
createTextDisplaybuffer (fromIntegral width) (fromIntegral height)
return trender {pMatrix = projectionMatrix, outbuffer = nbuffer}
changeTextColour :: Colour -> TextRenderer -> TextRenderer
changeTextColour newColour trender = trender {textColour = newColour}
renderText :: Int -> Int -> TextRenderer -> String -> IO ()
renderText xpos ypos renderer strings =
let (Savebuffer fbo _ _ _ _) = outbuffer renderer
height = textAreaHeight renderer
in do GL.bindFramebuffer Framebuffer $= fbo
renderCharacters xpos (height - ypos) renderer strings
printErrors
renderTextToBuffer :: TextRenderer -> IO ()
renderTextToBuffer renderer = do
GL.bindFramebuffer Framebuffer $= GL.defaultFramebufferObject
let (Savebuffer _ text _ program quadVBO) = outbuffer renderer
GL.currentProgram $= Just program
GL.activeTexture $= TextureUnit 0
GL.textureBinding Texture2D $= Just text
drawVBO quadVBO
renderCharacters :: Int -> Int -> TextRenderer -> String -> IO ()
renderCharacters xpos ypos renderer strings = do
GL.blend $= Enabled
GL.blendEquationSeparate $= (FuncAdd, FuncAdd)
GL.blendFuncSeparate $= ((SrcAlpha, OneMinusSrcAlpha), (One, Zero))
GL.depthFunc $= Nothing
GL.clearColor $= colToGLCol (Colour 0.0 0.0 0.0 0.0)
GL.clear [ColorBuffer]
let font = textFont renderer
foldM_
(\(xp, yp) c ->
case c of
'\n' -> return (xpos, yp - fontHeight font)
'\t' -> renderCharacterSpace renderer (fontAdvance font) xp yp font
_ ->
maybe
(return (xp, yp - fontAdvance font))
(\c -> renderChar c xp yp font)
(getCharacter font c))
(xpos, ypos)
strings
where
renderChar char xp yp f = do
renderCharacterBGQuad renderer char xp yp f
renderCharacterTextQuad renderer char xp yp f
sendProjectionMatrix :: Program -> M44 GLfloat -> IO ()
sendProjectionMatrix program mat = do
(UniformLocation projU) <- GL.get $ GL.uniformLocation program "projection"
with mat $ GLRaw.glUniformMatrix4fv projU 1 (fromBool True) . castPtr
sendVertices :: [GLfloat] -> IO ()
sendVertices verts =
let vertSize = sizeOf (head verts)
numVerts = length verts
size = fromIntegral (numVerts * vertSize)
in withArray verts $ \ptr ->
GL.bufferSubData ArrayBuffer WriteToBuffer 0 size ptr
renderCharacterQuad ::
Program -> M44 GLfloat -> VBO -> IO () -> [GLfloat] -> IO ()
renderCharacterQuad program pMatrix character charDrawFunc charVerts =
let (VBO arrayObject arrayBuffers primMode firstIndex numTriangles) =
character
in do GL.currentProgram $= Just program
GL.bindVertexArrayObject $= Just arrayObject
GL.bindBuffer ArrayBuffer $= listToMaybe arrayBuffers
charDrawFunc
sendProjectionMatrix program pMatrix
sendVertices charVerts
GL.drawArrays primMode firstIndex numTriangles
printErrors
renderCharacterTextQuad ::
TextRenderer -> Character -> Int -> Int -> Font -> IO (Int, Int)
renderCharacterTextQuad renderer (Character c width height adv xBearing yBearing text) x y font =
let baseline = fromIntegral (y - fontAscender font)
gX1 = fromIntegral (x + xBearing)
gX2 = gX1 + fromIntegral width
gY1 = baseline + fromIntegral yBearing
gY2 = gY1 - fromIntegral height
charVerts =
[ gX1
, gY1
, 0.0
, 0.0 -- coord 1
, gX1
, gY2
, 0.0
, 1.0 -- coord 2
, gX2
, gY1
, 1.0
, 0.0 -- coord 3
, gX1
, gY2
, 0.0
, 1.0 -- coord 4
, gX2
, gY2
, 1.0
, 1.0 -- coord 5
, gX2
, gY1
, 1.0
, 0.0 -- coord 6
] :: [GLfloat]
charDrawFunc = do
GL.activeTexture $= TextureUnit 0
GL.textureBinding Texture2D $= Just text
textColourU <-
GL.get $ GL.uniformLocation (textprogram renderer) "textColor"
GL.uniform textColourU $= colToGLCol (textColour renderer)
textBGColourU <-
GL.get $ GL.uniformLocation (textprogram renderer) "textBGColor"
GL.uniform textBGColourU $= colToGLCol (textBGColour renderer)
in do renderCharacterQuad
(textprogram renderer)
(pMatrix renderer)
(characterQuad renderer)
charDrawFunc
charVerts
return (x + adv, y)
renderCharacterBGQuad ::
TextRenderer -> Character -> Int -> Int -> Font -> IO (Int, Int)
renderCharacterBGQuad renderer (Character _ _ _ adv _ _ _) = renderCharacterSpace renderer adv
renderCharacterSpace ::
TextRenderer -> Int -> Int -> Int -> Font -> IO (Int, Int)
renderCharacterSpace renderer adv x y font =
let x1 = fromIntegral x
x2 = fromIntegral $ x + adv
y1 = fromIntegral y
y2 = fromIntegral $ y - fontHeight font
charVerts = [x1, y1, x1, y2, x2, y1, x1, y2, x2, y2, x2, y1] :: [GLfloat]
charDrawFunc = do
textBGColourU <-
GL.get $ GL.uniformLocation (bgprogram renderer) "textBGColor"
GL.uniform textBGColourU $= colToGLCol (textBGColour renderer)
in do renderCharacterQuad
(bgprogram renderer)
(pMatrix renderer)
(characterBGQuad renderer)
charDrawFunc
charVerts
return (x + adv, y)
| rumblesan/proviz | src/Gfx/TextRendering.hs | bsd-3-clause | 12,937 | 0 | 19 | 4,540 | 3,195 | 1,678 | 1,517 | -1 | -1 |
-- 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 GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Rules.TR
( rules
) where
import Duckling.Dimensions.Types
import qualified Duckling.Numeral.TR.Rules as Numeral
import qualified Duckling.Ordinal.TR.Rules as Ordinal
import Duckling.Types
rules :: Some Dimension -> [Rule]
rules (This Distance) = []
rules (This Duration) = []
rules (This Numeral) = Numeral.rules
rules (This Email) = []
rules (This AmountOfMoney) = []
rules (This Ordinal) = Ordinal.rules
rules (This PhoneNumber) = []
rules (This Quantity) = []
rules (This RegexMatch) = []
rules (This Temperature) = []
rules (This Time) = []
rules (This TimeGrain) = []
rules (This Url) = []
rules (This Volume) = []
| rfranek/duckling | Duckling/Rules/TR.hs | bsd-3-clause | 1,004 | 0 | 7 | 166 | 290 | 159 | 131 | 23 | 1 |
module Network.Tangaroa.Role
( becomeFollower
, becomeLeader
, becomeCandidate
, checkElection
, setVotedFor
) where
import Network.Tangaroa.Timer
import Network.Tangaroa.Types
import Network.Tangaroa.Combinator
import Network.Tangaroa.Util
import Network.Tangaroa.Sender
import Control.Lens hiding (Index)
import Control.Monad
import qualified Data.Map as Map
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
-- count the yes votes and become leader if you have reached a quorum
checkElection :: Ord nt => Raft nt et rt mt ()
checkElection = do
nyes <- Set.size <$> use cYesVotes
qsize <- view quorumSize
debug $ "yes votes: " ++ show nyes ++ " quorum size: " ++ show qsize
when (nyes >= qsize) $ becomeLeader
setVotedFor :: Maybe nt -> Raft nt et rt mt ()
setVotedFor mvote = do
_ <- rs.writeVotedFor ^$ mvote
votedFor .= mvote
becomeFollower :: Raft nt et rt mt ()
becomeFollower = do
debug "becoming follower"
role .= Follower
resetElectionTimer
becomeCandidate :: Ord nt => Raft nt et rt mt ()
becomeCandidate = do
debug "becoming candidate"
role .= Candidate
term += 1
rs.writeTermNumber ^=<<. term
nid <- view (cfg.nodeId)
setVotedFor $ Just nid
cYesVotes .= Set.singleton nid -- vote for yourself
(cPotentialVotes .=) =<< view (cfg.otherNodes)
resetElectionTimer
-- this is necessary for a single-node cluster, as we have already won the
-- election in that case. otherwise we will wait for more votes to check again
checkElection -- can possibly transition to leader
r <- use role
when (r == Candidate) $ fork_ sendAllRequestVotes
becomeLeader :: Ord nt => Raft nt et rt mt ()
becomeLeader = do
debug "becoming leader"
role .= Leader
(currentLeader .=) . Just =<< view (cfg.nodeId)
ni <- Seq.length <$> use logEntries
(lNextIndex .=) =<< Map.fromSet (const ni) <$> view (cfg.otherNodes)
(lMatchIndex .=) =<< Map.fromSet (const startIndex) <$> view (cfg.otherNodes)
fork_ sendAllAppendEntries
resetHeartbeatTimer
| chrisnc/tangaroa | src/Network/Tangaroa/Role.hs | bsd-3-clause | 2,033 | 0 | 11 | 385 | 599 | 301 | 298 | -1 | -1 |
{-# LANGUAGE DataKinds, TypeFamilies, TypeOperators #-}
module Text.Printf.Safe.Combinators (-- * Smart constructors
type (<>), (><), (%), (+++),
-- * Basic formatters
s, _S, _shows,
-- ** Number Formatters
base, d, d', o, o', b, b', h, h', f) where
import Data.Char (intToDigit)
import Data.Type.Equality ((:~:) (..), gcastWith)
import Numeric (showFloat, showIntAtBase)
import Text.Printf.Safe.Core (Printf (..), Formatter)
-- * Smart constructors
type family (<>) xs ys where
(<>) '[] xs = xs
(<>) (x ': xs) ys = x ': (xs <> ys)
appPrf :: Printf ts -> Printf ps -> Printf (ts <> ps)
appPrf EOS ps = ps
appPrf (str :<> ts) ps = str :<> appPrf ts ps
appPrf (fm :% ts) ps = fm :% appPrf ts ps
appNil :: Printf ts -> (ts <> '[]) :~: ts
appNil EOS = Refl
appNil (_ :<> a) = appNil a
appNil (_ :% bs) = case appNil bs of Refl -> Refl
-- | Append plain string to format.
(><) :: Printf ts -> String -> Printf ts
xs >< str = gcastWith (appNil xs) $ appPrf xs (str :<> EOS)
-- | Append formatter to format.
(%) :: Printf ts -> (a -> String) -> Printf (ts <> '[a])
(%) xs p = appPrf xs (p :% EOS)
-- | Concatenate two prtinf formats.
(+++) :: Printf ts -> Printf ps -> Printf (ts <> ps)
(+++) = appPrf
infixr 5 +++
infixl 5 ><, %
-- | Format @String@ as it is.
s :: Formatter String
s = id
-- | Formatter for @Show@ instances.
_S :: Show a => Formatter a
_S = show
-- | Converts @'ShowS'@ function to @'Formatter'@.
_shows :: (a -> ShowS) -> Formatter a
_shows fmt = flip fmt ""
-- | Format @Integral@s at base.
base :: (Show a, Integral a)
=> a -- ^ Base
-> Maybe (Char, Int) -- ^ Padding settings.
-> Formatter a
base adic mpd a =
let ans = showIntAtBase adic intToDigit a ""
in maybe "" (\(c,dig) -> replicate (dig - length ans) c) mpd ++ ans
-- | Decimal formatter with padding.
d' :: (Show a, Integral a) => Char -> Int -> Formatter a
d' c i = base 10 (Just (c,i))
-- | No padding version of @'d''@.
d :: (Show a, Integral a) => Formatter a
d = base 10 Nothing
-- | Octal formatter with padding.
o' :: (Show a, Integral a) => Char -> Int -> Formatter a
o' c i = base 8 (Just (c,i))
-- | No padding version of @'o''@.
o :: (Show a, Integral a) => Formatter a
o = base 8 Nothing
-- | Binary formatter with padding.
b' :: (Show a, Integral a) => Char -> Int -> Formatter a
b' c i = base 2 (Just (c,i))
-- | No padding version of @'b''@.
b :: (Show a, Integral a) => Formatter a
b = base 2 Nothing
-- | Binary formatter with padding.
h' :: (Show a, Integral a) => Char -> Int -> Formatter a
h' c i = base 16 (Just (c,i))
-- | No padding version of @'b''@.
h :: (Show a, Integral a) => Formatter a
h = base 16 Nothing
-- | @RealFloat@ formatter.
f :: RealFloat a => Formatter a
f = _shows showFloat
| konn/safe-printf | src/Text/Printf/Safe/Combinators.hs | bsd-3-clause | 2,980 | 4 | 14 | 840 | 1,122 | 616 | 506 | -1 | -1 |
{-
THIS FILE IS COPY FROM PROJECT: https://github.com/chrisdone/haskellnews
-}
-- | Display times as a relative duration. E.g. x days ago.
module Data.Time.Relative where
import Data.List
import Data.Time
import Text.Printf
-- | Display a time span as one time relative to another.
relativeZoned :: ZonedTime -- ^ The later time span.
-> ZonedTime -- ^ The earlier time span.
-> Bool -- ^ Display 'in/ago'?
-> String -- ^ Example: '3 seconds ago', 'in three days'.
relativeZoned t1 t2 =
relative (zonedTimeToUTC t1) (zonedTimeToUTC t2)
-- | Display a time span as one time relative to another.
relative :: UTCTime -- ^ The later time span.
-> UTCTime -- ^ The earlier time span.
-> Bool -- ^ Display 'in/ago'?
-> String -- ^ Example: '3 seconds ago', 'in three days'.
relative t1 t2 fix = maybe "unknown" format $ find (\(s,_,_) -> abs span>=s) $ reverse ranges where
minute = 60; hour = minute * 60; day = hour * 24;
week = day * 7; month = day * 30; year = month * 12
format range =
(if fix && span>0 then "in " else "")
++ case range of
(_,str,0) -> str
(_,str,base) -> printf str (abs $ round (span / base) :: Integer)
++ (if fix && span<0 then " ago" else "")
span = t1 `diffUTCTime` t2
ranges = [(0,"%d seconds",1)
,(minute,"a minute",0)
,(minute*2,"%d minutes",minute)
,(minute*30,"half an hour",0)
,(minute*31,"%d minutes",minute)
,(hour,"an hour",0)
,(hour*2,"%d hours",hour)
,(hour*3,"a few hours",0)
,(hour*4,"%d hours",hour)
,(day,"a day",0)
,(day*2,"%d days",day)
,(week,"a week",0)
,(week*2,"%d weeks",week)
,(month,"a month",0)
,(month*2,"%d months",month)
,(year,"a year",0)
,(year*2,"%d years",year)
]
| HaskellCNOrg/snap-web | src/Data/Time/Relative.hs | bsd-3-clause | 1,935 | 0 | 17 | 578 | 580 | 348 | 232 | 41 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
module Dhall.JSON.Util
( pattern V
, pattern FA
) where
import Data.Text (Text)
import Dhall.Core (Expr, FieldSelection)
import qualified Dhall.Core as Core
pattern V :: Int -> Expr s a
pattern V n = Core.Var (Core.V "_" n)
pattern FA :: Text -> FieldSelection s
pattern FA t <- Core.FieldSelection _ t _
where FA = Core.makeFieldSelection
| Gabriel439/Haskell-Dhall-Library | dhall-json/src/Dhall/JSON/Util.hs | bsd-3-clause | 430 | 0 | 9 | 87 | 136 | 75 | 61 | 13 | 0 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Contains a debug function to dump parts of the GHC.Hs AST. It uses a syb
-- traversal which falls back to displaying based on the constructor name, so
-- can be used to dump anything having a @Data.Data@ instance.
module GHC.Hs.Dump (
-- * Dumping ASTs
showAstData,
BlankSrcSpan(..),
) where
import GhcPrelude
import Data.Data hiding (Fixity)
import Bag
import BasicTypes
import FastString
import NameSet
import Name
import DataCon
import SrcLoc
import GHC.Hs
import OccName hiding (occName)
import Var
import Module
import Outputable
import qualified Data.ByteString as B
data BlankSrcSpan = BlankSrcSpan | NoBlankSrcSpan
deriving (Eq,Show)
-- | Show a GHC syntax tree. This parameterised because it is also used for
-- comparing ASTs in ppr roundtripping tests, where the SrcSpan's are blanked
-- out, to avoid comparing locations, only structure
showAstData :: Data a => BlankSrcSpan -> a -> SDoc
showAstData b a0 = blankLine $$ showAstData' a0
where
showAstData' :: Data a => a -> SDoc
showAstData' =
generic
`ext1Q` list
`extQ` string `extQ` fastString `extQ` srcSpan
`extQ` lit `extQ` litr `extQ` litt
`extQ` bytestring
`extQ` name `extQ` occName `extQ` moduleName `extQ` var
`extQ` dataCon
`extQ` bagName `extQ` bagRdrName `extQ` bagVar `extQ` nameSet
`extQ` fixity
`ext2Q` located
where generic :: Data a => a -> SDoc
generic t = parens $ text (showConstr (toConstr t))
$$ vcat (gmapQ showAstData' t)
string :: String -> SDoc
string = text . normalize_newlines . show
fastString :: FastString -> SDoc
fastString s = braces $
text "FastString: "
<> text (normalize_newlines . show $ s)
bytestring :: B.ByteString -> SDoc
bytestring = text . normalize_newlines . show
list [] = brackets empty
list [x] = brackets (showAstData' x)
list (x1 : x2 : xs) = (text "[" <> showAstData' x1)
$$ go x2 xs
where
go y [] = text "," <> showAstData' y <> text "]"
go y1 (y2 : ys) = (text "," <> showAstData' y1) $$ go y2 ys
-- Eliminate word-size dependence
lit :: HsLit GhcPs -> SDoc
lit (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s
lit (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s
lit (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s
lit (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s
lit l = generic l
litr :: HsLit GhcRn -> SDoc
litr (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s
litr (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s
litr (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s
litr (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s
litr l = generic l
litt :: HsLit GhcTc -> SDoc
litt (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s
litt (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s
litt (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s
litt (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s
litt l = generic l
numericLit :: String -> Integer -> SourceText -> SDoc
numericLit tag x s = braces $ hsep [ text tag
, generic x
, generic s ]
name :: Name -> SDoc
name nm = braces $ text "Name: " <> ppr nm
occName n = braces $
text "OccName: "
<> text (OccName.occNameString n)
moduleName :: ModuleName -> SDoc
moduleName m = braces $ text "ModuleName: " <> ppr m
srcSpan :: SrcSpan -> SDoc
srcSpan ss = case b of
BlankSrcSpan -> text "{ ss }"
NoBlankSrcSpan -> braces $ char ' ' <>
(hang (ppr ss) 1
-- TODO: show annotations here
(text ""))
var :: Var -> SDoc
var v = braces $ text "Var: " <> ppr v
dataCon :: DataCon -> SDoc
dataCon c = braces $ text "DataCon: " <> ppr c
bagRdrName:: Bag (Located (HsBind GhcPs)) -> SDoc
bagRdrName bg = braces $
text "Bag(Located (HsBind GhcPs)):"
$$ (list . bagToList $ bg)
bagName :: Bag (Located (HsBind GhcRn)) -> SDoc
bagName bg = braces $
text "Bag(Located (HsBind Name)):"
$$ (list . bagToList $ bg)
bagVar :: Bag (Located (HsBind GhcTc)) -> SDoc
bagVar bg = braces $
text "Bag(Located (HsBind Var)):"
$$ (list . bagToList $ bg)
nameSet ns = braces $
text "NameSet:"
$$ (list . nameSetElemsStable $ ns)
fixity :: Fixity -> SDoc
fixity fx = braces $
text "Fixity: "
<> ppr fx
located :: (Data b,Data loc) => GenLocated loc b -> SDoc
located (L ss a) = parens $
case cast ss of
Just (s :: SrcSpan) ->
srcSpan s
Nothing -> text "nnnnnnnn"
$$ showAstData' a
normalize_newlines :: String -> String
normalize_newlines ('\\':'r':'\\':'n':xs) = '\\':'n':normalize_newlines xs
normalize_newlines (x:xs) = x:normalize_newlines xs
normalize_newlines [] = []
{-
************************************************************************
* *
* Copied from syb
* *
************************************************************************
-}
-- | The type constructor for queries
newtype Q q x = Q { unQ :: x -> q }
-- | Extend a generic query by a type-specific case
extQ :: ( Typeable a
, Typeable b
)
=> (a -> q)
-> (b -> q)
-> a
-> q
extQ f g a = maybe (f a) g (cast a)
-- | Type extension of queries for type constructors
ext1Q :: (Data d, Typeable t)
=> (d -> q)
-> (forall e. Data e => t e -> q)
-> d -> q
ext1Q def ext = unQ ((Q def) `ext1` (Q ext))
-- | Type extension of queries for type constructors
ext2Q :: (Data d, Typeable t)
=> (d -> q)
-> (forall d1 d2. (Data d1, Data d2) => t d1 d2 -> q)
-> d -> q
ext2Q def ext = unQ ((Q def) `ext2` (Q ext))
-- | Flexible type extension
ext1 :: (Data a, Typeable t)
=> c a
-> (forall d. Data d => c (t d))
-> c a
ext1 def ext = maybe def id (dataCast1 ext)
-- | Flexible type extension
ext2 :: (Data a, Typeable t)
=> c a
-> (forall d1 d2. (Data d1, Data d2) => c (t d1 d2))
-> c a
ext2 def ext = maybe def id (dataCast2 ext)
| sdiehl/ghc | compiler/GHC/Hs/Dump.hs | bsd-3-clause | 7,670 | 0 | 25 | 3,073 | 2,063 | 1,074 | 989 | 150 | 18 |
{-# LANGUAGE JavaScriptFFI, GeneralizedNewtypeDeriving #-}
module GHCJS.Three.FontLoader
( FontLoader(..), mkFontLoader, loadFont
) where
import GHCJS.Types
import qualified GHCJS.Marshal as M
import GHCJS.Foreign.Callback
import GHCJS.Concurrent
import GHCJS.Three.Monad
newtype FontLoader = FontLoader {
fontLoaderObj :: BaseObject
} deriving ThreeJSVal
foreign import javascript unsafe "new window['THREE']['FontLoader']()"
thr_mkFontLoader :: Three JSVal
mkFontLoader :: Three FontLoader
mkFontLoader = fromJSVal <$> thr_mkFontLoader
foreign import javascript unsafe "($5)['load']($1, $2, $3, $4)"
thr_loadFont :: JSString -> Callback (JSVal -> IO ()) -> Callback (JSVal -> IO ()) -> Callback (IO ()) -> JSVal -> Three ()
loadFont :: JSString -> (JSVal -> IO ()) -> (JSVal -> IO ()) -> IO () -> FontLoader -> Three ()
loadFont url onLoad onProg onError loader = do
l <- syncCallback1 ThrowWouldBlock onLoad
p <- syncCallback1 ThrowWouldBlock onProg
e <- syncCallback ThrowWouldBlock onError
thr_loadFont url l p e (toJSVal loader)
| manyoo/ghcjs-three | src/GHCJS/Three/FontLoader.hs | bsd-3-clause | 1,083 | 16 | 9 | 187 | 311 | 165 | 146 | 23 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
--our libraries
import Demo2Shared
--vchan library
import VChanUtil
-- crypto libraries
import Crypto.Random
import Crypto.PubKey.HashDescr
import Crypto.PubKey.RSA
import Crypto.PubKey.RSA.PKCS15
-- utility libraries
import Control.Exception hiding (evaluate)
import Control.Monad
import Data.Bits
import Data.ByteString (ByteString, pack, append, empty)
import qualified Data.ByteString as B
import System.IO
import System.IO.Unsafe (unsafePerformIO)
prompt:: IO Int
prompt= loop
where loop = do putStrLn "Which Domain ID is the Appraiser?"
input <- getLine
case reads input of
[(id,_)] -> return id
_ -> do putStrLn "Error: Please Enter a Number."
loop
measurePrompt :: IO Int
measurePrompt = loop
where loop = do putStrLn "Which Domain ID is the Measurer?"
input <- getLine
case reads input of
[(id,_)] -> return id
_ -> do putStrLn "Error: Please Enter a Number."
loop
main :: IO ()
main = do
appraiserID <- prompt
chan <- server_init appraiserID
req <- receiveRequest chan
resp <- mkResponse req
sendResponse chan resp
return ()
-- Attestation primitives
mkResponse :: Request -> IO Response
mkResponse (desiredE, desiredPCRs, nonce) = do
measurerID <- measurePrompt
chan <- client_init measurerID
eList <- mapM (getEvidencePiece chan) desiredE
let evPack = signEvidence eList nonce
quote = mkSignedTPMQuote desiredPCRs nonce
hash = doHash $ ePack eList nonce
quoPack = signQuote quote hash
return (evPack, quoPack)
getEvidencePiece :: LibXenVChan -> EvidenceDescriptor -> IO EvidencePiece
getEvidencePiece chan ed = do
putStrLn $ "\n" ++ "Attestation Agent Sending: " ++ show ed
send chan ed
ctrlWait chan
evidence :: EvidencePiece <- receive chan --TODO: error handling
putStrLn $ "Received: " ++ show evidence
return evidence
receiveRequest :: LibXenVChan -> IO Request
receiveRequest chan = do
ctrlWait chan
res :: Shared <- receive chan
case res of
Appraisal req -> do
putStrLn $ "\n" ++ "Attester Received: " ++ show res ++ "\n"
return req
otherwise -> error requestReceiveError
sendResponse :: LibXenVChan -> Response-> IO ()
sendResponse chan resp = do
putStrLn $ "Attester Sending: " ++ show (Attestation resp) ++ "\n"
send chan $ Attestation resp
return ()
signQuote :: Quote -> Hash -> QuotePackage
signQuote quote hash =
case sign Nothing md5 pri res of
Left err -> error $ show err
Right signature -> (quote, hash, signature)
where res = qPack quote hash
signEvidence :: Evidence -> Nonce -> EvidencePackage
signEvidence e n =
case sign Nothing md5 pri res of
Left err -> error $ show err
Right signature -> (e, n, signature)
where res = ePack e n
mkSignedTPMQuote :: TPMRequest -> Nonce -> Quote
mkSignedTPMQuote mask nonce =
let pcrs' = pcrSelect mask
quote = (pcrs', nonce) in
case sign Nothing md5 pri $ tPack quote of
Left err -> error $ show err
Right signature -> (quote, signature)
-- PCR primitives
pcrsLocal :: [PCR]
pcrsLocal = a --b
where a :: [PCR]
a = map bit [0..7]
b :: [PCR]
b = bit 3 : map bit [1..7]
pcrSelect :: TPMRequest -> [PCR]
pcrSelect mask =
[ x | (x, n) <- zip pcrsLocal [0..7], testBit mask n]
-- Crypto primitives
md5 :: HashDescr
md5 = hashDescrMD5
pub :: PublicKey
pri :: PrivateKey
(pri, pub) = getKeys
-- Utility functions to get keys
attKeyFileName :: String
attKeyFileName = "attKeys.txt"
getKeys :: (PrivateKey, PublicKey)
getKeys = unsafePerformIO readKeys
getPriKey :: PrivateKey
getPriKey = fst getKeys
getPubKey :: PublicKey
getPubKey = snd getKeys
readKeys :: IO (PrivateKey, PublicKey)
readKeys = do
handle <- openFile attKeyFileName ReadMode
priString <- hGetLine handle
pubString <- hGetLine handle
let pri :: PrivateKey
pri = read priString
pub :: PublicKey
pub = read pubString
hClose handle
return (pri, pub)
--Error messages(only for debugging, at least for now)
requestReceiveError :: String
requestReceiveError = "Attester did not receive a Request as expected" | armoredsoftware/protocol | demos/demo2/Attestation.hs | bsd-3-clause | 4,564 | 5 | 15 | 1,303 | 1,400 | 666 | 734 | 124 | 2 |
{-# OPTIONS -XOverlappingInstances
-XTypeSynonymInstances
-XFlexibleInstances
-XUndecidableInstances
-XOverloadedStrings
#-}
-----------------------------------------------------------------------------
--
-- Module : Data.RefSerialize
-- Copyright : Alberto Gómez Corona
-- License : see LICENSE
--
-- Maintainer : [email protected]
-- Stability : experimental
{- | Read, Show and Data.Binary do not check for repeated references to the same address.
As a result, the data is duplicated when serialized. This is a waste of space in the filesystem
and also a waste of serialization time. but the worst consequence is that, when the serialized data is read,
it allocates multiple copies for the same object when referenced multiple times. Because multiple referenced
data is very typical in a pure language such is Haskell, this means that the resulting data loose the beatiful
economy of space and processing time that referential transparency permits.
This package leverages Show, Read and Data.Binary instances while it permits textual as well as binary serialization
keeping internal references.
Here comes a brief tutorial:
@runW applies showp, the serialization parser of the instance Int for the RefSerialize class
Data.RefSerialize>let x= 5 :: Int
Data.RefSerialize>runW $ showp x
"5"
every instance of Read and Show is an instance of RefSerialize. for how to construct showp and readp parsers, see the demo.hs
rshowp is derived from showp, it labels the serialized data with a variable name
Data.RefSerialize>runW $ rshowp x
" v8 where {v8= 5; }"
Data.RefSerialize>runW $ rshowp [2::Int,3::Int]
" v6 where {v6= [ v9, v10]; v9= 2; v10= 3; }"
while showp does a normal show serialization
Data.RefSerialize>runW $ showp [x,x]
"[5, 5]"
rshowp variables are serialized memory references: no piece of data that point to the same addrees is serialized but one time
Data.RefSerialize>runW $ rshowp [x,x]
" v9 where {v6= 5; v9= [ v6, v6]; }"
"this happens recursively"
Data.RefSerialize>let xs= [x,x] in str = runW $ rshowp [xs,xs]
Data.RefSerialize>str
" v8 where {v8= [ v10, v10]; v9= 5; v10= [ v9, v9]; }"
the rshowp serialized data is read with rreadp. The showp serialized data is read by readp
Data.RefSerialize>let xss= runR rreadp str :: [[Int]]
Data.RefSerialize>print xss
[[5,5],[5,5]]
this is the deserialized data
the deserialized data keep the references!! pointers are restored! That is the whole point!
Data.RefSerialize>varName xss !! 0 == varName xss !! 1
True
rShow= runW rshowp
rRead= runR rreadp
Data.RefSerialize>rShow x
" v11 where {v11= 5; }"
In the definition of a referencing parser non referencing parsers can be used and viceversa. Use a referencing parser
when the piece of data is being referenced many times inside the serialized data.
by default the referencing parser is constructed by:
rshowp= insertVar showp
rreadp= readVar readp
but this can be redefined. See for example the instance of [] in RefSerialize.hs
This is an example of a showp parser for a simple data structure.
data S= S Int Int deriving ( Show, Eq)
instance Serialize S where
showp (S x y)= do
-- insertString "S"
rshowp x -- rshowp parsers can be inside showp parser
rshowp y
readp = do
symbol "S" -- I included a (almost) complete Parsec for deserialization
x <- rreadp
y <- rreadp
return $ S x y
there is a mix between referencing and no referencing parser here:
Data.RefSerialize>putStrLn $ runW $ showp $ S x x
S v23 v23 where {v23= 5; }@
-}
module Data.RefSerialize
(
module Data.RefSerialize.Parser
,Serialize(
showp
,readp
)
,Context
,newContext
,rshowp
,rreadp
,showps
,showpText
,readpText
,takep
,showpBinary
,readpBinary
,insertString
,insertChar
,rShow
,rRead
,insertVar
,readVar
,varName
,runR
,runRC
,runW
,readHexp
,showHexp
,getContext
)
where
import Data.RefSerialize.Serialize
import Data.RefSerialize.Parser
import Unsafe.Coerce
import Data.Char(isAlpha, isSpace, isAlphaNum)
import Numeric(readHex,showHex)
import Data.ByteString.Lazy.Char8 as B
--import Data.ByteString(breakSubstring)
import Debug.Trace
import Data.Binary
import System.IO.Unsafe
import qualified Data.Map as M
newContext :: IO Context
newContext = Data.RefSerialize.Serialize.empty
class Serialize c where
showp :: c -> ST () -- ^ shows the content of a expression, must be defined bu the user
readp :: ST c -- ^ read the content of a expression, must be user defined
-- | insert a reference (a variable in the where section).
-- @rshowp = insertVar showp @
rshowp :: Serialize c => c -> ST ()
rshowp = insertVar showp
-- | read a variable in the where section (to use for deserializing rshowp output).
-- @rreadp = readVar readp@
rreadp :: Serialize c => ST c
rreadp = readVar readp
{-
#ifdef Axioms
serializeAxioms: Axioms c
serializeAxioms= axioms{
unary= [Axiom "reverse"
(\x -> let str= rShow x
y = rRead xtr
in y== x)
AxioM "pointer equality"
(\x -> let str= rShow[x,x]
[y,z] = rRead str
in varName y== varName z)
]
}
#endif
-}
-- | return the serialized list of variable values
-- useful for delayed deserialzation of expresions, in case of dynamic variables were deserialization
-- is done when needed, once the type is known with `runRC`
getContext :: ST (Context, ByteString)
getContext = ST(\(Stat(c,s,v)) -> Right (Stat (c,s,v), (c,v)))
-- | use the rshowp parser to serialize the object
-- @ rShow c= runW $ rshowp c@
rShow :: Serialize c => c -> ByteString
rShow c= runW $ showp c
-- | deserialize trough the rreadp parser
-- @ rRead str= runR rreadp $ str@
rRead :: Serialize c => ByteString -> c
rRead str= runR readp $ str
readHexp :: (Num a, Integral a) => ST a
readHexp = ST(\(Stat(c,s,v)) ->
let us= unpack s
l= readHex us
in if Prelude.null l then Left . Error $ "readHexp: not readable: " ++ us
else let ((x,str2):_)= l
in Right(Stat(c, pack $ Prelude.dropWhile isSpace str2,v),x) )
<?> "readHexp "
showHexp :: (Num a,Integral a,Show a) => a -> ST ()
showHexp var= ST(\(Stat(c,s,v)) -> Right(Stat(c, s `append` " " `append` (pack $ showHex var ""),v),())) <?> "showHexp "
-- |if a is an instance of Show, showpText can be used as the showp method
-- the drawback is that the data inside is not inspected for common references
-- so it is recommended to create your own readp method for your complex data structures
showpText :: Show a => a -> ST ()
showpText var= ST(\(Stat(c,s,v)) -> Right(Stat(c, s `append` (snoc (pack $ show var) ' ') ,v),())) <?> "showp: show "
-- |if a is an instance of Read, readpText can be used as the readp method
-- the drawback is that the data inside is not inspected for common references
-- so it is recommended to create your own readp method for your complex data structures
readpText :: Read a => ST a
readpText = ST(\(Stat(c,s,v)) ->
let us= unpack s
l= readsPrec 1 us
in if Prelude.null l then Left . Error $ "not readable: " ++ us
else let ((x,str2):_)= l
in Right(Stat(c, pack $ Prelude.dropWhile isSpace str2,v),x) )
<?> "readp: readsPrec "
-- | deserialize the string with the parser
runR:: ST a -> ByteString -> a
runR p str=unsafePerformIO $ do
c <- newContext
let (struct, vars)= readContext whereSep str
return $ runRC (c, vars) p struct
-- | read an expression with the variables definedd in a context passed as parameter.
runRC :: (Context, ByteString) -> ST a -> ByteString -> a
runRC (c,vars) (ST f) struct=
case f (Stat(c,struct,vars) ) of
Right (Stat _, a) -> a
Left (Error s) -> error s
whereSep= "\r\nwhere{\r\n "
-- | serialize x with the parser
runW :: ST () -> ByteString
runW (ST f) = unsafePerformIO $ do
c <- newContext
return $ case f (Stat(c,"","")) of
Right (Stat (c,str,_), _) ->
let scontext= assocs c
vars= B.concat $ Prelude.map (\(n,(_,_,v))->"v" `append` (pack $ show n) `append` "= " `append` v `append` ";\r\n ") scontext
strContext= if Prelude.null scontext then "" else whereSep `append` vars `append` "\r\n}"
in str `append` strContext
Left (Error s) -> error s
-- | output the string of the serialized variable
showps :: Serialize a => a -> ST ByteString
showps x= ST(\(Stat(c,s,v))->
let
ST f= showp x
Right (Stat (c',str,_), _) = f (Stat(c,"",v))
in Right(Stat(c',s ,v), str))
-- | insert a variable at this position. The expression value is inserted in the "where" section if it is not already
-- created. If the address of this object being parsed correspond with an address already parsed and
-- it is in the where section, then the same variable name is used
-- @runW showp (1::Int) -> "1"
-- runW (insertVar showp) (1::Int) -> v1 where { v1=1}
-- runW (insertVar showp) [(1::Int) ,1] -> [v1.v1] where { v1=1}@
-- This is useful when the object is referenced many times
insertVar :: (a -> ST ()) -> a -> ST ()
insertVar parser x= ST(\(Stat(c,s,v))->
let mf = trytofindEntireObject x c in
case mf of
Just var -> Right(Stat(c,s `append` " " `append` var,v),())
Nothing ->
let
ST f= parser x
Right (Stat (c',str,_), _) = f (Stat(c,"",v))
in Right(Stat(addc str c',s `append` (cons ' ' varname) ,v), ()))
where
addc str c= insert ( hash) (st,unsafeCoerce x, str) c
(hash,st) = hasht x
varname= pack$ "v" ++ show hash
trytofindEntireObject x c=
case Data.RefSerialize.Serialize.lookup hash c of
Nothing -> Nothing
Just _ -> Just varname
-- | inform if the expression iwas already referenced and return @Right varname@
-- otherwise, add the expresion to the context and giive it a name and return @Left varname@
-- The varname is not added to the serialized expression. The user must serialize it
-- This is usefu for expressions that admit different syntax depending or recursiviity, such are lists
isInVars :: (a -> ST ()) -> a -> ST (Either ByteString ByteString)
isInVars parser x= ST(\(Stat(c,s,v))->
let mf = trytofindEntireObject x c in
case mf of
Just var -> Right(Stat(c,s,v),Right var)
Nothing ->
let
ST f= parser x
Right (Stat (c',str,_), _) = f (Stat(c,"",v))
in Right(Stat(addc str c',s ,v), Left varname))
where
addc str c= insert ( hash) (st,unsafeCoerce x, str) c
(hash,st) = hasht x
varname= pack$ "v" ++ show hash
trytofindEntireObject x c=
case Data.RefSerialize.Serialize.lookup hash c of
Nothing -> Nothing
Just _ -> Just varname
-- | deserialize a variable serialized with insertVar. Memory references are restored
readVar :: Serialize c => ST c -> ST c
readVar (ST f)= ST(\(Stat(c,s,v))->
let
s1= B.dropWhile isSpace s
(var, str2) = B.span isAlphaNum s1
str3= B.dropWhile isSpace str2
nvar= numVar $ unpack var
in if B.null var then Left (Error "expected variable name" )
else
case trytofindEntireObject nvar c of
Just (_,x,_) -> Right(Stat(c,str3,v),unsafeCoerce x)
Nothing ->
let
(_, rest)= readContext (var `append` "= ") v
in if B.null rest then Left (Error ( "RedSerialize: readVar: " ++ unpack var ++ "value not found" ))
else case f (Stat(c,rest,v)) of
Right (Stat(c',s',v'),x) ->
let c''= insert nvar ( undefined, unsafeCoerce x, "") c'
in Right (Stat(c'', str3,v),x)
err -> err)
where
trytofindEntireObject x c=
case Data.RefSerialize.Serialize.lookup x c of
Nothing -> Nothing
justx -> justx
-- | Write a String in the serialized output with an added whitespace. Deserializable with `symbol`
insertString :: ByteString -> ST ()
insertString s1= ST(\(Stat(c,s,v)) -> Right(Stat(c, s `append` ( snoc s1 ' '),v),()))
-- | Write a char in the serialized output (no spaces)
insertChar :: Char -> ST()
insertChar car= ST(\(Stat(c,s,v)) -> Right(Stat(c, snoc s car,v),()))
--
-- -------------Instances
instance Serialize String where
showp = showpText
readp = readpText
instance Serialize a => Serialize [a] where
showp []= insertString "[]"
showp (x:xs)= do
insertChar '['
rshowp x
mapM f xs
insertString "]"
where
f :: Serialize a => a -> ST ()
f x= do
insertChar ','
rshowp x
readp = (brackets . commaSep $ rreadp) <?> "readp:: [] "
{-
instance Serialize a => Serialize [a] where
showp xs= showpl [] xs
where
showpl res []= bracketdisp $ Prelude.reverse res
showpl res xs= do
is <- isInVars showp xs
case is of
Right v ->parensdisp (Prelude.reverse res) v
Left v -> showpl (v:res) xs
parensdisp xs t= do
insertChar '('
disp ':' xs
insertChar ':'
insertString t
insertString ")"
bracketdisp []= insertString "[]"
bracketdisp xs= do
insertChar '['
disp ',' xs
insertString "]"
disp sep (x:xs)= do
insertString x
mapM f xs
where
f x= do
insertChar sep
insertString x
readp= choice [bracketsscan, parensscan] <?> "readp:: [] "
where
bracketsscan= (brackets . commaSep $ rreadp) <?> "readp:: [] "
parensscan=parens $ do
xs <- many(rreadp >>= \x -> symbol ":" >> return x)
end <- rreadp
return $ xs ++ end
-}
instance (Serialize a, Serialize b) => Serialize (a, b) where
showp (x, y)= do
insertString "("
rshowp x
insertString ","
rshowp y
insertString ")"
readp = parens (do
x <- rreadp
comma
y <- rreadp
return (x,y))
<?> "rreadp:: (,) "
instance (Serialize a, Serialize b, Serialize c) => Serialize (a, b,c) where
showp (x, y, z)= do
insertString "("
rshowp x
insertString ","
rshowp y
insertString ","
rshowp z
insertString ")"
readp = parens (do
x <- rreadp
comma
y <- rreadp
comma
z <- rreadp
return (x,y,z))
<?> "rreadp:: (,,) "
instance (Serialize a, Serialize b, Serialize c, Serialize d) => Serialize (a, b,c, d) where
showp (x, y, z, t)= do
insertString "("
rshowp x
insertString ","
rshowp y
insertString ","
rshowp z
insertString ","
rshowp t
insertString ")"
readp = parens (do
x <- rreadp
comma
y <- rreadp
comma
z <- rreadp
comma
t <- rreadp
return (x,y,z,t))
<?> "rreadp:: (,,,) "
instance (Serialize a, Ord a, Serialize b) => Serialize (M.Map a b) where
showp m= showp $ M.toList m
readp= do
list <- readp -- :: ST [(a,b)]
return $ M.fromList list
instance Serialize a => Serialize (Maybe a) where
showp Nothing = insertString "Nothing"
showp (Just x) =do
insertString "Just"
showp x
readp = choice [rNothing, rJust] where
rNothing = symbol "Nothing" >> return Nothing
rJust = do
symbol "Just"
x <- readp
return $ Just x
instance (Serialize a, Serialize b) => Serialize (Either a b) where
showp (Left x) = do
insertString "Left"
rshowp x
showp (Right x) = do
insertString "Right"
rshowp x
readp = choice [rLeft, rRight] where
rLeft = symbol "Left" >> rreadp >>= \x -> return $ Left x
rRight = symbol "Right" >> rreadp >>= \x -> return $ Right x
-- binary serialization
binPrefix= "Bin "
binPrefixSp= append (pack binPrefix) " "
-- | serialize a variable which has a Binary instance
showpBinary :: Binary a => a -> ST ()
showpBinary x = do
let s = encode x
let n = pack . show $ B.length s
insertString $ binPrefixSp `append` n `append` " " `append` s
-- | deserialize a variable serialized by `showpBinary`
readpBinary :: Binary a => ST a
readpBinary = do
symbol binPrefix
n <- integer
str <- takep $ fromIntegral n
let x = decode str
return x
-- return n chars form the serialized data
takep :: Int -> ST ByteString
takep n= take1 "" n
where
take1 s 0= return s
take1 s n= anyChar >>= \x -> take1 (snoc s x) (n-1)
-- | defualt instances
instance (Show a, Read a )=> Serialize a where
showp= showpText
readp= readpText
| agocorona/RefSerialize | Data/RefSerialize - copia.hs | bsd-3-clause | 17,844 | 0 | 26 | 5,492 | 4,075 | 2,129 | 1,946 | 279 | 6 |
module Renderer
(
AgentObservable
, renderSugarScapeFrame
) where
import FRP.BearRiver
import qualified Graphics.Gloss as GLO
import AgentMonad
import Discrete
import Model
type SugEnvironmentRenderer = EnvRendererDisc2d SugEnvCell
type SugarScapeAgentRenderer = AgentRendererDisc2d SugAgentObservable
renderSugarScapeFrame :: (Int, Int)
-> Time
-> SugEnvironment
-> [AgentObservable SugAgentObservable]
-> GLO.Picture
renderSugarScapeFrame wSize@(wx, wy) t e ss
= GLO.Pictures (timeStepTxt : envPics ++ agentPics)
where
(dx, dy) = dimensionsDisc2d e
cellWidth = fromIntegral wx / fromIntegral dx
cellHeight = fromIntegral wy / fromIntegral dy
cells = allCellsWithCoords e
agentPics = map (sugarscapeAgentRenderer (cellWidth, cellHeight) wSize t) ss
envPics = map (renderEnvCell (cellWidth, cellHeight) wSize t) cells
timeStepTxt = GLO.color GLO.black $ GLO.translate (-halfWSizeX) (halfWSizeY - 20) $ GLO.scale 0.1 0.1 $ GLO.Text (show t)
halfWSizeX = fromIntegral wx / 2.0
halfWSizeY = fromIntegral wy / 2.0
renderEnvCell :: SugEnvironmentRenderer
renderEnvCell r@(rw, rh) w _t (coord, cell)
| sugarRatio <= 0.01 = GLO.blank
| otherwise = sugarLevelCircle
where
sugarColor = GLO.makeColor 0.9 0.9 0.0 1.0
(x, y) = transformToWindow r w coord
sugarLevel = sugEnvSugarLevel cell
sugarRatio = sugarLevel / snd sugarCapacityRange
sugarRadius = rw * realToFrac sugarRatio
sugarLevelCircle = GLO.color sugarColor $ GLO.translate x y $ GLO.ThickCircle 0 sugarRadius
sugarscapeAgentRenderer :: SugarScapeAgentRenderer
sugarscapeAgentRenderer r@(rw, rh) w _t (aid, s)
= GLO.Pictures [circle, txt]
where
coord = sugObsCoord s
color = GLO.blue
(x, y) = transformToWindow r w coord
circle = GLO.color color $ GLO.translate x y $ GLO.ThickCircle 0 rw
txt = GLO.color GLO.white $ GLO.translate (x - (rw * 0.4)) (y - (rh * 0.1)) $ GLO.scale 0.04 0.04 $ GLO.Text (show aid)
-------------------------------------------------------------------------------
type AgentObservable o = (AgentId, o)
type AgentRendererDisc2d s = (Float, Float)
-> (Int, Int)
-> Time
-> (AgentId, s)
-> GLO.Picture
type EnvRendererDisc2d c = (Float, Float)
-> (Int, Int)
-> Time
-> (Discrete2dCoord, c)
-> GLO.Picture
transformToWindow :: (Float, Float)
-> (Int, Int)
-> Discrete2dCoord
-> (Float, Float)
transformToWindow (rw, rh) (wx, wy) (x, y) = (x', y')
where
halfXSize = fromRational (toRational wx / 2.0)
halfYSize = fromRational (toRational wy / 2.0)
x' = fromRational (toRational (fromIntegral x * rw)) - halfXSize
y' = fromRational (toRational (fromIntegral y * rh)) - halfYSize | thalerjonathan/phd | thesis/code/concurrent/sugarscape/SugarScapePure/src/Renderer.hs | gpl-3.0 | 3,199 | 0 | 14 | 1,003 | 929 | 500 | 429 | 65 | 1 |
import Graphics.UI.GLUT
import Data.IORef
type Point3 = (GLfloat,GLfloat,GLfloat)
type Point2 = (GLfloat,GLfloat)
type RadiusF = GLfloat
type Vertices = Int
main :: IO ()
main = do
(_progName, _args) <- getArgsAndInitialize
_window <- createWindow "Hello world"
object <- newIORef 0.5
displayCallback $= display object
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just (respond object)
mainLoop
display :: IORef RadiusF -> DisplayCallback
display ioRadius = do
radius <- get ioRadius
clear [ ColorBuffer ]
preservingMatrix $ renderPrimitive Polygon $
mapM_ (\(x,y,z) -> vertex $ Vertex3 x y z) $ sphere radius 10
print $ sphere radius 10
flush
sphere :: RadiusF -> Vertices -> [Point3]
sphere r ni = [(r * sin (2*pi*i/n),r * cos (2*pi*i/n),0) | i <- [1..n]]
where n = fromIntegral ni
reshape :: ReshapeCallback
reshape size = viewport $= (Position 0 0, size) >> postRedisplay Nothing
respond :: IORef RadiusF -> KeyboardMouseCallback
respond ioRadius (MouseButton _) keyState modifiers position = ioRadius $~! (+1) >> postRedisplay Nothing
respond _ _ _ _ _ = return ()
| hherman1/BindingOfHaskell | OldMain.hs | gpl-3.0 | 1,105 | 7 | 13 | 190 | 485 | 239 | 246 | 31 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main ( main ) where
import Prelude hiding (putStr)
import Control.Arrow ((&&&))
import Data.ByteString (putStr)
import Data.List (intercalate, sort)
import Data.String (fromString)
import Data.Yaml
import System.Environment (getArgs)
omg cartridgeVersion torVersions = object
[ ("Name", "tor")
, ("Cartridge-Short-Name", "TOR")
, ("Cartridge-Version", fromString cartridgeVersion)
, ("Cartridge-Vendor", "mkollar")
, ("Version", fromString $ last torVersions)
, ("Versions", array $ map fromString torVersions)
, ("License", "Tor's License")
, ("License-Url", "https://gitweb.torproject.org/tor.git/plain/LICENSE")
, ("Categories", array ["embedded", "tor"])
, ("Provides", array $ map (fromString . ("tor - " ++)) torVersions)
, ("Scaling", object [("Min", Number 1), ("Max", Number (-1))])
, ("Source-Url", "https://github.com/xkollar/tor-openshift/archive/master.zip")
]
annotatel :: (a -> b) -> a -> (b, a)
annotatel = (&&& id)
sep :: (a -> Bool) -> [a] -> [[a]]
sep p = uncurry (:) . foldr (\ x (a,s) -> if p x then ([],a:s) else ((x:a),s) ) ([],[])
parseVer :: String -> [Int]
parseVer = map readInt . sep ('.'==) where
readInt = read :: String -> Int
bumpVer :: [Int] -> [Int]
bumpVer [n] = [succ n]
bumpVer (x:s) = x : bumpVer s
bumpVerStr :: String -> String
bumpVerStr = intercalate "." . map show . bumpVer . parseVer
parseAndSortVersions :: String -> [String]
parseAndSortVersions = map snd . sort . map (annotatel $ parseVer) . lines
main' :: [String] -> IO ()
main' [oldCartridgeVersion] = do
versions <- fmap parseAndSortVersions getContents
putStr . encode $ omg (bumpVerStr oldCartridgeVersion) versions
main' _ = print "usage: $1 oldCartridgeVersion"
main :: IO ()
main = getArgs >>= main'
| xkollar/tor-openshift | utils/manifestgen/main.hs | agpl-3.0 | 1,824 | 0 | 13 | 327 | 693 | 393 | 300 | 43 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
module WithCli.ResultSpec where
import Data.Char
import Data.List
import Safe
import System.Exit
import Test.Hspec
import Test.QuickCheck hiding (Result(..))
import WithCli.Result
spec :: Spec
spec = do
describe "Result" $ do
context ">>" $ do
it "collects errors" $ do
(Errors ["foo"] >> Errors ["bar"] :: Result ())
`shouldBe` Errors ["foo", "bar"]
describe "handleResult" $ do
context "OutputAndExit" $ do
it "throws ExitSuccess" $ do
handleResult (OutputAndExit "foo")
`shouldThrow` (== ExitSuccess)
context "Errors" $ do
it "throws an ExitFailure" $ do
handleResult (Errors ["foo"])
`shouldThrow` (== ExitFailure 1)
describe "sanitize" $ do
it "removes empty lines" $ do
property $ \ (unlines -> s) -> do
sanitize s `shouldNotContain` "\n\n"
it "adds a newline at the end if missing" $ do
property $ \ (unlines -> s) ->
not (null (sanitize s)) ==>
lastMay (sanitize s) `shouldBe` Just '\n'
it "only strips spaces" $ do
property $ \ (unlines -> s) -> do
counterexample s $ do
let expected = case s of
"" -> ""
x | lastMay x == Just '\n' -> x
x -> x ++ "\n"
filter (not . isSpace) (sanitize s) `shouldBe` filter (not . isSpace) expected
it "removes trailing spaces" $ do
property $ \ (unlines -> s) -> do
sanitize s `shouldSatisfy` (not . (" \n" `isInfixOf`))
| kosmikus/getopt-generics | test/WithCli/ResultSpec.hs | bsd-3-clause | 1,648 | 0 | 31 | 538 | 537 | 268 | 269 | 45 | 3 |
-----------------------------------------------------------------------------
--
-- Makefile Dependency Generation
--
-- (c) The University of Glasgow 2005
--
-----------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
module ETA.Main.DriverMkDepend (
doMkDependHS
) where
import qualified ETA.Main.GHC as GHC
import ETA.Main.GhcMonad
import ETA.HsSyn.HsSyn ( ImportDecl(..) )
import ETA.Main.DynFlags
import ETA.Utils.Util
import ETA.Main.HscTypes
import ETA.Main.SysTools ( newTempName )
import qualified ETA.Main.SysTools as SysTools
import ETA.BasicTypes.Module
import ETA.Utils.Digraph ( SCC(..) )
import ETA.Main.Finder
import ETA.Utils.Outputable
import ETA.Utils.Panic
import ETA.BasicTypes.SrcLoc
import Data.List
import ETA.Utils.FastString
import ETA.Utils.Exception
import ETA.Main.ErrUtils
import System.Directory
import System.FilePath
import System.IO
import System.IO.Error ( isEOFError )
import Control.Monad ( when )
import Data.Maybe ( isJust )
#include "HsVersions.h"
-----------------------------------------------------------------
--
-- The main function
--
-----------------------------------------------------------------
doMkDependHS :: GhcMonad m => [FilePath] -> m ()
doMkDependHS srcs = do
-- Initialisation
dflags0 <- GHC.getSessionDynFlags
-- We kludge things a bit for dependency generation. Rather than
-- generating dependencies for each way separately, we generate
-- them once and then duplicate them for each way's osuf/hisuf.
-- We therefore do the initial dependency generation with an empty
-- way and .o/.hi extensions, regardless of any flags that might
-- be specified.
let dflags = dflags0 {
ways = [],
buildTag = mkBuildTag [],
hiSuf = "hi",
objectSuf = "jar",
depSuffixes = [""]
}
_ <- GHC.setSessionDynFlags dflags
-- when (null (depSuffixes dflags)) $ liftIO $
-- throwGhcExceptionIO (ProgramError "You must specify at least one -dep-suffix")
files <- liftIO $ beginMkDependHS dflags
-- Do the downsweep to find all the modules
targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
GHC.setTargets targets
let excl_mods = depExcludeMods dflags
mod_summaries <- GHC.depanal excl_mods True {- Allow dup roots -}
-- Sort into dependency order
-- There should be no cycles
let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
-- Print out the dependencies if wanted
liftIO $ debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
-- Prcess them one by one, dumping results into makefile
-- and complaining about cycles
hsc_env <- getSession
root <- liftIO getCurrentDirectory
mapM_ (liftIO . processDeps dflags hsc_env excl_mods root (mkd_tmp_hdl files)) sorted
-- If -ddump-mod-cycles, show cycles in the module graph
liftIO $ dumpModCycles dflags mod_summaries
-- Tidy up
liftIO $ endMkDependHS dflags files
-- Unconditional exiting is a bad idea. If an error occurs we'll get an
--exception; if that is not caught it's fine, but at least we have a
--chance to find out exactly what went wrong. Uncomment the following
--line if you disagree.
--`GHC.ghcCatch` \_ -> io $ exitWith (ExitFailure 1)
-----------------------------------------------------------------
--
-- beginMkDependHs
-- Create a temporary file,
-- find the Makefile,
-- slurp through it, etc
--
-----------------------------------------------------------------
data MkDepFiles
= MkDep { mkd_make_file :: FilePath, -- Name of the makefile
mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile
mkd_tmp_file :: FilePath, -- Name of the temporary file
mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
beginMkDependHS :: DynFlags -> IO MkDepFiles
beginMkDependHS dflags = do
-- open a new temp file in which to stuff the dependency info
-- as we go along.
tmp_file <- newTempName dflags "dep"
tmp_hdl <- openFile tmp_file WriteMode
-- open the makefile
let makefile = depMakefile dflags
exists <- doesFileExist makefile
mb_make_hdl <-
if not exists
then return Nothing
else do
makefile_hdl <- openFile makefile ReadMode
-- slurp through until we get the magic start string,
-- copying the contents into dep_makefile
let slurp = do
l <- hGetLine makefile_hdl
if (l == depStartMarker)
then return ()
else do hPutStrLn tmp_hdl l; slurp
-- slurp through until we get the magic end marker,
-- throwing away the contents
let chuck = do
l <- hGetLine makefile_hdl
if (l == depEndMarker)
then return ()
else chuck
catchIO slurp
(\e -> if isEOFError e then return () else ioError e)
catchIO chuck
(\e -> if isEOFError e then return () else ioError e)
return (Just makefile_hdl)
-- write the magic marker into the tmp file
hPutStrLn tmp_hdl depStartMarker
return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
-----------------------------------------------------------------
--
-- processDeps
--
-----------------------------------------------------------------
processDeps :: DynFlags
-> HscEnv
-> [ModuleName]
-> FilePath
-> Handle -- Write dependencies to here
-> SCC ModSummary
-> IO ()
-- Write suitable dependencies to handle
-- Always:
-- this.o : this.hs
--
-- If the dependency is on something other than a .hi file:
-- this.o this.p_o ... : dep
-- otherwise
-- this.o ... : dep.hi
-- this.p_o ... : dep.p_hi
-- ...
-- (where .o is $osuf, and the other suffixes come from
-- the cmdline -s options).
--
-- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
processDeps dflags _ _ _ _ (CyclicSCC nodes)
= -- There shouldn't be any cycles; report them
throwGhcExceptionIO (ProgramError (showSDoc dflags $ GHC.cyclicModuleErr nodes))
processDeps dflags hsc_env excl_mods root hdl (AcyclicSCC node)
= do { let extra_suffixes = depSuffixes dflags
include_pkg_deps = depIncludePkgDeps dflags
src_file = msHsFilePath node
obj_file = msObjFilePath node
obj_files = insertSuffixes obj_file extra_suffixes
do_imp loc is_boot pkg_qual imp_mod
= do { mb_hi <- findDependency hsc_env loc pkg_qual imp_mod
is_boot include_pkg_deps
; case mb_hi of {
Nothing -> return () ;
Just hi_file -> do
{ let hi_files = insertSuffixes hi_file extra_suffixes
write_dep (obj,hi) = writeDependency root hdl [obj] hi
-- Add one dependency for each suffix;
-- e.g. A.o : B.hi
-- A.x_o : B.x_hi
; mapM_ write_dep (obj_files `zip` hi_files) }}}
-- Emit std dependency of the object(s) on the source file
-- Something like A.o : A.hs
; writeDependency root hdl obj_files src_file
-- Emit a dependency for each import
; let do_imps is_boot idecls = sequence_
[ do_imp loc is_boot (ideclPkgQual i) mod
| L loc i <- idecls,
let mod = unLoc (ideclName i),
mod `notElem` excl_mods ]
; do_imps True (ms_srcimps node)
; do_imps False (ms_imps node)
}
findDependency :: HscEnv
-> SrcSpan
-> Maybe FastString -- package qualifier, if any
-> ModuleName -- Imported module
-> IsBootInterface -- Source import
-> Bool -- Record dependency on package modules
-> IO (Maybe FilePath) -- Interface file file
findDependency hsc_env srcloc pkg imp is_boot include_pkg_deps
= do { -- Find the module; this will be fast because
-- we've done it once during downsweep
r <- findImportedModule hsc_env imp pkg
; case r of
Found loc _
-- Home package: just depend on the .hi or hi-boot file
| isJust (ml_hs_file loc) || include_pkg_deps
-> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
-- Not in this package: we don't need a dependency
| otherwise
-> return Nothing
fail ->
let dflags = hsc_dflags hsc_env
in throwOneError $ mkPlainErrMsg dflags srcloc $
cannotFindModule dflags imp fail
}
-----------------------------
writeDependency :: FilePath -> Handle -> [FilePath] -> FilePath -> IO ()
-- (writeDependency r h [t1,t2] dep) writes to handle h the dependency
-- t1 t2 : dep
writeDependency root hdl targets dep
= do let -- We need to avoid making deps on
-- c:/foo/...
-- on cygwin as make gets confused by the :
-- Making relative deps avoids some instances of this.
dep' = makeRelative root dep
forOutput = escapeSpaces . reslash Forwards . normalise
output = unwords (map forOutput targets) ++ " : " ++ forOutput dep'
hPutStrLn hdl output
-----------------------------
insertSuffixes
:: FilePath -- Original filename; e.g. "foo.o"
-> [String] -- Suffix prefixes e.g. ["x_", "y_"]
-> [FilePath] -- Zapped filenames e.g. ["foo.x_o", "foo.y_o"]
-- Note that that the extra bit gets inserted *before* the old suffix
-- We assume the old suffix contains no dots, so we know where to
-- split it
insertSuffixes file_name extras
= [ basename <.> (extra ++ suffix) | extra <- extras ]
where
(basename, suffix) = case splitExtension file_name of
-- Drop the "." from the extension
(b, s) -> (b, drop 1 s)
-----------------------------------------------------------------
--
-- endMkDependHs
-- Complete the makefile, close the tmp file etc
--
-----------------------------------------------------------------
endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
endMkDependHS dflags
(MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
= do
-- write the magic marker into the tmp file
hPutStrLn tmp_hdl depEndMarker
case makefile_hdl of
Nothing -> return ()
Just hdl -> do
-- slurp the rest of the original makefile and copy it into the output
let slurp = do
l <- hGetLine hdl
hPutStrLn tmp_hdl l
slurp
catchIO slurp
(\e -> if isEOFError e then return () else ioError e)
hClose hdl
hClose tmp_hdl -- make sure it's flushed
-- Create a backup of the original makefile
when (isJust makefile_hdl)
(SysTools.copy dflags ("Backing up " ++ makefile)
makefile (makefile++".bak"))
-- Copy the new makefile in place
SysTools.copy dflags "Installing new makefile" tmp_file makefile
-----------------------------------------------------------------
-- Module cycles
-----------------------------------------------------------------
dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
dumpModCycles dflags mod_summaries
| not (dopt Opt_D_dump_mod_cycles dflags)
= return ()
| null cycles
= putMsg dflags (ptext (sLit "No module cycles"))
| otherwise
= putMsg dflags (hang (ptext (sLit "Module cycles found:")) 2 pp_cycles)
where
cycles :: [[ModSummary]]
cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
pp_cycles = vcat [ (ptext (sLit "---------- Cycle") <+> int n <+> ptext (sLit "----------"))
$$ pprCycle c $$ blankLine
| (n,c) <- [1..] `zip` cycles ]
pprCycle :: [ModSummary] -> SDoc
-- Print a cycle, but show only the imports within the cycle
pprCycle summaries = pp_group (CyclicSCC summaries)
where
cycle_mods :: [ModuleName] -- The modules in this cycle
cycle_mods = map (moduleName . ms_mod) summaries
pp_group (AcyclicSCC ms) = pp_ms ms
pp_group (CyclicSCC mss)
= ASSERT( not (null boot_only) )
-- The boot-only list must be non-empty, else there would
-- be an infinite chain of non-boot imoprts, and we've
-- already checked for that in processModDeps
pp_ms loop_breaker $$ vcat (map pp_group groups)
where
(boot_only, others) = partition is_boot_only mss
is_boot_only ms = not (any in_group (map (ideclName.unLoc) (ms_imps ms)))
in_group (L _ m) = m `elem` group_mods
group_mods = map (moduleName . ms_mod) mss
loop_breaker = head boot_only
all_others = tail boot_only ++ others
groups = GHC.topSortModuleGraph True all_others Nothing
pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
<+> (pp_imps empty (map (ideclName.unLoc) (ms_imps summary)) $$
pp_imps (ptext (sLit "{-# SOURCE #-}")) (map (ideclName.unLoc) (ms_srcimps summary)))
where
mod_str = moduleNameString (moduleName (ms_mod summary))
pp_imps :: SDoc -> [Located ModuleName] -> SDoc
pp_imps _ [] = empty
pp_imps what lms
= case [m | L _ m <- lms, m `elem` cycle_mods] of
[] -> empty
ms -> what <+> ptext (sLit "imports") <+>
pprWithCommas ppr ms
-----------------------------------------------------------------
--
-- Flags
--
-----------------------------------------------------------------
depStartMarker, depEndMarker :: String
depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"
| pparkkin/eta | compiler/ETA/Main/DriverMkDepend.hs | bsd-3-clause | 14,939 | 11 | 36 | 4,651 | 2,759 | 1,454 | 1,305 | 214 | 6 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Network.LambdaBridge where
-- Nothing right now | andygill/lambda-bridge | Network/LambdaBridge.hs | bsd-3-clause | 99 | 0 | 3 | 13 | 8 | 6 | 2 | 2 | 0 |
module Binpack.ParamTH where
import Binpack.Param
import Inter.Types () -- get some default instances
| Erdwolf/autotool-bonn | src/Binpack/ParamTH.hs | gpl-2.0 | 107 | 0 | 4 | 18 | 20 | 13 | 7 | 3 | 0 |
{-# LANGUAGE CPP #-}
module RnSplice (
rnTopSpliceDecls,
rnSpliceType, rnSpliceExpr, rnSplicePat, rnSpliceDecl,
rnBracket,
checkThLocalName
#ifdef GHCI
, traceSplice, SpliceInfo(..)
#endif
) where
#include "HsVersions.h"
import Name
import NameSet
import HsSyn
import RdrName
import TcRnMonad
import Kind
import RnEnv
import RnSource ( rnSrcDecls, findSplice )
import RnPat ( rnPat )
import BasicTypes ( TopLevelFlag, isTopLevel )
import Outputable
import Module
import SrcLoc
import RnTypes ( rnLHsType )
import Control.Monad ( unless, when )
import {-# SOURCE #-} RnExpr ( rnLExpr )
import TcEnv ( checkWellStaged )
import THNames ( liftName )
#ifdef GHCI
import DynFlags
import FastString
import ErrUtils ( dumpIfSet_dyn_printer )
import TcEnv ( tcMetaTy )
import Hooks
import Var ( Id )
import THNames ( quoteExpName, quotePatName, quoteDecName, quoteTypeName
, decsQTyConName, expQTyConName, patQTyConName, typeQTyConName, )
import {-# SOURCE #-} TcExpr ( tcPolyExpr )
import {-# SOURCE #-} TcSplice ( runMetaD, runMetaE, runMetaP, runMetaT, tcTopSpliceExpr )
#endif
import qualified GHC.LanguageExtensions as LangExt
{-
************************************************************************
* *
Template Haskell brackets
* *
************************************************************************
-}
rnBracket :: HsExpr RdrName -> HsBracket RdrName -> RnM (HsExpr Name, FreeVars)
rnBracket e br_body
= addErrCtxt (quotationCtxtDoc br_body) $
do { -- Check that -XTemplateHaskellQuotes is enabled and available
thQuotesEnabled <- xoptM LangExt.TemplateHaskellQuotes
; unless thQuotesEnabled $
failWith ( vcat
[ text "Syntax error on" <+> ppr e
, text ("Perhaps you intended to use TemplateHaskell"
++ " or TemplateHaskellQuotes") ] )
-- Check for nested brackets
; cur_stage <- getStage
; case cur_stage of
{ Splice Typed -> checkTc (isTypedBracket br_body)
illegalUntypedBracket
; Splice Untyped -> checkTc (not (isTypedBracket br_body))
illegalTypedBracket
; Comp -> return ()
; Brack {} -> failWithTc illegalBracket
}
-- Brackets are desugared to code that mentions the TH package
; recordThUse
; case isTypedBracket br_body of
True -> do { traceRn (text "Renaming typed TH bracket")
; (body', fvs_e) <-
setStage (Brack cur_stage RnPendingTyped) $
rn_bracket cur_stage br_body
; return (HsBracket body', fvs_e) }
False -> do { traceRn (text "Renaming untyped TH bracket")
; ps_var <- newMutVar []
; (body', fvs_e) <-
setStage (Brack cur_stage (RnPendingUntyped ps_var)) $
rn_bracket cur_stage br_body
; pendings <- readMutVar ps_var
; return (HsRnBracketOut body' pendings, fvs_e) }
}
rn_bracket :: ThStage -> HsBracket RdrName -> RnM (HsBracket Name, FreeVars)
rn_bracket outer_stage br@(VarBr flg rdr_name)
= do { name <- lookupOccRn rdr_name
; this_mod <- getModule
; when (flg && nameIsLocalOrFrom this_mod name) $
-- Type variables can be quoted in TH. See #5721.
do { mb_bind_lvl <- lookupLocalOccThLvl_maybe name
; case mb_bind_lvl of
{ Nothing -> return () -- Can happen for data constructors,
-- but nothing needs to be done for them
; Just (top_lvl, bind_lvl) -- See Note [Quoting names]
| isTopLevel top_lvl
-> when (isExternalName name) (keepAlive name)
| otherwise
-> do { traceRn (text "rn_bracket VarBr" <+> ppr name <+> ppr bind_lvl <+> ppr outer_stage)
; checkTc (thLevel outer_stage + 1 == bind_lvl)
(quotedNameStageErr br) }
}
}
; return (VarBr flg name, unitFV name) }
rn_bracket _ (ExpBr e) = do { (e', fvs) <- rnLExpr e
; return (ExpBr e', fvs) }
rn_bracket _ (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs)
rn_bracket _ (TypBr t) = do { (t', fvs) <- rnLHsType TypBrCtx t
; return (TypBr t', fvs) }
rn_bracket _ (DecBrL decls)
= do { group <- groupDecls decls
; gbl_env <- getGblEnv
; let new_gbl_env = gbl_env { tcg_dus = emptyDUs }
-- The emptyDUs is so that we just collect uses for this
-- group alone in the call to rnSrcDecls below
; (tcg_env, group') <- setGblEnv new_gbl_env $
rnSrcDecls group
-- Discard the tcg_env; it contains only extra info about fixity
; traceRn (text "rn_bracket dec" <+> (ppr (tcg_dus tcg_env) $$
ppr (duUses (tcg_dus tcg_env))))
; return (DecBrG group', duUses (tcg_dus tcg_env)) }
where
groupDecls :: [LHsDecl RdrName] -> RnM (HsGroup RdrName)
groupDecls decls
= do { (group, mb_splice) <- findSplice decls
; case mb_splice of
{ Nothing -> return group
; Just (splice, rest) ->
do { group' <- groupDecls rest
; let group'' = appendGroups group group'
; return group'' { hs_splcds = noLoc splice : hs_splcds group' }
}
}}
rn_bracket _ (DecBrG _) = panic "rn_bracket: unexpected DecBrG"
rn_bracket _ (TExpBr e) = do { (e', fvs) <- rnLExpr e
; return (TExpBr e', fvs) }
quotationCtxtDoc :: HsBracket RdrName -> SDoc
quotationCtxtDoc br_body
= hang (text "In the Template Haskell quotation")
2 (ppr br_body)
illegalBracket :: SDoc
illegalBracket =
text "Template Haskell brackets cannot be nested" <+>
text "(without intervening splices)"
illegalTypedBracket :: SDoc
illegalTypedBracket =
text "Typed brackets may only appear in typed splices."
illegalUntypedBracket :: SDoc
illegalUntypedBracket =
text "Untyped brackets may only appear in untyped splices."
quotedNameStageErr :: HsBracket RdrName -> SDoc
quotedNameStageErr br
= sep [ text "Stage error: the non-top-level quoted name" <+> ppr br
, text "must be used at the same stage at which is is bound" ]
#ifndef GHCI
rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
rnTopSpliceDecls e = failTH e "Template Haskell top splice"
rnSpliceType :: HsSplice RdrName -> PostTc Name Kind
-> RnM (HsType Name, FreeVars)
rnSpliceType e _ = failTH e "Template Haskell type splice"
rnSpliceExpr :: HsSplice RdrName -> RnM (HsExpr Name, FreeVars)
rnSpliceExpr e = failTH e "Template Haskell splice"
rnSplicePat :: HsSplice RdrName -> RnM (Either (Pat RdrName) (Pat Name), FreeVars)
rnSplicePat e = failTH e "Template Haskell pattern splice"
rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars)
rnSpliceDecl e = failTH e "Template Haskell declaration splice"
#else
{-
*********************************************************
* *
Splices
* *
*********************************************************
Note [Free variables of typed splices]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider renaming this:
f = ...
h = ...$(thing "f")...
where the splice is a *typed* splice. The splice can expand into
literally anything, so when we do dependency analysis we must assume
that it might mention 'f'. So we simply treat all locally-defined
names as mentioned by any splice. This is terribly brutal, but I
don't see what else to do. For example, it'll mean that every
locally-defined thing will appear to be used, so no unused-binding
warnings. But if we miss the dependency, then we might typecheck 'h'
before 'f', and that will crash the type checker because 'f' isn't in
scope.
Currently, I'm not treating a splice as also mentioning every import,
which is a bit inconsistent -- but there are a lot of them. We might
thereby get some bogus unused-import warnings, but we won't crash the
type checker. Not very satisfactory really.
Note [Renamer errors]
~~~~~~~~~~~~~~~~~~~~~
It's important to wrap renamer calls in checkNoErrs, because the
renamer does not fail for out of scope variables etc. Instead it
returns a bogus term/type, so that it can report more than one error.
We don't want the type checker to see these bogus unbound variables.
-}
rnSpliceGen :: (HsSplice Name -> RnM (a, FreeVars)) -- Outside brackets, run splice
-> (HsSplice Name -> (PendingRnSplice, a)) -- Inside brackets, make it pending
-> HsSplice RdrName
-> RnM (a, FreeVars)
rnSpliceGen run_splice pend_splice splice
= addErrCtxt (spliceCtxt splice) $ do
{ stage <- getStage
; case stage of
Brack pop_stage RnPendingTyped
-> do { checkTc is_typed_splice illegalUntypedSplice
; (splice', fvs) <- setStage pop_stage $
rnSplice splice
; let (_pending_splice, result) = pend_splice splice'
; return (result, fvs) }
Brack pop_stage (RnPendingUntyped ps_var)
-> do { checkTc (not is_typed_splice) illegalTypedSplice
; (splice', fvs) <- setStage pop_stage $
rnSplice splice
; let (pending_splice, result) = pend_splice splice'
; ps <- readMutVar ps_var
; writeMutVar ps_var (pending_splice : ps)
; return (result, fvs) }
_ -> do { (splice', fvs1) <- checkNoErrs $
setStage (Splice splice_type) $
rnSplice splice
-- checkNoErrs: don't attempt to run the splice if
-- renaming it failed; otherwise we get a cascade of
-- errors from e.g. unbound variables
; (result, fvs2) <- run_splice splice'
; return (result, fvs1 `plusFV` fvs2) } }
where
is_typed_splice = isTypedSplice splice
splice_type = if is_typed_splice
then Typed
else Untyped
------------------
runRnSplice :: UntypedSpliceFlavour
-> (LHsExpr Id -> TcRn res)
-> (res -> SDoc) -- How to pretty-print res
-- Usually just ppr, but not for [Decl]
-> HsSplice Name -- Always untyped
-> TcRn res
runRnSplice flavour run_meta ppr_res splice
= do { splice' <- getHooked runRnSpliceHook return >>= ($ splice)
; let the_expr = case splice' of
HsUntypedSplice _ e -> e
HsQuasiQuote _ q qs str -> mkQuasiQuoteExpr flavour q qs str
HsTypedSplice {} -> pprPanic "runRnSplice" (ppr splice)
-- Typecheck the expression
; meta_exp_ty <- tcMetaTy meta_ty_name
; zonked_q_expr <- tcTopSpliceExpr Untyped $
tcPolyExpr the_expr meta_exp_ty
-- Run the expression
; result <- run_meta zonked_q_expr
; traceSplice (SpliceInfo { spliceDescription = what
, spliceIsDecl = is_decl
, spliceSource = Just the_expr
, spliceGenerated = ppr_res result })
; return result }
where
meta_ty_name = case flavour of
UntypedExpSplice -> expQTyConName
UntypedPatSplice -> patQTyConName
UntypedTypeSplice -> typeQTyConName
UntypedDeclSplice -> decsQTyConName
what = case flavour of
UntypedExpSplice -> "expression"
UntypedPatSplice -> "pattern"
UntypedTypeSplice -> "type"
UntypedDeclSplice -> "declarations"
is_decl = case flavour of
UntypedDeclSplice -> True
_ -> False
------------------
makePending :: UntypedSpliceFlavour
-> HsSplice Name
-> PendingRnSplice
makePending flavour (HsUntypedSplice n e)
= PendingRnSplice flavour n e
makePending flavour (HsQuasiQuote n quoter q_span quote)
= PendingRnSplice flavour n (mkQuasiQuoteExpr flavour quoter q_span quote)
makePending _ splice@(HsTypedSplice {})
= pprPanic "makePending" (ppr splice)
------------------
mkQuasiQuoteExpr :: UntypedSpliceFlavour -> Name -> SrcSpan -> FastString -> LHsExpr Name
-- Return the expression (quoter "...quote...")
-- which is what we must run in a quasi-quote
mkQuasiQuoteExpr flavour quoter q_span quote
= L q_span $ HsApp (L q_span $
HsApp (L q_span (HsVar (L q_span quote_selector)))
quoterExpr)
quoteExpr
where
quoterExpr = L q_span $! HsVar $! (L q_span quoter)
quoteExpr = L q_span $! HsLit $! HsString "" quote
quote_selector = case flavour of
UntypedExpSplice -> quoteExpName
UntypedPatSplice -> quotePatName
UntypedTypeSplice -> quoteTypeName
UntypedDeclSplice -> quoteDecName
---------------------
rnSplice :: HsSplice RdrName -> RnM (HsSplice Name, FreeVars)
-- Not exported...used for all
rnSplice (HsTypedSplice splice_name expr)
= do { checkTH expr "Template Haskell typed splice"
; loc <- getSrcSpanM
; n' <- newLocalBndrRn (L loc splice_name)
; (expr', fvs) <- rnLExpr expr
; return (HsTypedSplice n' expr', fvs) }
rnSplice (HsUntypedSplice splice_name expr)
= do { checkTH expr "Template Haskell untyped splice"
; loc <- getSrcSpanM
; n' <- newLocalBndrRn (L loc splice_name)
; (expr', fvs) <- rnLExpr expr
; return (HsUntypedSplice n' expr', fvs) }
rnSplice (HsQuasiQuote splice_name quoter q_loc quote)
= do { checkTH quoter "Template Haskell quasi-quote"
; loc <- getSrcSpanM
; splice_name' <- newLocalBndrRn (L loc splice_name)
-- Rename the quoter; akin to the HsVar case of rnExpr
; quoter' <- lookupOccRn quoter
; this_mod <- getModule
; when (nameIsLocalOrFrom this_mod quoter') $
checkThLocalName quoter'
; return (HsQuasiQuote splice_name' quoter' q_loc quote, unitFV quoter') }
---------------------
rnSpliceExpr :: HsSplice RdrName -> RnM (HsExpr Name, FreeVars)
rnSpliceExpr splice
= rnSpliceGen run_expr_splice pend_expr_splice splice
where
pend_expr_splice :: HsSplice Name -> (PendingRnSplice, HsExpr Name)
pend_expr_splice rn_splice
= (makePending UntypedExpSplice rn_splice, HsSpliceE rn_splice)
run_expr_splice :: HsSplice Name -> RnM (HsExpr Name, FreeVars)
run_expr_splice rn_splice
| isTypedSplice rn_splice -- Run it later, in the type checker
= do { -- Ugh! See Note [Splices] above
traceRn (text "rnSpliceExpr: typed expression splice")
; lcl_rdr <- getLocalRdrEnv
; gbl_rdr <- getGlobalRdrEnv
; let gbl_names = mkNameSet [gre_name gre | gre <- globalRdrEnvElts gbl_rdr
, isLocalGRE gre]
lcl_names = mkNameSet (localRdrEnvElts lcl_rdr)
; return (HsSpliceE rn_splice, lcl_names `plusFV` gbl_names) }
| otherwise -- Run it here
= do { traceRn (text "rnSpliceExpr: untyped expression splice")
; rn_expr <- runRnSplice UntypedExpSplice runMetaE ppr rn_splice
; (lexpr3, fvs) <- checkNoErrs (rnLExpr rn_expr)
; return (HsPar lexpr3, fvs) }
----------------------
rnSpliceType :: HsSplice RdrName -> PostTc Name Kind
-> RnM (HsType Name, FreeVars)
rnSpliceType splice k
= rnSpliceGen run_type_splice pend_type_splice splice
where
pend_type_splice rn_splice
= (makePending UntypedTypeSplice rn_splice, HsSpliceTy rn_splice k)
run_type_splice rn_splice
= do { traceRn (text "rnSpliceType: untyped type splice")
; hs_ty2 <- runRnSplice UntypedTypeSplice runMetaT ppr rn_splice
; (hs_ty3, fvs) <- do { let doc = SpliceTypeCtx hs_ty2
; checkNoErrs $ rnLHsType doc hs_ty2 }
-- checkNoErrs: see Note [Renamer errors]
; return (HsParTy hs_ty3, fvs) }
-- Wrap the result of the splice in parens so that we don't
-- lose the outermost location set by runQuasiQuote (#7918)
{- Note [Partial Type Splices]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Partial Type Signatures are partially supported in TH type splices: only
anonymous wild cards are allowed.
-- ToDo: SLPJ says: I don't understand all this
Normally, named wild cards are collected before renaming a (partial) type
signature. However, TH type splices are run during renaming, i.e. after the
initial traversal, leading to out of scope errors for named wild cards. We
can't just extend the initial traversal to collect the named wild cards in TH
type splices, as we'd need to expand them, which is supposed to happen only
once, during renaming.
Similarly, the extra-constraints wild card is handled right before renaming
too, and is therefore also not supported in a TH type splice. Another reason
to forbid extra-constraints wild cards in TH type splices is that a single
signature can contain many TH type splices, whereas it mustn't contain more
than one extra-constraints wild card. Enforcing would this be hard the way
things are currently organised.
Anonymous wild cards pose no problem, because they start out without names and
are given names during renaming. These names are collected right after
renaming. The names generated for anonymous wild cards in TH type splices will
thus be collected as well.
For more details about renaming wild cards, see RnTypes.rnHsSigWcType
Note that partial type signatures are fully supported in TH declaration
splices, e.g.:
[d| foo :: _ => _
foo x y = x == y |]
This is because in this case, the partial type signature can be treated as a
whole signature, instead of as an arbitrary type.
-}
----------------------
-- | Rename a splice pattern. See Note [rnSplicePat]
rnSplicePat :: HsSplice RdrName -> RnM ( Either (Pat RdrName) (Pat Name)
, FreeVars)
rnSplicePat splice
= rnSpliceGen run_pat_splice pend_pat_splice splice
where
pend_pat_splice rn_splice
= (makePending UntypedPatSplice rn_splice, Right (SplicePat rn_splice))
run_pat_splice rn_splice
= do { traceRn (text "rnSplicePat: untyped pattern splice")
; pat <- runRnSplice UntypedPatSplice runMetaP ppr rn_splice
; return (Left (ParPat pat), emptyFVs) }
-- Wrap the result of the quasi-quoter in parens so that we don't
-- lose the outermost location set by runQuasiQuote (#7918)
----------------------
rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars)
rnSpliceDecl (SpliceDecl (L loc splice) flg)
= rnSpliceGen run_decl_splice pend_decl_splice splice
where
pend_decl_splice rn_splice
= (makePending UntypedDeclSplice rn_splice, SpliceDecl (L loc rn_splice) flg)
run_decl_splice rn_splice = pprPanic "rnSpliceDecl" (ppr rn_splice)
rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
-- Declaration splice at the very top level of the module
rnTopSpliceDecls splice
= do { (rn_splice, fvs) <- setStage (Splice Untyped) $
rnSplice splice
; traceRn (text "rnTopSpliceDecls: untyped declaration splice")
; decls <- runRnSplice UntypedDeclSplice runMetaD ppr_decls rn_splice
; return (decls,fvs) }
where
ppr_decls :: [LHsDecl RdrName] -> SDoc
ppr_decls ds = vcat (map ppr ds)
{-
Note [rnSplicePat]
~~~~~~~~~~~~~~~~~~
Renaming a pattern splice is a bit tricky, because we need the variables
bound in the pattern to be in scope in the RHS of the pattern. This scope
management is effectively done by using continuation-passing style in
RnPat, through the CpsRn monad. We don't wish to be in that monad here
(it would create import cycles and generally conflict with renaming other
splices), so we really want to return a (Pat RdrName) -- the result of
running the splice -- which can then be further renamed in RnPat, in
the CpsRn monad.
The problem is that if we're renaming a splice within a bracket, we
*don't* want to run the splice now. We really do just want to rename
it to an HsSplice Name. Of course, then we can't know what variables
are bound within the splice. So we accept any unbound variables and
rename them again when the bracket is spliced in. If a variable is brought
into scope by a pattern splice all is fine. If it is not then an error is
reported.
In any case, when we're done in rnSplicePat, we'll either have a
Pat RdrName (the result of running a top-level splice) or a Pat Name
(the renamed nested splice). Thus, the awkward return type of
rnSplicePat.
-}
spliceCtxt :: HsSplice RdrName -> SDoc
spliceCtxt splice
= hang (text "In the" <+> what) 2 (ppr splice)
where
what = case splice of
HsUntypedSplice {} -> text "untyped splice:"
HsTypedSplice {} -> text "typed splice:"
HsQuasiQuote {} -> text "quasi-quotation:"
-- | The splice data to be logged
data SpliceInfo
= SpliceInfo
{ spliceDescription :: String
, spliceSource :: Maybe (LHsExpr Name) -- Nothing <=> top-level decls
-- added by addTopDecls
, spliceIsDecl :: Bool -- True <=> put the generate code in a file
-- when -dth-dec-file is on
, spliceGenerated :: SDoc
}
-- Note that 'spliceSource' is *renamed* but not *typechecked*
-- Reason (a) less typechecking crap
-- (b) data constructors after type checking have been
-- changed to their *wrappers*, and that makes them
-- print always fully qualified
-- | outputs splice information for 2 flags which have different output formats:
-- `-ddump-splices` and `-dth-dec-file`
traceSplice :: SpliceInfo -> TcM ()
traceSplice (SpliceInfo { spliceDescription = sd, spliceSource = mb_src
, spliceGenerated = gen, spliceIsDecl = is_decl })
= do { loc <- case mb_src of
Nothing -> getSrcSpanM
Just (L loc _) -> return loc
; traceOptTcRn Opt_D_dump_splices (spliceDebugDoc loc)
; when is_decl $ -- Raw material for -dth-dec-file
do { dflags <- getDynFlags
; liftIO $ dumpIfSet_dyn_printer alwaysQualify dflags Opt_D_th_dec_file
(spliceCodeDoc loc) } }
where
-- `-ddump-splices`
spliceDebugDoc :: SrcSpan -> SDoc
spliceDebugDoc loc
= let code = case mb_src of
Nothing -> ending
Just e -> nest 2 (ppr e) : ending
ending = [ text "======>", nest 2 gen ]
in hang (ppr loc <> colon <+> text "Splicing" <+> text sd)
2 (sep code)
-- `-dth-dec-file`
spliceCodeDoc :: SrcSpan -> SDoc
spliceCodeDoc loc
= vcat [ text "--" <+> ppr loc <> colon <+> text "Splicing" <+> text sd
, gen ]
illegalTypedSplice :: SDoc
illegalTypedSplice = text "Typed splices may not appear in untyped brackets"
illegalUntypedSplice :: SDoc
illegalUntypedSplice = text "Untyped splices may not appear in typed brackets"
-- spliceResultDoc :: OutputableBndr id => LHsExpr id -> SDoc
-- spliceResultDoc expr
-- = vcat [ hang (text "In the splice:")
-- 2 (char '$' <> pprParendExpr expr)
-- , text "To see what the splice expanded to, use -ddump-splices" ]
#endif
checkThLocalName :: Name -> RnM ()
checkThLocalName name
| isUnboundName name -- Do not report two errors for
= return () -- $(not_in_scope args)
| otherwise
= do { traceRn (text "checkThLocalName" <+> ppr name)
; mb_local_use <- getStageAndBindLevel name
; case mb_local_use of {
Nothing -> return () ; -- Not a locally-bound thing
Just (top_lvl, bind_lvl, use_stage) ->
do { let use_lvl = thLevel use_stage
; checkWellStaged (quotes (ppr name)) bind_lvl use_lvl
; traceRn (text "checkThLocalName" <+> ppr name <+> ppr bind_lvl <+> ppr use_stage <+> ppr use_lvl)
; checkCrossStageLifting top_lvl bind_lvl use_stage use_lvl name } } }
--------------------------------------
checkCrossStageLifting :: TopLevelFlag -> ThLevel -> ThStage -> ThLevel
-> Name -> TcM ()
-- We are inside brackets, and (use_lvl > bind_lvl)
-- Now we must check whether there's a cross-stage lift to do
-- Examples \x -> [| x |]
-- [| map |]
--
-- This code is similar to checkCrossStageLifting in TcExpr, but
-- this is only run on *untyped* brackets.
checkCrossStageLifting top_lvl bind_lvl use_stage use_lvl name
| Brack _ (RnPendingUntyped ps_var) <- use_stage -- Only for untyped brackets
, use_lvl > bind_lvl -- Cross-stage condition
= check_cross_stage_lifting top_lvl name ps_var
| otherwise
= return ()
check_cross_stage_lifting :: TopLevelFlag -> Name -> TcRef [PendingRnSplice] -> TcM ()
check_cross_stage_lifting top_lvl name ps_var
| isTopLevel top_lvl
-- Top-level identifiers in this module,
-- (which have External Names)
-- are just like the imported case:
-- no need for the 'lifting' treatment
-- E.g. this is fine:
-- f x = x
-- g y = [| f 3 |]
= when (isExternalName name) (keepAlive name)
-- See Note [Keeping things alive for Template Haskell]
| otherwise
= -- Nested identifiers, such as 'x' in
-- E.g. \x -> [| h x |]
-- We must behave as if the reference to x was
-- h $(lift x)
-- We use 'x' itself as the SplicePointName, used by
-- the desugarer to stitch it all back together.
-- If 'x' occurs many times we may get many identical
-- bindings of the same SplicePointName, but that doesn't
-- matter, although it's a mite untidy.
do { traceRn (text "checkCrossStageLifting" <+> ppr name)
-- Construct the (lift x) expression
; let lift_expr = nlHsApp (nlHsVar liftName) (nlHsVar name)
pend_splice = PendingRnSplice UntypedExpSplice name lift_expr
-- Update the pending splices
; ps <- readMutVar ps_var
; writeMutVar ps_var (pend_splice : ps) }
{-
Note [Keeping things alive for Template Haskell]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f x = x+1
g y = [| f 3 |]
Here 'f' is referred to from inside the bracket, which turns into data
and mentions only f's *name*, not 'f' itself. So we need some other
way to keep 'f' alive, lest it get dropped as dead code. That's what
keepAlive does. It puts it in the keep-alive set, which subsequently
ensures that 'f' stays as a top level binding.
This must be done by the renamer, not the type checker (as of old),
because the type checker doesn't typecheck the body of untyped
brackets (Trac #8540).
A thing can have a bind_lvl of outerLevel, but have an internal name:
foo = [d| op = 3
bop = op + 1 |]
Here the bind_lvl of 'op' is (bogusly) outerLevel, even though it is
bound inside a bracket. That is because we don't even even record
binding levels for top-level things; the binding levels are in the
LocalRdrEnv.
So the occurrence of 'op' in the rhs of 'bop' looks a bit like a
cross-stage thing, but it isn't really. And in fact we never need
to do anything here for top-level bound things, so all is fine, if
a bit hacky.
For these chaps (which have Internal Names) we don't want to put
them in the keep-alive set.
Note [Quoting names]
~~~~~~~~~~~~~~~~~~~~
A quoted name 'n is a bit like a quoted expression [| n |], except that we
have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing
the use-level to account for the brackets, the cases are:
bind > use Error
bind = use+1 OK
bind < use
Imported things OK
Top-level things OK
Non-top-level Error
where 'use' is the binding level of the 'n quote. (So inside the implied
bracket the level would be use+1.)
Examples:
f 'map -- OK; also for top-level defns of this module
\x. f 'x -- Not ok (bind = 1, use = 1)
-- (whereas \x. f [| x |] might have been ok, by
-- cross-stage lifting
\y. [| \x. $(f 'y) |] -- Not ok (bind =1, use = 1)
[| \x. $(f 'x) |] -- OK (bind = 2, use = 1)
-}
| oldmanmike/ghc | compiler/rename/RnSplice.hs | bsd-3-clause | 30,024 | 0 | 21 | 9,152 | 2,261 | 1,176 | 1,085 | 160 | 5 |
module Yi.Keymap.Vim.TextObject
( TextObject(..)
, CountedTextObject(..)
, regionOfTextObjectB
, changeTextObjectCount
, changeTextObjectStyle
, stringToTextObject
) where
import Control.Monad (replicateM_, (<=<))
import Yi.Buffer.Adjusted
import Yi.Keymap.Vim.StyledRegion (StyledRegion (..), normalizeRegion)
data TextObject = TextObject !RegionStyle !TextUnit
data CountedTextObject = CountedTextObject !Int !TextObject
changeTextObjectCount :: Int -> CountedTextObject -> CountedTextObject
changeTextObjectCount n (CountedTextObject _ to) = CountedTextObject n to
regionOfTextObjectB :: CountedTextObject -> BufferM StyledRegion
regionOfTextObjectB = normalizeRegion <=< textObjectRegionB'
textObjectRegionB' :: CountedTextObject -> BufferM StyledRegion
textObjectRegionB' (CountedTextObject count (TextObject style unit)) =
fmap (StyledRegion style) $ regionWithTwoMovesB
(maybeMoveB unit Backward)
(replicateM_ count $ moveB unit Forward)
changeTextObjectStyle :: (RegionStyle -> RegionStyle) -> TextObject -> TextObject
changeTextObjectStyle smod (TextObject s u) = TextObject (smod s) u
stringToTextObject :: String -> Maybe TextObject
stringToTextObject ('i':s) = parseTextObject InsideBound s
stringToTextObject ('a':s) = parseTextObject OutsideBound s
stringToTextObject _ = Nothing
parseTextObject :: BoundarySide -> String -> Maybe TextObject
parseTextObject bs (c:[]) = fmap (TextObject Exclusive . ($ bs == OutsideBound)) mkUnit
where mkUnit = lookup c
[('w', toOuter unitViWord unitViWordAnyBnd)
,('W', toOuter unitViWORD unitViWORDAnyBnd)
,('p', toOuter unitEmacsParagraph unitEmacsParagraph) -- TODO inner could be inproved
,('s', toOuter unitSentence unitSentence) -- TODO inner could be inproved
,('"', unitDelimited '"' '"')
,('`', unitDelimited '`' '`')
,('\'', unitDelimited '\'' '\'')
,('(', unitDelimited '(' ')')
,(')', unitDelimited '(' ')')
,('b', unitDelimited '(' ')')
,('[', unitDelimited '[' ']')
,(']', unitDelimited '[' ']')
,('{', unitDelimited '{' '}')
,('}', unitDelimited '{' '}')
,('B', unitDelimited '{' '}')
,('<', unitDelimited '<' '>')
,('>', unitDelimited '<' '>')
-- TODO: 't'
]
parseTextObject _ _ = Nothing
-- TODO: this probably belongs to Buffer.TextUnit
toOuter :: TextUnit -> TextUnit -> Bool -> TextUnit
toOuter outer _ True = leftBoundaryUnit outer
toOuter _ inner False = inner
| TOSPIO/yi | src/library/Yi/Keymap/Vim/TextObject.hs | gpl-2.0 | 2,626 | 0 | 10 | 572 | 711 | 388 | 323 | 59 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Generate haddocks
module Stack.Build.Haddock
( copyDepHaddocks
, generateLocalHaddockIndex
, generateDepsHaddockIndex
, generateSnapHaddockIndex
, shouldHaddockPackage
, shouldHaddockDeps
) where
import Control.Exception (tryJust)
import Control.Monad
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Trans.Resource
import Control.Monad.Writer
import Data.Function
import Data.List
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Path
import Path.IO
import Prelude
import Safe (maximumMay)
import Stack.Types.Build
import Stack.GhcPkg
import Stack.Package
import Stack.Types
import System.Directory (getModificationTime)
import qualified System.FilePath as FP
import System.IO.Error (isDoesNotExistError)
import System.Process.Read
-- | Determine whether we should haddock for a package.
shouldHaddockPackage :: BuildOpts -> Set PackageName -> PackageName -> Bool
shouldHaddockPackage bopts wanted name =
if Set.member name wanted
then boptsHaddock bopts
else shouldHaddockDeps bopts
-- | Determine whether to build haddocks for dependencies.
shouldHaddockDeps :: BuildOpts -> Bool
shouldHaddockDeps bopts = fromMaybe (boptsHaddock bopts) (boptsHaddockDeps bopts)
-- | Copy dependencies' haddocks to documentation directory. This way, relative @../$pkg-$ver@
-- links work and it's easy to upload docs to a web server or otherwise view them in a
-- non-local-filesystem context. We copy instead of symlink for two reasons: (1) symlinks aren't
-- reliably supported on Windows, and (2) the filesystem containing dependencies' docs may not be
-- available where viewing the docs (e.g. if building in a Docker container).
copyDepHaddocks :: (MonadIO m, MonadLogger m, MonadThrow m, MonadCatch m, MonadBaseControl IO m)
=> EnvOverride
-> WhichCompiler
-> BaseConfigOpts
-> [Path Abs Dir]
-> PackageIdentifier
-> Set (Path Abs Dir)
-> m ()
copyDepHaddocks envOverride wc bco pkgDbs pkgId extraDestDirs = do
mpkgHtmlDir <- findGhcPkgHaddockHtml envOverride wc pkgDbs pkgId
case mpkgHtmlDir of
Nothing -> return ()
Just pkgHtmlDir -> do
depGhcIds <- findGhcPkgDepends envOverride wc pkgDbs pkgId
forM_ (map ghcPkgIdPackageIdentifier depGhcIds) $
copyDepWhenNeeded pkgHtmlDir
where
copyDepWhenNeeded pkgHtmlDir depId = do
mDepOrigDir <- findGhcPkgHaddockHtml envOverride wc pkgDbs depId
case mDepOrigDir of
Nothing -> return ()
Just depOrigDir -> do
let extraDestDirs' =
-- Parent test ensures we don't try to copy docs to global locations
if bcoSnapInstallRoot bco `isParentOf` pkgHtmlDir ||
bcoLocalInstallRoot bco `isParentOf` pkgHtmlDir
then Set.insert (parent pkgHtmlDir) extraDestDirs
else extraDestDirs
copyWhenNeeded extraDestDirs' depId depOrigDir
copyWhenNeeded destDirs depId depOrigDir = do
depRelDir <- parseRelDir (packageIdentifierString depId)
copied <- forM (Set.toList destDirs) $ \destDir -> do
let depCopyDir = destDir </> depRelDir
if depCopyDir == depOrigDir
then return False
else do
needCopy <- getNeedCopy depOrigDir depCopyDir
when needCopy $ doCopy depOrigDir depCopyDir
return needCopy
when (or copied) $
copyDepHaddocks envOverride wc bco pkgDbs depId destDirs
getNeedCopy depOrigDir depCopyDir = do
let depOrigIndex = haddockIndexFile depOrigDir
depCopyIndex = haddockIndexFile depCopyDir
depOrigExists <- fileExists depOrigIndex
depCopyExists <- fileExists depCopyIndex
case (depOrigExists, depCopyExists) of
(False, _) -> return False
(True, False) -> return True
(True, True) -> do
copyMod <- liftIO $ getModificationTime (toFilePath depCopyIndex)
origMod <- liftIO $ getModificationTime (toFilePath depOrigIndex)
return (copyMod <= origMod)
doCopy depOrigDir depCopyDir = do
removeTreeIfExists depCopyDir
createTree depCopyDir
copyDirectoryRecursive depOrigDir depCopyDir
-- | Generate Haddock index and contents for local packages.
generateLocalHaddockIndex
:: (MonadIO m, MonadCatch m, MonadThrow m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride -> WhichCompiler -> BaseConfigOpts -> [LocalPackage] -> m ()
generateLocalHaddockIndex envOverride wc bco locals = do
let packageIDs =
map
(\LocalPackage{lpPackage = Package{..}} ->
PackageIdentifier packageName packageVersion)
locals
generateHaddockIndex
"local packages"
envOverride
wc
packageIDs
"."
(localDocDir bco)
-- | Generate Haddock index and contents for local packages and their dependencies.
generateDepsHaddockIndex
:: (MonadIO m, MonadCatch m, MonadThrow m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride -> WhichCompiler -> BaseConfigOpts -> [LocalPackage] -> m ()
generateDepsHaddockIndex envOverride wc bco locals = do
depSets <-
mapM
(\LocalPackage{lpPackage = Package{..}} ->
findTransitiveGhcPkgDepends
envOverride
wc
[bcoSnapDB bco, bcoLocalDB bco]
(PackageIdentifier packageName packageVersion))
locals
generateHaddockIndex
"local packages and dependencies"
envOverride
wc
(Set.toList (Set.unions depSets))
".."
(localDocDir bco </> $(mkRelDir "all"))
-- | Generate Haddock index and contents for all snapshot packages.
generateSnapHaddockIndex
:: (MonadIO m, MonadCatch m, MonadThrow m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride -> WhichCompiler -> BaseConfigOpts -> Path Abs Dir -> m ()
generateSnapHaddockIndex envOverride wc bco globalDB = do
pkgIds <- listGhcPkgDbs envOverride wc [globalDB, bcoSnapDB bco]
generateHaddockIndex
"snapshot packages"
envOverride
wc
pkgIds
"."
(snapDocDir bco)
-- | Generate Haddock index and contents for specified packages.
generateHaddockIndex
:: (MonadIO m, MonadCatch m, MonadThrow m, MonadLogger m, MonadBaseControl IO m)
=> Text
-> EnvOverride
-> WhichCompiler
-> [PackageIdentifier]
-> FilePath
-> Path Abs Dir
-> m ()
generateHaddockIndex descr envOverride wc packageIDs docRelDir destDir = do
createTree destDir
interfaceOpts <- liftIO $ fmap catMaybes (mapM toInterfaceOpt packageIDs)
case maximumMay (map snd interfaceOpts) of
Nothing -> return ()
Just maxInterfaceModTime -> do
eindexModTime <-
liftIO $
tryJust (guard . isDoesNotExistError) $
getModificationTime (toFilePath (haddockIndexFile destDir))
let needUpdate =
case eindexModTime of
Left _ -> True
Right indexModTime ->
indexModTime < maxInterfaceModTime
when
needUpdate $
do $logInfo
("Updating Haddock index for " <> descr <> " in\n" <>
T.pack (toFilePath (haddockIndexFile destDir)))
readProcessNull
(Just destDir)
envOverride
(haddockExeName wc)
(["--gen-contents", "--gen-index"] ++ concatMap fst interfaceOpts)
where
toInterfaceOpt pid@(PackageIdentifier name _) = do
let interfaceRelFile =
docRelDir FP.</> packageIdentifierString pid FP.</>
packageNameString name FP.<.>
"haddock"
interfaceAbsFile = toFilePath destDir FP.</> interfaceRelFile
einterfaceModTime <-
tryJust (guard . isDoesNotExistError) $
getModificationTime interfaceAbsFile
return $
case einterfaceModTime of
Left _ -> Nothing
Right interfaceModTime ->
Just
( [ "-i"
, concat
[ docRelDir FP.</> packageIdentifierString pid
, ","
, interfaceRelFile]]
, interfaceModTime)
-- | Path of haddock index file.
haddockIndexFile :: Path Abs Dir -> Path Abs File
haddockIndexFile destDir = destDir </> $(mkRelFile "index.html")
-- | Path of local packages documentation directory.
localDocDir :: BaseConfigOpts -> Path Abs Dir
localDocDir bco = bcoLocalInstallRoot bco </> docDirSuffix
-- | Path of snapshot packages documentation directory.
snapDocDir :: BaseConfigOpts -> Path Abs Dir
snapDocDir bco = bcoSnapInstallRoot bco </> docDirSuffix
| Denommus/stack | src/Stack/Build/Haddock.hs | bsd-3-clause | 10,081 | 0 | 22 | 3,345 | 1,993 | 1,003 | 990 | 209 | 7 |
<?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="az-AZ">
<title>Report Generation</title>
<maps>
<homeID>reports</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/reports/src/main/javahelp/org/zaproxy/addon/reports/resources/help_az_AZ/helpset_az_AZ.hs | apache-2.0 | 966 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fil-PH">
<title>AJAX Spider | ZAP Extensions</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | ccgreen13/zap-extensions | src/org/zaproxy/zap/extension/spiderAjax/resources/help_fil_PH/helpset_fil_PH.hs | apache-2.0 | 975 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
module ShouldCompile where
import Control.Monad.ST
import Data.STRef
-- (Modified now that we don't have result type signatures)
f:: forall s. ST s Int
f = do v <- newSTRef 5
let g :: ST s Int
-- ^ should be in scope
g = readSTRef v
g
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/tc105.hs | bsd-3-clause | 326 | 0 | 10 | 94 | 73 | 39 | 34 | 9 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-# LANGUAGE RecordWildCards #-}
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Scrabble (scoreLetter, scoreWord)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = do
describe "scoreLetter" $ do
it "'a'" $ scoreLetter 'a' `shouldBe` 1
it "'Z'" $ scoreLetter 'Z' `shouldBe` 10
it "'?'" $ scoreLetter '?' `shouldBe` 0
describe "scoreWord" $ for_ cases test
where
test Case{..} = it description assertion
where
assertion = scoreWord input `shouldBe` fromIntegral expected
data Case = Case { description :: String
, input :: String
, expected :: Integer
}
cases :: [Case]
cases = [ Case { description = "lowercase letter"
, input = "a"
, expected = 1
}
, Case { description = "uppercase letter"
, input = "A"
, expected = 1
}
, Case { description = "valuable letter"
, input = "f"
, expected = 4
}
, Case { description = "short word"
, input = "at"
, expected = 2
}
, Case { description = "short, valuable word"
, input = "zoo"
, expected = 12
}
, Case { description = "medium word"
, input = "street"
, expected = 6
}
, Case { description = "medium, valuable word"
, input = "quirky"
, expected = 22
}
, Case { description = "long, mixed-case word"
, input = "OxyphenButazone"
, expected = 41
}
, Case { description = "english-like word"
, input = "pinata"
, expected = 8
}
, Case { description = "empty input"
, input = ""
, expected = 0
}
, Case { description = "entire alphabet available"
, input = "abcdefghijklmnopqrstuvwxyz"
, expected = 87
}
]
-- a0aa908486542f98a0e421ed775f18945317506e
| exercism/xhaskell | exercises/practice/scrabble-score/test/Tests.hs | mit | 2,527 | 0 | 12 | 1,134 | 514 | 307 | 207 | 54 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE StandaloneDeriving #-}
module Web.Socket where
import Control.Applicative
import Control.Concurrent.Async as Async
import Control.Exception (finally, bracket)
import Control.Lens
import Control.Monad
import Control.Monad.Managed
import Data.Aeson hiding ((.=))
import Data.Aeson.ByteString ()
import Data.ByteString.Lazy (ByteString)
import Data.Data
import Data.Default
import qualified Data.Foldable as F
import Data.IORef
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import GHC.Generics
import MVC
import qualified Network.Socket as S
import qualified Network.WebSockets as WS
import qualified Pipes.Prelude as Pipes
import Pipes.Extended
data SocketConfig
= SocketConfig
{ _cPort :: Int
, _cHost :: String
}
makeLenses ''SocketConfig
defaultSocketConfig :: SocketConfig
defaultSocketConfig = SocketConfig 3566 "0.0.0.0"
instance Default SocketConfig where
def = defaultSocketConfig
data SocketComms
= ServerReady
| CloseSocket
| ServerClosed
| ClientClosed
| ClientReady
| SocketLog ByteString
deriving (Show, Read, Eq, Data, Typeable, Generic)
instance FromJSON SocketComms
instance ToJSON SocketComms
wsSocket ::
SocketConfig ->
Managed (View (Either SocketComms ByteString),
Controller (Either SocketComms ByteString))
wsSocket c = join $ managed $ \k -> do
(oC, iC, sealC) <- spawn' unbounded
(oV, iV, sealV) <- spawn' unbounded
let handler pending =
with (managed (withConnection pending)) $ \conn -> do
aC <- async $ do
runEffect $
forever (do
d <- lift $ WS.receiveData conn
yield d) >->
Pipes.map Right >->
toOutput oC
atomically sealC
aV <- async $ do
runEffect $
fromInput iV >->
until' (Left CloseSocket) >->
forever (do
x <- await
case x of
Left CloseSocket -> do
lift $ WS.sendClose conn ("closing" :: Text)
lift $ putStrLn "CloseSocket!"
Right stream ->
lift $ WS.sendTextData conn stream
_ -> return ())
atomically sealV
link aV
link aC
_ <- waitAnyCancel [aV, aC]
void $ atomically $ send oC (Left ServerClosed)
aServer <- async $ run (c^.cHost) (c^.cPort) handler
(void . atomically . send oC) (Left ServerReady)
result <- k (return
( asSink (void . atomically . send oV)
, asInput iC
))
<* atomically sealC
<* atomically sealV
cancel aServer
return result
withConnection :: WS.PendingConnection -> (WS.Connection -> IO r) -> IO r
withConnection pending =
bracket
(WS.acceptRequest pending)
(\conn -> WS.sendClose conn ("closing" :: ByteString))
withSocket :: String -> Int -> (S.Socket -> IO c) -> IO c
withSocket host port = bracket (WS.makeListenSocket host port) S.sClose
runServerWith' :: String -> Int -> WS.ConnectionOptions -> WS.ServerApp -> IO ()
runServerWith' host port opts app = S.withSocketsDo $ do
sock <- WS.makeListenSocket host port
_ <- forever $ do
(conn, _) <- S.accept sock
a <- async $ Control.Exception.finally
(runApp' conn opts app)
(S.sClose conn)
link a
return ()
S.sClose sock
runApp' :: S.Socket
-> WS.ConnectionOptions
-> WS.ServerApp
-> IO ()
runApp' socket opts app = do
pending <- WS.makePendingConnection socket opts
app pending
run :: String -> Int -> WS.ServerApp -> IO r
run host port app = with (managed (withSocket host port)) $ \sock ->
forever $ do
-- TODO: top level handle
(conn, _) <- S.accept sock
a <- async $ Control.Exception.finally (runApp' conn WS.defaultConnectionOptions app) (S.sClose conn)
link a
return ()
stdinClient :: WS.ClientApp ()
stdinClient conn = do
putStrLn "echoClient Connected!"
-- Fork a thread that writes WS data to stdout
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ Text.putStrLn msg
-- Read from stdin and write to WS
let loop' = do
line <- Text.getLine
unless (Text.null line) $ WS.sendTextData conn line >> loop'
loop'
WS.sendClose conn ("Bye!" :: Text)
echoClient :: WS.ClientApp ()
echoClient conn = do
putStrLn "."
-- Fork a thread that writes WS data to stdout
a <- async $ forever $ do
WS.sendTextData conn (encode [99::Int])
msg <- WS.receiveData conn :: IO ByteString
putStrLn ".1"
WS.sendTextData conn msg
putStrLn $ ".2:" <> show msg
link a
runClient :: SocketConfig -> IO ()
runClient c = WS.runClient (c^.cHost) (c^.cPort) "/" echoClient
wsEchoClient ::
SocketConfig ->
Managed (View SocketComms, Controller SocketComms)
wsEchoClient c = join $ managed $ \k -> do
ref <- newIORef Nothing
(oV, iV, sealV) <- spawn' unbounded
(oC, iC, sealC) <- spawn' unbounded
aV <- async $ do
runEffect $
fromInput iV >->
Pipes.chain (\x -> case x of
ServerReady -> do
aClient <- async $ WS.runClient (c^.cHost) (c^.cPort) "/" echoClient
writeIORef ref (Just aClient)
(void . atomically . send oC) ClientReady
ServerClosed -> do
F.mapM_ cancel =<< readIORef ref
(void . atomically . send oC) ClientClosed
_ -> return ()) >->
forever await
atomically sealV
atomically sealC
res <- k (return
( asSink (void . atomically . send oV)
, asInput iC))
<* atomically sealV
<* atomically sealC
cancel aV
return res
| tonyday567/web-play | src/Web/Socket.hs | mit | 6,605 | 0 | 32 | 2,350 | 1,935 | 953 | 982 | 175 | 3 |
{-# OPTIONS_GHC -Wall #-}
module LeftistHeap where
import Control.Arrow
data Heap a = Leaf | Node Int a (Heap a) (Heap a) deriving (Eq, Show)
empty :: Heap a
empty = Leaf
isEmpty :: Heap a -> Bool
isEmpty Leaf = True
isEmpty _ = False
merge :: Ord a => Heap a -> Heap a -> Heap a
merge h Leaf = h
merge Leaf h = h
merge h0@(Node _ e0 l0 r0) h1@(Node _ e1 l1 r1)
| e0 <= e1 = create e0 l0 (merge r0 h1)
| otherwise = create e1 l1 (merge h0 r1)
rank :: Heap a -> Int
rank Leaf = 0
rank (Node r _ _ _) = r
create :: a -> Heap a -> Heap a -> Heap a
create e l r
| rank l >= rank r = Node (succ (rank r)) e l r
| otherwise = Node (succ (rank l)) e r l
singleton :: Ord a => a -> Heap a
singleton e = Node 1 e Leaf Leaf
insert :: Ord a => a -> Heap a -> Heap a
insert e = merge (singleton e)
findMin :: Heap a -> Maybe a
findMin Leaf = Nothing
findMin (Node _ e _ _) = return e
deleteMin :: Ord a => Heap a -> Heap a
deleteMin Leaf = Leaf
deleteMin (Node _ _ l r) = merge l r
fromList :: Ord a => [a] -> Heap a
fromList = foldr insert empty
-- exercise 3.1 (prove right-spine contains at most floor(log(n + 1)) elements)
-- - binary tree; observe that rightmost-weighted binary tree obeying leftist
-- property is balanced.
-- - right spine length is maximized in balanced case.
-- - tree has depth floor(log(n + 1)) in balanced case.
-- - right spine has at most floor(log(n + 1)) elements.
-- exercise 3.2 (define insert directly rather than by merge)
altInsert :: Ord a => a -> Heap a -> Heap a
altInsert e Leaf = singleton e
altInsert e0 (Node _ e1 l r) = create upper l0 r0 where
(l0, r0) = cascadeInsert (l, r)
(upper, lower)
| e0 <= e1 = (e0, e1)
| otherwise = (e1, e0)
cascadeInsert (h, Leaf) = (h, singleton lower)
cascadeInsert (Leaf, h) = (h, singleton lower)
cascadeInsert hs@(Node _ x _ _, Node _ y _ _)
| x > y = first (altInsert lower) hs
| otherwise = second (altInsert lower) hs
-- exercise 3.3 (implement alternate fromList)
-- - foldup halves list length on each pass, log n foldups
altFromList :: Ord a => [a] -> Heap a
altFromList [] = Leaf
altFromList es
| even (length xs) = merge x (wrapup xs)
| otherwise = wrapup (x:xs)
where
(x:xs) = fmap singleton es
foldup [] = []
foldup (_:[]) = []
foldup (z0:z1:zs) = merge z0 z1 : foldup zs
wrapup [z] = z
wrapup zs = wrapup (foldup zs)
| jtobin/okasaki | working/LeftistHeap.hs | mit | 2,428 | 0 | 10 | 623 | 1,048 | 520 | 528 | 57 | 4 |
module Grammar.Greek.Script.Rounds.WordPunctuationElision where
import Data.Either
import Data.Either.Validation
import Grammar.Common.Round
import Grammar.Common.Types
import Grammar.Greek.Script.Types
data InvalidWordPunctuation
= InvalidWordPunctuation [WordPunctuation]
| EmptyWord
deriving (Show)
wordPunctuationElision :: RoundFwd InvalidWordPunctuation [a :+ WordPunctuation] ([a] :* Elision)
wordPunctuationElision = makeRoundFwd to from
where
to xs = case xs of
[] -> Failure EmptyWord
(Right P_RightQuote : xs') -> case rights xs' of
[] -> Success (lefts xs', Aphaeresis)
ps@(_ : _) -> Failure $ InvalidWordPunctuation ps
(_ : _) -> case reverse xs of
[] -> Failure EmptyWord
(Right P_RightQuote : xs') -> case rights xs' of
[] -> Success (reverse . lefts $ xs', IsElided)
ps@(_ : _) -> Failure $ InvalidWordPunctuation (reverse ps)
xs'@(_ : _) -> case rights xs' of
[] -> Success (reverse . lefts $ xs', NotElided)
ps@(_ : _) -> Failure $ InvalidWordPunctuation (reverse ps)
from (xs, IsElided) = fmap Left xs ++ [Right P_RightQuote]
from (xs, Aphaeresis) = Right P_RightQuote : fmap Left xs
from (xs, NotElided) = fmap Left xs
| ancientlanguage/haskell-analysis | greek-script/src/Grammar/Greek/Script/Rounds/WordPunctuationElision.hs | mit | 1,233 | 0 | 19 | 257 | 450 | 238 | 212 | -1 | -1 |
module ReaderPractice where
import Control.Applicative
import Data.Maybe
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
-- lookup :: Eq a => a -> [(a, b)] -> Maybe b
-- zip x and y using 3 as the lookup key
xs :: Maybe Integer
xs = lookup 3 $ zip x y
-- zip y and z using 6 as the lookup key
ys :: Maybe Integer
ys = lookup 6 $ zip y z
-- zip x and y using 4 as the lookup key
zs :: Maybe Integer
zs = lookup 4 $ zip x y
-- now zip x and z using a variable lookup key
z' :: Integer -> Maybe Integer
z' n = lookup n $ zip x z
-- Have x1 make a tuple of xs and ys
x1 :: Maybe (Integer, Integer)
x1 = (,) <$> xs <*> ys
-- and x2 make a tuple of ys and zs
x2 :: Maybe (Integer, Integer)
x2 = (,) <$> ys <*> zs
x3 :: Integer -> (Maybe Integer, Maybe Integer)
x3 n = (a, a)
where a = z' n
-- 22.11 Chapter Exercises
uncurry' :: (a -> b -> c) -> (a, b) -> c
uncurry' f (a, b) = f a b
summed :: Num c => (c, c) -> c
summed = uncurry' (+)
bolt :: Integer -> Bool
bolt = (&&) <$> (>3) <*> (<8)
fromMaybe' :: a -> Maybe a -> a
fromMaybe' _ (Just x) = x
fromMaybe' y Nothing = y
main :: IO ()
main = do
print $ sequenceA [Just 3, Just 2, Just 1]
print $ sequenceA [x, y]
print $ sequenceA [xs, ys]
print $ summed <$> ((,) <$> xs <*> ys)
print $ fmap summed ((,) <$> xs <*> zs)
print $ bolt 7
print $ fmap bolt z
print $ sequenceA [(>3), (<8), even] 7
-- sequenceA
-- sequenceA :: (Applicative f, Traversable t) => t (f a) -> f (t a)
-- sequenceA [(>3), (<8), even] 7
-- f ~ (->) a and t ~ []
sequA :: Integral a => a -> [Bool]
sequA m = sequenceA [(>3), (<8), even] m
-- s' = Just 15
s' = summed <$> ((,) <$> xs <*> ys)
main' :: IO ()
main' = do
print $ foldr (&&) True $ sequA 7
print $ sequA $ fromMaybe' 0 s'
print $ bolt $ fromMaybe' 0 ys
| mudphone/HaskellBook | src/ReaderPractice.hs | mit | 1,771 | 0 | 12 | 456 | 755 | 407 | 348 | 48 | 1 |
{-# htermination (maximumMyInt :: (List MyInt) -> MyInt) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
foldl :: (b -> a -> b) -> b -> (List a) -> b;
foldl f z Nil = z;
foldl f z (Cons x xs) = foldl f (f z x) xs;
foldl1 :: (a -> a -> a) -> (List a) -> a;
foldl1 f (Cons x xs) = foldl f x xs;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
compareMyInt :: MyInt -> MyInt -> Ordering
compareMyInt = primCmpInt;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
not :: MyBool -> MyBool;
not MyTrue = MyFalse;
not MyFalse = MyTrue;
fsEsOrdering :: Ordering -> Ordering -> MyBool
fsEsOrdering x y = not (esEsOrdering x y);
ltEsMyInt :: MyInt -> MyInt -> MyBool
ltEsMyInt x y = fsEsOrdering (compareMyInt x y) GT;
max0 x y MyTrue = x;
otherwise :: MyBool;
otherwise = MyTrue;
max1 x y MyTrue = y;
max1 x y MyFalse = max0 x y otherwise;
max2 x y = max1 x y (ltEsMyInt x y);
maxMyInt :: MyInt -> MyInt -> MyInt
maxMyInt x y = max2 x y;
maximumMyInt :: (List MyInt) -> MyInt
maximumMyInt = foldl1 maxMyInt;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/maximum_5.hs | mit | 1,963 | 0 | 9 | 454 | 883 | 474 | 409 | 54 | 1 |
module Simulation.Node.Endpoint.Behavior.Descriptor
( Descriptor (..)
) where
import Control.Concurrent.Async (Async)
import Control.Concurrent.STM (TVar)
import Data.Text (Text)
import Simulation.Node.SystemCounter (SystemCounter)
-- | A descriptor for an installed, active, behavior.
data Descriptor c =
Descriptor { slogan :: !Text
, counter :: TVar SystemCounter
, appCounter :: TVar c
, thread :: Async () }
deriving Eq
instance Show c => Show (Descriptor c) where
show desc = "BehaviorDesc { theSlogan = " ++ show (slogan desc) ++ "}"
| kosmoskatten/programmable-endpoint | src/Simulation/Node/Endpoint/Behavior/Descriptor.hs | mit | 626 | 0 | 10 | 162 | 157 | 91 | 66 | 16 | 0 |
{-# LANGUAGE UnicodeSyntax #-}
{-|
Module : LinearRegression
Description : Gradient Descent
Copyright : (c) Fabrício Olivetti, 2017
License : GPL-3
Maintainer : [email protected]
Applies gradient descent to a linear regression problem.
-}
module LinearRegression where
import Control.Parallel.Strategies
import Data.List (foldl')
import Data.List.Split (chunksOf)
import Vector
-- |'parseFile' parses a space separated file
-- to a list of lists of Double
parseFile :: String -> ([[Double]], [Double])
parseFile file = ((map fst dataset), (map snd dataset))
where
dataset = map parseLine (lines file)
parseLine l = splitN (doubled l)
splitN l = (1 : (init l), last l) -- add bias +1
doubled l = map toDouble (words l)
toDouble w = read w :: Double
gradDesc :: [[Double]] -> [Double] -> Double -> Int -> [Double]
gradDesc x y α it = gradDesc' x y w0 α it
where
w0 = take (length' $ head x) [0.01,0.01..]
gradDesc' :: [[Double]] -> [Double] -> [Double] -> Double -> Int -> [Double]
gradDesc' x y w α it
| convergiu = w
| otherwise = gradDesc' x y w' α (it-1)
where
w' = w .+. (α *. nabla)
nabla = mediaVetor $ map (\(yi, xi) -> yi *. xi) $ zip (y .-. y') x
y' = map (dotprod w) x
convergiu = (erro' < 1e-6) || (it==0)
erro' = erro x y w
erro x y w = mean $ (y .-. y') .^ 2
where
y' = map (dotprod w) x
mean :: [Double] -> Double
mean l = (sum l) / (length' l)
polyfeats :: Int -> [[Double]] -> [[Double]]
polyfeats k x = map (\xi -> poly xi !! k) x
where
poly x' = foldr f ([1] : repeat []) x'
f x'' = scanl1 $ (++) . map (*x'')
| folivetti/BIGDATA | 07 - Regressão/LinearRegression.hs | mit | 1,676 | 0 | 12 | 428 | 671 | 361 | 310 | 33 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
module Nix.Expr where
import qualified Prelude as P
import Nix.Common
import qualified Data.HashMap.Strict as H
import qualified Data.HashSet as HS
import qualified Data.Text as T
data FuncArgs
= Arg Name
| Kwargs (HashMap Name (Maybe NixExpr)) Bool (Maybe Name)
deriving (Show, Eq)
data NixExpr
= Var Name
| NixPathVar Name
| Num Int
| Bool Bool
| Null
| OneLineString NixString
| MultiLineString NixString
| Path FilePath
| List [NixExpr]
| Set Bool [NixAssign]
| Let [NixAssign] NixExpr
| Function FuncArgs NixExpr
| Apply NixExpr NixExpr
| With NixExpr NixExpr
| If NixExpr NixExpr NixExpr
| Dot NixExpr [NixString] (Maybe NixExpr)
| BinOp NixExpr Text NixExpr
| Not NixExpr
| Assert NixExpr NixExpr
deriving (Show, Eq)
data NixAssign
= Assign [NixString] NixExpr
| Inherit (Maybe NixExpr) (HashSet Name)
deriving (Show, Eq)
data NixString
= Plain Text
| Antiquote NixString NixExpr NixString
deriving (Show, Eq)
instance IsString NixString where
fromString = Plain . fromString
instance IsString NixExpr where
fromString = Var . fromString
(=$=) :: Name -> NixExpr -> NixAssign
k =$= v = Assign [Plain k] v
str :: Text -> NixExpr
str = OneLineString . Plain
dot :: NixExpr -> [NixString] -> NixExpr
dot e pth = Dot e pth Nothing
simpleKwargs :: [Name] -> FuncArgs
simpleKwargs ns = Kwargs (H.fromList $ map (\n -> (n, Nothing)) ns) False Nothing
simpleSet :: [(Name, NixExpr)] -> NixExpr
simpleSet = Set False . map (uncurry (=$=))
simpleSetRec :: [(Name, NixExpr)] -> NixExpr
simpleSetRec = Set True . map (uncurry (=$=))
-- | Shortcut for a simple kwarg set.
toKwargs :: [(Name, Maybe NixExpr)] -> FuncArgs
toKwargs stuff = Kwargs (H.fromList stuff) False Nothing
-- | Returns whether a string is a valid identifier.
isValidIdentifier :: Name -> Bool
isValidIdentifier "" = False
isValidIdentifier (unpack -> c:cs) = validFirst c && validRest cs
where validFirst c = isAlpha c || c == '-' || c == '_'
validRest (c:cs) = (validFirst c || isDigit c) && validRest cs
validRest "" = True
-- | Renders a path.
renderPath :: [NixString] -> Text
renderPath = mapJoinBy "." ren where
ren (Plain txt) | isValidIdentifier txt = txt
ren txt = renderOneLineString txt
renderOneLineString :: NixString -> Text
renderOneLineString s = "\"" <> escape escapeSingle s <> "\""
renderMultiLineString :: NixString -> Text
renderMultiLineString s = "''" <> escape escapeMulti s <> "''"
renderParens e | isTerm e = render e
renderParens e = "(" <> render e <> ")"
renderKwargs :: [(Name, Maybe NixExpr)] -> Bool -> Text
renderKwargs ks dotdots = case (ks, dotdots) of
([], True) -> "{...}"
([], False) -> "{}"
(ks, True) -> "{" <> ren ks <> ", ...}"
(ks, False) -> "{" <> ren ks <> "}"
where ren ks = mapJoinBy ", " ren' ks
ren' (k, Nothing) = k
ren' (k, Just e) = k <> " ? " <> render e
renderDot :: NixExpr -> [NixString] -> Maybe NixExpr -> Text
renderDot e pth alt = renderParens e <> rpth <> ralt where
rpth = case pth of {[] -> ""; _ -> "." <> renderPath pth}
ralt = case alt of {Nothing -> ""; Just e' -> " or " <> render e'}
-- | A "term" is something which does not need to be enclosed in
-- parentheses.
isTerm :: NixExpr -> Bool
isTerm (Var _) = True
isTerm (Num _) = True
isTerm (Bool _) = True
isTerm Null = True
isTerm (Path p) = True
isTerm (OneLineString _) = True
isTerm (MultiLineString _) = True
isTerm (List _) = True
isTerm (Set _ _) = True
isTerm (Dot _ _ Nothing) = True
isTerm (NixPathVar _) = True
isTerm _ = False
instance Render NixExpr where
render = \case
Var name -> name
Num n -> pack $ show n
Bool True -> "true"
Bool False -> "false"
Null -> "null"
NixPathVar v -> "<" <> v <> ">"
OneLineString s -> renderOneLineString s
MultiLineString s -> renderMultiLineString s
Path pth -> pathToText pth
List es -> "[" <> mapJoinBy " " render es <> "]"
Set True asns -> "rec " <> render (Set False asns)
Set False asns -> "{" <> concatMap render asns <> "}"
Let asns e -> concat ["let ", concatMap render asns, " in ",
render e]
Function arg e -> render arg <> ": " <> render e
Apply e1@(Apply _ _) e2 -> render e1 <> " " <> render e2
Apply e1 e2 -> render e1 <> " " <> renderParens e2
With e1 e2 -> "with " <> render e1 <> "; " <> render e2
Assert e1 e2 -> "assert " <> render e1 <> "; " <> render e2
If e1 e2 e3 -> "if " <> render e1 <> " then "
<> render e2 <> " else " <> render e3
Dot e pth alt -> renderDot e pth alt
BinOp e1 op e2 -> renderParens e1 <> " " <> op <> " " <> renderParens e2
Not e -> "!" <> render e
renderI expr = case expr of
List es -> wrapIndented "[" "]" es
Set True asns -> tell "rec " >> renderI (Set False asns)
Set False asns -> wrapAssigns "{" "}" asns
Let asns e -> wrapAssigns "let " "in " asns >> renderI e
Function params e -> renderI params >> tell ": " >> renderI e
Apply e1@(Apply _ _) e2 -> renderI e1 >> tell " " >> renderI e2
Apply e1 e2 | isTerm e2 -> renderI e1 >> tell " " >> renderI e2
Apply e1 e2 -> renderI e1 >> tell " (" >> renderI e2 >> tell ")"
With e1 e2 -> do
tell "with "
renderI e1
tell "; "
renderI e2
e -> tell $ render e
renderSepBy :: Render a => Text -> [a] -> Indenter
renderSepBy sep [x, y] = renderI x >> tell sep >> renderI y
renderSepBy sep [x] = renderI x
renderSepBy sep (x:xs) = renderI x >> tell sep >> renderSepBy sep xs
renderSepBy _ [] = return ()
wrapAssigns :: Text -> Text -> [NixAssign] -> Indenter
wrapAssigns start finish [] = tell start >> tell finish
wrapAssigns start finish [a] = tell start >> renderI a >> tell finish
wrapAssigns start finish asns = wrapIndented start finish asns
instance Render FuncArgs where
render (Arg a) = a
render (Kwargs k dotdots mname) =
let args = renderKwargs (H.toList k) dotdots
in args <> maybe "" (\n -> " @ " <> n) mname
renderI (Arg a) = tell a
renderI k@(Kwargs ks _ _) | H.size ks <= 4 = tell $ render k
renderI (Kwargs ks dotdots mname) = do
tell "{"
indented $ do
let pairs = H.toList ks
renderPair (n, v) = inNewLine $ do
tell n
case v of
Nothing -> return ()
Just e -> tell " ? " >> renderI e
trailingCommas = if dotdots then pairs else P.init pairs
final = if dotdots then Nothing else Just $ P.last pairs
forM_ trailingCommas $ \(n, v) -> do
renderPair (n, v)
tell ","
forM_ final renderPair
when dotdots $ inNewLine $ tell "..."
inNewLine $ tell "}"
case mname of
Nothing -> return ()
Just name -> tell " @ " >> tell name
instance Render NixAssign where
render (Assign p e) = renderPath p <> " = " <> render e <> ";"
render (Inherit maybE names) = do
let ns = joinBy " " $ HS.toList names
e = maybe "" (\e -> " (" <> render e <> ") ") maybE
"inherit " <> e <> ns <> ";"
renderI (Assign p e) = do
tell $ renderPath p <> " = "
renderI e
tell "; "
renderI (Inherit maybE names) = do
let ns = joinBy " " $ HS.toList names
e = maybe "" (\e -> " (" <> render e <> ") ") maybE
tell $ "inherit " <> e <> ns <> "; "
escapeSingle :: String -> String
escapeSingle s = case s of
'$':'{':s' -> '\\':'$':'{':escapeSingle s'
'\n':s' -> '\\':'n':escapeSingle s'
'\t':s' -> '\\':'t':escapeSingle s'
'\r':s' -> '\\':'r':escapeSingle s'
'\b':s' -> '\\':'b':escapeSingle s'
c:s' -> c : escapeSingle s'
"" -> ""
escapeMulti :: String -> String
escapeMulti s = case s of
'$':'{':s' -> '\\':'$':'{':escapeMulti s
c:s' -> c : escapeMulti s'
"" -> ""
escape :: (String -> String) -> NixString -> Text
escape esc (Plain s) = pack $ esc $ unpack s
escape esc (Antiquote s e s') = concat [escape esc s, "${", render e,
"}", escape esc s']
| adnelson/simple-nix | src/Nix/Expr.hs | mit | 8,108 | 0 | 21 | 2,087 | 3,292 | 1,629 | 1,663 | 212 | 7 |
module Withdrawal where
import qualified Rest
import Network.HTTP.Conduit
import Network.HTTP.Types
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy.Char8 as LC8
import Data.String (fromString)
requests :: IO (Response LC8.ByteString)
requests = Rest.post "/withdrawal_requests/" []
bitcoin :: Double -> String -> IO (Response LC8.ByteString)
bitcoin amount address = Rest.post "/bitcoin_withdrawal/" [(fromString "amount", fromString $ show amount),
(fromString "address", fromString address)] | GildedHonour/BitstampApi | src/Withdrawal.hs | mit | 590 | 0 | 10 | 119 | 154 | 88 | 66 | 12 | 1 |
{-# LANGUAGE GADTs, OverloadedStrings, ScopedTypeVariables, FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances, DefaultSignatures, DeriveGeneric #-}
-- | Types representable as columns in Selda's subset of SQL.
module Database.Selda.SqlType
( SqlType (..), SqlEnum (..)
, Lit (..), UUID, UUID', RowID, ID, SqlValue (..), SqlTypeRep (..)
, invalidRowId, isInvalidRowId, toRowId, fromRowId
, fromId, toId, invalidId, isInvalidId, untyped
, compLit, litType
, sqlDateTimeFormat, sqlDateFormat, sqlTimeFormat
, typedUuid, untypedUuid
) where
import Control.Applicative ((<|>))
import Control.Exception (Exception (..), throw)
import Data.ByteString (ByteString, empty)
import qualified Data.ByteString.Lazy as BSL
import Data.Int (Int32, Int64)
import Data.Maybe (fromJust)
import Data.Proxy
import Data.Text (Text, pack, unpack)
import qualified Data.Text.Lazy as LazyText
import Data.Time
import Data.Typeable
import Data.UUID.Types (UUID, toString, fromByteString, nil)
import GHC.Generics (Generic)
-- | Format string used to represent date and time when
-- representing timestamps as text.
-- If at all possible, use 'SqlUTCTime' instead.
sqlDateTimeFormat :: String
sqlDateTimeFormat = "%F %H:%M:%S%Q%z"
-- | Format string used to represent date when
-- representing dates as text.
-- If at all possible, use 'SqlDate' instead.
sqlDateFormat :: String
sqlDateFormat = "%F"
-- | Format string used to represent time of day when
-- representing time as text.
-- If at all possible, use 'SqlTime' instead.
sqlTimeFormat :: String
sqlTimeFormat = "%H:%M:%S%Q%z"
-- | Representation of an SQL type.
data SqlTypeRep
= TText
| TRowID
| TInt64
| TInt32
| TFloat
| TBool
| TDateTime
| TDate
| TTime
| TBlob
| TUUID
| TJSON
deriving (Show, Eq, Ord)
-- | Any datatype representable in (Selda's subset of) SQL.
class Typeable a => SqlType a where
-- | Create a literal of this type.
mkLit :: a -> Lit a
default mkLit :: (Typeable a, SqlEnum a) => a -> Lit a
mkLit = LCustom TText . LText . toText
-- | The SQL representation for this type.
sqlType :: Proxy a -> SqlTypeRep
sqlType _ = litType (defaultValue :: Lit a)
-- | Convert an SqlValue into this type.
fromSql :: SqlValue -> a
default fromSql :: (Typeable a, SqlEnum a) => SqlValue -> a
fromSql = fromText . fromSql
-- | Default value when using 'def' at this type.
defaultValue :: Lit a
default defaultValue :: (Typeable a, SqlEnum a) => Lit a
defaultValue = mkLit (minBound :: a)
-- | Any type that's bounded, enumerable and has a text representation, and
-- thus representable as a Selda enumerable.
--
-- While it would be more efficient to store enumerables as integers, this
-- makes hand-rolled SQL touching the values inscrutable, and will break if
-- the user a) derives Enum and b) changes the order of their constructors.
-- Long-term, this should be implemented in PostgreSQL as a proper enum
-- anyway, which mostly renders the performance argument moot.
class (Typeable a, Bounded a, Enum a) => SqlEnum a where
toText :: a -> Text
fromText :: Text -> a
instance {-# OVERLAPPABLE #-}
(Typeable a, Bounded a, Enum a, Show a, Read a) => SqlEnum a where
toText = pack . show
fromText = read . unpack
-- | An SQL literal.
data Lit a where
LText :: !Text -> Lit Text
LInt32 :: !Int32 -> Lit Int32
LInt64 :: !Int64 -> Lit Int64
LDouble :: !Double -> Lit Double
LBool :: !Bool -> Lit Bool
LDateTime :: !UTCTime -> Lit UTCTime
LDate :: !Day -> Lit Day
LTime :: !TimeOfDay -> Lit TimeOfDay
LJust :: SqlType a => !(Lit a) -> Lit (Maybe a)
LBlob :: !ByteString -> Lit ByteString
LNull :: SqlType a => Lit (Maybe a)
LCustom :: SqlTypeRep -> Lit a -> Lit b
LUUID :: !UUID -> Lit UUID
-- | The SQL type representation for the given literal.
litType :: Lit a -> SqlTypeRep
litType (LText{}) = TText
litType (LInt32{}) = TInt32
litType (LInt64{}) = TInt64
litType (LDouble{}) = TFloat
litType (LBool{}) = TBool
litType (LDateTime{}) = TDateTime
litType (LDate{}) = TDate
litType (LTime{}) = TTime
litType (LJust x) = litType x
litType (LBlob{}) = TBlob
litType (x@LNull) = sqlType (proxyFor x)
where
proxyFor :: Lit (Maybe a) -> Proxy a
proxyFor _ = Proxy
litType (LCustom t _) = t
litType (LUUID{}) = TUUID
instance Eq (Lit a) where
a == b = compLit a b == EQ
instance Ord (Lit a) where
compare = compLit
-- | Constructor tag for all literals. Used for Ord instance.
litConTag :: Lit a -> Int
litConTag (LText{}) = 0
litConTag (LInt32{}) = 2
litConTag (LInt64{}) = 3
litConTag (LDouble{}) = 4
litConTag (LBool{}) = 5
litConTag (LDateTime{}) = 6
litConTag (LDate{}) = 7
litConTag (LTime{}) = 8
litConTag (LJust{}) = 9
litConTag (LBlob{}) = 10
litConTag (LNull) = 11
litConTag (LCustom{}) = 12
litConTag (LUUID{}) = 13
-- | Compare two literals of different type for equality.
compLit :: Lit a -> Lit b -> Ordering
compLit (LText x) (LText x') = x `compare` x'
compLit (LInt32 x) (LInt32 x') = x `compare` x'
compLit (LInt64 x) (LInt64 x') = x `compare` x'
compLit (LDouble x) (LDouble x') = x `compare` x'
compLit (LBool x) (LBool x') = x `compare` x'
compLit (LDateTime x) (LDateTime x') = x `compare` x'
compLit (LDate x) (LDate x') = x `compare` x'
compLit (LTime x) (LTime x') = x `compare` x'
compLit (LBlob x) (LBlob x') = x `compare` x'
compLit (LJust x) (LJust x') = x `compLit` x'
compLit (LCustom _ x) (LCustom _ x') = x `compLit` x'
compLit (LUUID x) (LUUID x') = x `compare` x'
compLit a b = litConTag a `compare` litConTag b
-- | Some value that is representable in SQL.
data SqlValue where
SqlInt32 :: !Int32 -> SqlValue
SqlInt64 :: !Int64 -> SqlValue
SqlFloat :: !Double -> SqlValue
SqlString :: !Text -> SqlValue
SqlBool :: !Bool -> SqlValue
SqlBlob :: !ByteString -> SqlValue
SqlUTCTime :: !UTCTime -> SqlValue
SqlTime :: !TimeOfDay -> SqlValue
SqlDate :: !Day -> SqlValue
SqlNull :: SqlValue
instance Show SqlValue where
show (SqlInt32 n) = "SqlInt32 " ++ show n
show (SqlInt64 n) = "SqlInt64 " ++ show n
show (SqlFloat f) = "SqlFloat " ++ show f
show (SqlString s) = "SqlString " ++ show s
show (SqlBool b) = "SqlBool " ++ show b
show (SqlBlob b) = "SqlBlob " ++ show b
show (SqlUTCTime t) = "SqlUTCTime " ++ show t
show (SqlTime t) = "SqlTime " ++ show t
show (SqlDate d) = "SqlDate " ++ show d
show (SqlNull) = "SqlNull"
instance Show (Lit a) where
show (LText s) = show s
show (LInt32 i) = show i
show (LInt64 i) = show i
show (LDouble d) = show d
show (LBool b) = show b
show (LDateTime s) = show s
show (LDate s) = show s
show (LTime s) = show s
show (LBlob b) = show b
show (LJust x) = "Just " ++ show x
show (LNull) = "Nothing"
show (LCustom _ l) = show l
show (LUUID u) = toString u
-- | A row identifier for some table.
-- This is the type of auto-incrementing primary keys.
newtype RowID = RowID Int64
deriving (Eq, Ord, Typeable, Generic)
instance Show RowID where
show (RowID n) = show n
-- | A row identifier which is guaranteed to not match any row in any table.
invalidRowId :: RowID
invalidRowId = RowID (-1)
-- | Is the given row identifier invalid? I.e. is it guaranteed to not match any
-- row in any table?
isInvalidRowId :: RowID -> Bool
isInvalidRowId (RowID n) = n < 0
-- | Create a row identifier from an integer.
-- Use with caution, preferably only when reading user input.
toRowId :: Int64 -> RowID
toRowId = RowID
-- | Inspect a row identifier.
fromRowId :: RowID -> Int64
fromRowId (RowID n) = n
-- | A typed row identifier.
-- Generic tables should use this instead of 'RowID'.
-- Use 'untyped' to erase the type of a row identifier, and @cast@ from the
-- "Database.Selda.Unsafe" module if you for some reason need to add a type
-- to a row identifier.
newtype ID a = ID {untyped :: RowID}
deriving (Eq, Ord, Typeable, Generic)
instance Show (ID a) where
show = show . untyped
-- | An UUID identifying a database row.
newtype UUID' a = UUID { untypedUuid :: UUID }
deriving (Eq, Ord, Typeable, Generic)
instance Show (UUID' a) where
show = show . untypedUuid
-- | Convert an untyped UUID to a typed one.
-- Use sparingly, preferably only during deserialization.
typedUuid :: UUID -> UUID' a
typedUuid = UUID
-- | Create a typed row identifier from an integer.
-- Use with caution, preferably only when reading user input.
toId :: Int64 -> ID a
toId = ID . toRowId
-- | Create a typed row identifier from an integer.
-- Use with caution, preferably only when reading user input.
fromId :: ID a -> Int64
fromId (ID i) = fromRowId i
-- | A typed row identifier which is guaranteed to not match any row in any
-- table.
invalidId :: ID a
invalidId = ID invalidRowId
-- | Is the given typed row identifier invalid? I.e. is it guaranteed to not
-- match any row in any table?
isInvalidId :: ID a -> Bool
isInvalidId = isInvalidRowId . untyped
fromSqlError :: String -> a
fromSqlError = throw . FromSqlError
newtype FromSqlError = FromSqlError String
instance Show FromSqlError where
show (FromSqlError e) = "[SELDA BUG] fromSql: " ++ e
instance Exception FromSqlError
instance SqlType RowID where
mkLit (RowID n) = LCustom TRowID (LInt64 n)
sqlType _ = TRowID
fromSql (SqlInt64 x) = RowID x
fromSql v = fromSqlError $ "RowID column with non-int value: " ++ show v
defaultValue = mkLit invalidRowId
instance Typeable a => SqlType (ID a) where
mkLit (ID n) = LCustom TRowID (mkLit n)
sqlType _ = TRowID
fromSql = ID . fromSql
defaultValue = mkLit (ID invalidRowId)
instance SqlType Int where
mkLit n = LCustom TInt64 (LInt64 $ fromIntegral n)
sqlType _ = TInt64
fromSql (SqlInt64 x) = fromIntegral x
fromSql v = fromSqlError $ "int column with non-int value: " ++ show v
defaultValue = mkLit (0 :: Int)
instance SqlType Int64 where
mkLit = LInt64
sqlType _ = TInt64
fromSql (SqlInt64 x) = x
fromSql v = fromSqlError $ "int64 column with non-int value: " ++ show v
defaultValue = LInt64 0
instance SqlType Int32 where
mkLit = LInt32
sqlType _ = TInt32
fromSql (SqlInt32 x) = x
fromSql v = fromSqlError $ "int32 column with non-int value: " ++ show v
defaultValue = LInt32 0
instance SqlType Double where
mkLit = LDouble
sqlType _ = TFloat
fromSql (SqlFloat x) = x
fromSql v = fromSqlError $ "float column with non-float value: " ++ show v
defaultValue = LDouble 0
instance SqlType Text where
mkLit = LText
sqlType _ = TText
fromSql (SqlString x) = x
fromSql v = fromSqlError $ "text column with non-text value: " ++ show v
defaultValue = LText ""
instance SqlType LazyText.Text where
mkLit = LCustom TText . LText . mconcat . LazyText.toChunks
sqlType _ = TText
fromSql (SqlString x) = LazyText.fromChunks [x]
fromSql v = fromSqlError $ "lazy text column with non-text value: " ++ show v
defaultValue = mkLit ""
instance SqlType Bool where
mkLit = LBool
sqlType _ = TBool
fromSql (SqlBool x) = x
fromSql (SqlInt32 0) = False
fromSql (SqlInt32 _) = True
fromSql (SqlInt64 0) = False
fromSql (SqlInt64 _) = True
fromSql v = fromSqlError $ "bool column with non-bool value: " ++ show v
defaultValue = LBool False
instance SqlType UTCTime where
mkLit = LDateTime
sqlType _ = TDateTime
fromSql (SqlUTCTime t) = t
fromSql (SqlString s) =
case withWeirdTimeZone sqlDateTimeFormat (unpack s) of
Just t -> t
_ -> fromSqlError $ "bad datetime string: " ++ unpack s
fromSql v = fromSqlError $ "datetime column with non-datetime value: " ++ show v
defaultValue = LDateTime $ UTCTime (ModifiedJulianDay 40587) 0
instance SqlType Day where
mkLit = LDate
sqlType _ = TDate
fromSql (SqlDate d) = d
fromSql (SqlString s) =
case parseTimeM True defaultTimeLocale sqlDateFormat (unpack s) of
Just t -> t
_ -> fromSqlError $ "bad date string: " ++ unpack s
fromSql v = fromSqlError $ "date column with non-date value: " ++ show v
defaultValue = LDate $ ModifiedJulianDay 40587
instance SqlType TimeOfDay where
mkLit = LTime
sqlType _ = TTime
fromSql (SqlTime s) = s
fromSql (SqlString s) =
case withWeirdTimeZone sqlTimeFormat (unpack s) of
Just t -> t
_ -> fromSqlError $ "bad time string: " ++ unpack s
fromSql v = fromSqlError $ "time column with non-time value: " ++ show v
defaultValue = LTime $ TimeOfDay 0 0 0
-- | Both PostgreSQL and SQLite to weird things with time zones.
-- Long term solution is to use proper binary types internally for
-- time values, so this is really just an interim solution.
withWeirdTimeZone :: ParseTime t => String -> String -> Maybe t
withWeirdTimeZone fmt s =
parseTimeM True defaultTimeLocale fmt (s++"00")
<|> parseTimeM True defaultTimeLocale fmt s
<|> parseTimeM True defaultTimeLocale fmt (s++"+0000")
instance SqlType ByteString where
mkLit = LBlob
sqlType _ = TBlob
fromSql (SqlBlob x) = x
fromSql v = fromSqlError $ "blob column with non-blob value: " ++ show v
defaultValue = LBlob empty
instance SqlType BSL.ByteString where
mkLit = LCustom TBlob . LBlob . BSL.toStrict
sqlType _ = TBlob
fromSql (SqlBlob x) = BSL.fromStrict x
fromSql v = fromSqlError $ "blob column with non-blob value: " ++ show v
defaultValue = LCustom TBlob (LBlob empty)
-- | @defaultValue@ for UUIDs is the all-zero RFC4122 nil UUID.
instance SqlType UUID where
mkLit = LUUID
sqlType _ = TUUID
fromSql (SqlBlob x) = fromJust . fromByteString $ BSL.fromStrict x
fromSql v = fromSqlError $ "UUID column with non-blob value: " ++ show v
defaultValue = LUUID nil
-- | @defaultValue@ for UUIDs is the all-zero RFC4122 nil UUID.
instance Typeable a => SqlType (UUID' a) where
mkLit = LCustom TUUID . LUUID . untypedUuid
sqlType _ = TUUID
fromSql = typedUuid . fromSql
defaultValue = LCustom TUUID (LUUID nil)
instance SqlType a => SqlType (Maybe a) where
mkLit (Just x) = LJust $ mkLit x
mkLit Nothing = LNull
sqlType _ = sqlType (Proxy :: Proxy a)
fromSql (SqlNull) = Nothing
fromSql x = Just $ fromSql x
defaultValue = LNull
instance SqlType Ordering
| valderman/selda | selda/src/Database/Selda/SqlType.hs | mit | 14,615 | 0 | 10 | 3,461 | 4,313 | 2,254 | 2,059 | 359 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.ScriptProfileNode (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.ScriptProfileNode
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.ScriptProfileNode
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/ScriptProfileNode.hs | mit | 364 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
module Verba.Utils where
-- Checks if the first list is contained in the
-- second list.
supersetOf :: (Eq a) => [a] -> [a] -> Bool
supersetOf set maybeSs = all (\x -> x `elem` maybeSs) set
| Jefffrey/Verba | src/Verba/Utils.hs | mit | 191 | 0 | 8 | 38 | 65 | 38 | 27 | 3 | 1 |
module EDDA.Types where
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.ByteString.Char8 as C
import qualified Data.HashSet as HS
import qualified Data.HashMap.Strict as HM
import qualified Data.Vector as V
import Control.Monad.Trans.Reader
import Data.Time
import Data.Int (Int32(..),Int64(..))
import Data.Maybe (isJust,fromJust)
type Str = T.Text
type Timestamp = UTCTime
data Config = Config { zeroMqHost :: String,
mongoHost :: String,
logPath :: String,
mongoDb :: T.Text,
restLogPath :: String,
restCacheTimeout :: Int64,
restPort :: Int,
restPath :: String } deriving Show
data Header = Header { headerUploaderId :: Str, headerSoftwareName :: Str, headerSoftwareVersion :: Str, headerGatewayTimestamp :: Maybe Timestamp } deriving Show
type Class = Char
type Rating = Char
data Level = None | Low | Med | High | Temporary deriving Show
data Mount = Fixed | Gimballed | Turreted deriving Show
data Guidance = Dumbfire | Seeker deriving Show
data CommodityMarketInfo = CommodityMarketInfo {
commodityMarketInfoName :: Str,
commodityMarketInfoMeanPrice :: Int,
commodityMarketInfoBuyPrice :: Int,
commodityMarketInfoSupply :: Int,
commodityMarketInfoSupplyLevel :: Level,
commodityMarketInfoSellPrice :: Int,
commodityMarketInfoDemand :: Int,
commodityMarketInfoDemandLevel :: Level,
commodityMarketInfoStatusFlags :: Maybe [Str]
} deriving Show
data OutfittingModuleInfo = OutfittingModuleHardpoint {
outfittingModuleHardpointName :: Str,
outfittingModuleHardpointMount :: Mount,
outfittingModuleHardpointGuidance :: Maybe Guidance,
outfittingModuleHardpointClass :: Class,
outfittingModuleHardpointRating :: Rating
} |
OutfittingModuleUtility {
outfittingModuleUtilityName :: Str,
outfittingModuleUtilityClass :: Class,
outfittingModuleUtilityRating :: Rating
} |
OutfittingModuleStandard {
outfittingModuleStandardName :: Str,
outfittingModuleStandardShip :: Maybe Str,
outfittingModuleStandardClass :: Class,
outfittingModuleStandardRating :: Rating
} |
OutfittingModuleInternal {
outfittingModuleInternalName :: Str,
outfittingModuleInternalClass :: Class,
outfittingModuleInternalRating :: Rating
}
deriving Show
data MessageInfo = CommodityInfo {
commodityInfoSystemName :: Str,
commodityInfoStationName :: Str,
commodityInfoTimestamp :: Timestamp,
commodityInfoCommodities :: HM.HashMap Str CommodityMarketInfo
} |
ShipyardInfo {
shipyardInfoSystemName :: Str,
shipyardInfoStationName :: Str,
shipyardInfoTimestamp :: Timestamp,
shipyardInfoShips :: HS.HashSet Str
} |
OutfittingInfo {
outfittingInfoSystemName :: Str,
outfittingInfoStationName :: Str,
outfittingInfoTimestamp :: Timestamp,
outfittingInfoModules :: HM.HashMap Str OutfittingModuleInfo
} |
IgnoreInfo
deriving Show
data Ships = Ships { ships :: HS.HashSet Str, shipsTimestamp :: Timestamp }
data Commodities = Commodities { commodities :: HM.HashMap Str CommodityMarketInfo, commoditiesTimestamp :: Timestamp }
data Outfittings = Outfittings { outfitting :: HM.HashMap Str OutfittingModuleInfo, outfittingTimestamp :: Timestamp }
data SystemCoord = SystemCoord {
systemCoordEdsmId :: Int32,
systemCoordSystemName :: Str,
systemCoordX :: Double,
systemCoordY :: Double,
systemCoordZ :: Double
} deriving Show
type ConfigT = ReaderT Config IO
outfittingModuleName :: OutfittingModuleInfo -> Str
outfittingModuleName OutfittingModuleUtility { outfittingModuleUtilityName = name } = name
outfittingModuleName OutfittingModuleHardpoint { outfittingModuleHardpointName = name } = name
outfittingModuleName OutfittingModuleStandard { outfittingModuleStandardName = name } = name
outfittingModuleName OutfittingModuleInternal { outfittingModuleInternalName = name } = name
outfittingModuleClass :: OutfittingModuleInfo -> Class
outfittingModuleClass OutfittingModuleUtility { outfittingModuleUtilityClass = cls } = cls
outfittingModuleClass OutfittingModuleHardpoint { outfittingModuleHardpointClass = cls } = cls
outfittingModuleClass OutfittingModuleStandard { outfittingModuleStandardClass = cls } = cls
outfittingModuleClass OutfittingModuleInternal { outfittingModuleInternalClass = cls } = cls
outfittingModuleRating :: OutfittingModuleInfo -> Rating
outfittingModuleRating OutfittingModuleUtility { outfittingModuleUtilityRating = rating } = rating
outfittingModuleRating OutfittingModuleHardpoint { outfittingModuleHardpointRating = rating } = rating
outfittingModuleRating OutfittingModuleStandard { outfittingModuleStandardRating = rating } = rating
outfittingModuleRating OutfittingModuleInternal { outfittingModuleInternalClass = rating } = rating
outfittingModuleClassRating :: OutfittingModuleInfo -> Str
outfittingModuleClassRating m = T.pack (outfittingModuleClass m : [outfittingModuleRating m])
outfittingModuleFullName m = T.concat [outfittingModuleClassRating m,T.singleton ' ',outfittingModuleName m]
toText :: Str -> T.Text
toText = id
toStr :: T.Text -> Str
toStr = id
allJust :: [Maybe a] -> Maybe [a]
allJust l = if all isJust l then Just $! map fromJust l
else Nothing
onlyJust :: [Maybe a] -> [a]
onlyJust l = map fromJust $! filter isJust l
onlyJustVec :: V.Vector (Maybe a) -> V.Vector a
onlyJustVec v = V.map fromJust (V.filter isJust v)
justNotEmpty :: [a] -> Maybe [a]
justNotEmpty [] = Nothing
justNotEmpty a = Just a
| troydm/edda | src/EDDA/Types.hs | mit | 6,752 | 0 | 10 | 2,088 | 1,239 | 726 | 513 | 118 | 2 |
module Entity
where
import Control.Monad.State
import Graphics.Rendering.OpenGL as OpenGL
import OpenGLUtils
import Utils
-- Entity stuff
data Entity = Entity {
position :: GLvector3
, velocity :: GLvector3
, acceleration :: GLvector3
, rotation :: GLdouble
, angVelocity :: GLdouble
, angAccel :: GLdouble
, color :: Color4 GLfloat
, primitive :: PrimitiveMode
, vertices :: [GLvector3]
, scale :: GLvector3
}
newEntity :: GLvector3 -> GLdouble -> Color4 GLfloat -> PrimitiveMode -> [GLvector3] -> GLvector3 -> Entity
newEntity p rot c pr vrt scl = Entity p glVector3Null glVector3Null rot 0 0 c pr vrt scl
-- TODO: generate mod-functions using TH
modifyPosition :: (GLvector3 -> GLvector3) -> Entity -> Entity
modifyPosition f t = t{Entity.position = f (Entity.position t)}
modifyVelocity :: (GLvector3 -> GLvector3) -> Entity -> Entity
modifyVelocity f t = t{velocity = f (velocity t)}
modifyAcceleration :: (GLvector3 -> GLvector3) -> Entity -> Entity
modifyAcceleration f t = t{acceleration = f (acceleration t)}
modifyRotation :: (GLdouble -> GLdouble) -> Entity -> Entity
modifyRotation f t = t{rotation = f (rotation t)}
modifyAngVelocity :: (GLdouble -> GLdouble) -> Entity -> Entity
modifyAngVelocity f t = t{angVelocity = f (angVelocity t)}
modifyAngAccel :: (GLdouble -> GLdouble) -> Entity -> Entity
modifyAngAccel f t = t{angAccel = f (angAccel t)}
modifyColor :: (Color4 GLfloat -> Color4 GLfloat) -> Entity -> Entity
modifyColor f t = t{Entity.color = f (Entity.color t)}
modifyPrimitive :: (PrimitiveMode -> PrimitiveMode) -> Entity -> Entity
modifyPrimitive f t = t{primitive = f (primitive t)}
modifyScale :: (GLvector3 -> GLvector3) -> Entity -> Entity
modifyScale f t = t{Entity.scale = f (Entity.scale t)}
updateEntity :: GLdouble -> Entity -> Entity
updateEntity delta ent = flip execState ent $ do
let (accx, accy, accz) = acceleration ent
let rr = degToRad $ rotation ent
let accVector =
(accx * cos rr - accy * sin rr,
accx * sin rr + accy * cos rr,
accz)
modify $ modifyVelocity (*+* (accVector *** delta))
modify $ modifyPosition (*+* ((velocity ent) *** delta))
modify $ modifyAngVelocity (+ (angAccel ent) * delta)
modify $ modifyRotation (wrapDegrees . (+ (angVelocity ent) * delta))
resetAcceleration :: Entity -> Entity
resetAcceleration = modifyAcceleration (const glVector3Null)
| anttisalonen/starrover2 | src/Entity.hs | mit | 2,435 | 0 | 15 | 483 | 866 | 462 | 404 | 50 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Main where
import Prelude hiding ((.), id)
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Category
import qualified Data.Text.Lazy as TL
import Data.Scientific
import Data.Semigroup
import Test.QuickCheck ()
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck as QC
import GHC.Generics
import Language.Sexp as Sexp hiding (parseSexp')
import Language.SexpGrammar as G
import Language.SexpGrammar.Generic
import Language.SexpGrammar.TH hiding (match)
pattern List' xs = List (Position "<no location information>" 1 0) xs
pattern Bool' x = Atom (Position "<no location information>" 1 0) (AtomBool x)
pattern Int' x = Atom (Position "<no location information>" 1 0) (AtomInt x)
pattern Keyword' x = Atom (Position "<no location information>" 1 0) (AtomKeyword x)
pattern Real' x = Atom (Position "<no location information>" 1 0) (AtomReal x)
pattern String' x = Atom (Position "<no location information>" 1 0) (AtomString x)
pattern Symbol' x = Atom (Position "<no location information>" 1 0) (AtomSymbol x)
stripPos :: Sexp -> Sexp
stripPos (Atom _ x) = Atom dummyPos x
stripPos (List _ xs) = List dummyPos $ map stripPos xs
stripPos (Vector _ xs) = Vector dummyPos $ map stripPos xs
stripPos (Quoted _ x) = Quoted dummyPos $ stripPos x
parseSexp' :: String -> Either String Sexp
parseSexp' input = stripPos <$> Sexp.decode (TL.pack input)
data Pair a b = Pair a b
deriving (Show, Eq, Ord, Generic)
data Foo a b = Bar a b
| Baz a b
deriving (Show, Eq, Ord, Generic)
data Rint = Rint Int
data ArithExpr =
Lit Int
| Add ArithExpr ArithExpr -- ^ (+ x y)
| Mul [ArithExpr] -- ^ (* x1 ... xN)
deriving (Show, Eq, Ord, Generic)
return []
instance Arbitrary ArithExpr where
arbitrary = frequency
[ (5, Lit <$> arbitrary)
, (1, Add <$> arbitrary <*> arbitrary)
, (1, do
n <- choose (0, 7)
Mul <$> vectorOf n arbitrary)
]
arithExprTHProp :: ArithExpr -> Bool
arithExprTHProp expr =
(G.genSexp arithExprGrammar expr >>= G.parseSexp arithExprGrammar :: Either String ArithExpr)
==
Right expr
where
arithExprGrammar :: Grammar SexpGrammar (Sexp :- t) (ArithExpr :- t)
arithExprGrammar = sexpIso
arithExprGenericsProp :: ArithExpr -> Bool
arithExprGenericsProp expr =
(G.genSexp arithExprGenericIso expr >>= G.parseSexp arithExprGenericIso :: Either String ArithExpr)
==
Right expr
instance (SexpIso a, SexpIso b) => SexpIso (Pair a b) where
sexpIso = $(grammarFor 'Pair) . list (el sexpIso >>> el sexpIso)
pairGenericIso :: SexpG a -> SexpG b -> SexpG (Pair a b)
pairGenericIso a b = with (\pair -> pair . list (el a >>> el b))
instance (SexpIso a, SexpIso b) => SexpIso (Foo a b) where
sexpIso = sconcat
[ $(grammarFor 'Bar) . list (el (sym "bar") >>> el sexpIso >>> el sexpIso)
, $(grammarFor 'Baz) . list (el (sym "baz") >>> el sexpIso >>> el sexpIso)
]
fooGenericIso :: SexpG a -> SexpG b -> SexpG (Foo a b)
fooGenericIso a b = match
$ With (\bar -> bar . list (el (sym "bar") >>> el a >>> el b))
$ With (\baz -> baz . list (el (sym "baz") >>> el a >>> el b))
$ End
instance SexpIso ArithExpr where
sexpIso = sconcat
[ $(grammarFor 'Lit) . int
, $(grammarFor 'Add) . list (el (sym "+") >>> el sexpIso >>> el sexpIso)
, $(grammarFor 'Mul) . list (el (sym "*") >>> rest sexpIso)
]
arithExprGenericIso :: SexpG ArithExpr
arithExprGenericIso = expr
where
expr :: SexpG ArithExpr
expr = match
$ With (\lit -> lit . int)
$ With (\add -> add . list (el (sym "+") >>> el expr >>> el expr))
$ With (\mul -> mul . list (el (sym "*") >>> rest expr))
$ End
----------------------------------------------------------------------
-- Test cases
allTests :: TestTree
allTests = testGroup "All tests"
[ lexerTests
, grammarTests
]
lexerTests :: TestTree
lexerTests = testGroup "Lexer tests"
[ testCase "123 is an integer number" $
parseSexp' "123" @?= Right (Int' 123)
, testCase "+123 is an integer number" $
parseSexp' "+123" @?= Right (Int' 123)
, testCase "-123 is an integer number" $
parseSexp' "-123" @?= Right (Int' (- 123))
, testCase "+123.4e5 is a floating number" $
parseSexp' "+123.4e5" @?= Right (Real' (read "+123.4e5" :: Scientific))
, testCase "comments" $
parseSexp' ";; hello, world\n 123" @?= Right (Int' 123)
, testCase "cyrillic characters in comments" $
parseSexp' ";; привет!\n 123" @?= Right (Int' 123)
, testCase "unicode math in comments" $
parseSexp' ";; Γ ctx\n;; ----- Nat-formation\n;; Γ ⊦ Nat : Type\nfoobar" @?=
Right (Symbol' "foobar")
, testCase "symbol" $
parseSexp' "hello-world" @?= Right (Symbol' "hello-world")
, testCase "cyrillic symbol" $
parseSexp' "привет-мир" @?= Right (Symbol' "привет-мир")
, testCase "string with arabic characters" $
parseSexp' "\"ي الخاطفة الجديدة، مع, بلديهم\"" @?=
Right (String' "ي الخاطفة الجديدة، مع, بلديهم")
, testCase "string with japanese characters" $
parseSexp' "\"媯綩 づ竤バ り姥娩ぎょひ\"" @?=
Right (String' "媯綩 づ竤バ り姥娩ぎょひ")
]
grammarTests :: TestTree
grammarTests = testGroup "Grammar tests"
[ baseTypeTests
, listTests
, revStackPrismTests
, parseTests
, genTests
, parseGenTests
]
baseTypeTests :: TestTree
baseTypeTests = testGroup "Base type combinator tests"
[ testCase "bool" $
G.parseSexp bool (Bool' True) @?= Right True
, testCase "integer" $
G.parseSexp integer (Int' (42 ^ (42 :: Integer))) @?= Right (42 ^ (42 :: Integer))
, testCase "int" $
G.parseSexp int (Int' 65536) @?= Right 65536
, testCase "real" $
G.parseSexp real (Real' 3.14) @?= Right 3.14
, testCase "double" $
G.parseSexp double (Real' 3.14) @?= Right 3.14
, testCase "string" $
G.parseSexp string (String' "foo\nbar baz") @?= Right "foo\nbar baz"
, testCase "string'" $
G.parseSexp string' (String' "foo\nbar baz") @?= Right "foo\nbar baz"
, testCase "keyword" $
G.parseSexp keyword (Keyword' (Kw "foobarbaz")) @?= Right (Kw "foobarbaz")
, testCase "symbol" $
G.parseSexp symbol (Symbol' "foobarbaz") @?= Right "foobarbaz"
, testCase "symbol'" $
G.parseSexp symbol' (Symbol' "foobarbaz") @?= Right "foobarbaz"
]
listTests :: TestTree
listTests = testGroup "List combinator tests"
[ testCase "empty list of bools" $
G.parseSexp (list (rest bool)) (List' []) @?= Right []
, testCase "list of bools" $
G.parseSexp (list (rest bool)) (List' [Bool' True, Bool' False, Bool' False]) @?=
Right [True, False, False]
]
revStackPrismTests :: TestTree
revStackPrismTests = testGroup "Reverse stack prism tests"
[ testCase "pair of two bools" $
G.parseSexp sexpIso (List' [Bool' False, Bool' True]) @?=
Right (Pair False True)
, testCase "sum of products (Bar True 42)" $
G.parseSexp sexpIso (List' [Symbol' "bar", Bool' True, Int' 42]) @?=
Right (Bar True (42 :: Int))
, testCase "sum of products (Baz True False) tries to parse (baz #f 10)" $
G.parseSexp sexpIso (List' [Symbol' "baz", Bool' False, Int' 10]) @?=
(Left ("<no location information>:1:0: mismatch:\n expected: atom of type bool\n got: 10") :: Either String (Foo Bool Bool))
]
testArithExpr :: ArithExpr
testArithExpr = Add (Lit 0) (Mul [])
testArithExprSexp :: Sexp
testArithExprSexp = List' [Symbol' "+", Int' 0, List' [Symbol' "*"]]
parseTests :: TestTree
parseTests = testGroup "parse tests"
[ testCase "(+ 0 (*))" $
Right testArithExpr @=? G.parseSexp sexpIso testArithExprSexp
]
genTests :: TestTree
genTests = testGroup "gen tests"
[ testCase "(+ 0 (*))" $
Right testArithExprSexp @=? G.genSexp sexpIso testArithExpr
]
parseGenTests :: TestTree
parseGenTests = testGroup "parse . gen == id"
[ QC.testProperty "ArithExprs TH" arithExprTHProp
, QC.testProperty "ArithExprs Generics" arithExprGenericsProp
]
main :: IO ()
main = defaultMain allTests
| ricardopenyamari/ir2haskell | clir-parser-haskell-master/lib/sexp-grammar/test/Main.hs | gpl-2.0 | 8,533 | 0 | 20 | 1,766 | 2,752 | 1,387 | 1,365 | 194 | 1 |
-- udisksevt source file
-- Copyright (C) Vladimir Matveev, 2010
-- Datatypes collection module
module UDisksEvt.Datatypes where
import Data.Map (Map)
import DBus.Client (Client)
import DBus.Types
import Control.Concurrent.STM (TVar)
import Text.ParserCombinators.Parsec (GenParser)
-- Main configuration datatype
data Configuration = C { cVars :: Map String ConfigVarValue
, cTriggers :: Map String [ConfigTriggerAction]
}
deriving (Show)
-- Configuration variable value
data ConfigVarValue = CVString String
| CVBool Bool
| CVInt Int
deriving (Show, Eq)
-- Configuration trigger action - these commands definition
data ConfigTriggerAction = CTAShellCommand { ctascCommand :: String
}
| CTANotification { ctanBody :: String
, ctanSummary :: String
, ctanIcon :: String
, ctanTimeout :: Int
, ctanUrgency :: NotificationUrgency
}
deriving (Show)
-- Notification urgency parameter
data NotificationUrgency = NULow
| NUNormal
| NUCritical
deriving (Show)
instance Read NotificationUrgency where
readsPrec _ = readUrgency
where
readUrgency "low" = [(NULow, "")]
readUrgency "normal" = [(NUNormal, "")]
readUrgency "critical" = [(NUCritical, "")]
readUrgency u = error ("Incorrect urgency level: " ++ u)
-- State type used in parsing
data ConfParserState = CPS { cpsCurrentTrigger :: Maybe String
, cpsConfiguration :: Configuration
}
-- Custom parser type with state
type ConfParser a = GenParser Char ConfParserState a
-- Device information structure, used for caching
data DeviceInfo = DInfo { diObjectPath :: String
, diDeviceFile :: String
, diProperties :: Map String Variant
} deriving (Show)
-- Global state datatype
data UState = U { uConfig :: Configuration
, uSessionClient :: Client
, uSystemClient :: Client
, uDevices :: TVar (Map String DeviceInfo)
}
| netvl/udisksevt | UDisksEvt/Datatypes.hs | gpl-2.0 | 2,569 | 0 | 11 | 1,059 | 420 | 251 | 169 | 41 | 0 |
import System.Random
import System.IO (hFlush, stdout)
import Data.Maybe (fromJust)
import Data.List.Split (chunksOf)
import Data.Map (Map)
import qualified Data.Map as Map
import qualified System.IO.Strict as S
accumF a b = (a + b, a + b)
ns = [7,6..1]
lastTplLst s = Map.singleton (last s) 1
lastN n xs = reverse (take n (reverse xs))
fileName = "viisi-viikkoa-ilmapallossa.txt"
chunks n xs
| n <= length xs = fst (splitAt n xs) : chunks n (tail xs)
| otherwise = []
nth rand r (x:y:zs)
| r <= rand = x
| otherwise = nth rand (r*r) (y:zs)
nth rand r (x:[]) = x
testSample sampleWrds str =
Map.lookup str sampleMap
where
sample = zip (map init sampleWrds) (map lastTplLst sampleWrds)
sampleMap = Map.fromListWith (Map.unionWith (+)) sample
intToDouble :: Int -> Double
intToDouble i = fromRational (toRational i)
frekratio x y =
intToDouble x / intToDouble y
growing xs =
zip b [sum (take n c) | n <- [1..length c]]
where
(b,c) = unzip xs
newLetter rands res7 =
fst (head dw)
where
fj = fromJust (nth r2 0.50 [x | x <- res7, x /= Nothing])
xs = Map.toList fj
frekSum = sum [snd x | x <- xs]
--(frekSum, accumTree) = Map.mapAccum accumF 0 fj
--accumLst = Map.toList accumTree
--dw = dropWhile (\x -> frekratio (snd x) frekSum < r1) accumLst
dw = dropWhile (\x -> frekratio (snd x) frekSum < r1) (growing xs)
r1 = head rands
r2 = head (drop 1 rands)
{-
# a typical res7:
Nothing
Nothing
Nothing
Just (fromList [('I',1)])
Just (fromList [(' ',2),('A',1),('I',2),('S',1),('a',14),('c',1),('e',22),
('i',6),('k',3),('o',2),('p',1),('t',1),('u',7)])
Just (fromList [('\n',411),('\r',411),(' ',2047),('!',19),('"',25),('\'',14),
('(',15),(')',19),(',',230),('-',102),('.',167),('0',9),('1',13),('2',6),
('3',4),('4',4),('5',9),('6',3),('7',2),('8',7),('9',1),(':',23),(';',21),
('=',2),('?',2),('A',20),('B',12),('C',8),('D',12),('E',37),('F',35),
('G',7),('H',20),('I',19),('J',13),('K',38),('L',24),('M',42),('N',16),
('O',7),('P',20),('R',10),('S',63),('T',35),('U',10),('V',10),('W',3),
('Y',4),('Z',3),('_',34),('a',1763),('b',16),('c',31),('d',113),('e',1393),
('f',21),('g',65),('h',374),('i',1775),('j',238),('k',809),('l',937),
('m',468),('n',1615),('o',823),('p',236),('q',1),('r',438),('s',1203),
('t',1446),('u',708),('v',304),('w',4),('x',3),('y',278),('z',3),
('\156',1),('\196',2),('\228',796),('\233',1),('\235',1),('\246',64),
('\252',1),('\65279',1)])
-}
generate sample7s accum rands =
c : generate sample7s newAccum newRands
where
newRands = drop 2 rands
newAccum = lastN 6 (accum ++ [c])
res7 = [testSample s (lastN (n-1) accum) | (s,n) <- zip sample7s ns]
c = newLetter (take 2 rands) res7
putCharF c = do
(putStr . charToString) c
hFlush stdout
cutGenerate piece accum = do
setStdGen (mkStdGen 2015) -- test case
g <- getStdGen
let
rands = randomRs (0.0,1.0) g :: [Double]
sample7s = [chunks n piece | n <- ns]
--mapM_ putCharF (generate sample7s accum rands)
putStrLn (take 3000 (generate sample7s accum rands))
--putStrLn ""
charToString :: Char -> String
charToString c = [c]
main = do
--content <- readFile fileName
content <- S.readFile fileName
let
startAccum = take 6 content
pieces = chunksOf 20000 content
piece = concat (take 1 pieces)
mapM_ putCharF startAccum
cutGenerate piece startAccum
| jsavatgy/dit-doo | too-old/too-old-01.hs | gpl-2.0 | 3,405 | 0 | 13 | 607 | 975 | 497 | 478 | 64 | 1 |
{-# LANGUAGE OverloadedStrings, TypeFamilies #-}
module Lamdu.GUI.ExpressionEdit
( make
) where
import Control.Lens.Operators
import Control.Lens.Tuple
import qualified Data.List as List
import qualified Graphics.UI.Bottle.Font as Font
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.TextEdit as TextEdit
import qualified Graphics.UI.Bottle.Widgets.TextView as TextView
import qualified Graphics.UI.Bottle.WidgetsEnvT as WE
import qualified Lamdu.Config as Config
import qualified Lamdu.GUI.ExpressionEdit.ApplyEdit as ApplyEdit
import qualified Lamdu.GUI.ExpressionEdit.CaseEdit as CaseEdit
import qualified Lamdu.GUI.ExpressionEdit.GetFieldEdit as GetFieldEdit
import qualified Lamdu.GUI.ExpressionEdit.GetVarEdit as GetVarEdit
import qualified Lamdu.GUI.ExpressionEdit.HoleEdit as HoleEdit
import qualified Lamdu.GUI.ExpressionEdit.InjectEdit as InjectEdit
import qualified Lamdu.GUI.ExpressionEdit.LambdaEdit as LambdaEdit
import qualified Lamdu.GUI.ExpressionEdit.LiteralEdit as LiteralEdit
import qualified Lamdu.GUI.ExpressionEdit.NomEdit as NomEdit
import qualified Lamdu.GUI.ExpressionEdit.RecordEdit as RecordEdit
import Lamdu.GUI.ExpressionGui (ExpressionGui)
import qualified Lamdu.GUI.ExpressionGui as ExpressionGui
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import Lamdu.Sugar.Names.Types (Name(..))
import qualified Lamdu.Sugar.Types as Sugar
shrinkIfHigherThanLine :: Monad m => ExprGuiM m (ExpressionGui f -> ExpressionGui f)
shrinkIfHigherThanLine =
do
sizedFont <-
ExprGuiM.widgetEnv WE.readTextStyle
<&> (^. TextEdit.sTextViewStyle . TextView.styleFont)
config <- ExprGuiM.readConfig <&> Config.hole
return $ \w ->
let ratio =
(Font.height sizedFont /
w ^. ExpressionGui.egWidget . Widget.height)
** realToFrac (Config.holeResultInjectedScaleExponent config)
result
| ratio >= 1 = w
| otherwise =
w
& ExpressionGui.scale (realToFrac ratio)
& ExpressionGui.egAlignment . _2 .~ 0.5
in result
make :: Monad m => ExprGuiT.SugarExpr m -> ExprGuiM m (ExpressionGui m)
make sExpr =
maybeShrink <*> makeEditor body pl
& assignCursor
where
Sugar.Expression body pl = sExpr
exprHiddenEntityIds =
List.delete (pl ^. Sugar.plEntityId)
(pl ^. Sugar.plData ^. ExprGuiT.plStoredEntityIds)
myId = WidgetIds.fromExprPayload pl
maybeShrink
| or (pl ^. Sugar.plData ^. ExprGuiT.plInjected) = shrinkIfHigherThanLine
| otherwise = pure id
assignCursor x =
foldr (`ExprGuiM.assignCursorPrefix` const myId) x $
exprHiddenEntityIds <&> WidgetIds.fromEntityId
makeEditor ::
Monad m =>
Sugar.Body (Name m) m (ExprGuiT.SugarExpr m) ->
Sugar.Payload m ExprGuiT.Payload ->
ExprGuiM m (ExpressionGui m)
makeEditor body =
case body of
Sugar.BodyHole x -> x & HoleEdit.make
Sugar.BodyApply x -> x & ApplyEdit.make
Sugar.BodyLam x -> x & LambdaEdit.make
Sugar.BodyLiteral x -> x & LiteralEdit.make
Sugar.BodyRecord x -> x & RecordEdit.make
Sugar.BodyCase x -> x & CaseEdit.make
Sugar.BodyGetField x -> x & GetFieldEdit.make
Sugar.BodyInject x -> x & InjectEdit.make
Sugar.BodyGetVar x -> x & GetVarEdit.make
Sugar.BodyToNom x -> x & NomEdit.makeToNom
Sugar.BodyFromNom x -> x & NomEdit.makeFromNom
| da-x/lamdu | Lamdu/GUI/ExpressionEdit.hs | gpl-3.0 | 3,900 | 0 | 20 | 960 | 925 | 525 | 400 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, FlexibleContexts, TypeSynonymInstances,
ScopedTypeVariables, OverloadedStrings, NoMonomorphismRestriction #-}
-----------------------------------------------------------------------------
-- |
-- Module : HEP.Parser.LHE.Sanitizer
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Main routine for parsing and processing (sanitizing) LHE file.
--
-----------------------------------------------------------------------------
module HEP.Parser.LHE.Sanitizer where
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Digest.Pure.MD5
import System.FilePath
import System.Directory
import System.IO
import System.Random
-- from this package
import HEP.Parser.LHE.Sanitizer.Action
import HEP.Parser.LHE.Sanitizer.Type
--
import Prelude hiding (dropWhile,takeWhile,sequence)
withRandomTempFile :: (FilePath -> IO ()) -> IO ()
withRandomTempFile act = do
tdir <- getTemporaryDirectory
r <- randomIO :: IO Int
let tmpfile = (tdir </>) . show . md5 . B.pack . show $ r
act tmpfile
removeFile tmpfile
-- | sanitize LHE file for one particular order
sanitize1 :: SanitizeCmd -> FilePath -> FilePath -> IO ()
sanitize1 (Eliminate pids) ifp ofp = eliminate pids ifp ofp
sanitize1 (Replace rpidtable) ifp ofp = replace rpidtable ifp ofp
sanitize1 Shuffle ifp ofp = shuffle ifp ofp
sanitize1 Blobize ifp ofp = blobize ifp ofp
-- | sanitize LHE file for a given order of sanitizing steps
sanitize :: [SanitizeCmd] -> FilePath -> FilePath -> IO ()
sanitize [] _ _ = return ()
sanitize (x:[]) ifp ofp = sanitize1 x ifp ofp
sanitize (x:xs) ifp ofp = withRandomTempFile $ \tmp -> sanitize1 x ifp tmp >> sanitize xs tmp ofp
| wavewave/LHE-sanitizer | src/HEP/Parser/LHE/Sanitizer.hs | gpl-3.0 | 1,895 | 0 | 15 | 373 | 419 | 229 | 190 | 28 | 1 |
{-# LANGUAGE ViewPatterns, OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
module VSim.Data.NamePath (
Ident
, NamePathElem
) where
import Data.Typeable
import Data.Generics
import Data.Bits (xor)
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe
import Control.Monad
import System.IO
import Data.Char
import Data.Int
bsToFs = id
fsToBs = id
type Ident = B.ByteString
type OverloadIndex = Integer
-- | Элемент пути к имени, используется при выводе деревьев значений
-- для отладчика и при генерации статических имен.
data NamePathElem
= NPELibrary Ident
| NPEFile Ident
| NPEPackage Ident
| NPEEntity Ident
| NPEProcess Ident
| NPEFunction OverloadIndex Ident
-- | NPEProcedure Ident -- OverloadIndex
| NPEType Ident
| NPEIdent NamedItemKind Ident
| NPEIndex [B.ByteString]
-- ^ не ident, чтобы не засирать таблицу с атомами
| NPESlice B.ByteString
| NPEField Ident
| NPEDeref
| NPECIndex [B.ByteString]
| NPECDeref
-- | Дополнительный идентификатор в имени, делающий его
-- уникальным. Используется в UI (чтобы одна и та же ф-ия на
-- разной глубине callStack-а была разной, возможно, где-нить
-- еще пригодится)
| NPEId B.ByteString NamePathElem
deriving (Show, Eq, Ord, Data, Typeable)
isProcessRevPath (stripNPEIds -> (NPEProcess _ : _)) = True
isProcessRevPath _ = False
isConstantRevPath = isJust . find c . stripNPEIds
where c (NPEIdent nik _) = skipAliases nik == NIKConstant
c _ = False
stripNPEIds [] = []
stripNPEIds (NPEId _ pe : pes) = stripNPEIds (pe : pes)
stripNPEIds (pe : pes) = pe : stripNPEIds pes
-- | Путь к имени, записывается задом наперед для удобства дальнейшей
-- работы (ну и, мимоходом, шарятся префиксы)
type RevNamePath = [NamePathElem]
data NamedItemKind
= NIKConstant
| NIKVariable
| NIKSignal
| NIKFile
| NIKAlias NamedItemKind
deriving (Show, Eq, Ord, Data, Typeable)
niKindToString nik = case nik of
NIKConstant -> "constant"
NIKVariable -> "variable"
NIKSignal -> "signal"
NIKFile -> "file"
NIKAlias anik -> niKindToString anik ++ " alias"
skipAliases (NIKAlias a) = skipAliases a
skipAliases n = n
| grwlf/vsim | src/VSim/Data/NamePath.hs | gpl-3.0 | 2,619 | 0 | 10 | 503 | 504 | 283 | 221 | 60 | 5 |
-- Exercício 02: Crie uma função projectEuler5 que retorna o primeiro número natural que retorna True para a função do exercício anterior. Pense em como reduzir o custo computacional.
divisivel20 :: Integer -> Bool
divisivel20 x = dividir x 20
dividir :: Integer -> Integer -> Bool
dividir x y
| y == 1 = True
| x `mod` y /= 0 = False
| otherwise = dividir x (y-1)
main = do
print(divisivel20(foldl lcm 1 [1..20]))
| danielgoncalvesti/BIGDATA2017 | Atividade01/Haskell/Activity1/Exercises3/Ex2.hs | gpl-3.0 | 462 | 0 | 12 | 117 | 129 | 64 | 65 | 9 | 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.GAN.Links.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves data about a single link if the requesting
-- advertiser\/publisher has access to it. Advertisers can look up their
-- own links. Publishers can look up visible links or links belonging to
-- advertisers they are in a relationship with.
--
-- /See:/ <https://developers.google.com/affiliate-network/ Google Affiliate Network API Reference> for @gan.links.get@.
module Network.Google.Resource.GAN.Links.Get
(
-- * REST Resource
LinksGetResource
-- * Creating a Request
, linksGet
, LinksGet
-- * Request Lenses
, lgRoleId
, lgRole
, lgLinkId
) where
import Network.Google.Affiliates.Types
import Network.Google.Prelude
-- | A resource alias for @gan.links.get@ method which the
-- 'LinksGet' request conforms to.
type LinksGetResource =
"gan" :>
"v1beta1" :>
Capture "role" LinksGetRole :>
Capture "roleId" Text :>
"link" :>
Capture "linkId" (Textual Int64) :>
QueryParam "alt" AltJSON :> Get '[JSON] Link
-- | Retrieves data about a single link if the requesting
-- advertiser\/publisher has access to it. Advertisers can look up their
-- own links. Publishers can look up visible links or links belonging to
-- advertisers they are in a relationship with.
--
-- /See:/ 'linksGet' smart constructor.
data LinksGet = LinksGet'
{ _lgRoleId :: !Text
, _lgRole :: !LinksGetRole
, _lgLinkId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LinksGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lgRoleId'
--
-- * 'lgRole'
--
-- * 'lgLinkId'
linksGet
:: Text -- ^ 'lgRoleId'
-> LinksGetRole -- ^ 'lgRole'
-> Int64 -- ^ 'lgLinkId'
-> LinksGet
linksGet pLgRoleId_ pLgRole_ pLgLinkId_ =
LinksGet'
{ _lgRoleId = pLgRoleId_
, _lgRole = pLgRole_
, _lgLinkId = _Coerce # pLgLinkId_
}
-- | The ID of the requesting advertiser or publisher.
lgRoleId :: Lens' LinksGet Text
lgRoleId = lens _lgRoleId (\ s a -> s{_lgRoleId = a})
-- | The role of the requester. Valid values: \'advertisers\' or
-- \'publishers\'.
lgRole :: Lens' LinksGet LinksGetRole
lgRole = lens _lgRole (\ s a -> s{_lgRole = a})
-- | The ID of the link to look up.
lgLinkId :: Lens' LinksGet Int64
lgLinkId
= lens _lgLinkId (\ s a -> s{_lgLinkId = a}) .
_Coerce
instance GoogleRequest LinksGet where
type Rs LinksGet = Link
type Scopes LinksGet = '[]
requestClient LinksGet'{..}
= go _lgRole _lgRoleId _lgLinkId (Just AltJSON)
affiliatesService
where go
= buildClient (Proxy :: Proxy LinksGetResource)
mempty
| rueshyna/gogol | gogol-affiliates/gen/Network/Google/Resource/GAN/Links/Get.hs | mpl-2.0 | 3,575 | 0 | 14 | 850 | 478 | 286 | 192 | 68 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.CreateAccessKey
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new AWS secret access key and corresponding AWS access key ID
-- for the specified user. The default status for new keys is 'Active'.
--
-- If you do not specify a user name, IAM determines the user name
-- implicitly based on the AWS access key ID signing the request. Because
-- this action works for access keys under the AWS account, you can use
-- this action to manage root credentials even if the AWS account has no
-- associated users.
--
-- For information about limits on the number of keys you can create, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities>
-- in the /Using IAM/ guide.
--
-- To ensure the security of your AWS account, the secret access key is
-- accessible only during key and user creation. You must save the key (for
-- example, in a text file) if you want to be able to access it again. If a
-- secret key is lost, you can delete the access keys for the associated
-- user and then create new keys.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html AWS API Reference> for CreateAccessKey.
module Network.AWS.IAM.CreateAccessKey
(
-- * Creating a Request
createAccessKey
, CreateAccessKey
-- * Request Lenses
, cakUserName
-- * Destructuring the Response
, createAccessKeyResponse
, CreateAccessKeyResponse
-- * Response Lenses
, cakrsResponseStatus
, cakrsAccessKey
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createAccessKey' smart constructor.
newtype CreateAccessKey = CreateAccessKey'
{ _cakUserName :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateAccessKey' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cakUserName'
createAccessKey
:: CreateAccessKey
createAccessKey =
CreateAccessKey'
{ _cakUserName = Nothing
}
-- | The user name that the new key will belong to.
cakUserName :: Lens' CreateAccessKey (Maybe Text)
cakUserName = lens _cakUserName (\ s a -> s{_cakUserName = a});
instance AWSRequest CreateAccessKey where
type Rs CreateAccessKey = CreateAccessKeyResponse
request = postQuery iAM
response
= receiveXMLWrapper "CreateAccessKeyResult"
(\ s h x ->
CreateAccessKeyResponse' <$>
(pure (fromEnum s)) <*> (x .@ "AccessKey"))
instance ToHeaders CreateAccessKey where
toHeaders = const mempty
instance ToPath CreateAccessKey where
toPath = const "/"
instance ToQuery CreateAccessKey where
toQuery CreateAccessKey'{..}
= mconcat
["Action" =: ("CreateAccessKey" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"UserName" =: _cakUserName]
-- | Contains the response to a successful CreateAccessKey request.
--
-- /See:/ 'createAccessKeyResponse' smart constructor.
data CreateAccessKeyResponse = CreateAccessKeyResponse'
{ _cakrsResponseStatus :: !Int
, _cakrsAccessKey :: !AccessKey
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateAccessKeyResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cakrsResponseStatus'
--
-- * 'cakrsAccessKey'
createAccessKeyResponse
:: Int -- ^ 'cakrsResponseStatus'
-> AccessKey -- ^ 'cakrsAccessKey'
-> CreateAccessKeyResponse
createAccessKeyResponse pResponseStatus_ pAccessKey_ =
CreateAccessKeyResponse'
{ _cakrsResponseStatus = pResponseStatus_
, _cakrsAccessKey = pAccessKey_
}
-- | The response status code.
cakrsResponseStatus :: Lens' CreateAccessKeyResponse Int
cakrsResponseStatus = lens _cakrsResponseStatus (\ s a -> s{_cakrsResponseStatus = a});
-- | Information about the access key.
cakrsAccessKey :: Lens' CreateAccessKeyResponse AccessKey
cakrsAccessKey = lens _cakrsAccessKey (\ s a -> s{_cakrsAccessKey = a});
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/CreateAccessKey.hs | mpl-2.0 | 4,926 | 0 | 14 | 999 | 561 | 345 | 216 | 70 | 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.Gmail.Users.Settings.GetPop
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets POP settings.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.getPop@.
module Network.Google.Resource.Gmail.Users.Settings.GetPop
(
-- * REST Resource
UsersSettingsGetPopResource
-- * Creating a Request
, usersSettingsGetPop
, UsersSettingsGetPop
-- * Request Lenses
, usgpXgafv
, usgpUploadProtocol
, usgpAccessToken
, usgpUploadType
, usgpUserId
, usgpCallback
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.settings.getPop@ method which the
-- 'UsersSettingsGetPop' request conforms to.
type UsersSettingsGetPopResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"settings" :>
"pop" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] PopSettings
-- | Gets POP settings.
--
-- /See:/ 'usersSettingsGetPop' smart constructor.
data UsersSettingsGetPop =
UsersSettingsGetPop'
{ _usgpXgafv :: !(Maybe Xgafv)
, _usgpUploadProtocol :: !(Maybe Text)
, _usgpAccessToken :: !(Maybe Text)
, _usgpUploadType :: !(Maybe Text)
, _usgpUserId :: !Text
, _usgpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersSettingsGetPop' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usgpXgafv'
--
-- * 'usgpUploadProtocol'
--
-- * 'usgpAccessToken'
--
-- * 'usgpUploadType'
--
-- * 'usgpUserId'
--
-- * 'usgpCallback'
usersSettingsGetPop
:: UsersSettingsGetPop
usersSettingsGetPop =
UsersSettingsGetPop'
{ _usgpXgafv = Nothing
, _usgpUploadProtocol = Nothing
, _usgpAccessToken = Nothing
, _usgpUploadType = Nothing
, _usgpUserId = "me"
, _usgpCallback = Nothing
}
-- | V1 error format.
usgpXgafv :: Lens' UsersSettingsGetPop (Maybe Xgafv)
usgpXgafv
= lens _usgpXgafv (\ s a -> s{_usgpXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
usgpUploadProtocol :: Lens' UsersSettingsGetPop (Maybe Text)
usgpUploadProtocol
= lens _usgpUploadProtocol
(\ s a -> s{_usgpUploadProtocol = a})
-- | OAuth access token.
usgpAccessToken :: Lens' UsersSettingsGetPop (Maybe Text)
usgpAccessToken
= lens _usgpAccessToken
(\ s a -> s{_usgpAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
usgpUploadType :: Lens' UsersSettingsGetPop (Maybe Text)
usgpUploadType
= lens _usgpUploadType
(\ s a -> s{_usgpUploadType = a})
-- | User\'s email address. The special value \"me\" can be used to indicate
-- the authenticated user.
usgpUserId :: Lens' UsersSettingsGetPop Text
usgpUserId
= lens _usgpUserId (\ s a -> s{_usgpUserId = a})
-- | JSONP
usgpCallback :: Lens' UsersSettingsGetPop (Maybe Text)
usgpCallback
= lens _usgpCallback (\ s a -> s{_usgpCallback = a})
instance GoogleRequest UsersSettingsGetPop where
type Rs UsersSettingsGetPop = PopSettings
type Scopes UsersSettingsGetPop =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.settings.basic"]
requestClient UsersSettingsGetPop'{..}
= go _usgpUserId _usgpXgafv _usgpUploadProtocol
_usgpAccessToken
_usgpUploadType
_usgpCallback
(Just AltJSON)
gmailService
where go
= buildClient
(Proxy :: Proxy UsersSettingsGetPopResource)
mempty
| brendanhay/gogol | gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/GetPop.hs | mpl-2.0 | 4,828 | 0 | 19 | 1,173 | 713 | 417 | 296 | 108 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Model.Excerpt.SQL
( selectAssetSlotExcerpt
, selectContainerExcerpt
, selectVolumeExcerpt
, insertExcerpt
, updateExcerpt
, deleteExcerpt
) where
import qualified Language.Haskell.TH as TH
import Model.SQL.Select
import Model.Audit.SQL
import Model.Release.Types
import Model.Volume.Types
import Model.Container.Types
import Model.Container.SQL
import Model.Segment
import Model.Asset.Types
import Model.Asset.SQL
import Model.AssetSlot.Types
import Model.AssetSlot.SQL
import Model.AssetSegment.Types
makeExcerpt :: Segment -> Maybe Release -> AssetSlot -> Excerpt
makeExcerpt s r a = newExcerpt a s r
excerptRow :: Selector -- ^ @'AssetSlot' -> 'Excerpt'@
excerptRow = selectColumns 'makeExcerpt "excerpt" ["segment", "release"]
selectAssetSlotExcerpt :: Selector -- ^ @'AssetSlot' -> 'Excerpt'@
selectAssetSlotExcerpt = excerptRow
makeAssetContainerExcerpt :: Segment -> (AssetSlot -> Excerpt) -> Asset -> Container -> Excerpt
makeAssetContainerExcerpt as e a c = e $ makeSlotAsset a c as
selectAssetContainerExcerpt :: Selector -- ^ @'Asset' -> 'Container' -> 'Excerpt'@
selectAssetContainerExcerpt = selectJoin 'makeAssetContainerExcerpt
[ slotAssetRow
, joinOn "slot_asset.asset = excerpt.asset"
excerptRow
]
makeContainerExcerpt :: (Asset -> Container -> Excerpt) -> AssetRow -> Container -> Excerpt
makeContainerExcerpt f ar c = f (Asset ar (containerVolume c)) c
selectContainerExcerpt :: Selector -- ^ @'Container' -> 'Excerpt'@
selectContainerExcerpt = selectJoin 'makeContainerExcerpt
[ selectAssetContainerExcerpt
, joinOn "slot_asset.asset = asset.id"
selectAssetRow -- XXX volumes match?
]
makeVolumeExcerpt :: (Asset -> Container -> Excerpt) -> AssetRow -> (Volume -> Container) -> Volume -> Excerpt
makeVolumeExcerpt f ar cf v = f (Asset ar v) (cf v)
selectVolumeExcerpt :: Selector -- ^ @'Volume' -> 'Excerpt'@
selectVolumeExcerpt = selectJoin 'makeVolumeExcerpt
[ selectAssetContainerExcerpt
, joinOn "slot_asset.asset = asset.id"
selectAssetRow
, joinOn "slot_asset.container = container.id AND asset.volume = container.volume"
selectVolumeContainer
]
excerptKeys :: String -- ^ @'Excerpt'@
-> [(String, String)]
excerptKeys o =
[ ("asset", "${assetId $ assetRow $ slotAsset $ segmentAsset $ excerptAsset " ++ o ++ "}")
, ("segment", "${assetSegment $ excerptAsset " ++ o ++ "}")
]
excerptSets :: String -- ^ @'Excerpt'@
-> [(String, String)]
excerptSets o =
[ ("release", "${excerptRelease " ++ o ++ "}")
]
insertExcerpt :: TH.Name -- ^ @'AuditIdentity'@
-> TH.Name -- ^ @'Excerpt'@
-> TH.ExpQ
insertExcerpt ident o = auditInsert ident "excerpt"
(excerptKeys os ++ excerptSets os)
Nothing
where os = nameRef o
updateExcerpt :: TH.Name -- ^ @'AuditIdentity'@
-> TH.Name -- ^ @'Excerpt'@
-> TH.ExpQ
updateExcerpt ident o = auditUpdate ident "excerpt"
(excerptSets os)
(whereEq $ excerptKeys os)
Nothing
where os = nameRef o
deleteExcerpt :: TH.Name -- ^ @'AuditIdentity'@
-> TH.Name -- ^ @'AssetSegment'@
-> TH.ExpQ
deleteExcerpt ident o = auditDelete ident "excerpt"
("asset = ${assetId $ assetRow $ slotAsset $ segmentAsset " ++ os ++ "} AND segment <@ ${assetSegment " ++ os ++ "}")
Nothing
where os = nameRef o
| databrary/databrary | src/Model/Excerpt/SQL.hs | agpl-3.0 | 3,286 | 0 | 10 | 535 | 765 | 426 | 339 | 81 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | A minimal wrapper for libgirepository.
module Data.GI.CodeGen.LibGIRepository
( girRequire
, setupTypelibSearchPath
, FieldInfo(..)
, girStructFieldInfo
, girUnionFieldInfo
, girLoadGType
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Control.Monad (forM, when, (>=>))
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text as T
import Foreign.C.Types (CInt(..), CSize(..))
import Foreign.C.String (CString, withCString)
import Foreign (nullPtr, Ptr, FunPtr, peek)
import System.Environment (lookupEnv)
import System.FilePath (searchPathSeparator)
import Data.GI.Base.BasicConversions (withTextCString, cstringToText)
import Data.GI.Base.BasicTypes (BoxedObject(..), GType(..), CGType, ManagedPtr)
import Data.GI.Base.GError (GError, checkGError)
import Data.GI.Base.ManagedPtr (wrapBoxed, withManagedPtr)
import Data.GI.Base.Utils (allocMem, freeMem)
import Data.GI.CodeGen.Util (splitOn)
-- | Wrapper for 'GIBaseInfo'
newtype BaseInfo = BaseInfo (ManagedPtr BaseInfo)
-- | Wrapper for 'GITypelib'
newtype Typelib = Typelib (Ptr Typelib)
-- | Extra info about a field in a struct or union which is not easily
-- determined from the GIR file. (And which we determine by using
-- libgirepository.)
data FieldInfo = FieldInfo {
fieldInfoOffset :: Int
}
foreign import ccall "g_base_info_gtype_get_type" c_g_base_info_gtype_get_type :: IO GType
instance BoxedObject BaseInfo where
boxedType _ = c_g_base_info_gtype_get_type
foreign import ccall "g_irepository_prepend_search_path" g_irepository_prepend_search_path :: CString -> IO ()
-- | Add the given directory to the typelib search path, this is a
-- thin wrapper over `g_irepository_prepend_search_path`.
girPrependSearchPath :: FilePath -> IO ()
girPrependSearchPath fp = withCString fp g_irepository_prepend_search_path
foreign import ccall "g_irepository_require" g_irepository_require ::
Ptr () -> CString -> CString -> CInt -> Ptr (Ptr GError)
-> IO (Ptr Typelib)
-- | A convenience function for setting up the typelib search path
-- from the environment. Note that for efficiency reasons this should
-- only be called once per program run. If the list of paths passed in
-- is empty, the environment variable @HASKELL_GI_TYPELIB_SEARCH_PATH@
-- will be checked. In either case the system directories will be
-- searched after the passed in directories.
setupTypelibSearchPath :: [FilePath] -> IO ()
setupTypelibSearchPath [] = do
env <- lookupEnv "HASKELL_GI_TYPELIB_SEARCH_PATH"
case env of
Nothing -> return ()
Just paths -> mapM_ girPrependSearchPath (splitOn searchPathSeparator paths)
setupTypelibSearchPath paths = mapM_ girPrependSearchPath paths
-- | Ensure that the given version of the namespace is loaded. If that
-- is not possible we error out.
girRequire :: Text -> Text -> IO Typelib
girRequire ns version =
withTextCString ns $ \cns ->
withTextCString version $ \cversion -> do
typelib <- checkGError (g_irepository_require nullPtr cns cversion 0)
(error $ "Could not load typelib for "
++ show ns ++ " version "
++ show version)
return (Typelib typelib)
foreign import ccall "g_irepository_find_by_name" g_irepository_find_by_name ::
Ptr () -> CString -> CString -> IO (Ptr BaseInfo)
-- | Find a given baseinfo by name, or give an error if it cannot be
-- found.
girFindByName :: Text -> Text -> IO BaseInfo
girFindByName ns name =
withTextCString ns $ \cns ->
withTextCString name $ \cname -> do
ptr <- g_irepository_find_by_name nullPtr cns cname
if ptr == nullPtr
then error ("Could not find " ++ T.unpack ns ++ "::" ++ T.unpack name)
else wrapBoxed BaseInfo ptr
foreign import ccall "g_field_info_get_offset" g_field_info_get_offset ::
Ptr BaseInfo -> IO CInt
foreign import ccall "g_base_info_get_name" g_base_info_get_name ::
Ptr BaseInfo -> IO CString
-- | Get the extra information for the given field.
getFieldInfo :: BaseInfo -> IO (Text, FieldInfo)
getFieldInfo field = withManagedPtr field $ \fi -> do
fname <- (g_base_info_get_name fi >>= cstringToText)
fOffset <- g_field_info_get_offset fi
return (fname, FieldInfo { fieldInfoOffset = fromIntegral fOffset })
foreign import ccall "g_struct_info_get_size" g_struct_info_get_size ::
Ptr BaseInfo -> IO CSize
foreign import ccall "g_struct_info_get_n_fields" g_struct_info_get_n_fields ::
Ptr BaseInfo -> IO CInt
foreign import ccall "g_struct_info_get_field" g_struct_info_get_field ::
Ptr BaseInfo -> CInt -> IO (Ptr BaseInfo)
-- | Find out the size of a struct, and the map from field names to
-- offsets inside the struct.
girStructFieldInfo :: Text -> Text -> IO (Int, M.Map Text FieldInfo)
girStructFieldInfo ns name = do
baseinfo <- girFindByName ns name
withManagedPtr baseinfo $ \si -> do
size <- g_struct_info_get_size si
nfields <- g_struct_info_get_n_fields si
fieldInfos <- forM [0..(nfields-1)]
(g_struct_info_get_field si >=> wrapBoxed BaseInfo >=> getFieldInfo)
return (fromIntegral size, M.fromList fieldInfos)
foreign import ccall "g_union_info_get_size" g_union_info_get_size ::
Ptr BaseInfo -> IO CSize
foreign import ccall "g_union_info_get_n_fields" g_union_info_get_n_fields ::
Ptr BaseInfo -> IO CInt
foreign import ccall "g_union_info_get_field" g_union_info_get_field ::
Ptr BaseInfo -> CInt -> IO (Ptr BaseInfo)
-- | Find out the size of a union, and the map from field names to
-- offsets inside the union.
girUnionFieldInfo :: Text -> Text -> IO (Int, M.Map Text FieldInfo)
girUnionFieldInfo ns name = do
baseinfo <- girFindByName ns name
withManagedPtr baseinfo $ \ui -> do
size <- g_union_info_get_size ui
nfields <- g_union_info_get_n_fields ui
fieldInfos <- forM [0..(nfields-1)] (
g_union_info_get_field ui >=> wrapBoxed BaseInfo >=> getFieldInfo)
return (fromIntegral size, M.fromList fieldInfos)
foreign import ccall "g_typelib_symbol" g_typelib_symbol ::
Ptr Typelib -> CString -> Ptr (FunPtr a) -> IO CInt
-- | Load a symbol from the dynamic library associated to the given namespace.
girSymbol :: forall a. Text -> Text -> IO (FunPtr a)
girSymbol ns symbol = do
typelib <- withTextCString ns $ \cns ->
checkGError (g_irepository_require nullPtr cns nullPtr 0)
(error $ "Could not load typelib " ++ show ns)
funPtrPtr <- allocMem :: IO (Ptr (FunPtr a))
result <- withTextCString symbol $ \csymbol ->
g_typelib_symbol typelib csymbol funPtrPtr
when (result /= 1) $
error ("Could not resolve symbol " ++ show symbol ++ " in namespace "
++ show ns)
funPtr <- peek funPtrPtr
freeMem funPtrPtr
return funPtr
type GTypeInit = IO CGType
foreign import ccall "dynamic" gtypeInit :: FunPtr GTypeInit -> GTypeInit
-- | Load a GType given the namespace where it lives and the type init
-- function.
girLoadGType :: Text -> Text -> IO GType
girLoadGType ns typeInit = do
funPtr <- girSymbol ns typeInit
GType <$> gtypeInit funPtr
| ford-prefect/haskell-gi | lib/Data/GI/CodeGen/LibGIRepository.hs | lgpl-2.1 | 7,302 | 0 | 18 | 1,451 | 1,713 | 894 | 819 | 124 | 2 |
x = 2 -- глобальное связывание
y = 42
foo = let z = x + y -- глобальное (foo) локальное (z)
s = z * z
in print s -- отступ (layout rule)
--oops = print 1 + 2
printThree = print (1 + 2)
z = 1 -- ok, связали
-- z = 2 -- ошибка
q q = \ q -> q -- ok, но...
factorial n = if n > 1
then n * factorial (n-1)
else 1
-- where
factorial'' n' = helper 1 n'
where helper acc n = if n > 1
then helper (acc * n) (n - 1)
else acc
cube x = x * square x
where
square = (^2)
-- let in
factorial''' n' =
let helper acc n = if n > 1
then helper (acc * n) (n - 1)
else acc
in helper 1 n'
-- guard
factorial'''' :: Integer -> Integer
factorial'''' n' = helper 1 n'
where helper acc n | n > 1 = helper (acc * n) (n - 1)
| otherwise = acc
--int gcd(int a, int b) {
-- while (b) {
-- int tmp = a;
-- a = b;
-- b = tmp % b
-- }
-- return a;
--}
--int gcd(int a, int b) {
-- return b == 0 ? a : gcd(b, a % b);
--}
-- pattern matching
gcd' a 0 = a
gcd' a b = gcd' b (mod a b)
whoami [] = []
whoami [x] = [x]
whoami (x : _ : xs) = x : (whoami xs)
-- lazy
k = \ x y -> x
lazyWow = print $ k 42 undefined
-- 2a. Написать функцию, возвращающую количество цифр числа.
-- Для целочисленного деления можете использовать функции div и mod.
toDigits :: Int -> [Int]
toDigits = undefined
numberOfDigits :: Int -> Int
numberOfDigits = undefined
-- 2b. Написать функцию, возвращающую сумму цифр числа.
sumOfDigits :: Int -> Int
sumOfDigits = undefined
-- operator
f --> a = f a
infixl 5 -->
index :: Int -> [Int] -> Int
index k l = let
helper [] _ = -1
helper (x:xs) i | x == k = i
| otherwise = helper xs (i + 1)
in helper l 0
-- Determine if list l is a palindrome
isPalindrome l = undefined
{-
- Duplicate the elements in list xs, for example "duplicate [1,2,3]" would give the list [1,1,2,2,3,3]
- Hint: The "concat [l]" function flattens a list of lists into a single list.
- (You can see the function definition by typing ":t concat" into the interpreter. Perhaps try this with other variables and functions)
-
- For example: concat [[1,2,3],[3,4,5]] returns [1,2,3,3,4,5]
-}
duplicate xs = undefined
{-
- Imitate the functinality of zip
- The function "min x y" returns the lower of values x and y
- For example "ziplike [1,2,3] ['a', 'b', 'c', 'd']" returns [(1,'a'), (2, 'b'), (3, 'c')]
-}
ziplike xs ys = undefined
-- Split a list l at element k into a tuple: The first part up to and including k, the second part after k
-- For example "splitAtIndex 3 [1,1,1,2,2,2]" returns ([1,1,1],[2,2,2])
splitAtIndex k l = undefined
-- Insert element x in list l at index k
-- For example, "insertElem 2 5 [0,0,0,0,0,0]" returns [0,0,0,0,0,2,0]
insertElem x k l = undefined
-- Rotate list l n places left.
-- For example, "rotate 2 [1,2,3,4,5]" gives [3,4,5,1,2]
rotate n l = undefined
main = do
print (factorial'''' 5)
lazyWow
putStrLn "hello, haskell"
| SPbAU-ProgrammingParadigms/materials | haskell_1/hello.hs | unlicense | 3,439 | 0 | 12 | 1,024 | 721 | 384 | 337 | 57 | 2 |
module Main where
import Network.MicrosoftAzure.ACS
import Network.HTTP.Conduit
import Network.HTTP.Client.Conduit
import Network.Connection (TLSSettings (..))
import qualified Data.ByteString.Char8 as C
import Control.Concurrent
acsNS = "XXXX"
issuerKey = C.pack "YYYYYYYYYYYYYYYYYYYYYYY=="
issuerName = C.pack "owner"
relyingPartyUrl = C.pack "http://XXXX.servicebus.windows.net"
main = do
acsCtx <- acsContext (AcsInfo acsNS relyingPartyUrl issuerName issuerKey)
manager <- newManagerSettings (mkManagerSettings (TLSSettingsSimple True False False) Nothing)
forkIO (acsToken manager acsCtx >>= print)
t1 <- acsToken manager acsCtx
print t1
| kapilash/hs-azure | azure-acs/examples/Example.hs | apache-2.0 | 687 | 0 | 12 | 112 | 177 | 94 | 83 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module GhWeekly.Report
( renderObject
, renderCommits
, renderIssues
) where
import Control.Applicative
import Control.Arrow
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens
import Data.Foldable
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Data.Text.Buildable
import qualified Data.Text.Format as F
import qualified Data.Text.Lazy as TL
import Data.Text.Lazy.Builder
import qualified Data.Vector as V
import Prelude hiding (foldr)
import Text.Blaze.Html5
-- import qualified Text.Blaze.Html5 as H
-- import qualified Text.Blaze.Html5.Attributes as A
import GhWeekly.Lens
import GhWeekly.Types
renderObject :: T.Text -> [Value] -> [Value] -> T.Text
renderObject repoName commits issues = TL.toStrict . toLazyText $
header <> renderCommits repoName commits <> renderIssues repoName issues
where
header = F.build "# {}\n\n" $ F.Only repoName
renderCommits :: T.Text -> [Value] -> Builder
renderCommits _ [] = mempty
renderCommits repo commits =
header <> foldr renderCommit "\n" commits <> footer
where
renderCommit v =
mappend (foldMap rc $ (,) <$> v ^? commit . author . date . _String
<*> v ^? commit . message . _String)
rc (d, m) = F.build "[{}] {}\n" (d, firstLine m)
firstLine = fromMaybe T.empty . listToMaybe . T.lines
sumOn prism = maybe mempty Sum . preview prism
fileCount = key "files" . _Array . to V.length
lineCount = key "stats" . key "total" . _Number
(Sum files, Sum lines) =
foldMap (sumOn fileCount &&& sumOn lineCount) commits
padS = F.left 5 ' ' . F.Shown
header = "## Commits\n\n"
footer = F.build "{} commits.\n{} files.\n{} lines.\n\n"
(padS $ length commits, padS files, padS $ round lines)
renderIssues :: T.Text -> [Value] -> Builder
renderIssues _ [] = mempty
renderIssues repo issues =
header <> foldr renderIssue "\n" issues' <> footer
where
issues' = V.concat $ issues ^.. traverse . key "items" . _Array
renderIssue :: Value -> Builder -> Builder
renderIssue i = mappend (renderIssue' i)
renderIssue' i =
F.build "#{}: [{}] {}\n"
( F.Shown . fromMaybe ((-1) :: Int) $ i ^? key "number" . _Integral
, state $ i ^? key "state" . _String
, fromMaybe "<Untitled>" $ i ^? key "title" . _String
)
state :: Maybe T.Text -> Builder
state (Just "open") = " "
state (Just "closed") = "*"
state Nothing = "?"
header = "## Issues\n\n"
footer = F.build "{} issues.\n\n" . F.Only $ V.length issues'
| erochest/gh-weekly | src/GhWeekly/Report.hs | apache-2.0 | 2,998 | 0 | 19 | 979 | 830 | 438 | 392 | -1 | -1 |
-- Copyright (c) 2013-2014 PivotCloud, Inc.
--
-- Aws.DynamoDb.Streams.Commands.GetRecords
--
-- Please feel free to contact us at [email protected] with any
-- contributions, additions, or other feedback; we would love to hear from
-- you.
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may
-- not use this file except in compliance with the License. You may obtain a
-- copy of the License at http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations
-- under the License.
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UnicodeSyntax #-}
-- |
-- Copyright: Copyright (c) 2013-2014 PivotCloud, Inc.
-- License: Apache-2.0
--
module Aws.DynamoDb.Streams.Commands.GetRecords
( -- * Request
GetRecords(..)
, getRecords
-- ** Lenses
, grShardIterator
, grLimit
-- * Response
, GetRecordsResponse(..)
-- ** Lenses
, grrRecords
, grrNextShardIterator
) where
import Aws.Core
import Aws.DynamoDb.Streams.Core
import Aws.DynamoDb.Streams.Types
import Control.Applicative
import Control.Applicative.Unicode
import Data.Aeson
import Data.Typeable
data GetRecords
= GetRecords
{ _grShardIterator ∷ !ShardIterator
, _grLimit ∷ !(Maybe Int)
} deriving (Eq, Ord, Show, Read, Typeable)
-- | A basic 'GetRecords' request for a given shard iterator.
--
-- @
-- myRequest = getRecords it & grLimit ?~ 42
-- @
--
getRecords
∷ ShardIterator
→ GetRecords
getRecords it = GetRecords
{ _grShardIterator = it
, _grLimit = Nothing
}
instance ToJSON GetRecords where
toJSON GetRecords{..} = object
[ "ShardIterator" .= _grShardIterator
, "Limit" .= _grLimit
]
instance FromJSON GetRecords where
parseJSON =
withObject "GetRecords" $ \o →
pure GetRecords
⊛ o .: "ShardIterator"
⊛ o .:? "Limit"
-- | A lens for '_grShardIterator'.
--
-- @
-- grShardIterator ∷ Lens' 'GetRecords' 'ShardIterator'
-- @
--
grShardIterator
∷ Functor f
⇒ (ShardIterator → f ShardIterator)
→ GetRecords
→ f GetRecords
grShardIterator i GetRecords{..} =
(\_grShardIterator → GetRecords{..})
<$> i _grShardIterator
{-# INLINE grShardIterator #-}
-- | A lens for '_grLimit'.
--
-- @
-- grLimit ∷ Lens' 'GetRecords' ('Maybe' 'Int')
-- @
--
grLimit
∷ Functor f
⇒ (Maybe Int → f (Maybe Int))
→ GetRecords
→ f GetRecords
grLimit i GetRecords{..} =
(\_grLimit → GetRecords{..})
<$> i _grLimit
{-# INLINE grLimit #-}
data GetRecordsResponse
= GetRecordsResponse
{ _grrNextShardIterator ∷ !(Maybe ShardIterator)
, _grrRecords ∷ ![Record]
} deriving (Eq, Ord, Show, Read, Typeable)
instance ToJSON GetRecordsResponse where
toJSON GetRecordsResponse{..} = object
[ "NextShardIterator" .= _grrNextShardIterator
, "Records" .= _grrRecords
]
instance FromJSON GetRecordsResponse where
parseJSON =
withObject "GetRecordsResponse" $ \o →
pure GetRecordsResponse
⊛ o .:? "NextShardIterator"
⊛ o .: "Records"
-- | A lens for '_grrRecords'.
--
-- @
-- grrRecords ∷ Lens' 'GetRecordsResponse' ['Record']
-- @
--
grrRecords
∷ Functor f
⇒ ([Record] → f [Record])
→ GetRecordsResponse
→ f GetRecordsResponse
grrRecords i GetRecordsResponse{..} =
(\_grrRecords → GetRecordsResponse{..})
<$> i _grrRecords
{-# INLINE grrRecords #-}
-- | A lens for '_grrNextShardIterator'.
--
-- @
-- grrNextShardIterator ∷ Lens' 'GetRecordsResponse' ('Maybe' 'ShardIterator')
-- @
--
grrNextShardIterator
∷ Functor f
⇒ (Maybe ShardIterator → f (Maybe ShardIterator))
→ GetRecordsResponse
→ f GetRecordsResponse
grrNextShardIterator i GetRecordsResponse{..} =
(\_grrNextShardIterator → GetRecordsResponse{..})
<$> i _grrNextShardIterator
{-# INLINE grrNextShardIterator #-}
instance ResponseConsumer r GetRecordsResponse where
type ResponseMetadata GetRecordsResponse = StreamsMetadata
responseConsumer _ = streamsResponseConsumer
instance SignQuery GetRecords where
type ServiceConfiguration GetRecords = StreamsConfiguration
signQuery cmd = streamsSignQuery StreamsQuery
{ _stqAction = ActionGetRecords
, _stqBody = encode cmd
}
instance Transaction GetRecords GetRecordsResponse
instance AsMemoryResponse GetRecordsResponse where
type MemoryResponse GetRecordsResponse = GetRecordsResponse
loadToMemory = return
instance ListResponse GetRecordsResponse Record where
listResponse = _grrRecords
instance IteratedTransaction GetRecords GetRecordsResponse where
nextIteratedRequest req@GetRecords{..} GetRecordsResponse{..} = do
nextShardIterator ← _grrNextShardIterator
return req
{ _grShardIterator = nextShardIterator
}
| jonsterling/hs-aws-dynamodb-streams | src/Aws/DynamoDb/Streams/Commands/GetRecords.hs | apache-2.0 | 5,148 | 0 | 12 | 883 | 924 | 522 | 402 | 122 | 1 |
module Bugs.Bug9 (main) where
import Control.Applicative (empty)
import Control.Monad (void)
import Text.Megaparsec
import Text.Megaparsec.Expr
import Text.Megaparsec.String (Parser)
import qualified Text.Megaparsec.Lexer as L
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
import Util
data Expr = Const Integer | Op Expr Expr deriving Show
main :: Test
main =
testCase "Tracing of current position in error message (#9)"
$ result @?= ["unexpected '>'", "expecting end of input or operator"]
where
result :: [String]
result = parseErrors parseTopLevel "4 >> 5"
-- Syntax analysis
sc :: Parser ()
sc = L.space (void spaceChar) empty empty
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
integer :: Parser Integer
integer = lexeme L.integer
operator :: String -> Parser String
operator = try . L.symbol sc
parseTopLevel :: Parser Expr
parseTopLevel = parseExpr <* eof
parseExpr :: Parser Expr
parseExpr = makeExprParser (Const <$> integer) table
where table = [[ InfixL (Op <$ operator ">>>") ]]
| neongreen/megaparsec | old-tests/Bugs/Bug9.hs | bsd-2-clause | 1,073 | 0 | 12 | 184 | 322 | 180 | 142 | 31 | 1 |
-- | Create a large HTML table and dump it to a handle
--
-- Tested in this benchmark:
--
-- * Creating a large HTML document using a builder
--
-- * Writing to a handle
--
{-# LANGUAGE CPP, OverloadedStrings #-}
module Benchmarks.Programs.BigTable
( benchmark
) where
import Test.Tasty.Bench (Benchmark, bench, whnfIO)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (mconcat, mempty, mappend)
#endif
import Data.Text.Lazy.Builder (Builder, fromText, toLazyText)
import Data.Text.Lazy.IO (hPutStr)
import System.IO (Handle)
import qualified Data.Text as T
benchmark :: Handle -> Benchmark
benchmark sink = bench "BigTable" $ whnfIO $ do
hPutStr sink "Content-Type: text/html\n\n<table>"
hPutStr sink . toLazyText . makeTable =<< rows
hPutStr sink "</table>"
where
-- We provide the number of rows in IO so the builder value isn't shared
-- between the benchmark samples.
rows :: IO Int
rows = return 20000
{-# NOINLINE rows #-}
makeTable :: Int -> Builder
makeTable n = mconcat $ replicate n $ mconcat $ map makeCol [1 .. 50]
makeCol :: Int -> Builder
makeCol 1 = fromText "<tr><td>1</td>"
makeCol 50 = fromText "<td>50</td></tr>"
makeCol i = fromText "<td>" `mappend` (fromInt i `mappend` fromText "</td>")
fromInt :: Int -> Builder
fromInt = fromText . T.pack . show
| bos/text | benchmarks/haskell/Benchmarks/Programs/BigTable.hs | bsd-2-clause | 1,317 | 0 | 11 | 245 | 317 | 179 | 138 | 25 | 1 |
{-# Language ParallelListComp #-}
module StaticAsteroids (benchmark, summary) where
import Control.Monad hiding (sequence_)
import Graphics.Blank
import System.Random
import Utils
benchmark :: CanvasBenchmark
benchmark ctx = do
xs <- replicateM numAsteroids $ randomXCoord ctx
ys <- replicateM numAsteroids $ randomYCoord ctx
dxs <- replicateM numAsteroids $ randomRIO (-15, 15)
dys <- replicateM numAsteroids $ randomRIO (-15, 15)
send' ctx $ do
clearCanvas
sequence_ [showAsteroid (x,y) (mkPts (x,y) ds)
| x <- xs
| y <- ys
| ds <- cycle $ splitEvery 6 $ zip dxs dys
]
summary :: String
summary = "StaticAsteroids"
numAsteroids :: Int
numAsteroids = 1000
showAsteroid :: Point -> [Point] -> Canvas ()
showAsteroid (x,y) pts = do
beginPath()
moveTo (x,y)
mapM_ lineTo pts
closePath()
stroke()
mkPts :: Point -> [(Double, Double)] -> [Point]
mkPts (x,y) xs = [ (x+x',y+y') | (x',y') <- xs ]
splitEvery :: Int -> [a] -> [[a]]
splitEvery n = takeWhile (not.null) . map (take n) . iterate (drop n) -- borrowed from Magnus Kronqvist on stack overflow
| ku-fpg/blank-canvas-mark | hs/StaticAsteroids.hs | bsd-3-clause | 1,194 | 2 | 16 | 314 | 459 | 237 | 222 | 33 | 1 |
------------------------------------------------------------------------
-- |
-- Module : ALife.Creatur.Wain.Audio.GeneratePopulation
-- Copyright : (c) Amy de Buitléir 2012-2016
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- ???
--
------------------------------------------------------------------------
{-# LANGUAGE TypeFamilies #-}
import ALife.Creatur (agentId)
import ALife.Creatur.Wain.AudioID.Experiment (PatternWain,
randomPatternWain, printStats)
import ALife.Creatur.Wain (adjustEnergy)
import ALife.Creatur.Wain.Pretty (pretty)
import ALife.Creatur.Wain.PersistentStatistics (clearStats)
import ALife.Creatur.Wain.Statistics (Statistic, stats, summarise)
import ALife.Creatur.Wain.AudioID.Universe (Universe(..),
writeToLog, store, loadUniverse, uClassifierSizeRange,
uPredictorSizeRange, uInitialPopulationSize, uStatsFile)
import Control.Lens
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Random (evalRandIO)
import Control.Monad.Random.Class (getRandomR)
import Control.Monad.State.Lazy (StateT, evalStateT, get)
introduceRandomAgent
:: String -> StateT (Universe PatternWain) IO [Statistic]
introduceRandomAgent name = do
u <- get
classifierSize
<- liftIO . evalRandIO . getRandomR . view uClassifierSizeRange $ u
predictorSize
<- liftIO . evalRandIO . getRandomR . view uPredictorSizeRange $ u
agent
<- liftIO . evalRandIO $
randomPatternWain name u classifierSize predictorSize
-- Make the first generation a little hungry so they start learning
-- immediately.
let (agent', _) = adjustEnergy 0.8 agent
writeToLog $ "GeneratePopulation: Created " ++ agentId agent'
writeToLog $ "GeneratePopulation: Stats " ++ pretty (stats agent')
store agent'
return (stats agent')
introduceRandomAgents
:: [String] -> StateT (Universe PatternWain) IO ()
introduceRandomAgents ns = do
xs <- mapM introduceRandomAgent ns
let yss = summarise xs
printStats yss
statsFile <- use uStatsFile
clearStats statsFile
main :: IO ()
main = do
u <- loadUniverse
let ns = map (("Founder" ++) . show) [1..(view uInitialPopulationSize u)]
print ns
evalStateT (introduceRandomAgents ns) u
| mhwombat/exp-audio-id-wains | src/ALife/Creatur/Wain/AudioID/GeneratePopulation.hs | bsd-3-clause | 2,255 | 0 | 13 | 334 | 544 | 295 | 249 | 46 | 1 |
markup = <div>
<h1>Installation == Pain, Pain == Love</h1>
<p>
Given the relative immaturity of Haskell's package installation tools, installation of Turbinado is fairly challenging. With <% anchorTag "http://hackage.haskell.org/trac/hackage/wiki/CabalInstall" "cabal-install" %> this should get better, but, for now, installation is an adventure.
</p>
<p>
In addition to its many other joys, the ORM in Turbinado only works with PostgreSQL right now.
</p>
<h1>Suit up</h1>
<p>
You'll need to have the following packages installed to have a go at installation:
</p>
<ul class="standard-list">
<li><a href="http://www.haskell.org/ghc">GHC</a><em> (darcs) </em></li>
<li><a href="http://code.haskell.org/HSP/haskell-src-exts/">haskell-src-exts</a><em> (darcs) </em></li>
<li><a href="http://code.haskell.org/HSP/harp/">harp</a><em> (darcs) </em></li>
<li><a href="http://git.complete.org/hslogger">hslogger</a><em> (git) </em></li>
<li><a href="http://code.haskell.org/encoding/">encoding</a><em> (darcs) </em></li>
<li><a href="http://code.haskell.org/HSP/hsx/">hsx</a><em> (darcs) </em></li>
<li><a href="http://code.haskell.org/hs-plugins">hs-plugins</a><em> (darcs) </em></li>
<li><a href="http://code.haskell.org/http">http</a><em> (darcs) </em></li>
<li><a href="http://git.complete.org/hdbc">HDBC</a><em> (git) </em></li>
<li><a href="http://git.complete.org/hdbc-postgresql">HDBC-PostgreSQL</a><em> (git) </em></li>
</ul>
<h1>Grab the code:</h1>
<pre>
git clone git://github.com/alsonkemp/turbinado.git
</pre>
<h1>Build it</h1>
<p>
With all of the packages installed, wait for a new moon, stand on tip-toes, and do the following:
</p>
<pre>
runghc Setup.lhs configure
runghc Setup.lhs build
</pre>
<p>
If everything goes well, you should be able to do:
</p>
<pre>
dist/build/turbinado/turbinado -p 9999
</pre>
<p>
Try browsing to http://the-machines-name:9999/images/1x1.gif.
</p>
</div>
| alsonkemp/turbinado-website | App/Views/Home/Install.hs | bsd-3-clause | 2,566 | 98 | 148 | 857 | 1,007 | 494 | 513 | -1 | -1 |
-- | The children elements of the @osm@ element of a OSM file.
module Data.Geo.OSM.Children
(
Children
, osmUser
, osmGpxFile
, osmApi
, osmChangeset
, osmNodeWayRelation
, foldChildren
) where
import Text.XML.HXT.Arrow.Pickle
import Data.Geo.OSM.User
import Data.Geo.OSM.Preferences
import Data.Geo.OSM.GpxFile
import Data.Geo.OSM.Api
import Data.Geo.OSM.Changeset
import Data.Geo.OSM.NodeWayRelation
-- | The children elements of the @osm@ element of a OSM file.
data Children =
User User
| Preferences Preferences
| GpxFile GpxFile
| Api Api
| Changeset Changeset
| NWR [NodeWayRelation]
deriving Eq
instance XmlPickler Children where
xpickle =
xpAlt (\r -> case r of
User _ -> 0
Preferences _ -> 1
GpxFile _ -> 2
Api _ -> 3
Changeset _ -> 4
NWR _ -> 5) [xpWrap (User, \(User u) -> u) xpickle,
xpWrap (Preferences, \(Preferences p) -> p) xpickle,
xpWrap (GpxFile, \(GpxFile f) -> f) xpickle,
xpWrap (Api, \(Api a) -> a) xpickle,
xpWrap (Changeset, \(Changeset c) -> c) xpickle,
xpWrap (NWR, \(NWR k) -> k) (xpList xpickle)]
instance Show Children where
show =
showPickled []
-- | A @user@ element.
osmUser ::
User
-> Children
osmUser =
User
-- | A @gpx_file@ element.
osmGpxFile ::
GpxFile
-> Children
osmGpxFile =
GpxFile
-- | A @api@ element.
osmApi ::
Api
-> Children
osmApi =
Api
-- | A @changeset@ element.
osmChangeset ::
Changeset
-> Children
osmChangeset =
Changeset
-- | A list of @node@, @way@ or @relation@ elements.
osmNodeWayRelation ::
[NodeWayRelation]
-> Children
osmNodeWayRelation =
NWR
-- | Folds OSM child elements (catamorphism).
foldChildren ::
(User -> a) -- ^ If a @user@ element.
-> (Preferences -> a) -- ^ If a @preferences@ element.
-> (GpxFile -> a) -- ^ If a @gpx_file@ element.
-> (Api -> a) -- ^ If a @api@ element.
-> (Changeset -> a) -- ^ If a @changeset@ element.
-> ([NodeWayRelation] -> a) -- ^ If a list of @node@, @way@ or @relation@ elements.
-> Children -- ^ The disjunctive type of child elements.
-> a
foldChildren z _ _ _ _ _ (User u) =
z u
foldChildren _ z _ _ _ _ (Preferences p) =
z p
foldChildren _ _ z _ _ _ (GpxFile f) =
z f
foldChildren _ _ _ z _ _ (Api a) =
z a
foldChildren _ _ _ _ z _ (Changeset c) =
z c
foldChildren _ _ _ _ _ z (NWR k) =
z k
| tonymorris/geo-osm | src/Data/Geo/OSM/Children.hs | bsd-3-clause | 2,639 | 0 | 13 | 833 | 719 | 401 | 318 | 87 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
'Snap.Extension.Less.Less' is an implementation of the 'MonadLess'
interface defined in 'Snap.Extension.Less'.
As always, to use, add 'LessState' to your application's state, along with an
instance of 'HasLessState' for your application's state, making sure to use a
'lessInitializer' in your application's 'Initializer', and then you're ready to go.
This implementation does not require that your application's monad implement
interfaces from any other Snap Extension.
-}
module Snap.Extension.Less.Less
( HasLessState(..)
, LessState
, lessInitializer
) where
import Control.Concurrent
import Control.Monad
import Control.Monad.Reader
import Control.Monad.Trans
import Data.ByteString (ByteString)
import qualified Data.ByteString.UTF8 as U
import qualified Data.ByteString as B
import qualified Data.Foldable as F
import Data.List
import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe
import Snap.Extension
import Snap.Extension.Less
import Snap.Extension.Utils
import Snap.Types hiding (dir, path)
import System.Directory
import System.Directory.Tree
import System.Exit
import System.IO
------------------------------------------------------------------------------
-- | Your application's state must include a 'LessState' in order for your
-- application to be a 'MonadLess'.
data LessState = LessState
{ _dir :: FilePath
, _mapping :: MVar (Map ByteString ByteString)
}
------------------------------------------------------------------------------
-- | For you appliaction's monad to be a 'MonadLess', your application's state
-- needs to be an instance of 'HasLessState'. Minimal complete definition:
-- 'getLessState', 'setLessState'.
class HasLessState s where
getLessState :: s -> LessState
setLessState :: LessState -> s -> s
------------------------------------------------------------------------------
instance InitializerState LessState where
extensionId = const "Less/Less"
mkCleanup = const $ return ()
mkReload (LessState d m) = modifyMVar_ m $ const $ loadStylesheets d
------------------------------------------------------------------------------
-- | The Initializer for the Less extension. It takes a path to a stylesheet
-- directory containing @.less@ files.
lessInitializer :: FilePath -> Initializer LessState
lessInitializer path = mkInitializer =<< (liftIO $
loadStylesheets path >>= newMVar >>= return . LessState path)
------------------------------------------------------------------------------
-- | Locates the 'lessc' executable.
findLessc :: IO FilePath
findLessc = do
findExecutable "lessc" >>= maybe (findM exec gems) (return . Just) >>=
maybe (error "Could not find executable `lessc'") return
where
gems = ["/var/lib/gems/1.9.1/bin/lessc", "/var/lib/gems/1.8/bin/lessc"]
findM p = fmap listToMaybe . filterM p
exec f = do
exists <- doesFileExist f
if exists then getPermissions f >>= return . executable
else return False
------------------------------------------------------------------------------
-- | Given the path to a @.less@ file, this returns its contents processed by
-- @lessc@.
loadStylesheet :: FilePath -> IO ByteString
loadStylesheet p = do
l <- findLessc
(exitCode, out, err) <- readProcessWithExitCode' l [p, "/dev/stdout"] ""
when (exitCode /= ExitSuccess) $ error $ p ++ ": " ++ U.toString err
return out
------------------------------------------------------------------------------
-- | Given the path to a directory containing @.less@ files, this returns a
-- map from the names of those @.less@ files with the @.less@ replaced with
-- @.css@ to the contents of those files after being processed with the
-- @lessc@ command.
loadStylesheets :: FilePath -> IO (Map ByteString ByteString)
loadStylesheets path = readDirectoryWith reader path >>=
return . M.fromList . map fromJust . filter isJust . F.toList . free
where
reader file = if ".less" `isSuffixOf` file then do
stylesheet <- loadStylesheet file
return $ Just $ (U.fromString $ cssify file, stylesheet)
else
return Nothing
cssify p = (drop (length path + 1) $ take (length p - 5) p) ++ ".css"
------------------------------------------------------------------------------
instance HasLessState s => MonadLess (SnapExtend s) where
lessServe = getRequest >>= getStylesheet . rqPathInfo >>= maybe pass serve
lessServeSingle p = getStylesheet p >>=
maybe (error $ "Stylesheet " ++ show p ++ " not found") serve
------------------------------------------------------------------------------
instance (MonadSnap m, HasLessState s) => MonadLess (ReaderT s m) where
lessServe = getRequest >>= getStylesheet . rqPathInfo >>= maybe pass serve
lessServeSingle p = getStylesheet p >>=
maybe (error $ "Stylesheet " ++ show p ++ " not found") serve
------------------------------------------------------------------------------
-- | A helper function used in the implementation of 'lessServe' and
-- 'lessServeSingle'.
getStylesheet :: (MonadSnap m, HasLessState s, MonadReader s m)
=> ByteString -> m (Maybe ByteString)
getStylesheet stylesheet = do
(LessState _ mapping) <- asks getLessState
liftIO $ readMVar mapping >>= return . M.lookup stylesheet
------------------------------------------------------------------------------
-- | A helper function used in the implementation of 'lessServe' and
-- 'lessServeSingle'.
serve :: MonadSnap m => ByteString -> m ()
serve css = do
modifyResponse $ setContentType "text/css; charset=utf-8"
modifyResponse $ setContentLength (fromIntegral $ B.length css)
writeBS css
| duairc/snap-extensions | src/Snap/Extension/Less/Less.hs | bsd-3-clause | 5,911 | 0 | 13 | 1,127 | 1,097 | 579 | 518 | 80 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module EventTests (
specTests
) where
import qualified Data.ByteString as BS
import Data.ByteString.Arbitrary
import Data.ByteString.Internal
import Data.Serialize
import Event
import Foreign.ForeignPtr
import Foreign.Marshal.Utils
import Foreign.Ptr
import JournalFile
import System.Directory
import System.IO
import System.IO.MMap
import Test.QuickCheck
import Test.Tasty
import Test.Tasty.Hspec
specTests :: IO TestTree
specTests = testGroup "event tests" <$> sequence [serialization]
newtype EventArbitrary = EventArbitrary Event deriving (Show, Eq)
serialization :: IO TestTree
serialization = testSpec "event tests" $
describe "serialization" $ do
it "should encode then decode to the original" $ property $
\((EventArbitrary x) :: EventArbitrary) -> decode (encode x) == Right x
it "same if we process through a file" $ do
(fp, h) <- openBinaryTempFile "test-output" "test"
EventArbitrary x <- generate arbitrary
let bytes = encode x
BS.hPut h bytes
hFlush h
hClose h
h' <- openBinaryFile fp ReadMode
x' <- BS.hGet h' $ BS.length bytes
removeFile fp
decode x' `shouldBe` Right x
it "also if we pass through a memory map" $ do
EventArbitrary x <- generate arbitrary
let bytes = encode x
let (fptr, offset, _) = toForeignPtr bytes
fp <- openTempJournalFile "test-output" "test" $ toInteger (BS.length bytes)
(ptr,rawsize,offset',size) <- mmapFilePtr fp ReadWrite Nothing
withForeignPtr fptr (\x' -> copyBytes (plusPtr ptr offset') (plusPtr x' offset) size)
bs' <- create size (\x'' -> copyBytes x'' (plusPtr ptr offset') size)
munmapFilePtr ptr rawsize
decode bs' `shouldBe` Right x
-- sampleEvent = Event 1 1 1 1 1 $ C.pack "blah"
instance Arbitrary EventArbitrary where
arbitrary = do
aId <- arbitrary
aVer <- arbitrary
uId <- arbitrary
t <- arbitrary
eId <- arbitrary
p <- arbitrary
return (EventArbitrary $ Event aId aVer uId t eId (fromABS p))
| fatlazycat/eventjournal | test/EventTests.hs | bsd-3-clause | 2,232 | 0 | 17 | 615 | 633 | 310 | 323 | 56 | 1 |
import Test.Hspec
main :: IO ()
main = putStrLn "Test suite not yet implemented"
| jpanda109/Hcommand | test/Spec.hs | bsd-3-clause | 82 | 0 | 6 | 15 | 24 | 12 | 12 | 3 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiWayIf #-}
module Types.Filter where
import Vivid
import qualified Data.Map as M
import qualified Data.Tree as T
import Data.Tree
import Data.Maybe
import Data.List
import Data.Functor.Classes
import Data.Data
import Control.Monad.Zip
import GHC.Generics
import Control.Lens
import Types.DSPNode
import Text.Printf
import Debug.Trace
-- | A DSP Program is a structure of DSPNodes, each with an Id
-- TODO relax from Tree to Directed Acyclic Graph
type Filter = T.Tree DSPNodeL
drawFilter :: Filter -> String
drawFilter =
drawTree. fmap (show. nodeContent)
-- | check that two filters have the same structure, ignoring parameters
-- TODO can this be written without so much repetition?
sameStructure :: Filter -> Filter -> Bool
sameStructure f1 f2 = fmap (toConstr. nodeContent) f1 == fmap (toConstr. nodeContent) f2
-- Tree has Ord1, which gives us liftCompare. No clue what is happening here really
-- If there are any stranger bugs with tree operations, this is probably the problem
instance Ord Filter where
compare = liftCompare (compare)
-- A log of the best filter for each structure
type FilterLog = M.Map Filter Double
{-showAmp amp = "amp@"++(printf "%.2f" $ ampScale amp)
showFreq freq = "freq@" ++ (printf "%.0f" $ freqScale freq)
showFreqP freq = "freq@" ++ (printf "%.0f" $ freqScalePitchShift freq)
showDelay d = "delay@" ++ (printf "%.2f" $ delayScale d)
-}
checkStructureThen :: Filter -> Filter -> a -> a-> a
checkStructureThen f1 f2 defaultVal a =
if sameStructure f1 f2
then a
else
-- TODO this shouldn't happen,
-- but for now we just result defaultVal (whatever that is)
-- so that the program doesnt crash
defaultVal -- error "can only calculate compare filters on equivelant structures"
filterDiff :: Filter -> Filter -> Double
filterDiff f1 f2 = let
nodeDiff n1 n2 = sum $ (zipWith (\p1 p2 -> abs (snd p1 - snd p2)) (getParams $ nodeContent n1) (getParams $ nodeContent n2))
diffTree = liftA2 nodeDiff f1 f2
in
checkStructureThen f1 f2 0 $ sum diffTree
-- | which field changed between two filters
-- if more than one change, returns only the first one found
filterFieldChange :: Filter -> Filter -> [Char]
filterFieldChange f1 f2 = let
-- TODO change 0.0000001 to something else
fieldDiff p1 p2 = if (abs (snd p1-snd p2)) < 0.00000001 then Nothing else Just $ fst p1
nodeDiff n1 n2 = zipWith fieldDiff (getParams $ nodeContent n1) (getParams $ nodeContent n2)
diffTree :: T.Tree ([Maybe String])
diffTree = zipTree nodeDiff f1 f2
in
case catMaybes $ concat $ T.flatten diffTree of
[] -> "No change"
[x] -> x
xs -> head xs --error $ "Multiple fields changed at once"++ show diffTree --this shouldnt really happen, but for now just give the head of the list
zipTree :: (a -> b -> c) -> T.Tree a -> T.Tree b -> T.Tree c
zipTree f t1 t2 = Node {
rootLabel = f (rootLabel t1) (rootLabel t2)
, subForest = zipSubForest f (subForest t1) (subForest t2)
}
zipSubForest :: (a -> b -> c) -> [T.Tree a] -> [T.Tree b] -> [T.Tree c]
zipSubForest f [] [] = []
zipSubForest f (x:xs) (y:ys) = (zipTree f x y): zipSubForest f xs ys
zipSubForest f [] _ = error "Structural mismatch"
zipSubForest f _ [] = error "structural mismatch"
-- | find a node in f that is the same DSPNode as n
-- if no such node is found, give back n
findSameNode :: Filter -> DSPNodeL -> DSPNodeL
findSameNode f n = case catMaybes $ foldr (\n1 ns -> (if sameConstructor (nodeContent n1) (nodeContent n) then Just n1 else Nothing):ns) [] f of
[] -> n
xs -> head xs
--implements feature scaling so during GD our thetas are -1<t<1
--we only scale them back to the appropriate values when we need to apply theatas in a filter
toVivid :: Filter -> SDBody' '[] Signal -> SDBody' '[] Signal
toVivid f = case T.subForest f of
[] -> nodeToVivid $ nodeContent $ T.rootLabel f
ns -> sequentialCompose (nodeToVivid $ nodeContent $ T.rootLabel f) ns
where
sequentialCompose :: (SDBody' '[] Signal -> SDBody' '[] Signal) ->
[Filter] ->
SDBody' '[] Signal -> SDBody' '[] Signal
sequentialCompose n ns =
(\bufs -> n $ (parallelCompose ns) bufs)
parallelCompose :: [Filter] -> (SDBody' '[] Signal -> SDBody' '[] Signal)
parallelCompose ns =
foldr (\thisNode composedNodes ->
(\bufs -> (composedNodes bufs) ~+ ((toVivid thisNode) bufs)))
id ns
nodeToVivid :: DSPNode -> SDBody' '[] Signal -> SDBody' '[] Signal
nodeToVivid = \case
ID a -> (\bufs -> (ampScale a::Float) ~* bufs)
HPF t a -> (\bufs -> (ampScale a::Float) ~* hpf (freq_ (freqScale t::Float), in_ bufs))
LPF t a -> (\bufs -> (ampScale a::Float) ~* lpf (freq_ (freqScale t::Float), in_ bufs))
PitchShift t a -> (\bufs -> (ampScale a::Float) ~* freqShift (freq_ (freqScalePitchShift t::Float), in_ bufs)) -- there is also pitchShift in vivid, but it is more complex
WhiteNoise a -> (\bufs -> (ampScale a::Float) ~* whiteNoise) --TODO mix bufs into output
--Ringz f d a -> (\bufs -> (ampScale a::Float) ~* ringz (freq_ (freqScale f::Float), decaySecs_ (delayScale d::Float), in_ bufs))
FreeVerb f d a -> (\bufs -> (ampScale a::Float) ~* freeVerb (mix_ (freqScale f::Float), room_ (delayScale d::Float), in_ bufs))
-- | Given a filter structure, extract the theta selctors that we need to do parameter synthesis
extractThetaUpdaters :: Filter -> [Filter -> (Double -> Double) -> Filter]
extractThetaUpdaters filter =
foldr ((++). getUpdater) [] filter
-- | Using the nodeId, we can get a function that updates the particular node of interest
-- this allows us to do SGD with multiple copies of the same DSPNode in a single Filter
getUpdater :: DSPNodeL -> [Filter -> (Double -> Double) -> Filter]
getUpdater dspNode = let
updater :: _ -> _ -> Filter -> (Double -> Double) -> Filter
updater nodeType nodeParam = (\ts f -> fmap (\n -> if nodeId n == nodeId dspNode then n{nodeContent = nodeType $ f nodeParam} else n) ts)
in
case nodeContent dspNode of
ID a -> [ updater ID a]
HPF t a -> [ updater (\newT -> HPF newT a) t
, updater (\newA -> HPF t newA) a]
LPF t a -> [ updater (\newT -> LPF newT a) t
, updater (\newA -> LPF t newA) a]
PitchShift t a -> [ updater (\newT -> PitchShift newT a) t
, updater (\newA -> PitchShift t newA) a]
WhiteNoise a -> [ updater WhiteNoise a]
FreeVerb t d a -> [ updater (\newT -> FreeVerb newT d a) t
, updater (\newD -> FreeVerb t newD a) d
, updater (\newA -> FreeVerb t d newA) a]
| aedanlombardo/HaskellPS | DSP-PBE/src/Types/Filter.hs | bsd-3-clause | 7,242 | 0 | 18 | 1,722 | 2,058 | 1,078 | 980 | 111 | 7 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS -Wall #-}
module GOA (
module Prelude,
lambdabot,
wakeup,
query,
setLambdabotHome,
findPosixLambdabot,
setLambdabotFlags
) where
import Data.List (isPrefixOf, find)
import Data.Char (isSpace)
import Data.Maybe
import System.IO
import System.Process
import System.IO.Unsafe
import System.Directory
import Data.IORef
import Control.Monad
import qualified Control.Exception as E
import System.FilePath.Posix (pathSeparator)
-- |
-- Path to lambdabot directory
--
lambdabotHome :: IORef FilePath
lambdabotHome = unsafePerformIO $ do
userHome <- getHomeDirectory
home <- readFile (userHome ++ [pathSeparator] ++ ".ghci")
newIORef (parsedHome home)
{-# NOINLINE lambdabotHome #-}
-- Try to parse the lambdabot home, otherwise return empty string.
parsedHome :: String -> String
parsedHome = path . find (isPrefixOf prefix) . lines where
path = trim . filter (/='"') . join . drop 1 . words . fromMaybe ""
prefix = "setLambdabotHome"
trim = unwords . words
lambdabotFlags :: IORef String
lambdabotFlags = unsafePerformIO $ newIORef ""
{-# NOINLINE lambdabotFlags #-}
-- |
-- let's you customize to the location of your lambdabot install
--
setLambdabotHome :: String -> IO ()
setLambdabotHome = writeIORef lambdabotHome
-- |
-- attempts to auto-detect where lambdabot is located, but requires "which"
--
findPosixLambdabot :: IO FilePath
findPosixLambdabot = do
p <- readProcess "which" ["lambdabot"] ""
liftM init $ readProcess "dirname" [p] ""
-- |
-- let's you set the lambdabot start up flags such as
--
-- @--online@
-- @--restricted@
--
setLambdabotFlags :: String -> IO ()
setLambdabotFlags = writeIORef lambdabotFlags
-- |
-- internal state, keep track of our in and out handles, and process id
--
data ST = ST !Handle -- ^ Handle to lambdabot stdin
!Handle -- ^ Handle to lambdabot stdout
!Handle -- ^ Handle to lambdabot stderr
!ProcessHandle -- ^ lambdabot's pid
-- |
-- Module-internal state. Hang on to lambdabot's handles
--
state :: IORef (Maybe ST)
state = unsafePerformIO $ newIORef Nothing
{-# NOINLINE state #-}
-- |
-- Fork lambdabot on start up
--
wakeup :: IO ()
wakeup = do _ <- wakeup'; return ()
-- | Bool indicates success/failure
wakeup' :: IO Bool
wakeup' = do
m <- forkLambdabot
case m of
Nothing -> return False
Just (a,b,c,d) -> do writeIORef state (Just (ST a b c d))
return True
-- |
-- fork a lambdabot on start up
--
-- TODO, do this hmp3-style, with a separate thread and a channel
--
-- catch error and print better message
forkLambdabot :: IO (Maybe (Handle,Handle,Handle,ProcessHandle))
forkLambdabot = withLambdabot $ do
b <- doesFileExist "./lambdabot"
home <- readIORef lambdabotHome
args' <- readIORef lambdabotFlags
let args | null args' = []
| otherwise = [args']
if not b
then do putStrLn $ "No lambdabot binary found in: " ++ home
return Nothing
else E.catch
(do x <- runInteractiveProcess "./lambdabot" args Nothing Nothing
return (Just x))
(\(e :: E.IOException) -> do
putStrLn $ "Unable to start lambdabot: " ++ show e
return Nothing)
-- |
-- Query lambdabot
--
lambdabot :: String -> String -> IO [Char]
lambdabot command args = withLambdabot $ do
r <- query command args
mapM_ putStrLn r
return []
-- |
-- query a running lambdabot
--
-- Could try to catch a closed handle here, and run 'wakeup' again
--
query :: String -> String -> IO [String]
query command args
| null $ command ++ args = return [] -- fixes a bug where lambdabot never
-- responds, thus hanging GoA
| otherwise = do
m <- readIORef state
E.handle
(\(e :: E.IOException) ->
do writeIORef state Nothing -- blank old handles if we fail
return ["Unable to run lambdabot: " ++ show e])
(case m of
Nothing -> do
-- maybe we can start the process automatically
success <- wakeup'
if success then query command args else return []
Just (ST i o _ _) -> do
-- some commands seem to assume no whitespace at the end so we trim it
let s = reverse . dropWhile isSpace . reverse $ unwords [command,args]
hPutStrLn i s >> hFlush i
-- hGetLine o -- throw away irc message (and prompt on first line)
result <- clean `fmap` getOutput o []
return (lines result))
where
clean x
| "lambdabot> " `isPrefixOf` x = drop 11 x
| otherwise = x
-- trim was spoiling some output
-- trim = dropWhile isSpace . reverse . dropWhile isSpace . reverse
-- |
-- read output until next command is seen
--
getOutput :: Handle -> String -> IO String
getOutput h acc
| ">tobadbmal\n" `isPrefixOf` acc = return $ reverse (drop 11 acc)
| otherwise = do
c <- hGetChar h
getOutput h (c:acc)
-- |
-- perform an IO action in the lambdabot directory
--
withLambdabot :: IO a -> IO a
withLambdabot a = do
p <- getCurrentDirectory
home <- readIORef lambdabotHome
setCurrentDirectory home
v <- a
setCurrentDirectory p
return v
| chrisdone/goa | GOA.hs | bsd-3-clause | 5,570 | 0 | 21 | 1,632 | 1,305 | 669 | 636 | 123 | 3 |
foo :: String -> Int -> Bool
foo i _
| (length i) < 5 = False
foo [] _ = False
foo (_ : _) j = j < 5
-- λ> foo "" 2
-- False
-- λ> foo "fdafdsdas" 2
-- True
-- λ> foo "fdafdsdas" 7
-- False
-- λ>
| redfish64/IrcScanner | src/Learn/guards.hs | bsd-3-clause | 207 | 0 | 10 | 61 | 80 | 43 | 37 | 5 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.UI.GLUT.Window
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/GLUT/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-- GLUT supports two types of windows: top-level windows and subwindows. Both
-- types support OpenGL rendering and GLUT callbacks. There is a single
-- identifier space for both types of windows.
--
--------------------------------------------------------------------------------
module Graphics.UI.GLUT.Window (
-- * Window identifiers
Window,
-- * Creating and destroying (sub-)windows
-- $CreatingAndDestroyingSubWindows
createWindow, createSubWindow, destroyWindow,
parentWindow, numSubWindows,
-- * Manipulating the /current window/
currentWindow,
-- * Re-displaying and double buffer management
postRedisplay, swapBuffers,
-- * Changing the window geometry
-- $ChangingTheWindowGeometry
windowPosition, windowSize, fullScreen,
-- * Manipulating the stacking order
-- $ManipulatingTheStackingOrder
pushWindow, popWindow,
-- * Managing a window\'s display status
WindowStatus(..), windowStatus,
-- * Changing the window\/icon title
-- $ChangingTheWindowIconTitle
windowTitle, iconTitle,
-- * Cursor management
Cursor(..), cursor, pointerPosition
) where
import Foreign.C.String ( CString, withCString )
import Foreign.C.Types ( CInt )
import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) )
import Graphics.Rendering.OpenGL.GL.StateVar (
GettableStateVar, makeGettableStateVar,
SettableStateVar, makeSettableStateVar,
StateVar, makeStateVar )
import Graphics.UI.GLUT.Constants (
glut_WINDOW_PARENT, glut_WINDOW_NUM_CHILDREN,
glut_WINDOW_X, glut_WINDOW_Y, glut_WINDOW_WIDTH, glut_WINDOW_HEIGHT,
glut_CURSOR_RIGHT_ARROW, glut_CURSOR_LEFT_ARROW, glut_CURSOR_INFO,
glut_CURSOR_DESTROY, glut_CURSOR_HELP, glut_CURSOR_CYCLE, glut_CURSOR_SPRAY,
glut_CURSOR_WAIT, glut_CURSOR_TEXT, glut_CURSOR_CROSSHAIR,
glut_CURSOR_UP_DOWN, glut_CURSOR_LEFT_RIGHT, glut_CURSOR_TOP_SIDE,
glut_CURSOR_BOTTOM_SIDE, glut_CURSOR_LEFT_SIDE, glut_CURSOR_RIGHT_SIDE,
glut_CURSOR_TOP_LEFT_CORNER, glut_CURSOR_TOP_RIGHT_CORNER,
glut_CURSOR_BOTTOM_RIGHT_CORNER, glut_CURSOR_BOTTOM_LEFT_CORNER,
glut_CURSOR_INHERIT, glut_CURSOR_NONE, glut_CURSOR_FULL_CROSSHAIR,
glut_WINDOW_CURSOR )
import Graphics.UI.GLUT.QueryUtils ( simpleGet )
import Graphics.UI.GLUT.Types ( Window, makeWindow )
--------------------------------------------------------------------------------
-- $CreatingAndDestroyingSubWindows
-- Each created window has a unique associated OpenGL context. State changes to
-- a window\'s associated OpenGL context can be done immediately after the
-- window is created.
--
-- The /display state/ of a window is initially for the window to be shown. But
-- the window\'s /display state/ is not actually acted upon until
-- 'Graphics.UI.GLUT.Begin.mainLoop' is entered. This means until
-- 'Graphics.UI.GLUT.Begin.mainLoop' is called, rendering to a created window is
-- ineffective because the window can not yet be displayed.
--
-- The value returned by 'createWindow' and 'createSubWindow' is a unique
-- identifier for the window, which can be used with 'currentWindow'.
-- | Create a top-level window. The given name will be provided to the window
-- system as the window\'s name. The intent is that the window system will label
-- the window with the name.Implicitly, the /current window/ is set to the newly
-- created window.
--
-- /X Implementation Notes:/ The proper X Inter-Client Communication Conventions
-- Manual (ICCCM) top-level properties are established. The @WM_COMMAND@
-- property that lists the command line used to invoke the GLUT program is only
-- established for the first window created.
createWindow
:: String -- ^ The window name
-> IO Window -- ^ The identifier for the newly created window
createWindow name = withCString name glutCreateWindow
foreign import CALLCONV unsafe "glutCreateWindow" glutCreateWindow ::
CString -> IO Window
--------------------------------------------------------------------------------
-- | Create a subwindow of the identified window with the given relative
-- position and size. Implicitly, the /current window/ is set to the
-- newly created subwindow. Subwindows can be nested arbitrarily deep.
createSubWindow
:: Window -- ^ Identifier of the subwindow\'s parent window.
-> Position -- ^ Window position in pixels relative to parent window\'s
-- origin.
-> Size -- ^ Window size in pixels
-> IO Window -- ^ The identifier for the newly created subwindow
createSubWindow win (Position x y) (Size w h) =
glutCreateSubWindow win
(fromIntegral x) (fromIntegral y)
(fromIntegral w) (fromIntegral h)
foreign import CALLCONV unsafe "glutCreateSubWindow" glutCreateSubWindow ::
Window -> CInt -> CInt -> CInt -> CInt -> IO Window
--------------------------------------------------------------------------------
-- | Contains the /current window\'s/ parent. If the /current window/ is a
-- top-level window, 'Nothing' is returned.
parentWindow :: GettableStateVar (Maybe Window)
parentWindow =
makeGettableStateVar $
getWindow (simpleGet makeWindow glut_WINDOW_PARENT)
--------------------------------------------------------------------------------
-- | Contains the number of subwindows the /current window/ has, not counting
-- children of children.
numSubWindows :: GettableStateVar Int
numSubWindows =
makeGettableStateVar $
simpleGet fromIntegral glut_WINDOW_NUM_CHILDREN
--------------------------------------------------------------------------------
-- | Destroy the specified window and the window\'s associated OpenGL context,
-- logical colormap (if the window is color index), and overlay and related
-- state (if an overlay has been established). Any subwindows of the destroyed
-- window are also destroyed by 'destroyWindow'. If the specified window was the
-- /current window/, the /current window/ becomes invalid ('currentWindow' will
-- contain 'Nothing').
foreign import CALLCONV unsafe "glutDestroyWindow" destroyWindow ::
Window -> IO ()
--------------------------------------------------------------------------------
-- | Controls the /current window/. It does /not/ affect the /layer in use/ for
-- the window; this is done using 'Graphics.UI.GLUT.Overlay.layerInUse'.
-- Contains 'Nothing' if no windows exist or the previously /current window/ was
-- destroyed. Setting the /current window/ to 'Nothing' is a no-op.
currentWindow :: StateVar (Maybe Window)
currentWindow =
makeStateVar (getWindow glutGetWindow) (maybe (return ()) glutSetWindow)
getWindow :: IO Window -> IO (Maybe Window)
getWindow act = do
win <- act
return $ if win == makeWindow 0 then Nothing else Just win
foreign import CALLCONV unsafe "glutSetWindow" glutSetWindow :: Window -> IO ()
foreign import CALLCONV unsafe "glutGetWindow" glutGetWindow :: IO Window
--------------------------------------------------------------------------------
-- | Mark the normal plane of given window (or the /current window/, if none
-- is supplied) as needing to be redisplayed. The next iteration through
-- 'Graphics.UI.GLUT.Begin.mainLoop', the window\'s display callback will be
-- called to redisplay the window\'s normal plane. Multiple calls to
-- 'postRedisplay' before the next display callback opportunity generates only a
-- single redisplay callback. 'postRedisplay' may be called within a window\'s
-- display or overlay display callback to re-mark that window for redisplay.
--
-- Logically, normal plane damage notification for a window is treated as a
-- 'postRedisplay' on the damaged window. Unlike damage reported by the window
-- system, 'postRedisplay' will /not/ set to true the normal plane\'s damaged
-- status (see 'Graphics.UI.GLUT.State.damaged').
--
-- Also, see 'Graphics.UI.GLUT.Overlay.postOverlayRedisplay'.
postRedisplay :: Maybe Window -> IO ()
postRedisplay = maybe glutPostRedisplay glutPostWindowRedisplay
foreign import CALLCONV unsafe "glutPostRedisplay" glutPostRedisplay :: IO ()
-- | Mark the normal plane of the given window as needing to be redisplayed,
-- otherwise the same as 'postRedisplay'.
--
-- The advantage of this routine is that it saves the cost of using
-- 'currentWindow' (entailing an expensive OpenGL context switch), which is
-- particularly useful when multiple windows need redisplays posted at the same
-- time.
foreign import CALLCONV unsafe "glutPostWindowRedisplay"
glutPostWindowRedisplay :: Window -> IO ()
--------------------------------------------------------------------------------
-- | Perform a buffer swap on the /layer in use/ for the /current window/.
-- Specifically, 'swapBuffers' promotes the contents of the back buffer of the
-- /layer in use/ of the /current window/ to become the contents of the front
-- buffer. The contents of the back buffer then become undefined. The update
-- typically takes place during the vertical retrace of the monitor, rather than
-- immediately after 'swapBuffers' is called.
--
-- An implicit 'Graphics.Rendering.OpenGL.GL.FlushFinish.flush' is done by
-- 'swapBuffers' before it returns. Subsequent OpenGL commands can be issued
-- immediately after calling 'swapBuffers', but are not executed until the
-- buffer exchange is completed.
--
-- If the /layer in use/ is not double buffered, 'swapBuffers' has no effect.
foreign import CALLCONV unsafe "glutSwapBuffers" swapBuffers :: IO ()
--------------------------------------------------------------------------------
-- $ChangingTheWindowGeometry
-- Note that the requests by 'windowPosition', 'windowSize', and 'fullScreen'
-- are not processed immediately. A request is executed after returning to the
-- main event loop. This allows multiple requests to the same window to be
-- coalesced.
--
-- 'windowPosition' and 'windowSize' requests on a window will disable the full
-- screen status of the window.
--------------------------------------------------------------------------------
-- | Controls the position of the /current window/. For top-level windows,
-- parameters of 'Position' are pixel offsets from the screen origin. For
-- subwindows, the parameters are pixel offsets from the window\'s parent window
-- origin.
--
-- In the case of top-level windows, setting 'windowPosition' is considered only
-- a request for positioning the window. The window system is free to apply its
-- own policies to top-level window placement. The intent is that top-level
-- windows should be repositioned according to the value of 'windowPosition'.
windowPosition :: StateVar Position
windowPosition = makeStateVar getWindowPosition setWindowPosition
setWindowPosition :: Position -> IO ()
setWindowPosition (Position x y) =
glutPositionWindow (fromIntegral x) (fromIntegral y)
foreign import CALLCONV unsafe "glutPositionWindow" glutPositionWindow ::
CInt -> CInt -> IO ()
getWindowPosition :: IO Position
getWindowPosition = do
x <- simpleGet fromIntegral glut_WINDOW_X
y <- simpleGet fromIntegral glut_WINDOW_Y
return $ Position x y
--------------------------------------------------------------------------------
-- | Controls the size of the /current window/. The parameters of 'Size' are
-- size extents in pixels. The width and height must be positive values.
--
-- In the case of top-level windows, setting 'windowSize' is considered only a
-- request for sizing the window. The window system is free to apply its own
-- policies to top-level window sizing. The intent is that top-level windows
-- should be reshaped according to the value of 'windowSize'. Whether a reshape
-- actually takes effect and, if so, the reshaped dimensions are reported to the
-- program by a reshape callback.
windowSize :: StateVar Size
windowSize = makeStateVar getWindowSize setWindowSize
setWindowSize :: Size -> IO ()
setWindowSize (Size w h) =
glutReshapeWindow (fromIntegral w) (fromIntegral h)
foreign import CALLCONV unsafe "glutReshapeWindow" glutReshapeWindow ::
CInt -> CInt -> IO ()
getWindowSize :: IO Size
getWindowSize = do
w <- simpleGet fromIntegral glut_WINDOW_WIDTH
h <- simpleGet fromIntegral glut_WINDOW_HEIGHT
return $ Size w h
--------------------------------------------------------------------------------
-- | Request that the /current window/ be made full screen. The exact semantics
-- of what full screen means may vary by window system. The intent is to make
-- the window as large as possible and disable any window decorations or borders
-- added the window system. The window width and height are not guaranteed to be
-- the same as the screen width and height, but that is the intent of making a
-- window full screen.
--
-- 'fullScreen' is defined to work only on top-level windows.
--
-- /X Implementation Notes:/ In the X implementation of GLUT, full screen is
-- implemented by sizing and positioning the window to cover the entire screen
-- and posting the @_MOTIF_WM_HINTS@ property on the window requesting
-- absolutely no decorations. Non-Motif window managers may not respond to
-- @_MOTIF_WM_HINTS@.
foreign import CALLCONV unsafe "glutFullScreen" fullScreen :: IO ()
--------------------------------------------------------------------------------
-- $ManipulatingTheStackingOrder
-- 'pushWindow' and 'popWindow' work on both top-level windows and subwindows.
-- The effect of pushing and popping windows does not take place immediately.
-- Instead the push or pop is saved for execution upon return to the GLUT event
-- loop. Subsequent pop or push requests on a window replace the previously
-- saved request for that window. The effect of pushing and popping top-level
-- windows is subject to the window system\'s policy for restacking windows.
-- | Change the stacking order of the /current window/ relative to its siblings
-- (lowering it).
foreign import CALLCONV unsafe "glutPushWindow" pushWindow :: IO ()
-- | Change the stacking order of the /current window/ relative to its siblings,
-- bringing the /current window/ closer to the top.
foreign import CALLCONV unsafe "glutPopWindow" popWindow :: IO ()
--------------------------------------------------------------------------------
-- | The display status of a window.
data WindowStatus
= Shown
| Hidden
| Iconified
deriving ( Eq, Ord, Show )
-- | Controls the display status of the /current window/.
--
-- Note that the effect of showing, hiding, and iconifying windows does not take
-- place immediately. Instead the requests are saved for execution upon return
-- to the GLUT event loop. Subsequent show, hide, or iconification requests on a
-- window replace the previously saved request for that window. The effect of
-- hiding, showing, or iconifying top-level windows is subject to the window
-- system\'s policy for displaying windows. Subwindows can\'t be iconified.
windowStatus :: SettableStateVar WindowStatus
windowStatus = makeSettableStateVar setStatus
where setStatus Shown = glutShowWindow
setStatus Hidden = glutHideWindow
setStatus Iconified = glutIconifyWindow
foreign import CALLCONV unsafe "glutShowWindow" glutShowWindow :: IO ()
foreign import CALLCONV unsafe "glutHideWindow" glutHideWindow :: IO ()
foreign import CALLCONV unsafe "glutIconifyWindow" glutIconifyWindow :: IO ()
--------------------------------------------------------------------------------
-- $ChangingTheWindowIconTitle
-- 'windowTitle' and 'iconTitle' should be set only when the /current
-- window/ is a top-level window. Upon creation of a top-level window, the
-- window and icon names are determined by the name given to 'createWindow'.
-- Once created, setting 'windowTitle' and 'iconTitle' can change the window and
-- icon names respectively of top-level windows. Each call requests the window
-- system change the title appropriately. Requests are not buffered or
-- coalesced. The policy by which the window and icon name are displayed is
-- window system dependent.
-- | Controls the window title of the /current top-level window/.
windowTitle :: SettableStateVar String
windowTitle =
makeSettableStateVar $ \name ->
withCString name glutSetWindowTitle
foreign import CALLCONV unsafe "glutSetWindowTitle" glutSetWindowTitle ::
CString -> IO ()
-- | Controls the icon title of the /current top-level window/.
iconTitle :: SettableStateVar String
iconTitle =
makeSettableStateVar $ \name ->
withCString name glutSetIconTitle
foreign import CALLCONV unsafe "glutSetIconTitle" glutSetIconTitle ::
CString -> IO ()
--------------------------------------------------------------------------------
-- | The different cursor images GLUT supports.
data Cursor
= RightArrow -- ^ Arrow pointing up and to the right.
| LeftArrow -- ^ Arrow pointing up and to the left.
| Info -- ^ Pointing hand.
| Destroy -- ^ Skull & cross bones.
| Help -- ^ Question mark.
| Cycle -- ^ Arrows rotating in a circle.
| Spray -- ^ Spray can.
| Wait -- ^ Wrist watch.
| Text -- ^ Insertion point cursor for text.
| Crosshair -- ^ Simple cross-hair.
| UpDown -- ^ Bi-directional pointing up & down.
| LeftRight -- ^ Bi-directional pointing left & right.
| TopSide -- ^ Arrow pointing to top side.
| BottomSide -- ^ Arrow pointing to bottom side.
| LeftSide -- ^ Arrow pointing to left side.
| RightSide -- ^ Arrow pointing to right side.
| TopLeftCorner -- ^ Arrow pointing to top-left corner.
| TopRightCorner -- ^ Arrow pointing to top-right corner.
| BottomRightCorner -- ^ Arrow pointing to bottom-left corner.
| BottomLeftCorner -- ^ Arrow pointing to bottom-right corner.
| Inherit -- ^ Use parent\'s cursor.
| None -- ^ Invisible cursor.
| FullCrosshair -- ^ Full-screen cross-hair cursor (if possible, otherwise 'Crosshair').
deriving ( Eq, Ord, Show )
marshalCursor :: Cursor -> CInt
marshalCursor x = case x of
RightArrow -> glut_CURSOR_RIGHT_ARROW
LeftArrow -> glut_CURSOR_LEFT_ARROW
Info -> glut_CURSOR_INFO
Destroy -> glut_CURSOR_DESTROY
Help -> glut_CURSOR_HELP
Cycle -> glut_CURSOR_CYCLE
Spray -> glut_CURSOR_SPRAY
Wait -> glut_CURSOR_WAIT
Text -> glut_CURSOR_TEXT
Crosshair -> glut_CURSOR_CROSSHAIR
UpDown -> glut_CURSOR_UP_DOWN
LeftRight -> glut_CURSOR_LEFT_RIGHT
TopSide -> glut_CURSOR_TOP_SIDE
BottomSide -> glut_CURSOR_BOTTOM_SIDE
LeftSide -> glut_CURSOR_LEFT_SIDE
RightSide -> glut_CURSOR_RIGHT_SIDE
TopLeftCorner -> glut_CURSOR_TOP_LEFT_CORNER
TopRightCorner -> glut_CURSOR_TOP_RIGHT_CORNER
BottomRightCorner -> glut_CURSOR_BOTTOM_RIGHT_CORNER
BottomLeftCorner -> glut_CURSOR_BOTTOM_LEFT_CORNER
Inherit -> glut_CURSOR_INHERIT
None -> glut_CURSOR_NONE
FullCrosshair -> glut_CURSOR_FULL_CROSSHAIR
unmarshalCursor :: CInt -> Cursor
unmarshalCursor x
| x == glut_CURSOR_RIGHT_ARROW = RightArrow
| x == glut_CURSOR_LEFT_ARROW = LeftArrow
| x == glut_CURSOR_INFO = Info
| x == glut_CURSOR_DESTROY = Destroy
| x == glut_CURSOR_HELP = Help
| x == glut_CURSOR_CYCLE = Cycle
| x == glut_CURSOR_SPRAY = Spray
| x == glut_CURSOR_WAIT = Wait
| x == glut_CURSOR_TEXT = Text
| x == glut_CURSOR_CROSSHAIR = Crosshair
| x == glut_CURSOR_UP_DOWN = UpDown
| x == glut_CURSOR_LEFT_RIGHT = LeftRight
| x == glut_CURSOR_TOP_SIDE = TopSide
| x == glut_CURSOR_BOTTOM_SIDE = BottomSide
| x == glut_CURSOR_LEFT_SIDE = LeftSide
| x == glut_CURSOR_RIGHT_SIDE = RightSide
| x == glut_CURSOR_TOP_LEFT_CORNER = TopLeftCorner
| x == glut_CURSOR_TOP_RIGHT_CORNER = TopRightCorner
| x == glut_CURSOR_BOTTOM_RIGHT_CORNER = BottomRightCorner
| x == glut_CURSOR_BOTTOM_LEFT_CORNER = BottomLeftCorner
| x == glut_CURSOR_INHERIT = Inherit
| x == glut_CURSOR_NONE = None
| x == glut_CURSOR_FULL_CROSSHAIR = FullCrosshair
| otherwise = error ("unmarshalCursor: illegal value " ++ show x)
--------------------------------------------------------------------------------
-- | Change the cursor image of the /current window/. Each call requests the
-- window system change the cursor appropriately. The cursor image when a window
-- is created is 'Inherit'. The exact cursor images used are implementation
-- dependent. The intent is for the image to convey the meaning of the cursor
-- name. For a top-level window, 'Inherit' uses the default window system
-- cursor.
--
-- /X Implementation Notes:/ GLUT for X uses SGI\'s @_SGI_CROSSHAIR_CURSOR@
-- convention to access a full-screen cross-hair cursor if possible.
cursor :: StateVar Cursor
cursor = makeStateVar getCursor setCursor
setCursor :: Cursor -> IO ()
setCursor = glutSetCursor . marshalCursor
foreign import CALLCONV unsafe "glutSetCursor" glutSetCursor :: CInt -> IO ()
getCursor :: IO Cursor
getCursor = simpleGet unmarshalCursor glut_WINDOW_CURSOR
--------------------------------------------------------------------------------
-- | Setting 'pointerPosition' warps the window system\'s pointer to a new
-- location relative to the origin of the /current window/ by the specified
-- pixel offset, which may be negative. The warp is done immediately.
--
-- If the pointer would be warped outside the screen\'s frame buffer region, the
-- location will be clamped to the nearest screen edge. The window system is
-- allowed to further constrain the pointer\'s location in window system
-- dependent ways.
--
-- Good advice from Xlib\'s @XWarpPointer@ man page: \"There is seldom any
-- reason for calling this function. The pointer should normally be left to the
-- user.\"
pointerPosition :: SettableStateVar Position
pointerPosition =
makeSettableStateVar $ \(Position x y) ->
glutWarpPointer (fromIntegral x) (fromIntegral y)
foreign import CALLCONV unsafe "glutWarpPointer" glutWarpPointer ::
CInt -> CInt -> IO ()
| FranklinChen/hugs98-plus-Sep2006 | packages/GLUT/Graphics/UI/GLUT/Window.hs | bsd-3-clause | 22,355 | 238 | 10 | 3,780 | 2,331 | 1,354 | 977 | -1 | -1 |
module Main where
import Control.DeepSeq
import qualified Criterion.Main as C
import Data.Array.Repa hiding ((++))
import Data.Array.Repa.Eval
import Data.Array.Repa.Repr.ForeignPtr
import Data.Word
import Foreign (castForeignPtr)
import qualified Graphics.Rendering.OpenGL as GL
import System.Environment (getArgs, withArgs)
import qualified Data.Array.Nikola.Backend.CUDA as N
import qualified Mandelbrot.NikolaV1 as MN1
import qualified Mandelbrot.NikolaV2 as MN2
import qualified Mandelbrot.NikolaV3 as MN3
import qualified Mandelbrot.NikolaV4 as MN4
import qualified Mandelbrot.NikolaV5 as MN5
import qualified Mandelbrot.RepaV1 as MR1
import qualified Mandelbrot.RepaV2 as MR2
import qualified Mandelbrot.RepaV3 as MR3
import Config
import ParseConfig
import qualified GUI as G
type R = Double
type RGBA = Word32
type Bitmap r = Array r DIM2 RGBA
type MBitmap r = MVec r RGBA
instance (Shape sh, Source r e) => NFData (Array r sh e) where
rnf arr = deepSeqArray arr ()
instance NFData GL.BufferObject where
rnf pbo = seq pbo ()
defaultView :: G.View
defaultView = G.View { G.left = -0.25
, G.bot = -1.0
, G.right = 0.0
, G.top = -0.75
}
main :: IO ()
main = do
args <- getArgs
case args of
"--benchmark":args' -> doBenchmark args'
_ -> doMandelbrot
doBenchmark :: [String] -> IO ()
doBenchmark args =
withArgs args $ do
G.initializeGLUT False
G.openWindowGLUT disp
N.initializeCUDAGLCtx N.DeviceListAll
repav2Gen <- MR2.mandelbrotImageGenerator
repav3Gen <- MR3.mandelbrotImageGenerator
nikolav2Gen <- MN2.mandelbrotImageGenerator
nikolav3Gen <- MN3.mandelbrotImageGenerator
nikolav4Gen <- MN4.mandelbrotImageGenerator
nikolav5Gen <- MN5.mandelbrotImageGenerator
let generateBitmapFrame :: Backend -> G.View -> Int -> Int -> IO (Bitmap F)
generateBitmapFrame RepaV1 (G.View lowx lowy highx highy) size limit =
MR1.mandelbrotImage lowx lowy highx highy size size limit
generateBitmapFrame RepaV2 (G.View lowx lowy highx highy) size limit =
repav2Gen lowx lowy highx highy size size limit
generateBitmapFrame RepaV3 (G.View lowx lowy highx highy) size limit =
repav3Gen lowx lowy highx highy size size limit
generateBitmapFrame NikolaV1 (G.View lowx lowy highx highy) size limit =
MN1.mandelbrotImage lowx lowy highx highy size size limit
generateBitmapFrame NikolaV2 (G.View lowx lowy highx highy) size limit =
nikolav2Gen lowx lowy highx highy size size limit
generateBitmapFrame NikolaV3 (G.View lowx lowy highx highy) size limit =
nikolav3Gen lowx lowy highx highy size size limit
generateBitmapFrame NikolaV4 (G.View lowx lowy highx highy) size limit =
nikolav4Gen lowx lowy highx highy size size limit
generateBitmapFrame backend _ _ _ =
fail $ "Cannot generate bitmap for" ++ show backend
let generatePBOFrame :: Backend -> G.View -> Int -> Int -> IO GL.BufferObject
generatePBOFrame NikolaV5 (G.View lowx lowy highx highy) size limit =
nikolav5Gen lowx lowy highx highy size size limit
generatePBOFrame backend _ _ _ =
fail $ "Cannot generate PBO for" ++ show backend
C.defaultMain
[C.bench "Repa V1" $ C.nfIO (generateBitmapFrame RepaV1 defaultView size limit)
,C.bench "Repa V2" $ C.nfIO (generateBitmapFrame RepaV2 defaultView size limit)
,C.bench "Repa V3" $ C.nfIO (generateBitmapFrame RepaV3 defaultView size limit)
,C.bench "Nikola V1" $ C.nfIO (generateBitmapFrame NikolaV1 defaultView size limit)
,C.bench "Nikola V2" $ C.nfIO (generateBitmapFrame NikolaV2 defaultView size limit)
,C.bench "Nikola V3" $ C.nfIO (generateBitmapFrame NikolaV3 defaultView size limit)
,C.bench "Nikola V4" $ C.nfIO (generateBitmapFrame NikolaV4 defaultView size limit)
,C.bench "Nikola V5" $ C.nfIO (generatePBOFrame NikolaV5 defaultView size limit)
]
where
size = 512
limit = 255
disp = G.InWindow "Mandelbrot" (size, size) (10, 10)
doMandelbrot :: IO ()
doMandelbrot = do
(config, _) <- getArgs >>= parseArgs defaultConfig
let size = fromIntegral $ fromLJust confSize config
limit = fromIntegral $ fromLJust confLimit config
backend = fromLJust confBackend config
disp = G.InWindow "Mandelbrot" (size, size) (10, 10)
G.display disp defaultView False (frameGenerator backend limit)
frameGenerator :: Backend -> Int -> IO G.FrameGen
frameGenerator RepaV1 limit = return f
where
f :: G.FrameGen
f _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
bmap <- MR1.mandelbrotImage lowx lowy highx highy sizeX sizeY limit
return $ bitmapToPicture bmap
frameGenerator RepaV2 limit = do
gen <- MR2.mandelbrotImageGenerator
return $ f gen
where
f gen _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
bmap <- gen lowx lowy highx highy sizeX sizeY limit
return $ bitmapToPicture bmap
frameGenerator RepaV3 limit = do
gen <- MR3.mandelbrotImageGenerator
return $ f gen
where
f gen _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
bmap <- gen lowx lowy highx highy sizeX sizeY limit
return $ bitmapToPicture bmap
frameGenerator NikolaV1 limit = return f
where
f :: G.FrameGen
f _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
bmap <- MN1.mandelbrotImage lowx lowy highx highy sizeX sizeY limit
return $ bitmapToPicture bmap
frameGenerator NikolaV2 limit = do
gen <- MN2.mandelbrotImageGenerator
return $ f gen
where
f gen _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
bmap <- gen lowx lowy highx highy sizeX sizeY limit
return $ bitmapToPicture bmap
frameGenerator NikolaV3 limit = do
gen <- MN3.mandelbrotImageGenerator
return $ f gen
where
f gen _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
bmap <- gen lowx lowy highx highy sizeX sizeY limit
return $ bitmapToPicture bmap
frameGenerator NikolaV4 limit = do
gen <- MN4.mandelbrotImageGenerator
return $ f gen
where
f gen _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
bmap <- gen lowx lowy highx highy sizeX sizeY limit
return $ bitmapToPicture bmap
frameGenerator NikolaV5 limit = do
gen <- MN5.mandelbrotImageGenerator
return $ f gen
where
f gen _ (G.View lowx lowy highx highy) (sizeX, sizeY) = do
pbo <- gen lowx lowy highx highy sizeX sizeY limit
return $ G.PBO sizeX sizeY pbo
bitmapToPicture :: Bitmap F -> G.Picture
bitmapToPicture arr =
G.bitmapOfForeignPtr h w (castForeignPtr (toForeignPtr arr))
where
h, w :: Int
Z:.h:.w = extent arr
{-
bitmapToPicture :: Bitmap F -> IO G.Picture
bitmapToPicture arr = do
pic@(G.PBO _ _ pbo) <- G.pboOfForeignPtr h w (castForeignPtr (toForeignPtr arr))
ref <- CUGL.registerBuffer pbo CUG.RegisterNone
CUG.mapResources [ref] Nothing
CUG.getMappedPointer ref >>= print
CUG.unmapResources [ref] Nothing
return pic
where
h, w :: Int
Z:.h:.w = extent arr
-}
| mainland/nikola | examples/mandelbrot/Main.hs | bsd-3-clause | 7,380 | 0 | 17 | 1,859 | 2,216 | 1,123 | 1,093 | 147 | 9 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE CPP, TemplateHaskell #-}
{-# LANGUAGE ScopedTypeVariables, TupleSections #-}
module Llvm.AsmHirConversion.MapLabels(compMapping) where
import Llvm.ErrorLoc
#define FLC (FileLoc $(srcLoc))
import qualified Compiler.Hoopl as H
import qualified Control.Monad as Md
import qualified Data.Map as M
import qualified Llvm.Asm.Data as A
import qualified Llvm.Hir.Data as I
import Llvm.Hir.Cast
import Llvm.AsmHirConversion.LabelMapM
import Llvm.Util.Monadic (maybeM, pairM)
import Llvm.AsmHirConversion.TypeConversion
import Data.Maybe (fromJust)
import Control.Monad.Reader
import Llvm.AsmHirConversion.Specialization
import Llvm.Hir.DataLayoutMetrics
import Llvm.Hir.Target
data ReaderData = ReaderData { typedefs :: M.Map A.LocalId A.Type
, funname :: I.Gname
}
type MM = ReaderT ReaderData (LabelMapM H.SimpleUniqueMonad)
typeDefs :: MM (M.Map A.LocalId A.Type)
typeDefs = ask >>= return . typedefs
funName :: MM I.Gname
funName = ask >>= return . funname
withFunName :: I.Gname -> MM a -> MM a
withFunName g f = withReaderT (\(ReaderData x _) -> ReaderData x g) f
stripOffPa :: [A.ParamAttr] -> [A.ParamAttr -> Bool] ->
([I.PAttr], [Maybe A.ParamAttr])
stripOffPa palist preds =
let (l,r) = foldl (\(pl, bl) pa -> let pl0 = filter (\x -> not $ pa x) pl
out = filter pa pl
in case out of
[x] -> (pl0, bl++[Just x])
[] -> (pl0, bl++[Nothing])
) (palist,[]) preds
in (fmap specializePAttr l, r)
{- Ast to Ir conversion -}
isTvector :: MP -> A.Type -> Bool
isTvector mp t = let (ta::I.Utype) = tconvert mp t
in case ta of
(I.UtypeVectorI _) -> True
(I.UtypeVectorF _) -> True
(I.UtypeVectorP _) -> True
_ -> False
getElemPtrIsTvector :: MP -> A.GetElementPtr v -> Bool
getElemPtrIsTvector mp (A.GetElementPtr n (A.Pointer (A.Typed t _)) l) = isTvector mp t
conversionIsTvector :: MP -> A.Conversion v -> Bool
conversionIsTvector mp (A.Conversion _ _ dt) = isTvector mp dt
convert_LabelId :: A.LabelId -> MM H.Label
convert_LabelId x = do { fn <- funName
; lift (labelFor (fn, x))
}
convert_PercentLabel :: A.PercentLabel -> MM H.Label
convert_PercentLabel (A.PercentLabel l) = convert_LabelId l
convert_PercentLabelEx :: I.Gname -> A.PercentLabel -> MM (Maybe H.Label)
convert_PercentLabelEx g (A.PercentLabel l) = convert_LabelIdEx g l
where
convert_LabelIdEx :: I.Gname -> A.LabelId -> MM (Maybe H.Label)
convert_LabelIdEx fn x = lift (getLabel (fn, x))
convert_TargetLabel :: A.TargetLabel -> MM H.Label
convert_TargetLabel (A.TargetLabel tl) = convert_PercentLabel tl
convert_BlockLabel :: A.BlockLabel -> MM H.Label
convert_BlockLabel (A.ImplicitBlockLabel p) =
error $ "ImplicitBlockLabel @" ++ show p
++ " should be normalized away in Asm.Simplification, and should not be leaked to Ast2Ir."
convert_BlockLabel (A.ExplicitBlockLabel b) = convert_LabelId b
convert_ComplexConstant :: A.ComplexConstant -> (MM (I.Const I.Gname))
convert_ComplexConstant (A.Cstruct b fs) = Md.liftM (I.C_struct b)
(mapM convert_TypedConstOrNUll fs)
convert_ComplexConstant (A.Cvector fs) = Md.liftM I.C_vector
(mapM convert_TypedConstOrNUll fs)
convert_ComplexConstant (A.Carray fs) = Md.liftM I.C_array
(mapM convert_TypedConstOrNUll fs)
data Binexp s v where {
Add :: (Maybe I.NoWrap) -> I.Type s I.I -> v -> v -> Binexp s v;
Sub :: (Maybe I.NoWrap) -> I.Type s I.I -> v -> v -> Binexp s v;
Mul :: (Maybe I.NoWrap) -> I.Type s I.I -> v -> v -> Binexp s v;
Udiv :: (Maybe I.Exact) -> I.Type s I.I -> v -> v -> Binexp s v;
Sdiv :: (Maybe I.Exact) -> I.Type s I.I -> v -> v -> Binexp s v;
Urem :: I.Type s I.I -> v -> v -> Binexp s v;
Srem :: I.Type s I.I -> v -> v -> Binexp s v;
Shl :: (Maybe I.NoWrap) -> I.Type s I.I -> v -> v -> Binexp s v;
Lshr :: (Maybe I.Exact) -> I.Type s I.I -> v -> v -> Binexp s v;
Ashr :: (Maybe I.Exact) -> I.Type s I.I -> v -> v -> Binexp s v;
And :: I.Type s I.I -> v -> v -> Binexp s v;
Or :: I.Type s I.I -> v -> v -> Binexp s v;
Xor :: I.Type s I.I -> v -> v -> Binexp s v;
} deriving (Eq, Ord, Show)
data FBinexp s v where {
Fadd :: I.FastMathFlags -> I.Type s I.F -> v -> v -> FBinexp s v;
Fsub :: I.FastMathFlags -> I.Type s I.F -> v -> v -> FBinexp s v;
Fmul :: I.FastMathFlags -> I.Type s I.F -> v -> v -> FBinexp s v;
Fdiv :: I.FastMathFlags -> I.Type s I.F -> v -> v -> FBinexp s v;
Frem :: I.FastMathFlags -> I.Type s I.F -> v -> v -> FBinexp s v;
} deriving (Eq, Ord, Show)
convert_to_Binexp :: (u -> MM v) -> A.IbinExpr u -> MM (Binexp I.ScalarB v)
convert_to_Binexp cvt (A.IbinExpr op cs t u1 u2) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; let ta::I.Type I.ScalarB I.I = dcast FLC $ ((tconvert mp t)::I.Utype)
; return (convert_IbinOp op cs ta u1a u2a)
}
where convert_IbinOp :: A.IbinOp -> [A.TrapFlag] -> I.Type I.ScalarB I.I -> v -> v -> Binexp I.ScalarB v
convert_IbinOp op cs = case op of
A.Add -> Add (getnowrap cs)
A.Sub -> Sub (getnowrap cs)
A.Mul -> Mul (getnowrap cs)
A.Udiv -> Udiv (getexact cs)
A.Sdiv -> Sdiv (getexact cs)
A.Shl -> Shl (getnowrap cs)
A.Lshr -> Lshr (getexact cs)
A.Ashr -> Ashr (getexact cs)
A.Urem -> Urem
A.Srem -> Srem
A.And -> And
A.Or -> Or
A.Xor -> Xor
convert_to_Binexp_V :: (u -> MM v) -> A.IbinExpr u -> MM (Binexp I.VectorB v)
convert_to_Binexp_V cvt (A.IbinExpr op cs t u1 u2) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; let ta::I.Type I.VectorB I.I = dcast FLC $ ((tconvert mp t)::I.Utype)
; return (convert_IbinOp op cs ta u1a u2a)
}
where convert_IbinOp :: A.IbinOp -> [A.TrapFlag] -> I.Type I.VectorB I.I -> v -> v -> Binexp I.VectorB v
convert_IbinOp op cs = case op of
A.Add -> Add (getnowrap cs)
A.Sub -> Sub (getnowrap cs)
A.Mul -> Mul (getnowrap cs)
A.Udiv -> Udiv (getexact cs)
A.Sdiv -> Sdiv (getexact cs)
A.Shl -> Shl (getnowrap cs)
A.Lshr -> Lshr (getexact cs)
A.Ashr -> Ashr (getexact cs)
A.Urem -> Urem
A.Srem -> Srem
A.And -> And
A.Or -> Or
A.Xor -> Xor
getnowrap :: [A.TrapFlag] -> Maybe I.NoWrap
getnowrap x = case x of
[A.Nsw] -> Just I.Nsw
[A.Nuw] -> Just I.Nuw
[A.Nsw,A.Nuw] -> Just I.Nsuw
[A.Nuw,A.Nsw] -> Just I.Nsuw
[] -> Nothing
_ -> error ("irrefutable error1 " ++ show x)
getexact :: [A.TrapFlag] -> Maybe I.Exact
getexact x = case x of
[A.Exact] -> Just I.Exact
[] -> Nothing
_ -> error "irrefutable error2"
convert_to_FBinexp :: (u -> MM v) -> A.FbinExpr u -> (MM (FBinexp I.ScalarB v))
convert_to_FBinexp cvt (A.FbinExpr op cs t u1 u2) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; let ta::I.Type I.ScalarB I.F = dcast FLC $ ((tconvert mp t)::I.Utype)
; return ((convertFop op) cs ta u1a u2a)
}
where
convertFop o = case o of
A.Fadd -> Fadd
A.Fsub -> Fsub
A.Fmul -> Fmul
A.Fdiv -> Fdiv
A.Frem -> Frem
convert_to_FBinexp_V :: (u -> MM v) -> A.FbinExpr u -> (MM (FBinexp I.VectorB v))
convert_to_FBinexp_V cvt (A.FbinExpr op cs t u1 u2) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; let ta::I.Type I.VectorB I.F = dcast FLC $ ((tconvert mp t)::I.Utype)
; return ((convertFop op) cs ta u1a u2a)
}
where
convertFop o = case o of
A.Fadd -> Fadd
A.Fsub -> Fsub
A.Fmul -> Fmul
A.Fdiv -> Fdiv
A.Frem -> Frem
convert_to_Conversion :: (u -> MM v) -> A.Conversion u -> (MM (I.Conversion I.ScalarB v))
convert_to_Conversion cvt (A.Conversion op (A.Typed t u) dt) =
do { mp <- typeDefs
; u1 <- cvt u
; let (t1::I.Utype) = tconvert mp t
(dt1::I.Utype) = tconvert mp dt
newOp = case op of
A.Trunc -> let (t2::I.Type I.ScalarB I.I) = dcast FLC t1
(dt2::I.Type I.ScalarB I.I) = dcast FLC dt1
in I.Trunc (I.T t2 u1) dt2
A.Zext -> let (t2::I.Type I.ScalarB I.I) = dcast FLC t1
(dt2::I.Type I.ScalarB I.I) = dcast FLC dt1
in I.Zext (I.T t2 u1) dt2
A.Sext -> let (t2::I.Type I.ScalarB I.I) = dcast FLC t1
(dt2::I.Type I.ScalarB I.I) = dcast FLC dt1
in I.Sext (I.T t2 u1) dt2
A.FpTrunc -> let (t2::I.Type I.ScalarB I.F) = dcast FLC t1
(dt2::I.Type I.ScalarB I.F) = dcast FLC dt1
in I.FpTrunc (I.T t2 u1) dt2
A.FpExt -> let (t2::I.Type I.ScalarB I.F) = dcast FLC t1
(dt2::I.Type I.ScalarB I.F) = dcast FLC dt1
in I.FpExt (I.T t2 u1) dt2
A.FpToUi -> let (t2::I.Type I.ScalarB I.F) = dcast FLC t1
(dt2::I.Type I.ScalarB I.I) = dcast FLC dt1
in I.FpToUi (I.T t2 u1) dt2
A.FpToSi -> let (t2::I.Type I.ScalarB I.F) = dcast FLC t1
(dt2::I.Type I.ScalarB I.I) = dcast FLC dt1
in I.FpToSi (I.T t2 u1) dt2
A.UiToFp -> let (t2::I.Type I.ScalarB I.I) = dcast FLC t1
(dt2::I.Type I.ScalarB I.F) = dcast FLC dt1
in I.UiToFp (I.T t2 u1) dt2
A.SiToFp -> let (t2::I.Type I.ScalarB I.I) = dcast FLC t1
(dt2::I.Type I.ScalarB I.F) = dcast FLC dt1
in I.SiToFp (I.T t2 u1) dt2
A.PtrToInt -> let (t2::I.Type I.ScalarB I.P) = dcast FLC t1
(dt2::I.Type I.ScalarB I.I) = dcast FLC dt1
in I.PtrToInt (I.T t2 u1) dt2
A.IntToPtr -> let (t2::I.Type I.ScalarB I.I) = dcast FLC t1
(dt2::I.Type I.ScalarB I.P) = dcast FLC dt1
in I.IntToPtr (I.T t2 u1) dt2
A.Bitcast -> let (t2::I.Dtype) = dcast FLC t1
(dt2::I.Dtype) = dcast FLC dt1
in I.Bitcast (I.T t2 u1) dt2
A.AddrSpaceCast -> let (t2::I.Type I.ScalarB I.P) = dcast FLC t1
(dt2::I.Type I.ScalarB I.P) = dcast FLC dt1
in I.AddrSpaceCast (I.T t2 u1) dt2
; return newOp
}
convert_to_Conversion_V :: (u -> MM v) -> A.Conversion u -> (MM (I.Conversion I.VectorB v))
convert_to_Conversion_V cvt (A.Conversion op (A.Typed t u) dt) =
do { mp <- typeDefs
; u1 <- cvt u
; let (t1::I.Utype) = tconvert mp t
(dt1::I.Utype) = tconvert mp dt
newOp = case op of
A.Trunc -> let (t2::I.Type I.VectorB I.I) = dcast FLC t1
(dt2::I.Type I.VectorB I.I) = dcast FLC dt1
in I.Trunc (I.T t2 u1) dt2
A.Zext -> let (t2::I.Type I.VectorB I.I) = dcast FLC t1
(dt2::I.Type I.VectorB I.I) = dcast FLC dt1
in I.Zext (I.T t2 u1) dt2
A.Sext -> let (t2::I.Type I.VectorB I.I) = dcast FLC t1
(dt2::I.Type I.VectorB I.I) = dcast FLC dt1
in I.Sext (I.T t2 u1) dt2
A.FpTrunc -> let (t2::I.Type I.VectorB I.F) = dcast FLC t1
(dt2::I.Type I.VectorB I.F) = dcast FLC dt1
in I.FpTrunc (I.T t2 u1) dt2
A.FpExt -> let (t2::I.Type I.VectorB I.F) = dcast FLC t1
(dt2::I.Type I.VectorB I.F) = dcast FLC dt1
in I.FpExt (I.T t2 u1) dt2
A.FpToUi -> let (t2::I.Type I.VectorB I.F) = dcast FLC t1
(dt2::I.Type I.VectorB I.I) = dcast FLC dt1
in I.FpToUi (I.T t2 u1) dt2
A.FpToSi -> let (t2::I.Type I.VectorB I.F) = dcast FLC t1
(dt2::I.Type I.VectorB I.I) = dcast FLC dt1
in I.FpToSi (I.T t2 u1) dt2
A.UiToFp -> let (t2::I.Type I.VectorB I.I) = dcast FLC t1
(dt2::I.Type I.VectorB I.F) = dcast FLC dt1
in I.UiToFp (I.T t2 u1) dt2
A.SiToFp -> let (t2::I.Type I.VectorB I.I) = dcast FLC t1
(dt2::I.Type I.VectorB I.F) = dcast FLC dt1
in I.SiToFp (I.T t2 u1) dt2
A.PtrToInt -> let (t2::I.Type I.VectorB I.P) = dcast FLC t1
(dt2::I.Type I.VectorB I.I) = dcast FLC dt1
in I.PtrToInt (I.T t2 u1) dt2
A.IntToPtr -> let (t2::I.Type I.VectorB I.I) = dcast FLC t1
(dt2::I.Type I.VectorB I.P) = dcast FLC dt1
in I.IntToPtr (I.T t2 u1) dt2
A.Bitcast -> let (t2::I.Dtype) = dcast FLC t1
(dt2::I.Dtype) = dcast FLC dt1
in I.Bitcast (I.T t2 u1) dt2
A.AddrSpaceCast -> let (t2::I.Type I.VectorB I.P) = dcast FLC t1
(dt2::I.Type I.VectorB I.P) = dcast FLC dt1
in I.AddrSpaceCast (I.T t2 u1) dt2
; return newOp
}
convert_to_GetElementPtr :: (u -> MM v) -> (u -> MM idx) -> A.GetElementPtr u -> (MM (I.GetElementPtr I.ScalarB v idx))
convert_to_GetElementPtr cvt cvidx (A.GetElementPtr b (A.Pointer (A.Typed t u)) us) =
do { mp <- typeDefs
; ua <- cvt u
; let (ta::I.Type I.ScalarB I.P) = dcast FLC ((tconvert mp t)::I.Utype)
; usa <- mapM convert_Tv_Tint us
; return $ I.GetElementPtr b (I.T ta ua) usa
}
where
convert_Tv_Tint (A.Typed t v) =
do { mp <- typeDefs
; va <- cvidx v
; let (ta::I.Type I.ScalarB I.I) = dcast FLC ((tconvert mp t)::I.Utype)
; return $ I.T ta va
}
convert_to_GetElementPtr_V :: (u -> MM v) -> (u -> MM idx) -> A.GetElementPtr u -> (MM (I.GetElementPtr I.VectorB v idx))
convert_to_GetElementPtr_V cvt cvidx (A.GetElementPtr b (A.Pointer (A.Typed t u)) us) =
do { mp <- typeDefs
; ua <- cvt u
; let (ta::I.Type I.VectorB I.P) = dcast FLC ((tconvert mp t)::I.Utype)
; usa <- mapM (convert_Tv_Tint) us
; return $ I.GetElementPtr b (I.T ta ua) usa
}
where
convert_Tv_Tint (A.Typed te v) = do { mp <- typeDefs
; va <- cvidx v
; let (ta::I.Utype) = tconvert mp te
; return $ I.T (dcast FLC ta) va
}
cast_to_EitherScalarOrVectorI :: FileLoc -> I.T I.Utype v ->
Either (I.T (I.Type I.ScalarB I.I) v) (I.T (I.Type I.VectorB I.I) v)
cast_to_EitherScalarOrVectorI flc (I.T t v) = case t of
I.UtypeScalarI e -> Left $ I.T e v
I.UtypeVectorI e -> Right $ I.T e v
_ -> errorLoc flc "$$$$"
convert_to_Select_I :: (u -> MM v) -> A.Select u -> (MM (I.Select I.ScalarB I.I v))
convert_to_Select_I cvt (A.Select (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.ScalarB I.I) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.I) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.ScalarB I.I) = dcast FLC ((tconvert mp t3)::I.Utype)
; return $ I.Select (Left (I.T t1a u1a)) (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_Select_VI :: (u -> MM v) -> A.Select u -> (MM (I.Select I.VectorB I.I v))
convert_to_Select_VI cvt (A.Select (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let t1a = cast_to_EitherScalarOrVectorI FLC (I.T ((tconvert mp t1)::I.Utype) u1a)
(t2a::I.Type I.VectorB I.I) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.VectorB I.I) = dcast FLC ((tconvert mp t3)::I.Utype)
; return $ I.Select t1a (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_Select_F :: (u -> MM v) -> A.Select u -> (MM (I.Select I.ScalarB I.F v))
convert_to_Select_F cvt (A.Select (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.ScalarB I.I) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.F) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.ScalarB I.F) = dcast FLC ((tconvert mp t3)::I.Utype)
; return $ I.Select (Left (I.T t1a u1a)) (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_Select_VF :: (u -> MM v) -> A.Select u -> (MM (I.Select I.VectorB I.F v))
convert_to_Select_VF cvt (A.Select (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let t1a = cast_to_EitherScalarOrVectorI FLC (I.T ((tconvert mp t1)::I.Utype) u1a)
(t2a::I.Type I.VectorB I.F) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.VectorB I.F) = dcast FLC ((tconvert mp t3)::I.Utype)
; return $ I.Select t1a (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_Select_P :: (u -> MM v) -> A.Select u -> (MM (I.Select I.ScalarB I.P v))
convert_to_Select_P cvt (A.Select (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.ScalarB I.I) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.P) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.ScalarB I.P) = dcast FLC ((tconvert mp t3)::I.Utype)
; return $ I.Select (Left (I.T t1a u1a)) (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_Select_VP :: (u -> MM v) -> A.Select u -> (MM (I.Select I.VectorB I.P v))
convert_to_Select_VP cvt (A.Select (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let t1a = cast_to_EitherScalarOrVectorI FLC (I.T ((tconvert mp t1)::I.Utype) u1a)
(t2a::I.Type I.VectorB I.P) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.VectorB I.P) = dcast FLC ((tconvert mp t3)::I.Utype)
; return $ I.Select t1a (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_Select_Record :: (u -> MM v) -> A.Select u -> (MM (I.Select I.FirstClassB I.D v))
convert_to_Select_Record cvt (A.Select (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.ScalarB I.I) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.FirstClassB I.D) = squeeze FLC (dcast FLC ((tconvert mp t2)::I.Utype))
(t3a::I.Type I.FirstClassB I.D) = squeeze FLC (dcast FLC ((tconvert mp t3)::I.Utype))
; return $ I.Select (Left (I.T t1a u1a)) (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_Icmp :: (u -> MM v) -> A.Icmp u -> MM (I.Icmp I.ScalarB v)
convert_to_Icmp cvt (A.Icmp op t u1 u2) =
do { mp <- typeDefs
; let (t1::I.IntOrPtrType I.ScalarB) = dcast FLC ((tconvert mp t)::I.Utype)
; u1a <- cvt u1
; u2a <- cvt u2
; return (I.Icmp op t1 u1a u2a)
}
convert_to_Icmp_V :: (u -> MM v) -> A.Icmp u -> MM (I.Icmp I.VectorB v)
convert_to_Icmp_V cvt (A.Icmp op t u1 u2) =
do { mp <- typeDefs
; let (t1::I.IntOrPtrType I.VectorB) = dcast FLC ((tconvert mp t)::I.Utype)
; u1a <- cvt u1
; u2a <- cvt u2
; return (I.Icmp op t1 u1a u2a)
}
convert_to_Fcmp :: (u -> MM v) -> A.Fcmp u -> MM (I.Fcmp I.ScalarB v)
convert_to_Fcmp cvt (A.Fcmp op t u1 u2) =
do { mp <- typeDefs
; let (t1::I.Type I.ScalarB I.F) = dcast FLC ((tconvert mp t)::I.Utype)
; u1a <- cvt u1
; u2a <- cvt u2
; return (I.Fcmp op t1 u1a u2a)
}
convert_to_Fcmp_V :: (u -> MM v) -> A.Fcmp u -> MM (I.Fcmp I.VectorB v)
convert_to_Fcmp_V cvt (A.Fcmp op t u1 u2) =
do { mp <- typeDefs
; let (t1::I.Type I.VectorB I.F) = dcast FLC ((tconvert mp t)::I.Utype)
; u1a <- cvt u1
; u2a <- cvt u2
; return (I.Fcmp op t1 u1a u2a)
}
convert_to_ShuffleVector_I :: (u -> MM v) -> A.ShuffleVector u -> MM (I.ShuffleVector I.I v)
convert_to_ShuffleVector_I cvt (A.ShuffleVector (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.VectorB I.I) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.VectorB I.I) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.VectorB I.I) = dcast FLC ((tconvert mp t3)::I.Utype)
; return (I.ShuffleVector (I.T t1a u1a) (I.T t2a u2a) (I.T t3a u3a))
}
convert_to_ShuffleVector_F :: (u -> MM v) -> A.ShuffleVector u -> MM (I.ShuffleVector I.F v)
convert_to_ShuffleVector_F cvt (A.ShuffleVector (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.VectorB I.F) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.VectorB I.F) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.VectorB I.I) = dcast FLC ((tconvert mp t3)::I.Utype)
; return (I.ShuffleVector (I.T t1a u1a) (I.T t2a u2a) (I.T t3a u3a))
}
convert_to_ShuffleVector_P :: (u -> MM v) -> A.ShuffleVector u -> MM (I.ShuffleVector I.P v)
convert_to_ShuffleVector_P cvt (A.ShuffleVector (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.VectorB I.P) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.VectorB I.P) = dcast FLC ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.VectorB I.I) = dcast FLC ((tconvert mp t3)::I.Utype)
; return (I.ShuffleVector (I.T t1a u1a) (I.T t2a u2a) (I.T t3a u3a))
}
convert_to_ExtractValue :: (u -> MM v) -> A.ExtractValue u -> MM (I.ExtractValue v)
convert_to_ExtractValue cvt (A.ExtractValue (A.Typed t u) s) =
do { mp <- typeDefs
; let (ta::I.Type I.RecordB I.D) = dcast FLC ((tconvert mp t)::I.Utype)
; ua <- cvt u
; return (I.ExtractValue (I.T ta ua) s)
}
convert_to_InsertValue :: (u -> MM v) -> A.InsertValue u -> MM (I.InsertValue v)
convert_to_InsertValue cvt (A.InsertValue (A.Typed t1 u1) (A.Typed t2 u2) s) =
do { mp <- typeDefs
; let (t1a::I.Type I.RecordB I.D) = dcast FLC ((tconvert mp t1)::I.Utype)
(t2a::I.Dtype) = dcast FLC ((tconvert mp t2)::I.Utype)
; u1a <- cvt u1
; u2a <- cvt u2
; return $ I.InsertValue (I.T t1a u1a) (I.T t2a u2a) s
}
convert_to_ExtractElement_I :: (u -> MM v) -> A.ExtractElement u -> MM (I.ExtractElement I.I v)
convert_to_ExtractElement_I cvt (A.ExtractElement (A.Typed t1 u1) (A.Typed t2 u2)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; let (t1a::I.Type I.VectorB I.I) = dcast FLC $ ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.I) = dcast FLC $ ((tconvert mp t2)::I.Utype)
; return $ I.ExtractElement (I.T t1a u1a) (I.T t2a u2a)
}
convert_to_ExtractElement_F :: (u -> MM v) -> A.ExtractElement u -> MM (I.ExtractElement I.F v)
convert_to_ExtractElement_F cvt (A.ExtractElement (A.Typed t1 u1) (A.Typed t2 u2)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; let (t1a::I.Type I.VectorB I.F) = dcast FLC $ ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.I) = dcast FLC $ ((tconvert mp t2)::I.Utype)
; return $ I.ExtractElement (I.T t1a u1a) (I.T t2a u2a)
}
convert_to_ExtractElement_P :: (u -> MM v) -> A.ExtractElement u -> MM (I.ExtractElement I.P v)
convert_to_ExtractElement_P cvt (A.ExtractElement (A.Typed t1 u1) (A.Typed t2 u2)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; let (t1a::I.Type I.VectorB I.P) = dcast FLC $ ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.I) = dcast FLC $ ((tconvert mp t2)::I.Utype)
; return $ I.ExtractElement (I.T t1a u1a) (I.T t2a u2a)
}
convert_to_InsertElement_I :: (u -> MM v) -> A.InsertElement u -> MM (I.InsertElement I.I v)
convert_to_InsertElement_I cvt (A.InsertElement (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.VectorB I.I) = dcast FLC $ ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.I) = dcast FLC $ ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.ScalarB I.I) = dcast FLC $ ((tconvert mp t3)::I.Utype)
; return $ I.InsertElement (I.T t1a u1a) (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_InsertElement_F :: (u -> MM v) -> A.InsertElement u -> MM (I.InsertElement I.F v)
convert_to_InsertElement_F cvt (A.InsertElement (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.VectorB I.F) = dcast FLC $ ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.F) = dcast FLC $ ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.ScalarB I.I) = dcast FLC $ ((tconvert mp t3)::I.Utype)
; return $ I.InsertElement (I.T t1a u1a) (I.T t2a u2a) (I.T t3a u3a)
}
convert_to_InsertElement_P :: (u -> MM v) -> A.InsertElement u -> MM (I.InsertElement I.P v)
convert_to_InsertElement_P cvt (A.InsertElement (A.Typed t1 u1) (A.Typed t2 u2) (A.Typed t3 u3)) =
do { mp <- typeDefs
; u1a <- cvt u1
; u2a <- cvt u2
; u3a <- cvt u3
; let (t1a::I.Type I.VectorB I.P) = dcast FLC $ ((tconvert mp t1)::I.Utype)
(t2a::I.Type I.ScalarB I.P) = dcast FLC $ ((tconvert mp t2)::I.Utype)
(t3a::I.Type I.ScalarB I.I) = dcast FLC $ ((tconvert mp t3)::I.Utype)
; return $ I.InsertElement (I.T t1a u1a) (I.T t2a u2a) (I.T t3a u3a)
}
convert_SimpleConst :: A.SimpleConstant -> I.Const I.Gname
convert_SimpleConst x = case x of
A.CpInt s -> I.C_int s
A.CpUhexInt s -> I.C_uhex_int s
A.CpShexInt s -> I.C_shex_int s
A.CpFloat s -> I.C_float s
A.CpNull -> I.C_null
A.CpUndef -> I.C_undef
A.CpTrue -> I.C_true
A.CpFalse -> I.C_false
A.CpZeroInitializer -> I.C_zeroinitializer
A.CpGlobalAddr s -> I.C_globalAddr (specializeGlobalId s)
A.CpStr s -> I.C_str s
A.CpBconst s -> convert_Bconst s
convert_Bconst :: A.BinaryConstant -> I.Const I.Gname
convert_Bconst x = case x of
A.BconstUint8 s -> I.C_u8 s
A.BconstUint16 s -> I.C_u16 s
A.BconstUint32 s -> I.C_u32 s
A.BconstUint64 s -> I.C_u64 s
A.BconstUint96 s -> I.C_u96 s
A.BconstUint128 s -> I.C_u128 s
A.BconstInt8 s -> I.C_s8 s
A.BconstInt16 s -> I.C_s16 s
A.BconstInt32 s -> I.C_s32 s
A.BconstInt64 s -> I.C_s64 s
A.BconstInt96 s -> I.C_s96 s
A.BconstInt128 s -> I.C_s128 s
convert_Const :: A.Const -> MM (I.Const I.Gname)
convert_Const x =
let cvt = convert_Const
in case x of
A.C_simple a -> return $ convert_SimpleConst a
A.C_complex a -> convert_ComplexConstant a
A.C_labelId a -> Md.liftM I.C_labelId (convert_LabelId a)
A.C_blockAddress g a -> do { a' <- convert_PercentLabelEx (specializeGlobalId g) a
; case a' of
Just a'' -> return $ I.C_block (specializeGlobalId g) a''
Nothing -> return $ I.C_u32 0 -- we don't report error here:-) because we only need the labal mapping.
}
A.C_binexp (A.Ie a@(A.IbinExpr _ _ t _ _)) ->
do { mp <- typeDefs
; if isTvector mp t then
do { x <- convert_to_Binexp_V cvt a
; let y = case x of
Add n ta v1a v2a -> I.C_add_V n ta v1a v2a
Sub n ta v1a v2a -> I.C_sub_V n ta v1a v2a
Mul n ta v1a v2a -> I.C_mul_V n ta v1a v2a
Udiv n ta v1a v2a -> I.C_udiv_V n ta v1a v2a
Sdiv n ta v1a v2a -> I.C_sdiv_V n ta v1a v2a
Urem ta v1a v2a -> I.C_urem_V ta v1a v2a
Srem ta v1a v2a -> I.C_srem_V ta v1a v2a
Shl n ta v1a v2a -> I.C_shl_V n ta v1a v2a
Lshr n ta v1a v2a -> I.C_lshr_V n ta v1a v2a
Ashr n ta v1a v2a -> I.C_ashr_V n ta v1a v2a
And ta v1a v2a -> I.C_and_V ta v1a v2a
Or ta v1a v2a -> I.C_or_V ta v1a v2a
Xor ta v1a v2a -> I.C_xor_V ta v1a v2a
; return y
}
else
do { x <- convert_to_Binexp cvt a
; let y = case x of
Add n ta v1a v2a -> I.C_add n ta v1a v2a
Sub n ta v1a v2a -> I.C_sub n ta v1a v2a
Mul n ta v1a v2a -> I.C_mul n ta v1a v2a
Udiv n ta v1a v2a -> I.C_udiv n ta v1a v2a
Sdiv n ta v1a v2a -> I.C_sdiv n ta v1a v2a
Urem ta v1a v2a -> I.C_urem ta v1a v2a
Srem ta v1a v2a -> I.C_srem ta v1a v2a
Shl n ta v1a v2a -> I.C_shl n ta v1a v2a
Lshr n ta v1a v2a -> I.C_lshr n ta v1a v2a
Ashr n ta v1a v2a -> I.C_ashr n ta v1a v2a
And ta v1a v2a -> I.C_and ta v1a v2a
Or ta v1a v2a -> I.C_or ta v1a v2a
Xor ta v1a v2a -> I.C_xor ta v1a v2a
; return y
}
}
A.C_binexp (A.Fe a@(A.FbinExpr _ _ t _ _)) ->
do { mp <- typeDefs
; if isTvector mp t then
do { x <- convert_to_FBinexp_V cvt a
; let y = case x of
Fadd n ta v1a v2a -> I.C_fadd_V n ta v1a v2a
Fsub n ta v1a v2a -> I.C_fsub_V n ta v1a v2a
Fmul n ta v1a v2a -> I.C_fmul_V n ta v1a v2a
Fdiv n ta v1a v2a -> I.C_fdiv_V n ta v1a v2a
Frem n ta v1a v2a -> I.C_frem_V n ta v1a v2a
; return y
}
else
do { x <- convert_to_FBinexp cvt a
; let y = case x of
Fadd n ta v1a v2a -> I.C_fadd n ta v1a v2a
Fsub n ta v1a v2a -> I.C_fsub n ta v1a v2a
Fmul n ta v1a v2a -> I.C_fmul n ta v1a v2a
Fdiv n ta v1a v2a -> I.C_fdiv n ta v1a v2a
Frem n ta v1a v2a -> I.C_frem n ta v1a v2a
; return y
}
}
A.C_conv a ->
do { mp <- typeDefs
; if conversionIsTvector mp a then
do { x <- convert_to_Conversion_V cvt a
; let y = case x of
I.Trunc tv dt -> I.C_trunc_V tv dt
I.Zext tv dt -> I.C_zext_V tv dt
I.Sext tv dt -> I.C_sext_V tv dt
I.FpTrunc tv dt -> I.C_fptrunc_V tv dt
I.FpExt tv dt -> I.C_fpext_V tv dt
I.FpToUi tv dt -> I.C_fptoui_V tv dt
I.FpToSi tv dt -> I.C_fptosi_V tv dt
I.UiToFp tv dt -> I.C_uitofp_V tv dt
I.SiToFp tv dt -> I.C_sitofp_V tv dt
I.PtrToInt tv dt -> I.C_ptrtoint_V tv dt
I.IntToPtr tv dt -> I.C_inttoptr_V tv dt
I.Bitcast tv dt -> I.C_bitcast tv dt
I.AddrSpaceCast tv dt -> I.C_addrspacecast_V tv dt
; return y
}
else
do { x <- convert_to_Conversion cvt a
; let y = case x of
I.Trunc tv dt -> I.C_trunc tv dt
I.Zext tv dt -> I.C_zext tv dt
I.Sext tv dt -> I.C_sext tv dt
I.FpTrunc tv dt -> I.C_fptrunc tv dt
I.FpExt tv dt -> I.C_fpext tv dt
I.FpToUi tv dt -> I.C_fptoui tv dt
I.FpToSi tv dt -> I.C_fptosi tv dt
I.UiToFp tv dt -> I.C_uitofp tv dt
I.SiToFp tv dt -> I.C_sitofp tv dt
I.PtrToInt tv dt -> I.C_ptrtoint tv dt
I.IntToPtr tv dt -> I.C_inttoptr tv dt
I.Bitcast tv dt -> I.C_bitcast tv dt
I.AddrSpaceCast tv dt -> I.C_addrspacecast tv dt
; return y
}
}
A.C_gep a ->
do { mp <- typeDefs
; if getElemPtrIsTvector mp a then
do { (I.GetElementPtr b t idx) <- convert_to_GetElementPtr_V convert_Const convert_Const a
; return $ I.C_getelementptr_V b t idx
}
else
do { (I.GetElementPtr b t idx) <- convert_to_GetElementPtr convert_Const convert_Const a
; return $ I.C_getelementptr b t idx
}
}
A.C_select a@(A.Select _ (A.Typed t _) _) ->
do { mp <- typeDefs
; case matchType mp t of
Tk_VectorI -> Md.liftM I.C_select_VI (convert_to_Select_VI cvt a)
Tk_ScalarI -> Md.liftM I.C_select_I (convert_to_Select_I cvt a)
Tk_VectorF -> Md.liftM I.C_select_VF (convert_to_Select_VF cvt a)
Tk_ScalarF -> Md.liftM I.C_select_F (convert_to_Select_F cvt a)
Tk_VectorP -> Md.liftM I.C_select_VP (convert_to_Select_VP cvt a)
Tk_ScalarP -> Md.liftM I.C_select_P (convert_to_Select_P cvt a)
Tk_RecordD -> do { (I.Select (Left cnd) t f) <- convert_to_Select_Record cvt a
; return $ I.C_select_First cnd t f
}
}
A.C_icmp a@(A.Icmp _ t _ _) ->
do { mp <- typeDefs
; if isTvector mp t then Md.liftM I.C_icmp_V (convert_to_Icmp_V cvt a)
else Md.liftM I.C_icmp (convert_to_Icmp cvt a)
}
A.C_fcmp a@(A.Fcmp _ t _ _) ->
do { mp <- typeDefs
; if isTvector mp t then Md.liftM I.C_fcmp_V (convert_to_Fcmp_V cvt a)
else Md.liftM I.C_fcmp (convert_to_Fcmp cvt a)
}
A.C_shufflevector a@(A.ShuffleVector (A.Typed t _) _ _) ->
do { mp <- typeDefs
; case matchType mp t of
Tk_VectorI -> Md.liftM I.C_shufflevector_I (convert_to_ShuffleVector_I cvt a)
Tk_VectorF -> Md.liftM I.C_shufflevector_F (convert_to_ShuffleVector_F cvt a)
Tk_VectorP -> Md.liftM I.C_shufflevector_P (convert_to_ShuffleVector_P cvt a)
}
A.C_extractvalue a -> Md.liftM I.C_extractvalue (convert_to_ExtractValue cvt a)
A.C_insertvalue a -> Md.liftM I.C_insertvalue (convert_to_InsertValue cvt a)
A.C_extractelement a@(A.ExtractElement (A.Typed t _) _) ->
do { mp <- typeDefs
; case matchType mp t of
Tk_VectorI -> Md.liftM I.C_extractelement_I (convert_to_ExtractElement_I cvt a)
Tk_VectorF -> Md.liftM I.C_extractelement_F (convert_to_ExtractElement_F cvt a)
Tk_VectorP -> Md.liftM I.C_extractelement_P (convert_to_ExtractElement_P cvt a)
}
A.C_insertelement a@(A.InsertElement (A.Typed t _) _ _) ->
do { mp <- typeDefs
; case matchType mp t of
Tk_VectorI -> Md.liftM I.C_insertelement_I (convert_to_InsertElement_I cvt a)
Tk_VectorF -> Md.liftM I.C_insertelement_F (convert_to_InsertElement_F cvt a)
Tk_VectorP -> Md.liftM I.C_insertelement_P (convert_to_InsertElement_P cvt a)
}
convert_MdName :: A.MdName -> (MM I.MdName)
convert_MdName (A.MdName s) = return $ I.MdName s
convert_MdNode :: A.MdNode -> (MM I.MdNode)
convert_MdNode (A.MdNode s) = return $ I.MdNode s
convert_MdRef :: A.MdRef -> MM I.MdRef
convert_MdRef x = case x of
A.MdRefName n -> Md.liftM I.MdRefName (convert_MdName n)
A.MdRefNode n -> Md.liftM I.MdRefNode (convert_MdNode n)
convert_MetaConst :: A.MetaConst -> MM (I.MetaConst I.Gname)
convert_MetaConst (A.McStruct c) = Md.liftM I.McStruct (mapM convert_MetaKindedConst c)
convert_MetaConst (A.McString s) = return $ I.McString s
convert_MetaConst (A.McMdRef n) = Md.liftM I.McMdRef (convert_MdRef n)
convert_MetaConst (A.McSsa i) = return $ I.McSsa (sLid i)
convert_MetaConst (A.McSimple sc) = Md.liftM I.McSimple (convert_Const sc)
convert_MetaKindedConst :: A.MetaKindedConst -> MM (I.MetaKindedConst I.Gname)
convert_MetaKindedConst x =
do { mp <- typeDefs
; case x of
(A.MetaKindedConst mk mc) -> Md.liftM (I.MetaKindedConst (tconvert mp mk)) (convert_MetaConst mc)
A.UnmetaKindedNull -> return I.UnmetaKindedNull
}
convert_FunPtr :: A.FunName -> MM (I.FunPtr I.Gname)
convert_FunPtr fn =
case fn of
A.FunNameGlobal g -> case g of
A.GolG g0 -> return $ I.FunId $ specializeGlobalId g0
A.GolL l0 -> return $ I.FunSsa (sLid l0)
A.FunNameBitcast tv t ->
do { mp <- typeDefs
; (I.T st c) <- convert_to_DtypedConst tv
; let t1::I.Utype = tconvert mp t
; return $ I.FunIdBitcast (I.T st c) (dcast FLC t1)
}
A.FunNameInttoptr tv t ->
do { mp <- typeDefs
; (I.T st c) <- convert_to_DtypedConst tv
; let t1::I.Utype = tconvert mp t
; return $ I.FunIdInttoptr (I.T st c) (dcast FLC t1)
}
A.FunName_null -> return I.Fun_null
A.FunName_undef -> return I.Fun_undef
convert_FunId :: A.FunName -> MM I.Gname
convert_FunId (A.FunNameGlobal (A.GolG g)) = return $ specializeGlobalId g
convert_FunId x = errorLoc FLC $ show x
convert_Value :: A.Value -> MM (I.Value I.Gname)
convert_Value (A.Val_local a) = return $ I.Val_ssa (sLid a)
convert_Value (A.Val_const a) = Md.liftM I.Val_const (convert_Const a)
convert_to_Minst :: A.CallSite -> MM (Maybe (I.Minst I.Gname))
convert_to_Minst x = case x of
(A.CallSiteFun cc pa t fn aps fa) | any isMetaParam aps ->
do { mp <- typeDefs
; fna <- convert_FunId fn
; let ert = A.splitCallReturnType t
; apsa <- mapM convert_MetaParam aps
; return (Just $ specializeMinst
$ I.Minst (I.CallSiteTypeRet $ dcast FLC ((tconvert mp (fst ert))::I.Utype)) fna apsa)
}
_ -> return Nothing
convert_to_CallFunInterface :: A.TailCall -> A.CallSite
-> MM (Bool, I.FunPtr I.Gname, I.CallFunInterface I.Gname)
convert_to_CallFunInterface tc (A.CallSiteFun cc pa t fn aps fa) =
do { mp <- typeDefs
; let ert = A.splitCallReturnType t
; erta <- eitherRet (fmap specializeRetAttr pa) ert aps
; fna <- convert_FunPtr fn
; apsa <- mapM convert_ActualParam aps
; return (fst ert == A.Tvoid, fna, I.CallFunInterface { I.cfi_tail = tc
, I.cfi_castType = fst erta
, I.cfi_signature = I.FunSignature (maybe I.Ccc id cc) (snd erta) apsa
, I.cfi_funAttrs = fa
})
}
convert_to_InvokeFunInterface :: A.CallSite -> MM (Bool, I.FunPtr I.Gname, I.InvokeFunInterface I.Gname)
convert_to_InvokeFunInterface (A.CallSiteFun cc pa t fn aps fa) =
do { mp <- typeDefs
; let ert = A.splitCallReturnType t
; erta <- eitherRet (fmap specializeRetAttr pa) ert aps
; fna <- convert_FunPtr fn
; apsa <- mapM convert_ActualParam aps
; return (fst ert == A.Tvoid, fna, I.InvokeFunInterface { I.ifi_castType = fst erta
, I.ifi_signature = I.FunSignature (maybe I.Ccc id cc)
(snd erta) apsa
, I.ifi_funAttrs = fa
})
}
convert_to_CallAsmInterface :: A.InlineAsmExp -> MM (Bool, I.AsmCode, I.CallAsmInterface I.Gname)
convert_to_CallAsmInterface (A.InlineAsmExp t dia b1 b2 qs1 qs2 as fa) =
do { mp <- typeDefs
; let ert = A.splitCallReturnType t
; erta <- eitherRet [] ert as
; asa <- mapM convert_ActualParam as
; let rt::I.Utype = tconvert mp (fst ert)
; return (fst ert == A.Tvoid, I.AsmCode b2 qs1 qs2, I.CallAsmInterface (snd erta) dia b1 asa fa)
}
eitherRet :: [I.RetAttr] -> (A.Type, Maybe (A.Type, A.AddrSpace))
-> [A.ActualParam] -> MM (Maybe (I.Type I.ScalarB I.P), I.Type I.CodeFunB I.X)
eitherRet retAttrs (rt, ft) actualParams =
let ts = fmap (\x -> case x of
A.ActualParamData t pa _ -> (t, pa)
A.ActualParamLabel t pa _ -> (ucast t, pa)
_ -> errorLoc FLC $ show x
) actualParams
in
do { mp <- typeDefs
; funType <- composeTfunction (rt,retAttrs) ts Nothing
; case ft of
Just (fta,as) -> case (dcast FLC ((tconvert mp fta)::I.Utype))::I.Type I.CodeFunB I.X of
I.Tfunction (rt0,_) mts mv -> return (Just $ I.Tpointer (ucast $ I.Tfunction (rt0, retAttrs) mts mv) (tconvert mp as), funType)
Nothing -> return (Nothing, funType)
}
convert_Clause :: A.Clause -> MM (I.Clause I.Gname)
convert_Clause x = case x of
(A.ClauseCatch (A.Typed t v)) -> do { mp <- typeDefs
; let (ti::I.Dtype) = dcast FLC ((tconvert mp t)::I.Utype)
; vi <- convert_Value v
; return $ I.Catch (I.T ti vi)
}
(A.ClauseFilter tc) -> Md.liftM I.Filter (convert_TypedConstOrNUll tc)
(A.ClauseConversion tc) ->
do { mp <- typeDefs
; if conversionIsTvector mp tc then Md.liftM I.CcoV (convert_to_Conversion_V convert_Value tc)
else Md.liftM I.CcoS (convert_to_Conversion convert_Value tc)
}
convert_GlobalOrLocalId :: A.GlobalOrLocalId -> MM I.GlobalOrLocalId
convert_GlobalOrLocalId = return
convert_Expr_CInst :: (Maybe A.LocalId, A.Expr) -> MM (I.Cinst I.Gname)
convert_Expr_CInst (Just lhs, A.ExprGetElementPtr c) =
do { mp <- typeDefs
; if getElemPtrIsTvector mp c then
do { (I.GetElementPtr b t idx) <- convert_to_GetElementPtr_V convert_Value convert_Value c
; return $ I.I_getelementptr_V b t idx (sLid lhs)
}
else
do { (I.GetElementPtr b t idx) <- convert_to_GetElementPtr convert_Value convert_Value c
; return $ I.I_getelementptr b t idx (sLid lhs)
}
}
convert_Expr_CInst (Just lhs, A.ExprIcmp a@(A.Icmp _ t _ _)) =
do { mp <- typeDefs
; if isTvector mp t then
do { (I.Icmp op ta v1a v2a) <- convert_to_Icmp_V convert_Value a
; return $ I.I_icmp_V op ta v1a v2a (sLid lhs)
}
else
do { (I.Icmp op ta v1a v2a) <- convert_to_Icmp convert_Value a
; return $ I.I_icmp op ta v1a v2a (sLid lhs)
}
}
convert_Expr_CInst (Just lhs, A.ExprFcmp a@(A.Fcmp _ t _ _)) =
do { mp <- typeDefs
; if isTvector mp t then
do { (I.Fcmp op ta v1a v2a) <- convert_to_Fcmp_V convert_Value a
; return $ I.I_fcmp_V op ta v1a v2a (sLid lhs)
}
else
do { (I.Fcmp op ta v1a v2a) <- convert_to_Fcmp convert_Value a
; return $ I.I_fcmp op ta v1a v2a (sLid lhs)
}
}
convert_Expr_CInst (Just lhs, A.ExprBinExpr (A.Ie a@(A.IbinExpr _ _ t _ _))) =
do { mp <- typeDefs
; if not $ isTvector mp t then
do { x <- convert_to_Binexp convert_Value a
; let y = case x of
Add n ta v1a v2a -> I.I_add n ta v1a v2a (sLid lhs)
Sub n ta v1a v2a -> I.I_sub n ta v1a v2a (sLid lhs)
Mul n ta v1a v2a -> I.I_mul n ta v1a v2a (sLid lhs)
Udiv n ta v1a v2a -> I.I_udiv n ta v1a v2a (sLid lhs)
Sdiv n ta v1a v2a -> I.I_sdiv n ta v1a v2a (sLid lhs)
Urem ta v1a v2a -> I.I_urem ta v1a v2a (sLid lhs)
Srem ta v1a v2a -> I.I_srem ta v1a v2a (sLid lhs)
Shl n ta v1a v2a -> I.I_shl n ta v1a v2a (sLid lhs)
Lshr n ta v1a v2a -> I.I_lshr n ta v1a v2a (sLid lhs)
Ashr n ta v1a v2a -> I.I_ashr n ta v1a v2a (sLid lhs)
And ta v1a v2a -> I.I_and ta v1a v2a (sLid lhs)
Or ta v1a v2a -> I.I_or ta v1a v2a (sLid lhs)
Xor ta v1a v2a -> I.I_xor ta v1a v2a (sLid lhs)
; return y
}
else
do { x <- convert_to_Binexp_V convert_Value a
; let y = case x of
Add n ta v1a v2a -> I.I_add_V n ta v1a v2a (sLid lhs)
Sub n ta v1a v2a -> I.I_sub_V n ta v1a v2a (sLid lhs)
Mul n ta v1a v2a -> I.I_mul_V n ta v1a v2a (sLid lhs)
Udiv n ta v1a v2a -> I.I_udiv_V n ta v1a v2a (sLid lhs)
Sdiv n ta v1a v2a -> I.I_sdiv_V n ta v1a v2a (sLid lhs)
Urem ta v1a v2a -> I.I_urem_V ta v1a v2a (sLid lhs)
Srem ta v1a v2a -> I.I_srem_V ta v1a v2a (sLid lhs)
Shl n ta v1a v2a -> I.I_shl_V n ta v1a v2a (sLid lhs)
Lshr n ta v1a v2a -> I.I_lshr_V n ta v1a v2a (sLid lhs)
Ashr n ta v1a v2a -> I.I_ashr_V n ta v1a v2a (sLid lhs)
And ta v1a v2a -> I.I_and_V ta v1a v2a (sLid lhs)
Or ta v1a v2a -> I.I_or_V ta v1a v2a (sLid lhs)
Xor ta v1a v2a -> I.I_xor_V ta v1a v2a (sLid lhs)
; return y
}
}
convert_Expr_CInst (Just lhs, A.ExprBinExpr (A.Fe a@(A.FbinExpr _ _ t _ _))) =
do { mp <- typeDefs
; if not $ isTvector mp t then
do { x <- convert_to_FBinexp convert_Value a
; let y = case x of
Fadd n ta v1a v2a -> I.I_fadd n ta v1a v2a (sLid lhs)
Fsub n ta v1a v2a -> I.I_fsub n ta v1a v2a (sLid lhs)
Fmul n ta v1a v2a -> I.I_fmul n ta v1a v2a (sLid lhs)
Fdiv n ta v1a v2a -> I.I_fdiv n ta v1a v2a (sLid lhs)
Frem n ta v1a v2a -> I.I_frem n ta v1a v2a (sLid lhs)
; return y
}
else
do { x <- convert_to_FBinexp_V convert_Value a
; let y = case x of
Fadd n ta v1a v2a -> I.I_fadd_V n ta v1a v2a (sLid lhs)
Fsub n ta v1a v2a -> I.I_fsub_V n ta v1a v2a (sLid lhs)
Fmul n ta v1a v2a -> I.I_fmul_V n ta v1a v2a (sLid lhs)
Fdiv n ta v1a v2a -> I.I_fdiv_V n ta v1a v2a (sLid lhs)
Frem n ta v1a v2a -> I.I_frem_V n ta v1a v2a (sLid lhs)
; return y
}
}
convert_Expr_CInst (Just lhs, A.ExprConversion a) =
do { mp <- typeDefs
; if not $ conversionIsTvector mp a then
do { x <- convert_to_Conversion convert_Value a
; let y = case x of
I.Trunc tv dt -> I.I_trunc tv dt (sLid lhs)
I.Zext tv dt -> I.I_zext tv dt (sLid lhs)
I.Sext tv dt -> I.I_sext tv dt (sLid lhs)
I.FpTrunc tv dt -> I.I_fptrunc tv dt (sLid lhs)
I.FpExt tv dt -> I.I_fpext tv dt (sLid lhs)
I.FpToUi tv dt -> I.I_fptoui tv dt (sLid lhs)
I.FpToSi tv dt -> I.I_fptosi tv dt (sLid lhs)
I.UiToFp tv dt -> I.I_uitofp tv dt (sLid lhs)
I.SiToFp tv dt -> I.I_sitofp tv dt (sLid lhs)
I.PtrToInt tv dt -> I.I_ptrtoint tv dt (sLid lhs)
I.IntToPtr tv dt -> I.I_inttoptr tv dt (sLid lhs)
I.Bitcast tv@(I.T st v) dt -> case (st, dt) of
(I.DtypeScalarP sta, I.DtypeScalarP dta) -> I.I_bitcast (I.T sta v) dta (sLid lhs)
(_,_) -> I.I_bitcast_D tv dt (sLid lhs)
I.AddrSpaceCast tv dt -> I.I_addrspacecast tv dt (sLid lhs)
; return y
}
else
do { x <- convert_to_Conversion_V convert_Value a
; let y = case x of
I.Trunc tv dt -> I.I_trunc_V tv dt (sLid lhs)
I.Zext tv dt -> I.I_zext_V tv dt (sLid lhs)
I.Sext tv dt -> I.I_sext_V tv dt (sLid lhs)
I.FpTrunc tv dt -> I.I_fptrunc_V tv dt (sLid lhs)
I.FpExt tv dt -> I.I_fpext_V tv dt (sLid lhs)
I.FpToUi tv dt -> I.I_fptoui_V tv dt (sLid lhs)
I.FpToSi tv dt -> I.I_fptosi_V tv dt (sLid lhs)
I.UiToFp tv dt -> I.I_uitofp_V tv dt (sLid lhs)
I.SiToFp tv dt -> I.I_sitofp_V tv dt (sLid lhs)
I.PtrToInt tv dt -> I.I_ptrtoint_V tv dt (sLid lhs)
I.IntToPtr tv dt -> I.I_inttoptr_V tv dt (sLid lhs)
I.Bitcast tv@(I.T st v) dt -> case (st, dt) of
(I.DtypeScalarP sta, I.DtypeScalarP dta) -> I.I_bitcast (I.T sta v) dta (sLid lhs)
(_,_) -> I.I_bitcast_D tv dt (sLid lhs)
I.AddrSpaceCast tv dt -> I.I_addrspacecast_V tv dt (sLid lhs)
; return y
}
}
convert_Expr_CInst (Just lhs, A.ExprSelect a@(A.Select _ (A.Typed t _) _)) =
do { mp <- typeDefs
; case matchType mp t of
Tk_ScalarI -> do { (I.Select (Left cnd) t f) <- convert_to_Select_I convert_Value a
; return $ I.I_select_I cnd t f (sLid lhs)
}
Tk_ScalarF -> do { (I.Select (Left cnd) t f) <- convert_to_Select_F convert_Value a
; return $ I.I_select_F cnd t f (sLid lhs)
}
Tk_ScalarP -> do { (I.Select (Left cnd) t f) <- convert_to_Select_P convert_Value a
; return $ I.I_select_P cnd t f (sLid lhs)
}
Tk_RecordD -> do { (I.Select (Left cnd) t f) <- convert_to_Select_Record convert_Value a
; return $ I.I_select_First cnd t f (sLid lhs)
}
Tk_VectorI -> do { (I.Select cnd t f) <- convert_to_Select_VI convert_Value a
; return $ I.I_select_VI cnd t f (sLid lhs)
}
Tk_VectorF -> do { (I.Select cnd t f) <- convert_to_Select_VF convert_Value a
; return $ I.I_select_VF cnd t f (sLid lhs)
}
Tk_VectorP -> do { (I.Select cnd t f) <- convert_to_Select_VP convert_Value a
; return $ I.I_select_VP cnd t f (sLid lhs)
}
}
convert_MemOp :: (Maybe A.LocalId, A.MemOp) -> MM (I.Cinst I.Gname)
convert_MemOp (mlhs, c) = case (mlhs, c) of
(Just lhs, A.Alloca mar t mtv ma) ->
do { mp <- typeDefs
; ti <- convert_Type_Dtype FLC t
; mtvi <- maybeM (convert_to_TypedValue_SI FLC) mtv
; return (I.I_alloca mar ti mtvi ma (sLid lhs))
}
(Just lhs, A.Load atom (A.Pointer tv) aa nonterm inv nonul) ->
do { tvi <- convert_to_TypedAddrValue FLC tv
; return (I.I_load atom tvi aa nonterm inv nonul (sLid lhs))
}
(Just lhs, A.LoadAtomic at v (A.Pointer tv) aa) ->
do { tvi <- convert_to_TypedAddrValue FLC tv
; return (I.I_loadatomic at v tvi aa (sLid lhs))
}
(Nothing, A.Store atom tv1 (A.Pointer tv2) aa nt) ->
do { tv1a <- convert_to_DtypedValue tv1
; tv2a <- convert_to_TypedAddrValue FLC tv2
; return $ I.I_store atom tv1a tv2a aa nt
}
(Nothing, A.StoreAtomic atom v tv1 (A.Pointer tv2) aa) ->
do { tv1a <- convert_to_DtypedValue tv1
; tv2a <- convert_to_TypedAddrValue FLC tv2
; return $ I.I_storeatomic atom v tv1a tv2a aa
}
(Nothing, A.Fence b fo) -> return $ I.I_fence b fo
(Just lhs, A.CmpXchg wk b1 (A.Pointer tv1) tv2@(A.Typed t2 _) tv3 b2 mf ff) ->
do { mp <- typeDefs
; tv1a <- convert_to_TypedAddrValue FLC tv1
; case matchType mp t2 of
Tk_ScalarI -> do { tv2a <- convert_to_TypedValue_SI FLC tv2
; tv3a <- convert_to_TypedValue_SI FLC tv3
; return $ I.I_cmpxchg_I wk b1 tv1a tv2a tv3a b2 mf ff (sLid lhs)
}
Tk_ScalarF -> do { tv2a <- convert_to_TypedValue_SF FLC tv2
; tv3a <- convert_to_TypedValue_SF FLC tv3
; return $ I.I_cmpxchg_F wk b1 tv1a tv2a tv3a b2 mf ff (sLid lhs)
}
Tk_ScalarP -> do { tv2a <- convert_to_TypedValue_SP FLC tv2
; tv3a <- convert_to_TypedValue_SP FLC tv3
; return $ I.I_cmpxchg_P wk b1 tv1a tv2a tv3a b2 mf ff (sLid lhs)
}
}
(Just lhs, A.AtomicRmw b1 op (A.Pointer tv1) tv2 b2 mf) ->
do { tv1a <- convert_to_TypedAddrValue FLC tv1
; tv2a <- convert_to_TypedValue_SI FLC tv2
; return $ I.I_atomicrmw b1 op tv1a tv2a b2 mf (sLid lhs)
}
(_,_) -> error $ "AstIrConversion:irrefutable lhs:" ++ show mlhs ++ " rhs:" ++ show c
convert_to_DtypedValue :: A.Typed A.Value -> MM (I.T I.Dtype (I.Value I.Gname))
convert_to_DtypedValue (A.Typed t v) = do { mp <- typeDefs
; let (ti::I.Dtype) = dcast FLC ((tconvert mp t)::I.Utype)
; vi <- convert_Value v
; return $ I.T ti vi
}
convert_to_DtypedConst :: A.Typed A.Const -> MM (I.T I.Dtype (I.Const I.Gname))
convert_to_DtypedConst (A.Typed t v) = do { mp <- typeDefs
; let (ti::I.Dtype) = dcast FLC ((tconvert mp t)::I.Utype)
; vi <- convert_Const v
; return $ I.T ti vi
}
convert_to_TypedValue_SI :: FileLoc -> A.Typed A.Value -> MM (I.T (I.Type I.ScalarB I.I) (I.Value I.Gname))
convert_to_TypedValue_SI lc (A.Typed t v) = do { mp <- typeDefs
; let (ti::I.Type I.ScalarB I.I) = dcast lc ((tconvert mp t)::I.Utype)
; vi <- convert_Value v
; return $ I.T ti vi
}
convert_to_TypedValue_SF :: FileLoc -> A.Typed A.Value -> MM (I.T (I.Type I.ScalarB I.F) (I.Value I.Gname))
convert_to_TypedValue_SF lc (A.Typed t v) = do { mp <- typeDefs
; let (ti::I.Type I.ScalarB I.F) = dcast lc ((tconvert mp t)::I.Utype)
; vi <- convert_Value v
; return $ I.T ti vi
}
convert_to_TypedValue_SP :: FileLoc -> A.Typed A.Value -> MM (I.T (I.Type I.ScalarB I.P) (I.Value I.Gname))
convert_to_TypedValue_SP lc (A.Typed t v) = do { mp <- typeDefs
; let (ti::I.Type I.ScalarB I.P) = dcast lc ((tconvert mp t)::I.Utype)
; vi <- convert_Value v
; return $ I.T ti vi
}
convert_to_TypedAddrValue :: FileLoc -> A.Typed A.Value -> MM (I.T (I.Type I.ScalarB I.P) (I.Value I.Gname))
convert_to_TypedAddrValue lc (A.Typed t v) =
do { mp <- typeDefs
; let (ti::I.Type I.ScalarB I.P) = dcast lc ((tconvert mp t)::I.Utype)
; vi <- convert_Value v
; return $ I.T ti vi
}
convert_Type_Dtype :: FileLoc -> A.Type -> MM I.Dtype
convert_Type_Dtype lc t = do { mp <- typeDefs
; return $ dcast lc ((tconvert mp t)::I.Utype)
}
convert_Rhs :: (Maybe A.LocalId, A.Rhs) -> MM (I.Node I.Gname () H.O H.O)
convert_Rhs (mlhs, A.RhsMemOp c) = Md.liftM (\x -> I.Cnode x []) (convert_MemOp (mlhs, c))
convert_Rhs (mlhs, A.RhsExpr e) = Md.liftM (\x -> I.Cnode x []) (convert_Expr_CInst (mlhs, e))
convert_Rhs (lhs, A.RhsCall b cs) =
case specializeRegisterIntrinsic lhs cs of
Just (Just r, ml, [m]) ->
do { ma <- convert_MetaParam m
; case ma of
I.MetaOperandMeta mc -> return $ I.Cnode (I.I_llvm_read_register ml mc (sLid r)) []
_ -> errorLoc FLC $ show ma
}
Just (Nothing, ml, [m,v]) ->
do { ma <- convert_MetaParam m
; (I.FunOperandData _ _ _ va) <- convert_ActualParam v
; case ma of
I.MetaOperandMeta mc -> return $ I.Cnode (I.I_llvm_write_register ml mc va) []
_ -> errorLoc FLC $ show ma
}
Nothing ->
do { mc <- convert_to_Minst cs
; case mc of
Just mi | lhs == Nothing -> return $ I.Mnode mi []
Just _ -> errorLoc FLC $ show lhs ++ " " ++ show cs
Nothing ->
Md.liftM (\x -> I.Cnode x []) $
do { (isvoid, fnptr, csi) <- convert_to_CallFunInterface b cs
; return $ maybe
(I.I_call_fun fnptr csi (fmap sLid lhs)) id (specializeCallSite (fmap sLid lhs) fnptr csi)
}
}
convert_Rhs (lhs, A.RhsInlineAsm cs) =
Md.liftM (\x -> I.Cnode x []) $
do { (isvoid, asm, csi) <- convert_to_CallAsmInterface cs
; return $ I.I_call_asm asm csi (fmap sLid lhs)
}
convert_Rhs (Just lhs, A.RhsVaArg (A.VaArg tv t)) =
do { tvi <- convert_to_DtypedValue tv
; ti <- convert_Type_Dtype FLC t
; return (I.Cnode (I.I_va_arg tvi ti (sLid lhs)) [])
}
convert_Rhs (Just lhs, A.RhsLandingPad (A.LandingPad t1 t2 pf b cs)) =
do { pfi <- convert_FunPtr pf
; csi <- mapM convert_Clause cs
; t1i <- convert_Type_Dtype FLC t1
; t2i <- convert_Type_Dtype FLC t2
; return (I.Cnode (I.I_landingpad t1i t2i pfi b csi (sLid lhs)) [])
}
convert_Rhs (Just lhs, A.RhsExtractElement a@(A.ExtractElement (A.Typed t1 _) _)) =
do { mp <- typeDefs
; case matchType mp t1 of
Tk_VectorI -> do { (I.ExtractElement vec idx) <- convert_to_ExtractElement_I convert_Value a
; return (I.Cnode (I.I_extractelement_I vec idx (sLid lhs)) [])
}
Tk_VectorF -> do { (I.ExtractElement vec idx) <- convert_to_ExtractElement_F convert_Value a
; return (I.Cnode (I.I_extractelement_F vec idx (sLid lhs)) [])
}
Tk_VectorP -> do { (I.ExtractElement vec idx) <- convert_to_ExtractElement_P convert_Value a
; return (I.Cnode (I.I_extractelement_P vec idx (sLid lhs)) [])
}
}
convert_Rhs (Just lhs, A.RhsInsertElement a@(A.InsertElement (A.Typed t1 _) _ _)) =
do { mp <- typeDefs
; case matchType mp t1 of
Tk_VectorI -> do { (I.InsertElement vec val idx) <- convert_to_InsertElement_I convert_Value a
; return (I.Cnode (I.I_insertelement_I vec val idx (sLid lhs)) [])
}
Tk_VectorF -> do { (I.InsertElement vec val idx) <- convert_to_InsertElement_F convert_Value a
; return (I.Cnode (I.I_insertelement_F vec val idx (sLid lhs)) [])
}
Tk_VectorP -> do { (I.InsertElement vec val idx) <- convert_to_InsertElement_P convert_Value a
; return (I.Cnode (I.I_insertelement_P vec val idx (sLid lhs)) [])
}
}
convert_Rhs (Just lhs, A.RhsShuffleVector a@(A.ShuffleVector (A.Typed t _) _ _)) =
do { mp <- typeDefs
; case matchType mp t of
Tk_VectorI -> do { (I.ShuffleVector tv1a tv2a tv3a) <- convert_to_ShuffleVector_I convert_Value a
; return (I.Cnode (I.I_shufflevector_I tv1a tv2a tv3a (sLid lhs)) [])
}
Tk_VectorF -> do { (I.ShuffleVector tv1a tv2a tv3a) <- convert_to_ShuffleVector_F convert_Value a
; return (I.Cnode (I.I_shufflevector_F tv1a tv2a tv3a (sLid lhs)) [])
}
Tk_VectorP -> do { (I.ShuffleVector tv1a tv2a tv3a) <- convert_to_ShuffleVector_P convert_Value a
; return (I.Cnode (I.I_shufflevector_P tv1a tv2a tv3a (sLid lhs)) [])
}
}
convert_Rhs (Just lhs, A.RhsExtractValue a) =
do { (I.ExtractValue blocka idxa) <- convert_to_ExtractValue convert_Value a
; return (I.Cnode (I.I_extractvalue blocka idxa (sLid lhs)) [])
}
convert_Rhs (Just lhs, A.RhsInsertValue a) =
do { (I.InsertValue blocka va idxa) <- convert_to_InsertValue convert_Value a
; return (I.Cnode (I.I_insertvalue blocka va idxa (sLid lhs)) [])
}
convert_Rhs (lhs,rhs) = errorLoc FLC $ "AstIrConversion:irrefutable error lhs:" ++ show lhs ++ " rhs:" ++ show rhs
specializeFirstParamAsRet :: A.ActualParam -> MM (Maybe (I.FunOperand (I.Value I.Gname)))
specializeFirstParamAsRet x = case x of
(A.ActualParamData t pa v) ->
do { mp <- typeDefs
; let (ta::I.Utype) = tconvert mp t
; va <- convert_Value v
; let (plist, bl) = stripOffPa pa sRetByValSignExtZeroExtAlignPreds
; case bl of
[Nothing, _, Nothing, Nothing, _] -> return Nothing
[Just _, Nothing, Nothing, Nothing, pa] -> return $ Just $ I.FunOperandAsRet (dcast FLC ta) plist (mapPaAlign pa) va
[Just _, Just _, _, _, Just (A.PaAlign n)] -> errorLoc FLC "byval cannot be used with sret"
}
(A.ActualParamLabel t pa v) ->
do { mp <- typeDefs
; let (ta::I.Utype) = tconvert mp t
; va <- convert_PercentLabel v
; case ta of
I.UtypeLabelX lbl -> return Nothing
}
A.ActualParamMeta mc -> errorLoc FLC $ show x ++ " is passed to convert_ActualParam"
convert_ActualParam :: A.ActualParam -> MM (I.FunOperand (I.Value I.Gname))
convert_ActualParam x = case x of
(A.ActualParamData t pa v) ->
do { mp <- typeDefs
; let (ta::I.Utype) = tconvert mp t
; va <- convert_Value v
; let (plist, bl) = stripOffPa pa sRetByValSignExtZeroExtAlignPreds
; case bl of
[Just _, Nothing, Nothing, Nothing, pn] -> return $ I.FunOperandAsRet (dcast FLC ta) plist (mapPaAlign pn) va
[Nothing, Just _, Nothing, Nothing, pn] -> return $ I.FunOperandByVal (dcast FLC ta) plist (mapPaAlign pn) va
[Nothing, Nothing, Just _ , Nothing, pn] -> return $ I.FunOperandExt I.Sign (dcast FLC ta) plist (mapPaAlign pn) va
[Nothing, Nothing, Nothing, Just _ , pn] -> return $ I.FunOperandExt I.Zero (dcast FLC ta) plist (mapPaAlign pn) va
[Nothing, Nothing, Nothing, Nothing, pn] -> return $ I.FunOperandData (dcast FLC ta) plist (mapPaAlign pn) va
}
(A.ActualParamLabel t pa v) ->
do { mp <- typeDefs
; let (ta::I.Utype) = tconvert mp t
; va <- convert_PercentLabel v
; let preds = [\x -> case x of
A.PaAlign _ -> True
_ -> False]
; let (plist, [pn]) = stripOffPa pa preds
; case ta of
I.UtypeLabelX lbl -> return $ I.FunOperandLabel lbl plist (mapPaAlign pn) (I.Val_const $ I.C_labelId va)
}
A.ActualParamMeta mc -> errorLoc FLC $ show x ++ " is passed to convert_ActualParam"
isMetaParam :: A.ActualParam -> Bool
isMetaParam x = case x of
A.ActualParamMeta _ -> True
_ -> False
isFormalMetaParam :: A.FormalParam -> Bool
isFormalMetaParam x = case x of
A.FormalParamMeta _ _ -> True
_ -> False
convert_MetaParam :: A.ActualParam -> MM (I.MetaOperand I.Gname)
convert_MetaParam x = case x of
A.ActualParamMeta mc -> Md.liftM I.MetaOperandMeta (convert_MetaKindedConst mc)
A.ActualParamData t pa v ->
do { mp <- typeDefs
; let (ta::I.Utype) = tconvert mp t
; va <- convert_Value v
; case ta of
I.UtypeLabelX lbl -> errorLoc FLC $ show x
_ -> return $ I.MetaOperandData (dcast FLC ta) pa (Nothing) va
}
_ -> errorLoc FLC $ show x ++ " is passed to convert_MetaParam"
convert_constToAliasee :: A.Const -> MM (I.Aliasee I.Gname)
convert_constToAliasee (A.C_simple (A.CpGlobalAddr v)) = return $ I.Aliasee $ specializeGlobalId v
convert_constToAliasee (A.C_conv cvt@(A.Conversion op src dt)) = convert_Aliasee (A.AliaseeConversion cvt)
convert_constToAliasee x = errorLoc FLC $ show x
convert_Aliasee :: A.Aliasee -> MM (I.Aliasee I.Gname)
convert_Aliasee ae = case ae of
A.Aliasee (A.Typed t c) -> do { mp <- typeDefs
; let (ta::I.Dtype) = dcast FLC ((tconvert mp t)::I.Utype)
; ca <- convert_constToAliasee c
; return $ I.AliaseeTyped ta ca
}
A.AliaseeConversion c@(A.Conversion _ _ dt) ->
do { mp <- typeDefs
; if isTvector mp dt then errorLoc FLC $ show dt
else Md.liftM I.AliaseeConversion (convert_to_Conversion convert_constToAliasee c)
}
A.AliaseeGetElementPtr a ->
do { mp <- typeDefs
; if getElemPtrIsTvector mp a then errorLoc FLC $ show ae
else Md.liftM I.AliaseeGEP (convert_to_GetElementPtr convert_constToAliasee convert_Const a)
}
convert_Prefix :: A.Prefix -> MM (I.Prefix I.Gname)
convert_Prefix (A.Prefix n) = Md.liftM I.Prefix (convert_TypedConstOrNUll n)
convert_Prologue :: A.Prologue -> MM (I.Prologue I.Gname)
convert_Prologue (A.Prologue n) = Md.liftM I.Prologue (convert_TypedConstOrNUll n)
convert_TypedConstOrNUll :: A.TypedConstOrNull -> MM (I.TypedConstOrNull I.Gname)
convert_TypedConstOrNUll x = case x of
A.TypedConst (A.Typed t v) -> do { mp <- typeDefs
; vi <- convert_Const v
; let (ti::I.Dtype) = dcast FLC ((tconvert mp t)::I.Utype)
; return (I.TypedConst (I.T ti vi))
}
A.UntypedNull -> return I.UntypedNull
convert_to_FunParamType :: A.FormalParam -> MM (I.FunOperand ())
convert_to_FunParamType x =
do { mp <- typeDefs
; case x of
(A.FormalParamData dt pa _) ->
case stripOffPa pa sRetByValSignExtZeroExtAlignPreds of
(palist, bl) -> case bl of
[Just _, Nothing, Nothing, Nothing, pa] ->
return $ I.FunOperandAsRet (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) ()
[Nothing, Just _, Nothing, Nothing, pa] ->
return $ I.FunOperandByVal (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) ()
[Nothing, Nothing, Just _, Nothing, pa] ->
return $ I.FunOperandExt I.Sign (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) ()
[Nothing, Nothing, Nothing, Just _, pa] ->
return $ I.FunOperandExt I.Zero (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) ()
[Nothing, Nothing, Nothing, Nothing, pa] ->
return $ I.FunOperandData (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) ()
_ -> errorLoc FLC $ show bl
(A.FormalParamMeta mk fp) -> errorLoc FLC $ show x
}
mapPaAlign pn = fmap (\(A.PaAlign n) -> I.AlignInByte n) pn
convert_to_FunParamTypeList :: [A.FormalParam] -> MM [I.FunOperand ()]
convert_to_FunParamTypeList l =
do { mp <- typeDefs
; la <- mapM convert_to_FunParamType l
; return la
}
composeTfunction :: (A.Type, [A.RetAttr]) -> [(A.Type, [A.ParamAttr])] -> Maybe A.VarArgParam -> MM (I.Type I.CodeFunB I.X)
composeTfunction (ret, retAttrs) params mv =
do { mp <- typeDefs
; ts <- mapM (\(dt, pa) ->
do { let (dt0::I.Utype) = tconvert mp dt
; let (plist, bl) = stripOffPa pa sRetByValSignExtZeroExtAlignPreds
; case bl of
[Just _, Nothing, Nothing, Nothing, pn] -> return (I.MtypeAsRet (dcast FLC dt0), mapPaAlign pn)
[Nothing, Just _, Nothing, Nothing, pn] -> return (I.MtypeByVal (dcast FLC dt0), mapPaAlign pn)
[Nothing, Nothing, Just _, Nothing, pn] -> return (I.MtypeExt I.Sign (dcast FLC dt0), mapPaAlign pn)
[Nothing, Nothing, Nothing, Just _, pn] -> return (I.MtypeExt I.Zero (dcast FLC dt0), mapPaAlign pn)
[Nothing, Nothing, Nothing, Nothing, pn] -> case dt0 of
I.UtypeLabelX lt -> return (I.MtypeLabel lt, mapPaAlign pn)
_ -> return (I.MtypeData (dcast FLC dt0), mapPaAlign pn)
_ -> errorLoc FLC $ show bl
}
) params
; let (ret0::I.Utype) = tconvert mp ret
; return $ I.Tfunction (dcast FLC ret0, retAttrs) ts mv
}
sRetByValSignExtZeroExtAlignPreds = [ (A.PaSRet==)
, (A.PaByVal==)
, (A.PaSignExt==)
, (A.PaZeroExt==)
, \x -> case x of
A.PaAlign _ -> True
_ -> False
]
convert_FunctionDeclareType :: A.FunctionPrototype -> MM (I.FunctionDeclare I.Gname)
convert_FunctionDeclareType (A.FunctionPrototype { A.fp_linkage = f0
, A.fp_visibility = f1
, A.fp_dllstorage = f2
, A.fp_callConv = f3
, A.fp_retAttrs = f4
, A.fp_retType = f5
, A.fp_fun_name = f6
, A.fp_param_list = f7@(A.FormalParamList fpl mv)
, A.fp_addr_naming = f8
, A.fp_fun_attrs = f9
, A.fp_section = f10
, A.fp_comdat = f10a
, A.fp_alignment = f11
, A.fp_gc = f12
, A.fp_prefix = f13
, A.fp_prologue = f14}) =
if not (any isFormalMetaParam fpl) then
do { f13a <- maybeM convert_Prefix f13
; f14a <- maybeM convert_Prologue f14
; f7a <- convert_to_FunParamTypeList fpl
; ft <- composeTfunction (f5, fmap specializeRetAttr f4)
(fmap (\x -> case x of
A.FormalParamData dt pa _ -> (dt, pa)
_ -> errorLoc FLC $ show x
) fpl) mv
; return $ I.FunctionDeclareData { I.fd_linkage = f0
, I.fd_visibility = f1
, I.fd_dllstorage = f2
, I.fd_signature = I.FunSignature (maybe I.Ccc id f3) ft f7a
, I.fd_fun_name = specializeGlobalId f6
, I.fd_addr_naming = f8
, I.fd_fun_attrs = f9
, I.fd_section = f10
, I.fd_comdat = fmap convert_Comdat f10a
, I.fd_alignment = f11
, I.fd_gc = f12
, I.fd_prefix = f13a
, I.fd_prologue = f14a
}
}
else
do { mp <- typeDefs
; return $ I.FunctionDeclareMeta { I.fd_fun_name = specializeGlobalId f6
, I.fd_retType = dcast FLC ((tconvert mp f5)::I.Utype)
, I.fd_metakinds =
fmap (\x -> case x of
(A.FormalParamMeta m _) -> Left $ tconvert mp m
(A.FormalParamData dt _ _) -> Right $ (dcast FLC ((tconvert mp dt)::I.Utype))
) fpl
, I.fd_fun_attrs = f9
}
}
convert_to_FunParam :: A.FormalParam -> MM (I.FunOperand I.Lname)
convert_to_FunParam x =
do { mp <- typeDefs
; case x of
(A.FormalParamData dt pa (A.FexplicitParam fp)) ->
let (palist, bl) = stripOffPa pa sRetByValSignExtZeroExtAlignPreds
in case bl of
[Just _, Nothing, Nothing, Nothing, pa] ->
return $ I.FunOperandAsRet (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) (sLid fp)
[Nothing, Just _, Nothing, Nothing, pa] ->
return $ I.FunOperandByVal (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) (sLid fp)
[Nothing, Nothing, Just _, Nothing, pa] ->
return $ I.FunOperandExt I.Sign (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) (sLid fp)
[Nothing, Nothing, Nothing, Just _, pa] ->
return $ I.FunOperandExt I.Zero (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) (sLid fp)
[Nothing, Nothing, Nothing, Nothing, pa] ->
return $ I.FunOperandData (dcast FLC ((tconvert mp dt)::I.Utype)) palist (mapPaAlign pa) (sLid fp)
_ -> errorLoc FLC $ show bl
(A.FormalParamData _ _ A.FimplicitParam) ->
errorLoc FLC "implicit param should be normalized in AsmSimplification"
}
convert_FunctionInterface :: A.FunctionPrototype -> MM (I.FunctionInterface I.Gname)
convert_FunctionInterface (A.FunctionPrototype f0 f1 f2 f3 f4 f5 f6 f7@(A.FormalParamList plist mv) f8 f9 f10 f10a f11 f12 f13 f14) =
do { mp <- typeDefs
; let (f5a::I.Rtype) = dcast FLC ((tconvert mp f5)::I.Utype)
; f13a <- maybeM convert_Prefix f13
; f14a <- maybeM convert_Prologue f14
; f7a <- mapM convert_to_FunParam plist
; ft <- composeTfunction (f5, fmap specializeRetAttr f4)
(fmap (\x -> case x of
A.FormalParamData dt pa _ -> (dt, pa)
_ -> errorLoc FLC $ show x
) plist) mv
; return $ I.FunctionInterface { I.fi_linkage = f0
, I.fi_visibility = f1
, I.fi_dllstorage = f2
, I.fi_signature = I.FunSignature (maybe I.Ccc id f3) ft f7a
, I.fi_fun_name = specializeGlobalId f6
, I.fi_addr_naming = f8
, I.fi_fun_attrs = f9
, I.fi_section = f10
, I.fi_comdat = fmap convert_Comdat f10a
, I.fi_alignment = f11
, I.fi_gc = f12
, I.fi_prefix = f13a
, I.fi_prologue = f14a
}
}
convert_PhiInst :: A.PhiInst -> MM (I.Pinst I.Gname)
convert_PhiInst phi@(A.PhiInst mg t branches) =
do { mp <- typeDefs
; branchesa <- mapM (pairM convert_Value convert_PercentLabel) branches
; let (ta::I.Utype) = tconvert mp t
; let (tab::I.Ftype) = case ta of
I.UtypeRecordD e -> dcast FLC (squeeze FLC e)
_ -> dcast FLC ta
; case mg of
Just lhs -> return $ I.Pinst tab (fmap (\x -> (fst x, snd x)) branchesa) (sLid lhs)
Nothing -> errorLoc FLC $ "unused phi" ++ show phi
}
convert_CInst :: A.ComputingInst -> MM (I.Node I.Gname () H.O H.O)
convert_CInst (A.ComputingInst mg rhs) = convert_Rhs (mg, rhs)
convert_TerminatorInst :: A.TerminatorInst -> MM (I.Tinst I.Gname)
convert_TerminatorInst (A.RetVoid) = return I.T_ret_void
convert_TerminatorInst (A.Return tvs) = Md.liftM I.T_return (mapM convert_to_DtypedValue tvs)
convert_TerminatorInst (A.Br t) = Md.liftM I.T_br (convert_TargetLabel t)
convert_TerminatorInst (A.Cbr cnd t f) =
Md.liftM3 I.T_cbr (convert_Value cnd) (convert_TargetLabel t)
(convert_TargetLabel f)
convert_TerminatorInst (A.IndirectBr cnd bs) =
Md.liftM2 I.T_indirectbr (convert_to_TypedAddrValue FLC cnd) (mapM convert_TargetLabel bs)
convert_TerminatorInst (A.Switch cnd d cases) =
do { dc <- convert_to_TypedValue_SI FLC cnd
; dl <- convert_TargetLabel d
; other <- mapM (pairM (convert_to_TypedValue_SI FLC) convert_TargetLabel) cases
; return $ I.T_switch (dc, dl) other
}
convert_TerminatorInst (A.Invoke mg cs t f) =
do { (_, fptr, csa) <- convert_to_InvokeFunInterface cs
; ta <- convert_TargetLabel t
; fa <- convert_TargetLabel f
; return $ I.T_invoke fptr csa ta fa (fmap sLid mg)
}
convert_TerminatorInst (A.InvokeInlineAsm mg cs t f) =
do { (_, asm, csa) <- convert_to_CallAsmInterface cs
; ta <- convert_TargetLabel t
; fa <- convert_TargetLabel f
; return $ I.T_invoke_asm asm csa ta fa (fmap sLid mg)
}
convert_TerminatorInst (A.Resume tv) = Md.liftM I.T_resume (convert_to_DtypedValue tv)
convert_TerminatorInst A.Unreachable = return I.T_unreachable
convert_TerminatorInst A.Unwind = return I.T_unwind
convert_Dbg :: A.Dbg -> MM (I.Dbg I.Gname)
convert_Dbg (A.Dbg mv mc) = Md.liftM2 I.Dbg (convert_MdRef mv) (convert_MetaConst mc)
convert_PhiInstWithDbg :: A.PhiInstWithDbg -> MM (I.Pinst I.Gname, [I.Dbg I.Gname])
convert_PhiInstWithDbg (A.PhiInstWithDbg ins dbgs) =
do { ins0 <- convert_PhiInst ins
; dbgs0 <- mapM convert_Dbg dbgs
; return (ins0, dbgs0)
}
convert_CInstWithDbg :: A.ComputingInstWithDbg -> MM (I.Node I.Gname () H.O H.O)
convert_CInstWithDbg (A.ComputingInstWithDbg ins dbgs) =
do { ins0 <- convert_CInst ins
; dbgs0 <- mapM convert_Dbg dbgs
; case ins0 of
I.Cnode n _ -> return $ I.Cnode n dbgs0
I.Mnode n _ -> return $ I.Mnode n dbgs0
}
convert_TerminatorInstWithDbg :: A.TerminatorInstWithDbg -> MM (I.Tinst I.Gname, [I.Dbg I.Gname])
convert_TerminatorInstWithDbg (A.TerminatorInstWithDbg term dbgs) =
do { term0 <- convert_TerminatorInst term
; dbgs0 <- mapM convert_Dbg dbgs
; return (term0, dbgs0)
}
toSingleNodeGraph :: A.Block -> MM (H.Graph (I.Node I.Gname ()) H.C H.C)
toSingleNodeGraph (A.Block f phi ms l) =
do { f' <- toFirst f
; phi' <- mapM toPhi phi
; ms' <- mapM toMid ms
; l' <- toLast l
; return $ H.mkFirst f' H.<*> H.mkMiddles phi' H.<*> H.mkMiddles ms' H.<*> H.mkLast l'
}
toFirst :: A.BlockLabel -> MM (I.Node I.Gname () H.C H.O)
toFirst x = Md.liftM I.Lnode (convert_BlockLabel x)
toPhi :: A.PhiInstWithDbg -> MM (I.Node I.Gname () H.O H.O)
toPhi phi = Md.liftM (uncurry I.Pnode) (convert_PhiInstWithDbg phi)
toMid :: A.ComputingInstWithDbg -> MM (I.Node I.Gname () H.O H.O)
toMid inst = convert_CInstWithDbg inst
toLast :: A.TerminatorInstWithDbg -> MM (I.Node I.Gname () H.O H.C)
toLast inst = Md.liftM (uncurry I.Tnode) (convert_TerminatorInstWithDbg inst)
-- | the head must be the entry block
getEntryAndAlist :: [A.Block] -> MM (H.Label, [A.LabelId])
getEntryAndAlist [] = error "Parsed procedures should not be empty"
getEntryAndAlist bs =
do { l <- convert_BlockLabel $ A.blockLabel $ head bs
; let ord = map (\b -> case A.blockLabel b of
A.ImplicitBlockLabel p -> error $ "irrefutable implicitblock "
++ show p ++ " should be normalized in AstSimplify"
A.ExplicitBlockLabel x -> x
) bs
; return (l, ord)
}
toGraph :: [A.Block] -> MM (H.Graph (I.Node I.Gname ()) H.C H.C)
toGraph bs =
{-
It's more likely that only reachable blocks are pulled out and used to create
a graph, the unreachable blocks are left.
-}
do { g <- foldl (Md.liftM2 (H.|*><*|)) (return H.emptyClosedGraph) (map toSingleNodeGraph bs)
; getBody g
}
getBody :: forall n. H.Graph n H.C H.C -> MM (H.Graph n H.C H.C)
getBody graph = lift (LabelMapM f)
where f m = return (m, graph)
blockToGraph :: A.FunctionPrototype -> [A.Block] -> MM (H.Label, H.Graph (I.Node I.Gname ()) H.C H.C)
blockToGraph fn blocks =
do { (entry, labels) <- getEntryAndAlist blocks
; body <- toGraph blocks
; return (entry, body)
}
convert_TlAlias :: A.TlAlias -> MM (I.TlAlias I.Gname)
convert_TlAlias (A.TlAlias g v dll tlm na l a) =
convert_Aliasee a >>= return . (I.TlAlias (specializeGlobalId g) v dll tlm na l)
convert_TlUnamedMd :: A.TlUnamedMd -> MM (I.TlUnamedMd I.Gname)
convert_TlUnamedMd (A.TlUnamedMd s tv) = do { mc <- convert_MetaKindedConst tv
; return $ specializeUnamedMd (I.TlUnamedMd s mc)
}
convert_TlNamedMd :: A.TlNamedMd -> (MM I.TlNamedMd)
convert_TlNamedMd (A.TlNamedMd m ns) = do { nsa <- mapM convert_MdNode ns
; return $ I.TlNamedMd m nsa
}
convert_TlDeclare :: A.TlDeclare -> MM (I.TlDeclare I.Gname)
convert_TlDeclare (A.TlDeclare f) = convert_FunctionDeclareType f >>= return . I.TlDeclare
convert_TlDefine :: A.TlDefine -> MM (I.TlDefine I.Gname ())
convert_TlDefine (A.TlDefine f b) = let (A.FunctionPrototype _ _ _ _ _ _ gid _ _ _ _ _ _ _ _ _) = f
in do { fa <- convert_FunctionInterface f
; (e, g) <- withFunName (specializeGlobalId gid) (blockToGraph f b)
; return $ I.TlDefine fa e g
}
convert_TlGlobal :: A.TlGlobal -> MM (I.TlGlobal I.Gname)
convert_TlGlobal (A.TlGlobal a1 a2 a3 a4 a5 a6 a7 a8 a8a a9 a10 a11 a12 a13) =
do { mp <- typeDefs
; let (a9a::I.Utype) = tconvert mp a9
; a10a <- maybeM convert_Const a10
; case a9a of
I.UtypeOpaqueD _ -> return $ I.TlGlobalOpaque (specializeGlobalId $ fromJust a1)
a2 a3 a4 a5 a6 (fmap (tconvert mp) a7)
a8 a8a (dcast FLC a9a) a10a a11 (fmap convert_Comdat a12) a13
_ -> return $ I.TlGlobalDtype (specializeGlobalId $ fromJust a1)
a2 a3 a4 a5 a6 (fmap (tconvert mp) a7)
a8 a8a (dcast FLC a9a) a10a a11 (fmap convert_Comdat a12) a13
}
convert_TlTypeDef :: A.TlTypeDef -> MM I.TlTypeDef
convert_TlTypeDef (A.TlTypeDef lid t) =
do { mp <- typeDefs
; let (ta::I.Utype) = tconvert mp t
; case ta of
I.UtypeFunX _ -> return (I.TlFunTypeDef (sLid lid) (dcast FLC ta))
I.UtypeOpaqueD _-> return (I.TlOpqTypeDef (sLid lid) (dcast FLC ta))
_ -> return (I.TlDatTypeDef (sLid lid) (dcast FLC ((tconvert mp t)::I.Utype)))
}
convert_TlDepLibs :: A.TlDepLibs -> MM I.TlDepLibs
convert_TlDepLibs (A.TlDepLibs s) = return (I.TlDepLibs s)
convert_TlUnamedType :: A.TlUnamedType -> (MM I.TlUnamedType)
convert_TlUnamedType (A.TlUnamedType i t) = do { mp <- typeDefs
; let (ta::I.Dtype) = dcast FLC ((tconvert mp t)::I.Utype)
; return (I.TlUnamedType i ta)
}
convert_TlModuleAsm :: A.TlModuleAsm -> MM I.TlModuleAsm
convert_TlModuleAsm (A.TlModuleAsm s) = return (I.TlModuleAsm s)
convert_TlAttribute :: A.TlAttribute -> MM I.TlAttribute
convert_TlAttribute (A.TlAttribute n l) = return (I.TlAttribute n l)
convert_TlComdat :: A.TlComdat -> MM (I.TlComdat I.Gname)
convert_TlComdat (A.TlComdat l s) = return (I.TlComdat (specializeDollarId l) s)
convert_Comdat :: A.Comdat -> I.Comdat I.Gname
convert_Comdat (A.Comdat n) = I.Comdat (fmap specializeDollarId n)
toplevel2IrP1 :: A.Toplevel -> MM (A.FunctionPrototype, I.Toplevel I.Gname ())
toplevel2IrP1 (A.ToplevelDefine f@(A.TlDefine fp _)) = do { f0 <- convert_TlDefine f
; return (fp, I.ToplevelDefine f0)
}
toplevel2IrP2 :: M.Map A.FunctionPrototype (I.Toplevel I.Gname ()) -> A.Toplevel -> MM (I.Toplevel I.Gname ())
toplevel2IrP2 _ (A.ToplevelAlias q) = Md.liftM I.ToplevelAlias (convert_TlAlias q)
toplevel2IrP2 _ (A.ToplevelUnamedMd s) = Md.liftM I.ToplevelUnamedMd (convert_TlUnamedMd s)
toplevel2IrP2 _ (A.ToplevelNamedMd m) = Md.liftM I.ToplevelNamedMd (convert_TlNamedMd m)
toplevel2IrP2 _ (A.ToplevelDeclare f) = Md.liftM I.ToplevelDeclare (convert_TlDeclare f)
toplevel2IrP2 mp (A.ToplevelDefine (A.TlDefine fp _)) = return $ fromJust $ M.lookup fp mp
toplevel2IrP2 _ (A.ToplevelGlobal g) = do { tlg <- convert_TlGlobal g
; case specializeTlGlobal tlg of
Just tli -> return $ I.ToplevelIntrinsic tli
Nothing -> return $ I.ToplevelGlobal tlg
}
toplevel2IrP2 _ (A.ToplevelTypeDef t) = Md.liftM I.ToplevelTypeDef (convert_TlTypeDef t)
toplevel2IrP2 _ (A.ToplevelDepLibs qs) = Md.liftM I.ToplevelDepLibs (convert_TlDepLibs qs)
toplevel2IrP2 _ (A.ToplevelUnamedType i) = Md.liftM I.ToplevelUnamedType (convert_TlUnamedType i)
toplevel2IrP2 _ (A.ToplevelModuleAsm q) = Md.liftM I.ToplevelModuleAsm (convert_TlModuleAsm q)
toplevel2IrP2 _ (A.ToplevelAttribute n) = Md.liftM I.ToplevelAttribute (convert_TlAttribute n)
toplevel2IrP2 _ (A.ToplevelComdat l) = Md.liftM I.ToplevelComdat (convert_TlComdat l)
filterOutDataLayoutAndTriple :: [A.Toplevel] -> ((A.DataLayout, A.TargetTriple), [A.Toplevel])
filterOutDataLayoutAndTriple tls =
let [A.ToplevelTriple (A.TlTriple triple)] = filter (\x -> case x of
A.ToplevelTriple a -> True
_ -> False) tls
[A.ToplevelDataLayout (A.TlDataLayout dl)] = filter (\x -> case x of
A.ToplevelDataLayout a -> True
_ -> False) tls
in ((dl, triple), filter (\x -> case x of
A.ToplevelTriple _ -> False
A.ToplevelDataLayout _ -> False
_ -> True) tls)
compMapping :: Target -> A.Module ->
H.SimpleUniqueMonad (IdLabelMap, I.SpecializedModule I.Gname ())
compMapping tg@(Target dlm) m@(A.Module ts) =
let ((A.DataLayout dl, tt), ts0) = filterOutDataLayoutAndTriple ts
td = M.fromList $ A.typeDefOfModule m
in if matchLayoutSpecAndTriple dlm dl tt then
runLabelMapM emptyIdLabelMap
$ (runReaderT (do { let defs0 = filter (\x -> case x of
A.ToplevelDefine _ -> True
_ -> False) ts0
; defs <- mapM toplevel2IrP1 defs0
; l <- mapM (toplevel2IrP2 (M.fromList defs)) ts0
; return $ I.SpecializedModule tg $ I.Module l
}
) (ReaderData td (I.Gname (errorLoc FLC $ "<fatal error>"))))
else
error $ show (dl,tt) ++ " does not match " ++ show dlm | mlite/hLLVM | src/Llvm/AsmHirConversion/MapLabels.hs | bsd-3-clause | 89,369 | 8 | 27 | 31,243 | 35,144 | 17,397 | 17,747 | 1,487 | 91 |
module Problem50 where
import Data.Array
import Prime
lim :: Int
lim = 1000000
main :: IO ()
main =
print
. head
. filter isPrimeNaive
$ [ sms ! (i, j) | j <- [ml - 1, ml - 2 .. 0], i <- [0 .. ml - j - 1] ]
where
primes' = getPrimesUpto lim
ml = length . takeWhile (<= lim) . scanl1 (+) $ primes'
primes = take ml primes'
sms = array
((0, 0), (ml - 1, ml - 1))
( zip (map (\i -> (i, 0)) [0 ..]) primes
++ [ ((i, j), sms ! (i, j - 1) + sms ! (i + j, 0))
| i <- [0 .. ml - 1]
, j <- [1 .. ml - i - 1]
]
)
| adityagupta1089/Project-Euler-Haskell | src/problems/Problem50.hs | bsd-3-clause | 628 | 0 | 16 | 257 | 322 | 182 | 140 | 20 | 1 |
module Spec where
import Control.Monad.State.Lazy
import Control.Monad.Trans.Maybe
import LineCount
import LineCount.Counter
import LineCount.Counter.Base
import LineCount.Counter.Values
import LineCount.Filter.Base
import LineCount.Filter.Values
import LineCount.Profile
import Test.Hspec
emptyOpts = MainOptions True [] [] True [] []
emptyProfile = mempty
testAFilter ∷ FileFilter → MainOptions → [Profile] → FilePath → Bool
testAFilter = unFilter
testAFilterWithEmpty ∷ FileFilter → FilePath → Bool
testAFilterWithEmpty f = testAFilter f emptyOpts []
filtersSpec ∷ Spec
filtersSpec = do
describe "[function] hiddenFilter" $ do
let testFunc = testAFilterWithEmpty hiddenFilter
it "rejects \".\"" $
testFunc "." `shouldBe` False
it "rejects .⍵" $
testFunc ".hello" `shouldBe` False
it "accepts { a⍵ | a ≠ '.' }" $
testFunc "hello" `shouldBe` True
it "accepts 𝜖" $
testFunc "" `shouldBe` True
it "accepts { a⍵ | a ∈ SYMBOLS\\{'.'} }" $
testFunc "," `shouldBe` True
it "rejects { ⍵/. } " $
testFunc "/." `shouldBe` False
it "rejects a unix filepath with the last component ∈ { .⍵ }" $
testFunc "some/path/.file" `shouldBe` False
describe "[function] sameFolderFilter" $ do
let testFunc = testAFilterWithEmpty sameFolderFilter
it "rejects \".\"" $
testFunc "." `shouldBe` False
it "rejects \"..\"" $
testFunc ".." `shouldBe` False
it "rejects an arbitrary unix path ending in \"/.\"" $
testFunc "some/path/." `shouldBe` False
it "rejects an arbitrary unix path ending in \"/..\"" $
testFunc "some/path/.." `shouldBe` False
it "accepts ⍵" $
testFunc "word" `shouldBe` True
it "accepts .⍵" $
testFunc ".some" `shouldBe` True
it "accepts an arbitrary path" $
testFunc "/some/path" `shouldBe` True
it "accepts an arbitrary path ending with a word prefixed with \".\"" $
testFunc "/some/path/.file" `shouldBe` True
testACounter ∷ Counter → MainOptions → Profile → CounterState → String → Maybe CalcResult
testACounter c opts profile state input = runMaybeT (unCounter c opts profile input) `evalState` state
testACounterWEmpty ∷ Counter → String → Maybe CalcResult
testACounterWEmpty c = testACounter c emptyOpts emptyProfile emptyCS
countersSpec ∷ Spec
countersSpec = do
let codeline = Just (mempty { nonEmpty = 1 })
let commentLine = Just (mempty { commentLines = 1 })
let emptyLine = Just (mempty { emptyLines = 1 })
let reject = Nothing
describe "[function] emptyCounters" $ do
let testFunc = testACounterWEmpty emptyCounter
it "counts {' '}*" $
testFunc " " `shouldBe` emptyLine
it "counts 𝜖" $
testFunc "" `shouldBe` emptyLine
it "rejects { ⍵ | ⍵ ∉ {' '}* }" $
testFunc "f" `shouldBe` reject
it "rejects { ⍵iσ | ⍵, σ ∈ Σ*, i ∈ {0-9} } " $
testFunc "4" `shouldBe` reject
it "rejects a line containing spaces and a character" $
testFunc " f" `shouldBe` reject
describe "[function] nonEmptyCounter" $ do
let testFunc = testACounterWEmpty nonEmptyCounter
it "counts { ⍵ | ⍵ ∈ Σ\\{' '} } as a new codeline" $
testFunc "f" `shouldBe` codeline
it "counts { ⍵a | ⍵ ∈ {' '}*, a ∈ Σ\\{' '} } as new codeline" $
testFunc " f" `shouldBe` codeline
it "counts a line with a non-word character" $
testFunc "." `shouldBe` codeline
it "rejects a line containing only spaces" $
testFunc " " `shouldBe` reject
it "rejects the empty string" $
testFunc "" `shouldBe` reject
describe "[function] singleLineCommentCounter" $ do
let testFunc = testACounter singleLineCommentCounter emptyOpts (emptyProfile { commentDelimiter = ["#"] }) emptyCS
it "counts a line with just the comment delimiter as new comment line" $
testFunc "#" `shouldBe` commentLine
it "counts a line with the delimiter and spaces before it" $
testFunc " #" `shouldBe` commentLine
it "counts a line with other stuff and the delimiter as first character" $
testFunc " #erubv" `shouldBe` commentLine
it "rejects a line not containing a comment delimiter" $
testFunc " l" `shouldBe` reject
it "rejects the empty string" $
testFunc "" `shouldBe` reject
it "rejects a line with the delimiter, but not as first character" $
testFunc " j#sv" `shouldBe` reject
describe "[composed counter] emptyCounter + nonEmptyCounter" $ do
let testFunc = testACounterWEmpty (emptyCounter `mappend` nonEmptyCounter)
it "counts a line with characters as a codeline" $
testFunc "wjn" `shouldBe` codeline
it "counts a line with spaces and characters as codeline" $
testFunc " erjgnv" `shouldBe` codeline
it "counts a line with only spaces as empty line" $
testFunc " " `shouldBe` emptyLine
it "counts the empty string as an empty line" $
testFunc "" `shouldBe` emptyLine
describe "[composed counter] emptyCounter + nonEmptyCounter + singleLineCommentCounter" $ do
let testFunc = testACounter (singleLineCommentCounter `mappend` nonEmptyCounter `mappend` emptyCounter) emptyOpts (emptyProfile { commentDelimiter = ["#"] }) emptyCS
it "counts a line with regular characters as codeline" $
testFunc "wefjb" `shouldBe` codeline
it "counts a line with no characters as empty" $
testFunc " " `shouldBe` emptyLine
it "counts the empty string as empty line" $
testFunc "" `shouldBe` emptyLine
it "counts a line with the comment delimiter as comment line" $
testFunc "#oernv" `shouldBe` commentLine
it "counts a line with the delimiter in the middle as code" $
testFunc "ejkn#ejnv" `shouldBe` codeline
main ∷ IO ()
main = hspec $ do
countersSpec
filtersSpec
| JustusAdam/hlinecount | testsuite/Spec.hs | bsd-3-clause | 5,990 | 0 | 17 | 1,431 | 1,349 | 663 | 686 | -1 | -1 |
{-# OPTIONS -XCPP #-}
module Grid ( grid) where
import Data.String
import Text.Blaze.Html5.Attributes as At hiding (step)
#define ALONE -- to execute it alone, uncomment this
#ifdef ALONE
import MFlow.Wai.Blaze.Html.All
main= runNavigation "" $ transientNav grid
#else
import MFlow.Wai.Blaze.Html.All hiding(retry, page)
import Menu
#endif
attr= fromString
grid = do
r <- page $ pageFlow "grid"
$ addLink
++> wEditList table row [(0,""),(0,"")] "wEditListAdd"
<** submitButton "submit"
page $ p << (show r ++ " returned")
++> wlink () (p << " back to menu")
where
row _= tr <<< ( (,) <$> tdborder <<< getInt (Just 0)
<*> tdborder <<< getTextBox (Just "")
<++ tdborder << delLink)
addLink= a ! href (attr "#")
! At.id (attr "wEditListAdd")
<< "add"
delLink= a ! href (attr "#")
! onclick (attr "this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)")
<< "delete"
tdborder= td ! At.style (attr "border: solid 1px")
| agocorona/MFlow | Demos/Grid.hs | bsd-3-clause | 1,183 | 0 | 16 | 385 | 316 | 168 | 148 | 24 | 1 |
module Robozzle.Haskell.Internal
(
) where
| reborg/robozzle-haskell | src/Robozzle/Haskell/Internal.hs | bsd-3-clause | 51 | 0 | 3 | 13 | 10 | 7 | 3 | 2 | 0 |
{-# LANGUAGE OverloadedStrings, PackageImports #-}
import "monads-tf" Control.Monad.State
import Data.Pipe
import Data.Pipe.ByteString
import System.IO
import Network.Sasl
import Network.Sasl.DigestMd5.Client
import qualified Data.ByteString as BS
data St = St [(BS.ByteString, BS.ByteString)] deriving Show
instance SaslState St where
getSaslState (St s) = s
putSaslState s _ = St s
serverFile :: String
serverFile = "examples/digestMd5sv.txt"
main :: IO ()
main = do
let (_, (_, p)) = sasl
r <- runPipe (fromFileLn serverFile =$= input =$= p =$= toHandleLn stdout)
`runStateT` St [
("username", "yoshikuni"),
("password", "password"),
("cnonce", "00DEADBEEF00"),
("nc", "00000001"),
("uri", "xmpp/localhost") ]
print r
input :: Pipe BS.ByteString (Either Success BS.ByteString) (StateT St IO) ()
input = await >>= \mbs -> case mbs of
Just "success" -> yield . Left $ Success Nothing
Just ch -> yield (Right ch) >> input
_ -> return ()
| YoshikuniJujo/sasl | examples/clientD.hs | bsd-3-clause | 969 | 12 | 14 | 166 | 362 | 197 | 165 | 30 | 3 |
{-# LANGUAGE BangPatterns #-}
module FRP.Reactive
( Behavior
, Event
-- * Interface
, newBehavior
, newEvent
, animate
, on
, Cacheable(..)
-- * Combinators
, filterJust
, hold
, switch
, execute
, (<@>)
, (<@)
) where
import Control.Applicative
import Control.Monad
import Control.Monad.STM
import Control.Monad.Trans
import Data.IORef
import FRP.Interval
import qualified FRP.LinkedList as LinkedList
swapIORef :: IORef a -> a -> IO a
swapIORef r a = atomicModifyIORef' r $ \b -> (a, b)
data Behavior a = Behavior
{ sample :: IO a
, listen :: (a -> IO ()) -> Managed ()
, cached :: Bool
}
instance Functor Behavior where
fmap f b = Behavior
{ sample = f <$> sample b
, listen = \k -> listen b (k . f)
, cached = False
}
instance Applicative Behavior where
pure a = Behavior
{ sample = return a
, listen = \_ -> return ()
, cached = True
}
b <*> c = Behavior
{ sample = sample b <*> sample c
, listen = \k -> do
listen c $ \a -> do
f <- sample b
k (f a)
listen b $ \f -> do
a <- sample c
k (f a)
, cached = False
}
instance Monad Behavior where
return = pure
b >>= f = Behavior
{ sample = sample b >>= sample . f
, listen = \k -> do
clean <- liftIO $ newIORef (return ())
listen b $ \a -> do
let c = f a
initial <- sample c
k initial
(_, d) <- runManaged (listen c k)
join (swapIORef clean d)
finally $ join (readIORef clean)
, cached = False
}
newtype Event a = Event { pulse :: Behavior (Maybe a) }
instance Functor Event where
fmap f = Event . fmap (fmap f) . pulse
instance Applicative Event where
pure = Event . pure . pure
f <*> a = Event $ (<*>) <$> pulse f <*> pulse a
instance Alternative Event where
empty = Event $ pure empty
a <|> b = Event $ (<|>) <$> pulse a <*> pulse b
instance Monad Event where
return = pure
e >>= k = Event $ pulse e >>= \m -> case m of
Nothing -> return Nothing
Just a -> pulse (k a)
fail _ = empty
instance MonadPlus Event where
mzero = empty
mplus = (<|>)
newBehavior :: a -> Interval (Behavior a, a -> IO ())
newBehavior initial = do
value <- liftIO $ newIORef initial
ll <- liftIO $ atomically LinkedList.empty
let b = Behavior
{ sample = readIORef value
, listen = \k -> do
node <- liftIO . atomically $ LinkedList.insert k ll
finally . atomically $ LinkedList.delete node
, cached = True
}
update !a = do
writeIORef value a
hs <- atomically $ LinkedList.toList ll
mapM_ ($ a) hs
defer . finally . atomically $ LinkedList.clear ll
return (b, update)
newEvent :: Interval (Event a, a -> IO ())
newEvent = do
(b, update) <- newBehavior Nothing
return (Event b, \a -> update (Just a) >> update Nothing)
animate :: Behavior a -> (a -> IO ()) -> Interval ()
animate b f = do
initial <- liftIO $ sample b
liftIO $ f initial
defer $ listen b f
on :: Event a -> (a -> IO ()) -> Interval ()
on e f = do
latch <- liftIO $ newIORef Nothing
defer $ listen (pulse e) $ \y -> do
x <- swapIORef latch y
case (x, y) of
(Just a, Nothing) -> f a
_ -> return ()
class Cacheable f where
cache :: f a -> Interval (f a)
instance Cacheable Event where
cache e
| cached (pulse e) = return e
| otherwise = do
a <- liftIO $ sample (pulse e)
latch <- liftIO $ newIORef a
(b, update) <- newBehavior a
defer $ listen (pulse e) $ \y -> do
x <- swapIORef latch y
case (x, y) of
(Nothing, Nothing) -> return ()
_ -> update y
return (Event b)
instance Cacheable Behavior where
cache b
| cached b = return b
| otherwise = do
a <- liftIO $ sample b
(b', update) <- newBehavior a
defer $ listen b update
return b'
filterJust :: Event (Maybe a) -> Event a
filterJust e = Event $ join <$> pulse e
hold :: a -> Event a -> Interval (Behavior a)
hold a e = do
(b, update) <- newBehavior a
on e update
return b
switch :: Behavior (Event a) -> Event a
switch s = Event $ s >>= pulse
execute :: Event (IO a) -> Interval (Event a)
execute e = do
(e', push) <- newEvent
on e (>>= push)
return e'
infixl 4 <@>, <@
(<@>) :: Behavior (a -> b) -> Event a -> Event b
b <@> e = Event $ fmap <$> b <*> pulse e
(<@) :: Behavior b -> Event a -> Event b
b <@ e = const <$> b <@> e
| knrafto/reactive | src/FRP/Reactive.hs | bsd-3-clause | 5,092 | 0 | 18 | 1,963 | 1,995 | 990 | 1,005 | 155 | 2 |
import List
-- Same factorization algorithm as from #3
-- Kind of stupid to use it here as it's totally stateless and will sieve
-- repeatedly (herp derp).
-- Pick out which primes divide the given integer.
-- Helper uses accfactors for tail recursion.
-- Takes in number to factor, list of things that are possibly primes (to check
-- against), and factor accumulator list.
-- For efficiency we only sieve the possible prime list as we need to.
factors :: Int -> [Int]
factors n = factorHelper n [2..n] []
where sieve :: Int -> [Int] -> [Int]
sieve p ps = filter (\m -> m `mod` p /= 0) ps
factorHelper :: Int -> [Int] -> [Int] -> [Int]
factorHelper 1 _ accfactors = accfactors
factorHelper m [] accfactors = (m:accfactors)
factorHelper m (p:ps) accfactors | m `mod` p == 0 = factorHelper (m `div` p) (p:ps) (p:accfactors)
| otherwise = factorHelper m (sieve p ps) accfactors
-- Counts divisors of a number (standard trick w/ prime factorization)
countDivs :: Int -> (Int, Int)
countDivs n = (n,product $ map (+1) facCounts)
where facs = factors n
facCounts = map (\i -> length $ filter (== i) facs) $ nub facs
main :: IO ()
main = print $ fst $ head $ dropWhile ((< 500) . snd) triDivs
where triDivs = map (countDivs . (\n -> n*(n+1)`div`2)) $ [5..]
| akerber47/haskalah | test/files/euler/12.hs | bsd-3-clause | 1,390 | 0 | 16 | 371 | 429 | 236 | 193 | 17 | 3 |
{-# LANGUAGE TypeSynonymInstances, GeneralizedNewtypeDeriving, OverloadedStrings #-}
-- | This module offers a simple implementation of @Localized@ class via @StateT@ transformer.
-- This implementation is usable if you have nothing against adding yet another transformer to
-- your already complicated monadic stack. Otherwise, it may be simpler for you to add necessary
-- fields to one of @StateT@s or @ReaderT@s in your stack.
module Text.Localize.State
(-- * Data types
LocState (..),
LocalizeT (..),
-- * Functions
runLocalizeT,
setLanguage, withLanguage,
setContext, withContext
) where
import Control.Applicative
import Control.Monad.State
import Control.Monad.Trans
import Text.Localize.Types
-- | Localization state
data LocState = LocState {
lsTranslations :: Translations,
lsLanguage :: LanguageId,
lsContext :: Maybe Context
}
deriving (Show)
-- | Localization monad transformer
newtype LocalizeT m a = LocalizeT {
unLocalizeT :: StateT LocState m a
}
deriving (Functor, Applicative, Monad, MonadIO, MonadState LocState)
instance Monad m => Localized (LocalizeT m) where
getTranslations = gets lsTranslations
getLanguage = gets lsLanguage
getContext = gets lsContext
-- | Run a computation inside @LocalizeT@.
runLocalizeT :: Monad m => LocalizeT m a -> LocState -> m a
runLocalizeT actions st = evalStateT (unLocalizeT actions) st
-- | Set current language
setLanguage :: Monad m => LanguageId -> LocalizeT m ()
setLanguage lang = modify $ \st -> st {lsLanguage = lang}
-- | Execute some actions with specified language.
withLanguage :: Monad m => LanguageId -> LocalizeT m a -> LocalizeT m a
withLanguage lang actions = do
oldLang <- gets lsLanguage
setLanguage lang
result <- actions
setLanguage oldLang
return result
-- | Set current context.
setContext :: Monad m => Maybe Context -> LocalizeT m ()
setContext ctxt = modify $ \st -> st {lsContext = ctxt}
-- | Execute some actions within specific context.
withContext :: Monad m => Maybe Context -> LocalizeT m a -> LocalizeT m a
withContext ctxt actions = do
oldContext <- gets lsContext
setContext ctxt
result <- actions
setContext oldContext
return result
| portnov/localize | Text/Localize/State.hs | bsd-3-clause | 2,211 | 0 | 9 | 404 | 505 | 265 | 240 | 44 | 1 |
{-# LANGUAGE CPP #-}
module Package
( packageRules
)
where
import Control.Applicative ((<$>))
import Data.Graph (flattenSCCs, stronglyConnComp)
import Data.List (isPrefixOf, isInfixOf)
#if MIN_VERSION_base(4,6,0)
import Data.Ord (Down(..))
#endif
import Data.Version (showVersion)
import Development.Shake
import Development.Shake.FilePath
import Config
import Dirs
import LocalCommand
import Paths
import PlatformDB
import Types
import Utils
#if !MIN_VERSION_base(4,6,0)
newtype Down a = Down a deriving (Eq)
instance Ord a => Ord (Down a) where
compare (Down x) (Down y) = y `compare` x
#endif
-- | All the default rules for packages. Includes unpacking, computing the
-- dependencies, and building.
packageRules :: Rules ()
packageRules = do
packageSourceDir PackageWildCard %/> \srcDir -> do
let pkg = extractPackage srcDir
let destDir = takeDirectory srcDir
let providedDir = sourceForPackageDir pkg
provided <- doesDirectoryExist providedDir
if provided
then command_ [] "cp" ["-pR", providedDir, srcDir]
else do
command_ [Cwd destDir] "cabal" ["unpack", show pkg]
command_ [Cwd destDir] "mv" [show pkg, "source"]
packageDepsFile PackageWildCard %> \depFile -> do
hpRel <- askHpRelease
bc <- askBuildConfig
installAction depFile (bcIncludeExtra bc) hpRel
listBuild %> \out -> do
hpRel <- askHpRelease
bc <- askBuildConfig
let pkgs = platformPackages (bcIncludeExtra bc) hpRel
need $ map packageDepsFile pkgs
nodes <- mapM buildNode pkgs
writeFileLinesChanged out $ flattenSCCs $ stronglyConnComp nodes
where
buildNode p = do
ns <- map (pkgName . read) <$> (readFileLines $ packageDepsFile p)
return (show p, Down $ pkgName p, map Down ns)
-- Having the package names reverse sort as graph keys makes the SCC
-- components come out closer to normal sort order. Go figure!
--TODO choose proper "allPackages" based on minimal or full build
installAction :: FilePath -> Bool -> Release -> Action ()
installAction depFile incExtras hpRel = do
let pkg = extractPackage depFile
let srcDir = packageSourceDir pkg
need [ dir srcDir ]
(Exit _, Stdout out, Stderr err) <- localCommand [Cwd srcDir]
"cabal" cabalInstallArgs
case decode out of
Right deps -> writeFileLinesChanged depFile deps
Left msg -> error $ "Error computing dependencies of "
++ show pkg ++ ":\n"
++ msg ++ "\n"
++ err
where
cabalInstallArgs =
[ "install"
, "--dry-run"
, "--only-dependencies"
, "--package-db=clear"
, "--package-db=global"
] ++ map ("--constraint=" ++) constraints
constraints =
map (\p -> pkgName p ++ "==" ++ showVersion (pkgVersion p)) $
(allPackages incExtras) hpRel
decode out = case drop 1 $ lines out of
("All the requested packages are already installed:":_) ->
Right []
("In order, the following would be installed (use -v for more details):":ls) ->
let deps = map (head . words) ls
in if all (`elem` packages) deps
|| "alex" `isInfixOf` depFile
|| "happy" `isInfixOf` depFile
|| any (`isInfixOf` depFile) ["QuickCheck","tf-random"]
then Right deps
else Left $ "Depends on non-HP packages: "
++ unwords (filter (not . (`elem` packages)) deps) ++ "\n" ++ "Could not build " ++ depFile
_ -> Left out
packages = map show $ (allPackages incExtras) hpRel
| erantapaa/haskell-platform | hptool/src/Package.hs | bsd-3-clause | 3,784 | 0 | 22 | 1,113 | 1,001 | 512 | 489 | 82 | 5 |
module Game where
import MExp
import Data.Char
import Data.Maybe
import Data.Function (on)
import Data.List
data Move = Move {
x :: Int
, y :: Int
, m :: String
} deriving (Eq,Ord,Show)
emptyMove = (Move (-1) (-1) "")
valuesListToMoves :: [Value] -> [Move] -> [Move]
valuesListToMoves [] [] = []
valuesListToMoves [] moves = moves
valuesListToMoves (h:t) moves =
let
(xKey, xVal) = getMapItem (stringToValue "x") h
(yKey, yVal) = getMapItem (stringToValue "y") h
(vKey, vVal) = getMapItem (stringToValue "v") h
x = fromJust $ getInt xVal
y = fromJust $ getInt yVal
v = fromJust $ getString vVal
in
valuesListToMoves t (moves ++ [(Move x y v)])
mExpToMoves :: String -> [Move]
mExpToMoves expression =
let
list = getList (parse expression)
moves = valuesListToMoves list []
in
moves
movesToValuesList :: [Move] -> [Value] -> [Value]
movesToValuesList [] [] = []
movesToValuesList [] values = values
movesToValuesList (h:t) values =
let
(Move x y v) = h
(xKey, xVal) = (stringToValue "x", intToValue x)
(yKey, yVal) = (stringToValue "y", intToValue y)
(vKey, vVal) = (stringToValue "v", stringToValue v)
valuesMap = [(xKey, xVal), (yKey, yVal), (vKey, vVal)]
map = valuesMapToValue valuesMap
in
movesToValuesList t (values ++ [map])
movesToMExp :: [Move] -> String
movesToMExp moves =
let
valuesList = valuesListToValue (movesToValuesList moves [])
in
toString valuesList
movesToMExpString :: [Move] -> String
movesToMExpString moves =
let
valuesList = movesToValuesList moves []
in
valuesToString valuesList ""
moveExist :: Int -> Int -> String -> [Move] -> Bool
moveExist x y t moves
| ((filter( \(Move mX mY mT) -> mX == x && mY == y && mT == t) moves) /= [] ) = True
| otherwise = False
moveExistAtCoords :: Int -> Int -> [Move] -> Bool
moveExistAtCoords x y moves
| ((filter( \(Move mX mY mT) -> mX == x && mY == y) moves) /= [] ) = True
| otherwise = False
moveExistAtPos :: Int -> [Move] -> Bool
moveExistAtPos pos moves =
let
(x, y) = posToCoords pos
in
moveExistAtCoords x y moves
countMoves :: String -> [Move] -> Int
countMoves t moves = length ( filter (\(Move mX mY mT) -> mT == t) moves)
getMoves :: String -> [Move] -> [Move]
getMoves t moves = filter (\(Move mX mY mT) -> mT == t) moves
replaceCharAtPos:: Int -> Char -> String -> String
replaceCharAtPos i v (h:t)
| i == 0 = v:t
| otherwise = h:replaceCharAtPos (i-1) v t
movesToStringInner :: [Move] -> String -> String
movesToStringInner [] expression = expression
movesToStringInner (move:moves) expression =
let
(Move mX mY mT) = move
pos = coordsToPos (mX, mY)
(h:t) = mT
result = replaceCharAtPos pos h expression
in
movesToStringInner moves result
movesToString :: [Move] -> String
movesToString moves = movesToStringInner moves "000000000"
posToCoords :: Int -> (Int, Int)
posToCoords pos =
let
y = pos `div` 3
x = pos `mod` 3
in
(x, y)
coordsToPos :: (Int, Int) -> Int
coordsToPos (x, y) = (y * 3) + x
oponent :: String -> String
oponent "x" = "o"
oponent _ = "x"
getPlayer :: Bool -> String
getPlayer player
| player = "x"
| otherwise = "o"
getPlayerState :: String -> Bool
getPlayerState player
| player == "x" = True
| otherwise = False
fullRow :: Char -> String -> Bool
fullRow t [] = False
fullRow t (a:b:c:s)
| (a == b && b == c && c == t) = True
| otherwise = fullRow t s
hasWon :: Char -> [Move] -> Bool
hasWon m moves =
let
board = movesToString moves
horizontals = fullRow m board -- Patikrinamos horizontalios eilutes
vertical [a1,b1,c1,a2,b2,c2,a3,b3,c3] = fullRow m [a1,a2,a3,b1,b2,b3,c1,c2,c3] -- Vertikalios paverciamos horizontaliomis ir patikrinamos.
diagonal [a1,_,b1,_,c2,_,b3,_,a3] = fullRow m [a1,c2,a3,b1,c2,b3] -- Istrizaines paverciamos horizontaliomis ir patikrinamos.
in
horizontals || diagonal board || vertical board -- Tikriname ar zaidejas laimejo siuo ejimu
boardFull :: [Move] -> Bool
boardFull moves =
let
board = movesToString moves
in
((filter( \(t) -> t == '0') board) == [] )
winner :: [Move] -> Maybe String
winner moves
| hasWon 'x' moves = Just "x"
| hasWon 'o' moves = Just "o"
| boardFull moves = Just "0"
| otherwise = Nothing
getGameState :: Maybe String -> String
getGameState state = case state of
Just "x" -> "Winner X!"
Just "o" -> "Winner O!"
Just "0" -> "Draw!"
_ -> "Game state unknown."
getMovesFromMExp :: String -> [Move]
getMovesFromMExp [] = []
getMovesFromMExp moveMExp = mExpToMoves moveMExp
miniMax :: String -> [Move] -> Move
miniMax player [] = (Move 0 0 player)
miniMax player moves =
let
availableMoves = getAvailableMoves player moves
mapped = map (\move -> ((minPlay (oponent player) player (makeMove player move moves) (availableMoves \\ [move])), move)) availableMoves
(score, move) = maximumBy (compare `on` fst) mapped
in
move
minPlay :: String -> String-> [Move] -> [Move] -> Int
minPlay player team moves availableMoves
| (winner moves) == Just team = 1
| (winner moves) == Just (oponent team) = -1
| (winner moves) == Just "0" = 0
| otherwise =
let
mapped = map (\move -> maxPlay (oponent player) team (makeMove player move moves) (availableMoves \\ [move])) availableMoves
in
minimum mapped
maxPlay :: String -> String -> [Move] -> [Move] -> Int
maxPlay player team moves availableMoves
| (winner moves) == Just team = 1
| (winner moves) == Just (oponent team) = -1
| (winner moves) == Just "0" = 0
| otherwise =
let
mapped = map (\move -> minPlay (oponent player) team (makeMove player move moves) (availableMoves \\ [move])) availableMoves
in
maximum mapped
makeMove player move moves = let (Move x y t) = move in moves ++ [(Move x y player)]
getAvailableMoves player moves = loop player 0 moves []
loop :: String -> Int -> [Move] -> [Move] -> [Move]
loop player pos moves available
| pos < 9 && (moveExistAtPos pos moves) == False =
let
(x, y) = posToCoords pos
in
loop player (pos + 1) moves (available ++ [(Move x y player)])
| pos < 9 = (loop player (pos + 1) moves available)
| otherwise = available | tomas-stuina/fp | src/Game.hs | bsd-3-clause | 6,558 | 0 | 18 | 1,716 | 2,714 | 1,404 | 1,310 | 172 | 4 |
module Kite.Optimizer where
import Data.List
import Control.Monad.State
import Control.Monad.Error
import Kite.Syntax
-- | The optimizer error type.
data OptiError = OptiError String
| UnknownError
deriving (Show, Eq)
instance Error OptiError where
noMsg = UnknownError
strMsg = OptiError
-- | Utility function for throwing an `OptiError`.
throwOE :: String -> Opti a
throwOE = throwError . OptiError
-- | Type synonyms to increase readability.
type Name = String
data Needs = Needs { fns :: [String] }
-- | The state that the optimizer uses to keep track of referenced identifiers.
data OptiState = OptiState { decls :: [Decl], scope :: [[Name]], checked :: [Name] }
type Opti a = ErrorT OptiError (State OptiState) a
-- | Built-in names, used to prevent removal of them.
builtInNames :: [Name]
builtInNames = ["print", "put", "sin", "cos", "tan", "sleep", "panic", "clear",
"arguments", ":", "==", "<=", "+", "-", "*", "/", "%", "^", "random"]
builtIns :: [Decl]
builtIns = map (`PDecl` PVoid) builtInNames
-- | Lookup a declaration in the optimizer state by its identifier.
findDecl :: Name -> Opti (Maybe Expr)
findDecl name = do
st <- get
let decl = find (\d -> case d of
PDecl dname _ -> dname == name
_ -> False
) (decls st)
case decl of
Just (PDecl _ expr) -> return (Just expr)
_ -> return Nothing
-- | Main function for performing optimization. Takes a list of
-- declarations and returns a list with only the used ones.
optimize :: [Decl] -> [Decl]
optimize ds = do
let used = evalState (runErrorT optimize') OptiState { decls = ds ++ builtIns,
scope = [],
checked = [] }
-- we expect this to always be Right, maybe refactor?
let Right names = used
keep = "main" : (builtInNames ++ names)
filter (\d -> case d of
PDecl name _ -> name `elem` keep
_ -> False) ds
optimize' :: Opti [Name]
optimize' = do
main <- findDecl "main"
case main of
Just expr -> mread expr
Nothing -> throwOE "Can't optimize, no 'main' found"
mread' :: [Expr] -> Opti [Name]
mread' exprs = do
a <- mapM mread exprs
return $ concat a
mread :: Expr -> Opti [Name]
-- primitives
mread PVoid = return []
mread (PInteger _) = return []
mread (PFloat _) = return []
mread (PChar _) = return []
mread (PBool _) = return []
-- base
mread (PIdentifier name) = do
st <- get
if name `elem` checked st
then return [name]
else do
d <- findDecl name
sub <- case d of
Just expr -> do
put st { checked = name : checked st }
mread expr
Nothing -> return []
return $ name : sub
-- look in scope, then decls, mread recursively
mread (PApply fn arg) = mread' [fn, arg]
mread (PList exprs) = mread' exprs
mread (PBlock exprs) = mread' exprs
mread (PPair exprA exprB) = mread' [exprA, exprB]
mread (PIf cond conseq alt) = mread' [cond, conseq, alt]
mread (PBind name expr) = do
e <- mread expr
return (e \\ [name])
mread (PLambda _ expr) = mread expr -- push scope
mread (PReturn expr) = mread expr
mread (PMatch expr cases) = mread' (expr : map snd cases)
| kite-lang/kite | src/Kite/Optimizer.hs | mit | 3,316 | 0 | 20 | 932 | 1,106 | 580 | 526 | 81 | 3 |
module Main where
import REPL (repl)
main :: IO ()
main = repl
| juanbono/tapl-haskell | untyped/app/Main.hs | gpl-3.0 | 65 | 0 | 6 | 15 | 27 | 16 | 11 | 4 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CloudTrail.DescribeTrails
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves settings for the trail associated with the current region for
-- your account.
--
-- /See:/ <http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_DescribeTrails.html AWS API Reference> for DescribeTrails.
module Network.AWS.CloudTrail.DescribeTrails
(
-- * Creating a Request
describeTrails
, DescribeTrails
-- * Request Lenses
, dtTrailNameList
-- * Destructuring the Response
, describeTrailsResponse
, DescribeTrailsResponse
-- * Response Lenses
, dtrsTrailList
, dtrsResponseStatus
) where
import Network.AWS.CloudTrail.Types
import Network.AWS.CloudTrail.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Returns information about the trail.
--
-- /See:/ 'describeTrails' smart constructor.
newtype DescribeTrails = DescribeTrails'
{ _dtTrailNameList :: Maybe [Text]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeTrails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtTrailNameList'
describeTrails
:: DescribeTrails
describeTrails =
DescribeTrails'
{ _dtTrailNameList = Nothing
}
-- | The trail returned.
dtTrailNameList :: Lens' DescribeTrails [Text]
dtTrailNameList = lens _dtTrailNameList (\ s a -> s{_dtTrailNameList = a}) . _Default . _Coerce;
instance AWSRequest DescribeTrails where
type Rs DescribeTrails = DescribeTrailsResponse
request = postJSON cloudTrail
response
= receiveJSON
(\ s h x ->
DescribeTrailsResponse' <$>
(x .?> "trailList" .!@ mempty) <*>
(pure (fromEnum s)))
instance ToHeaders DescribeTrails where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.DescribeTrails"
:: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON DescribeTrails where
toJSON DescribeTrails'{..}
= object
(catMaybes
[("trailNameList" .=) <$> _dtTrailNameList])
instance ToPath DescribeTrails where
toPath = const "/"
instance ToQuery DescribeTrails where
toQuery = const mempty
-- | Returns the objects or data listed below if successful. Otherwise,
-- returns an error.
--
-- /See:/ 'describeTrailsResponse' smart constructor.
data DescribeTrailsResponse = DescribeTrailsResponse'
{ _dtrsTrailList :: !(Maybe [Trail])
, _dtrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeTrailsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtrsTrailList'
--
-- * 'dtrsResponseStatus'
describeTrailsResponse
:: Int -- ^ 'dtrsResponseStatus'
-> DescribeTrailsResponse
describeTrailsResponse pResponseStatus_ =
DescribeTrailsResponse'
{ _dtrsTrailList = Nothing
, _dtrsResponseStatus = pResponseStatus_
}
-- | The list of trails.
dtrsTrailList :: Lens' DescribeTrailsResponse [Trail]
dtrsTrailList = lens _dtrsTrailList (\ s a -> s{_dtrsTrailList = a}) . _Default . _Coerce;
-- | The response status code.
dtrsResponseStatus :: Lens' DescribeTrailsResponse Int
dtrsResponseStatus = lens _dtrsResponseStatus (\ s a -> s{_dtrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-cloudtrail/gen/Network/AWS/CloudTrail/DescribeTrails.hs | mpl-2.0 | 4,342 | 0 | 13 | 986 | 603 | 362 | 241 | 78 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Glacier.DeleteVaultNotifications
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation deletes the notification configuration set for a vault.
-- The operation is eventually consistent; that is, it might take some time
-- for Amazon Glacier to completely disable the notifications and you might
-- still receive some notifications for a short time after you send the
-- delete request.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don\'t have any
-- permissions by default. You must grant them explicit permission to
-- perform specific actions. For more information, see
-- <http://docs.aws.amazon.com/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>.
--
-- For conceptual information and underlying REST API, go to
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/configuring-notifications.html Configuring Vault Notifications in Amazon Glacier>
-- and
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vault-notifications-delete.html Delete Vault Notification Configuration>
-- in the Amazon Glacier Developer Guide.
--
-- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-DeleteVaultNotifications.html AWS API Reference> for DeleteVaultNotifications.
module Network.AWS.Glacier.DeleteVaultNotifications
(
-- * Creating a Request
deleteVaultNotifications
, DeleteVaultNotifications
-- * Request Lenses
, dvnAccountId
, dvnVaultName
-- * Destructuring the Response
, deleteVaultNotificationsResponse
, DeleteVaultNotificationsResponse
) where
import Network.AWS.Glacier.Types
import Network.AWS.Glacier.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Provides options for deleting a vault notification configuration from an
-- Amazon Glacier vault.
--
-- /See:/ 'deleteVaultNotifications' smart constructor.
data DeleteVaultNotifications = DeleteVaultNotifications'
{ _dvnAccountId :: !Text
, _dvnVaultName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteVaultNotifications' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dvnAccountId'
--
-- * 'dvnVaultName'
deleteVaultNotifications
:: Text -- ^ 'dvnAccountId'
-> Text -- ^ 'dvnVaultName'
-> DeleteVaultNotifications
deleteVaultNotifications pAccountId_ pVaultName_ =
DeleteVaultNotifications'
{ _dvnAccountId = pAccountId_
, _dvnVaultName = pVaultName_
}
-- | The 'AccountId' value is the AWS account ID of the account that owns the
-- vault. You can either specify an AWS account ID or optionally a single
-- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account
-- ID associated with the credentials used to sign the request. If you use
-- an account ID, do not include any hyphens (apos-apos) in the ID.
dvnAccountId :: Lens' DeleteVaultNotifications Text
dvnAccountId = lens _dvnAccountId (\ s a -> s{_dvnAccountId = a});
-- | The name of the vault.
dvnVaultName :: Lens' DeleteVaultNotifications Text
dvnVaultName = lens _dvnVaultName (\ s a -> s{_dvnVaultName = a});
instance AWSRequest DeleteVaultNotifications where
type Rs DeleteVaultNotifications =
DeleteVaultNotificationsResponse
request = delete glacier
response
= receiveNull DeleteVaultNotificationsResponse'
instance ToHeaders DeleteVaultNotifications where
toHeaders = const mempty
instance ToPath DeleteVaultNotifications where
toPath DeleteVaultNotifications'{..}
= mconcat
["/", toBS _dvnAccountId, "/vaults/",
toBS _dvnVaultName, "/notification-configuration"]
instance ToQuery DeleteVaultNotifications where
toQuery = const mempty
-- | /See:/ 'deleteVaultNotificationsResponse' smart constructor.
data DeleteVaultNotificationsResponse =
DeleteVaultNotificationsResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteVaultNotificationsResponse' with the minimum fields required to make a request.
--
deleteVaultNotificationsResponse
:: DeleteVaultNotificationsResponse
deleteVaultNotificationsResponse = DeleteVaultNotificationsResponse'
| fmapfmapfmap/amazonka | amazonka-glacier/gen/Network/AWS/Glacier/DeleteVaultNotifications.hs | mpl-2.0 | 5,060 | 0 | 9 | 867 | 442 | 276 | 166 | 62 | 1 |
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies,
GeneralizedNewtypeDeriving,
TemplateHaskell, CPP, UndecidableInstances #-}
{-| All RPC calls are run within this monad.
It encapsulates:
* IO operations,
* failures,
* working with the daemon state.
Code that is specific either to the configuration or the lock management, should
go into their corresponding dedicated modules.
-}
{-
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.Monad
( DaemonHandle
, dhConfigPath
, dhLivelock
, mkDaemonHandle
, WConfdMonadInt
, runWConfdMonadInt
, WConfdMonad
, daemonHandle
, modifyConfigState
, modifyConfigStateWithImmediate
, forceConfigStateDistribution
, readConfigState
, modifyConfigDataErr_
, modifyConfigAndReturnWithLock
, modifyConfigWithLock
, modifyLockWaiting
, modifyLockWaiting_
, readLockWaiting
, readLockAllocation
, modifyTempResState
, modifyTempResStateErr
, readTempResState
) where
import Control.Applicative
import Control.Arrow ((&&&), second)
import Control.Concurrent (forkIO, myThreadId)
import Control.Exception.Lifted (bracket)
import Control.Monad
import Control.Monad.Base
import Control.Monad.Error
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans.Control
import Data.Functor.Identity
import Data.IORef.Lifted
import Data.Monoid (Any(..))
import qualified Data.Set as S
import Data.Tuple (swap)
import System.Posix.Process (getProcessID)
import System.Time (getClockTime, ClockTime)
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Errors
import Ganeti.JQueue (notifyJob)
import Ganeti.Lens
import qualified Ganeti.Locking.Allocation as LA
import Ganeti.Locking.Locks
import qualified Ganeti.Locking.Waiting as LW
import Ganeti.Logging
import Ganeti.Logging.WriterLog
import Ganeti.Objects (ConfigData)
import Ganeti.Utils.AsyncWorker
import Ganeti.Utils.IORef
import Ganeti.Utils.Livelock (Livelock)
import Ganeti.WConfd.ConfigState
import Ganeti.WConfd.TempRes
-- * Pure data types used in the monad
-- | The state of the daemon, capturing both the configuration state and the
-- locking state.
data DaemonState = DaemonState
{ dsConfigState :: ConfigState
, dsLockWaiting :: GanetiLockWaiting
, dsTempRes :: TempResState
}
$(makeCustomLenses ''DaemonState)
data DaemonHandle = DaemonHandle
{ dhDaemonState :: IORef DaemonState -- ^ The current state of the daemon
, dhConfigPath :: FilePath -- ^ The configuration file path
-- all static information that doesn't change during the life-time of the
-- daemon should go here;
-- all IDs of threads that do asynchronous work should probably also go here
, dhSaveConfigWorker :: AsyncWorker Any ()
, dhSaveLocksWorker :: AsyncWorker () ()
, dhSaveTempResWorker :: AsyncWorker () ()
, dhLivelock :: Livelock
}
mkDaemonHandle :: FilePath
-> ConfigState
-> GanetiLockWaiting
-> TempResState
-> (IO ConfigState -> [AsyncWorker () ()]
-> ResultG (AsyncWorker Any ()))
-- ^ A function that creates a worker that asynchronously
-- saves the configuration to the master file.
-> (IO ConfigState -> ResultG (AsyncWorker () ()))
-- ^ A function that creates a worker that asynchronously
-- distributes the configuration to master candidates
-> (IO ConfigState -> ResultG (AsyncWorker () ()))
-- ^ A function that creates a worker that asynchronously
-- distributes SSConf to nodes
-> (IO GanetiLockWaiting -> ResultG (AsyncWorker () ()))
-- ^ A function that creates a worker that asynchronously
-- saves the lock allocation state.
-> (IO TempResState -> ResultG (AsyncWorker () ()))
-- ^ A function that creates a worker that asynchronously
-- saves the temporary reservations state.
-> Livelock
-> ResultG DaemonHandle
mkDaemonHandle cpath cstat lstat trstat
saveWorkerFn distMCsWorkerFn distSSConfWorkerFn
saveLockWorkerFn saveTempResWorkerFn livelock = do
ds <- newIORef $ DaemonState cstat lstat trstat
let readConfigIO = dsConfigState `liftM` readIORef ds :: IO ConfigState
ssconfWorker <- distSSConfWorkerFn readConfigIO
distMCsWorker <- distMCsWorkerFn readConfigIO
saveWorker <- saveWorkerFn readConfigIO [ distMCsWorker
, ssconfWorker ]
saveLockWorker <- saveLockWorkerFn $ dsLockWaiting `liftM` readIORef ds
saveTempResWorker <- saveTempResWorkerFn $ dsTempRes `liftM` readIORef ds
return $ DaemonHandle ds cpath saveWorker saveLockWorker saveTempResWorker
livelock
-- * The monad and its instances
-- | A type alias for easier referring to the actual content of the monad
-- when implementing its instances.
type WConfdMonadIntType = ReaderT DaemonHandle IO
-- | The internal part of the monad without error handling.
newtype WConfdMonadInt a = WConfdMonadInt
{ getWConfdMonadInt :: WConfdMonadIntType a }
deriving (Functor, Applicative, Monad, MonadIO, MonadBase IO, MonadLog)
instance MonadBaseControl IO WConfdMonadInt where
#if MIN_VERSION_monad_control(1,0,0)
-- Needs Undecidable instances
type StM WConfdMonadInt b = StM WConfdMonadIntType b
liftBaseWith f = WConfdMonadInt . liftBaseWith
$ \r -> f (r . getWConfdMonadInt)
restoreM = WConfdMonadInt . restoreM
#else
newtype StM WConfdMonadInt b = StMWConfdMonadInt
{ runStMWConfdMonadInt :: StM WConfdMonadIntType b }
liftBaseWith f = WConfdMonadInt . liftBaseWith
$ \r -> f (liftM StMWConfdMonadInt . r . getWConfdMonadInt)
restoreM = WConfdMonadInt . restoreM . runStMWConfdMonadInt
#endif
-- | Runs the internal part of the WConfdMonad monad on a given daemon
-- handle.
runWConfdMonadInt :: WConfdMonadInt a -> DaemonHandle -> IO a
runWConfdMonadInt (WConfdMonadInt k) = runReaderT k
-- | The complete monad with error handling.
type WConfdMonad = ResultT GanetiException WConfdMonadInt
-- | A pure monad that logs and reports errors used for atomic modifications.
type AtomicModifyMonad a = ResultT GanetiException WriterLog a
-- * Basic functions in the monad
-- | Returns the daemon handle.
daemonHandle :: WConfdMonad DaemonHandle
daemonHandle = lift . WConfdMonadInt $ ask
-- | Returns the current configuration, given a handle
readConfigState :: WConfdMonad ConfigState
readConfigState = liftM dsConfigState . readIORef . dhDaemonState
=<< daemonHandle
-- | From a result of a configuration change, determine if the
-- configuration was changed and if full distribution is needed.
-- If so, also bump the serial number.
unpackConfigResult :: ClockTime -> ConfigState
-> (a, ConfigState) -> ((a, Bool, Bool), ConfigState)
unpackConfigResult now cs (r, cs')
| cs /= cs' = ( (r, True, needsFullDist cs cs')
, over csConfigDataL (bumpSerial now) cs'
)
| otherwise = ((r, False, False), cs')
-- | Atomically modifies the configuration state in the WConfdMonad
-- with a computation that can possibly fail; immediately afterwards,
-- while config write is still going on, do the followup action. Return
-- only after replication is finished.
modifyConfigStateErrWithImmediate
:: (TempResState -> ConfigState -> AtomicModifyMonad (a, ConfigState))
-> WConfdMonad ()
-> WConfdMonad a
modifyConfigStateErrWithImmediate f immediateFollowup = do
dh <- daemonHandle
now <- liftIO getClockTime
let modCS ds@(DaemonState { dsTempRes = tr }) =
mapMOf2
dsConfigStateL (\cs -> liftM (unpackConfigResult now cs) (f tr cs)) ds
(r, modified, distSync) <- atomicModifyIORefErrLog (dhDaemonState dh)
(liftM swap . modCS)
if modified
then if distSync
then do
logDebug $ "Triggering config write" ++
" together with full synchronous distribution"
res <- liftBase . triggerWithResult (Any True) $ dhSaveConfigWorker dh
immediateFollowup
wait res
logDebug "Config write and distribution finished"
else do
-- trigger the config. saving worker and wait for it
logDebug $ "Triggering config write" ++
" and asynchronous distribution"
res <- liftBase . triggerWithResult (Any False) $ dhSaveConfigWorker dh
immediateFollowup
wait res
logDebug "Config writer finished with local task"
else
immediateFollowup
return r
-- | Atomically modifies the configuration state in the WConfdMonad
-- with a computation that can possibly fail.
modifyConfigStateErr
:: (TempResState -> ConfigState -> AtomicModifyMonad (a, ConfigState))
-> WConfdMonad a
modifyConfigStateErr = flip modifyConfigStateErrWithImmediate (return ())
-- | Atomically modifies the configuration state in the WConfdMonad
-- with a computation that can possibly fail.
modifyConfigStateErr_
:: (TempResState -> ConfigState -> AtomicModifyMonad ConfigState)
-> WConfdMonad ()
modifyConfigStateErr_ f = modifyConfigStateErr ((liftM ((,) ()) .) . f)
-- | Atomically modifies the configuration state in the WConfdMonad.
modifyConfigState :: (ConfigState -> (a, ConfigState)) -> WConfdMonad a
modifyConfigState f = modifyConfigStateErr ((return .) . const f)
-- | Atomically modifies the configuration state in WConfdMonad; immediately
-- afterwards (while the config write-out is not necessarily finished) do
-- another acation.
modifyConfigStateWithImmediate :: (ConfigState -> (a, ConfigState))
-> WConfdMonad ()
-> WConfdMonad a
modifyConfigStateWithImmediate f =
modifyConfigStateErrWithImmediate ((return .) . const f)
-- | Force the distribution of configuration without actually modifying it.
--
-- We need a separate call for this operation, because 'modifyConfigState' only
-- triggers the distribution when the configuration changes.
forceConfigStateDistribution :: WConfdMonad ()
forceConfigStateDistribution = do
logDebug "Forcing synchronous config write together with full distribution"
dh <- daemonHandle
liftBase . triggerAndWait (Any True) . dhSaveConfigWorker $ dh
logDebug "Forced config write and distribution finished"
-- | Atomically modifies the configuration data in the WConfdMonad
-- with a computation that can possibly fail.
modifyConfigDataErr_
:: (TempResState -> ConfigData -> AtomicModifyMonad ConfigData)
-> WConfdMonad ()
modifyConfigDataErr_ f =
modifyConfigStateErr_ (traverseOf csConfigDataL . f)
-- | Atomically modifies the state of temporary reservations in
-- WConfdMonad in the presence of possible errors.
modifyTempResStateErr
:: (ConfigData -> StateT TempResState ErrorResult a) -> WConfdMonad a
modifyTempResStateErr f = do
-- we use Compose to traverse the composition of applicative functors
-- @ErrorResult@ and @(,) a@
let f' ds = traverseOf2 dsTempResL
(runStateT (f (csConfigData . dsConfigState $ ds))) ds
dh <- daemonHandle
r <- toErrorBase $ atomicModifyIORefErr (dhDaemonState dh)
(liftM swap . f')
-- logDebug $ "Current temporary reservations: " ++ J.encode tr
logDebug "Triggering temporary reservations write"
liftBase . triggerAndWait_ . dhSaveTempResWorker $ dh
logDebug "Temporary reservations write finished"
return r
-- | Atomically modifies the state of temporary reservations in
-- WConfdMonad.
modifyTempResState :: (ConfigData -> State TempResState a) -> WConfdMonad a
modifyTempResState f =
modifyTempResStateErr (mapStateT (return . runIdentity) . f)
-- | Reads the state of of the configuration and temporary reservations
-- in WConfdMonad.
readTempResState :: WConfdMonad (ConfigData, TempResState)
readTempResState = liftM (csConfigData . dsConfigState &&& dsTempRes)
. readIORef . dhDaemonState
=<< daemonHandle
-- | Atomically modifies the lock waiting state in WConfdMonad.
modifyLockWaiting :: (GanetiLockWaiting -> ( GanetiLockWaiting
, (a, S.Set ClientId) ))
-> WConfdMonad a
modifyLockWaiting f = do
dh <- lift . WConfdMonadInt $ ask
let f' = (id &&& fst) . f
(lockAlloc, (r, nfy)) <- atomicModifyWithLens
(dhDaemonState dh) dsLockWaitingL f'
logDebug $ "Current lock status: " ++ J.encode lockAlloc
logDebug "Triggering lock state write"
liftBase . triggerAndWait_ . dhSaveLocksWorker $ dh
logDebug "Lock write finished"
unless (S.null nfy) $ do
logDebug . (++) "Locks became available for " . show $ S.toList nfy
liftIO . mapM_ (notifyJob . ciPid) $ S.toList nfy
logDebug "Finished notifying processes"
return r
-- | Atomically modifies the lock allocation state in WConfdMonad, not
-- producing any result
modifyLockWaiting_ :: (GanetiLockWaiting -> (GanetiLockWaiting, S.Set ClientId))
-> WConfdMonad ()
modifyLockWaiting_ = modifyLockWaiting . ((second $ (,) ()) .)
-- | Read the lock waiting state in WConfdMonad.
readLockWaiting :: WConfdMonad GanetiLockWaiting
readLockWaiting = liftM dsLockWaiting
. readIORef . dhDaemonState
=<< daemonHandle
-- | Read the underlying lock allocation.
readLockAllocation :: WConfdMonad (LA.LockAllocation GanetiLocks ClientId)
readLockAllocation = liftM LW.getAllocation readLockWaiting
-- | Modify the configuration while temporarily acquiring
-- the configuration lock. If the configuration lock is held by
-- someone else, nothing is changed and Nothing is returned.
modifyConfigAndReturnWithLock
:: (TempResState -> ConfigState -> AtomicModifyMonad (a, ConfigState))
-> State TempResState ()
-> WConfdMonad (Maybe a)
modifyConfigAndReturnWithLock f tempres = do
now <- liftIO getClockTime
dh <- lift . WConfdMonadInt $ ask
pid <- liftIO getProcessID
tid <- liftIO myThreadId
let cid = ClientId { ciIdentifier = ClientOther $ "wconfd-" ++ show tid
, ciLockFile = dhLivelock dh
, ciPid = pid
}
let modCS ds@(DaemonState { dsTempRes = tr }) =
mapMOf2
dsConfigStateL
(\cs -> liftM (unpackConfigResult now cs) (f tr cs))
ds
maybeDist <- bracket
(atomicModifyWithLens (dhDaemonState dh) dsLockWaitingL
$ swap . LW.updateLocks cid [LA.requestExclusive ConfigLock])
(\(res, _) -> case res of
Ok s | S.null s -> do
(_, nfy) <- atomicModifyWithLens (dhDaemonState dh) dsLockWaitingL
$ swap . LW.updateLocks cid [LA.requestRelease ConfigLock]
unless (S.null nfy) . liftIO . void . forkIO $ do
logDebug . (++) "Locks became available for " . show $ S.toList nfy
mapM_ (notifyJob . ciPid) $ S.toList nfy
logDebug "Finished notifying processes"
_ -> return ())
(\(res, _) -> case res of
Ok s | S.null s ->do
ret <- atomicModifyIORefErrLog (dhDaemonState dh)
(liftM swap . modCS)
atomicModifyWithLens (dhDaemonState dh) dsTempResL $ runState tempres
return $ Just ret
_ -> return Nothing)
flip (maybe $ return Nothing) maybeDist $ \(val, modified, dist) -> do
when modified $ do
logDebug . (++) "Triggering config write; distribution "
$ if dist then "synchronously" else "asynchronously"
liftBase . triggerAndWait (Any dist) $ dhSaveConfigWorker dh
logDebug "Config write finished"
logDebug "Triggering temporary reservations write"
liftBase . triggerAndWait_ . dhSaveTempResWorker $ dh
logDebug "Temporary reservations write finished"
return $ Just val
modifyConfigWithLock
:: (TempResState -> ConfigState -> AtomicModifyMonad ConfigState)
-> State TempResState ()
-> WConfdMonad (Maybe ())
modifyConfigWithLock f = modifyConfigAndReturnWithLock f'
where f' tr cs = fmap ((,) ()) (f tr cs)
| bitemyapp/ganeti | src/Ganeti/WConfd/Monad.hs | bsd-2-clause | 17,648 | 0 | 24 | 4,029 | 3,233 | 1,690 | 1,543 | -1 | -1 |
Subsets and Splits