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
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} -- | -- Module : Database.HDBC.Schema.SQLite3 -- Copyright : 2013 Shohei Murayama -- License : BSD3 -- -- Maintainer : shohei.murayama@gmail.com -- Stability : experimental -- Portability : unknown module Database.HDBC.Schema.SQLite3 ( driverSQLite3 ) where import qualified Language.Haskell.TH.Lib.Extra as TH import qualified Database.Relational.Schema.SQLite3Syscat.IndexInfo as IndexInfo import qualified Database.Relational.Schema.SQLite3Syscat.IndexList as IndexList import qualified Database.Relational.Schema.SQLite3Syscat.TableInfo as TableInfo import Data.List (isPrefixOf, sort, sortBy) import Data.Map (fromList) import Database.HDBC (IConnection, SqlValue) import Database.HDBC.Record.Query (runQuery') import Database.HDBC.Record.Persistable () import Database.HDBC.Schema.Driver (TypeMap, Driver, getFieldsWithMap, getPrimaryKey, emptyDriver) import Database.Record.TH (makeRecordPersistableWithSqlTypeDefaultFromDefined) import Database.Relational.Schema.SQLite3 (getType, indexInfoQuerySQL, indexListQuerySQL, normalizeColumn, normalizeType, notNull, tableInfoQuerySQL) import Database.Relational.Schema.SQLite3Syscat.IndexInfo (IndexInfo) import Database.Relational.Schema.SQLite3Syscat.IndexList (IndexList) import Database.Relational.Schema.SQLite3Syscat.TableInfo (TableInfo) import Language.Haskell.TH (TypeQ) $(makeRecordPersistableWithSqlTypeDefaultFromDefined [t| SqlValue |] ''TableInfo) $(makeRecordPersistableWithSqlTypeDefaultFromDefined [t| SqlValue |] ''IndexList) $(makeRecordPersistableWithSqlTypeDefaultFromDefined [t| SqlValue |] ''IndexInfo) logPrefix :: String -> String logPrefix = ("SQLite3: " ++) putLog :: String -> IO () putLog = putStrLn . logPrefix compileErrorIO :: String -> IO a compileErrorIO = TH.compileErrorIO . logPrefix getPrimaryKey' :: IConnection conn => conn -> String -> String -> IO [String] getPrimaryKey' conn scm tbl = do tblinfo <- runQuery' conn (tableInfoQuerySQL scm tbl) () let primColumns = map (normalizeColumn . TableInfo.name) . filter ((1 ==) . TableInfo.pk) $ tblinfo if length primColumns <= 1 then do putLog $ "getPrimaryKey: key=" ++ show primColumns return primColumns else do idxlist <- runQuery' conn (indexListQuerySQL scm tbl) () let idxNames = filter (isPrefixOf "sqlite_autoindex_") . map IndexList.name . filter ((1 ==) . IndexList.unique) $ idxlist idxInfos <- mapM (\ixn -> runQuery' conn (indexInfoQuerySQL scm ixn) ()) idxNames let isPrimaryKey = (sort primColumns ==) . sort . map (normalizeColumn . IndexInfo.name) let idxInfo = concat . take 1 . filter isPrimaryKey $ idxInfos let comp x y = compare (IndexInfo.seqno x) (IndexInfo.seqno y) let primColumns' = map IndexInfo.name . sortBy comp $ idxInfo putLog $ "getPrimaryKey: keys=" ++ show primColumns' return primColumns' getFields' :: IConnection conn => TypeMap -> conn -> String -> String -> IO ([(String, TypeQ)], [Int]) getFields' tmap conn scm tbl = do rows <- runQuery' conn (tableInfoQuerySQL scm tbl) () case rows of [] -> compileErrorIO $ "getFields: No columns found: schema = " ++ scm ++ ", table = " ++ tbl _ -> return () let columnId = TableInfo.cid let notNullIdxs = map (fromIntegral . columnId) . filter notNull $ rows putLog $ "getFields: num of columns = " ++ show (length rows) ++ ", not null columns = " ++ show notNullIdxs let getType' ti = case getType (fromList tmap) ti of Nothing -> compileErrorIO $ "Type mapping is not defined against SQLite3 type: " ++ normalizeType (TableInfo.ctype ti) Just p -> return p types <- mapM getType' rows return (types, notNullIdxs) driverSQLite3 :: IConnection conn => Driver conn driverSQLite3 = emptyDriver { getFieldsWithMap = getFields' } { getPrimaryKey = getPrimaryKey' }
yuga/haskell-relational-record-driver-sqlite3
src/Database/HDBC/Schema/SQLite3.hs
bsd-3-clause
4,318
0
18
997
1,091
586
505
86
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE TupleSections #-} module Handler.Site where import Control.Applicative hiding (empty) import Control.Lens (set) import "mtl" Control.Monad.Trans import "either" Control.Monad.Trans.Either import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import Data.List (intersperse) import Data.Map (Map, assocs, empty, fromList, insert, lookup, (!)) import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Heist import Heist.Interpreted (Splice, addTemplate, bindSplice, bindSplices, lookupSplice, renderTemplate, runChildrenWith, textSplice) import Heist.Splices.BindStrict import Heist.Splices.Html import Network.HTTP.Conduit (Manager) import Prelude hiding (lookup) import qualified Prelude as L (lookup) import Snap.Core import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Heist import Snap.Util.FileServe import Snap.Util.FileUploads import Text.Digestive import Text.Digestive.Heist import Text.Digestive.Snap hiding (method) import Text.XmlHtml hiding (render) import Web.Analyze.Client import Application import Handler.API import Handler.Auth import Helpers.Forms import Helpers.Misc import Helpers.State import Helpers.Text import Splice.Blob import Splice.Data import Splice.File import Splice.HeaderFile import Splice.Page import Splice.Site import Splice.User import State.Blob import State.Data import State.File import State.HeaderFile import State.Image import State.Page import State.Site import State.User sitePath :: Site -> ByteString sitePath (Site id' _ _) = B.append "/site/" (B8.pack (show id')) siteForm :: Maybe Site -> Form Text AppHandler (Text, Text) siteForm old = (,) <$> "base" .: validateHtml (nonEmpty (text (fmap siteBase old))) <*> "token" .: text (siteAnalyzeToken =<< old) renderError :: AppHandler () renderError = render "error" newSiteHandler :: AppHandler () newSiteHandler = do r <- runForm "new-site" (siteForm (Just (Site (-1) "<authlink/>\n\n<apply-content/>" Nothing))) case r of (v, Nothing) -> renderWithSplices "site/new" (digestiveSplices v) (_, Just (base, token)) -> do mid <- newSite (Site (-1) base (if token == "" then Nothing else Just token)) case mid of Nothing -> error "Site could not be created" Just site_id -> do user <- fmap fromJust $ with auth currentUser newSiteUser (SiteUser ((read . T.unpack . unUid . fromJust . userId) user) site_id False) redirect (sitePath (Site site_id "" Nothing)) manageSiteHandler :: AppHandler () manageSiteHandler = do mid <- getParam "site_id" case fmap B8.unpack mid >>= readSafe of Nothing -> pass Just id' -> do msite <- getSiteById id' case msite of Nothing -> pass Just site -> route [("", ifTop $ showSiteHandler site) ,("/edit", editSiteHandler site) ,("/domain/new", newDomainHandler site) ,("/domain/:id/delete", deleteDomainHandler site) ,("/data/new", newDataHandler site) ,("/data/:id/add", addDataFieldHandler site) ,("/page/new", newPageHandler site) ,("/page/edit/:id", editPageHandler site) ,("/header/new", newHeaderHandler site) ,("/header/edit/:id", editHeaderHandler site) ,("/header/delete/:id", deleteHeaderHandler site) ,("/user/new", newUserHandler site) ,("/user/edit/:id", editUserHandler site) ,("/user/delete/:id", deleteUserHandler site) ,("/blob/new", newBlobHandler site) ,("/blob/edit/:id", editBlobHandler site) ,("/file/new", newFileHandler site) ,("/file/delete/:id", deleteFileHandler site) ] showSiteHandler :: Site -> AppHandler () showSiteHandler site = do ds <- getSiteData site pgs <- getSitePages site hdrs <- getSiteHeaders site blobs <- getSiteBlobs site users <- getSiteUsers site files <- getSiteFiles site renderWithSplices "site/index" $ do "site_id" ## textSplice (tshow (siteId site)) "domain" ## do domains <- map snd <$> lift (getSiteUrls site) textSplice (fromMaybe "" (listToMaybe domains)) "domains" ## domainsSplice site "users" ## manageUsersSplice users "data" ## manageDataSplice ds "pages" ## managePagesSplice pgs "headers" ## manageHeadersSplice hdrs "blobs" ## manageBlobsSplice blobs "files" ## manageFilesSplice files editSiteHandler :: Site -> AppHandler () editSiteHandler site = do r <- runForm "edit-base" (siteForm (Just site)) case r of (v, Nothing) -> renderWithSplices "site/edit" (digestiveSplices v <> siteSplices site) (_, Just (base, token)) -> do updateSite (site { siteBase = base, siteAnalyzeToken = if token == "" then Nothing else Just token }) redirect (sitePath site) newGenHandler :: Site -> Form Text AppHandler a -> ByteString -> (a -> AppHandler ()) -> AppHandler () newGenHandler site form tmpl creat = do r <- runForm "new-gen" form case r of (v, Nothing) -> renderWithSplices tmpl (digestiveSplices v) (_, Just x) -> do creat x redirect (sitePath site) editGenHandler :: Site -> (Int -> Site -> AppHandler (Maybe a)) -> Formlet Text AppHandler a -> ByteString -> (a -> AppHandler ()) -> AppHandler () editGenHandler site getter form tmpl updt = do mid <- getParam "id" case bsId mid of Nothing -> pass Just id' -> do mo <- getter id' site case mo of Nothing -> pass Just obj -> do r <- runForm "edit-gen" $ form (Just obj) case r of (v, Nothing) -> renderWithSplices tmpl (digestiveSplices v <> ("site" ## runChildrenWith (siteSplices site)) <> ("user-id" ## textSplice (tshow id'))) (_, Just x) -> do updt x redirect (sitePath site) deleteGenHandler :: Site -> (Int -> Site -> AppHandler ()) -> AppHandler () deleteGenHandler site dlt = do mid <- getParam "id" case bsId mid of Nothing -> pass Just id' -> do dlt id' site redirect (sitePath site) newDomainForm :: Form Text AppHandler Text newDomainForm = "url" .: checkM "Domain already in use." (\d -> isNothing <$> getSiteByName d) nonEmptyTextForm newDomainHandler :: Site -> AppHandler () newDomainHandler site = newGenHandler site newDomainForm "domain/new" (newDomain site) deleteDomainHandler :: Site -> AppHandler () deleteDomainHandler site = deleteGenHandler site deleteDomain newDataForm :: Form Text AppHandler (Text, Map Text FieldSpec) newDataForm = (,) <$> "name" .: nonEmptyTextForm <*> "fields" .: jsonMapForm newDataHandler :: Site -> AppHandler () newDataHandler site = newGenHandler site newDataForm "data/new" $ \(name, fields) -> void $ newData (Data (-1) (siteId site) name fields) addDataFieldForm :: Form Text AppHandler (Text, FieldSpec) addDataFieldForm = (,) <$> "name" .: nonEmptyTextForm <*> "type" .: fieldSpecForm addDataFieldHandler :: Site -> AppHandler () addDataFieldHandler site = do mid <- getParam "id" case bsId mid of Nothing -> pass Just id' -> do md <- getDataById site id' case md of Nothing -> pass Just d -> do newGenHandler site addDataFieldForm "data/add_field" $ \(name, typ) -> do items <- getItems d mapM_ updateItem (map (\i -> i { itemFields = insert name (defaultField typ) (itemFields i)}) items) updateData (d { dataFields = insert name typ (dataFields d)}) pageForm :: Site -> Maybe Page -> Form Text AppHandler Page pageForm site p = mkPg <$> "flat" .: nonEmpty (text $ fmap (decodeUtf8 . pageFlat) p) <*> "structured" .: nonEmpty (text $ fmap pageStructured p) <*> "body" .: validateHtml (nonEmpty (text $ fmap pageBody p)) where mkPg f s b = case p of Nothing -> Page (-1) (siteId site) (encodeUtf8 f) s b Just pg -> pg { pageFlat = encodeUtf8 f, pageStructured = s, pageBody = b } newPageHandler :: Site -> AppHandler () newPageHandler site = newGenHandler site (pageForm site Nothing) "page/new" (void . newPage) editPageHandler :: Site -> AppHandler () editPageHandler site = editGenHandler site getPageById (pageForm site) "page/edit" updatePage headerForm :: Site -> Maybe HeaderFile -> Form Text AppHandler HeaderFile headerForm site h = mkHeader <$> "name" .: nonEmpty (text $ fmap headerFileName h) <*> "type" .: choice [ (HeaderCSS, "CSS") , (HeaderJavascript, "Javascript")] (fmap headerFileType h) <*> "content" .: nonEmpty (text $ fmap headerFileContent h) where mkHeader n t c = case h of Nothing -> HeaderFile (-1) (siteId site) t n c Just header -> header { headerFileType = t , headerFileName = n , headerFileContent = c } newHeaderHandler :: Site -> AppHandler () newHeaderHandler site = newGenHandler site (headerForm site Nothing) "header/new" (void . newHeader) editHeaderHandler :: Site -> AppHandler () editHeaderHandler site = editGenHandler site getHeaderById (headerForm site) "header/edit" updateHeader deleteHeaderHandler :: Site -> AppHandler () deleteHeaderHandler site = deleteGenHandler site deleteHeaderFile blobForm :: Site -> Maybe Blob -> Form Text AppHandler Blob blobForm site b = mkBlob <$> "name" .: nonEmpty (text (fmap blobName b)) <*> "type" .: choice [(BlobPlain, "Plain Text") ,(BlobMarkdown, "Markdown") ,(BlobHTML, "HTML")] (fmap blobType b) <*> "admin" .: bool (fmap blobAdmin b) where mkBlob n t a = case b of Nothing -> Blob (-1) (siteId site) n "" t a Just blob -> blob { blobName = n , blobType = t , blobAdmin = a } newBlobHandler :: Site -> AppHandler () newBlobHandler site = newGenHandler site (blobForm site Nothing) "blob/new" (void . newBlob) editBlobHandler :: Site -> AppHandler () editBlobHandler site = editGenHandler site getBlobById (blobForm site) "blob/edit" updateBlob newUserHandler :: Site -> AppHandler () newUserHandler site = newGenHandler site (userForm Nothing) "user/new" $ \(UserData login p) -> do mu <- with auth $ createUser login (encodeUtf8 p) case mu of Left err -> return () Right au -> case userId au of Nothing -> return () Just uid -> newUser (SiteUser (read $ T.unpack $ unUid uid) (siteId site) False) editUserHandler :: Site -> AppHandler () editUserHandler site = editGenHandler site getUserData editUserForm "user/edit" $ \(EditUserData login p admn) -> do mid <- getParam "id" case bsId mid of Nothing -> redirect (sitePath site) Just id' -> do mu <- with auth $ withBackend $ \r -> liftIO $ lookupByUserId r (UserId (tshow id')) case mu of Nothing -> redirect (sitePath site) Just au -> do newau <- case p of "" -> return au _ -> liftIO $ setPassword au (encodeUtf8 p) with auth $ saveUser newau { userLogin = login } updateUser (SiteUser id' (siteId site) admn) redirect (sitePath site) where getUserData id' _ = do mn <- getUserAndNameById id' case mn of Nothing -> return Nothing Just (su, n) -> return (Just (EditUserData n "" (siteUserAdmin su))) deleteUserHandler :: Site -> AppHandler () deleteUserHandler site = deleteGenHandler site (\id' site -> do p <- getParam "permanent" case p of Nothing -> deleteSiteUser site id' Just _ -> deleteUser id') fileForm :: Site -> Maybe File -> Form Text AppHandler File fileForm site f = mkFile <$> "name" .: (T.toLower <$> noSpaces (nonEmpty (text (fmap fileName f)))) <*> "file" .: imageForm where mkFile = File (-1) (siteId site) newFileHandler :: Site -> AppHandler () newFileHandler site = do r <- runForm' "file-form" (fileForm site Nothing) case r of (v, Nothing) -> renderWithSplices "file/new" (digestiveSplices v) (_, Just f) -> do i <- newFile f case i of Nothing -> return () Just i' -> do p <- storeFile (tshow i') (filePath f) site updateFile f { fileId = i', filePath = p} redirect (sitePath site) deleteFileHandler :: Site -> AppHandler () deleteFileHandler site = deleteGenHandler site deleteFile -- What follows is routing the frontend of the site, ie when accessed from the -- site's domain. loginGuard :: AppHandler () -> AppHandler () loginGuard hndlr = do li <- with auth isLoggedIn if li then hndlr else do modifyResponse (setResponseCode 401) return () loginGuard' :: (SiteUser -> AppHandler ()) -> AppHandler () loginGuard' hndlr = do u <- with auth currentUser case u >>= userId of Nothing -> forbidden Just id' -> do su <- getUser (read (T.unpack (unUid id'))) case su of Nothing -> forbidden Just siteuser -> hndlr siteuser siteHandler :: Manager -> Site -> AppHandler () siteHandler man site = siteWrap $ route [("/api", loginGuard' $ siteApiHandler site) ,("/login", loginHandler) ,("/logout", logoutHandler) ,("/signup", signupHandler) ,("/images/:name", imagesHandler site) ,("/files/:name", filesHandler site) ,("/header/:id", headerHandler site) ,("", do pages <- getSitePages site routePages site pages)] where siteWrap = case siteAnalyzeToken site of Nothing -> id Just token -> wrap renderError man (encodeUtf8 token) imagesHandler :: Site -> AppHandler () imagesHandler site = do n <- getParam "name" case n of Nothing -> pass Just name -> do repo <- getImageRepository serveFile ((T.unpack repo) ++ "/" ++ (B8.unpack name)) filesHandler :: Site -> AppHandler () filesHandler site = do n <- getParam "name" case fmap decodeUtf8 n of Nothing -> pass Just name -> case (tshow (siteId site)) `T.isPrefixOf` name of True -> do repo <- getFileRepository serveFile ((T.unpack repo) ++ "/" ++ (T.unpack name)) False -> pass headerHandler :: Site -> AppHandler () headerHandler site = do i <- getParam "id" case i >>= (readSafe . T.unpack . decodeUtf8) of Nothing -> pass Just id' -> do hf <- getHeaderById id' site case hf of Nothing -> pass Just header -> writeText (headerFileContent header) routePages :: Site -> [Page] -> AppHandler () routePages site pgs = route (map (\p -> (pageFlat p, ifTop $ renderPage site p)) pgs) rebindSplice :: Splice AppHandler rebindSplice = do node <- getParamNode let attrs = do o <- getAttribute "old" node n <- getAttribute "new" node return (o, n) case attrs of Nothing -> return [] Just (old, new) -> do st <- getHS let spl = lookupSplice old st case spl of Nothing -> return [] Just splice -> do modifyHS $ bindSplice new splice return [] authLinkSplice :: Splice AppHandler authLinkSplice = do mau <- lift $ with auth currentUser u <- lift $ fmap rqURI getRequest let url = decodeUtf8 (urlEncode u) return (case mau of Just au -> [Element "a" [("class", "authlink ps-link") ,("href", T.append "/logout?redirect=" url) ,("title", userLogin au) ] [TextNode "Logout"]] Nothing -> [Element "a" [("class", "authlink ps-link") ,("href", T.append "/login?redirect=" url) ] [TextNode "Login"]]) headersSplice :: Site -> Splice AppHandler headersSplice site = do hfs <- lift $ getSiteHeaders site return (map renderHeader hfs) where renderHeader hf = case headerFileType hf of HeaderCSS -> Element "link" [("href", T.concat ["/header/", tshow (headerFileId hf), "/src.css"]) ,("rel", "stylesheet") ,("type", "text/css")] [] HeaderJavascript -> Element "script" [("src", T.concat ["/header/", tshow (headerFileId hf), "/src.js"]) ,("type", "text/javascript")] [] blobSplice :: Site -> Splice AppHandler blobSplice site = do node <- getParamNode case "name" `L.lookup` (elementAttrs node) of Nothing -> return [] Just name -> do b <- lift $ getBlobByName site name case b of Nothing -> return [] Just blob -> return (renderBlob blob) where renderBlob b = case blobType b of BlobPlain -> newlineReplace (blobContent b) BlobHTML -> case parseHTML "" (encodeUtf8 $ blobContent b) of Left err -> [] Right html -> docContent html BlobMarkdown -> error "Don't support markdown yet." setBlobSplice :: Site -> Splice AppHandler setBlobSplice site = do node <- getParamNode case "name" `L.lookup` (elementAttrs node) of Nothing -> return [] Just name -> do b <- lift $ getBlobByName site name case b of Nothing -> return [] Just blob -> if blobAdmin blob -- force an admin check then loginGuardSplice' (Item (-1) (-1) (-1) (-1) empty) $ do linkSplice editPoint (T.concat ["/api/blob/set/", tshow (blobId blob)]) -- just a regular login check else loginGuardSplice $ do linkSplice editPoint (T.concat ["/api/blob/set/", tshow (blobId blob)]) isUrlSplice :: Splice AppHandler isUrlSplice = do node <- getParamNode case getAttribute "url" node of Nothing -> return [] Just u -> do url <- fmap rqURI getRequest if u == (decodeUtf8 url) then return (elementChildren node) else return [] prefixUrlSplice :: Splice AppHandler prefixUrlSplice = do node <- getParamNode case getAttribute "url" node of Nothing -> return [] Just u -> do url <- fmap rqURI getRequest if u `T.isPrefixOf` (decodeUtf8 url) then return (elementChildren node) else return [] fileSplice :: Site -> Splice AppHandler fileSplice site = do node <- getParamNode case "name" `L.lookup` (elementAttrs node) of Nothing -> return [] Just name -> do f <- lift $ getFileByName name site case f of Nothing -> return [] Just file -> return [TextNode (T.append "/files" (filePath file))] clientSiteSplices :: Site -> Splices (Splice AppHandler) clientSiteSplices site = do "rebind" ## rebindSplice "authlink" ## authLinkSplice "html" ## htmlImpl "headers" ## headersSplice site "blob" ## blobSplice site "set-blob" ## setBlobSplice site "is-url" ## isUrlSplice "prefix-url" ## prefixUrlSplice "file" ## fileSplice site bindStrictTag ## bindStrictImpl renderPage :: Site -> Page -> AppHandler () renderPage s p = do urlDataSplices <- fmap mconcat (mapM (loadData s) (zip (T.splitOn "/" (decodeUtf8 (pageFlat p))) (T.splitOn "/" (pageStructured p)))) ds <- getSiteData s let splices = mconcat (map (dataSplices s) ds) <> clientSiteSplices s modifyResponse (setContentType "text/html") case parseHTML "" (encodeUtf8 $ pageBody p) of Left err -> error (show err) Right html -> do st <- fmap (either (error.show) id) $ liftIO $ runEitherT $ initHeist $ set hcTemplateLocations [loadTemplates "snaplets/heist/templates/sites"] emptyHeistConfig let newst = addTemplate "site_base" (docContent (fromRight (parseHTML "" (encodeUtf8 $ siteBase s)))) Nothing st let newst' = addTemplate "page" [Element "apply" [("template", "site")] (docContent html)] Nothing newst let newst'' = bindSplices (urlDataSplices <> splices <> defaultLoadTimeSplices) newst' res <- renderTemplate newst'' "page" case res of Nothing -> error "Could not render template" Just (builder, _) -> writeBuilder builder loadData :: Site -> (Text, Text) -> AppHandler (Splices (Splice AppHandler)) loadData site (f, s) | T.isPrefixOf "id(" s && T.isSuffixOf ")" s && T.isPrefixOf ":" f = do mparam <- getParam (encodeUtf8 (T.drop 1 f)) case bsId mparam of Nothing -> passLog' ["Param missing or not an integer: ", f] Just id' -> do let name = fromJust $ (T.stripSuffix ")") =<< (T.stripPrefix "id(" s) mdat <- getDataByName site name case mdat of Nothing -> error $ "Unknown data: " ++ (T.unpack name) Just dat -> do mitem <- getItemById site id' case mitem of Nothing -> passLog' ["Id for item does not correspond to an item: ", tshow id'] Just item -> case itemDataId item == dataId dat of False -> passLog' ["Id specified does not correspond to the right data type: ", tshow id', " for data ", name] True -> return $ T.append "this-" name ## runChildrenWith (itemSplices site dat item) where passLog' a = passLog a >> return mempty loadData _ _ = return mempty
dbp/positionsites
src/Handler/Site.hs
bsd-3-clause
25,440
3
30
9,521
7,311
3,619
3,692
539
6
{-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------- -- | -- Module : Database.HaskellDB.HDBC -- Copyright : HWT Group 2003, -- Bjorn Bringert 2005-2006 -- License : BSD-style -- -- Maintainer : haskelldb-users@lists.sourceforge.net -- Stability : experimental -- Portability : portable -- -- HDBC interface for HaskellDB -- ----------------------------------------------------------- module Database.HaskellDB.HDBC (hdbcConnect) where import Database.HaskellDB import Database.HaskellDB.Database import Database.HaskellDB.Sql.Generate (SqlGenerator(..)) import Database.HaskellDB.Sql.Print import Database.HaskellDB.PrimQuery import Database.HaskellDB.Query import Database.HaskellDB.FieldType import Database.HDBC as HDBC hiding (toSql) import Control.Monad.Trans (MonadIO, liftIO) import Data.Char (toLower) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) -- | Run an action on a HDBC IConnection and close the connection. hdbcConnect :: (MonadIO m, IConnection conn) => SqlGenerator -> IO conn -- ^ connection function -> (Database -> m a) -> m a hdbcConnect gen connect action = do conn <- liftIO $ handleSqlError connect x <- action (mkDatabase gen conn) -- FIXME: should we really commit here? liftIO $ HDBC.commit conn liftIO $ handleSqlError (HDBC.disconnect conn) return x mkDatabase :: (IConnection conn) => SqlGenerator -> conn -> Database mkDatabase gen connection = Database { dbQuery = hdbcQuery gen connection, dbInsert = hdbcInsert gen connection, dbInsertQuery = hdbcInsertQuery gen connection, dbDelete = hdbcDelete gen connection, dbUpdate = hdbcUpdate gen connection, dbTables = hdbcTables connection, dbDescribe = hdbcDescribe connection, dbTransaction = hdbcTransaction connection, dbCommit = HDBC.commit connection, dbCreateDB = hdbcCreateDB gen connection, dbCreateTable = hdbcCreateTable gen connection, dbDropDB = hdbcDropDB gen connection, dbDropTable = hdbcDropTable gen connection } hdbcQuery :: (GetRec er vr, IConnection conn) => SqlGenerator -> conn -> PrimQuery -> Rel er -> IO [Record vr] hdbcQuery gen connection q rel = hdbcPrimQuery connection sql scheme rel where sql = show $ ppSql $ sqlQuery gen q scheme = attributes q hdbcInsert :: (IConnection conn) => SqlGenerator -> conn -> TableName -> Assoc -> IO () hdbcInsert gen conn table assoc = hdbcPrimExecute conn $ show $ ppInsert $ sqlInsert gen table assoc hdbcInsertQuery :: (IConnection conn) => SqlGenerator -> conn -> TableName -> PrimQuery -> IO () hdbcInsertQuery gen conn table assoc = hdbcPrimExecute conn $ show $ ppInsert $ sqlInsertQuery gen table assoc hdbcDelete :: (IConnection conn) => SqlGenerator -> conn -> TableName -> [PrimExpr] -> IO () hdbcDelete gen conn table exprs = hdbcPrimExecute conn $ show $ ppDelete $ sqlDelete gen table exprs hdbcUpdate :: (IConnection conn) => SqlGenerator -> conn -> TableName -> [PrimExpr] -> Assoc -> IO () hdbcUpdate gen conn table criteria assigns = hdbcPrimExecute conn $ show $ ppUpdate $ sqlUpdate gen table criteria assigns hdbcTables :: (IConnection conn) => conn -> IO [TableName] hdbcTables conn = handleSqlError $ HDBC.getTables conn hdbcDescribe :: (IConnection conn) => conn -> TableName -> IO [(Attribute,FieldDesc)] hdbcDescribe conn table = handleSqlError $ do cs <- HDBC.describeTable conn table return [(n,colDescToFieldDesc c) | (n,c) <- cs] colDescToFieldDesc :: SqlColDesc -> FieldDesc colDescToFieldDesc c = (t, nullable) where nullable = fromMaybe True (colNullable c) string = maybe StringT BStrT (colSize c) t = case colType c of SqlCharT -> string SqlVarCharT -> string SqlLongVarCharT -> string SqlWCharT -> string SqlWVarCharT -> string SqlWLongVarCharT -> string SqlDecimalT -> IntegerT SqlNumericT -> IntegerT SqlSmallIntT -> IntT SqlIntegerT -> IntT SqlRealT -> DoubleT SqlFloatT -> DoubleT SqlDoubleT -> DoubleT SqlBitT -> BoolT SqlTinyIntT -> IntT SqlBigIntT -> IntT SqlBinaryT -> string SqlVarBinaryT -> string SqlLongVarBinaryT -> string SqlDateT -> CalendarTimeT SqlTimeT -> CalendarTimeT SqlTimestampT -> LocalTimeT SqlUTCDateTimeT -> CalendarTimeT SqlUTCTimeT -> CalendarTimeT SqlTimeWithZoneT -> CalendarTimeT SqlTimestampWithZoneT -> CalendarTimeT SqlIntervalT _ -> string SqlGUIDT -> string SqlUnknownT _ -> string hdbcCreateDB :: (IConnection conn) => SqlGenerator -> conn -> String -> IO () hdbcCreateDB gen conn name = hdbcPrimExecute conn $ show $ ppCreate $ sqlCreateDB gen name hdbcCreateTable :: (IConnection conn) => SqlGenerator -> conn -> TableName -> [(Attribute,FieldDesc)] -> IO () hdbcCreateTable gen conn name attrs = hdbcPrimExecute conn $ show $ ppCreate $ sqlCreateTable gen name attrs hdbcDropDB :: (IConnection conn) => SqlGenerator -> conn -> String -> IO () hdbcDropDB gen conn name = hdbcPrimExecute conn $ show $ ppDrop $ sqlDropDB gen name hdbcDropTable :: (IConnection conn) => SqlGenerator -> conn -> TableName -> IO () hdbcDropTable gen conn name = hdbcPrimExecute conn $ show $ ppDrop $ sqlDropTable gen name -- | HDBC implementation of 'Database.dbTransaction'. hdbcTransaction :: (IConnection conn) => conn -> IO a -> IO a hdbcTransaction conn action = handleSqlError $ HDBC.withTransaction conn (\_ -> action) ----------------------------------------------------------- -- Primitive operations ----------------------------------------------------------- type HDBCRow = Map String HDBC.SqlValue normalizeField :: String -> String normalizeField = map toLower -- | Primitive query hdbcPrimQuery :: (GetRec er vr, IConnection conn) => conn -- ^ Database connection. -> String -- ^ SQL query -> Scheme -- ^ List of field names to retrieve -> Rel er -- ^ Phantom argument to get the return type right. -> IO [Record vr] -- ^ Query results hdbcPrimQuery conn sql scheme rel = do stmt <- handleSqlError $ HDBC.prepare conn sql handleSqlError $ HDBC.execute stmt [] rows <- fetchNormalizedAllRowsAL stmt mapM (getRec hdbcGetInstances rel scheme) $ map Map.fromList rows where fetchNormalizedAllRowsAL sth = do names <- map normalizeField `fmap` getColumnNames sth rows <- fetchAllRows sth return $ map (zip names) rows -- | Primitive execute hdbcPrimExecute :: (IConnection conn) => conn -- ^ Database connection. -> String -- ^ SQL query. -> IO () hdbcPrimExecute conn sql = do handleSqlError $ HDBC.run conn sql [] return () ----------------------------------------------------------- -- Getting data from a statement ----------------------------------------------------------- hdbcGetInstances :: GetInstances HDBCRow hdbcGetInstances = GetInstances { getString = hdbcGetValue , getInt = hdbcGetValue , getInteger = hdbcGetValue , getDouble = hdbcGetValue , getBool = hdbcGetValue , getCalendarTime = hdbcGetValue , getLocalTime = hdbcGetValue } -- hdbcGetValue :: Data.Convertible.Base.Convertible SqlValue a -- => HDBCRow -> String -> IO (Maybe a) hdbcGetValue m f = case Map.lookup (normalizeField f) m of Nothing -> fail $ "No such field " ++ f Just x -> return $ HDBC.fromSql x
m4dc4p/haskelldb
driver-hdbc/Database/HaskellDB/HDBC.hs
bsd-3-clause
8,154
97
13
2,155
2,034
1,068
966
158
29
module Data.RDF.GraphTestUtils where import Data.RDF import Data.RDF.Namespace import Data.ByteString.Lazy.Char8(ByteString) import qualified Data.ByteString.Lazy.Char8 as B import Test.QuickCheck import Data.Char import Data.List import qualified Data.Set as Set --import Data.Map(Map) import qualified Data.Map as Map import Control.Monad import System.IO.Unsafe(unsafePerformIO) instance Arbitrary BaseUrl where arbitrary = oneof $ map (return . BaseUrl . s2b) ["http://example.com/a", "http://asdf.org/b"] --coarbitrary = undefined instance Arbitrary PrefixMappings where arbitrary = oneof $ [return $ PrefixMappings Map.empty, return $ PrefixMappings $ Map.fromAscList [(s2b "eg1", s2b "http://example.com/1"), (s2b "eg2", s2b "http://example.com/2")]] --coarbitrary = undefined -- Test stubs, which just require the appropriate graph impl function -- passed in to determine the graph implementation to be tested. -- empty graph should have no triples p_empty :: RDF g => (g -> Triples) -> g -> Bool p_empty _triplesOf _empty = _triplesOf _empty == [] -- triplesOf any graph should return unique triples used to create it p_mkRdf_triplesOf :: RDF g => (g -> Triples) -> (Triples -> Maybe BaseUrl -> PrefixMappings -> g) -> Triples -> Maybe BaseUrl -> PrefixMappings -> Bool p_mkRdf_triplesOf _triplesOf _mkRdf ts bUrl pms = uordered (_triplesOf (_mkRdf ts bUrl pms)) == uordered ts -- duplicate input triples should not be returned p_mkRdf_no_dupes :: RDF g => (g -> Triples) -> (Triples -> Maybe BaseUrl -> PrefixMappings -> g) -> Triples -> Maybe BaseUrl -> PrefixMappings -> Bool p_mkRdf_no_dupes _triplesOf _mkRdf ts bUrl pms = case null ts of True -> True False -> result == uordered ts where tsWithDupe = head ts : ts result = _triplesOf $ _mkRdf tsWithDupe bUrl pms -- query with all 3 wildcards should yield all triples in graph p_query_match_none :: RDF g => (Triples -> Maybe BaseUrl -> PrefixMappings -> g) -> Triples -> Maybe BaseUrl -> PrefixMappings -> Bool p_query_match_none _mkRdf ts bUrl pms = uordered ts == uordered result where result = query (_mkRdf ts bUrl pms) Nothing Nothing Nothing -- query with no wildcard and a triple in the graph should yield -- a singleton list with just the triple. p_query_matched_spo :: RDF g => (g -> Triples) -> g -> Property p_query_matched_spo _triplesOf gr = classify (null ts) "trivial" $ forAll (tripleFromGen _triplesOf gr) f where ts = _triplesOf gr f t = case t of Nothing -> True (Just t') -> [t'] == queryT gr t' -- query as in p_query_matched_spo after duplicating a triple in the -- graph, so that we can verify that the results just have 1, even -- if the graph itself doesn't ensure that there are no dupes internally. p_query_matched_spo_no_dupes :: RDF g => (g -> Triples) -> (Triples -> Maybe BaseUrl -> PrefixMappings -> g) -> g -> Property p_query_matched_spo_no_dupes _triplesOf _mkRdf gr = classify (null ts) "trivial" $ forAll (tripleFromGen _triplesOf gr) f where ts = _triplesOf gr f t = case t of Nothing -> True Just t' -> [t'] == queryT (mkRdfWithDupe _triplesOf _mkRdf gr t') t' -- query with no wildcard and a triple no in the graph should yield [] p_query_unmatched_spo :: RDF g => (g -> Triples) -> g -> Triple -> Property p_query_unmatched_spo _triplesOf gr t = classify (t `elem` ts) "ignored" $ not (t `elem` ts) ==> [] == queryT gr t where ts = _triplesOf gr -- query with fixed subject and wildcards for pred and obj should yield -- a list with all triples having subject, and graph minus result triples -- should yield all triple with unequal subjects. p_query_match_s :: RDF g => (g -> Triples) -> g -> Property p_query_match_s = mk_query_match_fn sameSubj f where f t = (Just (subjectOf t), Nothing, Nothing) -- query w/ fixed predicate and wildcards for subj and obj should yield -- a list with all triples having predicate, and graph minus result triples -- should yield all triple with unequal predicates. p_query_match_p :: RDF g => (g -> Triples) -> g -> Property p_query_match_p = mk_query_match_fn samePred f where f t = (Nothing, Just (predicateOf t), Nothing) -- likewise for fixed subject and predicate with object wildcard p_query_match_o :: RDF g => (g -> Triples) -> g -> Property p_query_match_o = mk_query_match_fn sameObj f where f t = (Nothing, Nothing, Just (objectOf t)) -- verify likewise for fixed subject and predicate with wildcard object p_query_match_sp :: RDF g => (g -> Triples) -> g -> Property p_query_match_sp = mk_query_match_fn same f where same t1 t2 = sameSubj t1 t2 && samePred t1 t2 f t = (Just $ subjectOf t, Just $ predicateOf t, Nothing) -- fixed subject and object with wildcard predicate p_query_match_so :: RDF g => (g -> Triples) -> g -> Property p_query_match_so = mk_query_match_fn same f where same t1 t2 = sameSubj t1 t2 && sameObj t1 t2 f t = (Just $ subjectOf t, Nothing, Just $ objectOf t) -- fixed predicate and object with wildcard subject p_query_match_po :: RDF g => (g -> Triples) -> g -> Property p_query_match_po = mk_query_match_fn same f where same t1 t2 = samePred t1 t2 && sameObj t1 t2 f t = (Nothing, Just $ predicateOf t, Just $ objectOf t) mk_query_match_fn :: RDF g => (Triple -> Triple -> Bool) -> (Triple -> (Maybe Node, Maybe Node, Maybe Node)) -> (g -> Triples) -> g -> Property mk_query_match_fn tripleCompareFn mkPatternFn _triplesOf gr = forAll (tripleFromGen _triplesOf gr) f where f :: Maybe Triple -> Bool f Nothing = True f (Just t) = let all_ts = _triplesOf gr all_ts_sorted = uordered all_ts results = uordered $ queryC gr (mkPatternFn t) notResults = ldiff all_ts_sorted results in all (tripleCompareFn t) results && all (not . tripleCompareFn t) notResults p_select_match_none :: RDF g => g -> Bool p_select_match_none gr = select gr Nothing Nothing Nothing == removeDupes (triplesOf gr) p_select_match_s :: RDF g => (g -> Triples) -> g -> Property p_select_match_s = p_select_match_fn same mkPattern where same = equivNode (==) subjectOf mkPattern t = (Just (\n -> n == subjectOf t), Nothing, Nothing) p_select_match_p :: RDF g => (g -> Triples) -> g -> Property p_select_match_p = p_select_match_fn same mkPattern where same = equivNode equiv predicateOf equiv (UNode u1) (UNode u2) = B.last (value u1) == B.last (value u2) equiv _ _ = error $ "GraphTestUtils.p_select_match_p.equiv" mkPattern t = (Nothing, Just (\n -> lastChar n == lastChar (predicateOf t)) , Nothing) lastChar (UNode uri) = B.last $ value uri lastChar _ = error "GraphTestUtils.p_select_match_p.lastChar" p_select_match_o :: RDF g => (g -> Triples) -> g -> Property p_select_match_o = p_select_match_fn same mkPattern where same = equivNode (/=) objectOf mkPattern t = (Nothing, Nothing, Just (\n -> n /= objectOf t)) p_select_match_sp :: RDF g => (g -> Triples) -> g -> Property p_select_match_sp = p_select_match_fn same mkPattern where same t1 t2 = subjectOf t1 == subjectOf t2 && predicateOf t1 /= predicateOf t2 mkPattern t = (Just (\n -> n == subjectOf t), Just (\n -> n /= predicateOf t), Nothing) p_select_match_so :: RDF g => (g -> Triples) -> g -> Property p_select_match_so = p_select_match_fn same mkPattern where same t1 t2 = subjectOf t1 /= subjectOf t2 && objectOf t1 == objectOf t2 mkPattern t = (Just (\n -> n /= subjectOf t), Nothing, Just (\n -> n == objectOf t)) p_select_match_po :: RDF g => (g -> Triples) -> g -> Property p_select_match_po = p_select_match_fn same mkPattern where same t1 t2 = predicateOf t1 == predicateOf t2 && objectOf t1 == objectOf t2 mkPattern t = (Nothing, Just (\n -> n == predicateOf t), Just (\n -> n == objectOf t)) p_select_match_spo :: RDF g => (g -> Triples) -> g -> Property p_select_match_spo = p_select_match_fn same mkPattern where same t1 t2 = subjectOf t1 == subjectOf t2 && predicateOf t1 == predicateOf t2 && objectOf t1 /= objectOf t2 mkPattern t = (Just (\n -> n == subjectOf t), Just (\n -> n == predicateOf t), Just (\n -> n /= objectOf t)) equivNode :: (Node -> Node -> Bool) -> (Triple -> Node) -> Triple -> Triple -> Bool equivNode eqFn exFn t1 t2 = (exFn t1) `eqFn` (exFn t2) p_select_match_fn :: RDF g => (Triple -> Triple -> Bool) -> (Triple -> (NodeSelector, NodeSelector, NodeSelector)) -> (g -> Triples) -> g -> Property p_select_match_fn tripleCompareFn mkPatternFn _triplesOf gr = forAll (tripleFromGen _triplesOf gr) f where f :: Maybe Triple -> Bool f Nothing = True f (Just t) = let all_ts = triplesOf gr all_ts_sorted = uordered all_ts results = uordered $ selectC gr (mkPatternFn t) notResults = ldiff all_ts_sorted results in all (tripleCompareFn t) results && all (not . tripleCompareFn t) notResults mkRdfWithDupe :: RDF g => (g -> Triples) -> (Triples -> Maybe BaseUrl -> PrefixMappings -> g) -> g -> Triple -> g mkRdfWithDupe _triplesOf _mkRdf gr t = _mkRdf ts (baseUrl gr) (prefixMappings gr) where ts = t : _triplesOf gr -- Utility functions and test data ... -- -- a curried version of query that delegates to the actual query after unpacking -- curried maybe node pattern. queryC :: RDF g => g -> (Maybe Node, Maybe Node, Maybe Node) -> Triples queryC gr (s, p, o) = query gr s p o selectC :: RDF g => g -> (NodeSelector, NodeSelector, NodeSelector) -> Triples selectC gr (s, p, o) = select gr s p o uncurry3 :: (a -> b -> c -> d) -> ((a, b, c) -> d) uncurry3 fn = \(x,y,z) -> fn x y z curry3 :: ((a, b, c) -> d) -> (a -> b -> c -> d) curry3 fn = \x -> \y -> \z -> fn (x,y,z) debug :: String -> Triples -> Bool debug msg ts = unsafePerformIO $ putStrLn msg >> mapM (putStrLn . show) ts >> return True ldiff :: Triples -> Triples -> Triples ldiff l1 l2 = Set.toList $(Set.fromList l1) `Set.difference` (Set.fromList l2) sameSubj :: Triple -> Triple -> Bool sameSubj t1 t2 = subjectOf t1 == subjectOf t2 samePred :: Triple -> Triple -> Bool samePred t1 t2 = predicateOf t1 == predicateOf t2 sameObj :: Triple -> Triple -> Bool sameObj t1 t2 = objectOf t1 == objectOf t2 -- Convert a list of triples into a sorted list of unique triples. uordered :: Triples -> Triples uordered = map head . group . sortTriples tripleFromGen :: RDF g => (g -> Triples) -> g -> Gen (Maybe Triple) tripleFromGen _triplesOf gr = case null ts of True -> return Nothing False -> oneof $ map (return . Just) ts where ts = _triplesOf gr queryT :: RDF g => g -> Triple -> Triples queryT gr t = query gr (Just $ subjectOf t) (Just $ predicateOf t) (Just $ objectOf t) languages :: [ByteString] languages = [s2b "fr", s2b "en"] datatypes :: [ByteString] datatypes = map (mkUri xsd . s2b) ["string", "int", "token"] uris :: [ByteString] uris = map (mkUri ex) [s2b n `B.append` (s2b $ show (i::Int)) | n <- ["foo", "bar", "quz", "zak"], i <- [0..9]] plainliterals :: [LValue] plainliterals = [plainLL lit lang | lit <- litvalues, lang <- languages] typedliterals :: [LValue] typedliterals = [typedL lit (mkFastString dtype) | lit <- litvalues, dtype <- datatypes] litvalues :: [ByteString] litvalues = map B.pack ["hello", "world", "peace", "earth", "", "haskell"] unodes :: [Node] unodes = map (UNode . mkFastString) uris bnodes :: [ Node] bnodes = map (BNode . mkFastString . \i -> s2b ":_genid" `B.append` (s2b $ show (i::Int))) [1..5] lnodes :: [Node] lnodes = [(LNode lit) | lit <- plainliterals ++ typedliterals] test_triples :: [Triple] test_triples = [triple s p o | s <- (unodes ++ bnodes), p <- unodes, o <- (unodes ++ bnodes ++ lnodes)] maxN :: Int maxN = min 100 (length test_triples - 1) instance Arbitrary Triple where arbitrary = liftM3 triple arbitraryS arbitraryP arbitraryO --coarbitrary = undefined instance Arbitrary Node where arbitrary = oneof $ map return unodes --coarbitrary = undefined arbitraryTNum :: Gen Int arbitraryTNum = choose (0, maxN - 1) arbitraryTs :: Gen Triples arbitraryTs = do n <- sized (\_ -> choose (0, maxN)) xs <- sequence [arbitrary | _ <- [1..n]] return xs arbitraryT :: Gen Triple arbitraryT = elements test_triples arbitraryN :: Gen Int arbitraryN = choose (0, maxN - 1) arbitraryS, arbitraryP, arbitraryO :: Gen (Node) arbitraryS = oneof $ map return $ unodes ++ bnodes arbitraryP = oneof $ map return $ unodes arbitraryO = oneof $ map return $ unodes ++ bnodes ++ lnodes
amccausl/RDF4H
testsuite/tests/Data/RDF/GraphTestUtils.hs
bsd-3-clause
12,731
0
14
2,756
4,391
2,279
2,112
225
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module P2PPicks ( P2PPicks (..) , initializeP2PPicks , module R , module T ) where import Data.Configurator as C import Data.Configurator.Types import System.FilePath ((</>)) import P2PPicks.Request as R import P2PPicks.Types as T data P2PPicks = P2PPicks { guardian :: FilePath , profitMaxLicense :: FilePath , lossMinLicense :: FilePath , paramM :: String , paramB :: String } deriving (Eq, Show) initializeP2PPicks :: FilePath -> Config -> IO P2PPicks initializeP2PPicks snapletFilePath config = do guardian <- (snapletFilePath </>) <$> lookupDefault defaultGuardian config "p2ppicks.guardian" profitMaxLicense <- (snapletFilePath </>) <$> lookupDefault defaultProfitMaxLicense config "p2ppicks.profitMaxLicense" lossMinLicense <- (snapletFilePath </>) <$> lookupDefault defaultLossMinLicense config "p2ppicks.profitMaxLicense" paramM <- lookupDefault defaultParamM config "p2ppicks.paramM" paramB <- lookupDefault defaultParamB config "p2ppicks.paramB" return P2PPicks {..} where defaultGuardian = "guardian_linux" defaultProfitMaxLicense = "PT_Prosper_PMax_hex" defaultLossMinLicense = "PT_Prosper_LMin_hex" defaultParamM = "0" defaultParamB = "0"
WraithM/peertrader-backend
src/P2PPicks.hs
bsd-3-clause
1,435
0
9
353
273
156
117
32
1
{-# LANGUAGE OverloadedStrings #-} module Main where import System.Exit (ExitCode(..), exitWith) import Htrans.Logger (setAppLogger, logStartAppDebug, logStopAppDebug, logConfigDebug, logInOutInfo) import Htrans.Cli (cli) import Htrans.Types (Config(..)) import Htrans.YandexTranslator (getTranslate) import Htrans.XSelector (xselect) import Htrans.EndPoint (showResult) main :: IO () main = cli >>= xselect >>= doTrans >>= exitWith doTrans :: Config -> IO ExitCode doTrans cfg = do setAppLogger (logPath cfg) (logLevel cfg) logStartAppDebug logConfigDebug cfg res <- getTranslate (keyAPI cfg) (fromLang cfg) (toLang cfg) (textToTranslate cfg) logInOutInfo (textToTranslate cfg) res logStopAppDebug showResult cfg res
johhy/htrans
app/Main.hs
bsd-3-clause
769
0
10
134
239
127
112
21
1
module Main(main) where import Data.Word import Distribution.TestSuite import System.Environment import Test.HUnitPlus.Base import Test.HUnitPlus.Execution import Test.HUnitPlus.Filter import Test.HUnitPlus.Reporting import qualified Data.Map as Map import qualified Data.Set as Set simpleTest :: Test simpleTest = let runTest = return (Finished Pass) testInstance = TestInstance { name = "synthetic_test", tags = [], setOption = (\_ _ -> Right testInstance), options = [], run = runTest } in Test testInstance makeTestTree :: Word -> Word -> Word -> [Test] -> IO Test makeTestTree _ _ 0 tail = return $! testGroup "synthetic_group" tail makeTestTree maxwidth 0 width tail = makeTestTree maxwidth 0 (width - 1) $! (simpleTest : tail) makeTestTree maxwidth height width tail = do branch <- makeTestTree maxwidth (height - 1) maxwidth [] makeTestTree maxwidth height (width - 1) $! (branch : tail) makeFilters :: [Selector] -> Word -> [Filter] -> [Filter] makeFilters _ 0 tail = tail makeFilters selectors count tail = let makeFilters' :: [Selector] -> [Filter] -> [Filter] makeFilters' [] tail = tail makeFilters' (selector : rest) tail = makeFilters' rest (Filter { filterSuites = Set.singleton (show count), filterSelector = selector } : tail) in makeFilters' selectors tail makeSuites :: Word -> [String] -> [String] makeSuites 0 tail = tail makeSuites count tail = makeSuites (count - 1) (show count : tail) makeFakeSuites :: Word -> [TestSuite] -> [TestSuite] makeFakeSuites 0 tail = tail makeFakeSuites count tail = makeFakeSuites (count - 1) (TestSuite { suiteName = show count, suiteTests = [simpleTest], suiteConcurrently = False, suiteOptions = [] } : tail) makeAllSelectors :: Word -> [Selector] -> [Selector] makeAllSelectors 0 tail = tail makeAllSelectors count tail = makeAllSelectors (count - 1) (allSelector : tail) quietReporter = defaultReporter { reporterStart = return () } runPerf :: Bool -> [String] -> IO () runPerf _ ("baseline" : rest) = runPerf True rest runPerf dryrun ["run_tests", widthstr, heightstr] = let width :: Word width = read widthstr height :: Word height = read heightstr selectormap = Map.singleton "suite" allSelector in do tree <- makeTestTree width height width [] _ <- performTestSuites quietReporter selectormap [TestSuite { suiteName = "suite", suiteTests = [tree], suiteConcurrently = False, suiteOptions = [] }] return () runPerf dryrun ["filters", selectorsstr, suitesstr] = let numsuites :: Word numsuites = read suitesstr numselectors :: Word numselectors = read selectorsstr selectors = makeAllSelectors numselectors [] filters = makeFilters selectors numsuites [] suites = makeSuites numsuites [] fakesuite = makeFakeSuites numsuites [] in do selectormap <- return $! (suiteSelectors suites filters) _ <- performTestSuites quietReporter selectormap fakesuite return () main :: IO () main = do args <- getArgs runPerf False args
emc2/HUnit-Plus
test/Perf.hs
bsd-3-clause
3,386
0
16
933
1,037
552
485
85
2
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ScopedTypeVariables #-} #ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} #endif #ifndef MIN_VERSION_containers #define MIN_VERSION_containers(x,y,z) 1 #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.IndexedTraversal -- Copyright : (C) 2012 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : rank 2 types, MPTCs, TFs, flexible -- ---------------------------------------------------------------------------- module Control.Lens.IndexedTraversal ( -- * Indexed Traversals IndexedTraversal , IndexedTraversal' -- * Common Indexed Traversals , iwhereOf , value , ignored , TraverseMin(..) , TraverseMax(..) , traversed , traversed64 , elementOf , element , elementsOf , elements -- * Indexed Traversal Combinators , itraverseOf , iforOf , imapMOf , iforMOf , imapAccumROf , imapAccumLOf -- * Storing Indexed Traversals , ReifiedIndexedTraversal(..) , ReifiedIndexedTraversal' -- * Deprecated , SimpleIndexedTraversal , SimpleReifiedIndexedTraversal ) where import Control.Applicative import Control.Applicative.Backwards import Control.Lens.Combinators import Control.Lens.Indexed import Control.Lens.Internal import Control.Lens.Type import Control.Monad.Trans.State.Lazy as Lazy import Data.Int import Data.IntMap as IntMap import Data.Map as Map import Data.Traversable -- $setup -- >>> import Control.Lens ------------------------------------------------------------------------------ -- Indexed Traversals ------------------------------------------------------------------------------ -- | Every indexed traversal is a valid 'Control.Lens.Traversal.Traversal' or -- 'Control.Lens.IndexedFold.IndexedFold'. -- -- The 'Indexed' constraint is used to allow an 'IndexedTraversal' to be used -- directly as a 'Control.Lens.Traversal.Traversal'. -- -- The 'Control.Lens.Traversal.Traversal' laws are still required to hold. type IndexedTraversal i s t a b = forall f p. (Indexable i p, Applicative f) => p a (f b) -> s -> f t -- | @type 'IndexedTraversal'' i = 'Simple' ('IndexedTraversal' i)@ type IndexedTraversal' i s a = IndexedTraversal i s s a a -- | Traversal with an index. -- -- /NB:/ When you don't need access to the index then you can just apply your 'IndexedTraversal' -- directly as a function! -- -- @ -- 'itraverseOf' ≡ 'withIndex' -- 'Control.Lens.Traversal.traverseOf' l = 'itraverseOf' l '.' 'const' = 'id' -- @ -- -- @ -- 'itraverseOf' :: 'Control.Lens.IndexedLens.IndexedLens' i s t a b -> (i -> a -> f b) -> s -> f t -- 'itraverseOf' :: 'IndexedTraversal' i s t a b -> (i -> a -> f b) -> s -> f t -- @ itraverseOf :: (Indexed i a (f b) -> s -> f t) -> (i -> a -> f b) -> s -> f t itraverseOf = withIndex {-# INLINE itraverseOf #-} -- | -- Traverse with an index (and the arguments flipped) -- -- @ -- 'Control.Lens.Traversal.forOf' l a ≡ 'iforOf' l a '.' 'const' -- 'iforOf' ≡ 'flip' . 'itraverseOf' -- @ -- -- @ -- 'iforOf' :: 'Control.Lens.IndexedLens.IndexedLens' i s t a b -> s -> (i -> a -> f b) -> f t -- 'iforOf' :: 'IndexedTraversal' i s t a b -> s -> (i -> a -> f b) -> f t -- @ iforOf :: (Indexed i a (f b) -> s -> f t) -> s -> (i -> a -> f b) -> f t iforOf = flip . withIndex {-# INLINE iforOf #-} -- | Map each element of a structure targeted by a lens to a monadic action, -- evaluate these actions from left to right, and collect the results, with access -- its position. -- -- When you don't need access to the index 'mapMOf' is more liberal in what it can accept. -- -- @'Control.Lens.Traversal.mapMOf' l ≡ 'imapMOf' l '.' 'const'@ -- -- @ -- 'imapMOf' :: 'Monad' m => 'Control.Lens.IndexedLens.IndexedLens' i s t a b -> (i -> a -> m b) -> s -> m t -- 'imapMOf' :: 'Monad' m => 'IndexedTraversal' i s t a b -> (i -> a -> m b) -> s -> m t -- @ imapMOf :: (Indexed i a (WrappedMonad m b) -> s -> WrappedMonad m t) -> (i -> a -> m b) -> s -> m t imapMOf l f = unwrapMonad . withIndex l (\i -> WrapMonad . f i) {-# INLINE imapMOf #-} -- | Map each element of a structure targeted by a lens to a monadic action, -- evaluate these actions from left to right, and collect the results, with access -- its position (and the arguments flipped). -- -- @ -- 'Control.Lens.Traversal.forMOf' l a ≡ 'iforMOf' l a '.' 'const' -- 'iforMOf' ≡ 'flip' '.' 'imapMOf' -- @ -- -- @ -- 'iforMOf' :: 'Monad' m => 'Control.Lens.IndexedLens.IndexedLens' i s t a b -> s -> (i -> a -> m b) -> m t -- 'iforMOf' :: 'Monad' m => 'IndexedTraversal' i s t a b -> s -> (i -> a -> m b) -> m t -- @ iforMOf :: (Indexed i a (WrappedMonad m b) -> s -> WrappedMonad m t) -> s -> (i -> a -> m b) -> m t iforMOf = flip . imapMOf {-# INLINE iforMOf #-} -- | Generalizes 'Data.Traversable.mapAccumR' to an arbitrary 'IndexedTraversal' with access to the index. -- -- 'imapAccumROf' accumulates state from right to left. -- -- @'Control.Lens.Traversal.mapAccumROf' l ≡ 'imapAccumROf' l '.' 'const'@ -- -- @ -- 'imapAccumROf' :: 'Control.Lens.IndexedLens.IndexedLens' i s t a b -> (i -> s -> a -> (s, b)) -> s -> s -> (s, t) -- 'imapAccumROf' :: 'IndexedTraversal' i s t a b -> (i -> s -> a -> (s, b)) -> s -> s -> (s, t) -- @ imapAccumROf :: (Indexed i a (Lazy.State s b) -> s -> Lazy.State s t) -> (i -> s -> a -> (s, b)) -> s -> s -> (s, t) imapAccumROf l f s0 a = swap (Lazy.runState (withIndex l (\i c -> Lazy.state (\s -> swap (f i s c))) a) s0) {-# INLINE imapAccumROf #-} -- | Generalizes 'Data.Traversable.mapAccumL' to an arbitrary 'IndexedTraversal' with access to the index. -- -- 'imapAccumLOf' accumulates state from left to right. -- -- @'Control.Lens.Traversal.mapAccumLOf' l ≡ 'imapAccumLOf' l '.' 'const'@ -- -- @ -- 'imapAccumLOf' :: 'Control.Lens.IndexedLens.IndexedLens' i s t a b -> (i -> s -> a -> (s, b)) -> s -> s -> (s, t) -- 'imapAccumLOf' :: 'IndexedTraversal' i s t a b -> (i -> s -> a -> (s, b)) -> s -> s -> (s, t) -- @ imapAccumLOf :: (Indexed i a (Backwards (Lazy.State s) b) -> s -> Backwards (Lazy.State s) t) -> (i -> s -> a -> (s, b)) -> s -> s -> (s, t) imapAccumLOf l f s0 a = swap (Lazy.runState (forwards (withIndex l (\i c -> Backwards (Lazy.state (\s -> swap (f i s c)))) a)) s0) {-# INLINE imapAccumLOf #-} swap :: (a,b) -> (b,a) swap (a,b) = (b,a) {-# INLINE swap #-} ------------------------------------------------------------------------------ -- Common Indexed Traversals ------------------------------------------------------------------------------ -- | Access the element of an 'IndexedTraversal' where the index matches a predicate. -- -- >>> over (iwhereOf traversed (>0)) reverse ["He","was","stressed","o_O"] -- ["He","saw","desserts","O_o"] -- -- @ -- 'iwhereOf' :: 'Control.Lens.IndexedFold.IndexedFold' i s a -> (i -> 'Bool') -> 'Control.Lens.IndexedFold.IndexedFold' i s a -- 'iwhereOf' :: 'IndexedGetter' i s a -> (i -> 'Bool') -> 'Control.Lens.IndexedFold.IndexedFold' i s a -- 'iwhereOf' :: 'IndexedLens'' i s a -> (i -> 'Bool') -> 'IndexedTraversal'' i s a -- 'iwhereOf' :: 'IndexedTraversal'' i s a -> (i -> 'Bool') -> 'IndexedTraversal'' i s a -- 'iwhereOf' :: 'IndexedSetter'' i s a -> (i -> 'Bool') -> 'IndexedSetter'' i s a -- @ iwhereOf :: (Indexable i p, Applicative f) => IndexedLensLike (Indexed i) f s t a a -> (i -> Bool) -> IndexedLensLike p f s t a a iwhereOf l p f = withIndex l (\i a -> if p i then indexed f i a else pure a) {-# INLINE iwhereOf #-} -- | Traverse any 'Traversable' container. This is an 'IndexedTraversal' that is indexed by ordinal position. traversed :: Traversable f => IndexedTraversal Int (f a) (f b) a b traversed = indexing traverse {-# INLINE traversed #-} -- | Traverse any 'Traversable' container. This is an 'IndexedTraversal' that is indexed by ordinal position. traversed64 :: Traversable f => IndexedTraversal Int64 (f a) (f b) a b traversed64 = indexing64 traverse {-# INLINE traversed64 #-} -- | This provides a 'Control.Lens.Traversal.Traversal' that checks a predicate on a key before -- allowing you to traverse into a value. value :: (k -> Bool) -> IndexedTraversal' k (k, v) v value p f kv@(k,v) | p k = (,) k <$> indexed f k v | otherwise = pure kv {-# INLINE value #-} -- | This is the trivial empty traversal. -- -- @'ignored' :: 'IndexedTraversal' i s s a b@ -- -- @'ignored' ≡ 'const' 'pure'@ ignored :: Applicative f => kafb -> s -> f s ignored _ = pure {-# INLINE ignored #-} -- | Allows 'IndexedTraversal' the value at the smallest index. class Ord k => TraverseMin k m | m -> k where -- | 'IndexedTraversal' of the element with the smallest index. traverseMin :: IndexedTraversal' k (m v) v instance TraverseMin Int IntMap where traverseMin f m = case IntMap.minViewWithKey m of #if MIN_VERSION_containers(0,5,0) Just ((k,a), _) -> indexed f k a <&> \v -> IntMap.updateMin (const (Just v)) m #else Just ((k,a), _) -> indexed f k a <&> \v -> IntMap.updateMin (const v) m #endif Nothing -> pure m {-# INLINE traverseMin #-} instance Ord k => TraverseMin k (Map k) where traverseMin f m = case Map.minViewWithKey m of Just ((k, a), _) -> indexed f k a <&> \v -> Map.updateMin (const (Just v)) m Nothing -> pure m {-# INLINE traverseMin #-} -- | Allows 'IndexedTraversal' of the value at the largest index. class Ord k => TraverseMax k m | m -> k where -- | 'IndexedTraversal' of the element at the largest index. traverseMax :: IndexedTraversal' k (m v) v instance TraverseMax Int IntMap where traverseMax f m = case IntMap.maxViewWithKey m of #if MIN_VERSION_containers(0,5,0) Just ((k,a), _) -> indexed f k a <&> \v -> IntMap.updateMax (const (Just v)) m #else Just ((k,a), _) -> indexed f k a <&> \v -> IntMap.updateMax (const v) m #endif Nothing -> pure m {-# INLINE traverseMax #-} instance Ord k => TraverseMax k (Map k) where traverseMax f m = case Map.maxViewWithKey m of Just ((k, a), _) -> indexed f k a <&> \v -> Map.updateMax (const (Just v)) m Nothing -> pure m {-# INLINE traverseMax #-} -- | Traverse the /nth/ element 'elementOf' a 'Control.Lens.Traversal.Traversal', 'Lens' or -- 'Control.Lens.Iso.Iso' if it exists. -- -- >>> [[1],[3,4]] & elementOf (traverse.traverse) 1 .~ 5 -- [[1],[5,4]] -- -- >>> [[1],[3,4]] ^? elementOf (folded.folded) 1 -- Just 3 -- -- >>> [0..] ^?! elementOf folded 5 -- 5 -- -- >>> take 10 $ elementOf traverse 3 .~ 16 $ [0..] -- [0,1,2,16,4,5,6,7,8,9] -- -- @ -- 'elementOf' :: 'Control.Lens.Traversal.Traversal'' s a -> Int -> 'IndexedTraversal'' 'Int' s a -- 'elementOf' :: 'Control.Lens.Fold.Fold' s a -> Int -> 'Control.Lens.IndexedFold.IndexedFold' 'Int' s a -- @ elementOf :: (Applicative f, Indexable Int p) => LensLike (Indexing f) s t a a -> Int -> IndexedLensLike p f s t a a elementOf l p = elementsOf l (p ==) {-# INLINE elementOf #-} -- | Traverse the /nth/ element of a 'Traversable' container. -- -- @'element' ≡ 'elementOf' 'traverse'@ element :: Traversable t => Int -> IndexedTraversal' Int (t a) a element = elementOf traverse {-# INLINE element #-} -- | Traverse (or fold) selected elements of a 'Control.Lens.Traversal.Traversal' (or 'Control.Lens.Fold.Fold') where their ordinal positions match a predicate. -- -- @ -- 'elementsOf' :: 'Control.Lens.Traversal.Traversal'' s a -> ('Int' -> 'Bool') -> 'IndexedTraversal'' 'Int' s a -- 'elementsOf' :: 'Control.Lens.Fold.Fold' s a -> ('Int' -> 'Bool') -> 'Control.Lens.IndexedFold.IndexedFold' 'Int' s a -- @ elementsOf :: (Applicative f, Indexable Int p) => LensLike (Indexing f) s t a a -> (Int -> Bool) -> IndexedLensLike p f s t a a elementsOf l p iafb s = case runIndexing (l (\a -> Indexing (\i -> i `seq` (if p i then indexed iafb i a else pure a, i + 1))) s) 0 of (r, _) -> r {-# INLINE elementsOf #-} -- | Traverse elements of a 'Traversable' container where their ordinal positions matches a predicate. -- -- @'elements' ≡ 'elementsOf' 'traverse'@ elements :: Traversable t => (Int -> Bool) -> IndexedTraversal' Int (t a) a elements = elementsOf traverse {-# INLINE elements #-} ------------------------------------------------------------------------------ -- Reifying Indexed Traversals ------------------------------------------------------------------------------ -- | Useful for storage. newtype ReifiedIndexedTraversal i s t a b = ReifyIndexedTraversal { reflectIndexedTraversal :: IndexedTraversal i s t a b } -- | @type 'ReifiedIndexedTraversal'' i = 'Simple' ('ReifiedIndexedTraversal' i)@ type ReifiedIndexedTraversal' i s a = ReifiedIndexedTraversal i s s a a ------------------------------------------------------------------------------ -- Deprecated ------------------------------------------------------------------------------ -- | @type 'SimpleReifiedIndexedTraversal' i = 'Simple' ('ReifiedIndexedTraversal' i)@ type SimpleReifiedIndexedTraversal i s a = ReifiedIndexedTraversal i s s a a {-# DEPRECATED SimpleReifiedIndexedTraversal "use ReifiedIndexedTraversal'" #-} -- | @type 'SimpleIndexedTraversal' i = 'Simple' ('IndexedTraversal' i)@ type SimpleIndexedTraversal i s a = IndexedTraversal i s s a a {-# DEPRECATED SimpleIndexedTraversal "use IndexedTraversal'" #-}
np/lens
src/Control/Lens/IndexedTraversal.hs
bsd-3-clause
13,617
0
21
2,566
2,354
1,339
1,015
135
2
{-# LANGUAGE BangPatterns #-} module Data.Digest.Groestl( groestl224, printWAsHex, printAsHex ) where import Data.Word (Word64, Word8) import Data.Int (Int64) import Data.Bits (xor, shiftR, setBit) import Data.List (foldl') import qualified Data.Binary as B import qualified Data.Binary.Get as G import qualified Data.ByteString.Lazy as L import qualified Data.Vector.Unboxed as V import Text.Printf import Prelude hiding (truncate) --import Control.Parallel (par, pseq) import Data.Digest.GroestlTables printWAsHex :: Word64 -> String printWAsHex = printf "0x%016x" printAsHex :: L.ByteString -> String printAsHex = concat . ("0x" :) . map (printf "%02x") . L.unpack -------------------------------------------------------------------------------- data DigestLength = G224 | G256 | G384 | G512 ----------------------------------------------------------------------------------- groestl224 :: Int64 -> L.ByteString -> L.ByteString groestl224 dataBitLen | dataBitLen < 0 = error "The data length can not be less than 0" | otherwise = truncate G224 . outputTransformation . foldl' f512 h0_224 . parseMessage dataBitLen 512 outputTransformation :: V.Vector Word64 -> V.Vector Word64 outputTransformation x = V.zipWith xor (permP x) x f512 :: V.Vector Word64 -> V.Vector Word64 -> V.Vector Word64 f512 !h !m = V.zipWith3 xor3 h (permP inP) (permQ m) where xor3 x1 x2 x3 = x1 `xor` x2 `xor` x3 inP = V.zipWith xor h m {- f512 h m = V.force outP `par` (V.force outQ `pseq` (V.zipWith3 xor3 h outP outQ)) where xor3 x1 x2 x3 = x1 `xor` x2 `xor` x3 inP = V.zipWith xor h m outP = permP inP outQ = permQ m -} column :: V.Vector Word64 -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Word64 column v c0 c1 c2 c3 c4 c5 c6 c7 = V.unsafeIndex tables (index 0 c0) `xor` V.unsafeIndex tables (index 1 c1) `xor` V.unsafeIndex tables (index 2 c2) `xor` V.unsafeIndex tables (index 3 c3) `xor` V.unsafeIndex tables (index 4 c4) `xor` V.unsafeIndex tables (index 5 c5) `xor` V.unsafeIndex tables (index 6 c6) `xor` V.unsafeIndex tables (index 7 c7) where index i c = i * 256 + fromIntegral (extractByte i (v V.! c)) extractByte :: Int -> Word64 -> Word8 extractByte n w = fromIntegral $ shiftR w (8 * (7 - n)) permQ :: V.Vector Word64 -> V.Vector Word64 permQ x = V.foldl' rnd512Q x (V.enumFromN 0 10) rnd512Q :: V.Vector Word64 -> Word64 -> V.Vector Word64 rnd512Q !x !rndNr = let !x0 = V.unsafeIndex x 0 `xor` 0xffffffffffffffff `xor` rndNr !x1 = V.unsafeIndex x 1 `xor` 0xffffffffffffffef `xor` rndNr !x2 = V.unsafeIndex x 2 `xor` 0xffffffffffffffdf `xor` rndNr !x3 = V.unsafeIndex x 3 `xor` 0xffffffffffffffcf `xor` rndNr !x4 = V.unsafeIndex x 4 `xor` 0xffffffffffffffbf `xor` rndNr !x5 = V.unsafeIndex x 5 `xor` 0xffffffffffffffaf `xor` rndNr !x6 = V.unsafeIndex x 6 `xor` 0xffffffffffffff9f `xor` rndNr !x7 = V.unsafeIndex x 7 `xor` 0xffffffffffffff8f `xor` rndNr !y = V.fromList [x0, x1, x2, x3, x4, x5, x6, x7] !w0 = column y 1 3 5 7 0 2 4 6 !w1 = column y 2 4 6 0 1 3 5 7 !w2 = column y 3 5 7 1 2 4 6 0 !w3 = column y 4 6 0 2 3 5 7 1 !w4 = column y 5 7 1 3 4 6 0 2 !w5 = column y 6 0 2 4 5 7 1 3 !w6 = column y 7 1 3 5 6 0 2 4 !w7 = column y 0 2 4 6 7 1 3 5 in V.fromList [w0, w1, w2, w3, w4, w5, w6, w7] permP :: V.Vector Word64 -> V.Vector Word64 permP x = V.foldl' rnd512P x (V.enumFromStepN 0 0x0100000000000000 10) rnd512P :: V.Vector Word64 -> Word64 -> V.Vector Word64 rnd512P !x rndNr = let !x0 = V.unsafeIndex x 0 `xor` 0x0000000000000000 `xor` rndNr !x1 = V.unsafeIndex x 1 `xor` 0x1000000000000000 `xor` rndNr !x2 = V.unsafeIndex x 2 `xor` 0x2000000000000000 `xor` rndNr !x3 = V.unsafeIndex x 3 `xor` 0x3000000000000000 `xor` rndNr !x4 = V.unsafeIndex x 4 `xor` 0x4000000000000000 `xor` rndNr !x5 = V.unsafeIndex x 5 `xor` 0x5000000000000000 `xor` rndNr !x6 = V.unsafeIndex x 6 `xor` 0x6000000000000000 `xor` rndNr !x7 = V.unsafeIndex x 7 `xor` 0x7000000000000000 `xor` rndNr !y = V.fromList [x0, x1, x2, x3, x4, x5, x6, x7] !w0 = column y 0 1 2 3 4 5 6 7 !w1 = column y 1 2 3 4 5 6 7 0 !w2 = column y 2 3 4 5 6 7 0 1 !w3 = column y 3 4 5 6 7 0 1 2 !w4 = column y 4 5 6 7 0 1 2 3 !w5 = column y 5 6 7 0 1 2 3 4 !w6 = column y 6 7 0 1 2 3 4 5 !w7 = column y 7 0 1 2 3 4 5 6 in V.fromList [w0, w1, w2, w3, w4, w5, w6, w7] ---------------------------- Parsing ------------------------------ parseMessage :: Int64 -> Int64 -> L.ByteString -> [V.Vector Word64] parseMessage dataLen blockLen xs | L.null suf = pad dataLen blockLen pre | otherwise = parseBlock pre : parseMessage dataLen blockLen suf where (!pre,suf) = L.splitAt 64 xs parseBlock :: L.ByteString -> V.Vector Word64 parseBlock = V.unfoldr (\bs -> if L.null bs then Nothing else Just (G.runGet G.getWord64be bs, L.drop 8 bs)) pad :: Int64 -> Int64 -> L.ByteString -> [V.Vector Word64] pad dataLen blockLen xs | dataLen == 0 || L.null xs = [V.fromList [0x8000000000000000, 0,0,0,0,0,0, lengthPad + 1]] | partialBlockLen == 0 = [parseBlock xs, V.fromList [0x8000000000000000, 0,0,0,0,0,0, lengthPad + 1]] | L.length onePadded <= (blockByteLen - 8) = [V.unsafeUpdate (parseBlock fullBlock) (V.singleton (7, lengthPad + 1))] | otherwise = [parseBlock fullBlock, V.fromList [0,0,0,0,0,0,0, lengthPad + 2]] where onePadded = appendOne xs partialBlockLen fullBlock = L.append onePadded (L.take (blockByteLen - L.length onePadded) zeroes) zeroes = L.repeat 0x00 blockByteLen = blockLen `div` 8 partialBlockLen = dataLen `rem` blockLen lengthPad = fromIntegral $ dataLen `div` blockLen appendOne :: L.ByteString -> Int64 -> L.ByteString appendOne xs len | len == 0 || L.null xs = L.singleton 0x80 | byteOffset == 0 = L.snoc xs 0x80 | otherwise = L.snoc (L.init xs) (setBit (L.last xs) (7 - byteOffset)) where byteOffset = fromIntegral $ len `mod` 8 truncate :: DigestLength -> V.Vector Word64 -> L.ByteString truncate G224 = L.drop 4 . L.concat . map B.encode . V.toList . V.unsafeSlice 4 4 truncate G256 = L.concat . map B.encode . V.toList . V.unsafeSlice 4 4 truncate G384 = L.concat . map B.encode . V.toList . V.unsafeSlice 2 6 truncate G512 = L.concat . map B.encode . V.toList ---------------------------------------------------------------------------------- h0_224 :: V.Vector Word64 h0_224 = V.fromList [0, 0, 0, 0, 0, 0, 0, 0xe0]
hakoja/SHA3
Data/Digest/Groestl.hs
bsd-3-clause
6,811
0
14
1,685
2,744
1,418
1,326
123
2
{-# LANGUAGE RankNTypes, TypeSynonymInstances, FlexibleInstances, ConstraintKinds, OverlappingInstances, OverloadedStrings, RecordWildCards, ExistentialQuantification #-} module TestHttpChannelA where import Control.Concurrent import HttpChannel import AbstractedCommunication myMain :: IO () myMain = do lilNeg <- defaultChan :: IO HttpChannel -- r <- toRequest lilNeg -- lilNeg' <- fromRequest r lilNeg --this puts their port to our serving port -- case lilNeg' of -- Left err -> do -- putStrLn $ "Error in creating fromReq of neg chan: " ++ err -- Right (HttpChannel {..}) -> do comneg <- mkChannel lilNeg --(HttpChannel { httpchanTheirIp = (Just "10.100.0.6"), ..}) dumchan <- defaultChan :: IO HttpChannel emptyChan <- mkChannel' dumchan forkIO $ declareCommunication (comneg, [emptyChan]) (\x -> putStrLn "succ") lilNeg2 <- defaultChan :: IO HttpChannel r2 <- toRequest lilNeg lilNeg2' <- fromRequest r2 lilNeg2 --this puts their port to our serving port case lilNeg2' of Left err -> do putStrLn $ "Error in creating fromReq of neg chan: " ++ err Right (HttpChannel {..}) -> do comneg2 <- mkChannel (HttpChannel { httpchanTheirIp = (Just "10.100.0.6"),httpchanMyServingPort=55999, ..}) (HttpChannel {..}) <- defaultChan :: IO HttpChannel let channelToBe = HttpChannel { httpchanMyServingPort= 55558, httpchanTheirIp=(Just "10.100.0.6"), httpchanTheirServingPort=Nothing,..} bigChantobe <- mkChannel channelToBe echan <- aChannelInit comneg2 bigChantobe case echan of Left err -> do putStrLn err Right chan -> do putStrLn "success on A side!!!!!!!!"
armoredsoftware/protocol
tpm/mainline/shared/protocolprotocol/TestHttpChannelA.hs
bsd-3-clause
1,828
5
11
484
331
177
154
31
3
{-# LANGUAGE TupleSections #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Language.Fixpoint.Types.Visitor ( -- * Visitor Visitor (..) -- * Extracting Symbolic Constants (String Literals) , SymConsts (..) -- * Default Visitor , defaultVisitor -- * Transformers , trans -- * Accumulators , fold -- * Clients , kvars , envKVars , rhsKVars , mapKVars, mapKVars', mapKVarSubsts -- * Predicates on Constraints , isConcC , isKvarC -- * Sorts , foldSort, mapSort ) where import Control.Monad.Trans.State (State, modify, runState) import qualified Data.HashSet as S import qualified Data.HashMap.Strict as M import qualified Data.List as L import Language.Fixpoint.Misc (sortNub) import Language.Fixpoint.Types data Visitor acc ctx = Visitor { -- | Context @ctx@ is built in a "top-down" fashion; not "across" siblings ctxExpr :: ctx -> Expr -> ctx , ctxPred :: ctx -> Pred -> ctx -- | Transforms can access current @ctx@ , txExpr :: ctx -> Expr -> Expr , txPred :: ctx -> Pred -> Pred -- | Accumulations can access current @ctx@; @acc@ value is monoidal , accExpr :: ctx -> Expr -> acc , accPred :: ctx -> Pred -> acc } --------------------------------------------------------------------------------- defaultVisitor :: Monoid acc => Visitor acc ctx --------------------------------------------------------------------------------- defaultVisitor = Visitor { ctxExpr = const -- \c _ -> c , ctxPred = const -- \c _ -> c , txExpr = \_ x -> x , txPred = \_ x -> x , accExpr = \_ _ -> mempty , accPred = \_ _ -> mempty } ------------------------------------------------------------------------ fold :: (Visitable t, Monoid a) => Visitor a ctx -> ctx -> a -> t -> a fold v c a t = snd $ execVisitM v c a visit t trans :: (Visitable t, Monoid a) => Visitor a ctx -> ctx -> a -> t -> t trans v c _ z = fst $ execVisitM v c mempty visit z execVisitM :: Visitor a ctx -> ctx -> a -> (Visitor a ctx -> ctx -> t -> State a t) -> t -> (t, a) execVisitM v c a f x = runState (f v c x) a type VisitM acc = State acc accum :: (Monoid a) => a -> VisitM a () accum = modify . mappend (<$$>) :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) f <$$> x = traverse f x ------------------------------------------------------------------------------ class Visitable t where visit :: (Monoid a) => Visitor a c -> c -> t -> VisitM a t instance Visitable Expr where visit = visitExpr instance Visitable Pred where visit = visitPred instance Visitable Reft where visit v c (Reft (x, ra)) = (Reft . (x, )) <$> visit v c ra instance Visitable SortedReft where visit v c (RR t r) = RR t <$> visit v c r instance Visitable (Symbol, SortedReft) where visit v c (sym, sr) = (sym, ) <$> visit v c sr instance Visitable BindEnv where visit v c = mapM (visit v c) --------------------------------------------------------------------------------- -- Warning: these instances were written for mapKVars over SInfos only; -- check that they behave as expected before using with other clients. instance Visitable (SimpC a) where visit v c x = do rhs' <- visit v c (_crhs x) return x { _crhs = rhs' } instance Visitable (SInfo a) where visit v c x = do cm' <- mapM (visit v c) (cm x) bs' <- visit v c (bs x) return x { cm = cm', bs = bs' } --------------------------------------------------------------------------------- visitMany :: (Monoid a, Visitable t) => Visitor a ctx -> ctx -> [t] -> VisitM a [t] visitMany v c xs = visit v c <$$> xs visitExpr :: (Monoid a) => Visitor a ctx -> ctx -> Expr -> VisitM a Expr visitExpr v = vE where vP = visitPred v vE c e = accum acc >> step c' e' where c' = ctxExpr v c e e' = txExpr v c' e acc = accExpr v c' e step _ e@EBot = return e step _ e@(ESym _) = return e step _ e@(ECon _) = return e step _ e@(EVar _) = return e step c (EApp f es) = EApp f <$> (vE c <$$> es) step c (ENeg e) = ENeg <$> vE c e step c (EBin o e1 e2) = EBin o <$> vE c e1 <*> vE c e2 step c (EIte p e1 e2) = EIte <$> vP c p <*> vE c e1 <*> vE c e2 step c (ECst e t) = (`ECst` t) <$> vE c e visitPred :: (Monoid a) => Visitor a ctx -> ctx -> Pred -> VisitM a Pred visitPred v = vP where -- vS1 c (x, e) = (x,) <$> vE c e -- vS c (Su xes) = Su <$> vS1 c <$$> xes vE = visitExpr v vP c p = accum acc >> step c' p' where c' = ctxPred v c p p' = txPred v c' p acc = accPred v c' p step c (PAnd ps) = PAnd <$> (vP c <$$> ps) step c (POr ps) = POr <$> (vP c <$$> ps) step c (PNot p) = PNot <$> vP c p step c (PImp p1 p2) = PImp <$> vP c p1 <*> vP c p2 step c (PIff p1 p2) = PIff <$> vP c p1 <*> vP c p2 step c (PBexp e) = PBexp <$> vE c e step c (PAtom r e1 e2) = PAtom r <$> vE c e1 <*> vE c e2 step c (PAll xts p) = PAll xts <$> vP c p step c (PExist xts p) = PExist xts <$> vP c p step _ p@(PKVar _ _) = return p -- PAtom r <$> vE c e1 <*> vE c e2 step _ p@PTrue = return p step _ p@PFalse = return p step _ p@PTop = return p mapKVars :: Visitable t => (KVar -> Maybe Pred) -> t -> t mapKVars f = mapKVars' f' where f' (kv', _) = f kv' mapKVars' :: Visitable t => ((KVar, Subst) -> Maybe Pred) -> t -> t mapKVars' f = trans kvVis () [] where kvVis = defaultVisitor { txPred = txK } txK _ (PKVar k su) | Just p' <- f (k, su) = subst su p' txK _ p = p mapKVarSubsts :: Visitable t => (KVar -> Subst -> Subst) -> t -> t mapKVarSubsts f = trans kvVis () [] where kvVis = defaultVisitor { txPred = txK } txK _ (PKVar k su) = PKVar k $ f k su txK _ p = p kvars :: Visitable t => t -> [KVar] kvars = fold kvVis () [] where kvVis = defaultVisitor { accPred = kv' } kv' _ (PKVar k _) = [k] kv' _ _ = [] envKVars :: (TaggedC c a) => BindEnv -> c a -> [KVar] envKVars be c = squish [ kvs sr | (_, sr) <- clhs be c] where squish = S.toList . S.fromList . concat kvs = kvars . sr_reft -- lhsKVars :: BindEnv -> SubC a -> [KVar] -- lhsKVars binds c = envKVs ++ lhsKVs -- where -- envKVs = envKVars binds c -- lhsKVs = kvars $ lhsCs c rhsKVars :: (TaggedC c a) => c a -> [KVar] rhsKVars = kvars . crhs -- rhsCs isKvarC :: (TaggedC c a) => c a -> Bool isKvarC = all isKvar . conjuncts . crhs isConcC :: (TaggedC c a) => c a -> Bool isConcC = all isConc . conjuncts . crhs isKvar :: Pred -> Bool isKvar (PKVar {}) = True isKvar _ = False isConc :: Pred -> Bool isConc = null . kvars --------------------------------------------------------------------------------- -- | Visitors over @Sort@ --------------------------------------------------------------------------------- foldSort :: (a -> Sort -> a) -> a -> Sort -> a foldSort f = step where step b t = go (f b t) t go b (FFunc _ ts) = L.foldl' step b ts go b (FApp t1 t2) = L.foldl' step b [t1, t2] go b _ = b mapSort :: (Sort -> Sort) -> Sort -> Sort mapSort f = step where step = go . f go (FFunc n ts) = FFunc n $ step <$> ts go (FApp t1 t2) = FApp (step t1) (step t2) go t = t --------------------------------------------------------------- -- | String Constants ----------------------------------------- --------------------------------------------------------------- -- symConstLits :: FInfo a -> [(Symbol, Sort)] -- symConstLits fi = [(symbol c, strSort) | c <- symConsts fi] class SymConsts a where symConsts :: a -> [SymConst] instance SymConsts (FInfo a) where symConsts fi = sortNub $ csLits ++ bsLits ++ qsLits where csLits = concatMap symConsts $ M.elems $ cm fi bsLits = symConsts $ bs fi qsLits = concatMap symConsts $ q_body <$> quals fi instance SymConsts BindEnv where symConsts = concatMap (symConsts . snd) . M.elems . beBinds instance SymConsts (SubC a) where symConsts c = symConsts (slhs c) ++ symConsts (srhs c) instance SymConsts SortedReft where symConsts = symConsts . sr_reft instance SymConsts Reft where symConsts (Reft (_, ra)) = getSymConsts ra instance SymConsts Pred where symConsts = getSymConsts getSymConsts :: Visitable t => t -> [SymConst] getSymConsts = fold scVis () [] where scVis = defaultVisitor { accExpr = sc } sc _ (ESym c) = [c] sc _ _ = [] {- instance SymConsts (SimpC a) where symConsts c = symConsts (crhs c) -}
gridaphobe/liquid-fixpoint
src/Language/Fixpoint/Types/Visitor.hs
bsd-3-clause
9,116
0
13
2,757
3,205
1,668
1,537
176
13
module Alonzo where import Control.Monad (forever) import Control.Monad.State (StateT, evalStateT, lift) import Network.IRC import Logging import IRC type Trait a = Message -> Alonzo a () type Alonzo a = StateT a IRC alonzo :: UserName -> a -> [Trait a] -> Config -> IO () alonzo name brain traits c = run c $ (`evalStateT` brain) $ do sendMessage (nick name) lift . send $ "USER " ++ name ++ " 0 * :Alonzo - Your friendly IRC bot!" forever $ do m <- receiveMessage sequence_ $ map ($ m) traits sendMessage :: Message -> Alonzo a () sendMessage = lift . send . encode receiveMessage :: Alonzo a Message receiveMessage = do s <- lift receive case decode s of Nothing -> logError ("Parsing of " ++ show s ++ " failed!") >> receiveMessage Just Message {msg_command = "PING", msg_params = servers} -> sendMessage (pong servers) >> receiveMessage Just m -> return m pong :: [ServerName] -> Message pong = Message Nothing "PONG"
beni55/alonzo
src/Alonzo.hs
mit
1,011
0
15
253
358
185
173
26
3
module AST where import Text.Parsec type Program = [ExternalDeclaration] --type Identifier = String type Identifier = String data ExternalDeclaration = Decl SourcePos DeclaratorList | FuncProt SourcePos Type Identifier [(Type, Identifier)] | FuncDef SourcePos Type Identifier [(Type,Identifier)] Stmt deriving (Show) type DeclaratorList = [(Type, DirectDeclarator)] data DirectDeclarator = Variable SourcePos Identifier | Sequence SourcePos Identifier Integer instance Show DirectDeclarator where show (Variable _ ident) = ident show (Sequence _ ident int) = concat [ident, "[", show int, "]"] {-=============== - Type ================-} data Type = CInt | CVoid | CPointer Type deriving(Eq) instance Show Type where show (CPointer CInt) = "int *" show (CInt) = "int " show (CVoid) = "void " show _ = error "invalid type" data Stmt = EmptyStmt SourcePos | ExprStmt SourcePos Expr | CompoundStmt SourcePos DeclaratorList [Stmt] | IfStmt SourcePos Expr Stmt Stmt | WhileStmt SourcePos Expr Stmt | ReturnStmt SourcePos Expr deriving (Show) --data CompoundStatement = CompoundStatement SourcePos DeclarationList [Stmt] -- deriving (Show) --data DeclarationList = DeclarationList SourcePos [DeclaratorList] -- deriving (Show) data Expr = AssignExpr SourcePos Expr Expr | Or SourcePos Expr Expr | And SourcePos Expr Expr | Equal SourcePos Expr Expr | NotEqual SourcePos Expr Expr | Lt SourcePos Expr Expr | Gt SourcePos Expr Expr | Lte SourcePos Expr Expr | Gte SourcePos Expr Expr | Plus SourcePos Expr Expr | Minus SourcePos Expr Expr | Multiple SourcePos Expr Expr | Divide SourcePos Expr Expr | UnaryAddress SourcePos Expr | UnaryPointer SourcePos Expr | CallFunc SourcePos Identifier [Expr] | ExprList SourcePos [Expr] | Constant SourcePos Integer | IdentExpr SourcePos Identifier deriving (Show)
tanishiking/HasC
src/AST.hs
mit
2,514
0
8
979
502
285
217
50
0
module Main where import Control.Exception (throw) import qualified System.IO.UTF8 as IO import Test.HUnit import Text.Parakeet defaultOptions :: Options defaultOptions = Options { inputFileJ = ([], []) , inputFileR = ([], []) , templateFile = Just ([], "$title$\n$author$\n$body$") , furigana = InHiragana , noMeta = False , keepLV = False } getOptions :: String -> Bool -> IO Options getOptions test keepLV = do let jf = "test-suite/" ++ test ++ "/" ++ test ++ ".j" let rf = "test-suite/" ++ test ++ "/" ++ test ++ ".r" j <- IO.readFile jf r <- IO.readFile rf return defaultOptions { inputFileJ = (jf, j) , inputFileR = (rf, r) , keepLV = keepLV } getTest :: String -> Bool -> IO Test getTest testName keepLV = do opts <- getOptions testName keepLV let result = parakeet opts TeXFormat output <- case result of Left err -> throw err Right r -> return (lines r) expect <- lines <$> IO.readFile ("test-expect/" ++ testName ++ ".tex.expect") return $ TestLabel testName $ TestCase $ do let nlines = length expect let singleLineTest (l, e, o) = assertEqual ("On line " ++ show (l + 1)) e o assertEqual "The number of lines" nlines (length output) mapM_ singleLineTest $ zip3 [0 .. nlines - 1] expect output main :: IO Counts main = do test1 <- getTest "Anonymous" False test2 <- getTest "Butter-fly" False test3 <- getTest "Nagori-yuki" True runTestTT $ TestList [test1, test2, test3]
foreverbell/obtuse-parakeet
test/Main.hs
mit
1,596
0
18
452
556
284
272
41
2
{- | Module : $Header$ Description : HolLight signature Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : jonathan.von_schroeder@dfki.de Stability : experimental Portability : portable -} module HolLight.Sign where import qualified Data.Map as Map import Common.DocUtils import Common.Doc import Common.Result import HolLight.Term import HolLight.Helper data Sign = Sign { types :: Map.Map String Int , ops :: Map.Map String HolType } deriving (Eq, Ord, Show) prettyTypes :: Map.Map String Int -> Doc prettyTypes = ppMap text (\ i -> if i < 1 then empty else parens (pretty i)) (const id) sepByCommas (<>) instance Pretty Sign where pretty s = keyword "types" <+> prettyTypes (types s) $++$ ppMap text ppPrintType (const id) vcat (\ a -> (a <+> colon <+>)) (ops s) emptySig :: Sign emptySig = Sign {types = Map.empty, ops = Map.empty } isSubSig :: Sign -> Sign -> Bool isSubSig s1 s2 = types s1 `Map.isSubmapOf` types s2 && ops s1 `Map.isSubmapOf` ops s2 sigUnion :: Sign -> Sign -> Result Sign sigUnion (Sign {types = t1, ops = o1}) (Sign {types = t2, ops = o2}) = return Sign {types = t1 `Map.union` t2, ops = o1 `Map.union` o2}
nevrenato/HetsAlloy
HolLight/Sign.hs
gpl-2.0
1,272
0
11
282
414
229
185
26
2
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[TcMonoType]{Typechecking user-specified @MonoTypes@} -} {-# LANGUAGE CPP #-} module TcHsType ( tcHsSigType, tcHsDeriv, tcHsVectInst, tcHsInstHead, UserTypeCtxt(..), -- Type checking type and class decls kcLookupKind, kcTyClTyVars, tcTyClTyVars, tcHsConArgType, tcDataKindSig, tcClassSigType, -- Kind-checking types -- No kind generalisation, no checkValidType kcHsTyVarBndrs, tcHsTyVarBndrs, tcHsLiftedType, tcHsOpenType, tcLHsType, tcCheckLHsType, tcCheckLHsTypeAndGen, tcHsContext, tcInferApps, tcHsArgTys, kindGeneralize, checkKind, -- Sort-checking kinds tcLHsKind, -- Pattern type signatures tcHsPatSigType, tcPatSig ) where #include "HsVersions.h" import HsSyn import TcRnMonad import TcEvidence( HsWrapper ) import TcEnv import TcMType import TcValidity import TcUnify import TcIface import TcType import Type import TypeRep( Type(..) ) -- For the mkNakedXXX stuff import Kind import RdrName( lookupLocalRdrOcc ) import Var import VarSet import TyCon import ConLike import DataCon import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName ) import Class import Name import NameEnv import TysWiredIn import BasicTypes import SrcLoc import DynFlags ( ExtensionFlag( Opt_DataKinds ), getDynFlags ) import Unique import UniqSupply import Outputable import FastString import Util import Data.Maybe( isNothing ) import Control.Monad ( unless, when, zipWithM ) import PrelNames( ipClassName, funTyConKey, allNameStrings ) {- ---------------------------- General notes ---------------------------- Generally speaking we now type-check types in three phases 1. kcHsType: kind check the HsType *includes* performing any TH type splices; so it returns a translated, and kind-annotated, type 2. dsHsType: convert from HsType to Type: perform zonking expand type synonyms [mkGenTyApps] hoist the foralls [tcHsType] 3. checkValidType: check the validity of the resulting type Often these steps are done one after the other (tcHsSigType). But in mutually recursive groups of type and class decls we do 1 kind-check the whole group 2 build TyCons/Classes in a knot-tied way 3 check the validity of types in the now-unknotted TyCons/Classes For example, when we find (forall a m. m a -> m a) we bind a,m to kind varibles and kind-check (m a -> m a). This makes a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in an environment that binds a and m suitably. The kind checker passed to tcHsTyVars needs to look at enough to establish the kind of the tyvar: * For a group of type and class decls, it's just the group, not the rest of the program * For a tyvar bound in a pattern type signature, its the types mentioned in the other type signatures in that bunch of patterns * For a tyvar bound in a RULE, it's the type signatures on other universally quantified variables in the rule Note that this may occasionally give surprising results. For example: data T a b = MkT (a b) Here we deduce a::*->*, b::* But equally valid would be a::(*->*)-> *, b::*->* Validity checking ~~~~~~~~~~~~~~~~~ Some of the validity check could in principle be done by the kind checker, but not all: - During desugaring, we normalise by expanding type synonyms. Only after this step can we check things like type-synonym saturation e.g. type T k = k Int type S a = a Then (T S) is ok, because T is saturated; (T S) expands to (S Int); and then S is saturated. This is a GHC extension. - Similarly, also a GHC extension, we look through synonyms before complaining about the form of a class or instance declaration - Ambiguity checks involve functional dependencies, and it's easier to wait until knots have been resolved before poking into them Also, in a mutually recursive group of types, we can't look at the TyCon until we've finished building the loop. So to keep things simple, we postpone most validity checking until step (3). Knot tying ~~~~~~~~~~ During step (1) we might fault in a TyCon defined in another module, and it might (via a loop) refer back to a TyCon defined in this module. So when we tie a big knot around type declarations with ARecThing, so that the fault-in code can get the TyCon being defined. ************************************************************************ * * Check types AND do validity checking * * ************************************************************************ -} tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type -- NB: it's important that the foralls that come from the top-level -- HsForAllTy in hs_ty occur *first* in the returned type. -- See Note [Scoped] with TcSigInfo tcHsSigType ctxt (L loc hs_ty) = setSrcSpan loc $ addErrCtxt (pprSigCtxt ctxt empty (ppr hs_ty)) $ do { kind <- case expectedKindInCtxt ctxt of Nothing -> newMetaKindVar Just k -> return k -- The kind is checked by checkValidType, and isn't necessarily -- of kind * in a Template Haskell quote eg [t| Maybe |] -- Generalise here: see Note [Kind generalisation] ; ty <- tcCheckHsTypeAndGen hs_ty kind -- Zonk to expose kind information to checkValidType ; ty <- zonkSigType ty ; checkValidType ctxt ty ; return ty } ----------------- tcHsInstHead :: UserTypeCtxt -> LHsType Name -> TcM ([TyVar], ThetaType, Class, [Type]) -- Like tcHsSigType, but for an instance head. tcHsInstHead user_ctxt lhs_ty@(L loc hs_ty) = setSrcSpan loc $ -- The "In the type..." context comes from the caller do { inst_ty <- tc_inst_head hs_ty ; kvs <- zonkTcTypeAndFV inst_ty ; kvs <- kindGeneralize kvs ; inst_ty <- zonkSigType (mkForAllTys kvs inst_ty) ; checkValidInstance user_ctxt lhs_ty inst_ty } tc_inst_head :: HsType Name -> TcM TcType tc_inst_head (HsForAllTy _ _ hs_tvs hs_ctxt hs_ty) = tcHsTyVarBndrs hs_tvs $ \ tvs -> do { ctxt <- tcHsContext hs_ctxt ; ty <- tc_lhs_type hs_ty ekConstraint -- Body for forall has kind Constraint ; return (mkSigmaTy tvs ctxt ty) } tc_inst_head hs_ty = tc_hs_type hs_ty ekConstraint ----------------- tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type], Kind) -- Like tcHsSigType, but for the ...deriving( C t1 ty2 ) clause -- Returns the C, [ty1, ty2, and the kind of C's *next* argument -- E.g. class C (a::*) (b::k->k) -- data T a b = ... deriving( C Int ) -- returns ([k], C, [k, Int], k->k) -- Also checks that (C ty1 ty2 arg) :: Constraint -- if arg has a suitable kind tcHsDeriv hs_ty = do { arg_kind <- newMetaKindVar ; ty <- tcCheckHsTypeAndGen hs_ty (mkArrowKind arg_kind constraintKind) ; ty <- zonkSigType ty ; arg_kind <- zonkSigType arg_kind ; let (tvs, pred) = splitForAllTys ty ; case getClassPredTys_maybe pred of Just (cls, tys) -> return (tvs, cls, tys, arg_kind) Nothing -> failWithTc (ptext (sLit "Illegal deriving item") <+> quotes (ppr hs_ty)) } -- Used for 'VECTORISE [SCALAR] instance' declarations -- tcHsVectInst :: LHsType Name -> TcM (Class, [Type]) tcHsVectInst ty | Just (L _ cls_name, tys) <- splitLHsClassTy_maybe ty = do { (cls, cls_kind) <- tcClass cls_name ; (arg_tys, _res_kind) <- tcInferApps cls_name cls_kind tys ; return (cls, arg_tys) } | otherwise = failWithTc $ ptext (sLit "Malformed instance type") {- These functions are used during knot-tying in type and class declarations, when we have to separate kind-checking, desugaring, and validity checking ************************************************************************ * * The main kind checker: no validity checks here * * ************************************************************************ First a couple of simple wrappers for kcHsType -} tcClassSigType :: LHsType Name -> TcM Type tcClassSigType lhs_ty = do { ty <- tcCheckLHsTypeAndGen lhs_ty liftedTypeKind ; zonkSigType ty } tcHsConArgType :: NewOrData -> LHsType Name -> TcM Type -- Permit a bang, but discard it tcHsConArgType NewType bty = tcHsLiftedType (getBangType bty) -- Newtypes can't have bangs, but we don't check that -- until checkValidDataCon, so do not want to crash here tcHsConArgType DataType bty = tcHsOpenType (getBangType bty) -- Can't allow an unlifted type for newtypes, because we're effectively -- going to remove the constructor while coercing it to a lifted type. -- And newtypes can't be bang'd --------------------------- tcHsArgTys :: SDoc -> [LHsType Name] -> [Kind] -> TcM [TcType] tcHsArgTys what tys kinds = sequence [ addTypeCtxt ty $ tc_lhs_type ty (expArgKind what kind n) | (ty,kind,n) <- zip3 tys kinds [1..] ] tc_hs_arg_tys :: SDoc -> [LHsType Name] -> [Kind] -> TcM [TcType] -- Just like tcHsArgTys but without the addTypeCtxt tc_hs_arg_tys what tys kinds = sequence [ tc_lhs_type ty (expArgKind what kind n) | (ty,kind,n) <- zip3 tys kinds [1..] ] --------------------------- tcHsOpenType, tcHsLiftedType :: LHsType Name -> TcM TcType -- Used for type signatures -- Do not do validity checking tcHsOpenType ty = addTypeCtxt ty $ tc_lhs_type ty ekOpen tcHsLiftedType ty = addTypeCtxt ty $ tc_lhs_type ty ekLifted -- Like tcHsType, but takes an expected kind tcCheckLHsType :: LHsType Name -> Kind -> TcM Type tcCheckLHsType hs_ty exp_kind = addTypeCtxt hs_ty $ tc_lhs_type hs_ty (EK exp_kind expectedKindMsg) tcLHsType :: LHsType Name -> TcM (TcType, TcKind) -- Called from outside: set the context tcLHsType ty = addTypeCtxt ty (tc_infer_lhs_type ty) --------------------------- tcCheckLHsTypeAndGen :: LHsType Name -> Kind -> TcM Type -- Typecheck a type signature, and kind-generalise it -- The result is not necessarily zonked, and has not been checked for validity tcCheckLHsTypeAndGen lhs_ty kind = do { ty <- tcCheckLHsType lhs_ty kind ; kvs <- zonkTcTypeAndFV ty ; kvs <- kindGeneralize kvs ; return (mkForAllTys kvs ty) } tcCheckHsTypeAndGen :: HsType Name -> Kind -> TcM Type -- Input type is HsType, not LHsType; the caller adds the context -- Otherwise same as tcCheckLHsTypeAndGen tcCheckHsTypeAndGen hs_ty kind = do { ty <- tc_hs_type hs_ty (EK kind expectedKindMsg) ; traceTc "tcCheckHsTypeAndGen" (ppr hs_ty) ; kvs <- zonkTcTypeAndFV ty ; kvs <- kindGeneralize kvs ; return (mkForAllTys kvs ty) } {- Like tcExpr, tc_hs_type takes an expected kind which it unifies with the kind it figures out. When we don't know what kind to expect, we use tc_lhs_type_fresh, to first create a new meta kind variable and use that as the expected kind. -} tc_infer_lhs_type :: LHsType Name -> TcM (TcType, TcKind) tc_infer_lhs_type ty = do { kv <- newMetaKindVar ; r <- tc_lhs_type ty (EK kv expectedKindMsg) ; return (r, kv) } tc_lhs_type :: LHsType Name -> ExpKind -> TcM TcType tc_lhs_type (L span ty) exp_kind = setSrcSpan span $ do { traceTc "tc_lhs_type:" (ppr ty $$ ppr exp_kind) ; tc_hs_type ty exp_kind } tc_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [TcType] tc_lhs_types tys_w_kinds = mapM (uncurry tc_lhs_type) tys_w_kinds ------------------------------------------ tc_fun_type :: HsType Name -> LHsType Name -> LHsType Name -> ExpKind -> TcM TcType -- We need to recognise (->) so that we can construct a FunTy, -- *and* we need to do by looking at the Name, not the TyCon -- (see Note [Zonking inside the knot]). For example, -- consider f :: (->) Int Int (Trac #7312) tc_fun_type ty ty1 ty2 exp_kind@(EK _ ctxt) = do { ty1' <- tc_lhs_type ty1 (EK openTypeKind ctxt) ; ty2' <- tc_lhs_type ty2 (EK openTypeKind ctxt) ; checkExpectedKind ty liftedTypeKind exp_kind ; return (mkFunTy ty1' ty2') } ------------------------------------------ tc_hs_type :: HsType Name -> ExpKind -> TcM TcType tc_hs_type (HsParTy ty) exp_kind = tc_lhs_type ty exp_kind tc_hs_type (HsDocTy ty _) exp_kind = tc_lhs_type ty exp_kind tc_hs_type ty@(HsBangTy {}) _ -- While top-level bangs at this point are eliminated (eg !(Maybe Int)), -- other kinds of bangs are not (eg ((!Maybe) Int)). These kinds of -- bangs are invalid, so fail. (#7210) = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty) tc_hs_type (HsRecTy _) _ = panic "tc_hs_type: record" -- Unwrapped by con decls -- Record types (which only show up temporarily in constructor -- signatures) should have been removed by now ---------- Functions and applications tc_hs_type hs_ty@(HsTyVar name) exp_kind = do { (ty, k) <- tcTyVar name ; checkExpectedKind hs_ty k exp_kind ; return ty } tc_hs_type ty@(HsFunTy ty1 ty2) exp_kind = tc_fun_type ty ty1 ty2 exp_kind tc_hs_type hs_ty@(HsOpTy ty1 (_, l_op@(L _ op)) ty2) exp_kind | op `hasKey` funTyConKey = tc_fun_type hs_ty ty1 ty2 exp_kind | otherwise = do { (op', op_kind) <- tcTyVar op ; tys' <- tcCheckApps hs_ty l_op op_kind [ty1,ty2] exp_kind ; return (mkNakedAppTys op' tys') } -- mkNakedAppTys: see Note [Zonking inside the knot] tc_hs_type hs_ty@(HsAppTy ty1 ty2) exp_kind -- | L _ (HsTyVar fun) <- fun_ty -- , fun `hasKey` funTyConKey -- , [fty1,fty2] <- arg_tys -- = tc_fun_type hs_ty fty1 fty2 exp_kind -- | otherwise = do { (fun_ty', fun_kind) <- tc_infer_lhs_type fun_ty ; arg_tys' <- tcCheckApps hs_ty fun_ty fun_kind arg_tys exp_kind ; return (mkNakedAppTys fun_ty' arg_tys') } -- mkNakedAppTys: see Note [Zonking inside the knot] -- This looks fragile; how do we *know* that fun_ty isn't -- a TyConApp, say (which is never supposed to appear in the -- function position of an AppTy)? where (fun_ty, arg_tys) = splitHsAppTys ty1 [ty2] --------- Foralls tc_hs_type hs_ty@(HsForAllTy _ _ hs_tvs context ty) exp_kind@(EK exp_k _) | isConstraintKind exp_k = failWithTc (hang (ptext (sLit "Illegal constraint:")) 2 (ppr hs_ty)) | otherwise = tcHsTyVarBndrs hs_tvs $ \ tvs' -> -- Do not kind-generalise here! See Note [Kind generalisation] do { ctxt' <- tcHsContext context ; ty' <- if null (unLoc context) then -- Plain forall, no context tc_lhs_type ty exp_kind -- Why exp_kind? See Note [Body kind of forall] else -- If there is a context, then this forall is really a -- _function_, so the kind of the result really is * -- The body kind (result of the function can be * or #, hence ekOpen do { checkExpectedKind hs_ty liftedTypeKind exp_kind ; tc_lhs_type ty ekOpen } ; return (mkSigmaTy tvs' ctxt' ty') } --------- Lists, arrays, and tuples tc_hs_type hs_ty@(HsListTy elt_ty) exp_kind = do { tau_ty <- tc_lhs_type elt_ty ekLifted ; checkExpectedKind hs_ty liftedTypeKind exp_kind ; checkWiredInTyCon listTyCon ; return (mkListTy tau_ty) } tc_hs_type hs_ty@(HsPArrTy elt_ty) exp_kind = do { tau_ty <- tc_lhs_type elt_ty ekLifted ; checkExpectedKind hs_ty liftedTypeKind exp_kind ; checkWiredInTyCon parrTyCon ; return (mkPArrTy tau_ty) } -- See Note [Distinguishing tuple kinds] in HsTypes -- See Note [Inferring tuple kinds] tc_hs_type hs_ty@(HsTupleTy HsBoxedOrConstraintTuple hs_tys) exp_kind@(EK exp_k _ctxt) -- (NB: not zonking before looking at exp_k, to avoid left-right bias) | Just tup_sort <- tupKindSort_maybe exp_k = traceTc "tc_hs_type tuple" (ppr hs_tys) >> tc_tuple hs_ty tup_sort hs_tys exp_kind | otherwise = do { traceTc "tc_hs_type tuple 2" (ppr hs_tys) ; (tys, kinds) <- mapAndUnzipM tc_infer_lhs_type hs_tys ; kinds <- mapM zonkTcKind kinds -- Infer each arg type separately, because errors can be -- confusing if we give them a shared kind. Eg Trac #7410 -- (Either Int, Int), we do not want to get an error saying -- "the second argument of a tuple should have kind *->*" ; let (arg_kind, tup_sort) = case [ (k,s) | k <- kinds , Just s <- [tupKindSort_maybe k] ] of ((k,s) : _) -> (k,s) [] -> (liftedTypeKind, BoxedTuple) -- In the [] case, it's not clear what the kind is, so guess * ; sequence_ [ setSrcSpan loc $ checkExpectedKind ty kind (expArgKind (ptext (sLit "a tuple")) arg_kind n) | (ty@(L loc _),kind,n) <- zip3 hs_tys kinds [1..] ] ; finish_tuple hs_ty tup_sort tys exp_kind } tc_hs_type hs_ty@(HsTupleTy hs_tup_sort tys) exp_kind = tc_tuple hs_ty tup_sort tys exp_kind where tup_sort = case hs_tup_sort of -- Fourth case dealt with above HsUnboxedTuple -> UnboxedTuple HsBoxedTuple -> BoxedTuple HsConstraintTuple -> ConstraintTuple _ -> panic "tc_hs_type HsTupleTy" --------- Promoted lists and tuples tc_hs_type hs_ty@(HsExplicitListTy _k tys) exp_kind = do { tks <- mapM tc_infer_lhs_type tys ; let taus = map fst tks ; kind <- unifyKinds (ptext (sLit "In a promoted list")) tks ; checkExpectedKind hs_ty (mkPromotedListTy kind) exp_kind ; return (foldr (mk_cons kind) (mk_nil kind) taus) } where mk_cons k a b = mkTyConApp (promoteDataCon consDataCon) [k, a, b] mk_nil k = mkTyConApp (promoteDataCon nilDataCon) [k] tc_hs_type hs_ty@(HsExplicitTupleTy _ tys) exp_kind = do { tks <- mapM tc_infer_lhs_type tys ; let n = length tys kind_con = promotedTupleTyCon BoxedTuple n ty_con = promotedTupleDataCon BoxedTuple n (taus, ks) = unzip tks tup_k = mkTyConApp kind_con ks ; checkExpectedKind hs_ty tup_k exp_kind ; return (mkTyConApp ty_con (ks ++ taus)) } --------- Constraint types tc_hs_type ipTy@(HsIParamTy n ty) exp_kind = do { ty' <- tc_lhs_type ty ekLifted ; checkExpectedKind ipTy constraintKind exp_kind ; ipClass <- tcLookupClass ipClassName ; let n' = mkStrLitTy $ hsIPNameFS n ; return (mkClassPred ipClass [n',ty']) } tc_hs_type ty@(HsEqTy ty1 ty2) exp_kind = do { (ty1', kind1) <- tc_infer_lhs_type ty1 ; (ty2', kind2) <- tc_infer_lhs_type ty2 ; checkExpectedKind ty2 kind2 (EK kind1 msg_fn) ; checkExpectedKind ty constraintKind exp_kind ; return (mkNakedTyConApp eqTyCon [kind1, ty1', ty2']) } where msg_fn pkind = ptext (sLit "The left argument of the equality had kind") <+> quotes (pprKind pkind) --------- Misc tc_hs_type (HsKindSig ty sig_k) exp_kind = do { sig_k' <- tcLHsKind sig_k ; checkExpectedKind ty sig_k' exp_kind ; tc_lhs_type ty (EK sig_k' msg_fn) } where msg_fn pkind = ptext (sLit "The signature specified kind") <+> quotes (pprKind pkind) tc_hs_type (HsCoreTy ty) exp_kind = do { checkExpectedKind ty (typeKind ty) exp_kind ; return ty } -- This should never happen; type splices are expanded by the renamer tc_hs_type ty@(HsSpliceTy {}) _exp_kind = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty) tc_hs_type (HsWrapTy {}) _exp_kind = panic "tc_hs_type HsWrapTy" -- We kind checked something twice tc_hs_type hs_ty@(HsTyLit (HsNumTy _ n)) exp_kind = do { checkExpectedKind hs_ty typeNatKind exp_kind ; checkWiredInTyCon typeNatKindCon ; return (mkNumLitTy n) } tc_hs_type hs_ty@(HsTyLit (HsStrTy _ s)) exp_kind = do { checkExpectedKind hs_ty typeSymbolKind exp_kind ; checkWiredInTyCon typeSymbolKindCon ; return (mkStrLitTy s) } tc_hs_type HsWildcardTy _ = panic "tc_hs_type HsWildcardTy" -- unnamed wildcards should have been replaced by named wildcards tc_hs_type hs_ty@(HsNamedWildcardTy name) exp_kind = do { (ty, k) <- tcTyVar name ; checkExpectedKind hs_ty k exp_kind ; return ty } --------------------------- tupKindSort_maybe :: TcKind -> Maybe TupleSort tupKindSort_maybe k | isConstraintKind k = Just ConstraintTuple | isLiftedTypeKind k = Just BoxedTuple | otherwise = Nothing tc_tuple :: HsType Name -> TupleSort -> [LHsType Name] -> ExpKind -> TcM TcType tc_tuple hs_ty tup_sort tys exp_kind = do { tau_tys <- tc_hs_arg_tys cxt_doc tys (repeat arg_kind) ; finish_tuple hs_ty tup_sort tau_tys exp_kind } where arg_kind = case tup_sort of BoxedTuple -> liftedTypeKind UnboxedTuple -> openTypeKind ConstraintTuple -> constraintKind cxt_doc = case tup_sort of BoxedTuple -> ptext (sLit "a tuple") UnboxedTuple -> ptext (sLit "an unboxed tuple") ConstraintTuple -> ptext (sLit "a constraint tuple") finish_tuple :: HsType Name -> TupleSort -> [TcType] -> ExpKind -> TcM TcType finish_tuple hs_ty tup_sort tau_tys exp_kind = do { traceTc "finish_tuple" (ppr res_kind $$ ppr exp_kind $$ ppr exp_kind) ; checkExpectedKind hs_ty res_kind exp_kind ; checkWiredInTyCon tycon ; return (mkTyConApp tycon tau_tys) } where tycon = tupleTyCon tup_sort (length tau_tys) res_kind = case tup_sort of UnboxedTuple -> unliftedTypeKind BoxedTuple -> liftedTypeKind ConstraintTuple -> constraintKind --------------------------- tcInferApps :: Outputable a => a -> TcKind -- Function kind -> [LHsType Name] -- Arg types -> TcM ([TcType], TcKind) -- Kind-checked args tcInferApps the_fun fun_kind args = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) fun_kind args ; args' <- tc_lhs_types args_w_kinds ; return (args', res_kind) } tcCheckApps :: Outputable a => HsType Name -- The type being checked (for err messages only) -> a -- The function -> TcKind -> [LHsType Name] -- Fun kind and arg types -> ExpKind -- Expected kind -> TcM [TcType] tcCheckApps hs_ty the_fun fun_kind args exp_kind = do { (arg_tys, res_kind) <- tcInferApps the_fun fun_kind args ; checkExpectedKind hs_ty res_kind exp_kind ; return arg_tys } --------------------------- splitFunKind :: SDoc -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind) splitFunKind the_fun fun_kind args = go 1 fun_kind args where go _ fk [] = return ([], fk) go arg_no fk (arg:args) = do { mb_fk <- matchExpectedFunKind fk ; case mb_fk of Nothing -> failWithTc too_many_args Just (ak,fk') -> do { (aks, rk) <- go (arg_no+1) fk' args ; let exp_kind = expArgKind (quotes the_fun) ak arg_no ; return ((arg, exp_kind) : aks, rk) } } too_many_args = quotes the_fun <+> ptext (sLit "is applied to too many type arguments") --------------------------- tcHsContext :: LHsContext Name -> TcM [PredType] tcHsContext ctxt = mapM tcHsLPredType (unLoc ctxt) tcHsLPredType :: LHsType Name -> TcM PredType tcHsLPredType pred = tc_lhs_type pred ekConstraint --------------------------- tcTyVar :: Name -> TcM (TcType, TcKind) -- See Note [Type checking recursive type and class declarations] -- in TcTyClsDecls tcTyVar name -- Could be a tyvar, a tycon, or a datacon = do { traceTc "lk1" (ppr name) ; thing <- tcLookup name ; case thing of ATyVar _ tv | isKindVar tv -> failWithTc (ptext (sLit "Kind variable") <+> quotes (ppr tv) <+> ptext (sLit "used as a type")) | otherwise -> return (mkTyVarTy tv, tyVarKind tv) AThing kind -> do { tc <- get_loopy_tc name ; inst_tycon (mkNakedTyConApp tc) kind } -- mkNakedTyConApp: see Note [Zonking inside the knot] AGlobal (ATyCon tc) -> inst_tycon (mkTyConApp tc) (tyConKind tc) AGlobal (AConLike (RealDataCon dc)) | Just tc <- promoteDataCon_maybe dc -> do { data_kinds <- xoptM Opt_DataKinds ; unless data_kinds $ promotionErr name NoDataKinds ; inst_tycon (mkTyConApp tc) (tyConKind tc) } | otherwise -> failWithTc (ptext (sLit "Data constructor") <+> quotes (ppr dc) <+> ptext (sLit "comes from an un-promotable type") <+> quotes (ppr (dataConTyCon dc))) APromotionErr err -> promotionErr name err _ -> wrongThingErr "type" thing name } where get_loopy_tc name = do { env <- getGblEnv ; case lookupNameEnv (tcg_type_env env) name of Just (ATyCon tc) -> return tc _ -> return (aThingErr "tcTyVar" name) } inst_tycon :: ([Type] -> Type) -> Kind -> TcM (Type, Kind) -- Instantiate the polymorphic kind -- Lazy in the TyCon inst_tycon mk_tc_app kind | null kvs = return (mk_tc_app [], ki_body) | otherwise = do { traceTc "lk4" (ppr name <+> dcolon <+> ppr kind) ; ks <- mapM (const newMetaKindVar) kvs ; return (mk_tc_app ks, substKiWith kvs ks ki_body) } where (kvs, ki_body) = splitForAllTys kind tcClass :: Name -> TcM (Class, TcKind) tcClass cls -- Must be a class = do { thing <- tcLookup cls ; case thing of AThing kind -> return (aThingErr "tcClass" cls, kind) AGlobal (ATyCon tc) | Just cls <- tyConClass_maybe tc -> return (cls, tyConKind tc) _ -> wrongThingErr "class" thing cls } aThingErr :: String -> Name -> b -- The type checker for types is sometimes called simply to -- do *kind* checking; and in that case it ignores the type -- returned. Which is a good thing since it may not be available yet! aThingErr str x = pprPanic "AThing evaluated unexpectedly" (text str <+> ppr x) {- Note [Zonking inside the knot] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we are checking the argument types of a data constructor. We must zonk the types before making the DataCon, because once built we can't change it. So we must traverse the type. BUT the parent TyCon is knot-tied, so we can't look at it yet. So we must be careful not to use "smart constructors" for types that look at the TyCon or Class involved. * Hence the use of mkNakedXXX functions. These do *not* enforce the invariants (for example that we use (FunTy s t) rather than (TyConApp (->) [s,t])). * Ditto in zonkTcType (which may be applied more than once, eg to squeeze out kind meta-variables), we are careful not to look at the TyCon. * We arrange to call zonkSigType *once* right at the end, and it does establish the invariants. But in exchange we can't look at the result (not even its structure) until we have emerged from the "knot". * TcHsSyn.zonkTcTypeToType also can safely check/establish invariants. This is horribly delicate. I hate it. A good example of how delicate it is can be seen in Trac #7903. -} mkNakedTyConApp :: TyCon -> [Type] -> Type -- Builds a TyConApp -- * without being strict in TyCon, -- * without satisfying the invariants of TyConApp -- A subsequent zonking will establish the invariants mkNakedTyConApp tc tys = TyConApp tc tys mkNakedAppTys :: Type -> [Type] -> Type mkNakedAppTys ty1 [] = ty1 mkNakedAppTys (TyConApp tc tys1) tys2 = mkNakedTyConApp tc (tys1 ++ tys2) mkNakedAppTys ty1 tys2 = foldl AppTy ty1 tys2 zonkSigType :: TcType -> TcM TcType -- Zonk the result of type-checking a user-written type signature -- It may have kind variables in it, but no meta type variables -- Because of knot-typing (see Note [Zonking inside the knot]) -- it may need to establish the Type invariants; -- hence the use of mkTyConApp and mkAppTy zonkSigType ty = go ty where go (TyConApp tc tys) = do tys' <- mapM go tys return (mkTyConApp tc tys') -- Key point: establish Type invariants! -- See Note [Zonking inside the knot] go (LitTy n) = return (LitTy n) go (FunTy arg res) = do arg' <- go arg res' <- go res return (FunTy arg' res') go (AppTy fun arg) = do fun' <- go fun arg' <- go arg return (mkAppTy fun' arg') -- NB the mkAppTy; we might have instantiated a -- type variable to a type constructor, so we need -- to pull the TyConApp to the top. -- The two interesting cases! go (TyVarTy tyvar) | isTcTyVar tyvar = zonkTcTyVar tyvar | otherwise = TyVarTy <$> updateTyVarKindM go tyvar -- Ordinary (non Tc) tyvars occur inside quantified types go (ForAllTy tv ty) = do { tv' <- zonkTcTyVarBndr tv ; ty' <- go ty ; return (ForAllTy tv' ty') } {- Note [Body kind of a forall] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The body of a forall is usually a type, but in principle there's no reason to prohibit *unlifted* types. In fact, GHC can itself construct a function with an unboxed tuple inside a for-all (via CPR analyis; see typecheck/should_compile/tc170). Moreover in instance heads we get forall-types with kind Constraint. Moreover if we have a signature f :: Int# then we represent it as (HsForAll Implicit [] [] Int#). And this must be legal! We can't drop the empty forall until *after* typechecking the body because of kind polymorphism: Typeable :: forall k. k -> Constraint data Apply f t = Apply (f t) -- Apply :: forall k. (k -> *) -> k -> * instance Typeable Apply where ... Then the dfun has type df :: forall k. Typeable ((k->*) -> k -> *) (Apply k) f :: Typeable Apply f :: forall (t:k->*) (a:k). t a -> t a class C a b where op :: a b -> Typeable Apply data T a = MkT (Typeable Apply) | T2 a T :: * -> * MkT :: forall k. (Typeable ((k->*) -> k -> *) (Apply k)) -> T a f :: (forall (k:BOX). forall (t:: k->*) (a:k). t a -> t a) -> Int f :: (forall a. a -> Typeable Apply) -> Int So we *must* keep the HsForAll on the instance type HsForAll Implicit [] [] (Typeable Apply) so that we do kind generalisation on it. Really we should check that it's a type of value kind {*, Constraint, #}, but I'm not doing that yet Example that should be rejected: f :: (forall (a:*->*). a) Int Note [Inferring tuple kinds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Give a tuple type (a,b,c), which the parser labels as HsBoxedOrConstraintTuple, we try to figure out whether it's a tuple of kind * or Constraint. Step 1: look at the expected kind Step 2: infer argument kinds If after Step 2 it's not clear from the arguments that it's Constraint, then it must be *. Once having decided that we re-check the Check the arguments again to give good error messages in eg. `(Maybe, Maybe)` Note that we will still fail to infer the correct kind in this case: type T a = ((a,a), D a) type family D :: Constraint -> Constraint While kind checking T, we do not yet know the kind of D, so we will default the kind of T to * -> *. It works if we annotate `a` with kind `Constraint`. Note [Desugaring types] ~~~~~~~~~~~~~~~~~~~~~~~ The type desugarer is phase 2 of dealing with HsTypes. Specifically: * It transforms from HsType to Type * It zonks any kinds. The returned type should have no mutable kind or type variables (hence returning Type not TcType): - any unconstrained kind variables are defaulted to AnyK just as in TcHsSyn. - there are no mutable type variables because we are kind-checking a type Reason: the returned type may be put in a TyCon or DataCon where it will never subsequently be zonked. You might worry about nested scopes: ..a:kappa in scope.. let f :: forall b. T '[a,b] -> Int In this case, f's type could have a mutable kind variable kappa in it; and we might then default it to AnyK when dealing with f's type signature. But we don't expect this to happen because we can't get a lexically scoped type variable with a mutable kind variable in it. A delicate point, this. If it becomes an issue we might need to distinguish top-level from nested uses. Moreover * it cannot fail, * it does no unifications * it does no validity checking, except for structural matters, such as (a) spurious ! annotations. (b) a class used as a type Note [Kind of a type splice] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider these terms, each with TH type splice inside: [| e1 :: Maybe $(..blah..) |] [| e2 :: $(..blah..) |] When kind-checking the type signature, we'll kind-check the splice $(..blah..); we want to give it a kind that can fit in any context, as if $(..blah..) :: forall k. k. In the e1 example, the context of the splice fixes kappa to *. But in the e2 example, we'll desugar the type, zonking the kind unification variables as we go. When we encounter the unconstrained kappa, we want to default it to '*', not to AnyK. Help functions for type applications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} addTypeCtxt :: LHsType Name -> TcM a -> TcM a -- Wrap a context around only if we want to show that contexts. -- Omit invisble ones and ones user's won't grok addTypeCtxt (L _ ty) thing = addErrCtxt doc thing where doc = ptext (sLit "In the type") <+> quotes (ppr ty) {- ************************************************************************ * * Type-variable binders * * ************************************************************************ -} mkKindSigVar :: Name -> TcM KindVar -- Use the specified name; don't clone it mkKindSigVar n = do { mb_thing <- tcLookupLcl_maybe n ; case mb_thing of Just (AThing k) | Just kvar <- getTyVar_maybe k -> return kvar _ -> return $ mkTcTyVar n superKind (SkolemTv False) } kcScopedKindVars :: [Name] -> TcM a -> TcM a -- Given some tyvar binders like [a (b :: k -> *) (c :: k)] -- bind each scoped kind variable (k in this case) to a fresh -- kind skolem variable kcScopedKindVars kv_ns thing_inside = do { kvs <- mapM (\n -> newSigTyVar n superKind) kv_ns -- NB: use mutable signature variables ; tcExtendTyVarEnv2 (kv_ns `zip` kvs) thing_inside } -- | Kind-check a 'LHsTyVarBndrs'. If the decl under consideration has a complete, -- user-supplied kind signature (CUSK), generalise the result. Used in 'getInitialKind' -- and in kind-checking. See also Note [Complete user-supplied kind signatures] in -- HsDecls. kcHsTyVarBndrs :: Bool -- ^ True <=> the decl being checked has a CUSK -> LHsTyVarBndrs Name -> TcM (Kind, r) -- ^ the result kind, possibly with other info -> TcM (Kind, r) -- ^ The full kind of the thing being declared, -- with the other info kcHsTyVarBndrs cusk (HsQTvs { hsq_kvs = kv_ns, hsq_tvs = hs_tvs }) thing_inside = do { kvs <- if cusk then mapM mkKindSigVar kv_ns else mapM (\n -> newSigTyVar n superKind) kv_ns ; tcExtendTyVarEnv2 (kv_ns `zip` kvs) $ do { nks <- mapM (kc_hs_tv . unLoc) hs_tvs ; (res_kind, stuff) <- tcExtendKindEnv nks thing_inside ; let full_kind = mkArrowKinds (map snd nks) res_kind kvs = filter (not . isMetaTyVar) $ varSetElems $ tyVarsOfType full_kind gen_kind = if cusk then mkForAllTys kvs full_kind else full_kind ; return (gen_kind, stuff) } } where kc_hs_tv :: HsTyVarBndr Name -> TcM (Name, TcKind) kc_hs_tv (UserTyVar n) = do { mb_thing <- tcLookupLcl_maybe n ; kind <- case mb_thing of Just (AThing k) -> return k _ | cusk -> return liftedTypeKind | otherwise -> newMetaKindVar ; return (n, kind) } kc_hs_tv (KindedTyVar (L _ n) k) = do { kind <- tcLHsKind k -- In an associated type decl, the type variable may already -- be in scope; in that case we want to make sure its kind -- matches the one declared here ; mb_thing <- tcLookupLcl_maybe n ; case mb_thing of Nothing -> return () Just (AThing ks) -> checkKind kind ks Just thing -> pprPanic "check_in_scope" (ppr thing) ; return (n, kind) } tcHsTyVarBndrs :: LHsTyVarBndrs Name -> ([TcTyVar] -> TcM r) -> TcM r -- Bind the kind variables to fresh skolem variables -- and type variables to skolems, each with a meta-kind variable kind tcHsTyVarBndrs (HsQTvs { hsq_kvs = kv_ns, hsq_tvs = hs_tvs }) thing_inside = do { kvs <- mapM mkKindSigVar kv_ns ; tcExtendTyVarEnv kvs $ do { tvs <- mapM tcHsTyVarBndr hs_tvs ; traceTc "tcHsTyVarBndrs {" (vcat [ text "Hs kind vars:" <+> ppr kv_ns , text "Hs type vars:" <+> ppr hs_tvs , text "Kind vars:" <+> ppr kvs , text "Type vars:" <+> ppr tvs ]) ; res <- tcExtendTyVarEnv tvs (thing_inside (kvs ++ tvs)) ; traceTc "tcHsTyVarBndrs }" (vcat [ text "Hs kind vars:" <+> ppr kv_ns , text "Hs type vars:" <+> ppr hs_tvs , text "Kind vars:" <+> ppr kvs , text "Type vars:" <+> ppr tvs ]) ; return res } } tcHsTyVarBndr :: LHsTyVarBndr Name -> TcM TcTyVar -- Return a type variable -- initialised with a kind variable. -- Typically the Kind inside the HsTyVarBndr will be a tyvar with a mutable kind -- in it. -- -- If the variable is already in scope return it, instead of introducing a new -- one. This can occur in -- instance C (a,b) where -- type F (a,b) c = ... -- Here a,b will be in scope when processing the associated type instance for F. -- See Note [Associated type tyvar names] in Class tcHsTyVarBndr (L _ hs_tv) = do { let name = hsTyVarName hs_tv ; mb_tv <- tcLookupLcl_maybe name ; case mb_tv of { Just (ATyVar _ tv) -> return tv ; _ -> do { kind <- case hs_tv of UserTyVar {} -> newMetaKindVar KindedTyVar _ kind -> tcLHsKind kind ; return ( mkTcTyVar name kind (SkolemTv False)) } } } ------------------ kindGeneralize :: TyVarSet -> TcM [KindVar] kindGeneralize tkvs = do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked ; quantifyTyVars gbl_tvs (filterVarSet isKindVar tkvs) } -- ToDo: remove the (filter isKindVar) -- Any type variables in tkvs will be in scope, -- and hence in gbl_tvs, so after removing gbl_tvs -- we should only have kind variables left -- -- BUT there is a smelly case (to be fixed when TH is reorganised) -- f t = [| e :: $t |] -- When typechecking the body of the bracket, we typecheck $t to a -- unification variable 'alpha', with no biding forall. We don't -- want to kind-quantify it! {- Note [Kind generalisation] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We do kind generalisation only at the outer level of a type signature. For example, consider T :: forall k. k -> * f :: (forall a. T a -> Int) -> Int When kind-checking f's type signature we generalise the kind at the outermost level, thus: f1 :: forall k. (forall (a:k). T k a -> Int) -> Int -- YES! and *not* at the inner forall: f2 :: (forall k. forall (a:k). T k a -> Int) -> Int -- NO! Reason: same as for HM inference on value level declarations, we want to infer the most general type. The f2 type signature would be *less applicable* than f1, because it requires a more polymorphic argument. Note [Kinds of quantified type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tcTyVarBndrsGen quantifies over a specified list of type variables, *and* over the kind variables mentioned in the kinds of those tyvars. Note that we must zonk those kinds (obviously) but less obviously, we must return type variables whose kinds are zonked too. Example (a :: k7) where k7 := k9 -> k9 We must return [k9, a:k9->k9] and NOT [k9, a:k7] Reason: we're going to turn this into a for-all type, forall k9. forall (a:k7). blah which the type checker will then instantiate, and instantiate does not look through unification variables! Hence using zonked_kinds when forming tvs'. -} -------------------- -- getInitialKind has made a suitably-shaped kind for the type or class -- Unpack it, and attribute those kinds to the type variables -- Extend the env with bindings for the tyvars, taken from -- the kind of the tycon/class. Give it to the thing inside, and -- check the result kind matches kcLookupKind :: Name -> TcM Kind kcLookupKind nm = do { tc_ty_thing <- tcLookup nm ; case tc_ty_thing of AThing k -> return k AGlobal (ATyCon tc) -> return (tyConKind tc) _ -> pprPanic "kcLookupKind" (ppr tc_ty_thing) } kcTyClTyVars :: Name -> LHsTyVarBndrs Name -> TcM a -> TcM a -- Used for the type variables of a type or class decl, -- when doing the initial kind-check. kcTyClTyVars name (HsQTvs { hsq_kvs = kvs, hsq_tvs = hs_tvs }) thing_inside = kcScopedKindVars kvs $ do { tc_kind <- kcLookupKind name ; let (_, mono_kind) = splitForAllTys tc_kind -- if we have a FullKindSignature, the tc_kind may already -- be generalized. The kvs get matched up while kind-checking -- the types in kc_tv, below (arg_ks, _res_k) = splitKindFunTysN (length hs_tvs) mono_kind -- There should be enough arrows, because -- getInitialKinds used the tcdTyVars ; name_ks <- zipWithM kc_tv hs_tvs arg_ks ; tcExtendKindEnv name_ks thing_inside } where -- getInitialKind has already gotten the kinds of these type -- variables, but tiresomely we need to check them *again* -- to match the kind variables they mention against the ones -- we've freshly brought into scope kc_tv :: LHsTyVarBndr Name -> Kind -> TcM (Name, Kind) kc_tv (L _ (UserTyVar n)) exp_k = return (n, exp_k) kc_tv (L _ (KindedTyVar (L _ n) hs_k)) exp_k = do { k <- tcLHsKind hs_k ; checkKind k exp_k ; return (n, exp_k) } ----------------------- tcTyClTyVars :: Name -> LHsTyVarBndrs Name -- LHS of the type or class decl -> ([TyVar] -> Kind -> TcM a) -> TcM a -- Used for the type variables of a type or class decl, -- on the second pass when constructing the final result -- (tcTyClTyVars T [a,b] thing_inside) -- where T : forall k1 k2 (a:k1 -> *) (b:k1). k2 -> * -- calls thing_inside with arguments -- [k1,k2,a,b] (k2 -> *) -- having also extended the type environment with bindings -- for k1,k2,a,b -- -- No need to freshen the k's because they are just skolem -- constants here, and we are at top level anyway. tcTyClTyVars tycon (HsQTvs { hsq_kvs = hs_kvs, hsq_tvs = hs_tvs }) thing_inside = kcScopedKindVars hs_kvs $ -- Bind scoped kind vars to fresh kind univ vars -- There may be fewer of these than the kvs of -- the type constructor, of course do { thing <- tcLookup tycon ; let { kind = case thing of AThing kind -> kind _ -> panic "tcTyClTyVars" -- We only call tcTyClTyVars during typechecking in -- TcTyClDecls, where the local env is extended with -- the generalized_env (mapping Names to AThings). ; (kvs, body) = splitForAllTys kind ; (kinds, res) = splitKindFunTysN (length hs_tvs) body } ; tvs <- zipWithM tc_hs_tv hs_tvs kinds ; tcExtendTyVarEnv tvs (thing_inside (kvs ++ tvs) res) } where -- In the case of associated types, the renamer has -- ensured that the names are in commmon -- e.g. class C a_29 where -- type T b_30 a_29 :: * -- Here the a_29 is shared tc_hs_tv (L _ (UserTyVar n)) kind = return (mkTyVar n kind) tc_hs_tv (L _ (KindedTyVar (L _ n) hs_k)) kind = do { tc_kind <- tcLHsKind hs_k ; checkKind kind tc_kind ; return (mkTyVar n kind) } ----------------------------------- tcDataKindSig :: Kind -> TcM [TyVar] -- GADT decls can have a (perhaps partial) kind signature -- e.g. data T :: * -> * -> * where ... -- This function makes up suitable (kinded) type variables for -- the argument kinds, and checks that the result kind is indeed *. -- We use it also to make up argument type variables for for data instances. tcDataKindSig kind = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind) ; span <- getSrcSpanM ; us <- newUniqueSupply ; rdr_env <- getLocalRdrEnv ; let uniqs = uniqsFromSupply us occs = [ occ | str <- allNameStrings , let occ = mkOccName tvName str , isNothing (lookupLocalRdrOcc rdr_env occ) ] -- Note [Avoid name clashes for associated data types] ; return [ mk_tv span uniq occ kind | ((kind, occ), uniq) <- arg_kinds `zip` occs `zip` uniqs ] } where (arg_kinds, res_kind) = splitKindFunTys kind mk_tv loc uniq occ kind = mkTyVar (mkInternalName uniq occ loc) kind badKindSig :: Kind -> SDoc badKindSig kind = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind")) 2 (ppr kind) {- Note [Avoid name clashes for associated data types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class C a b where data D b :: * -> * When typechecking the decl for D, we'll invent an extra type variable for D, to fill out its kind. Ideally we don't want this type variable to be 'a', because when pretty printing we'll get class C a b where data D b a0 (NB: the tidying happens in the conversion to IfaceSyn, which happens as part of pretty-printing a TyThing.) That's why we look in the LocalRdrEnv to see what's in scope. This is important only to get nice-looking output when doing ":info C" in GHCi. It isn't essential for correctness. ************************************************************************ * * Scoped type variables * * ************************************************************************ tcAddScopedTyVars is used for scoped type variables added by pattern type signatures e.g. \ ((x::a), (y::a)) -> x+y They never have explicit kinds (because this is source-code only) They are mutable (because they can get bound to a more specific type). Usually we kind-infer and expand type splices, and then tupecheck/desugar the type. That doesn't work well for scoped type variables, because they scope left-right in patterns. (e.g. in the example above, the 'a' in (y::a) is bound by the 'a' in (x::a). The current not-very-good plan is to * find all the types in the patterns * find their free tyvars * do kind inference * bring the kinded type vars into scope * BUT throw away the kind-checked type (we'll kind-check it again when we type-check the pattern) This is bad because throwing away the kind checked type throws away its splices. But too bad for now. [July 03] Historical note: We no longer specify that these type variables must be univerally quantified (lots of email on the subject). If you want to put that back in, you need to a) Do a checkSigTyVars after thing_inside b) More insidiously, don't pass in expected_ty, else we unify with it too early and checkSigTyVars barfs Instead you have to pass in a fresh ty var, and unify it with expected_ty afterwards -} tcHsPatSigType :: UserTypeCtxt -> HsWithBndrs Name (LHsType Name) -- The type signature -> TcM ( Type -- The signature , [(Name, TcTyVar)] -- The new bit of type environment, binding -- the scoped type variables , [(Name, TcTyVar)] ) -- The wildcards -- Used for type-checking type signatures in -- (a) patterns e.g f (x::Int) = e -- (b) result signatures e.g. g x :: Int = e -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x tcHsPatSigType ctxt (HsWB { hswb_cts = hs_ty, hswb_kvs = sig_kvs, hswb_tvs = sig_tvs, hswb_wcs = sig_wcs }) = addErrCtxt (pprSigCtxt ctxt empty (ppr hs_ty)) $ do { kvs <- mapM new_kv sig_kvs ; tvs <- mapM new_tv sig_tvs ; nwc_tvs <- mapM newWildcardVarMetaKind sig_wcs ; let nwc_binds = sig_wcs `zip` nwc_tvs ktv_binds = (sig_kvs `zip` kvs) ++ (sig_tvs `zip` tvs) ; sig_ty <- tcExtendTyVarEnv2 (ktv_binds ++ nwc_binds) $ tcHsLiftedType hs_ty ; sig_ty <- zonkSigType sig_ty ; checkValidType ctxt sig_ty ; emitWildcardHoleConstraints (zip sig_wcs nwc_tvs) ; return (sig_ty, ktv_binds, nwc_binds) } where new_kv name = new_tkv name superKind new_tv name = do { kind <- newMetaKindVar ; new_tkv name kind } new_tkv name kind -- See Note [Pattern signature binders] = case ctxt of RuleSigCtxt {} -> return (mkTcTyVar name kind (SkolemTv False)) _ -> newSigTyVar name kind -- See Note [Unifying SigTvs] tcPatSig :: Bool -- True <=> pattern binding -> HsWithBndrs Name (LHsType Name) -> TcSigmaType -> TcM (TcType, -- The type to use for "inside" the signature [(Name, TcTyVar)], -- The new bit of type environment, binding -- the scoped type variables [(Name, TcTyVar)], -- The wildcards HsWrapper) -- Coercion due to unification with actual ty -- Of shape: res_ty ~ sig_ty tcPatSig in_pat_bind sig res_ty = do { (sig_ty, sig_tvs, sig_nwcs) <- tcHsPatSigType PatSigCtxt sig -- sig_tvs are the type variables free in 'sig', -- and not already in scope. These are the ones -- that should be brought into scope ; if null sig_tvs then do { -- Just do the subsumption check and return wrap <- addErrCtxtM (mk_msg sig_ty) $ tcSubType_NC PatSigCtxt res_ty sig_ty ; return (sig_ty, [], sig_nwcs, wrap) } else do -- Type signature binds at least one scoped type variable -- A pattern binding cannot bind scoped type variables -- It is more convenient to make the test here -- than in the renamer { when in_pat_bind (addErr (patBindSigErr sig_tvs)) -- Check that all newly-in-scope tyvars are in fact -- constrained by the pattern. This catches tiresome -- cases like -- type T a = Int -- f :: Int -> Int -- f (x :: T a) = ... -- Here 'a' doesn't get a binding. Sigh ; let bad_tvs = [ tv | (_, tv) <- sig_tvs , not (tv `elemVarSet` exactTyVarsOfType sig_ty) ] ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs) -- Now do a subsumption check of the pattern signature against res_ty ; wrap <- addErrCtxtM (mk_msg sig_ty) $ tcSubType_NC PatSigCtxt res_ty sig_ty -- Phew! ; return (sig_ty, sig_tvs, sig_nwcs, wrap) } } where mk_msg sig_ty tidy_env = do { (tidy_env, sig_ty) <- zonkTidyTcType tidy_env sig_ty ; (tidy_env, res_ty) <- zonkTidyTcType tidy_env res_ty ; let msg = vcat [ hang (ptext (sLit "When checking that the pattern signature:")) 4 (ppr sig_ty) , nest 2 (hang (ptext (sLit "fits the type of its context:")) 2 (ppr res_ty)) ] ; return (tidy_env, msg) } patBindSigErr :: [(Name, TcTyVar)] -> SDoc patBindSigErr sig_tvs = hang (ptext (sLit "You cannot bind scoped type variable") <> plural sig_tvs <+> pprQuotedList (map fst sig_tvs)) 2 (ptext (sLit "in a pattern binding signature")) {- Note [Pattern signature binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T = forall a. T a (a->Int) f (T x (f :: a->Int) = blah) Here * The pattern (T p1 p2) creates a *skolem* type variable 'a_sk', It must be a skolem so that that it retains its identity, and TcErrors.getSkolemInfo can thereby find the binding site for the skolem. * The type signature pattern (f :: a->Int) binds "a" -> a_sig in the envt * Then unificaiton makes a_sig := a_sk That's why we must make a_sig a MetaTv (albeit a SigTv), not a SkolemTv, so that it can unify to a_sk. For RULE binders, though, things are a bit different (yuk). RULE "foo" forall (x::a) (y::[a]). f x y = ... Here this really is the binding site of the type variable so we'd like to use a skolem, so that we get a complaint if we unify two of them together. Note [Unifying SigTvs] ~~~~~~~~~~~~~~~~~~~~~~ ALAS we have no decent way of avoiding two SigTvs getting unified. Consider f (x::(a,b)) (y::c)) = [fst x, y] Here we'd really like to complain that 'a' and 'c' are unified. But for the reasons above we can't make a,b,c into skolems, so they are just SigTvs that can unify. And indeed, this would be ok, f x (y::c) = case x of (x1 :: a1, True) -> [x,y] (x1 :: a2, False) -> [x,y,y] Here the type of x's first component is called 'a1' in one branch and 'a2' in the other. We could try insisting on the same OccName, but they definitely won't have the sane lexical Name. I think we could solve this by recording in a SigTv a list of all the in-scope variables that it should not unify with, but it's fiddly. ************************************************************************ * * Checking kinds * * ************************************************************************ We would like to get a decent error message from (a) Under-applied type constructors f :: (Maybe, Maybe) (b) Over-applied type constructors f :: Int x -> Int x -} -- The ExpKind datatype means "expected kind" and contains -- some info about just why that kind is expected, to improve -- the error message on a mis-match data ExpKind = EK TcKind (TcKind -> SDoc) -- The second arg is function that takes a *tidied* version -- of the first arg, and produces something like -- "Expected kind k" -- "Expected a constraint" -- "The argument of Maybe should have kind k" instance Outputable ExpKind where ppr (EK k f) = f k ekLifted, ekOpen, ekConstraint :: ExpKind ekLifted = EK liftedTypeKind expectedKindMsg ekOpen = EK openTypeKind expectedKindMsg ekConstraint = EK constraintKind expectedKindMsg expectedKindMsg :: TcKind -> SDoc expectedKindMsg pkind | isConstraintKind pkind = ptext (sLit "Expected a constraint") | isOpenTypeKind pkind = ptext (sLit "Expected a type") | otherwise = ptext (sLit "Expected kind") <+> quotes (pprKind pkind) -- Build an ExpKind for arguments expArgKind :: SDoc -> TcKind -> Int -> ExpKind expArgKind exp kind arg_no = EK kind msg_fn where msg_fn pkind = sep [ ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of") <+> exp , nest 2 $ ptext (sLit "should have kind") <+> quotes (pprKind pkind) ] unifyKinds :: SDoc -> [(TcType, TcKind)] -> TcM TcKind unifyKinds fun act_kinds = do { kind <- newMetaKindVar ; let check (arg_no, (ty, act_kind)) = checkExpectedKind ty act_kind (expArgKind (quotes fun) kind arg_no) ; mapM_ check (zip [1..] act_kinds) ; return kind } checkKind :: TcKind -> TcKind -> TcM () checkKind act_kind exp_kind = do { mb_subk <- unifyKindX act_kind exp_kind ; case mb_subk of Just EQ -> return () _ -> unifyKindMisMatch act_kind exp_kind } checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM () -- A fancy wrapper for 'unifyKindX', which tries -- to give decent error messages. -- (checkExpectedKind ty act_kind exp_kind) -- checks that the actual kind act_kind is compatible -- with the expected kind exp_kind -- The first argument, ty, is used only in the error message generation checkExpectedKind ty act_kind (EK exp_kind ek_ctxt) = do { mb_subk <- unifyKindX act_kind exp_kind -- Kind unification only generates definite errors ; case mb_subk of { Just LT -> return () ; -- act_kind is a sub-kind of exp_kind Just EQ -> return () ; -- The two are equal _other -> do { -- So there's an error -- Now to find out what sort exp_kind <- zonkTcKind exp_kind ; act_kind <- zonkTcKind act_kind ; traceTc "checkExpectedKind" (ppr ty $$ ppr act_kind $$ ppr exp_kind) ; env0 <- tcInitTidyEnv ; dflags <- getDynFlags ; let (exp_as, _) = splitKindFunTys exp_kind (act_as, _) = splitKindFunTys act_kind n_exp_as = length exp_as n_act_as = length act_as n_diff_as = n_act_as - n_exp_as (env1, tidy_exp_kind) = tidyOpenKind env0 exp_kind (env2, tidy_act_kind) = tidyOpenKind env1 act_kind occurs_check | Just act_tv <- tcGetTyVar_maybe act_kind = check_occ act_tv exp_kind | Just exp_tv <- tcGetTyVar_maybe exp_kind = check_occ exp_tv act_kind | otherwise = False check_occ tv k = case occurCheckExpand dflags tv k of OC_Occurs -> True _bad -> False err | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty) <+> ptext (sLit "is unlifted") | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty) <+> ptext (sLit "is lifted") | occurs_check -- Must precede the "more args expected" check = ptext (sLit "Kind occurs check") $$ more_info | n_exp_as < n_act_as -- E.g. [Maybe] = vcat [ ptext (sLit "Expecting") <+> speakN n_diff_as <+> ptext (sLit "more argument") <> (if n_diff_as > 1 then char 's' else empty) <+> ptext (sLit "to") <+> quotes (ppr ty) , more_info ] -- Now n_exp_as >= n_act_as. In the next two cases, -- n_exp_as == 0, and hence so is n_act_as | otherwise -- E.g. Monad [Int] = more_info more_info = sep [ ek_ctxt tidy_exp_kind <> comma , nest 2 $ ptext (sLit "but") <+> quotes (ppr ty) <+> ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)] ; traceTc "checkExpectedKind 1" (ppr ty $$ ppr tidy_act_kind $$ ppr tidy_exp_kind $$ ppr env1 $$ ppr env2) ; failWithTcM (env2, err) } } } {- ************************************************************************ * * Sort checking kinds * * ************************************************************************ tcLHsKind converts a user-written kind to an internal, sort-checked kind. It does sort checking and desugaring at the same time, in one single pass. It fails when the kinds are not well-formed (eg. data A :: * Int), or if there are non-promotable or non-fully applied kinds. -} tcLHsKind :: LHsKind Name -> TcM Kind tcLHsKind k = addErrCtxt (ptext (sLit "In the kind") <+> quotes (ppr k)) $ tc_lhs_kind k tc_lhs_kind :: LHsKind Name -> TcM Kind tc_lhs_kind (L span ki) = setSrcSpan span (tc_hs_kind ki) -- The main worker tc_hs_kind :: HsKind Name -> TcM Kind tc_hs_kind (HsTyVar tc) = tc_kind_var_app tc [] tc_hs_kind k@(HsAppTy _ _) = tc_kind_app k [] tc_hs_kind (HsParTy ki) = tc_lhs_kind ki tc_hs_kind (HsFunTy ki1 ki2) = do kappa_ki1 <- tc_lhs_kind ki1 kappa_ki2 <- tc_lhs_kind ki2 return (mkArrowKind kappa_ki1 kappa_ki2) tc_hs_kind (HsListTy ki) = do kappa <- tc_lhs_kind ki checkWiredInTyCon listTyCon return $ mkPromotedListTy kappa tc_hs_kind (HsTupleTy _ kis) = do kappas <- mapM tc_lhs_kind kis checkWiredInTyCon tycon return $ mkTyConApp tycon kappas where tycon = promotedTupleTyCon BoxedTuple (length kis) -- Argument not kind-shaped tc_hs_kind k = pprPanic "tc_hs_kind" (ppr k) -- Special case for kind application tc_kind_app :: HsKind Name -> [LHsKind Name] -> TcM Kind tc_kind_app (HsAppTy ki1 ki2) kis = tc_kind_app (unLoc ki1) (ki2:kis) tc_kind_app (HsTyVar tc) kis = do { arg_kis <- mapM tc_lhs_kind kis ; tc_kind_var_app tc arg_kis } tc_kind_app ki _ = failWithTc (quotes (ppr ki) <+> ptext (sLit "is not a kind constructor")) tc_kind_var_app :: Name -> [Kind] -> TcM Kind -- Special case for * and Constraint kinds -- They are kinds already, so we don't need to promote them tc_kind_var_app name arg_kis | name == liftedTypeKindTyConName || name == constraintKindTyConName = do { unless (null arg_kis) (failWithTc (text "Kind" <+> ppr name <+> text "cannot be applied")) ; thing <- tcLookup name ; case thing of AGlobal (ATyCon tc) -> return (mkTyConApp tc []) _ -> panic "tc_kind_var_app 1" } -- General case tc_kind_var_app name arg_kis = do { thing <- tcLookup name ; case thing of AGlobal (ATyCon tc) -> do { data_kinds <- xoptM Opt_DataKinds ; unless data_kinds $ addErr (dataKindsErr name) ; case promotableTyCon_maybe tc of Just prom_tc | arg_kis `lengthIs` tyConArity prom_tc -> return (mkTyConApp prom_tc arg_kis) Just _ -> tycon_err tc "is not fully applied" Nothing -> tycon_err tc "is not promotable" } -- A lexically scoped kind variable ATyVar _ kind_var | not (isKindVar kind_var) -> failWithTc (ptext (sLit "Type variable") <+> quotes (ppr kind_var) <+> ptext (sLit "used as a kind")) | not (null arg_kis) -- Kind variables always have kind BOX, -- so cannot be applied to anything -> failWithTc (ptext (sLit "Kind variable") <+> quotes (ppr name) <+> ptext (sLit "cannot appear in a function position")) | otherwise -> return (mkAppTys (mkTyVarTy kind_var) arg_kis) -- It is in scope, but not what we expected AThing _ | isTyVarName name -> failWithTc (ptext (sLit "Type variable") <+> quotes (ppr name) <+> ptext (sLit "used in a kind")) | otherwise -> failWithTc (hang (ptext (sLit "Type constructor") <+> quotes (ppr name) <+> ptext (sLit "used in a kind")) 2 (ptext (sLit "inside its own recursive group"))) APromotionErr err -> promotionErr name err _ -> wrongThingErr "promoted type" thing name -- This really should not happen } where tycon_err tc msg = failWithTc (quotes (ppr tc) <+> ptext (sLit "of kind") <+> quotes (ppr (tyConKind tc)) <+> ptext (sLit msg)) dataKindsErr :: Name -> SDoc dataKindsErr name = hang (ptext (sLit "Illegal kind:") <+> quotes (ppr name)) 2 (ptext (sLit "Perhaps you intended to use DataKinds")) promotionErr :: Name -> PromotionErr -> TcM a promotionErr name err = failWithTc (hang (pprPECategory err <+> quotes (ppr name) <+> ptext (sLit "cannot be used here")) 2 (parens reason)) where reason = case err of FamDataConPE -> ptext (sLit "it comes from a data family instance") NoDataKinds -> ptext (sLit "Perhaps you intended to use DataKinds") _ -> ptext (sLit "it is defined and used in the same recursive group") {- ************************************************************************ * * Scoped type variables * * ************************************************************************ -} badPatSigTvs :: TcType -> [TyVar] -> SDoc badPatSigTvs sig_ty bad_tvs = vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs, quotes (pprWithCommas ppr bad_tvs), ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty), ptext (sLit "but are actually discarded by a type synonym") ] , ptext (sLit "To fix this, expand the type synonym") , ptext (sLit "[Note: I hope to lift this restriction in due course]") ] unifyKindMisMatch :: TcKind -> TcKind -> TcM a unifyKindMisMatch ki1 ki2 = do ki1' <- zonkTcKind ki1 ki2' <- zonkTcKind ki2 let msg = hang (ptext (sLit "Couldn't match kind")) 2 (sep [quotes (ppr ki1'), ptext (sLit "against"), quotes (ppr ki2')]) failWithTc msg
gcampax/ghc
compiler/typecheck/TcHsType.hs
bsd-3-clause
68,568
106
26
20,328
12,036
6,166
5,870
796
8
import Control.Concurrent import Control.Monad.IO.Class import Control.Monad import Data.List import StackTest main :: IO () main = do stack ["clean"] -- to make sure we can load the code even after a clean copy "src/Lib.v1" "src/Lib.hs" copy "src-internal/Internal.v1" "src-internal/Internal.hs" stack ["build"] -- need a build before ghci at the moment, see #4148 forkIO fileEditingThread replThread replThread :: IO () replThread = repl [] $ do replCommand ":main" line <- replGetLine when (line /= "hello world") $ error "Main module didn't load correctly." liftIO $ threadDelay 1000000 -- wait for an edit of the internal library reloadAndTest "testInt" "42" "Internal library didn't reload." liftIO $ threadDelay 1000000 -- wait for an edit of the internal library reloadAndTest "testStr" "\"OK\"" "Main library didn't reload." fileEditingThread :: IO () fileEditingThread = do threadDelay 1000000 -- edit the internal library and return to ghci copy "src-internal/Internal.v2" "src-internal/Internal.hs" threadDelay 1000000 -- edit the internal library and end thread, returning to ghci copy "src/Lib.v2" "src/Lib.hs" reloadAndTest :: String -> String -> String -> Repl () reloadAndTest cmd exp err = do reload replCommand cmd line <- replGetLine unless (exp `isSuffixOf` line) $ error err reload :: Repl () reload = replCommand ":reload" >> loop where loop = replGetLine >>= \line -> unless ("Ok" `isInfixOf` line) loop
juhp/stack
test/integration/tests/3926-ghci-with-sublibraries/Main.hs
bsd-3-clause
1,485
0
11
266
354
169
185
37
1
{-# LANGUAGE OverloadedStrings #-} module Inline ( inlineSpecs ) where import Test.Hspec import Text.Markdown.Inline import Data.Text (Text) import Data.Monoid (mempty) check :: Text -> [Inline] -> Expectation check md ins = toInline mempty md `shouldBe` ins inlineSpecs :: Spec inlineSpecs = do describe "raw text" $ do it "simple" $ check "raw text" [InlineText "raw text"] it "multiline" $ check "raw\ntext" [InlineText "raw\ntext"] describe "italic" $ do it "asterisk" $ check "raw *text*" [InlineText "raw ", InlineItalic [InlineText "text"]] it "underline" $ check "raw _text_" [InlineText "raw ", InlineItalic [InlineText "text"]] it "multiline" $ check "*raw\ntext*" [InlineItalic [InlineText "raw\ntext"]] it "mismatched" $ check "*foo* *bar" [InlineItalic [InlineText "foo"], InlineText " *bar"] describe "bold" $ do it "asterisk" $ check "raw **text**" [InlineText "raw ", InlineBold [InlineText "text"]] it "underline" $ check "raw __text__" [InlineText "raw ", InlineBold [InlineText "text"]] it "multiline" $ check "**raw\ntext**" [InlineBold [InlineText "raw\ntext"]] it "mismatched" $ check "**foo** *bar" [InlineBold [InlineText "foo"], InlineText " *bar"] describe "nested" $ do it "bold inside italic" $ check "*i __ib__ i*" [InlineItalic [InlineText "i ", InlineBold [InlineText "ib"], InlineText " i"]] it "bold inside italic swap" $ check "_i **ib** i_" [InlineItalic [InlineText "i ", InlineBold [InlineText "ib"], InlineText " i"]] it "italic inside bold" $ check "**b _ib_ b**" [InlineBold [InlineText "b ", InlineItalic [InlineText "ib"], InlineText " b"]] it "italic inside bold swap" $ check "__b *ib* b__" [InlineBold [InlineText "b ", InlineItalic [InlineText "ib"], InlineText " b"]] describe "code" $ do it "takes all characters" $ check "`foo*__*bar` baz`" [ InlineCode "foo*__*bar" , InlineText " baz`" ] describe "escaping" $ do it "asterisk" $ check "\\*foo*\\\\" [InlineText "*foo*\\"] describe "links" $ do it "simple" $ check "[bar](foo)" [InlineLink "foo" Nothing [InlineText "bar"]] it "title" $ check "[bar](foo \"baz\")" [InlineLink "foo" (Just "baz") [InlineText "bar"]] {- it "escaped href" $ check "<p><a href=\"foo)\" title=\"baz\">bar</a></p>" "[bar](foo\\) \"baz\")" it "escaped title" $ check "<p><a href=\"foo)\" title=\"baz&quot;\">bar</a></p>" "[bar](foo\\) \"baz\\\"\")" it "inside a paragraph" $ check "<p>Hello <a href=\"foo\">bar</a> World</p>" "Hello [bar](foo) World" it "not a link" $ check "<p>Not a [ link</p>" "Not a [ link" -}
thefalconfeat/markdown
test/Inline.hs
bsd-3-clause
3,090
0
17
946
749
349
400
56
1
{- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 \section{Code output phase} -} {-# LANGUAGE CPP #-} module CodeOutput( codeOutput, outputForeignStubs ) where #include "HsVersions.h" import AsmCodeGen ( nativeCodeGen ) import LlvmCodeGen ( llvmCodeGen ) import UniqSupply ( mkSplitUniqSupply ) import Finder ( mkStubPaths ) import PprC ( writeCs ) import CmmLint ( cmmLint ) import Packages import Cmm ( RawCmmGroup ) import HscTypes import DynFlags import Config import SysTools import Stream (Stream) import qualified Stream import ErrUtils import Outputable import Module import SrcLoc import Control.Exception import System.Directory import System.FilePath import System.IO {- ************************************************************************ * * \subsection{Steering} * * ************************************************************************ -} codeOutput :: DynFlags -> Module -> FilePath -> ModLocation -> ForeignStubs -> [UnitId] -> Stream IO RawCmmGroup () -- Compiled C-- -> IO (FilePath, (Bool{-stub_h_exists-}, Maybe FilePath{-stub_c_exists-})) codeOutput dflags this_mod filenm location foreign_stubs pkg_deps cmm_stream = do { -- Lint each CmmGroup as it goes past ; let linted_cmm_stream = if gopt Opt_DoCmmLinting dflags then Stream.mapM do_lint cmm_stream else cmm_stream do_lint cmm = withTiming (pure dflags) (text "CmmLint"<+>brackets (ppr this_mod)) (const ()) $ do { case cmmLint dflags cmm of Just err -> do { log_action dflags dflags NoReason SevDump noSrcSpan defaultDumpStyle err ; ghcExit dflags 1 } Nothing -> return () ; return cmm } ; stubs_exist <- outputForeignStubs dflags this_mod location foreign_stubs ; case hscTarget dflags of { HscAsm -> outputAsm dflags this_mod location filenm linted_cmm_stream; HscC -> outputC dflags filenm linted_cmm_stream pkg_deps; HscLlvm -> outputLlvm dflags filenm linted_cmm_stream; HscInterpreted -> panic "codeOutput: HscInterpreted"; HscNothing -> panic "codeOutput: HscNothing" } ; return (filenm, stubs_exist) } doOutput :: String -> (Handle -> IO a) -> IO a doOutput filenm io_action = bracket (openFile filenm WriteMode) hClose io_action {- ************************************************************************ * * \subsection{C} * * ************************************************************************ -} outputC :: DynFlags -> FilePath -> Stream IO RawCmmGroup () -> [UnitId] -> IO () outputC dflags filenm cmm_stream packages = do -- ToDo: make the C backend consume the C-- incrementally, by -- pushing the cmm_stream inside (c.f. nativeCodeGen) rawcmms <- Stream.collect cmm_stream -- figure out which header files to #include in the generated .hc file: -- -- * extra_includes from packages -- * -#include options from the cmdline and OPTIONS pragmas -- * the _stub.h file, if there is one. -- let rts = getPackageDetails dflags rtsUnitId let cc_injects = unlines (map mk_include (includes rts)) mk_include h_file = case h_file of '"':_{-"-} -> "#include "++h_file '<':_ -> "#include "++h_file _ -> "#include \""++h_file++"\"" let pkg_names = map unitIdString packages doOutput filenm $ \ h -> do hPutStr h ("/* GHC_PACKAGES " ++ unwords pkg_names ++ "\n*/\n") hPutStr h cc_injects writeCs dflags h rawcmms {- ************************************************************************ * * \subsection{Assembler} * * ************************************************************************ -} outputAsm :: DynFlags -> Module -> ModLocation -> FilePath -> Stream IO RawCmmGroup () -> IO () outputAsm dflags this_mod location filenm cmm_stream | cGhcWithNativeCodeGen == "YES" = do ncg_uniqs <- mkSplitUniqSupply 'n' debugTraceMsg dflags 4 (text "Outputing asm to" <+> text filenm) _ <- {-# SCC "OutputAsm" #-} doOutput filenm $ \h -> {-# SCC "NativeCodeGen" #-} nativeCodeGen dflags this_mod location h ncg_uniqs cmm_stream return () | otherwise = panic "This compiler was built without a native code generator" {- ************************************************************************ * * \subsection{LLVM} * * ************************************************************************ -} outputLlvm :: DynFlags -> FilePath -> Stream IO RawCmmGroup () -> IO () outputLlvm dflags filenm cmm_stream = do ncg_uniqs <- mkSplitUniqSupply 'n' {-# SCC "llvm_output" #-} doOutput filenm $ \f -> {-# SCC "llvm_CodeGen" #-} llvmCodeGen dflags f ncg_uniqs cmm_stream {- ************************************************************************ * * \subsection{Foreign import/export} * * ************************************************************************ -} outputForeignStubs :: DynFlags -> Module -> ModLocation -> ForeignStubs -> IO (Bool, -- Header file created Maybe FilePath) -- C file created outputForeignStubs dflags mod location stubs = do let stub_h = mkStubPaths dflags (moduleName mod) location stub_c <- newTempName dflags "c" case stubs of NoStubs -> return (False, Nothing) ForeignStubs h_code c_code -> do let stub_c_output_d = pprCode CStyle c_code stub_c_output_w = showSDoc dflags stub_c_output_d -- Header file protos for "foreign export"ed functions. stub_h_output_d = pprCode CStyle h_code stub_h_output_w = showSDoc dflags stub_h_output_d createDirectoryIfMissing True (takeDirectory stub_h) dumpIfSet_dyn dflags Opt_D_dump_foreign "Foreign export header file" stub_h_output_d -- we need the #includes from the rts package for the stub files let rts_includes = let rts_pkg = getPackageDetails dflags rtsUnitId in concatMap mk_include (includes rts_pkg) mk_include i = "#include \"" ++ i ++ "\"\n" -- wrapper code mentions the ffi_arg type, which comes from ffi.h ffi_includes | cLibFFI = "#include \"ffi.h\"\n" | otherwise = "" stub_h_file_exists <- outputForeignStubs_help stub_h stub_h_output_w ("#include \"HsFFI.h\"\n" ++ cplusplus_hdr) cplusplus_ftr dumpIfSet_dyn dflags Opt_D_dump_foreign "Foreign export stubs" stub_c_output_d stub_c_file_exists <- outputForeignStubs_help stub_c stub_c_output_w ("#define IN_STG_CODE 0\n" ++ "#include \"Rts.h\"\n" ++ rts_includes ++ ffi_includes ++ cplusplus_hdr) cplusplus_ftr -- We're adding the default hc_header to the stub file, but this -- isn't really HC code, so we need to define IN_STG_CODE==0 to -- avoid the register variables etc. being enabled. return (stub_h_file_exists, if stub_c_file_exists then Just stub_c else Nothing ) where cplusplus_hdr = "#ifdef __cplusplus\nextern \"C\" {\n#endif\n" cplusplus_ftr = "#ifdef __cplusplus\n}\n#endif\n" -- Don't use doOutput for dumping the f. export stubs -- since it is more than likely that the stubs file will -- turn out to be empty, in which case no file should be created. outputForeignStubs_help :: FilePath -> String -> String -> String -> IO Bool outputForeignStubs_help _fname "" _header _footer = return False outputForeignStubs_help fname doc_str header footer = do writeFile fname (header ++ doc_str ++ '\n':footer ++ "\n") return True
vikraman/ghc
compiler/main/CodeOutput.hs
bsd-3-clause
9,592
1
19
3,616
1,465
739
726
152
7
module Wrap0 () where import Language.Haskell.Liquid.Prelude (liquidError, liquidAssertB) data Foo a = F a type IntFoo = Foo Int {-@ assert flibberty :: (Eq a) => a -> Bool @-} flibberty x = prop x (F x) prop x (F y) = liquidAssertB (x == y) {-@ assert flibInt :: (Num a, Ord a) => a -> Bool @-} flibInt x = prop1 x (F (x + 1)) prop1 x (F y) = liquidAssertB (x < y) {-@ assert flibXs :: a -> Bool @-} flibXs x = prop2 (F [x, x, x]) prop2 (F []) = liquidError "no!" prop2 (F _ ) = True
mightymoose/liquidhaskell
tests/pos/wrap0.hs
bsd-3-clause
503
0
9
123
200
107
93
11
1
{-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} module T15341 where type family Foo (a :: k) :: k where Foo a = a
sdiehl/ghc
testsuite/tests/ghci/scripts/T15341.hs
bsd-3-clause
126
0
6
27
30
20
10
5
0
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ja-JP"> <title>Active Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>コンテンツ</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>インデックス</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>検索</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>お気に入り</label> <type>javax.help.FavoritesView</type> </view> </helpset>
ccgreen13/zap-extensions
src/org/zaproxy/zap/extension/ascanrules/resources/help_ja_JP/helpset_ja_JP.hs
apache-2.0
1,005
97
27
161
393
210
183
-1
-1
-- | Internal module to Dfterm3.Dfterm3State -- {-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Dfterm3.Dfterm3State.Internal.Types ( Storage(..) , PersistentStorageState(..) , VolatileStorageState(..) , gameSubscriptions , gameSubscriptionsVolatile , admin , loggedInUsers , readPersistentStorage , readVolatileStorage , modifyVolatileStorage , modifyVolatileStorage' ) where import Control.Lens import Data.Typeable ( Typeable ) import Data.Acid import Data.IORef import Data.SafeCopy import Dfterm3.GameSubscription.Internal.Types import Dfterm3.Admin.Internal.Types import qualified Data.Set as S import qualified Data.Text as T data PersistentStorageState = PersistentStorageState { _gameSubscriptions :: SubscriptionStatePersistent , _admin :: AdminStatePersistent } deriving ( Typeable ) data VolatileStorageState = VolatileStorageState { _gameSubscriptionsVolatile :: SubscriptionStateVolatile , _loggedInUsers :: S.Set T.Text } deriving ( Typeable ) makeLenses ''PersistentStorageState makeLenses ''VolatileStorageState deriveSafeCopy 0 'base ''PersistentStorageState -- | Handle to Dfterm3 state. newtype Storage = Storage ( AcidState PersistentStorageState, IORef VolatileStorageState ) deriving ( Typeable ) readPersistentStorage :: Storage -> AcidState PersistentStorageState readPersistentStorage (Storage (persistent, _)) = persistent readVolatileStorage :: Storage -> IO VolatileStorageState readVolatileStorage (Storage (_, ref)) = readIORef ref modifyVolatileStorage' :: Storage -> (VolatileStorageState -> VolatileStorageState) -> IO () modifyVolatileStorage' (Storage (_, ref)) modifier = atomicModifyIORef' ref $ \old -> ( modifier old, () ) modifyVolatileStorage :: Storage -> (VolatileStorageState -> ( VolatileStorageState, b ) ) -> IO b modifyVolatileStorage (Storage (_, ref)) = atomicModifyIORef' ref
Noeda/dfterm3
src/Dfterm3/Dfterm3State/Internal/Types.hs
isc
2,048
0
10
408
427
246
181
53
1
{-# LANGUAGE FlexibleContexts #-} module Futhark.Analysis.ScalExp ( RelOp0(..) , ScalExp(..) , scalExpType , scalExpSize , subExpToScalExp , toScalExp , expandScalExp , LookupVar , module Futhark.Representation.Primitive ) where import Control.Applicative import Control.Monad import Data.List import qualified Data.Set as S import Data.Maybe import Data.Monoid import Prelude import Futhark.Representation.Primitive hiding (SQuot, SRem, SDiv, SMod, SSignum) import Futhark.Representation.AST hiding (SQuot, SRem, SDiv, SMod, SSignum) import qualified Futhark.Representation.AST as AST import Futhark.Transform.Substitute import Futhark.Transform.Rename import Futhark.Util.Pretty hiding (pretty) ----------------------------------------------------------------- -- BINARY OPERATORS for Numbers -- -- Note that MOD, BAND, XOR, BOR, SHIFTR, SHIFTL not supported -- -- `a SHIFTL/SHIFTR p' can be translated if desired as as -- -- `a * 2^p' or `a / 2^p -- ----------------------------------------------------------------- -- | Relational operators. data RelOp0 = LTH0 | LEQ0 deriving (Eq, Ord, Enum, Bounded, Show) -- | Representation of a scalar expression, which is: -- -- (i) an algebraic expression, e.g., min(a+b, a*b), -- -- (ii) a relational expression: a+b < 5, -- -- (iii) a logical expression: e1 and (not (a+b>5) data ScalExp= Val PrimValue | Id VName PrimType | SNeg ScalExp | SNot ScalExp | SAbs ScalExp | SSignum ScalExp | SPlus ScalExp ScalExp | SMinus ScalExp ScalExp | STimes ScalExp ScalExp | SPow ScalExp ScalExp | SDiv ScalExp ScalExp | SMod ScalExp ScalExp | SQuot ScalExp ScalExp | SRem ScalExp ScalExp | MaxMin Bool [ScalExp] | RelExp RelOp0 ScalExp | SLogAnd ScalExp ScalExp | SLogOr ScalExp ScalExp deriving (Eq, Ord, Show) instance Num ScalExp where 0 + y = y x + 0 = x x + y = SPlus x y x - 0 = x x - y = SMinus x y 0 * _ = 0 _ * 0 = 0 1 * y = y y * 1 = y x * y = STimes x y abs = SAbs signum = SSignum fromInteger = Val . IntValue . Int32Value . fromInteger -- probably not OK negate = SNeg instance Pretty ScalExp where pprPrec _ (Val val) = ppr $ PrimVal val pprPrec _ (Id v _) = ppr v pprPrec _ (SNeg e) = text "-" <> pprPrec 9 e pprPrec _ (SNot e) = text "not" <+> pprPrec 9 e pprPrec _ (SAbs e) = text "abs" <+> pprPrec 9 e pprPrec _ (SSignum e) = text "signum" <+> pprPrec 9 e pprPrec prec (SPlus x y) = ppBinOp prec "+" 4 4 x y pprPrec prec (SMinus x y) = ppBinOp prec "-" 4 10 x y pprPrec prec (SPow x y) = ppBinOp prec "^" 6 6 x y pprPrec prec (STimes x y) = ppBinOp prec "*" 5 5 x y pprPrec prec (SDiv x y) = ppBinOp prec "/" 5 10 x y pprPrec prec (SMod x y) = ppBinOp prec "%" 5 10 x y pprPrec prec (SQuot x y) = ppBinOp prec "//" 5 10 x y pprPrec prec (SRem x y) = ppBinOp prec "%%" 5 10 x y pprPrec prec (SLogOr x y) = ppBinOp prec "||" 0 0 x y pprPrec prec (SLogAnd x y) = ppBinOp prec "&&" 1 1 x y pprPrec prec (RelExp LTH0 e) = ppBinOp prec "<" 2 2 e (0::Int) pprPrec prec (RelExp LEQ0 e) = ppBinOp prec "<=" 2 2 e (0::Int) pprPrec _ (MaxMin True es) = text "min" <> parens (commasep $ map ppr es) pprPrec _ (MaxMin False es) = text "max" <> parens (commasep $ map ppr es) ppBinOp :: (Pretty a, Pretty b) => Int -> String -> Int -> Int -> a -> b -> Doc ppBinOp p bop precedence rprecedence x y = parensIf (p > precedence) $ pprPrec precedence x <+/> text bop <+> pprPrec rprecedence y instance Substitute ScalExp where substituteNames subst e = case e of Id v t -> Id (substituteNames subst v) t Val v -> Val v SNeg x -> SNeg $ substituteNames subst x SNot x -> SNot $ substituteNames subst x SAbs x -> SAbs $ substituteNames subst x SSignum x -> SSignum $ substituteNames subst x SPlus x y -> substituteNames subst x `SPlus` substituteNames subst y SMinus x y -> substituteNames subst x `SMinus` substituteNames subst y SPow x y -> substituteNames subst x `SPow` substituteNames subst y STimes x y -> substituteNames subst x `STimes` substituteNames subst y SDiv x y -> substituteNames subst x `SDiv` substituteNames subst y SMod x y -> substituteNames subst x `SMod` substituteNames subst y SQuot x y -> substituteNames subst x `SDiv` substituteNames subst y SRem x y -> substituteNames subst x `SRem` substituteNames subst y MaxMin m es -> MaxMin m $ map (substituteNames subst) es RelExp r x -> RelExp r $ substituteNames subst x SLogAnd x y -> substituteNames subst x `SLogAnd` substituteNames subst y SLogOr x y -> substituteNames subst x `SLogOr` substituteNames subst y instance Rename ScalExp where rename = substituteRename scalExpType :: ScalExp -> PrimType scalExpType (Val v) = primValueType v scalExpType (Id _ t) = t scalExpType (SNeg e) = scalExpType e scalExpType (SNot _) = Bool scalExpType (SAbs e) = scalExpType e scalExpType (SSignum e) = scalExpType e scalExpType (SPlus e _) = scalExpType e scalExpType (SMinus e _) = scalExpType e scalExpType (STimes e _) = scalExpType e scalExpType (SDiv e _) = scalExpType e scalExpType (SMod e _) = scalExpType e scalExpType (SPow e _) = scalExpType e scalExpType (SQuot e _) = scalExpType e scalExpType (SRem e _) = scalExpType e scalExpType (SLogAnd _ _) = Bool scalExpType (SLogOr _ _) = Bool scalExpType (RelExp _ _) = Bool scalExpType (MaxMin _ []) = IntType Int32 -- arbitrary and probably wrong. scalExpType (MaxMin _ (e:_)) = scalExpType e -- | Number of nodes in the scalar expression. scalExpSize :: ScalExp -> Int scalExpSize Val{} = 1 scalExpSize Id{} = 1 scalExpSize (SNeg e) = scalExpSize e scalExpSize (SNot e) = scalExpSize e scalExpSize (SAbs e) = scalExpSize e scalExpSize (SSignum e) = scalExpSize e scalExpSize (SPlus x y) = scalExpSize x + scalExpSize y scalExpSize (SMinus x y) = scalExpSize x + scalExpSize y scalExpSize (STimes x y) = scalExpSize x + scalExpSize y scalExpSize (SDiv x y) = scalExpSize x + scalExpSize y scalExpSize (SMod x y) = scalExpSize x + scalExpSize y scalExpSize (SPow x y) = scalExpSize x + scalExpSize y scalExpSize (SQuot x y) = scalExpSize x + scalExpSize y scalExpSize (SRem x y) = scalExpSize x + scalExpSize y scalExpSize (SLogAnd x y) = scalExpSize x + scalExpSize y scalExpSize (SLogOr x y) = scalExpSize x + scalExpSize y scalExpSize (RelExp _ x) = scalExpSize x scalExpSize (MaxMin _ []) = 0 scalExpSize (MaxMin _ es) = sum $ map scalExpSize es -- | A function that checks whether a variable name corresponds to a -- scalar expression. type LookupVar = VName -> Maybe ScalExp -- | Non-recursively convert a subexpression to a 'ScalExp'. The -- (scalar) type of the subexpression must be given in advance. subExpToScalExp :: SubExp -> PrimType -> ScalExp subExpToScalExp (Var v) t = Id v t subExpToScalExp (Constant val) _ = Val val toScalExp :: (HasScope t f, Monad f) => LookupVar -> Exp lore -> f (Maybe ScalExp) toScalExp look (BasicOp (SubExp (Var v))) | Just se <- look v = return $ Just se | otherwise = do t <- lookupType v case t of Prim bt | typeIsOK bt -> return $ Just $ Id v bt _ -> return Nothing toScalExp _ (BasicOp (SubExp (Constant val))) | typeIsOK $ primValueType val = return $ Just $ Val val toScalExp look (BasicOp (CmpOp (CmpSlt _) x y)) = Just . RelExp LTH0 <$> (sminus <$> subExpToScalExp' look x <*> subExpToScalExp' look y) toScalExp look (BasicOp (CmpOp (CmpSle _) x y)) = Just . RelExp LEQ0 <$> (sminus <$> subExpToScalExp' look x <*> subExpToScalExp' look y) toScalExp look (BasicOp (CmpOp (CmpEq t) x y)) | typeIsOK t = do x' <- subExpToScalExp' look x y' <- subExpToScalExp' look y return $ Just $ case t of Bool -> SLogAnd x' y' `SLogOr` SLogAnd (SNot x') (SNot y') _ -> RelExp LEQ0 (x' `sminus` y') `SLogAnd` RelExp LEQ0 (y' `sminus` x') toScalExp look (BasicOp (BinOp (Sub t) (Constant x) y)) | typeIsOK $ IntType t, zeroIsh x = Just . SNeg <$> subExpToScalExp' look y toScalExp look (BasicOp (UnOp AST.Not e)) = Just . SNot <$> subExpToScalExp' look e toScalExp look (BasicOp (BinOp bop x y)) | Just f <- binOpScalExp bop = Just <$> (f <$> subExpToScalExp' look x <*> subExpToScalExp' look y) toScalExp _ _ = return Nothing typeIsOK :: PrimType -> Bool typeIsOK = (`elem` Bool : map IntType allIntTypes) subExpToScalExp' :: HasScope t f => LookupVar -> SubExp -> f ScalExp subExpToScalExp' look (Var v) | Just se <- look v = pure se | otherwise = withType <$> lookupType v where withType (Prim t) = subExpToScalExp (Var v) t withType t = error $ "Cannot create ScalExp from variable " ++ pretty v ++ " of type " ++ pretty t subExpToScalExp' _ (Constant val) = pure $ Val val -- | If you have a scalar expression that has been created with -- incomplete symbol table information, you can use this function to -- grow its 'Id' leaves. expandScalExp :: LookupVar -> ScalExp -> ScalExp expandScalExp _ (Val v) = Val v expandScalExp look (Id v t) = fromMaybe (Id v t) $ look v expandScalExp look (SNeg se) = SNeg $ expandScalExp look se expandScalExp look (SNot se) = SNot $ expandScalExp look se expandScalExp look (SAbs se) = SAbs $ expandScalExp look se expandScalExp look (SSignum se) = SSignum $ expandScalExp look se expandScalExp look (MaxMin b ses) = MaxMin b $ map (expandScalExp look) ses expandScalExp look (SPlus x y) = SPlus (expandScalExp look x) (expandScalExp look y) expandScalExp look (SMinus x y) = SMinus (expandScalExp look x) (expandScalExp look y) expandScalExp look (STimes x y) = STimes (expandScalExp look x) (expandScalExp look y) expandScalExp look (SDiv x y) = SDiv (expandScalExp look x) (expandScalExp look y) expandScalExp look (SMod x y) = SMod (expandScalExp look x) (expandScalExp look y) expandScalExp look (SQuot x y) = SQuot (expandScalExp look x) (expandScalExp look y) expandScalExp look (SRem x y) = SRem (expandScalExp look x) (expandScalExp look y) expandScalExp look (SPow x y) = SPow (expandScalExp look x) (expandScalExp look y) expandScalExp look (SLogAnd x y) = SLogAnd (expandScalExp look x) (expandScalExp look y) expandScalExp look (SLogOr x y) = SLogOr (expandScalExp look x) (expandScalExp look y) expandScalExp look (RelExp relop x) = RelExp relop $ expandScalExp look x -- | "Smart constructor" that checks whether we are subtracting zero, -- and if so just returns the first argument. sminus :: ScalExp -> ScalExp -> ScalExp sminus x (Val v) | zeroIsh v = x sminus x y = x `SMinus` y -- XXX: Only integers and booleans, OK? binOpScalExp :: BinOp -> Maybe (ScalExp -> ScalExp -> ScalExp) binOpScalExp bop = fmap snd . find ((==bop) . fst) $ concatMap intOps allIntTypes ++ [ (LogAnd, SLogAnd), (LogOr, SLogOr) ] where intOps t = [ (Add t, SPlus) , (Sub t, SMinus) , (Mul t, STimes) , (AST.SDiv t, SDiv) , (AST.Pow t, SPow) ] instance FreeIn ScalExp where freeIn (Val _) = mempty freeIn (Id i _) = S.singleton i freeIn (SNeg e) = freeIn e freeIn (SNot e) = freeIn e freeIn (SAbs e) = freeIn e freeIn (SSignum e) = freeIn e freeIn (SPlus x y) = freeIn x <> freeIn y freeIn (SMinus x y) = freeIn x <> freeIn y freeIn (SPow x y) = freeIn x <> freeIn y freeIn (STimes x y) = freeIn x <> freeIn y freeIn (SDiv x y) = freeIn x <> freeIn y freeIn (SMod x y) = freeIn x <> freeIn y freeIn (SQuot x y) = freeIn x <> freeIn y freeIn (SRem x y) = freeIn x <> freeIn y freeIn (SLogOr x y) = freeIn x <> freeIn y freeIn (SLogAnd x y) = freeIn x <> freeIn y freeIn (RelExp LTH0 e) = freeIn e freeIn (RelExp LEQ0 e) = freeIn e freeIn (MaxMin _ es) = mconcat $ map freeIn es
ihc/futhark
src/Futhark/Analysis/ScalExp.hs
isc
12,384
0
15
3,211
4,699
2,318
2,381
258
3
-------------------------------------------------------------------------------- -- | -- Module : System.Xattr -- Copyright : (c) Evan Klitzke 2009 -- License : BSD3 -- Maintainer: Evan Klitzke <evan@eklitzke.org> -- Stability : experimental -- Portability : GHC only -- -- Relatively low-level interface to work with extended attributes on Unix -- systems. This is a fairly straightforward port of the API exposed by SGI's -- libattr. -- -------------------------------------------------------------------------------- module System.Xattr ( -- * Functions -- ** Set Functions setxattr , lsetxattr , fsetxattr -- ** Get Functions , getxattr , lgetxattr , fgetxattr -- ** List Functions , listxattr , llistxattr , flistxattr -- * Data Types , AttrName , XattrMode(RegularMode,CreateMode,ReplaceMode) ) where import Data.Char import Foreign.C import Foreign.Ptr import Foreign.Marshal.Alloc import System.Posix.Types import System.Posix.IO import System.IO import System.Xattr.Types import Data.ByteString (ByteString, useAsCStringLen, packCStringLen) type Void = CChar allocBufSize :: Int allocBufSize = 4096 allocCSize :: CSize allocCSize = fromIntegral allocBufSize foreign import ccall unsafe "setxattr" c_setxattr :: CString -> CString -> Ptr Void -> CSize -> CInt -> IO CInt foreign import ccall unsafe "lsetxattr" c_lsetxattr :: CString -> CString -> Ptr Void -> CSize -> CInt -> IO CInt foreign import ccall unsafe "fsetxattr" c_fsetxattr :: CInt -> CString -> Ptr Void -> CSize -> CInt -> IO CInt foreign import ccall unsafe "getxattr" c_getxattr :: CString -> CString -> Ptr Void -> CSize -> IO CSize foreign import ccall unsafe "lgetxattr" c_lgetxattr :: CString -> CString -> Ptr Void -> CSize -> IO CSize foreign import ccall unsafe "fgetxattr" c_fgetxattr :: CInt -> CString -> Ptr Void -> CSize -> IO CSize foreign import ccall unsafe "listxattr" c_listxattr :: CString -> CString -> CSize -> IO CSsize foreign import ccall unsafe "llistxattr" c_llistxattr :: CString -> CString -> CSize -> IO CSsize foreign import ccall unsafe "flistxattr" c_flistxattr :: CInt -> CString -> CSize -> IO CSsize -- return a high level wrapper for a setxattr variant mkSetxattr :: String -> a -> (a -> IO b) -> (b -> CString -> Ptr Void -> CSize -> CInt -> IO CInt) -> AttrName -> ByteString -> XattrMode -> IO () mkSetxattr funcName x iox cFunc attrName attrData mode = do x' <- iox x cName <- newCString attrName val <- useAsCStringLen attrData $ \(binaryData, dataLen) -> cFunc x' cName binaryData (fromIntegral dataLen) (fromIntegral $ fromEnum mode) if val /= 0 then throwErrno funcName else return () handleToIOCInt :: Handle -> IO CInt handleToIOCInt = fmap fromIntegral . handleToFd -- |Set an attribute on a regular file, by path setxattr :: FilePath -> AttrName -> ByteString -> XattrMode -> IO () setxattr path = mkSetxattr "setxattr" path newCString c_setxattr -- |Like setxattr, but if the path is a symbolic link set the attribute on the link itself (not the file pointed to by the link) lsetxattr :: FilePath -> AttrName -> ByteString -> XattrMode -> IO () lsetxattr path = mkSetxattr "lsetxattr" path newCString c_lsetxattr -- |Like setxattr, but use the handle specified rather than a file path fsetxattr :: Handle -> AttrName -> ByteString -> XattrMode -> IO () fsetxattr handle = mkSetxattr "fsetxattr" handle handleToIOCInt c_fsetxattr -- return a high level wrapper for a getxattr variant mkGetxattr :: String -> a -> (a -> IO b) -> (b -> CString -> Ptr Void -> CSize -> IO CSize) -> AttrName -> IO ByteString mkGetxattr funcName x iox cFunc attrName = do x' <- iox x cName <- newCString attrName allocaBytes allocBufSize $ \mem -> do buflen <- cFunc x' cName mem allocCSize if buflen == -1 then throwErrno funcName else packCStringLen (mem, fromIntegral buflen) -- |Get an attribute on a regular file, by path getxattr :: FilePath -> AttrName -> IO ByteString getxattr path = mkGetxattr "getxattr" path newCString c_getxattr -- |Like getxattr, but if the path is a symbolic link get the attribute on the link itself (not the file pointed to by the link) lgetxattr :: FilePath -> AttrName -> IO ByteString lgetxattr path = mkGetxattr "lgetxattr" path newCString c_lgetxattr -- |Like getxattr, but use the handle specified rather than a file path fgetxattr :: Handle -> AttrName -> IO ByteString fgetxattr handle = mkGetxattr "fgetxattr" handle handleToIOCInt c_fgetxattr -- split a string on NUL characters splitNull :: String -> [String] splitNull [] = [] splitNull s = case suf of "" -> [pre] _ -> pre : (splitNull $ tail suf) where (pre, suf) = break (\c -> ord c == 0) s mkListxattr :: String -> a -> (a -> IO b) -> (b -> CString -> CSize -> IO CSsize) -> IO [AttrName] mkListxattr funcName x iox cFunc = do x' <- iox x allocaBytes allocBufSize $ \mem -> do buflen <- cFunc x' mem allocCSize if buflen == -1 then throwErrno funcName else fmap splitNull $ peekCStringLen (mem, fromIntegral buflen) -- |Get a list of all of the attributes set on a path listxattr :: FilePath -> IO [AttrName] listxattr path = mkListxattr "listxattr" path newCString c_listxattr -- |Like listxattr, but if the path is a symbolic link get the attributes on the link itself (not the file pointed to by the link) llistxattr :: FilePath -> IO [AttrName] llistxattr path = mkListxattr "llistxattr" path newCString c_llistxattr -- |Like listxattr, but use the handle specified rather than a file path flistxattr :: Handle -> IO [AttrName] flistxattr handle = mkListxattr "flistxattr" handle handleToIOCInt c_flistxattr
eklitzke/libattr-hs
src/System/Xattr.hs
isc
5,891
0
15
1,265
1,432
743
689
89
2
module Handler.AdminActions where import Import import Handler.AdminUserList (respondCSV) getAdminActionsR :: Handler TypedContent getAdminActionsR = respondCSV [] [Asc AdminActionTimestamp] $ \(Entity _ AdminAction {..}) -> return $ mapFromList [ ("userid", toPathPiece adminActionUser) , ("email", fromMaybe "" adminActionEmail) , ("timestamp", tshow adminActionTimestamp) , ("desc", adminActionDesc) ]
fpco/schoolofhaskell.com
src/Handler/AdminActions.hs
mit
451
0
11
90
122
68
54
-1
-1
{-# LANGUAGE TemplateHaskell #-} module Lib ( someFunc ) where import Control.Lens someFunc :: IO () someFunc = putStrLn "someFunc" data Foo a = Foo { _b :: Int, _c :: Int, _d :: a } deriving (Show) makeLenses ''Foo a = Foo {_b = 1, _c = 2, _d = 3} -- a ^. b -- a ^. c -- a ^. d -- a & b .~ 5 -- set b=5 data TypeA = TypeA { _field1 :: Int } deriving Show makeClassy ''TypeA data TypeB = TypeB { _field2 :: Int } deriving Show makeClassy ''TypeB data TypeC = TypeC { _fieldForA :: TypeA, _fieldForB :: TypeB } deriving Show makeClassy ''TypeC instance HasTypeA TypeC where typeA = fieldForA instance HasTypeB TypeC where typeB = fieldForB c' = TypeC (TypeA 1) (TypeB 2) -- c' ^. field1 -- c' ^. field2 data TypeD = TypeD { _fieldForC :: TypeC } deriving Show makeClassy ''TypeD instance HasTypeC TypeD where typeC = fieldForC instance HasTypeA TypeD where typeA = fieldForC . typeA instance HasTypeB TypeD where typeB = fieldForC . typeB d' = TypeD (TypeC (TypeA 1) (TypeB 2)) -- d' ^. field1 -- d' ^. field2 -- TODO: write some macros to reduce this BS boilerplate!
JoshuaGross/haskell-learning-log
code/lens/src/Lib.hs
mit
1,110
0
9
251
343
193
150
29
1
module Y2016.M09.D27.Solution where {-- We're going to do a bit of Merkle Tree exploration. So you have a Merkle tree; great! And you can compare it! Great! 1. Well, one thing to do is to copy it, so you have two (duplicate) Merkle trees. 2. Another thing to do is to update a branch of one Merkle tree with the branch of another. That sounds simple, but this is deceptive. For the whole Merkle tree, itself, is a branch, and a change to a node affects the hash at the main branch. How do we know which node changed (or was added to, or whatever). 3. Another-ANOTHER thing to do is to improve my insert algorithm. I noticed yesterday that insert was too eager to insert new twigs (nodes with only one leaf), even in the presence of collocated twigs. We must change that. But not today. Today, we're going to narrow down to a path through the Merkle tree so we may address 2. above directly, and then help, eventually, with 1. above. Let's do that. Construct a Merkle tree from the transactions from the latest block (so each leaf is a transaction), then, once constructed, find the leaf, using the hash, of the first transaction and the last transaction of the block. Return the path from the root all the way down to the leaf (exclusive), and then that leaf. --} -- below imports available from 1HaskellADay git repository import Control.Logic.Frege ((-|)) import Data.BlockChain.Block.Transactions import Data.BlockChain.Block.Types import Data.Tree.Merkle import Y2016.M09.D22.Solution (latestTransactions) -- hint: in a previous exercise you've defined latestTransactions -- (see import above). type Direction a = Either (Branch a) (Branch a) pathTo :: Hash -> MerkleTree a -> ([Direction a], Maybe a) pathTo h = pt [] h . root pt :: [Direction a] -> Hash -> Branch a -> ([Direction a], Maybe a) pt path h (Twig h' a) = if h == h' then (path, Just $ packet a) else noAns pt path h b@(Branch _ l r) = if h == dataHash l then genAns Left l else if h == dataHash r then genAns Right r else noAns where genAns dir leaf = (path ++ [dir b], Just $ packet leaf) pt path h (Parent _ l r) = if h < leastHash l then noAns else if h < leastHash r then pt (path ++ [Left $ branch l]) h (branch l) else pt (path ++ [Right $ branch r]) h (branch r) noAns :: ([Direction a], Maybe a) noAns = ([], Nothing) -- Since the Merkle tree is a binary tree, the path returned will be of the -- form ([Left a, Left b, Left c, Right d], e) showing which direction through -- the tree was taken to get to e. {-- *Y2016.M09.D27.Solution> latestTransactions ~> x ~> length ~> 1811 *Y2016.M09.D27.Solution> let xleaf x = Leaf (hashCode x) x *Y2016.M09.D27.Solution> let merk = fromList (map xleaf x) -- FIRST TRANSACTION ------------------------------------------------------- *Y2016.M09.D27.Solution> let (p1, ans) = pathTo (hashCode (head x)) merk *Y2016.M09.D27.Solution> length p1 ~> 17 *Y2016.M09.D27.Solution> ans Just (TX {lockTime = 0, version = 1, size = 116 inputs = [In {sequence = 2975175314, prevOut = Nothing, inScript = "..."}], time = 1475455895, txIndex = 179143255, vInSize = 1, vOutSize = 1, hashCode = "e79c284d8fb16ac53af0dc3f5371a5213d71ae8641fd470dcc0618597375816e", ...}) *Y2016.M09.D27.Solution> p1 [Left Parent,Right Parent,Left Parent,Left Parent,Left Parent,Left Parent, Left Parent,Left Parent,Left Parent,Left Parent,Left Parent,Left Parent, Left Parent,Left Parent,Left Parent,Left Branch,Left Branch] -- LAST TRANSACTION ------------------------------------------------------- *Y2016.M09.D27.Solution> let (pn, ans) = pathTo (hashCode $ last x) merk *Y2016.M09.D27.Solution> ans Just (TX {lockTime = 432579, version = 1, size = 226, inputs = ... ins ..{ *Y2016.M09.D27.Solution> length pn ~> 11 *Y2016.M09.D27.Solution> pn ~> [Left Parent,Left Parent,Left Parent,Left Parent,Left Parent,Left Parent, Right Parent,Left Parent,Left Parent,Left Branch,Left Branch] WOOT! --}
geophf/1HaskellADay
exercises/HAD/Y2016/M09/D27/Solution.hs
mit
3,950
0
12
698
466
255
211
22
6
module SpecHelper where import qualified Data.ByteString.Base64 as B64 (decodeLenient, encode) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy as BL import qualified Data.Map.Strict as M import qualified Data.Set as S import qualified System.IO.Error as E import Control.Monad (void) import Data.Aeson (Value (..), decode, encode) import Data.CaseInsensitive (CI (..)) import Data.List (lookup) import Network.Wai.Test (SResponse (simpleBody, simpleHeaders, simpleStatus)) import System.Environment (getEnv) import System.Process (readProcess) import Text.Regex.TDFA ((=~)) import Network.HTTP.Types import Test.Hspec import Test.Hspec.Wai import Text.Heredoc import PostgREST.Config (AppConfig (..)) import PostgREST.Types (JSPathExp (..), QualifiedIdentifier (..)) import Protolude matchContentTypeJson :: MatchHeader matchContentTypeJson = "Content-Type" <:> "application/json; charset=utf-8" matchContentTypeSingular :: MatchHeader matchContentTypeSingular = "Content-Type" <:> "application/vnd.pgrst.object+json; charset=utf-8" validateOpenApiResponse :: [Header] -> WaiSession () validateOpenApiResponse headers = do r <- request methodGet "/" headers "" liftIO $ let respStatus = simpleStatus r in respStatus `shouldSatisfy` \s -> s == Status { statusCode = 200, statusMessage="OK" } liftIO $ let respHeaders = simpleHeaders r in respHeaders `shouldSatisfy` \hs -> ("Content-Type", "application/openapi+json; charset=utf-8") `elem` hs let Just body = decode (simpleBody r) Just schema <- liftIO $ decode <$> BL.readFile "test/fixtures/openapi.json" let args :: M.Map Text Value args = M.fromList [ ( "schema", schema ) , ( "data", body ) ] hdrs = acceptHdrs "application/json" request methodPost "/rpc/validate_json_schema" hdrs (encode args) `shouldRespondWith` "true" { matchStatus = 200 , matchHeaders = [] } getEnvVarWithDefault :: Text -> Text -> IO Text getEnvVarWithDefault var def = toS <$> getEnv (toS var) `E.catchIOError` const (return $ toS def) _baseCfg :: AppConfig _baseCfg = -- Connection Settings AppConfig mempty "postgrest_test_anonymous" Nothing "test" "localhost" 3000 -- No user configured Unix Socket Nothing -- Jwt settings (Just $ encodeUtf8 "reallyreallyreallyreallyverysafe") False Nothing -- Connection Modifiers 10 10 Nothing (Just "test.switch_role") -- Debug Settings True [ ("app.settings.app_host", "localhost") , ("app.settings.external_api_secret", "0123456789abcdef") ] -- Default role claim key (Right [JSPKey "role"]) -- Empty db-extra-search-path [] -- No root spec override Nothing -- Raw output media types [] testCfg :: Text -> AppConfig testCfg testDbConn = _baseCfg { configDatabase = testDbConn } testCfgNoJWT :: Text -> AppConfig testCfgNoJWT testDbConn = (testCfg testDbConn) { configJwtSecret = Nothing } testUnicodeCfg :: Text -> AppConfig testUnicodeCfg testDbConn = (testCfg testDbConn) { configSchema = "تست" } testLtdRowsCfg :: Text -> AppConfig testLtdRowsCfg testDbConn = (testCfg testDbConn) { configMaxRows = Just 2 } testProxyCfg :: Text -> AppConfig testProxyCfg testDbConn = (testCfg testDbConn) { configProxyUri = Just "https://postgrest.com/openapi.json" } testCfgBinaryJWT :: Text -> AppConfig testCfgBinaryJWT testDbConn = (testCfg testDbConn) { configJwtSecret = Just . B64.decodeLenient $ "cmVhbGx5cmVhbGx5cmVhbGx5cmVhbGx5dmVyeXNhZmU=" } testCfgAudienceJWT :: Text -> AppConfig testCfgAudienceJWT testDbConn = (testCfg testDbConn) { configJwtSecret = Just . B64.decodeLenient $ "cmVhbGx5cmVhbGx5cmVhbGx5cmVhbGx5dmVyeXNhZmU=", configJwtAudience = Just "youraudience" } testCfgAsymJWK :: Text -> AppConfig testCfgAsymJWK testDbConn = (testCfg testDbConn) { configJwtSecret = Just $ encodeUtf8 [str|{"alg":"RS256","e":"AQAB","key_ops":["verify"],"kty":"RSA","n":"0etQ2Tg187jb04MWfpuogYGV75IFrQQBxQaGH75eq_FpbkyoLcEpRUEWSbECP2eeFya2yZ9vIO5ScD-lPmovePk4Aa4SzZ8jdjhmAbNykleRPCxMg0481kz6PQhnHRUv3nF5WP479CnObJKqTVdEagVL66oxnX9VhZG9IZA7k0Th5PfKQwrKGyUeTGczpOjaPqbxlunP73j9AfnAt4XCS8epa-n3WGz1j-wfpr_ys57Aq-zBCfqP67UYzNpeI1AoXsJhD9xSDOzvJgFRvc3vm2wjAW4LEMwi48rCplamOpZToIHEPIaPzpveYQwDnB1HFTR1ove9bpKJsHmi-e2uzQ","use":"sig"}|] } testCfgAsymJWKSet :: Text -> AppConfig testCfgAsymJWKSet testDbConn = (testCfg testDbConn) { configJwtSecret = Just $ encodeUtf8 [str|{"keys": [{"alg":"RS256","e":"AQAB","key_ops":["verify"],"kty":"RSA","n":"0etQ2Tg187jb04MWfpuogYGV75IFrQQBxQaGH75eq_FpbkyoLcEpRUEWSbECP2eeFya2yZ9vIO5ScD-lPmovePk4Aa4SzZ8jdjhmAbNykleRPCxMg0481kz6PQhnHRUv3nF5WP479CnObJKqTVdEagVL66oxnX9VhZG9IZA7k0Th5PfKQwrKGyUeTGczpOjaPqbxlunP73j9AfnAt4XCS8epa-n3WGz1j-wfpr_ys57Aq-zBCfqP67UYzNpeI1AoXsJhD9xSDOzvJgFRvc3vm2wjAW4LEMwi48rCplamOpZToIHEPIaPzpveYQwDnB1HFTR1ove9bpKJsHmi-e2uzQ","use":"sig"}]}|] } testNonexistentSchemaCfg :: Text -> AppConfig testNonexistentSchemaCfg testDbConn = (testCfg testDbConn) { configSchema = "nonexistent" } testCfgExtraSearchPath :: Text -> AppConfig testCfgExtraSearchPath testDbConn = (testCfg testDbConn) { configExtraSearchPath = ["public", "extensions"] } testCfgRootSpec :: Text -> AppConfig testCfgRootSpec testDbConn = (testCfg testDbConn) { configRootSpec = Just $ QualifiedIdentifier "test" "root"} testCfgHtmlRawOutput :: Text -> AppConfig testCfgHtmlRawOutput testDbConn = (testCfg testDbConn) { configRawMediaTypes = ["text/html"] } setupDb :: Text -> IO () setupDb dbConn = do loadFixture dbConn "database" loadFixture dbConn "roles" loadFixture dbConn "schema" loadFixture dbConn "jwt" loadFixture dbConn "jsonschema" loadFixture dbConn "privileges" resetDb dbConn resetDb :: Text -> IO () resetDb dbConn = loadFixture dbConn "data" loadFixture :: Text -> FilePath -> IO() loadFixture dbConn name = void $ readProcess "psql" ["--set", "ON_ERROR_STOP=1", toS dbConn, "-a", "-f", "test/fixtures/" ++ name ++ ".sql"] [] rangeHdrs :: ByteRange -> [Header] rangeHdrs r = [rangeUnit, (hRange, renderByteRange r)] rangeHdrsWithCount :: ByteRange -> [Header] rangeHdrsWithCount r = ("Prefer", "count=exact") : rangeHdrs r acceptHdrs :: BS.ByteString -> [Header] acceptHdrs mime = [(hAccept, mime)] rangeUnit :: Header rangeUnit = ("Range-Unit" :: CI BS.ByteString, "items") matchHeader :: CI BS.ByteString -> BS.ByteString -> [Header] -> Bool matchHeader name valRegex headers = maybe False (=~ valRegex) $ lookup name headers authHeaderBasic :: BS.ByteString -> BS.ByteString -> Header authHeaderBasic u p = (hAuthorization, "Basic " <> (toS . B64.encode . toS $ u <> ":" <> p)) authHeaderJWT :: BS.ByteString -> Header authHeaderJWT token = (hAuthorization, "Bearer " <> token) -- | Tests whether the text can be parsed as a json object comtaining -- the key "message", and optional keys "details", "hint", "code", -- and no extraneous keys isErrorFormat :: BL.ByteString -> Bool isErrorFormat s = "message" `S.member` keys && S.null (S.difference keys validKeys) where obj = decode s :: Maybe (M.Map Text Value) keys = maybe S.empty M.keysSet obj validKeys = S.fromList ["message", "details", "hint", "code"]
diogob/postgrest
test/SpecHelper.hs
mit
7,479
0
14
1,302
1,730
955
775
-1
-1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGTests (js_hasExtension, hasExtension, js_getRequiredFeatures, getRequiredFeatures, js_getRequiredExtensions, getRequiredExtensions, js_getSystemLanguage, getSystemLanguage, SVGTests, castToSVGTests, gTypeSVGTests) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "($1[\"hasExtension\"]($2) ? 1 : 0)" js_hasExtension :: JSRef SVGTests -> JSString -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGTests.hasExtension Mozilla SVGTests.hasExtension documentation> hasExtension :: (MonadIO m, ToJSString extension) => SVGTests -> extension -> m Bool hasExtension self extension = liftIO (js_hasExtension (unSVGTests self) (toJSString extension)) foreign import javascript unsafe "$1[\"requiredFeatures\"]" js_getRequiredFeatures :: JSRef SVGTests -> IO (JSRef SVGStringList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGTests.requiredFeatures Mozilla SVGTests.requiredFeatures documentation> getRequiredFeatures :: (MonadIO m) => SVGTests -> m (Maybe SVGStringList) getRequiredFeatures self = liftIO ((js_getRequiredFeatures (unSVGTests self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"requiredExtensions\"]" js_getRequiredExtensions :: JSRef SVGTests -> IO (JSRef SVGStringList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGTests.requiredExtensions Mozilla SVGTests.requiredExtensions documentation> getRequiredExtensions :: (MonadIO m) => SVGTests -> m (Maybe SVGStringList) getRequiredExtensions self = liftIO ((js_getRequiredExtensions (unSVGTests self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"systemLanguage\"]" js_getSystemLanguage :: JSRef SVGTests -> IO (JSRef SVGStringList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGTests.systemLanguage Mozilla SVGTests.systemLanguage documentation> getSystemLanguage :: (MonadIO m) => SVGTests -> m (Maybe SVGStringList) getSystemLanguage self = liftIO ((js_getSystemLanguage (unSVGTests self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGTests.hs
mit
2,990
26
11
461
664
387
277
49
1
-- | Just enough theorems to get us going with conversions, proven using a tree -- notation that allows us to make assumptions. module BootstrapDIY where import Data.Foldable import Data.List import Utils -- | Proof terms with assumptions. In the notes, we write Γ ⊢ P to denote a proof -- with conclusion P and assumptions Γ. Proofs are not guaranteed to be valid, and -- are pushed through the kernel via verify. data Proof a = Assume (Term a) | UseTheorem (Theorem a) | MP (Proof a) (Proof a) deriving Eq -- | sequent (Γ ⊢ P) yields (Γ, P) sequent :: (Ord a, Show a) => Proof a -> ([Term a], Term a) sequent (Assume a) = ([a], a) sequent (UseTheorem t) = ([], termOfTheorem t) sequent (MP pr pr') = let (asms,c) = sequent pr' in case sequent pr of (asms', p :=>: q) | p == c -> (nub $ sort $ asms ++ asms', q) | otherwise -> error ("MP: " ++ show [p :=>: q, c]) (_, imp) -> error ("MP: " ++ show [imp, c]) -- | concl (Γ ⊢ P) yields P concl :: (Ord a, Show a) => Proof a -> Term a concl = snd . sequent -- | concl (Γ ⊢ P) yields Γ assms :: (Ord a, Show a) => Proof a -> [Term a] assms = fst . sequent u :: Term () x :: Term Two y :: Term Two u = pure () (x,y) = (pure X, pure Y) -- | ⊢ P → P truthThm :: Theorem () truthThm = let step1 = inst2 u (truth ()) axiom1 step2 = inst3 u (truth ()) u axiom2 step3 = mp step2 step1 step4 = inst2 u u axiom1 in mp step3 step4 -- | discharge P (Γ ⊢ R) yields (Γ - {P} ⊢ P → R). This is mechanics of the deduction -- theorem. discharge :: (Ord a, Show a) => Term a -> Proof a -> Proof a discharge asm = d where d pr@(Assume t) | t == asm = UseTheorem (inst (const t) truthThm) | otherwise = MP (UseTheorem (inst2 (concl pr) asm axiom1)) pr d pr@(UseTheorem t) = MP (UseTheorem (inst2 (concl pr) asm axiom1)) pr d (MP imp p) = let p' = concl p in case concl imp of p'' :=>: r' | p' == p''-> MP (MP (UseTheorem (inst3 asm p' r' axiom2)) (d imp)) (d p) _ -> error ("Discharge MP:" ++ show [concl imp, p']) -- | Verify a proof. If there is only one assumption remaining, we automatically -- discharge it. verify :: (Ord a, Show a) => Proof a -> Theorem a verify proof = let v (UseTheorem t) = t v (MP pr pr') = mp (v pr) (v pr') in case assms proof of [] -> v proof [a] -> v (discharge a proof) as -> error errorMsg where errorMsg = "Undischarged assumptions:\n" ++ unlines [ " " ++ show a | a <- as ] -- | matchMPInst (P → Q) (Γ ⊢ P') inst -- attempts to match P with P', instantiates any remaining variables with inst, and -- then applies MP. matchMPInst :: (Eq a, Ord b, Show b) => Theorem a -> Proof b -> (a -> Term b) -> Proof b matchMPInst imp ant inst = let antT = concl ant in case termOfTheorem imp of p :=>: q -> case match p antT of Just insts -> MP (UseTheorem $ instM inst insts imp) ant _ -> error "MATCH MP: No match" _ -> error "MATCH MP" -- | matchMP without any instantiation. All theorems and proofs must be drawn from -- the same alphabet. matchMP :: (Ord a, Show a) => Theorem a -> Proof a -> Proof a matchMP imp ant = matchMPInst imp ant pure -- | ⊢ ¬P → P → ⊥ lemma1 :: Theorem Two lemma1 = let step1 = UseTheorem (inst2 (Not x) (Not (false Y)) axiom1) step2 = Assume (Not x) step3 = MP step1 step2 step4 = matchMP axiom3 step3 in verify step4 -- | ⊢ (¬P → ¬Q) -> (¬P → Q) → P -- | Mendelson's axiom3. mendelson :: Theorem Two mendelson = undefined -- | ⊢ ¬¬P → P dblNegElim :: Theorem () dblNegElim = undefined -- | ⊢ P → ¬¬P dblNegIntro :: Theorem () dblNegIntro = undefined -- | ⊢ (P → Q) → ¬Q → ¬P mt :: Theorem Two mt = undefined -- | ⊢ P → ¬P → Q notElim :: Theorem Two notElim = undefined -- | ⊢ (P → Q) → (¬P → Q) → Q cases :: Theorem Two cases = undefined -- | ⊢ (P → ¬P) → ¬P contra :: Theorem () contra = undefined -- | ⊢ (¬P → P) → P contra2 :: Theorem () contra2 = undefined -- | ⊢ P ∧ Q → P conj1 :: Theorem Two conj1 = undefined -- | ⊢ P ∧ Q → Q conj2 :: Theorem Two conj2 = undefined -- | ⊢ P → Q → P ∧ Q conjI :: Theorem Two conjI = undefined p :: Term Three q :: Term Three r :: Term Three (p,q,r) = (Var P, Var Q, Var R) -- | ⊢ (P → Q → R) ↔ (Q → P → R) swapT :: Theorem Three swapT = undefined -- | ⊦ (P → Q → R) ↔ (P /\ Q → R) uncurry :: Theorem Three uncurry = undefined -- | ⊢ (X ↔ Y) → X → Y eqMP :: Theorem Two eqMP = undefined -- | ⊢ (X ↔ X) reflEq :: Theorem () reflEq = undefined -- | ⊢ (X ↔ Y) ↔ (Y ↔ X) symEq :: Theorem Two symEq = undefined -- | ⊢ (X ↔ Y) → (Y ↔ Z) → (X ↔ Z) trans :: Theorem Three trans = undefined -- | reflect (⊢ (X ↔ Y) → φ(X) → ψ(X)) yields ⊢ (X ↔ Y) → φ(X,Y) ↔ ψ(X,Y) reflect :: (Ord a, Show a) => Theorem a -> Theorem a reflect = undefined -- | ⊢ (X ↔ Y) → (X → P ↔ Y → P) substLeft :: Theorem Three substLeft = undefined -- | ⊢ (X ↔ Y) → (P → X ↔ P → Y) substRight :: Theorem Three substRight = undefined -- | ⊢ (X ↔ Y) → (¬X ↔ ¬Y) substNot :: Theorem Two substNot = undefined
Chattered/proplcf
BootstrapDIY.hs
mit
5,524
0
19
1,584
1,711
884
827
119
4
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-| Briefly, the encryption scheme is a variant of the PBES2 encryption scheme, described in RFC 2898 section 6.2. @ Pass = User-supplied passphrase Salt = 64 bytes of cryptographic salt c = PBKDF2 iteration count DerivedKey = PBKDF2(SHA-512, Pass, Salt, c, 16 + 32) (EncKey, MacKey) = splitAt 16 DerivedKey IV = 0 CipherText = AES-128-CTR(IV, Message, EncKey) MAC = HMAC-SHA-256(MacKey, SHA-256(Salt) + SHA-256(CipherText))) @ The HMAC inputs are hashed before concatenation to avoid leaving "gaps" in the input. Only the derivation parameters and the ciphertext are hashed, to avoid leaking any information about the key material or the plain text. The salt length is set to the output size of the PBKDF2 PRF. TODO: explain why this is done. The HMAC key length is set to the output size of the hash function, the sensible maximum according to RFC 2104. References: * HMAC: Keyed-Hashing for Message Authentication, <https://www.ietf.org/rfc/rfc2104.txt> * PKCS #5: Password-Based Cryptography Specification Version 2.0, <https://www.ietf.org/rfc/rfc2898.txt> -} module Crypto ( getSalt, guessIterCount, encryptAndEncode, decodeAndDecrypt, recrypt, decode, #ifdef TEST encode, encrypt, decrypt, #endif ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad ((>=>)) import Crypto.Hash (SHA256) import Crypto.MAC (HMAC, hmac) import Data.Byteable (toBytes) import qualified Crypto.Cipher.AES as AES import qualified Crypto.Hash.SHA256 as SHA256 import qualified Crypto.PBKDF.ByteString as PBKDF import qualified Data.ByteString.Base64 as Base64 import qualified Data.Serialize as Serialize import Control.Exception (evaluate) import Data.String (fromString) import System.CPUTime (getCPUTime) import qualified Data.ByteString as SB import qualified Data.ByteString.Lazy as LB ------------------------------------------------------------------------ -- Global constants kEncKeyLen, kMacKeyLen, kPrfOutLen :: Int kEncKeyLen = 16 -- encryption key length, in octets kMacKeyLen = 32 -- MAC key length, in octets kPrfOutLen = 64 -- PBKDF2 hash output size, in octets ------------------------------------------------------------------------ -- Tuning parameters guessIterCount :: Double -> IO Int guessIterCount targetSecs = do salt <- getSalt let pass = fromString "Pass" loop !z = do t0 <- getCPUTime _ <- evaluate (kdf pass salt z) t1 <- getCPUTime if (fromIntegral (t1 - t0) * 1e-12) >= targetSecs then return z else loop (z + 1000) loop 0 ------------------------------------------------------------------------ -- High-level interface -- | Update passphrase and encryption parameters. recrypt :: SB.ByteString -- ^ Original passphrase -> SB.ByteString -- ^ New passphrase -> SB.ByteString -- ^ New salt -> Int -- ^ New iteration count -> SB.ByteString -- ^ Original encoded ciphertext -> Either String SB.ByteString -- ^ Either error or new encoded ciphertext recrypt origPass newPass newSalt newIter etxt = do (salt, c, mac, txt) <- decode etxt msg <- decrypt origPass salt c mac txt return $! encryptAndEncode newPass newSalt newIter msg -- | Encrypt the input message and return a base64 encoded string containing -- the encryption parameters along with the ciphertext. encryptAndEncode :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Salt -> Int -- ^ c -> SB.ByteString -- ^ Message -> SB.ByteString -- ^ Encoded ciphertext encryptAndEncode pass salt c = uncurry (encode salt c) . encrypt pass salt c -- | The inverse of 'encryptAndEncode'. decodeAndDecrypt :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Encoded ciphertext -> Either String SB.ByteString -- ^ Either an error or original plaintext decodeAndDecrypt pass etxt = do (salt, c, mac, txt) <- decode etxt decrypt pass salt c mac txt ------------------------------------------------------------------------ -- Serialization encode :: SB.ByteString -- ^ Salt -> Int -- ^ c -> SB.ByteString -- ^ MAC -> SB.ByteString -- ^ Ciphertext -> SB.ByteString -- ^ @Base64 (c + Salt + MAC + Ciphertext)@ encode salt c mac txt = Base64.encode . Serialize.runPut $ do Serialize.putWord16le (fromIntegral c) Serialize.putByteString (SB.concat [ salt, mac, txt ]) decode :: SB.ByteString -> Either String (SB.ByteString, Int, SB.ByteString, SB.ByteString) -- ^ Either error or @(Salt, c, MAC, Ciphertext)@. decode = Base64.decode >=> Serialize.runGet (do c <- fromIntegral <$> Serialize.getWord16le s <- Serialize.getByteString kPrfOutLen m <- Serialize.getByteString kMacKeyLen e <- Serialize.getByteString =<< Serialize.remaining return (s, c, m, e)) ------------------------------------------------------------------------ -- Encryption and decryption encrypt :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Salt -> Int -- ^ Iteration count -> SB.ByteString -- ^ Message -> (SB.ByteString, SB.ByteString) -- ^ @(MAC, Ciphertext)@ encrypt pass salt c plain = let (ekey, hkey) = kdf pass salt c ctx = AES.initAES ekey txt = AES.encryptCTR ctx kNONCE plain mac = hmac256 hkey (sha256 salt `SB.append` sha256 txt) in (mac, txt) decrypt :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Salt -> Int -- ^ Iteration count -> SB.ByteString -- ^ MAC -> SB.ByteString -- ^ Ciphertext -> Either String SB.ByteString -- ^ Error message or plaintext decrypt pass salt c mac' txt = let (ekey, hkey) = kdf pass salt c ctx = AES.initAES ekey mac = hmac256 hkey (sha256 salt `SB.append` sha256 txt) in if mac' == mac then Right (AES.decryptCTR ctx kNONCE txt) else Left "MAC mismatch" kNONCE :: SB.ByteString kNONCE = SB.pack [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0] ------------------------------------------------------------------------ -- Cryptographic salt getSalt :: IO SB.ByteString getSalt = (LB.toStrict . LB.take (fromIntegral kPrfOutLen)) <$> LB.readFile "/dev/urandom" ------------------------------------------------------------------------ -- Key derivation kdf :: SB.ByteString -> SB.ByteString -> Int -> (SB.ByteString, SB.ByteString) kdf pass salt c = SB.splitAt kEncKeyLen (PBKDF.sha512PBKDF2 pass salt c (kEncKeyLen + kMacKeyLen)) ------------------------------------------------------------------------ -- Internals sha256 :: SB.ByteString -> SB.ByteString sha256 = SHA256.hash hmac256 :: SB.ByteString -> SB.ByteString -> SB.ByteString hmac256 s m = toBytes (hmac s m :: HMAC SHA256)
joachifm/pwcrypt
src/Crypto.hs
mit
6,792
0
18
1,341
1,392
772
620
122
2
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE FlexibleInstances #-} module RockPaperScissors ( game , WinCounts(..) , Order(..) , Replay(..) ) where import Data.Maybe import Data.Monoid import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.IO as TLIO import qualified Data.Vector as V import Path import System.IO import AIChallenger.Types data RPS = RPS game :: RPS game = RPS data WinCounts = WinCounts Int Int deriving (Show, Eq) data Order = R | P | S deriving (Show, Eq) data Replay = Replay (V.Vector (WinCounts, Order, Order)) deriving (Show, Eq) instance Monoid Replay where mempty = Replay mempty mappend (Replay a) (Replay b) = Replay (mappend a b) instance Monoid WinCounts where mempty = WinCounts 0 0 mappend (WinCounts a1 b1) (WinCounts a2 b2) = WinCounts (a1 + a2) (b1 + b2) instance Game RPS where type GameState RPS = (WinCounts, Replay) type GameOrder RPS = Order type GameReplay RPS = Replay gameAvailableMaps _ = return (V.singleton (MapName "default")) gameInitialState _ _ = return (mempty, mempty) gameParseOrder _ "R" = Just R gameParseOrder _ "P" = Just P gameParseOrder _ "S" = Just S gameParseOrder _ _ = Nothing gameAdvance rawOrders (oldScore, oldReplay) = case validateOrders rawOrders of Left faults -> let winners = V.filter (not . (`V.elem` (fmap fst faults))) (fmap PlayerId [1, 2]) in Left (GameResult winners (Disqualification faults) oldReplay) Right orders@(o1, o2) -> let newScore = oldScore <> scoreRound orders in Right (newScore, oldReplay <> Replay [(newScore, o1, o2)]) gameTimeout (WinCounts x y, replay) = let winners = case compare x y of EQ -> [PlayerId 1, PlayerId 2] GT -> [PlayerId 1] LT -> [PlayerId 2] in GameResult winners TurnLimit replay gameExtractReplay _ (_state, replay) = replay gameSaveReplay _ path (Replay turns) = do let filepath = toFilePath path formatTurn (WinCounts c1 c2, o1, o2) = TL.pack (unwords [show c1, show c2, show o1, show o2]) withFile filepath WriteMode $ \h -> mapM_ (TLIO.hPutStrLn h . formatTurn) turns gameSendWorld _ _pid _state _sendLine = return () validateOrders :: V.Vector (PlayerId, V.Vector Order) -> Either Faults (Order, Order) validateOrders rawOrders = if V.null faults then let [a, b] = foldMap (V.take 1 . snd) rawOrders in Right (a, b) else Left faults where faults = V.fromList (mapMaybe go (V.toList rawOrders)) go (p, []) = Just (p, (pure (Fault "no moves"))) go (_, [_]) = Nothing go (p, _) = Just (p, (pure (Fault "multiple moves"))) scoreRound :: (Order, Order) -> WinCounts scoreRound (R, P) = WinCounts 0 1 scoreRound (R, S) = WinCounts 1 0 scoreRound (P, S) = WinCounts 0 1 scoreRound (P, R) = WinCounts 1 0 scoreRound (S, R) = WinCounts 0 1 scoreRound (S, P) = WinCounts 1 0 scoreRound _ = WinCounts 0 0
ethercrow/ai-challenger
game-rps/RockPaperScissors.hs
mit
3,261
0
18
922
1,207
641
566
86
4
{-| Module: Y2016.D02 Description: Advent of Code Day 02 Solutions. License: MIT Maintainer: @tylerjl Solutions to the day 02 set of problems for <adventofcode.com>. -} module Y2016.D02 ( bathroomCode , grid1 , grid2 ) where import qualified Data.Matrix as Matrix -- | A position on the keypad grid type Position = (Int, Int) -- | Wrapper to construct a `Matrix` grid :: Int -- ^ Rows -> Int -- ^ Columns -> [a] -- ^ Elements -> Matrix.Matrix a -- ^ Resulting `Matrix` grid = Matrix.fromList -- | `Matrix` for part 1 grid1 :: Matrix.Matrix String grid1 = grid 3 3 (map show ([1 ..] :: [Int])) -- | `Matrix` for part 2 grid2 :: Matrix.Matrix String grid2 = grid 5 5 $ [ "", "", "1", "", "" , "", "2", "3", "4", "" ] ++ map show ([5 .. 9] :: [Int]) ++ [ "", "A", "B", "C", "" , "", "", "D", "", "" ] bathroomCode :: Matrix.Matrix String -- ^ Grid to solve for -> Position -- ^ Starting `Position` (y, x) -> String -- ^ Input `String` of movement instructions -> String -- ^ Bathroom code bathroomCode m origin = decode m "" origin . lines decode :: Matrix.Matrix String -- ^ Grid to solve for -> String -- ^ Solution key that's being built up -> Position -- ^ Current position -> [String] -- ^ List of movements for each code character -> String -- ^ Solution decode _ key _ [] = key decode m key position (moves:xs) = decode m (key ++ Matrix.getElem y x m) position' xs where position'@(x, y) = translate m position moves translate :: Matrix.Matrix [a] -- ^ `Matrix` to move within bounds of -> Position -- ^ Starting `Position` -> String -- ^ List of directions to move -> Position -- ^ Final position after performing movements translate _ position [] = position translate m position (x:xs) | withinBounds position' m = translate m position' xs | otherwise = translate m position xs where position' = move position x withinBounds :: Position -- ^ Coordinates of position to check -> Matrix.Matrix [a] -- ^ `Matrix` to test against -> Bool -- ^ Whether the given position lies within the matrix withinBounds (x, y) m = case Matrix.safeGet y x m of Nothing -> False Just v -> not $ null v move :: Position -- ^ Initial `Position` -> Char -- ^ Movement directive (any of "UDLR") -> Position -- ^ New `Position` move (x, y) c = case c of 'U' -> (x, y - 1) 'R' -> (x + 1, y) 'D' -> (x, y + 1) 'L' -> (x - 1, y) _ -> (x, y)
tylerjl/adventofcode
src/Y2016/D02.hs
mit
2,462
0
9
595
695
389
306
67
5
module Control.DList where {-- Your basic difference list, from Haskell to Idris, and back This answers the Haskell exercise posed at http://lpaste.net/107593 --} import Control.Arrow (app) import Control.Monad import Control.Monad.Trans.Writer import Data.Monoid infixr 5 |> infixl 5 <| data DList a = DL { unDL :: [a] -> [a] } cons :: a -> [a] -> [a] cons a list = a : list (<|) :: DList a -> a -> DList a dlist <| a = DL ((unDL dlist) . (cons a)) (|>) :: a -> DList a -> DList a a |> dlist = DL ((cons a) . (unDL dlist)) emptyDL :: DList a emptyDL = DL id dlToList :: DList a -> [a] dlToList dlist = unDL dlist [] -- added a fromList for difference lists to start from somewhere dl :: [a] -> DList a dl = DL . (++) dl' :: a -> DList a -- your monadic return dl' x = dl [x] -- DLists are monoidal (perfect for writing to *cough* Writer *cough*) instance Monoid (DList a) where mempty = emptyDL d1 `mappend` d2 = DL (unDL d1 . unDL d2) samp :: Writer (DList Char) () -- from Writer w a samp = (\f twoB -> mapM_ f [twoB, " or not ", twoB]) (tell . dl) "to be" -- *Control.DList> dlToList $ snd $ runWriter samp ~> "to be or not to be" -- So now let's make DList a monad -- which means we have to make it a Functor, then an Applicative one -- You know: because monads are functors. -- No, they aren't but in Haskell they are required to be, because reasons. instance Monad DList where return = pure difflist >>= f = {-- ugh! --} mconcat . map f $ dlToList difflist -- but to be a monad these days, you MUST be applicative, so ... instance Applicative DList where pure = dl' dlfs <*> dlargs = dl $ zipWith (curry app) (dlToList dlfs) (dlToList dlargs) -- but applicative needs to be a functor, so ... instance Functor DList where fmap f = dl . map f . dlToList -- and while we're at it, let's make DList a Foldable instance {-- Okay, last week, we looked at improving the views on DList so that we could make it a monad, so that it could participate with MultiMap, which has a requirement of monadicity on the element-container-class. But is that the 'right' improvement? Looking at MultiMap, it's not so that a contain should be a monad, because what is the usage for these containers? Their monadicity? No, it's their foldability. This exercise is inspired by @argumatronic xxx. What is a Foldable instance? (quick lookup of Data.Foldable) A Foldable instance is something that which can be folded. (audience, sarcastically: Thank you, geophf) me: yer welcks. So, (... or maybe we need to ba Traversable, too?) (... I'll put more thought into this ... laterz). So, if what we need, really, is a Foldable instance (not a Monad), then we need to make DList a Foldable instance, too. Today's Haskell exercise: declare DList to be Foldable and define the Foldable functions for it. --} instance Foldable DList where foldr f z = foldr f z . dlToList -- let's talk Traversibility, now: {-- a solution to the problem posted at http://lpaste.net/4868288594713772032 So, we made DList a Foldable instance, all for @argumatronic, and she was grateful for the source material for @HaskellBook ... (geophf waits for the influx of gratitude) ... but then she was all like, "Phfeh! Foldable is so yesterday! Traversable is where it's at! Get with the times!" So, there's that. So, Traversable. What is it? traversable, adj.: that which can be traversed, see traversable. (audience, sarcastic: gee! thanks, geophf!) (geophf: yer welcks) Okay, but seriously, looking at the documentation for Data.Traversable, we see that class (Functor t, Foldable t) => Traversable t where ... Well, as we've done yesterday and the proceeding week, we've already made DList a Functor (and an Applicative Functor, no less, which will come in (very) handy today) and, yesterday, made it Foldable, so we've met the prerequisites of being able to make DList Traversable. What is the power of traversibility? Well, if you have some arbitrary type, t, that's a Traversable type, then you know you can map(M) or sequence over it... ... and as we learned in the '70s, being able to map over a type is a very powerful and useful thing to have. So, let's do this for DList: let's make DList a Traversable instance. Generally, with Applicative Functors, as the minimally-complete definition is traverse or sequenceA. Let's do this. --} instance Traversable DList where traverse f = (pure dl <*>) . traverse f . dlToList -- And if we just want a feelz, yo: instance Show (DList a) where show = const "a DList"
geophf/1HaskellADay
exercises/HAD/Control/DList.hs
mit
4,555
0
10
896
634
338
296
40
1
{-# LANGUAGE ViewPatterns #-} module Day05 where import Data.Map as M -- Part 1 contains3Vowels :: String -> Bool contains3Vowels = go 0 where go :: Int -> String -> Bool go 3 _ = True go _ [] = False go n (x:xs) | x `elem` vowels = go (n+1) xs | otherwise = go n xs vowels = "aeiou" doubleLetters :: String -> Bool doubleLetters [] = False doubleLetters [x] = False doubleLetters (x:y:xs) | x == y = True | otherwise = doubleLetters (y:xs) noPairs :: String -> Bool noPairs [] = True noPairs [x] = True noPairs (x:y:xs) | [x,y] `elem` badPairs = False | otherwise = noPairs (y:xs) where badPairs = ["ab", "cd", "pq", "xy"] part1 = do text <- readFile "day05-input.txt" let input = lines text len = length [x | x <- input, noPairs x, doubleLetters x, contains3Vowels x] print len -- Part 2 oneLetterBetween :: String -> Bool oneLetterBetween (x:y:z:xs) | x == z = True | otherwise = oneLetterBetween (y:z:xs) oneLetterBetween _ = False complexPairs :: String -> Bool complexPairs = go empty where go :: Map String Int -> String -> Bool go m [x,y] | (Just _) <- val = True where (val, m') = insertLookupWithKey (\_ a _ -> a) [x,y] 1 m go m (x:y:z:xs) | (Just _) <- val = True | x == y && x == z = go m' ( z:xs) | otherwise = go m' (y:z:xs) where (val, m') = insertLookupWithKey (\_ a _ -> a) [x,y] 1 m go m _ = False part2 = do text <- readFile "day05-input.txt" let input = lines text len = length [x | x <- input, oneLetterBetween x, complexPairs x] print len
cirquit/Personal-Repository
Haskell/Playground/AdventOfCode/advent-coding/src/Day05.hs
mit
1,709
0
13
536
783
398
385
52
3
module Language.Jass.Semantic.Callable( -- | Utilities to operate with function and natives Callable(..), getCallableName, getCallablePos, getCallableConstness, getCallableParameters, getCallableReturnType, isNativeFunction ) where import Language.Jass.Parser.AST -- | Holds function or native data Callable = CallableNative NativeDecl | CallableFunc Function deriving (Eq, Show) -- | Returns function or native name getCallableName :: Callable -> String getCallableName (CallableNative (NativeDecl _ _ funcDecl)) = getFuncDeclName funcDecl getCallableName (CallableFunc (Function _ _ funcDecl _ _)) = getFuncDeclName funcDecl -- | Returns source position of native or function declaration getCallablePos :: Callable -> SrcPos getCallablePos (CallableNative (NativeDecl pos _ _)) = pos getCallablePos (CallableFunc (Function pos _ _ _ _)) = pos -- | Returns constness flag of native or function getCallableConstness :: Callable -> Bool getCallableConstness (CallableNative (NativeDecl _ constness _)) = constness getCallableConstness (CallableFunc (Function _ constness _ _ _)) = constness -- | Returns formal parameters of native or function getCallableParameters :: Callable -> [Parameter] getCallableParameters (CallableNative (NativeDecl _ _ decl)) = getFuncDeclParameters decl getCallableParameters (CallableFunc (Function _ _ decl _ _)) = getFuncDeclParameters decl -- | Returns function or native return type getCallableReturnType :: Callable -> Maybe JassType getCallableReturnType (CallableNative (NativeDecl _ _ decl)) = getFuncDeclReturnType decl getCallableReturnType (CallableFunc (Function _ _ decl _ _)) = getFuncDeclReturnType decl -- | Returns true for stored natives isNativeFunction :: Callable -> Bool isNativeFunction (CallableNative _) = True isNativeFunction _ = False
NCrashed/hjass
src/library/Language/Jass/Semantic/Callable.hs
mit
1,822
0
9
255
435
231
204
29
1
module Monoids where import Data.Semigroup data NonEmpry a = a :| [a]
mortum5/programming
haskell/ITMO-Course/hw1/src/Monoids.hs
mit
82
0
7
24
24
15
9
3
0
module HaSC.Prim.IntermedSyntax where import HaSC.Prim.ObjInfo type IProgram = [IDecl] type IVar = ObjInfo type Label = String data IDecl = IVarDecl IVar | IFunDecl IVar [IVar] [ICode] deriving(Show, Eq, Ord) data ICode = ILabel Label | ILet IVar IVar | ILi IVar Integer | IAop String IVar IVar IVar | IRelop String IVar IVar IVar | IWrite IVar IVar | IRead IVar IVar | IAddr IVar IVar | IJumpTr IVar Label | IJumpFls IVar Label | IJump Label | ICall IVar IVar [IVar] | IReturn IVar | IRetVoid | IPrint IVar deriving(Show, Eq, Ord)
yu-i9/HaSC
src/HaSC/Prim/IntermedSyntax.hs
mit
794
0
7
356
198
116
82
24
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} module Data.WebsiteContent ( WebsiteContent (..) , StackRelease (..) , Post (..) , loadWebsiteContent ) where import ClassyPrelude.Yesod import CMarkGFM import Data.GhcLinks import Data.Yaml import System.FilePath (takeFileName) import Text.Blaze.Html (preEscapedToHtml) import Types data WebsiteContent = WebsiteContent { wcHomepage :: !Html , wcAuthors :: !Html , wcOlderReleases :: !Html , wcGhcLinks :: !GhcLinks , wcStackReleases :: ![StackRelease] , wcPosts :: !(Vector Post) , wcSpamPackages :: !(Set PackageNameP) -- ^ Packages considered spam which should not be displayed. } data Post = Post { postTitle :: !Text , postSlug :: !Text , postAuthor :: !Text , postTime :: !UTCTime , postDescription :: !Text , postBody :: !Html } loadWebsiteContent :: FilePath -> IO WebsiteContent loadWebsiteContent dir = do wcHomepage <- readHtml "homepage.html" wcAuthors <- readHtml "authors.html" wcOlderReleases <- readHtml "older-releases.html" `catchIO` \_ -> readMarkdown "older-releases.md" wcGhcLinks <- readGhcLinks $ dir </> "stackage-cli" wcStackReleases <- decodeFileEither (dir </> "stack" </> "releases.yaml") >>= either throwIO return wcPosts <- loadPosts (dir </> "posts") `catchAny` \e -> do putStrLn $ "Error loading posts: " ++ tshow e return mempty wcSpamPackages <- decodeFileEither (dir </> "spam-packages.yaml") >>= either throwIO (return . setFromList) return WebsiteContent {..} where readHtml fp = fmap preEscapedToMarkup $ readFileUtf8 $ dir </> fp readMarkdown fp = fmap (preEscapedToHtml . commonmarkToHtml [optSmart] [extTable, extAutolink]) $ readFileUtf8 $ dir </> fp loadPosts :: FilePath -> IO (Vector Post) loadPosts dir = fmap (sortBy (\x y -> postTime y `compare` postTime x)) $ runConduitRes $ sourceDirectory dir .| concatMapC (stripSuffix ".md") .| mapMC loadPost .| sinkVector where loadPost :: FilePath -> ResourceT IO Post loadPost noExt = handleAny (\e -> throwString $ "Could not parse " ++ noExt ++ ".md: " ++ show e) $ do bs <- readFile $ noExt ++ ".md" let slug = pack $ takeFileName noExt text = filter (/= '\r') $ decodeUtf8 bs (frontmatter, body) <- case lines text of "---":rest -> case break (== "---") rest of (frontmatter, "---":body) -> return (unlines frontmatter, unlines body) _ -> error "Missing closing --- on frontmatter" _ -> error "Does not start with --- frontmatter" case Data.Yaml.decodeEither' $ encodeUtf8 frontmatter of Left e -> throwIO e Right mkPost -> return $ mkPost slug $ preEscapedToHtml $ commonmarkToHtml [optSmart] [extTable, extAutolink] body instance (slug ~ Text, body ~ Html) => FromJSON (slug -> body -> Post) where parseJSON = withObject "Post" $ \o -> do postTitle <- o .: "title" postAuthor <- o .: "author" postTime <- o .: "timestamp" postDescription <- o .: "description" return $ \postSlug postBody -> Post {..} data StackRelease = StackRelease { srName :: !Text , srPattern :: !Text } instance FromJSON StackRelease where parseJSON = withObject "StackRelease" $ \o -> StackRelease <$> o .: "name" <*> o .: "pattern"
fpco/stackage-server
src/Data/WebsiteContent.hs
mit
3,666
0
19
995
1,016
523
493
121
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html module Stratosphere.Resources.ApplicationAutoScalingScalableTarget where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.ApplicationAutoScalingScalableTargetScheduledAction -- | Full data type definition for ApplicationAutoScalingScalableTarget. See -- 'applicationAutoScalingScalableTarget' for a more convenient constructor. data ApplicationAutoScalingScalableTarget = ApplicationAutoScalingScalableTarget { _applicationAutoScalingScalableTargetMaxCapacity :: Val Integer , _applicationAutoScalingScalableTargetMinCapacity :: Val Integer , _applicationAutoScalingScalableTargetResourceId :: Val Text , _applicationAutoScalingScalableTargetRoleARN :: Val Text , _applicationAutoScalingScalableTargetScalableDimension :: Val Text , _applicationAutoScalingScalableTargetScheduledActions :: Maybe [ApplicationAutoScalingScalableTargetScheduledAction] , _applicationAutoScalingScalableTargetServiceNamespace :: Val Text } deriving (Show, Eq) instance ToResourceProperties ApplicationAutoScalingScalableTarget where toResourceProperties ApplicationAutoScalingScalableTarget{..} = ResourceProperties { resourcePropertiesType = "AWS::ApplicationAutoScaling::ScalableTarget" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ (Just . ("MaxCapacity",) . toJSON) _applicationAutoScalingScalableTargetMaxCapacity , (Just . ("MinCapacity",) . toJSON) _applicationAutoScalingScalableTargetMinCapacity , (Just . ("ResourceId",) . toJSON) _applicationAutoScalingScalableTargetResourceId , (Just . ("RoleARN",) . toJSON) _applicationAutoScalingScalableTargetRoleARN , (Just . ("ScalableDimension",) . toJSON) _applicationAutoScalingScalableTargetScalableDimension , fmap (("ScheduledActions",) . toJSON) _applicationAutoScalingScalableTargetScheduledActions , (Just . ("ServiceNamespace",) . toJSON) _applicationAutoScalingScalableTargetServiceNamespace ] } -- | Constructor for 'ApplicationAutoScalingScalableTarget' containing -- required fields as arguments. applicationAutoScalingScalableTarget :: Val Integer -- ^ 'aasstMaxCapacity' -> Val Integer -- ^ 'aasstMinCapacity' -> Val Text -- ^ 'aasstResourceId' -> Val Text -- ^ 'aasstRoleARN' -> Val Text -- ^ 'aasstScalableDimension' -> Val Text -- ^ 'aasstServiceNamespace' -> ApplicationAutoScalingScalableTarget applicationAutoScalingScalableTarget maxCapacityarg minCapacityarg resourceIdarg roleARNarg scalableDimensionarg serviceNamespacearg = ApplicationAutoScalingScalableTarget { _applicationAutoScalingScalableTargetMaxCapacity = maxCapacityarg , _applicationAutoScalingScalableTargetMinCapacity = minCapacityarg , _applicationAutoScalingScalableTargetResourceId = resourceIdarg , _applicationAutoScalingScalableTargetRoleARN = roleARNarg , _applicationAutoScalingScalableTargetScalableDimension = scalableDimensionarg , _applicationAutoScalingScalableTargetScheduledActions = Nothing , _applicationAutoScalingScalableTargetServiceNamespace = serviceNamespacearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-maxcapacity aasstMaxCapacity :: Lens' ApplicationAutoScalingScalableTarget (Val Integer) aasstMaxCapacity = lens _applicationAutoScalingScalableTargetMaxCapacity (\s a -> s { _applicationAutoScalingScalableTargetMaxCapacity = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-mincapacity aasstMinCapacity :: Lens' ApplicationAutoScalingScalableTarget (Val Integer) aasstMinCapacity = lens _applicationAutoScalingScalableTargetMinCapacity (\s a -> s { _applicationAutoScalingScalableTargetMinCapacity = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-resourceid aasstResourceId :: Lens' ApplicationAutoScalingScalableTarget (Val Text) aasstResourceId = lens _applicationAutoScalingScalableTargetResourceId (\s a -> s { _applicationAutoScalingScalableTargetResourceId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-rolearn aasstRoleARN :: Lens' ApplicationAutoScalingScalableTarget (Val Text) aasstRoleARN = lens _applicationAutoScalingScalableTargetRoleARN (\s a -> s { _applicationAutoScalingScalableTargetRoleARN = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-scalabledimension aasstScalableDimension :: Lens' ApplicationAutoScalingScalableTarget (Val Text) aasstScalableDimension = lens _applicationAutoScalingScalableTargetScalableDimension (\s a -> s { _applicationAutoScalingScalableTargetScalableDimension = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-scheduledactions aasstScheduledActions :: Lens' ApplicationAutoScalingScalableTarget (Maybe [ApplicationAutoScalingScalableTargetScheduledAction]) aasstScheduledActions = lens _applicationAutoScalingScalableTargetScheduledActions (\s a -> s { _applicationAutoScalingScalableTargetScheduledActions = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-servicenamespace aasstServiceNamespace :: Lens' ApplicationAutoScalingScalableTarget (Val Text) aasstServiceNamespace = lens _applicationAutoScalingScalableTargetServiceNamespace (\s a -> s { _applicationAutoScalingScalableTargetServiceNamespace = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/ApplicationAutoScalingScalableTarget.hs
mit
6,217
0
15
548
734
417
317
61
1
{-| Implementation of cluster-wide logic. This module holds all pure cluster-logic; I\/O related functionality goes into the /Main/ module for the individual binaries. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.HTools.Cluster ( -- * Types AllocSolution(..) , EvacSolution(..) , Table(..) , CStats(..) , AllocNodes , AllocResult , AllocMethod , AllocSolutionList -- * Generic functions , totalResources , computeAllocationDelta -- * First phase functions , computeBadItems -- * Second phase functions , printSolutionLine , formatCmds , involvedNodes , splitJobs -- * Display functions , printNodes , printInsts -- * Balacing functions , checkMove , doNextBalance , tryBalance , compCV , compCVNodes , compDetailedCV , printStats , iMoveToJob -- * IAllocator functions , genAllocNodes , tryAlloc , tryMGAlloc , tryNodeEvac , tryChangeGroup , collapseFailures , allocList -- * Allocation functions , iterateAlloc , tieredAlloc -- * Node group functions , instanceGroup , findSplitInstances , splitCluster ) where import Control.Applicative (liftA2) import Control.Arrow ((&&&)) import qualified Data.IntSet as IntSet import Data.List import Data.Maybe (fromJust, fromMaybe, isJust, isNothing) import Data.Ord (comparing) import Text.Printf (printf) import Ganeti.BasicTypes import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Nic as Nic import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Group as Group import Ganeti.HTools.Types import Ganeti.Compat import qualified Ganeti.OpCodes as OpCodes import Ganeti.Utils import Ganeti.Types (mkNonEmpty) -- * Types -- | Allocation\/relocation solution. data AllocSolution = AllocSolution { asFailures :: [FailMode] -- ^ Failure counts , asAllocs :: Int -- ^ Good allocation count , asSolution :: Maybe Node.AllocElement -- ^ The actual allocation result , asLog :: [String] -- ^ Informational messages } -- | Node evacuation/group change iallocator result type. This result -- type consists of actual opcodes (a restricted subset) that are -- transmitted back to Ganeti. data EvacSolution = EvacSolution { esMoved :: [(Idx, Gdx, [Ndx])] -- ^ Instances moved successfully , esFailed :: [(Idx, String)] -- ^ Instances which were not -- relocated , esOpCodes :: [[OpCodes.OpCode]] -- ^ List of jobs } deriving (Show) -- | Allocation results, as used in 'iterateAlloc' and 'tieredAlloc'. type AllocResult = (FailStats, Node.List, Instance.List, [Instance.Instance], [CStats]) -- | Type alias for easier handling. type AllocSolutionList = [(Instance.Instance, AllocSolution)] -- | A type denoting the valid allocation mode/pairs. -- -- For a one-node allocation, this will be a @Left ['Ndx']@, whereas -- for a two-node allocation, this will be a @Right [('Ndx', -- ['Ndx'])]@. In the latter case, the list is basically an -- association list, grouped by primary node and holding the potential -- secondary nodes in the sub-list. type AllocNodes = Either [Ndx] [(Ndx, [Ndx])] -- | The empty solution we start with when computing allocations. emptyAllocSolution :: AllocSolution emptyAllocSolution = AllocSolution { asFailures = [], asAllocs = 0 , asSolution = Nothing, asLog = [] } -- | The empty evac solution. emptyEvacSolution :: EvacSolution emptyEvacSolution = EvacSolution { esMoved = [] , esFailed = [] , esOpCodes = [] } -- | The complete state for the balancing solution. data Table = Table Node.List Instance.List Score [Placement] deriving (Show) -- | Cluster statistics data type. data CStats = CStats { csFmem :: Integer -- ^ Cluster free mem , csFdsk :: Integer -- ^ Cluster free disk , csFspn :: Integer -- ^ Cluster free spindles , csAmem :: Integer -- ^ Cluster allocatable mem , csAdsk :: Integer -- ^ Cluster allocatable disk , csAcpu :: Integer -- ^ Cluster allocatable cpus , csMmem :: Integer -- ^ Max node allocatable mem , csMdsk :: Integer -- ^ Max node allocatable disk , csMcpu :: Integer -- ^ Max node allocatable cpu , csImem :: Integer -- ^ Instance used mem , csIdsk :: Integer -- ^ Instance used disk , csIspn :: Integer -- ^ Instance used spindles , csIcpu :: Integer -- ^ Instance used cpu , csTmem :: Double -- ^ Cluster total mem , csTdsk :: Double -- ^ Cluster total disk , csTspn :: Double -- ^ Cluster total spindles , csTcpu :: Double -- ^ Cluster total cpus , csVcpu :: Integer -- ^ Cluster total virtual cpus , csNcpu :: Double -- ^ Equivalent to 'csIcpu' but in terms of -- physical CPUs, i.e. normalised used phys CPUs , csXmem :: Integer -- ^ Unnacounted for mem , csNmem :: Integer -- ^ Node own memory , csScore :: Score -- ^ The cluster score , csNinst :: Int -- ^ The total number of instances } deriving (Show) -- | A simple type for allocation functions. type AllocMethod = Node.List -- ^ Node list -> Instance.List -- ^ Instance list -> Maybe Int -- ^ Optional allocation limit -> Instance.Instance -- ^ Instance spec for allocation -> AllocNodes -- ^ Which nodes we should allocate on -> [Instance.Instance] -- ^ Allocated instances -> [CStats] -- ^ Running cluster stats -> Result AllocResult -- ^ Allocation result -- | A simple type for the running solution of evacuations. type EvacInnerState = Either String (Node.List, Instance.Instance, Score, Ndx) -- * Utility functions -- | Verifies the N+1 status and return the affected nodes. verifyN1 :: [Node.Node] -> [Node.Node] verifyN1 = filter Node.failN1 {-| Computes the pair of bad nodes and instances. The bad node list is computed via a simple 'verifyN1' check, and the bad instance list is the list of primary and secondary instances of those nodes. -} computeBadItems :: Node.List -> Instance.List -> ([Node.Node], [Instance.Instance]) computeBadItems nl il = let bad_nodes = verifyN1 $ getOnline nl bad_instances = map (`Container.find` il) . sort . nub $ concatMap (\ n -> Node.sList n ++ Node.pList n) bad_nodes in (bad_nodes, bad_instances) -- | Extracts the node pairs for an instance. This can fail if the -- instance is single-homed. FIXME: this needs to be improved, -- together with the general enhancement for handling non-DRBD moves. instanceNodes :: Node.List -> Instance.Instance -> (Ndx, Ndx, Node.Node, Node.Node) instanceNodes nl inst = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_p = Container.find old_pdx nl old_s = Container.find old_sdx nl in (old_pdx, old_sdx, old_p, old_s) -- | Zero-initializer for the CStats type. emptyCStats :: CStats emptyCStats = CStats 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -- | Update stats with data from a new node. updateCStats :: CStats -> Node.Node -> CStats updateCStats cs node = let CStats { csFmem = x_fmem, csFdsk = x_fdsk, csAmem = x_amem, csAcpu = x_acpu, csAdsk = x_adsk, csMmem = x_mmem, csMdsk = x_mdsk, csMcpu = x_mcpu, csImem = x_imem, csIdsk = x_idsk, csIcpu = x_icpu, csTmem = x_tmem, csTdsk = x_tdsk, csTcpu = x_tcpu, csVcpu = x_vcpu, csNcpu = x_ncpu, csXmem = x_xmem, csNmem = x_nmem, csNinst = x_ninst, csFspn = x_fspn, csIspn = x_ispn, csTspn = x_tspn } = cs inc_amem = Node.fMem node - Node.rMem node inc_amem' = if inc_amem > 0 then inc_amem else 0 inc_adsk = Node.availDisk node inc_imem = truncate (Node.tMem node) - Node.nMem node - Node.xMem node - Node.fMem node inc_icpu = Node.uCpu node inc_idsk = truncate (Node.tDsk node) - Node.fDsk node inc_ispn = Node.tSpindles node - Node.fSpindles node inc_vcpu = Node.hiCpu node inc_acpu = Node.availCpu node inc_ncpu = fromIntegral (Node.uCpu node) / iPolicyVcpuRatio (Node.iPolicy node) in cs { csFmem = x_fmem + fromIntegral (Node.fMem node) , csFdsk = x_fdsk + fromIntegral (Node.fDsk node) , csFspn = x_fspn + fromIntegral (Node.fSpindles node) , csAmem = x_amem + fromIntegral inc_amem' , csAdsk = x_adsk + fromIntegral inc_adsk , csAcpu = x_acpu + fromIntegral inc_acpu , csMmem = max x_mmem (fromIntegral inc_amem') , csMdsk = max x_mdsk (fromIntegral inc_adsk) , csMcpu = max x_mcpu (fromIntegral inc_acpu) , csImem = x_imem + fromIntegral inc_imem , csIdsk = x_idsk + fromIntegral inc_idsk , csIspn = x_ispn + fromIntegral inc_ispn , csIcpu = x_icpu + fromIntegral inc_icpu , csTmem = x_tmem + Node.tMem node , csTdsk = x_tdsk + Node.tDsk node , csTspn = x_tspn + fromIntegral (Node.tSpindles node) , csTcpu = x_tcpu + Node.tCpu node , csVcpu = x_vcpu + fromIntegral inc_vcpu , csNcpu = x_ncpu + inc_ncpu , csXmem = x_xmem + fromIntegral (Node.xMem node) , csNmem = x_nmem + fromIntegral (Node.nMem node) , csNinst = x_ninst + length (Node.pList node) } -- | Compute the total free disk and memory in the cluster. totalResources :: Node.List -> CStats totalResources nl = let cs = foldl' updateCStats emptyCStats . Container.elems $ nl in cs { csScore = compCV nl } -- | Compute the delta between two cluster state. -- -- This is used when doing allocations, to understand better the -- available cluster resources. The return value is a triple of the -- current used values, the delta that was still allocated, and what -- was left unallocated. computeAllocationDelta :: CStats -> CStats -> AllocStats computeAllocationDelta cini cfin = let CStats {csImem = i_imem, csIdsk = i_idsk, csIcpu = i_icpu, csNcpu = i_ncpu, csIspn = i_ispn } = cini CStats {csImem = f_imem, csIdsk = f_idsk, csIcpu = f_icpu, csTmem = t_mem, csTdsk = t_dsk, csVcpu = f_vcpu, csNcpu = f_ncpu, csTcpu = f_tcpu, csIspn = f_ispn, csTspn = t_spn } = cfin rini = AllocInfo { allocInfoVCpus = fromIntegral i_icpu , allocInfoNCpus = i_ncpu , allocInfoMem = fromIntegral i_imem , allocInfoDisk = fromIntegral i_idsk , allocInfoSpn = fromIntegral i_ispn } rfin = AllocInfo { allocInfoVCpus = fromIntegral (f_icpu - i_icpu) , allocInfoNCpus = f_ncpu - i_ncpu , allocInfoMem = fromIntegral (f_imem - i_imem) , allocInfoDisk = fromIntegral (f_idsk - i_idsk) , allocInfoSpn = fromIntegral (f_ispn - i_ispn) } runa = AllocInfo { allocInfoVCpus = fromIntegral (f_vcpu - f_icpu) , allocInfoNCpus = f_tcpu - f_ncpu , allocInfoMem = truncate t_mem - fromIntegral f_imem , allocInfoDisk = truncate t_dsk - fromIntegral f_idsk , allocInfoSpn = truncate t_spn - fromIntegral f_ispn } in (rini, rfin, runa) -- | The names and weights of the individual elements in the CV list. detailedCVInfo :: [(Double, String)] detailedCVInfo = [ (1, "free_mem_cv") , (1, "free_disk_cv") , (1, "n1_cnt") , (1, "reserved_mem_cv") , (4, "offline_all_cnt") , (16, "offline_pri_cnt") , (1, "vcpu_ratio_cv") , (1, "cpu_load_cv") , (1, "mem_load_cv") , (1, "disk_load_cv") , (1, "net_load_cv") , (2, "pri_tags_score") , (1, "spindles_cv") ] -- | Holds the weights used by 'compCVNodes' for each metric. detailedCVWeights :: [Double] detailedCVWeights = map fst detailedCVInfo -- | Compute the mem and disk covariance. compDetailedCV :: [Node.Node] -> [Double] compDetailedCV all_nodes = let (offline, nodes) = partition Node.offline all_nodes mem_l = map Node.pMem nodes dsk_l = map Node.pDsk nodes -- metric: memory covariance mem_cv = stdDev mem_l -- metric: disk covariance dsk_cv = stdDev dsk_l -- metric: count of instances living on N1 failing nodes n1_score = fromIntegral . sum . map (\n -> length (Node.sList n) + length (Node.pList n)) . filter Node.failN1 $ nodes :: Double res_l = map Node.pRem nodes -- metric: reserved memory covariance res_cv = stdDev res_l -- offline instances metrics offline_ipri = sum . map (length . Node.pList) $ offline offline_isec = sum . map (length . Node.sList) $ offline -- metric: count of instances on offline nodes off_score = fromIntegral (offline_ipri + offline_isec)::Double -- metric: count of primary instances on offline nodes (this -- helps with evacuation/failover of primary instances on -- 2-node clusters with one node offline) off_pri_score = fromIntegral offline_ipri::Double cpu_l = map Node.pCpu nodes -- metric: covariance of vcpu/pcpu ratio cpu_cv = stdDev cpu_l -- metrics: covariance of cpu, memory, disk and network load (c_load, m_load, d_load, n_load) = unzip4 $ map (\n -> let DynUtil c1 m1 d1 n1 = Node.utilLoad n DynUtil c2 m2 d2 n2 = Node.utilPool n in (c1/c2, m1/m2, d1/d2, n1/n2)) nodes -- metric: conflicting instance count pri_tags_inst = sum $ map Node.conflictingPrimaries nodes pri_tags_score = fromIntegral pri_tags_inst::Double -- metric: spindles % spindles_cv = map (\n -> Node.instSpindles n / Node.hiSpindles n) nodes in [ mem_cv, dsk_cv, n1_score, res_cv, off_score, off_pri_score, cpu_cv , stdDev c_load, stdDev m_load , stdDev d_load, stdDev n_load , pri_tags_score, stdDev spindles_cv ] -- | Compute the /total/ variance. compCVNodes :: [Node.Node] -> Double compCVNodes = sum . zipWith (*) detailedCVWeights . compDetailedCV -- | Wrapper over 'compCVNodes' for callers that have a 'Node.List'. compCV :: Node.List -> Double compCV = compCVNodes . Container.elems -- | Compute online nodes from a 'Node.List'. getOnline :: Node.List -> [Node.Node] getOnline = filter (not . Node.offline) . Container.elems -- * Balancing functions -- | Compute best table. Note that the ordering of the arguments is important. compareTables :: Table -> Table -> Table compareTables a@(Table _ _ a_cv _) b@(Table _ _ b_cv _ ) = if a_cv > b_cv then b else a -- | Applies an instance move to a given node list and instance. applyMove :: Node.List -> Instance.Instance -> IMove -> OpResult (Node.List, Instance.Instance, Ndx, Ndx) -- Failover (f) applyMove nl inst Failover = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst new_nl = do -- Maybe monad new_p <- Node.addPriEx (Node.offline old_p) int_s inst new_s <- Node.addSec int_p inst old_sdx let new_inst = Instance.setBoth inst old_sdx old_pdx return (Container.addTwo old_pdx new_s old_sdx new_p nl, new_inst, old_sdx, old_pdx) in new_nl -- Failover to any (fa) applyMove nl inst (FailoverToAny new_pdx) = do let (old_pdx, old_sdx, old_pnode, _) = instanceNodes nl inst new_pnode = Container.find new_pdx nl force_failover = Node.offline old_pnode new_pnode' <- Node.addPriEx force_failover new_pnode inst let old_pnode' = Node.removePri old_pnode inst inst' = Instance.setPri inst new_pdx nl' = Container.addTwo old_pdx old_pnode' new_pdx new_pnode' nl return (nl', inst', new_pdx, old_sdx) -- Replace the primary (f:, r:np, f) applyMove nl inst (ReplacePrimary new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p new_nl = do -- Maybe monad -- check that the current secondary can host the instance -- during the migration tmp_s <- Node.addPriEx force_p int_s inst let tmp_s' = Node.removePri tmp_s inst new_p <- Node.addPriEx force_p tgt_n inst new_s <- Node.addSecEx force_p tmp_s' inst new_pdx let new_inst = Instance.setPri inst new_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx int_p old_sdx new_s nl, new_inst, new_pdx, old_sdx) in new_nl -- Replace the secondary (r:ns) applyMove nl inst (ReplaceSecondary new_sdx) = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_s = Container.find old_sdx nl tgt_n = Container.find new_sdx nl int_s = Node.removeSec old_s inst force_s = Node.offline old_s new_inst = Instance.setSec inst new_sdx new_nl = Node.addSecEx force_s tgt_n inst old_pdx >>= \new_s -> return (Container.addTwo new_sdx new_s old_sdx int_s nl, new_inst, old_pdx, new_sdx) in new_nl -- Replace the secondary and failover (r:np, f) applyMove nl inst (ReplaceAndFailover new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_s = Node.offline old_s new_nl = do -- Maybe monad new_p <- Node.addPri tgt_n inst new_s <- Node.addSecEx force_s int_p inst new_pdx let new_inst = Instance.setBoth inst new_pdx old_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx new_s old_sdx int_s nl, new_inst, new_pdx, old_pdx) in new_nl -- Failver and replace the secondary (f, r:ns) applyMove nl inst (FailoverAndReplace new_sdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_sdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p new_nl = do -- Maybe monad new_p <- Node.addPriEx force_p int_s inst new_s <- Node.addSecEx force_p tgt_n inst old_sdx let new_inst = Instance.setBoth inst old_sdx new_sdx return (Container.add new_sdx new_s $ Container.addTwo old_sdx new_p old_pdx int_p nl, new_inst, old_sdx, new_sdx) in new_nl -- | Tries to allocate an instance on one given node. allocateOnSingle :: Node.List -> Instance.Instance -> Ndx -> OpResult Node.AllocElement allocateOnSingle nl inst new_pdx = let p = Container.find new_pdx nl new_inst = Instance.setBoth inst new_pdx Node.noSecondary in do Instance.instMatchesPolicy inst (Node.iPolicy p) (Node.exclStorage p) new_p <- Node.addPri p inst let new_nl = Container.add new_pdx new_p nl new_score = compCV new_nl return (new_nl, new_inst, [new_p], new_score) -- | Tries to allocate an instance on a given pair of nodes. allocateOnPair :: Node.List -> Instance.Instance -> Ndx -> Ndx -> OpResult Node.AllocElement allocateOnPair nl inst new_pdx new_sdx = let tgt_p = Container.find new_pdx nl tgt_s = Container.find new_sdx nl in do Instance.instMatchesPolicy inst (Node.iPolicy tgt_p) (Node.exclStorage tgt_p) new_p <- Node.addPri tgt_p inst new_s <- Node.addSec tgt_s inst new_pdx let new_inst = Instance.setBoth inst new_pdx new_sdx new_nl = Container.addTwo new_pdx new_p new_sdx new_s nl return (new_nl, new_inst, [new_p, new_s], compCV new_nl) -- | Tries to perform an instance move and returns the best table -- between the original one and the new one. checkSingleStep :: Table -- ^ The original table -> Instance.Instance -- ^ The instance to move -> Table -- ^ The current best table -> IMove -- ^ The move to apply -> Table -- ^ The final best table checkSingleStep ini_tbl target cur_tbl move = let Table ini_nl ini_il _ ini_plc = ini_tbl tmp_resu = applyMove ini_nl target move in case tmp_resu of Bad _ -> cur_tbl Ok (upd_nl, new_inst, pri_idx, sec_idx) -> let tgt_idx = Instance.idx target upd_cvar = compCV upd_nl upd_il = Container.add tgt_idx new_inst ini_il upd_plc = (tgt_idx, pri_idx, sec_idx, move, upd_cvar):ini_plc upd_tbl = Table upd_nl upd_il upd_cvar upd_plc in compareTables cur_tbl upd_tbl -- | Given the status of the current secondary as a valid new node and -- the current candidate target node, generate the possible moves for -- a instance. possibleMoves :: MirrorType -- ^ The mirroring type of the instance -> Bool -- ^ Whether the secondary node is a valid new node -> Bool -- ^ Whether we can change the primary node -> Ndx -- ^ Target node candidate -> [IMove] -- ^ List of valid result moves possibleMoves MirrorNone _ _ _ = [] possibleMoves MirrorExternal _ False _ = [] possibleMoves MirrorExternal _ True tdx = [ FailoverToAny tdx ] possibleMoves MirrorInternal _ False tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal True True tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , ReplacePrimary tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal False True tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx ] -- | Compute the best move for a given instance. checkInstanceMove :: [Ndx] -- ^ Allowed target node indices -> Bool -- ^ Whether disk moves are allowed -> Bool -- ^ Whether instance moves are allowed -> Table -- ^ Original table -> Instance.Instance -- ^ Instance to move -> Table -- ^ Best new table for this instance checkInstanceMove nodes_idx disk_moves inst_moves ini_tbl target = let opdx = Instance.pNode target osdx = Instance.sNode target bad_nodes = [opdx, osdx] nodes = filter (`notElem` bad_nodes) nodes_idx mir_type = Instance.mirrorType target use_secondary = elem osdx nodes_idx && inst_moves aft_failover = if mir_type == MirrorInternal && use_secondary -- if drbd and allowed to failover then checkSingleStep ini_tbl target ini_tbl Failover else ini_tbl all_moves = if disk_moves then concatMap (possibleMoves mir_type use_secondary inst_moves) nodes else [] in -- iterate over the possible nodes for this instance foldl' (checkSingleStep ini_tbl target) aft_failover all_moves -- | Compute the best next move. checkMove :: [Ndx] -- ^ Allowed target node indices -> Bool -- ^ Whether disk moves are allowed -> Bool -- ^ Whether instance moves are allowed -> Table -- ^ The current solution -> [Instance.Instance] -- ^ List of instances still to move -> Table -- ^ The new solution checkMove nodes_idx disk_moves inst_moves ini_tbl victims = let Table _ _ _ ini_plc = ini_tbl -- we're using rwhnf from the Control.Parallel.Strategies -- package; we don't need to use rnf as that would force too -- much evaluation in single-threaded cases, and in -- multi-threaded case the weak head normal form is enough to -- spark the evaluation tables = parMap rwhnf (checkInstanceMove nodes_idx disk_moves inst_moves ini_tbl) victims -- iterate over all instances, computing the best move best_tbl = foldl' compareTables ini_tbl tables Table _ _ _ best_plc = best_tbl in if length best_plc == length ini_plc then ini_tbl -- no advancement else best_tbl -- | Check if we are allowed to go deeper in the balancing. doNextBalance :: Table -- ^ The starting table -> Int -- ^ Remaining length -> Score -- ^ Score at which to stop -> Bool -- ^ The resulting table and commands doNextBalance ini_tbl max_rounds min_score = let Table _ _ ini_cv ini_plc = ini_tbl ini_plc_len = length ini_plc in (max_rounds < 0 || ini_plc_len < max_rounds) && ini_cv > min_score -- | Run a balance move. tryBalance :: Table -- ^ The starting table -> Bool -- ^ Allow disk moves -> Bool -- ^ Allow instance moves -> Bool -- ^ Only evacuate moves -> Score -- ^ Min gain threshold -> Score -- ^ Min gain -> Maybe Table -- ^ The resulting table and commands tryBalance ini_tbl disk_moves inst_moves evac_mode mg_limit min_gain = let Table ini_nl ini_il ini_cv _ = ini_tbl all_inst = Container.elems ini_il all_nodes = Container.elems ini_nl (offline_nodes, online_nodes) = partition Node.offline all_nodes all_inst' = if evac_mode then let bad_nodes = map Node.idx offline_nodes in filter (any (`elem` bad_nodes) . Instance.allNodes) all_inst else all_inst reloc_inst = filter (\i -> Instance.movable i && Instance.autoBalance i) all_inst' node_idx = map Node.idx online_nodes fin_tbl = checkMove node_idx disk_moves inst_moves ini_tbl reloc_inst (Table _ _ fin_cv _) = fin_tbl in if fin_cv < ini_cv && (ini_cv > mg_limit || ini_cv - fin_cv >= min_gain) then Just fin_tbl -- this round made success, return the new table else Nothing -- * Allocation functions -- | Build failure stats out of a list of failures. collapseFailures :: [FailMode] -> FailStats collapseFailures flst = map (\k -> (k, foldl' (\a e -> if e == k then a + 1 else a) 0 flst)) [minBound..maxBound] -- | Compares two Maybe AllocElement and chooses the best score. bestAllocElement :: Maybe Node.AllocElement -> Maybe Node.AllocElement -> Maybe Node.AllocElement bestAllocElement a Nothing = a bestAllocElement Nothing b = b bestAllocElement a@(Just (_, _, _, ascore)) b@(Just (_, _, _, bscore)) = if ascore < bscore then a else b -- | Update current Allocation solution and failure stats with new -- elements. concatAllocs :: AllocSolution -> OpResult Node.AllocElement -> AllocSolution concatAllocs as (Bad reason) = as { asFailures = reason : asFailures as } concatAllocs as (Ok ns) = let -- Choose the old or new solution, based on the cluster score cntok = asAllocs as osols = asSolution as nsols = bestAllocElement osols (Just ns) nsuc = cntok + 1 -- Note: we force evaluation of nsols here in order to keep the -- memory profile low - we know that we will need nsols for sure -- in the next cycle, so we force evaluation of nsols, since the -- foldl' in the caller will only evaluate the tuple, but not the -- elements of the tuple in nsols `seq` nsuc `seq` as { asAllocs = nsuc, asSolution = nsols } -- | Sums two 'AllocSolution' structures. sumAllocs :: AllocSolution -> AllocSolution -> AllocSolution sumAllocs (AllocSolution aFails aAllocs aSols aLog) (AllocSolution bFails bAllocs bSols bLog) = -- note: we add b first, since usually it will be smaller; when -- fold'ing, a will grow and grow whereas b is the per-group -- result, hence smaller let nFails = bFails ++ aFails nAllocs = aAllocs + bAllocs nSols = bestAllocElement aSols bSols nLog = bLog ++ aLog in AllocSolution nFails nAllocs nSols nLog -- | Given a solution, generates a reasonable description for it. describeSolution :: AllocSolution -> String describeSolution as = let fcnt = asFailures as sols = asSolution as freasons = intercalate ", " . map (\(a, b) -> printf "%s: %d" (show a) b) . filter ((> 0) . snd) . collapseFailures $ fcnt in case sols of Nothing -> "No valid allocation solutions, failure reasons: " ++ (if null fcnt then "unknown reasons" else freasons) Just (_, _, nodes, cv) -> printf ("score: %.8f, successes %d, failures %d (%s)" ++ " for node(s) %s") cv (asAllocs as) (length fcnt) freasons (intercalate "/" . map Node.name $ nodes) -- | Annotates a solution with the appropriate string. annotateSolution :: AllocSolution -> AllocSolution annotateSolution as = as { asLog = describeSolution as : asLog as } -- | Reverses an evacuation solution. -- -- Rationale: we always concat the results to the top of the lists, so -- for proper jobset execution, we should reverse all lists. reverseEvacSolution :: EvacSolution -> EvacSolution reverseEvacSolution (EvacSolution f m o) = EvacSolution (reverse f) (reverse m) (reverse o) -- | Generate the valid node allocation singles or pairs for a new instance. genAllocNodes :: Group.List -- ^ Group list -> Node.List -- ^ The node map -> Int -- ^ The number of nodes required -> Bool -- ^ Whether to drop or not -- unallocable nodes -> Result AllocNodes -- ^ The (monadic) result genAllocNodes gl nl count drop_unalloc = let filter_fn = if drop_unalloc then filter (Group.isAllocable . flip Container.find gl . Node.group) else id all_nodes = filter_fn $ getOnline nl all_pairs = [(Node.idx p, [Node.idx s | s <- all_nodes, Node.idx p /= Node.idx s, Node.group p == Node.group s]) | p <- all_nodes] in case count of 1 -> Ok (Left (map Node.idx all_nodes)) 2 -> Ok (Right (filter (not . null . snd) all_pairs)) _ -> Bad "Unsupported number of nodes, only one or two supported" -- | Try to allocate an instance on the cluster. tryAlloc :: (Monad m) => Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> AllocNodes -- ^ The allocation targets -> m AllocSolution -- ^ Possible solution list tryAlloc _ _ _ (Right []) = fail "Not enough online nodes" tryAlloc nl _ inst (Right ok_pairs) = let psols = parMap rwhnf (\(p, ss) -> foldl' (\cstate -> concatAllocs cstate . allocateOnPair nl inst p) emptyAllocSolution ss) ok_pairs sols = foldl' sumAllocs emptyAllocSolution psols in return $ annotateSolution sols tryAlloc _ _ _ (Left []) = fail "No online nodes" tryAlloc nl _ inst (Left all_nodes) = let sols = foldl' (\cstate -> concatAllocs cstate . allocateOnSingle nl inst ) emptyAllocSolution all_nodes in return $ annotateSolution sols -- | Given a group/result, describe it as a nice (list of) messages. solutionDescription :: (Group.Group, Result AllocSolution) -> [String] solutionDescription (grp, result) = case result of Ok solution -> map (printf "Group %s (%s): %s" gname pol) (asLog solution) Bad message -> [printf "Group %s: error %s" gname message] where gname = Group.name grp pol = allocPolicyToRaw (Group.allocPolicy grp) -- | From a list of possibly bad and possibly empty solutions, filter -- only the groups with a valid result. Note that the result will be -- reversed compared to the original list. filterMGResults :: [(Group.Group, Result AllocSolution)] -> [(Group.Group, AllocSolution)] filterMGResults = foldl' fn [] where unallocable = not . Group.isAllocable fn accu (grp, rasol) = case rasol of Bad _ -> accu Ok sol | isNothing (asSolution sol) -> accu | unallocable grp -> accu | otherwise -> (grp, sol):accu -- | Sort multigroup results based on policy and score. sortMGResults :: [(Group.Group, AllocSolution)] -> [(Group.Group, AllocSolution)] sortMGResults sols = let extractScore (_, _, _, x) = x solScore (grp, sol) = (Group.allocPolicy grp, (extractScore . fromJust . asSolution) sol) in sortBy (comparing solScore) sols -- | Removes node groups which can't accommodate the instance filterValidGroups :: [(Group.Group, (Node.List, Instance.List))] -> Instance.Instance -> ([(Group.Group, (Node.List, Instance.List))], [String]) filterValidGroups [] _ = ([], []) filterValidGroups (ng:ngs) inst = let (valid_ngs, msgs) = filterValidGroups ngs inst hasNetwork nic = case Nic.network nic of Just net -> net `elem` Group.networks (fst ng) Nothing -> True hasRequiredNetworks = all hasNetwork (Instance.nics inst) in if hasRequiredNetworks then (ng:valid_ngs, msgs) else (valid_ngs, ("group " ++ Group.name (fst ng) ++ " is not connected to a network required by instance " ++ Instance.name inst):msgs) -- | Finds the best group for an instance on a multi-group cluster. -- -- Only solutions in @preferred@ and @last_resort@ groups will be -- accepted as valid, and additionally if the allowed groups parameter -- is not null then allocation will only be run for those group -- indices. findBestAllocGroup :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Maybe [Gdx] -- ^ The allowed groups -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result (Group.Group, AllocSolution, [String]) findBestAllocGroup mggl mgnl mgil allowed_gdxs inst cnt = let groups_by_idx = splitCluster mgnl mgil groups = map (\(gid, d) -> (Container.find gid mggl, d)) groups_by_idx groups' = maybe groups (\gs -> filter ((`elem` gs) . Group.idx . fst) groups) allowed_gdxs (groups'', filter_group_msgs) = filterValidGroups groups' inst sols = map (\(gr, (nl, il)) -> (gr, genAllocNodes mggl nl cnt False >>= tryAlloc nl il inst)) groups''::[(Group.Group, Result AllocSolution)] all_msgs = filter_group_msgs ++ concatMap solutionDescription sols goodSols = filterMGResults sols sortedSols = sortMGResults goodSols in case sortedSols of [] -> Bad $ if null groups' then "no groups for evacuation: allowed groups was" ++ show allowed_gdxs ++ ", all groups: " ++ show (map fst groups) else intercalate ", " all_msgs (final_group, final_sol):_ -> return (final_group, final_sol, all_msgs) -- | Try to allocate an instance on a multi-group cluster. tryMGAlloc :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result AllocSolution -- ^ Possible solution list tryMGAlloc mggl mgnl mgil inst cnt = do (best_group, solution, all_msgs) <- findBestAllocGroup mggl mgnl mgil Nothing inst cnt let group_name = Group.name best_group selmsg = "Selected group: " ++ group_name return $ solution { asLog = selmsg:all_msgs } -- | Calculate the new instance list after allocation solution. updateIl :: Instance.List -- ^ The original instance list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Instance.List -- ^ The updated instance list updateIl il Nothing = il updateIl il (Just (_, xi, _, _)) = Container.add (Container.size il) xi il -- | Extract the the new node list from the allocation solution. extractNl :: Node.List -- ^ The original node list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Node.List -- ^ The new node list extractNl nl Nothing = nl extractNl _ (Just (xnl, _, _, _)) = xnl -- | Try to allocate a list of instances on a multi-group cluster. allocList :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> [(Instance.Instance, Int)] -- ^ The instance to allocate -> AllocSolutionList -- ^ Possible solution list -> Result (Node.List, Instance.List, AllocSolutionList) -- ^ The final solution list allocList _ nl il [] result = Ok (nl, il, result) allocList gl nl il ((xi, xicnt):xies) result = do ares <- tryMGAlloc gl nl il xi xicnt let sol = asSolution ares nl' = extractNl nl sol il' = updateIl il sol allocList gl nl' il' xies ((xi, ares):result) -- | Function which fails if the requested mode is change secondary. -- -- This is useful since except DRBD, no other disk template can -- execute change secondary; thus, we can just call this function -- instead of always checking for secondary mode. After the call to -- this function, whatever mode we have is just a primary change. failOnSecondaryChange :: (Monad m) => EvacMode -> DiskTemplate -> m () failOnSecondaryChange ChangeSecondary dt = fail $ "Instances with disk template '" ++ diskTemplateToRaw dt ++ "' can't execute change secondary" failOnSecondaryChange _ _ = return () -- | Run evacuation for a single instance. -- -- /Note:/ this function should correctly execute both intra-group -- evacuations (in all modes) and inter-group evacuations (in the -- 'ChangeAll' mode). Of course, this requires that the correct list -- of target nodes is passed. nodeEvacInstance :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTDiskless}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTPlain}) _ _ = fail "Instances of type plain cannot be relocated" nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTFile}) _ _ = fail "Instances of type file cannot be relocated" nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTSharedFile}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTBlock}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTRbd}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTExt}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il ChangePrimary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) _ _ = do (nl', inst', _, _) <- opToResult $ applyMove nl inst Failover let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx Failover return (nl', il', ops) nodeEvacInstance nl il ChangeSecondary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = evacOneNodeOnly nl il inst gdx avail_nodes -- The algorithm for ChangeAll is as follows: -- -- * generate all (primary, secondary) node pairs for the target groups -- * for each pair, execute the needed moves (r:s, f, r:s) and compute -- the final node list state and group score -- * select the best choice via a foldl that uses the same Either -- String solution as the ChangeSecondary mode nodeEvacInstance nl il ChangeAll inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = do let no_nodes = Left "no nodes available" node_pairs = [(p,s) | p <- avail_nodes, s <- avail_nodes, p /= s] (nl', il', ops, _) <- annotateResult "Can't find any good nodes for relocation" . eitherToResult $ foldl' (\accu nodes -> case evacDrbdAllInner nl il inst gdx nodes of Bad msg -> case accu of Right _ -> accu -- we don't need more details (which -- nodes, etc.) as we only selected -- this group if we can allocate on -- it, hence failures will not -- propagate out of this fold loop Left _ -> Left $ "Allocation failed: " ++ msg Ok result@(_, _, _, new_cv) -> let new_accu = Right result in case accu of Left _ -> new_accu Right (_, _, _, old_cv) -> if old_cv < new_cv then accu else new_accu ) no_nodes node_pairs return (nl', il', ops) -- | Generic function for changing one node of an instance. -- -- This is similar to 'nodeEvacInstance' but will be used in a few of -- its sub-patterns. It folds the inner function 'evacOneNodeInner' -- over the list of available nodes, which results in the best choice -- for relocation. evacOneNodeOnly :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) evacOneNodeOnly nl il inst gdx avail_nodes = do op_fn <- case Instance.mirrorType inst of MirrorNone -> Bad "Can't relocate/evacuate non-mirrored instances" MirrorInternal -> Ok ReplaceSecondary MirrorExternal -> Ok FailoverToAny (nl', inst', _, ndx) <- annotateResult "Can't find any good node" . eitherToResult $ foldl' (evacOneNodeInner nl inst gdx op_fn) (Left "no nodes available") avail_nodes let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx (op_fn ndx) return (nl', il', ops) -- | Inner fold function for changing one node of an instance. -- -- Depending on the instance disk template, this will either change -- the secondary (for DRBD) or the primary node (for shared -- storage). However, the operation is generic otherwise. -- -- The running solution is either a @Left String@, which means we -- don't have yet a working solution, or a @Right (...)@, which -- represents a valid solution; it holds the modified node list, the -- modified instance (after evacuation), the score of that solution, -- and the new secondary node index. evacOneNodeInner :: Node.List -- ^ Cluster node list -> Instance.Instance -- ^ Instance being evacuated -> Gdx -- ^ The group index of the instance -> (Ndx -> IMove) -- ^ Operation constructor -> EvacInnerState -- ^ Current best solution -> Ndx -- ^ Node we're evaluating as target -> EvacInnerState -- ^ New best solution evacOneNodeInner nl inst gdx op_fn accu ndx = case applyMove nl inst (op_fn ndx) of Bad fm -> let fail_msg = "Node " ++ Container.nameOf nl ndx ++ " failed: " ++ show fm in either (const $ Left fail_msg) (const accu) accu Ok (nl', inst', _, _) -> let nodes = Container.elems nl' -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes new_accu = Right (nl', inst', new_cv, ndx) in case accu of Left _ -> new_accu Right (_, _, old_cv, _) -> if old_cv < new_cv then accu else new_accu -- | Compute result of changing all nodes of a DRBD instance. -- -- Given the target primary and secondary node (which might be in a -- different group or not), this function will 'execute' all the -- required steps and assuming all operations succceed, will return -- the modified node and instance lists, the opcodes needed for this -- and the new group score. evacDrbdAllInner :: Node.List -- ^ Cluster node list -> Instance.List -- ^ Cluster instance list -> Instance.Instance -- ^ The instance to be moved -> Gdx -- ^ The target group index -- (which can differ from the -- current group of the -- instance) -> (Ndx, Ndx) -- ^ Tuple of new -- primary\/secondary nodes -> Result (Node.List, Instance.List, [OpCodes.OpCode], Score) evacDrbdAllInner nl il inst gdx (t_pdx, t_sdx) = do let primary = Container.find (Instance.pNode inst) nl idx = Instance.idx inst -- if the primary is offline, then we first failover (nl1, inst1, ops1) <- if Node.offline primary then do (nl', inst', _, _) <- annotateResult "Failing over to the secondary" . opToResult $ applyMove nl inst Failover return (nl', inst', [Failover]) else return (nl, inst, []) let (o1, o2, o3) = (ReplaceSecondary t_pdx, Failover, ReplaceSecondary t_sdx) -- we now need to execute a replace secondary to the future -- primary node (nl2, inst2, _, _) <- annotateResult "Changing secondary to new primary" . opToResult $ applyMove nl1 inst1 o1 let ops2 = o1:ops1 -- we now execute another failover, the primary stays fixed now (nl3, inst3, _, _) <- annotateResult "Failing over to new primary" . opToResult $ applyMove nl2 inst2 o2 let ops3 = o2:ops2 -- and finally another replace secondary, to the final secondary (nl4, inst4, _, _) <- annotateResult "Changing secondary to final secondary" . opToResult $ applyMove nl3 inst3 o3 let ops4 = o3:ops3 il' = Container.add idx inst4 il ops = concatMap (iMoveToJob nl4 il' idx) $ reverse ops4 let nodes = Container.elems nl4 -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes return (nl4, il', ops, new_cv) -- | Computes the nodes in a given group which are available for -- allocation. availableGroupNodes :: [(Gdx, [Ndx])] -- ^ Group index/node index assoc list -> IntSet.IntSet -- ^ Nodes that are excluded -> Gdx -- ^ The group for which we -- query the nodes -> Result [Ndx] -- ^ List of available node indices availableGroupNodes group_nodes excl_ndx gdx = do local_nodes <- maybe (Bad $ "Can't find group with index " ++ show gdx) Ok (lookup gdx group_nodes) let avail_nodes = filter (not . flip IntSet.member excl_ndx) local_nodes return avail_nodes -- | Updates the evac solution with the results of an instance -- evacuation. updateEvacSolution :: (Node.List, Instance.List, EvacSolution) -> Idx -> Result (Node.List, Instance.List, [OpCodes.OpCode]) -> (Node.List, Instance.List, EvacSolution) updateEvacSolution (nl, il, es) idx (Bad msg) = (nl, il, es { esFailed = (idx, msg):esFailed es}) updateEvacSolution (_, _, es) idx (Ok (nl, il, opcodes)) = (nl, il, es { esMoved = new_elem:esMoved es , esOpCodes = opcodes:esOpCodes es }) where inst = Container.find idx il new_elem = (idx, instancePriGroup nl inst, Instance.allNodes inst) -- | Node-evacuation IAllocator mode main function. tryNodeEvac :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide, not per group) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryNodeEvac _ ini_nl ini_il mode idxs = let evac_ndx = nodesToEvacuate ini_il mode idxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) evac_ndx offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let gdx = instancePriGroup nl inst pdx = Instance.pNode inst in updateEvacSolution state (Instance.idx inst) $ availableGroupNodes group_ndx (IntSet.insert pdx excl_ndx) gdx >>= nodeEvacInstance nl il mode inst gdx ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Change-group IAllocator mode main function. -- -- This is very similar to 'tryNodeEvac', the only difference is that -- we don't choose as target group the current instance group, but -- instead: -- -- 1. at the start of the function, we compute which are the target -- groups; either no groups were passed in, in which case we choose -- all groups out of which we don't evacuate instance, or there were -- some groups passed, in which case we use those -- -- 2. for each instance, we use 'findBestAllocGroup' to choose the -- best group to hold the instance, and then we do what -- 'tryNodeEvac' does, except for this group instead of the current -- instance group. -- -- Note that the correct behaviour of this function relies on the -- function 'nodeEvacInstance' to be able to do correctly both -- intra-group and inter-group moves when passed the 'ChangeAll' mode. tryChangeGroup :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> [Gdx] -- ^ Target groups; if empty, any -- groups not being evacuated -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryChangeGroup gl ini_nl ini_il gdxs idxs = let evac_gdxs = nub $ map (instancePriGroup ini_nl . flip Container.find ini_il) idxs target_gdxs = (if null gdxs then Container.keys gl else gdxs) \\ evac_gdxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) IntSet.empty offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let solution = do let ncnt = Instance.requiredNodes $ Instance.diskTemplate inst (grp, _, _) <- findBestAllocGroup gl nl il (Just target_gdxs) inst ncnt let gdx = Group.idx grp av_nodes <- availableGroupNodes group_ndx excl_ndx gdx nodeEvacInstance nl il ChangeAll inst gdx av_nodes in updateEvacSolution state (Instance.idx inst) solution ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Standard-sized allocation method. -- -- This places instances of the same size on the cluster until we're -- out of space. The result will be a list of identically-sized -- instances. iterateAlloc :: AllocMethod iterateAlloc nl il limit newinst allocnodes ixes cstats = let depth = length ixes newname = printf "new-%d" depth::String newidx = Container.size il newi2 = Instance.setIdx (Instance.setName newinst newname) newidx newlimit = fmap (flip (-) 1) limit in case tryAlloc nl il newi2 allocnodes of Bad s -> Bad s Ok (AllocSolution { asFailures = errs, asSolution = sols3 }) -> let newsol = Ok (collapseFailures errs, nl, il, ixes, cstats) in case sols3 of Nothing -> newsol Just (xnl, xi, _, _) -> if limit == Just 0 then newsol else iterateAlloc xnl (Container.add newidx xi il) newlimit newinst allocnodes (xi:ixes) (totalResources xnl:cstats) -- | Predicate whether shrinking a single resource can lead to a valid -- allocation. sufficesShrinking :: (Instance.Instance -> AllocSolution) -> Instance.Instance -> FailMode -> Maybe Instance.Instance sufficesShrinking allocFn inst fm = case dropWhile (isNothing . asSolution . fst) . takeWhile (liftA2 (||) (elem fm . asFailures . fst) (isJust . asSolution . fst)) . map (allocFn &&& id) $ iterateOk (`Instance.shrinkByType` fm) inst of x:_ -> Just . snd $ x _ -> Nothing -- | Tiered allocation method. -- -- This places instances on the cluster, and decreases the spec until -- we can allocate again. The result will be a list of decreasing -- instance specs. tieredAlloc :: AllocMethod tieredAlloc nl il limit newinst allocnodes ixes cstats = case iterateAlloc nl il limit newinst allocnodes ixes cstats of Bad s -> Bad s Ok (errs, nl', il', ixes', cstats') -> let newsol = Ok (errs, nl', il', ixes', cstats') ixes_cnt = length ixes' (stop, newlimit) = case limit of Nothing -> (False, Nothing) Just n -> (n <= ixes_cnt, Just (n - ixes_cnt)) sortedErrs = map fst $ sortBy (comparing snd) errs suffShrink = sufficesShrinking (fromMaybe emptyAllocSolution . flip (tryAlloc nl' il') allocnodes) newinst bigSteps = filter isJust . map suffShrink . reverse $ sortedErrs in if stop then newsol else case bigSteps of Just newinst':_ -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' _ -> case Instance.shrinkByType newinst . last $ sortedErrs of Bad _ -> newsol Ok newinst' -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' -- * Formatting functions -- | Given the original and final nodes, computes the relocation description. computeMoves :: Instance.Instance -- ^ The instance to be moved -> String -- ^ The instance name -> IMove -- ^ The move being performed -> String -- ^ New primary -> String -- ^ New secondary -> (String, [String]) -- ^ Tuple of moves and commands list; moves is containing -- either @/f/@ for failover or @/r:name/@ for replace -- secondary, while the command list holds gnt-instance -- commands (without that prefix), e.g \"@failover instance1@\" computeMoves i inam mv c d = case mv of Failover -> ("f", [mig]) FailoverToAny _ -> (printf "fa:%s" c, [mig_any]) FailoverAndReplace _ -> (printf "f r:%s" d, [mig, rep d]) ReplaceSecondary _ -> (printf "r:%s" d, [rep d]) ReplaceAndFailover _ -> (printf "r:%s f" c, [rep c, mig]) ReplacePrimary _ -> (printf "f r:%s f" c, [mig, rep c, mig]) where morf = if Instance.isRunning i then "migrate" else "failover" mig = printf "%s -f %s" morf inam::String mig_any = printf "%s -f -n %s %s" morf c inam::String rep n = printf "replace-disks -n %s %s" n inam::String -- | Converts a placement to string format. printSolutionLine :: Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Int -- ^ Maximum node name length -> Int -- ^ Maximum instance name length -> Placement -- ^ The current placement -> Int -- ^ The index of the placement in -- the solution -> (String, [String]) printSolutionLine nl il nmlen imlen plc pos = let pmlen = (2*nmlen + 1) (i, p, s, mv, c) = plc old_sec = Instance.sNode inst inst = Container.find i il inam = Instance.alias inst npri = Node.alias $ Container.find p nl nsec = Node.alias $ Container.find s nl opri = Node.alias $ Container.find (Instance.pNode inst) nl osec = Node.alias $ Container.find old_sec nl (moves, cmds) = computeMoves inst inam mv npri nsec -- FIXME: this should check instead/also the disk template ostr = if old_sec == Node.noSecondary then printf "%s" opri::String else printf "%s:%s" opri osec::String nstr = if s == Node.noSecondary then printf "%s" npri::String else printf "%s:%s" npri nsec::String in (printf " %3d. %-*s %-*s => %-*s %12.8f a=%s" pos imlen inam pmlen ostr pmlen nstr c moves, cmds) -- | Return the instance and involved nodes in an instance move. -- -- Note that the output list length can vary, and is not required nor -- guaranteed to be of any specific length. involvedNodes :: Instance.List -- ^ Instance list, used for retrieving -- the instance from its index; note -- that this /must/ be the original -- instance list, so that we can -- retrieve the old nodes -> Placement -- ^ The placement we're investigating, -- containing the new nodes and -- instance index -> [Ndx] -- ^ Resulting list of node indices involvedNodes il plc = let (i, np, ns, _, _) = plc inst = Container.find i il in nub $ [np, ns] ++ Instance.allNodes inst -- | Inner function for splitJobs, that either appends the next job to -- the current jobset, or starts a new jobset. mergeJobs :: ([JobSet], [Ndx]) -> MoveJob -> ([JobSet], [Ndx]) mergeJobs ([], _) n@(ndx, _, _, _) = ([[n]], ndx) mergeJobs (cjs@(j:js), nbuf) n@(ndx, _, _, _) | null (ndx `intersect` nbuf) = ((n:j):js, ndx ++ nbuf) | otherwise = ([n]:cjs, ndx) -- | Break a list of moves into independent groups. Note that this -- will reverse the order of jobs. splitJobs :: [MoveJob] -> [JobSet] splitJobs = fst . foldl mergeJobs ([], []) -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatJob :: Int -> Int -> (Int, MoveJob) -> [String] formatJob jsn jsl (sn, (_, _, _, cmds)) = let out = printf " echo job %d/%d" jsn sn: printf " check": map (" gnt-instance " ++) cmds in if sn == 1 then ["", printf "echo jobset %d, %d jobs" jsn jsl] ++ out else out -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatCmds :: [JobSet] -> String formatCmds = unlines . concatMap (\(jsn, js) -> concatMap (formatJob jsn (length js)) (zip [1..] js)) . zip [1..] -- | Print the node list. printNodes :: Node.List -> [String] -> String printNodes nl fs = let fields = case fs of [] -> Node.defaultFields "+":rest -> Node.defaultFields ++ rest _ -> fs snl = sortBy (comparing Node.idx) (Container.elems nl) (header, isnum) = unzip $ map Node.showHeader fields in printTable "" header (map (Node.list fields) snl) isnum -- | Print the instance list. printInsts :: Node.List -> Instance.List -> String printInsts nl il = let sil = sortBy (comparing Instance.idx) (Container.elems il) helper inst = [ if Instance.isRunning inst then "R" else " " , Instance.name inst , Container.nameOf nl (Instance.pNode inst) , let sdx = Instance.sNode inst in if sdx == Node.noSecondary then "" else Container.nameOf nl sdx , if Instance.autoBalance inst then "Y" else "N" , printf "%3d" $ Instance.vcpus inst , printf "%5d" $ Instance.mem inst , printf "%5d" $ Instance.dsk inst `div` 1024 , printf "%5.3f" lC , printf "%5.3f" lM , printf "%5.3f" lD , printf "%5.3f" lN ] where DynUtil lC lM lD lN = Instance.util inst header = [ "F", "Name", "Pri_node", "Sec_node", "Auto_bal" , "vcpu", "mem" , "dsk", "lCpu", "lMem", "lDsk", "lNet" ] isnum = False:False:False:False:False:repeat True in printTable "" header (map helper sil) isnum -- | Shows statistics for a given node list. printStats :: String -> Node.List -> String printStats lp nl = let dcvs = compDetailedCV $ Container.elems nl (weights, names) = unzip detailedCVInfo hd = zip3 (weights ++ repeat 1) (names ++ repeat "unknown") dcvs header = [ "Field", "Value", "Weight" ] formatted = map (\(w, h, val) -> [ h , printf "%.8f" val , printf "x%.2f" w ]) hd in printTable lp header formatted $ False:repeat True -- | Convert a placement into a list of OpCodes (basically a job). iMoveToJob :: Node.List -- ^ The node list; only used for node -- names, so any version is good -- (before or after the operation) -> Instance.List -- ^ The instance list; also used for -- names only -> Idx -- ^ The index of the instance being -- moved -> IMove -- ^ The actual move to be described -> [OpCodes.OpCode] -- ^ The list of opcodes equivalent to -- the given move iMoveToJob nl il idx move = let inst = Container.find idx il iname = Instance.name inst lookNode n = case mkNonEmpty (Container.nameOf nl n) of -- FIXME: convert htools codebase to non-empty strings Bad msg -> error $ "Empty node name for idx " ++ show n ++ ": " ++ msg ++ "??" Ok ne -> Just ne opF = OpCodes.OpInstanceMigrate { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opMigrationMode = Nothing -- default , OpCodes.opOldLiveMode = Nothing -- default as well , OpCodes.opTargetNode = Nothing -- this is drbd , OpCodes.opTargetNodeUuid = Nothing , OpCodes.opAllowRuntimeChanges = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opMigrationCleanup = False , OpCodes.opIallocator = Nothing , OpCodes.opAllowFailover = True } opFA n = opF { OpCodes.opTargetNode = lookNode n } -- not drbd opR n = OpCodes.OpInstanceReplaceDisks { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opEarlyRelease = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opReplaceDisksMode = OpCodes.ReplaceNewSecondary , OpCodes.opReplaceDisksList = [] , OpCodes.opRemoteNode = lookNode n , OpCodes.opRemoteNodeUuid = Nothing , OpCodes.opIallocator = Nothing } in case move of Failover -> [ opF ] FailoverToAny np -> [ opFA np ] ReplacePrimary np -> [ opF, opR np, opF ] ReplaceSecondary ns -> [ opR ns ] ReplaceAndFailover np -> [ opR np, opF ] FailoverAndReplace ns -> [ opF, opR ns ] -- * Node group functions -- | Computes the group of an instance. instanceGroup :: Node.List -> Instance.Instance -> Result Gdx instanceGroup nl i = let sidx = Instance.sNode i pnode = Container.find (Instance.pNode i) nl snode = if sidx == Node.noSecondary then pnode else Container.find sidx nl pgroup = Node.group pnode sgroup = Node.group snode in if pgroup /= sgroup then fail ("Instance placed accross two node groups, primary " ++ show pgroup ++ ", secondary " ++ show sgroup) else return pgroup -- | Computes the group of an instance per the primary node. instancePriGroup :: Node.List -> Instance.Instance -> Gdx instancePriGroup nl i = let pnode = Container.find (Instance.pNode i) nl in Node.group pnode -- | Compute the list of badly allocated instances (split across node -- groups). findSplitInstances :: Node.List -> Instance.List -> [Instance.Instance] findSplitInstances nl = filter (not . isOk . instanceGroup nl) . Container.elems -- | Splits a cluster into the component node groups. splitCluster :: Node.List -> Instance.List -> [(Gdx, (Node.List, Instance.List))] splitCluster nl il = let ngroups = Node.computeGroups (Container.elems nl) in map (\(gdx, nodes) -> let nidxs = map Node.idx nodes nodes' = zip nidxs nodes instances = Container.filter ((`elem` nidxs) . Instance.pNode) il in (gdx, (Container.fromList nodes', instances))) ngroups -- | Compute the list of nodes that are to be evacuated, given a list -- of instances and an evacuation mode. nodesToEvacuate :: Instance.List -- ^ The cluster-wide instance list -> EvacMode -- ^ The evacuation mode we're using -> [Idx] -- ^ List of instance indices being evacuated -> IntSet.IntSet -- ^ Set of node indices nodesToEvacuate il mode = IntSet.delete Node.noSecondary . foldl' (\ns idx -> let i = Container.find idx il pdx = Instance.pNode i sdx = Instance.sNode i dt = Instance.diskTemplate i withSecondary = case dt of DTDrbd8 -> IntSet.insert sdx ns _ -> ns in case mode of ChangePrimary -> IntSet.insert pdx ns ChangeSecondary -> withSecondary ChangeAll -> IntSet.insert pdx withSecondary ) IntSet.empty
narurien/ganeti-ceph
src/Ganeti/HTools/Cluster.hs
gpl-2.0
71,896
0
23
22,734
15,489
8,392
7,097
1,166
7
-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca) -- Released under the GNU GPL, see LICENSE {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances, ViewPatterns #-} module Graphics.Implicit.ObjectUtil.GetImplicit3 (getImplicit3) where import Prelude hiding (round) import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, (⋯/), Obj3, SymbolicObj3(Shell3, UnionR3, IntersectR3, DifferenceR3, Translate3, Scale3, Rotate3, Outset3, Rect3R, Sphere, Cylinder, Complement3, EmbedBoxedObj3, Rotate3V, ExtrudeR, ExtrudeRM, ExtrudeOnEdgeOf, RotateExtrude)) import qualified Graphics.Implicit.MathUtil as MathUtil (rmaximum, rminimum, rmax) import qualified Data.Maybe as Maybe import qualified Data.Either as Either import Data.VectorSpace import Data.Cross (cross3) import Graphics.Implicit.ObjectUtil.GetImplicit2 (getImplicit2) getImplicit3 :: SymbolicObj3 -> Obj3 -- Primitives getImplicit3 (Rect3R r (x1,y1,z1) (x2,y2,z2)) = \(x,y,z) -> MathUtil.rmaximum r [abs (x-dx/2-x1) - dx/2, abs (y-dy/2-y1) - dy/2, abs (z-dz/2-z1) - dz/2] where (dx, dy, dz) = (x2-x1, y2-y1, z2-z1) getImplicit3 (Sphere r ) = \(x,y,z) -> sqrt (x**2 + y**2 + z**2) - r getImplicit3 (Cylinder h r1 r2) = \(x,y,z) -> let d = sqrt(x^2+y^2) - ((r2-r1)/h*z+r1) θ = atan2 (r2-r1) h in max (d * cos θ) (abs(z-h/(2::ℝ)) - h/(2::ℝ)) -- (Rounded) CSG getImplicit3 (Complement3 symbObj) = let obj = getImplicit3 symbObj in \p -> - obj p getImplicit3 (UnionR3 r symbObjs) = let objs = map getImplicit3 symbObjs in if r == 0 then \p -> minimum $ map ($p) objs else \p -> MathUtil.rminimum r $ map ($p) objs getImplicit3 (IntersectR3 r symbObjs) = let objs = map getImplicit3 symbObjs in if r == 0 then \p -> maximum $ map ($p) objs else \p -> MathUtil.rmaximum r $ map ($p) objs getImplicit3 (DifferenceR3 r symbObjs) = let obj:objs = map getImplicit3 symbObjs complement obj = \p -> - obj p in if r == 0 then \p -> maximum $ map ($p) $ obj:(map complement objs) else \p -> MathUtil.rmaximum r $ map ($p) $ obj:(map complement objs) -- Simple transforms getImplicit3 (Translate3 v symbObj) = let obj = getImplicit3 symbObj in \p -> obj (p ^-^ v) getImplicit3 (Scale3 s@(sx,sy,sz) symbObj) = let obj = getImplicit3 symbObj k = (sx*sy*sz)**(1/3) in \p -> k * obj (p ⋯/ s) getImplicit3 (Rotate3 (yz, zx, xy) symbObj) = let obj = getImplicit3 symbObj rotateYZ :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ) rotateYZ θ obj = \(x,y,z) -> obj ( x, cos(θ)*y + sin(θ)*z, cos(θ)*z - sin(θ)*y) rotateZX :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ) rotateZX θ obj = \(x,y,z) -> obj ( cos(θ)*x - sin(θ)*z, y, cos(θ)*z + sin(θ)*x) rotateXY :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ) rotateXY θ obj = \(x,y,z) -> obj ( cos(θ)*x + sin(θ)*y, cos(θ)*y - sin(θ)*x, z) in rotateYZ yz $ rotateZX zx $ rotateXY xy $ obj getImplicit3 (Rotate3V θ axis symbObj) = let axis' = normalized axis obj = getImplicit3 symbObj in \v -> obj $ v ^* cos(θ) ^-^ (axis' `cross3` v) ^* sin(θ) ^+^ (axis' ^* (axis' <.> (v ^* (1 - cos(θ))))) -- Boundary mods getImplicit3 (Shell3 w symbObj) = let obj = getImplicit3 symbObj in \p -> abs (obj p) - w/2 getImplicit3 (Outset3 d symbObj) = let obj = getImplicit3 symbObj in \p -> obj p - d -- Misc getImplicit3 (EmbedBoxedObj3 (obj,_)) = obj -- 2D Based getImplicit3 (ExtrudeR r symbObj h) = let obj = getImplicit2 symbObj in \(x,y,z) -> MathUtil.rmax r (obj (x,y)) (abs (z - h/2) - h/2) getImplicit3 (ExtrudeRM r twist scale translate symbObj height) = let obj = getImplicit2 symbObj twist' = Maybe.fromMaybe (const 0) twist scale' = Maybe.fromMaybe (const 1) scale translate' = Maybe.fromMaybe (const (0,0)) translate height' (x,y) = case height of Left n -> n Right f -> f (x,y) scaleVec :: ℝ -> ℝ2 -> ℝ2 scaleVec s = \(x,y) -> (x/s, y/s) rotateVec :: ℝ -> ℝ2 -> ℝ2 rotateVec θ (x,y) = (x*cos(θ)+y*sin(θ), y*cos(θ)-x*sin(θ)) k = (pi :: ℝ)/(180:: ℝ) in \(x,y,z) -> let h = height' (x,y) in MathUtil.rmax r (obj . rotateVec (-k*twist' z) . scaleVec (scale' z) . (\a -> a ^-^ translate' z) $ (x,y)) (abs (z - h/2) - h/2) getImplicit3 (ExtrudeOnEdgeOf symbObj1 symbObj2) = let obj1 = getImplicit2 symbObj1 obj2 = getImplicit2 symbObj2 in \(x,y,z) -> obj1 (obj2 (x,y), z) getImplicit3 (RotateExtrude totalRotation round translate rotate symbObj) = let tau = 2 * pi k = tau / 360 totalRotation' = totalRotation*k obj = getImplicit2 symbObj capped = Maybe.isJust round round' = Maybe.fromMaybe 0 round translate' :: ℝ -> ℝ2 translate' = Either.either (\(a,b) -> \θ -> (a*θ/totalRotation', b*θ/totalRotation')) (. (/k)) translate rotate' :: ℝ -> ℝ rotate' = Either.either (\t -> \θ -> t*θ/totalRotation' ) (. (/k)) rotate twists = case rotate of Left 0 -> True _ -> False in \(x,y,z) -> minimum $ do let r = sqrt (x^2 + y^2) θ = atan2 y x ns :: [Int] ns = if capped then -- we will cap a different way, but want leeway to keep the function cont [-1 .. (ceiling (totalRotation' / tau) :: Int) + (1 :: Int)] else [0 .. floor $ (totalRotation' - θ) /tau] n <- ns let θvirt = fromIntegral n * tau + θ (rshift, zshift) = translate' θvirt twist = rotate' θvirt rz_pos = if twists then let (c,s) = (cos(twist*k), sin(twist*k)) (r',z') = (r-rshift, z-zshift) in (c*r' - s*z', c*z' + s*r') else (r - rshift, z - zshift) return $ if capped then MathUtil.rmax round' (abs (θvirt - (totalRotation' / 2)) - (totalRotation' / 2)) (obj rz_pos) else obj rz_pos
silky/ImplicitCAD
Graphics/Implicit/ObjectUtil/GetImplicit3.hs
gpl-2.0
7,124
2
22
2,560
2,860
1,546
1,314
157
9
-- | Some shared utilites. module Shared ( breakAround , firstTrue , ErrorOr, forceError , asHex , Hash(..), emptyHash, hashAsHex , isHashString , fromHex , splitMSB , strictifyBS, makeBS , trace ) where import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Control.Monad.Error import Data.Bits import Data.Char import Data.Word import Debug.Trace -- | An alias for @Either String a@, for things that may fail with a String. type ErrorOr a = Either String a -- | Force an ErrorOr to either a monad failure or the ok value. forceError :: (MonadIO m) => ErrorOr a -> m a forceError (Left err) = fail err forceError (Right ok) = return ok -- | A SHA-1 hash. newtype Hash = Hash B.ByteString deriving Eq instance Show Hash where show (Hash bs) = "[Hash " ++ asHex bs ++ "]" -- | Special magic value for "none such file". emptyHash :: Hash emptyHash = Hash $ B.pack (replicate 20 0) -- | Dump a ByteString as a String of hexidecimal characters. asHex :: B.ByteString -> String asHex str = foldr hex "" $ B.unpack str where hex :: Word8 -> String -> String hex c rest = hexNybble (c `shiftR` 4) : hexNybble (c .&. 0xF) : rest hexNybble :: Word8 -> Char hexNybble c = ("0123456789abcdef" !! fromIntegral c) -- | Parse a string of hex into a ByteString. fromHex :: String -> B.ByteString fromHex = B.pack . bytes where bytes (x1:x2:rest) = parseHex x1 x2 : bytes rest bytes [] = [] parseHex x1 x2 = fromIntegral (digitToInt x1 * 16 + digitToInt x2) -- | A hash as a hex string. hashAsHex :: Hash -> String hashAsHex (Hash bs) = asHex bs -- | Test whether a string looks like a hash (40 chars long, all hex). isHashString :: String -> Bool isHashString str = length str == 40 && all isHexDigit str -- |Like @break@, but drops the matched item. breakAround :: Eq a => (a -> Bool) -> [a] -> ([a], [a]) breakAround pred list = (before, after) where (before, rest) = break pred list after = case rest of (x:xs) | pred x -> xs _ -> after -- |firstTrue takes a list of things to do and gives you back the first one -- that produces a result. (XXX this is probably the composition of some -- other monadic operators -- which?) firstTrue :: Monad m => [m (Maybe a)] -> m (Maybe a) firstTrue [] = return Nothing firstTrue (x:xs) = do test <- x case test of Just _ -> return test Nothing -> firstTrue xs -- |Split a byte into a (Bool, Word8) pair that has the most significant bit -- and the lower 7 bits. This is a common pattern in Git bit-packing schemes. splitMSB :: Word8 -> (Bool, Word8) splitMSB byte = (msb, bits) where msb = (byte .&. 0x80) /= 0 bits = byte .&. 0x7F -- |Convert a ByteString.Lazy to a strict ByteString. strictifyBS :: BL.ByteString -> B.ByteString strictifyBS = B.concat . BL.toChunks -- | Convert a String into a strict ByteString. makeBS :: String -> B.ByteString makeBS = B.pack . map (fromIntegral . fromEnum)
martine/gat
Shared.hs
gpl-2.0
2,969
0
13
640
854
461
393
63
2
{- Copyright (C) 2008-2014 John MacFarlane <jgm@berkeley.edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Highlighting Copyright : Copyright (C) 2008-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <jgm@berkeley.edu> Stability : alpha Portability : portable Exports functions for syntax highlighting. -} module Text.Pandoc.Highlighting ( languages , languagesByExtension , highlight , formatLaTeXInline , formatLaTeXBlock , styleToLaTeX , formatHtmlInline , formatHtmlBlock , styleToCss , pygments , espresso , zenburn , tango , kate , monochrome , haddock , Style , fromListingsLanguage , toListingsLanguage ) where import Text.Pandoc.Definition import Text.Pandoc.Shared (safeRead) import Text.Highlighting.Kate import Data.List (find) import Data.Maybe (fromMaybe) import Data.Char (toLower) import qualified Data.Map as M import Control.Applicative ((<|>)) lcLanguages :: [String] lcLanguages = map (map toLower) languages highlight :: (FormatOptions -> [SourceLine] -> a) -- ^ Formatter -> Attr -- ^ Attributes of the CodeBlock -> String -- ^ Raw contents of the CodeBlock -> Maybe a -- ^ Maybe the formatted result highlight formatter (_, classes, keyvals) rawCode = let firstNum = case safeRead (fromMaybe "1" $ lookup "startFrom" keyvals) of Just n -> n Nothing -> 1 fmtOpts = defaultFormatOpts{ startNumber = firstNum, numberLines = any (`elem` ["number","numberLines", "number-lines"]) classes } lcclasses = map (map toLower) classes in case find (`elem` lcLanguages) lcclasses of Nothing -> Nothing Just language -> Just $ formatter fmtOpts{ codeClasses = [language], containerClasses = classes } $ highlightAs language rawCode -- Functions for correlating latex listings package's language names -- with highlighting-kate language names: langToListingsMap :: M.Map String String langToListingsMap = M.fromList langsList listingsToLangMap :: M.Map String String listingsToLangMap = M.fromList $ map switch langsList where switch (a,b) = (b,a) langsList :: [(String, String)] langsList = [("ada","Ada") ,("java","Java") ,("prolog","Prolog") ,("python","Python") ,("gnuassembler","Assembler") ,("commonlisp","Lisp") ,("r","R") ,("awk","Awk") ,("bash","bash") ,("makefile","make") ,("c","C") ,("matlab","Matlab") ,("ruby","Ruby") ,("cpp","C++") ,("ocaml","Caml") ,("modula2","Modula-2") ,("sql","SQL") ,("eiffel","Eiffel") ,("tcl","tcl") ,("erlang","erlang") ,("verilog","Verilog") ,("fortran","Fortran") ,("vhdl","VHDL") ,("pascal","Pascal") ,("perl","Perl") ,("xml","XML") ,("haskell","Haskell") ,("php","PHP") ,("xslt","XSLT") ,("html","HTML") ] listingsLangs :: [String] listingsLangs = ["Ada","Java","Prolog","Algol","JVMIS","Promela", "Ant","ksh","Python","Assembler","Lisp","R","Awk", "Logo","Reduce","bash","make","Rexx","Basic", "Mathematica","RSL","C","Matlab","Ruby","C++", "Mercury","S","Caml","MetaPost","SAS","Clean", "Miranda","Scilab","Cobol","Mizar","sh","Comal", "ML","SHELXL","csh","Modula-2","Simula","Delphi", "MuPAD","SQL","Eiffel","NASTRAN","tcl","Elan", "Oberon-2","TeX","erlang","OCL","VBScript","Euphoria", "Octave","Verilog","Fortran","Oz","VHDL","GCL", "Pascal","VRML","Gnuplot","Perl","XML","Haskell", "PHP","XSLT","HTML","PL/I"] -- Determine listings language name from highlighting-kate language name. toListingsLanguage :: String -> Maybe String toListingsLanguage lang = (if lang `elem` listingsLangs then Just lang else Nothing) <|> M.lookup (map toLower lang) langToListingsMap -- Determine highlighting-kate language name from listings language name. fromListingsLanguage :: String -> Maybe String fromListingsLanguage lang = M.lookup lang listingsToLangMap
nickbart1980/pandoc
src/Text/Pandoc/Highlighting.hs
gpl-2.0
5,985
0
15
2,178
1,067
657
410
104
3
module AllTests(main) where import AnalysisTests import ParserTests main = do allAnalysisTests allParserTests
dillonhuff/GitVisualizer
test/AllTests.hs
gpl-2.0
116
0
6
18
26
15
11
6
1
{-# LANGUAGE UnicodeSyntax #-} -- -- Utility functions to run the program. -- module Program where import Prelude.Unicode import System.Environment import System.Exit runAction ∷ IO Bool → IO () runAction action = do isSuccess ← action exitWith $ exitStatus isSuccess where exitStatus True = ExitSuccess exitStatus False = ExitFailure (0-1)
c0c0n3/hAppYard
inkscape-util/src/shared/Program.hs
gpl-3.0
399
0
9
102
93
49
44
11
2
{-# OPTIONS_GHC -fno-warn-orphans #-} module Handler.TransById where import Import $(deriveJSON defaultOptions ''Transaction) getTransByIdR :: String -> Handler Value getTransByIdR uIdent = do mUser <- runDB $ selectFirst [ UserIdent ==. (pack uIdent) ] [] case mUser of Just user -> do trans <- runDB $ selectList [ TransactionVendor ==. (entityKey user) ] [] returnJson trans Nothing -> return $ object [ "result" .= ("error" :: Text)]
weshack/thelist
TheList/Handler/TransById.hs
gpl-3.0
465
0
18
93
154
76
78
-1
-1
{- Merch.Race.Data.Serialize - Serialization class for data types. Copyright 2013 Alan Manuel K. Gloria This file is part of Merchant's Race. Merchant's Race 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. Merchant's Race is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Merchant's Race. If not, see <http://www.gnu.org/licenses/>. -} module Merch.Race.Data.Serialize ( Serialize(..) , hPutConvert , hGetConvert ) where import Control.Monad import Data.Bits import Data.Int import Data.List import qualified Data.Map as Map import Data.Map(Map) import Data.Ratio import qualified Data.Set as Set import Data.Set(Set) import Data.Word import Foreign.Marshal.Alloc import Foreign.Storable import System.IO class Serialize a where hPut :: Handle -> a -> IO () hGet :: Handle -> IO a {- Although we *could* use Storable instances directly, doing that leaves us to the mercy of the target machine's endianness. By splitting up words "manually" without the help of Storable, we can mandate the ONE TRUE WAY to correctly store data, which is, of course, as everybody knows, little-endian. -} instance Serialize Word8 where hPut h w = alloca $ \p -> do poke p w hPutBuf h p 1 hGet h = alloca $ \p -> do hGetBuf h p 1 peek p instance Serialize Word16 where hPut h w = allocaBytes 2 $ \p -> do let bs = [ fromIntegral $ (w `shiftR` 0) .&. 255 , fromIntegral $ (w `shiftR` 8) .&. 255 ] forM_ (zip [0..1] bs) $ \ (n, b) -> do pokeByteOff p n (b :: Word8) hPutBuf h p 2 hGet h = allocaBytes 2 $ \p -> do hGetBuf h p 2 [b0, b1] <- forM [0..1] $ \n -> do peekByteOff p n :: IO Word8 return $ ((fromIntegral b0) `shiftL` 0) .|. ((fromIntegral b1) `shiftL` 8) instance Serialize Word32 where hPut h w = allocaBytes 2 $ \p -> do let bs = [ fromIntegral $ (w `shiftR` 0) .&. 255 , fromIntegral $ (w `shiftR` 8) .&. 255 , fromIntegral $ (w `shiftR` 16) .&. 255 , fromIntegral $ (w `shiftR` 24) .&. 255 ] forM_ (zip [0..3] bs) $ \ (n, b) -> do pokeByteOff p n (b :: Word8) hPutBuf h p 4 hGet h = allocaBytes 2 $ \p -> do hGetBuf h p 4 [b0, b1, b2, b3] <- forM [0..3] $ \n -> do peekByteOff p n :: IO Word8 return $ ((fromIntegral b0) `shiftL` 0) .|. ((fromIntegral b1) `shiftL` 8) .|. ((fromIntegral b2) `shiftL` 16) .|. ((fromIntegral b3) `shiftL` 24) instance Serialize Word64 where hPut h w = allocaBytes 2 $ \p -> do let bs = [ fromIntegral $ (w `shiftR` 0) .&. 255 , fromIntegral $ (w `shiftR` 8) .&. 255 , fromIntegral $ (w `shiftR` 16) .&. 255 , fromIntegral $ (w `shiftR` 24) .&. 255 , fromIntegral $ (w `shiftR` 32) .&. 255 , fromIntegral $ (w `shiftR` 40) .&. 255 , fromIntegral $ (w `shiftR` 48) .&. 255 , fromIntegral $ (w `shiftR` 56) .&. 255 ] forM_ (zip [0..7] bs) $ \ (n, b) -> do pokeByteOff p n (b :: Word8) hPutBuf h p 8 hGet h = allocaBytes 2 $ \p -> do hGetBuf h p 8 [b0, b1, b2, b3, b4, b5, b6, b7] <- forM [0..7] $ \n -> do peekByteOff p n :: IO Word8 return $ ((fromIntegral b0) `shiftL` 0) .|. ((fromIntegral b1) `shiftL` 8) .|. ((fromIntegral b2) `shiftL` 16) .|. ((fromIntegral b3) `shiftL` 24) .|. ((fromIntegral b4) `shiftL` 32) .|. ((fromIntegral b5) `shiftL` 40) .|. ((fromIntegral b6) `shiftL` 48) .|. ((fromIntegral b7) `shiftL` 56) -- For easy implementation of Serialize instances of -- data types which can be trivially converted to -- simpler Serialize data types. hPutConvert :: Serialize basetype => (a -> basetype) -> Handle -> a -> IO () hPutConvert convert h a = hPut h (convert a) hGetConvert :: Serialize basetype => (basetype -> a) -> Handle -> IO a hGetConvert convert h = hGet h >>= return . convert -- We assume that Word fits into Word32. instance Serialize Word where hPut = hPutConvert (fromIntegral :: Word -> Word32) hGet = hGetConvert (fromIntegral :: Word32 -> Word ) -- We assume that Int types are trivially convertible -- to the corresponding Word types, and that the -- conversion back to Int will restore negative signs. instance Serialize Int where hPut = hPutConvert (fromIntegral :: Int -> Word ) hGet = hGetConvert (fromIntegral :: Word -> Int ) instance Serialize Int8 where hPut = hPutConvert (fromIntegral :: Int8 -> Word8 ) hGet = hGetConvert (fromIntegral :: Word8 -> Int8 ) instance Serialize Int16 where hPut = hPutConvert (fromIntegral :: Int16 -> Word16) hGet = hGetConvert (fromIntegral :: Word16 -> Int16 ) instance Serialize Int32 where hPut = hPutConvert (fromIntegral :: Int32 -> Word32) hGet = hGetConvert (fromIntegral :: Word32 -> Int32 ) instance Serialize Int64 where hPut = hPutConvert (fromIntegral :: Int64 -> Word64) hGet = hGetConvert (fromIntegral :: Word64 -> Int64 ) -- Serializing common builtin datatypes instance Serialize Bool where hPut h t = hPut h (if t then 1 else 0 :: Word8) hGet h = (hGet h :: IO Word8) >>= \i -> return $ if i == 0 then False else True instance Serialize a => Serialize (Maybe a) where hPut h Nothing = do hPut h (0 :: Word8) hPut h (Just a) = do hPut h (1 :: Word8) hPut h a hGet h = do i <- hGet h :: IO Word8 if i == 0 then return Nothing else hGet h >>= return . Just instance (Serialize a, Serialize b) => Serialize (Either a b) where hPut h (Left a) = do hPut h (0 :: Word8) hPut h a hPut h (Right b) = do hPut h (1 :: Word8) hPut h b hGet h = do i <- hGet h :: IO Word8 if i == 0 then hGet h >>= return . Left else hGet h >>= return . Right instance Serialize a => Serialize [a] where hPut h as = do hPut h (length as :: Int) forM_ as $ hPut h hGet h = do n <- hGet h :: IO Int forM [1..n] $ \_ -> hGet h -- important data structures in base. instance (Serialize a, Serialize b, Ord a) => Serialize (Map a b) where hPut h s = hPut h $ Map.toList s hGet h = hGet h >>= return . Map.fromList instance (Serialize a, Integral a) => Serialize (Ratio a) where hPut h x = do let n = numerator x d = denominator x hPut h n hPut h d hGet h = do n <- hGet h d <- hGet h return $ n % d instance (Serialize a, Ord a) => Serialize (Set a) where hPut h s = hPut h $ Set.toList s hGet h = hGet h >>= return . Set.fromList {- Integer serialization. We observe that most Integers are small, fitting in one or two bytes. So, we use the following format: 1. The first byte is either 0 to indicate nothing follows and the number is a 0, or a signed number of bytes (the absolute value is the number of bytes, the sign is the sign of the Integer). 2. If the signed number of bytes has magnitude 127, it means that the integer is so freaking huge that it takes 127 or more bytes to store it. If so, this means there's a serialized Word after the first byte, which contains the real number of bytes in the Integer. 3. The Integer's magnitude is stored, lowest byte first, in the succeeding space. The sign is the sign of the first byte. -} -- split/unsplit Integers into bytes blast :: Integer -> (Bool, [Word8]) blast i | i < 0 = (True, loop $ negate i) | otherwise = (False, loop i) where loop i | i == 0 = [] | otherwise = let (q, r) = i `divMod` 256 in fromIntegral r:loop q unblast :: (Bool, [Word8]) -> Integer unblast (s, ws) | s = negate $ loop ws | otherwise = loop ws where loop = core 0 1 core acc mult [] = acc core acc mult (w:ws) = core (acc + fromIntegral w * mult) (mult * 256) ws instance Serialize Integer where hPut h i = do let (s, ws) = blast i num = genericLength ws :: Word sign | s = negate | otherwise = id if num <= 126 then do hPut h (sign $ fromIntegral num :: Int8 ) else do hPut h (sign 127 :: Int8) hPut h (num :: Word) forM_ ws $ hPut h hGet h = do nb <- hGet h :: IO Int8 let s = nb < 0 sign | s = negate | otherwise = id num | s = negate nb | otherwise = nb num <- if num <= 126 then return $ fromIntegral num else hGet h :: IO Word ws <- forM [1..num] $ \_ -> hGet h return $ unblast (s, ws) {- Encode Char using UTF-8. -} instance Serialize Char where hPut h c = do case fromEnum c of i | i <= 0x007F -> hPut h (fromIntegral i :: Word8) | i <= 0x07FF -> encode2 h i | i <= 0xFFFF -> encode3 h i | i <= 0x1FFFFF -> encode4 h i | i <= 0x3FFFFFF -> encode5 h i | i <= 0x7FFFFFFF -> encode6 h i | otherwise -> fail "Character too large to write." where encode2 h i = do let (i0, i1) = ( (i `shiftR` 6) , (i `shiftR` 0) .&. 0x3F ) ws = [ 0xC0 .|. fromIntegral i0 , 0x80 .|. fromIntegral i1 ] :: [Word8] forM_ ws $ hPut h encode3 h i = do let (i0, i1, i2) = ( (i `shiftR` 12) , (i `shiftR` 6) .&. 0x3F , (i `shiftR` 0) .&. 0x3F ) ws = [ 0xE0 .|. fromIntegral i0 , 0x80 .|. fromIntegral i1 , 0x80 .|. fromIntegral i2 ] :: [Word8] forM_ ws $ hPut h encode4 h i = do let (i0, i1, i2, i3) = ( (i `shiftR` 18) , (i `shiftR` 12) .&. 0x3F , (i `shiftR` 6) .&. 0x3F , (i `shiftR` 0) .&. 0x3F ) ws = [ 0xF0 .|. fromIntegral i0 , 0x80 .|. fromIntegral i1 , 0x80 .|. fromIntegral i2 , 0x80 .|. fromIntegral i3 ] :: [Word8] forM_ ws $ hPut h encode5 h i = do let (i0, i1, i2, i3, i4) = ( (i `shiftR` 24) , (i `shiftR` 18) .&. 0x3F , (i `shiftR` 12) .&. 0x3F , (i `shiftR` 6) .&. 0x3F , (i `shiftR` 0) .&. 0x3F ) ws = [ 0xF0 .|. fromIntegral i0 , 0x80 .|. fromIntegral i1 , 0x80 .|. fromIntegral i2 , 0x80 .|. fromIntegral i3 , 0x80 .|. fromIntegral i4 ] :: [Word8] forM_ ws $ hPut h encode6 h i = do let (i0, i1, i2, i3, i4, i5) = ( (i `shiftR` 30) , (i `shiftR` 24) .&. 0x3F , (i `shiftR` 18) .&. 0x3F , (i `shiftR` 12) .&. 0x3F , (i `shiftR` 6) .&. 0x3F , (i `shiftR` 0) .&. 0x3F ) ws = [ 0xF0 .|. fromIntegral i0 , 0x80 .|. fromIntegral i1 , 0x80 .|. fromIntegral i2 , 0x80 .|. fromIntegral i3 , 0x80 .|. fromIntegral i4 , 0x80 .|. fromIntegral i5 ] :: [Word8] forM_ ws $ hPut h hGet h = do i <- hGet h :: IO Word8 case i of i | (i .&. 0x80) == 0x00 -> return $ toEnum $ fromIntegral i | (i .&. 0xE0) == 0xC0 -> decode2 h (i .&. 0x1F) | (i .&. 0xF0) == 0xE0 -> decode3 h (i .&. 0x0F) | (i .&. 0xF8) == 0xF0 -> decode4 h (i .&. 0x07) | (i .&. 0xFC) == 0xF8 -> decode5 h (i .&. 0x03) | (i .&. 0xFE) == 0xFC -> decode6 h (i .&. 0x01) | otherwise -> fail "Invalid UTF-8 encoding." where readCont h = do w <- hGet h :: IO Word8 when ((w .&. 0xC0) /= 0x80) $ do fail "Expecting continuation character in UTF-8 encoding." return $ w .&. 0x3F decode2 h w0 = do [w1] <- forM [2..2] $ \_ -> readCont h return $ toEnum $ (fromIntegral w0 `shiftL` 6) .|. (fromIntegral w1 `shiftL` 0) decode3 h w0 = do [w1, w2] <- forM [2..3] $ \_ -> readCont h return $ toEnum $ (fromIntegral w0 `shiftL` 12) .|. (fromIntegral w1 `shiftL` 6) .|. (fromIntegral w2 `shiftL` 0) decode4 h w0 = do [w1, w2, w3] <- forM [2..4] $ \_ -> readCont h return $ toEnum $ (fromIntegral w0 `shiftL` 18) .|. (fromIntegral w1 `shiftL` 12) .|. (fromIntegral w2 `shiftL` 6) .|. (fromIntegral w3 `shiftL` 0) decode5 h w0 = do [w1, w2, w3, w4] <- forM [2..5] $ \_ -> readCont h return $ toEnum $ (fromIntegral w0 `shiftL` 24) .|. (fromIntegral w1 `shiftL` 18) .|. (fromIntegral w2 `shiftL` 12) .|. (fromIntegral w3 `shiftL` 6) .|. (fromIntegral w4 `shiftL` 0) decode6 h w0 = do [w1, w2, w3, w4, w5] <- forM [2..6] $ \_ -> readCont h return $ toEnum $ (fromIntegral w0 `shiftL` 30) .|. (fromIntegral w1 `shiftL` 24) .|. (fromIntegral w2 `shiftL` 18) .|. (fromIntegral w3 `shiftL` 12) .|. (fromIntegral w4 `shiftL` 6) .|. (fromIntegral w5 `shiftL` 0) -- Freaking Tuples! instance (Serialize i0, Serialize i1) => Serialize (i0, i1) where hPut h (i0,i1) = do hPut h i0 hPut h i1 hGet h = do i0 <- hGet h i1 <- hGet h return (i0,i1) instance (Serialize i0, Serialize i1, Serialize i2) => Serialize (i0, i1, i2) where hPut h (i0,i1,i2) = do hPut h i0 hPut h i1 hPut h i2 hGet h = do i0 <- hGet h i1 <- hGet h i2 <- hGet h return (i0,i1,i2) instance (Serialize i0, Serialize i1, Serialize i2, Serialize i3) => Serialize (i0, i1, i2, i3) where hPut h (i0,i1,i2,i3) = do hPut h i0 hPut h i1 hPut h i2 hPut h i3 hGet h = do i0 <- hGet h i1 <- hGet h i2 <- hGet h i3 <- hGet h return (i0,i1,i2,i3) instance (Serialize i0, Serialize i1, Serialize i2, Serialize i3, Serialize i4) => Serialize (i0, i1, i2, i3, i4) where hPut h (i0,i1,i2,i3,i4) = do hPut h i0 hPut h i1 hPut h i2 hPut h i3 hPut h i4 hGet h = do i0 <- hGet h i1 <- hGet h i2 <- hGet h i3 <- hGet h i4 <- hGet h return (i0,i1,i2,i3,i4) -- Freaking Tuples! Ends
AmkG/merchants-race
Merch/Race/Data/Serialize.hs
gpl-3.0
14,816
0
21
4,928
5,468
2,836
2,632
364
2
module Mudblood.Contrib.MG.Profile ( MGProfile (..) , readProfile , mkMGProfile ) where import Text.ParserCombinators.Parsec import Mudblood data MGProfile = MGProfile { profChar :: Maybe String , profPassword :: Maybe String , profLogfile :: Maybe FilePath , profMap :: Maybe FilePath } mkMGProfile = MGProfile { profChar = Nothing , profPassword = Nothing , profLogfile = Nothing , profMap = Nothing } readProfile :: String -> Either String MGProfile readProfile f = do case parse pFile "" f of Left err -> Left $ "Error reading profile: " ++ show err Right a -> Right a pFile :: Parser MGProfile pFile = do settings <- many pSetting eof return $ foldr ($) mkMGProfile settings pSetting :: Parser (MGProfile -> MGProfile) pSetting = choice [ pStringSetting "char" >>= \x -> return $ \p -> p { profChar = Just x } , pStringSetting "password" >>= \x -> return $ \p -> p { profPassword = Just x } , pStringSetting "logfile" >>= \x -> return $ \p -> p { profLogfile = Just x } , pStringSetting "map" >>= \x -> return $ \p -> p { profMap = Just x } ] pStringSetting :: String -> Parser String pStringSetting name = do string name spaces anyChar `manyTill` newline
talanis85/mudblood
src/Mudblood/Contrib/MG/Profile.hs
gpl-3.0
1,317
0
13
362
419
224
195
37
2
{- Copyright : Copyright (C) 2014-2015 Synchrotron Soleil License : GPL3+ Maintainer : picca@synchrotron-soleil.fr Stability : Experimental Portability: GHC only? -} module Hkl.Source ( ki ) where import Prelude hiding ((/)) import Numeric.LinearAlgebra (Vector, fromList) import Numeric.Units.Dimensional.Prelude (nano, meter, (*~), (/~), (/), Length, one) import Hkl.Lattice (tau) lambda :: Length Double lambda = 1.54 *~ nano meter ki :: Vector Double ki = fromList [(tau / lambda) /~ (one / meter), 0, 0]
klauer/hkl
contrib/Hkl/Source.hs
gpl-3.0
589
0
9
153
145
90
55
11
1
module Lamdu.GUI.ExpressionEdit.HoleEdit.Info ( HoleInfo(..) , hiSearchTermProperty , hiSearchTerm ) where import Control.Lens.Operators import Data.Store.Property (Property(..)) import qualified Data.Store.Property as Property import qualified Data.Store.Transaction as Transaction import Lamdu.Calc.Type (Type) import Lamdu.GUI.ExpressionEdit.HoleEdit.State (HoleState, hsSearchTerm) import Lamdu.GUI.ExpressionEdit.HoleEdit.WidgetIds (WidgetIds) import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT import Lamdu.Sugar.Names.Types (Name) import Lamdu.Sugar.NearestHoles (NearestHoles) import qualified Lamdu.Sugar.Types as Sugar type T = Transaction.Transaction data HoleInfo m = HoleInfo { hiEntityId :: Sugar.EntityId , hiInferredType :: Type , hiIds :: WidgetIds , hiHole :: Sugar.Hole (Name m) m (ExprGuiT.SugarExpr m) , hiNearestHoles :: NearestHoles , hiState :: Property (T m) HoleState } hiSearchTermProperty :: HoleInfo m -> Property (T m) String hiSearchTermProperty holeInfo = hiState holeInfo & Property.composeLens hsSearchTerm hiSearchTerm :: HoleInfo m -> String hiSearchTerm holeInfo = Property.value (hiState holeInfo) ^. hsSearchTerm
da-x/lamdu
Lamdu/GUI/ExpressionEdit/HoleEdit/Info.hs
gpl-3.0
1,279
0
12
243
313
191
122
27
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable #-} module Main where import Data.Conduit.Lazy import qualified Data.ByteString.Char8 as B import Control.Monad import Data.Conduit import Data.Conduit.List (consume) import Data.Conduit.Binary (sourceFile) import System.Console.CmdArgs import Text.Printf import Control.Applicative import Bio.Core.Sequence (Offset (..)) import Data.List.Split (chunksOf) import Control.Parallel.Strategies import Data.DList (toList) import qualified Text.PrettyPrint.ANSI.Leijen as PP import Biobase.Fasta import Biobase.Fasta.Import import Biobase.SubstMatrix import Biobase.SubstMatrix.Import import Biobase.Primary import BioInf.Alignment.DnaProtein import BioInf.Alignment.DnaProtein.Pretty data Option = Option { dna :: String -- , dnawindow :: Int , protein :: String -- , proteinwindow :: Int , windowMult :: Int , blastMatrix :: String , insertAA :: Int , deleteAA :: Int , rf1S :: Int , rf1delS :: Int , rf2S :: Int , rf2delS :: Int , minScore :: Int , minadjScore :: Double , parallelism :: Int } deriving (Show,Data,Typeable) option = Option { dna = def &= help "DNA fasta file to read" -- , dnawindow = 2000 , protein = def &= help "Protein fasta file to read" -- , proteinwindow = 10000000 , windowMult = 3 &= help "window of k nucleotides for each amino acid (actually 2k, as we use sliding windows)" , blastMatrix = def &= help "Blast matrix (PAM / BLOSUM) to use" , insertAA = -10 &= help "cost for inserting an amino acid (indel)" , deleteAA = -15 &= help "cost for deleting an amino acid (indel)" , rf1S = -20 &= help "cost for aligning only two nucleotides with an AA and frame shifting by 1" , rf1delS = -45 &= help "cost for deleting two nucleotides and frame shifting by 1" , rf2S = -60 &= help "cost for aligning only one nucleotide with an AA and frame shifting by 2" , rf2delS = -75 &= help "cost for deleting a nucleotide and frame shifting by 1" , minScore = -999999 &= help "display only scores above this threshold" , minadjScore = -999999 &= help "minimal (score / protein length)" , parallelism = 16 &= help "maximum parallelism (should be set 2-4x or more of the number of CPUs" } data Direction = Forward | Backward deriving (Eq,Ord,Show) main = do o@Option{..} <- cmdArgs option ps <- if null protein then return [] else runResourceT $ sourceFile protein $= parseFastaWindows 999999999 $$ consume forM_ ps $ \p -> do let lenP = fromIntegral $ B.length $ _fasta p ds <- if null dna then return [] else runResourceT $ sourceFile dna $= parseFastaWindows (lenP * windowMult) $$ consume when (null blastMatrix) $ error "require Blast matrix" mat <- fromFile blastMatrix let !n3m = mkNuc3SubstMatrix mat let !n2m = mkNuc2SubstMatrix max id mat let !n1m = mkNuc1SubstMatrix max id mat let xsF = [ (d,inpD,offD,p,Forward, dnaProtein n3m n2m n1m insertAA deleteAA rf1S rf1delS rf2S rf2delS inpD (B.unpack $ _fasta p)) | d <- ds , let inpD = _past d `B.append` _fasta d , let offD = (unOff $ _offset d) - (fromIntegral . B.length $ _past d) ] let xsB = [ (d,inpD,offD,p,Backward, dnaProtein n3m n2m n1m insertAA deleteAA rf1S rf1delS rf2S rf2delS inpD (B.unpack $ _fasta p)) | d <- ds , let inpD = B.map compl . B.reverse $ _past d `B.append` _fasta d , let offD = (unOff $ _offset d) - (fromIntegral . B.length $ _past d) ] forM_ ((xsF++xsB) `using` parBuffer parallelism (evalTuple6 r0 r0 r0 r0 r0 (evalTuple2 rdeepseq r0))) $ \(d,inpD,offD,p,dir,(s,bs)) -> do let sa :: Double = fromIntegral s / fromIntegral (B.length $ _fasta p) :: Double when (s>=minScore && sa>=minadjScore) $ do let llF = if null bs then 0 else length . takeWhile isLOC . toList . head $ bs let llR = if null bs then 0 else length . takeWhile isLOC . reverse . toList . head $ bs let frs1s = filter (\case (FRS [_,_] [_] _) -> True ; z->False) . toList . head $ bs let frs2s = filter (\case (FRS [_] [_] _) -> True ; z->False) . toList . head $ bs printf "DNA: %s %s @ %s %d\nProtein: %s %s @ %d\n" (B.unpack $ _identifier d) (B.unpack $ _description d) (show dir) (offD + if dir==Forward then (fromIntegral llF) else (fromIntegral llR)) (B.unpack $ _identifier p) (B.unpack $ _description p) (unOff $ _offset p) printf "DNA length: %d Protein length: %d\n" (B.length inpD) (B.length $ _fasta p) printf "1 Nt shifts: %d ||| 2 Nt shifts: %d\n" (length frs1s) (length frs2s) printf "Score: %d Length-adjusted: %.2f\n\n" s sa if null bs then putStrLn "NO ALIGNMENT?" else do let tt = length . takeWhile isPPS . drop llF . toList . head $ bs cs = chunksOf 30 . take tt . drop llF . toList . head $ bs llIdx = if dir==Forward then llF else llR foldM_ (\pos pps -> let adv = advancePos pos pps in PP.putDoc (pps2doc pos adv pps) >> return (advancePos pos pps) ) (fromIntegral offD + llIdx + 1, 1) cs putStrLn "" compl :: Char -> Char compl 'A' = 'T' compl 'T' = 'A' compl 'C' = 'G' compl 'G' = 'C' compl 'a' = 't' compl 't' = 'a' compl 'c' = 'g' compl 'g' = 'c' compl x = x advancePos :: (Int,Int) -> [PPS] -> (Int,Int) advancePos = foldl go where go (l,r) (PPS cs as _) = (l + length cs, r + length as) go (l,r) (FRS cs as _) = (l + length cs, r + length as) go (l,r) (LOC _ _) = (l + 1 , r ) pps2doc :: (Int,Int) -> (Int,Int) -> [PPS] -> PP.Doc pps2doc (pl,pr) (apl,apr) xs = PP.text (printf "%8d " pl) PP.<> us PP.<> (PP.text (printf " %8d" (apl-1))) PP.<$> PP.text (printf "%8d " pr) PP.<> os PP.<> (PP.text (printf " %8d" (apr-1))) PP.<$> PP.empty PP.<$> PP.empty where us = PP.hcat $ map upper xs os = PP.hcat $ map lower xs upper (PPS cs as k) = colorize k . PP.text . take 3 $ map fromNuc cs ++ repeat '-' upper (FRS cs as k) = PP.underline . PP.bold . colorize k . PP.text . take 3 $ map fromNuc cs ++ repeat '-' upper (LOC c k) = colorize k . PP.text $ [fromNuc c] lower (PPS cs [] k) = colorize k . PP.text $ "- " lower (PPS cs [a] k) = colorize k . PP.text . take 3 $ [a] ++ repeat ' ' lower (FRS cs [a] k) = PP.bold . colorize k . PP.text . take 3 $ [a] ++ repeat ' ' lower (LOC c k) = colorize k . PP.text $ "." colorize k | k>5 = PP.cyan | k>0 = PP.blue | k<(-5) = PP.red | k<0 = PP.yellow | otherwise = id
choener/DnaProteinAlignment
DnaProteinAlignment.hs
gpl-3.0
7,140
10
35
2,109
2,588
1,333
1,255
143
10
module Main where import VSim.Runtime elab :: Elab IO () elab = do integer <- alloc_unranged_type array <- alloc_array_type (alloc_range (pure 0) (pure 5)) integer clk <- alloc_signal "clk" integer (assign (int 0)) a1 <- alloc_signal "a2" array (aggregate [ access (int 0) (assign (pure clk)) , access (int 1) (assign (int 4)) ]) a2 <- alloc_signal "a1" array defval a3 <- alloc_signal "a2" array (assign (pure a1)) proc1 <- alloc_process "main" [] $ do breakpoint (pure clk) .<=. (next, assign ((pure clk) .+. (int 1))) (pure a2) .<=. (next, assign (pure a1)) (pure a1) .<=. (fs 2, aggregate [ access (int 1) (assign ((index (int 1) (pure a1)) .+. (int 1))) , access (int 2) (assign (int 3)) ]) (index (int 0) (pure a1)) .<=. (next, assign (int 0)) wait (fs 1) return () return () main = do sim maxBound elab
grwlf/vsim
src_r/Test/Array1.hs
gpl-3.0
1,019
0
23
351
480
232
248
25
1
-- Module for connecting to the AUR servers, -- downloading PKGBUILDs and source tarballs, and handling them. {- Copyright 2012, 2013, 2014, 2015 Colin Woodbury <colingw@gmail.com> This file is part of Aura. Aura 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. Aura is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Aura. If not, see <http://www.gnu.org/licenses/>. -} module Aura.Packages.AUR ( aurLookup , aurRepo , isAurPackage , sourceTarball , aurInfo , aurSearch , pkgUrl ) where import Control.Monad ((>=>),join) import Data.Function (on) import Data.List (sortBy) import Data.Maybe import qualified Data.Text as T import qualified Data.Traversable as Traversable (mapM) import Linux.Arch.Aur import System.FilePath ((</>)) import Aura.Monad.Aura import Aura.Pkgbuild.Base import Aura.Settings.Base import Aura.Core import Utilities (decompress) import Internet --- aurLookup :: String -> Aura (Maybe Buildable) aurLookup name = fmap (makeBuildable name . T.unpack) <$> pkgbuild name aurRepo :: Repository aurRepo = Repository $ aurLookup >=> Traversable.mapM packageBuildable makeBuildable :: String -> Pkgbuild -> Buildable makeBuildable name pb = Buildable { baseNameOf = name , pkgbuildOf = pb , isExplicit = False , buildScripts = f } where f fp = sourceTarball fp (T.pack name) >>= Traversable.mapM decompress isAurPackage :: String -> Aura Bool isAurPackage name = isJust <$> pkgbuild name ---------------- -- AUR PKGBUILDS ---------------- aurLink :: String aurLink = "https://aur4.archlinux.org" pkgUrl :: String -> String pkgUrl pkg = aurLink </> "packages" </> pkg ------------------ -- SOURCE TARBALLS ------------------ sourceTarball :: FilePath -- ^ Where to save the tarball. -> T.Text -- ^ Package name. -> IO (Maybe FilePath) -- ^ Saved tarball location. sourceTarball path = fmap join . (info >=> Traversable.mapM f) where f = saveUrlContents path . (++) aurLink . T.unpack . urlPathOf ------------ -- RPC CALLS ------------ sortAurInfo :: SortScheme -> [AurInfo] -> [AurInfo] sortAurInfo scheme ai = sortBy compare' ai where compare' = case scheme of ByVote -> \x y -> compare (aurVotesOf y) (aurVotesOf x) Alphabetically -> compare `on` aurNameOf aurSearch :: T.Text -> Aura [AurInfo] aurSearch regex = asks sortSchemeOf >>= \scheme -> sortAurInfo scheme <$> search regex aurInfo :: [T.Text] -> Aura [AurInfo] aurInfo pkgs = sortAurInfo Alphabetically <$> multiinfo pkgs
joehillen/aura
src/Aura/Packages/AUR.hs
gpl-3.0
3,208
0
13
803
625
349
276
54
2
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE DeriveFunctor #-} module Data.ChordPro ( Chunk (..), Music (..) , Line, Paragraph, Markup (..) , Layout , bake , prettyPrintChordPro ) where import Data.Music.Scales import Data.Music.Chords import Data.Music.Tonal -- File layout type Layout a = [Paragraph a] type Paragraph a = [Line a] type Line a = [Chunk a] data Chunk a = ChunkBoth (Music a) Markup | ChunkMusic (Music a) | ChunkMarkup Markup | ChunkEmpty deriving (Show, Functor) data Music a = MusicChord a | MusicBar deriving (Show, Functor) data Markup = NormalMarkup String | TitleMarkup String deriving (Show) type Option = (String, String) mapLayout :: (a -> b) -> Layout a -> Layout b mapLayout = map . map . map . fmap bake :: TonalScale -> Layout DegreeChord -> Layout TonalChord bake scale = mapLayout $ bakeChord scale prettyPrintChordPro :: (Show a) => Layout a -> IO () prettyPrintChordPro paras = mapM_ prettyPrintParagraph paras where prettyPrintParagraph p = do putStrLn "PARAGRAPH" mapM_ prettyPrintLine p prettyPrintLine l = do putStrLn " LINE" mapM_ prettyPrintChunk l prettyPrintChunk c = do putStr " CHUNK: " putStrLn (show c)
talanis85/rechord
src/Data/ChordPro.hs
gpl-3.0
1,297
0
11
321
397
217
180
39
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.AndroidEnterprise.Devices.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the device policy. To ensure the policy is properly enforced, -- you need to prevent unmanaged accounts from accessing Google Play by -- setting the allowed_accounts in the managed configuration for the Google -- Play package. See restrict accounts in Google Play. When provisioning a -- new device, you should set the device policy using this method before -- adding the managed Google Play Account to the device, otherwise the -- policy will not be applied for a short period of time after adding the -- account to the device. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.devices.update@. module Network.Google.Resource.AndroidEnterprise.Devices.Update ( -- * REST Resource DevicesUpdateResource -- * Creating a Request , devicesUpdate , DevicesUpdate -- * Request Lenses , duXgafv , duUploadProtocol , duUpdateMask , duEnterpriseId , duAccessToken , duUploadType , duPayload , duUserId , duDeviceId , duCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.devices.update@ method which the -- 'DevicesUpdate' request conforms to. type DevicesUpdateResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "users" :> Capture "userId" Text :> "devices" :> Capture "deviceId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Device :> Put '[JSON] Device -- | Updates the device policy. To ensure the policy is properly enforced, -- you need to prevent unmanaged accounts from accessing Google Play by -- setting the allowed_accounts in the managed configuration for the Google -- Play package. See restrict accounts in Google Play. When provisioning a -- new device, you should set the device policy using this method before -- adding the managed Google Play Account to the device, otherwise the -- policy will not be applied for a short period of time after adding the -- account to the device. -- -- /See:/ 'devicesUpdate' smart constructor. data DevicesUpdate = DevicesUpdate' { _duXgafv :: !(Maybe Xgafv) , _duUploadProtocol :: !(Maybe Text) , _duUpdateMask :: !(Maybe Text) , _duEnterpriseId :: !Text , _duAccessToken :: !(Maybe Text) , _duUploadType :: !(Maybe Text) , _duPayload :: !Device , _duUserId :: !Text , _duDeviceId :: !Text , _duCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DevicesUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'duXgafv' -- -- * 'duUploadProtocol' -- -- * 'duUpdateMask' -- -- * 'duEnterpriseId' -- -- * 'duAccessToken' -- -- * 'duUploadType' -- -- * 'duPayload' -- -- * 'duUserId' -- -- * 'duDeviceId' -- -- * 'duCallback' devicesUpdate :: Text -- ^ 'duEnterpriseId' -> Device -- ^ 'duPayload' -> Text -- ^ 'duUserId' -> Text -- ^ 'duDeviceId' -> DevicesUpdate devicesUpdate pDuEnterpriseId_ pDuPayload_ pDuUserId_ pDuDeviceId_ = DevicesUpdate' { _duXgafv = Nothing , _duUploadProtocol = Nothing , _duUpdateMask = Nothing , _duEnterpriseId = pDuEnterpriseId_ , _duAccessToken = Nothing , _duUploadType = Nothing , _duPayload = pDuPayload_ , _duUserId = pDuUserId_ , _duDeviceId = pDuDeviceId_ , _duCallback = Nothing } -- | V1 error format. duXgafv :: Lens' DevicesUpdate (Maybe Xgafv) duXgafv = lens _duXgafv (\ s a -> s{_duXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). duUploadProtocol :: Lens' DevicesUpdate (Maybe Text) duUploadProtocol = lens _duUploadProtocol (\ s a -> s{_duUploadProtocol = a}) -- | Mask that identifies which fields to update. If not set, all modifiable -- fields will be modified. When set in a query parameter, this field -- should be specified as updateMask=,,... duUpdateMask :: Lens' DevicesUpdate (Maybe Text) duUpdateMask = lens _duUpdateMask (\ s a -> s{_duUpdateMask = a}) -- | The ID of the enterprise. duEnterpriseId :: Lens' DevicesUpdate Text duEnterpriseId = lens _duEnterpriseId (\ s a -> s{_duEnterpriseId = a}) -- | OAuth access token. duAccessToken :: Lens' DevicesUpdate (Maybe Text) duAccessToken = lens _duAccessToken (\ s a -> s{_duAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). duUploadType :: Lens' DevicesUpdate (Maybe Text) duUploadType = lens _duUploadType (\ s a -> s{_duUploadType = a}) -- | Multipart request metadata. duPayload :: Lens' DevicesUpdate Device duPayload = lens _duPayload (\ s a -> s{_duPayload = a}) -- | The ID of the user. duUserId :: Lens' DevicesUpdate Text duUserId = lens _duUserId (\ s a -> s{_duUserId = a}) -- | The ID of the device. duDeviceId :: Lens' DevicesUpdate Text duDeviceId = lens _duDeviceId (\ s a -> s{_duDeviceId = a}) -- | JSONP duCallback :: Lens' DevicesUpdate (Maybe Text) duCallback = lens _duCallback (\ s a -> s{_duCallback = a}) instance GoogleRequest DevicesUpdate where type Rs DevicesUpdate = Device type Scopes DevicesUpdate = '["https://www.googleapis.com/auth/androidenterprise"] requestClient DevicesUpdate'{..} = go _duEnterpriseId _duUserId _duDeviceId _duXgafv _duUploadProtocol _duUpdateMask _duAccessToken _duUploadType _duCallback (Just AltJSON) _duPayload androidEnterpriseService where go = buildClient (Proxy :: Proxy DevicesUpdateResource) mempty
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Devices/Update.hs
mpl-2.0
7,071
0
23
1,730
1,036
606
430
145
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.CommentAnalyzer -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- The Perspective Comment Analyzer API provides information about the -- potential impact of a comment on a conversation (e.g. it can provide a -- score for the \"toxicity\" of a comment). Users can leverage the -- \"SuggestCommentScore\" method to submit corrections to improve -- Perspective over time. Users can set the \"doNotStore\" flag to ensure -- that all submitted comments are automatically deleted after scores are -- returned. -- -- /See:/ <https://github.com/conversationai/perspectiveapi/blob/master/README.md Perspective Comment Analyzer API Reference> module Network.Google.CommentAnalyzer ( -- * Service Configuration commentAnalyzerService -- * OAuth Scopes , userInfoEmailScope -- * API Declaration , CommentAnalyzerAPI -- * Resources -- ** commentanalyzer.comments.analyze , module Network.Google.Resource.CommentAnalyzer.Comments.Analyze -- ** commentanalyzer.comments.suggestscore , module Network.Google.Resource.CommentAnalyzer.Comments.Suggestscore -- * Types -- ** SpanScore , SpanScore , spanScore , ssBegin , ssScore , ssEnd -- ** AnalyzeCommentResponse , AnalyzeCommentResponse , analyzeCommentResponse , acrDetectedLanguages , acrClientToken , acrLanguages , acrAttributeScores -- ** SuggestCommentScoreResponse , SuggestCommentScoreResponse , suggestCommentScoreResponse , scsrDetectedLanguages , scsrClientToken , scsrRequestedLanguages -- ** Context , Context , context , cEntries , cArticleAndParentComment -- ** Score , Score , score , sValue , sType -- ** ArticleAndParentComment , ArticleAndParentComment , articleAndParentComment , aapcArticle , aapcParentComment -- ** AttributeParameters , AttributeParameters , attributeParameters , apScoreThreshold , apScoreType -- ** TextEntry , TextEntry , textEntry , teText , teType -- ** AttributeScores , AttributeScores , attributeScores , asSummaryScore , asSpanScores -- ** Xgafv , Xgafv (..) -- ** ScoreType , ScoreType (..) -- ** AnalyzeCommentResponseAttributeScores , AnalyzeCommentResponseAttributeScores , analyzeCommentResponseAttributeScores , acrasAddtional -- ** SuggestCommentScoreRequest , SuggestCommentScoreRequest , suggestCommentScoreRequest , sContext , sClientToken , sLanguages , sAttributeScores , sSessionId , sComment , sCommUnityId -- ** AttributeParametersScoreType , AttributeParametersScoreType (..) -- ** AnalyzeCommentRequest , AnalyzeCommentRequest , analyzeCommentRequest , aContext , aClientToken , aSpanAnnotations , aDoNotStore , aLanguages , aRequestedAttributes , aSessionId , aComment , aCommUnityId -- ** SuggestCommentScoreRequestAttributeScores , SuggestCommentScoreRequestAttributeScores , suggestCommentScoreRequestAttributeScores , scsrasAddtional -- ** AnalyzeCommentRequestRequestedAttributes , AnalyzeCommentRequestRequestedAttributes , analyzeCommentRequestRequestedAttributes , acrraAddtional -- ** TextEntryType , TextEntryType (..) ) where import Network.Google.Prelude import Network.Google.CommentAnalyzer.Types import Network.Google.Resource.CommentAnalyzer.Comments.Analyze import Network.Google.Resource.CommentAnalyzer.Comments.Suggestscore {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Perspective Comment Analyzer API service. type CommentAnalyzerAPI = CommentsSuggestscoreResource :<|> CommentsAnalyzeResource
brendanhay/gogol
gogol-commentanalyzer/gen/Network/Google/CommentAnalyzer.hs
mpl-2.0
4,253
0
5
908
363
264
99
92
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.Speech.Speech.Recognize -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Performs synchronous speech recognition: receive results after all audio -- has been sent and processed. -- -- /See:/ <https://cloud.google.com/speech-to-text/docs/quickstart-protocol Cloud Speech-to-Text API Reference> for @speech.speech.recognize@. module Network.Google.Resource.Speech.Speech.Recognize ( -- * REST Resource SpeechRecognizeResource -- * Creating a Request , speechRecognize , SpeechRecognize -- * Request Lenses , srXgafv , srUploadProtocol , srAccessToken , srUploadType , srPayload , srCallback ) where import Network.Google.Prelude import Network.Google.Speech.Types -- | A resource alias for @speech.speech.recognize@ method which the -- 'SpeechRecognize' request conforms to. type SpeechRecognizeResource = "v1p1beta1" :> "speech:recognize" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] RecognizeRequest :> Post '[JSON] RecognizeResponse -- | Performs synchronous speech recognition: receive results after all audio -- has been sent and processed. -- -- /See:/ 'speechRecognize' smart constructor. data SpeechRecognize = SpeechRecognize' { _srXgafv :: !(Maybe Xgafv) , _srUploadProtocol :: !(Maybe Text) , _srAccessToken :: !(Maybe Text) , _srUploadType :: !(Maybe Text) , _srPayload :: !RecognizeRequest , _srCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SpeechRecognize' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srXgafv' -- -- * 'srUploadProtocol' -- -- * 'srAccessToken' -- -- * 'srUploadType' -- -- * 'srPayload' -- -- * 'srCallback' speechRecognize :: RecognizeRequest -- ^ 'srPayload' -> SpeechRecognize speechRecognize pSrPayload_ = SpeechRecognize' { _srXgafv = Nothing , _srUploadProtocol = Nothing , _srAccessToken = Nothing , _srUploadType = Nothing , _srPayload = pSrPayload_ , _srCallback = Nothing } -- | V1 error format. srXgafv :: Lens' SpeechRecognize (Maybe Xgafv) srXgafv = lens _srXgafv (\ s a -> s{_srXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). srUploadProtocol :: Lens' SpeechRecognize (Maybe Text) srUploadProtocol = lens _srUploadProtocol (\ s a -> s{_srUploadProtocol = a}) -- | OAuth access token. srAccessToken :: Lens' SpeechRecognize (Maybe Text) srAccessToken = lens _srAccessToken (\ s a -> s{_srAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). srUploadType :: Lens' SpeechRecognize (Maybe Text) srUploadType = lens _srUploadType (\ s a -> s{_srUploadType = a}) -- | Multipart request metadata. srPayload :: Lens' SpeechRecognize RecognizeRequest srPayload = lens _srPayload (\ s a -> s{_srPayload = a}) -- | JSONP srCallback :: Lens' SpeechRecognize (Maybe Text) srCallback = lens _srCallback (\ s a -> s{_srCallback = a}) instance GoogleRequest SpeechRecognize where type Rs SpeechRecognize = RecognizeResponse type Scopes SpeechRecognize = '["https://www.googleapis.com/auth/cloud-platform"] requestClient SpeechRecognize'{..} = go _srXgafv _srUploadProtocol _srAccessToken _srUploadType _srCallback (Just AltJSON) _srPayload speechService where go = buildClient (Proxy :: Proxy SpeechRecognizeResource) mempty
brendanhay/gogol
gogol-speech/gen/Network/Google/Resource/Speech/Speech/Recognize.hs
mpl-2.0
4,663
0
16
1,130
705
412
293
102
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.Types -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. module Network.AWS.EC2.Types ( -- * Service EC2 -- ** Error , EC2Error -- ** XML , ns -- * ImageAttributeName , ImageAttributeName (..) -- * PermissionGroup , PermissionGroup (..) -- * NetworkAclEntry , NetworkAclEntry , networkAclEntry , naeCidrBlock , naeEgress , naeIcmpTypeCode , naePortRange , naeProtocol , naeRuleAction , naeRuleNumber -- * BlobAttributeValue , BlobAttributeValue , blobAttributeValue , bavValue -- * ImportInstanceLaunchSpecification , ImportInstanceLaunchSpecification , importInstanceLaunchSpecification , iilsAdditionalInfo , iilsArchitecture , iilsGroupIds , iilsGroupNames , iilsInstanceInitiatedShutdownBehavior , iilsInstanceType , iilsMonitoring , iilsPlacement , iilsPrivateIpAddress , iilsSubnetId , iilsUserData -- * Snapshot , Snapshot , snapshot , sDescription , sEncrypted , sKmsKeyId , sOwnerAlias , sOwnerId , sProgress , sSnapshotId , sStartTime , sState , sTags , sVolumeId , sVolumeSize -- * SpotInstanceStateFault , SpotInstanceStateFault , spotInstanceStateFault , sisfCode , sisfMessage -- * TagDescription , TagDescription , tagDescription , tdKey , tdResourceId , tdResourceType , tdValue -- * GroupIdentifier , GroupIdentifier , groupIdentifier , giGroupId , giGroupName -- * VpnStaticRouteSource , VpnStaticRouteSource (..) -- * ReservedInstancesListing , ReservedInstancesListing , reservedInstancesListing , rilClientToken , rilCreateDate , rilInstanceCounts , rilPriceSchedules , rilReservedInstancesId , rilReservedInstancesListingId , rilStatus , rilStatusMessage , rilTags , rilUpdateDate -- * InstanceLifecycleType , InstanceLifecycleType (..) -- * VirtualizationType , VirtualizationType (..) -- * NetworkInterfaceStatus , NetworkInterfaceStatus (..) -- * PlatformValues , PlatformValues (..) -- * CreateVolumePermission , CreateVolumePermission , createVolumePermission , cvpGroup , cvpUserId -- * NetworkInterfaceAttachmentChanges , NetworkInterfaceAttachmentChanges , networkInterfaceAttachmentChanges , niacAttachmentId , niacDeleteOnTermination -- * RecurringChargeFrequency , RecurringChargeFrequency (..) -- * DhcpOptions , DhcpOptions , dhcpOptions , doDhcpConfigurations , doDhcpOptionsId , doTags -- * InstanceNetworkInterfaceSpecification , InstanceNetworkInterfaceSpecification , instanceNetworkInterfaceSpecification , inisAssociatePublicIpAddress , inisDeleteOnTermination , inisDescription , inisDeviceIndex , inisGroups , inisNetworkInterfaceId , inisPrivateIpAddress , inisPrivateIpAddresses , inisSecondaryPrivateIpAddressCount , inisSubnetId -- * VolumeState , VolumeState (..) -- * AttributeValue , AttributeValue , attributeValue , avValue -- * PrivateIpAddressSpecification , PrivateIpAddressSpecification , privateIpAddressSpecification , piasPrimary , piasPrivateIpAddress -- * Image , Image , image , iArchitecture , iBlockDeviceMappings , iCreationDate , iDescription , iHypervisor , iImageId , iImageLocation , iImageOwnerAlias , iImageType , iKernelId , iName , iOwnerId , iPlatform , iProductCodes , iPublic , iRamdiskId , iRootDeviceName , iRootDeviceType , iSriovNetSupport , iState , iStateReason , iTags , iVirtualizationType -- * DhcpConfiguration , DhcpConfiguration , dhcpConfiguration , dcKey , dcValues -- * Tag , Tag , tag , tagKey , tagValue -- * AccountAttributeName , AccountAttributeName (..) -- * NetworkInterfaceAttachment , NetworkInterfaceAttachment , networkInterfaceAttachment , niaAttachTime , niaAttachmentId , niaDeleteOnTermination , niaDeviceIndex , niaInstanceId , niaInstanceOwnerId , niaStatus -- * RunInstancesMonitoringEnabled , RunInstancesMonitoringEnabled , runInstancesMonitoringEnabled , rimeEnabled -- * VolumeStatusInfo , VolumeStatusInfo , volumeStatusInfo , vsiDetails , vsiStatus -- * NetworkInterfaceAssociation , NetworkInterfaceAssociation , networkInterfaceAssociation , niaAllocationId , niaAssociationId , niaIpOwnerId , niaPublicDnsName , niaPublicIp -- * CreateVolumePermissionModifications , CreateVolumePermissionModifications , createVolumePermissionModifications , cvpmAdd , cvpmRemove -- * VpcState , VpcState (..) -- * ResourceType , ResourceType (..) -- * ReportStatusType , ReportStatusType (..) -- * CurrencyCodeValues , CurrencyCodeValues (..) -- * IcmpTypeCode , IcmpTypeCode , icmpTypeCode , itcCode , itcType -- * InstanceCount , InstanceCount , instanceCount , icInstanceCount , icState -- * ExportToS3Task , ExportToS3Task , exportToS3Task , etstContainerFormat , etstDiskImageFormat , etstS3Bucket , etstS3Key -- * BlockDeviceMapping , BlockDeviceMapping , blockDeviceMapping , bdmDeviceName , bdmEbs , bdmNoDevice , bdmVirtualName -- * ConversionTask , ConversionTask , conversionTask , ctConversionTaskId , ctExpirationTime , ctImportInstance , ctImportVolume , ctState , ctStatusMessage , ctTags -- * AttachmentStatus , AttachmentStatus (..) -- * ClassicLinkInstance , ClassicLinkInstance , classicLinkInstance , cliGroups , cliInstanceId , cliTags , cliVpcId -- * RouteOrigin , RouteOrigin (..) -- * ListingState , ListingState (..) -- * SpotPrice , SpotPrice , spotPrice , spAvailabilityZone , spInstanceType , spProductDescription , spSpotPrice , spTimestamp -- * InstanceMonitoring , InstanceMonitoring , instanceMonitoring , imInstanceId , imMonitoring -- * PriceScheduleSpecification , PriceScheduleSpecification , priceScheduleSpecification , pssCurrencyCode , pssPrice , pssTerm -- * SpotInstanceStatus , SpotInstanceStatus , spotInstanceStatus , sisCode , sisMessage , sisUpdateTime -- * AvailabilityZoneState , AvailabilityZoneState (..) -- * SpotInstanceRequest , SpotInstanceRequest , spotInstanceRequest , siAvailabilityZoneGroup , siCreateTime , siFault , siInstanceId , siLaunchGroup , siLaunchSpecification , siLaunchedAvailabilityZone , siProductDescription , siSpotInstanceRequestId , siSpotPrice , siState , siStatus , siTags , siType , siValidFrom , siValidUntil -- * LaunchSpecification , LaunchSpecification , launchSpecification , lsAddressingType , lsBlockDeviceMappings , lsEbsOptimized , lsIamInstanceProfile , lsImageId , lsInstanceType , lsKernelId , lsKeyName , lsMonitoring , lsNetworkInterfaces , lsPlacement , lsRamdiskId , lsSecurityGroups , lsSubnetId , lsUserData -- * VolumeStatusEvent , VolumeStatusEvent , volumeStatusEvent , vseDescription , vseEventId , vseEventType , vseNotAfter , vseNotBefore -- * Volume , Volume , volume , vAttachments , vAvailabilityZone , vCreateTime , vEncrypted , vIops , vKmsKeyId , vSize , vSnapshotId , vState , vTags , vVolumeId , vVolumeType -- * Reservation , Reservation , reservation , rGroups , rInstances , rOwnerId , rRequesterId , rReservationId -- * ImportInstanceVolumeDetailItem , ImportInstanceVolumeDetailItem , importInstanceVolumeDetailItem , iivdiAvailabilityZone , iivdiBytesConverted , iivdiDescription , iivdiImage , iivdiStatus , iivdiStatusMessage , iivdiVolume -- * SummaryStatus , SummaryStatus (..) -- * ReservedInstancesModification , ReservedInstancesModification , reservedInstancesModification , rimClientToken , rimCreateDate , rimEffectiveDate , rimModificationResults , rimReservedInstancesIds , rimReservedInstancesModificationId , rimStatus , rimStatusMessage , rimUpdateDate -- * RuleAction , RuleAction (..) -- * NetworkInterface , NetworkInterface , networkInterface , niAssociation , niAttachment , niAvailabilityZone , niDescription , niGroups , niMacAddress , niNetworkInterfaceId , niOwnerId , niPrivateDnsName , niPrivateIpAddress , niPrivateIpAddresses , niRequesterId , niRequesterManaged , niSourceDestCheck , niStatus , niSubnetId , niTagSet , niVpcId -- * TelemetryStatus , TelemetryStatus (..) -- * Subnet , Subnet , subnet , s1AvailabilityZone , s1AvailableIpAddressCount , s1CidrBlock , s1DefaultForAz , s1MapPublicIpOnLaunch , s1State , s1SubnetId , s1Tags , s1VpcId -- * KeyPairInfo , KeyPairInfo , keyPairInfo , kpiKeyFingerprint , kpiKeyName -- * LaunchPermissionModifications , LaunchPermissionModifications , launchPermissionModifications , lpmAdd , lpmRemove -- * SnapshotState , SnapshotState (..) -- * InstanceNetworkInterfaceAssociation , InstanceNetworkInterfaceAssociation , instanceNetworkInterfaceAssociation , iniaIpOwnerId , iniaPublicDnsName , iniaPublicIp -- * DiskImageDetail , DiskImageDetail , diskImageDetail , didBytes , didFormat , didImportManifestUrl -- * InstancePrivateIpAddress , InstancePrivateIpAddress , instancePrivateIpAddress , ipiaAssociation , ipiaPrimary , ipiaPrivateDnsName , ipiaPrivateIpAddress -- * CancelledSpotInstanceRequest , CancelledSpotInstanceRequest , cancelledSpotInstanceRequest , csiSpotInstanceRequestId , csiState -- * VpnConnectionOptionsSpecification , VpnConnectionOptionsSpecification , vpnConnectionOptionsSpecification , vcosStaticRoutesOnly -- * Address , Address , address , aAllocationId , aAssociationId , aDomain , aInstanceId , aNetworkInterfaceId , aNetworkInterfaceOwnerId , aPrivateIpAddress , aPublicIp -- * VolumeAttachmentState , VolumeAttachmentState (..) -- * LaunchPermission , LaunchPermission , launchPermission , lpGroup , lpUserId -- * RouteState , RouteState (..) -- * RouteTableAssociation , RouteTableAssociation , routeTableAssociation , rtaMain , rtaRouteTableAssociationId , rtaRouteTableId , rtaSubnetId -- * BundleTaskState , BundleTaskState (..) -- * PortRange , PortRange , portRange , prFrom , prTo -- * VpcAttributeName , VpcAttributeName (..) -- * ReservedInstancesConfiguration , ReservedInstancesConfiguration , reservedInstancesConfiguration , ricAvailabilityZone , ricInstanceCount , ricInstanceType , ricPlatform -- * VolumeStatusDetails , VolumeStatusDetails , volumeStatusDetails , vsdName , vsdStatus -- * SpotInstanceState , SpotInstanceState (..) -- * VpnConnectionOptions , VpnConnectionOptions , vpnConnectionOptions , vcoStaticRoutesOnly -- * UserIdGroupPair , UserIdGroupPair , userIdGroupPair , uigpGroupId , uigpGroupName , uigpUserId -- * InstanceStatusSummary , InstanceStatusSummary , instanceStatusSummary , issDetails , issStatus -- * SpotPlacement , SpotPlacement , spotPlacement , sp1AvailabilityZone , sp1GroupName -- * EbsInstanceBlockDeviceSpecification , EbsInstanceBlockDeviceSpecification , ebsInstanceBlockDeviceSpecification , eibdsDeleteOnTermination , eibdsVolumeId -- * NetworkAclAssociation , NetworkAclAssociation , networkAclAssociation , naaNetworkAclAssociationId , naaNetworkAclId , naaSubnetId -- * BundleTask , BundleTask , bundleTask , btBundleId , btBundleTaskError , btInstanceId , btProgress , btStartTime , btState , btStorage , btUpdateTime -- * InstanceStatusEvent , InstanceStatusEvent , instanceStatusEvent , iseCode , iseDescription , iseNotAfter , iseNotBefore -- * InstanceType , InstanceType (..) -- * Route , Route , route , rDestinationCidrBlock , rGatewayId , rInstanceId , rInstanceOwnerId , rNetworkInterfaceId , rOrigin , rState , rVpcPeeringConnectionId -- * SpotDatafeedSubscription , SpotDatafeedSubscription , spotDatafeedSubscription , sdsBucket , sdsFault , sdsOwnerId , sdsPrefix , sdsState -- * Storage , Storage , storage , sS3 -- * SecurityGroup , SecurityGroup , securityGroup , sgDescription , sgGroupId , sgGroupName , sgIpPermissions , sgIpPermissionsEgress , sgOwnerId , sgTags , sgVpcId -- * CancelSpotInstanceRequestState , CancelSpotInstanceRequestState (..) -- * PlacementGroupState , PlacementGroupState (..) -- * ReservedInstancesModificationResult , ReservedInstancesModificationResult , reservedInstancesModificationResult , rimrReservedInstancesId , rimrTargetConfiguration -- * InstanceBlockDeviceMappingSpecification , InstanceBlockDeviceMappingSpecification , instanceBlockDeviceMappingSpecification , ibdmsDeviceName , ibdmsEbs , ibdmsNoDevice , ibdmsVirtualName -- * ExportEnvironment , ExportEnvironment (..) -- * UserData , UserData , userData , udData -- * VolumeAttachment , VolumeAttachment , volumeAttachment , vaAttachTime , vaDeleteOnTermination , vaDevice , vaInstanceId , vaState , vaVolumeId -- * CustomerGateway , CustomerGateway , customerGateway , cgBgpAsn , cgCustomerGatewayId , cgIpAddress , cgState , cgTags , cgType -- * EbsInstanceBlockDevice , EbsInstanceBlockDevice , ebsInstanceBlockDevice , eibdAttachTime , eibdDeleteOnTermination , eibdStatus , eibdVolumeId -- * ShutdownBehavior , ShutdownBehavior (..) -- * DiskImageDescription , DiskImageDescription , diskImageDescription , did1Checksum , did1Format , did1ImportManifestUrl , did1Size -- * DiskImageVolumeDescription , DiskImageVolumeDescription , diskImageVolumeDescription , divdId , divdSize -- * Monitoring , Monitoring , monitoring , mState -- * SubnetState , SubnetState (..) -- * ContainerFormat , ContainerFormat (..) -- * AvailabilityZoneMessage , AvailabilityZoneMessage , availabilityZoneMessage , azmMessage -- * VpcAttachment , VpcAttachment , vpcAttachment , va1State , va1VpcId -- * InstanceBlockDeviceMapping , InstanceBlockDeviceMapping , instanceBlockDeviceMapping , ibdmDeviceName , ibdmEbs -- * StatusType , StatusType (..) -- * ExportToS3TaskSpecification , ExportToS3TaskSpecification , exportToS3TaskSpecification , etstsContainerFormat , etstsDiskImageFormat , etstsS3Bucket , etstsS3Prefix -- * NetworkInterfaceAttribute , NetworkInterfaceAttribute (..) -- * ImageTypeValues , ImageTypeValues (..) -- * InstanceExportDetails , InstanceExportDetails , instanceExportDetails , iedInstanceId , iedTargetEnvironment -- * SnapshotAttributeName , SnapshotAttributeName (..) -- * AvailabilityZone , AvailabilityZone , availabilityZone , azMessages , azRegionName , azState , azZoneName -- * VpnState , VpnState (..) -- * RouteTable , RouteTable , routeTable , rtAssociations , rtPropagatingVgws , rtRouteTableId , rtRoutes , rtTags , rtVpcId -- * HypervisorType , HypervisorType (..) -- * InstanceStatusDetails , InstanceStatusDetails , instanceStatusDetails , isdImpairedSince , isdName , isdStatus -- * IamInstanceProfile , IamInstanceProfile , iamInstanceProfile , iipArn , iipId -- * InternetGatewayAttachment , InternetGatewayAttachment , internetGatewayAttachment , igaState , igaVpcId -- * ReservedInstanceState , ReservedInstanceState (..) -- * InstanceAttributeName , InstanceAttributeName (..) -- * IpPermission , IpPermission , ipPermission , ipFromPort , ipIpProtocol , ipIpRanges , ipToPort , ipUserIdGroupPairs -- * ConversionTaskState , ConversionTaskState (..) -- * DiskImage , DiskImage , diskImage , diDescription , diImage , diVolume -- * Tenancy , Tenancy (..) -- * VpcPeeringConnectionStateReason , VpcPeeringConnectionStateReason , vpcPeeringConnectionStateReason , vpcsrCode , vpcsrMessage -- * IamInstanceProfileSpecification , IamInstanceProfileSpecification , iamInstanceProfileSpecification , iipsArn , iipsName -- * ImportVolumeTaskDetails , ImportVolumeTaskDetails , importVolumeTaskDetails , ivtdAvailabilityZone , ivtdBytesConverted , ivtdDescription , ivtdImage , ivtdVolume -- * PlacementStrategy , PlacementStrategy (..) -- * InstanceNetworkInterface , InstanceNetworkInterface , instanceNetworkInterface , iniAssociation , iniAttachment , iniDescription , iniGroups , iniMacAddress , iniNetworkInterfaceId , iniOwnerId , iniPrivateDnsName , iniPrivateIpAddress , iniPrivateIpAddresses , iniSourceDestCheck , iniStatus , iniSubnetId , iniVpcId -- * VolumeStatusAction , VolumeStatusAction , volumeStatusAction , vsaCode , vsaDescription , vsaEventId , vsaEventType -- * VpcPeeringConnectionVpcInfo , VpcPeeringConnectionVpcInfo , vpcPeeringConnectionVpcInfo , vpcviCidrBlock , vpcviOwnerId , vpcviVpcId -- * ReservedInstanceLimitPrice , ReservedInstanceLimitPrice , reservedInstanceLimitPrice , rilpAmount , rilpCurrencyCode -- * Vpc , Vpc , vpc , vpcCidrBlock , vpcDhcpOptionsId , vpcInstanceTenancy , vpcIsDefault , vpcState , vpcTags , vpcVpcId -- * InstanceStatus , InstanceStatus , instanceStatus , isAvailabilityZone , isEvents , isInstanceId , isInstanceState , isInstanceStatus , isSystemStatus -- * ArchitectureValues , ArchitectureValues (..) -- * ReportInstanceReasonCodes , ReportInstanceReasonCodes (..) -- * EbsBlockDevice , EbsBlockDevice , ebsBlockDevice , ebdDeleteOnTermination , ebdEncrypted , ebdIops , ebdSnapshotId , ebdVolumeSize , ebdVolumeType -- * AccountAttribute , AccountAttribute , accountAttribute , aaAttributeName , aaAttributeValues -- * PriceSchedule , PriceSchedule , priceSchedule , psActive , psCurrencyCode , psPrice , psTerm -- * DeviceType , DeviceType (..) -- * DomainType , DomainType (..) -- * Region , Region , region , rEndpoint , rRegionName -- * PropagatingVgw , PropagatingVgw , propagatingVgw , pvGatewayId -- * OfferingTypeValues , OfferingTypeValues (..) -- * VpnGateway , VpnGateway , vpnGateway , vgAvailabilityZone , vgState , vgTags , vgType , vgVpcAttachments , vgVpnGatewayId -- * Filter , Filter , filter' , fName , fValues -- * VolumeType , VolumeType (..) -- * InstanceStateChange , InstanceStateChange , instanceStateChange , iscCurrentState , iscInstanceId , iscPreviousState -- * NetworkAcl , NetworkAcl , networkAcl , naAssociations , naEntries , naIsDefault , naNetworkAclId , naTags , naVpcId -- * ImageState , ImageState (..) -- * GatewayType , GatewayType (..) -- * InstanceNetworkInterfaceAttachment , InstanceNetworkInterfaceAttachment , instanceNetworkInterfaceAttachment , iniaAttachTime , iniaAttachmentId , iniaDeleteOnTermination , iniaDeviceIndex , iniaStatus -- * AttributeBooleanValue , AttributeBooleanValue , attributeBooleanValue , abvValue -- * RecurringCharge , RecurringCharge , recurringCharge , rcAmount , rcFrequency -- * NewDhcpConfiguration , NewDhcpConfiguration , newDhcpConfiguration , ndcKey , ndcValues -- * StateReason , StateReason , stateReason , srCode , srMessage -- * MonitoringState , MonitoringState (..) -- * ReservedInstancesId , ReservedInstancesId , reservedInstancesId , riiReservedInstancesId -- * StatusName , StatusName (..) -- * InternetGateway , InternetGateway , internetGateway , igAttachments , igInternetGatewayId , igTags -- * VolumeStatusName , VolumeStatusName (..) -- * VolumeAttributeName , VolumeAttributeName (..) -- * ImportInstanceTaskDetails , ImportInstanceTaskDetails , importInstanceTaskDetails , iitdDescription , iitdInstanceId , iitdPlatform , iitdVolumes -- * PlacementGroup , PlacementGroup , placementGroup , pgGroupName , pgState , pgStrategy -- * ProductCode , ProductCode , productCode , pcProductCodeId , pcProductCodeType -- * ListingStatus , ListingStatus (..) -- * IpRange , IpRange , ipRange , irCidrIp -- * VolumeStatusInfoStatus , VolumeStatusInfoStatus (..) -- * AccountAttributeValue , AccountAttributeValue , accountAttributeValue , aavAttributeValue -- * RIProductDescription , RIProductDescription (..) -- * ReservedInstancesOffering , ReservedInstancesOffering , reservedInstancesOffering , rioAvailabilityZone , rioCurrencyCode , rioDuration , rioFixedPrice , rioInstanceTenancy , rioInstanceType , rioMarketplace , rioOfferingType , rioPricingDetails , rioProductDescription , rioRecurringCharges , rioReservedInstancesOfferingId , rioUsagePrice -- * ReservedInstances , ReservedInstances , reservedInstances , ri1AvailabilityZone , ri1CurrencyCode , ri1Duration , ri1End , ri1FixedPrice , ri1InstanceCount , ri1InstanceTenancy , ri1InstanceType , ri1OfferingType , ri1ProductDescription , ri1RecurringCharges , ri1ReservedInstancesId , ri1Start , ri1State , ri1Tags , ri1UsagePrice -- * DatafeedSubscriptionState , DatafeedSubscriptionState (..) -- * ExportTaskState , ExportTaskState (..) -- * ProductCodeValues , ProductCodeValues (..) -- * VpnConnection , VpnConnection , vpnConnection , vcCustomerGatewayConfiguration , vcCustomerGatewayId , vcOptions , vcRoutes , vcState , vcTags , vcType , vcVgwTelemetry , vcVpnConnectionId , vcVpnGatewayId -- * InstanceState , InstanceState , instanceState , isCode , isName -- * Placement , Placement , placement , pAvailabilityZone , pGroupName , pTenancy -- * EventCode , EventCode (..) -- * SpotInstanceType , SpotInstanceType (..) -- * VpcPeeringConnection , VpcPeeringConnection , vpcPeeringConnection , vpc1AccepterVpcInfo , vpc1ExpirationTime , vpc1RequesterVpcInfo , vpc1Status , vpc1Tags , vpc1VpcPeeringConnectionId -- * S3Storage , S3Storage , s3Storage , ssAWSAccessKeyId , ssBucket , ssPrefix , ssUploadPolicy , ssUploadPolicySignature -- * VgwTelemetry , VgwTelemetry , vgwTelemetry , vtAcceptedRouteCount , vtLastStatusChange , vtOutsideIpAddress , vtStatus , vtStatusMessage -- * VpnStaticRoute , VpnStaticRoute , vpnStaticRoute , vsrDestinationCidrBlock , vsrSource , vsrState -- * InstanceStateName , InstanceStateName (..) -- * Instance , Instance , instance' , i1AmiLaunchIndex , i1Architecture , i1BlockDeviceMappings , i1ClientToken , i1EbsOptimized , i1Hypervisor , i1IamInstanceProfile , i1ImageId , i1InstanceId , i1InstanceLifecycle , i1InstanceType , i1KernelId , i1KeyName , i1LaunchTime , i1Monitoring , i1NetworkInterfaces , i1Placement , i1Platform , i1PrivateDnsName , i1PrivateIpAddress , i1ProductCodes , i1PublicDnsName , i1PublicIpAddress , i1RamdiskId , i1RootDeviceName , i1RootDeviceType , i1SecurityGroups , i1SourceDestCheck , i1SpotInstanceRequestId , i1SriovNetSupport , i1State , i1StateReason , i1StateTransitionReason , i1SubnetId , i1Tags , i1VirtualizationType , i1VpcId -- * ExportTask , ExportTask , exportTask , etDescription , etExportTaskId , etExportToS3Task , etInstanceExportDetails , etState , etStatusMessage -- * ResetImageAttributeName , ResetImageAttributeName (..) -- * RequestSpotLaunchSpecification , RequestSpotLaunchSpecification , requestSpotLaunchSpecification , rslsAddressingType , rslsBlockDeviceMappings , rslsEbsOptimized , rslsIamInstanceProfile , rslsImageId , rslsInstanceType , rslsKernelId , rslsKeyName , rslsMonitoring , rslsNetworkInterfaces , rslsPlacement , rslsRamdiskId , rslsSecurityGroupIds , rslsSecurityGroups , rslsSubnetId , rslsUserData -- * VolumeDetail , VolumeDetail , volumeDetail , vdSize -- * PricingDetail , PricingDetail , pricingDetail , pdCount , pdPrice -- * NetworkInterfacePrivateIpAddress , NetworkInterfacePrivateIpAddress , networkInterfacePrivateIpAddress , nipiaAssociation , nipiaPrimary , nipiaPrivateDnsName , nipiaPrivateIpAddress -- * DiskImageFormat , DiskImageFormat (..) -- * BundleTaskError , BundleTaskError , bundleTaskError , bteCode , bteMessage -- * VpcClassicLink , VpcClassicLink , vpcClassicLink , vclClassicLinkEnabled , vclTags , vclVpcId -- * VolumeStatusItem , VolumeStatusItem , volumeStatusItem , vsiActions , vsiAvailabilityZone , vsiEvents , vsiVolumeId , vsiVolumeStatus -- * Common , module Network.AWS.EC2.Internal ) where import Network.AWS.Prelude import Network.AWS.Signing import Network.AWS.EC2.Internal import qualified GHC.Exts -- | Version @2014-10-01@ of the Amazon Elastic Compute Cloud service. data EC2 instance AWSService EC2 where type Sg EC2 = V4 type Er EC2 = EC2Error service = service' where service' :: Service EC2 service' = Service { _svcAbbrev = "EC2" , _svcPrefix = "ec2" , _svcVersion = "2014-10-01" , _svcTargetPrefix = Nothing , _svcJSONVersion = Nothing , _svcHandle = handle , _svcRetry = retry } handle :: Status -> Maybe (LazyByteString -> ServiceError EC2Error) handle = restError statusSuccess service' retry :: Retry EC2 retry = Exponential { _retryBase = 0.05 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check :: Status -> EC2Error -> Bool check (statusCode -> s) (awsErrorCode -> e) | s == 503 && "RequestLimitExceeded" == e = True -- Request Limit Exceeded | s == 500 = True -- General Server Error | s == 509 = True -- Limit Exceeded | s == 503 = True -- Service Unavailable | otherwise = False ns :: Text ns = "http://ec2.amazonaws.com/doc/2014-10-01" {-# INLINE ns #-} data ImageAttributeName = ImageBlockDeviceMapping -- ^ blockDeviceMapping | ImageDescription -- ^ description | ImageKernel -- ^ kernel | ImageLaunchPermission -- ^ launchPermission | ImageProductCodes -- ^ productCodes | ImageRamdisk -- ^ ramdisk deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ImageAttributeName instance FromText ImageAttributeName where parser = takeLowerText >>= \case "blockdevicemapping" -> pure ImageBlockDeviceMapping "description" -> pure ImageDescription "kernel" -> pure ImageKernel "launchpermission" -> pure ImageLaunchPermission "productcodes" -> pure ImageProductCodes "ramdisk" -> pure ImageRamdisk e -> fail $ "Failure parsing ImageAttributeName from " ++ show e instance ToText ImageAttributeName where toText = \case ImageBlockDeviceMapping -> "blockDeviceMapping" ImageDescription -> "description" ImageKernel -> "kernel" ImageLaunchPermission -> "launchPermission" ImageProductCodes -> "productCodes" ImageRamdisk -> "ramdisk" instance ToByteString ImageAttributeName instance ToHeader ImageAttributeName instance ToQuery ImageAttributeName instance FromXML ImageAttributeName where parseXML = parseXMLText "ImageAttributeName" data PermissionGroup = All -- ^ all deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable PermissionGroup instance FromText PermissionGroup where parser = takeLowerText >>= \case "all" -> pure All e -> fail $ "Failure parsing PermissionGroup from " ++ show e instance ToText PermissionGroup where toText All = "all" instance ToByteString PermissionGroup instance ToHeader PermissionGroup instance ToQuery PermissionGroup instance FromXML PermissionGroup where parseXML = parseXMLText "PermissionGroup" data NetworkAclEntry = NetworkAclEntry { _naeCidrBlock :: Maybe Text , _naeEgress :: Maybe Bool , _naeIcmpTypeCode :: Maybe IcmpTypeCode , _naePortRange :: Maybe PortRange , _naeProtocol :: Maybe Text , _naeRuleAction :: Maybe RuleAction , _naeRuleNumber :: Maybe Int } deriving (Eq, Read, Show) -- | 'NetworkAclEntry' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'naeCidrBlock' @::@ 'Maybe' 'Text' -- -- * 'naeEgress' @::@ 'Maybe' 'Bool' -- -- * 'naeIcmpTypeCode' @::@ 'Maybe' 'IcmpTypeCode' -- -- * 'naePortRange' @::@ 'Maybe' 'PortRange' -- -- * 'naeProtocol' @::@ 'Maybe' 'Text' -- -- * 'naeRuleAction' @::@ 'Maybe' 'RuleAction' -- -- * 'naeRuleNumber' @::@ 'Maybe' 'Int' -- networkAclEntry :: NetworkAclEntry networkAclEntry = NetworkAclEntry { _naeRuleNumber = Nothing , _naeProtocol = Nothing , _naeRuleAction = Nothing , _naeEgress = Nothing , _naeCidrBlock = Nothing , _naeIcmpTypeCode = Nothing , _naePortRange = Nothing } -- | The network range to allow or deny, in CIDR notation. naeCidrBlock :: Lens' NetworkAclEntry (Maybe Text) naeCidrBlock = lens _naeCidrBlock (\s a -> s { _naeCidrBlock = a }) -- | Indicates whether the rule is an egress rule (applied to traffic leaving the -- subnet). naeEgress :: Lens' NetworkAclEntry (Maybe Bool) naeEgress = lens _naeEgress (\s a -> s { _naeEgress = a }) -- | ICMP protocol: The ICMP type and code. naeIcmpTypeCode :: Lens' NetworkAclEntry (Maybe IcmpTypeCode) naeIcmpTypeCode = lens _naeIcmpTypeCode (\s a -> s { _naeIcmpTypeCode = a }) -- | TCP or UDP protocols: The range of ports the rule applies to. naePortRange :: Lens' NetworkAclEntry (Maybe PortRange) naePortRange = lens _naePortRange (\s a -> s { _naePortRange = a }) -- | The protocol. A value of '-1' means all protocols. naeProtocol :: Lens' NetworkAclEntry (Maybe Text) naeProtocol = lens _naeProtocol (\s a -> s { _naeProtocol = a }) -- | Indicates whether to allow or deny the traffic that matches the rule. naeRuleAction :: Lens' NetworkAclEntry (Maybe RuleAction) naeRuleAction = lens _naeRuleAction (\s a -> s { _naeRuleAction = a }) -- | The rule number for the entry. ACL entries are processed in ascending order -- by rule number. naeRuleNumber :: Lens' NetworkAclEntry (Maybe Int) naeRuleNumber = lens _naeRuleNumber (\s a -> s { _naeRuleNumber = a }) instance FromXML NetworkAclEntry where parseXML x = NetworkAclEntry <$> x .@? "cidrBlock" <*> x .@? "egress" <*> x .@? "icmpTypeCode" <*> x .@? "portRange" <*> x .@? "protocol" <*> x .@? "ruleAction" <*> x .@? "ruleNumber" instance ToQuery NetworkAclEntry where toQuery NetworkAclEntry{..} = mconcat [ "CidrBlock" =? _naeCidrBlock , "Egress" =? _naeEgress , "IcmpTypeCode" =? _naeIcmpTypeCode , "PortRange" =? _naePortRange , "Protocol" =? _naeProtocol , "RuleAction" =? _naeRuleAction , "RuleNumber" =? _naeRuleNumber ] newtype BlobAttributeValue = BlobAttributeValue { _bavValue :: Maybe Base64 } deriving (Eq, Read, Show) -- | 'BlobAttributeValue' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'bavValue' @::@ 'Maybe' 'Base64' -- blobAttributeValue :: BlobAttributeValue blobAttributeValue = BlobAttributeValue { _bavValue = Nothing } bavValue :: Lens' BlobAttributeValue (Maybe Base64) bavValue = lens _bavValue (\s a -> s { _bavValue = a }) instance FromXML BlobAttributeValue where parseXML x = BlobAttributeValue <$> x .@? "value" instance ToQuery BlobAttributeValue where toQuery BlobAttributeValue{..} = mconcat [ "Value" =? _bavValue ] data ImportInstanceLaunchSpecification = ImportInstanceLaunchSpecification { _iilsAdditionalInfo :: Maybe Text , _iilsArchitecture :: Maybe ArchitectureValues , _iilsGroupIds :: List "SecurityGroupId" Text , _iilsGroupNames :: List "SecurityGroup" Text , _iilsInstanceInitiatedShutdownBehavior :: Maybe ShutdownBehavior , _iilsInstanceType :: Maybe InstanceType , _iilsMonitoring :: Maybe Bool , _iilsPlacement :: Maybe Placement , _iilsPrivateIpAddress :: Maybe Text , _iilsSubnetId :: Maybe Text , _iilsUserData :: Maybe UserData } deriving (Eq, Read, Show) -- | 'ImportInstanceLaunchSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iilsAdditionalInfo' @::@ 'Maybe' 'Text' -- -- * 'iilsArchitecture' @::@ 'Maybe' 'ArchitectureValues' -- -- * 'iilsGroupIds' @::@ ['Text'] -- -- * 'iilsGroupNames' @::@ ['Text'] -- -- * 'iilsInstanceInitiatedShutdownBehavior' @::@ 'Maybe' 'ShutdownBehavior' -- -- * 'iilsInstanceType' @::@ 'Maybe' 'InstanceType' -- -- * 'iilsMonitoring' @::@ 'Maybe' 'Bool' -- -- * 'iilsPlacement' @::@ 'Maybe' 'Placement' -- -- * 'iilsPrivateIpAddress' @::@ 'Maybe' 'Text' -- -- * 'iilsSubnetId' @::@ 'Maybe' 'Text' -- -- * 'iilsUserData' @::@ 'Maybe' 'UserData' -- importInstanceLaunchSpecification :: ImportInstanceLaunchSpecification importInstanceLaunchSpecification = ImportInstanceLaunchSpecification { _iilsArchitecture = Nothing , _iilsGroupNames = mempty , _iilsGroupIds = mempty , _iilsAdditionalInfo = Nothing , _iilsUserData = Nothing , _iilsInstanceType = Nothing , _iilsPlacement = Nothing , _iilsMonitoring = Nothing , _iilsSubnetId = Nothing , _iilsInstanceInitiatedShutdownBehavior = Nothing , _iilsPrivateIpAddress = Nothing } iilsAdditionalInfo :: Lens' ImportInstanceLaunchSpecification (Maybe Text) iilsAdditionalInfo = lens _iilsAdditionalInfo (\s a -> s { _iilsAdditionalInfo = a }) -- | The architecture of the instance. iilsArchitecture :: Lens' ImportInstanceLaunchSpecification (Maybe ArchitectureValues) iilsArchitecture = lens _iilsArchitecture (\s a -> s { _iilsArchitecture = a }) -- | One or more security group IDs. iilsGroupIds :: Lens' ImportInstanceLaunchSpecification [Text] iilsGroupIds = lens _iilsGroupIds (\s a -> s { _iilsGroupIds = a }) . _List -- | One or more security group names. iilsGroupNames :: Lens' ImportInstanceLaunchSpecification [Text] iilsGroupNames = lens _iilsGroupNames (\s a -> s { _iilsGroupNames = a }) . _List -- | Indicates whether an instance stops or terminates when you initiate shutdown -- from the instance (using the operating system command for system shutdown). iilsInstanceInitiatedShutdownBehavior :: Lens' ImportInstanceLaunchSpecification (Maybe ShutdownBehavior) iilsInstanceInitiatedShutdownBehavior = lens _iilsInstanceInitiatedShutdownBehavior (\s a -> s { _iilsInstanceInitiatedShutdownBehavior = a }) -- | The instance type. This is not supported for VMs imported into a VPC, which -- are assigned the default security group. After a VM is imported into a VPC, -- you can specify another security group using the AWS Management Console. For -- more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html Instance Types> in the /Amazon Elastic Compute Cloud UserGuide for Linux/. For more information about the Linux instance types you can -- import, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/VMImportPrerequisites.html Before You Get Started> in the Amazon Elastic Compute Cloud User -- Guide for Linux. iilsInstanceType :: Lens' ImportInstanceLaunchSpecification (Maybe InstanceType) iilsInstanceType = lens _iilsInstanceType (\s a -> s { _iilsInstanceType = a }) iilsMonitoring :: Lens' ImportInstanceLaunchSpecification (Maybe Bool) iilsMonitoring = lens _iilsMonitoring (\s a -> s { _iilsMonitoring = a }) iilsPlacement :: Lens' ImportInstanceLaunchSpecification (Maybe Placement) iilsPlacement = lens _iilsPlacement (\s a -> s { _iilsPlacement = a }) -- | [EC2-VPC] Optionally, you can use this parameter to assign the instance a -- specific available IP address from the IP address range of the subnet. iilsPrivateIpAddress :: Lens' ImportInstanceLaunchSpecification (Maybe Text) iilsPrivateIpAddress = lens _iilsPrivateIpAddress (\s a -> s { _iilsPrivateIpAddress = a }) -- | [EC2-VPC] The ID of the subnet to launch the instance into. iilsSubnetId :: Lens' ImportInstanceLaunchSpecification (Maybe Text) iilsSubnetId = lens _iilsSubnetId (\s a -> s { _iilsSubnetId = a }) -- | User data to be made available to the instance. iilsUserData :: Lens' ImportInstanceLaunchSpecification (Maybe UserData) iilsUserData = lens _iilsUserData (\s a -> s { _iilsUserData = a }) instance FromXML ImportInstanceLaunchSpecification where parseXML x = ImportInstanceLaunchSpecification <$> x .@? "additionalInfo" <*> x .@? "architecture" <*> x .@? "GroupId" .!@ mempty <*> x .@? "GroupName" .!@ mempty <*> x .@? "instanceInitiatedShutdownBehavior" <*> x .@? "instanceType" <*> x .@? "monitoring" <*> x .@? "placement" <*> x .@? "privateIpAddress" <*> x .@? "subnetId" <*> x .@? "userData" instance ToQuery ImportInstanceLaunchSpecification where toQuery ImportInstanceLaunchSpecification{..} = mconcat [ "AdditionalInfo" =? _iilsAdditionalInfo , "Architecture" =? _iilsArchitecture , "GroupId" `toQueryList` _iilsGroupIds , "GroupName" `toQueryList` _iilsGroupNames , "InstanceInitiatedShutdownBehavior" =? _iilsInstanceInitiatedShutdownBehavior , "InstanceType" =? _iilsInstanceType , "Monitoring" =? _iilsMonitoring , "Placement" =? _iilsPlacement , "PrivateIpAddress" =? _iilsPrivateIpAddress , "SubnetId" =? _iilsSubnetId , "UserData" =? _iilsUserData ] data Snapshot = Snapshot { _sDescription :: Text , _sEncrypted :: Bool , _sKmsKeyId :: Maybe Text , _sOwnerAlias :: Maybe Text , _sOwnerId :: Text , _sProgress :: Text , _sSnapshotId :: Text , _sStartTime :: ISO8601 , _sState :: SnapshotState , _sTags :: List "item" Tag , _sVolumeId :: Text , _sVolumeSize :: Int } deriving (Eq, Read, Show) -- | 'Snapshot' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sDescription' @::@ 'Text' -- -- * 'sEncrypted' @::@ 'Bool' -- -- * 'sKmsKeyId' @::@ 'Maybe' 'Text' -- -- * 'sOwnerAlias' @::@ 'Maybe' 'Text' -- -- * 'sOwnerId' @::@ 'Text' -- -- * 'sProgress' @::@ 'Text' -- -- * 'sSnapshotId' @::@ 'Text' -- -- * 'sStartTime' @::@ 'UTCTime' -- -- * 'sState' @::@ 'SnapshotState' -- -- * 'sTags' @::@ ['Tag'] -- -- * 'sVolumeId' @::@ 'Text' -- -- * 'sVolumeSize' @::@ 'Int' -- snapshot :: Text -- ^ 'sSnapshotId' -> Text -- ^ 'sVolumeId' -> SnapshotState -- ^ 'sState' -> UTCTime -- ^ 'sStartTime' -> Text -- ^ 'sProgress' -> Text -- ^ 'sOwnerId' -> Text -- ^ 'sDescription' -> Int -- ^ 'sVolumeSize' -> Bool -- ^ 'sEncrypted' -> Snapshot snapshot p1 p2 p3 p4 p5 p6 p7 p8 p9 = Snapshot { _sSnapshotId = p1 , _sVolumeId = p2 , _sState = p3 , _sStartTime = withIso _Time (const id) p4 , _sProgress = p5 , _sOwnerId = p6 , _sDescription = p7 , _sVolumeSize = p8 , _sEncrypted = p9 , _sOwnerAlias = Nothing , _sTags = mempty , _sKmsKeyId = Nothing } -- | The description for the snapshot. sDescription :: Lens' Snapshot Text sDescription = lens _sDescription (\s a -> s { _sDescription = a }) -- | Indicates whether the snapshot is encrypted. sEncrypted :: Lens' Snapshot Bool sEncrypted = lens _sEncrypted (\s a -> s { _sEncrypted = a }) -- | The full ARN of the AWS Key Management Service (KMS) master key that was used -- to protect the volume encryption key for the parent volume. sKmsKeyId :: Lens' Snapshot (Maybe Text) sKmsKeyId = lens _sKmsKeyId (\s a -> s { _sKmsKeyId = a }) -- | The AWS account alias (for example, 'amazon', 'self') or AWS account ID that owns -- the snapshot. sOwnerAlias :: Lens' Snapshot (Maybe Text) sOwnerAlias = lens _sOwnerAlias (\s a -> s { _sOwnerAlias = a }) -- | The AWS account ID of the Amazon EBS snapshot owner. sOwnerId :: Lens' Snapshot Text sOwnerId = lens _sOwnerId (\s a -> s { _sOwnerId = a }) -- | The progress of the snapshot, as a percentage. sProgress :: Lens' Snapshot Text sProgress = lens _sProgress (\s a -> s { _sProgress = a }) -- | The ID of the snapshot. sSnapshotId :: Lens' Snapshot Text sSnapshotId = lens _sSnapshotId (\s a -> s { _sSnapshotId = a }) -- | The time stamp when the snapshot was initiated. sStartTime :: Lens' Snapshot UTCTime sStartTime = lens _sStartTime (\s a -> s { _sStartTime = a }) . _Time -- | The snapshot state. sState :: Lens' Snapshot SnapshotState sState = lens _sState (\s a -> s { _sState = a }) -- | Any tags assigned to the snapshot. sTags :: Lens' Snapshot [Tag] sTags = lens _sTags (\s a -> s { _sTags = a }) . _List -- | The ID of the volume. sVolumeId :: Lens' Snapshot Text sVolumeId = lens _sVolumeId (\s a -> s { _sVolumeId = a }) -- | The size of the volume, in GiB. sVolumeSize :: Lens' Snapshot Int sVolumeSize = lens _sVolumeSize (\s a -> s { _sVolumeSize = a }) instance FromXML Snapshot where parseXML x = Snapshot <$> x .@ "description" <*> x .@ "encrypted" <*> x .@? "kmsKeyId" <*> x .@? "ownerAlias" <*> x .@ "ownerId" <*> x .@ "progress" <*> x .@ "snapshotId" <*> x .@ "startTime" <*> x .@ "status" <*> x .@? "tagSet" .!@ mempty <*> x .@ "volumeId" <*> x .@ "volumeSize" instance ToQuery Snapshot where toQuery Snapshot{..} = mconcat [ "Description" =? _sDescription , "Encrypted" =? _sEncrypted , "KmsKeyId" =? _sKmsKeyId , "OwnerAlias" =? _sOwnerAlias , "OwnerId" =? _sOwnerId , "Progress" =? _sProgress , "SnapshotId" =? _sSnapshotId , "StartTime" =? _sStartTime , "Status" =? _sState , "TagSet" `toQueryList` _sTags , "VolumeId" =? _sVolumeId , "VolumeSize" =? _sVolumeSize ] data SpotInstanceStateFault = SpotInstanceStateFault { _sisfCode :: Maybe Text , _sisfMessage :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'SpotInstanceStateFault' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sisfCode' @::@ 'Maybe' 'Text' -- -- * 'sisfMessage' @::@ 'Maybe' 'Text' -- spotInstanceStateFault :: SpotInstanceStateFault spotInstanceStateFault = SpotInstanceStateFault { _sisfCode = Nothing , _sisfMessage = Nothing } -- | The reason code for the Spot Instance state change. sisfCode :: Lens' SpotInstanceStateFault (Maybe Text) sisfCode = lens _sisfCode (\s a -> s { _sisfCode = a }) -- | The message for the Spot Instance state change. sisfMessage :: Lens' SpotInstanceStateFault (Maybe Text) sisfMessage = lens _sisfMessage (\s a -> s { _sisfMessage = a }) instance FromXML SpotInstanceStateFault where parseXML x = SpotInstanceStateFault <$> x .@? "code" <*> x .@? "message" instance ToQuery SpotInstanceStateFault where toQuery SpotInstanceStateFault{..} = mconcat [ "Code" =? _sisfCode , "Message" =? _sisfMessage ] data TagDescription = TagDescription { _tdKey :: Text , _tdResourceId :: Text , _tdResourceType :: ResourceType , _tdValue :: Text } deriving (Eq, Read, Show) -- | 'TagDescription' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'tdKey' @::@ 'Text' -- -- * 'tdResourceId' @::@ 'Text' -- -- * 'tdResourceType' @::@ 'ResourceType' -- -- * 'tdValue' @::@ 'Text' -- tagDescription :: Text -- ^ 'tdResourceId' -> ResourceType -- ^ 'tdResourceType' -> Text -- ^ 'tdKey' -> Text -- ^ 'tdValue' -> TagDescription tagDescription p1 p2 p3 p4 = TagDescription { _tdResourceId = p1 , _tdResourceType = p2 , _tdKey = p3 , _tdValue = p4 } -- | The tag key. tdKey :: Lens' TagDescription Text tdKey = lens _tdKey (\s a -> s { _tdKey = a }) -- | The ID of the resource. For example, 'ami-1a2b3c4d'. tdResourceId :: Lens' TagDescription Text tdResourceId = lens _tdResourceId (\s a -> s { _tdResourceId = a }) -- | The resource type. tdResourceType :: Lens' TagDescription ResourceType tdResourceType = lens _tdResourceType (\s a -> s { _tdResourceType = a }) -- | The tag value. tdValue :: Lens' TagDescription Text tdValue = lens _tdValue (\s a -> s { _tdValue = a }) instance FromXML TagDescription where parseXML x = TagDescription <$> x .@ "key" <*> x .@ "resourceId" <*> x .@ "resourceType" <*> x .@ "value" instance ToQuery TagDescription where toQuery TagDescription{..} = mconcat [ "Key" =? _tdKey , "ResourceId" =? _tdResourceId , "ResourceType" =? _tdResourceType , "Value" =? _tdValue ] data GroupIdentifier = GroupIdentifier { _giGroupId :: Maybe Text , _giGroupName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'GroupIdentifier' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'giGroupId' @::@ 'Maybe' 'Text' -- -- * 'giGroupName' @::@ 'Maybe' 'Text' -- groupIdentifier :: GroupIdentifier groupIdentifier = GroupIdentifier { _giGroupName = Nothing , _giGroupId = Nothing } -- | The ID of the security group. giGroupId :: Lens' GroupIdentifier (Maybe Text) giGroupId = lens _giGroupId (\s a -> s { _giGroupId = a }) -- | The name of the security group. giGroupName :: Lens' GroupIdentifier (Maybe Text) giGroupName = lens _giGroupName (\s a -> s { _giGroupName = a }) instance FromXML GroupIdentifier where parseXML x = GroupIdentifier <$> x .@? "groupId" <*> x .@? "groupName" instance ToQuery GroupIdentifier where toQuery GroupIdentifier{..} = mconcat [ "GroupId" =? _giGroupId , "GroupName" =? _giGroupName ] data VpnStaticRouteSource = Static -- ^ Static deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VpnStaticRouteSource instance FromText VpnStaticRouteSource where parser = takeLowerText >>= \case "static" -> pure Static e -> fail $ "Failure parsing VpnStaticRouteSource from " ++ show e instance ToText VpnStaticRouteSource where toText Static = "Static" instance ToByteString VpnStaticRouteSource instance ToHeader VpnStaticRouteSource instance ToQuery VpnStaticRouteSource instance FromXML VpnStaticRouteSource where parseXML = parseXMLText "VpnStaticRouteSource" data ReservedInstancesListing = ReservedInstancesListing { _rilClientToken :: Maybe Text , _rilCreateDate :: Maybe ISO8601 , _rilInstanceCounts :: List "item" InstanceCount , _rilPriceSchedules :: List "item" PriceSchedule , _rilReservedInstancesId :: Maybe Text , _rilReservedInstancesListingId :: Maybe Text , _rilStatus :: Maybe ListingStatus , _rilStatusMessage :: Maybe Text , _rilTags :: List "item" Tag , _rilUpdateDate :: Maybe ISO8601 } deriving (Eq, Read, Show) -- | 'ReservedInstancesListing' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rilClientToken' @::@ 'Maybe' 'Text' -- -- * 'rilCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'rilInstanceCounts' @::@ ['InstanceCount'] -- -- * 'rilPriceSchedules' @::@ ['PriceSchedule'] -- -- * 'rilReservedInstancesId' @::@ 'Maybe' 'Text' -- -- * 'rilReservedInstancesListingId' @::@ 'Maybe' 'Text' -- -- * 'rilStatus' @::@ 'Maybe' 'ListingStatus' -- -- * 'rilStatusMessage' @::@ 'Maybe' 'Text' -- -- * 'rilTags' @::@ ['Tag'] -- -- * 'rilUpdateDate' @::@ 'Maybe' 'UTCTime' -- reservedInstancesListing :: ReservedInstancesListing reservedInstancesListing = ReservedInstancesListing { _rilReservedInstancesListingId = Nothing , _rilReservedInstancesId = Nothing , _rilCreateDate = Nothing , _rilUpdateDate = Nothing , _rilStatus = Nothing , _rilStatusMessage = Nothing , _rilInstanceCounts = mempty , _rilPriceSchedules = mempty , _rilTags = mempty , _rilClientToken = Nothing } -- | A unique, case-sensitive key supplied by the client to ensure that the -- request is idempotent. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html Ensuring Idempotency>. rilClientToken :: Lens' ReservedInstancesListing (Maybe Text) rilClientToken = lens _rilClientToken (\s a -> s { _rilClientToken = a }) -- | The time the listing was created. rilCreateDate :: Lens' ReservedInstancesListing (Maybe UTCTime) rilCreateDate = lens _rilCreateDate (\s a -> s { _rilCreateDate = a }) . mapping _Time -- | The number of instances in this state. rilInstanceCounts :: Lens' ReservedInstancesListing [InstanceCount] rilInstanceCounts = lens _rilInstanceCounts (\s a -> s { _rilInstanceCounts = a }) . _List -- | The price of the Reserved Instance listing. rilPriceSchedules :: Lens' ReservedInstancesListing [PriceSchedule] rilPriceSchedules = lens _rilPriceSchedules (\s a -> s { _rilPriceSchedules = a }) . _List -- | The ID of the Reserved Instance. rilReservedInstancesId :: Lens' ReservedInstancesListing (Maybe Text) rilReservedInstancesId = lens _rilReservedInstancesId (\s a -> s { _rilReservedInstancesId = a }) -- | The ID of the Reserved Instance listing. rilReservedInstancesListingId :: Lens' ReservedInstancesListing (Maybe Text) rilReservedInstancesListingId = lens _rilReservedInstancesListingId (\s a -> s { _rilReservedInstancesListingId = a }) -- | The status of the Reserved Instance listing. rilStatus :: Lens' ReservedInstancesListing (Maybe ListingStatus) rilStatus = lens _rilStatus (\s a -> s { _rilStatus = a }) -- | The reason for the current status of the Reserved Instance listing. The -- response can be blank. rilStatusMessage :: Lens' ReservedInstancesListing (Maybe Text) rilStatusMessage = lens _rilStatusMessage (\s a -> s { _rilStatusMessage = a }) -- | Any tags assigned to the resource. rilTags :: Lens' ReservedInstancesListing [Tag] rilTags = lens _rilTags (\s a -> s { _rilTags = a }) . _List -- | The last modified timestamp of the listing. rilUpdateDate :: Lens' ReservedInstancesListing (Maybe UTCTime) rilUpdateDate = lens _rilUpdateDate (\s a -> s { _rilUpdateDate = a }) . mapping _Time instance FromXML ReservedInstancesListing where parseXML x = ReservedInstancesListing <$> x .@? "clientToken" <*> x .@? "createDate" <*> x .@? "instanceCounts" .!@ mempty <*> x .@? "priceSchedules" .!@ mempty <*> x .@? "reservedInstancesId" <*> x .@? "reservedInstancesListingId" <*> x .@? "status" <*> x .@? "statusMessage" <*> x .@? "tagSet" .!@ mempty <*> x .@? "updateDate" instance ToQuery ReservedInstancesListing where toQuery ReservedInstancesListing{..} = mconcat [ "ClientToken" =? _rilClientToken , "CreateDate" =? _rilCreateDate , "InstanceCounts" `toQueryList` _rilInstanceCounts , "PriceSchedules" `toQueryList` _rilPriceSchedules , "ReservedInstancesId" =? _rilReservedInstancesId , "ReservedInstancesListingId" =? _rilReservedInstancesListingId , "Status" =? _rilStatus , "StatusMessage" =? _rilStatusMessage , "TagSet" `toQueryList` _rilTags , "UpdateDate" =? _rilUpdateDate ] data InstanceLifecycleType = Spot -- ^ spot deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable InstanceLifecycleType instance FromText InstanceLifecycleType where parser = takeLowerText >>= \case "spot" -> pure Spot e -> fail $ "Failure parsing InstanceLifecycleType from " ++ show e instance ToText InstanceLifecycleType where toText Spot = "spot" instance ToByteString InstanceLifecycleType instance ToHeader InstanceLifecycleType instance ToQuery InstanceLifecycleType instance FromXML InstanceLifecycleType where parseXML = parseXMLText "InstanceLifecycleType" data VirtualizationType = Hvm -- ^ hvm | Paravirtual -- ^ paravirtual deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VirtualizationType instance FromText VirtualizationType where parser = takeLowerText >>= \case "hvm" -> pure Hvm "paravirtual" -> pure Paravirtual e -> fail $ "Failure parsing VirtualizationType from " ++ show e instance ToText VirtualizationType where toText = \case Hvm -> "hvm" Paravirtual -> "paravirtual" instance ToByteString VirtualizationType instance ToHeader VirtualizationType instance ToQuery VirtualizationType instance FromXML VirtualizationType where parseXML = parseXMLText "VirtualizationType" data NetworkInterfaceStatus = Attaching -- ^ attaching | Available -- ^ available | Detaching -- ^ detaching | InUse -- ^ in-use deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable NetworkInterfaceStatus instance FromText NetworkInterfaceStatus where parser = takeLowerText >>= \case "attaching" -> pure Attaching "available" -> pure Available "detaching" -> pure Detaching "in-use" -> pure InUse e -> fail $ "Failure parsing NetworkInterfaceStatus from " ++ show e instance ToText NetworkInterfaceStatus where toText = \case Attaching -> "attaching" Available -> "available" Detaching -> "detaching" InUse -> "in-use" instance ToByteString NetworkInterfaceStatus instance ToHeader NetworkInterfaceStatus instance ToQuery NetworkInterfaceStatus instance FromXML NetworkInterfaceStatus where parseXML = parseXMLText "NetworkInterfaceStatus" data PlatformValues = Windows -- ^ Windows deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable PlatformValues instance FromText PlatformValues where parser = takeLowerText >>= \case "windows" -> pure Windows e -> fail $ "Failure parsing PlatformValues from " ++ show e instance ToText PlatformValues where toText Windows = "Windows" instance ToByteString PlatformValues instance ToHeader PlatformValues instance ToQuery PlatformValues instance FromXML PlatformValues where parseXML = parseXMLText "PlatformValues" data CreateVolumePermission = CreateVolumePermission { _cvpGroup :: Maybe PermissionGroup , _cvpUserId :: Maybe Text } deriving (Eq, Read, Show) -- | 'CreateVolumePermission' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cvpGroup' @::@ 'Maybe' 'PermissionGroup' -- -- * 'cvpUserId' @::@ 'Maybe' 'Text' -- createVolumePermission :: CreateVolumePermission createVolumePermission = CreateVolumePermission { _cvpUserId = Nothing , _cvpGroup = Nothing } -- | The specific group that is to be added or removed from a volume's list of -- create volume permissions. cvpGroup :: Lens' CreateVolumePermission (Maybe PermissionGroup) cvpGroup = lens _cvpGroup (\s a -> s { _cvpGroup = a }) -- | The specific AWS account ID that is to be added or removed from a volume's -- list of create volume permissions. cvpUserId :: Lens' CreateVolumePermission (Maybe Text) cvpUserId = lens _cvpUserId (\s a -> s { _cvpUserId = a }) instance FromXML CreateVolumePermission where parseXML x = CreateVolumePermission <$> x .@? "group" <*> x .@? "userId" instance ToQuery CreateVolumePermission where toQuery CreateVolumePermission{..} = mconcat [ "Group" =? _cvpGroup , "UserId" =? _cvpUserId ] data NetworkInterfaceAttachmentChanges = NetworkInterfaceAttachmentChanges { _niacAttachmentId :: Maybe Text , _niacDeleteOnTermination :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'NetworkInterfaceAttachmentChanges' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'niacAttachmentId' @::@ 'Maybe' 'Text' -- -- * 'niacDeleteOnTermination' @::@ 'Maybe' 'Bool' -- networkInterfaceAttachmentChanges :: NetworkInterfaceAttachmentChanges networkInterfaceAttachmentChanges = NetworkInterfaceAttachmentChanges { _niacAttachmentId = Nothing , _niacDeleteOnTermination = Nothing } -- | The ID of the network interface attachment. niacAttachmentId :: Lens' NetworkInterfaceAttachmentChanges (Maybe Text) niacAttachmentId = lens _niacAttachmentId (\s a -> s { _niacAttachmentId = a }) -- | Indicates whether the network interface is deleted when the instance is -- terminated. niacDeleteOnTermination :: Lens' NetworkInterfaceAttachmentChanges (Maybe Bool) niacDeleteOnTermination = lens _niacDeleteOnTermination (\s a -> s { _niacDeleteOnTermination = a }) instance FromXML NetworkInterfaceAttachmentChanges where parseXML x = NetworkInterfaceAttachmentChanges <$> x .@? "attachmentId" <*> x .@? "deleteOnTermination" instance ToQuery NetworkInterfaceAttachmentChanges where toQuery NetworkInterfaceAttachmentChanges{..} = mconcat [ "AttachmentId" =? _niacAttachmentId , "DeleteOnTermination" =? _niacDeleteOnTermination ] data RecurringChargeFrequency = Hourly -- ^ Hourly deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable RecurringChargeFrequency instance FromText RecurringChargeFrequency where parser = takeLowerText >>= \case "hourly" -> pure Hourly e -> fail $ "Failure parsing RecurringChargeFrequency from " ++ show e instance ToText RecurringChargeFrequency where toText Hourly = "Hourly" instance ToByteString RecurringChargeFrequency instance ToHeader RecurringChargeFrequency instance ToQuery RecurringChargeFrequency instance FromXML RecurringChargeFrequency where parseXML = parseXMLText "RecurringChargeFrequency" data DhcpOptions = DhcpOptions { _doDhcpConfigurations :: List "item" DhcpConfiguration , _doDhcpOptionsId :: Maybe Text , _doTags :: List "item" Tag } deriving (Eq, Read, Show) -- | 'DhcpOptions' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'doDhcpConfigurations' @::@ ['DhcpConfiguration'] -- -- * 'doDhcpOptionsId' @::@ 'Maybe' 'Text' -- -- * 'doTags' @::@ ['Tag'] -- dhcpOptions :: DhcpOptions dhcpOptions = DhcpOptions { _doDhcpOptionsId = Nothing , _doDhcpConfigurations = mempty , _doTags = mempty } -- | One or more DHCP options in the set. doDhcpConfigurations :: Lens' DhcpOptions [DhcpConfiguration] doDhcpConfigurations = lens _doDhcpConfigurations (\s a -> s { _doDhcpConfigurations = a }) . _List -- | The ID of the set of DHCP options. doDhcpOptionsId :: Lens' DhcpOptions (Maybe Text) doDhcpOptionsId = lens _doDhcpOptionsId (\s a -> s { _doDhcpOptionsId = a }) -- | Any tags assigned to the DHCP options set. doTags :: Lens' DhcpOptions [Tag] doTags = lens _doTags (\s a -> s { _doTags = a }) . _List instance FromXML DhcpOptions where parseXML x = DhcpOptions <$> x .@? "dhcpConfigurationSet" .!@ mempty <*> x .@? "dhcpOptionsId" <*> x .@? "tagSet" .!@ mempty instance ToQuery DhcpOptions where toQuery DhcpOptions{..} = mconcat [ "DhcpConfigurationSet" `toQueryList` _doDhcpConfigurations , "DhcpOptionsId" =? _doDhcpOptionsId , "TagSet" `toQueryList` _doTags ] data InstanceNetworkInterfaceSpecification = InstanceNetworkInterfaceSpecification { _inisAssociatePublicIpAddress :: Maybe Bool , _inisDeleteOnTermination :: Maybe Bool , _inisDescription :: Maybe Text , _inisDeviceIndex :: Maybe Int , _inisGroups :: List "SecurityGroupId" Text , _inisNetworkInterfaceId :: Maybe Text , _inisPrivateIpAddress :: Maybe Text , _inisPrivateIpAddresses :: List "item" PrivateIpAddressSpecification , _inisSecondaryPrivateIpAddressCount :: Maybe Int , _inisSubnetId :: Maybe Text } deriving (Eq, Read, Show) -- | 'InstanceNetworkInterfaceSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'inisAssociatePublicIpAddress' @::@ 'Maybe' 'Bool' -- -- * 'inisDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'inisDescription' @::@ 'Maybe' 'Text' -- -- * 'inisDeviceIndex' @::@ 'Maybe' 'Int' -- -- * 'inisGroups' @::@ ['Text'] -- -- * 'inisNetworkInterfaceId' @::@ 'Maybe' 'Text' -- -- * 'inisPrivateIpAddress' @::@ 'Maybe' 'Text' -- -- * 'inisPrivateIpAddresses' @::@ ['PrivateIpAddressSpecification'] -- -- * 'inisSecondaryPrivateIpAddressCount' @::@ 'Maybe' 'Int' -- -- * 'inisSubnetId' @::@ 'Maybe' 'Text' -- instanceNetworkInterfaceSpecification :: InstanceNetworkInterfaceSpecification instanceNetworkInterfaceSpecification = InstanceNetworkInterfaceSpecification { _inisNetworkInterfaceId = Nothing , _inisDeviceIndex = Nothing , _inisSubnetId = Nothing , _inisDescription = Nothing , _inisPrivateIpAddress = Nothing , _inisGroups = mempty , _inisDeleteOnTermination = Nothing , _inisPrivateIpAddresses = mempty , _inisSecondaryPrivateIpAddressCount = Nothing , _inisAssociatePublicIpAddress = Nothing } -- | Indicates whether to assign a public IP address to an instance you launch in -- a VPC. The public IP address can only be assigned to a network interface for -- eth0, and can only be assigned to a new network interface, not an existing -- one. You cannot specify more than one network interface in the request. If -- launching into a default subnet, the default value is 'true'. inisAssociatePublicIpAddress :: Lens' InstanceNetworkInterfaceSpecification (Maybe Bool) inisAssociatePublicIpAddress = lens _inisAssociatePublicIpAddress (\s a -> s { _inisAssociatePublicIpAddress = a }) -- | If set to 'true', the interface is deleted when the instance is terminated. You -- can specify 'true' only if creating a new network interface when launching an -- instance. inisDeleteOnTermination :: Lens' InstanceNetworkInterfaceSpecification (Maybe Bool) inisDeleteOnTermination = lens _inisDeleteOnTermination (\s a -> s { _inisDeleteOnTermination = a }) -- | The description of the network interface. Applies only if creating a network -- interface when launching an instance. inisDescription :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text) inisDescription = lens _inisDescription (\s a -> s { _inisDescription = a }) -- | The index of the device on the instance for the network interface attachment. -- If you are specifying a network interface in a 'RunInstances' request, you must -- provide the device index. inisDeviceIndex :: Lens' InstanceNetworkInterfaceSpecification (Maybe Int) inisDeviceIndex = lens _inisDeviceIndex (\s a -> s { _inisDeviceIndex = a }) -- | The IDs of the security groups for the network interface. Applies only if -- creating a network interface when launching an instance. inisGroups :: Lens' InstanceNetworkInterfaceSpecification [Text] inisGroups = lens _inisGroups (\s a -> s { _inisGroups = a }) . _List -- | The ID of the network interface. inisNetworkInterfaceId :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text) inisNetworkInterfaceId = lens _inisNetworkInterfaceId (\s a -> s { _inisNetworkInterfaceId = a }) -- | The private IP address of the network interface. Applies only if creating a -- network interface when launching an instance. inisPrivateIpAddress :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text) inisPrivateIpAddress = lens _inisPrivateIpAddress (\s a -> s { _inisPrivateIpAddress = a }) -- | One or more private IP addresses to assign to the network interface. Only one -- private IP address can be designated as primary. inisPrivateIpAddresses :: Lens' InstanceNetworkInterfaceSpecification [PrivateIpAddressSpecification] inisPrivateIpAddresses = lens _inisPrivateIpAddresses (\s a -> s { _inisPrivateIpAddresses = a }) . _List -- | The number of secondary private IP addresses. You can't specify this option -- and specify more than one private IP address using the private IP addresses -- option. inisSecondaryPrivateIpAddressCount :: Lens' InstanceNetworkInterfaceSpecification (Maybe Int) inisSecondaryPrivateIpAddressCount = lens _inisSecondaryPrivateIpAddressCount (\s a -> s { _inisSecondaryPrivateIpAddressCount = a }) -- | The ID of the subnet associated with the network string. Applies only if -- creating a network interface when launching an instance. inisSubnetId :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text) inisSubnetId = lens _inisSubnetId (\s a -> s { _inisSubnetId = a }) instance FromXML InstanceNetworkInterfaceSpecification where parseXML x = InstanceNetworkInterfaceSpecification <$> x .@? "associatePublicIpAddress" <*> x .@? "deleteOnTermination" <*> x .@? "description" <*> x .@? "deviceIndex" <*> x .@? "SecurityGroupId" .!@ mempty <*> x .@? "networkInterfaceId" <*> x .@? "privateIpAddress" <*> x .@? "privateIpAddressesSet" .!@ mempty <*> x .@? "secondaryPrivateIpAddressCount" <*> x .@? "subnetId" instance ToQuery InstanceNetworkInterfaceSpecification where toQuery InstanceNetworkInterfaceSpecification{..} = mconcat [ "AssociatePublicIpAddress" =? _inisAssociatePublicIpAddress , "DeleteOnTermination" =? _inisDeleteOnTermination , "Description" =? _inisDescription , "DeviceIndex" =? _inisDeviceIndex , "SecurityGroupId" `toQueryList` _inisGroups , "NetworkInterfaceId" =? _inisNetworkInterfaceId , "PrivateIpAddress" =? _inisPrivateIpAddress , "PrivateIpAddressesSet" `toQueryList` _inisPrivateIpAddresses , "SecondaryPrivateIpAddressCount" =? _inisSecondaryPrivateIpAddressCount , "SubnetId" =? _inisSubnetId ] data VolumeState = VSAvailable -- ^ available | VSCreating -- ^ creating | VSDeleted -- ^ deleted | VSDeleting -- ^ deleting | VSError -- ^ error | VSInUse -- ^ in-use deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VolumeState instance FromText VolumeState where parser = takeLowerText >>= \case "available" -> pure VSAvailable "creating" -> pure VSCreating "deleted" -> pure VSDeleted "deleting" -> pure VSDeleting "error" -> pure VSError "in-use" -> pure VSInUse e -> fail $ "Failure parsing VolumeState from " ++ show e instance ToText VolumeState where toText = \case VSAvailable -> "available" VSCreating -> "creating" VSDeleted -> "deleted" VSDeleting -> "deleting" VSError -> "error" VSInUse -> "in-use" instance ToByteString VolumeState instance ToHeader VolumeState instance ToQuery VolumeState instance FromXML VolumeState where parseXML = parseXMLText "VolumeState" newtype AttributeValue = AttributeValue { _avValue :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'AttributeValue' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'avValue' @::@ 'Maybe' 'Text' -- attributeValue :: AttributeValue attributeValue = AttributeValue { _avValue = Nothing } -- | Valid values are case-sensitive and vary by action. avValue :: Lens' AttributeValue (Maybe Text) avValue = lens _avValue (\s a -> s { _avValue = a }) instance FromXML AttributeValue where parseXML x = AttributeValue <$> x .@? "value" instance ToQuery AttributeValue where toQuery AttributeValue{..} = mconcat [ "Value" =? _avValue ] data PrivateIpAddressSpecification = PrivateIpAddressSpecification { _piasPrimary :: Maybe Bool , _piasPrivateIpAddress :: Text } deriving (Eq, Ord, Read, Show) -- | 'PrivateIpAddressSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'piasPrimary' @::@ 'Maybe' 'Bool' -- -- * 'piasPrivateIpAddress' @::@ 'Text' -- privateIpAddressSpecification :: Text -- ^ 'piasPrivateIpAddress' -> PrivateIpAddressSpecification privateIpAddressSpecification p1 = PrivateIpAddressSpecification { _piasPrivateIpAddress = p1 , _piasPrimary = Nothing } -- | Indicates whether the private IP address is the primary private IP address. -- Only one IP address can be designated as primary. piasPrimary :: Lens' PrivateIpAddressSpecification (Maybe Bool) piasPrimary = lens _piasPrimary (\s a -> s { _piasPrimary = a }) -- | The private IP addresses. piasPrivateIpAddress :: Lens' PrivateIpAddressSpecification Text piasPrivateIpAddress = lens _piasPrivateIpAddress (\s a -> s { _piasPrivateIpAddress = a }) instance FromXML PrivateIpAddressSpecification where parseXML x = PrivateIpAddressSpecification <$> x .@? "primary" <*> x .@ "privateIpAddress" instance ToQuery PrivateIpAddressSpecification where toQuery PrivateIpAddressSpecification{..} = mconcat [ "Primary" =? _piasPrimary , "PrivateIpAddress" =? _piasPrivateIpAddress ] data Image = Image { _iArchitecture :: ArchitectureValues , _iBlockDeviceMappings :: List "item" BlockDeviceMapping , _iCreationDate :: Maybe Text , _iDescription :: Maybe Text , _iHypervisor :: HypervisorType , _iImageId :: Text , _iImageLocation :: Text , _iImageOwnerAlias :: Maybe Text , _iImageType :: ImageTypeValues , _iKernelId :: Maybe Text , _iName :: Maybe Text , _iOwnerId :: Text , _iPlatform :: Maybe PlatformValues , _iProductCodes :: List "item" ProductCode , _iPublic :: Bool , _iRamdiskId :: Maybe Text , _iRootDeviceName :: Maybe Text , _iRootDeviceType :: DeviceType , _iSriovNetSupport :: Maybe Text , _iState :: ImageState , _iStateReason :: Maybe StateReason , _iTags :: List "item" Tag , _iVirtualizationType :: VirtualizationType } deriving (Eq, Read, Show) -- | 'Image' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iArchitecture' @::@ 'ArchitectureValues' -- -- * 'iBlockDeviceMappings' @::@ ['BlockDeviceMapping'] -- -- * 'iCreationDate' @::@ 'Maybe' 'Text' -- -- * 'iDescription' @::@ 'Maybe' 'Text' -- -- * 'iHypervisor' @::@ 'HypervisorType' -- -- * 'iImageId' @::@ 'Text' -- -- * 'iImageLocation' @::@ 'Text' -- -- * 'iImageOwnerAlias' @::@ 'Maybe' 'Text' -- -- * 'iImageType' @::@ 'ImageTypeValues' -- -- * 'iKernelId' @::@ 'Maybe' 'Text' -- -- * 'iName' @::@ 'Maybe' 'Text' -- -- * 'iOwnerId' @::@ 'Text' -- -- * 'iPlatform' @::@ 'Maybe' 'PlatformValues' -- -- * 'iProductCodes' @::@ ['ProductCode'] -- -- * 'iPublic' @::@ 'Bool' -- -- * 'iRamdiskId' @::@ 'Maybe' 'Text' -- -- * 'iRootDeviceName' @::@ 'Maybe' 'Text' -- -- * 'iRootDeviceType' @::@ 'DeviceType' -- -- * 'iSriovNetSupport' @::@ 'Maybe' 'Text' -- -- * 'iState' @::@ 'ImageState' -- -- * 'iStateReason' @::@ 'Maybe' 'StateReason' -- -- * 'iTags' @::@ ['Tag'] -- -- * 'iVirtualizationType' @::@ 'VirtualizationType' -- image :: Text -- ^ 'iImageId' -> Text -- ^ 'iImageLocation' -> ImageState -- ^ 'iState' -> Text -- ^ 'iOwnerId' -> Bool -- ^ 'iPublic' -> ArchitectureValues -- ^ 'iArchitecture' -> ImageTypeValues -- ^ 'iImageType' -> DeviceType -- ^ 'iRootDeviceType' -> VirtualizationType -- ^ 'iVirtualizationType' -> HypervisorType -- ^ 'iHypervisor' -> Image image p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 = Image { _iImageId = p1 , _iImageLocation = p2 , _iState = p3 , _iOwnerId = p4 , _iPublic = p5 , _iArchitecture = p6 , _iImageType = p7 , _iRootDeviceType = p8 , _iVirtualizationType = p9 , _iHypervisor = p10 , _iCreationDate = Nothing , _iProductCodes = mempty , _iKernelId = Nothing , _iRamdiskId = Nothing , _iPlatform = Nothing , _iSriovNetSupport = Nothing , _iStateReason = Nothing , _iImageOwnerAlias = Nothing , _iName = Nothing , _iDescription = Nothing , _iRootDeviceName = Nothing , _iBlockDeviceMappings = mempty , _iTags = mempty } -- | The architecture of the image. iArchitecture :: Lens' Image ArchitectureValues iArchitecture = lens _iArchitecture (\s a -> s { _iArchitecture = a }) -- | Any block device mapping entries. iBlockDeviceMappings :: Lens' Image [BlockDeviceMapping] iBlockDeviceMappings = lens _iBlockDeviceMappings (\s a -> s { _iBlockDeviceMappings = a }) . _List -- | The date and time the image was created. iCreationDate :: Lens' Image (Maybe Text) iCreationDate = lens _iCreationDate (\s a -> s { _iCreationDate = a }) -- | The description of the AMI that was provided during image creation. iDescription :: Lens' Image (Maybe Text) iDescription = lens _iDescription (\s a -> s { _iDescription = a }) -- | The hypervisor type of the image. iHypervisor :: Lens' Image HypervisorType iHypervisor = lens _iHypervisor (\s a -> s { _iHypervisor = a }) -- | The ID of the AMI. iImageId :: Lens' Image Text iImageId = lens _iImageId (\s a -> s { _iImageId = a }) -- | The location of the AMI. iImageLocation :: Lens' Image Text iImageLocation = lens _iImageLocation (\s a -> s { _iImageLocation = a }) -- | The AWS account alias (for example, 'amazon', 'self') or the AWS account ID of -- the AMI owner. iImageOwnerAlias :: Lens' Image (Maybe Text) iImageOwnerAlias = lens _iImageOwnerAlias (\s a -> s { _iImageOwnerAlias = a }) -- | The type of image. iImageType :: Lens' Image ImageTypeValues iImageType = lens _iImageType (\s a -> s { _iImageType = a }) -- | The kernel associated with the image, if any. Only applicable for machine -- images. iKernelId :: Lens' Image (Maybe Text) iKernelId = lens _iKernelId (\s a -> s { _iKernelId = a }) -- | The name of the AMI that was provided during image creation. iName :: Lens' Image (Maybe Text) iName = lens _iName (\s a -> s { _iName = a }) -- | The AWS account ID of the image owner. iOwnerId :: Lens' Image Text iOwnerId = lens _iOwnerId (\s a -> s { _iOwnerId = a }) -- | The value is 'Windows' for Windows AMIs; otherwise blank. iPlatform :: Lens' Image (Maybe PlatformValues) iPlatform = lens _iPlatform (\s a -> s { _iPlatform = a }) -- | Any product codes associated with the AMI. iProductCodes :: Lens' Image [ProductCode] iProductCodes = lens _iProductCodes (\s a -> s { _iProductCodes = a }) . _List -- | Indicates whether the image has public launch permissions. The value is 'true' -- if this image has public launch permissions or 'false' if it has only implicit -- and explicit launch permissions. iPublic :: Lens' Image Bool iPublic = lens _iPublic (\s a -> s { _iPublic = a }) -- | The RAM disk associated with the image, if any. Only applicable for machine -- images. iRamdiskId :: Lens' Image (Maybe Text) iRamdiskId = lens _iRamdiskId (\s a -> s { _iRamdiskId = a }) -- | The device name of the root device (for example, '/dev/sda1' or '/dev/xvda'). iRootDeviceName :: Lens' Image (Maybe Text) iRootDeviceName = lens _iRootDeviceName (\s a -> s { _iRootDeviceName = a }) -- | The type of root device used by the AMI. The AMI can use an Amazon EBS volume -- or an instance store volume. iRootDeviceType :: Lens' Image DeviceType iRootDeviceType = lens _iRootDeviceType (\s a -> s { _iRootDeviceType = a }) -- | Specifies whether enhanced networking is enabled. iSriovNetSupport :: Lens' Image (Maybe Text) iSriovNetSupport = lens _iSriovNetSupport (\s a -> s { _iSriovNetSupport = a }) -- | The current state of the AMI. If the state is 'available', the image is -- successfully registered and can be used to launch an instance. iState :: Lens' Image ImageState iState = lens _iState (\s a -> s { _iState = a }) -- | The reason for the state change. iStateReason :: Lens' Image (Maybe StateReason) iStateReason = lens _iStateReason (\s a -> s { _iStateReason = a }) -- | Any tags assigned to the image. iTags :: Lens' Image [Tag] iTags = lens _iTags (\s a -> s { _iTags = a }) . _List -- | The type of virtualization of the AMI. iVirtualizationType :: Lens' Image VirtualizationType iVirtualizationType = lens _iVirtualizationType (\s a -> s { _iVirtualizationType = a }) instance FromXML Image where parseXML x = Image <$> x .@ "architecture" <*> x .@? "blockDeviceMapping" .!@ mempty <*> x .@? "creationDate" <*> x .@? "description" <*> x .@ "hypervisor" <*> x .@ "imageId" <*> x .@ "imageLocation" <*> x .@? "imageOwnerAlias" <*> x .@ "imageType" <*> x .@? "kernelId" <*> x .@? "name" <*> x .@ "imageOwnerId" <*> x .@? "platform" <*> x .@? "productCodes" .!@ mempty <*> x .@ "isPublic" <*> x .@? "ramdiskId" <*> x .@? "rootDeviceName" <*> x .@ "rootDeviceType" <*> x .@? "sriovNetSupport" <*> x .@ "imageState" <*> x .@? "stateReason" <*> x .@? "tagSet" .!@ mempty <*> x .@ "virtualizationType" instance ToQuery Image where toQuery Image{..} = mconcat [ "Architecture" =? _iArchitecture , "BlockDeviceMapping" `toQueryList` _iBlockDeviceMappings , "CreationDate" =? _iCreationDate , "Description" =? _iDescription , "Hypervisor" =? _iHypervisor , "ImageId" =? _iImageId , "ImageLocation" =? _iImageLocation , "ImageOwnerAlias" =? _iImageOwnerAlias , "ImageType" =? _iImageType , "KernelId" =? _iKernelId , "Name" =? _iName , "ImageOwnerId" =? _iOwnerId , "Platform" =? _iPlatform , "ProductCodes" `toQueryList` _iProductCodes , "IsPublic" =? _iPublic , "RamdiskId" =? _iRamdiskId , "RootDeviceName" =? _iRootDeviceName , "RootDeviceType" =? _iRootDeviceType , "SriovNetSupport" =? _iSriovNetSupport , "ImageState" =? _iState , "StateReason" =? _iStateReason , "TagSet" `toQueryList` _iTags , "VirtualizationType" =? _iVirtualizationType ] data DhcpConfiguration = DhcpConfiguration { _dcKey :: Maybe Text , _dcValues :: List "item" AttributeValue } deriving (Eq, Read, Show) -- | 'DhcpConfiguration' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dcKey' @::@ 'Maybe' 'Text' -- -- * 'dcValues' @::@ ['AttributeValue'] -- dhcpConfiguration :: DhcpConfiguration dhcpConfiguration = DhcpConfiguration { _dcKey = Nothing , _dcValues = mempty } -- | The name of a DHCP option. dcKey :: Lens' DhcpConfiguration (Maybe Text) dcKey = lens _dcKey (\s a -> s { _dcKey = a }) -- | One or more values for the DHCP option. dcValues :: Lens' DhcpConfiguration [AttributeValue] dcValues = lens _dcValues (\s a -> s { _dcValues = a }) . _List instance FromXML DhcpConfiguration where parseXML x = DhcpConfiguration <$> x .@? "key" <*> x .@? "valueSet" .!@ mempty instance ToQuery DhcpConfiguration where toQuery DhcpConfiguration{..} = mconcat [ "Key" =? _dcKey , "ValueSet" `toQueryList` _dcValues ] data Tag = Tag { _tagKey :: Text , _tagValue :: Text } deriving (Eq, Ord, Read, Show) -- | 'Tag' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'tagKey' @::@ 'Text' -- -- * 'tagValue' @::@ 'Text' -- tag :: Text -- ^ 'tagKey' -> Text -- ^ 'tagValue' -> Tag tag p1 p2 = Tag { _tagKey = p1 , _tagValue = p2 } -- | The key of the tag. -- -- Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode -- characters. May not begin with 'aws:' tagKey :: Lens' Tag Text tagKey = lens _tagKey (\s a -> s { _tagKey = a }) -- | The value of the tag. -- -- Constraints: Tag values are case-sensitive and accept a maximum of 255 -- Unicode characters. tagValue :: Lens' Tag Text tagValue = lens _tagValue (\s a -> s { _tagValue = a }) instance FromXML Tag where parseXML x = Tag <$> x .@ "key" <*> x .@ "value" instance ToQuery Tag where toQuery Tag{..} = mconcat [ "Key" =? _tagKey , "Value" =? _tagValue ] data AccountAttributeName = DefaultVpc -- ^ default-vpc | SupportedPlatforms -- ^ supported-platforms deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable AccountAttributeName instance FromText AccountAttributeName where parser = takeLowerText >>= \case "default-vpc" -> pure DefaultVpc "supported-platforms" -> pure SupportedPlatforms e -> fail $ "Failure parsing AccountAttributeName from " ++ show e instance ToText AccountAttributeName where toText = \case DefaultVpc -> "default-vpc" SupportedPlatforms -> "supported-platforms" instance ToByteString AccountAttributeName instance ToHeader AccountAttributeName instance ToQuery AccountAttributeName instance FromXML AccountAttributeName where parseXML = parseXMLText "AccountAttributeName" data NetworkInterfaceAttachment = NetworkInterfaceAttachment { _niaAttachTime :: Maybe ISO8601 , _niaAttachmentId :: Maybe Text , _niaDeleteOnTermination :: Maybe Bool , _niaDeviceIndex :: Maybe Int , _niaInstanceId :: Maybe Text , _niaInstanceOwnerId :: Maybe Text , _niaStatus :: Maybe AttachmentStatus } deriving (Eq, Read, Show) -- | 'NetworkInterfaceAttachment' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'niaAttachTime' @::@ 'Maybe' 'UTCTime' -- -- * 'niaAttachmentId' @::@ 'Maybe' 'Text' -- -- * 'niaDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'niaDeviceIndex' @::@ 'Maybe' 'Int' -- -- * 'niaInstanceId' @::@ 'Maybe' 'Text' -- -- * 'niaInstanceOwnerId' @::@ 'Maybe' 'Text' -- -- * 'niaStatus' @::@ 'Maybe' 'AttachmentStatus' -- networkInterfaceAttachment :: NetworkInterfaceAttachment networkInterfaceAttachment = NetworkInterfaceAttachment { _niaAttachmentId = Nothing , _niaInstanceId = Nothing , _niaInstanceOwnerId = Nothing , _niaDeviceIndex = Nothing , _niaStatus = Nothing , _niaAttachTime = Nothing , _niaDeleteOnTermination = Nothing } -- | The timestamp indicating when the attachment initiated. niaAttachTime :: Lens' NetworkInterfaceAttachment (Maybe UTCTime) niaAttachTime = lens _niaAttachTime (\s a -> s { _niaAttachTime = a }) . mapping _Time -- | The ID of the network interface attachment. niaAttachmentId :: Lens' NetworkInterfaceAttachment (Maybe Text) niaAttachmentId = lens _niaAttachmentId (\s a -> s { _niaAttachmentId = a }) -- | Indicates whether the network interface is deleted when the instance is -- terminated. niaDeleteOnTermination :: Lens' NetworkInterfaceAttachment (Maybe Bool) niaDeleteOnTermination = lens _niaDeleteOnTermination (\s a -> s { _niaDeleteOnTermination = a }) -- | The device index of the network interface attachment on the instance. niaDeviceIndex :: Lens' NetworkInterfaceAttachment (Maybe Int) niaDeviceIndex = lens _niaDeviceIndex (\s a -> s { _niaDeviceIndex = a }) -- | The ID of the instance. niaInstanceId :: Lens' NetworkInterfaceAttachment (Maybe Text) niaInstanceId = lens _niaInstanceId (\s a -> s { _niaInstanceId = a }) -- | The AWS account ID of the owner of the instance. niaInstanceOwnerId :: Lens' NetworkInterfaceAttachment (Maybe Text) niaInstanceOwnerId = lens _niaInstanceOwnerId (\s a -> s { _niaInstanceOwnerId = a }) -- | The attachment state. niaStatus :: Lens' NetworkInterfaceAttachment (Maybe AttachmentStatus) niaStatus = lens _niaStatus (\s a -> s { _niaStatus = a }) instance FromXML NetworkInterfaceAttachment where parseXML x = NetworkInterfaceAttachment <$> x .@? "attachTime" <*> x .@? "attachmentId" <*> x .@? "deleteOnTermination" <*> x .@? "deviceIndex" <*> x .@? "instanceId" <*> x .@? "instanceOwnerId" <*> x .@? "status" instance ToQuery NetworkInterfaceAttachment where toQuery NetworkInterfaceAttachment{..} = mconcat [ "AttachTime" =? _niaAttachTime , "AttachmentId" =? _niaAttachmentId , "DeleteOnTermination" =? _niaDeleteOnTermination , "DeviceIndex" =? _niaDeviceIndex , "InstanceId" =? _niaInstanceId , "InstanceOwnerId" =? _niaInstanceOwnerId , "Status" =? _niaStatus ] newtype RunInstancesMonitoringEnabled = RunInstancesMonitoringEnabled { _rimeEnabled :: Bool } deriving (Eq, Ord, Read, Show, Enum) -- | 'RunInstancesMonitoringEnabled' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rimeEnabled' @::@ 'Bool' -- runInstancesMonitoringEnabled :: Bool -- ^ 'rimeEnabled' -> RunInstancesMonitoringEnabled runInstancesMonitoringEnabled p1 = RunInstancesMonitoringEnabled { _rimeEnabled = p1 } -- | Indicates whether monitoring is enabled for the instance. rimeEnabled :: Lens' RunInstancesMonitoringEnabled Bool rimeEnabled = lens _rimeEnabled (\s a -> s { _rimeEnabled = a }) instance FromXML RunInstancesMonitoringEnabled where parseXML x = RunInstancesMonitoringEnabled <$> x .@ "enabled" instance ToQuery RunInstancesMonitoringEnabled where toQuery RunInstancesMonitoringEnabled{..} = mconcat [ "Enabled" =? _rimeEnabled ] data VolumeStatusInfo = VolumeStatusInfo { _vsiDetails :: List "item" VolumeStatusDetails , _vsiStatus :: Maybe VolumeStatusInfoStatus } deriving (Eq, Read, Show) -- | 'VolumeStatusInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vsiDetails' @::@ ['VolumeStatusDetails'] -- -- * 'vsiStatus' @::@ 'Maybe' 'VolumeStatusInfoStatus' -- volumeStatusInfo :: VolumeStatusInfo volumeStatusInfo = VolumeStatusInfo { _vsiStatus = Nothing , _vsiDetails = mempty } -- | The details of the volume status. vsiDetails :: Lens' VolumeStatusInfo [VolumeStatusDetails] vsiDetails = lens _vsiDetails (\s a -> s { _vsiDetails = a }) . _List -- | The status of the volume. vsiStatus :: Lens' VolumeStatusInfo (Maybe VolumeStatusInfoStatus) vsiStatus = lens _vsiStatus (\s a -> s { _vsiStatus = a }) instance FromXML VolumeStatusInfo where parseXML x = VolumeStatusInfo <$> x .@? "details" .!@ mempty <*> x .@? "status" instance ToQuery VolumeStatusInfo where toQuery VolumeStatusInfo{..} = mconcat [ "Details" `toQueryList` _vsiDetails , "Status" =? _vsiStatus ] data NetworkInterfaceAssociation = NetworkInterfaceAssociation { _niaAllocationId :: Maybe Text , _niaAssociationId :: Maybe Text , _niaIpOwnerId :: Maybe Text , _niaPublicDnsName :: Maybe Text , _niaPublicIp :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'NetworkInterfaceAssociation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'niaAllocationId' @::@ 'Maybe' 'Text' -- -- * 'niaAssociationId' @::@ 'Maybe' 'Text' -- -- * 'niaIpOwnerId' @::@ 'Maybe' 'Text' -- -- * 'niaPublicDnsName' @::@ 'Maybe' 'Text' -- -- * 'niaPublicIp' @::@ 'Maybe' 'Text' -- networkInterfaceAssociation :: NetworkInterfaceAssociation networkInterfaceAssociation = NetworkInterfaceAssociation { _niaPublicIp = Nothing , _niaPublicDnsName = Nothing , _niaIpOwnerId = Nothing , _niaAllocationId = Nothing , _niaAssociationId = Nothing } -- | The allocation ID. niaAllocationId :: Lens' NetworkInterfaceAssociation (Maybe Text) niaAllocationId = lens _niaAllocationId (\s a -> s { _niaAllocationId = a }) -- | The association ID. niaAssociationId :: Lens' NetworkInterfaceAssociation (Maybe Text) niaAssociationId = lens _niaAssociationId (\s a -> s { _niaAssociationId = a }) -- | The ID of the Elastic IP address owner. niaIpOwnerId :: Lens' NetworkInterfaceAssociation (Maybe Text) niaIpOwnerId = lens _niaIpOwnerId (\s a -> s { _niaIpOwnerId = a }) -- | The public DNS name. niaPublicDnsName :: Lens' NetworkInterfaceAssociation (Maybe Text) niaPublicDnsName = lens _niaPublicDnsName (\s a -> s { _niaPublicDnsName = a }) -- | The address of the Elastic IP address bound to the network interface. niaPublicIp :: Lens' NetworkInterfaceAssociation (Maybe Text) niaPublicIp = lens _niaPublicIp (\s a -> s { _niaPublicIp = a }) instance FromXML NetworkInterfaceAssociation where parseXML x = NetworkInterfaceAssociation <$> x .@? "allocationId" <*> x .@? "associationId" <*> x .@? "ipOwnerId" <*> x .@? "publicDnsName" <*> x .@? "publicIp" instance ToQuery NetworkInterfaceAssociation where toQuery NetworkInterfaceAssociation{..} = mconcat [ "AllocationId" =? _niaAllocationId , "AssociationId" =? _niaAssociationId , "IpOwnerId" =? _niaIpOwnerId , "PublicDnsName" =? _niaPublicDnsName , "PublicIp" =? _niaPublicIp ] data CreateVolumePermissionModifications = CreateVolumePermissionModifications { _cvpmAdd :: List "item" CreateVolumePermission , _cvpmRemove :: List "item" CreateVolumePermission } deriving (Eq, Read, Show) -- | 'CreateVolumePermissionModifications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cvpmAdd' @::@ ['CreateVolumePermission'] -- -- * 'cvpmRemove' @::@ ['CreateVolumePermission'] -- createVolumePermissionModifications :: CreateVolumePermissionModifications createVolumePermissionModifications = CreateVolumePermissionModifications { _cvpmAdd = mempty , _cvpmRemove = mempty } -- | Adds a specific AWS account ID or group to a volume's list of create volume -- permissions. cvpmAdd :: Lens' CreateVolumePermissionModifications [CreateVolumePermission] cvpmAdd = lens _cvpmAdd (\s a -> s { _cvpmAdd = a }) . _List -- | Removes a specific AWS account ID or group from a volume's list of create -- volume permissions. cvpmRemove :: Lens' CreateVolumePermissionModifications [CreateVolumePermission] cvpmRemove = lens _cvpmRemove (\s a -> s { _cvpmRemove = a }) . _List instance FromXML CreateVolumePermissionModifications where parseXML x = CreateVolumePermissionModifications <$> x .@? "Add" .!@ mempty <*> x .@? "Remove" .!@ mempty instance ToQuery CreateVolumePermissionModifications where toQuery CreateVolumePermissionModifications{..} = mconcat [ "Add" `toQueryList` _cvpmAdd , "Remove" `toQueryList` _cvpmRemove ] data VpcState = VpcStateAvailable -- ^ available | VpcStatePending -- ^ pending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VpcState instance FromText VpcState where parser = takeLowerText >>= \case "available" -> pure VpcStateAvailable "pending" -> pure VpcStatePending e -> fail $ "Failure parsing VpcState from " ++ show e instance ToText VpcState where toText = \case VpcStateAvailable -> "available" VpcStatePending -> "pending" instance ToByteString VpcState instance ToHeader VpcState instance ToQuery VpcState instance FromXML VpcState where parseXML = parseXMLText "VpcState" data ResourceType = RTCustomerGateway -- ^ customer-gateway | RTDhcpOptions -- ^ dhcp-options | RTImage -- ^ image | RTInstance' -- ^ instance | RTInternetGateway -- ^ internet-gateway | RTNetworkAcl -- ^ network-acl | RTNetworkInterface -- ^ network-interface | RTReservedInstances -- ^ reserved-instances | RTRouteTable -- ^ route-table | RTSecurityGroup -- ^ security-group | RTSnapshot -- ^ snapshot | RTSpotInstancesRequest -- ^ spot-instances-request | RTSubnet -- ^ subnet | RTVolume -- ^ volume | RTVpc -- ^ vpc | RTVpnConnection -- ^ vpn-connection | RTVpnGateway -- ^ vpn-gateway deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ResourceType instance FromText ResourceType where parser = takeLowerText >>= \case "customer-gateway" -> pure RTCustomerGateway "dhcp-options" -> pure RTDhcpOptions "image" -> pure RTImage "instance" -> pure RTInstance' "internet-gateway" -> pure RTInternetGateway "network-acl" -> pure RTNetworkAcl "network-interface" -> pure RTNetworkInterface "reserved-instances" -> pure RTReservedInstances "route-table" -> pure RTRouteTable "security-group" -> pure RTSecurityGroup "snapshot" -> pure RTSnapshot "spot-instances-request" -> pure RTSpotInstancesRequest "subnet" -> pure RTSubnet "volume" -> pure RTVolume "vpc" -> pure RTVpc "vpn-connection" -> pure RTVpnConnection "vpn-gateway" -> pure RTVpnGateway e -> fail $ "Failure parsing ResourceType from " ++ show e instance ToText ResourceType where toText = \case RTCustomerGateway -> "customer-gateway" RTDhcpOptions -> "dhcp-options" RTImage -> "image" RTInstance' -> "instance" RTInternetGateway -> "internet-gateway" RTNetworkAcl -> "network-acl" RTNetworkInterface -> "network-interface" RTReservedInstances -> "reserved-instances" RTRouteTable -> "route-table" RTSecurityGroup -> "security-group" RTSnapshot -> "snapshot" RTSpotInstancesRequest -> "spot-instances-request" RTSubnet -> "subnet" RTVolume -> "volume" RTVpc -> "vpc" RTVpnConnection -> "vpn-connection" RTVpnGateway -> "vpn-gateway" instance ToByteString ResourceType instance ToHeader ResourceType instance ToQuery ResourceType instance FromXML ResourceType where parseXML = parseXMLText "ResourceType" data ReportStatusType = Impaired -- ^ impaired | Ok -- ^ ok deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ReportStatusType instance FromText ReportStatusType where parser = takeLowerText >>= \case "impaired" -> pure Impaired "ok" -> pure Ok e -> fail $ "Failure parsing ReportStatusType from " ++ show e instance ToText ReportStatusType where toText = \case Impaired -> "impaired" Ok -> "ok" instance ToByteString ReportStatusType instance ToHeader ReportStatusType instance ToQuery ReportStatusType instance FromXML ReportStatusType where parseXML = parseXMLText "ReportStatusType" data CurrencyCodeValues = Usd -- ^ USD deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable CurrencyCodeValues instance FromText CurrencyCodeValues where parser = takeLowerText >>= \case "usd" -> pure Usd e -> fail $ "Failure parsing CurrencyCodeValues from " ++ show e instance ToText CurrencyCodeValues where toText Usd = "USD" instance ToByteString CurrencyCodeValues instance ToHeader CurrencyCodeValues instance ToQuery CurrencyCodeValues instance FromXML CurrencyCodeValues where parseXML = parseXMLText "CurrencyCodeValues" data IcmpTypeCode = IcmpTypeCode { _itcCode :: Maybe Int , _itcType :: Maybe Int } deriving (Eq, Ord, Read, Show) -- | 'IcmpTypeCode' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'itcCode' @::@ 'Maybe' 'Int' -- -- * 'itcType' @::@ 'Maybe' 'Int' -- icmpTypeCode :: IcmpTypeCode icmpTypeCode = IcmpTypeCode { _itcType = Nothing , _itcCode = Nothing } -- | The ICMP type. A value of -1 means all types. itcCode :: Lens' IcmpTypeCode (Maybe Int) itcCode = lens _itcCode (\s a -> s { _itcCode = a }) -- | The ICMP code. A value of -1 means all codes for the specified ICMP type. itcType :: Lens' IcmpTypeCode (Maybe Int) itcType = lens _itcType (\s a -> s { _itcType = a }) instance FromXML IcmpTypeCode where parseXML x = IcmpTypeCode <$> x .@? "code" <*> x .@? "type" instance ToQuery IcmpTypeCode where toQuery IcmpTypeCode{..} = mconcat [ "Code" =? _itcCode , "Type" =? _itcType ] data InstanceCount = InstanceCount { _icInstanceCount :: Maybe Int , _icState :: Maybe ListingState } deriving (Eq, Read, Show) -- | 'InstanceCount' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'icInstanceCount' @::@ 'Maybe' 'Int' -- -- * 'icState' @::@ 'Maybe' 'ListingState' -- instanceCount :: InstanceCount instanceCount = InstanceCount { _icState = Nothing , _icInstanceCount = Nothing } -- | he number of listed Reserved Instances in the state specified by the 'state'. icInstanceCount :: Lens' InstanceCount (Maybe Int) icInstanceCount = lens _icInstanceCount (\s a -> s { _icInstanceCount = a }) -- | The states of the listed Reserved Instances. icState :: Lens' InstanceCount (Maybe ListingState) icState = lens _icState (\s a -> s { _icState = a }) instance FromXML InstanceCount where parseXML x = InstanceCount <$> x .@? "instanceCount" <*> x .@? "state" instance ToQuery InstanceCount where toQuery InstanceCount{..} = mconcat [ "InstanceCount" =? _icInstanceCount , "State" =? _icState ] data ExportToS3Task = ExportToS3Task { _etstContainerFormat :: Maybe ContainerFormat , _etstDiskImageFormat :: Maybe DiskImageFormat , _etstS3Bucket :: Maybe Text , _etstS3Key :: Maybe Text } deriving (Eq, Read, Show) -- | 'ExportToS3Task' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'etstContainerFormat' @::@ 'Maybe' 'ContainerFormat' -- -- * 'etstDiskImageFormat' @::@ 'Maybe' 'DiskImageFormat' -- -- * 'etstS3Bucket' @::@ 'Maybe' 'Text' -- -- * 'etstS3Key' @::@ 'Maybe' 'Text' -- exportToS3Task :: ExportToS3Task exportToS3Task = ExportToS3Task { _etstDiskImageFormat = Nothing , _etstContainerFormat = Nothing , _etstS3Bucket = Nothing , _etstS3Key = Nothing } -- | The container format used to combine disk images with metadata (such as OVF). -- If absent, only the disk image is exported. etstContainerFormat :: Lens' ExportToS3Task (Maybe ContainerFormat) etstContainerFormat = lens _etstContainerFormat (\s a -> s { _etstContainerFormat = a }) -- | The format for the exported image. etstDiskImageFormat :: Lens' ExportToS3Task (Maybe DiskImageFormat) etstDiskImageFormat = lens _etstDiskImageFormat (\s a -> s { _etstDiskImageFormat = a }) -- | The Amazon S3 bucket for the destination image. The destination bucket must -- exist and grant WRITE and READ_ACP permissions to the AWS account 'vm-import-export@amazon.com'. etstS3Bucket :: Lens' ExportToS3Task (Maybe Text) etstS3Bucket = lens _etstS3Bucket (\s a -> s { _etstS3Bucket = a }) etstS3Key :: Lens' ExportToS3Task (Maybe Text) etstS3Key = lens _etstS3Key (\s a -> s { _etstS3Key = a }) instance FromXML ExportToS3Task where parseXML x = ExportToS3Task <$> x .@? "containerFormat" <*> x .@? "diskImageFormat" <*> x .@? "s3Bucket" <*> x .@? "s3Key" instance ToQuery ExportToS3Task where toQuery ExportToS3Task{..} = mconcat [ "ContainerFormat" =? _etstContainerFormat , "DiskImageFormat" =? _etstDiskImageFormat , "S3Bucket" =? _etstS3Bucket , "S3Key" =? _etstS3Key ] data BlockDeviceMapping = BlockDeviceMapping { _bdmDeviceName :: Text , _bdmEbs :: Maybe EbsBlockDevice , _bdmNoDevice :: Maybe Text , _bdmVirtualName :: Maybe Text } deriving (Eq, Read, Show) -- | 'BlockDeviceMapping' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'bdmDeviceName' @::@ 'Text' -- -- * 'bdmEbs' @::@ 'Maybe' 'EbsBlockDevice' -- -- * 'bdmNoDevice' @::@ 'Maybe' 'Text' -- -- * 'bdmVirtualName' @::@ 'Maybe' 'Text' -- blockDeviceMapping :: Text -- ^ 'bdmDeviceName' -> BlockDeviceMapping blockDeviceMapping p1 = BlockDeviceMapping { _bdmDeviceName = p1 , _bdmVirtualName = Nothing , _bdmEbs = Nothing , _bdmNoDevice = Nothing } -- | The device name exposed to the instance (for example, '/dev/sdh' or 'xvdh'). bdmDeviceName :: Lens' BlockDeviceMapping Text bdmDeviceName = lens _bdmDeviceName (\s a -> s { _bdmDeviceName = a }) -- | Parameters used to automatically set up Amazon EBS volumes when the instance -- is launched. bdmEbs :: Lens' BlockDeviceMapping (Maybe EbsBlockDevice) bdmEbs = lens _bdmEbs (\s a -> s { _bdmEbs = a }) -- | Suppresses the specified device included in the block device mapping of the -- AMI. bdmNoDevice :: Lens' BlockDeviceMapping (Maybe Text) bdmNoDevice = lens _bdmNoDevice (\s a -> s { _bdmNoDevice = a }) -- | The virtual device name ('ephemeral'N). Instance store volumes are numbered -- starting from 0. An instance type with 2 available instance store volumes can -- specify mappings for 'ephemeral0' and 'ephemeral1'.The number of available -- instance store volumes depends on the instance type. After you connect to the -- instance, you must mount the volume. -- -- Constraints: For M3 instances, you must specify instance store volumes in -- the block device mapping for the instance. When you launch an M3 instance, we -- ignore any instance store volumes specified in the block device mapping for -- the AMI. bdmVirtualName :: Lens' BlockDeviceMapping (Maybe Text) bdmVirtualName = lens _bdmVirtualName (\s a -> s { _bdmVirtualName = a }) instance FromXML BlockDeviceMapping where parseXML x = BlockDeviceMapping <$> x .@ "deviceName" <*> x .@? "ebs" <*> x .@? "noDevice" <*> x .@? "virtualName" instance ToQuery BlockDeviceMapping where toQuery BlockDeviceMapping{..} = mconcat [ "DeviceName" =? _bdmDeviceName , "Ebs" =? _bdmEbs , "NoDevice" =? _bdmNoDevice , "VirtualName" =? _bdmVirtualName ] data ConversionTask = ConversionTask { _ctConversionTaskId :: Text , _ctExpirationTime :: Maybe Text , _ctImportInstance :: Maybe ImportInstanceTaskDetails , _ctImportVolume :: Maybe ImportVolumeTaskDetails , _ctState :: ConversionTaskState , _ctStatusMessage :: Maybe Text , _ctTags :: List "item" Tag } deriving (Eq, Read, Show) -- | 'ConversionTask' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ctConversionTaskId' @::@ 'Text' -- -- * 'ctExpirationTime' @::@ 'Maybe' 'Text' -- -- * 'ctImportInstance' @::@ 'Maybe' 'ImportInstanceTaskDetails' -- -- * 'ctImportVolume' @::@ 'Maybe' 'ImportVolumeTaskDetails' -- -- * 'ctState' @::@ 'ConversionTaskState' -- -- * 'ctStatusMessage' @::@ 'Maybe' 'Text' -- -- * 'ctTags' @::@ ['Tag'] -- conversionTask :: Text -- ^ 'ctConversionTaskId' -> ConversionTaskState -- ^ 'ctState' -> ConversionTask conversionTask p1 p2 = ConversionTask { _ctConversionTaskId = p1 , _ctState = p2 , _ctExpirationTime = Nothing , _ctImportInstance = Nothing , _ctImportVolume = Nothing , _ctStatusMessage = Nothing , _ctTags = mempty } -- | The ID of the conversion task. ctConversionTaskId :: Lens' ConversionTask Text ctConversionTaskId = lens _ctConversionTaskId (\s a -> s { _ctConversionTaskId = a }) -- | The time when the task expires. If the upload isn't complete before the -- expiration time, we automatically cancel the task. ctExpirationTime :: Lens' ConversionTask (Maybe Text) ctExpirationTime = lens _ctExpirationTime (\s a -> s { _ctExpirationTime = a }) -- | If the task is for importing an instance, this contains information about the -- import instance task. ctImportInstance :: Lens' ConversionTask (Maybe ImportInstanceTaskDetails) ctImportInstance = lens _ctImportInstance (\s a -> s { _ctImportInstance = a }) -- | If the task is for importing a volume, this contains information about the -- import volume task. ctImportVolume :: Lens' ConversionTask (Maybe ImportVolumeTaskDetails) ctImportVolume = lens _ctImportVolume (\s a -> s { _ctImportVolume = a }) -- | The state of the conversion task. ctState :: Lens' ConversionTask ConversionTaskState ctState = lens _ctState (\s a -> s { _ctState = a }) -- | The status message related to the conversion task. ctStatusMessage :: Lens' ConversionTask (Maybe Text) ctStatusMessage = lens _ctStatusMessage (\s a -> s { _ctStatusMessage = a }) ctTags :: Lens' ConversionTask [Tag] ctTags = lens _ctTags (\s a -> s { _ctTags = a }) . _List instance FromXML ConversionTask where parseXML x = ConversionTask <$> x .@ "conversionTaskId" <*> x .@? "expirationTime" <*> x .@? "importInstance" <*> x .@? "importVolume" <*> x .@ "state" <*> x .@? "statusMessage" <*> x .@? "tagSet" .!@ mempty instance ToQuery ConversionTask where toQuery ConversionTask{..} = mconcat [ "ConversionTaskId" =? _ctConversionTaskId , "ExpirationTime" =? _ctExpirationTime , "ImportInstance" =? _ctImportInstance , "ImportVolume" =? _ctImportVolume , "State" =? _ctState , "StatusMessage" =? _ctStatusMessage , "TagSet" `toQueryList` _ctTags ] data AttachmentStatus = ASAttached -- ^ attached | ASAttaching -- ^ attaching | ASDetached -- ^ detached | ASDetaching -- ^ detaching deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable AttachmentStatus instance FromText AttachmentStatus where parser = takeLowerText >>= \case "attached" -> pure ASAttached "attaching" -> pure ASAttaching "detached" -> pure ASDetached "detaching" -> pure ASDetaching e -> fail $ "Failure parsing AttachmentStatus from " ++ show e instance ToText AttachmentStatus where toText = \case ASAttached -> "attached" ASAttaching -> "attaching" ASDetached -> "detached" ASDetaching -> "detaching" instance ToByteString AttachmentStatus instance ToHeader AttachmentStatus instance ToQuery AttachmentStatus instance FromXML AttachmentStatus where parseXML = parseXMLText "AttachmentStatus" data ClassicLinkInstance = ClassicLinkInstance { _cliGroups :: List "item" GroupIdentifier , _cliInstanceId :: Maybe Text , _cliTags :: List "item" Tag , _cliVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'ClassicLinkInstance' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cliGroups' @::@ ['GroupIdentifier'] -- -- * 'cliInstanceId' @::@ 'Maybe' 'Text' -- -- * 'cliTags' @::@ ['Tag'] -- -- * 'cliVpcId' @::@ 'Maybe' 'Text' -- classicLinkInstance :: ClassicLinkInstance classicLinkInstance = ClassicLinkInstance { _cliInstanceId = Nothing , _cliVpcId = Nothing , _cliGroups = mempty , _cliTags = mempty } -- | A list of security groups. cliGroups :: Lens' ClassicLinkInstance [GroupIdentifier] cliGroups = lens _cliGroups (\s a -> s { _cliGroups = a }) . _List -- | The ID of the instance. cliInstanceId :: Lens' ClassicLinkInstance (Maybe Text) cliInstanceId = lens _cliInstanceId (\s a -> s { _cliInstanceId = a }) -- | Any tags assigned to the instance. cliTags :: Lens' ClassicLinkInstance [Tag] cliTags = lens _cliTags (\s a -> s { _cliTags = a }) . _List -- | The ID of the VPC. cliVpcId :: Lens' ClassicLinkInstance (Maybe Text) cliVpcId = lens _cliVpcId (\s a -> s { _cliVpcId = a }) instance FromXML ClassicLinkInstance where parseXML x = ClassicLinkInstance <$> x .@? "groupSet" .!@ mempty <*> x .@? "instanceId" <*> x .@? "tagSet" .!@ mempty <*> x .@? "vpcId" instance ToQuery ClassicLinkInstance where toQuery ClassicLinkInstance{..} = mconcat [ "GroupSet" `toQueryList` _cliGroups , "InstanceId" =? _cliInstanceId , "TagSet" `toQueryList` _cliTags , "VpcId" =? _cliVpcId ] data RouteOrigin = OriginCreateRoute -- ^ CreateRoute | OriginCreateRouteTable -- ^ CreateRouteTable | OriginEnableVgwRoutePropagation -- ^ EnableVgwRoutePropagation deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable RouteOrigin instance FromText RouteOrigin where parser = takeLowerText >>= \case "createroute" -> pure OriginCreateRoute "createroutetable" -> pure OriginCreateRouteTable "enablevgwroutepropagation" -> pure OriginEnableVgwRoutePropagation e -> fail $ "Failure parsing RouteOrigin from " ++ show e instance ToText RouteOrigin where toText = \case OriginCreateRoute -> "CreateRoute" OriginCreateRouteTable -> "CreateRouteTable" OriginEnableVgwRoutePropagation -> "EnableVgwRoutePropagation" instance ToByteString RouteOrigin instance ToHeader RouteOrigin instance ToQuery RouteOrigin instance FromXML RouteOrigin where parseXML = parseXMLText "RouteOrigin" data ListingState = LSAvailable -- ^ available | LSCancelled -- ^ cancelled | LSPending -- ^ pending | LSSold -- ^ sold deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ListingState instance FromText ListingState where parser = takeLowerText >>= \case "available" -> pure LSAvailable "cancelled" -> pure LSCancelled "pending" -> pure LSPending "sold" -> pure LSSold e -> fail $ "Failure parsing ListingState from " ++ show e instance ToText ListingState where toText = \case LSAvailable -> "available" LSCancelled -> "cancelled" LSPending -> "pending" LSSold -> "sold" instance ToByteString ListingState instance ToHeader ListingState instance ToQuery ListingState instance FromXML ListingState where parseXML = parseXMLText "ListingState" data SpotPrice = SpotPrice { _spAvailabilityZone :: Maybe Text , _spInstanceType :: Maybe InstanceType , _spProductDescription :: Maybe RIProductDescription , _spSpotPrice :: Maybe Text , _spTimestamp :: Maybe ISO8601 } deriving (Eq, Read, Show) -- | 'SpotPrice' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'spAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'spInstanceType' @::@ 'Maybe' 'InstanceType' -- -- * 'spProductDescription' @::@ 'Maybe' 'RIProductDescription' -- -- * 'spSpotPrice' @::@ 'Maybe' 'Text' -- -- * 'spTimestamp' @::@ 'Maybe' 'UTCTime' -- spotPrice :: SpotPrice spotPrice = SpotPrice { _spInstanceType = Nothing , _spProductDescription = Nothing , _spSpotPrice = Nothing , _spTimestamp = Nothing , _spAvailabilityZone = Nothing } -- | The Availability Zone. spAvailabilityZone :: Lens' SpotPrice (Maybe Text) spAvailabilityZone = lens _spAvailabilityZone (\s a -> s { _spAvailabilityZone = a }) -- | The instance type. spInstanceType :: Lens' SpotPrice (Maybe InstanceType) spInstanceType = lens _spInstanceType (\s a -> s { _spInstanceType = a }) -- | A general description of the AMI. spProductDescription :: Lens' SpotPrice (Maybe RIProductDescription) spProductDescription = lens _spProductDescription (\s a -> s { _spProductDescription = a }) -- | The maximum price (bid) that you are willing to pay for a Spot Instance. spSpotPrice :: Lens' SpotPrice (Maybe Text) spSpotPrice = lens _spSpotPrice (\s a -> s { _spSpotPrice = a }) -- | The date and time the request was created. spTimestamp :: Lens' SpotPrice (Maybe UTCTime) spTimestamp = lens _spTimestamp (\s a -> s { _spTimestamp = a }) . mapping _Time instance FromXML SpotPrice where parseXML x = SpotPrice <$> x .@? "availabilityZone" <*> x .@? "instanceType" <*> x .@? "productDescription" <*> x .@? "spotPrice" <*> x .@? "timestamp" instance ToQuery SpotPrice where toQuery SpotPrice{..} = mconcat [ "AvailabilityZone" =? _spAvailabilityZone , "InstanceType" =? _spInstanceType , "ProductDescription" =? _spProductDescription , "SpotPrice" =? _spSpotPrice , "Timestamp" =? _spTimestamp ] data InstanceMonitoring = InstanceMonitoring { _imInstanceId :: Maybe Text , _imMonitoring :: Maybe Monitoring } deriving (Eq, Read, Show) -- | 'InstanceMonitoring' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'imInstanceId' @::@ 'Maybe' 'Text' -- -- * 'imMonitoring' @::@ 'Maybe' 'Monitoring' -- instanceMonitoring :: InstanceMonitoring instanceMonitoring = InstanceMonitoring { _imInstanceId = Nothing , _imMonitoring = Nothing } -- | The ID of the instance. imInstanceId :: Lens' InstanceMonitoring (Maybe Text) imInstanceId = lens _imInstanceId (\s a -> s { _imInstanceId = a }) -- | The monitoring information. imMonitoring :: Lens' InstanceMonitoring (Maybe Monitoring) imMonitoring = lens _imMonitoring (\s a -> s { _imMonitoring = a }) instance FromXML InstanceMonitoring where parseXML x = InstanceMonitoring <$> x .@? "instanceId" <*> x .@? "monitoring" instance ToQuery InstanceMonitoring where toQuery InstanceMonitoring{..} = mconcat [ "InstanceId" =? _imInstanceId , "Monitoring" =? _imMonitoring ] data PriceScheduleSpecification = PriceScheduleSpecification { _pssCurrencyCode :: Maybe CurrencyCodeValues , _pssPrice :: Maybe Double , _pssTerm :: Maybe Integer } deriving (Eq, Read, Show) -- | 'PriceScheduleSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pssCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues' -- -- * 'pssPrice' @::@ 'Maybe' 'Double' -- -- * 'pssTerm' @::@ 'Maybe' 'Integer' -- priceScheduleSpecification :: PriceScheduleSpecification priceScheduleSpecification = PriceScheduleSpecification { _pssTerm = Nothing , _pssPrice = Nothing , _pssCurrencyCode = Nothing } -- | The currency for transacting the Reserved Instance resale. At this time, the -- only supported currency is 'USD'. pssCurrencyCode :: Lens' PriceScheduleSpecification (Maybe CurrencyCodeValues) pssCurrencyCode = lens _pssCurrencyCode (\s a -> s { _pssCurrencyCode = a }) -- | The fixed price for the term. pssPrice :: Lens' PriceScheduleSpecification (Maybe Double) pssPrice = lens _pssPrice (\s a -> s { _pssPrice = a }) -- | The number of months remaining in the reservation. For example, 2 is the -- second to the last month before the capacity reservation expires. pssTerm :: Lens' PriceScheduleSpecification (Maybe Integer) pssTerm = lens _pssTerm (\s a -> s { _pssTerm = a }) instance FromXML PriceScheduleSpecification where parseXML x = PriceScheduleSpecification <$> x .@? "currencyCode" <*> x .@? "price" <*> x .@? "term" instance ToQuery PriceScheduleSpecification where toQuery PriceScheduleSpecification{..} = mconcat [ "CurrencyCode" =? _pssCurrencyCode , "Price" =? _pssPrice , "Term" =? _pssTerm ] data SpotInstanceStatus = SpotInstanceStatus { _sisCode :: Maybe Text , _sisMessage :: Maybe Text , _sisUpdateTime :: Maybe ISO8601 } deriving (Eq, Ord, Read, Show) -- | 'SpotInstanceStatus' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sisCode' @::@ 'Maybe' 'Text' -- -- * 'sisMessage' @::@ 'Maybe' 'Text' -- -- * 'sisUpdateTime' @::@ 'Maybe' 'UTCTime' -- spotInstanceStatus :: SpotInstanceStatus spotInstanceStatus = SpotInstanceStatus { _sisCode = Nothing , _sisUpdateTime = Nothing , _sisMessage = Nothing } -- | The status code. sisCode :: Lens' SpotInstanceStatus (Maybe Text) sisCode = lens _sisCode (\s a -> s { _sisCode = a }) -- | The description for the status code. sisMessage :: Lens' SpotInstanceStatus (Maybe Text) sisMessage = lens _sisMessage (\s a -> s { _sisMessage = a }) -- | The time of the most recent status update. sisUpdateTime :: Lens' SpotInstanceStatus (Maybe UTCTime) sisUpdateTime = lens _sisUpdateTime (\s a -> s { _sisUpdateTime = a }) . mapping _Time instance FromXML SpotInstanceStatus where parseXML x = SpotInstanceStatus <$> x .@? "code" <*> x .@? "message" <*> x .@? "updateTime" instance ToQuery SpotInstanceStatus where toQuery SpotInstanceStatus{..} = mconcat [ "Code" =? _sisCode , "Message" =? _sisMessage , "UpdateTime" =? _sisUpdateTime ] data AvailabilityZoneState = AZSAvailable -- ^ available deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable AvailabilityZoneState instance FromText AvailabilityZoneState where parser = takeLowerText >>= \case "available" -> pure AZSAvailable e -> fail $ "Failure parsing AvailabilityZoneState from " ++ show e instance ToText AvailabilityZoneState where toText AZSAvailable = "available" instance ToByteString AvailabilityZoneState instance ToHeader AvailabilityZoneState instance ToQuery AvailabilityZoneState instance FromXML AvailabilityZoneState where parseXML = parseXMLText "AvailabilityZoneState" data SpotInstanceRequest = SpotInstanceRequest { _siAvailabilityZoneGroup :: Maybe Text , _siCreateTime :: Maybe ISO8601 , _siFault :: Maybe SpotInstanceStateFault , _siInstanceId :: Maybe Text , _siLaunchGroup :: Maybe Text , _siLaunchSpecification :: Maybe LaunchSpecification , _siLaunchedAvailabilityZone :: Maybe Text , _siProductDescription :: Maybe RIProductDescription , _siSpotInstanceRequestId :: Maybe Text , _siSpotPrice :: Maybe Text , _siState :: Maybe SpotInstanceState , _siStatus :: Maybe SpotInstanceStatus , _siTags :: List "item" Tag , _siType :: Maybe SpotInstanceType , _siValidFrom :: Maybe ISO8601 , _siValidUntil :: Maybe ISO8601 } deriving (Eq, Read, Show) -- | 'SpotInstanceRequest' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'siAvailabilityZoneGroup' @::@ 'Maybe' 'Text' -- -- * 'siCreateTime' @::@ 'Maybe' 'UTCTime' -- -- * 'siFault' @::@ 'Maybe' 'SpotInstanceStateFault' -- -- * 'siInstanceId' @::@ 'Maybe' 'Text' -- -- * 'siLaunchGroup' @::@ 'Maybe' 'Text' -- -- * 'siLaunchSpecification' @::@ 'Maybe' 'LaunchSpecification' -- -- * 'siLaunchedAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'siProductDescription' @::@ 'Maybe' 'RIProductDescription' -- -- * 'siSpotInstanceRequestId' @::@ 'Maybe' 'Text' -- -- * 'siSpotPrice' @::@ 'Maybe' 'Text' -- -- * 'siState' @::@ 'Maybe' 'SpotInstanceState' -- -- * 'siStatus' @::@ 'Maybe' 'SpotInstanceStatus' -- -- * 'siTags' @::@ ['Tag'] -- -- * 'siType' @::@ 'Maybe' 'SpotInstanceType' -- -- * 'siValidFrom' @::@ 'Maybe' 'UTCTime' -- -- * 'siValidUntil' @::@ 'Maybe' 'UTCTime' -- spotInstanceRequest :: SpotInstanceRequest spotInstanceRequest = SpotInstanceRequest { _siSpotInstanceRequestId = Nothing , _siSpotPrice = Nothing , _siType = Nothing , _siState = Nothing , _siFault = Nothing , _siStatus = Nothing , _siValidFrom = Nothing , _siValidUntil = Nothing , _siLaunchGroup = Nothing , _siAvailabilityZoneGroup = Nothing , _siLaunchSpecification = Nothing , _siInstanceId = Nothing , _siCreateTime = Nothing , _siProductDescription = Nothing , _siTags = mempty , _siLaunchedAvailabilityZone = Nothing } -- | 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. siAvailabilityZoneGroup :: Lens' SpotInstanceRequest (Maybe Text) siAvailabilityZoneGroup = lens _siAvailabilityZoneGroup (\s a -> s { _siAvailabilityZoneGroup = a }) -- | The time stamp when the Spot Instance request was created. siCreateTime :: Lens' SpotInstanceRequest (Maybe UTCTime) siCreateTime = lens _siCreateTime (\s a -> s { _siCreateTime = a }) . mapping _Time -- | The fault codes for the Spot Instance request, if any. siFault :: Lens' SpotInstanceRequest (Maybe SpotInstanceStateFault) siFault = lens _siFault (\s a -> s { _siFault = a }) -- | The instance ID, if an instance has been launched to fulfill the Spot -- Instance request. siInstanceId :: Lens' SpotInstanceRequest (Maybe Text) siInstanceId = lens _siInstanceId (\s a -> s { _siInstanceId = a }) -- | The instance launch group. Launch groups are Spot Instances that launch -- together and terminate together. siLaunchGroup :: Lens' SpotInstanceRequest (Maybe Text) siLaunchGroup = lens _siLaunchGroup (\s a -> s { _siLaunchGroup = a }) -- | Additional information for launching instances. siLaunchSpecification :: Lens' SpotInstanceRequest (Maybe LaunchSpecification) siLaunchSpecification = lens _siLaunchSpecification (\s a -> s { _siLaunchSpecification = a }) -- | The Availability Zone in which the bid is launched. siLaunchedAvailabilityZone :: Lens' SpotInstanceRequest (Maybe Text) siLaunchedAvailabilityZone = lens _siLaunchedAvailabilityZone (\s a -> s { _siLaunchedAvailabilityZone = a }) -- | The product description associated with the Spot Instance. siProductDescription :: Lens' SpotInstanceRequest (Maybe RIProductDescription) siProductDescription = lens _siProductDescription (\s a -> s { _siProductDescription = a }) -- | The ID of the Spot Instance request. siSpotInstanceRequestId :: Lens' SpotInstanceRequest (Maybe Text) siSpotInstanceRequestId = lens _siSpotInstanceRequestId (\s a -> s { _siSpotInstanceRequestId = a }) -- | The maximum hourly price (bid) for any Spot Instance launched to fulfill the -- request. siSpotPrice :: Lens' SpotInstanceRequest (Maybe Text) siSpotPrice = lens _siSpotPrice (\s a -> s { _siSpotPrice = a }) -- | The state of the Spot Instance request. Spot bid status information can help -- you track your Spot Instance requests. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html Spot BidStatus> in the /Amazon Elastic Compute Cloud User Guide for Linux/. siState :: Lens' SpotInstanceRequest (Maybe SpotInstanceState) siState = lens _siState (\s a -> s { _siState = a }) -- | The status code and status message describing the Spot Instance request. siStatus :: Lens' SpotInstanceRequest (Maybe SpotInstanceStatus) siStatus = lens _siStatus (\s a -> s { _siStatus = a }) -- | Any tags assigned to the resource. siTags :: Lens' SpotInstanceRequest [Tag] siTags = lens _siTags (\s a -> s { _siTags = a }) . _List -- | The Spot Instance request type. siType :: Lens' SpotInstanceRequest (Maybe SpotInstanceType) siType = lens _siType (\s a -> s { _siType = a }) -- | 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. siValidFrom :: Lens' SpotInstanceRequest (Maybe UTCTime) siValidFrom = lens _siValidFrom (\s a -> s { _siValidFrom = a }) . mapping _Time -- | The end date of the request. If this is a one-time request, the request -- remains active until all instances launch, the request is canceled, or this -- date is reached. If the request is persistent, it remains active until it is -- canceled or this date is reached. siValidUntil :: Lens' SpotInstanceRequest (Maybe UTCTime) siValidUntil = lens _siValidUntil (\s a -> s { _siValidUntil = a }) . mapping _Time instance FromXML SpotInstanceRequest where parseXML x = SpotInstanceRequest <$> x .@? "availabilityZoneGroup" <*> x .@? "createTime" <*> x .@? "fault" <*> x .@? "instanceId" <*> x .@? "launchGroup" <*> x .@? "launchSpecification" <*> x .@? "launchedAvailabilityZone" <*> x .@? "productDescription" <*> x .@? "spotInstanceRequestId" <*> x .@? "spotPrice" <*> x .@? "state" <*> x .@? "status" <*> x .@? "tagSet" .!@ mempty <*> x .@? "type" <*> x .@? "validFrom" <*> x .@? "validUntil" instance ToQuery SpotInstanceRequest where toQuery SpotInstanceRequest{..} = mconcat [ "AvailabilityZoneGroup" =? _siAvailabilityZoneGroup , "CreateTime" =? _siCreateTime , "Fault" =? _siFault , "InstanceId" =? _siInstanceId , "LaunchGroup" =? _siLaunchGroup , "LaunchSpecification" =? _siLaunchSpecification , "LaunchedAvailabilityZone" =? _siLaunchedAvailabilityZone , "ProductDescription" =? _siProductDescription , "SpotInstanceRequestId" =? _siSpotInstanceRequestId , "SpotPrice" =? _siSpotPrice , "State" =? _siState , "Status" =? _siStatus , "TagSet" `toQueryList` _siTags , "Type" =? _siType , "ValidFrom" =? _siValidFrom , "ValidUntil" =? _siValidUntil ] data LaunchSpecification = LaunchSpecification { _lsAddressingType :: Maybe Text , _lsBlockDeviceMappings :: List "item" BlockDeviceMapping , _lsEbsOptimized :: Maybe Bool , _lsIamInstanceProfile :: Maybe IamInstanceProfileSpecification , _lsImageId :: Maybe Text , _lsInstanceType :: Maybe InstanceType , _lsKernelId :: Maybe Text , _lsKeyName :: Maybe Text , _lsMonitoring :: Maybe RunInstancesMonitoringEnabled , _lsNetworkInterfaces :: List "item" InstanceNetworkInterfaceSpecification , _lsPlacement :: Maybe SpotPlacement , _lsRamdiskId :: Maybe Text , _lsSecurityGroups :: List "item" GroupIdentifier , _lsSubnetId :: Maybe Text , _lsUserData :: Maybe Text } deriving (Eq, Read, Show) -- | 'LaunchSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lsAddressingType' @::@ 'Maybe' 'Text' -- -- * 'lsBlockDeviceMappings' @::@ ['BlockDeviceMapping'] -- -- * 'lsEbsOptimized' @::@ 'Maybe' 'Bool' -- -- * 'lsIamInstanceProfile' @::@ 'Maybe' 'IamInstanceProfileSpecification' -- -- * 'lsImageId' @::@ 'Maybe' 'Text' -- -- * 'lsInstanceType' @::@ 'Maybe' 'InstanceType' -- -- * 'lsKernelId' @::@ 'Maybe' 'Text' -- -- * 'lsKeyName' @::@ 'Maybe' 'Text' -- -- * 'lsMonitoring' @::@ 'Maybe' 'RunInstancesMonitoringEnabled' -- -- * 'lsNetworkInterfaces' @::@ ['InstanceNetworkInterfaceSpecification'] -- -- * 'lsPlacement' @::@ 'Maybe' 'SpotPlacement' -- -- * 'lsRamdiskId' @::@ 'Maybe' 'Text' -- -- * 'lsSecurityGroups' @::@ ['GroupIdentifier'] -- -- * 'lsSubnetId' @::@ 'Maybe' 'Text' -- -- * 'lsUserData' @::@ 'Maybe' 'Text' -- launchSpecification :: LaunchSpecification launchSpecification = LaunchSpecification { _lsImageId = Nothing , _lsKeyName = Nothing , _lsSecurityGroups = mempty , _lsUserData = Nothing , _lsAddressingType = Nothing , _lsInstanceType = Nothing , _lsPlacement = Nothing , _lsKernelId = Nothing , _lsRamdiskId = Nothing , _lsBlockDeviceMappings = mempty , _lsSubnetId = Nothing , _lsNetworkInterfaces = mempty , _lsIamInstanceProfile = Nothing , _lsEbsOptimized = Nothing , _lsMonitoring = Nothing } -- | Deprecated. lsAddressingType :: Lens' LaunchSpecification (Maybe Text) lsAddressingType = lens _lsAddressingType (\s a -> s { _lsAddressingType = a }) -- | One or more block device mapping entries. lsBlockDeviceMappings :: Lens' LaunchSpecification [BlockDeviceMapping] lsBlockDeviceMappings = lens _lsBlockDeviceMappings (\s a -> s { _lsBlockDeviceMappings = a }) . _List -- | 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. -- -- Default: 'false' lsEbsOptimized :: Lens' LaunchSpecification (Maybe Bool) lsEbsOptimized = lens _lsEbsOptimized (\s a -> s { _lsEbsOptimized = a }) -- | The IAM instance profile. lsIamInstanceProfile :: Lens' LaunchSpecification (Maybe IamInstanceProfileSpecification) lsIamInstanceProfile = lens _lsIamInstanceProfile (\s a -> s { _lsIamInstanceProfile = a }) -- | The ID of the AMI. lsImageId :: Lens' LaunchSpecification (Maybe Text) lsImageId = lens _lsImageId (\s a -> s { _lsImageId = a }) -- | The instance type. lsInstanceType :: Lens' LaunchSpecification (Maybe InstanceType) lsInstanceType = lens _lsInstanceType (\s a -> s { _lsInstanceType = a }) -- | The ID of the kernel. lsKernelId :: Lens' LaunchSpecification (Maybe Text) lsKernelId = lens _lsKernelId (\s a -> s { _lsKernelId = a }) -- | The name of the key pair. lsKeyName :: Lens' LaunchSpecification (Maybe Text) lsKeyName = lens _lsKeyName (\s a -> s { _lsKeyName = a }) lsMonitoring :: Lens' LaunchSpecification (Maybe RunInstancesMonitoringEnabled) lsMonitoring = lens _lsMonitoring (\s a -> s { _lsMonitoring = a }) -- | One or more network interfaces. lsNetworkInterfaces :: Lens' LaunchSpecification [InstanceNetworkInterfaceSpecification] lsNetworkInterfaces = lens _lsNetworkInterfaces (\s a -> s { _lsNetworkInterfaces = a }) . _List -- | The placement information for the instance. lsPlacement :: Lens' LaunchSpecification (Maybe SpotPlacement) lsPlacement = lens _lsPlacement (\s a -> s { _lsPlacement = a }) -- | The ID of the RAM disk. lsRamdiskId :: Lens' LaunchSpecification (Maybe Text) lsRamdiskId = lens _lsRamdiskId (\s a -> s { _lsRamdiskId = a }) -- | One or more security groups. To request an instance in a nondefault VPC, you -- must specify the ID of the security group. To request an instance in -- EC2-Classic or a default VPC, you can specify the name or the ID of the -- security group. lsSecurityGroups :: Lens' LaunchSpecification [GroupIdentifier] lsSecurityGroups = lens _lsSecurityGroups (\s a -> s { _lsSecurityGroups = a }) . _List -- | The ID of the subnet in which to launch the instance. lsSubnetId :: Lens' LaunchSpecification (Maybe Text) lsSubnetId = lens _lsSubnetId (\s a -> s { _lsSubnetId = a }) -- | The Base64-encoded MIME user data to make available to the instances. lsUserData :: Lens' LaunchSpecification (Maybe Text) lsUserData = lens _lsUserData (\s a -> s { _lsUserData = a }) instance FromXML LaunchSpecification where parseXML x = LaunchSpecification <$> x .@? "addressingType" <*> x .@? "blockDeviceMapping" .!@ mempty <*> x .@? "ebsOptimized" <*> x .@? "iamInstanceProfile" <*> x .@? "imageId" <*> x .@? "instanceType" <*> x .@? "kernelId" <*> x .@? "keyName" <*> x .@? "monitoring" <*> x .@? "networkInterfaceSet" .!@ mempty <*> x .@? "placement" <*> x .@? "ramdiskId" <*> x .@? "groupSet" .!@ mempty <*> x .@? "subnetId" <*> x .@? "userData" instance ToQuery LaunchSpecification where toQuery LaunchSpecification{..} = mconcat [ "AddressingType" =? _lsAddressingType , "BlockDeviceMapping" `toQueryList` _lsBlockDeviceMappings , "EbsOptimized" =? _lsEbsOptimized , "IamInstanceProfile" =? _lsIamInstanceProfile , "ImageId" =? _lsImageId , "InstanceType" =? _lsInstanceType , "KernelId" =? _lsKernelId , "KeyName" =? _lsKeyName , "Monitoring" =? _lsMonitoring , "NetworkInterfaceSet" `toQueryList` _lsNetworkInterfaces , "Placement" =? _lsPlacement , "RamdiskId" =? _lsRamdiskId , "GroupSet" `toQueryList` _lsSecurityGroups , "SubnetId" =? _lsSubnetId , "UserData" =? _lsUserData ] data VolumeStatusEvent = VolumeStatusEvent { _vseDescription :: Maybe Text , _vseEventId :: Maybe Text , _vseEventType :: Maybe Text , _vseNotAfter :: Maybe ISO8601 , _vseNotBefore :: Maybe ISO8601 } deriving (Eq, Ord, Read, Show) -- | 'VolumeStatusEvent' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vseDescription' @::@ 'Maybe' 'Text' -- -- * 'vseEventId' @::@ 'Maybe' 'Text' -- -- * 'vseEventType' @::@ 'Maybe' 'Text' -- -- * 'vseNotAfter' @::@ 'Maybe' 'UTCTime' -- -- * 'vseNotBefore' @::@ 'Maybe' 'UTCTime' -- volumeStatusEvent :: VolumeStatusEvent volumeStatusEvent = VolumeStatusEvent { _vseEventType = Nothing , _vseDescription = Nothing , _vseNotBefore = Nothing , _vseNotAfter = Nothing , _vseEventId = Nothing } -- | A description of the event. vseDescription :: Lens' VolumeStatusEvent (Maybe Text) vseDescription = lens _vseDescription (\s a -> s { _vseDescription = a }) -- | The ID of this event. vseEventId :: Lens' VolumeStatusEvent (Maybe Text) vseEventId = lens _vseEventId (\s a -> s { _vseEventId = a }) -- | The type of this event. vseEventType :: Lens' VolumeStatusEvent (Maybe Text) vseEventType = lens _vseEventType (\s a -> s { _vseEventType = a }) -- | The latest end time of the event. vseNotAfter :: Lens' VolumeStatusEvent (Maybe UTCTime) vseNotAfter = lens _vseNotAfter (\s a -> s { _vseNotAfter = a }) . mapping _Time -- | The earliest start time of the event. vseNotBefore :: Lens' VolumeStatusEvent (Maybe UTCTime) vseNotBefore = lens _vseNotBefore (\s a -> s { _vseNotBefore = a }) . mapping _Time instance FromXML VolumeStatusEvent where parseXML x = VolumeStatusEvent <$> x .@? "description" <*> x .@? "eventId" <*> x .@? "eventType" <*> x .@? "notAfter" <*> x .@? "notBefore" instance ToQuery VolumeStatusEvent where toQuery VolumeStatusEvent{..} = mconcat [ "Description" =? _vseDescription , "EventId" =? _vseEventId , "EventType" =? _vseEventType , "NotAfter" =? _vseNotAfter , "NotBefore" =? _vseNotBefore ] data Volume = Volume { _vAttachments :: List "item" VolumeAttachment , _vAvailabilityZone :: Text , _vCreateTime :: ISO8601 , _vEncrypted :: Bool , _vIops :: Maybe Int , _vKmsKeyId :: Maybe Text , _vSize :: Int , _vSnapshotId :: Text , _vState :: VolumeState , _vTags :: List "item" Tag , _vVolumeId :: Text , _vVolumeType :: VolumeType } deriving (Eq, Read, Show) -- | 'Volume' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vAttachments' @::@ ['VolumeAttachment'] -- -- * 'vAvailabilityZone' @::@ 'Text' -- -- * 'vCreateTime' @::@ 'UTCTime' -- -- * 'vEncrypted' @::@ 'Bool' -- -- * 'vIops' @::@ 'Maybe' 'Int' -- -- * 'vKmsKeyId' @::@ 'Maybe' 'Text' -- -- * 'vSize' @::@ 'Int' -- -- * 'vSnapshotId' @::@ 'Text' -- -- * 'vState' @::@ 'VolumeState' -- -- * 'vTags' @::@ ['Tag'] -- -- * 'vVolumeId' @::@ 'Text' -- -- * 'vVolumeType' @::@ 'VolumeType' -- volume :: Text -- ^ 'vVolumeId' -> Int -- ^ 'vSize' -> Text -- ^ 'vSnapshotId' -> Text -- ^ 'vAvailabilityZone' -> VolumeState -- ^ 'vState' -> UTCTime -- ^ 'vCreateTime' -> VolumeType -- ^ 'vVolumeType' -> Bool -- ^ 'vEncrypted' -> Volume volume p1 p2 p3 p4 p5 p6 p7 p8 = Volume { _vVolumeId = p1 , _vSize = p2 , _vSnapshotId = p3 , _vAvailabilityZone = p4 , _vState = p5 , _vCreateTime = withIso _Time (const id) p6 , _vVolumeType = p7 , _vEncrypted = p8 , _vAttachments = mempty , _vTags = mempty , _vIops = Nothing , _vKmsKeyId = Nothing } vAttachments :: Lens' Volume [VolumeAttachment] vAttachments = lens _vAttachments (\s a -> s { _vAttachments = a }) . _List -- | The Availability Zone for the volume. vAvailabilityZone :: Lens' Volume Text vAvailabilityZone = lens _vAvailabilityZone (\s a -> s { _vAvailabilityZone = a }) -- | The time stamp when volume creation was initiated. vCreateTime :: Lens' Volume UTCTime vCreateTime = lens _vCreateTime (\s a -> s { _vCreateTime = a }) . _Time -- | Indicates whether the volume will be encrypted. vEncrypted :: Lens' Volume Bool vEncrypted = lens _vEncrypted (\s a -> s { _vEncrypted = a }) -- | The number of I/O operations per second (IOPS) that the volume supports. For -- Provisioned IOPS (SSD) volumes, this represents the number of IOPS that are -- provisioned for the volume. For General Purpose (SSD) volumes, this -- represents the baseline performance of the volume and the rate at which the -- volume accumulates I/O credits for bursting. For more information on General -- Purpose (SSD) baseline performance, I/O credits, and bursting, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html Amazon EBSVolume Types> in the /Amazon Elastic Compute Cloud User Guide for Linux/. -- -- Constraint: Range is 100 to 20000 for Provisioned IOPS (SSD) volumes and 3 -- to 10000 for General Purpose (SSD) volumes. -- -- Condition: This parameter is required for requests to create 'io1' volumes; it -- is not used in requests to create 'standard' or 'gp2' volumes. vIops :: Lens' Volume (Maybe Int) vIops = lens _vIops (\s a -> s { _vIops = a }) -- | The full ARN of the AWS Key Management Service (KMS) master key that was used -- to protect the volume encryption key for the volume. vKmsKeyId :: Lens' Volume (Maybe Text) vKmsKeyId = lens _vKmsKeyId (\s a -> s { _vKmsKeyId = a }) -- | The size of the volume, in GiBs. vSize :: Lens' Volume Int vSize = lens _vSize (\s a -> s { _vSize = a }) -- | The snapshot from which the volume was created, if applicable. vSnapshotId :: Lens' Volume Text vSnapshotId = lens _vSnapshotId (\s a -> s { _vSnapshotId = a }) -- | The volume state. vState :: Lens' Volume VolumeState vState = lens _vState (\s a -> s { _vState = a }) -- | Any tags assigned to the volume. vTags :: Lens' Volume [Tag] vTags = lens _vTags (\s a -> s { _vTags = a }) . _List -- | The ID of the volume. vVolumeId :: Lens' Volume Text vVolumeId = lens _vVolumeId (\s a -> s { _vVolumeId = a }) -- | The volume type. This can be 'gp2' for General Purpose (SSD) volumes, 'io1' for -- Provisioned IOPS (SSD) volumes, or 'standard' for Magnetic volumes. vVolumeType :: Lens' Volume VolumeType vVolumeType = lens _vVolumeType (\s a -> s { _vVolumeType = a }) instance FromXML Volume where parseXML x = Volume <$> x .@? "attachmentSet" .!@ mempty <*> x .@ "availabilityZone" <*> x .@ "createTime" <*> x .@ "encrypted" <*> x .@? "iops" <*> x .@? "kmsKeyId" <*> x .@ "size" <*> x .@ "snapshotId" <*> x .@ "status" <*> x .@? "tagSet" .!@ mempty <*> x .@ "volumeId" <*> x .@ "volumeType" instance ToQuery Volume where toQuery Volume{..} = mconcat [ "AttachmentSet" `toQueryList` _vAttachments , "AvailabilityZone" =? _vAvailabilityZone , "CreateTime" =? _vCreateTime , "Encrypted" =? _vEncrypted , "Iops" =? _vIops , "KmsKeyId" =? _vKmsKeyId , "Size" =? _vSize , "SnapshotId" =? _vSnapshotId , "Status" =? _vState , "TagSet" `toQueryList` _vTags , "VolumeId" =? _vVolumeId , "VolumeType" =? _vVolumeType ] data Reservation = Reservation { _rGroups :: List "item" GroupIdentifier , _rInstances :: List "item" Instance , _rOwnerId :: Text , _rRequesterId :: Maybe Text , _rReservationId :: Text } deriving (Eq, Read, Show) -- | 'Reservation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rGroups' @::@ ['GroupIdentifier'] -- -- * 'rInstances' @::@ ['Instance'] -- -- * 'rOwnerId' @::@ 'Text' -- -- * 'rRequesterId' @::@ 'Maybe' 'Text' -- -- * 'rReservationId' @::@ 'Text' -- reservation :: Text -- ^ 'rReservationId' -> Text -- ^ 'rOwnerId' -> Reservation reservation p1 p2 = Reservation { _rReservationId = p1 , _rOwnerId = p2 , _rRequesterId = Nothing , _rGroups = mempty , _rInstances = mempty } -- | One or more security groups. rGroups :: Lens' Reservation [GroupIdentifier] rGroups = lens _rGroups (\s a -> s { _rGroups = a }) . _List -- | One or more instances. rInstances :: Lens' Reservation [Instance] rInstances = lens _rInstances (\s a -> s { _rInstances = a }) . _List -- | The ID of the AWS account that owns the reservation. rOwnerId :: Lens' Reservation Text rOwnerId = lens _rOwnerId (\s a -> s { _rOwnerId = a }) -- | The ID of the requester that launched the instances on your behalf (for -- example, AWS Management Console or Auto Scaling). rRequesterId :: Lens' Reservation (Maybe Text) rRequesterId = lens _rRequesterId (\s a -> s { _rRequesterId = a }) -- | The ID of the reservation. rReservationId :: Lens' Reservation Text rReservationId = lens _rReservationId (\s a -> s { _rReservationId = a }) instance FromXML Reservation where parseXML x = Reservation <$> x .@? "groupSet" .!@ mempty <*> x .@? "instancesSet" .!@ mempty <*> x .@ "ownerId" <*> x .@? "requesterId" <*> x .@ "reservationId" instance ToQuery Reservation where toQuery Reservation{..} = mconcat [ "GroupSet" `toQueryList` _rGroups , "InstancesSet" `toQueryList` _rInstances , "OwnerId" =? _rOwnerId , "RequesterId" =? _rRequesterId , "ReservationId" =? _rReservationId ] data ImportInstanceVolumeDetailItem = ImportInstanceVolumeDetailItem { _iivdiAvailabilityZone :: Text , _iivdiBytesConverted :: Integer , _iivdiDescription :: Maybe Text , _iivdiImage :: DiskImageDescription , _iivdiStatus :: Text , _iivdiStatusMessage :: Maybe Text , _iivdiVolume :: DiskImageVolumeDescription } deriving (Eq, Read, Show) -- | 'ImportInstanceVolumeDetailItem' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iivdiAvailabilityZone' @::@ 'Text' -- -- * 'iivdiBytesConverted' @::@ 'Integer' -- -- * 'iivdiDescription' @::@ 'Maybe' 'Text' -- -- * 'iivdiImage' @::@ 'DiskImageDescription' -- -- * 'iivdiStatus' @::@ 'Text' -- -- * 'iivdiStatusMessage' @::@ 'Maybe' 'Text' -- -- * 'iivdiVolume' @::@ 'DiskImageVolumeDescription' -- importInstanceVolumeDetailItem :: Integer -- ^ 'iivdiBytesConverted' -> Text -- ^ 'iivdiAvailabilityZone' -> DiskImageDescription -- ^ 'iivdiImage' -> DiskImageVolumeDescription -- ^ 'iivdiVolume' -> Text -- ^ 'iivdiStatus' -> ImportInstanceVolumeDetailItem importInstanceVolumeDetailItem p1 p2 p3 p4 p5 = ImportInstanceVolumeDetailItem { _iivdiBytesConverted = p1 , _iivdiAvailabilityZone = p2 , _iivdiImage = p3 , _iivdiVolume = p4 , _iivdiStatus = p5 , _iivdiStatusMessage = Nothing , _iivdiDescription = Nothing } -- | The Availability Zone where the resulting instance will reside. iivdiAvailabilityZone :: Lens' ImportInstanceVolumeDetailItem Text iivdiAvailabilityZone = lens _iivdiAvailabilityZone (\s a -> s { _iivdiAvailabilityZone = a }) -- | The number of bytes converted so far. iivdiBytesConverted :: Lens' ImportInstanceVolumeDetailItem Integer iivdiBytesConverted = lens _iivdiBytesConverted (\s a -> s { _iivdiBytesConverted = a }) iivdiDescription :: Lens' ImportInstanceVolumeDetailItem (Maybe Text) iivdiDescription = lens _iivdiDescription (\s a -> s { _iivdiDescription = a }) -- | The image. iivdiImage :: Lens' ImportInstanceVolumeDetailItem DiskImageDescription iivdiImage = lens _iivdiImage (\s a -> s { _iivdiImage = a }) -- | The status of the import of this particular disk image. iivdiStatus :: Lens' ImportInstanceVolumeDetailItem Text iivdiStatus = lens _iivdiStatus (\s a -> s { _iivdiStatus = a }) -- | The status information or errors related to the disk image. iivdiStatusMessage :: Lens' ImportInstanceVolumeDetailItem (Maybe Text) iivdiStatusMessage = lens _iivdiStatusMessage (\s a -> s { _iivdiStatusMessage = a }) -- | The volume. iivdiVolume :: Lens' ImportInstanceVolumeDetailItem DiskImageVolumeDescription iivdiVolume = lens _iivdiVolume (\s a -> s { _iivdiVolume = a }) instance FromXML ImportInstanceVolumeDetailItem where parseXML x = ImportInstanceVolumeDetailItem <$> x .@ "availabilityZone" <*> x .@ "bytesConverted" <*> x .@? "description" <*> x .@ "image" <*> x .@ "status" <*> x .@? "statusMessage" <*> x .@ "volume" instance ToQuery ImportInstanceVolumeDetailItem where toQuery ImportInstanceVolumeDetailItem{..} = mconcat [ "AvailabilityZone" =? _iivdiAvailabilityZone , "BytesConverted" =? _iivdiBytesConverted , "Description" =? _iivdiDescription , "Image" =? _iivdiImage , "Status" =? _iivdiStatus , "StatusMessage" =? _iivdiStatusMessage , "Volume" =? _iivdiVolume ] data SummaryStatus = SSImpaired -- ^ impaired | SSInsufficientData -- ^ insufficient-data | SSNotApplicable -- ^ not-applicable | SSOk -- ^ ok deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SummaryStatus instance FromText SummaryStatus where parser = takeLowerText >>= \case "impaired" -> pure SSImpaired "insufficient-data" -> pure SSInsufficientData "not-applicable" -> pure SSNotApplicable "ok" -> pure SSOk e -> fail $ "Failure parsing SummaryStatus from " ++ show e instance ToText SummaryStatus where toText = \case SSImpaired -> "impaired" SSInsufficientData -> "insufficient-data" SSNotApplicable -> "not-applicable" SSOk -> "ok" instance ToByteString SummaryStatus instance ToHeader SummaryStatus instance ToQuery SummaryStatus instance FromXML SummaryStatus where parseXML = parseXMLText "SummaryStatus" data ReservedInstancesModification = ReservedInstancesModification { _rimClientToken :: Maybe Text , _rimCreateDate :: Maybe ISO8601 , _rimEffectiveDate :: Maybe ISO8601 , _rimModificationResults :: List "item" ReservedInstancesModificationResult , _rimReservedInstancesIds :: List "item" ReservedInstancesId , _rimReservedInstancesModificationId :: Maybe Text , _rimStatus :: Maybe Text , _rimStatusMessage :: Maybe Text , _rimUpdateDate :: Maybe ISO8601 } deriving (Eq, Read, Show) -- | 'ReservedInstancesModification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rimClientToken' @::@ 'Maybe' 'Text' -- -- * 'rimCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'rimEffectiveDate' @::@ 'Maybe' 'UTCTime' -- -- * 'rimModificationResults' @::@ ['ReservedInstancesModificationResult'] -- -- * 'rimReservedInstancesIds' @::@ ['ReservedInstancesId'] -- -- * 'rimReservedInstancesModificationId' @::@ 'Maybe' 'Text' -- -- * 'rimStatus' @::@ 'Maybe' 'Text' -- -- * 'rimStatusMessage' @::@ 'Maybe' 'Text' -- -- * 'rimUpdateDate' @::@ 'Maybe' 'UTCTime' -- reservedInstancesModification :: ReservedInstancesModification reservedInstancesModification = ReservedInstancesModification { _rimReservedInstancesModificationId = Nothing , _rimReservedInstancesIds = mempty , _rimModificationResults = mempty , _rimCreateDate = Nothing , _rimUpdateDate = Nothing , _rimEffectiveDate = Nothing , _rimStatus = Nothing , _rimStatusMessage = Nothing , _rimClientToken = Nothing } -- | A unique, case-sensitive key supplied by the client to ensure that the -- request is idempotent. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html Ensuring Idempotency>. rimClientToken :: Lens' ReservedInstancesModification (Maybe Text) rimClientToken = lens _rimClientToken (\s a -> s { _rimClientToken = a }) -- | The time when the modification request was created. rimCreateDate :: Lens' ReservedInstancesModification (Maybe UTCTime) rimCreateDate = lens _rimCreateDate (\s a -> s { _rimCreateDate = a }) . mapping _Time -- | The time for the modification to become effective. rimEffectiveDate :: Lens' ReservedInstancesModification (Maybe UTCTime) rimEffectiveDate = lens _rimEffectiveDate (\s a -> s { _rimEffectiveDate = a }) . mapping _Time -- | Contains target configurations along with their corresponding new Reserved -- Instance IDs. rimModificationResults :: Lens' ReservedInstancesModification [ReservedInstancesModificationResult] rimModificationResults = lens _rimModificationResults (\s a -> s { _rimModificationResults = a }) . _List -- | The IDs of one or more Reserved Instances. rimReservedInstancesIds :: Lens' ReservedInstancesModification [ReservedInstancesId] rimReservedInstancesIds = lens _rimReservedInstancesIds (\s a -> s { _rimReservedInstancesIds = a }) . _List -- | A unique ID for the Reserved Instance modification. rimReservedInstancesModificationId :: Lens' ReservedInstancesModification (Maybe Text) rimReservedInstancesModificationId = lens _rimReservedInstancesModificationId (\s a -> s { _rimReservedInstancesModificationId = a }) -- | The status of the Reserved Instances modification request. rimStatus :: Lens' ReservedInstancesModification (Maybe Text) rimStatus = lens _rimStatus (\s a -> s { _rimStatus = a }) -- | The reason for the status. rimStatusMessage :: Lens' ReservedInstancesModification (Maybe Text) rimStatusMessage = lens _rimStatusMessage (\s a -> s { _rimStatusMessage = a }) -- | The time when the modification request was last updated. rimUpdateDate :: Lens' ReservedInstancesModification (Maybe UTCTime) rimUpdateDate = lens _rimUpdateDate (\s a -> s { _rimUpdateDate = a }) . mapping _Time instance FromXML ReservedInstancesModification where parseXML x = ReservedInstancesModification <$> x .@? "clientToken" <*> x .@? "createDate" <*> x .@? "effectiveDate" <*> x .@? "modificationResultSet" .!@ mempty <*> x .@? "reservedInstancesSet" .!@ mempty <*> x .@? "reservedInstancesModificationId" <*> x .@? "status" <*> x .@? "statusMessage" <*> x .@? "updateDate" instance ToQuery ReservedInstancesModification where toQuery ReservedInstancesModification{..} = mconcat [ "ClientToken" =? _rimClientToken , "CreateDate" =? _rimCreateDate , "EffectiveDate" =? _rimEffectiveDate , "ModificationResultSet" `toQueryList` _rimModificationResults , "ReservedInstancesSet" `toQueryList` _rimReservedInstancesIds , "ReservedInstancesModificationId" =? _rimReservedInstancesModificationId , "Status" =? _rimStatus , "StatusMessage" =? _rimStatusMessage , "UpdateDate" =? _rimUpdateDate ] data RuleAction = Allow -- ^ allow | Deny -- ^ deny deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable RuleAction instance FromText RuleAction where parser = takeLowerText >>= \case "allow" -> pure Allow "deny" -> pure Deny e -> fail $ "Failure parsing RuleAction from " ++ show e instance ToText RuleAction where toText = \case Allow -> "allow" Deny -> "deny" instance ToByteString RuleAction instance ToHeader RuleAction instance ToQuery RuleAction instance FromXML RuleAction where parseXML = parseXMLText "RuleAction" data NetworkInterface = NetworkInterface { _niAssociation :: Maybe NetworkInterfaceAssociation , _niAttachment :: Maybe NetworkInterfaceAttachment , _niAvailabilityZone :: Maybe Text , _niDescription :: Maybe Text , _niGroups :: List "item" GroupIdentifier , _niMacAddress :: Maybe Text , _niNetworkInterfaceId :: Maybe Text , _niOwnerId :: Maybe Text , _niPrivateDnsName :: Maybe Text , _niPrivateIpAddress :: Maybe Text , _niPrivateIpAddresses :: List "item" NetworkInterfacePrivateIpAddress , _niRequesterId :: Maybe Text , _niRequesterManaged :: Maybe Bool , _niSourceDestCheck :: Maybe Bool , _niStatus :: Maybe NetworkInterfaceStatus , _niSubnetId :: Maybe Text , _niTagSet :: List "item" Tag , _niVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'NetworkInterface' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'niAssociation' @::@ 'Maybe' 'NetworkInterfaceAssociation' -- -- * 'niAttachment' @::@ 'Maybe' 'NetworkInterfaceAttachment' -- -- * 'niAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'niDescription' @::@ 'Maybe' 'Text' -- -- * 'niGroups' @::@ ['GroupIdentifier'] -- -- * 'niMacAddress' @::@ 'Maybe' 'Text' -- -- * 'niNetworkInterfaceId' @::@ 'Maybe' 'Text' -- -- * 'niOwnerId' @::@ 'Maybe' 'Text' -- -- * 'niPrivateDnsName' @::@ 'Maybe' 'Text' -- -- * 'niPrivateIpAddress' @::@ 'Maybe' 'Text' -- -- * 'niPrivateIpAddresses' @::@ ['NetworkInterfacePrivateIpAddress'] -- -- * 'niRequesterId' @::@ 'Maybe' 'Text' -- -- * 'niRequesterManaged' @::@ 'Maybe' 'Bool' -- -- * 'niSourceDestCheck' @::@ 'Maybe' 'Bool' -- -- * 'niStatus' @::@ 'Maybe' 'NetworkInterfaceStatus' -- -- * 'niSubnetId' @::@ 'Maybe' 'Text' -- -- * 'niTagSet' @::@ ['Tag'] -- -- * 'niVpcId' @::@ 'Maybe' 'Text' -- networkInterface :: NetworkInterface networkInterface = NetworkInterface { _niNetworkInterfaceId = Nothing , _niSubnetId = Nothing , _niVpcId = Nothing , _niAvailabilityZone = Nothing , _niDescription = Nothing , _niOwnerId = Nothing , _niRequesterId = Nothing , _niRequesterManaged = Nothing , _niStatus = Nothing , _niMacAddress = Nothing , _niPrivateIpAddress = Nothing , _niPrivateDnsName = Nothing , _niSourceDestCheck = Nothing , _niGroups = mempty , _niAttachment = Nothing , _niAssociation = Nothing , _niTagSet = mempty , _niPrivateIpAddresses = mempty } -- | The association information for an Elastic IP associated with the network -- interface. niAssociation :: Lens' NetworkInterface (Maybe NetworkInterfaceAssociation) niAssociation = lens _niAssociation (\s a -> s { _niAssociation = a }) -- | The network interface attachment. niAttachment :: Lens' NetworkInterface (Maybe NetworkInterfaceAttachment) niAttachment = lens _niAttachment (\s a -> s { _niAttachment = a }) -- | The Availability Zone. niAvailabilityZone :: Lens' NetworkInterface (Maybe Text) niAvailabilityZone = lens _niAvailabilityZone (\s a -> s { _niAvailabilityZone = a }) -- | A description. niDescription :: Lens' NetworkInterface (Maybe Text) niDescription = lens _niDescription (\s a -> s { _niDescription = a }) -- | Any security groups for the network interface. niGroups :: Lens' NetworkInterface [GroupIdentifier] niGroups = lens _niGroups (\s a -> s { _niGroups = a }) . _List -- | The MAC address. niMacAddress :: Lens' NetworkInterface (Maybe Text) niMacAddress = lens _niMacAddress (\s a -> s { _niMacAddress = a }) -- | The ID of the network interface. niNetworkInterfaceId :: Lens' NetworkInterface (Maybe Text) niNetworkInterfaceId = lens _niNetworkInterfaceId (\s a -> s { _niNetworkInterfaceId = a }) -- | The AWS account ID of the owner of the network interface. niOwnerId :: Lens' NetworkInterface (Maybe Text) niOwnerId = lens _niOwnerId (\s a -> s { _niOwnerId = a }) -- | The private DNS name. niPrivateDnsName :: Lens' NetworkInterface (Maybe Text) niPrivateDnsName = lens _niPrivateDnsName (\s a -> s { _niPrivateDnsName = a }) -- | The IP address of the network interface within the subnet. niPrivateIpAddress :: Lens' NetworkInterface (Maybe Text) niPrivateIpAddress = lens _niPrivateIpAddress (\s a -> s { _niPrivateIpAddress = a }) -- | The private IP addresses associated with the network interface. niPrivateIpAddresses :: Lens' NetworkInterface [NetworkInterfacePrivateIpAddress] niPrivateIpAddresses = lens _niPrivateIpAddresses (\s a -> s { _niPrivateIpAddresses = a }) . _List -- | The ID of the entity that launched the instance on your behalf (for example, -- AWS Management Console or Auto Scaling). niRequesterId :: Lens' NetworkInterface (Maybe Text) niRequesterId = lens _niRequesterId (\s a -> s { _niRequesterId = a }) -- | Indicates whether the network interface is being managed by AWS. niRequesterManaged :: Lens' NetworkInterface (Maybe Bool) niRequesterManaged = lens _niRequesterManaged (\s a -> s { _niRequesterManaged = a }) -- | Indicates whether traffic to or from the instance is validated. niSourceDestCheck :: Lens' NetworkInterface (Maybe Bool) niSourceDestCheck = lens _niSourceDestCheck (\s a -> s { _niSourceDestCheck = a }) -- | The status of the network interface. niStatus :: Lens' NetworkInterface (Maybe NetworkInterfaceStatus) niStatus = lens _niStatus (\s a -> s { _niStatus = a }) -- | The ID of the subnet. niSubnetId :: Lens' NetworkInterface (Maybe Text) niSubnetId = lens _niSubnetId (\s a -> s { _niSubnetId = a }) -- | Any tags assigned to the network interface. niTagSet :: Lens' NetworkInterface [Tag] niTagSet = lens _niTagSet (\s a -> s { _niTagSet = a }) . _List -- | The ID of the VPC. niVpcId :: Lens' NetworkInterface (Maybe Text) niVpcId = lens _niVpcId (\s a -> s { _niVpcId = a }) instance FromXML NetworkInterface where parseXML x = NetworkInterface <$> x .@? "association" <*> x .@? "attachment" <*> x .@? "availabilityZone" <*> x .@? "description" <*> x .@? "groupSet" .!@ mempty <*> x .@? "macAddress" <*> x .@? "networkInterfaceId" <*> x .@? "ownerId" <*> x .@? "privateDnsName" <*> x .@? "privateIpAddress" <*> x .@? "privateIpAddressesSet" .!@ mempty <*> x .@? "requesterId" <*> x .@? "requesterManaged" <*> x .@? "sourceDestCheck" <*> x .@? "status" <*> x .@? "subnetId" <*> x .@? "tagSet" .!@ mempty <*> x .@? "vpcId" instance ToQuery NetworkInterface where toQuery NetworkInterface{..} = mconcat [ "Association" =? _niAssociation , "Attachment" =? _niAttachment , "AvailabilityZone" =? _niAvailabilityZone , "Description" =? _niDescription , "GroupSet" `toQueryList` _niGroups , "MacAddress" =? _niMacAddress , "NetworkInterfaceId" =? _niNetworkInterfaceId , "OwnerId" =? _niOwnerId , "PrivateDnsName" =? _niPrivateDnsName , "PrivateIpAddress" =? _niPrivateIpAddress , "PrivateIpAddressesSet" `toQueryList` _niPrivateIpAddresses , "RequesterId" =? _niRequesterId , "RequesterManaged" =? _niRequesterManaged , "SourceDestCheck" =? _niSourceDestCheck , "Status" =? _niStatus , "SubnetId" =? _niSubnetId , "TagSet" `toQueryList` _niTagSet , "VpcId" =? _niVpcId ] data TelemetryStatus = Down -- ^ DOWN | Up -- ^ UP deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable TelemetryStatus instance FromText TelemetryStatus where parser = takeLowerText >>= \case "down" -> pure Down "up" -> pure Up e -> fail $ "Failure parsing TelemetryStatus from " ++ show e instance ToText TelemetryStatus where toText = \case Down -> "DOWN" Up -> "UP" instance ToByteString TelemetryStatus instance ToHeader TelemetryStatus instance ToQuery TelemetryStatus instance FromXML TelemetryStatus where parseXML = parseXMLText "TelemetryStatus" data Subnet = Subnet { _s1AvailabilityZone :: Text , _s1AvailableIpAddressCount :: Int , _s1CidrBlock :: Text , _s1DefaultForAz :: Bool , _s1MapPublicIpOnLaunch :: Bool , _s1State :: SubnetState , _s1SubnetId :: Text , _s1Tags :: List "item" Tag , _s1VpcId :: Text } deriving (Eq, Read, Show) -- | 'Subnet' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 's1AvailabilityZone' @::@ 'Text' -- -- * 's1AvailableIpAddressCount' @::@ 'Int' -- -- * 's1CidrBlock' @::@ 'Text' -- -- * 's1DefaultForAz' @::@ 'Bool' -- -- * 's1MapPublicIpOnLaunch' @::@ 'Bool' -- -- * 's1State' @::@ 'SubnetState' -- -- * 's1SubnetId' @::@ 'Text' -- -- * 's1Tags' @::@ ['Tag'] -- -- * 's1VpcId' @::@ 'Text' -- subnet :: Text -- ^ 's1SubnetId' -> SubnetState -- ^ 's1State' -> Text -- ^ 's1VpcId' -> Text -- ^ 's1CidrBlock' -> Int -- ^ 's1AvailableIpAddressCount' -> Text -- ^ 's1AvailabilityZone' -> Bool -- ^ 's1DefaultForAz' -> Bool -- ^ 's1MapPublicIpOnLaunch' -> Subnet subnet p1 p2 p3 p4 p5 p6 p7 p8 = Subnet { _s1SubnetId = p1 , _s1State = p2 , _s1VpcId = p3 , _s1CidrBlock = p4 , _s1AvailableIpAddressCount = p5 , _s1AvailabilityZone = p6 , _s1DefaultForAz = p7 , _s1MapPublicIpOnLaunch = p8 , _s1Tags = mempty } -- | The Availability Zone of the subnet. s1AvailabilityZone :: Lens' Subnet Text s1AvailabilityZone = lens _s1AvailabilityZone (\s a -> s { _s1AvailabilityZone = a }) -- | The number of unused IP addresses in the subnet. Note that the IP addresses -- for any stopped instances are considered unavailable. s1AvailableIpAddressCount :: Lens' Subnet Int s1AvailableIpAddressCount = lens _s1AvailableIpAddressCount (\s a -> s { _s1AvailableIpAddressCount = a }) -- | The CIDR block assigned to the subnet. s1CidrBlock :: Lens' Subnet Text s1CidrBlock = lens _s1CidrBlock (\s a -> s { _s1CidrBlock = a }) -- | Indicates whether this is the default subnet for the Availability Zone. s1DefaultForAz :: Lens' Subnet Bool s1DefaultForAz = lens _s1DefaultForAz (\s a -> s { _s1DefaultForAz = a }) -- | Indicates whether instances launched in this subnet receive a public IP -- address. s1MapPublicIpOnLaunch :: Lens' Subnet Bool s1MapPublicIpOnLaunch = lens _s1MapPublicIpOnLaunch (\s a -> s { _s1MapPublicIpOnLaunch = a }) -- | The current state of the subnet. s1State :: Lens' Subnet SubnetState s1State = lens _s1State (\s a -> s { _s1State = a }) -- | The ID of the subnet. s1SubnetId :: Lens' Subnet Text s1SubnetId = lens _s1SubnetId (\s a -> s { _s1SubnetId = a }) -- | Any tags assigned to the subnet. s1Tags :: Lens' Subnet [Tag] s1Tags = lens _s1Tags (\s a -> s { _s1Tags = a }) . _List -- | The ID of the VPC the subnet is in. s1VpcId :: Lens' Subnet Text s1VpcId = lens _s1VpcId (\s a -> s { _s1VpcId = a }) instance FromXML Subnet where parseXML x = Subnet <$> x .@ "availabilityZone" <*> x .@ "availableIpAddressCount" <*> x .@ "cidrBlock" <*> x .@ "defaultForAz" <*> x .@ "mapPublicIpOnLaunch" <*> x .@ "state" <*> x .@ "subnetId" <*> x .@? "tagSet" .!@ mempty <*> x .@ "vpcId" instance ToQuery Subnet where toQuery Subnet{..} = mconcat [ "AvailabilityZone" =? _s1AvailabilityZone , "AvailableIpAddressCount" =? _s1AvailableIpAddressCount , "CidrBlock" =? _s1CidrBlock , "DefaultForAz" =? _s1DefaultForAz , "MapPublicIpOnLaunch" =? _s1MapPublicIpOnLaunch , "State" =? _s1State , "SubnetId" =? _s1SubnetId , "TagSet" `toQueryList` _s1Tags , "VpcId" =? _s1VpcId ] data KeyPairInfo = KeyPairInfo { _kpiKeyFingerprint :: Maybe Text , _kpiKeyName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'KeyPairInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'kpiKeyFingerprint' @::@ 'Maybe' 'Text' -- -- * 'kpiKeyName' @::@ 'Maybe' 'Text' -- keyPairInfo :: KeyPairInfo keyPairInfo = KeyPairInfo { _kpiKeyName = Nothing , _kpiKeyFingerprint = Nothing } -- | If you used 'CreateKeyPair' to create the key pair, this is the SHA-1 digest of -- the DER encoded private key. If you used 'ImportKeyPair' to provide AWS the -- public key, this is the MD5 public key fingerprint as specified in section 4 -- of RFC4716. kpiKeyFingerprint :: Lens' KeyPairInfo (Maybe Text) kpiKeyFingerprint = lens _kpiKeyFingerprint (\s a -> s { _kpiKeyFingerprint = a }) -- | The name of the key pair. kpiKeyName :: Lens' KeyPairInfo (Maybe Text) kpiKeyName = lens _kpiKeyName (\s a -> s { _kpiKeyName = a }) instance FromXML KeyPairInfo where parseXML x = KeyPairInfo <$> x .@? "keyFingerprint" <*> x .@? "keyName" instance ToQuery KeyPairInfo where toQuery KeyPairInfo{..} = mconcat [ "KeyFingerprint" =? _kpiKeyFingerprint , "KeyName" =? _kpiKeyName ] data LaunchPermissionModifications = LaunchPermissionModifications { _lpmAdd :: List "item" LaunchPermission , _lpmRemove :: List "item" LaunchPermission } deriving (Eq, Read, Show) -- | 'LaunchPermissionModifications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lpmAdd' @::@ ['LaunchPermission'] -- -- * 'lpmRemove' @::@ ['LaunchPermission'] -- launchPermissionModifications :: LaunchPermissionModifications launchPermissionModifications = LaunchPermissionModifications { _lpmAdd = mempty , _lpmRemove = mempty } -- | The AWS account ID to add to the list of launch permissions for the AMI. lpmAdd :: Lens' LaunchPermissionModifications [LaunchPermission] lpmAdd = lens _lpmAdd (\s a -> s { _lpmAdd = a }) . _List -- | The AWS account ID to remove from the list of launch permissions for the AMI. lpmRemove :: Lens' LaunchPermissionModifications [LaunchPermission] lpmRemove = lens _lpmRemove (\s a -> s { _lpmRemove = a }) . _List instance FromXML LaunchPermissionModifications where parseXML x = LaunchPermissionModifications <$> x .@? "Add" .!@ mempty <*> x .@? "Remove" .!@ mempty instance ToQuery LaunchPermissionModifications where toQuery LaunchPermissionModifications{..} = mconcat [ "Add" `toQueryList` _lpmAdd , "Remove" `toQueryList` _lpmRemove ] data SnapshotState = Completed -- ^ completed | Error -- ^ error | Pending -- ^ pending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SnapshotState instance FromText SnapshotState where parser = takeLowerText >>= \case "completed" -> pure Completed "error" -> pure Error "pending" -> pure Pending e -> fail $ "Failure parsing SnapshotState from " ++ show e instance ToText SnapshotState where toText = \case Completed -> "completed" Error -> "error" Pending -> "pending" instance ToByteString SnapshotState instance ToHeader SnapshotState instance ToQuery SnapshotState instance FromXML SnapshotState where parseXML = parseXMLText "SnapshotState" data InstanceNetworkInterfaceAssociation = InstanceNetworkInterfaceAssociation { _iniaIpOwnerId :: Maybe Text , _iniaPublicDnsName :: Maybe Text , _iniaPublicIp :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'InstanceNetworkInterfaceAssociation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iniaIpOwnerId' @::@ 'Maybe' 'Text' -- -- * 'iniaPublicDnsName' @::@ 'Maybe' 'Text' -- -- * 'iniaPublicIp' @::@ 'Maybe' 'Text' -- instanceNetworkInterfaceAssociation :: InstanceNetworkInterfaceAssociation instanceNetworkInterfaceAssociation = InstanceNetworkInterfaceAssociation { _iniaPublicIp = Nothing , _iniaPublicDnsName = Nothing , _iniaIpOwnerId = Nothing } -- | The ID of the owner of the Elastic IP address. iniaIpOwnerId :: Lens' InstanceNetworkInterfaceAssociation (Maybe Text) iniaIpOwnerId = lens _iniaIpOwnerId (\s a -> s { _iniaIpOwnerId = a }) -- | The public DNS name. iniaPublicDnsName :: Lens' InstanceNetworkInterfaceAssociation (Maybe Text) iniaPublicDnsName = lens _iniaPublicDnsName (\s a -> s { _iniaPublicDnsName = a }) -- | The public IP address or Elastic IP address bound to the network interface. iniaPublicIp :: Lens' InstanceNetworkInterfaceAssociation (Maybe Text) iniaPublicIp = lens _iniaPublicIp (\s a -> s { _iniaPublicIp = a }) instance FromXML InstanceNetworkInterfaceAssociation where parseXML x = InstanceNetworkInterfaceAssociation <$> x .@? "ipOwnerId" <*> x .@? "publicDnsName" <*> x .@? "publicIp" instance ToQuery InstanceNetworkInterfaceAssociation where toQuery InstanceNetworkInterfaceAssociation{..} = mconcat [ "IpOwnerId" =? _iniaIpOwnerId , "PublicDnsName" =? _iniaPublicDnsName , "PublicIp" =? _iniaPublicIp ] data DiskImageDetail = DiskImageDetail { _didBytes :: Integer , _didFormat :: DiskImageFormat , _didImportManifestUrl :: Text } deriving (Eq, Read, Show) -- | 'DiskImageDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'didBytes' @::@ 'Integer' -- -- * 'didFormat' @::@ 'DiskImageFormat' -- -- * 'didImportManifestUrl' @::@ 'Text' -- diskImageDetail :: DiskImageFormat -- ^ 'didFormat' -> Integer -- ^ 'didBytes' -> Text -- ^ 'didImportManifestUrl' -> DiskImageDetail diskImageDetail p1 p2 p3 = DiskImageDetail { _didFormat = p1 , _didBytes = p2 , _didImportManifestUrl = p3 } didBytes :: Lens' DiskImageDetail Integer didBytes = lens _didBytes (\s a -> s { _didBytes = a }) -- | The disk image format. didFormat :: Lens' DiskImageDetail DiskImageFormat didFormat = lens _didFormat (\s a -> s { _didFormat = a }) -- | A presigned URL for the import manifest stored in Amazon S3 and presented -- here as an Amazon S3 presigned URL. For information about creating a -- presigned URL for an Amazon S3 object, read the "Query String Request -- Authentication Alternative" section of the <http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html Authenticating REST Requests> topic -- in the /Amazon Simple Storage Service Developer Guide/. didImportManifestUrl :: Lens' DiskImageDetail Text didImportManifestUrl = lens _didImportManifestUrl (\s a -> s { _didImportManifestUrl = a }) instance FromXML DiskImageDetail where parseXML x = DiskImageDetail <$> x .@ "bytes" <*> x .@ "format" <*> x .@ "importManifestUrl" instance ToQuery DiskImageDetail where toQuery DiskImageDetail{..} = mconcat [ "Bytes" =? _didBytes , "Format" =? _didFormat , "ImportManifestUrl" =? _didImportManifestUrl ] data InstancePrivateIpAddress = InstancePrivateIpAddress { _ipiaAssociation :: Maybe InstanceNetworkInterfaceAssociation , _ipiaPrimary :: Maybe Bool , _ipiaPrivateDnsName :: Maybe Text , _ipiaPrivateIpAddress :: Maybe Text } deriving (Eq, Read, Show) -- | 'InstancePrivateIpAddress' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ipiaAssociation' @::@ 'Maybe' 'InstanceNetworkInterfaceAssociation' -- -- * 'ipiaPrimary' @::@ 'Maybe' 'Bool' -- -- * 'ipiaPrivateDnsName' @::@ 'Maybe' 'Text' -- -- * 'ipiaPrivateIpAddress' @::@ 'Maybe' 'Text' -- instancePrivateIpAddress :: InstancePrivateIpAddress instancePrivateIpAddress = InstancePrivateIpAddress { _ipiaPrivateIpAddress = Nothing , _ipiaPrivateDnsName = Nothing , _ipiaPrimary = Nothing , _ipiaAssociation = Nothing } -- | The association information for an Elastic IP address for the network -- interface. ipiaAssociation :: Lens' InstancePrivateIpAddress (Maybe InstanceNetworkInterfaceAssociation) ipiaAssociation = lens _ipiaAssociation (\s a -> s { _ipiaAssociation = a }) -- | Indicates whether this IP address is the primary private IP address of the -- network interface. ipiaPrimary :: Lens' InstancePrivateIpAddress (Maybe Bool) ipiaPrimary = lens _ipiaPrimary (\s a -> s { _ipiaPrimary = a }) -- | The private DNS name. ipiaPrivateDnsName :: Lens' InstancePrivateIpAddress (Maybe Text) ipiaPrivateDnsName = lens _ipiaPrivateDnsName (\s a -> s { _ipiaPrivateDnsName = a }) -- | The private IP address of the network interface. ipiaPrivateIpAddress :: Lens' InstancePrivateIpAddress (Maybe Text) ipiaPrivateIpAddress = lens _ipiaPrivateIpAddress (\s a -> s { _ipiaPrivateIpAddress = a }) instance FromXML InstancePrivateIpAddress where parseXML x = InstancePrivateIpAddress <$> x .@? "association" <*> x .@? "primary" <*> x .@? "privateDnsName" <*> x .@? "privateIpAddress" instance ToQuery InstancePrivateIpAddress where toQuery InstancePrivateIpAddress{..} = mconcat [ "Association" =? _ipiaAssociation , "Primary" =? _ipiaPrimary , "PrivateDnsName" =? _ipiaPrivateDnsName , "PrivateIpAddress" =? _ipiaPrivateIpAddress ] data CancelledSpotInstanceRequest = CancelledSpotInstanceRequest { _csiSpotInstanceRequestId :: Maybe Text , _csiState :: Maybe CancelSpotInstanceRequestState } deriving (Eq, Read, Show) -- | 'CancelledSpotInstanceRequest' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'csiSpotInstanceRequestId' @::@ 'Maybe' 'Text' -- -- * 'csiState' @::@ 'Maybe' 'CancelSpotInstanceRequestState' -- cancelledSpotInstanceRequest :: CancelledSpotInstanceRequest cancelledSpotInstanceRequest = CancelledSpotInstanceRequest { _csiSpotInstanceRequestId = Nothing , _csiState = Nothing } -- | The ID of the Spot Instance request. csiSpotInstanceRequestId :: Lens' CancelledSpotInstanceRequest (Maybe Text) csiSpotInstanceRequestId = lens _csiSpotInstanceRequestId (\s a -> s { _csiSpotInstanceRequestId = a }) -- | The state of the Spot Instance request. csiState :: Lens' CancelledSpotInstanceRequest (Maybe CancelSpotInstanceRequestState) csiState = lens _csiState (\s a -> s { _csiState = a }) instance FromXML CancelledSpotInstanceRequest where parseXML x = CancelledSpotInstanceRequest <$> x .@? "spotInstanceRequestId" <*> x .@? "state" instance ToQuery CancelledSpotInstanceRequest where toQuery CancelledSpotInstanceRequest{..} = mconcat [ "SpotInstanceRequestId" =? _csiSpotInstanceRequestId , "State" =? _csiState ] newtype VpnConnectionOptionsSpecification = VpnConnectionOptionsSpecification { _vcosStaticRoutesOnly :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'VpnConnectionOptionsSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vcosStaticRoutesOnly' @::@ 'Maybe' 'Bool' -- vpnConnectionOptionsSpecification :: VpnConnectionOptionsSpecification vpnConnectionOptionsSpecification = VpnConnectionOptionsSpecification { _vcosStaticRoutesOnly = Nothing } -- | Indicates whether the VPN connection uses static routes only. Static routes -- must be used for devices that don't support BGP. vcosStaticRoutesOnly :: Lens' VpnConnectionOptionsSpecification (Maybe Bool) vcosStaticRoutesOnly = lens _vcosStaticRoutesOnly (\s a -> s { _vcosStaticRoutesOnly = a }) instance FromXML VpnConnectionOptionsSpecification where parseXML x = VpnConnectionOptionsSpecification <$> x .@? "staticRoutesOnly" instance ToQuery VpnConnectionOptionsSpecification where toQuery VpnConnectionOptionsSpecification{..} = mconcat [ "StaticRoutesOnly" =? _vcosStaticRoutesOnly ] data Address = Address { _aAllocationId :: Maybe Text , _aAssociationId :: Maybe Text , _aDomain :: Maybe DomainType , _aInstanceId :: Maybe Text , _aNetworkInterfaceId :: Maybe Text , _aNetworkInterfaceOwnerId :: Maybe Text , _aPrivateIpAddress :: Maybe Text , _aPublicIp :: Maybe Text } deriving (Eq, Read, Show) -- | 'Address' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aAllocationId' @::@ 'Maybe' 'Text' -- -- * 'aAssociationId' @::@ 'Maybe' 'Text' -- -- * 'aDomain' @::@ 'Maybe' 'DomainType' -- -- * 'aInstanceId' @::@ 'Maybe' 'Text' -- -- * 'aNetworkInterfaceId' @::@ 'Maybe' 'Text' -- -- * 'aNetworkInterfaceOwnerId' @::@ 'Maybe' 'Text' -- -- * 'aPrivateIpAddress' @::@ 'Maybe' 'Text' -- -- * 'aPublicIp' @::@ 'Maybe' 'Text' -- address :: Address address = Address { _aInstanceId = Nothing , _aPublicIp = Nothing , _aAllocationId = Nothing , _aAssociationId = Nothing , _aDomain = Nothing , _aNetworkInterfaceId = Nothing , _aNetworkInterfaceOwnerId = Nothing , _aPrivateIpAddress = Nothing } -- | The ID representing the allocation of the address for use with EC2-VPC. aAllocationId :: Lens' Address (Maybe Text) aAllocationId = lens _aAllocationId (\s a -> s { _aAllocationId = a }) -- | The ID representing the association of the address with an instance in a VPC. aAssociationId :: Lens' Address (Maybe Text) aAssociationId = lens _aAssociationId (\s a -> s { _aAssociationId = a }) -- | Indicates whether this Elastic IP address is for use with instances in -- EC2-Classic ('standard') or instances in a VPC ('vpc'). aDomain :: Lens' Address (Maybe DomainType) aDomain = lens _aDomain (\s a -> s { _aDomain = a }) -- | The ID of the instance the address is associated with (if any). aInstanceId :: Lens' Address (Maybe Text) aInstanceId = lens _aInstanceId (\s a -> s { _aInstanceId = a }) -- | The ID of the network interface. aNetworkInterfaceId :: Lens' Address (Maybe Text) aNetworkInterfaceId = lens _aNetworkInterfaceId (\s a -> s { _aNetworkInterfaceId = a }) -- | The ID of the AWS account that owns the network interface. aNetworkInterfaceOwnerId :: Lens' Address (Maybe Text) aNetworkInterfaceOwnerId = lens _aNetworkInterfaceOwnerId (\s a -> s { _aNetworkInterfaceOwnerId = a }) -- | The private IP address associated with the Elastic IP address. aPrivateIpAddress :: Lens' Address (Maybe Text) aPrivateIpAddress = lens _aPrivateIpAddress (\s a -> s { _aPrivateIpAddress = a }) -- | The Elastic IP address. aPublicIp :: Lens' Address (Maybe Text) aPublicIp = lens _aPublicIp (\s a -> s { _aPublicIp = a }) instance FromXML Address where parseXML x = Address <$> x .@? "allocationId" <*> x .@? "associationId" <*> x .@? "domain" <*> x .@? "instanceId" <*> x .@? "networkInterfaceId" <*> x .@? "networkInterfaceOwnerId" <*> x .@? "privateIpAddress" <*> x .@? "publicIp" instance ToQuery Address where toQuery Address{..} = mconcat [ "AllocationId" =? _aAllocationId , "AssociationId" =? _aAssociationId , "Domain" =? _aDomain , "InstanceId" =? _aInstanceId , "NetworkInterfaceId" =? _aNetworkInterfaceId , "NetworkInterfaceOwnerId" =? _aNetworkInterfaceOwnerId , "PrivateIpAddress" =? _aPrivateIpAddress , "PublicIp" =? _aPublicIp ] data VolumeAttachmentState = VASAttached -- ^ attached | VASAttaching -- ^ attaching | VASDetached -- ^ detached | VASDetaching -- ^ detaching deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VolumeAttachmentState instance FromText VolumeAttachmentState where parser = takeLowerText >>= \case "attached" -> pure VASAttached "attaching" -> pure VASAttaching "detached" -> pure VASDetached "detaching" -> pure VASDetaching e -> fail $ "Failure parsing VolumeAttachmentState from " ++ show e instance ToText VolumeAttachmentState where toText = \case VASAttached -> "attached" VASAttaching -> "attaching" VASDetached -> "detached" VASDetaching -> "detaching" instance ToByteString VolumeAttachmentState instance ToHeader VolumeAttachmentState instance ToQuery VolumeAttachmentState instance FromXML VolumeAttachmentState where parseXML = parseXMLText "VolumeAttachmentState" data LaunchPermission = LaunchPermission { _lpGroup :: Maybe PermissionGroup , _lpUserId :: Maybe Text } deriving (Eq, Read, Show) -- | 'LaunchPermission' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lpGroup' @::@ 'Maybe' 'PermissionGroup' -- -- * 'lpUserId' @::@ 'Maybe' 'Text' -- launchPermission :: LaunchPermission launchPermission = LaunchPermission { _lpUserId = Nothing , _lpGroup = Nothing } -- | The name of the group. lpGroup :: Lens' LaunchPermission (Maybe PermissionGroup) lpGroup = lens _lpGroup (\s a -> s { _lpGroup = a }) -- | The AWS account ID. lpUserId :: Lens' LaunchPermission (Maybe Text) lpUserId = lens _lpUserId (\s a -> s { _lpUserId = a }) instance FromXML LaunchPermission where parseXML x = LaunchPermission <$> x .@? "group" <*> x .@? "userId" instance ToQuery LaunchPermission where toQuery LaunchPermission{..} = mconcat [ "Group" =? _lpGroup , "UserId" =? _lpUserId ] data RouteState = Active -- ^ active | Blackhole -- ^ blackhole deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable RouteState instance FromText RouteState where parser = takeLowerText >>= \case "active" -> pure Active "blackhole" -> pure Blackhole e -> fail $ "Failure parsing RouteState from " ++ show e instance ToText RouteState where toText = \case Active -> "active" Blackhole -> "blackhole" instance ToByteString RouteState instance ToHeader RouteState instance ToQuery RouteState instance FromXML RouteState where parseXML = parseXMLText "RouteState" data RouteTableAssociation = RouteTableAssociation { _rtaMain :: Maybe Bool , _rtaRouteTableAssociationId :: Maybe Text , _rtaRouteTableId :: Maybe Text , _rtaSubnetId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'RouteTableAssociation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rtaMain' @::@ 'Maybe' 'Bool' -- -- * 'rtaRouteTableAssociationId' @::@ 'Maybe' 'Text' -- -- * 'rtaRouteTableId' @::@ 'Maybe' 'Text' -- -- * 'rtaSubnetId' @::@ 'Maybe' 'Text' -- routeTableAssociation :: RouteTableAssociation routeTableAssociation = RouteTableAssociation { _rtaRouteTableAssociationId = Nothing , _rtaRouteTableId = Nothing , _rtaSubnetId = Nothing , _rtaMain = Nothing } -- | Indicates whether this is the main route table. rtaMain :: Lens' RouteTableAssociation (Maybe Bool) rtaMain = lens _rtaMain (\s a -> s { _rtaMain = a }) -- | The ID of the association between a route table and a subnet. rtaRouteTableAssociationId :: Lens' RouteTableAssociation (Maybe Text) rtaRouteTableAssociationId = lens _rtaRouteTableAssociationId (\s a -> s { _rtaRouteTableAssociationId = a }) -- | The ID of the route table. rtaRouteTableId :: Lens' RouteTableAssociation (Maybe Text) rtaRouteTableId = lens _rtaRouteTableId (\s a -> s { _rtaRouteTableId = a }) -- | The ID of the subnet. rtaSubnetId :: Lens' RouteTableAssociation (Maybe Text) rtaSubnetId = lens _rtaSubnetId (\s a -> s { _rtaSubnetId = a }) instance FromXML RouteTableAssociation where parseXML x = RouteTableAssociation <$> x .@? "main" <*> x .@? "routeTableAssociationId" <*> x .@? "routeTableId" <*> x .@? "subnetId" instance ToQuery RouteTableAssociation where toQuery RouteTableAssociation{..} = mconcat [ "Main" =? _rtaMain , "RouteTableAssociationId" =? _rtaRouteTableAssociationId , "RouteTableId" =? _rtaRouteTableId , "SubnetId" =? _rtaSubnetId ] data BundleTaskState = BTSBundling -- ^ bundling | BTSCancelling -- ^ cancelling | BTSComplete -- ^ complete | BTSFailed -- ^ failed | BTSPending -- ^ pending | BTSStoring -- ^ storing | BTSWaitingForShutdown -- ^ waiting-for-shutdown deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable BundleTaskState instance FromText BundleTaskState where parser = takeLowerText >>= \case "bundling" -> pure BTSBundling "cancelling" -> pure BTSCancelling "complete" -> pure BTSComplete "failed" -> pure BTSFailed "pending" -> pure BTSPending "storing" -> pure BTSStoring "waiting-for-shutdown" -> pure BTSWaitingForShutdown e -> fail $ "Failure parsing BundleTaskState from " ++ show e instance ToText BundleTaskState where toText = \case BTSBundling -> "bundling" BTSCancelling -> "cancelling" BTSComplete -> "complete" BTSFailed -> "failed" BTSPending -> "pending" BTSStoring -> "storing" BTSWaitingForShutdown -> "waiting-for-shutdown" instance ToByteString BundleTaskState instance ToHeader BundleTaskState instance ToQuery BundleTaskState instance FromXML BundleTaskState where parseXML = parseXMLText "BundleTaskState" data PortRange = PortRange { _prFrom :: Maybe Int , _prTo :: Maybe Int } deriving (Eq, Ord, Read, Show) -- | 'PortRange' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'prFrom' @::@ 'Maybe' 'Int' -- -- * 'prTo' @::@ 'Maybe' 'Int' -- portRange :: PortRange portRange = PortRange { _prFrom = Nothing , _prTo = Nothing } -- | The first port in the range. prFrom :: Lens' PortRange (Maybe Int) prFrom = lens _prFrom (\s a -> s { _prFrom = a }) -- | The last port in the range. prTo :: Lens' PortRange (Maybe Int) prTo = lens _prTo (\s a -> s { _prTo = a }) instance FromXML PortRange where parseXML x = PortRange <$> x .@? "from" <*> x .@? "to" instance ToQuery PortRange where toQuery PortRange{..} = mconcat [ "From" =? _prFrom , "To" =? _prTo ] data VpcAttributeName = EnableDnsHostnames -- ^ enableDnsHostnames | EnableDnsSupport -- ^ enableDnsSupport deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VpcAttributeName instance FromText VpcAttributeName where parser = takeLowerText >>= \case "enablednshostnames" -> pure EnableDnsHostnames "enablednssupport" -> pure EnableDnsSupport e -> fail $ "Failure parsing VpcAttributeName from " ++ show e instance ToText VpcAttributeName where toText = \case EnableDnsHostnames -> "enableDnsHostnames" EnableDnsSupport -> "enableDnsSupport" instance ToByteString VpcAttributeName instance ToHeader VpcAttributeName instance ToQuery VpcAttributeName instance FromXML VpcAttributeName where parseXML = parseXMLText "VpcAttributeName" data ReservedInstancesConfiguration = ReservedInstancesConfiguration { _ricAvailabilityZone :: Maybe Text , _ricInstanceCount :: Maybe Int , _ricInstanceType :: Maybe InstanceType , _ricPlatform :: Maybe Text } deriving (Eq, Read, Show) -- | 'ReservedInstancesConfiguration' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ricAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'ricInstanceCount' @::@ 'Maybe' 'Int' -- -- * 'ricInstanceType' @::@ 'Maybe' 'InstanceType' -- -- * 'ricPlatform' @::@ 'Maybe' 'Text' -- reservedInstancesConfiguration :: ReservedInstancesConfiguration reservedInstancesConfiguration = ReservedInstancesConfiguration { _ricAvailabilityZone = Nothing , _ricPlatform = Nothing , _ricInstanceCount = Nothing , _ricInstanceType = Nothing } -- | The Availability Zone for the modified Reserved Instances. ricAvailabilityZone :: Lens' ReservedInstancesConfiguration (Maybe Text) ricAvailabilityZone = lens _ricAvailabilityZone (\s a -> s { _ricAvailabilityZone = a }) -- | The number of modified Reserved Instances. ricInstanceCount :: Lens' ReservedInstancesConfiguration (Maybe Int) ricInstanceCount = lens _ricInstanceCount (\s a -> s { _ricInstanceCount = a }) -- | The instance type for the modified Reserved Instances. ricInstanceType :: Lens' ReservedInstancesConfiguration (Maybe InstanceType) ricInstanceType = lens _ricInstanceType (\s a -> s { _ricInstanceType = a }) -- | The network platform of the modified Reserved Instances, which is either -- EC2-Classic or EC2-VPC. ricPlatform :: Lens' ReservedInstancesConfiguration (Maybe Text) ricPlatform = lens _ricPlatform (\s a -> s { _ricPlatform = a }) instance FromXML ReservedInstancesConfiguration where parseXML x = ReservedInstancesConfiguration <$> x .@? "availabilityZone" <*> x .@? "instanceCount" <*> x .@? "instanceType" <*> x .@? "platform" instance ToQuery ReservedInstancesConfiguration where toQuery ReservedInstancesConfiguration{..} = mconcat [ "AvailabilityZone" =? _ricAvailabilityZone , "InstanceCount" =? _ricInstanceCount , "InstanceType" =? _ricInstanceType , "Platform" =? _ricPlatform ] data VolumeStatusDetails = VolumeStatusDetails { _vsdName :: Maybe VolumeStatusName , _vsdStatus :: Maybe Text } deriving (Eq, Read, Show) -- | 'VolumeStatusDetails' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vsdName' @::@ 'Maybe' 'VolumeStatusName' -- -- * 'vsdStatus' @::@ 'Maybe' 'Text' -- volumeStatusDetails :: VolumeStatusDetails volumeStatusDetails = VolumeStatusDetails { _vsdName = Nothing , _vsdStatus = Nothing } -- | The name of the volume status. vsdName :: Lens' VolumeStatusDetails (Maybe VolumeStatusName) vsdName = lens _vsdName (\s a -> s { _vsdName = a }) -- | The intended status of the volume status. vsdStatus :: Lens' VolumeStatusDetails (Maybe Text) vsdStatus = lens _vsdStatus (\s a -> s { _vsdStatus = a }) instance FromXML VolumeStatusDetails where parseXML x = VolumeStatusDetails <$> x .@? "name" <*> x .@? "status" instance ToQuery VolumeStatusDetails where toQuery VolumeStatusDetails{..} = mconcat [ "Name" =? _vsdName , "Status" =? _vsdStatus ] data SpotInstanceState = SISActive -- ^ active | SISCancelled -- ^ cancelled | SISClosed -- ^ closed | SISFailed -- ^ failed | SISOpen -- ^ open deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SpotInstanceState instance FromText SpotInstanceState where parser = takeLowerText >>= \case "active" -> pure SISActive "cancelled" -> pure SISCancelled "closed" -> pure SISClosed "failed" -> pure SISFailed "open" -> pure SISOpen e -> fail $ "Failure parsing SpotInstanceState from " ++ show e instance ToText SpotInstanceState where toText = \case SISActive -> "active" SISCancelled -> "cancelled" SISClosed -> "closed" SISFailed -> "failed" SISOpen -> "open" instance ToByteString SpotInstanceState instance ToHeader SpotInstanceState instance ToQuery SpotInstanceState instance FromXML SpotInstanceState where parseXML = parseXMLText "SpotInstanceState" newtype VpnConnectionOptions = VpnConnectionOptions { _vcoStaticRoutesOnly :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'VpnConnectionOptions' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vcoStaticRoutesOnly' @::@ 'Maybe' 'Bool' -- vpnConnectionOptions :: VpnConnectionOptions vpnConnectionOptions = VpnConnectionOptions { _vcoStaticRoutesOnly = Nothing } -- | Indicates whether the VPN connection uses static routes only. Static routes -- must be used for devices that don't support BGP. vcoStaticRoutesOnly :: Lens' VpnConnectionOptions (Maybe Bool) vcoStaticRoutesOnly = lens _vcoStaticRoutesOnly (\s a -> s { _vcoStaticRoutesOnly = a }) instance FromXML VpnConnectionOptions where parseXML x = VpnConnectionOptions <$> x .@? "staticRoutesOnly" instance ToQuery VpnConnectionOptions where toQuery VpnConnectionOptions{..} = mconcat [ "StaticRoutesOnly" =? _vcoStaticRoutesOnly ] data UserIdGroupPair = UserIdGroupPair { _uigpGroupId :: Maybe Text , _uigpGroupName :: Maybe Text , _uigpUserId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'UserIdGroupPair' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'uigpGroupId' @::@ 'Maybe' 'Text' -- -- * 'uigpGroupName' @::@ 'Maybe' 'Text' -- -- * 'uigpUserId' @::@ 'Maybe' 'Text' -- userIdGroupPair :: UserIdGroupPair userIdGroupPair = UserIdGroupPair { _uigpUserId = Nothing , _uigpGroupName = Nothing , _uigpGroupId = Nothing } -- | The ID of the security group. uigpGroupId :: Lens' UserIdGroupPair (Maybe Text) uigpGroupId = lens _uigpGroupId (\s a -> s { _uigpGroupId = a }) -- | The name of the security group. In a request, use this parameter for a -- security group in EC2-Classic or a default VPC only. For a security group in -- a nondefault VPC, use 'GroupId'. uigpGroupName :: Lens' UserIdGroupPair (Maybe Text) uigpGroupName = lens _uigpGroupName (\s a -> s { _uigpGroupName = a }) -- | The ID of an AWS account. EC2-Classic only. uigpUserId :: Lens' UserIdGroupPair (Maybe Text) uigpUserId = lens _uigpUserId (\s a -> s { _uigpUserId = a }) instance FromXML UserIdGroupPair where parseXML x = UserIdGroupPair <$> x .@? "groupId" <*> x .@? "groupName" <*> x .@? "userId" instance ToQuery UserIdGroupPair where toQuery UserIdGroupPair{..} = mconcat [ "GroupId" =? _uigpGroupId , "GroupName" =? _uigpGroupName , "UserId" =? _uigpUserId ] data InstanceStatusSummary = InstanceStatusSummary { _issDetails :: List "item" InstanceStatusDetails , _issStatus :: Maybe SummaryStatus } deriving (Eq, Read, Show) -- | 'InstanceStatusSummary' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'issDetails' @::@ ['InstanceStatusDetails'] -- -- * 'issStatus' @::@ 'Maybe' 'SummaryStatus' -- instanceStatusSummary :: InstanceStatusSummary instanceStatusSummary = InstanceStatusSummary { _issStatus = Nothing , _issDetails = mempty } -- | The system instance health or application instance health. issDetails :: Lens' InstanceStatusSummary [InstanceStatusDetails] issDetails = lens _issDetails (\s a -> s { _issDetails = a }) . _List -- | The status. issStatus :: Lens' InstanceStatusSummary (Maybe SummaryStatus) issStatus = lens _issStatus (\s a -> s { _issStatus = a }) instance FromXML InstanceStatusSummary where parseXML x = InstanceStatusSummary <$> x .@? "details" .!@ mempty <*> x .@? "status" instance ToQuery InstanceStatusSummary where toQuery InstanceStatusSummary{..} = mconcat [ "Details" `toQueryList` _issDetails , "Status" =? _issStatus ] data SpotPlacement = SpotPlacement { _sp1AvailabilityZone :: Maybe Text , _sp1GroupName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'SpotPlacement' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sp1AvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'sp1GroupName' @::@ 'Maybe' 'Text' -- spotPlacement :: SpotPlacement spotPlacement = SpotPlacement { _sp1AvailabilityZone = Nothing , _sp1GroupName = Nothing } -- | The Availability Zone. sp1AvailabilityZone :: Lens' SpotPlacement (Maybe Text) sp1AvailabilityZone = lens _sp1AvailabilityZone (\s a -> s { _sp1AvailabilityZone = a }) -- | The name of the placement group (for cluster instances). sp1GroupName :: Lens' SpotPlacement (Maybe Text) sp1GroupName = lens _sp1GroupName (\s a -> s { _sp1GroupName = a }) instance FromXML SpotPlacement where parseXML x = SpotPlacement <$> x .@? "availabilityZone" <*> x .@? "groupName" instance ToQuery SpotPlacement where toQuery SpotPlacement{..} = mconcat [ "AvailabilityZone" =? _sp1AvailabilityZone , "GroupName" =? _sp1GroupName ] data EbsInstanceBlockDeviceSpecification = EbsInstanceBlockDeviceSpecification { _eibdsDeleteOnTermination :: Maybe Bool , _eibdsVolumeId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'EbsInstanceBlockDeviceSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'eibdsDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'eibdsVolumeId' @::@ 'Maybe' 'Text' -- ebsInstanceBlockDeviceSpecification :: EbsInstanceBlockDeviceSpecification ebsInstanceBlockDeviceSpecification = EbsInstanceBlockDeviceSpecification { _eibdsVolumeId = Nothing , _eibdsDeleteOnTermination = Nothing } -- | Indicates whether the volume is deleted on instance termination. eibdsDeleteOnTermination :: Lens' EbsInstanceBlockDeviceSpecification (Maybe Bool) eibdsDeleteOnTermination = lens _eibdsDeleteOnTermination (\s a -> s { _eibdsDeleteOnTermination = a }) -- | The ID of the Amazon EBS volume. eibdsVolumeId :: Lens' EbsInstanceBlockDeviceSpecification (Maybe Text) eibdsVolumeId = lens _eibdsVolumeId (\s a -> s { _eibdsVolumeId = a }) instance FromXML EbsInstanceBlockDeviceSpecification where parseXML x = EbsInstanceBlockDeviceSpecification <$> x .@? "deleteOnTermination" <*> x .@? "volumeId" instance ToQuery EbsInstanceBlockDeviceSpecification where toQuery EbsInstanceBlockDeviceSpecification{..} = mconcat [ "DeleteOnTermination" =? _eibdsDeleteOnTermination , "VolumeId" =? _eibdsVolumeId ] data NetworkAclAssociation = NetworkAclAssociation { _naaNetworkAclAssociationId :: Maybe Text , _naaNetworkAclId :: Maybe Text , _naaSubnetId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'NetworkAclAssociation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'naaNetworkAclAssociationId' @::@ 'Maybe' 'Text' -- -- * 'naaNetworkAclId' @::@ 'Maybe' 'Text' -- -- * 'naaSubnetId' @::@ 'Maybe' 'Text' -- networkAclAssociation :: NetworkAclAssociation networkAclAssociation = NetworkAclAssociation { _naaNetworkAclAssociationId = Nothing , _naaNetworkAclId = Nothing , _naaSubnetId = Nothing } -- | The ID of the association between a network ACL and a subnet. naaNetworkAclAssociationId :: Lens' NetworkAclAssociation (Maybe Text) naaNetworkAclAssociationId = lens _naaNetworkAclAssociationId (\s a -> s { _naaNetworkAclAssociationId = a }) -- | The ID of the network ACL. naaNetworkAclId :: Lens' NetworkAclAssociation (Maybe Text) naaNetworkAclId = lens _naaNetworkAclId (\s a -> s { _naaNetworkAclId = a }) -- | The ID of the subnet. naaSubnetId :: Lens' NetworkAclAssociation (Maybe Text) naaSubnetId = lens _naaSubnetId (\s a -> s { _naaSubnetId = a }) instance FromXML NetworkAclAssociation where parseXML x = NetworkAclAssociation <$> x .@? "networkAclAssociationId" <*> x .@? "networkAclId" <*> x .@? "subnetId" instance ToQuery NetworkAclAssociation where toQuery NetworkAclAssociation{..} = mconcat [ "NetworkAclAssociationId" =? _naaNetworkAclAssociationId , "NetworkAclId" =? _naaNetworkAclId , "SubnetId" =? _naaSubnetId ] data BundleTask = BundleTask { _btBundleId :: Text , _btBundleTaskError :: Maybe BundleTaskError , _btInstanceId :: Text , _btProgress :: Text , _btStartTime :: ISO8601 , _btState :: BundleTaskState , _btStorage :: Storage , _btUpdateTime :: ISO8601 } deriving (Eq, Read, Show) -- | 'BundleTask' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'btBundleId' @::@ 'Text' -- -- * 'btBundleTaskError' @::@ 'Maybe' 'BundleTaskError' -- -- * 'btInstanceId' @::@ 'Text' -- -- * 'btProgress' @::@ 'Text' -- -- * 'btStartTime' @::@ 'UTCTime' -- -- * 'btState' @::@ 'BundleTaskState' -- -- * 'btStorage' @::@ 'Storage' -- -- * 'btUpdateTime' @::@ 'UTCTime' -- bundleTask :: Text -- ^ 'btInstanceId' -> Text -- ^ 'btBundleId' -> BundleTaskState -- ^ 'btState' -> UTCTime -- ^ 'btStartTime' -> UTCTime -- ^ 'btUpdateTime' -> Storage -- ^ 'btStorage' -> Text -- ^ 'btProgress' -> BundleTask bundleTask p1 p2 p3 p4 p5 p6 p7 = BundleTask { _btInstanceId = p1 , _btBundleId = p2 , _btState = p3 , _btStartTime = withIso _Time (const id) p4 , _btUpdateTime = withIso _Time (const id) p5 , _btStorage = p6 , _btProgress = p7 , _btBundleTaskError = Nothing } -- | The ID of the bundle task. btBundleId :: Lens' BundleTask Text btBundleId = lens _btBundleId (\s a -> s { _btBundleId = a }) -- | If the task fails, a description of the error. btBundleTaskError :: Lens' BundleTask (Maybe BundleTaskError) btBundleTaskError = lens _btBundleTaskError (\s a -> s { _btBundleTaskError = a }) -- | The ID of the instance associated with this bundle task. btInstanceId :: Lens' BundleTask Text btInstanceId = lens _btInstanceId (\s a -> s { _btInstanceId = a }) -- | The level of task completion, as a percent (for example, 20%). btProgress :: Lens' BundleTask Text btProgress = lens _btProgress (\s a -> s { _btProgress = a }) -- | The time this task started. btStartTime :: Lens' BundleTask UTCTime btStartTime = lens _btStartTime (\s a -> s { _btStartTime = a }) . _Time -- | The state of the task. btState :: Lens' BundleTask BundleTaskState btState = lens _btState (\s a -> s { _btState = a }) -- | The Amazon S3 storage locations. btStorage :: Lens' BundleTask Storage btStorage = lens _btStorage (\s a -> s { _btStorage = a }) -- | The time of the most recent update for the task. btUpdateTime :: Lens' BundleTask UTCTime btUpdateTime = lens _btUpdateTime (\s a -> s { _btUpdateTime = a }) . _Time instance FromXML BundleTask where parseXML x = BundleTask <$> x .@ "bundleId" <*> x .@? "error" <*> x .@ "instanceId" <*> x .@ "progress" <*> x .@ "startTime" <*> x .@ "state" <*> x .@ "storage" <*> x .@ "updateTime" instance ToQuery BundleTask where toQuery BundleTask{..} = mconcat [ "BundleId" =? _btBundleId , "Error" =? _btBundleTaskError , "InstanceId" =? _btInstanceId , "Progress" =? _btProgress , "StartTime" =? _btStartTime , "State" =? _btState , "Storage" =? _btStorage , "UpdateTime" =? _btUpdateTime ] data InstanceStatusEvent = InstanceStatusEvent { _iseCode :: Maybe EventCode , _iseDescription :: Maybe Text , _iseNotAfter :: Maybe ISO8601 , _iseNotBefore :: Maybe ISO8601 } deriving (Eq, Read, Show) -- | 'InstanceStatusEvent' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iseCode' @::@ 'Maybe' 'EventCode' -- -- * 'iseDescription' @::@ 'Maybe' 'Text' -- -- * 'iseNotAfter' @::@ 'Maybe' 'UTCTime' -- -- * 'iseNotBefore' @::@ 'Maybe' 'UTCTime' -- instanceStatusEvent :: InstanceStatusEvent instanceStatusEvent = InstanceStatusEvent { _iseCode = Nothing , _iseDescription = Nothing , _iseNotBefore = Nothing , _iseNotAfter = Nothing } -- | The associated code of the event. iseCode :: Lens' InstanceStatusEvent (Maybe EventCode) iseCode = lens _iseCode (\s a -> s { _iseCode = a }) -- | A description of the event. iseDescription :: Lens' InstanceStatusEvent (Maybe Text) iseDescription = lens _iseDescription (\s a -> s { _iseDescription = a }) -- | The latest scheduled end time for the event. iseNotAfter :: Lens' InstanceStatusEvent (Maybe UTCTime) iseNotAfter = lens _iseNotAfter (\s a -> s { _iseNotAfter = a }) . mapping _Time -- | The earliest scheduled start time for the event. iseNotBefore :: Lens' InstanceStatusEvent (Maybe UTCTime) iseNotBefore = lens _iseNotBefore (\s a -> s { _iseNotBefore = a }) . mapping _Time instance FromXML InstanceStatusEvent where parseXML x = InstanceStatusEvent <$> x .@? "code" <*> x .@? "description" <*> x .@? "notAfter" <*> x .@? "notBefore" instance ToQuery InstanceStatusEvent where toQuery InstanceStatusEvent{..} = mconcat [ "Code" =? _iseCode , "Description" =? _iseDescription , "NotAfter" =? _iseNotAfter , "NotBefore" =? _iseNotBefore ] data InstanceType = C1_Medium -- ^ c1.medium | C1_XLarge -- ^ c1.xlarge | C3_2XLarge -- ^ c3.2xlarge | C3_4XLarge -- ^ c3.4xlarge | C3_8XLarge -- ^ c3.8xlarge | C3_Large -- ^ c3.large | C3_XLarge -- ^ c3.xlarge | C4_2XLarge -- ^ c4.2xlarge | C4_4XLarge -- ^ c4.4xlarge | C4_8XLarge -- ^ c4.8xlarge | C4_Large -- ^ c4.large | C4_XLarge -- ^ c4.xlarge | CC1_4XLarge -- ^ cc1.4xlarge | CC2_8XLarge -- ^ cc2.8xlarge | CG1_4XLarge -- ^ cg1.4xlarge | CR1_8XLarge -- ^ cr1.8xlarge | D2_2XLarge -- ^ d2.2xlarge | D2_4XLarge -- ^ d2.4xlarge | D2_8XLarge -- ^ d2.8xlarge | D2_XLarge -- ^ d2.xlarge | G2_2XLarge -- ^ g2.2xlarge | HI1_4XLarge -- ^ hi1.4xlarge | HS1_8XLarge -- ^ hs1.8xlarge | I2_2XLarge -- ^ i2.2xlarge | I2_4XLarge -- ^ i2.4xlarge | I2_8XLarge -- ^ i2.8xlarge | I2_XLarge -- ^ i2.xlarge | M1_Large -- ^ m1.large | M1_Medium -- ^ m1.medium | M1_Small -- ^ m1.small | M1_XLarge -- ^ m1.xlarge | M2_2XLarge -- ^ m2.2xlarge | M2_4XLarge -- ^ m2.4xlarge | M2_XLarge -- ^ m2.xlarge | M3_2XLarge -- ^ m3.2xlarge | M3_Large -- ^ m3.large | M3_Medium -- ^ m3.medium | M3_XLarge -- ^ m3.xlarge | R3_2XLarge -- ^ r3.2xlarge | R3_4XLarge -- ^ r3.4xlarge | R3_8XLarge -- ^ r3.8xlarge | R3_Large -- ^ r3.large | R3_XLarge -- ^ r3.xlarge | T1_Micro -- ^ t1.micro | T2_Medium -- ^ t2.medium | T2_Micro -- ^ t2.micro | T2_Small -- ^ t2.small deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable InstanceType instance FromText InstanceType where parser = takeLowerText >>= \case "c1.medium" -> pure C1_Medium "c1.xlarge" -> pure C1_XLarge "c3.2xlarge" -> pure C3_2XLarge "c3.4xlarge" -> pure C3_4XLarge "c3.8xlarge" -> pure C3_8XLarge "c3.large" -> pure C3_Large "c3.xlarge" -> pure C3_XLarge "c4.2xlarge" -> pure C4_2XLarge "c4.4xlarge" -> pure C4_4XLarge "c4.8xlarge" -> pure C4_8XLarge "c4.large" -> pure C4_Large "c4.xlarge" -> pure C4_XLarge "cc1.4xlarge" -> pure CC1_4XLarge "cc2.8xlarge" -> pure CC2_8XLarge "cg1.4xlarge" -> pure CG1_4XLarge "cr1.8xlarge" -> pure CR1_8XLarge "d2.2xlarge" -> pure D2_2XLarge "d2.4xlarge" -> pure D2_4XLarge "d2.8xlarge" -> pure D2_8XLarge "d2.xlarge" -> pure D2_XLarge "g2.2xlarge" -> pure G2_2XLarge "hi1.4xlarge" -> pure HI1_4XLarge "hs1.8xlarge" -> pure HS1_8XLarge "i2.2xlarge" -> pure I2_2XLarge "i2.4xlarge" -> pure I2_4XLarge "i2.8xlarge" -> pure I2_8XLarge "i2.xlarge" -> pure I2_XLarge "m1.large" -> pure M1_Large "m1.medium" -> pure M1_Medium "m1.small" -> pure M1_Small "m1.xlarge" -> pure M1_XLarge "m2.2xlarge" -> pure M2_2XLarge "m2.4xlarge" -> pure M2_4XLarge "m2.xlarge" -> pure M2_XLarge "m3.2xlarge" -> pure M3_2XLarge "m3.large" -> pure M3_Large "m3.medium" -> pure M3_Medium "m3.xlarge" -> pure M3_XLarge "r3.2xlarge" -> pure R3_2XLarge "r3.4xlarge" -> pure R3_4XLarge "r3.8xlarge" -> pure R3_8XLarge "r3.large" -> pure R3_Large "r3.xlarge" -> pure R3_XLarge "t1.micro" -> pure T1_Micro "t2.medium" -> pure T2_Medium "t2.micro" -> pure T2_Micro "t2.small" -> pure T2_Small e -> fail $ "Failure parsing InstanceType from " ++ show e instance ToText InstanceType where toText = \case C1_Medium -> "c1.medium" C1_XLarge -> "c1.xlarge" C3_2XLarge -> "c3.2xlarge" C3_4XLarge -> "c3.4xlarge" C3_8XLarge -> "c3.8xlarge" C3_Large -> "c3.large" C3_XLarge -> "c3.xlarge" C4_2XLarge -> "c4.2xlarge" C4_4XLarge -> "c4.4xlarge" C4_8XLarge -> "c4.8xlarge" C4_Large -> "c4.large" C4_XLarge -> "c4.xlarge" CC1_4XLarge -> "cc1.4xlarge" CC2_8XLarge -> "cc2.8xlarge" CG1_4XLarge -> "cg1.4xlarge" CR1_8XLarge -> "cr1.8xlarge" D2_2XLarge -> "d2.2xlarge" D2_4XLarge -> "d2.4xlarge" D2_8XLarge -> "d2.8xlarge" D2_XLarge -> "d2.xlarge" G2_2XLarge -> "g2.2xlarge" HI1_4XLarge -> "hi1.4xlarge" HS1_8XLarge -> "hs1.8xlarge" I2_2XLarge -> "i2.2xlarge" I2_4XLarge -> "i2.4xlarge" I2_8XLarge -> "i2.8xlarge" I2_XLarge -> "i2.xlarge" M1_Large -> "m1.large" M1_Medium -> "m1.medium" M1_Small -> "m1.small" M1_XLarge -> "m1.xlarge" M2_2XLarge -> "m2.2xlarge" M2_4XLarge -> "m2.4xlarge" M2_XLarge -> "m2.xlarge" M3_2XLarge -> "m3.2xlarge" M3_Large -> "m3.large" M3_Medium -> "m3.medium" M3_XLarge -> "m3.xlarge" R3_2XLarge -> "r3.2xlarge" R3_4XLarge -> "r3.4xlarge" R3_8XLarge -> "r3.8xlarge" R3_Large -> "r3.large" R3_XLarge -> "r3.xlarge" T1_Micro -> "t1.micro" T2_Medium -> "t2.medium" T2_Micro -> "t2.micro" T2_Small -> "t2.small" instance ToByteString InstanceType instance ToHeader InstanceType instance ToQuery InstanceType instance FromXML InstanceType where parseXML = parseXMLText "InstanceType" data Route = Route { _rDestinationCidrBlock :: Maybe Text , _rGatewayId :: Maybe Text , _rInstanceId :: Maybe Text , _rInstanceOwnerId :: Maybe Text , _rNetworkInterfaceId :: Maybe Text , _rOrigin :: Maybe RouteOrigin , _rState :: Maybe RouteState , _rVpcPeeringConnectionId :: Maybe Text } deriving (Eq, Read, Show) -- | 'Route' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rDestinationCidrBlock' @::@ 'Maybe' 'Text' -- -- * 'rGatewayId' @::@ 'Maybe' 'Text' -- -- * 'rInstanceId' @::@ 'Maybe' 'Text' -- -- * 'rInstanceOwnerId' @::@ 'Maybe' 'Text' -- -- * 'rNetworkInterfaceId' @::@ 'Maybe' 'Text' -- -- * 'rOrigin' @::@ 'Maybe' 'RouteOrigin' -- -- * 'rState' @::@ 'Maybe' 'RouteState' -- -- * 'rVpcPeeringConnectionId' @::@ 'Maybe' 'Text' -- route :: Route route = Route { _rDestinationCidrBlock = Nothing , _rGatewayId = Nothing , _rInstanceId = Nothing , _rInstanceOwnerId = Nothing , _rNetworkInterfaceId = Nothing , _rVpcPeeringConnectionId = Nothing , _rState = Nothing , _rOrigin = Nothing } -- | The CIDR block used for the destination match. rDestinationCidrBlock :: Lens' Route (Maybe Text) rDestinationCidrBlock = lens _rDestinationCidrBlock (\s a -> s { _rDestinationCidrBlock = a }) -- | The ID of a gateway attached to your VPC. rGatewayId :: Lens' Route (Maybe Text) rGatewayId = lens _rGatewayId (\s a -> s { _rGatewayId = a }) -- | The ID of a NAT instance in your VPC. rInstanceId :: Lens' Route (Maybe Text) rInstanceId = lens _rInstanceId (\s a -> s { _rInstanceId = a }) -- | The AWS account ID of the owner of the instance. rInstanceOwnerId :: Lens' Route (Maybe Text) rInstanceOwnerId = lens _rInstanceOwnerId (\s a -> s { _rInstanceOwnerId = a }) -- | The ID of the network interface. rNetworkInterfaceId :: Lens' Route (Maybe Text) rNetworkInterfaceId = lens _rNetworkInterfaceId (\s a -> s { _rNetworkInterfaceId = a }) -- | Describes how the route was created. -- -- 'CreateRouteTable' indicates that route was automatically created when the -- route table was created. 'CreateRoute' indicates that the route was manually -- added to the route table. 'EnableVgwRoutePropagation' indicates that the route -- was propagated by route propagation. rOrigin :: Lens' Route (Maybe RouteOrigin) rOrigin = lens _rOrigin (\s a -> s { _rOrigin = a }) -- | The state of the route. The 'blackhole' state indicates that the route's target -- isn't available (for example, the specified gateway isn't attached to the -- VPC, or the specified NAT instance has been terminated). rState :: Lens' Route (Maybe RouteState) rState = lens _rState (\s a -> s { _rState = a }) -- | The ID of the VPC peering connection. rVpcPeeringConnectionId :: Lens' Route (Maybe Text) rVpcPeeringConnectionId = lens _rVpcPeeringConnectionId (\s a -> s { _rVpcPeeringConnectionId = a }) instance FromXML Route where parseXML x = Route <$> x .@? "destinationCidrBlock" <*> x .@? "gatewayId" <*> x .@? "instanceId" <*> x .@? "instanceOwnerId" <*> x .@? "networkInterfaceId" <*> x .@? "origin" <*> x .@? "state" <*> x .@? "vpcPeeringConnectionId" instance ToQuery Route where toQuery Route{..} = mconcat [ "DestinationCidrBlock" =? _rDestinationCidrBlock , "GatewayId" =? _rGatewayId , "InstanceId" =? _rInstanceId , "InstanceOwnerId" =? _rInstanceOwnerId , "NetworkInterfaceId" =? _rNetworkInterfaceId , "Origin" =? _rOrigin , "State" =? _rState , "VpcPeeringConnectionId" =? _rVpcPeeringConnectionId ] data SpotDatafeedSubscription = SpotDatafeedSubscription { _sdsBucket :: Maybe Text , _sdsFault :: Maybe SpotInstanceStateFault , _sdsOwnerId :: Maybe Text , _sdsPrefix :: Maybe Text , _sdsState :: Maybe DatafeedSubscriptionState } deriving (Eq, Read, Show) -- | 'SpotDatafeedSubscription' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sdsBucket' @::@ 'Maybe' 'Text' -- -- * 'sdsFault' @::@ 'Maybe' 'SpotInstanceStateFault' -- -- * 'sdsOwnerId' @::@ 'Maybe' 'Text' -- -- * 'sdsPrefix' @::@ 'Maybe' 'Text' -- -- * 'sdsState' @::@ 'Maybe' 'DatafeedSubscriptionState' -- spotDatafeedSubscription :: SpotDatafeedSubscription spotDatafeedSubscription = SpotDatafeedSubscription { _sdsOwnerId = Nothing , _sdsBucket = Nothing , _sdsPrefix = Nothing , _sdsState = Nothing , _sdsFault = Nothing } -- | The Amazon S3 bucket where the Spot Instance data feed is located. sdsBucket :: Lens' SpotDatafeedSubscription (Maybe Text) sdsBucket = lens _sdsBucket (\s a -> s { _sdsBucket = a }) -- | The fault codes for the Spot Instance request, if any. sdsFault :: Lens' SpotDatafeedSubscription (Maybe SpotInstanceStateFault) sdsFault = lens _sdsFault (\s a -> s { _sdsFault = a }) -- | The AWS account ID of the account. sdsOwnerId :: Lens' SpotDatafeedSubscription (Maybe Text) sdsOwnerId = lens _sdsOwnerId (\s a -> s { _sdsOwnerId = a }) -- | The prefix that is prepended to data feed files. sdsPrefix :: Lens' SpotDatafeedSubscription (Maybe Text) sdsPrefix = lens _sdsPrefix (\s a -> s { _sdsPrefix = a }) -- | The state of the Spot Instance data feed subscription. sdsState :: Lens' SpotDatafeedSubscription (Maybe DatafeedSubscriptionState) sdsState = lens _sdsState (\s a -> s { _sdsState = a }) instance FromXML SpotDatafeedSubscription where parseXML x = SpotDatafeedSubscription <$> x .@? "bucket" <*> x .@? "fault" <*> x .@? "ownerId" <*> x .@? "prefix" <*> x .@? "state" instance ToQuery SpotDatafeedSubscription where toQuery SpotDatafeedSubscription{..} = mconcat [ "Bucket" =? _sdsBucket , "Fault" =? _sdsFault , "OwnerId" =? _sdsOwnerId , "Prefix" =? _sdsPrefix , "State" =? _sdsState ] newtype Storage = Storage { _sS3 :: Maybe S3Storage } deriving (Eq, Read, Show) -- | 'Storage' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sS3' @::@ 'Maybe' 'S3Storage' -- storage :: Storage storage = Storage { _sS3 = Nothing } -- | An Amazon S3 storage location. sS3 :: Lens' Storage (Maybe S3Storage) sS3 = lens _sS3 (\s a -> s { _sS3 = a }) instance FromXML Storage where parseXML x = Storage <$> x .@? "S3" instance ToQuery Storage where toQuery Storage{..} = mconcat [ "S3" =? _sS3 ] data SecurityGroup = SecurityGroup { _sgDescription :: Text , _sgGroupId :: Text , _sgGroupName :: Text , _sgIpPermissions :: List "item" IpPermission , _sgIpPermissionsEgress :: List "item" IpPermission , _sgOwnerId :: Text , _sgTags :: List "item" Tag , _sgVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'SecurityGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sgDescription' @::@ 'Text' -- -- * 'sgGroupId' @::@ 'Text' -- -- * 'sgGroupName' @::@ 'Text' -- -- * 'sgIpPermissions' @::@ ['IpPermission'] -- -- * 'sgIpPermissionsEgress' @::@ ['IpPermission'] -- -- * 'sgOwnerId' @::@ 'Text' -- -- * 'sgTags' @::@ ['Tag'] -- -- * 'sgVpcId' @::@ 'Maybe' 'Text' -- securityGroup :: Text -- ^ 'sgOwnerId' -> Text -- ^ 'sgGroupName' -> Text -- ^ 'sgGroupId' -> Text -- ^ 'sgDescription' -> SecurityGroup securityGroup p1 p2 p3 p4 = SecurityGroup { _sgOwnerId = p1 , _sgGroupName = p2 , _sgGroupId = p3 , _sgDescription = p4 , _sgIpPermissions = mempty , _sgIpPermissionsEgress = mempty , _sgVpcId = Nothing , _sgTags = mempty } -- | A description of the security group. sgDescription :: Lens' SecurityGroup Text sgDescription = lens _sgDescription (\s a -> s { _sgDescription = a }) -- | The ID of the security group. sgGroupId :: Lens' SecurityGroup Text sgGroupId = lens _sgGroupId (\s a -> s { _sgGroupId = a }) -- | The name of the security group. sgGroupName :: Lens' SecurityGroup Text sgGroupName = lens _sgGroupName (\s a -> s { _sgGroupName = a }) -- | One or more inbound rules associated with the security group. sgIpPermissions :: Lens' SecurityGroup [IpPermission] sgIpPermissions = lens _sgIpPermissions (\s a -> s { _sgIpPermissions = a }) . _List -- | [EC2-VPC] One or more outbound rules associated with the security group. sgIpPermissionsEgress :: Lens' SecurityGroup [IpPermission] sgIpPermissionsEgress = lens _sgIpPermissionsEgress (\s a -> s { _sgIpPermissionsEgress = a }) . _List -- | The AWS account ID of the owner of the security group. sgOwnerId :: Lens' SecurityGroup Text sgOwnerId = lens _sgOwnerId (\s a -> s { _sgOwnerId = a }) -- | Any tags assigned to the security group. sgTags :: Lens' SecurityGroup [Tag] sgTags = lens _sgTags (\s a -> s { _sgTags = a }) . _List -- | [EC2-VPC] The ID of the VPC for the security group. sgVpcId :: Lens' SecurityGroup (Maybe Text) sgVpcId = lens _sgVpcId (\s a -> s { _sgVpcId = a }) instance FromXML SecurityGroup where parseXML x = SecurityGroup <$> x .@ "groupDescription" <*> x .@ "groupId" <*> x .@ "groupName" <*> x .@? "ipPermissions" .!@ mempty <*> x .@? "ipPermissionsEgress" .!@ mempty <*> x .@ "ownerId" <*> x .@? "tagSet" .!@ mempty <*> x .@? "vpcId" instance ToQuery SecurityGroup where toQuery SecurityGroup{..} = mconcat [ "GroupDescription" =? _sgDescription , "GroupId" =? _sgGroupId , "GroupName" =? _sgGroupName , "IpPermissions" `toQueryList` _sgIpPermissions , "IpPermissionsEgress" `toQueryList` _sgIpPermissionsEgress , "OwnerId" =? _sgOwnerId , "TagSet" `toQueryList` _sgTags , "VpcId" =? _sgVpcId ] data CancelSpotInstanceRequestState = CSIRSActive -- ^ active | CSIRSCancelled -- ^ cancelled | CSIRSClosed -- ^ closed | CSIRSCompleted -- ^ completed | CSIRSOpen -- ^ open deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable CancelSpotInstanceRequestState instance FromText CancelSpotInstanceRequestState where parser = takeLowerText >>= \case "active" -> pure CSIRSActive "cancelled" -> pure CSIRSCancelled "closed" -> pure CSIRSClosed "completed" -> pure CSIRSCompleted "open" -> pure CSIRSOpen e -> fail $ "Failure parsing CancelSpotInstanceRequestState from " ++ show e instance ToText CancelSpotInstanceRequestState where toText = \case CSIRSActive -> "active" CSIRSCancelled -> "cancelled" CSIRSClosed -> "closed" CSIRSCompleted -> "completed" CSIRSOpen -> "open" instance ToByteString CancelSpotInstanceRequestState instance ToHeader CancelSpotInstanceRequestState instance ToQuery CancelSpotInstanceRequestState instance FromXML CancelSpotInstanceRequestState where parseXML = parseXMLText "CancelSpotInstanceRequestState" data PlacementGroupState = PGSAvailable -- ^ available | PGSDeleted -- ^ deleted | PGSDeleting -- ^ deleting | PGSPending -- ^ pending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable PlacementGroupState instance FromText PlacementGroupState where parser = takeLowerText >>= \case "available" -> pure PGSAvailable "deleted" -> pure PGSDeleted "deleting" -> pure PGSDeleting "pending" -> pure PGSPending e -> fail $ "Failure parsing PlacementGroupState from " ++ show e instance ToText PlacementGroupState where toText = \case PGSAvailable -> "available" PGSDeleted -> "deleted" PGSDeleting -> "deleting" PGSPending -> "pending" instance ToByteString PlacementGroupState instance ToHeader PlacementGroupState instance ToQuery PlacementGroupState instance FromXML PlacementGroupState where parseXML = parseXMLText "PlacementGroupState" data ReservedInstancesModificationResult = ReservedInstancesModificationResult { _rimrReservedInstancesId :: Maybe Text , _rimrTargetConfiguration :: Maybe ReservedInstancesConfiguration } deriving (Eq, Read, Show) -- | 'ReservedInstancesModificationResult' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rimrReservedInstancesId' @::@ 'Maybe' 'Text' -- -- * 'rimrTargetConfiguration' @::@ 'Maybe' 'ReservedInstancesConfiguration' -- reservedInstancesModificationResult :: ReservedInstancesModificationResult reservedInstancesModificationResult = ReservedInstancesModificationResult { _rimrReservedInstancesId = Nothing , _rimrTargetConfiguration = Nothing } -- | The ID for the Reserved Instances that were created as part of the -- modification request. This field is only available when the modification is -- fulfilled. rimrReservedInstancesId :: Lens' ReservedInstancesModificationResult (Maybe Text) rimrReservedInstancesId = lens _rimrReservedInstancesId (\s a -> s { _rimrReservedInstancesId = a }) -- | The target Reserved Instances configurations supplied as part of the -- modification request. rimrTargetConfiguration :: Lens' ReservedInstancesModificationResult (Maybe ReservedInstancesConfiguration) rimrTargetConfiguration = lens _rimrTargetConfiguration (\s a -> s { _rimrTargetConfiguration = a }) instance FromXML ReservedInstancesModificationResult where parseXML x = ReservedInstancesModificationResult <$> x .@? "reservedInstancesId" <*> x .@? "targetConfiguration" instance ToQuery ReservedInstancesModificationResult where toQuery ReservedInstancesModificationResult{..} = mconcat [ "ReservedInstancesId" =? _rimrReservedInstancesId , "TargetConfiguration" =? _rimrTargetConfiguration ] data InstanceBlockDeviceMappingSpecification = InstanceBlockDeviceMappingSpecification { _ibdmsDeviceName :: Maybe Text , _ibdmsEbs :: Maybe EbsInstanceBlockDeviceSpecification , _ibdmsNoDevice :: Maybe Text , _ibdmsVirtualName :: Maybe Text } deriving (Eq, Read, Show) -- | 'InstanceBlockDeviceMappingSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ibdmsDeviceName' @::@ 'Maybe' 'Text' -- -- * 'ibdmsEbs' @::@ 'Maybe' 'EbsInstanceBlockDeviceSpecification' -- -- * 'ibdmsNoDevice' @::@ 'Maybe' 'Text' -- -- * 'ibdmsVirtualName' @::@ 'Maybe' 'Text' -- instanceBlockDeviceMappingSpecification :: InstanceBlockDeviceMappingSpecification instanceBlockDeviceMappingSpecification = InstanceBlockDeviceMappingSpecification { _ibdmsDeviceName = Nothing , _ibdmsEbs = Nothing , _ibdmsVirtualName = Nothing , _ibdmsNoDevice = Nothing } -- | The device name exposed to the instance (for example, '/dev/sdh' or 'xvdh'). ibdmsDeviceName :: Lens' InstanceBlockDeviceMappingSpecification (Maybe Text) ibdmsDeviceName = lens _ibdmsDeviceName (\s a -> s { _ibdmsDeviceName = a }) -- | Parameters used to automatically set up Amazon EBS volumes when the instance -- is launched. ibdmsEbs :: Lens' InstanceBlockDeviceMappingSpecification (Maybe EbsInstanceBlockDeviceSpecification) ibdmsEbs = lens _ibdmsEbs (\s a -> s { _ibdmsEbs = a }) -- | suppress the specified device included in the block device mapping. ibdmsNoDevice :: Lens' InstanceBlockDeviceMappingSpecification (Maybe Text) ibdmsNoDevice = lens _ibdmsNoDevice (\s a -> s { _ibdmsNoDevice = a }) -- | The virtual device name. ibdmsVirtualName :: Lens' InstanceBlockDeviceMappingSpecification (Maybe Text) ibdmsVirtualName = lens _ibdmsVirtualName (\s a -> s { _ibdmsVirtualName = a }) instance FromXML InstanceBlockDeviceMappingSpecification where parseXML x = InstanceBlockDeviceMappingSpecification <$> x .@? "deviceName" <*> x .@? "ebs" <*> x .@? "noDevice" <*> x .@? "virtualName" instance ToQuery InstanceBlockDeviceMappingSpecification where toQuery InstanceBlockDeviceMappingSpecification{..} = mconcat [ "DeviceName" =? _ibdmsDeviceName , "Ebs" =? _ibdmsEbs , "NoDevice" =? _ibdmsNoDevice , "VirtualName" =? _ibdmsVirtualName ] data ExportEnvironment = Citrix -- ^ citrix | Microsoft -- ^ microsoft | Vmware -- ^ vmware deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ExportEnvironment instance FromText ExportEnvironment where parser = takeLowerText >>= \case "citrix" -> pure Citrix "microsoft" -> pure Microsoft "vmware" -> pure Vmware e -> fail $ "Failure parsing ExportEnvironment from " ++ show e instance ToText ExportEnvironment where toText = \case Citrix -> "citrix" Microsoft -> "microsoft" Vmware -> "vmware" instance ToByteString ExportEnvironment instance ToHeader ExportEnvironment instance ToQuery ExportEnvironment instance FromXML ExportEnvironment where parseXML = parseXMLText "ExportEnvironment" newtype UserData = UserData { _udData :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'UserData' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'udData' @::@ 'Maybe' 'Text' -- userData :: UserData userData = UserData { _udData = Nothing } udData :: Lens' UserData (Maybe Text) udData = lens _udData (\s a -> s { _udData = a }) instance FromXML UserData where parseXML x = UserData <$> x .@? "data" instance ToQuery UserData where toQuery UserData{..} = mconcat [ "Data" =? _udData ] data VolumeAttachment = VolumeAttachment { _vaAttachTime :: Maybe ISO8601 , _vaDeleteOnTermination :: Maybe Bool , _vaDevice :: Maybe Text , _vaInstanceId :: Maybe Text , _vaState :: Maybe VolumeAttachmentState , _vaVolumeId :: Maybe Text } deriving (Eq, Read, Show) -- | 'VolumeAttachment' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vaAttachTime' @::@ 'Maybe' 'UTCTime' -- -- * 'vaDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'vaDevice' @::@ 'Maybe' 'Text' -- -- * 'vaInstanceId' @::@ 'Maybe' 'Text' -- -- * 'vaState' @::@ 'Maybe' 'VolumeAttachmentState' -- -- * 'vaVolumeId' @::@ 'Maybe' 'Text' -- volumeAttachment :: VolumeAttachment volumeAttachment = VolumeAttachment { _vaVolumeId = Nothing , _vaInstanceId = Nothing , _vaDevice = Nothing , _vaState = Nothing , _vaAttachTime = Nothing , _vaDeleteOnTermination = Nothing } -- | The time stamp when the attachment initiated. vaAttachTime :: Lens' VolumeAttachment (Maybe UTCTime) vaAttachTime = lens _vaAttachTime (\s a -> s { _vaAttachTime = a }) . mapping _Time -- | Indicates whether the Amazon EBS volume is deleted on instance termination. vaDeleteOnTermination :: Lens' VolumeAttachment (Maybe Bool) vaDeleteOnTermination = lens _vaDeleteOnTermination (\s a -> s { _vaDeleteOnTermination = a }) -- | The device name. vaDevice :: Lens' VolumeAttachment (Maybe Text) vaDevice = lens _vaDevice (\s a -> s { _vaDevice = a }) -- | The ID of the instance. vaInstanceId :: Lens' VolumeAttachment (Maybe Text) vaInstanceId = lens _vaInstanceId (\s a -> s { _vaInstanceId = a }) -- | The attachment state of the volume. vaState :: Lens' VolumeAttachment (Maybe VolumeAttachmentState) vaState = lens _vaState (\s a -> s { _vaState = a }) -- | The ID of the volume. vaVolumeId :: Lens' VolumeAttachment (Maybe Text) vaVolumeId = lens _vaVolumeId (\s a -> s { _vaVolumeId = a }) instance FromXML VolumeAttachment where parseXML x = VolumeAttachment <$> x .@? "attachTime" <*> x .@? "deleteOnTermination" <*> x .@? "device" <*> x .@? "instanceId" <*> x .@? "status" <*> x .@? "volumeId" instance ToQuery VolumeAttachment where toQuery VolumeAttachment{..} = mconcat [ "AttachTime" =? _vaAttachTime , "DeleteOnTermination" =? _vaDeleteOnTermination , "Device" =? _vaDevice , "InstanceId" =? _vaInstanceId , "Status" =? _vaState , "VolumeId" =? _vaVolumeId ] data CustomerGateway = CustomerGateway { _cgBgpAsn :: Text , _cgCustomerGatewayId :: Text , _cgIpAddress :: Text , _cgState :: Text , _cgTags :: List "item" Tag , _cgType :: Text } deriving (Eq, Read, Show) -- | 'CustomerGateway' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cgBgpAsn' @::@ 'Text' -- -- * 'cgCustomerGatewayId' @::@ 'Text' -- -- * 'cgIpAddress' @::@ 'Text' -- -- * 'cgState' @::@ 'Text' -- -- * 'cgTags' @::@ ['Tag'] -- -- * 'cgType' @::@ 'Text' -- customerGateway :: Text -- ^ 'cgCustomerGatewayId' -> Text -- ^ 'cgState' -> Text -- ^ 'cgType' -> Text -- ^ 'cgIpAddress' -> Text -- ^ 'cgBgpAsn' -> CustomerGateway customerGateway p1 p2 p3 p4 p5 = CustomerGateway { _cgCustomerGatewayId = p1 , _cgState = p2 , _cgType = p3 , _cgIpAddress = p4 , _cgBgpAsn = p5 , _cgTags = mempty } -- | The customer gateway's Border Gateway Protocol (BGP) Autonomous System Number -- (ASN). cgBgpAsn :: Lens' CustomerGateway Text cgBgpAsn = lens _cgBgpAsn (\s a -> s { _cgBgpAsn = a }) -- | The ID of the customer gateway. cgCustomerGatewayId :: Lens' CustomerGateway Text cgCustomerGatewayId = lens _cgCustomerGatewayId (\s a -> s { _cgCustomerGatewayId = a }) -- | The Internet-routable IP address of the customer gateway's outside interface. cgIpAddress :: Lens' CustomerGateway Text cgIpAddress = lens _cgIpAddress (\s a -> s { _cgIpAddress = a }) -- | The current state of the customer gateway ('pending | available | deleting |deleted'). cgState :: Lens' CustomerGateway Text cgState = lens _cgState (\s a -> s { _cgState = a }) -- | Any tags assigned to the customer gateway. cgTags :: Lens' CustomerGateway [Tag] cgTags = lens _cgTags (\s a -> s { _cgTags = a }) . _List -- | The type of VPN connection the customer gateway supports ('ipsec.1'). cgType :: Lens' CustomerGateway Text cgType = lens _cgType (\s a -> s { _cgType = a }) instance FromXML CustomerGateway where parseXML x = CustomerGateway <$> x .@ "bgpAsn" <*> x .@ "customerGatewayId" <*> x .@ "ipAddress" <*> x .@ "state" <*> x .@? "tagSet" .!@ mempty <*> x .@ "type" instance ToQuery CustomerGateway where toQuery CustomerGateway{..} = mconcat [ "BgpAsn" =? _cgBgpAsn , "CustomerGatewayId" =? _cgCustomerGatewayId , "IpAddress" =? _cgIpAddress , "State" =? _cgState , "TagSet" `toQueryList` _cgTags , "Type" =? _cgType ] data EbsInstanceBlockDevice = EbsInstanceBlockDevice { _eibdAttachTime :: Maybe ISO8601 , _eibdDeleteOnTermination :: Maybe Bool , _eibdStatus :: Maybe AttachmentStatus , _eibdVolumeId :: Maybe Text } deriving (Eq, Read, Show) -- | 'EbsInstanceBlockDevice' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'eibdAttachTime' @::@ 'Maybe' 'UTCTime' -- -- * 'eibdDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'eibdStatus' @::@ 'Maybe' 'AttachmentStatus' -- -- * 'eibdVolumeId' @::@ 'Maybe' 'Text' -- ebsInstanceBlockDevice :: EbsInstanceBlockDevice ebsInstanceBlockDevice = EbsInstanceBlockDevice { _eibdVolumeId = Nothing , _eibdStatus = Nothing , _eibdAttachTime = Nothing , _eibdDeleteOnTermination = Nothing } -- | The time stamp when the attachment initiated. eibdAttachTime :: Lens' EbsInstanceBlockDevice (Maybe UTCTime) eibdAttachTime = lens _eibdAttachTime (\s a -> s { _eibdAttachTime = a }) . mapping _Time -- | Indicates whether the volume is deleted on instance termination. eibdDeleteOnTermination :: Lens' EbsInstanceBlockDevice (Maybe Bool) eibdDeleteOnTermination = lens _eibdDeleteOnTermination (\s a -> s { _eibdDeleteOnTermination = a }) -- | The attachment state. eibdStatus :: Lens' EbsInstanceBlockDevice (Maybe AttachmentStatus) eibdStatus = lens _eibdStatus (\s a -> s { _eibdStatus = a }) -- | The ID of the Amazon EBS volume. eibdVolumeId :: Lens' EbsInstanceBlockDevice (Maybe Text) eibdVolumeId = lens _eibdVolumeId (\s a -> s { _eibdVolumeId = a }) instance FromXML EbsInstanceBlockDevice where parseXML x = EbsInstanceBlockDevice <$> x .@? "attachTime" <*> x .@? "deleteOnTermination" <*> x .@? "status" <*> x .@? "volumeId" instance ToQuery EbsInstanceBlockDevice where toQuery EbsInstanceBlockDevice{..} = mconcat [ "AttachTime" =? _eibdAttachTime , "DeleteOnTermination" =? _eibdDeleteOnTermination , "Status" =? _eibdStatus , "VolumeId" =? _eibdVolumeId ] data ShutdownBehavior = Stop -- ^ stop | Terminate -- ^ terminate deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ShutdownBehavior instance FromText ShutdownBehavior where parser = takeLowerText >>= \case "stop" -> pure Stop "terminate" -> pure Terminate e -> fail $ "Failure parsing ShutdownBehavior from " ++ show e instance ToText ShutdownBehavior where toText = \case Stop -> "stop" Terminate -> "terminate" instance ToByteString ShutdownBehavior instance ToHeader ShutdownBehavior instance ToQuery ShutdownBehavior instance FromXML ShutdownBehavior where parseXML = parseXMLText "ShutdownBehavior" data DiskImageDescription = DiskImageDescription { _did1Checksum :: Maybe Text , _did1Format :: DiskImageFormat , _did1ImportManifestUrl :: Text , _did1Size :: Integer } deriving (Eq, Read, Show) -- | 'DiskImageDescription' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'did1Checksum' @::@ 'Maybe' 'Text' -- -- * 'did1Format' @::@ 'DiskImageFormat' -- -- * 'did1ImportManifestUrl' @::@ 'Text' -- -- * 'did1Size' @::@ 'Integer' -- diskImageDescription :: DiskImageFormat -- ^ 'did1Format' -> Integer -- ^ 'did1Size' -> Text -- ^ 'did1ImportManifestUrl' -> DiskImageDescription diskImageDescription p1 p2 p3 = DiskImageDescription { _did1Format = p1 , _did1Size = p2 , _did1ImportManifestUrl = p3 , _did1Checksum = Nothing } -- | The checksum computed for the disk image. did1Checksum :: Lens' DiskImageDescription (Maybe Text) did1Checksum = lens _did1Checksum (\s a -> s { _did1Checksum = a }) -- | The disk image format. did1Format :: Lens' DiskImageDescription DiskImageFormat did1Format = lens _did1Format (\s a -> s { _did1Format = a }) -- | A presigned URL for the import manifest stored in Amazon S3. For information -- about creating a presigned URL for an Amazon S3 object, read the "Query -- String Request Authentication Alternative" section of the <http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html Authenticating RESTRequests> topic in the /Amazon Simple Storage Service Developer Guide/. did1ImportManifestUrl :: Lens' DiskImageDescription Text did1ImportManifestUrl = lens _did1ImportManifestUrl (\s a -> s { _did1ImportManifestUrl = a }) -- | The size of the disk image. did1Size :: Lens' DiskImageDescription Integer did1Size = lens _did1Size (\s a -> s { _did1Size = a }) instance FromXML DiskImageDescription where parseXML x = DiskImageDescription <$> x .@? "checksum" <*> x .@ "format" <*> x .@ "importManifestUrl" <*> x .@ "size" instance ToQuery DiskImageDescription where toQuery DiskImageDescription{..} = mconcat [ "Checksum" =? _did1Checksum , "Format" =? _did1Format , "ImportManifestUrl" =? _did1ImportManifestUrl , "Size" =? _did1Size ] data DiskImageVolumeDescription = DiskImageVolumeDescription { _divdId :: Text , _divdSize :: Maybe Integer } deriving (Eq, Ord, Read, Show) -- | 'DiskImageVolumeDescription' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'divdId' @::@ 'Text' -- -- * 'divdSize' @::@ 'Maybe' 'Integer' -- diskImageVolumeDescription :: Text -- ^ 'divdId' -> DiskImageVolumeDescription diskImageVolumeDescription p1 = DiskImageVolumeDescription { _divdId = p1 , _divdSize = Nothing } -- | The volume identifier. divdId :: Lens' DiskImageVolumeDescription Text divdId = lens _divdId (\s a -> s { _divdId = a }) -- | The size of the volume. divdSize :: Lens' DiskImageVolumeDescription (Maybe Integer) divdSize = lens _divdSize (\s a -> s { _divdSize = a }) instance FromXML DiskImageVolumeDescription where parseXML x = DiskImageVolumeDescription <$> x .@ "id" <*> x .@? "size" instance ToQuery DiskImageVolumeDescription where toQuery DiskImageVolumeDescription{..} = mconcat [ "Id" =? _divdId , "Size" =? _divdSize ] newtype Monitoring = Monitoring { _mState :: Maybe MonitoringState } deriving (Eq, Read, Show) -- | 'Monitoring' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'mState' @::@ 'Maybe' 'MonitoringState' -- monitoring :: Monitoring monitoring = Monitoring { _mState = Nothing } -- | Indicates whether monitoring is enabled for the instance. mState :: Lens' Monitoring (Maybe MonitoringState) mState = lens _mState (\s a -> s { _mState = a }) instance FromXML Monitoring where parseXML x = Monitoring <$> x .@? "state" instance ToQuery Monitoring where toQuery Monitoring{..} = mconcat [ "State" =? _mState ] data SubnetState = SSAvailable -- ^ available | SSPending -- ^ pending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SubnetState instance FromText SubnetState where parser = takeLowerText >>= \case "available" -> pure SSAvailable "pending" -> pure SSPending e -> fail $ "Failure parsing SubnetState from " ++ show e instance ToText SubnetState where toText = \case SSAvailable -> "available" SSPending -> "pending" instance ToByteString SubnetState instance ToHeader SubnetState instance ToQuery SubnetState instance FromXML SubnetState where parseXML = parseXMLText "SubnetState" data ContainerFormat = Ova -- ^ ova deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ContainerFormat instance FromText ContainerFormat where parser = takeLowerText >>= \case "ova" -> pure Ova e -> fail $ "Failure parsing ContainerFormat from " ++ show e instance ToText ContainerFormat where toText Ova = "ova" instance ToByteString ContainerFormat instance ToHeader ContainerFormat instance ToQuery ContainerFormat instance FromXML ContainerFormat where parseXML = parseXMLText "ContainerFormat" newtype AvailabilityZoneMessage = AvailabilityZoneMessage { _azmMessage :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'AvailabilityZoneMessage' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'azmMessage' @::@ 'Maybe' 'Text' -- availabilityZoneMessage :: AvailabilityZoneMessage availabilityZoneMessage = AvailabilityZoneMessage { _azmMessage = Nothing } -- | The message about the Availability Zone. azmMessage :: Lens' AvailabilityZoneMessage (Maybe Text) azmMessage = lens _azmMessage (\s a -> s { _azmMessage = a }) instance FromXML AvailabilityZoneMessage where parseXML x = AvailabilityZoneMessage <$> x .@? "message" instance ToQuery AvailabilityZoneMessage where toQuery AvailabilityZoneMessage{..} = mconcat [ "Message" =? _azmMessage ] data VpcAttachment = VpcAttachment { _va1State :: Maybe AttachmentStatus , _va1VpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'VpcAttachment' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'va1State' @::@ 'Maybe' 'AttachmentStatus' -- -- * 'va1VpcId' @::@ 'Maybe' 'Text' -- vpcAttachment :: VpcAttachment vpcAttachment = VpcAttachment { _va1VpcId = Nothing , _va1State = Nothing } -- | The current state of the attachment. va1State :: Lens' VpcAttachment (Maybe AttachmentStatus) va1State = lens _va1State (\s a -> s { _va1State = a }) -- | The ID of the VPC. va1VpcId :: Lens' VpcAttachment (Maybe Text) va1VpcId = lens _va1VpcId (\s a -> s { _va1VpcId = a }) instance FromXML VpcAttachment where parseXML x = VpcAttachment <$> x .@? "state" <*> x .@? "vpcId" instance ToQuery VpcAttachment where toQuery VpcAttachment{..} = mconcat [ "State" =? _va1State , "VpcId" =? _va1VpcId ] data InstanceBlockDeviceMapping = InstanceBlockDeviceMapping { _ibdmDeviceName :: Maybe Text , _ibdmEbs :: Maybe EbsInstanceBlockDevice } deriving (Eq, Read, Show) -- | 'InstanceBlockDeviceMapping' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ibdmDeviceName' @::@ 'Maybe' 'Text' -- -- * 'ibdmEbs' @::@ 'Maybe' 'EbsInstanceBlockDevice' -- instanceBlockDeviceMapping :: InstanceBlockDeviceMapping instanceBlockDeviceMapping = InstanceBlockDeviceMapping { _ibdmDeviceName = Nothing , _ibdmEbs = Nothing } -- | The device name exposed to the instance (for example, '/dev/sdh' or 'xvdh'). ibdmDeviceName :: Lens' InstanceBlockDeviceMapping (Maybe Text) ibdmDeviceName = lens _ibdmDeviceName (\s a -> s { _ibdmDeviceName = a }) -- | Parameters used to automatically set up Amazon EBS volumes when the instance -- is launched. ibdmEbs :: Lens' InstanceBlockDeviceMapping (Maybe EbsInstanceBlockDevice) ibdmEbs = lens _ibdmEbs (\s a -> s { _ibdmEbs = a }) instance FromXML InstanceBlockDeviceMapping where parseXML x = InstanceBlockDeviceMapping <$> x .@? "deviceName" <*> x .@? "ebs" instance ToQuery InstanceBlockDeviceMapping where toQuery InstanceBlockDeviceMapping{..} = mconcat [ "DeviceName" =? _ibdmDeviceName , "Ebs" =? _ibdmEbs ] data StatusType = Failed -- ^ failed | InsufficientData -- ^ insufficient-data | Passed -- ^ passed deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable StatusType instance FromText StatusType where parser = takeLowerText >>= \case "failed" -> pure Failed "insufficient-data" -> pure InsufficientData "passed" -> pure Passed e -> fail $ "Failure parsing StatusType from " ++ show e instance ToText StatusType where toText = \case Failed -> "failed" InsufficientData -> "insufficient-data" Passed -> "passed" instance ToByteString StatusType instance ToHeader StatusType instance ToQuery StatusType instance FromXML StatusType where parseXML = parseXMLText "StatusType" data ExportToS3TaskSpecification = ExportToS3TaskSpecification { _etstsContainerFormat :: Maybe ContainerFormat , _etstsDiskImageFormat :: Maybe DiskImageFormat , _etstsS3Bucket :: Maybe Text , _etstsS3Prefix :: Maybe Text } deriving (Eq, Read, Show) -- | 'ExportToS3TaskSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'etstsContainerFormat' @::@ 'Maybe' 'ContainerFormat' -- -- * 'etstsDiskImageFormat' @::@ 'Maybe' 'DiskImageFormat' -- -- * 'etstsS3Bucket' @::@ 'Maybe' 'Text' -- -- * 'etstsS3Prefix' @::@ 'Maybe' 'Text' -- exportToS3TaskSpecification :: ExportToS3TaskSpecification exportToS3TaskSpecification = ExportToS3TaskSpecification { _etstsDiskImageFormat = Nothing , _etstsContainerFormat = Nothing , _etstsS3Bucket = Nothing , _etstsS3Prefix = Nothing } etstsContainerFormat :: Lens' ExportToS3TaskSpecification (Maybe ContainerFormat) etstsContainerFormat = lens _etstsContainerFormat (\s a -> s { _etstsContainerFormat = a }) etstsDiskImageFormat :: Lens' ExportToS3TaskSpecification (Maybe DiskImageFormat) etstsDiskImageFormat = lens _etstsDiskImageFormat (\s a -> s { _etstsDiskImageFormat = a }) etstsS3Bucket :: Lens' ExportToS3TaskSpecification (Maybe Text) etstsS3Bucket = lens _etstsS3Bucket (\s a -> s { _etstsS3Bucket = a }) -- | The image is written to a single object in the Amazon S3 bucket at the S3 key -- s3prefix + exportTaskId + '.' + diskImageFormat. etstsS3Prefix :: Lens' ExportToS3TaskSpecification (Maybe Text) etstsS3Prefix = lens _etstsS3Prefix (\s a -> s { _etstsS3Prefix = a }) instance FromXML ExportToS3TaskSpecification where parseXML x = ExportToS3TaskSpecification <$> x .@? "containerFormat" <*> x .@? "diskImageFormat" <*> x .@? "s3Bucket" <*> x .@? "s3Prefix" instance ToQuery ExportToS3TaskSpecification where toQuery ExportToS3TaskSpecification{..} = mconcat [ "ContainerFormat" =? _etstsContainerFormat , "DiskImageFormat" =? _etstsDiskImageFormat , "S3Bucket" =? _etstsS3Bucket , "S3Prefix" =? _etstsS3Prefix ] data NetworkInterfaceAttribute = Attachment -- ^ attachment | Description -- ^ description | GroupSet -- ^ groupSet | SourceDestCheck -- ^ sourceDestCheck deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable NetworkInterfaceAttribute instance FromText NetworkInterfaceAttribute where parser = takeLowerText >>= \case "attachment" -> pure Attachment "description" -> pure Description "groupset" -> pure GroupSet "sourcedestcheck" -> pure SourceDestCheck e -> fail $ "Failure parsing NetworkInterfaceAttribute from " ++ show e instance ToText NetworkInterfaceAttribute where toText = \case Attachment -> "attachment" Description -> "description" GroupSet -> "groupSet" SourceDestCheck -> "sourceDestCheck" instance ToByteString NetworkInterfaceAttribute instance ToHeader NetworkInterfaceAttribute instance ToQuery NetworkInterfaceAttribute instance FromXML NetworkInterfaceAttribute where parseXML = parseXMLText "NetworkInterfaceAttribute" data ImageTypeValues = Kernel -- ^ kernel | Machine -- ^ machine | Ramdisk -- ^ ramdisk deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ImageTypeValues instance FromText ImageTypeValues where parser = takeLowerText >>= \case "kernel" -> pure Kernel "machine" -> pure Machine "ramdisk" -> pure Ramdisk e -> fail $ "Failure parsing ImageTypeValues from " ++ show e instance ToText ImageTypeValues where toText = \case Kernel -> "kernel" Machine -> "machine" Ramdisk -> "ramdisk" instance ToByteString ImageTypeValues instance ToHeader ImageTypeValues instance ToQuery ImageTypeValues instance FromXML ImageTypeValues where parseXML = parseXMLText "ImageTypeValues" data InstanceExportDetails = InstanceExportDetails { _iedInstanceId :: Maybe Text , _iedTargetEnvironment :: Maybe ExportEnvironment } deriving (Eq, Read, Show) -- | 'InstanceExportDetails' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iedInstanceId' @::@ 'Maybe' 'Text' -- -- * 'iedTargetEnvironment' @::@ 'Maybe' 'ExportEnvironment' -- instanceExportDetails :: InstanceExportDetails instanceExportDetails = InstanceExportDetails { _iedInstanceId = Nothing , _iedTargetEnvironment = Nothing } -- | The ID of the resource being exported. iedInstanceId :: Lens' InstanceExportDetails (Maybe Text) iedInstanceId = lens _iedInstanceId (\s a -> s { _iedInstanceId = a }) -- | The target virtualization environment. iedTargetEnvironment :: Lens' InstanceExportDetails (Maybe ExportEnvironment) iedTargetEnvironment = lens _iedTargetEnvironment (\s a -> s { _iedTargetEnvironment = a }) instance FromXML InstanceExportDetails where parseXML x = InstanceExportDetails <$> x .@? "instanceId" <*> x .@? "targetEnvironment" instance ToQuery InstanceExportDetails where toQuery InstanceExportDetails{..} = mconcat [ "InstanceId" =? _iedInstanceId , "TargetEnvironment" =? _iedTargetEnvironment ] data SnapshotAttributeName = SANCreateVolumePermission -- ^ createVolumePermission | SANProductCodes -- ^ productCodes deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SnapshotAttributeName instance FromText SnapshotAttributeName where parser = takeLowerText >>= \case "createvolumepermission" -> pure SANCreateVolumePermission "productcodes" -> pure SANProductCodes e -> fail $ "Failure parsing SnapshotAttributeName from " ++ show e instance ToText SnapshotAttributeName where toText = \case SANCreateVolumePermission -> "createVolumePermission" SANProductCodes -> "productCodes" instance ToByteString SnapshotAttributeName instance ToHeader SnapshotAttributeName instance ToQuery SnapshotAttributeName instance FromXML SnapshotAttributeName where parseXML = parseXMLText "SnapshotAttributeName" data AvailabilityZone = AvailabilityZone { _azMessages :: List "item" AvailabilityZoneMessage , _azRegionName :: Maybe Text , _azState :: Maybe AvailabilityZoneState , _azZoneName :: Maybe Text } deriving (Eq, Read, Show) -- | 'AvailabilityZone' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'azMessages' @::@ ['AvailabilityZoneMessage'] -- -- * 'azRegionName' @::@ 'Maybe' 'Text' -- -- * 'azState' @::@ 'Maybe' 'AvailabilityZoneState' -- -- * 'azZoneName' @::@ 'Maybe' 'Text' -- availabilityZone :: AvailabilityZone availabilityZone = AvailabilityZone { _azZoneName = Nothing , _azState = Nothing , _azRegionName = Nothing , _azMessages = mempty } -- | Any messages about the Availability Zone. azMessages :: Lens' AvailabilityZone [AvailabilityZoneMessage] azMessages = lens _azMessages (\s a -> s { _azMessages = a }) . _List -- | The name of the region. azRegionName :: Lens' AvailabilityZone (Maybe Text) azRegionName = lens _azRegionName (\s a -> s { _azRegionName = a }) -- | The state of the Availability Zone ('available' | 'impaired' | 'unavailable'). azState :: Lens' AvailabilityZone (Maybe AvailabilityZoneState) azState = lens _azState (\s a -> s { _azState = a }) -- | The name of the Availability Zone. azZoneName :: Lens' AvailabilityZone (Maybe Text) azZoneName = lens _azZoneName (\s a -> s { _azZoneName = a }) instance FromXML AvailabilityZone where parseXML x = AvailabilityZone <$> x .@? "messageSet" .!@ mempty <*> x .@? "regionName" <*> x .@? "zoneState" <*> x .@? "zoneName" instance ToQuery AvailabilityZone where toQuery AvailabilityZone{..} = mconcat [ "MessageSet" `toQueryList` _azMessages , "RegionName" =? _azRegionName , "ZoneState" =? _azState , "ZoneName" =? _azZoneName ] data VpnState = VpnStateAvailable -- ^ available | VpnStateDeleted -- ^ deleted | VpnStateDeleting -- ^ deleting | VpnStatePending -- ^ pending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VpnState instance FromText VpnState where parser = takeLowerText >>= \case "available" -> pure VpnStateAvailable "deleted" -> pure VpnStateDeleted "deleting" -> pure VpnStateDeleting "pending" -> pure VpnStatePending e -> fail $ "Failure parsing VpnState from " ++ show e instance ToText VpnState where toText = \case VpnStateAvailable -> "available" VpnStateDeleted -> "deleted" VpnStateDeleting -> "deleting" VpnStatePending -> "pending" instance ToByteString VpnState instance ToHeader VpnState instance ToQuery VpnState instance FromXML VpnState where parseXML = parseXMLText "VpnState" data RouteTable = RouteTable { _rtAssociations :: List "item" RouteTableAssociation , _rtPropagatingVgws :: List "item" PropagatingVgw , _rtRouteTableId :: Maybe Text , _rtRoutes :: List "item" Route , _rtTags :: List "item" Tag , _rtVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'RouteTable' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rtAssociations' @::@ ['RouteTableAssociation'] -- -- * 'rtPropagatingVgws' @::@ ['PropagatingVgw'] -- -- * 'rtRouteTableId' @::@ 'Maybe' 'Text' -- -- * 'rtRoutes' @::@ ['Route'] -- -- * 'rtTags' @::@ ['Tag'] -- -- * 'rtVpcId' @::@ 'Maybe' 'Text' -- routeTable :: RouteTable routeTable = RouteTable { _rtRouteTableId = Nothing , _rtVpcId = Nothing , _rtRoutes = mempty , _rtAssociations = mempty , _rtTags = mempty , _rtPropagatingVgws = mempty } -- | The associations between the route table and one or more subnets. rtAssociations :: Lens' RouteTable [RouteTableAssociation] rtAssociations = lens _rtAssociations (\s a -> s { _rtAssociations = a }) . _List -- | Any virtual private gateway (VGW) propagating routes. rtPropagatingVgws :: Lens' RouteTable [PropagatingVgw] rtPropagatingVgws = lens _rtPropagatingVgws (\s a -> s { _rtPropagatingVgws = a }) . _List -- | The ID of the route table. rtRouteTableId :: Lens' RouteTable (Maybe Text) rtRouteTableId = lens _rtRouteTableId (\s a -> s { _rtRouteTableId = a }) -- | The routes in the route table. rtRoutes :: Lens' RouteTable [Route] rtRoutes = lens _rtRoutes (\s a -> s { _rtRoutes = a }) . _List -- | Any tags assigned to the route table. rtTags :: Lens' RouteTable [Tag] rtTags = lens _rtTags (\s a -> s { _rtTags = a }) . _List -- | The ID of the VPC. rtVpcId :: Lens' RouteTable (Maybe Text) rtVpcId = lens _rtVpcId (\s a -> s { _rtVpcId = a }) instance FromXML RouteTable where parseXML x = RouteTable <$> x .@? "associationSet" .!@ mempty <*> x .@? "propagatingVgwSet" .!@ mempty <*> x .@? "routeTableId" <*> x .@? "routeSet" .!@ mempty <*> x .@? "tagSet" .!@ mempty <*> x .@? "vpcId" instance ToQuery RouteTable where toQuery RouteTable{..} = mconcat [ "AssociationSet" `toQueryList` _rtAssociations , "PropagatingVgwSet" `toQueryList` _rtPropagatingVgws , "RouteTableId" =? _rtRouteTableId , "RouteSet" `toQueryList` _rtRoutes , "TagSet" `toQueryList` _rtTags , "VpcId" =? _rtVpcId ] data HypervisorType = Ovm -- ^ ovm | Xen -- ^ xen deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable HypervisorType instance FromText HypervisorType where parser = takeLowerText >>= \case "ovm" -> pure Ovm "xen" -> pure Xen e -> fail $ "Failure parsing HypervisorType from " ++ show e instance ToText HypervisorType where toText = \case Ovm -> "ovm" Xen -> "xen" instance ToByteString HypervisorType instance ToHeader HypervisorType instance ToQuery HypervisorType instance FromXML HypervisorType where parseXML = parseXMLText "HypervisorType" data InstanceStatusDetails = InstanceStatusDetails { _isdImpairedSince :: Maybe ISO8601 , _isdName :: Maybe StatusName , _isdStatus :: Maybe StatusType } deriving (Eq, Read, Show) -- | 'InstanceStatusDetails' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'isdImpairedSince' @::@ 'Maybe' 'UTCTime' -- -- * 'isdName' @::@ 'Maybe' 'StatusName' -- -- * 'isdStatus' @::@ 'Maybe' 'StatusType' -- instanceStatusDetails :: InstanceStatusDetails instanceStatusDetails = InstanceStatusDetails { _isdName = Nothing , _isdStatus = Nothing , _isdImpairedSince = Nothing } -- | The time when a status check failed. For an instance that was launched and -- impaired, this is the time when the instance was launched. isdImpairedSince :: Lens' InstanceStatusDetails (Maybe UTCTime) isdImpairedSince = lens _isdImpairedSince (\s a -> s { _isdImpairedSince = a }) . mapping _Time -- | The type of instance status. isdName :: Lens' InstanceStatusDetails (Maybe StatusName) isdName = lens _isdName (\s a -> s { _isdName = a }) -- | The status. isdStatus :: Lens' InstanceStatusDetails (Maybe StatusType) isdStatus = lens _isdStatus (\s a -> s { _isdStatus = a }) instance FromXML InstanceStatusDetails where parseXML x = InstanceStatusDetails <$> x .@? "impairedSince" <*> x .@? "name" <*> x .@? "status" instance ToQuery InstanceStatusDetails where toQuery InstanceStatusDetails{..} = mconcat [ "ImpairedSince" =? _isdImpairedSince , "Name" =? _isdName , "Status" =? _isdStatus ] data IamInstanceProfile = IamInstanceProfile { _iipArn :: Maybe Text , _iipId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'IamInstanceProfile' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iipArn' @::@ 'Maybe' 'Text' -- -- * 'iipId' @::@ 'Maybe' 'Text' -- iamInstanceProfile :: IamInstanceProfile iamInstanceProfile = IamInstanceProfile { _iipArn = Nothing , _iipId = Nothing } -- | The Amazon Resource Name (ARN) of the instance profile. iipArn :: Lens' IamInstanceProfile (Maybe Text) iipArn = lens _iipArn (\s a -> s { _iipArn = a }) -- | The ID of the instance profile. iipId :: Lens' IamInstanceProfile (Maybe Text) iipId = lens _iipId (\s a -> s { _iipId = a }) instance FromXML IamInstanceProfile where parseXML x = IamInstanceProfile <$> x .@? "arn" <*> x .@? "id" instance ToQuery IamInstanceProfile where toQuery IamInstanceProfile{..} = mconcat [ "Arn" =? _iipArn , "Id" =? _iipId ] data InternetGatewayAttachment = InternetGatewayAttachment { _igaState :: AttachmentStatus , _igaVpcId :: Text } deriving (Eq, Read, Show) -- | 'InternetGatewayAttachment' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'igaState' @::@ 'AttachmentStatus' -- -- * 'igaVpcId' @::@ 'Text' -- internetGatewayAttachment :: Text -- ^ 'igaVpcId' -> AttachmentStatus -- ^ 'igaState' -> InternetGatewayAttachment internetGatewayAttachment p1 p2 = InternetGatewayAttachment { _igaVpcId = p1 , _igaState = p2 } -- | The current state of the attachment. igaState :: Lens' InternetGatewayAttachment AttachmentStatus igaState = lens _igaState (\s a -> s { _igaState = a }) -- | The ID of the VPC. igaVpcId :: Lens' InternetGatewayAttachment Text igaVpcId = lens _igaVpcId (\s a -> s { _igaVpcId = a }) instance FromXML InternetGatewayAttachment where parseXML x = InternetGatewayAttachment <$> x .@ "state" <*> x .@ "vpcId" instance ToQuery InternetGatewayAttachment where toQuery InternetGatewayAttachment{..} = mconcat [ "State" =? _igaState , "VpcId" =? _igaVpcId ] data ReservedInstanceState = RISActive -- ^ active | RISPaymentFailed -- ^ payment-failed | RISPaymentPending -- ^ payment-pending | RISRetired -- ^ retired deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ReservedInstanceState instance FromText ReservedInstanceState where parser = takeLowerText >>= \case "active" -> pure RISActive "payment-failed" -> pure RISPaymentFailed "payment-pending" -> pure RISPaymentPending "retired" -> pure RISRetired e -> fail $ "Failure parsing ReservedInstanceState from " ++ show e instance ToText ReservedInstanceState where toText = \case RISActive -> "active" RISPaymentFailed -> "payment-failed" RISPaymentPending -> "payment-pending" RISRetired -> "retired" instance ToByteString ReservedInstanceState instance ToHeader ReservedInstanceState instance ToQuery ReservedInstanceState instance FromXML ReservedInstanceState where parseXML = parseXMLText "ReservedInstanceState" data InstanceAttributeName = IANInstanceBlockDeviceMapping -- ^ blockDeviceMapping | IANInstanceDisableApiTermination -- ^ disableApiTermination | IANInstanceEbsOptimized -- ^ ebsOptimized | IANInstanceGroupSet -- ^ groupSet | IANInstanceInstanceInitiatedShutdownBehavior -- ^ instanceInitiatedShutdownBehavior | IANInstanceInstanceType -- ^ instanceType | IANInstanceKernel -- ^ kernel | IANInstanceProductCodes -- ^ productCodes | IANInstanceRamdisk -- ^ ramdisk | IANInstanceRootDeviceName -- ^ rootDeviceName | IANInstanceSourceDestCheck -- ^ sourceDestCheck | IANInstanceSriovNetSupport -- ^ sriovNetSupport | IANInstanceUserData -- ^ userData deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable InstanceAttributeName instance FromText InstanceAttributeName where parser = takeLowerText >>= \case "blockdevicemapping" -> pure IANInstanceBlockDeviceMapping "disableapitermination" -> pure IANInstanceDisableApiTermination "ebsoptimized" -> pure IANInstanceEbsOptimized "groupset" -> pure IANInstanceGroupSet "instanceinitiatedshutdownbehavior" -> pure IANInstanceInstanceInitiatedShutdownBehavior "instancetype" -> pure IANInstanceInstanceType "kernel" -> pure IANInstanceKernel "productcodes" -> pure IANInstanceProductCodes "ramdisk" -> pure IANInstanceRamdisk "rootdevicename" -> pure IANInstanceRootDeviceName "sourcedestcheck" -> pure IANInstanceSourceDestCheck "sriovnetsupport" -> pure IANInstanceSriovNetSupport "userdata" -> pure IANInstanceUserData e -> fail $ "Failure parsing InstanceAttributeName from " ++ show e instance ToText InstanceAttributeName where toText = \case IANInstanceBlockDeviceMapping -> "blockDeviceMapping" IANInstanceDisableApiTermination -> "disableApiTermination" IANInstanceEbsOptimized -> "ebsOptimized" IANInstanceGroupSet -> "groupSet" IANInstanceInstanceInitiatedShutdownBehavior -> "instanceInitiatedShutdownBehavior" IANInstanceInstanceType -> "instanceType" IANInstanceKernel -> "kernel" IANInstanceProductCodes -> "productCodes" IANInstanceRamdisk -> "ramdisk" IANInstanceRootDeviceName -> "rootDeviceName" IANInstanceSourceDestCheck -> "sourceDestCheck" IANInstanceSriovNetSupport -> "sriovNetSupport" IANInstanceUserData -> "userData" instance ToByteString InstanceAttributeName instance ToHeader InstanceAttributeName instance ToQuery InstanceAttributeName instance FromXML InstanceAttributeName where parseXML = parseXMLText "InstanceAttributeName" data IpPermission = IpPermission { _ipFromPort :: Maybe Int , _ipIpProtocol :: Text , _ipIpRanges :: List "item" IpRange , _ipToPort :: Maybe Int , _ipUserIdGroupPairs :: List "item" UserIdGroupPair } deriving (Eq, Read, Show) -- | 'IpPermission' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ipFromPort' @::@ 'Maybe' 'Int' -- -- * 'ipIpProtocol' @::@ 'Text' -- -- * 'ipIpRanges' @::@ ['IpRange'] -- -- * 'ipToPort' @::@ 'Maybe' 'Int' -- -- * 'ipUserIdGroupPairs' @::@ ['UserIdGroupPair'] -- ipPermission :: Text -- ^ 'ipIpProtocol' -> IpPermission ipPermission p1 = IpPermission { _ipIpProtocol = p1 , _ipFromPort = Nothing , _ipToPort = Nothing , _ipUserIdGroupPairs = mempty , _ipIpRanges = mempty } -- | The start of port range for the TCP and UDP protocols, or an ICMP type -- number. A value of '-1' indicates all ICMP types. ipFromPort :: Lens' IpPermission (Maybe Int) ipFromPort = lens _ipFromPort (\s a -> s { _ipFromPort = a }) -- | The protocol. -- -- When you call 'DescribeSecurityGroups', the protocol value returned is the -- number. Exception: For TCP, UDP, and ICMP, the value returned is the name -- (for example, 'tcp', 'udp', or 'icmp'). For a list of protocol numbers, see <http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml Protocol Numbers>. (VPC only) When you call 'AuthorizeSecurityGroupIngress', you can use '-1' to -- specify all. ipIpProtocol :: Lens' IpPermission Text ipIpProtocol = lens _ipIpProtocol (\s a -> s { _ipIpProtocol = a }) -- | One or more IP ranges. ipIpRanges :: Lens' IpPermission [IpRange] ipIpRanges = lens _ipIpRanges (\s a -> s { _ipIpRanges = a }) . _List -- | The end of port range for the TCP and UDP protocols, or an ICMP code. A value -- of '-1' indicates all ICMP codes for the specified ICMP type. ipToPort :: Lens' IpPermission (Maybe Int) ipToPort = lens _ipToPort (\s a -> s { _ipToPort = a }) -- | One or more security group and AWS account ID pairs. ipUserIdGroupPairs :: Lens' IpPermission [UserIdGroupPair] ipUserIdGroupPairs = lens _ipUserIdGroupPairs (\s a -> s { _ipUserIdGroupPairs = a }) . _List instance FromXML IpPermission where parseXML x = IpPermission <$> x .@? "fromPort" <*> x .@ "ipProtocol" <*> x .@? "ipRanges" .!@ mempty <*> x .@? "toPort" <*> x .@? "groups" .!@ mempty instance ToQuery IpPermission where toQuery IpPermission{..} = mconcat [ "FromPort" =? _ipFromPort , "IpProtocol" =? _ipIpProtocol , "IpRanges" `toQueryList` _ipIpRanges , "ToPort" =? _ipToPort , "Groups" `toQueryList` _ipUserIdGroupPairs ] data ConversionTaskState = CTSActive -- ^ active | CTSCancelled -- ^ cancelled | CTSCancelling -- ^ cancelling | CTSCompleted -- ^ completed deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ConversionTaskState instance FromText ConversionTaskState where parser = takeLowerText >>= \case "active" -> pure CTSActive "cancelled" -> pure CTSCancelled "cancelling" -> pure CTSCancelling "completed" -> pure CTSCompleted e -> fail $ "Failure parsing ConversionTaskState from " ++ show e instance ToText ConversionTaskState where toText = \case CTSActive -> "active" CTSCancelled -> "cancelled" CTSCancelling -> "cancelling" CTSCompleted -> "completed" instance ToByteString ConversionTaskState instance ToHeader ConversionTaskState instance ToQuery ConversionTaskState instance FromXML ConversionTaskState where parseXML = parseXMLText "ConversionTaskState" data DiskImage = DiskImage { _diDescription :: Maybe Text , _diImage :: Maybe DiskImageDetail , _diVolume :: Maybe VolumeDetail } deriving (Eq, Read, Show) -- | 'DiskImage' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'diDescription' @::@ 'Maybe' 'Text' -- -- * 'diImage' @::@ 'Maybe' 'DiskImageDetail' -- -- * 'diVolume' @::@ 'Maybe' 'VolumeDetail' -- diskImage :: DiskImage diskImage = DiskImage { _diImage = Nothing , _diDescription = Nothing , _diVolume = Nothing } diDescription :: Lens' DiskImage (Maybe Text) diDescription = lens _diDescription (\s a -> s { _diDescription = a }) diImage :: Lens' DiskImage (Maybe DiskImageDetail) diImage = lens _diImage (\s a -> s { _diImage = a }) diVolume :: Lens' DiskImage (Maybe VolumeDetail) diVolume = lens _diVolume (\s a -> s { _diVolume = a }) instance FromXML DiskImage where parseXML x = DiskImage <$> x .@? "Description" <*> x .@? "Image" <*> x .@? "Volume" instance ToQuery DiskImage where toQuery DiskImage{..} = mconcat [ "Description" =? _diDescription , "Image" =? _diImage , "Volume" =? _diVolume ] data Tenancy = Dedicated -- ^ dedicated | Default' -- ^ default deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable Tenancy instance FromText Tenancy where parser = takeLowerText >>= \case "dedicated" -> pure Dedicated "default" -> pure Default' e -> fail $ "Failure parsing Tenancy from " ++ show e instance ToText Tenancy where toText = \case Dedicated -> "dedicated" Default' -> "default" instance ToByteString Tenancy instance ToHeader Tenancy instance ToQuery Tenancy instance FromXML Tenancy where parseXML = parseXMLText "Tenancy" data VpcPeeringConnectionStateReason = VpcPeeringConnectionStateReason { _vpcsrCode :: Maybe Text , _vpcsrMessage :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'VpcPeeringConnectionStateReason' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vpcsrCode' @::@ 'Maybe' 'Text' -- -- * 'vpcsrMessage' @::@ 'Maybe' 'Text' -- vpcPeeringConnectionStateReason :: VpcPeeringConnectionStateReason vpcPeeringConnectionStateReason = VpcPeeringConnectionStateReason { _vpcsrCode = Nothing , _vpcsrMessage = Nothing } -- | The status of the VPC peering connection. vpcsrCode :: Lens' VpcPeeringConnectionStateReason (Maybe Text) vpcsrCode = lens _vpcsrCode (\s a -> s { _vpcsrCode = a }) -- | A message that provides more information about the status, if applicable. vpcsrMessage :: Lens' VpcPeeringConnectionStateReason (Maybe Text) vpcsrMessage = lens _vpcsrMessage (\s a -> s { _vpcsrMessage = a }) instance FromXML VpcPeeringConnectionStateReason where parseXML x = VpcPeeringConnectionStateReason <$> x .@? "code" <*> x .@? "message" instance ToQuery VpcPeeringConnectionStateReason where toQuery VpcPeeringConnectionStateReason{..} = mconcat [ "Code" =? _vpcsrCode , "Message" =? _vpcsrMessage ] data IamInstanceProfileSpecification = IamInstanceProfileSpecification { _iipsArn :: Maybe Text , _iipsName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'IamInstanceProfileSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iipsArn' @::@ 'Maybe' 'Text' -- -- * 'iipsName' @::@ 'Maybe' 'Text' -- iamInstanceProfileSpecification :: IamInstanceProfileSpecification iamInstanceProfileSpecification = IamInstanceProfileSpecification { _iipsArn = Nothing , _iipsName = Nothing } -- | The Amazon Resource Name (ARN) of the instance profile. iipsArn :: Lens' IamInstanceProfileSpecification (Maybe Text) iipsArn = lens _iipsArn (\s a -> s { _iipsArn = a }) -- | The name of the instance profile. iipsName :: Lens' IamInstanceProfileSpecification (Maybe Text) iipsName = lens _iipsName (\s a -> s { _iipsName = a }) instance FromXML IamInstanceProfileSpecification where parseXML x = IamInstanceProfileSpecification <$> x .@? "arn" <*> x .@? "name" instance ToQuery IamInstanceProfileSpecification where toQuery IamInstanceProfileSpecification{..} = mconcat [ "Arn" =? _iipsArn , "Name" =? _iipsName ] data ImportVolumeTaskDetails = ImportVolumeTaskDetails { _ivtdAvailabilityZone :: Text , _ivtdBytesConverted :: Integer , _ivtdDescription :: Maybe Text , _ivtdImage :: DiskImageDescription , _ivtdVolume :: DiskImageVolumeDescription } deriving (Eq, Read, Show) -- | 'ImportVolumeTaskDetails' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ivtdAvailabilityZone' @::@ 'Text' -- -- * 'ivtdBytesConverted' @::@ 'Integer' -- -- * 'ivtdDescription' @::@ 'Maybe' 'Text' -- -- * 'ivtdImage' @::@ 'DiskImageDescription' -- -- * 'ivtdVolume' @::@ 'DiskImageVolumeDescription' -- importVolumeTaskDetails :: Integer -- ^ 'ivtdBytesConverted' -> Text -- ^ 'ivtdAvailabilityZone' -> DiskImageDescription -- ^ 'ivtdImage' -> DiskImageVolumeDescription -- ^ 'ivtdVolume' -> ImportVolumeTaskDetails importVolumeTaskDetails p1 p2 p3 p4 = ImportVolumeTaskDetails { _ivtdBytesConverted = p1 , _ivtdAvailabilityZone = p2 , _ivtdImage = p3 , _ivtdVolume = p4 , _ivtdDescription = Nothing } -- | The Availability Zone where the resulting volume will reside. ivtdAvailabilityZone :: Lens' ImportVolumeTaskDetails Text ivtdAvailabilityZone = lens _ivtdAvailabilityZone (\s a -> s { _ivtdAvailabilityZone = a }) -- | The number of bytes converted so far. ivtdBytesConverted :: Lens' ImportVolumeTaskDetails Integer ivtdBytesConverted = lens _ivtdBytesConverted (\s a -> s { _ivtdBytesConverted = a }) -- | The description you provided when starting the import volume task. ivtdDescription :: Lens' ImportVolumeTaskDetails (Maybe Text) ivtdDescription = lens _ivtdDescription (\s a -> s { _ivtdDescription = a }) -- | The image. ivtdImage :: Lens' ImportVolumeTaskDetails DiskImageDescription ivtdImage = lens _ivtdImage (\s a -> s { _ivtdImage = a }) -- | The volume. ivtdVolume :: Lens' ImportVolumeTaskDetails DiskImageVolumeDescription ivtdVolume = lens _ivtdVolume (\s a -> s { _ivtdVolume = a }) instance FromXML ImportVolumeTaskDetails where parseXML x = ImportVolumeTaskDetails <$> x .@ "availabilityZone" <*> x .@ "bytesConverted" <*> x .@? "description" <*> x .@ "image" <*> x .@ "volume" instance ToQuery ImportVolumeTaskDetails where toQuery ImportVolumeTaskDetails{..} = mconcat [ "AvailabilityZone" =? _ivtdAvailabilityZone , "BytesConverted" =? _ivtdBytesConverted , "Description" =? _ivtdDescription , "Image" =? _ivtdImage , "Volume" =? _ivtdVolume ] data PlacementStrategy = Cluster -- ^ cluster deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable PlacementStrategy instance FromText PlacementStrategy where parser = takeLowerText >>= \case "cluster" -> pure Cluster e -> fail $ "Failure parsing PlacementStrategy from " ++ show e instance ToText PlacementStrategy where toText Cluster = "cluster" instance ToByteString PlacementStrategy instance ToHeader PlacementStrategy instance ToQuery PlacementStrategy instance FromXML PlacementStrategy where parseXML = parseXMLText "PlacementStrategy" data InstanceNetworkInterface = InstanceNetworkInterface { _iniAssociation :: Maybe InstanceNetworkInterfaceAssociation , _iniAttachment :: Maybe InstanceNetworkInterfaceAttachment , _iniDescription :: Maybe Text , _iniGroups :: List "item" GroupIdentifier , _iniMacAddress :: Maybe Text , _iniNetworkInterfaceId :: Maybe Text , _iniOwnerId :: Maybe Text , _iniPrivateDnsName :: Maybe Text , _iniPrivateIpAddress :: Maybe Text , _iniPrivateIpAddresses :: List "item" InstancePrivateIpAddress , _iniSourceDestCheck :: Maybe Bool , _iniStatus :: Maybe NetworkInterfaceStatus , _iniSubnetId :: Maybe Text , _iniVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'InstanceNetworkInterface' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iniAssociation' @::@ 'Maybe' 'InstanceNetworkInterfaceAssociation' -- -- * 'iniAttachment' @::@ 'Maybe' 'InstanceNetworkInterfaceAttachment' -- -- * 'iniDescription' @::@ 'Maybe' 'Text' -- -- * 'iniGroups' @::@ ['GroupIdentifier'] -- -- * 'iniMacAddress' @::@ 'Maybe' 'Text' -- -- * 'iniNetworkInterfaceId' @::@ 'Maybe' 'Text' -- -- * 'iniOwnerId' @::@ 'Maybe' 'Text' -- -- * 'iniPrivateDnsName' @::@ 'Maybe' 'Text' -- -- * 'iniPrivateIpAddress' @::@ 'Maybe' 'Text' -- -- * 'iniPrivateIpAddresses' @::@ ['InstancePrivateIpAddress'] -- -- * 'iniSourceDestCheck' @::@ 'Maybe' 'Bool' -- -- * 'iniStatus' @::@ 'Maybe' 'NetworkInterfaceStatus' -- -- * 'iniSubnetId' @::@ 'Maybe' 'Text' -- -- * 'iniVpcId' @::@ 'Maybe' 'Text' -- instanceNetworkInterface :: InstanceNetworkInterface instanceNetworkInterface = InstanceNetworkInterface { _iniNetworkInterfaceId = Nothing , _iniSubnetId = Nothing , _iniVpcId = Nothing , _iniDescription = Nothing , _iniOwnerId = Nothing , _iniStatus = Nothing , _iniMacAddress = Nothing , _iniPrivateIpAddress = Nothing , _iniPrivateDnsName = Nothing , _iniSourceDestCheck = Nothing , _iniGroups = mempty , _iniAttachment = Nothing , _iniAssociation = Nothing , _iniPrivateIpAddresses = mempty } -- | The association information for an Elastic IP associated with the network -- interface. iniAssociation :: Lens' InstanceNetworkInterface (Maybe InstanceNetworkInterfaceAssociation) iniAssociation = lens _iniAssociation (\s a -> s { _iniAssociation = a }) -- | The network interface attachment. iniAttachment :: Lens' InstanceNetworkInterface (Maybe InstanceNetworkInterfaceAttachment) iniAttachment = lens _iniAttachment (\s a -> s { _iniAttachment = a }) -- | The description. iniDescription :: Lens' InstanceNetworkInterface (Maybe Text) iniDescription = lens _iniDescription (\s a -> s { _iniDescription = a }) -- | One or more security groups. iniGroups :: Lens' InstanceNetworkInterface [GroupIdentifier] iniGroups = lens _iniGroups (\s a -> s { _iniGroups = a }) . _List -- | The MAC address. iniMacAddress :: Lens' InstanceNetworkInterface (Maybe Text) iniMacAddress = lens _iniMacAddress (\s a -> s { _iniMacAddress = a }) -- | The ID of the network interface. iniNetworkInterfaceId :: Lens' InstanceNetworkInterface (Maybe Text) iniNetworkInterfaceId = lens _iniNetworkInterfaceId (\s a -> s { _iniNetworkInterfaceId = a }) -- | The ID of the AWS account that created the network interface. iniOwnerId :: Lens' InstanceNetworkInterface (Maybe Text) iniOwnerId = lens _iniOwnerId (\s a -> s { _iniOwnerId = a }) -- | The private DNS name. iniPrivateDnsName :: Lens' InstanceNetworkInterface (Maybe Text) iniPrivateDnsName = lens _iniPrivateDnsName (\s a -> s { _iniPrivateDnsName = a }) -- | The IP address of the network interface within the subnet. iniPrivateIpAddress :: Lens' InstanceNetworkInterface (Maybe Text) iniPrivateIpAddress = lens _iniPrivateIpAddress (\s a -> s { _iniPrivateIpAddress = a }) -- | The private IP addresses associated with the network interface. iniPrivateIpAddresses :: Lens' InstanceNetworkInterface [InstancePrivateIpAddress] iniPrivateIpAddresses = lens _iniPrivateIpAddresses (\s a -> s { _iniPrivateIpAddresses = a }) . _List -- | Indicates whether to validate network traffic to or from this network -- interface. iniSourceDestCheck :: Lens' InstanceNetworkInterface (Maybe Bool) iniSourceDestCheck = lens _iniSourceDestCheck (\s a -> s { _iniSourceDestCheck = a }) -- | The status of the network interface. iniStatus :: Lens' InstanceNetworkInterface (Maybe NetworkInterfaceStatus) iniStatus = lens _iniStatus (\s a -> s { _iniStatus = a }) -- | The ID of the subnet. iniSubnetId :: Lens' InstanceNetworkInterface (Maybe Text) iniSubnetId = lens _iniSubnetId (\s a -> s { _iniSubnetId = a }) -- | The ID of the VPC. iniVpcId :: Lens' InstanceNetworkInterface (Maybe Text) iniVpcId = lens _iniVpcId (\s a -> s { _iniVpcId = a }) instance FromXML InstanceNetworkInterface where parseXML x = InstanceNetworkInterface <$> x .@? "association" <*> x .@? "attachment" <*> x .@? "description" <*> x .@? "groupSet" .!@ mempty <*> x .@? "macAddress" <*> x .@? "networkInterfaceId" <*> x .@? "ownerId" <*> x .@? "privateDnsName" <*> x .@? "privateIpAddress" <*> x .@? "privateIpAddressesSet" .!@ mempty <*> x .@? "sourceDestCheck" <*> x .@? "status" <*> x .@? "subnetId" <*> x .@? "vpcId" instance ToQuery InstanceNetworkInterface where toQuery InstanceNetworkInterface{..} = mconcat [ "Association" =? _iniAssociation , "Attachment" =? _iniAttachment , "Description" =? _iniDescription , "GroupSet" `toQueryList` _iniGroups , "MacAddress" =? _iniMacAddress , "NetworkInterfaceId" =? _iniNetworkInterfaceId , "OwnerId" =? _iniOwnerId , "PrivateDnsName" =? _iniPrivateDnsName , "PrivateIpAddress" =? _iniPrivateIpAddress , "PrivateIpAddressesSet" `toQueryList` _iniPrivateIpAddresses , "SourceDestCheck" =? _iniSourceDestCheck , "Status" =? _iniStatus , "SubnetId" =? _iniSubnetId , "VpcId" =? _iniVpcId ] data VolumeStatusAction = VolumeStatusAction { _vsaCode :: Maybe Text , _vsaDescription :: Maybe Text , _vsaEventId :: Maybe Text , _vsaEventType :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'VolumeStatusAction' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vsaCode' @::@ 'Maybe' 'Text' -- -- * 'vsaDescription' @::@ 'Maybe' 'Text' -- -- * 'vsaEventId' @::@ 'Maybe' 'Text' -- -- * 'vsaEventType' @::@ 'Maybe' 'Text' -- volumeStatusAction :: VolumeStatusAction volumeStatusAction = VolumeStatusAction { _vsaCode = Nothing , _vsaDescription = Nothing , _vsaEventType = Nothing , _vsaEventId = Nothing } -- | The code identifying the operation, for example, 'enable-volume-io'. vsaCode :: Lens' VolumeStatusAction (Maybe Text) vsaCode = lens _vsaCode (\s a -> s { _vsaCode = a }) -- | A description of the operation. vsaDescription :: Lens' VolumeStatusAction (Maybe Text) vsaDescription = lens _vsaDescription (\s a -> s { _vsaDescription = a }) -- | The ID of the event associated with this operation. vsaEventId :: Lens' VolumeStatusAction (Maybe Text) vsaEventId = lens _vsaEventId (\s a -> s { _vsaEventId = a }) -- | The event type associated with this operation. vsaEventType :: Lens' VolumeStatusAction (Maybe Text) vsaEventType = lens _vsaEventType (\s a -> s { _vsaEventType = a }) instance FromXML VolumeStatusAction where parseXML x = VolumeStatusAction <$> x .@? "code" <*> x .@? "description" <*> x .@? "eventId" <*> x .@? "eventType" instance ToQuery VolumeStatusAction where toQuery VolumeStatusAction{..} = mconcat [ "Code" =? _vsaCode , "Description" =? _vsaDescription , "EventId" =? _vsaEventId , "EventType" =? _vsaEventType ] data VpcPeeringConnectionVpcInfo = VpcPeeringConnectionVpcInfo { _vpcviCidrBlock :: Maybe Text , _vpcviOwnerId :: Maybe Text , _vpcviVpcId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'VpcPeeringConnectionVpcInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vpcviCidrBlock' @::@ 'Maybe' 'Text' -- -- * 'vpcviOwnerId' @::@ 'Maybe' 'Text' -- -- * 'vpcviVpcId' @::@ 'Maybe' 'Text' -- vpcPeeringConnectionVpcInfo :: VpcPeeringConnectionVpcInfo vpcPeeringConnectionVpcInfo = VpcPeeringConnectionVpcInfo { _vpcviCidrBlock = Nothing , _vpcviOwnerId = Nothing , _vpcviVpcId = Nothing } -- | The CIDR block for the VPC. vpcviCidrBlock :: Lens' VpcPeeringConnectionVpcInfo (Maybe Text) vpcviCidrBlock = lens _vpcviCidrBlock (\s a -> s { _vpcviCidrBlock = a }) -- | The AWS account ID of the VPC owner. vpcviOwnerId :: Lens' VpcPeeringConnectionVpcInfo (Maybe Text) vpcviOwnerId = lens _vpcviOwnerId (\s a -> s { _vpcviOwnerId = a }) -- | The ID of the VPC. vpcviVpcId :: Lens' VpcPeeringConnectionVpcInfo (Maybe Text) vpcviVpcId = lens _vpcviVpcId (\s a -> s { _vpcviVpcId = a }) instance FromXML VpcPeeringConnectionVpcInfo where parseXML x = VpcPeeringConnectionVpcInfo <$> x .@? "cidrBlock" <*> x .@? "ownerId" <*> x .@? "vpcId" instance ToQuery VpcPeeringConnectionVpcInfo where toQuery VpcPeeringConnectionVpcInfo{..} = mconcat [ "CidrBlock" =? _vpcviCidrBlock , "OwnerId" =? _vpcviOwnerId , "VpcId" =? _vpcviVpcId ] data ReservedInstanceLimitPrice = ReservedInstanceLimitPrice { _rilpAmount :: Maybe Double , _rilpCurrencyCode :: Maybe CurrencyCodeValues } deriving (Eq, Read, Show) -- | 'ReservedInstanceLimitPrice' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rilpAmount' @::@ 'Maybe' 'Double' -- -- * 'rilpCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues' -- reservedInstanceLimitPrice :: ReservedInstanceLimitPrice reservedInstanceLimitPrice = ReservedInstanceLimitPrice { _rilpAmount = Nothing , _rilpCurrencyCode = Nothing } -- | Used for Reserved Instance Marketplace offerings. Specifies the limit price -- on the total order (instanceCount * price). rilpAmount :: Lens' ReservedInstanceLimitPrice (Maybe Double) rilpAmount = lens _rilpAmount (\s a -> s { _rilpAmount = a }) -- | The currency in which the 'limitPrice' amount is specified. At this time, the -- only supported currency is 'USD'. rilpCurrencyCode :: Lens' ReservedInstanceLimitPrice (Maybe CurrencyCodeValues) rilpCurrencyCode = lens _rilpCurrencyCode (\s a -> s { _rilpCurrencyCode = a }) instance FromXML ReservedInstanceLimitPrice where parseXML x = ReservedInstanceLimitPrice <$> x .@? "amount" <*> x .@? "currencyCode" instance ToQuery ReservedInstanceLimitPrice where toQuery ReservedInstanceLimitPrice{..} = mconcat [ "Amount" =? _rilpAmount , "CurrencyCode" =? _rilpCurrencyCode ] data Vpc = Vpc { _vpcCidrBlock :: Text , _vpcDhcpOptionsId :: Text , _vpcInstanceTenancy :: Tenancy , _vpcIsDefault :: Bool , _vpcState :: VpcState , _vpcTags :: List "item" Tag , _vpcVpcId :: Text } deriving (Eq, Read, Show) -- | 'Vpc' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vpcCidrBlock' @::@ 'Text' -- -- * 'vpcDhcpOptionsId' @::@ 'Text' -- -- * 'vpcInstanceTenancy' @::@ 'Tenancy' -- -- * 'vpcIsDefault' @::@ 'Bool' -- -- * 'vpcState' @::@ 'VpcState' -- -- * 'vpcTags' @::@ ['Tag'] -- -- * 'vpcVpcId' @::@ 'Text' -- vpc :: Text -- ^ 'vpcVpcId' -> VpcState -- ^ 'vpcState' -> Text -- ^ 'vpcCidrBlock' -> Text -- ^ 'vpcDhcpOptionsId' -> Tenancy -- ^ 'vpcInstanceTenancy' -> Bool -- ^ 'vpcIsDefault' -> Vpc vpc p1 p2 p3 p4 p5 p6 = Vpc { _vpcVpcId = p1 , _vpcState = p2 , _vpcCidrBlock = p3 , _vpcDhcpOptionsId = p4 , _vpcInstanceTenancy = p5 , _vpcIsDefault = p6 , _vpcTags = mempty } -- | The CIDR block for the VPC. vpcCidrBlock :: Lens' Vpc Text vpcCidrBlock = lens _vpcCidrBlock (\s a -> s { _vpcCidrBlock = a }) -- | The ID of the set of DHCP options you've associated with the VPC (or 'default' -- if the default options are associated with the VPC). vpcDhcpOptionsId :: Lens' Vpc Text vpcDhcpOptionsId = lens _vpcDhcpOptionsId (\s a -> s { _vpcDhcpOptionsId = a }) -- | The allowed tenancy of instances launched into the VPC. vpcInstanceTenancy :: Lens' Vpc Tenancy vpcInstanceTenancy = lens _vpcInstanceTenancy (\s a -> s { _vpcInstanceTenancy = a }) -- | Indicates whether the VPC is the default VPC. vpcIsDefault :: Lens' Vpc Bool vpcIsDefault = lens _vpcIsDefault (\s a -> s { _vpcIsDefault = a }) -- | The current state of the VPC. vpcState :: Lens' Vpc VpcState vpcState = lens _vpcState (\s a -> s { _vpcState = a }) -- | Any tags assigned to the VPC. vpcTags :: Lens' Vpc [Tag] vpcTags = lens _vpcTags (\s a -> s { _vpcTags = a }) . _List -- | The ID of the VPC. vpcVpcId :: Lens' Vpc Text vpcVpcId = lens _vpcVpcId (\s a -> s { _vpcVpcId = a }) instance FromXML Vpc where parseXML x = Vpc <$> x .@ "cidrBlock" <*> x .@ "dhcpOptionsId" <*> x .@ "instanceTenancy" <*> x .@ "isDefault" <*> x .@ "state" <*> x .@? "tagSet" .!@ mempty <*> x .@ "vpcId" instance ToQuery Vpc where toQuery Vpc{..} = mconcat [ "CidrBlock" =? _vpcCidrBlock , "DhcpOptionsId" =? _vpcDhcpOptionsId , "InstanceTenancy" =? _vpcInstanceTenancy , "IsDefault" =? _vpcIsDefault , "State" =? _vpcState , "TagSet" `toQueryList` _vpcTags , "VpcId" =? _vpcVpcId ] data InstanceStatus = InstanceStatus { _isAvailabilityZone :: Maybe Text , _isEvents :: List "item" InstanceStatusEvent , _isInstanceId :: Maybe Text , _isInstanceState :: Maybe InstanceState , _isInstanceStatus :: Maybe InstanceStatusSummary , _isSystemStatus :: Maybe InstanceStatusSummary } deriving (Eq, Read, Show) -- | 'InstanceStatus' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'isAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'isEvents' @::@ ['InstanceStatusEvent'] -- -- * 'isInstanceId' @::@ 'Maybe' 'Text' -- -- * 'isInstanceState' @::@ 'Maybe' 'InstanceState' -- -- * 'isInstanceStatus' @::@ 'Maybe' 'InstanceStatusSummary' -- -- * 'isSystemStatus' @::@ 'Maybe' 'InstanceStatusSummary' -- instanceStatus :: InstanceStatus instanceStatus = InstanceStatus { _isInstanceId = Nothing , _isAvailabilityZone = Nothing , _isEvents = mempty , _isInstanceState = Nothing , _isSystemStatus = Nothing , _isInstanceStatus = Nothing } -- | The Availability Zone of the instance. isAvailabilityZone :: Lens' InstanceStatus (Maybe Text) isAvailabilityZone = lens _isAvailabilityZone (\s a -> s { _isAvailabilityZone = a }) -- | Extra information regarding events associated with the instance. isEvents :: Lens' InstanceStatus [InstanceStatusEvent] isEvents = lens _isEvents (\s a -> s { _isEvents = a }) . _List -- | The ID of the instance. isInstanceId :: Lens' InstanceStatus (Maybe Text) isInstanceId = lens _isInstanceId (\s a -> s { _isInstanceId = a }) -- | The intended state of the instance. 'DescribeInstanceStatus' requires that an -- instance be in the 'running' state. isInstanceState :: Lens' InstanceStatus (Maybe InstanceState) isInstanceState = lens _isInstanceState (\s a -> s { _isInstanceState = a }) -- | Reports impaired functionality that stems from issues internal to the -- instance, such as impaired reachability. isInstanceStatus :: Lens' InstanceStatus (Maybe InstanceStatusSummary) isInstanceStatus = lens _isInstanceStatus (\s a -> s { _isInstanceStatus = a }) -- | Reports impaired functionality that stems from issues related to the systems -- that support an instance, such as hardware failures and network connectivity -- problems. isSystemStatus :: Lens' InstanceStatus (Maybe InstanceStatusSummary) isSystemStatus = lens _isSystemStatus (\s a -> s { _isSystemStatus = a }) instance FromXML InstanceStatus where parseXML x = InstanceStatus <$> x .@? "availabilityZone" <*> x .@? "eventsSet" .!@ mempty <*> x .@? "instanceId" <*> x .@? "instanceState" <*> x .@? "instanceStatus" <*> x .@? "systemStatus" instance ToQuery InstanceStatus where toQuery InstanceStatus{..} = mconcat [ "AvailabilityZone" =? _isAvailabilityZone , "EventsSet" `toQueryList` _isEvents , "InstanceId" =? _isInstanceId , "InstanceState" =? _isInstanceState , "InstanceStatus" =? _isInstanceStatus , "SystemStatus" =? _isSystemStatus ] data ArchitectureValues = I386 -- ^ i386 | X8664 -- ^ x86_64 deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ArchitectureValues instance FromText ArchitectureValues where parser = takeLowerText >>= \case "i386" -> pure I386 "x86_64" -> pure X8664 e -> fail $ "Failure parsing ArchitectureValues from " ++ show e instance ToText ArchitectureValues where toText = \case I386 -> "i386" X8664 -> "x86_64" instance ToByteString ArchitectureValues instance ToHeader ArchitectureValues instance ToQuery ArchitectureValues instance FromXML ArchitectureValues where parseXML = parseXMLText "ArchitectureValues" data ReportInstanceReasonCodes = InstanceStuckInState -- ^ instance-stuck-in-state | NotAcceptingCredentials -- ^ not-accepting-credentials | Other -- ^ other | PasswordNotAvailable -- ^ password-not-available | PerformanceEbsVolume -- ^ performance-ebs-volume | PerformanceInstanceStore -- ^ performance-instance-store | PerformanceNetwork -- ^ performance-network | PerformanceOther -- ^ performance-other | Unresponsive -- ^ unresponsive deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ReportInstanceReasonCodes instance FromText ReportInstanceReasonCodes where parser = takeLowerText >>= \case "instance-stuck-in-state" -> pure InstanceStuckInState "not-accepting-credentials" -> pure NotAcceptingCredentials "other" -> pure Other "password-not-available" -> pure PasswordNotAvailable "performance-ebs-volume" -> pure PerformanceEbsVolume "performance-instance-store" -> pure PerformanceInstanceStore "performance-network" -> pure PerformanceNetwork "performance-other" -> pure PerformanceOther "unresponsive" -> pure Unresponsive e -> fail $ "Failure parsing ReportInstanceReasonCodes from " ++ show e instance ToText ReportInstanceReasonCodes where toText = \case InstanceStuckInState -> "instance-stuck-in-state" NotAcceptingCredentials -> "not-accepting-credentials" Other -> "other" PasswordNotAvailable -> "password-not-available" PerformanceEbsVolume -> "performance-ebs-volume" PerformanceInstanceStore -> "performance-instance-store" PerformanceNetwork -> "performance-network" PerformanceOther -> "performance-other" Unresponsive -> "unresponsive" instance ToByteString ReportInstanceReasonCodes instance ToHeader ReportInstanceReasonCodes instance ToQuery ReportInstanceReasonCodes instance FromXML ReportInstanceReasonCodes where parseXML = parseXMLText "ReportInstanceReasonCodes" data EbsBlockDevice = EbsBlockDevice { _ebdDeleteOnTermination :: Maybe Bool , _ebdEncrypted :: Maybe Bool , _ebdIops :: Maybe Int , _ebdSnapshotId :: Maybe Text , _ebdVolumeSize :: Maybe Int , _ebdVolumeType :: Maybe VolumeType } deriving (Eq, Read, Show) -- | 'EbsBlockDevice' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ebdDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'ebdEncrypted' @::@ 'Maybe' 'Bool' -- -- * 'ebdIops' @::@ 'Maybe' 'Int' -- -- * 'ebdSnapshotId' @::@ 'Maybe' 'Text' -- -- * 'ebdVolumeSize' @::@ 'Maybe' 'Int' -- -- * 'ebdVolumeType' @::@ 'Maybe' 'VolumeType' -- ebsBlockDevice :: EbsBlockDevice ebsBlockDevice = EbsBlockDevice { _ebdSnapshotId = Nothing , _ebdVolumeSize = Nothing , _ebdDeleteOnTermination = Nothing , _ebdVolumeType = Nothing , _ebdIops = Nothing , _ebdEncrypted = Nothing } -- | Indicates whether the Amazon EBS volume is deleted on instance termination. ebdDeleteOnTermination :: Lens' EbsBlockDevice (Maybe Bool) ebdDeleteOnTermination = lens _ebdDeleteOnTermination (\s a -> s { _ebdDeleteOnTermination = a }) -- | Indicates whether the Amazon EBS volume is encrypted. Encrypted Amazon EBS -- volumes may only be attached to instances that support Amazon EBS encryption. ebdEncrypted :: Lens' EbsBlockDevice (Maybe Bool) ebdEncrypted = lens _ebdEncrypted (\s a -> s { _ebdEncrypted = a }) -- | The number of I/O operations per second (IOPS) that the volume supports. For -- Provisioned IOPS (SSD) volumes, this represents the number of IOPS that are -- provisioned for the volume. For General Purpose (SSD) volumes, this -- represents the baseline performance of the volume and the rate at which the -- volume accumulates I/O credits for bursting. For more information on General -- Purpose (SSD) baseline performance, I/O credits, and bursting, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html Amazon EBSVolume Types> in the /Amazon Elastic Compute Cloud User Guide for Linux/. -- -- Constraint: Range is 100 to 20000 for Provisioned IOPS (SSD) volumes and 3 -- to 10000 for General Purpose (SSD) volumes. -- -- Condition: This parameter is required for requests to create 'io1' volumes; it -- is not used in requests to create 'standard' or 'gp2' volumes. ebdIops :: Lens' EbsBlockDevice (Maybe Int) ebdIops = lens _ebdIops (\s a -> s { _ebdIops = a }) -- | The ID of the snapshot. ebdSnapshotId :: Lens' EbsBlockDevice (Maybe Text) ebdSnapshotId = lens _ebdSnapshotId (\s a -> s { _ebdSnapshotId = a }) -- | The size of the volume, in GiB. -- -- Constraints: '1-1024' for 'standard' volumes, '1-16384' for 'gp2' volumes, and '4-16384' for 'io1' volumes. If you specify a snapshot, the volume size must be equal to -- or larger than the snapshot size. -- -- Default: If you're creating the volume from a snapshot and don't specify a -- volume size, the default is the snapshot size. ebdVolumeSize :: Lens' EbsBlockDevice (Maybe Int) ebdVolumeSize = lens _ebdVolumeSize (\s a -> s { _ebdVolumeSize = a }) -- | The volume type. 'gp2' for General Purpose (SSD) volumes, 'io1' for Provisioned -- IOPS (SSD) volumes, and 'standard' for Magnetic volumes. -- -- Default: 'standard' ebdVolumeType :: Lens' EbsBlockDevice (Maybe VolumeType) ebdVolumeType = lens _ebdVolumeType (\s a -> s { _ebdVolumeType = a }) instance FromXML EbsBlockDevice where parseXML x = EbsBlockDevice <$> x .@? "deleteOnTermination" <*> x .@? "encrypted" <*> x .@? "iops" <*> x .@? "snapshotId" <*> x .@? "volumeSize" <*> x .@? "volumeType" instance ToQuery EbsBlockDevice where toQuery EbsBlockDevice{..} = mconcat [ "DeleteOnTermination" =? _ebdDeleteOnTermination , "Encrypted" =? _ebdEncrypted , "Iops" =? _ebdIops , "SnapshotId" =? _ebdSnapshotId , "VolumeSize" =? _ebdVolumeSize , "VolumeType" =? _ebdVolumeType ] data AccountAttribute = AccountAttribute { _aaAttributeName :: Maybe Text , _aaAttributeValues :: List "item" AccountAttributeValue } deriving (Eq, Read, Show) -- | 'AccountAttribute' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aaAttributeName' @::@ 'Maybe' 'Text' -- -- * 'aaAttributeValues' @::@ ['AccountAttributeValue'] -- accountAttribute :: AccountAttribute accountAttribute = AccountAttribute { _aaAttributeName = Nothing , _aaAttributeValues = mempty } -- | The name of the account attribute. aaAttributeName :: Lens' AccountAttribute (Maybe Text) aaAttributeName = lens _aaAttributeName (\s a -> s { _aaAttributeName = a }) -- | One or more values for the account attribute. aaAttributeValues :: Lens' AccountAttribute [AccountAttributeValue] aaAttributeValues = lens _aaAttributeValues (\s a -> s { _aaAttributeValues = a }) . _List instance FromXML AccountAttribute where parseXML x = AccountAttribute <$> x .@? "attributeName" <*> x .@? "attributeValueSet" .!@ mempty instance ToQuery AccountAttribute where toQuery AccountAttribute{..} = mconcat [ "AttributeName" =? _aaAttributeName , "AttributeValueSet" `toQueryList` _aaAttributeValues ] data PriceSchedule = PriceSchedule { _psActive :: Maybe Bool , _psCurrencyCode :: Maybe CurrencyCodeValues , _psPrice :: Maybe Double , _psTerm :: Maybe Integer } deriving (Eq, Read, Show) -- | 'PriceSchedule' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'psActive' @::@ 'Maybe' 'Bool' -- -- * 'psCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues' -- -- * 'psPrice' @::@ 'Maybe' 'Double' -- -- * 'psTerm' @::@ 'Maybe' 'Integer' -- priceSchedule :: PriceSchedule priceSchedule = PriceSchedule { _psTerm = Nothing , _psPrice = Nothing , _psCurrencyCode = Nothing , _psActive = Nothing } -- | The current price schedule, as determined by the term remaining for the -- Reserved Instance in the listing. -- -- A specific price schedule is always in effect, but only one price schedule -- can be active at any time. Take, for example, a Reserved Instance listing -- that has five months remaining in its term. When you specify price schedules -- for five months and two months, this means that schedule 1, covering the -- first three months of the remaining term, will be active during months 5, 4, -- and 3. Then schedule 2, covering the last two months of the term, will be -- active for months 2 and 1. psActive :: Lens' PriceSchedule (Maybe Bool) psActive = lens _psActive (\s a -> s { _psActive = a }) -- | The currency for transacting the Reserved Instance resale. At this time, the -- only supported currency is 'USD'. psCurrencyCode :: Lens' PriceSchedule (Maybe CurrencyCodeValues) psCurrencyCode = lens _psCurrencyCode (\s a -> s { _psCurrencyCode = a }) -- | The fixed price for the term. psPrice :: Lens' PriceSchedule (Maybe Double) psPrice = lens _psPrice (\s a -> s { _psPrice = a }) -- | The number of months remaining in the reservation. For example, 2 is the -- second to the last month before the capacity reservation expires. psTerm :: Lens' PriceSchedule (Maybe Integer) psTerm = lens _psTerm (\s a -> s { _psTerm = a }) instance FromXML PriceSchedule where parseXML x = PriceSchedule <$> x .@? "active" <*> x .@? "currencyCode" <*> x .@? "price" <*> x .@? "term" instance ToQuery PriceSchedule where toQuery PriceSchedule{..} = mconcat [ "Active" =? _psActive , "CurrencyCode" =? _psCurrencyCode , "Price" =? _psPrice , "Term" =? _psTerm ] data DeviceType = Ebs -- ^ ebs | InstanceStore -- ^ instance-store deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable DeviceType instance FromText DeviceType where parser = takeLowerText >>= \case "ebs" -> pure Ebs "instance-store" -> pure InstanceStore e -> fail $ "Failure parsing DeviceType from " ++ show e instance ToText DeviceType where toText = \case Ebs -> "ebs" InstanceStore -> "instance-store" instance ToByteString DeviceType instance ToHeader DeviceType instance ToQuery DeviceType instance FromXML DeviceType where parseXML = parseXMLText "DeviceType" data DomainType = DTStandard -- ^ standard | DTVpc -- ^ vpc deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable DomainType instance FromText DomainType where parser = takeLowerText >>= \case "standard" -> pure DTStandard "vpc" -> pure DTVpc e -> fail $ "Failure parsing DomainType from " ++ show e instance ToText DomainType where toText = \case DTStandard -> "standard" DTVpc -> "vpc" instance ToByteString DomainType instance ToHeader DomainType instance ToQuery DomainType instance FromXML DomainType where parseXML = parseXMLText "DomainType" data Region = Region { _rEndpoint :: Maybe Text , _rRegionName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'Region' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rEndpoint' @::@ 'Maybe' 'Text' -- -- * 'rRegionName' @::@ 'Maybe' 'Text' -- region :: Region region = Region { _rRegionName = Nothing , _rEndpoint = Nothing } -- | The region service endpoint. rEndpoint :: Lens' Region (Maybe Text) rEndpoint = lens _rEndpoint (\s a -> s { _rEndpoint = a }) -- | The name of the region. rRegionName :: Lens' Region (Maybe Text) rRegionName = lens _rRegionName (\s a -> s { _rRegionName = a }) instance FromXML Region where parseXML x = Region <$> x .@? "regionEndpoint" <*> x .@? "regionName" instance ToQuery Region where toQuery Region{..} = mconcat [ "RegionEndpoint" =? _rEndpoint , "RegionName" =? _rRegionName ] newtype PropagatingVgw = PropagatingVgw { _pvGatewayId :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'PropagatingVgw' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pvGatewayId' @::@ 'Maybe' 'Text' -- propagatingVgw :: PropagatingVgw propagatingVgw = PropagatingVgw { _pvGatewayId = Nothing } -- | The ID of the virtual private gateway (VGW). pvGatewayId :: Lens' PropagatingVgw (Maybe Text) pvGatewayId = lens _pvGatewayId (\s a -> s { _pvGatewayId = a }) instance FromXML PropagatingVgw where parseXML x = PropagatingVgw <$> x .@? "gatewayId" instance ToQuery PropagatingVgw where toQuery PropagatingVgw{..} = mconcat [ "GatewayId" =? _pvGatewayId ] data OfferingTypeValues = AllUpfront -- ^ All Upfront | HeavyUtilization -- ^ Heavy Utilization | LightUtilization -- ^ Light Utilization | MediumUtilization -- ^ Medium Utilization | NoUpfront -- ^ No Upfront | PartialUpfront -- ^ Partial Upfront deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable OfferingTypeValues instance FromText OfferingTypeValues where parser = takeLowerText >>= \case "all upfront" -> pure AllUpfront "heavy utilization" -> pure HeavyUtilization "light utilization" -> pure LightUtilization "medium utilization" -> pure MediumUtilization "no upfront" -> pure NoUpfront "partial upfront" -> pure PartialUpfront e -> fail $ "Failure parsing OfferingTypeValues from " ++ show e instance ToText OfferingTypeValues where toText = \case AllUpfront -> "All Upfront" HeavyUtilization -> "Heavy Utilization" LightUtilization -> "Light Utilization" MediumUtilization -> "Medium Utilization" NoUpfront -> "No Upfront" PartialUpfront -> "Partial Upfront" instance ToByteString OfferingTypeValues instance ToHeader OfferingTypeValues instance ToQuery OfferingTypeValues instance FromXML OfferingTypeValues where parseXML = parseXMLText "OfferingTypeValues" data VpnGateway = VpnGateway { _vgAvailabilityZone :: Maybe Text , _vgState :: Maybe VpnState , _vgTags :: List "item" Tag , _vgType :: Maybe GatewayType , _vgVpcAttachments :: List "item" VpcAttachment , _vgVpnGatewayId :: Maybe Text } deriving (Eq, Read, Show) -- | 'VpnGateway' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vgAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'vgState' @::@ 'Maybe' 'VpnState' -- -- * 'vgTags' @::@ ['Tag'] -- -- * 'vgType' @::@ 'Maybe' 'GatewayType' -- -- * 'vgVpcAttachments' @::@ ['VpcAttachment'] -- -- * 'vgVpnGatewayId' @::@ 'Maybe' 'Text' -- vpnGateway :: VpnGateway vpnGateway = VpnGateway { _vgVpnGatewayId = Nothing , _vgState = Nothing , _vgType = Nothing , _vgAvailabilityZone = Nothing , _vgVpcAttachments = mempty , _vgTags = mempty } -- | The Availability Zone where the virtual private gateway was created. vgAvailabilityZone :: Lens' VpnGateway (Maybe Text) vgAvailabilityZone = lens _vgAvailabilityZone (\s a -> s { _vgAvailabilityZone = a }) -- | The current state of the virtual private gateway. vgState :: Lens' VpnGateway (Maybe VpnState) vgState = lens _vgState (\s a -> s { _vgState = a }) -- | Any tags assigned to the virtual private gateway. vgTags :: Lens' VpnGateway [Tag] vgTags = lens _vgTags (\s a -> s { _vgTags = a }) . _List -- | The type of VPN connection the virtual private gateway supports. vgType :: Lens' VpnGateway (Maybe GatewayType) vgType = lens _vgType (\s a -> s { _vgType = a }) -- | Any VPCs attached to the virtual private gateway. vgVpcAttachments :: Lens' VpnGateway [VpcAttachment] vgVpcAttachments = lens _vgVpcAttachments (\s a -> s { _vgVpcAttachments = a }) . _List -- | The ID of the virtual private gateway. vgVpnGatewayId :: Lens' VpnGateway (Maybe Text) vgVpnGatewayId = lens _vgVpnGatewayId (\s a -> s { _vgVpnGatewayId = a }) instance FromXML VpnGateway where parseXML x = VpnGateway <$> x .@? "availabilityZone" <*> x .@? "state" <*> x .@? "tagSet" .!@ mempty <*> x .@? "type" <*> x .@? "attachments" .!@ mempty <*> x .@? "vpnGatewayId" instance ToQuery VpnGateway where toQuery VpnGateway{..} = mconcat [ "AvailabilityZone" =? _vgAvailabilityZone , "State" =? _vgState , "TagSet" `toQueryList` _vgTags , "Type" =? _vgType , "Attachments" `toQueryList` _vgVpcAttachments , "VpnGatewayId" =? _vgVpnGatewayId ] data Filter = Filter { _fName :: Text , _fValues :: List "item" Text } deriving (Eq, Ord, Read, Show) -- | 'Filter' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'fName' @::@ 'Text' -- -- * 'fValues' @::@ ['Text'] -- filter' :: Text -- ^ 'fName' -> Filter filter' p1 = Filter { _fName = p1 , _fValues = mempty } -- | The name of the filter. Filter names are case-sensitive. fName :: Lens' Filter Text fName = lens _fName (\s a -> s { _fName = a }) -- | One or more filter values. Filter values are case-sensitive. fValues :: Lens' Filter [Text] fValues = lens _fValues (\s a -> s { _fValues = a }) . _List instance FromXML Filter where parseXML x = Filter <$> x .@ "Name" <*> x .@? "Value" .!@ mempty instance ToQuery Filter where toQuery Filter{..} = mconcat [ "Name" =? _fName , "Value" `toQueryList` _fValues ] data VolumeType = Gp2 -- ^ gp2 | Io1 -- ^ io1 | Standard -- ^ standard deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VolumeType instance FromText VolumeType where parser = takeLowerText >>= \case "gp2" -> pure Gp2 "io1" -> pure Io1 "standard" -> pure Standard e -> fail $ "Failure parsing VolumeType from " ++ show e instance ToText VolumeType where toText = \case Gp2 -> "gp2" Io1 -> "io1" Standard -> "standard" instance ToByteString VolumeType instance ToHeader VolumeType instance ToQuery VolumeType instance FromXML VolumeType where parseXML = parseXMLText "VolumeType" data InstanceStateChange = InstanceStateChange { _iscCurrentState :: Maybe InstanceState , _iscInstanceId :: Maybe Text , _iscPreviousState :: Maybe InstanceState } deriving (Eq, Read, Show) -- | 'InstanceStateChange' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iscCurrentState' @::@ 'Maybe' 'InstanceState' -- -- * 'iscInstanceId' @::@ 'Maybe' 'Text' -- -- * 'iscPreviousState' @::@ 'Maybe' 'InstanceState' -- instanceStateChange :: InstanceStateChange instanceStateChange = InstanceStateChange { _iscInstanceId = Nothing , _iscCurrentState = Nothing , _iscPreviousState = Nothing } -- | The current state of the instance. iscCurrentState :: Lens' InstanceStateChange (Maybe InstanceState) iscCurrentState = lens _iscCurrentState (\s a -> s { _iscCurrentState = a }) -- | The ID of the instance. iscInstanceId :: Lens' InstanceStateChange (Maybe Text) iscInstanceId = lens _iscInstanceId (\s a -> s { _iscInstanceId = a }) -- | The previous state of the instance. iscPreviousState :: Lens' InstanceStateChange (Maybe InstanceState) iscPreviousState = lens _iscPreviousState (\s a -> s { _iscPreviousState = a }) instance FromXML InstanceStateChange where parseXML x = InstanceStateChange <$> x .@? "currentState" <*> x .@? "instanceId" <*> x .@? "previousState" instance ToQuery InstanceStateChange where toQuery InstanceStateChange{..} = mconcat [ "CurrentState" =? _iscCurrentState , "InstanceId" =? _iscInstanceId , "PreviousState" =? _iscPreviousState ] data NetworkAcl = NetworkAcl { _naAssociations :: List "item" NetworkAclAssociation , _naEntries :: List "item" NetworkAclEntry , _naIsDefault :: Maybe Bool , _naNetworkAclId :: Maybe Text , _naTags :: List "item" Tag , _naVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'NetworkAcl' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'naAssociations' @::@ ['NetworkAclAssociation'] -- -- * 'naEntries' @::@ ['NetworkAclEntry'] -- -- * 'naIsDefault' @::@ 'Maybe' 'Bool' -- -- * 'naNetworkAclId' @::@ 'Maybe' 'Text' -- -- * 'naTags' @::@ ['Tag'] -- -- * 'naVpcId' @::@ 'Maybe' 'Text' -- networkAcl :: NetworkAcl networkAcl = NetworkAcl { _naNetworkAclId = Nothing , _naVpcId = Nothing , _naIsDefault = Nothing , _naEntries = mempty , _naAssociations = mempty , _naTags = mempty } -- | Any associations between the network ACL and one or more subnets naAssociations :: Lens' NetworkAcl [NetworkAclAssociation] naAssociations = lens _naAssociations (\s a -> s { _naAssociations = a }) . _List -- | One or more entries (rules) in the network ACL. naEntries :: Lens' NetworkAcl [NetworkAclEntry] naEntries = lens _naEntries (\s a -> s { _naEntries = a }) . _List -- | Indicates whether this is the default network ACL for the VPC. naIsDefault :: Lens' NetworkAcl (Maybe Bool) naIsDefault = lens _naIsDefault (\s a -> s { _naIsDefault = a }) -- | The ID of the network ACL. naNetworkAclId :: Lens' NetworkAcl (Maybe Text) naNetworkAclId = lens _naNetworkAclId (\s a -> s { _naNetworkAclId = a }) -- | Any tags assigned to the network ACL. naTags :: Lens' NetworkAcl [Tag] naTags = lens _naTags (\s a -> s { _naTags = a }) . _List -- | The ID of the VPC for the network ACL. naVpcId :: Lens' NetworkAcl (Maybe Text) naVpcId = lens _naVpcId (\s a -> s { _naVpcId = a }) instance FromXML NetworkAcl where parseXML x = NetworkAcl <$> x .@? "associationSet" .!@ mempty <*> x .@? "entrySet" .!@ mempty <*> x .@? "default" <*> x .@? "networkAclId" <*> x .@? "tagSet" .!@ mempty <*> x .@? "vpcId" instance ToQuery NetworkAcl where toQuery NetworkAcl{..} = mconcat [ "AssociationSet" `toQueryList` _naAssociations , "EntrySet" `toQueryList` _naEntries , "Default" =? _naIsDefault , "NetworkAclId" =? _naNetworkAclId , "TagSet" `toQueryList` _naTags , "VpcId" =? _naVpcId ] data ImageState = ISAvailable -- ^ available | ISDeregistered -- ^ deregistered deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ImageState instance FromText ImageState where parser = takeLowerText >>= \case "available" -> pure ISAvailable "deregistered" -> pure ISDeregistered e -> fail $ "Failure parsing ImageState from " ++ show e instance ToText ImageState where toText = \case ISAvailable -> "available" ISDeregistered -> "deregistered" instance ToByteString ImageState instance ToHeader ImageState instance ToQuery ImageState instance FromXML ImageState where parseXML = parseXMLText "ImageState" data GatewayType = Ipsec1 -- ^ ipsec.1 deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable GatewayType instance FromText GatewayType where parser = takeLowerText >>= \case "ipsec.1" -> pure Ipsec1 e -> fail $ "Failure parsing GatewayType from " ++ show e instance ToText GatewayType where toText Ipsec1 = "ipsec.1" instance ToByteString GatewayType instance ToHeader GatewayType instance ToQuery GatewayType instance FromXML GatewayType where parseXML = parseXMLText "GatewayType" data InstanceNetworkInterfaceAttachment = InstanceNetworkInterfaceAttachment { _iniaAttachTime :: Maybe ISO8601 , _iniaAttachmentId :: Maybe Text , _iniaDeleteOnTermination :: Maybe Bool , _iniaDeviceIndex :: Maybe Int , _iniaStatus :: Maybe AttachmentStatus } deriving (Eq, Read, Show) -- | 'InstanceNetworkInterfaceAttachment' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iniaAttachTime' @::@ 'Maybe' 'UTCTime' -- -- * 'iniaAttachmentId' @::@ 'Maybe' 'Text' -- -- * 'iniaDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'iniaDeviceIndex' @::@ 'Maybe' 'Int' -- -- * 'iniaStatus' @::@ 'Maybe' 'AttachmentStatus' -- instanceNetworkInterfaceAttachment :: InstanceNetworkInterfaceAttachment instanceNetworkInterfaceAttachment = InstanceNetworkInterfaceAttachment { _iniaAttachmentId = Nothing , _iniaDeviceIndex = Nothing , _iniaStatus = Nothing , _iniaAttachTime = Nothing , _iniaDeleteOnTermination = Nothing } -- | The time stamp when the attachment initiated. iniaAttachTime :: Lens' InstanceNetworkInterfaceAttachment (Maybe UTCTime) iniaAttachTime = lens _iniaAttachTime (\s a -> s { _iniaAttachTime = a }) . mapping _Time -- | The ID of the network interface attachment. iniaAttachmentId :: Lens' InstanceNetworkInterfaceAttachment (Maybe Text) iniaAttachmentId = lens _iniaAttachmentId (\s a -> s { _iniaAttachmentId = a }) -- | Indicates whether the network interface is deleted when the instance is -- terminated. iniaDeleteOnTermination :: Lens' InstanceNetworkInterfaceAttachment (Maybe Bool) iniaDeleteOnTermination = lens _iniaDeleteOnTermination (\s a -> s { _iniaDeleteOnTermination = a }) -- | The index of the device on the instance for the network interface attachment. iniaDeviceIndex :: Lens' InstanceNetworkInterfaceAttachment (Maybe Int) iniaDeviceIndex = lens _iniaDeviceIndex (\s a -> s { _iniaDeviceIndex = a }) -- | The attachment state. iniaStatus :: Lens' InstanceNetworkInterfaceAttachment (Maybe AttachmentStatus) iniaStatus = lens _iniaStatus (\s a -> s { _iniaStatus = a }) instance FromXML InstanceNetworkInterfaceAttachment where parseXML x = InstanceNetworkInterfaceAttachment <$> x .@? "attachTime" <*> x .@? "attachmentId" <*> x .@? "deleteOnTermination" <*> x .@? "deviceIndex" <*> x .@? "status" instance ToQuery InstanceNetworkInterfaceAttachment where toQuery InstanceNetworkInterfaceAttachment{..} = mconcat [ "AttachTime" =? _iniaAttachTime , "AttachmentId" =? _iniaAttachmentId , "DeleteOnTermination" =? _iniaDeleteOnTermination , "DeviceIndex" =? _iniaDeviceIndex , "Status" =? _iniaStatus ] newtype AttributeBooleanValue = AttributeBooleanValue { _abvValue :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'AttributeBooleanValue' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'abvValue' @::@ 'Maybe' 'Bool' -- attributeBooleanValue :: AttributeBooleanValue attributeBooleanValue = AttributeBooleanValue { _abvValue = Nothing } -- | Valid values are 'true' or 'false'. abvValue :: Lens' AttributeBooleanValue (Maybe Bool) abvValue = lens _abvValue (\s a -> s { _abvValue = a }) instance FromXML AttributeBooleanValue where parseXML x = AttributeBooleanValue <$> x .@? "value" instance ToQuery AttributeBooleanValue where toQuery AttributeBooleanValue{..} = mconcat [ "Value" =? _abvValue ] data RecurringCharge = RecurringCharge { _rcAmount :: Maybe Double , _rcFrequency :: Maybe RecurringChargeFrequency } deriving (Eq, Read, Show) -- | 'RecurringCharge' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rcAmount' @::@ 'Maybe' 'Double' -- -- * 'rcFrequency' @::@ 'Maybe' 'RecurringChargeFrequency' -- recurringCharge :: RecurringCharge recurringCharge = RecurringCharge { _rcFrequency = Nothing , _rcAmount = Nothing } -- | The amount of the recurring charge. rcAmount :: Lens' RecurringCharge (Maybe Double) rcAmount = lens _rcAmount (\s a -> s { _rcAmount = a }) -- | The frequency of the recurring charge. rcFrequency :: Lens' RecurringCharge (Maybe RecurringChargeFrequency) rcFrequency = lens _rcFrequency (\s a -> s { _rcFrequency = a }) instance FromXML RecurringCharge where parseXML x = RecurringCharge <$> x .@? "amount" <*> x .@? "frequency" instance ToQuery RecurringCharge where toQuery RecurringCharge{..} = mconcat [ "Amount" =? _rcAmount , "Frequency" =? _rcFrequency ] data NewDhcpConfiguration = NewDhcpConfiguration { _ndcKey :: Maybe Text , _ndcValues :: List "item" Text } deriving (Eq, Ord, Read, Show) -- | 'NewDhcpConfiguration' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ndcKey' @::@ 'Maybe' 'Text' -- -- * 'ndcValues' @::@ ['Text'] -- newDhcpConfiguration :: NewDhcpConfiguration newDhcpConfiguration = NewDhcpConfiguration { _ndcKey = Nothing , _ndcValues = mempty } ndcKey :: Lens' NewDhcpConfiguration (Maybe Text) ndcKey = lens _ndcKey (\s a -> s { _ndcKey = a }) ndcValues :: Lens' NewDhcpConfiguration [Text] ndcValues = lens _ndcValues (\s a -> s { _ndcValues = a }) . _List instance FromXML NewDhcpConfiguration where parseXML x = NewDhcpConfiguration <$> x .@? "key" <*> x .@? "Value" .!@ mempty instance ToQuery NewDhcpConfiguration where toQuery NewDhcpConfiguration{..} = mconcat [ "Key" =? _ndcKey , "Value" `toQueryList` _ndcValues ] data StateReason = StateReason { _srCode :: Maybe Text , _srMessage :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'StateReason' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'srCode' @::@ 'Maybe' 'Text' -- -- * 'srMessage' @::@ 'Maybe' 'Text' -- stateReason :: StateReason stateReason = StateReason { _srCode = Nothing , _srMessage = Nothing } -- | The reason code for the state change. srCode :: Lens' StateReason (Maybe Text) srCode = lens _srCode (\s a -> s { _srCode = a }) -- | The message for the state change. -- -- 'Server.SpotInstanceTermination': A Spot Instance was terminated due to an -- increase in the market price. -- -- 'Server.InternalError': An internal error occurred during instance launch, -- resulting in termination. -- -- 'Server.InsufficientInstanceCapacity': There was insufficient instance -- capacity to satisfy the launch request. -- -- 'Client.InternalError': A client error caused the instance to terminate on -- launch. -- -- 'Client.InstanceInitiatedShutdown': The instance was shut down using the 'shutdown -h' command from the instance. -- -- 'Client.UserInitiatedShutdown': The instance was shut down using the Amazon -- EC2 API. -- -- 'Client.VolumeLimitExceeded': The volume limit was exceeded. -- -- 'Client.InvalidSnapshot.NotFound': The specified snapshot was not found. -- -- srMessage :: Lens' StateReason (Maybe Text) srMessage = lens _srMessage (\s a -> s { _srMessage = a }) instance FromXML StateReason where parseXML x = StateReason <$> x .@? "code" <*> x .@? "message" instance ToQuery StateReason where toQuery StateReason{..} = mconcat [ "Code" =? _srCode , "Message" =? _srMessage ] data MonitoringState = MSDisabled -- ^ disabled | MSEnabled -- ^ enabled | MSPending -- ^ pending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable MonitoringState instance FromText MonitoringState where parser = takeLowerText >>= \case "disabled" -> pure MSDisabled "enabled" -> pure MSEnabled "pending" -> pure MSPending e -> fail $ "Failure parsing MonitoringState from " ++ show e instance ToText MonitoringState where toText = \case MSDisabled -> "disabled" MSEnabled -> "enabled" MSPending -> "pending" instance ToByteString MonitoringState instance ToHeader MonitoringState instance ToQuery MonitoringState instance FromXML MonitoringState where parseXML = parseXMLText "MonitoringState" newtype ReservedInstancesId = ReservedInstancesId { _riiReservedInstancesId :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'ReservedInstancesId' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'riiReservedInstancesId' @::@ 'Maybe' 'Text' -- reservedInstancesId :: ReservedInstancesId reservedInstancesId = ReservedInstancesId { _riiReservedInstancesId = Nothing } -- | The ID of the Reserved Instance. riiReservedInstancesId :: Lens' ReservedInstancesId (Maybe Text) riiReservedInstancesId = lens _riiReservedInstancesId (\s a -> s { _riiReservedInstancesId = a }) instance FromXML ReservedInstancesId where parseXML x = ReservedInstancesId <$> x .@? "reservedInstancesId" instance ToQuery ReservedInstancesId where toQuery ReservedInstancesId{..} = mconcat [ "ReservedInstancesId" =? _riiReservedInstancesId ] data StatusName = Reachability -- ^ reachability deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable StatusName instance FromText StatusName where parser = takeLowerText >>= \case "reachability" -> pure Reachability e -> fail $ "Failure parsing StatusName from " ++ show e instance ToText StatusName where toText Reachability = "reachability" instance ToByteString StatusName instance ToHeader StatusName instance ToQuery StatusName instance FromXML StatusName where parseXML = parseXMLText "StatusName" data InternetGateway = InternetGateway { _igAttachments :: List "item" InternetGatewayAttachment , _igInternetGatewayId :: Text , _igTags :: List "item" Tag } deriving (Eq, Read, Show) -- | 'InternetGateway' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'igAttachments' @::@ ['InternetGatewayAttachment'] -- -- * 'igInternetGatewayId' @::@ 'Text' -- -- * 'igTags' @::@ ['Tag'] -- internetGateway :: Text -- ^ 'igInternetGatewayId' -> InternetGateway internetGateway p1 = InternetGateway { _igInternetGatewayId = p1 , _igAttachments = mempty , _igTags = mempty } -- | Any VPCs attached to the Internet gateway. igAttachments :: Lens' InternetGateway [InternetGatewayAttachment] igAttachments = lens _igAttachments (\s a -> s { _igAttachments = a }) . _List -- | The ID of the Internet gateway. igInternetGatewayId :: Lens' InternetGateway Text igInternetGatewayId = lens _igInternetGatewayId (\s a -> s { _igInternetGatewayId = a }) -- | Any tags assigned to the Internet gateway. igTags :: Lens' InternetGateway [Tag] igTags = lens _igTags (\s a -> s { _igTags = a }) . _List instance FromXML InternetGateway where parseXML x = InternetGateway <$> x .@? "attachmentSet" .!@ mempty <*> x .@ "internetGatewayId" <*> x .@? "tagSet" .!@ mempty instance ToQuery InternetGateway where toQuery InternetGateway{..} = mconcat [ "AttachmentSet" `toQueryList` _igAttachments , "InternetGatewayId" =? _igInternetGatewayId , "TagSet" `toQueryList` _igTags ] data VolumeStatusName = IoEnabled -- ^ io-enabled | IoPerformance -- ^ io-performance deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VolumeStatusName instance FromText VolumeStatusName where parser = takeLowerText >>= \case "io-enabled" -> pure IoEnabled "io-performance" -> pure IoPerformance e -> fail $ "Failure parsing VolumeStatusName from " ++ show e instance ToText VolumeStatusName where toText = \case IoEnabled -> "io-enabled" IoPerformance -> "io-performance" instance ToByteString VolumeStatusName instance ToHeader VolumeStatusName instance ToQuery VolumeStatusName instance FromXML VolumeStatusName where parseXML = parseXMLText "VolumeStatusName" data VolumeAttributeName = AutoEnableIO -- ^ autoEnableIO | ProductCodes -- ^ productCodes deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VolumeAttributeName instance FromText VolumeAttributeName where parser = takeLowerText >>= \case "autoenableio" -> pure AutoEnableIO "productcodes" -> pure ProductCodes e -> fail $ "Failure parsing VolumeAttributeName from " ++ show e instance ToText VolumeAttributeName where toText = \case AutoEnableIO -> "autoEnableIO" ProductCodes -> "productCodes" instance ToByteString VolumeAttributeName instance ToHeader VolumeAttributeName instance ToQuery VolumeAttributeName instance FromXML VolumeAttributeName where parseXML = parseXMLText "VolumeAttributeName" data ImportInstanceTaskDetails = ImportInstanceTaskDetails { _iitdDescription :: Maybe Text , _iitdInstanceId :: Maybe Text , _iitdPlatform :: Maybe PlatformValues , _iitdVolumes :: List "item" ImportInstanceVolumeDetailItem } deriving (Eq, Read, Show) -- | 'ImportInstanceTaskDetails' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'iitdDescription' @::@ 'Maybe' 'Text' -- -- * 'iitdInstanceId' @::@ 'Maybe' 'Text' -- -- * 'iitdPlatform' @::@ 'Maybe' 'PlatformValues' -- -- * 'iitdVolumes' @::@ ['ImportInstanceVolumeDetailItem'] -- importInstanceTaskDetails :: ImportInstanceTaskDetails importInstanceTaskDetails = ImportInstanceTaskDetails { _iitdVolumes = mempty , _iitdInstanceId = Nothing , _iitdPlatform = Nothing , _iitdDescription = Nothing } iitdDescription :: Lens' ImportInstanceTaskDetails (Maybe Text) iitdDescription = lens _iitdDescription (\s a -> s { _iitdDescription = a }) iitdInstanceId :: Lens' ImportInstanceTaskDetails (Maybe Text) iitdInstanceId = lens _iitdInstanceId (\s a -> s { _iitdInstanceId = a }) -- | The instance operating system. iitdPlatform :: Lens' ImportInstanceTaskDetails (Maybe PlatformValues) iitdPlatform = lens _iitdPlatform (\s a -> s { _iitdPlatform = a }) iitdVolumes :: Lens' ImportInstanceTaskDetails [ImportInstanceVolumeDetailItem] iitdVolumes = lens _iitdVolumes (\s a -> s { _iitdVolumes = a }) . _List instance FromXML ImportInstanceTaskDetails where parseXML x = ImportInstanceTaskDetails <$> x .@? "description" <*> x .@? "instanceId" <*> x .@? "platform" <*> x .@? "volumes" .!@ mempty instance ToQuery ImportInstanceTaskDetails where toQuery ImportInstanceTaskDetails{..} = mconcat [ "Description" =? _iitdDescription , "InstanceId" =? _iitdInstanceId , "Platform" =? _iitdPlatform , "Volumes" `toQueryList` _iitdVolumes ] data PlacementGroup = PlacementGroup { _pgGroupName :: Maybe Text , _pgState :: Maybe PlacementGroupState , _pgStrategy :: Maybe PlacementStrategy } deriving (Eq, Read, Show) -- | 'PlacementGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pgGroupName' @::@ 'Maybe' 'Text' -- -- * 'pgState' @::@ 'Maybe' 'PlacementGroupState' -- -- * 'pgStrategy' @::@ 'Maybe' 'PlacementStrategy' -- placementGroup :: PlacementGroup placementGroup = PlacementGroup { _pgGroupName = Nothing , _pgStrategy = Nothing , _pgState = Nothing } -- | The name of the placement group. pgGroupName :: Lens' PlacementGroup (Maybe Text) pgGroupName = lens _pgGroupName (\s a -> s { _pgGroupName = a }) -- | The state of the placement group. pgState :: Lens' PlacementGroup (Maybe PlacementGroupState) pgState = lens _pgState (\s a -> s { _pgState = a }) -- | The placement strategy. pgStrategy :: Lens' PlacementGroup (Maybe PlacementStrategy) pgStrategy = lens _pgStrategy (\s a -> s { _pgStrategy = a }) instance FromXML PlacementGroup where parseXML x = PlacementGroup <$> x .@? "groupName" <*> x .@? "state" <*> x .@? "strategy" instance ToQuery PlacementGroup where toQuery PlacementGroup{..} = mconcat [ "GroupName" =? _pgGroupName , "State" =? _pgState , "Strategy" =? _pgStrategy ] data ProductCode = ProductCode { _pcProductCodeId :: Maybe Text , _pcProductCodeType :: Maybe ProductCodeValues } deriving (Eq, Read, Show) -- | 'ProductCode' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pcProductCodeId' @::@ 'Maybe' 'Text' -- -- * 'pcProductCodeType' @::@ 'Maybe' 'ProductCodeValues' -- productCode :: ProductCode productCode = ProductCode { _pcProductCodeId = Nothing , _pcProductCodeType = Nothing } -- | The product code. pcProductCodeId :: Lens' ProductCode (Maybe Text) pcProductCodeId = lens _pcProductCodeId (\s a -> s { _pcProductCodeId = a }) -- | The type of product code. pcProductCodeType :: Lens' ProductCode (Maybe ProductCodeValues) pcProductCodeType = lens _pcProductCodeType (\s a -> s { _pcProductCodeType = a }) instance FromXML ProductCode where parseXML x = ProductCode <$> x .@? "productCode" <*> x .@? "type" instance ToQuery ProductCode where toQuery ProductCode{..} = mconcat [ "ProductCode" =? _pcProductCodeId , "Type" =? _pcProductCodeType ] data ListingStatus = ListingStatusActive -- ^ active | ListingStatusCancelled -- ^ cancelled | ListingStatusClosed -- ^ closed | ListingStatusPending -- ^ pending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ListingStatus instance FromText ListingStatus where parser = takeLowerText >>= \case "active" -> pure ListingStatusActive "cancelled" -> pure ListingStatusCancelled "closed" -> pure ListingStatusClosed "pending" -> pure ListingStatusPending e -> fail $ "Failure parsing ListingStatus from " ++ show e instance ToText ListingStatus where toText = \case ListingStatusActive -> "active" ListingStatusCancelled -> "cancelled" ListingStatusClosed -> "closed" ListingStatusPending -> "pending" instance ToByteString ListingStatus instance ToHeader ListingStatus instance ToQuery ListingStatus instance FromXML ListingStatus where parseXML = parseXMLText "ListingStatus" newtype IpRange = IpRange { _irCidrIp :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'IpRange' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'irCidrIp' @::@ 'Text' -- ipRange :: Text -- ^ 'irCidrIp' -> IpRange ipRange p1 = IpRange { _irCidrIp = p1 } -- | The CIDR range. You can either specify a CIDR range or a source security -- group, not both. irCidrIp :: Lens' IpRange Text irCidrIp = lens _irCidrIp (\s a -> s { _irCidrIp = a }) instance FromXML IpRange where parseXML x = IpRange <$> x .@ "cidrIp" instance ToQuery IpRange where toQuery IpRange{..} = mconcat [ "CidrIp" =? _irCidrIp ] data VolumeStatusInfoStatus = VSISImpaired -- ^ impaired | VSISInsufficientData -- ^ insufficient-data | VSISOk -- ^ ok deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable VolumeStatusInfoStatus instance FromText VolumeStatusInfoStatus where parser = takeLowerText >>= \case "impaired" -> pure VSISImpaired "insufficient-data" -> pure VSISInsufficientData "ok" -> pure VSISOk e -> fail $ "Failure parsing VolumeStatusInfoStatus from " ++ show e instance ToText VolumeStatusInfoStatus where toText = \case VSISImpaired -> "impaired" VSISInsufficientData -> "insufficient-data" VSISOk -> "ok" instance ToByteString VolumeStatusInfoStatus instance ToHeader VolumeStatusInfoStatus instance ToQuery VolumeStatusInfoStatus instance FromXML VolumeStatusInfoStatus where parseXML = parseXMLText "VolumeStatusInfoStatus" newtype AccountAttributeValue = AccountAttributeValue { _aavAttributeValue :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'AccountAttributeValue' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aavAttributeValue' @::@ 'Maybe' 'Text' -- accountAttributeValue :: AccountAttributeValue accountAttributeValue = AccountAttributeValue { _aavAttributeValue = Nothing } -- | The value of the attribute. aavAttributeValue :: Lens' AccountAttributeValue (Maybe Text) aavAttributeValue = lens _aavAttributeValue (\s a -> s { _aavAttributeValue = a }) instance FromXML AccountAttributeValue where parseXML x = AccountAttributeValue <$> x .@? "attributeValue" instance ToQuery AccountAttributeValue where toQuery AccountAttributeValue{..} = mconcat [ "AttributeValue" =? _aavAttributeValue ] data RIProductDescription = RIPDLinuxUNIX -- ^ Linux/UNIX | RIPDLinuxUNIXAmazonVPC -- ^ Linux/UNIX (Amazon VPC) | RIPDWindows -- ^ Windows | RIPDWindowsAmazonVPC -- ^ Windows (Amazon VPC) deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable RIProductDescription instance FromText RIProductDescription where parser = takeLowerText >>= \case "linux/unix" -> pure RIPDLinuxUNIX "linux/unix (amazon vpc)" -> pure RIPDLinuxUNIXAmazonVPC "windows" -> pure RIPDWindows "windows (amazon vpc)" -> pure RIPDWindowsAmazonVPC e -> fail $ "Failure parsing RIProductDescription from " ++ show e instance ToText RIProductDescription where toText = \case RIPDLinuxUNIX -> "Linux/UNIX" RIPDLinuxUNIXAmazonVPC -> "Linux/UNIX (Amazon VPC)" RIPDWindows -> "Windows" RIPDWindowsAmazonVPC -> "Windows (Amazon VPC)" instance ToByteString RIProductDescription instance ToHeader RIProductDescription instance ToQuery RIProductDescription instance FromXML RIProductDescription where parseXML = parseXMLText "RIProductDescription" data ReservedInstancesOffering = ReservedInstancesOffering { _rioAvailabilityZone :: Maybe Text , _rioCurrencyCode :: Maybe CurrencyCodeValues , _rioDuration :: Maybe Integer , _rioFixedPrice :: Maybe Double , _rioInstanceTenancy :: Maybe Tenancy , _rioInstanceType :: Maybe InstanceType , _rioMarketplace :: Maybe Bool , _rioOfferingType :: Maybe OfferingTypeValues , _rioPricingDetails :: List "item" PricingDetail , _rioProductDescription :: Maybe RIProductDescription , _rioRecurringCharges :: List "item" RecurringCharge , _rioReservedInstancesOfferingId :: Maybe Text , _rioUsagePrice :: Maybe Double } deriving (Eq, Read, Show) -- | 'ReservedInstancesOffering' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rioAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'rioCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues' -- -- * 'rioDuration' @::@ 'Maybe' 'Integer' -- -- * 'rioFixedPrice' @::@ 'Maybe' 'Double' -- -- * 'rioInstanceTenancy' @::@ 'Maybe' 'Tenancy' -- -- * 'rioInstanceType' @::@ 'Maybe' 'InstanceType' -- -- * 'rioMarketplace' @::@ 'Maybe' 'Bool' -- -- * 'rioOfferingType' @::@ 'Maybe' 'OfferingTypeValues' -- -- * 'rioPricingDetails' @::@ ['PricingDetail'] -- -- * 'rioProductDescription' @::@ 'Maybe' 'RIProductDescription' -- -- * 'rioRecurringCharges' @::@ ['RecurringCharge'] -- -- * 'rioReservedInstancesOfferingId' @::@ 'Maybe' 'Text' -- -- * 'rioUsagePrice' @::@ 'Maybe' 'Double' -- reservedInstancesOffering :: ReservedInstancesOffering reservedInstancesOffering = ReservedInstancesOffering { _rioReservedInstancesOfferingId = Nothing , _rioInstanceType = Nothing , _rioAvailabilityZone = Nothing , _rioDuration = Nothing , _rioUsagePrice = Nothing , _rioFixedPrice = Nothing , _rioProductDescription = Nothing , _rioInstanceTenancy = Nothing , _rioCurrencyCode = Nothing , _rioOfferingType = Nothing , _rioRecurringCharges = mempty , _rioMarketplace = Nothing , _rioPricingDetails = mempty } -- | The Availability Zone in which the Reserved Instance can be used. rioAvailabilityZone :: Lens' ReservedInstancesOffering (Maybe Text) rioAvailabilityZone = lens _rioAvailabilityZone (\s a -> s { _rioAvailabilityZone = a }) -- | The currency of the Reserved Instance offering you are purchasing. It's -- specified using ISO 4217 standard currency codes. At this time, the only -- supported currency is 'USD'. rioCurrencyCode :: Lens' ReservedInstancesOffering (Maybe CurrencyCodeValues) rioCurrencyCode = lens _rioCurrencyCode (\s a -> s { _rioCurrencyCode = a }) -- | The duration of the Reserved Instance, in seconds. rioDuration :: Lens' ReservedInstancesOffering (Maybe Integer) rioDuration = lens _rioDuration (\s a -> s { _rioDuration = a }) -- | The purchase price of the Reserved Instance. rioFixedPrice :: Lens' ReservedInstancesOffering (Maybe Double) rioFixedPrice = lens _rioFixedPrice (\s a -> s { _rioFixedPrice = a }) -- | The tenancy of the reserved instance. rioInstanceTenancy :: Lens' ReservedInstancesOffering (Maybe Tenancy) rioInstanceTenancy = lens _rioInstanceTenancy (\s a -> s { _rioInstanceTenancy = a }) -- | The instance type on which the Reserved Instance can be used. rioInstanceType :: Lens' ReservedInstancesOffering (Maybe InstanceType) rioInstanceType = lens _rioInstanceType (\s a -> s { _rioInstanceType = a }) -- | Indicates whether the offering is available through the Reserved Instance -- Marketplace (resale) or AWS. If it's a Reserved Instance Marketplace -- offering, this is 'true'. rioMarketplace :: Lens' ReservedInstancesOffering (Maybe Bool) rioMarketplace = lens _rioMarketplace (\s a -> s { _rioMarketplace = a }) -- | The Reserved Instance offering type. rioOfferingType :: Lens' ReservedInstancesOffering (Maybe OfferingTypeValues) rioOfferingType = lens _rioOfferingType (\s a -> s { _rioOfferingType = a }) -- | The pricing details of the Reserved Instance offering. rioPricingDetails :: Lens' ReservedInstancesOffering [PricingDetail] rioPricingDetails = lens _rioPricingDetails (\s a -> s { _rioPricingDetails = a }) . _List -- | The Reserved Instance description. rioProductDescription :: Lens' ReservedInstancesOffering (Maybe RIProductDescription) rioProductDescription = lens _rioProductDescription (\s a -> s { _rioProductDescription = a }) -- | The recurring charge tag assigned to the resource. rioRecurringCharges :: Lens' ReservedInstancesOffering [RecurringCharge] rioRecurringCharges = lens _rioRecurringCharges (\s a -> s { _rioRecurringCharges = a }) . _List -- | The ID of the Reserved Instance offering. rioReservedInstancesOfferingId :: Lens' ReservedInstancesOffering (Maybe Text) rioReservedInstancesOfferingId = lens _rioReservedInstancesOfferingId (\s a -> s { _rioReservedInstancesOfferingId = a }) -- | The usage price of the Reserved Instance, per hour. rioUsagePrice :: Lens' ReservedInstancesOffering (Maybe Double) rioUsagePrice = lens _rioUsagePrice (\s a -> s { _rioUsagePrice = a }) instance FromXML ReservedInstancesOffering where parseXML x = ReservedInstancesOffering <$> x .@? "availabilityZone" <*> x .@? "currencyCode" <*> x .@? "duration" <*> x .@? "fixedPrice" <*> x .@? "instanceTenancy" <*> x .@? "instanceType" <*> x .@? "marketplace" <*> x .@? "offeringType" <*> x .@? "pricingDetailsSet" .!@ mempty <*> x .@? "productDescription" <*> x .@? "recurringCharges" .!@ mempty <*> x .@? "reservedInstancesOfferingId" <*> x .@? "usagePrice" instance ToQuery ReservedInstancesOffering where toQuery ReservedInstancesOffering{..} = mconcat [ "AvailabilityZone" =? _rioAvailabilityZone , "CurrencyCode" =? _rioCurrencyCode , "Duration" =? _rioDuration , "FixedPrice" =? _rioFixedPrice , "InstanceTenancy" =? _rioInstanceTenancy , "InstanceType" =? _rioInstanceType , "Marketplace" =? _rioMarketplace , "OfferingType" =? _rioOfferingType , "PricingDetailsSet" `toQueryList` _rioPricingDetails , "ProductDescription" =? _rioProductDescription , "RecurringCharges" `toQueryList` _rioRecurringCharges , "ReservedInstancesOfferingId" =? _rioReservedInstancesOfferingId , "UsagePrice" =? _rioUsagePrice ] data ReservedInstances = ReservedInstances { _ri1AvailabilityZone :: Maybe Text , _ri1CurrencyCode :: Maybe CurrencyCodeValues , _ri1Duration :: Maybe Integer , _ri1End :: Maybe ISO8601 , _ri1FixedPrice :: Maybe Double , _ri1InstanceCount :: Maybe Int , _ri1InstanceTenancy :: Maybe Tenancy , _ri1InstanceType :: Maybe InstanceType , _ri1OfferingType :: Maybe OfferingTypeValues , _ri1ProductDescription :: Maybe RIProductDescription , _ri1RecurringCharges :: List "item" RecurringCharge , _ri1ReservedInstancesId :: Maybe Text , _ri1Start :: Maybe ISO8601 , _ri1State :: Maybe ReservedInstanceState , _ri1Tags :: List "item" Tag , _ri1UsagePrice :: Maybe Double } deriving (Eq, Read, Show) -- | 'ReservedInstances' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ri1AvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'ri1CurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues' -- -- * 'ri1Duration' @::@ 'Maybe' 'Integer' -- -- * 'ri1End' @::@ 'Maybe' 'UTCTime' -- -- * 'ri1FixedPrice' @::@ 'Maybe' 'Double' -- -- * 'ri1InstanceCount' @::@ 'Maybe' 'Int' -- -- * 'ri1InstanceTenancy' @::@ 'Maybe' 'Tenancy' -- -- * 'ri1InstanceType' @::@ 'Maybe' 'InstanceType' -- -- * 'ri1OfferingType' @::@ 'Maybe' 'OfferingTypeValues' -- -- * 'ri1ProductDescription' @::@ 'Maybe' 'RIProductDescription' -- -- * 'ri1RecurringCharges' @::@ ['RecurringCharge'] -- -- * 'ri1ReservedInstancesId' @::@ 'Maybe' 'Text' -- -- * 'ri1Start' @::@ 'Maybe' 'UTCTime' -- -- * 'ri1State' @::@ 'Maybe' 'ReservedInstanceState' -- -- * 'ri1Tags' @::@ ['Tag'] -- -- * 'ri1UsagePrice' @::@ 'Maybe' 'Double' -- reservedInstances :: ReservedInstances reservedInstances = ReservedInstances { _ri1ReservedInstancesId = Nothing , _ri1InstanceType = Nothing , _ri1AvailabilityZone = Nothing , _ri1Start = Nothing , _ri1End = Nothing , _ri1Duration = Nothing , _ri1UsagePrice = Nothing , _ri1FixedPrice = Nothing , _ri1InstanceCount = Nothing , _ri1ProductDescription = Nothing , _ri1State = Nothing , _ri1Tags = mempty , _ri1InstanceTenancy = Nothing , _ri1CurrencyCode = Nothing , _ri1OfferingType = Nothing , _ri1RecurringCharges = mempty } -- | The Availability Zone in which the Reserved Instance can be used. ri1AvailabilityZone :: Lens' ReservedInstances (Maybe Text) ri1AvailabilityZone = lens _ri1AvailabilityZone (\s a -> s { _ri1AvailabilityZone = a }) -- | The currency of the Reserved Instance. It's specified using ISO 4217 standard -- currency codes. At this time, the only supported currency is 'USD'. ri1CurrencyCode :: Lens' ReservedInstances (Maybe CurrencyCodeValues) ri1CurrencyCode = lens _ri1CurrencyCode (\s a -> s { _ri1CurrencyCode = a }) -- | The duration of the Reserved Instance, in seconds. ri1Duration :: Lens' ReservedInstances (Maybe Integer) ri1Duration = lens _ri1Duration (\s a -> s { _ri1Duration = a }) -- | The time when the Reserved Instance expires. ri1End :: Lens' ReservedInstances (Maybe UTCTime) ri1End = lens _ri1End (\s a -> s { _ri1End = a }) . mapping _Time -- | The purchase price of the Reserved Instance. ri1FixedPrice :: Lens' ReservedInstances (Maybe Double) ri1FixedPrice = lens _ri1FixedPrice (\s a -> s { _ri1FixedPrice = a }) -- | The number of Reserved Instances purchased. ri1InstanceCount :: Lens' ReservedInstances (Maybe Int) ri1InstanceCount = lens _ri1InstanceCount (\s a -> s { _ri1InstanceCount = a }) -- | The tenancy of the reserved instance. ri1InstanceTenancy :: Lens' ReservedInstances (Maybe Tenancy) ri1InstanceTenancy = lens _ri1InstanceTenancy (\s a -> s { _ri1InstanceTenancy = a }) -- | The instance type on which the Reserved Instance can be used. ri1InstanceType :: Lens' ReservedInstances (Maybe InstanceType) ri1InstanceType = lens _ri1InstanceType (\s a -> s { _ri1InstanceType = a }) -- | The Reserved Instance offering type. ri1OfferingType :: Lens' ReservedInstances (Maybe OfferingTypeValues) ri1OfferingType = lens _ri1OfferingType (\s a -> s { _ri1OfferingType = a }) -- | The Reserved Instance description. ri1ProductDescription :: Lens' ReservedInstances (Maybe RIProductDescription) ri1ProductDescription = lens _ri1ProductDescription (\s a -> s { _ri1ProductDescription = a }) -- | The recurring charge tag assigned to the resource. ri1RecurringCharges :: Lens' ReservedInstances [RecurringCharge] ri1RecurringCharges = lens _ri1RecurringCharges (\s a -> s { _ri1RecurringCharges = a }) . _List -- | The ID of the Reserved Instance. ri1ReservedInstancesId :: Lens' ReservedInstances (Maybe Text) ri1ReservedInstancesId = lens _ri1ReservedInstancesId (\s a -> s { _ri1ReservedInstancesId = a }) -- | The date and time the Reserved Instance started. ri1Start :: Lens' ReservedInstances (Maybe UTCTime) ri1Start = lens _ri1Start (\s a -> s { _ri1Start = a }) . mapping _Time -- | The state of the Reserved Instance purchase. ri1State :: Lens' ReservedInstances (Maybe ReservedInstanceState) ri1State = lens _ri1State (\s a -> s { _ri1State = a }) -- | Any tags assigned to the resource. ri1Tags :: Lens' ReservedInstances [Tag] ri1Tags = lens _ri1Tags (\s a -> s { _ri1Tags = a }) . _List -- | The usage price of the Reserved Instance, per hour. ri1UsagePrice :: Lens' ReservedInstances (Maybe Double) ri1UsagePrice = lens _ri1UsagePrice (\s a -> s { _ri1UsagePrice = a }) instance FromXML ReservedInstances where parseXML x = ReservedInstances <$> x .@? "availabilityZone" <*> x .@? "currencyCode" <*> x .@? "duration" <*> x .@? "end" <*> x .@? "fixedPrice" <*> x .@? "instanceCount" <*> x .@? "instanceTenancy" <*> x .@? "instanceType" <*> x .@? "offeringType" <*> x .@? "productDescription" <*> x .@? "recurringCharges" .!@ mempty <*> x .@? "reservedInstancesId" <*> x .@? "start" <*> x .@? "state" <*> x .@? "tagSet" .!@ mempty <*> x .@? "usagePrice" instance ToQuery ReservedInstances where toQuery ReservedInstances{..} = mconcat [ "AvailabilityZone" =? _ri1AvailabilityZone , "CurrencyCode" =? _ri1CurrencyCode , "Duration" =? _ri1Duration , "End" =? _ri1End , "FixedPrice" =? _ri1FixedPrice , "InstanceCount" =? _ri1InstanceCount , "InstanceTenancy" =? _ri1InstanceTenancy , "InstanceType" =? _ri1InstanceType , "OfferingType" =? _ri1OfferingType , "ProductDescription" =? _ri1ProductDescription , "RecurringCharges" `toQueryList` _ri1RecurringCharges , "ReservedInstancesId" =? _ri1ReservedInstancesId , "Start" =? _ri1Start , "State" =? _ri1State , "TagSet" `toQueryList` _ri1Tags , "UsagePrice" =? _ri1UsagePrice ] data DatafeedSubscriptionState = DSSActive -- ^ Active | DSSInactive -- ^ Inactive deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable DatafeedSubscriptionState instance FromText DatafeedSubscriptionState where parser = takeLowerText >>= \case "active" -> pure DSSActive "inactive" -> pure DSSInactive e -> fail $ "Failure parsing DatafeedSubscriptionState from " ++ show e instance ToText DatafeedSubscriptionState where toText = \case DSSActive -> "Active" DSSInactive -> "Inactive" instance ToByteString DatafeedSubscriptionState instance ToHeader DatafeedSubscriptionState instance ToQuery DatafeedSubscriptionState instance FromXML DatafeedSubscriptionState where parseXML = parseXMLText "DatafeedSubscriptionState" data ExportTaskState = ETSActive -- ^ active | ETSCancelled -- ^ cancelled | ETSCancelling -- ^ cancelling | ETSCompleted -- ^ completed deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ExportTaskState instance FromText ExportTaskState where parser = takeLowerText >>= \case "active" -> pure ETSActive "cancelled" -> pure ETSCancelled "cancelling" -> pure ETSCancelling "completed" -> pure ETSCompleted e -> fail $ "Failure parsing ExportTaskState from " ++ show e instance ToText ExportTaskState where toText = \case ETSActive -> "active" ETSCancelled -> "cancelled" ETSCancelling -> "cancelling" ETSCompleted -> "completed" instance ToByteString ExportTaskState instance ToHeader ExportTaskState instance ToQuery ExportTaskState instance FromXML ExportTaskState where parseXML = parseXMLText "ExportTaskState" data ProductCodeValues = Devpay -- ^ devpay | Marketplace -- ^ marketplace deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ProductCodeValues instance FromText ProductCodeValues where parser = takeLowerText >>= \case "devpay" -> pure Devpay "marketplace" -> pure Marketplace e -> fail $ "Failure parsing ProductCodeValues from " ++ show e instance ToText ProductCodeValues where toText = \case Devpay -> "devpay" Marketplace -> "marketplace" instance ToByteString ProductCodeValues instance ToHeader ProductCodeValues instance ToQuery ProductCodeValues instance FromXML ProductCodeValues where parseXML = parseXMLText "ProductCodeValues" data VpnConnection = VpnConnection { _vcCustomerGatewayConfiguration :: Text , _vcCustomerGatewayId :: Text , _vcOptions :: Maybe VpnConnectionOptions , _vcRoutes :: List "item" VpnStaticRoute , _vcState :: VpnState , _vcTags :: List "item" Tag , _vcType :: GatewayType , _vcVgwTelemetry :: List "item" VgwTelemetry , _vcVpnConnectionId :: Text , _vcVpnGatewayId :: Maybe Text } deriving (Eq, Read, Show) -- | 'VpnConnection' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vcCustomerGatewayConfiguration' @::@ 'Text' -- -- * 'vcCustomerGatewayId' @::@ 'Text' -- -- * 'vcOptions' @::@ 'Maybe' 'VpnConnectionOptions' -- -- * 'vcRoutes' @::@ ['VpnStaticRoute'] -- -- * 'vcState' @::@ 'VpnState' -- -- * 'vcTags' @::@ ['Tag'] -- -- * 'vcType' @::@ 'GatewayType' -- -- * 'vcVgwTelemetry' @::@ ['VgwTelemetry'] -- -- * 'vcVpnConnectionId' @::@ 'Text' -- -- * 'vcVpnGatewayId' @::@ 'Maybe' 'Text' -- vpnConnection :: Text -- ^ 'vcVpnConnectionId' -> VpnState -- ^ 'vcState' -> Text -- ^ 'vcCustomerGatewayConfiguration' -> GatewayType -- ^ 'vcType' -> Text -- ^ 'vcCustomerGatewayId' -> VpnConnection vpnConnection p1 p2 p3 p4 p5 = VpnConnection { _vcVpnConnectionId = p1 , _vcState = p2 , _vcCustomerGatewayConfiguration = p3 , _vcType = p4 , _vcCustomerGatewayId = p5 , _vcVpnGatewayId = Nothing , _vcTags = mempty , _vcVgwTelemetry = mempty , _vcOptions = Nothing , _vcRoutes = mempty } -- | The configuration information for the VPN connection's customer gateway (in -- the native XML format). This element is always present in the 'CreateVpnConnection' response; however, it's present in the 'DescribeVpnConnections' response only -- if the VPN connection is in the 'pending' or 'available' state. vcCustomerGatewayConfiguration :: Lens' VpnConnection Text vcCustomerGatewayConfiguration = lens _vcCustomerGatewayConfiguration (\s a -> s { _vcCustomerGatewayConfiguration = a }) -- | The ID of the customer gateway at your end of the VPN connection. vcCustomerGatewayId :: Lens' VpnConnection Text vcCustomerGatewayId = lens _vcCustomerGatewayId (\s a -> s { _vcCustomerGatewayId = a }) -- | The VPN connection options. vcOptions :: Lens' VpnConnection (Maybe VpnConnectionOptions) vcOptions = lens _vcOptions (\s a -> s { _vcOptions = a }) -- | The static routes associated with the VPN connection. vcRoutes :: Lens' VpnConnection [VpnStaticRoute] vcRoutes = lens _vcRoutes (\s a -> s { _vcRoutes = a }) . _List -- | The current state of the VPN connection. vcState :: Lens' VpnConnection VpnState vcState = lens _vcState (\s a -> s { _vcState = a }) -- | Any tags assigned to the VPN connection. vcTags :: Lens' VpnConnection [Tag] vcTags = lens _vcTags (\s a -> s { _vcTags = a }) . _List -- | The type of VPN connection. vcType :: Lens' VpnConnection GatewayType vcType = lens _vcType (\s a -> s { _vcType = a }) -- | Information about the VPN tunnel. vcVgwTelemetry :: Lens' VpnConnection [VgwTelemetry] vcVgwTelemetry = lens _vcVgwTelemetry (\s a -> s { _vcVgwTelemetry = a }) . _List -- | The ID of the VPN connection. vcVpnConnectionId :: Lens' VpnConnection Text vcVpnConnectionId = lens _vcVpnConnectionId (\s a -> s { _vcVpnConnectionId = a }) -- | The ID of the virtual private gateway at the AWS side of the VPN connection. vcVpnGatewayId :: Lens' VpnConnection (Maybe Text) vcVpnGatewayId = lens _vcVpnGatewayId (\s a -> s { _vcVpnGatewayId = a }) instance FromXML VpnConnection where parseXML x = VpnConnection <$> x .@ "customerGatewayConfiguration" <*> x .@ "customerGatewayId" <*> x .@? "options" <*> x .@? "routes" .!@ mempty <*> x .@ "state" <*> x .@? "tagSet" .!@ mempty <*> x .@ "type" <*> x .@? "vgwTelemetry" .!@ mempty <*> x .@ "vpnConnectionId" <*> x .@? "vpnGatewayId" instance ToQuery VpnConnection where toQuery VpnConnection{..} = mconcat [ "CustomerGatewayConfiguration" =? _vcCustomerGatewayConfiguration , "CustomerGatewayId" =? _vcCustomerGatewayId , "Options" =? _vcOptions , "Routes" `toQueryList` _vcRoutes , "State" =? _vcState , "TagSet" `toQueryList` _vcTags , "Type" =? _vcType , "VgwTelemetry" `toQueryList` _vcVgwTelemetry , "VpnConnectionId" =? _vcVpnConnectionId , "VpnGatewayId" =? _vcVpnGatewayId ] data InstanceState = InstanceState { _isCode :: Int , _isName :: InstanceStateName } deriving (Eq, Read, Show) -- | 'InstanceState' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'isCode' @::@ 'Int' -- -- * 'isName' @::@ 'InstanceStateName' -- instanceState :: Int -- ^ 'isCode' -> InstanceStateName -- ^ 'isName' -> InstanceState instanceState p1 p2 = InstanceState { _isCode = p1 , _isName = p2 } -- | The low byte represents the state. The high byte is an opaque internal value -- and should be ignored. -- -- '0' : 'pending' -- -- '16' : 'running' -- -- '32' : 'shutting-down' -- -- '48' : 'terminated' -- -- '64' : 'stopping' -- -- '80' : 'stopped' -- -- isCode :: Lens' InstanceState Int isCode = lens _isCode (\s a -> s { _isCode = a }) -- | The current state of the instance. isName :: Lens' InstanceState InstanceStateName isName = lens _isName (\s a -> s { _isName = a }) instance FromXML InstanceState where parseXML x = InstanceState <$> x .@ "code" <*> x .@ "name" instance ToQuery InstanceState where toQuery InstanceState{..} = mconcat [ "Code" =? _isCode , "Name" =? _isName ] data Placement = Placement { _pAvailabilityZone :: Maybe Text , _pGroupName :: Maybe Text , _pTenancy :: Maybe Tenancy } deriving (Eq, Read, Show) -- | 'Placement' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'pGroupName' @::@ 'Maybe' 'Text' -- -- * 'pTenancy' @::@ 'Maybe' 'Tenancy' -- placement :: Placement placement = Placement { _pAvailabilityZone = Nothing , _pGroupName = Nothing , _pTenancy = Nothing } -- | The Availability Zone of the instance. pAvailabilityZone :: Lens' Placement (Maybe Text) pAvailabilityZone = lens _pAvailabilityZone (\s a -> s { _pAvailabilityZone = a }) -- | The name of the placement group the instance is in (for cluster compute -- instances). pGroupName :: Lens' Placement (Maybe Text) pGroupName = lens _pGroupName (\s a -> s { _pGroupName = a }) -- | The tenancy of the instance (if the instance is running in a VPC). An -- instance with a tenancy of 'dedicated' runs on single-tenant hardware. pTenancy :: Lens' Placement (Maybe Tenancy) pTenancy = lens _pTenancy (\s a -> s { _pTenancy = a }) instance FromXML Placement where parseXML x = Placement <$> x .@? "availabilityZone" <*> x .@? "groupName" <*> x .@? "tenancy" instance ToQuery Placement where toQuery Placement{..} = mconcat [ "AvailabilityZone" =? _pAvailabilityZone , "GroupName" =? _pGroupName , "Tenancy" =? _pTenancy ] data EventCode = InstanceReboot -- ^ instance-reboot | InstanceRetirement -- ^ instance-retirement | InstanceStop -- ^ instance-stop | SystemMaintenance -- ^ system-maintenance | SystemReboot -- ^ system-reboot deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable EventCode instance FromText EventCode where parser = takeLowerText >>= \case "instance-reboot" -> pure InstanceReboot "instance-retirement" -> pure InstanceRetirement "instance-stop" -> pure InstanceStop "system-maintenance" -> pure SystemMaintenance "system-reboot" -> pure SystemReboot e -> fail $ "Failure parsing EventCode from " ++ show e instance ToText EventCode where toText = \case InstanceReboot -> "instance-reboot" InstanceRetirement -> "instance-retirement" InstanceStop -> "instance-stop" SystemMaintenance -> "system-maintenance" SystemReboot -> "system-reboot" instance ToByteString EventCode instance ToHeader EventCode instance ToQuery EventCode instance FromXML EventCode where parseXML = parseXMLText "EventCode" data SpotInstanceType = OneTime -- ^ one-time | Persistent -- ^ persistent deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SpotInstanceType instance FromText SpotInstanceType where parser = takeLowerText >>= \case "one-time" -> pure OneTime "persistent" -> pure Persistent e -> fail $ "Failure parsing SpotInstanceType from " ++ show e instance ToText SpotInstanceType where toText = \case OneTime -> "one-time" Persistent -> "persistent" instance ToByteString SpotInstanceType instance ToHeader SpotInstanceType instance ToQuery SpotInstanceType instance FromXML SpotInstanceType where parseXML = parseXMLText "SpotInstanceType" data VpcPeeringConnection = VpcPeeringConnection { _vpc1AccepterVpcInfo :: Maybe VpcPeeringConnectionVpcInfo , _vpc1ExpirationTime :: Maybe ISO8601 , _vpc1RequesterVpcInfo :: Maybe VpcPeeringConnectionVpcInfo , _vpc1Status :: Maybe VpcPeeringConnectionStateReason , _vpc1Tags :: List "item" Tag , _vpc1VpcPeeringConnectionId :: Maybe Text } deriving (Eq, Read, Show) -- | 'VpcPeeringConnection' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vpc1AccepterVpcInfo' @::@ 'Maybe' 'VpcPeeringConnectionVpcInfo' -- -- * 'vpc1ExpirationTime' @::@ 'Maybe' 'UTCTime' -- -- * 'vpc1RequesterVpcInfo' @::@ 'Maybe' 'VpcPeeringConnectionVpcInfo' -- -- * 'vpc1Status' @::@ 'Maybe' 'VpcPeeringConnectionStateReason' -- -- * 'vpc1Tags' @::@ ['Tag'] -- -- * 'vpc1VpcPeeringConnectionId' @::@ 'Maybe' 'Text' -- vpcPeeringConnection :: VpcPeeringConnection vpcPeeringConnection = VpcPeeringConnection { _vpc1AccepterVpcInfo = Nothing , _vpc1ExpirationTime = Nothing , _vpc1RequesterVpcInfo = Nothing , _vpc1Status = Nothing , _vpc1Tags = mempty , _vpc1VpcPeeringConnectionId = Nothing } -- | The information of the peer VPC. vpc1AccepterVpcInfo :: Lens' VpcPeeringConnection (Maybe VpcPeeringConnectionVpcInfo) vpc1AccepterVpcInfo = lens _vpc1AccepterVpcInfo (\s a -> s { _vpc1AccepterVpcInfo = a }) -- | The time that an unaccepted VPC peering connection will expire. vpc1ExpirationTime :: Lens' VpcPeeringConnection (Maybe UTCTime) vpc1ExpirationTime = lens _vpc1ExpirationTime (\s a -> s { _vpc1ExpirationTime = a }) . mapping _Time -- | The information of the requester VPC. vpc1RequesterVpcInfo :: Lens' VpcPeeringConnection (Maybe VpcPeeringConnectionVpcInfo) vpc1RequesterVpcInfo = lens _vpc1RequesterVpcInfo (\s a -> s { _vpc1RequesterVpcInfo = a }) -- | The status of the VPC peering connection. vpc1Status :: Lens' VpcPeeringConnection (Maybe VpcPeeringConnectionStateReason) vpc1Status = lens _vpc1Status (\s a -> s { _vpc1Status = a }) -- | Any tags assigned to the resource. vpc1Tags :: Lens' VpcPeeringConnection [Tag] vpc1Tags = lens _vpc1Tags (\s a -> s { _vpc1Tags = a }) . _List -- | The ID of the VPC peering connection. vpc1VpcPeeringConnectionId :: Lens' VpcPeeringConnection (Maybe Text) vpc1VpcPeeringConnectionId = lens _vpc1VpcPeeringConnectionId (\s a -> s { _vpc1VpcPeeringConnectionId = a }) instance FromXML VpcPeeringConnection where parseXML x = VpcPeeringConnection <$> x .@? "accepterVpcInfo" <*> x .@? "expirationTime" <*> x .@? "requesterVpcInfo" <*> x .@? "status" <*> x .@? "tagSet" .!@ mempty <*> x .@? "vpcPeeringConnectionId" instance ToQuery VpcPeeringConnection where toQuery VpcPeeringConnection{..} = mconcat [ "AccepterVpcInfo" =? _vpc1AccepterVpcInfo , "ExpirationTime" =? _vpc1ExpirationTime , "RequesterVpcInfo" =? _vpc1RequesterVpcInfo , "Status" =? _vpc1Status , "TagSet" `toQueryList` _vpc1Tags , "VpcPeeringConnectionId" =? _vpc1VpcPeeringConnectionId ] data S3Storage = S3Storage { _ssAWSAccessKeyId :: Maybe Text , _ssBucket :: Maybe Text , _ssPrefix :: Maybe Text , _ssUploadPolicy :: Maybe Base64 , _ssUploadPolicySignature :: Maybe Text } deriving (Eq, Read, Show) -- | 'S3Storage' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ssAWSAccessKeyId' @::@ 'Maybe' 'Text' -- -- * 'ssBucket' @::@ 'Maybe' 'Text' -- -- * 'ssPrefix' @::@ 'Maybe' 'Text' -- -- * 'ssUploadPolicy' @::@ 'Maybe' 'Base64' -- -- * 'ssUploadPolicySignature' @::@ 'Maybe' 'Text' -- s3Storage :: S3Storage s3Storage = S3Storage { _ssBucket = Nothing , _ssPrefix = Nothing , _ssAWSAccessKeyId = Nothing , _ssUploadPolicy = Nothing , _ssUploadPolicySignature = Nothing } -- | The access key ID of the owner of the bucket. Before you specify a value for -- your access key ID, review and follow the guidance in <http://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html Best Practices forManaging AWS Access Keys>. ssAWSAccessKeyId :: Lens' S3Storage (Maybe Text) ssAWSAccessKeyId = lens _ssAWSAccessKeyId (\s a -> s { _ssAWSAccessKeyId = a }) -- | The bucket in which to store the AMI. You can specify a bucket that you -- already own or a new bucket that Amazon EC2 creates on your behalf. If you -- specify a bucket that belongs to someone else, Amazon EC2 returns an error. ssBucket :: Lens' S3Storage (Maybe Text) ssBucket = lens _ssBucket (\s a -> s { _ssBucket = a }) -- | The beginning of the file name of the AMI. ssPrefix :: Lens' S3Storage (Maybe Text) ssPrefix = lens _ssPrefix (\s a -> s { _ssPrefix = a }) -- | A Base64-encoded Amazon S3 upload policy that gives Amazon EC2 permission to -- upload items into Amazon S3 on your behalf. ssUploadPolicy :: Lens' S3Storage (Maybe Base64) ssUploadPolicy = lens _ssUploadPolicy (\s a -> s { _ssUploadPolicy = a }) -- | The signature of the Base64 encoded JSON document. ssUploadPolicySignature :: Lens' S3Storage (Maybe Text) ssUploadPolicySignature = lens _ssUploadPolicySignature (\s a -> s { _ssUploadPolicySignature = a }) instance FromXML S3Storage where parseXML x = S3Storage <$> x .@? "AWSAccessKeyId" <*> x .@? "bucket" <*> x .@? "prefix" <*> x .@? "uploadPolicy" <*> x .@? "uploadPolicySignature" instance ToQuery S3Storage where toQuery S3Storage{..} = mconcat [ "AWSAccessKeyId" =? _ssAWSAccessKeyId , "Bucket" =? _ssBucket , "Prefix" =? _ssPrefix , "UploadPolicy" =? _ssUploadPolicy , "UploadPolicySignature" =? _ssUploadPolicySignature ] data VgwTelemetry = VgwTelemetry { _vtAcceptedRouteCount :: Maybe Int , _vtLastStatusChange :: Maybe ISO8601 , _vtOutsideIpAddress :: Maybe Text , _vtStatus :: Maybe TelemetryStatus , _vtStatusMessage :: Maybe Text } deriving (Eq, Read, Show) -- | 'VgwTelemetry' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vtAcceptedRouteCount' @::@ 'Maybe' 'Int' -- -- * 'vtLastStatusChange' @::@ 'Maybe' 'UTCTime' -- -- * 'vtOutsideIpAddress' @::@ 'Maybe' 'Text' -- -- * 'vtStatus' @::@ 'Maybe' 'TelemetryStatus' -- -- * 'vtStatusMessage' @::@ 'Maybe' 'Text' -- vgwTelemetry :: VgwTelemetry vgwTelemetry = VgwTelemetry { _vtOutsideIpAddress = Nothing , _vtStatus = Nothing , _vtLastStatusChange = Nothing , _vtStatusMessage = Nothing , _vtAcceptedRouteCount = Nothing } -- | The number of accepted routes. vtAcceptedRouteCount :: Lens' VgwTelemetry (Maybe Int) vtAcceptedRouteCount = lens _vtAcceptedRouteCount (\s a -> s { _vtAcceptedRouteCount = a }) -- | The date and time of the last change in status. vtLastStatusChange :: Lens' VgwTelemetry (Maybe UTCTime) vtLastStatusChange = lens _vtLastStatusChange (\s a -> s { _vtLastStatusChange = a }) . mapping _Time -- | The Internet-routable IP address of the virtual private gateway's outside -- interface. vtOutsideIpAddress :: Lens' VgwTelemetry (Maybe Text) vtOutsideIpAddress = lens _vtOutsideIpAddress (\s a -> s { _vtOutsideIpAddress = a }) -- | The status of the VPN tunnel. vtStatus :: Lens' VgwTelemetry (Maybe TelemetryStatus) vtStatus = lens _vtStatus (\s a -> s { _vtStatus = a }) -- | If an error occurs, a description of the error. vtStatusMessage :: Lens' VgwTelemetry (Maybe Text) vtStatusMessage = lens _vtStatusMessage (\s a -> s { _vtStatusMessage = a }) instance FromXML VgwTelemetry where parseXML x = VgwTelemetry <$> x .@? "acceptedRouteCount" <*> x .@? "lastStatusChange" <*> x .@? "outsideIpAddress" <*> x .@? "status" <*> x .@? "statusMessage" instance ToQuery VgwTelemetry where toQuery VgwTelemetry{..} = mconcat [ "AcceptedRouteCount" =? _vtAcceptedRouteCount , "LastStatusChange" =? _vtLastStatusChange , "OutsideIpAddress" =? _vtOutsideIpAddress , "Status" =? _vtStatus , "StatusMessage" =? _vtStatusMessage ] data VpnStaticRoute = VpnStaticRoute { _vsrDestinationCidrBlock :: Maybe Text , _vsrSource :: Maybe VpnStaticRouteSource , _vsrState :: Maybe VpnState } deriving (Eq, Read, Show) -- | 'VpnStaticRoute' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vsrDestinationCidrBlock' @::@ 'Maybe' 'Text' -- -- * 'vsrSource' @::@ 'Maybe' 'VpnStaticRouteSource' -- -- * 'vsrState' @::@ 'Maybe' 'VpnState' -- vpnStaticRoute :: VpnStaticRoute vpnStaticRoute = VpnStaticRoute { _vsrDestinationCidrBlock = Nothing , _vsrSource = Nothing , _vsrState = Nothing } -- | The CIDR block associated with the local subnet of the customer data center. vsrDestinationCidrBlock :: Lens' VpnStaticRoute (Maybe Text) vsrDestinationCidrBlock = lens _vsrDestinationCidrBlock (\s a -> s { _vsrDestinationCidrBlock = a }) -- | Indicates how the routes were provided. vsrSource :: Lens' VpnStaticRoute (Maybe VpnStaticRouteSource) vsrSource = lens _vsrSource (\s a -> s { _vsrSource = a }) -- | The current state of the static route. vsrState :: Lens' VpnStaticRoute (Maybe VpnState) vsrState = lens _vsrState (\s a -> s { _vsrState = a }) instance FromXML VpnStaticRoute where parseXML x = VpnStaticRoute <$> x .@? "destinationCidrBlock" <*> x .@? "source" <*> x .@? "state" instance ToQuery VpnStaticRoute where toQuery VpnStaticRoute{..} = mconcat [ "DestinationCidrBlock" =? _vsrDestinationCidrBlock , "Source" =? _vsrSource , "State" =? _vsrState ] data InstanceStateName = ISNPending -- ^ pending | ISNRunning -- ^ running | ISNShuttingDown -- ^ shutting-down | ISNStopped -- ^ stopped | ISNStopping -- ^ stopping | ISNTerminated -- ^ terminated deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable InstanceStateName instance FromText InstanceStateName where parser = takeLowerText >>= \case "pending" -> pure ISNPending "running" -> pure ISNRunning "shutting-down" -> pure ISNShuttingDown "stopped" -> pure ISNStopped "stopping" -> pure ISNStopping "terminated" -> pure ISNTerminated e -> fail $ "Failure parsing InstanceStateName from " ++ show e instance ToText InstanceStateName where toText = \case ISNPending -> "pending" ISNRunning -> "running" ISNShuttingDown -> "shutting-down" ISNStopped -> "stopped" ISNStopping -> "stopping" ISNTerminated -> "terminated" instance ToByteString InstanceStateName instance ToHeader InstanceStateName instance ToQuery InstanceStateName instance FromXML InstanceStateName where parseXML = parseXMLText "InstanceStateName" data Instance = Instance { _i1AmiLaunchIndex :: Int , _i1Architecture :: ArchitectureValues , _i1BlockDeviceMappings :: List "item" InstanceBlockDeviceMapping , _i1ClientToken :: Maybe Text , _i1EbsOptimized :: Bool , _i1Hypervisor :: HypervisorType , _i1IamInstanceProfile :: Maybe IamInstanceProfile , _i1ImageId :: Text , _i1InstanceId :: Text , _i1InstanceLifecycle :: Maybe InstanceLifecycleType , _i1InstanceType :: InstanceType , _i1KernelId :: Maybe Text , _i1KeyName :: Maybe Text , _i1LaunchTime :: ISO8601 , _i1Monitoring :: Monitoring , _i1NetworkInterfaces :: List "item" InstanceNetworkInterface , _i1Placement :: Placement , _i1Platform :: Maybe PlatformValues , _i1PrivateDnsName :: Maybe Text , _i1PrivateIpAddress :: Maybe Text , _i1ProductCodes :: List "item" ProductCode , _i1PublicDnsName :: Maybe Text , _i1PublicIpAddress :: Maybe Text , _i1RamdiskId :: Maybe Text , _i1RootDeviceName :: Maybe Text , _i1RootDeviceType :: DeviceType , _i1SecurityGroups :: List "item" GroupIdentifier , _i1SourceDestCheck :: Maybe Bool , _i1SpotInstanceRequestId :: Maybe Text , _i1SriovNetSupport :: Maybe Text , _i1State :: InstanceState , _i1StateReason :: Maybe StateReason , _i1StateTransitionReason :: Maybe Text , _i1SubnetId :: Maybe Text , _i1Tags :: List "item" Tag , _i1VirtualizationType :: VirtualizationType , _i1VpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'Instance' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'i1AmiLaunchIndex' @::@ 'Int' -- -- * 'i1Architecture' @::@ 'ArchitectureValues' -- -- * 'i1BlockDeviceMappings' @::@ ['InstanceBlockDeviceMapping'] -- -- * 'i1ClientToken' @::@ 'Maybe' 'Text' -- -- * 'i1EbsOptimized' @::@ 'Bool' -- -- * 'i1Hypervisor' @::@ 'HypervisorType' -- -- * 'i1IamInstanceProfile' @::@ 'Maybe' 'IamInstanceProfile' -- -- * 'i1ImageId' @::@ 'Text' -- -- * 'i1InstanceId' @::@ 'Text' -- -- * 'i1InstanceLifecycle' @::@ 'Maybe' 'InstanceLifecycleType' -- -- * 'i1InstanceType' @::@ 'InstanceType' -- -- * 'i1KernelId' @::@ 'Maybe' 'Text' -- -- * 'i1KeyName' @::@ 'Maybe' 'Text' -- -- * 'i1LaunchTime' @::@ 'UTCTime' -- -- * 'i1Monitoring' @::@ 'Monitoring' -- -- * 'i1NetworkInterfaces' @::@ ['InstanceNetworkInterface'] -- -- * 'i1Placement' @::@ 'Placement' -- -- * 'i1Platform' @::@ 'Maybe' 'PlatformValues' -- -- * 'i1PrivateDnsName' @::@ 'Maybe' 'Text' -- -- * 'i1PrivateIpAddress' @::@ 'Maybe' 'Text' -- -- * 'i1ProductCodes' @::@ ['ProductCode'] -- -- * 'i1PublicDnsName' @::@ 'Maybe' 'Text' -- -- * 'i1PublicIpAddress' @::@ 'Maybe' 'Text' -- -- * 'i1RamdiskId' @::@ 'Maybe' 'Text' -- -- * 'i1RootDeviceName' @::@ 'Maybe' 'Text' -- -- * 'i1RootDeviceType' @::@ 'DeviceType' -- -- * 'i1SecurityGroups' @::@ ['GroupIdentifier'] -- -- * 'i1SourceDestCheck' @::@ 'Maybe' 'Bool' -- -- * 'i1SpotInstanceRequestId' @::@ 'Maybe' 'Text' -- -- * 'i1SriovNetSupport' @::@ 'Maybe' 'Text' -- -- * 'i1State' @::@ 'InstanceState' -- -- * 'i1StateReason' @::@ 'Maybe' 'StateReason' -- -- * 'i1StateTransitionReason' @::@ 'Maybe' 'Text' -- -- * 'i1SubnetId' @::@ 'Maybe' 'Text' -- -- * 'i1Tags' @::@ ['Tag'] -- -- * 'i1VirtualizationType' @::@ 'VirtualizationType' -- -- * 'i1VpcId' @::@ 'Maybe' 'Text' -- instance' :: Text -- ^ 'i1InstanceId' -> Text -- ^ 'i1ImageId' -> InstanceState -- ^ 'i1State' -> Int -- ^ 'i1AmiLaunchIndex' -> InstanceType -- ^ 'i1InstanceType' -> UTCTime -- ^ 'i1LaunchTime' -> Placement -- ^ 'i1Placement' -> Monitoring -- ^ 'i1Monitoring' -> ArchitectureValues -- ^ 'i1Architecture' -> DeviceType -- ^ 'i1RootDeviceType' -> VirtualizationType -- ^ 'i1VirtualizationType' -> HypervisorType -- ^ 'i1Hypervisor' -> Bool -- ^ 'i1EbsOptimized' -> Instance instance' p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 = Instance { _i1InstanceId = p1 , _i1ImageId = p2 , _i1State = p3 , _i1AmiLaunchIndex = p4 , _i1InstanceType = p5 , _i1LaunchTime = withIso _Time (const id) p6 , _i1Placement = p7 , _i1Monitoring = p8 , _i1Architecture = p9 , _i1RootDeviceType = p10 , _i1VirtualizationType = p11 , _i1Hypervisor = p12 , _i1EbsOptimized = p13 , _i1PrivateDnsName = Nothing , _i1PublicDnsName = Nothing , _i1StateTransitionReason = Nothing , _i1KeyName = Nothing , _i1ProductCodes = mempty , _i1KernelId = Nothing , _i1RamdiskId = Nothing , _i1Platform = Nothing , _i1SubnetId = Nothing , _i1VpcId = Nothing , _i1PrivateIpAddress = Nothing , _i1PublicIpAddress = Nothing , _i1StateReason = Nothing , _i1RootDeviceName = Nothing , _i1BlockDeviceMappings = mempty , _i1InstanceLifecycle = Nothing , _i1SpotInstanceRequestId = Nothing , _i1ClientToken = Nothing , _i1Tags = mempty , _i1SecurityGroups = mempty , _i1SourceDestCheck = Nothing , _i1NetworkInterfaces = mempty , _i1IamInstanceProfile = Nothing , _i1SriovNetSupport = Nothing } -- | The AMI launch index, which can be used to find this instance in the launch -- group. i1AmiLaunchIndex :: Lens' Instance Int i1AmiLaunchIndex = lens _i1AmiLaunchIndex (\s a -> s { _i1AmiLaunchIndex = a }) -- | The architecture of the image. i1Architecture :: Lens' Instance ArchitectureValues i1Architecture = lens _i1Architecture (\s a -> s { _i1Architecture = a }) -- | Any block device mapping entries for the instance. i1BlockDeviceMappings :: Lens' Instance [InstanceBlockDeviceMapping] i1BlockDeviceMappings = lens _i1BlockDeviceMappings (\s a -> s { _i1BlockDeviceMappings = a }) . _List -- | The idempotency token you provided when you launched the instance. i1ClientToken :: Lens' Instance (Maybe Text) i1ClientToken = lens _i1ClientToken (\s a -> s { _i1ClientToken = a }) -- | 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 I/O performance. This optimization isn't available -- with all instance types. Additional usage charges apply when using an EBS -- Optimized instance. i1EbsOptimized :: Lens' Instance Bool i1EbsOptimized = lens _i1EbsOptimized (\s a -> s { _i1EbsOptimized = a }) -- | The hypervisor type of the instance. i1Hypervisor :: Lens' Instance HypervisorType i1Hypervisor = lens _i1Hypervisor (\s a -> s { _i1Hypervisor = a }) -- | The IAM instance profile associated with the instance. i1IamInstanceProfile :: Lens' Instance (Maybe IamInstanceProfile) i1IamInstanceProfile = lens _i1IamInstanceProfile (\s a -> s { _i1IamInstanceProfile = a }) -- | The ID of the AMI used to launch the instance. i1ImageId :: Lens' Instance Text i1ImageId = lens _i1ImageId (\s a -> s { _i1ImageId = a }) -- | The ID of the instance. i1InstanceId :: Lens' Instance Text i1InstanceId = lens _i1InstanceId (\s a -> s { _i1InstanceId = a }) -- | Indicates whether this is a Spot Instance. i1InstanceLifecycle :: Lens' Instance (Maybe InstanceLifecycleType) i1InstanceLifecycle = lens _i1InstanceLifecycle (\s a -> s { _i1InstanceLifecycle = a }) -- | The instance type. i1InstanceType :: Lens' Instance InstanceType i1InstanceType = lens _i1InstanceType (\s a -> s { _i1InstanceType = a }) -- | The kernel associated with this instance. i1KernelId :: Lens' Instance (Maybe Text) i1KernelId = lens _i1KernelId (\s a -> s { _i1KernelId = a }) -- | The name of the key pair, if this instance was launched with an associated -- key pair. i1KeyName :: Lens' Instance (Maybe Text) i1KeyName = lens _i1KeyName (\s a -> s { _i1KeyName = a }) -- | The time the instance was launched. i1LaunchTime :: Lens' Instance UTCTime i1LaunchTime = lens _i1LaunchTime (\s a -> s { _i1LaunchTime = a }) . _Time -- | The monitoring information for the instance. i1Monitoring :: Lens' Instance Monitoring i1Monitoring = lens _i1Monitoring (\s a -> s { _i1Monitoring = a }) -- | [EC2-VPC] One or more network interfaces for the instance. i1NetworkInterfaces :: Lens' Instance [InstanceNetworkInterface] i1NetworkInterfaces = lens _i1NetworkInterfaces (\s a -> s { _i1NetworkInterfaces = a }) . _List -- | The location where the instance launched. i1Placement :: Lens' Instance Placement i1Placement = lens _i1Placement (\s a -> s { _i1Placement = a }) -- | The value is 'Windows' for Windows instances; otherwise blank. i1Platform :: Lens' Instance (Maybe PlatformValues) i1Platform = lens _i1Platform (\s a -> s { _i1Platform = a }) -- | The private DNS name assigned to the instance. This DNS name can only be used -- inside the Amazon EC2 network. This name is not available until the instance -- enters the 'running' state. i1PrivateDnsName :: Lens' Instance (Maybe Text) i1PrivateDnsName = lens _i1PrivateDnsName (\s a -> s { _i1PrivateDnsName = a }) -- | The private IP address assigned to the instance. i1PrivateIpAddress :: Lens' Instance (Maybe Text) i1PrivateIpAddress = lens _i1PrivateIpAddress (\s a -> s { _i1PrivateIpAddress = a }) -- | The product codes attached to this instance. i1ProductCodes :: Lens' Instance [ProductCode] i1ProductCodes = lens _i1ProductCodes (\s a -> s { _i1ProductCodes = a }) . _List -- | The public DNS name assigned to the instance. This name is not available -- until the instance enters the 'running' state. i1PublicDnsName :: Lens' Instance (Maybe Text) i1PublicDnsName = lens _i1PublicDnsName (\s a -> s { _i1PublicDnsName = a }) -- | The public IP address assigned to the instance. i1PublicIpAddress :: Lens' Instance (Maybe Text) i1PublicIpAddress = lens _i1PublicIpAddress (\s a -> s { _i1PublicIpAddress = a }) -- | The RAM disk associated with this instance. i1RamdiskId :: Lens' Instance (Maybe Text) i1RamdiskId = lens _i1RamdiskId (\s a -> s { _i1RamdiskId = a }) -- | The root device name (for example, '/dev/sda1' or '/dev/xvda'). i1RootDeviceName :: Lens' Instance (Maybe Text) i1RootDeviceName = lens _i1RootDeviceName (\s a -> s { _i1RootDeviceName = a }) -- | The root device type used by the AMI. The AMI can use an Amazon EBS volume or -- an instance store volume. i1RootDeviceType :: Lens' Instance DeviceType i1RootDeviceType = lens _i1RootDeviceType (\s a -> s { _i1RootDeviceType = a }) -- | One or more security groups for the instance. i1SecurityGroups :: Lens' Instance [GroupIdentifier] i1SecurityGroups = lens _i1SecurityGroups (\s a -> s { _i1SecurityGroups = a }) . _List -- | Specifies whether to enable an instance launched in a VPC to perform NAT. -- This controls whether source/destination checking is enabled on the instance. -- A value of 'true' means checking is enabled, and 'false' means checking is -- disabled. The value must be 'false' for the instance to perform NAT. For more -- information, see <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html NAT Instances> in the /Amazon Virtual Private Cloud User Guide/. i1SourceDestCheck :: Lens' Instance (Maybe Bool) i1SourceDestCheck = lens _i1SourceDestCheck (\s a -> s { _i1SourceDestCheck = a }) -- | The ID of the Spot Instance request. i1SpotInstanceRequestId :: Lens' Instance (Maybe Text) i1SpotInstanceRequestId = lens _i1SpotInstanceRequestId (\s a -> s { _i1SpotInstanceRequestId = a }) -- | Specifies whether enhanced networking is enabled. i1SriovNetSupport :: Lens' Instance (Maybe Text) i1SriovNetSupport = lens _i1SriovNetSupport (\s a -> s { _i1SriovNetSupport = a }) -- | The current state of the instance. i1State :: Lens' Instance InstanceState i1State = lens _i1State (\s a -> s { _i1State = a }) -- | The reason for the most recent state transition. i1StateReason :: Lens' Instance (Maybe StateReason) i1StateReason = lens _i1StateReason (\s a -> s { _i1StateReason = a }) -- | The reason for the most recent state transition. This might be an empty -- string. i1StateTransitionReason :: Lens' Instance (Maybe Text) i1StateTransitionReason = lens _i1StateTransitionReason (\s a -> s { _i1StateTransitionReason = a }) -- | The ID of the subnet in which the instance is running. i1SubnetId :: Lens' Instance (Maybe Text) i1SubnetId = lens _i1SubnetId (\s a -> s { _i1SubnetId = a }) -- | Any tags assigned to the instance. i1Tags :: Lens' Instance [Tag] i1Tags = lens _i1Tags (\s a -> s { _i1Tags = a }) . _List -- | The virtualization type of the instance. i1VirtualizationType :: Lens' Instance VirtualizationType i1VirtualizationType = lens _i1VirtualizationType (\s a -> s { _i1VirtualizationType = a }) -- | The ID of the VPC in which the instance is running. i1VpcId :: Lens' Instance (Maybe Text) i1VpcId = lens _i1VpcId (\s a -> s { _i1VpcId = a }) instance FromXML Instance where parseXML x = Instance <$> x .@ "amiLaunchIndex" <*> x .@ "architecture" <*> x .@? "blockDeviceMapping" .!@ mempty <*> x .@? "clientToken" <*> x .@ "ebsOptimized" <*> x .@ "hypervisor" <*> x .@? "iamInstanceProfile" <*> x .@ "imageId" <*> x .@ "instanceId" <*> x .@? "instanceLifecycle" <*> x .@ "instanceType" <*> x .@? "kernelId" <*> x .@? "keyName" <*> x .@ "launchTime" <*> x .@ "monitoring" <*> x .@? "networkInterfaceSet" .!@ mempty <*> x .@ "placement" <*> x .@? "platform" <*> x .@? "privateDnsName" <*> x .@? "privateIpAddress" <*> x .@? "productCodes" .!@ mempty <*> x .@? "dnsName" <*> x .@? "ipAddress" <*> x .@? "ramdiskId" <*> x .@? "rootDeviceName" <*> x .@ "rootDeviceType" <*> x .@? "groupSet" .!@ mempty <*> x .@? "sourceDestCheck" <*> x .@? "spotInstanceRequestId" <*> x .@? "sriovNetSupport" <*> x .@ "instanceState" <*> x .@? "stateReason" <*> x .@? "reason" <*> x .@? "subnetId" <*> x .@? "tagSet" .!@ mempty <*> x .@ "virtualizationType" <*> x .@? "vpcId" instance ToQuery Instance where toQuery Instance{..} = mconcat [ "AmiLaunchIndex" =? _i1AmiLaunchIndex , "Architecture" =? _i1Architecture , "BlockDeviceMapping" `toQueryList` _i1BlockDeviceMappings , "ClientToken" =? _i1ClientToken , "EbsOptimized" =? _i1EbsOptimized , "Hypervisor" =? _i1Hypervisor , "IamInstanceProfile" =? _i1IamInstanceProfile , "ImageId" =? _i1ImageId , "InstanceId" =? _i1InstanceId , "InstanceLifecycle" =? _i1InstanceLifecycle , "InstanceType" =? _i1InstanceType , "KernelId" =? _i1KernelId , "KeyName" =? _i1KeyName , "LaunchTime" =? _i1LaunchTime , "Monitoring" =? _i1Monitoring , "NetworkInterfaceSet" `toQueryList` _i1NetworkInterfaces , "Placement" =? _i1Placement , "Platform" =? _i1Platform , "PrivateDnsName" =? _i1PrivateDnsName , "PrivateIpAddress" =? _i1PrivateIpAddress , "ProductCodes" `toQueryList` _i1ProductCodes , "DnsName" =? _i1PublicDnsName , "IpAddress" =? _i1PublicIpAddress , "RamdiskId" =? _i1RamdiskId , "RootDeviceName" =? _i1RootDeviceName , "RootDeviceType" =? _i1RootDeviceType , "GroupSet" `toQueryList` _i1SecurityGroups , "SourceDestCheck" =? _i1SourceDestCheck , "SpotInstanceRequestId" =? _i1SpotInstanceRequestId , "SriovNetSupport" =? _i1SriovNetSupport , "InstanceState" =? _i1State , "StateReason" =? _i1StateReason , "Reason" =? _i1StateTransitionReason , "SubnetId" =? _i1SubnetId , "TagSet" `toQueryList` _i1Tags , "VirtualizationType" =? _i1VirtualizationType , "VpcId" =? _i1VpcId ] data ExportTask = ExportTask { _etDescription :: Text , _etExportTaskId :: Text , _etExportToS3Task :: ExportToS3Task , _etInstanceExportDetails :: InstanceExportDetails , _etState :: ExportTaskState , _etStatusMessage :: Text } deriving (Eq, Read, Show) -- | 'ExportTask' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'etDescription' @::@ 'Text' -- -- * 'etExportTaskId' @::@ 'Text' -- -- * 'etExportToS3Task' @::@ 'ExportToS3Task' -- -- * 'etInstanceExportDetails' @::@ 'InstanceExportDetails' -- -- * 'etState' @::@ 'ExportTaskState' -- -- * 'etStatusMessage' @::@ 'Text' -- exportTask :: Text -- ^ 'etExportTaskId' -> Text -- ^ 'etDescription' -> ExportTaskState -- ^ 'etState' -> Text -- ^ 'etStatusMessage' -> InstanceExportDetails -- ^ 'etInstanceExportDetails' -> ExportToS3Task -- ^ 'etExportToS3Task' -> ExportTask exportTask p1 p2 p3 p4 p5 p6 = ExportTask { _etExportTaskId = p1 , _etDescription = p2 , _etState = p3 , _etStatusMessage = p4 , _etInstanceExportDetails = p5 , _etExportToS3Task = p6 } -- | A description of the resource being exported. etDescription :: Lens' ExportTask Text etDescription = lens _etDescription (\s a -> s { _etDescription = a }) -- | The ID of the export task. etExportTaskId :: Lens' ExportTask Text etExportTaskId = lens _etExportTaskId (\s a -> s { _etExportTaskId = a }) etExportToS3Task :: Lens' ExportTask ExportToS3Task etExportToS3Task = lens _etExportToS3Task (\s a -> s { _etExportToS3Task = a }) -- | The instance being exported. etInstanceExportDetails :: Lens' ExportTask InstanceExportDetails etInstanceExportDetails = lens _etInstanceExportDetails (\s a -> s { _etInstanceExportDetails = a }) -- | The state of the conversion task. etState :: Lens' ExportTask ExportTaskState etState = lens _etState (\s a -> s { _etState = a }) -- | The status message related to the export task. etStatusMessage :: Lens' ExportTask Text etStatusMessage = lens _etStatusMessage (\s a -> s { _etStatusMessage = a }) instance FromXML ExportTask where parseXML x = ExportTask <$> x .@ "description" <*> x .@ "exportTaskId" <*> x .@ "exportToS3" <*> x .@ "instanceExport" <*> x .@ "state" <*> x .@ "statusMessage" instance ToQuery ExportTask where toQuery ExportTask{..} = mconcat [ "Description" =? _etDescription , "ExportTaskId" =? _etExportTaskId , "ExportToS3" =? _etExportToS3Task , "InstanceExport" =? _etInstanceExportDetails , "State" =? _etState , "StatusMessage" =? _etStatusMessage ] data ResetImageAttributeName = RIANLaunchPermission -- ^ launchPermission deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ResetImageAttributeName instance FromText ResetImageAttributeName where parser = takeLowerText >>= \case "launchpermission" -> pure RIANLaunchPermission e -> fail $ "Failure parsing ResetImageAttributeName from " ++ show e instance ToText ResetImageAttributeName where toText RIANLaunchPermission = "launchPermission" instance ToByteString ResetImageAttributeName instance ToHeader ResetImageAttributeName instance ToQuery ResetImageAttributeName instance FromXML ResetImageAttributeName where parseXML = parseXMLText "ResetImageAttributeName" data RequestSpotLaunchSpecification = RequestSpotLaunchSpecification { _rslsAddressingType :: Maybe Text , _rslsBlockDeviceMappings :: List "item" BlockDeviceMapping , _rslsEbsOptimized :: Maybe Bool , _rslsIamInstanceProfile :: Maybe IamInstanceProfileSpecification , _rslsImageId :: Maybe Text , _rslsInstanceType :: Maybe InstanceType , _rslsKernelId :: Maybe Text , _rslsKeyName :: Maybe Text , _rslsMonitoring :: Maybe RunInstancesMonitoringEnabled , _rslsNetworkInterfaces :: List "item" InstanceNetworkInterfaceSpecification , _rslsPlacement :: Maybe SpotPlacement , _rslsRamdiskId :: Maybe Text , _rslsSecurityGroupIds :: List "item" Text , _rslsSecurityGroups :: List "item" Text , _rslsSubnetId :: Maybe Text , _rslsUserData :: Maybe Text } deriving (Eq, Read, Show) -- | 'RequestSpotLaunchSpecification' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rslsAddressingType' @::@ 'Maybe' 'Text' -- -- * 'rslsBlockDeviceMappings' @::@ ['BlockDeviceMapping'] -- -- * 'rslsEbsOptimized' @::@ 'Maybe' 'Bool' -- -- * 'rslsIamInstanceProfile' @::@ 'Maybe' 'IamInstanceProfileSpecification' -- -- * 'rslsImageId' @::@ 'Maybe' 'Text' -- -- * 'rslsInstanceType' @::@ 'Maybe' 'InstanceType' -- -- * 'rslsKernelId' @::@ 'Maybe' 'Text' -- -- * 'rslsKeyName' @::@ 'Maybe' 'Text' -- -- * 'rslsMonitoring' @::@ 'Maybe' 'RunInstancesMonitoringEnabled' -- -- * 'rslsNetworkInterfaces' @::@ ['InstanceNetworkInterfaceSpecification'] -- -- * 'rslsPlacement' @::@ 'Maybe' 'SpotPlacement' -- -- * 'rslsRamdiskId' @::@ 'Maybe' 'Text' -- -- * 'rslsSecurityGroupIds' @::@ ['Text'] -- -- * 'rslsSecurityGroups' @::@ ['Text'] -- -- * 'rslsSubnetId' @::@ 'Maybe' 'Text' -- -- * 'rslsUserData' @::@ 'Maybe' 'Text' -- requestSpotLaunchSpecification :: RequestSpotLaunchSpecification requestSpotLaunchSpecification = RequestSpotLaunchSpecification { _rslsImageId = Nothing , _rslsKeyName = Nothing , _rslsSecurityGroups = mempty , _rslsUserData = Nothing , _rslsAddressingType = Nothing , _rslsInstanceType = Nothing , _rslsPlacement = Nothing , _rslsKernelId = Nothing , _rslsRamdiskId = Nothing , _rslsBlockDeviceMappings = mempty , _rslsSubnetId = Nothing , _rslsNetworkInterfaces = mempty , _rslsIamInstanceProfile = Nothing , _rslsEbsOptimized = Nothing , _rslsMonitoring = Nothing , _rslsSecurityGroupIds = mempty } -- | Deprecated. rslsAddressingType :: Lens' RequestSpotLaunchSpecification (Maybe Text) rslsAddressingType = lens _rslsAddressingType (\s a -> s { _rslsAddressingType = a }) -- | One or more block device mapping entries. rslsBlockDeviceMappings :: Lens' RequestSpotLaunchSpecification [BlockDeviceMapping] rslsBlockDeviceMappings = lens _rslsBlockDeviceMappings (\s a -> s { _rslsBlockDeviceMappings = a }) . _List -- | 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. -- -- Default: 'false' rslsEbsOptimized :: Lens' RequestSpotLaunchSpecification (Maybe Bool) rslsEbsOptimized = lens _rslsEbsOptimized (\s a -> s { _rslsEbsOptimized = a }) -- | The IAM instance profile. rslsIamInstanceProfile :: Lens' RequestSpotLaunchSpecification (Maybe IamInstanceProfileSpecification) rslsIamInstanceProfile = lens _rslsIamInstanceProfile (\s a -> s { _rslsIamInstanceProfile = a }) -- | The ID of the AMI. rslsImageId :: Lens' RequestSpotLaunchSpecification (Maybe Text) rslsImageId = lens _rslsImageId (\s a -> s { _rslsImageId = a }) -- | The instance type. rslsInstanceType :: Lens' RequestSpotLaunchSpecification (Maybe InstanceType) rslsInstanceType = lens _rslsInstanceType (\s a -> s { _rslsInstanceType = a }) -- | The ID of the kernel. rslsKernelId :: Lens' RequestSpotLaunchSpecification (Maybe Text) rslsKernelId = lens _rslsKernelId (\s a -> s { _rslsKernelId = a }) -- | The name of the key pair. rslsKeyName :: Lens' RequestSpotLaunchSpecification (Maybe Text) rslsKeyName = lens _rslsKeyName (\s a -> s { _rslsKeyName = a }) rslsMonitoring :: Lens' RequestSpotLaunchSpecification (Maybe RunInstancesMonitoringEnabled) rslsMonitoring = lens _rslsMonitoring (\s a -> s { _rslsMonitoring = a }) -- | One or more network interfaces. rslsNetworkInterfaces :: Lens' RequestSpotLaunchSpecification [InstanceNetworkInterfaceSpecification] rslsNetworkInterfaces = lens _rslsNetworkInterfaces (\s a -> s { _rslsNetworkInterfaces = a }) . _List -- | The placement information for the instance. rslsPlacement :: Lens' RequestSpotLaunchSpecification (Maybe SpotPlacement) rslsPlacement = lens _rslsPlacement (\s a -> s { _rslsPlacement = a }) -- | The ID of the RAM disk. rslsRamdiskId :: Lens' RequestSpotLaunchSpecification (Maybe Text) rslsRamdiskId = lens _rslsRamdiskId (\s a -> s { _rslsRamdiskId = a }) rslsSecurityGroupIds :: Lens' RequestSpotLaunchSpecification [Text] rslsSecurityGroupIds = lens _rslsSecurityGroupIds (\s a -> s { _rslsSecurityGroupIds = a }) . _List rslsSecurityGroups :: Lens' RequestSpotLaunchSpecification [Text] rslsSecurityGroups = lens _rslsSecurityGroups (\s a -> s { _rslsSecurityGroups = a }) . _List -- | The ID of the subnet in which to launch the instance. rslsSubnetId :: Lens' RequestSpotLaunchSpecification (Maybe Text) rslsSubnetId = lens _rslsSubnetId (\s a -> s { _rslsSubnetId = a }) -- | The Base64-encoded MIME user data to make available to the instances. rslsUserData :: Lens' RequestSpotLaunchSpecification (Maybe Text) rslsUserData = lens _rslsUserData (\s a -> s { _rslsUserData = a }) instance FromXML RequestSpotLaunchSpecification where parseXML x = RequestSpotLaunchSpecification <$> x .@? "addressingType" <*> x .@? "blockDeviceMapping" .!@ mempty <*> x .@? "ebsOptimized" <*> x .@? "iamInstanceProfile" <*> x .@? "imageId" <*> x .@? "instanceType" <*> x .@? "kernelId" <*> x .@? "keyName" <*> x .@? "monitoring" <*> x .@? "NetworkInterface" .!@ mempty <*> x .@? "placement" <*> x .@? "ramdiskId" <*> x .@? "SecurityGroupId" .!@ mempty <*> x .@? "SecurityGroup" .!@ mempty <*> x .@? "subnetId" <*> x .@? "userData" instance ToQuery RequestSpotLaunchSpecification where toQuery RequestSpotLaunchSpecification{..} = mconcat [ "AddressingType" =? _rslsAddressingType , "BlockDeviceMapping" `toQueryList` _rslsBlockDeviceMappings , "EbsOptimized" =? _rslsEbsOptimized , "IamInstanceProfile" =? _rslsIamInstanceProfile , "ImageId" =? _rslsImageId , "InstanceType" =? _rslsInstanceType , "KernelId" =? _rslsKernelId , "KeyName" =? _rslsKeyName , "Monitoring" =? _rslsMonitoring , "NetworkInterface" `toQueryList` _rslsNetworkInterfaces , "Placement" =? _rslsPlacement , "RamdiskId" =? _rslsRamdiskId , "SecurityGroupId" `toQueryList` _rslsSecurityGroupIds , "SecurityGroup" `toQueryList` _rslsSecurityGroups , "SubnetId" =? _rslsSubnetId , "UserData" =? _rslsUserData ] newtype VolumeDetail = VolumeDetail { _vdSize :: Integer } deriving (Eq, Ord, Read, Show, Enum, Num, Integral, Real) -- | 'VolumeDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vdSize' @::@ 'Integer' -- volumeDetail :: Integer -- ^ 'vdSize' -> VolumeDetail volumeDetail p1 = VolumeDetail { _vdSize = p1 } -- | The size of the volume, in GiB. vdSize :: Lens' VolumeDetail Integer vdSize = lens _vdSize (\s a -> s { _vdSize = a }) instance FromXML VolumeDetail where parseXML x = VolumeDetail <$> x .@ "size" instance ToQuery VolumeDetail where toQuery VolumeDetail{..} = mconcat [ "Size" =? _vdSize ] data PricingDetail = PricingDetail { _pdCount :: Maybe Int , _pdPrice :: Maybe Double } deriving (Eq, Ord, Read, Show) -- | 'PricingDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pdCount' @::@ 'Maybe' 'Int' -- -- * 'pdPrice' @::@ 'Maybe' 'Double' -- pricingDetail :: PricingDetail pricingDetail = PricingDetail { _pdPrice = Nothing , _pdCount = Nothing } -- | The number of instances available for the price. pdCount :: Lens' PricingDetail (Maybe Int) pdCount = lens _pdCount (\s a -> s { _pdCount = a }) -- | The price per instance. pdPrice :: Lens' PricingDetail (Maybe Double) pdPrice = lens _pdPrice (\s a -> s { _pdPrice = a }) instance FromXML PricingDetail where parseXML x = PricingDetail <$> x .@? "count" <*> x .@? "price" instance ToQuery PricingDetail where toQuery PricingDetail{..} = mconcat [ "Count" =? _pdCount , "Price" =? _pdPrice ] data NetworkInterfacePrivateIpAddress = NetworkInterfacePrivateIpAddress { _nipiaAssociation :: Maybe NetworkInterfaceAssociation , _nipiaPrimary :: Maybe Bool , _nipiaPrivateDnsName :: Maybe Text , _nipiaPrivateIpAddress :: Maybe Text } deriving (Eq, Read, Show) -- | 'NetworkInterfacePrivateIpAddress' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'nipiaAssociation' @::@ 'Maybe' 'NetworkInterfaceAssociation' -- -- * 'nipiaPrimary' @::@ 'Maybe' 'Bool' -- -- * 'nipiaPrivateDnsName' @::@ 'Maybe' 'Text' -- -- * 'nipiaPrivateIpAddress' @::@ 'Maybe' 'Text' -- networkInterfacePrivateIpAddress :: NetworkInterfacePrivateIpAddress networkInterfacePrivateIpAddress = NetworkInterfacePrivateIpAddress { _nipiaPrivateIpAddress = Nothing , _nipiaPrivateDnsName = Nothing , _nipiaPrimary = Nothing , _nipiaAssociation = Nothing } -- | The association information for an Elastic IP address associated with the -- network interface. nipiaAssociation :: Lens' NetworkInterfacePrivateIpAddress (Maybe NetworkInterfaceAssociation) nipiaAssociation = lens _nipiaAssociation (\s a -> s { _nipiaAssociation = a }) -- | Indicates whether this IP address is the primary private IP address of the -- network interface. nipiaPrimary :: Lens' NetworkInterfacePrivateIpAddress (Maybe Bool) nipiaPrimary = lens _nipiaPrimary (\s a -> s { _nipiaPrimary = a }) -- | The private DNS name. nipiaPrivateDnsName :: Lens' NetworkInterfacePrivateIpAddress (Maybe Text) nipiaPrivateDnsName = lens _nipiaPrivateDnsName (\s a -> s { _nipiaPrivateDnsName = a }) -- | The private IP address. nipiaPrivateIpAddress :: Lens' NetworkInterfacePrivateIpAddress (Maybe Text) nipiaPrivateIpAddress = lens _nipiaPrivateIpAddress (\s a -> s { _nipiaPrivateIpAddress = a }) instance FromXML NetworkInterfacePrivateIpAddress where parseXML x = NetworkInterfacePrivateIpAddress <$> x .@? "association" <*> x .@? "primary" <*> x .@? "privateDnsName" <*> x .@? "privateIpAddress" instance ToQuery NetworkInterfacePrivateIpAddress where toQuery NetworkInterfacePrivateIpAddress{..} = mconcat [ "Association" =? _nipiaAssociation , "Primary" =? _nipiaPrimary , "PrivateDnsName" =? _nipiaPrivateDnsName , "PrivateIpAddress" =? _nipiaPrivateIpAddress ] data DiskImageFormat = Raw -- ^ RAW | Vhd -- ^ VHD | Vmdk -- ^ VMDK deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable DiskImageFormat instance FromText DiskImageFormat where parser = takeLowerText >>= \case "raw" -> pure Raw "vhd" -> pure Vhd "vmdk" -> pure Vmdk e -> fail $ "Failure parsing DiskImageFormat from " ++ show e instance ToText DiskImageFormat where toText = \case Raw -> "RAW" Vhd -> "VHD" Vmdk -> "VMDK" instance ToByteString DiskImageFormat instance ToHeader DiskImageFormat instance ToQuery DiskImageFormat instance FromXML DiskImageFormat where parseXML = parseXMLText "DiskImageFormat" data BundleTaskError = BundleTaskError { _bteCode :: Maybe Text , _bteMessage :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'BundleTaskError' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'bteCode' @::@ 'Maybe' 'Text' -- -- * 'bteMessage' @::@ 'Maybe' 'Text' -- bundleTaskError :: BundleTaskError bundleTaskError = BundleTaskError { _bteCode = Nothing , _bteMessage = Nothing } -- | The error code. bteCode :: Lens' BundleTaskError (Maybe Text) bteCode = lens _bteCode (\s a -> s { _bteCode = a }) -- | The error message. bteMessage :: Lens' BundleTaskError (Maybe Text) bteMessage = lens _bteMessage (\s a -> s { _bteMessage = a }) instance FromXML BundleTaskError where parseXML x = BundleTaskError <$> x .@? "code" <*> x .@? "message" instance ToQuery BundleTaskError where toQuery BundleTaskError{..} = mconcat [ "Code" =? _bteCode , "Message" =? _bteMessage ] data VpcClassicLink = VpcClassicLink { _vclClassicLinkEnabled :: Maybe Bool , _vclTags :: List "item" Tag , _vclVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'VpcClassicLink' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vclClassicLinkEnabled' @::@ 'Maybe' 'Bool' -- -- * 'vclTags' @::@ ['Tag'] -- -- * 'vclVpcId' @::@ 'Maybe' 'Text' -- vpcClassicLink :: VpcClassicLink vpcClassicLink = VpcClassicLink { _vclVpcId = Nothing , _vclClassicLinkEnabled = Nothing , _vclTags = mempty } -- | Indicates whether the VPC is enabled for ClassicLink. vclClassicLinkEnabled :: Lens' VpcClassicLink (Maybe Bool) vclClassicLinkEnabled = lens _vclClassicLinkEnabled (\s a -> s { _vclClassicLinkEnabled = a }) -- | Any tags assigned to the VPC. vclTags :: Lens' VpcClassicLink [Tag] vclTags = lens _vclTags (\s a -> s { _vclTags = a }) . _List -- | The ID of the VPC. vclVpcId :: Lens' VpcClassicLink (Maybe Text) vclVpcId = lens _vclVpcId (\s a -> s { _vclVpcId = a }) instance FromXML VpcClassicLink where parseXML x = VpcClassicLink <$> x .@? "classicLinkEnabled" <*> x .@? "tagSet" .!@ mempty <*> x .@? "vpcId" instance ToQuery VpcClassicLink where toQuery VpcClassicLink{..} = mconcat [ "ClassicLinkEnabled" =? _vclClassicLinkEnabled , "TagSet" `toQueryList` _vclTags , "VpcId" =? _vclVpcId ] data VolumeStatusItem = VolumeStatusItem { _vsiActions :: List "item" VolumeStatusAction , _vsiAvailabilityZone :: Maybe Text , _vsiEvents :: List "item" VolumeStatusEvent , _vsiVolumeId :: Maybe Text , _vsiVolumeStatus :: Maybe VolumeStatusInfo } deriving (Eq, Read, Show) -- | 'VolumeStatusItem' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vsiActions' @::@ ['VolumeStatusAction'] -- -- * 'vsiAvailabilityZone' @::@ 'Maybe' 'Text' -- -- * 'vsiEvents' @::@ ['VolumeStatusEvent'] -- -- * 'vsiVolumeId' @::@ 'Maybe' 'Text' -- -- * 'vsiVolumeStatus' @::@ 'Maybe' 'VolumeStatusInfo' -- volumeStatusItem :: VolumeStatusItem volumeStatusItem = VolumeStatusItem { _vsiVolumeId = Nothing , _vsiAvailabilityZone = Nothing , _vsiVolumeStatus = Nothing , _vsiEvents = mempty , _vsiActions = mempty } -- | The details of the operation. vsiActions :: Lens' VolumeStatusItem [VolumeStatusAction] vsiActions = lens _vsiActions (\s a -> s { _vsiActions = a }) . _List -- | The Availability Zone of the volume. vsiAvailabilityZone :: Lens' VolumeStatusItem (Maybe Text) vsiAvailabilityZone = lens _vsiAvailabilityZone (\s a -> s { _vsiAvailabilityZone = a }) -- | A list of events associated with the volume. vsiEvents :: Lens' VolumeStatusItem [VolumeStatusEvent] vsiEvents = lens _vsiEvents (\s a -> s { _vsiEvents = a }) . _List -- | The volume ID. vsiVolumeId :: Lens' VolumeStatusItem (Maybe Text) vsiVolumeId = lens _vsiVolumeId (\s a -> s { _vsiVolumeId = a }) -- | The volume status. vsiVolumeStatus :: Lens' VolumeStatusItem (Maybe VolumeStatusInfo) vsiVolumeStatus = lens _vsiVolumeStatus (\s a -> s { _vsiVolumeStatus = a }) instance FromXML VolumeStatusItem where parseXML x = VolumeStatusItem <$> x .@? "actionsSet" .!@ mempty <*> x .@? "availabilityZone" <*> x .@? "eventsSet" .!@ mempty <*> x .@? "volumeId" <*> x .@? "volumeStatus" instance ToQuery VolumeStatusItem where toQuery VolumeStatusItem{..} = mconcat [ "ActionsSet" `toQueryList` _vsiActions , "AvailabilityZone" =? _vsiAvailabilityZone , "EventsSet" `toQueryList` _vsiEvents , "VolumeId" =? _vsiVolumeId , "VolumeStatus" =? _vsiVolumeStatus ]
kim/amazonka
amazonka-ec2/gen/Network/AWS/EC2/Types.hs
mpl-2.0
431,589
0
84
106,530
78,776
44,487
34,289
-1
-1
module GitHub ( CreateFailure(..) , uploadRelease ) where import Prelude hiding ((++)) import Data.Traversable import Data.Monoid import Control.Lens import Network.Wreq hiding (postWith) import Network.Wreq.Session import qualified Data.ByteString.Lazy as LB import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Aeson as A import qualified Data.HashMap.Strict as H import ByteString (ByteString, RawFilePath) import qualified ByteString as B import Platform (releaseSuffix) (++) :: Monoid m => m -> m -> m (++) = mappend data CreateFailure = AuthFail | DecodeFail | NotObject | MissingField Text | FieldTypeMismatch | CreateFailure Int deriving (Show) opts :: ByteString -> Options opts token = defaults & header "Accept" .~ ["application/vnd.github.v3+json"] & header "Authorization" .~ ["token " ++ token] & header "User-Agent" .~ ["wild"] & header "Content-Type" .~ ["application/json; charset=utf-8"] & checkResponse .~ Nothing createRelease :: Session -> ByteString -> ByteString -> ByteString -> ByteString -> IO (Either CreateFailure (Response LB.ByteString)) createRelease session token owner repo tagName = resp >>= \ r -> return $ case r ^. responseStatus . statusCode of 401 -> Left AuthFail _ -> Right r where resp = postWith (opts token) session uri content uri = B.unpack $ mconcat ["https://api.github.com/repos/", owner, "/", repo, "/releases"] content = mconcat [ "{\"tag_name\":\"", tagName, "\",\"name\":\"", tagName , "\",\"draft\":true,\"prerelease\":false,\ \\"target_commitish\":\"master\"}" ] lookupField :: Text -> Response LB.ByteString -> Either CreateFailure Text lookupField field r = case r ^. responseStatus . statusCode of 201 -> case A.decode (r ^. responseBody) of Nothing -> Left DecodeFail Just v -> case v of A.Object obj -> case field `H.lookup` obj of Nothing -> Left (MissingField field) Just v2 -> case v2 of A.String url -> Right url _ -> Left FieldTypeMismatch _ -> Left NotObject 401 -> Left AuthFail x -> Left (CreateFailure x) uploadAsset :: Session -> ByteString -> RawFilePath -> Text -> IO (Response LB.ByteString) uploadAsset session token path url = B.readFile path >>= postWith (opts token) session uploadURL where name = (snd $ B.breakEnd (== '/') path) <> "_" <> releaseSuffix uploadURL = B.unpack $ mconcat [T.encodeUtf8 $ T.takeWhile (/= '{') url, "?name=", name] uploadRelease :: ByteString -> ByteString -> ByteString -> ByteString -> [RawFilePath] -> IO (Either CreateFailure ()) uploadRelease token owner repo tagName paths = withSession $ \ s -> do r1 <- createRelease s token owner repo tagName case r1 >>= lookupField "upload_url" of Left err -> return $ Left err Right url -> fmap sequence_ <$> for paths $ \ path -> do r2 <- uploadAsset s token path url return $ case r2 ^. responseStatus . statusCode of 201 -> Right () 401 -> Left AuthFail x -> Left (CreateFailure x)
kinoru/wild
src/GitHub.hs
agpl-3.0
3,376
0
22
908
1,010
534
476
-1
-1
func x | x = simple expression | otherwise = 0
lspitzner/brittany
data/Test88.hs
agpl-3.0
62
2
5
26
24
11
13
2
1
module Codewars.Kata.Combos where combos :: Int -> [[Int]] combos n = f 1 n where f u n = if u <= n then [n] : ([u .. n] >>= \x -> (x :) <$> f x (n - x)) else [] --
ice1000/OI-codes
codewars/1-100/find-all-possible-number-combos-that-sum-to-a-number.hs-optimized.hs
agpl-3.0
168
0
15
46
107
61
46
4
2
module Prim( plusOne, plusOne8, plusOne16, plusOne32, plusOne64 , plusOneU, plusOneU8, plusOneU16, plusOneU32, plusOneU64 , lshc, lshc8, lshc16, lshc32, lshc64 , rshc, rshc8, rshc16, rshc32, rshc64 , lshcU, lshcU8, lshcU16, lshcU32, lshcU64 , rshcU, rshcU8, rshcU16, rshcU32, rshcU64) where import Data.Int import Data.Word import Data.Bits plusOne :: Int -> Int plusOne = (+1) plusOne8 :: Int8 -> Int8 plusOne8 = (+1) plusOne16 :: Int16 -> Int16 plusOne16 = (+1) plusOne32 :: Int32 -> Int32 plusOne32 = (+1) plusOne64 :: Int64 -> Int64 plusOne64 = (+1) plusOneU :: Word -> Word plusOneU = (+1) plusOneU8 :: Word8 -> Word8 plusOneU8 = (+1) plusOneU16 :: Word16 -> Word16 plusOneU16 = (+1) plusOneU32 :: Word32 -> Word32 plusOneU32 = (+1) plusOneU64 :: Word64 -> Word64 plusOneU64 = (+1) -- Left shift by a constant lshc :: Int -> Int lshc = (`shift` 1) lshc8 :: Int8 -> Int8 lshc8 = (`shift` 2) lshc16 :: Int16 -> Int16 lshc16 = (`shift` 3) lshc32 :: Int32 -> Int32 lshc32 = (`shift` 4) lshc64 :: Int64 -> Int64 lshc64 = (`shift` 5) lshcU :: Word -> Word lshcU = (`shift` 1) lshcU8 :: Word8 -> Word8 lshcU8 = (`shift` 2) lshcU16 :: Word16 -> Word16 lshcU16 = (`shift` 3) lshcU32 :: Word32 -> Word32 lshcU32 = (`shift` 4) lshcU64 :: Word64 -> Word64 lshcU64 = (`shift` 5) -- Right shift by a constant rshc :: Int -> Int rshc = (`shift` (-1)) rshc8 :: Int8 -> Int8 rshc8 = (`shift` (-1)) rshc16 :: Int16 -> Int16 rshc16 = (`shift` (-1)) rshc32 :: Int32 -> Int32 rshc32 = (`shift` (-1)) rshc64 :: Int64 -> Int64 rshc64 = (`shift` (-1)) rshcU :: Word -> Word rshcU = (`shift` (-1)) rshcU8 :: Word8 -> Word8 rshcU8 = (`shift` (-1)) rshcU16 :: Word16 -> Word16 rshcU16 = (`shift` (-1)) rshcU32 :: Word32 -> Word32 rshcU32 = (`shift` (-1)) rshcU64 :: Word64 -> Word64 rshcU64 = (`shift` (-1))
yjwen/hada
test/Prim.hs
lgpl-3.0
1,873
0
7
403
743
475
268
69
1
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE JavaScriptFFI #-} {- Copyright 2018 The CodeWorld Authors. All Rights Reserved. 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. -} module Blockly.Event ( Event(..) ,EventType(..) ,getType ,getWorkspaceId ,getBlockId -- ,getIds ,addChangeListener ) where import GHCJS.Types import Data.JSString (pack, unpack) import GHCJS.Foreign import GHCJS.Marshal import GHCJS.Foreign.Callback import Blockly.General import Blockly.Workspace import JavaScript.Array (JSArray) newtype Event = Event JSVal data EventType = CreateEvent Event | DeleteEvent Event | ChangeEvent Event | MoveEvent Event | UIEvent Event | GeneralEvent Event getType :: Event -> EventType getType event = case unpack $ js_type event of "create" -> CreateEvent event "delete" -> DeleteEvent event "change" -> ChangeEvent event "move" -> MoveEvent event "ui" -> UIEvent event _ -> GeneralEvent event getWorkspaceId :: Event -> UUID getWorkspaceId event = UUID $ unpack $ js_workspaceId event getBlockId :: Event -> UUID getBlockId event = UUID $ unpack $ js_blockId event getGroup :: Event -> UUID getGroup event = UUID $ unpack $ js_group event -- getIds :: Event -> UUID -- getIds event = UUID $ unpack $ js_ids event type EventCallback = Event -> IO () addChangeListener :: Workspace -> EventCallback -> IO () addChangeListener workspace func = do cb <- syncCallback1 ContinueAsync (func . Event) js_addChangeListener workspace cb --- FFI foreign import javascript unsafe "$1.addChangeListener($2)" js_addChangeListener :: Workspace -> Callback a -> IO () -- One of Blockly.Events.CREATE, Blockly.Events.DELETE, Blockly.Events.CHANGE, -- Blockly.Events.MOVE, Blockly.Events.UI. foreign import javascript unsafe "$1.type" js_type :: Event -> JSString -- UUID of workspace foreign import javascript unsafe "$1.workspaceId" js_workspaceId :: Event -> JSString -- UUID of block. foreign import javascript unsafe "$1.blockId" js_blockId :: Event -> JSString -- UUID of group foreign import javascript unsafe "$1.group" js_group :: Event -> JSString -- UUIDs of affected blocks foreign import javascript unsafe "$1.ids" js_ids :: Event -> JSArray
tgdavies/codeworld
funblocks-client/src/Blockly/Event.hs
apache-2.0
3,031
15
11
773
507
273
234
54
6
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE DuplicateRecordFields #-} module DuplicateRecordFields (RawReplay(..)) where import Prelude hiding (Int) data Int = Int data RawReplay = RawReplay { headerSize :: Int -- ^ The byte size of the first section. , headerCRC :: Int -- ^ The CRC of the first section. , header :: Int -- ^ The first section. , contentSize :: Int -- ^ The byte size of the second section. , contentCRC :: Int -- ^ The CRC of the second section. , content :: Int -- ^ The second section. , footer :: Int -- ^ Arbitrary data after the second section. In replays generated by -- Rocket League, this is always empty. However it is not technically -- invalid to put something here. }
haskell/haddock
html-test/src/DuplicateRecordFields.hs
bsd-2-clause
767
0
8
197
91
63
28
13
0
--- Pretty printing for the T functor ------------------------------------------ module HsTypePretty where import HsTypeStruct --import HsIdent import PrettySymbols(rarrow,forall') import PrettyPrint import PrettyUtil instance (Printable i,Printable t,PrintableApp t t) => Printable (TI i t) where ppi (HsTyFun a b) = sep [ wrap a <+> rarrow, ppi b ] ppi (HsTyApp f x) = ppiApp f [x] ppi (HsTyForall xs ts t) = forall' <+> hsep (map ppi xs) <> kw '.' <+> ppContext ts <+> t ppi t = wrap t -- wrap (HsTyTuple ts) = ppiTuple ts wrap (HsTyApp f x) = wrapApp f [x] wrap (HsTyVar v) = wrap v wrap (HsTyCon c) = tcon (wrap c) wrap t = parens $ ppi t instance (PrintableApp i t,PrintableApp t t) => PrintableApp (TI i t) t where ppiApp (HsTyApp tf ta) ts = ppiApp tf (ta:ts) ppiApp (HsTyCon c) ts = ppiApp c ts ppiApp t ts = wrap t<+>fsep (map wrap ts) wrapApp (HsTyApp tf ta) ts = wrapApp tf (ta:ts) wrapApp (HsTyCon c) ts = wrapApp c ts wrapApp t ts = parens (wrap t<+>fsep (map wrap ts))
forste/haReFork
tools/base/AST/HsTypePretty.hs
bsd-3-clause
1,125
0
12
322
467
233
234
-1
-1
module Grammar where import Control.Applicative ((<$>), (<*>)) import Control.Arrow ((***)) import Control.Monad.Reader (Reader, ask, local, runReader) import Data.List (elemIndex) import Data.Maybe (fromJust) import Data.Set as Set (Set, empty, singleton, toList, union, unions) import Test.QuickCheck (Arbitrary(..), elements, oneof, sized) -- | Simply Typed Lambda Calculus data Type = TyUnit | TyBool | TyNat | TyArr Type Type deriving (Show, Eq) data Term = TUnit | TTrue | TFalse | TNat Integer | TIf Term Term Term | TVar Int | TAbs Type Term | TApp Term Term deriving (Show, Eq) -- | Untyped Lambda Calculus using explicit variable names. data NamedTerm = NUnit | NTrue | NFalse | NNat Integer | NIf NamedTerm NamedTerm NamedTerm | NVar String | NAbs Type String NamedTerm | NApp NamedTerm NamedTerm deriving (Show, Eq) validIdentifiers :: [String] validIdentifiers = (flip (:)) <$> ("":validRest) <*> validStart where validStart = ['a'..'z'] ++ ['A'..'Z'] ++ "_" validRest = (flip (:)) <$> ("" : validRest) <*> (validStart ++ ['0'..'9'] ++ "'") -- | Convert back and forth between De Bruijn and explicit names -- | Returns the nameless term and a list representing the encodings of -- | the free variables (the naming context). removeNames :: NamedTerm -> (Term, [String]) removeNames t = withFree $ runReader (rec t) free where withFree x = (x, free) free = freeVars t rec nt = do ctx <- ask case nt of NUnit -> return TUnit NTrue -> return TTrue NFalse -> return TFalse NNat i -> return $ TNat i NIf t1 t2 t3 -> TIf <$> rec t1 <*> rec t2 <*> rec t3 (NVar s) -> let i = fromJust $ s `elemIndex` ctx in return $ TVar i (NAbs ty s bod) -> TAbs ty <$> (local (s:) $ rec bod) (NApp t1 t2) -> TApp <$> rec t1 <*> rec t2 freeVars :: NamedTerm -> [String] freeVars t = Set.toList $ runReader (go t) [] where go :: NamedTerm -> Reader [String] (Set String) go nt = do bound <- ask case nt of NUnit -> return Set.empty NTrue -> return Set.empty NFalse -> return Set.empty NNat{} -> return Set.empty NIf nt1 nt2 nt3 -> do free1 <- go nt1 free2 <- go nt2 free3 <- go nt3 return $ Set.unions $ [free1, free2, free3] NVar s -> return $ if s `elem` bound then Set.empty else Set.singleton s NAbs _ s bod -> local (s:) $ go bod NApp t1 t2 -> do free1 <- go t1 free2 <- go t2 return $ free1 `Set.union` free2 restoreNames :: Term -> [String] -> NamedTerm restoreNames t' ctx = runReader (rec t') (nameCtx) where rec :: Term -> Reader ([String], [String]) NamedTerm rec TUnit = return NUnit rec TTrue = return NTrue rec TFalse = return NFalse rec (TNat i) = return $ NNat i rec (TIf t1 t2 t3) = NIf <$> rec t1 <*> rec t2 <*> rec t3 rec (TVar i) = do (names, _) <- ask return $ NVar (names !! i) rec (TApp t1 t2) = NApp <$> rec t1 <*> rec t2 rec (TAbs ty t) = do (_, unused) <- ask let s = head unused in NAbs ty s <$> (local ((s:) *** tail) $ rec t) nameCtx = splitAt (length ctx) validIdentifiers -- | Testing instance Arbitrary Type where arbitrary = sized type' where type' 0 = elements [TyUnit, TyBool, TyNat] type' n = TyArr <$> halved <*> halved where halved = type' (n `div` 2) shrink (TyArr t1 t2) = [t1, t2] shrink _ = [] instance Arbitrary Term where arbitrary = sized term' where term' 0 = oneof $ (TVar . abs <$> arbitrary) : (TNat <$> arbitrary) : map return [TUnit, TTrue, TFalse] term' n = oneof [ TIf <$> thirded <*> thirded <*> thirded , TAbs <$> arbitrary <*> (term' (n-1)) , TApp <$> halved <*> halved ] where halved = term' (n `div` 2) thirded = term' (n `div` 3) shrink (TIf t1 t2 t3) = [t1, t2, t3] shrink (TApp t1 t2) = [t1, t2] shrink (TAbs ty t) = t : ((flip TAbs t) <$> shrink ty) shrink _ = [] instance Arbitrary NamedTerm where arbitrary = sized term' where term' 0 = oneof $ (NVar <$> vars) : map return [NTrue, NFalse] term' n = oneof [ NIf <$> thirded <*> thirded <*> thirded , NAbs <$> arbitrary <*> vars <*> (term' (n-1)) , NApp <$> halved <*> halved ] where halved = term' (n `div` 2) thirded = term' (n `div` 3) vars = elements . fmap (:[]) $ ['a'..'z'] shrink (NApp t1 t2) = [t1, t2] shrink (NAbs _ _ t) = [t] shrink _ = [] prop_idempotent_encoding :: NamedTerm -> Bool prop_idempotent_encoding nt = run nt == (run . run $ nt) where run = uncurry restoreNames . removeNames
maxsnew/TAPL
SimplyTyped/Lambda/Implementation/Grammar.hs
bsd-3-clause
5,507
0
17
2,105
1,940
1,021
919
129
9
{-# LANGUAGE BangPatterns #-} module Network.Openflow.Ethernet.IPv4 (IPv4Flag(..), IPv4(..), putIPv4Pkt) where import Network.Openflow.Ethernet.Types import Network.Openflow.Misc import Data.Word -- import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS import Network.Openflow.StrictPut import Data.Bits import System.IO.Unsafe data IPv4Flag = DF | MF | Res deriving (Eq, Ord, Show, Read) instance Enum IPv4Flag where fromEnum DF = 4 fromEnum MF = 2 fromEnum Res = 1 toEnum _ = error "method is not supported yet" class IPv4 a where ipHeaderLen :: a -> Word8 ipVersion :: a -> Word8 ipTOS :: a -> Word8 ipID :: a -> Word16 ipFlags :: a -> Word8 ipFragOffset :: a -> Word16 ipTTL :: a -> Word8 ipProto :: a -> Word8 ipSrc :: a -> IPv4Addr ipDst :: a -> IPv4Addr ipPutPayload :: a -> PutM () putIPv4Pkt :: IPv4 a => a -> PutM () putIPv4Pkt x = do start <- marker putWord8 lenIhl putWord8 tos totLen <- delayedWord16be putWord16be ipId putWord16be flagsOff putWord8 ttl putWord8 proto acrc <- delayedWord16be putIP ipS putIP ipD hlen <- distance start ipPutPayload x undelay totLen . Word16be . fromIntegral =<< distance start undelay acrc (Word16be $ csum16' (unsafeDupablePerformIO $ BS.unsafePackAddressLen hlen (toAddr start))) where lenIhl = (ihl .&. 0xF) .|. (ver `shiftL` 4 .&. 0xF0) ihl = ipHeaderLen x ver = ipVersion x tos = ipTOS x ipId = ipID x flagsOff = (off .&. 0x1FFF) .|. ((fromIntegral flags) `shiftL` 13) flags = ipFlags x -- totLen = fromIntegral $ 4*(ipHeaderLen x) + fromIntegral (BS.length body) off = ipFragOffset x ttl = ipTTL x proto = ipProto x ipS = ipSrc x ipD = ipDst x
ARCCN/hcprobe
src/Network/Openflow/Ethernet/IPv4.hs
bsd-3-clause
1,878
0
15
518
577
300
277
58
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Char import qualified Data.Map as M import Data.Traversable (sequenceA) import Control.Monad.Fix import Control.Applicative ((<|>), liftA2) import Control.Monad import System.Environment (getArgs) import System.Console.GetOpt import System.IO import System.Exit data Args = Encrypt | Decrypt | Key String deriving (Show, Eq, Ord) tokey Encrypt = "e" tokey Decrypt = "d" tokey (Key _) = "k" -- Perform encryption or decryption, depending on f. crypt f key = map toLetter . zipWith f (cycle key) where toLetter = chr . (+) (ord 'A') -- Encrypt or decrypt one letter. enc k c = (ord k + ord c) `mod` 26 dec k c = (ord c - ord k) `mod` 26 -- Given a key, encrypt or decrypt an input string. encrypt = crypt enc decrypt = crypt dec -- Convert a string to have only upper case letters. convert = map toUpper . filter isLetter flags = [ Option ['e'] [] (NoArg Encrypt) "encryption" , Option ['d'] [] (NoArg Decrypt) "decription" , Option ['k'] [] (ReqArg Key "KEY") "key" ] main :: IO () main = do args <- getArgs let (opts, _, _) = getOpt Permute flags args let opts' = M.fromList $ fmap (\a -> (tokey a, a)) opts let lookupOpts = flip M.lookup opts' input <- getInput run (lookupOpts "d" <|> lookupOpts "e") (lookupOpts "k") input where getInput = do c <- hGetChar stdin if c == '\n' then return [] else (c:) <$> getInput -- getInput = getLine run (Just Encrypt) (Just (Key key)) input = putStrLn $ encrypt key input run (Just Decrypt) (Just (Key key)) input = putStrLn $ decrypt key input run _ _ _ = die "please use this software correctly."
taojang/haskell-programming-book-exercise
src/ch29/Vigenere.hs
bsd-3-clause
1,735
0
15
415
635
333
302
43
4
------------------------------------------------------------------------------- -- -- | Dynamic flags -- -- Most flags are dynamic flags, which means they can change from compilation -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each -- session can be using different dynamic flags. Dynamic flags can also be set -- at the prompt in GHCi. -- -- (c) The University of Glasgow 2005 -- ------------------------------------------------------------------------------- {-# OPTIONS -fno-cse #-} -- -fno-cse is needed for GLOBAL_VAR's to behave properly module DynFlags ( -- * Dynamic flags and associated configuration types DumpFlag(..), GeneralFlag(..), WarningFlag(..), ExtensionFlag(..), Language(..), PlatformConstants(..), FatalMessager, LogAction, FlushOut(..), FlushErr(..), ProfAuto(..), glasgowExtsFlags, dopt, dopt_set, dopt_unset, gopt, gopt_set, gopt_unset, wopt, wopt_set, wopt_unset, xopt, xopt_set, xopt_unset, lang_set, whenGeneratingDynamicToo, ifGeneratingDynamicToo, whenCannotGenerateDynamicToo, dynamicTooMkDynamicDynFlags, DynFlags(..), HasDynFlags(..), ContainsDynFlags(..), RtsOptsEnabled(..), HscTarget(..), isObjectTarget, defaultObjectTarget, targetRetainsAllBindings, GhcMode(..), isOneShot, GhcLink(..), isNoLink, PackageFlag(..), PkgConfRef(..), Option(..), showOpt, DynLibLoader(..), fFlags, fWarningFlags, fLangFlags, xFlags, dynFlagDependencies, tablesNextToCode, mkTablesNextToCode, printOutputForUser, printInfoForUser, Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays, wayGeneralFlags, wayUnsetGeneralFlags, -- ** Safe Haskell SafeHaskellMode(..), safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn, packageTrustOn, safeDirectImpsReq, safeImplicitImpsReq, unsafeFlags, -- ** System tool settings and locations Settings(..), targetPlatform, ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings, extraGccViaCFlags, systemPackageConfig, pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T, pgm_sysman, pgm_windres, pgm_libtool, pgm_lo, pgm_lc, opt_L, opt_P, opt_F, opt_c, opt_a, opt_l, opt_windres, opt_lo, opt_lc, -- ** Manipulating DynFlags defaultDynFlags, -- Settings -> DynFlags defaultWays, interpWays, initDynFlags, -- DynFlags -> IO DynFlags defaultFatalMessager, defaultLogAction, defaultLogActionHPrintDoc, defaultLogActionHPutStrDoc, defaultFlushOut, defaultFlushErr, getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a] getVerbFlags, updOptLevel, setTmpDir, setPackageName, -- ** Parsing DynFlags parseDynamicFlagsCmdLine, parseDynamicFilePragma, parseDynamicFlagsFull, -- ** Available DynFlags allFlags, flagsAll, flagsDynamic, flagsPackage, supportedLanguagesAndExtensions, languageExtensions, -- ** DynFlags C compiler options picCCOpts, picPOpts, -- * Configuration of the stg-to-stg passes StgToDo(..), getStgToDo, -- * Compiler configuration suitable for display to the user compilerInfo, #ifdef GHCI -- Only in stage 2 can we be sure that the RTS -- exposes the appropriate runtime boolean rtsIsProfiled, #endif #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs" bLOCK_SIZE_W, wORD_SIZE_IN_BITS, tAG_MASK, mAX_PTR_TAG, tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD, unsafeGlobalDynFlags, setUnsafeGlobalDynFlags, -- * SSE and AVX isSseEnabled, isSse2Enabled, isSse4_2Enabled, isAvxEnabled, isAvx2Enabled, isAvx512cdEnabled, isAvx512erEnabled, isAvx512fEnabled, isAvx512pfEnabled, -- * Linker information LinkerInfo(..), ) where #include "HsVersions.h" import Platform import PlatformConstants import Module import PackageConfig import {-# SOURCE #-} Hooks import {-# SOURCE #-} PrelNames ( mAIN ) import {-# SOURCE #-} Packages (PackageState) import DriverPhases ( Phase(..), phaseInputExt ) import Config import CmdLineParser import Constants import Panic import Util import Maybes ( orElse ) import MonadUtils import qualified Pretty import SrcLoc import FastString import Outputable #ifdef GHCI import Foreign.C ( CInt(..) ) #endif import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage ) import System.IO.Unsafe ( unsafePerformIO ) import Data.IORef import Control.Monad import Data.Bits import Data.Char import Data.Int import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Word import System.FilePath import System.IO import System.IO.Error import Data.IntSet (IntSet) import qualified Data.IntSet as IntSet import GHC.Foreign (withCString, peekCString) -- ----------------------------------------------------------------------------- -- DynFlags data DumpFlag -- debugging flags = Opt_D_dump_cmm | Opt_D_dump_cmm_raw -- All of the cmm subflags (there are a lot!) Automatically -- enabled if you run -ddump-cmm | Opt_D_dump_cmm_cfg | Opt_D_dump_cmm_cbe | Opt_D_dump_cmm_proc | Opt_D_dump_cmm_sink | Opt_D_dump_cmm_sp | Opt_D_dump_cmm_procmap | Opt_D_dump_cmm_split | Opt_D_dump_cmm_info | Opt_D_dump_cmm_cps -- end cmm subflags | Opt_D_dump_asm | Opt_D_dump_asm_native | Opt_D_dump_asm_liveness | Opt_D_dump_asm_regalloc | Opt_D_dump_asm_regalloc_stages | Opt_D_dump_asm_conflicts | Opt_D_dump_asm_stats | Opt_D_dump_asm_expanded | Opt_D_dump_llvm | Opt_D_dump_core_stats | Opt_D_dump_deriv | Opt_D_dump_ds | Opt_D_dump_foreign | Opt_D_dump_inlinings | Opt_D_dump_rule_firings | Opt_D_dump_rule_rewrites | Opt_D_dump_simpl_trace | Opt_D_dump_occur_anal | Opt_D_dump_parsed | Opt_D_dump_rn | Opt_D_dump_core_pipeline -- TODO FIXME: dump after simplifier stats | Opt_D_dump_simpl | Opt_D_dump_simpl_iterations | Opt_D_dump_simpl_phases | Opt_D_dump_spec | Opt_D_dump_prep | Opt_D_dump_stg | Opt_D_dump_stranal | Opt_D_dump_tc | Opt_D_dump_types | Opt_D_dump_rules | Opt_D_dump_cse | Opt_D_dump_worker_wrapper | Opt_D_dump_rn_trace | Opt_D_dump_rn_stats | Opt_D_dump_opt_cmm | Opt_D_dump_simpl_stats | Opt_D_dump_cs_trace -- Constraint solver in type checker | Opt_D_dump_tc_trace | Opt_D_dump_if_trace | Opt_D_dump_vt_trace | Opt_D_dump_splices | Opt_D_dump_BCOs | Opt_D_dump_vect | Opt_D_dump_ticked | Opt_D_dump_rtti | Opt_D_source_stats | Opt_D_verbose_stg2stg | Opt_D_dump_hi | Opt_D_dump_hi_diffs | Opt_D_dump_mod_cycles | Opt_D_dump_view_pattern_commoning | Opt_D_verbose_core2core deriving (Eq, Show, Enum) -- | Enumerates the simple on-or-off dynamic flags data GeneralFlag = Opt_DumpToFile -- ^ Append dump output to files instead of stdout. | Opt_D_faststring_stats | Opt_D_dump_minimal_imports | Opt_DoCoreLinting | Opt_DoStgLinting | Opt_DoCmmLinting | Opt_DoAsmLinting | Opt_NoLlvmMangler -- hidden flag | Opt_WarnIsError -- -Werror; makes warnings fatal | Opt_PrintExplicitForalls -- optimisation opts | Opt_Strictness | Opt_LateDmdAnal | Opt_KillAbsence | Opt_KillOneShot | Opt_FullLaziness | Opt_FloatIn | Opt_Specialise | Opt_StaticArgumentTransformation | Opt_CSE | Opt_LiberateCase | Opt_SpecConstr | Opt_DoLambdaEtaExpansion | Opt_IgnoreAsserts | Opt_DoEtaReduction | Opt_CaseMerge | Opt_UnboxStrictFields | Opt_UnboxSmallStrictFields | Opt_DictsCheap | Opt_EnableRewriteRules -- Apply rewrite rules during simplification | Opt_Vectorise | Opt_VectorisationAvoidance | Opt_RegsGraph -- do graph coloring register allocation | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation | Opt_PedanticBottoms -- Be picky about how we treat bottom | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag) | Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag) | Opt_IrrefutableTuples | Opt_CmmSink | Opt_CmmElimCommonBlocks | Opt_OmitYields | Opt_SimpleListLiterals | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas | Opt_DictsStrict -- be strict in argument dictionaries | Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors | Opt_Loopification -- See Note [Self-recursive tail calls] -- Interface files | Opt_IgnoreInterfacePragmas | Opt_OmitInterfacePragmas | Opt_ExposeAllUnfoldings -- profiling opts | Opt_AutoSccsOnIndividualCafs | Opt_ProfCountEntries -- misc opts | Opt_Pp | Opt_ForceRecomp | Opt_ExcessPrecision | Opt_EagerBlackHoling | Opt_NoHsMain | Opt_SplitObjs | Opt_StgStats | Opt_HideAllPackages | Opt_PrintBindResult | Opt_Haddock | Opt_HaddockOptions | Opt_Hpc_No_Auto | Opt_BreakOnException | Opt_BreakOnError | Opt_PrintEvldWithShow | Opt_PrintBindContents | Opt_GenManifest | Opt_EmbedManifest | Opt_EmitExternalCore | Opt_SharedImplib | Opt_BuildingCabalPackage | Opt_IgnoreDotGhci | Opt_GhciSandbox | Opt_GhciHistory | Opt_HelpfulErrors | Opt_DeferTypeErrors | Opt_Parallel | Opt_GranMacros | Opt_PIC | Opt_SccProfilingOn | Opt_Ticky | Opt_Ticky_Allocd | Opt_Ticky_LNE | Opt_Ticky_Dyn_Thunk | Opt_Static | Opt_RPath | Opt_RelativeDynlibPaths | Opt_Hpc | Opt_FlatCache -- PreInlining is on by default. The option is there just to see how -- bad things get if you turn it off! | Opt_SimplPreInlining -- output style opts | Opt_ErrorSpans -- Include full span info in error messages, -- instead of just the start position. | Opt_PprCaseAsLet -- Suppress all coercions, them replacing with '...' | Opt_SuppressCoercions | Opt_SuppressVarKinds -- Suppress module id prefixes on variables. | Opt_SuppressModulePrefixes -- Suppress type applications. | Opt_SuppressTypeApplications -- Suppress info such as arity and unfoldings on identifiers. | Opt_SuppressIdInfo -- Suppress separate type signatures in core, but leave types on -- lambda bound vars | Opt_SuppressTypeSignatures -- Suppress unique ids on variables. -- Except for uniques, as some simplifier phases introduce new -- variables that have otherwise identical names. | Opt_SuppressUniques -- temporary flags | Opt_RunCPS | Opt_RunCPSZ | Opt_AutoLinkPackages | Opt_ImplicitImportQualified -- keeping stuff | Opt_KeepHiDiffs | Opt_KeepHcFiles | Opt_KeepSFiles | Opt_KeepTmpFiles | Opt_KeepRawTokenStream | Opt_KeepLlvmFiles | Opt_BuildDynamicToo -- safe haskell flags | Opt_DistrustAllPackages | Opt_PackageTrust deriving (Eq, Show, Enum) data WarningFlag = Opt_WarnDuplicateExports | Opt_WarnDuplicateConstraints | Opt_WarnHiShadows | Opt_WarnImplicitPrelude | Opt_WarnIncompletePatterns | Opt_WarnIncompleteUniPatterns | Opt_WarnIncompletePatternsRecUpd | Opt_WarnOverflowedLiterals | Opt_WarnEmptyEnumerations | Opt_WarnMissingFields | Opt_WarnMissingImportList | Opt_WarnMissingMethods | Opt_WarnMissingSigs | Opt_WarnMissingLocalSigs | Opt_WarnNameShadowing | Opt_WarnOverlappingPatterns | Opt_WarnTypeDefaults | Opt_WarnMonomorphism | Opt_WarnUnusedBinds | Opt_WarnUnusedImports | Opt_WarnUnusedMatches | Opt_WarnWarningsDeprecations | Opt_WarnDeprecatedFlags | Opt_WarnAMP | Opt_WarnDodgyExports | Opt_WarnDodgyImports | Opt_WarnOrphans | Opt_WarnAutoOrphans | Opt_WarnIdentities | Opt_WarnTabs | Opt_WarnUnrecognisedPragmas | Opt_WarnDodgyForeignImports | Opt_WarnLazyUnliftedBindings | Opt_WarnUnusedDoBind | Opt_WarnWrongDoBind | Opt_WarnAlternativeLayoutRuleTransitional | Opt_WarnUnsafe | Opt_WarnSafe | Opt_WarnPointlessPragmas | Opt_WarnUnsupportedCallingConventions | Opt_WarnUnsupportedLlvmVersion | Opt_WarnInlineRuleShadowing deriving (Eq, Show, Enum) data Language = Haskell98 | Haskell2010 deriving Enum -- | The various Safe Haskell modes data SafeHaskellMode = Sf_None | Sf_Unsafe | Sf_Trustworthy | Sf_Safe | Sf_SafeInferred deriving (Eq) instance Show SafeHaskellMode where show Sf_None = "None" show Sf_Unsafe = "Unsafe" show Sf_Trustworthy = "Trustworthy" show Sf_Safe = "Safe" show Sf_SafeInferred = "Safe-Inferred" instance Outputable SafeHaskellMode where ppr = text . show data ExtensionFlag = Opt_Cpp | Opt_OverlappingInstances | Opt_UndecidableInstances | Opt_IncoherentInstances | Opt_MonomorphismRestriction | Opt_MonoPatBinds | Opt_MonoLocalBinds | Opt_RelaxedPolyRec -- Deprecated | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting | Opt_ForeignFunctionInterface | Opt_UnliftedFFITypes | Opt_InterruptibleFFI | Opt_CApiFFI | Opt_GHCForeignImportPrim | Opt_JavaScriptFFI | Opt_ParallelArrays -- Syntactic support for parallel arrays | Opt_Arrows -- Arrow-notation syntax | Opt_TemplateHaskell | Opt_QuasiQuotes | Opt_ImplicitParams | Opt_ImplicitPrelude | Opt_ScopedTypeVariables | Opt_AllowAmbiguousTypes | Opt_UnboxedTuples | Opt_BangPatterns | Opt_TypeFamilies | Opt_OverloadedStrings | Opt_OverloadedLists | Opt_NumDecimals | Opt_DisambiguateRecordFields | Opt_RecordWildCards | Opt_RecordPuns | Opt_ViewPatterns | Opt_GADTs | Opt_GADTSyntax | Opt_NPlusKPatterns | Opt_DoAndIfThenElse | Opt_RebindableSyntax | Opt_ConstraintKinds | Opt_PolyKinds -- Kind polymorphism | Opt_DataKinds -- Datatype promotion | Opt_InstanceSigs | Opt_StandaloneDeriving | Opt_DeriveDataTypeable | Opt_AutoDeriveTypeable -- Automatic derivation of Typeable | Opt_DeriveFunctor | Opt_DeriveTraversable | Opt_DeriveFoldable | Opt_DeriveGeneric -- Allow deriving Generic/1 | Opt_DefaultSignatures -- Allow extra signatures for defmeths | Opt_TypeSynonymInstances | Opt_FlexibleContexts | Opt_FlexibleInstances | Opt_ConstrainedClassMethods | Opt_MultiParamTypeClasses | Opt_NullaryTypeClasses | Opt_FunctionalDependencies | Opt_UnicodeSyntax | Opt_ExistentialQuantification | Opt_MagicHash | Opt_EmptyDataDecls | Opt_KindSignatures | Opt_RoleAnnotations | Opt_ParallelListComp | Opt_TransformListComp | Opt_MonadComprehensions | Opt_GeneralizedNewtypeDeriving | Opt_RecursiveDo | Opt_PostfixOperators | Opt_TupleSections | Opt_PatternGuards | Opt_LiberalTypeSynonyms | Opt_RankNTypes | Opt_ImpredicativeTypes | Opt_TypeOperators | Opt_ExplicitNamespaces | Opt_PackageImports | Opt_ExplicitForAll | Opt_AlternativeLayoutRule | Opt_AlternativeLayoutRuleTransitional | Opt_DatatypeContexts | Opt_NondecreasingIndentation | Opt_RelaxedLayout | Opt_TraditionalRecordSyntax | Opt_LambdaCase | Opt_MultiWayIf | Opt_TypeHoles | Opt_NegativeLiterals | Opt_EmptyCase deriving (Eq, Enum, Show) -- | Contains not only a collection of 'GeneralFlag's but also a plethora of -- information relating to the compilation of a single file or GHC session data DynFlags = DynFlags { ghcMode :: GhcMode, ghcLink :: GhcLink, hscTarget :: HscTarget, settings :: Settings, verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels] optLevel :: Int, -- ^ Optimisation level simplPhases :: Int, -- ^ Number of simplifier phases maxSimplIterations :: Int, -- ^ Max simplifier iterations shouldDumpSimplPhase :: Maybe String, ruleCheck :: Maybe String, strictnessBefore :: [Int], -- ^ Additional demand analysis parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel -- in --make mode, where Nothing ==> compile as -- many in parallel as there are CPUs. maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt -- to show in type error messages simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types -- Not optional; otherwise ForceSpecConstr can diverge. liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating -- See CoreMonad.FloatOutSwitches historySize :: Int, cmdlineHcIncludes :: [String], -- ^ @\-\#includes@ importPaths :: [FilePath], mainModIs :: Module, mainFunIs :: Maybe String, ctxtStkDepth :: Int, -- ^ Typechecker context stack depth thisPackage :: PackageId, -- ^ name of package currently being compiled -- ways ways :: [Way], -- ^ Way flags from the command line buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof) rtsBuildTag :: String, -- ^ The RTS \"way\" -- For object splitting splitInfo :: Maybe (String,Int), -- paths etc. objectDir :: Maybe String, dylibInstallName :: Maybe String, hiDir :: Maybe String, stubDir :: Maybe String, dumpDir :: Maybe String, objectSuf :: String, hcSuf :: String, hiSuf :: String, canGenerateDynamicToo :: IORef Bool, dynObjectSuf :: String, dynHiSuf :: String, -- Packages.isDllName needs to know whether a call is within a -- single DLL or not. Normally it does this by seeing if the call -- is to the same package, but for the ghc package, we split the -- package between 2 DLLs. The dllSplit tells us which sets of -- modules are in which package. dllSplitFile :: Maybe FilePath, dllSplit :: Maybe [Set String], outputFile :: Maybe String, dynOutputFile :: Maybe String, outputHi :: Maybe String, dynLibLoader :: DynLibLoader, -- | This is set by 'DriverPipeline.runPipeline' based on where -- its output is going. dumpPrefix :: Maybe FilePath, -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'. -- Set by @-ddump-file-prefix@ dumpPrefixForce :: Maybe FilePath, ldInputs :: [Option], includePaths :: [String], libraryPaths :: [String], frameworkPaths :: [String], -- used on darwin only cmdlineFrameworks :: [String], -- ditto rtsOpts :: Maybe String, rtsOptsEnabled :: RtsOptsEnabled, hpcDir :: String, -- ^ Path to store the .mix files -- Plugins pluginModNames :: [ModuleName], pluginModNameOpts :: [(ModuleName,String)], -- GHC API hooks hooks :: Hooks, -- For ghc -M depMakefile :: FilePath, depIncludePkgDeps :: Bool, depExcludeMods :: [ModuleName], depSuffixes :: [String], -- Package flags extraPkgConfs :: [PkgConfRef] -> [PkgConfRef], -- ^ The @-package-db@ flags given on the command line, in the order -- they appeared. packageFlags :: [PackageFlag], -- ^ The @-package@ and @-hide-package@ flags from the command-line -- Package state -- NB. do not modify this field, it is calculated by -- Packages.initPackages and Packages.updatePackages. pkgDatabase :: Maybe [PackageConfig], pkgState :: PackageState, -- Temporary files -- These have to be IORefs, because the defaultCleanupHandler needs to -- know what to clean when an exception happens filesToClean :: IORef [FilePath], dirsToClean :: IORef (Map FilePath FilePath), filesToNotIntermediateClean :: IORef [FilePath], -- The next available suffix to uniquely name a temp file, updated atomically nextTempSuffix :: IORef Int, -- Names of files which were generated from -ddump-to-file; used to -- track which ones we need to truncate because it's our first run -- through generatedDumps :: IORef (Set FilePath), -- hsc dynamic flags dumpFlags :: IntSet, generalFlags :: IntSet, warningFlags :: IntSet, -- Don't change this without updating extensionFlags: language :: Maybe Language, -- | Safe Haskell mode safeHaskell :: SafeHaskellMode, -- We store the location of where some extension and flags were turned on so -- we can produce accurate error messages when Safe Haskell fails due to -- them. thOnLoc :: SrcSpan, newDerivOnLoc :: SrcSpan, pkgTrustOnLoc :: SrcSpan, warnSafeOnLoc :: SrcSpan, warnUnsafeOnLoc :: SrcSpan, -- Don't change this without updating extensionFlags: extensions :: [OnOff ExtensionFlag], -- extensionFlags should always be equal to -- flattenExtensionFlags language extensions extensionFlags :: IntSet, -- Unfolding control -- See Note [Discounts and thresholds] in CoreUnfold ufCreationThreshold :: Int, ufUseThreshold :: Int, ufFunAppDiscount :: Int, ufDictDiscount :: Int, ufKeenessFactor :: Float, ufDearOp :: Int, maxWorkerArgs :: Int, ghciHistSize :: Int, -- | MsgDoc output action: use "ErrUtils" instead of this if you can log_action :: LogAction, flushOut :: FlushOut, flushErr :: FlushErr, haddockOptions :: Maybe String, ghciScripts :: [String], -- Output style options pprUserLength :: Int, pprCols :: Int, traceLevel :: Int, -- Standard level is 1. Less verbose is 0. useUnicodeQuotes :: Bool, -- | what kind of {-# SCC #-} to add automatically profAuto :: ProfAuto, interactivePrint :: Maybe String, llvmVersion :: IORef Int, nextWrapperNum :: IORef (ModuleEnv Int), -- | Machine dependant flags (-m<blah> stuff) sseVersion :: Maybe (Int, Int), -- (major, minor) avx :: Bool, avx2 :: Bool, avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions. avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions. avx512f :: Bool, -- Enable AVX-512 instructions. avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions. -- | Run-time linker information (what options we need, etc.) rtldFlags :: IORef (Maybe LinkerInfo) } class HasDynFlags m where getDynFlags :: m DynFlags class ContainsDynFlags t where extractDynFlags :: t -> DynFlags replaceDynFlags :: t -> DynFlags -> t data ProfAuto = NoProfAuto -- ^ no SCC annotations added | ProfAutoAll -- ^ top-level and nested functions are annotated | ProfAutoTop -- ^ top-level functions annotated only | ProfAutoExports -- ^ exported functions annotated only | ProfAutoCalls -- ^ annotate call-sites deriving (Enum) data Settings = Settings { sTargetPlatform :: Platform, -- Filled in by SysTools sGhcUsagePath :: FilePath, -- Filled in by SysTools sGhciUsagePath :: FilePath, -- ditto sTopDir :: FilePath, sTmpDir :: String, -- no trailing '/' -- You shouldn't need to look things up in rawSettings directly. -- They should have their own fields instead. sRawSettings :: [(String, String)], sExtraGccViaCFlags :: [String], sSystemPackageConfig :: FilePath, sLdSupportsCompactUnwind :: Bool, sLdSupportsBuildId :: Bool, sLdSupportsFilelist :: Bool, sLdIsGnuLd :: Bool, -- commands for particular phases sPgm_L :: String, sPgm_P :: (String,[Option]), sPgm_F :: String, sPgm_c :: (String,[Option]), sPgm_s :: (String,[Option]), sPgm_a :: (String,[Option]), sPgm_l :: (String,[Option]), sPgm_dll :: (String,[Option]), sPgm_T :: String, sPgm_sysman :: String, sPgm_windres :: String, sPgm_libtool :: String, sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler -- options for particular phases sOpt_L :: [String], sOpt_P :: [String], sOpt_F :: [String], sOpt_c :: [String], sOpt_a :: [String], sOpt_l :: [String], sOpt_windres :: [String], sOpt_lo :: [String], -- LLVM: llvm optimiser sOpt_lc :: [String], -- LLVM: llc static compiler sPlatformConstants :: PlatformConstants } targetPlatform :: DynFlags -> Platform targetPlatform dflags = sTargetPlatform (settings dflags) ghcUsagePath :: DynFlags -> FilePath ghcUsagePath dflags = sGhcUsagePath (settings dflags) ghciUsagePath :: DynFlags -> FilePath ghciUsagePath dflags = sGhciUsagePath (settings dflags) topDir :: DynFlags -> FilePath topDir dflags = sTopDir (settings dflags) tmpDir :: DynFlags -> String tmpDir dflags = sTmpDir (settings dflags) rawSettings :: DynFlags -> [(String, String)] rawSettings dflags = sRawSettings (settings dflags) extraGccViaCFlags :: DynFlags -> [String] extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags) systemPackageConfig :: DynFlags -> FilePath systemPackageConfig dflags = sSystemPackageConfig (settings dflags) pgm_L :: DynFlags -> String pgm_L dflags = sPgm_L (settings dflags) pgm_P :: DynFlags -> (String,[Option]) pgm_P dflags = sPgm_P (settings dflags) pgm_F :: DynFlags -> String pgm_F dflags = sPgm_F (settings dflags) pgm_c :: DynFlags -> (String,[Option]) pgm_c dflags = sPgm_c (settings dflags) pgm_s :: DynFlags -> (String,[Option]) pgm_s dflags = sPgm_s (settings dflags) pgm_a :: DynFlags -> (String,[Option]) pgm_a dflags = sPgm_a (settings dflags) pgm_l :: DynFlags -> (String,[Option]) pgm_l dflags = sPgm_l (settings dflags) pgm_dll :: DynFlags -> (String,[Option]) pgm_dll dflags = sPgm_dll (settings dflags) pgm_T :: DynFlags -> String pgm_T dflags = sPgm_T (settings dflags) pgm_sysman :: DynFlags -> String pgm_sysman dflags = sPgm_sysman (settings dflags) pgm_windres :: DynFlags -> String pgm_windres dflags = sPgm_windres (settings dflags) pgm_libtool :: DynFlags -> String pgm_libtool dflags = sPgm_libtool (settings dflags) pgm_lo :: DynFlags -> (String,[Option]) pgm_lo dflags = sPgm_lo (settings dflags) pgm_lc :: DynFlags -> (String,[Option]) pgm_lc dflags = sPgm_lc (settings dflags) opt_L :: DynFlags -> [String] opt_L dflags = sOpt_L (settings dflags) opt_P :: DynFlags -> [String] opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags) ++ sOpt_P (settings dflags) opt_F :: DynFlags -> [String] opt_F dflags = sOpt_F (settings dflags) opt_c :: DynFlags -> [String] opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags) ++ sOpt_c (settings dflags) opt_a :: DynFlags -> [String] opt_a dflags = sOpt_a (settings dflags) opt_l :: DynFlags -> [String] opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags) ++ sOpt_l (settings dflags) opt_windres :: DynFlags -> [String] opt_windres dflags = sOpt_windres (settings dflags) opt_lo :: DynFlags -> [String] opt_lo dflags = sOpt_lo (settings dflags) opt_lc :: DynFlags -> [String] opt_lc dflags = sOpt_lc (settings dflags) -- | The target code type of the compilation (if any). -- -- Whenever you change the target, also make sure to set 'ghcLink' to -- something sensible. -- -- 'HscNothing' can be used to avoid generating any output, however, note -- that: -- -- * If a program uses Template Haskell the typechecker may try to run code -- from an imported module. This will fail if no code has been generated -- for this module. You can use 'GHC.needsTemplateHaskell' to detect -- whether this might be the case and choose to either switch to a -- different target or avoid typechecking such modules. (The latter may be -- preferable for security reasons.) -- data HscTarget = HscC -- ^ Generate C code. | HscAsm -- ^ Generate assembly using the native code generator. | HscLlvm -- ^ Generate assembly using the llvm code generator. | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory') | HscNothing -- ^ Don't generate any code. See notes above. deriving (Eq, Show) -- | Will this target result in an object file on the disk? isObjectTarget :: HscTarget -> Bool isObjectTarget HscC = True isObjectTarget HscAsm = True isObjectTarget HscLlvm = True isObjectTarget _ = False -- | Does this target retain *all* top-level bindings for a module, -- rather than just the exported bindings, in the TypeEnv and compiled -- code (if any)? In interpreted mode we do this, so that GHCi can -- call functions inside a module. In HscNothing mode we also do it, -- so that Haddock can get access to the GlobalRdrEnv for a module -- after typechecking it. targetRetainsAllBindings :: HscTarget -> Bool targetRetainsAllBindings HscInterpreted = True targetRetainsAllBindings HscNothing = True targetRetainsAllBindings _ = False -- | The 'GhcMode' tells us whether we're doing multi-module -- compilation (controlled via the "GHC" API) or one-shot -- (single-module) compilation. This makes a difference primarily to -- the "Finder": in one-shot mode we look for interface files for -- imported modules, but in multi-module mode we look for source files -- in order to check whether they need to be recompiled. data GhcMode = CompManager -- ^ @\-\-make@, GHCi, etc. | OneShot -- ^ @ghc -c Foo.hs@ | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this deriving Eq instance Outputable GhcMode where ppr CompManager = ptext (sLit "CompManager") ppr OneShot = ptext (sLit "OneShot") ppr MkDepend = ptext (sLit "MkDepend") isOneShot :: GhcMode -> Bool isOneShot OneShot = True isOneShot _other = False -- | What to do in the link step, if there is one. data GhcLink = NoLink -- ^ Don't link at all | LinkBinary -- ^ Link object code into a binary | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both -- bytecode and object code). | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms) | LinkStaticLib -- ^ Link objects into a static lib deriving (Eq, Show) isNoLink :: GhcLink -> Bool isNoLink NoLink = True isNoLink _ = False data PackageFlag = ExposePackage String | ExposePackageId String | HidePackage String | IgnorePackage String | TrustPackage String | DistrustPackage String deriving (Eq, Show) defaultHscTarget :: Platform -> HscTarget defaultHscTarget = defaultObjectTarget -- | The 'HscTarget' value corresponding to the default way to create -- object files on the current platform. defaultObjectTarget :: Platform -> HscTarget defaultObjectTarget platform | platformUnregisterised platform = HscC | cGhcWithNativeCodeGen == "YES" = HscAsm | otherwise = HscLlvm tablesNextToCode :: DynFlags -> Bool tablesNextToCode dflags = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags)) -- Determines whether we will be compiling -- info tables that reside just before the entry code, or with an -- indirection to the entry code. See TABLES_NEXT_TO_CODE in -- includes/rts/storage/InfoTables.h. mkTablesNextToCode :: Bool -> Bool mkTablesNextToCode unregisterised = not unregisterised && cGhcEnableTablesNextToCode == "YES" data DynLibLoader = Deployable | SystemDependent deriving Eq data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll deriving (Show) ----------------------------------------------------------------------------- -- Ways -- The central concept of a "way" is that all objects in a given -- program must be compiled in the same "way". Certain options change -- parameters of the virtual machine, eg. profiling adds an extra word -- to the object header, so profiling objects cannot be linked with -- non-profiling objects. -- After parsing the command-line options, we determine which "way" we -- are building - this might be a combination way, eg. profiling+threaded. -- We then find the "build-tag" associated with this way, and this -- becomes the suffix used to find .hi files and libraries used in -- this compilation. data Way = WayCustom String -- for GHC API clients building custom variants | WayThreaded | WayDebug | WayProf | WayEventLog | WayPar | WayGran | WayNDP | WayDyn deriving (Eq, Ord, Show) allowed_combination :: [Way] -> Bool allowed_combination way = and [ x `allowedWith` y | x <- way, y <- way, x < y ] where -- Note ordering in these tests: the left argument is -- <= the right argument, according to the Ord instance -- on Way above. -- dyn is allowed with everything _ `allowedWith` WayDyn = True WayDyn `allowedWith` _ = True -- debug is allowed with everything _ `allowedWith` WayDebug = True WayDebug `allowedWith` _ = True (WayCustom {}) `allowedWith` _ = True WayProf `allowedWith` WayNDP = True WayThreaded `allowedWith` WayProf = True WayThreaded `allowedWith` WayEventLog = True _ `allowedWith` _ = False mkBuildTag :: [Way] -> String mkBuildTag ways = concat (intersperse "_" (map wayTag ways)) wayTag :: Way -> String wayTag (WayCustom xs) = xs wayTag WayThreaded = "thr" wayTag WayDebug = "debug" wayTag WayDyn = "dyn" wayTag WayProf = "p" wayTag WayEventLog = "l" wayTag WayPar = "mp" wayTag WayGran = "mg" wayTag WayNDP = "ndp" wayRTSOnly :: Way -> Bool wayRTSOnly (WayCustom {}) = False wayRTSOnly WayThreaded = True wayRTSOnly WayDebug = True wayRTSOnly WayDyn = False wayRTSOnly WayProf = False wayRTSOnly WayEventLog = True wayRTSOnly WayPar = False wayRTSOnly WayGran = False wayRTSOnly WayNDP = False wayDesc :: Way -> String wayDesc (WayCustom xs) = xs wayDesc WayThreaded = "Threaded" wayDesc WayDebug = "Debug" wayDesc WayDyn = "Dynamic" wayDesc WayProf = "Profiling" wayDesc WayEventLog = "RTS Event Logging" wayDesc WayPar = "Parallel" wayDesc WayGran = "GranSim" wayDesc WayNDP = "Nested data parallelism" -- Turn these flags on when enabling this way wayGeneralFlags :: Platform -> Way -> [GeneralFlag] wayGeneralFlags _ (WayCustom {}) = [] wayGeneralFlags _ WayThreaded = [] wayGeneralFlags _ WayDebug = [] wayGeneralFlags _ WayDyn = [Opt_PIC] wayGeneralFlags _ WayProf = [Opt_SccProfilingOn] wayGeneralFlags _ WayEventLog = [] wayGeneralFlags _ WayPar = [Opt_Parallel] wayGeneralFlags _ WayGran = [Opt_GranMacros] wayGeneralFlags _ WayNDP = [] -- Turn these flags off when enabling this way wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag] wayUnsetGeneralFlags _ (WayCustom {}) = [] wayUnsetGeneralFlags _ WayThreaded = [] wayUnsetGeneralFlags _ WayDebug = [] wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects -- when we're going to be dynamically -- linking. Plus it breaks compilation -- on OSX x86. Opt_SplitObjs] wayUnsetGeneralFlags _ WayProf = [] wayUnsetGeneralFlags _ WayEventLog = [] wayUnsetGeneralFlags _ WayPar = [] wayUnsetGeneralFlags _ WayGran = [] wayUnsetGeneralFlags _ WayNDP = [] wayExtras :: Platform -> Way -> DynFlags -> DynFlags wayExtras _ (WayCustom {}) dflags = dflags wayExtras _ WayThreaded dflags = dflags wayExtras _ WayDebug dflags = dflags wayExtras _ WayDyn dflags = dflags wayExtras _ WayProf dflags = dflags wayExtras _ WayEventLog dflags = dflags wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags wayExtras _ WayGran dflags = exposePackage' "concurrent" dflags wayExtras _ WayNDP dflags = setExtensionFlag' Opt_ParallelArrays $ setGeneralFlag' Opt_Vectorise dflags wayOptc :: Platform -> Way -> [String] wayOptc _ (WayCustom {}) = [] wayOptc platform WayThreaded = case platformOS platform of OSOpenBSD -> ["-pthread"] OSNetBSD -> ["-pthread"] _ -> [] wayOptc _ WayDebug = [] wayOptc _ WayDyn = [] wayOptc _ WayProf = ["-DPROFILING"] wayOptc _ WayEventLog = ["-DTRACING"] wayOptc _ WayPar = ["-DPAR", "-w"] wayOptc _ WayGran = ["-DGRAN"] wayOptc _ WayNDP = [] wayOptl :: Platform -> Way -> [String] wayOptl _ (WayCustom {}) = [] wayOptl platform WayThreaded = case platformOS platform of -- FreeBSD's default threading library is the KSE-based M:N libpthread, -- which GHC has some problems with. It's currently not clear whether -- the problems are our fault or theirs, but it seems that using the -- alternative 1:1 threading library libthr works around it: OSFreeBSD -> ["-lthr"] OSSolaris2 -> ["-lrt"] OSOpenBSD -> ["-pthread"] OSNetBSD -> ["-pthread"] _ -> [] wayOptl _ WayDebug = [] wayOptl _ WayDyn = [] wayOptl _ WayProf = [] wayOptl _ WayEventLog = [] wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}", "-lpvm3", "-lgpvm3"] wayOptl _ WayGran = [] wayOptl _ WayNDP = [] wayOptP :: Platform -> Way -> [String] wayOptP _ (WayCustom {}) = [] wayOptP _ WayThreaded = [] wayOptP _ WayDebug = [] wayOptP _ WayDyn = [] wayOptP _ WayProf = ["-DPROFILING"] wayOptP _ WayEventLog = ["-DTRACING"] wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"] wayOptP _ WayGran = ["-D__GRANSIM__"] wayOptP _ WayNDP = [] whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m () whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ()) ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m () whenCannotGenerateDynamicToo dflags f = ifCannotGenerateDynamicToo dflags f (return ()) ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a ifCannotGenerateDynamicToo dflags f g = generateDynamicTooConditional dflags g f g generateDynamicTooConditional :: MonadIO m => DynFlags -> m a -> m a -> m a -> m a generateDynamicTooConditional dflags canGen cannotGen notTryingToGen = if gopt Opt_BuildDynamicToo dflags then do let ref = canGenerateDynamicToo dflags b <- liftIO $ readIORef ref if b then canGen else cannotGen else notTryingToGen dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags dynamicTooMkDynamicDynFlags dflags0 = let dflags1 = addWay' WayDyn dflags0 dflags2 = dflags1 { outputFile = dynOutputFile dflags1, hiSuf = dynHiSuf dflags1, objectSuf = dynObjectSuf dflags1 } dflags3 = updateWays dflags2 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo in dflags4 ----------------------------------------------------------------------------- -- | Used by 'GHC.newSession' to partially initialize a new 'DynFlags' value initDynFlags :: DynFlags -> IO DynFlags initDynFlags dflags = do let -- We can't build with dynamic-too on Windows, as labels before -- the fork point are different depending on whether we are -- building dynamically or not. platformCanGenerateDynamicToo = platformOS (targetPlatform dflags) /= OSMinGW32 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo refNextTempSuffix <- newIORef 0 refFilesToClean <- newIORef [] refDirsToClean <- newIORef Map.empty refFilesToNotIntermediateClean <- newIORef [] refGeneratedDumps <- newIORef Set.empty refLlvmVersion <- newIORef 28 refRtldFlags <- newIORef Nothing wrapperNum <- newIORef emptyModuleEnv canUseUnicodeQuotes <- do let enc = localeEncoding str = "‛’" (withCString enc str $ \cstr -> do str' <- peekCString enc cstr return (str == str')) `catchIOError` \_ -> return False return dflags{ canGenerateDynamicToo = refCanGenerateDynamicToo, nextTempSuffix = refNextTempSuffix, filesToClean = refFilesToClean, dirsToClean = refDirsToClean, filesToNotIntermediateClean = refFilesToNotIntermediateClean, generatedDumps = refGeneratedDumps, llvmVersion = refLlvmVersion, nextWrapperNum = wrapperNum, useUnicodeQuotes = canUseUnicodeQuotes, rtldFlags = refRtldFlags } -- | The normal 'DynFlags'. Note that they is not suitable for use in this form -- and must be fully initialized by 'GHC.newSession' first. defaultDynFlags :: Settings -> DynFlags defaultDynFlags mySettings = DynFlags { ghcMode = CompManager, ghcLink = LinkBinary, hscTarget = defaultHscTarget (sTargetPlatform mySettings), verbosity = 0, optLevel = 0, simplPhases = 2, maxSimplIterations = 4, shouldDumpSimplPhase = Nothing, ruleCheck = Nothing, maxRelevantBinds = Just 6, simplTickFactor = 100, specConstrThreshold = Just 2000, specConstrCount = Just 3, specConstrRecursive = 3, liberateCaseThreshold = Just 2000, floatLamArgs = Just 0, -- Default: float only if no fvs historySize = 20, strictnessBefore = [], parMakeCount = Just 1, cmdlineHcIncludes = [], importPaths = ["."], mainModIs = mAIN, mainFunIs = Nothing, ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH, thisPackage = mainPackageId, objectDir = Nothing, dylibInstallName = Nothing, hiDir = Nothing, stubDir = Nothing, dumpDir = Nothing, objectSuf = phaseInputExt StopLn, hcSuf = phaseInputExt HCc, hiSuf = "hi", canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo", dynObjectSuf = "dyn_" ++ phaseInputExt StopLn, dynHiSuf = "dyn_hi", dllSplitFile = Nothing, dllSplit = Nothing, pluginModNames = [], pluginModNameOpts = [], hooks = emptyHooks, outputFile = Nothing, dynOutputFile = Nothing, outputHi = Nothing, dynLibLoader = SystemDependent, dumpPrefix = Nothing, dumpPrefixForce = Nothing, ldInputs = [], includePaths = [], libraryPaths = [], frameworkPaths = [], cmdlineFrameworks = [], rtsOpts = Nothing, rtsOptsEnabled = RtsOptsSafeOnly, hpcDir = ".hpc", extraPkgConfs = id, packageFlags = [], pkgDatabase = Nothing, pkgState = panic "no package state yet: call GHC.setSessionDynFlags", ways = defaultWays mySettings, buildTag = mkBuildTag (defaultWays mySettings), rtsBuildTag = mkBuildTag (defaultWays mySettings), splitInfo = Nothing, settings = mySettings, -- ghc -M values depMakefile = "Makefile", depIncludePkgDeps = False, depExcludeMods = [], depSuffixes = [], -- end of ghc -M values nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix", filesToClean = panic "defaultDynFlags: No filesToClean", dirsToClean = panic "defaultDynFlags: No dirsToClean", filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean", generatedDumps = panic "defaultDynFlags: No generatedDumps", haddockOptions = Nothing, dumpFlags = IntSet.empty, generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)), warningFlags = IntSet.fromList (map fromEnum standardWarnings), ghciScripts = [], language = Nothing, safeHaskell = Sf_SafeInferred, thOnLoc = noSrcSpan, newDerivOnLoc = noSrcSpan, pkgTrustOnLoc = noSrcSpan, warnSafeOnLoc = noSrcSpan, warnUnsafeOnLoc = noSrcSpan, extensions = [], extensionFlags = flattenExtensionFlags Nothing [], -- The ufCreationThreshold threshold must be reasonably high to -- take account of possible discounts. -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline -- into Csg.calc (The unfolding for sqr never makes it into the -- interface file.) ufCreationThreshold = 750, ufUseThreshold = 60, ufFunAppDiscount = 60, -- Be fairly keen to inline a fuction if that means -- we'll be able to pick the right method from a dictionary ufDictDiscount = 30, ufKeenessFactor = 1.5, ufDearOp = 40, maxWorkerArgs = 10, ghciHistSize = 50, -- keep a log of length 50 by default log_action = defaultLogAction, flushOut = defaultFlushOut, flushErr = defaultFlushErr, pprUserLength = 5, pprCols = 100, useUnicodeQuotes = False, traceLevel = 1, profAuto = NoProfAuto, llvmVersion = panic "defaultDynFlags: No llvmVersion", interactivePrint = Nothing, nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum", sseVersion = Nothing, avx = False, avx2 = False, avx512cd = False, avx512er = False, avx512f = False, avx512pf = False, rtldFlags = panic "defaultDynFlags: no rtldFlags" } defaultWays :: Settings -> [Way] defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings) then [WayDyn] else [] interpWays :: [Way] interpWays = if cDYNAMIC_GHC_PROGRAMS then [WayDyn] else [] -------------------------------------------------------------------------- type FatalMessager = String -> IO () type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO () defaultFatalMessager :: FatalMessager defaultFatalMessager = hPutStrLn stderr defaultLogAction :: LogAction defaultLogAction dflags severity srcSpan style msg = case severity of SevOutput -> printSDoc msg style SevDump -> printSDoc (msg $$ blankLine) style SevInteractive -> putStrSDoc msg style SevInfo -> printErrs msg style SevFatal -> printErrs msg style _ -> do hPutChar stderr '\n' printErrs (mkLocMessage severity srcSpan msg) style -- careful (#2302): printErrs prints in UTF-8, -- whereas converting to string first and using -- hPutStr would just emit the low 8 bits of -- each unicode char. where printSDoc = defaultLogActionHPrintDoc dflags stdout printErrs = defaultLogActionHPrintDoc dflags stderr putStrSDoc = defaultLogActionHPutStrDoc dflags stdout defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO () defaultLogActionHPrintDoc dflags h d sty = do let doc = runSDoc d (initSDocContext dflags sty) Pretty.printDoc Pretty.PageMode (pprCols dflags) h doc hFlush h defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO () defaultLogActionHPutStrDoc dflags h d sty = do let doc = runSDoc d (initSDocContext dflags sty) hPutStr h (Pretty.render doc) hFlush h newtype FlushOut = FlushOut (IO ()) defaultFlushOut :: FlushOut defaultFlushOut = FlushOut $ hFlush stdout newtype FlushErr = FlushErr (IO ()) defaultFlushErr :: FlushErr defaultFlushErr = FlushErr $ hFlush stderr printOutputForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO () printOutputForUser = printSevForUser SevOutput printInfoForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO () printInfoForUser = printSevForUser SevInfo printSevForUser :: Severity -> DynFlags -> PrintUnqualified -> SDoc -> IO () printSevForUser sev dflags unqual doc = log_action dflags dflags sev noSrcSpan (mkUserStyle unqual AllTheWay) doc {- Note [Verbosity levels] ~~~~~~~~~~~~~~~~~~~~~~~ 0 | print errors & warnings only 1 | minimal verbosity: print "compiling M ... done." for each module. 2 | equivalent to -dshow-passes 3 | equivalent to existing "ghc -v" 4 | "ghc -v -ddump-most" 5 | "ghc -v -ddump-all" -} data OnOff a = On a | Off a -- OnOffs accumulate in reverse order, so we use foldr in order to -- process them in the right order flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet flattenExtensionFlags ml = foldr f defaultExtensionFlags where f (On f) flags = IntSet.insert (fromEnum f) flags f (Off f) flags = IntSet.delete (fromEnum f) flags defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml)) languageExtensions :: Maybe Language -> [ExtensionFlag] languageExtensions Nothing -- Nothing => the default case = Opt_NondecreasingIndentation -- This has been on by default for some time : delete Opt_DatatypeContexts -- The Haskell' committee decided to -- remove datatype contexts from the -- language: -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html (languageExtensions (Just Haskell2010)) -- NB: MonoPatBinds is no longer the default languageExtensions (Just Haskell98) = [Opt_ImplicitPrelude, Opt_MonomorphismRestriction, Opt_NPlusKPatterns, Opt_DatatypeContexts, Opt_TraditionalRecordSyntax, Opt_NondecreasingIndentation -- strictly speaking non-standard, but we always had this -- on implicitly before the option was added in 7.1, and -- turning it off breaks code, so we're keeping it on for -- backwards compatibility. Cabal uses -XHaskell98 by -- default unless you specify another language. ] languageExtensions (Just Haskell2010) = [Opt_ImplicitPrelude, Opt_MonomorphismRestriction, Opt_DatatypeContexts, Opt_TraditionalRecordSyntax, Opt_EmptyDataDecls, Opt_ForeignFunctionInterface, Opt_PatternGuards, Opt_DoAndIfThenElse, Opt_RelaxedPolyRec] -- | Test whether a 'DumpFlag' is set dopt :: DumpFlag -> DynFlags -> Bool dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags) || (verbosity dflags >= 4 && enableIfVerbose f) where enableIfVerbose Opt_D_dump_tc_trace = False enableIfVerbose Opt_D_dump_rn_trace = False enableIfVerbose Opt_D_dump_cs_trace = False enableIfVerbose Opt_D_dump_if_trace = False enableIfVerbose Opt_D_dump_vt_trace = False enableIfVerbose Opt_D_dump_tc = False enableIfVerbose Opt_D_dump_rn = False enableIfVerbose Opt_D_dump_rn_stats = False enableIfVerbose Opt_D_dump_hi_diffs = False enableIfVerbose Opt_D_verbose_core2core = False enableIfVerbose Opt_D_verbose_stg2stg = False enableIfVerbose Opt_D_dump_splices = False enableIfVerbose Opt_D_dump_rule_firings = False enableIfVerbose Opt_D_dump_rule_rewrites = False enableIfVerbose Opt_D_dump_simpl_trace = False enableIfVerbose Opt_D_dump_rtti = False enableIfVerbose Opt_D_dump_inlinings = False enableIfVerbose Opt_D_dump_core_stats = False enableIfVerbose Opt_D_dump_asm_stats = False enableIfVerbose Opt_D_dump_types = False enableIfVerbose Opt_D_dump_simpl_iterations = False enableIfVerbose Opt_D_dump_ticked = False enableIfVerbose Opt_D_dump_view_pattern_commoning = False enableIfVerbose Opt_D_dump_mod_cycles = False enableIfVerbose _ = True -- | Set a 'DumpFlag' dopt_set :: DynFlags -> DumpFlag -> DynFlags dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) } -- | Unset a 'DumpFlag' dopt_unset :: DynFlags -> DumpFlag -> DynFlags dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) } -- | Test whether a 'GeneralFlag' is set gopt :: GeneralFlag -> DynFlags -> Bool gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags -- | Set a 'GeneralFlag' gopt_set :: DynFlags -> GeneralFlag -> DynFlags gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) } -- | Unset a 'GeneralFlag' gopt_unset :: DynFlags -> GeneralFlag -> DynFlags gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) } -- | Test whether a 'WarningFlag' is set wopt :: WarningFlag -> DynFlags -> Bool wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags -- | Set a 'WarningFlag' wopt_set :: DynFlags -> WarningFlag -> DynFlags wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) } -- | Unset a 'WarningFlag' wopt_unset :: DynFlags -> WarningFlag -> DynFlags wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) } -- | Test whether a 'ExtensionFlag' is set xopt :: ExtensionFlag -> DynFlags -> Bool xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags -- | Set a 'ExtensionFlag' xopt_set :: DynFlags -> ExtensionFlag -> DynFlags xopt_set dfs f = let onoffs = On f : extensions dfs in dfs { extensions = onoffs, extensionFlags = flattenExtensionFlags (language dfs) onoffs } -- | Unset a 'ExtensionFlag' xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags xopt_unset dfs f = let onoffs = Off f : extensions dfs in dfs { extensions = onoffs, extensionFlags = flattenExtensionFlags (language dfs) onoffs } lang_set :: DynFlags -> Maybe Language -> DynFlags lang_set dflags lang = dflags { language = lang, extensionFlags = flattenExtensionFlags lang (extensions dflags) } -- | Set the Haskell language standard to use setLanguage :: Language -> DynP () setLanguage l = upd (`lang_set` Just l) -- | Some modules have dependencies on others through the DynFlags rather than textual imports dynFlagDependencies :: DynFlags -> [ModuleName] dynFlagDependencies = pluginModNames -- | Is the -fpackage-trust mode on packageTrustOn :: DynFlags -> Bool packageTrustOn = gopt Opt_PackageTrust -- | Is Safe Haskell on in some way (including inference mode) safeHaskellOn :: DynFlags -> Bool safeHaskellOn dflags = safeHaskell dflags /= Sf_None -- | Is the Safe Haskell safe language in use safeLanguageOn :: DynFlags -> Bool safeLanguageOn dflags = safeHaskell dflags == Sf_Safe -- | Is the Safe Haskell safe inference mode active safeInferOn :: DynFlags -> Bool safeInferOn dflags = safeHaskell dflags == Sf_SafeInferred -- | Test if Safe Imports are on in some form safeImportsOn :: DynFlags -> Bool safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe || safeHaskell dflags == Sf_Trustworthy || safeHaskell dflags == Sf_Safe -- | Set a 'Safe Haskell' flag setSafeHaskell :: SafeHaskellMode -> DynP () setSafeHaskell s = updM f where f dfs = do let sf = safeHaskell dfs safeM <- combineSafeFlags sf s return $ dfs { safeHaskell = safeM } -- | Are all direct imports required to be safe for this Safe Haskell mode? -- Direct imports are when the code explicitly imports a module safeDirectImpsReq :: DynFlags -> Bool safeDirectImpsReq d = safeLanguageOn d -- | Are all implicit imports required to be safe for this Safe Haskell mode? -- Implicit imports are things in the prelude. e.g System.IO when print is used. safeImplicitImpsReq :: DynFlags -> Bool safeImplicitImpsReq d = safeLanguageOn d -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags. -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't -- want to export this functionality from the module but do want to export the -- type constructors. combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode combineSafeFlags a b | a == Sf_SafeInferred = return b | b == Sf_SafeInferred = return a | a == Sf_None = return b | b == Sf_None = return a | a == b = return a | otherwise = addErr errm >> return (panic errm) where errm = "Incompatible Safe Haskell flags! (" ++ show a ++ ", " ++ show b ++ ")" -- | A list of unsafe flags under Safe Haskell. Tuple elements are: -- * name of the flag -- * function to get srcspan that enabled the flag -- * function to test if the flag is on -- * function to turn the flag off unsafeFlags :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)] unsafeFlags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc, xopt Opt_GeneralizedNewtypeDeriving, flip xopt_unset Opt_GeneralizedNewtypeDeriving), ("-XTemplateHaskell", thOnLoc, xopt Opt_TemplateHaskell, flip xopt_unset Opt_TemplateHaskell)] -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors -> [a] -- ^ Correctly ordered extracted options getOpts dflags opts = reverse (opts dflags) -- We add to the options from the front, so we need to reverse the list -- | Gets the verbosity flag for the current verbosity level. This is fed to -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included getVerbFlags :: DynFlags -> [String] getVerbFlags dflags | verbosity dflags >= 4 = ["-v"] | otherwise = [] setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir, setDynObjectSuf, setDynHiSuf, setDylibInstallName, setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode, setPgmP, addOptl, addOptc, addOptP, addCmdlineFramework, addHaddockOpts, addGhciScript, setInteractivePrint :: String -> DynFlags -> DynFlags setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce :: Maybe String -> DynFlags -> DynFlags setObjectDir f d = d{ objectDir = Just f} setHiDir f d = d{ hiDir = Just f} setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d } -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file -- \#included from the .hc file when compiling via C (i.e. unregisterised -- builds). setDumpDir f d = d{ dumpDir = Just f} setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f setDylibInstallName f d = d{ dylibInstallName = Just f} setObjectSuf f d = d{ objectSuf = f} setDynObjectSuf f d = d{ dynObjectSuf = f} setHiSuf f d = d{ hiSuf = f} setDynHiSuf f d = d{ dynHiSuf = f} setHcSuf f d = d{ hcSuf = f} setOutputFile f d = d{ outputFile = f} setDynOutputFile f d = d{ dynOutputFile = f} setOutputHi f d = d{ outputHi = f} addPluginModuleName :: String -> DynFlags -> DynFlags addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) } addPluginModuleNameOption :: String -> DynFlags -> DynFlags addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) } where (m, rest) = break (== ':') optflag option = case rest of [] -> "" -- should probably signal an error (_:plug_opt) -> plug_opt -- ignore the ':' from break parseDynLibLoaderMode f d = case splitAt 8 f of ("deploy", "") -> d{ dynLibLoader = Deployable } ("sysdep", "") -> d{ dynLibLoader = SystemDependent } _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f)) setDumpPrefixForce f d = d { dumpPrefixForce = f} -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"] -- Config.hs should really use Option. setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)}) addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s}) addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s}) addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s}) setDepMakefile :: FilePath -> DynFlags -> DynFlags setDepMakefile f d = d { depMakefile = deOptDep f } setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags setDepIncludePkgDeps b d = d { depIncludePkgDeps = b } addDepExcludeMod :: String -> DynFlags -> DynFlags addDepExcludeMod m d = d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d } addDepSuffix :: FilePath -> DynFlags -> DynFlags addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d } -- XXX Legacy code: -- We used to use "-optdep-flag -optdeparg", so for legacy applications -- we need to strip the "-optdep" off of the arg deOptDep :: String -> String deOptDep x = case stripPrefix "-optdep" x of Just rest -> rest Nothing -> x addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d} addHaddockOpts f d = d{ haddockOptions = Just f} addGhciScript f d = d{ ghciScripts = f : ghciScripts d} setInteractivePrint f d = d{ interactivePrint = Just f} -- ----------------------------------------------------------------------------- -- Command-line options -- | When invoking external tools as part of the compilation pipeline, we -- pass these a sequence of options on the command-line. Rather than -- just using a list of Strings, we use a type that allows us to distinguish -- between filepaths and 'other stuff'. The reason for this is that -- this type gives us a handle on transforming filenames, and filenames only, -- to whatever format they're expected to be on a particular platform. data Option = FileOption -- an entry that _contains_ filename(s) / filepaths. String -- a non-filepath prefix that shouldn't be -- transformed (e.g., "/out=") String -- the filepath/filename portion | Option String deriving ( Eq ) showOpt :: Option -> String showOpt (FileOption pre f) = pre ++ f showOpt (Option s) = s ----------------------------------------------------------------------------- -- Setting the optimisation level updOptLevel :: Int -> DynFlags -> DynFlags -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level updOptLevel n dfs = dfs2{ optLevel = final_n } where final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2 dfs1 = foldr (flip gopt_unset) dfs remove_gopts dfs2 = foldr (flip gopt_set) dfs1 extra_gopts extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ] remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ] -- ----------------------------------------------------------------------------- -- StgToDo: abstraction of stg-to-stg passes to run. data StgToDo = StgDoMassageForProfiling -- should be (next to) last -- There's also setStgVarInfo, but its absolute "lastness" -- is so critical that it is hardwired in (no flag). | D_stg_stats getStgToDo :: DynFlags -> [StgToDo] getStgToDo dflags = todo2 where stg_stats = gopt Opt_StgStats dflags todo1 = if stg_stats then [D_stg_stats] else [] todo2 | WayProf `elem` ways dflags = StgDoMassageForProfiling : todo1 | otherwise = todo1 {- ********************************************************************** %* * DynFlags parser %* * %********************************************************************* -} -- ----------------------------------------------------------------------------- -- Parsing the dynamic flags. -- | Parse dynamic flags from a list of command line arguments. Returns the -- the parsed 'DynFlags', the left-over arguments, and a list of warnings. -- Throws a 'UsageError' if errors occurred during parsing (such as unknown -- flags or missing arguments). parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) -- ^ Updated 'DynFlags', left-over arguments, and -- list of warnings. parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db). -- Used to parse flags set in a modules pragma. parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) -- ^ Updated 'DynFlags', left-over arguments, and -- list of warnings. parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False -- | Parses the dynamically set flags for GHC. This is the most general form of -- the dynamic flag parser that the other methods simply wrap. It allows -- saying which flags are valid flags and indicating if we are parsing -- arguments from the command line or from a file pragma. parseDynamicFlagsFull :: MonadIO m => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against -> Bool -- ^ are the arguments from the command line? -> DynFlags -- ^ current dynamic flags -> [Located String] -- ^ arguments to parse -> m (DynFlags, [Located String], [Located String]) parseDynamicFlagsFull activeFlags cmdline dflags0 args = do -- XXX Legacy support code -- We used to accept things like -- optdep-f -optdepdepend -- optdep-f -optdep depend -- optdep -f -optdepdepend -- optdep -f -optdep depend -- but the spaces trip up proper argument handling. So get rid of them. let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs f (x : xs) = x : f xs f xs = xs args' = f args let ((leftover, errs, warns), dflags1) = runCmdLine (processArgs activeFlags args') dflags0 when (not (null errs)) $ liftIO $ throwGhcExceptionIO $ errorsToGhcException errs -- check for disabled flags in safe haskell let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1 dflags3 = updateWays dflags2 theWays = ways dflags3 unless (allowed_combination theWays) $ liftIO $ throwGhcExceptionIO (CmdLineError ("combination not supported: " ++ intercalate "/" (map wayDesc theWays))) whenGeneratingDynamicToo dflags3 $ unless (isJust (outputFile dflags3) == isJust (dynOutputFile dflags3)) $ liftIO $ throwGhcExceptionIO $ CmdLineError "With -dynamic-too, must give -dyno iff giving -o" let (dflags4, consistency_warnings) = makeDynFlagsConsistent dflags3 dflags5 <- case dllSplitFile dflags4 of Nothing -> return (dflags4 { dllSplit = Nothing }) Just f -> case dllSplit dflags4 of Just _ -> -- If dllSplit is out of date then it would have -- been set to Nothing. As it's a Just, it must be -- up-to-date. return dflags4 Nothing -> do xs <- liftIO $ readFile f let ss = map (Set.fromList . words) (lines xs) return $ dflags4 { dllSplit = Just ss } liftIO $ setUnsafeGlobalDynFlags dflags5 return (dflags5, leftover, consistency_warnings ++ sh_warns ++ warns) updateWays :: DynFlags -> DynFlags updateWays dflags = let theWays = sort $ nub $ ways dflags f = if WayDyn `elem` theWays then unSetGeneralFlag' else setGeneralFlag' in f Opt_Static $ dflags { ways = theWays, buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays), rtsBuildTag = mkBuildTag theWays } -- | Check (and potentially disable) any extensions that aren't allowed -- in safe mode. -- -- The bool is to indicate if we are parsing command line flags (false means -- file pragma). This allows us to generate better warnings. safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String]) safeFlagCheck _ dflags | not (safeLanguageOn dflags || safeInferOn dflags) = (dflags, []) -- safe or safe-infer ON safeFlagCheck cmdl dflags = case safeLanguageOn dflags of True -> (dflags', warns) -- throw error if -fpackage-trust by itself with no safe haskell flag False | not cmdl && packageTrustOn dflags -> (gopt_unset dflags' Opt_PackageTrust, [L (pkgTrustOnLoc dflags') $ "-fpackage-trust ignored;" ++ " must be specified with a Safe Haskell flag"] ) False | null warns && safeInfOk -> (dflags', []) | otherwise -> (dflags' { safeHaskell = Sf_None }, []) -- Have we inferred Unsafe? -- See Note [HscMain . Safe Haskell Inference] where -- TODO: Can we do better than this for inference? safeInfOk = not $ xopt Opt_OverlappingInstances dflags (dflags', warns) = foldl check_method (dflags, []) unsafeFlags check_method (df, warns) (str,loc,test,fix) | test df = (apFix fix df, warns ++ safeFailure (loc dflags) str) | otherwise = (df, warns) apFix f = if safeInferOn dflags then id else f safeFailure loc str = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring " ++ str] {- ********************************************************************** %* * DynFlags specifications %* * %********************************************************************* -} -- | All dynamic flags option strings. These are the user facing strings for -- enabling and disabling options. allFlags :: [String] allFlags = map ('-':) $ [ flagName flag | flag <- dynamic_flags ++ package_flags, ok (flagOptKind flag) ] ++ map ("fno-"++) fflags ++ map ("f"++) fflags ++ map ("X"++) supportedExtensions where ok (PrefixPred _ _) = False ok _ = True fflags = fflags0 ++ fflags1 ++ fflags2 fflags0 = [ name | (name, _, _) <- fFlags ] fflags1 = [ name | (name, _, _) <- fWarningFlags ] fflags2 = [ name | (name, _, _) <- fLangFlags ] {- - Below we export user facing symbols for GHC dynamic flags for use with the - GHC API. -} -- All dynamic flags present in GHC. flagsAll :: [Flag (CmdLineP DynFlags)] flagsAll = package_flags ++ dynamic_flags -- All dynamic flags, minus package flags, present in GHC. flagsDynamic :: [Flag (CmdLineP DynFlags)] flagsDynamic = dynamic_flags -- ALl package flags present in GHC. flagsPackage :: [Flag (CmdLineP DynFlags)] flagsPackage = package_flags --------------- The main flags themselves ------------------ dynamic_flags :: [Flag (CmdLineP DynFlags)] dynamic_flags = [ Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect")) , Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp)) , Flag "F" (NoArg (setGeneralFlag Opt_Pp)) , Flag "#include" (HasArg (\s -> do addCmdlineHCInclude s addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect")) , Flag "v" (OptIntSuffix setVerbosity) , Flag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n}))) ------- ways -------------------------------------------------------- , Flag "prof" (NoArg (addWay WayProf)) , Flag "eventlog" (NoArg (addWay WayEventLog)) , Flag "parallel" (NoArg (addWay WayPar)) , Flag "gransim" (NoArg (addWay WayGran)) , Flag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead")) , Flag "debug" (NoArg (addWay WayDebug)) , Flag "ndp" (NoArg (addWay WayNDP)) , Flag "threaded" (NoArg (addWay WayThreaded)) , Flag "ticky" (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug)) -- -ticky enables ticky-ticky code generation, and also implies -debug which -- is required to get the RTS ticky support. ----- Linker -------------------------------------------------------- , Flag "static" (NoArg removeWayDyn) , Flag "dynamic" (NoArg (addWay WayDyn)) -- ignored for compat w/ gcc: , Flag "rdynamic" (NoArg (return ())) , Flag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths)) ------- Specific phases -------------------------------------------- -- need to appear before -pgmL to be parsed as LLVM flags. , Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])}))) , Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])}))) , Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f}))) , Flag "pgmP" (hasArg setPgmP) , Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f}))) , Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])}))) , Flag "pgmm" (HasArg (\_ -> addWarn "The -pgmm flag does nothing; it will be removed in a future GHC release")) , Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])}))) , Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])}))) , Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])}))) , Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])}))) , Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f}))) , Flag "pgmlibtool" (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f}))) -- need to appear before -optl/-opta to be parsed as LLVM flags. , Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s}))) , Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s}))) , Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s}))) , Flag "optP" (hasArg addOptP) , Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s}))) , Flag "optc" (hasArg addOptc) , Flag "optm" (HasArg (\_ -> addWarn "The -optm flag does nothing; it will be removed in a future GHC release")) , Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s}))) , Flag "optl" (hasArg addOptl) , Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s}))) , Flag "split-objs" (NoArg (if can_split then setGeneralFlag Opt_SplitObjs else addWarn "ignoring -fsplit-objs")) -------- ghc -M ----------------------------------------------------- , Flag "dep-suffix" (hasArg addDepSuffix) , Flag "optdep-s" (hasArgDF addDepSuffix "Use -dep-suffix instead") , Flag "dep-makefile" (hasArg setDepMakefile) , Flag "optdep-f" (hasArgDF setDepMakefile "Use -dep-makefile instead") , Flag "optdep-w" (NoArg (deprecate "doesn't do anything")) , Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True)) , Flag "optdep--include-prelude" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead") , Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead") , Flag "exclude-module" (hasArg addDepExcludeMod) , Flag "optdep--exclude-module" (hasArgDF addDepExcludeMod "Use -exclude-module instead") , Flag "optdep-x" (hasArgDF addDepExcludeMod "Use -exclude-module instead") -------- Linking ---------------------------------------------------- , Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink })) , Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib })) , Flag "staticlib" (noArg (\d -> d{ ghcLink=LinkStaticLib })) , Flag "dynload" (hasArg parseDynLibLoaderMode) , Flag "dylib-install-name" (hasArg setDylibInstallName) -- -dll-split is an internal flag, used only during the GHC build , Flag "dll-split" (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing })) ------- Libraries --------------------------------------------------- , Flag "L" (Prefix addLibraryPath) , Flag "l" (hasArg (addLdInputs . Option . ("-l" ++))) ------- Frameworks -------------------------------------------------- -- -framework-path should really be -F ... , Flag "framework-path" (HasArg addFrameworkPath) , Flag "framework" (hasArg addCmdlineFramework) ------- Output Redirection ------------------------------------------ , Flag "odir" (hasArg setObjectDir) , Flag "o" (sepArg (setOutputFile . Just)) , Flag "dyno" (sepArg (setDynOutputFile . Just)) , Flag "ohi" (hasArg (setOutputHi . Just )) , Flag "osuf" (hasArg setObjectSuf) , Flag "dynosuf" (hasArg setDynObjectSuf) , Flag "hcsuf" (hasArg setHcSuf) , Flag "hisuf" (hasArg setHiSuf) , Flag "dynhisuf" (hasArg setDynHiSuf) , Flag "hidir" (hasArg setHiDir) , Flag "tmpdir" (hasArg setTmpDir) , Flag "stubdir" (hasArg setStubDir) , Flag "dumpdir" (hasArg setDumpDir) , Flag "outputdir" (hasArg setOutputDir) , Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just)) , Flag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo)) ------- Keeping temporary files ------------------------------------- -- These can be singular (think ghc -c) or plural (think ghc --make) , Flag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , Flag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , Flag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles)) , Flag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles)) , Flag "keep-raw-s-file" (NoArg (addWarn "The -keep-raw-s-file flag does nothing; it will be removed in a future GHC release")) , Flag "keep-raw-s-files" (NoArg (addWarn "The -keep-raw-s-files flag does nothing; it will be removed in a future GHC release")) , Flag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm setGeneralFlag Opt_KeepLlvmFiles)) , Flag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm setGeneralFlag Opt_KeepLlvmFiles)) -- This only makes sense as plural , Flag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles)) ------- Miscellaneous ---------------------------------------------- , Flag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages)) , Flag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain)) , Flag "with-rtsopts" (HasArg setRtsOpts) , Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll)) , Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll)) , Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly)) , Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone)) , Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone)) , Flag "main-is" (SepArg setMainIs) , Flag "haddock" (NoArg (setGeneralFlag Opt_Haddock)) , Flag "haddock-opts" (hasArg addHaddockOpts) , Flag "hpcdir" (SepArg setOptHpcDir) , Flag "ghci-script" (hasArg addGhciScript) , Flag "interactive-print" (hasArg setInteractivePrint) , Flag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd)) , Flag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE)) , Flag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk)) ------- recompilation checker -------------------------------------- , Flag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp deprecate "Use -fno-force-recomp instead")) , Flag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp deprecate "Use -fforce-recomp instead")) ------ HsCpp opts --------------------------------------------------- , Flag "D" (AnySuffix (upd . addOptP)) , Flag "U" (AnySuffix (upd . addOptP)) ------- Include/Import Paths ---------------------------------------- , Flag "I" (Prefix addIncludePath) , Flag "i" (OptPrefix addImportPath) ------ Output style options ----------------------------------------- , Flag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n })) , Flag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n })) , Flag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n })) -- Suppress all that is suppressable in core dumps. -- Except for uniques, as some simplifier phases introduce new varibles that -- have otherwise identical names. , Flag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions setGeneralFlag Opt_SuppressVarKinds setGeneralFlag Opt_SuppressModulePrefixes setGeneralFlag Opt_SuppressTypeApplications setGeneralFlag Opt_SuppressIdInfo setGeneralFlag Opt_SuppressTypeSignatures) ------ Debugging ---------------------------------------------------- , Flag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats)) , Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm) , Flag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw) , Flag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg) , Flag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe) , Flag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc) , Flag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink) , Flag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp) , Flag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap) , Flag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split) , Flag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info) , Flag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps) , Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats) , Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm) , Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native) , Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness) , Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc) , Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts) , Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages) , Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats) , Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded) , Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm setDumpFlag' Opt_D_dump_llvm)) , Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv) , Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds) , Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign) , Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings) , Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings) , Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites) , Flag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace) , Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal) , Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed) , Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn) , Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline) , Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl) , Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations) , Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases) , Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec) , Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep) , Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg) , Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal) , Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc) , Flag "ddump-types" (setDumpFlag Opt_D_dump_types) , Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules) , Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse) , Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper) , Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace) , Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace) , Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace) , Flag "ddump-tc-trace" (setDumpFlag Opt_D_dump_tc_trace) , Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace) , Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices) , Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats) , Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm) , Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats) , Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs) , Flag "dsource-stats" (setDumpFlag Opt_D_source_stats) , Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2) setVerboseCore2Core)) , Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg) , Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi) , Flag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports)) , Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect) , Flag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat , Flag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked) , Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles) , Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning) , Flag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile)) , Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs) , Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti) , Flag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting)) , Flag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting)) , Flag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting)) , Flag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting)) , Flag "dshow-passes" (NoArg (do forceRecompile setVerbosity $ Just 2)) , Flag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats)) , Flag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag ------ Machine dependant (-m<blah>) stuff --------------------------- , Flag "monly-2-regs" (NoArg (addWarn "The -monly-2-regs flag does nothing; it will be removed in a future GHC release")) , Flag "monly-3-regs" (NoArg (addWarn "The -monly-3-regs flag does nothing; it will be removed in a future GHC release")) , Flag "monly-4-regs" (NoArg (addWarn "The -monly-4-regs flag does nothing; it will be removed in a future GHC release")) , Flag "msse" (versionSuffix (\maj min d -> d{ sseVersion = Just (maj, min) })) , Flag "mavx" (noArg (\d -> d{ avx = True })) , Flag "mavx2" (noArg (\d -> d{ avx2 = True })) , Flag "mavx512cd" (noArg (\d -> d{ avx512cd = True })) , Flag "mavx512er" (noArg (\d -> d{ avx512er = True })) , Flag "mavx512f" (noArg (\d -> d{ avx512f = True })) , Flag "mavx512pf" (noArg (\d -> d{ avx512pf = True })) ------ Warning opts ------------------------------------------------- , Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts)) , Flag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError)) , Flag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError)) , Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts)) , Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty}) deprecate "Use -w instead")) , Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty}))) ------ Plugin flags ------------------------------------------------ , Flag "fplugin-opt" (hasArg addPluginModuleNameOption) , Flag "fplugin" (hasArg addPluginModuleName) ------ Optimisation flags ------------------------------------------ , Flag "O" (noArgM (setOptLevel 1)) , Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead" setOptLevel 0 dflags)) , Flag "Odph" (noArgM setDPHOpt) , Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1))) -- If the number is missing, use 1 , Flag "fmax-relevant-binds" (intSuffix (\n d -> d{ maxRelevantBinds = Just n })) , Flag "fno-max-relevant-binds" (noArg (\d -> d{ maxRelevantBinds = Nothing })) , Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n })) , Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n })) , Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n })) , Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n })) , Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing })) , Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n })) , Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing })) , Flag "fspec-constr-recursive" (intSuffix (\n d -> d{ specConstrRecursive = n })) , Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n })) , Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing })) , Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s })) , Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n })) , Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d })) , Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n })) , Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing })) , Flag "fhistory-size" (intSuffix (\n d -> d{ historySize = n })) , Flag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n})) , Flag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n})) , Flag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n})) , Flag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n})) , Flag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n})) , Flag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n})) , Flag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n})) ------ Profiling ---------------------------------------------------- -- OLD profiling flags , Flag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } )) , Flag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } )) , Flag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } )) , Flag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) , Flag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs)) , Flag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs)) -- NEW profiling flags , Flag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } )) , Flag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } )) , Flag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } )) , Flag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } )) , Flag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) ------ Compiler flags ----------------------------------------------- , Flag "fasm" (NoArg (setObjTarget HscAsm)) , Flag "fvia-c" (NoArg (addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release")) , Flag "fvia-C" (NoArg (addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release")) , Flag "fllvm" (NoArg (setObjTarget HscLlvm)) , Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink } setTarget HscNothing)) , Flag "fbyte-code" (NoArg (setTarget HscInterpreted)) , Flag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget)) , Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead")) , Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead")) ------ Safe Haskell flags ------------------------------------------- , Flag "fpackage-trust" (NoArg setPackageTrust) , Flag "fno-safe-infer" (NoArg (setSafeHaskell Sf_None)) , Flag "fPIC" (NoArg (setGeneralFlag Opt_PIC)) , Flag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC)) ] ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags ++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags ++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags ++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags ++ map (mkFlag turnOn "X" setLanguage) languageFlags ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags ++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) , Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ] package_flags :: [Flag (CmdLineP DynFlags)] package_flags = [ ------- Packages ---------------------------------------------------- Flag "package-db" (HasArg (addPkgConfRef . PkgConfFile)) , Flag "clear-package-db" (NoArg clearPkgConf) , Flag "no-global-package-db" (NoArg removeGlobalPkgConf) , Flag "no-user-package-db" (NoArg removeUserPkgConf) , Flag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf)) , Flag "user-package-db" (NoArg (addPkgConfRef UserPkgConf)) -- backwards compat with GHC<=7.4 : , Flag "package-conf" (HasArg $ \path -> do addPkgConfRef (PkgConfFile path) deprecate "Use -package-db instead") , Flag "no-user-package-conf" (NoArg $ do removeUserPkgConf deprecate "Use -no-user-package-db instead") , Flag "package-name" (hasArg setPackageName) , Flag "package-id" (HasArg exposePackageId) , Flag "package" (HasArg exposePackage) , Flag "hide-package" (HasArg hidePackage) , Flag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages)) , Flag "ignore-package" (HasArg ignorePackage) , Flag "syslib" (HasArg (\s -> do exposePackage s deprecate "Use -package instead")) , Flag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages)) , Flag "trust" (HasArg trustPackage) , Flag "distrust" (HasArg distrustPackage) ] type TurnOnFlag = Bool -- True <=> we are turning the flag on -- False <=> we are turning the flag off turnOn :: TurnOnFlag; turnOn = True turnOff :: TurnOnFlag; turnOff = False type FlagSpec flag = ( String -- Flag in string form , flag -- Flag in internal form , TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found -- Typically, emit a warning or error mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on -> String -- ^ The flag prefix -> (flag -> DynP ()) -- ^ What to do when the flag is found -> FlagSpec flag -- ^ Specification of this particular flag -> Flag (CmdLineP DynFlags) mkFlag turn_on flagPrefix f (name, flag, extra_action) = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) deprecatedForExtension :: String -> TurnOnFlag -> DynP () deprecatedForExtension lang turn_on = deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead") where flag | turn_on = lang | otherwise = "No"++lang useInstead :: String -> TurnOnFlag -> DynP () useInstead flag turn_on = deprecate ("Use -f" ++ no ++ flag ++ " instead") where no = if turn_on then "" else "no-" nop :: TurnOnFlag -> DynP () nop _ = return () -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fWarningFlags :: [FlagSpec WarningFlag] fWarningFlags = [ ( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ), ( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ), ( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ), ( "warn-overflowed-literals", Opt_WarnOverflowedLiterals, nop ), ( "warn-empty-enumerations", Opt_WarnEmptyEnumerations, nop ), ( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ), ( "warn-duplicate-constraints", Opt_WarnDuplicateConstraints, nop ), ( "warn-hi-shadowing", Opt_WarnHiShadows, nop ), ( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ), ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ), ( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ), ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ), ( "warn-missing-fields", Opt_WarnMissingFields, nop ), ( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ), ( "warn-missing-methods", Opt_WarnMissingMethods, nop ), ( "warn-missing-signatures", Opt_WarnMissingSigs, nop ), ( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ), ( "warn-name-shadowing", Opt_WarnNameShadowing, nop ), ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ), ( "warn-type-defaults", Opt_WarnTypeDefaults, nop ), ( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ), ( "warn-unused-binds", Opt_WarnUnusedBinds, nop ), ( "warn-unused-imports", Opt_WarnUnusedImports, nop ), ( "warn-unused-matches", Opt_WarnUnusedMatches, nop ), ( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ), ( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ), ( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ), ( "warn-amp", Opt_WarnAMP, nop ), ( "warn-orphans", Opt_WarnOrphans, nop ), ( "warn-identities", Opt_WarnIdentities, nop ), ( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ), ( "warn-tabs", Opt_WarnTabs, nop ), ( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ), ( "warn-lazy-unlifted-bindings", Opt_WarnLazyUnliftedBindings, nop ), ( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ), ( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ), ( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ), ( "warn-unsafe", Opt_WarnUnsafe, setWarnUnsafe ), ( "warn-safe", Opt_WarnSafe, setWarnSafe ), ( "warn-pointless-pragmas", Opt_WarnPointlessPragmas, nop ), ( "warn-unsupported-calling-conventions", Opt_WarnUnsupportedCallingConventions, nop ), ( "warn-inline-rule-shadowing", Opt_WarnInlineRuleShadowing, nop ), ( "warn-unsupported-llvm-version", Opt_WarnUnsupportedLlvmVersion, nop ) ] -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@ negatableFlags :: [FlagSpec GeneralFlag] negatableFlags = [ ( "ignore-dot-ghci", Opt_IgnoreDotGhci, nop ) ] -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@ dFlags :: [FlagSpec GeneralFlag] dFlags = [ ( "suppress-coercions", Opt_SuppressCoercions, nop), ( "suppress-var-kinds", Opt_SuppressVarKinds, nop), ( "suppress-module-prefixes", Opt_SuppressModulePrefixes, nop), ( "suppress-type-applications", Opt_SuppressTypeApplications, nop), ( "suppress-idinfo", Opt_SuppressIdInfo, nop), ( "suppress-type-signatures", Opt_SuppressTypeSignatures, nop), ( "suppress-uniques", Opt_SuppressUniques, nop), ( "ppr-case-as-let", Opt_PprCaseAsLet, nop)] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fFlags :: [FlagSpec GeneralFlag] fFlags = [ ( "error-spans", Opt_ErrorSpans, nop ), ( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ), ( "strictness", Opt_Strictness, nop ), ( "late-dmd-anal", Opt_LateDmdAnal, nop ), ( "specialise", Opt_Specialise, nop ), ( "float-in", Opt_FloatIn, nop ), ( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ), ( "full-laziness", Opt_FullLaziness, nop ), ( "liberate-case", Opt_LiberateCase, nop ), ( "spec-constr", Opt_SpecConstr, nop ), ( "cse", Opt_CSE, nop ), ( "pedantic-bottoms", Opt_PedanticBottoms, nop ), ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ), ( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ), ( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ), ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ), ( "ignore-asserts", Opt_IgnoreAsserts, nop ), ( "do-eta-reduction", Opt_DoEtaReduction, nop ), ( "case-merge", Opt_CaseMerge, nop ), ( "unbox-strict-fields", Opt_UnboxStrictFields, nop ), ( "unbox-small-strict-fields", Opt_UnboxSmallStrictFields, nop ), ( "dicts-cheap", Opt_DictsCheap, nop ), ( "excess-precision", Opt_ExcessPrecision, nop ), ( "eager-blackholing", Opt_EagerBlackHoling, nop ), ( "print-bind-result", Opt_PrintBindResult, nop ), ( "force-recomp", Opt_ForceRecomp, nop ), ( "hpc-no-auto", Opt_Hpc_No_Auto, nop ), ( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ), ( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ), ( "break-on-exception", Opt_BreakOnException, nop ), ( "break-on-error", Opt_BreakOnError, nop ), ( "print-evld-with-show", Opt_PrintEvldWithShow, nop ), ( "print-bind-contents", Opt_PrintBindContents, nop ), ( "run-cps", Opt_RunCPS, nop ), ( "run-cpsz", Opt_RunCPSZ, nop ), ( "vectorise", Opt_Vectorise, nop ), ( "vectorisation-avoidance", Opt_VectorisationAvoidance, nop ), ( "regs-graph", Opt_RegsGraph, nop ), ( "regs-iterative", Opt_RegsIterative, nop ), ( "llvm-tbaa", Opt_LlvmTBAA, nop), -- hidden flag ( "llvm-pass-vectors-in-regs", Opt_LlvmPassVectorsInRegisters, nop), -- hidden flag ( "irrefutable-tuples", Opt_IrrefutableTuples, nop ), ( "cmm-sink", Opt_CmmSink, nop ), ( "cmm-elim-common-blocks", Opt_CmmElimCommonBlocks, nop ), ( "omit-yields", Opt_OmitYields, nop ), ( "simple-list-literals", Opt_SimpleListLiterals, nop ), ( "fun-to-thunk", Opt_FunToThunk, nop ), ( "gen-manifest", Opt_GenManifest, nop ), ( "embed-manifest", Opt_EmbedManifest, nop ), ( "ext-core", Opt_EmitExternalCore, nop ), ( "shared-implib", Opt_SharedImplib, nop ), ( "ghci-sandbox", Opt_GhciSandbox, nop ), ( "ghci-history", Opt_GhciHistory, nop ), ( "helpful-errors", Opt_HelpfulErrors, nop ), ( "defer-type-errors", Opt_DeferTypeErrors, nop ), ( "building-cabal-package", Opt_BuildingCabalPackage, nop ), ( "implicit-import-qualified", Opt_ImplicitImportQualified, nop ), ( "prof-count-entries", Opt_ProfCountEntries, nop ), ( "prof-cafs", Opt_AutoSccsOnIndividualCafs, nop ), ( "hpc", Opt_Hpc, nop ), ( "pre-inlining", Opt_SimplPreInlining, nop ), ( "flat-cache", Opt_FlatCache, nop ), ( "use-rpaths", Opt_RPath, nop ), ( "kill-absence", Opt_KillAbsence, nop), ( "kill-one-shot", Opt_KillOneShot, nop), ( "dicts-strict", Opt_DictsStrict, nop ), ( "dmd-tx-dict-sel", Opt_DmdTxDictSel, nop ), ( "loopification", Opt_Loopification, nop ) ] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fLangFlags :: [FlagSpec ExtensionFlag] fLangFlags = [ ( "th", Opt_TemplateHaskell, \on -> deprecatedForExtension "TemplateHaskell" on >> checkTemplateHaskellOk on ), ( "fi", Opt_ForeignFunctionInterface, deprecatedForExtension "ForeignFunctionInterface" ), ( "ffi", Opt_ForeignFunctionInterface, deprecatedForExtension "ForeignFunctionInterface" ), ( "arrows", Opt_Arrows, deprecatedForExtension "Arrows" ), ( "implicit-prelude", Opt_ImplicitPrelude, deprecatedForExtension "ImplicitPrelude" ), ( "bang-patterns", Opt_BangPatterns, deprecatedForExtension "BangPatterns" ), ( "monomorphism-restriction", Opt_MonomorphismRestriction, deprecatedForExtension "MonomorphismRestriction" ), ( "mono-pat-binds", Opt_MonoPatBinds, deprecatedForExtension "MonoPatBinds" ), ( "extended-default-rules", Opt_ExtendedDefaultRules, deprecatedForExtension "ExtendedDefaultRules" ), ( "implicit-params", Opt_ImplicitParams, deprecatedForExtension "ImplicitParams" ), ( "scoped-type-variables", Opt_ScopedTypeVariables, deprecatedForExtension "ScopedTypeVariables" ), ( "parr", Opt_ParallelArrays, deprecatedForExtension "ParallelArrays" ), ( "PArr", Opt_ParallelArrays, deprecatedForExtension "ParallelArrays" ), ( "allow-overlapping-instances", Opt_OverlappingInstances, deprecatedForExtension "OverlappingInstances" ), ( "allow-undecidable-instances", Opt_UndecidableInstances, deprecatedForExtension "UndecidableInstances" ), ( "allow-incoherent-instances", Opt_IncoherentInstances, deprecatedForExtension "IncoherentInstances" ) ] supportedLanguages :: [String] supportedLanguages = [ name | (name, _, _) <- languageFlags ] supportedLanguageOverlays :: [String] supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ] supportedExtensions :: [String] supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ] supportedLanguagesAndExtensions :: [String] supportedLanguagesAndExtensions = supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions -- | These -X<blah> flags cannot be reversed with -XNo<blah> languageFlags :: [FlagSpec Language] languageFlags = [ ( "Haskell98", Haskell98, nop ), ( "Haskell2010", Haskell2010, nop ) ] -- | These -X<blah> flags cannot be reversed with -XNo<blah> -- They are used to place hard requirements on what GHC Haskell language -- features can be used. safeHaskellFlags :: [FlagSpec SafeHaskellMode] safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe] where mkF flag = (show flag, flag, nop) -- | These -X<blah> flags can all be reversed with -XNo<blah> xFlags :: [FlagSpec ExtensionFlag] xFlags = [ ( "CPP", Opt_Cpp, nop ), ( "PostfixOperators", Opt_PostfixOperators, nop ), ( "TupleSections", Opt_TupleSections, nop ), ( "PatternGuards", Opt_PatternGuards, nop ), ( "UnicodeSyntax", Opt_UnicodeSyntax, nop ), ( "MagicHash", Opt_MagicHash, nop ), ( "ExistentialQuantification", Opt_ExistentialQuantification, nop ), ( "KindSignatures", Opt_KindSignatures, nop ), ( "RoleAnnotations", Opt_RoleAnnotations, nop ), ( "EmptyDataDecls", Opt_EmptyDataDecls, nop ), ( "ParallelListComp", Opt_ParallelListComp, nop ), ( "TransformListComp", Opt_TransformListComp, nop ), ( "MonadComprehensions", Opt_MonadComprehensions, nop), ( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ), ( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ), ( "InterruptibleFFI", Opt_InterruptibleFFI, nop ), ( "CApiFFI", Opt_CApiFFI, nop ), ( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ), ( "JavaScriptFFI", Opt_JavaScriptFFI, nop ), ( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ), ( "PolymorphicComponents", Opt_RankNTypes, nop), ( "Rank2Types", Opt_RankNTypes, nop), ( "RankNTypes", Opt_RankNTypes, nop ), ( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop), ( "TypeOperators", Opt_TypeOperators, nop ), ( "ExplicitNamespaces", Opt_ExplicitNamespaces, nop ), ( "RecursiveDo", Opt_RecursiveDo, nop ), -- Enables 'mdo' and 'rec' ( "DoRec", Opt_RecursiveDo, deprecatedForExtension "RecursiveDo" ), ( "Arrows", Opt_Arrows, nop ), ( "ParallelArrays", Opt_ParallelArrays, nop ), ( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ), ( "QuasiQuotes", Opt_QuasiQuotes, nop ), ( "ImplicitPrelude", Opt_ImplicitPrelude, nop ), ( "RecordWildCards", Opt_RecordWildCards, nop ), ( "NamedFieldPuns", Opt_RecordPuns, nop ), ( "RecordPuns", Opt_RecordPuns, deprecatedForExtension "NamedFieldPuns" ), ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ), ( "OverloadedStrings", Opt_OverloadedStrings, nop ), ( "NumDecimals", Opt_NumDecimals, nop), ( "OverloadedLists", Opt_OverloadedLists, nop), ( "GADTs", Opt_GADTs, nop ), ( "GADTSyntax", Opt_GADTSyntax, nop ), ( "ViewPatterns", Opt_ViewPatterns, nop ), ( "TypeFamilies", Opt_TypeFamilies, nop ), ( "BangPatterns", Opt_BangPatterns, nop ), ( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ), ( "NPlusKPatterns", Opt_NPlusKPatterns, nop ), ( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ), ( "RebindableSyntax", Opt_RebindableSyntax, nop ), ( "ConstraintKinds", Opt_ConstraintKinds, nop ), ( "PolyKinds", Opt_PolyKinds, nop ), ( "DataKinds", Opt_DataKinds, nop ), ( "InstanceSigs", Opt_InstanceSigs, nop ), ( "MonoPatBinds", Opt_MonoPatBinds, \ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ), ( "ExplicitForAll", Opt_ExplicitForAll, nop ), ( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ), ( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ), ( "DatatypeContexts", Opt_DatatypeContexts, \ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ), ( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ), ( "RelaxedLayout", Opt_RelaxedLayout, nop ), ( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ), ( "LambdaCase", Opt_LambdaCase, nop ), ( "MultiWayIf", Opt_MultiWayIf, nop ), ( "MonoLocalBinds", Opt_MonoLocalBinds, nop ), ( "RelaxedPolyRec", Opt_RelaxedPolyRec, \ turn_on -> unless turn_on $ deprecate "You can't turn off RelaxedPolyRec any more" ), ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ), ( "ImplicitParams", Opt_ImplicitParams, nop ), ( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ), ( "AllowAmbiguousTypes", Opt_AllowAmbiguousTypes, nop), ( "PatternSignatures", Opt_ScopedTypeVariables, deprecatedForExtension "ScopedTypeVariables" ), ( "UnboxedTuples", Opt_UnboxedTuples, nop ), ( "StandaloneDeriving", Opt_StandaloneDeriving, nop ), ( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ), ( "AutoDeriveTypeable", Opt_AutoDeriveTypeable, nop ), ( "DeriveFunctor", Opt_DeriveFunctor, nop ), ( "DeriveTraversable", Opt_DeriveTraversable, nop ), ( "DeriveFoldable", Opt_DeriveFoldable, nop ), ( "DeriveGeneric", Opt_DeriveGeneric, nop ), ( "DefaultSignatures", Opt_DefaultSignatures, nop ), ( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ), ( "FlexibleContexts", Opt_FlexibleContexts, nop ), ( "FlexibleInstances", Opt_FlexibleInstances, nop ), ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ), ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ), ( "NullaryTypeClasses", Opt_NullaryTypeClasses, nop ), ( "FunctionalDependencies", Opt_FunctionalDependencies, nop ), ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ), ( "OverlappingInstances", Opt_OverlappingInstances, nop ), ( "UndecidableInstances", Opt_UndecidableInstances, nop ), ( "IncoherentInstances", Opt_IncoherentInstances, nop ), ( "PackageImports", Opt_PackageImports, nop ), ( "TypeHoles", Opt_TypeHoles, nop ), ( "NegativeLiterals", Opt_NegativeLiterals, nop ), ( "EmptyCase", Opt_EmptyCase, nop ) ] defaultFlags :: Settings -> [GeneralFlag] defaultFlags settings = [ Opt_AutoLinkPackages, Opt_SharedImplib, Opt_OmitYields, Opt_GenManifest, Opt_EmbedManifest, Opt_PrintBindContents, Opt_GhciSandbox, Opt_GhciHistory, Opt_HelpfulErrors, Opt_ProfCountEntries, Opt_SimplPreInlining, Opt_FlatCache, Opt_RPath ] ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns] -- The default -O0 options ++ default_PIC platform ++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings) then wayGeneralFlags platform WayDyn else []) where platform = sTargetPlatform settings default_PIC :: Platform -> [GeneralFlag] default_PIC platform = case (platformOS platform, platformArch platform) of (OSDarwin, ArchX86_64) -> [Opt_PIC] _ -> [] impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)] impliedFlags = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll) , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll) , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll) , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll) , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances) , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses) , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off! , (Opt_GADTs, turnOn, Opt_GADTSyntax) , (Opt_GADTs, turnOn, Opt_MonoLocalBinds) , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds) , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures , (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds -- AutoDeriveTypeable is not very useful without DeriveDataTypeable , (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable) -- We turn this on so that we can export associated type -- type synonyms in subordinates (e.g. MyClass(type AssocType)) , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces) , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces) , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes) -- Record wild-cards implies field disambiguation -- Otherwise if you write (C {..}) you may well get -- stuff like " 'a' not in scope ", which is a bit silly -- if the compiler has just filled in field 'a' of constructor 'C' , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields) , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp) -- An implicit parameter constraint, `?x::Int`, is desugared into -- `IP "x" Int`, which requires a flexible context/instance. , (Opt_ImplicitParams, turnOn, Opt_FlexibleContexts) , (Opt_ImplicitParams, turnOn, Opt_FlexibleInstances) , (Opt_JavaScriptFFI, turnOn, Opt_InterruptibleFFI) ] optLevelFlags :: [([Int], GeneralFlag)] optLevelFlags = [ ([0], Opt_IgnoreInterfacePragmas) , ([0], Opt_OmitInterfacePragmas) , ([1,2], Opt_IgnoreAsserts) , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules] -- in PrelRules , ([1,2], Opt_DoEtaReduction) , ([1,2], Opt_CaseMerge) , ([1,2], Opt_Strictness) , ([1,2], Opt_CSE) , ([1,2], Opt_FullLaziness) , ([1,2], Opt_Specialise) , ([1,2], Opt_FloatIn) , ([1,2], Opt_UnboxSmallStrictFields) , ([2], Opt_LiberateCase) , ([2], Opt_SpecConstr) -- XXX disabled, see #7192 -- , ([2], Opt_RegsGraph) , ([0,1,2], Opt_LlvmTBAA) , ([1,2], Opt_CmmSink) , ([1,2], Opt_CmmElimCommonBlocks) , ([0,1,2], Opt_DmdTxDictSel) -- , ([2], Opt_StaticArgumentTransformation) -- Max writes: I think it's probably best not to enable SAT with -O2 for the -- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate -- several improvements to the heuristics, and I'm concerned that without -- those changes SAT will interfere with some attempts to write "high -- performance Haskell", as we saw in some posts on Haskell-Cafe earlier -- this year. In particular, the version in HEAD lacks the tail call -- criterion, so many things that look like reasonable loops will be -- turned into functions with extra (unneccesary) thunk creation. , ([0,1,2], Opt_DoLambdaEtaExpansion) -- This one is important for a tiresome reason: -- we want to make sure that the bindings for data -- constructors are eta-expanded. This is probably -- a good thing anyway, but it seems fragile. , ([0,1,2], Opt_VectorisationAvoidance) ] -- ----------------------------------------------------------------------------- -- Standard sets of warning options standardWarnings :: [WarningFlag] standardWarnings = [ Opt_WarnOverlappingPatterns, Opt_WarnWarningsDeprecations, Opt_WarnDeprecatedFlags, Opt_WarnAMP, Opt_WarnUnrecognisedPragmas, Opt_WarnPointlessPragmas, Opt_WarnDuplicateConstraints, Opt_WarnDuplicateExports, Opt_WarnOverflowedLiterals, Opt_WarnEmptyEnumerations, Opt_WarnMissingFields, Opt_WarnMissingMethods, Opt_WarnLazyUnliftedBindings, Opt_WarnWrongDoBind, Opt_WarnUnsupportedCallingConventions, Opt_WarnDodgyForeignImports, Opt_WarnInlineRuleShadowing, Opt_WarnAlternativeLayoutRuleTransitional, Opt_WarnUnsupportedLlvmVersion ] minusWOpts :: [WarningFlag] -- Things you get with -W minusWOpts = standardWarnings ++ [ Opt_WarnUnusedBinds, Opt_WarnUnusedMatches, Opt_WarnUnusedImports, Opt_WarnIncompletePatterns, Opt_WarnDodgyExports, Opt_WarnDodgyImports ] minusWallOpts :: [WarningFlag] -- Things you get with -Wall minusWallOpts = minusWOpts ++ [ Opt_WarnTypeDefaults, Opt_WarnNameShadowing, Opt_WarnMissingSigs, Opt_WarnHiShadows, Opt_WarnOrphans, Opt_WarnUnusedDoBind ] enableGlasgowExts :: DynP () enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls mapM_ setExtensionFlag glasgowExtsFlags disableGlasgowExts :: DynP () disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls mapM_ unSetExtensionFlag glasgowExtsFlags glasgowExtsFlags :: [ExtensionFlag] glasgowExtsFlags = [ Opt_ForeignFunctionInterface , Opt_UnliftedFFITypes , Opt_ImplicitParams , Opt_ScopedTypeVariables , Opt_UnboxedTuples , Opt_TypeSynonymInstances , Opt_StandaloneDeriving , Opt_DeriveDataTypeable , Opt_DeriveFunctor , Opt_DeriveFoldable , Opt_DeriveTraversable , Opt_DeriveGeneric , Opt_FlexibleContexts , Opt_FlexibleInstances , Opt_ConstrainedClassMethods , Opt_MultiParamTypeClasses , Opt_FunctionalDependencies , Opt_MagicHash , Opt_ExistentialQuantification , Opt_UnicodeSyntax , Opt_PostfixOperators , Opt_PatternGuards , Opt_LiberalTypeSynonyms , Opt_RankNTypes , Opt_TypeOperators , Opt_ExplicitNamespaces , Opt_RecursiveDo , Opt_ParallelListComp , Opt_EmptyDataDecls , Opt_KindSignatures , Opt_GeneralizedNewtypeDeriving ] #ifdef GHCI -- Consult the RTS to find whether GHC itself has been built profiled -- If so, you can't use Template Haskell foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt rtsIsProfiled :: Bool rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0 #endif setWarnSafe :: Bool -> DynP () setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l }) setWarnSafe False = return () setWarnUnsafe :: Bool -> DynP () setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l }) setWarnUnsafe False = return () setPackageTrust :: DynP () setPackageTrust = do setGeneralFlag Opt_PackageTrust l <- getCurLoc upd $ \d -> d { pkgTrustOnLoc = l } setGenDeriving :: TurnOnFlag -> DynP () setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l }) setGenDeriving False = return () checkTemplateHaskellOk :: TurnOnFlag -> DynP () #ifdef GHCI checkTemplateHaskellOk turn_on | turn_on && rtsIsProfiled = addErr "You can't use Template Haskell with a profiled compiler" | otherwise = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l }) #else -- In stage 1 we don't know that the RTS has rts_isProfiled, -- so we simply say "ok". It doesn't matter because TH isn't -- available in stage 1 anyway. checkTemplateHaskellOk _ = return () #endif {- ********************************************************************** %* * DynFlags constructors %* * %********************************************************************* -} type DynP = EwM (CmdLineP DynFlags) upd :: (DynFlags -> DynFlags) -> DynP () upd f = liftEwM (do dflags <- getCmdLineState putCmdLineState $! f dflags) updM :: (DynFlags -> DynP DynFlags) -> DynP () updM f = do dflags <- liftEwM getCmdLineState dflags' <- f dflags liftEwM $ putCmdLineState $! dflags' --------------- Constructor functions for OptKind ----------------- noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) noArg fn = NoArg (upd fn) noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) noArgM fn = NoArg (updM fn) noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags) noArgDF fn deprec = NoArg (upd fn >> deprecate deprec) hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) hasArg fn = HasArg (upd . fn) hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags) hasArgDF fn deprec = HasArg (\s -> do upd (fn s) deprecate deprec) sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) sepArg fn = SepArg (upd . fn) intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) intSuffix fn = IntSuffix (\n -> upd (fn n)) floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) floatSuffix fn = FloatSuffix (\n -> upd (fn n)) optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi)) versionSuffix :: (Int -> Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) versionSuffix fn = VersionSuffix (\maj min -> upd (fn maj min)) setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags) setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag) -------------------------- addWay :: Way -> DynP () addWay w = upd (addWay' w) addWay' :: Way -> DynFlags -> DynFlags addWay' w dflags0 = let platform = targetPlatform dflags0 dflags1 = dflags0 { ways = w : ways dflags0 } dflags2 = wayExtras platform w dflags1 dflags3 = foldr setGeneralFlag' dflags2 (wayGeneralFlags platform w) dflags4 = foldr unSetGeneralFlag' dflags3 (wayUnsetGeneralFlags platform w) in dflags4 removeWayDyn :: DynP () removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) }) -------------------------- setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP () setGeneralFlag f = upd (setGeneralFlag' f) unSetGeneralFlag f = upd (unSetGeneralFlag' f) setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags setGeneralFlag' f dflags = gopt_set dflags f unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags unSetGeneralFlag' f dflags = gopt_unset dflags f -------------------------- setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP () setWarningFlag f = upd (\dfs -> wopt_set dfs f) unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f) -------------------------- setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP () setExtensionFlag f = upd (setExtensionFlag' f) unSetExtensionFlag f = upd (unSetExtensionFlag' f) setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps where deps = [ if turn_on then setExtensionFlag' d else unSetExtensionFlag' d | (f', turn_on, d) <- impliedFlags, f' == f ] -- When you set f, set the ones it implies -- NB: use setExtensionFlag recursively, in case the implied flags -- implies further flags unSetExtensionFlag' f dflags = xopt_unset dflags f -- When you un-set f, however, we don't un-set the things it implies -- (except for -fno-glasgow-exts, which is treated specially) -------------------------- alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags alterSettings f dflags = dflags { settings = f (settings dflags) } -------------------------- setDumpFlag' :: DumpFlag -> DynP () setDumpFlag' dump_flag = do upd (\dfs -> dopt_set dfs dump_flag) when want_recomp forceRecompile where -- Certain dumpy-things are really interested in what's going -- on during recompilation checking, so in those cases we -- don't want to turn it off. want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace, Opt_D_dump_hi_diffs] forceRecompile :: DynP () -- Whenver we -ddump, force recompilation (by switching off the -- recompilation checker), else you don't see the dump! However, -- don't switch it off in --make mode, else *everything* gets -- recompiled which probably isn't what you want forceRecompile = do dfs <- liftEwM getCmdLineState when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp) where force_recomp dfs = isOneShot (ghcMode dfs) setVerboseCore2Core :: DynP () setVerboseCore2Core = do setDumpFlag' Opt_D_verbose_core2core upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing }) setDumpSimplPhases :: String -> DynP () setDumpSimplPhases s = do forceRecompile upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec }) where spec = case s of { ('=' : s') -> s'; _ -> s } setVerbosity :: Maybe Int -> DynP () setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 }) addCmdlineHCInclude :: String -> DynP () addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s}) data PkgConfRef = GlobalPkgConf | UserPkgConf | PkgConfFile FilePath addPkgConfRef :: PkgConfRef -> DynP () addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s } removeUserPkgConf :: DynP () removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s } where isNotUser UserPkgConf = False isNotUser _ = True removeGlobalPkgConf :: DynP () removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s } where isNotGlobal GlobalPkgConf = False isNotGlobal _ = True clearPkgConf :: DynP () clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] } exposePackage, exposePackageId, hidePackage, ignorePackage, trustPackage, distrustPackage :: String -> DynP () exposePackage p = upd (exposePackage' p) exposePackageId p = upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s }) hidePackage p = upd (\s -> s{ packageFlags = HidePackage p : packageFlags s }) ignorePackage p = upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s }) trustPackage p = exposePackage p >> -- both trust and distrust also expose a package upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s }) distrustPackage p = exposePackage p >> upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s }) exposePackage' :: String -> DynFlags -> DynFlags exposePackage' p dflags = dflags { packageFlags = ExposePackage p : packageFlags dflags } setPackageName :: String -> DynFlags -> DynFlags setPackageName p s = s{ thisPackage = stringToPackageId p } -- If we're linking a binary, then only targets that produce object -- code are allowed (requests for other target types are ignored). setTarget :: HscTarget -> DynP () setTarget l = setTargetWithPlatform (const l) setTargetWithPlatform :: (Platform -> HscTarget) -> DynP () setTargetWithPlatform f = upd set where set dfs = let l = f (targetPlatform dfs) in if ghcLink dfs /= LinkBinary || isObjectTarget l then dfs{ hscTarget = l } else dfs -- Changes the target only if we're compiling object code. This is -- used by -fasm and -fllvm, which switch from one to the other, but -- not from bytecode to object-code. The idea is that -fasm/-fllvm -- can be safely used in an OPTIONS_GHC pragma. setObjTarget :: HscTarget -> DynP () setObjTarget l = updM set where set dflags | isObjectTarget (hscTarget dflags) = return $ dflags { hscTarget = l } | otherwise = return dflags setOptLevel :: Int -> DynFlags -> DynP DynFlags setOptLevel n dflags | hscTarget dflags == HscInterpreted && n > 0 = do addWarn "-O conflicts with --interactive; -O ignored." return dflags | otherwise = return (updOptLevel n dflags) -- -Odph is equivalent to -- -- -O2 optimise as much as possible -- -fmax-simplifier-iterations20 this is necessary sometimes -- -fsimplifier-phases=3 we use an additional simplifier phase for fusion -- setDPHOpt :: DynFlags -> DynP DynFlags setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20 , simplPhases = 3 }) setMainIs :: String -> DynP () setMainIs arg | not (null main_fn) && isLower (head main_fn) -- The arg looked like "Foo.Bar.baz" = upd $ \d -> d{ mainFunIs = Just main_fn, mainModIs = mkModule mainPackageId (mkModuleName main_mod) } | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar" = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) } | otherwise -- The arg looked like "baz" = upd $ \d -> d{ mainFunIs = Just arg } where (main_mod, main_fn) = splitLongestPrefix arg (== '.') addLdInputs :: Option -> DynFlags -> DynFlags addLdInputs p dflags = dflags{ldInputs = ldInputs dflags ++ [p]} ----------------------------------------------------------------------------- -- Paths & Libraries addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP () -- -i on its own deletes the import paths addImportPath "" = upd (\s -> s{importPaths = []}) addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p}) addLibraryPath p = upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p}) addIncludePath p = upd (\s -> s{includePaths = includePaths s ++ splitPathList p}) addFrameworkPath p = upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p}) #ifndef mingw32_TARGET_OS split_marker :: Char split_marker = ':' -- not configurable (ToDo) #endif splitPathList :: String -> [String] splitPathList s = filter notNull (splitUp s) -- empty paths are ignored: there might be a trailing -- ':' in the initial list, for example. Empty paths can -- cause confusion when they are translated into -I options -- for passing to gcc. where #ifndef mingw32_TARGET_OS splitUp xs = split split_marker xs #else -- Windows: 'hybrid' support for DOS-style paths in directory lists. -- -- That is, if "foo:bar:baz" is used, this interpreted as -- consisting of three entries, 'foo', 'bar', 'baz'. -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar" -- -- Notice that no attempt is made to fully replace the 'standard' -- split marker ':' with the Windows / DOS one, ';'. The reason being -- that this will cause too much breakage for users & ':' will -- work fine even with DOS paths, if you're not insisting on being silly. -- So, use either. splitUp [] = [] splitUp (x:':':div:xs) | div `elem` dir_markers = ((x:':':div:p): splitUp rs) where (p,rs) = findNextPath xs -- we used to check for existence of the path here, but that -- required the IO monad to be threaded through the command-line -- parser which is quite inconvenient. The splitUp xs = cons p (splitUp rs) where (p,rs) = findNextPath xs cons "" xs = xs cons x xs = x:xs -- will be called either when we've consumed nought or the -- "<Drive>:/" part of a DOS path, so splitting is just a Q of -- finding the next split marker. findNextPath xs = case break (`elem` split_markers) xs of (p, _:ds) -> (p, ds) (p, xs) -> (p, xs) split_markers :: [Char] split_markers = [':', ';'] dir_markers :: [Char] dir_markers = ['/', '\\'] #endif -- ----------------------------------------------------------------------------- -- tmpDir, where we store temporary files. setTmpDir :: FilePath -> DynFlags -> DynFlags setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir }) -- we used to fix /cygdrive/c/.. on Windows, but this doesn't -- seem necessary now --SDM 7/2/2008 ----------------------------------------------------------------------------- -- RTS opts setRtsOpts :: String -> DynP () setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg} setRtsOptsEnabled :: RtsOptsEnabled -> DynP () setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg} ----------------------------------------------------------------------------- -- Hpc stuff setOptHpcDir :: String -> DynP () setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg} ----------------------------------------------------------------------------- -- Via-C compilation stuff -- There are some options that we need to pass to gcc when compiling -- Haskell code via C, but are only supported by recent versions of -- gcc. The configure script decides which of these options we need, -- and puts them in the "settings" file in $topdir. The advantage of -- having these in a separate file is that the file can be created at -- install-time depending on the available gcc version, and even -- re-generated later if gcc is upgraded. -- -- The options below are not dependent on the version of gcc, only the -- platform. picCCOpts :: DynFlags -> [String] picCCOpts dflags = case platformOS (targetPlatform dflags) of OSDarwin -- Apple prefers to do things the other way round. -- PIC is on by default. -- -mdynamic-no-pic: -- Turn off PIC code generation. -- -fno-common: -- Don't generate "common" symbols - these are unwanted -- in dynamic libraries. | gopt Opt_PIC dflags -> ["-fno-common", "-U __PIC__", "-D__PIC__"] | otherwise -> ["-mdynamic-no-pic"] OSMinGW32 -- no -fPIC for Windows | gopt Opt_PIC dflags -> ["-U __PIC__", "-D__PIC__"] | otherwise -> [] _ -- we need -fPIC for C files when we are compiling with -dynamic, -- otherwise things like stub.c files don't get compiled -- correctly. They need to reference data in the Haskell -- objects, but can't without -fPIC. See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode | gopt Opt_PIC dflags || not (gopt Opt_Static dflags) -> ["-fPIC", "-U __PIC__", "-D__PIC__"] | otherwise -> [] picPOpts :: DynFlags -> [String] picPOpts dflags | gopt Opt_PIC dflags = ["-U __PIC__", "-D__PIC__"] | otherwise = [] -- ----------------------------------------------------------------------------- -- Splitting can_split :: Bool can_split = cSupportsSplitObjs == "YES" -- ----------------------------------------------------------------------------- -- Compiler Info compilerInfo :: DynFlags -> [(String, String)] compilerInfo dflags = -- We always make "Project name" be first to keep parsing in -- other languages simple, i.e. when looking for other fields, -- you don't have to worry whether there is a leading '[' or not ("Project name", cProjectName) -- Next come the settings, so anything else can be overridden -- in the settings file (as "lookup" uses the first match for the -- key) : rawSettings dflags ++ [("Project version", cProjectVersion), ("Booter version", cBooterVersion), ("Stage", cStage), ("Build platform", cBuildPlatformString), ("Host platform", cHostPlatformString), ("Target platform", cTargetPlatformString), ("Have interpreter", cGhcWithInterpreter), ("Object splitting supported", cSupportsSplitObjs), ("Have native code generator", cGhcWithNativeCodeGen), ("Support SMP", cGhcWithSMP), ("Tables next to code", cGhcEnableTablesNextToCode), ("RTS ways", cGhcRTSWays), ("Support dynamic-too", "YES"), ("Support parallel --make", "YES"), ("Dynamic by default", if dYNAMIC_BY_DEFAULT dflags then "YES" else "NO"), ("GHC Dynamic", if cDYNAMIC_GHC_PROGRAMS then "YES" else "NO"), ("Leading underscore", cLeadingUnderscore), ("Debug on", show debugIsOn), ("LibDir", topDir dflags), ("Global Package DB", systemPackageConfig dflags) ] #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellWrappers.hs" bLOCK_SIZE_W :: DynFlags -> Int bLOCK_SIZE_W dflags = bLOCK_SIZE dflags `quot` wORD_SIZE dflags wORD_SIZE_IN_BITS :: DynFlags -> Int wORD_SIZE_IN_BITS dflags = wORD_SIZE dflags * 8 tAG_MASK :: DynFlags -> Int tAG_MASK dflags = (1 `shiftL` tAG_BITS dflags) - 1 mAX_PTR_TAG :: DynFlags -> Int mAX_PTR_TAG = tAG_MASK -- Might be worth caching these in targetPlatform? tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: DynFlags -> Integer tARGET_MIN_INT dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (minBound :: Int32) 8 -> toInteger (minBound :: Int64) w -> panic ("tARGET_MIN_INT: Unknown platformWordSize: " ++ show w) tARGET_MAX_INT dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (maxBound :: Int32) 8 -> toInteger (maxBound :: Int64) w -> panic ("tARGET_MAX_INT: Unknown platformWordSize: " ++ show w) tARGET_MAX_WORD dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (maxBound :: Word32) 8 -> toInteger (maxBound :: Word64) w -> panic ("tARGET_MAX_WORD: Unknown platformWordSize: " ++ show w) -- Whenever makeDynFlagsConsistent does anything, it starts over, to -- ensure that a later change doesn't invalidate an earlier check. -- Be careful not to introduce potential loops! makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String]) makeDynFlagsConsistent dflags | hscTarget dflags == HscC && not (platformUnregisterised (targetPlatform dflags)) = if cGhcWithNativeCodeGen == "YES" then let dflags' = dflags { hscTarget = HscAsm } warn = "Compiler not unregisterised, so using native code generator rather than compiling via C" in loop dflags' warn else let dflags' = dflags { hscTarget = HscLlvm } warn = "Compiler not unregisterised, so using LLVM rather than compiling via C" in loop dflags' warn | hscTarget dflags == HscAsm && platformUnregisterised (targetPlatform dflags) = loop (dflags { hscTarget = HscC }) "Compiler unregisterised, so compiling via C" | hscTarget dflags == HscAsm && cGhcWithNativeCodeGen /= "YES" = let dflags' = dflags { hscTarget = HscLlvm } warn = "No native code generator, so using LLVM" in loop dflags' warn | hscTarget dflags == HscLlvm && not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin)) && not ((isARM arch) && (os == OSLinux)) && (not (gopt Opt_Static dflags) || gopt Opt_PIC dflags) = if cGhcWithNativeCodeGen == "YES" then let dflags' = dflags { hscTarget = HscAsm } warn = "Using native code generator rather than LLVM, as LLVM is incompatible with -fPIC and -dynamic on this platform" in loop dflags' warn else throwGhcException $ CmdLineError "Can't use -fPIC or -dynamic on this platform" | os == OSDarwin && arch == ArchX86_64 && not (gopt Opt_PIC dflags) = loop (gopt_set dflags Opt_PIC) "Enabling -fPIC as it is always on for this platform" | otherwise = (dflags, []) where loc = mkGeneralSrcSpan (fsLit "when making flags consistent") loop updated_dflags warning = case makeDynFlagsConsistent updated_dflags of (dflags', ws) -> (dflags', L loc warning : ws) platform = targetPlatform dflags arch = platformArch platform os = platformOS platform -------------------------------------------------------------------------- -- Do not use unsafeGlobalDynFlags! -- -- unsafeGlobalDynFlags is a hack, necessary because we need to be able -- to show SDocs when tracing, but we don't always have DynFlags -- available. -- -- Do not use it if you can help it. You may get the wrong value! GLOBAL_VAR(v_unsafeGlobalDynFlags, panic "v_unsafeGlobalDynFlags: not initialised", DynFlags) unsafeGlobalDynFlags :: DynFlags unsafeGlobalDynFlags = unsafePerformIO $ readIORef v_unsafeGlobalDynFlags setUnsafeGlobalDynFlags :: DynFlags -> IO () setUnsafeGlobalDynFlags = writeIORef v_unsafeGlobalDynFlags -- ----------------------------------------------------------------------------- -- SSE and AVX -- TODO: Instead of using a separate predicate (i.e. isSse2Enabled) to -- check if SSE is enabled, we might have x86-64 imply the -msse2 -- flag. isSseEnabled :: DynFlags -> Bool isSseEnabled dflags = case platformArch (targetPlatform dflags) of ArchX86_64 -> True ArchX86 -> sseVersion dflags >= Just (1,0) _ -> False isSse2Enabled :: DynFlags -> Bool isSse2Enabled dflags = case platformArch (targetPlatform dflags) of ArchX86_64 -> -- SSE2 is fixed on for x86_64. It would be -- possible to make it optional, but we'd need to -- fix at least the foreign call code where the -- calling convention specifies the use of xmm regs, -- and possibly other places. True ArchX86 -> sseVersion dflags >= Just (2,0) _ -> False isSse4_2Enabled :: DynFlags -> Bool isSse4_2Enabled dflags = sseVersion dflags >= Just (4,2) isAvxEnabled :: DynFlags -> Bool isAvxEnabled dflags = avx dflags || avx2 dflags || avx512f dflags isAvx2Enabled :: DynFlags -> Bool isAvx2Enabled dflags = avx2 dflags || avx512f dflags isAvx512cdEnabled :: DynFlags -> Bool isAvx512cdEnabled dflags = avx512cd dflags isAvx512erEnabled :: DynFlags -> Bool isAvx512erEnabled dflags = avx512er dflags isAvx512fEnabled :: DynFlags -> Bool isAvx512fEnabled dflags = avx512f dflags isAvx512pfEnabled :: DynFlags -> Bool isAvx512pfEnabled dflags = avx512pf dflags -- ----------------------------------------------------------------------------- -- Linker information -- LinkerInfo contains any extra options needed by the system linker. data LinkerInfo = GnuLD [Option] | GnuGold [Option] | DarwinLD [Option] | UnknownLD deriving Eq
ekmett/ghc
compiler/main/DynFlags.hs
bsd-3-clause
154,957
0
32
42,727
30,016
16,888
13,128
-1
-1
{-# LANGUAGE QuasiQuotes #-} module Write.Type.Handle ( writeHandleType ) where import Data.String import Language.C.Types as C import Spec.Type import Text.InterpolatedString.Perl6 import Text.PrettyPrint.Leijen.Text hiding ((<$>)) import Write.TypeConverter import Write.Utils import Write.WriteMonad writeHandleType :: HandleType -> Write Doc writeHandleType ht = let cType = htCType ht in case cType of Ptr [] t@(TypeDef (Struct _)) -> writeDispatchableHandleType ht t t@(TypeDef (TypeName _)) -> writeNonDispatchableHandleType ht t t -> error ("Unhandled handle type " ++ show t ++ ", have more been added to the spec?") writeDispatchableHandleType :: HandleType -> CType -> Write Doc writeDispatchableHandleType ht t = do tellRequiredName (ExternalName (ModuleName "Foreign.Ptr") "Ptr") hsType <- cTypeToHsTypeString t pure [qc|data {hsType} type {htName ht} = Ptr {hsType} |] writeNonDispatchableHandleType :: HandleType -> CType -> Write Doc writeNonDispatchableHandleType ht t = do doesDeriveStorable hsType <- cTypeToHsTypeString t boot <- isBoot let derivingString :: Doc derivingString = if boot then [qc| instance Eq {htName ht} instance Storable {htName ht}|] else fromString "deriving (Eq, Storable)" pure [qc|newtype {htName ht} = {htName ht} {hsType} {derivingString} |]
oldmanmike/vulkan
generate/src/Write/Type/Handle.hs
bsd-3-clause
1,416
0
15
297
338
179
159
34
3
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE LambdaCase #-} -- -- | Convert from core primitives to x86-64 primitives. -- module River.X64.Transform.Reprim ( reprimProgram , reprimTerm , ReprimError(..) ) where import Control.Monad.Trans.Except (ExceptT, throwE) import River.Bifunctor import qualified River.Core.Primitive as Core import River.Core.Syntax import River.Fresh import River.X64.Primitive (Cc(..)) import qualified River.X64.Primitive as X64 data ReprimError n a = ReprimInvalidPrim ![n] Core.Prim ![Atom n a] deriving (Eq, Ord, Show, Functor) reprimProgram :: FreshName n => MonadFresh m => Program k Core.Prim n a -> ExceptT (ReprimError n a) m (Program k X64.Prim n a) reprimProgram = \case Program a tm -> Program a <$> reprimTerm tm reprimTerm :: FreshName n => MonadFresh m => Term k Core.Prim n a -> ExceptT (ReprimError n a) m (Term k X64.Prim n a) reprimTerm = \case Return ar (Call ac n xs) -> pure $ Return ar (Call ac n xs) Return a tl -> do -- TODO should be based on arity of tail, not just [n] -- TODO need to do arity inference before this is possible. n <- newFresh let_tail <- reprimTail a [n] tl pure . let_tail $ Return a (Copy a [Variable a n]) If a k i t e -> do If a k i <$> reprimTerm t <*> reprimTerm e Let a ns tl tm -> do let_tail <- reprimTail a ns tl let_tail <$> reprimTerm tm LetRec a bs tm -> LetRec a <$> reprimBindings bs <*> reprimTerm tm reprimBindings :: FreshName n => MonadFresh m => Bindings k Core.Prim n a -> ExceptT (ReprimError n a) m (Bindings k X64.Prim n a) reprimBindings = \case Bindings a bs -> Bindings a <$> traverse (secondA reprimBinding) bs reprimBinding :: FreshName n => MonadFresh m => Binding k Core.Prim n a -> ExceptT (ReprimError n a) m (Binding k X64.Prim n a) reprimBinding = \case Lambda a ns tm -> Lambda a ns <$> reprimTerm tm reprimTail :: FreshName n => MonadFresh m => a -> [n] -> Tail Core.Prim n a -> ExceptT (ReprimError n a) m (Term k X64.Prim n a -> Term k X64.Prim n a) reprimTail an ns = \case Copy ac xs -> pure $ Let an ns (Copy ac xs) Call ac n xs -> pure $ Let an ns (Call ac n xs) Prim ap p0 xs -> do case reprimTrivial p0 of Just p -> pure $ Let an ns (Prim ap p xs) Nothing -> reprimComplex an ns ap p0 xs reprimTrivial :: Core.Prim -> Maybe X64.Prim reprimTrivial = \case -- Trivial cases Core.Neg -> Just X64.Neg Core.Not -> Just X64.Not Core.Add -> Just X64.Add Core.Sub -> Just X64.Sub Core.And -> Just X64.And Core.Xor -> Just X64.Xor Core.Or -> Just X64.Or Core.Shl -> Just X64.Sal Core.Shr -> Just X64.Sar -- Complex cases, must be handled by reprimComplex. Core.Mul -> Nothing Core.Div -> Nothing Core.Mod -> Nothing Core.Eq -> Nothing Core.Ne -> Nothing Core.Lt -> Nothing Core.Le -> Nothing Core.Gt -> Nothing Core.Ge -> Nothing reprimComplex :: FreshName n => MonadFresh m => a -> [n] -> a -> Core.Prim -> [Atom n a] -> ExceptT (ReprimError n a) m (Term k X64.Prim n a -> Term k X64.Prim n a) reprimComplex an ns ap p xs = case (ns, p, xs) of -- Arithmetic -- ([dst], Core.Mul, [x, y]) -> do ignore <- newFresh pure . Let an [dst, ignore] $ Prim ap X64.Imul [x, y] ([dst], Core.Div, [x, y]) -> do ignore <- newFresh high_x <- newFresh pure $ Let ap [high_x] (Prim ap X64.Cqto [x]) . Let an [dst, ignore] (Prim ap X64.Idiv [x, Variable ap high_x, y]) ([dst], Core.Mod, [x, y]) -> do ignore <- newFresh high_x <- newFresh pure $ Let ap [high_x] (Prim ap X64.Cqto [x]) . Let an [ignore, dst] (Prim ap X64.Idiv [x, Variable ap high_x, y]) -- Relations -- ([dst], prim, [x, y]) | Just cc <- takeCC prim -> do flags <- freshen dst dst8 <- freshen dst pure $ Let an [flags] (Prim ap X64.Cmp [x, y]) . Let an [dst8] (Prim ap (X64.Set cc) [Variable ap flags]) . Let an [dst] (Prim ap X64.Movzbq [Variable ap dst8]) _ -> throwE $ ReprimInvalidPrim ns p xs takeCC :: Core.Prim -> Maybe Cc takeCC = \case Core.Eq -> Just E Core.Ne -> Just Ne Core.Lt -> Just L Core.Le -> Just Le Core.Gt -> Just G Core.Ge -> Just Ge _ -> Nothing
jystic/river
src/River/X64/Transform/Reprim.hs
bsd-3-clause
4,760
0
18
1,568
1,868
935
933
-1
-1
-- -- | This test reads the current directory and dumps a topologically sorted package list -- module Main where import Distribution.ArchLinux.SrcRepo import System.IO import System.Directory import System.Environment import Control.Monad main = do [pkg] <- getArgs dot <- getCurrentDirectory repo <- getRepoFromDir dot case repo of Nothing -> return () Just r -> foldM (\a -> \s -> putStrLn s) () (getDependencies pkg r)
archhaskell/archlinux
scripts/recdeps.hs
bsd-3-clause
441
0
14
83
125
66
59
13
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Sonos.Plugins.Pandora ( login , getStationList , searchStation , createStation , module Sonos.Plugins.Pandora.Types ) where import Sonos.Plugins.Pandora.Types import Sonos.Plugins.Pandora.Crypt import Network.Wreq import Control.Monad import Network.HTTP.Types.Status (status200) import Control.Lens ((^?), (^?!), (.~), (&)) import qualified Data.Time.Clock.POSIX as POSIX import qualified Data.Aeson as J import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Char8 as BSC endpoint = "http://tuner.pandora.com/services/json/" endpointSecure = "https://tuner.pandora.com/services/json/" mkPandoraRequest (PandoraWorld {..}) a = do adjustedSyncTime <- adjustSyncTime pwSyncTime pwTimeSynced return $ PandoraRequest a adjustedSyncTime pwUserAuthToken userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7" partnerLogin = do let plUserName = "android" plPassword = "AC7IBG09A3DTSYM4R41UJWL07VLN8JI7" plDeviceModel = "android-generic" plVersion = "5" plIncludeUrls = True pl = PartnerLogin {..} target = endpointSecure postBody = J.encode $ pl opts = defaults & header "Content-type" .~ ["text/plain; charset=utf8"] & header "User-Agent" .~ [userAgent] & param "method" .~ ["auth.partnerLogin"] resp <- postWith opts target postBody let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply PartnerLoginReply)) let readSyncTime = plrSyncTime $ prResult $ resp' decodedSyncTime = decSyncTime readSyncTime unixSyncTime <- fmap floor POSIX.getPOSIXTime return (read $ BSC.unpack decodedSyncTime , plrPartnerId $ prResult $ resp' , plrPartnerAuthToken $ prResult $ resp' , unixSyncTime ) userLogin ulSyncTime partnerId ulPartnerAuthToken ulUserName ulPassword = do let ul = UserLogin {..} target = endpointSecure postBody = J.encode $ ul postBodyC = enc $ BSL.toStrict postBody opts = defaults & header "Content-type" .~ ["text/plain; charset=utf8"] & header "User-Agent" .~ [userAgent] & param "method" .~ ["auth.userLogin"] & param "partner_id" .~ [partnerId] & param "auth_token" .~ [ulPartnerAuthToken] resp <- postWith opts target postBodyC let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply UserLoginReply)) return (ulrUserAuthToken $ prResult resp', ulrUserId $ prResult resp', not $ ulrHasAudioAds $ prResult resp') login email password = do (pwSyncTime, pwPartnerId, pauth, pwTimeSynced) <- partnerLogin (pwUserAuthToken, pwUserId, pwHasSub) <- userLogin pwSyncTime pwPartnerId pauth email password return (PandoraWorld {..}) adjustSyncTime syncTime timeSynced = do now <- fmap floor POSIX.getPOSIXTime return $ syncTime + (now - timeSynced) handle resp = do when (resp ^?! responseStatus /= status200) $ do putStrLn $ show (resp ^?! responseBody) getStationList pw@(PandoraWorld {..}) = do let target = endpoint slIncludeStationArtUrl = True resp <- postIt' pw "user.getStationList" $ StationList {..} let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply StationListReply)) return $ slrStations $ prResult $ resp' searchStation pw@(PandoraWorld {..}) t = do let target = endpoint msSearchText = t resp <- postIt' pw "music.search" $ MusicSearch {..} let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply MusicSearchReply)) return $ prResult $ resp' createStation pw@(PandoraWorld {..}) t = do let target = endpoint csToken = t resp <- postIt' pw "station.createStation" $ CreateStation {..} let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply CreateStationReply)) return $ prResult $ resp' postIt' pw method js = do resp <- postIt pw method js handle resp return resp postIt pw@(PandoraWorld {..}) method js = do preq <- mkPandoraRequest pw js let target = endpoint postBody = J.encode $ preq postBodyC = enc $ BSL.toStrict postBody opts = defaults & header "Content-type" .~ ["text/plain; charset=utf8"] & header "User-Agent" .~ [userAgent] & param "method" .~ [method] & param "partner_id" .~ [pwPartnerId] & param "auth_token" .~ [pwUserAuthToken] & param "user_id" .~ [pwUserId] resp <- postWith opts target postBodyC return resp
merc1031/haskell-sonos-http-api
src/Sonos/Plugins/Pandora.hs
bsd-3-clause
5,076
0
22
1,295
1,423
728
695
103
1
{-# LANGUAGE FlexibleContexts #-} import Control.Monad.State import Test.Tasty import Test.Tasty.HUnit import qualified Text.Parsec as P hiding (State) import Text.Parsec.Indent import Parser.NanoHaskellParser import Parser.CoreParser import Syntax.Name import Syntax.NanoHaskell import Utils.Pretty main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [parserPrettyTests] parserPrettyTests :: TestTree parserPrettyTests = testGroup "Parser and Pretty Printer Tests" [ testGroup "Literals" [ testCase "Char:" $ genSyntaxPrettyTest (LitChar 'c') literalP , testCase "String:" $ genSyntaxPrettyTest (LitString "abc") literalP , testGroup "Numbers:" [ testCase "Int positive:" $ genSyntaxPrettyTest (LitInt 23) literalP , testCase "Int negative:" $ genSyntaxPrettyTest (LitInt (-23)) literalP , testCase "Float:" $ genSyntaxPrettyTest (LitFloat (23.45)) literalP ] ] , testGroup "Expressions" [ testCase "Var:" $ genSyntaxPrettyTest (EVar (Name "xs")) atomP , testCase "Con:" $ genSyntaxPrettyTest (ECon (Name "Cons")) atomP , testCase "Lit:" $ genSyntaxPrettyTest (ELit (LitFloat (3.14))) atomP , testCase "Lam:" $ genSyntaxPrettyTest (ELam (Name "x") (EVar (Name "x"))) lamP -- , testCase "If:" $ genSyntaxPrettyTest (EIf (ECon (Name "True")) (EVar (Name "xs")) (EVar (Name "x"))) atomP ] ] genSyntaxPrettyTest :: (Show a, Eq a, PPrint a) => a -> Parser a -> Assertion genSyntaxPrettyTest x px = case runIndent "" $ P.runParserT px () "" (render $ pprint x) of Left e -> print (pprint x) Right x' -> x @=? x'
rodrigogribeiro/nanohaskell
test/Spec.hs
bsd-3-clause
2,533
0
16
1,206
490
251
239
32
2
module ErrVal where -- ErrVal captures a value, or an error state indicating -- that the value could not be computed. The error state -- includes a "reason" message and context information on -- where the error occurred. -- -- Instances of Functor, Applicative, Monad, Num, and Fractional are -- provided. import Control.Monad import Control.Applicative data ErrVal a = EValue a | Error { ereason :: String, econtext :: [String] } deriving (Eq,Ord,Show) instance Functor ErrVal where fmap f (EValue a) = EValue (f a) fmap _ (Error e c) = Error e c instance Applicative ErrVal where pure = EValue (EValue f) <*> (EValue a) = EValue (f a) (Error e c) <*> _ = Error e c _ <*> (Error e c) = Error e c instance Monad ErrVal where return = pure (EValue a) >>= f = f a (Error e c ) >>= f = Error e c eVal a = EValue a eErr s = Error s [] eContext :: String -> ErrVal a -> ErrVal a eContext c ev@(EValue v) = ev eContext c (Error msg cs) = Error msg (c:cs) evMaybe :: Maybe a -> String -> ErrVal a evMaybe (Just v) _ = eVal v evMaybe _ s = eErr s evFilter :: [ErrVal a] -> [a] evFilter = foldr f [] where f (EValue a) as = a:as f _ as= as evlift1 :: (a->a) -> ErrVal a -> ErrVal a evlift1 f e = pure f <*> e evlift2 :: (a->a->a) -> ErrVal a -> ErrVal a -> ErrVal a evlift2 f e1 e2 = pure f <*> e1 <*> e2 instance Num a => Num (ErrVal a) where (+) = evlift2 (+) (-) = evlift2 (-) (*) = evlift2 (*) negate = evlift1 negate abs = evlift1 abs signum = evlift1 signum fromInteger i = eVal (fromInteger i) instance Fractional a => Fractional (ErrVal a) where fromRational r = eVal (fromRational r) (/) = evlift2 (/) errval :: (a -> b) -> (String -> b) -> (ErrVal a) -> b errval fa fe (EValue a) = fa a errval fa fe (Error e c) = fe e
timbod7/veditor
ErrVal.hs
bsd-3-clause
1,843
0
9
481
811
414
397
48
2
-- {-# LANGUAGE DeriveFunctor #-} -- {-# LANGUAGE DeriveFoldable #-} -- {-# LANGUAGE DeriveTraversable #-} -- {-# LANGUAGE DeriveGeneric #-} -- {-# LANGUAGE BangPatterns #-} -- {-# LANGUAGE TemplateHaskell #-} -- {-# LANGUAGE RecordWildCards #-} -- {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE CPP #-} -- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-} -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <rx@a-rx.info> -- Stability : experimental -- Portability: non-portable -- -- This module provides Pire's refactoring features: -- calculate token ranges (ie. exact position information), -- based upon Trifecta Delta's and LineColunn numbers, module Pire.Refactor.Range ( module Pire.Refactor.Range ) where import Pire.Syntax.Ws import Pire.Syntax.Nm import Pire.Syntax.Token import Pire.Syntax.Modules import Pire.Syntax.Expr import Pire.Syntax.Decl import Pire.Syntax.Binder import Pire.Syntax.Eps import Pire.Syntax.Telescope import Pire.Syntax.Pattern import Pire.Syntax.Constructor import Pire.Refactor.Pos import qualified Data.Text as T import Text.Trifecta.Delta -- import Control.Monad.Error #ifdef MIN_VERSION_GLASGOW_HASKELL #if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0) -- ghc >= 7.10.3 -- import Control.Monad.Except #else -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined #endif #else -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) import Data.Monoid -- import Data.Foldable (foldMap) import Data.Foldable hiding (elem) #endif import Data.Bifoldable #ifdef DocTest -- for the doctests import Pire.Refactor.Decorate (decorate) import Pire.Wrap (wrap) import Pire.Parser.ParseUtils (parse) import Pire.Parser.Expr (expr_) import Pire.Parser.Parser (beginning) import System.IO.Silently (silence) import Control.Monad.Except (runExceptT) import Control.Monad.Except (runExceptT) import Data.Either.Combinators (fromRight') import Pire.Modules (getModules_) import Pire.Refactor.Navigation (body, toDecl, focus, fromExp, ezipper, right, Tr(Mod)) import Pire.Refactor.Decorate (decorateM) #endif import Control.Lens hiding (from, to) {-| @(Pos 8 100) `inRange` ("hello \n \n \n", Range (Pos 7 0) (To 9 2))@ ? No: there is no 100th char in line 8 (the understanding is, that lines are not just infinitely long, that way we get more precise position info) @ 7 "hello \n" 8 " \n" 9 " \n" @ >>> let range = rangeS "hello \n \n \n" (Pos 7 0) >>> range Range (Pos 7 0) (Pos 9 2) >>> let detailed = detailedRangeS "hello \n \n \n" (Pos 7 0) >>> detailed DetailedRange [Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 8 0,Pos 8 1,Pos 9 0,Pos 9 1,Pos 9 2] >>> (Pos 8 100) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) False but @(Pos 8 2)@ deserves more attention: it seems: yes, but details inspection reveals: no >>> (Pos 8 100) `inRange` range True >>> (Pos 8 100) `inRange` detailed False -} {-| >>> detailedRangeS " " (Pos 4 6) DetailedRange [Pos 4 6] >>> (Pos 4 6) `inRange` (detailedRangeS " " (Pos 4 6)) True >>> (Pos 4 7) `inRange` (detailedRangeS " " (Pos 4 6)) False >>> (detailedRangeS "\n\n" (Pos 4 17)) DetailedRange [Pos 4 17,Pos 5 0] >>> (Pos 4 17) `inRange` (detailedRangeS "\n\n" (Pos 4 17)) True >>> rangeS "hello \n \n \n" (Pos 7 0) Range (Pos 7 0) (Pos 9 2) >>> detailedRangeS "hello \n \n \n" (Pos 7 0) DetailedRange [Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 8 0,Pos 8 1,Pos 9 0,Pos 9 1,Pos 9 2] >>> (Pos 7 2) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) True >>> rangeS "hello \n \n \n" (Pos 4 6) Range (Pos 4 6) (Pos 6 2) >>> detailedRangeS "hello \n \n \n" (Pos 4 6) DetailedRange [Pos 4 6,Pos 4 7,Pos 4 8,Pos 4 9,Pos 4 10,Pos 4 11,Pos 4 12,Pos 4 13,Pos 5 0,Pos 5 1,Pos 6 0,Pos 6 1,Pos 6 2] >>> (Pos 4 6) `inRange` (detailedRangeS "hello \n \n \n" (Pos 4 6)) True >>> detailedRangeS "hello \n \n \n" (Pos 7 0) DetailedRange [Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 8 0,Pos 8 1,Pos 9 0,Pos 9 1,Pos 9 2] >>> (Pos 7 0) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) True >>> (Pos 7 8) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) False >>> (Pos 8 1) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) True >>> (Pos 8 100) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) False -} data Range = Range Pos Pos | NoRange deriving (Show) data DetailedRange = DetailedRange [Pos] deriving (Show) -- helper nextpos '\n' (Pos x _) = Pos (x+1) 0 nextpos _ (Pos x y) = Pos x (y+1) -- another helper: accumulate the Pos pos found so far in the first param -- | -- >>> foo [] "hi\n " (Pos 4 16) -- [Pos 4 16,Pos 4 17,Pos 4 18,Pos 5 0,Pos 5 1] foo :: [Pos] -> String -> Pos -> [Pos] foo found [] _ = found foo found (c:rest) usepos = foo (found ++ [usepos]) rest (nextpos c usepos) fooT :: [Pos] -> T.Text -> Pos -> [Pos] fooT found chars usepos | T.length chars == 0 = found | otherwise = fooT (found ++ [usepos]) rest (nextpos c usepos) where c = T.head chars rest = T.tail chars rangeS :: [Char] -> Pos -> Range rangeS [] _ = NoRange rangeS (_:[]) from = Range from from rangeS s from = Range from to where to = last $ foo [] s from rangeT :: T.Text -> Pos -> Range rangeT txt from | T.length txt == 0 = NoRange | T.length txt == 1 = Range from from | otherwise = Range from to where to = last $ fooT [] txt from -- | helpers take a @Pos@ (not a @Delta@) detailedRangeS :: [Char] -> Pos -> DetailedRange detailedRangeS s from = DetailedRange $ foo [] s from detailedRangeT :: T.Text -> Pos -> DetailedRange detailedRangeT t from = DetailedRange $ fooT [] t from -- | -- range of a token (ie. of the text parts within the token), -- but also more generally: of any piece of the syntax tree: exprs, decls class HasRange t where range :: t -> Range class HasDetailedRange t where -- | "detailed range" drange :: t -> DetailedRange instance HasRange (String, Delta) where range (s, (Lines l c _ _)) = rangeS s (Pos l c) instance HasDetailedRange (String, Delta) where drange (s, (Lines l c _ _)) = detailedRangeS s (Pos l c) instance HasRange (T.Text, Delta) where range (s, (Lines l c _ _)) = rangeT s (Pos l c) instance HasDetailedRange (T.Text, Delta) where drange (s, (Lines l c _ _)) = detailedRangeT s (Pos l c) -- -------------------------------------------------- -- pos < (Range from _) = compare pos from == LT class InRange x where inRange :: Pos -> x -> Bool instance InRange Range where pos `inRange` (Range from to) | from <= pos && pos <= to = True | otherwise = False _ `inRange` NoRange = False instance InRange DetailedRange where pos `inRange` (DetailedRange ls) = pos `elem` ls instance InRange (T.Text, Delta) where pos `inRange` pair@(_,_) = pos `inRange` range pair && pos `inRange` drange pair instance InRange (String, Delta) where pos `inRange` pair@(_,_) = pos `inRange` range pair && pos `inRange` drange pair -- -------------------------------------------------- -- ranges of token, Decls etc -- can add ranges, and therefore understand them as monoids -- (*) -- refined version of addRange: -- a range being added should only contribute it's larger -- examples: -- w/ tst parsed from file tst -- fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus -- range $ fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus -- drange $ fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus -- (ezipper $ Mod tst) >>= lineColumn 19 22 -- by hand: -- >>> decorate( wrap $ nopos $ t2s $ parse expr "\\a . x a") (Lines 0 0 0 0) -- LamPAs [(RuntimeP,("a",Lines 0 0 0 0),Annot Nothing)] (Scope (V (F (V ("x",Lines 0 1 0 0))) :@ BndV ("a",Lines 0 2 0 0) (V (B 0)))) -- -- >>> instantiate1 (V ("a",Lines 0 0 0 0 )) $ scopepl $ decorate( wrap $ nopos $ t2s $ parse expr "\\a . x a") (Lines 0 0 0 0) -- V ("x",Lines 0 1 0 0) :@ BndV ("a",Lines 0 2 0 0) (V ("a",Lines 0 0 0 0)) -- it appears that that last "a" is at a smaller postion (ie. because the binder was), -- the range should nevertheless be -- >>> range $ instantiate1 (V ("a",Lines 0 0 0 0 )) $ scopepl $ decorate( wrap $ nopos $ t2s $ parse expr "\\a . x a") (Lines 0 0 0 0) -- Range (Pos 0 1) (Pos 0 2) {- wo/ any of these precautions this is what happens: fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus >>> range (Ws_ (V ("x",Lines 19 20 0 0)) (Ws (" ",Lines 19 21 0 0)) :@ Ws_ (BndV ("a",Lines 19 22 0 0) (V ("a",Lines 19 16 0 0))) (Ws ("",Lines 19 23 0 0))) Range (Pos 19 20) (Pos 19 16) >>> drange (Ws_ (V ("x",Lines 19 20 0 0)) (Ws (" ",Lines 19 21 0 0)) :@ Ws_ (BndV ("a",Lines 19 22 0 0) (V ("a",Lines 19 16 0 0))) (Ws ("",Lines 19 23 0 0))) DetailedRange [Pos 19 20,Pos 19 21,Pos 19 22,Pos 19 16] -} -- formerly just -- addRange (Range f _) (Range _ t') = Range f t' -- but need to watch out for instantiated vars, cf (*) above addRange (Range f t) (Range _ t') | t <= t' = Range f t' -- stick with the old Range | otherwise = Range f t addRange (Range f t) NoRange = Range f t addRange NoRange (Range f t) = Range f t addRange _ _ = NoRange -- likewise we want only positions to contribute to addition that are larger than the previous ones -- addDetailedRange (DetailedRange l) (DetailedRange l') = DetailedRange $ l ++ l' -- ok, but not necessary maybe -- addDetailedRange (DetailedRange l) (DetailedRange l') = DetailedRange $ l ++ [x | x <- l', (x >=) `all` l ] -- this should be enough, and faster addDetailedRange (DetailedRange []) (DetailedRange l') = DetailedRange l' addDetailedRange (DetailedRange l@(_:_)) (DetailedRange l') = DetailedRange $ l ++ [x | x <- l', x >= last l ] -- maybe ">" -- addDetailedRange (DetailedRange l@(_:_)) (DetailedRange l') -- = DetailedRange $ l ++ [x | x <- l', x > last l ] -- [drange d| d <- _decls $ decorateM $ wrap $ tst] instance Monoid Range where mempty = NoRange mappend = addRange instance Monoid DetailedRange where mempty = DetailedRange [] mappend = addDetailedRange class Decorated t where instance Decorated (t', Delta) -- think of (t', Delta) when t is Decorated -- (but there may be other kinds of decorations as well in the future), -- eg. (t', Pos) -- instance (HasRange (t, Delta)) => HasRange (Ws (t, Delta)) where -- range = foldMap range -- instance (HasDetailedRange (t, Delta)) => HasDetailedRange (Ws (t, Delta)) where -- drange = foldMap drange -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Ws t) where range = foldMap range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Ws t) where drange = foldMap drange {-| Ws >>> range $ Ws (" ",Lines 6 6 0 0) Range (Pos 6 6) (Pos 6 8) >>> drange $ Ws (" ",Lines 6 6 0 0) DetailedRange [Pos 6 6,Pos 6 7,Pos 6 8] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Ws t) where pos `inRange` ws = pos `inRange` range ws && pos `inRange` drange ws -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Token ty t) where range = foldMap range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Token ty t) where drange = foldMap drange {-| ImportTok >>> range $ ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)) Range (Pos 6 0) (Pos 6 8) >>> drange $ ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)) DetailedRange [Pos 6 0,Pos 6 1,Pos 6 2,Pos 6 3,Pos 6 4,Pos 6 5,Pos 6 6,Pos 6 7,Pos 6 8] -} {-| Equal >>> range $ Equal ("=",Lines 11 2 0 0) (Ws (" ",Lines 11 3 0 0)) Range (Pos 11 2) (Pos 11 3) >>> drange $ Equal ("=",Lines 11 2 0 0) (Ws (" ",Lines 11 3 0 0)) DetailedRange [Pos 11 2,Pos 11 3] -} {-| LamTok >>> range $ LamTok ("\\",Lines 9 4 0 0) (Ws (" ",Lines 9 5 0 0)) Range (Pos 9 4) (Pos 9 6) >>> drange $ LamTok ("\\",Lines 9 4 0 0) (Ws (" ",Lines 9 5 0 0)) DetailedRange [Pos 9 4,Pos 9 5,Pos 9 6] -} {-| Dot >>> range $ (Dot (".",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (Dot (".",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| ParenOpen >>> range $ (ParenOpen ("(",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (ParenOpen ("(",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| ParenClose >>> range $ (ParenClose (")",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (ParenClose (")",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| BracketOpen >>> range $ (BracketOpen ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (BracketOpen ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| BracketClose >>> range $ (BracketClose ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (BracketClose ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| missing still: doctests/examples for @VBar@, @Comma@, @Of@, @PcaseTok@, @CaseTok@, @SubsTok@, @By@ -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Token ty t) where pos `inRange` itok = pos `inRange` range itok && pos `inRange` drange itok -- -------------------------------------------------- instance (HasRange t) => HasRange (Maybe t) where range = foldMap range instance (HasDetailedRange t) => HasDetailedRange (Maybe t) where drange = foldMap drange instance InRange t => InRange (Maybe t) where _ `inRange` Nothing = False pos `inRange` Just t = pos `inRange` t -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Nm1 t) where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (Nm1 t) where drange = foldMap drange {-| >>> range $ Nm1_ ("g",Lines 15 0 0 0) (Ws (" ",Lines 15 1 0 0)) Range (Pos 15 0) (Pos 15 1) >>> drange $ Nm1_ ("g",Lines 15 0 0 0) (Ws (" ",Lines 15 1 0 0)) DetailedRange [Pos 15 0,Pos 15 1] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Nm1 t) where pos `inRange` nm = pos `inRange` range nm && pos `inRange` drange nm -- -------------------------------------------------- instance ( Decorated t , HasRange t ) => HasRange (ModuleImport t) where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (ModuleImport t) where drange = foldMap drange {-| ModuleImport >>> range $ ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))} Range (Pos 6 0) (Pos 6 12) >>> drange $ ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))} DetailedRange [Pos 6 0,Pos 6 1,Pos 6 2,Pos 6 3,Pos 6 4,Pos 6 5,Pos 6 6,Pos 6 7,Pos 6 8,Pos 6 9,Pos 6 10,Pos 6 11,Pos 6 12] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (ModuleImport t) where pos `inRange` mi = pos `inRange` range mi && pos `inRange` drange mi -- -------------------------------------------------- {-| cf @inRange@ below -} instance ( Decorated t , HasRange t ) => HasRange [ModuleImport t] where range = foldMap range {-| cf @inRange@ below -} instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [ModuleImport t] where drange = foldMap drange {-| \[ModuleImport\] >>> range $ [ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))},ModuleImport_ {_importtok = ImportTok ("import",Lines 7 0 0 0) (Ws (" ",Lines 7 6 0 0)), _importnm = Nm1_ ("Sample",Lines 7 7 0 0) (Ws ("\n\n",Lines 7 13 0 0))}] Range (Pos 6 0) (Pos 8 0) >>> drange $ [ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))},ModuleImport_ {_importtok = ImportTok ("import",Lines 7 0 0 0) (Ws (" ",Lines 7 6 0 0)), _importnm = Nm1_ ("Sample",Lines 7 7 0 0) (Ws ("\n\n",Lines 7 13 0 0))}] DetailedRange [Pos 6 0,Pos 6 1,Pos 6 2,Pos 6 3,Pos 6 4,Pos 6 5,Pos 6 6,Pos 6 7,Pos 6 8,Pos 6 9,Pos 6 10,Pos 6 11,Pos 6 12,Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 7 8,Pos 7 9,Pos 7 10,Pos 7 11,Pos 7 12,Pos 7 13,Pos 8 0] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [ModuleImport t] where pos `inRange` mis = pos `inRange` range mis && pos `inRange` drange mis -- -------------------------------------------------- {-| cf @inRange@ below -} instance (Decorated t, HasRange t) => HasRange (Expr t t) where range = bifoldMap range range {-| cf @inRange@ below -} instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Expr t t) where drange = bifoldMap drange drange {-| ranges of exprs >>> range $ decorate (wrap $ parse expr_ "f ") beginning Range (Pos 0 0) (Pos 0 3) >>> range $ decorate (wrap $ parse expr_ "f a b ") beginning Range (Pos 0 0) (Pos 0 6) -} {- those examples, that contain {-ws-} comments we better test in regular (doctest) "--" comments, otherwise (within the {-| ... -} above) we need extra escaping à la {\-ws-\}, and things soon get unreadable -} -- | -- >>> range $ decorate (wrap $ parse expr_ "\\ x . f a b{-ws-}") beginning -- Range (Pos 0 0) (Pos 0 16) -- -- >>> drange $ (decorate (wrap $ parse expr_ "f a b{-ws-}") beginning) -- DetailedRange [Pos 0 0,Pos 0 1,Pos 0 2,Pos 0 3,Pos 0 4,Pos 0 5,Pos 0 6,Pos 0 7,Pos 0 8,Pos 0 9,Pos 0 10] instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Expr t t) where pos `inRange` ex = pos `inRange` range ex && pos `inRange` drange ex -- -------------------------------------------------- -- need to handle [Expr t t] as well, for TCon_ at least instance ( Decorated t , HasRange t ) => HasRange [Expr t t] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [Expr t t] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Expr t t] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Decl t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Decl t t) where drange = bifoldMap drange drange {-| ranges of decls, examples/tests! -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Decl t t) where pos `inRange` dcl = pos `inRange` range dcl && pos `inRange` drange dcl -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange [Decl t t] where range = foldMap $ bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange [Decl t t] where drange = foldMap $ bifoldMap drange drange {-| ranges of lists of decls, examples/tests! -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Decl t t] where pos `inRange` dcls = pos `inRange` range dcls && pos `inRange` drange dcls -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Binder t) where range = foldMap range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Binder t) where drange = foldMap drange {-| ranges of binders, examples/tests! -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Binder t) where pos `inRange` bndr = pos `inRange` range bndr && pos `inRange` drange bndr -- for the binders of a LamPAs_, the triple list ie. instance (Decorated t, HasRange t) => HasRange (Eps, Binder t, Annot t t) where range = foldMap range . (^. _2) instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Eps, Binder t, Annot t t) where drange = foldMap drange . (^. _2) instance (Decorated t, HasRange t) => HasRange [(Eps, Binder t, Annot t t)] where range = foldMap $ foldMap range . (^. _2) instance (Decorated t, HasDetailedRange t) => HasDetailedRange [(Eps, Binder t, Annot t t)] where drange = foldMap $ foldMap drange . (^. _2) instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Eps, Binder t, Annot t t) where pos `inRange` trpl = pos `inRange` range trpl && pos `inRange` drange trpl instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [(Eps, Binder t, Annot t t)] where pos `inRange` trpls = pos `inRange` range trpls && pos `inRange` drange trpls -- nov2015, telescopes instance (Decorated t, HasRange t) => HasRange (Telescope t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Telescope t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Telescope t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele -- match/case - Nov 2015 instance (Decorated t, HasRange t) => HasRange (Match t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Match t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Match t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele -- uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu instance (Decorated t, HasRange a, HasRange t) => HasRange (Pattern t a) where range = foldMap range instance (Decorated t, HasDetailedRange a, HasDetailedRange t) => HasDetailedRange (Pattern t a) where drange = foldMap drange instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange (Pattern t a) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele -- instance ( Decorated t , HasRange a , HasRange t ) => HasRange (Pattern t a, Eps) where range = range . fst instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange (Pattern t a, Eps) where drange = drange . fst instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange (Pattern t a, Eps) where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches instance ( Decorated t , HasRange a , HasRange t ) => HasRange [(Pattern t a, Eps)] where range = foldMap (range . fst) instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange [(Pattern t a, Eps)] where drange = foldMap (drange . fst) instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange [(Pattern t a, Eps)] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- and the other way around instance ( Decorated t , HasRange a , HasRange t ) => HasRange (Eps, Pattern t a) where range = range . snd instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange (Eps, Pattern t a) where drange = drange . snd instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange (Eps, Pattern t a) where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches instance ( Decorated t , HasRange a , HasRange t ) => HasRange [(Eps, Pattern t a)] where range = foldMap (range . snd) instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange [(Eps, Pattern t a)] where drange = foldMap (drange . snd) instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange [(Eps, Pattern t a)] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu -- hm, do I really need to add these ranges by hand ? - it seems so ! (foldMap is of no use here) instance ( Decorated t , HasRange t ) => HasRange (Match t t, Maybe (Token 'SemiColonTy t)) where range (match, may) = range match `addRange` range may instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (Match t t, Maybe (Token 'SemiColonTy t)) where drange (match, may) = drange match `addDetailedRange` drange may instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange (Match t t, Maybe (Token 'SemiColonTy t)) where pos `inRange` pair = pos `inRange` range pair && pos `inRange` drange pair -- -- guess I need them the other way around now instance ( Decorated t , HasRange t ) => HasRange (Maybe (Token 'SemiColonTy t), Match t t) where range (may, match) = range match `addRange` range may instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (Maybe (Token 'SemiColonTy t), Match t t) where drange (may, match) = drange match `addDetailedRange` drange may instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange (Maybe (Token 'SemiColonTy t), Match t t) where pos `inRange` pair = pos `inRange` range pair && pos `inRange` drange pair -- -------------------------------------------------- -- ... instance ( Decorated t , HasRange t ) => HasRange [Match t t] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [Match t t] where drange = foldMap drange {-| >>> nat <- (silence $ runExceptT $ getModules_ ["samples"] "Nat") >>= return . last . fromRight' >>> let Case_ casetok exp of' mayopen matches mayclose annot = fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap nat) >>= toDecl 2 >>= right >>= body >>= focus >>> range (snd $ matches !! 0) Range (Pos 17 2) (Pos 18 1) >>> range (matches !! 0) Range (Pos 17 2) (Pos 18 1) >>> (Pos 17 10) `inRange` (snd $ matches !! 0) True >>> (Pos 17 10) `inRange` (matches !! 0) True -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Match t t] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- -------------------------------------------------- instance ( Decorated t , HasRange t ) => HasRange [(Match t t, Maybe (Token 'SemiColonTy t))] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [(Match t t, Maybe (Token 'SemiColonTy t))] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [(Match t t, Maybe (Token 'SemiColonTy t))] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- ...and the other way around instance ( Decorated t , HasRange t ) => HasRange [(Maybe (Token 'SemiColonTy t), Match t t)] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [(Maybe (Token 'SemiColonTy t), Match t t)] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [(Maybe (Token 'SemiColonTy t), Match t t)] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- DCon_/Arg - Nov 2015 instance (Decorated t, HasRange t) => HasRange (Arg t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Arg t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Arg t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele instance ( Decorated t , HasRange t ) => HasRange [Arg t t] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [Arg t t] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Arg t t] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- similar to Match above instance (Decorated t, HasRange t) => HasRange (ConstructorDef t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (ConstructorDef t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (ConstructorDef t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele instance ( Decorated t , HasRange t ) => HasRange (ConstructorDef t t, Maybe (Token 'SemiColonTy t)) where range (match, may) = range match `addRange` range may instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (ConstructorDef t t, Maybe (Token 'SemiColonTy t)) where drange (match, may) = drange match `addDetailedRange` drange may instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange (ConstructorDef t t, Maybe (Token 'SemiColonTy t)) where pos `inRange` pair = pos `inRange` range pair && pos `inRange` drange pair instance ( Decorated t , HasRange t ) => HasRange [(ConstructorDef t t, Maybe (Token 'SemiColonTy t))] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [(ConstructorDef t t, Maybe (Token 'SemiColonTy t))] where drange = foldMap drange instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange [(ConstructorDef t t, Maybe (Token 'SemiColonTy t))] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches
reuleaux/pire
src/Pire/Refactor/Range.hs
bsd-3-clause
30,759
0
11
6,642
6,936
3,722
3,214
-1
-1
module BinaryTree ( BinaryTree(..), newNode, value, left, right, getNode, safeGetValue, modifyNode, setNode, listToTree, append, flatten, Bit.natToBits ) where import Bit import Data.List(foldl') data BinaryTree a = Leaf | Branch (Maybe a) (BinaryTree a) (BinaryTree a) instance Show a => Show (BinaryTree a) where show Leaf = "_" show (Branch Nothing l r) = "(_," ++ show l ++ "," ++ show r ++ ")" show (Branch (Just x) l r) = "(" ++ show x ++ "," ++ show l ++ "," ++ show r ++ ")" newNode x = Branch (Just x) Leaf Leaf value Leaf = Nothing value (Branch x _ _) = x left Leaf = Leaf left (Branch _ l _) = l right Leaf = Leaf right (Branch _ _ r) = r getNode Leaf _ = Leaf getNode t@(Branch _ _ _) [] = t getNode (Branch _ l r) (b:bs) = if b then getNode r bs else getNode l bs -- Ignores all leading zeros and one leading one, then calls f. -- If there is no one, returns Nothing ignorePrefixBits _ [] = Nothing ignorePrefixBits f (b:bs) = if b then f bs else ignorePrefixBits f bs safeGetValue tree = ignorePrefixBits (value . getNode tree) modifyNode f Leaf [] = Branch (f Nothing) Leaf Leaf modifyNode f (Branch x l r) [] = Branch (f x) l r modifyNode f Leaf (b:bs) = if b then Branch Nothing Leaf (modifyNode f Leaf bs) else Branch Nothing (modifyNode f Leaf bs) Leaf modifyNode f (Branch x l r) (b:bs) = if b then Branch x l (modifyNode f r bs) else Branch x (modifyNode f l bs) r setNode value = modifyNode (const (Just value)) listToTree xs = snd $ foldl' append ([], Leaf) xs append (n, tree) x = (incrementNat n, setNode x tree n) getDepth :: Int -> BinaryTree a -> [Maybe a] getDepth n = concat . getDepth' n getDepth' :: Int -> BinaryTree a -> [[Maybe a]] getDepth' 0 _ = [] getDepth' n t = let l = getDepth' (n - 1) $ left t r = getDepth' (n - 1) $ right t in [value t] : zipWith (++) l r findDepth Leaf = 0 findDepth (Branch _ l r) = 1 + max (findDepth l) (findDepth r) flatten tree = getDepth (findDepth tree) tree
cullina/Extractor
src/BinaryTree.hs
bsd-3-clause
2,206
0
12
665
969
494
475
67
3
-- -- DMA.hs --- STM32F427 DMA driver. -- -- Copyright (C) 2015, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32F427.DMA where import Ivory.BSP.STM32.Peripheral.DMA import Ivory.Language import Ivory.HW import Ivory.BSP.STM32.Interrupt import Ivory.BSP.STM32F427.RCC import Ivory.BSP.STM32F427.MemoryMap import Ivory.BSP.STM32F427.Interrupt ahb1Enable :: BitDataField RCC_AHB1ENR Bit -> Ivory eff () ahb1Enable bit = modifyReg regRCC_AHB1ENR (setBit bit) ahb1Disable :: BitDataField RCC_AHB1ENR Bit -> Ivory eff () ahb1Disable bit = modifyReg regRCC_AHB1ENR (clearBit bit) dma1 :: DMA dma1 = mkDMA dma1_periph_base (ahb1Enable rcc_ahb1en_dma1) (ahb1Disable rcc_ahb1en_dma1) ints "dma1" where ints = DMAInterrupt { dmaInterruptStream0 = HasSTM32Interrupt DMA1_Stream0 , dmaInterruptStream1 = HasSTM32Interrupt DMA1_Stream1 , dmaInterruptStream2 = HasSTM32Interrupt DMA1_Stream2 , dmaInterruptStream3 = HasSTM32Interrupt DMA1_Stream3 , dmaInterruptStream4 = HasSTM32Interrupt DMA1_Stream4 , dmaInterruptStream5 = HasSTM32Interrupt DMA1_Stream5 , dmaInterruptStream6 = HasSTM32Interrupt DMA1_Stream6 , dmaInterruptStream7 = HasSTM32Interrupt DMA1_Stream7 } dma2 :: DMA dma2 = mkDMA dma2_periph_base (ahb1Enable rcc_ahb1en_dma2) (ahb1Disable rcc_ahb1en_dma2) ints "dma2" where ints = DMAInterrupt { dmaInterruptStream0 = HasSTM32Interrupt DMA2_Stream0 , dmaInterruptStream1 = HasSTM32Interrupt DMA2_Stream1 , dmaInterruptStream2 = HasSTM32Interrupt DMA2_Stream2 , dmaInterruptStream3 = HasSTM32Interrupt DMA2_Stream3 , dmaInterruptStream4 = HasSTM32Interrupt DMA2_Stream4 , dmaInterruptStream5 = HasSTM32Interrupt DMA2_Stream5 , dmaInterruptStream6 = HasSTM32Interrupt DMA2_Stream6 , dmaInterruptStream7 = HasSTM32Interrupt DMA2_Stream7 }
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32F427/DMA.hs
bsd-3-clause
1,945
0
9
379
368
206
162
42
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Diagrams.TwoD.Path.Follow -- Copyright : (c) 2016 Brent Yorgey -- License : BSD-style (see LICENSE) -- Maintainer : byorgey@gmail.com -- -- An alternative monoid for trails which rotates trails so their -- starting and ending tangents match at join points. -- ----------------------------------------------------------------------------- module Diagrams.TwoD.Path.Follow ( Following, follow, unfollow ) where import Diagrams.Prelude import Data.Monoid.SemiDirectProduct.Strict -- | @Following@ is just like @Trail' Line V2@, except that it has a -- different 'Monoid' instance. @Following@ values are -- concatenated, just like regular lines, except that they are also -- rotated so the tangents match at the join point. In addition, -- they are normalized so the tangent at the start point is in the -- direction of the positive x axis (essentially we are considering -- trails equivalent up to rotation). -- -- Pro tip: you can concatenate a list of trails so their tangents -- match using 'ala' from "Control.Lens", like so: -- -- @ala follow foldMap :: [Trail' Line V2 n] -> Trail' Line V2 n@ -- -- This is illustrated in the example below. -- -- <<diagrams/src_Diagrams_TwoD_Path_Follow_followExample.svg#diagram=followExample&width=400>> -- -- > import Control.Lens (ala) -- > import Diagrams.TwoD.Path.Follow -- > -- > wibble :: Trail' Line V2 Double -- > wibble = hrule 1 <> hrule 0.5 # rotateBy (1/6) <> hrule 0.5 # rotateBy (-1/6) <> a -- > where a = arc (xDir # rotateBy (-1/4)) (1/5 @@ turn) -- > # scale 0.7 -- > -- > followExample = -- > [ wibble -- > , wibble -- > # replicate 5 -- > # ala follow foldMap -- > ] -- > # map stroke -- > # map centerXY -- > # vsep 1 -- > # frame 0.5 -- newtype Following n = Following { unFollowing :: Semi (Trail' Line V2 n) (Angle n) } deriving (Monoid, Semigroup) -- | Note this is only an iso when considering trails equivalent up to -- rotation. instance RealFloat n => Wrapped (Following n) where type Unwrapped (Following n) = Trail' Line V2 n _Wrapped' = iso unfollow follow instance RealFloat n => Rewrapped (Following n) (Following n') -- | Create a @Following@ from a line, normalizing it (by rotation) -- so that it starts in the positive x direction. follow :: RealFloat n => Trail' Line V2 n -> Following n follow t = Following $ (t # rotate (signedAngleBetween unitX s)) `tag` theta where s = tangentAtStart t e = tangentAtEnd t theta = signedAngleBetween e s -- | Project out the line from a `Following`. -- -- If trails are considered equivalent up to rotation, then -- 'unfollow' and 'follow' are inverse. unfollow :: Following n -> Trail' Line V2 n unfollow = untag . unFollowing
diagrams/diagrams-contrib
src/Diagrams/TwoD/Path/Follow.hs
bsd-3-clause
3,104
0
11
689
335
204
131
22
1
module HSync.Server.Handler.API where import Control.Lens import HSync.Common.API import qualified HSync.Common.StorageTree as ST import HSync.Server.Import import HSync.Common.Header import HSync.Common.Zip import HSync.Server.LocalAuth(validateUser) import HSync.Server.Notifications import HSync.Server.Handler.AcidUtils import Data.Maybe(fromJust) import Data.Aeson(encode) import qualified Data.Conduit.List as C import qualified Data.Text as T import qualified Data.Foldable as F import qualified System.FilePath as FP -------------------------------------------------------------------------------- postAPILoginR :: APIHandler Value postAPILoginR = lift $ do mu <- lookupTypedHeader HUserName mpw <- fmap hashPassword <$> lookupTypedHeader HPassword b <- validateUser' mu mpw when b $ setCreds False $ Creds "PostAPILoginR" ((fromJust mu)^.unUserName) [] return $ toJSON b where validateUser' mu mpw = fromMaybe (pure False) $ validateUser <$> mu <*> mpw -------------------------------------------------------------------------------- getListenNowR :: RealmId -> Path -> APIHandler TypedContent getListenNowR ri p = lift $ respondWithSource (notificationsFor ri p) getListenR :: DateTime -> RealmId -> Path -> APIHandler TypedContent getListenR d ri p = lift $ respondWithSource (notificationsAsOf d ri p) -- | Given a function to produce a source of a's (that can be encoded as JSON). -- Respond with this source respondWithSource :: ToJSON a => Handler (Source Handler a) -> Handler TypedContent respondWithSource mkSource = do s <- mkSource respondSource typePlain (s $= C.map encode $= awaitForever sendChunk') where sendChunk' x = sendChunk x >> sendFlush -------------------------------------------------------------------------------- getCurrentRealmR :: RealmId -> Path -> APIHandler Value getCurrentRealmR ri p = do mr <- lift . queryAcid $ Access ri p case mr of Nothing -> notFound Just node -> pure . toJSON . current' $ node getDownloadR :: RealmId -> FileKind -> Path -> APIHandler TypedContent getDownloadR _ NonExistent _ = notFound getDownloadR ri Directory p = lift $ queryAcid (Access ri p) >>= \case Nothing -> notFound Just node -> do let ps = mapMaybe toPath . ST.flatten . current' $ node fps <- mapM getFPs ps addTypedHeader HFileKind Directory addHeader "Content-Disposition" $ mconcat [ "attachment; filename=\"" , _unFileName $ fileNameOf p, ".zip\"" ] respondSource typeOctet (readArchive fps $= awaitForever sendChunk) where -- toPath :: _ -> Maybe (Path, Signature) toPath (n,(_,x)) = (Path $ F.toList n,) <$> x^?fileKind.signature getFPs (p',s) = (f p',) <$> getFilePath ri p' s f (Path ps) = FP.joinPath $ map (\n -> T.unpack $ n^.unFileName) ps getDownloadR ri fk@(File s) p = addTypedHeader HFileKind fk >> getFileR ri s p getFileR :: RealmId -> Signature -> Path -> APIHandler TypedContent getFileR ri s p = do fp <- lift $ getFilePath ri p s sendFile (contentTypeOf p) fp getDownloadCurrentR :: RealmId -> Path -> APIHandler TypedContent getDownloadCurrentR ri p = do mr <- lift . queryAcid $ Access ri p case (^.nodeData.headVersionLens.fileKind) <$> mr of Nothing -> notFound Just fk -> getDownloadR ri fk p -------------------------------------------------------------------------------- postCreateDirR :: ClientName -> RealmId -> Path -> APIHandler Value postCreateDirR cn ri p = toJSON <$> lift (withClientId cn $ \ci -> createDirectory ci ri p NonExistent) postStoreFileR :: ClientName -> RealmId -> FileKind -> Path -> APIHandler Value postStoreFileR _ _ Directory _ = lift $ invalidArgs ["Cannot replace a directory by a file"] postStoreFileR cn ri fk p = toJSON <$> lift (withClientId cn $ \ci -> addFile ci ri p fk rawRequestBody) -------------------------------------------------------------------------------- deleteDeleteR :: ClientName -> RealmId -> FileKind -> Path -> APIHandler Value deleteDeleteR _ _ NonExistent _ = reportError_ "Nothing to delete" deleteDeleteR cn ri fk p = toJSON <$> lift (withClientId cn $ \ci -> deleteFileOrDir ci ri p fk) reportError :: Text -> Either ErrorMessage (FileVersion (Maybe ClientName)) reportError = Left reportError_ :: Monad m => Text -> m Value reportError_ = pure . toJSON . reportError -- typedText typedText :: Text -> TypedContent typedText = toTypedContent typedText_ :: Monad m => Text -> m TypedContent typedText_ = return . typedText
noinia/hsync-server
src/HSync/Server/Handler/API.hs
bsd-3-clause
5,429
0
17
1,693
1,362
690
672
-1
-1
import Text.EBNF hiding (main) import Text.EBNF.Informal (syntax) import Text.EBNF.SyntaxTree import Text.EBNF.Helper import Text.EBNF.Build.Parser import Text.EBNF.Build.Parser.Except main :: IO () main = print . raiseBk raiseBk :: SyntaxTree -> SyntaxTree raiseBk = raise ((`elem` [ "definitions list", "single definition", "syntactic factor", "syntactic primary", "syntactic exception", "syntactic term", "integer" ]) . identifier)
Lokidottir/ebnf-bff
ebnf-test/ebnf-test.hs
mit
645
0
9
260
120
75
45
18
1
{-# OPTIONS -Wall -Werror #-} module Test.TestEaster where import Data.Time.Calendar.Easter import Data.Time.Calendar import Data.Time.Format import System.Locale import Test.TestUtil import Test.TestEasterRef -- days :: [Day] days = [ModifiedJulianDay 53000 .. ModifiedJulianDay 53014] showWithWDay :: Day -> String showWithWDay = formatTime defaultTimeLocale "%F %A" testEaster :: Test testEaster = pureTest "testEaster" $ let ds = unlines $ map (\day -> unwords [ showWithWDay day, "->" , showWithWDay (sundayAfter day)]) days f y = unwords [ show y ++ ", Gregorian: moon," , show (gregorianPaschalMoon y) ++ ": Easter," , showWithWDay (gregorianEaster y)] ++ "\n" g y = unwords [ show y ++ ", Orthodox : moon," , show (orthodoxPaschalMoon y) ++ ": Easter," , showWithWDay (orthodoxEaster y)] ++ "\n" in diff testEasterRef $ ds ++ concatMap (\y -> f y ++ g y) [2000..2020]
jwiegley/ghc-release
libraries/time/test/TestEaster.hs
gpl-3.0
1,090
0
18
346
300
158
142
26
1
module Translation where import Control.Monad (unless, mapAndUnzipM) import Control.Monad.Except (throwError) import Control.Arrow (second) -- import Parser -- import Debug.Trace import Expr import Syntax import TypeCheck import Utils -- | Elaboration trans :: Env -> Expr -> TC (Type, Expr) trans _ (Kind Star) = return (Kind Star, Kind Star) trans env (Var s) = findVar env s >>= \t -> return (t, Var s) trans env (App f a) = do (tf, f') <- trans env f case tf of Pi x at rt -> do (ta, a') <- trans env a unless (alphaEq ta at) $ throwError "Bad function argument type" return (subst x a rt, App f' a') _ -> throwError "Non-function in application" trans env (Lam s t e) = do let env' = extend s t env (te, e') <- trans env' e let lt = Pi s t te (_, Pi _ t' _) <- trans env lt return (lt, Lam s t' e') trans env (Pi x a b) = do (s, a') <- trans env a let env' = extend x a env (t, b') <- trans env' b unless (alphaEq t (Kind Star) && alphaEq s (Kind Star)) $ throwError "Bad abstraction" return (t, Pi x a' b') trans env (Mu i t e) = do let env' = extend i t env (te, e') <- trans env' e unless (alphaEq t te) $ throwError "Bad recursive type" (_, t') <- trans env t return (t, Mu i t' e') -- Note that in the surface language, casts should not appear. -- Here we return as it is trans _ (F n t1 e) = do return (t1, F n t1 e) trans env (U n e) = do (t1, _) <- trans env e t2 <- reductN n t1 return (t2, U n e) -- TODO: Lack 1) exhaustive test 2) overlap test trans env (Case e alts) = do (dv, e') <- trans env e actualTypes <- fmap reverse (getActualTypes dv) let arity = length actualTypes (altTypeList, e2List) <- mapAndUnzipM (transPattern dv actualTypes) alts unless (all (alphaEq . head $ altTypeList) (tail altTypeList)) $ throwError "Bad pattern expressions" let (Pi "" _ t) = head . filter (\(Pi "" _ t') -> t' /= Error) $ altTypeList let genExpr = foldl App (App (U (arity + 1) e') t) e2List return (t, genExpr) where transPattern :: Type -> [Type] -> Alt -> TC (Type, Expr) transPattern dv tys (Alt (PConstr constr params) body) = do let k = constrName constr (kt, _) <- trans env (Var k) -- check patterns, quite hacky let tcApp = foldl App (Var "dummy$") (tys ++ map (Var . fst) params) (typ, _) <- trans (("dummy$", kt) : params ++ env) tcApp unless (alphaEq typ dv) $ throwError "Bad patterns" (bodyType, body') <- trans (params ++ env) body return (arr dv bodyType, genLambdas params body') trans env (Data db@(DB tc tca constrs) e) = do env' <- tcdatatypes env db let nenv = env' ++ env (t, e') <- trans nenv e let tct = mkProdType (Kind Star) tca let du = foldl App (Var tc) (map (Var . fst) tca) let dcArgs = map constrParams constrs let dcArgChains = map (mkProdType (Var "B0")) dcArgs let transTC' = map (mkProdType (Var "B0") . map (second (substVar tc "X"))) dcArgs let transTC = (tc, (tct, Mu "X" tct (genLambdas tca (Pi "B0" (Kind Star) (chainType (Var "B0") transTC'))))) let tduList = map (mkProdType du . constrParams) constrs let dctList = map (`mkProdType` tca) tduList let arity = length tca let transDC = zip (map constrName constrs) (zip dctList (map (\(i, taus) -> let cs = genVarsAndTypes 'c' dcArgChains in genLambdas tca (genLambdas taus (F (arity + 1) du (Lam "B0" (Kind Star) (genLambdas cs (foldl App (Var ('c' : show i)) (map (Var . fst) taus))))))) (zip [0 :: Int ..] dcArgs))) return (t, foldr (\(n, (kt, ke)) body -> Let n kt ke body) e' (transTC : transDC)) trans _ Nat = return (Kind Star, Nat) trans _ n@(Lit _) = return (Nat, n) trans env (Add e1 e2) = do (t1, e1') <- trans env e1 (t2, e2') <- trans env e2 unless (t1 == Nat && t2 == Nat) $ throwError "Addition is only allowed for numbers!" return (Nat, Add e1' e2') trans _ Error = return (Error, Error) trans _ e = throwError $ "Trans: Impossible happened, trying to translate: " ++ show e -- | type check datatype tcdatatypes :: Env -> DataBind -> TC Env tcdatatypes env (DB tc tca constrs) = do -- check type constructor let tct = mkProdType (Kind Star) tca tcs <- tcheck env tct unless (tcs == Kind Star) $ throwError "Bad type constructor arguments" -- check data constructors let du = foldl App (Var tc) (map (Var . fst) tca) let tduList = map (mkProdType du . constrParams) constrs dcts <- mapM (tcheck (reverse tca ++ ((tc, tct) : env))) tduList -- Note: reverse type parameters list (tca) unless (all (== Kind Star) dcts) $ throwError "Bad data constructor arguments" -- return environment containing type constructor and data constructors let dctList = map (\tdu -> foldr (\(u, k) t -> Pi u k t) tdu tca) tduList return ((tc, tct) : zip (map constrName constrs) dctList)
bixuanzju/full-version
src/Translation.hs
gpl-3.0
5,168
0
34
1,467
2,290
1,132
1,158
108
2
module Debug where import Control.Monad (when, void) import Constants debug :: Bool -> String -> IO () debug b msg = when b $ putStrLn msg
keera-studios/pang-a-lambda
Experiments/splitballs/Debug.hs
gpl-3.0
142
0
8
29
58
31
27
5
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.CreateInstanceExportTask -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | 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 <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ExportingEC2Instances.html ExportingEC2 Instances> in the /Amazon Elastic Compute Cloud User Guide for Linux/. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateInstanceExportTask.html> module Network.AWS.EC2.CreateInstanceExportTask ( -- * Request CreateInstanceExportTask -- ** Request constructor , createInstanceExportTask -- ** Request lenses , cietDescription , cietExportToS3Task , cietInstanceId , cietTargetEnvironment -- * Response , CreateInstanceExportTaskResponse -- ** Response constructor , createInstanceExportTaskResponse -- ** Response lenses , cietrExportTask ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data CreateInstanceExportTask = CreateInstanceExportTask { _cietDescription :: Maybe Text , _cietExportToS3Task :: Maybe ExportToS3TaskSpecification , _cietInstanceId :: Text , _cietTargetEnvironment :: Maybe ExportEnvironment } deriving (Eq, Read, Show) -- | 'CreateInstanceExportTask' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cietDescription' @::@ 'Maybe' 'Text' -- -- * 'cietExportToS3Task' @::@ 'Maybe' 'ExportToS3TaskSpecification' -- -- * 'cietInstanceId' @::@ 'Text' -- -- * 'cietTargetEnvironment' @::@ 'Maybe' 'ExportEnvironment' -- createInstanceExportTask :: Text -- ^ 'cietInstanceId' -> CreateInstanceExportTask createInstanceExportTask p1 = CreateInstanceExportTask { _cietInstanceId = p1 , _cietDescription = Nothing , _cietTargetEnvironment = Nothing , _cietExportToS3Task = Nothing } -- | A description for the conversion task or the resource being exported. The -- maximum length is 255 bytes. cietDescription :: Lens' CreateInstanceExportTask (Maybe Text) cietDescription = lens _cietDescription (\s a -> s { _cietDescription = a }) cietExportToS3Task :: Lens' CreateInstanceExportTask (Maybe ExportToS3TaskSpecification) cietExportToS3Task = lens _cietExportToS3Task (\s a -> s { _cietExportToS3Task = a }) -- | The ID of the instance. cietInstanceId :: Lens' CreateInstanceExportTask Text cietInstanceId = lens _cietInstanceId (\s a -> s { _cietInstanceId = a }) -- | The target virtualization environment. cietTargetEnvironment :: Lens' CreateInstanceExportTask (Maybe ExportEnvironment) cietTargetEnvironment = lens _cietTargetEnvironment (\s a -> s { _cietTargetEnvironment = a }) newtype CreateInstanceExportTaskResponse = CreateInstanceExportTaskResponse { _cietrExportTask :: Maybe ExportTask } deriving (Eq, Read, Show) -- | 'CreateInstanceExportTaskResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cietrExportTask' @::@ 'Maybe' 'ExportTask' -- createInstanceExportTaskResponse :: CreateInstanceExportTaskResponse createInstanceExportTaskResponse = CreateInstanceExportTaskResponse { _cietrExportTask = Nothing } cietrExportTask :: Lens' CreateInstanceExportTaskResponse (Maybe ExportTask) cietrExportTask = lens _cietrExportTask (\s a -> s { _cietrExportTask = a }) instance ToPath CreateInstanceExportTask where toPath = const "/" instance ToQuery CreateInstanceExportTask where toQuery CreateInstanceExportTask{..} = mconcat [ "Description" =? _cietDescription , "ExportToS3" =? _cietExportToS3Task , "InstanceId" =? _cietInstanceId , "TargetEnvironment" =? _cietTargetEnvironment ] instance ToHeaders CreateInstanceExportTask instance AWSRequest CreateInstanceExportTask where type Sv CreateInstanceExportTask = EC2 type Rs CreateInstanceExportTask = CreateInstanceExportTaskResponse request = post "CreateInstanceExportTask" response = xmlResponse instance FromXML CreateInstanceExportTaskResponse where parseXML x = CreateInstanceExportTaskResponse <$> x .@? "exportTask"
kim/amazonka
amazonka-ec2/gen/Network/AWS/EC2/CreateInstanceExportTask.hs
mpl-2.0
5,345
0
9
1,037
621
375
246
73
1
module Language.Haskell.GhcMod.PkgDoc (packageDoc) where import Language.Haskell.GhcMod.Types import Language.Haskell.GhcMod.GhcPkg import Control.Applicative ((<$>)) import System.Process (readProcess) -- | Obtaining the package name and the doc path of a module. packageDoc :: Options -> Cradle -> ModuleString -> IO String packageDoc _ cradle mdl = pkgDoc cradle mdl pkgDoc :: Cradle -> String -> IO String pkgDoc cradle mdl = do pkg <- trim <$> readProcess "ghc-pkg" toModuleOpts [] if pkg == "" then return "\n" else do htmlpath <- readProcess "ghc-pkg" (toDocDirOpts pkg) [] let ret = pkg ++ " " ++ drop 14 htmlpath return ret where toModuleOpts = ["find-module", mdl, "--simple-output"] ++ ghcPkgDbStackOpts (cradlePkgDbStack cradle) toDocDirOpts pkg = ["field", pkg, "haddock-html"] ++ ghcPkgDbStackOpts (cradlePkgDbStack cradle) trim = takeWhile (`notElem` " \n")
carlohamalainen/ghc-mod
Language/Haskell/GhcMod/PkgDoc.hs
bsd-3-clause
1,012
0
14
260
274
146
128
24
2
-- | -- Copyright: (C) 2014-2015 EURL Tweag {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative ((<$>)) import Network.Transport import Network.Transport.ZMQ import Network.Transport.Tests import Network.Transport.Tests.Auxiliary (runTests) main :: IO () main = testTransport' (Right <$> createTransport defaultZMQParameters "127.0.0.1") testTransport' :: IO (Either String Transport) -> IO () testTransport' newTransport = do Right transport <- newTransport runTests [ ("PingPong", testPingPong transport numPings) , ("EndPoints", testEndPoints transport numPings) , ("Connections", testConnections transport numPings) , ("CloseOneConnection", testCloseOneConnection transport numPings) , ("CloseOneDirection", testCloseOneDirection transport numPings) , ("CloseReopen", testCloseReopen transport numPings) , ("ParallelConnects", testParallelConnects transport 10) , ("SendAfterClose", testSendAfterClose transport 100) , ("Crossing", testCrossing transport 10) , ("CloseTwice", testCloseTwice transport 100) , ("ConnectToSelf", testConnectToSelf transport numPings) , ("ConnectToSelfTwice", testConnectToSelfTwice transport numPings) , ("CloseSelf", testCloseSelf newTransport) , ("CloseEndPoint", testCloseEndPoint transport numPings) , ("CloseTransport", testCloseTransport newTransport) , ("ExceptionOnReceive", testExceptionOnReceive newTransport) , ("SendException", testSendException newTransport) , ("Kill", testKill newTransport 80) -- testKill test have a timeconstraint so n-t-zmq -- fails to work with required speed, we need to -- reduce a number of tests here ] where numPings = 500 :: Int
tweag/network-transport-zeromq
tests/TestZMQ.hs
bsd-3-clause
1,973
0
10
515
384
219
165
32
1
-- | Temporary aspect pseudo-item definitions. module Content.ItemKindTemporary ( temporaries ) where import Data.Text (Text) import Game.LambdaHack.Common.Color import Game.LambdaHack.Common.Dice import Game.LambdaHack.Common.Flavour import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.Msg import Game.LambdaHack.Content.ItemKind temporaries :: [ItemKind] temporaries = [tmpStrengthened, tmpWeakened, tmpProtected, tmpVulnerable, tmpFast20, tmpSlow10, tmpFarSighted, tmpKeenSmelling, tmpDrunk, tmpRegenerating, tmpPoisoned, tmpSlow10Resistant, tmpPoisonResistant] tmpStrengthened, tmpWeakened, tmpProtected, tmpVulnerable, tmpFast20, tmpSlow10, tmpFarSighted, tmpKeenSmelling, tmpDrunk, tmpRegenerating, tmpPoisoned, tmpSlow10Resistant, tmpPoisonResistant :: ItemKind -- The @name@ is be used in item description, so it should be an adjective -- describing the temporary set of aspects. tmpAs :: Text -> [Aspect Dice] -> ItemKind tmpAs name aspects = ItemKind { isymbol = '+' , iname = name , ifreq = [(toGroupName name, 1), ("temporary conditions", 1)] , iflavour = zipPlain [BrWhite] , icount = 1 , irarity = [(1, 1)] , iverbHit = "affect" , iweight = 0 , iaspects = [Periodic, Timeout 0] -- activates and vanishes soon, -- depending on initial timer setting ++ aspects , ieffects = let tmp = Temporary $ "be no longer" <+> name in [Recharging tmp, OnSmash tmp] , ifeature = [Identified] , idesc = "" , ikit = [] } tmpStrengthened = tmpAs "strengthened" [AddHurtMelee 20] tmpWeakened = tmpAs "weakened" [AddHurtMelee (-20)] tmpProtected = tmpAs "protected" [ AddArmorMelee 30 , AddArmorRanged 30 ] tmpVulnerable = tmpAs "defenseless" [ AddArmorMelee (-30) , AddArmorRanged (-30) ] tmpFast20 = tmpAs "fast 20" [AddSpeed 20] tmpSlow10 = tmpAs "slow 10" [AddSpeed (-10)] tmpFarSighted = tmpAs "far-sighted" [AddSight 5] tmpKeenSmelling = tmpAs "keen-smelling" [AddSmell 2] tmpDrunk = tmpAs "drunk" [ AddHurtMelee 30 -- fury , AddArmorMelee (-20) , AddArmorRanged (-20) , AddSight (-7) ] tmpRegenerating = let tmp = tmpAs "regenerating" [] in tmp { icount = 7 + d 5 , ieffects = Recharging (RefillHP 1) : ieffects tmp } tmpPoisoned = let tmp = tmpAs "poisoned" [] in tmp { icount = 7 + d 5 , ieffects = Recharging (RefillHP (-1)) : ieffects tmp } tmpSlow10Resistant = let tmp = tmpAs "slow resistant" [] in tmp { icount = 7 + d 5 , ieffects = Recharging (DropItem COrgan "slow 10" True) : ieffects tmp } tmpPoisonResistant = let tmp = tmpAs "poison resistant" [] in tmp { icount = 7 + d 5 , ieffects = Recharging (DropItem COrgan "poisoned" True) : ieffects tmp }
beni55/LambdaHack
GameDefinition/Content/ItemKindTemporary.hs
bsd-3-clause
2,960
0
14
762
806
460
346
59
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE TypeSynonymInstances, FlexibleInstances, ScopedTypeVariables #-} -- provides Arbitrary instance for Pandoc types module Tests.Arbitrary () where import Test.QuickCheck.Gen import Test.QuickCheck.Arbitrary import Control.Monad (liftM, liftM2) import Text.Pandoc.Definition import Text.Pandoc.Shared (normalize, escapeURI) import Text.Pandoc.Builder realString :: Gen String realString = resize 8 $ listOf $ frequency [ (9, elements [' '..'\127']) , (1, elements ['\128'..'\9999']) ] arbAttr :: Gen Attr arbAttr = do id' <- elements ["","loc"] classes <- elements [[],["haskell"],["c","numberLines"]] keyvals <- elements [[],[("start","22")],[("a","11"),("b_2","a b c")]] return (id',classes,keyvals) instance Arbitrary Inlines where arbitrary = liftM (fromList :: [Inline] -> Inlines) arbitrary instance Arbitrary Blocks where arbitrary = liftM (fromList :: [Block] -> Blocks) arbitrary instance Arbitrary Inline where arbitrary = resize 3 $ arbInline 2 arbInlines :: Int -> Gen [Inline] arbInlines n = listOf1 (arbInline n) `suchThat` (not . startsWithSpace) where startsWithSpace (Space:_) = True startsWithSpace _ = False -- restrict to 3 levels of nesting max; otherwise we get -- bogged down in indefinitely large structures arbInline :: Int -> Gen Inline arbInline n = frequency $ [ (60, liftM Str realString) , (60, return Space) , (10, liftM2 Code arbAttr realString) , (5, elements [ RawInline (Format "html") "<a id=\"eek\">" , RawInline (Format "latex") "\\my{command}" ]) ] ++ [ x | x <- nesters, n > 1] where nesters = [ (10, liftM Emph $ arbInlines (n-1)) , (10, liftM Strong $ arbInlines (n-1)) , (10, liftM Strikeout $ arbInlines (n-1)) , (10, liftM Superscript $ arbInlines (n-1)) , (10, liftM Subscript $ arbInlines (n-1)) , (10, liftM SmallCaps $ arbInlines (n-1)) , (10, do x1 <- arbitrary x2 <- arbInlines (n-1) return $ Quoted x1 x2) , (10, do x1 <- arbitrary x2 <- realString return $ Math x1 x2) , (10, do x0 <- arbAttr x1 <- arbInlines (n-1) x3 <- realString x2 <- liftM escapeURI realString return $ Link x0 x1 (x2,x3)) , (10, do x0 <- arbAttr x1 <- arbInlines (n-1) x3 <- realString x2 <- liftM escapeURI realString return $ Image x0 x1 (x2,x3)) , (2, liftM2 Cite arbitrary (arbInlines 1)) , (2, liftM Note $ resize 3 $ listOf1 $ arbBlock (n-1)) ] instance Arbitrary Block where arbitrary = resize 3 $ arbBlock 2 arbBlock :: Int -> Gen Block arbBlock n = frequency $ [ (10, liftM Plain $ arbInlines (n-1)) , (15, liftM Para $ arbInlines (n-1)) , (5, liftM2 CodeBlock arbAttr realString) , (2, elements [ RawBlock (Format "html") "<div>\n*&amp;*\n</div>" , RawBlock (Format "latex") "\\begin[opt]{env}\nhi\n{\\end{env}" ]) , (5, do x1 <- choose (1 :: Int, 6) x2 <- arbInlines (n-1) return (Header x1 nullAttr x2)) , (2, return HorizontalRule) ] ++ [x | x <- nesters, n > 0] where nesters = [ (5, liftM BlockQuote $ listOf1 $ arbBlock (n-1)) , (5, do x2 <- arbitrary x3 <- arbitrary x1 <- arbitrary `suchThat` (> 0) x4 <- listOf1 $ listOf1 $ arbBlock (n-1) return $ OrderedList (x1,x2,x3) x4 ) , (5, liftM BulletList $ (listOf1 $ listOf1 $ arbBlock (n-1))) , (5, do items <- listOf1 $ do x1 <- listOf1 $ listOf1 $ arbBlock (n-1) x2 <- arbInlines (n-1) return (x2,x1) return $ DefinitionList items) , (2, do rs <- choose (1 :: Int, 4) cs <- choose (1 :: Int, 4) x1 <- arbInlines (n-1) x2 <- vector cs x3 <- vectorOf cs $ elements [0, 0.25] x4 <- vectorOf cs $ listOf $ arbBlock (n-1) x5 <- vectorOf rs $ vectorOf cs $ listOf $ arbBlock (n-1) return (Table x1 x2 x3 x4 x5)) ] instance Arbitrary Pandoc where arbitrary = resize 8 $ liftM normalize $ liftM2 Pandoc arbitrary arbitrary instance Arbitrary CitationMode where arbitrary = do x <- choose (0 :: Int, 2) case x of 0 -> return AuthorInText 1 -> return SuppressAuthor 2 -> return NormalCitation _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary Citation where arbitrary = do x1 <- listOf $ elements $ ['a'..'z'] ++ ['0'..'9'] ++ ['_'] x2 <- arbInlines 1 x3 <- arbInlines 1 x4 <- arbitrary x5 <- arbitrary x6 <- arbitrary return (Citation x1 x2 x3 x4 x5 x6) instance Arbitrary MathType where arbitrary = do x <- choose (0 :: Int, 1) case x of 0 -> return DisplayMath 1 -> return InlineMath _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary QuoteType where arbitrary = do x <- choose (0 :: Int, 1) case x of 0 -> return SingleQuote 1 -> return DoubleQuote _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary Meta where arbitrary = do (x1 :: Inlines) <- arbitrary (x2 :: [Inlines]) <- liftM (filter (not . isNull)) arbitrary (x3 :: Inlines) <- arbitrary return $ setMeta "title" x1 $ setMeta "author" x2 $ setMeta "date" x3 $ nullMeta instance Arbitrary Alignment where arbitrary = do x <- choose (0 :: Int, 3) case x of 0 -> return AlignLeft 1 -> return AlignRight 2 -> return AlignCenter 3 -> return AlignDefault _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary ListNumberStyle where arbitrary = do x <- choose (0 :: Int, 6) case x of 0 -> return DefaultStyle 1 -> return Example 2 -> return Decimal 3 -> return LowerRoman 4 -> return UpperRoman 5 -> return LowerAlpha 6 -> return UpperAlpha _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary ListNumberDelim where arbitrary = do x <- choose (0 :: Int, 3) case x of 0 -> return DefaultDelim 1 -> return Period 2 -> return OneParen 3 -> return TwoParens _ -> error "FATAL ERROR: Arbitrary instance, logic bug"
janschulz/pandoc
tests/Tests/Arbitrary.hs
gpl-2.0
8,350
0
19
3,770
2,393
1,223
1,170
168
2
{-# LANGUAGE LambdaCase, RankNTypes, ScopedTypeVariables #-} module Stream.Folding.ByteString where import Stream.Types import Stream.Folding.Prelude hiding (fromHandle) import Control.Monad hiding (filterM, mapM) import Data.Functor.Identity import Control.Monad.Trans import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.ByteString.Lazy.Internal (foldrChunks, defaultChunkSize) import Data.ByteString (ByteString) import qualified System.IO as IO import Prelude hiding (map, filter, drop, take, sum , iterate, repeat, replicate, splitAt , takeWhile, enumFrom, enumFromTo) import Foreign.C.Error (Errno(Errno), ePIPE) import qualified GHC.IO.Exception as G import Control.Exception (throwIO, try) import Data.Word fromLazy bs = Folding (\construct wrap done -> foldrChunks (kurry construct) (done ()) bs) stdinLn :: Folding (Of ByteString) IO () stdinLn = fromHandleLn IO.stdin {-# INLINABLE stdinLn #-} fromHandleLn :: IO.Handle -> Folding (Of ByteString) IO () fromHandleLn h = Folding $ \construct wrap done -> wrap $ let go = do eof <- IO.hIsEOF h if eof then return (done ()) else do bs <- B.hGetLine h return (construct (bs :> wrap go)) in go {-# INLINABLE fromHandleLn #-} stdin :: Folding (Of ByteString) IO () stdin = fromHandle IO.stdin fromHandle :: IO.Handle -> Folding (Of ByteString) IO () fromHandle = hGetSome defaultChunkSize {-# INLINABLE fromHandle #-} hGetSome :: Int -> IO.Handle -> Folding (Of ByteString) IO () hGetSome size h = Folding $ \construct wrap done -> let go = do bs <- B.hGetSome h size if B.null bs then return (done ()) else liftM (construct . (bs :>)) go in wrap go {-# INLINABLE hGetSome #-} hGet :: Int -> IO.Handle -> Folding (Of ByteString) IO () hGet size h = Folding $ \construct wrap done -> let go = do bs <- B.hGet h size if B.null bs then return (done ()) else liftM (construct . (bs :>)) go in wrap go {-# INLINABLE hGet #-} stdout :: MonadIO m => Folding (Of ByteString) m () -> m () stdout (Folding phi) = phi (\(bs :> rest) -> do x <- liftIO (try (B.putStr bs)) case x of Left (G.IOError { G.ioe_type = G.ResourceVanished , G.ioe_errno = Just ioe }) | Errno ioe == ePIPE -> return () Left e -> liftIO (throwIO e) Right () -> rest) join (\_ -> return ()) {-# INLINABLE stdout #-} toHandle :: MonadIO m => IO.Handle -> Folding (Of ByteString) m () -> m () toHandle h (Folding phi) = phi (\(bs :> rest) -> liftIO (B.hPut h bs) >> rest) join (\_ -> return ()) {-# INLINE toHandle #-} -- span -- :: Monad m -- => (Word8 -> Bool) -- -> Lens' (Producer ByteString m x) -- (Producer ByteString m (Producer ByteString m x)) -- span_ :: Monad m -- => Folding_ (Of ByteString) m r -- -> (Word8 -> Bool) -- -- span_ :: Folding_ (Of ByteString) m r -- -- -> (Word8 -> Bool) -- -> (Of ByteString r' -> r') -- -> (m r' -> r') -- -> (Folding (Of ByteString) m r -> r') -- -> r' -- -- span_ :: Monad m -- => Folding (Of ByteString) m r -- -> (Word8 -> Bool) -> Folding (Of ByteString) m (Folding (Of ByteString) m r) -- ------------------------ -- span_ (Folding phi) p = Folding $ \construct wrap done -> -- getFolding (phi -- (\(bs :> rest) -> undefined) -- (\mf -> undefined) -- (\r c w d -> getFolding r c w d)) -- construct wrap done -- ------------------------ -- (\(bs :> Folding rest) -> Folding $ \c w d -> -- let (prefix, suffix) = B.span p bs -- in if B.null suffix -- then getFolding (rest c w d ) -- else c (prefix :> d rest) -- (\mpsi -> Folding $ \c w d -> -- w $ mpsi >>= \(Folding psi) -> return (psi c w d)) -- (\r -> Folding $ \c w d -> getFolding (d r)) -- -- Folding $ \c w d -> wrap $ mpsi >>= \(Folding psi) -> return (psi c w d) -- where -- go p = do -- x <- lift (next p) -- case x of -- Left r -> return (return r) -- Right (bs, p') -> do -- let (prefix, suffix) = BS.span predicate bs -- if (BS.null suffix) -- then do -- yield bs -- go p' -- else do -- yield prefix -- return (yield suffix >> p') -- # INLINABLE span #-} -- break predicate = span (not . predicate) -- -- nl :: Word8 -- nl = fromIntegral (ord '\n') -- -- _lines -- :: Monad m => Producer ByteString m x -> FreeT (Producer ByteString m) m x -- _lines p0 = PG.FreeT (go0 p0) -- where -- go0 p = do -- x <- next p -- case x of -- Left r -> return (PG.Pure r) -- Right (bs, p') -> -- if (BS.null bs) -- then go0 p' -- else return $ PG.Free $ go1 (yield bs >> p') -- go1 p = do -- p' <- p^.line -- return $ PG.FreeT $ do -- x <- nextByte p' -- case x of -- Left r -> return (PG.Pure r) -- Right (_, p'') -> go0 p'' -- {-# INLINABLE _lines #-} -- -- _unlines -- :: Monad m => FreeT (Producer ByteString m) m x -> Producer ByteString m x -- _unlines = concats . PG.maps addNewline -- where -- addNewline p = p <* yield (BS.singleton nl) -- {-# INLINABLE _unlines # -- -- splitAt :: (Monad m) => Int -> Folding (Of ByteString) m r -> Folding (Of ByteString) m (Folding (Of ByteString) m r) splitAt n0 (Folding phi) = phi (\(bs :> nfold) n -> let len = fromIntegral (B.length bs) rest = joinFold (nfold (n-len)) in if n > 0 then if n > len then Folding $ \construct wrap done -> construct $ bs :> getFolding (nfold (n-len)) construct wrap done else let (prefix, suffix) = B.splitAt (fromIntegral n) bs in Folding $ \construct wrap done -> construct $ if B.null suffix then prefix :> done rest else prefix :> done (cons suffix rest) else Folding $ \construct wrap done -> done $ bs `cons` rest ) (\m n -> Folding $ \construct wrap done -> wrap $ liftM (\f -> getFolding (f n) construct wrap done) m ) (\r n -> Folding $ \construct wrap done -> done $ Folding $ \c w d -> d r ) n0
haskell-streaming/streaming
benchmarks/old/Stream/Folding/ByteString.hs
bsd-3-clause
7,155
0
22
2,670
1,527
841
686
90
4
module A where ~(Just x) = Nothing
forste/haReFork
tools/base/transforms/tests/1.hs
bsd-3-clause
37
0
7
9
17
9
8
2
1
module IfThenElseIn1 where -- refactorer should give an error! f x@(y:ys) = if x == [] then error "Error!" else y
kmate/HaRe
old/testing/simplifyExpr/IfThenElseIn1_TokOut.hs
bsd-3-clause
143
0
8
50
40
23
17
3
2
module P2 where
urbanslug/ghc
testsuite/tests/cabal/cabal05/p/P2.hs
bsd-3-clause
16
0
2
3
4
3
1
1
0