code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module BLeague.Models.User where import MyPrelude hiding (get, getAll) import Data.Aeson (FromJSON, ToJSON (..), Value (..), toJSON) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.List (group, sort, sortBy) import qualified Data.Map as M import Data.Pool import Data.Text (Text, unpack) import Data.Time import Prelude hiding (id) import Safe (headMay) import BLeague.Crud import BLeague.Types import qualified Database.RethinkDB as R import Database.RethinkDB.NoClash hiding (Change, Null, Object, group, status, table, toJSON) import GHC.Generics --------------------------- User API ----------------------------- data User = User { id :: Text , username :: Text , hashedPassword :: Text , admin :: Bool , created :: UTCTime } deriving (Show, Eq, Generic) newtype SecureUser = SecureUser User deriving (Show, Generic) instance ToJSON SecureUser where toJSON (SecureUser user) = Object $ foldr HashMap.delete obj ["hashedPassword"] where (Object obj) = toJSON user instance FromJSON User instance ToJSON User instance FromDatum User instance ToDatum User userTable = R.table "users" listUser :: App [User] listUser = runDb $ userTable # orderBy [asc "id"] find :: Text -> App (Maybe User) find id = runDb $ userTable # get (expr id) findByUsername :: Text -> App (Maybe User) findByUsername u = do us <- runDb $ userTable # getAll usernameIndex [expr u] return $ headMay us save :: Text -> User -> App () save = docsSave userTable remove :: Text -> App () remove id = runDb $ userTable # get (expr id) # delete secure :: (Functor m) => m User -> m SecureUser secure = fmap SecureUser insert :: User -> App User insert u = do r <- runDb $ userTable # create u let user = u { id = generatedKey r} return user usernameIndexName = "username" usernameIndex = Index usernameIndexName init :: App () init = do initDb $ runDb $ tableCreate userTable initDb $ runDb $ userTable # indexCreate usernameIndexName (!expr usernameIndexName)
ardfard/bleague
server/BLeague/Models/User.hs
bsd-3-clause
2,460
0
12
729
724
393
331
62
1
{-# LANGUAGE OverloadedStrings #-} module Cauterize.Dynamic.Unpack ( dynamicUnpack , dynamicUnpack' ) where import Cauterize.Dynamic.Types import Cauterize.Dynamic.Common import Control.Exception import Control.Monad import Data.Bits import qualified Data.Map as M import qualified Data.Text.Lazy as T import qualified Cauterize.Specification as S import qualified Cauterize.Common.Types as C import qualified Data.ByteString as B import Data.Serialize.IEEE754 import Data.Serialize.Get dynamicUnpack :: S.Spec -> T.Text -> B.ByteString -> Either T.Text CautType dynamicUnpack s n b = case flip runGet b $ dynamicUnpack' s n of Left e -> Left $ T.pack e Right r -> Right r dynamicUnpack' :: S.Spec -> T.Text -> Get CautType dynamicUnpack' s n = let m = S.specTypeMap s in do d <- dynamicUnpackDetails m n return CautType { ctName = n, ctDetails = d } dynamicUnpackDetails :: TyMap -> T.Text -> Get CautDetails dynamicUnpackDetails m n = let t = n `lu` m in case t of S.BuiltIn { S.unBuiltIn = b } -> dynamicUnpackBuiltIn m b S.Synonym { S.unSynonym = s } -> dynamicUnpackSynonym m s S.Array { S.unArray = a } -> dynamicUnpackArray m a S.Vector { S.unVector = v, S.lenRepr = lr } -> dynamicUnpackVector m v lr S.Record { S.unRecord = r } -> dynamicUnpackRecord m r S.Combination { S.unCombination = c, S.flagsRepr = fr } -> dynamicUnpackCombination m c fr S.Union { S.unUnion = u, S.tagRepr = tr } -> dynamicUnpackUnion m u tr dynamicUnpackBuiltIn :: TyMap -> C.TBuiltIn -> Get CautDetails dynamicUnpackBuiltIn _ (C.TBuiltIn b) = liftM CDBuiltIn (unpackBuiltIn b) dynamicUnpackSynonym :: TyMap -> C.TSynonym -> Get CautDetails dynamicUnpackSynonym _ (C.TSynonym { C.synonymRepr = r }) = liftM CDSynonym (unpackBuiltIn r) dynamicUnpackArray :: TyMap -> C.TArray -> Get CautDetails dynamicUnpackArray m (C.TArray { C.arrayRef = r, C.arrayLen = l }) = liftM CDArray $ replicateM (fromIntegral l) getter where getter = dynamicUnpackDetails m r dynamicUnpackVector :: TyMap -> C.TVector -> S.LengthRepr -> Get CautDetails dynamicUnpackVector m (C.TVector { C.vectorRef = r, C.vectorMaxLen = maxLen }) (S.LengthRepr lr) = do len <- unpackTag lr if len > maxLen then fail $ "vector length out of bounds: " ++ show len ++ " > " ++ show maxLen else liftM CDVector $ replicateM (fromIntegral len) getter where getter = dynamicUnpackDetails m r dynamicUnpackRecord :: TyMap -> C.TRecord -> Get CautDetails dynamicUnpackRecord m (C.TRecord { C.recordFields = C.Fields { C.unFields = fs } }) = liftM (CDRecord . M.fromList) $ mapM (unpackField m) fs dynamicUnpackCombination :: TyMap -> C.TCombination -> S.FlagsRepr -> Get CautDetails dynamicUnpackCombination m (C.TCombination { C.combinationFields = C.Fields { C.unFields = fs } }) (S.FlagsRepr fr) = do flags <- unpackTag fr liftM (CDCombination . M.fromList) $ mapM (unpackField m) (setFields flags) where setFields flags = filter (\f -> flags `testBit` (fromIntegral . C.fIndex $ f)) fs dynamicUnpackUnion :: TyMap -> C.TUnion -> S.TagRepr -> Get CautDetails dynamicUnpackUnion m (C.TUnion { C.unionFields = C.Fields { C.unFields = fs } }) (S.TagRepr { S.unTagRepr = tr } ) = do tag <- liftM fromIntegral $ unpackTag tr case tag `M.lookup` fm of Nothing -> fail $ "invalid union tag: " ++ show tag Just f -> do (n, d) <- unpackField m f return CDUnion { cdUnionFieldName = n, cdUnionFieldDetails = d } where fm = fieldsToIndexMap fs unpackField :: TyMap -> C.Field -> Get (T.Text, FieldValue) unpackField _ (C.EmptyField { C.fName = n }) = return (n, EmptyField) unpackField m (C.Field { C.fName = n, C.fRef = r }) = liftM (\d -> (n, DataField d)) (dynamicUnpackDetails m r) unpackBuiltIn :: C.BuiltIn -> Get BIDetails unpackBuiltIn b = case b of C.BIu8 -> liftM BDu8 getWord8 C.BIu16 -> liftM BDu16 getWord16le C.BIu32 -> liftM BDu32 getWord32le C.BIu64 -> liftM BDu64 getWord64le C.BIs8 -> liftM (BDs8 . fromIntegral) getWord8 C.BIs16 -> liftM (BDs16 . fromIntegral) getWord16le C.BIs32 -> liftM (BDs32 . fromIntegral) getWord32le C.BIs64 -> liftM (BDs64 . fromIntegral) getWord64le C.BIf32 -> liftM BDf32 getFloat32le C.BIf64 -> liftM BDf64 getFloat64le C.BIbool -> do w8 <- getWord8 case w8 of 0 -> return $ BDbool False 1 -> return $ BDbool True x -> fail $ "unexpected value for boolean: " ++ show x unpackTag :: C.BuiltIn -> Get Integer unpackTag C.BIu8 = liftM fromIntegral getWord8 unpackTag C.BIu16 = liftM fromIntegral getWord16le unpackTag C.BIu32 = liftM fromIntegral getWord32le unpackTag C.BIu64 = liftM fromIntegral getWord64le unpackTag b = throw $ NotATagType (T.pack . show $ b)
reiddraper/cauterize
src/Cauterize/Dynamic/Unpack.hs
bsd-3-clause
4,820
0
14
996
1,749
896
853
97
13
{-# LANGUAGE OverloadedStrings #-} module Gvty.Serialization where import Control.Applicative import Control.Monad.State import Data.Aeson import Data.Aeson.Types (Parser) import Data.Vect.Float import Data.Vector as V import Gvty.World instance FromJSON Vec2 where parseJSON (Array x) = do [a, b] <- toList <$> V.mapM (parseJSON :: Value -> Parser Float) x return $ mkVec2 (a, b) instance FromJSON Obj where parseJSON (Object x) = Obj <$> x .: "position" <*> x .: "velocity" instance FromJSON Planet where parseJSON (Object x) = Planet <$> x .: "position" <*> x .: "mass" <*> x .: "radius" instance FromJSON Anomaly where parseJSON (Object x) = Anomaly <$> x .: "position" <*> x .: "radius" instance FromJSON World where parseJSON (Object x) = World <$> x .:? "time" .!= 0 <*> x .:? "size" .!= (800, 800) <*> x .:? "objects" .!= [] <*> x .: "planets" <*> x .: "anomalies" <*> x .:? "new_obj_coords" .!= Nothing <*> x .:? "new_obj_preview_coords" .!= Nothing
coffeecup-winner/gvty
Gvty/Serialization.hs
bsd-3-clause
1,372
0
24
567
355
187
168
31
0
module Sols.Prob7 ( solution ) where import Common.Primes (primes) solution = print (primes !! 10000)
authentik8/haskell-euler
src/Sols/Prob7.hs
bsd-3-clause
110
0
7
23
36
21
15
4
1
-- | Module that uses "Process.MapReduce.Multicore" to implement -- the standard Mapreduce wordcount algorithm. module Parallel.MapReduce.WordCount ( mapReduce ) where --import Parallel.MapReduce.Multicore import Parallel.MapReduce (run,distribute,lift,(>>=)) import Prelude hiding (return,(>>=)) -- | Perform MapReduce on a list of words, returning word / count pairs mapReduce :: Int -- ^ The number of mappers to use on the first stage -> [String] -- ^ The list of words to count -> [(String,Int)] -- ^ The list of word / count pairs mapReduce n state = run mr state where mr = distribute n >>= lift mapper >>= lift reducer -- transformers mapper :: [String] -> [(String,String)] mapper [] = [] mapper (x:xs) = parse x ++ mapper xs where parse x = map (\w -> (w,w)) $ words x reducer :: [String] -> [(String,Int)] reducer [] = [] reducer xs = [(head xs,length xs)]
Julianporter/Haskell-MapReduce
src/Parallel/MapReduce/WordCount.hs
bsd-3-clause
976
0
11
250
267
153
114
16
1
module PostgREST.Parsers -- ( parseGetRequest -- ) where import Control.Applicative hiding ((<$>)) import Data.Monoid import Data.String.Conversions (cs) import Data.Text (Text) import Data.Tree import PostgREST.Types import Text.ParserCombinators.Parsec hiding (many, (<|>)) import PostgREST.QueryBuilder (operators) pRequestSelect :: Text -> Parser ReadRequest pRequestSelect rootNodeName = do fieldTree <- pFieldForest return $ foldr treeEntry (Node (Select [] [rootNodeName] [] Nothing, (rootNodeName, Nothing)) []) fieldTree where treeEntry :: Tree SelectItem -> ReadRequest -> ReadRequest treeEntry (Node fld@((fn, _),_) fldForest) (Node (q, i) rForest) = case fldForest of [] -> Node (q {select=fld:select q}, i) rForest _ -> Node (q, i) (foldr treeEntry (Node (Select [] [fn] [] Nothing, (fn, Nothing)) []) fldForest:rForest) pRequestFilter :: (String, String) -> Either ParseError (Path, Filter) pRequestFilter (k, v) = (,) <$> path <*> (Filter <$> fld <*> op <*> val) where treePath = parse pTreePath ("failed to parser tree path (" ++ k ++ ")") k opVal = parse pOpValueExp ("failed to parse filter (" ++ v ++ ")") v path = fst <$> treePath fld = snd <$> treePath op = fst <$> opVal val = snd <$> opVal ws :: Parser Text ws = cs <$> many (oneOf " \t") lexeme :: Parser a -> Parser a lexeme p = ws *> p <* ws pTreePath :: Parser (Path,Field) pTreePath = do p <- pFieldName `sepBy1` pDelimiter jp <- optionMaybe pJsonPath let pp = map cs p jpp = map cs <$> jp return (init pp, (last pp, jpp)) pFieldForest :: Parser [Tree SelectItem] pFieldForest = pFieldTree `sepBy1` lexeme (char ',') pFieldTree :: Parser (Tree SelectItem) pFieldTree = try (Node <$> pSelect <*> between (char '{') (char '}') pFieldForest) <|> Node <$> pSelect <*> pure [] pStar :: Parser Text pStar = cs <$> (string "*" *> pure ("*"::String)) pFieldName :: Parser Text pFieldName = cs <$> (many1 (letter <|> digit <|> oneOf "_") <?> "field name (* or [a..z0..9_])") pJsonPathStep :: Parser Text pJsonPathStep = cs <$> try (string "->" *> pFieldName) pJsonPath :: Parser [Text] pJsonPath = (++) <$> many pJsonPathStep <*> ( (:[]) <$> (string "->>" *> pFieldName) ) pField :: Parser Field pField = lexeme $ (,) <$> pFieldName <*> optionMaybe pJsonPath pSelect :: Parser SelectItem pSelect = lexeme $ try ((,) <$> pField <*>((cs <$>) <$> optionMaybe (string "::" *> many letter)) ) <|> do s <- pStar return ((s, Nothing), Nothing) pOperator :: Parser Operator pOperator = cs <$> (pOp <?> "operator (eq, gt, ...)") where pOp = foldl (<|>) empty $ map (try . string . cs . fst) operators pValue :: Parser FValue pValue = VText <$> (cs <$> many anyChar) pDelimiter :: Parser Char pDelimiter = char '.' <?> "delimiter (.)" pOperatiorWithNegation :: Parser Operator pOperatiorWithNegation = try ( (<>) <$> ( cs <$> string "not." ) <*> pOperator) <|> pOperator pOpValueExp :: Parser (Operator, FValue) pOpValueExp = (,) <$> pOperatiorWithNegation <*> (pDelimiter *> pValue) pOrder :: Parser [OrderTerm] pOrder = lexeme pOrderTerm `sepBy` char ',' pOrderTerm :: Parser OrderTerm pOrderTerm = try ( do c <- pFieldName _ <- pDelimiter d <- (string "asc" *> pure OrderAsc) <|> (string "desc" *> pure OrderDesc) nls <- optionMaybe (pDelimiter *> ( try(string "nullslast" *> pure OrderNullsLast) <|> try(string "nullsfirst" *> pure OrderNullsFirst) )) return $ OrderTerm c d nls ) <|> OrderTerm <$> (cs <$> pFieldName) <*> pure OrderAsc <*> pure Nothing
motiz88/postgrest
src/PostgREST/Parsers.hs
mit
3,737
0
22
872
1,403
738
665
84
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Dampf.ConfigFile.Types ( -- * Configuration Types DampfProfiles(..) , HasDampfProfiles(..) , DampfConfig(..) , HasDampfConfig(..) , PostgresConfig(..) , HasPostgresConfig(..) ) where import Control.Lens import Control.Monad (forM) import Data.Aeson import qualified Data.HashMap.Lazy as HM import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Text (Text) import qualified Data.Text as T import GHC.Generics import Dampf.Internal.Yaml -- Configuration Types data PostgresConfig = PostgresConfig { _host :: Text , _port :: Int , _users :: Map Text Text } deriving (Eq, Show, Generic) makeClassy ''PostgresConfig instance FromJSON PostgresConfig where parseJSON = gDecode data DampfConfig = DC { _postgres :: Maybe PostgresConfig } deriving (Eq, Show, Generic) makeClassy ''DampfConfig instance FromJSON DampfConfig where parseJSON = gDecode data DampfProfiles = DP { _profiles :: Map Text DampfConfig } deriving (Eq, Show, Generic) makeClassy ''DampfProfiles instance FromJSON DampfProfiles where parseJSON = withObject "Configuration File" $ \o -> fmap (DP . Map.fromList) $ forM (HM.toList o) $ \(k, v) -> case T.words k of ["profile", name] -> (,) <$> return name <*> parseJSON v _ -> fail "Invalid profile specification"
diffusionkinetics/open
dampf/lib/Dampf/ConfigFile/Types.hs
mit
1,673
0
15
475
414
239
175
46
0
{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} module Yi.Process (runProgCommand, runShellCommand, shellFileName, createSubprocess, readAvailable, SubprocessInfo(..), SubprocessId) where import Control.Exc (orException) import qualified Data.ListLike as L (empty) import Foreign.C.String (peekCStringLen) import Foreign.Marshal.Alloc (allocaBytes) import System.Directory (findExecutable) import System.Environment (getEnv) import System.Exit (ExitCode (ExitFailure)) import System.IO (BufferMode (NoBuffering), Handle, hSetBuffering, hGetBufNonBlocking) import System.Process (ProcessHandle, runProcess) import System.Process.ListLike (ListLikeProcessIO, readProcessWithExitCode) import Yi.Buffer.Basic (BufferRef) import Yi.Monad (repeatUntilM) #ifndef mingw32_HOST_OS import System.Posix.IO (createPipe, fdToHandle) #endif runProgCommand :: ListLikeProcessIO a c => String -> [String] -> IO (ExitCode, a, a) runProgCommand prog args = do loc <- findExecutable prog case loc of Nothing -> return (ExitFailure 1, L.empty, L.empty) Just fp -> readProcessWithExitCode fp args L.empty ------------------------------------------------------------------------ -- | Run a command using the system shell, returning stdout, stderr and exit code shellFileName :: IO String shellFileName = orException (getEnv "SHELL") (return "/bin/sh") shellCommandSwitch :: String shellCommandSwitch = "-c" runShellCommand :: ListLikeProcessIO a c => String -> IO (ExitCode, a, a) runShellCommand cmd = do sh <- shellFileName readProcessWithExitCode sh [shellCommandSwitch, cmd] L.empty -------------------------------------------------------------------------------- -- Subprocess support (ie. async processes whose output goes to a buffer) type SubprocessId = Integer data SubprocessInfo = SubprocessInfo { procCmd :: FilePath, procArgs :: [String], procHandle :: ProcessHandle, hIn :: Handle, hOut :: Handle, hErr :: Handle, bufRef :: BufferRef, separateStdErr :: Bool } {- Simon Marlow said this: It turns out to be dead easy to bind stderr and stdout to the same pipe. After a couple of minor tweaks the following now works: createProcess (proc cmd args){ std_out = CreatePipe, std_err = UseHandle stdout } Therefore it should be possible to simplifiy the following greatly with the new process package. -} createSubprocess :: FilePath -> [String] -> BufferRef -> IO SubprocessInfo createSubprocess cmd args bufref = do #ifdef mingw32_HOST_OS (inp,out,err,handle) <- runInteractiveProcess cmd args Nothing Nothing let separate = True #else (inpReadFd,inpWriteFd) <- System.Posix.IO.createPipe (outReadFd,outWriteFd) <- System.Posix.IO.createPipe [inpRead,inpWrite,outRead,outWrite] <- mapM fdToHandle [inpReadFd,inpWriteFd,outReadFd,outWriteFd] handle <- runProcess cmd args Nothing Nothing (Just inpRead) (Just outWrite) (Just outWrite) let inp = inpWrite out = outRead err = outRead separate = False #endif hSetBuffering inp NoBuffering hSetBuffering out NoBuffering hSetBuffering err NoBuffering return SubprocessInfo { procCmd=cmd, procArgs=args, procHandle=handle, hIn=inp, hOut=out, hErr=err, bufRef=bufref, separateStdErr=separate } -- Read as much as possible from handle without blocking readAvailable :: Handle -> IO String readAvailable handle = fmap concat $ repeatUntilM $ readChunk handle -- Read a chunk from a handle, bool indicates if there is potentially more data available readChunk :: Handle -> IO (Bool, String) readChunk handle = do let bufferSize = 1024 allocaBytes bufferSize $ \buffer -> do bytesRead <- hGetBufNonBlocking handle buffer bufferSize s <- peekCStringLen (buffer,bytesRead) let mightHaveMore = bytesRead == bufferSize return (mightHaveMore, s)
siddhanathan/yi
yi-core/src/Yi/Process.hs
gpl-2.0
4,282
0
14
1,051
778
437
341
64
2
{-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PackageImports #-} {- Copyright 2016 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 Internal.Color where import qualified "codeworld-api" CodeWorld as CW import Internal.Num import Internal.Truth import qualified "base" Prelude as P import "base" Prelude ((.)) newtype Color = RGBA(Number, Number, Number, Number) deriving P.Eq type Colour = Color {-# RULES "equality/color" forall (x :: Color). (==) x = (P.==) x #-} toCWColor :: Color -> CW.Color toCWColor (RGBA (r,g,b,a)) = CW.RGBA (toDouble r) (toDouble g) (toDouble b) (toDouble a) fromCWColor :: CW.Color -> Color fromCWColor (CW.RGBA r g b a) = RGBA (fromDouble r, fromDouble g, fromDouble b, fromDouble a) white, black :: Color white = fromCWColor CW.white black = fromCWColor CW.black -- Primary and secondary colors red, green, blue, cyan, magenta, yellow :: Color red = fromCWColor CW.red yellow = fromCWColor CW.yellow green = fromCWColor CW.green cyan = fromCWColor CW.cyan blue = fromCWColor CW.blue magenta = fromCWColor CW.magenta -- Tertiary colors orange, rose, chartreuse, aquamarine, violet, azure :: Color orange = fromCWColor CW.orange chartreuse = fromCWColor CW.chartreuse aquamarine = fromCWColor CW.aquamarine azure = fromCWColor CW.azure violet = fromCWColor CW.violet rose = fromCWColor CW.rose -- Other common colors and color names brown = fromCWColor CW.brown purple = fromCWColor CW.purple pink = fromCWColor CW.pink mixed :: (Color, Color) -> Color mixed (a, b) = fromCWColor (CW.mixed (toCWColor a) (toCWColor b)) lighter :: (Color, Number) -> Color lighter (c, d) = fromCWColor (CW.lighter (toDouble d) (toCWColor c)) light :: Color -> Color light = fromCWColor . CW.light . toCWColor darker :: (Color, Number) -> Color darker (c, d) = fromCWColor (CW.darker (toDouble d) (toCWColor c)) dark :: Color -> Color dark = fromCWColor . CW.dark . toCWColor brighter :: (Color, Number) -> Color brighter (c, d) = fromCWColor (CW.brighter (toDouble d) (toCWColor c)) bright :: Color -> Color bright = fromCWColor . CW.bright . toCWColor duller :: (Color, Number) -> Color duller (c, d) = fromCWColor (CW.duller (toDouble d) (toCWColor c)) dull :: Color -> Color dull = fromCWColor . CW.dull . toCWColor translucent :: Color -> Color translucent = fromCWColor . CW.translucent . toCWColor gray, grey :: Number -> Color gray = fromCWColor . CW.gray . toDouble grey = gray hue, saturation, luminosity :: Color -> Number hue = (180 *) . (/ pi) . fromDouble . CW.hue . toCWColor saturation = fromDouble . CW.saturation . toCWColor luminosity = fromDouble . CW.luminosity . toCWColor fromHSL :: (Number, Number, Number) -> Color fromHSL (h, s, l) = fromCWColor (CW.fromHSL (toDouble (pi * h / 180)) (toDouble s) (toDouble l))
nomeata/codeworld
codeworld-base/src/Internal/Color.hs
apache-2.0
3,513
0
12
713
993
556
437
67
1
----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 2006 -- -- The purpose of this module is to transform an HsExpr into a CoreExpr which -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the -- input HsExpr. We do this in the DsM monad, which supplies access to -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype. -- -- It also defines a bunch of knownKeyNames, in the same way as is done -- in prelude/PrelNames. It's much more convenient to do it here, because -- otherwise we have to recompile PrelNames whenever we add a Name, which is -- a Royal Pain (triggers other recompilation). ----------------------------------------------------------------------------- --TODO: Implement Template Haskell module ETA.DeSugar.DsMeta where -- module ETA.DeSugar.DsMeta( dsBracket, -- templateHaskellNames, qTyConName, nameTyConName, -- liftName, liftStringName, expQTyConName, patQTyConName, -- decQTyConName, decsQTyConName, typeQTyConName, -- decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName, -- quoteExpName, quotePatName, quoteDecName, quoteTypeName, -- tExpTyConName, tExpDataConName, unTypeName, unTypeQName, -- unsafeTExpCoerceName -- ) where -- import {-# SOURCE #-} ETA.DeSugar.DsExpr ( dsExpr ) -- import ETA.DeSugar.MatchLit -- import ETA.DeSugar.DsMonad -- import qualified Language.Haskell.TH as TH -- import ETA.HsSyn.HsSyn -- import ETA.Types.Class -- import ETA.Prelude.PrelNames -- -- To avoid clashes with DsMeta.varName we must make a local alias for -- -- OccName.varName we do this by removing varName from the import of -- -- OccName above, making a qualified instance of OccName and using -- -- OccNameAlias.varName where varName ws previously used in this file. -- import qualified ETA.BasicTypes.OccName as OccName( isDataOcc, isVarOcc, isTcOcc, varName, tcName, dataName ) -- import ETA.BasicTypes.Module -- import ETA.BasicTypes.Id -- import ETA.BasicTypes.Name hiding( isVarOcc, isTcOcc, varName, tcName ) -- import ETA.BasicTypes.NameEnv -- import ETA.TypeCheck.TcType -- import ETA.Types.TyCon -- import ETA.Prelude.TysWiredIn -- import ETA.Prelude.TysPrim ( liftedTypeKindTyConName, constraintKindTyConName ) -- import ETA.Core.CoreSyn -- import ETA.Core.MkCore -- import ETA.Core.CoreUtils -- import ETA.BasicTypes.SrcLoc -- import ETA.BasicTypes.Unique -- import ETA.BasicTypes.BasicTypes -- import ETA.Utils.Outputable -- import ETA.Utils.Bag -- import ETA.Main.DynFlags -- import ETA.Utils.FastString -- import ETA.Prelude.ForeignCall -- import ETA.Utils.Util -- import ETA.Utils.MonadUtils -- import Data.Maybe -- import Control.Monad -- import Data.List -- ----------------------------------------------------------------------------- -- dsBracket :: HsBracket Name -> [PendingTcSplice] -> DsM CoreExpr -- -- Returns a CoreExpr of type TH.ExpQ -- -- The quoted thing is parameterised over Name, even though it has -- -- been type checked. We don't want all those type decorations! -- dsBracket brack splices -- = dsExtendMetaEnv new_bit (do_brack brack) -- where -- new_bit = mkNameEnv [(n, DsSplice (unLoc e)) | PendSplice n e <- splices] -- do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 } -- do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 } -- do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 } -- do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 } -- do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 } -- do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL" -- do_brack (TExpBr e) = do { MkC e1 <- repLE e ; return e1 } -- {- -------------- Examples -------------------- -- [| \x -> x |] -- ====> -- gensym (unpackString "x"#) `bindQ` \ x1::String -> -- lam (pvar x1) (var x1) -- [| \x -> $(f [| x |]) |] -- ====> -- gensym (unpackString "x"#) `bindQ` \ x1::String -> -- lam (pvar x1) (f (var x1)) -- -} -- ------------------------------------------------------- -- -- Declarations -- ------------------------------------------------------- -- repTopP :: LPat Name -> DsM (Core TH.PatQ) -- repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat) -- ; pat' <- addBinds ss (repLP pat) -- ; wrapGenSyms ss pat' } -- repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec])) -- repTopDs group@(HsGroup { hs_valds = valds -- , hs_splcds = splcds -- , hs_tyclds = tyclds -- , hs_instds = instds -- , hs_derivds = derivds -- , hs_fixds = fixds -- , hs_defds = defds -- , hs_fords = fords -- , hs_warnds = warnds -- , hs_annds = annds -- , hs_ruleds = ruleds -- , hs_vects = vects -- , hs_docs = docs }) -- = do { let { tv_bndrs = hsSigTvBinders valds -- ; bndrs = tv_bndrs ++ hsGroupBinders group } ; -- ss <- mkGenSyms bndrs ; -- -- Bind all the names mainly to avoid repeated use of explicit strings. -- -- Thus we get -- -- do { t :: String <- genSym "T" ; -- -- return (Data t [] ...more t's... } -- -- The other important reason is that the output must mention -- -- only "T", not "Foo:T" where Foo is the current module -- decls <- addBinds ss ( -- do { val_ds <- rep_val_binds valds -- ; _ <- mapM no_splice splcds -- ; tycl_ds <- mapM repTyClD (tyClGroupConcat tyclds) -- ; role_ds <- mapM repRoleD (concatMap group_roles tyclds) -- ; inst_ds <- mapM repInstD instds -- ; deriv_ds <- mapM repStandaloneDerivD derivds -- ; fix_ds <- mapM repFixD fixds -- ; _ <- mapM no_default_decl defds -- ; for_ds <- mapM repForD fords -- ; _ <- mapM no_warn (concatMap (wd_warnings . unLoc) -- warnds) -- ; ann_ds <- mapM repAnnD annds -- ; rule_ds <- mapM repRuleD (concatMap (rds_rules . unLoc) -- ruleds) -- ; _ <- mapM no_vect vects -- ; _ <- mapM no_doc docs -- -- more needed -- ; return (de_loc $ sort_by_loc $ -- val_ds ++ catMaybes tycl_ds ++ role_ds -- ++ (concat fix_ds) -- ++ inst_ds ++ rule_ds ++ for_ds -- ++ ann_ds ++ deriv_ds) }) ; -- decl_ty <- lookupType decQTyConName ; -- let { core_list = coreList' decl_ty decls } ; -- dec_ty <- lookupType decTyConName ; -- q_decs <- repSequenceQ dec_ty core_list ; -- wrapGenSyms ss q_decs -- } -- where -- no_splice (L loc _) -- = notHandledL loc "Splices within declaration brackets" empty -- no_default_decl (L loc decl) -- = notHandledL loc "Default declarations" (ppr decl) -- no_warn (L loc (Warning thing _)) -- = notHandledL loc "WARNING and DEPRECATION pragmas" $ -- text "Pragma for declaration of" <+> ppr thing -- no_vect (L loc decl) -- = notHandledL loc "Vectorisation pragmas" (ppr decl) -- no_doc (L loc _) -- = notHandledL loc "Haddock documentation" empty -- hsSigTvBinders :: HsValBinds Name -> [Name] -- -- See Note [Scoped type variables in bindings] -- hsSigTvBinders binds -- = [hsLTyVarName tv | L _ (TypeSig _ (L _ (HsForAllTy Explicit _ qtvs _ _)) _) <- sigs -- , tv <- hsQTvBndrs qtvs] -- where -- sigs = case binds of -- ValBindsIn _ sigs -> sigs -- ValBindsOut _ sigs -> sigs -- {- Notes -- Note [Scoped type variables in bindings] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Consider -- f :: forall a. a -> a -- f x = x::a -- Here the 'forall a' brings 'a' into scope over the binding group. -- To achieve this we -- a) Gensym a binding for 'a' at the same time as we do one for 'f' -- collecting the relevant binders with hsSigTvBinders -- b) When processing the 'forall', don't gensym -- The relevant places are signposted with references to this Note -- Note [Binders and occurrences] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- When we desugar [d| data T = MkT |] -- we want to get -- Data "T" [] [Con "MkT" []] [] -- and *not* -- Data "Foo:T" [] [Con "Foo:MkT" []] [] -- That is, the new data decl should fit into whatever new module it is -- asked to fit in. We do *not* clone, though; no need for this: -- Data "T79" .... -- But if we see this: -- data T = MkT -- foo = reifyDecl T -- then we must desugar to -- foo = Data "Foo:T" [] [Con "Foo:MkT" []] [] -- So in repTopDs we bring the binders into scope with mkGenSyms and addBinds. -- And we use lookupOcc, rather than lookupBinder -- in repTyClD and repC. -- -} -- -- represent associated family instances -- -- -- repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ)) -- repTyClD (L loc (FamDecl { tcdFam = fam })) = liftM Just $ repFamilyDecl (L loc fam) -- repTyClD (L loc (SynDecl { tcdLName = tc, tcdTyVars = tvs, tcdRhs = rhs })) -- = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] -- ; dec <- addTyClTyVarBinds tvs $ \bndrs -> -- repSynDecl tc1 bndrs rhs -- ; return (Just (loc, dec)) } -- repTyClD (L loc (DataDecl { tcdLName = tc, tcdTyVars = tvs, tcdDataDefn = defn })) -- = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] -- ; tc_tvs <- mk_extra_tvs tc tvs defn -- ; dec <- addTyClTyVarBinds tc_tvs $ \bndrs -> -- repDataDefn tc1 bndrs Nothing (hsLTyVarNames tc_tvs) defn -- ; return (Just (loc, dec)) } -- repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, -- tcdTyVars = tvs, tcdFDs = fds, -- tcdSigs = sigs, tcdMeths = meth_binds, -- tcdATs = ats, tcdATDefs = [] })) -- = do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences] -- ; dec <- addTyVarBinds tvs $ \bndrs -> -- do { cxt1 <- repLContext cxt -- ; sigs1 <- rep_sigs sigs -- ; binds1 <- rep_binds meth_binds -- ; fds1 <- repLFunDeps fds -- ; ats1 <- repFamilyDecls ats -- ; decls1 <- coreList decQTyConName (ats1 ++ sigs1 ++ binds1) -- ; repClass cxt1 cls1 bndrs fds1 decls1 -- } -- ; return $ Just (loc, dec) -- } -- -- Un-handled cases -- repTyClD (L loc d) = putSrcSpanDs loc $ -- do { warnDs (hang ds_msg 4 (ppr d)) -- ; return Nothing } -- ------------------------- -- repRoleD :: LRoleAnnotDecl Name -> DsM (SrcSpan, Core TH.DecQ) -- repRoleD (L loc (RoleAnnotDecl tycon roles)) -- = do { tycon1 <- lookupLOcc tycon -- ; roles1 <- mapM repRole roles -- ; roles2 <- coreList roleTyConName roles1 -- ; dec <- repRoleAnnotD tycon1 roles2 -- ; return (loc, dec) } -- ------------------------- -- repDataDefn :: Core TH.Name -> Core [TH.TyVarBndr] -- -> Maybe (Core [TH.TypeQ]) -- -> [Name] -> HsDataDefn Name -- -> DsM (Core TH.DecQ) -- repDataDefn tc bndrs opt_tys tv_names -- (HsDataDefn { dd_ND = new_or_data, dd_ctxt = cxt -- , dd_cons = cons, dd_derivs = mb_derivs }) -- = do { cxt1 <- repLContext cxt -- ; derivs1 <- repDerivs mb_derivs -- ; case new_or_data of -- NewType -> do { con1 <- repC tv_names (head cons) -- ; case con1 of -- [c] -> repNewtype cxt1 tc bndrs opt_tys c derivs1 -- _cs -> failWithDs (ptext -- (sLit "Multiple constructors for newtype:") -- <+> pprQuotedList -- (con_names $ unLoc $ head cons)) -- } -- DataType -> do { consL <- concatMapM (repC tv_names) cons -- ; cons1 <- coreList conQTyConName consL -- ; repData cxt1 tc bndrs opt_tys cons1 derivs1 } } -- repSynDecl :: Core TH.Name -> Core [TH.TyVarBndr] -- -> LHsType Name -- -> DsM (Core TH.DecQ) -- repSynDecl tc bndrs ty -- = do { ty1 <- repLTy ty -- ; repTySyn tc bndrs ty1 } -- repFamilyDecl :: LFamilyDecl Name -> DsM (SrcSpan, Core TH.DecQ) -- repFamilyDecl (L loc (FamilyDecl { fdInfo = info, -- fdLName = tc, -- fdTyVars = tvs, -- fdKindSig = opt_kind })) -- = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] -- ; dec <- addTyClTyVarBinds tvs $ \bndrs -> -- case (opt_kind, info) of -- (Nothing, ClosedTypeFamily eqns) -> -- do { eqns1 <- mapM repTyFamEqn eqns -- ; eqns2 <- coreList tySynEqnQTyConName eqns1 -- ; repClosedFamilyNoKind tc1 bndrs eqns2 } -- (Just ki, ClosedTypeFamily eqns) -> -- do { eqns1 <- mapM repTyFamEqn eqns -- ; eqns2 <- coreList tySynEqnQTyConName eqns1 -- ; ki1 <- repLKind ki -- ; repClosedFamilyKind tc1 bndrs ki1 eqns2 } -- (Nothing, _) -> -- do { info' <- repFamilyInfo info -- ; repFamilyNoKind info' tc1 bndrs } -- (Just ki, _) -> -- do { info' <- repFamilyInfo info -- ; ki1 <- repLKind ki -- ; repFamilyKind info' tc1 bndrs ki1 } -- ; return (loc, dec) -- } -- repFamilyDecls :: [LFamilyDecl Name] -> DsM [Core TH.DecQ] -- repFamilyDecls fds = liftM de_loc (mapM repFamilyDecl fds) -- ------------------------- -- mk_extra_tvs :: Located Name -> LHsTyVarBndrs Name -- -> HsDataDefn Name -> DsM (LHsTyVarBndrs Name) -- -- If there is a kind signature it must be of form -- -- k1 -> .. -> kn -> * -- -- Return type variables [tv1:k1, tv2:k2, .., tvn:kn] -- mk_extra_tvs tc tvs defn -- | HsDataDefn { dd_kindSig = Just hs_kind } <- defn -- = do { extra_tvs <- go hs_kind -- ; return (tvs { hsq_tvs = hsq_tvs tvs ++ extra_tvs }) } -- | otherwise -- = return tvs -- where -- go :: LHsKind Name -> DsM [LHsTyVarBndr Name] -- go (L loc (HsFunTy kind rest)) -- = do { uniq <- newUnique -- ; let { occ = mkTyVarOccFS (fsLit "t") -- ; nm = mkInternalName uniq occ loc -- ; hs_tv = L loc (KindedTyVar (noLoc nm) kind) } -- ; hs_tvs <- go rest -- ; return (hs_tv : hs_tvs) } -- go (L _ (HsTyVar n)) -- | n == liftedTypeKindTyConName -- = return [] -- go _ = failWithDs (ptext (sLit "Malformed kind signature for") <+> ppr tc) -- ------------------------- -- -- represent fundeps -- -- -- repLFunDeps :: [Located (FunDep (Located Name))] -> DsM (Core [TH.FunDep]) -- repLFunDeps fds = repList funDepTyConName repLFunDep fds -- repLFunDep :: Located (FunDep (Located Name)) -> DsM (Core TH.FunDep) -- repLFunDep (L _ (xs, ys)) -- = do xs' <- repList nameTyConName (lookupBinder . unLoc) xs -- ys' <- repList nameTyConName (lookupBinder . unLoc) ys -- repFunDep xs' ys' -- -- represent family declaration flavours -- -- -- repFamilyInfo :: FamilyInfo Name -> DsM (Core TH.FamFlavour) -- repFamilyInfo OpenTypeFamily = rep2 typeFamName [] -- repFamilyInfo DataFamily = rep2 dataFamName [] -- repFamilyInfo ClosedTypeFamily {} = panic "repFamilyInfo" -- -- Represent instance declarations -- -- -- repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ) -- repInstD (L loc (TyFamInstD { tfid_inst = fi_decl })) -- = do { dec <- repTyFamInstD fi_decl -- ; return (loc, dec) } -- repInstD (L loc (DataFamInstD { dfid_inst = fi_decl })) -- = do { dec <- repDataFamInstD fi_decl -- ; return (loc, dec) } -- repInstD (L loc (ClsInstD { cid_inst = cls_decl })) -- = do { dec <- repClsInstD cls_decl -- ; return (loc, dec) } -- repClsInstD :: ClsInstDecl Name -> DsM (Core TH.DecQ) -- repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds -- , cid_sigs = prags, cid_tyfam_insts = ats -- , cid_datafam_insts = adts }) -- = addTyVarBinds tvs $ \_ -> -- -- We must bring the type variables into scope, so their -- -- occurrences don't fail, even though the binders don't -- -- appear in the resulting data structure -- -- -- -- But we do NOT bring the binders of 'binds' into scope -- -- because they are properly regarded as occurrences -- -- For example, the method names should be bound to -- -- the selector Ids, not to fresh names (Trac #5410) -- -- -- do { cxt1 <- repContext cxt -- ; cls_tcon <- repTy (HsTyVar (unLoc cls)) -- ; cls_tys <- repLTys tys -- ; inst_ty1 <- repTapps cls_tcon cls_tys -- ; binds1 <- rep_binds binds -- ; prags1 <- rep_sigs prags -- ; ats1 <- mapM (repTyFamInstD . unLoc) ats -- ; adts1 <- mapM (repDataFamInstD . unLoc) adts -- ; decls <- coreList decQTyConName (ats1 ++ adts1 ++ binds1 ++ prags1) -- ; repInst cxt1 inst_ty1 decls } -- where -- Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty -- repStandaloneDerivD :: LDerivDecl Name -> DsM (SrcSpan, Core TH.DecQ) -- repStandaloneDerivD (L loc (DerivDecl { deriv_type = ty })) -- = do { dec <- addTyVarBinds tvs $ \_ -> -- do { cxt' <- repContext cxt -- ; cls_tcon <- repTy (HsTyVar (unLoc cls)) -- ; cls_tys <- repLTys tys -- ; inst_ty <- repTapps cls_tcon cls_tys -- ; repDeriv cxt' inst_ty } -- ; return (loc, dec) } -- where -- Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty -- repTyFamInstD :: TyFamInstDecl Name -> DsM (Core TH.DecQ) -- repTyFamInstD decl@(TyFamInstDecl { tfid_eqn = eqn }) -- = do { let tc_name = tyFamInstDeclLName decl -- ; tc <- lookupLOcc tc_name -- See note [Binders and occurrences] -- ; eqn1 <- repTyFamEqn eqn -- ; repTySynInst tc eqn1 } -- repTyFamEqn :: LTyFamInstEqn Name -> DsM (Core TH.TySynEqnQ) -- repTyFamEqn (L loc (TyFamEqn { tfe_pats = HsWB { hswb_cts = tys -- , hswb_kvs = kv_names -- , hswb_tvs = tv_names } -- , tfe_rhs = rhs })) -- = do { let hs_tvs = HsQTvs { hsq_kvs = kv_names -- , hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk -- ; addTyClTyVarBinds hs_tvs $ \ _ -> -- do { tys1 <- repLTys tys -- ; tys2 <- coreList typeQTyConName tys1 -- ; rhs1 <- repLTy rhs -- ; repTySynEqn tys2 rhs1 } } -- repDataFamInstD :: DataFamInstDecl Name -> DsM (Core TH.DecQ) -- repDataFamInstD (DataFamInstDecl { dfid_tycon = tc_name -- , dfid_pats = HsWB { hswb_cts = tys, hswb_kvs = kv_names, hswb_tvs = tv_names } -- , dfid_defn = defn }) -- = do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences] -- ; let loc = getLoc tc_name -- hs_tvs = HsQTvs { hsq_kvs = kv_names, hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk -- ; addTyClTyVarBinds hs_tvs $ \ bndrs -> -- do { tys1 <- repList typeQTyConName repLTy tys -- ; repDataDefn tc bndrs (Just tys1) tv_names defn } } -- repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ) -- repForD (L loc (ForeignImport name typ _ (CImport (L _ cc) (L _ s) mch cis _))) -- = do MkC name' <- lookupLOcc name -- MkC typ' <- repLTy typ -- MkC cc' <- repCCallConv cc -- MkC s' <- repSafety s -- cis' <- conv_cimportspec cis -- MkC str <- coreStringLit (static ++ chStr ++ cis') -- dec <- rep2 forImpDName [cc', s', str, name', typ'] -- return (loc, dec) -- where -- conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls)) -- conv_cimportspec (CFunction DynamicTarget) = return "dynamic" -- conv_cimportspec (CFunction (StaticTarget fs _ True)) = return (unpackFS fs) -- conv_cimportspec (CFunction (StaticTarget _ _ False)) = panic "conv_cimportspec: values not supported yet" -- conv_cimportspec CWrapper = return "wrapper" -- -- these calling conventions do not support headers and the static keyword -- raw_cconv = cc == PrimCallConv || cc == JavaScriptCallConv -- static = case cis of -- CFunction (StaticTarget _ _ _) | not raw_cconv -> "static " -- _ -> "" -- chStr = case mch of -- Just (Header h) | not raw_cconv -> unpackFS h ++ " " -- _ -> "" -- repForD decl = notHandled "Foreign declaration" (ppr decl) -- repCCallConv :: CCallConv -> DsM (Core TH.Callconv) -- repCCallConv CCallConv = rep2 cCallName [] -- repCCallConv StdCallConv = rep2 stdCallName [] -- repCCallConv CApiConv = rep2 cApiCallName [] -- repCCallConv PrimCallConv = rep2 primCallName [] -- repCCallConv JavaScriptCallConv = rep2 javaScriptCallName [] -- repSafety :: Safety -> DsM (Core TH.Safety) -- repSafety PlayRisky = rep2 unsafeName [] -- repSafety PlayInterruptible = rep2 interruptibleName [] -- repSafety PlaySafe = rep2 safeName [] -- repFixD :: LFixitySig Name -> DsM [(SrcSpan, Core TH.DecQ)] -- repFixD (L loc (FixitySig names (Fixity prec dir))) -- = do { MkC prec' <- coreIntLit prec -- ; let rep_fn = case dir of -- InfixL -> infixLDName -- InfixR -> infixRDName -- InfixN -> infixNDName -- ; let do_one name -- = do { MkC name' <- lookupLOcc name -- ; dec <- rep2 rep_fn [prec', name'] -- ; return (loc,dec) } -- ; mapM do_one names } -- repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ) -- repRuleD (L loc (HsRule n act bndrs lhs _ rhs _)) -- = do { let bndr_names = concatMap ruleBndrNames bndrs -- ; ss <- mkGenSyms bndr_names -- ; rule1 <- addBinds ss $ -- do { bndrs' <- repList ruleBndrQTyConName repRuleBndr bndrs -- ; n' <- coreStringLit $ unpackFS $ unLoc n -- ; act' <- repPhases act -- ; lhs' <- repLE lhs -- ; rhs' <- repLE rhs -- ; repPragRule n' bndrs' lhs' rhs' act' } -- ; rule2 <- wrapGenSyms ss rule1 -- ; return (loc, rule2) } -- ruleBndrNames :: LRuleBndr Name -> [Name] -- ruleBndrNames (L _ (RuleBndr n)) = [unLoc n] -- ruleBndrNames (L _ (RuleBndrSig n (HsWB { hswb_kvs = kvs, hswb_tvs = tvs }))) -- = unLoc n : kvs ++ tvs -- repRuleBndr :: LRuleBndr Name -> DsM (Core TH.RuleBndrQ) -- repRuleBndr (L _ (RuleBndr n)) -- = do { MkC n' <- lookupLBinder n -- ; rep2 ruleVarName [n'] } -- repRuleBndr (L _ (RuleBndrSig n (HsWB { hswb_cts = ty }))) -- = do { MkC n' <- lookupLBinder n -- ; MkC ty' <- repLTy ty -- ; rep2 typedRuleVarName [n', ty'] } -- repAnnD :: LAnnDecl Name -> DsM (SrcSpan, Core TH.DecQ) -- repAnnD (L loc (HsAnnotation _ ann_prov (L _ exp))) -- = do { target <- repAnnProv ann_prov -- ; exp' <- repE exp -- ; dec <- repPragAnn target exp' -- ; return (loc, dec) } -- repAnnProv :: AnnProvenance Name -> DsM (Core TH.AnnTarget) -- repAnnProv (ValueAnnProvenance (L _ n)) -- = do { MkC n' <- globalVar n -- ANNs are allowed only at top-level -- ; rep2 valueAnnotationName [ n' ] } -- repAnnProv (TypeAnnProvenance (L _ n)) -- = do { MkC n' <- globalVar n -- ; rep2 typeAnnotationName [ n' ] } -- repAnnProv ModuleAnnProvenance -- = rep2 moduleAnnotationName [] -- ds_msg :: SDoc -- ds_msg = ptext (sLit "Cannot desugar this Template Haskell declaration:") -- ------------------------------------------------------- -- -- Constructors -- ------------------------------------------------------- -- repC :: [Name] -> LConDecl Name -> DsM [Core TH.ConQ] -- repC _ (L _ (ConDecl { con_names = con, con_qvars = con_tvs, con_cxt = L _ [] -- , con_details = details, con_res = ResTyH98 })) -- | null (hsQTvBndrs con_tvs) -- = do { con1 <- mapM lookupLOcc con -- See Note [Binders and occurrences] -- ; mapM (\c -> repConstr c details) con1 } -- repC tvs (L _ (ConDecl { con_names = cons -- , con_qvars = con_tvs, con_cxt = L _ ctxt -- , con_details = details -- , con_res = res_ty })) -- = do { (eq_ctxt, con_tv_subst) <- mkGadtCtxt tvs res_ty -- ; let ex_tvs = HsQTvs { hsq_kvs = filterOut (in_subst con_tv_subst) (hsq_kvs con_tvs) -- , hsq_tvs = filterOut (in_subst con_tv_subst . hsLTyVarName) (hsq_tvs con_tvs) } -- ; binds <- mapM dupBinder con_tv_subst -- ; b <- dsExtendMetaEnv (mkNameEnv binds) $ -- Binds some of the con_tvs -- addTyVarBinds ex_tvs $ \ ex_bndrs -> -- Binds the remaining con_tvs -- do { cons1 <- mapM lookupLOcc cons -- See Note [Binders and occurrences] -- ; c' <- mapM (\c -> repConstr c details) cons1 -- ; ctxt' <- repContext (eq_ctxt ++ ctxt) -- ; rep2 forallCName ([unC ex_bndrs, unC ctxt'] ++ (map unC c')) } -- ; return [b] -- } -- in_subst :: [(Name,Name)] -> Name -> Bool -- in_subst [] _ = False -- in_subst ((n',_):ns) n = n==n' || in_subst ns n -- mkGadtCtxt :: [Name] -- Tyvars of the data type -- -> ResType (LHsType Name) -- -> DsM (HsContext Name, [(Name,Name)]) -- -- Given a data type in GADT syntax, figure out the equality -- -- context, so that we can represent it with an explicit -- -- equality context, because that is the only way to express -- -- the GADT in TH syntax -- -- -- -- Example: -- -- data T a b c where { MkT :: forall d e. d -> e -> T d [e] e -- -- mkGadtCtxt [a,b,c] [d,e] (T d [e] e) -- -- returns -- -- (b~[e], c~e), [d->a] -- -- -- -- This function is fiddly, but not really hard -- mkGadtCtxt _ ResTyH98 -- = return ([], []) -- mkGadtCtxt data_tvs (ResTyGADT _ res_ty) -- | Just (_, tys) <- hsTyGetAppHead_maybe res_ty -- , data_tvs `equalLength` tys -- = return (go [] [] (data_tvs `zip` tys)) -- | otherwise -- = failWithDs (ptext (sLit "Malformed constructor result type:") <+> ppr res_ty) -- where -- go cxt subst [] = (cxt, subst) -- go cxt subst ((data_tv, ty) : rest) -- | Just con_tv <- is_hs_tyvar ty -- , isTyVarName con_tv -- , not (in_subst subst con_tv) -- = go cxt ((con_tv, data_tv) : subst) rest -- | otherwise -- = go (eq_pred : cxt) subst rest -- where -- loc = getLoc ty -- eq_pred = L loc (HsEqTy (L loc (HsTyVar data_tv)) ty) -- is_hs_tyvar (L _ (HsTyVar n)) = Just n -- Type variables *and* tycons -- is_hs_tyvar (L _ (HsParTy ty)) = is_hs_tyvar ty -- is_hs_tyvar _ = Nothing -- repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ)) -- repBangTy ty= do -- MkC s <- rep2 str [] -- MkC t <- repLTy ty' -- rep2 strictTypeName [s, t] -- where -- (str, ty') = case ty of -- L _ (HsBangTy (HsSrcBang _ (Just True) True) ty) -> (unpackedName, ty) -- L _ (HsBangTy (HsSrcBang _ _ True) ty) -> (isStrictName, ty) -- _ -> (notStrictName, ty) -- ------------------------------------------------------- -- -- Deriving clause -- ------------------------------------------------------- -- repDerivs :: Maybe (Located [LHsType Name]) -> DsM (Core [TH.Name]) -- repDerivs Nothing = coreList nameTyConName [] -- repDerivs (Just (L _ ctxt)) -- = repList nameTyConName rep_deriv ctxt -- where -- rep_deriv :: LHsType Name -> DsM (Core TH.Name) -- -- Deriving clauses must have the simple H98 form -- rep_deriv ty -- | Just (cls, []) <- splitHsClassTy_maybe (unLoc ty) -- = lookupOcc cls -- | otherwise -- = notHandled "Non-H98 deriving clause" (ppr ty) -- ------------------------------------------------------- -- -- Signatures in a class decl, or a group of bindings -- ------------------------------------------------------- -- rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ] -- rep_sigs sigs = do locs_cores <- rep_sigs' sigs -- return $ de_loc $ sort_by_loc locs_cores -- rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)] -- -- We silently ignore ones we don't recognise -- rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ; -- return (concat sigs1) } -- rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)] -- rep_sig (L loc (TypeSig nms ty _)) = mapM (rep_ty_sig sigDName loc ty) nms -- rep_sig (L _ (PatSynSig {})) = notHandled "Pattern type signatures" empty -- rep_sig (L loc (GenericSig nms ty)) = mapM (rep_ty_sig defaultSigDName loc ty) nms -- rep_sig d@(L _ (IdSig {})) = pprPanic "rep_sig IdSig" (ppr d) -- rep_sig (L _ (FixSig {})) = return [] -- fixity sigs at top level -- rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc -- rep_sig (L loc (SpecSig nm tys ispec)) -- = concatMapM (\t -> rep_specialise nm t ispec loc) tys -- rep_sig (L loc (SpecInstSig _ ty)) = rep_specialiseInst ty loc -- rep_sig (L _ (MinimalSig {})) = notHandled "MINIMAL pragmas" empty -- rep_ty_sig :: Name -> SrcSpan -> LHsType Name -> Located Name -- -> DsM (SrcSpan, Core TH.DecQ) -- rep_ty_sig mk_sig loc (L _ ty) nm -- = do { nm1 <- lookupLOcc nm -- ; ty1 <- rep_ty ty -- ; sig <- repProto mk_sig nm1 ty1 -- ; return (loc, sig) } -- where -- -- We must special-case the top-level explicit for-all of a TypeSig -- -- See Note [Scoped type variables in bindings] -- rep_ty (HsForAllTy Explicit _ tvs ctxt ty) -- = do { let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv) -- ; repTyVarBndrWithKind tv name } -- ; bndrs1 <- repList tyVarBndrTyConName rep_in_scope_tv (hsQTvBndrs tvs) -- ; ctxt1 <- repLContext ctxt -- ; ty1 <- repLTy ty -- ; repTForall bndrs1 ctxt1 ty1 } -- rep_ty ty = repTy ty -- rep_inline :: Located Name -- -> InlinePragma -- Never defaultInlinePragma -- -> SrcSpan -- -> DsM [(SrcSpan, Core TH.DecQ)] -- rep_inline nm ispec loc -- = do { nm1 <- lookupLOcc nm -- ; inline <- repInline $ inl_inline ispec -- ; rm <- repRuleMatch $ inl_rule ispec -- ; phases <- repPhases $ inl_act ispec -- ; pragma <- repPragInl nm1 inline rm phases -- ; return [(loc, pragma)] -- } -- rep_specialise :: Located Name -> LHsType Name -> InlinePragma -> SrcSpan -- -> DsM [(SrcSpan, Core TH.DecQ)] -- rep_specialise nm ty ispec loc -- = do { nm1 <- lookupLOcc nm -- ; ty1 <- repLTy ty -- ; phases <- repPhases $ inl_act ispec -- ; let inline = inl_inline ispec -- ; pragma <- if isEmptyInlineSpec inline -- then -- SPECIALISE -- repPragSpec nm1 ty1 phases -- else -- SPECIALISE INLINE -- do { inline1 <- repInline inline -- ; repPragSpecInl nm1 ty1 inline1 phases } -- ; return [(loc, pragma)] -- } -- rep_specialiseInst :: LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] -- rep_specialiseInst ty loc -- = do { ty1 <- repLTy ty -- ; pragma <- repPragSpecInst ty1 -- ; return [(loc, pragma)] } -- repInline :: InlineSpec -> DsM (Core TH.Inline) -- repInline NoInline = dataCon noInlineDataConName -- repInline Inline = dataCon inlineDataConName -- repInline Inlinable = dataCon inlinableDataConName -- repInline spec = notHandled "repInline" (ppr spec) -- repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch) -- repRuleMatch ConLike = dataCon conLikeDataConName -- repRuleMatch FunLike = dataCon funLikeDataConName -- repPhases :: Activation -> DsM (Core TH.Phases) -- repPhases (ActiveBefore i) = do { MkC arg <- coreIntLit i -- ; dataCon' beforePhaseDataConName [arg] } -- repPhases (ActiveAfter i) = do { MkC arg <- coreIntLit i -- ; dataCon' fromPhaseDataConName [arg] } -- repPhases _ = dataCon allPhasesDataConName -- ------------------------------------------------------- -- -- Types -- ------------------------------------------------------- -- addTyVarBinds :: LHsTyVarBndrs Name -- the binders to be added -- -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env -- -> DsM (Core (TH.Q a)) -- -- gensym a list of type variables and enter them into the meta environment; -- -- the computations passed as the second argument is executed in that extended -- -- meta environment and gets the *new* names on Core-level as an argument -- addTyVarBinds (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs }) m -- = do { fresh_kv_names <- mkGenSyms kvs -- ; fresh_tv_names <- mkGenSyms (map hsLTyVarName tvs) -- ; let fresh_names = fresh_kv_names ++ fresh_tv_names -- ; term <- addBinds fresh_names $ -- do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (tvs `zip` fresh_tv_names) -- ; m kbs } -- ; wrapGenSyms fresh_names term } -- where -- mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v) -- addTyClTyVarBinds :: LHsTyVarBndrs Name -- -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- -> DsM (Core (TH.Q a)) -- -- Used for data/newtype declarations, and family instances, -- -- so that the nested type variables work right -- -- instance C (T a) where -- -- type W (T a) = blah -- -- The 'a' in the type instance is the one bound by the instance decl -- addTyClTyVarBinds tvs m -- = do { let tv_names = hsLKiTyVarNames tvs -- ; env <- dsGetMetaEnv -- ; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names) -- -- Make fresh names for the ones that are not already in scope -- -- This makes things work for family declarations -- ; term <- addBinds freshNames $ -- do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (hsQTvBndrs tvs) -- ; m kbs } -- ; wrapGenSyms freshNames term } -- where -- mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv) -- ; repTyVarBndrWithKind tv v } -- -- Produce kinded binder constructors from the Haskell tyvar binders -- -- -- repTyVarBndrWithKind :: LHsTyVarBndr Name -- -> Core TH.Name -> DsM (Core TH.TyVarBndr) -- repTyVarBndrWithKind (L _ (UserTyVar _)) nm -- = repPlainTV nm -- repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm -- = repLKind ki >>= repKindedTV nm -- -- represent a type context -- -- -- repLContext :: LHsContext Name -> DsM (Core TH.CxtQ) -- repLContext (L _ ctxt) = repContext ctxt -- repContext :: HsContext Name -> DsM (Core TH.CxtQ) -- repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt -- repCtxt preds -- -- yield the representation of a list of types -- -- -- repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ] -- repLTys tys = mapM repLTy tys -- -- represent a type -- -- -- repLTy :: LHsType Name -> DsM (Core TH.TypeQ) -- repLTy (L _ ty) = repTy ty -- repTy :: HsType Name -> DsM (Core TH.TypeQ) -- repTy (HsForAllTy _ _ tvs ctxt ty) = -- addTyVarBinds tvs $ \bndrs -> do -- ctxt1 <- repLContext ctxt -- ty1 <- repLTy ty -- repTForall bndrs ctxt1 ty1 -- repTy (HsTyVar n) -- | isTvOcc occ = do tv1 <- lookupOcc n -- repTvar tv1 -- | isDataOcc occ = do tc1 <- lookupOcc n -- repPromotedTyCon tc1 -- | otherwise = do tc1 <- lookupOcc n -- repNamedTyCon tc1 -- where -- occ = nameOccName n -- repTy (HsAppTy f a) = do -- f1 <- repLTy f -- a1 <- repLTy a -- repTapp f1 a1 -- repTy (HsFunTy f a) = do -- f1 <- repLTy f -- a1 <- repLTy a -- tcon <- repArrowTyCon -- repTapps tcon [f1, a1] -- repTy (HsListTy t) = do -- t1 <- repLTy t -- tcon <- repListTyCon -- repTapp tcon t1 -- repTy (HsPArrTy t) = do -- t1 <- repLTy t -- tcon <- repTy (HsTyVar (tyConName parrTyCon)) -- repTapp tcon t1 -- repTy (HsTupleTy HsUnboxedTuple tys) = do -- tys1 <- repLTys tys -- tcon <- repUnboxedTupleTyCon (length tys) -- repTapps tcon tys1 -- repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys -- tcon <- repTupleTyCon (length tys) -- repTapps tcon tys1 -- repTy (HsOpTy ty1 (_, n) ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) -- `nlHsAppTy` ty2) -- repTy (HsParTy t) = repLTy t -- repTy (HsEqTy t1 t2) = do -- t1' <- repLTy t1 -- t2' <- repLTy t2 -- eq <- repTequality -- repTapps eq [t1', t2'] -- repTy (HsKindSig t k) = do -- t1 <- repLTy t -- k1 <- repLKind k -- repTSig t1 k1 -- repTy (HsSpliceTy splice _) = repSplice splice -- repTy (HsExplicitListTy _ tys) = do -- tys1 <- repLTys tys -- repTPromotedList tys1 -- repTy (HsExplicitTupleTy _ tys) = do -- tys1 <- repLTys tys -- tcon <- repPromotedTupleTyCon (length tys) -- repTapps tcon tys1 -- repTy (HsTyLit lit) = do -- lit' <- repTyLit lit -- repTLit lit' -- repTy ty = notHandled "Exotic form of type" (ppr ty) -- repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ) -- repTyLit (HsNumTy _ i) = do iExpr <- mkIntegerExpr i -- rep2 numTyLitName [iExpr] -- repTyLit (HsStrTy _ s) = do { s' <- mkStringExprFS s -- ; rep2 strTyLitName [s'] -- } -- -- represent a kind -- -- -- repLKind :: LHsKind Name -> DsM (Core TH.Kind) -- repLKind ki -- = do { let (kis, ki') = splitHsFunType ki -- ; kis_rep <- mapM repLKind kis -- ; ki'_rep <- repNonArrowLKind ki' -- ; kcon <- repKArrow -- ; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2 -- ; foldrM f ki'_rep kis_rep -- } -- repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind) -- repNonArrowLKind (L _ ki) = repNonArrowKind ki -- repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind) -- repNonArrowKind (HsTyVar name) -- | name == liftedTypeKindTyConName = repKStar -- | name == constraintKindTyConName = repKConstraint -- | isTvOcc (nameOccName name) = lookupOcc name >>= repKVar -- | otherwise = lookupOcc name >>= repKCon -- repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f -- ; a' <- repLKind a -- ; repKApp f' a' -- } -- repNonArrowKind (HsListTy k) = do { k' <- repLKind k -- ; kcon <- repKList -- ; repKApp kcon k' -- } -- repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks -- ; kcon <- repKTuple (length ks) -- ; repKApps kcon ks' -- } -- repNonArrowKind k = notHandled "Exotic form of kind" (ppr k) -- repRole :: Located (Maybe Role) -> DsM (Core TH.Role) -- repRole (L _ (Just Nominal)) = rep2 nominalRName [] -- repRole (L _ (Just Representational)) = rep2 representationalRName [] -- repRole (L _ (Just Phantom)) = rep2 phantomRName [] -- repRole (L _ Nothing) = rep2 inferRName [] -- ----------------------------------------------------------------------------- -- -- Splices -- ----------------------------------------------------------------------------- -- repSplice :: HsSplice Name -> DsM (Core a) -- -- See Note [How brackets and nested splices are handled] in TcSplice -- -- We return a CoreExpr of any old type; the context should know -- repSplice (HsSplice n _) -- = do { mb_val <- dsLookupMetaEnv n -- ; case mb_val of -- Just (DsSplice e) -> do { e' <- dsExpr e -- ; return (MkC e') } -- _ -> pprPanic "HsSplice" (ppr n) } -- -- Should not happen; statically checked -- ----------------------------------------------------------------------------- -- -- Expressions -- ----------------------------------------------------------------------------- -- repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ]) -- repLEs es = repList expQTyConName repLE es -- -- FIXME: some of these panics should be converted into proper error messages -- -- unless we can make sure that constructs, which are plainly not -- -- supported in TH already lead to error messages at an earlier stage -- repLE :: LHsExpr Name -> DsM (Core TH.ExpQ) -- repLE (L loc e) = putSrcSpanDs loc (repE e) -- repE :: HsExpr Name -> DsM (Core TH.ExpQ) -- repE (HsVar x) = -- do { mb_val <- dsLookupMetaEnv x -- ; case mb_val of -- Nothing -> do { str <- globalVar x -- ; repVarOrCon x str } -- Just (DsBound y) -> repVarOrCon x (coreVar y) -- Just (DsSplice e) -> do { e' <- dsExpr e -- ; return (MkC e') } } -- repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e) -- -- Remember, we're desugaring renamer output here, so -- -- HsOverlit can definitely occur -- repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a } -- repE (HsLit l) = do { a <- repLiteral l; repLit a } -- repE (HsLam (MG { mg_alts = [m] })) = repLambda m -- repE (HsLamCase _ (MG { mg_alts = ms })) -- = do { ms' <- mapM repMatchTup ms -- ; core_ms <- coreList matchQTyConName ms' -- ; repLamCase core_ms } -- repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b} -- repE (OpApp e1 op _ e2) = -- do { arg1 <- repLE e1; -- arg2 <- repLE e2; -- the_op <- repLE op ; -- repInfixApp arg1 the_op arg2 } -- repE (NegApp x _) = do -- a <- repLE x -- negateVar <- lookupOcc negateName >>= repVar -- negateVar `repApp` a -- repE (HsPar x) = repLE x -- repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b } -- repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b } -- repE (HsCase e (MG { mg_alts = ms })) -- = do { arg <- repLE e -- ; ms2 <- mapM repMatchTup ms -- ; core_ms2 <- coreList matchQTyConName ms2 -- ; repCaseE arg core_ms2 } -- repE (HsIf _ x y z) = do -- a <- repLE x -- b <- repLE y -- c <- repLE z -- repCond a b c -- repE (HsMultiIf _ alts) -- = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts -- ; expr' <- repMultiIf (nonEmptyCoreList alts') -- ; wrapGenSyms (concat binds) expr' } -- repE (HsLet bs e) = do { (ss,ds) <- repBinds bs -- ; e2 <- addBinds ss (repLE e) -- ; z <- repLetE ds e2 -- ; wrapGenSyms ss z } -- -- FIXME: I haven't got the types here right yet -- repE e@(HsDo ctxt sts _) -- | case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False } -- = do { (ss,zs) <- repLSts sts; -- e' <- repDoE (nonEmptyCoreList zs); -- wrapGenSyms ss e' } -- | ListComp <- ctxt -- = do { (ss,zs) <- repLSts sts; -- e' <- repComp (nonEmptyCoreList zs); -- wrapGenSyms ss e' } -- | otherwise -- = notHandled "mdo, monad comprehension and [: :]" (ppr e) -- repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs } -- repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e) -- repE e@(ExplicitTuple es boxed) -- | not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e) -- | isBoxed boxed = do { xs <- repLEs [e | L _ (Present e) <- es]; repTup xs } -- | otherwise = do { xs <- repLEs [e | L _ (Present e) <- es] -- ; repUnboxedTup xs } -- repE (RecordCon c _ flds) -- = do { x <- lookupLOcc c; -- fs <- repFields flds; -- repRecCon x fs } -- repE (RecordUpd e flds _ _ _) -- = do { x <- repLE e; -- fs <- repFields flds; -- repRecUpd x fs } -- repE (ExprWithTySig e ty _) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 } -- repE (ArithSeq _ _ aseq) = -- case aseq of -- From e -> do { ds1 <- repLE e; repFrom ds1 } -- FromThen e1 e2 -> do -- ds1 <- repLE e1 -- ds2 <- repLE e2 -- repFromThen ds1 ds2 -- FromTo e1 e2 -> do -- ds1 <- repLE e1 -- ds2 <- repLE e2 -- repFromTo ds1 ds2 -- FromThenTo e1 e2 e3 -> do -- ds1 <- repLE e1 -- ds2 <- repLE e2 -- ds3 <- repLE e3 -- repFromThenTo ds1 ds2 ds3 -- repE (HsSpliceE _ splice) = repSplice splice -- repE (HsStatic e) = repLE e >>= rep2 staticEName . (:[]) . unC -- repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e) -- repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e) -- repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e) -- repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e) -- repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e) -- repE e = notHandled "Expression form" (ppr e) -- ----------------------------------------------------------------------------- -- -- Building representations of auxillary structures like Match, Clause, Stmt, -- repMatchTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.MatchQ) -- repMatchTup (L _ (Match _ [p] _ (GRHSs guards wheres))) = -- do { ss1 <- mkGenSyms (collectPatBinders p) -- ; addBinds ss1 $ do { -- ; p1 <- repLP p -- ; (ss2,ds) <- repBinds wheres -- ; addBinds ss2 $ do { -- ; gs <- repGuards guards -- ; match <- repMatch p1 gs ds -- ; wrapGenSyms (ss1++ss2) match }}} -- repMatchTup _ = panic "repMatchTup: case alt with more than one arg" -- repClauseTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ClauseQ) -- repClauseTup (L _ (Match _ ps _ (GRHSs guards wheres))) = -- do { ss1 <- mkGenSyms (collectPatsBinders ps) -- ; addBinds ss1 $ do { -- ps1 <- repLPs ps -- ; (ss2,ds) <- repBinds wheres -- ; addBinds ss2 $ do { -- gs <- repGuards guards -- ; clause <- repClause ps1 gs ds -- ; wrapGenSyms (ss1++ss2) clause }}} -- repGuards :: [LGRHS Name (LHsExpr Name)] -> DsM (Core TH.BodyQ) -- repGuards [L _ (GRHS [] e)] -- = do {a <- repLE e; repNormal a } -- repGuards other -- = do { zs <- mapM repLGRHS other -- ; let (xs, ys) = unzip zs -- ; gd <- repGuarded (nonEmptyCoreList ys) -- ; wrapGenSyms (concat xs) gd } -- repLGRHS :: LGRHS Name (LHsExpr Name) -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp)))) -- repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2)) -- = do { guarded <- repLNormalGE e1 e2 -- ; return ([], guarded) } -- repLGRHS (L _ (GRHS ss rhs)) -- = do { (gs, ss') <- repLSts ss -- ; rhs' <- addBinds gs $ repLE rhs -- ; guarded <- repPatGE (nonEmptyCoreList ss') rhs' -- ; return (gs, guarded) } -- repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp]) -- repFields (HsRecFields { rec_flds = flds }) -- = repList fieldExpQTyConName rep_fld flds -- where -- rep_fld (L _ fld) = do { fn <- lookupLOcc (hsRecFieldId fld) -- ; e <- repLE (hsRecFieldArg fld) -- ; repFieldExp fn e } -- ----------------------------------------------------------------------------- -- -- Representing Stmt's is tricky, especially if bound variables -- -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |] -- -- First gensym new names for every variable in any of the patterns. -- -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y")) -- -- if variables didn't shaddow, the static gensym wouldn't be necessary -- -- and we could reuse the original names (x and x). -- -- -- -- do { x'1 <- gensym "x" -- -- ; x'2 <- gensym "x" -- -- ; doE [ BindSt (pvar x'1) [| f 1 |] -- -- , BindSt (pvar x'2) [| f x |] -- -- , NoBindSt [| g x |] -- -- ] -- -- } -- -- The strategy is to translate a whole list of do-bindings by building a -- -- bigger environment, and a bigger set of meta bindings -- -- (like: x'1 <- gensym "x" ) and then combining these with the translations -- -- of the expressions within the Do -- ----------------------------------------------------------------------------- -- -- The helper function repSts computes the translation of each sub expression -- -- and a bunch of prefix bindings denoting the dynamic renaming. -- repLSts :: [LStmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) -- repLSts stmts = repSts (map unLoc stmts) -- repSts :: [Stmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) -- repSts (BindStmt p e _ _ : ss) = -- do { e2 <- repLE e -- ; ss1 <- mkGenSyms (collectPatBinders p) -- ; addBinds ss1 $ do { -- ; p1 <- repLP p; -- ; (ss2,zs) <- repSts ss -- ; z <- repBindSt p1 e2 -- ; return (ss1++ss2, z : zs) }} -- repSts (LetStmt bs : ss) = -- do { (ss1,ds) <- repBinds bs -- ; z <- repLetSt ds -- ; (ss2,zs) <- addBinds ss1 (repSts ss) -- ; return (ss1++ss2, z : zs) } -- repSts (BodyStmt e _ _ _ : ss) = -- do { e2 <- repLE e -- ; z <- repNoBindSt e2 -- ; (ss2,zs) <- repSts ss -- ; return (ss2, z : zs) } -- repSts (ParStmt stmt_blocks _ _ : ss) = -- do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks -- ; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1 -- ss1 = concat ss_s -- ; z <- repParSt stmt_blocks2 -- ; (ss2, zs) <- addBinds ss1 (repSts ss) -- ; return (ss1++ss2, z : zs) } -- where -- rep_stmt_block :: ParStmtBlock Name Name -> DsM ([GenSymBind], Core [TH.StmtQ]) -- rep_stmt_block (ParStmtBlock stmts _ _) = -- do { (ss1, zs) <- repSts (map unLoc stmts) -- ; zs1 <- coreList stmtQTyConName zs -- ; return (ss1, zs1) } -- repSts [LastStmt e _] -- = do { e2 <- repLE e -- ; z <- repNoBindSt e2 -- ; return ([], [z]) } -- repSts [] = return ([],[]) -- repSts other = notHandled "Exotic statement" (ppr other) -- ----------------------------------------------------------- -- -- Bindings -- ----------------------------------------------------------- -- repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ]) -- repBinds EmptyLocalBinds -- = do { core_list <- coreList decQTyConName [] -- ; return ([], core_list) } -- repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b) -- repBinds (HsValBinds decs) -- = do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs } -- -- No need to worrry about detailed scopes within -- -- the binding group, because we are talking Names -- -- here, so we can safely treat it as a mutually -- -- recursive group -- -- For hsSigTvBinders see Note [Scoped type variables in bindings] -- ; ss <- mkGenSyms bndrs -- ; prs <- addBinds ss (rep_val_binds decs) -- ; core_list <- coreList decQTyConName -- (de_loc (sort_by_loc prs)) -- ; return (ss, core_list) } -- rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] -- -- Assumes: all the binders of the binding are alrady in the meta-env -- rep_val_binds (ValBindsOut binds sigs) -- = do { core1 <- rep_binds' (unionManyBags (map snd binds)) -- ; core2 <- rep_sigs' sigs -- ; return (core1 ++ core2) } -- rep_val_binds (ValBindsIn _ _) -- = panic "rep_val_binds: ValBindsIn" -- rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ] -- rep_binds binds = do { binds_w_locs <- rep_binds' binds -- ; return (de_loc (sort_by_loc binds_w_locs)) } -- rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] -- rep_binds' = mapM rep_bind . bagToList -- rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ) -- -- Assumes: all the binders of the binding are alrady in the meta-env -- -- Note GHC treats declarations of a variable (not a pattern) -- -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match -- -- with an empty list of patterns -- rep_bind (L loc (FunBind -- { fun_id = fn, -- fun_matches = MG { mg_alts = [L _ (Match _ [] _ -- (GRHSs guards wheres))] } })) -- = do { (ss,wherecore) <- repBinds wheres -- ; guardcore <- addBinds ss (repGuards guards) -- ; fn' <- lookupLBinder fn -- ; p <- repPvar fn' -- ; ans <- repVal p guardcore wherecore -- ; ans' <- wrapGenSyms ss ans -- ; return (loc, ans') } -- rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = ms } })) -- = do { ms1 <- mapM repClauseTup ms -- ; fn' <- lookupLBinder fn -- ; ans <- repFun fn' (nonEmptyCoreList ms1) -- ; return (loc, ans) } -- rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres })) -- = do { patcore <- repLP pat -- ; (ss,wherecore) <- repBinds wheres -- ; guardcore <- addBinds ss (repGuards guards) -- ; ans <- repVal patcore guardcore wherecore -- ; ans' <- wrapGenSyms ss ans -- ; return (loc, ans') } -- rep_bind (L _ (VarBind { var_id = v, var_rhs = e})) -- = do { v' <- lookupBinder v -- ; e2 <- repLE e -- ; x <- repNormal e2 -- ; patcore <- repPvar v' -- ; empty_decls <- coreList decQTyConName [] -- ; ans <- repVal patcore x empty_decls -- ; return (srcLocSpan (getSrcLoc v), ans) } -- rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds" -- rep_bind (L _ dec@(PatSynBind {})) = notHandled "pattern synonyms" (ppr dec) -- ----------------------------------------------------------------------------- -- -- Since everything in a Bind is mutually recursive we need rename all -- -- all the variables simultaneously. For example: -- -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to -- -- do { f'1 <- gensym "f" -- -- ; g'2 <- gensym "g" -- -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]}, -- -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]} -- -- ]} -- -- This requires collecting the bindings (f'1 <- gensym "f"), and the -- -- environment ( f |-> f'1 ) from each binding, and then unioning them -- -- together. As we do this we collect GenSymBinds's which represent the renamed -- -- variables bound by the Bindings. In order not to lose track of these -- -- representations we build a shadow datatype MB with the same structure as -- -- MonoBinds, but which has slots for the representations -- ----------------------------------------------------------------------------- -- -- GHC allows a more general form of lambda abstraction than specified -- -- by Haskell 98. In particular it allows guarded lambda's like : -- -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in -- -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like -- -- (\ p1 .. pn -> exp) by causing an error. -- repLambda :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ExpQ) -- repLambda (L _ (Match _ ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds))) -- = do { let bndrs = collectPatsBinders ps ; -- ; ss <- mkGenSyms bndrs -- ; lam <- addBinds ss ( -- do { xs <- repLPs ps; body <- repLE e; repLam xs body }) -- ; wrapGenSyms ss lam } -- repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m) -- ----------------------------------------------------------------------------- -- -- Patterns -- -- repP deals with patterns. It assumes that we have already -- -- walked over the pattern(s) once to collect the binders, and -- -- have extended the environment. So every pattern-bound -- -- variable should already appear in the environment. -- -- Process a list of patterns -- repLPs :: [LPat Name] -> DsM (Core [TH.PatQ]) -- repLPs ps = repList patQTyConName repLP ps -- repLP :: LPat Name -> DsM (Core TH.PatQ) -- repLP (L _ p) = repP p -- repP :: Pat Name -> DsM (Core TH.PatQ) -- repP (WildPat _) = repPwild -- repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 } -- repP (VarPat x) = do { x' <- lookupBinder x; repPvar x' } -- repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 } -- repP (BangPat p) = do { p1 <- repLP p; repPbang p1 } -- repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 } -- repP (ParPat p) = repLP p -- repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs } -- repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE e; repPview e' p} -- repP (TuplePat ps boxed _) -- | isBoxed boxed = do { qs <- repLPs ps; repPtup qs } -- | otherwise = do { qs <- repLPs ps; repPunboxedTup qs } -- repP (ConPatIn dc details) -- = do { con_str <- lookupLOcc dc -- ; case details of -- PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs } -- RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec) -- ; repPrec con_str fps } -- InfixCon p1 p2 -> do { p1' <- repLP p1; -- p2' <- repLP p2; -- repPinfix p1' con_str p2' } -- } -- where -- rep_fld (L _ fld) = do { MkC v <- lookupLOcc (hsRecFieldId fld) -- ; MkC p <- repLP (hsRecFieldArg fld) -- ; rep2 fieldPatName [v,p] } -- repP (NPat (L _ l) Nothing _) = do { a <- repOverloadedLiteral l; repPlit a } -- repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' } -- repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p) -- repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p) -- -- The problem is to do with scoped type variables. -- -- To implement them, we have to implement the scoping rules -- -- here in DsMeta, and I don't want to do that today! -- -- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' } -- -- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ) -- -- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t] -- repP (SplicePat splice) = repSplice splice -- repP other = notHandled "Exotic pattern" (ppr other) -- ---------------------------------------------------------- -- -- Declaration ordering helpers -- sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)] -- sort_by_loc xs = sortBy comp xs -- where comp x y = compare (fst x) (fst y) -- de_loc :: [(a, b)] -> [b] -- de_loc = map snd -- ---------------------------------------------------------- -- -- The meta-environment -- -- A name/identifier association for fresh names of locally bound entities -- type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id -- -- I.e. (x, x_id) means -- -- let x_id = gensym "x" in ... -- -- Generate a fresh name for a locally bound entity -- mkGenSyms :: [Name] -> DsM [GenSymBind] -- -- We can use the existing name. For example: -- -- [| \x_77 -> x_77 + x_77 |] -- -- desugars to -- -- do { x_77 <- genSym "x"; .... } -- -- We use the same x_77 in the desugared program, but with the type Bndr -- -- instead of Int -- -- -- -- We do make it an Internal name, though (hence localiseName) -- -- -- -- Nevertheless, it's monadic because we have to generate nameTy -- mkGenSyms ns = do { var_ty <- lookupType nameTyConName -- ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] } -- addBinds :: [GenSymBind] -> DsM a -> DsM a -- -- Add a list of fresh names for locally bound entities to the -- -- meta environment (which is part of the state carried around -- -- by the desugarer monad) -- addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,DsBound id) | (n,id) <- bs]) m -- dupBinder :: (Name, Name) -> DsM (Name, DsMetaVal) -- dupBinder (new, old) -- = do { mb_val <- dsLookupMetaEnv old -- ; case mb_val of -- Just val -> return (new, val) -- Nothing -> pprPanic "dupBinder" (ppr old) } -- -- Look up a locally bound name -- -- -- lookupLBinder :: Located Name -> DsM (Core TH.Name) -- lookupLBinder (L _ n) = lookupBinder n -- lookupBinder :: Name -> DsM (Core TH.Name) -- lookupBinder = lookupOcc -- -- Binders are brought into scope before the pattern or what-not is -- -- desugared. Moreover, in instance declaration the binder of a method -- -- will be the selector Id and hence a global; so we need the -- -- globalVar case of lookupOcc -- -- Look up a name that is either locally bound or a global name -- -- -- -- * If it is a global name, generate the "original name" representation (ie, -- -- the <module>:<name> form) for the associated entity -- -- -- lookupLOcc :: Located Name -> DsM (Core TH.Name) -- -- Lookup an occurrence; it can't be a splice. -- -- Use the in-scope bindings if they exist -- lookupLOcc (L _ n) = lookupOcc n -- lookupOcc :: Name -> DsM (Core TH.Name) -- lookupOcc n -- = do { mb_val <- dsLookupMetaEnv n ; -- case mb_val of -- Nothing -> globalVar n -- Just (DsBound x) -> return (coreVar x) -- Just (DsSplice _) -> pprPanic "repE:lookupOcc" (ppr n) -- } -- globalVar :: Name -> DsM (Core TH.Name) -- -- Not bound by the meta-env -- -- Could be top-level; or could be local -- -- f x = $(g [| x |]) -- -- Here the x will be local -- globalVar name -- | isExternalName name -- = do { MkC mod <- coreStringLit name_mod -- ; MkC pkg <- coreStringLit name_pkg -- ; MkC occ <- occNameLit name -- ; rep2 mk_varg [pkg,mod,occ] } -- | otherwise -- = do { MkC occ <- occNameLit name -- ; MkC uni <- coreIntLit (getKey (getUnique name)) -- ; rep2 mkNameLName [occ,uni] } -- where -- mod = {-ASSERT( isExternalName name)-} nameModule name -- name_mod = moduleNameString (moduleName mod) -- name_pkg = unitIdString (moduleUnitId mod) -- name_occ = nameOccName name -- mk_varg | OccName.isDataOcc name_occ = mkNameG_dName -- | OccName.isVarOcc name_occ = mkNameG_vName -- | OccName.isTcOcc name_occ = mkNameG_tcName -- | otherwise = pprPanic "DsMeta.globalVar" (ppr name) -- lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ) -- -> DsM Type -- The type -- lookupType tc_name = do { tc <- dsLookupTyCon tc_name ; -- return (mkTyConApp tc []) } -- wrapGenSyms :: [GenSymBind] -- -> Core (TH.Q a) -> DsM (Core (TH.Q a)) -- -- wrapGenSyms [(nm1,id1), (nm2,id2)] y -- -- --> bindQ (gensym nm1) (\ id1 -> -- -- bindQ (gensym nm2 (\ id2 -> -- -- y)) -- wrapGenSyms binds body@(MkC b) -- = do { var_ty <- lookupType nameTyConName -- ; go var_ty binds } -- where -- [elt_ty] = tcTyConAppArgs (exprType b) -- -- b :: Q a, so we can get the type 'a' by looking at the -- -- argument type. NB: this relies on Q being a data/newtype, -- -- not a type synonym -- go _ [] = return body -- go var_ty ((name,id) : binds) -- = do { MkC body' <- go var_ty binds -- ; lit_str <- occNameLit name -- ; gensym_app <- repGensym lit_str -- ; repBindQ var_ty elt_ty -- gensym_app (MkC (Lam id body')) } -- occNameLit :: Name -> DsM (Core String) -- occNameLit n = coreStringLit (occNameString (nameOccName n)) -- -- %********************************************************************* -- -- %* * -- -- Constructing code -- -- %* * -- -- %********************************************************************* -- ----------------------------------------------------------------------------- -- -- PHANTOM TYPES for consistency. In order to make sure we do this correct -- -- we invent a new datatype which uses phantom types. -- newtype Core a = MkC CoreExpr -- unC :: Core a -> CoreExpr -- unC (MkC x) = x -- rep2 :: Name -> [ CoreExpr ] -> DsM (Core a) -- rep2 n xs = do { id <- dsLookupGlobalId n -- ; return (MkC (foldl App (Var id) xs)) } -- dataCon' :: Name -> [CoreExpr] -> DsM (Core a) -- dataCon' n args = do { id <- dsLookupDataCon n -- ; return $ MkC $ mkCoreConApps id args } -- dataCon :: Name -> DsM (Core a) -- dataCon n = dataCon' n [] -- -- Then we make "repConstructors" which use the phantom types for each of the -- -- smart constructors of the Meta.Meta datatypes. -- -- %********************************************************************* -- -- %* * -- -- The 'smart constructors' -- -- %* * -- -- %********************************************************************* -- --------------- Patterns ----------------- -- repPlit :: Core TH.Lit -> DsM (Core TH.PatQ) -- repPlit (MkC l) = rep2 litPName [l] -- repPvar :: Core TH.Name -> DsM (Core TH.PatQ) -- repPvar (MkC s) = rep2 varPName [s] -- repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) -- repPtup (MkC ps) = rep2 tupPName [ps] -- repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) -- repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps] -- repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ) -- repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps] -- repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ) -- repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps] -- repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) -- repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2] -- repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ) -- repPtilde (MkC p) = rep2 tildePName [p] -- repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ) -- repPbang (MkC p) = rep2 bangPName [p] -- repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) -- repPaspat (MkC s) (MkC p) = rep2 asPName [s, p] -- repPwild :: DsM (Core TH.PatQ) -- repPwild = rep2 wildPName [] -- repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ) -- repPlist (MkC ps) = rep2 listPName [ps] -- repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ) -- repPview (MkC e) (MkC p) = rep2 viewPName [e,p] -- --------------- Expressions ----------------- -- repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ) -- repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str -- | otherwise = repVar str -- repVar :: Core TH.Name -> DsM (Core TH.ExpQ) -- repVar (MkC s) = rep2 varEName [s] -- repCon :: Core TH.Name -> DsM (Core TH.ExpQ) -- repCon (MkC s) = rep2 conEName [s] -- repLit :: Core TH.Lit -> DsM (Core TH.ExpQ) -- repLit (MkC c) = rep2 litEName [c] -- repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repApp (MkC x) (MkC y) = rep2 appEName [x,y] -- repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e] -- repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ) -- repLamCase (MkC ms) = rep2 lamCaseEName [ms] -- repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) -- repTup (MkC es) = rep2 tupEName [es] -- repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) -- repUnboxedTup (MkC es) = rep2 unboxedTupEName [es] -- repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z] -- repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ) -- repMultiIf (MkC alts) = rep2 multiIfEName [alts] -- repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e] -- repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ) -- repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms] -- repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) -- repDoE (MkC ss) = rep2 doEName [ss] -- repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) -- repComp (MkC ss) = rep2 compEName [ss] -- repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) -- repListExp (MkC es) = rep2 listEName [es] -- repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ) -- repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t] -- repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ) -- repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs] -- repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ) -- repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs] -- repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp)) -- repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x] -- repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z] -- repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y] -- repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y] -- ------------ Right hand sides (guarded expressions) ---- -- repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ) -- repGuarded (MkC pairs) = rep2 guardedBName [pairs] -- repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ) -- repNormal (MkC e) = rep2 normalBName [e] -- ------------ Guards ---- -- repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) -- repLNormalGE g e = do g' <- repLE g -- e' <- repLE e -- repNormalGE g' e' -- repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) -- repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e] -- repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) -- repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e] -- ------------- Stmts ------------------- -- repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ) -- repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e] -- repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ) -- repLetSt (MkC ds) = rep2 letSName [ds] -- repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ) -- repNoBindSt (MkC e) = rep2 noBindSName [e] -- repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ) -- repParSt (MkC sss) = rep2 parSName [sss] -- -------------- Range (Arithmetic sequences) ----------- -- repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repFrom (MkC x) = rep2 fromEName [x] -- repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y] -- repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y] -- repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) -- repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z] -- ------------ Match and Clause Tuples ----------- -- repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ) -- repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds] -- repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ) -- repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds] -- -------------- Dec ----------------------------- -- repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) -- repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds] -- repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ) -- repFun (MkC nm) (MkC b) = rep2 funDName [nm, b] -- repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -- -> Maybe (Core [TH.TypeQ]) -- -> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ) -- repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC cons) (MkC derivs) -- = rep2 dataDName [cxt, nm, tvs, cons, derivs] -- repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC cons) (MkC derivs) -- = rep2 dataInstDName [cxt, nm, tys, cons, derivs] -- repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -- -> Maybe (Core [TH.TypeQ]) -- -> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ) -- repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC con) (MkC derivs) -- = rep2 newtypeDName [cxt, nm, tvs, con, derivs] -- repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC con) (MkC derivs) -- = rep2 newtypeInstDName [cxt, nm, tys, con, derivs] -- repTySyn :: Core TH.Name -> Core [TH.TyVarBndr] -- -> Core TH.TypeQ -> DsM (Core TH.DecQ) -- repTySyn (MkC nm) (MkC tvs) (MkC rhs) -- = rep2 tySynDName [nm, tvs, rhs] -- repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) -- repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds] -- repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -- -> Core [TH.FunDep] -> Core [TH.DecQ] -- -> DsM (Core TH.DecQ) -- repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds) -- = rep2 classDName [cxt, cls, tvs, fds, ds] -- repDeriv :: Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.DecQ) -- repDeriv (MkC cxt) (MkC ty) = rep2 standaloneDerivDName [cxt, ty] -- repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch -- -> Core TH.Phases -> DsM (Core TH.DecQ) -- repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases) -- = rep2 pragInlDName [nm, inline, rm, phases] -- repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases -- -> DsM (Core TH.DecQ) -- repPragSpec (MkC nm) (MkC ty) (MkC phases) -- = rep2 pragSpecDName [nm, ty, phases] -- repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline -- -> Core TH.Phases -> DsM (Core TH.DecQ) -- repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases) -- = rep2 pragSpecInlDName [nm, ty, inline, phases] -- repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ) -- repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty] -- repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ -- -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ) -- repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases) -- = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases] -- repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ) -- repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e] -- repFamilyNoKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -- -> DsM (Core TH.DecQ) -- repFamilyNoKind (MkC flav) (MkC nm) (MkC tvs) -- = rep2 familyNoKindDName [flav, nm, tvs] -- repFamilyKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -- -> Core TH.Kind -- -> DsM (Core TH.DecQ) -- repFamilyKind (MkC flav) (MkC nm) (MkC tvs) (MkC ki) -- = rep2 familyKindDName [flav, nm, tvs, ki] -- repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ) -- repTySynInst (MkC nm) (MkC eqn) -- = rep2 tySynInstDName [nm, eqn] -- repClosedFamilyNoKind :: Core TH.Name -- -> Core [TH.TyVarBndr] -- -> Core [TH.TySynEqnQ] -- -> DsM (Core TH.DecQ) -- repClosedFamilyNoKind (MkC nm) (MkC tvs) (MkC eqns) -- = rep2 closedTypeFamilyNoKindDName [nm, tvs, eqns] -- repClosedFamilyKind :: Core TH.Name -- -> Core [TH.TyVarBndr] -- -> Core TH.Kind -- -> Core [TH.TySynEqnQ] -- -> DsM (Core TH.DecQ) -- repClosedFamilyKind (MkC nm) (MkC tvs) (MkC ki) (MkC eqns) -- = rep2 closedTypeFamilyKindDName [nm, tvs, ki, eqns] -- repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ) -- repTySynEqn (MkC lhs) (MkC rhs) -- = rep2 tySynEqnName [lhs, rhs] -- repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ) -- repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles] -- repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep) -- repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys] -- repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ) -- repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty] -- repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ) -- repCtxt (MkC tys) = rep2 cxtName [tys] -- repConstr :: Core TH.Name -> HsConDeclDetails Name -- -> DsM (Core TH.ConQ) -- repConstr con (PrefixCon ps) -- = do arg_tys <- repList strictTypeQTyConName repBangTy ps -- rep2 normalCName [unC con, unC arg_tys] -- repConstr con (RecCon (L _ ips)) -- = do { args <- concatMapM rep_ip ips -- ; arg_vtys <- coreList varStrictTypeQTyConName args -- ; rep2 recCName [unC con, unC arg_vtys] } -- where -- rep_ip (L _ ip) = mapM (rep_one_ip (cd_fld_type ip)) (cd_fld_names ip) -- rep_one_ip t n = do { MkC v <- lookupLOcc n -- ; MkC ty <- repBangTy t -- ; rep2 varStrictTypeName [v,ty] } -- repConstr con (InfixCon st1 st2) -- = do arg1 <- repBangTy st1 -- arg2 <- repBangTy st2 -- rep2 infixCName [unC arg1, unC con, unC arg2] -- ------------ Types ------------------- -- repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ -- -> DsM (Core TH.TypeQ) -- repTForall (MkC tvars) (MkC ctxt) (MkC ty) -- = rep2 forallTName [tvars, ctxt, ty] -- repTvar :: Core TH.Name -> DsM (Core TH.TypeQ) -- repTvar (MkC s) = rep2 varTName [s] -- repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) -- repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2] -- repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ) -- repTapps f [] = return f -- repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts } -- repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ) -- repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki] -- repTequality :: DsM (Core TH.TypeQ) -- repTequality = rep2 equalityTName [] -- repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ) -- repTPromotedList [] = repPromotedNilTyCon -- repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon -- ; f <- repTapp tcon t -- ; t' <- repTPromotedList ts -- ; repTapp f t' -- } -- repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ) -- repTLit (MkC lit) = rep2 litTName [lit] -- --------- Type constructors -------------- -- repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) -- repNamedTyCon (MkC s) = rep2 conTName [s] -- repTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- -- Note: not Core Int; it's easier to be direct here -- repTupleTyCon i = do dflags <- getDynFlags -- rep2 tupleTName [mkIntExprInt dflags i] -- repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- -- Note: not Core Int; it's easier to be direct here -- repUnboxedTupleTyCon i = do dflags <- getDynFlags -- rep2 unboxedTupleTName [mkIntExprInt dflags i] -- repArrowTyCon :: DsM (Core TH.TypeQ) -- repArrowTyCon = rep2 arrowTName [] -- repListTyCon :: DsM (Core TH.TypeQ) -- repListTyCon = rep2 listTName [] -- repPromotedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) -- repPromotedTyCon (MkC s) = rep2 promotedTName [s] -- repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- repPromotedTupleTyCon i = do dflags <- getDynFlags -- rep2 promotedTupleTName [mkIntExprInt dflags i] -- repPromotedNilTyCon :: DsM (Core TH.TypeQ) -- repPromotedNilTyCon = rep2 promotedNilTName [] -- repPromotedConsTyCon :: DsM (Core TH.TypeQ) -- repPromotedConsTyCon = rep2 promotedConsTName [] -- ------------ Kinds ------------------- -- repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr) -- repPlainTV (MkC nm) = rep2 plainTVName [nm] -- repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr) -- repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki] -- repKVar :: Core TH.Name -> DsM (Core TH.Kind) -- repKVar (MkC s) = rep2 varKName [s] -- repKCon :: Core TH.Name -> DsM (Core TH.Kind) -- repKCon (MkC s) = rep2 conKName [s] -- repKTuple :: Int -> DsM (Core TH.Kind) -- repKTuple i = do dflags <- getDynFlags -- rep2 tupleKName [mkIntExprInt dflags i] -- repKArrow :: DsM (Core TH.Kind) -- repKArrow = rep2 arrowKName [] -- repKList :: DsM (Core TH.Kind) -- repKList = rep2 listKName [] -- repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind) -- repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2] -- repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind) -- repKApps f [] = return f -- repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks } -- repKStar :: DsM (Core TH.Kind) -- repKStar = rep2 starKName [] -- repKConstraint :: DsM (Core TH.Kind) -- repKConstraint = rep2 constraintKName [] -- ---------------------------------------------------------- -- -- Literals -- repLiteral :: HsLit -> DsM (Core TH.Lit) -- repLiteral lit -- = do lit' <- case lit of -- HsIntPrim _ i -> mk_integer i -- HsWordPrim _ w -> mk_integer w -- HsInt _ i -> mk_integer i -- HsFloatPrim r -> mk_rational r -- HsDoublePrim r -> mk_rational r -- _ -> return lit -- lit_expr <- dsLit lit' -- case mb_lit_name of -- Just lit_name -> rep2 lit_name [lit_expr] -- Nothing -> notHandled "Exotic literal" (ppr lit) -- where -- mb_lit_name = case lit of -- HsInteger _ _ _ -> Just integerLName -- HsInt _ _ -> Just integerLName -- HsIntPrim _ _ -> Just intPrimLName -- HsWordPrim _ _ -> Just wordPrimLName -- HsFloatPrim _ -> Just floatPrimLName -- HsDoublePrim _ -> Just doublePrimLName -- HsChar _ _ -> Just charLName -- HsString _ _ -> Just stringLName -- HsRat _ _ -> Just rationalLName -- _ -> Nothing -- mk_integer :: Integer -> DsM HsLit -- mk_integer i = do integer_ty <- lookupType integerTyConName -- return $ HsInteger "" i integer_ty -- mk_rational :: FractionalLit -> DsM HsLit -- mk_rational r = do rat_ty <- lookupType rationalTyConName -- return $ HsRat r rat_ty -- mk_string :: FastString -> DsM HsLit -- mk_string s = return $ HsString "" s -- repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit) -- repOverloadedLiteral (OverLit { ol_val = val}) -- = do { lit <- mk_lit val; repLiteral lit } -- -- The type Rational will be in the environment, because -- -- the smart constructor 'TH.Syntax.rationalL' uses it in its type, -- -- and rationalL is sucked in when any TH stuff is used -- mk_lit :: OverLitVal -> DsM HsLit -- mk_lit (HsIntegral _ i) = mk_integer i -- mk_lit (HsFractional f) = mk_rational f -- mk_lit (HsIsString _ s) = mk_string s -- --------------- Miscellaneous ------------------- -- repGensym :: Core String -> DsM (Core (TH.Q TH.Name)) -- repGensym (MkC lit_str) = rep2 newNameName [lit_str] -- repBindQ :: Type -> Type -- a and b -- -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b)) -- repBindQ ty_a ty_b (MkC x) (MkC y) -- = rep2 bindQName [Type ty_a, Type ty_b, x, y] -- repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a])) -- repSequenceQ ty_a (MkC list) -- = rep2 sequenceQName [Type ty_a, list] -- ------------ Lists and Tuples ------------------- -- -- turn a list of patterns into a single pattern matching a list -- repList :: Name -> (a -> DsM (Core b)) -- -> [a] -> DsM (Core [b]) -- repList tc_name f args -- = do { args1 <- mapM f args -- ; coreList tc_name args1 } -- coreList :: Name -- Of the TyCon of the element type -- -> [Core a] -> DsM (Core [a]) -- coreList tc_name es -- = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) } -- coreList' :: Type -- The element type -- -> [Core a] -> Core [a] -- coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es )) -- nonEmptyCoreList :: [Core a] -> Core [a] -- -- The list must be non-empty so we can get the element type -- -- Otherwise use coreList -- nonEmptyCoreList [] = panic "coreList: empty argument" -- nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs)) -- coreStringLit :: String -> DsM (Core String) -- coreStringLit s = do { z <- mkStringExpr s; return(MkC z) } -- ------------ Literals & Variables ------------------- -- coreIntLit :: Int -> DsM (Core Int) -- coreIntLit i = do dflags <- getDynFlags -- return (MkC (mkIntExprInt dflags i)) -- coreVar :: Id -> Core TH.Name -- The Id has type Name -- coreVar id = MkC (Var id) -- ----------------- Failure ----------------------- -- notHandledL :: SrcSpan -> String -> SDoc -> DsM a -- notHandledL loc what doc -- | isGoodSrcSpan loc -- = putSrcSpanDs loc $ notHandled what doc -- | otherwise -- = notHandled what doc -- notHandled :: String -> SDoc -> DsM a -- notHandled what doc = failWithDs msg -- where -- msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell")) -- 2 doc -- -- %************************************************************************ -- -- %* * -- -- The known-key names for Template Haskell -- -- %* * -- -- %************************************************************************ -- -- To add a name, do three things -- -- -- -- 1) Allocate a key -- -- 2) Make a "Name" -- -- 3) Add the name to knownKeyNames -- templateHaskellNames :: [Name] -- -- The names that are implicitly mentioned by ``bracket'' -- -- Should stay in sync with the import list of DsMeta -- templateHaskellNames = [ -- returnQName, bindQName, sequenceQName, newNameName, liftName, -- mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, -- liftStringName, -- unTypeName, -- unTypeQName, -- unsafeTExpCoerceName, -- -- Lit -- charLName, stringLName, integerLName, intPrimLName, wordPrimLName, -- floatPrimLName, doublePrimLName, rationalLName, -- -- Pat -- litPName, varPName, tupPName, unboxedTupPName, -- conPName, tildePName, bangPName, infixPName, -- asPName, wildPName, recPName, listPName, sigPName, viewPName, -- -- FieldPat -- fieldPatName, -- -- Match -- matchName, -- -- Clause -- clauseName, -- -- Exp -- varEName, conEName, litEName, appEName, infixEName, -- infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, -- tupEName, unboxedTupEName, -- condEName, multiIfEName, letEName, caseEName, doEName, compEName, -- fromEName, fromThenEName, fromToEName, fromThenToEName, -- listEName, sigEName, recConEName, recUpdEName, staticEName, -- -- FieldExp -- fieldExpName, -- -- Body -- guardedBName, normalBName, -- -- Guard -- normalGEName, patGEName, -- -- Stmt -- bindSName, letSName, noBindSName, parSName, -- -- Dec -- funDName, valDName, dataDName, newtypeDName, tySynDName, -- classDName, instanceDName, standaloneDerivDName, sigDName, forImpDName, -- pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, -- pragRuleDName, pragAnnDName, defaultSigDName, -- familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName, -- tySynInstDName, closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, -- infixLDName, infixRDName, infixNDName, -- roleAnnotDName, -- -- Cxt -- cxtName, -- -- Strict -- isStrictName, notStrictName, unpackedName, -- -- Con -- normalCName, recCName, infixCName, forallCName, -- -- StrictType -- strictTypeName, -- -- VarStrictType -- varStrictTypeName, -- -- Type -- forallTName, varTName, conTName, appTName, equalityTName, -- tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName, -- promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, -- -- TyLit -- numTyLitName, strTyLitName, -- -- TyVarBndr -- plainTVName, kindedTVName, -- -- Role -- nominalRName, representationalRName, phantomRName, inferRName, -- -- Kind -- varKName, conKName, tupleKName, arrowKName, listKName, appKName, -- starKName, constraintKName, -- -- Callconv -- cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName, -- -- Safety -- unsafeName, -- safeName, -- interruptibleName, -- -- Inline -- noInlineDataConName, inlineDataConName, inlinableDataConName, -- -- RuleMatch -- conLikeDataConName, funLikeDataConName, -- -- Phases -- allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName, -- -- TExp -- tExpDataConName, -- -- RuleBndr -- ruleVarName, typedRuleVarName, -- -- FunDep -- funDepName, -- -- FamFlavour -- typeFamName, dataFamName, -- -- TySynEqn -- tySynEqnName, -- -- AnnTarget -- valueAnnotationName, typeAnnotationName, moduleAnnotationName, -- -- And the tycons -- qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName, -- clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName, -- stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, -- varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName, -- typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, -- patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName, -- predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, -- roleTyConName, tExpTyConName, -- -- Quasiquoting -- quoteDecName, quoteTypeName, quoteExpName, quotePatName] -- thSyn, thLib, qqLib :: Module -- thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax") -- thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib") -- qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote") -- mkTHModule :: FastString -> Module -- mkTHModule m = mkModule thUnitId (mkModuleNameFS m) -- libFun, libTc, thFun, thTc, thCon, qqFun :: FastString -> Unique -> Name -- libFun = mk_known_key_name OccName.varName thLib -- libTc = mk_known_key_name OccName.tcName thLib -- thFun = mk_known_key_name OccName.varName thSyn -- thTc = mk_known_key_name OccName.tcName thSyn -- thCon = mk_known_key_name OccName.dataName thSyn -- qqFun = mk_known_key_name OccName.varName qqLib -- -------------------- TH.Syntax ----------------------- -- qTyConName, nameTyConName, fieldExpTyConName, patTyConName, -- fieldPatTyConName, expTyConName, decTyConName, typeTyConName, -- tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName, -- predTyConName, tExpTyConName :: Name -- qTyConName = thTc (fsLit "Q") qTyConKey -- nameTyConName = thTc (fsLit "Name") nameTyConKey -- fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey -- patTyConName = thTc (fsLit "Pat") patTyConKey -- fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey -- expTyConName = thTc (fsLit "Exp") expTyConKey -- decTyConName = thTc (fsLit "Dec") decTyConKey -- typeTyConName = thTc (fsLit "Type") typeTyConKey -- tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey -- matchTyConName = thTc (fsLit "Match") matchTyConKey -- clauseTyConName = thTc (fsLit "Clause") clauseTyConKey -- funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey -- predTyConName = thTc (fsLit "Pred") predTyConKey -- tExpTyConName = thTc (fsLit "TExp") tExpTyConKey -- returnQName, bindQName, sequenceQName, newNameName, liftName, -- mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, -- mkNameLName, liftStringName, unTypeName, unTypeQName, -- unsafeTExpCoerceName :: Name -- returnQName = thFun (fsLit "returnQ") returnQIdKey -- bindQName = thFun (fsLit "bindQ") bindQIdKey -- sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey -- newNameName = thFun (fsLit "newName") newNameIdKey -- liftName = thFun (fsLit "lift") liftIdKey -- liftStringName = thFun (fsLit "liftString") liftStringIdKey -- mkNameName = thFun (fsLit "mkName") mkNameIdKey -- mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey -- mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey -- mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey -- mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey -- unTypeName = thFun (fsLit "unType") unTypeIdKey -- unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey -- unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey -- -------------------- TH.Lib ----------------------- -- -- data Lit = ... -- charLName, stringLName, integerLName, intPrimLName, wordPrimLName, -- floatPrimLName, doublePrimLName, rationalLName :: Name -- charLName = libFun (fsLit "charL") charLIdKey -- stringLName = libFun (fsLit "stringL") stringLIdKey -- integerLName = libFun (fsLit "integerL") integerLIdKey -- intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey -- wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey -- floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey -- doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey -- rationalLName = libFun (fsLit "rationalL") rationalLIdKey -- -- data Pat = ... -- litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName, -- asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name -- litPName = libFun (fsLit "litP") litPIdKey -- varPName = libFun (fsLit "varP") varPIdKey -- tupPName = libFun (fsLit "tupP") tupPIdKey -- unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey -- conPName = libFun (fsLit "conP") conPIdKey -- infixPName = libFun (fsLit "infixP") infixPIdKey -- tildePName = libFun (fsLit "tildeP") tildePIdKey -- bangPName = libFun (fsLit "bangP") bangPIdKey -- asPName = libFun (fsLit "asP") asPIdKey -- wildPName = libFun (fsLit "wildP") wildPIdKey -- recPName = libFun (fsLit "recP") recPIdKey -- listPName = libFun (fsLit "listP") listPIdKey -- sigPName = libFun (fsLit "sigP") sigPIdKey -- viewPName = libFun (fsLit "viewP") viewPIdKey -- -- type FieldPat = ... -- fieldPatName :: Name -- fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey -- -- data Match = ... -- matchName :: Name -- matchName = libFun (fsLit "match") matchIdKey -- -- data Clause = ... -- clauseName :: Name -- clauseName = libFun (fsLit "clause") clauseIdKey -- -- data Exp = ... -- varEName, conEName, litEName, appEName, infixEName, infixAppName, -- sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, -- unboxedTupEName, condEName, multiIfEName, letEName, caseEName, -- doEName, compEName, staticEName :: Name -- varEName = libFun (fsLit "varE") varEIdKey -- conEName = libFun (fsLit "conE") conEIdKey -- litEName = libFun (fsLit "litE") litEIdKey -- appEName = libFun (fsLit "appE") appEIdKey -- infixEName = libFun (fsLit "infixE") infixEIdKey -- infixAppName = libFun (fsLit "infixApp") infixAppIdKey -- sectionLName = libFun (fsLit "sectionL") sectionLIdKey -- sectionRName = libFun (fsLit "sectionR") sectionRIdKey -- lamEName = libFun (fsLit "lamE") lamEIdKey -- lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey -- tupEName = libFun (fsLit "tupE") tupEIdKey -- unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey -- condEName = libFun (fsLit "condE") condEIdKey -- multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey -- letEName = libFun (fsLit "letE") letEIdKey -- caseEName = libFun (fsLit "caseE") caseEIdKey -- doEName = libFun (fsLit "doE") doEIdKey -- compEName = libFun (fsLit "compE") compEIdKey -- -- ArithSeq skips a level -- fromEName, fromThenEName, fromToEName, fromThenToEName :: Name -- fromEName = libFun (fsLit "fromE") fromEIdKey -- fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey -- fromToEName = libFun (fsLit "fromToE") fromToEIdKey -- fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey -- -- end ArithSeq -- listEName, sigEName, recConEName, recUpdEName :: Name -- listEName = libFun (fsLit "listE") listEIdKey -- sigEName = libFun (fsLit "sigE") sigEIdKey -- recConEName = libFun (fsLit "recConE") recConEIdKey -- recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey -- staticEName = libFun (fsLit "staticE") staticEIdKey -- -- type FieldExp = ... -- fieldExpName :: Name -- fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey -- -- data Body = ... -- guardedBName, normalBName :: Name -- guardedBName = libFun (fsLit "guardedB") guardedBIdKey -- normalBName = libFun (fsLit "normalB") normalBIdKey -- -- data Guard = ... -- normalGEName, patGEName :: Name -- normalGEName = libFun (fsLit "normalGE") normalGEIdKey -- patGEName = libFun (fsLit "patGE") patGEIdKey -- -- data Stmt = ... -- bindSName, letSName, noBindSName, parSName :: Name -- bindSName = libFun (fsLit "bindS") bindSIdKey -- letSName = libFun (fsLit "letS") letSIdKey -- noBindSName = libFun (fsLit "noBindS") noBindSIdKey -- parSName = libFun (fsLit "parS") parSIdKey -- -- data Dec = ... -- funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, -- instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName, -- pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, -- familyNoKindDName, standaloneDerivDName, defaultSigDName, -- familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName, -- closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, -- infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name -- funDName = libFun (fsLit "funD") funDIdKey -- valDName = libFun (fsLit "valD") valDIdKey -- dataDName = libFun (fsLit "dataD") dataDIdKey -- newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey -- tySynDName = libFun (fsLit "tySynD") tySynDIdKey -- classDName = libFun (fsLit "classD") classDIdKey -- instanceDName = libFun (fsLit "instanceD") instanceDIdKey -- standaloneDerivDName -- = libFun (fsLit "standaloneDerivD") standaloneDerivDIdKey -- sigDName = libFun (fsLit "sigD") sigDIdKey -- defaultSigDName = libFun (fsLit "defaultSigD") defaultSigDIdKey -- forImpDName = libFun (fsLit "forImpD") forImpDIdKey -- pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey -- pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey -- pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey -- pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey -- pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey -- pragAnnDName = libFun (fsLit "pragAnnD") pragAnnDIdKey -- familyNoKindDName = libFun (fsLit "familyNoKindD") familyNoKindDIdKey -- familyKindDName = libFun (fsLit "familyKindD") familyKindDIdKey -- dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey -- newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey -- tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey -- closedTypeFamilyKindDName -- = libFun (fsLit "closedTypeFamilyKindD") closedTypeFamilyKindDIdKey -- closedTypeFamilyNoKindDName -- = libFun (fsLit "closedTypeFamilyNoKindD") closedTypeFamilyNoKindDIdKey -- infixLDName = libFun (fsLit "infixLD") infixLDIdKey -- infixRDName = libFun (fsLit "infixRD") infixRDIdKey -- infixNDName = libFun (fsLit "infixND") infixNDIdKey -- roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey -- -- type Ctxt = ... -- cxtName :: Name -- cxtName = libFun (fsLit "cxt") cxtIdKey -- -- data Strict = ... -- isStrictName, notStrictName, unpackedName :: Name -- isStrictName = libFun (fsLit "isStrict") isStrictKey -- notStrictName = libFun (fsLit "notStrict") notStrictKey -- unpackedName = libFun (fsLit "unpacked") unpackedKey -- -- data Con = ... -- normalCName, recCName, infixCName, forallCName :: Name -- normalCName = libFun (fsLit "normalC") normalCIdKey -- recCName = libFun (fsLit "recC") recCIdKey -- infixCName = libFun (fsLit "infixC") infixCIdKey -- forallCName = libFun (fsLit "forallC") forallCIdKey -- -- type StrictType = ... -- strictTypeName :: Name -- strictTypeName = libFun (fsLit "strictType") strictTKey -- -- type VarStrictType = ... -- varStrictTypeName :: Name -- varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey -- -- data Type = ... -- forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName, -- listTName, appTName, sigTName, equalityTName, litTName, -- promotedTName, promotedTupleTName, -- promotedNilTName, promotedConsTName :: Name -- forallTName = libFun (fsLit "forallT") forallTIdKey -- varTName = libFun (fsLit "varT") varTIdKey -- conTName = libFun (fsLit "conT") conTIdKey -- tupleTName = libFun (fsLit "tupleT") tupleTIdKey -- unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey -- arrowTName = libFun (fsLit "arrowT") arrowTIdKey -- listTName = libFun (fsLit "listT") listTIdKey -- appTName = libFun (fsLit "appT") appTIdKey -- sigTName = libFun (fsLit "sigT") sigTIdKey -- equalityTName = libFun (fsLit "equalityT") equalityTIdKey -- litTName = libFun (fsLit "litT") litTIdKey -- promotedTName = libFun (fsLit "promotedT") promotedTIdKey -- promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey -- promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey -- promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey -- -- data TyLit = ... -- numTyLitName, strTyLitName :: Name -- numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey -- strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey -- -- data TyVarBndr = ... -- plainTVName, kindedTVName :: Name -- plainTVName = libFun (fsLit "plainTV") plainTVIdKey -- kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey -- -- data Role = ... -- nominalRName, representationalRName, phantomRName, inferRName :: Name -- nominalRName = libFun (fsLit "nominalR") nominalRIdKey -- representationalRName = libFun (fsLit "representationalR") representationalRIdKey -- phantomRName = libFun (fsLit "phantomR") phantomRIdKey -- inferRName = libFun (fsLit "inferR") inferRIdKey -- -- data Kind = ... -- varKName, conKName, tupleKName, arrowKName, listKName, appKName, -- starKName, constraintKName :: Name -- varKName = libFun (fsLit "varK") varKIdKey -- conKName = libFun (fsLit "conK") conKIdKey -- tupleKName = libFun (fsLit "tupleK") tupleKIdKey -- arrowKName = libFun (fsLit "arrowK") arrowKIdKey -- listKName = libFun (fsLit "listK") listKIdKey -- appKName = libFun (fsLit "appK") appKIdKey -- starKName = libFun (fsLit "starK") starKIdKey -- constraintKName = libFun (fsLit "constraintK") constraintKIdKey -- -- data Callconv = ... -- cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName :: Name -- cCallName = libFun (fsLit "cCall") cCallIdKey -- stdCallName = libFun (fsLit "stdCall") stdCallIdKey -- cApiCallName = libFun (fsLit "cApi") cApiCallIdKey -- primCallName = libFun (fsLit "prim") primCallIdKey -- javaScriptCallName = libFun (fsLit "javaScript") javaScriptCallIdKey -- -- data Safety = ... -- unsafeName, safeName, interruptibleName :: Name -- unsafeName = libFun (fsLit "unsafe") unsafeIdKey -- safeName = libFun (fsLit "safe") safeIdKey -- interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey -- -- data Inline = ... -- noInlineDataConName, inlineDataConName, inlinableDataConName :: Name -- noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey -- inlineDataConName = thCon (fsLit "Inline") inlineDataConKey -- inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey -- -- data RuleMatch = ... -- conLikeDataConName, funLikeDataConName :: Name -- conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey -- funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey -- -- data Phases = ... -- allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name -- allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey -- fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey -- beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey -- -- newtype TExp a = ... -- tExpDataConName :: Name -- tExpDataConName = thCon (fsLit "TExp") tExpDataConKey -- -- data RuleBndr = ... -- ruleVarName, typedRuleVarName :: Name -- ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey -- typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey -- -- data FunDep = ... -- funDepName :: Name -- funDepName = libFun (fsLit "funDep") funDepIdKey -- -- data FamFlavour = ... -- typeFamName, dataFamName :: Name -- typeFamName = libFun (fsLit "typeFam") typeFamIdKey -- dataFamName = libFun (fsLit "dataFam") dataFamIdKey -- -- data TySynEqn = ... -- tySynEqnName :: Name -- tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey -- -- data AnnTarget = ... -- valueAnnotationName, typeAnnotationName, moduleAnnotationName :: Name -- valueAnnotationName = libFun (fsLit "valueAnnotation") valueAnnotationIdKey -- typeAnnotationName = libFun (fsLit "typeAnnotation") typeAnnotationIdKey -- moduleAnnotationName = libFun (fsLit "moduleAnnotation") moduleAnnotationIdKey -- matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName, -- decQTyConName, conQTyConName, strictTypeQTyConName, -- varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName, -- patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName, -- ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name -- matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey -- clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey -- expQTyConName = libTc (fsLit "ExpQ") expQTyConKey -- stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey -- decQTyConName = libTc (fsLit "DecQ") decQTyConKey -- decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec] -- conQTyConName = libTc (fsLit "ConQ") conQTyConKey -- strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey -- varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey -- typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey -- fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey -- patQTyConName = libTc (fsLit "PatQ") patQTyConKey -- fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey -- predQTyConName = libTc (fsLit "PredQ") predQTyConKey -- ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey -- tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey -- roleTyConName = libTc (fsLit "Role") roleTyConKey -- -- quasiquoting -- quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name -- quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey -- quotePatName = qqFun (fsLit "quotePat") quotePatKey -- quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey -- quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey -- -- TyConUniques available: 200-299 -- -- Check in PrelNames if you want to change this -- expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey, -- decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey, -- stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey, -- decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey, -- fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey, -- fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey, -- predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey, -- roleTyConKey, tExpTyConKey :: Unique -- expTyConKey = mkPreludeTyConUnique 200 -- matchTyConKey = mkPreludeTyConUnique 201 -- clauseTyConKey = mkPreludeTyConUnique 202 -- qTyConKey = mkPreludeTyConUnique 203 -- expQTyConKey = mkPreludeTyConUnique 204 -- decQTyConKey = mkPreludeTyConUnique 205 -- patTyConKey = mkPreludeTyConUnique 206 -- matchQTyConKey = mkPreludeTyConUnique 207 -- clauseQTyConKey = mkPreludeTyConUnique 208 -- stmtQTyConKey = mkPreludeTyConUnique 209 -- conQTyConKey = mkPreludeTyConUnique 210 -- typeQTyConKey = mkPreludeTyConUnique 211 -- typeTyConKey = mkPreludeTyConUnique 212 -- decTyConKey = mkPreludeTyConUnique 213 -- varStrictTypeQTyConKey = mkPreludeTyConUnique 214 -- strictTypeQTyConKey = mkPreludeTyConUnique 215 -- fieldExpTyConKey = mkPreludeTyConUnique 216 -- fieldPatTyConKey = mkPreludeTyConUnique 217 -- nameTyConKey = mkPreludeTyConUnique 218 -- patQTyConKey = mkPreludeTyConUnique 219 -- fieldPatQTyConKey = mkPreludeTyConUnique 220 -- fieldExpQTyConKey = mkPreludeTyConUnique 221 -- funDepTyConKey = mkPreludeTyConUnique 222 -- predTyConKey = mkPreludeTyConUnique 223 -- predQTyConKey = mkPreludeTyConUnique 224 -- tyVarBndrTyConKey = mkPreludeTyConUnique 225 -- decsQTyConKey = mkPreludeTyConUnique 226 -- ruleBndrQTyConKey = mkPreludeTyConUnique 227 -- tySynEqnQTyConKey = mkPreludeTyConUnique 228 -- roleTyConKey = mkPreludeTyConUnique 229 -- tExpTyConKey = mkPreludeTyConUnique 230 -- -- IdUniques available: 200-499 -- -- If you want to change this, make sure you check in PrelNames -- returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey, -- mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey, -- mkNameLIdKey, unTypeIdKey, unTypeQIdKey, unsafeTExpCoerceIdKey :: Unique -- returnQIdKey = mkPreludeMiscIdUnique 200 -- bindQIdKey = mkPreludeMiscIdUnique 201 -- sequenceQIdKey = mkPreludeMiscIdUnique 202 -- liftIdKey = mkPreludeMiscIdUnique 203 -- newNameIdKey = mkPreludeMiscIdUnique 204 -- mkNameIdKey = mkPreludeMiscIdUnique 205 -- mkNameG_vIdKey = mkPreludeMiscIdUnique 206 -- mkNameG_dIdKey = mkPreludeMiscIdUnique 207 -- mkNameG_tcIdKey = mkPreludeMiscIdUnique 208 -- mkNameLIdKey = mkPreludeMiscIdUnique 209 -- unTypeIdKey = mkPreludeMiscIdUnique 210 -- unTypeQIdKey = mkPreludeMiscIdUnique 211 -- unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 212 -- -- data Lit = ... -- charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey, -- floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique -- charLIdKey = mkPreludeMiscIdUnique 220 -- stringLIdKey = mkPreludeMiscIdUnique 221 -- integerLIdKey = mkPreludeMiscIdUnique 222 -- intPrimLIdKey = mkPreludeMiscIdUnique 223 -- wordPrimLIdKey = mkPreludeMiscIdUnique 224 -- floatPrimLIdKey = mkPreludeMiscIdUnique 225 -- doublePrimLIdKey = mkPreludeMiscIdUnique 226 -- rationalLIdKey = mkPreludeMiscIdUnique 227 -- liftStringIdKey :: Unique -- liftStringIdKey = mkPreludeMiscIdUnique 228 -- -- data Pat = ... -- litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey, -- asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique -- litPIdKey = mkPreludeMiscIdUnique 240 -- varPIdKey = mkPreludeMiscIdUnique 241 -- tupPIdKey = mkPreludeMiscIdUnique 242 -- unboxedTupPIdKey = mkPreludeMiscIdUnique 243 -- conPIdKey = mkPreludeMiscIdUnique 244 -- infixPIdKey = mkPreludeMiscIdUnique 245 -- tildePIdKey = mkPreludeMiscIdUnique 246 -- bangPIdKey = mkPreludeMiscIdUnique 247 -- asPIdKey = mkPreludeMiscIdUnique 248 -- wildPIdKey = mkPreludeMiscIdUnique 249 -- recPIdKey = mkPreludeMiscIdUnique 250 -- listPIdKey = mkPreludeMiscIdUnique 251 -- sigPIdKey = mkPreludeMiscIdUnique 252 -- viewPIdKey = mkPreludeMiscIdUnique 253 -- -- type FieldPat = ... -- fieldPatIdKey :: Unique -- fieldPatIdKey = mkPreludeMiscIdUnique 260 -- -- data Match = ... -- matchIdKey :: Unique -- matchIdKey = mkPreludeMiscIdUnique 261 -- -- data Clause = ... -- clauseIdKey :: Unique -- clauseIdKey = mkPreludeMiscIdUnique 262 -- -- data Exp = ... -- varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey, -- sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey, -- unboxedTupEIdKey, condEIdKey, multiIfEIdKey, -- letEIdKey, caseEIdKey, doEIdKey, compEIdKey, -- fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey, -- listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey, staticEIdKey :: Unique -- varEIdKey = mkPreludeMiscIdUnique 270 -- conEIdKey = mkPreludeMiscIdUnique 271 -- litEIdKey = mkPreludeMiscIdUnique 272 -- appEIdKey = mkPreludeMiscIdUnique 273 -- infixEIdKey = mkPreludeMiscIdUnique 274 -- infixAppIdKey = mkPreludeMiscIdUnique 275 -- sectionLIdKey = mkPreludeMiscIdUnique 276 -- sectionRIdKey = mkPreludeMiscIdUnique 277 -- lamEIdKey = mkPreludeMiscIdUnique 278 -- lamCaseEIdKey = mkPreludeMiscIdUnique 279 -- tupEIdKey = mkPreludeMiscIdUnique 280 -- unboxedTupEIdKey = mkPreludeMiscIdUnique 281 -- condEIdKey = mkPreludeMiscIdUnique 282 -- multiIfEIdKey = mkPreludeMiscIdUnique 283 -- letEIdKey = mkPreludeMiscIdUnique 284 -- caseEIdKey = mkPreludeMiscIdUnique 285 -- doEIdKey = mkPreludeMiscIdUnique 286 -- compEIdKey = mkPreludeMiscIdUnique 287 -- fromEIdKey = mkPreludeMiscIdUnique 288 -- fromThenEIdKey = mkPreludeMiscIdUnique 289 -- fromToEIdKey = mkPreludeMiscIdUnique 290 -- fromThenToEIdKey = mkPreludeMiscIdUnique 291 -- listEIdKey = mkPreludeMiscIdUnique 292 -- sigEIdKey = mkPreludeMiscIdUnique 293 -- recConEIdKey = mkPreludeMiscIdUnique 294 -- recUpdEIdKey = mkPreludeMiscIdUnique 295 -- staticEIdKey = mkPreludeMiscIdUnique 296 -- -- type FieldExp = ... -- fieldExpIdKey :: Unique -- fieldExpIdKey = mkPreludeMiscIdUnique 310 -- -- data Body = ... -- guardedBIdKey, normalBIdKey :: Unique -- guardedBIdKey = mkPreludeMiscIdUnique 311 -- normalBIdKey = mkPreludeMiscIdUnique 312 -- -- data Guard = ... -- normalGEIdKey, patGEIdKey :: Unique -- normalGEIdKey = mkPreludeMiscIdUnique 313 -- patGEIdKey = mkPreludeMiscIdUnique 314 -- -- data Stmt = ... -- bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique -- bindSIdKey = mkPreludeMiscIdUnique 320 -- letSIdKey = mkPreludeMiscIdUnique 321 -- noBindSIdKey = mkPreludeMiscIdUnique 322 -- parSIdKey = mkPreludeMiscIdUnique 323 -- -- data Dec = ... -- funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey, -- classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey, -- pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey, -- pragAnnDIdKey, familyNoKindDIdKey, familyKindDIdKey, defaultSigDIdKey, -- dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey, standaloneDerivDIdKey, -- closedTypeFamilyKindDIdKey, closedTypeFamilyNoKindDIdKey, -- infixLDIdKey, infixRDIdKey, infixNDIdKey, roleAnnotDIdKey :: Unique -- funDIdKey = mkPreludeMiscIdUnique 330 -- valDIdKey = mkPreludeMiscIdUnique 331 -- dataDIdKey = mkPreludeMiscIdUnique 332 -- newtypeDIdKey = mkPreludeMiscIdUnique 333 -- tySynDIdKey = mkPreludeMiscIdUnique 334 -- classDIdKey = mkPreludeMiscIdUnique 335 -- instanceDIdKey = mkPreludeMiscIdUnique 336 -- sigDIdKey = mkPreludeMiscIdUnique 337 -- forImpDIdKey = mkPreludeMiscIdUnique 338 -- pragInlDIdKey = mkPreludeMiscIdUnique 339 -- pragSpecDIdKey = mkPreludeMiscIdUnique 340 -- pragSpecInlDIdKey = mkPreludeMiscIdUnique 341 -- pragSpecInstDIdKey = mkPreludeMiscIdUnique 342 -- pragRuleDIdKey = mkPreludeMiscIdUnique 343 -- pragAnnDIdKey = mkPreludeMiscIdUnique 344 -- familyNoKindDIdKey = mkPreludeMiscIdUnique 345 -- familyKindDIdKey = mkPreludeMiscIdUnique 346 -- dataInstDIdKey = mkPreludeMiscIdUnique 347 -- newtypeInstDIdKey = mkPreludeMiscIdUnique 348 -- tySynInstDIdKey = mkPreludeMiscIdUnique 349 -- closedTypeFamilyKindDIdKey = mkPreludeMiscIdUnique 350 -- closedTypeFamilyNoKindDIdKey = mkPreludeMiscIdUnique 351 -- infixLDIdKey = mkPreludeMiscIdUnique 352 -- infixRDIdKey = mkPreludeMiscIdUnique 353 -- infixNDIdKey = mkPreludeMiscIdUnique 354 -- roleAnnotDIdKey = mkPreludeMiscIdUnique 355 -- standaloneDerivDIdKey = mkPreludeMiscIdUnique 356 -- defaultSigDIdKey = mkPreludeMiscIdUnique 357 -- -- type Cxt = ... -- cxtIdKey :: Unique -- cxtIdKey = mkPreludeMiscIdUnique 360 -- -- data Strict = ... -- isStrictKey, notStrictKey, unpackedKey :: Unique -- isStrictKey = mkPreludeMiscIdUnique 363 -- notStrictKey = mkPreludeMiscIdUnique 364 -- unpackedKey = mkPreludeMiscIdUnique 365 -- -- data Con = ... -- normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique -- normalCIdKey = mkPreludeMiscIdUnique 370 -- recCIdKey = mkPreludeMiscIdUnique 371 -- infixCIdKey = mkPreludeMiscIdUnique 372 -- forallCIdKey = mkPreludeMiscIdUnique 373 -- -- type StrictType = ... -- strictTKey :: Unique -- strictTKey = mkPreludeMiscIdUnique 374 -- -- type VarStrictType = ... -- varStrictTKey :: Unique -- varStrictTKey = mkPreludeMiscIdUnique 375 -- -- data Type = ... -- forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey, -- listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey, -- promotedTIdKey, promotedTupleTIdKey, -- promotedNilTIdKey, promotedConsTIdKey :: Unique -- forallTIdKey = mkPreludeMiscIdUnique 380 -- varTIdKey = mkPreludeMiscIdUnique 381 -- conTIdKey = mkPreludeMiscIdUnique 382 -- tupleTIdKey = mkPreludeMiscIdUnique 383 -- unboxedTupleTIdKey = mkPreludeMiscIdUnique 384 -- arrowTIdKey = mkPreludeMiscIdUnique 385 -- listTIdKey = mkPreludeMiscIdUnique 386 -- appTIdKey = mkPreludeMiscIdUnique 387 -- sigTIdKey = mkPreludeMiscIdUnique 388 -- equalityTIdKey = mkPreludeMiscIdUnique 389 -- litTIdKey = mkPreludeMiscIdUnique 390 -- promotedTIdKey = mkPreludeMiscIdUnique 391 -- promotedTupleTIdKey = mkPreludeMiscIdUnique 392 -- promotedNilTIdKey = mkPreludeMiscIdUnique 393 -- promotedConsTIdKey = mkPreludeMiscIdUnique 394 -- -- data TyLit = ... -- numTyLitIdKey, strTyLitIdKey :: Unique -- numTyLitIdKey = mkPreludeMiscIdUnique 395 -- strTyLitIdKey = mkPreludeMiscIdUnique 396 -- -- data TyVarBndr = ... -- plainTVIdKey, kindedTVIdKey :: Unique -- plainTVIdKey = mkPreludeMiscIdUnique 397 -- kindedTVIdKey = mkPreludeMiscIdUnique 398 -- -- data Role = ... -- nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique -- nominalRIdKey = mkPreludeMiscIdUnique 400 -- representationalRIdKey = mkPreludeMiscIdUnique 401 -- phantomRIdKey = mkPreludeMiscIdUnique 402 -- inferRIdKey = mkPreludeMiscIdUnique 403 -- -- data Kind = ... -- varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey, -- starKIdKey, constraintKIdKey :: Unique -- varKIdKey = mkPreludeMiscIdUnique 404 -- conKIdKey = mkPreludeMiscIdUnique 405 -- tupleKIdKey = mkPreludeMiscIdUnique 406 -- arrowKIdKey = mkPreludeMiscIdUnique 407 -- listKIdKey = mkPreludeMiscIdUnique 408 -- appKIdKey = mkPreludeMiscIdUnique 409 -- starKIdKey = mkPreludeMiscIdUnique 410 -- constraintKIdKey = mkPreludeMiscIdUnique 411 -- -- data Callconv = ... -- cCallIdKey, stdCallIdKey, cApiCallIdKey, primCallIdKey, -- javaScriptCallIdKey :: Unique -- cCallIdKey = mkPreludeMiscIdUnique 420 -- stdCallIdKey = mkPreludeMiscIdUnique 421 -- cApiCallIdKey = mkPreludeMiscIdUnique 422 -- primCallIdKey = mkPreludeMiscIdUnique 423 -- javaScriptCallIdKey = mkPreludeMiscIdUnique 424 -- -- data Safety = ... -- unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique -- unsafeIdKey = mkPreludeMiscIdUnique 430 -- safeIdKey = mkPreludeMiscIdUnique 431 -- interruptibleIdKey = mkPreludeMiscIdUnique 432 -- -- data Inline = ... -- noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique -- noInlineDataConKey = mkPreludeDataConUnique 40 -- inlineDataConKey = mkPreludeDataConUnique 41 -- inlinableDataConKey = mkPreludeDataConUnique 42 -- -- data RuleMatch = ... -- conLikeDataConKey, funLikeDataConKey :: Unique -- conLikeDataConKey = mkPreludeDataConUnique 43 -- funLikeDataConKey = mkPreludeDataConUnique 44 -- -- data Phases = ... -- allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique -- allPhasesDataConKey = mkPreludeDataConUnique 45 -- fromPhaseDataConKey = mkPreludeDataConUnique 46 -- beforePhaseDataConKey = mkPreludeDataConUnique 47 -- -- newtype TExp a = ... -- tExpDataConKey :: Unique -- tExpDataConKey = mkPreludeDataConUnique 48 -- -- data FunDep = ... -- funDepIdKey :: Unique -- funDepIdKey = mkPreludeMiscIdUnique 440 -- -- data FamFlavour = ... -- typeFamIdKey, dataFamIdKey :: Unique -- typeFamIdKey = mkPreludeMiscIdUnique 450 -- dataFamIdKey = mkPreludeMiscIdUnique 451 -- -- data TySynEqn = ... -- tySynEqnIdKey :: Unique -- tySynEqnIdKey = mkPreludeMiscIdUnique 460 -- -- quasiquoting -- quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique -- quoteExpKey = mkPreludeMiscIdUnique 470 -- quotePatKey = mkPreludeMiscIdUnique 471 -- quoteDecKey = mkPreludeMiscIdUnique 472 -- quoteTypeKey = mkPreludeMiscIdUnique 473 -- -- data RuleBndr = ... -- ruleVarIdKey, typedRuleVarIdKey :: Unique -- ruleVarIdKey = mkPreludeMiscIdUnique 480 -- typedRuleVarIdKey = mkPreludeMiscIdUnique 481 -- -- data AnnTarget = ... -- valueAnnotationIdKey, typeAnnotationIdKey, moduleAnnotationIdKey :: Unique -- valueAnnotationIdKey = mkPreludeMiscIdUnique 490 -- typeAnnotationIdKey = mkPreludeMiscIdUnique 491 -- moduleAnnotationIdKey = mkPreludeMiscIdUnique 492
pparkkin/eta
compiler/ETA/DeSugar/DsMeta.hs
bsd-3-clause
128,511
0
3
35,123
2,508
2,506
2
1
0
{-# LANGUAGE TupleSections #-} foo = do liftIO $ atomicModifyIORef ciTokens ((,()) . f) liftIO $ atomicModifyIORef ciTokens (((),) . f) liftIO $ atomicModifyIORef ciTokens ((,) . f) -- | Make bilateral dictionary from PoliMorf. mkPoli :: [P.Entry] -> Poli mkPoli = mkBila . map ((,,(),,()) <$> P.base <*> P.pos <*> P.form) foo = baz where _1 = ((,Nothing,Nothing,Nothing,Nothing,Nothing) . Just <$>) _2 = ((Nothing,,Nothing,Nothing,Nothing,Nothing) . Just <$>) _3 = ((Nothing,Nothing,,Nothing,Nothing,Nothing) . Just <$>) _4 = ((Nothing,Nothing,Nothing,,Nothing,Nothing) . Just <$>) _5 = ((Nothing,Nothing,Nothing,Nothing,,Nothing) . Just <$>) _6 = ((Nothing,Nothing,Nothing,Nothing,Nothing,) . Just <$>) foo = (,,(),,,())
mpickering/ghc-exactprint
tests/examples/ghc710/TupleSections.hs
bsd-3-clause
759
3
12
131
350
207
143
15
1
module Graphics.Vty.Widgets.Vim ( VimBindings(..) ) where import Graphics.Vty.Widgets.All import Graphics.Vty.Widgets.HeaderList import Graphics.Vty class VimBindings a where addVimBindings :: (Widget a) -> IO () instance VimBindings (HeaderList a b) where addVimBindings list = do list `onKeyPressed` \_ key _ -> case key of KChar 'j' -> onList list scrollDown >> return True KChar 'k' -> onList list scrollUp >> return True KChar 'g' -> onList list scrollToBeginning >> return True KChar 'G' -> onList list scrollToEnd >> return True _ -> return False instance VimBindings FocusGroup where addVimBindings fg = do fg `onKeyPressed` \_ key _ -> case key of KChar 'h' -> focusPrevious fg >> return True KChar 'l' -> focusNext fg >> return True _ -> return False
hpdeifel/dbus-browser
src/Graphics/Vty/Widgets/Vim.hs
bsd-3-clause
841
0
15
199
289
143
146
21
0
{-# LANGUAGE Haskell98, BangPatterns #-} {-# LINE 1 "Data/ByteString/Search/DFA.hs" #-} {-# LANGUAGE BangPatterns #-} -- | -- Module : Data.ByteString.Search.DFA -- Copyright : Daniel Fischer -- Licence : BSD3 -- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com> -- Stability : Provisional -- Portability : non-portable (BangPatterns) -- -- Fast search of strict 'S.ByteString' values. Breaking, splitting and -- replacing using a deterministic finite automaton. module Data.ByteString.Search.DFA ( -- * Overview -- $overview -- ** Complexity and performance -- $complexity -- ** Partial application -- $partial -- * Finding substrings indices , nonOverlappingIndices -- * Breaking on substrings , breakOn , breakAfter -- * Replacing , replace -- * Splitting , split , splitKeepEnd , splitKeepFront ) where import Data.ByteString.Search.Internal.Utils (automaton) import Data.ByteString.Search.Substitution import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as LI import Data.ByteString.Unsafe (unsafeIndex) import Data.Array.Base (unsafeAt) --import Data.Array.Unboxed import Data.Bits -- $overview -- -- This module provides functions related to searching a substring within -- a string. The searching algorithm uses a deterministic finite automaton -- based on the Knuth-Morris-Pratt algorithm. -- The automaton is implemented as an array of @(patternLength + 1) * &#963;@ -- state transitions, where &#963; is the alphabet size (256), so it is -- only suitable for short enough patterns. -- -- When searching a pattern in a UTF-8-encoded 'S.ByteString', be aware that -- these functions work on bytes, not characters, so the indices are -- byte-offsets, not character offsets. -- $complexity -- -- The time and space complexity of the preprocessing phase is -- /O/(@patternLength * &#963;@). -- The searching phase is /O/(@targetLength@), each target character is -- inspected only once. -- -- In general the functions in this module are slightly faster than the -- corresponding functions using the Knuth-Morris-Pratt algorithm but -- considerably slower than the Boyer-Moore functions. For very short -- patterns or, in the case of 'indices', patterns with a short period -- which occur often, however, times are close to or even below the -- Boyer-Moore times. -- $partial -- -- All functions can usefully be partially applied. Given only a pattern, -- the automaton is constructed only once, allowing efficient re-use. ------------------------------------------------------------------------------ -- Exported Functions -- ------------------------------------------------------------------------------ -- | @'indices'@ finds the starting indices of all possibly overlapping -- occurrences of the pattern in the target string. -- If the pattern is empty, the result is @[0 .. 'length' target]@. {-# INLINE indices #-} indices :: S.ByteString -- ^ Pattern to find -> S.ByteString -- ^ String to search -> [Int] -- ^ Offsets of matches indices = strictSearcher True -- | @'nonOverlappingIndices'@ finds the starting indices of all -- non-overlapping occurrences of the pattern in the target string. -- It is more efficient than removing indices from the list produced -- by 'indices'. {-# INLINE nonOverlappingIndices #-} nonOverlappingIndices :: S.ByteString -- ^ Pattern to find -> S.ByteString -- ^ String to search -> [Int] -- ^ Offsets of matches nonOverlappingIndices = strictSearcher False -- | @'breakOn' pattern target@ splits @target@ at the first occurrence -- of @pattern@. If the pattern does not occur in the target, the -- second component of the result is empty, otherwise it starts with -- @pattern@. If the pattern is empty, the first component is empty. -- -- @ -- 'uncurry' 'S.append' . 'breakOn' pattern = 'id' -- @ breakOn :: S.ByteString -- ^ String to search for -> S.ByteString -- ^ String to search in -> (S.ByteString, S.ByteString) -- ^ Head and tail of string broken at substring breakOn pat = breaker where searcher = strictSearcher False pat breaker str = case searcher str of [] -> (str, S.empty) (i:_) -> S.splitAt i str -- | @'breakAfter' pattern target@ splits @target@ behind the first occurrence -- of @pattern@. An empty second component means that either the pattern -- does not occur in the target or the first occurrence of pattern is at -- the very end of target. To discriminate between those cases, use e.g. -- 'S.isSuffixOf'. -- -- @ -- 'uncurry' 'S.append' . 'breakAfter' pattern = 'id' -- @ breakAfter :: S.ByteString -- ^ String to search for -> S.ByteString -- ^ String to search in -> (S.ByteString, S.ByteString) -- ^ Head and tail of string broken after substring breakAfter pat = breaker where !patLen = S.length pat searcher = strictSearcher False pat breaker str = case searcher str of [] -> (str, S.empty) (i:_) -> S.splitAt (i + patLen) str -- | @'replace' pat sub text@ replaces all (non-overlapping) occurrences of -- @pat@ in @text@ with @sub@. If occurrences of @pat@ overlap, the first -- occurrence that does not overlap with a replaced previous occurrence -- is substituted. Occurrences of @pat@ arising from a substitution -- will not be substituted. For example: -- -- @ -- 'replace' \"ana\" \"olog\" \"banana\" = \"bologna\" -- 'replace' \"ana\" \"o\" \"bananana\" = \"bono\" -- 'replace' \"aab\" \"abaa\" \"aaabb\" = \"aabaab\" -- @ -- -- The result is a /lazy/ 'L.ByteString', -- which is lazily produced, without copying. -- Equality of pattern and substitution is not checked, but -- -- @ -- 'S.concat' . 'L.toChunks' $ 'replace' pat pat text == text -- @ -- -- holds. If the pattern is empty but not the substitution, the result -- is equivalent to (were they 'String's) @'cycle' sub@. -- -- For non-empty @pat@ and @sub@ a strict 'S.ByteString', -- -- @ -- 'L.fromChunks' . 'Data.List.intersperse' sub . 'split' pat = 'replace' pat sub -- @ -- -- and analogous relations hold for other types of @sub@. replace :: Substitution rep => S.ByteString -- ^ Substring to replace -> rep -- ^ Replacement string -> S.ByteString -- ^ String to modify -> L.ByteString -- ^ Lazy result replace pat | S.null pat = \sub -> prependCycle sub . flip LI.chunk LI.Empty | otherwise = let !patLen = S.length pat searcher = strictSearcher False pat repl sub = let {-# NOINLINE subst #-} !subst = substitution sub replacer str | S.null str = [] | otherwise = case searcher str of [] -> [str] (i:_) | i == 0 -> subst $ replacer (S.drop patLen str) | otherwise -> S.take i str : subst (replacer (S.drop (i + patLen) str)) in replacer in \sub -> L.fromChunks . repl sub -- | @'split' pattern target@ splits @target@ at each (non-overlapping) -- occurrence of @pattern@, removing @pattern@. If @pattern@ is empty, -- the result is an infinite list of empty 'S.ByteString's, if @target@ -- is empty but not @pattern@, the result is an empty list, otherwise -- the following relations hold: -- -- @ -- 'S.concat' . 'Data.List.intersperse' pat . 'split' pat = 'id', -- 'length' ('split' pattern target) == -- 'length' ('nonOverlappingIndices' pattern target) + 1, -- @ -- -- no fragment in the result contains an occurrence of @pattern@. split :: S.ByteString -- ^ Pattern to split on -> S.ByteString -- ^ String to split -> [S.ByteString] -- ^ Fragments of string split pat | S.null pat = const (repeat S.empty) split pat = splitter where !patLen = S.length pat searcher = strictSearcher False pat splitter str | S.null str = [] | otherwise = splitter' str splitter' str | S.null str = [S.empty] | otherwise = case searcher str of [] -> [str] (i:_) -> S.take i str : splitter' (S.drop (i + patLen) str) -- | @'splitKeepEnd' pattern target@ splits @target@ after each (non-overlapping) -- occurrence of @pattern@. If @pattern@ is empty, the result is an -- infinite list of empty 'S.ByteString's, otherwise the following -- relations hold: -- -- @ -- 'S.concat' . 'splitKeepEnd' pattern = 'id', -- @ -- -- all fragments in the result except possibly the last end with -- @pattern@, no fragment contains more than one occurrence of @pattern@. splitKeepEnd :: S.ByteString -- ^ Pattern to split on -> S.ByteString -- ^ String to split -> [S.ByteString] -- ^ Fragments of string splitKeepEnd pat | S.null pat = const (repeat S.empty) splitKeepEnd pat = splitter where !patLen = S.length pat searcher = strictSearcher False pat splitter str | S.null str = [] | otherwise = case searcher str of [] -> [str] (i:_) -> S.take (i + patLen) str : splitter (S.drop (i + patLen) str) -- | @'splitKeepFront'@ is like 'splitKeepEnd', except that @target@ is split -- before each occurrence of @pattern@ and hence all fragments -- with the possible exception of the first begin with @pattern@. -- No fragment contains more than one non-overlapping occurrence -- of @pattern@. splitKeepFront :: S.ByteString -- ^ Pattern to split on -> S.ByteString -- ^ String to split -> [S.ByteString] -- ^ Fragments of string splitKeepFront pat | S.null pat = const (repeat S.empty) splitKeepFront pat = splitter where !patLen = S.length pat searcher = strictSearcher False pat splitter str | S.null str = [] | otherwise = case searcher str of [] -> [str] (i:rst) | i == 0 -> case rst of [] -> [str] (j:_) -> S.take j str : splitter' (S.drop j str) | otherwise -> S.take i str : splitter' (S.drop i str) splitter' str | S.null str = [] | otherwise = case searcher (S.drop patLen str) of [] -> [str] (i:_) -> S.take (i + patLen) str : splitter' (S.drop (i + patLen) str) ------------------------------------------------------------------------------ -- Searching Function -- ------------------------------------------------------------------------------ strictSearcher :: Bool -> S.ByteString -> S.ByteString -> [Int] strictSearcher _ !pat | S.null pat = enumFromTo 0 . S.length | S.length pat == 1 = let !w = S.head pat in S.elemIndices w strictSearcher !overlap pat = search where !patLen = S.length pat !auto = automaton pat !p0 = unsafeIndex pat 0 !ams = if overlap then patLen else 0 search str = match 0 0 where !strLen = S.length str {-# INLINE strAt #-} strAt :: Int -> Int strAt !i = fromIntegral (unsafeIndex str i) match 0 idx | idx == strLen = [] | unsafeIndex str idx == p0 = match 1 (idx + 1) | otherwise = match 0 (idx + 1) match state idx | idx == strLen = [] | otherwise = let !nstate = unsafeAt auto ((state `shiftL` 8) + strAt idx) !nxtIdx = idx + 1 in if nstate == patLen then (nxtIdx - patLen) : match ams nxtIdx else match nstate nxtIdx
phischu/fragnix
tests/packages/scotty/Data.ByteString.Search.DFA.hs
bsd-3-clause
12,753
0
26
3,987
1,972
1,056
916
154
4
{-# LANGUAGE ViewPatterns #-} {- Copyright (C) 2014 Matthew Pickering <matthewtpickering@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.Txt2Tags Copyright : Copyright (C) 2014 Matthew Pickering License : GNU GPL, version 2 or above Maintainer : Matthew Pickering <matthewtpickering@gmail.com> Conversion of txt2tags formatted plain text to 'Pandoc' document. -} module Text.Pandoc.Readers.Txt2Tags ( readTxt2Tags , getT2TMeta , T2TMeta (..) , readTxt2TagsNoMacros) where import qualified Text.Pandoc.Builder as B import Text.Pandoc.Builder ( Inlines, Blocks, (<>) , trimInlines ) import Text.Pandoc.Definition import Text.Pandoc.Options import Text.Pandoc.Shared (escapeURI,compactify', compactify'DL) import Text.Pandoc.Parsing hiding (space, spaces, uri, macro) import Control.Applicative ((<$>), (<$), (<*>), (<*), (*>)) import Data.Char (toLower) import Data.List (transpose, intersperse, intercalate) import Data.Maybe (fromMaybe) import Data.Monoid (Monoid, mconcat, mempty, mappend) --import Network.URI (isURI) -- Not sure whether to use this function import Control.Monad (void, guard, when) import Data.Default import Control.Monad.Reader (Reader, runReader, asks) import Data.Time.LocalTime (getZonedTime) import Text.Pandoc.Compat.Directory(getModificationTime) import Data.Time.Format (formatTime) import System.Locale (defaultTimeLocale) import System.IO.Error (catchIOError) type T2T = ParserT String ParserState (Reader T2TMeta) -- | An object for the T2T macros meta information -- the contents of each field is simply substituted verbatim into the file data T2TMeta = T2TMeta { date :: String -- ^ Current date , mtime :: String -- ^ Last modification time of infile , infile :: FilePath -- ^ Input file , outfile :: FilePath -- ^ Output file } deriving Show instance Default T2TMeta where def = T2TMeta "" "" "" "" -- | Get the meta information required by Txt2Tags macros getT2TMeta :: [FilePath] -> FilePath -> IO T2TMeta getT2TMeta inps out = do curDate <- formatTime defaultTimeLocale "%F" <$> getZonedTime let getModTime = fmap (formatTime defaultTimeLocale "%T") . getModificationTime curMtime <- case inps of [] -> formatTime defaultTimeLocale "%T" <$> getZonedTime _ -> catchIOError (maximum <$> mapM getModTime inps) (const (return "")) return $ T2TMeta curDate curMtime (intercalate ", " inps) out -- | Read Txt2Tags from an input string returning a Pandoc document readTxt2Tags :: T2TMeta -> ReaderOptions -> String -> Pandoc readTxt2Tags t opts s = flip runReader t $ readWithM parseT2T (def {stateOptions = opts}) (s ++ "\n\n") -- | Read Txt2Tags (ignoring all macros) from an input string returning -- a Pandoc document readTxt2TagsNoMacros :: ReaderOptions -> String -> Pandoc readTxt2TagsNoMacros = readTxt2Tags def parseT2T :: T2T Pandoc parseT2T = do -- Parse header if standalone flag is set standalone <- getOption readerStandalone when standalone parseHeader body <- mconcat <$> manyTill block eof meta' <- stateMeta <$> getState return $ Pandoc meta' (B.toList body) parseHeader :: T2T () parseHeader = do () <$ try blankline <|> header meta <- stateMeta <$> getState optional blanklines config <- manyTill setting (notFollowedBy setting) -- TODO: Handle settings better let settings = foldr (\(k,v) -> B.setMeta k (MetaString v)) meta config updateState (\s -> s {stateMeta = settings}) <* optional blanklines header :: T2T () header = titleline >> authorline >> dateline headerline :: B.ToMetaValue a => String -> T2T a -> T2T () headerline field p = (() <$ try blankline) <|> (p >>= updateState . B.setMeta field) titleline :: T2T () titleline = headerline "title" (trimInlines . mconcat <$> manyTill inline newline) authorline :: T2T () authorline = headerline "author" (sepBy author (char ';') <* newline) where author = trimInlines . mconcat <$> many (notFollowedBy (char ';' <|> newline) >> inline) dateline :: T2T () dateline = headerline "date" (trimInlines . mconcat <$> manyTill inline newline) type Keyword = String type Value = String setting :: T2T (Keyword, Value) setting = do string "%!" keyword <- ignoreSpacesCap (many1 alphaNum) char ':' value <- ignoreSpacesCap (manyTill anyChar (newline)) return (keyword, value) -- Blocks parseBlocks :: T2T Blocks parseBlocks = mconcat <$> manyTill block eof block :: T2T Blocks block = do choice [ mempty <$ blanklines , quote , hrule -- hrule must go above title , title , commentBlock , verbatim , rawBlock , taggedBlock , list , table , para ] title :: T2T Blocks title = try $ balancedTitle '+' <|> balancedTitle '=' balancedTitle :: Char -> T2T Blocks balancedTitle c = try $ do spaces level <- length <$> many1 (char c) guard (level <= 5) -- Max header level 5 heading <- manyTill (noneOf "\n\r") (count level (char c)) label <- optionMaybe (enclosed (char '[') (char ']') (alphaNum <|> oneOf "_-")) many spaceChar *> newline let attr = maybe nullAttr (\x -> (x, [], [])) label return $ B.headerWith attr level (trimInlines $ B.text heading) para :: T2T Blocks para = try $ do ils <- parseInlines nl <- option False (True <$ newline) option (B.plain ils) (guard nl >> notFollowedBy listStart >> return (B.para ils)) where listStart = try bulletListStart <|> orderedListStart commentBlock :: T2T Blocks commentBlock = try (blockMarkupArea (anyLine) (const mempty) "%%%") <|> comment -- Seperator and Strong line treated the same hrule :: T2T Blocks hrule = try $ do spaces line <- many1 (oneOf "=-_") guard (length line >= 20) B.horizontalRule <$ blankline quote :: T2T Blocks quote = try $ do lookAhead tab rawQuote <- many1 (tab *> optional spaces *> anyLine) contents <- parseFromString parseBlocks (intercalate "\n" rawQuote ++ "\n\n") return $ B.blockQuote contents commentLine :: T2T Inlines commentLine = comment -- List Parsing code from Org Reader list :: T2T Blocks list = choice [bulletList, orderedList, definitionList] bulletList :: T2T Blocks bulletList = B.bulletList . compactify' <$> many1 (listItem bulletListStart parseBlocks) orderedList :: T2T Blocks orderedList = B.orderedList . compactify' <$> many1 (listItem orderedListStart parseBlocks) definitionList :: T2T Blocks definitionList = try $ do B.definitionList . compactify'DL <$> many1 (listItem definitionListStart definitionListEnd) definitionListEnd :: T2T (Inlines, [Blocks]) definitionListEnd = (,) <$> (mconcat <$> manyTill inline newline) <*> ((:[]) <$> parseBlocks) genericListStart :: T2T Char -> T2T Int genericListStart listMarker = try $ (2+) <$> (length <$> many spaceChar <* listMarker <* space <* notFollowedBy space) -- parses bullet list \start and returns its length (excl. following whitespace) bulletListStart :: T2T Int bulletListStart = genericListStart (char '-') orderedListStart :: T2T Int orderedListStart = genericListStart (char '+' ) definitionListStart :: T2T Int definitionListStart = genericListStart (char ':') -- parse raw text for one list item, excluding start marker and continuations listItem :: T2T Int -> T2T a -> T2T a listItem start end = try $ do markerLength <- try start firstLine <- anyLineNewline blank <- option "" ("\n" <$ blankline) rest <- concat <$> many (listContinuation markerLength) parseFromString end $ firstLine ++ blank ++ rest -- continuation of a list item - indented and separated by blankline or endline. -- Note: nested lists are parsed as continuations. listContinuation :: Int -> T2T String listContinuation markerLength = try $ notFollowedBy' (blankline >> blankline) *> (mappend <$> (concat <$> many1 listLine) <*> many blankline) where listLine = try $ indentWith markerLength *> anyLineNewline anyLineNewline :: T2T String anyLineNewline = (++ "\n") <$> anyLine indentWith :: Int -> T2T String indentWith n = count n space -- Table table :: T2T Blocks table = try $ do tableHeader <- fmap snd <$> option mempty (try headerRow) rows <- many1 (many commentLine *> tableRow) let columns = transpose rows let ncolumns = length columns let aligns = map (foldr1 findAlign) (map (map fst) columns) let rows' = map (map snd) rows let size = maximum (map length rows') let rowsPadded = map (pad size) rows' let headerPadded = if (not (null tableHeader)) then pad size tableHeader else mempty return $ B.table mempty (zip aligns (replicate ncolumns 0.0)) headerPadded rowsPadded pad :: (Show a, Monoid a) => Int -> [a] -> [a] pad n xs = xs ++ (replicate (n - length xs) mempty) findAlign :: Alignment -> Alignment -> Alignment findAlign x y | x == y = x | otherwise = AlignDefault headerRow :: T2T [(Alignment, Blocks)] headerRow = genericRow (string "||") tableRow :: T2T [(Alignment, Blocks)] tableRow = genericRow (char '|') genericRow :: T2T a -> T2T [(Alignment, Blocks)] genericRow start = try $ do spaces *> start manyTill tableCell newline <?> "genericRow" tableCell :: T2T (Alignment, Blocks) tableCell = try $ do leftSpaces <- length <$> lookAhead (many1 space) -- Case of empty cell means we must lookAhead content <- (manyTill inline (try $ lookAhead (cellEnd))) rightSpaces <- length <$> many space let align = case compare leftSpaces rightSpaces of LT -> AlignLeft EQ -> AlignCenter GT -> AlignRight endOfCell return $ (align, B.plain (B.trimInlines $ mconcat content)) where cellEnd = (void newline <|> (many1 space *> endOfCell)) endOfCell :: T2T () endOfCell = try (skipMany1 $ char '|') <|> ( () <$ lookAhead newline) -- Raw area verbatim :: T2T Blocks verbatim = genericBlock anyLineNewline B.codeBlock "```" rawBlock :: T2T Blocks rawBlock = genericBlock anyLineNewline (B.para . B.str) "\"\"\"" taggedBlock :: T2T Blocks taggedBlock = do target <- getTarget genericBlock anyLineNewline (B.rawBlock target) "'''" -- Generic genericBlock :: Monoid a => T2T a -> (a -> Blocks) -> String -> T2T Blocks genericBlock p f s = blockMarkupArea p f s <|> blockMarkupLine p f s blockMarkupArea :: Monoid a => (T2T a) -> (a -> Blocks) -> String -> T2T Blocks blockMarkupArea p f s = try $ (do string s *> blankline f . mconcat <$> (manyTill p (eof <|> void (string s *> blankline)))) blockMarkupLine :: T2T a -> (a -> Blocks) -> String -> T2T Blocks blockMarkupLine p f s = try (f <$> (string s *> space *> p)) -- Can be in either block or inline position comment :: Monoid a => T2T a comment = try $ do atStart notFollowedBy macro mempty <$ (char '%' *> anyLine) -- Inline parseInlines :: T2T Inlines parseInlines = trimInlines . mconcat <$> many1 inline inline :: T2T Inlines inline = do choice [ endline , macro , commentLine , whitespace , url , link , image , bold , underline , code , raw , tagged , strike , italic , code , str , symbol ] bold :: T2T Inlines bold = inlineMarkup inline B.strong '*' (B.str) underline :: T2T Inlines underline = inlineMarkup inline B.emph '_' (B.str) strike :: T2T Inlines strike = inlineMarkup inline B.strikeout '-' (B.str) italic :: T2T Inlines italic = inlineMarkup inline B.emph '/' (B.str) code :: T2T Inlines code = inlineMarkup ((:[]) <$> anyChar) B.code '`' id raw :: T2T Inlines raw = inlineMarkup ((:[]) <$> anyChar) B.text '"' id tagged :: T2T Inlines tagged = do target <- getTarget inlineMarkup ((:[]) <$> anyChar) (B.rawInline target) '\'' id -- Parser for markup indicated by a double character. -- Inline markup is greedy and glued -- Greedy meaning ***a*** = Bold [Str "*a*"] -- Glued meaning that markup must be tight to content -- Markup can't pass newlines inlineMarkup :: Monoid a => (T2T a) -- Content parser -> (a -> Inlines) -- Constructor -> Char -- Fence -> (String -> a) -- Special Case to handle ****** -> T2T Inlines inlineMarkup p f c special = try $ do start <- many1 (char c) let l = length start guard (l >= 2) when (l == 2) (void $ notFollowedBy space) -- We must make sure that there is no space before the start of the -- closing tags body <- optionMaybe (try $ manyTill (noneOf "\n\r") $ (try $ lookAhead (noneOf " " >> string [c,c] ))) case body of Just middle -> do lastChar <- anyChar end <- many1 (char c) let parser inp = parseFromString (mconcat <$> many p) inp let start' = special (drop 2 start) body' <- parser (middle ++ [lastChar]) let end' = special (drop 2 end) return $ f (start' <> body' <> end') Nothing -> do -- Either bad or case such as ***** guard (l >= 5) let body' = (replicate (l - 4) c) return $ f (special body') link :: T2T Inlines link = try imageLink <|> titleLink -- Link with title titleLink :: T2T Inlines titleLink = try $ do char '[' notFollowedBy space tokens <- sepBy1 (many $ noneOf " ]") space guard (length tokens >= 2) char ']' let link' = last tokens guard (length link' > 0) let tit = concat (intersperse " " (init tokens)) return $ B.link link' "" (B.text tit) -- Link with image imageLink :: T2T Inlines imageLink = try $ do char '[' body <- image many1 space l <- manyTill (noneOf "\n\r ") (char ']') return (B.link l "" body) macro :: T2T Inlines macro = try $ do name <- string "%%" *> oneOfStringsCI (map fst commands) optional (try $ enclosed (char '(') (char ')') anyChar) lookAhead (spaceChar <|> oneOf specialChars <|> newline) maybe (return mempty) (\f -> B.str <$> asks f) (lookup name commands) where commands = [ ("date", date), ("mtime", mtime) , ("infile", infile), ("outfile", outfile)] -- raw URLs in text are automatically linked url :: T2T Inlines url = try $ do (rawUrl, escapedUrl) <- (try uri <|> emailAddress) return $ B.link rawUrl "" (B.str escapedUrl) uri :: T2T (String, String) uri = try $ do address <- t2tURI return (address, escapeURI address) -- The definition of a URI in the T2T source differs from the -- actual definition. This is a transcription of the definition in -- the source of v2.6 --isT2TURI :: String -> Bool --isT2TURI (parse t2tURI "" -> Right _) = True --isT2TURI _ = False t2tURI :: T2T String t2tURI = do start <- try ((++) <$> proto <*> urlLogin) <|> guess domain <- many1 chars sep <- many (char '/') form' <- option mempty ((:) <$> char '?' <*> many1 form) anchor' <- option mempty ((:) <$> char '#' <*> many anchor) return (start ++ domain ++ sep ++ form' ++ anchor') where protos = ["http", "https", "ftp", "telnet", "gopher", "wais"] proto = (++) <$> oneOfStrings protos <*> string "://" guess = (++) <$> (((++) <$> stringAnyCase "www" <*> option mempty ((:[]) <$> oneOf "23")) <|> stringAnyCase "ftp") <*> ((:[]) <$> char '.') login = alphaNum <|> oneOf "_.-" pass = many (noneOf " @") chars = alphaNum <|> oneOf "%._/~:,=$@&+-" anchor = alphaNum <|> oneOf "%._0" form = chars <|> oneOf ";*" urlLogin = option mempty $ try ((\x y z -> x ++ y ++ [z]) <$> many1 login <*> option mempty ((:) <$> char ':' <*> pass) <*> char '@') image :: T2T Inlines image = try $ do -- List taken from txt2tags source let extensions = [".jpg", ".jpeg", ".gif", ".png", ".eps", ".bmp"] char '[' path <- manyTill (noneOf "\n\t\r ") (try $ lookAhead (oneOfStrings extensions)) ext <- oneOfStrings extensions char ']' return $ B.image (path ++ ext) "" mempty -- Characters used in markup specialChars :: String specialChars = "%*-_/|:+;" tab :: T2T Char tab = char '\t' space :: T2T Char space = char ' ' spaces :: T2T String spaces = many space endline :: T2T Inlines endline = try $ do newline notFollowedBy blankline notFollowedBy hrule notFollowedBy title notFollowedBy verbatim notFollowedBy rawBlock notFollowedBy taggedBlock notFollowedBy quote notFollowedBy list notFollowedBy table return $ B.space str :: T2T Inlines str = try $ do B.str <$> many1 (noneOf $ specialChars ++ "\n\r ") whitespace :: T2T Inlines whitespace = try $ B.space <$ spaceChar symbol :: T2T Inlines symbol = B.str . (:[]) <$> oneOf specialChars -- Utility getTarget :: T2T String getTarget = do mv <- lookupMeta "target" . stateMeta <$> getState let MetaString target = fromMaybe (MetaString "html") mv return target atStart :: T2T () atStart = (sourceColumn <$> getPosition) >>= guard . (== 1) ignoreSpacesCap :: T2T String -> T2T String ignoreSpacesCap p = map toLower <$> (spaces *> p <* spaces)
peter-fogg/pardoc
src/Text/Pandoc/Readers/Txt2Tags.hs
gpl-2.0
17,827
0
19
4,061
5,642
2,863
2,779
409
3
module Main (main) where import Parser (parse) import System.IO (hPutStrLn, stderr) main :: IO () main = do x <- getContents case parse x of Left e -> hPutStrLn stderr $ "Failed with: " ++ e Right t -> print t
PhilThomas/happy
examples/igloo/Foo.hs
bsd-2-clause
252
0
12
83
94
48
46
8
2
{-# LANGUAGE TemplateHaskell, QuasiQuotes, FlexibleContexts #-} import TensorQQ main :: IO () main = do let x = [1, 2, 3] i = 1 print [tens|x_i|]
tanakh/Peggy
example/Tensor.hs
bsd-3-clause
157
0
10
37
53
30
23
7
1
module Main (main) where import Data.List (genericLength) import Data.Maybe (catMaybes) import System.Directory (doesFileExist) import System.Exit (exitFailure, exitSuccess) import System.Process (readProcess) import Text.Regex (matchRegex, mkRegex) average :: (Fractional a, Real b) => [b] -> a average xs = realToFrac (sum xs) / genericLength xs expected :: Fractional a => a expected = 90 main :: IO () main = do file <- tix let arguments = ["report", file] output <- readProcess "hpc" arguments "" if average (match output) >= (expected :: Float) then exitSuccess else putStr output >> exitFailure match :: String -> [Int] match = fmap read . concat . catMaybes . fmap (matchRegex pattern) . lines where pattern = mkRegex "^ *([0-9]*)% " -- The location of the TIX file changed between versions of cabal-install. -- See <https://github.com/tfausak/haskeleton/issues/31> for details. tix :: IO FilePath tix = do let newFile = "tests.tix" oldFile = "dist/hpc/tix/tests/tests.tix" newFileExists <- doesFileExist newFile let file = if newFileExists then newFile else oldFile return file
danplubell/tzworld-api
test-suite/HPC.hs
mit
1,156
0
11
229
348
184
164
29
2
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="pt-BR"> <title>Directory List v1.0</title> <maps> <homeID>directorylistv1</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/directorylistv1/src/main/javahelp/help_pt_BR/helpset_pt_BR.hs
apache-2.0
976
78
66
157
412
209
203
-1
-1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Get information on modules, expreesions, and identifiers module GHCi.UI.Info ( ModInfo(..) , SpanInfo(..) , spanInfoFromRealSrcSpan , collectInfo , findLoc , findNameUses , findType , getModInfo ) where import Control.Exception import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.Except import Control.Monad.Trans.Maybe import Data.Data import Data.Function import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe import Data.Time import Prelude hiding (mod) import System.Directory import qualified CoreUtils import Desugar import DynFlags (HasDynFlags(..)) import FastString import GHC import GhcMonad import Name import NameSet import Outputable import SrcLoc import TcHsSyn import Var -- | Info about a module. This information is generated every time a -- module is loaded. data ModInfo = ModInfo { modinfoSummary :: !ModSummary -- ^ Summary generated by GHC. Can be used to access more -- information about the module. , modinfoSpans :: [SpanInfo] -- ^ Generated set of information about all spans in the -- module that correspond to some kind of identifier for -- which there will be type info and/or location info. , modinfoInfo :: !ModuleInfo -- ^ Again, useful from GHC for accessing information -- (exports, instances, scope) from a module. , modinfoLastUpdate :: !UTCTime } -- | Type of some span of source code. Most of these fields are -- unboxed but Haddock doesn't show that. data SpanInfo = SpanInfo { spaninfoSrcSpan :: {-# UNPACK #-} !RealSrcSpan -- ^ The span we associate information with , spaninfoType :: !(Maybe Type) -- ^ The 'Type' associated with the span , spaninfoVar :: !(Maybe Id) -- ^ The actual 'Var' associated with the span, if -- any. This can be useful for accessing a variety of -- information about the identifier such as module, -- locality, definition location, etc. } -- | Test whether second span is contained in (or equal to) first span. -- This is basically 'containsSpan' for 'SpanInfo' containsSpanInfo :: SpanInfo -> SpanInfo -> Bool containsSpanInfo = containsSpan `on` spaninfoSrcSpan -- | Filter all 'SpanInfo' which are contained in 'SpanInfo' spaninfosWithin :: [SpanInfo] -> SpanInfo -> [SpanInfo] spaninfosWithin spans' si = filter (si `containsSpanInfo`) spans' -- | Construct a 'SpanInfo' from a 'RealSrcSpan' and optionally a -- 'Type' and an 'Id' (for 'spaninfoType' and 'spaninfoVar' -- respectively) spanInfoFromRealSrcSpan :: RealSrcSpan -> Maybe Type -> Maybe Id -> SpanInfo spanInfoFromRealSrcSpan spn mty mvar = SpanInfo spn mty mvar -- | Convenience wrapper around 'spanInfoFromRealSrcSpan' which needs -- only a 'RealSrcSpan' spanInfoFromRealSrcSpan' :: RealSrcSpan -> SpanInfo spanInfoFromRealSrcSpan' s = spanInfoFromRealSrcSpan s Nothing Nothing -- | Convenience wrapper around 'srcSpanFile' which results in a 'FilePath' srcSpanFilePath :: RealSrcSpan -> FilePath srcSpanFilePath = unpackFS . srcSpanFile -- | Try to find the location of the given identifier at the given -- position in the module. findLoc :: GhcMonad m => Map ModuleName ModInfo -> RealSrcSpan -> String -> ExceptT SDoc m (ModInfo,Name,SrcSpan) findLoc infos span0 string = do name <- maybeToExceptT "Couldn't guess that module name. Does it exist?" $ guessModule infos (srcSpanFilePath span0) info <- maybeToExceptT "No module info for current file! Try loading it?" $ MaybeT $ pure $ M.lookup name infos name' <- findName infos span0 info string case getSrcSpan name' of UnhelpfulSpan{} -> do throwE ("Found a name, but no location information." <+> "The module is:" <+> maybe "<unknown>" (ppr . moduleName) (nameModule_maybe name')) span' -> return (info,name',span') -- | Find any uses of the given identifier in the codebase. findNameUses :: (GhcMonad m) => Map ModuleName ModInfo -> RealSrcSpan -> String -> ExceptT SDoc m [SrcSpan] findNameUses infos span0 string = locToSpans <$> findLoc infos span0 string where locToSpans (modinfo,name',span') = stripSurrounding (span' : map toSrcSpan spans) where toSrcSpan = RealSrcSpan . spaninfoSrcSpan spans = filter ((== Just name') . fmap getName . spaninfoVar) (modinfoSpans modinfo) -- | Filter out redundant spans which surround/contain other spans. stripSurrounding :: [SrcSpan] -> [SrcSpan] stripSurrounding xs = filter (not . isRedundant) xs where isRedundant x = any (x `strictlyContains`) xs (RealSrcSpan s1) `strictlyContains` (RealSrcSpan s2) = s1 /= s2 && s1 `containsSpan` s2 _ `strictlyContains` _ = False -- | Try to resolve the name located at the given position, or -- otherwise resolve based on the current module's scope. findName :: GhcMonad m => Map ModuleName ModInfo -> RealSrcSpan -> ModInfo -> String -> ExceptT SDoc m Name findName infos span0 mi string = case resolveName (modinfoSpans mi) (spanInfoFromRealSrcSpan' span0) of Nothing -> tryExternalModuleResolution Just name -> case getSrcSpan name of UnhelpfulSpan {} -> tryExternalModuleResolution RealSrcSpan {} -> return (getName name) where tryExternalModuleResolution = case find (matchName $ mkFastString string) (fromMaybe [] (modInfoTopLevelScope (modinfoInfo mi))) of Nothing -> throwE "Couldn't resolve to any modules." Just imported -> resolveNameFromModule infos imported matchName :: FastString -> Name -> Bool matchName str name = str == occNameFS (getOccName name) -- | Try to resolve the name from another (loaded) module's exports. resolveNameFromModule :: GhcMonad m => Map ModuleName ModInfo -> Name -> ExceptT SDoc m Name resolveNameFromModule infos name = do modL <- maybe (throwE $ "No module for" <+> ppr name) return $ nameModule_maybe name info <- maybe (throwE (ppr (moduleUnitId modL) <> ":" <> ppr modL)) return $ M.lookup (moduleName modL) infos maybe (throwE "No matching export in any local modules.") return $ find (matchName name) (modInfoExports (modinfoInfo info)) where matchName :: Name -> Name -> Bool matchName x y = occNameFS (getOccName x) == occNameFS (getOccName y) -- | Try to resolve the type display from the given span. resolveName :: [SpanInfo] -> SpanInfo -> Maybe Var resolveName spans' si = listToMaybe $ mapMaybe spaninfoVar $ reverse spans' `spaninfosWithin` si -- | Try to find the type of the given span. findType :: GhcMonad m => Map ModuleName ModInfo -> RealSrcSpan -> String -> ExceptT SDoc m (ModInfo, Type) findType infos span0 string = do name <- maybeToExceptT "Couldn't guess that module name. Does it exist?" $ guessModule infos (srcSpanFilePath span0) info <- maybeToExceptT "No module info for current file! Try loading it?" $ MaybeT $ pure $ M.lookup name infos case resolveType (modinfoSpans info) (spanInfoFromRealSrcSpan' span0) of Nothing -> (,) info <$> lift (exprType TM_Inst string) Just ty -> return (info, ty) where -- | Try to resolve the type display from the given span. resolveType :: [SpanInfo] -> SpanInfo -> Maybe Type resolveType spans' si = listToMaybe $ mapMaybe spaninfoType $ reverse spans' `spaninfosWithin` si -- | Guess a module name from a file path. guessModule :: GhcMonad m => Map ModuleName ModInfo -> FilePath -> MaybeT m ModuleName guessModule infos fp = do target <- lift $ guessTarget fp Nothing case targetId target of TargetModule mn -> return mn TargetFile fp' _ -> guessModule' fp' where guessModule' :: GhcMonad m => FilePath -> MaybeT m ModuleName guessModule' fp' = case findModByFp fp' of Just mn -> return mn Nothing -> do fp'' <- liftIO (makeRelativeToCurrentDirectory fp') target' <- lift $ guessTarget fp'' Nothing case targetId target' of TargetModule mn -> return mn _ -> MaybeT . pure $ findModByFp fp'' findModByFp :: FilePath -> Maybe ModuleName findModByFp fp' = fst <$> find ((Just fp' ==) . mifp) (M.toList infos) where mifp :: (ModuleName, ModInfo) -> Maybe FilePath mifp = ml_hs_file . ms_location . modinfoSummary . snd -- | Collect type info data for the loaded modules. collectInfo :: (GhcMonad m) => Map ModuleName ModInfo -> [ModuleName] -> m (Map ModuleName ModInfo) collectInfo ms loaded = do df <- getDynFlags liftIO (filterM cacheInvalid loaded) >>= \case [] -> return ms invalidated -> do liftIO (putStrLn ("Collecting type info for " ++ show (length invalidated) ++ " module(s) ... ")) foldM (go df) ms invalidated where go df m name = do { info <- getModInfo name; return (M.insert name info m) } `gcatch` (\(e :: SomeException) -> do liftIO $ putStrLn $ showSDocForUser df alwaysQualify $ "Error while getting type info from" <+> ppr name <> ":" <+> text (show e) return m) cacheInvalid name = case M.lookup name ms of Nothing -> return True Just mi -> do let fp = ml_obj_file (ms_location (modinfoSummary mi)) last' = modinfoLastUpdate mi exists <- doesFileExist fp if exists then (> last') <$> getModificationTime fp else return True -- | Get info about the module: summary, types, etc. getModInfo :: (GhcMonad m) => ModuleName -> m ModInfo getModInfo name = do m <- getModSummary name p <- parseModule m typechecked <- typecheckModule p allTypes <- processAllTypeCheckedModule typechecked let i = tm_checked_module_info typechecked now <- liftIO getCurrentTime return (ModInfo m allTypes i now) -- | Get ALL source spans in the module. processAllTypeCheckedModule :: forall m . GhcMonad m => TypecheckedModule -> m [SpanInfo] processAllTypeCheckedModule tcm = do bts <- mapM getTypeLHsBind $ listifyAllSpans tcs ets <- mapM getTypeLHsExpr $ listifyAllSpans tcs pts <- mapM getTypeLPat $ listifyAllSpans tcs return $ mapMaybe toSpanInfo $ sortBy cmpSpan $ catMaybes (bts ++ ets ++ pts) where tcs = tm_typechecked_source tcm -- | Extract 'Id', 'SrcSpan', and 'Type' for 'LHsBind's getTypeLHsBind :: LHsBind Id -> m (Maybe (Maybe Id,SrcSpan,Type)) getTypeLHsBind (L _spn FunBind{fun_id = pid,fun_matches = MG _ _ _typ _}) = pure $ Just (Just (unLoc pid),getLoc pid,varType (unLoc pid)) getTypeLHsBind _ = pure Nothing -- | Extract 'Id', 'SrcSpan', and 'Type' for 'LHsExpr's getTypeLHsExpr :: LHsExpr Id -> m (Maybe (Maybe Id,SrcSpan,Type)) getTypeLHsExpr e = do hs_env <- getSession (_,mbe) <- liftIO $ deSugarExpr hs_env e return $ fmap (\expr -> (mid, getLoc e, CoreUtils.exprType expr)) mbe where mid :: Maybe Id mid | HsVar (L _ i) <- unwrapVar (unLoc e) = Just i | otherwise = Nothing unwrapVar (HsWrap _ var) = var unwrapVar e' = e' -- | Extract 'Id', 'SrcSpan', and 'Type' for 'LPats's getTypeLPat :: LPat Id -> m (Maybe (Maybe Id,SrcSpan,Type)) getTypeLPat (L spn pat) = pure (Just (getMaybeId pat,spn,hsPatType pat)) where getMaybeId (VarPat (L _ vid)) = Just vid getMaybeId _ = Nothing -- | Get ALL source spans in the source. listifyAllSpans :: Typeable a => TypecheckedSource -> [Located a] listifyAllSpans = everythingAllSpans (++) [] ([] `mkQ` (\x -> [x | p x])) where p (L spn _) = isGoodSrcSpan spn -- | Variant of @syb@'s @everything@ (which summarises all nodes -- in top-down, left-to-right order) with a stop-condition on 'NameSet's everythingAllSpans :: (r -> r -> r) -> r -> GenericQ r -> GenericQ r everythingAllSpans k z f x | (False `mkQ` (const True :: NameSet -> Bool)) x = z | otherwise = foldl k (f x) (gmapQ (everythingAllSpans k z f) x) cmpSpan (_,a,_) (_,b,_) | a `isSubspanOf` b = LT | b `isSubspanOf` a = GT | otherwise = EQ -- | Pretty print the types into a 'SpanInfo'. toSpanInfo :: (Maybe Id,SrcSpan,Type) -> Maybe SpanInfo toSpanInfo (n,RealSrcSpan spn,typ) = Just $ spanInfoFromRealSrcSpan spn (Just typ) n toSpanInfo _ = Nothing -- helper stolen from @syb@ package type GenericQ r = forall a. Data a => a -> r mkQ :: (Typeable a, Typeable b) => r -> (b -> r) -> a -> r (r `mkQ` br) a = maybe r br (cast a)
snoyberg/ghc
ghc/GHCi/UI/Info.hs
bsd-3-clause
13,983
1
21
4,162
3,407
1,739
1,668
265
5
{-# LANGUAGE CPP #-} #ifdef __GLASGOW_HASKELL__ {-# LANGUAGE DeriveDataTypeable #-} #endif -- | When you've caught all the exceptions that can be handled safely, -- this is what you're left with. -- -- > runEitherIO . fromIO ≡ id -- -- It is intended that you use qualified imports with this library. -- -- > import UnexceptionalIO (UIO) -- > import qualified UnexceptionalIO as UIO module UnexceptionalIO ( UIO, Unexceptional(..), fromIO, #ifdef __GLASGOW_HASKELL__ fromIO', #endif run, runEitherIO, -- * Unsafe entry points unsafeFromIO, -- * Pseudo exceptions SomeNonPseudoException, #ifdef __GLASGOW_HASKELL__ PseudoException(..), ProgrammerError(..), ExternalError(..), -- * Pseudo exception helpers bracket, #if MIN_VERSION_base(4,7,0) forkFinally, fork, ChildThreadError(..) #endif #endif ) where import Data.Maybe (fromMaybe) import Control.Applicative (Applicative(..), (<|>), (<$>)) import Control.Monad (liftM, ap, (<=<)) import Control.Monad.Fix (MonadFix(..)) #ifdef __GLASGOW_HASKELL__ import System.Exit (ExitCode) import Control.Exception (try) import Data.Typeable (Typeable) import qualified Control.Exception as Ex import qualified Control.Concurrent as Concurrent #if MIN_VERSION_base(4,11,0) import qualified Control.Exception.Base as Ex #endif -- | Not everything handled by the exception system is a run-time error -- you can handle. This is the class of unrecoverable pseudo-exceptions. -- -- Additionally, except for 'ExitCode' any of these pseudo-exceptions -- you could never guarantee to have caught. Since they can come -- from anywhere at any time, we could never guarentee that 'UIO' does -- not contain them. data PseudoException = ProgrammerError ProgrammerError | -- ^ Mistakes programmers make ExternalError ExternalError | -- ^ Errors thrown by the runtime Exit ExitCode -- ^ Process exit requests deriving (Show, Typeable) instance Ex.Exception PseudoException where toException (ProgrammerError e) = Ex.toException e toException (ExternalError e) = Ex.toException e toException (Exit e) = Ex.toException e fromException e = ProgrammerError <$> Ex.fromException e <|> ExternalError <$> Ex.fromException e <|> Exit <$> Ex.fromException e -- | Pseudo-exceptions caused by a programming error -- -- Partial functions, 'error', 'undefined', etc data ProgrammerError = #if MIN_VERSION_base(4,9,0) TypeError Ex.TypeError | #endif ArithException Ex.ArithException | ArrayException Ex.ArrayException | AssertionFailed Ex.AssertionFailed | ErrorCall Ex.ErrorCall | NestedAtomically Ex.NestedAtomically | NoMethodError Ex.NoMethodError | PatternMatchFail Ex.PatternMatchFail | RecConError Ex.RecConError | RecSelError Ex.RecSelError | RecUpdError Ex.RecSelError deriving (Show, Typeable) instance Ex.Exception ProgrammerError where #if MIN_VERSION_base(4,9,0) toException (TypeError e) = Ex.toException e #endif toException (ArithException e) = Ex.toException e toException (ArrayException e) = Ex.toException e toException (AssertionFailed e) = Ex.toException e toException (ErrorCall e) = Ex.toException e toException (NestedAtomically e) = Ex.toException e toException (NoMethodError e) = Ex.toException e toException (PatternMatchFail e) = Ex.toException e toException (RecConError e) = Ex.toException e toException (RecSelError e) = Ex.toException e toException (RecUpdError e) = Ex.toException e fromException e = #if MIN_VERSION_base(4,9,0) TypeError <$> Ex.fromException e <|> #endif ArithException <$> Ex.fromException e <|> ArrayException <$> Ex.fromException e <|> AssertionFailed <$> Ex.fromException e <|> ErrorCall <$> Ex.fromException e <|> NestedAtomically <$> Ex.fromException e <|> NoMethodError <$> Ex.fromException e <|> PatternMatchFail <$> Ex.fromException e <|> RecConError <$> Ex.fromException e <|> RecSelError <$> Ex.fromException e <|> RecUpdError <$> Ex.fromException e -- | Pseudo-exceptions thrown by the runtime environment data ExternalError = #if MIN_VERSION_base(4,10,0) CompactionFailed Ex.CompactionFailed | #endif #if MIN_VERSION_base(4,11,0) FixIOException Ex.FixIOException | #endif #if MIN_VERSION_base(4,7,0) AsyncException Ex.SomeAsyncException | #else AsyncException Ex.AsyncException | #endif BlockedIndefinitelyOnSTM Ex.BlockedIndefinitelyOnSTM | BlockedIndefinitelyOnMVar Ex.BlockedIndefinitelyOnMVar | Deadlock Ex.Deadlock | NonTermination Ex.NonTermination deriving (Show, Typeable) instance Ex.Exception ExternalError where #if MIN_VERSION_base(4,10,0) toException (CompactionFailed e) = Ex.toException e #endif #if MIN_VERSION_base(4,11,0) toException (FixIOException e) = Ex.toException e #endif toException (AsyncException e) = Ex.toException e toException (BlockedIndefinitelyOnMVar e) = Ex.toException e toException (BlockedIndefinitelyOnSTM e) = Ex.toException e toException (Deadlock e) = Ex.toException e toException (NonTermination e) = Ex.toException e fromException e = #if MIN_VERSION_base(4,10,0) CompactionFailed <$> Ex.fromException e <|> #endif #if MIN_VERSION_base(4,11,0) FixIOException <$> Ex.fromException e <|> #endif AsyncException <$> Ex.fromException e <|> BlockedIndefinitelyOnSTM <$> Ex.fromException e <|> BlockedIndefinitelyOnMVar <$> Ex.fromException e <|> Deadlock <$> Ex.fromException e <|> NonTermination <$> Ex.fromException e -- | Every 'Ex.SomeException' but 'PseudoException' newtype SomeNonPseudoException = SomeNonPseudoException Ex.SomeException deriving (Show, Typeable) instance Ex.Exception SomeNonPseudoException where toException (SomeNonPseudoException e) = e fromException e = case Ex.fromException e of Just pseudo -> const Nothing (pseudo :: PseudoException) Nothing -> Just (SomeNonPseudoException e) throwIO :: (Ex.Exception e) => e -> IO a throwIO = Ex.throwIO #else -- Haskell98 import 'IO' instead import System.IO.Error (IOError, ioError, try) type SomeNonPseudoException = IOError throwIO :: SomeNonPseudoException -> IO a throwIO = ioError #endif -- | Like IO, but throws only 'PseudoException' newtype UIO a = UIO (IO a) instance Functor UIO where fmap = liftM instance Applicative UIO where pure = return (<*>) = ap instance Monad UIO where return = UIO . return (UIO x) >>= f = UIO (x >>= run . f) #if !MIN_VERSION_base(4,13,0) fail s = error $ "UnexceptionalIO cannot fail (" ++ s ++ ")" #endif instance MonadFix UIO where mfix f = UIO (mfix $ run . f) -- | Monads in which 'UIO' computations may be embedded class (Monad m) => Unexceptional m where lift :: UIO a -> m a instance Unexceptional UIO where lift = id instance Unexceptional IO where lift = run -- | Catch any exception but 'PseudoException' in an 'IO' action fromIO :: (Unexceptional m) => IO a -> m (Either SomeNonPseudoException a) fromIO = unsafeFromIO . try #ifdef __GLASGOW_HASKELL__ -- | Catch any 'e' in an 'IO' action, with a default mapping for -- unexpected cases fromIO' :: (Ex.Exception e, Unexceptional m) => (SomeNonPseudoException -> e) -- ^ Default if an unexpected exception occurs -> IO a -> m (Either e a) fromIO' f = liftM (either (Left . f) id) . fromIO . try #endif -- | Re-embed 'UIO' into 'IO' run :: UIO a -> IO a run (UIO io) = io -- | Re-embed 'UIO' and possible exception back into 'IO' #ifdef __GLASGOW_HASKELL__ runEitherIO :: (Ex.Exception e) => UIO (Either e a) -> IO a #else runEitherIO :: UIO (Either SomeNonPseudoException a) -> IO a #endif runEitherIO = either throwIO return <=< run -- | You promise there are no exceptions but 'PseudoException' thrown by this 'IO' action unsafeFromIO :: (Unexceptional m) => IO a -> m a unsafeFromIO = lift . UIO #ifdef __GLASGOW_HASKELL__ -- | When you're doing resource handling, 'PseudoException' matters. -- You still need to use the 'Ex.bracket' pattern to handle cleanup. bracket :: (Unexceptional m) => UIO a -> (a -> UIO ()) -> (a -> UIO c) -> m c bracket acquire release body = unsafeFromIO $ Ex.bracket (run acquire) (run . release) (run . body) #if MIN_VERSION_base(4,7,0) -- | Mirrors 'Concurrent.forkFinally', but since the body is 'UIO', -- the thread must terminate successfully or because of 'PseudoException' forkFinally :: (Unexceptional m) => UIO a -> (Either PseudoException a -> UIO ()) -> m Concurrent.ThreadId forkFinally body handler = unsafeFromIO $ Concurrent.forkFinally (run body) $ \result -> case result of Left e -> case Ex.fromException e of Just pseudo -> run $ handler $ Left pseudo Nothing -> error $ "Bug in UnexceptionalIO: forkFinally caught a non-PseudoException: " ++ show e Right x -> run $ handler $ Right x -- | Mirrors 'Concurrent.forkIO', but re-throws errors to the parent thread -- -- * Ignores manual thread kills, since those are on purpose. -- * Re-throws async exceptions ('SomeAsyncException') as is. -- * Re-throws 'ExitCode' as is in an attempt to exit with the requested code. -- * Wraps synchronous 'PseudoException' in async 'ChildThreadError'. fork :: (Unexceptional m) => UIO () -> m Concurrent.ThreadId fork body = do parent <- unsafeFromIO Concurrent.myThreadId forkFinally body $ either (handler parent) (const $ return ()) where handler parent e -- Thread manually killed. I assume on purpose | Just Ex.ThreadKilled <- castException e = return () -- Async exception, nothing to do with this thread, propogate directly | Just (Ex.SomeAsyncException _) <- castException e = unsafeFromIO $ Concurrent.throwTo parent e -- Attempt to manually end the process, -- not an async exception, so a bit dangerous to throw async'ly, but -- you really do want this to reach the top as-is for the exit code to -- work. | Just e <- castException e = unsafeFromIO $ Concurrent.throwTo parent (e :: ExitCode) -- Non-async PseudoException, so wrap in an async wrapper before -- throwing async'ly | otherwise = unsafeFromIO $ Concurrent.throwTo parent (ChildThreadError e) castException :: (Ex.Exception e1, Ex.Exception e2) => e1 -> Maybe e2 castException = Ex.fromException . Ex.toException -- | Async signal that a child thread ended due to non-async PseudoException newtype ChildThreadError = ChildThreadError PseudoException deriving (Show, Typeable) instance Ex.Exception ChildThreadError where toException = Ex.asyncExceptionToException fromException = Ex.asyncExceptionFromException #endif #endif
singpolyma/unexceptionalio
UnexceptionalIO.hs
isc
10,799
134
28
2,074
2,458
1,304
1,154
43
1
module Text.Typeical.Gramma ( Gramma() , fromList , empty , asMap , getExpression , extend , symbols , Expression , Term , Token(..) , Symbol(..) , SyntaxTree(..) , Variable(..) ) where import qualified Data.Map as M; newtype Gramma = Gramma { innerMap :: M.Map Symbol Expression } deriving (Show, Eq) -- | Create a Gramma form a list of symbols and expressions fromList :: [(Symbol, Expression)] -> Gramma fromList = Gramma . M.fromList -- | Extend a gramma, using a new gramma, overriding old rules extend :: Gramma -> Gramma -> Gramma extend g1 g2 = Gramma $ asMap g2 `M.union` asMap g1 -- | Get a expression from a gramma getExpression :: Gramma -> Symbol -> Expression getExpression bnf s = innerMap bnf M.! s -- | Return the Gramma as a map asMap :: Gramma -> M.Map Symbol Expression asMap = innerMap -- | Finds all the symbols in the gramma symbols :: Gramma -> [Symbol] symbols = M.keys . asMap -- | Empty gramma empty :: Gramma empty = Gramma M.empty -- A symbol is a recursive structure newtype Symbol = Symbol { symbolName :: String } deriving (Show, Eq, Ord) type Expression = [Term] type Term = [Token] data Token = Const String | Ref Symbol deriving (Show, Eq) data Variable = Variable { varSymbol :: Symbol , varMajor :: Int , varMinor :: Int } deriving (Show, Eq, Ord) data SyntaxTree = SyntaxTree Term [SyntaxTree] | Var Variable deriving (Show, Eq)
kalhauge/typeical
src/Text/Typeical/Gramma.hs
mit
2,047
0
8
925
418
249
169
44
1
{-# LANGUAGE CPP #-} module Data.HTTPSEverywhere.Rules.Internal ( getRulesetsMatching, havingRulesThatTrigger, havingCookieRulesThatTrigger, setSecureFlag, #ifdef TEST hasTargetMatching, hasTriggeringRuleOn, hasExclusionMatching #endif ) where import Prelude hiding (readFile, filter) import Control.Applicative ((<*>), (<$>)) import Control.Lens ((&)) import Control.Monad ((<=<), join) import Data.Bool (bool) import Data.Functor.Infix ((<$$>)) import Data.List (find) import Data.Maybe (isJust) import Network.HTTP.Client (Cookie(..)) import Network.URI (URI) import Pipes (Pipe, Producer, for, each, await, yield, lift, (>->)) import Pipes.Prelude (filter) import Data.HTTPSEverywhere.Rules.Internal.Parser (parseRuleSets) import qualified Data.HTTPSEverywhere.Rules.Internal.Raw as Raw (getRule, getRules) import Data.HTTPSEverywhere.Rules.Internal.Types (RuleSet(..), Target(..), Exclusion(..), Rule(..), CookieRule(..)) getRulesets :: Producer RuleSet IO () getRulesets = lift Raw.getRules >>= flip (for . each) (flip (for . each) yield <=< lift . (parseRuleSets <$$> Raw.getRule)) getRulesetsMatching :: URI -> Producer RuleSet IO () getRulesetsMatching url = getRulesets >-> filter (flip hasTargetMatching url) >-> filter (not . flip hasExclusionMatching url) havingRulesThatTrigger :: URI -> Pipe RuleSet (Maybe URI) IO () havingRulesThatTrigger url = flip hasTriggeringRuleOn url <$> await >>= maybe (havingRulesThatTrigger url) (yield . Just) havingCookieRulesThatTrigger :: Cookie -> Pipe RuleSet Bool IO () havingCookieRulesThatTrigger cookie = flip hasTriggeringCookieRuleOn cookie <$> await >>= bool (havingCookieRulesThatTrigger cookie) (yield True) hasTargetMatching :: RuleSet -> URI -> Bool hasTargetMatching ruleset url = getTargets ruleset <*> [url] & or where getTargets = getTarget <$$> ruleSetTargets hasExclusionMatching :: RuleSet -> URI -> Bool hasExclusionMatching ruleset url = getExclusions ruleset <*> [url] & or where getExclusions = getExclusion <$$> ruleSetExclusions hasTriggeringRuleOn :: RuleSet -> URI -> Maybe URI -- Nothing ~ False hasTriggeringRuleOn ruleset url = getRules ruleset <*> [url] & find isJust & join where getRules = getRule <$$> ruleSetRules hasTriggeringCookieRuleOn :: RuleSet -> Cookie -> Bool hasTriggeringCookieRuleOn ruleset cookie = getCookieRules ruleset <*> [cookie] & or where getCookieRules = getCookieRule <$$> ruleSetCookieRules setSecureFlag :: Cookie -> Cookie setSecureFlag cookie = cookie { cookie_secure_only = True }
fmap/https-everywhere-rules
src/Data/HTTPSEverywhere/Rules/Internal.hs
mit
2,640
0
12
443
759
432
327
-1
-1
{-# LANGUAGE FlexibleContexts #-} module S where import Test.QuickCheck import Test.QuickCheck.Checkers import Data.Monoid data S n a = S (n a) a deriving (Eq, Ord, Show) {- nickager: I’m trying to understand this type: “data S n a = S (n a) a” nickager: is (n a) applying function n to parameter a? PiDelport: nickager: It's taking n as a type constructor, and applying that to the type a nickager: so N could be “Just” nickager: for example? PiDelport: Not quitee, but it could be Maybe PiDelport: Maybe is the type constructor: PiDelport: :k Maybe lambdabot: * -> * ralu: :k Either lambdabot: * -> * -> * PiDelport: Just is a data constructor. PiDelport: nickager: In other words, Maybe taken a concrete type, and then returns a new type. PiDelport: Such as "Maybe Int" PiDelport: Or "Maybe String". PiDelport: So one example instance of the *type* above is S Maybe Int PiDelport: And a valid value of that type would be S (Just 5) 5 PiDelport: It's a bit confusing because S is being used both at the type level and value level there, but they're distinct. PiDelport: You could also rewrite the above to data S n a = MkS (n a) a nickager: another valid instance: nickager: S Nothing "hello" PiDelport: There, S is the type constructor, and MkS is the data constructor for it. PiDelport: nickager: Right. nickager: OK thanks that makes sense PiDelport: And the type of that would be S Maybe String -} -- data S n a = S (n a) a -- S (Just 5) 10 -- I cheated a little on this exercise and looked at https://github.com/dmvianna/haskellbook/blob/master/src/Ch21-Traversable.hs instance Functor n => Functor (S n) where fmap f (S na a) = S (fmap f na) (f a) instance Foldable n => Foldable (S n) where foldMap f (S na a) = foldMap f na <> f a instance (Traversable n) => Traversable (S n) where traverse f (S na a) = S <$> traverse f na <*> f a {- > let s = S (Just "hello") "again" > traverse (\x -> [x ++ "!!"]) s [S (Just "hello!!") "again!!"] -} -- instance (Arbitrary (n a), CoArbitrary (n a), Arbitrary a, CoArbitrary a) => Arbitrary (S n a) where arbitrary = S <$> arbitrary <*> arbitrary instance (Eq (n a), Eq a) => EqProp (S n a) where (=-=) = eq
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter21/Exercises/src/S.hs
mit
2,200
0
8
435
339
178
161
18
0
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} module Hpack.Convert where import Data.Char import Data.Monoid import Prelude () import Prelude.Compat import Data.List.Split (splitOn) import Data.Maybe import qualified Data.Version as Version import qualified Distribution.Compiler as Compiler import qualified Distribution.InstalledPackageInfo as Cabal import qualified Distribution.Package as Cabal import qualified Distribution.PackageDescription as Cabal import qualified Distribution.PackageDescription.Parse as Cabal import qualified Distribution.Text as Cabal import qualified Distribution.Version as Cabal import Hpack.Config hiding (package) import Text.PrettyPrint (fsep, (<+>)) -- * Public API -- | Reads a 'Package' from cabal's 'GenericPackageDescription' representation -- of a @.cabal@ file fromPackageDescription :: Cabal.GenericPackageDescription -> Package fromPackageDescription Cabal.GenericPackageDescription{..} = let Cabal.PackageDescription{..} = packageDescription in Package { packageName = Cabal.unPackageName (Cabal.pkgName package) , packageVersion = Version.showVersion (Cabal.pkgVersion package) , packageSynopsis = nullNothing synopsis , packageDescription = nullNothing description , packageHomepage = nullNothing homepage , packageBugReports = nullNothing bugReports , packageCategory = nullNothing category , packageStability = nullNothing stability , packageAuthor = maybe [] parseCommaSep (nullNothing author) , packageMaintainer = maybe [] parseCommaSep (nullNothing maintainer) , packageCopyright = maybe [] parseCommaSep (nullNothing copyright) , packageLicense = Just (show (Cabal.disp license)) , packageLicenseFile = listToMaybe licenseFiles , packageTestedWith = map toUpper . show . fsep . map (\(f, vr) -> Cabal.disp f <> Cabal.disp vr ) <$> nullNothing testedWith , packageFlags = map (\Cabal.MkFlag{..} -> let Cabal.FlagName fn = flagName in Flag { flagName = fn , flagDescription = nullNothing flagDescription , flagManual = flagManual , flagDefault = flagDefault }) genPackageFlags , packageExtraSourceFiles = extraSrcFiles , packageDataFiles = dataFiles , packageSourceRepository = fromSourceRepos sourceRepos , packageLibrary = fromCondLibrary condLibrary , packageExecutables = fromCondExecutables condExecutables , packageTests = fromCondTestSuites condTestSuites , packageBenchmarks = fromCondBenchmarks condBenchmarks } -- | Reads a 'Package' from a @.cabal@ manifest string fromPackageDescriptionString :: String -> Either ConvertError Package fromPackageDescriptionString pkgStr = case Cabal.parsePackageDescription pkgStr of Cabal.ParseFailed e -> Left (ConvertCabalParseError e) Cabal.ParseOk _ gpkg -> Right (fromPackageDescription gpkg) data ConvertError = ConvertCabalParseError Cabal.PError deriving(Show, Eq) -- data ConvertWarning = CWIgnoreSection String -- | CWIgnoreCondition String -- | CWIgnoreSourceRepo Cabal.SourceRepo -- | CWSourceRepoWithoutUrl Cabal.SourceRepo -- * Private functions for converting each section fromSourceRepos :: [Cabal.SourceRepo] -> Maybe SourceRepository fromSourceRepos [] = Nothing fromSourceRepos (_repo@Cabal.SourceRepo{..}:_more) = -- ( Just SourceRepository { sourceRepositoryUrl = fromMaybe "" repoLocation -- TODO - this is broken (?) , sourceRepositorySubdir = fmap processDir repoSubdir } -- TODO - Warnings -- , case repoLocation of -- Nothing -> [CWSourceRepoWithoutUrl repo] -- _ -> [] -- ++ map CWIgnoreSourceRepo more -- ) fromDependency :: Cabal.Dependency -> Dependency fromDependency (Cabal.Dependency pn vr) | vr == Cabal.anyVersion = Dependency (show (Cabal.disp pn)) Nothing fromDependency (Cabal.Dependency pn vr) = Dependency (show (Cabal.disp pn <+> Cabal.disp vr)) Nothing fromCondLibrary :: Maybe (Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Library) -> Maybe (Section Library) fromCondLibrary mcondLibrary = do condLibrary@(Cabal.CondNode Cabal.Library{libBuildInfo} _ components) <- mcondLibrary l <- libFromCondLibrary condLibrary return (sectionWithBuildInfo l libBuildInfo) { sectionConditionals = map fromCondComponentHasBuildInfo components } fromCondExecutables :: [(String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Executable)] -> [Section Executable] fromCondExecutables = map fromCondExecutableTup fromCondTestSuites :: [(String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.TestSuite)] -> [Section Executable] fromCondTestSuites = mapMaybe fromCondTestSuiteTup fromCondBenchmarks :: [(String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Benchmark)] -> [Section Executable] fromCondBenchmarks = mapMaybe fromCondBenchmarkTup fromCondExecutableTup :: (String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Executable) -> Section Executable fromCondExecutableTup etup@(_, Cabal.CondNode Cabal.Executable{buildInfo} _ components) = let e = exeFromCondExecutableTup etup in (sectionWithBuildInfo e buildInfo) { sectionConditionals = map fromCondComponentHasBuildInfo components } fromCondTestSuiteTup :: (String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.TestSuite) -> Maybe (Section Executable) fromCondTestSuiteTup ttup@(_, Cabal.CondNode Cabal.TestSuite{testBuildInfo} _ components) = do te <- testExeFromCondExecutableTup ttup return (sectionWithBuildInfo te testBuildInfo) { sectionConditionals = map fromCondComponentHasBuildInfo components } fromCondBenchmarkTup :: (String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Benchmark) -> Maybe (Section Executable) fromCondBenchmarkTup btup@(_, Cabal.CondNode Cabal.Benchmark{benchmarkBuildInfo} _ components) = do be <- benchExeFromCondExecutableTup btup return (sectionWithBuildInfo be benchmarkBuildInfo) { sectionConditionals = map fromCondComponentHasBuildInfo components } -- * Conditional Mapping class HasBuildInfo a where getBuildInfo :: a -> Cabal.BuildInfo instance HasBuildInfo Cabal.Library where getBuildInfo Cabal.Library{libBuildInfo} = libBuildInfo instance HasBuildInfo Cabal.Executable where getBuildInfo Cabal.Executable{buildInfo} = buildInfo instance HasBuildInfo Cabal.TestSuite where getBuildInfo Cabal.TestSuite{testBuildInfo} = testBuildInfo instance HasBuildInfo Cabal.Benchmark where getBuildInfo Cabal.Benchmark{benchmarkBuildInfo} = benchmarkBuildInfo fromCondHasBuildInfo :: HasBuildInfo a => Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] a -> Section () fromCondHasBuildInfo (Cabal.CondNode hbi _ components) = let bi = getBuildInfo hbi in (sectionWithBuildInfo () bi) { sectionConditionals = map fromCondComponentHasBuildInfo components } fromCondComponentHasBuildInfo :: (HasBuildInfo a) => ( Cabal.Condition Cabal.ConfVar , Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] a , Maybe (Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] a) ) -> Conditional fromCondComponentHasBuildInfo (cond, ifTree, elseTree) = Conditional { conditionalCondition = fromCondition cond , conditionalThen = fromCondHasBuildInfo ifTree , conditionalElse = fromCondHasBuildInfo <$> elseTree } fromCondition :: Cabal.Condition Cabal.ConfVar -> String fromCondition (Cabal.Var c) = case c of Cabal.OS os -> "os(" ++ show (Cabal.disp os) ++ ")" Cabal.Flag (Cabal.FlagName fl) -> "flag(" ++ fl ++ ")" Cabal.Arch ar -> "arch(" ++ show (Cabal.disp ar) ++ ")" Cabal.Impl cc vr -> "impl(" ++ show (Cabal.disp cc <+> Cabal.disp vr) ++ ")" fromCondition (Cabal.CNot c) = "!(" ++ fromCondition c ++ ")" fromCondition (Cabal.COr c1 c2) = "(" ++ fromCondition c1 ++ ") || (" ++ fromCondition c2 ++ ")" fromCondition (Cabal.CAnd c1 c2) = "(" ++ fromCondition c1 ++ ") && (" ++ fromCondition c2 ++ ")" fromCondition (Cabal.Lit b) = show b -- * Private helpers -- | Builds a 'Package' 'Section' from a data entity and a 'BuildInfo' entity sectionWithBuildInfo :: a -> Cabal.BuildInfo -> Section a sectionWithBuildInfo d Cabal.BuildInfo{..} = Section { sectionData = d , sectionSourceDirs = processDirs hsSourceDirs , sectionDependencies = map fromDependency targetBuildDepends , sectionDefaultExtensions = map (show . Cabal.disp) defaultExtensions , sectionOtherExtensions = map (show . Cabal.disp) otherExtensions , sectionGhcOptions = map (\l -> case words l of [] -> "" [x] -> x _ -> ensureQuoted l) $ fromMaybe [] $ lookup Compiler.GHC options , sectionGhcProfOptions = fromMaybe [] $ lookup Compiler.GHC profOptions , sectionCppOptions = cppOptions , sectionCCOptions = ccOptions , sectionCSources = cSources , sectionExtraLibDirs = processDirs extraLibDirs , sectionExtraLibraries = extraLibs , sectionIncludeDirs = processDirs includeDirs , sectionInstallIncludes = installIncludes , sectionLdOptions = ldOptions , sectionBuildable = Just buildable -- TODO ^^ ???? , sectionConditionals = [] -- TODO ^^ ???? , sectionBuildTools = map fromDependency buildTools } libFromCondLibrary :: Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Library -> Maybe Library libFromCondLibrary (Cabal.CondNode (Cabal.Library{..}) _ _) = do let Cabal.BuildInfo{..} = libBuildInfo return Library { libraryExposed = Just libExposed , libraryExposedModules = map (show . Cabal.disp) exposedModules , libraryOtherModules = map (show . Cabal.disp) otherModules , libraryReexportedModules = map (show . Cabal.disp) reexportedModules } exeFromCondExecutableTup :: (String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Executable) -> Executable exeFromCondExecutableTup (name, Cabal.CondNode Cabal.Executable{..} _ _) = Executable { executableName = name , executableMain = modulePath , executableOtherModules = map (show . Cabal.disp) (Cabal.otherModules buildInfo) } testExeFromCondExecutableTup :: (String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.TestSuite) -> Maybe Executable testExeFromCondExecutableTup (name, Cabal.CondNode Cabal.TestSuite{..} _ _) = case testInterface of Cabal.TestSuiteExeV10 _ mainIs -> Just Executable { executableName = name , executableMain = mainIs , executableOtherModules = map (show . Cabal.disp) (Cabal.otherModules testBuildInfo) } _ -> Nothing benchExeFromCondExecutableTup :: (String, Cabal.CondTree Cabal.ConfVar [Cabal.Dependency] Cabal.Benchmark) -> Maybe Executable benchExeFromCondExecutableTup (name, Cabal.CondNode Cabal.Benchmark{..} _ _) = case benchmarkInterface of Cabal.BenchmarkExeV10 _ mainIs -> Just Executable { executableName = name , executableMain = mainIs , executableOtherModules = map (show . Cabal.disp) (Cabal.otherModules benchmarkBuildInfo) } _ -> Nothing -- | Returns Nothing if a list is empty and Just the list otherwise -- -- >>> nullNothing [] -- Nothing -- >>> nullNothing [1, 2, 3] -- Just [1, 2, 3] nullNothing :: [a] -> Maybe [a] nullNothing s = const s <$> listToMaybe s processDirs :: [String] -> [String] processDirs = map processDir -- | Replaces @.@ with @./.@ -- -- See https://github.com/sol/hpack/issues/119 processDir :: String -> String processDir "." = "./." processDir d = d -- | Parse comma separated list, stripping whitespace parseCommaSep :: String -> [String] parseCommaSep s = -- separate on commas -- strip leading and trailing whitespace fmap trimEnds (splitOn "," s) -- | Trim leading and trailing whitespace trimEnds :: String -> String trimEnds = f . f where f = reverse . dropWhile isSpace ensureQuoted :: String -> String ensureQuoted l = if isQuoted l then l else "\"" <> l <> "\"" isQuoted :: String -> Bool isQuoted s = testQuote '\'' || testQuote '\"' where testQuote q = head s == q && last s == q
yamadapc/hpack-convert
src/Hpack/Convert.hs
mit
13,953
0
17
3,912
3,153
1,669
1,484
216
4
{-| Module : Language.GoLite.Lexer Description : Lexer combinators for the GoLite language. Copyright : (c) Jacob Errington and Frederic Lafrance, 2016 License : MIT Maintainer : goto@mail.jerrington.me Stability : experimental -} module Language.GoLite.Lexer ( module Language.GoLite.Lexer.Core , module Language.GoLite.Lexer.Keywords , module Language.GoLite.Lexer.Literal , module Language.GoLite.Lexer.Semi , module Language.GoLite.Lexer.Symbols ) where import Language.GoLite.Lexer.Core import Language.GoLite.Lexer.Keywords import Language.GoLite.Lexer.Literal import Language.GoLite.Lexer.Semi import Language.GoLite.Lexer.Symbols
djeik/goto
libgoto/Language/GoLite/Lexer.hs
mit
654
0
5
76
85
62
23
11
0
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Lens import Control.Monad import Data.Char import Data.Maybe import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Time import System.Environment import Text.Printf import SpaceWeather.Format import SpaceWeather.TimeLine import qualified System.IO.Hadoop as HFS -- AIA/AIA20100701_010006_0193.fits 5.1739596800e+09 main :: IO () main = getArgs >>= mapM_ process process :: FilePath -> IO () process fn0 = do txt0 <- HFS.readFile fn0 let ls0 = T.lines txt0 lsx = mapMaybe parse ls0 fn1=fn0 ++ ".timebin" parse :: T.Text -> Maybe (TimeBin, Double) parse txt1 = do let txt2 = T.dropWhile (not . isDigit) txt1 iyear <- readMaySubT 0 4 txt2 imon <- readMaySubT 4 2 txt2 iday <- readMaySubT 6 2 txt2 ihour <- readMaySubT 9 2 txt2 let day = fromGregorian iyear imon iday sec = secondsToDiffTime $ ihour * 3600 t = UTCTime day sec val <- readAt (T.words txt1) 1 Just (t ^. discreteTime, val) lsxpp :: T.Text lsxpp = T.unlines $ map (\(t,v) -> T.pack $ printf "%6d %20e" t v ) lsx HFS.writeFile fn1 lsxpp
nushio3/UFCORIN
exe-src/aia2timebin.hs
mit
1,241
0
17
327
408
212
196
37
1
module Types.Commands where import Data.Romefile import Data.Carthage.TargetPlatform data RomeCommand = Upload RomeUDCPayload | Download RomeUDCPayload | List RomeListPayload | Utils RomeUtilsPayload deriving (Show, Eq) data RomeUDCPayload = RomeUDCPayload { _payload :: [ProjectName] , _udcPlatforms :: [TargetPlatform] , _cachePrefix :: String -- , _verifyFlag :: VerifyFlag , _skipLocalCacheFlag :: SkipLocalCacheFlag , _noIgnoreFlag :: NoIgnoreFlag , _noSkipCurrentFlag :: NoSkipCurrentFlag , _concurrentlyFlag :: ConcurrentlyFlag } deriving (Show, Eq) data RomeUtilsPayload = RomeUtilsPayload { _subcommand :: RomeUtilsSubcommand } deriving (Show, Eq) data RomeUtilsSubcommand = MigrateRomefile deriving (Show, Eq) -- newtype VerifyFlag = VerifyFlag { _verify :: Bool } deriving (Show, Eq) newtype SkipLocalCacheFlag = SkipLocalCacheFlag { _skipLocalCache :: Bool } deriving (Show, Eq) newtype NoIgnoreFlag = NoIgnoreFlag { _noIgnore :: Bool } deriving (Show, Eq) newtype NoSkipCurrentFlag = NoSkipCurrentFlag { _noSkipCurrent :: Bool } deriving (Show, Eq) newtype ConcurrentlyFlag = ConcurrentlyFlag { _concurrently :: Bool } deriving (Show, Eq) data RomeListPayload = RomeListPayload { _listMode :: ListMode , _listPlatforms :: [TargetPlatform] , _listCachePrefix :: String , _listFormat :: PrintFormat , _listNoIgnoreFlag :: NoIgnoreFlag , _listNoSkipCurrentFlag :: NoSkipCurrentFlag } deriving (Show, Eq) data PrintFormat = Text | JSON deriving (Show, Eq, Read) data ListMode = All | Missing | Present deriving (Show, Eq) data RomeOptions = RomeOptions { romeCommand :: RomeCommand , romefilePath :: FilePath , verbose :: Bool } deriving (Show, Eq)
blender/Rome
src/Types/Commands.hs
mit
2,882
0
9
1,442
408
249
159
45
0
{-# LANGUAGE OverloadedStrings #-} -- | This module contains everything that you need to support -- server-sent events in Yesod applications. module Yesod.EventSource ( RepEventSource , repEventSource , ioToRepEventSource , EventSourcePolyfill(..) ) where import Blaze.ByteString.Builder (Builder) import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import Data.Functor ((<$>)) import Data.Monoid (mappend, mempty) import Yesod.Content import Yesod.Core import qualified Data.Conduit as C import qualified Network.Wai as W import qualified Network.Wai.EventSource as ES import qualified Network.Wai.EventSource.EventStream as ES -- | Data type representing a response of server-sent events -- (e.g., see 'repEventSource' and 'ioToRepEventSource'). newtype RepEventSource = RepEventSource (C.Source (C.ResourceT IO) (C.Flush Builder)) instance HasReps RepEventSource where chooseRep (RepEventSource src) = const $ return ("text/event-stream", ContentSource src) -- | (Internal) Find out the request's 'EventSourcePolyfill' and -- set any necessary headers. prepareForEventSource :: GHandler sub master EventSourcePolyfill prepareForEventSource = do reqWith <- lookup "X-Requested-With" . W.requestHeaders <$> waiRequest let polyfill | reqWith == Just "XMLHttpRequest" = Remy'sESPolyfill | otherwise = NoESPolyfill setHeader "Cache-Control" "no-cache" -- extremely important! return polyfill -- | Returns a Server-Sent Event stream from a 'C.Source' of -- 'ES.ServerEvent'@s@. The HTTP socket is flushed after every -- event. The connection is closed either when the 'C.Source' -- finishes outputting data or a 'ES.CloseEvent' is outputted, -- whichever comes first. repEventSource :: (EventSourcePolyfill -> C.Source (C.ResourceT IO) ES.ServerEvent) -> GHandler sub master RepEventSource repEventSource src = RepEventSource . ES.sourceToSource . src <$> prepareForEventSource -- | Return a Server-Sent Event stream given an @IO@ action that -- is repeatedly called. A state is threaded for the action so -- that it may avoid using @IORefs@. The @IO@ action may sleep -- or block while waiting for more data. The HTTP socket is -- flushed after every list of simultaneous events. The -- connection is closed as soon as an 'ES.CloseEvent' is -- outputted, after which no other events are sent to the client. ioToRepEventSource :: s -> (EventSourcePolyfill -> s -> IO ([ES.ServerEvent], s)) -> GHandler sub master RepEventSource ioToRepEventSource initial act = do polyfill <- prepareForEventSource let -- Get new events to be sent. getEvents s = do (evs, s') <- liftIO (act polyfill s) case evs of [] -> getEvents s' _ -> do let (builder, continue) = joinEvents evs mempty C.yield (C.Chunk builder) C.yield C.Flush when continue (getEvents s') -- Join all events in a single Builder. Returns @False@ -- when we the connection should be closed. joinEvents (ev:evs) acc = case ES.eventToBuilder ev of Just b -> joinEvents evs (acc `mappend` b) Nothing -> (fst $ joinEvents [] acc, False) joinEvents [] acc = (acc, True) return $ RepEventSource $ getEvents initial -- | Which @EventSource@ polyfill was detected (if any). data EventSourcePolyfill = NoESPolyfill -- ^ We didn't detect any @EventSource@ polyfill that we know. | Remy'sESPolyfill -- ^ See -- <https://github.com/remy/polyfills/blob/master/EventSource.js>. -- In order to support Remy\'s polyfill, your server needs to -- explicitly close the connection from time to -- time--browsers such as IE7 will not show any event until -- the connection is closed. deriving (Eq, Ord, Show, Enum)
piyush-kurur/yesod
yesod-eventsource/Yesod/EventSource.hs
mit
3,886
0
20
830
690
377
313
57
4
-- | -- The first HW assignment. module HW1.CreditCard (toDigits, toDigitsRev, doubleEveryOther, sumDigits, validate) where import Data.Char -- | -- Returns a list of digits. -- -- >>> toDigits 1234 -- [1,2,3,4] -- -- >>> toDigits 0 -- [] -- -- >>> toDigits (-17) -- [] toDigits :: Integer -> [Integer] -- | -- Returns a reversed list of digits. -- -- >>> toDigitsRev 1234 -- [4,3,2,1] toDigitsRev :: Integer -> [Integer] -- | -- Doubles every other element, starting from the right -- -- >>> doubleEveryOther [8,7,6,5] -- [16,7,12,5] -- -- >>> doubleEveryOther [1,2,3] -- [1,4,3] doubleEveryOther :: [Integer] -> [Integer] -- | -- Returns the sum of the sum of the digits of the elements of the list. -- -- >>> sumDigits [12,3,4] -- 10 -- -- >>> sumDigits [16,7,12,5] -- 22 -- -- >>> sumDigits [] -- 0 sumDigits :: [Integer] -> Integer -- | -- Validates a "credit card number". Doubles every other element of the list, starting from the right, -- calculates the sum of all of the digits, and returns true if the result is divisible by 10. -- -- >>> validate 4012888888881881 -- True -- -- >>> validate 4012888888881882 -- False validate :: Integer -> Bool toDigits n | n <= 0 = [] | otherwise = map fromIntegral . map digitToInt . show $ n toDigitsRev = reverse . toDigits doubleEveryOther x = reverse (dropSecond ( map doubleSecond (tagItems (reverse x)))) sumDigits = sum . concat . map toDigits validate = validateChecksum . checksum --private functions tagItems :: (Num b) => [a] -> [(a,b)] tagItems x = zip x (take (length x) $ cycle [1,2]) doubleSecond :: (Num a, Num b, Eq b) => (a,b) -> (a,b) doubleSecond (a, b) | b == 2 = (2 * a, b) | otherwise = (a,b) dropSecond :: [(a,b)] -> [a] dropSecond = map fst type Checksum = Integer checksum :: Integer -> Checksum checksum x = fromInteger (sumDigits $ doubleEveryOther $ toDigits x) `rem` 10 validateChecksum :: Checksum -> Bool validateChecksum x | x == 0 = True | otherwise = False
mulchy/practice
src/HW1/CreditCard.hs
mit
1,966
0
13
374
523
303
220
29
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLTableColElement (js_setAlign, setAlign, js_getAlign, getAlign, js_setCh, setCh, js_getCh, getCh, js_setChOff, setChOff, js_getChOff, getChOff, js_setSpan, setSpan, js_getSpan, getSpan, js_setVAlign, setVAlign, js_getVAlign, getVAlign, js_setWidth, setWidth, js_getWidth, getWidth, HTMLTableColElement, castToHTMLTableColElement, gTypeHTMLTableColElement) 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[\"align\"] = $2;" js_setAlign :: JSRef HTMLTableColElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.align Mozilla HTMLTableColElement.align documentation> setAlign :: (MonadIO m, ToJSString val) => HTMLTableColElement -> val -> m () setAlign self val = liftIO (js_setAlign (unHTMLTableColElement self) (toJSString val)) foreign import javascript unsafe "$1[\"align\"]" js_getAlign :: JSRef HTMLTableColElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.align Mozilla HTMLTableColElement.align documentation> getAlign :: (MonadIO m, FromJSString result) => HTMLTableColElement -> m result getAlign self = liftIO (fromJSString <$> (js_getAlign (unHTMLTableColElement self))) foreign import javascript unsafe "$1[\"ch\"] = $2;" js_setCh :: JSRef HTMLTableColElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.ch Mozilla HTMLTableColElement.ch documentation> setCh :: (MonadIO m, ToJSString val) => HTMLTableColElement -> val -> m () setCh self val = liftIO (js_setCh (unHTMLTableColElement self) (toJSString val)) foreign import javascript unsafe "$1[\"ch\"]" js_getCh :: JSRef HTMLTableColElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.ch Mozilla HTMLTableColElement.ch documentation> getCh :: (MonadIO m, FromJSString result) => HTMLTableColElement -> m result getCh self = liftIO (fromJSString <$> (js_getCh (unHTMLTableColElement self))) foreign import javascript unsafe "$1[\"chOff\"] = $2;" js_setChOff :: JSRef HTMLTableColElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.chOff Mozilla HTMLTableColElement.chOff documentation> setChOff :: (MonadIO m, ToJSString val) => HTMLTableColElement -> val -> m () setChOff self val = liftIO (js_setChOff (unHTMLTableColElement self) (toJSString val)) foreign import javascript unsafe "$1[\"chOff\"]" js_getChOff :: JSRef HTMLTableColElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.chOff Mozilla HTMLTableColElement.chOff documentation> getChOff :: (MonadIO m, FromJSString result) => HTMLTableColElement -> m result getChOff self = liftIO (fromJSString <$> (js_getChOff (unHTMLTableColElement self))) foreign import javascript unsafe "$1[\"span\"] = $2;" js_setSpan :: JSRef HTMLTableColElement -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.span Mozilla HTMLTableColElement.span documentation> setSpan :: (MonadIO m) => HTMLTableColElement -> Int -> m () setSpan self val = liftIO (js_setSpan (unHTMLTableColElement self) val) foreign import javascript unsafe "$1[\"span\"]" js_getSpan :: JSRef HTMLTableColElement -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.span Mozilla HTMLTableColElement.span documentation> getSpan :: (MonadIO m) => HTMLTableColElement -> m Int getSpan self = liftIO (js_getSpan (unHTMLTableColElement self)) foreign import javascript unsafe "$1[\"vAlign\"] = $2;" js_setVAlign :: JSRef HTMLTableColElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.vAlign Mozilla HTMLTableColElement.vAlign documentation> setVAlign :: (MonadIO m, ToJSString val) => HTMLTableColElement -> val -> m () setVAlign self val = liftIO (js_setVAlign (unHTMLTableColElement self) (toJSString val)) foreign import javascript unsafe "$1[\"vAlign\"]" js_getVAlign :: JSRef HTMLTableColElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.vAlign Mozilla HTMLTableColElement.vAlign documentation> getVAlign :: (MonadIO m, FromJSString result) => HTMLTableColElement -> m result getVAlign self = liftIO (fromJSString <$> (js_getVAlign (unHTMLTableColElement self))) foreign import javascript unsafe "$1[\"width\"] = $2;" js_setWidth :: JSRef HTMLTableColElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.width Mozilla HTMLTableColElement.width documentation> setWidth :: (MonadIO m, ToJSString val) => HTMLTableColElement -> val -> m () setWidth self val = liftIO (js_setWidth (unHTMLTableColElement self) (toJSString val)) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: JSRef HTMLTableColElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement.width Mozilla HTMLTableColElement.width documentation> getWidth :: (MonadIO m, FromJSString result) => HTMLTableColElement -> m result getWidth self = liftIO (fromJSString <$> (js_getWidth (unHTMLTableColElement self)))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/HTMLTableColElement.hs
mit
6,314
84
11
949
1,404
770
634
99
1
module Raindrops (convert) where convert :: Int -> String convert input = [result | (appliesTo, result) <- rules, appliesTo input] `concatOrIfEmpty` show input concatOrIfEmpty :: [String] -> String -> String concatOrIfEmpty [] defaultValue = defaultValue concatOrIfEmpty list _ = concat list rules :: [(Int -> Bool, String)] rules = [ (divisibleBy 3, "Pling"), (divisibleBy 5, "Plang"), (divisibleBy 7, "Plong") ] divisibleBy :: Int -> Int -> Bool divisibleBy divisor input = input `mod` divisor == 0
enolive/exercism
haskell/raindrops/src/Raindrops.hs
mit
519
0
9
94
192
107
85
16
1
module TreeStuff ( Tree () , emptyTree , insertChar , insert , insertStrings , makeTree , findChar , findString ) where -------------------- -- Global Imports -- import Control.Lens import Data.Char ---------- -- Code -- -- | The tuple type. type TreeTuple = (Bool, Tree) -- | The tree type newtype Tree = Tree [TreeTuple] -- | Being able to display the Tree without going down EVERY SINGLE PATH instance Show Tree where show (Tree l) = "( Tree " ++ showTree l ++ ") " -- | The more raw function for displaying the tree. showTree :: [(Bool, Tree)] -> String showTree [] = "" showTree ((False, _):ts) = "end " ++ showTree ts showTree ((True , t):ts) = show t ++ showTree ts -- | Getting the bool of a @'TreeTuple'@. getBool :: TreeTuple -> Bool getBool = fst -- | Getting the tree of a @'TreeTuple'@. getTree :: TreeTuple -> Tree getTree = snd -- | Setting the value of the @'Bool'@ in a @'TreeTuple'@. setBool :: TreeTuple -> Bool -> TreeTuple setBool (_, t) b = (b, t) -- | Setting the value of the @'Tree'@ in a @'TreeTuple'@. setTree :: TreeTuple -> Tree -> TreeTuple setTree (b, _) t = (b, t) -- | Getting the index in the array for the char. charIndex :: Char -> Int charIndex c = fromEnum (toUpper c) - 65 -- | Creating an empty tree emptyTree :: Tree emptyTree = Tree $ zip (repeat False) (replicate 26 emptyTree) -- | Inserting a single char into a tree. insertChar :: Tree -> Char -> Tree insertChar (Tree l) c = Tree $ l & ix ci .~ (setBool (l !! ci) True) where ci = charIndex c -- | Inserting a string into a tree. insert :: Tree -> String -> Tree insert t [] = t insert t (c:[]) = insertChar t c insert t (c:cs) = Tree $ tus & ix ci .~ (setTree targetTuple $ insert (getTree $ targetTuple) cs) where ci = charIndex c (Tree tus) = insertChar t c targetTuple = tus !! ci -- | Inserting a list of strings into a tree. insertStrings :: Tree -> [String] -> Tree insertStrings = foldl insert -- | Given a list of words, makes a tree from them makeTree :: [String] -> Tree makeTree = insertStrings emptyTree -- | Checking if a Char in a given Tree is valid. findChar :: Tree -> Char -> Bool findChar (Tree l) c = getBool $ l !! charIndex c -- | Finding if a String is valid in a given Tree. findString :: Tree -> String -> Bool findString _ [] = False findString t (c:[]) = findChar t c findString t@(Tree l) (c:cs) | findChar t c = findString (getTree $ l !! charIndex c) cs | otherwise = False
crockeo/treestuff
trie_in_hs/src/TreeStuff.hs
mit
2,680
0
10
751
773
419
354
60
1
{-# LANGUAGE DataKinds #-} -- | Finding files. module Filesystem.Path.Find where import Data.List import Data.Maybe import Filesystem import Filesystem.Loc as FL import Prelude hiding (FilePath) -- | Find the location of a file matching the given predicate. findFileUp :: Loc Absolute Dir -- ^ Start here. -> (Loc Absolute File -> Bool) -- ^ Predicate to match the file. -> Maybe (Loc Absolute Dir) -- ^ Do not ascend above this directory. -> IO (Maybe (Loc Absolute File)) -- ^ Absolute file path. findFileUp dir p upperBound = do files <- listDirectory (FL.toFilePath dir) case find p (mapMaybe parseAbsoluteFileLoc files) of Just path -> return (Just path) Nothing -> if Just dir == upperBound then return Nothing else if FL.parentOfDir dir == dir then return Nothing else findFileUp (FL.parentOfDir dir) p upperBound
fpco/stackage-view
server/Filesystem/Path/Find.hs
mit
1,063
0
15
374
232
121
111
24
4
module Piece (Piece(..), Color(..), Shape(..), Height(..), Top(..), haveCommonProperty, printPiece, readPiece) where import Data.Char import Data.List data Color = White | Black deriving (Show, Eq) data Shape = Circular | Square deriving (Show, Eq) data Height = Short | Tall deriving (Show, Eq) data Top = Hollow | Solid deriving (Show, Eq) data Piece = Piece Color Shape Height Top deriving (Show, Eq) haveCommonProperty :: [Piece] -> Bool haveCommonProperty pieces = any (haveCommonBool pieces) [0..3] haveCommonBool :: [Piece] -> Int -> Bool haveCommonBool pieces index = length (nub (map ((!! index) . pieceToBools) pieces)) == 1 pieceToBools :: Piece -> [Bool] pieceToBools (Piece White Circular Short Hollow) = [False, False, False, False] pieceToBools (Piece White Circular Short Solid) = [False, False, False, True] pieceToBools (Piece White Circular Tall Hollow) = [False, False, True, False] pieceToBools (Piece White Circular Tall Solid) = [False, False, True, True] pieceToBools (Piece White Square Short Hollow) = [False, True, False, False] pieceToBools (Piece White Square Short Solid) = [False, True, False, True] pieceToBools (Piece White Square Tall Hollow) = [False, True, True, False] pieceToBools (Piece White Square Tall Solid) = [False, True, True, True] pieceToBools (Piece Black Circular Short Hollow) = [True, False, False, False] pieceToBools (Piece Black Circular Short Solid) = [True, False, False, True] pieceToBools (Piece Black Circular Tall Hollow) = [True, False, True, False] pieceToBools (Piece Black Circular Tall Solid) = [True, False, True, True] pieceToBools (Piece Black Square Short Hollow) = [True, True, False, False] pieceToBools (Piece Black Square Short Solid) = [True, True, False, True] pieceToBools (Piece Black Square Tall Hollow) = [True, True, True, False] pieceToBools (Piece Black Square Tall Solid) = [True, True, True, True] printPiece :: Piece -> String printPiece piece = zipWith caseSelector (pieceToBools piece) "CSHT" where caseSelector True = toUpper caseSelector False = toLower readPiece :: String -> Maybe Piece readPiece [c, s, h, t] = do color <- readColor c shape <- readShape s height <- readHeight h top <- readTop t Just (Piece color shape height top) readPiece _ = Nothing readColor :: Char -> Maybe Color readColor 'c' = Just White readColor 'C' = Just Black readColor _ = Nothing readShape :: Char -> Maybe Shape readShape 's' = Just Circular readShape 'S' = Just Square readShape _ = Nothing readHeight :: Char -> Maybe Height readHeight 'h' = Just Short readHeight 'H' = Just Tall readHeight _ = Nothing readTop :: Char -> Maybe Top readTop 't' = Just Hollow readTop 'T' = Just Solid readTop _ = Nothing
nablaa/hquarto
src/Piece.hs
gpl-2.0
2,913
0
13
648
1,102
598
504
63
2
{-# LANGUAGE DeriveDataTypeable #-} module Blaaargh.Internal.Exception ( BlaaarghException(..) , blaaarghExceptionMsg ) where import Control.Exception import Data.Typeable import Prelude hiding (catch) -- | 'BlaaarghException' is the exception type thrown when Blaaargh encounters -- an error. data BlaaarghException = BlaaarghException String deriving (Show, Typeable) instance Exception BlaaarghException -- | Obtain the error message from a 'BlaaarghException' blaaarghExceptionMsg :: BlaaarghException -> String blaaarghExceptionMsg (BlaaarghException s) = s
gregorycollins/blaaargh
src/Blaaargh/Internal/Exception.hs
gpl-2.0
603
0
7
104
92
55
37
12
1
module Factor where -- Returns whether n is a factor of p -- Time: O(1), Space: O(1) isFactorOf :: Integer -> Integer -> Bool isFactorOf n p = p `rem` n == 0
NorfairKing/project-euler
lib/haskell/Factor.hs
gpl-2.0
159
0
6
34
39
23
16
3
1
sumOfSquare :: Int -> Int sumOfSquare x = sum(map (^2) [1..x]) squareOfSum :: Int -> Int squareOfSum x = (sum [1..x])^2 n = 100 main = print (squareOfSum n - sumOfSquare n)
garykrige/project_euler
Haskell/euler/euler6.hs
gpl-2.0
175
0
8
34
96
50
46
6
1
module Crepuscolo.Recognizer.C ( recognizer ) where import System.FilePath (takeExtension) import Text.Regex.PCRE ((=~)) import qualified Crepuscolo.Recognize.DSL as DSL data Recognizer = C deriving (Show) instance DSL.Recognizer Recognizer where recognize C path = case takeExtension path of ".c" -> return (Just "c") ".h" -> do content <- readFile path return $ if notCXX content then Just "c" else Nothing _ -> return Nothing where notCXX string = not (string =~ "\\bclass\\b") && not (string =~ "::") recognizePath C path = case takeExtension path of ".c" -> Just "c" ".h" -> Just "c" _ -> Nothing recognizeContent C string = if string =~ "^\\s*#include" && not (string =~ "\\bclass\\b") && not (string =~ "::") then Just "c" else Nothing recognizer :: DSL.Recognizable recognizer = DSL.recognizable C
meh/crepuscolo
src/Crepuscolo/Recognizer/C.hs
gpl-3.0
1,048
0
13
365
291
151
140
28
1
-- grid is a game written in Haskell -- Copyright (C) 2018 karamellpelle@hotmail.com -- -- This file is part of grid. -- -- grid 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. -- -- grid 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 grid. If not, see <http://www.gnu.org/licenses/>. -- module Game.Memory.MemoryWorld.OutputState ( #ifdef GRID_STYLE_FANCY module Game.Memory.MemoryWorld.OutputState.Fancy, #endif #ifdef GRID_STYLE_PLAIN module Game.Memory.MemoryWorld.OutputState.Plain, #endif ) where #ifdef GRID_STYLE_FANCY import Game.Memory.MemoryWorld.OutputState.Fancy #endif #ifdef GRID_STYLE_PLAIN import Game.Memory.MemoryWorld.OutputState.Plain #endif
karamellpelle/grid
source/Game/Memory/MemoryWorld/OutputState.hs
gpl-3.0
1,143
0
5
180
71
60
11
2
0
-- tree construction from node string data Tree a = Node a [Tree a] deriving Show p70 :: String -> Tree Char p70 (x:xs) = Node x (fst (p70' xs)) where p70' (x:xs) | x == '^' = ([], xs) | otherwise = (Node x tree0 : trees1, rest1) where (tree0, rest0) = p70' xs (trees1, rest1) = p70' rest0
yalpul/CENG242
H99/70-73/p70.hs
gpl-3.0
383
0
10
153
158
82
76
8
1
{- # This file is part of matrix-arbitrary. # # # # matrix-arbitrary 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. # # # # matrix-arbitrary 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. # # # # A copy of the GNU General Public License resides in the `LICENSE` # # file distributed along with matrix-arbitrary. # # # # Copyright 2012, Johannes Weiß <weiss@tux4u.de> # # # # Thanks to Alberto Ruiz for the `instance Show Matrix` code, shamelessly # # stolen from hmatrix # -} module Data.Matrix.Internal ( Matrix(..) , (><) , rows, cols, shape , trans , fromLists, toLists ) where import Data.Array.IArray (Array) import Data.List (transpose, intersperse) import Data.Tuple (swap) import qualified Data.Array.IArray as A newtype Matrix e = Matrix (Array (Int, Int) e) (><) :: Int -> Int -> [a] -> Matrix a (><) r c = Matrix . A.listArray ((1,1), (r,c)) shape :: Matrix a -> (Int, Int) shape (Matrix m) = (snd . A.bounds) m cols :: Matrix a -> Int cols = snd . shape rows :: Matrix a -> Int rows = fst . shape trans :: Matrix a -> Matrix a trans m@(Matrix arr) = Matrix $ A.ixmap ((1,1), (swap . shape) m) swap arr toLists :: Matrix a -> [[a]] toLists m@(Matrix arr) = let doIt :: Int -> [a] -> Int -> [[a]] -> [[a]] doIt c es' r acc = if r > 0 then let (mes, es'') = splitAt c es' in doIt c es'' (r-1) (acc++[mes]) else acc (mRows, mCols) = shape m in doIt mCols (A.elems arr) mRows [] fromLists :: [[a]] -> Matrix a fromLists es = let mRows :: Int mRows = length es mCols' :: [Int] mCols' = map length es mCols :: Int mCols = let minCols = minimum mCols' maxCols = minimum mCols' in if minCols == maxCols then minCols else error "fromLists: applied to lists of different sizes" in (mRows >< mCols) $ concat es instance (Show e) => (Show (Matrix e)) where show m = (sizes++) . dsp . map (map show) . toLists $ m where sizes = "("++show (rows m)++"><"++show (cols m)++")\n" dsp as = let mt = transpose as longs = map (maximum . map length) mt mtp = zipWith (\a b -> map (pad a) b) longs mt pad n str = replicate (n - length str) ' ' ++ str unwords' = concat . intersperse ", " in (++" ]") . (" ["++) . init . drop 2 . unlines . map (" , "++) . map unwords' $ transpose mtp instance (Eq e) => Eq (Matrix e) where (==) (Matrix l) (Matrix r) = l == r -- vim: set fileencoding=utf8 :
weissi/matrix-arbitrary
src/Data/Matrix/Internal.hs
gpl-3.0
3,784
2
15
1,650
960
514
446
58
2
-- The account register screen, showing transactions in an account, like hledger-web's register. {-# LANGUAGE OverloadedStrings, FlexibleContexts, RecordWildCards #-} module Hledger.UI.RegisterScreen (registerScreen ,rsHandle ,rsSetAccount ,rsCenterAndContinue ) where import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.List.Split (splitOn) import Data.Monoid import Data.Maybe import qualified Data.Text as T import Data.Time.Calendar import qualified Data.Vector as V import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Brick import Brick.Widgets.List import Brick.Widgets.Edit import Brick.Widgets.Border (borderAttr) import Lens.Micro.Platform import Safe import System.Console.ANSI import Hledger import Hledger.Cli hiding (progname,prognameandversion) import Hledger.UI.UIOptions -- import Hledger.UI.Theme import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.Editor import Hledger.UI.TransactionScreen import Hledger.UI.ErrorScreen registerScreen :: Screen registerScreen = RegisterScreen{ sInit = rsInit ,sDraw = rsDraw ,sHandle = rsHandle ,rsList = list RegisterList V.empty 1 ,rsAccount = "" ,rsForceInclusive = False } rsSetAccount :: AccountName -> Bool -> Screen -> Screen rsSetAccount a forceinclusive scr@RegisterScreen{} = scr{rsAccount=replaceHiddenAccountsNameWith "*" a, rsForceInclusive=forceinclusive} rsSetAccount _ _ scr = scr rsInit :: Day -> Bool -> UIState -> UIState rsInit d reset ui@UIState{aopts=UIOpts{cliopts_=CliOpts{reportopts_=ropts}}, ajournal=j, aScreen=s@RegisterScreen{..}} = ui{aScreen=s{rsList=newitems'}} where -- gather arguments and queries -- XXX temp inclusive = not (flat_ ropts) || rsForceInclusive thisacctq = Acct $ (if inclusive then accountNameToAccountRegex else accountNameToAccountOnlyRegex) rsAccount ropts' = ropts{ depth_=Nothing } q = queryFromOpts d ropts' -- reportq = filterQuery (not . queryIsDepth) q (_label,items) = accountTransactionsReport ropts' j q thisacctq items' = (if empty_ ropts' then id else filter (not . isZeroMixedAmount . fifth6)) $ -- without --empty, exclude no-change txns reverse -- most recent last items -- generate pre-rendered list items. This helps calculate column widths. displayitems = map displayitem items' where displayitem (t, _, _issplit, otheracctsstr, change, bal) = RegisterScreenItem{rsItemDate = showDate $ transactionRegisterDate q thisacctq t ,rsItemStatus = tstatus t ,rsItemDescription = T.unpack $ tdescription t ,rsItemOtherAccounts = case splitOn ", " otheracctsstr of [s] -> s ss -> intercalate ", " ss -- _ -> "<split>" -- should do this if accounts field width < 30 ,rsItemChangeAmount = showMixedAmountOneLineWithoutPrice change ,rsItemBalanceAmount = showMixedAmountOneLineWithoutPrice bal ,rsItemTransaction = t } -- blank items are added to allow more control of scroll position; we won't allow movement over these blankitems = replicate 100 -- 100 ought to be enough for anyone RegisterScreenItem{rsItemDate = "" ,rsItemStatus = Unmarked ,rsItemDescription = "" ,rsItemOtherAccounts = "" ,rsItemChangeAmount = "" ,rsItemBalanceAmount = "" ,rsItemTransaction = nulltransaction } -- build the List newitems = list RegisterList (V.fromList $ displayitems ++ blankitems) 1 -- decide which transaction is selected: -- if reset is true, the last (latest) transaction; -- otherwise, the previously selected transaction if possible; -- otherwise, the transaction nearest in date to it; -- or if there's several with the same date, the nearest in journal order; -- otherwise, the last (latest) transaction. newitems' = listMoveTo newselidx newitems where newselidx = case (reset, listSelectedElement rsList) of (True, _) -> endidx (_, Nothing) -> endidx (_, Just (_, RegisterScreenItem{rsItemTransaction=Transaction{tindex=prevselidx, tdate=prevseld}})) -> headDef endidx $ catMaybes [ findIndex ((==prevselidx) . tindex . rsItemTransaction) displayitems ,findIndex ((==nearestidbydatethenid) . Just . tindex . rsItemTransaction) displayitems ] where nearestidbydatethenid = third3 <$> (headMay $ sort [(abs $ diffDays (tdate t) prevseld, abs (tindex t - prevselidx), tindex t) | t <- ts]) ts = map rsItemTransaction displayitems endidx = length displayitems - 1 rsInit _ _ _ = error "init function called with wrong screen type, should not happen" rsDraw :: UIState -> [Widget Name] rsDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,aScreen=RegisterScreen{..} ,aMode=mode } = case mode of Help -> [helpDialog copts, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where displayitems = V.toList $ rsList ^. listElementsL maincontent = Widget Greedy Greedy $ do -- calculate column widths, based on current available width c <- getContext let totalwidth = c^.availWidthL - 2 -- XXX due to margin ? shouldn't be necessary (cf UIUtils) -- the date column is fixed width datewidth = 10 -- multi-commodity amounts rendered on one line can be -- arbitrarily wide. Give the two amounts as much space as -- they need, while reserving a minimum of space for other -- columns and whitespace. If they don't get all they need, -- allocate it to them proportionally to their maximum widths. whitespacewidth = 10 -- inter-column whitespace, fixed width minnonamtcolswidth = datewidth + 1 + 2 + 2 -- date column plus at least 1 for status and 2 for desc and accts maxamtswidth = max 0 (totalwidth - minnonamtcolswidth - whitespacewidth) maxchangewidthseen = maximum' $ map (strWidth . rsItemChangeAmount) displayitems maxbalwidthseen = maximum' $ map (strWidth . rsItemBalanceAmount) displayitems changewidthproportion = fromIntegral maxchangewidthseen / fromIntegral (maxchangewidthseen + maxbalwidthseen) maxchangewidth = round $ changewidthproportion * fromIntegral maxamtswidth maxbalwidth = maxamtswidth - maxchangewidth changewidth = min maxchangewidth maxchangewidthseen balwidth = min maxbalwidth maxbalwidthseen -- assign the remaining space to the description and accounts columns -- maxdescacctswidth = totalwidth - (whitespacewidth - 4) - changewidth - balwidth maxdescacctswidth = -- trace (show (totalwidth, datewidth, changewidth, balwidth, whitespacewidth)) $ max 0 (totalwidth - datewidth - 1 - changewidth - balwidth - whitespacewidth) -- allocating proportionally. -- descwidth' = maximum' $ map (strWidth . second6) displayitems -- acctswidth' = maximum' $ map (strWidth . third6) displayitems -- descwidthproportion = (descwidth' + acctswidth') / descwidth' -- maxdescwidth = min (maxdescacctswidth - 7) (maxdescacctswidth / descwidthproportion) -- maxacctswidth = maxdescacctswidth - maxdescwidth -- descwidth = min maxdescwidth descwidth' -- acctswidth = min maxacctswidth acctswidth' -- allocating equally. descwidth = maxdescacctswidth `div` 2 acctswidth = maxdescacctswidth - descwidth colwidths = (datewidth,descwidth,acctswidth,changewidth,balwidth) render $ defaultLayout toplabel bottomlabel $ renderList (rsDrawItem colwidths) True rsList where ishistorical = balancetype_ ropts == HistoricalBalance inclusive = not (flat_ ropts) || rsForceInclusive toplabel = withAttr ("border" <> "bold") (str $ T.unpack $ replaceHiddenAccountsNameWith "All" rsAccount) -- <+> withAttr (borderAttr <> "query") (str $ if inclusive then "" else " exclusive") <+> togglefilters <+> str " transactions" -- <+> str (if ishistorical then " historical total" else " period total") <+> borderQueryStr (query_ ropts) -- <+> str " and subs" <+> borderPeriodStr "in" (period_ ropts) <+> str " (" <+> cur <+> str "/" <+> total <+> str ")" <+> (if ignore_assertions_ $ inputopts_ copts then withAttr (borderAttr <> "query") (str " ignoring balance assertions") else str "") where togglefilters = case concat [ uiShowStatus copts $ statuses_ ropts ,if real_ ropts then ["real"] else [] ,if empty_ ropts then [] else ["nonzero"] ] of [] -> str "" fs -> withAttr (borderAttr <> "query") (str $ " " ++ intercalate ", " fs) cur = str $ case rsList ^. listSelectedL of Nothing -> "-" Just i -> show (i + 1) total = str $ show $ length nonblanks nonblanks = V.takeWhile (not . null . rsItemDate) $ rsList^.listElementsL -- query = query_ $ reportopts_ $ cliopts_ opts bottomlabel = case mode of Minibuffer ed -> minibuffer ed _ -> quickhelp where selectedstr = withAttr (borderAttr <> "query") . str quickhelp = borderKeysStr' [ ("?", str "help") ,("left", str "back") ,("right", str "transaction") ,("H" ,if ishistorical then selectedstr "historical" <+> str "/period" else str "historical/" <+> selectedstr "period") ,("F" ,if inclusive then selectedstr "inclusive" <+> str "/exclusive" else str "inclusive/" <+> selectedstr "exclusive") -- ,("a", "add") -- ,("g", "reload") -- ,("q", "quit") ] rsDraw _ = error "draw function called with wrong screen type, should not happen" rsDrawItem :: (Int,Int,Int,Int,Int) -> Bool -> RegisterScreenItem -> Widget Name rsDrawItem (datewidth,descwidth,acctswidth,changewidth,balwidth) selected RegisterScreenItem{..} = Widget Greedy Fixed $ do render $ str (fitString (Just datewidth) (Just datewidth) True True rsItemDate) <+> str " " <+> str (fitString (Just 1) (Just 1) True True (show rsItemStatus)) <+> str " " <+> str (fitString (Just descwidth) (Just descwidth) True True rsItemDescription) <+> str " " <+> str (fitString (Just acctswidth) (Just acctswidth) True True rsItemOtherAccounts) <+> str " " <+> withAttr changeattr (str (fitString (Just changewidth) (Just changewidth) True False rsItemChangeAmount)) <+> str " " <+> withAttr balattr (str (fitString (Just balwidth) (Just balwidth) True False rsItemBalanceAmount)) where changeattr | '-' `elem` rsItemChangeAmount = sel $ "list" <> "amount" <> "decrease" | otherwise = sel $ "list" <> "amount" <> "increase" balattr | '-' `elem` rsItemBalanceAmount = sel $ "list" <> "balance" <> "negative" | otherwise = sel $ "list" <> "balance" <> "positive" sel | selected = (<> "selected") | otherwise = id rsHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) rsHandle ui@UIState{ aScreen=s@RegisterScreen{..} ,aopts=UIOpts{cliopts_=copts} ,ajournal=j ,aMode=mode } ev = do d <- liftIO getCurrentDay let journalspan = journalDateSpan False j nonblanks = V.takeWhile (not . null . rsItemDate) $ rsList^.listElementsL lastnonblankidx = max 0 (length nonblanks - 1) case mode of Minibuffer ed -> case ev of VtyEvent (EvKey KEsc []) -> continue $ closeMinibuffer ui VtyEvent (EvKey KEnter []) -> continue $ regenerateScreens j d $ setFilter s $ closeMinibuffer ui where s = chomp $ unlines $ map strip $ getEditContents ed VtyEvent ev -> do ed' <- handleEditorEvent ev ed continue $ ui{aMode=Minibuffer ed'} AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui Help -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui _ -> helpHandle ui ev Normal -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui VtyEvent (EvKey KEsc []) -> continue $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c `elem` ['?'] -> continue $ setMode Help ui AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui where p = reportPeriod ui e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> liftIO (uiReloadJournal copts d ui) >>= continue VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (toggleIgnoreBalanceAssertions ui) VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add copts j >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar 'A') []) -> suspendAndResume $ void (runIadd (journalFilePath j)) >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar 't') []) -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor pos f) >> uiReloadJournalIfChanged copts d j ui where (pos,f) = case listSelectedElement rsList of Nothing -> (endPos, journalFilePath j) Just (_, RegisterScreenItem{ rsItemTransaction=Transaction{tsourcepos=GenericSourcePos f l c}}) -> (Just (l, Just c),f) Just (_, RegisterScreenItem{ rsItemTransaction=Transaction{tsourcepos=JournalSourcePos f (l,_)}}) -> (Just (l, Nothing),f) -- display mode/query toggles VtyEvent (EvKey (KChar 'H') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleHistorical ui VtyEvent (EvKey (KChar 'F') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleFlat ui VtyEvent (EvKey (KChar 'Z') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleEmpty ui VtyEvent (EvKey (KChar 'R') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleReal ui VtyEvent (EvKey (KChar 'U') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleUnmarked ui VtyEvent (EvKey (KChar 'P') []) -> rsCenterAndContinue $ regenerateScreens j d $ togglePending ui VtyEvent (EvKey (KChar 'C') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleCleared ui VtyEvent (EvKey (KChar '/') []) -> continue $ regenerateScreens j d $ showMinibuffer ui VtyEvent (EvKey (KDown) [MShift]) -> continue $ regenerateScreens j d $ shrinkReportPeriod d ui VtyEvent (EvKey (KUp) [MShift]) -> continue $ regenerateScreens j d $ growReportPeriod d ui VtyEvent (EvKey (KRight) [MShift]) -> continue $ regenerateScreens j d $ nextReportPeriod journalspan ui VtyEvent (EvKey (KLeft) [MShift]) -> continue $ regenerateScreens j d $ previousReportPeriod journalspan ui VtyEvent (EvKey k []) | k `elem` [KBS, KDel] -> (continue $ regenerateScreens j d $ resetFilter ui) VtyEvent e | e `elem` moveLeftEvents -> continue $ popScreen ui VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle rsList >> invalidateCache >> continue ui -- enter transaction screen for selected transaction VtyEvent e | e `elem` moveRightEvents -> do case listSelectedElement rsList of Just (_, RegisterScreenItem{rsItemTransaction=t}) -> let ts = map rsItemTransaction $ V.toList $ nonblanks numberedts = zip [1..] ts i = fromIntegral $ maybe 0 (+1) $ elemIndex t ts -- XXX in continue $ screenEnter d transactionScreen{tsTransaction=(i,t) ,tsTransactions=numberedts ,tsAccount=rsAccount} ui Nothing -> continue ui -- prevent moving down over blank padding items; -- instead scroll down by one, until maximally scrolled - shows the end has been reached VtyEvent e | e `elem` moveDownEvents, isBlankElement mnextelement -> do vScrollBy (viewportScroll $ rsList^.listNameL) 1 continue ui where mnextelement = listSelectedElement $ listMoveDown rsList -- if page down or end leads to a blank padding item, stop at last non-blank VtyEvent e@(EvKey k []) | k `elem` [KPageDown, KEnd] -> do list <- handleListEvent e rsList if isBlankElement $ listSelectedElement list then do let list' = listMoveTo lastnonblankidx list scrollSelectionToMiddle list' continue ui{aScreen=s{rsList=list'}} else continue ui{aScreen=s{rsList=list}} -- fall through to the list's event handler (handles other [pg]up/down events) VtyEvent ev -> do let ev' = normaliseMovementKeys ev newitems <- handleListEvent ev' rsList continue ui{aScreen=s{rsList=newitems}} AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui rsHandle _ _ = error "event handler called with wrong screen type, should not happen" isBlankElement mel = ((rsItemDate . snd) <$> mel) == Just "" rsCenterAndContinue ui = do scrollSelectionToMiddle $ rsList $ aScreen ui continue ui
ony/hledger
hledger-ui/Hledger/UI/RegisterScreen.hs
gpl-3.0
19,053
42
46
5,793
4,331
2,337
1,994
283
44
{-# LANGUAGE ForeignFunctionInterface #-} {----------------------------------------------------------------- (c) 2008-2009 Markus Dittrich, Pittsburgh Supercomputing Center & Carnegie Mellon University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. 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 Version 3 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. --------------------------------------------------------------------} -- | definition of additional math and helper functions module ExtraFunctions ( convert_rate , erf , erfc , fact , is_equal , is_equal_with , maybe_to_int , maybe_to_positive_int , real_exp , to_int ) where -- imports import Foreign() import Foreign.C.Types import Prelude -- local imports import GenericModel (MathExpr(..)) import RpnData (RpnStack(..), RpnItem(..)) --import Debug.Trace -- | a few constants avogadroNum :: Double avogadroNum = 6.0221415e23 -- | use glibc DBL_EPSILON dbl_epsilon :: Double dbl_epsilon = 2.2204460492503131e-16 -- | comparison function for doubles via dbl_epsion is_equal :: Double -> Double -> Bool is_equal x y = abs(x-y) <= abs(x) * dbl_epsilon -- | comparison function for doubles via threshold is_equal_with :: Double -> Double -> Double -> Bool is_equal_with x y th = abs(x-y) <= abs(x) * th -- | function checking if a Double can be interpreted as a non -- negative Integer. We need this since all parsing of numbers -- is done with Doubles but some functions only work for -- non-negative integers such as factorial. -- To check if we are dealing with Double, we convert to an -- Integer via floor and the compare if the numbers are identical. -- If yes, the number seems to be an Integer and we return it, -- otherwise Nothing maybe_to_positive_int :: Double -> Maybe Integer maybe_to_positive_int x = case (is_equal (fromInteger . floor $ x) x) && (x > 0.0) of True -> Just $ floor x False -> Nothing -- | function checking if a Double can be interpreted as an -- Integer. See is_positive_int for more detail maybe_to_int :: Double -> Maybe Integer maybe_to_int x = case is_equal (fromInteger . floor $ x) x of True -> Just $ floor x False -> Nothing -- | helper function for defining real powers -- NOTE: We use glibc's pow function since it is more -- precise than implementing it ourselves via, e.g., -- pow a x = exp $ x * log a foreign import ccall "math.h pow" c_pow :: CDouble -> CDouble -> CDouble real_exp :: Double -> Double -> Double real_exp a x = realToFrac $ c_pow (realToFrac a) (realToFrac x) -- | factorial function fact :: Integer -> Integer fact 0 = 1 fact n = n * fact (n-1) -- | error function erf(x) -- we use a recursive solution of the Taylor series expansion erf :: Double -> Double erf x | x == 0.0 = 0.0 -- our recursive alg. loops forever -- in this case | abs(x) > 2.2 = 1.0 - erfc x -- use erfc for numerical accuracy | otherwise = 2.0 / sqrt(pi) * (erf_h x x 1.0) where erf_h old x_old n = let x_new = x_old * (x_next n) tot = old + x_new in if abs(x_new/tot) < dbl_epsilon then tot else erf_h tot x_new (n+1.0) -- Note: We need (2::Int) here to silence ghc x_next n = -(x^(2::Int)) * (2.0*n-1.0)/(n * (2.0*n+1.0)) -- | complementary error function erfc(x) = 1 - erf(x) -- we use a recursive solution of the continued fraction -- expression of erfc(x) for it superior convergence -- property. Here, we calculate the ith and (i+1)th convergent, (see -- http://archives.math.utk.edu/articles/atuyl/confrac/intro.html) -- and terminate when the relative difference is smaller than a -- certain threshold. erfc :: Double -> Double erfc x | abs(x) < 2.2 = 1.0 - erf(x) -- use erf(x) in [-2.2,2.2] | signum(x) < 0 = 2.0 - erfc(-x) -- continued fraction expansion -- only valid for x > 0 | otherwise = 1/sqrt(pi) * exp(-x^(2::Int)) * (erfc_h nc1 nc2 dc1 dc2 1.0) where nc1 = 1.0 :: Double -- numerator of 1st convergent nc2 = x :: Double -- numerator of 2nd convergent dc1 = x :: Double -- denominator of 1st convergent dc2 = x^(2::Int)+0.5 :: Double -- denominator of 2nd convergent erfc_h n1 n2 d1 d2 i = let num_new = n1*i + n2*x denom_new = d1*i + d2*x d_old = n2/d2 d_new = num_new/denom_new in if abs((d_old - d_new)/d_new) < dbl_epsilon then d_new else erfc_h n2 num_new d2 denom_new (i+0.5) -- | convert reaction propensities into rates if requested -- by the user. For constants we simply multiply, for -- rate functions we push the neccessary conversion onto -- the stack convert_rate :: MathExpr -> Int -> Double -> MathExpr convert_rate theConst@(Constant c) order volume = case order of 1 -> theConst _ -> Constant $ c/(avogadroNum * volume)^(order-1) convert_rate theFunc@(Function stack) order volume = case order of 1 -> theFunc _ -> let mult = 1.0/(avogadroNum * volume)^(order-1) in Function . RpnStack $ (toList stack) ++ [Number mult,BinFunc (*)] -- | convert a double to int -- NOTE: presently, converting double -> int is done -- via floor. Is this a good policy (once documented -- properly)? to_int :: (RealFrac a, Integral b) => a -> b to_int = floor
haskelladdict/simgi
src/ExtraFunctions.hs
gpl-3.0
6,288
0
15
1,777
1,229
674
555
83
3
module Hob.Command.FocusCommandEntry ( toggleFocusOnCommandEntryCommandHandler, focusActiveEditorAndExitLastModeCommandHandler, focusCommandEntryCommandHandler, ) where import Control.Monad.Reader import Graphics.UI.Gtk import Hob.Context import Hob.Context.UiContext import Hob.Control import Hob.Ui.Editor focusCommandEntryCommandHandler :: CommandHandler focusCommandEntryCommandHandler = CommandHandler Nothing focusCommandEntry focusActiveEditorAndExitLastModeCommandHandler :: CommandHandler focusActiveEditorAndExitLastModeCommandHandler = CommandHandler Nothing focusActiveEditorAndExitLastMode toggleFocusOnCommandEntryCommandHandler :: CommandHandler toggleFocusOnCommandEntryCommandHandler = CommandHandler Nothing toggleFocusOnCommandEntry focusCommandEntry :: App() focusCommandEntry = do ctx <- ask liftIO $ widgetGrabFocus $ cmdEntry ctx where cmdEntry ctx = commandEntry.uiContext $ ctx focusActiveEditorAndExitLastMode :: App() focusActiveEditorAndExitLastMode = do exitLastMode ctx <- ask editor <- liftIO $ getActiveEditor ctx liftIO $ maybeDo widgetGrabFocus editor toggleFocusOnCommandEntry :: App() toggleFocusOnCommandEntry = do ctx <- ask isFocused <- liftIO $ widgetGetIsFocus $ cmdEntry ctx if isFocused then do editor <- liftIO $ getActiveEditor ctx liftIO $ maybeDo widgetGrabFocus editor else liftIO $ widgetGrabFocus $ cmdEntry ctx where cmdEntry ctx = commandEntry.uiContext $ ctx
svalaskevicius/hob
src/lib/Hob/Command/FocusCommandEntry.hs
gpl-3.0
1,509
0
12
230
305
156
149
36
2
{-# LANGUAGE FlexibleContexts #-} module Circuits ( -- wires Wire, newWire, query, set, -- gates newAnd, newOr, newNot, newNand, newNor, newXor ) where import Data.IORef (IORef, newIORef, readIORef, modifyIORef) import Control.Monad (forM_) {- Wire -} -- consists of an IORef holding its current value and a list of gates -- which require updating when the value of this wire is updated data Wire = Wire { value :: IORef Bool , connections :: IORef [Gate] } instance Show Wire where show _ = "wire" newWire :: IO Wire newWire = do v <- newIORef False cs <- newIORef [] return $ Wire v cs -- add the given gate to the list of gates that should be updated when -- the value of the wire is changed connect :: Wire -> Gate -> IO () connect (Wire _ cs) g = do modifyIORef cs (g:) update g -- return the current value of the wire query :: Wire -> IO Bool query (Wire v _) = readIORef v -- assign the value to the wire and tell all connected gates to update set :: Wire -> Bool -> IO () set (Wire v cs) b = do modifyIORef v (\_ -> b) gates <- readIORef cs forM_ gates update {- Gate -} -- this data structure is not exported. smart constructors return -- output wire data Gate = And {in0 :: Wire, in1 :: Wire, out :: Wire} | Or {in0 :: Wire, in1 :: Wire, out :: Wire} | Not {in0 :: Wire, out :: Wire} | Nand {in0 :: Wire, in1 :: Wire, out :: Wire} | Nor {in0 :: Wire, in1 :: Wire, out :: Wire} | Xor {in0 :: Wire, in1 :: Wire, out :: Wire} deriving Show newGate :: (Wire -> Wire -> Wire -> Gate) -> Wire -> Wire -> IO Wire newGate constructor in0 in1 = do out <- newWire let g = constructor in0 in1 out connect in0 g connect in1 g return out newAnd :: Wire -> Wire -> IO Wire newAnd = newGate And newOr :: Wire -> Wire -> IO Wire newOr = newGate Or newNot :: Wire -> IO Wire newNot in0 = do out <- newWire let g = Not in0 out connect in0 g return out newNand :: Wire -> Wire -> IO Wire newNand = newGate Nand newNor :: Wire -> Wire -> IO Wire newNor = newGate Nor newXor :: Wire -> Wire -> IO Wire newXor = newGate Xor -- defines the behavior of each gate update :: Gate -> IO () update (And in0 in1 out) = do v0 <- query in0 v1 <- query in1 set out (v0 && v1) update (Or in0 in1 out) = do v0 <- query in0 v1 <- query in1 set out (v0 || v1) update (Not in0 out) = do v <- query in0 set out (not v) update (Nand in0 in1 out) = do v0 <- query in0 v1 <- query in1 set out (not (v0 && v1)) update (Nor in0 in1 out) = do v0 <- query in0 v1 <- query in1 set out (not (v0 || v1)) update (Xor in0 in1 out) = do v0 <- query in0 v1 <- query in1 set out ((v0 && (not v1)) || ((not v0) && v1))
jgraydus/circuits
src/Circuits.hs
gpl-3.0
2,720
0
13
696
1,090
557
533
82
1
module Emyrald.Eval (evalExpr{-, evalProg-}) where import Emyrald.Error (Error (..)) import Emyrald.Expr (Expr (..), Env) -- | The function 'evalExpr' evaluates an 'Expr' -- within the global context of the provided -- 'Env'. evalExpr :: Env -> Expr -> Either Error Expr -- self evaluating expressions evalExpr _ (Num i) = Right $ Num i evalExpr _ (SBase s) = Right $ SBase s evalExpr _ (Func v ex) = Right $ Func v ex evalExpr _ (Builtin f) = Right $ Builtin f -- symbols evalExpr e (Sym (SBase s)) = maybe (Left $ Error "reference" $ "'" ++ s ++ "' is not in scope") Right $ lookup (Sym $ SBase s) e evalExpr _ (Sym ex) = Right ex -- function application evalExpr _ (App (Builtin f) a) = f a evalExpr e (App (Func v ex) a) = evalExpr (e ++ [(v, a)]) ex evalExpr e (App (Sym (SBase s)) a) = evalExpr e $ App (Sym $ SBase s) a evalExpr e (App (Sym ex) a) = (\x->evalExpr e $ App x a) =<< evalExpr e (Sym ex) evalExpr e (App (App f' a') a) = (\ex->evalExpr e $ App ex a) =<< evalExpr e (App f' a') evalExpr _ (App (Num _) _) = Left $ Error "type" "'int' objects are not callable" -- otherwise evalExpr _ _ = Left $ Error "unknown" "invalid expression"
Kwarrtz/Emyrald
src/Emyrald/Eval.hs
gpl-3.0
1,198
0
12
277
551
280
271
17
1
module MirakelBot.Message.Send (send,sendText,send',answer) where import Control.Lens import Control.Monad.Reader import qualified Data.ByteString.Char8 as BC import qualified Data.Text as T import qualified Data.Text.Encoding as T import MirakelBot.Handlers import MirakelBot.Types import System.IO send :: Message -> Handler () send message = do env <- getBotEnv let h = view socket env liftIO $ send' h message answer :: T.Text -> Handler () answer txt=do msg <- getMessage let dest = getDest msg sendText txt [dest] sendText :: T.Text -> [To] -> Handler () sendText txt dest = do let msg = PrivateMessage Nothing dest txt env <- getBotEnv let h = view socket env liftIO $ send' h msg getDest :: Message -> To getDest (PrivateMessage {_privateSender = Just sndr, _privateDestination = (dest:_)}) = case dest of ToChannel _ -> dest _ -> ToNick sndr --_ -> error "Wrong destination" getDest _ = error "Wrong destination" send' :: Handle -> Message -> IO () send' h message@(PrivateMessage {_privateMessage = txt}) = mapM_ (\l -> sendOneLiner h message {_privateMessage = l}) $ T.lines txt send' h message = sendOneLiner h message sendOneLiner :: Handle -> Message -> IO () sendOneLiner h message = do let msgT= showt message liftIO $ BC.hPutStrLn h $ T.encodeUtf8 msgT liftIO $ putStrLn $ '>' : T.unpack msgT
azapps/mirakelbot
src/MirakelBot/Message/Send.hs
gpl-3.0
1,468
0
11
367
515
263
252
40
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.PubSub.Projects.Schemas.TestIAMPermissions -- 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) -- -- Returns permissions that a caller has on the specified resource. If the -- resource does not exist, this will return an empty set of permissions, -- not a \`NOT_FOUND\` error. Note: This operation is designed to be used -- for building permission-aware UIs and command-line tools, not for -- authorization checking. This operation may \"fail open\" without -- warning. -- -- /See:/ <https://cloud.google.com/pubsub/docs Cloud Pub/Sub API Reference> for @pubsub.projects.schemas.testIamPermissions@. module Network.Google.Resource.PubSub.Projects.Schemas.TestIAMPermissions ( -- * REST Resource ProjectsSchemasTestIAMPermissionsResource -- * Creating a Request , projectsSchemasTestIAMPermissions , ProjectsSchemasTestIAMPermissions -- * Request Lenses , pstipsXgafv , pstipsUploadProtocol , pstipsAccessToken , pstipsUploadType , pstipsPayload , pstipsResource , pstipsCallback ) where import Network.Google.Prelude import Network.Google.PubSub.Types -- | A resource alias for @pubsub.projects.schemas.testIamPermissions@ method which the -- 'ProjectsSchemasTestIAMPermissions' request conforms to. type ProjectsSchemasTestIAMPermissionsResource = "v1" :> CaptureMode "resource" "testIamPermissions" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TestIAMPermissionsRequest :> Post '[JSON] TestIAMPermissionsResponse -- | Returns permissions that a caller has on the specified resource. If the -- resource does not exist, this will return an empty set of permissions, -- not a \`NOT_FOUND\` error. Note: This operation is designed to be used -- for building permission-aware UIs and command-line tools, not for -- authorization checking. This operation may \"fail open\" without -- warning. -- -- /See:/ 'projectsSchemasTestIAMPermissions' smart constructor. data ProjectsSchemasTestIAMPermissions = ProjectsSchemasTestIAMPermissions' { _pstipsXgafv :: !(Maybe Xgafv) , _pstipsUploadProtocol :: !(Maybe Text) , _pstipsAccessToken :: !(Maybe Text) , _pstipsUploadType :: !(Maybe Text) , _pstipsPayload :: !TestIAMPermissionsRequest , _pstipsResource :: !Text , _pstipsCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsSchemasTestIAMPermissions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pstipsXgafv' -- -- * 'pstipsUploadProtocol' -- -- * 'pstipsAccessToken' -- -- * 'pstipsUploadType' -- -- * 'pstipsPayload' -- -- * 'pstipsResource' -- -- * 'pstipsCallback' projectsSchemasTestIAMPermissions :: TestIAMPermissionsRequest -- ^ 'pstipsPayload' -> Text -- ^ 'pstipsResource' -> ProjectsSchemasTestIAMPermissions projectsSchemasTestIAMPermissions pPstipsPayload_ pPstipsResource_ = ProjectsSchemasTestIAMPermissions' { _pstipsXgafv = Nothing , _pstipsUploadProtocol = Nothing , _pstipsAccessToken = Nothing , _pstipsUploadType = Nothing , _pstipsPayload = pPstipsPayload_ , _pstipsResource = pPstipsResource_ , _pstipsCallback = Nothing } -- | V1 error format. pstipsXgafv :: Lens' ProjectsSchemasTestIAMPermissions (Maybe Xgafv) pstipsXgafv = lens _pstipsXgafv (\ s a -> s{_pstipsXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pstipsUploadProtocol :: Lens' ProjectsSchemasTestIAMPermissions (Maybe Text) pstipsUploadProtocol = lens _pstipsUploadProtocol (\ s a -> s{_pstipsUploadProtocol = a}) -- | OAuth access token. pstipsAccessToken :: Lens' ProjectsSchemasTestIAMPermissions (Maybe Text) pstipsAccessToken = lens _pstipsAccessToken (\ s a -> s{_pstipsAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pstipsUploadType :: Lens' ProjectsSchemasTestIAMPermissions (Maybe Text) pstipsUploadType = lens _pstipsUploadType (\ s a -> s{_pstipsUploadType = a}) -- | Multipart request metadata. pstipsPayload :: Lens' ProjectsSchemasTestIAMPermissions TestIAMPermissionsRequest pstipsPayload = lens _pstipsPayload (\ s a -> s{_pstipsPayload = a}) -- | REQUIRED: The resource for which the policy detail is being requested. -- See the operation documentation for the appropriate value for this -- field. pstipsResource :: Lens' ProjectsSchemasTestIAMPermissions Text pstipsResource = lens _pstipsResource (\ s a -> s{_pstipsResource = a}) -- | JSONP pstipsCallback :: Lens' ProjectsSchemasTestIAMPermissions (Maybe Text) pstipsCallback = lens _pstipsCallback (\ s a -> s{_pstipsCallback = a}) instance GoogleRequest ProjectsSchemasTestIAMPermissions where type Rs ProjectsSchemasTestIAMPermissions = TestIAMPermissionsResponse type Scopes ProjectsSchemasTestIAMPermissions = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/pubsub"] requestClient ProjectsSchemasTestIAMPermissions'{..} = go _pstipsResource _pstipsXgafv _pstipsUploadProtocol _pstipsAccessToken _pstipsUploadType _pstipsCallback (Just AltJSON) _pstipsPayload pubSubService where go = buildClient (Proxy :: Proxy ProjectsSchemasTestIAMPermissionsResource) mempty
brendanhay/gogol
gogol-pubsub/gen/Network/Google/Resource/PubSub/Projects/Schemas/TestIAMPermissions.hs
mpl-2.0
6,568
0
16
1,382
792
467
325
122
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Games.Types.Product -- 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) -- module Network.Google.Games.Types.Product where import Network.Google.Games.Types.Sum import Network.Google.Prelude -- | A representation of the individual components of the name. -- -- /See:/ 'playerName' smart constructor. data PlayerName = PlayerName' { _pnGivenName :: !(Maybe Text) , _pnFamilyName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerName' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pnGivenName' -- -- * 'pnFamilyName' playerName :: PlayerName playerName = PlayerName' {_pnGivenName = Nothing, _pnFamilyName = Nothing} -- | The given name of this player. In some places, this is known as the -- first name. pnGivenName :: Lens' PlayerName (Maybe Text) pnGivenName = lens _pnGivenName (\ s a -> s{_pnGivenName = a}) -- | The family name of this player. In some places, this is known as the -- last name. pnFamilyName :: Lens' PlayerName (Maybe Text) pnFamilyName = lens _pnFamilyName (\ s a -> s{_pnFamilyName = a}) instance FromJSON PlayerName where parseJSON = withObject "PlayerName" (\ o -> PlayerName' <$> (o .:? "givenName") <*> (o .:? "familyName")) instance ToJSON PlayerName where toJSON PlayerName'{..} = object (catMaybes [("givenName" .=) <$> _pnGivenName, ("familyName" .=) <$> _pnFamilyName]) -- | An snapshot object. -- -- /See:/ 'snapshot' smart constructor. data Snapshot = Snapshot' { _sLastModifiedMillis :: !(Maybe (Textual Int64)) , _sKind :: !(Maybe Text) , _sProgressValue :: !(Maybe (Textual Int64)) , _sUniqueName :: !(Maybe Text) , _sCoverImage :: !(Maybe SnapshotImage) , _sId :: !(Maybe Text) , _sDurationMillis :: !(Maybe (Textual Int64)) , _sTitle :: !(Maybe Text) , _sType :: !(Maybe SnapshotType) , _sDescription :: !(Maybe Text) , _sDriveId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Snapshot' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sLastModifiedMillis' -- -- * 'sKind' -- -- * 'sProgressValue' -- -- * 'sUniqueName' -- -- * 'sCoverImage' -- -- * 'sId' -- -- * 'sDurationMillis' -- -- * 'sTitle' -- -- * 'sType' -- -- * 'sDescription' -- -- * 'sDriveId' snapshot :: Snapshot snapshot = Snapshot' { _sLastModifiedMillis = Nothing , _sKind = Nothing , _sProgressValue = Nothing , _sUniqueName = Nothing , _sCoverImage = Nothing , _sId = Nothing , _sDurationMillis = Nothing , _sTitle = Nothing , _sType = Nothing , _sDescription = Nothing , _sDriveId = Nothing } -- | The timestamp (in millis since Unix epoch) of the last modification to -- this snapshot. sLastModifiedMillis :: Lens' Snapshot (Maybe Int64) sLastModifiedMillis = lens _sLastModifiedMillis (\ s a -> s{_sLastModifiedMillis = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#snapshot\`. sKind :: Lens' Snapshot (Maybe Text) sKind = lens _sKind (\ s a -> s{_sKind = a}) -- | The progress value (64-bit integer set by developer) associated with -- this snapshot. sProgressValue :: Lens' Snapshot (Maybe Int64) sProgressValue = lens _sProgressValue (\ s a -> s{_sProgressValue = a}) . mapping _Coerce -- | The unique name provided when the snapshot was created. sUniqueName :: Lens' Snapshot (Maybe Text) sUniqueName = lens _sUniqueName (\ s a -> s{_sUniqueName = a}) -- | The cover image of this snapshot. May be absent if there is no image. sCoverImage :: Lens' Snapshot (Maybe SnapshotImage) sCoverImage = lens _sCoverImage (\ s a -> s{_sCoverImage = a}) -- | The ID of the snapshot. sId :: Lens' Snapshot (Maybe Text) sId = lens _sId (\ s a -> s{_sId = a}) -- | The duration associated with this snapshot, in millis. sDurationMillis :: Lens' Snapshot (Maybe Int64) sDurationMillis = lens _sDurationMillis (\ s a -> s{_sDurationMillis = a}) . mapping _Coerce -- | The title of this snapshot. sTitle :: Lens' Snapshot (Maybe Text) sTitle = lens _sTitle (\ s a -> s{_sTitle = a}) -- | The type of this snapshot. sType :: Lens' Snapshot (Maybe SnapshotType) sType = lens _sType (\ s a -> s{_sType = a}) -- | The description of this snapshot. sDescription :: Lens' Snapshot (Maybe Text) sDescription = lens _sDescription (\ s a -> s{_sDescription = a}) -- | The ID of the file underlying this snapshot in the Drive API. Only -- present if the snapshot is a view on a Drive file and the file is owned -- by the caller. sDriveId :: Lens' Snapshot (Maybe Text) sDriveId = lens _sDriveId (\ s a -> s{_sDriveId = a}) instance FromJSON Snapshot where parseJSON = withObject "Snapshot" (\ o -> Snapshot' <$> (o .:? "lastModifiedMillis") <*> (o .:? "kind") <*> (o .:? "progressValue") <*> (o .:? "uniqueName") <*> (o .:? "coverImage") <*> (o .:? "id") <*> (o .:? "durationMillis") <*> (o .:? "title") <*> (o .:? "type") <*> (o .:? "description") <*> (o .:? "driveId")) instance ToJSON Snapshot where toJSON Snapshot'{..} = object (catMaybes [("lastModifiedMillis" .=) <$> _sLastModifiedMillis, ("kind" .=) <$> _sKind, ("progressValue" .=) <$> _sProgressValue, ("uniqueName" .=) <$> _sUniqueName, ("coverImage" .=) <$> _sCoverImage, ("id" .=) <$> _sId, ("durationMillis" .=) <$> _sDurationMillis, ("title" .=) <$> _sTitle, ("type" .=) <$> _sType, ("description" .=) <$> _sDescription, ("driveId" .=) <$> _sDriveId]) -- | An event status resource. -- -- /See:/ 'playerEvent' smart constructor. data PlayerEvent = PlayerEvent' { _peKind :: !(Maybe Text) , _peNumEvents :: !(Maybe (Textual Int64)) , _peFormattedNumEvents :: !(Maybe Text) , _peDefinitionId :: !(Maybe Text) , _pePlayerId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerEvent' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'peKind' -- -- * 'peNumEvents' -- -- * 'peFormattedNumEvents' -- -- * 'peDefinitionId' -- -- * 'pePlayerId' playerEvent :: PlayerEvent playerEvent = PlayerEvent' { _peKind = Nothing , _peNumEvents = Nothing , _peFormattedNumEvents = Nothing , _peDefinitionId = Nothing , _pePlayerId = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerEvent\`. peKind :: Lens' PlayerEvent (Maybe Text) peKind = lens _peKind (\ s a -> s{_peKind = a}) -- | The current number of times this event has occurred. peNumEvents :: Lens' PlayerEvent (Maybe Int64) peNumEvents = lens _peNumEvents (\ s a -> s{_peNumEvents = a}) . mapping _Coerce -- | The current number of times this event has occurred, as a string. The -- formatting of this string depends on the configuration of your event in -- the Play Games Developer Console. peFormattedNumEvents :: Lens' PlayerEvent (Maybe Text) peFormattedNumEvents = lens _peFormattedNumEvents (\ s a -> s{_peFormattedNumEvents = a}) -- | The ID of the event definition. peDefinitionId :: Lens' PlayerEvent (Maybe Text) peDefinitionId = lens _peDefinitionId (\ s a -> s{_peDefinitionId = a}) -- | The ID of the player. pePlayerId :: Lens' PlayerEvent (Maybe Text) pePlayerId = lens _pePlayerId (\ s a -> s{_pePlayerId = a}) instance FromJSON PlayerEvent where parseJSON = withObject "PlayerEvent" (\ o -> PlayerEvent' <$> (o .:? "kind") <*> (o .:? "numEvents") <*> (o .:? "formattedNumEvents") <*> (o .:? "definitionId") <*> (o .:? "playerId")) instance ToJSON PlayerEvent where toJSON PlayerEvent'{..} = object (catMaybes [("kind" .=) <$> _peKind, ("numEvents" .=) <$> _peNumEvents, ("formattedNumEvents" .=) <$> _peFormattedNumEvents, ("definitionId" .=) <$> _peDefinitionId, ("playerId" .=) <$> _pePlayerId]) -- | A third party stats resource. -- -- /See:/ 'statsResponse' smart constructor. data StatsResponse = StatsResponse' { _srTotalSpendNext28Days :: !(Maybe (Textual Double)) , _srDaysSinceLastPlayed :: !(Maybe (Textual Int32)) , _srKind :: !(Maybe Text) , _srSpendPercentile :: !(Maybe (Textual Double)) , _srNumPurchases :: !(Maybe (Textual Int32)) , _srNumSessions :: !(Maybe (Textual Int32)) , _srHighSpenderProbability :: !(Maybe (Textual Double)) , _srAvgSessionLengthMinutes :: !(Maybe (Textual Double)) , _srNumSessionsPercentile :: !(Maybe (Textual Double)) , _srChurnProbability :: !(Maybe (Textual Double)) , _srSpendProbability :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srTotalSpendNext28Days' -- -- * 'srDaysSinceLastPlayed' -- -- * 'srKind' -- -- * 'srSpendPercentile' -- -- * 'srNumPurchases' -- -- * 'srNumSessions' -- -- * 'srHighSpenderProbability' -- -- * 'srAvgSessionLengthMinutes' -- -- * 'srNumSessionsPercentile' -- -- * 'srChurnProbability' -- -- * 'srSpendProbability' statsResponse :: StatsResponse statsResponse = StatsResponse' { _srTotalSpendNext28Days = Nothing , _srDaysSinceLastPlayed = Nothing , _srKind = Nothing , _srSpendPercentile = Nothing , _srNumPurchases = Nothing , _srNumSessions = Nothing , _srHighSpenderProbability = Nothing , _srAvgSessionLengthMinutes = Nothing , _srNumSessionsPercentile = Nothing , _srChurnProbability = Nothing , _srSpendProbability = Nothing } -- | The predicted amount of money that the player going to spend in the next -- 28 days. E.g., 1, 30, 60, ... . Not populated if there is not enough -- information. srTotalSpendNext28Days :: Lens' StatsResponse (Maybe Double) srTotalSpendNext28Days = lens _srTotalSpendNext28Days (\ s a -> s{_srTotalSpendNext28Days = a}) . mapping _Coerce -- | Number of days since the player last played this game. E.g., 0, 1, 5, -- 10, ... . Not populated if there is not enough information. srDaysSinceLastPlayed :: Lens' StatsResponse (Maybe Int32) srDaysSinceLastPlayed = lens _srDaysSinceLastPlayed (\ s a -> s{_srDaysSinceLastPlayed = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#statsResponse\`. srKind :: Lens' StatsResponse (Maybe Text) srKind = lens _srKind (\ s a -> s{_srKind = a}) -- | The approximate spend percentile of the player in this game. E.g., 0, -- 0.25, 0.5, 0.75. Not populated if there is not enough information. srSpendPercentile :: Lens' StatsResponse (Maybe Double) srSpendPercentile = lens _srSpendPercentile (\ s a -> s{_srSpendPercentile = a}) . mapping _Coerce -- | Number of in-app purchases made by the player in this game. E.g., 0, 1, -- 5, 10, ... . Not populated if there is not enough information. srNumPurchases :: Lens' StatsResponse (Maybe Int32) srNumPurchases = lens _srNumPurchases (\ s a -> s{_srNumPurchases = a}) . mapping _Coerce -- | The approximate number of sessions of the player within the last 28 -- days, where a session begins when the player is connected to Play Games -- Services and ends when they are disconnected. E.g., 0, 1, 5, 10, ... . -- Not populated if there is not enough information. srNumSessions :: Lens' StatsResponse (Maybe Int32) srNumSessions = lens _srNumSessions (\ s a -> s{_srNumSessions = a}) . mapping _Coerce -- | The probability of the player going to spend beyond a threshold amount -- of money. E.g., 0, 0.25, 0.50, 0.75. Not populated if there is not -- enough information. srHighSpenderProbability :: Lens' StatsResponse (Maybe Double) srHighSpenderProbability = lens _srHighSpenderProbability (\ s a -> s{_srHighSpenderProbability = a}) . mapping _Coerce -- | Average session length in minutes of the player. E.g., 1, 30, 60, ... . -- Not populated if there is not enough information. srAvgSessionLengthMinutes :: Lens' StatsResponse (Maybe Double) srAvgSessionLengthMinutes = lens _srAvgSessionLengthMinutes (\ s a -> s{_srAvgSessionLengthMinutes = a}) . mapping _Coerce -- | The approximation of the sessions percentile of the player within the -- last 30 days, where a session begins when the player is connected to -- Play Games Services and ends when they are disconnected. E.g., 0, 0.25, -- 0.5, 0.75. Not populated if there is not enough information. srNumSessionsPercentile :: Lens' StatsResponse (Maybe Double) srNumSessionsPercentile = lens _srNumSessionsPercentile (\ s a -> s{_srNumSessionsPercentile = a}) . mapping _Coerce -- | The probability of the player not returning to play the game in the next -- day. E.g., 0, 0.1, 0.5, ..., 1.0. Not populated if there is not enough -- information. srChurnProbability :: Lens' StatsResponse (Maybe Double) srChurnProbability = lens _srChurnProbability (\ s a -> s{_srChurnProbability = a}) . mapping _Coerce -- | The probability of the player going to spend the game in the next seven -- days. E.g., 0, 0.25, 0.50, 0.75. Not populated if there is not enough -- information. srSpendProbability :: Lens' StatsResponse (Maybe Double) srSpendProbability = lens _srSpendProbability (\ s a -> s{_srSpendProbability = a}) . mapping _Coerce instance FromJSON StatsResponse where parseJSON = withObject "StatsResponse" (\ o -> StatsResponse' <$> (o .:? "total_spend_next_28_days") <*> (o .:? "days_since_last_played") <*> (o .:? "kind") <*> (o .:? "spend_percentile") <*> (o .:? "num_purchases") <*> (o .:? "num_sessions") <*> (o .:? "high_spender_probability") <*> (o .:? "avg_session_length_minutes") <*> (o .:? "num_sessions_percentile") <*> (o .:? "churn_probability") <*> (o .:? "spend_probability")) instance ToJSON StatsResponse where toJSON StatsResponse'{..} = object (catMaybes [("total_spend_next_28_days" .=) <$> _srTotalSpendNext28Days, ("days_since_last_played" .=) <$> _srDaysSinceLastPlayed, ("kind" .=) <$> _srKind, ("spend_percentile" .=) <$> _srSpendPercentile, ("num_purchases" .=) <$> _srNumPurchases, ("num_sessions" .=) <$> _srNumSessions, ("high_spender_probability" .=) <$> _srHighSpenderProbability, ("avg_session_length_minutes" .=) <$> _srAvgSessionLengthMinutes, ("num_sessions_percentile" .=) <$> _srNumSessionsPercentile, ("churn_probability" .=) <$> _srChurnProbability, ("spend_probability" .=) <$> _srSpendProbability]) -- | A player leaderboard score object. -- -- /See:/ 'playerLeaderboardScore' smart constructor. data PlayerLeaderboardScore = PlayerLeaderboardScore' { _plsScoreTag :: !(Maybe Text) , _plsScoreString :: !(Maybe Text) , _plsKind :: !(Maybe Text) , _plsScoreValue :: !(Maybe (Textual Int64)) , _plsTimeSpan :: !(Maybe PlayerLeaderboardScoreTimeSpan) , _plsFriendsRank :: !(Maybe LeaderboardScoreRank) , _plsPublicRank :: !(Maybe LeaderboardScoreRank) , _plsSocialRank :: !(Maybe LeaderboardScoreRank) , _plsLeaderboardId :: !(Maybe Text) , _plsWriteTimestamp :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerLeaderboardScore' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plsScoreTag' -- -- * 'plsScoreString' -- -- * 'plsKind' -- -- * 'plsScoreValue' -- -- * 'plsTimeSpan' -- -- * 'plsFriendsRank' -- -- * 'plsPublicRank' -- -- * 'plsSocialRank' -- -- * 'plsLeaderboardId' -- -- * 'plsWriteTimestamp' playerLeaderboardScore :: PlayerLeaderboardScore playerLeaderboardScore = PlayerLeaderboardScore' { _plsScoreTag = Nothing , _plsScoreString = Nothing , _plsKind = Nothing , _plsScoreValue = Nothing , _plsTimeSpan = Nothing , _plsFriendsRank = Nothing , _plsPublicRank = Nothing , _plsSocialRank = Nothing , _plsLeaderboardId = Nothing , _plsWriteTimestamp = Nothing } -- | Additional information about the score. Values must contain no more than -- 64 URI-safe characters as defined by section 2.3 of RFC 3986. plsScoreTag :: Lens' PlayerLeaderboardScore (Maybe Text) plsScoreTag = lens _plsScoreTag (\ s a -> s{_plsScoreTag = a}) -- | The formatted value of this score. plsScoreString :: Lens' PlayerLeaderboardScore (Maybe Text) plsScoreString = lens _plsScoreString (\ s a -> s{_plsScoreString = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerLeaderboardScore\`. plsKind :: Lens' PlayerLeaderboardScore (Maybe Text) plsKind = lens _plsKind (\ s a -> s{_plsKind = a}) -- | The numerical value of this score. plsScoreValue :: Lens' PlayerLeaderboardScore (Maybe Int64) plsScoreValue = lens _plsScoreValue (\ s a -> s{_plsScoreValue = a}) . mapping _Coerce -- | The time span of this score. plsTimeSpan :: Lens' PlayerLeaderboardScore (Maybe PlayerLeaderboardScoreTimeSpan) plsTimeSpan = lens _plsTimeSpan (\ s a -> s{_plsTimeSpan = a}) -- | The rank of the score in the friends collection for this leaderboard. plsFriendsRank :: Lens' PlayerLeaderboardScore (Maybe LeaderboardScoreRank) plsFriendsRank = lens _plsFriendsRank (\ s a -> s{_plsFriendsRank = a}) -- | The public rank of the score in this leaderboard. This object will not -- be present if the user is not sharing their scores publicly. plsPublicRank :: Lens' PlayerLeaderboardScore (Maybe LeaderboardScoreRank) plsPublicRank = lens _plsPublicRank (\ s a -> s{_plsPublicRank = a}) -- | The social rank of the score in this leaderboard. plsSocialRank :: Lens' PlayerLeaderboardScore (Maybe LeaderboardScoreRank) plsSocialRank = lens _plsSocialRank (\ s a -> s{_plsSocialRank = a}) -- | The ID of the leaderboard this score is in. plsLeaderboardId :: Lens' PlayerLeaderboardScore (Maybe Text) plsLeaderboardId = lens _plsLeaderboardId (\ s a -> s{_plsLeaderboardId = a}) -- | The timestamp at which this score was recorded, in milliseconds since -- the epoch in UTC. plsWriteTimestamp :: Lens' PlayerLeaderboardScore (Maybe Int64) plsWriteTimestamp = lens _plsWriteTimestamp (\ s a -> s{_plsWriteTimestamp = a}) . mapping _Coerce instance FromJSON PlayerLeaderboardScore where parseJSON = withObject "PlayerLeaderboardScore" (\ o -> PlayerLeaderboardScore' <$> (o .:? "scoreTag") <*> (o .:? "scoreString") <*> (o .:? "kind") <*> (o .:? "scoreValue") <*> (o .:? "timeSpan") <*> (o .:? "friendsRank") <*> (o .:? "publicRank") <*> (o .:? "socialRank") <*> (o .:? "leaderboard_id") <*> (o .:? "writeTimestamp")) instance ToJSON PlayerLeaderboardScore where toJSON PlayerLeaderboardScore'{..} = object (catMaybes [("scoreTag" .=) <$> _plsScoreTag, ("scoreString" .=) <$> _plsScoreString, ("kind" .=) <$> _plsKind, ("scoreValue" .=) <$> _plsScoreValue, ("timeSpan" .=) <$> _plsTimeSpan, ("friendsRank" .=) <$> _plsFriendsRank, ("publicRank" .=) <$> _plsPublicRank, ("socialRank" .=) <$> _plsSocialRank, ("leaderboard_id" .=) <$> _plsLeaderboardId, ("writeTimestamp" .=) <$> _plsWriteTimestamp]) -- | The Application resource. -- -- /See:/ 'application' smart constructor. data Application = Application' { _aThemeColor :: !(Maybe Text) , _aLeaderboardCount :: !(Maybe (Textual Int32)) , _aKind :: !(Maybe Text) , _aCategory :: !(Maybe ApplicationCategory) , _aName :: !(Maybe Text) , _aEnabledFeatures :: !(Maybe [ApplicationEnabledFeaturesItem]) , _aInstances :: !(Maybe [Instance]) , _aAuthor :: !(Maybe Text) , _aId :: !(Maybe Text) , _aAchievementCount :: !(Maybe (Textual Int32)) , _aAssets :: !(Maybe [ImageAsset]) , _aDescription :: !(Maybe Text) , _aLastUpdatedTimestamp :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Application' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aThemeColor' -- -- * 'aLeaderboardCount' -- -- * 'aKind' -- -- * 'aCategory' -- -- * 'aName' -- -- * 'aEnabledFeatures' -- -- * 'aInstances' -- -- * 'aAuthor' -- -- * 'aId' -- -- * 'aAchievementCount' -- -- * 'aAssets' -- -- * 'aDescription' -- -- * 'aLastUpdatedTimestamp' application :: Application application = Application' { _aThemeColor = Nothing , _aLeaderboardCount = Nothing , _aKind = Nothing , _aCategory = Nothing , _aName = Nothing , _aEnabledFeatures = Nothing , _aInstances = Nothing , _aAuthor = Nothing , _aId = Nothing , _aAchievementCount = Nothing , _aAssets = Nothing , _aDescription = Nothing , _aLastUpdatedTimestamp = Nothing } -- | A hint to the client UI for what color to use as an app-themed color. -- The color is given as an RGB triplet (e.g. \"E0E0E0\"). aThemeColor :: Lens' Application (Maybe Text) aThemeColor = lens _aThemeColor (\ s a -> s{_aThemeColor = a}) -- | The number of leaderboards visible to the currently authenticated -- player. aLeaderboardCount :: Lens' Application (Maybe Int32) aLeaderboardCount = lens _aLeaderboardCount (\ s a -> s{_aLeaderboardCount = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#application\`. aKind :: Lens' Application (Maybe Text) aKind = lens _aKind (\ s a -> s{_aKind = a}) -- | The category of the application. aCategory :: Lens' Application (Maybe ApplicationCategory) aCategory = lens _aCategory (\ s a -> s{_aCategory = a}) -- | The name of the application. aName :: Lens' Application (Maybe Text) aName = lens _aName (\ s a -> s{_aName = a}) -- | A list of features that have been enabled for the application. aEnabledFeatures :: Lens' Application [ApplicationEnabledFeaturesItem] aEnabledFeatures = lens _aEnabledFeatures (\ s a -> s{_aEnabledFeatures = a}) . _Default . _Coerce -- | The instances of the application. aInstances :: Lens' Application [Instance] aInstances = lens _aInstances (\ s a -> s{_aInstances = a}) . _Default . _Coerce -- | The author of the application. aAuthor :: Lens' Application (Maybe Text) aAuthor = lens _aAuthor (\ s a -> s{_aAuthor = a}) -- | The ID of the application. aId :: Lens' Application (Maybe Text) aId = lens _aId (\ s a -> s{_aId = a}) -- | The number of achievements visible to the currently authenticated -- player. aAchievementCount :: Lens' Application (Maybe Int32) aAchievementCount = lens _aAchievementCount (\ s a -> s{_aAchievementCount = a}) . mapping _Coerce -- | The assets of the application. aAssets :: Lens' Application [ImageAsset] aAssets = lens _aAssets (\ s a -> s{_aAssets = a}) . _Default . _Coerce -- | The description of the application. aDescription :: Lens' Application (Maybe Text) aDescription = lens _aDescription (\ s a -> s{_aDescription = a}) -- | The last updated timestamp of the application. aLastUpdatedTimestamp :: Lens' Application (Maybe Int64) aLastUpdatedTimestamp = lens _aLastUpdatedTimestamp (\ s a -> s{_aLastUpdatedTimestamp = a}) . mapping _Coerce instance FromJSON Application where parseJSON = withObject "Application" (\ o -> Application' <$> (o .:? "themeColor") <*> (o .:? "leaderboard_count") <*> (o .:? "kind") <*> (o .:? "category") <*> (o .:? "name") <*> (o .:? "enabledFeatures" .!= mempty) <*> (o .:? "instances" .!= mempty) <*> (o .:? "author") <*> (o .:? "id") <*> (o .:? "achievement_count") <*> (o .:? "assets" .!= mempty) <*> (o .:? "description") <*> (o .:? "lastUpdatedTimestamp")) instance ToJSON Application where toJSON Application'{..} = object (catMaybes [("themeColor" .=) <$> _aThemeColor, ("leaderboard_count" .=) <$> _aLeaderboardCount, ("kind" .=) <$> _aKind, ("category" .=) <$> _aCategory, ("name" .=) <$> _aName, ("enabledFeatures" .=) <$> _aEnabledFeatures, ("instances" .=) <$> _aInstances, ("author" .=) <$> _aAuthor, ("id" .=) <$> _aId, ("achievement_count" .=) <$> _aAchievementCount, ("assets" .=) <$> _aAssets, ("description" .=) <$> _aDescription, ("lastUpdatedTimestamp" .=) <$> _aLastUpdatedTimestamp]) -- | An application category object. -- -- /See:/ 'applicationCategory' smart constructor. data ApplicationCategory = ApplicationCategory' { _acSecondary :: !(Maybe Text) , _acKind :: !(Maybe Text) , _acPrimary :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationCategory' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acSecondary' -- -- * 'acKind' -- -- * 'acPrimary' applicationCategory :: ApplicationCategory applicationCategory = ApplicationCategory' {_acSecondary = Nothing, _acKind = Nothing, _acPrimary = Nothing} -- | The secondary category. acSecondary :: Lens' ApplicationCategory (Maybe Text) acSecondary = lens _acSecondary (\ s a -> s{_acSecondary = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#applicationCategory\`. acKind :: Lens' ApplicationCategory (Maybe Text) acKind = lens _acKind (\ s a -> s{_acKind = a}) -- | The primary category. acPrimary :: Lens' ApplicationCategory (Maybe Text) acPrimary = lens _acPrimary (\ s a -> s{_acPrimary = a}) instance FromJSON ApplicationCategory where parseJSON = withObject "ApplicationCategory" (\ o -> ApplicationCategory' <$> (o .:? "secondary") <*> (o .:? "kind") <*> (o .:? "primary")) instance ToJSON ApplicationCategory where toJSON ApplicationCategory'{..} = object (catMaybes [("secondary" .=) <$> _acSecondary, ("kind" .=) <$> _acKind, ("primary" .=) <$> _acPrimary]) -- | A list of score submission statuses. -- -- /See:/ 'playerScoreListResponse' smart constructor. data PlayerScoreListResponse = PlayerScoreListResponse' { _pslrSubmittedScores :: !(Maybe [PlayerScoreResponse]) , _pslrKind :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerScoreListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pslrSubmittedScores' -- -- * 'pslrKind' playerScoreListResponse :: PlayerScoreListResponse playerScoreListResponse = PlayerScoreListResponse' {_pslrSubmittedScores = Nothing, _pslrKind = Nothing} -- | The score submissions statuses. pslrSubmittedScores :: Lens' PlayerScoreListResponse [PlayerScoreResponse] pslrSubmittedScores = lens _pslrSubmittedScores (\ s a -> s{_pslrSubmittedScores = a}) . _Default . _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerScoreListResponse\`. pslrKind :: Lens' PlayerScoreListResponse (Maybe Text) pslrKind = lens _pslrKind (\ s a -> s{_pslrKind = a}) instance FromJSON PlayerScoreListResponse where parseJSON = withObject "PlayerScoreListResponse" (\ o -> PlayerScoreListResponse' <$> (o .:? "submittedScores" .!= mempty) <*> (o .:? "kind")) instance ToJSON PlayerScoreListResponse where toJSON PlayerScoreListResponse'{..} = object (catMaybes [("submittedScores" .=) <$> _pslrSubmittedScores, ("kind" .=) <$> _pslrKind]) -- | An updated achievement. -- -- /See:/ 'achievementUpdateResponse' smart constructor. data AchievementUpdateResponse = AchievementUpdateResponse' { _aurUpdateOccurred :: !(Maybe Bool) , _aurAchievementId :: !(Maybe Text) , _aurKind :: !(Maybe Text) , _aurCurrentState :: !(Maybe AchievementUpdateResponseCurrentState) , _aurNewlyUnlocked :: !(Maybe Bool) , _aurCurrentSteps :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementUpdateResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aurUpdateOccurred' -- -- * 'aurAchievementId' -- -- * 'aurKind' -- -- * 'aurCurrentState' -- -- * 'aurNewlyUnlocked' -- -- * 'aurCurrentSteps' achievementUpdateResponse :: AchievementUpdateResponse achievementUpdateResponse = AchievementUpdateResponse' { _aurUpdateOccurred = Nothing , _aurAchievementId = Nothing , _aurKind = Nothing , _aurCurrentState = Nothing , _aurNewlyUnlocked = Nothing , _aurCurrentSteps = Nothing } -- | Whether the requested updates actually affected the achievement. aurUpdateOccurred :: Lens' AchievementUpdateResponse (Maybe Bool) aurUpdateOccurred = lens _aurUpdateOccurred (\ s a -> s{_aurUpdateOccurred = a}) -- | The achievement this update is was applied to. aurAchievementId :: Lens' AchievementUpdateResponse (Maybe Text) aurAchievementId = lens _aurAchievementId (\ s a -> s{_aurAchievementId = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementUpdateResponse\`. aurKind :: Lens' AchievementUpdateResponse (Maybe Text) aurKind = lens _aurKind (\ s a -> s{_aurKind = a}) -- | The current state of the achievement. aurCurrentState :: Lens' AchievementUpdateResponse (Maybe AchievementUpdateResponseCurrentState) aurCurrentState = lens _aurCurrentState (\ s a -> s{_aurCurrentState = a}) -- | Whether this achievement was newly unlocked (that is, whether the unlock -- request for the achievement was the first for the player). aurNewlyUnlocked :: Lens' AchievementUpdateResponse (Maybe Bool) aurNewlyUnlocked = lens _aurNewlyUnlocked (\ s a -> s{_aurNewlyUnlocked = a}) -- | The current steps recorded for this achievement if it is incremental. aurCurrentSteps :: Lens' AchievementUpdateResponse (Maybe Int32) aurCurrentSteps = lens _aurCurrentSteps (\ s a -> s{_aurCurrentSteps = a}) . mapping _Coerce instance FromJSON AchievementUpdateResponse where parseJSON = withObject "AchievementUpdateResponse" (\ o -> AchievementUpdateResponse' <$> (o .:? "updateOccurred") <*> (o .:? "achievementId") <*> (o .:? "kind") <*> (o .:? "currentState") <*> (o .:? "newlyUnlocked") <*> (o .:? "currentSteps")) instance ToJSON AchievementUpdateResponse where toJSON AchievementUpdateResponse'{..} = object (catMaybes [("updateOccurred" .=) <$> _aurUpdateOccurred, ("achievementId" .=) <$> _aurAchievementId, ("kind" .=) <$> _aurKind, ("currentState" .=) <$> _aurCurrentState, ("newlyUnlocked" .=) <$> _aurNewlyUnlocked, ("currentSteps" .=) <$> _aurCurrentSteps]) -- | The Leaderboard Entry resource. -- -- /See:/ 'leaderboardEntry' smart constructor. data LeaderboardEntry = LeaderboardEntry' { _leScoreTag :: !(Maybe Text) , _leWriteTimestampMillis :: !(Maybe (Textual Int64)) , _leKind :: !(Maybe Text) , _leScoreValue :: !(Maybe (Textual Int64)) , _leFormattedScore :: !(Maybe Text) , _leTimeSpan :: !(Maybe LeaderboardEntryTimeSpan) , _leFormattedScoreRank :: !(Maybe Text) , _lePlayer :: !(Maybe Player) , _leScoreRank :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LeaderboardEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'leScoreTag' -- -- * 'leWriteTimestampMillis' -- -- * 'leKind' -- -- * 'leScoreValue' -- -- * 'leFormattedScore' -- -- * 'leTimeSpan' -- -- * 'leFormattedScoreRank' -- -- * 'lePlayer' -- -- * 'leScoreRank' leaderboardEntry :: LeaderboardEntry leaderboardEntry = LeaderboardEntry' { _leScoreTag = Nothing , _leWriteTimestampMillis = Nothing , _leKind = Nothing , _leScoreValue = Nothing , _leFormattedScore = Nothing , _leTimeSpan = Nothing , _leFormattedScoreRank = Nothing , _lePlayer = Nothing , _leScoreRank = Nothing } -- | Additional information about the score. Values must contain no more than -- 64 URI-safe characters as defined by section 2.3 of RFC 3986. leScoreTag :: Lens' LeaderboardEntry (Maybe Text) leScoreTag = lens _leScoreTag (\ s a -> s{_leScoreTag = a}) -- | The timestamp at which this score was recorded, in milliseconds since -- the epoch in UTC. leWriteTimestampMillis :: Lens' LeaderboardEntry (Maybe Int64) leWriteTimestampMillis = lens _leWriteTimestampMillis (\ s a -> s{_leWriteTimestampMillis = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#leaderboardEntry\`. leKind :: Lens' LeaderboardEntry (Maybe Text) leKind = lens _leKind (\ s a -> s{_leKind = a}) -- | The numerical value of this score. leScoreValue :: Lens' LeaderboardEntry (Maybe Int64) leScoreValue = lens _leScoreValue (\ s a -> s{_leScoreValue = a}) . mapping _Coerce -- | The localized string for the numerical value of this score. leFormattedScore :: Lens' LeaderboardEntry (Maybe Text) leFormattedScore = lens _leFormattedScore (\ s a -> s{_leFormattedScore = a}) -- | The time span of this high score. leTimeSpan :: Lens' LeaderboardEntry (Maybe LeaderboardEntryTimeSpan) leTimeSpan = lens _leTimeSpan (\ s a -> s{_leTimeSpan = a}) -- | The localized string for the rank of this score for this leaderboard. leFormattedScoreRank :: Lens' LeaderboardEntry (Maybe Text) leFormattedScoreRank = lens _leFormattedScoreRank (\ s a -> s{_leFormattedScoreRank = a}) -- | The player who holds this score. lePlayer :: Lens' LeaderboardEntry (Maybe Player) lePlayer = lens _lePlayer (\ s a -> s{_lePlayer = a}) -- | The rank of this score for this leaderboard. leScoreRank :: Lens' LeaderboardEntry (Maybe Int64) leScoreRank = lens _leScoreRank (\ s a -> s{_leScoreRank = a}) . mapping _Coerce instance FromJSON LeaderboardEntry where parseJSON = withObject "LeaderboardEntry" (\ o -> LeaderboardEntry' <$> (o .:? "scoreTag") <*> (o .:? "writeTimestampMillis") <*> (o .:? "kind") <*> (o .:? "scoreValue") <*> (o .:? "formattedScore") <*> (o .:? "timeSpan") <*> (o .:? "formattedScoreRank") <*> (o .:? "player") <*> (o .:? "scoreRank")) instance ToJSON LeaderboardEntry where toJSON LeaderboardEntry'{..} = object (catMaybes [("scoreTag" .=) <$> _leScoreTag, ("writeTimestampMillis" .=) <$> _leWriteTimestampMillis, ("kind" .=) <$> _leKind, ("scoreValue" .=) <$> _leScoreValue, ("formattedScore" .=) <$> _leFormattedScore, ("timeSpan" .=) <$> _leTimeSpan, ("formattedScoreRank" .=) <$> _leFormattedScoreRank, ("player" .=) <$> _lePlayer, ("scoreRank" .=) <$> _leScoreRank]) -- | A third party list snapshots response. -- -- /See:/ 'snapshotListResponse' smart constructor. data SnapshotListResponse = SnapshotListResponse' { _slrNextPageToken :: !(Maybe Text) , _slrKind :: !(Maybe Text) , _slrItems :: !(Maybe [Snapshot]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SnapshotListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slrNextPageToken' -- -- * 'slrKind' -- -- * 'slrItems' snapshotListResponse :: SnapshotListResponse snapshotListResponse = SnapshotListResponse' {_slrNextPageToken = Nothing, _slrKind = Nothing, _slrItems = Nothing} -- | Token corresponding to the next page of results. If there are no more -- results, the token is omitted. slrNextPageToken :: Lens' SnapshotListResponse (Maybe Text) slrNextPageToken = lens _slrNextPageToken (\ s a -> s{_slrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#snapshotListResponse\`. slrKind :: Lens' SnapshotListResponse (Maybe Text) slrKind = lens _slrKind (\ s a -> s{_slrKind = a}) -- | The snapshots. slrItems :: Lens' SnapshotListResponse [Snapshot] slrItems = lens _slrItems (\ s a -> s{_slrItems = a}) . _Default . _Coerce instance FromJSON SnapshotListResponse where parseJSON = withObject "SnapshotListResponse" (\ o -> SnapshotListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON SnapshotListResponse where toJSON SnapshotListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _slrNextPageToken, ("kind" .=) <$> _slrKind, ("items" .=) <$> _slrItems]) -- | 1P\/3P metadata about a user\'s level. -- -- /See:/ 'playerLevel' smart constructor. data PlayerLevel = PlayerLevel' { _plMaxExperiencePoints :: !(Maybe (Textual Int64)) , _plKind :: !(Maybe Text) , _plMinExperiencePoints :: !(Maybe (Textual Int64)) , _plLevel :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerLevel' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plMaxExperiencePoints' -- -- * 'plKind' -- -- * 'plMinExperiencePoints' -- -- * 'plLevel' playerLevel :: PlayerLevel playerLevel = PlayerLevel' { _plMaxExperiencePoints = Nothing , _plKind = Nothing , _plMinExperiencePoints = Nothing , _plLevel = Nothing } -- | The maximum experience points for this level. plMaxExperiencePoints :: Lens' PlayerLevel (Maybe Int64) plMaxExperiencePoints = lens _plMaxExperiencePoints (\ s a -> s{_plMaxExperiencePoints = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerLevel\`. plKind :: Lens' PlayerLevel (Maybe Text) plKind = lens _plKind (\ s a -> s{_plKind = a}) -- | The minimum experience points for this level. plMinExperiencePoints :: Lens' PlayerLevel (Maybe Int64) plMinExperiencePoints = lens _plMinExperiencePoints (\ s a -> s{_plMinExperiencePoints = a}) . mapping _Coerce -- | The level for the user. plLevel :: Lens' PlayerLevel (Maybe Int32) plLevel = lens _plLevel (\ s a -> s{_plLevel = a}) . mapping _Coerce instance FromJSON PlayerLevel where parseJSON = withObject "PlayerLevel" (\ o -> PlayerLevel' <$> (o .:? "maxExperiencePoints") <*> (o .:? "kind") <*> (o .:? "minExperiencePoints") <*> (o .:? "level")) instance ToJSON PlayerLevel where toJSON PlayerLevel'{..} = object (catMaybes [("maxExperiencePoints" .=) <$> _plMaxExperiencePoints, ("kind" .=) <$> _plKind, ("minExperiencePoints" .=) <$> _plMinExperiencePoints, ("level" .=) <$> _plLevel]) -- | Response message for UpdateMultipleAchievements rpc. -- -- /See:/ 'achievementUpdateMultipleResponse' smart constructor. data AchievementUpdateMultipleResponse = AchievementUpdateMultipleResponse' { _aumrKind :: !(Maybe Text) , _aumrUpdatedAchievements :: !(Maybe [AchievementUpdateResponse]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementUpdateMultipleResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aumrKind' -- -- * 'aumrUpdatedAchievements' achievementUpdateMultipleResponse :: AchievementUpdateMultipleResponse achievementUpdateMultipleResponse = AchievementUpdateMultipleResponse' {_aumrKind = Nothing, _aumrUpdatedAchievements = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementUpdateMultipleResponse\`. aumrKind :: Lens' AchievementUpdateMultipleResponse (Maybe Text) aumrKind = lens _aumrKind (\ s a -> s{_aumrKind = a}) -- | The updated state of the achievements. aumrUpdatedAchievements :: Lens' AchievementUpdateMultipleResponse [AchievementUpdateResponse] aumrUpdatedAchievements = lens _aumrUpdatedAchievements (\ s a -> s{_aumrUpdatedAchievements = a}) . _Default . _Coerce instance FromJSON AchievementUpdateMultipleResponse where parseJSON = withObject "AchievementUpdateMultipleResponse" (\ o -> AchievementUpdateMultipleResponse' <$> (o .:? "kind") <*> (o .:? "updatedAchievements" .!= mempty)) instance ToJSON AchievementUpdateMultipleResponse where toJSON AchievementUpdateMultipleResponse'{..} = object (catMaybes [("kind" .=) <$> _aumrKind, ("updatedAchievements" .=) <$> _aumrUpdatedAchievements]) -- | A ListDefinitions response. -- -- /See:/ 'eventDefinitionListResponse' smart constructor. data EventDefinitionListResponse = EventDefinitionListResponse' { _edlrNextPageToken :: !(Maybe Text) , _edlrKind :: !(Maybe Text) , _edlrItems :: !(Maybe [EventDefinition]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventDefinitionListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'edlrNextPageToken' -- -- * 'edlrKind' -- -- * 'edlrItems' eventDefinitionListResponse :: EventDefinitionListResponse eventDefinitionListResponse = EventDefinitionListResponse' {_edlrNextPageToken = Nothing, _edlrKind = Nothing, _edlrItems = Nothing} -- | The pagination token for the next page of results. edlrNextPageToken :: Lens' EventDefinitionListResponse (Maybe Text) edlrNextPageToken = lens _edlrNextPageToken (\ s a -> s{_edlrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventDefinitionListResponse\`. edlrKind :: Lens' EventDefinitionListResponse (Maybe Text) edlrKind = lens _edlrKind (\ s a -> s{_edlrKind = a}) -- | The event definitions. edlrItems :: Lens' EventDefinitionListResponse [EventDefinition] edlrItems = lens _edlrItems (\ s a -> s{_edlrItems = a}) . _Default . _Coerce instance FromJSON EventDefinitionListResponse where parseJSON = withObject "EventDefinitionListResponse" (\ o -> EventDefinitionListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON EventDefinitionListResponse where toJSON EventDefinitionListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _edlrNextPageToken, ("kind" .=) <$> _edlrKind, ("items" .=) <$> _edlrItems]) -- | Data related to individual game categories. -- -- /See:/ 'category' smart constructor. data Category = Category' { _cKind :: !(Maybe Text) , _cCategory :: !(Maybe Text) , _cExperiencePoints :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Category' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cKind' -- -- * 'cCategory' -- -- * 'cExperiencePoints' category :: Category category = Category' {_cKind = Nothing, _cCategory = Nothing, _cExperiencePoints = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#category\`. cKind :: Lens' Category (Maybe Text) cKind = lens _cKind (\ s a -> s{_cKind = a}) -- | The category name. cCategory :: Lens' Category (Maybe Text) cCategory = lens _cCategory (\ s a -> s{_cCategory = a}) -- | Experience points earned in this category. cExperiencePoints :: Lens' Category (Maybe Int64) cExperiencePoints = lens _cExperiencePoints (\ s a -> s{_cExperiencePoints = a}) . mapping _Coerce instance FromJSON Category where parseJSON = withObject "Category" (\ o -> Category' <$> (o .:? "kind") <*> (o .:? "category") <*> (o .:? "experiencePoints")) instance ToJSON Category where toJSON Category'{..} = object (catMaybes [("kind" .=) <$> _cKind, ("category" .=) <$> _cCategory, ("experiencePoints" .=) <$> _cExperiencePoints]) -- | The Android instance details resource. -- -- /See:/ 'instanceAndroidDetails' smart constructor. data InstanceAndroidDetails = InstanceAndroidDetails' { _iadPackageName :: !(Maybe Text) , _iadPreferred :: !(Maybe Bool) , _iadKind :: !(Maybe Text) , _iadEnablePiracyCheck :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InstanceAndroidDetails' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iadPackageName' -- -- * 'iadPreferred' -- -- * 'iadKind' -- -- * 'iadEnablePiracyCheck' instanceAndroidDetails :: InstanceAndroidDetails instanceAndroidDetails = InstanceAndroidDetails' { _iadPackageName = Nothing , _iadPreferred = Nothing , _iadKind = Nothing , _iadEnablePiracyCheck = Nothing } -- | Android package name which maps to Google Play URL. iadPackageName :: Lens' InstanceAndroidDetails (Maybe Text) iadPackageName = lens _iadPackageName (\ s a -> s{_iadPackageName = a}) -- | Indicates that this instance is the default for new installations. iadPreferred :: Lens' InstanceAndroidDetails (Maybe Bool) iadPreferred = lens _iadPreferred (\ s a -> s{_iadPreferred = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#instanceAndroidDetails\`. iadKind :: Lens' InstanceAndroidDetails (Maybe Text) iadKind = lens _iadKind (\ s a -> s{_iadKind = a}) -- | Flag indicating whether the anti-piracy check is enabled. iadEnablePiracyCheck :: Lens' InstanceAndroidDetails (Maybe Bool) iadEnablePiracyCheck = lens _iadEnablePiracyCheck (\ s a -> s{_iadEnablePiracyCheck = a}) instance FromJSON InstanceAndroidDetails where parseJSON = withObject "InstanceAndroidDetails" (\ o -> InstanceAndroidDetails' <$> (o .:? "packageName") <*> (o .:? "preferred") <*> (o .:? "kind") <*> (o .:? "enablePiracyCheck")) instance ToJSON InstanceAndroidDetails where toJSON InstanceAndroidDetails'{..} = object (catMaybes [("packageName" .=) <$> _iadPackageName, ("preferred" .=) <$> _iadPreferred, ("kind" .=) <$> _iadKind, ("enablePiracyCheck" .=) <$> _iadEnablePiracyCheck]) -- | A list of achievement definition objects. -- -- /See:/ 'achievementDefinitionsListResponse' smart constructor. data AchievementDefinitionsListResponse = AchievementDefinitionsListResponse' { _adlrNextPageToken :: !(Maybe Text) , _adlrKind :: !(Maybe Text) , _adlrItems :: !(Maybe [AchievementDefinition]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementDefinitionsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adlrNextPageToken' -- -- * 'adlrKind' -- -- * 'adlrItems' achievementDefinitionsListResponse :: AchievementDefinitionsListResponse achievementDefinitionsListResponse = AchievementDefinitionsListResponse' {_adlrNextPageToken = Nothing, _adlrKind = Nothing, _adlrItems = Nothing} -- | Token corresponding to the next page of results. adlrNextPageToken :: Lens' AchievementDefinitionsListResponse (Maybe Text) adlrNextPageToken = lens _adlrNextPageToken (\ s a -> s{_adlrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementDefinitionsListResponse\`. adlrKind :: Lens' AchievementDefinitionsListResponse (Maybe Text) adlrKind = lens _adlrKind (\ s a -> s{_adlrKind = a}) -- | The achievement definitions. adlrItems :: Lens' AchievementDefinitionsListResponse [AchievementDefinition] adlrItems = lens _adlrItems (\ s a -> s{_adlrItems = a}) . _Default . _Coerce instance FromJSON AchievementDefinitionsListResponse where parseJSON = withObject "AchievementDefinitionsListResponse" (\ o -> AchievementDefinitionsListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON AchievementDefinitionsListResponse where toJSON AchievementDefinitionsListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _adlrNextPageToken, ("kind" .=) <$> _adlrKind, ("items" .=) <$> _adlrItems]) -- | A list of leaderboard entry resources. -- -- /See:/ 'playerScoreResponse' smart constructor. data PlayerScoreResponse = PlayerScoreResponse' { _psrScoreTag :: !(Maybe Text) , _psrKind :: !(Maybe Text) , _psrFormattedScore :: !(Maybe Text) , _psrLeaderboardId :: !(Maybe Text) , _psrBeatenScoreTimeSpans :: !(Maybe [PlayerScoreResponseBeatenScoreTimeSpansItem]) , _psrUnbeatenScores :: !(Maybe [PlayerScore]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerScoreResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psrScoreTag' -- -- * 'psrKind' -- -- * 'psrFormattedScore' -- -- * 'psrLeaderboardId' -- -- * 'psrBeatenScoreTimeSpans' -- -- * 'psrUnbeatenScores' playerScoreResponse :: PlayerScoreResponse playerScoreResponse = PlayerScoreResponse' { _psrScoreTag = Nothing , _psrKind = Nothing , _psrFormattedScore = Nothing , _psrLeaderboardId = Nothing , _psrBeatenScoreTimeSpans = Nothing , _psrUnbeatenScores = Nothing } -- | Additional information about this score. Values will contain no more -- than 64 URI-safe characters as defined by section 2.3 of RFC 3986. psrScoreTag :: Lens' PlayerScoreResponse (Maybe Text) psrScoreTag = lens _psrScoreTag (\ s a -> s{_psrScoreTag = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerScoreResponse\`. psrKind :: Lens' PlayerScoreResponse (Maybe Text) psrKind = lens _psrKind (\ s a -> s{_psrKind = a}) -- | The formatted value of the submitted score. psrFormattedScore :: Lens' PlayerScoreResponse (Maybe Text) psrFormattedScore = lens _psrFormattedScore (\ s a -> s{_psrFormattedScore = a}) -- | The leaderboard ID that this score was submitted to. psrLeaderboardId :: Lens' PlayerScoreResponse (Maybe Text) psrLeaderboardId = lens _psrLeaderboardId (\ s a -> s{_psrLeaderboardId = a}) -- | The time spans where the submitted score is better than the existing -- score for that time span. psrBeatenScoreTimeSpans :: Lens' PlayerScoreResponse [PlayerScoreResponseBeatenScoreTimeSpansItem] psrBeatenScoreTimeSpans = lens _psrBeatenScoreTimeSpans (\ s a -> s{_psrBeatenScoreTimeSpans = a}) . _Default . _Coerce -- | The scores in time spans that have not been beaten. As an example, the -- submitted score may be better than the player\'s \`DAILY\` score, but -- not better than the player\'s scores for the \`WEEKLY\` or \`ALL_TIME\` -- time spans. psrUnbeatenScores :: Lens' PlayerScoreResponse [PlayerScore] psrUnbeatenScores = lens _psrUnbeatenScores (\ s a -> s{_psrUnbeatenScores = a}) . _Default . _Coerce instance FromJSON PlayerScoreResponse where parseJSON = withObject "PlayerScoreResponse" (\ o -> PlayerScoreResponse' <$> (o .:? "scoreTag") <*> (o .:? "kind") <*> (o .:? "formattedScore") <*> (o .:? "leaderboardId") <*> (o .:? "beatenScoreTimeSpans" .!= mempty) <*> (o .:? "unbeatenScores" .!= mempty)) instance ToJSON PlayerScoreResponse where toJSON PlayerScoreResponse'{..} = object (catMaybes [("scoreTag" .=) <$> _psrScoreTag, ("kind" .=) <$> _psrKind, ("formattedScore" .=) <$> _psrFormattedScore, ("leaderboardId" .=) <$> _psrLeaderboardId, ("beatenScoreTimeSpans" .=) <$> _psrBeatenScoreTimeSpans, ("unbeatenScores" .=) <$> _psrUnbeatenScores]) -- | A list of leaderboard objects. -- -- /See:/ 'leaderboardListResponse' smart constructor. data LeaderboardListResponse = LeaderboardListResponse' { _llrNextPageToken :: !(Maybe Text) , _llrKind :: !(Maybe Text) , _llrItems :: !(Maybe [Leaderboard]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LeaderboardListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'llrNextPageToken' -- -- * 'llrKind' -- -- * 'llrItems' leaderboardListResponse :: LeaderboardListResponse leaderboardListResponse = LeaderboardListResponse' {_llrNextPageToken = Nothing, _llrKind = Nothing, _llrItems = Nothing} -- | Token corresponding to the next page of results. llrNextPageToken :: Lens' LeaderboardListResponse (Maybe Text) llrNextPageToken = lens _llrNextPageToken (\ s a -> s{_llrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#leaderboardListResponse\`. llrKind :: Lens' LeaderboardListResponse (Maybe Text) llrKind = lens _llrKind (\ s a -> s{_llrKind = a}) -- | The leaderboards. llrItems :: Lens' LeaderboardListResponse [Leaderboard] llrItems = lens _llrItems (\ s a -> s{_llrItems = a}) . _Default . _Coerce instance FromJSON LeaderboardListResponse where parseJSON = withObject "LeaderboardListResponse" (\ o -> LeaderboardListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON LeaderboardListResponse where toJSON LeaderboardListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _llrNextPageToken, ("kind" .=) <$> _llrKind, ("items" .=) <$> _llrItems]) -- | A player score. -- -- /See:/ 'playerScore' smart constructor. data PlayerScore = PlayerScore' { _psScoreTag :: !(Maybe Text) , _psScore :: !(Maybe (Textual Int64)) , _psKind :: !(Maybe Text) , _psFormattedScore :: !(Maybe Text) , _psTimeSpan :: !(Maybe PlayerScoreTimeSpan) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerScore' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psScoreTag' -- -- * 'psScore' -- -- * 'psKind' -- -- * 'psFormattedScore' -- -- * 'psTimeSpan' playerScore :: PlayerScore playerScore = PlayerScore' { _psScoreTag = Nothing , _psScore = Nothing , _psKind = Nothing , _psFormattedScore = Nothing , _psTimeSpan = Nothing } -- | Additional information about this score. Values will contain no more -- than 64 URI-safe characters as defined by section 2.3 of RFC 3986. psScoreTag :: Lens' PlayerScore (Maybe Text) psScoreTag = lens _psScoreTag (\ s a -> s{_psScoreTag = a}) -- | The numerical value for this player score. psScore :: Lens' PlayerScore (Maybe Int64) psScore = lens _psScore (\ s a -> s{_psScore = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerScore\`. psKind :: Lens' PlayerScore (Maybe Text) psKind = lens _psKind (\ s a -> s{_psKind = a}) -- | The formatted score for this player score. psFormattedScore :: Lens' PlayerScore (Maybe Text) psFormattedScore = lens _psFormattedScore (\ s a -> s{_psFormattedScore = a}) -- | The time span for this player score. psTimeSpan :: Lens' PlayerScore (Maybe PlayerScoreTimeSpan) psTimeSpan = lens _psTimeSpan (\ s a -> s{_psTimeSpan = a}) instance FromJSON PlayerScore where parseJSON = withObject "PlayerScore" (\ o -> PlayerScore' <$> (o .:? "scoreTag") <*> (o .:? "score") <*> (o .:? "kind") <*> (o .:? "formattedScore") <*> (o .:? "timeSpan")) instance ToJSON PlayerScore where toJSON PlayerScore'{..} = object (catMaybes [("scoreTag" .=) <$> _psScoreTag, ("score" .=) <$> _psScore, ("kind" .=) <$> _psKind, ("formattedScore" .=) <$> _psFormattedScore, ("timeSpan" .=) <$> _psTimeSpan]) -- | An image of a snapshot. -- -- /See:/ 'snapshotImage' smart constructor. data SnapshotImage = SnapshotImage' { _siHeight :: !(Maybe (Textual Int32)) , _siKind :: !(Maybe Text) , _siURL :: !(Maybe Text) , _siMimeType :: !(Maybe Text) , _siWidth :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SnapshotImage' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siHeight' -- -- * 'siKind' -- -- * 'siURL' -- -- * 'siMimeType' -- -- * 'siWidth' snapshotImage :: SnapshotImage snapshotImage = SnapshotImage' { _siHeight = Nothing , _siKind = Nothing , _siURL = Nothing , _siMimeType = Nothing , _siWidth = Nothing } -- | The height of the image. siHeight :: Lens' SnapshotImage (Maybe Int32) siHeight = lens _siHeight (\ s a -> s{_siHeight = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#snapshotImage\`. siKind :: Lens' SnapshotImage (Maybe Text) siKind = lens _siKind (\ s a -> s{_siKind = a}) -- | The URL of the image. This URL may be invalidated at any time and should -- not be cached. siURL :: Lens' SnapshotImage (Maybe Text) siURL = lens _siURL (\ s a -> s{_siURL = a}) -- | The MIME type of the image. siMimeType :: Lens' SnapshotImage (Maybe Text) siMimeType = lens _siMimeType (\ s a -> s{_siMimeType = a}) -- | The width of the image. siWidth :: Lens' SnapshotImage (Maybe Int32) siWidth = lens _siWidth (\ s a -> s{_siWidth = a}) . mapping _Coerce instance FromJSON SnapshotImage where parseJSON = withObject "SnapshotImage" (\ o -> SnapshotImage' <$> (o .:? "height") <*> (o .:? "kind") <*> (o .:? "url") <*> (o .:? "mime_type") <*> (o .:? "width")) instance ToJSON SnapshotImage where toJSON SnapshotImage'{..} = object (catMaybes [("height" .=) <$> _siHeight, ("kind" .=) <$> _siKind, ("url" .=) <$> _siURL, ("mime_type" .=) <$> _siMimeType, ("width" .=) <$> _siWidth]) -- | A list of player leaderboard scores. -- -- /See:/ 'playerLeaderboardScoreListResponse' smart constructor. data PlayerLeaderboardScoreListResponse = PlayerLeaderboardScoreListResponse' { _plslrNextPageToken :: !(Maybe Text) , _plslrKind :: !(Maybe Text) , _plslrItems :: !(Maybe [PlayerLeaderboardScore]) , _plslrPlayer :: !(Maybe Player) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerLeaderboardScoreListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plslrNextPageToken' -- -- * 'plslrKind' -- -- * 'plslrItems' -- -- * 'plslrPlayer' playerLeaderboardScoreListResponse :: PlayerLeaderboardScoreListResponse playerLeaderboardScoreListResponse = PlayerLeaderboardScoreListResponse' { _plslrNextPageToken = Nothing , _plslrKind = Nothing , _plslrItems = Nothing , _plslrPlayer = Nothing } -- | The pagination token for the next page of results. plslrNextPageToken :: Lens' PlayerLeaderboardScoreListResponse (Maybe Text) plslrNextPageToken = lens _plslrNextPageToken (\ s a -> s{_plslrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerLeaderboardScoreListResponse\`. plslrKind :: Lens' PlayerLeaderboardScoreListResponse (Maybe Text) plslrKind = lens _plslrKind (\ s a -> s{_plslrKind = a}) -- | The leaderboard scores. plslrItems :: Lens' PlayerLeaderboardScoreListResponse [PlayerLeaderboardScore] plslrItems = lens _plslrItems (\ s a -> s{_plslrItems = a}) . _Default . _Coerce -- | The Player resources for the owner of this score. plslrPlayer :: Lens' PlayerLeaderboardScoreListResponse (Maybe Player) plslrPlayer = lens _plslrPlayer (\ s a -> s{_plslrPlayer = a}) instance FromJSON PlayerLeaderboardScoreListResponse where parseJSON = withObject "PlayerLeaderboardScoreListResponse" (\ o -> PlayerLeaderboardScoreListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty) <*> (o .:? "player")) instance ToJSON PlayerLeaderboardScoreListResponse where toJSON PlayerLeaderboardScoreListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _plslrNextPageToken, ("kind" .=) <$> _plslrKind, ("items" .=) <$> _plslrItems, ("player" .=) <$> _plslrPlayer]) -- | The iOS details resource. -- -- /See:/ 'instanceIosDetails' smart constructor. data InstanceIosDetails = InstanceIosDetails' { _iidItunesAppId :: !(Maybe Text) , _iidPreferredForIPad :: !(Maybe Bool) , _iidSupportIPhone :: !(Maybe Bool) , _iidKind :: !(Maybe Text) , _iidSupportIPad :: !(Maybe Bool) , _iidPreferredForIPhone :: !(Maybe Bool) , _iidBundleIdentifier :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InstanceIosDetails' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iidItunesAppId' -- -- * 'iidPreferredForIPad' -- -- * 'iidSupportIPhone' -- -- * 'iidKind' -- -- * 'iidSupportIPad' -- -- * 'iidPreferredForIPhone' -- -- * 'iidBundleIdentifier' instanceIosDetails :: InstanceIosDetails instanceIosDetails = InstanceIosDetails' { _iidItunesAppId = Nothing , _iidPreferredForIPad = Nothing , _iidSupportIPhone = Nothing , _iidKind = Nothing , _iidSupportIPad = Nothing , _iidPreferredForIPhone = Nothing , _iidBundleIdentifier = Nothing } -- | iTunes App ID. iidItunesAppId :: Lens' InstanceIosDetails (Maybe Text) iidItunesAppId = lens _iidItunesAppId (\ s a -> s{_iidItunesAppId = a}) -- | Indicates that this instance is the default for new installations on -- iPad devices. iidPreferredForIPad :: Lens' InstanceIosDetails (Maybe Bool) iidPreferredForIPad = lens _iidPreferredForIPad (\ s a -> s{_iidPreferredForIPad = a}) -- | Flag to indicate if this instance supports iPhone. iidSupportIPhone :: Lens' InstanceIosDetails (Maybe Bool) iidSupportIPhone = lens _iidSupportIPhone (\ s a -> s{_iidSupportIPhone = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#instanceIosDetails\`. iidKind :: Lens' InstanceIosDetails (Maybe Text) iidKind = lens _iidKind (\ s a -> s{_iidKind = a}) -- | Flag to indicate if this instance supports iPad. iidSupportIPad :: Lens' InstanceIosDetails (Maybe Bool) iidSupportIPad = lens _iidSupportIPad (\ s a -> s{_iidSupportIPad = a}) -- | Indicates that this instance is the default for new installations on -- iPhone devices. iidPreferredForIPhone :: Lens' InstanceIosDetails (Maybe Bool) iidPreferredForIPhone = lens _iidPreferredForIPhone (\ s a -> s{_iidPreferredForIPhone = a}) -- | Bundle identifier. iidBundleIdentifier :: Lens' InstanceIosDetails (Maybe Text) iidBundleIdentifier = lens _iidBundleIdentifier (\ s a -> s{_iidBundleIdentifier = a}) instance FromJSON InstanceIosDetails where parseJSON = withObject "InstanceIosDetails" (\ o -> InstanceIosDetails' <$> (o .:? "itunesAppId") <*> (o .:? "preferredForIpad") <*> (o .:? "supportIphone") <*> (o .:? "kind") <*> (o .:? "supportIpad") <*> (o .:? "preferredForIphone") <*> (o .:? "bundleIdentifier")) instance ToJSON InstanceIosDetails where toJSON InstanceIosDetails'{..} = object (catMaybes [("itunesAppId" .=) <$> _iidItunesAppId, ("preferredForIpad" .=) <$> _iidPreferredForIPad, ("supportIphone" .=) <$> _iidSupportIPhone, ("kind" .=) <$> _iidKind, ("supportIpad" .=) <$> _iidSupportIPad, ("preferredForIphone" .=) <$> _iidPreferredForIPhone, ("bundleIdentifier" .=) <$> _iidBundleIdentifier]) -- | An event period update resource. -- -- /See:/ 'eventUpdateResponse' smart constructor. data EventUpdateResponse = EventUpdateResponse' { _eurPlayerEvents :: !(Maybe [PlayerEvent]) , _eurBatchFailures :: !(Maybe [EventBatchRecordFailure]) , _eurEventFailures :: !(Maybe [EventRecordFailure]) , _eurKind :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventUpdateResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eurPlayerEvents' -- -- * 'eurBatchFailures' -- -- * 'eurEventFailures' -- -- * 'eurKind' eventUpdateResponse :: EventUpdateResponse eventUpdateResponse = EventUpdateResponse' { _eurPlayerEvents = Nothing , _eurBatchFailures = Nothing , _eurEventFailures = Nothing , _eurKind = Nothing } -- | The current status of any updated events eurPlayerEvents :: Lens' EventUpdateResponse [PlayerEvent] eurPlayerEvents = lens _eurPlayerEvents (\ s a -> s{_eurPlayerEvents = a}) . _Default . _Coerce -- | Any batch-wide failures which occurred applying updates. eurBatchFailures :: Lens' EventUpdateResponse [EventBatchRecordFailure] eurBatchFailures = lens _eurBatchFailures (\ s a -> s{_eurBatchFailures = a}) . _Default . _Coerce -- | Any failures updating a particular event. eurEventFailures :: Lens' EventUpdateResponse [EventRecordFailure] eurEventFailures = lens _eurEventFailures (\ s a -> s{_eurEventFailures = a}) . _Default . _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventUpdateResponse\`. eurKind :: Lens' EventUpdateResponse (Maybe Text) eurKind = lens _eurKind (\ s a -> s{_eurKind = a}) instance FromJSON EventUpdateResponse where parseJSON = withObject "EventUpdateResponse" (\ o -> EventUpdateResponse' <$> (o .:? "playerEvents" .!= mempty) <*> (o .:? "batchFailures" .!= mempty) <*> (o .:? "eventFailures" .!= mempty) <*> (o .:? "kind")) instance ToJSON EventUpdateResponse where toJSON EventUpdateResponse'{..} = object (catMaybes [("playerEvents" .=) <$> _eurPlayerEvents, ("batchFailures" .=) <$> _eurBatchFailures, ("eventFailures" .=) <$> _eurEventFailures, ("kind" .=) <$> _eurKind]) -- | A third party checking a revision response. -- -- /See:/ 'revisionCheckResponse' smart constructor. data RevisionCheckResponse = RevisionCheckResponse' { _rcrAPIVersion :: !(Maybe Text) , _rcrKind :: !(Maybe Text) , _rcrRevisionStatus :: !(Maybe RevisionCheckResponseRevisionStatus) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RevisionCheckResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rcrAPIVersion' -- -- * 'rcrKind' -- -- * 'rcrRevisionStatus' revisionCheckResponse :: RevisionCheckResponse revisionCheckResponse = RevisionCheckResponse' {_rcrAPIVersion = Nothing, _rcrKind = Nothing, _rcrRevisionStatus = Nothing} -- | The version of the API this client revision should use when calling API -- methods. rcrAPIVersion :: Lens' RevisionCheckResponse (Maybe Text) rcrAPIVersion = lens _rcrAPIVersion (\ s a -> s{_rcrAPIVersion = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#revisionCheckResponse\`. rcrKind :: Lens' RevisionCheckResponse (Maybe Text) rcrKind = lens _rcrKind (\ s a -> s{_rcrKind = a}) -- | The result of the revision check. rcrRevisionStatus :: Lens' RevisionCheckResponse (Maybe RevisionCheckResponseRevisionStatus) rcrRevisionStatus = lens _rcrRevisionStatus (\ s a -> s{_rcrRevisionStatus = a}) instance FromJSON RevisionCheckResponse where parseJSON = withObject "RevisionCheckResponse" (\ o -> RevisionCheckResponse' <$> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "revisionStatus")) instance ToJSON RevisionCheckResponse where toJSON RevisionCheckResponse'{..} = object (catMaybes [("apiVersion" .=) <$> _rcrAPIVersion, ("kind" .=) <$> _rcrKind, ("revisionStatus" .=) <$> _rcrRevisionStatus]) -- | The Leaderboard resource. -- -- /See:/ 'leaderboard' smart constructor. data Leaderboard = Leaderboard' { _lKind :: !(Maybe Text) , _lIsIconURLDefault :: !(Maybe Bool) , _lName :: !(Maybe Text) , _lId :: !(Maybe Text) , _lIconURL :: !(Maybe Text) , _lOrder :: !(Maybe LeaderboardOrder) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Leaderboard' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lKind' -- -- * 'lIsIconURLDefault' -- -- * 'lName' -- -- * 'lId' -- -- * 'lIconURL' -- -- * 'lOrder' leaderboard :: Leaderboard leaderboard = Leaderboard' { _lKind = Nothing , _lIsIconURLDefault = Nothing , _lName = Nothing , _lId = Nothing , _lIconURL = Nothing , _lOrder = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#leaderboard\`. lKind :: Lens' Leaderboard (Maybe Text) lKind = lens _lKind (\ s a -> s{_lKind = a}) -- | Indicates whether the icon image being returned is a default image, or -- is game-provided. lIsIconURLDefault :: Lens' Leaderboard (Maybe Bool) lIsIconURLDefault = lens _lIsIconURLDefault (\ s a -> s{_lIsIconURLDefault = a}) -- | The name of the leaderboard. lName :: Lens' Leaderboard (Maybe Text) lName = lens _lName (\ s a -> s{_lName = a}) -- | The leaderboard ID. lId :: Lens' Leaderboard (Maybe Text) lId = lens _lId (\ s a -> s{_lId = a}) -- | The icon for the leaderboard. lIconURL :: Lens' Leaderboard (Maybe Text) lIconURL = lens _lIconURL (\ s a -> s{_lIconURL = a}) -- | How scores are ordered. lOrder :: Lens' Leaderboard (Maybe LeaderboardOrder) lOrder = lens _lOrder (\ s a -> s{_lOrder = a}) instance FromJSON Leaderboard where parseJSON = withObject "Leaderboard" (\ o -> Leaderboard' <$> (o .:? "kind") <*> (o .:? "isIconUrlDefault") <*> (o .:? "name") <*> (o .:? "id") <*> (o .:? "iconUrl") <*> (o .:? "order")) instance ToJSON Leaderboard where toJSON Leaderboard'{..} = object (catMaybes [("kind" .=) <$> _lKind, ("isIconUrlDefault" .=) <$> _lIsIconURLDefault, ("name" .=) <$> _lName, ("id" .=) <$> _lId, ("iconUrl" .=) <$> _lIconURL, ("order" .=) <$> _lOrder]) -- | The metagame config resource -- -- /See:/ 'metagameConfig' smart constructor. data MetagameConfig = MetagameConfig' { _mcKind :: !(Maybe Text) , _mcCurrentVersion :: !(Maybe (Textual Int32)) , _mcPlayerLevels :: !(Maybe [PlayerLevel]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MetagameConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mcKind' -- -- * 'mcCurrentVersion' -- -- * 'mcPlayerLevels' metagameConfig :: MetagameConfig metagameConfig = MetagameConfig' {_mcKind = Nothing, _mcCurrentVersion = Nothing, _mcPlayerLevels = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#metagameConfig\`. mcKind :: Lens' MetagameConfig (Maybe Text) mcKind = lens _mcKind (\ s a -> s{_mcKind = a}) -- | Current version of the metagame configuration data. When this data is -- updated, the version number will be increased by one. mcCurrentVersion :: Lens' MetagameConfig (Maybe Int32) mcCurrentVersion = lens _mcCurrentVersion (\ s a -> s{_mcCurrentVersion = a}) . mapping _Coerce -- | The list of player levels. mcPlayerLevels :: Lens' MetagameConfig [PlayerLevel] mcPlayerLevels = lens _mcPlayerLevels (\ s a -> s{_mcPlayerLevels = a}) . _Default . _Coerce instance FromJSON MetagameConfig where parseJSON = withObject "MetagameConfig" (\ o -> MetagameConfig' <$> (o .:? "kind") <*> (o .:? "currentVersion") <*> (o .:? "playerLevels" .!= mempty)) instance ToJSON MetagameConfig where toJSON MetagameConfig'{..} = object (catMaybes [("kind" .=) <$> _mcKind, ("currentVersion" .=) <$> _mcCurrentVersion, ("playerLevels" .=) <$> _mcPlayerLevels]) -- | A third party list metagame categories response. -- -- /See:/ 'categoryListResponse' smart constructor. data CategoryListResponse = CategoryListResponse' { _clrNextPageToken :: !(Maybe Text) , _clrKind :: !(Maybe Text) , _clrItems :: !(Maybe [Category]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CategoryListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'clrNextPageToken' -- -- * 'clrKind' -- -- * 'clrItems' categoryListResponse :: CategoryListResponse categoryListResponse = CategoryListResponse' {_clrNextPageToken = Nothing, _clrKind = Nothing, _clrItems = Nothing} -- | Token corresponding to the next page of results. clrNextPageToken :: Lens' CategoryListResponse (Maybe Text) clrNextPageToken = lens _clrNextPageToken (\ s a -> s{_clrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#categoryListResponse\`. clrKind :: Lens' CategoryListResponse (Maybe Text) clrKind = lens _clrKind (\ s a -> s{_clrKind = a}) -- | The list of categories with usage data. clrItems :: Lens' CategoryListResponse [Category] clrItems = lens _clrItems (\ s a -> s{_clrItems = a}) . _Default . _Coerce instance FromJSON CategoryListResponse where parseJSON = withObject "CategoryListResponse" (\ o -> CategoryListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON CategoryListResponse where toJSON CategoryListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _clrNextPageToken, ("kind" .=) <$> _clrKind, ("items" .=) <$> _clrItems]) -- | An event definition resource. -- -- /See:/ 'eventDefinition' smart constructor. data EventDefinition = EventDefinition' { _edIsDefaultImageURL :: !(Maybe Bool) , _edKind :: !(Maybe Text) , _edVisibility :: !(Maybe EventDefinitionVisibility) , _edImageURL :: !(Maybe Text) , _edDisplayName :: !(Maybe Text) , _edId :: !(Maybe Text) , _edChildEvents :: !(Maybe [EventChild]) , _edDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventDefinition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'edIsDefaultImageURL' -- -- * 'edKind' -- -- * 'edVisibility' -- -- * 'edImageURL' -- -- * 'edDisplayName' -- -- * 'edId' -- -- * 'edChildEvents' -- -- * 'edDescription' eventDefinition :: EventDefinition eventDefinition = EventDefinition' { _edIsDefaultImageURL = Nothing , _edKind = Nothing , _edVisibility = Nothing , _edImageURL = Nothing , _edDisplayName = Nothing , _edId = Nothing , _edChildEvents = Nothing , _edDescription = Nothing } -- | Indicates whether the icon image being returned is a default image, or -- is game-provided. edIsDefaultImageURL :: Lens' EventDefinition (Maybe Bool) edIsDefaultImageURL = lens _edIsDefaultImageURL (\ s a -> s{_edIsDefaultImageURL = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventDefinition\`. edKind :: Lens' EventDefinition (Maybe Text) edKind = lens _edKind (\ s a -> s{_edKind = a}) -- | The visibility of event being tracked in this definition. edVisibility :: Lens' EventDefinition (Maybe EventDefinitionVisibility) edVisibility = lens _edVisibility (\ s a -> s{_edVisibility = a}) -- | The base URL for the image that represents the event. edImageURL :: Lens' EventDefinition (Maybe Text) edImageURL = lens _edImageURL (\ s a -> s{_edImageURL = a}) -- | The name to display for the event. edDisplayName :: Lens' EventDefinition (Maybe Text) edDisplayName = lens _edDisplayName (\ s a -> s{_edDisplayName = a}) -- | The ID of the event. edId :: Lens' EventDefinition (Maybe Text) edId = lens _edId (\ s a -> s{_edId = a}) -- | A list of events that are a child of this event. edChildEvents :: Lens' EventDefinition [EventChild] edChildEvents = lens _edChildEvents (\ s a -> s{_edChildEvents = a}) . _Default . _Coerce -- | Description of what this event represents. edDescription :: Lens' EventDefinition (Maybe Text) edDescription = lens _edDescription (\ s a -> s{_edDescription = a}) instance FromJSON EventDefinition where parseJSON = withObject "EventDefinition" (\ o -> EventDefinition' <$> (o .:? "isDefaultImageUrl") <*> (o .:? "kind") <*> (o .:? "visibility") <*> (o .:? "imageUrl") <*> (o .:? "displayName") <*> (o .:? "id") <*> (o .:? "childEvents" .!= mempty) <*> (o .:? "description")) instance ToJSON EventDefinition where toJSON EventDefinition'{..} = object (catMaybes [("isDefaultImageUrl" .=) <$> _edIsDefaultImageURL, ("kind" .=) <$> _edKind, ("visibility" .=) <$> _edVisibility, ("imageUrl" .=) <$> _edImageURL, ("displayName" .=) <$> _edDisplayName, ("id" .=) <$> _edId, ("childEvents" .=) <$> _edChildEvents, ("description" .=) <$> _edDescription]) -- | An event period update resource. -- -- /See:/ 'eventUpdateRequest' smart constructor. data EventUpdateRequest = EventUpdateRequest' { _eUpdateCount :: !(Maybe (Textual Int64)) , _eKind :: !(Maybe Text) , _eDefinitionId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventUpdateRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eUpdateCount' -- -- * 'eKind' -- -- * 'eDefinitionId' eventUpdateRequest :: EventUpdateRequest eventUpdateRequest = EventUpdateRequest' {_eUpdateCount = Nothing, _eKind = Nothing, _eDefinitionId = Nothing} -- | The number of times this event occurred in this time period. eUpdateCount :: Lens' EventUpdateRequest (Maybe Int64) eUpdateCount = lens _eUpdateCount (\ s a -> s{_eUpdateCount = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventUpdateRequest\`. eKind :: Lens' EventUpdateRequest (Maybe Text) eKind = lens _eKind (\ s a -> s{_eKind = a}) -- | The ID of the event being modified in this update. eDefinitionId :: Lens' EventUpdateRequest (Maybe Text) eDefinitionId = lens _eDefinitionId (\ s a -> s{_eDefinitionId = a}) instance FromJSON EventUpdateRequest where parseJSON = withObject "EventUpdateRequest" (\ o -> EventUpdateRequest' <$> (o .:? "updateCount") <*> (o .:? "kind") <*> (o .:? "definitionId")) instance ToJSON EventUpdateRequest where toJSON EventUpdateRequest'{..} = object (catMaybes [("updateCount" .=) <$> _eUpdateCount, ("kind" .=) <$> _eKind, ("definitionId" .=) <$> _eDefinitionId]) -- | An achievement unlock response -- -- /See:/ 'achievementUnlockResponse' smart constructor. data AchievementUnlockResponse = AchievementUnlockResponse' { _achKind :: !(Maybe Text) , _achNewlyUnlocked :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementUnlockResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'achKind' -- -- * 'achNewlyUnlocked' achievementUnlockResponse :: AchievementUnlockResponse achievementUnlockResponse = AchievementUnlockResponse' {_achKind = Nothing, _achNewlyUnlocked = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementUnlockResponse\`. achKind :: Lens' AchievementUnlockResponse (Maybe Text) achKind = lens _achKind (\ s a -> s{_achKind = a}) -- | Whether this achievement was newly unlocked (that is, whether the unlock -- request for the achievement was the first for the player). achNewlyUnlocked :: Lens' AchievementUnlockResponse (Maybe Bool) achNewlyUnlocked = lens _achNewlyUnlocked (\ s a -> s{_achNewlyUnlocked = a}) instance FromJSON AchievementUnlockResponse where parseJSON = withObject "AchievementUnlockResponse" (\ o -> AchievementUnlockResponse' <$> (o .:? "kind") <*> (o .:? "newlyUnlocked")) instance ToJSON AchievementUnlockResponse where toJSON AchievementUnlockResponse'{..} = object (catMaybes [("kind" .=) <$> _achKind, ("newlyUnlocked" .=) <$> _achNewlyUnlocked]) -- | An achievement object. -- -- /See:/ 'playerAchievement' smart constructor. data PlayerAchievement = PlayerAchievement' { _paKind :: !(Maybe Text) , _paAchievementState :: !(Maybe PlayerAchievementAchievementState) , _paFormattedCurrentStepsString :: !(Maybe Text) , _paExperiencePoints :: !(Maybe (Textual Int64)) , _paId :: !(Maybe Text) , _paCurrentSteps :: !(Maybe (Textual Int32)) , _paLastUpdatedTimestamp :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerAchievement' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'paKind' -- -- * 'paAchievementState' -- -- * 'paFormattedCurrentStepsString' -- -- * 'paExperiencePoints' -- -- * 'paId' -- -- * 'paCurrentSteps' -- -- * 'paLastUpdatedTimestamp' playerAchievement :: PlayerAchievement playerAchievement = PlayerAchievement' { _paKind = Nothing , _paAchievementState = Nothing , _paFormattedCurrentStepsString = Nothing , _paExperiencePoints = Nothing , _paId = Nothing , _paCurrentSteps = Nothing , _paLastUpdatedTimestamp = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerAchievement\`. paKind :: Lens' PlayerAchievement (Maybe Text) paKind = lens _paKind (\ s a -> s{_paKind = a}) -- | The state of the achievement. paAchievementState :: Lens' PlayerAchievement (Maybe PlayerAchievementAchievementState) paAchievementState = lens _paAchievementState (\ s a -> s{_paAchievementState = a}) -- | The current steps for an incremental achievement as a string. paFormattedCurrentStepsString :: Lens' PlayerAchievement (Maybe Text) paFormattedCurrentStepsString = lens _paFormattedCurrentStepsString (\ s a -> s{_paFormattedCurrentStepsString = a}) -- | Experience points earned for the achievement. This field is absent for -- achievements that have not yet been unlocked and 0 for achievements that -- have been unlocked by testers but that are unpublished. paExperiencePoints :: Lens' PlayerAchievement (Maybe Int64) paExperiencePoints = lens _paExperiencePoints (\ s a -> s{_paExperiencePoints = a}) . mapping _Coerce -- | The ID of the achievement. paId :: Lens' PlayerAchievement (Maybe Text) paId = lens _paId (\ s a -> s{_paId = a}) -- | The current steps for an incremental achievement. paCurrentSteps :: Lens' PlayerAchievement (Maybe Int32) paCurrentSteps = lens _paCurrentSteps (\ s a -> s{_paCurrentSteps = a}) . mapping _Coerce -- | The timestamp of the last modification to this achievement\'s state. paLastUpdatedTimestamp :: Lens' PlayerAchievement (Maybe Int64) paLastUpdatedTimestamp = lens _paLastUpdatedTimestamp (\ s a -> s{_paLastUpdatedTimestamp = a}) . mapping _Coerce instance FromJSON PlayerAchievement where parseJSON = withObject "PlayerAchievement" (\ o -> PlayerAchievement' <$> (o .:? "kind") <*> (o .:? "achievementState") <*> (o .:? "formattedCurrentStepsString") <*> (o .:? "experiencePoints") <*> (o .:? "id") <*> (o .:? "currentSteps") <*> (o .:? "lastUpdatedTimestamp")) instance ToJSON PlayerAchievement where toJSON PlayerAchievement'{..} = object (catMaybes [("kind" .=) <$> _paKind, ("achievementState" .=) <$> _paAchievementState, ("formattedCurrentStepsString" .=) <$> _paFormattedCurrentStepsString, ("experiencePoints" .=) <$> _paExperiencePoints, ("id" .=) <$> _paId, ("currentSteps" .=) <$> _paCurrentSteps, ("lastUpdatedTimestamp" .=) <$> _paLastUpdatedTimestamp]) -- | An image asset object. -- -- /See:/ 'imageAsset' smart constructor. data ImageAsset = ImageAsset' { _iaHeight :: !(Maybe (Textual Int32)) , _iaKind :: !(Maybe Text) , _iaURL :: !(Maybe Text) , _iaWidth :: !(Maybe (Textual Int32)) , _iaName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ImageAsset' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iaHeight' -- -- * 'iaKind' -- -- * 'iaURL' -- -- * 'iaWidth' -- -- * 'iaName' imageAsset :: ImageAsset imageAsset = ImageAsset' { _iaHeight = Nothing , _iaKind = Nothing , _iaURL = Nothing , _iaWidth = Nothing , _iaName = Nothing } -- | The height of the asset. iaHeight :: Lens' ImageAsset (Maybe Int32) iaHeight = lens _iaHeight (\ s a -> s{_iaHeight = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#imageAsset\`. iaKind :: Lens' ImageAsset (Maybe Text) iaKind = lens _iaKind (\ s a -> s{_iaKind = a}) -- | The URL of the asset. iaURL :: Lens' ImageAsset (Maybe Text) iaURL = lens _iaURL (\ s a -> s{_iaURL = a}) -- | The width of the asset. iaWidth :: Lens' ImageAsset (Maybe Int32) iaWidth = lens _iaWidth (\ s a -> s{_iaWidth = a}) . mapping _Coerce -- | The name of the asset. iaName :: Lens' ImageAsset (Maybe Text) iaName = lens _iaName (\ s a -> s{_iaName = a}) instance FromJSON ImageAsset where parseJSON = withObject "ImageAsset" (\ o -> ImageAsset' <$> (o .:? "height") <*> (o .:? "kind") <*> (o .:? "url") <*> (o .:? "width") <*> (o .:? "name")) instance ToJSON ImageAsset where toJSON ImageAsset'{..} = object (catMaybes [("height" .=) <$> _iaHeight, ("kind" .=) <$> _iaKind, ("url" .=) <$> _iaURL, ("width" .=) <$> _iaWidth, ("name" .=) <$> _iaName]) -- | A list of achievement update requests. -- -- /See:/ 'achievementUpdateMultipleRequest' smart constructor. data AchievementUpdateMultipleRequest = AchievementUpdateMultipleRequest' { _aumruKind :: !(Maybe Text) , _aumruUpdates :: !(Maybe [AchievementUpdateRequest]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementUpdateMultipleRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aumruKind' -- -- * 'aumruUpdates' achievementUpdateMultipleRequest :: AchievementUpdateMultipleRequest achievementUpdateMultipleRequest = AchievementUpdateMultipleRequest' {_aumruKind = Nothing, _aumruUpdates = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementUpdateMultipleRequest\`. aumruKind :: Lens' AchievementUpdateMultipleRequest (Maybe Text) aumruKind = lens _aumruKind (\ s a -> s{_aumruKind = a}) -- | The individual achievement update requests. aumruUpdates :: Lens' AchievementUpdateMultipleRequest [AchievementUpdateRequest] aumruUpdates = lens _aumruUpdates (\ s a -> s{_aumruUpdates = a}) . _Default . _Coerce instance FromJSON AchievementUpdateMultipleRequest where parseJSON = withObject "AchievementUpdateMultipleRequest" (\ o -> AchievementUpdateMultipleRequest' <$> (o .:? "kind") <*> (o .:? "updates" .!= mempty)) instance ToJSON AchievementUpdateMultipleRequest where toJSON AchievementUpdateMultipleRequest'{..} = object (catMaybes [("kind" .=) <$> _aumruKind, ("updates" .=) <$> _aumruUpdates]) -- | A request to update an achievement. -- -- /See:/ 'achievementUpdateRequest' smart constructor. data AchievementUpdateRequest = AchievementUpdateRequest' { _auruAchievementId :: !(Maybe Text) , _auruKind :: !(Maybe Text) , _auruUpdateType :: !(Maybe AchievementUpdateRequestUpdateType) , _auruSetStepsAtLeastPayload :: !(Maybe GamesAchievementSetStepsAtLeast) , _auruIncrementPayload :: !(Maybe GamesAchievementIncrement) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementUpdateRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'auruAchievementId' -- -- * 'auruKind' -- -- * 'auruUpdateType' -- -- * 'auruSetStepsAtLeastPayload' -- -- * 'auruIncrementPayload' achievementUpdateRequest :: AchievementUpdateRequest achievementUpdateRequest = AchievementUpdateRequest' { _auruAchievementId = Nothing , _auruKind = Nothing , _auruUpdateType = Nothing , _auruSetStepsAtLeastPayload = Nothing , _auruIncrementPayload = Nothing } -- | The achievement this update is being applied to. auruAchievementId :: Lens' AchievementUpdateRequest (Maybe Text) auruAchievementId = lens _auruAchievementId (\ s a -> s{_auruAchievementId = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementUpdateRequest\`. auruKind :: Lens' AchievementUpdateRequest (Maybe Text) auruKind = lens _auruKind (\ s a -> s{_auruKind = a}) -- | The type of update being applied. auruUpdateType :: Lens' AchievementUpdateRequest (Maybe AchievementUpdateRequestUpdateType) auruUpdateType = lens _auruUpdateType (\ s a -> s{_auruUpdateType = a}) -- | The payload if an update of type \`SET_STEPS_AT_LEAST\` was requested -- for the achievement. auruSetStepsAtLeastPayload :: Lens' AchievementUpdateRequest (Maybe GamesAchievementSetStepsAtLeast) auruSetStepsAtLeastPayload = lens _auruSetStepsAtLeastPayload (\ s a -> s{_auruSetStepsAtLeastPayload = a}) -- | The payload if an update of type \`INCREMENT\` was requested for the -- achievement. auruIncrementPayload :: Lens' AchievementUpdateRequest (Maybe GamesAchievementIncrement) auruIncrementPayload = lens _auruIncrementPayload (\ s a -> s{_auruIncrementPayload = a}) instance FromJSON AchievementUpdateRequest where parseJSON = withObject "AchievementUpdateRequest" (\ o -> AchievementUpdateRequest' <$> (o .:? "achievementId") <*> (o .:? "kind") <*> (o .:? "updateType") <*> (o .:? "setStepsAtLeastPayload") <*> (o .:? "incrementPayload")) instance ToJSON AchievementUpdateRequest where toJSON AchievementUpdateRequest'{..} = object (catMaybes [("achievementId" .=) <$> _auruAchievementId, ("kind" .=) <$> _auruKind, ("updateType" .=) <$> _auruUpdateType, ("setStepsAtLeastPayload" .=) <$> _auruSetStepsAtLeastPayload, ("incrementPayload" .=) <$> _auruIncrementPayload]) -- | A score rank in a leaderboard. -- -- /See:/ 'leaderboardScoreRank' smart constructor. data LeaderboardScoreRank = LeaderboardScoreRank' { _lsrNumScores :: !(Maybe (Textual Int64)) , _lsrKind :: !(Maybe Text) , _lsrFormattedRank :: !(Maybe Text) , _lsrFormattedNumScores :: !(Maybe Text) , _lsrRank :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LeaderboardScoreRank' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsrNumScores' -- -- * 'lsrKind' -- -- * 'lsrFormattedRank' -- -- * 'lsrFormattedNumScores' -- -- * 'lsrRank' leaderboardScoreRank :: LeaderboardScoreRank leaderboardScoreRank = LeaderboardScoreRank' { _lsrNumScores = Nothing , _lsrKind = Nothing , _lsrFormattedRank = Nothing , _lsrFormattedNumScores = Nothing , _lsrRank = Nothing } -- | The number of scores in the leaderboard. lsrNumScores :: Lens' LeaderboardScoreRank (Maybe Int64) lsrNumScores = lens _lsrNumScores (\ s a -> s{_lsrNumScores = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#leaderboardScoreRank\`. lsrKind :: Lens' LeaderboardScoreRank (Maybe Text) lsrKind = lens _lsrKind (\ s a -> s{_lsrKind = a}) -- | The rank in the leaderboard as a string. lsrFormattedRank :: Lens' LeaderboardScoreRank (Maybe Text) lsrFormattedRank = lens _lsrFormattedRank (\ s a -> s{_lsrFormattedRank = a}) -- | The number of scores in the leaderboard as a string. lsrFormattedNumScores :: Lens' LeaderboardScoreRank (Maybe Text) lsrFormattedNumScores = lens _lsrFormattedNumScores (\ s a -> s{_lsrFormattedNumScores = a}) -- | The rank in the leaderboard. lsrRank :: Lens' LeaderboardScoreRank (Maybe Int64) lsrRank = lens _lsrRank (\ s a -> s{_lsrRank = a}) . mapping _Coerce instance FromJSON LeaderboardScoreRank where parseJSON = withObject "LeaderboardScoreRank" (\ o -> LeaderboardScoreRank' <$> (o .:? "numScores") <*> (o .:? "kind") <*> (o .:? "formattedRank") <*> (o .:? "formattedNumScores") <*> (o .:? "rank")) instance ToJSON LeaderboardScoreRank where toJSON LeaderboardScoreRank'{..} = object (catMaybes [("numScores" .=) <$> _lsrNumScores, ("kind" .=) <$> _lsrKind, ("formattedRank" .=) <$> _lsrFormattedRank, ("formattedNumScores" .=) <$> _lsrFormattedNumScores, ("rank" .=) <$> _lsrRank]) -- | A third party player list response. -- -- /See:/ 'playerListResponse' smart constructor. data PlayerListResponse = PlayerListResponse' { _plrNextPageToken :: !(Maybe Text) , _plrKind :: !(Maybe Text) , _plrItems :: !(Maybe [Player]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plrNextPageToken' -- -- * 'plrKind' -- -- * 'plrItems' playerListResponse :: PlayerListResponse playerListResponse = PlayerListResponse' {_plrNextPageToken = Nothing, _plrKind = Nothing, _plrItems = Nothing} -- | Token corresponding to the next page of results. plrNextPageToken :: Lens' PlayerListResponse (Maybe Text) plrNextPageToken = lens _plrNextPageToken (\ s a -> s{_plrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerListResponse\`. plrKind :: Lens' PlayerListResponse (Maybe Text) plrKind = lens _plrKind (\ s a -> s{_plrKind = a}) -- | The players. plrItems :: Lens' PlayerListResponse [Player] plrItems = lens _plrItems (\ s a -> s{_plrItems = a}) . _Default . _Coerce instance FromJSON PlayerListResponse where parseJSON = withObject "PlayerListResponse" (\ o -> PlayerListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON PlayerListResponse where toJSON PlayerListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _plrNextPageToken, ("kind" .=) <$> _plrKind, ("items" .=) <$> _plrItems]) -- | A ListScores response. -- -- /See:/ 'leaderboardScores' smart constructor. data LeaderboardScores = LeaderboardScores' { _lsNextPageToken :: !(Maybe Text) , _lsNumScores :: !(Maybe (Textual Int64)) , _lsKind :: !(Maybe Text) , _lsPlayerScore :: !(Maybe LeaderboardEntry) , _lsItems :: !(Maybe [LeaderboardEntry]) , _lsPrevPageToken :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LeaderboardScores' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsNextPageToken' -- -- * 'lsNumScores' -- -- * 'lsKind' -- -- * 'lsPlayerScore' -- -- * 'lsItems' -- -- * 'lsPrevPageToken' leaderboardScores :: LeaderboardScores leaderboardScores = LeaderboardScores' { _lsNextPageToken = Nothing , _lsNumScores = Nothing , _lsKind = Nothing , _lsPlayerScore = Nothing , _lsItems = Nothing , _lsPrevPageToken = Nothing } -- | The pagination token for the next page of results. lsNextPageToken :: Lens' LeaderboardScores (Maybe Text) lsNextPageToken = lens _lsNextPageToken (\ s a -> s{_lsNextPageToken = a}) -- | The total number of scores in the leaderboard. lsNumScores :: Lens' LeaderboardScores (Maybe Int64) lsNumScores = lens _lsNumScores (\ s a -> s{_lsNumScores = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#leaderboardScores\`. lsKind :: Lens' LeaderboardScores (Maybe Text) lsKind = lens _lsKind (\ s a -> s{_lsKind = a}) -- | The score of the requesting player on the leaderboard. The player\'s -- score may appear both here and in the list of scores above. If you are -- viewing a public leaderboard and the player is not sharing their -- gameplay information publicly, the \`scoreRank\`and -- \`formattedScoreRank\` values will not be present. lsPlayerScore :: Lens' LeaderboardScores (Maybe LeaderboardEntry) lsPlayerScore = lens _lsPlayerScore (\ s a -> s{_lsPlayerScore = a}) -- | The scores in the leaderboard. lsItems :: Lens' LeaderboardScores [LeaderboardEntry] lsItems = lens _lsItems (\ s a -> s{_lsItems = a}) . _Default . _Coerce -- | The pagination token for the previous page of results. lsPrevPageToken :: Lens' LeaderboardScores (Maybe Text) lsPrevPageToken = lens _lsPrevPageToken (\ s a -> s{_lsPrevPageToken = a}) instance FromJSON LeaderboardScores where parseJSON = withObject "LeaderboardScores" (\ o -> LeaderboardScores' <$> (o .:? "nextPageToken") <*> (o .:? "numScores") <*> (o .:? "kind") <*> (o .:? "playerScore") <*> (o .:? "items" .!= mempty) <*> (o .:? "prevPageToken")) instance ToJSON LeaderboardScores where toJSON LeaderboardScores'{..} = object (catMaybes [("nextPageToken" .=) <$> _lsNextPageToken, ("numScores" .=) <$> _lsNumScores, ("kind" .=) <$> _lsKind, ("playerScore" .=) <$> _lsPlayerScore, ("items" .=) <$> _lsItems, ("prevPageToken" .=) <$> _lsPrevPageToken]) -- | An achievement definition object. -- -- /See:/ 'achievementDefinition' smart constructor. data AchievementDefinition = AchievementDefinition' { _adAchievementType :: !(Maybe AchievementDefinitionAchievementType) , _adFormattedTotalSteps :: !(Maybe Text) , _adRevealedIconURL :: !(Maybe Text) , _adKind :: !(Maybe Text) , _adExperiencePoints :: !(Maybe (Textual Int64)) , _adInitialState :: !(Maybe AchievementDefinitionInitialState) , _adName :: !(Maybe Text) , _adId :: !(Maybe Text) , _adIsUnlockedIconURLDefault :: !(Maybe Bool) , _adTotalSteps :: !(Maybe (Textual Int32)) , _adDescription :: !(Maybe Text) , _adIsRevealedIconURLDefault :: !(Maybe Bool) , _adUnlockedIconURL :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementDefinition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adAchievementType' -- -- * 'adFormattedTotalSteps' -- -- * 'adRevealedIconURL' -- -- * 'adKind' -- -- * 'adExperiencePoints' -- -- * 'adInitialState' -- -- * 'adName' -- -- * 'adId' -- -- * 'adIsUnlockedIconURLDefault' -- -- * 'adTotalSteps' -- -- * 'adDescription' -- -- * 'adIsRevealedIconURLDefault' -- -- * 'adUnlockedIconURL' achievementDefinition :: AchievementDefinition achievementDefinition = AchievementDefinition' { _adAchievementType = Nothing , _adFormattedTotalSteps = Nothing , _adRevealedIconURL = Nothing , _adKind = Nothing , _adExperiencePoints = Nothing , _adInitialState = Nothing , _adName = Nothing , _adId = Nothing , _adIsUnlockedIconURLDefault = Nothing , _adTotalSteps = Nothing , _adDescription = Nothing , _adIsRevealedIconURLDefault = Nothing , _adUnlockedIconURL = Nothing } -- | The type of the achievement. adAchievementType :: Lens' AchievementDefinition (Maybe AchievementDefinitionAchievementType) adAchievementType = lens _adAchievementType (\ s a -> s{_adAchievementType = a}) -- | The total steps for an incremental achievement as a string. adFormattedTotalSteps :: Lens' AchievementDefinition (Maybe Text) adFormattedTotalSteps = lens _adFormattedTotalSteps (\ s a -> s{_adFormattedTotalSteps = a}) -- | The image URL for the revealed achievement icon. adRevealedIconURL :: Lens' AchievementDefinition (Maybe Text) adRevealedIconURL = lens _adRevealedIconURL (\ s a -> s{_adRevealedIconURL = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementDefinition\`. adKind :: Lens' AchievementDefinition (Maybe Text) adKind = lens _adKind (\ s a -> s{_adKind = a}) -- | Experience points which will be earned when unlocking this achievement. adExperiencePoints :: Lens' AchievementDefinition (Maybe Int64) adExperiencePoints = lens _adExperiencePoints (\ s a -> s{_adExperiencePoints = a}) . mapping _Coerce -- | The initial state of the achievement. adInitialState :: Lens' AchievementDefinition (Maybe AchievementDefinitionInitialState) adInitialState = lens _adInitialState (\ s a -> s{_adInitialState = a}) -- | The name of the achievement. adName :: Lens' AchievementDefinition (Maybe Text) adName = lens _adName (\ s a -> s{_adName = a}) -- | The ID of the achievement. adId :: Lens' AchievementDefinition (Maybe Text) adId = lens _adId (\ s a -> s{_adId = a}) -- | Indicates whether the unlocked icon image being returned is a default -- image, or is game-provided. adIsUnlockedIconURLDefault :: Lens' AchievementDefinition (Maybe Bool) adIsUnlockedIconURLDefault = lens _adIsUnlockedIconURLDefault (\ s a -> s{_adIsUnlockedIconURLDefault = a}) -- | The total steps for an incremental achievement. adTotalSteps :: Lens' AchievementDefinition (Maybe Int32) adTotalSteps = lens _adTotalSteps (\ s a -> s{_adTotalSteps = a}) . mapping _Coerce -- | The description of the achievement. adDescription :: Lens' AchievementDefinition (Maybe Text) adDescription = lens _adDescription (\ s a -> s{_adDescription = a}) -- | Indicates whether the revealed icon image being returned is a default -- image, or is provided by the game. adIsRevealedIconURLDefault :: Lens' AchievementDefinition (Maybe Bool) adIsRevealedIconURLDefault = lens _adIsRevealedIconURLDefault (\ s a -> s{_adIsRevealedIconURLDefault = a}) -- | The image URL for the unlocked achievement icon. adUnlockedIconURL :: Lens' AchievementDefinition (Maybe Text) adUnlockedIconURL = lens _adUnlockedIconURL (\ s a -> s{_adUnlockedIconURL = a}) instance FromJSON AchievementDefinition where parseJSON = withObject "AchievementDefinition" (\ o -> AchievementDefinition' <$> (o .:? "achievementType") <*> (o .:? "formattedTotalSteps") <*> (o .:? "revealedIconUrl") <*> (o .:? "kind") <*> (o .:? "experiencePoints") <*> (o .:? "initialState") <*> (o .:? "name") <*> (o .:? "id") <*> (o .:? "isUnlockedIconUrlDefault") <*> (o .:? "totalSteps") <*> (o .:? "description") <*> (o .:? "isRevealedIconUrlDefault") <*> (o .:? "unlockedIconUrl")) instance ToJSON AchievementDefinition where toJSON AchievementDefinition'{..} = object (catMaybes [("achievementType" .=) <$> _adAchievementType, ("formattedTotalSteps" .=) <$> _adFormattedTotalSteps, ("revealedIconUrl" .=) <$> _adRevealedIconURL, ("kind" .=) <$> _adKind, ("experiencePoints" .=) <$> _adExperiencePoints, ("initialState" .=) <$> _adInitialState, ("name" .=) <$> _adName, ("id" .=) <$> _adId, ("isUnlockedIconUrlDefault" .=) <$> _adIsUnlockedIconURLDefault, ("totalSteps" .=) <$> _adTotalSteps, ("description" .=) <$> _adDescription, ("isRevealedIconUrlDefault" .=) <$> _adIsRevealedIconURLDefault, ("unlockedIconUrl" .=) <$> _adUnlockedIconURL]) -- | A batch update failure resource. -- -- /See:/ 'eventBatchRecordFailure' smart constructor. data EventBatchRecordFailure = EventBatchRecordFailure' { _ebrfKind :: !(Maybe Text) , _ebrfRange :: !(Maybe EventPeriodRange) , _ebrfFailureCause :: !(Maybe EventBatchRecordFailureFailureCause) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventBatchRecordFailure' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ebrfKind' -- -- * 'ebrfRange' -- -- * 'ebrfFailureCause' eventBatchRecordFailure :: EventBatchRecordFailure eventBatchRecordFailure = EventBatchRecordFailure' {_ebrfKind = Nothing, _ebrfRange = Nothing, _ebrfFailureCause = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventBatchRecordFailure\`. ebrfKind :: Lens' EventBatchRecordFailure (Maybe Text) ebrfKind = lens _ebrfKind (\ s a -> s{_ebrfKind = a}) -- | The time range which was rejected; empty for a request-wide failure. ebrfRange :: Lens' EventBatchRecordFailure (Maybe EventPeriodRange) ebrfRange = lens _ebrfRange (\ s a -> s{_ebrfRange = a}) -- | The cause for the update failure. ebrfFailureCause :: Lens' EventBatchRecordFailure (Maybe EventBatchRecordFailureFailureCause) ebrfFailureCause = lens _ebrfFailureCause (\ s a -> s{_ebrfFailureCause = a}) instance FromJSON EventBatchRecordFailure where parseJSON = withObject "EventBatchRecordFailure" (\ o -> EventBatchRecordFailure' <$> (o .:? "kind") <*> (o .:? "range") <*> (o .:? "failureCause")) instance ToJSON EventBatchRecordFailure where toJSON EventBatchRecordFailure'{..} = object (catMaybes [("kind" .=) <$> _ebrfKind, ("range" .=) <$> _ebrfRange, ("failureCause" .=) <$> _ebrfFailureCause]) -- | An achievement increment response -- -- /See:/ 'achievementIncrementResponse' smart constructor. data AchievementIncrementResponse = AchievementIncrementResponse' { _airKind :: !(Maybe Text) , _airNewlyUnlocked :: !(Maybe Bool) , _airCurrentSteps :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementIncrementResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'airKind' -- -- * 'airNewlyUnlocked' -- -- * 'airCurrentSteps' achievementIncrementResponse :: AchievementIncrementResponse achievementIncrementResponse = AchievementIncrementResponse' { _airKind = Nothing , _airNewlyUnlocked = Nothing , _airCurrentSteps = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementIncrementResponse\`. airKind :: Lens' AchievementIncrementResponse (Maybe Text) airKind = lens _airKind (\ s a -> s{_airKind = a}) -- | Whether the current steps for the achievement has reached the number of -- steps required to unlock. airNewlyUnlocked :: Lens' AchievementIncrementResponse (Maybe Bool) airNewlyUnlocked = lens _airNewlyUnlocked (\ s a -> s{_airNewlyUnlocked = a}) -- | The current steps recorded for this incremental achievement. airCurrentSteps :: Lens' AchievementIncrementResponse (Maybe Int32) airCurrentSteps = lens _airCurrentSteps (\ s a -> s{_airCurrentSteps = a}) . mapping _Coerce instance FromJSON AchievementIncrementResponse where parseJSON = withObject "AchievementIncrementResponse" (\ o -> AchievementIncrementResponse' <$> (o .:? "kind") <*> (o .:? "newlyUnlocked") <*> (o .:? "currentSteps")) instance ToJSON AchievementIncrementResponse where toJSON AchievementIncrementResponse'{..} = object (catMaybes [("kind" .=) <$> _airKind, ("newlyUnlocked" .=) <$> _airNewlyUnlocked, ("currentSteps" .=) <$> _airCurrentSteps]) -- | An achievement reveal response -- -- /See:/ 'achievementRevealResponse' smart constructor. data AchievementRevealResponse = AchievementRevealResponse' { _arrKind :: !(Maybe Text) , _arrCurrentState :: !(Maybe AchievementRevealResponseCurrentState) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementRevealResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'arrKind' -- -- * 'arrCurrentState' achievementRevealResponse :: AchievementRevealResponse achievementRevealResponse = AchievementRevealResponse' {_arrKind = Nothing, _arrCurrentState = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementRevealResponse\`. arrKind :: Lens' AchievementRevealResponse (Maybe Text) arrKind = lens _arrKind (\ s a -> s{_arrKind = a}) -- | The current state of the achievement for which a reveal was attempted. -- This might be \`UNLOCKED\` if the achievement was already unlocked. arrCurrentState :: Lens' AchievementRevealResponse (Maybe AchievementRevealResponseCurrentState) arrCurrentState = lens _arrCurrentState (\ s a -> s{_arrCurrentState = a}) instance FromJSON AchievementRevealResponse where parseJSON = withObject "AchievementRevealResponse" (\ o -> AchievementRevealResponse' <$> (o .:? "kind") <*> (o .:? "currentState")) instance ToJSON AchievementRevealResponse where toJSON AchievementRevealResponse'{..} = object (catMaybes [("kind" .=) <$> _arrKind, ("currentState" .=) <$> _arrCurrentState]) -- | An achievement set steps at least response. -- -- /See:/ 'achievementSetStepsAtLeastResponse' smart constructor. data AchievementSetStepsAtLeastResponse = AchievementSetStepsAtLeastResponse' { _assalrKind :: !(Maybe Text) , _assalrNewlyUnlocked :: !(Maybe Bool) , _assalrCurrentSteps :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementSetStepsAtLeastResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'assalrKind' -- -- * 'assalrNewlyUnlocked' -- -- * 'assalrCurrentSteps' achievementSetStepsAtLeastResponse :: AchievementSetStepsAtLeastResponse achievementSetStepsAtLeastResponse = AchievementSetStepsAtLeastResponse' { _assalrKind = Nothing , _assalrNewlyUnlocked = Nothing , _assalrCurrentSteps = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#achievementSetStepsAtLeastResponse\`. assalrKind :: Lens' AchievementSetStepsAtLeastResponse (Maybe Text) assalrKind = lens _assalrKind (\ s a -> s{_assalrKind = a}) -- | Whether the current steps for the achievement has reached the number of -- steps required to unlock. assalrNewlyUnlocked :: Lens' AchievementSetStepsAtLeastResponse (Maybe Bool) assalrNewlyUnlocked = lens _assalrNewlyUnlocked (\ s a -> s{_assalrNewlyUnlocked = a}) -- | The current steps recorded for this incremental achievement. assalrCurrentSteps :: Lens' AchievementSetStepsAtLeastResponse (Maybe Int32) assalrCurrentSteps = lens _assalrCurrentSteps (\ s a -> s{_assalrCurrentSteps = a}) . mapping _Coerce instance FromJSON AchievementSetStepsAtLeastResponse where parseJSON = withObject "AchievementSetStepsAtLeastResponse" (\ o -> AchievementSetStepsAtLeastResponse' <$> (o .:? "kind") <*> (o .:? "newlyUnlocked") <*> (o .:? "currentSteps")) instance ToJSON AchievementSetStepsAtLeastResponse where toJSON AchievementSetStepsAtLeastResponse'{..} = object (catMaybes [("kind" .=) <$> _assalrKind, ("newlyUnlocked" .=) <$> _assalrNewlyUnlocked, ("currentSteps" .=) <$> _assalrCurrentSteps]) -- | A list of achievement objects. -- -- /See:/ 'playerAchievementListResponse' smart constructor. data PlayerAchievementListResponse = PlayerAchievementListResponse' { _palrNextPageToken :: !(Maybe Text) , _palrKind :: !(Maybe Text) , _palrItems :: !(Maybe [PlayerAchievement]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerAchievementListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'palrNextPageToken' -- -- * 'palrKind' -- -- * 'palrItems' playerAchievementListResponse :: PlayerAchievementListResponse playerAchievementListResponse = PlayerAchievementListResponse' {_palrNextPageToken = Nothing, _palrKind = Nothing, _palrItems = Nothing} -- | Token corresponding to the next page of results. palrNextPageToken :: Lens' PlayerAchievementListResponse (Maybe Text) palrNextPageToken = lens _palrNextPageToken (\ s a -> s{_palrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerAchievementListResponse\`. palrKind :: Lens' PlayerAchievementListResponse (Maybe Text) palrKind = lens _palrKind (\ s a -> s{_palrKind = a}) -- | The achievements. palrItems :: Lens' PlayerAchievementListResponse [PlayerAchievement] palrItems = lens _palrItems (\ s a -> s{_palrItems = a}) . _Default . _Coerce instance FromJSON PlayerAchievementListResponse where parseJSON = withObject "PlayerAchievementListResponse" (\ o -> PlayerAchievementListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON PlayerAchievementListResponse where toJSON PlayerAchievementListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _palrNextPageToken, ("kind" .=) <$> _palrKind, ("items" .=) <$> _palrItems]) -- | An event period update resource. -- -- /See:/ 'eventRecordRequest' smart constructor. data EventRecordRequest = EventRecordRequest' { _errRequestId :: !(Maybe (Textual Int64)) , _errKind :: !(Maybe Text) , _errCurrentTimeMillis :: !(Maybe (Textual Int64)) , _errTimePeriods :: !(Maybe [EventPeriodUpdate]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventRecordRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'errRequestId' -- -- * 'errKind' -- -- * 'errCurrentTimeMillis' -- -- * 'errTimePeriods' eventRecordRequest :: EventRecordRequest eventRecordRequest = EventRecordRequest' { _errRequestId = Nothing , _errKind = Nothing , _errCurrentTimeMillis = Nothing , _errTimePeriods = Nothing } -- | The request ID used to identify this attempt to record events. errRequestId :: Lens' EventRecordRequest (Maybe Int64) errRequestId = lens _errRequestId (\ s a -> s{_errRequestId = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventRecordRequest\`. errKind :: Lens' EventRecordRequest (Maybe Text) errKind = lens _errKind (\ s a -> s{_errKind = a}) -- | The current time when this update was sent, in milliseconds, since 1970 -- UTC (Unix Epoch). errCurrentTimeMillis :: Lens' EventRecordRequest (Maybe Int64) errCurrentTimeMillis = lens _errCurrentTimeMillis (\ s a -> s{_errCurrentTimeMillis = a}) . mapping _Coerce -- | A list of the time period updates being made in this request. errTimePeriods :: Lens' EventRecordRequest [EventPeriodUpdate] errTimePeriods = lens _errTimePeriods (\ s a -> s{_errTimePeriods = a}) . _Default . _Coerce instance FromJSON EventRecordRequest where parseJSON = withObject "EventRecordRequest" (\ o -> EventRecordRequest' <$> (o .:? "requestId") <*> (o .:? "kind") <*> (o .:? "currentTimeMillis") <*> (o .:? "timePeriods" .!= mempty)) instance ToJSON EventRecordRequest where toJSON EventRecordRequest'{..} = object (catMaybes [("requestId" .=) <$> _errRequestId, ("kind" .=) <$> _errKind, ("currentTimeMillis" .=) <$> _errCurrentTimeMillis, ("timePeriods" .=) <$> _errTimePeriods]) -- | An event period update resource. -- -- /See:/ 'eventPeriodUpdate' smart constructor. data EventPeriodUpdate = EventPeriodUpdate' { _epuKind :: !(Maybe Text) , _epuTimePeriod :: !(Maybe EventPeriodRange) , _epuUpdates :: !(Maybe [EventUpdateRequest]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventPeriodUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'epuKind' -- -- * 'epuTimePeriod' -- -- * 'epuUpdates' eventPeriodUpdate :: EventPeriodUpdate eventPeriodUpdate = EventPeriodUpdate' {_epuKind = Nothing, _epuTimePeriod = Nothing, _epuUpdates = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventPeriodUpdate\`. epuKind :: Lens' EventPeriodUpdate (Maybe Text) epuKind = lens _epuKind (\ s a -> s{_epuKind = a}) -- | The time period being covered by this update. epuTimePeriod :: Lens' EventPeriodUpdate (Maybe EventPeriodRange) epuTimePeriod = lens _epuTimePeriod (\ s a -> s{_epuTimePeriod = a}) -- | The updates being made for this time period. epuUpdates :: Lens' EventPeriodUpdate [EventUpdateRequest] epuUpdates = lens _epuUpdates (\ s a -> s{_epuUpdates = a}) . _Default . _Coerce instance FromJSON EventPeriodUpdate where parseJSON = withObject "EventPeriodUpdate" (\ o -> EventPeriodUpdate' <$> (o .:? "kind") <*> (o .:? "timePeriod") <*> (o .:? "updates" .!= mempty)) instance ToJSON EventPeriodUpdate where toJSON EventPeriodUpdate'{..} = object (catMaybes [("kind" .=) <$> _epuKind, ("timePeriod" .=) <$> _epuTimePeriod, ("updates" .=) <$> _epuUpdates]) -- | A request to submit a score to leaderboards. -- -- /See:/ 'scoreSubmission' smart constructor. data ScoreSubmission = ScoreSubmission' { _scoSignature :: !(Maybe Text) , _scoScoreTag :: !(Maybe Text) , _scoScore :: !(Maybe (Textual Int64)) , _scoKind :: !(Maybe Text) , _scoLeaderboardId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ScoreSubmission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scoSignature' -- -- * 'scoScoreTag' -- -- * 'scoScore' -- -- * 'scoKind' -- -- * 'scoLeaderboardId' scoreSubmission :: ScoreSubmission scoreSubmission = ScoreSubmission' { _scoSignature = Nothing , _scoScoreTag = Nothing , _scoScore = Nothing , _scoKind = Nothing , _scoLeaderboardId = Nothing } -- | Signature Values will contain URI-safe characters as defined by section -- 2.3 of RFC 3986. scoSignature :: Lens' ScoreSubmission (Maybe Text) scoSignature = lens _scoSignature (\ s a -> s{_scoSignature = a}) -- | Additional information about this score. Values will contain no more -- than 64 URI-safe characters as defined by section 2.3 of RFC 3986. scoScoreTag :: Lens' ScoreSubmission (Maybe Text) scoScoreTag = lens _scoScoreTag (\ s a -> s{_scoScoreTag = a}) -- | The new score being submitted. scoScore :: Lens' ScoreSubmission (Maybe Int64) scoScore = lens _scoScore (\ s a -> s{_scoScore = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#scoreSubmission\`. scoKind :: Lens' ScoreSubmission (Maybe Text) scoKind = lens _scoKind (\ s a -> s{_scoKind = a}) -- | The leaderboard this score is being submitted to. scoLeaderboardId :: Lens' ScoreSubmission (Maybe Text) scoLeaderboardId = lens _scoLeaderboardId (\ s a -> s{_scoLeaderboardId = a}) instance FromJSON ScoreSubmission where parseJSON = withObject "ScoreSubmission" (\ o -> ScoreSubmission' <$> (o .:? "signature") <*> (o .:? "scoreTag") <*> (o .:? "score") <*> (o .:? "kind") <*> (o .:? "leaderboardId")) instance ToJSON ScoreSubmission where toJSON ScoreSubmission'{..} = object (catMaybes [("signature" .=) <$> _scoSignature, ("scoreTag" .=) <$> _scoScoreTag, ("score" .=) <$> _scoScore, ("kind" .=) <$> _scoKind, ("leaderboardId" .=) <$> _scoLeaderboardId]) -- | Container for a URL end point of the requested type. -- -- /See:/ 'endPoint' smart constructor. newtype EndPoint = EndPoint' { _epURL :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EndPoint' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'epURL' endPoint :: EndPoint endPoint = EndPoint' {_epURL = Nothing} -- | A URL suitable for loading in a web browser for the requested endpoint. epURL :: Lens' EndPoint (Maybe Text) epURL = lens _epURL (\ s a -> s{_epURL = a}) instance FromJSON EndPoint where parseJSON = withObject "EndPoint" (\ o -> EndPoint' <$> (o .:? "url")) instance ToJSON EndPoint where toJSON EndPoint'{..} = object (catMaybes [("url" .=) <$> _epURL]) -- | The Web details resource. -- -- /See:/ 'instanceWebDetails' smart constructor. data InstanceWebDetails = InstanceWebDetails' { _iwdPreferred :: !(Maybe Bool) , _iwdKind :: !(Maybe Text) , _iwdLaunchURL :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InstanceWebDetails' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iwdPreferred' -- -- * 'iwdKind' -- -- * 'iwdLaunchURL' instanceWebDetails :: InstanceWebDetails instanceWebDetails = InstanceWebDetails' {_iwdPreferred = Nothing, _iwdKind = Nothing, _iwdLaunchURL = Nothing} -- | Indicates that this instance is the default for new installations. iwdPreferred :: Lens' InstanceWebDetails (Maybe Bool) iwdPreferred = lens _iwdPreferred (\ s a -> s{_iwdPreferred = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#instanceWebDetails\`. iwdKind :: Lens' InstanceWebDetails (Maybe Text) iwdKind = lens _iwdKind (\ s a -> s{_iwdKind = a}) -- | Launch URL for the game. iwdLaunchURL :: Lens' InstanceWebDetails (Maybe Text) iwdLaunchURL = lens _iwdLaunchURL (\ s a -> s{_iwdLaunchURL = a}) instance FromJSON InstanceWebDetails where parseJSON = withObject "InstanceWebDetails" (\ o -> InstanceWebDetails' <$> (o .:? "preferred") <*> (o .:? "kind") <*> (o .:? "launchUrl")) instance ToJSON InstanceWebDetails where toJSON InstanceWebDetails'{..} = object (catMaybes [("preferred" .=) <$> _iwdPreferred, ("kind" .=) <$> _iwdKind, ("launchUrl" .=) <$> _iwdLaunchURL]) -- | 1P\/3P metadata about the player\'s experience. -- -- /See:/ 'playerExperienceInfo' smart constructor. data PlayerExperienceInfo = PlayerExperienceInfo' { _peiKind :: !(Maybe Text) , _peiCurrentExperiencePoints :: !(Maybe (Textual Int64)) , _peiCurrentLevel :: !(Maybe PlayerLevel) , _peiNextLevel :: !(Maybe PlayerLevel) , _peiLastLevelUpTimestampMillis :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerExperienceInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'peiKind' -- -- * 'peiCurrentExperiencePoints' -- -- * 'peiCurrentLevel' -- -- * 'peiNextLevel' -- -- * 'peiLastLevelUpTimestampMillis' playerExperienceInfo :: PlayerExperienceInfo playerExperienceInfo = PlayerExperienceInfo' { _peiKind = Nothing , _peiCurrentExperiencePoints = Nothing , _peiCurrentLevel = Nothing , _peiNextLevel = Nothing , _peiLastLevelUpTimestampMillis = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerExperienceInfo\`. peiKind :: Lens' PlayerExperienceInfo (Maybe Text) peiKind = lens _peiKind (\ s a -> s{_peiKind = a}) -- | The current number of experience points for the player. peiCurrentExperiencePoints :: Lens' PlayerExperienceInfo (Maybe Int64) peiCurrentExperiencePoints = lens _peiCurrentExperiencePoints (\ s a -> s{_peiCurrentExperiencePoints = a}) . mapping _Coerce -- | The current level of the player. peiCurrentLevel :: Lens' PlayerExperienceInfo (Maybe PlayerLevel) peiCurrentLevel = lens _peiCurrentLevel (\ s a -> s{_peiCurrentLevel = a}) -- | The next level of the player. If the current level is the maximum level, -- this should be same as the current level. peiNextLevel :: Lens' PlayerExperienceInfo (Maybe PlayerLevel) peiNextLevel = lens _peiNextLevel (\ s a -> s{_peiNextLevel = a}) -- | The timestamp when the player was leveled up, in millis since Unix epoch -- UTC. peiLastLevelUpTimestampMillis :: Lens' PlayerExperienceInfo (Maybe Int64) peiLastLevelUpTimestampMillis = lens _peiLastLevelUpTimestampMillis (\ s a -> s{_peiLastLevelUpTimestampMillis = a}) . mapping _Coerce instance FromJSON PlayerExperienceInfo where parseJSON = withObject "PlayerExperienceInfo" (\ o -> PlayerExperienceInfo' <$> (o .:? "kind") <*> (o .:? "currentExperiencePoints") <*> (o .:? "currentLevel") <*> (o .:? "nextLevel") <*> (o .:? "lastLevelUpTimestampMillis")) instance ToJSON PlayerExperienceInfo where toJSON PlayerExperienceInfo'{..} = object (catMaybes [("kind" .=) <$> _peiKind, ("currentExperiencePoints" .=) <$> _peiCurrentExperiencePoints, ("currentLevel" .=) <$> _peiCurrentLevel, ("nextLevel" .=) <$> _peiNextLevel, ("lastLevelUpTimestampMillis" .=) <$> _peiLastLevelUpTimestampMillis]) -- | The payload to request to increment an achievement. -- -- /See:/ 'gamesAchievementSetStepsAtLeast' smart constructor. data GamesAchievementSetStepsAtLeast = GamesAchievementSetStepsAtLeast' { _gassalKind :: !(Maybe Text) , _gassalSteps :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GamesAchievementSetStepsAtLeast' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gassalKind' -- -- * 'gassalSteps' gamesAchievementSetStepsAtLeast :: GamesAchievementSetStepsAtLeast gamesAchievementSetStepsAtLeast = GamesAchievementSetStepsAtLeast' {_gassalKind = Nothing, _gassalSteps = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#GamesAchievementSetStepsAtLeast\`. gassalKind :: Lens' GamesAchievementSetStepsAtLeast (Maybe Text) gassalKind = lens _gassalKind (\ s a -> s{_gassalKind = a}) -- | The minimum number of steps for the achievement to be set to. gassalSteps :: Lens' GamesAchievementSetStepsAtLeast (Maybe Int32) gassalSteps = lens _gassalSteps (\ s a -> s{_gassalSteps = a}) . mapping _Coerce instance FromJSON GamesAchievementSetStepsAtLeast where parseJSON = withObject "GamesAchievementSetStepsAtLeast" (\ o -> GamesAchievementSetStepsAtLeast' <$> (o .:? "kind") <*> (o .:? "steps")) instance ToJSON GamesAchievementSetStepsAtLeast where toJSON GamesAchievementSetStepsAtLeast'{..} = object (catMaybes [("kind" .=) <$> _gassalKind, ("steps" .=) <$> _gassalSteps]) -- | A Player resource. -- -- /See:/ 'player' smart constructor. data Player = Player' { _pBannerURLLandscape :: !(Maybe Text) , _pAvatarImageURL :: !(Maybe Text) , _pKind :: !(Maybe Text) , _pExperienceInfo :: !(Maybe PlayerExperienceInfo) , _pName :: !(Maybe PlayerName) , _pOriginalPlayerId :: !(Maybe Text) , _pDisplayName :: !(Maybe Text) , _pTitle :: !(Maybe Text) , _pBannerURLPortrait :: !(Maybe Text) , _pPlayerId :: !(Maybe Text) , _pProFileSettings :: !(Maybe ProFileSettings) , _pFriendStatus :: !(Maybe PlayerFriendStatus) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Player' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pBannerURLLandscape' -- -- * 'pAvatarImageURL' -- -- * 'pKind' -- -- * 'pExperienceInfo' -- -- * 'pName' -- -- * 'pOriginalPlayerId' -- -- * 'pDisplayName' -- -- * 'pTitle' -- -- * 'pBannerURLPortrait' -- -- * 'pPlayerId' -- -- * 'pProFileSettings' -- -- * 'pFriendStatus' player :: Player player = Player' { _pBannerURLLandscape = Nothing , _pAvatarImageURL = Nothing , _pKind = Nothing , _pExperienceInfo = Nothing , _pName = Nothing , _pOriginalPlayerId = Nothing , _pDisplayName = Nothing , _pTitle = Nothing , _pBannerURLPortrait = Nothing , _pPlayerId = Nothing , _pProFileSettings = Nothing , _pFriendStatus = Nothing } -- | The url to the landscape mode player banner image. pBannerURLLandscape :: Lens' Player (Maybe Text) pBannerURLLandscape = lens _pBannerURLLandscape (\ s a -> s{_pBannerURLLandscape = a}) -- | The base URL for the image that represents the player. pAvatarImageURL :: Lens' Player (Maybe Text) pAvatarImageURL = lens _pAvatarImageURL (\ s a -> s{_pAvatarImageURL = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#player\` pKind :: Lens' Player (Maybe Text) pKind = lens _pKind (\ s a -> s{_pKind = a}) -- | An object to represent Play Game experience information for the player. pExperienceInfo :: Lens' Player (Maybe PlayerExperienceInfo) pExperienceInfo = lens _pExperienceInfo (\ s a -> s{_pExperienceInfo = a}) -- | A representation of the individual components of the name. pName :: Lens' Player (Maybe PlayerName) pName = lens _pName (\ s a -> s{_pName = a}) -- | The player ID that was used for this player the first time they signed -- into the game in question. This is only populated for calls to -- player.get for the requesting player, only if the player ID has -- subsequently changed, and only to clients that support remapping player -- IDs. pOriginalPlayerId :: Lens' Player (Maybe Text) pOriginalPlayerId = lens _pOriginalPlayerId (\ s a -> s{_pOriginalPlayerId = a}) -- | The name to display for the player. pDisplayName :: Lens' Player (Maybe Text) pDisplayName = lens _pDisplayName (\ s a -> s{_pDisplayName = a}) -- | The player\'s title rewarded for their game activities. pTitle :: Lens' Player (Maybe Text) pTitle = lens _pTitle (\ s a -> s{_pTitle = a}) -- | The url to the portrait mode player banner image. pBannerURLPortrait :: Lens' Player (Maybe Text) pBannerURLPortrait = lens _pBannerURLPortrait (\ s a -> s{_pBannerURLPortrait = a}) -- | The ID of the player. pPlayerId :: Lens' Player (Maybe Text) pPlayerId = lens _pPlayerId (\ s a -> s{_pPlayerId = a}) -- | The player\'s profile settings. Controls whether or not the player\'s -- profile is visible to other players. pProFileSettings :: Lens' Player (Maybe ProFileSettings) pProFileSettings = lens _pProFileSettings (\ s a -> s{_pProFileSettings = a}) -- | The friend status of the given player, relative to the requester. This -- is unset if the player is not sharing their friends list with the game. pFriendStatus :: Lens' Player (Maybe PlayerFriendStatus) pFriendStatus = lens _pFriendStatus (\ s a -> s{_pFriendStatus = a}) instance FromJSON Player where parseJSON = withObject "Player" (\ o -> Player' <$> (o .:? "bannerUrlLandscape") <*> (o .:? "avatarImageUrl") <*> (o .:? "kind") <*> (o .:? "experienceInfo") <*> (o .:? "name") <*> (o .:? "originalPlayerId") <*> (o .:? "displayName") <*> (o .:? "title") <*> (o .:? "bannerUrlPortrait") <*> (o .:? "playerId") <*> (o .:? "profileSettings") <*> (o .:? "friendStatus")) instance ToJSON Player where toJSON Player'{..} = object (catMaybes [("bannerUrlLandscape" .=) <$> _pBannerURLLandscape, ("avatarImageUrl" .=) <$> _pAvatarImageURL, ("kind" .=) <$> _pKind, ("experienceInfo" .=) <$> _pExperienceInfo, ("name" .=) <$> _pName, ("originalPlayerId" .=) <$> _pOriginalPlayerId, ("displayName" .=) <$> _pDisplayName, ("title" .=) <$> _pTitle, ("bannerUrlPortrait" .=) <$> _pBannerURLPortrait, ("playerId" .=) <$> _pPlayerId, ("profileSettings" .=) <$> _pProFileSettings, ("friendStatus" .=) <$> _pFriendStatus]) -- | The payload to request to increment an achievement. -- -- /See:/ 'gamesAchievementIncrement' smart constructor. data GamesAchievementIncrement = GamesAchievementIncrement' { _gaiRequestId :: !(Maybe (Textual Int64)) , _gaiKind :: !(Maybe Text) , _gaiSteps :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GamesAchievementIncrement' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gaiRequestId' -- -- * 'gaiKind' -- -- * 'gaiSteps' gamesAchievementIncrement :: GamesAchievementIncrement gamesAchievementIncrement = GamesAchievementIncrement' {_gaiRequestId = Nothing, _gaiKind = Nothing, _gaiSteps = Nothing} -- | The requestId associated with an increment to an achievement. gaiRequestId :: Lens' GamesAchievementIncrement (Maybe Int64) gaiRequestId = lens _gaiRequestId (\ s a -> s{_gaiRequestId = a}) . mapping _Coerce -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#GamesAchievementIncrement\`. gaiKind :: Lens' GamesAchievementIncrement (Maybe Text) gaiKind = lens _gaiKind (\ s a -> s{_gaiKind = a}) -- | The number of steps to be incremented. gaiSteps :: Lens' GamesAchievementIncrement (Maybe Int32) gaiSteps = lens _gaiSteps (\ s a -> s{_gaiSteps = a}) . mapping _Coerce instance FromJSON GamesAchievementIncrement where parseJSON = withObject "GamesAchievementIncrement" (\ o -> GamesAchievementIncrement' <$> (o .:? "requestId") <*> (o .:? "kind") <*> (o .:? "steps")) instance ToJSON GamesAchievementIncrement where toJSON GamesAchievementIncrement'{..} = object (catMaybes [("requestId" .=) <$> _gaiRequestId, ("kind" .=) <$> _gaiKind, ("steps" .=) <$> _gaiSteps]) -- | An event child relationship resource. -- -- /See:/ 'eventChild' smart constructor. data EventChild = EventChild' { _ecKind :: !(Maybe Text) , _ecChildId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventChild' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ecKind' -- -- * 'ecChildId' eventChild :: EventChild eventChild = EventChild' {_ecKind = Nothing, _ecChildId = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventChild\`. ecKind :: Lens' EventChild (Maybe Text) ecKind = lens _ecKind (\ s a -> s{_ecKind = a}) -- | The ID of the child event. ecChildId :: Lens' EventChild (Maybe Text) ecChildId = lens _ecChildId (\ s a -> s{_ecChildId = a}) instance FromJSON EventChild where parseJSON = withObject "EventChild" (\ o -> EventChild' <$> (o .:? "kind") <*> (o .:? "childId")) instance ToJSON EventChild where toJSON EventChild'{..} = object (catMaybes [("kind" .=) <$> _ecKind, ("childId" .=) <$> _ecChildId]) -- | A third party application verification response resource. -- -- /See:/ 'applicationVerifyResponse' smart constructor. data ApplicationVerifyResponse = ApplicationVerifyResponse' { _avrKind :: !(Maybe Text) , _avrAlternatePlayerId :: !(Maybe Text) , _avrPlayerId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationVerifyResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'avrKind' -- -- * 'avrAlternatePlayerId' -- -- * 'avrPlayerId' applicationVerifyResponse :: ApplicationVerifyResponse applicationVerifyResponse = ApplicationVerifyResponse' { _avrKind = Nothing , _avrAlternatePlayerId = Nothing , _avrPlayerId = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#applicationVerifyResponse\`. avrKind :: Lens' ApplicationVerifyResponse (Maybe Text) avrKind = lens _avrKind (\ s a -> s{_avrKind = a}) -- | An alternate ID that was once used for the player that was issued the -- auth token used in this request. (This field is not normally populated.) avrAlternatePlayerId :: Lens' ApplicationVerifyResponse (Maybe Text) avrAlternatePlayerId = lens _avrAlternatePlayerId (\ s a -> s{_avrAlternatePlayerId = a}) -- | The ID of the player that was issued the auth token used in this -- request. avrPlayerId :: Lens' ApplicationVerifyResponse (Maybe Text) avrPlayerId = lens _avrPlayerId (\ s a -> s{_avrPlayerId = a}) instance FromJSON ApplicationVerifyResponse where parseJSON = withObject "ApplicationVerifyResponse" (\ o -> ApplicationVerifyResponse' <$> (o .:? "kind") <*> (o .:? "alternate_player_id") <*> (o .:? "player_id")) instance ToJSON ApplicationVerifyResponse where toJSON ApplicationVerifyResponse'{..} = object (catMaybes [("kind" .=) <$> _avrKind, ("alternate_player_id" .=) <$> _avrAlternatePlayerId, ("player_id" .=) <$> _avrPlayerId]) -- | A ListByPlayer response. -- -- /See:/ 'playerEventListResponse' smart constructor. data PlayerEventListResponse = PlayerEventListResponse' { _pelrNextPageToken :: !(Maybe Text) , _pelrKind :: !(Maybe Text) , _pelrItems :: !(Maybe [PlayerEvent]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerEventListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pelrNextPageToken' -- -- * 'pelrKind' -- -- * 'pelrItems' playerEventListResponse :: PlayerEventListResponse playerEventListResponse = PlayerEventListResponse' {_pelrNextPageToken = Nothing, _pelrKind = Nothing, _pelrItems = Nothing} -- | The pagination token for the next page of results. pelrNextPageToken :: Lens' PlayerEventListResponse (Maybe Text) pelrNextPageToken = lens _pelrNextPageToken (\ s a -> s{_pelrNextPageToken = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerEventListResponse\`. pelrKind :: Lens' PlayerEventListResponse (Maybe Text) pelrKind = lens _pelrKind (\ s a -> s{_pelrKind = a}) -- | The player events. pelrItems :: Lens' PlayerEventListResponse [PlayerEvent] pelrItems = lens _pelrItems (\ s a -> s{_pelrItems = a}) . _Default . _Coerce instance FromJSON PlayerEventListResponse where parseJSON = withObject "PlayerEventListResponse" (\ o -> PlayerEventListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty)) instance ToJSON PlayerEventListResponse where toJSON PlayerEventListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _pelrNextPageToken, ("kind" .=) <$> _pelrKind, ("items" .=) <$> _pelrItems]) -- | Profile settings -- -- /See:/ 'proFileSettings' smart constructor. data ProFileSettings = ProFileSettings' { _pfsProFileVisible :: !(Maybe Bool) , _pfsFriendsListVisibility :: !(Maybe ProFileSettingsFriendsListVisibility) , _pfsKind :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProFileSettings' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pfsProFileVisible' -- -- * 'pfsFriendsListVisibility' -- -- * 'pfsKind' proFileSettings :: ProFileSettings proFileSettings = ProFileSettings' { _pfsProFileVisible = Nothing , _pfsFriendsListVisibility = Nothing , _pfsKind = Nothing } -- | Whether the player\'s profile is visible to the currently signed in -- player. pfsProFileVisible :: Lens' ProFileSettings (Maybe Bool) pfsProFileVisible = lens _pfsProFileVisible (\ s a -> s{_pfsProFileVisible = a}) pfsFriendsListVisibility :: Lens' ProFileSettings (Maybe ProFileSettingsFriendsListVisibility) pfsFriendsListVisibility = lens _pfsFriendsListVisibility (\ s a -> s{_pfsFriendsListVisibility = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#profileSettings\`. pfsKind :: Lens' ProFileSettings (Maybe Text) pfsKind = lens _pfsKind (\ s a -> s{_pfsKind = a}) instance FromJSON ProFileSettings where parseJSON = withObject "ProFileSettings" (\ o -> ProFileSettings' <$> (o .:? "profileVisible") <*> (o .:? "friendsListVisibility") <*> (o .:? "kind")) instance ToJSON ProFileSettings where toJSON ProFileSettings'{..} = object (catMaybes [("profileVisible" .=) <$> _pfsProFileVisible, ("friendsListVisibility" .=) <$> _pfsFriendsListVisibility, ("kind" .=) <$> _pfsKind]) -- | An event period time range. -- -- /See:/ 'eventPeriodRange' smart constructor. data EventPeriodRange = EventPeriodRange' { _eprKind :: !(Maybe Text) , _eprPeriodStartMillis :: !(Maybe (Textual Int64)) , _eprPeriodEndMillis :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventPeriodRange' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eprKind' -- -- * 'eprPeriodStartMillis' -- -- * 'eprPeriodEndMillis' eventPeriodRange :: EventPeriodRange eventPeriodRange = EventPeriodRange' { _eprKind = Nothing , _eprPeriodStartMillis = Nothing , _eprPeriodEndMillis = Nothing } -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventPeriodRange\`. eprKind :: Lens' EventPeriodRange (Maybe Text) eprKind = lens _eprKind (\ s a -> s{_eprKind = a}) -- | The time when this update period begins, in millis, since 1970 UTC (Unix -- Epoch). eprPeriodStartMillis :: Lens' EventPeriodRange (Maybe Int64) eprPeriodStartMillis = lens _eprPeriodStartMillis (\ s a -> s{_eprPeriodStartMillis = a}) . mapping _Coerce -- | The time when this update period ends, in millis, since 1970 UTC (Unix -- Epoch). eprPeriodEndMillis :: Lens' EventPeriodRange (Maybe Int64) eprPeriodEndMillis = lens _eprPeriodEndMillis (\ s a -> s{_eprPeriodEndMillis = a}) . mapping _Coerce instance FromJSON EventPeriodRange where parseJSON = withObject "EventPeriodRange" (\ o -> EventPeriodRange' <$> (o .:? "kind") <*> (o .:? "periodStartMillis") <*> (o .:? "periodEndMillis")) instance ToJSON EventPeriodRange where toJSON EventPeriodRange'{..} = object (catMaybes [("kind" .=) <$> _eprKind, ("periodStartMillis" .=) <$> _eprPeriodStartMillis, ("periodEndMillis" .=) <$> _eprPeriodEndMillis]) -- | An event update failure resource. -- -- /See:/ 'eventRecordFailure' smart constructor. data EventRecordFailure = EventRecordFailure' { _erfKind :: !(Maybe Text) , _erfFailureCause :: !(Maybe EventRecordFailureFailureCause) , _erfEventId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventRecordFailure' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'erfKind' -- -- * 'erfFailureCause' -- -- * 'erfEventId' eventRecordFailure :: EventRecordFailure eventRecordFailure = EventRecordFailure' {_erfKind = Nothing, _erfFailureCause = Nothing, _erfEventId = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#eventRecordFailure\`. erfKind :: Lens' EventRecordFailure (Maybe Text) erfKind = lens _erfKind (\ s a -> s{_erfKind = a}) -- | The cause for the update failure. erfFailureCause :: Lens' EventRecordFailure (Maybe EventRecordFailureFailureCause) erfFailureCause = lens _erfFailureCause (\ s a -> s{_erfFailureCause = a}) -- | The ID of the event that was not updated. erfEventId :: Lens' EventRecordFailure (Maybe Text) erfEventId = lens _erfEventId (\ s a -> s{_erfEventId = a}) instance FromJSON EventRecordFailure where parseJSON = withObject "EventRecordFailure" (\ o -> EventRecordFailure' <$> (o .:? "kind") <*> (o .:? "failureCause") <*> (o .:? "eventId")) instance ToJSON EventRecordFailure where toJSON EventRecordFailure'{..} = object (catMaybes [("kind" .=) <$> _erfKind, ("failureCause" .=) <$> _erfFailureCause, ("eventId" .=) <$> _erfEventId]) -- | A list of score submission requests. -- -- /See:/ 'playerScoreSubmissionList' smart constructor. data PlayerScoreSubmissionList = PlayerScoreSubmissionList' { _psslKind :: !(Maybe Text) , _psslScores :: !(Maybe [ScoreSubmission]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlayerScoreSubmissionList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psslKind' -- -- * 'psslScores' playerScoreSubmissionList :: PlayerScoreSubmissionList playerScoreSubmissionList = PlayerScoreSubmissionList' {_psslKind = Nothing, _psslScores = Nothing} -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#playerScoreSubmissionList\`. psslKind :: Lens' PlayerScoreSubmissionList (Maybe Text) psslKind = lens _psslKind (\ s a -> s{_psslKind = a}) -- | The score submissions. psslScores :: Lens' PlayerScoreSubmissionList [ScoreSubmission] psslScores = lens _psslScores (\ s a -> s{_psslScores = a}) . _Default . _Coerce instance FromJSON PlayerScoreSubmissionList where parseJSON = withObject "PlayerScoreSubmissionList" (\ o -> PlayerScoreSubmissionList' <$> (o .:? "kind") <*> (o .:? "scores" .!= mempty)) instance ToJSON PlayerScoreSubmissionList where toJSON PlayerScoreSubmissionList'{..} = object (catMaybes [("kind" .=) <$> _psslKind, ("scores" .=) <$> _psslScores]) -- | The Instance resource. -- -- /See:/ 'instance'' smart constructor. data Instance = Instance' { _iAndroidInstance :: !(Maybe InstanceAndroidDetails) , _iKind :: !(Maybe Text) , _iWebInstance :: !(Maybe InstanceWebDetails) , _iIosInstance :: !(Maybe InstanceIosDetails) , _iName :: !(Maybe Text) , _iAcquisitionURI :: !(Maybe Text) , _iPlatformType :: !(Maybe InstancePlatformType) , _iTurnBasedPlay :: !(Maybe Bool) , _iRealtimePlay :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Instance' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iAndroidInstance' -- -- * 'iKind' -- -- * 'iWebInstance' -- -- * 'iIosInstance' -- -- * 'iName' -- -- * 'iAcquisitionURI' -- -- * 'iPlatformType' -- -- * 'iTurnBasedPlay' -- -- * 'iRealtimePlay' instance' :: Instance instance' = Instance' { _iAndroidInstance = Nothing , _iKind = Nothing , _iWebInstance = Nothing , _iIosInstance = Nothing , _iName = Nothing , _iAcquisitionURI = Nothing , _iPlatformType = Nothing , _iTurnBasedPlay = Nothing , _iRealtimePlay = Nothing } -- | Platform dependent details for Android. iAndroidInstance :: Lens' Instance (Maybe InstanceAndroidDetails) iAndroidInstance = lens _iAndroidInstance (\ s a -> s{_iAndroidInstance = a}) -- | Uniquely identifies the type of this resource. Value is always the fixed -- string \`games#instance\`. iKind :: Lens' Instance (Maybe Text) iKind = lens _iKind (\ s a -> s{_iKind = a}) -- | Platform dependent details for Web. iWebInstance :: Lens' Instance (Maybe InstanceWebDetails) iWebInstance = lens _iWebInstance (\ s a -> s{_iWebInstance = a}) -- | Platform dependent details for iOS. iIosInstance :: Lens' Instance (Maybe InstanceIosDetails) iIosInstance = lens _iIosInstance (\ s a -> s{_iIosInstance = a}) -- | Localized display name. iName :: Lens' Instance (Maybe Text) iName = lens _iName (\ s a -> s{_iName = a}) -- | URI which shows where a user can acquire this instance. iAcquisitionURI :: Lens' Instance (Maybe Text) iAcquisitionURI = lens _iAcquisitionURI (\ s a -> s{_iAcquisitionURI = a}) -- | The platform type. iPlatformType :: Lens' Instance (Maybe InstancePlatformType) iPlatformType = lens _iPlatformType (\ s a -> s{_iPlatformType = a}) -- | Flag to show if this game instance supports turn based play. iTurnBasedPlay :: Lens' Instance (Maybe Bool) iTurnBasedPlay = lens _iTurnBasedPlay (\ s a -> s{_iTurnBasedPlay = a}) -- | Flag to show if this game instance supports realtime play. iRealtimePlay :: Lens' Instance (Maybe Bool) iRealtimePlay = lens _iRealtimePlay (\ s a -> s{_iRealtimePlay = a}) instance FromJSON Instance where parseJSON = withObject "Instance" (\ o -> Instance' <$> (o .:? "androidInstance") <*> (o .:? "kind") <*> (o .:? "webInstance") <*> (o .:? "iosInstance") <*> (o .:? "name") <*> (o .:? "acquisitionUri") <*> (o .:? "platformType") <*> (o .:? "turnBasedPlay") <*> (o .:? "realtimePlay")) instance ToJSON Instance where toJSON Instance'{..} = object (catMaybes [("androidInstance" .=) <$> _iAndroidInstance, ("kind" .=) <$> _iKind, ("webInstance" .=) <$> _iWebInstance, ("iosInstance" .=) <$> _iIosInstance, ("name" .=) <$> _iName, ("acquisitionUri" .=) <$> _iAcquisitionURI, ("platformType" .=) <$> _iPlatformType, ("turnBasedPlay" .=) <$> _iTurnBasedPlay, ("realtimePlay" .=) <$> _iRealtimePlay])
brendanhay/gogol
gogol-games/gen/Network/Google/Games/Types/Product.hs
mpl-2.0
163,440
0
23
40,334
32,526
18,654
13,872
3,573
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.Monitoring.Services.ServiceLevelObjectives.Delete -- 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) -- -- Delete the given ServiceLevelObjective. -- -- /See:/ <https://cloud.google.com/monitoring/api/ Cloud Monitoring API Reference> for @monitoring.services.serviceLevelObjectives.delete@. module Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Delete ( -- * REST Resource ServicesServiceLevelObjectivesDeleteResource -- * Creating a Request , servicesServiceLevelObjectivesDelete , ServicesServiceLevelObjectivesDelete -- * Request Lenses , sslodXgafv , sslodUploadProtocol , sslodAccessToken , sslodUploadType , sslodName , sslodCallback ) where import Network.Google.Monitoring.Types import Network.Google.Prelude -- | A resource alias for @monitoring.services.serviceLevelObjectives.delete@ method which the -- 'ServicesServiceLevelObjectivesDelete' request conforms to. type ServicesServiceLevelObjectivesDeleteResource = "v3" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Delete the given ServiceLevelObjective. -- -- /See:/ 'servicesServiceLevelObjectivesDelete' smart constructor. data ServicesServiceLevelObjectivesDelete = ServicesServiceLevelObjectivesDelete' { _sslodXgafv :: !(Maybe Xgafv) , _sslodUploadProtocol :: !(Maybe Text) , _sslodAccessToken :: !(Maybe Text) , _sslodUploadType :: !(Maybe Text) , _sslodName :: !Text , _sslodCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServicesServiceLevelObjectivesDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sslodXgafv' -- -- * 'sslodUploadProtocol' -- -- * 'sslodAccessToken' -- -- * 'sslodUploadType' -- -- * 'sslodName' -- -- * 'sslodCallback' servicesServiceLevelObjectivesDelete :: Text -- ^ 'sslodName' -> ServicesServiceLevelObjectivesDelete servicesServiceLevelObjectivesDelete pSslodName_ = ServicesServiceLevelObjectivesDelete' { _sslodXgafv = Nothing , _sslodUploadProtocol = Nothing , _sslodAccessToken = Nothing , _sslodUploadType = Nothing , _sslodName = pSslodName_ , _sslodCallback = Nothing } -- | V1 error format. sslodXgafv :: Lens' ServicesServiceLevelObjectivesDelete (Maybe Xgafv) sslodXgafv = lens _sslodXgafv (\ s a -> s{_sslodXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). sslodUploadProtocol :: Lens' ServicesServiceLevelObjectivesDelete (Maybe Text) sslodUploadProtocol = lens _sslodUploadProtocol (\ s a -> s{_sslodUploadProtocol = a}) -- | OAuth access token. sslodAccessToken :: Lens' ServicesServiceLevelObjectivesDelete (Maybe Text) sslodAccessToken = lens _sslodAccessToken (\ s a -> s{_sslodAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). sslodUploadType :: Lens' ServicesServiceLevelObjectivesDelete (Maybe Text) sslodUploadType = lens _sslodUploadType (\ s a -> s{_sslodUploadType = a}) -- | Required. Resource name of the ServiceLevelObjective to delete. The -- format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/services\/[SERVICE_ID]\/serviceLevelObjectives\/[SLO_NAME] sslodName :: Lens' ServicesServiceLevelObjectivesDelete Text sslodName = lens _sslodName (\ s a -> s{_sslodName = a}) -- | JSONP sslodCallback :: Lens' ServicesServiceLevelObjectivesDelete (Maybe Text) sslodCallback = lens _sslodCallback (\ s a -> s{_sslodCallback = a}) instance GoogleRequest ServicesServiceLevelObjectivesDelete where type Rs ServicesServiceLevelObjectivesDelete = Empty type Scopes ServicesServiceLevelObjectivesDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/monitoring"] requestClient ServicesServiceLevelObjectivesDelete'{..} = go _sslodName _sslodXgafv _sslodUploadProtocol _sslodAccessToken _sslodUploadType _sslodCallback (Just AltJSON) monitoringService where go = buildClient (Proxy :: Proxy ServicesServiceLevelObjectivesDeleteResource) mempty
brendanhay/gogol
gogol-monitoring/gen/Network/Google/Resource/Monitoring/Services/ServiceLevelObjectives/Delete.hs
mpl-2.0
5,343
0
15
1,109
700
410
290
107
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.GlobalAddresses.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates an address resource in the specified project using the data -- included in the request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.globalAddresses.insert@. module Network.Google.Resource.Compute.GlobalAddresses.Insert ( -- * REST Resource GlobalAddressesInsertResource -- * Creating a Request , globalAddressesInsert , GlobalAddressesInsert -- * Request Lenses , gaiProject , gaiPayload ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.globalAddresses.insert@ method which the -- 'GlobalAddressesInsert' request conforms to. type GlobalAddressesInsertResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "addresses" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Address :> Post '[JSON] Operation -- | Creates an address resource in the specified project using the data -- included in the request. -- -- /See:/ 'globalAddressesInsert' smart constructor. data GlobalAddressesInsert = GlobalAddressesInsert' { _gaiProject :: !Text , _gaiPayload :: !Address } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'GlobalAddressesInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gaiProject' -- -- * 'gaiPayload' globalAddressesInsert :: Text -- ^ 'gaiProject' -> Address -- ^ 'gaiPayload' -> GlobalAddressesInsert globalAddressesInsert pGaiProject_ pGaiPayload_ = GlobalAddressesInsert' { _gaiProject = pGaiProject_ , _gaiPayload = pGaiPayload_ } -- | Project ID for this request. gaiProject :: Lens' GlobalAddressesInsert Text gaiProject = lens _gaiProject (\ s a -> s{_gaiProject = a}) -- | Multipart request metadata. gaiPayload :: Lens' GlobalAddressesInsert Address gaiPayload = lens _gaiPayload (\ s a -> s{_gaiPayload = a}) instance GoogleRequest GlobalAddressesInsert where type Rs GlobalAddressesInsert = Operation type Scopes GlobalAddressesInsert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient GlobalAddressesInsert'{..} = go _gaiProject (Just AltJSON) _gaiPayload computeService where go = buildClient (Proxy :: Proxy GlobalAddressesInsertResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/GlobalAddresses/Insert.hs
mpl-2.0
3,445
0
15
782
395
238
157
64
1
#!/usr/bin/env runhaskell import System (system, ExitCode) import Distribution.Simple import Distribution.PackageDescription -- for the argument types of the `postInst' hook import Distribution.Simple.LocalBuildInfo main = defaultMain
jelmer/tdb-hs
Setup.hs
lgpl-3.0
239
0
5
28
35
22
13
5
1
module Preferences where import Character import System.Random data Color = Red | Blue | Green | Yellow | Black | Gray | White | Magenta | Orange | Purple | Cyan | Viridian | Pink | Beige | Brown deriving (Show, Eq, Enum) genColor :: Int -> Color genColor x = toEnum x data Appreciation = High | Medium | Low deriving (Show, Eq, Ord, Enum) toAppreciation x | x >= (100 * 2) / 3 = High | x >= (100 / 3) = Medium | otherwise = Low data Season = Winter | Spring | Summer | Autumn deriving (Show, Eq, Enum) data TimeOfDay = Morning | Midday | Afternoon | Evening | Night deriving (Show, Eq, Ord, Enum) data Climate = Arctic | Subarctic | Temperate | Tropical | Desert | Alpine deriving (Show, Eq, Enum) data Gender = Male | Female deriving (Show, Eq, Enum) data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Show, Eq, Enum) data Holiday = TaxReturnDay | NoPantsDay | ValentinesDay data Preference = ColorPref Color Appreciation | MusicPref String Appreciation | FoodPref String Appreciation | SeasonPref Season Appreciation | TodPref TimeOfDay Appreciation | GamePref String Appreciation | ClimatePref Climate Appreciation | GenderPref Gender Appreciation | BrandPref String Appreciation | LifeStylePref String Appreciation | DayPref Day Appreciation | HolidayPref Holiday Appreciation -- data Subject -- = Color -- | Music -- | Food -- | Season -- | Tod -- | Game -- | Climate -- | Gender -- | Brand -- | LifeStyle -- | Day -- | Holiday -- data Preference = Preference Subject Appreciation data Preferences = Preferences { color :: Preference , music :: Preference , food :: Preference , season :: Preference , timeofday :: Preference , game :: Preference , region :: Preference , gender :: Preference , brand :: Preference , lifestyle :: Preference , day :: Preference , holiday :: Preference , gear :: Preference } musicGenres :: [String] musicGenres = map ((++) "Genre") [1..20] genRandElemFrom :: [String] -> Int -> String genRandElemFrom xs seed = (!!) xs $ head $ randomRs (0, ln) $ mkStdGen seed where ln = length xs foodCategories :: [String] foodCategories = map ((++) "Category") [1..20] genFoodCategories seed = (!!) foodCategories $ head $ randomRs (0, ln) $ mkStdGen seed where ln = length foodCategories genPreferences :: Int -> Traits -> Preferences genPreferences seed (Traits atn com cnf cth dtm dsp emo fea fms lgc men pat rea) = Preferences { color = ColorPref (genColor $ rn !! 0) ap , music = MusicPref (genRandElemFrom musicGenres seed) ap , food = rn !! 0 , season = rn !! 0 , timeofday = rn !! 0 , game = rn !! 0 , region = rn !! 0 , gender = rn !! 0 , brand = rn !! 0 , lifestyle = rn !! 0 , day = rn !! 0 , holiday = rn !! 0 , gear = rn !! 0 } where rn = take 13 . randomRs (1, 99) $ mkStdGen seed ap = toAppreciation $ rn !! 1
lboklin/CharacterGenerator
src/Preferences.hs
lgpl-3.0
3,263
0
11
996
982
565
417
123
1
import Data.List replace :: String -> String -> String -> String replace _ _ [] = [] replace patA patB str@(s:sx) = if isPrefixOf patA str then replace patA patB (patB ++ (drop (length patA) str)) else s:(replace patA patB sx) ans :: [String] -> [String] ans inputs = map (replace "Hoshino" "Hoshina") inputs main = do c <- getContents let i = drop 1 $ lines c o = ans i mapM_ putStrLn o
a143753/AOJ
0101.hs
apache-2.0
411
0
12
98
199
100
99
15
2
{-# LANGUAGE OverloadedStrings #-} {- | Module : Glider.NLP.IndexTest Copyright : Copyright (C) 2013-2016 Krzysztof Langner License : BSD3 Maintainer : Krzysztof Langner <klangner@gmail.com> Stability : alpha Portability : portable -} module Glider.NLP.StatisticsSpec (spec) where import Test.Hspec import Glider.NLP.Statistics spec :: Spec spec = do describe "countWords" $ do it "text tokens" $ countWords "one two three" `shouldBe` 3 describe "wordFreq" $ do it "single word" $ wordFreq "one" `shouldBe` [("one", 1)] it "2 words frequency" $ wordFreq "one two" `shouldBe` [("one", 1), ("two", 1)] it "Multi words frequency" $ wordFreq "one two one" `shouldBe` [("one", 2), ("two", 1)]
klangner/glider-nlp
test-src/Glider/NLP/StatisticsSpec.hs
bsd-2-clause
715
0
12
126
176
97
79
12
1
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -Wall #-} ---------------------------------------------------------------------- -- | -- Module : ShapedTypes.Sized -- Copyright : (c) 2016 Conal Elliott -- License : BSD3 -- -- Maintainer : conal@conal.net -- Stability : experimental -- -- Statically sized functors ---------------------------------------------------------------------- -- TODO: Reconsider whether I can use 'length' from 'Foldable' rather than the -- Sized type class. Can 'Foldable.length' operate efficiently on our data types -- (without traversing)? module ShapedTypes.Sized (Sized(..),genericSize,sizeAF) where -- TODO: explicit exports import GHC.Generics class Sized (f :: * -> *) where size :: Int dummySized :: () dummySized = () -- TODO: Switch from f () to f Void or Proxy -- | Generic 'size' genericSize :: forall f. Sized (Rep1 f) => Int genericSize = size @(Rep1 f) {-# INLINABLE genericSize #-} -- | Default for 'size' on an applicative foldable. -- Warning: runs in linear time (though possibly at compile time). sizeAF :: forall f. (Applicative f, Foldable f) => Int sizeAF = sum (pure 1 :: f Int) {-------------------------------------------------------------------- Generics --------------------------------------------------------------------} instance Sized U1 where size = 0 {-# INLINABLE size #-} instance Sized Par1 where size = 1 {-# INLINABLE size #-} instance Sized (K1 i c) where size = 0 {-# INLINABLE size #-} instance Sized f => Sized (M1 i c f) where size = size @f {-# INLINABLE size #-} instance (Sized g, Sized f) => Sized (g :.: f) where size = size @g * size @f {-# INLINABLE size #-} instance (Sized f, Sized g) => Sized (f :*: g) where size = size @f + size @g {-# INLINABLE size #-}
conal/shaped-types
src/ShapedTypes/Sized.hs
bsd-3-clause
2,038
0
9
395
363
209
154
30
1
{-# LANGUAGE PackageImports #-} module Control.Category (module M) where import "base" Control.Category as M
silkapp/base-noprelude
src/Control/Category.hs
bsd-3-clause
114
0
4
18
21
15
6
3
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Description: Represent and operate on retcond documents. -- -- A 'Document' is, essentially, a JSON 'Value' together with some metadata -- describing its type, system of origin, etc. module Retcon.Document ( Document(..), documentEntity, documentSource, documentContent, emptyDocument, calculateInitialDocument, ) where import Control.Lens import Control.Monad import Data.Aeson import Data.List import Data.Monoid import Retcon.Identifier -- | A JSON 'Value' from a particular 'Entity'. data Document = Document { _documentEntity :: EntityName -- ^ Type of data. , _documentSource :: SourceName -- ^ System of origin. , _documentContent :: Value -- ^ Document content. } deriving (Eq, Show) makeLenses ''Document instance ToJSON Document where toJSON = _documentContent instance FromJSON Document where parseJSON x = return $ Document "" "" x instance Synchronisable Document where getEntityName = _documentEntity getSourceName = _documentSource -------------------------------------------------------------------------------- -- | Construct an empty 'Document'. emptyDocument :: EntityName -> SourceName -> Document emptyDocument e s = Document e s Null -- | Construct an initial 'Document' for use in identifying and processing -- changes. -- -- Reports an error when some or all documents have conflicting entities or -- sources. calculateInitialDocument :: [Document] -> Either String Document calculateInitialDocument docs = do entity <- determineEntity docs checkSources docs case docs of [] -> bail "No documents provided." [d] -> Right $ d & documentEntity .~ entity & documentSource .~ "<initial>" _ -> bail "Too many documents provided." where bail m = Left $ "Cannot calculate initial document: " <> m determineEntity ds = case nub . fmap (view documentEntity) $ ds of [] -> bail "No documents" [e] -> Right e l -> bail $ "Types do not match (" <> show l <> ")" -- Check that the documents all come from different sources checkSources ds = let all_sources = fmap (view documentSource) ds uniq_sources = group . sort $ all_sources in when (any (\x -> length x > 1) uniq_sources) $ bail "Multiple documents from same data source."
anchor/retcon
lib/Retcon/Document.hs
bsd-3-clause
2,514
0
16
627
477
255
222
54
5
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Recur2 where -- Automate the mutual recursion seen in 'Recur' module import Control.Lens import Control.Lens.TH import Data.Data import Data.Data.Lens import qualified Data.Text as T import Data.Typeable (Typeable) import GHC.Generics (Generic) {- -- got rid of polykinds {-# LANGUAGE PolyKinds #-} -- tie the knot newtype Mu (f :: * -> *) = Mu { _unMu :: (f (Mu f)) } -- recur on first argument newtype MuL (f :: * -> k -> *) (a :: k) = MuL { _unMuL :: (f (MuL f a) a) } -- recur on second argument newtype MuR (f :: k -> * -> *) (a :: k) = MuR { _unMuR :: (f a (MuR f a)) } -- "choice" for both arguments newtype Ch (f :: * -> *) (g :: * -> *) (b :: *) (a :: *) = Ch { _unCh :: (Either (f a) (g b)) } deriving (Eq, Ord, Show, Data, Typeable, Generic) -} -- tie the knot newtype Mu (f :: * -> *) = Mu { _unMu :: (f (Mu f)) } -- recur on first argument newtype MuL (f :: * -> * -> *) (a :: *) = MuL { _unMuL :: (f (MuL f a) a) } -- recur on second argument newtype MuR (f :: * -> * -> *) (a :: *) = MuR { _unMuR :: (f a (MuR f a)) } -- "choice" for both arguments newtype Ch (f :: * -> *) (g :: * -> *) (b :: *) (a :: *) = Ch { _unCh :: (Either (f a) (g b)) } deriving (Eq, Ord, Show, Data, Typeable, Generic) makeLenses ''Mu makeLenses ''MuL makeLenses ''MuR makeLenses ''Ch -- TODO: what about free monads? data UT1 a = Id T.Text | Lam T.Text a | App a a deriving (Eq, Ord, Show, Functor, Data, Typeable, Generic) data CL1 a = Id2 T.Text | Lam2 T.Text a | App2 a a deriving (Eq, Ord, Show, Functor, Data, Typeable, Generic) makePrisms ''UT1 makePrisms ''CL1 -- CoRecur a b ~~ Either (a (CoRecur a b)) (b (CoRecur a b)) type CoRecur a b = Mu (MuL (Ch a b)) type U = CoRecur UT1 CL1 test2 :: U test2 = (Mu (MuL (Ch (Left (Lam "x" (Mu (MuL (Ch (Right (Id2 "hi")))))))))) test4 :: U test4 = (Mu (MuL (Ch (Left (Lam "y" (Mu (MuL (Ch (Right (Id2 "hi")))))))))) type UT = Mu UT1 deriving instance Eq (f (Mu f)) => Eq (Mu f) deriving instance Ord (f (Mu f)) => Ord (Mu f) deriving instance Show (f (Mu f)) => Show (Mu f) deriving instance Typeable (f (Mu f)) => Typeable (Mu f) deriving instance Generic (f (Mu f)) => Generic (Mu f) deriving instance (Typeable f, Data (f (Mu f))) => Data (Mu f) deriving instance Eq (f (MuL f a) a) => Eq (MuL f a) deriving instance Ord (f (MuL f a) a) => Ord (MuL f a) deriving instance Show (f (MuL f a) a) => Show (MuL f a) deriving instance Typeable (f (MuL f a) a) => Typeable (MuL f a) deriving instance Generic (f (MuL f a) a) => Generic (MuL f a) -- Deriving this instance is what required making MuL not poly-kinded deriving instance (Typeable MuL, Typeable f, Typeable a, Data (f (MuL f a) a)) => Data (MuL f a) -- Doing biplate-style transformations with these datastructures is not as -- ergonomic as we would like, because there are so many leading newtype -- constructors. trans1 :: U -> U trans1 u = u & temp %~ (\case { (Mu (MuL (Ch (Left (Lam x (Mu z)))))) -> (Mu (MuL (Ch (Right (Lam2 x z))))); x -> x }) where temp :: Traversal' U U temp = template -- We can, of course, peel back these constructors by unrolling the recursive -- definition. But this ic actually quite hard to do by hand trans2 :: U -> U trans2 u = u & temp %~ (\case { (Left (Lam x (Mu z))) -> (Right (Lam2 x z)); x -> x }) where temp :: Traversal' U (Either (UT1 (Mu (MuL (Ch UT1 CL1)))) (CL1 (MuL (Ch UT1 CL1) (Mu (MuL (Ch UT1 CL1)))))) temp = template -- Instead, we can define type families to apply the "unroll" portion of the -- isomorphism for us. These just follow the definition of the newtypes type family Unroll a where Unroll (Mu f) = f (Mu f) Unroll (f a) = f (Unroll a) type family Unroll2 a where Unroll2 (MuL f a) = f (MuL f a) a Unroll2 (f a b) = f (Unroll2 a) (Unroll b) type family UnrollCh a where UnrollCh (Ch f g b a) = Either (f a) (g b) -- Sanity check: These unrolling operations follow their corresponding lenses unroll3 :: Lens' U (UnrollCh (Unroll2 (Unroll U))) unroll3 = unMu.unMuL.unCh -- We can now define 'trans' in a more natural way. Filling in the other -- variants as well. Though we still have this awkwardness of recurring more -- on the left. trans :: U -> U trans u = u & temp %~ \case Left (Lam x (Mu z)) -> Right (Lam2 x z) Left (App (Mu x) (Mu z)) -> Right (App2 x z) Left (Id x) -> Right (Id2 x) x -> x where temp :: Traversal' U (UnrollCh (Unroll2 (Unroll U))) temp = template
ezrosent/s-explore
src/Recur3.hs
bsd-3-clause
5,322
0
24
1,564
1,807
957
850
81
4
{-# LANGUAGE CPP #-} -- ----------------------------------------------------------------------------- -- -- Main.hs, part of Alex -- -- (c) Chris Dornan 1995-2000, Simon Marlow 2003 -- -- ----------------------------------------------------------------------------} module Main (main) where import AbsSyn import CharSet import DFA import DFAMin import NFA import Info import Map ( Map ) import qualified Map hiding ( Map ) import Output import ParseMonad ( runP ) import Parser import Scan import Util ( hline ) import Paths_alex ( version, getDataDir ) #if __GLASGOW_HASKELL__ < 610 import Control.Exception as Exception ( block, unblock, catch, throw ) #endif #if __GLASGOW_HASKELL__ >= 610 import Control.Exception ( bracketOnError ) #endif import Control.Monad ( when, liftM ) import Data.Char ( chr ) import Data.List ( isSuffixOf ) import Data.Maybe ( isJust, fromJust ) import Data.Version ( showVersion ) import System.Console.GetOpt ( getOpt, usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..) ) import System.Directory ( removeFile ) import System.Environment ( getProgName, getArgs ) import System.Exit ( ExitCode(..), exitWith ) import System.IO ( stderr, Handle, IOMode(..), openFile, hClose, hPutStr, hPutStrLn ) #if __GLASGOW_HASKELL__ >= 612 import System.IO ( hGetContents, hSetEncoding, utf8 ) #endif -- We need to force every file we open to be read in -- as UTF8 alexReadFile :: FilePath -> IO String #if __GLASGOW_HASKELL__ >= 612 alexReadFile file = do h <- alexOpenFile file ReadMode hGetContents h #else alexReadFile = readFile #endif -- We need to force every file we write to be written -- to as UTF8 alexOpenFile :: FilePath -> IOMode -> IO Handle #if __GLASGOW_HASKELL__ >= 612 alexOpenFile file mode = do h <- openFile file mode hSetEncoding h utf8 return h #else alexOpenFile = openFile #endif -- `main' decodes the command line arguments and calls `alex'. main:: IO () main = do args <- getArgs case getOpt Permute argInfo args of (cli,_,[]) | DumpHelp `elem` cli -> do prog <- getProgramName bye (usageInfo (usageHeader prog) argInfo) (cli,_,[]) | DumpVersion `elem` cli -> bye copyright (cli,[file],[]) -> runAlex cli file (_,_,errors) -> do prog <- getProgramName die (concat errors ++ usageInfo (usageHeader prog) argInfo) projectVersion :: String projectVersion = showVersion version copyright :: String copyright = "Alex version " ++ projectVersion ++ ", (c) 2003 Chris Dornan and Simon Marlow\n" usageHeader :: String -> String usageHeader prog = "Usage: " ++ prog ++ " [OPTION...] file\n" runAlex :: [CLIFlags] -> FilePath -> IO () runAlex cli file = do basename <- case (reverse file) of 'x':'.':r -> return (reverse r) _ -> die (file ++ ": filename must end in \'.x\'\n") prg <- alexReadFile file script <- parseScript file prg alex cli file basename script parseScript :: FilePath -> String -> IO (Maybe (AlexPosn,Code), [Directive], Scanner, Maybe (AlexPosn,Code)) parseScript file prg = case runP prg initialParserEnv parse of Left (Just (AlexPn _ line col),err) -> die (file ++ ":" ++ show line ++ ":" ++ show col ++ ": " ++ err ++ "\n") Left (Nothing, err) -> die (file ++ ": " ++ err ++ "\n") Right script -> return script alex :: [CLIFlags] -> FilePath -> FilePath -> (Maybe (AlexPosn, Code), [Directive], Scanner, Maybe (AlexPosn, Code)) -> IO () alex cli file basename script = do (put_info, finish_info) <- case [ f | OptInfoFile f <- cli ] of [] -> return (\_ -> return (), return ()) [Nothing] -> infoStart file (basename ++ ".info") [Just f] -> infoStart file f _ -> dieAlex "multiple -i/--info options" o_file <- case [ f | OptOutputFile f <- cli ] of [] -> return (basename ++ ".hs") [f] -> return f _ -> dieAlex "multiple -o/--outfile options" tab_size <- case [ s | OptTabSize s <- cli ] of [] -> return 8 [s] -> case reads s of [(n,"")] -> return n _ -> dieAlex "-s/--tab-size option is not a valid integer" _ -> dieAlex "multiple -s/--tab-size options" let target | OptGhcTarget `elem` cli = GhcTarget | otherwise = HaskellTarget let encoding | OptLatin1 `elem` cli = Latin1 | otherwise = UTF8 template_dir <- templateDir getDataDir cli -- open the output file; remove it if we encounter an error bracketOnError (alexOpenFile o_file WriteMode) (\h -> do hClose h; removeFile o_file) $ \out_h -> do let (maybe_header, directives, scanner1, maybe_footer) = script (scanner2, scs, sc_hdr) = encodeStartCodes scanner1 (scanner_final, actions) = extractActions scanner2 wrapper_name <- wrapperFile template_dir directives hPutStr out_h (optsToInject target cli) injectCode maybe_header file out_h hPutStr out_h (importsToInject target cli) -- add the wrapper, if necessary when (isJust wrapper_name) $ do str <- alexReadFile (fromJust wrapper_name) hPutStr out_h str -- Inject the tab size hPutStrLn out_h $ "alex_tab_size :: Int" hPutStrLn out_h $ "alex_tab_size = " ++ show tab_size let dfa = scanner2dfa encoding scanner_final scs min_dfa = minimizeDFA dfa nm = scannerName scanner_final usespreds = usesPreds min_dfa put_info "\nStart codes\n" put_info (show $ scs) put_info "\nScanner\n" put_info (show $ scanner_final) put_info "\nNFA\n" put_info (show $ scanner2nfa encoding scanner_final scs) put_info "\nDFA" put_info (infoDFA 1 nm dfa "") put_info "\nMinimized DFA" put_info (infoDFA 1 nm min_dfa "") hPutStr out_h (outputDFA target 1 nm min_dfa "") injectCode maybe_footer file out_h hPutStr out_h (sc_hdr "") hPutStr out_h (actions "") -- add the template let template_name = templateFile template_dir target usespreds cli tmplt <- alexReadFile template_name hPutStr out_h tmplt hClose out_h finish_info -- inject some code, and add a {-# LINE #-} pragma at the top injectCode :: Maybe (AlexPosn,Code) -> FilePath -> Handle -> IO () injectCode Nothing _ _ = return () injectCode (Just (AlexPn _ ln _,code)) filename hdl = do hPutStrLn hdl ("{-# LINE " ++ show ln ++ " \"" ++ filename ++ "\" #-}") hPutStrLn hdl code optsToInject :: Target -> [CLIFlags] -> String optsToInject GhcTarget _ = optNoWarnings ++ "{-# LANGUAGE CPP,MagicHash #-}\n" optsToInject _ _ = optNoWarnings ++ "{-# LANGUAGE CPP #-}\n" optNoWarnings :: String optNoWarnings = "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-missing-signatures #-}\n" importsToInject :: Target -> [CLIFlags] -> String importsToInject _ cli = always_imports ++ debug_imports ++ glaexts_import where glaexts_import | OptGhcTarget `elem` cli = import_glaexts | otherwise = "" debug_imports | OptDebugParser `elem` cli = import_debug | otherwise = "" -- CPP is turned on for -fglasogw-exts, so we can use conditional -- compilation. We need to #include "config.h" to get hold of -- WORDS_BIGENDIAN (see GenericTemplate.hs). always_imports :: String always_imports = "#if __GLASGOW_HASKELL__ >= 603\n" ++ "#include \"ghcconfig.h\"\n" ++ "#elif defined(__GLASGOW_HASKELL__)\n" ++ "#include \"config.h\"\n" ++ "#endif\n" ++ "#if __GLASGOW_HASKELL__ >= 503\n" ++ "import Data.Array\n" ++ "import Data.Array.Base (unsafeAt)\n" ++ "#else\n" ++ "import Array\n" ++ "#endif\n" import_glaexts :: String import_glaexts = "#if __GLASGOW_HASKELL__ >= 503\n" ++ "import GHC.Exts\n" ++ "#else\n" ++ "import GlaExts\n" ++ "#endif\n" import_debug :: String import_debug = "#if __GLASGOW_HASKELL__ >= 503\n" ++ "import System.IO\n" ++ "import System.IO.Unsafe\n" ++ "import Debug.Trace\n" ++ "#else\n" ++ "import IO\n" ++ "import IOExts\n" ++ "#endif\n" templateDir :: IO FilePath -> [CLIFlags] -> IO FilePath templateDir def cli = case [ d | OptTemplateDir d <- cli ] of [] -> def ds -> return (last ds) templateFile :: FilePath -> Target -> UsesPreds -> [CLIFlags] -> FilePath templateFile dir target usespreds cli = dir ++ "/AlexTemplate" ++ maybe_ghc ++ maybe_debug ++ maybe_nopred where maybe_ghc = case target of GhcTarget -> "-ghc" _ -> "" maybe_debug | OptDebugParser `elem` cli = "-debug" | otherwise = "" maybe_nopred = case usespreds of DoesntUsePreds | not (null maybe_ghc) && null maybe_debug -> "-nopred" _ -> "" wrapperFile :: FilePath -> [Directive] -> IO (Maybe FilePath) wrapperFile dir directives = case [ f | WrapperDirective f <- directives ] of [] -> return Nothing [f] -> return (Just (dir ++ "/AlexWrapper-" ++ f)) _many -> dieAlex "multiple %wrapper directives" infoStart :: FilePath -> FilePath -> IO (String -> IO (), IO ()) infoStart x_file info_file = do bracketOnError (alexOpenFile info_file WriteMode) (\h -> do hClose h; removeFile info_file) (\h -> do infoHeader h x_file return (hPutStr h, hClose h) ) infoHeader :: Handle -> FilePath -> IO () infoHeader h file = do -- hSetBuffering h NoBuffering hPutStrLn h ("Info file produced by Alex version " ++ projectVersion ++ ", from " ++ file) hPutStrLn h hline hPutStr h "\n" initialParserEnv :: (Map String CharSet, Map String RExp) initialParserEnv = (initSetEnv, initREEnv) initSetEnv :: Map String CharSet initSetEnv = Map.fromList [("white", charSet " \t\n\v\f\r"), ("printable", charSetRange (chr 32) (chr 0x10FFFF)), -- FIXME: Look it up the unicode standard (".", charSetComplement emptyCharSet `charSetMinus` charSetSingleton '\n')] initREEnv :: Map String RExp initREEnv = Map.empty -- ----------------------------------------------------------------------------- -- Command-line flags data CLIFlags = OptDebugParser | OptGhcTarget | OptOutputFile FilePath | OptInfoFile (Maybe FilePath) | OptTabSize String | OptTemplateDir FilePath | OptLatin1 | DumpHelp | DumpVersion deriving Eq argInfo :: [OptDescr CLIFlags] argInfo = [ Option ['o'] ["outfile"] (ReqArg OptOutputFile "FILE") "write the output to FILE (default: file.hs)", Option ['i'] ["info"] (OptArg OptInfoFile "FILE") "put detailed state-machine info in FILE (or file.info)", Option ['t'] ["template"] (ReqArg OptTemplateDir "DIR") "look in DIR for template files", Option ['g'] ["ghc"] (NoArg OptGhcTarget) "use GHC extensions", Option ['l'] ["latin1"] (NoArg OptLatin1) "generated lexer will use the Latin-1 encoding instead of UTF-8", Option ['s'] ["tab-size"] (ReqArg OptTabSize "NUMBER") "set tab size to be used in the generated lexer (default: 8)", Option ['d'] ["debug"] (NoArg OptDebugParser) "produce a debugging scanner", Option ['?'] ["help"] (NoArg DumpHelp) "display this help and exit", Option ['V','v'] ["version"] (NoArg DumpVersion) -- ToDo: -v is deprecated! "output version information and exit" ] -- ----------------------------------------------------------------------------- -- Utils getProgramName :: IO String getProgramName = liftM (`withoutSuffix` ".bin") getProgName where str `withoutSuffix` suff | suff `isSuffixOf` str = take (length str - length suff) str | otherwise = str bye :: String -> IO a bye s = putStr s >> exitWith ExitSuccess die :: String -> IO a die s = hPutStr stderr s >> exitWith (ExitFailure 1) dieAlex :: String -> IO a dieAlex s = getProgramName >>= \prog -> die (prog ++ ": " ++ s) #if __GLASGOW_HASKELL__ < 610 bracketOnError :: IO a -- ^ computation to run first (\"acquire resource\") -> (a -> IO b) -- ^ computation to run last (\"release resource\") -> (a -> IO c) -- ^ computation to run in-between -> IO c -- returns the value from the in-between computation bracketOnError before after thing = block (do a <- before r <- Exception.catch (unblock (thing a)) (\e -> do { after a; throw e }) return r ) #endif
Teino1978-Corp/Teino1978-Corp-alex
src/Main.hs
bsd-3-clause
13,162
0
17
3,645
3,485
1,793
1,692
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Main where import Data.Maybe (fromMaybe) import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as TIO import Text.Megaparsec import Text.Megaparsec.Text import System.Environment (getArgs) iCalP :: Parser [Text] iCalP = section "VCALENDAR" $ do string "VERSION:" >> manyTill anyChar crlf string "METHOD:" >> manyTill anyChar crlf string "PRODID:" >> manyTill anyChar crlf crlf -- skip the timezone info section "VTIMEZONE" (manyTill anyChar $ lookAhead (string "END:VTIMEZONE")) crlf (map renderEvent) <$> sepEndBy (section "VEVENT" eventP) crlf data Event = Event { eventSummary :: Text , eventStart :: Text , eventLocation :: Text } renderEvent :: Event -> Text renderEvent Event{..} = "* " <> eventStart <> " " <> eventSummary <> ", " <> eventLocation eventP :: Parser Event eventP = do ignoreLine -- UID summary <- keyValueP "SUMMARY" dtstart <- timeValueP "DTSTART" ignoreLine -- DTEND ignoreLine -- SEQUENCE ignoreLine -- X-MOZ-GENERATION ignoreLine -- DTSTAMP location <- keyValueP "LOCATION" ignoreLine -- CATEGORIES ignoreLine -- DESCRIPTION ignoreLine -- CLASS pure $ Event summary dtstart location ignoreLine :: Parser () ignoreLine = manyTill anyChar (lookAhead crlf) >> crlf >> pure () keyValueP :: String -> Parser Text keyValueP needed = do string needed char ':' T.pack <$> manyTill anyChar crlf timeValueP :: String -> Parser Text timeValueP needed = do string needed char ';' manyTill anyChar (char ':') year <- count 4 digitChar month <- count 2 digitChar day <- count 2 digitChar char 'T' hours <- count 2 digitChar minutes<- count 2 digitChar _ <- count 2 digitChar -- seconds crlf pure . T.pack $ "T[" <> year <> "-" <> month <> "-" <> day <> ":" <> hours <> ":" <> minutes <> "]" section :: String -> Parser a -> Parser a section sectionName inner = do string "BEGIN:" string sectionName crlf res <- inner string "END:" string sectionName crlf pure res parseICal :: Text -> IO () parseICal input = case parse iCalP "" input of Right res -> mapM_ TIO.putStrLn res Left err -> print err main :: IO () main = do args <- getArgs case args of [] -> putStrLn "needs argument." (fName:_) -> TIO.readFile fName >>= parseICal
ibabushkin/morgue
app/ICalImport.hs
bsd-3-clause
2,511
0
19
610
817
389
428
83
2
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} module Data.Strict.Drive where import Lib infixl 1 >>~, >~> class (Functor f, Functor g) => Absorb f g where (>>~) :: f a -> (a -> g b) -> g b a >>~ f = abjoin $ fmap f a {-# INLINE (>>~) #-} abjoin :: f (g a) -> g a abjoin a = a >>~ id {-# INLINE abjoin #-} (>~>) :: Absorb f m => (a -> f b) -> (b -> m c) -> a -> m c f >~> g = \x -> f x >>~ g {-# INLINE (>~>) #-} data Drive a = Stop !a | More !a drive :: (a -> b) -> (a -> b) -> Drive a -> b drive f g (Stop x) = f x drive f g (More x) = g x {-# INLINABLE drive #-} runDrive :: Drive a -> a runDrive = drive id id {-# INLINEABLE runDrive #-} isStop :: Drive a -> Bool isStop = drive (const True) (const False) {-# INLINABLE isStop #-} isMore :: Drive a -> Bool isMore = drive (const False) (const True) {-# INLINABLE isMore #-} driveToEither :: Drive a -> Either a a driveToEither = drive Left Right {-# INLINABLE driveToEither #-} instance Functor Drive where fmap f = drive (Stop . f) (More . f) {-# INLINEABLE fmap #-} instance SumApplicative Drive where spure = Stop {-# INLINEABLE spure #-} Stop f <+> Stop x = Stop $ f x f <+> x = More $ runDrive f (runDrive x) {-# INLINEABLE (<+>) #-} instance AndApplicative Drive where apure = More {-# INLINEABLE apure #-} More f <&> More x = More $ f x f <&> x = Stop $ runDrive f (runDrive x) {-# INLINEABLE (<&>) #-} instance Foldable Drive where foldMap = foldMapDefault {-# INLINEABLE foldMap #-} instance Traversable Drive where traverse f = drive (Stop <.> f) (More <.> f) {-# INLINEABLE traverse #-} instance MonoMonad Drive where mpure = apure {-# INLINABLE mpure #-} a >># f = drive Stop f a {-# INLINABLE (>>#) #-} instance Comonad Drive where extract = runDrive {-# INLINEABLE extract #-} extend f = drive (Stop . f . Stop) (More . f . More) {-# INLINEABLE extend #-} -- Is there a type class for this? sequenceBi :: Bifunctor f => Drive (f a b) -> f (Drive a) (Drive b) sequenceBi = drive (bimap Stop Stop) (bimap More More) {-# INLINABLE sequenceBi #-} newtype DriveT m a = DriveT { getDriveT :: m (Drive a) } driveToDriveT :: Applicative f => Drive a -> DriveT f a driveToDriveT = DriveT . pure {-# INLINEABLE driveToDriveT #-} driveT :: Functor f => (a -> b) -> (a -> b) -> DriveT f a -> f b driveT g f (DriveT a) = drive g f <$> a {-# INLINEABLE driveT #-} driveTM :: Monad m => (a -> m b) -> (a -> m b) -> DriveT m a -> m b driveTM g f (DriveT a) = a >>= drive g f {-# INLINEABLE driveTM #-} runDriveT :: Functor f => DriveT f a -> f a runDriveT (DriveT a) = runDrive <$> a {-# INLINEABLE runDriveT #-} driveDriveT :: Monad m => (a -> DriveT m b) -> (a -> DriveT m b) -> DriveT m a -> DriveT m b driveDriveT f g (DriveT a) = a >>~ drive f g {-# INLINABLE driveDriveT #-} isStopT :: Functor f => DriveT f a -> f Bool isStopT (DriveT a) = isStop <$> a {-# INLINABLE isStopT #-} isMoreT :: Functor f => DriveT f a -> f Bool isMoreT (DriveT a) = isMore <$> a {-# INLINABLE isMoreT #-} driveToExceptT :: Monad m => DriveT m a -> ExceptT a m a driveToExceptT (DriveT a) = ExceptT $ driveToEither <$> a {-# INLINABLE driveToExceptT #-} -- A few slightly asymmetric synonyms to make things readable. halt :: SumApplicative f => a -> f a halt = spure {-# INLINEABLE halt #-} more :: MonoMonad m => a -> m a more = mpure {-# INLINEABLE more #-} haltWhen :: (SumApplicative m, MonoMonad m) => (a -> Bool) -> a -> m a haltWhen p x = if p x then halt x else more x {-# INLINEABLE haltWhen #-} moreWhen :: (SumApplicative m, MonoMonad m) => (a -> Bool) -> a -> m a moreWhen p x = if p x then more x else halt x {-# INLINEABLE moreWhen #-} stop :: (SumApplicativeTrans t, Monad m) => m a -> t m a stop = slift {-# INLINEABLE stop #-} keep :: (AndApplicativeTrans t, Monad m) => m a -> t m a keep = alift {-# INLINEABLE keep #-} terminate :: (SumApplicative m, MonoMonad m) => m a -> m a terminate a = a >># halt {-# INLINEABLE terminate #-} terminateWhen :: (SumApplicative m, MonoMonad m) => (a -> Bool) -> m a -> m a terminateWhen p a = a >># \x -> if p x then halt x else more x {-# INLINEABLE terminateWhen #-} instance Functor f => Functor (DriveT f) where fmap f (DriveT a) = DriveT $ fmap (fmap f) a {-# INLINEABLE fmap #-} instance Applicative f => SumApplicative (DriveT f) where spure = DriveT . pure . Stop {-# INLINEABLE spure #-} DriveT h <+> DriveT a = DriveT $ (<+>) <$> h <*> a {-# INLINEABLE (<+>) #-} instance Applicative f => AndApplicative (DriveT f) where apure = DriveT . pure . More {-# INLINEABLE apure #-} DriveT h <&> DriveT a = DriveT $ (<&>) <$> h <*> a {-# INLINEABLE (<&>) #-} instance Foldable m => Foldable (DriveT m) where foldMap f (DriveT a) = foldMap (f . runDrive) a {-# INLINEABLE foldMap #-} instance Traversable m => Traversable (DriveT m) where traverse f (DriveT a) = fmap DriveT $ traverse (traverse f) a {-# INLINEABLE traverse #-} instance Monad m => MonoMonad (DriveT m) where mpure = apure {-# INLINABLE mpure #-} a >># f = driveDriveT halt f a {-# INLINABLE (>>#) #-} instance Monad m => Comonad (DriveT m) where extract = error "there is no `extract` for `DriveT m` unless `m` is a comonad, \ \ but this is not needed for `extend`, which is more important than `extract`" extend f = driveDriveT (halt . f . halt) (more . f . more) {-# INLINABLE extend #-} instance SumApplicativeTrans DriveT where slift a = DriveT $ Stop <$> a {-# INLINEABLE slift #-} instance AndApplicativeTrans DriveT where alift a = DriveT $ More <$> a {-# INLINEABLE alift #-} instance MFunctor DriveT where hoist h (DriveT a) = DriveT $ h a {-# INLINEABLE hoist #-} instance TransTraversable DriveT (ReaderT r) where sequenceT (DriveT (ReaderT f)) = ReaderT $ DriveT . f {-# INLINEABLE sequenceT #-} runDriveReaderT :: Monad m => r -> DriveT (ReaderT r m) a -> DriveT m a runDriveReaderT r = flip runReaderT r . sequenceT {-# INLINEABLE runDriveReaderT #-} instance TransTraversable DriveT (StateT s) where sequenceT (DriveT (StateT f)) = StateT $ DriveT . uncurry tupr <.> f {-# INLINEABLE sequenceT #-} runDriveStateT :: Monad m => s -> DriveT (StateT s m) a -> DriveT m (a, s) runDriveStateT s = flip runStateT s . sequenceT {-# INLINEABLE runDriveStateT #-} instance TransTraversable DriveT (ExceptT e) where sequenceT (DriveT (ExceptT s)) = ExceptT . DriveT $ either (Stop . Left) (fmap Right) <$> s {-# INLINEABLE sequenceT #-} runDriveExceptT :: Monad m => DriveT (ExceptT e m) a -> DriveT m (Either e a) runDriveExceptT = runExceptT . sequenceT {-# INLINEABLE runDriveExceptT #-} instance Monad m => Absorb (DriveT m) m where a >>~ f = runDriveT a >>= f {-# INLINEABLE (>>~) #-} instance Monad m => Absorb m (DriveT m) where a >>~ f = DriveT $ a >>= getDriveT . f {-# INLINEABLE (>>~) #-}
effectfully/prefolds
src/Data/Strict/Drive.hs
bsd-3-clause
6,921
0
11
1,567
2,559
1,294
1,265
-1
-1
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE ForeignFunctionInterface #-} -- | -- Module : Crypto.MAC.Siphash48 -- Copyright : (c) Austin Seipp 2013 -- License : BSD3 -- -- Maintainer : aseipp@pobox.com -- Stability : experimental -- Portability : portable -- -- This module provides @siphash48@ as a message-authentication code -- (MAC.) The underlying implementation is the @little@ code of -- @siphash48@ from SUPERCOP, and should be relatively fast. -- -- For more information visit <https://131002.net/siphash/>. -- -- This module is intended to be imported @qualified@ to avoid name -- clashes with other cryptographic primitives, e.g. -- -- > import qualified Crypto.MAC.Siphash48 as Siphash48 -- module Crypto.MAC.Siphash48 ( -- * Security model -- $securitymodel -- * Types Siphash48 -- :: * , Auth(..) -- :: * -- * Key creation , randomKey -- :: IO (SecretKey Siphash48) -- * Authentication -- ** Example usage -- $example , authenticate -- :: SecretKey Siphash48 -> ByteString -> Auth , verify -- :: SecretKey Siphash48 -> Auth -> ByteString -> Bool ) where import Data.Word import Foreign.C.Types import Foreign.Ptr import System.IO.Unsafe (unsafePerformIO) import Data.ByteString (ByteString) import Data.ByteString.Internal (create) import Data.ByteString.Unsafe import Crypto.Key import System.Crypto.Random -- $securitymodel -- -- The @'authenticate'@ function, viewed as a function of the message -- for a uniform random key, is designed to meet the standard notion -- of unforgeability. This means that an attacker cannot find -- authenticators for any messages not authenticated by the sender, -- even if the attacker has adaptively influenced the messages -- authenticated by the sender. For a formal definition see, e.g., -- Section 2.4 of Bellare, Kilian, and Rogaway, \"The security of the -- cipher block chaining message authentication code,\" Journal of -- Computer and System Sciences 61 (2000), 362–399; -- <http://www-cse.ucsd.edu/~mihir/papers/cbc.html>. -- -- NaCl does not make any promises regarding \"strong\" -- unforgeability; perhaps one valid authenticator can be converted -- into another valid authenticator for the same message. NaCl also -- does not make any promises regarding \"truncated unforgeability.\" -- $example -- >>> key <- randomKey -- >>> let a = authenticate key "Hello" -- >>> verify key a "Hello" -- True -- | A phantom type for representing types related to SipHash-4-8 -- MACs. data Siphash48 -- | Generate a random key for performing encryption. randomKey :: IO (SecretKey Siphash48) randomKey = SecretKey `fmap` randombytes siphashKEYBYTES -- | An authenticator. newtype Auth = Auth { unAuth :: ByteString } deriving (Eq, Show, Ord) -- | @'authenticate' k m@ authenticates a message @'m'@ using a secret -- @'Key'@ @k@ and returns the authenticator, @'Auth'@. authenticate :: SecretKey Siphash48 -- ^ Secret key -> ByteString -- ^ Message -> Auth -- ^ Authenticator authenticate (SecretKey k) msg = Auth . unsafePerformIO . create siphashBYTES $ \out -> unsafeUseAsCStringLen msg $ \(cstr, clen) -> unsafeUseAsCString k $ \pk -> c_crypto_siphash48 out cstr (fromIntegral clen) pk >> return () {-# INLINE authenticate #-} -- | @'verify' k a m@ verifies @a@ is the correct authenticator of @m@ -- under a secret @'Key'@ @k@. verify :: SecretKey Siphash48 -- ^ Secret key -> Auth -- ^ Authenticator returned via 'authenticateOnce' -> ByteString -- ^ Message -> Bool -- ^ Result: @True@ if verified, @False@ otherwise verify (SecretKey k) (Auth auth) msg = unsafePerformIO . unsafeUseAsCString auth $ \pauth -> unsafeUseAsCStringLen msg $ \(cstr, clen) -> unsafeUseAsCString k $ \pk -> do b <- c_crypto_siphash48_verify pauth cstr (fromIntegral clen) pk return (b == 0) {-# INLINE verify #-} -- -- FFI mac binding -- siphashKEYBYTES :: Int siphashKEYBYTES = 16 siphashBYTES :: Int siphashBYTES = 8 foreign import ccall unsafe "siphash48_mac" c_crypto_siphash48 :: Ptr Word8 -> Ptr CChar -> CULLong -> Ptr CChar -> IO Int foreign import ccall unsafe "siphash48_mac_verify" c_crypto_siphash48_verify :: Ptr CChar -> Ptr CChar -> CULLong -> Ptr CChar -> IO Int
thoughtpolice/hs-nacl
src/Crypto/MAC/Siphash48.hs
bsd-3-clause
4,610
0
16
1,122
563
337
226
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Ordinal.NB.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.Ordinal.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale NB Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (OrdinalData 4) [ "4." , "fjerde" , "fJerde" ] , examples (OrdinalData 15) [ "15." , "femtende" ] , examples (OrdinalData 5) [ "5." , "femte" ] ]
facebookincubator/duckling
Duckling/Ordinal/NB/Corpus.hs
bsd-3-clause
881
0
9
253
160
97
63
23
1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} module ParserSpecs (tests ) where import Test.Framework (testGroup, Test) import Test.Framework.Providers.QuickCheck2 (testProperty) import qualified Parser as P import qualified Lexer as L import Arbitrary tests :: Test tests = testGroup "Parser tests" [ testProperty "Tokens in Loop should create the same program" prop_Loop, testProperty "Optimized program shouldn't be longer than source" prop_optimizedProgramShouldBeShorterOrEqual, testProperty "Optimize should squash move commands to one" prop_optimizeSquashesMoveCommands, testProperty "Optimize should squash add commands to one" prop_optimizeSquashesAddCommands, testProperty "Optimized loop contains optimized commands" prop_optimizedLoopContainsOptimizedCommands, testProperty "Non closed bracket results in SyntaxError" prop_nonClosedBracketResultsInSyntaxError, testProperty "Not opened bracket results in SyntaxError" prop_notOpenedBracketResultsInSyntaxError ] prop_Loop :: [L.Token] -> Bool prop_Loop input = P.parse input == (fmap extractProgramInLoop . P.parse . wrapInLoop $ input) where createToken x = L.Token { L.tokenType = x, L.position = (L.Position 0 0) } wrapInLoop i = [createToken L.StartLoop] ++ i ++ [createToken L.EndLoop] extractProgramInLoop ((P.Loop p):[]) = p extractProgramInLoop x = x prop_optimizedProgramShouldBeShorterOrEqual :: [P.Command] -> Bool prop_optimizedProgramShouldBeShorterOrEqual cmd = length cmd >= (length optimized) where optimized = P.optimize cmd prop_optimizeSquashesMoveCommands :: [Int] -> Bool prop_optimizeSquashesMoveCommands x = case optimized of [] -> 0 == sum x ((P.Move r):_) -> r == sum x _ -> False where optimized = P.optimize . fmap P.Move $ x prop_optimizeSquashesAddCommands :: [Int] -> Bool prop_optimizeSquashesAddCommands x = case optimized of [] -> 0 == sum x ((P.Add r):_) -> r == sum x _ -> False where optimized = P.optimize . fmap P.Add $ x prop_optimizedLoopContainsOptimizedCommands :: [P.Command] -> Bool prop_optimizedLoopContainsOptimizedCommands cmds = P.optimize cmds == (deLoop . head . P.optimize $ [inLoop cmds]) where inLoop = P.Loop deLoop (P.Loop x) = x deLoop x = [x] prop_nonClosedBracketResultsInSyntaxError :: [L.Token] -> Bool prop_nonClosedBracketResultsInSyntaxError tokens = either matchErrorType (\_ -> False) . P.parse $ withOpenLoop where matchErrorType (P.SyntaxError{P.errorType = et}:[]) = et == P.MissingLoopClose matchErrorType _ = False withOpenLoop = (L.Token L.StartLoop (L.Position 0 0 )):tokens prop_notOpenedBracketResultsInSyntaxError :: [L.Token] -> Bool prop_notOpenedBracketResultsInSyntaxError tokens = either matchErrorType (\_ -> False) . P.parse $ withClosedLoop where matchErrorType (P.SyntaxError{P.errorType = et}:[]) = et == P.MissingLoopOpening matchErrorType _ = False withClosedLoop = (L.Token L.EndLoop (L.Position 0 0)):tokens
batkot/haskell-bf
test/ParserSpecs.hs
bsd-3-clause
3,080
0
12
569
848
447
401
62
3
module TwiceM where {-@ LIQUID "--short-names" @-} import RIO {-@ appM :: forall <pre :: World -> Prop, post :: World -> b -> World -> Prop>. (a -> RIO <pre, post> b) -> a -> RIO <pre, post> b @-} appM :: (a -> RIO b) -> a -> RIO b appM f x = f x {-@ twiceM :: forall < pre :: World -> Prop , post1 :: World -> a -> World -> Prop , post :: World -> a -> World -> Prop>. {w ::World<pre>, x::a|- World<post1 w x> <: World<pre>} {w1::World<pre>, y::a, w2::World<post1 w1 y>, x::a |- World<post1 w2 x> <: World<post w1 x>} (b -> RIO <pre, post1> a) -> b -> RIO <pre, post> a @-} twiceM :: (b -> RIO a) -> b -> RIO a twiceM f w = let (RIO g) = f w in RIO $ \x -> case g x of {(y, s) -> let ff = \_ -> f w in (runState (ff y)) s} {-@ measure counter :: World -> Int @-} {-@ incr :: RIO <{\x -> counter x >= 0}, {\w1 x w2 -> counter w2 = counter w1 + 1}> Nat Nat @-} incr :: RIO Int incr = undefined {-@ incr2 :: RIO <{\x -> counter x >= 0}, {\w1 x w2 -> counter w2 = counter w1 + 2}> Nat Nat @-} incr2 :: RIO Int incr2 = twiceM (\_ -> incr) 0
abakst/liquidhaskell
benchmarks/icfp15/pos/TwiceM.hs
bsd-3-clause
1,146
0
18
352
212
111
101
10
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} -- This program must be called with GHC's libdir as the single command line -- argument. module Main where -- import Data.Generics import Data.Data hiding (Fixity) import Data.List import System.IO import GHC import BasicTypes import DynFlags import FastString import ForeignCall import MonadUtils import Outputable import GHC.Hs.Decls import Bag (filterBag,isEmptyBag) import System.Directory (removeFile) import System.Environment( getArgs ) import qualified Data.Map as Map import Data.Dynamic ( fromDynamic,Dynamic ) main::IO() main = do [libdir,fileName] <- getArgs testOneFile libdir fileName testOneFile libdir fileName = do ((anns,cs),p) <- runGhc (Just libdir) $ do dflags <- getSessionDynFlags setSessionDynFlags dflags let mn =mkModuleName fileName addTarget Target { targetId = TargetModule mn , targetAllowObjCode = True , targetContents = Nothing } load LoadAllTargets modSum <- getModSummary mn p <- parseModule modSum return (pm_annotations p,p) let tupArgs = gq (pm_parsed_source p) putStrLn (intercalate "\n" $ map show tupArgs) -- putStrLn (pp tupArgs) -- putStrLn (intercalate "\n" [showAnns anns]) where gq ast = everything (++) ([] `mkQ` doFixity `extQ` doRuleDecl `extQ` doHsExpr `extQ` doInline ) ast doFixity :: Fixity -> [(String,[String])] doFixity (Fixity (SourceText ss) _ _) = [("f",[ss])] doRuleDecl :: RuleDecl GhcPs -> [(String,[String])] doRuleDecl (HsRule _ _ (ActiveBefore (SourceText ss) _) _ _ _ _) = [("rb",[ss])] doRuleDecl (HsRule _ _ (ActiveAfter (SourceText ss) _) _ _ _ _) = [("ra",[ss])] doRuleDecl (HsRule _ _ _ _ _ _ _) = [] doHsExpr :: HsExpr GhcPs -> [(String,[String])] doHsExpr (HsPragE _ (HsPragTick _ src (_,_,_) ss) _) = [("tp",[show ss])] doHsExpr _ = [] doInline (InlinePragma _ _ _ (ActiveBefore (SourceText ss) _) _) = [("ib",[ss])] doInline (InlinePragma _ _ _ (ActiveAfter (SourceText ss) _) _) = [("ia",[ss])] doInline (InlinePragma _ _ _ _ _ ) = [] showAnns anns = "[\n" ++ (intercalate "\n" $ map (\((s,k),v) -> ("(AK " ++ pp s ++ " " ++ show k ++" = " ++ pp v ++ ")\n")) $ Map.toList anns) ++ "]\n" pp a = showPpr unsafeGlobalDynFlags a -- --------------------------------------------------------------------- -- Copied from syb for the test -- | Generic queries of type \"r\", -- i.e., take any \"a\" and return an \"r\" -- type GenericQ r = forall a. Data a => a -> r -- | Make a generic query; -- start from a type-specific case; -- return a constant otherwise -- mkQ :: ( Typeable a , Typeable b ) => r -> (b -> r) -> a -> r (r `mkQ` br) a = case cast a of Just b -> br b Nothing -> r -- | Extend a generic query by a type-specific case extQ :: ( Typeable a , Typeable b ) => (a -> q) -> (b -> q) -> a -> q extQ f g a = maybe (f a) g (cast a) -- | Summarise all nodes in top-down, left-to-right order everything :: (r -> r -> r) -> GenericQ r -> GenericQ r -- Apply f to x to summarise top-level node; -- use gmapQ to recurse into immediate subterms; -- use ordinary foldl to reduce list of intermediate results everything k f x = foldl k (f x) (gmapQ (everything k f) x)
sdiehl/ghc
testsuite/tests/ghc-api/annotations/t11430.hs
bsd-3-clause
3,875
1
20
1,264
1,168
632
536
85
6
{-# LANGUAGE DeriveGeneric #-} module Data.SourceMap ( SourceMap(..) ) where import Data.Aeson (ToJSON, FromJSON, encode, fromJSON, Result(..)) import GHC.Generics (Generic) import Data.Attoparsec.Lazy (parse, Result(..), many1) import Control.Monad (forM_) import Data.Text (Text) data SourceMap = SourceMap { version :: Int, file :: FilePath, lineCount :: Int, mappings :: Text, sources :: [FilePath], names :: [Text] } deriving (Generic, Eq, Show) instance FromJSON SourceMap instance ToJSON SourceMap
ghcjs/source-map
src/Data/SourceMap.hs
bsd-3-clause
552
0
9
112
173
107
66
17
0
{-# OPTIONS_HADDOCK hide #-} module ForSyDe.Atom.Skel.FastVector.Lib where import ForSyDe.Atom import Data.Maybe import Control.Applicative import Data.List.Split import qualified Data.List as L import Prelude hiding (take, drop, length, zip, unzip) -- | In this library 'Vector' is just a wrapper around a list. newtype Vector a = Vector { fromVector :: [a] } deriving (Eq) vector = Vector instance Functor Vector where fmap f (Vector a) = Vector (fmap f a) instance Applicative Vector where pure a = Vector [a] (Vector fs) <*> (Vector as) = Vector $ getZipList (ZipList fs <*> ZipList as) instance (Show a) => Show (Vector a) where showsPrec p (Vector []) = showParen (p > 9) (showString "<>") showsPrec p (Vector xs) = showParen (p > 9) (showChar '<' . showVector1 xs) where showVector1 [] = showChar '>' showVector1 (y:[]) = shows y . showChar '>' showVector1 (y:ys) = shows y . showChar ',' . showVector1 ys instance Foldable Vector where foldr f x (Vector a) = foldr f x a farm11 f = fmap f farm21 f a b = f <$> a <*> b farm31 f a b c = f <$> a <*> b <*> c farm41 f a b c d = f <$> a <*> b <*> c <*> d farm51 f a b c d e = f <$> a <*> b <*> c <*> d <*> e farm12 f = (|<) . fmap f farm22 f a = (|<) . farm21 f a infixr 5 <++> (Vector a) <++> (Vector b) = Vector (a ++ b) unsafeApply f (Vector a) = f a unsafeLift f (Vector a) = Vector (f a) -- | See 'ForSyDe.Atom.Skel.Vector.reduce'. reduce f = unsafeApply (L.foldr1 f) -- | See 'ForSyDe.Atom.Skel.Vector.length'. length = unsafeApply (L.length) -- | See 'ForSyDe.Atom.Skel.Vector.drop'. drop n = unsafeLift (L.drop n) -- | See 'ForSyDe.Atom.Skel.Vector.take'. take n = unsafeLift (L.take n) -- | See 'ForSyDe.Atom.Skel.Vector.first'. first = unsafeApply L.head -- | See 'ForSyDe.Atom.Skel.Vector.group'. group :: Int -> Vector a -> Vector (Vector a) group n (Vector a) = vector $ map vector $ chunksOf n a -- | See 'ForSyDe.Atom.Skel.Vector.fanout'. fanout = vector . L.repeat -- | See 'ForSyDe.Atom.Skel.Vector.fanoutn'. fanoutn n = vector . L.replicate n -- | See 'ForSyDe.Atom.Skel.Vector.stencil'. stencil n v = farm11 (take n) $ dropFromEnd n $ tails v where dropFromEnd n = take (length v - n + 1) -- | See 'ForSyDe.Atom.Skel.Vector.tails'. tails = unsafeLift (L.init . map vector . L.tails) -- | See 'ForSyDe.Atom.Skel.Vector.concat'. concat = unsafeLift (L.concat . map fromVector) -- | See 'ForSyDe.Atom.Skel.Vector.iterate'. iterate n f i = vector $ L.take n $ L.iterate f i -- | See 'ForSyDe.Atom.Skel.Vector.pipe'. pipe (Vector []) i = i pipe v i = unsafeApply (L.foldr1 (.)) v i -- | See 'ForSyDe.Atom.Skel.Vector.pipe1'. pipe1 f v i = unsafeApply (L.foldr f i) v -- | See 'ForSyDe.Atom.Skel.Vector.reverse'. reverse = unsafeLift L.reverse -- | See 'ForSyDe.Atom.Skel.Vector.recuri'. recuri ps s = farm11 (`pipe` s) (unsafeLift (L.map vector . L.tails) ps) -- reducei1 p i v1 vs = S.farm21 p v1 vs =<<= i -- tail' Null = Null -- tail' xs = V.tail xs -- first' Null = Null -- first' xs = V.first xs -- -- | The function 'rotate' rotates a vector based on an index offset. -- -- -- -- * @(> 0)@ : rotates the vector left with the corresponding number -- -- of positions. -- -- -- -- * @(= 0)@ : does not modify the vector. -- -- -- -- * @(< 0)@ : rotates the vector right with the corresponding number -- -- of positions. -- rotate :: Int -> Vector a -> Vector a -- rotate n -- | n > 0 = V.pipe (V.fanoutn (abs n) V.rotl) -- | n < 0 = V.pipe (V.fanoutn (abs n) V.rotr) -- | otherwise = id -- -- | takes the first /n/ elements of a vector. -- -- -- -- >>> take 5 $ vector [1,2,3,4,5,6,7,8,9] -- -- <1,2,3,4,5> -- -- -- -- <<fig/eqs-skel-vector-take.png>> -- take _ Null = Null -- take n v = reducei1 sel Null indexes . S.farm11 unit $ v -- where sel i x y = if i < n then x <++> y else x -- -- | drops the first /n/ elements of a vector. -- -- -- -- >>> drop 5 $ vector [1,2,3,4,5,6,7,8,9] -- -- <6,7,8,9> -- -- -- -- <<fig/eqs-skel-vector-drop.png>> -- drop _ Null = Null -- drop n v = reducei1 sel Null indexes . S.farm11 unit $ v -- where sel i x y = if i > n then x <++> y else y -- -- | groups a vector into sub-vectors of /n/ elements. -- -- -- -- >>> group 3 $ vector [1,2,3,4,5,6,7,8] -- -- <<1,2,3>,<4,5,6>,<7,8>> -- -- -- -- <<fig/eqs-skel-vector-group.png>> -- -- -- -- <<fig/skel-vector-comm-group.png>> -- -- <<fig/skel-vector-comm-group-net.png>> -- group :: Int -> Vector a -> Vector (Vector a) -- group _ Null = unit Null -- group n v = reducei1 sel Null indexes . S.farm11 (unit . unit) $ v -- where sel i x y -- | i `mod` n == 0 = x <++> y -- | otherwise = (S.first x <++> first' y) :> tail' y -- | See 'ForSyDe.Atom.Skel.Vector.get'. get :: Int -> Vector a -> Maybe a get _ (Vector []) = Nothing get n v | n >= length v = Nothing | otherwise = Just $ fromVector v !! n -- -- | the same as 'get' but with flipped arguments. -- v <@ ix = get ix v -- -- | unsafe version of '<@>'. Throws an exception if /n > l/. -- v <@! ix | isNothing e = error "get!: index out of bounds" -- | otherwise = fromJust e -- where e = get ix v -- indexes = V.vector [1..] :: Vector Int -- indexesTo n = take n $ indexes -- -- | Returns a stencil of @n@ neighboring elements for each possible -- -- element in a vector. -- -- -- -- >>> stencilV 3 $ vector [1..5] -- -- <<1,2,3>,<2,3,4>,<3,4,5>> -- stencil :: Int -- ^ stencil size @= n@ -- -> Vector a -- ^ /length/ = @la@ -- -> Vector (Vector a) -- ^ /length/ = @la - n + 1@ -- stencil n v = V.farm11 (take n) $ dropFromEnd n $ V.tails v -- where dropFromEnd n = take (length v - n + 1) -- zip = farm21 (,) -- unzip = farm12 id evensF [] = [] evensF [x] = [x] evensF (x:_:xs) = x:evensF xs oddsF [] = [] oddsF [_] = [] oddsF (_:y:xs) = y:oddsF xs -- | See 'ForSyDe.Atom.Skel.Vector.DSP.evens'. evens = unsafeLift evensF -- | See 'ForSyDe.Atom.Skel.Vector.DSP.odds'. odds = unsafeLift oddsF
forsyde/forsyde-atom
src/ForSyDe/Atom/Skel/FastVector/Lib.hs
bsd-3-clause
6,049
0
11
1,367
1,362
732
630
66
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module Network.Protocol.Snmp.AgentX.MIBTree.MIBTree ( initModule , registerFullTree , unregisterFullTree , findOne , findMany , findNext , findClosest , findManyNext , regWrapper , askTree , regByDiff ) where import Data.Maybe import Control.Applicative import Control.Monad.State.Strict (MonadIO, forM_, lift, get, put, liftIO, when) import Network.Protocol.Snmp.AgentX.MIBTree.Types hiding (context) import Network.Protocol.Snmp.AgentX.MIBTree.Tree import Network.Protocol.Snmp (OID, Value(EndOfMibView, NoSuchInstance, NoSuchObject)) import Network.Protocol.Snmp.AgentX.Packet (Context, SearchRange, startOID, endOID, include) import Control.Concurrent.MVar import qualified Data.Label as L import Data.List (stripPrefix) import Data.Monoid import Data.Label.Monadic import Control.Category ((.)) import Prelude hiding ((.)) -- import Debug.Trace -- | build tree and init module initModule :: MIBTree IO () initModule = flip forM_ evalTree =<< toUpdateList <$> gets ou where evalTree :: MIB -> MIBTree IO () evalTree obj = do (mibs, updates) <- buildTree <$> (lift $ unUpdate . fromJust . update $ obj) case updates of Empty -> do -- if without updates just attach subtree modify zipper $ top . attach mibs . (fromJust . setCursor (oi obj) Nothing) . top modify ou $ top . attach updates . (fromJust . setCursor (oi obj) Nothing) . top _ -> do -- if with updates, save state, build new subtree, return state, and attach builded subtree modify zipper $ fromJust . setCursor (oi obj) Nothing . top modify ou $ fromJust . setCursor (oi obj) Nothing . top old <- get modify zipper $ const (mibs, []) modify ou $ const (updates, []) initModule Module (z,_) (o,_) _ _ <- get put old modify zipper $ top . attach z modify ou $ top . attach o -- | register all MIBs in snmp server registerFullTree :: (Monad m, MonadIO m, Functor m) => MIBTree m () registerFullTree = do z <- fst . top <$> gets zipper mv <- gets register b <- gets moduleOID liftIO $ putMVar mv (addBaseOid b $ regPair z Empty) unregisterFullTree :: (Monad m, MonadIO m, Functor m) => MIBTree m () unregisterFullTree = do z <- fst . top <$> gets zipper mv <- gets register b <- gets moduleOID liftIO $ putMVar mv (addBaseOid b $ regPair Empty z) askTree :: (Monad m, MonadIO m, Functor m) => MIBTree m (Tree IValue) askTree = fst . top <$> gets zipper regByDiff :: (Monad m, MonadIO m, Functor m) => Tree IValue -> Tree IValue -> MIBTree m () regByDiff old new = do mv <- gets register b <- gets moduleOID liftIO $ putMVar mv (addBaseOid b $ regPair old new) addBaseOid :: OID -> ([(OID, Maybe Context)], [(OID, Maybe Context)]) -> ([(OID, Maybe Context)], [(OID, Maybe Context)]) addBaseOid b (reg, unreg) = (map fun reg, map fun unreg) where fun (o, mc) = (b <> o, mc) toUpdateList :: Zipper Tree IUpdate -> [MIB] toUpdateList (Empty, _) = [] toUpdateList (t, _) = toUpdateList' ([], t) where toUpdateList' :: (OID, Tree IUpdate) -> [MIB] toUpdateList' (o, Node x next level) = if withValue x then Object (reverse $ index x : o) (index x) "" "" (valueFromContexted x) : toUpdateList' (o, next) <> toUpdateList' (index x : o, level) else toUpdateList' (o, next) <> toUpdateList' (index x : o, level) toUpdateList' _ = [] valueFromContexted (Contexted (_, _, x)) = x inRange :: SearchRange -> MIB -> MIB inRange s m = if (L.get startOID s) <= oi m && oi m < (L.get endOID s) then ObjectType (oi m) (last $ oi m) "" "" Nothing (val m) else ObjectType (L.get startOID s) (last $ L.get startOID s) "" "" Nothing (rsValue EndOfMibView) -- | find one MIB findOne :: OID -- ^ path for find -> Maybe Context -- ^ context, you can have many values with one path and different context -> MIBTree IO MIB findOne ys mcontext = do -- init zippers modify zipper top modify ou top modOID <- gets moduleOID -- strip module prefix case stripPrefix modOID ys of Nothing -> return $ ObjectType ys (last ys) "" "" mcontext nso Just ys' -> do updates <- gets ou -- put update subtree to state puts ou (updateSubtree ys' updates) -- update dynamic branches initModule -- get back full update tree puts ou updates -- find findOne' ys' <$> gets zipper where findOne' xs z = toObject $ setCursor xs mcontext z toObject Nothing = ObjectType ys (last ys) "" "" mcontext nsi toObject (Just (Node (Contexted (i, _, v)) _ Empty, _)) = ObjectType ys i "" "" mcontext (fromMaybe nso v) toObject _ = ObjectType ys (last ys) "" "" mcontext nso nso, nsi :: PVal nso = rsValue NoSuchObject nsi = rsValue NoSuchInstance updateSubtree :: Contexted a => OID -> Zipper Tree a -> Zipper Tree a updateSubtree xs z = let (x, u) = goClosest xs Nothing z isLevel (Level _) = True isLevel _ = False cleanUnused (Level (Node v _ l)) = Level (Node v Empty l) cleanUnused _ = error "cleanUnused" cleanHead Empty = Empty cleanHead (Node v _ l) = Node v Empty l in top (cleanHead x, map cleanUnused $ filter isLevel u) -- | wrap MIBTree action, get MIB tree before and after, register added mibs, unregister removed mibs regWrapper :: (Monad m, MonadIO m, Functor m) => MIBTree m x -> MIBTree m x regWrapper x = do old <- fst . top <$> gets zipper r <- x new <- fst . top <$> gets zipper mv <- gets register b <- gets moduleOID let diff = addBaseOid b $ regPair new old when (diff /= ([], [])) $ do liftIO $ putMVar mv diff return r -- | like findOne, but for many paths findMany :: [OID] -> Maybe Context -> MIBTree IO [MIB] findMany xs mc = mapM (flip findOne mc) xs -- | find next node in MIBTree findNext :: SearchRange -- ^ SearchRange (getwalk or getnext requests) -> Maybe Context -- ^ context -> MIBTree IO MIB -- ^ search result findNext sr mcontext = do modify zipper top modify ou top modOID <- gets moduleOID let start = L.get startOID sr end = L.get endOID sr case (stripPrefix modOID start, stripPrefix modOID end) of (Nothing, _) -> return $ ObjectType start (last start) "" "" mcontext eom (Just start', Just end') -> do updates <- gets ou puts ou (updateSubtree start' updates) initModule puts ou updates let fixSearchRange = L.set startOID start' . L.set endOID end' fixMib modOID . findNext' (fixSearchRange sr) <$> gets zipper _ -> error "findNext" where eom :: PVal eom = rsValue EndOfMibView fixMib :: OID -> MIB -> MIB fixMib m (ObjectType o i _ _ mc v) = ObjectType (m <> o) i "" "" mc v fixMib _ _ = error "fixMib" findNext' :: SearchRange -> Zipper Tree IValue -> MIB findNext' sr' z | L.get include sr' = let start = L.get startOID sr' nz@(Node v _ _, _) = goClosest start mcontext z o = oid nz Contexted (i, mc, Just pv) = v in if o == start && withValue v && mc == mcontext then ObjectType o i "" "" mc pv else findNext' (L.set include False $ sr') z | otherwise = let start = L.get startOID sr' nz = goClosest start mcontext z l = hasLevel nz n = hasNext nz in case (l, n) of (True, _) -> inRange sr' $ findClosest False start mcontext (fromJust $ goLevel nz) (False, True) -> inRange sr' $ findClosest False start mcontext (fromJust $ goNext nz) (False, False) -> inRange sr' $ findClosest True start mcontext (fromJust $ goUp nz) findClosest :: Bool -> OID -> Maybe Context -> Zipper Tree IValue -> MIB findClosest back o mcontext z = let (canBeObject, checkContextEquality) = isFocusObjectType z magic = if back then not (hasLevel z) else (hasLevel z) isNextAvailable = hasNext z in case (canBeObject, checkContextEquality mcontext, magic, isNextAvailable) of (True, True, _, _ ) -> getFocus z (_, _, True, _ ) -> findClosest False o mcontext (fromJust $ goLevel z) (_, _, False, True ) -> findClosest False o mcontext (fromJust $ goNext z) _ -> case goUp z of Just nz -> findClosest True o mcontext nz Nothing -> ObjectType o (last o) "" "" Nothing (rsValue EndOfMibView) isFocusObjectType :: Contexted a => (Tree a, t) -> (Bool, Maybe Context -> Bool) isFocusObjectType (Node v _ Empty,_) = (withValue v, (==) (context v)) isFocusObjectType _ = (False, const False) getFocus :: Zipper Tree IValue -> MIB getFocus z@(Node (Contexted (i, mc, Just v)) _ _, _) = let o = oid z in ObjectType o i "" "" mc v getFocus _ = error "getFocus" -- | like findNext findManyNext :: [SearchRange] -> Maybe Context -> MIBTree IO [MIB] findManyNext xs mc = mapM (flip findNext mc) xs
chemist/agentx
src/Network/Protocol/Snmp/AgentX/MIBTree/MIBTree.hs
bsd-3-clause
9,617
0
20
2,891
3,458
1,748
1,710
202
7
{-# language CPP #-} -- | = Name -- -- VK_FUCHSIA_buffer_collection - device extension -- -- == VK_FUCHSIA_buffer_collection -- -- [__Name String__] -- @VK_FUCHSIA_buffer_collection@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 367 -- -- [__Revision__] -- 2 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_FUCHSIA_external_memory@ -- -- - Requires @VK_KHR_sampler_ycbcr_conversion@ -- -- [__Contact__] -- -- - John Rosasco -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_FUCHSIA_buffer_collection] @rosasco%0A<<Here describe the issue or question you have about the VK_FUCHSIA_buffer_collection extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2021-09-23 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Craig Stout, Google -- -- - John Bauman, Google -- -- - John Rosasco, Google -- -- == Description -- -- A buffer collection is a collection of one or more buffers which were -- allocated together as a group and which all have the same properties. -- These properties describe the buffers\' internal representation such as -- its dimensions and memory layout. This ensures that all of the buffers -- can be used interchangeably by tasks that require swapping among -- multiple buffers, such as double-buffered graphics rendering. -- -- By sharing such a collection of buffers between components, -- communication about buffer lifecycle can be made much simpler and more -- efficient. For example, when a content producer finishes writing to a -- buffer, it can message the consumer of the buffer with the buffer index, -- rather than passing a handle to the shared memory. -- -- On Fuchsia, the Sysmem service uses buffer collections as a core -- construct in its design. VK_FUCHSIA_buffer_collection is the Vulkan -- extension that allows Vulkan applications to interoperate with the -- Sysmem service on Fuchsia. -- -- == New Object Types -- -- - 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- -- == New Commands -- -- - 'createBufferCollectionFUCHSIA' -- -- - 'destroyBufferCollectionFUCHSIA' -- -- - 'getBufferCollectionPropertiesFUCHSIA' -- -- - 'setBufferCollectionBufferConstraintsFUCHSIA' -- -- - 'setBufferCollectionImageConstraintsFUCHSIA' -- -- == New Structures -- -- - 'BufferCollectionConstraintsInfoFUCHSIA' -- -- - 'BufferCollectionCreateInfoFUCHSIA' -- -- - 'BufferCollectionPropertiesFUCHSIA' -- -- - 'BufferConstraintsInfoFUCHSIA' -- -- - 'ImageConstraintsInfoFUCHSIA' -- -- - 'ImageFormatConstraintsInfoFUCHSIA' -- -- - 'SysmemColorSpaceFUCHSIA' -- -- - Extending 'Vulkan.Core10.Buffer.BufferCreateInfo': -- -- - 'BufferCollectionBufferCreateInfoFUCHSIA' -- -- - Extending 'Vulkan.Core10.Image.ImageCreateInfo': -- -- - 'BufferCollectionImageCreateInfoFUCHSIA' -- -- - Extending 'Vulkan.Core10.Memory.MemoryAllocateInfo': -- -- - 'ImportMemoryBufferCollectionFUCHSIA' -- -- == New Enums -- -- - 'ImageConstraintsInfoFlagBitsFUCHSIA' -- -- == New Bitmasks -- -- - 'ImageConstraintsInfoFlagsFUCHSIA' -- -- - 'ImageFormatConstraintsFlagsFUCHSIA' -- -- == New Enum Constants -- -- - 'FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME' -- -- - 'FUCHSIA_BUFFER_COLLECTION_SPEC_VERSION' -- -- - Extending -- 'Vulkan.Extensions.VK_EXT_debug_report.DebugReportObjectTypeEXT': -- -- - 'Vulkan.Extensions.VK_EXT_debug_report.DEBUG_REPORT_OBJECT_TYPE_BUFFER_COLLECTION_FUCHSIA_EXT' -- -- - Extending 'Vulkan.Core10.Enums.ObjectType.ObjectType': -- -- - 'Vulkan.Core10.Enums.ObjectType.OBJECT_TYPE_BUFFER_COLLECTION_FUCHSIA' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_COLLECTION_BUFFER_CREATE_INFO_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_COLLECTION_CONSTRAINTS_INFO_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_COLLECTION_CREATE_INFO_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_COLLECTION_IMAGE_CREATE_INFO_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_COLLECTION_PROPERTIES_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_CONSTRAINTS_INFO_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_CONSTRAINTS_INFO_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_FORMAT_CONSTRAINTS_INFO_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMPORT_MEMORY_BUFFER_COLLECTION_FUCHSIA' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SYSMEM_COLOR_SPACE_FUCHSIA' -- -- == Issues -- -- 1) When configuring a 'ImageConstraintsInfoFUCHSIA' structure for -- constraint setting, should a NULL @pFormatConstraints@ parameter be -- allowed ? -- -- __RESOLVED__: No. Specifying a NULL @pFormatConstraints@ results in -- logical complexity of interpreting the relationship between the -- 'Vulkan.Core10.Image.ImageCreateInfo'::@usage@ settings of the elements -- of the @pImageCreateInfos@ array and the implied or desired -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlags'. -- -- The explicit requirement for @pFormatConstraints@ to be non-NULL -- simplifies the implied logic of the implementation and expectations for -- the Vulkan application. -- -- == Version History -- -- - Revision 2, 2021-09-23 (John Rosasco) -- -- - Review passes -- -- - Revision 1, 2021-03-09 (John Rosasco) -- -- - Initial revision -- -- == See Also -- -- 'BufferCollectionBufferCreateInfoFUCHSIA', -- 'BufferCollectionConstraintsInfoFUCHSIA', -- 'BufferCollectionCreateInfoFUCHSIA', -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'BufferCollectionImageCreateInfoFUCHSIA', -- 'BufferCollectionPropertiesFUCHSIA', 'BufferConstraintsInfoFUCHSIA', -- 'ImageConstraintsInfoFUCHSIA', 'ImageConstraintsInfoFlagBitsFUCHSIA', -- 'ImageConstraintsInfoFlagsFUCHSIA', -- 'ImageFormatConstraintsFlagsFUCHSIA', -- 'ImageFormatConstraintsInfoFUCHSIA', -- 'ImportMemoryBufferCollectionFUCHSIA', 'SysmemColorSpaceFUCHSIA', -- 'createBufferCollectionFUCHSIA', 'destroyBufferCollectionFUCHSIA', -- 'getBufferCollectionPropertiesFUCHSIA', -- 'setBufferCollectionBufferConstraintsFUCHSIA', -- 'setBufferCollectionImageConstraintsFUCHSIA' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_FUCHSIA_buffer_collection ( createBufferCollectionFUCHSIA , withBufferCollectionFUCHSIA , setBufferCollectionBufferConstraintsFUCHSIA , setBufferCollectionImageConstraintsFUCHSIA , destroyBufferCollectionFUCHSIA , getBufferCollectionPropertiesFUCHSIA , ImportMemoryBufferCollectionFUCHSIA(..) , BufferCollectionImageCreateInfoFUCHSIA(..) , BufferCollectionBufferCreateInfoFUCHSIA(..) , BufferCollectionCreateInfoFUCHSIA(..) , BufferCollectionPropertiesFUCHSIA(..) , BufferConstraintsInfoFUCHSIA(..) , SysmemColorSpaceFUCHSIA(..) , ImageFormatConstraintsInfoFUCHSIA(..) , ImageConstraintsInfoFUCHSIA(..) , BufferCollectionConstraintsInfoFUCHSIA(..) , ImageFormatConstraintsFlagsFUCHSIA(..) , ImageConstraintsInfoFlagsFUCHSIA , ImageConstraintsInfoFlagBitsFUCHSIA( IMAGE_CONSTRAINTS_INFO_CPU_READ_RARELY_FUCHSIA , IMAGE_CONSTRAINTS_INFO_CPU_READ_OFTEN_FUCHSIA , IMAGE_CONSTRAINTS_INFO_CPU_WRITE_RARELY_FUCHSIA , IMAGE_CONSTRAINTS_INFO_CPU_WRITE_OFTEN_FUCHSIA , IMAGE_CONSTRAINTS_INFO_PROTECTED_OPTIONAL_FUCHSIA , .. ) , FUCHSIA_BUFFER_COLLECTION_SPEC_VERSION , pattern FUCHSIA_BUFFER_COLLECTION_SPEC_VERSION , FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME , pattern FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME , BufferCollectionFUCHSIA(..) , DebugReportObjectTypeEXT(..) , Zx_handle_t ) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showString) import Numeric (showHex) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Word (Word32) import Data.Word (Word64) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.CStruct.Extends (forgetExtensions) import Vulkan.CStruct.Extends (peekSomeCStruct) import Vulkan.CStruct.Extends (pokeSomeCStruct) import Vulkan.NamedType ((:::)) import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks) import Vulkan.Extensions.Handles (BufferCollectionFUCHSIA) import Vulkan.Extensions.Handles (BufferCollectionFUCHSIA(..)) import Vulkan.Core10.Buffer (BufferCreateInfo) import Vulkan.Core11.Enums.ChromaLocation (ChromaLocation) import Vulkan.Core10.ImageView (ComponentMapping) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkCreateBufferCollectionFUCHSIA)) import Vulkan.Dynamic (DeviceCmds(pVkDestroyBufferCollectionFUCHSIA)) import Vulkan.Dynamic (DeviceCmds(pVkGetBufferCollectionPropertiesFUCHSIA)) import Vulkan.Dynamic (DeviceCmds(pVkSetBufferCollectionBufferConstraintsFUCHSIA)) import Vulkan.Dynamic (DeviceCmds(pVkSetBufferCollectionImageConstraintsFUCHSIA)) import Vulkan.Core10.Handles (Device_T) import Vulkan.Core10.FundamentalTypes (Flags) import Vulkan.Core10.Enums.FormatFeatureFlagBits (FormatFeatureFlags) import Vulkan.Core10.Image (ImageCreateInfo) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core11.Enums.SamplerYcbcrModelConversion (SamplerYcbcrModelConversion) import Vulkan.Core11.Enums.SamplerYcbcrRange (SamplerYcbcrRange) import Vulkan.CStruct.Extends (SomeStruct) import Vulkan.CStruct.Extends (SomeStruct(..)) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Exception (VulkanException(..)) import Vulkan.Extensions.VK_FUCHSIA_imagepipe_surface (Zx_handle_t) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BUFFER_COLLECTION_BUFFER_CREATE_INFO_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BUFFER_COLLECTION_CONSTRAINTS_INFO_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BUFFER_COLLECTION_CREATE_INFO_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BUFFER_COLLECTION_IMAGE_CREATE_INFO_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BUFFER_COLLECTION_PROPERTIES_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BUFFER_CONSTRAINTS_INFO_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMAGE_CONSTRAINTS_INFO_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMAGE_FORMAT_CONSTRAINTS_INFO_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMPORT_MEMORY_BUFFER_COLLECTION_FUCHSIA)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SYSMEM_COLOR_SPACE_FUCHSIA)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Extensions.Handles (BufferCollectionFUCHSIA(..)) import Vulkan.Extensions.VK_EXT_debug_report (DebugReportObjectTypeEXT(..)) import Vulkan.Extensions.VK_FUCHSIA_imagepipe_surface (Zx_handle_t) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCreateBufferCollectionFUCHSIA :: FunPtr (Ptr Device_T -> Ptr BufferCollectionCreateInfoFUCHSIA -> Ptr AllocationCallbacks -> Ptr BufferCollectionFUCHSIA -> IO Result) -> Ptr Device_T -> Ptr BufferCollectionCreateInfoFUCHSIA -> Ptr AllocationCallbacks -> Ptr BufferCollectionFUCHSIA -> IO Result -- | vkCreateBufferCollectionFUCHSIA - Create a new buffer collection -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCreateBufferCollectionFUCHSIA-device-parameter# @device@ -- /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkCreateBufferCollectionFUCHSIA-pCreateInfo-parameter# -- @pCreateInfo@ /must/ be a valid pointer to a valid -- 'BufferCollectionCreateInfoFUCHSIA' structure -- -- - #VUID-vkCreateBufferCollectionFUCHSIA-pAllocator-parameter# If -- @pAllocator@ is not @NULL@, @pAllocator@ /must/ be a valid pointer -- to a valid 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' -- structure -- -- - #VUID-vkCreateBufferCollectionFUCHSIA-pCollection-parameter# -- @pCollection@ /must/ be a valid pointer to a -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_INVALID_EXTERNAL_HANDLE' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- -- == Host Access -- -- All functions referencing a -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' /must/ be externally -- synchronized with the exception of 'createBufferCollectionFUCHSIA'. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'BufferCollectionCreateInfoFUCHSIA', -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'Vulkan.Core10.Handles.Device' createBufferCollectionFUCHSIA :: forall io . (MonadIO io) => -- | @device@ is the logical device that creates the -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' Device -> -- | @pCreateInfo@ is a pointer to a 'BufferCollectionCreateInfoFUCHSIA' -- structure containing parameters affecting creation of the buffer -- collection BufferCollectionCreateInfoFUCHSIA -> -- | @pAllocator@ is a pointer to a -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- controlling host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter ("allocator" ::: Maybe AllocationCallbacks) -> io (BufferCollectionFUCHSIA) createBufferCollectionFUCHSIA device createInfo allocator = liftIO . evalContT $ do let vkCreateBufferCollectionFUCHSIAPtr = pVkCreateBufferCollectionFUCHSIA (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkCreateBufferCollectionFUCHSIAPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateBufferCollectionFUCHSIA is null" Nothing Nothing let vkCreateBufferCollectionFUCHSIA' = mkVkCreateBufferCollectionFUCHSIA vkCreateBufferCollectionFUCHSIAPtr pCreateInfo <- ContT $ withCStruct (createInfo) pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) pPCollection <- ContT $ bracket (callocBytes @BufferCollectionFUCHSIA 8) free r <- lift $ traceAroundEvent "vkCreateBufferCollectionFUCHSIA" (vkCreateBufferCollectionFUCHSIA' (deviceHandle (device)) pCreateInfo pAllocator (pPCollection)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pCollection <- lift $ peek @BufferCollectionFUCHSIA pPCollection pure $ (pCollection) -- | A convenience wrapper to make a compatible pair of calls to -- 'createBufferCollectionFUCHSIA' and 'destroyBufferCollectionFUCHSIA' -- -- To ensure that 'destroyBufferCollectionFUCHSIA' is always called: pass -- 'Control.Exception.bracket' (or the allocate function from your -- favourite resource management library) as the last argument. -- To just extract the pair pass '(,)' as the last argument. -- withBufferCollectionFUCHSIA :: forall io r . MonadIO io => Device -> BufferCollectionCreateInfoFUCHSIA -> Maybe AllocationCallbacks -> (io BufferCollectionFUCHSIA -> (BufferCollectionFUCHSIA -> io ()) -> r) -> r withBufferCollectionFUCHSIA device pCreateInfo pAllocator b = b (createBufferCollectionFUCHSIA device pCreateInfo pAllocator) (\(o0) -> destroyBufferCollectionFUCHSIA device o0 pAllocator) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkSetBufferCollectionBufferConstraintsFUCHSIA :: FunPtr (Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr BufferConstraintsInfoFUCHSIA -> IO Result) -> Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr BufferConstraintsInfoFUCHSIA -> IO Result -- | vkSetBufferCollectionBufferConstraintsFUCHSIA - Set buffer-based -- constraints for a buffer collection -- -- = Description -- -- 'setBufferCollectionBufferConstraintsFUCHSIA' /may/ fail if the -- implementation does not support the constraints specified in the -- @bufferCollectionConstraints@ structure. If that occurs, -- 'setBufferCollectionBufferConstraintsFUCHSIA' will return -- 'Vulkan.Core10.Enums.Result.ERROR_FORMAT_NOT_SUPPORTED'. -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FORMAT_NOT_SUPPORTED' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'BufferConstraintsInfoFUCHSIA', 'Vulkan.Core10.Handles.Device' setBufferCollectionBufferConstraintsFUCHSIA :: forall io . (MonadIO io) => -- | @device@ is the logical device -- -- #VUID-vkSetBufferCollectionBufferConstraintsFUCHSIA-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle Device -> -- | @collection@ is the 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- handle -- -- #VUID-vkSetBufferCollectionBufferConstraintsFUCHSIA-collection-parameter# -- @collection@ /must/ be a valid -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle -- -- #VUID-vkSetBufferCollectionBufferConstraintsFUCHSIA-collection-parent# -- @collection@ /must/ have been created, allocated, or retrieved from -- @device@ BufferCollectionFUCHSIA -> -- | @pBufferConstraintsInfo@ is a pointer to a -- 'BufferConstraintsInfoFUCHSIA' structure -- -- #VUID-vkSetBufferCollectionBufferConstraintsFUCHSIA-pBufferConstraintsInfo-parameter# -- @pBufferConstraintsInfo@ /must/ be a valid pointer to a valid -- 'BufferConstraintsInfoFUCHSIA' structure BufferConstraintsInfoFUCHSIA -> io () setBufferCollectionBufferConstraintsFUCHSIA device collection bufferConstraintsInfo = liftIO . evalContT $ do let vkSetBufferCollectionBufferConstraintsFUCHSIAPtr = pVkSetBufferCollectionBufferConstraintsFUCHSIA (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkSetBufferCollectionBufferConstraintsFUCHSIAPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkSetBufferCollectionBufferConstraintsFUCHSIA is null" Nothing Nothing let vkSetBufferCollectionBufferConstraintsFUCHSIA' = mkVkSetBufferCollectionBufferConstraintsFUCHSIA vkSetBufferCollectionBufferConstraintsFUCHSIAPtr pBufferConstraintsInfo <- ContT $ withCStruct (bufferConstraintsInfo) r <- lift $ traceAroundEvent "vkSetBufferCollectionBufferConstraintsFUCHSIA" (vkSetBufferCollectionBufferConstraintsFUCHSIA' (deviceHandle (device)) (collection) pBufferConstraintsInfo) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkSetBufferCollectionImageConstraintsFUCHSIA :: FunPtr (Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr ImageConstraintsInfoFUCHSIA -> IO Result) -> Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr ImageConstraintsInfoFUCHSIA -> IO Result -- | vkSetBufferCollectionImageConstraintsFUCHSIA - Set image-based -- constraints for a buffer collection -- -- = Description -- -- 'setBufferCollectionImageConstraintsFUCHSIA' /may/ fail if -- @pImageConstraintsInfo@::@formatConstraintsCount@ is larger than the -- implementation-defined limit. If that occurs, -- 'setBufferCollectionImageConstraintsFUCHSIA' will return -- VK_ERROR_INITIALIZATION_FAILED. -- -- 'setBufferCollectionImageConstraintsFUCHSIA' /may/ fail if the -- implementation does not support any of the formats described by the -- @pImageConstraintsInfo@ structure. If that occurs, -- 'setBufferCollectionImageConstraintsFUCHSIA' will return -- 'Vulkan.Core10.Enums.Result.ERROR_FORMAT_NOT_SUPPORTED'. -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FORMAT_NOT_SUPPORTED' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'Vulkan.Core10.Handles.Device', 'ImageConstraintsInfoFUCHSIA' setBufferCollectionImageConstraintsFUCHSIA :: forall io . (MonadIO io) => -- | @device@ is the logical device -- -- #VUID-vkSetBufferCollectionImageConstraintsFUCHSIA-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle Device -> -- | @collection@ is the 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- handle -- -- #VUID-vkSetBufferCollectionImageConstraintsFUCHSIA-collection-parameter# -- @collection@ /must/ be a valid -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle -- -- #VUID-vkSetBufferCollectionImageConstraintsFUCHSIA-collection-parent# -- @collection@ /must/ have been created, allocated, or retrieved from -- @device@ BufferCollectionFUCHSIA -> -- | @pImageConstraintsInfo@ is a pointer to a 'ImageConstraintsInfoFUCHSIA' -- structure -- -- #VUID-vkSetBufferCollectionImageConstraintsFUCHSIA-pImageConstraintsInfo-parameter# -- @pImageConstraintsInfo@ /must/ be a valid pointer to a valid -- 'ImageConstraintsInfoFUCHSIA' structure ImageConstraintsInfoFUCHSIA -> io () setBufferCollectionImageConstraintsFUCHSIA device collection imageConstraintsInfo = liftIO . evalContT $ do let vkSetBufferCollectionImageConstraintsFUCHSIAPtr = pVkSetBufferCollectionImageConstraintsFUCHSIA (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkSetBufferCollectionImageConstraintsFUCHSIAPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkSetBufferCollectionImageConstraintsFUCHSIA is null" Nothing Nothing let vkSetBufferCollectionImageConstraintsFUCHSIA' = mkVkSetBufferCollectionImageConstraintsFUCHSIA vkSetBufferCollectionImageConstraintsFUCHSIAPtr pImageConstraintsInfo <- ContT $ withCStruct (imageConstraintsInfo) r <- lift $ traceAroundEvent "vkSetBufferCollectionImageConstraintsFUCHSIA" (vkSetBufferCollectionImageConstraintsFUCHSIA' (deviceHandle (device)) (collection) pImageConstraintsInfo) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkDestroyBufferCollectionFUCHSIA :: FunPtr (Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr AllocationCallbacks -> IO ()) -> Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr AllocationCallbacks -> IO () -- | vkDestroyBufferCollectionFUCHSIA - Destroy a buffer collection -- -- == Valid Usage -- -- - #VUID-vkDestroyBufferCollectionFUCHSIA-collection-06407# -- 'Vulkan.Core10.Handles.Image' and 'Vulkan.Core10.Handles.Buffer' -- objects that referenced @collection@ upon creation by inclusion of a -- 'BufferCollectionImageCreateInfoFUCHSIA' or -- 'BufferCollectionBufferCreateInfoFUCHSIA' chained to their -- 'Vulkan.Core10.Image.ImageCreateInfo' or -- 'Vulkan.Core10.Buffer.BufferCreateInfo' structures respectively, -- /may/ outlive @collection@. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkDestroyBufferCollectionFUCHSIA-device-parameter# @device@ -- /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkDestroyBufferCollectionFUCHSIA-collection-parameter# -- @collection@ /must/ be a valid -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle -- -- - #VUID-vkDestroyBufferCollectionFUCHSIA-pAllocator-parameter# If -- @pAllocator@ is not @NULL@, @pAllocator@ /must/ be a valid pointer -- to a valid 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' -- structure -- -- - #VUID-vkDestroyBufferCollectionFUCHSIA-collection-parent# -- @collection@ /must/ have been created, allocated, or retrieved from -- @device@ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'Vulkan.Core10.Handles.Device' destroyBufferCollectionFUCHSIA :: forall io . (MonadIO io) => -- | @device@ is the logical device that creates the -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' Device -> -- | @collection@ is the 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- handle BufferCollectionFUCHSIA -> -- | @pAllocator@ is a pointer to a -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- controlling host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter ("allocator" ::: Maybe AllocationCallbacks) -> io () destroyBufferCollectionFUCHSIA device collection allocator = liftIO . evalContT $ do let vkDestroyBufferCollectionFUCHSIAPtr = pVkDestroyBufferCollectionFUCHSIA (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkDestroyBufferCollectionFUCHSIAPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkDestroyBufferCollectionFUCHSIA is null" Nothing Nothing let vkDestroyBufferCollectionFUCHSIA' = mkVkDestroyBufferCollectionFUCHSIA vkDestroyBufferCollectionFUCHSIAPtr pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ traceAroundEvent "vkDestroyBufferCollectionFUCHSIA" (vkDestroyBufferCollectionFUCHSIA' (deviceHandle (device)) (collection) pAllocator) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetBufferCollectionPropertiesFUCHSIA :: FunPtr (Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr BufferCollectionPropertiesFUCHSIA -> IO Result) -> Ptr Device_T -> BufferCollectionFUCHSIA -> Ptr BufferCollectionPropertiesFUCHSIA -> IO Result -- | vkGetBufferCollectionPropertiesFUCHSIA - Retrieve properties from a -- buffer collection -- -- = Description -- -- For image-based buffer collections, upon calling -- 'getBufferCollectionPropertiesFUCHSIA', Sysmem will choose an element of -- the 'ImageConstraintsInfoFUCHSIA'::@pImageCreateInfos@ established by -- the preceding call to 'setBufferCollectionImageConstraintsFUCHSIA'. The -- index of the element chosen is stored in and can be retrieved from -- 'BufferCollectionPropertiesFUCHSIA'::@createInfoIndex@. -- -- For buffer-based buffer collections, a single -- 'Vulkan.Core10.Buffer.BufferCreateInfo' is specified as -- 'BufferConstraintsInfoFUCHSIA'::@createInfo@. -- 'BufferCollectionPropertiesFUCHSIA'::@createInfoIndex@ will therefore -- always be zero. -- -- 'getBufferCollectionPropertiesFUCHSIA' /may/ fail if Sysmem is unable to -- resolve the constraints of all of the participants in the buffer -- collection. If that occurs, 'getBufferCollectionPropertiesFUCHSIA' will -- return 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED'. -- -- == Valid Usage -- -- - #VUID-vkGetBufferCollectionPropertiesFUCHSIA-None-06405# Prior to -- calling 'getBufferCollectionPropertiesFUCHSIA', the constraints on -- the buffer collection /must/ have been set by either -- 'setBufferCollectionImageConstraintsFUCHSIA' or -- 'setBufferCollectionBufferConstraintsFUCHSIA'. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetBufferCollectionPropertiesFUCHSIA-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetBufferCollectionPropertiesFUCHSIA-collection-parameter# -- @collection@ /must/ be a valid -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle -- -- - #VUID-vkGetBufferCollectionPropertiesFUCHSIA-pProperties-parameter# -- @pProperties@ /must/ be a valid pointer to a -- 'BufferCollectionPropertiesFUCHSIA' structure -- -- - #VUID-vkGetBufferCollectionPropertiesFUCHSIA-collection-parent# -- @collection@ /must/ have been created, allocated, or retrieved from -- @device@ -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'BufferCollectionPropertiesFUCHSIA', 'Vulkan.Core10.Handles.Device' getBufferCollectionPropertiesFUCHSIA :: forall io . (MonadIO io) => -- | @device@ is the logical device handle Device -> -- | @collection@ is the 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- handle BufferCollectionFUCHSIA -> io (BufferCollectionPropertiesFUCHSIA) getBufferCollectionPropertiesFUCHSIA device collection = liftIO . evalContT $ do let vkGetBufferCollectionPropertiesFUCHSIAPtr = pVkGetBufferCollectionPropertiesFUCHSIA (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkGetBufferCollectionPropertiesFUCHSIAPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetBufferCollectionPropertiesFUCHSIA is null" Nothing Nothing let vkGetBufferCollectionPropertiesFUCHSIA' = mkVkGetBufferCollectionPropertiesFUCHSIA vkGetBufferCollectionPropertiesFUCHSIAPtr pPProperties <- ContT (withZeroCStruct @BufferCollectionPropertiesFUCHSIA) r <- lift $ traceAroundEvent "vkGetBufferCollectionPropertiesFUCHSIA" (vkGetBufferCollectionPropertiesFUCHSIA' (deviceHandle (device)) (collection) (pPProperties)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pProperties <- lift $ peekCStruct @BufferCollectionPropertiesFUCHSIA pPProperties pure $ (pProperties) -- | VkImportMemoryBufferCollectionFUCHSIA - Structure to specify the Sysmem -- buffer to import -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data ImportMemoryBufferCollectionFUCHSIA = ImportMemoryBufferCollectionFUCHSIA { -- | @collection@ is the 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- handle -- -- #VUID-VkImportMemoryBufferCollectionFUCHSIA-collection-parameter# -- @collection@ /must/ be a valid -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle collection :: BufferCollectionFUCHSIA , -- | @index@ the index of the buffer to import from @collection@ -- -- #VUID-VkImportMemoryBufferCollectionFUCHSIA-index-06406# @index@ /must/ -- be less than the value retrieved as -- 'BufferCollectionPropertiesFUCHSIA':bufferCount index :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImportMemoryBufferCollectionFUCHSIA) #endif deriving instance Show ImportMemoryBufferCollectionFUCHSIA instance ToCStruct ImportMemoryBufferCollectionFUCHSIA where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImportMemoryBufferCollectionFUCHSIA{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMPORT_MEMORY_BUFFER_COLLECTION_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) (collection) poke ((p `plusPtr` 24 :: Ptr Word32)) (index) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMPORT_MEMORY_BUFFER_COLLECTION_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) f instance FromCStruct ImportMemoryBufferCollectionFUCHSIA where peekCStruct p = do collection <- peek @BufferCollectionFUCHSIA ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) index <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) pure $ ImportMemoryBufferCollectionFUCHSIA collection index instance Storable ImportMemoryBufferCollectionFUCHSIA where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero ImportMemoryBufferCollectionFUCHSIA where zero = ImportMemoryBufferCollectionFUCHSIA zero zero -- | VkBufferCollectionImageCreateInfoFUCHSIA - Create a -- VkBufferCollectionFUCHSIA-compatible VkImage -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data BufferCollectionImageCreateInfoFUCHSIA = BufferCollectionImageCreateInfoFUCHSIA { -- | @collection@ is the 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- handle -- -- #VUID-VkBufferCollectionImageCreateInfoFUCHSIA-collection-parameter# -- @collection@ /must/ be a valid -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle collection :: BufferCollectionFUCHSIA , -- | @index@ is the index of the buffer in the buffer collection from which -- the memory will be imported -- -- #VUID-VkBufferCollectionImageCreateInfoFUCHSIA-index-06391# @index@ -- /must/ be less than 'BufferCollectionPropertiesFUCHSIA'::@bufferCount@ index :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (BufferCollectionImageCreateInfoFUCHSIA) #endif deriving instance Show BufferCollectionImageCreateInfoFUCHSIA instance ToCStruct BufferCollectionImageCreateInfoFUCHSIA where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p BufferCollectionImageCreateInfoFUCHSIA{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_IMAGE_CREATE_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) (collection) poke ((p `plusPtr` 24 :: Ptr Word32)) (index) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_IMAGE_CREATE_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) f instance FromCStruct BufferCollectionImageCreateInfoFUCHSIA where peekCStruct p = do collection <- peek @BufferCollectionFUCHSIA ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) index <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) pure $ BufferCollectionImageCreateInfoFUCHSIA collection index instance Storable BufferCollectionImageCreateInfoFUCHSIA where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BufferCollectionImageCreateInfoFUCHSIA where zero = BufferCollectionImageCreateInfoFUCHSIA zero zero -- | VkBufferCollectionBufferCreateInfoFUCHSIA - Create a -- VkBufferCollectionFUCHSIA-compatible VkBuffer -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data BufferCollectionBufferCreateInfoFUCHSIA = BufferCollectionBufferCreateInfoFUCHSIA { -- | @collection@ is the 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- handle -- -- #VUID-VkBufferCollectionBufferCreateInfoFUCHSIA-collection-parameter# -- @collection@ /must/ be a valid -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' handle collection :: BufferCollectionFUCHSIA , -- | @index@ is the index of the buffer in the buffer collection from which -- the memory will be imported -- -- #VUID-VkBufferCollectionBufferCreateInfoFUCHSIA-index-06388# @index@ -- /must/ be less than 'BufferCollectionPropertiesFUCHSIA'::@bufferCount@ index :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (BufferCollectionBufferCreateInfoFUCHSIA) #endif deriving instance Show BufferCollectionBufferCreateInfoFUCHSIA instance ToCStruct BufferCollectionBufferCreateInfoFUCHSIA where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p BufferCollectionBufferCreateInfoFUCHSIA{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_BUFFER_CREATE_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) (collection) poke ((p `plusPtr` 24 :: Ptr Word32)) (index) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_BUFFER_CREATE_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) f instance FromCStruct BufferCollectionBufferCreateInfoFUCHSIA where peekCStruct p = do collection <- peek @BufferCollectionFUCHSIA ((p `plusPtr` 16 :: Ptr BufferCollectionFUCHSIA)) index <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) pure $ BufferCollectionBufferCreateInfoFUCHSIA collection index instance Storable BufferCollectionBufferCreateInfoFUCHSIA where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BufferCollectionBufferCreateInfoFUCHSIA where zero = BufferCollectionBufferCreateInfoFUCHSIA zero zero -- | VkBufferCollectionCreateInfoFUCHSIA - Structure specifying desired -- parameters to create the buffer collection -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'createBufferCollectionFUCHSIA' data BufferCollectionCreateInfoFUCHSIA = BufferCollectionCreateInfoFUCHSIA { -- | @collectionToken@ is a @zx_handle_t@ containing the Sysmem client’s -- buffer collection token -- -- #VUID-VkBufferCollectionCreateInfoFUCHSIA-collectionToken-06393# -- @collectionToken@ /must/ be a valid @zx_handle_t@ to a Zircon channel -- allocated from Sysmem -- (@fuchsia.sysmem.Allocator@\/AllocateSharedCollection) with -- @ZX_DEFAULT_CHANNEL_RIGHTS@ rights collectionToken :: Zx_handle_t } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (BufferCollectionCreateInfoFUCHSIA) #endif deriving instance Show BufferCollectionCreateInfoFUCHSIA instance ToCStruct BufferCollectionCreateInfoFUCHSIA where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p BufferCollectionCreateInfoFUCHSIA{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_CREATE_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Zx_handle_t)) (collectionToken) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_CREATE_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Zx_handle_t)) (zero) f instance FromCStruct BufferCollectionCreateInfoFUCHSIA where peekCStruct p = do collectionToken <- peek @Zx_handle_t ((p `plusPtr` 16 :: Ptr Zx_handle_t)) pure $ BufferCollectionCreateInfoFUCHSIA collectionToken instance Storable BufferCollectionCreateInfoFUCHSIA where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BufferCollectionCreateInfoFUCHSIA where zero = BufferCollectionCreateInfoFUCHSIA zero -- | VkBufferCollectionPropertiesFUCHSIA - Structure specifying the -- negotiated format chosen by Sysmem -- -- = Description -- -- @sysmemColorSpace@ is only set for image-based buffer collections where -- the constraints were specified using 'ImageConstraintsInfoFUCHSIA' in a -- call to 'setBufferCollectionImageConstraintsFUCHSIA'. -- -- For image-based buffer collections, @createInfoIndex@ will identify both -- the 'ImageConstraintsInfoFUCHSIA'::@pImageCreateInfos@ element and the -- 'ImageConstraintsInfoFUCHSIA'::@pFormatConstraints@ element chosen by -- Sysmem when 'setBufferCollectionImageConstraintsFUCHSIA' was called. The -- value of @sysmemColorSpaceIndex@ will be an index to one of the color -- spaces provided in the -- 'ImageFormatConstraintsInfoFUCHSIA'::@pColorSpaces@ array. -- -- The implementation must have @formatFeatures@ with all bits set that -- were set in -- 'ImageFormatConstraintsInfoFUCHSIA'::@requiredFormatFeatures@, by the -- call to 'setBufferCollectionImageConstraintsFUCHSIA', at -- @createInfoIndex@ (other bits could be set as well). -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation', -- 'Vulkan.Core10.ImageView.ComponentMapping', -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlags', -- 'Vulkan.Core11.Enums.SamplerYcbcrModelConversion.SamplerYcbcrModelConversion', -- 'Vulkan.Core11.Enums.SamplerYcbcrRange.SamplerYcbcrRange', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'SysmemColorSpaceFUCHSIA', 'getBufferCollectionPropertiesFUCHSIA' data BufferCollectionPropertiesFUCHSIA = BufferCollectionPropertiesFUCHSIA { -- | @memoryTypeBits@ is a bitmask containing one bit set for every memory -- type which the buffer collection can be imported as buffer collection memoryTypeBits :: Word32 , -- | @bufferCount@ is the number of buffers in the collection bufferCount :: Word32 , -- | @createInfoIndex@ as described in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#sysmem-chosen-create-infos Sysmem chosen create infos> createInfoIndex :: Word32 , -- | @sysmemPixelFormat@ is the Sysmem @PixelFormatType@ as defined in -- @fuchsia.sysmem\/image_formats.fidl@ sysmemPixelFormat :: Word64 , -- | @formatFeatures@ is a bitmask of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits' shared -- by the buffer collection -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-formatFeatures-parameter# -- @formatFeatures@ /must/ be a valid combination of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits' values -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-formatFeatures-requiredbitmask# -- @formatFeatures@ /must/ not be @0@ formatFeatures :: FormatFeatureFlags , -- | @sysmemColorSpaceIndex@ is a 'SysmemColorSpaceFUCHSIA' struct specifying -- the color space -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-sysmemColorSpaceIndex-parameter# -- @sysmemColorSpaceIndex@ /must/ be a valid 'SysmemColorSpaceFUCHSIA' -- structure sysmemColorSpaceIndex :: SysmemColorSpaceFUCHSIA , -- | @samplerYcbcrConversionComponents@ is a -- 'Vulkan.Core10.ImageView.ComponentMapping' struct specifying the -- component mapping -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-samplerYcbcrConversionComponents-parameter# -- @samplerYcbcrConversionComponents@ /must/ be a valid -- 'Vulkan.Core10.ImageView.ComponentMapping' structure samplerYcbcrConversionComponents :: ComponentMapping , -- | @suggestedYcbcrModel@ is a -- 'Vulkan.Core11.Enums.SamplerYcbcrModelConversion.SamplerYcbcrModelConversion' -- value specifying the suggested Y′CBCR model -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-suggestedYcbcrModel-parameter# -- @suggestedYcbcrModel@ /must/ be a valid -- 'Vulkan.Core11.Enums.SamplerYcbcrModelConversion.SamplerYcbcrModelConversion' -- value suggestedYcbcrModel :: SamplerYcbcrModelConversion , -- | @suggestedYcbcrRange@ is a -- 'Vulkan.Core11.Enums.SamplerYcbcrRange.SamplerYcbcrRange' value -- specifying the suggested Y′CBCR range -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-suggestedYcbcrRange-parameter# -- @suggestedYcbcrRange@ /must/ be a valid -- 'Vulkan.Core11.Enums.SamplerYcbcrRange.SamplerYcbcrRange' value suggestedYcbcrRange :: SamplerYcbcrRange , -- | @suggestedXChromaOffset@ is a -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation' value specifying the -- suggested X chroma offset -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-suggestedXChromaOffset-parameter# -- @suggestedXChromaOffset@ /must/ be a valid -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation' value suggestedXChromaOffset :: ChromaLocation , -- | @suggestedYChromaOffset@ is a -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation' value specifying the -- suggested Y chroma offset -- -- #VUID-VkBufferCollectionPropertiesFUCHSIA-suggestedYChromaOffset-parameter# -- @suggestedYChromaOffset@ /must/ be a valid -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation' value suggestedYChromaOffset :: ChromaLocation } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (BufferCollectionPropertiesFUCHSIA) #endif deriving instance Show BufferCollectionPropertiesFUCHSIA instance ToCStruct BufferCollectionPropertiesFUCHSIA where withCStruct x f = allocaBytes 104 $ \p -> pokeCStruct p x (f p) pokeCStruct p BufferCollectionPropertiesFUCHSIA{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_PROPERTIES_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (memoryTypeBits) poke ((p `plusPtr` 20 :: Ptr Word32)) (bufferCount) poke ((p `plusPtr` 24 :: Ptr Word32)) (createInfoIndex) poke ((p `plusPtr` 32 :: Ptr Word64)) (sysmemPixelFormat) poke ((p `plusPtr` 40 :: Ptr FormatFeatureFlags)) (formatFeatures) poke ((p `plusPtr` 48 :: Ptr SysmemColorSpaceFUCHSIA)) (sysmemColorSpaceIndex) poke ((p `plusPtr` 72 :: Ptr ComponentMapping)) (samplerYcbcrConversionComponents) poke ((p `plusPtr` 88 :: Ptr SamplerYcbcrModelConversion)) (suggestedYcbcrModel) poke ((p `plusPtr` 92 :: Ptr SamplerYcbcrRange)) (suggestedYcbcrRange) poke ((p `plusPtr` 96 :: Ptr ChromaLocation)) (suggestedXChromaOffset) poke ((p `plusPtr` 100 :: Ptr ChromaLocation)) (suggestedYChromaOffset) f cStructSize = 104 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_PROPERTIES_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (zero) poke ((p `plusPtr` 20 :: Ptr Word32)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) poke ((p `plusPtr` 32 :: Ptr Word64)) (zero) poke ((p `plusPtr` 40 :: Ptr FormatFeatureFlags)) (zero) poke ((p `plusPtr` 48 :: Ptr SysmemColorSpaceFUCHSIA)) (zero) poke ((p `plusPtr` 72 :: Ptr ComponentMapping)) (zero) poke ((p `plusPtr` 88 :: Ptr SamplerYcbcrModelConversion)) (zero) poke ((p `plusPtr` 92 :: Ptr SamplerYcbcrRange)) (zero) poke ((p `plusPtr` 96 :: Ptr ChromaLocation)) (zero) poke ((p `plusPtr` 100 :: Ptr ChromaLocation)) (zero) f instance FromCStruct BufferCollectionPropertiesFUCHSIA where peekCStruct p = do memoryTypeBits <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) bufferCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) createInfoIndex <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) sysmemPixelFormat <- peek @Word64 ((p `plusPtr` 32 :: Ptr Word64)) formatFeatures <- peek @FormatFeatureFlags ((p `plusPtr` 40 :: Ptr FormatFeatureFlags)) sysmemColorSpaceIndex <- peekCStruct @SysmemColorSpaceFUCHSIA ((p `plusPtr` 48 :: Ptr SysmemColorSpaceFUCHSIA)) samplerYcbcrConversionComponents <- peekCStruct @ComponentMapping ((p `plusPtr` 72 :: Ptr ComponentMapping)) suggestedYcbcrModel <- peek @SamplerYcbcrModelConversion ((p `plusPtr` 88 :: Ptr SamplerYcbcrModelConversion)) suggestedYcbcrRange <- peek @SamplerYcbcrRange ((p `plusPtr` 92 :: Ptr SamplerYcbcrRange)) suggestedXChromaOffset <- peek @ChromaLocation ((p `plusPtr` 96 :: Ptr ChromaLocation)) suggestedYChromaOffset <- peek @ChromaLocation ((p `plusPtr` 100 :: Ptr ChromaLocation)) pure $ BufferCollectionPropertiesFUCHSIA memoryTypeBits bufferCount createInfoIndex sysmemPixelFormat formatFeatures sysmemColorSpaceIndex samplerYcbcrConversionComponents suggestedYcbcrModel suggestedYcbcrRange suggestedXChromaOffset suggestedYChromaOffset instance Storable BufferCollectionPropertiesFUCHSIA where sizeOf ~_ = 104 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BufferCollectionPropertiesFUCHSIA where zero = BufferCollectionPropertiesFUCHSIA zero zero zero zero zero zero zero zero zero zero zero -- | VkBufferConstraintsInfoFUCHSIA - Structure buffer-based buffer -- collection constraints -- -- == Valid Usage -- -- - #VUID-VkBufferConstraintsInfoFUCHSIA-requiredFormatFeatures-06404# -- The @requiredFormatFeatures@ bitmask of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits' -- /must/ be chosen from among the buffer compatible format features -- listed in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#buffer-compatible-format-features buffer compatible format features> -- -- == Valid Usage (Implicit) -- -- - #VUID-VkBufferConstraintsInfoFUCHSIA-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_CONSTRAINTS_INFO_FUCHSIA' -- -- - #VUID-VkBufferConstraintsInfoFUCHSIA-pNext-pNext# @pNext@ /must/ be -- @NULL@ -- -- - #VUID-VkBufferConstraintsInfoFUCHSIA-createInfo-parameter# -- @createInfo@ /must/ be a valid -- 'Vulkan.Core10.Buffer.BufferCreateInfo' structure -- -- - #VUID-VkBufferConstraintsInfoFUCHSIA-requiredFormatFeatures-parameter# -- @requiredFormatFeatures@ /must/ be a valid combination of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits' -- values -- -- - #VUID-VkBufferConstraintsInfoFUCHSIA-bufferCollectionConstraints-parameter# -- @bufferCollectionConstraints@ /must/ be a valid -- 'BufferCollectionConstraintsInfoFUCHSIA' structure -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'BufferCollectionConstraintsInfoFUCHSIA', -- 'Vulkan.Core10.Buffer.BufferCreateInfo', -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlags', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'setBufferCollectionBufferConstraintsFUCHSIA' data BufferConstraintsInfoFUCHSIA = BufferConstraintsInfoFUCHSIA { -- No documentation found for Nested "VkBufferConstraintsInfoFUCHSIA" "createInfo" createInfo :: SomeStruct BufferCreateInfo , -- | @requiredFormatFeatures@ bitmask of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits' -- required features of the buffers in the buffer collection requiredFormatFeatures :: FormatFeatureFlags , -- | @bufferCollectionConstraints@ is used to supply parameters for the -- negotiation and allocation of the buffer collection bufferCollectionConstraints :: BufferCollectionConstraintsInfoFUCHSIA } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (BufferConstraintsInfoFUCHSIA) #endif deriving instance Show BufferConstraintsInfoFUCHSIA instance ToCStruct BufferConstraintsInfoFUCHSIA where withCStruct x f = allocaBytes 120 $ \p -> pokeCStruct p x (f p) pokeCStruct p BufferConstraintsInfoFUCHSIA{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_CONSTRAINTS_INFO_FUCHSIA) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) ContT $ pokeSomeCStruct (forgetExtensions ((p `plusPtr` 16 :: Ptr (BufferCreateInfo _)))) (createInfo) . ($ ()) lift $ poke ((p `plusPtr` 72 :: Ptr FormatFeatureFlags)) (requiredFormatFeatures) lift $ poke ((p `plusPtr` 80 :: Ptr BufferCollectionConstraintsInfoFUCHSIA)) (bufferCollectionConstraints) lift $ f cStructSize = 120 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_CONSTRAINTS_INFO_FUCHSIA) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) ContT $ pokeSomeCStruct (forgetExtensions ((p `plusPtr` 16 :: Ptr (BufferCreateInfo _)))) ((SomeStruct zero)) . ($ ()) lift $ poke ((p `plusPtr` 80 :: Ptr BufferCollectionConstraintsInfoFUCHSIA)) (zero) lift $ f instance FromCStruct BufferConstraintsInfoFUCHSIA where peekCStruct p = do createInfo <- peekSomeCStruct (forgetExtensions ((p `plusPtr` 16 :: Ptr (BufferCreateInfo _)))) requiredFormatFeatures <- peek @FormatFeatureFlags ((p `plusPtr` 72 :: Ptr FormatFeatureFlags)) bufferCollectionConstraints <- peekCStruct @BufferCollectionConstraintsInfoFUCHSIA ((p `plusPtr` 80 :: Ptr BufferCollectionConstraintsInfoFUCHSIA)) pure $ BufferConstraintsInfoFUCHSIA createInfo requiredFormatFeatures bufferCollectionConstraints instance Zero BufferConstraintsInfoFUCHSIA where zero = BufferConstraintsInfoFUCHSIA (SomeStruct zero) zero zero -- | VkSysmemColorSpaceFUCHSIA - Structure describing the buffer collections -- color space -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'BufferCollectionPropertiesFUCHSIA', -- 'ImageFormatConstraintsInfoFUCHSIA', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data SysmemColorSpaceFUCHSIA = SysmemColorSpaceFUCHSIA { -- | @colorSpace@ value of the Sysmem @ColorSpaceType@ -- -- #VUID-VkSysmemColorSpaceFUCHSIA-colorSpace-06402# @colorSpace@ /must/ be -- a @ColorSpaceType@ as defined in @fuchsia.sysmem\/image_formats.fidl@ colorSpace :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SysmemColorSpaceFUCHSIA) #endif deriving instance Show SysmemColorSpaceFUCHSIA instance ToCStruct SysmemColorSpaceFUCHSIA where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p SysmemColorSpaceFUCHSIA{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SYSMEM_COLOR_SPACE_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (colorSpace) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SYSMEM_COLOR_SPACE_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (zero) f instance FromCStruct SysmemColorSpaceFUCHSIA where peekCStruct p = do colorSpace <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pure $ SysmemColorSpaceFUCHSIA colorSpace instance Storable SysmemColorSpaceFUCHSIA where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SysmemColorSpaceFUCHSIA where zero = SysmemColorSpaceFUCHSIA zero -- | VkImageFormatConstraintsInfoFUCHSIA - Structure image-based buffer -- collection constraints -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlags', -- 'ImageConstraintsInfoFUCHSIA', 'Vulkan.Core10.Image.ImageCreateInfo', -- 'ImageFormatConstraintsFlagsFUCHSIA', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'SysmemColorSpaceFUCHSIA' data ImageFormatConstraintsInfoFUCHSIA = ImageFormatConstraintsInfoFUCHSIA { -- | @imageCreateInfo@ is the 'Vulkan.Core10.Image.ImageCreateInfo' used to -- create a 'Vulkan.Core10.Handles.Image' that is to use memory from the -- 'Vulkan.Extensions.Handles.BufferCollectionFUCHSIA' -- -- #VUID-VkImageFormatConstraintsInfoFUCHSIA-imageCreateInfo-parameter# -- @imageCreateInfo@ /must/ be a valid -- 'Vulkan.Core10.Image.ImageCreateInfo' structure imageCreateInfo :: SomeStruct ImageCreateInfo , -- | @requiredFormatFeatures@ is a bitmask of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits' -- specifying required features of the buffers in the buffer collection -- -- #VUID-VkImageFormatConstraintsInfoFUCHSIA-requiredFormatFeatures-parameter# -- @requiredFormatFeatures@ /must/ be a valid combination of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits' values -- -- #VUID-VkImageFormatConstraintsInfoFUCHSIA-requiredFormatFeatures-requiredbitmask# -- @requiredFormatFeatures@ /must/ not be @0@ requiredFormatFeatures :: FormatFeatureFlags , -- | @flags@ is reserved for future use -- -- #VUID-VkImageFormatConstraintsInfoFUCHSIA-flags-zerobitmask# @flags@ -- /must/ be @0@ flags :: ImageFormatConstraintsFlagsFUCHSIA , -- | @sysmemPixelFormat@ is a @PixelFormatType@ value from the -- @fuchsia.sysmem\/image_formats.fidl@ FIDL interface sysmemPixelFormat :: Word64 , -- | @pColorSpaces@ is a pointer to an array of 'SysmemColorSpaceFUCHSIA' -- structs of size @colorSpaceCount@ -- -- #VUID-VkImageFormatConstraintsInfoFUCHSIA-pColorSpaces-parameter# -- @pColorSpaces@ /must/ be a valid pointer to an array of -- @colorSpaceCount@ valid 'SysmemColorSpaceFUCHSIA' structures colorSpaces :: Vector SysmemColorSpaceFUCHSIA } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImageFormatConstraintsInfoFUCHSIA) #endif deriving instance Show ImageFormatConstraintsInfoFUCHSIA instance ToCStruct ImageFormatConstraintsInfoFUCHSIA where withCStruct x f = allocaBytes 136 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImageFormatConstraintsInfoFUCHSIA{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_FORMAT_CONSTRAINTS_INFO_FUCHSIA) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) ContT $ pokeSomeCStruct (forgetExtensions ((p `plusPtr` 16 :: Ptr (ImageCreateInfo _)))) (imageCreateInfo) . ($ ()) lift $ poke ((p `plusPtr` 104 :: Ptr FormatFeatureFlags)) (requiredFormatFeatures) lift $ poke ((p `plusPtr` 108 :: Ptr ImageFormatConstraintsFlagsFUCHSIA)) (flags) lift $ poke ((p `plusPtr` 112 :: Ptr Word64)) (sysmemPixelFormat) lift $ poke ((p `plusPtr` 120 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (colorSpaces)) :: Word32)) pPColorSpaces' <- ContT $ allocaBytes @SysmemColorSpaceFUCHSIA ((Data.Vector.length (colorSpaces)) * 24) lift $ Data.Vector.imapM_ (\i e -> poke (pPColorSpaces' `plusPtr` (24 * (i)) :: Ptr SysmemColorSpaceFUCHSIA) (e)) (colorSpaces) lift $ poke ((p `plusPtr` 128 :: Ptr (Ptr SysmemColorSpaceFUCHSIA))) (pPColorSpaces') lift $ f cStructSize = 136 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_FORMAT_CONSTRAINTS_INFO_FUCHSIA) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) ContT $ pokeSomeCStruct (forgetExtensions ((p `plusPtr` 16 :: Ptr (ImageCreateInfo _)))) ((SomeStruct zero)) . ($ ()) lift $ poke ((p `plusPtr` 104 :: Ptr FormatFeatureFlags)) (zero) lift $ f instance FromCStruct ImageFormatConstraintsInfoFUCHSIA where peekCStruct p = do imageCreateInfo <- peekSomeCStruct (forgetExtensions ((p `plusPtr` 16 :: Ptr (ImageCreateInfo _)))) requiredFormatFeatures <- peek @FormatFeatureFlags ((p `plusPtr` 104 :: Ptr FormatFeatureFlags)) flags <- peek @ImageFormatConstraintsFlagsFUCHSIA ((p `plusPtr` 108 :: Ptr ImageFormatConstraintsFlagsFUCHSIA)) sysmemPixelFormat <- peek @Word64 ((p `plusPtr` 112 :: Ptr Word64)) colorSpaceCount <- peek @Word32 ((p `plusPtr` 120 :: Ptr Word32)) pColorSpaces <- peek @(Ptr SysmemColorSpaceFUCHSIA) ((p `plusPtr` 128 :: Ptr (Ptr SysmemColorSpaceFUCHSIA))) pColorSpaces' <- generateM (fromIntegral colorSpaceCount) (\i -> peekCStruct @SysmemColorSpaceFUCHSIA ((pColorSpaces `advancePtrBytes` (24 * (i)) :: Ptr SysmemColorSpaceFUCHSIA))) pure $ ImageFormatConstraintsInfoFUCHSIA imageCreateInfo requiredFormatFeatures flags sysmemPixelFormat pColorSpaces' instance Zero ImageFormatConstraintsInfoFUCHSIA where zero = ImageFormatConstraintsInfoFUCHSIA (SomeStruct zero) zero zero zero mempty -- | VkImageConstraintsInfoFUCHSIA - Structure of image-based buffer -- collection constraints -- -- == Valid Usage -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pFormatConstraints-06395# All -- elements of @pFormatConstraints@ /must/ have at least one bit set in -- its 'ImageFormatConstraintsInfoFUCHSIA'::@requiredFormatFeatures@ -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pFormatConstraints-06396# If -- @pFormatConstraints@::@imageCreateInfo@::@usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_SAMPLED_BIT', -- then @pFormatConstraints@::@requiredFormatFeatures@ /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_BIT' -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pFormatConstraints-06397# If -- @pFormatConstraints@::@imageCreateInfo@::@usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_STORAGE_BIT', -- then @pFormatConstraints@::@requiredFormatFeatures@ /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_STORAGE_IMAGE_BIT' -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pFormatConstraints-06398# If -- @pFormatConstraints@::@imageCreateInfo@::@usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_COLOR_ATTACHMENT_BIT', -- then @pFormatConstraints@::@requiredFormatFeatures@ /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_COLOR_ATTACHMENT_BIT' -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pFormatConstraints-06399# If -- @pFormatConstraints@::@imageCreateInfo@::@usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT', -- then @pFormatConstraints@::@requiredFormatFeatures@ /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT' -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pFormatConstraints-06400# If -- @pFormatConstraints@::@imageCreateInfo@::@usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_INPUT_ATTACHMENT_BIT', -- then @pFormatConstraints@::@requiredFormatFeatures@ /must/ contain -- at least one of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_COLOR_ATTACHMENT_BIT' -- or -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT' -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-attachmentFragmentShadingRate-06401# -- If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-attachmentFragmentShadingRate attachmentFragmentShadingRate feature> -- is enabled, and @pFormatConstraints@::@imageCreateInfo@::@usage@ -- contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR', -- then @pFormatConstraints@::@requiredFormatFeatures@ /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_CONSTRAINTS_INFO_FUCHSIA' -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pNext-pNext# @pNext@ /must/ be -- @NULL@ -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-pFormatConstraints-parameter# -- @pFormatConstraints@ /must/ be a valid pointer to an array of -- @formatConstraintsCount@ valid 'ImageFormatConstraintsInfoFUCHSIA' -- structures -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-bufferCollectionConstraints-parameter# -- @bufferCollectionConstraints@ /must/ be a valid -- 'BufferCollectionConstraintsInfoFUCHSIA' structure -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-flags-parameter# @flags@ /must/ -- be a valid combination of 'ImageConstraintsInfoFlagBitsFUCHSIA' -- values -- -- - #VUID-VkImageConstraintsInfoFUCHSIA-formatConstraintsCount-arraylength# -- @formatConstraintsCount@ /must/ be greater than @0@ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'BufferCollectionConstraintsInfoFUCHSIA', -- 'ImageConstraintsInfoFlagsFUCHSIA', 'ImageFormatConstraintsInfoFUCHSIA', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'setBufferCollectionImageConstraintsFUCHSIA' data ImageConstraintsInfoFUCHSIA = ImageConstraintsInfoFUCHSIA { -- | @pFormatConstraints@ is a pointer to an array of -- 'ImageFormatConstraintsInfoFUCHSIA' structures of size -- @formatConstraintsCount@ that is used to further constrain buffer -- collection format selection for image-based buffer collections. formatConstraints :: Vector ImageFormatConstraintsInfoFUCHSIA , -- | @bufferCollectionConstraints@ is a -- 'BufferCollectionConstraintsInfoFUCHSIA' structure used to supply -- parameters for the negotiation and allocation for buffer-based buffer -- collections. bufferCollectionConstraints :: BufferCollectionConstraintsInfoFUCHSIA , -- | @flags@ is a 'ImageConstraintsInfoFlagBitsFUCHSIA' value specifying -- hints about the type of memory Sysmem should allocate for the buffer -- collection. flags :: ImageConstraintsInfoFlagsFUCHSIA } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImageConstraintsInfoFUCHSIA) #endif deriving instance Show ImageConstraintsInfoFUCHSIA instance ToCStruct ImageConstraintsInfoFUCHSIA where withCStruct x f = allocaBytes 80 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImageConstraintsInfoFUCHSIA{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_CONSTRAINTS_INFO_FUCHSIA) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (formatConstraints)) :: Word32)) pPFormatConstraints' <- ContT $ allocaBytes @ImageFormatConstraintsInfoFUCHSIA ((Data.Vector.length (formatConstraints)) * 136) Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPFormatConstraints' `plusPtr` (136 * (i)) :: Ptr ImageFormatConstraintsInfoFUCHSIA) (e) . ($ ())) (formatConstraints) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr ImageFormatConstraintsInfoFUCHSIA))) (pPFormatConstraints') lift $ poke ((p `plusPtr` 32 :: Ptr BufferCollectionConstraintsInfoFUCHSIA)) (bufferCollectionConstraints) lift $ poke ((p `plusPtr` 72 :: Ptr ImageConstraintsInfoFlagsFUCHSIA)) (flags) lift $ f cStructSize = 80 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_CONSTRAINTS_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 32 :: Ptr BufferCollectionConstraintsInfoFUCHSIA)) (zero) f instance FromCStruct ImageConstraintsInfoFUCHSIA where peekCStruct p = do formatConstraintsCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pFormatConstraints <- peek @(Ptr ImageFormatConstraintsInfoFUCHSIA) ((p `plusPtr` 24 :: Ptr (Ptr ImageFormatConstraintsInfoFUCHSIA))) pFormatConstraints' <- generateM (fromIntegral formatConstraintsCount) (\i -> peekCStruct @ImageFormatConstraintsInfoFUCHSIA ((pFormatConstraints `advancePtrBytes` (136 * (i)) :: Ptr ImageFormatConstraintsInfoFUCHSIA))) bufferCollectionConstraints <- peekCStruct @BufferCollectionConstraintsInfoFUCHSIA ((p `plusPtr` 32 :: Ptr BufferCollectionConstraintsInfoFUCHSIA)) flags <- peek @ImageConstraintsInfoFlagsFUCHSIA ((p `plusPtr` 72 :: Ptr ImageConstraintsInfoFlagsFUCHSIA)) pure $ ImageConstraintsInfoFUCHSIA pFormatConstraints' bufferCollectionConstraints flags instance Zero ImageConstraintsInfoFUCHSIA where zero = ImageConstraintsInfoFUCHSIA mempty zero zero -- | VkBufferCollectionConstraintsInfoFUCHSIA - Structure of general buffer -- collection constraints -- -- = Description -- -- Sysmem uses all buffer count parameters in combination to determine the -- number of buffers it will allocate. Sysmem defines buffer count -- constraints in @fuchsia.sysmem\/constraints.fidl@. -- -- /Camping/ as referred to by @minBufferCountForCamping@, is the number of -- buffers that should be available for the participant that are not for -- transient use. This number of buffers is required for the participant to -- logically operate. -- -- /Slack/ as referred to by @minBufferCountForDedicatedSlack@ and -- @minBufferCountForSharedSlack@, refers to the number of buffers desired -- by participants for optimal performance. -- @minBufferCountForDedicatedSlack@ refers to the current participant. -- @minBufferCountForSharedSlack@ refers to buffer slack for all -- participants in the collection. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'BufferConstraintsInfoFUCHSIA', 'ImageConstraintsInfoFUCHSIA', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data BufferCollectionConstraintsInfoFUCHSIA = BufferCollectionConstraintsInfoFUCHSIA { -- | @minBufferCount@ is the minimum number of buffers available in the -- collection minBufferCount :: Word32 , -- | @maxBufferCount@ is the maximum number of buffers allowed in the -- collection maxBufferCount :: Word32 , -- | @minBufferCountForCamping@ is the per-participant minimum buffers for -- camping minBufferCountForCamping :: Word32 , -- | @minBufferCountForDedicatedSlack@ is the per-participant minimum buffers -- for dedicated slack minBufferCountForDedicatedSlack :: Word32 , -- | @minBufferCountForSharedSlack@ is the per-participant minimum buffers -- for shared slack minBufferCountForSharedSlack :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (BufferCollectionConstraintsInfoFUCHSIA) #endif deriving instance Show BufferCollectionConstraintsInfoFUCHSIA instance ToCStruct BufferCollectionConstraintsInfoFUCHSIA where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p BufferCollectionConstraintsInfoFUCHSIA{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_CONSTRAINTS_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (minBufferCount) poke ((p `plusPtr` 20 :: Ptr Word32)) (maxBufferCount) poke ((p `plusPtr` 24 :: Ptr Word32)) (minBufferCountForCamping) poke ((p `plusPtr` 28 :: Ptr Word32)) (minBufferCountForDedicatedSlack) poke ((p `plusPtr` 32 :: Ptr Word32)) (minBufferCountForSharedSlack) f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_COLLECTION_CONSTRAINTS_INFO_FUCHSIA) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (zero) poke ((p `plusPtr` 20 :: Ptr Word32)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) poke ((p `plusPtr` 28 :: Ptr Word32)) (zero) poke ((p `plusPtr` 32 :: Ptr Word32)) (zero) f instance FromCStruct BufferCollectionConstraintsInfoFUCHSIA where peekCStruct p = do minBufferCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) maxBufferCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) minBufferCountForCamping <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) minBufferCountForDedicatedSlack <- peek @Word32 ((p `plusPtr` 28 :: Ptr Word32)) minBufferCountForSharedSlack <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pure $ BufferCollectionConstraintsInfoFUCHSIA minBufferCount maxBufferCount minBufferCountForCamping minBufferCountForDedicatedSlack minBufferCountForSharedSlack instance Storable BufferCollectionConstraintsInfoFUCHSIA where sizeOf ~_ = 40 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BufferCollectionConstraintsInfoFUCHSIA where zero = BufferCollectionConstraintsInfoFUCHSIA zero zero zero zero zero -- | VkImageFormatConstraintsFlagsFUCHSIA - Reserved for future use -- -- = Description -- -- 'ImageFormatConstraintsFlagsFUCHSIA' is a bitmask type for setting a -- mask, but is currently reserved for future use. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'ImageFormatConstraintsInfoFUCHSIA' newtype ImageFormatConstraintsFlagsFUCHSIA = ImageFormatConstraintsFlagsFUCHSIA Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) conNameImageFormatConstraintsFlagsFUCHSIA :: String conNameImageFormatConstraintsFlagsFUCHSIA = "ImageFormatConstraintsFlagsFUCHSIA" enumPrefixImageFormatConstraintsFlagsFUCHSIA :: String enumPrefixImageFormatConstraintsFlagsFUCHSIA = "" showTableImageFormatConstraintsFlagsFUCHSIA :: [(ImageFormatConstraintsFlagsFUCHSIA, String)] showTableImageFormatConstraintsFlagsFUCHSIA = [] instance Show ImageFormatConstraintsFlagsFUCHSIA where showsPrec = enumShowsPrec enumPrefixImageFormatConstraintsFlagsFUCHSIA showTableImageFormatConstraintsFlagsFUCHSIA conNameImageFormatConstraintsFlagsFUCHSIA (\(ImageFormatConstraintsFlagsFUCHSIA x) -> x) (\x -> showString "0x" . showHex x) instance Read ImageFormatConstraintsFlagsFUCHSIA where readPrec = enumReadPrec enumPrefixImageFormatConstraintsFlagsFUCHSIA showTableImageFormatConstraintsFlagsFUCHSIA conNameImageFormatConstraintsFlagsFUCHSIA ImageFormatConstraintsFlagsFUCHSIA type ImageConstraintsInfoFlagsFUCHSIA = ImageConstraintsInfoFlagBitsFUCHSIA -- | VkImageConstraintsInfoFlagBitsFUCHSIA - Bitmask specifying image -- constraints flags -- -- = Description -- -- General hints about the type of memory that should be allocated by -- Sysmem based on the expected usage of the images in the buffer -- collection include: -- -- For protected memory: -- -- Note that if all participants in the buffer collection (Vulkan or -- otherwise) specify that protected memory is optional, Sysmem will not -- allocate protected memory. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_FUCHSIA_buffer_collection VK_FUCHSIA_buffer_collection>, -- 'ImageConstraintsInfoFlagsFUCHSIA' newtype ImageConstraintsInfoFlagBitsFUCHSIA = ImageConstraintsInfoFlagBitsFUCHSIA Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'IMAGE_CONSTRAINTS_INFO_CPU_READ_RARELY_FUCHSIA' pattern IMAGE_CONSTRAINTS_INFO_CPU_READ_RARELY_FUCHSIA = ImageConstraintsInfoFlagBitsFUCHSIA 0x00000001 -- | 'IMAGE_CONSTRAINTS_INFO_CPU_READ_OFTEN_FUCHSIA' pattern IMAGE_CONSTRAINTS_INFO_CPU_READ_OFTEN_FUCHSIA = ImageConstraintsInfoFlagBitsFUCHSIA 0x00000002 -- | 'IMAGE_CONSTRAINTS_INFO_CPU_WRITE_RARELY_FUCHSIA' pattern IMAGE_CONSTRAINTS_INFO_CPU_WRITE_RARELY_FUCHSIA = ImageConstraintsInfoFlagBitsFUCHSIA 0x00000004 -- | 'IMAGE_CONSTRAINTS_INFO_CPU_WRITE_OFTEN_FUCHSIA' pattern IMAGE_CONSTRAINTS_INFO_CPU_WRITE_OFTEN_FUCHSIA = ImageConstraintsInfoFlagBitsFUCHSIA 0x00000008 -- | 'IMAGE_CONSTRAINTS_INFO_PROTECTED_OPTIONAL_FUCHSIA' specifies that -- protected memory is optional for the buffer collection. pattern IMAGE_CONSTRAINTS_INFO_PROTECTED_OPTIONAL_FUCHSIA = ImageConstraintsInfoFlagBitsFUCHSIA 0x00000010 conNameImageConstraintsInfoFlagBitsFUCHSIA :: String conNameImageConstraintsInfoFlagBitsFUCHSIA = "ImageConstraintsInfoFlagBitsFUCHSIA" enumPrefixImageConstraintsInfoFlagBitsFUCHSIA :: String enumPrefixImageConstraintsInfoFlagBitsFUCHSIA = "IMAGE_CONSTRAINTS_INFO_" showTableImageConstraintsInfoFlagBitsFUCHSIA :: [(ImageConstraintsInfoFlagBitsFUCHSIA, String)] showTableImageConstraintsInfoFlagBitsFUCHSIA = [ (IMAGE_CONSTRAINTS_INFO_CPU_READ_RARELY_FUCHSIA , "CPU_READ_RARELY_FUCHSIA") , (IMAGE_CONSTRAINTS_INFO_CPU_READ_OFTEN_FUCHSIA , "CPU_READ_OFTEN_FUCHSIA") , (IMAGE_CONSTRAINTS_INFO_CPU_WRITE_RARELY_FUCHSIA , "CPU_WRITE_RARELY_FUCHSIA") , (IMAGE_CONSTRAINTS_INFO_CPU_WRITE_OFTEN_FUCHSIA , "CPU_WRITE_OFTEN_FUCHSIA") , (IMAGE_CONSTRAINTS_INFO_PROTECTED_OPTIONAL_FUCHSIA, "PROTECTED_OPTIONAL_FUCHSIA") ] instance Show ImageConstraintsInfoFlagBitsFUCHSIA where showsPrec = enumShowsPrec enumPrefixImageConstraintsInfoFlagBitsFUCHSIA showTableImageConstraintsInfoFlagBitsFUCHSIA conNameImageConstraintsInfoFlagBitsFUCHSIA (\(ImageConstraintsInfoFlagBitsFUCHSIA x) -> x) (\x -> showString "0x" . showHex x) instance Read ImageConstraintsInfoFlagBitsFUCHSIA where readPrec = enumReadPrec enumPrefixImageConstraintsInfoFlagBitsFUCHSIA showTableImageConstraintsInfoFlagBitsFUCHSIA conNameImageConstraintsInfoFlagBitsFUCHSIA ImageConstraintsInfoFlagBitsFUCHSIA type FUCHSIA_BUFFER_COLLECTION_SPEC_VERSION = 2 -- No documentation found for TopLevel "VK_FUCHSIA_BUFFER_COLLECTION_SPEC_VERSION" pattern FUCHSIA_BUFFER_COLLECTION_SPEC_VERSION :: forall a . Integral a => a pattern FUCHSIA_BUFFER_COLLECTION_SPEC_VERSION = 2 type FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME = "VK_FUCHSIA_buffer_collection" -- No documentation found for TopLevel "VK_FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME" pattern FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME = "VK_FUCHSIA_buffer_collection"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_FUCHSIA_buffer_collection.hs
bsd-3-clause
88,463
1
19
16,521
11,984
6,922
5,062
-1
-1
{-# LANGUAGE RecordWildCards #-} -- | Module for command-line utilites, parsers and convenient handlers. module Pos.Client.CLI.Util ( attackTypeParser , attackTargetParser , defaultLoggerConfig , readLoggerConfig , stakeholderIdParser ) where import Universum import Text.Megaparsec (Parsec) import qualified Text.Megaparsec as P import qualified Text.Megaparsec.Char as P import Pos.Chain.Security (AttackTarget (..), AttackType (..)) import Pos.Core (StakeholderId) import Pos.Core.NetworkAddress (addrParser) import Pos.Crypto (decodeAbstractHash) import Pos.Util.Wlog (LoggerConfig (..), parseLoggerConfig, productionB) attackTypeParser :: Parsec () String AttackType attackTypeParser = P.string "No" >> AttackNoBlocks <$ (P.string "Blocks") <|> AttackNoCommitments <$ (P.string "Commitments") stakeholderIdParser :: Parsec () String StakeholderId stakeholderIdParser = do token <- some P.alphaNumChar either (fail . toString) return $ decodeAbstractHash (toText token) attackTargetParser :: Parsec () String AttackTarget attackTargetParser = (PubKeyAddressTarget <$> P.try stakeholderIdParser) <|> (NetworkAddressTarget <$> addrParser) -- | Default logger config. Will be used if `--log-config` argument is -- not passed. defaultLoggerConfig :: LoggerConfig defaultLoggerConfig = productionB -- | Reads logger config from given path. By default returns -- 'defaultLoggerConfig'. readLoggerConfig :: MonadIO m => Maybe FilePath -> m LoggerConfig readLoggerConfig = maybe (return defaultLoggerConfig) parseLoggerConfig
input-output-hk/pos-haskell-prototype
lib/src/Pos/Client/CLI/Util.hs
mit
1,697
0
10
347
340
194
146
34
1
-- Currently this configuration has some problems! import qualified Data.Map as M -- XMonad import XMonad -- XMonad contrib import qualified XMonad.StackSet as W -- For cycling screens import qualified XMonad.Actions.CycleWS as CWS -- For grid selection import XMonad.Actions.GridSelect -- For launching xmobar import XMonad.Util.Run -- For output info about the internal state of XMonad import XMonad.Hooks.DynamicLog import System.IO -- For reserve space for xmobar import XMonad.Hooks.ManageDocks -- Java Swing import XMonad.Hooks.SetWMName -- TODO systray -- Send applications to their dedicated Workspace myManageHook = composeAll [ resource =? "gvim" --> doShift "1:editor" , className =? "Firefox" --> doShift "3:web" , className =? "Iceweasel" --> doShift "3:web" , resource =? "chromium-browser" --> doShift "3:web" , resource =? "icecat" --> doShift "3:web" , resource =? "opera" --> doShift "3:web" , resource =? "calibre" --> doShift "5:readings" , resource =? "evince" --> doShift "5:readings" , className =? "Gimp" --> doShift "6:design" , resource =? "inkscape" --> doShift "6:design" , resource =? "krita" --> doShift "6:design" , resource =? "amarok" --> doShift "7:media" , resource =? "rhythmbox" --> doShift "7:media" , resource =? "tuxguitar" --> doShift "7:media" , resource =? "vlc" --> doShift "7:media" , resource =? "transmission-gtk" --> doShift "8:network" , resource =? "filezilla" --> doShift "8:network" , resource =? "dolphin" --> doShift "9:explorer" , resource =? "nautilus" --> doShift "9:explorer" , className =? "Thunderbird" --> doShift "0:communication" , resource =? "virtualbox" --> doShift "=:limbo" , resource =? "emacs" --> doShift "-:org" ] -- Key binding to toggle the gap for the bar. toggleStrutsKey XConfig {XMonad.modMask = modMask} = (modMask, xK_b) main = do -- Launch xmobar TODO show on mod myXmobar <- spawnPipe "xmobar ~/.xmonad/xmobarrc.hs" xmonad =<< myStatusBar myXmobar defaultConfig { manageHook = myManageHook <+> manageHook defaultConfig -- Use super instead of alt as the modkey , modMask = mod4Mask , keys = \c -> myKeys c `M.union` keys defaultConfig c -- Mouse -- TODO maintain the mouse position but highlight it -- Border options , borderWidth = 4 , normalBorderColor = "#48F" , focusedBorderColor = "#F00" -- Default terminal , terminal = "gnome-terminal" , workspaces = myWorkSpaces -- Fix Java Swing?? , startupHook = setWMName "LG3D" -- Logging XMonad status with with pretty-printing format -- , logHook = dynamicLogWithPP myBarPP -- , handleEvent } where myStatusBar bar = statusBar myBarCommand myBarPP toggleStrutsKey where myBarCommand = "xmobar ~/.xmonad/xmobarrc.hs" myBarPP = xmobarPP -- Output to xmobar instead of stdout { ppOutput = hPutStrLn bar , ppTitle = xmobarColor "white" "" . shorten 50 -- Avoid showing the layout , ppLayout = const "" } myWorkSpaces = ["`:home", "1:editor", "2:console", "3:web", "4:helper", "5:readings", "6:design", "7:media", "8:network", "9:explorer", "0:communication", "-:org", "=:limbo"] -- Keys for the workspaces workSpacesKeys = [xK_quoteleft, xK_1, xK_2, xK_3, xK_4, xK_5, xK_6, xK_7, xK_8, xK_9, xK_0, xK_minus, xK_equal] -- Applications -- TODO position -- TODO Only use Dolphin or Nautilus or Thunar or ... myApplications = ["gvim -f", "firefox", "iceweasel", "chromium-browser", "thunderbird", "emacs", "amarok", "rhythmbox", "gimp", "calibre", "tuxguitar", "nautilus", "dolphin", "opera", "icecat", "midori", "transmission-gtk", "inkscape", "krita", "libreoffice", "konqueror", "virtualbox", "filezilla"] myKeys conf@(XConfig {modMask = modm}) = M.fromList $ -- Use Esc instead of Shift + c for closing a program [ ((modm .|. shiftMask, xK_c), return ()) , ((modm, xK_Escape), kill) -- Move focus to other Xinerama screen , ((modm, xK_Tab), CWS.nextScreen) -- Select applications using the grid selection , ((modm, xK_s), spawnSelected defaultGSConfig myApplications) -- Go to a workspace using the grid selection , ((modm, xK_g), gridselectWorkspace defaultGSConfig (\ws -> W.greedyView ws)) -- Dmenu -- , (modMask, xK_m), spawn "dmenu") -- Application shortcuts , ((modm, xK_v), spawn "gvim -f") , ((modm, xK_f), spawn "firefox") -- , ((modm, xK_c), spawn "chromium-browser") -- , ((modm, xK_u), spawn "thunderbird") -- Commands TODO grid -- TODO Screenshot -- , ((modm , xK_Print ), spawn "scrot -q 75 ${HOME}/screenshots/'%d-%m-%Y-%H-%M-%S.jpg'") -- ADDWM full print -- , ((myAltKey , xK_Print ), spawn "sleep 1; scrot -s -q 75 ${HOME}/screenshots/'%d-%m-%Y-%H-%M-%S.jpg'") -- ADDWM only selected rectangle print ] ++ -- TODO switch focus to screen with workspace N -- TODO move workspace N to focused screen -- mod-n, Switch to workspace N -- mod-shift-n, Move client to workspace N [((m .|. modm, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) workSpacesKeys , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
j-a-m-l/.dot
_legacy_/xmonad/xmonad.hs
mit
5,399
21
15
1,241
1,081
635
446
67
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module State.App where import Control.Exception import Control.Monad.Trans.Class import State.Error import State.Machine import State.Trans.Machine import State.Output import State.Tape newtype App m a = App { runApp :: MachineT m a } deriving (Functor , Applicative , Monad , MonadTrans) -- Output the string `str` without changing the state of the program. output' :: (MonadOutput m) => String -> a -> App m a output' str x = do lift (output str) return x -- Runs the program in the given environment. evalApp :: App m a -> m (Machine a) evalApp p = runMachineT (runApp p) -- Converts from Maybe to App. tryMaybe :: (Monad m) => Maybe a -> RuntimeError -> App m a tryMaybe x err = maybe (throw err) return x
BakerSmithA/Metal
src/State/App.hs
mit
802
0
9
175
235
126
109
23
1
import System.Environment import Text.Printf import Data.List main = do [d] <- map read `fmap` getArgs printf "%f\n" (mean [1..d]) {-- snippet fold --} mean :: [Double] -> Double mean xs = s / fromIntegral n where (n, s) = foldl' k (0, 0) xs k (n, s) x = n `seq` s `seq` (n+1, s+x) {-- /snippet fold --}
binesiyu/ifl
examples/ch25/D.hs
mit
328
0
10
83
157
87
70
10
1
{- DATX02-17-26, automated assessment of imperative programs. - Copyright, 2017, see AUTHORS.md. - - 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. -} {-# LANGUAGE LambdaCase #-} -- | Normalizers for simplifying if + else statements -- where some branch is empty. module Norm.IfElseEmpty ( -- * Normalizers normIESiEmpty , normIESeEmpty , normIEBothEmpty ) where import Util.Monad (traverseJ) import Norm.NormCS -- TODO allocate stages. At the moment chosen arbitrarily. stage :: Int stage = 1 -------------------------------------------------------------------------------- -- Exported Rules: -------------------------------------------------------------------------------- -- | Simplifies an if else where the if branch is empty. -- > if ( c ) ; else se => if ( !c ) se -- and: -- > if ( c ) ; => sideEffectsOf( c ) normIESiEmpty :: NormCUR normIESiEmpty = makeRule' "if_else_empty.stmt.si_empty" [stage] execIESiEmpty -- | Simplifies an if else where the else branch is empty. -- > if ( c ) si else ; => if ( c ) si normIESeEmpty :: NormCUR normIESeEmpty = makeRule' "if_else_empty.stmt.se_empty" [stage] execIESeEmpty -- | Simplifies an if else where both branches are empty. -- > if ( c ) ; else ; => sideEffectsOf( c ) normIEBothEmpty :: NormCUR normIEBothEmpty = makeRule' "if_else_empty.stmt.both_empty" [stage] execIEBothEmpty -------------------------------------------------------------------------------- -- if_else_empty.stmt.si_empty: -------------------------------------------------------------------------------- execIESiEmpty :: NormCUA execIESiEmpty = normEvery $ traverseJ $ \case SIf c SEmpty -> change $ exprIntoStmts c SIfElse c SEmpty se -> change [SIf (ENot c) se] x -> unique [x] -------------------------------------------------------------------------------- -- if_else_empty.stmt.se_empty: -------------------------------------------------------------------------------- execIESeEmpty :: NormCUA execIESeEmpty = normEvery $ \case SIfElse c si SEmpty -> change $ SIf c si x -> unique x -------------------------------------------------------------------------------- -- if_else_empty.stmt.both_empty: -------------------------------------------------------------------------------- execIEBothEmpty :: NormCUA execIEBothEmpty = normEvery $ traverseJ $ \case SIfElse c SEmpty SEmpty -> change $ exprIntoStmts c x -> unique [x]
DATX02-17-26/DATX02-17-26
libsrc/Norm/IfElseEmpty.hs
gpl-2.0
3,101
0
13
497
307
173
134
29
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.DirectConnect.DeleteInterconnect -- Copyright : (c) 2013-2015 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) -- -- Deletes the specified interconnect. -- -- /See:/ <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_DeleteInterconnect.html AWS API Reference> for DeleteInterconnect. module Network.AWS.DirectConnect.DeleteInterconnect ( -- * Creating a Request deleteInterconnect , DeleteInterconnect -- * Request Lenses , dInterconnectId -- * Destructuring the Response , deleteInterconnectResponse , DeleteInterconnectResponse -- * Response Lenses , drsInterconnectState , drsResponseStatus ) where import Network.AWS.DirectConnect.Types import Network.AWS.DirectConnect.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Container for the parameters to the DeleteInterconnect operation. -- -- /See:/ 'deleteInterconnect' smart constructor. newtype DeleteInterconnect = DeleteInterconnect' { _dInterconnectId :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteInterconnect' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dInterconnectId' deleteInterconnect :: Text -- ^ 'dInterconnectId' -> DeleteInterconnect deleteInterconnect pInterconnectId_ = DeleteInterconnect' { _dInterconnectId = pInterconnectId_ } -- | Undocumented member. dInterconnectId :: Lens' DeleteInterconnect Text dInterconnectId = lens _dInterconnectId (\ s a -> s{_dInterconnectId = a}); instance AWSRequest DeleteInterconnect where type Rs DeleteInterconnect = DeleteInterconnectResponse request = postJSON directConnect response = receiveJSON (\ s h x -> DeleteInterconnectResponse' <$> (x .?> "interconnectState") <*> (pure (fromEnum s))) instance ToHeaders DeleteInterconnect where toHeaders = const (mconcat ["X-Amz-Target" =# ("OvertureService.DeleteInterconnect" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DeleteInterconnect where toJSON DeleteInterconnect'{..} = object (catMaybes [Just ("interconnectId" .= _dInterconnectId)]) instance ToPath DeleteInterconnect where toPath = const "/" instance ToQuery DeleteInterconnect where toQuery = const mempty -- | The response received when DeleteInterconnect is called. -- -- /See:/ 'deleteInterconnectResponse' smart constructor. data DeleteInterconnectResponse = DeleteInterconnectResponse' { _drsInterconnectState :: !(Maybe InterconnectState) , _drsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteInterconnectResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'drsInterconnectState' -- -- * 'drsResponseStatus' deleteInterconnectResponse :: Int -- ^ 'drsResponseStatus' -> DeleteInterconnectResponse deleteInterconnectResponse pResponseStatus_ = DeleteInterconnectResponse' { _drsInterconnectState = Nothing , _drsResponseStatus = pResponseStatus_ } -- | Undocumented member. drsInterconnectState :: Lens' DeleteInterconnectResponse (Maybe InterconnectState) drsInterconnectState = lens _drsInterconnectState (\ s a -> s{_drsInterconnectState = a}); -- | The response status code. drsResponseStatus :: Lens' DeleteInterconnectResponse Int drsResponseStatus = lens _drsResponseStatus (\ s a -> s{_drsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-directconnect/gen/Network/AWS/DirectConnect/DeleteInterconnect.hs
mpl-2.0
4,463
0
13
936
582
348
234
78
1
-- Repro for https://github.com/lambdacube3d/lambdacube-gl/issues/10 -- Usage: -- ghc -threaded -eventlog -rtsopts -isrc --make LCstress.hs && ./LCstress +RTS -T -ls -N2 -- {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UnicodeSyntax #-} {-# OPTIONS_GHC -Wall -Wno-unused-imports -Wno-type-defaults #-} import Control.Lens import Control.Monad (filterM, when, forM_) import Control.Monad.IO.Class (MonadIO, liftIO) import qualified Data.Aeson as AE import qualified Data.ByteString.Char8 as SB import qualified Data.ByteString.Lazy as LB import Data.List import qualified Data.Map.Strict as Map import Data.Maybe import Data.String import qualified Data.Vector as V import qualified Foreign.Ptr as F import qualified Foreign.ForeignPtr as F import qualified Data.GI.Base as GI import qualified GI.Cairo as GIC import qualified GI.PangoCairo.Functions as GIPC import qualified Graphics.Rendering.Cairo as GRC import qualified Graphics.Rendering.Cairo.Types as GRC import qualified Graphics.Rendering.Cairo.Internal as GRCI (create) --,destroy, imageSurfaceCreate, unCairo import qualified Graphics.GL.Core33 as GL import qualified "GLFW-b" Graphics.UI.GLFW as GLFW import qualified LambdaCube.Compiler as LCC import qualified LambdaCube.GL as GL import qualified LambdaCube.GL.Mesh as GL import qualified LambdaCube.Linear as LCLin import LambdaCube.Mesh as LC import Text.Printf (printf) import Text.Show.Pretty (ppShow) import qualified System.Clock as Sys import qualified System.Directory as FS import qualified System.Environment as Sys import qualified System.IO as Sys import qualified System.Mem as Sys import qualified GHC.Stats as Sys import qualified System.Mem.Weak as SMem import LambdaCube.GL.Type as T import LambdaCube.GL.Util import Data.Map.Strict (Map) import Data.IntMap (IntMap) import qualified Data.IntMap as IM import LambdaCube.PipelineSchema import Data.IORef import Data.Vector (Vector,(//),(!)) import LambdaCube.GL.Input (createObjectCommands, mkUniform) import LambdaCube.GL.Mesh (GPUMesh(..), GPUData(..)) foreign import ccall "&cairo_destroy" cairo_destroy ∷ F.FinalizerPtr GRC.Cairo data Scenario = ManMesh -- memory reclaimed OK | ManMeshObj -- memory reclaimed OK | AutoMesh -- SIGSEGV on nVidia drivers | AutoMeshObj -- memory usage climbs, ~3k/frame deriving (Eq, Read, Show) experiment ∷ Scenario → Integer → GL.GLStorage → GL.Mesh → IO () experiment scen n store dMesh = do mesh ← GL.uploadMeshToGPU dMesh case scen of ManMesh → do GL.disposeMesh mesh ManMeshObj → do object ← GL.addMeshToObjectArray store "portStream" ["portMtl"] mesh GL.removeObject store object GL.disposeMesh mesh AutoMesh → do SMem.addFinalizer mesh $ do GL.disposeMesh mesh AutoMeshObj → do object ← GL.addMeshToObjectArray store "portStream" ["portMtl"] mesh SMem.addFinalizer object $ do printf "running finalizer, n=%d\n" n GL.removeObject store object GL.disposeMesh mesh --- Mostly boring parts below --- newtype UniformNameS = UniformNameS { fromUNS ∷ SB.ByteString } deriving (Eq, IsString, Ord, Show) newtype ObjArrayNameS = ObjArrayNameS { fromOANS ∷ String } deriving (Eq, IsString, Ord, Show) pipelineSchema ∷ [(ObjArrayNameS, UniformNameS)] → GL.PipelineSchema pipelineSchema schemaPairs = let arrays = fromOANS . view _1 <$> schemaPairs textures = SB.unpack . fromUNS . view _2 <$> schemaPairs simplePosUVSchema = GL.ObjectArraySchema GL.Triangles $ Map.fromList [ ("position", GL.Attribute_V2F) , ("uv", GL.Attribute_V2F) ] in GL.PipelineSchema { objectArrays = Map.fromList $ zip arrays $ repeat simplePosUVSchema , uniforms = Map.fromList $ [ ("viewProj", GL.M44F) , ("worldMat", GL.M44F) , ("entityRGB", GL.V3F) , ("entityAlpha", GL.Float) , ("identityLight", GL.Float) , ("time", GL.Float) ] ++ zip textures (repeat GL.FTexture2D) } main ∷ IO () main = do args ← Sys.getArgs let scen = case args of [] → ManMeshObj x:_ → read x Sys.hSetBuffering Sys.stdout Sys.NoBuffering _ ← GLFW.init GLFW.defaultWindowHints mapM_ GLFW.windowHint [ GLFW.WindowHint'ContextVersionMajor 3 , GLFW.WindowHint'ContextVersionMinor 3 , GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core , GLFW.WindowHint'OpenGLForwardCompat True ] Just win ← GLFW.createWindow 1024 768 "repro" Nothing Nothing GLFW.makeContextCurrent $ Just win GL.glEnable GL.GL_FRAMEBUFFER_SRGB GLFW.swapInterval 0 glstorage ← GL.allocStorage $ pipelineSchema [("portStream", "portMtl")] let pipelineJSON = "Holotype.json" pipelineSrc = "Holotype.lc" _ ← LCC.compileMain ["lc"] LCC.OpenGL33 pipelineSrc >>= \case Left err → error "-- error compiling %s:\n%s\n" pipelineSrc (ppShow err) >> return False Right ppl → LB.writeFile pipelineJSON (AE.encode ppl) >> return True let paths = [pipelineJSON] validPaths ← filterM FS.doesFileExist paths when (Prelude.null validPaths) $ error $ "GPU pipeline " ++ pipelineJSON ++ " couldn't be found in " ++ show paths renderer ← printTimeDiff "-- allocating GPU pipeline (GL.allocRenderer)... " $ do AE.eitherDecode <$> LB.readFile (Prelude.head validPaths) >>= \case Left err → error err Right ppl → GL.allocRenderer ppl _ ← GL.setStorage renderer glstorage <&> fromMaybe (error $ printf "setStorage failed") timeStart ← getTime let (w, h) = (1, 1) navg = 10 loop (iterN, timePre) avgPre preKB = do let (dx, dy) = (fromIntegral w, fromIntegral $ -h) position = V.fromList [ LCLin.V2 0 dy, LCLin.V2 0 0, LCLin.V2 dx 0, LCLin.V2 0 dy, LCLin.V2 dx 0, LCLin.V2 dx dy ] texcoord = V.fromList [ LCLin.V2 0 1, LCLin.V2 0 0, LCLin.V2 1 0, LCLin.V2 0 1, LCLin.V2 1 0, LCLin.V2 1 1 ] mesh = LC.Mesh { mPrimitive = P_Triangles , mAttributes = Map.fromList [ ("position", A_V2F position) , ("uv", A_V2F texcoord) ] } experiment scen iterN glstorage mesh timePreGC ← getTime gc new ← gcKBytesUsed timePost ← getTime let dt = timePost - timePre nonGCt = timePreGC - timePre avgPost@(avgVal, _) = avgStep dt avgPre when (0 == mod iterN 40) $ printf " frame used dFrMem avgFrMem avgFrTime frTimeNonGC scenario: %s\n" (show scen) when (preKB /= new) $ printf "%5dn %dk %4ddK %5dK/f %4.2fms %4.2fms\n" iterN new (new - preKB) (ceiling $ (fromIntegral new / fromIntegral iterN) ∷ Int) (avgVal * 1000) (nonGCt * 1000) loop (iterN + 1, timePost) avgPost new loop (0 ∷ Integer, timeStart) (0.0, (navg, 0, [])) =<< gcKBytesUsed timespecToSecs ∷ Sys.TimeSpec → Double timespecToSecs = (/ 1000000000.0) . fromIntegral . Sys.toNanoSecs getTime ∷ IO Double getTime = timespecToSecs <$> Sys.getTime Sys.Monotonic gc ∷ IO () gc = liftIO $ Sys.performGC gcKBytesUsed ∷ (MonadIO m) ⇒ m Integer gcKBytesUsed = liftIO $ (`div` 1024) . fromIntegral . Sys.gcdetails_mem_in_use_bytes . Sys.gc <$> Sys.getRTSStats type Avg a = (Int, Int, [a]) avgStep ∷ Fractional a ⇒ a → (a, Avg a) → (a, Avg a) avgStep x (_, (lim, cur, xs)) = let (ncur, nxs) = if cur < lim then (cur + 1, x:xs) else (lim, x:Data.List.init xs) in ((sum nxs) / fromIntegral ncur, (lim, ncur, nxs))
deepfire/mood
tests/LCstress.hs
agpl-3.0
9,027
4
20
2,605
2,303
1,270
1,033
-1
-1
where foo :: Monad m => Functor m => MonadIO m -> Int
ruchee/vimrc
vimfiles/bundle/vim-haskell/tests/indent/test016/test.hs
mit
79
5
3
37
25
13
12
-1
-1
module Vectorise.Monad.Local ( readLEnv , setLEnv , updLEnv , localV , closedV , getBindName , inBind , lookupTyVarPA , defLocalTyVar , defLocalTyVarWithPA , localTyVars ) where import GhcPrelude import Vectorise.Monad.Base import Vectorise.Env import CoreSyn import Name import VarEnv import Var import FastString -- Local Environment ---------------------------------------------------------- -- |Project something from the local environment. -- readLEnv :: (LocalEnv -> a) -> VM a readLEnv f = VM $ \_ genv lenv -> return (Yes genv lenv (f lenv)) -- |Set the local environment. -- setLEnv :: LocalEnv -> VM () setLEnv lenv = VM $ \_ genv _ -> return (Yes genv lenv ()) -- |Update the environment using the provided function. -- updLEnv :: (LocalEnv -> LocalEnv) -> VM () updLEnv f = VM $ \_ genv lenv -> return (Yes genv (f lenv) ()) -- |Perform a computation in its own local environment. -- This does not alter the environment of the current state. -- localV :: VM a -> VM a localV p = do { env <- readLEnv id ; x <- p ; setLEnv env ; return x } -- |Perform a computation in an empty local environment. -- closedV :: VM a -> VM a closedV p = do { env <- readLEnv id ; setLEnv (emptyLocalEnv { local_bind_name = local_bind_name env }) ; x <- p ; setLEnv env ; return x } -- |Get the name of the local binding currently being vectorised. -- getBindName :: VM FastString getBindName = readLEnv local_bind_name -- |Run a vectorisation computation in a local environment, -- with this id set as the current binding. -- inBind :: Id -> VM a -> VM a inBind id p = do updLEnv $ \env -> env { local_bind_name = occNameFS (getOccName id) } p -- |Lookup a PA tyvars from the local environment. lookupTyVarPA :: Var -> VM (Maybe CoreExpr) lookupTyVarPA tv = readLEnv $ \env -> lookupVarEnv (local_tyvar_pa env) tv -- |Add a tyvar to the local environment. defLocalTyVar :: TyVar -> VM () defLocalTyVar tv = updLEnv $ \env -> env { local_tyvars = tv : local_tyvars env , local_tyvar_pa = local_tyvar_pa env `delVarEnv` tv } -- |Add mapping between a tyvar and pa dictionary to the local environment. defLocalTyVarWithPA :: TyVar -> CoreExpr -> VM () defLocalTyVarWithPA tv pa = updLEnv $ \env -> env { local_tyvars = tv : local_tyvars env , local_tyvar_pa = extendVarEnv (local_tyvar_pa env) tv pa } -- |Get the set of tyvars from the local environment. localTyVars :: VM [TyVar] localTyVars = readLEnv (reverse . local_tyvars)
ezyang/ghc
compiler/vectorise/Vectorise/Monad/Local.hs
bsd-3-clause
2,558
0
13
563
680
365
315
60
1
<?xml version='1.0' encoding='ISO-8859-1'?> <!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"> <title>msopentech-tools-help.2</title> <maps> <homeID></homeID> <mapref location="map.xml"/> </maps> <view mergetype="javax.help.AppendMerge"> <name>TOC</name> <label>Table of Contents</label> <type>javax.help.TOCView</type> <data>toc.xml</data> </view> <view mergetype="javax.help.AppendMerge"> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> </helpset>
guiling/msopentech-tools-for-intellij
help/msopentech-tools-help/helpset.hs
apache-2.0
680
56
44
92
292
148
144
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} {-| Combines the construction of RPC server components and their Python stubs. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.THH.PyRPC ( genPyUDSRpcStub , genPyUDSRpcStubStr ) where import Control.Monad import Data.Char (toLower, toUpper) import Data.Functor import Data.Maybe (fromMaybe) import Language.Haskell.TH import Language.Haskell.TH.Syntax (liftString) import Text.PrettyPrint import Ganeti.THH.Types -- | The indentation step in generated Python files. pythonIndentStep :: Int pythonIndentStep = 2 -- | A helper function that nests a block of generated output by the default -- step (see 'pythonIndentStep'). nest' :: Doc -> Doc nest' = nest pythonIndentStep -- | The name of an abstract function to which all method in a Python stub -- are forwarded to. genericInvokeName :: String genericInvokeName = "_GenericInvoke" -- | The name of a function that returns the socket path for reaching the -- appropriate RPC client. socketPathName :: String socketPathName = "_GetSocketPath" -- | Create a Python expression that applies a given function to a list of -- given expressions apply :: String -> [Doc] -> Doc apply name as = text name <> parens (hcat $ punctuate (text ", ") as) -- | An empty line block. emptyLine :: Doc emptyLine = text "" -- apparently using 'empty' doesn't work lowerFirst :: String -> String lowerFirst (x:xs) = toLower x : xs lowerFirst [] = [] upperFirst :: String -> String upperFirst (x:xs) = toUpper x : xs upperFirst [] = [] -- | Creates a method declaration given a function name and a list of -- Haskell types corresponding to its arguments. toFunc :: String -> [Type] -> Q Doc toFunc fname as = do args <- zipWithM varName [1..] as let args' = text "self" : args callName = lowerFirst fname return $ (text "def" <+> apply fname args') <> colon $+$ nest' (text "return" <+> text "self." <> apply genericInvokeName (text (show callName) : args) ) where -- | Create a name for a method argument, given its index position -- and Haskell type. varName :: Int -> Type -> Q Doc varName _ (VarT n) = lowerFirstNameQ n varName _ (ConT n) = lowerFirstNameQ n varName idx (AppT ListT t) = listOf idx t varName idx (AppT (ConT n) t) | n == ''[] = listOf idx t | otherwise = kind1Of idx n t varName idx (AppT (AppT (TupleT 2) t) t') = pairOf idx t t' varName idx (AppT (AppT (ConT n) t) t') | n == ''(,) = pairOf idx t t' varName idx t = do report False $ "Don't know how to make a Python variable name from " ++ show t ++ "; using a numbered one." return $ text ('_' : show idx) -- | Create a name for a method argument, knowing that its a list of -- a given type. listOf :: Int -> Type -> Q Doc listOf idx t = (<> text "List") <$> varName idx t -- | Create a name for a method argument, knowing that its wrapped in -- a type of kind @* -> *@. kind1Of :: Int -> Name -> Type -> Q Doc kind1Of idx name t = (<> text (nameBase name)) <$> varName idx t -- | Create a name for a method argument, knowing that its a pair of -- the given types. pairOf :: Int -> Type -> Type -> Q Doc pairOf idx t t' = do tn <- varName idx t tn' <- varName idx t' return $ tn <> text "_" <> tn' <> text "_Pair" lowerFirstNameQ :: Name -> Q Doc lowerFirstNameQ = return . text . lowerFirst . nameBase -- | Creates a method declaration by inspecting (reifying) Haskell's function -- name. nameToFunc :: Name -> Q Doc nameToFunc name = do (as, _) <- funArgs `liftM` typeOfFun name -- If the function has just one argument, try if it isn't a tuple; -- if not, use the arguments as they are. let as' = fromMaybe as $ case as of [t] -> tupleArgs t -- TODO CHECK! _ -> Nothing toFunc (upperFirst $ nameBase name) as' -- | Generates a Python class stub, given a class name, the list of Haskell -- functions to expose as methods, and a optionally a piece of code to -- include. namesToClass :: String -- ^ the class name -> Doc -- ^ Python code to include in the class -> [Name] -- ^ the list of functions to include -> Q Doc namesToClass cname pycode fns = do fnsCode <- mapM (liftM ($+$ emptyLine) . nameToFunc) fns return $ vcat [ text "class" <+> apply cname [text "object"] <> colon , nest' ( pycode $+$ vcat fnsCode ) ] -- | Takes a list of function names and creates a RPC handler that delegates -- calls to them, as well as writes out the corresponding Python stub. -- -- See 'mkRpcM' for the requirements on the passed functions and the returned -- expression. genPyUDSRpcStub :: String -- ^ the name of the class to be generated -> String -- ^ the name of the constant from @constants.py@ holding -- the path to a UDS socket -> [Name] -- ^ names of functions to include -> Q Doc genPyUDSRpcStub className constName = liftM (header $+$) . namesToClass className stubCode where header = text "# This file is automatically generated, do not edit!" $+$ text "# pylint: disable-all" stubCode = abstrMethod genericInvokeName [ text "method", text "*args"] $+$ method socketPathName [] ( text "from ganeti import pathutils" $+$ text "return" <+> text "pathutils." <> text constName) method name args body = text "def" <+> apply name (text "self" : args) <> colon $+$ nest' body $+$ emptyLine abstrMethod name args = method name args $ text "raise" <+> apply "NotImplementedError" [] -- The same as 'genPyUDSRpcStub', but returns the result as a @String@ -- expression. genPyUDSRpcStubStr :: String -- ^ the name of the class to be generated -> String -- ^ the constant in @pathutils.py@ holding the socket path -> [Name] -- ^ functions to include -> Q Exp genPyUDSRpcStubStr className constName names = liftString . render =<< genPyUDSRpcStub className constName names
apyrgio/ganeti
src/Ganeti/THH/PyRPC.hs
bsd-2-clause
7,733
0
16
2,033
1,426
732
694
110
7
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.Ex.Commands.Yi -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable module Yi.Keymap.Vim.Ex.Commands.Help (parse) where import Control.Monad (void) import qualified Data.Text as T (append, pack) import qualified Data.Attoparsec.Text as P (anyChar, many1, option, space, string, try) import Yi.Command.Help (displayHelpFor) import Yi.Keymap (Action (YiA)) import Yi.Keymap.Vim.Common (EventString) import qualified Yi.Keymap.Vim.Ex.Commands.Common as Common (impureExCommand, parse) import Yi.Keymap.Vim.Ex.Types (ExCommand (cmdAction, cmdShow)) parse :: EventString -> Maybe ExCommand parse = Common.parse $ do void $ P.string "help" cmd <- P.option "" $ P.try $ do void $ P.many1 P.space T.pack <$> P.many1 P.anyChar return $! Common.impureExCommand { cmdAction = YiA $ displayHelpFor cmd , cmdShow = "help" `T.append` if cmd == "" then "" else " " `T.append` cmd }
siddhanathan/yi
yi-keymap-vim/src/Yi/Keymap/Vim/Ex/Commands/Help.hs
gpl-2.0
1,345
0
14
445
299
182
117
23
2
module CertCmd where import PFE_Certs(CertType,QCertName(..)) import PrettyPrint(Printable(..),pp) data CertCmd = ValidateCert QCertName | RemoveCert QCertName | NewCert CertType QCertName String | NewCertAll CertType String{-ModuleName-} | TodoCert deriving (Eq,Show) instance Printable CertCmd where ppi = ppi . shellCmd --isValidate ValidateCert{} = True --isValidate _ = False cmdCert (ValidateCert cert) = Just cert cmdCert (RemoveCert cert) = Just cert cmdCert (NewCert ty cert concl) = Just cert cmdCert _ = Nothing shellCmd (ValidateCert cert) = "cert validate "++quote (ppqcert cert) shellCmd (RemoveCert cert) = "cert rm "++quote (ppqcert cert) shellCmd (NewCert ty cert concl) = unwords ["cert new",ty,quote (ppqcert cert),quote concl] shellCmd (NewCertAll ty mod) = unwords ["cert new -all",ty,mod] shellCmd TodoCert = "cert todo" ppqcert (QCertName m c) = pp m++"/"++c quote s = q++s++q where q="\""
forste/haReFork
tools/pfe/Browser/CertCmd.hs
bsd-3-clause
942
0
9
155
346
183
163
23
1
{-# LANGUAGE TemplateHaskell #-} module Bug where import Language.Haskell.TH main :: IO () main = putStrLn $(recover (stringE "reifyFixity failed") (do foo <- newName "foo" _ <- reifyFixity foo stringE "reifyFixity successful"))
sdiehl/ghc
testsuite/tests/th/T15481.hs
bsd-3-clause
317
0
13
120
73
36
37
8
1
{-# LANGUAGE RankNTypes #-} {-# OPTIONS -Wall -Werror #-} module InferAssert where import AnnotatedExpr import Control.Applicative ((<$>), Applicative(..)) import Control.Lens.Operators import Control.Monad (void) import Control.Monad.Trans.State (runStateT, runState) import InferWrappers import Lamdu.Data.Arbitrary () -- Arbitrary instance import Lamdu.Data.Expression.IRef (DefI) import System.IO (hPutStrLn, stderr) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertBool) import Utils import qualified Control.DeepSeq as DeepSeq import qualified Control.Exception as E import qualified Control.Lens as Lens import qualified Data.List as List import qualified Data.Map as Map import qualified Lamdu.Data.Expression as Expr import qualified Lamdu.Data.Expression.IRef as ExprIRef import qualified Lamdu.Data.Expression.Infer as Infer import qualified Lamdu.Data.Expression.Infer.ImplicitVariables as ImplicitVariables import qualified Lamdu.Data.Expression.Utils as ExprUtil import qualified System.Random as Random import qualified Test.Framework as TestFramework import qualified Test.HUnit as HUnit canonizeInferred :: InferResults t -> InferResults t canonizeInferred = ExprUtil.randomizeParamIdsG (const ()) ExprUtil.debugNameGen Map.empty canonizePayload where canonizePayload gen guidMap (ival, ityp) = ( ExprUtil.randomizeParamIdsG (const ()) gen1 guidMap (\_ _ x -> x) ival , ExprUtil.randomizeParamIdsG (const ()) gen2 guidMap (\_ _ x -> x) ityp ) where (gen1, gen2) = ExprUtil.ngSplit gen assertCompareInferred :: InferResults t -> InferResults t -> HUnit.Assertion assertCompareInferred result expected = assertBool errorMsg (null resultErrs) where resultC = canonizeInferred result expectedC = canonizeInferred expected (resultErrs, errorMsg) = errorMessage $ ExprUtil.matchExpression match mismatch resultC expectedC check s x y | ExprUtil.alphaEq x y = pure [] | otherwise = fmap (: []) . addAnnotation $ List.intercalate "\n" [ " expected " ++ s ++ ":" ++ (show . simplifyDef) y , " result " ++ s ++ ":" ++ (show . simplifyDef) x ] match (v0, t0) (v1, t1) = (++) <$> check " type" t0 t1 <*> check "value" v0 v1 mismatch e0 e1 = error $ concat [ "Result must have same expression shape:" , "\n Result: ", redShow e0 , "\n vs. Expected: ", redShow e1 , "\n whole result: ", redShow resultC , "\n whole expected: ", redShow expectedC ] redShow = ansiAround ansiRed . show . void inferAssertion :: InferResults t -> HUnit.Assertion inferAssertion expr = assertCompareInferred inferredExpr expr where inferredExpr = inferResults . fst . doInfer_ $ void expr inferWVAssertion :: InferResults t -> InferResults t -> HUnit.Assertion inferWVAssertion expr wvExpr = do -- TODO: assertCompareInferred should take an error prefix string, -- and do ALL the error printing itself. It has more information -- about what kind of error string would be useful. assertCompareInferred (inferResults inferredExpr) expr `E.onException` printOrig assertCompareInferred (inferResults wvInferredExpr) wvExpr `E.onException` (printOrig >> printWV) where printOrig = hPutStrLn stderr $ "WithoutVars:\n" ++ showInferredValType inferredExpr printWV = hPutStrLn stderr $ "WithVars:\n" ++ showInferredValType wvInferredExpr (inferredExpr, inferContext) = doInfer_ $ void expr wvInferredExpr = fst <$> wvInferredExprPL (wvInferredExprPL, _) = either error id $ (`runStateT` inferContext) (ImplicitVariables.add (Random.mkStdGen 0) loader (flip (,) () <$> inferredExpr)) allowFailAssertion :: HUnit.Assertion -> HUnit.Assertion allowFailAssertion assertion = (assertion >> successOccurred) `E.catch` \(E.SomeException _) -> errorOccurred where successOccurred = hPutStrLn stderr . ansiAround ansiYellow $ "NOTE: doesn't fail. Remove AllowFail?" errorOccurred = hPutStrLn stderr . ansiAround ansiYellow $ "WARNING: Allowing failure in:" testInfer :: String -> InferResults t -> TestFramework.Test testInfer name = testCase name . inferAssertion testInferAllowFail :: String -> InferResults t -> TestFramework.Test testInferAllowFail name expr = testCase name . allowFailAssertion $ inferAssertion expr type InferredExpr t = ExprIRef.Expression t (Infer.Inferred (DefI t)) testResume :: String -> InferResults t -> Lens.Traversal' (InferredExpr t) (InferredExpr t) -> InferResults t -> TestFramework.Test testResume name origExpr position newExpr = testCase name $ assertResume origExpr position newExpr assertResume :: InferResults t -> Lens.Traversal' (InferredExpr t) (InferredExpr t) -> InferResults t -> HUnit.Assertion assertResume origExpr position newExpr = void . E.evaluate . DeepSeq.force . (`runState` inferContext) $ doInferM point newExpr where (tExpr, inferContext) = doInfer_ origExpr Just point = tExpr ^? position . Expr.ePayload . Lens.to Infer.iNode
sinelaw/lamdu
test/InferAssert.hs
gpl-3.0
5,108
0
14
946
1,379
748
631
-1
-1
-- See Trac #1221 module ShouldFail where a :: Num a => (Bool -> [a]) -> [a] a x = x True ++ [1] y :: b -> () y = const () -- Typechecks ok b = a (const [2]) -- This one had an uninformative error message c = a y -- More informative d = a ()
siddhanathan/ghc
testsuite/tests/typecheck/should_fail/tcfail178.hs
bsd-3-clause
249
0
9
67
111
61
50
8
1
-- !!! a very simple test of class and instance declarations module ShouldSucceed where class H a where op1 :: a -> a -> a instance H Bool where op1 x y = y f :: Bool -> Int -> Bool f x y = op1 x x
urbanslug/ghc
testsuite/tests/typecheck/should_compile/tc041.hs
bsd-3-clause
204
0
8
54
73
38
35
7
1
module Quote (agpl, agpl_f, aparse) where import Parser import CodeGen import Language.Haskell.TH import Language.Haskell.TH.Quote import Agpl_syntax import Debug.Trace agpl :: QuasiQuoter agpl = QuasiQuoter undefined undefined undefined aparse aparse :: String -> Q [Dec] aparse s = (makeAGPLDecs (parseGame s)) agpl_f :: QuasiQuoter agpl_f = quoteFile agpl
matthew-eads/agpl
Quote.hs
isc
361
0
8
49
109
63
46
13
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} module Jot.Rope ( JotString , null , length , newLines , singleton , toLazyByteString , empty , append , concat , replicate , splitAt , slice , splice , copy , delete , reverse ) where import Control.Arrow ((&&&)) import Control.Lens (_Just, _2, preview, to) import Control.Monad (guard) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C import qualified Data.ByteString.Lazy as BL import qualified Data.FingerTree as T import Data.FingerTree (FingerTree, Measured(..), ViewL(..), ViewR(..)) import Data.Foldable (foldl') import Data.Function (on) import Data.Semigroup (Semigroup(..)) import Prelude hiding (concat, length, null, replicate, reverse, splitAt) import Jot.Range (Range(..), size) -- | newtype JotString = JotString { fromRope :: FingerTree JotSize JotChunk } deriving (Show) -- | data JotSize = JotSize { len :: {-# UNPACK #-} !Int , nls :: Int } deriving (Show) -- | newtype JotChunk = JotChunk { fromChunk :: BS.ByteString } deriving (Semigroup, Show) -- | null :: JotString -> Bool null = T.null . fromRope -- | length' :: Measured JotSize m => m -> Int length' = len . measure -- | length :: JotString -> Int length = length' -- | newLines :: JotString -> Int newLines = nls . measure -- | singleton :: BS.ByteString -> JotString singleton bs | BS.null bs = mempty | otherwise = JotString (T.singleton (JotChunk bs)) -- | toLazyByteString :: JotString -> BL.ByteString toLazyByteString = foldMap (BL.fromStrict . fromChunk) . fromRope -- | nominalChunkSize :: Int nominalChunkSize = 512 -- | empty :: JotString empty = JotString mempty -- | append :: JotString -> JotString -> JotString append (JotString s) (JotString t) = case (T.viewr s, T.viewl t) of (EmptyR, _) -> JotString t (_, EmptyL) -> JotString s (ss :> m1, m2 :< ts) -> JotString $ ss `mappend` lump m1 m2 `mappend` ts where lump c1 c2 = if ((+) `on` length') c1 c2 <= nominalChunkSize then T.singleton (c1 <> c2) else (mappend `on` T.singleton) c1 c2 -- | concat :: Foldable t => t JotString -> JotString concat = foldl' (<>) mempty -- | replicate :: Int -> JotString -> JotString replicate n s | n <= 0 = mempty | even n = t <> t | otherwise = t <> t <> s where t = replicate (n `div` 2) s -- | splitAt :: Int -> JotString -> Maybe (JotString, JotString) splitAt n (JotString s) = do guard $ 0 <= n && n <= length' s let (l, r) = T.split (\m -> len m > n) s pure $ case T.viewl r of EmptyL -> (JotString l, JotString r) JotChunk x :< xs -> let (m1, m2) = BS.splitAt (n - len (measure l)) x in (JotString l <> singleton m1, singleton m2 <> JotString xs) -- | splitRange :: Range -> JotString -> Maybe (JotString, JotString, JotString) splitRange r@(Range i _) s = do let sz = size r guard $ sz >= 0 (a, t) <- splitAt i s (b, c) <- splitAt sz t pure (a, b, c) -- | slice :: Range -> JotString -> Maybe JotString slice r = preview $ to (splitRange r) . _Just._2 -- | splice :: JotString -> Range -> JotString -> Maybe JotString splice t r s = do (pr, _, sf) <- splitRange r s pure $ pr <> t <> sf -- | copy :: Range -> Range -> JotString -> Maybe JotString copy src dst s = do t <- slice src s splice t dst s -- | delete :: Range -> JotString -> Maybe JotString delete = splice mempty -- | reverse :: JotString -> JotString reverse = JotString . T.reverse . T.unsafeFmap (JotChunk . BS.reverse . fromChunk) . fromRope instance Monoid JotSize where mempty = JotSize 0 0 mappend (JotSize l n) (JotSize l' n') = JotSize (l+l') (n+n') instance Semigroup JotSize instance Measured JotSize JotChunk where measure = (JotSize <$> BS.length <*> C.count '\n') . fromChunk instance Measured JotSize JotString where measure = measure . fromRope instance Monoid JotString where mempty = empty mappend = append mconcat = concat instance Semigroup JotString instance Eq JotString where (==) = (==) `on` (length' &&& toLazyByteString)
tldrlol/jot
src/Jot/Rope.hs
isc
4,396
0
20
1,146
1,597
873
724
128
4
{-# LANGUAGE TemplateHaskell #-} import Memory import Thought import Control.Arrow import Control.Category import Control.Lens import Data.Char import Data.Maybe import Prelude hiding ((.), id) import System.Random getLoop :: Thought IO String (Maybe String) -> IO () getLoop thought = do (nextVal, newThought) <- getLine >>= stepThought thought case nextVal of Just s -> putStrLn s >> getLoop newThought Nothing -> return () data Play = Rock | Paper | Scissors deriving (Eq,Show,Ord,Enum) data Result = Win | Draw | Loss deriving (Eq,Show,Ord,Bounded,Enum) data World = World { _humanWins :: Integer , _aiWins :: Integer , _gen :: StdGen , _lastResult :: Result } deriving (Show) makeLenses ''World playResult :: Play -> Play -> Result playResult Rock Paper = Loss playResult Paper Scissors = Loss playResult Scissors Rock = Loss playResult a b | a == b = Draw | otherwise = Win choosePlay :: String -> Maybe Play choosePlay s | map toLower s == "rock" = Just Rock | map toLower s == "paper" = Just Paper | map toLower s == "scissors" = Just Scissors | otherwise = Nothing handleGame :: Play -> World -> World handleGame hP s = lastResult .~ res $ gen .~ newGen $ case res of Win -> s & humanWins +~ 1 Loss -> s & aiWins +~ 1 Draw -> s where (newPlay,newGen) = over _1 toEnum $ randomR (0,2) $ view gen s res = playResult hP newPlay logic :: Memory World String logic = filterInput (isJust . choosePlay) $ updateWithInput (\i -> handleGame (fromJust $ choosePlay i)) startWorld = World 0 0 <$> newStdGen <*> pure undefined main = do sw <- startWorld getLoop $ think logic sw >>> arr (Just . show)
edwardwas/memory
example/rockPaperScissors/Main.hs
mit
1,789
0
12
474
661
336
325
55
3
module Coroutine where import Prelude hiding (id, (.)) import Control.Applicative import Control.Arrow import Control.Category newtype Coroutine i o = Coroutine { runC :: i -> (o, Coroutine i o) } instance Functor (Coroutine i) where fmap f co = Coroutine $ \i -> let (o, co') = runC co i in (f o, fmap f co') instance Applicative (Coroutine i) where pure x = Coroutine $ const (x, pure x) cof <*> cox = Coroutine $ \i -> let (f, cof') = runC cof i (x, cox') = runC cox i in (f x, cof' <*> cox') instance Category Coroutine where id = Coroutine $ \i -> (i, id) cof . cog = Coroutine $ \i -> let (x, cog') = runC cog i (y, cof') = runC cof x in (y, cof' . cog') instance Arrow Coroutine where arr f = Coroutine $ \i -> (f i, arr f) first co = Coroutine $ \(b, d) -> let (c, co') = runC co b in ((c, d), first co') scanC :: (a -> b -> a) -> a -> Coroutine b a scanC f i = Coroutine $ step i where step a b = let a' = f a b in (a', scanC f a')
sgrif/haskell-game
Coroutine.hs
mit
1,120
0
12
386
525
278
247
30
1
module Rebase.Data.Biapplicative ( module Data.Biapplicative ) where import Data.Biapplicative
nikita-volkov/rebase
library/Rebase/Data/Biapplicative.hs
mit
98
0
5
12
20
13
7
4
0
-------------------------------------------------------------------------------- -- | -- Module : Network.HTTP.Server.Logger -- Copyright : (c) Galois, Inc. 2007, 2008 -- License : BSD3 -- -- Maintainer : diatchki@galois.com -- Stability : provisional -- Portability : -- module Network.HTTP.Server.Logger ( Logger(..) , stdLogger, quietLogger, utf8Logger , LogItem(..), LogType(..) , showLogItem, readLogItem, filterLog ) where import System.IO (Handle,stdout,stderr,hFlush,hPutStrLn) -- | A type used by the server to report various events. -- Useful for debugging. data Logger = Logger { logInfo :: Int -> String -> IO () , logDebug :: String -> IO () , logError :: String -> IO () , logWarning :: String -> IO () , getLog :: Maybe Int -- limit -> (LogType -> Bool) -- which items -> IO [LogItem] } notSaved :: Maybe Int -> (LogType -> Bool) -> IO [LogItem] notSaved l p = return $ filterLog l p [LogItem Warning "Not saving the log"] -- | A logger that uses the standard output and standard error. -- Text is UTF8 encoded. stdLogger :: Logger stdLogger = utf8Logger stdout stderr -- | A logger that does not report anything. quietLogger :: Logger quietLogger = Logger { logInfo = \ _ _ -> return () , logDebug = \_ -> return () , logError = \_ -> return () , logWarning = \_ -> return () , getLog = notSaved } -- | A logger that uses the given handles for output and errors. utf8Logger :: Handle -> Handle -> Logger utf8Logger h hErr = Logger { logInfo = \ _lev s -> logUTF8 h (LogItem (Info _lev) s) , logDebug = logUTF8 h . LogItem Debug , logError = logUTF8 hErr . LogItem Error , logWarning = logUTF8 hErr . LogItem Warning , getLog = notSaved } logUTF8 :: Handle -> LogItem -> IO () logUTF8 h i = hPutStrLn h (showLogItem i) >> hFlush h data LogType = Error | Warning | Debug | Info Int deriving Show data LogItem = LogItem { item_type :: LogType, item_data :: String } showLogItem :: LogItem -> String showLogItem (LogItem t txt) = show t ++ ": " ++ txt readLogItem :: String -> Maybe LogItem readLogItem l = case break (':' ==) l of ("Error",_:txt) -> Just $ LogItem Error txt ("Warning",_:txt) -> Just $ LogItem Warning txt ("Debug",_:txt) -> Just $ LogItem Debug txt ('I':'n':'f':'o':' ':lvl,_:txt) -> case reads lvl of [(n,"")] -> Just $ LogItem (Info n) txt _ -> Nothing _ -> Nothing -- NOTE: always reads the whole file! filterLog :: Maybe Int -> (LogType -> Bool) -> [LogItem] -> [LogItem] filterLog limit choose ls = case limit of Just n -> take n allItems _ -> allItems where allItems = filter (choose . item_type) ls
GaloisInc/http-server
Network/HTTP/Server/Logger.hs
mit
2,950
0
14
863
866
476
390
58
6
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.OverconstrainedErrorEvent (newOverconstrainedErrorEvent, getError, getErrorUnsafe, getErrorUnchecked, OverconstrainedErrorEvent(..), gTypeOverconstrainedErrorEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/OverconstrainedErrorEvent Mozilla OverconstrainedErrorEvent documentation> newOverconstrainedErrorEvent :: (MonadDOM m, ToJSString type') => type' -> Maybe OverconstrainedErrorEventInit -> m OverconstrainedErrorEvent newOverconstrainedErrorEvent type' eventInitDict = liftDOM (OverconstrainedErrorEvent <$> new (jsg "OverconstrainedErrorEvent") [toJSVal type', toJSVal eventInitDict]) -- | <https://developer.mozilla.org/en-US/docs/Web/API/OverconstrainedErrorEvent.error Mozilla OverconstrainedErrorEvent.error documentation> getError :: (MonadDOM m) => OverconstrainedErrorEvent -> m (Maybe OverconstrainedError) getError self = liftDOM ((self ^. js "error") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/OverconstrainedErrorEvent.error Mozilla OverconstrainedErrorEvent.error documentation> getErrorUnsafe :: (MonadDOM m, HasCallStack) => OverconstrainedErrorEvent -> m OverconstrainedError getErrorUnsafe self = liftDOM (((self ^. js "error") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/OverconstrainedErrorEvent.error Mozilla OverconstrainedErrorEvent.error documentation> getErrorUnchecked :: (MonadDOM m) => OverconstrainedErrorEvent -> m OverconstrainedError getErrorUnchecked self = liftDOM ((self ^. js "error") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/OverconstrainedErrorEvent.hs
mit
2,761
0
12
471
562
336
226
-1
-1
module ETL (transform) where import Data.Char (toLower) import Data.Map (Map, empty, foldrWithKey, insert) transform :: Map Int [String] -> Map String Int transform = foldrWithKey f empty where f score letters m = foldl g m (zip letters (repeat score)) g m (letter, score) = insert (map toLower letter) score m
tfausak/exercism-solutions
haskell/etl/ETL.hs
mit
317
0
11
57
136
73
63
7
1
{-# LANGUAGE GADTs, DataKinds, PolyKinds #-} {-# LANGUAGE FlexibleContexts #-} module TensorDAG where import Data.Vinyl import Data.Vinyl.Functor import Data.Singletons import Numeric.LinearAlgebra (Numeric) import TensorHMatrix import DAGIO import VarArgs makeGrad1 :: (a -> b -> a) -> HList '[a] -> Identity b -> HList '[a] makeGrad1 g (Identity a :& RNil) (Identity b) = Identity (g a b) :& RNil makeGrad2 :: (a -> b -> c -> (a, b)) -> HList '[a, b] -> Identity c -> HList '[a, b] makeGrad2 g (Identity a :& Identity b :& RNil) (Identity c) = Identity a' :& Identity b' :& RNil where (a', b') = g a b c makeDot :: Numeric a => Node (Tensor '[n] a) -> Node (Tensor '[n] a) -> IO (Node a) makeDot = makeNode (uncurry2 dot, makeGrad2 gradDot) makeMV :: (SingI n, IntegralN n, Usable a) => Node (Tensor '[n, m] a) -> Node (Tensor '[m] a) -> IO (Node (Tensor '[n] a)) makeMV = makeNode (uncurry2 mv, makeGrad2 gradMV) makeMM :: (SingI n, IntegralN n, SingI k, Usable a) => Node (Tensor '[n, m] a) -> Node (Tensor '[m, k] a) -> IO (Node (Tensor '[n, k] a)) makeMM = makeNode (uncurry2 mm, makeGrad2 gradMM) makeSelect i = makeNode (uncurry1 $ select i, makeGrad1 $ gradSelect i)
vladfi1/hs-misc
TensorDAG.hs
mit
1,188
0
14
224
610
316
294
22
1
{-# OPTIONS_GHC -fno-warn-orphans #-} -- instances for Word -- this is a VM with simple Word values as machine values -- and just simple integer arithmetic -- -- no type checking, no security against illegal usage of -- Int's as code or data pointers is detected -- ---------------------------------------- module PPL2.VM.Machines.UntaggedInt where import PPL2.Prelude import PPL2.VM import PPL2.VM.ALU.IntegerArithmUnit import PPL2.CodeGen import Data.Bits (shiftR, shiftL, (.|.), (.&.)) -- ---------------------------------------- type MV = Word type MExpr = UntypedExpr MV type MCode a = MicroCode MV a -- ---------------------------------------- -- -- basic access prisms instance WordValue MV where _Word = prism id Right instance DataRefValue MV where _DataRef = _Word . isoWordRef where isoWordRef = iso toRef frRef toRef w = (fromEnum w `shiftR` 32, w .&. 0xffffffff) frRef (sid, i) = fromIntegral sid `shiftL` 32 .|. i instance CodeRefValue MV where _CodeRef = _Word instance DefaultValue MV where _Default = prism (const 0) (\ w -> if w == 0 then Right () else Left w) -- ---------------------------------------- instrSet :: CInstrSet MV instrSet = integerArithmeticUnit -- ----------------------------------------
UweSchmidt/ppl2
src/PPL2/VM/Machines/UntaggedInt.hs
mit
1,322
0
11
271
273
161
112
27
1
-------------------------------------------------------------------- -- | -- Module : My.Prelude -- Copyright : 2009 (c) Dmitry Antonyuk -- License : MIT -- -- Maintainer: Dmitry Antonyuk <lomeo.nuke@gmail.com> -- Stability : experimental -- Portability: portable -- -- This module just exports other modules items. -- -------------------------------------------------------------------- module My.Prelude ( module My.Data.List, module My.Data.Maybe, module My.Data.Tuple, module My.Control.Monad, module My.Control.Concurrent, module My.Control.Concurrent.MaybeChan, module My.Control.Concurrent.STM ) where import My.Data.List import My.Data.Maybe import My.Data.Tuple import My.Control.Monad import My.Control.Concurrent import My.Control.Concurrent.MaybeChan import My.Control.Concurrent.STM
lomeo/my
src/My/Prelude.hs
mit
837
0
5
116
116
85
31
15
0
-- | -- Module : Data.Edison.Coll.Utils -- Copyright : Copyright (c) 1998 Chris Okasaki -- License : MIT; see COPYRIGHT file for terms and conditions -- -- Maintainer : robdockins AT fastmail DOT fm -- Stability : stable -- Portability : GHC, Hugs (MPTC and FD) -- -- This module provides implementations of several useful operations -- that are not included in the collection classes themselves. This is -- usually because the operation involves transforming a collection into a -- different type of collection; such operations cannot be typed using -- the collection classes without significantly complicating them. -- -- Be aware that these functions are defined using the external class -- interfaces and may be less efficient than corresponding, but more -- restrictively typed, functions in the collection classes. module Data.Edison.Coll.Utils where import Prelude hiding (map,null,foldr,foldl,foldr1,foldl1,lookup,filter) import Data.Edison.Coll -- | Apply a function across all the elements in a collection and transform -- the collection type. map :: (Coll cin a, CollX cout b) => (a -> b) -> (cin -> cout) map f xs = fold (\x ys -> insert (f x) ys) empty xs -- | Map a partial function across all elements of a collection and transform -- the collection type. mapPartial :: (Coll cin a, CollX cout b) => (a -> Maybe b) -> (cin -> cout) mapPartial f xs = fold (\ x ys -> case f x of Just y -> insert y ys Nothing -> ys) empty xs -- | Map a monotonic function across all the elements of a collection and -- transform the collection type. The function is required to satisfy -- the following precondition: -- -- > forall x y. x < y ==> f x < f y unsafeMapMonotonic :: (OrdColl cin a, OrdCollX cout b) => (a -> b) -> (cin -> cout) unsafeMapMonotonic f xs = foldr (unsafeInsertMin . f) empty xs -- | Map a collection-producing function across all elements of a collection -- and collect the results together using 'union'. unionMap :: (Coll cin a, CollX cout b) => (a -> cout) -> (cin -> cout) unionMap f xs = fold (\x ys -> union (f x) ys) empty xs
robdockins/edison
edison-api/src/Data/Edison/Coll/Utils.hs
mit
2,222
0
11
532
398
228
170
14
2