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 DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.TLSConfig where import GHC.Generics import Data.Text import qualified Data.Aeson -- | data TLSConfig = TLSConfig { termination :: Text -- ^ indicates termination type , certificate :: Maybe Text -- ^ provides certificate contents , key :: Maybe Text -- ^ provides key file contents , caCertificate :: Maybe Text -- ^ provides the cert authority certificate contents , destinationCACertificate :: Maybe Text -- ^ provides the contents of the ca certificate of the final destination. When using re-encrypt termination this file should be provided in order to have routers use it for health checks on the secure connection , insecureEdgeTerminationPolicy :: Maybe Text -- ^ indicates desired behavior for insecure connections to an edge-terminated route. If not set, insecure connections will not be allowed } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON TLSConfig instance Data.Aeson.ToJSON TLSConfig
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/TLSConfig.hs
apache-2.0
1,141
0
9
198
130
79
51
19
0
-- Copyright (c) 2010 - Seweryn Dynerowicz -- 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 -- imitations under the License. import Policy.UsablePath import Policy.WidestPath import Policy.ShortestPath import Policy.ShortestPathNeg import Policy.MostReliablePath import Policy.Paths import Policy.PathCount import Policy.NextHop import Algebra import LaTeX
sdynerow/SemiringsLibrary
Policy/AllPolicies.hs
apache-2.0
830
0
4
121
59
40
19
10
0
module MultilineTh (multiline) where import qualified Data.Text as T import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax import Prelude multiline :: QuasiQuoter multiline = QuasiQuoter { quoteExp = quoteUnlines , quotePat = const badUse , quoteType = const badUse , quoteDec = const badUse } where badUse = fail "multiline quasiquoter can only be used as an expression" quoteUnlines :: String -> Q Exp quoteUnlines = liftString . T.unpack . T.unwords . filter (not . T.null) . T.words . T.pack
quchen/prettyprinter
prettyprinter/app/MultilineTh.hs
bsd-2-clause
652
0
11
194
152
88
64
21
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE Rank2Types #-} #if __GLASGOW_HASKELL__ >= 800 -- a) THQ works on cross-compilers and unregisterised GHCs -- b) may make compilation faster as no dynamic loading is ever needed (not sure about this) -- c) removes one hindrance to have code inferred as SafeHaskell safe {-# LANGUAGE TemplateHaskellQuotes #-} #else {-# LANGUAGE TemplateHaskell #-} #endif -- | -- Module: Data.Aeson.Types.Internal -- Copyright: (c) 2011-2016 Bryan O'Sullivan -- (c) 2011 MailRank, Inc. -- License: BSD3 -- Maintainer: Bryan O'Sullivan <[email protected]> -- Stability: experimental -- Portability: portable -- -- Types for working with JSON data. module Data.Aeson.Types.Internal ( -- * Core JSON types Value(..) , Array , emptyArray, isEmptyArray , Pair , Object , emptyObject -- * Type conversion , Parser , Result(..) , IResult(..) , JSONPathElement(..) , JSONPath , iparse , parse , parseEither , parseMaybe , modifyFailure , parserThrowError , parserCatchError , formatError , (<?>) -- * Constructors and accessors , object -- * Generic and TH encoding configuration , Options( fieldLabelModifier , constructorTagModifier , allNullaryToStringTag , omitNothingFields , sumEncoding , unwrapUnaryRecords , tagSingleConstructors ) , SumEncoding(..) , defaultOptions , defaultTaggedObject -- * Used for changing CamelCase names into something else. , camelTo , camelTo2 -- * Other types , DotNetTime(..) ) where import Prelude () import Prelude.Compat import Control.Applicative (Alternative(..)) import Control.Arrow (first) import Control.DeepSeq (NFData(..)) import Control.Monad (MonadPlus(..), ap) import Data.Char (isLower, isUpper, toLower, isAlpha, isAlphaNum) import Data.Data (Data) import Data.Foldable (foldl') import Data.HashMap.Strict (HashMap) import Data.Hashable (Hashable(..)) import Data.List (intercalate) import Data.Scientific (Scientific) import Data.Semigroup (Semigroup((<>))) import Data.String (IsString(..)) import Data.Text (Text, pack, unpack) import Data.Time (UTCTime) import Data.Time.Format (FormatTime) import Data.Typeable (Typeable) import Data.Vector (Vector) import GHC.Generics (Generic) import qualified Control.Monad.Fail as Fail import qualified Data.HashMap.Strict as H import qualified Data.Scientific as S import qualified Data.Vector as V import qualified Language.Haskell.TH.Syntax as TH #if !MIN_VERSION_unordered_containers(0,2,6) import Data.List (sort) #endif -- | Elements of a JSON path used to describe the location of an -- error. data JSONPathElement = Key Text -- ^ JSON path element of a key into an object, -- \"object.key\". | Index {-# UNPACK #-} !Int -- ^ JSON path element of an index into an -- array, \"array[index]\". deriving (Eq, Show, Typeable, Ord) type JSONPath = [JSONPathElement] -- | The internal result of running a 'Parser'. data IResult a = IError JSONPath String | ISuccess a deriving (Eq, Show, Typeable) -- | The result of running a 'Parser'. data Result a = Error String | Success a deriving (Eq, Show, Typeable) instance NFData JSONPathElement where rnf (Key t) = rnf t rnf (Index i) = rnf i instance (NFData a) => NFData (IResult a) where rnf (ISuccess a) = rnf a rnf (IError path err) = rnf path `seq` rnf err instance (NFData a) => NFData (Result a) where rnf (Success a) = rnf a rnf (Error err) = rnf err instance Functor IResult where fmap f (ISuccess a) = ISuccess (f a) fmap _ (IError path err) = IError path err {-# INLINE fmap #-} instance Functor Result where fmap f (Success a) = Success (f a) fmap _ (Error err) = Error err {-# INLINE fmap #-} instance Monad IResult where return = pure {-# INLINE return #-} ISuccess a >>= k = k a IError path err >>= _ = IError path err {-# INLINE (>>=) #-} fail = Fail.fail {-# INLINE fail #-} instance Fail.MonadFail IResult where fail err = IError [] err {-# INLINE fail #-} instance Monad Result where return = pure {-# INLINE return #-} Success a >>= k = k a Error err >>= _ = Error err {-# INLINE (>>=) #-} fail = Fail.fail {-# INLINE fail #-} instance Fail.MonadFail Result where fail err = Error err {-# INLINE fail #-} instance Applicative IResult where pure = ISuccess {-# INLINE pure #-} (<*>) = ap {-# INLINE (<*>) #-} instance Applicative Result where pure = Success {-# INLINE pure #-} (<*>) = ap {-# INLINE (<*>) #-} instance MonadPlus IResult where mzero = fail "mzero" {-# INLINE mzero #-} mplus a@(ISuccess _) _ = a mplus _ b = b {-# INLINE mplus #-} instance MonadPlus Result where mzero = fail "mzero" {-# INLINE mzero #-} mplus a@(Success _) _ = a mplus _ b = b {-# INLINE mplus #-} instance Alternative IResult where empty = mzero {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance Alternative Result where empty = mzero {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance Semigroup (IResult a) where (<>) = mplus {-# INLINE (<>) #-} instance Monoid (IResult a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = (<>) {-# INLINE mappend #-} instance Semigroup (Result a) where (<>) = mplus {-# INLINE (<>) #-} instance Monoid (Result a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = (<>) {-# INLINE mappend #-} instance Foldable IResult where foldMap _ (IError _ _) = mempty foldMap f (ISuccess y) = f y {-# INLINE foldMap #-} foldr _ z (IError _ _) = z foldr f z (ISuccess y) = f y z {-# INLINE foldr #-} instance Foldable Result where foldMap _ (Error _) = mempty foldMap f (Success y) = f y {-# INLINE foldMap #-} foldr _ z (Error _) = z foldr f z (Success y) = f y z {-# INLINE foldr #-} instance Traversable IResult where traverse _ (IError path err) = pure (IError path err) traverse f (ISuccess a) = ISuccess <$> f a {-# INLINE traverse #-} instance Traversable Result where traverse _ (Error err) = pure (Error err) traverse f (Success a) = Success <$> f a {-# INLINE traverse #-} -- | Failure continuation. type Failure f r = JSONPath -> String -> f r -- | Success continuation. type Success a f r = a -> f r -- | A JSON parser. newtype Parser a = Parser { runParser :: forall f r. JSONPath -> Failure f r -> Success a f r -> f r } instance Monad Parser where m >>= g = Parser $ \path kf ks -> let ks' a = runParser (g a) path kf ks in runParser m path kf ks' {-# INLINE (>>=) #-} return = pure {-# INLINE return #-} fail = Fail.fail {-# INLINE fail #-} instance Fail.MonadFail Parser where fail msg = Parser $ \path kf _ks -> kf (reverse path) msg {-# INLINE fail #-} instance Functor Parser where fmap f m = Parser $ \path kf ks -> let ks' a = ks (f a) in runParser m path kf ks' {-# INLINE fmap #-} instance Applicative Parser where pure a = Parser $ \_path _kf ks -> ks a {-# INLINE pure #-} (<*>) = apP {-# INLINE (<*>) #-} instance Alternative Parser where empty = fail "empty" {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance MonadPlus Parser where mzero = fail "mzero" {-# INLINE mzero #-} mplus a b = Parser $ \path kf ks -> let kf' _ _ = runParser b path kf ks in runParser a path kf' ks {-# INLINE mplus #-} instance Semigroup (Parser a) where (<>) = mplus {-# INLINE (<>) #-} instance Monoid (Parser a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = (<>) {-# INLINE mappend #-} apP :: Parser (a -> b) -> Parser a -> Parser b apP d e = do b <- d a <- e return (b a) {-# INLINE apP #-} -- | A JSON \"object\" (key\/value map). type Object = HashMap Text Value -- | A JSON \"array\" (sequence). type Array = Vector Value -- | A JSON value represented as a Haskell value. data Value = Object !Object | Array !Array | String !Text | Number !Scientific | Bool !Bool | Null deriving (Eq, Read, Show, Typeable, Data, Generic) -- | A newtype wrapper for 'UTCTime' that uses the same non-standard -- serialization format as Microsoft .NET, whose -- <https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx System.DateTime> -- type is by default serialized to JSON as in the following example: -- -- > /Date(1302547608878)/ -- -- The number represents milliseconds since the Unix epoch. newtype DotNetTime = DotNetTime { fromDotNetTime :: UTCTime -- ^ Acquire the underlying value. } deriving (Eq, Ord, Read, Show, Typeable, FormatTime) instance NFData Value where rnf (Object o) = rnf o rnf (Array a) = foldl' (\x y -> rnf y `seq` x) () a rnf (String s) = rnf s rnf (Number n) = rnf n rnf (Bool b) = rnf b rnf Null = () instance IsString Value where fromString = String . pack {-# INLINE fromString #-} hashValue :: Int -> Value -> Int #if MIN_VERSION_unordered_containers(0,2,6) hashValue s (Object o) = s `hashWithSalt` (0::Int) `hashWithSalt` o #else hashValue s (Object o) = foldl' hashWithSalt (s `hashWithSalt` (0::Int)) assocHashesSorted where assocHashesSorted = sort [hash k `hashWithSalt` v | (k, v) <- H.toList o] #endif hashValue s (Array a) = foldl' hashWithSalt (s `hashWithSalt` (1::Int)) a hashValue s (String str) = s `hashWithSalt` (2::Int) `hashWithSalt` str hashValue s (Number n) = s `hashWithSalt` (3::Int) `hashWithSalt` n hashValue s (Bool b) = s `hashWithSalt` (4::Int) `hashWithSalt` b hashValue s Null = s `hashWithSalt` (5::Int) instance Hashable Value where hashWithSalt = hashValue -- @since 0.11.0.0 instance TH.Lift Value where lift Null = [| Null |] lift (Bool b) = [| Bool b |] lift (Number n) = [| Number (S.scientific c e) |] where c = S.coefficient n e = S.base10Exponent n lift (String t) = [| String (pack s) |] where s = unpack t lift (Array a) = [| Array (V.fromList a') |] where a' = V.toList a lift (Object o) = [| Object (H.fromList . map (first pack) $ o') |] where o' = map (first unpack) . H.toList $ o -- | The empty array. emptyArray :: Value emptyArray = Array V.empty -- | Determines if the 'Value' is an empty 'Array'. -- Note that: @isEmptyArray 'emptyArray'@. isEmptyArray :: Value -> Bool isEmptyArray (Array arr) = V.null arr isEmptyArray _ = False -- | The empty object. emptyObject :: Value emptyObject = Object H.empty -- | Run a 'Parser'. parse :: (a -> Parser b) -> a -> Result b parse m v = runParser (m v) [] (const Error) Success {-# INLINE parse #-} -- | Run a 'Parser'. iparse :: (a -> Parser b) -> a -> IResult b iparse m v = runParser (m v) [] IError ISuccess {-# INLINE iparse #-} -- | Run a 'Parser' with a 'Maybe' result type. parseMaybe :: (a -> Parser b) -> a -> Maybe b parseMaybe m v = runParser (m v) [] (\_ _ -> Nothing) Just {-# INLINE parseMaybe #-} -- | Run a 'Parser' with an 'Either' result type. If the parse fails, -- the 'Left' payload will contain an error message. parseEither :: (a -> Parser b) -> a -> Either String b parseEither m v = runParser (m v) [] onError Right where onError path msg = Left (formatError path msg) {-# INLINE parseEither #-} -- | Annotate an error message with a -- <http://goessner.net/articles/JsonPath/ JSONPath> error location. formatError :: JSONPath -> String -> String formatError path msg = "Error in " ++ format "$" path ++ ": " ++ msg where format :: String -> JSONPath -> String format pfx [] = pfx format pfx (Index idx:parts) = format (pfx ++ "[" ++ show idx ++ "]") parts format pfx (Key key:parts) = format (pfx ++ formatKey key) parts formatKey :: Text -> String formatKey key | isIdentifierKey strKey = "." ++ strKey | otherwise = "['" ++ escapeKey strKey ++ "']" where strKey = unpack key isIdentifierKey :: String -> Bool isIdentifierKey [] = False isIdentifierKey (x:xs) = isAlpha x && all isAlphaNum xs escapeKey :: String -> String escapeKey = concatMap escapeChar escapeChar :: Char -> String escapeChar '\'' = "\\'" escapeChar '\\' = "\\\\" escapeChar c = [c] -- | A key\/value pair for an 'Object'. type Pair = (Text, Value) -- | Create a 'Value' from a list of name\/value 'Pair's. If duplicate -- keys arise, earlier keys and their associated values win. object :: [Pair] -> Value object = Object . H.fromList {-# INLINE object #-} -- | Add JSON Path context to a parser -- -- When parsing a complex structure, it helps to annotate (sub)parsers -- with context, so that if an error occurs, you can find its location. -- -- > withObject "Person" $ \o -> -- > Person -- > <$> o .: "name" <?> Key "name" -- > <*> o .: "age" <?> Key "age" -- -- (Standard methods like '(.:)' already do this.) -- -- With such annotations, if an error occurs, you will get a JSON Path -- location of that error. -- -- Since 0.10 (<?>) :: Parser a -> JSONPathElement -> Parser a p <?> pathElem = Parser $ \path kf ks -> runParser p (pathElem:path) kf ks -- | If the inner @Parser@ failed, modify the failure message using the -- provided function. This allows you to create more descriptive error messages. -- For example: -- -- > parseJSON (Object o) = modifyFailure -- > ("Parsing of the Foo value failed: " ++) -- > (Foo <$> o .: "someField") -- -- Since 0.6.2.0 modifyFailure :: (String -> String) -> Parser a -> Parser a modifyFailure f (Parser p) = Parser $ \path kf ks -> p path (\p' m -> kf p' (f m)) ks -- | Throw a parser error with an additional path. -- -- @since 1.2.1.0 parserThrowError :: JSONPath -> String -> Parser a parserThrowError path' msg = Parser $ \path kf _ks -> kf (reverse path ++ path') msg -- | A handler function to handle previous errors and return to normal execution. -- -- @since 1.2.1.0 parserCatchError :: Parser a -> (JSONPath -> String -> Parser a) -> Parser a parserCatchError (Parser p) handler = Parser $ \path kf ks -> p path (\e msg -> runParser (handler e msg) path kf ks) ks -------------------------------------------------------------------------------- -- Generic and TH encoding configuration -------------------------------------------------------------------------------- -- | Options that specify how to encode\/decode your datatype to\/from JSON. -- -- Options can be set using record syntax on 'defaultOptions' with the fields -- below. data Options = Options { fieldLabelModifier :: String -> String -- ^ Function applied to field labels. -- Handy for removing common record prefixes for example. , constructorTagModifier :: String -> String -- ^ Function applied to constructor tags which could be handy -- for lower-casing them for example. , allNullaryToStringTag :: Bool -- ^ If 'True' the constructors of a datatype, with /all/ -- nullary constructors, will be encoded to just a string with -- the constructor tag. If 'False' the encoding will always -- follow the `sumEncoding`. , omitNothingFields :: Bool -- ^ If 'True' record fields with a 'Nothing' value will be -- omitted from the resulting object. If 'False' the resulting -- object will include those fields mapping to @null@. , sumEncoding :: SumEncoding -- ^ Specifies how to encode constructors of a sum datatype. , unwrapUnaryRecords :: Bool -- ^ Hide the field name when a record constructor has only one -- field, like a newtype. , tagSingleConstructors :: Bool -- ^ Encode types with a single constructor as sums, -- so that `allNullaryToStringTag` and `sumEncoding` apply. } instance Show Options where show (Options f c a o s u t) = "Options {" ++ intercalate ", " [ "fieldLabelModifier =~ " ++ show (f "exampleField") , "constructorTagModifier =~ " ++ show (c "ExampleConstructor") , "allNullaryToStringTag = " ++ show a , "omitNothingFields = " ++ show o , "sumEncoding = " ++ show s , "unwrapUnaryRecords = " ++ show u , "tagSingleConstructors = " ++ show t ] ++ "}" -- | Specifies how to encode constructors of a sum datatype. data SumEncoding = TaggedObject { tagFieldName :: String , contentsFieldName :: String } -- ^ A constructor will be encoded to an object with a field -- 'tagFieldName' which specifies the constructor tag (modified by -- the 'constructorTagModifier'). If the constructor is a record -- the encoded record fields will be unpacked into this object. So -- make sure that your record doesn't have a field with the same -- label as the 'tagFieldName'. Otherwise the tag gets overwritten -- by the encoded value of that field! If the constructor is not a -- record the encoded constructor contents will be stored under -- the 'contentsFieldName' field. | UntaggedValue -- ^ Constructor names won't be encoded. Instead only the contents of the -- constructor will be encoded as if the type had a single constructor. JSON -- encodings have to be disjoint for decoding to work properly. -- -- When decoding, constructors are tried in the order of definition. If some -- encodings overlap, the first one defined will succeed. -- -- /Note:/ Nullary constructors are encoded as strings (using -- 'constructorTagModifier'). Having a nullary constructor alongside a -- single field constructor that encodes to a string leads to ambiguity. -- -- /Note:/ Only the last error is kept when decoding, so in the case of -- malformed JSON, only an error for the last constructor will be reported. | ObjectWithSingleField -- ^ A constructor will be encoded to an object with a single -- field named after the constructor tag (modified by the -- 'constructorTagModifier') which maps to the encoded contents of -- the constructor. | TwoElemArray -- ^ A constructor will be encoded to a 2-element array where the -- first element is the tag of the constructor (modified by the -- 'constructorTagModifier') and the second element the encoded -- contents of the constructor. deriving (Eq, Show) -- | Default encoding 'Options': -- -- @ -- 'Options' -- { 'fieldLabelModifier' = id -- , 'constructorTagModifier' = id -- , 'allNullaryToStringTag' = True -- , 'omitNothingFields' = False -- , 'sumEncoding' = 'defaultTaggedObject' -- , 'unwrapUnaryRecords' = False -- , 'tagSingleConstructors' = False -- } -- @ defaultOptions :: Options defaultOptions = Options { fieldLabelModifier = id , constructorTagModifier = id , allNullaryToStringTag = True , omitNothingFields = False , sumEncoding = defaultTaggedObject , unwrapUnaryRecords = False , tagSingleConstructors = False } -- | Default 'TaggedObject' 'SumEncoding' options: -- -- @ -- defaultTaggedObject = 'TaggedObject' -- { 'tagFieldName' = \"tag\" -- , 'contentsFieldName' = \"contents\" -- } -- @ defaultTaggedObject :: SumEncoding defaultTaggedObject = TaggedObject { tagFieldName = "tag" , contentsFieldName = "contents" } -- | Converts from CamelCase to another lower case, interspersing -- the character between all capital letters and their previous -- entries, except those capital letters that appear together, -- like 'API'. -- -- For use by Aeson template haskell calls. -- -- > camelTo '_' 'CamelCaseAPI' == "camel_case_api" camelTo :: Char -> String -> String {-# DEPRECATED camelTo "Use camelTo2 for better results" #-} camelTo c = lastWasCap True where lastWasCap :: Bool -- ^ Previous was a capital letter -> String -- ^ The remaining string -> String lastWasCap _ [] = [] lastWasCap prev (x : xs) = if isUpper x then if prev then toLower x : lastWasCap True xs else c : toLower x : lastWasCap True xs else x : lastWasCap False xs -- | Better version of 'camelTo'. Example where it works better: -- -- > camelTo '_' 'CamelAPICase' == "camel_apicase" -- > camelTo2 '_' 'CamelAPICase' == "camel_api_case" camelTo2 :: Char -> String -> String camelTo2 c = map toLower . go2 . go1 where go1 "" = "" go1 (x:u:l:xs) | isUpper u && isLower l = x : c : u : l : go1 xs go1 (x:xs) = x : go1 xs go2 "" = "" go2 (l:u:xs) | isLower l && isUpper u = l : c : u : go2 xs go2 (x:xs) = x : go2 xs
sol/aeson
Data/Aeson/Types/Internal.hs
bsd-3-clause
21,962
0
14
6,009
4,560
2,546
2,014
416
6
import Control.Exception import Control.Monad import qualified Data.ByteString.Lazy as BS import Text.XML.HaXml.ByteStringPP import Text.XML.HaXml.Parse (xmlParse') import XmlLibrary main = mainBenchmark haXmlLibrary haXmlLibrary = XmlLibrary parse render where parse fp = readFile fp >>= either fail return . xmlParse' fp render fp = BS.writeFile fp . document
pepeiborra/xml-bench
src/Haxml.hs
bsd-3-clause
371
0
9
54
106
58
48
10
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Transform.Extract.Common ( BlockKind, ExtractFunc, Extractor, ExtractOptions(..), runExtractor, Entry, entryPath, scopedEntry, tellEntry, getOptions ) where import Control.Monad.State.Lazy (StateT, evalStateT, gets, modify) import Control.Monad.Trans (liftIO) import Hoops.SyntaxToken import System.FilePath ((</>)) import System.IO (openFile, IOMode(WriteMode), hClose, Handle, hPutStr) type BlockKind = String type NamePrefix = String type Extension = String type ExtractFunc = [SyntaxToken Hoops] -> Extractor (Maybe [SyntaxToken Hoops]) type EntryId = Int data ExtractOptions = ExtractOptions { minStmtRequirement :: Int } deriving (Show) data ExtractorState = ExtractorState { entryBasePath :: FilePath, nextEntryId :: EntryId, options :: ExtractOptions } newtype Extractor a = Extractor { unExtractor :: StateT ExtractorState IO a } deriving (Functor, Applicative, Monad) runExtractor :: ExtractOptions -> FilePath -> Extractor a -> IO a runExtractor opts basePath = flip evalStateT st . unExtractor where st = ExtractorState { entryBasePath = basePath, nextEntryId = 0, options = opts } data Entry = Entry { entryHandle :: Handle, entryPath :: FilePath } deriving (Show) newEntry :: NamePrefix -> Extension -> Extractor Entry newEntry entryPrefix ext = Extractor $ do basePath <- gets entryBasePath entId <- gets nextEntryId modify $ \st -> st { nextEntryId = entId + 1 } let path = basePath </> (entryPrefix ++ "-" ++ show entId ++ "." ++ ext) handle <- liftIO $ openFile path WriteMode let entry = Entry { entryHandle = handle, entryPath = path } return entry scopedEntry :: NamePrefix -> Extension -> (Entry -> Extractor a) -> Extractor a scopedEntry entryPrefix ext f = do entry <- newEntry entryPrefix ext res <- f entry Extractor $ liftIO $ hClose $ entryHandle entry return res tellEntry :: Entry -> String -> Extractor () tellEntry entry str = Extractor $ do liftIO $ hPutStr (entryHandle entry) str getOptions :: Extractor ExtractOptions getOptions = Extractor $ gets options
thomaseding/cgs
src/Transform/Extract/Common.hs
bsd-3-clause
2,235
0
16
490
668
365
303
62
1
module KifuDB.Model.Type ( Player(..) , Koma(..) , Masu(..) , Pos(..) , Result(..) , Ban(..) , Fugou(..) , showKoma , getAt , initBan , emptyBan , nextBan , drawBan ) where import KifuDB.Model.Type.Internal
suzuki-shin/kifuDB
src/KifuDB/Model/Type.hs
bsd-3-clause
266
0
5
91
83
58
25
15
0
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE Trustworthy #-} #include "lens-common.h" ----------------------------------------------------------------------------- -- | -- Module : Data.Set.Lens -- Copyright : (C) 2012-16 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : portable -- ---------------------------------------------------------------------------- module Data.Set.Lens ( setmapped , setOf ) where import Control.Lens.Getter ( Getting, views ) import Control.Lens.Setter ( setting ) import Control.Lens.Type import Data.Set as Set -- $setup -- >>> :set -XNoOverloadedStrings -- >>> import Control.Lens -- | This 'Setter' can be used to change the type of a 'Set' by mapping -- the elements to new values. -- -- Sadly, you can't create a valid 'Traversal' for a 'Set', but you can -- manipulate it by reading using 'Control.Lens.Fold.folded' and reindexing it via 'setmapped'. -- -- >>> over setmapped (+1) (fromList [1,2,3,4]) -- fromList [2,3,4,5] #if MIN_VERSION_containers(0,5,2) setmapped :: Ord j => IndexPreservingSetter (Set i) (Set j) i j #else setmapped :: (Ord i, Ord j) => IndexPreservingSetter (Set i) (Set j) i j #endif setmapped = setting Set.map {-# INLINE setmapped #-} -- | Construct a set from a 'Getter', 'Control.Lens.Fold.Fold', 'Control.Lens.Traversal.Traversal', 'Control.Lens.Lens.Lens' or 'Control.Lens.Iso.Iso'. -- -- >>> setOf folded ["hello","world"] -- fromList ["hello","world"] -- -- >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)] -- fromList [1,2,3] -- -- @ -- 'setOf' :: 'Getter' s a -> s -> 'Set' a -- 'setOf' :: 'Ord' a => 'Fold' s a -> s -> 'Set' a -- 'setOf' :: 'Iso'' s a -> s -> 'Set' a -- 'setOf' :: 'Lens'' s a -> s -> 'Set' a -- 'setOf' :: 'Ord' a => 'Traversal'' s a -> s -> 'Set' a -- @ setOf :: Getting (Set a) s a -> s -> Set a setOf l = views l Set.singleton {-# INLINE setOf #-}
ddssff/lens
src/Data/Set/Lens.hs
bsd-3-clause
2,050
0
8
386
185
122
63
16
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} {-# LANGUAGE EmptyCase #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UndecidableSuperClasses #-} -- | Render the first widget on the server, and the second on the client. module Reflex.Dom.Prerender ( Prerender (..) , prerender_ , PrerenderClientConstraint , PrerenderBaseConstraints ) where import Control.Monad.Primitive (PrimMonad(..)) import Control.Monad.Reader import Control.Monad.Ref (MonadRef(..), MonadAtomicRef(..)) import Data.IORef (IORef, newIORef) import Data.Semigroup (Semigroup) import Data.Text (Text) import Data.Void import Foreign.JavaScript.TH import GHCJS.DOM.Types (MonadJSM) import Reflex hiding (askEvents) import Reflex.Dom.Builder.Class import Reflex.Dom.Builder.Hydratable import Reflex.Dom.Builder.Immediate import Reflex.Dom.Builder.InputDisabled import Reflex.Dom.Builder.Static import Reflex.Host.Class import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import qualified GHCJS.DOM.Document as Document import qualified GHCJS.DOM.Node as Node import qualified GHCJS.DOM.Types as DOM type PrerenderClientConstraint js t m = ( DomBuilder t m , DomBuilderSpace m ~ GhcjsDomSpace , DomRenderHook t m , HasDocument m , TriggerEvent t m , PrerenderBaseConstraints js t m ) type PrerenderBaseConstraints js t m = ( HasJSContext (Performable m) , HasJSContext m , MonadFix m , MonadHold t m , MonadJSM (Performable m) , MonadJSM m , MonadRef (Performable m) , MonadRef m , MonadReflexCreateTrigger t m , MonadSample t (Performable m) , PerformEvent t m , PostBuild t m , PrimMonad m , Ref (Performable m) ~ IORef , Ref m ~ IORef , HasJS js m , HasJS js (Performable m) ) -- | Render the first widget on the server, and the second on the client. The -- hydration builder will run *both* widgets. prerender_ :: (Functor m, Reflex t, Prerender js t m) => m () -> Client m () -> m () prerender_ server client = void $ prerender server client class (PrerenderClientConstraint js t (Client m), Client (Client m) ~ Client m, Prerender js t (Client m)) => Prerender js t m | m -> t js where -- | Monad in which the client widget is built type Client m :: * -> * -- | Render the first widget on the server, and the second on the client. The -- hydration builder will run *both* widgets, updating the result dynamic at -- switchover time. prerender :: m a -> Client m a -> m (Dynamic t a) instance (ReflexHost t, Adjustable t m, PrerenderBaseConstraints js t m) => Prerender js t (HydrationDomBuilderT GhcjsDomSpace t m) where type Client (HydrationDomBuilderT GhcjsDomSpace t m) = HydrationDomBuilderT GhcjsDomSpace t m prerender _ client = pure <$> client instance (Adjustable t m, PrerenderBaseConstraints js t m, ReflexHost t) => Prerender js t (HydrationDomBuilderT HydrationDomSpace t m) where -- | PostBuildT is needed here because we delay running the client builder -- until after switchover, at which point the postBuild of @m@ has already fired type Client (HydrationDomBuilderT HydrationDomSpace t m) = PostBuildT t (HydrationDomBuilderT GhcjsDomSpace t m) -- | Runs the server widget up until switchover, then replaces it with the -- client widget. prerender server client = do env <- HydrationDomBuilderT ask events <- askEvents doc <- askDocument serverDf <- Document.createDocumentFragment doc -- server dom should not be mounted in the window's doc in hydration df <- Document.createDocumentFragment doc unreadyChildren <- HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_unreadyChildren immediateMode <- liftIO $ newIORef HydrationMode_Immediate delayed <- liftIO $ newIORef $ pure () let clientEnv = env { _hydrationDomBuilderEnv_parent = Left $ DOM.toNode df , _hydrationDomBuilderEnv_hydrationMode = immediateMode } serverEnv = HydrationDomBuilderEnv { _hydrationDomBuilderEnv_document = doc , _hydrationDomBuilderEnv_parent = Left $ DOM.toNode serverDf , _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren , _hydrationDomBuilderEnv_commitAction = pure () , _hydrationDomBuilderEnv_delayed = delayed , _hydrationDomBuilderEnv_hydrationMode = immediateMode , _hydrationDomBuilderEnv_switchover = never } a0 <- lift $ runHydrationDomBuilderT server serverEnv events (a', trigger) <- newTriggerEvent getHydrationMode >>= \case HydrationMode_Immediate -> do liftIO . trigger <=< lift $ runHydrationDomBuilderT (runPostBuildT client $ void a') clientEnv events append $ DOM.toNode df HydrationMode_Hydrating -> addHydrationStep $ do liftIO . trigger <=< lift $ runHydrationDomBuilderT (runPostBuildT client $ void a') clientEnv events insertBefore df =<< deleteToPrerenderEnd doc holdDyn a0 a' newtype UnrunnableT js t m a = UnrunnableT (ReaderT Void m a) deriving (Functor, Applicative, Monad, MonadTrans) unrunnable :: UnrunnableT js t m a unrunnable = UnrunnableT $ ReaderT $ \case {} instance (Reflex t, Monad m) => DomBuilder t (UnrunnableT js t m) where type DomBuilderSpace (UnrunnableT js t m) = GhcjsDomSpace textNode _ = unrunnable commentNode _ = unrunnable element _ _ _ = unrunnable inputElement _ = unrunnable textAreaElement _ = unrunnable selectElement _ _ = unrunnable placeRawElement _ = unrunnable wrapRawElement _ _ = unrunnable instance (Reflex t, Monad m) => NotReady t (UnrunnableT js t m) where notReadyUntil _ = unrunnable notReady = unrunnable instance (Reflex t, Monad m) => Adjustable t (UnrunnableT js t m) where runWithReplace _ _ = unrunnable traverseIntMapWithKeyWithAdjust _ _ _ = unrunnable traverseDMapWithKeyWithAdjust _ _ _ = unrunnable traverseDMapWithKeyWithAdjustWithMove _ _ _ = unrunnable instance (Reflex t, Monad m) => PerformEvent t (UnrunnableT js t m) where type Performable (UnrunnableT js t m) = UnrunnableT js t m performEvent _ = unrunnable performEvent_ _ = unrunnable instance Monad m => MonadRef (UnrunnableT js t m) where type Ref (UnrunnableT js t m) = Ref IO newRef _ = unrunnable readRef _ = unrunnable writeRef _ _ = unrunnable instance Monad m => MonadAtomicRef (UnrunnableT js t m) where atomicModifyRef _ _ = unrunnable instance Monad m => HasDocument (UnrunnableT js t m) where askDocument = unrunnable instance Monad m => HasJSContext (UnrunnableT js t m) where type JSContextPhantom (UnrunnableT js t m) = () askJSContext = unrunnable instance Monad m => HasJS JS' (UnrunnableT js t m) where type JSX (UnrunnableT js t m) = UnrunnableT js t m liftJS _ = unrunnable instance Monad m => MonadJS JS' (UnrunnableT js t m) where runJS _ _ = unrunnable forkJS _ = unrunnable mkJSUndefined = unrunnable isJSNull _ = unrunnable isJSUndefined _ = unrunnable fromJSBool _ = unrunnable fromJSString _ = unrunnable fromJSArray _ = unrunnable fromJSUint8Array _ = unrunnable fromJSNumber _ = unrunnable withJSBool _ _ = unrunnable withJSString _ _ = unrunnable withJSNumber _ _ = unrunnable withJSArray _ _ = unrunnable withJSUint8Array _ _ = unrunnable mkJSFun _ = unrunnable freeJSFun _ = unrunnable setJSProp _ _ _ = unrunnable getJSProp _ _ = unrunnable withJSNode _ _ = unrunnable instance Monad m => TriggerEvent t (UnrunnableT js t m) where newTriggerEvent = unrunnable newTriggerEventWithOnComplete = unrunnable newEventWithLazyTriggerWithOnComplete _ = unrunnable instance Monad m => MonadReflexCreateTrigger t (UnrunnableT js t m) where newEventWithTrigger _ = unrunnable newFanEventWithTrigger _ = unrunnable instance Monad m => MonadFix (UnrunnableT js t m) where mfix _ = unrunnable instance Monad m => MonadHold t (UnrunnableT js t m) where hold _ _ = unrunnable holdDyn _ _ = unrunnable holdIncremental _ _ = unrunnable buildDynamic _ _ = unrunnable headE _ = unrunnable instance Monad m => MonadSample t (UnrunnableT js t m) where sample _ = unrunnable instance Monad m => MonadIO (UnrunnableT js t m) where liftIO _ = unrunnable #ifndef ghcjs_HOST_OS instance Monad m => MonadJSM (UnrunnableT js t m) where liftJSM' _ = unrunnable #endif instance (Reflex t, Monad m) => PostBuild t (UnrunnableT js t m) where getPostBuild = unrunnable instance Monad m => PrimMonad (UnrunnableT js t m) where type PrimState (UnrunnableT js t m) = PrimState IO primitive _ = unrunnable instance (Reflex t, Monad m) => DomRenderHook t (UnrunnableT js t m) where withRenderHook _ _ = unrunnable requestDomAction _ = unrunnable requestDomAction_ _ = unrunnable instance (Reflex t, Monad m) => Prerender JS' t (UnrunnableT js t m) where type Client (UnrunnableT js t m) = UnrunnableT js t m prerender _ _ = unrunnable instance (SupportsStaticDomBuilder t m) => Prerender JS' t (StaticDomBuilderT t m) where type Client (StaticDomBuilderT t m) = UnrunnableT JS' t m prerender server _ = do _ <- commentNode $ CommentNodeConfig startMarker Nothing a <- server _ <- commentNode $ CommentNodeConfig endMarker Nothing pure $ pure a instance (Prerender js t m, Monad m) => Prerender js t (ReaderT r m) where type Client (ReaderT r m) = ReaderT r (Client m) prerender server client = do r <- ask lift $ prerender (runReaderT server r) (runReaderT client r) instance (Prerender js t m, Monad m, Reflex t, MonadFix m, Monoid w) => Prerender js t (DynamicWriterT t w m) where type Client (DynamicWriterT t w m) = DynamicWriterT t w (Client m) prerender server client = do x <- lift $ prerender (runDynamicWriterT server) (runDynamicWriterT client) let (a, w') = splitDynPure x w = join w' tellDyn w pure a instance (Prerender js t m, Monad m, Reflex t, Semigroup w) => Prerender js t (EventWriterT t w m) where type Client (EventWriterT t w m) = EventWriterT t w (Client m) prerender server client = do x <- lift $ prerender (runEventWriterT server) (runEventWriterT client) let (a, w') = splitDynPure x w = switch $ current w' tellEvent w pure a instance (Prerender js t m, MonadFix m, Reflex t) => Prerender js t (RequesterT t request response m) where type Client (RequesterT t request response m) = RequesterT t request response (Client m) prerender server client = mdo let fannedResponses = fanInt responses withFannedResponses :: forall m' a. Monad m' => RequesterT t request response m' a -> Int -> m' (a, Event t (IntMap (RequesterData request))) withFannedResponses w selector = do (x, e) <- runRequesterT w (selectInt fannedResponses selector) pure (x, fmapCheap (IntMap.singleton selector) e) (result, requestsDyn) <- fmap splitDynPure $ lift $ prerender (withFannedResponses server 0) (withFannedResponses client 1) responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requestsDyn return result instance (Prerender js t m, Monad m, Reflex t, MonadFix m, Group q, Additive q, Query q, Eq q) => Prerender js t (QueryT t q m) where type Client (QueryT t q m) = QueryT t q (Client m) prerender server client = mdo result <- queryDyn query x <- lift $ prerender (runQueryT server result) (runQueryT client result) let (a, inc) = splitDynPure x query = incrementalToDynamic =<< inc -- Can we avoid the incrementalToDynamic? pure a instance (Prerender js t m, Monad m) => Prerender js t (InputDisabledT m) where type Client (InputDisabledT m) = InputDisabledT (Client m) prerender (InputDisabledT server) (InputDisabledT client) = InputDisabledT $ prerender server client instance (Prerender js t m, Monad m) => Prerender js t (HydratableT m) where type Client (HydratableT m) = HydratableT (Client m) prerender (HydratableT server) (HydratableT client) = HydratableT $ prerender server client instance (Prerender js t m, Monad m, ReflexHost t) => Prerender js t (PostBuildT t m) where type Client (PostBuildT t m) = PostBuildT t (Client m) prerender server client = PostBuildT $ do pb <- ask lift $ prerender (runPostBuildT server pb) (runPostBuildT client pb) startMarker, endMarker :: Text startMarker = "prerender/start" endMarker = "prerender/end" deleteToPrerenderEnd :: (MonadIO m, MonadJSM m, Reflex t, MonadFix m) => DOM.Document -> HydrationRunnerT t m DOM.Comment deleteToPrerenderEnd doc = do startNode <- hydrateComment doc startMarker Nothing let go (n :: Int) lastNode = Node.getNextSibling lastNode >>= \case Nothing -> do c <- Document.createComment doc endMarker insertAfterPreviousNode c pure c Just node -> DOM.castTo DOM.Comment node >>= \case Nothing -> go n node Just c -> Node.getTextContentUnchecked c >>= \case t | t == startMarker -> go (succ n) node | t == endMarker -> case n of 0 -> pure c _ -> go (pred n) node | otherwise -> go n node endNode <- go 0 $ DOM.toNode startNode deleteBetweenExclusive startNode endNode setPreviousNode $ Just $ DOM.toNode endNode pure endNode
ryantrinkle/reflex-dom
reflex-dom-core/src/Reflex/Dom/Prerender.hs
bsd-3-clause
13,606
1
28
2,791
4,301
2,180
2,121
-1
-1
module Websave.Web.AppData ( App (..) ) where import Data.Pool (Pool) import Database.PostgreSQL.Simple (Connection) import Yesod.Static (Static) data App = App { getConnectionPool :: Pool Connection , getStatic :: Static }
dimsmol/websave
src/Websave/Web/AppData.hs
bsd-3-clause
244
0
9
50
71
44
27
8
0
module Init where import Configuration import TodoArguments import System.Directory import System.FilePath import Database.HDBC import Database.HDBC.Sqlite3 createDatabase :: TodoCommand -> Config -> IO () createDatabase initCommand config = case databaseFile initCommand of Nothing -> if userLevel initCommand then runCreateDatabase $ defaultDatabaseLocation config else runCreateDatabase $ defaultDatabaseName config Just databasePath -> runCreateDatabase databasePath runCreateDatabase :: String -> IO () runCreateDatabase filename = do exist <- doesFileExist filename if exist then putStrLn $ "Database at '" ++ filename ++ "' already exists. Doing nothing." else do putStrLn $ "Creating hTodo database: " ++ filename conn <- connectSqlite3 filename runRaw conn tableUpdates runRaw conn tableLists runRaw conn insertMainList runRaw conn tableItems runRaw conn tableItemEvents runRaw conn tableTags runRaw conn tableTagMap commit conn disconnect conn insertMainList = "INSERT INTO lists (id,name,hidden,created_at,parent_id) VALUES (1, 'Main', 0, datetime(), null)" tableUpdates = "create table updates ( version integer primary key, description text, upgradeDate date );" tableLists = "create table lists (" ++ "id integer primary key autoincrement not null," ++ "name text not null," ++ "hidden INT2 not null," ++ "created_at datetime not null," ++ "parent_id integer," ++ "FOREIGN KEY(parent_id) references lists(id) on delete cascade" ++ ");" tableItems = "create table items (" ++ "id integer primary key autoincrement not null," ++ "list_id integer not null," ++ "description text not null," ++ "current_state integer not null default 0," ++ "created_at datetime not null," ++ "priority integer not null," ++ "due_date date," ++ "FOREIGN KEY(list_id) references listts(id) on delete cascade" ++ ");" tableItemEvents = "create table item_events (" ++ "id integer primary key autoincrement not null," ++ "item_id integer not null," ++ "item_event_type integer not null," ++ "event_description text," ++ "occurred_at datetime not null," ++ "FOREIGN KEY(item_id) references items(id) on delete cascade" ++ ");" tableTags = "create table tags (" ++ "id integer primary key autoincrement not null," ++ "tag_name text not null," ++ "created_at datetime not null" ++ ");" tableTagMap = "create table tag_map (" ++ "item_id integer not null," ++ "tag_id integer not null," ++ "created_at datetime not null," ++ "FOREIGN KEY(item_id) references items(id) on delete cascade," ++ "FOREIGN KEY(tag_id) references tags(id) on delete cascade" ++ ");"
robertmassaioli/hdo
src/Init.hs
bsd-3-clause
3,139
0
13
944
420
205
215
72
3
{-| Module: ScaledImage Description: Scalable, positionable image widget Copyright: (c) Greg Hale, 2016 License: BSD3 Maintainer: [email protected] Stability: experimental Portability: GHCJS This module provides a reflex-dom widget for scaling and positioning images. A top-level div defaults to the natural size of a source image. The @topScale@ config parameter adjusts the size of this container. @sicSetOffset@, @sicSetScale@, and @sicSetBounding@ allow the image to be offset, scaled, and cropped while holding the top-level div's size constant. The crop is in dimensions of the natural size of the image (cropping an 10x10 pixel image by 5 pixels will always result in a picture cut in half) @imageSpace*@ properties transform various mouse events to the coordinate frame of the original imaage. -} {-# language BangPatterns #-} {-# language CPP #-} {-# language FlexibleContexts #-} {-# language GADTs #-} {-# language RecursiveDo #-} {-# language KindSignatures #-} {-# language LambdaCase #-} {-# language OverloadedStrings #-} {-# language RankNTypes #-} {-# language TypeFamilies #-} {-# language ScopedTypeVariables #-} module ScaledImage ( ScaledImageConfig(..), ScaledImage(..), scaledImage, BoundingBox (..), Coord(..), fI, r2, CanvasRenderingContext2D(..), ImageData(..), ClientRect(..), getWidth, getHeight, getBoundingClientRect, divImgSpace', divImgSpace, wheelEvents )where import Control.Monad (liftM2) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Bool import Data.Default (Default, def) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Text as T import Reflex.Dom hiding (restore) #ifdef ghcjs_HOST_OS import GHCJS.DOM.HTMLCanvasElement (getContext, castToHTMLCanvasElement) import GHCJS.DOM.CanvasRenderingContext2D (CanvasRenderingContext2D, save, restore, getImageData) import GHCJS.DOM.Types (ImageData, ClientRect, Nullable, nullableToMaybe) import GHCJS.Marshal (fromJSValUnchecked, toJSVal) import GHCJS.DOM.Element (getBoundingClientRect, getClientTop, getClientLeft) import GHCJS.DOM.ClientRect (getTop, getLeft, getWidth, getHeight) #endif import GHCJS.DOM.Types (IsGObject, HTMLCanvasElement, HTMLImageElement) import GHCJS.DOM.CanvasRenderingContext2D as Context2D import qualified GHCJS.DOM.HTMLImageElement as ImageElement import GHCJS.DOM.EventM (on, event, stopPropagation, preventDefault) import qualified GHCJS.DOM.ClientRect as CR import GHCJS.DOM.Element (getClientTop, getClientLeft) import GHCJS.DOM.MouseEvent (getClientX, getClientY) import qualified GHCJS.DOM.Types as GT import GHCJS.DOM.WheelEvent as WheelEvent import qualified GHCJS.DOM.Element as E data Coord = Coord { coordX :: !Double , coordY :: !Double } deriving (Eq, Show, Ord, Read) data BoundingBox = BoundingBox { bbTopLeft :: !Coord , bbBotRight :: !Coord } deriving (Eq, Show, Ord, Read) data ScaledImageConfig t = ScaledImageConfig { sicInitialSource :: T.Text , sicSetSource :: Event t T.Text , sicTopLevelScale :: Dynamic t Double , sicTopLevelAttributes :: Dynamic t (Map T.Text T.Text) , sicCroppingAttributes :: Dynamic t (Map T.Text T.Text) , sicImgStyle :: Dynamic t T.Text , sicInitialOffset :: (Double, Double) , sicSetOffset :: Event t (Double, Double) , sicInitialScale :: Double , sicSetScale :: Event t Double , sicInitialBounding :: Maybe BoundingBox , sicSetBounding :: Event t (Maybe BoundingBox) } instance Reflex t => Default (ScaledImageConfig t) where def = ScaledImageConfig "" never (constDyn 1) (constDyn mempty) (constDyn mempty) (constDyn "") (0,0) never 1 never def never data ScaledImage t = ScaledImage { siImage :: HTMLImageElement , siEl :: El t , siImgEl :: El t , siNaturalSize :: Dynamic t (Int,Int) , screenToImageSpace :: Dynamic t ((Double,Double) -> (Double, Double)) , imageToScreenSpace :: Dynamic t ((Double,Double) -> (Double, Double)) } -- | A widget supporting clipping, zooming, and translation of a source image. -- Composed of -- - a parent div fixed to the size of the source image, -- - a cropping div -- - the source image scaledImage :: forall t m. MonadWidget t m => ScaledImageConfig t -> m (ScaledImage t) scaledImage (ScaledImageConfig img0 dImg topScale topAttrs cropAttrs iStyle trans0 dTrans scale0 dScale bounding0 dBounding) = mdo pb <- getPostBuild firstLoad <- headE $ domEvent Load img naturalSize :: Dynamic t (Int,Int) <- holdDyn (1 :: Int, 1 :: Int) =<< performEvent (ffor firstLoad $ \() -> (,) <$> (ImageElement.getNaturalWidth htmlImg) <*> (ImageElement.getNaturalHeight htmlImg)) let htmlImg = ImageElement.castToHTMLImageElement (_element_raw img) imgSrc <- holdDyn img0 dImg bounding <- holdDyn bounding0 dBounding trans <- holdDyn trans0 dTrans innerScale <- holdDyn scale0 dScale let scale = zipDynWith (*) innerScale topScale shiftScreenPix = mkShiftScreenPix <$> trans <*> bounding <*> scale parentAttrs = mkTopLevelAttrs <$> naturalSize <*> topAttrs <*> topScale (parentDiv, (img, imgSpace, screenSpace)) <- elDynAttr' "div" parentAttrs $ do let croppingAttrs = mkCroppingAttrs <$> naturalSize <*> bounding <*> scale <*> shiftScreenPix <*> cropAttrs <*> iStyle imgAttrs = mkImgAttrs <$> imgSrc <*> naturalSize <*> scale <*> trans <*> bounding -- The DOM element for the image itself (croppingDiv,img) <- elDynAttr' "div" croppingAttrs $ fst <$> elDynAttr' "img" imgAttrs (return ()) let imgSpace = mkImgSpace <$> scale <*> shiftScreenPix screenSpace = mkScreenSpace <$> scale <*> shiftScreenPix return (img, imgSpace, screenSpace) return $ ScaledImage htmlImg parentDiv img naturalSize imgSpace screenSpace where mkTopLevelAttrs (naturalWid, naturalHei) topAttrs topScale = let defAttrs = "class" =: "scaled-image-top" <> "style" =: ("pointer-events:none;position:relative;overflow:hidden;width:" <> (T.pack . show) (fI naturalWid * topScale) <> "px;height:" <> (T.pack . show) (fI naturalHei * topScale) <> "px;") in Map.unionWith (<>) defAttrs topAttrs mkShiftScreenPix (natX, natY) bounding s = let (bX0,bY0) = maybe (0,0) (\(BoundingBox (Coord x y) _) -> (x,y)) bounding in ((bX0 + natX)*s, (bY0 + natY)*s) mkCroppingAttrs (natWid, natHei) bnd scale (offXPx, offYPx) attrs extStyle = let sizingStyle = case bnd of Nothing -> let w :: Int = round $ fI natWid * scale h :: Int = round $ fI natHei * scale x :: Int = round $ offXPx y :: Int = round $ offYPx in "width:" <> (T.pack . show) w <> "px; height: " <> (T.pack . show) h <> "px; left:" <> (T.pack . show) x <> "px;top:" <> (T.pack . show) y <> "px;" Just (BoundingBox (Coord x0 y0) (Coord x1 y1)) -> let w :: Int = round $ (x1 - x0) * scale h :: Int = round $ (y1 - y0) * scale x :: Int = round $ offXPx --(x0 <> offX) * scale y :: Int = round $ offYPx -- (y0 <> offY) * scale in ("width:" <> (T.pack . show) w <> "px;height:" <> (T.pack . show) h <> "px;" <> "left:" <> (T.pack . show) x <> "px;top:" <> (T.pack . show) y <> "px;") baseStyle = "pointer-events:auto;position:relative;overflow:hidden;" style = case Map.lookup "style" attrs of Nothing -> baseStyle <> sizingStyle <> extStyle Just s -> baseStyle <> sizingStyle <> s <> extStyle in Map.insert "style" style ("class" =: "cropping-div" <> attrs) mkImgAttrs src (naturalWid, naturalHei) scale (offX, offY) bb = let posPart = case bb of Nothing -> let w :: Int = round $ fI naturalWid * scale h :: Int = round $ fI naturalHei * scale in "width:" <> (T.pack . show) w <> "px; height: " <> (T.pack . show) h <> "px; position:absolute; left: 0px; top 0px;" Just (BoundingBox (Coord x0 y0) (Coord x1 y1)) -> let w :: Int = round $ fromIntegral naturalWid * scale h :: Int = round $ fromIntegral naturalHei * scale x :: Int = round $ negate x0 * scale y :: Int = round $ negate y0 * scale in "pointer-events:auto;position:absolute;left:" <> (T.pack . show) x <> "px;top:" <> (T.pack . show) y <> "px;" <> "width:" <> (T.pack . show) w <> "px;" in "src" =: src <> "style" =: posPart mkImgSpace scale (imgOffX, imgOffY) = \(x,y) -> ((x - imgOffX) / scale, (y - imgOffY) / scale) mkScreenSpace scale (imgOffX, imgOffY) = \(x,y)-> (scale * x + imgOffX, scale * y + imgOffY) relativizeEvent e f eventName shiftScreenPix = do let i = zipDynWith (,) f shiftScreenPix evs <- wrapDomEvent e (`on` eventName) $ do ev <- event Just br <- getBoundingClientRect e xOff <- (r2 . negate) <$> getLeft br yOff <- (r2 . negate) <$> getTop br liftM2 (,) (((<> xOff). fI) <$> getClientX ev) (((<> yOff) . fI) <$> getClientY ev) return $ attachWith (\(f,(dx,dy)) (x,y) -> f $ (x<>dx,y<>dy)) (current i) evs divImgSpace' :: MonadWidget t m => Dynamic t ((Double,Double) -> (Double,Double)) -> Dynamic t BoundingBox -> Dynamic t (Map T.Text T.Text) -> m a -> m (El t, a) divImgSpace' toWidgetSpace bounding attrs children = do let widgetPos = zipDynWith (\f bb -> let (x0,y0) = f (coordX (bbTopLeft bb), coordY (bbTopLeft bb)) (x1,y1) = f (coordX (bbBotRight bb), coordY (bbBotRight bb)) in ((x0,y0), (x1-x0, y1-y0)) ) toWidgetSpace bounding attrs' = zipDynWith (\((x0,y0), (w,h)) ats -> let left = "left: " <> (T.pack . show) x0 <> "px;" top = "top: " <> (T.pack . show) y0 <> "px;" wid = "width: " <> (T.pack . show) w <> "px;" hei = "height: " <> (T.pack . show) h <> "px;" thisStyle = "position: absolute; " <> mconcat [left, top, wid, hei] style' = thisStyle <> fromMaybe "" (Map.lookup "style" ats) in (Map.insert "style" style' ats) ) widgetPos attrs elDynAttr' "div" attrs' children divImgSpace :: MonadWidget t m => Dynamic t ((Double,Double) -> (Double,Double)) -> Dynamic t BoundingBox -> Dynamic t (Map T.Text T.Text) -> m a -> m a divImgSpace f b a c = fmap snd $ divImgSpace' f b a c fI :: (Integral a, RealFrac b) => a -> b fI = fromIntegral r2 :: (Real a, Fractional b) => a -> b r2 = realToFrac #ifndef ghcjs_HOST_OS fromJSValUnchecked = error "" toJSVal = error "" data CanvasRenderingContext2D data ImageData data ClientRect = ClientRect deriving Show getContext :: MonadIO m => HTMLCanvasElement -> T.Text -> m CanvasRenderingContext2D getContext = error "getContext only available in ghcjs" getImageData :: CanvasRenderingContext2D -> Float -> Float -> Float -> Float -> IO (Maybe ImageData) getImageData = error "getImageData only available in ghcjs" castToHTMLCanvasElement :: IsGObject obj => obj -> HTMLCanvasElement castToHTMLCanvasElement = error "castToHTMLCanvasElement only available in ghcjs" save :: MonadIO m => CanvasRenderingContext2D -> m () save = error "save only available in ghcjs" restore :: MonadIO m => CanvasRenderingContext2D -> m () restore = error "restore only available in ghcjs" getBoundingClientRect :: MonadIO m => a -> m (Maybe ClientRect) getBoundingClientRect = error "getBoundingClientRect only available in ghcjs" getTop :: MonadIO m => ClientRect -> m Float getTop = error "getTop only available in ghcjs" getLeft :: MonadIO m => ClientRect -> m Float getLeft = error "getLeft only available in ghcjs" getWidth :: MonadIO m => ClientRect -> m Float getWidth = error "getWidth only available in ghcjs" getHeight :: MonadIO m => ClientRect -> m Float getHeight = error "getHeight only available in ghcjs" #endif wheelEvents x = do wrapDomEvent (_element_raw x) (`on` E.wheel) $ do ev <- event delY <- getDeltaY ev Just br <- getBoundingClientRect (_element_raw x) xOff <- fmap (r2 . negate) (getLeft br) yOff <- fmap (r2 . negate) (getTop br) cX <- getClientX ev cY <- getClientY ev return (delY, (fI cX + xOff, fI cY + yOff ))
CBMM/petersonfaces
petersonfaces-frontend/src/ScaledImage.hs
bsd-3-clause
13,182
11
33
3,551
3,889
2,071
1,818
-1
-1
{-# LANGUAGE ForeignFunctionInterface, CPP #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.NV.HalfFloat -- Copyright : (c) Sven Panne 2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- All raw functions, tokens and types from the NV_fragment_program extension, -- see <http://www.opengl.org/registry/specs/NV/fragment_program.txt>. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.NV.HalfFloat ( -- * Functions glVertex2h, glVertex2hv, glVertex3h, glVertex3hv, glVertex4h, glVertex4hv, glNormal3h, glNormal3hv, glColor3h, glColor3hv, glColor4h, glColor4hv, glTexCoord1h, glTexCoord1hv, glTexCoord2h, glTexCoord2hv, glTexCoord3h, glTexCoord3hv, glTexCoord4h, glTexCoord4hv, glMultiTexCoord1h, glMultiTexCoord1hv, glMultiTexCoord2h, glMultiTexCoord2hv, glMultiTexCoord3h, glMultiTexCoord3hv, glMultiTexCoord4h, glMultiTexCoord4hv, glFogCoordh, glFogCoordhv, glSecondaryColor3h, glSecondaryColor3hv, glVertexWeighth, glVertexWeighthv, glVertexAttrib1h, glVertexAttrib1hv, glVertexAttrib2h, glVertexAttrib2hv, glVertexAttrib3h, glVertexAttrib3hv, glVertexAttrib4h, glVertexAttrib4hv, glVertexAttribs1hv, glVertexAttribs2hv, glVertexAttribs3hv, glVertexAttribs4hv, -- * Tokens gl_HALF_FLOAT, -- * Types GLhalf ) where import Foreign.Ptr import Foreign.C.Types import Graphics.Rendering.OpenGL.Raw.Core31.Types import Graphics.Rendering.OpenGL.Raw.Core32 import Graphics.Rendering.OpenGL.Raw.Extensions #include "HsOpenGLRaw.h" extensionNameString :: String extensionNameString = "GL_NV_half_float" EXTENSION_ENTRY(dyn_glVertex2h,ptr_glVertex2h,"glVertex2h",glVertex2h,GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertex2hv,ptr_glVertex2hv,"glVertex2hv",glVertex2hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertex3h,ptr_glVertex3h,"glVertex3h",glVertex3h,GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertex3hv,ptr_glVertex3hv,"glVertex3hv",glVertex3hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertex4h,ptr_glVertex4h,"glVertex4h",glVertex4h,GLhalf -> GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertex4hv,ptr_glVertex4hv,"glVertex4hv",glVertex4hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glNormal3h,ptr_glNormal3h,"glNormal3h",glNormal3h,GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glNormal3hv,ptr_glNormal3hv,"glNormal3hv",glNormal3hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glColor3h,ptr_glColor3h,"glColor3h",glColor3h,GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glColor3hv,ptr_glColor3hv,"glColor3hv",glColor3hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glColor4h,ptr_glColor4h,"glColor4h",glColor4h,GLhalf -> GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glColor4hv,ptr_glColor4hv,"glColor4hv",glColor4hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord1h,ptr_glTexCoord1h,"glTexCoord1h",glTexCoord1h,GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord1hv,ptr_glTexCoord1hv,"glTexCoord1hv",glTexCoord1hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord2h,ptr_glTexCoord2h,"glTexCoord2h",glTexCoord2h,GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord2hv,ptr_glTexCoord2hv,"glTexCoord2hv",glTexCoord2hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord3h,ptr_glTexCoord3h,"glTexCoord3h",glTexCoord3h,GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord3hv,ptr_glTexCoord3hv,"glTexCoord3hv",glTexCoord3hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord4h,ptr_glTexCoord4h,"glTexCoord4h",glTexCoord4h,GLhalf -> GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glTexCoord4hv,ptr_glTexCoord4hv,"glTexCoord4hv",glTexCoord4hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord1h,ptr_glMultiTexCoord1h,"glMultiTexCoord1h",glMultiTexCoord1h,GLenum -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord1hv,ptr_glMultiTexCoord1hv,"glMultiTexCoord1hv",glMultiTexCoord1hv,GLenum -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord2h,ptr_glMultiTexCoord2h,"glMultiTexCoord2h",glMultiTexCoord2h,GLenum -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord2hv,ptr_glMultiTexCoord2hv,"glMultiTexCoord2hv",glMultiTexCoord2hv,GLenum -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord3h,ptr_glMultiTexCoord3h,"glMultiTexCoord3h",glMultiTexCoord3h,GLenum -> GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord3hv,ptr_glMultiTexCoord3hv,"glMultiTexCoord3hv",glMultiTexCoord3hv,GLenum -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord4h,ptr_glMultiTexCoord4h,"glMultiTexCoord4h",glMultiTexCoord4h,GLenum -> GLhalf -> GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoord4hv,ptr_glMultiTexCoord4hv,"glMultiTexCoord4hv",glMultiTexCoord4hv,GLenum -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glFogCoordh,ptr_glFogCoordh,"glFogCoordh",glFogCoordh,GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glFogCoordhv,ptr_glFogCoordhv,"glFogCoordhv",glFogCoordhv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glSecondaryColor3h,ptr_glSecondaryColor3h,"glSecondaryColor3h",glSecondaryColor3h,GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glSecondaryColor3hv,ptr_glSecondaryColor3hv,"glSecondaryColor3hv",glSecondaryColor3hv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexWeighth,ptr_glVertexWeighth,"glVertexWeighth",glVertexWeighth,GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexWeighthv,ptr_glVertexWeighthv,"glVertexWeighthv",glVertexWeighthv,Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib1h,ptr_glVertexAttrib1h,"glVertexAttrib1h",glVertexAttrib1h,GLuint -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib1hv,ptr_glVertexAttrib1hv,"glVertexAttrib1hv",glVertexAttrib1hv,GLuint -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib2h,ptr_glVertexAttrib2h,"glVertexAttrib2h",glVertexAttrib2h,GLuint -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib2hv,ptr_glVertexAttrib2hv,"glVertexAttrib2hv",glVertexAttrib2hv,GLuint -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib3h,ptr_glVertexAttrib3h,"glVertexAttrib3h",glVertexAttrib3h,GLuint -> GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib3hv,ptr_glVertexAttrib3hv,"glVertexAttrib3hv",glVertexAttrib3hv,GLuint -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib4h,ptr_glVertexAttrib4h,"glVertexAttrib4h",glVertexAttrib4h,GLuint -> GLhalf -> GLhalf -> GLhalf -> GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttrib4hv,ptr_glVertexAttrib4hv,"glVertexAttrib4hv",glVertexAttrib4hv,GLuint -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttribs1hv,ptr_glVertexAttribs1hv,"glVertexAttribs1hv",glVertexAttribs1hv,GLuint -> GLsizei -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttribs2hv,ptr_glVertexAttribs2hv,"glVertexAttribs2hv",glVertexAttribs2hv,GLuint -> GLsizei -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttribs3hv,ptr_glVertexAttribs3hv,"glVertexAttribs3hv",glVertexAttribs3hv,GLuint -> GLsizei -> Ptr GLhalf -> IO ()) EXTENSION_ENTRY(dyn_glVertexAttribs4hv,ptr_glVertexAttribs4hv,"glVertexAttribs4hv",glVertexAttribs4hv,GLuint -> GLsizei -> Ptr GLhalf -> IO ())
mfpi/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/NV/HalfFloat.hs
bsd-3-clause
7,369
1
13
636
1,814
1,031
783
-1
-1
module Main where import Control.Applicative import Control.Monad import System.Exit import System.IO import System.Environment import System.Console.GetOpt import Data.Maybe import Text.PrettyPrint.HughesPJ import Language.MIXAL.Parser import Language.MIXAL.PP (ppMIXALStmt) import MIX.Assembler import MIX.Assembler.PP import MIX.Assembler.IO data Flag = DoDebug | Output FilePath | PrettyPrint | Help deriving (Eq) flags :: [OptDescr Flag] flags = [ Option "d" ["debug"] (NoArg DoDebug) "Generate debugging information in the output binary" , Option "o" ["output"] (ReqArg Output "FILENAME") "Where to write the assembled binary" , Option "p" ["pretty-print"] (NoArg PrettyPrint) "Pretty-print the resulting program" , Option "h" ["help"] (NoArg Help) "This help output" ] formatMessage :: AsmError -> String formatMessage (UnresolvedLocalForward i Nothing) = "Unresolved forward reference for " ++ show i formatMessage (UnresolvedLocalForward i (Just s)) = "Unresolved forward reference for " ++ show i ++ "\n " ++ (render $ ppMIXALStmt s) formatMessage (UnresolvedSymbol sym (Just s)) = "Unresolved symbol " ++ show sym ++ "\n " ++ (render $ ppMIXALStmt s) formatMessage (UnresolvedSymbol sym Nothing) = "Unresolved symbol " ++ show sym formatMessage (AsmError s Nothing) = s formatMessage (AsmError s (Just stmt)) = s ++ "\nLast processed statement:\n " ++ (render $ ppMIXALStmt stmt) getOutputFile :: [Flag] -> Maybe FilePath getOutputFile fs = listToMaybe $ catMaybes $ outputFile <$> fs where outputFile (Output f) = Just f outputFile _ = Nothing usage :: IO () usage = do pName <- getProgName let header = "Usage: " ++ pName ++ " <path> [options]" putStr $ usageInfo header flags main :: IO () main = do (flgs, args, rest) <- getOpt Permute flags <$> getArgs when (Help `elem` flgs) $ do usage exitFailure when (not $ null rest) $ do mapM_ putStrLn rest usage exitFailure when (length args /= 1) $ do putStrLn "No input program specified" usage exitFailure let [fname] = args opts = Options { preserveDebugData = DoDebug `elem` flgs } s <- readFile fname let r = parseMIXAL fname s case r of Left e -> putStrLn $ "Error: " ++ show e Right is -> case assemble opts is of Left e -> do putStrLn "Error during assembly:" putStrLn $ formatMessage e Right res -> do putStrLn "Assembly successful." when (PrettyPrint `elem` flgs) $ putStrLn $ render $ ppProgram $ (program res) case getOutputFile flgs of Nothing -> putStrLn "Output not written." Just f -> do h <- openFile f WriteMode writeProgram h $ program res hClose h putStrLn $ "Output written to " ++ show f
jtdaugherty/mix-assembler
src/Main.hs
bsd-3-clause
3,116
0
21
951
907
449
458
86
4
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.UK.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Maybe import Data.Text (Text) import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData (..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Regex.Types import Duckling.Types twentyNinetyMap :: HashMap Text Integer twentyNinetyMap = HashMap.fromList [ ( "\x0434\x0432\x0430\x0434\x0446\x044f\x0442\x044c" , 20 ) , ( "\x0442\x0440\x0438\x0434\x0446\x044f\x0442\x044c" , 30 ) , ( "\x0441\x043e\x0440\x043e\x043a" , 40 ) , ( "\x043f\x2018\x044f\x0442\x0434\x0435\x0441\x044f\x0442" , 50 ) , ( "\x0448\x0456\x0441\x0442\x0434\x0435\x0441\x044f\x0442" , 60 ) , ( "\x0441\x0456\x043c\x0434\x0435\x0441\x044f\x0442" , 70 ) , ( "\x0434\x0435\x0432\x2018\x044f\x043d\x043e\x0441\x0442\x043e" , 90 ) , ( "\x0432\x0456\x0441\x0456\x043c\x0434\x0435\x0441\x044f\x0442" , 80 ) ] ruleInteger5 :: Rule ruleInteger5 = Rule { name = "integer (20..90)" , pattern = [ regex "(\x0434\x0432\x0430\x0434\x0446\x044f\x0442\x044c|\x0442\x0440\x0438\x0434\x0446\x044f\x0442\x044c|\x0441\x043e\x0440\x043e\x043a|\x043f\x2018\x044f\x0442\x0434\x0435\x0441\x044f\x0442|\x0448\x0456\x0441\x0442\x0434\x0435\x0441\x044f\x0442|\x0441\x0456\x043c\x0434\x0435\x0441\x044f\x0442|\x0432\x0456\x0441\x0456\x043c\x0434\x0435\x0441\x044f\x0442|\x0434\x0435\x0432\x2018\x044f\x043d\x043e\x0441\x0442\x043e)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) twentyNinetyMap >>= integer _ -> Nothing } ruleIntegerNumeric :: Rule ruleIntegerNumeric = Rule { name = "integer (numeric)" , pattern = [ regex "(\\d{1,18})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do v <- parseInt match integer $ toInteger v _ -> Nothing } ruleDecimalWithThousandsSeparator :: Rule ruleDecimalWithThousandsSeparator = Rule { name = "decimal with thousands separator" , pattern = [ regex "(\\d+(,\\d\\d\\d)+\\.\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDouble (Text.replace (Text.singleton ',') Text.empty match) >>= double _ -> Nothing } ruleDecimalNumeral :: Rule ruleDecimalNumeral = Rule { name = "decimal number" , pattern = [ regex "(\\d*\\.\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDecimal True match _ -> Nothing } ruleInteger3 :: Rule ruleInteger3 = Rule { name = "integer 2" , pattern = [ regex "(\x0434\x0432\x0430|\x0434\x0432\x0456|\x0434\x0432\x043e\x0454|\x043f\x0430\x0440\x0430|\x043f\x0430\x0440\x0443|\x043f\x0430\x0440\x043e\x0447\x043a\x0443|\x043f\x0430\x0440\x043e\x0447\x043a\x0430)" ] , prod = \_ -> integer 2 } hundredsMap :: HashMap Text Integer hundredsMap = HashMap.fromList [ ( "\x0441\x0442\x043e" , 100 ) , ( "\x0434\x0432\x0456\x0441\x0442\x0456" , 200 ) , ( "\x0442\x0440\x0438\x0441\x0442\x0430" , 300 ) , ( "\x0447\x043e\x0442\x0438\x0440\x0438\x0441\x0442\x0430" , 400 ) , ( "\x043f\x2018\x044f\x0442\x0441\x043e\x0442" , 500 ) , ( "\x0448\x0456\x0441\x0442\x0441\x043e\x0442" , 600 ) , ( "\x0441\x0456\x043c\x0441\x043e\x0442" , 700 ) , ( "\x0432\x0456\x0441\x0456\x043c\x0441\x043e\x0442" , 800 ) , ( "\x0434\x0435\x0432\x2018\x044f\x0442\x0441\x043e\x0442" , 900 ) ] ruleInteger6 :: Rule ruleInteger6 = Rule { name = "integer (100..900)" , pattern = [ regex "(\x0441\x0442\x043e|\x0434\x0432\x0456\x0441\x0442\x0456|\x0442\x0440\x0438\x0441\x0442\x0430|\x0447\x043e\x0442\x0438\x0440\x0438\x0441\x0442\x0430|\x043f\x2018\x044f\x0442\x0441\x043e\x0442|\x0448\x0456\x0441\x0442\x0441\x043e\x0442|\x0441\x0456\x043c\x0441\x043e\x0442|\x0432\x0456\x0441\x0456\x043c\x0441\x043e\x0442|\x0434\x0435\x0432\x2018\x044f\x0442\x0441\x043e\x0442)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) hundredsMap >>= integer _ -> Nothing } ruleNumeralsPrefixWithMinus :: Rule ruleNumeralsPrefixWithMinus = Rule { name = "numbers prefix with -, minus" , pattern = [ regex "-|\x043c\x0456\x043d\x0443\x0441\\s?" , dimension Numeral ] , prod = \tokens -> case tokens of (_:Token Numeral nd:_) -> double (TNumeral.value nd * (-1)) _ -> Nothing } ruleNumeralsSuffixesKMG :: Rule ruleNumeralsSuffixesKMG = Rule { name = "numbers suffixes (K, M, G)" , pattern = [ dimension Numeral , regex "((\x043a|\x043c|\x0433)|(\x041a|\x041c|\x0413))(?=[\\W\\$\x20ac]|$)" ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v}): Token RegexMatch (GroupMatch (match:_)): _) -> case Text.toLower match of "\x043a" -> double $ v * 1e3 "\x041a" -> double $ v * 1e3 "\x043c" -> double $ v * 1e6 "\x041c" -> double $ v * 1e6 "\x0433" -> double $ v * 1e9 "\x0413" -> double $ v * 1e9 _ -> Nothing _ -> Nothing } ruleInteger7 :: Rule ruleInteger7 = Rule { name = "integer 21..99" , pattern = [ oneOf [70, 20, 60, 50, 40, 90, 30, 80] , numberBetween 1 10 ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ v1 + v2 _ -> Nothing } ruleInteger8 :: Rule ruleInteger8 = Rule { name = "integer 101..999" , pattern = [ oneOf [300, 600, 500, 100, 800, 200, 900, 700, 400] , numberBetween 1 100 ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ v1 + v2 _ -> Nothing } ruleInteger :: Rule ruleInteger = Rule { name = "integer 0" , pattern = [ regex "(\x043d\x0443\x043b\x044c)" ] , prod = \_ -> integer 0 } threeNineteenMap :: HashMap Text Integer threeNineteenMap = HashMap.fromList [ ( "\x0442\x0440\x0438" , 3 ) , ( "\x0447\x043e\x0442\x0438\x0440\x0438" , 4 ) , ( "\x043f\x2018\x044f\x0442\x044c" , 5 ) , ( "\x0448\x0456\x0441\x0442\x044c" , 6 ) , ( "\x0441\x0456\x043c" , 7 ) , ( "\x0432\x0456\x0441\x0456\x043c" , 8 ) , ( "\x0434\x0435\x0432\x2018\x044f\x0442\x044c" , 9 ) , ( "\x0434\x0435\x0441\x044f\x0442\x044c" , 10 ) , ( "\x043e\x0434\x0438\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 11 ) , ( "\x0434\x0432\x0430\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 12 ) , ( "\x0442\x0440\x0438\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 13 ) , ( "\x0447\x043e\x0442\x0438\x0440\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 14 ) , ( "\x043f\x2018\x044f\x0442\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 15 ) , ( "\x0448\x0456\x0441\x0442\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 16 ) , ( "\x0441\x0456\x043c\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 17 ) , ( "\x0432\x0456\x0441\x0456\x043c\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 18 ) , ( "\x0434\x0435\x0432\x2018\x044f\x0442\x043d\x0430\x0434\x0446\x044f\x0442\x044c" , 19 ) ] ruleInteger4 :: Rule ruleInteger4 = Rule { name = "integer (3..19)" , pattern = [ regex "(\x0442\x0440\x0438|\x0447\x043e\x0442\x0438\x0440\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x0447\x043e\x0442\x0438\x0440\x0438|\x043f\x2018\x044f\x0442\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x043f\x2018\x044f\x0442\x044c|\x0448\x0456\x0441\x0442\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x0448\x0456\x0441\x0442\x044c|\x0441\x0456\x043c\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x0441\x0456\x043c|\x0432\x0456\x0441\x0456\x043c\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x0432\x0456\x0441\x0456\x043c|\x0434\x0435\x0432\x2018\x044f\x0442\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x0434\x0435\x0432\x2018\x044f\x0442\x044c|\x0434\x0435\x0441\x044f\x0442\x044c|\x043e\x0434\x0438\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x0434\x0432\x0430\x043d\x0430\x0434\x0446\x044f\x0442\x044c|\x0442\x0440\x0438\x043d\x0430\x0434\x0446\x044f\x0442\x044c)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) threeNineteenMap >>= integer _ -> Nothing } ruleInteger2 :: Rule ruleInteger2 = Rule { name = "integer 1" , pattern = [ regex "(\x043e\x0434\x0438\x043d|\x043e\x0434\x043d\x0430|\x043e\x0434\x043d\x0443|\x043e\x0434\x043d\x0435|\x043e\x0434\x043d\x043e\x0433\x043e)" ] , prod = \_ -> integer 1 } ruleNumeralDotNumeral :: Rule ruleNumeralDotNumeral = Rule { name = "number dot number" , pattern = [ dimension Numeral , regex "\x043a\x0440\x0430\x043f\x043a\x0430" , numberWith TNumeral.grain isNothing ] , prod = \tokens -> case tokens of (Token Numeral nd1:_:Token Numeral nd2:_) -> double $ TNumeral.value nd1 + decimalsToDouble (TNumeral.value nd2) _ -> Nothing } ruleIntegerWithThousandsSeparator :: Rule ruleIntegerWithThousandsSeparator = Rule { name = "integer with thousands separator ," , pattern = [ regex "(\\d{1,3}(,\\d\\d\\d){1,5})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)): _) -> let fmt = Text.replace (Text.singleton ',') Text.empty match in parseDouble fmt >>= double _ -> Nothing } rules :: [Rule] rules = [ ruleDecimalNumeral , ruleDecimalWithThousandsSeparator , ruleInteger , ruleInteger2 , ruleInteger3 , ruleInteger4 , ruleInteger5 , ruleInteger6 , ruleInteger7 , ruleInteger8 , ruleIntegerNumeric , ruleIntegerWithThousandsSeparator , ruleNumeralDotNumeral , ruleNumeralsPrefixWithMinus , ruleNumeralsSuffixesKMG ]
rfranek/duckling
Duckling/Numeral/UK/Rules.hs
bsd-3-clause
10,868
0
18
2,246
2,123
1,219
904
216
8
module ELc.ExecSpec where import Control.Monad.State import Language.ELc import Language.Lc import Language.Lc.Interpreter.Dynamic import ELc.Arbitrary () import Test.Hspec import Test.QuickCheck -------------------------------------------------------------- -- Exec -------------------------------------------------------------- run :: ELc -> Lc run elc = head . runAll $ [elc] runAll :: [ELc] -> [Lc] runAll allElcs = evalState (go allElcs) emptyExecEnv where go :: [ELc] -> ExecState [Lc] go [] = return [] go (elc:elcs) = do val <- dynamicInterpreter `exec` elc vals <- go elcs return $ val : vals runWithLets :: [Let] -> ELc -> Lc runWithLets lets elc = evalState (dynamicInterpreter `exec` elc) (ExecEnv lets) spec :: Spec spec = describe "exec" $ do it "always evaluates the value of a let" $ property prop_LetEvaluesToValue it "correctly evaluates some examples" $ mapM_ (\(elcs, ex) -> last (runAll elcs) `shouldBe` ex) [ ([ELc (LcVar "y")], LcVar "y") , ([ELcLet (Let "y" (LcVar "x")), ELc (LcVar "y")], LcVar "x") , ( [ ELcLet (Let "id" (LcAbs "x" (LcVar "x"))) , ELcLet (Let "foo" (LcApp (LcVar "id") (LcVar "a"))) , ELc (LcVar "foo") ] , LcVar "a" ) ] prop_LetEvaluesToValue :: Let -> Bool prop_LetEvaluesToValue let_@(Let _ value) = eval dynamicInterpreter value == run (ELcLet let_)
d-dorazio/lc
test/ELc/ExecSpec.hs
bsd-3-clause
1,399
0
19
293
516
273
243
33
2
{-# LANGUAGE FlexibleContexts #-} module ParserUtils where import Data.List import Data.Char import Control.Applicative ((<$>)) import Control.Monad import Text.Parsec.Char import Text.Parsec.Prim import Text.Parsec.Combinator number :: Stream s m Char => ParsecT s u m Int number = (liftM (foldl' (\z x -> 10 * z + ord x - ord '0') 0) $ many1 digit) <?> "number" identifier :: Stream s m Char => ParsecT s u m String identifier = (letter <|> char '_') >>= \c -> (c:) <$> many (alphaNum <|> char '_') unesc :: Char -> Char unesc 'n' = '\n' unesc 't' = '\t' unesc 'r' = '\r' unesc 'v' = '\v' unesc c = c escapedChar :: Stream s m Char => ParsecT s u m Char escapedChar = (liftM unesc $ char '\\' >> anyChar) <?> "escaped char" doubleQuoted :: Stream s m Char => ParsecT s u m String doubleQuoted = flip label "doublequoted literal" $ do _ <- char '\"' res <- many $ escapedChar <|> noneOf ['\n', '"'] _ <- char '\"' return res nonQuoted :: Stream s m Char => ParsecT s u m String nonQuoted = (many1 $ (escapedChar <|> noneOf ", \t\n{}()")) <?> "nonquoted literal"
ratatosk/traceblade
ParserUtils.hs
bsd-3-clause
1,084
0
15
217
443
227
216
29
1
{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving, OverloadedStrings, QuasiQuotes, BangPatterns, NoImplicitPrelude #-} module JS where -- General import BasePrelude -- Text import qualified Data.Text.All as T import Data.Text.All (Text) -- Interpolation import NeatInterpolation -- Local import Utils -- | Javascript code. newtype JS = JS {fromJS :: Text} deriving (Show, T.Buildable, Monoid) -- | A concatenation of all Javascript functions defined in this module. allJSFunctions :: JS allJSFunctions = JS . T.unlines . map fromJS $ [ -- Utilities replaceWithData, prependData, appendData, moveNodeUp, moveNodeDown, switchSection, switchSectionsEverywhere, fadeIn, fadeOutAndRemove, -- Misc createAjaxIndicator, autosizeTextarea, showFormError, -- Signup/login trySignup, tryLogin, logout, -- Other submitWords, createUsers, showRoundEditPopup, addPlayerSelf, removePlayerSelf, endPreregistration, generateGroups, beginNextPhase, finishCurrentPhase, setAbsent, setWinner, startRound, cancelCurrentRound, finishCurrentRound, changeCurrentRound, recalcTime, keepTimer, pauseTimer, makeAdmin ] -- | A class for things that can be converted to Javascript syntax. class ToJS a where toJS :: a -> JS instance ToJS Bool where toJS True = JS "true" toJS False = JS "false" instance ToJS JS where toJS = id instance ToJS Text where toJS = JS . escapeJSString instance ToJS Integer where toJS = JS . T.show instance ToJS Int where toJS = JS . T.show instance ToJS (Uid a) where toJS = toJS . uidToText -- | A helper class for calling Javascript functions. class JSParams a where jsParams :: a -> [JS] instance JSParams () where jsParams () = [] instance ToJS a => JSParams [a] where jsParams = map toJS instance (ToJS a,ToJS b) => JSParams (a,b) where jsParams (a,b) = [toJS a, toJS b] instance (ToJS a,ToJS b,ToJS c) => JSParams (a,b,c) where jsParams (a,b,c) = [toJS a, toJS b, toJS c] instance (ToJS a,ToJS b,ToJS c,ToJS d) => JSParams (a,b,c,d) where jsParams (a,b,c,d) = [toJS a, toJS b, toJS c, toJS d] instance (ToJS a,ToJS b,ToJS c,ToJS d,ToJS e) => JSParams (a,b,c,d,e) where jsParams (a,b,c,d,e) = [toJS a, toJS b, toJS c, toJS d, toJS e] instance (ToJS a,ToJS b,ToJS c,ToJS d,ToJS e,ToJS f) => JSParams (a,b,c,d,e,f) where jsParams (a,b,c,d,e,f) = [toJS a, toJS b, toJS c, toJS d, toJS e, toJS f] instance (ToJS a,ToJS b,ToJS c,ToJS d,ToJS e,ToJS f,ToJS g) => JSParams (a,b,c,d,e,f,g) where jsParams (a,b,c,d,e,f,g) = [toJS a, toJS b, toJS c, toJS d, toJS e, toJS f, toJS g] instance (ToJS a,ToJS b,ToJS c,ToJS d,ToJS e,ToJS f,ToJS g,ToJS h) => JSParams (a,b,c,d,e,f,g,h) where jsParams (a,b,c,d,e,f,g,h) = [toJS a, toJS b, toJS c, toJS d, toJS e, toJS f, toJS g, toJS h] instance (ToJS a,ToJS b,ToJS c,ToJS d,ToJS e,ToJS f,ToJS g,ToJS h,ToJS i) => JSParams (a,b,c,d,e,f,g,h,i) where jsParams (a,b,c,d,e,f,g,h,i) = [toJS a, toJS b, toJS c, toJS d, toJS e, toJS f, toJS g, toJS h, toJS i] {- | This hacky class lets you construct and use Javascript functions; you give 'makeJSFunction' function name, function parameters, and function body, and you get a polymorphic value of type @JSFunction a => a@, which you can use either as a complete function definition (if you set @a@ to be @JS@), or as a function that you can give some parameters and it would return a Javascript call: > plus = makeJSFunction "plus" ["a", "b"] "return a+b;" >>> plus :: JS JS "function plus(a,b) {\nreturn a+b;}\n" >>> plus (3, 5) :: JS JS "plus(3,5);" -} class JSFunction a where makeJSFunction :: Text -- ^ Name -> [Text] -- ^ Parameter names -> Text -- ^ Definition -> a -- This generates function definition instance JSFunction JS where makeJSFunction fName fParams fDef = JS $ T.format "function {}({}) {\n{}}\n" (fName, T.intercalate "," fParams, fDef) -- This generates a function that takes arguments and produces a Javascript -- function call instance JSParams a => JSFunction (a -> JS) where makeJSFunction fName _fParams _fDef = \args -> JS $ T.format "{}({});" (fName, T.intercalate "," (map fromJS (jsParams args))) -- This isn't a standalone function and so it doesn't have to be listed in -- 'allJSFunctions'. assign :: ToJS x => JS -> x -> JS assign v x = JS $ T.format "{} = {};" (v, toJS x) replaceWithData :: JSFunction a => a replaceWithData = makeJSFunction "replaceWithData" ["node"] [text| return function(data) {$(node).replaceWith(data);}; |] prependData :: JSFunction a => a prependData = makeJSFunction "prependData" ["node"] [text| return function(data) {$(node).prepend(data);}; |] appendData :: JSFunction a => a appendData = makeJSFunction "appendData" ["node"] [text| return function(data) {$(node).append(data);}; |] -- | Move node up (in a list of sibling nodes), ignoring anchor elements -- inserted by 'thisNode'. moveNodeUp :: JSFunction a => a moveNodeUp = makeJSFunction "moveNodeUp" ["node"] [text| var el = $(node); while (el.prev().is(".dummy")) el.prev().before(el); if (el.not(':first-child')) el.prev().before(el); |] -- | Move node down (in a list of sibling nodes), ignoring anchor elements -- inserted by 'thisNode'. moveNodeDown :: JSFunction a => a moveNodeDown = makeJSFunction "moveNodeDown" ["node"] [text| var el = $(node); while (el.next().is(".dummy")) el.next().after(el); if (el.not(':last-child')) el.next().after(el); |] -- | Given something that contains section divs (or spans), show one and -- hide the rest. The div/span with the given @class@ will be chosen. -- -- See Note [show-hide] switchSection :: JSFunction a => a switchSection = makeJSFunction "switchSection" ["node", "section"] [text| $(node).children(".section").removeClass("shown"); $(node).children(".section."+section).addClass("shown"); // See Note [autosize] autosize($('textarea')); autosize.update($('textarea')); |] -- | Switch sections /everywhere/ inside the container. -- -- See Note [show-hide] switchSectionsEverywhere :: JSFunction a => a switchSectionsEverywhere = makeJSFunction "switchSectionsEverywhere" ["node", "section"] [text| $(node).find(".section").removeClass("shown"); $(node).find(".section."+section).addClass("shown"); // See Note [autosize] autosize($('textarea')); autosize.update($('textarea')); |] -- | This function makes the node half-transparent and then animates it to -- full opaqueness. It's useful when e.g. something has been moved and you -- want to “flash” the item to draw user's attention to it. fadeIn :: JSFunction a => a fadeIn = makeJSFunction "fadeIn" ["node"] [text| $(node).fadeTo(0,0.2).fadeTo(600,1); |] -- | This function animates the node to half-transparency and then removes it -- completely. It's useful when you're removing something and you want to -- draw user's attention to the fact that it's being removed. -- -- The reason there isn't a simple @fadeOut@ utility function here is that -- removal has to be done by passing a callback to @fadeTo@. In jQuery you -- can't simply wait until the animation has stopped. fadeOutAndRemove :: JSFunction a => a fadeOutAndRemove = makeJSFunction "fadeOutAndRemove" ["node"] [text| $(node).fadeTo(400,0.2,function(){$(node).remove()}); |] createAjaxIndicator :: JSFunction a => a createAjaxIndicator = makeJSFunction "createAjaxIndicator" [] [text| $("body").prepend('<div id="ajax-indicator"></div>'); $(document).ajaxStart(function() { $("#ajax-indicator").show(); }); $(document).ajaxStop(function() { $("#ajax-indicator").hide(); }); $("#ajax-indicator").hide(); |] autosizeTextarea :: JSFunction a => a autosizeTextarea = makeJSFunction "autosizeTextarea" ["textareaNode"] [text| autosize(textareaNode); autosize.update(textareaNode); |] showFormError :: JSFunction a => a showFormError = makeJSFunction "showFormError" ["form", "field", "err"] [text| $(form).find(".label-err").remove(); label = $(form).find("[name="+field+"]").prev(); errSpan = $("<span>", { "class" : "float-right label-err", "text" : err })[0]; label.append(errSpan); |] trySignup :: JSFunction a => a trySignup = makeJSFunction "trySignup" ["form"] [text| $.post("/signup", $(form).serialize()) .done(function (data) { if (data[0]) { window.location.href = "/"; } else { showFormError(form, data[1], data[2]); } }); |] tryLogin :: JSFunction a => a tryLogin = makeJSFunction "tryLogin" ["form"] [text| $.post("/login", $(form).serialize()) .done(function (data) { if (data[0]) { window.location.href = "/"; } else { showFormError(form, data[1], data[2]); } }); |] logout :: JSFunction a => a logout = makeJSFunction "logout" [] [text| $.post("/logout") .done(function () { location.reload(); }); |] submitWords :: JSFunction a => a submitWords = makeJSFunction "submitWords" ["gameId", "form"] [text| $.post("/game/" + gameId + "/words/submit", $(form).serialize()) .done(function (data) { if (data[0]) location.reload(); else showFormError(form, data[1], data[2]); }); |] createUsers :: JSFunction a => a createUsers = makeJSFunction "submitWords" ["form"] [text| $.post("/create-users", $(form).serialize()) .done(function (data) { if (data[0]) location.reload(); else showFormError(form, data[1], data[2]); }); |] showRoundEditPopup :: JSFunction a => a showRoundEditPopup = makeJSFunction "showRoundEditPopup" ["gameId", "phaseNum", "roomNum", "namerId", "guesserId", "score", "namerPenalty", "guesserPenalty", "discards"] [text| dialog = $("<div>", { "class" : "round-edit-popup" })[0]; form = $("<form>")[0]; $(form).submit(function(event) { event.preventDefault(); $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/round/" + namerId + "/" + guesserId + "/set", $(form).serialize()) .done(function() { location.reload(); }); }); labelScore = $("<label>", { "for" : "score", "text" : "Words" })[0]; inputScore = $("<input>", { "name" : "score", "type" : "number", "min" : "0", "value" : score })[0]; penalties = $("<div>", { "name" : "penalties" })[0]; penalty1 = $("<div>")[0]; labelDiscards = $("<label>", { "for" : "discards", "text" : "Discards" })[0]; inputDiscards = $("<input>", { "name" : "discards", "type" : "number", "min" : "0", "value" : discards })[0]; $(penalty1).append(labelDiscards, inputDiscards); penalty2 = $("<div>")[0]; labelNamerPenalty = $("<label>", { "for" : "namer-penalty", "text" : "Namer penalty" })[0]; inputNamerPenalty = $("<input>", { "name" : "namer-penalty", "type" : "number", "min" : "0", "value" : namerPenalty })[0]; $(penalty2).append(labelNamerPenalty, inputNamerPenalty); penalty3 = $("<div>")[0]; labelGuesserPenalty = $("<label>", { "for" : "guesser-penalty", "text" : "Guesser penalty" })[0]; inputGuesserPenalty = $("<input>", { "name" : "guesser-penalty", "type" : "number", "min" : "0", "value" : guesserPenalty })[0]; $(penalty3).append(labelGuesserPenalty, inputGuesserPenalty); $(penalties).append(penalty1, penalty2, penalty3); saveButton = $("<button>", { "type" : "submit", "text" : "Save" })[0]; clearButton = $("<button>", { "type" : "button", "name" : "clear", "text" : "Clear round" })[0]; $(clearButton).click(function() { $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/round/" + namerId + "/" + guesserId + "/clear") .done(function() { location.reload(); }); }); cancelButton = $("<button>", { "type" : "button", "name" : "cancel", "class" : "button-outline", "text" : "Cancel" })[0]; $(cancelButton).click(function() { $.magnificPopup.close(); }); $([inputScore, inputDiscards, inputNamerPenalty, inputGuesserPenalty]) .focus(function() {this.select();}); $(form).append(labelScore, inputScore, penalties, saveButton, clearButton, cancelButton); $(dialog).append(form); $.magnificPopup.open({ modal: true, focus: "[name=score]", items: { src: dialog, type: 'inline' } }); |] makeAdmin :: JSFunction a => a makeAdmin = makeJSFunction "makeAdmin" ["nick"] [text| $.post("/user/" + nick + "/make-admin") .done(function () { location.reload(); }); |] addPlayerSelf :: JSFunction a => a addPlayerSelf = makeJSFunction "addPlayerSelf" ["errorNode", "gameId"] [text| $.post("/game/" + gameId + "/players/add-self") .done(function (data) { if (data[0]) { $(errorNode).hide(); location.reload(); } else { $(errorNode).text(data[1]); $(errorNode).show(); } }); |] removePlayerSelf :: JSFunction a => a removePlayerSelf = makeJSFunction "removePlayerSelf" ["errorNode", "gameId"] [text| $.post("/game/" + gameId + "/players/remove-self") .done(function (data) { if (data[0]) { $(errorNode).hide(); location.reload(); } else { $(errorNode).text(data[1]); $(errorNode).show(); } }); |] endPreregistration :: JSFunction a => a endPreregistration = makeJSFunction "endPreregistration" ["gameId"] [text| $.post("/game/" + gameId + "/begin") .done(function () { location.reload(); }); |] generateGroups :: JSFunction a => a generateGroups = makeJSFunction "generateGroups" ["gameId", "numInput"] [text| num = parseInt($(numInput)[0].value, 10); $.post("/game/" + gameId + "/generate-groups", {num: num}) .done(function () { location.reload(); }); |] beginNextPhase :: JSFunction a => a beginNextPhase = makeJSFunction "beginNextPhase" ["gameId", "timeInput", "winnersInput"] [text| time = parseInt($(timeInput)[0].value, 10); winners = $(winnersInput)[0].value; $.post("/game/" + gameId + "/begin-next-phase", {"time-per-round" : time, "winners-per-room" : winners}) .done(function () { location.reload(); }); |] finishCurrentPhase :: JSFunction a => a finishCurrentPhase = makeJSFunction "finishCurrentPhase" ["gameId"] [text| $.post("/game/" + gameId + "/finish-current-phase") .done(function () { location.reload(); }); |] setAbsent :: JSFunction a => a setAbsent = makeJSFunction "setAbsent" ["gameId", "phaseNum", "roomNum", "playerId", "val"] [text| $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/player/" + playerId + "/absent", {"val": val}) .done(function () { location.reload(); }); |] setWinner :: JSFunction a => a setWinner = makeJSFunction "setWinner" ["gameId", "phaseNum", "roomNum", "playerId", "val"] [text| $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/player/" + playerId + "/winner", {"val": val}) .done(function () { location.reload(); }); |] startRound :: JSFunction a => a startRound = makeJSFunction "startRound" ["gameId", "phaseNum", "roomNum"] [text| $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/start-round") .done(function () { location.reload(); }); |] cancelCurrentRound :: JSFunction a => a cancelCurrentRound = makeJSFunction "cancelCurrentRound" ["gameId", "phaseNum", "roomNum"] [text| $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/cancel-current-round") .done(function () { location.reload(); }); |] finishCurrentRound :: JSFunction a => a finishCurrentRound = makeJSFunction "finishCurrentRound" ["gameId", "phaseNum", "roomNum"] [text| $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/finish-current-round") .done(function () { location.reload(); }); |] changeCurrentRound :: JSFunction a => a changeCurrentRound = makeJSFunction "changeCurrentRound" ["gameId", "phaseNum", "roomNum", "numNode", "parameter", "delta"] [text| obj = { "score": 0, "discards": 0, "namer-penalty": 0, "guesser-penalty": 0 }; obj[parameter] = delta; $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/change-current-round", obj) .done(function () { prevNum = parseInt($(numNode).text(), 10); $(numNode).text(Math.max(0, prevNum + delta)); }); |] recalcTime :: JSFunction a => a recalcTime = makeJSFunction "recalcTime" ["maxRounds", "roundInput", "timeSpan"] [text| $(roundInput).bind('input', function() { maxTime = maxRounds*this.value + (maxRounds-1)*15; $(timeSpan).html(Math.floor(maxTime/60)); }); |] keepTimer :: JSFunction a => a keepTimer = makeJSFunction "keepTimer" ["timerNode", "time"] [text| m = Math.floor(time/60); s = time % 60; $(timerNode).text(m+":"+("00"+s).slice(-2)); setInterval(function() { if (s > 0 || m > 0) { s = s-1; if (s<0) {s = s+60; m = m-1;} } $(timerNode).text(m+":"+("00"+s).slice(-2)); }, 1000); |] pauseTimer :: JSFunction a => a pauseTimer = makeJSFunction "pauseTimer" ["gameId", "phaseNum", "roomNum", "pause"] [text| $.post("/game/" + gameId + "/" + phaseNum + "/" + roomNum + "/pause-timer", {pause: pause}) .done(function () { location.reload(); }); |] -- When adding a function, don't forget to add it to 'allJSFunctions'! escapeJSString :: Text -> Text escapeJSString s = T.toStrict $ T.bsingleton '"' <> quote s <> T.bsingleton '"' where quote q = case T.uncons t of Nothing -> T.toBuilder h Just (!c, t') -> T.toBuilder h <> escape c <> quote t' where (h, t) = T.break isEscape q -- 'isEscape' doesn't mention \n, \r and \t because they are handled by -- the “< '\x20'” case; yes, later 'escape' escapes them differently, -- but it's irrelevant isEscape c = c == '\"' || c == '\\' || c == '\x2028' || c == '\x2029' || c < '\x20' escape '\"' = "\\\"" escape '\\' = "\\\\" escape '\n' = "\\n" escape '\r' = "\\r" escape '\t' = "\\t" escape c | c < '\x20' || c == '\x2028' || c == '\x2029' = T.toBuilder $ "\\u" <> T.replicate (4 - T.length h) "0" <> h | otherwise = T.bsingleton c where h = T.pack (showHex (fromEnum c) "") newtype JQuerySelector = JQuerySelector Text deriving (ToJS, T.Buildable) selectId :: Text -> JQuerySelector selectId x = JQuerySelector $ T.format "#{}" [x] selectUid :: Uid Node -> JQuerySelector selectUid x = JQuerySelector $ T.format "#{}" [x] selectClass :: Text -> JQuerySelector selectClass x = JQuerySelector $ T.format ".{}" [x] selectParent :: JQuerySelector -> JQuerySelector selectParent x = JQuerySelector $ T.format ":has(> {})" [x] selectChildren :: JQuerySelector -> JQuerySelector -> JQuerySelector selectChildren a b = JQuerySelector $ T.format "{} > {}" (a, b)
neongreen/hat
src/JS.hs
bsd-3-clause
19,911
0
15
4,713
3,284
1,848
1,436
-1
-1
{-# language ScopedTypeVariables, DataKinds #-} module RawSqlTest where import Data.Coerce import qualified Data.Conduit as C import qualified Data.Conduit.List as CL import qualified Data.Text as T import Init import Database.Persist.SqlBackend import PersistTestPetType import PersistentTestModels specsWith :: Runner SqlBackend m => RunDb SqlBackend m -> Spec specsWith runDb = describe "rawSql" $ do it "2+2" $ runDb $ do ret <- rawSql "SELECT 2+2" [] liftIO $ ret @?= [Single (4::Int)] it "?-?" $ runDb $ do ret <- rawSql "SELECT ?-?" [PersistInt64 5, PersistInt64 3] liftIO $ ret @?= [Single (2::Int)] it "NULL" $ runDb $ do ret <- rawSql "SELECT NULL" [] liftIO $ ret @?= [Nothing :: Maybe (Single Int)] it "entity" $ runDb $ do Entity p1k p1 <- insertEntity $ Person "Mathias" 23 Nothing Entity p2k p2 <- insertEntity $ Person "Norbert" 44 Nothing Entity p3k _ <- insertEntity $ Person "Cassandra" 19 Nothing Entity _ _ <- insertEntity $ Person "Thiago" 19 Nothing Entity a1k a1 <- insertEntity $ Pet p1k "Rodolfo" Cat Entity a2k a2 <- insertEntity $ Pet p1k "Zeno" Cat Entity a3k a3 <- insertEntity $ Pet p2k "Lhama" Dog Entity _ _ <- insertEntity $ Pet p3k "Abacate" Cat escape <- getEscape person <- getTableName (error "rawSql Person" :: Person) name_ <- getFieldName PersonName pet <- getTableName (error "rawSql Pet" :: Pet) petName_ <- getFieldName PetName let query = T.concat [ "SELECT ??, ?? " , "FROM ", person , ", ", escape "Pet" , " WHERE ", person, ".", escape "age", " >= ? " , "AND ", escape "Pet", ".", escape "ownerId", " = " , person, ".", escape "id" , " ORDER BY ", person, ".", name_, ", ", pet, ".", petName_ ] ret <- rawSql query [PersistInt64 20] liftIO $ ret @?= [ (Entity p1k p1, Entity a1k a1) , (Entity p1k p1, Entity a2k a2) , (Entity p2k p2, Entity a3k a3) ] ret2 <- rawSql query [PersistInt64 20] liftIO $ ret2 @?= [ (Just (Entity p1k p1), Just (Entity a1k a1)) , (Just (Entity p1k p1), Just (Entity a2k a2)) , (Just (Entity p2k p2), Just (Entity a3k a3)) ] ret3 <- rawSql query [PersistInt64 20] liftIO $ ret3 @?= [ Just (Entity p1k p1, Entity a1k a1) , Just (Entity p1k p1, Entity a2k a2) , Just (Entity p2k p2, Entity a3k a3) ] it "order-proof" $ runDb $ do let p1 = Person "Zacarias" 93 Nothing p1k <- insert p1 escape <- getEscape let query = T.concat [ "SELECT ?? " , "FROM ", escape "Person" ] ret1 <- rawSql query [] ret2 <- rawSql query [] :: MonadIO m => SqlPersistT m [Entity (ReverseFieldOrder Person)] liftIO $ ret1 @?= [Entity p1k p1] liftIO $ ret2 @?= [Entity (RFOKey $ unPersonKey p1k) (RFO p1)] it "permits prefixes" $ runDb $ do let r1 = Relationship "Foo" Nothing r1k <- insert r1 let r2 = Relationship "Bar" (Just r1k) r2k <- insert r2 let r3 = Relationship "Lmao" (Just r1k) r3k <- insert r3 let r4 = Relationship "Boring" (Just r2k) r4k <- insert r4 escape <- getEscape let query = T.concat [ "SELECT ??, ?? " , "FROM ", escape "Relationship", " AS parent " , "LEFT OUTER JOIN ", escape "Relationship", " AS child " , "ON parent.id = child.parent" ] result :: [(EntityWithPrefix "parent" Relationship, Maybe (EntityWithPrefix "child" Relationship))] <- rawSql query [] liftIO $ coerce result `shouldMatchList` [ (Entity r1k r1, Just (Entity r2k r2)) , (Entity r1k r1, Just (Entity r3k r3)) , (Entity r2k r2, Just (Entity r4k r4)) , (Entity r3k r3, Nothing) , (Entity r4k r4, Nothing) ] it "OUTER JOIN" $ runDb $ do let insert' :: (PersistStore backend, PersistEntity val, PersistEntityBackend val ~ BaseBackend backend, MonadIO m) => val -> ReaderT backend m (Key val, val) insert' v = insert v >>= \k -> return (k, v) (p1k, p1) <- insert' $ Person "Mathias" 23 Nothing (p2k, p2) <- insert' $ Person "Norbert" 44 Nothing (a1k, a1) <- insert' $ Pet p1k "Rodolfo" Cat (a2k, a2) <- insert' $ Pet p1k "Zeno" Cat escape <- getEscape let query = T.concat [ "SELECT ??, ?? " , "FROM ", person , "LEFT OUTER JOIN ", pet , " ON ", person, ".", escape "id" , " = ", pet, ".", escape "ownerId" , " ORDER BY ", person, ".", escape "name" , ", ", pet, ".", escape "id" ] person = escape "Person" pet = escape "Pet" ret <- rawSql query [] liftIO $ ret @?= [ (Entity p1k p1, Just (Entity a1k a1)) , (Entity p1k p1, Just (Entity a2k a2)) , (Entity p2k p2, Nothing) ] it "handles lower casing" $ runDb $ do C.runConduitRes $ rawQuery "SELECT full_name from lower_case_table WHERE my_id=5" [] C..| CL.sinkNull C.runConduitRes $ rawQuery "SELECT something_else from ref_table WHERE id=4" [] C..| CL.sinkNull it "commit/rollback" $ do caseCommitRollback runDb runDb cleanDB it "queries with large number of results" $ runDb $ do -- max size of a GHC tuple is 62, but Eq instances currently only exist up to 15-tuples -- See https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3369 ret <- rawSql "SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?" $ map PersistInt64 [1..15] liftIO $ ret @?= [(Single (1::Int), Single (2::Int), Single (3::Int), Single (4::Int), Single (5::Int), Single (6::Int), Single (7::Int), Single (8::Int), Single (9::Int), Single (10::Int), Single (11::Int), Single (12::Int), Single (13::Int), Single (14::Int), Single (15::Int))] getEscape :: MonadReader SqlBackend m => m (Text -> Text) getEscape = getEscapeRawNameFunction caseCommitRollback :: Runner SqlBackend m => RunDb SqlBackend m -> Assertion caseCommitRollback runDb = runDb $ do let filt :: [Filter Person1] filt = [] let p = Person1 "foo" 0 insert_ p insert_ p insert_ p c1 <- count filt c1 @== 3 transactionSave c2 <- count filt c2 @== 3 insert_ p transactionUndo c3 <- count filt c3 @== 3 insert_ p transactionSave insert_ p insert_ p transactionUndo c4 <- count filt c4 @== 4
yesodweb/persistent
persistent-test/src/RawSqlTest.hs
mit
7,208
0
18
2,589
2,394
1,180
1,214
-1
-1
import System.Process import System.Environment import System.Exit import Control.Monad import System.Console.GetOpt import Data.Char import BrowserX.Webkit import BrowserX.Network import BrowserX.Options import BrowserX.Parser -- | 'main' runs the main program main :: IO () main = do argv <- getArgs (settings, params) <- parse argv when (optShowHelp settings) $ putStrLn (usageInfo "Usage: BrowserX [flags] [METHOD] URL [ITEM [ITEM]]" options) >> exitSuccess when (optShowVersion settings) $ putStrLn "BrowserX: version: 0.1" >> exitSuccess putStrLn $ show settings putStrLn $ show params url <- case params of [] -> return "http://google.com" (x:xs) -> return x when (optDebug settings) $ console settings url unless (optDebug settings) $ browser settings url console :: Options -> String -> IO () console settings url = do html <- fetchURL settings url out <- parseHTML html putStrLn out
igniting/browser-x
BrowserX.hs
gpl-3.0
931
0
12
165
301
144
157
28
2
{-# 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.EC2.DescribeNetworkInterfaces -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Describes one or more of your network interfaces. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkInterfaces.html AWS API Reference> for DescribeNetworkInterfaces. module Network.AWS.EC2.DescribeNetworkInterfaces ( -- * Creating a Request describeNetworkInterfaces , DescribeNetworkInterfaces -- * Request Lenses , dnisNetworkInterfaceIds , dnisFilters , dnisDryRun -- * Destructuring the Response , describeNetworkInterfacesResponse , DescribeNetworkInterfacesResponse -- * Response Lenses , dnirsNetworkInterfaces , dnirsResponseStatus ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeNetworkInterfaces' smart constructor. data DescribeNetworkInterfaces = DescribeNetworkInterfaces' { _dnisNetworkInterfaceIds :: !(Maybe [Text]) , _dnisFilters :: !(Maybe [Filter]) , _dnisDryRun :: !(Maybe Bool) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeNetworkInterfaces' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dnisNetworkInterfaceIds' -- -- * 'dnisFilters' -- -- * 'dnisDryRun' describeNetworkInterfaces :: DescribeNetworkInterfaces describeNetworkInterfaces = DescribeNetworkInterfaces' { _dnisNetworkInterfaceIds = Nothing , _dnisFilters = Nothing , _dnisDryRun = Nothing } -- | One or more network interface IDs. -- -- Default: Describes all your network interfaces. dnisNetworkInterfaceIds :: Lens' DescribeNetworkInterfaces [Text] dnisNetworkInterfaceIds = lens _dnisNetworkInterfaceIds (\ s a -> s{_dnisNetworkInterfaceIds = a}) . _Default . _Coerce; -- | One or more filters. -- -- - 'addresses.private-ip-address' - The private IP addresses associated -- with the network interface. -- -- - 'addresses.primary' - Whether the private IP address is the primary -- IP address associated with the network interface. -- -- - 'addresses.association.public-ip' - The association ID returned when -- the network interface was associated with the Elastic IP address. -- -- - 'addresses.association.owner-id' - The owner ID of the addresses -- associated with the network interface. -- -- - 'association.association-id' - The association ID returned when the -- network interface was associated with an IP address. -- -- - 'association.allocation-id' - The allocation ID returned when you -- allocated the Elastic IP address for your network interface. -- -- - 'association.ip-owner-id' - The owner of the Elastic IP address -- associated with the network interface. -- -- - 'association.public-ip' - The address of the Elastic IP address -- bound to the network interface. -- -- - 'association.public-dns-name' - The public DNS name for the network -- interface. -- -- - 'attachment.attachment-id' - The ID of the interface attachment. -- -- - 'attachment.instance-id' - The ID of the instance to which the -- network interface is attached. -- -- - 'attachment.instance-owner-id' - The owner ID of the instance to -- which the network interface is attached. -- -- - 'attachment.device-index' - The device index to which the network -- interface is attached. -- -- - 'attachment.status' - The status of the attachment ('attaching' | -- 'attached' | 'detaching' | 'detached'). -- -- - 'attachment.attach.time' - The time that the network interface was -- attached to an instance. -- -- - 'attachment.delete-on-termination' - Indicates whether the -- attachment is deleted when an instance is terminated. -- -- - 'availability-zone' - The Availability Zone of the network -- interface. -- -- - 'description' - The description of the network interface. -- -- - 'group-id' - The ID of a security group associated with the network -- interface. -- -- - 'group-name' - The name of a security group associated with the -- network interface. -- -- - 'mac-address' - The MAC address of the network interface. -- -- - 'network-interface-id' - The ID of the network interface. -- -- - 'owner-id' - The AWS account ID of the network interface owner. -- -- - 'private-ip-address' - The private IP address or addresses of the -- network interface. -- -- - 'private-dns-name' - The private DNS name of the network interface. -- -- - 'requester-id' - The ID of the entity that launched the instance on -- your behalf (for example, AWS Management Console, Auto Scaling, and -- so on). -- -- - 'requester-managed' - Indicates whether the network interface is -- being managed by an AWS service (for example, AWS Management -- Console, Auto Scaling, and so on). -- -- - 'source-desk-check' - Indicates whether the network interface -- performs source\/destination checking. A value of 'true' means -- checking is enabled, and 'false' means checking is disabled. The -- value must be 'false' for the network interface to perform Network -- Address Translation (NAT) in your VPC. -- -- - 'status' - The status of the network interface. If the network -- interface is not attached to an instance, the status is 'available'; -- if a network interface is attached to an instance the status is -- 'in-use'. -- -- - 'subnet-id' - The ID of the subnet for the network interface. -- -- - 'tag':/key/=/value/ - The key\/value combination of a tag assigned -- to the resource. -- -- - 'tag-key' - The key of a tag assigned to the resource. This filter -- is independent of the 'tag-value' filter. For example, if you use -- both the filter \"tag-key=Purpose\" and the filter \"tag-value=X\", -- you get any resources assigned both the tag key Purpose (regardless -- of what the tag\'s value is), and the tag value X (regardless of -- what the tag\'s key is). If you want to list only resources where -- Purpose is X, see the 'tag':/key/=/value/ filter. -- -- - 'tag-value' - The value of a tag assigned to the resource. This -- filter is independent of the 'tag-key' filter. -- -- - 'vpc-id' - The ID of the VPC for the network interface. -- dnisFilters :: Lens' DescribeNetworkInterfaces [Filter] dnisFilters = lens _dnisFilters (\ s a -> s{_dnisFilters = a}) . _Default . _Coerce; -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have -- the required permissions, the error response is 'DryRunOperation'. -- Otherwise, it is 'UnauthorizedOperation'. dnisDryRun :: Lens' DescribeNetworkInterfaces (Maybe Bool) dnisDryRun = lens _dnisDryRun (\ s a -> s{_dnisDryRun = a}); instance AWSRequest DescribeNetworkInterfaces where type Rs DescribeNetworkInterfaces = DescribeNetworkInterfacesResponse request = postQuery eC2 response = receiveXML (\ s h x -> DescribeNetworkInterfacesResponse' <$> (x .@? "networkInterfaceSet" .!@ mempty >>= may (parseXMLList "item")) <*> (pure (fromEnum s))) instance ToHeaders DescribeNetworkInterfaces where toHeaders = const mempty instance ToPath DescribeNetworkInterfaces where toPath = const "/" instance ToQuery DescribeNetworkInterfaces where toQuery DescribeNetworkInterfaces'{..} = mconcat ["Action" =: ("DescribeNetworkInterfaces" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), toQuery (toQueryList "NetworkInterfaceId" <$> _dnisNetworkInterfaceIds), toQuery (toQueryList "Filter" <$> _dnisFilters), "DryRun" =: _dnisDryRun] -- | /See:/ 'describeNetworkInterfacesResponse' smart constructor. data DescribeNetworkInterfacesResponse = DescribeNetworkInterfacesResponse' { _dnirsNetworkInterfaces :: !(Maybe [NetworkInterface]) , _dnirsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeNetworkInterfacesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dnirsNetworkInterfaces' -- -- * 'dnirsResponseStatus' describeNetworkInterfacesResponse :: Int -- ^ 'dnirsResponseStatus' -> DescribeNetworkInterfacesResponse describeNetworkInterfacesResponse pResponseStatus_ = DescribeNetworkInterfacesResponse' { _dnirsNetworkInterfaces = Nothing , _dnirsResponseStatus = pResponseStatus_ } -- | Information about one or more network interfaces. dnirsNetworkInterfaces :: Lens' DescribeNetworkInterfacesResponse [NetworkInterface] dnirsNetworkInterfaces = lens _dnirsNetworkInterfaces (\ s a -> s{_dnirsNetworkInterfaces = a}) . _Default . _Coerce; -- | The response status code. dnirsResponseStatus :: Lens' DescribeNetworkInterfacesResponse Int dnirsResponseStatus = lens _dnirsResponseStatus (\ s a -> s{_dnirsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DescribeNetworkInterfaces.hs
mpl-2.0
10,028
0
15
2,064
876
562
314
93
1
{-# LANGUAGE ScopedTypeVariables, TupleSections, TemplateHaskell #-} {-| This module defines the routines necessary to inline member annotation declarations for the purpose of constructing an initial environment. Inlining proceeds by extracting the annotations from the AST and representing them in a form more amenable to duplicate detection. This form is essentially a dictionary of dictionary pairs. The outermost layer maps identifiers to the annotations bound under them. Each annotation is represented as a pair of dictionaries which map identifiers to the binding lifted attributes and attributes, respectively. In this form, annotations also track the member annotation declarations they contain as well as a set of them which has been processed; this helps to resolve cyclic dependencies and reduces duplicate work. -} module Language.K3.TypeSystem.TypeDecision.AnnotationInlining ( AnnMemRepr(..) , TypeParameterContext , TypeParameterContextEntry , FlatAnnotation , FlatAnnotationDecls , inlineAnnotations ) where import Control.Applicative import Control.Arrow import Control.Monad import Data.List import qualified Data.Map as Map import Data.Map (Map) import Data.Maybe import Data.Monoid import qualified Data.Set as Set import Data.Set (Set) import qualified Data.Traversable as Trav import Data.Tree import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Declaration import Language.K3.Core.Type import Language.K3.Utils.Pretty import Language.K3.TypeSystem.Data import Language.K3.TypeSystem.Error import Language.K3.TypeSystem.Monad.Iface.FreshVar import Language.K3.TypeSystem.Monad.Iface.TypeError import Language.K3.TypeSystem.Utils import Language.K3.TypeSystem.Utils.K3Tree import Language.K3.Utils.Logger $(loggingFunctions) -- |An internal repersentation of an annotation member. This representation -- carries additional metadata which applies to the member in particular; this -- allows inlining to occur without confusing the context in which the member -- was declared. In particular, @typeParamCxt@ describes the context of -- declared type parameters on this annotation member and @reprNative@ -- indicates whether or not the member is "native" (e.g. was not inlined from -- another source). data AnnMemRepr = AnnMemRepr { reprMem :: AnnMemDecl , typeParamCxt :: TypeParameterContext , reprNative :: Bool } deriving (Show) -- |A type alias for type parameter contexts. Each entry maps the name of a -- declared type parameter to a pair of type variables chosen for it as well as -- an upper bounding type expression when one was provided. type TypeParameterContext = Map Identifier TypeParameterContextEntry type TypeParameterContextEntry = (UVar,QVar,Maybe (K3 Type)) -- |The internal representation of annotations during and after inlining. The -- type parameter map relates declared type variable identifiers to the type -- variables which represent them. This map only includes type variables from -- the current annotation and not those from included annotations (via the -- "requires annotation" or "provides annotation" syntax) since it is only -- necessary to test the new parametricity. data AnnRepr = AnnRepr { liftedAttMap :: Map Identifier AnnMemRepr , schemaAttMap :: Map Identifier AnnMemRepr , memberAnnDecls :: Set (Identifier, TPolarity) , processedMemberAnnDecls :: Set (Identifier, TPolarity) } instance Pretty AnnRepr where prettyLines (AnnRepr lam sam mad umad) = ["〈 "] %+ prettyAttMap lam %$ [", "] %+ prettyAttMap sam %$ [", "] %+ intersperseBoxes [", "] (map (prettyTriple . rearrange) $ Set.toList $ mad Set.\\ umad) +% [" 〉"] where prettyAttMap m = intersperseBoxes [", "] $ map prettyEntry $ Map.toList m rearrange (i,pol) = (pol,i,Nothing) prettyEntry (_,memRepr) = prettyMem $ reprMem memRepr prettyMem mem = prettyTriple $ case mem of Lifted pol i _ _ anns -> (typeOfPol pol,i,uidFromAnns anns) Attribute pol i _ _ anns -> (typeOfPol pol,i,uidFromAnns anns) MAnnotation pol i anns -> (typeOfPol pol,i,uidFromAnns anns) prettyTriple (pol,i,mu) = [i ++ pStr pol ++ ": UID#" ++ maybe "?" (\(UID u) -> show u) mu] pStr pol = case pol of { Positive -> "+"; Negative -> "-" } uidFromAnns anns = maybe Nothing extractUID $ find isDUID anns extractUID (DUID u) = Just u extractUID _ = Nothing -- |A data type which tracks information about an @AnnRepr@ in addition to the -- @AnnRepr@ itself. type TaggedAnnRepr = (AnnRepr, UID, K3 Declaration) -- |A type alias describing the representation of annotations internal to the -- type decision procedure. The first list of annotations describes the -- lifted attributes; the second list describes the schema attributes. type FlatAnnotation = (TypeParameterContext, [AnnMemRepr], [AnnMemRepr]) -- |A type alias describing the representation of a group of declared -- annotations internal to the type decision procedure. The declaration -- included here is solely for error reporting purposes; it indicates the -- original declaration (pre-inlining) from which the @FlatAnnotation@ was -- derived. type FlatAnnotationDecls = Map Identifier (FlatAnnotation, K3 Declaration) emptyRepr :: AnnRepr emptyRepr = AnnRepr Map.empty Map.empty Set.empty Set.empty appendRepr :: forall m. (TypeErrorI m, Monad m) => AnnRepr -> AnnRepr -> m AnnRepr appendRepr (AnnRepr lam sam mad umad) (AnnRepr lam' sam' mad' umad') = do overlapCheck lam lam' overlapCheck sam sam' return $ AnnRepr (lam `mappend` lam') (sam `mappend` sam') (mad `mappend` mad') (umad `mappend` umad') where overlapCheck :: Map Identifier AnnMemRepr -> Map Identifier AnnMemRepr -> m () overlapCheck m1 m2 = let ks = Set.toList $ Set.fromList (Map.keys m1) `Set.intersection` Set.fromList (Map.keys m2) in unless (null ks) $ let i = head ks in typeError $ MultipleAnnotationBindings i [ reprMem $ m1 Map.! i , reprMem $ m2 Map.! i] concatReprs :: forall m. (TypeErrorI m, Monad m) => [AnnRepr] -> m AnnRepr concatReprs = foldM appendRepr emptyRepr -- |Converts a single annotation into internal representation. convertAnnotationToRepr :: forall m. (TypeErrorI m, Monad m) => TypeParameterContext -> [AnnMemDecl] -> m AnnRepr convertAnnotationToRepr typeParams mems = concatReprs =<< mapM convertMemToRepr mems where convertMemToRepr :: AnnMemDecl -> m AnnRepr convertMemToRepr mem = let repr = AnnMemRepr mem typeParams True in case mem of Lifted _ i _ _ _ -> return $ AnnRepr (Map.singleton i repr) Map.empty Set.empty Set.empty Attribute _ i _ _ _ -> return $ AnnRepr Map.empty (Map.singleton i repr) Set.empty Set.empty MAnnotation pol i _ -> let s = Set.singleton (i,typeOfPol pol) in return $ AnnRepr Map.empty Map.empty s Set.empty -- |Given a role AST, converts all annotations contained within to the internal -- form. convertAstToRepr :: forall m. ( TypeErrorI m, FreshVarI m, Monad m , Applicative m, Functor m) => K3 Declaration -> m ( Map Identifier TypeParameterContext , Map Identifier TaggedAnnRepr) convertAstToRepr ast = case tag ast of DRole _ -> do let decls = subForest ast m' <- Map.fromList <$> catMaybes <$> mapM declToRepr decls return (Map.map fst m', Map.map snd m') _ -> internalTypeError $ TopLevelDeclarationNonRole ast where declToRepr :: K3 Declaration -> m (Maybe (Identifier, (TypeParameterContext, TaggedAnnRepr))) declToRepr decl = case tag decl of DDataAnnotation i vdecls mems -> do u <- uidOf decl -- TODO: for parametricity, also include the bounding expression(s) -- in the type params map typeParams <- Map.fromList <$> mapM contextEntryForVDecl vdecls repr <- convertAnnotationToRepr typeParams mems _debug $ boxToString $ ["Annotation " ++ i ++ " representation: "] %$ indent 2 (prettyLines repr) return $ Just (i, (typeParams, (repr, u, decl))) _ -> return Nothing where contextEntryForVDecl :: TypeVarDecl -> m (Identifier, TypeParameterContextEntry) contextEntryForVDecl (TypeVarDecl i' mlbtExpr mubtExpr) = do u <- uidOf decl let origin = TVarAnnotationDeclaredParamOrigin u i' a <- freshUVar origin qa <- freshQVar origin when (isJust mlbtExpr) $ error "Type decision does not support declared lower bounds!" return (i',(a,qa,mubtExpr)) -- |Given a map of internal annotation representations, performs closure over -- their member annotation declarations until they have all been processed. -- Because closure may reveal overlapping bindings, this process may fail. -- If it does not, every member annotation will have been processed. closeReprs :: forall m. (TypeErrorI m, Monad m, Functor m, Applicative m) => Map Identifier TaggedAnnRepr -- ^The current representation of annotations -> m (Map Identifier TaggedAnnRepr) closeReprs dict = do -- FIXME: This isn't quite an accurate representation of the scenario. The -- annotations from the external environment (in theory obtained from -- other modules) do not appear here. They should be in the dictionary -- passed to updateRepr below. computed <- Trav.sequence $ Map.map (updateRepr dict) dict let result = Map.map fst computed let progress = any (snd . snd) (Map.toList computed) (if progress then closeReprs else return) result where updateRepr :: Map Identifier TaggedAnnRepr -> TaggedAnnRepr -> m (TaggedAnnRepr, Bool) updateRepr current (repr,s,decl) = let unproc = memberAnnDecls repr Set.\\ processedMemberAnnDecls repr in if Set.null unproc then return ((repr,s,decl), False) else do let (i,pol) = Set.findMin unproc (repr',_,_) <- maybe (typeError (UnboundTypeEnvironmentIdentifier s $ TEnvIdentifier i)) return $ Map.lookup i current let repr'' = case pol of Positive -> repr' Negative -> negatize repr' newRepr <- appendRepr repr $ foreignize repr'' let newRepr' = newRepr { processedMemberAnnDecls = Set.insert (i,pol) $ processedMemberAnnDecls newRepr } return ((newRepr',s,decl),True) foreignize :: AnnRepr -> AnnRepr foreignize (AnnRepr lam sam mad umad) = AnnRepr (Map.map f lam) (Map.map f sam) mad umad where f (AnnMemRepr mem tps _) = AnnMemRepr mem tps False negatize :: AnnRepr -> AnnRepr negatize (AnnRepr lam sam mad umad) = AnnRepr (negMap lam) (negMap sam) (negSet mad) (negSet umad) where negMap = Map.map negRepr negSet = Set.map (second $ const Negative) negRepr (AnnMemRepr mem tps ntv) = AnnMemRepr (negMem mem) tps ntv negMem mem = case mem of Lifted _ i tExpr _ anns -> Lifted Requires i tExpr Nothing anns Attribute _ i tExpr _ anns -> Attribute Requires i tExpr Nothing anns MAnnotation _ i anns -> MAnnotation Requires i anns -- |A routine which performs annotation inlining. The input arrives in the form -- of a top-level K3 AST. The result is a mapping from identifiers to -- annotation representations. Each representation is a pair of maps from -- identifiers to relevant member declarations; the first represents lifted -- attributes while the second represents schema attributes. inlineAnnotations :: ( FreshVarI m, TypeErrorI m, Monad m, Functor m , Applicative m) => K3 Declaration -> m FlatAnnotationDecls inlineAnnotations decl = do (cxtm, reprm) <- convertAstToRepr decl reprm' <- closeReprs reprm return $ Map.mapWithKey (f cxtm) reprm' where f cxtm i (repr,UID u,decl') = let ans = ( ( cxtm Map.! i , Map.elems $ liftedAttMap repr , Map.elems $ schemaAttMap repr) , decl') in _debugI ( boxToString $ ["Inlined form of UID " ++ show u ++ ":"] %$ indent 2 (prettyLines repr) ) ans
DaMSL/K3
src/Language/K3/TypeSystem/TypeDecision/AnnotationInlining.hs
apache-2.0
12,987
0
19
3,412
2,895
1,519
1,376
197
6
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UndecidableSuperClasses #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-} {-# OPTIONS_GHC -Wno-orphans #-} -- | This is an internal module. You are very discouraged from using it directly. module Tisch.Internal.Fun ( PgNum , PgIntegral , PgFractional , PgFloating , modulo , itruncate , iround , ifloor , iceil , euler's , matchBool , lnot , lor , lors , land , lands , PgEq , eq , member , PgOrd , lt , lte , gt , gte , PgBitwise , bwand , bwor , bwxor , bwnot , bwsl , bwsr , toTimestamptz , toTimestamp , tstzEpoch , tsCentury , tsDay , tsDayOfTheWeek , tsDayOfTheWeekISO8601 , tsDayOfTheYear , tsDecade , tsHour , tsMicroseconds , tsMillenium , tsMilliseconds , tsMinute , tsMonth , tsQuarter , tsSecond , tsWeekISO8601 , tsYear , tsYearISO8601 , unsafeFunExpr__date_part , nowTransaction , nowStatement , nowClock , reMatch , reSub , reReplace , reReplaceg , reSplit ) where import Control.Lens () import Data.Foldable import qualified Data.ByteString import qualified Data.CaseInsensitive import Data.Semigroup (Semigroup(..)) import qualified GHC.TypeLits as GHC import qualified Opaleye as O import qualified Opaleye.Internal.Column as OI import qualified Opaleye.Internal.HaskellDB.PrimQuery as HDB import Tisch.Internal.Kol (CastKol, Kol(..), PgTyped(..), ToKol(..), liftKol1, liftKol2, liftKol3, unsaferCastKol, unsaferCoerceKol, kolArray) import Tisch.Internal.Koln (Koln(..)) import Tisch.Internal.Compat (PGNumeric, AnyColumn(..), unsafeFunExpr) ------------------------------------------------------------------------------- -- Semigroups, Monoids instance Semigroup (Kol O.PGText) where (<>) = liftKol2 (OI.binOp (HDB.:||)) instance Monoid (Kol O.PGText) where mempty = kol "" mappend = (<>) --- instance Semigroup (Kol O.PGCitext) where (<>) ka kb = unsaferCoerceKol (mappend (unsaferCoerceKol ka :: Kol O.PGText) (unsaferCoerceKol kb :: Kol O.PGText)) instance Monoid (Kol O.PGCitext) where mempty = kol (Data.CaseInsensitive.mk "") mappend = (<>) --- instance Semigroup (Kol O.PGBytea) where (<>) = liftKol2 (OI.binOp (HDB.:||)) instance Monoid (Kol O.PGBytea) where mempty = kol Data.ByteString.empty mappend = (<>) --- instance PgTyped a => Semigroup (Kol (O.PGArray a)) where (<>) = liftKol2 (\x y -> unsafeFunExpr "array_cat" [AnyColumn x, AnyColumn y]) instance forall a. PgTyped a => Monoid (Kol (O.PGArray a)) where mempty = kolArray ([] :: [Kol a]) mappend = (<>) ------------------------------------------------------------------------------- -- 'Num' and related operations -- | A @'PgNum' a@ instance gives you a @'Num' ('Kol' a)@ instance for free. class (PgTyped a, OI.PGNum (PgType a)) => PgNum (a :: k) instance PgNum O.PGInt2 instance PgNum O.PGInt4 instance PgNum O.PGInt8 instance PgNum O.PGFloat4 instance PgNum O.PGFloat8 instance GHC.KnownNat s => PgNum (PGNumeric s) instance (PgNum a, Num (O.Column (PgType a))) => Num (Kol a) where fromInteger = Kol . fromInteger (*) = liftKol2 (*) (+) = liftKol2 (+) (-) = liftKol2 (-) abs = liftKol1 abs negate = liftKol1 negate signum = liftKol1 signum -- | Sql operator @%@ modulo :: PgNum a => Kol a -> Kol a -> Kol a modulo = liftKol2 (OI.binOp HDB.OpMod) ------------------------------------------------------------------------------- -- | A 'PgIntegral' is guaranteed to be an integral type. class PgTyped a => PgIntegral (a :: k) instance PgIntegral O.PGInt2 instance PgIntegral O.PGInt4 instance PgIntegral O.PGInt8 instance PgIntegral (PGNumeric 0) itruncate :: (PgFloating a, PgIntegral b) => Kol a -> Kol b itruncate = liftKol1 (unsafeFunExpr "trunc" . pure . AnyColumn) iround :: (PgFloating a, PgIntegral b) => Kol a -> Kol b iround = liftKol1 (unsafeFunExpr "round" . pure . AnyColumn) iceil :: (PgFloating a, PgIntegral b) => Kol a -> Kol b iceil = liftKol1 (unsafeFunExpr "ceil" . pure . AnyColumn) ifloor :: (PgFloating a, PgIntegral b) => Kol a -> Kol b ifloor = liftKol1 (unsafeFunExpr "floor" . pure . AnyColumn) ------------------------------------------------------------------------------- -- | A @'PgFractional' a@ instance gives you a @'Fractional' ('Kol' a)@ instance -- for free. class (PgTyped a, PgNum a, OI.PGFractional (PgType a)) => PgFractional (a :: k) instance PgFractional O.PGFloat4 instance PgFractional O.PGFloat8 instance GHC.KnownNat s => PgFractional (PGNumeric s) instance ( PgTyped a, PgFractional a , Fractional (O.Column (PgType a)) , Num (O.Column (PgType a)) ) => Fractional (Kol a) where fromRational = Kol . fromRational (/) = liftKol2 (/) ------------------------------------------------------------------------------- -- | A 'PgFloating' instance gives you 'Floating'-support. class (PgTyped a, PgFractional a) => PgFloating (a :: k) instance PgFloating O.PGFloat4 instance PgFloating O.PGFloat8 -- | @2.718281828459045@ euler's :: PgFloating a => Kol a euler's = unsaferCastKol (kol (2.718281828459045 :: Double) :: Kol O.PGFloat8) {-# INLINE euler's #-} instance ( PgTyped a , PgFloating a , Fractional (Kol a) , PgFloating (Kol a) ) => Floating (Kol a) where pi = Kol (unsafeFunExpr "pi" []) exp = liftKol1 (unsafeFunExpr "exp" . pure . AnyColumn) log = liftKol1 (unsafeFunExpr "log" . pure . AnyColumn) sqrt = liftKol1 (unsafeFunExpr "sqrt" . pure . AnyColumn) (**) = liftKol2 (\base ex -> unsafeFunExpr "power" [AnyColumn base, AnyColumn ex]) logBase = liftKol2 (\base n -> unsafeFunExpr "log" [AnyColumn base, AnyColumn n]) sin = liftKol1 (unsafeFunExpr "sin" . pure . AnyColumn) cos = liftKol1 (unsafeFunExpr "cos" . pure . AnyColumn) tan = liftKol1 (unsafeFunExpr "tan" . pure . AnyColumn) asin = liftKol1 (unsafeFunExpr "asin" . pure . AnyColumn) acos = liftKol1 (unsafeFunExpr "acos" . pure . AnyColumn) atan = liftKol1 (unsafeFunExpr "atan" . pure . AnyColumn) -- Not the most efficient implementations, but PostgreSQL doesn't provide -- builtin support for hyperbolic functions. We add these for completeness, -- so that we can implement the 'Floating' typeclass in full. sinh x = ((euler's ** x) - (euler's ** (negate x))) / fromInteger 2 cosh x = ((euler's ** x) + (euler's ** (negate x))) / fromInteger 2 tanh x = ((euler's ** x) - (euler's ** (negate x))) / ((euler's ** x) + (euler's ** (negate x))) asinh x = log (x + sqrt ((x ** fromInteger 2) + fromInteger 1)) acosh x = log (x + sqrt ((x ** fromInteger 2) - fromInteger 1)) atanh x = log ((fromInteger 1 + x) / (fromInteger 1 - x)) / fromInteger 2 ------------------------------------------------------------------------------- -- Booleans. -- | Like 'Prelude.bool', @'matchBool' f t x@ evaluates to @f@ if @x@ is false, -- otherwise it evaluates to @t@. matchBool :: PgTyped a => Kol a -> Kol a -> Kol O.PGBool -> Kol a matchBool = liftKol3 (\f' t' x' -> O.ifThenElse x' t' f') -- | Logical NOT. -- -- Note: This function can take any of 'Kol' and 'Koln' argument, with the -- return type being fully determined by it. The valid combinations are: -- -- @ -- 'lnot' :: 'Kol' 'O.PGBool' -> 'Kol' 'O.PGBool' -- 'lnot' :: 'Koln' 'O.PGBool' -> 'Koln' 'O.PGBool' -- @ lnot :: Kol O.PGBool -> Kol O.PGBool lnot = liftKol1 O.not -- | Logical OR. See 'eq' for possible argument types. lor :: Kol O.PGBool -> Kol O.PGBool -> Kol O.PGBool lor = liftKol2 (O..||) -- | Whether any of the given 'O.PGBool's is true. -- -- Notice that 'lor' is more general that 'lors', as it doesn't restrict @kol@. -- -- Mnemonic reminder: Logical ORs. lors :: Foldable f => f (Kol O.PGBool) -> Kol O.PGBool lors = foldl' lor (kol False) -- Logical AND. See 'eq' for possible argument types. land :: Kol O.PGBool -> Kol O.PGBool -> Kol O.PGBool land = liftKol2 (O..&&) -- | Whether all of the given 'O.PGBool's are true. -- -- Notice that 'land' is more general that 'lands', as it doesn't restrict -- @kol@. -- -- Mnemonic reminder: Logical ANDs. lands :: Foldable f => f (Kol O.PGBool) -> Kol O.PGBool lands = foldl' land (kol True) -------------------------------------------------------------------------------- -- Equality -- | A @'PgEq' a@ instance states that @a@ can be compared for equality. class PgTyped a => PgEq (a :: k) instance PgEq O.PGBool instance PgEq O.PGBytea instance PgEq O.PGCitext instance PgEq O.PGDate instance PgEq O.PGFloat4 instance PgEq O.PGFloat8 instance PgEq O.PGInt2 instance PgEq O.PGInt4 instance PgEq O.PGInt8 instance PgEq O.PGJsonb instance PgEq O.PGJson instance PgEq O.PGText instance PgEq O.PGTimestamptz instance PgEq O.PGTimestamp instance PgEq O.PGTime instance PgEq O.PGUuid instance PgEq (PGNumeric s) -- | Whether two column values are equal. -- -- Mnemonic reminder: EQual. eq :: PgEq a => Kol a -> Kol a -> Kol O.PGBool eq = liftKol2 (O..==) -- | Whether the given value is a member of the given collection. member :: (PgEq a, Foldable f) => Kol a -> f (Kol a) -> Kol O.PGBool member ka fkas = Kol (O.in_ (map unKol (toList fkas)) (unKol ka)) -------------------------------------------------------------------------------- -- Ordering -- | A 'PgOrd' instance says that @a@ has an ordering. See 'orderBy'. class (PgTyped a, O.PGOrd (PgType a)) => PgOrd (a :: k) instance (PgTyped a, O.PGOrd (PgType a)) => PgOrd a -- | Whether the first argument is less than the second. -- -- Mnemonic reminder: Less Than. lt :: PgOrd a => Kol a -> Kol a -> Kol O.PGBool lt = liftKol2 (O..<) -- | Whether the first argument is less than or equal to the second. -- -- Mnemonic reminder: Less Than or Equal. lte :: PgOrd a => Kol a -> Kol a -> Kol O.PGBool lte = liftKol2 (O..<=) -- | Whether the first argument is greater than the second. -- -- Mnemonic reminder: Greater Than. gt :: PgOrd a => Kol a -> Kol a -> Kol O.PGBool gt = liftKol2 (O..>) -- | Whether the first argument is greater than or equal to the second. -- -- Mnemonic reminder: Greater Than or Equal. gte :: PgOrd a => Kol a -> Kol a -> Kol O.PGBool gte = liftKol2 (O..>=) -------------------------------------------------------------------------------- -- Bitwise -- | Only 'PgBitwise' instance can be used with bitwise operators 'btwand', -- 'bword', 'bwxor', 'bwnot', 'bwsl' and 'bwsr'. class PgTyped a => PgBitwise (a :: k) instance PgBitwise O.PGInt2 instance PgBitwise O.PGInt4 instance PgBitwise O.PGInt8 -- instance PgBitwise O.PGBitstring ? -- | Bitwise AND. Sql operator: @&@ bwand :: PgBitwise a => Kol a -> Kol a -> Kol a bwand = liftKol2 (OI.binOp (HDB.:&)) -- | Bitwise OR. Sql operator: @|@ bwor :: PgBitwise a => Kol a -> Kol a -> Kol a bwor = liftKol2 (OI.binOp (HDB.:|)) -- | Bitwise XOR. Sql operator: @#@ bwxor :: PgBitwise a => Kol a -> Kol a -> Kol a bwxor = liftKol2 (OI.binOp (HDB.:^)) -- | Bitwise NOT. Sql operator: @~@ bwnot :: PgBitwise a => Kol a -> Kol a bwnot = liftKol1 (OI.unOp (HDB.UnOpOther "~")) -- | Bitwise shift left. Sql operator: @<<@ -- -- @'bwsl' a n@ shifts @a@ to the right @n@ positions. Translates to @a << n@ in -- the generated SQL. bwsl :: (PgBitwise a, PgIntegral b) => Kol a -> Kol b -> Kol a bwsl = liftKol2 (OI.binOp (HDB.OpOther ("<<"))) -- | Bitwise shift right. Sql operator: @>>@ -- -- @'bwsr' a n@ shifts @a@ to the right @n@ positions. Translates to @a >> n@ in -- the generated SQL. bwsr :: (PgBitwise a, PgIntegral b) => Kol a -> Kol b -> Kol a bwsr = liftKol2 (OI.binOp (HDB.OpOther (">>"))) -------------------------------------------------------------------------------- -- Time -- Convert a PostgreSQL @timestamptz@ to a @timestamp@ at a given timezone. -- -- Notice that a @timestamp@ value is usually meaningless unless you also know -- the timezone where that @timestamp@ happens. In other words, you should -- store the passed in @'Kol' zone@ somewhere. -- -- Warning: Dealing with @timestamp@ values in PostgreSQL is very error prone -- unless you really know what you are doing. Quite likely you shouldn't be -- using @timestamp@ values in PostgreSQL unless you are storing distant dates -- in the future for which the precise UTC time can't be known (e.g., can you -- tell the UTC time for January 1 4045, 00:00:00 in Peru? Me neither, as I -- have no idea in what timezone Peru will be in year 4045, so I can't convert -- that to UTC). -- -- Law 1: Provided the timezone database information stays the same, the -- following equality holds: -- -- @ -- 'toTimestamptz' zone . 'toTimestamp' zone === 'id' -- 'toTimestamp' zone . 'toTimestamptz' zone === 'id' -- @ toTimestamptz :: ( PgTyped zone, PgType zone ~ O.PGText , PgTyped a, PgType a ~ O.PGTimestamptz , PgTyped b, PgType b ~ O.PGTimestamp ) => Kol zone -> Kol a -> Kol b toTimestamptz = liftKol2 (\zone a -> unsafeFunExpr "timezone" [AnyColumn zone, AnyColumn a]) -- Convert a PostgreSQL @timestamp@ to a @timestamptz@, making the assumption -- that the given @timestamp@ happens at the given timezone. -- -- Law 1: Provided the timezone database information stays the same, the -- following equality holds: -- -- @ -- 'toTimestamptz' zone . 'toTimestamp' zone === 'id' -- 'toTimestamp' zone . 'toTimestamptz' zone === 'id' -- @ toTimestamp :: ( PgTyped zone, PgType zone ~ O.PGText , PgTyped a, PgType a ~ O.PGTimestamp , PgTyped b, PgType b ~ O.PGTimestamptz ) => Kol zone -> Kol a -> Kol b toTimestamp = liftKol2 (\zone a -> unsafeFunExpr "timezone" [AnyColumn zone, AnyColumn a]) unsafeFunExpr__date_part :: (PgTyped tsy, PgTyped b) => HDB.Name -> Kol tsy -> Kol b unsafeFunExpr__date_part n = unsaferCastKol @O.PGFloat8 . liftKol1 (\x -> unsafeFunExpr "date_part" [AnyColumn (O.pgString n), AnyColumn x]) tstzEpoch :: Kol O.PGTimestamptz -> Kol O.PGFloat8 tstzEpoch = unsafeFunExpr__date_part "epoch" tsCentury :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsCentury = unsafeFunExpr__date_part "century" tsDay :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsDay = unsafeFunExpr__date_part "day" tsDayOfTheWeek :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsDayOfTheWeek = unsafeFunExpr__date_part "dow" tsDayOfTheWeekISO8601 :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsDayOfTheWeekISO8601 = unsafeFunExpr__date_part "isodow" tsDayOfTheYear :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsDayOfTheYear = unsafeFunExpr__date_part "doy" tsDecade :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsDecade = unsafeFunExpr__date_part "decade" tsHour :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsHour = unsafeFunExpr__date_part "hour" tsMicroseconds :: (PgIntegral b, CastKol O.PGInt4 b) => Kol O.PGTimestamp -> Kol b tsMicroseconds = unsafeFunExpr__date_part "microseconds" tsMillenium :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsMillenium = unsafeFunExpr__date_part "millenium" tsMilliseconds :: (PgIntegral b, CastKol O.PGInt4 b) => Kol O.PGTimestamp -> Kol b tsMilliseconds = unsafeFunExpr__date_part "milliseconds" tsMinute :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsMinute = unsafeFunExpr__date_part "minute" tsMonth :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsMonth = unsafeFunExpr__date_part "month" tsQuarter :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsQuarter = unsafeFunExpr__date_part "quarter" tsSecond :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsSecond = unsafeFunExpr__date_part "second" tsWeekISO8601 :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsWeekISO8601 = unsafeFunExpr__date_part "week" tsYear :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsYear = unsafeFunExpr__date_part "year" tsYearISO8601 :: (PgIntegral b) => Kol O.PGTimestamp -> Kol b tsYearISO8601 = unsafeFunExpr__date_part "isoyear" -- | Time when the current transaction started. -- -- Sql function: @transaction_timestamp()@, @now()@. nowTransaction :: Kol O.PGTimestamptz nowTransaction = Kol (unsafeFunExpr "transaction_timestamp" []) -- | Time when the current statement started. -- -- SqlFunction: @statement_timestamp()@. nowStatement :: Kol O.PGTimestamptz nowStatement = Kol (unsafeFunExpr "statement_timestamp" []) -- | Current clock time. -- -- SqlFunction: @clock_timestamp()@. nowClock :: Kol O.PGTimestamptz nowClock = Kol (unsafeFunExpr "clock_timestamp" []) -------------------------------------------------------------------------------- -- Regular expressions -- | Whether the given regular expression matches the given text. -- -- Sql operator: @~@ reMatch :: (O.PGText ~ regex, O.PGText ~ source) => Kol regex -> Kol source -> Kol O.PGBool -- ^ Is there a match? reMatch = liftKol2 (flip (OI.binOp (HDB.OpOther "~"))) -- | Extract a substring matching the given regular expression. If there is no -- match, then @nul@ is returned. -- -- Sql function: @substring()@. reSub :: (O.PGText ~ regex, O.PGText ~ source) => Kol regex -- ^ Regular expression. If the pattern contains any parentheses, the portion -- of the text that matched the first parenthesized subexpression (the one -- whose left parenthesis comes first) is returned. See Section 9.1 of the -- PostgreSQL manual to understand the syntax. -> Kol source -> Koln O.PGText -- ^ Possibly matched substring. reSub (Kol re) (Kol a) = Koln (unsafeFunExpr "substring" [AnyColumn a, AnyColumn re]) -- | Replaces with @replacement@ in the given @source@ string the /first/ -- substring matching the regular expression @regex@. -- -- Sql function: @regexp_replace(_, _, _)@. reReplace :: (O.PGText ~ regex, O.PGText ~ source, O.PGText ~ replacement) => Kol regex -- ^ Regular expression. See Section 9.1 of the PostgreSQL manual to -- understand the syntax. -> Kol replacement -- ^ Replacement expression. See Section 9.1 of the PostgreSQL manual to -- understand the syntax. -> Kol source -> Kol O.PGText reReplace (Kol re) (Kol rep) (Kol s) = Kol $ unsafeFunExpr "regexp_replace" [AnyColumn s, AnyColumn re, AnyColumn rep] -- | Like 'reReplace', but replaces /all/ of the substrings matching the -- pattern, not just the first one. -- -- Sql function: @regexp_replace(_, _, _, 'g')@. reReplaceg :: (O.PGText ~ regex, O.PGText ~ source, O.PGText ~ replacement) => Kol regex -- ^ Regular expression. See Section 9.1 of the PostgreSQL manual to -- understand the syntax. -> Kol replacement -- ^ Replacement expression. See Section 9.1 of the PostgreSQL manual to -- understand the syntax. -> Kol source -> Kol O.PGText reReplaceg (Kol re) (Kol rep) (Kol s) = Kol $ unsafeFunExpr "regexp_replace" [AnyColumn s, AnyColumn re, AnyColumn rep, AnyColumn (O.pgString "g")] -- | Split the @source@ string using the given Regular Expression as a -- delimiter. -- -- If there is no match to the pattern, the function an array with just one -- element: the original string. If there is at least one match, -- for each match it returns the text from the end of the last match (or the -- beginning of the string) to the beginning of the match. When there are no -- more matches, it returns the text from the end of the last match to the end -- of the string. -- -- Sql function: @regexp_split_to_array(source, regexp)@. reSplit :: (O.PGText ~ regex, O.PGText ~ source) => Kol regex -- ^ Regular expression. See Section 9.1 of the PostgreSQL manual to -- understand the syntax. -> Kol source -> Kol (O.PGArray O.PGText) reSplit (Kol re) (Kol s) = Kol $ unsafeFunExpr "regexp_split_to_array" [AnyColumn s, AnyColumn re]
k0001/opaleye-sot
src/lib/Tisch/Internal/Fun.hs
bsd-3-clause
19,618
0
14
3,420
5,060
2,678
2,382
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Optical.Severable -- Copyright : (c) Christopher Chalmers -- License : BSD3 -- -- Maintainer : Christopher Chalmers -- Stability : provisional -- Portability : non-portable -- ----------------------------------------------------------------------------- module Optical.Severable where -- ( -- -- * Witherable -- Witherable(..) -- , ordNub -- , hashNub -- -- * Generalization -- , WitherLike, Wither, WitherLike', Wither' -- , witherOf -- , mapMaybeOf -- , catMaybesOf -- , filterAOf -- , filterOf -- , ordNubOf -- , hashNubOf -- -- * Cloning -- , cloneWither -- , Dungeon(..) -- -- * Witherable from Traversable -- , Chipped(..) -- ) where import Control.Comonad import Control.Lens.Internal import Data.Bifunctor import Data.Bool import Data.Profunctor.Rep import qualified Data.IntMap.Lazy as IM import qualified Data.Map.Lazy as M import Data.Profunctor.Sieve import qualified Data.Sequence as S import qualified Data.Vector as V import Control.Applicative import qualified Data.Foldable as F import Data.Functor.Identity import Control.Monad.Trans.State.Strict import Data.Orphans () import Data.Tuple (swap) import qualified Data.List as L import Data.Profunctor.Unsafe import Prelude hiding (drop, dropWhile, filter, init, span, splitAt, take, takeWhile) import qualified Data.Vector.Generic as GV import Control.Lens import qualified Prelude as P -- | A 'Sever' with a particular @f@. type SeverLike f s t a b = (a -> f (Maybe b)) -> s -> f (t, s) -- | A simple 'SeverLike'. type SeverLike' f s a = SeverLike f s s a a -- | A description of how to wither an object. 'Sever's can be composed -- on the left with van Laarhoven lenses (or the more general -- 'Traversal') to form a 'Sever' on the target. type Sever s t a b = forall f. Applicative f => SeverLike f s t a b -- | A simple 'Sever'. type Sever' s a = Sever s s a a -- | An 'ASever' with a particular profunctor @p@. type Severing p s t a b = p a (Identity (Maybe b)) -> s -> Identity (t,s) -- | A simple 'Severing'. type Severing' p s a = Severing p s s a a -- | A 'Sever' without side effects. type ASever s t a b = SeverLike Identity s t a b -- | A simple 'ASever' type ASever' s a = SeverLike' Identity s a -- | A 'Sever' for a particular @p@ and @f@. type Through p f s t a b = p a (f (Maybe b)) -> s -> f (t, s) -- | A simple 'Across'. type Through' p f s a = Through p f s s a a tReverse :: Traversable t => t a -> t a tReverse = partsOf traverse %~ reverse -- | 'Traversable' with the ability to break into two at some point. The follow -- -- @'traverse' f = fmap fst . 'sever' (fmap 'Just' . f)@ class Traversable t => Severable t where -- | Divide a structure in two by collecting all 'Just' values in the -- 'fst' tuple. Anything left behind is in the 'snd' tuple. sever :: Applicative f => (a -> f (Maybe b)) -> t a -> f (t b, t a) -- detatch :: (a -> Maybe b) -> t a -> (t b, t a) -- | Take up to the first @n@ items. take :: Int -> t a -> t a take i = fst . splitAt i {-# INLINE take #-} -- | Drop up to the first @n@ items. drop :: Int -> t a -> t a drop i = snd . splitAt i {-# INLINE drop #-} -- split :: Eq a => a -> t a -> (t a, t a) -- split = splitOf sever -- | Equivilent to @('take' n t, 'drop' n t)@ but can have a more -- efficient implimentation. splitAt :: Int -> t a -> (t a, t a) splitAt = splitAtOf sever {-# INLINE splitAt #-} -- | Take elements while the predicate is 'True'. takeWhileA :: Applicative f => (a -> f Bool) -> t a -> f (t a) takeWhileA = takeWhileAOf sever -- | Take elements while the predicate is 'True'. takeWhile :: (a -> Bool) -> t a -> t a takeWhile = takeWhileOf sever -- | Discard elements while the predicate is 'True'. dropWhileA :: Applicative f => (a -> f Bool) -> t a -> f (t a) dropWhileA = dropWhileAOf sever -- | Discard elements while the predicate is 'True'. dropWhile :: (a -> Bool) -> t a -> t a dropWhile = dropWhileOf sever -- | Equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@. span :: (a -> Bool) -> t a -> (t a, t a) span = spanOf sever -- | Equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@. spanA :: Applicative f => (a -> f Bool) -> t a -> f (t a, t a) spanA = spanAOf sever -- | 'break' with effects. breakA :: Applicative f => (a -> f Bool) -> t a -> f (t a, t a) breakA = breakAOf sever -- | Equivalent to @'span' ('not' . p)@. break :: (a -> Bool) -> t a -> (t a, t a) break p = span (not . p) -- End variants ------------------------------------------------------ -- | Take a number of elements from the end of the list. -- -- > takeEnd 3 "hello" == "llo" -- > takeEnd 5 "bye" == "bye" -- > takeEnd (-1) "bye" == "" -- > \i xs -> takeEnd i xs `isSuffixOf` xs -- > \i xs -> length (takeEnd i xs) == min (max 0 i) (length xs) takeEnd :: Int -> t a -> t a takeEnd i = tReverse . take i . tReverse -- | Drop a number of elements from the end of the list. -- -- > dropEnd 3 "hello" == "he" -- > dropEnd 5 "bye" == "" -- > dropEnd (-1) "bye" == "bye" -- > \i xs -> dropEnd i xs `isPrefixOf` xs -- > \i xs -> length (dropEnd i xs) == max 0 (length xs - max 0 i) -- > \i -> take 3 (dropEnd 5 [i..]) == take 3 [i..] dropEnd :: Int -> t a -> t a dropEnd i = tReverse . drop i . tReverse -- | @'splitAtEnd' n xs@ returns a split where the second element tries to -- contain @n@ elements. -- -- > splitAtEnd 3 "hello" == ("he","llo") -- > splitAtEnd 3 "he" == ("", "he") -- > \i xs -> uncurry (++) (splitAt i xs) == xs -- > \i xs -> splitAtEnd i xs == (dropEnd i xs, takeEnd i xs) splitAtEnd :: Int -> t a -> (t a, t a) splitAtEnd i = bimap tReverse tReverse . swap . splitAt i . tReverse -- | A version of 'takeWhile' operating from the end. -- -- > takeWhileEnd even [2,3,4,6] == [4,6] takeWhileEnd :: (a -> Bool) -> t a -> t a takeWhileEnd f = tReverse . takeWhile f . tReverse -- | Discard elements while the predicate is 'True', going from the -- end of the structure. This is equivilent to @'Optical.reverse' . -- 'dropWhile' p . 'Optical.reverse'@. dropWhileEnd :: (a -> Bool) -> t a -> t a dropWhileEnd f = tReverse . dropWhile f . tReverse -- -- | Drops the given prefix if it exists. Returns 'Nothing' if the -- -- prefix is not present. -- stripPrefix :: (Foldable f, Witherable t, Eq a) => f a -> t a -> Maybe (t a) -- stripPrefix p t -- | b && null l = Just t' -- | otherwise = Nothing -- where -- (t', (b, l)) = runState (wither f t) (True, F.toList p) -- f a = state $ \(b, l) -> case l of -- x:xs -> if x == a -- then (Nothing, (b, xs)) -- else (Just a, (False, [])) -- [] -> (Just a, (b, [])) #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707 {-# MINIMAL sever #-} #endif ------------------------------------------------------------------------ -- Wither type ------------------------------------------------------------------------ splitAtOf :: SeverLike' (State Int) s a -> Int -> s -> (s,s) splitAtOf w n = \t -> evalState (w f t) 0 where f a = state $ \i -> if i < n then (Nothing, i) else (Just a, i + 1) {-# INLINE splitAtOf #-} -- | Take the first @n@ elements from the target of a 'Wither'. takeOf :: SeverLike' (State Int) s a -> Int -> s -> s takeOf s n = fst . splitAtOf s n {-# INLINE takeOf #-} -- | Drop the first @n@ elements from the target of a 'Wither'. dropOf :: SeverLike' (State Int) s a -> Int -> s -> s dropOf s n = snd . splitAtOf s n {-# INLINE dropOf #-} splitOf :: Eq a => ASever' s a -> a -> s -> (s,s) splitOf s a = runIdentity #. s (Identity #. f) where f x | x == a = Nothing | otherwise = Just x -- | Collect all elements while the predicate is 'True' in the left of -- the tuple, the rest is in the right. -- -- @ -- spanAOf :: Applicative f => Sever' s a -> (a -> f Bool) -> s -> f (s,s) -- @ spanAOf :: (Conjoined p, Functor f) => Through' p f s a -> p a (f Bool) -> s -> f (s,s) spanAOf s pafb = s $ cotabulate $ \wa -> bool Nothing (Just $ extract wa) <$> cosieve pafb wa -- | Collect all elements while the predicate is 'True' in the left of -- the tuple, the rest is in the right. -- -- @ -- spanOf :: Sever' s a -> (a -> Bool) -> s -> (s,s) -- @ spanOf :: Conjoined p => Severing' p s a -> p a Bool -> s -> (s, s) spanOf s f = runIdentity #. spanAOf s (Identity #. f) {-# INLINE spanOf #-} -- | Equivalent to @'span' ('not' . p)@. breakAOf :: (Conjoined p, Functor f) => Through' p f s a -> p a (f Bool) -> s -> f (s,s) breakAOf s p = spanAOf s (fmap not `rmap` p) -- | Equivalent to @'span' ('not' . p)@. breakOf :: Conjoined p => Severing' p s a -> p a Bool -> s -> (s, s) breakOf s p = spanOf s (not `rmap` p) takeWhileAOf :: (Conjoined p, Functor f) => Through' p f s a -> p a (f Bool) -> s -> f s takeWhileAOf s p = fmap fst . spanAOf s p takeWhileOf :: Conjoined p => Severing' p s a -> p a Bool -> s -> s takeWhileOf s f = fst . spanOf s f {-# INLINE takeWhileOf #-} dropWhileAOf :: (Conjoined p, Functor f) => Through' p f s a -> p a (f Bool) -> s -> f s dropWhileAOf s p = fmap snd . spanAOf s p dropWhileOf :: Conjoined p => Severing' p s a -> p a Bool -> s -> s dropWhileOf s f = snd . spanOf s f {-# INLINE dropWhileOf #-} -- Instances ----------------------------------------------------------- instance Severable Maybe where sever f (Just a) = f a <&> \case b@Just {} -> (b, Nothing); _ -> (Nothing, Just a) sever _ Nothing = pure (Nothing, Nothing) {-# INLINE sever #-} instance Severable [] where sever f = go where go xss@(x:xs) = maybe (const ([], xss)) (first . (:)) <$> f x <*> go xs go [] = pure ([], []) {-# INLINE sever #-} take = P.take drop = P.drop -- split a = span (==a) splitAt = P.splitAt takeWhile = P.takeWhile dropWhile = P.dropWhile span = P.span break = P.break takeWhileEnd f = P.reverse . P.takeWhile f . P.reverse dropWhileEnd = L.dropWhileEnd takeEnd i xs0 = f xs0 (drop i xs0) where f (_:xs) (_:ys) = f xs ys f xs _ = xs dropEnd i xs0 = f xs0 (drop i xs0) where f (x:xs) (_:ys) = x : f xs ys f _ _ = [] {-# INLINE take #-} {-# INLINE drop #-} {-# INLINE splitAt #-} {-# INLINE takeWhile #-} {-# INLINE dropWhile #-} {-# INLINE span #-} {-# INLINE break #-} {-# INLINE takeWhileEnd #-} {-# INLINE dropWhileEnd #-} instance Severable IM.IntMap where sever f = fmap (bimap IM.fromList IM.fromAscList) . sever (\(i, a) -> fmap ((,) i) <$> f a) . IM.toList {-# INLINE sever #-} take n = IM.fromAscList . P.take n . IM.toAscList {-# INLINE take #-} drop n = IM.fromAscList . P.drop n . IM.toAscList {-# INLINE drop #-} instance Ord k => Severable (M.Map k) where sever f = fmap (bimap M.fromList M.fromAscList) . sever (\(i, a) -> fmap ((,) i) <$> f a) . M.toList {-# INLINE sever #-} take n = M.fromAscList . P.take n . M.toAscList {-# INLINE take #-} drop n = M.fromAscList . P.drop n . M.toAscList {-# INLINE drop #-} instance Severable V.Vector where sever f = fmap (bimap V.fromList V.fromList) . sever f . V.toList {-# INLINE sever #-} take = V.take {-# INLINE take #-} drop = V.drop {-# INLINE drop #-} splitAt = V.splitAt {-# INLINE splitAt #-} takeWhile = V.takeWhile {-# INLINE takeWhile #-} dropWhile = V.dropWhile {-# INLINE dropWhile #-} instance Severable S.Seq where sever f = fmap (bimap S.fromList S.fromList) . sever f . F.toList {-# INLINE sever #-} take = S.take {-# INLINE take #-} drop = S.drop {-# INLINE drop #-} splitAt = S.splitAt {-# INLINE splitAt #-} takeWhile = S.takeWhileL {-# INLINE takeWhile #-} dropWhile = S.dropWhileL {-# INLINE dropWhile #-} ------------------------------------------------------------------------ -- Indexed Severs ------------------------------------------------------------------------ type IndexedSeverLike i f s t a b = forall p. Indexable i p => p a (f (Maybe b)) -> s -> f (t,s) type IndexedSeverLike' i f s a = IndexedSeverLike i f s s a a type IndexedSever i s t a b = forall f. Applicative f => IndexedSeverLike i f s t a b type IndexedSever' i s a = IndexedSever i s s a a type AnIndexedSever i s t a b = IndexedSeverLike i Identity s t a b type AnIndexedSever' i s a = IndexedSeverLike' i Identity s a class (TraversableWithIndex i t, Severable t) => SeverableWithIndex i t | t -> i where isever :: Applicative f => (i -> a -> f (Maybe b)) -> t a -> f (t b, t a) isevered :: IndexedSever i (t a) (t b) a b isevered = conjoined sever (isever . indexed) -- | Take elements while the predicate is 'True'. itakeWhile :: (i -> a -> Bool) -> t a -> t a itakeWhile = itakeWhileOf isevered -- | Take elements while the predicate is 'True'. itakeWhileA :: Applicative f => (i -> a -> f Bool) -> t a -> f (t a) itakeWhileA = itakeWhileAOf isevered -- | Discard elements while the predicate is 'True'. idropWhileA :: Applicative f => (i -> a -> f Bool) -> t a -> f (t a) idropWhileA = idropWhileAOf isevered -- | Discard elements while the predicate is 'True'. idropWhile :: (i -> a -> Bool) -> t a -> t a idropWhile = idropWhileOf isevered -- -- | Discard elements while the predicate is 'True', going from the -- -- end of the structure. This is equivilent to @'Optical.reverse' . -- -- 'dropWhile' p . 'Optical.reverse'@. -- dropWhileEnd :: (a -> Bool) -> t a -> t a -- | Equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@. ispan :: (i -> a -> Bool) -> t a -> (t a, t a) ispan = ispanOf isevered -- | Equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@. ispanA :: Applicative f => (i -> a -> f Bool) -> t a -> f (t a, t a) ispanA = ispanAOf isevered -- | 'break' with effects. ibreakA :: Applicative f => (i -> a -> f Bool) -> t a -> f (t a, t a) ibreakA = ibreakAOf isevered -- | Equivalent to @'span' ('not' . p)@. ibreak :: (i -> a -> Bool) -> t a -> (t a, t a) ibreak = ibreakOf isevered itakeWhileAOf :: Functor f => IndexedSeverLike' i f s a -> (i -> a -> f Bool) -> s -> f s itakeWhileAOf s = takeWhileAOf s .# Indexed {-# INLINE itakeWhileAOf #-} idropWhileAOf :: Functor f => IndexedSeverLike' i f s a -> (i -> a -> f Bool) -> s -> f s idropWhileAOf s = dropWhileAOf s .# Indexed {-# INLINE idropWhileAOf #-} itakeWhileOf :: AnIndexedSever' i s a -> (i -> a -> Bool) -> s -> s itakeWhileOf s = takeWhileOf s .# Indexed {-# INLINE itakeWhileOf #-} idropWhileOf :: AnIndexedSever' i s a -> (i -> a -> Bool) -> s -> s idropWhileOf s = dropWhileOf s .# Indexed {-# INLINE idropWhileOf #-} ibreakAOf :: Functor f => IndexedSeverLike' i f s a -> (i -> a -> f Bool) -> s -> f (s, s) ibreakAOf s = breakAOf s .# Indexed {-# INLINE ibreakAOf #-} ibreakOf :: AnIndexedSever' i s a -> (i -> a -> Bool) -> s -> (s, s) ibreakOf s = breakOf s .# Indexed {-# INLINE ibreakOf #-} ispanAOf :: Functor f => IndexedSeverLike' i f s a -> (i -> a -> f Bool) -> s -> f (s, s) ispanAOf s = spanAOf s .# Indexed {-# INLINE ispanAOf #-} ispanOf :: AnIndexedSever' i s a -> (i -> a -> Bool) -> s -> (s, s) ispanOf s = spanOf s .# Indexed {-# INLINE ispanOf #-} instance SeverableWithIndex Int [] where isever f = go 0 where go i xss@(x:xs) = maybe (const ([], xss)) (first . (:)) <$> f i x <*> go (i+1) xs go _ [] = pure ([], []) {-# INLINE isever #-} instance SeverableWithIndex Int S.Seq where isever f = fmap (bimap S.fromList S.fromList) . isever f . F.toList instance SeverableWithIndex Int V.Vector where isever f = fmap (bimap V.fromList V.fromList) . isever f . V.toList -- ------------------------------------------------------------------------ -- -- Predefined severs -- ------------------------------------------------------------------------ -- | A sever over a generic vector. severVector :: (GV.Vector v a, GV.Vector w b) => IndexedSever Int (v a) (w b) a b severVector f = fmap (bimap GV.fromList GV.fromList) . severed f . GV.toList {-# INLINE severVector #-} -- {-# RULES -- "catMaybe vector sever" -- severVector = sets (\f -> GV.fromList . mapMaybe f . GV.toList) -- :: (GV.Vector v a, GV.Vector w b) => ASever (v a) (w b) a b -- #-} -- | 'sever' with an index according to its ordinal position. severed :: Severable t => IndexedSever Int (t a) (t b) a b severed = conjoined sever (indexing sever) {-# INLINE severed #-}
cchalmers/optical
src/Optical/Severable.hs
bsd-3-clause
17,536
0
15
4,513
4,779
2,565
2,214
258
2
-------------------------------------------------------------------------------- -- | -- Module : System.Taffybar.Widget.DiskIOMonitor -- Copyright : (c) José A. Romero L. -- License : BSD3-style (see LICENSE) -- -- Maintainer : José A. Romero L. <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Simple Disk IO monitor that uses a PollingGraph to visualize the speed of -- read/write operations in one selected disk or partition. -- -------------------------------------------------------------------------------- module System.Taffybar.Widget.DiskIOMonitor ( dioMonitorNew ) where import Control.Monad.IO.Class import qualified GI.Gtk import System.Taffybar.Information.DiskIO ( getDiskTransfer ) import System.Taffybar.Widget.Generic.PollingGraph ( GraphConfig, pollingGraphNew ) -- | Creates a new disk IO monitor widget. This is a 'PollingGraph' fed by -- regular calls to 'getDiskTransfer'. The results of calling this function -- are normalized to the maximum value of the obtained probe (either read or -- write transfer). dioMonitorNew :: MonadIO m => GraphConfig -- ^ Configuration data for the Graph. -> Double -- ^ Polling period (in seconds). -> String -- ^ Name of the disk or partition to watch (e.g. \"sda\", \"sdb1\"). -> m GI.Gtk.Widget dioMonitorNew cfg pollSeconds = pollingGraphNew cfg pollSeconds . probeDisk probeDisk :: String -> IO [Double] probeDisk disk = do transfer <- getDiskTransfer disk let top = foldr max 1.0 transfer return $ map (/top) transfer
teleshoes/taffybar
src/System/Taffybar/Widget/DiskIOMonitor.hs
bsd-3-clause
1,582
0
10
269
189
113
76
18
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Stack.Dot (dot ,DotOpts(..) ,resolveDependencies ,printGraph ,pruneGraph ) where import Control.Applicative import Control.Monad (void) import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger) import Control.Monad.Reader (MonadReader) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Data.Foldable as F import qualified Data.HashSet as HashSet import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid ((<>)) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Data.Traversable as T import Network.HTTP.Client.Conduit (HasHttpManager) import Stack.Build (withLoadPackage) import Stack.Build.Source import Stack.Build.Types import Stack.Constants import Stack.Package import Stack.Types -- | Options record for `stack dot` data DotOpts = DotOpts { dotIncludeExternal :: Bool -- ^ Include external dependencies , dotIncludeBase :: Bool -- ^ Include dependencies on base , dotDependencyDepth :: Maybe Int -- ^ Limit the depth of dependency resolution to (Just n) or continue until fixpoint , dotPrune :: Set String -- ^ Package names to prune from the graph } -- | Visualize the project's dependencies as a graphviz graph dot :: (HasEnvConfig env ,HasHttpManager env ,MonadBaseControl IO m ,MonadCatch m ,MonadLogger m ,MonadIO m ,MonadReader env m ) => DotOpts -> m () dot dotOpts = do (locals,_,_) <- loadLocals defaultBuildOpts Map.empty (_,_,_,sourceMap) <- loadSourceMap defaultBuildOpts let graph = Map.fromList (localDependencies dotOpts locals) menv <- getMinimalEnvOverride resultGraph <- withLoadPackage menv (\loader -> do let depLoader = createDepLoader sourceMap (fmap3 packageAllDeps loader) liftIO $ resolveDependencies (dotDependencyDepth dotOpts) graph depLoader) let pkgsToPrune = if dotIncludeBase dotOpts then dotPrune dotOpts else Set.insert "base" (dotPrune dotOpts) localNames = Set.fromList (map (packageName . lpPackage) locals) prunedGraph = pruneGraph localNames pkgsToPrune resultGraph printGraph dotOpts locals prunedGraph where -- fmap a function over the result of a function with 3 arguments fmap3 :: Functor f => (d -> e) -> (a -> b -> c -> f d) -> a -> b -> c -> f e fmap3 f g a b c = f <$> g a b c -- | `pruneGraph dontPrune toPrune graph` prunes all packages in -- `graph` with a name in `toPrune` and removes resulting orphans -- unless they are in `dontPrune` pruneGraph :: (F.Foldable f, F.Foldable g) => f PackageName -> g String -> Map PackageName (Set PackageName) -> Map PackageName (Set PackageName) pruneGraph dontPrune names = pruneUnreachable dontPrune . Map.mapMaybeWithKey (\pkg pkgDeps -> if show pkg `F.elem` names then Nothing else let filtered = Set.filter (\n -> show n `F.notElem` names) pkgDeps in if Set.null filtered && not (Set.null pkgDeps) then Nothing else Just filtered) -- | Make sure that all unreachable nodes (orphans) are pruned pruneUnreachable :: F.Foldable f => f PackageName -> Map PackageName (Set PackageName) -> Map PackageName (Set PackageName) pruneUnreachable dontPrune = fixpoint prune where fixpoint :: Eq a => (a -> a) -> a -> a fixpoint f v = if f v == v then v else fixpoint f (f v) prune graph' = Map.filterWithKey (\k _ -> reachable k) graph' where reachable k = k `F.elem` dontPrune || k `Set.member` reachables reachables = F.fold graph' -- | Resolve the dependency graph up to (Just depth) or until fixpoint is reached resolveDependencies :: (Applicative m, Monad m) => Maybe Int -> Map PackageName (Set PackageName) -> (PackageName -> m (Set PackageName)) -> m (Map PackageName (Set PackageName)) resolveDependencies (Just 0) graph _ = return graph resolveDependencies limit graph loadPackageDeps = do let values = Set.unions (Map.elems graph) keys = Map.keysSet graph next = Set.difference values keys if Set.null next then return graph else do x <- T.traverse (\name -> (name,) <$> loadPackageDeps name) (F.toList next) resolveDependencies (subtract 1 <$> limit) (Map.unionWith Set.union graph (Map.fromList x)) loadPackageDeps -- | Given a SourceMap and a dependency loader, load the set of dependencies for a package createDepLoader :: Applicative m => Map PackageName PackageSource -> (PackageName -> Version -> Map FlagName Bool -> m (Set PackageName)) -> PackageName -> m (Set PackageName) createDepLoader sourceMap loadPackageDeps pkgName = case Map.lookup pkgName sourceMap of Just (PSLocal lp) -> pure (packageAllDeps (lpPackage lp)) Just (PSUpstream version _ flags) -> loadPackageDeps pkgName version flags Nothing -> pure Set.empty -- | Resolve the direct (depth 0) external dependencies of the given local packages localDependencies :: DotOpts -> [LocalPackage] -> [(PackageName,Set PackageName)] localDependencies dotOpts locals = map (\lp -> (packageName (lpPackage lp), deps lp)) locals where deps lp = if dotIncludeExternal dotOpts then Set.delete (lpName lp) (packageAllDeps (lpPackage lp)) else Set.intersection localNames (packageAllDeps (lpPackage lp)) lpName lp = packageName (lpPackage lp) localNames = Set.fromList $ map (packageName . lpPackage) locals -- | Print a graphviz graph of the edges in the Map and highlight the given local packages printGraph :: (Applicative m, MonadIO m) => DotOpts -> [LocalPackage] -> Map PackageName (Set PackageName) -> m () printGraph dotOpts locals graph = do liftIO $ Text.putStrLn "strict digraph deps {" printLocalNodes dotOpts filteredLocals printLeaves graph void (Map.traverseWithKey printEdges graph) liftIO $ Text.putStrLn "}" where filteredLocals = filter (\local -> show (packageName (lpPackage local)) `Set.notMember` dotPrune dotOpts) locals -- | Print the local nodes with a different style depending on options printLocalNodes :: (F.Foldable t, MonadIO m) => DotOpts -> t LocalPackage -> m () printLocalNodes dotOpts locals = liftIO $ Text.putStrLn (Text.intercalate "\n" lpNodes) where applyStyle :: Text -> Text applyStyle n = if dotIncludeExternal dotOpts then n <> " [style=dashed];" else n <> " [style=solid];" lpNodes :: [Text] lpNodes = map (applyStyle . nodeName . packageName . lpPackage) (F.toList locals) -- | Print nodes without dependencies printLeaves :: (Applicative m, MonadIO m) => Map PackageName (Set PackageName) -> m () printLeaves = F.traverse_ printLeaf . Map.keysSet . Map.filter Set.null -- | `printDedges p ps` prints an edge from p to every ps printEdges :: (Applicative m, MonadIO m) => PackageName -> Set PackageName -> m () printEdges package deps = F.for_ deps (printEdge package) -- | Print an edge between the two package names printEdge :: MonadIO m => PackageName -> PackageName -> m () printEdge from to = liftIO $ Text.putStrLn (Text.concat [ nodeName from, " -> ", nodeName to, ";"]) -- | Convert a package name to a graph node name. nodeName :: PackageName -> Text nodeName name = "\"" <> Text.pack (packageNameString name) <> "\"" -- | Print a node with no dependencies printLeaf :: MonadIO m => PackageName -> m () printLeaf package = liftIO . Text.putStrLn . Text.concat $ if isWiredIn package then ["{rank=max; ", nodeName package, " [shape=box]; };"] else ["{rank=max; ", nodeName package, "; };"] -- | Check if the package is wired in (shipped with) ghc isWiredIn :: PackageName -> Bool isWiredIn = (`HashSet.member` wiredInPackages)
wskplho/stack
src/Stack/Dot.hs
bsd-3-clause
8,682
0
18
2,294
2,292
1,197
1,095
160
3
{-# LANGUAGE NumericUnderscores #-} -- Test for NumericUnderscores extension. -- See #14473 -- This is a testcase for invalid case of NumericUnderscores. main :: IO () main = do print [ -- integer 1000000_, _1000000 ]
sdiehl/ghc
testsuite/tests/parser/should_fail/NumericUnderscoresFail0.hs
bsd-3-clause
270
0
8
88
33
19
14
6
1
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, OverloadedStrings, Rank2Types, RecordWildCards, TypeFamilies #-} -- | -- Module : Data.Attoparsec.Internal.Types -- Copyright : Bryan O'Sullivan 2007-2014 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : unknown -- -- Simple, efficient parser combinators, loosely based on the Parsec -- library. module Data.Attoparsec.Internal.Types ( Parser(..) , State , Failure , Success , Pos(..) , IResult(..) , More(..) , (<>) , Chunk(..) ) where import Control.Applicative (Alternative(..), Applicative(..), (<$>)) import Control.DeepSeq (NFData(rnf)) import Control.Monad (MonadPlus(..)) import Data.Word (Word8) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.ByteString.Internal (w2c) import Data.Monoid (Monoid(..)) import Prelude hiding (getChar, succ) import qualified Data.Attoparsec.ByteString.Buffer as B newtype Pos = Pos { fromPos :: Int } deriving (Eq, Ord, Show, Num) -- | The result of a parse. This is parameterised over the type @i@ -- of string that was processed. -- -- This type is an instance of 'Functor', where 'fmap' transforms the -- value in a 'Done' result. data IResult i r = Fail i [String] String -- ^ The parse failed. The @i@ parameter is the input that had -- not yet been consumed when the failure occurred. The -- @[@'String'@]@ is a list of contexts in which the error -- occurred. The 'String' is the message describing the error, if -- any. | Partial (i -> IResult i r) -- ^ Supply this continuation with more input so that the parser -- can resume. To indicate that no more input is available, pass -- an empty string to the continuation. -- -- __Note__: if you get a 'Partial' result, do not call its -- continuation more than once. | Done i r -- ^ The parse succeeded. The @i@ parameter is the input that had -- not yet been consumed (if any) when the parse succeeded. instance (Show i, Show r) => Show (IResult i r) where show (Fail t stk msg) = unwords [ "Fail", show t, show stk, show msg] show (Partial _) = "Partial _" show (Done t r) = unwords ["Done", show t, show r] instance (NFData i, NFData r) => NFData (IResult i r) where rnf (Fail t stk msg) = rnf t `seq` rnf stk `seq` rnf msg rnf (Partial _) = () rnf (Done t r) = rnf t `seq` rnf r {-# INLINE rnf #-} instance Functor (IResult i) where fmap _ (Fail t stk msg) = Fail t stk msg fmap f (Partial k) = Partial (fmap f . k) fmap f (Done t r) = Done t (f r) -- | The core parser type. This is parameterised over the types @i@ -- of string being processed and @t@ of internal state representation. -- -- This type is an instance of the following classes: -- -- * 'Monad', where 'fail' throws an exception (i.e. fails) with an -- error message. -- -- * 'Functor' and 'Applicative', which follow the usual definitions. -- -- * 'MonadPlus', where 'mzero' fails (with no error message) and -- 'mplus' executes the right-hand parser if the left-hand one -- fails. When the parser on the right executes, the input is reset -- to the same state as the parser on the left started with. (In -- other words, attoparsec is a backtracking parser that supports -- arbitrary lookahead.) -- -- * 'Alternative', which follows 'MonadPlus'. newtype Parser i a = Parser { runParser :: forall r. State i -> Pos -> More -> Failure i (State i) r -> Success i (State i) a r -> IResult i r } type family State i type instance State ByteString = B.Buffer type Failure i t r = t -> Pos -> More -> [String] -> String -> IResult i r type Success i t a r = t -> Pos -> More -> a -> IResult i r -- | Have we read all available input? data More = Complete | Incomplete deriving (Eq, Show) instance Monoid More where mappend c@Complete _ = c mappend _ m = m mempty = Incomplete instance Monad (Parser i) where fail err = Parser $ \t pos more lose _succ -> lose t pos more [] msg where msg = "Failed reading: " ++ err {-# INLINE fail #-} return v = Parser $ \t pos more _lose succ -> succ t pos more v {-# INLINE return #-} m >>= k = Parser $ \t !pos more lose succ -> let succ' t' !pos' more' a = runParser (k a) t' pos' more' lose succ in runParser m t pos more lose succ' {-# INLINE (>>=) #-} plus :: Parser i a -> Parser i a -> Parser i a plus f g = Parser $ \t pos more lose succ -> let lose' t' _pos' more' _ctx _msg = runParser g t' pos more' lose succ in runParser f t pos more lose' succ instance MonadPlus (Parser i) where mzero = fail "mzero" {-# INLINE mzero #-} mplus = plus instance Functor (Parser i) where fmap f p = Parser $ \t pos more lose succ -> let succ' t' pos' more' a = succ t' pos' more' (f a) in runParser p t pos more lose succ' {-# INLINE fmap #-} apP :: Parser i (a -> b) -> Parser i a -> Parser i b apP d e = do b <- d a <- e return (b a) {-# INLINE apP #-} instance Applicative (Parser i) where pure = return {-# INLINE pure #-} (<*>) = apP {-# INLINE (<*>) #-} -- These definitions are equal to the defaults, but this -- way the optimizer doesn't have to work so hard to figure -- that out. (*>) = (>>) {-# INLINE (*>) #-} x <* y = x >>= \a -> y >> return a {-# INLINE (<*) #-} instance Monoid (Parser i a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = plus {-# INLINE mappend #-} instance Alternative (Parser i) where empty = fail "empty" {-# INLINE empty #-} (<|>) = plus {-# INLINE (<|>) #-} many v = many_v where many_v = some_v <|> pure [] some_v = (:) <$> v <*> many_v {-# INLINE many #-} some v = some_v where many_v = some_v <|> pure [] some_v = (:) <$> v <*> many_v {-# INLINE some #-} (<>) :: (Monoid m) => m -> m -> m (<>) = mappend {-# INLINE (<>) #-} -- | A common interface for input chunks. class Monoid c => Chunk c where type ChunkElem c -- | Test if the chunk is empty. nullChunk :: c -> Bool -- | Append chunk to a buffer. pappendChunk :: State c -> c -> State c -- | Position at the end of a buffer. The first argument is ignored. atBufferEnd :: c -> State c -> Pos -- | Return the buffer element at the given position along with its length. bufferElemAt :: c -> Pos -> State c -> Maybe (ChunkElem c, Int) -- | Map an element to the corresponding character. -- The first argument is ignored. chunkElemToChar :: c -> ChunkElem c -> Char instance Chunk ByteString where type ChunkElem ByteString = Word8 nullChunk = BS.null {-# INLINE nullChunk #-} pappendChunk = B.pappend {-# INLINE pappendChunk #-} atBufferEnd _ = Pos . B.length {-# INLINE atBufferEnd #-} bufferElemAt _ (Pos i) buf | i < B.length buf = Just (B.unsafeIndex buf i, 1) | otherwise = Nothing {-# INLINE bufferElemAt #-} chunkElemToChar _ = w2c {-# INLINE chunkElemToChar #-}
DavidAlphaFox/ghc
utils/haddock/haddock-library/vendor/attoparsec-0.12.1.1/Data/Attoparsec/Internal/Types.hs
bsd-3-clause
7,311
0
15
1,958
1,818
1,005
813
140
1
{-# LANGUAGE ScopedTypeVariables, ExistentialQuantification, ApplicativeDo #-} {-# OPTIONS_GHC -foptimal-applicative-do #-} module Main where import Control.Applicative import Text.PrettyPrint as PP (a:b:c:d:e:f:g:h:_) = map (\c -> doc [c]) ['a'..] -- This one requires -foptimal-applicative-do to find the best solution -- ((a; b) | (c; d)); e test1 :: M () test1 = do x1 <- a x2 <- const b x1 x3 <- c x4 <- const d x3 x5 <- const e (x1,x4) return (const () x5) -- (a | c); (b | d); e test2 :: M () test2 = do x1 <- a x3 <- c x2 <- const b x1 x4 <- const d x3 x5 <- const e (x1,x4) return (const () x5) main = mapM_ run [ test1 , test2 ] -- Testing code, prints out the structure of a monad/applicative expression newtype M a = M (Bool -> (Maybe Doc, a)) maybeParen True d = parens d maybeParen _ d = d run :: M a -> IO () run (M m) = print d where (Just d,_) = m False instance Functor M where fmap f m = m >>= return . f instance Applicative M where pure a = M $ \_ -> (Nothing, a) M f <*> M a = M $ \p -> let (Just d1, f') = f True (Just d2, a') = a True in (Just (maybeParen p (d1 <+> char '|' <+> d2)), f' a') instance Monad M where return = pure M m >>= k = M $ \p -> let (d1, a) = m True (d2, b) = case k a of M f -> f True in case (d1,d2) of (Nothing,Nothing) -> (Nothing, b) (Just d, Nothing) -> (Just d, b) (Nothing, Just d) -> (Just d, b) (Just d1, Just d2) -> (Just (maybeParen p (d1 PP.<> semi <+> d2)), b) doc :: String -> M () doc d = M $ \_ -> (Just (text d), ())
ezyang/ghc
testsuite/tests/ado/ado-optimal.hs
bsd-3-clause
1,599
0
19
442
796
406
390
50
1
{-# LANGUAGE DatatypeContexts #-} module ShouldFail where import Data.Ratio data Integral a => P a = P { p :: a } f :: Integral a => P (Ratio a) -> P (Ratio a) f x = x { p = p x }
siddhanathan/ghc
testsuite/tests/typecheck/should_fail/tcfail102.hs
bsd-3-clause
183
0
9
47
86
46
40
6
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wno-overlapping-patterns -Wno-incomplete-patterns -Wno-incomplete-uni-patterns -Wno-incomplete-record-updates #-} module Futhark.Pass.ExtractKernels.DistributeNests ( MapLoop (..), mapLoopStm, bodyContainsParallelism, lambdaContainsParallelism, determineReduceOp, histKernel, DistEnv (..), DistAcc (..), runDistNestT, DistNestT, liftInner, distributeMap, distribute, distributeSingleStm, distributeMapBodyStms, addStmsToAcc, addStmToAcc, permutationAndMissing, addPostStms, postStm, inNesting, ) where import Control.Arrow (first) import Control.Monad.Identity import Control.Monad.RWS.Strict import Control.Monad.Reader import Control.Monad.Trans.Maybe import Control.Monad.Writer.Strict import Data.Function ((&)) import Data.List (find, partition, tails) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map as M import Data.Maybe import Futhark.IR import Futhark.IR.SOACS (SOACS) import qualified Futhark.IR.SOACS as SOACS import Futhark.IR.SOACS.SOAC hiding (HistOp, histDest) import Futhark.IR.SOACS.Simplify (simpleSOACS, simplifyStms) import Futhark.IR.SegOp import Futhark.MonadFreshNames import Futhark.Pass.ExtractKernels.BlockedKernel import Futhark.Pass.ExtractKernels.Distribution import Futhark.Pass.ExtractKernels.ISRWIM import Futhark.Pass.ExtractKernels.Interchange import Futhark.Tools import Futhark.Transform.CopyPropagate import qualified Futhark.Transform.FirstOrderTransform as FOT import Futhark.Transform.Rename import Futhark.Util import Futhark.Util.Log scopeForSOACs :: SameScope rep SOACS => Scope rep -> Scope SOACS scopeForSOACs = castScope data MapLoop = MapLoop (Pat Type) (StmAux ()) SubExp (Lambda SOACS) [VName] mapLoopStm :: MapLoop -> Stm SOACS mapLoopStm (MapLoop pat aux w lam arrs) = Let pat aux $ Op $ Screma w arrs $ mapSOAC lam data DistEnv rep m = DistEnv { distNest :: Nestings, distScope :: Scope rep, distOnTopLevelStms :: Stms SOACS -> DistNestT rep m (Stms rep), distOnInnerMap :: MapLoop -> DistAcc rep -> DistNestT rep m (DistAcc rep), distOnSOACSStms :: Stm SOACS -> Builder rep (Stms rep), distOnSOACSLambda :: Lambda SOACS -> Builder rep (Lambda rep), distSegLevel :: MkSegLevel rep m } data DistAcc rep = DistAcc { distTargets :: Targets, distStms :: Stms rep } data DistRes rep = DistRes { accPostStms :: PostStms rep, accLog :: Log } instance Semigroup (DistRes rep) where DistRes ks1 log1 <> DistRes ks2 log2 = DistRes (ks1 <> ks2) (log1 <> log2) instance Monoid (DistRes rep) where mempty = DistRes mempty mempty newtype PostStms rep = PostStms {unPostStms :: Stms rep} instance Semigroup (PostStms rep) where PostStms xs <> PostStms ys = PostStms $ ys <> xs instance Monoid (PostStms rep) where mempty = PostStms mempty typeEnvFromDistAcc :: DistRep rep => DistAcc rep -> Scope rep typeEnvFromDistAcc = scopeOfPat . fst . outerTarget . distTargets addStmsToAcc :: Stms rep -> DistAcc rep -> DistAcc rep addStmsToAcc stms acc = acc {distStms = stms <> distStms acc} addStmToAcc :: (MonadFreshNames m, DistRep rep) => Stm SOACS -> DistAcc rep -> DistNestT rep m (DistAcc rep) addStmToAcc stm acc = do onSoacs <- asks distOnSOACSStms (stm', _) <- runBuilder $ onSoacs stm return acc {distStms = stm' <> distStms acc} soacsLambda :: (MonadFreshNames m, DistRep rep) => Lambda SOACS -> DistNestT rep m (Lambda rep) soacsLambda lam = do onLambda <- asks distOnSOACSLambda fst <$> runBuilder (onLambda lam) newtype DistNestT rep m a = DistNestT (ReaderT (DistEnv rep m) (WriterT (DistRes rep) m) a) deriving ( Functor, Applicative, Monad, MonadReader (DistEnv rep m), MonadWriter (DistRes rep) ) liftInner :: (LocalScope rep m, DistRep rep) => m a -> DistNestT rep m a liftInner m = do outer_scope <- askScope DistNestT $ lift $ lift $ do inner_scope <- askScope localScope (outer_scope `M.difference` inner_scope) m instance MonadFreshNames m => MonadFreshNames (DistNestT rep m) where getNameSource = DistNestT $ lift getNameSource putNameSource = DistNestT . lift . putNameSource instance (Monad m, ASTRep rep) => HasScope rep (DistNestT rep m) where askScope = asks distScope instance (Monad m, ASTRep rep) => LocalScope rep (DistNestT rep m) where localScope types = local $ \env -> env {distScope = types <> distScope env} instance Monad m => MonadLogger (DistNestT rep m) where addLog msgs = tell mempty {accLog = msgs} runDistNestT :: (MonadLogger m, DistRep rep) => DistEnv rep m -> DistNestT rep m (DistAcc rep) -> m (Stms rep) runDistNestT env (DistNestT m) = do (acc, res) <- runWriterT $ runReaderT m env addLog $ accLog res -- There may be a few final targets remaining - these correspond to -- arrays that are identity mapped, and must have statements -- inserted here. pure $ unPostStms (accPostStms res) <> identityStms (outerTarget $ distTargets acc) where outermost = nestingLoop $ case distNest env of (nest, []) -> nest (_, nest : _) -> nest params_to_arrs = map (first paramName) $ loopNestingParamsAndArrs outermost identityStms (rem_pat, res) = stmsFromList $ zipWith identityStm (patElems rem_pat) res identityStm pe (SubExpRes cs (Var v)) | Just arr <- lookup v params_to_arrs = certify cs $ Let (Pat [pe]) (defAux ()) $ BasicOp $ Copy arr identityStm pe (SubExpRes cs se) = certify cs . Let (Pat [pe]) (defAux ()) . BasicOp $ Replicate (Shape [loopNestingWidth outermost]) se addPostStms :: Monad m => PostStms rep -> DistNestT rep m () addPostStms ks = tell $ mempty {accPostStms = ks} postStm :: Monad m => Stms rep -> DistNestT rep m () postStm stms = addPostStms $ PostStms stms withStm :: (Monad m, DistRep rep) => Stm SOACS -> DistNestT rep m a -> DistNestT rep m a withStm stm = local $ \env -> env { distScope = castScope (scopeOf stm) <> distScope env, distNest = letBindInInnerNesting provided $ distNest env } where provided = namesFromList $ patNames $ stmPat stm leavingNesting :: (MonadFreshNames m, DistRep rep) => DistAcc rep -> DistNestT rep m (DistAcc rep) leavingNesting acc = case popInnerTarget $ distTargets acc of Nothing -> error "The kernel targets list is unexpectedly small" Just ((pat, res), newtargets) | not $ null $ distStms acc -> do -- Any statements left over correspond to something that -- could not be distributed because it would cause irregular -- arrays. These must be reconstructed into a a Map SOAC -- that will be sequentialised. XXX: life would be better if -- we were able to distribute irregular parallelism. (Nesting _ inner, _) <- asks distNest let MapNesting _ aux w params_and_arrs = inner body = Body () (distStms acc) res used_in_body = freeIn body (used_params, used_arrs) = unzip $ filter ((`nameIn` used_in_body) . paramName . fst) params_and_arrs lam' = Lambda { lambdaParams = used_params, lambdaBody = body, lambdaReturnType = map rowType $ patTypes pat } stms <- runBuilder_ . auxing aux . FOT.transformSOAC pat $ Screma w used_arrs $ mapSOAC lam' return $ acc {distTargets = newtargets, distStms = stms} | otherwise -> do -- Any results left over correspond to a Replicate or a Copy in -- the parent nesting, depending on whether the argument is a -- parameter of the innermost nesting. (Nesting _ inner_nesting, _) <- asks distNest let w = loopNestingWidth inner_nesting aux = loopNestingAux inner_nesting inps = loopNestingParamsAndArrs inner_nesting remnantStm pe (SubExpRes cs (Var v)) | Just (_, arr) <- find ((== v) . paramName . fst) inps = certify cs $ Let (Pat [pe]) aux $ BasicOp $ Copy arr remnantStm pe (SubExpRes cs se) = certify cs $ Let (Pat [pe]) aux $ BasicOp $ Replicate (Shape [w]) se stms = stmsFromList $ zipWith remnantStm (patElems pat) res return $ acc {distTargets = newtargets, distStms = stms} mapNesting :: (MonadFreshNames m, DistRep rep) => Pat Type -> StmAux () -> SubExp -> Lambda SOACS -> [VName] -> DistNestT rep m (DistAcc rep) -> DistNestT rep m (DistAcc rep) mapNesting pat aux w lam arrs m = local extend $ leavingNesting =<< m where nest = Nesting mempty $ MapNesting pat aux w $ zip (lambdaParams lam) arrs extend env = env { distNest = pushInnerNesting nest $ distNest env, distScope = castScope (scopeOf lam) <> distScope env } inNesting :: (Monad m, DistRep rep) => KernelNest -> DistNestT rep m a -> DistNestT rep m a inNesting (outer, nests) = local $ \env -> env { distNest = (inner, nests'), distScope = foldMap scopeOfLoopNesting (outer : nests) <> distScope env } where (inner, nests') = case reverse nests of [] -> (asNesting outer, []) (inner' : ns) -> (asNesting inner', map asNesting $ outer : reverse ns) asNesting = Nesting mempty bodyContainsParallelism :: Body SOACS -> Bool bodyContainsParallelism = any isParallelStm . bodyStms where isParallelStm stm = isMap (stmExp stm) && not ("sequential" `inAttrs` stmAuxAttrs (stmAux stm)) isMap BasicOp {} = False isMap Apply {} = False isMap If {} = False isMap (DoLoop _ ForLoop {} body) = bodyContainsParallelism body isMap (DoLoop _ WhileLoop {} _) = False isMap (WithAcc _ lam) = bodyContainsParallelism $ lambdaBody lam isMap Op {} = True lambdaContainsParallelism :: Lambda SOACS -> Bool lambdaContainsParallelism = bodyContainsParallelism . lambdaBody distributeMapBodyStms :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => DistAcc rep -> Stms SOACS -> DistNestT rep m (DistAcc rep) distributeMapBodyStms orig_acc = distribute <=< onStms orig_acc . stmsToList where onStms acc [] = return acc onStms acc (Let pat (StmAux cs _ _) (Op (Stream w arrs Sequential accs lam)) : stms) = do types <- asksScope scopeForSOACs stream_stms <- snd <$> runBuilderT (sequentialStreamWholeArray pat w accs lam arrs) types stream_stms' <- runReaderT (copyPropagateInStms simpleSOACS types stream_stms) types onStms acc $ stmsToList (fmap (certify cs) stream_stms') ++ stms onStms acc (stm : stms) = -- It is important that stm is in scope if 'maybeDistributeStm' -- wants to distribute, even if this causes the slightly silly -- situation that stm is in scope of itself. withStm stm $ maybeDistributeStm stm =<< onStms acc stms onInnerMap :: Monad m => MapLoop -> DistAcc rep -> DistNestT rep m (DistAcc rep) onInnerMap loop acc = do f <- asks distOnInnerMap f loop acc onTopLevelStms :: Monad m => Stms SOACS -> DistNestT rep m () onTopLevelStms stms = do f <- asks distOnTopLevelStms postStm =<< f stms maybeDistributeStm :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => Stm SOACS -> DistAcc rep -> DistNestT rep m (DistAcc rep) maybeDistributeStm stm acc | "sequential" `inAttrs` stmAuxAttrs (stmAux stm) = addStmToAcc stm acc maybeDistributeStm (Let pat aux (Op soac)) acc | "sequential_outer" `inAttrs` stmAuxAttrs aux = distributeMapBodyStms acc . fmap (certify (stmAuxCerts aux)) =<< runBuilder_ (FOT.transformSOAC pat soac) maybeDistributeStm stm@(Let pat _ (Op (Screma w arrs form))) acc | Just lam <- isMapSOAC form = -- Only distribute inside the map if we can distribute everything -- following the map. distributeIfPossible acc >>= \case Nothing -> addStmToAcc stm acc Just acc' -> distribute =<< onInnerMap (MapLoop pat (stmAux stm) w lam arrs) acc' maybeDistributeStm stm@(Let pat aux (DoLoop merge form@ForLoop {} body)) acc | not $ any (`nameIn` freeIn pat) $ patNames pat, bodyContainsParallelism body = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | -- XXX: We cannot distribute if this loop depends on -- certificates bound within the loop nest (well, we could, -- but interchange would not be valid). This is not a -- fundamental restriction, but an artifact of our -- certificate representation, which we should probably -- rethink. not $ (freeIn form <> freeIn aux) `namesIntersect` boundInKernelNest nest, Just (perm, pat_unused) <- permutationAndMissing pat res -> -- We need to pretend pat_unused was used anyway, by adding -- it to the kernel nest. localScope (typeEnvFromDistAcc acc') $ do addPostStms kernels nest' <- expandKernelNest pat_unused nest types <- asksScope scopeForSOACs -- Simplification is key to hoisting out statements that -- were variant to the loop, but invariant to the outer maps -- (which are now innermost). stms <- (`runReaderT` types) $ simplifyStms =<< interchangeLoops nest' (SeqLoop perm pat merge form body) onTopLevelStms stms return acc' _ -> addStmToAcc stm acc maybeDistributeStm stm@(Let pat _ (If cond tbranch fbranch ret)) acc | not $ any (`nameIn` freeIn pat) $ patNames pat, bodyContainsParallelism tbranch || bodyContainsParallelism fbranch || not (all primType (ifReturns ret)) = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | not $ (freeIn cond <> freeIn ret) `namesIntersect` boundInKernelNest nest, Just (perm, pat_unused) <- permutationAndMissing pat res -> -- We need to pretend pat_unused was used anyway, by adding -- it to the kernel nest. localScope (typeEnvFromDistAcc acc') $ do nest' <- expandKernelNest pat_unused nest addPostStms kernels types <- asksScope scopeForSOACs let branch = Branch perm pat cond tbranch fbranch ret stms <- (`runReaderT` types) $ simplifyStms =<< interchangeBranch nest' branch onTopLevelStms stms return acc' _ -> addStmToAcc stm acc maybeDistributeStm stm@(Let pat _ (WithAcc inputs lam)) acc | lambdaContainsParallelism lam = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | not $ freeIn (drop num_accs (lambdaReturnType lam)) `namesIntersect` boundInKernelNest nest, Just (perm, pat_unused) <- permutationAndMissing pat res -> -- We need to pretend pat_unused was used anyway, by adding -- it to the kernel nest. localScope (typeEnvFromDistAcc acc') $ do nest' <- expandKernelNest pat_unused nest types <- asksScope scopeForSOACs addPostStms kernels let withacc = WithAccStm perm pat inputs lam stms <- (`runReaderT` types) $ simplifyStms =<< interchangeWithAcc nest' withacc onTopLevelStms stms return acc' _ -> addStmToAcc stm acc where num_accs = length inputs maybeDistributeStm (Let pat aux (Op (Screma w arrs form))) acc | Just [Reduce comm lam nes] <- isReduceSOAC form, Just m <- irwim pat w comm lam $ zip nes arrs = do types <- asksScope scopeForSOACs (_, stms) <- runBuilderT (auxing aux m) types distributeMapBodyStms acc stms -- Parallelise segmented scatters. maybeDistributeStm stm@(Let pat (StmAux cs _ _) (Op (Scatter w ivs lam as))) acc = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | Just (perm, pat_unused) <- permutationAndMissing pat res -> localScope (typeEnvFromDistAcc acc') $ do nest' <- expandKernelNest pat_unused nest lam' <- soacsLambda lam addPostStms kernels postStm =<< segmentedScatterKernel nest' perm pat cs w lam' ivs as return acc' _ -> addStmToAcc stm acc -- Parallelise segmented Hist. maybeDistributeStm stm@(Let pat (StmAux cs _ _) (Op (Hist w as ops lam))) acc = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | Just (perm, pat_unused) <- permutationAndMissing pat res -> localScope (typeEnvFromDistAcc acc') $ do lam' <- soacsLambda lam nest' <- expandKernelNest pat_unused nest addPostStms kernels postStm =<< segmentedHistKernel nest' perm cs w ops lam' as return acc' _ -> addStmToAcc stm acc -- Parallelise Index slices if the result is going to be returned -- directly from the kernel. This is because we would otherwise have -- to sequentialise writing the result, which may be costly. maybeDistributeStm stm@(Let (Pat [pe]) aux (BasicOp (Index arr slice))) acc | not $ null $ sliceDims slice, Var (patElemName pe) `elem` map resSubExp (snd (innerTarget (distTargets acc))) = distributeSingleStm acc stm >>= \case Just (kernels, _res, nest, acc') -> localScope (typeEnvFromDistAcc acc') $ do addPostStms kernels postStm =<< segmentedGatherKernel nest (stmAuxCerts aux) arr slice return acc' _ -> addStmToAcc stm acc -- If the scan can be distributed by itself, we will turn it into a -- segmented scan. -- -- If the scan cannot be distributed by itself, it will be -- sequentialised in the default case for this function. maybeDistributeStm stm@(Let pat (StmAux cs _ _) (Op (Screma w arrs form))) acc | Just (scans, map_lam) <- isScanomapSOAC form, Scan lam nes <- singleScan scans = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | Just (perm, pat_unused) <- permutationAndMissing pat res -> -- We need to pretend pat_unused was used anyway, by adding -- it to the kernel nest. localScope (typeEnvFromDistAcc acc') $ do nest' <- expandKernelNest pat_unused nest map_lam' <- soacsLambda map_lam localScope (typeEnvFromDistAcc acc') $ segmentedScanomapKernel nest' perm cs w lam map_lam' nes arrs >>= kernelOrNot mempty stm acc kernels acc' _ -> addStmToAcc stm acc -- If the map function of the reduction contains parallelism we split -- it, so that the parallelism can be exploited. maybeDistributeStm (Let pat aux (Op (Screma w arrs form))) acc | Just (reds, map_lam) <- isRedomapSOAC form, lambdaContainsParallelism map_lam = do (mapstm, redstm) <- redomapToMapAndReduce pat (w, reds, map_lam, arrs) distributeMapBodyStms acc $ oneStm mapstm {stmAux = aux} <> oneStm redstm -- if the reduction can be distributed by itself, we will turn it into a -- segmented reduce. -- -- If the reduction cannot be distributed by itself, it will be -- sequentialised in the default case for this function. maybeDistributeStm stm@(Let pat (StmAux cs _ _) (Op (Screma w arrs form))) acc | Just (reds, map_lam) <- isRedomapSOAC form, Reduce comm lam nes <- singleReduce reds = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | Just (perm, pat_unused) <- permutationAndMissing pat res -> -- We need to pretend pat_unused was used anyway, by adding -- it to the kernel nest. localScope (typeEnvFromDistAcc acc') $ do nest' <- expandKernelNest pat_unused nest lam' <- soacsLambda lam map_lam' <- soacsLambda map_lam let comm' | commutativeLambda lam = Commutative | otherwise = comm regularSegmentedRedomapKernel nest' perm cs w comm' lam' map_lam' nes arrs >>= kernelOrNot mempty stm acc kernels acc' _ -> addStmToAcc stm acc maybeDistributeStm (Let pat (StmAux cs _ _) (Op (Screma w arrs form))) acc = do -- This Screma is too complicated for us to immediately do -- anything, so split it up and try again. scope <- asksScope scopeForSOACs distributeMapBodyStms acc . fmap (certify cs) . snd =<< runBuilderT (dissectScrema pat w form arrs) scope maybeDistributeStm (Let pat aux (BasicOp (Replicate (Shape (d : ds)) v))) acc | [t] <- patTypes pat = do tmp <- newVName "tmp" let rowt = rowType t newstm = Let pat aux $ Op $ Screma d [] $ mapSOAC lam tmpstm = Let (Pat [PatElem tmp rowt]) aux $ BasicOp $ Replicate (Shape ds) v lam = Lambda { lambdaReturnType = [rowt], lambdaParams = [], lambdaBody = mkBody (oneStm tmpstm) [varRes tmp] } maybeDistributeStm newstm acc maybeDistributeStm stm@(Let _ aux (BasicOp (Copy stm_arr))) acc = distributeSingleUnaryStm acc stm stm_arr $ \_ outerpat arr -> return $ oneStm $ Let outerpat aux $ BasicOp $ Copy arr -- Opaques are applied to the full array, because otherwise they can -- drastically inhibit parallelisation in some cases. maybeDistributeStm stm@(Let (Pat [pe]) aux (BasicOp (Opaque _ (Var stm_arr)))) acc | not $ primType $ typeOf pe = distributeSingleUnaryStm acc stm stm_arr $ \_ outerpat arr -> return $ oneStm $ Let outerpat aux $ BasicOp $ Copy arr maybeDistributeStm stm@(Let _ aux (BasicOp (Rearrange perm stm_arr))) acc = distributeSingleUnaryStm acc stm stm_arr $ \nest outerpat arr -> do let r = length (snd nest) + 1 perm' = [0 .. r -1] ++ map (+ r) perm -- We need to add a copy, because the original map nest -- will have produced an array without aliases, and so must we. arr' <- newVName $ baseString arr arr_t <- lookupType arr return $ stmsFromList [ Let (Pat [PatElem arr' arr_t]) aux $ BasicOp $ Copy arr, Let outerpat aux $ BasicOp $ Rearrange perm' arr' ] maybeDistributeStm stm@(Let _ aux (BasicOp (Reshape reshape stm_arr))) acc = distributeSingleUnaryStm acc stm stm_arr $ \nest outerpat arr -> do let reshape' = map DimNew (kernelNestWidths nest) ++ map DimNew (newDims reshape) return $ oneStm $ Let outerpat aux $ BasicOp $ Reshape reshape' arr maybeDistributeStm stm@(Let _ aux (BasicOp (Rotate rots stm_arr))) acc = distributeSingleUnaryStm acc stm stm_arr $ \nest outerpat arr -> do let rots' = map (const $ intConst Int64 0) (kernelNestWidths nest) ++ rots return $ oneStm $ Let outerpat aux $ BasicOp $ Rotate rots' arr maybeDistributeStm stm@(Let pat aux (BasicOp (Update _ arr slice (Var v)))) acc | not $ null $ sliceDims slice = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | map resSubExp res == map Var (patNames $ stmPat stm), Just (perm, pat_unused) <- permutationAndMissing pat res -> do addPostStms kernels localScope (typeEnvFromDistAcc acc') $ do nest' <- expandKernelNest pat_unused nest postStm =<< segmentedUpdateKernel nest' perm (stmAuxCerts aux) arr slice v return acc' _ -> addStmToAcc stm acc maybeDistributeStm stm@(Let _ aux (BasicOp (Concat d (x :| xs) w))) acc = distributeSingleStm acc stm >>= \case Just (kernels, _, nest, acc') -> localScope (typeEnvFromDistAcc acc') $ segmentedConcat nest >>= kernelOrNot (stmAuxCerts aux) stm acc kernels acc' _ -> addStmToAcc stm acc where segmentedConcat nest = isSegmentedOp nest [0] mempty mempty [] (x : xs) $ \pat _ _ _ (x' : xs') -> let d' = d + length (snd nest) + 1 in addStm $ Let pat aux $ BasicOp $ Concat d' (x' :| xs') w maybeDistributeStm stm acc = addStmToAcc stm acc distributeSingleUnaryStm :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => DistAcc rep -> Stm SOACS -> VName -> (KernelNest -> Pat Type -> VName -> DistNestT rep m (Stms rep)) -> DistNestT rep m (DistAcc rep) distributeSingleUnaryStm acc stm stm_arr f = distributeSingleStm acc stm >>= \case Just (kernels, res, nest, acc') | map resSubExp res == map Var (patNames $ stmPat stm), (outer, _) <- nest, [(arr_p, arr)] <- loopNestingParamsAndArrs outer, boundInKernelNest nest `namesIntersection` freeIn stm == oneName (paramName arr_p), perfectlyMapped arr nest -> do addPostStms kernels let outerpat = loopNestingPat $ fst nest localScope (typeEnvFromDistAcc acc') $ do postStm =<< f nest outerpat arr return acc' _ -> addStmToAcc stm acc where perfectlyMapped arr (outer, nest) | [(p, arr')] <- loopNestingParamsAndArrs outer, arr == arr' = case nest of [] -> paramName p == stm_arr x : xs -> perfectlyMapped (paramName p) (x, xs) | otherwise = False distribute :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => DistAcc rep -> DistNestT rep m (DistAcc rep) distribute acc = fromMaybe acc <$> distributeIfPossible acc mkSegLevel :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => DistNestT rep m (MkSegLevel rep (DistNestT rep m)) mkSegLevel = do mk_lvl <- asks distSegLevel return $ \w desc r -> do (lvl, stms) <- lift $ liftInner $ runBuilderT' $ mk_lvl w desc r addStms stms return lvl distributeIfPossible :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => DistAcc rep -> DistNestT rep m (Maybe (DistAcc rep)) distributeIfPossible acc = do nest <- asks distNest mk_lvl <- mkSegLevel tryDistribute mk_lvl nest (distTargets acc) (distStms acc) >>= \case Nothing -> return Nothing Just (targets, kernel) -> do postStm kernel return $ Just DistAcc { distTargets = targets, distStms = mempty } distributeSingleStm :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => DistAcc rep -> Stm SOACS -> DistNestT rep m ( Maybe ( PostStms rep, Result, KernelNest, DistAcc rep ) ) distributeSingleStm acc stm = do nest <- asks distNest mk_lvl <- mkSegLevel tryDistribute mk_lvl nest (distTargets acc) (distStms acc) >>= \case Nothing -> return Nothing Just (targets, distributed_stms) -> tryDistributeStm nest targets stm >>= \case Nothing -> return Nothing Just (res, targets', new_kernel_nest) -> return $ Just ( PostStms distributed_stms, res, new_kernel_nest, DistAcc { distTargets = targets', distStms = mempty } ) segmentedScatterKernel :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => KernelNest -> [Int] -> Pat Type -> Certs -> SubExp -> Lambda rep -> [VName] -> [(Shape, Int, VName)] -> DistNestT rep m (Stms rep) segmentedScatterKernel nest perm scatter_pat cs scatter_w lam ivs dests = do -- We replicate some of the checking done by 'isSegmentedOp', but -- things are different because a scatter is not a reduction or -- scan. -- -- First, pretend that the scatter is also part of the nesting. The -- KernelNest we produce here is technically not sensible, but it's -- good enough for flatKernel to work. let nesting = MapNesting scatter_pat (StmAux cs mempty ()) scatter_w $ zip (lambdaParams lam) ivs nest' = pushInnerKernelNesting (scatter_pat, bodyResult $ lambdaBody lam) nesting nest (ispace, kernel_inps) <- flatKernel nest' let (as_ws, as_ns, as) = unzip3 dests indexes = zipWith (*) as_ns $ map length as_ws -- The input/output arrays ('as') _must_ correspond to some kernel -- input, or else the original nested scatter would have been -- ill-typed. Find them. as_inps <- mapM (findInput kernel_inps) as mk_lvl <- mkSegLevel let rts = concatMap (take 1) $ chunks as_ns $ drop (sum indexes) $ lambdaReturnType lam (is, vs) = splitAt (sum indexes) $ bodyResult $ lambdaBody lam (is', k_body_stms) <- runBuilder $ do addStms $ bodyStms $ lambdaBody lam pure is let k_body = groupScatterResults (zip3 as_ws as_ns as_inps) (is' ++ vs) & map (inPlaceReturn ispace) & KernelBody () k_body_stms -- Remove unused kernel inputs, since some of these might -- reference the array we are scattering into. kernel_inps' = filter ((`nameIn` freeIn k_body) . kernelInputName) kernel_inps (k, k_stms) <- mapKernel mk_lvl ispace kernel_inps' rts k_body traverse renameStm <=< runBuilder_ $ do addStms k_stms let pat = Pat . rearrangeShape perm $ patElems $ loopNestingPat $ fst nest letBind pat $ Op $ segOp k where findInput kernel_inps a = maybe bad return $ find ((== a) . kernelInputName) kernel_inps bad = error "Ill-typed nested scatter encountered." inPlaceReturn ispace (aw, inp, is_vs) = WriteReturns ( foldMap (foldMap resCerts . fst) is_vs <> foldMap (resCerts . snd) is_vs ) (Shape (init ws ++ shapeDims aw)) (kernelInputArray inp) [ (Slice $ map DimFix $ map Var (init gtids) ++ map resSubExp is, resSubExp v) | (is, v) <- is_vs ] where (gtids, ws) = unzip ispace segmentedUpdateKernel :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => KernelNest -> [Int] -> Certs -> VName -> Slice SubExp -> VName -> DistNestT rep m (Stms rep) segmentedUpdateKernel nest perm cs arr slice v = do (base_ispace, kernel_inps) <- flatKernel nest let slice_dims = sliceDims slice slice_gtids <- replicateM (length slice_dims) (newVName "gtid_slice") let ispace = base_ispace ++ zip slice_gtids slice_dims ((res_t, res), kstms) <- runBuilder $ do -- Compute indexes into full array. v' <- certifying cs $ letSubExp "v" $ BasicOp $ Index v $ Slice $ map (DimFix . Var) slice_gtids slice_is <- traverse (toSubExp "index") $ fixSlice (fmap pe64 slice) $ map (pe64 . Var) slice_gtids let write_is = map (Var . fst) base_ispace ++ slice_is arr' = maybe (error "incorrectly typed Update") kernelInputArray $ find ((== arr) . kernelInputName) kernel_inps arr_t <- lookupType arr' v_t <- subExpType v' return ( v_t, WriteReturns mempty (arrayShape arr_t) arr' [(Slice $ map DimFix write_is, v')] ) -- Remove unused kernel inputs, since some of these might -- reference the array we are scattering into. let kernel_inps' = filter ((`nameIn` (freeIn kstms <> freeIn res)) . kernelInputName) kernel_inps mk_lvl <- mkSegLevel (k, prestms) <- mapKernel mk_lvl ispace kernel_inps' [res_t] $ KernelBody () kstms [res] traverse renameStm <=< runBuilder_ $ do addStms prestms let pat = Pat . rearrangeShape perm $ patElems $ loopNestingPat $ fst nest letBind pat $ Op $ segOp k segmentedGatherKernel :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => KernelNest -> Certs -> VName -> Slice SubExp -> DistNestT rep m (Stms rep) segmentedGatherKernel nest cs arr slice = do let slice_dims = sliceDims slice slice_gtids <- replicateM (length slice_dims) (newVName "gtid_slice") (base_ispace, kernel_inps) <- flatKernel nest let ispace = base_ispace ++ zip slice_gtids slice_dims ((res_t, res), kstms) <- runBuilder $ do -- Compute indexes into full array. slice'' <- subExpSlice . sliceSlice (primExpSlice slice) $ primExpSlice $ Slice $ map (DimFix . Var) slice_gtids v' <- certifying cs $ letSubExp "v" $ BasicOp $ Index arr slice'' v_t <- subExpType v' return (v_t, Returns ResultMaySimplify mempty v') mk_lvl <- mkSegLevel (k, prestms) <- mapKernel mk_lvl ispace kernel_inps [res_t] $ KernelBody () kstms [res] traverse renameStm <=< runBuilder_ $ do addStms prestms let pat = Pat $ patElems $ loopNestingPat $ fst nest letBind pat $ Op $ segOp k segmentedHistKernel :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => KernelNest -> [Int] -> Certs -> SubExp -> [SOACS.HistOp SOACS] -> Lambda rep -> [VName] -> DistNestT rep m (Stms rep) segmentedHistKernel nest perm cs hist_w ops lam arrs = do -- We replicate some of the checking done by 'isSegmentedOp', but -- things are different because a Hist is not a reduction or -- scan. (ispace, inputs) <- flatKernel nest let orig_pat = Pat . rearrangeShape perm $ patElems $ loopNestingPat $ fst nest -- The input/output arrays _must_ correspond to some kernel input, -- or else the original nested Hist would have been ill-typed. -- Find them. ops' <- forM ops $ \(SOACS.HistOp num_bins rf dests nes op) -> SOACS.HistOp num_bins rf <$> mapM (fmap kernelInputArray . findInput inputs) dests <*> pure nes <*> pure op mk_lvl <- asks distSegLevel onLambda <- asks distOnSOACSLambda let onLambda' = fmap fst . runBuilder . onLambda liftInner $ runBuilderT'_ $ do -- It is important not to launch unnecessarily many threads for -- histograms, because it may mean we unnecessarily need to reduce -- subhistograms as well. lvl <- mk_lvl (hist_w : map snd ispace) "seghist" $ NoRecommendation SegNoVirt addStms =<< histKernel onLambda' lvl orig_pat ispace inputs cs hist_w ops' lam arrs where findInput kernel_inps a = maybe bad return $ find ((== a) . kernelInputName) kernel_inps bad = error "Ill-typed nested Hist encountered." histKernel :: (MonadBuilder m, DistRep (Rep m)) => (Lambda SOACS -> m (Lambda (Rep m))) -> SegOpLevel (Rep m) -> Pat Type -> [(VName, SubExp)] -> [KernelInput] -> Certs -> SubExp -> [SOACS.HistOp SOACS] -> Lambda (Rep m) -> [VName] -> m (Stms (Rep m)) histKernel onLambda lvl orig_pat ispace inputs cs hist_w ops lam arrs = runBuilderT'_ $ do ops' <- forM ops $ \(SOACS.HistOp dest_shape rf dests nes op) -> do (op', nes', shape) <- determineReduceOp op nes op'' <- lift $ onLambda op' return $ HistOp dest_shape rf dests nes' shape op'' let isDest = flip elem $ concatMap histDest ops' inputs' = filter (not . isDest . kernelInputArray) inputs certifying cs $ addStms =<< traverse renameStm =<< segHist lvl orig_pat hist_w ispace inputs' ops' lam arrs determineReduceOp :: MonadBuilder m => Lambda SOACS -> [SubExp] -> m (Lambda SOACS, [SubExp], Shape) determineReduceOp lam nes = -- FIXME? We are assuming that the accumulator is a replicate, and -- we fish out its value in a gross way. case mapM subExpVar nes of Just ne_vs' -> do let (shape, lam') = isVectorMap lam nes' <- forM ne_vs' $ \ne_v -> do ne_v_t <- lookupType ne_v letSubExp "hist_ne" $ BasicOp $ Index ne_v $ fullSlice ne_v_t $ replicate (shapeRank shape) $ DimFix $ intConst Int64 0 return (lam', nes', shape) Nothing -> return (lam, nes, mempty) isVectorMap :: Lambda SOACS -> (Shape, Lambda SOACS) isVectorMap lam | [Let (Pat pes) _ (Op (Screma w arrs form))] <- stmsToList $ bodyStms $ lambdaBody lam, map resSubExp (bodyResult (lambdaBody lam)) == map (Var . patElemName) pes, Just map_lam <- isMapSOAC form, arrs == map paramName (lambdaParams lam) = let (shape, lam') = isVectorMap map_lam in (Shape [w] <> shape, lam') | otherwise = (mempty, lam) segmentedScanomapKernel :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => KernelNest -> [Int] -> Certs -> SubExp -> Lambda SOACS -> Lambda rep -> [SubExp] -> [VName] -> DistNestT rep m (Maybe (Stms rep)) segmentedScanomapKernel nest perm cs segment_size lam map_lam nes arrs = do mk_lvl <- asks distSegLevel onLambda <- asks distOnSOACSLambda let onLambda' = fmap fst . runBuilder . onLambda isSegmentedOp nest perm (freeIn lam) (freeIn map_lam) nes [] $ \pat ispace inps nes' _ -> do (lam', nes'', shape) <- determineReduceOp lam nes' lam'' <- onLambda' lam' let scan_op = SegBinOp Noncommutative lam'' nes'' shape lvl <- mk_lvl (segment_size : map snd ispace) "segscan" $ NoRecommendation SegNoVirt addStms =<< traverse renameStm =<< segScan lvl pat cs segment_size [scan_op] map_lam arrs ispace inps regularSegmentedRedomapKernel :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => KernelNest -> [Int] -> Certs -> SubExp -> Commutativity -> Lambda rep -> Lambda rep -> [SubExp] -> [VName] -> DistNestT rep m (Maybe (Stms rep)) regularSegmentedRedomapKernel nest perm cs segment_size comm lam map_lam nes arrs = do mk_lvl <- asks distSegLevel isSegmentedOp nest perm (freeIn lam) (freeIn map_lam) nes [] $ \pat ispace inps nes' _ -> do let red_op = SegBinOp comm lam nes' mempty lvl <- mk_lvl (segment_size : map snd ispace) "segred" $ NoRecommendation SegNoVirt addStms =<< traverse renameStm =<< segRed lvl pat cs segment_size [red_op] map_lam arrs ispace inps isSegmentedOp :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => KernelNest -> [Int] -> Names -> Names -> [SubExp] -> [VName] -> ( Pat Type -> [(VName, SubExp)] -> [KernelInput] -> [SubExp] -> [VName] -> BuilderT rep m () ) -> DistNestT rep m (Maybe (Stms rep)) isSegmentedOp nest perm free_in_op _free_in_fold_op nes arrs m = runMaybeT $ do -- We must verify that array inputs to the operation are inputs to -- the outermost loop nesting or free in the loop nest. Nothing -- free in the op may be bound by the nest. Furthermore, the -- neutral elements must be free in the loop nest. -- -- We must summarise any names from free_in_op that are bound in the -- nest, and describe how to obtain them given segment indices. let bound_by_nest = boundInKernelNest nest (ispace, kernel_inps) <- flatKernel nest when (free_in_op `namesIntersect` bound_by_nest) $ fail "Non-fold lambda uses nest-bound parameters." let indices = map fst ispace prepareNe (Var v) | v `nameIn` bound_by_nest = fail "Neutral element bound in nest" prepareNe ne = return ne prepareArr arr = case find ((== arr) . kernelInputName) kernel_inps of Just inp | kernelInputIndices inp == map Var indices -> return $ return $ kernelInputArray inp Nothing | not (arr `nameIn` bound_by_nest) -> -- This input is something that is free inside -- the loop nesting. We will have to replicate -- it. return $ letExp (baseString arr ++ "_repd") (BasicOp $ Replicate (Shape $ map snd ispace) $ Var arr) _ -> fail "Input not free, perfectly mapped, or outermost." nes' <- mapM prepareNe nes mk_arrs <- mapM prepareArr arrs lift $ liftInner $ runBuilderT'_ $ do nested_arrs <- sequence mk_arrs let pat = Pat . rearrangeShape perm $ patElems $ loopNestingPat $ fst nest m pat ispace kernel_inps nes' nested_arrs permutationAndMissing :: Pat Type -> Result -> Maybe ([Int], [PatElem Type]) permutationAndMissing (Pat pes) res = do let (_used, unused) = partition ((`nameIn` freeIn res) . patElemName) pes res' = map resSubExp res res_expanded = res' ++ map (Var . patElemName) unused perm <- map (Var . patElemName) pes `isPermutationOf` res_expanded return (perm, unused) -- Add extra pattern elements to every kernel nesting level. expandKernelNest :: MonadFreshNames m => [PatElem Type] -> KernelNest -> m KernelNest expandKernelNest pes (outer_nest, inner_nests) = do let outer_size = loopNestingWidth outer_nest : map loopNestingWidth inner_nests inner_sizes = tails $ map loopNestingWidth inner_nests outer_nest' <- expandWith outer_nest outer_size inner_nests' <- zipWithM expandWith inner_nests inner_sizes return (outer_nest', inner_nests') where expandWith nest dims = do pes' <- mapM (expandPatElemWith dims) pes return nest { loopNestingPat = Pat $ patElems (loopNestingPat nest) <> pes' } expandPatElemWith dims pe = do name <- newVName $ baseString $ patElemName pe return pe { patElemName = name, patElemDec = patElemType pe `arrayOfShape` Shape dims } kernelOrNot :: (MonadFreshNames m, DistRep rep) => Certs -> Stm SOACS -> DistAcc rep -> PostStms rep -> DistAcc rep -> Maybe (Stms rep) -> DistNestT rep m (DistAcc rep) kernelOrNot cs stm acc _ _ Nothing = addStmToAcc (certify cs stm) acc kernelOrNot cs _ _ kernels acc' (Just stms) = do addPostStms kernels postStm $ fmap (certify cs) stms return acc' distributeMap :: (MonadFreshNames m, LocalScope rep m, DistRep rep) => MapLoop -> DistAcc rep -> DistNestT rep m (DistAcc rep) distributeMap (MapLoop pat aux w lam arrs) acc = distribute =<< mapNesting pat aux w lam arrs (distribute =<< distributeMapBodyStms acc' lam_stms) where acc' = DistAcc { distTargets = pushInnerTarget (pat, bodyResult $ lambdaBody lam) $ distTargets acc, distStms = mempty } lam_stms = bodyStms $ lambdaBody lam
diku-dk/futhark
src/Futhark/Pass/ExtractKernels/DistributeNests.hs
isc
42,586
0
23
11,273
13,195
6,533
6,662
-1
-1
module Phone (areaCode, number, prettyPrint) where import Data.Char import Control.Arrow isValid :: String -> String isValid xs | n < 10 = "0000000000" | n == 10 = xs | n == 11 && first == '1' = ret | n >= 11 = "0000000000" where ( first , ret ) = ( head &&& tail ) xs n = length xs number :: String -> String number = isValid . filter isDigit areaCode :: String -> String areaCode = take 3 . number prettyPrint :: String -> String prettyPrint = pretty . number where pretty :: String -> String pretty xs = "(" ++ xs' ++ ") " ++ ys' ++ "-" ++ ret' where ( xs', ret ) = splitAt 3 xs ( ys', ret' ) = splitAt 3 ret
mukeshtiwari/Excercism
haskell/phone-number/Phone.hs
mit
679
0
11
199
266
139
127
21
1
module ExLint.Example ( getExamples ) where import ExLint.Plugins (pluginForBlock) import ExLint.Types import Data.List (findIndex) import Data.Maybe (mapMaybe) import Data.Text (Text) import qualified Data.Text as T getExamples :: [Block a] -> [Example] getExamples = mapMaybe blockToExample blockToExample :: Block a -> Maybe Example blockToExample b@(BlockCode _ code) = pluginForBlock b >>= linesToExample (T.lines code) blockToExample _ = Nothing linesToExample :: [Text] -> Plugin -> Maybe Example linesToExample lns p = case findIndex (sigil `T.isPrefixOf`) $ lns of Just idx | idx /= 0 -> Just $ Example { examplePlugin = p , examplePreamble = T.unlines $ take (idx - 1) lns , exampleExpression = lns !! (idx - 1) , exampleResult = T.drop (T.length sigil + 1) $ lns !! idx } _ -> Nothing where sigil :: Text sigil = pluginSigil p
pbrisbin/ex-lint
src/ExLint/Example.hs
mit
958
0
18
252
322
174
148
25
2
module Code.Haskellbook.Record where import Data.List data OperatingSystem = GnuPlusLinux | OpenBSDPlusNevermindJustBSDStill | Mac | Windows deriving (Eq, Show, Enum) data ProgrammingLanguage = Haskell | Agda | Idris | PureScript deriving (Eq, Show, Enum) data Programmer = Programmer { os :: OperatingSystem , lang :: ProgrammingLanguage } deriving (Eq, Show) nineToFive :: Programmer nineToFive = Programmer { os = Mac, lang = Idris } -- You can iterate all enum values by referencing the first one, -- if the datatype is an instance of Enum allOperatingSystems :: [OperatingSystem] allOperatingSystems = [GnuPlusLinux ..] allProgrammingLanguages :: [ProgrammingLanguage] allProgrammingLanguages = [Haskell ..] allProgrammers :: [Programmer] allProgrammers = nub $ foldr (\(a,b) c -> Programmer a b : c) [] (comboOfN allOperatingSystems allProgrammingLanguages) -- get all combos of N lists of elements -- Modified from Combinatorial.hs comboOfN :: [a] -> [b] -> [(a, b)] comboOfN = (joinCombinations .) . makeCombinations where makeCombinations x y = zip (replicate (length y) x) y joinCombinations = concatMap $ \(xs, y) -> map (flip (,) y) xs
JoshuaGross/haskell-learning-log
Code/Haskellbook/Record.hs
mit
1,177
0
12
197
335
196
139
17
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Symmetry.Verify where import Symmetry.SymbEx import Symmetry.IL.AST import Symmetry.IL.Model (generateModel) import Symmetry.IL.ConfigInfo import Symmetry.IL.Model.HaskellModel (printHaskell,printQCFile) -- import Symmetry.IL.Unfold -- import Symmetry.IL.Inst -- import Symmetry.IL.TrailParser import System.Console.ANSI import Paths_checker import Control.Exception import Control.Monad import Control.Applicative import System.Exit import System.Directory import System.FilePath import System.IO import System.Process hiding (runCommand) import Text.Printf import Options import Text.PrettyPrint.Leijen (Pretty, pretty, prettyList, nest, text, (<>), line, hPutDoc) import qualified Data.Map.Strict as M import qualified Data.IntMap.Strict as IM data MainOptions = MainOptions { optVerify :: Bool , optQC :: Bool , optQCSamples :: Int , optVerbose :: Bool , optProcess :: Bool , optModel :: Bool , optDir :: String } instance Options MainOptions where defineOptions = MainOptions <$> simpleOption "verify" False "Run Verifier" <*> simpleOption "qc" False "Run QuickCheck instead of Verifier" <*> simpleOption "qc-samples" 1000 "Number of random initial states to explore" <*> simpleOption "verbose" False "Verbose Output" <*> simpleOption "dump-process" False "Display Intermediate Process Description" <*> simpleOption "dump-model" False "Dump Liquid Haskell model" <*> simpleOption "outdir" ".symcheck" "Directory to store intermediate results" runCmd :: Bool -> String -> FilePath -> CreateProcess -> IO Bool runCmd verb pre wd c = do (_,Just hout,Just herr,p) <- createProcess c { cwd = Just wd , std_out = CreatePipe , std_err = CreatePipe } when verb $ do setSGR [SetConsoleIntensity FaintIntensity] putStr (pre ++ "...") output <- hGetContents hout when (output /= "") $ putStr ("\n" ++ output) setSGR [Reset] b <- checkExit p herr when verb $ do setSGR [SetConsoleIntensity FaintIntensity] putStr "DONE.\n" setSGR [Reset] return b where checkExit x h = do e <- waitForProcess x case e of ExitSuccess -> return True _ -> do putStrLn =<< hGetContents h return False copyMapModule opt d = do let f' = if optQC opt then "SymMapQC.hs" else "SymMap.hs" f <- getDataFileName ("checker" </> "include" </> f') copyFile f (d </> "SymMap.hs") copyVectorModule opt d = do let f' = if optQC opt then "SymVectorQC.hs" else "SymVector.hs" f <- getDataFileName ("checker" </> "include" </> f') copyFile f (d </> "SymVector.hs") copyBoilerModule opt d = do let f' = if optQC opt then "SymBoilerPlateQC.hs" else "SymBoilerPlate.hs" f <- getDataFileName ("checker" </> "include" </> f') copyFile f (d </> "SymBoilerPlate.hs") copyWeb _ d = forM_ ["states.js", "states.html"] $ \f -> do f' <- fn f copyFile f' (d </> f) where fn f = getDataFileName ("checker" </> "include" </> f) copyIncludes opt d = mapM_ (\f -> f opt d) [ copyMapModule , copyVectorModule , copyBoilerModule , copyWeb ] runLiquid :: Bool -> FilePath -> FilePath -> IO Bool runLiquid verb fp cwd = runCmd verb "Running Verifier" cwd cmd where cmd = shell (printf "liquid %s" fp) runQC :: Bool -> FilePath -> FilePath -> IO Bool runQC verb fp cwd = runCmd verb "Running QuickCheck" cwd cmd where cmd = shell (printf "runghc %s" fp) copyOtherQCIncludes d = forM_ fns $ \fn -> do f <- getDataFileName ("checker" </> "include" </> fn) copyFile f (d </> fn) where fns = ["SymQCTH.hs", "TargetClient.hs"] runVerifier opt outd | optVerify opt && optQC opt = runQC (optVerbose opt) (outd </> "QC.hs") outd | optVerify opt = runLiquid (optVerbose opt) (outd </> "SymVerify.hs") outd | otherwise = return True instance (Pretty v) => Pretty (IM.IntMap v) where pretty m = pretty (IM.toList m) hd (h:_) = h hd _ = error "empty list given to hd" run1Cfg :: MainOptions -> FilePath -> Config () -> IO Bool run1Cfg opt outd conf = do when (optProcess opt) $ pprint (config cinfo) when (optModel opt) $ do createDirectoryIfMissing True outd copyIncludes opt outd writeFile (outd </> "SymVerify.hs") f when (optQC opt) (do -- let cfgList = (cfg cinfo') -- hPutDoc stdout $ pretty cfgList -- putStrLn "" -- hPutDoc stdout $ prettyList $ map (\(p, ss) -> (p, maximum (IM.keys ss))) cfgList -- return () writeFile (outd </> "QC.hs") (printQCFile cinfo' m) copyOtherQCIncludes outd) runVerifier opt outd where cinfo :: ConfigInfo (PredAnnot Int) (cinfo, m) = generateModel conf cinfo' = cinfo { isQC = optQC opt , qcSamples = optQCSamples opt} f = printHaskell cinfo' m pprint c = print $ text "Config" <> nest 2 (line <> pretty c) report status = if not status then do setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Vivid Red] putStr "UNSAFE" setSGR [Reset] putStr "\n" else do setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Vivid Green] putStr "SAFE" setSGR [Reset] putStr "\n" checkerMain :: SymbEx () -> IO () checkerMain main = runCommand $ \opts _ -> do d <- getCurrentDirectory let dir = optDir opts outd = d </> dir optsImplied = opts { optModel = optModel opts || optVerify opts } es <- forM cfgs $ run1Cfg optsImplied outd let status = and es when (optVerify opts) $ report status unless status exitFailure exitSuccess where cfgs = stateToConfigs . runSymb $ main type IdStmtMap = M.Map Int (Stmt Int) flattenStmt :: Stmt a -> [Stmt a] flattenStmt s@(Block l _) = s : (concatMap flattenStmt l) flattenStmt s@(Iter _ _ s' _) = s : (flattenStmt s') flattenStmt s@(Loop _ s' _) = s : (flattenStmt s') flattenStmt s@(Choose _ _ s' _) = s : (flattenStmt s') flattenStmt s@(Case _ _ _ sl sr _) = s : (concatMap flattenStmt [sl,sr]) flattenStmt s@(NonDet l _) = s : (concatMap flattenStmt l) flattenStmt s = [s] buildIdStmtMap :: Config Int -> IdStmtMap buildIdStmtMap (Config { cProcs = ps }) = let pairs = [ (annot s,s) | (pid,main_s) <- ps, s <- (flattenStmt main_s) ] in M.fromList pairs dangerZone :: String -> IO () dangerZone str = do setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Vivid Red] putStr str setSGR [Reset] putStr "\n"
gokhankici/symmetry
checker/src/Symmetry/Verify.hs
mit
7,757
0
16
2,693
2,200
1,102
1,098
179
2
module Data.PTree.Internal ( PTree(..) , Key , ChildKey , Children ) where import qualified Data.ByteString as S import qualified Data.IntMap as IM {-------------------------------------------------------------------- Types --------------------------------------------------------------------} -- | A map of ByteStrings to values. data PTree a = Nil | Node {-# UNPACK #-} !Key (Maybe a) !(Children a) -- | The key type for PTrees. type Key = S.ByteString type ChildKey = IM.Key type Children a = IM.IntMap (PTree a)
cpettitt/haskell-ptree
Data/PTree/Internal.hs
mit
559
0
9
113
110
69
41
14
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Rpi (Program, applyRpiMessage, defaultProgram) where import Control.Lens import Data.Int import Data.List import Data.Maybe import Data.Text.Lens import qualified Sound.OSC as OSC data Program = Program { _lightLevel:: Float , _program :: String } defaultProgram :: Program defaultProgram = Program { _lightLevel = 0 , _program = "lit" } data Message = ProgramMessage { _newProgram :: String } | LightLevelMessage { _newLightLevel :: Float } | EmptyMessage programAddress = "/rpi/program" lightLevelAddress = "/rpi/lightLevel" -- Lenses makeLenses ''Program makePrisms ''Message applyRpiMessage :: OSC.Message -> Program -> (Program, [OSC.Message]) applyRpiMessage (OSC.Message a datum) program = let message = parseMessage a datum in (setter message program, createMessages message) parseMessage :: String -> [OSC.Datum] -> Message parseMessage address datum | programAddress `isPrefixOf` address = ProgramMessage { _newProgram = OSC.ascii_to_string $ firstValue datum } | lightLevelAddress `isPrefixOf` address = LightLevelMessage { _newLightLevel = firstValue datum } | otherwise = EmptyMessage setter :: Message -> Program -> Program setter ProgramMessage { _newProgram=program_ } = set program program_ setter LightLevelMessage { _newLightLevel=lightLevel_ } = set lightLevel lightLevel_ setter EmptyMessage = programId programId :: Program -> Program programId program = program createMessages :: Message -> [OSC.Message] createMessages ProgramMessage { _newProgram=program_ } = [OSC.Message "/rpi/program" [OSC.d_put (OSC.ascii program_)]] createMessages LightLevelMessage { _newLightLevel=lightLevel_ } = [OSC.Message "/rpi/lightLevel" [OSC.d_put lightLevel_]] createMessages EmptyMessage = [] -- Utils firstValue :: OSC.Datem a => [OSC.Datum] -> a firstValue datum = fromJust $ OSC.d_get $ head datum
ulyssesp/haskell-avsyn
Rpi.hs
mit
2,049
0
11
403
549
298
251
44
1
module Y2016.M12.D14.Exercise where import Data.Complex -- import available via 1HaskellADay git repository import Data.Matrix {-- I'm thinking about quantum computation. IBM has released a 5-qubit computer for public experimentation. So, let's experiment. One way to go about that is to dive right in, so, yes, if you wish: dive right in. Another approach is to comprehend the maths behind quantum computation. So, let's look at that. I was going to bewail that Shor's prime factors algorithm needs 7 qubits to work, but, NEWSFLASH! IBM has added Shor's algorithm to their API, so ... CANCEL BEWAILMENT. *ahem* Moving on. First, let's look at qubits. Qubits are 'bra-ket'ted numbers (ket numbers) with the representation |0> = | 1 | or |1> = | 0 | | 0 | | 1 | OOH! MATRICES! exercise 1. Represent ket0 and ket1 states as matrices in Haskell --} type Qubit = Matrix (Complex Float) --- where Float is 1 or 0 but okay ket0, ket1 :: Qubit ket0 = undefined ket1 = undefined {-- It MAY be helpful to have a show-instance of a qubit that abbreviates the complex number to something more presentable. Your choice. A qubit state is most-times in a super-position of |0> or |1> and we represent that as |ψ> = α|0> + β|1> And we KNOW that |α|² + |β|² = 1 YAY! Okay. Whatever. So, we have a qubit at |0>-state and we want to flip it to |1>-state, or vice versa. How do we do that? We put it through a Pauli X gate The Pauli X operator is = | 0 1 | | 1 0 | That is to say, zero goes to 1 and 1 goes to zero. excercise 2: represent the Pauli X, Y, and Z operators --} type PauliOperator = Matrix (Complex Float) pauliX, pauliY, pauliZ :: PauliOperator pauliX = undefined pauliY = undefined pauliZ = undefined -- exercise 3: rotate the qubits ket0 and ket1 through the pauliX operator -- (figure out what that means). The intended result is: -- X|0> = |1> and X|1> = |0> -- what are your results? rotate :: PauliOperator -> Qubit -> Qubit rotate p q = undefined
geophf/1HaskellADay
exercises/HAD/Y2016/M12/D14/Exercise.hs
mit
2,046
0
7
452
120
75
45
14
1
-- | Minimalistic configuration reader using environment variables. -- -- Based on the 'Maybe' monad, which means that failures are represented by a -- lonesome 'Nothing'. module Config.Env.Util ( ConfigReader , runConfigReader , env , env' , read , envRead , envBS , withDef , opt ) where import Control.Monad.Trans.Class import Control.Monad.Trans.Maybe import qualified Text.Read as TR import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS8 import Data.Text (Text) import qualified Data.Text as T import System.Environment import Util -- ---------------------------------------------- -- | The configuration reader type. type ConfigReader = MaybeT IO -- | Run the configuration reader. runConfigReader :: ConfigReader cfg -> IO (Maybe cfg) runConfigReader = runMaybeT -- ---------------------------------------------- -- | Read an environment variable with this name. env :: Text -> ConfigReader Text env = env' (return . T.pack) -- | Read an environment variable with that name -- and convert the result with the given function. env' :: (String -> ConfigReader b) -> Text -> ConfigReader b env' valToMaybeT key = do val <- lift (lookupEnv (T.unpack key)) >>= liftMaybe valToMaybeT val -- XXX: silently defaults if parsing fails -- | Lift the reader result to a 'Maybe'. opt :: (Text -> ConfigReader a) -> Text -> ConfigReader (Maybe a) opt f t = return <$> f t -- | Read an environment variable as a 'ByteString'. envBS :: Text -> ConfigReader ByteString envBS = env' (return . BS8.pack) -- | Read an environment variable and convert the result to the desired type -- using its 'Read' instance. -- -- /Note/: Non-'Read'able types will fail. This cannot be used for conversion -- of string types. See 'TR.readEither'. envRead :: Read b => Text -> ConfigReader b envRead = env' (liftMaybe . eitherToMaybe . TR.readEither) -- ---------------------------------------------- -- | Lift me up. liftMaybe :: (Monad m) => Maybe a -> MaybeT m a liftMaybe = MaybeT . return -- | With default combinator, e.g. -- -- @env \"URL\" `withDef` \"www.google.com\"@ withDef :: ConfigReader a -> a -> ConfigReader a withDef m def = lift $ runMaybeT m >>= \val -> case val of Just v -> return v Nothing -> return def
UlfS/ghmm
src/Config/Env/Util.hs
mit
2,425
0
14
551
484
270
214
41
2
{-# OPTIONS_GHC -fwarn-unused-matches -fwarn-incomplete-patterns -fwarn-type-defaults #-} module FrontEnd.Syn.Traverse where import Control.Monad.Writer import Util.Std import qualified Data.Set as Set import qualified Data.Traversable as T import FrontEnd.HsSyn import FrontEnd.SrcLoc import Name.Name import Support.FreeVars import Util.Inst() instance FreeVars HsType (Set.Set Name) where freeVars t = execWriter (f t) where f (HsTyVar v) = tell (Set.singleton $ toName TypeVal v) f (HsTyCon v) = tell (Set.singleton $ toName TypeConstructor v) f t = traverseHsType_ f t traverse_ :: Applicative m => (a -> m b) -> a -> m a traverse_ fn x = fn x *> pure x traverseHsExp_ :: (Monad m,Applicative m,MonadSetSrcLoc m) => (HsExp -> m ()) -> HsExp -> m () traverseHsExp_ fn e = traverseHsExp (traverse_ fn) e *> pure () traverseHsExp :: (Monad m,MonadSetSrcLoc m,TraverseHsOps e) => (HsExp -> m HsExp) -> e -> m e traverseHsExp fn e = traverseHsOps ops e where ops = (hsOpsDefault ops) { opHsExp, opHsPat, opHsType } where opHsExp e = fn e opHsPat p = return p opHsType t = return t traverseHsType_ :: Applicative m => (HsType -> m b) -> HsType -> m () traverseHsType_ fn p = traverseHsType (traverse_ fn) p *> pure () traverseHsType :: Applicative m => (HsType -> m HsType) -> HsType -> m HsType traverseHsType fn t = f t where f (HsTyFun a1 a2) = HsTyFun <$> fn a1 <*> fn a2 f (HsTyTuple a1) = HsTyTuple <$> T.traverse fn a1 f (HsTyUnboxedTuple a1) = HsTyUnboxedTuple <$> T.traverse fn a1 f (HsTyApp a1 a2) = HsTyApp <$> fn a1 <*> fn a2 f (HsTyForall vs qt) = doQual HsTyForall f vs qt f (HsTyExists vs qt) = doQual HsTyExists f vs qt f x@HsTyVar {} = pure x f x@HsTyCon {} = pure x f HsTyExpKind { .. } = h <$> T.traverse fn hsTyLType where h hsTyLType = HsTyExpKind { .. } -- f HsTyExpKind { .. } = do -- hsTyLType <- T.mapM f hsTyLType -- return HsTyExpKind { .. } f (HsTyEq a1 a2) = HsTyEq <$> fn a1 <*> fn a2 --f (HsTyEq a b) = return HsTyEq `ap` f a `ap` f b f (HsTyStrictType a1 a2) = HsTyStrictType <$> pure a1 <*> T.traverse fn a2 -- f (HsTyStrictType a b ) = return HsTyStrictType `ap` return a `ap` T.mapM f b f HsTyAssoc = pure HsTyAssoc doQual :: Applicative m => (a -> HsQualType -> b) -> (HsType -> m HsType) -> a -> HsQualType -> m b doQual hsTyForall f vs qt = cr <$> cntx <*> f (hsQualTypeType qt) where cr cntx x = hsTyForall vs qt { hsQualTypeContext = cntx, hsQualTypeType = x } cntx = flip T.traverse (hsQualTypeContext qt) $ \v -> case v of x@HsAsst {} -> pure x HsAsstEq a b -> HsAsstEq <$> f a <*> f b -- return $ hsTyForall vs qt { hsQualTypeContext = cntx, hsQualTypeType = x } traverseHsPat_ :: (Monad m,Applicative m,MonadSetSrcLoc m) => (HsPat -> m b) -> HsPat -> m () traverseHsPat_ fn p = traverseHsPat (traverse_ fn) p *> pure () traverseHsPat :: (Monad m,MonadSetSrcLoc m,TraverseHsOps e) => (HsPat -> m HsPat) -> e -> m e traverseHsPat fn e = traverseHsOps ops e where ops = (hsOpsDefault ops) { opHsPat, opHsType } where opHsPat p = fn p opHsType t = return t traverseHsDeclHsExp :: (Monad m,MonadSetSrcLoc m) => (HsExp -> m HsExp) -> HsDecl -> m HsDecl traverseHsDeclHsExp fn d = traverseHsExp fn d getNamesFromHsPat :: HsPat -> [Name] getNamesFromHsPat p = execWriter (getNamesFromPat p) where getNamesFromPat (HsPVar hsName) = tell [hsName] getNamesFromPat (HsPAsPat hsName hsPat) = do tell [hsName] getNamesFromPat hsPat getNamesFromPat (HsPatExp e) = f e where f (HsVar v) = do tell [v] f (HsAsPat v e) = do tell [v] f e f e = traverseHsExp_ f e getNamesFromPat p = traverseHsPat_ getNamesFromPat p data HsOps m = HsOps { opHsDecl :: HsDecl -> m HsDecl, opHsExp :: HsExp -> m HsExp, opHsPat :: HsPat -> m HsPat, opHsType :: HsType -> m HsType, opHsStmt :: HsStmt -> m HsStmt } -- | provides a default hsOps that recurses further down the tree for undeclared -- operations. In order to tie the knot properly, you need to pass its return -- value into itself, as in. -- -- let ops = (hsOpsDefault ops) { opHsType = custom type handler } -- -- NOTE: if you forget the parentheses around hsopsdefault ops, your program -- will still typecheck and compile, but it will behave incorrectly. hsOpsDefault :: (Applicative m, MonadSetSrcLoc m) => HsOps m -> HsOps m hsOpsDefault hops = HsOps { .. } where f x = traverseHsOps hops x opHsDecl = f opHsExp = f opHsPat = f opHsStmt = f opHsType = f class TraverseHsOps a where -- act on the direct children of the argument. traverseHsOps :: (Applicative m,MonadSetSrcLoc m) => HsOps m -> a -> m a -- act on the argument itself or its children. applyHsOps :: (Applicative m,MonadSetSrcLoc m) => HsOps m -> a -> m a applyHsOps os x = traverseHsOps os x instance TraverseHsOps HsAlt where traverseHsOps ops@HsOps { .. } (HsAlt sl p rhs ds) = HsAlt sl <$> opHsPat p <*> applyHsOps ops rhs <*> T.traverse opHsDecl ds instance TraverseHsOps HsModule where traverseHsOps HsOps { .. } HsModule { .. } = cr <$> T.traverse opHsDecl hsModuleDecls where cr hsModuleDecls = HsModule { .. } instance TraverseHsOps HsType where applyHsOps = opHsType traverseHsOps HsOps { .. } = traverseHsType opHsType instance TraverseHsOps HsDecl where applyHsOps = opHsDecl traverseHsOps hops@HsOps { .. } x = g x where thops x = applyHsOps hops x g x = withSrcLoc (srcLoc x) $ f x f HsTypeFamilyDecl { .. } = h <$> thops hsDeclTArgs where h hsDeclTArgs = HsTypeFamilyDecl { .. } f HsTypeDecl { .. } = h <$> thops hsDeclTArgs <*> thops hsDeclType where h hsDeclTArgs hsDeclType = HsTypeDecl { .. } f HsDefaultDecl { .. } = h <$> thops hsDeclType where h hsDeclType = HsDefaultDecl { .. } f HsDataDecl { .. } = h <$> thops hsDeclContext <*> thops hsDeclCons where h hsDeclContext hsDeclCons = HsDataDecl { .. } f HsClassDecl { .. } = h <$> thops hsDeclClassHead <*> thops hsDeclDecls where h hsDeclClassHead hsDeclDecls = HsClassDecl { .. } f HsClassAliasDecl { .. } = h <$> thops hsDeclTypeArgs <*> thops hsDeclContext <*> thops hsDeclClasses <*> thops hsDeclDecls where h hsDeclTypeArgs hsDeclContext hsDeclClasses hsDeclDecls = HsClassAliasDecl { .. } f HsInstDecl { .. } = h <$> thops hsDeclClassHead <*> thops hsDeclDecls where h hsDeclClassHead hsDeclDecls = HsInstDecl { .. } f HsTypeSig { .. } = h <$> thops hsDeclQualType where h hsDeclQualType = HsTypeSig { .. } f HsActionDecl { .. } = h <$> thops hsDeclPat <*> thops hsDeclExp where h hsDeclPat hsDeclExp = HsActionDecl { .. } f (HsFunBind ms) = HsFunBind <$> thops ms f HsPatBind { .. } = h <$> thops hsDeclPat <*> thops hsDeclRhs <*> thops hsDeclDecls where h hsDeclPat hsDeclRhs hsDeclDecls = HsPatBind { .. } f HsSpaceDecl { .. } = dr <$> opHsExp hsDeclExp <*> thops hsDeclQualType where dr hsDeclExp hsDeclQualType = HsSpaceDecl { .. } f HsForeignDecl { .. } = dr <$> thops hsDeclQualType where dr hsDeclQualType = HsForeignDecl { .. } f HsForeignExport { .. } = dr <$> thops hsDeclQualType where dr hsDeclQualType = HsForeignExport { .. } f HsDeclDeriving { .. } = dr <$> thops hsDeclClassHead where dr hsDeclClassHead = HsDeclDeriving { .. } f x@HsInfixDecl {} = pure x f x@HsPragmaProps {} = pure x f (HsPragmaRules rs) = HsPragmaRules <$> thops rs f HsPragmaSpecialize { .. } = dr <$> thops hsDeclType where dr hsDeclType = HsPragmaSpecialize { .. } instance TraverseHsOps HsRule where traverseHsOps hops HsRule { .. } = hr <$> ah hsRuleLeftExpr <*> ah hsRuleRightExpr <*> f hsRuleFreeVars where --f xs = T.traverse (T.traverse (T.traverse ah)) xs f xs = applyHsOps hops xs hr hsRuleLeftExpr hsRuleRightExpr hsRuleFreeVars = HsRule { .. } ah x = applyHsOps hops x instance TraverseHsOps HsClassHead where traverseHsOps hops HsClassHead { .. } = mch <$> applyHsOps hops hsClassHeadContext <*> applyHsOps hops hsClassHeadArgs where mch hsClassHeadContext hsClassHeadArgs = HsClassHead { .. } instance TraverseHsOps HsMatch where traverseHsOps hops m = withSrcLoc (hsMatchSrcLoc m) $ f m where f HsMatch { .. } = h <$> thops hsMatchPats <*> thops hsMatchRhs <*> thops hsMatchDecls where h hsMatchPats hsMatchRhs hsMatchDecls = HsMatch { .. } thops x = applyHsOps hops x instance TraverseHsOps HsConDecl where traverseHsOps hops d = withSrcLoc (srcLoc d) $ f d where thops x = applyHsOps hops x f HsConDecl { .. } = h <$> thops hsConDeclConArg where h hsConDeclConArg = HsConDecl { .. } f HsRecDecl { .. } = h <$> thops hsConDeclRecArg where h hsConDeclRecArg = HsRecDecl { .. } instance TraverseHsOps HsPat where applyHsOps ho x = opHsPat ho x traverseHsOps hops@HsOps { .. } x = f x where fn x = applyHsOps hops x f (HsPTypeSig sl p qt) = HsPTypeSig sl <$> fn p <*> fn qt f p@HsPVar {} = pure p f p@HsPLit {} = pure p f (HsPNeg a1) = HsPNeg <$> fn a1 f (HsPInfixApp a1 a2 a3) = HsPInfixApp <$> fn a1 <*> pure a2 <*> fn a3 f (HsPApp d1 a1) = HsPApp d1 <$> fn a1 f (HsPTuple a1) = HsPTuple <$> fn a1 f (HsPUnboxedTuple a1) = HsPUnboxedTuple <$> fn a1 f (HsPList a1) = HsPList <$> fn a1 f (HsPParen a1) = HsPParen <$> fn a1 f (HsPAsPat d1 a1) = HsPAsPat d1 <$> fn a1 f HsPWildCard = pure HsPWildCard f (HsPIrrPat a1) = HsPIrrPat <$> fn a1 f (HsPBangPat a1) = HsPBangPat <$> fn a1 f (HsPRec d1 a1) = HsPRec d1 <$> fn a1 f (HsPatExp e) = HsPatExp <$> fn e f (HsPatWords ws) = HsPatWords <$> fn ws f (HsPatBackTick ws) = HsPatBackTick <$> fn ws instance TraverseHsOps HsQualType where traverseHsOps hops HsQualType { .. } = h <$> applyHsOps hops hsQualTypeContext <*> applyHsOps hops hsQualTypeType where h hsQualTypeContext hsQualTypeType = HsQualType { .. } -- traverseHsOps hops HsQualType { .. } = do -- hsQualTypeContext <- applyHsOps hops hsQualTypeContext -- hsQualTypeType <- opHsType hops hsQualTypeType -- return HsQualType { .. } instance TraverseHsOps HsAsst where traverseHsOps HsOps { .. } (HsAsstEq a b) = HsAsstEq <$> opHsType a <*> opHsType b traverseHsOps _ x = pure x instance TraverseHsOps HsComp where traverseHsOps ops HsComp { .. } = h <$> applyHsOps ops hsCompStmts <*> applyHsOps ops hsCompBody where h hsCompStmts hsCompBody = HsComp { .. } instance TraverseHsOps HsRhs where traverseHsOps ops (HsUnGuardedRhs rhs) = HsUnGuardedRhs <$> applyHsOps ops rhs traverseHsOps ops (HsGuardedRhss rhss) = HsGuardedRhss <$> applyHsOps ops rhss instance TraverseHsOps HsStmt where applyHsOps = opHsStmt traverseHsOps hops@HsOps { .. } x = f x where f (HsGenerator sl p e) = withSrcLoc sl $ HsGenerator sl <$> opHsPat p <*> opHsExp e f (HsQualifier e) = HsQualifier <$> opHsExp e f (HsLetStmt dl) = HsLetStmt <$> applyHsOps hops dl instance TraverseHsOps HsExp where applyHsOps = opHsExp traverseHsOps hops@HsOps { .. } e = g e where fn x = applyHsOps hops x g e = withSrcLoc (srcLoc e) $ f e f (HsCase e as) = HsCase <$> fn e <*> fn as f (HsDo hsStmts) = HsDo <$> fn hsStmts f (HsExpTypeSig srcLoc e hsQualType) = HsExpTypeSig srcLoc <$> fn e <*> fn hsQualType f (HsLambda srcLoc hsPats e) = HsLambda srcLoc <$> fn hsPats <*> fn e f (HsLet hsDecls e) = HsLet <$> fn hsDecls <*> fn e f (HsListComp c) = HsListComp <$> fn c f (HsRecConstr n fus) = HsRecConstr n <$> fn fus f (HsRecUpdate e fus) = HsRecUpdate <$> fn e <*> fn fus -- only exp f e@HsCon {} = pure e f e@HsError {} = pure e f e@HsLit {} = pure e f e@HsVar {} = pure e f (HsApp a1 a2) = HsApp <$> fn a1 <*> fn a2 f (HsAsPat hsName e) = HsAsPat hsName <$> fn e f (HsBackTick e) = HsBackTick <$> fn e f (HsBangPat e) = HsBangPat <$> fn e f (HsEnumFrom e) = HsEnumFrom <$> fn e f (HsEnumFromThen e1 e2) = HsEnumFromThen <$> fn e1 <*> fn e2 f (HsEnumFromThenTo a1 a2 a3) = HsEnumFromThenTo <$> fn a1 <*> fn a2 <*> fn a3 f (HsEnumFromTo e1 e2) = HsEnumFromTo <$> fn e1 <*> fn e2 f (HsIf e1 e2 e3) = liftA3 HsIf (fn e1) (fn e2) (fn e3) f (HsInfixApp a1 a2 a3) = HsInfixApp <$> fn a1 <*> fn a2 <*> fn a3 f (HsIrrPat hsExp) = HsIrrPat <$> fn hsExp f (HsLeftSection e1 e2) = HsLeftSection <$> fn e1 <*> fn e2 f (HsList hsExps) = HsList <$> fn hsExps f (HsLocatedExp le) = HsLocatedExp <$> fn le f (HsNegApp a1) = HsNegApp <$> fn a1 f (HsParen e) = HsParen <$> fn e f (HsRightSection e1 e2) = HsRightSection <$> fn e1 <*> fn e2 f (HsTuple es) = HsTuple <$> fn es f (HsUnboxedTuple es) = HsUnboxedTuple <$> fn es f (HsWildCard x) = pure (HsWildCard x) f (HsWords ws) = HsWords <$> fn ws --f h = error $ "FrontEnd.Syn.Traverse.traverseHsExp f unrecognized construct: " ++ show h instance TraverseHsOps e => TraverseHsOps (Located e) where traverseHsOps hops (Located l e) = withSrcSpan l (Located l <$> applyHsOps hops e) instance (TraverseHsOps a,T.Traversable f) => TraverseHsOps (f a) where traverseHsOps hops xs = T.traverse (applyHsOps hops) xs maybeGetDeclName :: Monad m => HsDecl -> m Name maybeGetDeclName HsPatBind { hsDeclPat = HsPVar name } = return (toName Val name) maybeGetDeclName HsActionDecl { hsDeclPat = HsPVar name } = return (toName Val name) maybeGetDeclName (HsFunBind ((HsMatch _ name _ _ _):_)) = return (toName Val name) maybeGetDeclName HsDataDecl { hsDeclDeclType = DeclTypeKind, hsDeclName } = return (toName SortName hsDeclName) maybeGetDeclName HsDataDecl { hsDeclName = name } = return (toName TypeConstructor name) maybeGetDeclName HsClassDecl { hsDeclClassHead = h } = return $ toName ClassName $ hsClassHead h maybeGetDeclName x@HsForeignDecl {} = return $ toName Val $ hsDeclName x maybeGetDeclName (HsForeignExport _ e _ _) = return $ ffiExportName e --maybeGetDeclName (HsTypeSig _ [n] _ ) = return n maybeGetDeclName d = fail $ "getDeclName: could not find name for a decl: " ++ show d getDeclName :: HsDecl -> Name getDeclName d = runIdentity $ maybeGetDeclName d
m-alvarez/jhc
src/FrontEnd/Syn/Traverse.hs
mit
15,438
0
14
4,461
5,239
2,567
2,672
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-| Module : Evaluator Description : Types and operations for managing the elaboration context. Copyright : (c) Michael Lopez, 2017 License : MIT Maintainer : m-lopez (github) Stability : unstable Portability : non-portable -} module Evaluator ( evalExpr ) where import Expressions ( Expr(..), ExprName, substExprs, CType(..), QType(..) ) import Context ( Ctx, Binding(BVar), lookupSignature ) import Util.DebugOr ( DebugOr, requireOrElse, mkSuccess ) -------------------------------------------------------------------------------- -- Evaluation system -- -- Based on small-step semantics: -- -- e_i ~> v => e(e_1, ..., e_i, ..., e_n) ~> e (e_1, ..., v, ..., e_n) -- e ~> \(x_1, ..., x_n).e' => e (v_1, ..., v_n) ~> e' [v_1 -> x_1, ..., v_n -> x_n] -- e1 ~> v => if e1 then e2 else e3 ~> if v then e2 else e3 -- if true then e1 else e2 ~> e1 -- if false then e1 else e2 ~> e2 -- We allow Maybe to catch compiler errors that lead to an unsound type system. evalExpr :: Ctx -> Expr -> DebugOr Expr evalExpr ctx e = case e of ELitBool _ -> return e ELitInt _ -> return e EVar x t -> evalVar ctx x t EAbs _ _ -> return e EApp e' es -> evalApp ctx e' es EIf c e1 e2 -> do res <- evalExpr ctx c b <- asBool res if b then evalExpr ctx e1 else evalExpr ctx e2 e1 -> mkSuccess e1 evalVar :: Ctx -> ExprName -> QType -> DebugOr Expr evalVar ctx x t = do BVar _ _ v_maybe <- lookupSignature ctx x t case v_maybe of Just e -> mkSuccess e Nothing -> fail $ printed ++ " has no definition" where printed = "`" ++ show x ++ ": " ++ show t ++ "`" evalApp :: Ctx -> Expr -> [Expr] -> DebugOr Expr evalApp ctx e es = do vs <- evalExprs ctx es -- FIXME: Add value check here. f <- evalExpr ctx e case f of EAbs xs e' -> evalLambdaApp ctx e' xs vs EUnBuiltin _ _ f' -> evalUnaryBuiltin f' vs EBinBuiltin _ _ f' -> evalBinaryBuiltin f' vs _ -> fail $ "callee " ++ show f ++ " is not callable" evalLambdaApp :: Ctx -> Expr -> [(ExprName, CType)] -> [Expr] -> DebugOr Expr evalLambdaApp ctx e xs vs = do requireOrElse (length vs == length xs) "arity doesn't match number of arguments" let xts = map (\(x,t) -> (x, Unquantified t)) xs let subst = zip xts vs evalExpr ctx $ substExprs subst e evalUnaryBuiltin :: (Expr -> DebugOr Expr) -> [Expr] -> DebugOr Expr evalUnaryBuiltin f vs = case vs of [v] -> f v _ -> fail $ "unary builtin expects 1 argument; got " ++ (show $ length vs) evalBinaryBuiltin :: ((Expr, Expr) -> DebugOr Expr) -> [Expr] -> DebugOr Expr evalBinaryBuiltin f vs = case vs of [v1, v2] -> f (v1, v2) _ -> fail $ "unary builtin expects 2 argument; got " ++ (show $ length vs) evalExprs :: Ctx -> [Expr] -> DebugOr [Expr] evalExprs ctx = traverse (evalExpr ctx) asBool :: Expr -> DebugOr Bool asBool e = case e of ELitBool b -> return b _ -> fail "value is not a Boolean"
m-lopez/jack
src/Evaluator.hs
mit
3,015
0
14
760
910
459
451
64
8
{-# LANGUAGE NoImplicitPrelude #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} module Handler.RemoteAccess where import Import -- | -- -- Retrieve computer details -- operationId: getComputer getComputerApiJsonR :: Handler Value getComputerApiJsonR = notImplemented -- | -- -- Retrieve Jenkins details -- operationId: getJenkins getApiJsonR :: Handler Value getApiJsonR = notImplemented -- | -- -- Retrieve job details -- operationId: getJob getJobByTextApiJsonR :: Text -- ^ Name of the job -> Handler Value getJobByTextApiJsonR name = notImplemented -- | -- -- Retrieve job configuration -- operationId: getJobConfig getJobByTextConfigXmlR :: Text -- ^ Name of the job -> Handler Value getJobByTextConfigXmlR name = notImplemented -- | -- -- Retrieve job&#39;s last build details -- operationId: getJobLastBuild getJobByTextLastBuildApiJsonR :: Text -- ^ Name of the job -> Handler Value getJobByTextLastBuildApiJsonR name = notImplemented -- | -- -- Retrieve job&#39;s build progressive text output -- operationId: getJobProgressiveText getJobByTextByTextLogTextProgressiveTextR :: Text -- ^ Name of the job -> Text -- ^ Build number -> Handler Value getJobByTextByTextLogTextProgressiveTextR name number = notImplemented -- | -- -- Retrieve queue details -- operationId: getQueue getQueueApiJsonR :: Handler Value getQueueApiJsonR = notImplemented -- | -- -- Retrieve queued item details -- operationId: getQueueItem getQueueItemByTextApiJsonR :: Text -- ^ Queue number -> Handler Value getQueueItemByTextApiJsonR number = notImplemented -- | -- -- Retrieve view details -- operationId: getView getViewByTextApiJsonR :: Text -- ^ Name of the view -> Handler Value getViewByTextApiJsonR name = notImplemented -- | -- -- Retrieve view configuration -- operationId: getViewConfig getViewByTextConfigXmlR :: Text -- ^ Name of the view -> Handler Value getViewByTextConfigXmlR name = notImplemented -- | -- -- Retrieve Jenkins headers -- operationId: headJenkins headApiJsonR :: Handler Value headApiJsonR = notImplemented -- | -- -- Create a new job using job configuration, or copied from an existing job -- operationId: postCreateItem postCreateItemR :: Handler Value postCreateItemR = notImplemented -- | -- -- Create a new view using view configuration -- operationId: postCreateView postCreateViewR :: Handler Value postCreateViewR = notImplemented -- | -- -- Build a job -- operationId: postJobBuild postJobByTextBuildR :: Text -- ^ Name of the job -> Handler Value postJobByTextBuildR name = notImplemented -- | -- -- Update job configuration -- operationId: postJobConfig postJobByTextConfigXmlR :: Text -- ^ Name of the job -> Handler Value postJobByTextConfigXmlR name = notImplemented -- | -- -- Delete a job -- operationId: postJobDelete postJobByTextDoDeleteR :: Text -- ^ Name of the job -> Handler Value postJobByTextDoDeleteR name = notImplemented -- | -- -- Disable a job -- operationId: postJobDisable postJobByTextDisableR :: Text -- ^ Name of the job -> Handler Value postJobByTextDisableR name = notImplemented -- | -- -- Enable a job -- operationId: postJobEnable postJobByTextEnableR :: Text -- ^ Name of the job -> Handler Value postJobByTextEnableR name = notImplemented -- | -- -- Stop a job -- operationId: postJobLastBuildStop postJobByTextLastBuildStopR :: Text -- ^ Name of the job -> Handler Value postJobByTextLastBuildStopR name = notImplemented -- | -- -- Update view configuration -- operationId: postViewConfig postViewByTextConfigXmlR :: Text -- ^ Name of the view -> Handler Value postViewByTextConfigXmlR name = notImplemented
cliffano/swaggy-jenkins
clients/haskell-yesod/generated/src/Handler/RemoteAccess.hs
mit
4,013
0
7
950
470
288
182
59
1
module SchemeSpec.TypesSpec where import Test.Hspec import Prelude hiding(lookup) import Scheme.Types spec :: Spec spec = do describe "Value" $ do let x = IntVal 42 let y = IntVal 7 let z = LamVal (intern "x") (Val 7) emptyEnv it "can be displayed" $ do show x `shouldBe` "42" show y `shouldBe` "7" show z `shouldBe` "#<procedure>" context "Eq" $ do it "can compare IntVals" $ do x == x `shouldBe` True y == y `shouldBe` True x == y `shouldBe` False it "cannot compare LamVals" $ do z == z `shouldBe` False it "cannot compare different types of Values" $ do x == z `shouldBe` False y == z `shouldBe` False describe "Env" $ do let x = intern "x" let v = IntVal 42 context "when empty" $ do it "has no entries" $ do lookup emptyEnv x `shouldBe` Nothing it "can store entires" $ do let env = extend emptyEnv x v lookup env x `shouldBe` Just v
mjdwitt/a-scheme
test/SchemeSpec/TypesSpec.hs
mit
1,004
0
19
325
372
177
195
33
1
module ProjectEuler.Problem62 ( problem ) where import Control.Arrow import Data.Function import Data.List import Data.Tuple import Petbox import qualified Data.Map.Strict as M import ProjectEuler.Types problem :: Problem problem = pureProblem 62 Solved result -- get a list of (num, num^3 (broken into digits)), -- and then group by cubic number length sameCubicLengthGroups :: [] [(Int,[Int])] sameCubicLengthGroups = groupBy ((==) `on` (length . snd)) . map (id &&& (intToDigits . (^(3 :: Int)))) $ [1..] permSet :: [(Int,[Int])] -> [ [Int] ] permSet = M.elems . M.fromListWith (++) . map (swap . second sort . first (:[])) result :: Int result = minimum $ map (^(3 :: Int)) answerGroup where cubicPermSets = map permSet sameCubicLengthGroups -- this is the permset we interested in: -- a group containing exactly 5 elements answerGroup:_ = concatMap (filter ((== 5) . length)) cubicPermSets
Javran/Project-Euler
src/ProjectEuler/Problem62.hs
mit
936
0
13
178
303
177
126
25
1
{-# LANGUAGE FlexibleInstances #-} module Orville.PostgreSQL.Internal.OrvilleState ( OrvilleState, newOrvilleState, resetOrvilleState, orvilleConnectionPool, orvilleConnectionState, orvilleErrorDetailLevel, HasOrvilleState (askOrvilleState, localOrvilleState), ConnectionState (NotConnected, Connected), ConnectedState (ConnectedState, connectedConnection, connectedTransaction), connectState, TransactionState (OutermostTransaction, SavepointTransaction), newTransaction, Savepoint, savepointNestingLevel, ) where import Control.Monad.Trans.Reader (ReaderT, ask, local) import Data.Pool (Pool) import Orville.PostgreSQL.Connection (Connection) import Orville.PostgreSQL.Internal.ErrorDetailLevel (ErrorDetailLevel) {- | 'OrvilleState' is used to manange opening connections to the database, transactions, etc. 'newOrvilleState' should be used to create an appopriate initial state for your monad's context. -} data OrvilleState = OrvilleState { _orvilleConnectionPool :: Pool Connection , _orvilleConnectionState :: ConnectionState , _orvilleErrorDetailLevel :: ErrorDetailLevel } orvilleConnectionPool :: OrvilleState -> Pool Connection orvilleConnectionPool = _orvilleConnectionPool orvilleConnectionState :: OrvilleState -> ConnectionState orvilleConnectionState = _orvilleConnectionState orvilleErrorDetailLevel :: OrvilleState -> ErrorDetailLevel orvilleErrorDetailLevel = _orvilleErrorDetailLevel {- | 'HasOrvilleState' is the typeclass that Orville uses to access and manange the connection pool and state tracking when it is being executed inside an unknown Monad. It is a specialized version of the Reader interface so that it can easily implemented by application Monads that already have a Reader context and want to simply add 'OrvilleState' as an attribute to that context, like so @ data MyApplicationState = MyApplicationState { appConfig :: MyAppConfig , appOrvilleState :: OrvilleState } newtype MyApplicationMonad a = MyApplicationMonad (ReaderT MyApplicationState IO) a instance HasOrvilleState MyApplicationMonad where askOrvilleState = MyApplicationMonad (asks appOrvilleState) localOrvilleState f (MyApplicationMonad reader) = MyApplicationMonad $ local (\state -> state { appOrvilleState = f (appOrvilleState state)) reader @ An instance for 'ReaderT OrvilleState m' is provided as a convenience in the case that your application has no extra context to track. -} class HasOrvilleState m where {- Fetches the current 'OrvilleState' from the host Monad context. The equivalent of 'ask' for 'ReaderT OrvilleState' -} askOrvilleState :: m OrvilleState {- Applies a modification to the 'OrvilleState' that is local to the given monad operation. Calls to 'askOrvilleState' made within the 'm a' provided must return the modified state. The modified state must only apply to the given 'm a' and not persisted beyond it. The equivalent of 'local' for 'ReaderT OrvilleState' -} localOrvilleState :: -- | The function to modify the 'OrvilleState' (OrvilleState -> OrvilleState) -> -- | The monad operation to execute with the modified state m a -> m a instance Monad m => HasOrvilleState (ReaderT OrvilleState m) where askOrvilleState = ask localOrvilleState = local {- | Creates a appropriate initial 'OrvilleState' that will use the connection pool given to initiate connections to the database. -} newOrvilleState :: ErrorDetailLevel -> Pool Connection -> OrvilleState newOrvilleState errorDetailLevel pool = OrvilleState { _orvilleConnectionPool = pool , _orvilleConnectionState = NotConnected , _orvilleErrorDetailLevel = errorDetailLevel } {- | Creates a new initial 'OrvilleState' using the connection pool from the provide state. You might need to use this if you are spawning one Orville monad from another and they should not share the same connection and transaction state. -} resetOrvilleState :: OrvilleState -> OrvilleState resetOrvilleState = newOrvilleState <$> _orvilleErrorDetailLevel <*> _orvilleConnectionPool {- | INTERNAL: Transitions the 'OrvilleState' into "connected" status, storing the given 'Connection' as the database connection to be used to execute all queries. This is used by 'withConnection' to track the connection it retrieves from the pool. -} connectState :: ConnectedState -> OrvilleState -> OrvilleState connectState connectedState state = state { _orvilleConnectionState = Connected connectedState } {- | INTERNAL: This type is used to signal whether a database connection has been retrieved from the pool for the current operation or not. The value is tracked in the 'OrvilleState' for the host monad, and is checked by 'withConnection' to avoid checking out two separate connections for a multiple operations that needs to be run on the same connection (e.g. multiple operations inside a transaction). -} data ConnectionState = NotConnected | Connected ConnectedState data ConnectedState = ConnectedState { connectedConnection :: Connection , connectedTransaction :: Maybe TransactionState } data TransactionState = OutermostTransaction | SavepointTransaction Savepoint newTransaction :: Maybe TransactionState -> TransactionState newTransaction maybeTransactionState = case maybeTransactionState of Nothing -> OutermostTransaction Just OutermostTransaction -> SavepointTransaction initialSavepoint Just (SavepointTransaction savepoint) -> SavepointTransaction (nextSavepoint savepoint) newtype Savepoint = Savepoint Int initialSavepoint :: Savepoint initialSavepoint = Savepoint 1 nextSavepoint :: Savepoint -> Savepoint nextSavepoint (Savepoint n) = Savepoint (n + 1) savepointNestingLevel :: Savepoint -> Int savepointNestingLevel (Savepoint n) = n
flipstone/orville
orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/OrvilleState.hs
mit
6,029
0
10
1,117
585
339
246
94
3
{-# LANGUAGE TypeFamilies, DeriveDataTypeable, FlexibleContexts, GADTs #-} module Main ( main ) where import Data.Typeable import qualified Data.Traversable as Traversable import Control.Applicative import Control.Monad import Data.Maybe import Data.IORef import System.Mem.Weak --transformers package: import Control.Monad.IO.Class main = example data Person = Person { name :: String } deriving (Show, Typeable) data Company = Company { legalName :: String } deriving (Show, Typeable) -- the only thing we need MonadIO for in this exmple is printing output example :: (MonadIO m, MonadComputed m) => m () example = do -- aliceRef :: Reference Person aliceRef <- new $ Person { name = "Alice" } -- alice :: Computed Person alice <- track aliceRef bobRef <- new $ Person { name = "Bob" } bob <- track bobRef -- companyRef :: Reference Company companyRef <- new $ Company { legalName = "Eve's Surveillance" } -- company :: Computed Company company <- track companyRef let dumpValues = do (liftIO . print) =<< runComputed alice (liftIO . print) =<< runComputed bob (liftIO . print) =<< runComputed company (liftIO . putStrLn) "" dumpValues people <- share $ Traversable.sequenceA [alice, bob] structure2 <- share $ do a <- alice c <- company return (a, c) structure3 <- share $ (pure (,)) <*> structure2 <*> bob let dumpStructures = do (liftIO . print) =<< runComputed people (liftIO . print) =<< runComputed structure2 (liftIO . print) =<< runComputed structure3 (liftIO . putStrLn) "" dumpStructures set aliceRef Person { name = "Mike" } dumpValues dumpStructures set companyRef Company { legalName = "Mike's Meddling" } dumpValues dumpStructures -- Run it again to demonstrate that only one get is required to get the entire pure structure dumpStructures set aliceRef Person { name = "Alice Again" } dumpValues dumpStructures set bobRef Person { name = "Bob doesn't touch structure2" } dumpValues dumpStructures -- Class for a typed dictionary in a monadic context class (Monad m) => MonadReference m where type Reference :: * -> * new :: (Typeable a) => a -> m (Reference a) set :: (Typeable a) => Reference a -> a -> m () get :: (Typeable a) => Reference a -> m a -- Class for a monad with state dependent values class (MonadReference m, Applicative Computed, Monad Computed) => MonadComputed m where type Computed :: * -> * track :: (Typeable a) => Reference a -> m (Computed a) share :: (Typeable a) => (Computed a) -> m (Computed a) runComputed :: (Typeable a) => (Computed a) -> m a -- A published value for IO, using Weak references to the subscribers data Published a = Published { valueRef :: IORef a, subscribers :: IORef [Weak (IO ())] } -- A new implementation that keeps an update list instance MonadReference IO where type Reference = Published new = newIORefPublished set = setIORefPublished get = readIORefPublished -- Separate implemenations for these, since we'd like to drop the Typeable constraint newIORefPublished value = do ref <- newIORef value subscribersRef <- newIORef [] return Published { valueRef = ref, subscribers = subscribersRef } setIORefPublished published value = do writeIORef (valueRef published) value notify $ subscribers published --readIORefPublished = readIORef . valueRef readIORefPublished x = do putStrLn "getting" readIORef $ valueRef x notify :: IORef [Weak (IO ())] -> IO () notify = go where go subscribersRef = do subscribers <- readIORef subscribersRef needsCleanup <- (liftM (any id)) (mapM notifySubscriber subscribers) when needsCleanup $ cleanupWeakRefs subscribersRef notifySubscriber weakSubscriber = do maybeSubscriber <- deRefWeak weakSubscriber case maybeSubscriber of Nothing -> return True Just subscriber -> subscriber >> return False cleanupWeakRefs :: IORef [Weak a] -> IO () cleanupWeakRefs ref = do weaks <- readIORef ref newWeaks <- (liftM catMaybes) $ mapM testWeak weaks writeIORef ref newWeaks where testWeak weakRef = liftM (>> Just weakRef) $ deRefWeak weakRef -- Data type for building computations data IORefComputed a where Pure :: a -> IORefComputed a Apply :: IORefComputed (b -> a) -> IORefComputed b -> IORefComputed a Bound :: IORefComputed b -> (b -> IORefComputed a) -> IORefComputed a Tracked :: Published a -> IORefComputed a Shared :: Published (Either (IORefComputed a) a) -> IORefComputed a instance Monad IORefComputed where return = Pure (>>=) = Bound (>>) _ = id instance Applicative IORefComputed where pure = return (<*>) = Apply instance Functor IORefComputed where fmap = (<*>) . pure -- Evaluate computations built in IO instance MonadComputed IO where type Computed = IORefComputed track = trackIORefComputed runComputed = evalIORefComputed share = shareIORefComputed -- Separate implementations, again to drop the Typeable constraint trackIORefComputed = return . Tracked evalIORefComputed :: IORefComputed a -> IO a evalIORefComputed c = case c of Pure x -> return x Apply cf cx -> do f <- evalIORefComputed cf x <- evalIORefComputed cx return (f x) Bound cx k -> do value <- evalIORefComputed cx evalIORefComputed (k value) Tracked published -> readIORefPublished published Shared publishedThunk -> do thunk <- readIORefPublished publishedThunk case thunk of Left computation@(Bound cx k) -> do x <- evalIORefComputed cx -- Make a shared version of the computed computation currentExpression <- shareIORefComputed (k x) let gcKeyedCurrentExpression = Left currentExpression writeIORef (valueRef publishedThunk) gcKeyedCurrentExpression markDirty <- makeMarkDirty publishedThunk gcKeyedCurrentExpression computation subscribeTo currentExpression markDirty evalIORefComputed c Left computation -> do value <- evalIORefComputed computation writeIORef (valueRef publishedThunk) (Right value) return value Right x -> return x shareIORefComputed :: IORefComputed a -> IO (IORefComputed a) --shareIORefComputed c = return c shareIORefComputed c = case c of Apply cf cx -> do sharedf <- shareIORefComputed cf sharedx <- shareIORefComputed cx case (sharedf, sharedx) of -- Optimize away constants (Pure f, Pure x) -> return . Pure $ f x _ -> do let sharedc = sharedf <*> sharedx published <- newIORefPublished $ Left sharedc -- What we are going to do when either argument changes markDirty <- makeMarkDirty published published sharedc subscribeTo sharedf markDirty subscribeTo sharedx markDirty return $ Shared published Bound cx k -> do sharedx <- shareIORefComputed cx case cx of -- Optimize away constants (Pure x) -> shareIORefComputed $ k x _ -> do let dirtyc = sharedx >>= k published <- newIORefPublished $ Left dirtyc -- What we are going to do when the argument to k changes markDirty <- makeMarkDirty published published dirtyc subscribeTo sharedx markDirty return $ Shared published _ -> return c makeMarkDirty :: Published (Either (IORefComputed a) a) -> k -> IORefComputed a -> IO (Weak (IO ())) makeMarkDirty published key definition = do let markDirty = do existing <- readIORef (valueRef published) case existing of Right _ -> setIORefPublished published $ Left definition _ -> return () mkWeak key markDirty Nothing subscribeTo :: IORefComputed a -> Weak (IO ()) -> IO () subscribeTo (Tracked published) trigger = modifyIORef' (subscribers published) (trigger :) subscribeTo (Shared published) trigger = modifyIORef' (subscribers published) (trigger :) subscribeTo _ _ = return ()
Cedev/monad-computed
Main.hs
mit
8,992
0
18
2,825
2,332
1,134
1,198
-1
-1
--带上下文的计算过程 具体例子可以看clojure文件中的例子 将上下文处理的细节封装在内部 让外部的代码保证一致性与简洁性 class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b x >> y = x >>= \_ -> y --return类似applicative functor中的pure函数 将一个值包裹在最小上下文中 --(>>=)也就是大名鼎鼎的bind函数 用来进行带上下文的计算 bind runs the monad m a, feeding the yielded a value into the function it received as an argument - any context carried by that monad will be taken into account. --(>>)是bind函数中的回调忽略之前参数值的版本 成为then --maybe monad 带有一个可能计算失败的上下文 加入一串计算中 某一处出现了失败 直接返回失败结果 而不继续进行下去了 防止系统崩溃 instance Monad Maybe where return x = Just x Nothing >>= f = Nothing Just x >>= f = f x fail _ = Nothing a = Just 9 >>= \x -> return (x*10) --Just 90 b = Nothing >>= \x -> return (x*10) --Nothing --list monad 带有一个不确定结果的上下文 instance Monad [] where return x = [x] xs >>= f = concat (map f xs) fail _ = [] c = [3,4,5] >>= \x -> [x,-x] --[3,-3,4,-4,5,-5] --just list comprehension d = [1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch) --[(1,'a'),(1,'b'),(2,'a'),(2,'b')] --为了防止出现bind的嵌套影响可读性 haskell中有do notation语法糖来简化代码 routine :: Maybe Pole routine = do start <- return (0,0) first <- landLeft 2 start Nothing second <- landRight 2 first landLeft 1 second --上面的代码展开为bind嵌套为 routine = return (0, 0) >>= (\start -> landLeft 2 start >>= \first -> Nothing >>= (\_ -> landRight 2 first >>= (\_ second -> landLeft 1 second))) --上面 do notation中的Nothing其实写得verbose一点就是_ <- Nothing routine = return (0, 0) >>= (\start -> landLeft 2 start >>= \first -> Nothing >> landRight 2 first >>= (\_ second -> landLeft 1 second)) --monad law --Right unit m >>= return = m --m is a monad value --Left unit return x >>= f = f x --Associativity(结合律) (m >>= f) >>= g = m >>= (\x -> f x >>= g) --reader monad is just wrap a binary function context --a reader monad in haskell newtype Reader r a = Reader { runReader :: r -> a } ask = Reader $ \x -> x -- or just identity function asks = Reader $ \f -> (\env -> f env) instance Monad (Reader ((->) r)) where return x = Reader $ \_ -> x --m is a reader monad and runReader m is just get the unwrapped function m >>= k = Reader $ \r -> runReader (k (runReader m r)) r greeter :: Reader String String greeter = do name <- ask return ("hello, " ++ name ++ "!") --expand the do notation ask >>= (\name -> return ("hello, " ++ name ++ "!")) --runReader ask => \x -> x Reader $ \r -> runReader ((\name -> return ("hello, " ++ name ++ "!")) (runReader ask r)) r runReader greeter $ "adit" --=> "hello, adit!" runReader (Reader $ \r -> runReader ((\name -> return ("hello, " ++ name ++ "!")) (runReader ask r)) r) "adit" (\r -> runReader ((\name -> return ("hello, " ++ name ++ "!")) (runReader ask r)) r) "adit" runReader ((\name -> return ("hello, " ++ name ++ "!")) (runReader ask "adit")) "adit" runReader ((\name -> return ("hello, " ++ name ++ "!")) "adit") "adit" runReader return ("hello, " ++ "adit" ++ "!") "adit" (\_ -> ("hello, " ++ "adit" ++ "!")) "adit" "hello, adit!" --reader monad的一个最大的作用就是将一个很多个函数都要用到的配置信息 传给所有这些函数 比如一个不太恰当的例子 import Control.Monad.Reader hello :: Reader String String hello = do name <- ask return ("hello, " ++ name ++ "!") bye :: Reader String String bye = do name <- ask return ("bye, " ++ name ++ "!") convo :: Reader String String convo = do c1 <- hello c2 <- bye return $ c1 ++ c2 main = print . runReader convo $ "adit" --可以看到我们不需要每次都把"adit"这个配置值都显式的传给hello和bye之类依赖这个配置值的函数了 而是用reader monad在外部接受一次就行了 内部代码非常的简洁 --State Monad is similiar to reader monad --The State monad is the Reader monad’s more impressionable best friend --a是当前值的类型 s是当前状态的类型 内部包装的是一个接受一个状态返回一个值和新的状态的函数 newtype State s a = State { runState :: s -> (a, s) } instance Monad (State s) where return x = State $ \s -> (x, s) m >>= k = State $ \s -> let (a, st) = runState m s in runState (k a) st --yet another bind definition use pattern match not use runState function (State h) >>= f = State $ \s -> let (a, newState) = h s (State g) = f a in g newState --state monad 的bind的实现乍一看有一点烧脑 其实思路很简单 --就是返回一个包在State上下文中接受一个状态值 返回的是先将传入的状态作用在旧的State monad包裹的函数上 --得到值和状态 然后将得到的值传入新的函数 最后将之前得到的状态传给新得到的状态函数 得到最终的新的值和状态 get = State $ \s -> (s, s) --获取当前的状态作为结果 put newState = State $ \s -> ((), newState) --创建一个新的带状态函数 greeter :: State String String greeter = do name <- get put "tintin" return ("hello, " ++ name ++ "!") --expand the do notation get >>= (\name -> put "tintin" >>= (\_ -> return ("hello, " ++ name ++ "!"))) State $ \s -> let (a, st) = (\s -> (s, s)) s in runState ((\name -> put "tintin" >>= (\_ -> return ("hello, " ++ name ++ "!"))) a) st State $ \s -> let (a, st) = (s, s) in runState ((\name -> put "tintin" >>= (\_ -> return ("hello, " ++ name ++ "!"))) a) st State $ \s -> runState ((\name -> put "tintin" >>= (\_ -> return ("hello, " ++ name ++ "!"))) s) s State $ \s -> runState put "tintin" >>= (\_ -> return ("hello, " ++ s ++ "!")) s State $ \s -> runState (State $ \s1 -> let (a, st) = (\s -> ((), "tintin") s1) in runState (\_ -> return ("hello, " ++ s ++ "!")) a st) s State $ \s -> runState (State $ \s1 -> let (a, st) = ((), "tintin") in runState (\_ -> return ("hello, " ++ s ++ "!")) a st) s State $ \s -> runState (State $ \s1 -> runState (\_ -> return ("hello, " ++ s ++ "!")) () "tintin") s State $ \s -> runState (State $ \s1 -> runState return ("hello, " ++ s ++ "!") "tintin") s State $ \s -> runState (State $ \s1 -> \s2 -> ("hello, " ++ s ++ "!", s2) "tintin") s State $ \s -> runState (State $ \s1 -> ("hello, " ++ s ++ "!", "tintin")) s State $ \s -> \s1 -> ("hello, " ++ s ++ "!", "tintin") s State $ \s -> ("hello, " ++ s ++ "!", "tintin") runState greeter $ "adit" --((runState greeter) "adit") 要这样理解这个表达式 先获得等待状态传入的函数 在作用在外部的状态上 (\s -> ("hello, " ++ s ++ "!", "tintin")) "adit" --=> ("hello, adit!", "tintin") "tintin" is just the current state --另一种reader monad的实现 只是单纯的将函数当做了上下文 instance Monad ((->) r) where return x = \_ -> x h >>= f = \w -> f (h w) w import Control.Monad.Instances addStuff :: Int -> Int addStuff = do a <- (*2) b <- (+10) return (a+b) --化简展开会很复杂 (*2) >>= (\a -> (+10) >>= (\b -> (\_ -> return (a+b))) \w -> (\a -> (+10) >>= (\b -> (\_ -> return (a+b)))) ((*2) w) w \w -> (\a -> (\t -> (\b -> (\_ -> return (a+b))) ((+10) t) t)) ((*2) w) w addStuff 3 -- (3*2) + (3+10) -> 19 --will expand to ((\w -> (\a -> (\t -> (\b -> (\_ -> return (a+b))) ((+10) t) t)) ((*2) w) w) 3) \3 -> (\a -> (\t -> (\b -> (\_ -> return (a+b))) ((+10) t) t)) ((*2) 3) 3 (\a -> (\t -> (\b -> (\_ -> return (a+b))) ((+10) t) t)) 6 3 (\t -> (\b -> (\_ -> return (6+b))) ((+10) t) t) 3 \b -> (\_ -> return (6+b))) 13 3 (\_ -> return (6+13)) 3 return 19 --just get 19 --the writer monad newtype Writer w a = Writer { runWriter :: (a, w) } --runWriter just get the tuple from a Writer --mempty是由w这个Monoid类型确定的 比如Maybe List instance (Monoid w) => Monad (Writer w) where return x = Writer (x, mempty) (Writer (x, v)) >>= f = let (Writer (y, vt)) = f x in Writer (y, v `mappend` vt) import Control.Monad.Writer logNumber :: Int -> Writer [String] Int logNumber x = writer (x, ["Got number: " ++ show x]) --tell implementation for my own tell :: [String] -> Writer [String] Int tell msg = writer (0, msg) multWithLog :: Writer [String] Int multWithLog = do a <- logNumber 3 b <- logNumber 5 tell ["Gonna multiply these two"] return (a*b) --just expand this nested monad logNumber 3 >>= (\a -> logNumber 5 >>= (\b -> tell ["Gonna multiply these two"] >>= (\_ -> return (a*b)))) let (Writer (y, vt)) = logNumber 5 >>= (\b -> tell ["Gonna multiply these two"] >>= (\_ -> return (3*b))) in Writer (y, "Got number: 3" `mappend` vt) let (Writer (y, vt)) = (let (Writer (y1, vt1)) = tell ["Gonna multiply these two"] >>= (\_ -> return (3*5)) in Writer (y1, "Got number: 5" `mappend` vt1)) in Writer (y, "Got number: 3" `mappend` vt) let (Writer (y, vt)) = (let (Writer (y1, vt1)) = (let (Writer (y2, vt2)) = return (3*5) in Writer (y2, ["Gonna multiply these two"] `mappend` vt2)) in Writer (y1, ["Got number: 5"] `mappend` vt1)) in Writer (y, ["Got number: 3"] `mappend` vt) y2 = 15 vt2 = mempty :: [String] y1 = 15 vt1 = ["Gonna multiply these two"] y = 15 vt = ["Got number: 5", "Gonna multiply these two"] -- so the final result is Writer (15, ["Got number: 3", "Got number: 5", "Gonna multiply these two"]) --use runWriter to get the unwrapped tuple value runWriter multWithLog --(15, ["Got number: 3", "Got number: 5", "Gonna multiply these two"])
zjhmale/monadme
monad/src/monad/haskell/monad.hs
epl-1.0
10,169
5
31
2,258
3,837
2,040
1,797
-1
-1
{- | Module : $Header$ Description : datastructures for annotations of (Het)CASL. Copyright : (c) Klaus Luettich, Christian Maeder, and Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Datastructures for annotations of (Het)CASL. There is also a paramterized data type for an 'Annoted' 'item'. See also chapter II.5 of the CASL Reference Manual. -} module Common.AS_Annotation where import Common.Id import Common.IRI (IRI) import Data.Maybe -- DrIFT command {-! global: GetRange !-} -- | start of an annote with its WORD or a comment data Annote_word = Annote_word String | Comment_start deriving (Show, Eq, Ord) -- | line or group for 'Unparsed_anno' data Annote_text = Line_anno String | Group_anno [String] deriving (Show, Eq, Ord) {- | formats to be displayed (may be extended in the future). Drop 3 from the show result to get the string for parsing and printing -} data Display_format = DF_HTML | DF_LATEX | DF_RTF deriving (Show, Eq, Ord) -- | swap the entries of a lookup table swapTable :: [(a, b)] -> [(b, a)] swapTable = map $ \ (a, b) -> (b, a) -- | drop the first 3 characters from the show result toTable :: (Show a) => [a] -> [(a, String)] toTable = map $ \ a -> (a, drop 3 $ show a) -- | a lookup table for the textual representation of display formats display_format_table :: [(Display_format, String)] display_format_table = toTable [ DF_HTML, DF_LATEX, DF_RTF ] {- | lookup the textual representation of a display format in 'display_format_table' -} lookupDisplayFormat :: Display_format -> String lookupDisplayFormat df = fromMaybe (error "lookupDisplayFormat: unknown display format") $ lookup df display_format_table {- | precedence 'Lower' means less and 'BothDirections' means less and greater. 'Higher' means greater but this is syntactically not allowed in 'Prec_anno'. 'NoDirection' can also not be specified explicitly, but covers those ids that are not mentionend in precedences. -} data PrecRel = Higher | Lower | BothDirections | NoDirection deriving (Show, Eq, Ord) -- | either left or right associative data AssocEither = ALeft | ARight deriving (Show, Eq, Ord) {- | semantic (line) annotations without further information. Use the same drop-3-trick as for the 'Display_format'. -} data Semantic_anno = SA_cons | SA_def | SA_implies | SA_mono | SA_implied | SA_mcons | SA_ccons deriving (Show, Eq, Ord) -- | a lookup table for the textual representation of semantic annos semantic_anno_table :: [(Semantic_anno, String)] semantic_anno_table = toTable [SA_cons, SA_def, SA_implies, SA_mono, SA_implied, SA_mcons, SA_ccons] {- | lookup the textual representation of a semantic anno in 'semantic_anno_table' -} lookupSemanticAnno :: Semantic_anno -> String lookupSemanticAnno sa = fromMaybe (error "lookupSemanticAnno: no semantic anno") $ lookup sa semantic_anno_table -- | all possible annotations (without comment-outs) data Annotation = -- | constructor for comments or unparsed annotes Unparsed_anno Annote_word Annote_text Range -- | known annotes | Display_anno Id [(Display_format, String)] Range -- position of anno start, keywords and anno end | List_anno Id Id Id Range -- position of anno start, commas and anno end | Number_anno Id Range -- position of anno start, commas and anno end | Float_anno Id Id Range -- position of anno start, commas and anno end | String_anno Id Id Range -- position of anno start, commas and anno end | Prec_anno PrecRel [Id] [Id] Range {- positions: "{",commas,"}", RecRel, "{",commas,"}" Lower = "< " BothDirections = "<>" -} | Assoc_anno AssocEither [Id] Range -- position of commas | Label [String] Range -- position of anno start and anno end | Prefix_anno [(String, IRI)] Range -- position of anno start and anno end -- All annotations below are only as annote line allowed | Semantic_anno Semantic_anno Range {- position information for annotations is provided by every annotation -} deriving (Show, Eq, Ord) {- | 'isLabel' tests if the given 'Annotation' is a label (a 'Label' typically follows a formula) -} isLabel :: Annotation -> Bool isLabel a = case a of Label _ _ -> True _ -> False isImplies :: Annotation -> Bool isImplies a = case a of Semantic_anno SA_implies _ -> True _ -> False isImplied :: Annotation -> Bool isImplied a = case a of Semantic_anno SA_implied _ -> True _ -> False -- | 'isSemanticAnno' tests if the given 'Annotation' is a semantic one isSemanticAnno :: Annotation -> Bool isSemanticAnno a = case a of Semantic_anno _ _ -> True _ -> False {- | 'isComment' tests if the given 'Annotation' is a comment line or a comment group -} isComment :: Annotation -> Bool isComment c = case c of Unparsed_anno Comment_start _ _ -> True _ -> False -- | 'isAnnote' is the negation of 'isComment' isAnnote :: Annotation -> Bool isAnnote = not . isComment {- | an item wrapped in preceding (left 'l_annos') and following (right 'r_annos') annotations. 'opt_pos' should carry the position of an optional semicolon following a formula (but is currently unused). -} data Annoted a = Annoted { item :: a , opt_pos :: Range , l_annos :: [Annotation] , r_annos :: [Annotation] } deriving (Show, Ord, Eq) annoRange :: (a -> [Pos]) -> Annoted a -> [Pos] annoRange f a = joinRanges $ map (rangeToList . getRange) (l_annos a) ++ [f $ item a] ++ [rangeToList (opt_pos a)] ++ map (rangeToList . getRange) (r_annos a) notImplied :: Annoted a -> Bool notImplied = not . any isImplied . r_annos -- | naming or labelling sentences data SenAttr s a = SenAttr { senAttr :: a , isAxiom :: Bool , isDef :: Bool , wasTheorem :: Bool {- will be set to True when status of isAxiom changes from False to True -} , simpAnno :: Maybe Bool -- for %simp or %nosimp annotations , attrOrigin :: Maybe Id , sentence :: s } deriving (Eq, Ord, Show) -- | equip a sentence with a name makeNamed :: a -> s -> SenAttr s a makeNamed a s = SenAttr { senAttr = a , isAxiom = True , isDef = False , wasTheorem = False , simpAnno = Nothing , attrOrigin = Nothing , sentence = s } type Named s = SenAttr s String reName :: (a -> b) -> SenAttr s a -> SenAttr s b reName f x = x { senAttr = f $ senAttr x } -- | extending sentence maps to maps on labelled sentences mapNamed :: (s -> t) -> SenAttr s a -> SenAttr t a mapNamed f x = x { sentence = f $ sentence x } -- | extending sentence maybe-maps to maps on labelled sentences mapNamedM :: Monad m => (s -> m t) -> Named s -> m (Named t) mapNamedM f x = do y <- f $ sentence x return x {sentence = y} -- | process all items and wrap matching annotations around the results mapAnM :: (Monad m) => (a -> m b) -> [Annoted a] -> m [Annoted b] mapAnM f al = do il <- mapM (f . item) al return $ zipWith (flip replaceAnnoted) al il instance Functor Annoted where fmap f (Annoted x o l r) = Annoted (f x) o l r -- | replace the 'item' replaceAnnoted :: b -> Annoted a -> Annoted b replaceAnnoted x (Annoted _ o l r) = Annoted x o l r {- one could use this fmap variant instead (less efficient) replaceAnnoted x = fmap (const x) or even: replaceAnnoted = (<$) -} -- | add further following annotations appendAnno :: Annoted a -> [Annotation] -> Annoted a appendAnno (Annoted x p l r) = Annoted x p l . (r ++) -- | put together preceding annotations and an item addLeftAnno :: [Annotation] -> a -> Annoted a addLeftAnno l i = Annoted i nullRange l [] -- | decorate with no annotations emptyAnno :: a -> Annoted a emptyAnno = addLeftAnno [] -- | get the label following (or to the right of) an 'item' getRLabel :: Annoted a -> String getRLabel a = case filter isLabel (r_annos a) of Label l _ : _ -> unwords $ concatMap words l _ -> "" {- | check for an annotation starting with % and the input str (does not work for known annotation words) -} identAnno :: String -> Annotation -> Bool identAnno str an = case an of Unparsed_anno (Annote_word wrd) _ _ -> wrd == str _ -> False -- | test all anntotions for an item hasIdentAnno :: String -> Annoted a -> Bool hasIdentAnno str a = any (identAnno str) $ l_annos a ++ r_annos a makeNamedSen :: Annoted a -> Named a makeNamedSen a = (makeNamed (getRLabel a) $ item a) { isAxiom = notImplied a , simpAnno = case (hasIdentAnno "simp" a, hasIdentAnno "nosimp" a) of (True, False) -> Just True (False, True) -> Just False _ -> Nothing } annoArg :: Annote_text -> String annoArg txt = case txt of Line_anno str -> str Group_anno ls -> unlines ls newtype Name = Name String instance Show Name where show (Name s) = s getAnnoName :: Annoted a -> Name getAnnoName = Name . foldr (\ an -> case an of Unparsed_anno (Annote_word wrd) txt _ | wrd == "name" -> (annoArg txt ++) _ -> id) "" . l_annos
nevrenato/Hets_Fork
Common/AS_Annotation.der.hs
gpl-2.0
9,351
4
17
2,267
2,101
1,148
953
147
3
{- | Module : $Header$ - Description : Implementation of main file for the prover - Copyright : (c) Georgel Calin & Lutz Schroeder, DFKI Lab Bremen - License : GPLv2 or higher, see LICENSE.txt - Maintainer : [email protected] - Stability : provisional - Portability : portable - - Provides the implementation of the user interaction "interface" -} module Main where import GenericSequent import ModalLogic import CombLogic import Parser import Text.ParserCombinators.Parsec import System.Environment import IO -- | Main parsing unit for checking provability/satisfiability run :: (Eq a, Form a b c) => Parser (Boole a) -> String -> IO () run parser input = case (parse parser "" input) of Left err -> do putStr "parse error at " print err Right x -> do --putStrLn (show x{-++" <=> "++input-}) let isP = provable x case isP of True -> putStrLn "... is Provable" _ -> let isS = sat x in case isS of True -> putStrLn ("... is not Provable" ++ " but Satisfiable") _ -> putStrLn "... is not Satisfiable" -- | Runs the main parsing unit (probably superfluous) runLex :: (Eq a, Form a b c) => Parser (Boole a) -> String -> IO () runLex parser input = run (do spaces res <- parser eof return res ) input -- | Auxiliary run function for testing with the input given as string runTest :: [Int] -> String -> IO () runTest logics input = do {-case (head logics) of 1 -> runLex (parseKindex{-(par5er Sqr parseKindex) :: Parser (L K)-}) input 2 -> runLex ((par5er Sqr parseKDindex) :: Parser (L KD)) input 3 -> runLex ((par5er Sqr parseCindex) :: Parser (L C)) input 4 -> runLex ((par5er Ang parseGindex) :: Parser (L G)) input 5 -> runLex ((par5er Ang parsePindex) :: Parser (L P)) input 6 -> runLex ((par5er Sqr parseHMindex) :: Parser (L HM)) input 7 -> runLex ((par5er Sqr parseMindex) :: Parser (L Mon)) input _ -> showHelp -} return () -- | Map logic indexes from [Char] to Int indexToInt :: [Char] -> Int indexToInt c = case c of "K" -> 1; "KD" -> 2 "C" -> 3; "G" -> 4 "P" -> 5; "HM" -> 6 "M" -> 7; _ -> error "Main.indexToInt" -- | Function for displying user help showHelp :: IO() showHelp = do putStrLn ( "Usage:\n" ++ " ./main -p <path> <N> <L1> <L2> .. <LN>\n" ++ " ./main -t <test> <N> <L1> <L2> .. <LN>\n\n" ++ "<N>: a natural number >0 specifing the number of " ++ "combined/embedded logics\n" ++ "<Lx>: each logic can be one of the following cases:\n" ++ " K - K Modal Logic\n" ++ " KD - KD Modal Logic\n" ++ " C - Coalition Logic\n" ++ " G - Graded Modal Logic\n" ++ " P - Probability Logic\n" ++ " HM - Hennessy-Milner Modal Logic\n" ++ " M - Monotonic Logic\n" ++ "<path>: path to input file\n" ++ "<test>: test given as a string\n") -- | Main program function main :: IO() main = do args <- getArgs if (args == [])||(head args == "--help")||(length args < 4) then showHelp else let it:test:n:[] = take 3 args rest = tail.tail.tail $ args in if (length rest < read n) then showHelp else let list = take (read n) rest in case it of "-p" -> do let logics = map indexToInt rest test <- readFile test putStrLn test -- run prover with given input putStrLn $ show logics "-t" -> do let logics = map indexToInt rest putStrLn test -- run prover with given input putStrLn $ show logics _ -> showHelp
nevrenato/Hets_Fork
GMP/Main.hs
gpl-2.0
4,431
0
22
1,824
748
370
378
74
8
module Config where data Config = Config { configRulesDir :: String , configNotifyCMD:: String , configTCPPortsBase:: Int , configConnectionTimeout:: Int } deriving Show defaultConfig = Config { configRulesDir = "/etc/hproxy/rules.d/" , configNotifyCMD = "proxynotify" , configTCPPortsBase = 10000 , configConnectionTimeout = 1200 } -- dummy config loader loadConfig:: String-> IO Config loadConfig fname = return defaultConfig
dambaev/hproxyserver
src/Config.hs
gpl-2.0
476
0
8
104
95
58
37
14
1
{-# LANGUAGE OverloadedStrings #-} module Estuary.Widgets.View where import Reflex import Reflex.Dom hiding (Link) import qualified Data.IntMap.Strict as IntMap import qualified Data.Map.Strict as Map import qualified Data.Text as T import Control.Monad import Control.Monad.IO.Class import Data.Maybe import TextShow import Data.Time import qualified Data.Sequence as Seq import Estuary.Types.Live import Estuary.Types.Definition import Estuary.Types.View import Estuary.Types.EnsembleC import Estuary.Types.Ensemble import Estuary.Types.Context import Estuary.Tidal.Types (TransformedPattern(..)) import Estuary.Types.TextNotation import Estuary.Types.TidalParser import Estuary.Types.RenderInfo import Estuary.Types.Tempo import Estuary.Widgets.W import Estuary.Widgets.Reflex import Estuary.Widgets.Text import Estuary.Widgets.TransformedPattern import Estuary.Widgets.Sequencer import Estuary.Widgets.Roulette import Estuary.Widgets.EnsembleStatus import Estuary.Widgets.Tempo import Estuary.Types.EnsembleRequest import Estuary.Types.EnsembleResponse import Estuary.Types.Hint import Estuary.Widgets.AudioMap import Estuary.Widgets.StopWatchExplorations import Estuary.Widgets.Notepad viewWidget :: MonadWidget t m => Event t [EnsembleResponse] -> View -> W t m (Event t EnsembleRequest) viewWidget er EmptyView = return never viewWidget er (Div c vs) = divClass c $ liftM leftmost $ mapM (viewWidget er) vs viewWidget er (Views vs) = viewWidget er (Div "views" vs) viewWidget er (BorderDiv vs) = viewWidget er (Div "borderDiv" vs) viewWidget er (Paragraph vs) = viewWidget er (Div "paragraph code-font" vs) viewWidget er (Link url vs) = elAttr "a" ("href" =: url) $ viewWidget er (Views vs) viewWidget er (BulletPoints vs) = el "ul" $ do rs <- forM vs $ \v -> el "li" $ viewWidget er v return $ leftmost rs viewWidget er (GridView c r vs) = viewsContainer $ liftM leftmost $ mapM (\v -> divClass "gridChild" $ viewWidget er v) vs where viewsContainer x = elAttr "div" ("class" =: "gridView" <> "style" =: (setColumnsAndRows) ) $ x defineNumRowsOrColumns n = replicate n $ showt ((100.0 :: Double) / (fromIntegral n)) <> "%" setNumColumns = "grid-template-columns: " <> (T.intercalate " " $ defineNumRowsOrColumns c) <> ";" setNumRows = "grid-template-rows: " <> (T.intercalate " " $ defineNumRowsOrColumns r) <> ";" setColumnsAndRows = setNumColumns <> setNumRows viewWidget _ (Text t) = translatableText t >>= dynText >> return never viewWidget er (LabelView z) = zoneWidget z "" maybeLabelText LabelText er labelEditor viewWidget er (StructureView z) = zoneWidget z EmptyTransformedPattern maybeTidalStructure TidalStructure er structureEditor viewWidget er (CodeView z rows) = do whenever <- liftIO $ getCurrentTime ri <- renderInfo let errorDyn = fmap (IntMap.lookup z . errors) ri zoneWidget z (Live (UnspecifiedNotation,"",whenever) L3) maybeTextProgram TextProgram er (textProgramEditor rows errorDyn) viewWidget er (SequenceView z) = zoneWidget z defaultValue maybeSequence Sequence er sequencer where defaultValue = Map.singleton 0 ("",replicate 8 False) viewWidget er EnsembleStatusView = ensembleStatusWidget viewWidget er (RouletteView z rows) = zoneWidget z [] maybeRoulette Roulette er (rouletteWidget rows) viewWidget er (CountDownView z) = zoneWidget z (Holding 60) maybeTimerDownState CountDown er countDownWidget viewWidget er (SandClockView z) = zoneWidget z (Holding 60) maybeTimerDownState CountDown er sandClockWidget viewWidget er (StopWatchView z) = zoneWidget z Cleared maybeTimerUpState StopWatch er stopWatchWidget viewWidget er (SeeTimeView z) = do ahorita <- liftIO $ getCurrentTime zoneWidget z (Tempo {freq= 0.5, time=ahorita, Estuary.Types.Tempo.count=0}) maybeSeeTime SeeTime er visualiseTempoWidget viewWidget er (NotePadView z) = zoneWidget z (0,Seq.fromList[("","")]) maybeNotePad NotePad er notePadWidget viewWidget er TempoView = do ctx <- context iCtx <- sample $ current ctx let initialTempo = (tempo . ensemble . ensembleC) iCtx tempoDelta <- holdDyn initialTempo $ fmapMaybe lastTempoChange er tempoE <- tempoWidget tempoDelta return $ fmap WriteTempo tempoE viewWidget _ (Example n t) = do b <- clickableDiv "example code-font" $ text t bTime <- performEvent $ fmap (liftIO . const getCurrentTime) b hint $ fmap (\et -> ZoneHint 1 (TextProgram (Live (n,t,et) L3))) bTime return never viewWidget _ AudioMapView = do audioMapWidget return never viewWidget _ (IFrame url) = do let attrs = Map.fromList [("src",url), ("style","height:100%"), ("allow","microphone *")] elAttr "iframe" attrs $ return () return never zoneWidget :: (MonadWidget t m, Eq a) => Int -> a -> (Definition -> Maybe a) -> (a -> Definition) -> Event t [EnsembleResponse] -> (Dynamic t a -> W t m (Variable t a)) -> W t m (Event t EnsembleRequest) zoneWidget z defaultA f g ensResponses anEditorWidget = do ctx <- context iCtx <- sample $ current ctx let iDef = IntMap.findWithDefault (g defaultA) z $ zones $ ensemble $ ensembleC iCtx let iValue = maybe defaultA id $ f iDef let resetValue = g defaultA let deltas = fmapMaybe (lastEditOrResetInZone resetValue z) ensResponses let deltas' = fmapMaybe f deltas dynUpdates <- holdDyn iValue deltas' variableFromWidget <- anEditorWidget dynUpdates return $ (WriteZone z . g) <$> localEdits variableFromWidget
d0kt0r0/estuary
client/src/Estuary/Widgets/View.hs
gpl-3.0
5,402
0
16
831
1,861
947
914
107
1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE BangPatterns, LambdaCase, ApplicativeDo, OverloadedStrings, ScopedTypeVariables, DeriveFunctor, DeriveTraversable, FlexibleInstances, FlexibleContexts #-} module Main (main) where import Helpers import Data.Set as Set (toList) import TokenAwareParser(ParseRule(..),ParseAtom(..),tripleStoreToParseRules,fmap23,Atom(..),freshTokenSt,parseText,deAtomize,deAtomizeString,freshenUp,parseOf,runToken,Token,LinePos,showPos,builtIns,makeQuoted) import RuleSet(oldNewSystem,prePostRuleSet,Rule(..),Expression(..)) import System.IO (stderr) import System.Exit (exitFailure) import System.Console.Terminal.Size (size,width) import BaseState import qualified Data.Map as Map main :: IO () main = do as <- getChunks =<< getArgs evalStateT (forM_ as (uncurry doCommand)) (initialstate as) where getChunks' [] = ([],[]) getChunks' (a:as) = let (res,spl) = getChunks' as in case a of ('-':cmd) -> ((pack cmd,spl):res,[]) _ -> (res,pack a:spl) getChunks as = case getChunks' as of (r,[]) -> return r (_,_ ) -> finishError "First argument should be a command, that is: it should start with '-'" popFromLst :: [Triple (Atom Text) (Atom Text)] -> Population popFromLst = TR . storeFromLst storeFromLst :: [Triple (Atom Text) (Atom Text)] -> FullStore storeFromLst = foldl' (\v w -> fst (insertTriple w v)) mempty newtype Population = TR { getPop :: FullStore} type FullStore = TripleStore (Atom Text) (Atom Text) type FullParser = [ParseRule (Atom Text) Text Text] type FullRules = [Rule (TransactionVariable (Atom Text)) (Atom Text)] type SpiegelState a = StateT (Map Text Population) IO a doCommand :: Text -> [Text] -> SpiegelState () doCommand cmd = findWithDefault (\_ -> lift$ finishError ("Not a valid command: "<>cmd<>"\nGet a list of commands using: -h")) cmd lkp' where lkp' = fmap snd (fromListWith const commands) showUnexpected :: Maybe (Token (LinePos Text, Bool)) -> Text -> Maybe Text -> Either Text x showUnexpected tk expc mby = Left $ "Parse error, unexpected "<> (showPs tk)<>"\n Expecting: "<> expc <> (case mby of {Nothing -> "";Just v ->"\n mby(TODO: fix me into something more descriptive):"<> v}) where showPs (Just tk') = (showPos id . fst . runToken) tk' showPs _ = "end of file" parse :: (Monad m, IsString z, Ord z, Show z) => [ParseRule (Atom Text) Text z] -> Text -> SpiegelState (StateT Int m [Triple (Atom Text) (Atom Text)]) parse p = eitherError id . parseText id (parseOf builtIns (p,"Start")) showUnexpected commands :: [ ( Text, ( Text, [Text] -> SpiegelState () ) ) ] commands = [ ( "i" , ( "parse file as input" , (\files -> parseAsIn files))) , ( "parse" , ( "Read the file mentioned in the first argument, use the parser mentioned in the second (default: population). Put the result in the final argument." , let pr f p' r = do txt <- liftIO$ Helpers.readFile (unpack f) p <- getParser p' trps <- parse p txt overwrite r (TR . storeFromLst . runIdentity . unFresh $ trps) return () in \case [] -> liftIO$finishError "-parse needs a file-name as argument" [f] -> pr f "population" "population" [f,p] -> pr f p "population" [f,p,r] -> pr f p r _ -> liftIO$finishError "-parse cannot take more than three arguments")) , ( "Parse" , ( "Read the file mentioned in the first argument, use the parser mentioned in the second (default: population), and apply the rules in it. Put the result in the final argument." , let pr f p' r' = do txt <- liftIO$ Helpers.readFile (unpack f) p <- getParser p' trps <- parse p txt r <- getRules p' res <- unFresh (ruleConsequences r =<< trps) overwrite r' (TR res) return () in \case [] -> liftIO$finishError "-Parse needs a file-name as argument" [f] -> pr f "population" "population" [f,p] -> pr f p "population" [f,p,r] -> pr f p r _ -> liftIO$finishError "-Parse cannot take more than three arguments")) , ( "h" , ( "display this help" , \_ -> liftIO (Helpers.putStrLn . helpText =<< size))) , ( "list" , ( "show a list of all triple-stores" , noArgs "list"$ lift . sequenceA_ . map Helpers.putStrLn . keys =<< get )) , ( "show" , ( "display the triples as a list" , eachPop (lift . Helpers.putStrLn . prettyPPopulation))) , ( "showP" , ( "display the triples as a set of parse-rules" , eachDo (lift . Helpers.putStrLn . prettyPParser) getParser)) , ( "showR" , ( "display the triples as a set of parse-rules" , eachDo (lift . Helpers.putStrLn . prettyPRules) getRules)) , ( "showTS" , ( "display for populations generated with -collect" , eachDo (lift . Helpers.putStrLn . prettyPPopulations) (\v -> eitherError id . makePops =<< retrieve v) )) , ( "print" , ( "Print the second argument(s) using syntax of the first argument. Missing arguments default to \"population\". Prints to stdout" , \args -> let (synt,pops) = case args of [] -> ("population",["population"]) [x] -> (x,["population"]) (x:xs) -> (x,xs) in do parser <- getParser synt pop <- mconcat <$> mapM (fmap getList . retrieve) pops printPop parser (popFromLst pop) ) ) , ( "count" , ( "count the number of triples" , eachPop (lift . Prelude.putStrLn . show . length . getList))) , ( "asParser" , ( "turn the population into the parser for -i" , noArgs "asParser" $ do parser <- apply "asParser" ["population"] overwrite "parser" (TR parser) overwrite "population" (TR parser))) , ( "apply" , ( "apply the rule-system of first argument to the (union of the) system(s) in the second argument(s). Put the result in the last argument. Uses \"population\" by default." , \args -> let (rsys,from,targ) = case args of [] -> ("population",["population"],"population") [x] -> (x,["population"],"population") [x,y] -> (x,[y],"population") (x:xs) -> (x,init xs,last xs) in overwrite targ . TR =<< apply rsys from )) , ( "collect" , ( "collect the current state of amperspiegel and put the result into the population" , oneArg "collect" (\arg -> overwrite arg . popFromLst . popsToPop =<< get) )) , ( "distribute" , ( "set the population as the current state of amperspiegel" , oneArg "distribute" (\arg -> put =<< eitherError id . makePops =<< retrieve arg) )) ] where parseAsIn files = do txts <- lift$ mapM (Helpers.readFile . unpack) files p <- getParser "parser" trps <- traverse (parse p) txts r <- getRules "parser" res <- unFresh (ruleConsequences r . mconcat =<< sequence trps) overwrite "population" (TR res) return () pass f v = const v <$> f v printPop :: FullParser -> Population -> SpiegelState () printPop pr (TR pop) = sequenceA_ [ (liftIO . traverse Helpers.putStrLn) =<< matchStart pa | pa <- findInMap "Start" pm ] -- should actually only print one where -- parse map based on all parse rules (faster lookup) pm :: Map Text [[ParseAtom (Atom Text) Text Text]] pm = Map.fromListWith merge [(k,[v]) | ParseRule k v <- ParseRule "StringAndOrigin" [(ParseRef "string" "String" Nothing)] : pr] merge [] l = l merge l [] = l merge o1@(h1:l1) o2@(h2:l2) = if numRefs h1 < numRefs h2 then h2 : merge o1 l2 else h1 : merge l1 o2 numRefs lst = length [() | ParseRef _ _ _ <- lst] matchStart :: [ParseAtom (Atom Text) Text Text] -> SpiegelState [Text] matchStart [] = pure [] matchStart (ParseString v:r) = map ((v<>" ")<>) <$> matchStart r matchStart (ParseRef rel cont sep:r) = sequence [ mappend . intercalate sep' <$> sequence h <*> (intercalate " " <$> sequence r') | (k,v@(_:_))<-getRel pop rel -- if there's no sep, do want to make sure that (length v == 1)? , Just h <- [traverse (printAs cont) v] , let sep' = case sep of {Nothing -> " "; Just v' -> v'} , Just r' <- [traverse (match k) r] ] printAs :: Text -> Atom Text -> Maybe (SpiegelState Text) printAs cont v = case cont of "String" -> Just$ eitherError (mappend "Not a String: ".showT) $ deAtomizeString v "UnquotedString" -> Just$ eitherError (mappend "Not a String: ".showT) $ deAtomize v "QuotedString" -> Just$ fmap (showT . unpack) . eitherError (mappend "Not a String: ".showT) $ deAtomize v _ -> pickBest -- print the first of all matching patterns [ sequence r | pa <- findInMap cont pm, Just r <- [traverse (match v) pa]] match :: Atom Text -> ParseAtom (Atom Text) Text Text -> Maybe (SpiegelState Text) match _ (ParseString v) = Just (pure v) -- maybe throw an error upon multiple match v (ParseRef rel cont sep) = case (forEachOf pop rel v,sep) of ([],_) -> Nothing -- no match (h:_,Nothing) -> (printAs cont h) (hs,Just s) -> (Just . fmap (intercalate s) . sequence . catMaybes . map (printAs cont)) hs pickBest :: [SpiegelState [Text]] -> Maybe (SpiegelState Text) pickBest [] = Nothing pickBest (h:tl) = Just$ chooseBest (pickBest tl) =<< h chooseBest (Just v) [] = v chooseBest _ h = return (intercalate " " h) ruleConsequences :: forall x. MonadIO x => FullRules -> [Triple (Atom Text) (Atom Text)] -> StateT Int x FullStore ruleConsequences r v = fst <$> (pass (liftIO . renameWarnings) =<< oldNewSystem (liftIO$finishError "Error occurred in applying rule-set: rules & data lead to an inconsistency.") freshTokenSt r v) -- renameAndAdd v (v',n) = (storeFromLst . (map (fmap (findSelfMap n)) v <>) . getList . TR) v' apply :: Text -> [Text] -> SpiegelState FullStore apply rsys from = do pops <- mapM (fmap getList . retrieve) from let pop = mconcat <$> traverse (freshenUp freshTokenSt) pops r <- getRules rsys unFresh (ruleConsequences r =<< pop) noArgs :: Text -> SpiegelState () -> [t] -> SpiegelState () noArgs s f = \case {[] -> f;_->lift$finishError (s <> " takes no arguments")} oneArg :: Text -> (Text -> SpiegelState ()) -> [Text] -> SpiegelState () oneArg s f = \case [] -> f "population"; [i] -> f i v->lift$finishError (s <> " takes one argument (given: "<>showT (length v)<>")") eachPop :: (Population -> SpiegelState ()) -> [Text] -> SpiegelState () eachPop f = eachDo f retrieve eachDo :: (a -> SpiegelState ()) -> (Text -> SpiegelState a) -> ([Text] -> SpiegelState ()) eachDo f g = \case [] -> f =<< g "population" l -> mapM_ (\v -> f =<< g v) l renameWarnings (_,res) = sequenceA_ [ Helpers.hPutStrLn stderr ("Application of rules caused "<>showT v<>" to be equal to "<> showT r) | (v,r) <- Map.toList res , case v of {Fresh _ -> False; _ -> True}] helpText Nothing = mconcat [ s <> "\t" <> d <> "\n" | (s,(d,_)) <- commands ] helpText (Just wdw) = "These are the switches you can use: "<> "\n\n" <> mconcat [ pad maxw (" " <> s) <> wrap 0 (twords d) <>"\n" | (s,(d,_)) <- commands] where maxw :: Int maxw = 3 + foldr max 0 (map (tlength . fst) commands) wrap _ [] = "" wrap cur (w:r) = case tlength w + 1 of v | cur + v > lim -> "\n " <> pad maxw "" <> w <> wrap v r v -> " "<>w<>wrap (cur + v) r lim = max 20 (width wdw - maxw) unFresh :: Monad m => StateT Int m a -> m a unFresh v = evalStateT v 0 makePops :: Population -> Either Text (Map Text Population) makePops (TR ts) = fmap popFromLst . fromListWith (++) <$> traverse toTripList (getRel ts "contains") where asTriple :: Atom Text -> Either Text (Triple (Atom Text) (Atom Text)) asTriple trp = Triple <$> forOne (Left "'relation' must be a function") ts "relation" trp pure <*> forOne (Left "'source' must be a function") ts "source" trp pure <*> forOne (Left "'target' must be a function") ts "target" trp pure toTripList :: (Atom Text, [Atom Text]) -> Either Text (Text, [(Triple (Atom Text) (Atom Text))]) toTripList (p,tgt) = (,) <$> (case deAtomize p of {Left v -> Left (showT v);Right v -> Right v}) <*> traverse asTriple tgt popsToPop :: Map Text Population -> [Triple (Atom Text) (Atom Text)] popsToPop = concat . runIdentity . unFresh . traverse mkContains . Map.toList where mkContains (nm,p) = do tps <- freshenUp freshTokenSt (getList p) concat <$> (traverse (\(Triple n s t) -> (\fr -> [ Triple "contains" (makeQuoted nm) fr , Triple "relation" fr n , Triple "source" fr s , Triple "target" fr t ]) <$> freshTokenSt) tps) prettyPParser :: FullParser -> Text prettyPParser [] = "" prettyPParser o@(ParseRule t _:_) = t <> " := " <> Helpers.intercalate ("\n "<>pad (tlength t) ""<>"| ") res <> "\n" <> prettyPParser tl where (res,tl) = mapsplit (\(ParseRule t' lst) -> if t == t' then Just (pp lst) else Nothing) o pp = Helpers.intercalate ", " . map showT mapsplit _ [] = ([],[]) mapsplit f o'@(a:r) = case f a of Just v -> let (rs,rm) = mapsplit f r in (v:rs,rm) Nothing -> ([],o') prettyPRules :: FullRules -> Text prettyPRules = mconcat . map (\v -> pRule v <> "\n") where pRule (Subset l r) = pExp l<>" |- "<>pExp r pExp (ExprAtom r) = showT r pExp I = "I" pExp (Compose e1 e2) = "("<>pExp e1<>";"<>pExp e2<>")" pExp (Conjunction e1 e2) = "("<>pExp e1<>" /\\ "<>pExp e2<>")" pExp (Flp e1) = pExp e1<>"~" pExp Bot = "Bot" pExp (Pair a1 a2) = "< "<>showT a1<>" , "<>showT a2<>" >" prettyPPopulation :: Population -> Text prettyPPopulation v = Helpers.unlines [ showPad w1 n <> "\8715 "<>showPad w2 s<>" \8614 "<>showT t | Triple n s t <- l] where (w1,w2) = foldr max2 (0,0) l l = getList v max2 (Triple a b _) (al,bl) = (max al (length (show a)), max bl (length (show b))) prettyPPopulations :: (Map Text Population) -> Text prettyPPopulations v = intercalate "\n , " [ "( "<>showT k<>"\n , [ " <> intercalate "\n , " [ showT n <> " \8715 "<>showT s<>" \8614 "<>showT t | Triple n s t <- getList p ] <> "\n ])" | (k,p)<-Map.toList v] showPad :: forall a. Show a => Int -> a -> Text showPad w = pad w . showT pad :: Int -> Text -> Text pad w s = let x = w - (tlength) s in s <> pack (Prelude.take x (repeat ' ')) getList :: Population -> [Triple (Atom Text) (Atom Text)] getList x = mconcat . map getTripls . Map.toList $ getPop x where getTripls (a,(mp,_)) = [(Triple nm a b) | (nm,bs) <- Map.toList mp, b<-Set.toList bs] overwrite :: Monad b => Text -> Population -> StateT (Map Text Population) b () overwrite s p = modify (insert s p) retrieve :: Monad b => Text -> StateT (Map Text Population) b Population retrieve s = do mp <- get return $ findWithDefault (popFromLst []) s mp getParser :: Text -> SpiegelState FullParser getParser s = do mp <- retrieve s unAtomize =<< tripleStoreToParseRules (\m -> liftIO$finishError ("TripleStoreToParseRules could not make a parser out of the population: "<>m)) pure (getPop mp) where unAtomize :: [ParseRule (Atom Text) (Atom Text) (Atom Text)] -> SpiegelState FullParser unAtomize = traverse (eitherError (("error: "<>) . showT) . fmap23 deAtomize deAtomize) eitherError ::(MonadIO m) => (t -> Text) -> Either t a -> m a eitherError sh (Left a) = liftIO$finishError (sh a) eitherError _ (Right a) = pure a getRules :: Text -> SpiegelState FullRules getRules s = do mp <- retrieve s prePostRuleSet (liftIO$finishError "tripleStoreToRuleSet could not make a set of rules out of the population") pure (getPop mp) finishError :: Text -> IO a finishError s = hPutStrLn stderr s >> exitFailure selfZip :: Monad m => [a] -> StateT Int m [((a, Atom y), Maybe (Atom y))] selfZip lst = do l <- traverse (\v -> (,) v <$> freshTokenSt) lst return (zip l (Nothing:map (Just . snd) l)) parseSwitch :: Monad m => (((a, [a]), Atom a), Maybe (Atom a)) -> StateT Int m [Triple (Atom Text) (Atom a)] parseSwitch o = (parseArgument "cur" id (makeQuoted . fst) o ++) . concatMap (parseArgument "first" (const (snd (fst o))) makeQuoted) <$> selfZip (snd (fst (fst o))) where parseArgument fs c q (arg,prev) = [ case prev of Nothing -> Triple fs (c (snd arg)) (snd arg) Just v -> Triple "next" v (snd arg) , Triple "string" (snd arg) (q (fst arg)) ] -- TODO: think of a way to get this out of the source code initialstate :: [(Text,[Text])] -> Map Text Population initialstate switches = fromListWith const $ [ ( "switches" , popFromLst . runIdentity . unFresh . fmap concat $ do sw <- selfZip switches traverse parseSwitch sw ) ] ++ map (fmap popFromLst) baseState
sjcjoosten/amperspiegel
src/amperspiegel.hs
gpl-3.0
18,402
0
20
5,585
6,740
3,436
3,304
356
36
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} -------------------------------------------------------------------------------- -- | -- Module: Game -- -- This is a very simple implementation of the rules of John Conway's -- Game of Life. It uses `Repa' arrays and `Stencil' functionality. -- -- This is based on slides at -- <http://illustratedhaskell.org/index.php/2011/09/24/conways-game-of-life-with-repa/> module Game where import Data.Array.Repa ((:.) (..), Z (..), (!)) import qualified Data.Array.Repa as R import Data.Array.Repa.Stencil (Boundary (..), Stencil) import Data.Array.Repa.Stencil.Dim2 type Grid = R.Array R.U R.DIM2 Int -- | A stencil that calculates a cell's neighbor count. neighbors :: Stencil R.DIM2 Int neighbors = [stencil2|1 1 1 1 0 1 1 1 1|] -- | A blank width × height grid. blank :: Int -> Int -> Grid blank width height = R.fromListUnboxed (Z :. width :. height) $ replicate (width * height) 0 -- | Represents the rules of the game of life for each cell. transition :: Int -> Int -> Int transition 1 2 = 1 transition 1 3 = 1 transition 1 _ = 0 transition 0 3 = 1 transition 0 _ = 0 -- | Represents a single generation of life. step :: Grid -> Grid step grid = R.computeUnboxedS . R.zipWith transition grid $ mapStencil2 (BoundConst 0) neighbors grid -- | Flips the value at the given point. If the value is 0, it becomes -- 1; otherwise, it becomes 0. modify :: (Int, Int) -> Grid -> Grid modify p grid = R.computeUnboxedS $ R.fromFunction (R.extent grid) go where go i@(Z :. x' :. y') | p == (x', y') = if grid ! i == 0 then 1 else 0 | otherwise = grid ! i -- | Returns a list of points corresponding to which pixel should be drawn. render :: Grid -> [(Int, Int)] render grid = [(x, y) | x <- [0..width - 1], y <- [0..height - 1], grid ! (Z :. x :. y) /= 0] where Z :. width :. height = R.extent grid -- ** Interesting Start States -- | The r pentomino is a "methuselah", a simple pattern that results -- in a lot of activity—1103 generations from *five* starting cells! rPentomino :: Grid rPentomino = foldr modify (blank 400 400) [(99, 100), (100, 99), (100, 100), (100, 101), (101, 99)] -- | Starts a glider in the top lefhand corner that moves towards the -- bottom righthand corner. glider :: Grid glider = foldr modify (blank 400 400) [(2, 0), (3, 1), (1, 2), (2, 2), (3, 2)]
TikhonJelvis/Reactive-Life
src/Game.hs
gpl-3.0
2,529
0
11
582
670
389
281
32
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} -- This file is the source code for the tests. You're not supposed to be here! module Main where import Data.Foldable ( toList, ) import Data.List ( intersperse, ) import Test.Hspec ( Spec, describe, hspec, it, shouldSatisfy, ) import Test.QuickCheck ( Arbitrary, Property, (==>), arbitrary, arbitrarySizedNatural, choose, listOf, property, ) import qualified A1Nat as N import qualified A2List as L import qualified A3BreadButter as B isInverseOf :: (Arbitrary a, Eq a, Show a) => (b -> a) -> (a -> b) -> Property isInverseOf f g = property $ \a -> f (g a) == a itIsAssociative :: (Arbitrary a, Eq a, Show a) => (a -> a -> a) -> Spec itIsAssociative f = it "is associative" $ property $ \a b c -> f (f a b) c == f a (f b c) itIsCommutative :: (Arbitrary a, Show a, Eq b) => (a -> a -> b) -> Spec itIsCommutative f = it "is commutative" $ property $ \a b -> f a b == f b a itIsInvolutory :: (Arbitrary a, Show a, Eq a) => (a -> a) -> Spec itIsInvolutory f = it "is involutory" $ f `isInverseOf` f itIsIrreflexive :: (Arbitrary a, Show a) => (a -> a -> Bool) -> Spec itIsIrreflexive f = it "is irreflexive" $ property $ \a -> not $ f a a itIsReflexive :: (Arbitrary a, Show a) => (a -> a -> Bool) -> Spec itIsReflexive f = it "is reflexive" $ property $ \a -> f a a itIsTransitive :: (Arbitrary a, Show a) => (a -> a -> Bool) -> Spec itIsTransitive f = it "is transitive" $ property $ \a b c -> f a b && f b c ==> f a c main :: IO () main = hspec $ do describe "Nat.==" $ do it "tests *arbitrary* Nats for equality" $ property $ \x y -> (N.S x == N.S y) == (x == y) itIsCommutative ((==) :: N.Nat -> N.Nat -> Bool) itIsReflexive ((==) :: N.Nat -> N.Nat -> Bool) describe "Nat.isZ" $ it "checks if *arbitrary* Nats are zero" $ property $ \n -> N.isZ n == (n == N.Z) describe "Nat.toNat" $ do it "turns *arbitrary* Ints into Nats" $ property $ \n -> N.toNat n == toNat n it "is the inverse of Nat.fromNat" $ N.toNat `isInverseOf` N.fromNat describe "Nat.fromNat" $ it "turns *arbitrary* Nats into Ints" $ property $ \n -> N.fromNat (N.S n) == 1 + N.fromNat n describe "Nat.predNat" $ do it "preceed *arbitrary* Nats" $ property $ \n -> N.predNat (N.S n) == n it "is the inverse of Nat.succNat" $ N.predNat `isInverseOf` N.succNat describe "Nat.succNat" $ it "succeed *arbitrary* Nats" $ property $ \n -> N.succNat n == N.S n describe "Nat.plus" $ do it "adds *arbitrary* Nats" $ property $ \x y -> N.plus (N.S x) y == N.S (N.plus x y) itIsAssociative N.plus itIsCommutative N.plus describe "Nat.times" $ do it "multiplies *arbitrary* Nats" $ property $ \x y -> N.times (N.S x) y == N.plus y (N.times x y) itIsAssociative (\(Small x) (Small y) -> Small (N.times x y)) itIsCommutative N.times describe "Nat.powerOf" $ it "raises *arbitrary* Nats to the power of *arbitrary* Nats" $ property $ \(Small b) (Tiny e) -> N.powerOf b (N.S e) == N.times b (N.powerOf b e) describe "Nat.minus" $ do it "subtracts *arbitrary* Nats" $ property $ \x y -> N.minus (N.S x) (N.S y) == N.minus x y it "is the inverse of Nat.plus" $ property $ \a -> (`N.minus` a) `isInverseOf` (`N.plus` a) describe "Nat.lteNat" $ do it "finds out if an *arbitrary* Nat is smaller than or equal to an *arbitrary* Nat" $ property $ \x y -> N.lteNat (N.S x) (N.S y) == N.lteNat x y itIsReflexive N.lteNat itIsTransitive N.lteNat describe "Nat.ltNat" $ do it "finds out if an *arbitrary* Nat is smaller than an *arbitrary* Nat" $ property $ \x y -> N.ltNat x y == N.lteNat (N.S x) y itIsIrreflexive N.ltNat itIsTransitive N.ltNat describe "Nat.gteNat" $ do it "finds out if an *arbitrary* Nat is larger than or equal to an *arbitrary* Nat" $ property $ \x y -> N.gteNat x y == N.lteNat y x itIsReflexive N.gteNat itIsTransitive N.gteNat describe "Nat.gtNat" $ do it "finds out if an *arbitrary* Nat is greater than an *arbitrary* Nat" $ property $ \x y -> N.gtNat x y == N.ltNat y x itIsIrreflexive N.gtNat itIsTransitive N.gtNat describe "Nat.minNat" $ do it "finds out which out of two *arbitrary* Nats is the smaller" $ property $ \x y -> N.minNat x (N.plus x y) == x itIsAssociative N.minNat itIsCommutative N.minNat describe "Nat.maxNat" $ do it "finds out which out of two *arbitrary* Nats is the bigger" $ property $ \x y -> N.maxNat x (N.plus x y) == N.plus x y itIsAssociative N.maxNat itIsCommutative N.maxNat describe "Nat.compare" $ it "compares *arbitrary* Nats" $ property $ \x y -> compare (N.S x) (N.S y) == compare x y describe "Nat.fact" $ it "calculates an *arbitrary* factorial" $ property $ \(Tiny n) -> N.fact (N.S n) == N.times (N.S n) (N.fact n) describe "Nat.fib" $ it "calculates an *arbitrary* fibonacci sequence number" $ property $ \(Small n) -> N.fib (N.S (N.S n)) == N.plus (N.fib (N.S n)) (N.fib n) describe "List.append" $ do it "appends *arbitrary* Lists" $ property $ \(IntList xs) (IntList ys) -> L.append xs ys == case xs of L.Nil -> ys L.Cons z zs -> L.append (L.Cons z zs) ys itIsAssociative (L.append :: L.List Int -> L.List Int -> L.List Int) describe "List.headList" $ it "gets the head of an *arbitrary* List" $ property $ \(IntList xs) -> L.headList xs == case xs of L.Nil -> L.Nope (L.Cons y _) -> L.Have y describe "List.tailList" $ it "gets the tail of an *arbitrary* List" $ property $ \(IntList xs) -> L.tailList xs == case xs of L.Nil -> L.Nope (L.Cons _ ys) -> L.Have ys describe "List.initList" $ it "gets the init of an *arbitrary* List" $ property $ \(IntList xs) -> L.initList xs == case xs of L.Nil -> L.Nope L.Cons y L.Nil -> L.Nope L.Cons y ys -> L.Have (go y ys) where go _ L.Nil = L.Nil go z (L.Cons zz zs) = L.Cons z (go zz zs) describe "List.unconsList" $ do it "unconses an *arbitrary* List" $ property $ \(IntList xs) -> L.unconsList xs == case xs of L.Nil -> L.Nope L.Cons y ys -> L.Have (y, ys) it "is the inverse of List.Cons" $ ((\(L.Have x) -> x) . L.unconsList) `isInverseOf` (\(y, ys) -> L.Cons (y :: Int) ys) describe "List.nullList" $ it "checks if an *arbitrary* List is null" $ property $ \(IntList xs) -> L.nullList xs == (xs == L.Nil) describe "List.sumList" $ it "sums an *arbitrary* List of Nats" $ property $ \xs -> L.sumList xs == case xs of L.Nil -> N.Z L.Cons y ys -> N.plus y (L.sumList ys) describe "List.productList" $ it "calculates the product of an *arbitrary* List of Nats" $ property $ \(SmallList xs) -> L.productList xs == case xs of L.Nil -> N.S N.Z L.Cons y ys -> N.times y (L.productList ys) describe "List.maximumList" $ it "gets the greatest element of an *arbitrary* List of Nats" $ property $ \xs -> L.maximumNatList xs == case xs of L.Nil -> L.Nope _ -> L.Have . maximum . toList $ xs describe "List.minimumList" $ it "gets the smallest element of an *arbitrary* List of Nats" $ property $ \xs -> L.minimumNatList xs == case xs of L.Nil -> L.Nope _ -> L.Have . minimum . toList $ xs describe "List.takeList" $ it "takes the given number of elements from the head of an *arbitrary* List" $ property $ \n (IntList xs) -> toList (L.takeList n xs) == take n (toList xs) describe "List.dropList" $ it "drops the given number of elements from the head of an *arbitrary* List" $ property $ \n (IntList xs) -> toList (L.dropList n xs) == drop n (toList xs) describe "List.splitList" $ it "splits an *arbitrary* List on an *arbitrary* index" $ property $ \n (IntList xs) -> L.splitList n xs == (L.takeList n xs, L.dropList n xs) describe "List.reverseList" $ do it "reverses an *arbitrary* List" $ property $ \(IntList xs) -> L.reverseList xs == case xs of L.Nil -> L.Nil L.Cons y ys -> L.append (L.reverseList ys) (L.Cons y L.Nil) itIsInvolutory (L.reverseList :: L.List Int -> L.List Int) describe "List.intersperseList" $ it "intersperses an *arbitrary* element to an *arbitrary* List" $ property $ \x (IntList xs) -> L.intersperseList x xs == case xs of L.Nil -> L.Nil L.Cons y ys -> L.Cons y (L.Cons x (L.intersperseList x ys)) describe "List.concatList" $ it "concatenates an *arbitrary* List" $ property $ \(IntListList xs) -> L.concatList xs == case xs of L.Nil -> L.Nil L.Cons ys L.Nil -> ys L.Cons ys zs -> L.append ys (L.concatList zs) describe "List.intercalateList" $ it "intercalates an *arbitrary* List with an *arbitrary* List" $ property $ \(IntList xs) (IntListList ys) -> L.intercalateList xs ys == L.concatList (L.intersperseList xs ys) describe "List.zipList" $ it "zips two *arbitrary* Lists" $ property $ \(IntList xs) (IntList ys) -> L.zipList xs ys == case xs of L.Nil -> L.Nil L.Cons z zs -> case ys of L.Nil -> L.Nil L.Cons zz zzs -> L.Cons (z, zz) (L.zipList zs zzs) describe "List.elemList" $ it "checks if an *arbitrary* element is in an *arbitrary* List" $ property $ \x (IntListList xs) -> L.elemList x xs == elem x (toList xs) describe "BreadButter.mapList" $ it "maps a function on an *arbitrary* list" $ property $ \(xs :: [Int]) -> B.mapList (odd . (* 6)) xs == map (odd . (* 6)) xs describe "BreadButter.filterList" $ it "filters an *arbitrary* list on a predicate" $ property $ \(xs :: [Int]) -> B.filterList (> 5) xs == filter (> 5) xs describe "BreadButter.add42List" $ it "maps (+ 42) to an *arbitrary* list of Ints" $ property $ \xs -> B.add42List xs == map (+ 42) xs describe "BreadButter.invertBoolList" $ do it "inverts an arbitrary list of Booleans" $ property $ \xs -> B.invertBoolList xs == map not xs itIsInvolutory B.invertBoolList describe "BreadButter.geq42List" $ it "filters an *arbitrary* list of Ints for any Int >42" $ property $ \xs -> B.geq42List xs == filter (> 42) xs describe "BreadButter.onlyTrueList" $ it "filters out any False values from an *arbitrary* list of Bools" $ property $ \xs -> B.onlyTrueList xs == filter (== True) xs describe "BreadButter.times2" $ it "multiplies an *arbitrary* Int with 2" $ property $ \n -> B.times2 n == n * 2 describe "BreadButter.take4" $ it "takes 4 elements from the head of an *arbitrary* list" $ property $ \(xs :: [Int]) -> B.take4 xs == take 4 xs describe "BreadButter.intersperse0" $ it "intersperses 0 to an *arbitrary* list of Ints" $ property $ \xs -> B.intersperse0 xs == intersperse 0 xs describe "BreadButter.take4intersperse0" $ it "takes 4 elements from the head of an *arbitrary* list of Ints, then intersperses 0 to the resulting list" $ property $ \xs -> B.take4intersperse0 xs == (take 4 . intersperse 0 $ xs) describe "BreadButter.t4i0t2" $ it "takes 4 elements from the head of an *arbitrary* list of Ints, then intersperses 0 to the resulting list, and finally multiplies every element with 2" $ property $ \xs -> B.t4i0t2 xs == (take 4 . intersperse 0 . map (* 2) $ xs) describe "BreadButter.letterT" $ it "filters out any value that is not 't' or 'T' from an *arbitrary* String" $ property $ \xs -> B.letterT xs == (filter (== 't') . filter (== 'T') $ xs) describe "BreadButter.notElemList" $ it "checks if an *arbitrary* element is not in an *arbitrary* list" $ property $ \x (xs :: [Int]) -> B.notElemList x xs == notElem x xs describe "BreadButter.lengthFold" $ it "calculates the length of an *arbitrary* list" $ property $ \(xs :: [Int]) -> B.lengthFold xs == length xs describe "BreadButter.reverseFold" $ it "reverses an *arbitrary* list" $ property $ \(xs :: [Int]) -> B.reverseFold xs == reverse xs describe "BreadButter.appendFold" $ it "appends *arbitrary* lists" $ property $ \(xs :: [Int]) (ys :: [Int]) -> B.appendFold xs ys == xs ++ ys describe "BreadButter.mapFold" $ it "maps a function on an *arbitrary* list" $ property $ \(xs :: [Int]) -> B.mapFold (odd . (* 6)) xs == map (odd . (* 6)) xs describe "BreadButter.filterFold" $ it "filters an *arbitrary* list on a predicate" $ property $ \(xs :: [Int]) -> B.filterFold (> 5) xs == filter (> 5) xs toNat :: Int -> N.Nat toNat n | n > 0 = N.S (toNat (n - 1)) | otherwise = N.Z newtype TinyNats = Tiny N.Nat deriving (Eq, Show) newtype SmallNats = Small N.Nat deriving (Eq, Show) newtype IntList = IntList (L.List Int) deriving (Eq, Show) newtype IntIntList = IntListList (L.List (L.List Int)) deriving (Eq, Show) newtype TinyList = TinyList (L.List N.Nat) deriving (Eq, Show) newtype SmallList = SmallList (L.List N.Nat) deriving (Eq, Show) instance Arbitrary N.Nat where arbitrary = toNat <$> arbitrarySizedNatural instance Arbitrary (TinyNats) where arbitrary = Tiny . toNat <$> choose (0, 3) instance Arbitrary (SmallNats) where arbitrary = Small . toNat <$> choose (0, 9) instance (Arbitrary a) => Arbitrary (L.List a) where arbitrary = (foldr L.Cons L.Nil :: [a] -> L.List a) <$> arbitrary instance Arbitrary IntList where arbitrary = IntList <$> arbitrary instance Arbitrary IntIntList where arbitrary = IntListList <$> arbitrary instance Arbitrary TinyList where arbitrary = TinyList . foldr L.Cons L.Nil <$> listOf (toNat <$> choose (0, 3)) instance Arbitrary SmallList where arbitrary = SmallList . foldr L.Cons L.Nil <$> listOf (toNat <$> choose (0, 3))
alexander-b/thug-beginners
lessonA/Tests.hs
gpl-3.0
14,467
0
20
3,890
5,224
2,555
2,669
314
18
module Biobase.Fasta.Types where import Control.DeepSeq import Control.Lens import Data.ByteString.Char8 (ByteString) import Data.Data import GHC.Generics -- | data FHD = FH ByteString | FD ByteString newtype RawFastaEntry = RawFastaEntry { _rawFastaEntry ∷ ByteString } deriving (Show,Eq,Ord,Data,Typeable,Generic) makeLenses ''RawFastaEntry -- | 'StreamEvent's are chunked pieces of data, where the raw data is -- a strict @ByteString@. Each element also retains information on the -- first and last line and column (via 'streamLines') that are part of this -- chunk. data StreamEvent -- | A Header event, multiple header events signal that the header name -- was longer than the chunk size. = StreamHeader { streamHeader :: !ByteString, streamLines :: !LineInfo } -- | A data event. We keep a pointer to the previous chunk (which is -- useful for some algorithms). The chunk is free of newlines! | StreamFasta { streamFasta :: !ByteString, prevStreamFasta :: !ByteString, streamLines :: !LineInfo, streamHeader :: !ByteString } deriving (Show,Eq,Ord,Data,Typeable,Generic) instance NFData StreamEvent -- | Complete information on line and column start and end for a chunk. -- -- TODO This is a 1-based format? Lets use the BiobaseTypes facilities! data LineInfo = LineInfo { firstLine :: !Int -- ^ first line for this chunk @(lines in complete file!)@ , firstCol :: !Int -- ^ first column in first line for this chunk , lastLine :: !Int -- ^ last line for this chunk @(lines in complete file!)@ , lastCol :: !Int -- ^ last column in last line for this chunk , firstIndex :: !Int -- ^ first index in this fasta block. Counts just the number of symbols in the @Fasta@ payload. } deriving (Show,Eq,Ord,Data,Typeable,Generic) instance NFData LineInfo
choener/BiobaseFasta
Biobase/Fasta/Types.hs
gpl-3.0
1,827
0
9
348
285
166
119
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module Parsing(Car, mark, date, model, year, engine, mileage, price, isBroken, isNoDocs, isPushedUp, url, Engine, capacity, power, typeOfDrive, typeOfFuel, autoTransmission, Drive (Forward, Backward, WD4), Fuel (Diesel, Petrol, Gas), getCarsFromPage) where import Text.HTML.TagSoup import Network.HTTP import Data.List.Split import Data.Char (isDigit, isPrint, isSpace, isNumber, isPunctuation) import Text.Read(readMaybe) import Data.List(isInfixOf) import Control.Exception import Control.Concurrent(threadDelay) data Car = Car { mark::String, date::(Int, Int), model::String, year::Maybe Int, engine::Engine, mileage::Maybe Int, price::Maybe Int, --description::String, --comments::[String], isBroken::Bool, isNoDocs::Bool, isPushedUp::Bool, url::String } deriving (Show, Read, Eq) data Engine = Engine {capacity::Maybe Float, power::Maybe Int, typeOfDrive::Drive, typeOfFuel::Fuel, autoTransmission::Bool }deriving (Show, Read, Eq) data Drive = Forward | Backward | WD4 deriving (Show, Read, Eq) data Fuel = Diesel | Petrol | Gas deriving (Show, Read, Eq) parseCars::[Tag String]->[[Tag String]] parseCars = tail. splitWhen (~== "<tr data-index>") openURL::String->IO [Tag String] openURL url = putStr (normalizeStrWith 50 '.' url ++ " Download(") >> (simpleHTTP (getRequest url)>>= (\x -> case x of Left _ -> putStr "Error)" >> return [] Right _ -> putStr "OK)" >> getResponseBody x >>= return.parseTags )) `catch` (\(e::IOException)-> putStr ("Exception openURL: "++ show e++")") >> return []) getCarsFromPage::String->IO [Car] getCarsFromPage url = do --threadDelay 500000 tags <- openURL url putStr " Parse(" if null tags then putStrLn "Error)" >> return [] else putStrLn "OK)" >> return (map parseStats (parseCars tags)) normalizeStrWith::Int->Char->String->String normalizeStrWith len s str | length str > len = normalizeStrWith mid s (take (mid-2 ) a) ++ reverse (normalizeStrWith mid s (take (mid-1) (reverse b))) | otherwise = str ++ replicate (len - length str) s where mid = div len 2 (a, b) = splitAt (div (length str) 2) str parseStats::[Tag String]->Car parseStats oneCarTags = Car { mark = "", date = parseDate dateData, model = parseModel modelData, year = readMaybe (parseYear yearData), engine = parseEngine engineData, mileage = readMaybe (parseMileage mileageData), price = readMaybe (parsePrice priceData), --description = "", --TODO --comments = [], --TODO isBroken = parseIsBroken additionalData, isNoDocs = parseIsNoDocs additionalData, isPushedUp = parseIsPushedUp dateData, url = parseUrl urlData } where (dateData: urlData :modelData: yearData: engineData: mileageData: additionalData:priceData:_) = tail$ splitWhen (~== "<td>") oneCarTags parseDate = toIntPair. prepareText (\x -> (isDigit x) || (x=='-')) 10 parseModel = unwords. words. innerText. filter isTagText. take 10 parseYear = prepareText isDigit 10 parseMileage=prepareText isDigit 10 parseIsBroken = isImage "damaged.png" parseIsNoDocs = isImage "nodocs.png" parsePrice = prepareText isDigit 10 parseIsPushedUp = isImage "up.gif" parseUrl = last. map (fromAttrib "href") . take 5 prepareText p num = unwords. words. filter p. innerText. filter isTagText. take num toIntPair list= let x = map read (splitOn "-" list) in (head x, last x) isImage name= any (isInfixOf name). map (fromAttrib "src"). filter (isTagOpenName "img"). take 10 parseEngine x = let tmp = words. filter isPrint. innerText. filter isTagText$ take 15 x in Engine { capacity = readMaybe$ head tmp, power = readMaybe$ parsePower tmp, typeOfDrive = parseDrive tmp, typeOfFuel = parseFuel tmp, autoTransmission = parseTransmission tmp } where parsePower tmp = let x = filter (elem '(') tmp in if null x then [] else filter isDigit$ head x parseFuel tmp = let x = filter (\x->elem (head x) ['\225','\228']) tmp in --some shit with encoding if null x then Gas else if head (head x) == '\225' then Petrol else Diesel parseDrive tmp = let tmp' = last tmp in if tmp' == "4WD" then WD4 else if head tmp' == '\239' then Forward else Backward parseTransmission tmp = not.null$ filter (\x->'\224'==head x) tmp {- trim = f . f where f = reverse . dropWhile isSpace dropSpaces [] = [] dropSpaces (' ':' ':a) = dropSpaces (' ' : a) dropSpaces (a:b) = a : dropSpaces b fromCP1251::String->String fromCP1251 = map (\chr -> case lookup chr rusTable of Just x -> x _ -> chr) where rusTable = zip ['\192'..'\255'] ['А'..'я'] -}
NoobsEnslaver/hDromParser
Parsing.hs
gpl-3.0
5,633
0
18
1,852
1,648
875
773
98
6
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- 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.Grid.Do ( --pathWait, postStepDTModify, pathEatWait, pathEatContinue, ) where import MyPrelude import Game import Game.Grid.GridWorld import Game.Grid.Modify import Game.Grid.Helpers -- | to be done after StepDT postStepDTModify :: s -> GridWorld -> b -> MEnv' (s, GridWorld, b) postStepDTModify s grid b = case pathEvents $ gridPathA grid of (EventNewSegment:_) -> do -- if new segment, reset reference pos grid' <- keysTouchHandlePointVector grid $ \_ _ pos' -> grid { gridControlPosRef = pos' } return (s, grid', b) -- fixme: (e:es) -> f es (but currently only 1 PathEvent) _ -> do return (s, grid, b) -------------------------------------------------------------------------------- -- onPathNode -- | eat node and wait for defined turn pathEatWait :: Path -> IO Path pathEatWait path = case pathTurnState path of -- no defined turn, eat and wait Nothing -> do path' <- pathEatTurn path straightTurn return $ path' { pathWaiting = True } -- continue in direction defined by turn Just turn -> do path' <- pathEatTurn path turn return $ path' { pathTurnState = Nothing } -- | continue straight ahead if no defined turn pathEatContinue :: Path -> IO Path pathEatContinue path = do path' <- pathEatTurn path (maybe straightTurn id $ pathTurnState path) return $ path' { pathTurnState = Nothing }
karamellpelle/grid
designer/source/Game/Grid/Do.hs
gpl-3.0
2,321
0
14
606
361
202
159
32
2
{-# LANGUAGE NoImplicitPrelude, DeriveGeneric, GeneralizedNewtypeDeriving #-} module Lamdu.Expr.Identifier ( Identifier(..) ) where import Prelude.Compat import Control.DeepSeq (NFData(..)) import Control.DeepSeq.Generics (genericRnf) import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Hashable (Hashable) import Data.String (IsString(..)) import GHC.Generics (Generic) import qualified Text.PrettyPrint as PP import Text.PrettyPrint.HughesPJClass (Pretty(..)) newtype Identifier = Identifier ByteString deriving (Eq, Ord, Generic, Show, Binary, Hashable) instance NFData Identifier where rnf = genericRnf instance IsString Identifier where fromString = Identifier . fromString instance Pretty Identifier where pPrint (Identifier x) = PP.text $ BS.unpack x
da-x/Algorithm-W-Step-By-Step
Lamdu/Expr/Identifier.hs
gpl-3.0
939
0
8
200
231
138
93
19
0
-- Author: Vic Fryzel - edited by: Nicholas Mobbs -- http://github.com/vicfryzel/xmonad-config import System.IO import System.IO.Unsafe (unsafePerformIO) import Text.Printf (printf) import XMonad.Util.WindowProperties (getProp32s) import System.Exit import XMonad import XMonad.Config (def) import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.ManageHelpers import XMonad.Layout.Fullscreen import XMonad.Layout.NoBorders import XMonad.Layout.Spiral import XMonad.Util.Run(spawnPipe) import XMonad.Actions.SpawnOn import XMonad.Actions.OnScreen import XMonad.Actions.CycleWS import qualified XMonad.StackSet as W import qualified Data.Map as M ------------------------------------------------------------------------ -- Terminal -- The preferred terminal program, which is used in a binding below and by -- certain contrib modules. -- myTerminal = "/usr/bin/urxvt" ------------------------------------------------------------------------ -- Workspaces -- The default number of workspaces (virtual screens) and their names. -- myWorkspaces = ["1:term","2:web","3:code"] ++ map show [4..9] ------------------------------------------------------------------------ -- Window rules -- Execute arbitrary actions and WindowSet manipulations when managing -- a new window. You can use this to, for example, always float a -- particular program, or have a client always appear on a particular -- workspace. --THIS IS THE MOST MESSY PIECE OF SHIT I HAVE EVER CODED --I DESERVE TO GO TO HELL FOR THIS SHIT!!!!!!!!!!!!!!!!! getpstat :: String -> Int -> String getpstat pid i = words (unsafePerformIO $ readFile $ printf "/proc/%s/stat" pid) !! i pname :: Query (Maybe String) pname = ask >>= \w -> liftX $ do p <- getProp32s "_NET_WM_PID" w return $ case p of Just [x] -> Just $ getpstat (getpstat (show x) 3) 1 _ -> Nothing myManageHook = composeAll [ className =? "Firefox" --> doShift "2:web" , className =? "Thunderbird" --> doShift "4:mail" , className =? "mpv" <&&> pname =? (Just "(mpsyt)") --> doShift "1:term" , isFullscreen --> doFullFloat , className =? "Civ5XP" --> doFullFloat] ------------------------------------------------------------------------ -- Layouts -- You can specify and transform your layouts by modifying these values. -- If you change layout bindings be sure to use 'mod-shift-space' after -- restarting (with 'mod-q') to reset your layout state to the new -- defaults, as xmonad preserves your old layout settings by default. -- -- The available layouts. Note that each layout is separated by |||, -- which denotes layout choice. -- myLayout = avoidStruts ( Tall 1 (3/100) (1/2) ||| Mirror (Tall 1 (3/100) (1/2))) ||| noBorders (fullscreenFull Full) ------------------------------------------------------------------------ -- Colors and borders -- myNormalBorderColor = "#7c7c7c" -- Color of current window title in xmobar. xmobarTitleColor = "#FFB6B0" -- Color of current workspace in xmobar. xmobarCurrentWorkspaceColor = "#CEFFAC" -- Width of the window border in pixels. myBorderWidth = 1 ------------------------------------------------------------------------ -- Key bindings -- -- modMask lets you specify which modkey you want to use. The default -- is mod1Mask ("left alt"). You may also consider using mod3Mask -- ("right alt"), which does not conflict with emacs keybindings. The -- "windows key" is usually mod4Mask. -- myModMask = mod1Mask myKeys conf@(XConfig {XMonad.modMask = modMask}) = M.fromList $ ---------------------------------------------------------------------- -- Custom key bindings -- -- Start a terminal. Terminal to start is specified by myTerminal variable. [ ((modMask .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf) -- Toggle xmobar , ((modMask, xK_b), sendMessage ToggleStruts) -- Lock the screen using xscreensaver. , ((modMask .|. controlMask, xK_x), spawn "xscreensaver-command -lock") -- Mute volume. , ((modMask .|. controlMask, xK_m), spawn "$HOME/.xmonad/bin/mute.sh") --"amixer -q set Master toggle") -- Decrease volume. , ((modMask .|. controlMask, xK_j), spawn "amixer set Master 5%-") -- Decrease volume. , ((modMask, xK_z), spawn "amixer set Master 5%-") -- Increase volume. , ((modMask .|. controlMask, xK_k), spawn "amixer set Master 5%+") -- Increase volume. , ((modMask, xK_x), spawn "amixer set Master 5%+") -- Audio previous. , ((modMask .|. controlMask, xK_h), spawn "cmus-remote -r") -- Play/pause. , ((modMask .|. controlMask, xK_p), spawn "cmus-remote -u") -- Audio next. , ((modMask .|. controlMask, xK_l), spawn "cmus-remote -n") -- Launch Firefox. , ((modMask .|. controlMask, xK_f), spawn "firefox") -------------------------------------------------------------------- -- Close focused window. , ((modMask .|. shiftMask, xK_c), kill) -- Cycle through the available layout algorithms. , ((modMask, xK_space), sendMessage NextLayout) -- Reset the layouts on the current workspace to default. , ((modMask .|. shiftMask, xK_space), setLayout $ XMonad.layoutHook conf) -- Swap to previous workspace , ((modMask, xK_Tab), toggleWS) -- Move focus to the next window. , ((modMask, xK_j), windows W.focusDown) -- Move focus to the previous window. , ((modMask, xK_k), windows W.focusUp ) -- Swap the focused window with the next window. , ((modMask .|. shiftMask, xK_j), windows W.swapDown ) -- Swap the focused window with the previous window. , ((modMask .|. shiftMask, xK_k), windows W.swapUp ) -- Shrink the master area. , ((modMask, xK_h), sendMessage Shrink) -- Expand the master area. , ((modMask, xK_l), sendMessage Expand) -- Push window back into tiling. , ((modMask, xK_t), withFocused $ windows . W.sink) -- Quit xmonad. , ((modMask .|. shiftMask, xK_q), io (exitWith ExitSuccess)) -- Restart xmonad. , ((modMask, xK_q), restart "xmonad" True) ] ++ -- mod-[1..9], Switch to workspace N -- mod-shift-[1..9], Move client to workspace N [((m .|. modMask, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] ++ -- mod-[a,s,d,f], Switch to workspace on physical screens -- mod-shift-[a,s,d,f], Move client to workspace on physical screens [((m .|. modMask, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_a, xK_s, xK_d, xK_f] [0..] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]] ------------------------------------------------------------------------ -- Mouse bindings myMouseBindings (XConfig {XMonad.modMask = modMask}) = M.fromList $ [ -- mod-button1, Set the window to floating mode and move by dragging ((modMask, button1), (\w -> focus w >> mouseMoveWindow w)) -- mod-button3, Set the window to floating mode and resize by dragging , ((modMask, button3), (\w -> focus w >> mouseResizeWindow w)) ] ------------------------------------------------------------------------ -- Run xmonad with all the defaults we set up. -- main = do xmproc <- spawnPipe "xmobar ~/.xmonad/xmobar.hs" xmonad $ defaults { logHook = dynamicLogWithPP $ xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor xmobarTitleColor "" . shorten 100 , ppCurrent = xmobarColor xmobarCurrentWorkspaceColor "" , ppSep = " " } } ------------------------------------------------------------------------ -- Combine it all together -- A structure containing your configuration settings, overriding -- fields in the default config. Any you don't override, will -- use the defaults defined in xmonad/XMonad/Config.hs -- -- No need to modify this. -- defaults = def { -- simple stuff terminal = myTerminal, focusFollowsMouse = False, borderWidth = myBorderWidth, modMask = myModMask, workspaces = myWorkspaces, normalBorderColor = myNormalBorderColor, -- key bindings keys = myKeys, mouseBindings = myMouseBindings, -- hooks, layouts layoutHook = smartBorders $ myLayout, manageHook = myManageHook }
narakhan/dotfiles
auto_link/xmonad/xmonad/xmonad.hs
agpl-3.0
8,467
0
19
1,724
1,612
968
644
128
2
module Linguisticks.Util where import Data.Maybe ( isNothing, fromJust ) import Text.ParserCombinators.Parsec ( GenParser, many, noneOf, char, (<|>), optionMaybe, eof, runParser ) import Text.Parsec.Prim ( ParsecT ) import Text.Parsec.Error ( ParseError ) import qualified Data.Set as S type Set = S.Set sequenceSecond :: Monad m => [(a, m b)] -> m [(a, b)] sequenceSecond ms = let (as, mbs) = unzip ms mb = sequence mbs in do bs <- mb return $ zip as bs choose :: Int -> [a] -> [[a]] choose 0 _ = [[]] choose n ss = let splits = [0..(length ss - 1)] in do split <- splits let (top, bot) = splitAt split ss rest <- choose (n-1) (tail bot) return $ (head bot):rest map2 :: (a -> a -> b) -> [a] -> [b] map2 f = let map2' [_] = [] map2' (a:b:xs) = (f a b):(map2' (b:xs)) in map2' fromRight :: Either a b -> b fromRight (Right b) = b fromLeft :: Either a b -> a fromLeft (Left b) = b isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft _ = False (<<) :: Monad m => m a -> m b -> m a (<<) a b = do { v <- a ; b ; return v } maybeP :: ParsecT s u m (Maybe a) -> ParsecT s u m a maybeP parser = do parsed <- parser maybe (fail "got nothing") return parsed eitherToList :: Either a b -> [b] eitherToList (Left _) = [] eitherToList (Right a) = [a] -- eitherToList = rights . return fromEither :: b -> Either a b -> b fromEither v = either (const v) id -- ADT for a Syllable. data Stress = NoStress | Secondary | Primary deriving (Eq, Show, Ord, Enum) primaryStress = 'ˈ' secondaryStress = 'ˌ' data Syllables = Syllables { syllOnset :: String, syllNucleus :: String, syllCoda :: String, syllStress :: Stress, syllNext :: Maybe Syllables } deriving (Eq) type Syllable = (String, String, String, Stress) syllsToList :: Syllables -> [Syllable] syllsToList s@(Syllables ons nuc cod stress next) | isNothing next = [(ons, nuc, cod, stress)] | otherwise = (ons, nuc, cod, stress):(syllsToList $ fromJust next) nullSign = "∅" nullReplace s = if null s then nullSign else s showFirstSyllable (Syllables ons nuc cod stress _) = let stressMarker = if stress == Primary then "ˈ" else if stress == Secondary then "ˌ" else "" in stressMarker ++ "(" ++ nullReplace ons ++ " " ++ nullReplace nuc ++ " " ++ nullReplace cod ++ ")" instance Show Syllables where show s@(Syllables _ _ _ _ Nothing ) = showFirstSyllable s show s@(Syllables _ _ _ _ (Just ss)) = showFirstSyllable s ++ " " ++ show ss type P = GenParser Char SyllState data SyllState = SyllState { nextStress :: Stress } deriving (Show, Eq, Ord) zeroState :: SyllState zeroState = SyllState NoStress -- Quick parser for Read Syllables readParserMaybe :: P (Maybe Syllables) readParserMaybe = let stripNull :: String -> String stripNull = filter (/= head nullSign) wordNoNull :: P String wordNoNull = fmap stripNull $ many $ noneOf " ()" oneSyllable :: P Syllables oneSyllable = do stress <- (char primaryStress >> return Primary) <|> (char secondaryStress >> return Secondary) <|> (return NoStress) char '(' ons <- wordNoNull << char ' ' nuc <- wordNoNull << char ' ' cod <- wordNoNull << char ')' optionMaybe $ char ' ' next <- readParserMaybe return $ Syllables ons nuc cod stress next in (eof >> return Nothing) <|> fmap Just oneSyllable instance Read Syllables where readsPrec _ ss = [(sylls, "")] where sylls = let parsed = runParser (maybeP readParserMaybe) zeroState "" ss in either (const $ error "no parse") id parsed data Word a = Word { wordSpelling :: String, wordTranscription :: String, wordSyllables :: a } deriving (Show, Eq) type ParsedWord a = Word (Either ParseError a)
jmacmahon/syllabify
Linguisticks/Util.hs
agpl-3.0
5,097
0
16
2,213
1,570
820
750
97
3
-- ------------------------------------------------ -- ------------------------------------------------ -- Interface comun a cajas contenedoras de datos -- class Box m where link :: (a -> m b) -> m a -> m b pack :: a -> m a unite :: m (m a) -> m a -- es para definir mas facilmente el link -- ------------------------------------------------ -- Implementacion de Box para el tipo Maybe -- instance Box Maybe where pack = Just link f Nothing = Nothing link f (Just x) = f x -- unite Nothing = Nothing unite (Just Nothing) = Nothing unite (Just (Just x)) = Just x -- Implementacion de Box para el tipo Lista -- instance Box [] where pack x = [x] unite = concat link f ls = unite (map f ls) --bind f ls = concat (map f ls) -- Implementacion de Box para las funciones que toman un tipo a -- instance Box ((->)a) where pack v = \k -> v -- return unite b = \k -> (b k) k -- concat -- handle f b = \k -> f (b k) -- map, definido en Package -- link f b = unite (handle f b) -- el bind es el concatMap link f b = \k-> (f (b k)) k -- ---------------------------------------------------------- handle' :: Box m => (a -> b) -> m a -> m b handle' f m = link f' m where f' x = pack (f x) {- Es el equivalente a liftM liftM :: (Monad m) => (a -> b) -> (m a -> m b) liftM f m = do x <- m return (f x) liftM "promueve" una funcion a una monada. Puede verse como que le das una funcion y una monada, y aplica la funcion "adentro" de la monada: liftM :: (Monad m) => (a -> b) -> m a -> m b o bien se puede ver como una funcion a la cual le pasas una funcion (a -> b) y te devuelve una funcion monadica (m a -> m b) liftM :: (Monad m) => (a -> b) -> (m a -> m b) -- Otras versiones: -- -- Del modulo monad.hs, notacion do con corchetes y ; -- liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r liftM f m1 = do { x1 <- m1; return (f x1) } -- Si bind tomara primero la monada y despues la funcion, como en las diapositivas -- liftM f m = (>>=) m (\x -> return (f x) ) -- Version con where -- liftM f m = bind f' m where f' x = return (f x) -- Version con funcion anonima (lambda) liftM f m = bind (\x -> return (f x)) m -} -- Version que promueve una funcion que toma dos argumentos {- liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r liftM2 f m1 m2 = do x1 <- m1 x2 <- m2 return (f x1 x2) liftM2 f m1 m2 = (>>=) m1 (\x1 -> (>>=) m2 (\x2 -> return f x1 x2)) liftM2 f m1 m2 = (>>=) (\x1 -> (>>=) (\x2 -> return f x1 x2) m2 ) m1 -} handle2' :: Box m => (a -> b -> c) -> m a -> m b -> m c handle2' f m1 m2 = link (\x -> link (\y -> pack (f x y) ) m2 ) m1 -- ---------------------------------------------------------- unite' :: Box m => m (m a) -> m a unite' m = link f m where f x = f x unite'' :: Box m => m (m a) -> m a unite'' m = link id m -- Es el equivalente a la funcion join -- join :: (Monad m) => m (m a) -> m a -- join x = x >>= id -- join x = bind id x {- join se usa para remover un nivel de estructura monadica, proyectando su argumento ligado hacia afuera -} -- ---------------------------------------------------------- -- Es el equivalente a la funcion ap -- ap :: (Monad m) => m (a -> b) -> m a -> m b -- ap = liftM2 id employ :: Box m => m (a -> b) -> m a -> m b employ mf m = link f mf where f x = handle' x m -- ap es similar a liftM -- TODO diferencias entre ap y liftM -- ---------------------------------------------------------- -- Dada una funcion que construye cajas y una lista de elementos, -- retorna una caja de listas associate :: Box m => (a -> m b) -> [a] -> m [b] associate f ls = sucession (map f ls) -- associate f = sucession . map f -- Es el equivalente a mapM -- mapM :: (Monad m) => (a -> m b) -> [a] -> m [b] -- mapM f = sequence . map f -- ---------------------------------------------------------- -- Dada una lista de cajas, construye una unica caja con la lista de elementos -- resultante de recolectar secuencialmente los elementos de las cajas -- -- La funcion es recursiva en la estructura de las listas sucession :: (Box m) => [m a] -> m [a] sucession = foldr (handle2' (:)) (pack []) -- sucession [] = pack [] -- armo una caja con la lista vacia -- sucession (m:ms) = (handle2' (:)) m (sucession ms) -- lifteo cons {- Es el equivalente a sequence: sequence :: Monad m => [m a] -> m [a] sequence [] = return [] sequence (c:cs) = do x <- c xs <- sequence cs return (x:xs) c >>= \x -> sequence cs >>= \xs -> return (x:xs) -- otra definiciones de sequence: sequence = foldr (liftM2 (:)) (return []) -}
luchist/Funcional
Box.hs
unlicense
5,243
0
13
1,775
770
401
369
36
1
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} --really, a better name for this module could be "TransTransactionGraphRelationalExpr", but that name is too long module ProjectM36.TransGraphRelationalExpression where import ProjectM36.Base import ProjectM36.TransactionGraph import ProjectM36.Error import qualified Data.Map as M import Control.Monad.Trans.Reader import Control.Monad.Trans.Class import Control.Monad.Trans.Except import Data.Functor.Identity -- | The TransGraphRelationalExpression is equivalent to a relational expression except that relation variables can reference points in the transaction graph (at previous points in time). type TransGraphRelationalExpr = RelationalExprBase TransactionIdLookup type TransGraphAttributeNames = AttributeNamesBase TransactionIdLookup type TransGraphExtendTupleExpr = ExtendTupleExprBase TransactionIdLookup type TransGraphTupleExpr = TupleExprBase TransactionIdLookup type TransGraphTupleExprs = TupleExprsBase TransactionIdLookup type TransGraphRestrictionPredicateExpr = RestrictionPredicateExprBase TransactionIdLookup type TransGraphAtomExpr = AtomExprBase TransactionIdLookup type TransGraphAttributeExpr = AttributeExprBase TransactionIdLookup type TransGraphWithNameExpr = WithNameExprBase TransactionIdLookup newtype TransGraphEvalEnv = TransGraphEvalEnv { tge_graph :: TransactionGraph } type TransGraphEvalMonad a = ReaderT TransGraphEvalEnv (ExceptT RelationalError Identity) a process :: TransGraphEvalEnv -> TransGraphRelationalExpr -> Either RelationalError GraphRefRelationalExpr process env texpr = runIdentity (runExceptT (runReaderT (processTransGraphRelationalExpr texpr) env)) liftE :: Either RelationalError a -> TransGraphEvalMonad a liftE = lift . except askGraph :: TransGraphEvalMonad TransactionGraph askGraph = tge_graph <$> ask findTransId :: TransactionIdLookup -> TransGraphEvalMonad GraphRefTransactionMarker findTransId tlook = TransactionMarker . transactionId <$> findTrans tlook findTrans :: TransactionIdLookup -> TransGraphEvalMonad Transaction findTrans tlook = do graph <- askGraph liftE $ lookupTransaction graph tlook -- OUTDATED a previous attempt at this function attempted to convert TransGraphRelationalExpr to RelationalExpr by resolving the transaction lookups. However, there is no way to resolve a FunctionAtomExpr to an Atom without fully evaluating the higher levels (TupleExpr, etc.). An anonymous function expression cannot be serialized, so that workaround is out. Still, I suspect we can reuse the existing static optimizer logic to work on both structures. The current conversion reduces the chance of whole-query optimization due to full-evaluation on top of full-evaluation, so this function would benefit from some re-design. processTransGraphRelationalExpr :: TransGraphRelationalExpr -> TransGraphEvalMonad GraphRefRelationalExpr processTransGraphRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do tupleExprs' <- processTransGraphTupleExprs tupleExprs case mAttrExprs of Nothing -> pure (MakeRelationFromExprs Nothing tupleExprs') Just attrExprs -> do attrExprs' <- mapM processTransGraphAttributeExpr attrExprs pure (MakeRelationFromExprs (Just attrExprs') tupleExprs') processTransGraphRelationalExpr (MakeStaticRelation attrs tupSet) = pure (MakeStaticRelation attrs tupSet) processTransGraphRelationalExpr (ExistingRelation rel) = pure (ExistingRelation rel) processTransGraphRelationalExpr (RelationVariable rvname transLookup) = RelationVariable rvname <$> findTransId transLookup processTransGraphRelationalExpr (Project transAttrNames expr) = Project <$> processTransGraphAttributeNames transAttrNames <*> processTransGraphRelationalExpr expr processTransGraphRelationalExpr (Union exprA exprB) = Union <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB processTransGraphRelationalExpr (Join exprA exprB) = Join <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB processTransGraphRelationalExpr (Rename attrName1 attrName2 expr) = Rename attrName1 attrName2 <$> processTransGraphRelationalExpr expr processTransGraphRelationalExpr (Difference exprA exprB) = Difference <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB processTransGraphRelationalExpr (Group transAttrNames attrName expr) = Group <$> processTransGraphAttributeNames transAttrNames <*> pure attrName <*> processTransGraphRelationalExpr expr processTransGraphRelationalExpr (Ungroup attrName expr) = Ungroup attrName <$> processTransGraphRelationalExpr expr processTransGraphRelationalExpr (Restrict predicateExpr expr) = Restrict <$> evalTransGraphRestrictionPredicateExpr predicateExpr <*> processTransGraphRelationalExpr expr processTransGraphRelationalExpr (Equals exprA exprB) = do exprA' <- processTransGraphRelationalExpr exprA exprB' <- processTransGraphRelationalExpr exprB pure (Equals exprA' exprB') processTransGraphRelationalExpr (NotEquals exprA exprB) = do exprA' <- processTransGraphRelationalExpr exprA exprB' <- processTransGraphRelationalExpr exprB pure (NotEquals exprA' exprB') processTransGraphRelationalExpr (Extend extendExpr expr) = do extendExpr' <- processTransGraphExtendTupleExpr extendExpr expr' <- processTransGraphRelationalExpr expr pure (Extend extendExpr' expr') processTransGraphRelationalExpr (With views expr) = do evaldViews <- mapM (\(wnexpr, vexpr) -> do wnexpr' <- processTransGraphWithNameExpr wnexpr vexpr' <- processTransGraphRelationalExpr vexpr pure (wnexpr', vexpr') ) views expr' <- processTransGraphRelationalExpr expr pure (With evaldViews expr') processTransGraphTupleExprs :: TransGraphTupleExprs -> TransGraphEvalMonad GraphRefTupleExprs processTransGraphTupleExprs (TupleExprs marker texprs) = TupleExprs <$> findTransId marker <*> mapM processTransGraphTupleExpr texprs processTransGraphTupleExpr :: TransGraphTupleExpr -> TransGraphEvalMonad GraphRefTupleExpr processTransGraphTupleExpr (TupleExpr attrMap) = do let attrAssoc = mapM (\(attrName, atomExpr) -> do aExpr <- processTransGraphAtomExpr atomExpr pure (attrName, aExpr) ) (M.toList attrMap) TupleExpr . M.fromList <$> attrAssoc processTransGraphAtomExpr :: TransGraphAtomExpr -> TransGraphEvalMonad GraphRefAtomExpr processTransGraphAtomExpr (AttributeAtomExpr aname) = pure $ AttributeAtomExpr aname processTransGraphAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom processTransGraphAtomExpr (FunctionAtomExpr funcName' args tLookup) = FunctionAtomExpr funcName' <$> mapM processTransGraphAtomExpr args <*> findTransId tLookup processTransGraphAtomExpr (RelationAtomExpr expr) = RelationAtomExpr <$> processTransGraphRelationalExpr expr processTransGraphAtomExpr (ConstructedAtomExpr dConsName args tLookup) = ConstructedAtomExpr dConsName <$> mapM processTransGraphAtomExpr args <*> findTransId tLookup evalTransGraphRestrictionPredicateExpr :: TransGraphRestrictionPredicateExpr -> TransGraphEvalMonad GraphRefRestrictionPredicateExpr evalTransGraphRestrictionPredicateExpr TruePredicate = pure TruePredicate evalTransGraphRestrictionPredicateExpr (AndPredicate exprA exprB) = do exprA' <- evalTransGraphRestrictionPredicateExpr exprA exprB' <- evalTransGraphRestrictionPredicateExpr exprB pure (AndPredicate exprA' exprB') evalTransGraphRestrictionPredicateExpr (OrPredicate exprA exprB) = do exprA' <- evalTransGraphRestrictionPredicateExpr exprA exprB' <- evalTransGraphRestrictionPredicateExpr exprB pure (OrPredicate exprA' exprB') evalTransGraphRestrictionPredicateExpr (NotPredicate expr) = do let expr' = evalTransGraphRestrictionPredicateExpr expr NotPredicate <$> expr' evalTransGraphRestrictionPredicateExpr (RelationalExprPredicate expr) = do let expr' = processTransGraphRelationalExpr expr RelationalExprPredicate <$> expr' evalTransGraphRestrictionPredicateExpr (AtomExprPredicate expr) = do let expr' = processTransGraphAtomExpr expr AtomExprPredicate <$> expr' evalTransGraphRestrictionPredicateExpr (AttributeEqualityPredicate attrName expr) = do let expr' = processTransGraphAtomExpr expr AttributeEqualityPredicate attrName <$> expr' processTransGraphExtendTupleExpr :: TransGraphExtendTupleExpr -> TransGraphEvalMonad GraphRefExtendTupleExpr processTransGraphExtendTupleExpr (AttributeExtendTupleExpr attrName expr) = AttributeExtendTupleExpr attrName <$> processTransGraphAtomExpr expr processTransGraphAttributeExpr :: TransGraphAttributeExpr -> TransGraphEvalMonad GraphRefAttributeExpr processTransGraphAttributeExpr (AttributeAndTypeNameExpr attrName tCons tLookup) = AttributeAndTypeNameExpr attrName tCons <$> findTransId tLookup processTransGraphAttributeExpr (NakedAttributeExpr attr) = pure (NakedAttributeExpr attr) processTransGraphAttributeNames :: TransGraphAttributeNames -> TransGraphEvalMonad GraphRefAttributeNames processTransGraphAttributeNames (AttributeNames names) = pure (AttributeNames names) processTransGraphAttributeNames (InvertedAttributeNames names) = pure (InvertedAttributeNames names) processTransGraphAttributeNames (UnionAttributeNames namesA namesB) = do nA <- processTransGraphAttributeNames namesA nB <- processTransGraphAttributeNames namesB pure (UnionAttributeNames nA nB) processTransGraphAttributeNames (IntersectAttributeNames namesA namesB) = do nA <- processTransGraphAttributeNames namesA nB <- processTransGraphAttributeNames namesB pure (IntersectAttributeNames nA nB) processTransGraphAttributeNames (RelationalExprAttributeNames expr) = do evaldExpr <- processTransGraphRelationalExpr expr pure (RelationalExprAttributeNames evaldExpr) processTransGraphWithNameExpr :: TransGraphWithNameExpr -> TransGraphEvalMonad GraphRefWithNameExpr processTransGraphWithNameExpr (WithNameExpr rvname tlookup) = WithNameExpr rvname <$> findTransId tlookup
agentm/project-m36
src/lib/ProjectM36/TransGraphRelationalExpression.hs
unlicense
10,145
0
16
1,264
1,898
909
989
152
2
module Data.FormulaBench (benchs) where import Data.Formula import Criterion.Main benchs :: Benchmark benchs = bgroup "Data.Formula" [ ] {- bench_someFunction :: Benchmark bench_someFunction = bgroup "someFunction" [ bench "1" $ nf someFunction 1 , bench "2" $ nf someFunction 2 , bench "100" $ nf someFunction 100 ] bench_someIO :: Benchmark bench_someIO = bench "someIO" $ whnfIO someIO -}
jokusi/mso
bench/Data/FormulaBench.hs
apache-2.0
408
0
6
74
39
23
16
6
1
{-# LANGUAGE OverloadedStrings #-} module Templates.Resource where import Data.String (fromString) import Data.Text.Encoding (decodeUtf8) import Data.Monoid (mappend, (<>), mconcat) import Control.Monad (when, liftM3) import Network.HTTP.Types.Method (methodGet, methodPost, methodPut, methodDelete) import Lucid import CourseStitch.Models import Database.Persist (Entity(..), Key, entityKey, entityVal, toBackendKey) import Database.Persist.Sql (unSqlBackendKey) import CourseStitch.Templates.Utils import CourseStitch.Templates.Resource import CourseStitch.Templates.Concept (conceptSimple) import CourseStitch.Templates.Relationship (relationshipUri) import Templates.Website (page , typeahead) resourceDetailed :: Entity Resource -> [(RelationshipType, [Entity Concept])] -> Html () resourceDetailed resource rels = do resourceLink resource $ resourceHeading resource link (resourceUri resource `mappend` "/edit") "edit" resourceText resource resourceExternalLink resource $ resourceQuote resource resourceForm :: Maybe (Entity Resource) -> Html () resourceForm resource = do form_ [action_ uri, method_ method] $ do fieldset_ $ do input "URL" "url" $ get resourceUrl input "Media" "media" $ get resourceMedia input "Title" "title" $ get resourceTitle input "Course" "course" $ get resourceCourse textInput "Summary" "summary" $ get resourceSummary fieldset_ $ do textInput "Preview" "preview" $ get resourcePreview input "Keywords" "keywords" $ get resourceKeywords input_ [type_ "submit"] script_ [src_ "/js/form-methods.js"] ("" :: String) where get f = fmap (f . entityVal) resource uri = case resource of Just resource -> resourceUri resource Nothing -> "/resource" method = case resource of Just _ -> decodeUtf8 methodPut Nothing -> decodeUtf8 methodPost resourceRelationships :: Entity Resource -> [(Entity Topic, [Entity Concept])] -> [Entity Relationship] -> Html () resourceRelationships resource topics relationships = do script_ [src_ "/js/request.js"] ("" :: String) script_ [src_ "/js/checkbox-change.js"] ("" :: String) script_ [src_ "/js/add-concept.js"] ("" :: String) script_ [src_ "/js/add-topic.js"] ("" :: String) ul_ [class_ "topic-list"] $ mconcat $ (map li_) $ map (uncurry (topicRelationships (entityKey resource) (map entityVal relationships))) topics typeahead "/topic" "Enter a new topic" ["add-topic"] topicRelationships :: Key Resource -> [Relationship] -> Entity Topic -> [Entity Concept] -> Html () topicRelationships resource relationships topic concepts = do h1_ $ (toHtml . topicTitle . entityVal) topic ul_ [id_ $ fromString ("topic-"++ (fromString . show . entityId) topic), class_ "concept-list"] $ mconcat $ (map li_) $ map (relationship resource relationships) concepts input_ [class_ "add-concept", placeholder_ "Enter a new concept", data_ "topic" $ (fromString . show . entityId) topic] relationship :: Key Resource -> [Relationship] -> Entity Concept -> Html () relationship resource relationships concept = do (toHtml . conceptTitle . entityVal) concept br_ [] mconcat $ map checkbox [Taught ..] where checkbox rel = do input_ ([id_ $ id rel, type_ "checkbox", name_ "relationship", onchange_ $ update rel] ++ checked rel) label_ [for_ $ id rel] $ (toHtml . show) rel checked rel = if elem (relationship rel) relationships then [checked_] else [] id rel = mconcat [(fromString . show) rel, key concept] key = (fromString . show . unSqlBackendKey . toBackendKey . entityKey) relationship rel = Relationship resource rel (entityKey concept) update rel = fromString $ concat ["checkboxChange(this,", "request.bind(this, 'PUT', '"++uri (relationship rel)++"'),", "request.bind(this, 'DELETE', '"++uri (relationship rel)++"')", ")"] uri = relationshipUri resourceConcepts :: Entity Resource -> [(RelationshipType, [Entity Concept])] -> Html () resourceConcepts resource rels = mconcat $ map doRelationship rels where doRelationship (rel, concepts) = do resourceConceptsHeading rel case concepts of [] -> resourceConceptsMissing rel concepts -> unorderedList $ map conceptSimple concepts resourceConceptsMastery :: Entity Resource -> [(RelationshipType, [(Entity Concept, Bool)])] -> Html () resourceConceptsMastery resource rels = mconcat $ map doRelationship rels where doRelationship (rel, concepts) = do resourceConceptsHeading rel case concepts of [] -> resourceConceptsMissing rel concepts -> unorderedList $ map conceptWithCheckbox concepts conceptWithCheckbox (c, m) = do input_ ([type_ "checkbox"] <> if m then [checked_] else []) conceptSimple c resourceText = p_ . toHtml . resourceSummary . entityVal resourceExternalLink resource = link ((resourceUrl . entityVal) resource) resourceQuote = blockquote_ . toHtml . resourcePreview . entityVal resourceConceptsHeading rel = h2_ ("Concepts " `mappend` (fromString . show) rel) resourceConceptsMissing rel = p_ ("There are no concepts " `mappend` (fromString . show) rel `mappend` " by this resource") resourcePage :: Entity Resource -> [(RelationshipType, [Entity Concept])] -> Html() resourcePage r rels = page $ resourceDetailed r rels
coursestitch/coursestitch-api
src/Templates/Resource.hs
apache-2.0
5,610
0
19
1,216
1,764
887
877
101
3
-- add a b = a + b
chinaran/haskell-study
ch02/add.hs
apache-2.0
18
0
5
7
16
8
8
1
1
-- |JavaScript's syntax. module BrownPLT.TypedJS.Syntax ( Expression(..) , CaseClause(..) , ConstrFieldAsgn(..) , constrBodyStmt , Statement(..) , InfixOp(..) , CatchClause(..) , VarDecl(..) , AssignOp(..) , Id(..) , PrefixOp(..) , UnaryAssignOp(..) , Prop(..) , ForInit(..) , ForInInit(..) , Type(..) , LValue (..) , ArgType (..) , TopLevel (..) , unId ) where import BrownPLT.TypedJS.Prelude import qualified Data.Foldable as F import BrownPLT.JavaScript (InfixOp (..), AssignOp (..), PrefixOp (..), UnaryAssignOp(..)) import BrownPLT.JavaScript.Analysis.ANF (Lit, eqLit) import BrownPLT.TypedJS.LocalFlows (RuntimeType (..)) import BrownPLT.TypedJS.TypeDefinitions data Id a = Id a String deriving (Show, Eq, Ord, Data, Typeable) data LatentPred = LPType Type | LPNone deriving (Show, Eq, Ord, Data, Typeable) data Prop a = PropId a (Id a) | PropString a String | PropNum a Integer deriving (Show, Eq, Ord, Data, Typeable) data LValue a = LVar a String | LDot a (Expression a) String | LBracket a (Expression a) (Expression a) deriving (Show, Eq, Ord, Data, Typeable) data Expression a = StringLit a String | RegexpLit a String Bool {- global? -} Bool {- case-insensitive? -} | NumLit a Double -- pg. 5 of ECMA-262 | IntLit a Int -- int/double distinction. | BoolLit a Bool | NullLit a | ArrayLit a [Expression a] | ObjectLit a [(Prop a, Expression a)] | ThisRef a | VarRef a (Id a) | DotRef a (Expression a) (Id a) | BracketRef a (Expression a) {- container -} (Expression a) {- key -} | NewExpr a (Expression a) {- constructor -} [Expression a] | UnaryAssignExpr a UnaryAssignOp (LValue a) | PrefixExpr a PrefixOp (Expression a) | InfixExpr a InfixOp (Expression a) (Expression a) | CondExpr a (Expression a) (Expression a) (Expression a) --ternary operator | AssignExpr a AssignOp (LValue a) (Expression a) | ParenExpr a (Expression a) | ListExpr a [Expression a] -- expressions separated by ',' | CallExpr a (Expression a) [Type] [Expression a] | TyAppExpr a (Expression a) Type | FuncExpr a [Id a] {- arg names -} Type --if TFunc, then function. if TConstr, then a constructor. (Statement a) {- body -} -- Dataflow analysis may deterine a set of possible runtime types for -- certain variable references. | AnnotatedVarRef a (Set RuntimeType) String -- introducing existential types. Elimination form in 'VarDecl' | PackExpr a (Expression a) Type {- concrete -} Type {- existential -} deriving (Show, Eq, Ord, Data, Typeable) data CaseClause a = CaseClause a (Expression a) [Statement a] | CaseDefault a [Statement a] deriving (Show, Eq, Ord, Data, Typeable) data CatchClause a = CatchClause a (Id a) (Statement a) deriving (Show, Eq, Ord, Data, Typeable) data VarDecl a = VarDecl a (Id a) Type | VarDeclExpr a (Id a) (Maybe Type) (Expression a) | UnpackDecl a (Id a) [String] (Expression a) deriving (Show, Eq, Ord, Data, Typeable) data ForInit a = NoInit | VarInit [VarDecl a] | ExprInit (Expression a) deriving (Show, Eq, Ord, Data, Typeable) data ForInInit a -- |These terms introduce a name to the enclosing function's environment. -- Without a type declaration, we can't return a 'RawEnv' without some -- type inference. Save type inference for later. = ForInVar (Id a) | ForInNoVar (Id a) deriving (Show, Eq, Ord, Data, Typeable) data Statement a = BlockStmt a [Statement a] | EmptyStmt a | ExprStmt a (Expression a) | IfStmt a (Expression a) (Statement a) (Statement a) | IfSingleStmt a (Expression a) (Statement a) | SwitchStmt a (Expression a) [CaseClause a] | WhileStmt a (Expression a) (Statement a) | DoWhileStmt a (Statement a) (Expression a) | BreakStmt a (Maybe (Id a)) | ContinueStmt a (Maybe (Id a)) | LabelledStmt a (Id a) (Statement a) | ForInStmt a (ForInInit a) (Expression a) (Statement a) | ForStmt a (ForInit a) (Maybe (Expression a)) -- test (Maybe (Expression a)) -- increment (Statement a) -- body | TryStmt a (Statement a) {-body-} [CatchClause a] {-catches-} (Maybe (Statement a)) {-finally-} | ThrowStmt a (Expression a) | ReturnStmt a (Maybe (Expression a)) | VarDeclStmt a [VarDecl a] deriving (Show, Eq, Ord, Data, Typeable) data ConstrFieldAsgn a = ConstrFieldAsgn a String (Expression a) deriving (Show, Eq, Ord, Data, Typeable) asgnToStmt (ConstrFieldAsgn p n x) = ExprStmt p (AssignExpr p OpAssign (LDot p (ThisRef p) n) x) --given a constructorstmt, turn fieldasgns into normal stmts and put in a block constrBodyStmt p asgns body = BlockStmt p $ (map asgnToStmt asgns) ++ [body] data TopLevel a -- |@ConstructorStmt loc brand args constrTy asgnbody body@ -- asgnbody is all the assignments to fields of constructors -- body is the regularly scheduled programming = ConstructorStmt a String [String] Type [ConstrFieldAsgn a] (Statement a) -- |@ExternalFieldStmt loc brand field expr@ -- corresponds to -- @brand.prototype.field = expr@ | ExternalFieldStmt a (Id a) (Id a) (Expression a) | TopLevelStmt (Statement a) -- |@ImportStmt loc name isAssumed ty@ -- If @isAssumed@ is @true@, we do not use contracts. | ImportStmt a (Id a) Bool Type | ImportConstrStmt a (Id a) Bool Type deriving (Show, Eq, Ord, Data, Typeable) unId (Id _ s) = s
brownplt/strobe-old
src/BrownPLT/TypedJS/Syntax.hs
bsd-2-clause
5,464
0
11
1,197
1,850
1,036
814
130
1
-- | Basic types. module NLP.Nerf.Types ( Word , NE , Ob , Lb ) where import Prelude hiding (Word) import qualified Data.Text as T import qualified Data.Named.IOB as IOB -- | A word. type Word = T.Text -- | A named entity. type NE = T.Text -- | An observation consist of an index (of list type) and an actual -- observation value. type Ob = ([Int], T.Text) -- | A label is created by encoding the named entity forest using the -- IOB method. type Lb = IOB.Label NE
kawu/nerf
src/NLP/Nerf/Types.hs
bsd-2-clause
482
0
6
108
98
67
31
12
0
{-# LANGUAGE OverloadedStrings, UnboxedTuples, CPP #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif -- | -- Module : Data.Text.Read -- Copyright : (c) 2010, 2011 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- Functions used frequently when reading textual data. module Data.Text.Read ( Reader , decimal , hexadecimal , signed , rational , double ) where import Control.Monad (liftM) import Data.Char (isDigit, isHexDigit) import Data.Int (Int8, Int16, Int32, Int64) import Data.Ratio ((%)) import Data.Text as T import Data.Text.Internal.Private (span_) import Data.Text.Internal.Read import Data.Word (Word, Word8, Word16, Word32, Word64) -- | Read some text. If the read succeeds, return its value and the -- remaining text, otherwise an error message. type Reader a = IReader Text a type Parser a = IParser Text a -- | Read a decimal integer. The input must begin with at least one -- decimal digit, and is consumed until a non-digit or end of string -- is reached. -- -- This function does not handle leading sign characters. If you need -- to handle signed input, use @'signed' 'decimal'@. -- -- /Note/: For fixed-width integer types, this function does not -- attempt to detect overflow, so a sufficiently long input may give -- incorrect results. If you are worried about overflow, use -- 'Integer' for your result type. decimal :: Integral a => Reader a {-# SPECIALIZE decimal :: Reader Int #-} {-# SPECIALIZE decimal :: Reader Int8 #-} {-# SPECIALIZE decimal :: Reader Int16 #-} {-# SPECIALIZE decimal :: Reader Int32 #-} {-# SPECIALIZE decimal :: Reader Int64 #-} {-# SPECIALIZE decimal :: Reader Integer #-} {-# SPECIALIZE decimal :: Reader Data.Word.Word #-} {-# SPECIALIZE decimal :: Reader Word8 #-} {-# SPECIALIZE decimal :: Reader Word16 #-} {-# SPECIALIZE decimal :: Reader Word32 #-} {-# SPECIALIZE decimal :: Reader Word64 #-} decimal txt | T.null h = Left "input does not start with a digit" | otherwise = Right (T.foldl' go 0 h, t) where (# h,t #) = span_ isDigit txt go n d = (n * 10 + fromIntegral (digitToInt d)) -- | Read a hexadecimal integer, consisting of an optional leading -- @\"0x\"@ followed by at least one hexadecimal digit. Input is -- consumed until a non-hex-digit or end of string is reached. -- This function is case insensitive. -- -- This function does not handle leading sign characters. If you need -- to handle signed input, use @'signed' 'hexadecimal'@. -- -- /Note/: For fixed-width integer types, this function does not -- attempt to detect overflow, so a sufficiently long input may give -- incorrect results. If you are worried about overflow, use -- 'Integer' for your result type. hexadecimal :: Integral a => Reader a {-# SPECIALIZE hexadecimal :: Reader Int #-} {-# SPECIALIZE hexadecimal :: Reader Int8 #-} {-# SPECIALIZE hexadecimal :: Reader Int16 #-} {-# SPECIALIZE hexadecimal :: Reader Int32 #-} {-# SPECIALIZE hexadecimal :: Reader Int64 #-} {-# SPECIALIZE hexadecimal :: Reader Integer #-} {-# SPECIALIZE hexadecimal :: Reader Word #-} {-# SPECIALIZE hexadecimal :: Reader Word8 #-} {-# SPECIALIZE hexadecimal :: Reader Word16 #-} {-# SPECIALIZE hexadecimal :: Reader Word32 #-} {-# SPECIALIZE hexadecimal :: Reader Word64 #-} hexadecimal txt | h == "0x" || h == "0X" = hex t | otherwise = hex txt where (h,t) = T.splitAt 2 txt hex :: Integral a => Reader a {-# SPECIALIZE hex :: Reader Int #-} {-# SPECIALIZE hex :: Reader Int8 #-} {-# SPECIALIZE hex :: Reader Int16 #-} {-# SPECIALIZE hex :: Reader Int32 #-} {-# SPECIALIZE hex :: Reader Int64 #-} {-# SPECIALIZE hex :: Reader Integer #-} {-# SPECIALIZE hex :: Reader Word #-} {-# SPECIALIZE hex :: Reader Word8 #-} {-# SPECIALIZE hex :: Reader Word16 #-} {-# SPECIALIZE hex :: Reader Word32 #-} {-# SPECIALIZE hex :: Reader Word64 #-} hex txt | T.null h = Left "input does not start with a hexadecimal digit" | otherwise = Right (T.foldl' go 0 h, t) where (# h,t #) = span_ isHexDigit txt go n d = (n * 16 + fromIntegral (hexDigitToInt d)) -- | Read an optional leading sign character (@\'-\'@ or @\'+\'@) and -- apply it to the result of applying the given reader. signed :: Num a => Reader a -> Reader a {-# INLINE signed #-} signed f = runP (signa (P f)) -- | Read a rational number. -- -- This function accepts an optional leading sign character, followed -- by at least one decimal digit. The syntax similar to that accepted -- by the 'read' function, with the exception that a trailing @\'.\'@ -- or @\'e\'@ /not/ followed by a number is not consumed. -- -- Examples (with behaviour identical to 'read'): -- -- >rational "3" == Right (3.0, "") -- >rational "3.1" == Right (3.1, "") -- >rational "3e4" == Right (30000.0, "") -- >rational "3.1e4" == Right (31000.0, "") -- >rational ".3" == Left "input does not start with a digit" -- >rational "e3" == Left "input does not start with a digit" -- -- Examples of differences from 'read': -- -- >rational "3.foo" == Right (3.0, ".foo") -- >rational "3e" == Right (3.0, "e") rational :: Fractional a => Reader a {-# SPECIALIZE rational :: Reader Double #-} rational = floaty $ \real frac fracDenom -> fromRational $ real % 1 + frac % fracDenom -- | Read a rational number. -- -- The syntax accepted by this function is the same as for 'rational'. -- -- /Note/: This function is almost ten times faster than 'rational', -- but is slightly less accurate. -- -- The 'Double' type supports about 16 decimal places of accuracy. -- For 94.2% of numbers, this function and 'rational' give identical -- results, but for the remaining 5.8%, this function loses precision -- around the 15th decimal place. For 0.001% of numbers, this -- function will lose precision at the 13th or 14th decimal place. double :: Reader Double double = floaty $ \real frac fracDenom -> fromIntegral real + fromIntegral frac / fromIntegral fracDenom signa :: Num a => Parser a -> Parser a {-# SPECIALIZE signa :: Parser Int -> Parser Int #-} {-# SPECIALIZE signa :: Parser Int8 -> Parser Int8 #-} {-# SPECIALIZE signa :: Parser Int16 -> Parser Int16 #-} {-# SPECIALIZE signa :: Parser Int32 -> Parser Int32 #-} {-# SPECIALIZE signa :: Parser Int64 -> Parser Int64 #-} {-# SPECIALIZE signa :: Parser Integer -> Parser Integer #-} signa p = do sign <- perhaps '+' $ char (\c -> c == '-' || c == '+') if sign == '+' then p else negate `liftM` p char :: (Char -> Bool) -> Parser Char char p = P $ \t -> case T.uncons t of Just (c,t') | p c -> Right (c,t') _ -> Left "character does not match" floaty :: Fractional a => (Integer -> Integer -> Integer -> a) -> Reader a {-# INLINE floaty #-} floaty f = runP $ do sign <- perhaps '+' $ char (\c -> c == '-' || c == '+') real <- P decimal T fraction fracDigits <- perhaps (T 0 0) $ do _ <- char (=='.') digits <- P $ \t -> Right (T.length $ T.takeWhile isDigit t, t) n <- P decimal return $ T n digits let e c = c == 'e' || c == 'E' power <- perhaps 0 (char e >> signa (P decimal) :: Parser Int) let n = if fracDigits == 0 then if power == 0 then fromIntegral real else fromIntegral real * (10 ^^ power) else if power == 0 then f real fraction (10 ^ fracDigits) else f real fraction (10 ^ fracDigits) * (10 ^^ power) return $! if sign == '+' then n else -n
hvr/text
Data/Text/Read.hs
bsd-2-clause
7,645
0
19
1,708
1,258
693
565
116
5
module Main where import AdventOfCode data Block = Repeat Int String [Block] | Plain String deriving (Show) blockLenA :: Block -> Int blockLenA (Repeat n s _) = n * length s blockLenA (Plain s) = length s blockLenB :: Block -> Int blockLenB (Repeat n _ bs) = n * sum (blockLenB <$> bs) blockLenB (Plain s) = length s parseBlock :: Parser Block parseBlock = try parseRepeat <|> (Plain <$> many1 letter) where parseRepeat = do len <- char '(' *> number <* char 'x' mult <- number <* char ')' rest <- count len anyChar case runP (many parseBlock <* eof) () "block" rest of Right subBlocks -> pure $ Repeat mult rest subBlocks Left err -> fail (show err) number = read <$> many1 digit main = runDay $ Day 9 (many1 parseBlock <* newline) (return . show . sum . fmap blockLenA) (return . show . sum . fmap blockLenB)
purcell/adventofcode2016
src/Day9.hs
bsd-3-clause
915
0
14
259
370
182
188
31
2
-- | This module provides an instance for 'MemoryModel' module Jat.PState.MemoryModel.Primitive ( Primitive ) where import Jat.JatM import Jat.PState.Data import Jat.PState.AbstrValue import qualified Jat.PState.AbstrDomain as AD import Jat.PState.Heap import Jat.PState.Frame import Jat.PState.Fun import Jat.PState.IntDomain import Jat.PState.MemoryModel.Data import Jat.Utils.Pretty import qualified Jinja.Program as P import Control.Monad (zipWithM) -- | The Primitive type provides an implmentation without heap operations. -- Suitably for integer/Boolean only programs and testing. data Primitive = Primitive deriving Show instance Pretty Primitive where pretty _ = text "" instance MemoryModel Primitive where new = error "Jat.PState.MemoryModel.Primitive: not supported." getField = error "Jat.PState.MemoryModel.Primitive: not supported." putField = error "Jat.PState.MemoryModel.Primitive: not supported." invoke = error "Jat.PState.MemoryModel.Primitive: not supported." equals = error "Jat.PState.MemoryModel.Primitive: not supported." nequals = error "Jat.PState.MemoryModel.Primitive: not supported." initMem = initMemx leq = leqx lub = joinx normalize = undefined state2TRS = undefined initMemx :: (Monad m, IntDomain i) => P.ClassId -> P.MethodId -> JatM m (PState i Primitive) initMemx cn mn = do p <- getProgram let m = P.theMethod p cn mn params <- mapM defaultAbstrValue $ P.methodParams m let loc = initL params $ P.maxLoc m return $ PState emptyH [Frame loc [] cn mn 0] Primitive where defaultAbstrValue P.BoolType = BoolVal `liftM` AD.top defaultAbstrValue P.IntType = IntVal `liftM` AD.top defaultAbstrValue P.NullType = return Null defaultAbstrValue P.Void = return Unit defaultAbstrValue _ = error "Jat.PState.MemorModel.Primitive: not supported" leqx :: IntDomain i => P.Program -> PState i Primitive -> PState i Primitive -> Bool leqx _ st1 st2 | not (isSimilar st1 st2) = error "Jat.PState.MemoryModel.NoMem: unexpected case." leqx _ st1 st2 = frames st1 `leqFS` frames st2 where frms1 `leqFS` frms2 = and $ zipWith leqF frms1 frms2 frm1 `leqF` frm2 = and $ zipWith leqV (elemsF frm1) (elemsF frm2) Unit `leqV` _ = True Null `leqV` Null = True BoolVal b1 `leqV` BoolVal b2 = b1 `AD.leq` b2 IntVal i1 `leqV` IntVal i2 = i1 `AD.leq` i2 _ `leqV` _ = error "Jat.PState.MemoryModel.Primitive: not supported." joinx :: (Monad m, IntDomain i) => PState i Primitive -> PState i Primitive -> JatM m (PState i Primitive) joinx st1 st2 = do frms3 <- frames st1 `joinFS` frames st2 return $ PState (heap st1) frms3 Primitive where frms1 `joinFS` frms2 = zipWithM joinF frms1 frms2 Frame loc1 stk1 cn1 mn1 pc1 `joinF` Frame loc2 stk2 _ _ _ = do loc3 <- zipWithM joinV (elemsL loc1) (elemsL loc2) stk3 <- zipWithM joinV (elemsL stk1) (elemsL stk2) return $ Frame loc3 stk3 cn1 mn1 pc1 Unit `joinV` v = return v Null `joinV` Null = return Null BoolVal b1 `joinV` BoolVal b2 = BoolVal `liftM` (b1 `AD.lub` b2) IntVal i1 `joinV` IntVal i2 = IntVal `liftM` (i1 `AD.lub` i2) _ `joinV` _ = error "Jat.PState.MemoryModel.Primitive: not supported."
ComputationWithBoundedResources/jat
src/Jat/PState/MemoryModel/Primitive.hs
bsd-3-clause
3,363
0
12
757
1,029
529
500
65
5
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings #-} module Language.Whippet.Typecheck.ExprSpec where import Control.Lens import Control.Lens.Extras import Control.Monad.Identity import Data.Sequence (Seq) import Data.Text (Text) import qualified Data.Text as Text import qualified Language.Whippet.Parser as Parser import Language.Whippet.Parser.ParseUtils import qualified Language.Whippet.Typecheck as Typecheck import Test.Hspec main :: IO () main = hspec spec runCheck :: Parser.Expr a -> Either (Seq Typecheck.Err) Typecheck.Type runCheck = Typecheck.typecheck . fmap (const ()) instance Parser.HasPos () where position () = Nothing spec :: Spec spec = do describe "expressions" $ do let fullyQualifiedStringType = "Language.Whippet.Prim.String" fullyQualifiedIntType = "Language.Whippet.Prim.Int" fullyQualifiedCharType = "Language.Whippet.Prim.Char" fullyQualifiedScientificType = "Language.Whippet.Prim.Scientific" fullyQualifiedSeqType = "Language.Whippet.Prim.Seq" describe "literals" $ do describe "string literal" $ do let result = runCheck (str "foo") it "is accepted" $ result `shouldSatisfy` is _Right it "has the expected type" $ result ^.. _Right `shouldBe` [Typecheck.TyNominal fullyQualifiedStringType] describe "int literal" $ do let result = runCheck (int 1) it "is accepted" $ result `shouldSatisfy` is _Right it "has the expected type" $ result ^.. _Right `shouldBe` [Typecheck.TyNominal fullyQualifiedIntType] describe "char literal" $ do let result = runCheck (char 'a') it "is accepted" $ result `shouldSatisfy` is _Right it "has the expected type" $ result ^.. _Right `shouldBe` [Typecheck.TyNominal fullyQualifiedCharType] describe "scientific literal" $ do let result = runCheck (scientific 1) it "is accepted" $ result `shouldSatisfy` is _Right it "has the expected type" $ result ^.. _Right `shouldBe` [Typecheck.TyNominal fullyQualifiedScientificType] describe "list literal" $ do let tySeqOf = Typecheck.TyApp (Typecheck.TyNominal fullyQualifiedSeqType) tyInt = Typecheck.TyNominal fullyQualifiedIntType describe "homogenous children" $ do let result = runCheck (list [int 1, int 2]) it "is accepted" $ result `shouldSatisfy` is _Right it "has expected type" $ result ^.. _Right `shouldBe` [tySeqOf tyInt] describe "heterogeneous children" $ do let result = runCheck (list [int 1, str "2"]) it "is rejected" $ result `shouldSatisfy` is _Left describe "type annotations" $ do let ann :: Parser.Expr () -> Parser.Type () -> Parser.Expr () ann e t = Parser.EAnnotation (Parser.Annotation () e t) tyString = nominalType fullyQualifiedStringType describe "invalid annotation" $ do let result = runCheck (int 1 `ann` tyString) it "is rejected" $ result `shouldSatisfy` is _Left describe "valid annotation" $ do let result = runCheck (str "foo" `ann` tyString) it "is accepted" $ result `shouldSatisfy` is _Right
chrisbarrett/whippet
test/Language/Whippet/Typecheck/ExprSpec.hs
bsd-3-clause
3,970
2
34
1,479
914
449
465
78
1
module Config (config) where import Dawn import Mire.Plugin import Mire.Data.Flow import qualified Data.Text as T import qualified Testworld.World import Pipes config :: Config config = Config plugins worlds where plugins = [ Plugin "1" plugin, Plugin "2" plugin2, Plugin "3" plugin3 ] worlds = [Testworld.World.world] plugin :: Producer Flow IO () -> IO (Producer Flow IO ()) plugin p = return (p >-> pipe) where pipe = forever $ await >>= \x -> case x of (FlowInput input) -> do if input == "/test" then do yield (FlowOutput [("Plugin 1 called", [])]) yield x else yield x _ -> yield x plugin2 :: Producer Flow IO () -> IO (Producer Flow IO ()) plugin2 = command "/x" $ const $ return [undefined [("Plugin 2 called", [])]] plugin3 = command "/test" $ const $ return [FlowOutput [("Plugin 3 called", [])]] quitCommand = command "/quit" $ const $ return [FlowAction ActionQuit] quitHotkey = hotkey (Hotkey [Ctrl] (KeyChar 'd')) $ return [FlowAction ActionQuit] {-command :: Text -> ([Text] -> IO [Flow]) -> Producer Flow IO () -> IO (Producer Flow IO ()) command cmd f p = do -- let split = [cmd] -- flows <- f split let pipe = forever $ do a <- await case a of FlowInput input -> do let split = [input] -- TODO really split if head split == cmd then liftIO (f split) >>= mapM_ yield -- TODO pass only the arguments else yield a _ -> yield a return (p >-> pipe) hotkey :: Hotkey -> (IO [Flow]) -> Producer Flow IO () -> IO (Producer Flow IO ()) hotkey k f p = do let pipe = forever $ do a <- await case a of FlowHotkey h -> if h == k then liftIO f >>= mapM_ yield else yield a _ -> yield a return (p >-> pipe)-} --plugin :: Hooks -> MomentIO Hooks --plugin (Hooks e o) = do -- e' <- splitList e -- let x a = case a of -- InputText t -> [InputText (if T.isPrefixOf "/lala" t then "meep" else t)] -- c -> [c] -- return (Hooks (x <$> e') o) --plugin2 :: Hooks -> MomentIO Hooks --plugin2 (Hooks e) = Hooks <$> run where -- run = sideEvent2 e fromInputSend $ \d -> do -- let x = T.take 10 <$> d -- return (InputAction . ActionOut <$> x) --plugin2 = return --fromInputSend (InputText t) = Right t --fromInputSend a = Left a --sideEvent2 :: MonadMoment m => Event a -> (a -> Either a b) -> (Event b -> m (Event a)) -> m (Event a) --sideEvent2 event filter transform = do -- let (skip, proc) = split (filter <$> event) -- proc2 <- transform proc -- return (unionWith const skip proc2)
ellej/mire
example/Config.hs
bsd-3-clause
2,981
0
22
1,062
429
235
194
30
3
{-# LANGUAGE RecordWildCards, CPP #-} {-# LANGUAGE RecursiveDo #-} module Foreign.JavaScript.EventLoop ( eventLoop, runEval, callEval, debug, onDisconnect, newHandler, fromJSStablePtr, ) where import Control.Applicative import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.STM as STM import Control.Exception as E (finally) import Control.Monad import qualified Data.Aeson as JSON import Data.IORef import qualified Data.Map as Map import qualified Data.Text as T import qualified System.Mem import Foreign.RemotePtr as Foreign import Foreign.JavaScript.Types rebug :: IO () #ifdef REBUG rebug = System.Mem.performGC #else rebug = return () #endif {----------------------------------------------------------------------------- Event Loop ------------------------------------------------------------------------------} -- | Handle a single event handleEvent w@(Window{..}) (name, args, consistency) = do mhandler <- Foreign.lookup name wEventHandlers case mhandler of Nothing -> return () Just f -> withRemotePtr f (\_ f -> f args) -- | Event loop for a browser window. -- Supports concurrent invocations of `runEval` and `callEval`. eventLoop :: (Window -> IO void) -> (Comm -> IO ()) eventLoop init comm = do -- To support concurrent FFI calls, we make three threads. -- The thread `multiplexer` reads from the client and -- sorts the messages into the appropriate queue. events <- newTQueueIO results <- newTQueueIO :: IO (TQueue JSON.Value) -- The thread `handleCalls` executes FFI calls -- from the Haskell side in order. -- The corresponding queue records `TMVar`s in which to put the results. calls <- newTQueueIO :: IO (TQueue (Maybe (TMVar JSON.Value), ServerMsg)) -- The thread `handleEvents` handles client Events in order. -- Events will be queued (and labelled `Inconsistent`) whenever -- the server is -- * busy handling an event -- * or waiting for the result of a function call. handling <- newTVarIO False calling <- newTVarIO False -- FFI calls are made by writing to the `calls` queue. w0 <- newPartialWindow let runEval s = do atomically $ writeTQueue calls (Nothing , RunEval s) callEval s = do ref <- newEmptyTMVarIO atomically $ writeTQueue calls (Just ref, CallEval s) atomically $ takeTMVar ref debug s = do atomically $ writeServer comm $ Debug s -- We also send a separate event when the client disconnects. disconnect <- newTVarIO $ return () let onDisconnect m = atomically $ writeTVar disconnect m let w = w0 { runEval = runEval , callEval = callEval , debug = debug , onDisconnect = onDisconnect } -- The individual threads are as follows: -- -- Read client messages and send them to the -- thread that handles events or the thread that handles FFI calls. let multiplexer = do m <- untilJustM $ atomically $ do msg <- readClient comm case msg of Event x y -> do b <- (||) <$> readTVar handling <*> readTVar calling let c = if b then Inconsistent else Consistent writeTQueue events (x,y,c) return Nothing Result x -> do writeTQueue results x return Nothing Quit -> Just <$> readTVar disconnect m -- Send FFI calls to client and collect results let handleCalls = forever $ do ref <- atomically $ do (ref, msg) <- readTQueue calls writeTVar calling True writeServer comm msg return ref atomically $ do writeTVar calling False case ref of Just ref -> do result <- readTQueue results putTMVar ref result Nothing -> return () -- Receive events from client and handle them in order. let handleEvents = do init w forever $ do e <- atomically $ do writeTVar handling True readTQueue events handleEvent w e rebug atomically $ writeTVar handling False -- Foreign.addFinalizer (wRoot w) $ putStrLn "wRoot garbage collected." Foreign.withRemotePtr (wRoot w) $ \_ _ -> do -- keep root alive E.finally (foldr1 race_ [multiplexer, handleEvents, handleCalls]) (commClose comm) return () -- | Repeat an action until it returns 'Just'. Similar to 'forever'. untilJustM :: Monad m => m (Maybe a) -> m a untilJustM m = m >>= \x -> case x of Nothing -> untilJustM m Just a -> return a {----------------------------------------------------------------------------- Exports, Imports and garbage collection ------------------------------------------------------------------------------} -- | Turn a Haskell function into an event handler. newHandler :: Window -> ([JSON.Value] -> IO ()) -> IO HsEvent newHandler w@(Window{..}) handler = do coupon <- newCoupon wEventHandlers newRemotePtr coupon (handler . parseArgs) wEventHandlers where fromSuccess (JSON.Success x) = x -- parse a genuine JavaScript array parseArgs x = fromSuccess (JSON.fromJSON x) :: [JSON.Value] -- parse a JavaScript arguments object -- parseArgs x = Map.elems (fromSuccess (JSON.fromJSON x) :: Map.Map String JSON.Value) -- | Convert a stable pointer from JavaScript into a 'JSObject'. fromJSStablePtr :: JSON.Value -> Window -> IO JSObject fromJSStablePtr js w@(Window{..}) = do let JSON.Success coupon = JSON.fromJSON js mhs <- Foreign.lookup coupon wJSObjects case mhs of Just hs -> return hs Nothing -> do ptr <- newRemotePtr coupon (JSPtr coupon) wJSObjects addFinalizer ptr $ runEval ("Haskell.freeStablePtr('" ++ T.unpack coupon ++ "')") return ptr
duplode/threepenny-gui
src/Foreign/JavaScript/EventLoop.hs
bsd-3-clause
6,472
0
24
2,086
1,339
671
668
110
5
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[PrelNames]{Definitions of prelude modules and names} Nota Bene: all Names defined in here should come from the base package - ModuleNames for prelude modules, e.g. pREL_BASE_Name :: ModuleName - Modules for prelude modules e.g. pREL_Base :: Module - Uniques for Ids, DataCons, TyCons and Classes that the compiler "knows about" in some way e.g. intTyConKey :: Unique minusClassOpKey :: Unique - Names for Ids, DataCons, TyCons and Classes that the compiler "knows about" in some way e.g. intTyConName :: Name minusName :: Name One of these Names contains (a) the module and occurrence name of the thing (b) its Unique The may way the compiler "knows about" one of these things is where the type checker or desugarer needs to look it up. For example, when desugaring list comprehensions the desugarer needs to conjure up 'foldr'. It does this by looking up foldrName in the environment. - RdrNames for Ids, DataCons etc that the compiler may emit into generated code (e.g. for deriving). It's not necessary to know the uniques for these guys, only their names Note [Known-key names] ~~~~~~~~~~~~~~~~~~~~~~ It is *very* important that the compiler gives wired-in things and things with "known-key" names the correct Uniques wherever they occur. We have to be careful about this in exactly two places: 1. When we parse some source code, renaming the AST better yield an AST whose Names have the correct uniques 2. When we read an interface file, the read-in gubbins better have the right uniques This is accomplished through a combination of mechanisms: 1. When parsing source code, the RdrName-decorated AST has some RdrNames which are Exact. These are wired-in RdrNames where the we could directly tell from the parsed syntax what Name to use. For example, when we parse a [] in a type we can just insert an Exact RdrName Name with the listTyConKey. Currently, I believe this is just an optimisation: it would be equally valid to just output Orig RdrNames that correctly record the module etc we expect the final Name to come from. However, were we to eliminate isBuiltInOcc_maybe it would become essential (see point 3). 2. The knownKeyNames (which consist of the basicKnownKeyNames from the module, and those names reachable via the wired-in stuff from TysWiredIn) are used to initialise the "OrigNameCache" in IfaceEnv. This initialization ensures that when the type checker or renamer (both of which use IfaceEnv) look up an original name (i.e. a pair of a Module and an OccName) for a known-key name they get the correct Unique. This is the most important mechanism for ensuring that known-key stuff gets the right Unique, and is why it is so important to place your known-key names in the appropriate lists. 3. For "infinite families" of known-key names (i.e. tuples), we have to be extra careful. Because there are an infinite number of these things, we cannot add them to the list of known-key names used to initialise the OrigNameCache. Instead, we have to rely on never having to look them up in that cache. This is accomplished through a variety of mechanisms: a) The parser recognises them specially and generates an Exact Name (hence not looked up in the orig-name cache) b) The known infinite families of names are specially serialised by BinIface.putName, with that special treatment detected when we read back to ensure that we get back to the correct uniques. Most of the infinite families cannot occur in source code, so mechanisms (a,b) sufficies to ensure that they always have the right Unique. In particular, implicit param TyCon names, constraint tuples and Any TyCons cannot be mentioned by the user. c) IfaceEnv.lookupOrigNameCache uses isBuiltInOcc_maybe to map built-in syntax directly onto the corresponding name, rather than trying to find it in the original-name cache. See also Note [Built-in syntax and the OrigNameCache] -} {-# LANGUAGE CPP #-} module PrelNames ( Unique, Uniquable(..), hasKey, -- Re-exported for convenience ----------------------------------------------------------- module PrelNames, -- A huge bunch of (a) Names, e.g. intTyConName -- (b) Uniques e.g. intTyConKey -- (c) Groups of classes and types -- (d) miscellaneous things -- So many that we export them all ) where #include "HsVersions.h" import Module import OccName import RdrName import Unique import Name import SrcLoc import FastString import Config ( cIntegerLibraryType, IntegerLibrary(..) ) import Panic ( panic ) {- ************************************************************************ * * allNameStrings * * ************************************************************************ -} allNameStrings :: [String] -- Infinite list of a,b,c...z, aa, ab, ac, ... etc allNameStrings = [ c:cs | cs <- "" : allNameStrings, c <- ['a'..'z'] ] {- ************************************************************************ * * \subsection{Local Names} * * ************************************************************************ This *local* name is used by the interactive stuff -} itName :: Unique -> SrcSpan -> Name itName uniq loc = mkInternalName uniq (mkOccNameFS varName (fsLit "it")) loc -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly -- during compiler debugging. mkUnboundName :: OccName -> Name mkUnboundName occ = mkInternalName unboundKey occ noSrcSpan isUnboundName :: Name -> Bool isUnboundName name = name `hasKey` unboundKey {- ************************************************************************ * * \subsection{Known key Names} * * ************************************************************************ This section tells what the compiler knows about the association of names with uniques. These ones are the *non* wired-in ones. The wired in ones are defined in TysWiredIn etc. -} basicKnownKeyNames :: [Name] basicKnownKeyNames = genericTyConNames ++ [ -- Classes. *Must* include: -- classes that are grabbed by key (e.g., eqClassKey) -- classes in "Class.standardClassKeys" (quite a few) eqClassName, -- mentioned, derivable ordClassName, -- derivable boundedClassName, -- derivable numClassName, -- mentioned, numeric enumClassName, -- derivable monadClassName, functorClassName, realClassName, -- numeric integralClassName, -- numeric fractionalClassName, -- numeric floatingClassName, -- numeric realFracClassName, -- numeric realFloatClassName, -- numeric dataClassName, isStringClassName, applicativeClassName, alternativeClassName, foldableClassName, traversableClassName, semigroupClassName, sappendName, monoidClassName, memptyName, mappendName, mconcatName, -- The IO type -- See Note [TyConRepNames for non-wired-in TyCons] ioTyConName, ioDataConName, runMainIOName, -- Type representation types trModuleTyConName, trModuleDataConName, trNameTyConName, trNameSDataConName, trNameDDataConName, trTyConTyConName, trTyConDataConName, -- Typeable typeableClassName, typeRepTyConName, typeRepIdName, mkPolyTyConAppName, mkAppTyName, typeSymbolTypeRepName, typeNatTypeRepName, trGhcPrimModuleName, -- Dynamic toDynName, -- Numeric stuff negateName, minusName, geName, eqName, -- Conversion functions rationalTyConName, ratioTyConName, ratioDataConName, fromRationalName, fromIntegerName, toIntegerName, toRationalName, fromIntegralName, realToFracName, -- String stuff fromStringName, -- Enum stuff enumFromName, enumFromThenName, enumFromThenToName, enumFromToName, -- Applicative stuff pureAName, apAName, thenAName, -- Monad stuff thenIOName, bindIOName, returnIOName, failIOName, bindMName, thenMName, returnMName, fmapName, joinMName, -- MonadFail monadFailClassName, failMName, failMName_preMFP, -- MonadFix monadFixClassName, mfixName, -- Arrow stuff arrAName, composeAName, firstAName, appAName, choiceAName, loopAName, -- Ix stuff ixClassName, -- Show stuff showClassName, -- Read stuff readClassName, -- Stable pointers newStablePtrName, -- GHC Extensions groupWithName, -- Strings and lists unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name, -- Overloaded lists isListClassName, fromListName, fromListNName, toListName, -- List operations concatName, filterName, mapName, zipName, foldrName, buildName, augmentName, appendName, -- FFI primitive types that are not wired-in. stablePtrTyConName, ptrTyConName, funPtrTyConName, int8TyConName, int16TyConName, int32TyConName, int64TyConName, word16TyConName, word32TyConName, word64TyConName, -- Others otherwiseIdName, inlineIdName, eqStringName, assertName, breakpointName, breakpointCondName, breakpointAutoName, opaqueTyConName, assertErrorName, printName, fstName, sndName, -- Integer integerTyConName, mkIntegerName, integerToWord64Name, integerToInt64Name, word64ToIntegerName, int64ToIntegerName, plusIntegerName, timesIntegerName, smallIntegerName, wordToIntegerName, integerToWordName, integerToIntName, minusIntegerName, negateIntegerName, eqIntegerPrimName, neqIntegerPrimName, absIntegerName, signumIntegerName, leIntegerPrimName, gtIntegerPrimName, ltIntegerPrimName, geIntegerPrimName, compareIntegerName, quotRemIntegerName, divModIntegerName, quotIntegerName, remIntegerName, divIntegerName, modIntegerName, floatFromIntegerName, doubleFromIntegerName, encodeFloatIntegerName, encodeDoubleIntegerName, decodeDoubleIntegerName, gcdIntegerName, lcmIntegerName, andIntegerName, orIntegerName, xorIntegerName, complementIntegerName, shiftLIntegerName, shiftRIntegerName, bitIntegerName, -- Float/Double rationalToFloatName, rationalToDoubleName, -- Other classes randomClassName, randomGenClassName, monadPlusClassName, -- Type-level naturals knownNatClassName, knownSymbolClassName, -- Overloaded labels isLabelClassName, -- Implicit Parameters ipClassName, -- Call Stacks callStackTyConName, emptyCallStackName, pushCallStackName, -- Source Locations srcLocDataConName, -- Annotation type checking toAnnotationWrapperName -- The Ordering type , orderingTyConName , ltDataConName, eqDataConName, gtDataConName -- The SPEC type for SpecConstr , specTyConName -- The Either type , eitherTyConName, leftDataConName, rightDataConName -- Plugins , pluginTyConName , frontendPluginTyConName -- Generics , genClassName, gen1ClassName , datatypeClassName, constructorClassName, selectorClassName -- Monad comprehensions , guardMName , liftMName , mzipName -- GHCi Sandbox , ghciIoClassName, ghciStepIoMName -- StaticPtr , staticPtrTyConName , staticPtrDataConName, staticPtrInfoDataConName , fromStaticPtrName -- Fingerprint , fingerprintDataConName -- Custom type errors , errorMessageTypeErrorFamName , typeErrorTextDataConName , typeErrorAppendDataConName , typeErrorVAppendDataConName , typeErrorShowTypeDataConName -- homogeneous equality , eqTyConName ] ++ case cIntegerLibraryType of IntegerGMP -> [integerSDataConName] IntegerSimple -> [] genericTyConNames :: [Name] genericTyConNames = [ v1TyConName, u1TyConName, par1TyConName, rec1TyConName, k1TyConName, m1TyConName, sumTyConName, prodTyConName, compTyConName, rTyConName, dTyConName, cTyConName, sTyConName, rec0TyConName, d1TyConName, c1TyConName, s1TyConName, noSelTyConName, repTyConName, rep1TyConName, uRecTyConName, uAddrTyConName, uCharTyConName, uDoubleTyConName, uFloatTyConName, uIntTyConName, uWordTyConName, prefixIDataConName, infixIDataConName, leftAssociativeDataConName, rightAssociativeDataConName, notAssociativeDataConName, sourceUnpackDataConName, sourceNoUnpackDataConName, noSourceUnpackednessDataConName, sourceLazyDataConName, sourceStrictDataConName, noSourceStrictnessDataConName, decidedLazyDataConName, decidedStrictDataConName, decidedUnpackDataConName, metaDataDataConName, metaConsDataConName, metaSelDataConName ] {- ************************************************************************ * * \subsection{Module names} * * ************************************************************************ --MetaHaskell Extension Add a new module here -} pRELUDE :: Module pRELUDE = mkBaseModule_ pRELUDE_NAME gHC_PRIM, gHC_TYPES, gHC_GENERICS, gHC_MAGIC, gHC_CLASSES, gHC_BASE, gHC_ENUM, gHC_GHCI, gHC_CSTRING, gHC_SHOW, gHC_READ, gHC_NUM, gHC_INTEGER_TYPE, gHC_LIST, gHC_TUPLE, dATA_TUPLE, dATA_EITHER, dATA_STRING, dATA_FOLDABLE, dATA_TRAVERSABLE, dATA_MONOID, dATA_SEMIGROUP, gHC_CONC, gHC_IO, gHC_IO_Exception, gHC_ST, gHC_ARR, gHC_STABLE, gHC_PTR, gHC_ERR, gHC_REAL, gHC_FLOAT, gHC_TOP_HANDLER, sYSTEM_IO, dYNAMIC, tYPEABLE, tYPEABLE_INTERNAL, gENERICS, rEAD_PREC, lEX, gHC_INT, gHC_WORD, mONAD, mONAD_FIX, mONAD_ZIP, mONAD_FAIL, aRROW, cONTROL_APPLICATIVE, gHC_DESUGAR, rANDOM, gHC_EXTS, cONTROL_EXCEPTION_BASE, gHC_TYPELITS, dATA_TYPE_EQUALITY, dATA_COERCE :: Module gHC_PRIM = mkPrimModule (fsLit "GHC.Prim") -- Primitive types and values gHC_TYPES = mkPrimModule (fsLit "GHC.Types") gHC_MAGIC = mkPrimModule (fsLit "GHC.Magic") gHC_CSTRING = mkPrimModule (fsLit "GHC.CString") gHC_CLASSES = mkPrimModule (fsLit "GHC.Classes") gHC_BASE = mkBaseModule (fsLit "GHC.Base") gHC_ENUM = mkBaseModule (fsLit "GHC.Enum") gHC_GHCI = mkBaseModule (fsLit "GHC.GHCi") gHC_SHOW = mkBaseModule (fsLit "GHC.Show") gHC_READ = mkBaseModule (fsLit "GHC.Read") gHC_NUM = mkBaseModule (fsLit "GHC.Num") gHC_INTEGER_TYPE= mkIntegerModule (fsLit "GHC.Integer.Type") gHC_LIST = mkBaseModule (fsLit "GHC.List") gHC_TUPLE = mkPrimModule (fsLit "GHC.Tuple") dATA_TUPLE = mkBaseModule (fsLit "Data.Tuple") dATA_EITHER = mkBaseModule (fsLit "Data.Either") dATA_STRING = mkBaseModule (fsLit "Data.String") dATA_FOLDABLE = mkBaseModule (fsLit "Data.Foldable") dATA_TRAVERSABLE= mkBaseModule (fsLit "Data.Traversable") dATA_SEMIGROUP = mkBaseModule (fsLit "Data.Semigroup") dATA_MONOID = mkBaseModule (fsLit "Data.Monoid") gHC_CONC = mkBaseModule (fsLit "GHC.Conc") gHC_IO = mkBaseModule (fsLit "GHC.IO") gHC_IO_Exception = mkBaseModule (fsLit "GHC.IO.Exception") gHC_ST = mkBaseModule (fsLit "GHC.ST") gHC_ARR = mkBaseModule (fsLit "GHC.Arr") gHC_STABLE = mkBaseModule (fsLit "GHC.Stable") gHC_PTR = mkBaseModule (fsLit "GHC.Ptr") gHC_ERR = mkBaseModule (fsLit "GHC.Err") gHC_REAL = mkBaseModule (fsLit "GHC.Real") gHC_FLOAT = mkBaseModule (fsLit "GHC.Float") gHC_TOP_HANDLER = mkBaseModule (fsLit "GHC.TopHandler") sYSTEM_IO = mkBaseModule (fsLit "System.IO") dYNAMIC = mkBaseModule (fsLit "Data.Dynamic") tYPEABLE = mkBaseModule (fsLit "Data.Typeable") tYPEABLE_INTERNAL = mkBaseModule (fsLit "Data.Typeable.Internal") gENERICS = mkBaseModule (fsLit "Data.Data") rEAD_PREC = mkBaseModule (fsLit "Text.ParserCombinators.ReadPrec") lEX = mkBaseModule (fsLit "Text.Read.Lex") gHC_INT = mkBaseModule (fsLit "GHC.Int") gHC_WORD = mkBaseModule (fsLit "GHC.Word") mONAD = mkBaseModule (fsLit "Control.Monad") mONAD_FIX = mkBaseModule (fsLit "Control.Monad.Fix") mONAD_ZIP = mkBaseModule (fsLit "Control.Monad.Zip") mONAD_FAIL = mkBaseModule (fsLit "Control.Monad.Fail") aRROW = mkBaseModule (fsLit "Control.Arrow") cONTROL_APPLICATIVE = mkBaseModule (fsLit "Control.Applicative") gHC_DESUGAR = mkBaseModule (fsLit "GHC.Desugar") rANDOM = mkBaseModule (fsLit "System.Random") gHC_EXTS = mkBaseModule (fsLit "GHC.Exts") cONTROL_EXCEPTION_BASE = mkBaseModule (fsLit "Control.Exception.Base") gHC_GENERICS = mkBaseModule (fsLit "GHC.Generics") gHC_TYPELITS = mkBaseModule (fsLit "GHC.TypeLits") dATA_TYPE_EQUALITY = mkBaseModule (fsLit "Data.Type.Equality") dATA_COERCE = mkBaseModule (fsLit "Data.Coerce") gHC_PARR' :: Module gHC_PARR' = mkBaseModule (fsLit "GHC.PArr") gHC_SRCLOC :: Module gHC_SRCLOC = mkBaseModule (fsLit "GHC.SrcLoc") gHC_STACK, gHC_STACK_TYPES :: Module gHC_STACK = mkBaseModule (fsLit "GHC.Stack") gHC_STACK_TYPES = mkBaseModule (fsLit "GHC.Stack.Types") gHC_STATICPTR :: Module gHC_STATICPTR = mkBaseModule (fsLit "GHC.StaticPtr") gHC_FINGERPRINT_TYPE :: Module gHC_FINGERPRINT_TYPE = mkBaseModule (fsLit "GHC.Fingerprint.Type") gHC_OVER_LABELS :: Module gHC_OVER_LABELS = mkBaseModule (fsLit "GHC.OverloadedLabels") mAIN, rOOT_MAIN :: Module mAIN = mkMainModule_ mAIN_NAME rOOT_MAIN = mkMainModule (fsLit ":Main") -- Root module for initialisation mkInteractiveModule :: Int -> Module -- (mkInteractiveMoudule 9) makes module 'interactive:M9' mkInteractiveModule n = mkModule interactiveUnitId (mkModuleName ("Ghci" ++ show n)) pRELUDE_NAME, mAIN_NAME :: ModuleName pRELUDE_NAME = mkModuleNameFS (fsLit "Prelude") mAIN_NAME = mkModuleNameFS (fsLit "Main") dATA_ARRAY_PARALLEL_NAME, dATA_ARRAY_PARALLEL_PRIM_NAME :: ModuleName dATA_ARRAY_PARALLEL_NAME = mkModuleNameFS (fsLit "Data.Array.Parallel") dATA_ARRAY_PARALLEL_PRIM_NAME = mkModuleNameFS (fsLit "Data.Array.Parallel.Prim") mkPrimModule :: FastString -> Module mkPrimModule m = mkModule primUnitId (mkModuleNameFS m) mkIntegerModule :: FastString -> Module mkIntegerModule m = mkModule integerUnitId (mkModuleNameFS m) mkBaseModule :: FastString -> Module mkBaseModule m = mkModule baseUnitId (mkModuleNameFS m) mkBaseModule_ :: ModuleName -> Module mkBaseModule_ m = mkModule baseUnitId m mkThisGhcModule :: FastString -> Module mkThisGhcModule m = mkModule thisGhcUnitId (mkModuleNameFS m) mkThisGhcModule_ :: ModuleName -> Module mkThisGhcModule_ m = mkModule thisGhcUnitId m mkMainModule :: FastString -> Module mkMainModule m = mkModule mainUnitId (mkModuleNameFS m) mkMainModule_ :: ModuleName -> Module mkMainModule_ m = mkModule mainUnitId m {- ************************************************************************ * * RdrNames * * ************************************************************************ -} main_RDR_Unqual :: RdrName main_RDR_Unqual = mkUnqual varName (fsLit "main") -- We definitely don't want an Orig RdrName, because -- main might, in principle, be imported into module Main forall_tv_RDR, dot_tv_RDR :: RdrName forall_tv_RDR = mkUnqual tvName (fsLit "forall") dot_tv_RDR = mkUnqual tvName (fsLit ".") eq_RDR, ge_RDR, ne_RDR, le_RDR, lt_RDR, gt_RDR, compare_RDR, ltTag_RDR, eqTag_RDR, gtTag_RDR :: RdrName eq_RDR = nameRdrName eqName ge_RDR = nameRdrName geName ne_RDR = varQual_RDR gHC_CLASSES (fsLit "/=") le_RDR = varQual_RDR gHC_CLASSES (fsLit "<=") lt_RDR = varQual_RDR gHC_CLASSES (fsLit "<") gt_RDR = varQual_RDR gHC_CLASSES (fsLit ">") compare_RDR = varQual_RDR gHC_CLASSES (fsLit "compare") ltTag_RDR = dataQual_RDR gHC_TYPES (fsLit "LT") eqTag_RDR = dataQual_RDR gHC_TYPES (fsLit "EQ") gtTag_RDR = dataQual_RDR gHC_TYPES (fsLit "GT") eqClass_RDR, numClass_RDR, ordClass_RDR, enumClass_RDR, monadClass_RDR :: RdrName eqClass_RDR = nameRdrName eqClassName numClass_RDR = nameRdrName numClassName ordClass_RDR = nameRdrName ordClassName enumClass_RDR = nameRdrName enumClassName monadClass_RDR = nameRdrName monadClassName map_RDR, append_RDR :: RdrName map_RDR = varQual_RDR gHC_BASE (fsLit "map") append_RDR = varQual_RDR gHC_BASE (fsLit "++") foldr_RDR, build_RDR, returnM_RDR, bindM_RDR, failM_RDR_preMFP, failM_RDR:: RdrName foldr_RDR = nameRdrName foldrName build_RDR = nameRdrName buildName returnM_RDR = nameRdrName returnMName bindM_RDR = nameRdrName bindMName failM_RDR_preMFP = nameRdrName failMName_preMFP failM_RDR = nameRdrName failMName left_RDR, right_RDR :: RdrName left_RDR = nameRdrName leftDataConName right_RDR = nameRdrName rightDataConName fromEnum_RDR, toEnum_RDR :: RdrName fromEnum_RDR = varQual_RDR gHC_ENUM (fsLit "fromEnum") toEnum_RDR = varQual_RDR gHC_ENUM (fsLit "toEnum") enumFrom_RDR, enumFromTo_RDR, enumFromThen_RDR, enumFromThenTo_RDR :: RdrName enumFrom_RDR = nameRdrName enumFromName enumFromTo_RDR = nameRdrName enumFromToName enumFromThen_RDR = nameRdrName enumFromThenName enumFromThenTo_RDR = nameRdrName enumFromThenToName ratioDataCon_RDR, plusInteger_RDR, timesInteger_RDR :: RdrName ratioDataCon_RDR = nameRdrName ratioDataConName plusInteger_RDR = nameRdrName plusIntegerName timesInteger_RDR = nameRdrName timesIntegerName ioDataCon_RDR :: RdrName ioDataCon_RDR = nameRdrName ioDataConName eqString_RDR, unpackCString_RDR, unpackCStringFoldr_RDR, unpackCStringUtf8_RDR :: RdrName eqString_RDR = nameRdrName eqStringName unpackCString_RDR = nameRdrName unpackCStringName unpackCStringFoldr_RDR = nameRdrName unpackCStringFoldrName unpackCStringUtf8_RDR = nameRdrName unpackCStringUtf8Name newStablePtr_RDR :: RdrName newStablePtr_RDR = nameRdrName newStablePtrName bindIO_RDR, returnIO_RDR :: RdrName bindIO_RDR = nameRdrName bindIOName returnIO_RDR = nameRdrName returnIOName fromInteger_RDR, fromRational_RDR, minus_RDR, times_RDR, plus_RDR :: RdrName fromInteger_RDR = nameRdrName fromIntegerName fromRational_RDR = nameRdrName fromRationalName minus_RDR = nameRdrName minusName times_RDR = varQual_RDR gHC_NUM (fsLit "*") plus_RDR = varQual_RDR gHC_NUM (fsLit "+") toInteger_RDR, toRational_RDR, fromIntegral_RDR :: RdrName toInteger_RDR = nameRdrName toIntegerName toRational_RDR = nameRdrName toRationalName fromIntegral_RDR = nameRdrName fromIntegralName stringTy_RDR, fromString_RDR :: RdrName stringTy_RDR = tcQual_RDR gHC_BASE (fsLit "String") fromString_RDR = nameRdrName fromStringName fromList_RDR, fromListN_RDR, toList_RDR :: RdrName fromList_RDR = nameRdrName fromListName fromListN_RDR = nameRdrName fromListNName toList_RDR = nameRdrName toListName compose_RDR :: RdrName compose_RDR = varQual_RDR gHC_BASE (fsLit ".") not_RDR, getTag_RDR, succ_RDR, pred_RDR, minBound_RDR, maxBound_RDR, and_RDR, range_RDR, inRange_RDR, index_RDR, unsafeIndex_RDR, unsafeRangeSize_RDR :: RdrName and_RDR = varQual_RDR gHC_CLASSES (fsLit "&&") not_RDR = varQual_RDR gHC_CLASSES (fsLit "not") getTag_RDR = varQual_RDR gHC_BASE (fsLit "getTag") succ_RDR = varQual_RDR gHC_ENUM (fsLit "succ") pred_RDR = varQual_RDR gHC_ENUM (fsLit "pred") minBound_RDR = varQual_RDR gHC_ENUM (fsLit "minBound") maxBound_RDR = varQual_RDR gHC_ENUM (fsLit "maxBound") range_RDR = varQual_RDR gHC_ARR (fsLit "range") inRange_RDR = varQual_RDR gHC_ARR (fsLit "inRange") index_RDR = varQual_RDR gHC_ARR (fsLit "index") unsafeIndex_RDR = varQual_RDR gHC_ARR (fsLit "unsafeIndex") unsafeRangeSize_RDR = varQual_RDR gHC_ARR (fsLit "unsafeRangeSize") readList_RDR, readListDefault_RDR, readListPrec_RDR, readListPrecDefault_RDR, readPrec_RDR, parens_RDR, choose_RDR, lexP_RDR, expectP_RDR :: RdrName readList_RDR = varQual_RDR gHC_READ (fsLit "readList") readListDefault_RDR = varQual_RDR gHC_READ (fsLit "readListDefault") readListPrec_RDR = varQual_RDR gHC_READ (fsLit "readListPrec") readListPrecDefault_RDR = varQual_RDR gHC_READ (fsLit "readListPrecDefault") readPrec_RDR = varQual_RDR gHC_READ (fsLit "readPrec") parens_RDR = varQual_RDR gHC_READ (fsLit "parens") choose_RDR = varQual_RDR gHC_READ (fsLit "choose") lexP_RDR = varQual_RDR gHC_READ (fsLit "lexP") expectP_RDR = varQual_RDR gHC_READ (fsLit "expectP") punc_RDR, ident_RDR, symbol_RDR :: RdrName punc_RDR = dataQual_RDR lEX (fsLit "Punc") ident_RDR = dataQual_RDR lEX (fsLit "Ident") symbol_RDR = dataQual_RDR lEX (fsLit "Symbol") step_RDR, alt_RDR, reset_RDR, prec_RDR, pfail_RDR :: RdrName step_RDR = varQual_RDR rEAD_PREC (fsLit "step") alt_RDR = varQual_RDR rEAD_PREC (fsLit "+++") reset_RDR = varQual_RDR rEAD_PREC (fsLit "reset") prec_RDR = varQual_RDR rEAD_PREC (fsLit "prec") pfail_RDR = varQual_RDR rEAD_PREC (fsLit "pfail") showList_RDR, showList___RDR, showsPrec_RDR, shows_RDR, showString_RDR, showSpace_RDR, showParen_RDR :: RdrName showList_RDR = varQual_RDR gHC_SHOW (fsLit "showList") showList___RDR = varQual_RDR gHC_SHOW (fsLit "showList__") showsPrec_RDR = varQual_RDR gHC_SHOW (fsLit "showsPrec") shows_RDR = varQual_RDR gHC_SHOW (fsLit "shows") showString_RDR = varQual_RDR gHC_SHOW (fsLit "showString") showSpace_RDR = varQual_RDR gHC_SHOW (fsLit "showSpace") showParen_RDR = varQual_RDR gHC_SHOW (fsLit "showParen") undefined_RDR :: RdrName undefined_RDR = varQual_RDR gHC_ERR (fsLit "undefined") error_RDR :: RdrName error_RDR = varQual_RDR gHC_ERR (fsLit "error") -- Generics (constructors and functions) u1DataCon_RDR, par1DataCon_RDR, rec1DataCon_RDR, k1DataCon_RDR, m1DataCon_RDR, l1DataCon_RDR, r1DataCon_RDR, prodDataCon_RDR, comp1DataCon_RDR, unPar1_RDR, unRec1_RDR, unK1_RDR, unComp1_RDR, from_RDR, from1_RDR, to_RDR, to1_RDR, datatypeName_RDR, moduleName_RDR, packageName_RDR, isNewtypeName_RDR, conName_RDR, conFixity_RDR, conIsRecord_RDR, selName_RDR, prefixDataCon_RDR, infixDataCon_RDR, leftAssocDataCon_RDR, rightAssocDataCon_RDR, notAssocDataCon_RDR, uAddrDataCon_RDR, uCharDataCon_RDR, uDoubleDataCon_RDR, uFloatDataCon_RDR, uIntDataCon_RDR, uWordDataCon_RDR, uAddrHash_RDR, uCharHash_RDR, uDoubleHash_RDR, uFloatHash_RDR, uIntHash_RDR, uWordHash_RDR :: RdrName u1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "U1") par1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Par1") rec1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Rec1") k1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "K1") m1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "M1") l1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "L1") r1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "R1") prodDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit ":*:") comp1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Comp1") unPar1_RDR = varQual_RDR gHC_GENERICS (fsLit "unPar1") unRec1_RDR = varQual_RDR gHC_GENERICS (fsLit "unRec1") unK1_RDR = varQual_RDR gHC_GENERICS (fsLit "unK1") unComp1_RDR = varQual_RDR gHC_GENERICS (fsLit "unComp1") from_RDR = varQual_RDR gHC_GENERICS (fsLit "from") from1_RDR = varQual_RDR gHC_GENERICS (fsLit "from1") to_RDR = varQual_RDR gHC_GENERICS (fsLit "to") to1_RDR = varQual_RDR gHC_GENERICS (fsLit "to1") datatypeName_RDR = varQual_RDR gHC_GENERICS (fsLit "datatypeName") moduleName_RDR = varQual_RDR gHC_GENERICS (fsLit "moduleName") packageName_RDR = varQual_RDR gHC_GENERICS (fsLit "packageName") isNewtypeName_RDR = varQual_RDR gHC_GENERICS (fsLit "isNewtype") selName_RDR = varQual_RDR gHC_GENERICS (fsLit "selName") conName_RDR = varQual_RDR gHC_GENERICS (fsLit "conName") conFixity_RDR = varQual_RDR gHC_GENERICS (fsLit "conFixity") conIsRecord_RDR = varQual_RDR gHC_GENERICS (fsLit "conIsRecord") prefixDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Prefix") infixDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Infix") leftAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "LeftAssociative") rightAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "RightAssociative") notAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "NotAssociative") uAddrDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UAddr") uCharDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UChar") uDoubleDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UDouble") uFloatDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UFloat") uIntDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UInt") uWordDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UWord") uAddrHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uAddr#") uCharHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uChar#") uDoubleHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uDouble#") uFloatHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uFloat#") uIntHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uInt#") uWordHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uWord#") fmap_RDR, pure_RDR, ap_RDR, foldable_foldr_RDR, foldMap_RDR, traverse_RDR, mempty_RDR, mappend_RDR :: RdrName fmap_RDR = varQual_RDR gHC_BASE (fsLit "fmap") pure_RDR = nameRdrName pureAName ap_RDR = nameRdrName apAName foldable_foldr_RDR = varQual_RDR dATA_FOLDABLE (fsLit "foldr") foldMap_RDR = varQual_RDR dATA_FOLDABLE (fsLit "foldMap") traverse_RDR = varQual_RDR dATA_TRAVERSABLE (fsLit "traverse") mempty_RDR = varQual_RDR gHC_BASE (fsLit "mempty") mappend_RDR = varQual_RDR gHC_BASE (fsLit "mappend") eqTyCon_RDR :: RdrName eqTyCon_RDR = tcQual_RDR dATA_TYPE_EQUALITY (fsLit "~") ---------------------- varQual_RDR, tcQual_RDR, clsQual_RDR, dataQual_RDR :: Module -> FastString -> RdrName varQual_RDR mod str = mkOrig mod (mkOccNameFS varName str) tcQual_RDR mod str = mkOrig mod (mkOccNameFS tcName str) clsQual_RDR mod str = mkOrig mod (mkOccNameFS clsName str) dataQual_RDR mod str = mkOrig mod (mkOccNameFS dataName str) {- ************************************************************************ * * \subsection{Known-key names} * * ************************************************************************ Many of these Names are not really "built in", but some parts of the compiler (notably the deriving mechanism) need to mention their names, and it's convenient to write them all down in one place. --MetaHaskell Extension add the constrs and the lower case case -- guys as well (perhaps) e.g. see trueDataConName below -} wildCardName :: Name wildCardName = mkSystemVarName wildCardKey (fsLit "wild") runMainIOName :: Name runMainIOName = varQual gHC_TOP_HANDLER (fsLit "runMainIO") runMainKey orderingTyConName, ltDataConName, eqDataConName, gtDataConName :: Name orderingTyConName = tcQual gHC_TYPES (fsLit "Ordering") orderingTyConKey ltDataConName = dcQual gHC_TYPES (fsLit "LT") ltDataConKey eqDataConName = dcQual gHC_TYPES (fsLit "EQ") eqDataConKey gtDataConName = dcQual gHC_TYPES (fsLit "GT") gtDataConKey specTyConName :: Name specTyConName = tcQual gHC_TYPES (fsLit "SPEC") specTyConKey eitherTyConName, leftDataConName, rightDataConName :: Name eitherTyConName = tcQual dATA_EITHER (fsLit "Either") eitherTyConKey leftDataConName = dcQual dATA_EITHER (fsLit "Left") leftDataConKey rightDataConName = dcQual dATA_EITHER (fsLit "Right") rightDataConKey -- Generics (types) v1TyConName, u1TyConName, par1TyConName, rec1TyConName, k1TyConName, m1TyConName, sumTyConName, prodTyConName, compTyConName, rTyConName, dTyConName, cTyConName, sTyConName, rec0TyConName, d1TyConName, c1TyConName, s1TyConName, noSelTyConName, repTyConName, rep1TyConName, uRecTyConName, uAddrTyConName, uCharTyConName, uDoubleTyConName, uFloatTyConName, uIntTyConName, uWordTyConName, prefixIDataConName, infixIDataConName, leftAssociativeDataConName, rightAssociativeDataConName, notAssociativeDataConName, sourceUnpackDataConName, sourceNoUnpackDataConName, noSourceUnpackednessDataConName, sourceLazyDataConName, sourceStrictDataConName, noSourceStrictnessDataConName, decidedLazyDataConName, decidedStrictDataConName, decidedUnpackDataConName, metaDataDataConName, metaConsDataConName, metaSelDataConName :: Name v1TyConName = tcQual gHC_GENERICS (fsLit "V1") v1TyConKey u1TyConName = tcQual gHC_GENERICS (fsLit "U1") u1TyConKey par1TyConName = tcQual gHC_GENERICS (fsLit "Par1") par1TyConKey rec1TyConName = tcQual gHC_GENERICS (fsLit "Rec1") rec1TyConKey k1TyConName = tcQual gHC_GENERICS (fsLit "K1") k1TyConKey m1TyConName = tcQual gHC_GENERICS (fsLit "M1") m1TyConKey sumTyConName = tcQual gHC_GENERICS (fsLit ":+:") sumTyConKey prodTyConName = tcQual gHC_GENERICS (fsLit ":*:") prodTyConKey compTyConName = tcQual gHC_GENERICS (fsLit ":.:") compTyConKey rTyConName = tcQual gHC_GENERICS (fsLit "R") rTyConKey dTyConName = tcQual gHC_GENERICS (fsLit "D") dTyConKey cTyConName = tcQual gHC_GENERICS (fsLit "C") cTyConKey sTyConName = tcQual gHC_GENERICS (fsLit "S") sTyConKey rec0TyConName = tcQual gHC_GENERICS (fsLit "Rec0") rec0TyConKey d1TyConName = tcQual gHC_GENERICS (fsLit "D1") d1TyConKey c1TyConName = tcQual gHC_GENERICS (fsLit "C1") c1TyConKey s1TyConName = tcQual gHC_GENERICS (fsLit "S1") s1TyConKey noSelTyConName = tcQual gHC_GENERICS (fsLit "NoSelector") noSelTyConKey repTyConName = tcQual gHC_GENERICS (fsLit "Rep") repTyConKey rep1TyConName = tcQual gHC_GENERICS (fsLit "Rep1") rep1TyConKey uRecTyConName = tcQual gHC_GENERICS (fsLit "URec") uRecTyConKey uAddrTyConName = tcQual gHC_GENERICS (fsLit "UAddr") uAddrTyConKey uCharTyConName = tcQual gHC_GENERICS (fsLit "UChar") uCharTyConKey uDoubleTyConName = tcQual gHC_GENERICS (fsLit "UDouble") uDoubleTyConKey uFloatTyConName = tcQual gHC_GENERICS (fsLit "UFloat") uFloatTyConKey uIntTyConName = tcQual gHC_GENERICS (fsLit "UInt") uIntTyConKey uWordTyConName = tcQual gHC_GENERICS (fsLit "UWord") uWordTyConKey prefixIDataConName = dcQual gHC_GENERICS (fsLit "PrefixI") prefixIDataConKey infixIDataConName = dcQual gHC_GENERICS (fsLit "InfixI") infixIDataConKey leftAssociativeDataConName = dcQual gHC_GENERICS (fsLit "LeftAssociative") leftAssociativeDataConKey rightAssociativeDataConName = dcQual gHC_GENERICS (fsLit "RightAssociative") rightAssociativeDataConKey notAssociativeDataConName = dcQual gHC_GENERICS (fsLit "NotAssociative") notAssociativeDataConKey sourceUnpackDataConName = dcQual gHC_GENERICS (fsLit "SourceUnpack") sourceUnpackDataConKey sourceNoUnpackDataConName = dcQual gHC_GENERICS (fsLit "SourceNoUnpack") sourceNoUnpackDataConKey noSourceUnpackednessDataConName = dcQual gHC_GENERICS (fsLit "NoSourceUnpackedness") noSourceUnpackednessDataConKey sourceLazyDataConName = dcQual gHC_GENERICS (fsLit "SourceLazy") sourceLazyDataConKey sourceStrictDataConName = dcQual gHC_GENERICS (fsLit "SourceStrict") sourceStrictDataConKey noSourceStrictnessDataConName = dcQual gHC_GENERICS (fsLit "NoSourceStrictness") noSourceStrictnessDataConKey decidedLazyDataConName = dcQual gHC_GENERICS (fsLit "DecidedLazy") decidedLazyDataConKey decidedStrictDataConName = dcQual gHC_GENERICS (fsLit "DecidedStrict") decidedStrictDataConKey decidedUnpackDataConName = dcQual gHC_GENERICS (fsLit "DecidedUnpack") decidedUnpackDataConKey metaDataDataConName = dcQual gHC_GENERICS (fsLit "MetaData") metaDataDataConKey metaConsDataConName = dcQual gHC_GENERICS (fsLit "MetaCons") metaConsDataConKey metaSelDataConName = dcQual gHC_GENERICS (fsLit "MetaSel") metaSelDataConKey -- Base strings Strings unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name, eqStringName :: Name unpackCStringName = varQual gHC_CSTRING (fsLit "unpackCString#") unpackCStringIdKey unpackCStringFoldrName = varQual gHC_CSTRING (fsLit "unpackFoldrCString#") unpackCStringFoldrIdKey unpackCStringUtf8Name = varQual gHC_CSTRING (fsLit "unpackCStringUtf8#") unpackCStringUtf8IdKey eqStringName = varQual gHC_BASE (fsLit "eqString") eqStringIdKey -- The 'inline' function inlineIdName :: Name inlineIdName = varQual gHC_MAGIC (fsLit "inline") inlineIdKey -- Base classes (Eq, Ord, Functor) fmapName, eqClassName, eqName, ordClassName, geName, functorClassName :: Name eqClassName = clsQual gHC_CLASSES (fsLit "Eq") eqClassKey eqName = varQual gHC_CLASSES (fsLit "==") eqClassOpKey ordClassName = clsQual gHC_CLASSES (fsLit "Ord") ordClassKey geName = varQual gHC_CLASSES (fsLit ">=") geClassOpKey functorClassName = clsQual gHC_BASE (fsLit "Functor") functorClassKey fmapName = varQual gHC_BASE (fsLit "fmap") fmapClassOpKey -- Class Monad monadClassName, thenMName, bindMName, returnMName, failMName_preMFP :: Name monadClassName = clsQual gHC_BASE (fsLit "Monad") monadClassKey thenMName = varQual gHC_BASE (fsLit ">>") thenMClassOpKey bindMName = varQual gHC_BASE (fsLit ">>=") bindMClassOpKey returnMName = varQual gHC_BASE (fsLit "return") returnMClassOpKey failMName_preMFP = varQual gHC_BASE (fsLit "fail") failMClassOpKey_preMFP -- Class MonadFail monadFailClassName, failMName :: Name monadFailClassName = clsQual mONAD_FAIL (fsLit "MonadFail") monadFailClassKey failMName = varQual mONAD_FAIL (fsLit "fail") failMClassOpKey -- Class Applicative applicativeClassName, pureAName, apAName, thenAName :: Name applicativeClassName = clsQual gHC_BASE (fsLit "Applicative") applicativeClassKey apAName = varQual gHC_BASE (fsLit "<*>") apAClassOpKey pureAName = varQual gHC_BASE (fsLit "pure") pureAClassOpKey thenAName = varQual gHC_BASE (fsLit "*>") thenAClassOpKey -- Classes (Foldable, Traversable) foldableClassName, traversableClassName :: Name foldableClassName = clsQual dATA_FOLDABLE (fsLit "Foldable") foldableClassKey traversableClassName = clsQual dATA_TRAVERSABLE (fsLit "Traversable") traversableClassKey -- Classes (Semigroup, Monoid) semigroupClassName, sappendName :: Name semigroupClassName = clsQual dATA_SEMIGROUP (fsLit "Semigroup") semigroupClassKey sappendName = varQual dATA_SEMIGROUP (fsLit "<>") sappendClassOpKey monoidClassName, memptyName, mappendName, mconcatName :: Name monoidClassName = clsQual gHC_BASE (fsLit "Monoid") monoidClassKey memptyName = varQual gHC_BASE (fsLit "mempty") memptyClassOpKey mappendName = varQual gHC_BASE (fsLit "mappend") mappendClassOpKey mconcatName = varQual gHC_BASE (fsLit "mconcat") mconcatClassOpKey -- AMP additions joinMName, alternativeClassName :: Name joinMName = varQual gHC_BASE (fsLit "join") joinMIdKey alternativeClassName = clsQual mONAD (fsLit "Alternative") alternativeClassKey -- joinMIdKey, apAClassOpKey, pureAClassOpKey, thenAClassOpKey, alternativeClassKey :: Unique joinMIdKey = mkPreludeMiscIdUnique 750 apAClassOpKey = mkPreludeMiscIdUnique 751 -- <*> pureAClassOpKey = mkPreludeMiscIdUnique 752 thenAClassOpKey = mkPreludeMiscIdUnique 753 alternativeClassKey = mkPreludeMiscIdUnique 754 -- Functions for GHC extensions groupWithName :: Name groupWithName = varQual gHC_EXTS (fsLit "groupWith") groupWithIdKey -- Random PrelBase functions fromStringName, otherwiseIdName, foldrName, buildName, augmentName, mapName, appendName, assertName, breakpointName, breakpointCondName, breakpointAutoName, opaqueTyConName :: Name fromStringName = varQual dATA_STRING (fsLit "fromString") fromStringClassOpKey otherwiseIdName = varQual gHC_BASE (fsLit "otherwise") otherwiseIdKey foldrName = varQual gHC_BASE (fsLit "foldr") foldrIdKey buildName = varQual gHC_BASE (fsLit "build") buildIdKey augmentName = varQual gHC_BASE (fsLit "augment") augmentIdKey mapName = varQual gHC_BASE (fsLit "map") mapIdKey appendName = varQual gHC_BASE (fsLit "++") appendIdKey assertName = varQual gHC_BASE (fsLit "assert") assertIdKey breakpointName = varQual gHC_BASE (fsLit "breakpoint") breakpointIdKey breakpointCondName= varQual gHC_BASE (fsLit "breakpointCond") breakpointCondIdKey breakpointAutoName= varQual gHC_BASE (fsLit "breakpointAuto") breakpointAutoIdKey opaqueTyConName = tcQual gHC_BASE (fsLit "Opaque") opaqueTyConKey breakpointJumpName :: Name breakpointJumpName = mkInternalName breakpointJumpIdKey (mkOccNameFS varName (fsLit "breakpointJump")) noSrcSpan breakpointCondJumpName :: Name breakpointCondJumpName = mkInternalName breakpointCondJumpIdKey (mkOccNameFS varName (fsLit "breakpointCondJump")) noSrcSpan breakpointAutoJumpName :: Name breakpointAutoJumpName = mkInternalName breakpointAutoJumpIdKey (mkOccNameFS varName (fsLit "breakpointAutoJump")) noSrcSpan -- PrelTup fstName, sndName :: Name fstName = varQual dATA_TUPLE (fsLit "fst") fstIdKey sndName = varQual dATA_TUPLE (fsLit "snd") sndIdKey -- Module GHC.Num numClassName, fromIntegerName, minusName, negateName :: Name numClassName = clsQual gHC_NUM (fsLit "Num") numClassKey fromIntegerName = varQual gHC_NUM (fsLit "fromInteger") fromIntegerClassOpKey minusName = varQual gHC_NUM (fsLit "-") minusClassOpKey negateName = varQual gHC_NUM (fsLit "negate") negateClassOpKey integerTyConName, mkIntegerName, integerSDataConName, integerToWord64Name, integerToInt64Name, word64ToIntegerName, int64ToIntegerName, plusIntegerName, timesIntegerName, smallIntegerName, wordToIntegerName, integerToWordName, integerToIntName, minusIntegerName, negateIntegerName, eqIntegerPrimName, neqIntegerPrimName, absIntegerName, signumIntegerName, leIntegerPrimName, gtIntegerPrimName, ltIntegerPrimName, geIntegerPrimName, compareIntegerName, quotRemIntegerName, divModIntegerName, quotIntegerName, remIntegerName, divIntegerName, modIntegerName, floatFromIntegerName, doubleFromIntegerName, encodeFloatIntegerName, encodeDoubleIntegerName, decodeDoubleIntegerName, gcdIntegerName, lcmIntegerName, andIntegerName, orIntegerName, xorIntegerName, complementIntegerName, shiftLIntegerName, shiftRIntegerName, bitIntegerName :: Name integerTyConName = tcQual gHC_INTEGER_TYPE (fsLit "Integer") integerTyConKey integerSDataConName = dcQual gHC_INTEGER_TYPE (fsLit n) integerSDataConKey where n = case cIntegerLibraryType of IntegerGMP -> "S#" IntegerSimple -> panic "integerSDataConName evaluated for integer-simple" mkIntegerName = varQual gHC_INTEGER_TYPE (fsLit "mkInteger") mkIntegerIdKey integerToWord64Name = varQual gHC_INTEGER_TYPE (fsLit "integerToWord64") integerToWord64IdKey integerToInt64Name = varQual gHC_INTEGER_TYPE (fsLit "integerToInt64") integerToInt64IdKey word64ToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "word64ToInteger") word64ToIntegerIdKey int64ToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "int64ToInteger") int64ToIntegerIdKey plusIntegerName = varQual gHC_INTEGER_TYPE (fsLit "plusInteger") plusIntegerIdKey timesIntegerName = varQual gHC_INTEGER_TYPE (fsLit "timesInteger") timesIntegerIdKey smallIntegerName = varQual gHC_INTEGER_TYPE (fsLit "smallInteger") smallIntegerIdKey wordToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "wordToInteger") wordToIntegerIdKey integerToWordName = varQual gHC_INTEGER_TYPE (fsLit "integerToWord") integerToWordIdKey integerToIntName = varQual gHC_INTEGER_TYPE (fsLit "integerToInt") integerToIntIdKey minusIntegerName = varQual gHC_INTEGER_TYPE (fsLit "minusInteger") minusIntegerIdKey negateIntegerName = varQual gHC_INTEGER_TYPE (fsLit "negateInteger") negateIntegerIdKey eqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "eqInteger#") eqIntegerPrimIdKey neqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "neqInteger#") neqIntegerPrimIdKey absIntegerName = varQual gHC_INTEGER_TYPE (fsLit "absInteger") absIntegerIdKey signumIntegerName = varQual gHC_INTEGER_TYPE (fsLit "signumInteger") signumIntegerIdKey leIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "leInteger#") leIntegerPrimIdKey gtIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "gtInteger#") gtIntegerPrimIdKey ltIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "ltInteger#") ltIntegerPrimIdKey geIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "geInteger#") geIntegerPrimIdKey compareIntegerName = varQual gHC_INTEGER_TYPE (fsLit "compareInteger") compareIntegerIdKey quotRemIntegerName = varQual gHC_INTEGER_TYPE (fsLit "quotRemInteger") quotRemIntegerIdKey divModIntegerName = varQual gHC_INTEGER_TYPE (fsLit "divModInteger") divModIntegerIdKey quotIntegerName = varQual gHC_INTEGER_TYPE (fsLit "quotInteger") quotIntegerIdKey remIntegerName = varQual gHC_INTEGER_TYPE (fsLit "remInteger") remIntegerIdKey divIntegerName = varQual gHC_INTEGER_TYPE (fsLit "divInteger") divIntegerIdKey modIntegerName = varQual gHC_INTEGER_TYPE (fsLit "modInteger") modIntegerIdKey floatFromIntegerName = varQual gHC_INTEGER_TYPE (fsLit "floatFromInteger") floatFromIntegerIdKey doubleFromIntegerName = varQual gHC_INTEGER_TYPE (fsLit "doubleFromInteger") doubleFromIntegerIdKey encodeFloatIntegerName = varQual gHC_INTEGER_TYPE (fsLit "encodeFloatInteger") encodeFloatIntegerIdKey encodeDoubleIntegerName = varQual gHC_INTEGER_TYPE (fsLit "encodeDoubleInteger") encodeDoubleIntegerIdKey decodeDoubleIntegerName = varQual gHC_INTEGER_TYPE (fsLit "decodeDoubleInteger") decodeDoubleIntegerIdKey gcdIntegerName = varQual gHC_INTEGER_TYPE (fsLit "gcdInteger") gcdIntegerIdKey lcmIntegerName = varQual gHC_INTEGER_TYPE (fsLit "lcmInteger") lcmIntegerIdKey andIntegerName = varQual gHC_INTEGER_TYPE (fsLit "andInteger") andIntegerIdKey orIntegerName = varQual gHC_INTEGER_TYPE (fsLit "orInteger") orIntegerIdKey xorIntegerName = varQual gHC_INTEGER_TYPE (fsLit "xorInteger") xorIntegerIdKey complementIntegerName = varQual gHC_INTEGER_TYPE (fsLit "complementInteger") complementIntegerIdKey shiftLIntegerName = varQual gHC_INTEGER_TYPE (fsLit "shiftLInteger") shiftLIntegerIdKey shiftRIntegerName = varQual gHC_INTEGER_TYPE (fsLit "shiftRInteger") shiftRIntegerIdKey bitIntegerName = varQual gHC_INTEGER_TYPE (fsLit "bitInteger") bitIntegerIdKey -- GHC.Real types and classes rationalTyConName, ratioTyConName, ratioDataConName, realClassName, integralClassName, realFracClassName, fractionalClassName, fromRationalName, toIntegerName, toRationalName, fromIntegralName, realToFracName :: Name rationalTyConName = tcQual gHC_REAL (fsLit "Rational") rationalTyConKey ratioTyConName = tcQual gHC_REAL (fsLit "Ratio") ratioTyConKey ratioDataConName = dcQual gHC_REAL (fsLit ":%") ratioDataConKey realClassName = clsQual gHC_REAL (fsLit "Real") realClassKey integralClassName = clsQual gHC_REAL (fsLit "Integral") integralClassKey realFracClassName = clsQual gHC_REAL (fsLit "RealFrac") realFracClassKey fractionalClassName = clsQual gHC_REAL (fsLit "Fractional") fractionalClassKey fromRationalName = varQual gHC_REAL (fsLit "fromRational") fromRationalClassOpKey toIntegerName = varQual gHC_REAL (fsLit "toInteger") toIntegerClassOpKey toRationalName = varQual gHC_REAL (fsLit "toRational") toRationalClassOpKey fromIntegralName = varQual gHC_REAL (fsLit "fromIntegral")fromIntegralIdKey realToFracName = varQual gHC_REAL (fsLit "realToFrac") realToFracIdKey -- PrelFloat classes floatingClassName, realFloatClassName :: Name floatingClassName = clsQual gHC_FLOAT (fsLit "Floating") floatingClassKey realFloatClassName = clsQual gHC_FLOAT (fsLit "RealFloat") realFloatClassKey -- other GHC.Float functions rationalToFloatName, rationalToDoubleName :: Name rationalToFloatName = varQual gHC_FLOAT (fsLit "rationalToFloat") rationalToFloatIdKey rationalToDoubleName = varQual gHC_FLOAT (fsLit "rationalToDouble") rationalToDoubleIdKey -- Class Ix ixClassName :: Name ixClassName = clsQual gHC_ARR (fsLit "Ix") ixClassKey -- Typeable representation types trModuleTyConName , trModuleDataConName , trNameTyConName , trNameSDataConName , trNameDDataConName , trTyConTyConName , trTyConDataConName :: Name trModuleTyConName = tcQual gHC_TYPES (fsLit "Module") trModuleTyConKey trModuleDataConName = dcQual gHC_TYPES (fsLit "Module") trModuleDataConKey trNameTyConName = tcQual gHC_TYPES (fsLit "TrName") trNameTyConKey trNameSDataConName = dcQual gHC_TYPES (fsLit "TrNameS") trNameSDataConKey trNameDDataConName = dcQual gHC_TYPES (fsLit "TrNameD") trNameDDataConKey trTyConTyConName = tcQual gHC_TYPES (fsLit "TyCon") trTyConTyConKey trTyConDataConName = dcQual gHC_TYPES (fsLit "TyCon") trTyConDataConKey -- Class Typeable, and functions for constructing `Typeable` dictionaries typeableClassName , typeRepTyConName , mkPolyTyConAppName , mkAppTyName , typeRepIdName , typeNatTypeRepName , typeSymbolTypeRepName , trGhcPrimModuleName :: Name typeableClassName = clsQual tYPEABLE_INTERNAL (fsLit "Typeable") typeableClassKey typeRepTyConName = tcQual tYPEABLE_INTERNAL (fsLit "TypeRep") typeRepTyConKey typeRepIdName = varQual tYPEABLE_INTERNAL (fsLit "typeRep#") typeRepIdKey mkPolyTyConAppName = varQual tYPEABLE_INTERNAL (fsLit "mkPolyTyConApp") mkPolyTyConAppKey mkAppTyName = varQual tYPEABLE_INTERNAL (fsLit "mkAppTy") mkAppTyKey typeNatTypeRepName = varQual tYPEABLE_INTERNAL (fsLit "typeNatTypeRep") typeNatTypeRepKey typeSymbolTypeRepName = varQual tYPEABLE_INTERNAL (fsLit "typeSymbolTypeRep") typeSymbolTypeRepKey -- this is the Typeable 'Module' for GHC.Prim (which has no code, so we place in GHC.Types) -- See Note [Grand plan for Typeable] in TcTypeable. trGhcPrimModuleName = varQual gHC_TYPES (fsLit "tr$ModuleGHCPrim") trGhcPrimModuleKey -- Custom type errors errorMessageTypeErrorFamName , typeErrorTextDataConName , typeErrorAppendDataConName , typeErrorVAppendDataConName , typeErrorShowTypeDataConName :: Name errorMessageTypeErrorFamName = tcQual gHC_TYPELITS (fsLit "TypeError") errorMessageTypeErrorFamKey typeErrorTextDataConName = dcQual gHC_TYPELITS (fsLit "Text") typeErrorTextDataConKey typeErrorAppendDataConName = dcQual gHC_TYPELITS (fsLit ":<>:") typeErrorAppendDataConKey typeErrorVAppendDataConName = dcQual gHC_TYPELITS (fsLit ":$$:") typeErrorVAppendDataConKey typeErrorShowTypeDataConName = dcQual gHC_TYPELITS (fsLit "ShowType") typeErrorShowTypeDataConKey -- Dynamic toDynName :: Name toDynName = varQual dYNAMIC (fsLit "toDyn") toDynIdKey -- Class Data dataClassName :: Name dataClassName = clsQual gENERICS (fsLit "Data") dataClassKey -- Error module assertErrorName :: Name assertErrorName = varQual gHC_IO_Exception (fsLit "assertError") assertErrorIdKey -- Enum module (Enum, Bounded) enumClassName, enumFromName, enumFromToName, enumFromThenName, enumFromThenToName, boundedClassName :: Name enumClassName = clsQual gHC_ENUM (fsLit "Enum") enumClassKey enumFromName = varQual gHC_ENUM (fsLit "enumFrom") enumFromClassOpKey enumFromToName = varQual gHC_ENUM (fsLit "enumFromTo") enumFromToClassOpKey enumFromThenName = varQual gHC_ENUM (fsLit "enumFromThen") enumFromThenClassOpKey enumFromThenToName = varQual gHC_ENUM (fsLit "enumFromThenTo") enumFromThenToClassOpKey boundedClassName = clsQual gHC_ENUM (fsLit "Bounded") boundedClassKey -- List functions concatName, filterName, zipName :: Name concatName = varQual gHC_LIST (fsLit "concat") concatIdKey filterName = varQual gHC_LIST (fsLit "filter") filterIdKey zipName = varQual gHC_LIST (fsLit "zip") zipIdKey -- Overloaded lists isListClassName, fromListName, fromListNName, toListName :: Name isListClassName = clsQual gHC_EXTS (fsLit "IsList") isListClassKey fromListName = varQual gHC_EXTS (fsLit "fromList") fromListClassOpKey fromListNName = varQual gHC_EXTS (fsLit "fromListN") fromListNClassOpKey toListName = varQual gHC_EXTS (fsLit "toList") toListClassOpKey -- Class Show showClassName :: Name showClassName = clsQual gHC_SHOW (fsLit "Show") showClassKey -- Class Read readClassName :: Name readClassName = clsQual gHC_READ (fsLit "Read") readClassKey -- Classes Generic and Generic1, Datatype, Constructor and Selector genClassName, gen1ClassName, datatypeClassName, constructorClassName, selectorClassName :: Name genClassName = clsQual gHC_GENERICS (fsLit "Generic") genClassKey gen1ClassName = clsQual gHC_GENERICS (fsLit "Generic1") gen1ClassKey datatypeClassName = clsQual gHC_GENERICS (fsLit "Datatype") datatypeClassKey constructorClassName = clsQual gHC_GENERICS (fsLit "Constructor") constructorClassKey selectorClassName = clsQual gHC_GENERICS (fsLit "Selector") selectorClassKey genericClassNames :: [Name] genericClassNames = [genClassName, gen1ClassName] -- GHCi things ghciIoClassName, ghciStepIoMName :: Name ghciIoClassName = clsQual gHC_GHCI (fsLit "GHCiSandboxIO") ghciIoClassKey ghciStepIoMName = varQual gHC_GHCI (fsLit "ghciStepIO") ghciStepIoMClassOpKey -- IO things ioTyConName, ioDataConName, thenIOName, bindIOName, returnIOName, failIOName :: Name ioTyConName = tcQual gHC_TYPES (fsLit "IO") ioTyConKey ioDataConName = dcQual gHC_TYPES (fsLit "IO") ioDataConKey thenIOName = varQual gHC_BASE (fsLit "thenIO") thenIOIdKey bindIOName = varQual gHC_BASE (fsLit "bindIO") bindIOIdKey returnIOName = varQual gHC_BASE (fsLit "returnIO") returnIOIdKey failIOName = varQual gHC_IO (fsLit "failIO") failIOIdKey -- IO things printName :: Name printName = varQual sYSTEM_IO (fsLit "print") printIdKey -- Int, Word, and Addr things int8TyConName, int16TyConName, int32TyConName, int64TyConName :: Name int8TyConName = tcQual gHC_INT (fsLit "Int8") int8TyConKey int16TyConName = tcQual gHC_INT (fsLit "Int16") int16TyConKey int32TyConName = tcQual gHC_INT (fsLit "Int32") int32TyConKey int64TyConName = tcQual gHC_INT (fsLit "Int64") int64TyConKey -- Word module word16TyConName, word32TyConName, word64TyConName :: Name word16TyConName = tcQual gHC_WORD (fsLit "Word16") word16TyConKey word32TyConName = tcQual gHC_WORD (fsLit "Word32") word32TyConKey word64TyConName = tcQual gHC_WORD (fsLit "Word64") word64TyConKey -- PrelPtr module ptrTyConName, funPtrTyConName :: Name ptrTyConName = tcQual gHC_PTR (fsLit "Ptr") ptrTyConKey funPtrTyConName = tcQual gHC_PTR (fsLit "FunPtr") funPtrTyConKey -- Foreign objects and weak pointers stablePtrTyConName, newStablePtrName :: Name stablePtrTyConName = tcQual gHC_STABLE (fsLit "StablePtr") stablePtrTyConKey newStablePtrName = varQual gHC_STABLE (fsLit "newStablePtr") newStablePtrIdKey -- Recursive-do notation monadFixClassName, mfixName :: Name monadFixClassName = clsQual mONAD_FIX (fsLit "MonadFix") monadFixClassKey mfixName = varQual mONAD_FIX (fsLit "mfix") mfixIdKey -- Arrow notation arrAName, composeAName, firstAName, appAName, choiceAName, loopAName :: Name arrAName = varQual aRROW (fsLit "arr") arrAIdKey composeAName = varQual gHC_DESUGAR (fsLit ">>>") composeAIdKey firstAName = varQual aRROW (fsLit "first") firstAIdKey appAName = varQual aRROW (fsLit "app") appAIdKey choiceAName = varQual aRROW (fsLit "|||") choiceAIdKey loopAName = varQual aRROW (fsLit "loop") loopAIdKey -- Monad comprehensions guardMName, liftMName, mzipName :: Name guardMName = varQual mONAD (fsLit "guard") guardMIdKey liftMName = varQual mONAD (fsLit "liftM") liftMIdKey mzipName = varQual mONAD_ZIP (fsLit "mzip") mzipIdKey -- Annotation type checking toAnnotationWrapperName :: Name toAnnotationWrapperName = varQual gHC_DESUGAR (fsLit "toAnnotationWrapper") toAnnotationWrapperIdKey -- Other classes, needed for type defaulting monadPlusClassName, randomClassName, randomGenClassName, isStringClassName :: Name monadPlusClassName = clsQual mONAD (fsLit "MonadPlus") monadPlusClassKey randomClassName = clsQual rANDOM (fsLit "Random") randomClassKey randomGenClassName = clsQual rANDOM (fsLit "RandomGen") randomGenClassKey isStringClassName = clsQual dATA_STRING (fsLit "IsString") isStringClassKey -- Type-level naturals knownNatClassName :: Name knownNatClassName = clsQual gHC_TYPELITS (fsLit "KnownNat") knownNatClassNameKey knownSymbolClassName :: Name knownSymbolClassName = clsQual gHC_TYPELITS (fsLit "KnownSymbol") knownSymbolClassNameKey -- Overloaded labels isLabelClassName :: Name isLabelClassName = clsQual gHC_OVER_LABELS (fsLit "IsLabel") isLabelClassNameKey -- Implicit Parameters ipClassName :: Name ipClassName = clsQual gHC_CLASSES (fsLit "IP") ipClassKey -- Source Locations callStackTyConName, emptyCallStackName, pushCallStackName, srcLocDataConName :: Name callStackTyConName = tcQual gHC_STACK_TYPES (fsLit "CallStack") callStackTyConKey emptyCallStackName = varQual gHC_STACK_TYPES (fsLit "emptyCallStack") emptyCallStackKey pushCallStackName = varQual gHC_STACK_TYPES (fsLit "pushCallStack") pushCallStackKey srcLocDataConName = dcQual gHC_STACK_TYPES (fsLit "SrcLoc") srcLocDataConKey -- plugins pLUGINS :: Module pLUGINS = mkThisGhcModule (fsLit "Plugins") pluginTyConName :: Name pluginTyConName = tcQual pLUGINS (fsLit "Plugin") pluginTyConKey frontendPluginTyConName :: Name frontendPluginTyConName = tcQual pLUGINS (fsLit "FrontendPlugin") frontendPluginTyConKey -- Static pointers staticPtrInfoTyConName :: Name staticPtrInfoTyConName = tcQual gHC_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoTyConKey staticPtrInfoDataConName :: Name staticPtrInfoDataConName = dcQual gHC_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoDataConKey staticPtrTyConName :: Name staticPtrTyConName = tcQual gHC_STATICPTR (fsLit "StaticPtr") staticPtrTyConKey staticPtrDataConName :: Name staticPtrDataConName = dcQual gHC_STATICPTR (fsLit "StaticPtr") staticPtrDataConKey fromStaticPtrName :: Name fromStaticPtrName = varQual gHC_STATICPTR (fsLit "fromStaticPtr") fromStaticPtrClassOpKey fingerprintDataConName :: Name fingerprintDataConName = dcQual gHC_FINGERPRINT_TYPE (fsLit "Fingerprint") fingerprintDataConKey -- homogeneous equality. See Note [The equality types story] in TysPrim eqTyConName :: Name eqTyConName = tcQual dATA_TYPE_EQUALITY (fsLit "~") eqTyConKey {- ************************************************************************ * * \subsection{Local helpers} * * ************************************************************************ All these are original names; hence mkOrig -} varQual, tcQual, clsQual, dcQual :: Module -> FastString -> Unique -> Name varQual = mk_known_key_name varName tcQual = mk_known_key_name tcName clsQual = mk_known_key_name clsName dcQual = mk_known_key_name dataName mk_known_key_name :: NameSpace -> Module -> FastString -> Unique -> Name mk_known_key_name space modu str unique = mkExternalName unique modu (mkOccNameFS space str) noSrcSpan {- ************************************************************************ * * \subsubsection[Uniques-prelude-Classes]{@Uniques@ for wired-in @Classes@} * * ************************************************************************ --MetaHaskell extension hand allocate keys here -} boundedClassKey, enumClassKey, eqClassKey, floatingClassKey, fractionalClassKey, integralClassKey, monadClassKey, dataClassKey, functorClassKey, numClassKey, ordClassKey, readClassKey, realClassKey, realFloatClassKey, realFracClassKey, showClassKey, ixClassKey :: Unique boundedClassKey = mkPreludeClassUnique 1 enumClassKey = mkPreludeClassUnique 2 eqClassKey = mkPreludeClassUnique 3 floatingClassKey = mkPreludeClassUnique 5 fractionalClassKey = mkPreludeClassUnique 6 integralClassKey = mkPreludeClassUnique 7 monadClassKey = mkPreludeClassUnique 8 dataClassKey = mkPreludeClassUnique 9 functorClassKey = mkPreludeClassUnique 10 numClassKey = mkPreludeClassUnique 11 ordClassKey = mkPreludeClassUnique 12 readClassKey = mkPreludeClassUnique 13 realClassKey = mkPreludeClassUnique 14 realFloatClassKey = mkPreludeClassUnique 15 realFracClassKey = mkPreludeClassUnique 16 showClassKey = mkPreludeClassUnique 17 ixClassKey = mkPreludeClassUnique 18 typeableClassKey, typeable1ClassKey, typeable2ClassKey, typeable3ClassKey, typeable4ClassKey, typeable5ClassKey, typeable6ClassKey, typeable7ClassKey :: Unique typeableClassKey = mkPreludeClassUnique 20 typeable1ClassKey = mkPreludeClassUnique 21 typeable2ClassKey = mkPreludeClassUnique 22 typeable3ClassKey = mkPreludeClassUnique 23 typeable4ClassKey = mkPreludeClassUnique 24 typeable5ClassKey = mkPreludeClassUnique 25 typeable6ClassKey = mkPreludeClassUnique 26 typeable7ClassKey = mkPreludeClassUnique 27 monadFixClassKey :: Unique monadFixClassKey = mkPreludeClassUnique 28 monadFailClassKey :: Unique monadFailClassKey = mkPreludeClassUnique 29 monadPlusClassKey, randomClassKey, randomGenClassKey :: Unique monadPlusClassKey = mkPreludeClassUnique 30 randomClassKey = mkPreludeClassUnique 31 randomGenClassKey = mkPreludeClassUnique 32 isStringClassKey :: Unique isStringClassKey = mkPreludeClassUnique 33 applicativeClassKey, foldableClassKey, traversableClassKey :: Unique applicativeClassKey = mkPreludeClassUnique 34 foldableClassKey = mkPreludeClassUnique 35 traversableClassKey = mkPreludeClassUnique 36 genClassKey, gen1ClassKey, datatypeClassKey, constructorClassKey, selectorClassKey :: Unique genClassKey = mkPreludeClassUnique 37 gen1ClassKey = mkPreludeClassUnique 38 datatypeClassKey = mkPreludeClassUnique 39 constructorClassKey = mkPreludeClassUnique 40 selectorClassKey = mkPreludeClassUnique 41 -- KnownNat: see Note [KnowNat & KnownSymbol and EvLit] in TcEvidence knownNatClassNameKey :: Unique knownNatClassNameKey = mkPreludeClassUnique 42 -- KnownSymbol: see Note [KnownNat & KnownSymbol and EvLit] in TcEvidence knownSymbolClassNameKey :: Unique knownSymbolClassNameKey = mkPreludeClassUnique 43 ghciIoClassKey :: Unique ghciIoClassKey = mkPreludeClassUnique 44 isLabelClassNameKey :: Unique isLabelClassNameKey = mkPreludeClassUnique 45 semigroupClassKey, monoidClassKey :: Unique semigroupClassKey = mkPreludeClassUnique 46 monoidClassKey = mkPreludeClassUnique 47 -- Implicit Parameters ipClassKey :: Unique ipClassKey = mkPreludeClassUnique 48 ---------------- Template Haskell ------------------- -- THNames.hs: USES ClassUniques 200-299 ----------------------------------------------------- {- ************************************************************************ * * \subsubsection[Uniques-prelude-TyCons]{@Uniques@ for wired-in @TyCons@} * * ************************************************************************ -} addrPrimTyConKey, arrayPrimTyConKey, arrayArrayPrimTyConKey, boolTyConKey, byteArrayPrimTyConKey, charPrimTyConKey, charTyConKey, doublePrimTyConKey, doubleTyConKey, floatPrimTyConKey, floatTyConKey, funTyConKey, intPrimTyConKey, intTyConKey, int8TyConKey, int16TyConKey, int32PrimTyConKey, int32TyConKey, int64PrimTyConKey, int64TyConKey, integerTyConKey, listTyConKey, foreignObjPrimTyConKey, maybeTyConKey, weakPrimTyConKey, mutableArrayPrimTyConKey, mutableArrayArrayPrimTyConKey, mutableByteArrayPrimTyConKey, orderingTyConKey, mVarPrimTyConKey, ratioTyConKey, rationalTyConKey, realWorldTyConKey, stablePtrPrimTyConKey, stablePtrTyConKey, eqTyConKey, heqTyConKey, smallArrayPrimTyConKey, smallMutableArrayPrimTyConKey :: Unique addrPrimTyConKey = mkPreludeTyConUnique 1 arrayPrimTyConKey = mkPreludeTyConUnique 3 boolTyConKey = mkPreludeTyConUnique 4 byteArrayPrimTyConKey = mkPreludeTyConUnique 5 charPrimTyConKey = mkPreludeTyConUnique 7 charTyConKey = mkPreludeTyConUnique 8 doublePrimTyConKey = mkPreludeTyConUnique 9 doubleTyConKey = mkPreludeTyConUnique 10 floatPrimTyConKey = mkPreludeTyConUnique 11 floatTyConKey = mkPreludeTyConUnique 12 funTyConKey = mkPreludeTyConUnique 13 intPrimTyConKey = mkPreludeTyConUnique 14 intTyConKey = mkPreludeTyConUnique 15 int8TyConKey = mkPreludeTyConUnique 16 int16TyConKey = mkPreludeTyConUnique 17 int32PrimTyConKey = mkPreludeTyConUnique 18 int32TyConKey = mkPreludeTyConUnique 19 int64PrimTyConKey = mkPreludeTyConUnique 20 int64TyConKey = mkPreludeTyConUnique 21 integerTyConKey = mkPreludeTyConUnique 22 listTyConKey = mkPreludeTyConUnique 24 foreignObjPrimTyConKey = mkPreludeTyConUnique 25 maybeTyConKey = mkPreludeTyConUnique 26 weakPrimTyConKey = mkPreludeTyConUnique 27 mutableArrayPrimTyConKey = mkPreludeTyConUnique 28 mutableByteArrayPrimTyConKey = mkPreludeTyConUnique 29 orderingTyConKey = mkPreludeTyConUnique 30 mVarPrimTyConKey = mkPreludeTyConUnique 31 ratioTyConKey = mkPreludeTyConUnique 32 rationalTyConKey = mkPreludeTyConUnique 33 realWorldTyConKey = mkPreludeTyConUnique 34 stablePtrPrimTyConKey = mkPreludeTyConUnique 35 stablePtrTyConKey = mkPreludeTyConUnique 36 eqTyConKey = mkPreludeTyConUnique 38 heqTyConKey = mkPreludeTyConUnique 39 arrayArrayPrimTyConKey = mkPreludeTyConUnique 40 mutableArrayArrayPrimTyConKey = mkPreludeTyConUnique 41 statePrimTyConKey, stableNamePrimTyConKey, stableNameTyConKey, mutVarPrimTyConKey, ioTyConKey, wordPrimTyConKey, wordTyConKey, word8TyConKey, word16TyConKey, word32PrimTyConKey, word32TyConKey, word64PrimTyConKey, word64TyConKey, liftedConKey, unliftedConKey, anyBoxConKey, kindConKey, boxityConKey, typeConKey, threadIdPrimTyConKey, bcoPrimTyConKey, ptrTyConKey, funPtrTyConKey, tVarPrimTyConKey, eqPrimTyConKey, eqReprPrimTyConKey, eqPhantPrimTyConKey, voidPrimTyConKey :: Unique statePrimTyConKey = mkPreludeTyConUnique 50 stableNamePrimTyConKey = mkPreludeTyConUnique 51 stableNameTyConKey = mkPreludeTyConUnique 52 eqPrimTyConKey = mkPreludeTyConUnique 53 eqReprPrimTyConKey = mkPreludeTyConUnique 54 eqPhantPrimTyConKey = mkPreludeTyConUnique 55 mutVarPrimTyConKey = mkPreludeTyConUnique 56 ioTyConKey = mkPreludeTyConUnique 57 voidPrimTyConKey = mkPreludeTyConUnique 58 wordPrimTyConKey = mkPreludeTyConUnique 59 wordTyConKey = mkPreludeTyConUnique 60 word8TyConKey = mkPreludeTyConUnique 61 word16TyConKey = mkPreludeTyConUnique 62 word32PrimTyConKey = mkPreludeTyConUnique 63 word32TyConKey = mkPreludeTyConUnique 64 word64PrimTyConKey = mkPreludeTyConUnique 65 word64TyConKey = mkPreludeTyConUnique 66 liftedConKey = mkPreludeTyConUnique 67 unliftedConKey = mkPreludeTyConUnique 68 anyBoxConKey = mkPreludeTyConUnique 69 kindConKey = mkPreludeTyConUnique 70 boxityConKey = mkPreludeTyConUnique 71 typeConKey = mkPreludeTyConUnique 72 threadIdPrimTyConKey = mkPreludeTyConUnique 73 bcoPrimTyConKey = mkPreludeTyConUnique 74 ptrTyConKey = mkPreludeTyConUnique 75 funPtrTyConKey = mkPreludeTyConUnique 76 tVarPrimTyConKey = mkPreludeTyConUnique 77 -- Parallel array type constructor parrTyConKey :: Unique parrTyConKey = mkPreludeTyConUnique 82 -- dotnet interop objectTyConKey :: Unique objectTyConKey = mkPreludeTyConUnique 83 eitherTyConKey :: Unique eitherTyConKey = mkPreludeTyConUnique 84 -- Kind constructors liftedTypeKindTyConKey, tYPETyConKey, unliftedTypeKindTyConKey, constraintKindTyConKey, starKindTyConKey, unicodeStarKindTyConKey, runtimeRepTyConKey, vecCountTyConKey, vecElemTyConKey :: Unique liftedTypeKindTyConKey = mkPreludeTyConUnique 87 tYPETyConKey = mkPreludeTyConUnique 88 unliftedTypeKindTyConKey = mkPreludeTyConUnique 89 constraintKindTyConKey = mkPreludeTyConUnique 92 starKindTyConKey = mkPreludeTyConUnique 93 unicodeStarKindTyConKey = mkPreludeTyConUnique 94 runtimeRepTyConKey = mkPreludeTyConUnique 95 vecCountTyConKey = mkPreludeTyConUnique 96 vecElemTyConKey = mkPreludeTyConUnique 97 pluginTyConKey, frontendPluginTyConKey :: Unique pluginTyConKey = mkPreludeTyConUnique 102 frontendPluginTyConKey = mkPreludeTyConUnique 103 unknownTyConKey, unknown1TyConKey, unknown2TyConKey, unknown3TyConKey, opaqueTyConKey :: Unique unknownTyConKey = mkPreludeTyConUnique 129 unknown1TyConKey = mkPreludeTyConUnique 130 unknown2TyConKey = mkPreludeTyConUnique 131 unknown3TyConKey = mkPreludeTyConUnique 132 opaqueTyConKey = mkPreludeTyConUnique 133 -- Generics (Unique keys) v1TyConKey, u1TyConKey, par1TyConKey, rec1TyConKey, k1TyConKey, m1TyConKey, sumTyConKey, prodTyConKey, compTyConKey, rTyConKey, dTyConKey, cTyConKey, sTyConKey, rec0TyConKey, d1TyConKey, c1TyConKey, s1TyConKey, noSelTyConKey, repTyConKey, rep1TyConKey, uRecTyConKey, uAddrTyConKey, uCharTyConKey, uDoubleTyConKey, uFloatTyConKey, uIntTyConKey, uWordTyConKey :: Unique v1TyConKey = mkPreludeTyConUnique 135 u1TyConKey = mkPreludeTyConUnique 136 par1TyConKey = mkPreludeTyConUnique 137 rec1TyConKey = mkPreludeTyConUnique 138 k1TyConKey = mkPreludeTyConUnique 139 m1TyConKey = mkPreludeTyConUnique 140 sumTyConKey = mkPreludeTyConUnique 141 prodTyConKey = mkPreludeTyConUnique 142 compTyConKey = mkPreludeTyConUnique 143 rTyConKey = mkPreludeTyConUnique 144 dTyConKey = mkPreludeTyConUnique 146 cTyConKey = mkPreludeTyConUnique 147 sTyConKey = mkPreludeTyConUnique 148 rec0TyConKey = mkPreludeTyConUnique 149 d1TyConKey = mkPreludeTyConUnique 151 c1TyConKey = mkPreludeTyConUnique 152 s1TyConKey = mkPreludeTyConUnique 153 noSelTyConKey = mkPreludeTyConUnique 154 repTyConKey = mkPreludeTyConUnique 155 rep1TyConKey = mkPreludeTyConUnique 156 uRecTyConKey = mkPreludeTyConUnique 157 uAddrTyConKey = mkPreludeTyConUnique 158 uCharTyConKey = mkPreludeTyConUnique 159 uDoubleTyConKey = mkPreludeTyConUnique 160 uFloatTyConKey = mkPreludeTyConUnique 161 uIntTyConKey = mkPreludeTyConUnique 162 uWordTyConKey = mkPreludeTyConUnique 163 -- Type-level naturals typeNatKindConNameKey, typeSymbolKindConNameKey, typeNatAddTyFamNameKey, typeNatMulTyFamNameKey, typeNatExpTyFamNameKey, typeNatLeqTyFamNameKey, typeNatSubTyFamNameKey , typeSymbolCmpTyFamNameKey, typeNatCmpTyFamNameKey :: Unique typeNatKindConNameKey = mkPreludeTyConUnique 164 typeSymbolKindConNameKey = mkPreludeTyConUnique 165 typeNatAddTyFamNameKey = mkPreludeTyConUnique 166 typeNatMulTyFamNameKey = mkPreludeTyConUnique 167 typeNatExpTyFamNameKey = mkPreludeTyConUnique 168 typeNatLeqTyFamNameKey = mkPreludeTyConUnique 169 typeNatSubTyFamNameKey = mkPreludeTyConUnique 170 typeSymbolCmpTyFamNameKey = mkPreludeTyConUnique 171 typeNatCmpTyFamNameKey = mkPreludeTyConUnique 172 -- Custom user type-errors errorMessageTypeErrorFamKey :: Unique errorMessageTypeErrorFamKey = mkPreludeTyConUnique 173 ntTyConKey:: Unique ntTyConKey = mkPreludeTyConUnique 174 coercibleTyConKey :: Unique coercibleTyConKey = mkPreludeTyConUnique 175 proxyPrimTyConKey :: Unique proxyPrimTyConKey = mkPreludeTyConUnique 176 specTyConKey :: Unique specTyConKey = mkPreludeTyConUnique 177 anyTyConKey :: Unique anyTyConKey = mkPreludeTyConUnique 178 smallArrayPrimTyConKey = mkPreludeTyConUnique 179 smallMutableArrayPrimTyConKey = mkPreludeTyConUnique 180 staticPtrTyConKey :: Unique staticPtrTyConKey = mkPreludeTyConUnique 181 staticPtrInfoTyConKey :: Unique staticPtrInfoTyConKey = mkPreludeTyConUnique 182 callStackTyConKey :: Unique callStackTyConKey = mkPreludeTyConUnique 183 -- Typeables typeRepTyConKey :: Unique typeRepTyConKey = mkPreludeTyConUnique 184 ---------------- Template Haskell ------------------- -- THNames.hs: USES TyConUniques 200-299 ----------------------------------------------------- ----------------------- SIMD ------------------------ -- USES TyConUniques 300-399 ----------------------------------------------------- #include "primop-vector-uniques.hs-incl" {- ************************************************************************ * * \subsubsection[Uniques-prelude-DataCons]{@Uniques@ for wired-in @DataCons@} * * ************************************************************************ -} charDataConKey, consDataConKey, doubleDataConKey, falseDataConKey, floatDataConKey, intDataConKey, integerSDataConKey, nilDataConKey, ratioDataConKey, stableNameDataConKey, trueDataConKey, wordDataConKey, word8DataConKey, ioDataConKey, integerDataConKey, heqDataConKey, coercibleDataConKey, nothingDataConKey, justDataConKey :: Unique charDataConKey = mkPreludeDataConUnique 1 consDataConKey = mkPreludeDataConUnique 2 doubleDataConKey = mkPreludeDataConUnique 3 falseDataConKey = mkPreludeDataConUnique 4 floatDataConKey = mkPreludeDataConUnique 5 intDataConKey = mkPreludeDataConUnique 6 integerSDataConKey = mkPreludeDataConUnique 7 nothingDataConKey = mkPreludeDataConUnique 8 justDataConKey = mkPreludeDataConUnique 9 nilDataConKey = mkPreludeDataConUnique 11 ratioDataConKey = mkPreludeDataConUnique 12 word8DataConKey = mkPreludeDataConUnique 13 stableNameDataConKey = mkPreludeDataConUnique 14 trueDataConKey = mkPreludeDataConUnique 15 wordDataConKey = mkPreludeDataConUnique 16 ioDataConKey = mkPreludeDataConUnique 17 integerDataConKey = mkPreludeDataConUnique 18 heqDataConKey = mkPreludeDataConUnique 19 -- Generic data constructors crossDataConKey, inlDataConKey, inrDataConKey, genUnitDataConKey :: Unique crossDataConKey = mkPreludeDataConUnique 20 inlDataConKey = mkPreludeDataConUnique 21 inrDataConKey = mkPreludeDataConUnique 22 genUnitDataConKey = mkPreludeDataConUnique 23 -- Data constructor for parallel arrays parrDataConKey :: Unique parrDataConKey = mkPreludeDataConUnique 24 leftDataConKey, rightDataConKey :: Unique leftDataConKey = mkPreludeDataConUnique 25 rightDataConKey = mkPreludeDataConUnique 26 ltDataConKey, eqDataConKey, gtDataConKey :: Unique ltDataConKey = mkPreludeDataConUnique 27 eqDataConKey = mkPreludeDataConUnique 28 gtDataConKey = mkPreludeDataConUnique 29 coercibleDataConKey = mkPreludeDataConUnique 32 staticPtrDataConKey :: Unique staticPtrDataConKey = mkPreludeDataConUnique 33 staticPtrInfoDataConKey :: Unique staticPtrInfoDataConKey = mkPreludeDataConUnique 34 fingerprintDataConKey :: Unique fingerprintDataConKey = mkPreludeDataConUnique 35 srcLocDataConKey :: Unique srcLocDataConKey = mkPreludeDataConUnique 37 trTyConTyConKey, trTyConDataConKey, trModuleTyConKey, trModuleDataConKey, trNameTyConKey, trNameSDataConKey, trNameDDataConKey, trGhcPrimModuleKey :: Unique trTyConTyConKey = mkPreludeDataConUnique 41 trTyConDataConKey = mkPreludeDataConUnique 42 trModuleTyConKey = mkPreludeDataConUnique 43 trModuleDataConKey = mkPreludeDataConUnique 44 trNameTyConKey = mkPreludeDataConUnique 45 trNameSDataConKey = mkPreludeDataConUnique 46 trNameDDataConKey = mkPreludeDataConUnique 47 trGhcPrimModuleKey = mkPreludeDataConUnique 48 typeErrorTextDataConKey, typeErrorAppendDataConKey, typeErrorVAppendDataConKey, typeErrorShowTypeDataConKey :: Unique typeErrorTextDataConKey = mkPreludeDataConUnique 50 typeErrorAppendDataConKey = mkPreludeDataConUnique 51 typeErrorVAppendDataConKey = mkPreludeDataConUnique 52 typeErrorShowTypeDataConKey = mkPreludeDataConUnique 53 prefixIDataConKey, infixIDataConKey, leftAssociativeDataConKey, rightAssociativeDataConKey, notAssociativeDataConKey, sourceUnpackDataConKey, sourceNoUnpackDataConKey, noSourceUnpackednessDataConKey, sourceLazyDataConKey, sourceStrictDataConKey, noSourceStrictnessDataConKey, decidedLazyDataConKey, decidedStrictDataConKey, decidedUnpackDataConKey, metaDataDataConKey, metaConsDataConKey, metaSelDataConKey :: Unique prefixIDataConKey = mkPreludeDataConUnique 54 infixIDataConKey = mkPreludeDataConUnique 55 leftAssociativeDataConKey = mkPreludeDataConUnique 56 rightAssociativeDataConKey = mkPreludeDataConUnique 57 notAssociativeDataConKey = mkPreludeDataConUnique 58 sourceUnpackDataConKey = mkPreludeDataConUnique 59 sourceNoUnpackDataConKey = mkPreludeDataConUnique 60 noSourceUnpackednessDataConKey = mkPreludeDataConUnique 61 sourceLazyDataConKey = mkPreludeDataConUnique 62 sourceStrictDataConKey = mkPreludeDataConUnique 63 noSourceStrictnessDataConKey = mkPreludeDataConUnique 64 decidedLazyDataConKey = mkPreludeDataConUnique 65 decidedStrictDataConKey = mkPreludeDataConUnique 66 decidedUnpackDataConKey = mkPreludeDataConUnique 67 metaDataDataConKey = mkPreludeDataConUnique 68 metaConsDataConKey = mkPreludeDataConUnique 69 metaSelDataConKey = mkPreludeDataConUnique 70 vecRepDataConKey :: Unique vecRepDataConKey = mkPreludeDataConUnique 71 -- See Note [Wiring in RuntimeRep] in TysWiredIn runtimeRepSimpleDataConKeys :: [Unique] ptrRepLiftedDataConKey, ptrRepUnliftedDataConKey :: Unique runtimeRepSimpleDataConKeys@( ptrRepLiftedDataConKey : ptrRepUnliftedDataConKey : _) = map mkPreludeDataConUnique [72..82] -- See Note [Wiring in RuntimeRep] in TysWiredIn -- VecCount vecCountDataConKeys :: [Unique] vecCountDataConKeys = map mkPreludeDataConUnique [83..88] -- See Note [Wiring in RuntimeRep] in TysWiredIn -- VecElem vecElemDataConKeys :: [Unique] vecElemDataConKeys = map mkPreludeDataConUnique [89..98] ---------------- Template Haskell ------------------- -- THNames.hs: USES DataUniques 100-150 ----------------------------------------------------- {- ************************************************************************ * * \subsubsection[Uniques-prelude-Ids]{@Uniques@ for wired-in @Ids@ (except @DataCons@)} * * ************************************************************************ -} wildCardKey, absentErrorIdKey, augmentIdKey, appendIdKey, buildIdKey, errorIdKey, foldrIdKey, recSelErrorIdKey, seqIdKey, irrefutPatErrorIdKey, eqStringIdKey, noMethodBindingErrorIdKey, nonExhaustiveGuardsErrorIdKey, runtimeErrorIdKey, patErrorIdKey, voidPrimIdKey, realWorldPrimIdKey, recConErrorIdKey, unpackCStringUtf8IdKey, unpackCStringAppendIdKey, unpackCStringFoldrIdKey, unpackCStringIdKey, typeErrorIdKey :: Unique wildCardKey = mkPreludeMiscIdUnique 0 -- See Note [WildCard binders] absentErrorIdKey = mkPreludeMiscIdUnique 1 augmentIdKey = mkPreludeMiscIdUnique 2 appendIdKey = mkPreludeMiscIdUnique 3 buildIdKey = mkPreludeMiscIdUnique 4 errorIdKey = mkPreludeMiscIdUnique 5 foldrIdKey = mkPreludeMiscIdUnique 6 recSelErrorIdKey = mkPreludeMiscIdUnique 7 seqIdKey = mkPreludeMiscIdUnique 8 irrefutPatErrorIdKey = mkPreludeMiscIdUnique 9 eqStringIdKey = mkPreludeMiscIdUnique 10 noMethodBindingErrorIdKey = mkPreludeMiscIdUnique 11 nonExhaustiveGuardsErrorIdKey = mkPreludeMiscIdUnique 12 runtimeErrorIdKey = mkPreludeMiscIdUnique 13 patErrorIdKey = mkPreludeMiscIdUnique 14 realWorldPrimIdKey = mkPreludeMiscIdUnique 15 recConErrorIdKey = mkPreludeMiscIdUnique 16 unpackCStringUtf8IdKey = mkPreludeMiscIdUnique 17 unpackCStringAppendIdKey = mkPreludeMiscIdUnique 18 unpackCStringFoldrIdKey = mkPreludeMiscIdUnique 19 unpackCStringIdKey = mkPreludeMiscIdUnique 20 voidPrimIdKey = mkPreludeMiscIdUnique 21 typeErrorIdKey = mkPreludeMiscIdUnique 22 unsafeCoerceIdKey, concatIdKey, filterIdKey, zipIdKey, bindIOIdKey, returnIOIdKey, newStablePtrIdKey, printIdKey, failIOIdKey, nullAddrIdKey, voidArgIdKey, fstIdKey, sndIdKey, otherwiseIdKey, assertIdKey :: Unique unsafeCoerceIdKey = mkPreludeMiscIdUnique 30 concatIdKey = mkPreludeMiscIdUnique 31 filterIdKey = mkPreludeMiscIdUnique 32 zipIdKey = mkPreludeMiscIdUnique 33 bindIOIdKey = mkPreludeMiscIdUnique 34 returnIOIdKey = mkPreludeMiscIdUnique 35 newStablePtrIdKey = mkPreludeMiscIdUnique 36 printIdKey = mkPreludeMiscIdUnique 37 failIOIdKey = mkPreludeMiscIdUnique 38 nullAddrIdKey = mkPreludeMiscIdUnique 39 voidArgIdKey = mkPreludeMiscIdUnique 40 fstIdKey = mkPreludeMiscIdUnique 41 sndIdKey = mkPreludeMiscIdUnique 42 otherwiseIdKey = mkPreludeMiscIdUnique 43 assertIdKey = mkPreludeMiscIdUnique 44 mkIntegerIdKey, smallIntegerIdKey, wordToIntegerIdKey, integerToWordIdKey, integerToIntIdKey, integerToWord64IdKey, integerToInt64IdKey, word64ToIntegerIdKey, int64ToIntegerIdKey, plusIntegerIdKey, timesIntegerIdKey, minusIntegerIdKey, negateIntegerIdKey, eqIntegerPrimIdKey, neqIntegerPrimIdKey, absIntegerIdKey, signumIntegerIdKey, leIntegerPrimIdKey, gtIntegerPrimIdKey, ltIntegerPrimIdKey, geIntegerPrimIdKey, compareIntegerIdKey, quotRemIntegerIdKey, divModIntegerIdKey, quotIntegerIdKey, remIntegerIdKey, divIntegerIdKey, modIntegerIdKey, floatFromIntegerIdKey, doubleFromIntegerIdKey, encodeFloatIntegerIdKey, encodeDoubleIntegerIdKey, decodeDoubleIntegerIdKey, gcdIntegerIdKey, lcmIntegerIdKey, andIntegerIdKey, orIntegerIdKey, xorIntegerIdKey, complementIntegerIdKey, shiftLIntegerIdKey, shiftRIntegerIdKey :: Unique mkIntegerIdKey = mkPreludeMiscIdUnique 60 smallIntegerIdKey = mkPreludeMiscIdUnique 61 integerToWordIdKey = mkPreludeMiscIdUnique 62 integerToIntIdKey = mkPreludeMiscIdUnique 63 integerToWord64IdKey = mkPreludeMiscIdUnique 64 integerToInt64IdKey = mkPreludeMiscIdUnique 65 plusIntegerIdKey = mkPreludeMiscIdUnique 66 timesIntegerIdKey = mkPreludeMiscIdUnique 67 minusIntegerIdKey = mkPreludeMiscIdUnique 68 negateIntegerIdKey = mkPreludeMiscIdUnique 69 eqIntegerPrimIdKey = mkPreludeMiscIdUnique 70 neqIntegerPrimIdKey = mkPreludeMiscIdUnique 71 absIntegerIdKey = mkPreludeMiscIdUnique 72 signumIntegerIdKey = mkPreludeMiscIdUnique 73 leIntegerPrimIdKey = mkPreludeMiscIdUnique 74 gtIntegerPrimIdKey = mkPreludeMiscIdUnique 75 ltIntegerPrimIdKey = mkPreludeMiscIdUnique 76 geIntegerPrimIdKey = mkPreludeMiscIdUnique 77 compareIntegerIdKey = mkPreludeMiscIdUnique 78 quotIntegerIdKey = mkPreludeMiscIdUnique 79 remIntegerIdKey = mkPreludeMiscIdUnique 80 divIntegerIdKey = mkPreludeMiscIdUnique 81 modIntegerIdKey = mkPreludeMiscIdUnique 82 divModIntegerIdKey = mkPreludeMiscIdUnique 83 quotRemIntegerIdKey = mkPreludeMiscIdUnique 84 floatFromIntegerIdKey = mkPreludeMiscIdUnique 85 doubleFromIntegerIdKey = mkPreludeMiscIdUnique 86 encodeFloatIntegerIdKey = mkPreludeMiscIdUnique 87 encodeDoubleIntegerIdKey = mkPreludeMiscIdUnique 88 gcdIntegerIdKey = mkPreludeMiscIdUnique 89 lcmIntegerIdKey = mkPreludeMiscIdUnique 90 andIntegerIdKey = mkPreludeMiscIdUnique 91 orIntegerIdKey = mkPreludeMiscIdUnique 92 xorIntegerIdKey = mkPreludeMiscIdUnique 93 complementIntegerIdKey = mkPreludeMiscIdUnique 94 shiftLIntegerIdKey = mkPreludeMiscIdUnique 95 shiftRIntegerIdKey = mkPreludeMiscIdUnique 96 wordToIntegerIdKey = mkPreludeMiscIdUnique 97 word64ToIntegerIdKey = mkPreludeMiscIdUnique 98 int64ToIntegerIdKey = mkPreludeMiscIdUnique 99 decodeDoubleIntegerIdKey = mkPreludeMiscIdUnique 100 rootMainKey, runMainKey :: Unique rootMainKey = mkPreludeMiscIdUnique 101 runMainKey = mkPreludeMiscIdUnique 102 thenIOIdKey, lazyIdKey, assertErrorIdKey, oneShotKey, runRWKey :: Unique thenIOIdKey = mkPreludeMiscIdUnique 103 lazyIdKey = mkPreludeMiscIdUnique 104 assertErrorIdKey = mkPreludeMiscIdUnique 105 oneShotKey = mkPreludeMiscIdUnique 106 runRWKey = mkPreludeMiscIdUnique 107 breakpointIdKey, breakpointCondIdKey, breakpointAutoIdKey, breakpointJumpIdKey, breakpointCondJumpIdKey, breakpointAutoJumpIdKey :: Unique breakpointIdKey = mkPreludeMiscIdUnique 110 breakpointCondIdKey = mkPreludeMiscIdUnique 111 breakpointAutoIdKey = mkPreludeMiscIdUnique 112 breakpointJumpIdKey = mkPreludeMiscIdUnique 113 breakpointCondJumpIdKey = mkPreludeMiscIdUnique 114 breakpointAutoJumpIdKey = mkPreludeMiscIdUnique 115 inlineIdKey :: Unique inlineIdKey = mkPreludeMiscIdUnique 120 mapIdKey, groupWithIdKey, dollarIdKey :: Unique mapIdKey = mkPreludeMiscIdUnique 121 groupWithIdKey = mkPreludeMiscIdUnique 122 dollarIdKey = mkPreludeMiscIdUnique 123 coercionTokenIdKey :: Unique coercionTokenIdKey = mkPreludeMiscIdUnique 124 rationalToFloatIdKey, rationalToDoubleIdKey :: Unique rationalToFloatIdKey = mkPreludeMiscIdUnique 130 rationalToDoubleIdKey = mkPreludeMiscIdUnique 131 -- dotnet interop unmarshalObjectIdKey, marshalObjectIdKey, marshalStringIdKey, unmarshalStringIdKey, checkDotnetResNameIdKey :: Unique unmarshalObjectIdKey = mkPreludeMiscIdUnique 150 marshalObjectIdKey = mkPreludeMiscIdUnique 151 marshalStringIdKey = mkPreludeMiscIdUnique 152 unmarshalStringIdKey = mkPreludeMiscIdUnique 153 checkDotnetResNameIdKey = mkPreludeMiscIdUnique 154 undefinedKey :: Unique undefinedKey = mkPreludeMiscIdUnique 155 magicDictKey :: Unique magicDictKey = mkPreludeMiscIdUnique 156 coerceKey :: Unique coerceKey = mkPreludeMiscIdUnique 157 {- Certain class operations from Prelude classes. They get their own uniques so we can look them up easily when we want to conjure them up during type checking. -} -- Just a placeholder for unbound variables produced by the renamer: unboundKey :: Unique unboundKey = mkPreludeMiscIdUnique 158 fromIntegerClassOpKey, minusClassOpKey, fromRationalClassOpKey, enumFromClassOpKey, enumFromThenClassOpKey, enumFromToClassOpKey, enumFromThenToClassOpKey, eqClassOpKey, geClassOpKey, negateClassOpKey, failMClassOpKey_preMFP, bindMClassOpKey, thenMClassOpKey, returnMClassOpKey, fmapClassOpKey :: Unique fromIntegerClassOpKey = mkPreludeMiscIdUnique 160 minusClassOpKey = mkPreludeMiscIdUnique 161 fromRationalClassOpKey = mkPreludeMiscIdUnique 162 enumFromClassOpKey = mkPreludeMiscIdUnique 163 enumFromThenClassOpKey = mkPreludeMiscIdUnique 164 enumFromToClassOpKey = mkPreludeMiscIdUnique 165 enumFromThenToClassOpKey = mkPreludeMiscIdUnique 166 eqClassOpKey = mkPreludeMiscIdUnique 167 geClassOpKey = mkPreludeMiscIdUnique 168 negateClassOpKey = mkPreludeMiscIdUnique 169 failMClassOpKey_preMFP = mkPreludeMiscIdUnique 170 bindMClassOpKey = mkPreludeMiscIdUnique 171 -- (>>=) thenMClassOpKey = mkPreludeMiscIdUnique 172 -- (>>) fmapClassOpKey = mkPreludeMiscIdUnique 173 returnMClassOpKey = mkPreludeMiscIdUnique 174 -- Recursive do notation mfixIdKey :: Unique mfixIdKey = mkPreludeMiscIdUnique 175 -- MonadFail operations failMClassOpKey :: Unique failMClassOpKey = mkPreludeMiscIdUnique 176 -- Arrow notation arrAIdKey, composeAIdKey, firstAIdKey, appAIdKey, choiceAIdKey, loopAIdKey :: Unique arrAIdKey = mkPreludeMiscIdUnique 180 composeAIdKey = mkPreludeMiscIdUnique 181 -- >>> firstAIdKey = mkPreludeMiscIdUnique 182 appAIdKey = mkPreludeMiscIdUnique 183 choiceAIdKey = mkPreludeMiscIdUnique 184 -- ||| loopAIdKey = mkPreludeMiscIdUnique 185 fromStringClassOpKey :: Unique fromStringClassOpKey = mkPreludeMiscIdUnique 186 -- Annotation type checking toAnnotationWrapperIdKey :: Unique toAnnotationWrapperIdKey = mkPreludeMiscIdUnique 187 -- Conversion functions fromIntegralIdKey, realToFracIdKey, toIntegerClassOpKey, toRationalClassOpKey :: Unique fromIntegralIdKey = mkPreludeMiscIdUnique 190 realToFracIdKey = mkPreludeMiscIdUnique 191 toIntegerClassOpKey = mkPreludeMiscIdUnique 192 toRationalClassOpKey = mkPreludeMiscIdUnique 193 -- Monad comprehensions guardMIdKey, liftMIdKey, mzipIdKey :: Unique guardMIdKey = mkPreludeMiscIdUnique 194 liftMIdKey = mkPreludeMiscIdUnique 195 mzipIdKey = mkPreludeMiscIdUnique 196 -- GHCi ghciStepIoMClassOpKey :: Unique ghciStepIoMClassOpKey = mkPreludeMiscIdUnique 197 -- Overloaded lists isListClassKey, fromListClassOpKey, fromListNClassOpKey, toListClassOpKey :: Unique isListClassKey = mkPreludeMiscIdUnique 198 fromListClassOpKey = mkPreludeMiscIdUnique 199 fromListNClassOpKey = mkPreludeMiscIdUnique 500 toListClassOpKey = mkPreludeMiscIdUnique 501 proxyHashKey :: Unique proxyHashKey = mkPreludeMiscIdUnique 502 ---------------- Template Haskell ------------------- -- THNames.hs: USES IdUniques 200-499 ----------------------------------------------------- -- Used to make `Typeable` dictionaries mkTyConKey , mkPolyTyConAppKey , mkAppTyKey , typeNatTypeRepKey , typeSymbolTypeRepKey , typeRepIdKey :: Unique mkTyConKey = mkPreludeMiscIdUnique 503 mkPolyTyConAppKey = mkPreludeMiscIdUnique 504 mkAppTyKey = mkPreludeMiscIdUnique 505 typeNatTypeRepKey = mkPreludeMiscIdUnique 506 typeSymbolTypeRepKey = mkPreludeMiscIdUnique 507 typeRepIdKey = mkPreludeMiscIdUnique 508 -- Dynamic toDynIdKey :: Unique toDynIdKey = mkPreludeMiscIdUnique 509 bitIntegerIdKey :: Unique bitIntegerIdKey = mkPreludeMiscIdUnique 510 heqSCSelIdKey, coercibleSCSelIdKey :: Unique heqSCSelIdKey = mkPreludeMiscIdUnique 511 coercibleSCSelIdKey = mkPreludeMiscIdUnique 512 sappendClassOpKey :: Unique sappendClassOpKey = mkPreludeMiscIdUnique 513 memptyClassOpKey, mappendClassOpKey, mconcatClassOpKey :: Unique memptyClassOpKey = mkPreludeMiscIdUnique 514 mappendClassOpKey = mkPreludeMiscIdUnique 515 mconcatClassOpKey = mkPreludeMiscIdUnique 516 emptyCallStackKey, pushCallStackKey :: Unique emptyCallStackKey = mkPreludeMiscIdUnique 517 pushCallStackKey = mkPreludeMiscIdUnique 518 fromStaticPtrClassOpKey :: Unique fromStaticPtrClassOpKey = mkPreludeMiscIdUnique 519 {- ************************************************************************ * * \subsection[Class-std-groups]{Standard groups of Prelude classes} * * ************************************************************************ NOTE: @Eq@ and @Text@ do need to appear in @standardClasses@ even though every numeric class has these two as a superclass, because the list of ambiguous dictionaries hasn't been simplified. -} numericClassKeys :: [Unique] numericClassKeys = [ numClassKey , realClassKey , integralClassKey ] ++ fractionalClassKeys fractionalClassKeys :: [Unique] fractionalClassKeys = [ fractionalClassKey , floatingClassKey , realFracClassKey , realFloatClassKey ] -- The "standard classes" are used in defaulting (Haskell 98 report 4.3.4), -- and are: "classes defined in the Prelude or a standard library" standardClassKeys :: [Unique] standardClassKeys = derivableClassKeys ++ numericClassKeys ++ [randomClassKey, randomGenClassKey, functorClassKey, monadClassKey, monadPlusClassKey, monadFailClassKey, semigroupClassKey, monoidClassKey, isStringClassKey, applicativeClassKey, foldableClassKey, traversableClassKey, alternativeClassKey ] {- @derivableClassKeys@ is also used in checking \tr{deriving} constructs (@TcDeriv@). -} derivableClassKeys :: [Unique] derivableClassKeys = [ eqClassKey, ordClassKey, enumClassKey, ixClassKey, boundedClassKey, showClassKey, readClassKey ] -- These are the "interactive classes" that are consulted when doing -- defaulting. Does not include Num or IsString, which have special -- handling. interactiveClassNames :: [Name] interactiveClassNames = [ showClassName, eqClassName, ordClassName, foldableClassName , traversableClassName ] interactiveClassKeys :: [Unique] interactiveClassKeys = map getUnique interactiveClassNames {- ************************************************************************ * * Semi-builtin names * * ************************************************************************ The following names should be considered by GHCi to be in scope always. -} pretendNameIsInScope :: Name -> Bool pretendNameIsInScope n = any (n `hasKey`) [ starKindTyConKey, liftedTypeKindTyConKey, tYPETyConKey , unliftedTypeKindTyConKey , runtimeRepTyConKey, ptrRepLiftedDataConKey, ptrRepUnliftedDataConKey ]
vTurbine/ghc
compiler/prelude/PrelNames.hs
bsd-3-clause
101,220
0
10
22,765
15,490
8,836
6,654
1,549
2
module Module3.Task7 where import Data.Char readDigits :: String -> (String, String) readDigits x = (takeWhile isDigit x, dropWhile isDigit x)
dstarcev/stepic-haskell
src/Module3/Task7.hs
bsd-3-clause
145
0
6
22
50
28
22
4
1
-- | -- Module: Graphics.Chalkboard.Utils -- Copyright: (c) 2009 The University of Kansas -- License: BSD3 -- -- Maintainer: Andy Gill <[email protected]> -- Stability: unstable -- Portability: ghc -- -- This module has some basic, externally visable, definitions. module Graphics.ChalkBoard.Utils ( -- * Point Utilties. insideRegion , insideCircle , distance , intervalOnLine , circleOfDots , insidePoly -- * Utilties for @R@. , innerSteps, outerSteps, fracPart , fromPolar , toPolar , angleOfLine , ) where -- , red, green, blue, white, black, cyan, purple, yellow import Graphics.ChalkBoard.Types -- | innerSteps takes n even steps from 0 .. 1, by not actually touching 0 or 1. -- The first and last step are 1/2 the size of the others, so that repeated innerSteps -- can be tiled neatly. innerSteps :: Int -> [R] innerSteps n = map (/ fromIntegral (n * 2)) (map fromIntegral (take n [1::Int,3..])) -- | outerSteps takes n even steps from 0 .. 1, starting with 0, and ending with 1, -- returning n+1 elements. outerSteps :: Int -> [R] outerSteps n = map (/ fromIntegral n) (map fromIntegral (take (n + 1) [(0::Int)..])) -- | Extract the fractional part of an @R@. fracPart :: R -> R fracPart x = x - fromIntegral ((floor x) :: Integer) -- Point operations -- | is a @Point@ inside a region? insideRegion :: (Point,Point) -> Point -> Bool insideRegion ((x1,y1),(x2,y2)) (x,y) = x1 <= x && x <= x2 && y1 <= y && y <= y2 -- | is a @Point@ inside a circle, where the first two arguments are the center of the circle, -- and the radius. insideCircle :: Point -> R -> Point -> Bool insideCircle (x1,y1) r (x,y) = distance (x1,y1) (x,y) <= r -- | What is the 'distance' between two points in R2? -- This is optimised for the normal form @distance p1 p2 <= v@, which avoids using @sqrt@. distance :: Point -> Point -> R distance (x,y) (x',y') = sqrt (xd * xd + yd * yd) where xd = x - x' yd = y - y' {-# INLINE distance #-} -- The obvious sqrt (x * x) ==> x does not fire. {-# RULES "distance <= w" forall t u w . distance t u <= w = distanceLe t u w #-} {-# INLINE distanceLe #-} distanceLe :: Point -> Point -> R -> Bool distanceLe (x,y) (x',y') w = (xd * xd + yd * yd) <= w * w where xd = x - x' yd = y - y' -- | 'intervalOnLine' find the place on a line (between 0 and 1) that is closest to the given point. intervalOnLine :: (Point,Point) -> Point -> R intervalOnLine ((x1,y1),(x2,y2)) (x0,y0) = ((x0-x1)*(x2-x1)+(y0-y1)*(y2-y1))/(xd * xd + yd * yd) where xd = x2-x1 yd = y2-y1 fromPolar :: (R,Radian) -> Point fromPolar (p, phi) = (p * cos phi, p * sin phi) toPolar :: Point -> (R,Radian) toPolar (x, y) = (sqrt (x * x + y * y), atan2 y x) angleOfLine :: (Point,Point) -> Radian angleOfLine ((x1,y1),(x2,y2)) = atan2 (x2 - x1) (y2 - y1) -- | circleOfDots generates a set of points between (-1..1,-1..1), inside a circle. circleOfDots :: Int -> [Point] circleOfDots 0 = error "circleOfDots 0" circleOfDots n = [ (x,y) | x <- map (\ t -> t * 2 - 1) $ outerSteps n , y <- map (\ t -> t * 2 - 1) $ outerSteps n , (x * x + y * y) <= 1.0 ] insidePoly :: [Point] -> Point -> Bool insidePoly nodes (x,y) -- no numbers above 0, or no numbers below zero -- means that the numbers we the *same* sign (or zero)> | null (filter (> 0) vals) || null (filter (< 0) vals) = True | otherwise = False where vals = [ (y - y0) * (x1 - x0) - (x - x0) * (y1 - y0) | ((x0,y0),(x1,y1)) <- zip nodes (tail nodes ++ [head nodes]) ]
andygill/chalkboard2
Graphics/ChalkBoard/Utils.hs
bsd-3-clause
3,541
16
14
807
1,176
667
509
58
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} #ifdef USE_TEMPLATE_HASKELL {-# LANGUAGE TemplateHaskell #-} #endif {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} #ifdef ghcjs_HOST_OS {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE JavaScriptFFI #-} #endif -- | This is a builder to be used on the client side. It can be run in two modes: -- -- 1. in "hydration mode", reusing DOM nodes already in the page (as produced -- by 'Reflex.Dom.Builder.Static.renderStatic') -- 2. in "immediate mode", creating and appending DOM nodes as required -- -- In "hydration mode", the preexisting DOM __must contain__ what the builder -- will expect at switchover time (the time at which parity with the static -- renderer is reached, and the time after which the page is "live"). -- -- For example, displaying the current time as text should be done inside -- 'Reflex.Dom.Prerender.prerender' to ensure that we don't attempt to hydrate the incorrect text. -- The server will prerender a text node with time A, and the client will expect -- a text node with time B. Barring a miracle, time A and time B will not match, -- and hydration will fail. module Reflex.Dom.Builder.Immediate ( HydrationDomBuilderT (..) , HydrationDomBuilderEnv (..) , HydrationMode (..) , HydrationRunnerT (..) , runHydrationRunnerT , runHydrationRunnerTWithFailure , ImmediateDomBuilderT , runHydrationDomBuilderT , getHydrationMode , addHydrationStep , addHydrationStepWithSetup , setPreviousNode , insertAfterPreviousNode , hydrateComment , askParent , askEvents , append , textNodeInternal , removeSubsequentNodes , deleteBetweenExclusive , extractBetweenExclusive , deleteUpTo , extractUpTo , SupportsHydrationDomBuilder , collectUpTo , collectUpToGivenParent , EventTriggerRef (..) , EventFilterTriggerRef (..) , wrap , elementInternal , HydrationDomSpace , GhcjsDomSpace , GhcjsDomHandler (..) , GhcjsDomHandler1 (..) , GhcjsDomEvent (..) , GhcjsEventFilter (..) , Pair1 (..) , Maybe1 (..) , GhcjsEventSpec (..) , HasDocument (..) , ghcjsEventSpec_filters , ghcjsEventSpec_handler , GhcjsEventHandler (..) , drawChildUpdate , ChildReadyState (..) , mkHasFocus , insertBefore , EventType , defaultDomEventHandler , defaultDomWindowEventHandler , withIsEvent , showEventName , elementOnEventName , windowOnEventName , wrapDomEvent , subscribeDomEvent , wrapDomEventMaybe , wrapDomEventsMaybe , getKeyEvent , getMouseEventCoords , getTouchEvent , WindowConfig (..) , Window (..) , wrapWindow -- * Attributes for controlling hydration , hydratableAttribute , skipHydrationAttribute -- * Internal , traverseDMapWithKeyWithAdjust' , hoistTraverseWithKeyWithAdjust , traverseIntMapWithKeyWithAdjust' , hoistTraverseIntMapWithKeyWithAdjust ) where import Control.Concurrent import Control.Exception (bracketOnError) import Control.Lens (Identity(..), imapM_, iforM_, (^.), makeLenses) import Control.Monad.Exception import Control.Monad.Primitive import Control.Monad.Reader import Control.Monad.Ref import Control.Monad.State.Strict (StateT, mapStateT, get, modify', gets, runStateT) import Data.Bitraversable import Data.Default import Data.Dependent.Map (DMap) import Data.Dependent.Sum import Data.FastMutableIntMap (PatchIntMap (..)) import Data.Foldable (for_, traverse_) import Data.Functor.Compose import Data.Functor.Constant import Data.Functor.Misc import Data.Functor.Product import Data.GADT.Compare (GCompare) import Data.IORef import Data.IntMap.Strict (IntMap) import Data.Maybe import Data.Monoid ((<>)) import Data.Some (Some(..)) import Data.String (IsString) import Data.Text (Text) import Foreign.JavaScript.Internal.Utils import Foreign.JavaScript.TH import GHCJS.DOM.ClipboardEvent as ClipboardEvent import GHCJS.DOM.Document (Document, createDocumentFragment, createElement, createElementNS, createTextNode, createComment) import GHCJS.DOM.Element (getScrollTop, removeAttribute, removeAttributeNS, setAttribute, setAttributeNS, hasAttribute) import GHCJS.DOM.EventM (EventM, event, on) import GHCJS.DOM.KeyboardEvent as KeyboardEvent import GHCJS.DOM.MouseEvent import GHCJS.DOM.Node (appendChild_, getOwnerDocumentUnchecked, getParentNodeUnchecked, setNodeValue, toNode) import GHCJS.DOM.Types (liftJSM, askJSM, runJSM, JSM, MonadJSM, FocusEvent, IsElement, IsEvent, IsNode, KeyboardEvent, Node, TouchEvent, WheelEvent, uncheckedCastTo, ClipboardEvent) import GHCJS.DOM.UIEvent #ifndef ghcjs_HOST_OS import Language.Javascript.JSaddle (call, eval) -- Avoid using eval in ghcjs. Use ffi instead #endif import Reflex.Adjustable.Class import Reflex.Class as Reflex import Reflex.Dom.Builder.Class import Reflex.Dynamic import Reflex.Host.Class import Reflex.Patch.DMapWithMove (PatchDMapWithMove(..)) import Reflex.Patch.MapWithMove (PatchMapWithMove(..)) import Reflex.PerformEvent.Base (PerformEventT) import Reflex.PerformEvent.Class import Reflex.PostBuild.Base (PostBuildT) import Reflex.PostBuild.Class #ifdef PROFILE_REFLEX import Reflex.Profiled #endif import Reflex.Requester.Base import Reflex.Requester.Class import Reflex.Spider (Spider, SpiderHost, Global) import Reflex.TriggerEvent.Base hiding (askEvents) import Reflex.TriggerEvent.Class import qualified Data.Dependent.Map as DMap import qualified Data.FastMutableIntMap as FastMutableIntMap import qualified Data.IntMap.Strict as IntMap import qualified Data.Map as Map import qualified Data.Text as T import qualified GHCJS.DOM as DOM import qualified GHCJS.DOM.DataTransfer as DataTransfer import qualified GHCJS.DOM.DocumentAndElementEventHandlers as Events import qualified GHCJS.DOM.DocumentOrShadowRoot as Document import qualified GHCJS.DOM.Element as Element import qualified GHCJS.DOM.Event as Event import qualified GHCJS.DOM.EventM as DOM import qualified GHCJS.DOM.FileList as FileList import qualified GHCJS.DOM.GlobalEventHandlers as Events import qualified GHCJS.DOM.HTMLInputElement as Input import qualified GHCJS.DOM.HTMLSelectElement as Select import qualified GHCJS.DOM.HTMLTextAreaElement as TextArea import qualified GHCJS.DOM.Node as Node import qualified GHCJS.DOM.Text as DOM import qualified GHCJS.DOM.Touch as Touch import qualified GHCJS.DOM.TouchEvent as TouchEvent import qualified GHCJS.DOM.TouchList as TouchList import qualified GHCJS.DOM.Types as DOM import qualified GHCJS.DOM.Window as Window import qualified GHCJS.DOM.WheelEvent as WheelEvent import qualified Reflex.Patch.DMap as PatchDMap import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove import qualified Reflex.Patch.MapWithMove as PatchMapWithMove import qualified Reflex.TriggerEvent.Base as TriggerEventT (askEvents) #ifndef USE_TEMPLATE_HASKELL import Data.Functor.Contravariant (phantom) import Control.Lens (Lens', Getter) #endif #ifndef ghcjs_HOST_OS import GHCJS.DOM.Types (MonadJSM (..)) instance MonadJSM m => MonadJSM (HydrationRunnerT t m) where {-# INLINABLE liftJSM' #-} liftJSM' = lift . liftJSM' instance MonadJSM m => MonadJSM (HydrationDomBuilderT s t m) where {-# INLINABLE liftJSM' #-} liftJSM' = lift . liftJSM' instance MonadJSM m => MonadJSM (DomRenderHookT t m) where {-# INLINABLE liftJSM' #-} liftJSM' = lift . liftJSM' #endif data HydrationDomBuilderEnv t m = HydrationDomBuilderEnv { _hydrationDomBuilderEnv_document :: {-# UNPACK #-} !Document -- ^ Reference to the document , _hydrationDomBuilderEnv_parent :: !(Either Node (IORef Node)) -- ^ This is in an IORef because in the time up to hydration we can't actually know what the -- parent is - we populate this reference during the DOM traversal at hydration time , _hydrationDomBuilderEnv_unreadyChildren :: {-# UNPACK #-} !(IORef Word) -- ^ Number of children who still aren't fully rendered , _hydrationDomBuilderEnv_commitAction :: !(JSM ()) -- ^ Action to take when all children are ready --TODO: we should probably get rid of this once we invoke it , _hydrationDomBuilderEnv_hydrationMode :: {-# UNPACK #-} !(IORef HydrationMode) -- ^ In hydration mode? Should be switched to `HydrationMode_Immediate` after hydration is finished , _hydrationDomBuilderEnv_switchover :: !(Event t ()) , _hydrationDomBuilderEnv_delayed :: {-# UNPACK #-} !(IORef (HydrationRunnerT t m ())) } -- | A monad for DomBuilder which just gets the results of children and pushes -- work into an action that is delayed until after postBuild (to match the -- static builder). The action runs in 'HydrationRunnerT', which performs the -- DOM takeover and sets up the events, after which point this monad will -- continue in the vein of 'ImmediateDomBuilderT'. newtype HydrationDomBuilderT s t m a = HydrationDomBuilderT { unHydrationDomBuilderT :: ReaderT (HydrationDomBuilderEnv t m) (DomRenderHookT t m) a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException #if MIN_VERSION_base(4,9,1) , MonadAsyncException #endif ) instance PrimMonad m => PrimMonad (HydrationDomBuilderT s t m) where type PrimState (HydrationDomBuilderT s t m) = PrimState m primitive = lift . primitive instance MonadTrans (HydrationDomBuilderT s t) where lift = HydrationDomBuilderT . lift . lift instance (Reflex t, MonadFix m) => DomRenderHook t (HydrationDomBuilderT s t m) where withRenderHook hook = HydrationDomBuilderT . mapReaderT (withRenderHook hook) . unHydrationDomBuilderT requestDomAction = HydrationDomBuilderT . lift . requestDomAction requestDomAction_ = HydrationDomBuilderT . lift . requestDomAction_ -- | The monad which performs the delayed actions to reuse prerendered nodes and set up events. -- State contains reference to the previous node sibling, if any, and the reader contains reference to the parent node. newtype HydrationRunnerT t m a = HydrationRunnerT { unHydrationRunnerT :: StateT HydrationState (ReaderT Node (DomRenderHookT t m)) a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException #if MIN_VERSION_base(4,9,1) , MonadAsyncException #endif ) data HydrationState = HydrationState { _hydrationState_previousNode :: !(Maybe Node) , _hydrationState_failed :: !Bool } {-# INLINABLE localRunner #-} localRunner :: (MonadJSM m, Monad m) => HydrationRunnerT t m a -> Maybe Node -> Node -> HydrationRunnerT t m a localRunner (HydrationRunnerT m) s parent = do s0 <- HydrationRunnerT get (a, s') <- HydrationRunnerT $ lift $ local (\_ -> parent) $ runStateT m (s0 { _hydrationState_previousNode = s }) traverse_ removeSubsequentNodes $ _hydrationState_previousNode s' HydrationRunnerT $ modify' $ \hs -> hs { _hydrationState_failed = _hydrationState_failed s' } pure a {-# INLINABLE runHydrationRunnerT #-} runHydrationRunnerT :: (MonadRef m, Ref m ~ IORef, Monad m, PerformEvent t m, MonadFix m, MonadReflexCreateTrigger t m, MonadJSM m, MonadJSM (Performable m)) => HydrationRunnerT t m a -> Maybe Node -> Node -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a runHydrationRunnerT m = runHydrationRunnerTWithFailure m (pure ()) {-# INLINABLE runHydrationRunnerTWithFailure #-} runHydrationRunnerTWithFailure :: (MonadRef m, Ref m ~ IORef, Monad m, PerformEvent t m, MonadFix m, MonadReflexCreateTrigger t m, MonadJSM m, MonadJSM (Performable m)) => HydrationRunnerT t m a -> IO () -> Maybe Node -> Node -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a runHydrationRunnerTWithFailure (HydrationRunnerT m) onFailure s parent events = flip runDomRenderHookT events $ flip runReaderT parent $ do (a, s') <- runStateT m (HydrationState s False) traverse_ removeSubsequentNodes $ _hydrationState_previousNode s' when (_hydrationState_failed s') $ liftIO $ putStrLn "reflex-dom warning: hydration failed: the DOM was not as expected at switchover time. This may be due to invalid HTML which the browser has altered upon parsing, some external JS altering the DOM, or the page being served from an outdated cache." when (_hydrationState_failed s') $ liftIO onFailure pure a instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (HydrationRunnerT t m) where {-# INLINABLE newEventWithTrigger #-} newEventWithTrigger = lift . newEventWithTrigger {-# INLINABLE newFanEventWithTrigger #-} newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance MonadTrans (HydrationRunnerT t) where {-# INLINABLE lift #-} lift = HydrationRunnerT . lift . lift . lift instance MonadSample t m => MonadSample t (HydrationRunnerT t m) where {-# INLINABLE sample #-} sample = lift . sample instance (Reflex t, MonadFix m) => DomRenderHook t (HydrationRunnerT t m) where withRenderHook hook = HydrationRunnerT . mapStateT (mapReaderT (withRenderHook hook)) . unHydrationRunnerT requestDomAction = HydrationRunnerT . lift . lift . requestDomAction requestDomAction_ = HydrationRunnerT . lift . lift . requestDomAction_ -- | Add a hydration step which depends on some computation that should only be -- done *before* the switchover to immediate mode - this is most likely some -- form of 'hold' which we want to remove after hydration is done {-# INLINABLE addHydrationStepWithSetup #-} addHydrationStepWithSetup :: MonadIO m => m a -> (a -> HydrationRunnerT t m ()) -> HydrationDomBuilderT s t m () addHydrationStepWithSetup setup f = getHydrationMode >>= \case HydrationMode_Immediate -> pure () HydrationMode_Hydrating -> do s <- lift setup addHydrationStep (f s) -- | Add a hydration step {-# INLINABLE addHydrationStep #-} addHydrationStep :: MonadIO m => HydrationRunnerT t m () -> HydrationDomBuilderT s t m () addHydrationStep m = do delayedRef <- HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_delayed liftIO $ modifyIORef' delayedRef (>> m) -- | Shared behavior for HydrationDomBuilderT and HydrationRunnerT newtype DomRenderHookT t m a = DomRenderHookT { unDomRenderHookT :: RequesterT t JSM Identity (TriggerEventT t m) a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException #if MIN_VERSION_base(4,9,1) , MonadAsyncException #endif ) {-# INLINABLE runDomRenderHookT #-} runDomRenderHookT :: (MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadJSM m, MonadJSM (Performable m), MonadRef m, Ref m ~ IORef) => DomRenderHookT t m a -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a runDomRenderHookT (DomRenderHookT a) events = do flip runTriggerEventT events $ do rec (result, req) <- runRequesterT a rsp rsp <- performEventAsync $ ffor req $ \rm f -> liftJSM $ runInAnimationFrame f $ traverseRequesterData (fmap Identity) rm return result where runInAnimationFrame f x = void . DOM.inAnimationFrame' $ \_ -> do v <- synchronously x void . liftIO $ f v instance MonadTrans (DomRenderHookT t) where {-# INLINABLE lift #-} lift = DomRenderHookT . lift . lift instance (Reflex t, MonadFix m) => DomRenderHook t (DomRenderHookT t m) where withRenderHook hook (DomRenderHookT a) = do DomRenderHookT $ withRequesting $ \rsp -> do (x, req) <- lift $ runRequesterT a $ runIdentity <$> rsp return (ffor req $ \rm -> hook $ traverseRequesterData (fmap Identity) rm, x) requestDomAction = DomRenderHookT . requestingIdentity requestDomAction_ = DomRenderHookT . requesting_ {-# INLINABLE runHydrationDomBuilderT #-} runHydrationDomBuilderT :: ( MonadFix m , PerformEvent t m , MonadReflexCreateTrigger t m , MonadJSM m , MonadJSM (Performable m) , MonadRef m , Ref m ~ IORef ) => HydrationDomBuilderT s t m a -> HydrationDomBuilderEnv t m -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a runHydrationDomBuilderT (HydrationDomBuilderT a) env = runDomRenderHookT (runReaderT a env) instance (RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, Monad m) => HasDocument (HydrationDomBuilderT s t m) where {-# INLINABLE askDocument #-} askDocument = HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_document {-# INLINABLE askParent #-} askParent :: Monad m => HydrationRunnerT t m DOM.Node askParent = HydrationRunnerT ask {-# INLINABLE getParent #-} getParent :: MonadIO m => HydrationDomBuilderT s t m DOM.Node getParent = either pure (liftIO . readIORef) =<< HydrationDomBuilderT (asks _hydrationDomBuilderEnv_parent) {-# INLINABLE askEvents #-} askEvents :: Monad m => HydrationDomBuilderT s t m (Chan [DSum (EventTriggerRef t) TriggerInvocation]) askEvents = HydrationDomBuilderT . lift . DomRenderHookT . lift $ TriggerEventT.askEvents {-# INLINABLE localEnv #-} localEnv :: Monad m => (HydrationDomBuilderEnv t m -> HydrationDomBuilderEnv t m) -> HydrationDomBuilderT s t m a -> HydrationDomBuilderT s t m a localEnv f = HydrationDomBuilderT . local (f $!) . unHydrationDomBuilderT {-# INLINABLE append #-} append :: MonadJSM m => DOM.Node -> HydrationDomBuilderT s t m () append n = do p <- getParent liftJSM $ appendChild_ p n return () {-# SPECIALIZE append :: DOM.Node -> HydrationDomBuilderT s Spider HydrationM () #-} data HydrationMode = HydrationMode_Hydrating -- ^ The time from initial load to parity with static builder | HydrationMode_Immediate -- ^ After hydration deriving (Eq, Ord, Show) {-# INLINABLE getPreviousNode #-} getPreviousNode :: Monad m => HydrationRunnerT t m (Maybe DOM.Node) getPreviousNode = HydrationRunnerT $ gets _hydrationState_previousNode {-# INLINABLE setPreviousNode #-} setPreviousNode :: Monad m => Maybe DOM.Node -> HydrationRunnerT t m () setPreviousNode n = HydrationRunnerT $ modify' (\hs -> hs { _hydrationState_previousNode = n }) {-# INLINABLE askUnreadyChildren #-} askUnreadyChildren :: Monad m => HydrationDomBuilderT s t m (IORef Word) askUnreadyChildren = HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_unreadyChildren {-# INLINABLE askCommitAction #-} askCommitAction :: Monad m => HydrationDomBuilderT s t m (JSM ()) askCommitAction = HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_commitAction {-# INLINABLE getHydrationMode #-} getHydrationMode :: MonadIO m => HydrationDomBuilderT s t m HydrationMode getHydrationMode = liftIO . readIORef =<< HydrationDomBuilderT (asks _hydrationDomBuilderEnv_hydrationMode) -- | Remove all nodes after given node removeSubsequentNodes :: (MonadJSM m, IsNode n) => n -> m () #ifdef ghcjs_HOST_OS --NOTE: Although wrapping this javascript in a function seems unnecessary, GHCJS's optimizer will break it if it is entered without that wrapping (as of 2021-11-06) foreign import javascript unsafe "(function() { var n = $1; while (n['nextSibling']) { n['parentNode']['removeChild'](n['nextSibling']); }; })()" removeSubsequentNodes_ :: DOM.Node -> IO () removeSubsequentNodes n = liftJSM $ removeSubsequentNodes_ (toNode n) #else removeSubsequentNodes n = liftJSM $ do f <- eval ("(function(n) { while (n.nextSibling) { (n.parentNode).removeChild(n.nextSibling); }; })" :: Text) void $ call f f [n] #endif -- | s and e must both be children of the same node and s must precede e; -- all nodes between s and e will be removed, but s and e will not be removed deleteBetweenExclusive :: (MonadJSM m, IsNode start, IsNode end) => start -> end -> m () deleteBetweenExclusive s e = liftJSM $ do df <- createDocumentFragment =<< getOwnerDocumentUnchecked s extractBetweenExclusive df s e -- In many places in ImmediateDomBuilderT, we assume that things always have a parent; by adding them to this DocumentFragment, we maintain that invariant -- | s and e must both be children of the same node and s must precede e; all -- nodes between s and e will be moved into the given DocumentFragment, but s -- and e will not be moved extractBetweenExclusive :: (MonadJSM m, IsNode start, IsNode end) => DOM.DocumentFragment -> start -> end -> m () #ifdef ghcjs_HOST_OS --NOTE: Although wrapping this javascript in a function seems unnecessary, GHCJS's optimizer will break it if it is entered without that wrapping (as of 2021-11-06) foreign import javascript unsafe "(function() { var df = $1; var s = $2; var e = $3; var x; for(;;) { x = s['nextSibling']; if(e===x) { break; }; df['appendChild'](x); } })()" extractBetweenExclusive_ :: DOM.DocumentFragment -> DOM.Node -> DOM.Node -> IO () extractBetweenExclusive df s e = liftJSM $ extractBetweenExclusive_ df (toNode s) (toNode e) #else extractBetweenExclusive df s e = liftJSM $ do f <- eval ("(function(df,s,e) { var x; for(;;) { x = s['nextSibling']; if(e===x) { break; }; df['appendChild'](x); } })" :: Text) void $ call f f (df, s, e) #endif -- | s and e must both be children of the same node and s must precede e; -- s and all nodes between s and e will be removed, but e will not be removed {-# INLINABLE deleteUpTo #-} deleteUpTo :: (MonadJSM m, IsNode start, IsNode end) => start -> end -> m () deleteUpTo s e = do df <- createDocumentFragment =<< getOwnerDocumentUnchecked s extractUpTo df s e -- In many places in ImmediateDomBuilderT, we assume that things always have a parent; by adding them to this DocumentFragment, we maintain that invariant extractUpTo :: (MonadJSM m, IsNode start, IsNode end) => DOM.DocumentFragment -> start -> end -> m () #ifdef ghcjs_HOST_OS --NOTE: Although wrapping this javascript in a function seems unnecessary, GHCJS's optimizer will break it if it is entered without that wrapping (as of 2017-09-04) foreign import javascript unsafe "(function() { var x = $2; while(x !== $3) { var y = x['nextSibling']; $1['appendChild'](x); x = y; } })()" extractUpTo_ :: DOM.DocumentFragment -> DOM.Node -> DOM.Node -> IO () extractUpTo df s e = liftJSM $ extractUpTo_ df (toNode s) (toNode e) #else extractUpTo df s e = liftJSM $ do f <- eval ("(function(df,s,e){ var x = s; var y; for(;;) { y = x['nextSibling']; df['appendChild'](x); if(e===y) { break; } x = y; } })" :: Text) void $ call f f (df, s, e) #endif type SupportsHydrationDomBuilder t m = (Reflex t, MonadJSM m, MonadHold t m, MonadFix m, MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref JSM, Adjustable t m, PrimMonad m, PerformEvent t m, MonadJSM (Performable m)) {-# INLINABLE collectUpTo #-} collectUpTo :: (MonadJSM m, IsNode start, IsNode end) => start -> end -> m DOM.DocumentFragment collectUpTo s e = do currentParent <- getParentNodeUnchecked e -- May be different than it was at initial construction, e.g., because the parent may have dumped us in from a DocumentFragment collectUpToGivenParent currentParent s e {-# INLINABLE collectUpToGivenParent #-} collectUpToGivenParent :: (MonadJSM m, IsNode parent, IsNode start, IsNode end) => parent -> start -> end -> m DOM.DocumentFragment collectUpToGivenParent currentParent s e = do doc <- getOwnerDocumentUnchecked currentParent df <- createDocumentFragment doc extractUpTo df s e return df newtype EventFilterTriggerRef t er (en :: EventTag) = EventFilterTriggerRef (IORef (Maybe (EventTrigger t (er en)))) -- | This 'wrap' is only partial: it doesn't create the 'EventSelector' itself {-# INLINE wrap #-} wrap :: forall s m er t. (Reflex t, MonadJSM m, MonadReflexCreateTrigger t m, DomRenderHook t m, EventSpec s ~ GhcjsEventSpec) => Chan [DSum (EventTriggerRef t) TriggerInvocation] -> DOM.Element -> RawElementConfig er t s -> m (DMap EventName (EventFilterTriggerRef t er)) wrap events e cfg = do forM_ (_rawElementConfig_modifyAttributes cfg) $ \modifyAttrs -> requestDomAction_ $ ffor modifyAttrs $ imapM_ $ \(AttributeName mAttrNamespace n) mv -> case mAttrNamespace of Nothing -> maybe (removeAttribute e n) (setAttribute e n) mv Just ns -> maybe (removeAttributeNS e (Just ns) n) (setAttributeNS e (Just ns) n) mv eventTriggerRefs :: DMap EventName (EventFilterTriggerRef t er) <- liftJSM $ fmap DMap.fromList $ forM (DMap.toList $ _ghcjsEventSpec_filters $ _rawElementConfig_eventSpec cfg) $ \(en :=> GhcjsEventFilter f) -> do triggerRef <- liftIO $ newIORef Nothing _ <- elementOnEventName en e $ do --TODO: Something safer than this cast evt <- DOM.event (flags, k) <- liftJSM $ f $ GhcjsDomEvent evt when (_eventFlags_preventDefault flags) $ withIsEvent en DOM.preventDefault case _eventFlags_propagation flags of Propagation_Continue -> return () Propagation_Stop -> withIsEvent en DOM.stopPropagation Propagation_StopImmediate -> withIsEvent en DOM.stopImmediatePropagation mv <- liftJSM k --TODO: Only do this when the event is subscribed liftIO $ forM_ mv $ \v -> writeChan events [EventTriggerRef triggerRef :=> TriggerInvocation v (return ())] return $ en :=> EventFilterTriggerRef triggerRef return eventTriggerRefs {-# SPECIALIZE wrap :: Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation] -> DOM.Element -> RawElementConfig er DomTimeline HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (DMap EventName (EventFilterTriggerRef DomTimeline er)) #-} {-# SPECIALIZE wrap :: Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation] -> DOM.Element -> RawElementConfig er DomTimeline GhcjsDomSpace -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (DMap EventName (EventFilterTriggerRef DomTimeline er)) #-} {-# INLINE triggerBody #-} triggerBody :: forall s er t x. EventSpec s ~ GhcjsEventSpec => DOM.JSContextRef -> RawElementConfig er t s -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> DMap EventName (EventFilterTriggerRef t er) -> DOM.Element -> WrapArg er EventName x -> EventTrigger t x -> IO (IO ()) triggerBody ctx cfg events eventTriggerRefs e (WrapArg en) t = case DMap.lookup en eventTriggerRefs of Just (EventFilterTriggerRef r) -> do writeIORef r $ Just t return $ do writeIORef r Nothing Nothing -> (`runJSM` ctx) <$> (`runJSM` ctx) (elementOnEventName en e $ do evt <- DOM.event mv <- lift $ unGhcjsEventHandler handler (en, GhcjsDomEvent evt) case mv of Nothing -> return () Just v -> liftIO $ do --TODO: I don't think this is quite right: if a new trigger is created between when this is enqueued and when it fires, this may not work quite right ref <- newIORef $ Just t writeChan events [EventTriggerRef ref :=> TriggerInvocation v (return ())]) where -- Note: this needs to be done strictly and outside of the newFanEventWithTrigger, so that the newFanEventWithTrigger doesn't -- retain the entire cfg, which can cause a cyclic dependency that the GC won't be able to clean up handler :: GhcjsEventHandler er !handler = _ghcjsEventSpec_handler $ _rawElementConfig_eventSpec cfg {-# SPECIALIZE triggerBody :: DOM.JSContextRef -> RawElementConfig er DomTimeline HydrationDomSpace -> Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation] -> DMap EventName (EventFilterTriggerRef DomTimeline er) -> DOM.Element -> WrapArg er EventName x -> EventTrigger DomTimeline x -> IO (IO ()) #-} {-# SPECIALIZE triggerBody :: DOM.JSContextRef -> RawElementConfig er DomTimeline GhcjsDomSpace -> Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation] -> DMap EventName (EventFilterTriggerRef DomTimeline er) -> DOM.Element -> WrapArg er EventName x -> EventTrigger DomTimeline x -> IO (IO ()) #-} newtype GhcjsDomHandler a b = GhcjsDomHandler { unGhcjsDomHandler :: a -> JSM b } newtype GhcjsDomHandler1 a b = GhcjsDomHandler1 { unGhcjsDomHandler1 :: forall (x :: EventTag). a x -> JSM (b x) } newtype GhcjsDomEvent en = GhcjsDomEvent { unGhcjsDomEvent :: EventType en } data GhcjsDomSpace instance DomSpace GhcjsDomSpace where type EventSpec GhcjsDomSpace = GhcjsEventSpec type RawDocument GhcjsDomSpace = DOM.Document type RawTextNode GhcjsDomSpace = DOM.Text type RawCommentNode GhcjsDomSpace = DOM.Comment type RawElement GhcjsDomSpace = DOM.Element type RawInputElement GhcjsDomSpace = DOM.HTMLInputElement type RawTextAreaElement GhcjsDomSpace = DOM.HTMLTextAreaElement type RawSelectElement GhcjsDomSpace = DOM.HTMLSelectElement addEventSpecFlags _ en f es = es { _ghcjsEventSpec_filters = let f' = Just . GhcjsEventFilter . \case Nothing -> \evt -> do mEventResult <- unGhcjsEventHandler (_ghcjsEventSpec_handler es) (en, evt) return (f mEventResult, return mEventResult) Just (GhcjsEventFilter oldFilter) -> \evt -> do (oldFlags, oldContinuation) <- oldFilter evt mEventResult <- oldContinuation let newFlags = oldFlags <> f mEventResult return (newFlags, return mEventResult) in DMap.alter f' en $ _ghcjsEventSpec_filters es } newtype GhcjsEventFilter er en = GhcjsEventFilter (GhcjsDomEvent en -> JSM (EventFlags, JSM (Maybe (er en)))) data Pair1 (f :: k -> *) (g :: k -> *) (a :: k) = Pair1 (f a) (g a) data Maybe1 f a = Nothing1 | Just1 (f a) data GhcjsEventSpec er = GhcjsEventSpec { _ghcjsEventSpec_filters :: DMap EventName (GhcjsEventFilter er) , _ghcjsEventSpec_handler :: GhcjsEventHandler er } newtype GhcjsEventHandler er = GhcjsEventHandler { unGhcjsEventHandler :: forall en. (EventName en, GhcjsDomEvent en) -> JSM (Maybe (er en)) } #ifndef USE_TEMPLATE_HASKELL ghcjsEventSpec_filters :: forall er . Lens' (GhcjsEventSpec er) (DMap EventName (GhcjsEventFilter er)) ghcjsEventSpec_filters f (GhcjsEventSpec a b) = (\a' -> GhcjsEventSpec a' b) <$> f a {-# INLINE ghcjsEventSpec_filters #-} ghcjsEventSpec_handler :: forall er en . Getter (GhcjsEventSpec er) ((EventName en, GhcjsDomEvent en) -> JSM (Maybe (er en))) ghcjsEventSpec_handler f (GhcjsEventSpec _ (GhcjsEventHandler b)) = phantom (f b) {-# INLINE ghcjsEventSpec_handler #-} #endif instance er ~ EventResult => Default (GhcjsEventSpec er) where def = GhcjsEventSpec { _ghcjsEventSpec_filters = mempty , _ghcjsEventSpec_handler = GhcjsEventHandler $ \(en, GhcjsDomEvent evt) -> do t :: DOM.EventTarget <- withIsEvent en $ Event.getTargetUnchecked evt --TODO: Rework this; defaultDomEventHandler shouldn't need to take this as an argument let e = uncheckedCastTo DOM.Element t runReaderT (defaultDomEventHandler e en) evt } {-# INLINE makeElement #-} makeElement :: MonadJSM m => Document -> Text -> ElementConfig er t s -> m DOM.Element makeElement doc elementTag cfg = do e <- uncheckedCastTo DOM.Element <$> case cfg ^. namespace of Nothing -> createElement doc elementTag Just ens -> createElementNS doc (Just ens) elementTag iforM_ (cfg ^. initialAttributes) $ \(AttributeName mAttrNamespace n) v -> case mAttrNamespace of Nothing -> setAttribute e n v Just ans -> setAttributeNS e (Just ans) n v pure e {-# INLINE elementImmediate #-} elementImmediate :: ( RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, EventSpec s ~ GhcjsEventSpec , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m ) => Text -> ElementConfig er t s -> HydrationDomBuilderT s t m a -> HydrationDomBuilderT s t m (Element er GhcjsDomSpace t, a) elementImmediate elementTag cfg child = do doc <- askDocument ctx <- askJSM events <- askEvents parent <- getParent e <- makeElement doc elementTag cfg appendChild_ parent e -- Run the child builder with updated parent and previous sibling references result <- localEnv (\env -> env { _hydrationDomBuilderEnv_parent = Left $ toNode e }) child let rawCfg = extractRawElementConfig cfg eventTriggerRefs <- wrap events e rawCfg es <- newFanEventWithTrigger $ triggerBody ctx rawCfg events eventTriggerRefs e return (Element es e, result) {-# SPECIALIZE elementImmediate :: Text -> ElementConfig er DomTimeline HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM a -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (Element er GhcjsDomSpace DomTimeline, a) #-} {-# SPECIALIZE elementImmediate :: Text -> ElementConfig er DomTimeline GhcjsDomSpace -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM a -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (Element er GhcjsDomSpace DomTimeline, a) #-} -- For specialisation -- | The Reflex timeline for interacting with the DOM type DomTimeline = #ifdef PROFILE_REFLEX ProfiledTimeline #endif Spider -- | The ReflexHost the DOM lives in type DomHost = #ifdef PROFILE_REFLEX ProfiledM #endif (SpiderHost Global) type DomCoreWidget x = PostBuildT DomTimeline (WithJSContextSingleton x (PerformEventT DomTimeline DomHost)) type HydrationM = DomCoreWidget () {-# INLINE elementInternal #-} elementInternal :: (MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m) => Text -> ElementConfig er t HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace t m a -> HydrationDomBuilderT HydrationDomSpace t m (Element er HydrationDomSpace t, a) elementInternal elementTag cfg child = getHydrationMode >>= \case HydrationMode_Immediate -> do (Element es _, result) <- elementImmediate elementTag cfg child return (Element es (), result) HydrationMode_Hydrating -> fst <$> hydrateElement elementTag cfg child {-# SPECIALIZE elementInternal :: Text -> ElementConfig er DomTimeline HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM a -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (Element er HydrationDomSpace DomTimeline, a) #-} -- | An attribute which causes hydration to skip over an element completely. skipHydrationAttribute :: IsString s => s skipHydrationAttribute = "data-hydration-skip" -- | An attribute which signals that an element should be hydrated. hydratableAttribute :: IsString s => s hydratableAttribute = "data-ssr" {-# INLINE hydrateElement #-} hydrateElement :: forall er t m a. (MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m) => Text -> ElementConfig er t HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace t m a -> HydrationDomBuilderT HydrationDomSpace t m ((Element er HydrationDomSpace t, a), IORef DOM.Element) hydrateElement elementTag cfg child = do ctx <- askJSM events <- askEvents -- Schedule everything for after postBuild, except for getting the result itself parentRef <- liftIO $ newIORef $ error "Parent not yet initialized" e' <- liftIO $ newIORef $ error "hydrateElement: Element not yet initialized" env <- HydrationDomBuilderT ask childDelayedRef <- liftIO $ newIORef $ pure () let env' = env { _hydrationDomBuilderEnv_parent = Right parentRef , _hydrationDomBuilderEnv_delayed = childDelayedRef } result <- HydrationDomBuilderT $ lift $ runReaderT (unHydrationDomBuilderT child) env' wrapResult <- liftIO newEmptyMVar let -- Determine if we should skip an element. We currently skip elements for -- two reasons: -- 1) it was not produced by a static builder which supports hydration -- 2) it is explicitly marked to be skipped shouldSkip :: DOM.Element -> HydrationRunnerT t m Bool shouldSkip e = do skip <- hasAttribute e (skipHydrationAttribute :: DOM.JSString) hydratable <- hasAttribute e (hydratableAttribute :: DOM.JSString) pure $ skip || not hydratable childDom <- liftIO $ readIORef childDelayedRef let rawCfg = extractRawElementConfig cfg doc <- askDocument addHydrationStep $ do parent <- askParent lastHydrationNode <- getPreviousNode let go mLastNode = maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case Nothing -> do -- ran out of nodes, create the element HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True } e <- makeElement doc elementTag cfg insertAfterPreviousNode e pure e Just node -> DOM.castTo DOM.Element node >>= \case Nothing -> go (Just node) -- this node is not an element, skip Just e -> shouldSkip e >>= \case True -> go (Just node) -- this element should be skipped by hydration False -> do t <- Element.getTagName e -- TODO: check attributes? if T.toCaseFold elementTag == T.toCaseFold t then pure e -- we came to some other statically rendered element, so something has gone wrong else do HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True } n <- makeElement doc elementTag cfg insertAfterPreviousNode n pure n e <- go lastHydrationNode setPreviousNode $ Just $ toNode e -- Update the parent node used by the children liftIO $ writeIORef parentRef $ toNode e liftIO $ writeIORef e' e -- Setup events, store the result so we can wait on it later refs <- wrap events e rawCfg liftIO $ putMVar wrapResult (e, refs) localRunner childDom Nothing $ toNode e -- We need the EventSelector to switch to the real event handler after activation es <- newFanEventWithTrigger $ \(WrapArg en) t -> do cleanup <- newEmptyMVar threadId <- forkIO $ do -- Wait on the data we need from the delayed action (e, eventTriggerRefs) <- readMVar wrapResult bracketOnError -- Run the setup, acquiring the cleanup action (triggerBody ctx rawCfg events eventTriggerRefs e (WrapArg en) t) -- Run the cleanup, if we have it - but only when an exception is -- raised (we might get killed between acquiring the cleanup action -- from 'triggerBody' and putting it in the MVar) id -- Try to put this action into the cleanup MVar (putMVar cleanup) pure $ do tryReadMVar cleanup >>= \case Nothing -> killThread threadId Just c -> c return ((Element es (), result), e') {-# SPECIALIZE hydrateElement :: Text -> ElementConfig er DomTimeline HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM a -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM ((Element er HydrationDomSpace DomTimeline, a), IORef DOM.Element) #-} {-# INLINE inputElementImmediate #-} inputElementImmediate :: ( RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, EventSpec s ~ GhcjsEventSpec , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m , MonadRef m, Ref m ~ IORef ) => InputElementConfig er t s -> HydrationDomBuilderT s t m (InputElement er GhcjsDomSpace t) inputElementImmediate cfg = do (e@(Element eventSelector domElement), ()) <- elementImmediate "input" (_inputElementConfig_elementConfig cfg) $ return () let domInputElement = uncheckedCastTo DOM.HTMLInputElement domElement Input.setValue domInputElement $ cfg ^. inputElementConfig_initialValue v0 <- Input.getValue domInputElement let getMyValue = Input.getValue domInputElement valueChangedByUI <- requestDomAction $ liftJSM getMyValue <$ Reflex.select eventSelector (WrapArg Input) valueChangedBySetValue <- case _inputElementConfig_setValue cfg of Nothing -> return never Just eSetValue -> requestDomAction $ ffor eSetValue $ \v' -> do Input.setValue domInputElement v' getMyValue -- We get the value after setting it in case the browser has mucked with it somehow v <- holdDyn v0 $ leftmost [ valueChangedBySetValue , valueChangedByUI ] Input.setChecked domInputElement $ _inputElementConfig_initialChecked cfg checkedChangedByUI <- wrapDomEvent domInputElement (`on` Events.click) $ do Input.getChecked domInputElement checkedChangedBySetChecked <- case _inputElementConfig_setChecked cfg of Nothing -> return never Just eNewchecked -> requestDomAction $ ffor eNewchecked $ \newChecked -> do oldChecked <- Input.getChecked domInputElement Input.setChecked domInputElement newChecked return $ if newChecked /= oldChecked then Just newChecked else Nothing c <- holdDyn (_inputElementConfig_initialChecked cfg) $ leftmost [ fmapMaybe id checkedChangedBySetChecked , checkedChangedByUI ] hasFocus <- mkHasFocus e files <- holdDyn mempty <=< wrapDomEvent domInputElement (`on` Events.change) $ do mfiles <- Input.getFiles domInputElement let getMyFiles xs = fmap catMaybes . mapM (FileList.item xs) . flip take [0..] . fromIntegral =<< FileList.getLength xs maybe (return []) getMyFiles mfiles checked <- holdUniqDyn c return $ InputElement { _inputElement_value = v , _inputElement_checked = checked , _inputElement_checkedChange = checkedChangedByUI , _inputElement_input = valueChangedByUI , _inputElement_hasFocus = hasFocus , _inputElement_element = e , _inputElement_raw = domInputElement , _inputElement_files = files } {-# INLINE inputElementInternal #-} inputElementInternal :: ( MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m , MonadRef m, Ref m ~ IORef ) => InputElementConfig er t HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace t m (InputElement er HydrationDomSpace t) inputElementInternal cfg = getHydrationMode >>= \case HydrationMode_Immediate -> ffor (inputElementImmediate cfg) $ \result -> result { _inputElement_element = Element (_element_events $ _inputElement_element result) () , _inputElement_raw = () } HydrationMode_Hydrating -> do ((e, _), domElementRef) <- hydrateElement "input" (cfg ^. inputElementConfig_elementConfig) $ return () (valueChangedByUI, triggerChangeByUI) <- newTriggerEvent (valueChangedBySetValue, triggerChangeBySetValue) <- newTriggerEvent (focusChange, triggerFocusChange) <- newTriggerEvent (checkedChangedByUI, triggerCheckedChangedByUI) <- newTriggerEvent (checkedChangedBySetChecked, triggerCheckedChangedBySetChecked) <- newTriggerEvent (fileChange, triggerFileChange) <- newTriggerEvent doc <- askDocument -- Expected initial value from config let v0 = _inputElementConfig_initialValue cfg c0 = _inputElementConfig_initialChecked cfg valuesAtSwitchover = do v <- maybe (pure $ pure v0) (hold v0) (_inputElementConfig_setValue cfg) c <- maybe (pure $ pure c0) (hold c0) (_inputElementConfig_setChecked cfg) pure (v, c) addHydrationStepWithSetup valuesAtSwitchover $ \(switchoverValue', switchoverChecked') -> do switchoverValue <- sample switchoverValue' switchoverChecked <- sample switchoverChecked' domElement <- liftIO $ readIORef domElementRef let domInputElement = uncheckedCastTo DOM.HTMLInputElement domElement getValue = Input.getValue domInputElement -- When the value has been updated by setValue before switchover, we must -- send an update here to remain in sync. This is because the later -- requestDomAction based on the setValue event will not capture events -- happening before postBuild, because this code runs after switchover. when (v0 /= switchoverValue) $ liftIO $ triggerChangeBySetValue switchoverValue -- The user could have altered the value before switchover. This must be -- triggered after the setValue one in order for the events to be in the -- correct order. liftJSM getValue >>= \realValue -> when (realValue /= switchoverValue) $ liftIO $ triggerChangeByUI realValue -- Watch for user interaction and trigger event accordingly requestDomAction_ $ (liftJSM getValue >>= liftIO . triggerChangeByUI) <$ Reflex.select (_element_events e) (WrapArg Input) for_ (_inputElementConfig_setValue cfg) $ \eSetValue -> requestDomAction_ $ ffor eSetValue $ \v' -> do Input.setValue domInputElement v' v <- getValue -- We get the value after setting it in case the browser has mucked with it somehow liftIO $ triggerChangeBySetValue v let focusChange' = leftmost [ False <$ Reflex.select (_element_events e) (WrapArg Blur) , True <$ Reflex.select (_element_events e) (WrapArg Focus) ] liftIO . triggerFocusChange =<< Node.isSameNode (toNode domElement) . fmap toNode =<< Document.getActiveElement doc requestDomAction_ $ liftIO . triggerFocusChange <$> focusChange' -- When the checked state has been updated by setChecked before -- switchover, we must send an update here to remain in sync. This is -- because the later requestDomAction based on the setChecked event will not -- capture events happening before postBuild, because this code runs after -- switchover. when (c0 /= switchoverChecked) $ liftIO $ triggerCheckedChangedBySetChecked switchoverChecked -- The user could have clicked the checkbox before switchover, we only -- detect cases where they flipped the state. This must be triggered after -- the setValue one in order for the events to be in the correct order. liftJSM (Input.getChecked domInputElement) >>= \realChecked -> when (realChecked /= switchoverChecked) $ liftIO $ triggerCheckedChangedByUI realChecked _ <- liftJSM $ domInputElement `on` Events.click $ do liftIO . triggerCheckedChangedByUI =<< Input.getChecked domInputElement for_ (_inputElementConfig_setChecked cfg) $ \eNewchecked -> requestDomAction $ ffor eNewchecked $ \newChecked -> do oldChecked <- Input.getChecked domInputElement Input.setChecked domInputElement newChecked when (newChecked /= oldChecked) $ liftIO $ triggerCheckedChangedBySetChecked newChecked _ <- liftJSM $ domInputElement `on` Events.change $ do mfiles <- Input.getFiles domInputElement let getMyFiles xs = fmap catMaybes . mapM (FileList.item xs) . flip take [0..] . fromIntegral =<< FileList.getLength xs liftIO . triggerFileChange =<< maybe (return []) getMyFiles mfiles return () checked' <- holdDyn c0 $ leftmost [ checkedChangedBySetChecked , checkedChangedByUI ] checked <- holdUniqDyn checked' let initialFocus = False -- Assume it isn't focused, but we update the actual focus state at switchover hasFocus <- holdUniqDyn =<< holdDyn initialFocus focusChange v <- holdDyn v0 $ leftmost [ valueChangedBySetValue , valueChangedByUI ] files <- holdDyn mempty fileChange return $ InputElement { _inputElement_value = v , _inputElement_checked = checked , _inputElement_checkedChange = checkedChangedByUI , _inputElement_input = valueChangedByUI , _inputElement_hasFocus = hasFocus , _inputElement_element = e , _inputElement_raw = () , _inputElement_files = files } {-# INLINE textAreaElementImmediate #-} textAreaElementImmediate :: ( RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, EventSpec s ~ GhcjsEventSpec , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m , MonadRef m, Ref m ~ IORef ) => TextAreaElementConfig er t s -> HydrationDomBuilderT s t m (TextAreaElement er GhcjsDomSpace t) textAreaElementImmediate cfg = do (e@(Element eventSelector domElement), _) <- elementImmediate "textarea" (cfg ^. textAreaElementConfig_elementConfig) $ return () let domTextAreaElement = uncheckedCastTo DOM.HTMLTextAreaElement domElement TextArea.setValue domTextAreaElement $ cfg ^. textAreaElementConfig_initialValue v0 <- TextArea.getValue domTextAreaElement let getMyValue = TextArea.getValue domTextAreaElement valueChangedByUI <- requestDomAction $ liftJSM getMyValue <$ Reflex.select eventSelector (WrapArg Input) valueChangedBySetValue <- case _textAreaElementConfig_setValue cfg of Nothing -> return never Just eSetValue -> requestDomAction $ ffor eSetValue $ \v' -> do TextArea.setValue domTextAreaElement v' getMyValue -- We get the value after setting it in case the browser has mucked with it somehow v <- holdDyn v0 $ leftmost [ valueChangedBySetValue , valueChangedByUI ] hasFocus <- mkHasFocus e return $ TextAreaElement { _textAreaElement_value = v , _textAreaElement_input = valueChangedByUI , _textAreaElement_hasFocus = hasFocus , _textAreaElement_element = e , _textAreaElement_raw = domTextAreaElement } {-# INLINE textAreaElementInternal #-} textAreaElementInternal :: ( MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m , MonadRef m, Ref m ~ IORef ) => TextAreaElementConfig er t HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace t m (TextAreaElement er HydrationDomSpace t) textAreaElementInternal cfg = getHydrationMode >>= \case HydrationMode_Immediate -> ffor (textAreaElementImmediate cfg) $ \result -> result { _textAreaElement_element = Element (_element_events $ _textAreaElement_element result) () , _textAreaElement_raw = () } HydrationMode_Hydrating -> do ((e, _), domElementRef) <- hydrateElement "textarea" (cfg ^. textAreaElementConfig_elementConfig) $ return () (valueChangedByUI, triggerChangeByUI) <- newTriggerEvent (valueChangedBySetValue, triggerChangeBySetValue) <- newTriggerEvent (focusChange, triggerFocusChange) <- newTriggerEvent doc <- askDocument -- Expected initial value from config let v0 = _textAreaElementConfig_initialValue cfg valueAtSwitchover = maybe (pure $ pure v0) (hold v0) (_textAreaElementConfig_setValue cfg) addHydrationStepWithSetup valueAtSwitchover $ \switchoverValue' -> do switchoverValue <- sample switchoverValue' domElement <- liftIO $ readIORef domElementRef let domTextAreaElement = uncheckedCastTo DOM.HTMLTextAreaElement domElement getValue = TextArea.getValue domTextAreaElement -- When the value has been updated by setValue before switchover, we must -- send an update here to remain in sync. This is because the later -- requestDomAction based on the setValue event will not capture events -- happening before postBuild, because this code runs after switchover. when (v0 /= switchoverValue) $ liftIO $ triggerChangeBySetValue switchoverValue -- The user could have altered the value before switchover. This must be -- triggered after the setValue one in order for the events to be in the -- correct order. liftJSM getValue >>= \realValue -> when (realValue /= switchoverValue) $ liftIO $ triggerChangeByUI realValue -- Watch for user interaction and trigger event accordingly requestDomAction_ $ (liftJSM getValue >>= liftIO . triggerChangeByUI) <$ Reflex.select (_element_events e) (WrapArg Input) for_ (_textAreaElementConfig_setValue cfg) $ \eSetValue -> requestDomAction_ $ ffor eSetValue $ \v' -> do TextArea.setValue domTextAreaElement v' v <- getValue -- We get the value after setting it in case the browser has mucked with it somehow liftIO $ triggerChangeBySetValue v let focusChange' = leftmost [ False <$ Reflex.select (_element_events e) (WrapArg Blur) , True <$ Reflex.select (_element_events e) (WrapArg Focus) ] liftIO . triggerFocusChange =<< Node.isSameNode (toNode domElement) . fmap toNode =<< Document.getActiveElement doc requestDomAction_ $ liftIO . triggerFocusChange <$> focusChange' let initialFocus = False -- Assume it isn't focused, but we update the actual focus state at switchover hasFocus <- holdUniqDyn =<< holdDyn initialFocus focusChange v <- holdDyn v0 $ leftmost [ valueChangedBySetValue , valueChangedByUI ] return $ TextAreaElement { _textAreaElement_value = v , _textAreaElement_input = valueChangedByUI , _textAreaElement_hasFocus = hasFocus , _textAreaElement_element = e , _textAreaElement_raw = () } {-# INLINE selectElementImmediate #-} selectElementImmediate :: ( EventSpec s ~ GhcjsEventSpec, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m ) => SelectElementConfig er t s -> HydrationDomBuilderT s t m a -> HydrationDomBuilderT s t m (SelectElement er GhcjsDomSpace t, a) selectElementImmediate cfg child = do (e@(Element eventSelector domElement), result) <- elementImmediate "select" (cfg ^. selectElementConfig_elementConfig) child let domSelectElement = uncheckedCastTo DOM.HTMLSelectElement domElement Select.setValue domSelectElement $ cfg ^. selectElementConfig_initialValue v0 <- Select.getValue domSelectElement let getMyValue = Select.getValue domSelectElement valueChangedByUI <- requestDomAction $ liftJSM getMyValue <$ Reflex.select eventSelector (WrapArg Change) valueChangedBySetValue <- case _selectElementConfig_setValue cfg of Nothing -> return never Just eSetValue -> requestDomAction $ ffor eSetValue $ \v' -> do Select.setValue domSelectElement v' getMyValue -- We get the value after setting it in case the browser has mucked with it somehow v <- holdDyn v0 $ leftmost [ valueChangedBySetValue , valueChangedByUI ] hasFocus <- mkHasFocus e let wrapped = SelectElement { _selectElement_value = v , _selectElement_change = valueChangedByUI , _selectElement_hasFocus = hasFocus , _selectElement_element = e , _selectElement_raw = domSelectElement } return (wrapped, result) {-# INLINE selectElementInternal #-} selectElementInternal :: ( MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m , MonadRef m, Ref m ~ IORef ) => SelectElementConfig er t HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace t m a -> HydrationDomBuilderT HydrationDomSpace t m (SelectElement er HydrationDomSpace t, a) selectElementInternal cfg child = getHydrationMode >>= \case HydrationMode_Immediate -> ffor (selectElementImmediate cfg child) $ \(e, result) -> (e { _selectElement_element = Element (_element_events $ _selectElement_element e) () , _selectElement_raw = () }, result) HydrationMode_Hydrating -> do ((e, result), domElementRef) <- hydrateElement "select" (cfg ^. selectElementConfig_elementConfig) child (valueChangedByUI, triggerChangeByUI) <- newTriggerEvent (valueChangedBySetValue, triggerChangeBySetValue) <- newTriggerEvent (focusChange, triggerFocusChange) <- newTriggerEvent doc <- askDocument -- Expected initial value from config let v0 = _selectElementConfig_initialValue cfg addHydrationStep $ do domElement <- liftIO $ readIORef domElementRef let domSelectElement = uncheckedCastTo DOM.HTMLSelectElement domElement getValue = Select.getValue domSelectElement -- The browser might have messed with the value, or the user could have -- altered it before activation, so we set it if it isn't what we expect liftJSM getValue >>= \v0' -> do when (v0' /= v0) $ liftIO $ triggerChangeByUI v0' -- Watch for user interaction and trigger event accordingly requestDomAction_ $ (liftJSM getValue >>= liftIO . triggerChangeByUI) <$ Reflex.select (_element_events e) (WrapArg Change) for_ (_selectElementConfig_setValue cfg) $ \eSetValue -> requestDomAction_ $ ffor eSetValue $ \v' -> do Select.setValue domSelectElement v' v <- getValue -- We get the value after setting it in case the browser has mucked with it somehow liftIO $ triggerChangeBySetValue v let focusChange' = leftmost [ False <$ Reflex.select (_element_events e) (WrapArg Blur) , True <$ Reflex.select (_element_events e) (WrapArg Focus) ] liftIO . triggerFocusChange =<< Node.isSameNode (toNode domElement) . fmap toNode =<< Document.getActiveElement doc requestDomAction_ $ liftIO . triggerFocusChange <$> focusChange' let initialFocus = False -- Assume it isn't focused, but we update the actual focus state at switchover hasFocus <- holdUniqDyn =<< holdDyn initialFocus focusChange v <- holdDyn v0 $ leftmost [ valueChangedBySetValue , valueChangedByUI ] return $ (,result) $ SelectElement { _selectElement_value = v , _selectElement_change = valueChangedByUI , _selectElement_hasFocus = hasFocus , _selectElement_element = e , _selectElement_raw = () } {-# INLINE textNodeImmediate #-} textNodeImmediate :: (RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, MonadJSM m, Reflex t, MonadFix m) => TextNodeConfig t -> HydrationDomBuilderT s t m DOM.Text textNodeImmediate (TextNodeConfig !t mSetContents) = do p <- getParent doc <- askDocument n <- createTextNode doc t appendChild_ p n mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents pure n {-# SPECIALIZE textNodeImmediate :: TextNodeConfig DomTimeline -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM DOM.Text #-} {-# SPECIALIZE textNodeImmediate :: TextNodeConfig DomTimeline -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM DOM.Text #-} {-# INLINE textNodeInternal #-} textNodeInternal :: (Adjustable t m, MonadHold t m, MonadJSM m, MonadFix m, Reflex t) => TextNodeConfig t -> HydrationDomBuilderT HydrationDomSpace t m (TextNode HydrationDomSpace t) textNodeInternal tc@(TextNodeConfig !t mSetContents) = do doc <- askDocument getHydrationMode >>= \case HydrationMode_Immediate -> void $ textNodeImmediate tc HydrationMode_Hydrating -> addHydrationStepWithSetup (maybe (pure $ pure t) (hold t) mSetContents) $ \currentText -> do n <- hydrateTextNode doc =<< sample currentText mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents pure $ TextNode () {-# SPECIALIZE textNodeInternal :: TextNodeConfig DomTimeline -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (TextNode HydrationDomSpace DomTimeline) #-} -- | The static builder mashes adjacent text nodes into one node: we check the -- text content of each node we come to, comparing it to the content we -- expect. We also have a special case for empty text nodes - we always create -- the and add them after the previous node reference. {-# INLINE hydrateTextNode #-} hydrateTextNode :: MonadJSM m => Document -> Text -> HydrationRunnerT t m DOM.Text hydrateTextNode doc t@"" = do tn <- createTextNode doc t insertAfterPreviousNode tn pure tn hydrateTextNode doc t = do n <- join $ go <$> askParent <*> getPreviousNode setPreviousNode $ Just $ toNode n return n where go parent mLastNode = maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case Nothing -> do HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True } n <- createTextNode doc t insertAfterPreviousNode n pure n Just node -> DOM.castTo DOM.Text node >>= \case Nothing -> go parent $ Just node Just originalNode -> do originalText <- Node.getTextContentUnchecked originalNode case T.stripPrefix t originalText of Just "" -> return originalNode Just _ -> do -- If we have the right prefix, we split the text node into a node containing the -- required text and a subsequent sibling node containing the rest of the text. DOM.splitText_ originalNode $ fromIntegral $ T.length t return originalNode Nothing -> do HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True } n <- createTextNode doc t insertAfterPreviousNode n pure n {-# INLINE commentNodeImmediate #-} commentNodeImmediate :: (RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, MonadJSM m, Reflex t, MonadFix m) => CommentNodeConfig t -> HydrationDomBuilderT s t m DOM.Comment commentNodeImmediate (CommentNodeConfig !t mSetContents) = do p <- getParent doc <- askDocument n <- createComment doc t appendChild_ p n mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents pure n {-# INLINE commentNodeInternal #-} commentNodeInternal :: (Ref m ~ IORef, MonadRef m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadJSM (Performable m), MonadJSM m, MonadFix m, Reflex t, Adjustable t m, MonadHold t m, MonadSample t m) => CommentNodeConfig t -> HydrationDomBuilderT HydrationDomSpace t m (CommentNode HydrationDomSpace t) commentNodeInternal tc@(CommentNodeConfig t0 mSetContents) = do doc <- askDocument getHydrationMode >>= \case HydrationMode_Immediate -> void $ commentNodeInternal tc HydrationMode_Hydrating -> addHydrationStepWithSetup (maybe (pure $ pure t0) (hold t0) mSetContents) $ \bt -> do t <- sample bt void $ hydrateComment doc t mSetContents pure $ CommentNode () {-# INLINE hydrateComment #-} hydrateComment :: (MonadJSM m, Reflex t, MonadFix m) => Document -> Text -> Maybe (Event t Text) -> HydrationRunnerT t m DOM.Comment hydrateComment doc t mSetContents = do parent <- askParent let go mLastNode = maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case Nothing -> do c <- createComment doc t insertAfterPreviousNode c pure c Just node -> DOM.castTo DOM.Comment node >>= \case Nothing -> go (Just node) Just c -> do t' <- Node.getTextContentUnchecked c if t == t' then pure c else do c' <- createComment doc t insertAfterPreviousNode c' pure c' n <- go =<< getPreviousNode setPreviousNode $ Just $ toNode n mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents pure n -- | We leave markers in the static builder as comments, and rip these comments -- out at hydration time, replacing them with empty text nodes. {-# INLINABLE skipToAndReplaceComment #-} skipToAndReplaceComment :: (MonadJSM m, Reflex t, MonadFix m, Adjustable t m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => Text -> IORef (Maybe Text) -> HydrationDomBuilderT s t m (HydrationRunnerT t m (), IORef DOM.Text, IORef (Maybe Text)) skipToAndReplaceComment prefix key0Ref = getHydrationMode >>= \case HydrationMode_Immediate -> do -- If we're in immediate mode, we don't try to replace an existing comment, -- and just return a dummy key t <- textNodeImmediate $ TextNodeConfig ("" :: Text) Nothing append $ toNode t textNodeRef <- liftIO $ newIORef t keyRef <- liftIO $ newIORef Nothing pure (pure (), textNodeRef, keyRef) HydrationMode_Hydrating -> do doc <- askDocument textNodeRef <- liftIO $ newIORef $ error "textNodeRef not yet initialized" keyRef <- liftIO $ newIORef $ error "keyRef not yet initialized" let go Nothing _ = do tn <- createTextNode doc ("" :: Text) insertAfterPreviousNode tn HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True } pure (tn, Nothing) go (Just key0) mLastNode = do parent <- askParent maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case Nothing -> go Nothing Nothing Just node -> DOM.castTo DOM.Comment node >>= \case Just comment -> do commentText <- fromMaybe (error "Cannot get text content of comment node") <$> Node.getTextContent comment case T.stripPrefix (prefix <> key0) commentText of -- 'key0' may be @""@ in which case we're just finding the actual key; TODO: Don't be clever. Just key -> do -- Replace the comment with an (invisible) text node tn <- createTextNode doc ("" :: Text) Node.replaceChild_ parent tn comment pure (tn, Just key) Nothing -> do go (Just key0) (Just node) Nothing -> do go (Just key0) (Just node) switchComment = do key0 <- liftIO $ readIORef key0Ref (tn, key) <- go key0 =<< getPreviousNode setPreviousNode $ Just $ toNode tn liftIO $ do writeIORef textNodeRef tn writeIORef keyRef key pure (switchComment, textNodeRef, keyRef) {-# INLINABLE skipToReplaceStart #-} skipToReplaceStart :: (MonadJSM m, Reflex t, MonadFix m, Adjustable t m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => HydrationDomBuilderT s t m (HydrationRunnerT t m (), IORef DOM.Text, IORef (Maybe Text)) skipToReplaceStart = skipToAndReplaceComment "replace-start" =<< liftIO (newIORef $ Just "") -- TODO: Don't rely on clever usage @""@ to make this work. {-# INLINABLE skipToReplaceEnd #-} skipToReplaceEnd :: (MonadJSM m, Reflex t, MonadFix m, Adjustable t m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => IORef (Maybe Text) -> HydrationDomBuilderT s t m (HydrationRunnerT t m (), IORef DOM.Text) skipToReplaceEnd key = fmap (\(m,e,_) -> (m,e)) $ skipToAndReplaceComment "replace-end" key instance SupportsHydrationDomBuilder t m => NotReady t (HydrationDomBuilderT s t m) where notReadyUntil e = do eOnce <- headE e unreadyChildren <- askUnreadyChildren commitAction <- askCommitAction liftIO $ modifyIORef' unreadyChildren succ let ready = do old <- liftIO $ readIORef unreadyChildren let new = pred old liftIO $ writeIORef unreadyChildren $! new when (new == 0) commitAction requestDomAction_ $ ready <$ eOnce notReady = do unreadyChildren <- askUnreadyChildren liftIO $ modifyIORef' unreadyChildren succ data HydrationDomSpace instance DomSpace HydrationDomSpace where type EventSpec HydrationDomSpace = GhcjsEventSpec type RawDocument HydrationDomSpace = DOM.Document type RawTextNode HydrationDomSpace = () type RawCommentNode HydrationDomSpace = () type RawElement HydrationDomSpace = () type RawInputElement HydrationDomSpace = () type RawTextAreaElement HydrationDomSpace = () type RawSelectElement HydrationDomSpace = () addEventSpecFlags _ en f es = es { _ghcjsEventSpec_filters = let f' = Just . GhcjsEventFilter . \case Nothing -> \evt -> do mEventResult <- unGhcjsEventHandler (_ghcjsEventSpec_handler es) (en, evt) return (f mEventResult, return mEventResult) Just (GhcjsEventFilter oldFilter) -> \evt -> do (oldFlags, oldContinuation) <- oldFilter evt mEventResult <- oldContinuation let newFlags = oldFlags <> f mEventResult return (newFlags, return mEventResult) in DMap.alter f' en $ _ghcjsEventSpec_filters es } instance SupportsHydrationDomBuilder t m => DomBuilder t (HydrationDomBuilderT HydrationDomSpace t m) where type DomBuilderSpace (HydrationDomBuilderT HydrationDomSpace t m) = HydrationDomSpace {-# INLINABLE element #-} element = elementInternal {-# INLINABLE textNode #-} textNode = textNodeInternal {-# INLINABLE commentNode #-} commentNode = commentNodeInternal {-# INLINABLE inputElement #-} inputElement = inputElementInternal {-# INLINABLE textAreaElement #-} textAreaElement = textAreaElementInternal {-# INLINABLE selectElement #-} selectElement = selectElementInternal placeRawElement () = pure () wrapRawElement () _cfg = pure $ Element (EventSelector $ const never) () instance SupportsHydrationDomBuilder t m => DomBuilder t (HydrationDomBuilderT GhcjsDomSpace t m) where type DomBuilderSpace (HydrationDomBuilderT GhcjsDomSpace t m) = GhcjsDomSpace {-# INLINABLE element #-} element = elementImmediate {-# INLINABLE textNode #-} textNode = fmap TextNode . textNodeImmediate {-# INLINABLE commentNode #-} commentNode = fmap CommentNode . commentNodeImmediate {-# INLINABLE inputElement #-} inputElement = inputElementImmediate {-# INLINABLE textAreaElement #-} textAreaElement = textAreaElementImmediate {-# INLINABLE selectElement #-} selectElement = selectElementImmediate placeRawElement = append . toNode wrapRawElement e rawCfg = do events <- askEvents ctx <- askJSM eventTriggerRefs <- wrap events e rawCfg es <- newFanEventWithTrigger $ triggerBody ctx rawCfg events eventTriggerRefs e pure $ Element es e data FragmentState = FragmentState_Unmounted | FragmentState_Mounted (DOM.Text, DOM.Text) data ImmediateDomFragment = ImmediateDomFragment { _immediateDomFragment_document :: DOM.DocumentFragment , _immediateDomFragment_state :: IORef FragmentState } extractFragment :: MonadJSM m => ImmediateDomFragment -> m () extractFragment fragment = do state <- liftIO $ readIORef $ _immediateDomFragment_state fragment case state of FragmentState_Unmounted -> return () FragmentState_Mounted (before, after) -> do extractBetweenExclusive (_immediateDomFragment_document fragment) before after liftIO $ writeIORef (_immediateDomFragment_state fragment) FragmentState_Unmounted instance SupportsHydrationDomBuilder t m => MountableDomBuilder t (HydrationDomBuilderT GhcjsDomSpace t m) where type DomFragment (HydrationDomBuilderT GhcjsDomSpace t m) = ImmediateDomFragment buildDomFragment w = do df <- createDocumentFragment =<< askDocument result <- flip localEnv w $ \env -> env { _hydrationDomBuilderEnv_parent = Left $ toNode df } state <- liftIO $ newIORef FragmentState_Unmounted return (ImmediateDomFragment df state, result) mountDomFragment fragment setFragment = do parent <- getParent extractFragment fragment before <- textNodeImmediate $ TextNodeConfig ("" :: Text) Nothing appendChild_ parent $ _immediateDomFragment_document fragment after <- textNodeImmediate $ TextNodeConfig ("" :: Text) Nothing xs <- foldDyn (\new (previous, _) -> (new, Just previous)) (fragment, Nothing) setFragment requestDomAction_ $ ffor (updated xs) $ \(childFragment, Just previousFragment) -> do extractFragment previousFragment extractFragment childFragment insertBefore (_immediateDomFragment_document childFragment) after liftIO $ writeIORef (_immediateDomFragment_state childFragment) $ FragmentState_Mounted (before, after) liftIO $ writeIORef (_immediateDomFragment_state fragment) $ FragmentState_Mounted (before, after) instance (Reflex t, Monad m, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (DomRenderHookT t m) where runWithReplace a0 a' = DomRenderHookT $ runWithReplace (unDomRenderHookT a0) (fmapCheap unDomRenderHookT a') traverseIntMapWithKeyWithAdjust f m = DomRenderHookT . traverseIntMapWithKeyWithAdjust (\k -> unDomRenderHookT . f k) m traverseDMapWithKeyWithAdjust f m = DomRenderHookT . traverseDMapWithKeyWithAdjust (\k -> unDomRenderHookT . f k) m traverseDMapWithKeyWithAdjustWithMove f m = DomRenderHookT . traverseDMapWithKeyWithAdjustWithMove (\k -> unDomRenderHookT . f k) m instance (Adjustable t m, MonadJSM m, MonadHold t m, MonadFix m, PrimMonad m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => Adjustable t (HydrationDomBuilderT s t m) where {-# INLINABLE runWithReplace #-} runWithReplace a0 a' = do initialEnv <- HydrationDomBuilderT ask let hydrating = _hydrationDomBuilderEnv_hydrationMode initialEnv (hydrateStart, before, beforeKey) <- skipToReplaceStart let parentUnreadyChildren = _hydrationDomBuilderEnv_unreadyChildren initialEnv haveEverBeenReady <- liftIO $ newIORef False currentCohort <- liftIO $ newIORef (-1 :: Int) -- Equal to the cohort currently in the DOM let myCommitAction = do liftIO (readIORef haveEverBeenReady) >>= \case True -> return () False -> do liftIO $ writeIORef haveEverBeenReady True old <- liftIO $ readIORef parentUnreadyChildren let new = pred old liftIO $ writeIORef parentUnreadyChildren $! new when (new == 0) $ _hydrationDomBuilderEnv_commitAction initialEnv -- We draw 'after' in this roundabout way to avoid using MonadFix doc <- askDocument parent <- getParent (hydrateEnd, after) <- skipToReplaceEnd beforeKey let drawInitialChild = do h <- liftIO $ readIORef hydrating p' <- case h of HydrationMode_Hydrating -> pure parent HydrationMode_Immediate -> toNode <$> createDocumentFragment doc unreadyChildren <- liftIO $ newIORef 0 let a0' = case h of HydrationMode_Hydrating -> a0 HydrationMode_Immediate -> do a <- a0 insertBefore p' =<< liftIO (readIORef after) pure a delayed <- case h of HydrationMode_Hydrating -> liftIO $ newIORef $ pure () HydrationMode_Immediate -> pure $ _hydrationDomBuilderEnv_delayed initialEnv result <- runReaderT (unHydrationDomBuilderT a0') initialEnv { _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren , _hydrationDomBuilderEnv_commitAction = myCommitAction , _hydrationDomBuilderEnv_parent = Left p' , _hydrationDomBuilderEnv_delayed = delayed } dom <- case h of HydrationMode_Hydrating -> liftIO $ readIORef delayed HydrationMode_Immediate -> pure $ pure () liftIO $ readIORef unreadyChildren >>= \case 0 -> writeIORef haveEverBeenReady True _ -> modifyIORef' parentUnreadyChildren succ return (dom, result) a'' <- numberOccurrences a' ((hydrate0, result0), child') <- HydrationDomBuilderT $ lift $ runWithReplace drawInitialChild $ ffor a'' $ \(cohortId, child) -> do h <- liftIO $ readIORef hydrating p' <- case h of HydrationMode_Hydrating -> pure parent HydrationMode_Immediate -> toNode <$> createDocumentFragment doc unreadyChildren <- liftIO $ newIORef 0 let commitAction = do c <- liftIO $ readIORef currentCohort when (c <= cohortId) $ do -- If a newer cohort has already been committed, just ignore this !before' <- liftIO $ readIORef before !after' <- liftIO $ readIORef after deleteBetweenExclusive before' after' insertBefore p' after' liftIO $ writeIORef currentCohort cohortId myCommitAction delayed <- case h of HydrationMode_Hydrating -> liftIO $ newIORef $ pure () HydrationMode_Immediate -> pure $ _hydrationDomBuilderEnv_delayed initialEnv result <- runReaderT (unHydrationDomBuilderT child) $ initialEnv { _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren , _hydrationDomBuilderEnv_commitAction = case h of HydrationMode_Hydrating -> myCommitAction HydrationMode_Immediate -> commitAction , _hydrationDomBuilderEnv_parent = Left p' , _hydrationDomBuilderEnv_delayed = delayed } dom <- case h of HydrationMode_Hydrating -> liftIO $ readIORef delayed HydrationMode_Immediate -> pure $ pure () uc <- liftIO $ readIORef unreadyChildren let commitActionToRunNow = if uc == 0 then Just $ commitAction else Nothing -- A child will run it when unreadyChildren is decremented to 0 actions = case h of HydrationMode_Hydrating -> Left dom HydrationMode_Immediate -> Right commitActionToRunNow return (actions, result) let (hydrate', commitAction) = fanEither $ fmap fst child' addHydrationStepWithSetup (hold hydrate0 hydrate') $ \contents -> do hydrateStart join $ sample contents hydrateEnd requestDomAction_ $ fmapMaybe id commitAction return (result0, snd <$> child') {-# INLINABLE traverseIntMapWithKeyWithAdjust #-} traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjust' {-# INLINABLE traverseDMapWithKeyWithAdjust #-} traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjust' {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-} traverseDMapWithKeyWithAdjustWithMove = do let updateChildUnreadiness (p :: PatchDMapWithMove k (Compose (TraverseChild t m (Some k)) v')) old = do let new :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Compose (TraverseChild t m (Some k)) v') a -> IO (PatchDMapWithMove.NodeInfo k (Constant (IORef (ChildReadyState (Some k)))) a) new k = PatchDMapWithMove.nodeInfoMapFromM $ \case PatchDMapWithMove.From_Insert (Compose (TraverseChild (Left _hydration) _)) -> return PatchDMapWithMove.From_Delete PatchDMapWithMove.From_Insert (Compose (TraverseChild (Right immediate) _)) -> do readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case ChildReadyState_Ready -> return PatchDMapWithMove.From_Delete ChildReadyState_Unready _ -> do writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just $ Some k return $ PatchDMapWithMove.From_Insert $ Constant (_traverseChildImmediate_childReadyState immediate) PatchDMapWithMove.From_Delete -> return PatchDMapWithMove.From_Delete PatchDMapWithMove.From_Move fromKey -> return $ PatchDMapWithMove.From_Move fromKey deleteOrMove :: forall a. k a -> Product (Constant (IORef (ChildReadyState (Some k)))) (ComposeMaybe k) a -> IO (Constant () a) deleteOrMove _ (Pair (Constant sRef) (ComposeMaybe mToKey)) = do writeIORef sRef $ ChildReadyState_Unready $ Some <$> mToKey -- This will be Nothing if deleting, and Just if moving, so it works out in both cases return $ Constant () p' <- fmap unsafePatchDMapWithMove $ DMap.traverseWithKey new $ unPatchDMapWithMove p _ <- DMap.traverseWithKey deleteOrMove $ PatchDMapWithMove.getDeletionsAndMoves p old return $ applyAlways p' old hoistTraverseWithKeyWithAdjust traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove updateChildUnreadiness $ \placeholders lastPlaceholder (p_ :: PatchDMapWithMove k (Compose (TraverseChild t m (Some k)) v')) -> do let p = unPatchDMapWithMove p_ phsBefore <- liftIO $ readIORef placeholders let collectIfMoved :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Compose (TraverseChild t m (Some k)) v') a -> JSM (Constant (Maybe DOM.DocumentFragment) a) collectIfMoved k e = do let mThisPlaceholder = Map.lookup (Some k) phsBefore -- Will be Nothing if this element wasn't present before nextPlaceholder = maybe lastPlaceholder snd $ Map.lookupGT (Some k) phsBefore case isJust $ getComposeMaybe $ PatchDMapWithMove._nodeInfo_to e of False -> do mapM_ (`deleteUpTo` nextPlaceholder) mThisPlaceholder return $ Constant Nothing True -> do Constant <$> mapM (`collectUpTo` nextPlaceholder) mThisPlaceholder collected <- DMap.traverseWithKey collectIfMoved p let !phsAfter = fromMaybe phsBefore $ apply filtered phsBefore weakened :: PatchMapWithMove (Some k) (Either (TraverseChildHydration t m) (TraverseChildImmediate (Some k))) weakened = weakenPatchDMapWithMoveWith (_traverseChild_mode . getCompose) p_ filtered :: PatchMapWithMove (Some k) DOM.Text filtered = PatchMapWithMove $ flip Map.mapMaybe (unPatchMapWithMove weakened) $ \(PatchMapWithMove.NodeInfo from to) -> flip PatchMapWithMove.NodeInfo to <$> case from of PatchMapWithMove.From_Insert (Left _hydration) -> Nothing PatchMapWithMove.From_Insert (Right immediate) -> Just $ PatchMapWithMove.From_Insert $ _traverseChildImmediate_placeholder immediate PatchMapWithMove.From_Delete -> Just $ PatchMapWithMove.From_Delete PatchMapWithMove.From_Move k -> Just $ PatchMapWithMove.From_Move k let placeFragment :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Compose (TraverseChild t m (Some k)) v') a -> JSM (Constant () a) placeFragment k e = do let nextPlaceholder = maybe lastPlaceholder snd $ Map.lookupGT (Some k) phsAfter case PatchDMapWithMove._nodeInfo_from e of PatchDMapWithMove.From_Insert (Compose (TraverseChild x _)) -> case x of Left _ -> pure () Right immediate -> _traverseChildImmediate_fragment immediate `insertBefore` nextPlaceholder PatchDMapWithMove.From_Delete -> do return () PatchDMapWithMove.From_Move fromKey -> do Just (Constant mdf) <- return $ DMap.lookup fromKey collected mapM_ (`insertBefore` nextPlaceholder) mdf return $ Constant () mapM_ (\(k :=> v) -> void $ placeFragment k v) $ DMap.toDescList p -- We need to go in reverse order here, to make sure the placeholders are in the right spot at the right time liftIO $ writeIORef placeholders $! phsAfter {-# INLINABLE traverseDMapWithKeyWithAdjust' #-} traverseDMapWithKeyWithAdjust' :: forall s t m (k :: * -> *) v v'. (Adjustable t m, MonadHold t m, MonadFix m, MonadJSM m, PrimMonad m, GCompare k, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => (forall a. k a -> v a -> HydrationDomBuilderT s t m (v' a)) -> DMap k v -> Event t (PatchDMap k v) -> HydrationDomBuilderT s t m (DMap k v', Event t (PatchDMap k v')) traverseDMapWithKeyWithAdjust' = do let updateChildUnreadiness (p :: PatchDMap k (Compose (TraverseChild t m (Some k)) v')) old = do let new :: forall a. k a -> ComposeMaybe (Compose (TraverseChild t m (Some k)) v') a -> IO (ComposeMaybe (Constant (IORef (ChildReadyState (Some k)))) a) new k (ComposeMaybe m) = ComposeMaybe <$> case m of Nothing -> return Nothing Just (Compose (TraverseChild (Left _hydration) _)) -> pure Nothing Just (Compose (TraverseChild (Right immediate) _)) -> do readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case ChildReadyState_Ready -> return Nothing -- Delete this child, since it's ready ChildReadyState_Unready _ -> do writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just $ Some k return $ Just $ Constant (_traverseChildImmediate_childReadyState immediate) delete _ (Constant sRef) = do writeIORef sRef $ ChildReadyState_Unready Nothing return $ Constant () p' <- fmap PatchDMap $ DMap.traverseWithKey new $ unPatchDMap p _ <- DMap.traverseWithKey delete $ PatchDMap.getDeletions p old return $ applyAlways p' old hoistTraverseWithKeyWithAdjust traverseDMapWithKeyWithAdjust mapPatchDMap updateChildUnreadiness $ \placeholders lastPlaceholder (PatchDMap patch) -> do phs <- liftIO $ readIORef placeholders forM_ (DMap.toList patch) $ \(k :=> ComposeMaybe mv) -> do let nextPlaceholder = maybe lastPlaceholder snd $ Map.lookupGT (Some k) phs -- Delete old node forM_ (Map.lookup (Some k) phs) $ \thisPlaceholder -> do thisPlaceholder `deleteUpTo` nextPlaceholder -- Insert new node forM_ mv $ \(Compose (TraverseChild e _)) -> case e of Left _hydration -> pure () Right immediate -> do _traverseChildImmediate_fragment immediate `insertBefore` nextPlaceholder let weakened :: PatchMap (Some k) (Either (TraverseChildHydration t m) (TraverseChildImmediate (Some k))) weakened = weakenPatchDMapWith (_traverseChild_mode . getCompose) $ PatchDMap patch filtered :: PatchMap (Some k) DOM.Text filtered = PatchMap $ flip Map.mapMaybe (unPatchMap weakened) $ \case Nothing -> Just Nothing -- deletion Just (Left _) -> Nothing Just (Right immediate) -> Just $ Just $ _traverseChildImmediate_placeholder immediate liftIO $ writeIORef placeholders $! fromMaybe phs $ apply filtered phs {-# INLINABLE traverseIntMapWithKeyWithAdjust' #-} traverseIntMapWithKeyWithAdjust' :: forall s t m v v'. (Adjustable t m, MonadJSM m, MonadFix m, PrimMonad m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => (IntMap.Key -> v -> HydrationDomBuilderT s t m v') -> IntMap v -> Event t (PatchIntMap v) -> HydrationDomBuilderT s t m (IntMap v', Event t (PatchIntMap v')) traverseIntMapWithKeyWithAdjust' = do let updateChildUnreadiness (p@(PatchIntMap pInner) :: PatchIntMap (TraverseChild t m Int v')) old = do let new :: IntMap.Key -> Maybe (TraverseChild t m Int v') -> IO (Maybe (IORef (ChildReadyState Int))) new k m = case m of Nothing -> return Nothing Just (TraverseChild (Left _hydration) _) -> pure Nothing Just (TraverseChild (Right immediate) _) -> do let sRef = _traverseChildImmediate_childReadyState immediate readIORef sRef >>= \case ChildReadyState_Ready -> return Nothing -- Delete this child, since it's ready ChildReadyState_Unready _ -> do writeIORef sRef $ ChildReadyState_Unready $ Just k return $ Just sRef delete _ sRef = do writeIORef sRef $ ChildReadyState_Unready Nothing return () p' <- PatchIntMap <$> IntMap.traverseWithKey new pInner _ <- IntMap.traverseWithKey delete $ FastMutableIntMap.getDeletions p old return $ applyAlways p' old hoistTraverseIntMapWithKeyWithAdjust traverseIntMapWithKeyWithAdjust updateChildUnreadiness $ \placeholders lastPlaceholder (PatchIntMap p) -> do phs <- liftIO $ readIORef placeholders forM_ (IntMap.toList p) $ \(k, mv) -> do let nextPlaceholder = maybe lastPlaceholder snd $ IntMap.lookupGT k phs -- Delete old node forM_ (IntMap.lookup k phs) $ \thisPlaceholder -> thisPlaceholder `deleteUpTo` nextPlaceholder -- Insert new node forM_ mv $ \(TraverseChild e _) -> case e of Left _hydration -> pure () Right immediate -> do _traverseChildImmediate_fragment immediate `insertBefore` nextPlaceholder let filtered :: PatchIntMap DOM.Text filtered = PatchIntMap $ flip IntMap.mapMaybe p $ \case Nothing -> Just Nothing -- deletion Just tc | Right immediate <- _traverseChild_mode tc -> Just $ Just $ _traverseChildImmediate_placeholder immediate | otherwise -> Nothing liftIO $ writeIORef placeholders $! fromMaybe phs $ apply filtered phs {-# SPECIALIZE traverseIntMapWithKeyWithAdjust' :: (IntMap.Key -> v -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM v') -> IntMap v -> Event DomTimeline (PatchIntMap v) -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v')) #-} {-# SPECIALIZE traverseIntMapWithKeyWithAdjust' :: (IntMap.Key -> v -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM v') -> IntMap v -> Event DomTimeline (PatchIntMap v) -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v')) #-} data ChildReadyState a = ChildReadyState_Ready | ChildReadyState_Unready !(Maybe a) deriving (Show, Read, Eq, Ord) insertAfterPreviousNode :: (Monad m, MonadJSM m) => DOM.IsNode node => node -> HydrationRunnerT t m () insertAfterPreviousNode node = do parent <- askParent nextNode <- maybe (Node.getFirstChild parent) Node.getNextSibling =<< getPreviousNode Node.insertBefore_ parent node nextNode setPreviousNode $ Just $ toNode node {-# INLINABLE hoistTraverseWithKeyWithAdjust #-} hoistTraverseWithKeyWithAdjust :: ( Adjustable t m , MonadHold t m , GCompare k , MonadIO m , MonadJSM m , PrimMonad m , MonadFix m , Patch (p k v) , Patch (p k (Constant Int)) , PatchTarget (p k (Constant Int)) ~ DMap k (Constant Int) , Patch (p k (Compose (TraverseChild t m (Some k)) v')) , PatchTarget (p k (Compose (TraverseChild t m (Some k)) v')) ~ DMap k (Compose (TraverseChild t m (Some k)) v') , Monoid (p k (Compose (TraverseChild t m (Some k)) v')) , RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document ) => (forall vv vv'. (forall a. k a -> vv a -> DomRenderHookT t m (vv' a)) -> DMap k vv -> Event t (p k vv) -> DomRenderHookT t m (DMap k vv', Event t (p k vv'))) -- ^ The base monad's traversal -> (forall vv vv'. (forall a. vv a -> vv' a) -> p k vv -> p k vv') -- ^ A way of mapping over the patch type -> (p k (Compose (TraverseChild t m (Some k)) v') -> DMap k (Constant (IORef (ChildReadyState (Some k)))) -> IO (DMap k (Constant (IORef (ChildReadyState (Some k)))))) -- ^ Given a patch for the children DOM elements, produce a patch for the childrens' unreadiness state -> (IORef (Map.Map (Some k) DOM.Text) -> DOM.Text -> p k (Compose (TraverseChild t m (Some k)) v') -> JSM ()) -- ^ Apply a patch to the DOM -> (forall a. k a -> v a -> HydrationDomBuilderT s t m (v' a)) -> DMap k v -> Event t (p k v) -> HydrationDomBuilderT s t m (DMap k v', Event t (p k v')) hoistTraverseWithKeyWithAdjust base mapPatch updateChildUnreadiness applyDomUpdate_ f dm0 dm' = do doc <- askDocument initialEnv <- HydrationDomBuilderT ask let parentUnreadyChildren = _hydrationDomBuilderEnv_unreadyChildren initialEnv pendingChange :: IORef (DMap k (Constant (IORef (ChildReadyState (Some k)))), p k (Compose (TraverseChild t m (Some k)) v')) <- liftIO $ newIORef mempty haveEverBeenReady <- liftIO $ newIORef False placeholders <- liftIO $ newIORef Map.empty lastPlaceholder <- createTextNode doc ("" :: Text) let applyDomUpdate p = do applyDomUpdate_ placeholders lastPlaceholder p markSelfReady liftIO $ writeIORef pendingChange $! mempty markSelfReady = do liftIO (readIORef haveEverBeenReady) >>= \case True -> return () False -> do liftIO $ writeIORef haveEverBeenReady True old <- liftIO $ readIORef parentUnreadyChildren let new = pred old liftIO $ writeIORef parentUnreadyChildren $! new when (new == 0) $ _hydrationDomBuilderEnv_commitAction initialEnv markChildReady :: IORef (ChildReadyState (Some k)) -> JSM () markChildReady childReadyState = do liftIO (readIORef childReadyState) >>= \case ChildReadyState_Ready -> return () ChildReadyState_Unready countedAt -> do liftIO $ writeIORef childReadyState ChildReadyState_Ready case countedAt of Nothing -> return () Just (Some k) -> do -- This child has been counted as unready, so we need to remove it from the unready set (oldUnready, p) <- liftIO $ readIORef pendingChange when (not $ DMap.null oldUnready) $ do -- This shouldn't actually ever be null let newUnready = DMap.delete k oldUnready liftIO $ writeIORef pendingChange (newUnready, p) when (DMap.null newUnready) $ do applyDomUpdate p (children0 :: DMap k (Compose (TraverseChild t m (Some k)) v'), children' :: Event t (p k (Compose (TraverseChild t m (Some k)) v'))) <- HydrationDomBuilderT $ lift $ base (\k v -> drawChildUpdate initialEnv markChildReady $ f k v) dm0 dm' let processChild k (Compose (TraverseChild e _)) = case e of Left _ -> pure $ ComposeMaybe Nothing Right immediate -> ComposeMaybe <$> do readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case ChildReadyState_Ready -> return Nothing ChildReadyState_Unready _ -> do writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just $ Some k return $ Just $ Constant (_traverseChildImmediate_childReadyState immediate) initialUnready <- liftIO $ DMap.mapMaybeWithKey (\_ -> getComposeMaybe) <$> DMap.traverseWithKey processChild children0 liftIO $ if DMap.null initialUnready then writeIORef haveEverBeenReady True else do modifyIORef' parentUnreadyChildren succ writeIORef pendingChange (initialUnready, mempty) -- The patch is always empty because it got applied implicitly when we ran the children the first time getHydrationMode >>= \case HydrationMode_Hydrating -> addHydrationStepWithSetup (holdIncremental children0 children') $ \children -> do dm :: DMap k (Compose (TraverseChild t m (Some k)) v') <- sample $ currentIncremental children phs <- sequenceA $ weakenDMapWith (either _traverseChildHydration_delayed (pure . _traverseChildImmediate_placeholder) . _traverseChild_mode . getCompose) dm liftIO $ writeIORef placeholders $! phs insertAfterPreviousNode lastPlaceholder HydrationMode_Immediate -> do let activate i = do append $ toNode $ _traverseChildImmediate_fragment i pure $ _traverseChildImmediate_placeholder i phs <- sequenceA $ weakenDMapWith (either (error "impossible") activate . _traverseChild_mode . getCompose) children0 liftIO $ writeIORef placeholders $! phs append $ toNode lastPlaceholder requestDomAction_ $ ffor children' $ \p -> do (oldUnready, oldP) <- liftIO $ readIORef pendingChange newUnready <- liftIO $ updateChildUnreadiness p oldUnready let !newP = p <> oldP liftIO $ writeIORef pendingChange (newUnready, newP) when (DMap.null newUnready) $ do applyDomUpdate newP let result0 = DMap.map (_traverseChild_result . getCompose) children0 result' = ffor children' $ mapPatch $ _traverseChild_result . getCompose return (result0, result') {-# INLINE hoistTraverseIntMapWithKeyWithAdjust #-} hoistTraverseIntMapWithKeyWithAdjust :: ( Adjustable t m , MonadHold t m , MonadJSM m , MonadFix m , PrimMonad m , Monoid (p (TraverseChild t m Int v')) , Functor p , PatchTarget (p (HydrationRunnerT t m ())) ~ IntMap (HydrationRunnerT t m ()) , PatchTarget (p (TraverseChild t m Int v')) ~ IntMap (TraverseChild t m Int v') , Patch (p (HydrationRunnerT t m ())) , Patch (p (TraverseChild t m Int v')) , RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document ) => ((IntMap.Key -> v -> DomRenderHookT t m (TraverseChild t m Int v')) -> IntMap v -> Event t (p v) -> DomRenderHookT t m (IntMap (TraverseChild t m Int v'), Event t (p (TraverseChild t m Int v')))) -- ^ The base monad's traversal -> (p (TraverseChild t m Int v') -> IntMap (IORef (ChildReadyState Int)) -> IO (IntMap (IORef (ChildReadyState Int)))) -- ^ Given a patch for the children DOM elements, produce a patch for the childrens' unreadiness state -> (IORef (IntMap DOM.Text) -> DOM.Text -> p (TraverseChild t m Int v') -> JSM ()) -- ^ Apply a patch to the DOM -> (IntMap.Key -> v -> HydrationDomBuilderT s t m v') -> IntMap v -> Event t (p v) -> HydrationDomBuilderT s t m (IntMap v', Event t (p v')) hoistTraverseIntMapWithKeyWithAdjust base updateChildUnreadiness applyDomUpdate_ f dm0 dm' = do doc <- askDocument initialEnv <- HydrationDomBuilderT ask let parentUnreadyChildren = _hydrationDomBuilderEnv_unreadyChildren initialEnv pendingChange :: IORef (IntMap (IORef (ChildReadyState Int)), p (TraverseChild t m Int v')) <- liftIO $ newIORef mempty haveEverBeenReady <- liftIO $ newIORef False placeholders <- liftIO $ newIORef IntMap.empty lastPlaceholder <- createTextNode doc ("" :: Text) let applyDomUpdate p = do applyDomUpdate_ placeholders lastPlaceholder p markSelfReady liftIO $ writeIORef pendingChange $! mempty markSelfReady = do liftIO (readIORef haveEverBeenReady) >>= \case True -> return () False -> do liftIO $ writeIORef haveEverBeenReady True old <- liftIO $ readIORef parentUnreadyChildren let new = pred old liftIO $ writeIORef parentUnreadyChildren $! new when (new == 0) $ _hydrationDomBuilderEnv_commitAction initialEnv markChildReady :: IORef (ChildReadyState Int) -> JSM () markChildReady childReadyState = do liftIO (readIORef childReadyState) >>= \case ChildReadyState_Ready -> return () ChildReadyState_Unready countedAt -> do liftIO $ writeIORef childReadyState ChildReadyState_Ready case countedAt of Nothing -> return () Just k -> do -- This child has been counted as unready, so we need to remove it from the unready set (oldUnready, p) <- liftIO $ readIORef pendingChange when (not $ IntMap.null oldUnready) $ do -- This shouldn't actually ever be null let newUnready = IntMap.delete k oldUnready liftIO $ writeIORef pendingChange (newUnready, p) when (IntMap.null newUnready) $ do applyDomUpdate p (children0 :: IntMap (TraverseChild t m Int v'), children' :: Event t (p (TraverseChild t m Int v'))) <- HydrationDomBuilderT $ lift $ base (\k v -> drawChildUpdateInt initialEnv markChildReady $ f k v) dm0 dm' let processChild k (TraverseChild e _) = case e of Left _ -> pure Nothing Right immediate -> do readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case ChildReadyState_Ready -> return Nothing ChildReadyState_Unready _ -> do writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just k return $ Just (_traverseChildImmediate_childReadyState immediate) initialUnready <- liftIO $ IntMap.mapMaybe id <$> IntMap.traverseWithKey processChild children0 liftIO $ if IntMap.null initialUnready then writeIORef haveEverBeenReady True else do modifyIORef' parentUnreadyChildren succ writeIORef pendingChange (initialUnready, mempty) -- The patch is always empty because it got applied implicitly when we ran the children the first time getHydrationMode >>= \case HydrationMode_Hydrating -> addHydrationStepWithSetup (holdIncremental children0 children') $ \children -> do dm :: IntMap (TraverseChild t m Int v') <- sample $ currentIncremental children phs <- traverse (either _traverseChildHydration_delayed (pure . _traverseChildImmediate_placeholder) . _traverseChild_mode) dm liftIO $ writeIORef placeholders $! phs insertAfterPreviousNode lastPlaceholder HydrationMode_Immediate -> do let activate i = do append $ toNode $ _traverseChildImmediate_fragment i pure $ _traverseChildImmediate_placeholder i phs <- traverse (either (error "impossible") activate . _traverseChild_mode) children0 liftIO $ writeIORef placeholders $! phs append $ toNode lastPlaceholder requestDomAction_ $ ffor children' $ \p -> do (oldUnready, oldP) <- liftIO $ readIORef pendingChange newUnready <- liftIO $ updateChildUnreadiness p oldUnready let !newP = p <> oldP liftIO $ writeIORef pendingChange (newUnready, newP) when (IntMap.null newUnready) $ do applyDomUpdate newP let result0 = IntMap.map _traverseChild_result children0 result' = ffor children' $ fmap $ _traverseChild_result return (result0, result') {-# SPECIALIZE hoistTraverseIntMapWithKeyWithAdjust :: ((IntMap.Key -> v -> DomRenderHookT DomTimeline HydrationM (TraverseChild DomTimeline HydrationM Int v')) -> IntMap v -> Event DomTimeline (PatchIntMap v) -> DomRenderHookT DomTimeline HydrationM (IntMap (TraverseChild DomTimeline HydrationM Int v'), Event DomTimeline (PatchIntMap (TraverseChild DomTimeline HydrationM Int v')))) -> (PatchIntMap (TraverseChild DomTimeline HydrationM Int v') -> IntMap (IORef (ChildReadyState Int)) -> IO (IntMap (IORef (ChildReadyState Int)))) -> (IORef (IntMap DOM.Text) -> DOM.Text -> PatchIntMap (TraverseChild DomTimeline HydrationM Int v') -> JSM ()) -> (IntMap.Key -> v -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM v') -> IntMap v -> Event DomTimeline (PatchIntMap v) -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v')) #-} {-# SPECIALIZE hoistTraverseIntMapWithKeyWithAdjust :: ((IntMap.Key -> v -> DomRenderHookT DomTimeline HydrationM (TraverseChild DomTimeline HydrationM Int v')) -> IntMap v -> Event DomTimeline (PatchIntMap v) -> DomRenderHookT DomTimeline HydrationM (IntMap (TraverseChild DomTimeline HydrationM Int v'), Event DomTimeline (PatchIntMap (TraverseChild DomTimeline HydrationM Int v')))) -> (PatchIntMap (TraverseChild DomTimeline HydrationM Int v') -> IntMap (IORef (ChildReadyState Int)) -> IO (IntMap (IORef (ChildReadyState Int)))) -> (IORef (IntMap DOM.Text) -> DOM.Text -> PatchIntMap (TraverseChild DomTimeline HydrationM Int v') -> JSM ()) -> (IntMap.Key -> v -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM v') -> IntMap v -> Event DomTimeline (PatchIntMap v) -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v')) #-} data TraverseChildImmediate k = TraverseChildImmediate { _traverseChildImmediate_fragment :: {-# UNPACK #-} !DOM.DocumentFragment -- ^ Child is appended to this fragment , _traverseChildImmediate_placeholder :: {-# UNPACK #-} !DOM.Text -- ^ Placeholder reference , _traverseChildImmediate_childReadyState :: {-# UNPACK #-} !(IORef (ChildReadyState k)) } newtype TraverseChildHydration t m = TraverseChildHydration { _traverseChildHydration_delayed :: HydrationRunnerT t m DOM.Text -- ^ Action to run at switchover, returns the placeholder } data TraverseChild t m k a = TraverseChild { _traverseChild_mode :: !(Either (TraverseChildHydration t m) (TraverseChildImmediate k)) , _traverseChild_result :: !a } deriving Functor {-# INLINABLE drawChildUpdate #-} drawChildUpdate :: (MonadJSM m, Reflex t) => HydrationDomBuilderEnv t m -> (IORef (ChildReadyState k) -> JSM ()) -- This will NOT be called if the child is ready at initialization time; instead, the ChildReadyState return value will be ChildReadyState_Ready -> HydrationDomBuilderT s t m (f a) -> DomRenderHookT t m (Compose (TraverseChild t m k) f a) drawChildUpdate initialEnv markReady child = do let doc = _hydrationDomBuilderEnv_document initialEnv unreadyChildren <- liftIO $ newIORef 0 liftIO (readIORef $ _hydrationDomBuilderEnv_hydrationMode initialEnv) >>= \case HydrationMode_Hydrating -> do childDelayedRef <- liftIO $ newIORef $ pure () result <- runReaderT (unHydrationDomBuilderT child) initialEnv { _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren , _hydrationDomBuilderEnv_delayed = childDelayedRef } childDelayed <- liftIO $ readIORef childDelayedRef return $ Compose $ TraverseChild { _traverseChild_result = result , _traverseChild_mode = Left TraverseChildHydration { _traverseChildHydration_delayed = do placeholder <- createTextNode doc ("" :: Text) insertAfterPreviousNode placeholder childDelayed pure placeholder } } HydrationMode_Immediate -> do childReadyState <- liftIO $ newIORef $ ChildReadyState_Unready Nothing df <- createDocumentFragment doc placeholder <- createTextNode doc ("" :: Text) Node.appendChild_ df placeholder result <- runReaderT (unHydrationDomBuilderT child) initialEnv { _hydrationDomBuilderEnv_parent = Left $ toNode df , _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren , _hydrationDomBuilderEnv_commitAction = markReady childReadyState } u <- liftIO $ readIORef unreadyChildren when (u == 0) $ liftIO $ writeIORef childReadyState ChildReadyState_Ready return $ Compose $ TraverseChild { _traverseChild_result = result , _traverseChild_mode = Right TraverseChildImmediate { _traverseChildImmediate_fragment = df , _traverseChildImmediate_placeholder = placeholder , _traverseChildImmediate_childReadyState = childReadyState } } {-# SPECIALIZE drawChildUpdate :: HydrationDomBuilderEnv DomTimeline HydrationM -> (IORef (ChildReadyState Int) -> JSM ()) -> HydrationDomBuilderT s DomTimeline HydrationM (Identity a) -> DomRenderHookT DomTimeline HydrationM (Compose (TraverseChild DomTimeline HydrationM Int) Identity a) #-} {-# SPECIALIZE drawChildUpdate :: HydrationDomBuilderEnv DomTimeline HydrationM -> (IORef (ChildReadyState (Some k)) -> JSM ()) -> HydrationDomBuilderT s DomTimeline HydrationM (f a) -> DomRenderHookT DomTimeline HydrationM (Compose (TraverseChild DomTimeline HydrationM (Some k)) f a) #-} {-# INLINABLE drawChildUpdateInt #-} drawChildUpdateInt :: (MonadIO m, MonadJSM m, Reflex t) => HydrationDomBuilderEnv t m -> (IORef (ChildReadyState k) -> JSM ()) -> HydrationDomBuilderT s t m v -> DomRenderHookT t m (TraverseChild t m k v) drawChildUpdateInt env mark m = fmap runIdentity . getCompose <$> drawChildUpdate env mark (Identity <$> m) {-# SPECIALIZE drawChildUpdateInt :: HydrationDomBuilderEnv DomTimeline HydrationM -> (IORef (ChildReadyState k) -> JSM ()) -> HydrationDomBuilderT s DomTimeline HydrationM v -> DomRenderHookT DomTimeline HydrationM (TraverseChild DomTimeline HydrationM k v) #-} {-# INLINE mkHasFocus #-} mkHasFocus :: (HasDocument m, MonadJSM m, IsNode (RawElement d), MonadHold t m, Reflex t, DOM.IsDocumentOrShadowRoot (RawDocument (DomBuilderSpace m))) => Element er d t -> m (Dynamic t Bool) mkHasFocus e = do doc <- askDocument initialFocus <- Node.isSameNode (toNode $ _element_raw e) . fmap toNode =<< Document.getActiveElement doc holdDyn initialFocus $ leftmost [ False <$ Reflex.select (_element_events e) (WrapArg Blur) , True <$ Reflex.select (_element_events e) (WrapArg Focus) ] insertBefore :: (MonadJSM m, IsNode new, IsNode existing) => new -> existing -> m () insertBefore new existing = do p <- getParentNodeUnchecked existing Node.insertBefore_ p new (Just existing) -- If there's no parent, that means we've been removed from the DOM; this should not happen if the we're removing ourselves from the performEvent properly type ImmediateDomBuilderT = HydrationDomBuilderT GhcjsDomSpace instance PerformEvent t m => PerformEvent t (HydrationDomBuilderT s t m) where type Performable (HydrationDomBuilderT s t m) = Performable m {-# INLINABLE performEvent_ #-} performEvent_ e = lift $ performEvent_ e {-# INLINABLE performEvent #-} performEvent e = lift $ performEvent e instance PostBuild t m => PostBuild t (HydrationDomBuilderT s t m) where {-# INLINABLE getPostBuild #-} getPostBuild = lift getPostBuild instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (HydrationDomBuilderT s t m) where {-# INLINABLE newEventWithTrigger #-} newEventWithTrigger = lift . newEventWithTrigger {-# INLINABLE newFanEventWithTrigger #-} newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (HydrationDomBuilderT s t m) where {-# INLINABLE newTriggerEvent #-} newTriggerEvent = HydrationDomBuilderT . lift $ newTriggerEvent {-# INLINABLE newTriggerEventWithOnComplete #-} newTriggerEventWithOnComplete = HydrationDomBuilderT . lift $ newTriggerEventWithOnComplete {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-} newEventWithLazyTriggerWithOnComplete f = HydrationDomBuilderT . lift $ newEventWithLazyTriggerWithOnComplete f instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (DomRenderHookT t m) where {-# INLINABLE newTriggerEvent #-} newTriggerEvent = DomRenderHookT . lift $ newTriggerEvent {-# INLINABLE newTriggerEventWithOnComplete #-} newTriggerEventWithOnComplete = DomRenderHookT . lift $ newTriggerEventWithOnComplete {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-} newEventWithLazyTriggerWithOnComplete f = DomRenderHookT . lift $ newEventWithLazyTriggerWithOnComplete f instance MonadRef m => MonadRef (HydrationDomBuilderT s t m) where type Ref (HydrationDomBuilderT s t m) = Ref m {-# INLINABLE newRef #-} newRef = lift . newRef {-# INLINABLE readRef #-} readRef = lift . readRef {-# INLINABLE writeRef #-} writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (HydrationDomBuilderT s t m) where {-# INLINABLE atomicModifyRef #-} atomicModifyRef r = lift . atomicModifyRef r type family EventType en where EventType 'AbortTag = UIEvent EventType 'BlurTag = FocusEvent EventType 'ChangeTag = DOM.Event EventType 'ClickTag = MouseEvent EventType 'ContextmenuTag = MouseEvent EventType 'DblclickTag = MouseEvent EventType 'DragTag = MouseEvent EventType 'DragendTag = MouseEvent EventType 'DragenterTag = MouseEvent EventType 'DragleaveTag = MouseEvent EventType 'DragoverTag = MouseEvent EventType 'DragstartTag = MouseEvent EventType 'DropTag = MouseEvent EventType 'ErrorTag = UIEvent EventType 'FocusTag = FocusEvent EventType 'InputTag = DOM.Event EventType 'InvalidTag = DOM.Event EventType 'KeydownTag = KeyboardEvent EventType 'KeypressTag = KeyboardEvent EventType 'KeyupTag = KeyboardEvent EventType 'LoadTag = UIEvent EventType 'MousedownTag = MouseEvent EventType 'MouseenterTag = MouseEvent EventType 'MouseleaveTag = MouseEvent EventType 'MousemoveTag = MouseEvent EventType 'MouseoutTag = MouseEvent EventType 'MouseoverTag = MouseEvent EventType 'MouseupTag = MouseEvent EventType 'MousewheelTag = MouseEvent EventType 'ScrollTag = UIEvent EventType 'SelectTag = UIEvent EventType 'SubmitTag = DOM.Event EventType 'WheelTag = WheelEvent EventType 'BeforecutTag = ClipboardEvent EventType 'CutTag = ClipboardEvent EventType 'BeforecopyTag = ClipboardEvent EventType 'CopyTag = ClipboardEvent EventType 'BeforepasteTag = ClipboardEvent EventType 'PasteTag = ClipboardEvent EventType 'ResetTag = DOM.Event EventType 'SearchTag = DOM.Event EventType 'SelectstartTag = DOM.Event EventType 'TouchstartTag = TouchEvent EventType 'TouchmoveTag = TouchEvent EventType 'TouchendTag = TouchEvent EventType 'TouchcancelTag = TouchEvent {-# INLINABLE defaultDomEventHandler #-} defaultDomEventHandler :: IsElement e => e -> EventName en -> EventM e (EventType en) (Maybe (EventResult en)) defaultDomEventHandler e evt = fmap (Just . EventResult) $ case evt of Click -> return () Dblclick -> getMouseEventCoords Keypress -> getKeyEvent Scroll -> fromIntegral <$> getScrollTop e Keydown -> getKeyEvent Keyup -> getKeyEvent Mousemove -> getMouseEventCoords Mouseup -> getMouseEventCoords Mousedown -> getMouseEventCoords Mouseenter -> return () Mouseleave -> return () Focus -> return () Blur -> return () Change -> return () Drag -> return () Dragend -> return () Dragenter -> return () Dragleave -> return () Dragover -> return () Dragstart -> return () Drop -> return () Abort -> return () Contextmenu -> return () Error -> return () Input -> return () Invalid -> return () Load -> return () Mouseout -> return () Mouseover -> return () Select -> return () Submit -> return () Beforecut -> return () Cut -> return () Beforecopy -> return () Copy -> return () Beforepaste -> return () Paste -> getPasteData Reset -> return () Search -> return () Selectstart -> return () Touchstart -> getTouchEvent Touchmove -> getTouchEvent Touchend -> getTouchEvent Touchcancel -> getTouchEvent Mousewheel -> return () Wheel -> getWheelEvent {-# INLINABLE defaultDomWindowEventHandler #-} defaultDomWindowEventHandler :: DOM.Window -> EventName en -> EventM DOM.Window (EventType en) (Maybe (EventResult en)) defaultDomWindowEventHandler w evt = fmap (Just . EventResult) $ case evt of Click -> return () Dblclick -> getMouseEventCoords Keypress -> getKeyEvent Scroll -> Window.getScrollY w Keydown -> getKeyEvent Keyup -> getKeyEvent Mousemove -> getMouseEventCoords Mouseup -> getMouseEventCoords Mousedown -> getMouseEventCoords Mouseenter -> return () Mouseleave -> return () Focus -> return () Blur -> return () Change -> return () Drag -> return () Dragend -> return () Dragenter -> return () Dragleave -> return () Dragover -> return () Dragstart -> return () Drop -> return () Abort -> return () Contextmenu -> return () Error -> return () Input -> return () Invalid -> return () Load -> return () Mouseout -> return () Mouseover -> return () Select -> return () Submit -> return () Beforecut -> return () Cut -> return () Beforecopy -> return () Copy -> return () Beforepaste -> return () Paste -> getPasteData Reset -> return () Search -> return () Selectstart -> return () Touchstart -> getTouchEvent Touchmove -> getTouchEvent Touchend -> getTouchEvent Touchcancel -> getTouchEvent Mousewheel -> return () Wheel -> getWheelEvent {-# INLINABLE withIsEvent #-} withIsEvent :: EventName en -> (IsEvent (EventType en) => r) -> r withIsEvent en r = case en of Click -> r Dblclick -> r Keypress -> r Scroll -> r Keydown -> r Keyup -> r Mousemove -> r Mouseup -> r Mousedown -> r Mouseenter -> r Mouseleave -> r Focus -> r Blur -> r Change -> r Drag -> r Dragend -> r Dragenter -> r Dragleave -> r Dragover -> r Dragstart -> r Drop -> r Abort -> r Contextmenu -> r Error -> r Input -> r Invalid -> r Load -> r Mouseout -> r Mouseover -> r Select -> r Submit -> r Beforecut -> r Cut -> r Beforecopy -> r Copy -> r Beforepaste -> r Paste -> r Reset -> r Search -> r Selectstart -> r Touchstart -> r Touchmove -> r Touchend -> r Touchcancel -> r Mousewheel -> r Wheel -> r showEventName :: EventName en -> String showEventName en = case en of Abort -> "Abort" Blur -> "Blur" Change -> "Change" Click -> "Click" Contextmenu -> "Contextmenu" Dblclick -> "Dblclick" Drag -> "Drag" Dragend -> "Dragend" Dragenter -> "Dragenter" Dragleave -> "Dragleave" Dragover -> "Dragover" Dragstart -> "Dragstart" Drop -> "Drop" Error -> "Error" Focus -> "Focus" Input -> "Input" Invalid -> "Invalid" Keydown -> "Keydown" Keypress -> "Keypress" Keyup -> "Keyup" Load -> "Load" Mousedown -> "Mousedown" Mouseenter -> "Mouseenter" Mouseleave -> "Mouseleave" Mousemove -> "Mousemove" Mouseout -> "Mouseout" Mouseover -> "Mouseover" Mouseup -> "Mouseup" Mousewheel -> "Mousewheel" Scroll -> "Scroll" Select -> "Select" Submit -> "Submit" Wheel -> "Wheel" Beforecut -> "Beforecut" Cut -> "Cut" Beforecopy -> "Beforecopy" Copy -> "Copy" Beforepaste -> "Beforepaste" Paste -> "Paste" Reset -> "Reset" Search -> "Search" Selectstart -> "Selectstart" Touchstart -> "Touchstart" Touchmove -> "Touchmove" Touchend -> "Touchend" Touchcancel -> "Touchcancel" --TODO: Get rid of this hack -- ElementEventTarget is here to allow us to treat SVG and HTML elements as the same thing; without it, we'll break any existing SVG code. newtype ElementEventTarget = ElementEventTarget DOM.Element deriving (DOM.IsGObject, DOM.ToJSVal, DOM.IsSlotable, DOM.IsParentNode, DOM.IsNonDocumentTypeChildNode, DOM.IsChildNode, DOM.IsAnimatable, IsNode, IsElement) instance DOM.FromJSVal ElementEventTarget where fromJSVal = fmap (fmap ElementEventTarget) . DOM.fromJSVal instance DOM.IsEventTarget ElementEventTarget instance DOM.IsGlobalEventHandlers ElementEventTarget instance DOM.IsDocumentAndElementEventHandlers ElementEventTarget {-# INLINABLE elementOnEventName #-} elementOnEventName :: IsElement e => EventName en -> e -> EventM e (EventType en) () -> JSM (JSM ()) elementOnEventName en e_ = let e = ElementEventTarget (DOM.toElement e_) in case en of Abort -> on e Events.abort Blur -> on e Events.blur Change -> on e Events.change Click -> on e Events.click Contextmenu -> on e Events.contextMenu Dblclick -> on e Events.dblClick Drag -> on e Events.drag Dragend -> on e Events.dragEnd Dragenter -> on e Events.dragEnter Dragleave -> on e Events.dragLeave Dragover -> on e Events.dragOver Dragstart -> on e Events.dragStart Drop -> on e Events.drop Error -> on e Events.error Focus -> on e Events.focus Input -> on e Events.input Invalid -> on e Events.invalid Keydown -> on e Events.keyDown Keypress -> on e Events.keyPress Keyup -> on e Events.keyUp Load -> on e Events.load Mousedown -> on e Events.mouseDown Mouseenter -> on e Events.mouseEnter Mouseleave -> on e Events.mouseLeave Mousemove -> on e Events.mouseMove Mouseout -> on e Events.mouseOut Mouseover -> on e Events.mouseOver Mouseup -> on e Events.mouseUp Mousewheel -> on e Events.mouseWheel Scroll -> on e Events.scroll Select -> on e Events.select Submit -> on e Events.submit Wheel -> on e Events.wheel Beforecut -> on e Events.beforeCut Cut -> on e Events.cut Beforecopy -> on e Events.beforeCopy Copy -> on e Events.copy Beforepaste -> on e Events.beforePaste Paste -> on e Events.paste Reset -> on e Events.reset Search -> on e Events.search Selectstart -> on e Element.selectStart Touchstart -> on e Events.touchStart Touchmove -> on e Events.touchMove Touchend -> on e Events.touchEnd Touchcancel -> on e Events.touchCancel {-# INLINABLE windowOnEventName #-} windowOnEventName :: EventName en -> DOM.Window -> EventM DOM.Window (EventType en) () -> JSM (JSM ()) windowOnEventName en e = case en of Abort -> on e Events.abort Blur -> on e Events.blur Change -> on e Events.change Click -> on e Events.click Contextmenu -> on e Events.contextMenu Dblclick -> on e Events.dblClick Drag -> on e Events.drag Dragend -> on e Events.dragEnd Dragenter -> on e Events.dragEnter Dragleave -> on e Events.dragLeave Dragover -> on e Events.dragOver Dragstart -> on e Events.dragStart Drop -> on e Events.drop Error -> on e Events.error Focus -> on e Events.focus Input -> on e Events.input Invalid -> on e Events.invalid Keydown -> on e Events.keyDown Keypress -> on e Events.keyPress Keyup -> on e Events.keyUp Load -> on e Events.load Mousedown -> on e Events.mouseDown Mouseenter -> on e Events.mouseEnter Mouseleave -> on e Events.mouseLeave Mousemove -> on e Events.mouseMove Mouseout -> on e Events.mouseOut Mouseover -> on e Events.mouseOver Mouseup -> on e Events.mouseUp Mousewheel -> on e Events.mouseWheel Scroll -> on e Events.scroll Select -> on e Events.select Submit -> on e Events.submit Wheel -> on e Events.wheel Beforecut -> const $ return $ return () --TODO Cut -> const $ return $ return () --TODO Beforecopy -> const $ return $ return () --TODO Copy -> const $ return $ return () --TODO Beforepaste -> const $ return $ return () --TODO Paste -> const $ return $ return () --TODO Reset -> on e Events.reset Search -> on e Events.search Selectstart -> const $ return $ return () --TODO Touchstart -> on e Events.touchStart Touchmove -> on e Events.touchMove Touchend -> on e Events.touchEnd Touchcancel -> on e Events.touchCancel {-# INLINABLE wrapDomEvent #-} wrapDomEvent :: (TriggerEvent t m, MonadJSM m) => e -> (e -> EventM e event () -> JSM (JSM ())) -> EventM e event a -> m (Event t a) wrapDomEvent el elementOnevent getValue = wrapDomEventMaybe el elementOnevent $ fmap Just getValue {-# INLINABLE subscribeDomEvent #-} subscribeDomEvent :: (EventM e event () -> JSM (JSM ())) -> EventM e event (Maybe a) -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> EventTrigger t a -> JSM (JSM ()) subscribeDomEvent elementOnevent getValue eventChan et = elementOnevent $ do mv <- getValue forM_ mv $ \v -> liftIO $ do --TODO: I don't think this is quite right: if a new trigger is created between when this is enqueued and when it fires, this may not work quite right etr <- newIORef $ Just et writeChan eventChan [EventTriggerRef etr :=> TriggerInvocation v (return ())] {-# INLINABLE wrapDomEventMaybe #-} wrapDomEventMaybe :: (TriggerEvent t m, MonadJSM m) => e -> (e -> EventM e event () -> JSM (JSM ())) -> EventM e event (Maybe a) -> m (Event t a) wrapDomEventMaybe el elementOnevent getValue = do ctx <- askJSM newEventWithLazyTriggerWithOnComplete $ \trigger -> (`runJSM` ctx) <$> (`runJSM` ctx) (elementOnevent el $ do mv <- getValue forM_ mv $ \v -> liftIO $ trigger v $ return ()) {-# INLINABLE wrapDomEventsMaybe #-} wrapDomEventsMaybe :: (MonadJSM m, MonadReflexCreateTrigger t m) => e -> (forall en. IsEvent (EventType en) => EventName en -> EventM e (EventType en) (Maybe (f en))) -> (forall en. EventName en -> e -> EventM e (EventType en) () -> JSM (JSM ())) -> ImmediateDomBuilderT t m (EventSelector t (WrapArg f EventName)) wrapDomEventsMaybe target handlers onEventName = do ctx <- askJSM eventChan <- askEvents e <- lift $ newFanEventWithTrigger $ \(WrapArg en) -> withIsEvent en (((`runJSM` ctx) <$>) . (`runJSM` ctx) . subscribeDomEvent (onEventName en target) (handlers en) eventChan) return $! e {-# INLINABLE getKeyEvent #-} getKeyEvent :: EventM e KeyboardEvent Word getKeyEvent = do e <- event which <- KeyboardEvent.getWhich e if which /= 0 then return which else do charCode <- getCharCode e if charCode /= 0 then return charCode else getKeyCode e {-# INLINABLE getMouseEventCoords #-} getMouseEventCoords :: EventM e MouseEvent (Int, Int) getMouseEventCoords = do e <- event bisequence (getClientX e, getClientY e) {-# INLINABLE getPasteData #-} getPasteData :: EventM e ClipboardEvent (Maybe Text) getPasteData = do e <- event mdt <- ClipboardEvent.getClipboardData e case mdt of Nothing -> return Nothing Just dt -> Just <$> DataTransfer.getData dt ("text" :: Text) {-# INLINABLE getTouchEvent #-} getTouchEvent :: EventM e TouchEvent TouchEventResult getTouchEvent = do let touchResults ts = do n <- TouchList.getLength ts forM (takeWhile (< n) [0..]) $ \ix -> do t <- TouchList.item ts ix identifier <- Touch.getIdentifier t screenX <- Touch.getScreenX t screenY <- Touch.getScreenY t clientX <- Touch.getClientX t clientY <- Touch.getClientY t pageX <- Touch.getPageX t pageY <- Touch.getPageY t return TouchResult { _touchResult_identifier = identifier , _touchResult_screenX = screenX , _touchResult_screenY = screenY , _touchResult_clientX = clientX , _touchResult_clientY = clientY , _touchResult_pageX = pageX , _touchResult_pageY = pageY } e <- event altKey <- TouchEvent.getAltKey e ctrlKey <- TouchEvent.getCtrlKey e shiftKey <- TouchEvent.getShiftKey e metaKey <- TouchEvent.getMetaKey e changedTouches <- touchResults =<< TouchEvent.getChangedTouches e targetTouches <- touchResults =<< TouchEvent.getTargetTouches e touches <- touchResults =<< TouchEvent.getTouches e return $ TouchEventResult { _touchEventResult_altKey = altKey , _touchEventResult_changedTouches = changedTouches , _touchEventResult_ctrlKey = ctrlKey , _touchEventResult_metaKey = metaKey , _touchEventResult_shiftKey = shiftKey , _touchEventResult_targetTouches = targetTouches , _touchEventResult_touches = touches } {-# INLINABLE getWheelEvent #-} getWheelEvent :: EventM e WheelEvent WheelEventResult getWheelEvent = do e <- event dx :: Double <- WheelEvent.getDeltaX e dy :: Double <- WheelEvent.getDeltaY e dz :: Double <- WheelEvent.getDeltaZ e deltaMode :: Word <- WheelEvent.getDeltaMode e return $ WheelEventResult { _wheelEventResult_deltaX = dx , _wheelEventResult_deltaY = dy , _wheelEventResult_deltaZ = dz , _wheelEventResult_deltaMode = case deltaMode of 0 -> DeltaPixel 1 -> DeltaLine 2 -> DeltaPage -- See https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode _ -> error "getWheelEvent: impossible encoding" } instance MonadSample t m => MonadSample t (HydrationDomBuilderT s t m) where {-# INLINABLE sample #-} sample = lift . sample instance MonadHold t m => MonadHold t (HydrationDomBuilderT s t m) where {-# INLINABLE hold #-} hold v0 v' = lift $ hold v0 v' {-# INLINABLE holdDyn #-} holdDyn v0 v' = lift $ holdDyn v0 v' {-# INLINABLE holdIncremental #-} holdIncremental v0 v' = lift $ holdIncremental v0 v' {-# INLINABLE buildDynamic #-} buildDynamic a0 = lift . buildDynamic a0 {-# INLINABLE headE #-} headE = lift . headE data WindowConfig t = WindowConfig -- No config options yet instance Default (WindowConfig t) where def = WindowConfig data Window t = Window { _window_events :: EventSelector t (WrapArg EventResult EventName) , _window_raw :: DOM.Window } wrapWindow :: (MonadJSM m, MonadReflexCreateTrigger t m) => DOM.Window -> WindowConfig t -> HydrationDomBuilderT GhcjsDomSpace t m (Window t) wrapWindow wv _ = do events <- wrapDomEventsMaybe wv (defaultDomWindowEventHandler wv) windowOnEventName return $ Window { _window_events = events , _window_raw = wv } #ifdef USE_TEMPLATE_HASKELL makeLenses ''GhcjsEventSpec #endif
reflex-frp/reflex-dom
reflex-dom-core/src/Reflex/Dom/Builder/Immediate.hs
bsd-3-clause
127,061
122
63
26,048
31,773
15,791
15,982
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.Version14 -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.Version14 ( -- * Types GLbitfield, GLboolean, GLbyte, GLclampd, GLclampf, GLdouble, GLenum, GLfloat, GLint, GLshort, GLsizei, GLubyte, GLuint, GLushort, GLvoid, -- * Enums gl_2D, gl_2_BYTES, gl_3D, gl_3D_COLOR, gl_3D_COLOR_TEXTURE, gl_3_BYTES, gl_4D_COLOR_TEXTURE, gl_4_BYTES, gl_ACCUM, gl_ACCUM_ALPHA_BITS, gl_ACCUM_BLUE_BITS, gl_ACCUM_BUFFER_BIT, gl_ACCUM_CLEAR_VALUE, gl_ACCUM_GREEN_BITS, gl_ACCUM_RED_BITS, gl_ACTIVE_TEXTURE, gl_ADD, gl_ADD_SIGNED, gl_ALIASED_LINE_WIDTH_RANGE, gl_ALIASED_POINT_SIZE_RANGE, gl_ALL_ATTRIB_BITS, gl_ALPHA, gl_ALPHA12, gl_ALPHA16, gl_ALPHA4, gl_ALPHA8, gl_ALPHA_BIAS, gl_ALPHA_BITS, gl_ALPHA_SCALE, gl_ALPHA_TEST, gl_ALPHA_TEST_FUNC, gl_ALPHA_TEST_REF, gl_ALWAYS, gl_AMBIENT, gl_AMBIENT_AND_DIFFUSE, gl_AND, gl_AND_INVERTED, gl_AND_REVERSE, gl_ATTRIB_STACK_DEPTH, gl_AUTO_NORMAL, gl_AUX0, gl_AUX1, gl_AUX2, gl_AUX3, gl_AUX_BUFFERS, gl_BACK, gl_BACK_LEFT, gl_BACK_RIGHT, gl_BGR, gl_BGRA, gl_BITMAP, gl_BITMAP_TOKEN, gl_BLEND, gl_BLEND_DST, gl_BLEND_DST_ALPHA, gl_BLEND_DST_RGB, gl_BLEND_SRC, gl_BLEND_SRC_ALPHA, gl_BLEND_SRC_RGB, gl_BLUE, gl_BLUE_BIAS, gl_BLUE_BITS, gl_BLUE_SCALE, gl_BYTE, gl_C3F_V3F, gl_C4F_N3F_V3F, gl_C4UB_V2F, gl_C4UB_V3F, gl_CCW, gl_CLAMP, gl_CLAMP_TO_BORDER, gl_CLAMP_TO_EDGE, gl_CLEAR, gl_CLIENT_ACTIVE_TEXTURE, gl_CLIENT_ALL_ATTRIB_BITS, gl_CLIENT_ATTRIB_STACK_DEPTH, gl_CLIENT_PIXEL_STORE_BIT, gl_CLIENT_VERTEX_ARRAY_BIT, gl_CLIP_PLANE0, gl_CLIP_PLANE1, gl_CLIP_PLANE2, gl_CLIP_PLANE3, gl_CLIP_PLANE4, gl_CLIP_PLANE5, gl_COEFF, gl_COLOR, gl_COLOR_ARRAY, gl_COLOR_ARRAY_POINTER, gl_COLOR_ARRAY_SIZE, gl_COLOR_ARRAY_STRIDE, gl_COLOR_ARRAY_TYPE, gl_COLOR_BUFFER_BIT, gl_COLOR_CLEAR_VALUE, gl_COLOR_INDEX, gl_COLOR_INDEXES, gl_COLOR_LOGIC_OP, gl_COLOR_MATERIAL, gl_COLOR_MATERIAL_FACE, gl_COLOR_MATERIAL_PARAMETER, gl_COLOR_SUM, gl_COLOR_WRITEMASK, gl_COMBINE, gl_COMBINE_ALPHA, gl_COMBINE_RGB, gl_COMPARE_R_TO_TEXTURE, gl_COMPILE, gl_COMPILE_AND_EXECUTE, gl_COMPRESSED_ALPHA, gl_COMPRESSED_INTENSITY, gl_COMPRESSED_LUMINANCE, gl_COMPRESSED_LUMINANCE_ALPHA, gl_COMPRESSED_RGB, gl_COMPRESSED_RGBA, gl_COMPRESSED_TEXTURE_FORMATS, gl_CONSTANT, gl_CONSTANT_ALPHA, gl_CONSTANT_ATTENUATION, gl_CONSTANT_COLOR, gl_COPY, gl_COPY_INVERTED, gl_COPY_PIXEL_TOKEN, gl_CULL_FACE, gl_CULL_FACE_MODE, gl_CURRENT_BIT, gl_CURRENT_COLOR, gl_CURRENT_FOG_COORDINATE, gl_CURRENT_INDEX, gl_CURRENT_NORMAL, gl_CURRENT_RASTER_COLOR, gl_CURRENT_RASTER_DISTANCE, gl_CURRENT_RASTER_INDEX, gl_CURRENT_RASTER_POSITION, gl_CURRENT_RASTER_POSITION_VALID, gl_CURRENT_RASTER_TEXTURE_COORDS, gl_CURRENT_SECONDARY_COLOR, gl_CURRENT_TEXTURE_COORDS, gl_CW, gl_DECAL, gl_DECR, gl_DECR_WRAP, gl_DEPTH, gl_DEPTH_BIAS, gl_DEPTH_BITS, gl_DEPTH_BUFFER_BIT, gl_DEPTH_CLEAR_VALUE, gl_DEPTH_COMPONENT, gl_DEPTH_COMPONENT16, gl_DEPTH_COMPONENT24, gl_DEPTH_COMPONENT32, gl_DEPTH_FUNC, gl_DEPTH_RANGE, gl_DEPTH_SCALE, gl_DEPTH_TEST, gl_DEPTH_TEXTURE_MODE, gl_DEPTH_WRITEMASK, gl_DIFFUSE, gl_DITHER, gl_DOMAIN, gl_DONT_CARE, gl_DOT3_RGB, gl_DOT3_RGBA, gl_DOUBLE, gl_DOUBLEBUFFER, gl_DRAW_BUFFER, gl_DRAW_PIXEL_TOKEN, gl_DST_ALPHA, gl_DST_COLOR, gl_EDGE_FLAG, gl_EDGE_FLAG_ARRAY, gl_EDGE_FLAG_ARRAY_POINTER, gl_EDGE_FLAG_ARRAY_STRIDE, gl_EMISSION, gl_ENABLE_BIT, gl_EQUAL, gl_EQUIV, gl_EVAL_BIT, gl_EXP, gl_EXP2, gl_EXTENSIONS, gl_EYE_LINEAR, gl_EYE_PLANE, gl_FALSE, gl_FASTEST, gl_FEEDBACK, gl_FEEDBACK_BUFFER_POINTER, gl_FEEDBACK_BUFFER_SIZE, gl_FEEDBACK_BUFFER_TYPE, gl_FILL, gl_FLAT, gl_FLOAT, gl_FOG, gl_FOG_BIT, gl_FOG_COLOR, gl_FOG_COORDINATE, gl_FOG_COORDINATE_ARRAY, gl_FOG_COORDINATE_ARRAY_POINTER, gl_FOG_COORDINATE_ARRAY_STRIDE, gl_FOG_COORDINATE_ARRAY_TYPE, gl_FOG_COORDINATE_SOURCE, gl_FOG_DENSITY, gl_FOG_END, gl_FOG_HINT, gl_FOG_INDEX, gl_FOG_MODE, gl_FOG_START, gl_FRAGMENT_DEPTH, gl_FRONT, gl_FRONT_AND_BACK, gl_FRONT_FACE, gl_FRONT_LEFT, gl_FRONT_RIGHT, gl_FUNC_ADD, gl_FUNC_REVERSE_SUBTRACT, gl_FUNC_SUBTRACT, gl_GENERATE_MIPMAP, gl_GENERATE_MIPMAP_HINT, gl_GEQUAL, gl_GREATER, gl_GREEN, gl_GREEN_BIAS, gl_GREEN_BITS, gl_GREEN_SCALE, gl_HINT_BIT, gl_INCR, gl_INCR_WRAP, gl_INDEX_ARRAY, gl_INDEX_ARRAY_POINTER, gl_INDEX_ARRAY_STRIDE, gl_INDEX_ARRAY_TYPE, gl_INDEX_BITS, gl_INDEX_CLEAR_VALUE, gl_INDEX_LOGIC_OP, gl_INDEX_MODE, gl_INDEX_OFFSET, gl_INDEX_SHIFT, gl_INDEX_WRITEMASK, gl_INT, gl_INTENSITY, gl_INTENSITY12, gl_INTENSITY16, gl_INTENSITY4, gl_INTENSITY8, gl_INTERPOLATE, gl_INVALID_ENUM, gl_INVALID_OPERATION, gl_INVALID_VALUE, gl_INVERT, gl_KEEP, gl_LEFT, gl_LEQUAL, gl_LESS, gl_LIGHT0, gl_LIGHT1, gl_LIGHT2, gl_LIGHT3, gl_LIGHT4, gl_LIGHT5, gl_LIGHT6, gl_LIGHT7, gl_LIGHTING, gl_LIGHTING_BIT, gl_LIGHT_MODEL_AMBIENT, gl_LIGHT_MODEL_COLOR_CONTROL, gl_LIGHT_MODEL_LOCAL_VIEWER, gl_LIGHT_MODEL_TWO_SIDE, gl_LINE, gl_LINEAR, gl_LINEAR_ATTENUATION, gl_LINEAR_MIPMAP_LINEAR, gl_LINEAR_MIPMAP_NEAREST, gl_LINES, gl_LINE_BIT, gl_LINE_LOOP, gl_LINE_RESET_TOKEN, gl_LINE_SMOOTH, gl_LINE_SMOOTH_HINT, gl_LINE_STIPPLE, gl_LINE_STIPPLE_PATTERN, gl_LINE_STIPPLE_REPEAT, gl_LINE_STRIP, gl_LINE_TOKEN, gl_LINE_WIDTH, gl_LINE_WIDTH_GRANULARITY, gl_LINE_WIDTH_RANGE, gl_LIST_BASE, gl_LIST_BIT, gl_LIST_INDEX, gl_LIST_MODE, gl_LOAD, gl_LOGIC_OP, gl_LOGIC_OP_MODE, gl_LUMINANCE, gl_LUMINANCE12, gl_LUMINANCE12_ALPHA12, gl_LUMINANCE12_ALPHA4, gl_LUMINANCE16, gl_LUMINANCE16_ALPHA16, gl_LUMINANCE4, gl_LUMINANCE4_ALPHA4, gl_LUMINANCE6_ALPHA2, gl_LUMINANCE8, gl_LUMINANCE8_ALPHA8, gl_LUMINANCE_ALPHA, gl_MAP1_COLOR_4, gl_MAP1_GRID_DOMAIN, gl_MAP1_GRID_SEGMENTS, gl_MAP1_INDEX, gl_MAP1_NORMAL, gl_MAP1_TEXTURE_COORD_1, gl_MAP1_TEXTURE_COORD_2, gl_MAP1_TEXTURE_COORD_3, gl_MAP1_TEXTURE_COORD_4, gl_MAP1_VERTEX_3, gl_MAP1_VERTEX_4, gl_MAP2_COLOR_4, gl_MAP2_GRID_DOMAIN, gl_MAP2_GRID_SEGMENTS, gl_MAP2_INDEX, gl_MAP2_NORMAL, gl_MAP2_TEXTURE_COORD_1, gl_MAP2_TEXTURE_COORD_2, gl_MAP2_TEXTURE_COORD_3, gl_MAP2_TEXTURE_COORD_4, gl_MAP2_VERTEX_3, gl_MAP2_VERTEX_4, gl_MAP_COLOR, gl_MAP_STENCIL, gl_MATRIX_MODE, gl_MAX, gl_MAX_3D_TEXTURE_SIZE, gl_MAX_ATTRIB_STACK_DEPTH, gl_MAX_CLIENT_ATTRIB_STACK_DEPTH, gl_MAX_CLIP_PLANES, gl_MAX_CUBE_MAP_TEXTURE_SIZE, gl_MAX_ELEMENTS_INDICES, gl_MAX_ELEMENTS_VERTICES, gl_MAX_EVAL_ORDER, gl_MAX_LIGHTS, gl_MAX_LIST_NESTING, gl_MAX_MODELVIEW_STACK_DEPTH, gl_MAX_NAME_STACK_DEPTH, gl_MAX_PIXEL_MAP_TABLE, gl_MAX_PROJECTION_STACK_DEPTH, gl_MAX_TEXTURE_LOD_BIAS, gl_MAX_TEXTURE_SIZE, gl_MAX_TEXTURE_STACK_DEPTH, gl_MAX_TEXTURE_UNITS, gl_MAX_VIEWPORT_DIMS, gl_MIN, gl_MIRRORED_REPEAT, gl_MODELVIEW, gl_MODELVIEW_MATRIX, gl_MODELVIEW_STACK_DEPTH, gl_MODULATE, gl_MULT, gl_MULTISAMPLE, gl_MULTISAMPLE_BIT, gl_N3F_V3F, gl_NAME_STACK_DEPTH, gl_NAND, gl_NEAREST, gl_NEAREST_MIPMAP_LINEAR, gl_NEAREST_MIPMAP_NEAREST, gl_NEVER, gl_NICEST, gl_NONE, gl_NOOP, gl_NOR, gl_NORMALIZE, gl_NORMAL_ARRAY, gl_NORMAL_ARRAY_POINTER, gl_NORMAL_ARRAY_STRIDE, gl_NORMAL_ARRAY_TYPE, gl_NORMAL_MAP, gl_NOTEQUAL, gl_NO_ERROR, gl_NUM_COMPRESSED_TEXTURE_FORMATS, gl_OBJECT_LINEAR, gl_OBJECT_PLANE, gl_ONE, gl_ONE_MINUS_CONSTANT_ALPHA, gl_ONE_MINUS_CONSTANT_COLOR, gl_ONE_MINUS_DST_ALPHA, gl_ONE_MINUS_DST_COLOR, gl_ONE_MINUS_SRC_ALPHA, gl_ONE_MINUS_SRC_COLOR, gl_OPERAND0_ALPHA, gl_OPERAND0_RGB, gl_OPERAND1_ALPHA, gl_OPERAND1_RGB, gl_OPERAND2_ALPHA, gl_OPERAND2_RGB, gl_OR, gl_ORDER, gl_OR_INVERTED, gl_OR_REVERSE, gl_OUT_OF_MEMORY, gl_PACK_ALIGNMENT, gl_PACK_IMAGE_HEIGHT, gl_PACK_LSB_FIRST, gl_PACK_ROW_LENGTH, gl_PACK_SKIP_IMAGES, gl_PACK_SKIP_PIXELS, gl_PACK_SKIP_ROWS, gl_PACK_SWAP_BYTES, gl_PASS_THROUGH_TOKEN, gl_PERSPECTIVE_CORRECTION_HINT, gl_PIXEL_MAP_A_TO_A, gl_PIXEL_MAP_A_TO_A_SIZE, gl_PIXEL_MAP_B_TO_B, gl_PIXEL_MAP_B_TO_B_SIZE, gl_PIXEL_MAP_G_TO_G, gl_PIXEL_MAP_G_TO_G_SIZE, gl_PIXEL_MAP_I_TO_A, gl_PIXEL_MAP_I_TO_A_SIZE, gl_PIXEL_MAP_I_TO_B, gl_PIXEL_MAP_I_TO_B_SIZE, gl_PIXEL_MAP_I_TO_G, gl_PIXEL_MAP_I_TO_G_SIZE, gl_PIXEL_MAP_I_TO_I, gl_PIXEL_MAP_I_TO_I_SIZE, gl_PIXEL_MAP_I_TO_R, gl_PIXEL_MAP_I_TO_R_SIZE, gl_PIXEL_MAP_R_TO_R, gl_PIXEL_MAP_R_TO_R_SIZE, gl_PIXEL_MAP_S_TO_S, gl_PIXEL_MAP_S_TO_S_SIZE, gl_PIXEL_MODE_BIT, gl_POINT, gl_POINTS, gl_POINT_BIT, gl_POINT_DISTANCE_ATTENUATION, gl_POINT_FADE_THRESHOLD_SIZE, gl_POINT_SIZE, gl_POINT_SIZE_GRANULARITY, gl_POINT_SIZE_MAX, gl_POINT_SIZE_MIN, gl_POINT_SIZE_RANGE, gl_POINT_SMOOTH, gl_POINT_SMOOTH_HINT, gl_POINT_TOKEN, gl_POLYGON, gl_POLYGON_BIT, gl_POLYGON_MODE, gl_POLYGON_OFFSET_FACTOR, gl_POLYGON_OFFSET_FILL, gl_POLYGON_OFFSET_LINE, gl_POLYGON_OFFSET_POINT, gl_POLYGON_OFFSET_UNITS, gl_POLYGON_SMOOTH, gl_POLYGON_SMOOTH_HINT, gl_POLYGON_STIPPLE, gl_POLYGON_STIPPLE_BIT, gl_POLYGON_TOKEN, gl_POSITION, gl_PREVIOUS, gl_PRIMARY_COLOR, gl_PROJECTION, gl_PROJECTION_MATRIX, gl_PROJECTION_STACK_DEPTH, gl_PROXY_TEXTURE_1D, gl_PROXY_TEXTURE_2D, gl_PROXY_TEXTURE_3D, gl_PROXY_TEXTURE_CUBE_MAP, gl_Q, gl_QUADRATIC_ATTENUATION, gl_QUADS, gl_QUAD_STRIP, gl_R, gl_R3_G3_B2, gl_READ_BUFFER, gl_RED, gl_RED_BIAS, gl_RED_BITS, gl_RED_SCALE, gl_REFLECTION_MAP, gl_RENDER, gl_RENDERER, gl_RENDER_MODE, gl_REPEAT, gl_REPLACE, gl_RESCALE_NORMAL, gl_RETURN, gl_RGB, gl_RGB10, gl_RGB10_A2, gl_RGB12, gl_RGB16, gl_RGB4, gl_RGB5, gl_RGB5_A1, gl_RGB8, gl_RGBA, gl_RGBA12, gl_RGBA16, gl_RGBA2, gl_RGBA4, gl_RGBA8, gl_RGBA_MODE, gl_RGB_SCALE, gl_RIGHT, gl_S, gl_SAMPLES, gl_SAMPLE_ALPHA_TO_COVERAGE, gl_SAMPLE_ALPHA_TO_ONE, gl_SAMPLE_BUFFERS, gl_SAMPLE_COVERAGE, gl_SAMPLE_COVERAGE_INVERT, gl_SAMPLE_COVERAGE_VALUE, gl_SCISSOR_BIT, gl_SCISSOR_BOX, gl_SCISSOR_TEST, gl_SECONDARY_COLOR_ARRAY, gl_SECONDARY_COLOR_ARRAY_POINTER, gl_SECONDARY_COLOR_ARRAY_SIZE, gl_SECONDARY_COLOR_ARRAY_STRIDE, gl_SECONDARY_COLOR_ARRAY_TYPE, gl_SELECT, gl_SELECTION_BUFFER_POINTER, gl_SELECTION_BUFFER_SIZE, gl_SEPARATE_SPECULAR_COLOR, gl_SET, gl_SHADE_MODEL, gl_SHININESS, gl_SHORT, gl_SINGLE_COLOR, gl_SMOOTH, gl_SMOOTH_LINE_WIDTH_GRANULARITY, gl_SMOOTH_LINE_WIDTH_RANGE, gl_SMOOTH_POINT_SIZE_GRANULARITY, gl_SMOOTH_POINT_SIZE_RANGE, gl_SOURCE0_ALPHA, gl_SOURCE0_RGB, gl_SOURCE1_ALPHA, gl_SOURCE1_RGB, gl_SOURCE2_ALPHA, gl_SOURCE2_RGB, gl_SPECULAR, gl_SPHERE_MAP, gl_SPOT_CUTOFF, gl_SPOT_DIRECTION, gl_SPOT_EXPONENT, gl_SRC_ALPHA, gl_SRC_ALPHA_SATURATE, gl_SRC_COLOR, gl_STACK_OVERFLOW, gl_STACK_UNDERFLOW, gl_STENCIL, gl_STENCIL_BITS, gl_STENCIL_BUFFER_BIT, gl_STENCIL_CLEAR_VALUE, gl_STENCIL_FAIL, gl_STENCIL_FUNC, gl_STENCIL_INDEX, gl_STENCIL_PASS_DEPTH_FAIL, gl_STENCIL_PASS_DEPTH_PASS, gl_STENCIL_REF, gl_STENCIL_TEST, gl_STENCIL_VALUE_MASK, gl_STENCIL_WRITEMASK, gl_STEREO, gl_SUBPIXEL_BITS, gl_SUBTRACT, gl_T, gl_T2F_C3F_V3F, gl_T2F_C4F_N3F_V3F, gl_T2F_C4UB_V3F, gl_T2F_N3F_V3F, gl_T2F_V3F, gl_T4F_C4F_N3F_V4F, gl_T4F_V4F, gl_TEXTURE, gl_TEXTURE0, gl_TEXTURE1, gl_TEXTURE10, gl_TEXTURE11, gl_TEXTURE12, gl_TEXTURE13, gl_TEXTURE14, gl_TEXTURE15, gl_TEXTURE16, gl_TEXTURE17, gl_TEXTURE18, gl_TEXTURE19, gl_TEXTURE2, gl_TEXTURE20, gl_TEXTURE21, gl_TEXTURE22, gl_TEXTURE23, gl_TEXTURE24, gl_TEXTURE25, gl_TEXTURE26, gl_TEXTURE27, gl_TEXTURE28, gl_TEXTURE29, gl_TEXTURE3, gl_TEXTURE30, gl_TEXTURE31, gl_TEXTURE4, gl_TEXTURE5, gl_TEXTURE6, gl_TEXTURE7, gl_TEXTURE8, gl_TEXTURE9, gl_TEXTURE_1D, gl_TEXTURE_2D, gl_TEXTURE_3D, gl_TEXTURE_ALPHA_SIZE, gl_TEXTURE_BASE_LEVEL, gl_TEXTURE_BINDING_1D, gl_TEXTURE_BINDING_2D, gl_TEXTURE_BINDING_3D, gl_TEXTURE_BINDING_CUBE_MAP, gl_TEXTURE_BIT, gl_TEXTURE_BLUE_SIZE, gl_TEXTURE_BORDER, gl_TEXTURE_BORDER_COLOR, gl_TEXTURE_COMPARE_FUNC, gl_TEXTURE_COMPARE_MODE, gl_TEXTURE_COMPONENTS, gl_TEXTURE_COMPRESSED, gl_TEXTURE_COMPRESSED_IMAGE_SIZE, gl_TEXTURE_COMPRESSION_HINT, gl_TEXTURE_COORD_ARRAY, gl_TEXTURE_COORD_ARRAY_POINTER, gl_TEXTURE_COORD_ARRAY_SIZE, gl_TEXTURE_COORD_ARRAY_STRIDE, gl_TEXTURE_COORD_ARRAY_TYPE, gl_TEXTURE_CUBE_MAP, gl_TEXTURE_CUBE_MAP_NEGATIVE_X, gl_TEXTURE_CUBE_MAP_NEGATIVE_Y, gl_TEXTURE_CUBE_MAP_NEGATIVE_Z, gl_TEXTURE_CUBE_MAP_POSITIVE_X, gl_TEXTURE_CUBE_MAP_POSITIVE_Y, gl_TEXTURE_CUBE_MAP_POSITIVE_Z, gl_TEXTURE_DEPTH, gl_TEXTURE_DEPTH_SIZE, gl_TEXTURE_ENV, gl_TEXTURE_ENV_COLOR, gl_TEXTURE_ENV_MODE, gl_TEXTURE_FILTER_CONTROL, gl_TEXTURE_GEN_MODE, gl_TEXTURE_GEN_Q, gl_TEXTURE_GEN_R, gl_TEXTURE_GEN_S, gl_TEXTURE_GEN_T, gl_TEXTURE_GREEN_SIZE, gl_TEXTURE_HEIGHT, gl_TEXTURE_INTENSITY_SIZE, gl_TEXTURE_INTERNAL_FORMAT, gl_TEXTURE_LOD_BIAS, gl_TEXTURE_LUMINANCE_SIZE, gl_TEXTURE_MAG_FILTER, gl_TEXTURE_MATRIX, gl_TEXTURE_MAX_LEVEL, gl_TEXTURE_MAX_LOD, gl_TEXTURE_MIN_FILTER, gl_TEXTURE_MIN_LOD, gl_TEXTURE_PRIORITY, gl_TEXTURE_RED_SIZE, gl_TEXTURE_RESIDENT, gl_TEXTURE_STACK_DEPTH, gl_TEXTURE_WIDTH, gl_TEXTURE_WRAP_R, gl_TEXTURE_WRAP_S, gl_TEXTURE_WRAP_T, gl_TRANSFORM_BIT, gl_TRANSPOSE_COLOR_MATRIX, gl_TRANSPOSE_MODELVIEW_MATRIX, gl_TRANSPOSE_PROJECTION_MATRIX, gl_TRANSPOSE_TEXTURE_MATRIX, gl_TRIANGLES, gl_TRIANGLE_FAN, gl_TRIANGLE_STRIP, gl_TRUE, gl_UNPACK_ALIGNMENT, gl_UNPACK_IMAGE_HEIGHT, gl_UNPACK_LSB_FIRST, gl_UNPACK_ROW_LENGTH, gl_UNPACK_SKIP_IMAGES, gl_UNPACK_SKIP_PIXELS, gl_UNPACK_SKIP_ROWS, gl_UNPACK_SWAP_BYTES, gl_UNSIGNED_BYTE, gl_UNSIGNED_BYTE_2_3_3_REV, gl_UNSIGNED_BYTE_3_3_2, gl_UNSIGNED_INT, gl_UNSIGNED_INT_10_10_10_2, gl_UNSIGNED_INT_2_10_10_10_REV, gl_UNSIGNED_INT_8_8_8_8, gl_UNSIGNED_INT_8_8_8_8_REV, gl_UNSIGNED_SHORT, gl_UNSIGNED_SHORT_1_5_5_5_REV, gl_UNSIGNED_SHORT_4_4_4_4, gl_UNSIGNED_SHORT_4_4_4_4_REV, gl_UNSIGNED_SHORT_5_5_5_1, gl_UNSIGNED_SHORT_5_6_5, gl_UNSIGNED_SHORT_5_6_5_REV, gl_V2F, gl_V3F, gl_VENDOR, gl_VERSION, gl_VERTEX_ARRAY, gl_VERTEX_ARRAY_POINTER, gl_VERTEX_ARRAY_SIZE, gl_VERTEX_ARRAY_STRIDE, gl_VERTEX_ARRAY_TYPE, gl_VIEWPORT, gl_VIEWPORT_BIT, gl_XOR, gl_ZERO, gl_ZOOM_X, gl_ZOOM_Y, -- * Functions glAccum, glActiveTexture, glAlphaFunc, glAreTexturesResident, glArrayElement, glBegin, glBindTexture, glBitmap, glBlendColor, glBlendEquation, glBlendFunc, glBlendFuncSeparate, glCallList, glCallLists, glClear, glClearAccum, glClearColor, glClearDepth, glClearIndex, glClearStencil, glClientActiveTexture, glClipPlane, glColor3b, glColor3bv, glColor3d, glColor3dv, glColor3f, glColor3fv, glColor3i, glColor3iv, glColor3s, glColor3sv, glColor3ub, glColor3ubv, glColor3ui, glColor3uiv, glColor3us, glColor3usv, glColor4b, glColor4bv, glColor4d, glColor4dv, glColor4f, glColor4fv, glColor4i, glColor4iv, glColor4s, glColor4sv, glColor4ub, glColor4ubv, glColor4ui, glColor4uiv, glColor4us, glColor4usv, glColorMask, glColorMaterial, glColorPointer, glCompressedTexImage1D, glCompressedTexImage2D, glCompressedTexImage3D, glCompressedTexSubImage1D, glCompressedTexSubImage2D, glCompressedTexSubImage3D, glCopyPixels, glCopyTexImage1D, glCopyTexImage2D, glCopyTexSubImage1D, glCopyTexSubImage2D, glCopyTexSubImage3D, glCullFace, glDeleteLists, glDeleteTextures, glDepthFunc, glDepthMask, glDepthRange, glDisable, glDisableClientState, glDrawArrays, glDrawBuffer, glDrawElements, glDrawPixels, glDrawRangeElements, glEdgeFlag, glEdgeFlagPointer, glEdgeFlagv, glEnable, glEnableClientState, glEnd, glEndList, glEvalCoord1d, glEvalCoord1dv, glEvalCoord1f, glEvalCoord1fv, glEvalCoord2d, glEvalCoord2dv, glEvalCoord2f, glEvalCoord2fv, glEvalMesh1, glEvalMesh2, glEvalPoint1, glEvalPoint2, glFeedbackBuffer, glFinish, glFlush, glFogCoordPointer, glFogCoordd, glFogCoorddv, glFogCoordf, glFogCoordfv, glFogf, glFogfv, glFogi, glFogiv, glFrontFace, glFrustum, glGenLists, glGenTextures, glGetBooleanv, glGetClipPlane, glGetCompressedTexImage, glGetDoublev, glGetError, glGetFloatv, glGetIntegerv, glGetLightfv, glGetLightiv, glGetMapdv, glGetMapfv, glGetMapiv, glGetMaterialfv, glGetMaterialiv, glGetPixelMapfv, glGetPixelMapuiv, glGetPixelMapusv, glGetPointerv, glGetPolygonStipple, glGetString, glGetTexEnvfv, glGetTexEnviv, glGetTexGendv, glGetTexGenfv, glGetTexGeniv, glGetTexImage, glGetTexLevelParameterfv, glGetTexLevelParameteriv, glGetTexParameterfv, glGetTexParameteriv, glHint, glIndexMask, glIndexPointer, glIndexd, glIndexdv, glIndexf, glIndexfv, glIndexi, glIndexiv, glIndexs, glIndexsv, glIndexub, glIndexubv, glInitNames, glInterleavedArrays, glIsEnabled, glIsList, glIsTexture, glLightModelf, glLightModelfv, glLightModeli, glLightModeliv, glLightf, glLightfv, glLighti, glLightiv, glLineStipple, glLineWidth, glListBase, glLoadIdentity, glLoadMatrixd, glLoadMatrixf, glLoadName, glLoadTransposeMatrixd, glLoadTransposeMatrixf, glLogicOp, glMap1d, glMap1f, glMap2d, glMap2f, glMapGrid1d, glMapGrid1f, glMapGrid2d, glMapGrid2f, glMaterialf, glMaterialfv, glMateriali, glMaterialiv, glMatrixMode, glMultMatrixd, glMultMatrixf, glMultTransposeMatrixd, glMultTransposeMatrixf, glMultiDrawArrays, glMultiDrawElements, glMultiTexCoord1d, glMultiTexCoord1dv, glMultiTexCoord1f, glMultiTexCoord1fv, glMultiTexCoord1i, glMultiTexCoord1iv, glMultiTexCoord1s, glMultiTexCoord1sv, glMultiTexCoord2d, glMultiTexCoord2dv, glMultiTexCoord2f, glMultiTexCoord2fv, glMultiTexCoord2i, glMultiTexCoord2iv, glMultiTexCoord2s, glMultiTexCoord2sv, glMultiTexCoord3d, glMultiTexCoord3dv, glMultiTexCoord3f, glMultiTexCoord3fv, glMultiTexCoord3i, glMultiTexCoord3iv, glMultiTexCoord3s, glMultiTexCoord3sv, glMultiTexCoord4d, glMultiTexCoord4dv, glMultiTexCoord4f, glMultiTexCoord4fv, glMultiTexCoord4i, glMultiTexCoord4iv, glMultiTexCoord4s, glMultiTexCoord4sv, glNewList, glNormal3b, glNormal3bv, glNormal3d, glNormal3dv, glNormal3f, glNormal3fv, glNormal3i, glNormal3iv, glNormal3s, glNormal3sv, glNormalPointer, glOrtho, glPassThrough, glPixelMapfv, glPixelMapuiv, glPixelMapusv, glPixelStoref, glPixelStorei, glPixelTransferf, glPixelTransferi, glPixelZoom, glPointParameterf, glPointParameterfv, glPointParameteri, glPointParameteriv, glPointSize, glPolygonMode, glPolygonOffset, glPolygonStipple, glPopAttrib, glPopClientAttrib, glPopMatrix, glPopName, glPrioritizeTextures, glPushAttrib, glPushClientAttrib, glPushMatrix, glPushName, glRasterPos2d, glRasterPos2dv, glRasterPos2f, glRasterPos2fv, glRasterPos2i, glRasterPos2iv, glRasterPos2s, glRasterPos2sv, glRasterPos3d, glRasterPos3dv, glRasterPos3f, glRasterPos3fv, glRasterPos3i, glRasterPos3iv, glRasterPos3s, glRasterPos3sv, glRasterPos4d, glRasterPos4dv, glRasterPos4f, glRasterPos4fv, glRasterPos4i, glRasterPos4iv, glRasterPos4s, glRasterPos4sv, glReadBuffer, glReadPixels, glRectd, glRectdv, glRectf, glRectfv, glRecti, glRectiv, glRects, glRectsv, glRenderMode, glRotated, glRotatef, glSampleCoverage, glScaled, glScalef, glScissor, glSecondaryColor3b, glSecondaryColor3bv, glSecondaryColor3d, glSecondaryColor3dv, glSecondaryColor3f, glSecondaryColor3fv, glSecondaryColor3i, glSecondaryColor3iv, glSecondaryColor3s, glSecondaryColor3sv, glSecondaryColor3ub, glSecondaryColor3ubv, glSecondaryColor3ui, glSecondaryColor3uiv, glSecondaryColor3us, glSecondaryColor3usv, glSecondaryColorPointer, glSelectBuffer, glShadeModel, glStencilFunc, glStencilMask, glStencilOp, glTexCoord1d, glTexCoord1dv, glTexCoord1f, glTexCoord1fv, glTexCoord1i, glTexCoord1iv, glTexCoord1s, glTexCoord1sv, glTexCoord2d, glTexCoord2dv, glTexCoord2f, glTexCoord2fv, glTexCoord2i, glTexCoord2iv, glTexCoord2s, glTexCoord2sv, glTexCoord3d, glTexCoord3dv, glTexCoord3f, glTexCoord3fv, glTexCoord3i, glTexCoord3iv, glTexCoord3s, glTexCoord3sv, glTexCoord4d, glTexCoord4dv, glTexCoord4f, glTexCoord4fv, glTexCoord4i, glTexCoord4iv, glTexCoord4s, glTexCoord4sv, glTexCoordPointer, glTexEnvf, glTexEnvfv, glTexEnvi, glTexEnviv, glTexGend, glTexGendv, glTexGenf, glTexGenfv, glTexGeni, glTexGeniv, glTexImage1D, glTexImage2D, glTexImage3D, glTexParameterf, glTexParameterfv, glTexParameteri, glTexParameteriv, glTexSubImage1D, glTexSubImage2D, glTexSubImage3D, glTranslated, glTranslatef, glVertex2d, glVertex2dv, glVertex2f, glVertex2fv, glVertex2i, glVertex2iv, glVertex2s, glVertex2sv, glVertex3d, glVertex3dv, glVertex3f, glVertex3fv, glVertex3i, glVertex3iv, glVertex3s, glVertex3sv, glVertex4d, glVertex4dv, glVertex4f, glVertex4fv, glVertex4i, glVertex4iv, glVertex4s, glVertex4sv, glVertexPointer, glViewport, glWindowPos2d, glWindowPos2dv, glWindowPos2f, glWindowPos2fv, glWindowPos2i, glWindowPos2iv, glWindowPos2s, glWindowPos2sv, glWindowPos3d, glWindowPos3dv, glWindowPos3f, glWindowPos3fv, glWindowPos3i, glWindowPos3iv, glWindowPos3s, glWindowPos3sv ) where import Graphics.Rendering.OpenGL.Raw.Types import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/Version14.hs
bsd-3-clause
22,637
0
4
3,566
3,532
2,362
1,170
1,165
0
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE RecordWildCards, NamedFieldPuns #-} module BoneDewd.RxPacket where import Control.Applicative ((<$>)) import Data.Binary.Get import Data.Bits import qualified Data.Text as T import Data.Text.Encoding import qualified Data.ByteString as B import Data.Word import BoneDewd.Types import BoneDewd.Util import Text.Printf parse :: ParseState -> RawPacket -> Either String (ParseState,RxPacket) parse PreGameState (RawPacket raw) = Right $ (GameState,ClientAuthKey (runGet getWord32be (strict2lazy raw))) parse state (RawPacket raw) = case parseApp pid raw of Right pkt -> Right (state,pkt) Left err -> Left err where pid = runGet getWord8 (strict2lazy raw) parseApp :: Word8 -> B.ByteString -> Either String RxPacket -- [0x02] MoveRequest parseApp 0x02 raw = runGet getter (strict2lazy raw) where getter = do skip 1 d <- getWord8 s <- getWord8 k <- getWord32be return $ Right (MoveRequest (toEnum (fromIntegral d) :: MobDirection) s k) -- [0x06] UseRequest / PaperDollRequest parseApp 0x06 raw = runGet getter (strict2lazy raw) where getter = do skip 1 res <- getWord32be if (res .&. 0x80000000) == 0x80000000 then return $ Right PaperDollRequest else return $ Right (UseRequest (Serial res)) -- [0x09] LookRequest parseApp 0x09 raw = runGet getter (strict2lazy raw) where getter = do skip 1 Right . LookRequest . Serial <$> getWord32be -- [0x2C] IgnoredPacket (Resurrection Menu? / RunUO ignores it) parseApp 0x2C _ = Right IgnoredPacket -- [0x34] RequestStatus / RequestSkills parseApp 0x34 raw = runGet getter (strict2lazy raw) where getter = do skip 5 t <- getWord8 -- type s <- Serial <$> getWord32be return $ case t of 0x04 -> Right (RequestStatus s) 0x05 -> Right (RequestSkills s) _ -> Left "unknown type for app packet 0x34" -- [0x5D] CharacterLoginRequest parseApp 0x5D raw = runGet getter (strict2lazy raw) where getter = do skip 5 n <- getFixedStringNul 30 -- char name skip 2 f <- getWord32be skip 4 c <- getWord32be skip 16 s <- getWord32be i <- getWord32be return $ Right (CharacterLoginRequest n f c s i) -- [0x72] RequestWarMode parseApp 0x72 raw = runGet getter (strict2lazy raw) where getter = do skip 1 Right . RequestWarMode . toEnum . fromIntegral <$> getWord8 -- [0x73] Ping parseApp 0x73 raw = Right (Ping seqid) where seqid = runGet (skip 1 >> getWord8) (strict2lazy raw) -- [0x80] AccountLoginRequest parseApp 0x80 raw = runGet getter (strict2lazy raw) where getter = do skip 1 u <- getFixedStringNul 30 -- user p <- getFixedStringNul 30 -- password return $ Right (AccountLoginRequest u p) -- [0x91] GameLoginRequest parseApp 0x91 raw = runGet getter (strict2lazy raw) where getter = do skip 1 k <- getWord32be -- key used u <- getFixedStringNul 30 -- user p <- getFixedStringNul 30 -- password return $ Right (GameLoginRequest k u p) -- [0x9B] HelpButton parseApp 0x9B _ = Right HelpButton -- [0xA0] ServerSelect parseApp 0xA0 raw = runGet getter (strict2lazy raw) where getter = do skip 1 i <- getWord8 -- index of server that was selected return $ Right (ServerSelect (fromIntegral i)) -- [0xAD] SpeechRequest parseApp 0xAD raw = runGet getter (strict2lazy raw) where getter = do skip 3 rawType <- getWord8 -- rawtype, need to know if its 0xc0 let t = toEnum (fromIntegral rawType) -- speech type hue <- Hue <$> getWord16be -- color font <- SpeechFont <$> getWord16be -- font lang <- Language <$> getFixedStringNul 4 -- language if rawType .&. 0xC0 == 0xC0 -- need to parse keywords + ascii, then normalize to unicode then do keyLen <- getWord16be let keyLen' = shiftR keyLen 4 -- real len is 12 bit int keyBitsLeft = keyLen' * 12 - 4 keyBytesLeft = (keyBitsLeft + (keyBitsLeft `mod` 8)) `div` 8 strLen = B.length raw - (fromIntegral (14 + keyBytesLeft)) -- skip the remaining keyword bytes skip (fromIntegral keyBytesLeft) txt <- decodeASCII <$> getFixedByteString strLen -- decode leaves the nul, so need to take it out... let txt' = T.take (T.length txt - 1) txt return $ Right (SpeechRequest t hue font lang txt') -- parse in standard unicode fashion else do let strLen = B.length raw - 12 txt <- decodeUtf16BE <$> getFixedByteString strLen -- decode leaves the nul, so need to take it out... let txt' = T.take (T.length txt - 1) txt return $ Right (SpeechRequest t hue font lang txt') -- [0xB5] ChatButton parseApp 0xB5 _ = Right ChatButton -- [0xBD] ClientVersion parseApp 0xBD raw = runGet getter (strict2lazy raw) where plen = B.length raw getter = do skip 3 s <- getFixedStringNul (plen - 3) -- version string return $ Right (ClientVersion s) -- [0xBF] generalized packet parseApp 0xBF raw = runGet getter (strict2lazy raw) where _plen = B.length raw getter = do skip 3 subcmd <- getWord16be case subcmd of 0x05 -> do -- ScreenSize skip 2 x <- getWord16be y <- getWord16be return $ Right (ScreenSize x y) 0x0B -> do -- ClientLanguage l <- getFixedString 3 return $ Right (ClientLanguage l) 0x0C -> do -- ClosedStatusGump s <- Serial <$> getWord32be return $ Right (ClosedStatusGump s) 0x0F -> do -- PopupEntrySelection cid <- getWord32be eid <- getWord8 -- i think this is right, penultima says word16 tho.. return $ Right (PopupEntrySelection cid eid) 0x24 -> do -- unknown. UOSE Introduced (http://docs.polserver.com/packets/index.php?Packet=0xBF) return (Right IgnoredPacket) _ -> return $ Left ("don't know how to parse subcommand of 0xBF: " ++ printf "0x%02x" subcmd ++ "\n" ++ fmtHex raw) -- [0xD7] generalized AOS packet parseApp 0xD7 raw = runGet getter (strict2lazy raw) where _plen = B.length raw getter = do skip 3 _pserial <- getWord32be subcmd <- getWord16be case subcmd of 0x28 -> do -- GuildButton return (Right GuildButton) 0x32 -> do -- QuestButton return (Right QuestButton) _ -> return $ Left ("don't know how to parse subcommand of 0xD7: " ++ printf "0x%02x" subcmd ++ "\n" ++ fmtHex raw) -- [0xD9] IgnoredPacket (unused system/video/hw info) parseApp 0xD9 _ = Right IgnoredPacket -- [0xEF] ClientLoginSeed parseApp 0xEF raw = runGet getter (strict2lazy raw) where getter = do skip 1 seed <- getWord32be verA <- getWord32be verB <- getWord32be verC <- getWord32be verD <- getWord32be return $ Right (ClientLoginSeed seed verA verB verC verD) parseApp pid raw = Left ("don't know how to parse packet: " ++ printf "0x%02X" pid ++ "\n" ++ fmtHex raw)
dreamcodez/bonedewd
src/BoneDewd/RxPacket.hs
bsd-3-clause
8,330
0
19
3,109
2,058
997
1,061
180
12
{-# language CPP #-} -- | = Name -- -- XR_EXT_debug_utils - instance extension -- -- = Specification -- -- See -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_debug_utils XR_EXT_debug_utils> -- in the main specification for complete information. -- -- = Registered Extension Number -- -- 20 -- -- = Revision -- -- 3 -- -- = Extension and Version Dependencies -- -- - Requires OpenXR 1.0 -- -- = See Also -- -- 'PFN_xrDebugUtilsMessengerCallbackEXT', 'DebugUtilsLabelEXT', -- 'DebugUtilsMessengerCallbackDataEXT', -- 'DebugUtilsMessengerCreateInfoEXT', 'DebugUtilsObjectNameInfoEXT', -- 'createDebugUtilsMessengerEXT', 'destroyDebugUtilsMessengerEXT', -- 'sessionBeginDebugUtilsLabelRegionEXT', -- 'sessionEndDebugUtilsLabelRegionEXT', 'sessionInsertDebugUtilsLabelEXT', -- 'setDebugUtilsObjectNameEXT', 'submitDebugUtilsMessageEXT' -- -- = Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_debug_utils OpenXR Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module OpenXR.Extensions.XR_EXT_debug_utils ( setDebugUtilsObjectNameEXT , createDebugUtilsMessengerEXT , withDebugUtilsMessengerEXT , destroyDebugUtilsMessengerEXT , submitDebugUtilsMessageEXT , sessionBeginDebugUtilsLabelRegionEXT , sessionEndDebugUtilsLabelRegionEXT , sessionInsertDebugUtilsLabelEXT , DebugUtilsObjectNameInfoEXT(..) , DebugUtilsLabelEXT(..) , DebugUtilsMessengerCallbackDataEXT(..) , DebugUtilsMessengerCreateInfoEXT(..) , DebugUtilsMessageSeverityFlagsEXT , DebugUtilsMessageSeverityFlagBitsEXT( DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT , DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT , DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT , DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT , .. ) , DebugUtilsMessageTypeFlagsEXT , DebugUtilsMessageTypeFlagBitsEXT( DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT , DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT , DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT , DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT , .. ) , PFN_xrDebugUtilsMessengerCallbackEXT , FN_xrDebugUtilsMessengerCallbackEXT , EXT_debug_utils_SPEC_VERSION , pattern EXT_debug_utils_SPEC_VERSION , EXT_DEBUG_UTILS_EXTENSION_NAME , pattern EXT_DEBUG_UTILS_EXTENSION_NAME , DebugUtilsMessengerEXT(..) ) where import OpenXR.Internal.Utils (enumReadPrec) import OpenXR.Internal.Utils (enumShowsPrec) import OpenXR.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 Foreign.Marshal.Utils (maybePeek) 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 Data.ByteString (packCString) import Data.ByteString (useAsCString) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import OpenXR.CStruct (FromCStruct) import OpenXR.CStruct (FromCStruct(..)) import OpenXR.CStruct (ToCStruct) import OpenXR.CStruct (ToCStruct(..)) import OpenXR.Zero (Zero) import OpenXR.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.C.Types (CChar) 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.ByteString (ByteString) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import OpenXR.NamedType ((:::)) import OpenXR.Core10.FundamentalTypes (Bool32) import OpenXR.Extensions.Handles (DebugUtilsMessengerEXT) import OpenXR.Extensions.Handles (DebugUtilsMessengerEXT(..)) import OpenXR.Extensions.Handles (DebugUtilsMessengerEXT(DebugUtilsMessengerEXT)) import OpenXR.Extensions.Handles (DebugUtilsMessengerEXT_T) import OpenXR.Core10.FundamentalTypes (Flags64) import OpenXR.Core10.Handles (Instance) import OpenXR.Core10.Handles (Instance(..)) import OpenXR.Core10.Handles (Instance(Instance)) import OpenXR.Dynamic (InstanceCmds(pXrCreateDebugUtilsMessengerEXT)) import OpenXR.Dynamic (InstanceCmds(pXrDestroyDebugUtilsMessengerEXT)) import OpenXR.Dynamic (InstanceCmds(pXrSessionBeginDebugUtilsLabelRegionEXT)) import OpenXR.Dynamic (InstanceCmds(pXrSessionEndDebugUtilsLabelRegionEXT)) import OpenXR.Dynamic (InstanceCmds(pXrSessionInsertDebugUtilsLabelEXT)) import OpenXR.Dynamic (InstanceCmds(pXrSetDebugUtilsObjectNameEXT)) import OpenXR.Dynamic (InstanceCmds(pXrSubmitDebugUtilsMessageEXT)) import OpenXR.Core10.Handles (Instance_T) import OpenXR.Core10.Enums.ObjectType (ObjectType) import OpenXR.Exception (OpenXrException(..)) import OpenXR.Core10.Enums.Result (Result) import OpenXR.Core10.Enums.Result (Result(..)) import OpenXR.Core10.Handles (Session) import OpenXR.Core10.Handles (Session(..)) import OpenXR.Core10.Handles (Session(Session)) import OpenXR.Core10.Handles (Session_T) import OpenXR.Core10.Enums.StructureType (StructureType) import OpenXR.Core10.Enums.Result (Result(SUCCESS)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_DEBUG_UTILS_LABEL_EXT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT)) import OpenXR.Extensions.Handles (DebugUtilsMessengerEXT(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrSetDebugUtilsObjectNameEXT :: FunPtr (Ptr Instance_T -> Ptr DebugUtilsObjectNameInfoEXT -> IO Result) -> Ptr Instance_T -> Ptr DebugUtilsObjectNameInfoEXT -> IO Result -- | xrSetDebugUtilsObjectNameEXT - Sets debug utils object name -- -- == Valid Usage -- -- - In the structure pointed to by @nameInfo@, -- 'DebugUtilsObjectNameInfoEXT'::@objectType@ /must/ not be -- 'OpenXR.Core10.Enums.ObjectType.OBJECT_TYPE_UNKNOWN' -- -- - In the structure pointed to by @nameInfo@, -- 'DebugUtilsObjectNameInfoEXT'::@objectHandle@ /must/ not be -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_NULL_HANDLE XR_NULL_HANDLE> -- -- == Valid Usage (Implicit) -- -- - #VUID-xrSetDebugUtilsObjectNameEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to calling -- 'setDebugUtilsObjectNameEXT' -- -- - #VUID-xrSetDebugUtilsObjectNameEXT-instance-parameter# @instance@ -- /must/ be a valid 'OpenXR.Core10.Handles.Instance' handle -- -- - #VUID-xrSetDebugUtilsObjectNameEXT-nameInfo-parameter# @nameInfo@ -- /must/ be a pointer to a valid 'DebugUtilsObjectNameInfoEXT' -- structure -- -- == Thread Safety -- -- - Access to the @objectHandle@ member of the @nameInfo@ parameter -- /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>] -- -- - 'OpenXR.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_OUT_OF_MEMORY' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- Applications /may/ change the name associated with an object simply by -- calling 'setDebugUtilsObjectNameEXT' again with a new string. If -- 'DebugUtilsObjectNameInfoEXT'::@objectName@ is an empty string, then any -- previously set name is removed. -- -- = See Also -- -- 'DebugUtilsObjectNameInfoEXT', 'OpenXR.Core10.Handles.Instance' setDebugUtilsObjectNameEXT :: forall io . (MonadIO io) => -- | @instance@ is the 'OpenXR.Core10.Handles.Instance' that the object was -- created under. Instance -> -- | @nameInfo@ is a pointer to an instance of the -- 'DebugUtilsObjectNameInfoEXT' structure specifying the parameters of the -- name to set on the object. DebugUtilsObjectNameInfoEXT -> io () setDebugUtilsObjectNameEXT instance' nameInfo = liftIO . evalContT $ do let xrSetDebugUtilsObjectNameEXTPtr = pXrSetDebugUtilsObjectNameEXT (case instance' of Instance{instanceCmds} -> instanceCmds) lift $ unless (xrSetDebugUtilsObjectNameEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrSetDebugUtilsObjectNameEXT is null" Nothing Nothing let xrSetDebugUtilsObjectNameEXT' = mkXrSetDebugUtilsObjectNameEXT xrSetDebugUtilsObjectNameEXTPtr nameInfo' <- ContT $ withCStruct (nameInfo) r <- lift $ traceAroundEvent "xrSetDebugUtilsObjectNameEXT" (xrSetDebugUtilsObjectNameEXT' (instanceHandle (instance')) nameInfo') lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrCreateDebugUtilsMessengerEXT :: FunPtr (Ptr Instance_T -> Ptr DebugUtilsMessengerCreateInfoEXT -> Ptr (Ptr DebugUtilsMessengerEXT_T) -> IO Result) -> Ptr Instance_T -> Ptr DebugUtilsMessengerCreateInfoEXT -> Ptr (Ptr DebugUtilsMessengerEXT_T) -> IO Result -- | xrCreateDebugUtilsMessengerEXT - Creates a debug messenger -- -- == Valid Usage (Implicit) -- -- - #VUID-xrCreateDebugUtilsMessengerEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to calling -- 'createDebugUtilsMessengerEXT' -- -- - #VUID-xrCreateDebugUtilsMessengerEXT-instance-parameter# @instance@ -- /must/ be a valid 'OpenXR.Core10.Handles.Instance' handle -- -- - #VUID-xrCreateDebugUtilsMessengerEXT-createInfo-parameter# -- @createInfo@ /must/ be a pointer to a valid -- 'DebugUtilsMessengerCreateInfoEXT' structure -- -- - #VUID-xrCreateDebugUtilsMessengerEXT-messenger-parameter# -- @messenger@ /must/ be a pointer to an -- 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT' handle -- -- == Thread Safety -- -- - Access to @instance@, and any child handles, /must/ be externally -- synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>] -- -- - 'OpenXR.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_OUT_OF_MEMORY' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_LIMIT_REACHED' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- The application /must/ ensure that 'createDebugUtilsMessengerEXT' is not -- executed in parallel with any OpenXR function that is also called with -- @instance@ or child of @instance@. -- -- When an event of interest occurs a debug messenger calls its -- @createInfo@->@userCallback@ with a debug message from the producer of -- the event. Additionally, the debug messenger /must/ filter out any debug -- messages that the application’s callback is not interested in based on -- 'DebugUtilsMessengerCreateInfoEXT' flags, as described below. -- -- = See Also -- -- 'DebugUtilsMessengerCreateInfoEXT', -- 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT', -- 'OpenXR.Core10.Handles.Instance', 'destroyDebugUtilsMessengerEXT' createDebugUtilsMessengerEXT :: forall io . (MonadIO io) => -- | @instance@ is the instance the messenger will be used with. Instance -> -- | @createInfo@ points to an 'DebugUtilsMessengerCreateInfoEXT' structure, -- which contains the callback pointer as well as defines the conditions -- under which this messenger will trigger the callback. DebugUtilsMessengerCreateInfoEXT -> io (DebugUtilsMessengerEXT) createDebugUtilsMessengerEXT instance' createInfo = liftIO . evalContT $ do let cmds = case instance' of Instance{instanceCmds} -> instanceCmds let xrCreateDebugUtilsMessengerEXTPtr = pXrCreateDebugUtilsMessengerEXT cmds lift $ unless (xrCreateDebugUtilsMessengerEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrCreateDebugUtilsMessengerEXT is null" Nothing Nothing let xrCreateDebugUtilsMessengerEXT' = mkXrCreateDebugUtilsMessengerEXT xrCreateDebugUtilsMessengerEXTPtr createInfo' <- ContT $ withCStruct (createInfo) pMessenger <- ContT $ bracket (callocBytes @(Ptr DebugUtilsMessengerEXT_T) 8) free r <- lift $ traceAroundEvent "xrCreateDebugUtilsMessengerEXT" (xrCreateDebugUtilsMessengerEXT' (instanceHandle (instance')) createInfo' (pMessenger)) lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) messenger <- lift $ peek @(Ptr DebugUtilsMessengerEXT_T) pMessenger pure $ (((\h -> DebugUtilsMessengerEXT h cmds ) messenger)) -- | A convenience wrapper to make a compatible pair of calls to -- 'createDebugUtilsMessengerEXT' and 'destroyDebugUtilsMessengerEXT' -- -- To ensure that 'destroyDebugUtilsMessengerEXT' 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. -- withDebugUtilsMessengerEXT :: forall io r . MonadIO io => Instance -> DebugUtilsMessengerCreateInfoEXT -> (io DebugUtilsMessengerEXT -> (DebugUtilsMessengerEXT -> io ()) -> r) -> r withDebugUtilsMessengerEXT instance' createInfo b = b (createDebugUtilsMessengerEXT instance' createInfo) (\(o0) -> destroyDebugUtilsMessengerEXT o0) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrDestroyDebugUtilsMessengerEXT :: FunPtr (Ptr DebugUtilsMessengerEXT_T -> IO Result) -> Ptr DebugUtilsMessengerEXT_T -> IO Result -- | xrDestroyDebugUtilsMessengerEXT - Destroys a debug messenger -- -- == Valid Usage (Implicit) -- -- - #VUID-xrDestroyDebugUtilsMessengerEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to calling -- 'destroyDebugUtilsMessengerEXT' -- -- - #VUID-xrDestroyDebugUtilsMessengerEXT-messenger-parameter# -- @messenger@ /must/ be a valid -- 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT' handle -- -- == Thread Safety -- -- - Access to @messenger@ /must/ be externally synchronized -- -- - Access to the 'OpenXR.Core10.Handles.Instance' used to create -- @messenger@, and all of its child handles /must/ be externally -- synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>] -- -- - 'OpenXR.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- The application /must/ ensure that 'destroyDebugUtilsMessengerEXT' is -- not executed in parallel with any OpenXR function that is also called -- with the @instance@ or child of @instance@ that it was created with. -- -- = See Also -- -- 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT', -- 'createDebugUtilsMessengerEXT' destroyDebugUtilsMessengerEXT :: forall io . (MonadIO io) => -- | @messenger@ the 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT' -- object to destroy. @messenger@ is an externally synchronized object and -- /must/ not be used on more than one thread at a time. This means that -- 'destroyDebugUtilsMessengerEXT' /must/ not be called when a callback is -- active. DebugUtilsMessengerEXT -> io () destroyDebugUtilsMessengerEXT messenger = liftIO $ do let xrDestroyDebugUtilsMessengerEXTPtr = pXrDestroyDebugUtilsMessengerEXT (case messenger of DebugUtilsMessengerEXT{instanceCmds} -> instanceCmds) unless (xrDestroyDebugUtilsMessengerEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrDestroyDebugUtilsMessengerEXT is null" Nothing Nothing let xrDestroyDebugUtilsMessengerEXT' = mkXrDestroyDebugUtilsMessengerEXT xrDestroyDebugUtilsMessengerEXTPtr r <- traceAroundEvent "xrDestroyDebugUtilsMessengerEXT" (xrDestroyDebugUtilsMessengerEXT' (debugUtilsMessengerEXTHandle (messenger))) when (r < SUCCESS) (throwIO (OpenXrException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrSubmitDebugUtilsMessageEXT :: FunPtr (Ptr Instance_T -> DebugUtilsMessageSeverityFlagsEXT -> DebugUtilsMessageTypeFlagsEXT -> Ptr DebugUtilsMessengerCallbackDataEXT -> IO Result) -> Ptr Instance_T -> DebugUtilsMessageSeverityFlagsEXT -> DebugUtilsMessageTypeFlagsEXT -> Ptr DebugUtilsMessengerCallbackDataEXT -> IO Result -- | xrSubmitDebugUtilsMessageEXT - Submits debug utils message -- -- == Valid Usage -- -- - For each structure in @objects@ found in @callbackData@, the value -- of 'DebugUtilsObjectNameInfoEXT'::@objectType@ /must/ not be -- 'OpenXR.Core10.Enums.ObjectType.OBJECT_TYPE_UNKNOWN' -- -- == Valid Usage (Implicit) -- -- - #VUID-xrSubmitDebugUtilsMessageEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to calling -- 'submitDebugUtilsMessageEXT' -- -- - #VUID-xrSubmitDebugUtilsMessageEXT-instance-parameter# @instance@ -- /must/ be a valid 'OpenXR.Core10.Handles.Instance' handle -- -- - #VUID-xrSubmitDebugUtilsMessageEXT-messageSeverity-parameter# -- @messageSeverity@ /must/ be a valid combination of -- 'DebugUtilsMessageSeverityFlagBitsEXT' values -- -- - #VUID-xrSubmitDebugUtilsMessageEXT-messageSeverity-requiredbitmask# -- @messageSeverity@ /must/ not be @0@ -- -- - #VUID-xrSubmitDebugUtilsMessageEXT-messageTypes-parameter# -- @messageTypes@ /must/ be a valid combination of -- 'DebugUtilsMessageTypeFlagBitsEXT' values -- -- - #VUID-xrSubmitDebugUtilsMessageEXT-messageTypes-requiredbitmask# -- @messageTypes@ /must/ not be @0@ -- -- - #VUID-xrSubmitDebugUtilsMessageEXT-callbackData-parameter# -- @callbackData@ /must/ be a pointer to a valid -- 'DebugUtilsMessengerCallbackDataEXT' structure -- -- == Return Codes -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>] -- -- - 'OpenXR.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- The application /can/ also produce a debug message, and submit it into -- the OpenXR messaging system. -- -- The call will propagate through the layers and generate callback(s) as -- indicated by the message’s flags. The parameters are passed on to the -- callback in addition to the userData value that was defined at the time -- the messenger was created. -- -- = See Also -- -- 'DebugUtilsMessageSeverityFlagsEXT', 'DebugUtilsMessageTypeFlagsEXT', -- 'DebugUtilsMessengerCallbackDataEXT', 'OpenXR.Core10.Handles.Instance' submitDebugUtilsMessageEXT :: forall io . (MonadIO io) => -- | @instance@ is the debug stream’s 'OpenXR.Core10.Handles.Instance'. Instance -> -- | @messageSeverity@ is a single bit value of -- 'DebugUtilsMessageSeverityFlagsEXT' severity of this event\/message. DebugUtilsMessageSeverityFlagsEXT -> -- | @messageTypes@ is an 'DebugUtilsMessageTypeFlagsEXT' bitmask of -- 'DebugUtilsMessageTypeFlagBitsEXT' specifying which types of event to -- identify this message with. ("messageTypes" ::: DebugUtilsMessageTypeFlagsEXT) -> -- | @callbackData@ contains all the callback related data in the -- 'DebugUtilsMessengerCallbackDataEXT' structure. DebugUtilsMessengerCallbackDataEXT -> io () submitDebugUtilsMessageEXT instance' messageSeverity messageTypes callbackData = liftIO . evalContT $ do let xrSubmitDebugUtilsMessageEXTPtr = pXrSubmitDebugUtilsMessageEXT (case instance' of Instance{instanceCmds} -> instanceCmds) lift $ unless (xrSubmitDebugUtilsMessageEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrSubmitDebugUtilsMessageEXT is null" Nothing Nothing let xrSubmitDebugUtilsMessageEXT' = mkXrSubmitDebugUtilsMessageEXT xrSubmitDebugUtilsMessageEXTPtr callbackData' <- ContT $ withCStruct (callbackData) r <- lift $ traceAroundEvent "xrSubmitDebugUtilsMessageEXT" (xrSubmitDebugUtilsMessageEXT' (instanceHandle (instance')) (messageSeverity) (messageTypes) callbackData') lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrSessionBeginDebugUtilsLabelRegionEXT :: FunPtr (Ptr Session_T -> Ptr DebugUtilsLabelEXT -> IO Result) -> Ptr Session_T -> Ptr DebugUtilsLabelEXT -> IO Result -- | xrSessionBeginDebugUtilsLabelRegionEXT - Session begin debug utils label -- region -- -- == Valid Usage (Implicit) -- -- - #VUID-xrSessionBeginDebugUtilsLabelRegionEXT-extension-notenabled# -- The @XR_EXT_debug_utils@ extension /must/ be enabled prior to -- calling 'sessionBeginDebugUtilsLabelRegionEXT' -- -- - #VUID-xrSessionBeginDebugUtilsLabelRegionEXT-session-parameter# -- @session@ /must/ be a valid 'OpenXR.Core10.Handles.Session' handle -- -- - #VUID-xrSessionBeginDebugUtilsLabelRegionEXT-labelInfo-parameter# -- @labelInfo@ /must/ be a pointer to a valid 'DebugUtilsLabelEXT' -- structure -- -- == Return Codes -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>] -- -- - 'OpenXR.Core10.Enums.Result.SUCCESS' -- -- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_SESSION_LOST' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- The 'sessionBeginDebugUtilsLabelRegionEXT' function begins a label -- region within @session@. -- -- = See Also -- -- 'DebugUtilsLabelEXT', 'OpenXR.Core10.Handles.Session' sessionBeginDebugUtilsLabelRegionEXT :: forall io . (MonadIO io) => -- | @session@ is the 'OpenXR.Core10.Handles.Session' that a label region -- should be associated with. Session -> -- | @labelInfo@ is the 'DebugUtilsLabelEXT' containing the label information -- for the region that should be begun. ("labelInfo" ::: DebugUtilsLabelEXT) -> io (Result) sessionBeginDebugUtilsLabelRegionEXT session labelInfo = liftIO . evalContT $ do let xrSessionBeginDebugUtilsLabelRegionEXTPtr = pXrSessionBeginDebugUtilsLabelRegionEXT (case session of Session{instanceCmds} -> instanceCmds) lift $ unless (xrSessionBeginDebugUtilsLabelRegionEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrSessionBeginDebugUtilsLabelRegionEXT is null" Nothing Nothing let xrSessionBeginDebugUtilsLabelRegionEXT' = mkXrSessionBeginDebugUtilsLabelRegionEXT xrSessionBeginDebugUtilsLabelRegionEXTPtr labelInfo' <- ContT $ withCStruct (labelInfo) r <- lift $ traceAroundEvent "xrSessionBeginDebugUtilsLabelRegionEXT" (xrSessionBeginDebugUtilsLabelRegionEXT' (sessionHandle (session)) labelInfo') lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) pure $ (r) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrSessionEndDebugUtilsLabelRegionEXT :: FunPtr (Ptr Session_T -> IO Result) -> Ptr Session_T -> IO Result -- | xrSessionEndDebugUtilsLabelRegionEXT - Session end debug utils label -- region -- -- == Valid Usage -- -- - 'sessionEndDebugUtilsLabelRegionEXT' /must/ be called only after a -- matching 'sessionBeginDebugUtilsLabelRegionEXT'. -- -- == Valid Usage (Implicit) -- -- - #VUID-xrSessionEndDebugUtilsLabelRegionEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to calling -- 'sessionEndDebugUtilsLabelRegionEXT' -- -- - #VUID-xrSessionEndDebugUtilsLabelRegionEXT-session-parameter# -- @session@ /must/ be a valid 'OpenXR.Core10.Handles.Session' handle -- -- == Return Codes -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>] -- -- - 'OpenXR.Core10.Enums.Result.SUCCESS' -- -- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_SESSION_LOST' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- This function ends the last label region begun with the -- 'sessionBeginDebugUtilsLabelRegionEXT' function within the same -- @session@. -- -- = See Also -- -- 'OpenXR.Core10.Handles.Session' sessionEndDebugUtilsLabelRegionEXT :: forall io . (MonadIO io) => -- | @session@ is the 'OpenXR.Core10.Handles.Session' that a label region -- should be associated with. Session -> io (Result) sessionEndDebugUtilsLabelRegionEXT session = liftIO $ do let xrSessionEndDebugUtilsLabelRegionEXTPtr = pXrSessionEndDebugUtilsLabelRegionEXT (case session of Session{instanceCmds} -> instanceCmds) unless (xrSessionEndDebugUtilsLabelRegionEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrSessionEndDebugUtilsLabelRegionEXT is null" Nothing Nothing let xrSessionEndDebugUtilsLabelRegionEXT' = mkXrSessionEndDebugUtilsLabelRegionEXT xrSessionEndDebugUtilsLabelRegionEXTPtr r <- traceAroundEvent "xrSessionEndDebugUtilsLabelRegionEXT" (xrSessionEndDebugUtilsLabelRegionEXT' (sessionHandle (session))) when (r < SUCCESS) (throwIO (OpenXrException r)) pure $ (r) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrSessionInsertDebugUtilsLabelEXT :: FunPtr (Ptr Session_T -> Ptr DebugUtilsLabelEXT -> IO Result) -> Ptr Session_T -> Ptr DebugUtilsLabelEXT -> IO Result -- | xrSessionInsertDebugUtilsLabelEXT - Session insert debug utils label -- -- == Valid Usage (Implicit) -- -- - #VUID-xrSessionInsertDebugUtilsLabelEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to calling -- 'sessionInsertDebugUtilsLabelEXT' -- -- - #VUID-xrSessionInsertDebugUtilsLabelEXT-session-parameter# @session@ -- /must/ be a valid 'OpenXR.Core10.Handles.Session' handle -- -- - #VUID-xrSessionInsertDebugUtilsLabelEXT-labelInfo-parameter# -- @labelInfo@ /must/ be a pointer to a valid 'DebugUtilsLabelEXT' -- structure -- -- == Return Codes -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>] -- -- - 'OpenXR.Core10.Enums.Result.SUCCESS' -- -- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' -- -- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_SESSION_LOST' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- The 'sessionInsertDebugUtilsLabelEXT' function inserts an individual -- label within @session@. The individual labels are useful for different -- reasons based on the type of debugging scenario. When used with -- something active like a profiler or debugger, it identifies a single -- point of time. When used with logging, the individual label identifies -- that a particular location has been passed at the point the log message -- is triggered. Because of this usage, individual labels only exist in a -- log until the next call to any of the label functions: -- -- - 'sessionBeginDebugUtilsLabelRegionEXT' -- -- - 'sessionEndDebugUtilsLabelRegionEXT' -- -- - 'sessionInsertDebugUtilsLabelEXT' -- -- = See Also -- -- 'DebugUtilsLabelEXT', 'OpenXR.Core10.Handles.Session', -- 'sessionBeginDebugUtilsLabelRegionEXT', -- 'sessionEndDebugUtilsLabelRegionEXT' sessionInsertDebugUtilsLabelEXT :: forall io . (MonadIO io) => -- | @session@ is the 'OpenXR.Core10.Handles.Session' that a label region -- should be associated with. Session -> -- | @labelInfo@ is the 'DebugUtilsLabelEXT' containing the label information -- for the region that should be begun. ("labelInfo" ::: DebugUtilsLabelEXT) -> io (Result) sessionInsertDebugUtilsLabelEXT session labelInfo = liftIO . evalContT $ do let xrSessionInsertDebugUtilsLabelEXTPtr = pXrSessionInsertDebugUtilsLabelEXT (case session of Session{instanceCmds} -> instanceCmds) lift $ unless (xrSessionInsertDebugUtilsLabelEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrSessionInsertDebugUtilsLabelEXT is null" Nothing Nothing let xrSessionInsertDebugUtilsLabelEXT' = mkXrSessionInsertDebugUtilsLabelEXT xrSessionInsertDebugUtilsLabelEXTPtr labelInfo' <- ContT $ withCStruct (labelInfo) r <- lift $ traceAroundEvent "xrSessionInsertDebugUtilsLabelEXT" (xrSessionInsertDebugUtilsLabelEXT' (sessionHandle (session)) labelInfo') lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) pure $ (r) -- | XrDebugUtilsObjectNameInfoEXT - Debug utils object name info -- -- == Valid Usage -- -- - If @objectType@ is -- 'OpenXR.Core10.Enums.ObjectType.OBJECT_TYPE_UNKNOWN', @objectHandle@ -- /must/ not be -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_NULL_HANDLE XR_NULL_HANDLE> -- -- - If @objectType@ is not -- 'OpenXR.Core10.Enums.ObjectType.OBJECT_TYPE_UNKNOWN', @objectHandle@ -- /must/ be -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_NULL_HANDLE XR_NULL_HANDLE> -- or an OpenXR handle of the type associated with @objectType@ -- -- == Valid Usage (Implicit) -- -- - #VUID-XrDebugUtilsObjectNameInfoEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to using -- 'DebugUtilsObjectNameInfoEXT' -- -- - #VUID-XrDebugUtilsObjectNameInfoEXT-type-type# @type@ /must/ be -- 'OpenXR.Core10.Enums.StructureType.TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT' -- -- - #VUID-XrDebugUtilsObjectNameInfoEXT-next-next# @next@ /must/ be -- @NULL@ or a valid pointer to the -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrDebugUtilsObjectNameInfoEXT-objectType-parameter# -- @objectType@ /must/ be a valid -- 'OpenXR.Core10.Enums.ObjectType.ObjectType' value -- -- - #VUID-XrDebugUtilsObjectNameInfoEXT-objectName-parameter# If -- @objectName@ is not @NULL@, @objectName@ /must/ be a null-terminated -- UTF-8 string -- -- = See Also -- -- 'DebugUtilsMessengerCallbackDataEXT', -- 'OpenXR.Core10.Enums.ObjectType.ObjectType', -- 'OpenXR.Core10.Enums.StructureType.StructureType', -- 'setDebugUtilsObjectNameEXT' data DebugUtilsObjectNameInfoEXT = DebugUtilsObjectNameInfoEXT { -- | @objectType@ is an 'OpenXR.Core10.Enums.ObjectType.ObjectType' -- specifying the type of the object to be named. objectType :: ObjectType , -- | @objectHandle@ is the object to be named. objectHandle :: Word64 , -- | @objectName@ is a @NULL@ terminated UTF-8 string specifying the name to -- apply to objectHandle. objectName :: Maybe ByteString } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DebugUtilsObjectNameInfoEXT) #endif deriving instance Show DebugUtilsObjectNameInfoEXT instance ToCStruct DebugUtilsObjectNameInfoEXT where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p DebugUtilsObjectNameInfoEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr ObjectType)) (objectType) lift $ poke ((p `plusPtr` 24 :: Ptr Word64)) (objectHandle) objectName'' <- case (objectName) of Nothing -> pure nullPtr Just j -> ContT $ useAsCString (j) lift $ poke ((p `plusPtr` 32 :: Ptr (Ptr CChar))) objectName'' lift $ f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ObjectType)) (zero) poke ((p `plusPtr` 24 :: Ptr Word64)) (zero) f instance FromCStruct DebugUtilsObjectNameInfoEXT where peekCStruct p = do objectType <- peek @ObjectType ((p `plusPtr` 16 :: Ptr ObjectType)) objectHandle <- peek @Word64 ((p `plusPtr` 24 :: Ptr Word64)) objectName <- peek @(Ptr CChar) ((p `plusPtr` 32 :: Ptr (Ptr CChar))) objectName' <- maybePeek (\j -> packCString (j)) objectName pure $ DebugUtilsObjectNameInfoEXT objectType objectHandle objectName' instance Zero DebugUtilsObjectNameInfoEXT where zero = DebugUtilsObjectNameInfoEXT zero zero Nothing -- | XrDebugUtilsLabelEXT - Debug Utils Label -- -- == Valid Usage (Implicit) -- -- - #VUID-XrDebugUtilsLabelEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to using -- 'DebugUtilsLabelEXT' -- -- - #VUID-XrDebugUtilsLabelEXT-type-type# @type@ /must/ be -- 'OpenXR.Core10.Enums.StructureType.TYPE_DEBUG_UTILS_LABEL_EXT' -- -- - #VUID-XrDebugUtilsLabelEXT-next-next# @next@ /must/ be @NULL@ or a -- valid pointer to the -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrDebugUtilsLabelEXT-labelName-parameter# @labelName@ /must/ -- be a null-terminated UTF-8 string -- -- = See Also -- -- 'DebugUtilsMessengerCallbackDataEXT', -- 'OpenXR.Core10.Enums.StructureType.StructureType', -- 'sessionBeginDebugUtilsLabelRegionEXT', -- 'sessionInsertDebugUtilsLabelEXT' data DebugUtilsLabelEXT = DebugUtilsLabelEXT { -- | @labelName@ is a @NULL@ terminated UTF-8 string specifying the label -- name. labelName :: ByteString } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DebugUtilsLabelEXT) #endif deriving instance Show DebugUtilsLabelEXT instance ToCStruct DebugUtilsLabelEXT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p DebugUtilsLabelEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_LABEL_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) labelName'' <- ContT $ useAsCString (labelName) lift $ poke ((p `plusPtr` 16 :: Ptr (Ptr CChar))) labelName'' lift $ f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_LABEL_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) labelName'' <- ContT $ useAsCString (mempty) lift $ poke ((p `plusPtr` 16 :: Ptr (Ptr CChar))) labelName'' lift $ f instance FromCStruct DebugUtilsLabelEXT where peekCStruct p = do labelName <- packCString =<< peek ((p `plusPtr` 16 :: Ptr (Ptr CChar))) pure $ DebugUtilsLabelEXT labelName instance Zero DebugUtilsLabelEXT where zero = DebugUtilsLabelEXT mempty -- | XrDebugUtilsMessengerCallbackDataEXT - Debug utils messenger callback -- data -- -- == Valid Usage (Implicit) -- -- - #VUID-XrDebugUtilsMessengerCallbackDataEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to using -- 'DebugUtilsMessengerCallbackDataEXT' -- -- - #VUID-XrDebugUtilsMessengerCallbackDataEXT-type-type# @type@ /must/ -- be -- 'OpenXR.Core10.Enums.StructureType.TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT' -- -- - #VUID-XrDebugUtilsMessengerCallbackDataEXT-next-next# @next@ /must/ -- be @NULL@ or a valid pointer to the -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrDebugUtilsMessengerCallbackDataEXT-messageId-parameter# -- @messageId@ /must/ be a null-terminated UTF-8 string -- -- - #VUID-XrDebugUtilsMessengerCallbackDataEXT-functionName-parameter# -- @functionName@ /must/ be a null-terminated UTF-8 string -- -- - #VUID-XrDebugUtilsMessengerCallbackDataEXT-message-parameter# -- @message@ /must/ be a null-terminated UTF-8 string -- -- An 'DebugUtilsMessengerCallbackDataEXT' is a messenger object that -- handles passing along debug messages to a provided debug callback. -- -- Note -- -- This structure should only be considered valid during the lifetime of -- the triggered callback. -- -- The labels listed inside @sessionLabels@ are organized in time order, -- with the most recently generated label appearing first, and the oldest -- label appearing last. -- -- = See Also -- -- 'DebugUtilsLabelEXT', 'DebugUtilsObjectNameInfoEXT', -- 'OpenXR.Core10.Enums.StructureType.StructureType', -- 'submitDebugUtilsMessageEXT' data DebugUtilsMessengerCallbackDataEXT = DebugUtilsMessengerCallbackDataEXT { -- | @messageId@ is a @NULL@ terminated string that identifies the message in -- a unique way. If the callback is triggered by a validation layer, this -- string corresponds the Valid Usage ID (VUID) that can be used to jump to -- the appropriate location in the OpenXR specification. This value /may/ -- be @NULL@ if no unique message identifier is associated with the -- message. messageId :: ByteString , -- | @functionName@ is a @NULL@ terminated string that identifies the OpenXR -- function that was executing at the time the message callback was -- triggered. This value /may/ be @NULL@ in cases where it is difficult to -- determine the originating OpenXR function. functionName :: ByteString , -- | @message@ is a @NULL@ terminated string detailing the trigger -- conditions. message :: ByteString , -- | @objectCount@ is a count of items contained in the @objects@ array. This -- may be @0@. objectCount :: Word32 , -- | @objects@ is a pointer to an array of 'DebugUtilsObjectNameInfoEXT' -- objects related to the detected issue. The array is roughly in order or -- importance, but the 0th element is always guaranteed to be the most -- important object for this message. objects :: Ptr DebugUtilsObjectNameInfoEXT , -- | @sessionLabelCount@ is a count of items contained in the @sessionLabels@ -- array. This may be @0@. sessionLabelCount :: Word32 , -- | @sessionLabels@ is a pointer to an array of 'DebugUtilsLabelEXT' objects -- related to the detected issue. The array is roughly in order or -- importance, but the 0th element is always guaranteed to be the most -- important object for this message. -- -- @sessionLabels@ is NULL or a pointer to an array of 'DebugUtilsLabelEXT' -- active in the current 'OpenXR.Core10.Handles.Session' at the time the -- callback was triggered. Refer to -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#session-labels Session Labels> -- for more information. sessionLabels :: Ptr DebugUtilsLabelEXT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DebugUtilsMessengerCallbackDataEXT) #endif deriving instance Show DebugUtilsMessengerCallbackDataEXT instance ToCStruct DebugUtilsMessengerCallbackDataEXT where withCStruct x f = allocaBytes 72 $ \p -> pokeCStruct p x (f p) pokeCStruct p DebugUtilsMessengerCallbackDataEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) messageId'' <- ContT $ useAsCString (messageId) lift $ poke ((p `plusPtr` 16 :: Ptr (Ptr CChar))) messageId'' functionName'' <- ContT $ useAsCString (functionName) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr CChar))) functionName'' message'' <- ContT $ useAsCString (message) lift $ poke ((p `plusPtr` 32 :: Ptr (Ptr CChar))) message'' lift $ poke ((p `plusPtr` 40 :: Ptr Word32)) (objectCount) lift $ poke ((p `plusPtr` 48 :: Ptr (Ptr DebugUtilsObjectNameInfoEXT))) (objects) lift $ poke ((p `plusPtr` 56 :: Ptr Word32)) (sessionLabelCount) lift $ poke ((p `plusPtr` 64 :: Ptr (Ptr DebugUtilsLabelEXT))) (sessionLabels) lift $ f cStructSize = 72 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) messageId'' <- ContT $ useAsCString (mempty) lift $ poke ((p `plusPtr` 16 :: Ptr (Ptr CChar))) messageId'' functionName'' <- ContT $ useAsCString (mempty) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr CChar))) functionName'' message'' <- ContT $ useAsCString (mempty) lift $ poke ((p `plusPtr` 32 :: Ptr (Ptr CChar))) message'' lift $ f instance FromCStruct DebugUtilsMessengerCallbackDataEXT where peekCStruct p = do messageId <- packCString =<< peek ((p `plusPtr` 16 :: Ptr (Ptr CChar))) functionName <- packCString =<< peek ((p `plusPtr` 24 :: Ptr (Ptr CChar))) message <- packCString =<< peek ((p `plusPtr` 32 :: Ptr (Ptr CChar))) objectCount <- peek @Word32 ((p `plusPtr` 40 :: Ptr Word32)) objects <- peek @(Ptr DebugUtilsObjectNameInfoEXT) ((p `plusPtr` 48 :: Ptr (Ptr DebugUtilsObjectNameInfoEXT))) sessionLabelCount <- peek @Word32 ((p `plusPtr` 56 :: Ptr Word32)) sessionLabels <- peek @(Ptr DebugUtilsLabelEXT) ((p `plusPtr` 64 :: Ptr (Ptr DebugUtilsLabelEXT))) pure $ DebugUtilsMessengerCallbackDataEXT messageId functionName message objectCount objects sessionLabelCount sessionLabels instance Zero DebugUtilsMessengerCallbackDataEXT where zero = DebugUtilsMessengerCallbackDataEXT mempty mempty mempty zero zero zero zero -- | XrDebugUtilsMessengerCreateInfoEXT - Debug utils messenger create info -- -- == Valid Usage -- -- - @userCallback@ /must/ be a valid -- PFN_xrDebugUtilsMessengerCallbackEXT -- -- == Valid Usage (Implicit) -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-extension-notenabled# The -- @XR_EXT_debug_utils@ extension /must/ be enabled prior to using -- 'DebugUtilsMessengerCreateInfoEXT' -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-type-type# @type@ /must/ be -- 'OpenXR.Core10.Enums.StructureType.TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT' -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-next-next# @next@ /must/ be -- @NULL@ or a valid pointer to the -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-messageSeverities-parameter# -- @messageSeverities@ /must/ be a valid combination of -- 'DebugUtilsMessageSeverityFlagBitsEXT' values -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-messageSeverities-requiredbitmask# -- @messageSeverities@ /must/ not be @0@ -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-messageTypes-parameter# -- @messageTypes@ /must/ be a valid combination of -- 'DebugUtilsMessageTypeFlagBitsEXT' values -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-messageTypes-requiredbitmask# -- @messageTypes@ /must/ not be @0@ -- -- - #VUID-XrDebugUtilsMessengerCreateInfoEXT-userCallback-parameter# -- @userCallback@ /must/ be a valid -- 'PFN_xrDebugUtilsMessengerCallbackEXT' value -- -- For each 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT' that is -- created the 'DebugUtilsMessengerCreateInfoEXT'::@messageSeverities@ and -- 'DebugUtilsMessengerCreateInfoEXT'::@messageTypes@ determine when that -- 'DebugUtilsMessengerCreateInfoEXT'::@userCallback@ is called. The -- process to determine if the user’s userCallback is triggered when an -- event occurs is as follows: -- -- - The runtime will perform a bitwise AND of the event’s -- 'DebugUtilsMessageSeverityFlagBitsEXT' with the -- 'DebugUtilsMessengerCreateInfoEXT'::@messageSeverities@ provided -- during creation of the -- 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT' object. -- -- - If this results in @0@, the message is skipped. -- -- - The runtime will perform bitwise AND of the event’s -- 'DebugUtilsMessageTypeFlagBitsEXT' with the -- 'DebugUtilsMessengerCreateInfoEXT'::@messageTypes@ provided during -- the creation of the -- 'OpenXR.Extensions.Handles.DebugUtilsMessengerEXT' object. -- -- - If this results in @0@, the message is skipped. -- -- - If the message of the current event is not skipped, the callback -- will be called with the message. -- -- The callback will come directly from the component that detected the -- event, unless some other layer intercepts the calls for its own purposes -- (filter them in a different way, log to a system error log, etc.). -- -- = See Also -- -- 'PFN_xrDebugUtilsMessengerCallbackEXT', -- 'DebugUtilsMessageSeverityFlagsEXT', 'DebugUtilsMessageTypeFlagsEXT', -- 'OpenXR.Core10.Enums.StructureType.StructureType', -- 'createDebugUtilsMessengerEXT' data DebugUtilsMessengerCreateInfoEXT = DebugUtilsMessengerCreateInfoEXT { -- | @messageSeverities@ is a bitmask of -- 'DebugUtilsMessageSeverityFlagBitsEXT' specifying which severity of -- event(s) that will cause this callback to be called. messageSeverities :: DebugUtilsMessageSeverityFlagsEXT , -- | @messageTypes@ is a combination of 'DebugUtilsMessageTypeFlagBitsEXT' -- specifying which type of event(s) will cause this callback to be called. messageTypes :: DebugUtilsMessageTypeFlagsEXT , -- | @userCallback@ is the application defined callback function to call. userCallback :: PFN_xrDebugUtilsMessengerCallbackEXT , -- | @userData@ is arbitrary user data to be passed to the callback. userData :: Ptr () } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DebugUtilsMessengerCreateInfoEXT) #endif deriving instance Show DebugUtilsMessengerCreateInfoEXT instance ToCStruct DebugUtilsMessengerCreateInfoEXT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p DebugUtilsMessengerCreateInfoEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr DebugUtilsMessageSeverityFlagsEXT)) (messageSeverities) poke ((p `plusPtr` 24 :: Ptr DebugUtilsMessageTypeFlagsEXT)) (messageTypes) poke ((p `plusPtr` 32 :: Ptr PFN_xrDebugUtilsMessengerCallbackEXT)) (userCallback) poke ((p `plusPtr` 40 :: Ptr (Ptr ()))) (userData) f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr DebugUtilsMessageSeverityFlagsEXT)) (zero) poke ((p `plusPtr` 24 :: Ptr DebugUtilsMessageTypeFlagsEXT)) (zero) poke ((p `plusPtr` 32 :: Ptr PFN_xrDebugUtilsMessengerCallbackEXT)) (zero) f instance FromCStruct DebugUtilsMessengerCreateInfoEXT where peekCStruct p = do messageSeverities <- peek @DebugUtilsMessageSeverityFlagsEXT ((p `plusPtr` 16 :: Ptr DebugUtilsMessageSeverityFlagsEXT)) messageTypes <- peek @DebugUtilsMessageTypeFlagsEXT ((p `plusPtr` 24 :: Ptr DebugUtilsMessageTypeFlagsEXT)) userCallback <- peek @PFN_xrDebugUtilsMessengerCallbackEXT ((p `plusPtr` 32 :: Ptr PFN_xrDebugUtilsMessengerCallbackEXT)) userData <- peek @(Ptr ()) ((p `plusPtr` 40 :: Ptr (Ptr ()))) pure $ DebugUtilsMessengerCreateInfoEXT messageSeverities messageTypes userCallback userData instance Storable DebugUtilsMessengerCreateInfoEXT where sizeOf ~_ = 48 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero DebugUtilsMessengerCreateInfoEXT where zero = DebugUtilsMessengerCreateInfoEXT zero zero zero zero type DebugUtilsMessageSeverityFlagsEXT = DebugUtilsMessageSeverityFlagBitsEXT -- | XrDebugUtilsMessageSeverityFlagBitsEXT - -- XrDebugUtilsMessageSeverityFlagBitsEXT -- -- = See Also -- -- No cross-references are available newtype DebugUtilsMessageSeverityFlagBitsEXT = DebugUtilsMessageSeverityFlagBitsEXT Flags64 deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- No documentation found for Nested "XrDebugUtilsMessageSeverityFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT = DebugUtilsMessageSeverityFlagBitsEXT 0x0000000000000001 -- No documentation found for Nested "XrDebugUtilsMessageSeverityFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT = DebugUtilsMessageSeverityFlagBitsEXT 0x0000000000000010 -- No documentation found for Nested "XrDebugUtilsMessageSeverityFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT = DebugUtilsMessageSeverityFlagBitsEXT 0x0000000000000100 -- No documentation found for Nested "XrDebugUtilsMessageSeverityFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT = DebugUtilsMessageSeverityFlagBitsEXT 0x0000000000001000 conNameDebugUtilsMessageSeverityFlagBitsEXT :: String conNameDebugUtilsMessageSeverityFlagBitsEXT = "DebugUtilsMessageSeverityFlagBitsEXT" enumPrefixDebugUtilsMessageSeverityFlagBitsEXT :: String enumPrefixDebugUtilsMessageSeverityFlagBitsEXT = "DEBUG_UTILS_MESSAGE_SEVERITY_" showTableDebugUtilsMessageSeverityFlagBitsEXT :: [(DebugUtilsMessageSeverityFlagBitsEXT, String)] showTableDebugUtilsMessageSeverityFlagBitsEXT = [ (DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT, "VERBOSE_BIT_EXT") , (DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT , "INFO_BIT_EXT") , (DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT, "WARNING_BIT_EXT") , (DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT , "ERROR_BIT_EXT") ] instance Show DebugUtilsMessageSeverityFlagBitsEXT where showsPrec = enumShowsPrec enumPrefixDebugUtilsMessageSeverityFlagBitsEXT showTableDebugUtilsMessageSeverityFlagBitsEXT conNameDebugUtilsMessageSeverityFlagBitsEXT (\(DebugUtilsMessageSeverityFlagBitsEXT x) -> x) (\x -> showString "0x" . showHex x) instance Read DebugUtilsMessageSeverityFlagBitsEXT where readPrec = enumReadPrec enumPrefixDebugUtilsMessageSeverityFlagBitsEXT showTableDebugUtilsMessageSeverityFlagBitsEXT conNameDebugUtilsMessageSeverityFlagBitsEXT DebugUtilsMessageSeverityFlagBitsEXT type DebugUtilsMessageTypeFlagsEXT = DebugUtilsMessageTypeFlagBitsEXT -- | XrDebugUtilsMessageTypeFlagBitsEXT - XrDebugUtilsMessageTypeFlagBitsEXT -- -- = See Also -- -- No cross-references are available newtype DebugUtilsMessageTypeFlagBitsEXT = DebugUtilsMessageTypeFlagBitsEXT Flags64 deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- No documentation found for Nested "XrDebugUtilsMessageTypeFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT = DebugUtilsMessageTypeFlagBitsEXT 0x0000000000000001 -- No documentation found for Nested "XrDebugUtilsMessageTypeFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT = DebugUtilsMessageTypeFlagBitsEXT 0x0000000000000002 -- No documentation found for Nested "XrDebugUtilsMessageTypeFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT = DebugUtilsMessageTypeFlagBitsEXT 0x0000000000000004 -- No documentation found for Nested "XrDebugUtilsMessageTypeFlagBitsEXT" "XR_DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT" pattern DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT = DebugUtilsMessageTypeFlagBitsEXT 0x0000000000000008 conNameDebugUtilsMessageTypeFlagBitsEXT :: String conNameDebugUtilsMessageTypeFlagBitsEXT = "DebugUtilsMessageTypeFlagBitsEXT" enumPrefixDebugUtilsMessageTypeFlagBitsEXT :: String enumPrefixDebugUtilsMessageTypeFlagBitsEXT = "DEBUG_UTILS_MESSAGE_TYPE_" showTableDebugUtilsMessageTypeFlagBitsEXT :: [(DebugUtilsMessageTypeFlagBitsEXT, String)] showTableDebugUtilsMessageTypeFlagBitsEXT = [ (DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT , "GENERAL_BIT_EXT") , (DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT , "VALIDATION_BIT_EXT") , (DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, "PERFORMANCE_BIT_EXT") , (DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT, "CONFORMANCE_BIT_EXT") ] instance Show DebugUtilsMessageTypeFlagBitsEXT where showsPrec = enumShowsPrec enumPrefixDebugUtilsMessageTypeFlagBitsEXT showTableDebugUtilsMessageTypeFlagBitsEXT conNameDebugUtilsMessageTypeFlagBitsEXT (\(DebugUtilsMessageTypeFlagBitsEXT x) -> x) (\x -> showString "0x" . showHex x) instance Read DebugUtilsMessageTypeFlagBitsEXT where readPrec = enumReadPrec enumPrefixDebugUtilsMessageTypeFlagBitsEXT showTableDebugUtilsMessageTypeFlagBitsEXT conNameDebugUtilsMessageTypeFlagBitsEXT DebugUtilsMessageTypeFlagBitsEXT type FN_xrDebugUtilsMessengerCallbackEXT = DebugUtilsMessageSeverityFlagsEXT -> ("messageTypes" ::: DebugUtilsMessageTypeFlagsEXT) -> Ptr DebugUtilsMessengerCallbackDataEXT -> ("userData" ::: Ptr ()) -> IO Bool32 -- | PFN_xrDebugUtilsMessengerCallbackEXT - Type of callback function invoked -- by the debug utils -- -- == Parameter Descriptions -- -- = Description -- -- The callback /must/ not call 'destroyDebugUtilsMessengerEXT'. -- -- The callback returns an -- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 > -- that indicates to the calling layer the application’s desire to abort -- the call. A value of 'OpenXR.Core10.FundamentalTypes.TRUE' indicates -- that the application wants to abort this call. If the application -- returns 'OpenXR.Core10.FundamentalTypes.FALSE', the function /must/ not -- be aborted. Applications /should/ always return -- 'OpenXR.Core10.FundamentalTypes.FALSE' so that they see the same -- behavior with and without validation layers enabled. -- -- If the application returns 'OpenXR.Core10.FundamentalTypes.TRUE' from -- its callback and the OpenXR call being aborted returns an -- 'OpenXR.Core10.Enums.Result.Result', the layer will return -- 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE'. -- -- The object pointed to by @callbackData@ (and any pointers in it -- recursively) /must/ be valid during the lifetime of the triggered -- callback. It /may/ become invalid afterwards. -- -- = See Also -- -- 'DebugUtilsMessengerCreateInfoEXT', 'createDebugUtilsMessengerEXT' type PFN_xrDebugUtilsMessengerCallbackEXT = FunPtr FN_xrDebugUtilsMessengerCallbackEXT type EXT_debug_utils_SPEC_VERSION = 3 -- No documentation found for TopLevel "XR_EXT_debug_utils_SPEC_VERSION" pattern EXT_debug_utils_SPEC_VERSION :: forall a . Integral a => a pattern EXT_debug_utils_SPEC_VERSION = 3 type EXT_DEBUG_UTILS_EXTENSION_NAME = "XR_EXT_debug_utils" -- No documentation found for TopLevel "XR_EXT_DEBUG_UTILS_EXTENSION_NAME" pattern EXT_DEBUG_UTILS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_DEBUG_UTILS_EXTENSION_NAME = "XR_EXT_debug_utils"
expipiplus1/vulkan
openxr/src/OpenXR/Extensions/XR_EXT_debug_utils.hs
bsd-3-clause
61,515
2
17
11,783
7,608
4,424
3,184
-1
-1
{-#LANGUAGE MultiParamTypeClasses #-} {-#LANGUAGE OverloadedStrings #-} {-#LANGUAGE ViewPatterns #-} module Twilio.Recording ( -- * Resource Recording(..) , Twilio.Recording.get ) where import Control.Applicative import Control.Error.Safe import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types {- Resource -} data Recording = Recording { sid :: !RecordingSID , dateCreated :: !UTCTime , dateUpdated :: !UTCTime , accountSID :: !AccountSID , callSID :: !CallSID , duration :: !(Maybe Int) , apiVersion :: !APIVersion , uri :: !URI } deriving (Show, Eq) instance FromJSON Recording where parseJSON (Object v) = Recording <$> v .: "sid" <*> (v .: "date_created" >>= parseDateTime) <*> (v .: "date_updated" >>= parseDateTime) <*> v .: "account_sid" <*> v .: "call_sid" <*> (v .: "duration" <&> fmap readZ >>= maybeReturn') <*> v .: "api_version" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) parseJSON _ = mzero instance Get1 RecordingSID Recording where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Recordings/" <> sid <> ".json") -- | Get a 'Recording' by 'RecordingSID'. get :: MonadThrow m => RecordingSID -> TwilioT m Recording get = Resource.get
seagreen/twilio-haskell
src/Twilio/Recording.hs
bsd-3-clause
1,670
0
18
439
390
219
171
64
1
{-# LANGUAGE PolyKinds, DataKinds, TemplateHaskell, TypeFamilies, GADTs, TypeOperators, RankNTypes, FlexibleContexts, UndecidableInstances, FlexibleInstances, ScopedTypeVariables, MultiParamTypeClasses, OverlappingInstances, TemplateHaskell #-} module Oxymoron.Environment.Internal where import Oxymoron.Regions (ShaderResource, R (..)) import qualified Oxymoron.Regions as R import Data.Singletons import Graphics.Rendering.OpenGL.Raw import qualified Graphics.Rendering.OpenGL.Raw as GL import Oxymoron.TypeLevel.AssociativeArray import Control.Monad.State import Oxymoron.Environment.Shader import Oxymoron.Environment.Program import Oxymoron.Environment.Image import Control.Monad.Trans.Region import Control.Monad.Trans.Region.OnExit import Control.Monad.IO.Class ( MonadIO, liftIO ) import qualified Oxymoron.Description.Image as Desc import Oxymoron.TypeLevel.Nat import Oxymoron.TypeLevel.Symbol hiding (Insert) import qualified Oxymoron.Description.Shader as Desc import Oxymoron.Class singletons [d| data Named a = Named Symbol a |] data NamedShader :: Symbol -> (* -> *) -> * where NamedShader :: Sing a -> R Shader s -> NamedShader a s data Env :: Maybe Program -> Maybe (Desc.ImageTarget, Image) -> AssocArray Symbol Image -> AssocArray Symbol Shader -> AssocArray Symbol Program -> * where Env :: { currentProgram :: Sing a, currentImage :: Sing b, images :: Sing c, shaders :: Sing d, programs :: Sing e } -> Env a b c d e type family FromJust (a :: Maybe k) :: k type instance FromJust ('Just x) = x type family HasSource (a :: Maybe Shader) :: Bool type instance HasSource 'Nothing = 'False type instance HasSource ('Just ('ShaderMoved x )) = 'True type instance HasSource ('Just ('ShaderCompiled x)) = 'True type family LookupShaderType (a :: k) (x :: AssocArray a Shader) :: ShaderType type instance LookupShaderType k a = GetShaderType (FromJust (Lookup k a)) -- instead insertShader :: Sing (name :: Symbol) -> Sing (shader :: Shader) -> Env a b c ('AssocArray xs :: AssocArray Symbol Shader) e -> Env a b c ('AssocArray ('( name, shader) ': xs)) e insertShader name value (Env a b c (SAssocArray xs) e) = undefined --Env a b c (SAssocArray undefined) e --(SAssocArray ((name, value) : xs)) glCreateShader :: (MonadIO pr, ToGLenum (Sing (typ :: ShaderType)), SingI (typ :: ShaderType)) => Env a b c ('AssocArray xs) e -> Sing (name :: Symbol) -> Sing (typ :: ShaderType) -> RegionT s pr (Env a b c ('AssocArray ('(name, 'ShaderCreated typ) ': xs)) e, NamedShader name (RegionT s pr)) glCreateShader env name typ = do shaderId <- liftIO $ GL.glCreateShader (toGLenum typ) fin <- onExit $ GL.glDeleteShader shaderId return $ (insertShader name (SShaderCreated typ) env, NamedShader name (R shaderId fin)) glShaderSource :: (AncestorRegion pr cr, MonadIO cr, (Lookup id d) ~ 'Just z, (d' :==: (Insert id ('ShaderMoved (LookupShaderType id d)) d)) ~ 'True) => Env a b c d e -> NamedShader id pr -> cr (Env a b c d' e) glShaderSource x = undefined {-do let shaderId' = x^.shaderId sourcesCount = x^.sources.count sourcesStrings = x^.sources.strings sourcesLengths = x^.sources.lengths liftIO $ GL.glShaderSource shaderId' sourcesCount sourcesStrings sourcesLengths return $ set shaderState SMoved x -} glShaderCompile :: (AncestorRegion pr cr, MonadIO cr, HasSource(Lookup id d) ~ 'True, (d' :==: (Insert id ('ShaderCompiled shader) d)) ~ 'True, ((LookupShaderType id d) :==: (GetShaderDescType shader)) ~'True) => Env a b c d e -> NamedShader id pr -> Sing (shader :: Desc.Shader) -> cr (Env a b c d' e) glShaderCompile = undefined
jfischoff/oxymoron
src/Oxymoron/Environment/Internal.hs
bsd-3-clause
4,243
19
14
1,204
1,177
653
524
81
1
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, FlexibleContexts, CPP, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Language.R.Generator -- Copyright : (c) 2010 David M. Rosenberg -- License : BSD3 -- -- Maintainer : David Rosenberg <[email protected]> -- Stability : experimental -- Portability : portable -- Created : 05/28/10 -- -- Description : -- This module contains the functions used for lexing an list of -- strings (representing either source code lines or interactive -- input) into a stack of tokens. ----------------------------------------------------------------------------- module Language.R.Generator where import Language.R.SrcLocation import Language.R.Token import Language.R.AST {- retokenize :: [Token] -> [Token] -> Maybe [Token] retokenize [] outToks = outToks retokenize inToks outToks = let slurp = takeWhile (\z -> tryBuildSyntaxNode z == []) inToks' inToks' = drop (length slurp) inToks' newSyntax = buildSyntaxNode slurp outToks' = concat [[newSyntax], outToks] in retokenize inToks' outToks' data IdentStatus = IdReserved | IdBuiltin | IdDefined | IdUndefined classifyIdent tk | tk `elem` (map fst rFuncPrims) = IdReserved | tk `elem` rBuiltins = IdBuiltin | tk `elem` (map fst rNameTable) = IdDefined | otherwise = IdUndefined -- | Production rules -- buildStmtExpr rBuiltins = [ "zeroin2", "zeroin", "xzfile", "xspline", "X11", "wsbrowser" "writeLines" , "writeChar", "writeBin", "write.table", "withVisible", "which.min" , "which.max", "warning", "Version", "vector", "utf8ToInt", "url" , "update.formula", "unzip", "unz", "unserializeFromConn" , "unregisterNamespace", "unlockBinding", "unlist", "unlink", "unique" , "undebug", "typeof", "type.convert", "truncate", "toupper", "tolower" , "title", "textConnectionValue", "textConnection", "text", "terms.formula" , "tempfile", "tempdir", "tcrossprod", "t.default", "system", "Sys.unsetenv" , "Sys.umask", "Sys.time", "Sys.sleep", "Sys.setlocale", "Sys.setenv" , "Sys.readlink", "sys.parents", "sys.parent", "sys.on.exit", "sys.nframe" , "Sys.localeconv", "Sys.info", "Sys.glob", "Sys.getpid", "Sys.getlocale" , "Sys.getenv", "sys.function", "sys.frames", "sys.frame", "Sys.chmod" , "sys.calls", "sys.call", "symbols", "switch", "summary.connection" , "substr<-", "substr", "sub", "strwidth", "strtrim", "strsplit", "strptime" , "strheight", "stopHTTPD", "stop", "stdout", "stdin", "stderr", "startHTTPD" , "sprintf", "split", "sort", "sockSelect", "socketConnection", "sink.number" , "sink", "setwd", "setToCConverterActiveStatus", "setTimeLimit" , "setSessionTimeLimit", "seterrmessage", "setEncoding", "set.seed" , "serializeToConn", "select.list", "segments", "seek", "search", "scan" , "saveToConn", "savePlot", "savehistory", "save.to.file", "save", "sample" , "rwilcox", "rweibull", "runif", "rt", "rsignrank", "Rprofmem", "Rprof" , "rpois", "rowSums", "rowMeans", "row", "rnorm", "RNGkind", "rnchisq" , "rnbinom_mu", "rnbinom", "rmultinom", "rlogis", "rlnorm", "rhyper", "rgeom" , "rgb2hsv", "rgb256", "rgb", "rgamma", "rf", "rexp", "restart", "rep.int" , "removeToCConverterActiveStatus", "remove", "registerNamespace", "regexpr" , "reg.finalizer", "rect", "recordGraphics", "Recall", "readTableHead" , "readLines", "readline", "readDCF", "readChar", "readBin", "rchisq" , "rcauchy", "rbinom", "rbind", "rbeta", "rawToChar", "rawToBits", "rawShift" , "rawConnectionValue", "rawConnection", "rapply", "rank", "radixsort" , "R.home", "qwilcox", "qweibull", "qunif", "quit", "qtukey", "qt", "qsort" , "qsignrank", "qpois", "qnt", "qnorm", "qnf", "qnchisq", "qnbinom_mu" , "qnbinom", "qnbeta", "qlogis", "qlnorm", "qhyper", "qgeom", "qgamma", "qf" , "qexp", "qchisq", "qcauchy", "qbinom", "qbeta", "pwilcox", "pweibull" , "putconst", "pushBackLength", "pushBack", "punif", "ptukey", "pt", "psort" , "psignrank", "psigamma", "prmatrix", "printDeferredWarnings" , "print.function", "print.default", "ppois", "POSIXlt2Date", "polyroot" , "polygon", "pnt", "pnorm", "pnf", "pnchisq", "pnbinom_mu", "pnbinom" , "pnbeta", "pmin", "pmax", "pmatch", "plot.xy", "plot.window", "plot.new" , "plogis", "plnorm", "playSnapshot", "pkgbrowser", "pipe", "phyper", "pgeom" , "pgamma", "pf", "pexp", "persp", "pchisq", "pcauchy", "pbinom", "pbeta" , "path.expand", "paste", "parse_Rd", "parse", "parent.frame", "parent.env<-" , "parent.env", "par", "palette", "packBits", "package.manager", "order" , "options", "optimhess", "optim", "open", "object.size", "nsl" , "normalizePath", "nlm", "ngettext", "nextn", "NextMethod", "new.env", "nchar" , "mvfft", "mtext", "model.matrix", "model.frame", "mkUnbound", "mkCode" , "mget", "merge", "menu", "memory.profile", "memDecompress", "memCompress" , "mem.limits", "mean", "matrix", "match.call", "match", "makeLazy" , "makeActiveBinding", "make.unique", "make.names", "machine", "ls" , "lockEnvironment", "lockBinding", "locator", "loadhistory", "loadFromConn2" , "load.from.file", "load", "list.files", "lib.fixup", "lchoose", "lbeta" , "layout", "lapply", "l10n_info", "isSeekable", "isOpen", "isNamespaceEnv" , "islistfactor", "isIncomplete", "isdebugged", "is.vector", "is.unsorted" , "is.loaded", "is.builtin.internal", "intToUtf8", "intToBits" , "interruptsSuspended", "inspect", "inherits", "index.search", "importIntoEnv" , "image", "identify", "identical", "icuSetCollate", "iconv", "hsv" , "hsbrowser", "hcl", "gzfile", "gzcon", "gsub", "grepl", "grep", "gregexpr" , "grconvertY", "grconvertX", "gray", "getwd", "gettext", "getSnapshot" , "getRtoCConverterStatus", "getRtoCConverterDescriptions" , "getRegisteredNamespace", "getNumRtoCConverters", "getNamespaceRegistry" , "getGraphicsEvent", "geterrmessage", "getConnection", "getAllConnections" , "get", "gctorture", "gcinfo", "gc", "format.POSIXlt", "format.info", "format" , "formals", "fmin", "flush.console", "flush", "filledcontour", "file.symlink" , "file.show", "file.rename", "file.remove", "file.path", "file.info" , "file.exists", "file.edit", "file.create", "file.copy", "file.choose" , "file.append", "file.access", "file", "fifo", "fft", "exists" , "eval.with.vis", "eval", "erase", "environmentName", "environmentIsLocked" , "environment", "env2list", "env.profile", "Encoding", "encodeString", "edit" , "eapply", "dyn.unload", "dyn.load", "dwilcox", "dweibull", "duplicated" , "dunif", "dump", "dtukey", "dt", "dsignrank", "drop", "dput", "dpois" , "download", "do.call", "dnt", "dnorm", "dnf", "dnchisq", "dnbinom_mu" , "dnbinom", "dnbeta", "dlogis", "dlnorm", "disassemble", "dirname", "dirchmod" , "dir.create", "dhyper", "dgeom", "dgamma", "df", "dexp", "devAskNewPage" , "dev.size", "dev.set", "dev.prev", "dev.off", "dev.next", "dev.displaylist" , "dev.cur", "dev.copy", "dev.control", "detach", "deriv.default", "deparseRd" , "deparse", "dend.window", "dend", "delayedAssign", "debugonce", "debug" , "dchisq", "dcauchy", "dbinom", "dbeta", "Date2POSIXlt", "date", "dataviewer" , "dataentry", "data.manager", "D", "Cstack_info", "crossprod", "cov" , "count.fields", "cor", "contourLines", "contour", "complex", "complete.cases" , "comment<-", "comment", "commandArgs", "colSums", "colors", "colMeans" , "col2rgb", "col", "codeFiles.append", "close", "clip", "clearPushBack" , "choose", "chartr", "charToRaw", "charmatch", "cbind", "cat" , "capabilitiesX11", "capabilities", "cairo", "bzfile", "builtins" , "browserText", "browserSetDebug", "browserCondition", "box", "bodyCode" , "body", "bindtextdomain", "bindingIsLocked", "bindingIsActive", "beta" , "besselY", "besselK", "besselJ", "besselI", "bcVersion", "bcClose" , "basename", "axis", "attach", "atan2", "assign", "as.vector", "as.POSIXlt" , "as.POSIXct", "as.function.default", "arrows", "args", "aqua.custom.print" , "aperm", "anyDuplicated", "all.names", "agrep", "addhistory", "abline" , "abbreviate", ".signalCondition", ".resetCondHands", ".invokeRestart" , ".getRestart", ".dfltWarn", ".dfltStop", ".addTryHandlers", ".addRestart" , ".addCondHands" ] -}
rosenbergdm/language-r
src/Language/R/Generator.hs
bsd-3-clause
8,286
0
4
1,085
43
35
8
5
0
module Control.Error.Util.ExtendedSpec (spec) where import Control.Error.Util.Extended import Test.Tasty import Test.Tasty.QuickCheck as QC import Test.QuickCheck import Test.QuickCheck.Instances spec :: TestTree spec = testGroup "Control.Error.Util.Extended" [ QC.testProperty "`someFunction` should pass" someFunction ] someFunction :: Bool -> Property someFunction x = not (not $ x) === x
athanclark/errors-mtl
test/Control/Error/Util/ExtendedSpec.hs
bsd-3-clause
407
0
8
59
100
59
41
12
1
----------------------------------------------------------------------------- -- | -- Module : ForSyDe.Shallow.MoC.Adaptivity -- Copyright : (c) ForSyDe Group, KTH 2007-2008 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Adaptivity Library, yet to be completed. -- ----------------------------------------------------------------------------- module ForSyDe.Shallow.MoC.Adaptivity ( applyfSY, applyf2SY, applyf3SY, applyfU ) where import ForSyDe.Shallow.Core.Signal import ForSyDe.Shallow.MoC.Synchronous.Lib import ForSyDe.Shallow.MoC.Untimed applyfSY :: Signal (a -> b) -> Signal a -> Signal b applyfSY = zipWithSY ($) applyf2SY :: Signal (a -> c -> d) -> Signal a -> Signal c -> Signal d applyf2SY = zipWith3SY ($) applyf3SY :: Signal (a -> c -> d -> e) -> Signal a -> Signal c -> Signal d -> Signal e applyf3SY = zipWith4SY ($) applyfU :: Int -> Signal ([a] -> [b]) -> Signal a -> Signal b applyfU tokenNum = comb2UC tokenNum apply where apply f = f
forsyde/forsyde-shallow
src/ForSyDe/Shallow/MoC/Adaptivity.hs
bsd-3-clause
1,107
0
10
201
269
150
119
17
1
{-# Language RecordWildCards #-} module SymVerify () where import SymVector import SymMap import SymBoilerPlate import Language.Haskell.Liquid.Prelude state0 :: State state0 = undefined sched0 :: State -> [Pid] sched0 state = undefined check = runState state0 emptyVec emptyVec2D (sched0 state0) {-@ runState :: state:{v:State | pidR0PtrW0 v >= 0 && (pidR0Pc v = (-1) => x_loop_0 v = r2 v) && ((pidR0Pc v = 1 || pidR0Pc v = 2 || pidR0Pc v = 3) => x_loop_0 v < r2 v) && (x_loop_0 v <= r2 v) && x_1 v = r2 v && x_loop_0 v >= 0 } -> Vec<{\i -> false}, {\x y -> true}> (Val Pid) -> Vec2D<{\p i -> 0 <= p && p <= x_loop_0 state && (pidR0Pc state != 3 => p < x_loop_0 state) && 0 <= i && i < Map_select (pidR2PtrW0 state) p },{\p i v -> true}> (Val Pid) -> [Pid_pre {v:Int | Map_select (pidR2PtrW0 state) v >= 0 && 0 <= v && v < r2 state && Map_select (pidR2PtrW0 state) v <= 1 && ((pidR0Pc state = 3) => ((Map_select (pidR2PtrW0 state) v = 1) <=> v <= x_loop_0 state)) && ((pidR0Pc state != 3) => ((Map_select (pidR2PtrW0 state) v = 1) <=> v < x_loop_0 state))}] -> () @-} runState :: State -> Vec (Val Pid) -> Vec2D (Val Pid) -> [Pid] -> () runState state@State{pidR2PtrW0 = pidR2PtrW0,..} pidR0Buf0 pidR2Buf0 (PIDR0 : PIDR2 i : sched) | ((pidR0Pc == 0) && (x_loop_0 < x_1)) = runState state{pidR0Pc = 1} pidR0Buf0 pidR2Buf0 sched | ((pidR0Pc == 0) && (not (x_loop_0 < x_1))) = runState state{pidR0Pc = (-1)} pidR0Buf0 pidR2Buf0 sched | (pidR0Pc == 1) = runState state{pidR0Pc = 2} pidR0Buf0 pidR2Buf0 sched | (pidR0Pc == 2) && (i == x_loop_0) = {-@ qualif Upd(v:State, w:State): pidR2PtrW0 v = Map_store (pidR2PtrW0 w) (x_loop_0 w) (Map_select (pidR2PtrW0 w) (x_loop_0 w) + 1) @-} {-@ qualif MapUpd(v:Map_t Int Int, w:Map_t Int Int, s:State): v = Map_store w (x_loop_0 s) (Map_select w (x_loop_0 s) + 1) @-} {-@ qualif PcEq3(v:State): pidR0Pc v = 3 @-} runState state{ pidR2PtrW0 = (put pidR2PtrW0 x_loop_0 ((get pidR2PtrW0 x_loop_0) + 1)), pidR0Pc = 3} pidR0Buf0 (setVec2D x_loop_0 (get pidR2PtrW0 x_loop_0) VUnit pidR2Buf0) sched | (pidR0Pc == 3) = runState state{x_loop_0 = x_loop_0 + 1, pidR0Pc = 0} pidR0Buf0 pidR2Buf0 sched | (pidR0Pc == (-1)) = liquidAssert (x_loop_0 == r2) () runState state@State{..} pidR0Buf0 pidR2Buf0 ((PIDR2 ir2) : sched) | ((get pidR2Pc ir2) == 0) = runState state{pidR2Pc = (put pidR2Pc ir2 (-1))} pidR0Buf0 pidR2Buf0 sched runState state@State{..} pidR0Buf0 pidR2Buf0 (PIDR0 : ((PIDR2 ir2) : sched)) = liquidAssert (not ((False || False) && ((((get pidR2PcK (-1)) == r2 - 1) && (False || ((get pidR2Pc ir2) == (-1)))) && (False || (pidR0Pc == (-1)))))) $ () {-@ assume state0 :: {v:State | (pidR0Pc v == 0 && pidR0PtrR0 v == 0 && 0 <= pidR0PtrR0 v && pidR0PtrW0 v == 0 && 0 <= pidR0PtrW0 v && pidR0PtrR0 v <= pidR0PtrW0 v) && (r2 v - 1 == Map_select (pidR2PcK v) 0 && 0 == Map_select (pidR2Pc v) (pidR2K v) && (0 <= pidR2K v && pidR2K v < r2 v) && Map_select (pidR2PcK v) (-1 : int) + Map_select (pidR2PcK v) 0 == r2 v - 1 && 0 == Map_select (pidR2PcK v) (-1 : int)) && x_loop_0 v == 0 && x_1 v == r2 v} @-} {-@ assume sched0 :: state0:State -> [Pid_pre {v:Int | Map_select (pidR2Pc state0) v == 0 && (0 <= v && v < r2 state0) && (Map_select (pidR2PtrR0 state0) v <= 0 && 0 <= Map_select (pidR2PtrW0 state0) v) && Map_select (pidR2PtrW0 state0) v == 0 && 0 <= Map_select (pidR2PtrW0 state0) v}] @-} {-@ data State = State{pidR0Pc :: Int, pidR2Pc :: Map_t Int Int, pidR0PtrR0 :: Int, pidR2PtrR0 :: Map_t Int {v:Int | v >= 0}, pidR0PtrW0 :: Int, pidR2PtrW0 :: Map_t Int {v:Int | v >= 0}, x_loop_0 :: Int, r2 :: Int, pidR2PcK :: Map_t Int Int, pidR2K :: Int, x_1 :: Int} @-} {-@ qualif Deref_pidR0Pc(v:Int, w:State): v = pidR0Pc w @-} {-@ qualif Eq_pidR0Pc(v:State, w:State ): pidR0Pc v = pidR0Pc w @-} {-@ qualif Deref_pidR2Pc(v:Map_t Int Int, w:State): v = pidR2Pc w @-} {-@ qualif Eq_pidR2Pc(v:State, w:State ): pidR2Pc v = pidR2Pc w @-} {-@ qualif Deref_pidR0PtrR0(v:Int, w:State): v = pidR0PtrR0 w @-} {-@ qualif Eq_pidR0PtrR0(v:State, w:State ): pidR0PtrR0 v = pidR0PtrR0 w @-} {-@ qualif Deref_pidR2PtrR0(v:Map_t Int Int, w:State): v = pidR2PtrR0 w @-} {-@ qualif Eq_pidR2PtrR0(v:State, w:State ): pidR2PtrR0 v = pidR2PtrR0 w @-} {-@ qualif Deref_pidR0PtrW0(v:Int, w:State): v = pidR0PtrW0 w @-} {-@ qualif Eq_pidR0PtrW0(v:State, w:State ): pidR0PtrW0 v = pidR0PtrW0 w @-} {-@ qualif Deref_pidR2PtrW0(v:Map_t Int Int, w:State): v = pidR2PtrW0 w @-} {-@ qualif Eq_pidR2PtrW0(v:State, w:State ): pidR2PtrW0 v = pidR2PtrW0 w @-} {-@ qualif Deref_x_loop_0(v:Int, w:State): v = x_loop_0 w @-} {-@ qualif Eq_x_loop_0(v:State, w:State ): x_loop_0 v = x_loop_0 w @-} {-@ qualif Deref_r2(v:Int, w:State): v = r2 w @-} {-@ qualif Eq_r2(v:State, w:State ): r2 v = r2 w @-} {-@ qualif Deref_pidR2PcK(v:Map_t Int Int, w:State): v = pidR2PcK w @-} {-@ qualif Eq_pidR2PcK(v:State, w:State ): pidR2PcK v = pidR2PcK w @-} {-@ qualif Deref_pidR2K(v:Int, w:State): v = pidR2K w @-} {-@ qualif Eq_pidR2K(v:State, w:State ): pidR2K v = pidR2K w @-} {-@ qualif Deref_x_1(v:Int, w:State): v = x_1 w @-} {-@ qualif Eq_x_1(v:State, w:State ): x_1 v = x_1 w @-} data State = State{pidR0Pc :: Int, pidR2Pc :: Map_t Int Int, pidR0PtrR0 :: Int, pidR2PtrR0 :: Map_t Int Int, pidR0PtrW0 :: Int, pidR2PtrW0 :: Map_t Int Int, x_loop_0 :: Int, r2 :: Int, pidR2PcK :: Map_t Int Int, pidR2K :: Int, x_1 :: Int} data Pid_pre p1 = PIDR0 | PIDR2 p1 type Pid = Pid_pre Int isPidR0 PIDR0 = (True) isPidR0 _ = (False) isPidR2 (PIDR2 ir2) = (True) isPidR2 _ = (False) {-@ measure isPidR0 @-} {-@ measure isPidR2 @-} {-@ qualif IterInv(v:State): pidR0Pc v == -1 => x_loop_0 v == r2 v @-} {-@ qualif IterInv(v:State): x_loop_0 v <= r2 v @-} {-@ qualif Iter(v:State): pidR0Pc v == 1 => x_loop_0 v < r2 v @-} {-@ qualif Iter(v:State): pidR0Pc v == 2 => x_loop_0 v < r2 v @-} {-@ qualif Iter(v:State): pidR0Pc v == 3 => x_loop_0 v < r2 v @-}
abakst/symmetry
checker/saved-quals/PingBabyVectors.hs
mit
6,347
0
21
1,562
917
515
402
59
1
{-# LANGUAGE FlexibleInstances #-} {-| This module implements the constraint set consistency checking routines from the specification. -} module Language.K3.TypeSystem.Consistency ( ConsistencyError(..) , checkConsistent , checkClosureConsistent ) where import Control.Applicative import Control.Monad import Data.List.Split import qualified Data.Map as Map import Data.Monoid import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.Set (Set) import qualified Data.Set as Set import Language.K3.Utils.Pretty import Language.K3.TypeSystem.Closure import Language.K3.TypeSystem.Data import Language.K3.TypeSystem.Utils import Language.K3.Utils.Either data ConsistencyError = ImmediateInconsistency ShallowType ShallowType -- ^Indicates that two types were immediately inconsistent. | UnboundedOpaqueVariable OpaqueVar -- ^Indicates that no bounds have been defined for an opaque variable -- which appears in the constraint set. | MultipleOpaqueBounds OpaqueVar [(TypeOrVar,TypeOrVar)] -- ^Indicates that an opaque variable exists in the constraint set and is -- bounded by multiple opaque bounding constraints. | MultipleLowerBoundsForOpaque OpaqueVar [ShallowType] -- ^Indicates that an opaque variable had a bounding constraint which used -- a variable for the lower bound and that variable had multiple concrete -- lower bounds. | MultipleUpperBoundsForOpaque OpaqueVar [ShallowType] -- ^Indicates that an opaque variable had a bounding constraint which used -- a variable for the upper bound and that variable had multiple concrete -- upper bounds. | IncompatibleTupleLengths ShallowType ShallowType -- ^Indicates that two tuples are incompatible due to having different -- lengths. | UnsatisfiedRecordBound ShallowType ShallowType -- ^Indicates that a record type lower bound met a record type upper -- bound and was not a correct subtype. | UnconcatenatableRecordType ShallowType ShallowType OpaqueVar TypeOrVar RecordConcatenationError -- ^Indicates that a given type cannot be concatenated as a lower-bounding -- record. The arguments are, in order: the type which cannot be -- concatenated; its upper bound; the opaque component whose bound was -- being concatenated; that component's bound; and the error from -- record concatenation that occurred. | ConflictingRecordConcatenation RecordConcatenationError -- ^Indicates that a record type was concatenated in such a way that an -- overlap occurred. | IncompatibleTypeQualifiers (Set TQual) (Set TQual) -- ^Indicates that a set of type qualifiers was insufficient. | IncorrectBinaryOperatorArguments BinaryOperator ShallowType ShallowType -- ^Indicates that a binary operator was used with incompatible arguments. | BottomLowerBound ShallowType -- ^Indicates that a type appeared as a lower bound of bottom. | TopUpperBound ShallowType -- ^Indicates that a type appeared as an upper bound of top. deriving (Show) instance Pretty [ConsistencyError] where prettyLines ces = ["["] %$ indent 2 (foldl1 (%$) $ map prettyLines ces) %$ ["]"] instance Pretty ConsistencyError where prettyLines ce = case ce of ImmediateInconsistency t1 t2 -> ["Immediate inconsistency: "] %+ prettyLines t1 %+ [" <: "] %+ prettyLines t2 UnsatisfiedRecordBound t1 t2 -> ["Unsatisfied record bound: "] %+ prettyLines t1 %+ [" <: "] %+ prettyLines t2 BottomLowerBound t -> ["Lower bound of bottom: "] %+ prettyLines t _ -> splitOn "\n" $ show ce type ConsistencyCheck = Either (Seq ConsistencyError) () -- |Determines whether a constraint set is consistent or not. If it is, an -- appropriate consistency error is generated. checkConsistent :: ConstraintSet -> ConsistencyCheck checkConsistent cs = mconcat <$> gatherParallelErrors (map checkSingleInconsistency (csToList cs)) where -- |Determines if a single constraint is inconsistent in and of itself. checkSingleInconsistency :: Constraint -> ConsistencyCheck checkSingleInconsistency c = case c of IntermediateConstraint (CLeft t1) (CLeft t2) -> do unless (isImmediatelyConsistent t1 t2) $ genErr $ ImmediateInconsistency t1 t2 when (t1 == STop && t2 /= STop) $ genErr $ TopUpperBound t2 when (t1 /= SBottom && t2 == SBottom) $ genErr $ BottomLowerBound t1 checkOpaqueBounds t1 checkOpaqueBounds t2 checkTupleInconsistent t1 t2 checkRecordInconsistent t1 t2 checkConcatenationInconsistent t1 QualifiedIntermediateConstraint (CLeft q1) (CLeft q2) -> when (q1 `Set.isProperSubsetOf` q2) $ genErr $ IncompatibleTypeQualifiers q1 q2 _ -> return () isImmediatelyConsistent :: ShallowType -> ShallowType -> Bool isImmediatelyConsistent t1 t2 = t1 == SBottom || t2 == STop || isOpaque t1 || isOpaque t2 || t1 `isPrimitiveSubtype` t2 || sameForm where isOpaque (SOpaque _) = True isOpaque _ = False sameForm = case (t1,t2) of (SFunction _ _, SFunction _ _) -> True (SFunction _ _, _) -> False (STrigger _, STrigger _) -> True (STrigger _, _) -> False (SBool,SBool) -> True (SBool,_) -> False (SInt,SInt) -> True (SInt,_) -> False (SReal,SReal) -> True (SReal,_) -> False (SNumber,SNumber) -> True (SNumber,_) -> False (SString,SString) -> True (SString,_) -> False (SAddress,SAddress) -> True (SAddress,_) -> False (SOption _,SOption _) -> True (SOption _, _) -> False (SIndirection _,SIndirection _) -> True (SIndirection _, _) -> False (STuple _, STuple _) -> True (STuple _, _) -> False (SRecord _ _ _, SRecord _ _ _) -> True (SRecord _ _ _, _) -> False (STop, STop) -> True (STop, _) -> False (SBottom, SBottom) -> True (SBottom, _) -> False (SOpaque _, SOpaque _) -> True (SOpaque _, _) -> False checkTupleInconsistent :: ShallowType -> ShallowType -> ConsistencyCheck checkTupleInconsistent t1 t2 = case (t1,t2) of (STuple xs, STuple xs') -> when (length xs /= length xs') $ genErr $ IncompatibleTupleLengths t1 t2 _ -> return () checkRecordInconsistent :: ShallowType -> ShallowType -> ConsistencyCheck checkRecordInconsistent t1 t2 = case (t1,t2) of (SRecord m1 oas1 _, SRecord m2 oas2 _) | Set.null oas1 && Set.null oas2 -> unless (Map.keysSet m2 `Set.isSubsetOf` Map.keysSet m1) $ genErr $ UnsatisfiedRecordBound t1 t2 (SRecord m oas ctOpt, _) -> mconcat <$> sequence (do oa' <- Set.toList oas (_, ta_U) <- csQuery cs $ QueryOpaqueBounds oa' t_U <- getUpperBoundsOf cs ta_U case recordConcat [t_U, SRecord m (Set.delete oa' oas) ctOpt] of Left err -> return $ Left $ Seq.singleton $ UnconcatenatableRecordType t1 t2 oa' ta_U err Right _ -> return $ Right ()) _ -> return () checkConcatenationInconsistent :: ShallowType -> ConsistencyCheck checkConcatenationInconsistent t = case t of SRecord m oas ctOpt -> mconcat <$> gatherParallelErrors (do oa <- Set.toList oas (_,ta_U) <- csQuery cs $ QueryOpaqueBounds oa t_U <- getUpperBoundsOf cs ta_U case recordConcat [SRecord m oas ctOpt, t_U] of Left err -> return $ genErr $ ConflictingRecordConcatenation err Right _ -> return $ Right () ) _ -> return () checkOpaqueBounds :: ShallowType -> ConsistencyCheck checkOpaqueBounds t = case t of SOpaque oa -> let bounds = csQuery cs $ QueryOpaqueBounds oa in case bounds of [] -> genErr $ UnboundedOpaqueVariable oa _:_:_ -> genErr $ MultipleOpaqueBounds oa bounds [(ta_L,ta_U)] -> let t_Ls = getLowerBoundsOf cs ta_L in let t_Us = getUpperBoundsOf cs ta_U in case (length t_Ls, length t_Us) of (1,1) -> return () (1,_) -> genErr $ MultipleUpperBoundsForOpaque oa t_Us (_,_) -> genErr $ MultipleLowerBoundsForOpaque oa t_Ls _ -> return () genErr :: ConsistencyError -> ConsistencyCheck genErr = Left . Seq.singleton -- |A convenience routine to check if the closure of a constraint set is -- consistent. checkClosureConsistent :: ConstraintSet -> ConsistencyCheck checkClosureConsistent cs = checkConsistent $ calculateClosure cs
DaMSL/K3
src/Language/K3/TypeSystem/Consistency.hs
apache-2.0
8,842
0
23
2,314
2,109
1,102
1,007
160
44
-- Mersenne Prime Numbers import Set import Primes import Base import Data.Char str2int :: String -> Integer str2int string = fromBase 10 (map char2int string) where char2int char = toInteger $ ord(char) - ord('0') mersPrimePowersTo n = Set [ e | e <- primesTo n, isPrime (2^e - 1) ] mersPrimesToPower n = Set [ 2^e - 1 | e <- primesTo n, isPrime (2^e - 1) ] main = do putStrLn "Choose an option:\n\t[1] : Mersenne Prime Powers upto a power 'n'\n\t[2] : Mersenne Prime Numbers upto a power 'n'\n\t[3] : Exit" option <- getLine case option of "1" -> do putStrLn "Enter power" power <- getLine putStrLn ("\nPowers - \n" ++ show (mersPrimePowersTo (str2int power))) "2" -> do putStrLn "Enter power" power <- getLine putStrLn ("\nNumbers - \n" ++ show (mersPrimesToPower (str2int power))) "3" -> do putStrLn "Exiting." {- Choose an option: [1] : Mersenne Prime Powers upto a power 'n' [2] : Mersenne Prime Numbers upto a power 'n' [3] : Exit 1 Enter power 100 Answer - [2,3,5,7,13,17,19,31,61,89] -} {- Choose an option: [1] : Mersenne Prime Powers upto a power 'n' [2] : Mersenne Prime Numbers upto a power 'n' [3] : Exit 2 Enter power 100 Answer - [3,7,31,127,8191,131071,524287,2147483647,2305843009213693951,618970019642690137449562111] -} {- Choose an option: [1] : Mersenne Prime Powers upto a power 'n' [2] : Mersenne Prime Numbers upto a power 'n' [3] : Exit 3 Exiting. -}
rohitjha/DiMPL
examples/mers.hs
bsd-2-clause
1,566
0
19
423
304
147
157
23
3
-------------------------------------------------------------------- -- | -- Module : Flickr.Auth -- Description : flickr.auth - authentication, flickr-style. -- Copyright : (c) Sigbjorn Finne, 2008 -- License : BSD3 -- -- Maintainer: Sigbjorn Finne <[email protected]> -- Stability : provisional -- Portability: portable -- -- Binding to flickr.auth's (signed) API -------------------------------------------------------------------- module Flickr.Auth where import Flickr.Types import Flickr.Types.Import import Flickr.Monad -- | Returns a frob to be used during authentication. -- This method call must be signed. getFrob :: FM AuthFrob getFrob = signedMethod $ do flickTranslate toAuthFrob $ flickCall "flickr.auth.getFrob" [] -- | Returns the credentials attached to an authentication token. -- This call must be signed as specified in the authentication API spec. checkToken :: AuthTokenValue -> FM AuthToken checkToken tok = signedMethod $ do flickTranslate toAuthToken $ flickCall "flickr.auth.checkToken" [("auth_token", tok)] getFullToken :: AuthMiniToken -> FM AuthToken getFullToken mtok = signedMethod $ do flickTranslate toAuthToken $ flickCall "flickr.auth.getFullToken" [("mini_token", mtok)] -- | Returns the auth token for the given frob, if one has been -- attached. This method call must be signed. getToken :: AuthFrob -> FM AuthToken getToken frob = signedMethod $ do flickTranslate toAuthToken $ flickCall "flickr.auth.getToken" [("frob", aFrob frob)]
BeautifulDestinations/hs-flickr
Flickr/Auth.hs
bsd-3-clause
1,515
0
12
233
222
122
100
20
1
module RenameCase1 where foo x = case (baz x) of 1 -> "a" _ -> "b"
mpickering/ghc-exactprint
tests/examples/transform/RenameCase1.hs
bsd-3-clause
77
0
7
26
34
18
16
4
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Main where import Data.Monoid import Data.Maybe (isJust) import qualified Data.Text as T import qualified Data.Text.Template as T import Test.QuickCheck import Control.Applicative genTemplate :: Gen T.Template genTemplate = oneof [ do t <- genText return (T.lit t) , do t1 <- genText t2 <- genText t3 <- genTemplate return (T.lit t1 <> T.placeholder t2 <> t3) , do t1 <- genText t2 <- genTemplate return (T.placeholder t1 <> t2) ] genTemplateString :: Gen T.Text genTemplateString = mconcat <$> listOf (oneof [ genText, ("{{" <>) . (<> "}}") <$> genText ]) genText :: Gen T.Text genText = T.pack <$> listOf1 (elements (['a'..'z'] ++ ['0'..'9'])) main :: IO () main = do -- Parser and pretty printer are compatible quickCheck $ do t <- genTemplate return $ T.parseTemplate (T.printTemplate t) == t quickCheck $ do s <- genTemplateString return $ T.printTemplate (T.parseTemplate s) == s -- printTemplate is a Monoid morphism quickCheck $ T.printTemplate mempty == mempty quickCheck $ do t1 <- genTemplate t2 <- genTemplate return $ T.printTemplate (t1 <> t2) == T.printTemplate t1 <> T.printTemplate t2
dicomgrid/tinytemplate
tests/Main.hs
mit
1,437
0
15
444
440
222
218
36
1
module Main where import Build_doctests (autogen_dir, deps) import Control.Applicative import Control.Monad import Data.List import System.Directory import System.FilePath import Test.DocTest main :: IO () main = getSources >>= \sources -> doctest $ "-isrc" : ("-i" ++ autogen_dir) : "-optP-include" : ("-optP" ++ autogen_dir ++ "/cabal_macros.h") : "-hide-all-packages" : map ("-package="++) deps ++ sources getSources :: IO [FilePath] getSources = filter (isSuffixOf ".hs") <$> go "src" where go dir = do (dirs, files) <- getFilesAndDirectories dir (files ++) . concat <$> mapM go dirs getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath]) getFilesAndDirectories dir = do c <- map (dir </>) . filter (`notElem` ["..", "."]) <$> getDirectoryContents dir (,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c
bgamari/linear
tests/doctests.hs
bsd-3-clause
872
0
14
155
298
160
138
25
1
module Surface ( Surface(..) , mkSphere , mkPlane ) where import Core ( UnitVector, Point(..), Ray(..), Transform(..), RayPosition, VectorUnaryOps(..) , origin, to, neg, toRayPosition, unsafeForceUnitVector, (|.|) ) import Material ( Material ) data Surface = Surface { intersection :: Ray -> Maybe RayPosition , normalAtPoint :: Point -> UnitVector , material :: Material } instance Transform Surface where translate !v (Surface sfcIntersection sfcNormal sfcMaterial) = Surface { intersection = newIntersection , normalAtPoint = newNormal , material = sfcMaterial } where newIntersection !ray = sfcIntersection $ translate nv ray newNormal !pos = sfcNormal $ translate nv pos nv = neg v mkSphere :: Double -> Material -> Surface mkSphere !radius !mat = Surface { intersection = sphereIntersection radius , normalAtPoint = sphereNormal (1.0 / radius) , material = mat } mkPlane :: Point -> UnitVector -> Material -> Surface mkPlane !point !normal !mat = Surface { intersection = planeIntersection point normal , normalAtPoint = const normal , material = mat } sphereIntersection :: Double -> Ray -> Maybe RayPosition sphereIntersection !r (Ray !ro !rd) | det < 0 = Nothing | b - sd > eps = Just $ toRayPosition (b - sd) | b + sd > eps = Just $ toRayPosition (b + sd) | otherwise = Nothing where !op = ro `to` origin !eps = 1e-4 !b = op |.| rd !det = (b * b) - (op |.| op) + (r * r) sd = sqrt det sphereNormal :: Double -> Point -> UnitVector sphereNormal invr p = unsafeForceUnitVector $ (origin `to` p) |*| invr planeIntersection :: Point -> UnitVector -> Ray -> Maybe RayPosition planeIntersection point normal (Ray ro rd) | ln == 0.0 = Nothing | d < 0.0 = Nothing | otherwise = Just $ toRayPosition d where d = ((ro `to` point) |.| normal) / ln ln = rd |.| normal
stu-smith/rendering-in-haskell
src/experiment05/Surface.hs
mit
2,128
0
11
669
687
365
322
-1
-1
{-| Module : Idris.Elab.Transform Description : Transformations for elaborate terms. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} module Idris.Elab.Transform where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Utils import Idris.Elab.Term import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Util.Pretty(pretty, text) elabTransform :: ElabInfo -> FC -> Bool -> PTerm -> PTerm -> Idris (Term, Term) elabTransform info fc safe lhs_in@(PApp _ (PRef _ _ tf) _) rhs_in = do ctxt <- getContext i <- getIState let lhs = addImplPat i lhs_in logElab 5 ("Transform LHS input: " ++ showTmImpls lhs) (ElabResult lhs' dlhs [] ctxt' newDecls highlights newGName, _) <- tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "transLHS") infP initEState (erun fc (buildTC i info ETransLHS [] (sUN "transform") (allNamesIn lhs_in) (infTerm lhs))) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights updateIState $ \i -> i { idris_name = newGName } let lhs_tm = orderPats (getInferTerm lhs') let lhs_ty = getInferType lhs' let newargs = pvars i lhs_tm (clhs_tm_in, clhs_ty) <- recheckC_borrowing False False [] (constraintNS info) fc id [] lhs_tm let clhs_tm = renamepats pnames clhs_tm_in logElab 3 ("Transform LHS " ++ show clhs_tm) logElab 3 ("Transform type " ++ show clhs_ty) let rhs = addImplBound i (map fst newargs) rhs_in logElab 5 ("Transform RHS input: " ++ showTmImpls rhs) ((rhs', defer, ctxt', newDecls, newGName), _) <- tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "transRHS") clhs_ty initEState (do pbinds i lhs_tm setNextName (ElabResult _ _ _ ctxt' newDecls highlights newGName) <- erun fc (build i info ERHS [] (sUN "transform") rhs) set_global_nextname newGName erun fc $ psolve lhs_tm tt <- get_term let (rhs', defer) = runState (collectDeferred Nothing [] ctxt tt) [] newGName <- get_global_nextname return (rhs', defer, ctxt', newDecls, newGName)) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights updateIState $ \i -> i { idris_name = newGName } (crhs_tm_in, crhs_ty) <- recheckC_borrowing False False [] (constraintNS info) fc id [] rhs' let crhs_tm = renamepats pnames crhs_tm_in logElab 3 ("Transform RHS " ++ show crhs_tm) -- Types must always convert case converts ctxt [] clhs_ty crhs_ty of OK _ -> return () Error e -> ierror (At fc (CantUnify False (clhs_tm, Nothing) (crhs_tm, Nothing) e [] 0)) -- In safe mode, values must convert (Thinks: This is probably not -- useful as is, perhaps it should require a proof of equality instead) when safe $ case converts ctxt [] clhs_tm crhs_tm of OK _ -> return () Error e -> ierror (At fc (CantUnify False (clhs_tm, Nothing) (crhs_tm, Nothing) e [] 0)) case unApply (depat clhs_tm) of (P _ tfname _, _) -> do addTrans tfname (clhs_tm, crhs_tm) addIBC (IBCTrans tf (clhs_tm, crhs_tm)) _ -> ierror (At fc (Msg "Invalid transformation rule (must be function application)")) return (clhs_tm, crhs_tm) where depat (Bind n (PVar t) sc) = depat (instantiate (P Bound n t) sc) depat x = x renamepats (n' : ns) (Bind n (PVar t) sc) = Bind n' (PVar t) (renamepats ns sc) -- all Vs renamepats _ sc = sc -- names for transformation variables. Need to ensure these don't clash -- with any other names when applying rules, so rename here. pnames = map (\i -> sMN i ("tvar" ++ show i)) [0..] elabTransform info fc safe lhs_in rhs_in = ierror (At fc (Msg "Invalid transformation rule (must be function application)"))
tpsinnem/Idris-dev
src/Idris/Elab/Transform.hs
bsd-3-clause
5,240
0
19
1,456
1,559
804
755
101
6
module Foo where data Foo = Bar { x :: Int, y :: Bool } foo a = a{x=2} bar = Bar{ x = 1, y = False} foobar = foo (id id bar)
sdiehl/ghc
testsuite/tests/hiefile/should_compile/hie001.hs
bsd-3-clause
129
0
8
38
76
45
31
5
1
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-# LANGUAGE GADTs, KindSignatures, EmptyCase, LambdaCase #-} -- Check some GADTs module EmptyCase004 where import Data.Kind (Type) data A :: Type -> Type where A1 :: A Int A2 :: A Bool -- Non-exhaustive: Missing A2 f1 :: A Bool -> a f1 = \case -- Non-exhaustive: missing both A1 & A2 f2 :: A a -> b f2 = \case -- Exhaustive f3 :: A [a] -> b f3 = \case data B :: Type -> Type -> Type where B1 :: Int -> B Bool Bool B2 :: B Int Bool -- Non-exhaustive: missing (B1 _) g1 :: B a a -> b g1 x = case x of -- Non-exhaustive: missing both (B1 _) & B2 g2 :: B a b -> c g2 = \case -- Exhaustive g3 :: B Char a -> b g3 = \case -- NOTE: A lambda-case always has ONE scrutinee and a lambda case refers -- always to the first of the arguments. Hence, the following warnings are -- valid: -- Non-exhaustive: Missing both A1 & A2 h1 :: A a -> A a -> b h1 = \case h2 :: A a -> B a b -> () h2 A1 = \case -- Non-exhaustive, missing B2 h2 A2 = \case -- Non-exhaustive, missing (B1 _)
sdiehl/ghc
testsuite/tests/pmcheck/should_compile/EmptyCase004.hs
bsd-3-clause
1,041
0
7
248
283
161
122
-1
-1
{- (c) Bartosz Nitka, Facebook 2015 Utilities for efficiently and deterministically computing free variables. -} {-# LANGUAGE BangPatterns #-} module FV ( -- * Deterministic free vars computations FV, InterestingVarFun, -- * Running the computations fvVarListVarSet, fvVarList, fvVarSet, fvDVarSet, -- ** Manipulating those computations unitFV, emptyFV, mkFVs, unionFV, unionsFV, delFV, delFVs, filterFV, mapUnionFV, ) where import Var import VarSet -- | Predicate on possible free variables: returns @True@ iff the variable is -- interesting type InterestingVarFun = Var -> Bool -- Note [Deterministic FV] -- ~~~~~~~~~~~~~~~~~~~~~~~ -- When computing free variables, the order in which you get them affects -- the results of floating and specialization. If you use UniqFM to collect -- them and then turn that into a list, you get them in nondeterministic -- order as described in Note [Deterministic UniqFM] in UniqDFM. -- A naive algorithm for free variables relies on merging sets of variables. -- Merging costs O(n+m) for UniqFM and for UniqDFM there's an additional log -- factor. It's cheaper to incrementally add to a list and use a set to check -- for duplicates. type FV = InterestingVarFun -- Used for filtering sets as we build them -> VarSet -- Locally bound variables -> ([Var], VarSet) -- List to preserve ordering and set to check for membership, -- so that the list doesn't have duplicates -- For explanation of why using `VarSet` is not deterministic see -- Note [Deterministic UniqFM] in UniqDFM. -> ([Var], VarSet) -- Note [FV naming conventions] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- To get the performance and determinism that FV provides, FV computations -- need to built up from smaller FV computations and then evaluated with -- one of `fvVarList`, `fvDVarSet`, `fvVarListVarSet`. That means the functions -- returning FV need to be exported. -- -- The conventions are: -- -- a) non-deterministic functions: -- * a function that returns VarSet -- e.g. `tyVarsOfType` -- b) deterministic functions: -- * a worker that returns FV -- e.g. `tyFVsOfType` -- * a function that returns [Var] -- e.g. `tyVarsOfTypeList` -- * a function that returns DVarSet -- e.g. `tyVarsOfTypeDSet` -- -- Where tyVarsOfType, tyVarsOfTypeList, tyVarsOfTypeDSet are implemented -- in terms of the worker evaluated with fvVarSet, fvVarList, fvDVarSet -- respectively. -- | Run a free variable computation, returning a list of distinct free -- variables in deterministic order and a non-deterministic set containing -- those variables. fvVarListVarSet :: FV -> ([Var], VarSet) fvVarListVarSet fv = fv (const True) emptyVarSet ([], emptyVarSet) -- | Run a free variable computation, returning a list of distinct free -- variables in deterministic order. fvVarList :: FV -> [Var] fvVarList = fst . fvVarListVarSet -- | Run a free variable computation, returning a deterministic set of free -- variables. Note that this is just a wrapper around the version that -- returns a deterministic list. If you need a list you should use -- `fvVarList`. fvDVarSet :: FV -> DVarSet fvDVarSet = mkDVarSet . fst . fvVarListVarSet -- | Run a free variable computation, returning a non-deterministic set of -- free variables. Don't use if the set will be later converted to a list -- and the order of that list will impact the generated code. fvVarSet :: FV -> VarSet fvVarSet = snd . fvVarListVarSet -- Note [FV eta expansion] -- ~~~~~~~~~~~~~~~~~~~~~~~ -- Let's consider an eta-reduced implementation of freeVarsOf using FV: -- -- freeVarsOf (App a b) = freeVarsOf a `unionFV` freeVarsOf b -- -- If GHC doesn't eta-expand it, after inlining unionFV we end up with -- -- freeVarsOf = \x -> -- case x of -- App a b -> \fv_cand in_scope acc -> -- freeVarsOf a fv_cand in_scope $! freeVarsOf b fv_cand in_scope $! acc -- -- which has to create a thunk, resulting in more allocations. -- -- On the other hand if it is eta-expanded: -- -- freeVarsOf (App a b) fv_cand in_scope acc = -- (freeVarsOf a `unionFV` freeVarsOf b) fv_cand in_scope acc -- -- after inlining unionFV we have: -- -- freeVarsOf = \x fv_cand in_scope acc -> -- case x of -- App a b -> -- freeVarsOf a fv_cand in_scope $! freeVarsOf b fv_cand in_scope $! acc -- -- which saves allocations. -- -- GHC when presented with knowledge about all the call sites, correctly -- eta-expands in this case. Unfortunately due to the fact that freeVarsOf gets -- exported to be composed with other functions, GHC doesn't have that -- information and has to be more conservative here. -- -- Hence functions that get exported and return FV need to be manually -- eta-expanded. See also #11146. -- | Add a variable - when free, to the returned free variables. -- Ignores duplicates and respects the filtering function. unitFV :: Id -> FV unitFV var fv_cand in_scope acc@(have, haveSet) | var `elemVarSet` in_scope = acc | var `elemVarSet` haveSet = acc | fv_cand var = (var:have, extendVarSet haveSet var) | otherwise = acc {-# INLINE unitFV #-} -- | Return no free variables. emptyFV :: FV emptyFV _ _ acc = acc {-# INLINE emptyFV #-} -- | Union two free variable computations. unionFV :: FV -> FV -> FV unionFV fv1 fv2 fv_cand in_scope acc = fv1 fv_cand in_scope $! fv2 fv_cand in_scope $! acc {-# INLINE unionFV #-} -- | Mark the variable as not free by putting it in scope. delFV :: Var -> FV -> FV delFV var fv fv_cand !in_scope acc = fv fv_cand (extendVarSet in_scope var) acc {-# INLINE delFV #-} -- | Mark many free variables as not free. delFVs :: VarSet -> FV -> FV delFVs vars fv fv_cand !in_scope acc = fv fv_cand (in_scope `unionVarSet` vars) acc {-# INLINE delFVs #-} -- | Filter a free variable computation. filterFV :: InterestingVarFun -> FV -> FV filterFV fv_cand2 fv fv_cand1 in_scope acc = fv (\v -> fv_cand1 v && fv_cand2 v) in_scope acc {-# INLINE filterFV #-} -- | Map a free variable computation over a list and union the results. mapUnionFV :: (a -> FV) -> [a] -> FV mapUnionFV _f [] _fv_cand _in_scope acc = acc mapUnionFV f (a:as) fv_cand in_scope acc = mapUnionFV f as fv_cand in_scope $! f a fv_cand in_scope $! acc {-# INLINABLE mapUnionFV #-} -- | Union many free variable computations. unionsFV :: [FV] -> FV unionsFV fvs fv_cand in_scope acc = mapUnionFV id fvs fv_cand in_scope acc {-# INLINE unionsFV #-} -- | Add multiple variables - when free, to the returned free variables. -- Ignores duplicates and respects the filtering function. mkFVs :: [Var] -> FV mkFVs vars fv_cand in_scope acc = mapUnionFV unitFV vars fv_cand in_scope acc {-# INLINE mkFVs #-}
olsner/ghc
compiler/utils/FV.hs
bsd-3-clause
6,847
0
9
1,430
792
478
314
65
1
{-# LANGUAGE GADTs #-} module T9096 where data Foo a where MkFoo :: (->) a (Foo a)
ghc-android/ghc
testsuite/tests/gadt/T9096.hs
bsd-3-clause
87
0
8
21
29
18
11
4
0
-- | This module implements a compiler pass for inlining functions, -- then removing those that have become dead. module Futhark.Optimise.InliningDeadFun ( inlineAndRemoveDeadFunctions , removeDeadFunctions ) where import Control.Monad.Reader import Control.Monad.Identity import Data.List import Data.Loc import Data.Maybe import qualified Data.Map.Strict as M import qualified Data.Set as S import Prelude import Futhark.Representation.SOACS import Futhark.Transform.Rename import Futhark.Analysis.CallGraph import Futhark.Binder import Futhark.Pass aggInlining :: CallGraph -> [FunDef] -> [FunDef] aggInlining cg = filter keep . recurse where noInterestingCalls :: S.Set Name -> FunDef -> Bool noInterestingCalls interesting fundec = case M.lookup (funDefName fundec) cg of Just calls | not $ any (`elem` interesting') calls -> True _ -> False where interesting' = funDefName fundec `S.insert` interesting recurse funs = let interesting = S.fromList $ map funDefName funs (to_be_inlined, to_inline_in) = partition (noInterestingCalls interesting) funs inlined_but_entry_points = filter (isJust . funDefEntryPoint) to_be_inlined in if null to_be_inlined then funs else inlined_but_entry_points ++ recurse (map (`doInlineInCaller` to_be_inlined) to_inline_in) keep fundec = isJust (funDefEntryPoint fundec) || callsRecursive fundec callsRecursive fundec = maybe False (any recursive) $ M.lookup (funDefName fundec) cg recursive fname = case M.lookup fname cg of Just calls -> fname `elem` calls Nothing -> False -- | @doInlineInCaller caller inlcallees@ inlines in @calleer@ the functions -- in @inlcallees@. At this point the preconditions are that if @inlcallees@ -- is not empty, and, more importantly, the functions in @inlcallees@ do -- not call any other functions. Further extensions that transform a -- tail-recursive function to a do or while loop, should do the transformation -- first and then do the inlining. doInlineInCaller :: FunDef -> [FunDef] -> FunDef doInlineInCaller (FunDef entry name rtp args body) inlcallees = let body' = inlineInBody inlcallees body in FunDef entry name rtp args body' inlineInBody :: [FunDef] -> Body -> Body inlineInBody inlcallees (Body _ (bnd@(Let pat _ (Apply fname args _ (safety,loc,locs))):bnds) res) = let continue callbnds = callbnds `insertStms` inlineInBody inlcallees (mkBody bnds res) continue' (Body _ callbnds res') = continue $ addLocations safety (loc:locs) callbnds ++ zipWith reshapeIfNecessary (patternIdents pat) res' in case filter ((== fname) . funDefName) inlcallees of [] -> continue [bnd] fun:_ -> let revbnds = zip (map paramIdent $ funDefParams fun) $ map fst args in continue' $ foldr addArgBnd (funDefBody fun) revbnds where addArgBnd :: (Ident, SubExp) -> Body -> Body addArgBnd (farg, aarg) body = reshapeIfNecessary farg aarg `insertStm` body reshapeIfNecessary ident se | t@Array{} <- identType ident, Var v <- se = mkLet' [] [ident] $ shapeCoerce (arrayDims t) v | otherwise = mkLet' [] [ident] $ BasicOp $ SubExp se inlineInBody inlcallees (Body () (bnd:bnds) res) = let bnd' = inlineInStm inlcallees bnd Body () bnds' res' = inlineInBody inlcallees $ Body () bnds res in Body () (bnd':bnds') res' inlineInBody _ (Body () [] res) = Body () [] res inliner :: Monad m => [FunDef] -> Mapper SOACS SOACS m inliner funs = identityMapper { mapOnBody = const $ return . inlineInBody funs , mapOnOp = return . inlineInSOAC funs } inlineInSOAC :: [FunDef] -> SOAC SOACS -> SOAC SOACS inlineInSOAC inlcallees = runIdentity . mapSOACM identitySOACMapper { mapOnSOACLambda = return . inlineInLambda inlcallees , mapOnSOACExtLambda = return . inlineInExtLambda inlcallees } inlineInStm :: [FunDef] -> Stm -> Stm inlineInStm inlcallees (Let pat aux e) = Let pat aux $ mapExp (inliner inlcallees) e inlineInLambda :: [FunDef] -> Lambda -> Lambda inlineInLambda inlcallees (Lambda params body ret) = Lambda params (inlineInBody inlcallees body) ret inlineInExtLambda :: [FunDef] -> ExtLambda -> ExtLambda inlineInExtLambda inlcallees (ExtLambda params body ret) = ExtLambda params (inlineInBody inlcallees body) ret addLocations :: Safety -> [SrcLoc] -> [Stm] -> [Stm] addLocations caller_safety more_locs = map onStm where onStm stm = stm { stmExp = onExp $ stmExp stm } onExp (Apply fname args t (safety, loc,locs)) = Apply fname args t (min caller_safety safety, loc,locs++more_locs) onExp (BasicOp (Assert cond desc (loc,locs))) = case caller_safety of Safe -> BasicOp $ Assert cond desc (loc,locs++more_locs) Unsafe -> BasicOp $ SubExp $ Constant Checked onExp e = mapExp identityMapper { mapOnBody = const $ return . onBody } e onBody body = body { bodyStms = addLocations caller_safety more_locs $ bodyStms body } -- | A composition of 'inlineAggressively' and 'removeDeadFunctions', -- to avoid the cost of type-checking the intermediate stage. inlineAndRemoveDeadFunctions :: Pass SOACS SOACS inlineAndRemoveDeadFunctions = Pass { passName = "Inline and remove dead functions" , passDescription = "Inline and remove resulting dead functions." , passFunction = pass } where pass prog = do let cg = buildCallGraph prog renameProg $ Prog $ aggInlining cg $ progFunctions prog -- | @removeDeadFunctions prog@ removes the functions that are unreachable from -- the main function from the program. removeDeadFunctions :: Pass SOACS SOACS removeDeadFunctions = Pass { passName = "Remove dead functions" , passDescription = "Remove the functions that are unreachable from the main function" , passFunction = return . pass } where pass prog = let cg = buildCallGraph prog live_funs = filter (isFunInCallGraph cg) (progFunctions prog) in Prog live_funs isFunInCallGraph cg fundec = isJust $ M.lookup (funDefName fundec) cg
ihc/futhark
src/Futhark/Optimise/InliningDeadFun.hs
isc
6,617
0
18
1,764
1,774
918
856
118
4
module Home.Controller ( HomeAPI , rootPath ) where import App (AppT, AppConfig(..)) import Control.Monad.Reader import Home.View (showA) import Servant import Servant.HTML.Blaze (HTML) import Text.Blaze.Html5 (Html) import Users.Api type HomeAPI = Get '[HTML] Html rootPath :: Maybe User -> AppT Html rootPath user = ask >>= \AppConfig{..} -> return (showA user getAuthUrl)
gust/feature-creature
marketing-site/app/Home/Controller.hs
mit
387
0
9
63
140
81
59
-1
-1