code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ECS
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Amazon EC2 Container Service (Amazon ECS) is a highly scalable, fast,
-- container management service that makes it easy to run, stop, and manage
-- Docker containers on a cluster of Amazon EC2 instances. Amazon ECS lets
-- you launch and stop container-enabled applications with simple API
-- calls, allows you to get the state of your cluster from a centralized
-- service, and gives you access to many familiar Amazon EC2 features like
-- security groups, Amazon EBS volumes, and IAM roles.
--
-- You can use Amazon ECS to schedule the placement of containers across
-- your cluster based on your resource needs, isolation policies, and
-- availability requirements. Amazon EC2 Container Service eliminates the
-- need for you to operate your own cluster management and configuration
-- management systems or worry about scaling your management
-- infrastructure.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/Welcome.html AWS API Reference>
module Network.AWS.ECS
(
-- * Service Configuration
eCS
-- * Errors
-- $errors
-- ** InvalidParameterException
, _InvalidParameterException
-- ** ServerException
, _ServerException
-- ** ClusterContainsServicesException
, _ClusterContainsServicesException
-- ** ClusterContainsContainerInstancesException
, _ClusterContainsContainerInstancesException
-- ** ServiceNotActiveException
, _ServiceNotActiveException
-- ** ClusterNotFoundException
, _ClusterNotFoundException
-- ** NoUpdateAvailableException
, _NoUpdateAvailableException
-- ** ServiceNotFoundException
, _ServiceNotFoundException
-- ** MissingVersionException
, _MissingVersionException
-- ** UpdateInProgressException
, _UpdateInProgressException
-- ** ClientException
, _ClientException
-- * Waiters
-- $waiters
-- ** ServicesInactive
, servicesInactive
-- ** TasksRunning
, tasksRunning
-- ** TasksStopped
, tasksStopped
-- * Operations
-- $operations
-- ** ListServices (Paginated)
, module Network.AWS.ECS.ListServices
-- ** DescribeClusters
, module Network.AWS.ECS.DescribeClusters
-- ** DeleteService
, module Network.AWS.ECS.DeleteService
-- ** UpdateService
, module Network.AWS.ECS.UpdateService
-- ** DiscoverPollEndpoint
, module Network.AWS.ECS.DiscoverPollEndpoint
-- ** SubmitContainerStateChange
, module Network.AWS.ECS.SubmitContainerStateChange
-- ** StopTask
, module Network.AWS.ECS.StopTask
-- ** DescribeTaskDefinition
, module Network.AWS.ECS.DescribeTaskDefinition
-- ** SubmitTaskStateChange
, module Network.AWS.ECS.SubmitTaskStateChange
-- ** DescribeContainerInstances
, module Network.AWS.ECS.DescribeContainerInstances
-- ** DeleteCluster
, module Network.AWS.ECS.DeleteCluster
-- ** CreateCluster
, module Network.AWS.ECS.CreateCluster
-- ** ListTaskDefinitions (Paginated)
, module Network.AWS.ECS.ListTaskDefinitions
-- ** RunTask
, module Network.AWS.ECS.RunTask
-- ** ListTasks (Paginated)
, module Network.AWS.ECS.ListTasks
-- ** RegisterContainerInstance
, module Network.AWS.ECS.RegisterContainerInstance
-- ** UpdateContainerAgent
, module Network.AWS.ECS.UpdateContainerAgent
-- ** ListContainerInstances (Paginated)
, module Network.AWS.ECS.ListContainerInstances
-- ** ListTaskDefinitionFamilies (Paginated)
, module Network.AWS.ECS.ListTaskDefinitionFamilies
-- ** StartTask
, module Network.AWS.ECS.StartTask
-- ** DeregisterTaskDefinition
, module Network.AWS.ECS.DeregisterTaskDefinition
-- ** DescribeTasks
, module Network.AWS.ECS.DescribeTasks
-- ** ListClusters (Paginated)
, module Network.AWS.ECS.ListClusters
-- ** DescribeServices
, module Network.AWS.ECS.DescribeServices
-- ** DeregisterContainerInstance
, module Network.AWS.ECS.DeregisterContainerInstance
-- ** RegisterTaskDefinition
, module Network.AWS.ECS.RegisterTaskDefinition
-- ** CreateService
, module Network.AWS.ECS.CreateService
-- * Types
-- ** AgentUpdateStatus
, AgentUpdateStatus (..)
-- ** DesiredStatus
, DesiredStatus (..)
-- ** SortOrder
, SortOrder (..)
-- ** TaskDefinitionStatus
, TaskDefinitionStatus (..)
-- ** TransportProtocol
, TransportProtocol (..)
-- ** Cluster
, Cluster
, cluster
, cStatus
, cClusterARN
, cRunningTasksCount
, cRegisteredContainerInstancesCount
, cPendingTasksCount
, cClusterName
, cActiveServicesCount
-- ** Container
, Container
, container
, cNetworkBindings
, cContainerARN
, cTaskARN
, cLastStatus
, cReason
, cName
, cExitCode
-- ** ContainerDefinition
, ContainerDefinition
, containerDefinition
, cdImage
, cdCommand
, cdVolumesFrom
, cdEnvironment
, cdEntryPoint
, cdPortMappings
, cdMemory
, cdName
, cdMountPoints
, cdLinks
, cdEssential
, cdCpu
-- ** ContainerInstance
, ContainerInstance
, containerInstance
, ciStatus
, ciRunningTasksCount
, ciRemainingResources
, ciEc2InstanceId
, ciContainerInstanceARN
, ciAgentConnected
, ciVersionInfo
, ciAgentUpdateStatus
, ciPendingTasksCount
, ciRegisteredResources
-- ** ContainerOverride
, ContainerOverride
, containerOverride
, coCommand
, coEnvironment
, coName
-- ** ContainerService
, ContainerService
, containerService
, csRunningCount
, csStatus
, csClusterARN
, csDesiredCount
, csLoadBalancers
, csPendingCount
, csEvents
, csDeployments
, csServiceName
, csServiceARN
, csTaskDefinition
, csRoleARN
-- ** Deployment
, Deployment
, deployment
, dRunningCount
, dStatus
, dCreatedAt
, dDesiredCount
, dPendingCount
, dId
, dUpdatedAt
, dTaskDefinition
-- ** Failure
, Failure
, failure
, fArn
, fReason
-- ** HostVolumeProperties
, HostVolumeProperties
, hostVolumeProperties
, hvpSourcePath
-- ** KeyValuePair
, KeyValuePair
, keyValuePair
, kvpValue
, kvpName
-- ** LoadBalancer
, LoadBalancer
, loadBalancer
, lbLoadBalancerName
, lbContainerName
, lbContainerPort
-- ** MountPoint
, MountPoint
, mountPoint
, mpContainerPath
, mpSourceVolume
, mpReadOnly
-- ** NetworkBinding
, NetworkBinding
, networkBinding
, nbBindIP
, nbProtocol
, nbHostPort
, nbContainerPort
-- ** PortMapping
, PortMapping
, portMapping
, pmProtocol
, pmHostPort
, pmContainerPort
-- ** Resource
, Resource
, resource
, rStringSetValue
, rIntegerValue
, rDoubleValue
, rLongValue
, rName
, rType
-- ** ServiceEvent
, ServiceEvent
, serviceEvent
, seCreatedAt
, seId
, seMessage
-- ** Task
, Task
, task
, tDesiredStatus
, tOverrides
, tClusterARN
, tTaskARN
, tContainerInstanceARN
, tLastStatus
, tContainers
, tStartedBy
, tTaskDefinitionARN
-- ** TaskDefinition
, TaskDefinition
, taskDefinition
, tdStatus
, tdFamily
, tdContainerDefinitions
, tdTaskDefinitionARN
, tdRevision
, tdVolumes
-- ** TaskOverride
, TaskOverride
, taskOverride
, toContainerOverrides
-- ** VersionInfo
, VersionInfo
, versionInfo
, viAgentHash
, viAgentVersion
, viDockerVersion
-- ** Volume
, Volume
, volume
, vName
, vHost
-- ** VolumeFrom
, VolumeFrom
, volumeFrom
, vfSourceContainer
, vfReadOnly
) where
import Network.AWS.ECS.CreateCluster
import Network.AWS.ECS.CreateService
import Network.AWS.ECS.DeleteCluster
import Network.AWS.ECS.DeleteService
import Network.AWS.ECS.DeregisterContainerInstance
import Network.AWS.ECS.DeregisterTaskDefinition
import Network.AWS.ECS.DescribeClusters
import Network.AWS.ECS.DescribeContainerInstances
import Network.AWS.ECS.DescribeServices
import Network.AWS.ECS.DescribeTaskDefinition
import Network.AWS.ECS.DescribeTasks
import Network.AWS.ECS.DiscoverPollEndpoint
import Network.AWS.ECS.ListClusters
import Network.AWS.ECS.ListContainerInstances
import Network.AWS.ECS.ListServices
import Network.AWS.ECS.ListTaskDefinitionFamilies
import Network.AWS.ECS.ListTaskDefinitions
import Network.AWS.ECS.ListTasks
import Network.AWS.ECS.RegisterContainerInstance
import Network.AWS.ECS.RegisterTaskDefinition
import Network.AWS.ECS.RunTask
import Network.AWS.ECS.StartTask
import Network.AWS.ECS.StopTask
import Network.AWS.ECS.SubmitContainerStateChange
import Network.AWS.ECS.SubmitTaskStateChange
import Network.AWS.ECS.Types
import Network.AWS.ECS.UpdateContainerAgent
import Network.AWS.ECS.UpdateService
import Network.AWS.ECS.Waiters
{- $errors
Error matchers are designed for use with the functions provided by
<http://hackage.haskell.org/package/lens/docs/Control-Exception-Lens.html Control.Exception.Lens>.
This allows catching (and rethrowing) service specific errors returned
by 'ECS'.
-}
{- $operations
Some AWS operations return results that are incomplete and require subsequent
requests in order to obtain the entire result set. The process of sending
subsequent requests to continue where a previous request left off is called
pagination. For example, the 'ListObjects' operation of Amazon S3 returns up to
1000 objects at a time, and you must send subsequent requests with the
appropriate Marker in order to retrieve the next page of results.
Operations that have an 'AWSPager' instance can transparently perform subsequent
requests, correctly setting Markers and other request facets to iterate through
the entire result set of a truncated API operation. Operations which support
this have an additional note in the documentation.
Many operations have the ability to filter results on the server side. See the
individual operation parameters for details.
-}
{- $waiters
Waiters poll by repeatedly sending a request until some remote success condition
configured by the 'Wait' specification is fulfilled. The 'Wait' specification
determines how many attempts should be made, in addition to delay and retry strategies.
-}
| fmapfmapfmap/amazonka | amazonka-ecs/gen/Network/AWS/ECS.hs | mpl-2.0 | 11,225 | 0 | 5 | 2,632 | 1,073 | 780 | 293 | 233 | 0 |
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
program = drawingOf(target)
target = pictures([ circle(r) | r = [1, 2, 3, 4, 5] ])
| alphalambda/codeworld | codeworld-compiler/test/testcases/equationInListComp/source.hs | apache-2.0 | 693 | 3 | 8 | 131 | 62 | 32 | 30 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
module GramLab.Data.Diff.Instances ( Diff (..)
, editList
, editListRev
, editListBidi
, editTree
)
where
import qualified GramLab.Data.Diff.EditList as EL
import qualified GramLab.Data.Diff.EditListRev as ELR
import qualified GramLab.Data.Diff.EditListBidi as ELB
import qualified GramLab.Data.Diff.EditTree as ET
-- FIXME adapt to StringLike
class Diff d a | d -> a where
make :: d -> [a] -> [a] -> d
apply :: d -> [a] -> [a]
check :: d -> [a] -> Bool
instance (Ord a,Ord s) => Diff (ET.EditTree s a) a where
make _ = ET.make
apply = ET.apply
check = ET.check
instance (Ord a) => Diff (EL.EditList a) a where
make _ = EL.make
apply = EL.apply
check = EL.check
instance (Ord a) => Diff (ELR.EditListRev a) a where
make _ = ELR.make
apply = ELR.apply
check = ELR.check
instance (Ord a) => Diff (ELB.EditListBidi a) a where
make _ = ELB.make
apply = ELB.apply
check = ELB.check
-- witnesses
editList :: (Ord a) => EL.EditList a
editList = undefined
editListRev :: (Ord a) => ELR.EditListRev a
editListRev = undefined
editListBidi :: (Ord a) => ELB.EditListBidi a
editListBidi = undefined
editTree :: (Ord a,Ord s) => ET.EditTree s a
editTree = undefined
| gchrupala/morfette | src/GramLab/Data/Diff/Instances.hs | bsd-2-clause | 1,537 | 0 | 10 | 507 | 464 | 266 | 198 | 39 | 1 |
{-# LANGUAGE FlexibleContexts #-}
-- | Discrete Fourier Transform
module DFT
( dft
, idft
) where
import Prelude ()
import Feldspar
import Feldspar.Data.Vector
-- | Discrete Fourier Transform
dft :: (RealFloat a, PrimType a, PrimType (Complex a)) =>
DPull (Complex a) -> DPull (Complex a)
dft vec = fromColVec $ matMul (mat (length vec)) (toColVec vec)
where
mat n = Pull2 n n $ \k l ->
polar 1 (-(2*π * i2n k * i2n l) / i2n n)
-- | Inverse Discrete Fourier Transform
idft :: (RealFloat a, PrimType a, PrimType (Complex a)) =>
DPull (Complex a) -> DPull (Complex a)
idft = divLen . map conjugate . dft . map conjugate
where
divLen v = fmap (/ i2n (length v)) v
| kmate/raw-feldspar | examples/DFT.hs | bsd-3-clause | 707 | 0 | 16 | 169 | 289 | 149 | 140 | 16 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, TypeFamilies #-}
module Utils.Point where
type Pt a = (a,a)
instance Num a => Num (Pt a) where
(x1,x2) + (y1,y2) = (x1+y1,x2+y2)
(x1,x2) * (y1,y2) = (x1*y1,x2*y2)
(x1,x2) - (y1,y2) = (x1-y1,x2-y2)
negate (x1,x2) = (negate x1,negate x2)
abs (x1,x2) = (abs x1, abs x2) -- Not really mathematical, but the type must be same
signum (x1,x2) = (signum x1, signum x2) -- Ditto
fromInteger x = (fromInteger x,fromInteger x) -- As well
norm2 :: (Num a) => Pt a -> a
norm2 (a,b) = a*a+b*b
norm = sqrt . norm2
(a,b) >/ (c,d) = (a `div` c, b `div` d)
| TomMD/CV | Utils/Point.hs | bsd-3-clause | 628 | 0 | 7 | 141 | 350 | 197 | 153 | 15 | 1 |
{-# language ConstraintKinds #-}
{-# language DataKinds #-}
{-# language FlexibleContexts #-}
{-# language FlexibleInstances #-}
{-# language GeneralizedNewtypeDeriving #-}
{-# language MultiParamTypeClasses #-}
{-# language NamedFieldPuns #-}
{-# language OverloadedStrings #-}
{-# language PackageImports #-}
{-# language StandaloneDeriving #-}
{-# language TypeApplications #-}
{-# language TypeFamilies #-}
{-# language TupleSections #-}
-- A simple Core Frank parser
module Planetary.Support.Parser where
import Control.Applicative
import Control.Lens (unsnoc)
import Control.Monad.Trans (MonadTrans(lift))
import Control.Monad.State.Strict
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B8
import Data.Int (Int64)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import qualified Network.IPLD as IPLD
import Network.IPLD (Cid, IsIpld(..), valueCid, compact)
-- TODO: be suspicious of `try`, see where it can be removed
-- http://blog.ezyang.com/2014/05/parsec-try-a-or-b-considered-harmful/
import Text.Trifecta hiding (parens) -- hiding (try)
import Text.Trifecta.Delta hiding (delta)
import "indentation-trifecta" Text.Trifecta.Indentation
import Data.Char
import qualified Text.Parser.Token as Tok
import Text.Parser.Token.Style
import qualified Text.Parser.Token.Highlight as Hi
import qualified Data.HashSet as HashSet
import Planetary.Core
import Planetary.Util
type Ability' = Ability Text
type CompTy' = CompTy Text
type ConstructorDecl' = ConstructorDecl Text
type Peg' = Peg Text
type Polytype' = Polytype Text
type TyArg' = TyArg Text
type ValTy' = ValTy Text
type Tm' = Tm Text
newtype CoreParser t m a =
CoreParser { runCoreParser :: IndentationParserT t (StateT ValueStore m) a }
deriving (Functor, Alternative, Applicative, Monad, Parsing
, IndentationParsing, MonadPlus)
deriving instance DeltaParsing m => CharParsing (CoreParser Char m)
deriving instance DeltaParsing m => CharParsing (CoreParser Token m)
deriving instance DeltaParsing m => TokenParsing (CoreParser Char m)
instance Monad m => MonadState ValueStore (CoreParser t m) where
get = CoreParser $ lift get
put s = CoreParser $ lift (put s)
instance DeltaParsing m => TokenParsing (CoreParser Token m) where
someSpace = CoreParser $ buildSomeSpaceParser someSpace haskellCommentStyle
nesting = CoreParser . nesting . runCoreParser
semi = CoreParser $ runCoreParser semi
highlight h = CoreParser . highlight h . runCoreParser
token p = (CoreParser $ token (runCoreParser p)) <* whiteSpace
type MonadicParsing m
= (TokenParsing m, IndentationParsing m, Monad m, MonadState ValueStore m)
planetaryStyle :: MonadicParsing m => IdentifierStyle m
planetaryStyle = IdentifierStyle {
_styleName = "Planetary"
, _styleStart = satisfy (\c -> isAlphaNum c || c == '_' || c == '$')
, _styleLetter = satisfy (\c -> isAlphaNum c || c == '_' || c == '\'')
, _styleReserved = HashSet.fromList
-- TODO: data and interface aren't really reserved from the term language
[ "data"
, "interface"
, "let"
, "letrec"
, "in"
, "forall"
, "case"
, "handle"
, "of"
, "with"
]
, _styleHighlight = Hi.Identifier
, _styleReservedHighlight = Hi.ReservedIdentifier }
arr, bar, assign, bang :: MonadicParsing m => m Text
arr = textSymbol "->"
bar = textSymbol "|"
assign = textSymbol "="
bang = textSymbol "!"
indentedBlock :: MonadicParsing m => m a -> m a
indentedBlock = localIndentation Gt
parens :: MonadicParsing m => m a -> m a
parens = Tok.parens . localIndentation Any
reserved :: MonadicParsing m => Text -> m ()
reserved = Tok.reserveText planetaryStyle
identifier :: MonadicParsing m => m Text
identifier = Tok.ident planetaryStyle
<?> "identifier"
-- TODO: get an exact count of digits
parseUid :: MonadicParsing m => m Text
parseUid = identifier <?> "uid"
parseValTy :: MonadicParsing m => m (TyFix Text)
parseValTy = choice
[ parseDataTy
, parens parseValTy
, SuspendedTy <$> braces parseCompTy
, VariableTy <$> identifier
] <?> "Val Ty"
parseTyArg :: MonadicParsing m => m TyArg'
parseTyArg = TyArgAbility <$> brackets parseAbilityBody
<|> TyArgVal <$> parseValTy
<?> "Ty Arg"
parseConstructor
:: MonadicParsing m => Vector TyArg' -> m ConstructorDecl'
parseConstructor tyArgs = angles (ConstructorDecl
<$> identifier
<*> many parseValTy
<*> pure tyArgs
) <?> "Constructor"
parseDataTy :: MonadicParsing m => m ValTy'
parseDataTy = angles $ DataTy
<$> (VariableTy <$> parseUid)
<*> many parseTyArg
-- <*> localIndentation Gt (many parseTyArg)
<?> "Data Ty"
parseTyVar :: MonadicParsing m => m (Text, Kind)
parseTyVar = (,EffTyK) <$> brackets identifier
<|> (,ValTyK) <$> identifier
<?> "Ty Var"
-- 0 | 0,Interfaces | e,Interfaces | Interfaces
-- TODO: allow explicit e? `[e]`
parseAbilityBody :: MonadicParsing m => m Ability'
parseAbilityBody =
let closedAb = do
_ <- textSymbol "0"
skipOptional comma
instances <- option [] parseInterfaceInstances
return $ Ability ClosedAbility (fromList instances)
varAb = do
var <- option ("e" :: Text) (try identifier)
skipOptional comma
instances <- parseInterfaceInstances
return $ Ability OpenAbility (fromList instances)
in closedAb <|> varAb <?> "Ability Body"
parseAbility :: MonadicParsing m => m Ability'
parseAbility = do
mxs <- optional $ brackets parseAbilityBody
return $ fromMaybe emptyAbility mxs
parsePeg :: MonadicParsing m => m Peg'
parsePeg = Peg
<$> parseAbility
<*> parseValTy
<?> "Peg"
parseCompTy :: MonadicParsing m => m (CompTy Text)
parseCompTy = CompTy
<$> many (try (parseValTy <* arr)) -- TODO: bad use of try
<*> parsePeg
<?> "Comp Ty"
parseInterfaceInstance :: MonadicParsing m => m (Text, [TyArg'])
parseInterfaceInstance = angles $ (,)
<$> parseUid
<*> many parseTyArg
<?> "Interface Instance"
parseInterfaceInstances :: MonadicParsing m => m [(Text, [TyArg'])]
parseInterfaceInstances = parseInterfaceInstance `sepBy` comma
<?> "Interface Instances"
parseDataDecl :: MonadicParsing m => m (DataDecl Text)
parseDataDecl = do
reserved "data"
name <- identifier
tyArgs <- many parseTyVar
_ <- assign
-- this is the result type each constructor will saturate to
let tyArgs' = map (\(name', _) -> (TyArgVal (VariableTy name'))) tyArgs
-- put bindingState
ctrs <- indentedBlock
(many (absoluteIndentation (bar *> parseConstructor tyArgs')))
return (DataDecl name (DataTypeInterface tyArgs ctrs))
-- only value arguments and result type
parseCommandType
:: MonadicParsing m
=> m (Text, Vector ValTy', ValTy')
parseCommandType = do
name <- identifier
_ <- colon
vs <- sepBy1 parseValTy arr
(args, result) <- maybe empty pure (unsnoc vs)
pure (name, args, result)
parseCommandDecl :: MonadicParsing m => m (CommandDeclaration Text)
parseCommandDecl = bar >> (uncurry3 CommandDeclaration <$> parseCommandType)
<?> "Command Decl"
parseInterfaceDecl :: MonadicParsing m => m (InterfaceDecl Text)
parseInterfaceDecl = (do
reserved "interface"
name <- identifier
tyVars <- many parseTyVar
_ <- assign
-- inBoundTys
xs <- indentedBlock (many (absoluteIndentation parseCommandDecl))
return (InterfaceDecl name (EffectInterface tyVars xs))
) <?> "Interface Decl"
parseDecls :: MonadicParsing m => m [Decl Text]
parseDecls = some (choice
[ DataDecl_ <$> parseDataDecl
, InterfaceDecl_ <$> parseInterfaceDecl
, TermDecl_ <$> parseTermDecl
]) <?> "Data or Interface Decls"
-- TODO allow a more succinct form of `x = letrec x = ... in x`
-- ... `letrec x =
-- ... this could be generalizd to let (but that would cost the complexity of
-- multiple types of toplevel)
parseTermDecl :: MonadicParsing m => m (TermDecl Text)
parseTermDecl =
let parser = TermDecl <$> identifier <* assign <*> parseLetrec
in parser <?> "definition"
parseLetrec :: MonadicParsing m => m Tm'
parseLetrec =
let parser = do
reserved "letrec"
definitions <- indentedBlock $ many $ absoluteIndentation $ do
name <- identifier
tyAndDef <- indentedBlock $ absoluteIndentation $ (,)
<$> (colon *> parsePolyty)
<*> (assign *> parseLambda)
pure (name, tyAndDef)
reserved "in"
body <- indentedBlock parseTm
let (names, binderVals) = unzip definitions
return $ Letrec names binderVals body
in parser <?> "Letrec"
parsePolyty :: MonadicParsing m => m Polytype'
parsePolyty = do
reserved "forall"
args <- many parseTyVar
_ <- dot
result <- parseValTy
pure (Polytype args result)
parseLet :: MonadicParsing m => m Tm'
parseLet =
let parser = do
reserved "let"
name <- identifier
_ <- colon
ty <- parsePolyty
_ <- assign
rhs <- parseTm
reserved "in"
body <- parseTm
pure (Let rhs ty name body)
in parser <?> "Let"
parseValue :: MonadicParsing m => m Tm'
parseValue = choice
[ parseDataConstructor
, parseText
-- parseCommand
, parseLambda
] <?> "Value"
mkForeign :: IsIpld a => a -> (Cid, IPLD.Value)
mkForeign val = let val' = toIpld val in (valueCid val', val')
mkForeignTm :: IsIpld a => Cid -> Vector ValTyI -> a -> (TmI, IPLD.Value)
mkForeignTm tyId tySat a =
let (cid, val) = mkForeign a
in (ForeignValue tyId tySat cid, val)
parseText :: MonadicParsing m => m Tm'
parseText = do
str <- stringLiteral
let (cid, ipldVal) = mkForeign @Text str
modify (storeOf [ipldVal] <>)
pure (ForeignValue "Text" [] (cidText cid))
cidText :: Cid -> Text
cidText = T.pack . B8.unpack . compact
parseDataConstructor :: MonadicParsing m => m Tm'
parseDataConstructor = angles (DataConstructor
<$> parseUid <* dot
<*> (fromIntegral <$> natural)
<*> many parseTmNoApp
) <?> "Data constructor"
parseCase :: MonadicParsing m => m Tm'
parseCase =
let parser = do
_ <- reserved "case"
m <- parseTm
_ <- reserved "of"
branches <- localIndentation Any $ absoluteIndentation $ many $ do
_ <- bar
idents <- angles $ some identifier
_ <- arr
rhs <- parseTm
let _uncheckedName:vars = idents
pure (vars, rhs)
pure $ Case m branches
in parser <?> "case"
parseHandle :: MonadicParsing m => m Tm'
parseHandle = (do
_ <- reserved "handle"
scrutinee <- parseTm
_ <- colon
peg <- parsePeg
_ <- reserved "with"
(effectHandlers, adjustment, valueHandler) <- indentedBlock $ do
effectHandlers <- many $ absoluteIndentation $ do
uid <- parseUid
tyArgs <- many parseTyArg
_ <- colon
rows <- indentedBlock $ many $ do
_ <- bar
(idents, kVar) <- angles $ (,)
<$> some identifier <* arr
<*> identifier
_ <- arr
rhs <- parseTm
let _uncheckedName:vars = idents
pure (vars, kVar, rhs)
pure (uid, tyArgs, rows)
valueHandler <- absoluteIndentation $ do
_ <- bar
var <- identifier
_ <- arr
rhs <- parseTm
pure (var, rhs)
let handlers = fromList $
(\(uid, _, rows) -> (uid, rows)) <$> effectHandlers
adjustment = Adjustment $ fromList $
(\(uid, tyArgs, _) -> (uid, tyArgs)) <$> effectHandlers
pure (handlers, adjustment, valueHandler)
pure $ Handle scrutinee adjustment peg effectHandlers valueHandler
) <?> "handle"
parseTm :: MonadicParsing m => m Tm'
parseTm = (do
tms <- some $ do
tm <- parseTmNoApp
-- "We write '!' for the empty spine"
(AppT tm [] <$ bang) <|> pure tm
case tms of
[] -> empty
[tm] -> pure tm
fun:spine -> pure $ AppT fun spine
) <?> "Tm"
parseTmOrAnnot :: MonadicParsing m => m Tm'
parseTmOrAnnot =
let p1 = do
val <- parseValue
maybeTy <- optional $ try $ do
_ <- colon
parseValTy
pure $ case maybeTy of
Nothing -> val
Just ty -> Annotation val ty
p2 = parseTm
in p1 <|> p2 <?> "term or annot"
parseTmNoApp :: MonadicParsing m => m Tm'
parseTmNoApp = choice
[ parens parseTmOrAnnot
, parseValue
, parseCase
, parseHandle
, parseLet
, parseLetrec
, parseCommandOrIdent
] <?> "Tm (no app)"
parseCommandOrIdent :: MonadicParsing m => m Tm'
parseCommandOrIdent = do
name <- identifier
dotRow <- optional $ try $ do
_ <- dot
natural
hasBang <- optional $ try bang
let v = case dotRow of
Just row -> Command name (fromIntegral row)
Nothing -> Variable name
let v' = case hasBang of
Just _bang -> AppT v []
Nothing -> v
pure v'
-- TODO: named commands
-- TODO application of terms
parseLambda :: MonadicParsing m => m Tm'
parseLambda = Lambda
<$> (textSymbol "\\" *> many identifier) <*> (arr *> parseTm)
<?> "Lambda"
evalCharIndentationParserT
:: Monad m => CoreParser Char m a -> IndentationState -> m (a, ValueStore)
evalCharIndentationParserT p i = runStateT (evalIndentationParserT (runCoreParser p) i) mempty
evalTokenIndentationParserT
:: Monad m => CoreParser Token m a -> IndentationState -> m (a, ValueStore)
evalTokenIndentationParserT p i = runStateT (evalIndentationParserT (runCoreParser p) i) mempty
data ParseLocation = ParseLocation !ByteString !Int64 !Int64
testLocation, forceLocation :: ParseLocation
testLocation = ParseLocation "(test)" 0 0
forceLocation = ParseLocation "(force)" 0 0
lowLevelRunParse
:: (t -> IndentationState -> Parser b)
-> t
-> ParseLocation
-> Text
-> Either String b
lowLevelRunParse ev p (ParseLocation filename row col) input
= let indA = ev p $ mkIndentationState 0 infIndentation True Ge
delta = Directed filename row col 0 0
in case parseByteString indA delta (encodeUtf8 input) of
Failure (ErrInfo errDoc _deltas) -> Left (show errDoc)
Success t -> Right t
runTokenParse
:: CoreParser Token Parser b -> ParseLocation -> Text -> Either String (b, ValueStore)
runTokenParse = lowLevelRunParse evalTokenIndentationParserT
forceDeclarations :: Text -> ([Decl Text], ValueStore)
forceDeclarations str = case runTokenParse parseDecls forceLocation str of
Left bad -> error bad
Right result -> result
forceTm :: Text -> (Tm', ValueStore)
forceTm str = case runTokenParse parseTm forceLocation str of
Left bad -> error bad
Right result -> result
| joelburget/frankenstein | src/Planetary/Support/Parser.hs | bsd-3-clause | 14,626 | 0 | 26 | 3,306 | 4,378 | 2,208 | 2,170 | 400 | 3 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- Load information on package sources
module Stack.Build.Source
( loadSourceMap
, SourceMap
, PackageSource (..)
, localFlags
, getLocalPackageViews
, loadLocalPackage
, parseTargetsFromBuildOpts
, addUnlistedToBuildCache
) where
import Control.Applicative
import Control.Arrow ((&&&))
import Control.Exception (assert, catch)
import Control.Monad
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import Crypto.Hash (Digest, SHA256)
import Crypto.Hash.Conduit (sinkHash)
import qualified Data.ByteString as S
import Data.Byteable (toBytes)
import Data.Conduit (($$), ZipSink (..))
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.Either
import Data.Function
import qualified Data.HashSet as HashSet
import Data.List
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Distribution.Package (pkgName, pkgVersion)
import Distribution.PackageDescription (GenericPackageDescription, package, packageDescription)
import qualified Distribution.PackageDescription as C
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Path.IO
import Prelude
import Stack.Build.Cache
import Stack.Build.Target
import Stack.BuildPlan (loadMiniBuildPlan, shadowMiniBuildPlan,
parseCustomMiniBuildPlan)
import Stack.Constants (wiredInPackages)
import Stack.Package
import Stack.PackageIndex
import Stack.Types
import System.Directory
import System.IO (withBinaryFile, IOMode (ReadMode))
import System.IO.Error (isDoesNotExistError)
loadSourceMap :: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m, HasEnvConfig env)
=> NeedTargets
-> BuildOpts
-> m ( Map PackageName SimpleTarget
, MiniBuildPlan
, [LocalPackage]
, Set PackageName -- non-local targets
, SourceMap
)
loadSourceMap needTargets bopts = do
bconfig <- asks getBuildConfig
rawLocals <- getLocalPackageViews
(mbp0, cliExtraDeps, targets) <- parseTargetsFromBuildOpts needTargets bopts
menv <- getMinimalEnvOverride
caches <- getPackageCaches menv
let latestVersion = Map.fromListWith max $ map toTuple $ Map.keys caches
-- Extend extra-deps to encompass targets requested on the command line
-- that are not in the snapshot.
extraDeps0 <- extendExtraDeps
(bcExtraDeps bconfig)
cliExtraDeps
(Map.keysSet $ Map.filter (== STUnknown) targets)
latestVersion
locals <- mapM (loadLocalPackage bopts targets) $ Map.toList rawLocals
checkFlagsUsed bopts locals extraDeps0 (mbpPackages mbp0)
let
-- loadLocals returns PackageName (foo) and PackageIdentifier (bar-1.2.3) targets separately;
-- here we combine them into nonLocalTargets. This is one of the
-- return values of this function.
nonLocalTargets :: Set PackageName
nonLocalTargets =
Map.keysSet $ Map.filter (not . isLocal) targets
where
isLocal (STLocalComps _) = True
isLocal STLocalAll = True
isLocal STUnknown = False
isLocal STNonLocal = False
shadowed = Map.keysSet rawLocals <> Map.keysSet extraDeps0
(mbp, extraDeps1) = shadowMiniBuildPlan mbp0 shadowed
-- Add the extra deps from the stack.yaml file to the deps grabbed from
-- the snapshot
extraDeps2 = Map.union
(Map.map (\v -> (v, Map.empty)) extraDeps0)
(Map.map (\mpi -> (mpiVersion mpi, mpiFlags mpi)) extraDeps1)
-- Overwrite any flag settings with those from the config file
extraDeps3 = Map.mapWithKey
(\n (v, f) -> PSUpstream v Local $
case ( Map.lookup (Just n) $ boptsFlags bopts
, Map.lookup Nothing $ boptsFlags bopts
, Map.lookup n $ bcFlags bconfig
) of
-- Didn't have any flag overrides, fall back to the flags
-- defined in the snapshot.
(Nothing, Nothing, Nothing) -> f
-- Either command line flag for this package, general
-- command line flag, or flag in stack.yaml is defined.
-- Take all of those and ignore the snapshot flags.
(x, y, z) -> Map.unions
[ fromMaybe Map.empty x
, fromMaybe Map.empty y
, fromMaybe Map.empty z
])
extraDeps2
let sourceMap = Map.unions
[ Map.fromList $ flip map locals $ \lp ->
let p = lpPackage lp
in (packageName p, PSLocal lp)
, extraDeps3
, flip fmap (mbpPackages mbp) $ \mpi ->
(PSUpstream (mpiVersion mpi) Snap (mpiFlags mpi))
] `Map.difference` Map.fromList (map (, ()) (HashSet.toList wiredInPackages))
return (targets, mbp, locals, nonLocalTargets, sourceMap)
-- | Use the build options and environment to parse targets.
parseTargetsFromBuildOpts
:: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m, HasEnvConfig env)
=> NeedTargets
-> BuildOpts
-> m (MiniBuildPlan, M.Map PackageName Version, M.Map PackageName SimpleTarget)
parseTargetsFromBuildOpts needTargets bopts = do
bconfig <- asks getBuildConfig
mbp0 <-
case bcResolver bconfig of
ResolverSnapshot snapName -> do
$logDebug $ "Checking resolver: " <> renderSnapName snapName
loadMiniBuildPlan snapName
ResolverCompiler _ -> do
-- We ignore the resolver version, as it might be
-- GhcMajorVersion, and we want the exact version
-- we're using.
version <- asks (envConfigCompilerVersion . getEnvConfig)
return MiniBuildPlan
{ mbpCompilerVersion = version
, mbpPackages = Map.empty
}
ResolverCustom _ url -> do
stackYamlFP <- asks $ bcStackYaml . getBuildConfig
parseCustomMiniBuildPlan stackYamlFP url
rawLocals <- getLocalPackageViews
workingDir <- getWorkingDir
let snapshot = mpiVersion <$> mbpPackages mbp0
flagExtraDeps <- convertSnapshotToExtra
snapshot
(bcExtraDeps bconfig)
(catMaybes $ Map.keys $ boptsFlags bopts)
(cliExtraDeps, targets) <-
parseTargets
needTargets
(bcImplicitGlobal bconfig)
snapshot
(flagExtraDeps <> bcExtraDeps bconfig)
(fst <$> rawLocals)
workingDir
(boptsTargets bopts)
return (mbp0, cliExtraDeps <> flagExtraDeps, targets)
-- | For every package in the snapshot which is referenced by a flag, give the
-- user a warning and then add it to extra-deps.
convertSnapshotToExtra
:: MonadLogger m
=> Map PackageName Version -- ^ snapshot
-> Map PackageName Version -- ^ extra-deps
-> [PackageName] -- ^ packages referenced by a flag
-> m (Map PackageName Version)
convertSnapshotToExtra snapshot extra0 flags0 =
go Map.empty flags0
where
go !extra [] = return extra
go extra (flag:flags)
| Just _ <- Map.lookup flag extra0 = go extra flags
| otherwise = case Map.lookup flag snapshot of
Nothing -> go extra flags
Just version -> do
$logWarn $ T.concat
[ "- Implicitly adding "
, T.pack $ packageNameString flag
, " to extra-deps based on command line flag"
]
go (Map.insert flag version extra) flags
-- | Parse out the local package views for the current project
getLocalPackageViews :: (MonadThrow m, MonadIO m, MonadReader env m, HasEnvConfig env, MonadLogger m)
=> m (Map PackageName (LocalPackageView, GenericPackageDescription))
getLocalPackageViews = do
econfig <- asks getEnvConfig
locals <- forM (Map.toList $ envConfigPackages econfig) $ \(dir, validWanted) -> do
cabalfp <- getCabalFileName dir
(warnings,gpkg) <- readPackageUnresolved cabalfp
mapM_ (printCabalFileWarning cabalfp) warnings
let cabalID = package $ packageDescription gpkg
name = fromCabalPackageName $ pkgName $ cabalID
checkCabalFileName name cabalfp
let lpv = LocalPackageView
{ lpvVersion = fromCabalVersion $ pkgVersion cabalID
, lpvRoot = dir
, lpvCabalFP = cabalfp
, lpvExtraDep = not validWanted
, lpvComponents = getNamedComponents gpkg
}
return (name, (lpv, gpkg))
checkDuplicateNames locals
return $ Map.fromList locals
where
getNamedComponents gpkg = Set.fromList $ concat
[ maybe [] (const [CLib]) (C.condLibrary gpkg)
, go CExe C.condExecutables
, go CTest C.condTestSuites
, go CBench C.condBenchmarks
]
where
go wrapper f = map (wrapper . T.pack . fst) $ f gpkg
-- | Check if there are any duplicate package names and, if so, throw an
-- exception.
checkDuplicateNames :: MonadThrow m => [(PackageName, (LocalPackageView, gpd))] -> m ()
checkDuplicateNames locals =
case filter hasMultiples $ Map.toList $ Map.fromListWith (++) $ map toPair locals of
[] -> return ()
x -> throwM $ DuplicateLocalPackageNames x
where
toPair (pn, (lpv, _)) = (pn, [lpvRoot lpv])
hasMultiples (_, _:_:_) = True
hasMultiples _ = False
splitComponents :: [NamedComponent]
-> (Set Text, Set Text, Set Text)
splitComponents =
go id id id
where
go a b c [] = (Set.fromList $ a [], Set.fromList $ b [], Set.fromList $ c [])
go a b c (CLib:xs) = go a b c xs
go a b c (CExe x:xs) = go (a . (x:)) b c xs
go a b c (CTest x:xs) = go a (b . (x:)) c xs
go a b c (CBench x:xs) = go a b (c . (x:)) xs
-- | Upgrade the initial local package info to a full-blown @LocalPackage@
-- based on the selected components
loadLocalPackage
:: forall m env.
(MonadReader env m, HasEnvConfig env, MonadCatch m, MonadLogger m, MonadIO m)
=> BuildOpts
-> Map PackageName SimpleTarget
-> (PackageName, (LocalPackageView, GenericPackageDescription))
-> m LocalPackage
loadLocalPackage bopts targets (name, (lpv, gpkg)) = do
bconfig <- asks getBuildConfig
econfig <- asks getEnvConfig
let config = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = localFlags (boptsFlags bopts) bconfig name
, packageConfigCompilerVersion = envConfigCompilerVersion econfig
, packageConfigPlatform = configPlatform $ getConfig bconfig
}
pkg = resolvePackage config gpkg
mtarget = Map.lookup name targets
(exes, tests, benches) =
case mtarget of
Just (STLocalComps comps) -> splitComponents $ Set.toList comps
Just STLocalAll ->
( packageExes pkg
, if boptsTests bopts
then packageTests pkg
else Set.empty
, if boptsBenchmarks bopts
then packageBenchmarks pkg
else Set.empty
)
Just STNonLocal -> assert False mempty
Just STUnknown -> assert False mempty
Nothing -> mempty
btconfig = config
{ packageConfigEnableTests = not $ Set.null tests
, packageConfigEnableBenchmarks = not $ Set.null benches
}
testconfig = config
{ packageConfigEnableTests = True
, packageConfigEnableBenchmarks = False
}
benchconfig = config
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = True
}
btpkg
| Set.null tests && Set.null benches = Nothing
| otherwise = Just $ LocalPackageTB
{ lptbPackage = resolvePackage btconfig gpkg
, lptbTests = tests
, lptbBenches = benches
}
testpkg = resolvePackage testconfig gpkg
benchpkg = resolvePackage benchconfig gpkg
mbuildCache <- tryGetBuildCache $ lpvRoot lpv
(files,_) <- getPackageFilesSimple pkg (lpvCabalFP lpv)
(isDirty, newBuildCache) <- checkBuildCache
(fromMaybe Map.empty mbuildCache)
(map toFilePath $ Set.toList files)
return LocalPackage
{ lpPackage = pkg
, lpTestDeps = packageDeps $ testpkg
, lpBenchDeps = packageDeps $ benchpkg
, lpExeComponents =
case mtarget of
Nothing -> Nothing
Just _ -> Just exes
, lpTestBench = btpkg
, lpFiles = files
, lpDirtyFiles = isDirty || boptsForceDirty bopts
, lpNewBuildCache = newBuildCache
, lpCabalFile = lpvCabalFP lpv
, lpDir = lpvRoot lpv
, lpComponents = Set.unions
[ Set.map CExe exes
, Set.map CTest tests
, Set.map CBench benches
]
}
-- | Ensure that the flags specified in the stack.yaml file and on the command
-- line are used.
checkFlagsUsed :: (MonadThrow m, MonadReader env m, HasBuildConfig env)
=> BuildOpts
-> [LocalPackage]
-> Map PackageName extraDeps -- ^ extra deps
-> Map PackageName snapshot -- ^ snapshot, for error messages
-> m ()
checkFlagsUsed bopts lps extraDeps snapshot = do
bconfig <- asks getBuildConfig
-- Check if flags specified in stack.yaml and the command line are
-- used, see https://github.com/commercialhaskell/stack/issues/617
let flags = map (, FSCommandLine) [(k, v) | (Just k, v) <- Map.toList $ boptsFlags bopts]
++ map (, FSStackYaml) (Map.toList $ bcFlags bconfig)
localNameMap = Map.fromList $ map (packageName . lpPackage &&& lpPackage) lps
checkFlagUsed ((name, userFlags), source) =
case Map.lookup name localNameMap of
-- Package is not available locally
Nothing ->
case Map.lookup name extraDeps of
-- Also not in extra-deps, it's an error
Nothing ->
case Map.lookup name snapshot of
Nothing -> Just $ UFNoPackage source name
Just _ -> Just $ UFSnapshot name
-- We don't check for flag presence for extra deps
Just _ -> Nothing
-- Package exists locally, let's check if the flags are defined
Just pkg ->
let unused = Set.difference (Map.keysSet userFlags) (packageDefinedFlags pkg)
in if Set.null unused
-- All flags are defined, nothing to do
then Nothing
-- Error about the undefined flags
else Just $ UFFlagsNotDefined source pkg unused
unusedFlags = mapMaybe checkFlagUsed flags
unless (null unusedFlags)
$ throwM
$ InvalidFlagSpecification
$ Set.fromList unusedFlags
-- | All flags for a local package
localFlags :: (Map (Maybe PackageName) (Map FlagName Bool))
-> BuildConfig
-> PackageName
-> Map FlagName Bool
localFlags boptsflags bconfig name = Map.unions
[ fromMaybe Map.empty $ Map.lookup (Just name) $ boptsflags
, fromMaybe Map.empty $ Map.lookup Nothing $ boptsflags
, fromMaybe Map.empty $ Map.lookup name $ bcFlags bconfig
]
-- | Add in necessary packages to extra dependencies
--
-- Originally part of https://github.com/commercialhaskell/stack/issues/272,
-- this was then superseded by
-- https://github.com/commercialhaskell/stack/issues/651
extendExtraDeps :: (MonadThrow m, MonadReader env m, HasBuildConfig env)
=> Map PackageName Version -- ^ original extra deps
-> Map PackageName Version -- ^ package identifiers from the command line
-> Set PackageName -- ^ all packages added on the command line
-> Map PackageName Version -- ^ latest versions in indices
-> m (Map PackageName Version) -- ^ new extradeps
extendExtraDeps extraDeps0 cliExtraDeps unknowns latestVersion
| null errs = return $ Map.unions $ extraDeps1 : unknowns'
| otherwise = do
bconfig <- asks getBuildConfig
throwM $ UnknownTargets
(Set.fromList errs)
Map.empty -- TODO check the cliExtraDeps for presence in index
(bcStackYaml bconfig)
where
extraDeps1 = Map.union extraDeps0 cliExtraDeps
(errs, unknowns') = partitionEithers $ map addUnknown $ Set.toList unknowns
addUnknown pn =
case Map.lookup pn extraDeps1 of
Just _ -> Right Map.empty
Nothing ->
case Map.lookup pn latestVersion of
Just v -> Right $ Map.singleton pn v
Nothing -> Left pn
-- | Compare the current filesystem state to the cached information, and
-- determine (1) if the files are dirty, and (2) the new cache values.
checkBuildCache :: MonadIO m
=> Map FilePath FileCacheInfo -- ^ old cache
-> [FilePath] -- ^ files in package
-> m (Bool, Map FilePath FileCacheInfo)
checkBuildCache oldCache files = liftIO $ do
(Any isDirty, m) <- fmap mconcat $ mapM go files
return (isDirty, m)
where
go fp = do
mmodTime <- getModTimeMaybe fp
case mmodTime of
Nothing -> return (Any False, Map.empty)
Just modTime' -> do
(isDirty, newFci) <-
case Map.lookup fp oldCache of
Just fci
| fciModTime fci == modTime' -> return (False, fci)
| otherwise -> do
newFci <- calcFci modTime' fp
let isDirty =
fciSize fci /= fciSize newFci ||
fciHash fci /= fciHash newFci
return (isDirty, newFci)
Nothing -> do
newFci <- calcFci modTime' fp
return (True, newFci)
return (Any isDirty, Map.singleton fp newFci)
-- | Returns entries to add to the build cache for any newly found unlisted modules
addUnlistedToBuildCache
:: (MonadIO m, MonadReader env m, MonadCatch m, MonadLogger m, HasEnvConfig env)
=> ModTime
-> Package
-> Path Abs File
-> Map FilePath a
-> m ([Map FilePath FileCacheInfo], [PackageWarning])
addUnlistedToBuildCache preBuildTime pkg cabalFP buildCache = do
(files,warnings) <- getPackageFilesSimple pkg cabalFP
let newFiles =
Set.toList $
Set.map toFilePath files `Set.difference` Map.keysSet buildCache
addBuildCache <- mapM addFileToCache newFiles
return (addBuildCache, warnings)
where
addFileToCache fp = do
mmodTime <- getModTimeMaybe fp
case mmodTime of
Nothing -> return Map.empty
Just modTime' ->
if modTime' < preBuildTime
then do
newFci <- calcFci modTime' fp
return (Map.singleton fp newFci)
else return Map.empty
-- | Gets list of Paths for files in a package
getPackageFilesSimple
:: (MonadIO m, MonadReader env m, MonadCatch m, MonadLogger m, HasEnvConfig env)
=> Package -> Path Abs File -> m (Set (Path Abs File), [PackageWarning])
getPackageFilesSimple pkg cabalFP = do
(_,compFiles,cabalFiles,warnings) <-
getPackageFiles (packageFiles pkg) cabalFP
return
( Set.map dotCabalGetPath (mconcat (M.elems compFiles)) <> cabalFiles
, warnings)
-- | Get file modification time, if it exists.
getModTimeMaybe :: MonadIO m => FilePath -> m (Maybe ModTime)
getModTimeMaybe fp =
liftIO
(catch
(liftM
(Just . modTime)
(getModificationTime fp))
(\e ->
if isDoesNotExistError e
then return Nothing
else throwM e))
-- | Create FileCacheInfo for a file.
calcFci :: MonadIO m => ModTime -> FilePath -> m FileCacheInfo
calcFci modTime' fp = liftIO $
withBinaryFile fp ReadMode $ \h -> do
(size, digest) <- CB.sourceHandle h $$ getZipSink
((,)
<$> ZipSink (CL.fold
(\x y -> x + fromIntegral (S.length y))
0)
<*> ZipSink sinkHash)
return FileCacheInfo
{ fciModTime = modTime'
, fciSize = size
, fciHash = toBytes (digest :: Digest SHA256)
}
| kairuku/stack | src/Stack/Build/Source.hs | bsd-3-clause | 22,503 | 0 | 27 | 7,594 | 5,259 | 2,719 | 2,540 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | Graph coloring register allocator.
module RegAlloc.Graph.Main (
regAlloc
) where
import GhcPrelude
import qualified GraphColor as Color
import RegAlloc.Liveness
import RegAlloc.Graph.Spill
import RegAlloc.Graph.SpillClean
import RegAlloc.Graph.SpillCost
import RegAlloc.Graph.Stats
import RegAlloc.Graph.TrivColorable
import Instruction
import TargetReg
import RegClass
import Reg
import Bag
import DynFlags
import Outputable
import Platform
import UniqFM
import UniqSet
import UniqSupply
import Util (seqList)
import Data.List
import Data.Maybe
import Control.Monad
-- | The maximum number of build\/spill cycles we'll allow.
--
-- It should only take 3 or 4 cycles for the allocator to converge.
-- If it takes any longer than this it's probably in an infinite loop,
-- so it's better just to bail out and report a bug.
maxSpinCount :: Int
maxSpinCount = 10
-- | The top level of the graph coloring register allocator.
regAlloc
:: (Outputable statics, Outputable instr, Instruction instr)
=> DynFlags
-> UniqFM (UniqSet RealReg) -- ^ registers we can use for allocation
-> UniqSet Int -- ^ set of available spill slots.
-> [LiveCmmDecl statics instr] -- ^ code annotated with liveness information.
-> UniqSM ( [NatCmmDecl statics instr], [RegAllocStats statics instr] )
-- ^ code with registers allocated and stats for each stage of
-- allocation
regAlloc dflags regsFree slotsFree code
= do
-- TODO: the regClass function is currently hard coded to the default
-- target architecture. Would prefer to determine this from dflags.
-- There are other uses of targetRegClass later in this module.
let platform = targetPlatform dflags
triv = trivColorable platform
(targetVirtualRegSqueeze platform)
(targetRealRegSqueeze platform)
(code_final, debug_codeGraphs, _)
<- regAlloc_spin dflags 0
triv
regsFree slotsFree [] code
return ( code_final
, reverse debug_codeGraphs )
-- | Perform solver iterations for the graph coloring allocator.
--
-- We extract a register confict graph from the provided cmm code,
-- and try to colour it. If that works then we use the solution rewrite
-- the code with real hregs. If coloring doesn't work we add spill code
-- and try to colour it again. After `maxSpinCount` iterations we give up.
--
regAlloc_spin
:: (Instruction instr,
Outputable instr,
Outputable statics)
=> DynFlags
-> Int -- ^ Number of solver iterations we've already performed.
-> Color.Triv VirtualReg RegClass RealReg
-- ^ Function for calculating whether a register is trivially
-- colourable.
-> UniqFM (UniqSet RealReg) -- ^ Free registers that we can allocate.
-> UniqSet Int -- ^ Free stack slots that we can use.
-> [RegAllocStats statics instr] -- ^ Current regalloc stats to add to.
-> [LiveCmmDecl statics instr] -- ^ Liveness annotated code to allocate.
-> UniqSM ( [NatCmmDecl statics instr]
, [RegAllocStats statics instr]
, Color.Graph VirtualReg RegClass RealReg)
regAlloc_spin dflags spinCount triv regsFree slotsFree debug_codeGraphs code
= do
let platform = targetPlatform dflags
-- If any of these dump flags are turned on we want to hang on to
-- intermediate structures in the allocator - otherwise tell the
-- allocator to ditch them early so we don't end up creating space leaks.
let dump = or
[ dopt Opt_D_dump_asm_regalloc_stages dflags
, dopt Opt_D_dump_asm_stats dflags
, dopt Opt_D_dump_asm_conflicts dflags ]
-- Check that we're not running off down the garden path.
when (spinCount > maxSpinCount)
$ pprPanic "regAlloc_spin: max build/spill cycle count exceeded."
( text "It looks like the register allocator is stuck in an infinite loop."
$$ text "max cycles = " <> int maxSpinCount
$$ text "regsFree = " <> (hcat $ punctuate space $ map ppr
$ nonDetEltsUniqSet $ unionManyUniqSets
$ nonDetEltsUFM regsFree)
-- This is non-deterministic but we do not
-- currently support deterministic code-generation.
-- See Note [Unique Determinism and code generation]
$$ text "slotsFree = " <> ppr (sizeUniqSet slotsFree))
-- Build the register conflict graph from the cmm code.
(graph :: Color.Graph VirtualReg RegClass RealReg)
<- {-# SCC "BuildGraph" #-} buildGraph code
-- VERY IMPORTANT:
-- We really do want the graph to be fully evaluated _before_ we
-- start coloring. If we don't do this now then when the call to
-- Color.colorGraph forces bits of it, the heap will be filled with
-- half evaluated pieces of graph and zillions of apply thunks.
seqGraph graph `seq` return ()
-- Build a map of the cost of spilling each instruction.
-- This is a lazy binding, so the map will only be computed if we
-- actually have to spill to the stack.
let spillCosts = foldl' plusSpillCostInfo zeroSpillCostInfo
$ map (slurpSpillCostInfo platform) code
-- The function to choose regs to leave uncolored.
let spill = chooseSpill spillCosts
-- Record startup state in our log.
let stat1
= if spinCount == 0
then Just $ RegAllocStatsStart
{ raLiveCmm = code
, raGraph = graph
, raSpillCosts = spillCosts }
else Nothing
-- Try and color the graph.
let (graph_colored, rsSpill, rmCoalesce)
= {-# SCC "ColorGraph" #-}
Color.colorGraph
(gopt Opt_RegsIterative dflags)
spinCount
regsFree triv spill graph
-- Rewrite registers in the code that have been coalesced.
let patchF reg
| RegVirtual vr <- reg
= case lookupUFM rmCoalesce vr of
Just vr' -> patchF (RegVirtual vr')
Nothing -> reg
| otherwise
= reg
let code_coalesced
= map (patchEraseLive patchF) code
-- Check whether we've found a coloring.
if isEmptyUniqSet rsSpill
-- Coloring was successful because no registers needed to be spilled.
then do
-- if -fasm-lint is turned on then validate the graph.
-- This checks for bugs in the graph allocator itself.
let graph_colored_lint =
if gopt Opt_DoAsmLinting dflags
then Color.validateGraph (text "")
True -- Require all nodes to be colored.
graph_colored
else graph_colored
-- Rewrite the code to use real hregs, using the colored graph.
let code_patched
= map (patchRegsFromGraph platform graph_colored_lint)
code_coalesced
-- Clean out unneeded SPILL/RELOAD meta instructions.
-- The spill code generator just spills the entire live range
-- of a vreg, but it might not need to be on the stack for
-- its entire lifetime.
let code_spillclean
= map (cleanSpills platform) code_patched
-- Strip off liveness information from the allocated code.
-- Also rewrite SPILL/RELOAD meta instructions into real machine
-- instructions along the way
let code_final
= map (stripLive dflags) code_spillclean
-- Record what happened in this stage for debugging
let stat
= RegAllocStatsColored
{ raCode = code
, raGraph = graph
, raGraphColored = graph_colored_lint
, raCoalesced = rmCoalesce
, raCodeCoalesced = code_coalesced
, raPatched = code_patched
, raSpillClean = code_spillclean
, raFinal = code_final
, raSRMs = foldl' addSRM (0, 0, 0)
$ map countSRMs code_spillclean }
-- Bundle up all the register allocator statistics.
-- .. but make sure to drop them on the floor if they're not
-- needed, otherwise we'll get a space leak.
let statList =
if dump then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
else []
-- Ensure all the statistics are evaluated, to avoid space leaks.
seqList statList (return ())
return ( code_final
, statList
, graph_colored_lint)
-- Coloring was unsuccessful. We need to spill some register to the
-- stack, make a new graph, and try to color it again.
else do
-- if -fasm-lint is turned on then validate the graph
let graph_colored_lint =
if gopt Opt_DoAsmLinting dflags
then Color.validateGraph (text "")
False -- don't require nodes to be colored
graph_colored
else graph_colored
-- Spill uncolored regs to the stack.
(code_spilled, slotsFree', spillStats)
<- regSpill platform code_coalesced slotsFree rsSpill
-- Recalculate liveness information.
-- NOTE: we have to reverse the SCCs here to get them back into
-- the reverse-dependency order required by computeLiveness.
-- If they're not in the correct order that function will panic.
code_relive <- mapM (regLiveness platform . reverseBlocksInTops)
code_spilled
-- Record what happened in this stage for debugging.
let stat =
RegAllocStatsSpill
{ raCode = code
, raGraph = graph_colored_lint
, raCoalesced = rmCoalesce
, raSpillStats = spillStats
, raSpillCosts = spillCosts
, raSpilled = code_spilled }
-- Bundle up all the register allocator statistics.
-- .. but make sure to drop them on the floor if they're not
-- needed, otherwise we'll get a space leak.
let statList =
if dump
then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
else []
-- Ensure all the statistics are evaluated, to avoid space leaks.
seqList statList (return ())
regAlloc_spin dflags (spinCount + 1) triv regsFree slotsFree'
statList
code_relive
-- | Build a graph from the liveness and coalesce information in this code.
buildGraph
:: Instruction instr
=> [LiveCmmDecl statics instr]
-> UniqSM (Color.Graph VirtualReg RegClass RealReg)
buildGraph code
= do
-- Slurp out the conflicts and reg->reg moves from this code.
let (conflictList, moveList) =
unzip $ map slurpConflicts code
-- Slurp out the spill/reload coalesces.
let moveList2 = map slurpReloadCoalesce code
-- Add the reg-reg conflicts to the graph.
let conflictBag = unionManyBags conflictList
let graph_conflict
= foldrBag graphAddConflictSet Color.initGraph conflictBag
-- Add the coalescences edges to the graph.
let moveBag
= unionBags (unionManyBags moveList2)
(unionManyBags moveList)
let graph_coalesce
= foldrBag graphAddCoalesce graph_conflict moveBag
return graph_coalesce
-- | Add some conflict edges to the graph.
-- Conflicts between virtual and real regs are recorded as exclusions.
graphAddConflictSet
:: UniqSet Reg
-> Color.Graph VirtualReg RegClass RealReg
-> Color.Graph VirtualReg RegClass RealReg
graphAddConflictSet set graph
= let virtuals = mkUniqSet
[ vr | RegVirtual vr <- nonDetEltsUniqSet set ]
graph1 = Color.addConflicts virtuals classOfVirtualReg graph
graph2 = foldr (\(r1, r2) -> Color.addExclusion r1 classOfVirtualReg r2)
graph1
[ (vr, rr)
| RegVirtual vr <- nonDetEltsUniqSet set
, RegReal rr <- nonDetEltsUniqSet set]
-- See Note [Unique Determinism and code generation]
in graph2
-- | Add some coalesence edges to the graph
-- Coalesences between virtual and real regs are recorded as preferences.
graphAddCoalesce
:: (Reg, Reg)
-> Color.Graph VirtualReg RegClass RealReg
-> Color.Graph VirtualReg RegClass RealReg
graphAddCoalesce (r1, r2) graph
| RegReal rr <- r1
, RegVirtual vr <- r2
= Color.addPreference (vr, classOfVirtualReg vr) rr graph
| RegReal rr <- r2
, RegVirtual vr <- r1
= Color.addPreference (vr, classOfVirtualReg vr) rr graph
| RegVirtual vr1 <- r1
, RegVirtual vr2 <- r2
= Color.addCoalesce
(vr1, classOfVirtualReg vr1)
(vr2, classOfVirtualReg vr2)
graph
-- We can't coalesce two real regs, but there could well be existing
-- hreg,hreg moves in the input code. We'll just ignore these
-- for coalescing purposes.
| RegReal _ <- r1
, RegReal _ <- r2
= graph
| otherwise
= panic "graphAddCoalesce"
-- | Patch registers in code using the reg -> reg mapping in this graph.
patchRegsFromGraph
:: (Outputable statics, Outputable instr, Instruction instr)
=> Platform -> Color.Graph VirtualReg RegClass RealReg
-> LiveCmmDecl statics instr -> LiveCmmDecl statics instr
patchRegsFromGraph platform graph code
= patchEraseLive patchF code
where
-- Function to lookup the hardreg for a virtual reg from the graph.
patchF reg
-- leave real regs alone.
| RegReal{} <- reg
= reg
-- this virtual has a regular node in the graph.
| RegVirtual vr <- reg
, Just node <- Color.lookupNode graph vr
= case Color.nodeColor node of
Just color -> RegReal color
Nothing -> RegVirtual vr
-- no node in the graph for this virtual, bad news.
| otherwise
= pprPanic "patchRegsFromGraph: register mapping failed."
( text "There is no node in the graph for register "
<> ppr reg
$$ ppr code
$$ Color.dotGraph
(\_ -> text "white")
(trivColorable platform
(targetVirtualRegSqueeze platform)
(targetRealRegSqueeze platform))
graph)
-----
-- for when laziness just isn't what you wanted...
-- We need to deepSeq the whole graph before trying to colour it to avoid
-- space leaks.
seqGraph :: Color.Graph VirtualReg RegClass RealReg -> ()
seqGraph graph = seqNodes (nonDetEltsUFM (Color.graphMap graph))
-- See Note [Unique Determinism and code generation]
seqNodes :: [Color.Node VirtualReg RegClass RealReg] -> ()
seqNodes ns
= case ns of
[] -> ()
(n : ns) -> seqNode n `seq` seqNodes ns
seqNode :: Color.Node VirtualReg RegClass RealReg -> ()
seqNode node
= seqVirtualReg (Color.nodeId node)
`seq` seqRegClass (Color.nodeClass node)
`seq` seqMaybeRealReg (Color.nodeColor node)
`seq` (seqVirtualRegList (nonDetEltsUniqSet (Color.nodeConflicts node)))
`seq` (seqRealRegList (nonDetEltsUniqSet (Color.nodeExclusions node)))
`seq` (seqRealRegList (Color.nodePreference node))
`seq` (seqVirtualRegList (nonDetEltsUniqSet (Color.nodeCoalesce node)))
-- It's OK to use nonDetEltsUniqSet for seq
seqVirtualReg :: VirtualReg -> ()
seqVirtualReg reg = reg `seq` ()
seqRealReg :: RealReg -> ()
seqRealReg reg = reg `seq` ()
seqRegClass :: RegClass -> ()
seqRegClass c = c `seq` ()
seqMaybeRealReg :: Maybe RealReg -> ()
seqMaybeRealReg mr
= case mr of
Nothing -> ()
Just r -> seqRealReg r
seqVirtualRegList :: [VirtualReg] -> ()
seqVirtualRegList rs
= case rs of
[] -> ()
(r : rs) -> seqVirtualReg r `seq` seqVirtualRegList rs
seqRealRegList :: [RealReg] -> ()
seqRealRegList rs
= case rs of
[] -> ()
(r : rs) -> seqRealReg r `seq` seqRealRegList rs
| ezyang/ghc | compiler/nativeGen/RegAlloc/Graph/Main.hs | bsd-3-clause | 18,575 | 0 | 19 | 7,204 | 2,779 | 1,448 | 1,331 | 281 | 8 |
let foo = 1
bar = baz
quux
in
| ruchee/vimrc | vimfiles/bundle/vim-haskell/tests/indent/test018/test.hs | mit | 49 | 0 | 9 | 26 | 23 | 10 | 13 | -1 | -1 |
module ImgTex (plugin) where
{-
This plugin provides a clear math LaTeX output.
(* latex and dvipng executable must be in the path.)
like this:
~~~ {.dvipng}
\nabla \times \bm{V}
=
\frac{1}{h_1 h_2 h_3}
\begin{vmatrix}
h_1 e_1 & h_2 e_2 & h_3 e_3 \\
\frac{\partial}{\partial q_{1}} &
\frac{\partial}{\partial q_{2}} &
\frac{\partial}{\partial q_{3}} \\
h_1 V_1 & h_2 V_2 & h_3 V_3
\end{vmatrix}
~~~
License: GPL
written by Kohei OZAKI <i@smly.org>
modified by John MacFarlane to use withTempDir
-}
import Network.Gitit.Interface
import System.Process (system)
import System.Directory
import Data.ByteString.Lazy.UTF8 (fromString)
import Data.Digest.Pure.SHA
import System.FilePath
import Control.Monad.Trans (liftIO)
plugin :: Plugin
plugin = mkPageTransformM transformBlock
templateHeader, templateFooter :: String
templateHeader = concat
[ "\\documentclass[12pt]{article}\n"
, "\\usepackage{amsmath,amssymb,bm}\n"
, "\\begin{document}\n"
, "\\thispagestyle{empty}\n"
, "\\[\n"]
templateFooter =
"\n"
++ "\\]\n"
++ "\\end{document}\n"
transformBlock :: Block -> PluginM Block
transformBlock (CodeBlock (_, classes, namevals) contents)
| "dvipng" `elem` classes = do
cfg <- askConfig
let (name, outfile) = case lookup "name" namevals of
Just fn -> ([Str fn], fn ++ ".png")
Nothing -> ([], uniqueName contents ++ ".png")
curr <- liftIO getCurrentDirectory
liftIO $ withTempDir "gitit-imgtex" $ \tmpdir -> do
setCurrentDirectory tmpdir
writeFile (outfile ++ ".tex") (templateHeader ++ contents ++ templateFooter)
system $ "latex " ++ outfile ++ ".tex > /dev/null"
setCurrentDirectory curr
system $ "dvipng -T tight -bd 1000 -freetype0 -Q 5 --gamma 1.3 " ++
(tmpdir </> outfile <.> "dvi") ++ " -o " ++ (staticDir cfg </> "img" </> outfile)
return $ Para [Image name ("/img" </> outfile, "")]
transformBlock x = return x
uniqueName :: String -> String
uniqueName = showDigest . sha1 . fromString
| bergmannf/gitit | plugins/ImgTex.hs | gpl-2.0 | 2,092 | 0 | 17 | 462 | 436 | 231 | 205 | 40 | 2 |
-- !!! testing hGetLine
import System.IO
-- one version of 'cat'
main = do
let loop h = do b <- hIsEOF h
if b then return ()
else do l <- hGetLine h; putStrLn l; loop h
loop stdin
h <- openFile "hGetLine001.hs" ReadMode
hSetBinaryMode stdout True
hSetBuffering h NoBuffering
loop h
hSeek h AbsoluteSeek 0
hSetBuffering h LineBuffering
loop h
hSeek h AbsoluteSeek 0
hSetBuffering h (BlockBuffering (Just 83))
loop h
| ezyang/ghc | libraries/base/tests/IO/hGetLine001.hs | bsd-3-clause | 487 | 1 | 16 | 145 | 178 | 74 | 104 | 16 | 2 |
{-# LANGUAGE MonomorphismRestriction, NoExtendedDefaultRules #-}
module T10971b where
import Data.Traversable (fmapDefault)
f = \x -> length x
g = \f x -> fmapDefault f x
h = \f x -> (fmapDefault f x, length x)
| ezyang/ghc | testsuite/tests/typecheck/should_fail/T10971b.hs | bsd-3-clause | 211 | 0 | 7 | 35 | 71 | 40 | 31 | 6 | 1 |
-- !!! Redefining an imported name
-- was: Imported var clashes with local var definition
module M where
import Prelude(id)
id x = x
| holzensp/ghc | testsuite/tests/module/mod33.hs | bsd-3-clause | 133 | 0 | 5 | 24 | 22 | 14 | 8 | 3 | 1 |
main = print "ok"
| wxwxwwxxx/ghc | testsuite/tests/rts/T7037.hs | bsd-3-clause | 18 | 1 | 4 | 4 | 12 | 4 | 8 | 1 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
module LesserActionSpec where
import Algebra.LesserAction
import Algebra.SemiLatticeAction
import Data.ChatData
import Data.Map (Map)
import Data.Proxy
import Data.Set
import Test.Tasty
import Test.Tasty.QuickCheck
allLesserAction :: TestTree
allLesserAction = testGroup "LesserAction"
[ setIsJoinLesserAction
, chatDataLesserAction
, specJoinLesserAction (Proxy :: Proxy (Map Int (Set Int))) (Proxy :: Proxy (Map Int (Set Int))) "Map Int (Set Int) is LesserAction"
]
applicationOfLesserAction :: (Eq a, JoinLesserAction s a) => s -> a -> Bool
applicationOfLesserAction action state = joinLesserEq action state == (apply action state == state)
specJoinLesserAction :: forall s a. (JoinLesserAction s a, Arbitrary s, Arbitrary a, Eq a, Show s, Show a) =>
Proxy s -> Proxy a -> String -> TestTree
specJoinLesserAction _ _ name = testGroup name
[ testProperty "is lesser action iff no change" (applicationOfLesserAction :: s -> a -> Bool)]
setIsJoinLesserAction :: TestTree
setIsJoinLesserAction = testGroup "set is JoinLesserAction"
[ testProperty "joinLesserEq action state == (apply action state == state)" (applicationOfLesserAction:: Set Int -> Set Int -> Bool)]
chatDataLesserAction :: TestTree
chatDataLesserAction =
specJoinLesserAction (Proxy :: Proxy (ChatData String)) (Proxy :: Proxy (ChatData String)) "ChatData is JoinLesserAction"
| blargg/crdt | src-test/LesserActionSpec.hs | isc | 1,577 | 0 | 13 | 343 | 389 | 208 | 181 | 28 | 1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.Enums
(KeyType(..), ToJSVal, FromJSVal, js_KeyTypePublic,
js_KeyTypePrivate, js_KeyTypeSecret, CryptoKeyUsage(..),
js_CryptoKeyUsageEncrypt, js_CryptoKeyUsageDecrypt,
js_CryptoKeyUsageSign, js_CryptoKeyUsageVerify,
js_CryptoKeyUsageDeriveKey, js_CryptoKeyUsageDeriveBits,
js_CryptoKeyUsageWrapKey, js_CryptoKeyUsageUnwrapKey,
KeyFormat(..), js_KeyFormatRaw, js_KeyFormatSpki,
js_KeyFormatPkcs8, js_KeyFormatJwk, FontFaceLoadStatus(..),
js_FontFaceLoadStatusUnloaded, js_FontFaceLoadStatusLoading,
js_FontFaceLoadStatusLoaded, js_FontFaceLoadStatusError,
FontFaceSetLoadStatus(..), js_FontFaceSetLoadStatusLoading,
js_FontFaceSetLoadStatusLoaded, VisibilityState(..),
js_VisibilityStateHidden, js_VisibilityStateVisible,
js_VisibilityStatePrerender, DocumentReadyState(..),
js_DocumentReadyStateLoading, js_DocumentReadyStateInteractive,
js_DocumentReadyStateComplete, ShadowRootMode(..),
js_ShadowRootModeUserAgent, js_ShadowRootModeClosed,
js_ShadowRootModeOpen, BlobLineEndings(..),
js_BlobLineEndingsTransparent, js_BlobLineEndingsNative,
ImageSmoothingQuality(..), js_ImageSmoothingQualityLow,
js_ImageSmoothingQualityMedium, js_ImageSmoothingQualityHigh,
CanvasWindingRule(..), js_CanvasWindingRuleNonzero,
js_CanvasWindingRuleEvenodd, WebGLPowerPreference(..),
js_WebGLPowerPreferenceDefault, js_WebGLPowerPreferenceLowPower,
js_WebGLPowerPreferenceHighPerformance, WebGPUCompareFunction(..),
js_WebGPUCompareFunctionNever, js_WebGPUCompareFunctionLess,
js_WebGPUCompareFunctionEqual, js_WebGPUCompareFunctionLessequal,
js_WebGPUCompareFunctionGreater, js_WebGPUCompareFunctionNotequal,
js_WebGPUCompareFunctionGreaterequal,
js_WebGPUCompareFunctionAlways, WebGPUPixelFormat(..),
js_WebGPUPixelFormatBGRA8Unorm, WebGPULoadAction(..),
js_WebGPULoadActionDontcare, js_WebGPULoadActionLoad,
js_WebGPULoadActionClear, WebGPUStoreAction(..),
js_WebGPUStoreActionDontcare, js_WebGPUStoreActionStore,
js_WebGPUStoreActionMultisampleresolve, WebGPUPrimitiveType(..),
js_WebGPUPrimitiveTypePoint, js_WebGPUPrimitiveTypeLine,
js_WebGPUPrimitiveTypeLinestrip, js_WebGPUPrimitiveTypeTriangle,
js_WebGPUPrimitiveTypeTrianglestrip, WebGPUFunctionType(..),
js_WebGPUFunctionTypeFragment, js_WebGPUFunctionTypeVertex,
WebGPUStencilOperation(..), js_WebGPUStencilOperationKeep,
js_WebGPUStencilOperationZero, js_WebGPUStencilOperationReplace,
js_WebGPUStencilOperationIncrementclamp,
js_WebGPUStencilOperationDecrementclamp,
js_WebGPUStencilOperationInvert,
js_WebGPUStencilOperationIncrementwrap,
js_WebGPUStencilOperationDecrementwrap, WebGPUStatus(..),
js_WebGPUStatusNotenqueued, js_WebGPUStatusEnqueued,
js_WebGPUStatusCommitted, js_WebGPUStatusScheduled,
js_WebGPUStatusCompleted, js_WebGPUStatusError,
WebGPUSamplerAddressMode(..),
js_WebGPUSamplerAddressModeClamptoedge,
js_WebGPUSamplerAddressModeMirrorclamptoedge,
js_WebGPUSamplerAddressModeRepeat,
js_WebGPUSamplerAddressModeMirrorrepeat,
js_WebGPUSamplerAddressModeClamptozero,
WebGPUSamplerMinMagFilter(..), js_WebGPUSamplerMinMagFilterNearest,
js_WebGPUSamplerMinMagFilterLinear, WebGPUSamplerMipFilter(..),
js_WebGPUSamplerMipFilterNotmipmapped,
js_WebGPUSamplerMipFilterNearest, js_WebGPUSamplerMipFilterLinear,
WebGPUCullMode(..), js_WebGPUCullModeNone, js_WebGPUCullModeFront,
js_WebGPUCullModeBack, WebGPUIndexType(..),
js_WebGPUIndexTypeUint16, js_WebGPUIndexTypeUint32,
WebGPUVisibilityResultMode(..),
js_WebGPUVisibilityResultModeDisabled,
js_WebGPUVisibilityResultModeBoolean,
js_WebGPUVisibilityResultModeCounting, WebGPUWinding(..),
js_WebGPUWindingClockwise, js_WebGPUWindingCounterclockwise,
WebGPUDepthClipMode(..), js_WebGPUDepthClipModeClip,
js_WebGPUDepthClipModeClamp, WebGPUTriangleFillMode(..),
js_WebGPUTriangleFillModeFill, js_WebGPUTriangleFillModeLines,
WebGPUCPUCacheMode(..), js_WebGPUCPUCacheModeDefaultcache,
js_WebGPUCPUCacheModeWritecombined, WebGPUStorageMode(..),
js_WebGPUStorageModeShared, js_WebGPUStorageModeManaged,
js_WebGPUStorageModePrivate, WebGPUResourceOptions(..),
js_WebGPUResourceOptionsCpucachemodedefaultcache,
js_WebGPUResourceOptionsCpucachemodewritecombined,
js_WebGPUResourceOptionsStoragemodeshared,
js_WebGPUResourceOptionsStoragemodemanaged,
js_WebGPUResourceOptionsStoragemodeprivate,
js_WebGPUResourceOptionsOptioncpucachemodedefaultcache,
js_WebGPUResourceOptionsOptioncpucachemodewritecombined,
WebGPUTextureUsage(..), js_WebGPUTextureUsageUnknown,
js_WebGPUTextureUsageShaderread, js_WebGPUTextureUsageShaderwrite,
js_WebGPUTextureUsageRendertarget,
js_WebGPUTextureUsagePixelformatview, WebGPUBlendOperation(..),
js_WebGPUBlendOperationAdd, js_WebGPUBlendOperationSubtract,
js_WebGPUBlendOperationReversesubtract, js_WebGPUBlendOperationMin,
js_WebGPUBlendOperationMax, WebGPUBlendFactor(..),
js_WebGPUBlendFactorZero, js_WebGPUBlendFactorOne,
js_WebGPUBlendFactorSourcecolor,
js_WebGPUBlendFactorOneminussourcecolor,
js_WebGPUBlendFactorSourcealpha,
js_WebGPUBlendFactorOneminussourcealpha,
js_WebGPUBlendFactorDestinationcolor,
js_WebGPUBlendFactorOneminusdestinationcolor,
js_WebGPUBlendFactorDestinationalpha,
js_WebGPUBlendFactorOneminusdestinationalpha,
js_WebGPUBlendFactorSourcealphasaturated,
js_WebGPUBlendFactorBlendcolor,
js_WebGPUBlendFactorOneminusblendcolor,
js_WebGPUBlendFactorBlendalpha,
js_WebGPUBlendFactorOneminusblendalpha, WebGPUColorWriteMask(..),
js_WebGPUColorWriteMaskNone, js_WebGPUColorWriteMaskRed,
js_WebGPUColorWriteMaskGreen, js_WebGPUColorWriteMaskBlue,
js_WebGPUColorWriteMaskAlpha, js_WebGPUColorWriteMaskAll,
WebGPUMultisampleDepthResolveFilter(..),
js_WebGPUMultisampleDepthResolveFilterSample0,
js_WebGPUMultisampleDepthResolveFilterMin,
js_WebGPUMultisampleDepthResolveFilterMax, WebGPUFeatureSet(..),
js_WebGPUFeatureSetLevel1, js_WebGPUFeatureSetLevel2,
VideoPresentationMode(..), js_VideoPresentationModeFullscreen,
js_VideoPresentationModePictureInPicture,
js_VideoPresentationModeInline, TextTrackMode(..),
js_TextTrackModeDisabled, js_TextTrackModeHidden,
js_TextTrackModeShowing, TextTrackKind(..),
js_TextTrackKindSubtitles, js_TextTrackKindCaptions,
js_TextTrackKindDescriptions, js_TextTrackKindChapters,
js_TextTrackKindMetadata, js_TextTrackKindForced,
ApplePayErrorCode(..), js_ApplePayErrorCodeUnknown,
js_ApplePayErrorCodeShippingContactInvalid,
js_ApplePayErrorCodeBillingContactInvalid,
js_ApplePayErrorCodeAddressUnservicable,
ApplePayErrorContactField(..),
js_ApplePayErrorContactFieldPhoneNumber,
js_ApplePayErrorContactFieldEmailAddress,
js_ApplePayErrorContactFieldName,
js_ApplePayErrorContactFieldPostalAddress,
js_ApplePayErrorContactFieldAddressLines,
js_ApplePayErrorContactFieldLocality,
js_ApplePayErrorContactFieldPostalCode,
js_ApplePayErrorContactFieldAdministrativeArea,
js_ApplePayErrorContactFieldCountry, ApplePayLineItemType(..),
js_ApplePayLineItemTypePending, js_ApplePayLineItemTypeFinal,
ApplePayPaymentMethodType(..), js_ApplePayPaymentMethodTypeDebit,
js_ApplePayPaymentMethodTypeCredit,
js_ApplePayPaymentMethodTypePrepaid,
js_ApplePayPaymentMethodTypeStore,
ApplePayPaymentPassActivationState(..),
js_ApplePayPaymentPassActivationStateActivated,
js_ApplePayPaymentPassActivationStateRequiresActivation,
js_ApplePayPaymentPassActivationStateActivating,
js_ApplePayPaymentPassActivationStateSuspended,
js_ApplePayPaymentPassActivationStateDeactivated,
ApplePayMerchantCapability(..),
js_ApplePayMerchantCapabilitySupports3DS,
js_ApplePayMerchantCapabilitySupportsEMV,
js_ApplePayMerchantCapabilitySupportsCredit,
js_ApplePayMerchantCapabilitySupportsDebit,
ApplePayContactField(..), js_ApplePayContactFieldEmail,
js_ApplePayContactFieldName, js_ApplePayContactFieldPhone,
js_ApplePayContactFieldPostalAddress, ApplePayShippingType(..),
js_ApplePayShippingTypeShipping, js_ApplePayShippingTypeDelivery,
js_ApplePayShippingTypeStorePickup,
js_ApplePayShippingTypeServicePickup, MediaKeyMessageType(..),
js_MediaKeyMessageTypeLicenseRequest,
js_MediaKeyMessageTypeLicenseRenewal,
js_MediaKeyMessageTypeLicenseRelease,
js_MediaKeyMessageTypeIndividualizationRequest,
MediaKeySessionType(..), js_MediaKeySessionTypeTemporary,
js_MediaKeySessionTypePersistentUsageRecord,
js_MediaKeySessionTypePersistentLicense, MediaKeysRequirement(..),
js_MediaKeysRequirementRequired, js_MediaKeysRequirementOptional,
js_MediaKeysRequirementNotAllowed, MediaKeyStatus(..),
js_MediaKeyStatusUsable, js_MediaKeyStatusExpired,
js_MediaKeyStatusReleased, js_MediaKeyStatusOutputRestricted,
js_MediaKeyStatusOutputDownscaled, js_MediaKeyStatusStatusPending,
js_MediaKeyStatusInternalError, RequestType(..), js_RequestType,
js_RequestTypeAudio, js_RequestTypeFont, js_RequestTypeImage,
js_RequestTypeScript, js_RequestTypeStyle, js_RequestTypeTrack,
js_RequestTypeVideo, RequestDestination(..), js_RequestDestination,
js_RequestDestinationDocument, js_RequestDestinationSharedworker,
js_RequestDestinationSubresource, js_RequestDestinationUnknown,
js_RequestDestinationWorker, RequestMode(..),
js_RequestModeNavigate, js_RequestModeSameOrigin,
js_RequestModeNoCors, js_RequestModeCors, RequestCredentials(..),
js_RequestCredentialsOmit, js_RequestCredentialsSameOrigin,
js_RequestCredentialsInclude, RequestCache(..),
js_RequestCacheDefault, js_RequestCacheNoStore,
js_RequestCacheReload, js_RequestCacheNoCache,
js_RequestCacheForceCache, js_RequestCacheOnlyIfCached,
RequestRedirect(..), js_RequestRedirectFollow,
js_RequestRedirectError, js_RequestRedirectManual,
ReferrerPolicy(..), js_ReferrerPolicy, js_ReferrerPolicyNoReferrer,
js_ReferrerPolicyNoReferrerWhenDowngrade, js_ReferrerPolicyOrigin,
js_ReferrerPolicyOriginWhenCrossOrigin, js_ReferrerPolicyUnsafeUrl,
ResponseType(..), js_ResponseTypeBasic, js_ResponseTypeCors,
js_ResponseTypeDefault, js_ResponseTypeError,
js_ResponseTypeOpaque, js_ResponseTypeOpaqueredirect,
IDBCursorDirection(..), js_IDBCursorDirectionNext,
js_IDBCursorDirectionNextunique, js_IDBCursorDirectionPrev,
js_IDBCursorDirectionPrevunique, IDBRequestReadyState(..),
js_IDBRequestReadyStatePending, js_IDBRequestReadyStateDone,
IDBTransactionMode(..), js_IDBTransactionModeReadonly,
js_IDBTransactionModeReadwrite, js_IDBTransactionModeVersionchange,
DeviceType(..), js_DeviceTypeNone, js_DeviceTypeAirplay,
js_DeviceTypeTvout, MediaSessionKind(..),
js_MediaSessionKindContent, js_MediaSessionKindTransient,
js_MediaSessionKindTransientSolo, js_MediaSessionKindAmbient,
EndOfStreamError(..), js_EndOfStreamErrorNetwork,
js_EndOfStreamErrorDecode, ReadyState(..), js_ReadyStateClosed,
js_ReadyStateOpen, js_ReadyStateEnded, AppendMode(..),
js_AppendModeSegments, js_AppendModeSequence, MediaDeviceKind(..),
js_MediaDeviceKindAudioinput, js_MediaDeviceKindAudiooutput,
js_MediaDeviceKindVideoinput, MediaStreamTrackState(..),
js_MediaStreamTrackStateLive, js_MediaStreamTrackStateEnded,
RTCIceTransportPolicy(..), js_RTCIceTransportPolicyRelay,
js_RTCIceTransportPolicyAll, RTCBundlePolicy(..),
js_RTCBundlePolicyBalanced, js_RTCBundlePolicyMaxCompat,
js_RTCBundlePolicyMaxBundle, RTCDataChannelState(..),
js_RTCDataChannelStateConnecting, js_RTCDataChannelStateOpen,
js_RTCDataChannelStateClosing, js_RTCDataChannelStateClosed,
RTCIceConnectionState(..), js_RTCIceConnectionStateNew,
js_RTCIceConnectionStateChecking,
js_RTCIceConnectionStateConnected,
js_RTCIceConnectionStateCompleted, js_RTCIceConnectionStateFailed,
js_RTCIceConnectionStateDisconnected,
js_RTCIceConnectionStateClosed, RTCIceGatheringState(..),
js_RTCIceGatheringStateNew, js_RTCIceGatheringStateGathering,
js_RTCIceGatheringStateComplete, RTCIceTransportState(..),
js_RTCIceTransportStateNew, js_RTCIceTransportStateChecking,
js_RTCIceTransportStateConnected, js_RTCIceTransportStateCompleted,
js_RTCIceTransportStateFailed, js_RTCIceTransportStateDisconnected,
js_RTCIceTransportStateClosed, RTCPeerConnectionState(..),
js_RTCPeerConnectionStateNew, js_RTCPeerConnectionStateConnecting,
js_RTCPeerConnectionStateConnected,
js_RTCPeerConnectionStateDisconnected,
js_RTCPeerConnectionStateFailed, js_RTCPeerConnectionStateClosed,
RTCDegradationPreference(..),
js_RTCDegradationPreferenceMaintainFramerate,
js_RTCDegradationPreferenceMaintainResolution,
js_RTCDegradationPreferenceBalanced, RTCDtxStatus(..),
js_RTCDtxStatusDisabled, js_RTCDtxStatusEnabled,
RTCPriorityType(..), js_RTCPriorityTypeVeryLow,
js_RTCPriorityTypeLow, js_RTCPriorityTypeMedium,
js_RTCPriorityTypeHigh, RTCRtpTransceiverDirection(..),
js_RTCRtpTransceiverDirectionSendrecv,
js_RTCRtpTransceiverDirectionSendonly,
js_RTCRtpTransceiverDirectionRecvonly,
js_RTCRtpTransceiverDirectionInactive, RTCSdpType(..),
js_RTCSdpTypeOffer, js_RTCSdpTypePranswer, js_RTCSdpTypeAnswer,
js_RTCSdpTypeRollback, RTCSignalingState(..),
js_RTCSignalingStateStable, js_RTCSignalingStateHaveLocalOffer,
js_RTCSignalingStateHaveRemoteOffer,
js_RTCSignalingStateHaveLocalPranswer,
js_RTCSignalingStateHaveRemotePranswer, RTCStatsType(..),
js_RTCStatsTypeCodec, js_RTCStatsTypeInboundRtp,
js_RTCStatsTypeOutboundRtp, js_RTCStatsTypePeerConnection,
js_RTCStatsTypeDataChannel, js_RTCStatsTypeTrack,
js_RTCStatsTypeTransport, js_RTCStatsTypeCandidatePair,
js_RTCStatsTypeLocalCandidate, js_RTCStatsTypeRemoteCandidate,
js_RTCStatsTypeCertificate, NotificationDirection(..),
js_NotificationDirectionAuto, js_NotificationDirectionLtr,
js_NotificationDirectionRtl, AudioContextState(..),
js_AudioContextStateSuspended, js_AudioContextStateRunning,
js_AudioContextStateInterrupted, js_AudioContextStateClosed,
BiquadFilterType(..), js_BiquadFilterTypeLowpass,
js_BiquadFilterTypeHighpass, js_BiquadFilterTypeBandpass,
js_BiquadFilterTypeLowshelf, js_BiquadFilterTypeHighshelf,
js_BiquadFilterTypePeaking, js_BiquadFilterTypeNotch,
js_BiquadFilterTypeAllpass, OscillatorType(..),
js_OscillatorTypeSine, js_OscillatorTypeSquare,
js_OscillatorTypeSawtooth, js_OscillatorTypeTriangle,
js_OscillatorTypeCustom, PanningModelType(..),
js_PanningModelTypeEqualpower, js_PanningModelTypeHRTF,
DistanceModelType(..), js_DistanceModelTypeLinear,
js_DistanceModelTypeInverse, js_DistanceModelTypeExponential,
OverSampleType(..), js_OverSampleTypeNone, js_OverSampleType2x,
js_OverSampleType4x, ScrollRestoration(..),
js_ScrollRestorationAuto, js_ScrollRestorationManual,
XMLHttpRequestResponseType(..), js_XMLHttpRequestResponseType,
js_XMLHttpRequestResponseTypeArraybuffer,
js_XMLHttpRequestResponseTypeBlob,
js_XMLHttpRequestResponseTypeDocument,
js_XMLHttpRequestResponseTypeJson,
js_XMLHttpRequestResponseTypeText)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
data KeyType = KeyTypePublic
| KeyTypePrivate
| KeyTypeSecret
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal KeyType where
toJSVal KeyTypePublic = toJSVal js_KeyTypePublic
toJSVal KeyTypePrivate = toJSVal js_KeyTypePrivate
toJSVal KeyTypeSecret = toJSVal js_KeyTypeSecret
instance FromJSVal KeyType where
fromJSVal x
= x `strictEqual` js_KeyTypePublic >>=
\ r ->
case r of
True -> return (Just KeyTypePublic)
False
-> x `strictEqual` js_KeyTypePrivate >>=
\ r ->
case r of
True -> return (Just KeyTypePrivate)
False
-> x `strictEqual` js_KeyTypeSecret >>=
\ r ->
case r of
True -> return (Just KeyTypeSecret)
False -> return Nothing
js_KeyTypePublic = "public"
js_KeyTypePrivate = "private"
js_KeyTypeSecret = "secret"
data CryptoKeyUsage = CryptoKeyUsageEncrypt
| CryptoKeyUsageDecrypt
| CryptoKeyUsageSign
| CryptoKeyUsageVerify
| CryptoKeyUsageDeriveKey
| CryptoKeyUsageDeriveBits
| CryptoKeyUsageWrapKey
| CryptoKeyUsageUnwrapKey
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal CryptoKeyUsage where
toJSVal CryptoKeyUsageEncrypt = toJSVal js_CryptoKeyUsageEncrypt
toJSVal CryptoKeyUsageDecrypt = toJSVal js_CryptoKeyUsageDecrypt
toJSVal CryptoKeyUsageSign = toJSVal js_CryptoKeyUsageSign
toJSVal CryptoKeyUsageVerify = toJSVal js_CryptoKeyUsageVerify
toJSVal CryptoKeyUsageDeriveKey
= toJSVal js_CryptoKeyUsageDeriveKey
toJSVal CryptoKeyUsageDeriveBits
= toJSVal js_CryptoKeyUsageDeriveBits
toJSVal CryptoKeyUsageWrapKey = toJSVal js_CryptoKeyUsageWrapKey
toJSVal CryptoKeyUsageUnwrapKey
= toJSVal js_CryptoKeyUsageUnwrapKey
instance FromJSVal CryptoKeyUsage where
fromJSVal x
= x `strictEqual` js_CryptoKeyUsageEncrypt >>=
\ r ->
case r of
True -> return (Just CryptoKeyUsageEncrypt)
False
-> x `strictEqual` js_CryptoKeyUsageDecrypt >>=
\ r ->
case r of
True -> return (Just CryptoKeyUsageDecrypt)
False
-> x `strictEqual` js_CryptoKeyUsageSign >>=
\ r ->
case r of
True -> return (Just CryptoKeyUsageSign)
False
-> x `strictEqual` js_CryptoKeyUsageVerify >>=
\ r ->
case r of
True
-> return (Just CryptoKeyUsageVerify)
False
-> x `strictEqual`
js_CryptoKeyUsageDeriveKey
>>=
\ r ->
case r of
True
-> return
(Just
CryptoKeyUsageDeriveKey)
False
-> x `strictEqual`
js_CryptoKeyUsageDeriveBits
>>=
\ r ->
case r of
True
-> return
(Just
CryptoKeyUsageDeriveBits)
False
-> x `strictEqual`
js_CryptoKeyUsageWrapKey
>>=
\ r ->
case r
of
True
-> return
(Just
CryptoKeyUsageWrapKey)
False
-> x `strictEqual`
js_CryptoKeyUsageUnwrapKey
>>=
\ r
->
case
r
of
True
-> return
(Just
CryptoKeyUsageUnwrapKey)
False
-> return
Nothing
js_CryptoKeyUsageEncrypt = "encrypt"
js_CryptoKeyUsageDecrypt = "decrypt"
js_CryptoKeyUsageSign = "sign"
js_CryptoKeyUsageVerify = "verify"
js_CryptoKeyUsageDeriveKey = "deriveKey"
js_CryptoKeyUsageDeriveBits = "deriveBits"
js_CryptoKeyUsageWrapKey = "wrapKey"
js_CryptoKeyUsageUnwrapKey = "unwrapKey"
data KeyFormat = KeyFormatRaw
| KeyFormatSpki
| KeyFormatPkcs8
| KeyFormatJwk
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal KeyFormat where
toJSVal KeyFormatRaw = toJSVal js_KeyFormatRaw
toJSVal KeyFormatSpki = toJSVal js_KeyFormatSpki
toJSVal KeyFormatPkcs8 = toJSVal js_KeyFormatPkcs8
toJSVal KeyFormatJwk = toJSVal js_KeyFormatJwk
instance FromJSVal KeyFormat where
fromJSVal x
= x `strictEqual` js_KeyFormatRaw >>=
\ r ->
case r of
True -> return (Just KeyFormatRaw)
False
-> x `strictEqual` js_KeyFormatSpki >>=
\ r ->
case r of
True -> return (Just KeyFormatSpki)
False
-> x `strictEqual` js_KeyFormatPkcs8 >>=
\ r ->
case r of
True -> return (Just KeyFormatPkcs8)
False
-> x `strictEqual` js_KeyFormatJwk >>=
\ r ->
case r of
True -> return (Just KeyFormatJwk)
False -> return Nothing
js_KeyFormatRaw = "raw"
js_KeyFormatSpki = "spki"
js_KeyFormatPkcs8 = "pkcs8"
js_KeyFormatJwk = "jwk"
data FontFaceLoadStatus = FontFaceLoadStatusUnloaded
| FontFaceLoadStatusLoading
| FontFaceLoadStatusLoaded
| FontFaceLoadStatusError
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal FontFaceLoadStatus where
toJSVal FontFaceLoadStatusUnloaded
= toJSVal js_FontFaceLoadStatusUnloaded
toJSVal FontFaceLoadStatusLoading
= toJSVal js_FontFaceLoadStatusLoading
toJSVal FontFaceLoadStatusLoaded
= toJSVal js_FontFaceLoadStatusLoaded
toJSVal FontFaceLoadStatusError
= toJSVal js_FontFaceLoadStatusError
instance FromJSVal FontFaceLoadStatus where
fromJSVal x
= x `strictEqual` js_FontFaceLoadStatusUnloaded >>=
\ r ->
case r of
True -> return (Just FontFaceLoadStatusUnloaded)
False
-> x `strictEqual` js_FontFaceLoadStatusLoading >>=
\ r ->
case r of
True -> return (Just FontFaceLoadStatusLoading)
False
-> x `strictEqual` js_FontFaceLoadStatusLoaded >>=
\ r ->
case r of
True -> return (Just FontFaceLoadStatusLoaded)
False
-> x `strictEqual` js_FontFaceLoadStatusError >>=
\ r ->
case r of
True
-> return
(Just FontFaceLoadStatusError)
False -> return Nothing
js_FontFaceLoadStatusUnloaded = "unloaded"
js_FontFaceLoadStatusLoading = "loading"
js_FontFaceLoadStatusLoaded = "loaded"
js_FontFaceLoadStatusError = "error"
data FontFaceSetLoadStatus = FontFaceSetLoadStatusLoading
| FontFaceSetLoadStatusLoaded
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal FontFaceSetLoadStatus where
toJSVal FontFaceSetLoadStatusLoading
= toJSVal js_FontFaceSetLoadStatusLoading
toJSVal FontFaceSetLoadStatusLoaded
= toJSVal js_FontFaceSetLoadStatusLoaded
instance FromJSVal FontFaceSetLoadStatus where
fromJSVal x
= x `strictEqual` js_FontFaceSetLoadStatusLoading >>=
\ r ->
case r of
True -> return (Just FontFaceSetLoadStatusLoading)
False
-> x `strictEqual` js_FontFaceSetLoadStatusLoaded >>=
\ r ->
case r of
True -> return (Just FontFaceSetLoadStatusLoaded)
False -> return Nothing
js_FontFaceSetLoadStatusLoading = "loading"
js_FontFaceSetLoadStatusLoaded = "loaded"
data VisibilityState = VisibilityStateHidden
| VisibilityStateVisible
| VisibilityStatePrerender
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal VisibilityState where
toJSVal VisibilityStateHidden = toJSVal js_VisibilityStateHidden
toJSVal VisibilityStateVisible = toJSVal js_VisibilityStateVisible
toJSVal VisibilityStatePrerender
= toJSVal js_VisibilityStatePrerender
instance FromJSVal VisibilityState where
fromJSVal x
= x `strictEqual` js_VisibilityStateHidden >>=
\ r ->
case r of
True -> return (Just VisibilityStateHidden)
False
-> x `strictEqual` js_VisibilityStateVisible >>=
\ r ->
case r of
True -> return (Just VisibilityStateVisible)
False
-> x `strictEqual` js_VisibilityStatePrerender >>=
\ r ->
case r of
True -> return (Just VisibilityStatePrerender)
False -> return Nothing
js_VisibilityStateHidden = "hidden"
js_VisibilityStateVisible = "visible"
js_VisibilityStatePrerender = "prerender"
data DocumentReadyState = DocumentReadyStateLoading
| DocumentReadyStateInteractive
| DocumentReadyStateComplete
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal DocumentReadyState where
toJSVal DocumentReadyStateLoading
= toJSVal js_DocumentReadyStateLoading
toJSVal DocumentReadyStateInteractive
= toJSVal js_DocumentReadyStateInteractive
toJSVal DocumentReadyStateComplete
= toJSVal js_DocumentReadyStateComplete
instance FromJSVal DocumentReadyState where
fromJSVal x
= x `strictEqual` js_DocumentReadyStateLoading >>=
\ r ->
case r of
True -> return (Just DocumentReadyStateLoading)
False
-> x `strictEqual` js_DocumentReadyStateInteractive >>=
\ r ->
case r of
True -> return (Just DocumentReadyStateInteractive)
False
-> x `strictEqual` js_DocumentReadyStateComplete >>=
\ r ->
case r of
True -> return (Just DocumentReadyStateComplete)
False -> return Nothing
js_DocumentReadyStateLoading = "loading"
js_DocumentReadyStateInteractive = "interactive"
js_DocumentReadyStateComplete = "complete"
data ShadowRootMode = ShadowRootModeUserAgent
| ShadowRootModeClosed
| ShadowRootModeOpen
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ShadowRootMode where
toJSVal ShadowRootModeUserAgent
= toJSVal js_ShadowRootModeUserAgent
toJSVal ShadowRootModeClosed = toJSVal js_ShadowRootModeClosed
toJSVal ShadowRootModeOpen = toJSVal js_ShadowRootModeOpen
instance FromJSVal ShadowRootMode where
fromJSVal x
= x `strictEqual` js_ShadowRootModeUserAgent >>=
\ r ->
case r of
True -> return (Just ShadowRootModeUserAgent)
False
-> x `strictEqual` js_ShadowRootModeClosed >>=
\ r ->
case r of
True -> return (Just ShadowRootModeClosed)
False
-> x `strictEqual` js_ShadowRootModeOpen >>=
\ r ->
case r of
True -> return (Just ShadowRootModeOpen)
False -> return Nothing
js_ShadowRootModeUserAgent = "user-agent"
js_ShadowRootModeClosed = "closed"
js_ShadowRootModeOpen = "open"
data BlobLineEndings = BlobLineEndingsTransparent
| BlobLineEndingsNative
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal BlobLineEndings where
toJSVal BlobLineEndingsTransparent
= toJSVal js_BlobLineEndingsTransparent
toJSVal BlobLineEndingsNative = toJSVal js_BlobLineEndingsNative
instance FromJSVal BlobLineEndings where
fromJSVal x
= x `strictEqual` js_BlobLineEndingsTransparent >>=
\ r ->
case r of
True -> return (Just BlobLineEndingsTransparent)
False
-> x `strictEqual` js_BlobLineEndingsNative >>=
\ r ->
case r of
True -> return (Just BlobLineEndingsNative)
False -> return Nothing
js_BlobLineEndingsTransparent = "transparent"
js_BlobLineEndingsNative = "native"
data ImageSmoothingQuality = ImageSmoothingQualityLow
| ImageSmoothingQualityMedium
| ImageSmoothingQualityHigh
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ImageSmoothingQuality where
toJSVal ImageSmoothingQualityLow
= toJSVal js_ImageSmoothingQualityLow
toJSVal ImageSmoothingQualityMedium
= toJSVal js_ImageSmoothingQualityMedium
toJSVal ImageSmoothingQualityHigh
= toJSVal js_ImageSmoothingQualityHigh
instance FromJSVal ImageSmoothingQuality where
fromJSVal x
= x `strictEqual` js_ImageSmoothingQualityLow >>=
\ r ->
case r of
True -> return (Just ImageSmoothingQualityLow)
False
-> x `strictEqual` js_ImageSmoothingQualityMedium >>=
\ r ->
case r of
True -> return (Just ImageSmoothingQualityMedium)
False
-> x `strictEqual` js_ImageSmoothingQualityHigh >>=
\ r ->
case r of
True -> return (Just ImageSmoothingQualityHigh)
False -> return Nothing
js_ImageSmoothingQualityLow = "low"
js_ImageSmoothingQualityMedium = "medium"
js_ImageSmoothingQualityHigh = "high"
data CanvasWindingRule = CanvasWindingRuleNonzero
| CanvasWindingRuleEvenodd
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal CanvasWindingRule where
toJSVal CanvasWindingRuleNonzero
= toJSVal js_CanvasWindingRuleNonzero
toJSVal CanvasWindingRuleEvenodd
= toJSVal js_CanvasWindingRuleEvenodd
instance FromJSVal CanvasWindingRule where
fromJSVal x
= x `strictEqual` js_CanvasWindingRuleNonzero >>=
\ r ->
case r of
True -> return (Just CanvasWindingRuleNonzero)
False
-> x `strictEqual` js_CanvasWindingRuleEvenodd >>=
\ r ->
case r of
True -> return (Just CanvasWindingRuleEvenodd)
False -> return Nothing
js_CanvasWindingRuleNonzero = "nonzero"
js_CanvasWindingRuleEvenodd = "evenodd"
data WebGLPowerPreference = WebGLPowerPreferenceDefault
| WebGLPowerPreferenceLowPower
| WebGLPowerPreferenceHighPerformance
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGLPowerPreference where
toJSVal WebGLPowerPreferenceDefault
= toJSVal js_WebGLPowerPreferenceDefault
toJSVal WebGLPowerPreferenceLowPower
= toJSVal js_WebGLPowerPreferenceLowPower
toJSVal WebGLPowerPreferenceHighPerformance
= toJSVal js_WebGLPowerPreferenceHighPerformance
instance FromJSVal WebGLPowerPreference where
fromJSVal x
= x `strictEqual` js_WebGLPowerPreferenceDefault >>=
\ r ->
case r of
True -> return (Just WebGLPowerPreferenceDefault)
False
-> x `strictEqual` js_WebGLPowerPreferenceLowPower >>=
\ r ->
case r of
True -> return (Just WebGLPowerPreferenceLowPower)
False
-> x `strictEqual` js_WebGLPowerPreferenceHighPerformance >>=
\ r ->
case r of
True
-> return (Just WebGLPowerPreferenceHighPerformance)
False -> return Nothing
js_WebGLPowerPreferenceDefault = "default"
js_WebGLPowerPreferenceLowPower = "low-power"
js_WebGLPowerPreferenceHighPerformance = "high-performance"
data WebGPUCompareFunction = WebGPUCompareFunctionNever
| WebGPUCompareFunctionLess
| WebGPUCompareFunctionEqual
| WebGPUCompareFunctionLessequal
| WebGPUCompareFunctionGreater
| WebGPUCompareFunctionNotequal
| WebGPUCompareFunctionGreaterequal
| WebGPUCompareFunctionAlways
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUCompareFunction where
toJSVal WebGPUCompareFunctionNever
= toJSVal js_WebGPUCompareFunctionNever
toJSVal WebGPUCompareFunctionLess
= toJSVal js_WebGPUCompareFunctionLess
toJSVal WebGPUCompareFunctionEqual
= toJSVal js_WebGPUCompareFunctionEqual
toJSVal WebGPUCompareFunctionLessequal
= toJSVal js_WebGPUCompareFunctionLessequal
toJSVal WebGPUCompareFunctionGreater
= toJSVal js_WebGPUCompareFunctionGreater
toJSVal WebGPUCompareFunctionNotequal
= toJSVal js_WebGPUCompareFunctionNotequal
toJSVal WebGPUCompareFunctionGreaterequal
= toJSVal js_WebGPUCompareFunctionGreaterequal
toJSVal WebGPUCompareFunctionAlways
= toJSVal js_WebGPUCompareFunctionAlways
instance FromJSVal WebGPUCompareFunction where
fromJSVal x
= x `strictEqual` js_WebGPUCompareFunctionNever >>=
\ r ->
case r of
True -> return (Just WebGPUCompareFunctionNever)
False
-> x `strictEqual` js_WebGPUCompareFunctionLess >>=
\ r ->
case r of
True -> return (Just WebGPUCompareFunctionLess)
False
-> x `strictEqual` js_WebGPUCompareFunctionEqual >>=
\ r ->
case r of
True -> return (Just WebGPUCompareFunctionEqual)
False
-> x `strictEqual` js_WebGPUCompareFunctionLessequal
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUCompareFunctionLessequal)
False
-> x `strictEqual`
js_WebGPUCompareFunctionGreater
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUCompareFunctionGreater)
False
-> x `strictEqual`
js_WebGPUCompareFunctionNotequal
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUCompareFunctionNotequal)
False
-> x `strictEqual`
js_WebGPUCompareFunctionGreaterequal
>>=
\ r ->
case r
of
True
-> return
(Just
WebGPUCompareFunctionGreaterequal)
False
-> x `strictEqual`
js_WebGPUCompareFunctionAlways
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUCompareFunctionAlways)
False
-> return
Nothing
js_WebGPUCompareFunctionNever = "never"
js_WebGPUCompareFunctionLess = "less"
js_WebGPUCompareFunctionEqual = "equal"
js_WebGPUCompareFunctionLessequal = "lessequal"
js_WebGPUCompareFunctionGreater = "greater"
js_WebGPUCompareFunctionNotequal = "notequal"
js_WebGPUCompareFunctionGreaterequal = "greaterequal"
js_WebGPUCompareFunctionAlways = "always"
data WebGPUPixelFormat = WebGPUPixelFormatBGRA8Unorm
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUPixelFormat where
toJSVal WebGPUPixelFormatBGRA8Unorm
= toJSVal js_WebGPUPixelFormatBGRA8Unorm
instance FromJSVal WebGPUPixelFormat where
fromJSVal x
= x `strictEqual` js_WebGPUPixelFormatBGRA8Unorm >>=
\ r ->
case r of
True -> return (Just WebGPUPixelFormatBGRA8Unorm)
False -> return Nothing
js_WebGPUPixelFormatBGRA8Unorm = "BGRA8Unorm"
data WebGPULoadAction = WebGPULoadActionDontcare
| WebGPULoadActionLoad
| WebGPULoadActionClear
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPULoadAction where
toJSVal WebGPULoadActionDontcare
= toJSVal js_WebGPULoadActionDontcare
toJSVal WebGPULoadActionLoad = toJSVal js_WebGPULoadActionLoad
toJSVal WebGPULoadActionClear = toJSVal js_WebGPULoadActionClear
instance FromJSVal WebGPULoadAction where
fromJSVal x
= x `strictEqual` js_WebGPULoadActionDontcare >>=
\ r ->
case r of
True -> return (Just WebGPULoadActionDontcare)
False
-> x `strictEqual` js_WebGPULoadActionLoad >>=
\ r ->
case r of
True -> return (Just WebGPULoadActionLoad)
False
-> x `strictEqual` js_WebGPULoadActionClear >>=
\ r ->
case r of
True -> return (Just WebGPULoadActionClear)
False -> return Nothing
js_WebGPULoadActionDontcare = "dontcare"
js_WebGPULoadActionLoad = "load"
js_WebGPULoadActionClear = "clear"
data WebGPUStoreAction = WebGPUStoreActionDontcare
| WebGPUStoreActionStore
| WebGPUStoreActionMultisampleresolve
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUStoreAction where
toJSVal WebGPUStoreActionDontcare
= toJSVal js_WebGPUStoreActionDontcare
toJSVal WebGPUStoreActionStore = toJSVal js_WebGPUStoreActionStore
toJSVal WebGPUStoreActionMultisampleresolve
= toJSVal js_WebGPUStoreActionMultisampleresolve
instance FromJSVal WebGPUStoreAction where
fromJSVal x
= x `strictEqual` js_WebGPUStoreActionDontcare >>=
\ r ->
case r of
True -> return (Just WebGPUStoreActionDontcare)
False
-> x `strictEqual` js_WebGPUStoreActionStore >>=
\ r ->
case r of
True -> return (Just WebGPUStoreActionStore)
False
-> x `strictEqual` js_WebGPUStoreActionMultisampleresolve >>=
\ r ->
case r of
True
-> return (Just WebGPUStoreActionMultisampleresolve)
False -> return Nothing
js_WebGPUStoreActionDontcare = "dontcare"
js_WebGPUStoreActionStore = "store"
js_WebGPUStoreActionMultisampleresolve = "multisampleresolve"
data WebGPUPrimitiveType = WebGPUPrimitiveTypePoint
| WebGPUPrimitiveTypeLine
| WebGPUPrimitiveTypeLinestrip
| WebGPUPrimitiveTypeTriangle
| WebGPUPrimitiveTypeTrianglestrip
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUPrimitiveType where
toJSVal WebGPUPrimitiveTypePoint
= toJSVal js_WebGPUPrimitiveTypePoint
toJSVal WebGPUPrimitiveTypeLine
= toJSVal js_WebGPUPrimitiveTypeLine
toJSVal WebGPUPrimitiveTypeLinestrip
= toJSVal js_WebGPUPrimitiveTypeLinestrip
toJSVal WebGPUPrimitiveTypeTriangle
= toJSVal js_WebGPUPrimitiveTypeTriangle
toJSVal WebGPUPrimitiveTypeTrianglestrip
= toJSVal js_WebGPUPrimitiveTypeTrianglestrip
instance FromJSVal WebGPUPrimitiveType where
fromJSVal x
= x `strictEqual` js_WebGPUPrimitiveTypePoint >>=
\ r ->
case r of
True -> return (Just WebGPUPrimitiveTypePoint)
False
-> x `strictEqual` js_WebGPUPrimitiveTypeLine >>=
\ r ->
case r of
True -> return (Just WebGPUPrimitiveTypeLine)
False
-> x `strictEqual` js_WebGPUPrimitiveTypeLinestrip >>=
\ r ->
case r of
True -> return (Just WebGPUPrimitiveTypeLinestrip)
False
-> x `strictEqual` js_WebGPUPrimitiveTypeTriangle
>>=
\ r ->
case r of
True
-> return
(Just WebGPUPrimitiveTypeTriangle)
False
-> x `strictEqual`
js_WebGPUPrimitiveTypeTrianglestrip
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUPrimitiveTypeTrianglestrip)
False -> return Nothing
js_WebGPUPrimitiveTypePoint = "point"
js_WebGPUPrimitiveTypeLine = "line"
js_WebGPUPrimitiveTypeLinestrip = "linestrip"
js_WebGPUPrimitiveTypeTriangle = "triangle"
js_WebGPUPrimitiveTypeTrianglestrip = "trianglestrip"
data WebGPUFunctionType = WebGPUFunctionTypeFragment
| WebGPUFunctionTypeVertex
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUFunctionType where
toJSVal WebGPUFunctionTypeFragment
= toJSVal js_WebGPUFunctionTypeFragment
toJSVal WebGPUFunctionTypeVertex
= toJSVal js_WebGPUFunctionTypeVertex
instance FromJSVal WebGPUFunctionType where
fromJSVal x
= x `strictEqual` js_WebGPUFunctionTypeFragment >>=
\ r ->
case r of
True -> return (Just WebGPUFunctionTypeFragment)
False
-> x `strictEqual` js_WebGPUFunctionTypeVertex >>=
\ r ->
case r of
True -> return (Just WebGPUFunctionTypeVertex)
False -> return Nothing
js_WebGPUFunctionTypeFragment = "fragment"
js_WebGPUFunctionTypeVertex = "vertex"
data WebGPUStencilOperation = WebGPUStencilOperationKeep
| WebGPUStencilOperationZero
| WebGPUStencilOperationReplace
| WebGPUStencilOperationIncrementclamp
| WebGPUStencilOperationDecrementclamp
| WebGPUStencilOperationInvert
| WebGPUStencilOperationIncrementwrap
| WebGPUStencilOperationDecrementwrap
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUStencilOperation where
toJSVal WebGPUStencilOperationKeep
= toJSVal js_WebGPUStencilOperationKeep
toJSVal WebGPUStencilOperationZero
= toJSVal js_WebGPUStencilOperationZero
toJSVal WebGPUStencilOperationReplace
= toJSVal js_WebGPUStencilOperationReplace
toJSVal WebGPUStencilOperationIncrementclamp
= toJSVal js_WebGPUStencilOperationIncrementclamp
toJSVal WebGPUStencilOperationDecrementclamp
= toJSVal js_WebGPUStencilOperationDecrementclamp
toJSVal WebGPUStencilOperationInvert
= toJSVal js_WebGPUStencilOperationInvert
toJSVal WebGPUStencilOperationIncrementwrap
= toJSVal js_WebGPUStencilOperationIncrementwrap
toJSVal WebGPUStencilOperationDecrementwrap
= toJSVal js_WebGPUStencilOperationDecrementwrap
instance FromJSVal WebGPUStencilOperation where
fromJSVal x
= x `strictEqual` js_WebGPUStencilOperationKeep >>=
\ r ->
case r of
True -> return (Just WebGPUStencilOperationKeep)
False
-> x `strictEqual` js_WebGPUStencilOperationZero >>=
\ r ->
case r of
True -> return (Just WebGPUStencilOperationZero)
False
-> x `strictEqual` js_WebGPUStencilOperationReplace >>=
\ r ->
case r of
True -> return (Just WebGPUStencilOperationReplace)
False
-> x `strictEqual`
js_WebGPUStencilOperationIncrementclamp
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUStencilOperationIncrementclamp)
False
-> x `strictEqual`
js_WebGPUStencilOperationDecrementclamp
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUStencilOperationDecrementclamp)
False
-> x `strictEqual`
js_WebGPUStencilOperationInvert
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUStencilOperationInvert)
False
-> x `strictEqual`
js_WebGPUStencilOperationIncrementwrap
>>=
\ r ->
case r
of
True
-> return
(Just
WebGPUStencilOperationIncrementwrap)
False
-> x `strictEqual`
js_WebGPUStencilOperationDecrementwrap
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUStencilOperationDecrementwrap)
False
-> return
Nothing
js_WebGPUStencilOperationKeep = "keep"
js_WebGPUStencilOperationZero = "zero"
js_WebGPUStencilOperationReplace = "replace"
js_WebGPUStencilOperationIncrementclamp = "incrementclamp"
js_WebGPUStencilOperationDecrementclamp = "decrementclamp"
js_WebGPUStencilOperationInvert = "invert"
js_WebGPUStencilOperationIncrementwrap = "incrementwrap"
js_WebGPUStencilOperationDecrementwrap = "decrementwrap"
data WebGPUStatus = WebGPUStatusNotenqueued
| WebGPUStatusEnqueued
| WebGPUStatusCommitted
| WebGPUStatusScheduled
| WebGPUStatusCompleted
| WebGPUStatusError
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUStatus where
toJSVal WebGPUStatusNotenqueued
= toJSVal js_WebGPUStatusNotenqueued
toJSVal WebGPUStatusEnqueued = toJSVal js_WebGPUStatusEnqueued
toJSVal WebGPUStatusCommitted = toJSVal js_WebGPUStatusCommitted
toJSVal WebGPUStatusScheduled = toJSVal js_WebGPUStatusScheduled
toJSVal WebGPUStatusCompleted = toJSVal js_WebGPUStatusCompleted
toJSVal WebGPUStatusError = toJSVal js_WebGPUStatusError
instance FromJSVal WebGPUStatus where
fromJSVal x
= x `strictEqual` js_WebGPUStatusNotenqueued >>=
\ r ->
case r of
True -> return (Just WebGPUStatusNotenqueued)
False
-> x `strictEqual` js_WebGPUStatusEnqueued >>=
\ r ->
case r of
True -> return (Just WebGPUStatusEnqueued)
False
-> x `strictEqual` js_WebGPUStatusCommitted >>=
\ r ->
case r of
True -> return (Just WebGPUStatusCommitted)
False
-> x `strictEqual` js_WebGPUStatusScheduled >>=
\ r ->
case r of
True
-> return (Just WebGPUStatusScheduled)
False
-> x `strictEqual`
js_WebGPUStatusCompleted
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUStatusCompleted)
False
-> x `strictEqual`
js_WebGPUStatusError
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUStatusError)
False
-> return
Nothing
js_WebGPUStatusNotenqueued = "notenqueued"
js_WebGPUStatusEnqueued = "enqueued"
js_WebGPUStatusCommitted = "committed"
js_WebGPUStatusScheduled = "scheduled"
js_WebGPUStatusCompleted = "completed"
js_WebGPUStatusError = "error"
data WebGPUSamplerAddressMode = WebGPUSamplerAddressModeClamptoedge
| WebGPUSamplerAddressModeMirrorclamptoedge
| WebGPUSamplerAddressModeRepeat
| WebGPUSamplerAddressModeMirrorrepeat
| WebGPUSamplerAddressModeClamptozero
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUSamplerAddressMode where
toJSVal WebGPUSamplerAddressModeClamptoedge
= toJSVal js_WebGPUSamplerAddressModeClamptoedge
toJSVal WebGPUSamplerAddressModeMirrorclamptoedge
= toJSVal js_WebGPUSamplerAddressModeMirrorclamptoedge
toJSVal WebGPUSamplerAddressModeRepeat
= toJSVal js_WebGPUSamplerAddressModeRepeat
toJSVal WebGPUSamplerAddressModeMirrorrepeat
= toJSVal js_WebGPUSamplerAddressModeMirrorrepeat
toJSVal WebGPUSamplerAddressModeClamptozero
= toJSVal js_WebGPUSamplerAddressModeClamptozero
instance FromJSVal WebGPUSamplerAddressMode where
fromJSVal x
= x `strictEqual` js_WebGPUSamplerAddressModeClamptoedge >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerAddressModeClamptoedge)
False
-> x `strictEqual` js_WebGPUSamplerAddressModeMirrorclamptoedge >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerAddressModeMirrorclamptoedge)
False
-> x `strictEqual` js_WebGPUSamplerAddressModeRepeat >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerAddressModeRepeat)
False
-> x `strictEqual`
js_WebGPUSamplerAddressModeMirrorrepeat
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUSamplerAddressModeMirrorrepeat)
False
-> x `strictEqual`
js_WebGPUSamplerAddressModeClamptozero
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUSamplerAddressModeClamptozero)
False -> return Nothing
js_WebGPUSamplerAddressModeClamptoedge = "clamptoedge"
js_WebGPUSamplerAddressModeMirrorclamptoedge = "mirrorclamptoedge"
js_WebGPUSamplerAddressModeRepeat = "repeat"
js_WebGPUSamplerAddressModeMirrorrepeat = "mirrorrepeat"
js_WebGPUSamplerAddressModeClamptozero = "clamptozero"
data WebGPUSamplerMinMagFilter = WebGPUSamplerMinMagFilterNearest
| WebGPUSamplerMinMagFilterLinear
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUSamplerMinMagFilter where
toJSVal WebGPUSamplerMinMagFilterNearest
= toJSVal js_WebGPUSamplerMinMagFilterNearest
toJSVal WebGPUSamplerMinMagFilterLinear
= toJSVal js_WebGPUSamplerMinMagFilterLinear
instance FromJSVal WebGPUSamplerMinMagFilter where
fromJSVal x
= x `strictEqual` js_WebGPUSamplerMinMagFilterNearest >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerMinMagFilterNearest)
False
-> x `strictEqual` js_WebGPUSamplerMinMagFilterLinear >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerMinMagFilterLinear)
False -> return Nothing
js_WebGPUSamplerMinMagFilterNearest = "nearest"
js_WebGPUSamplerMinMagFilterLinear = "linear"
data WebGPUSamplerMipFilter = WebGPUSamplerMipFilterNotmipmapped
| WebGPUSamplerMipFilterNearest
| WebGPUSamplerMipFilterLinear
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUSamplerMipFilter where
toJSVal WebGPUSamplerMipFilterNotmipmapped
= toJSVal js_WebGPUSamplerMipFilterNotmipmapped
toJSVal WebGPUSamplerMipFilterNearest
= toJSVal js_WebGPUSamplerMipFilterNearest
toJSVal WebGPUSamplerMipFilterLinear
= toJSVal js_WebGPUSamplerMipFilterLinear
instance FromJSVal WebGPUSamplerMipFilter where
fromJSVal x
= x `strictEqual` js_WebGPUSamplerMipFilterNotmipmapped >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerMipFilterNotmipmapped)
False
-> x `strictEqual` js_WebGPUSamplerMipFilterNearest >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerMipFilterNearest)
False
-> x `strictEqual` js_WebGPUSamplerMipFilterLinear >>=
\ r ->
case r of
True -> return (Just WebGPUSamplerMipFilterLinear)
False -> return Nothing
js_WebGPUSamplerMipFilterNotmipmapped = "notmipmapped"
js_WebGPUSamplerMipFilterNearest = "nearest"
js_WebGPUSamplerMipFilterLinear = "linear"
data WebGPUCullMode = WebGPUCullModeNone
| WebGPUCullModeFront
| WebGPUCullModeBack
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUCullMode where
toJSVal WebGPUCullModeNone = toJSVal js_WebGPUCullModeNone
toJSVal WebGPUCullModeFront = toJSVal js_WebGPUCullModeFront
toJSVal WebGPUCullModeBack = toJSVal js_WebGPUCullModeBack
instance FromJSVal WebGPUCullMode where
fromJSVal x
= x `strictEqual` js_WebGPUCullModeNone >>=
\ r ->
case r of
True -> return (Just WebGPUCullModeNone)
False
-> x `strictEqual` js_WebGPUCullModeFront >>=
\ r ->
case r of
True -> return (Just WebGPUCullModeFront)
False
-> x `strictEqual` js_WebGPUCullModeBack >>=
\ r ->
case r of
True -> return (Just WebGPUCullModeBack)
False -> return Nothing
js_WebGPUCullModeNone = "none"
js_WebGPUCullModeFront = "front"
js_WebGPUCullModeBack = "back"
data WebGPUIndexType = WebGPUIndexTypeUint16
| WebGPUIndexTypeUint32
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUIndexType where
toJSVal WebGPUIndexTypeUint16 = toJSVal js_WebGPUIndexTypeUint16
toJSVal WebGPUIndexTypeUint32 = toJSVal js_WebGPUIndexTypeUint32
instance FromJSVal WebGPUIndexType where
fromJSVal x
= x `strictEqual` js_WebGPUIndexTypeUint16 >>=
\ r ->
case r of
True -> return (Just WebGPUIndexTypeUint16)
False
-> x `strictEqual` js_WebGPUIndexTypeUint32 >>=
\ r ->
case r of
True -> return (Just WebGPUIndexTypeUint32)
False -> return Nothing
js_WebGPUIndexTypeUint16 = "uint16"
js_WebGPUIndexTypeUint32 = "uint32"
data WebGPUVisibilityResultMode = WebGPUVisibilityResultModeDisabled
| WebGPUVisibilityResultModeBoolean
| WebGPUVisibilityResultModeCounting
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUVisibilityResultMode where
toJSVal WebGPUVisibilityResultModeDisabled
= toJSVal js_WebGPUVisibilityResultModeDisabled
toJSVal WebGPUVisibilityResultModeBoolean
= toJSVal js_WebGPUVisibilityResultModeBoolean
toJSVal WebGPUVisibilityResultModeCounting
= toJSVal js_WebGPUVisibilityResultModeCounting
instance FromJSVal WebGPUVisibilityResultMode where
fromJSVal x
= x `strictEqual` js_WebGPUVisibilityResultModeDisabled >>=
\ r ->
case r of
True -> return (Just WebGPUVisibilityResultModeDisabled)
False
-> x `strictEqual` js_WebGPUVisibilityResultModeBoolean >>=
\ r ->
case r of
True -> return (Just WebGPUVisibilityResultModeBoolean)
False
-> x `strictEqual` js_WebGPUVisibilityResultModeCounting >>=
\ r ->
case r of
True
-> return (Just WebGPUVisibilityResultModeCounting)
False -> return Nothing
js_WebGPUVisibilityResultModeDisabled = "disabled"
js_WebGPUVisibilityResultModeBoolean = "boolean"
js_WebGPUVisibilityResultModeCounting = "counting"
data WebGPUWinding = WebGPUWindingClockwise
| WebGPUWindingCounterclockwise
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUWinding where
toJSVal WebGPUWindingClockwise = toJSVal js_WebGPUWindingClockwise
toJSVal WebGPUWindingCounterclockwise
= toJSVal js_WebGPUWindingCounterclockwise
instance FromJSVal WebGPUWinding where
fromJSVal x
= x `strictEqual` js_WebGPUWindingClockwise >>=
\ r ->
case r of
True -> return (Just WebGPUWindingClockwise)
False
-> x `strictEqual` js_WebGPUWindingCounterclockwise >>=
\ r ->
case r of
True -> return (Just WebGPUWindingCounterclockwise)
False -> return Nothing
js_WebGPUWindingClockwise = "clockwise"
js_WebGPUWindingCounterclockwise = "counterclockwise"
data WebGPUDepthClipMode = WebGPUDepthClipModeClip
| WebGPUDepthClipModeClamp
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUDepthClipMode where
toJSVal WebGPUDepthClipModeClip
= toJSVal js_WebGPUDepthClipModeClip
toJSVal WebGPUDepthClipModeClamp
= toJSVal js_WebGPUDepthClipModeClamp
instance FromJSVal WebGPUDepthClipMode where
fromJSVal x
= x `strictEqual` js_WebGPUDepthClipModeClip >>=
\ r ->
case r of
True -> return (Just WebGPUDepthClipModeClip)
False
-> x `strictEqual` js_WebGPUDepthClipModeClamp >>=
\ r ->
case r of
True -> return (Just WebGPUDepthClipModeClamp)
False -> return Nothing
js_WebGPUDepthClipModeClip = "clip"
js_WebGPUDepthClipModeClamp = "clamp"
data WebGPUTriangleFillMode = WebGPUTriangleFillModeFill
| WebGPUTriangleFillModeLines
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUTriangleFillMode where
toJSVal WebGPUTriangleFillModeFill
= toJSVal js_WebGPUTriangleFillModeFill
toJSVal WebGPUTriangleFillModeLines
= toJSVal js_WebGPUTriangleFillModeLines
instance FromJSVal WebGPUTriangleFillMode where
fromJSVal x
= x `strictEqual` js_WebGPUTriangleFillModeFill >>=
\ r ->
case r of
True -> return (Just WebGPUTriangleFillModeFill)
False
-> x `strictEqual` js_WebGPUTriangleFillModeLines >>=
\ r ->
case r of
True -> return (Just WebGPUTriangleFillModeLines)
False -> return Nothing
js_WebGPUTriangleFillModeFill = "fill"
js_WebGPUTriangleFillModeLines = "lines"
data WebGPUCPUCacheMode = WebGPUCPUCacheModeDefaultcache
| WebGPUCPUCacheModeWritecombined
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUCPUCacheMode where
toJSVal WebGPUCPUCacheModeDefaultcache
= toJSVal js_WebGPUCPUCacheModeDefaultcache
toJSVal WebGPUCPUCacheModeWritecombined
= toJSVal js_WebGPUCPUCacheModeWritecombined
instance FromJSVal WebGPUCPUCacheMode where
fromJSVal x
= x `strictEqual` js_WebGPUCPUCacheModeDefaultcache >>=
\ r ->
case r of
True -> return (Just WebGPUCPUCacheModeDefaultcache)
False
-> x `strictEqual` js_WebGPUCPUCacheModeWritecombined >>=
\ r ->
case r of
True -> return (Just WebGPUCPUCacheModeWritecombined)
False -> return Nothing
js_WebGPUCPUCacheModeDefaultcache = "defaultcache"
js_WebGPUCPUCacheModeWritecombined = "writecombined"
data WebGPUStorageMode = WebGPUStorageModeShared
| WebGPUStorageModeManaged
| WebGPUStorageModePrivate
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUStorageMode where
toJSVal WebGPUStorageModeShared
= toJSVal js_WebGPUStorageModeShared
toJSVal WebGPUStorageModeManaged
= toJSVal js_WebGPUStorageModeManaged
toJSVal WebGPUStorageModePrivate
= toJSVal js_WebGPUStorageModePrivate
instance FromJSVal WebGPUStorageMode where
fromJSVal x
= x `strictEqual` js_WebGPUStorageModeShared >>=
\ r ->
case r of
True -> return (Just WebGPUStorageModeShared)
False
-> x `strictEqual` js_WebGPUStorageModeManaged >>=
\ r ->
case r of
True -> return (Just WebGPUStorageModeManaged)
False
-> x `strictEqual` js_WebGPUStorageModePrivate >>=
\ r ->
case r of
True -> return (Just WebGPUStorageModePrivate)
False -> return Nothing
js_WebGPUStorageModeShared = "shared"
js_WebGPUStorageModeManaged = "managed"
js_WebGPUStorageModePrivate = "private"
data WebGPUResourceOptions = WebGPUResourceOptionsCpucachemodedefaultcache
| WebGPUResourceOptionsCpucachemodewritecombined
| WebGPUResourceOptionsStoragemodeshared
| WebGPUResourceOptionsStoragemodemanaged
| WebGPUResourceOptionsStoragemodeprivate
| WebGPUResourceOptionsOptioncpucachemodedefaultcache
| WebGPUResourceOptionsOptioncpucachemodewritecombined
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUResourceOptions where
toJSVal WebGPUResourceOptionsCpucachemodedefaultcache
= toJSVal js_WebGPUResourceOptionsCpucachemodedefaultcache
toJSVal WebGPUResourceOptionsCpucachemodewritecombined
= toJSVal js_WebGPUResourceOptionsCpucachemodewritecombined
toJSVal WebGPUResourceOptionsStoragemodeshared
= toJSVal js_WebGPUResourceOptionsStoragemodeshared
toJSVal WebGPUResourceOptionsStoragemodemanaged
= toJSVal js_WebGPUResourceOptionsStoragemodemanaged
toJSVal WebGPUResourceOptionsStoragemodeprivate
= toJSVal js_WebGPUResourceOptionsStoragemodeprivate
toJSVal WebGPUResourceOptionsOptioncpucachemodedefaultcache
= toJSVal js_WebGPUResourceOptionsOptioncpucachemodedefaultcache
toJSVal WebGPUResourceOptionsOptioncpucachemodewritecombined
= toJSVal js_WebGPUResourceOptionsOptioncpucachemodewritecombined
instance FromJSVal WebGPUResourceOptions where
fromJSVal x
= x `strictEqual` js_WebGPUResourceOptionsCpucachemodedefaultcache
>>=
\ r ->
case r of
True -> return (Just WebGPUResourceOptionsCpucachemodedefaultcache)
False
-> x `strictEqual`
js_WebGPUResourceOptionsCpucachemodewritecombined
>>=
\ r ->
case r of
True
-> return (Just WebGPUResourceOptionsCpucachemodewritecombined)
False
-> x `strictEqual` js_WebGPUResourceOptionsStoragemodeshared >>=
\ r ->
case r of
True
-> return
(Just WebGPUResourceOptionsStoragemodeshared)
False
-> x `strictEqual`
js_WebGPUResourceOptionsStoragemodemanaged
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUResourceOptionsStoragemodemanaged)
False
-> x `strictEqual`
js_WebGPUResourceOptionsStoragemodeprivate
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUResourceOptionsStoragemodeprivate)
False
-> x `strictEqual`
js_WebGPUResourceOptionsOptioncpucachemodedefaultcache
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUResourceOptionsOptioncpucachemodedefaultcache)
False
-> x `strictEqual`
js_WebGPUResourceOptionsOptioncpucachemodewritecombined
>>=
\ r ->
case r
of
True
-> return
(Just
WebGPUResourceOptionsOptioncpucachemodewritecombined)
False
-> return
Nothing
js_WebGPUResourceOptionsCpucachemodedefaultcache
= "cpucachemodedefaultcache"
js_WebGPUResourceOptionsCpucachemodewritecombined
= "cpucachemodewritecombined"
js_WebGPUResourceOptionsStoragemodeshared = "storagemodeshared"
js_WebGPUResourceOptionsStoragemodemanaged = "storagemodemanaged"
js_WebGPUResourceOptionsStoragemodeprivate = "storagemodeprivate"
js_WebGPUResourceOptionsOptioncpucachemodedefaultcache
= "optioncpucachemodedefaultcache"
js_WebGPUResourceOptionsOptioncpucachemodewritecombined
= "optioncpucachemodewritecombined"
data WebGPUTextureUsage = WebGPUTextureUsageUnknown
| WebGPUTextureUsageShaderread
| WebGPUTextureUsageShaderwrite
| WebGPUTextureUsageRendertarget
| WebGPUTextureUsagePixelformatview
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUTextureUsage where
toJSVal WebGPUTextureUsageUnknown
= toJSVal js_WebGPUTextureUsageUnknown
toJSVal WebGPUTextureUsageShaderread
= toJSVal js_WebGPUTextureUsageShaderread
toJSVal WebGPUTextureUsageShaderwrite
= toJSVal js_WebGPUTextureUsageShaderwrite
toJSVal WebGPUTextureUsageRendertarget
= toJSVal js_WebGPUTextureUsageRendertarget
toJSVal WebGPUTextureUsagePixelformatview
= toJSVal js_WebGPUTextureUsagePixelformatview
instance FromJSVal WebGPUTextureUsage where
fromJSVal x
= x `strictEqual` js_WebGPUTextureUsageUnknown >>=
\ r ->
case r of
True -> return (Just WebGPUTextureUsageUnknown)
False
-> x `strictEqual` js_WebGPUTextureUsageShaderread >>=
\ r ->
case r of
True -> return (Just WebGPUTextureUsageShaderread)
False
-> x `strictEqual` js_WebGPUTextureUsageShaderwrite >>=
\ r ->
case r of
True -> return (Just WebGPUTextureUsageShaderwrite)
False
-> x `strictEqual` js_WebGPUTextureUsageRendertarget
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUTextureUsageRendertarget)
False
-> x `strictEqual`
js_WebGPUTextureUsagePixelformatview
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUTextureUsagePixelformatview)
False -> return Nothing
js_WebGPUTextureUsageUnknown = "unknown"
js_WebGPUTextureUsageShaderread = "shaderread"
js_WebGPUTextureUsageShaderwrite = "shaderwrite"
js_WebGPUTextureUsageRendertarget = "rendertarget"
js_WebGPUTextureUsagePixelformatview = "pixelformatview"
data WebGPUBlendOperation = WebGPUBlendOperationAdd
| WebGPUBlendOperationSubtract
| WebGPUBlendOperationReversesubtract
| WebGPUBlendOperationMin
| WebGPUBlendOperationMax
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUBlendOperation where
toJSVal WebGPUBlendOperationAdd
= toJSVal js_WebGPUBlendOperationAdd
toJSVal WebGPUBlendOperationSubtract
= toJSVal js_WebGPUBlendOperationSubtract
toJSVal WebGPUBlendOperationReversesubtract
= toJSVal js_WebGPUBlendOperationReversesubtract
toJSVal WebGPUBlendOperationMin
= toJSVal js_WebGPUBlendOperationMin
toJSVal WebGPUBlendOperationMax
= toJSVal js_WebGPUBlendOperationMax
instance FromJSVal WebGPUBlendOperation where
fromJSVal x
= x `strictEqual` js_WebGPUBlendOperationAdd >>=
\ r ->
case r of
True -> return (Just WebGPUBlendOperationAdd)
False
-> x `strictEqual` js_WebGPUBlendOperationSubtract >>=
\ r ->
case r of
True -> return (Just WebGPUBlendOperationSubtract)
False
-> x `strictEqual` js_WebGPUBlendOperationReversesubtract >>=
\ r ->
case r of
True
-> return (Just WebGPUBlendOperationReversesubtract)
False
-> x `strictEqual` js_WebGPUBlendOperationMin >>=
\ r ->
case r of
True
-> return
(Just WebGPUBlendOperationMin)
False
-> x `strictEqual`
js_WebGPUBlendOperationMax
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUBlendOperationMax)
False -> return Nothing
js_WebGPUBlendOperationAdd = "add"
js_WebGPUBlendOperationSubtract = "subtract"
js_WebGPUBlendOperationReversesubtract = "reversesubtract"
js_WebGPUBlendOperationMin = "min"
js_WebGPUBlendOperationMax = "max"
data WebGPUBlendFactor = WebGPUBlendFactorZero
| WebGPUBlendFactorOne
| WebGPUBlendFactorSourcecolor
| WebGPUBlendFactorOneminussourcecolor
| WebGPUBlendFactorSourcealpha
| WebGPUBlendFactorOneminussourcealpha
| WebGPUBlendFactorDestinationcolor
| WebGPUBlendFactorOneminusdestinationcolor
| WebGPUBlendFactorDestinationalpha
| WebGPUBlendFactorOneminusdestinationalpha
| WebGPUBlendFactorSourcealphasaturated
| WebGPUBlendFactorBlendcolor
| WebGPUBlendFactorOneminusblendcolor
| WebGPUBlendFactorBlendalpha
| WebGPUBlendFactorOneminusblendalpha
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUBlendFactor where
toJSVal WebGPUBlendFactorZero = toJSVal js_WebGPUBlendFactorZero
toJSVal WebGPUBlendFactorOne = toJSVal js_WebGPUBlendFactorOne
toJSVal WebGPUBlendFactorSourcecolor
= toJSVal js_WebGPUBlendFactorSourcecolor
toJSVal WebGPUBlendFactorOneminussourcecolor
= toJSVal js_WebGPUBlendFactorOneminussourcecolor
toJSVal WebGPUBlendFactorSourcealpha
= toJSVal js_WebGPUBlendFactorSourcealpha
toJSVal WebGPUBlendFactorOneminussourcealpha
= toJSVal js_WebGPUBlendFactorOneminussourcealpha
toJSVal WebGPUBlendFactorDestinationcolor
= toJSVal js_WebGPUBlendFactorDestinationcolor
toJSVal WebGPUBlendFactorOneminusdestinationcolor
= toJSVal js_WebGPUBlendFactorOneminusdestinationcolor
toJSVal WebGPUBlendFactorDestinationalpha
= toJSVal js_WebGPUBlendFactorDestinationalpha
toJSVal WebGPUBlendFactorOneminusdestinationalpha
= toJSVal js_WebGPUBlendFactorOneminusdestinationalpha
toJSVal WebGPUBlendFactorSourcealphasaturated
= toJSVal js_WebGPUBlendFactorSourcealphasaturated
toJSVal WebGPUBlendFactorBlendcolor
= toJSVal js_WebGPUBlendFactorBlendcolor
toJSVal WebGPUBlendFactorOneminusblendcolor
= toJSVal js_WebGPUBlendFactorOneminusblendcolor
toJSVal WebGPUBlendFactorBlendalpha
= toJSVal js_WebGPUBlendFactorBlendalpha
toJSVal WebGPUBlendFactorOneminusblendalpha
= toJSVal js_WebGPUBlendFactorOneminusblendalpha
instance FromJSVal WebGPUBlendFactor where
fromJSVal x
= x `strictEqual` js_WebGPUBlendFactorZero >>=
\ r ->
case r of
True -> return (Just WebGPUBlendFactorZero)
False
-> x `strictEqual` js_WebGPUBlendFactorOne >>=
\ r ->
case r of
True -> return (Just WebGPUBlendFactorOne)
False
-> x `strictEqual` js_WebGPUBlendFactorSourcecolor >>=
\ r ->
case r of
True -> return (Just WebGPUBlendFactorSourcecolor)
False
-> x `strictEqual`
js_WebGPUBlendFactorOneminussourcecolor
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUBlendFactorOneminussourcecolor)
False
-> x `strictEqual`
js_WebGPUBlendFactorSourcealpha
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUBlendFactorSourcealpha)
False
-> x `strictEqual`
js_WebGPUBlendFactorOneminussourcealpha
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUBlendFactorOneminussourcealpha)
False
-> x `strictEqual`
js_WebGPUBlendFactorDestinationcolor
>>=
\ r ->
case r
of
True
-> return
(Just
WebGPUBlendFactorDestinationcolor)
False
-> x `strictEqual`
js_WebGPUBlendFactorOneminusdestinationcolor
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorOneminusdestinationcolor)
False
-> x `strictEqual`
js_WebGPUBlendFactorDestinationalpha
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorDestinationalpha)
False
-> x `strictEqual`
js_WebGPUBlendFactorOneminusdestinationalpha
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorOneminusdestinationalpha)
False
-> x `strictEqual`
js_WebGPUBlendFactorSourcealphasaturated
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorSourcealphasaturated)
False
-> x `strictEqual`
js_WebGPUBlendFactorBlendcolor
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorBlendcolor)
False
-> x `strictEqual`
js_WebGPUBlendFactorOneminusblendcolor
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorOneminusblendcolor)
False
-> x `strictEqual`
js_WebGPUBlendFactorBlendalpha
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorBlendalpha)
False
-> x `strictEqual`
js_WebGPUBlendFactorOneminusblendalpha
>>=
\ r
->
case
r
of
True
-> return
(Just
WebGPUBlendFactorOneminusblendalpha)
False
-> return
Nothing
js_WebGPUBlendFactorZero = "zero"
js_WebGPUBlendFactorOne = "one"
js_WebGPUBlendFactorSourcecolor = "sourcecolor"
js_WebGPUBlendFactorOneminussourcecolor = "oneminussourcecolor"
js_WebGPUBlendFactorSourcealpha = "sourcealpha"
js_WebGPUBlendFactorOneminussourcealpha = "oneminussourcealpha"
js_WebGPUBlendFactorDestinationcolor = "destinationcolor"
js_WebGPUBlendFactorOneminusdestinationcolor
= "oneminusdestinationcolor"
js_WebGPUBlendFactorDestinationalpha = "destinationalpha"
js_WebGPUBlendFactorOneminusdestinationalpha
= "oneminusdestinationalpha"
js_WebGPUBlendFactorSourcealphasaturated = "sourcealphasaturated"
js_WebGPUBlendFactorBlendcolor = "blendcolor"
js_WebGPUBlendFactorOneminusblendcolor = "oneminusblendcolor"
js_WebGPUBlendFactorBlendalpha = "blendalpha"
js_WebGPUBlendFactorOneminusblendalpha = "oneminusblendalpha"
data WebGPUColorWriteMask = WebGPUColorWriteMaskNone
| WebGPUColorWriteMaskRed
| WebGPUColorWriteMaskGreen
| WebGPUColorWriteMaskBlue
| WebGPUColorWriteMaskAlpha
| WebGPUColorWriteMaskAll
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUColorWriteMask where
toJSVal WebGPUColorWriteMaskNone
= toJSVal js_WebGPUColorWriteMaskNone
toJSVal WebGPUColorWriteMaskRed
= toJSVal js_WebGPUColorWriteMaskRed
toJSVal WebGPUColorWriteMaskGreen
= toJSVal js_WebGPUColorWriteMaskGreen
toJSVal WebGPUColorWriteMaskBlue
= toJSVal js_WebGPUColorWriteMaskBlue
toJSVal WebGPUColorWriteMaskAlpha
= toJSVal js_WebGPUColorWriteMaskAlpha
toJSVal WebGPUColorWriteMaskAll
= toJSVal js_WebGPUColorWriteMaskAll
instance FromJSVal WebGPUColorWriteMask where
fromJSVal x
= x `strictEqual` js_WebGPUColorWriteMaskNone >>=
\ r ->
case r of
True -> return (Just WebGPUColorWriteMaskNone)
False
-> x `strictEqual` js_WebGPUColorWriteMaskRed >>=
\ r ->
case r of
True -> return (Just WebGPUColorWriteMaskRed)
False
-> x `strictEqual` js_WebGPUColorWriteMaskGreen >>=
\ r ->
case r of
True -> return (Just WebGPUColorWriteMaskGreen)
False
-> x `strictEqual` js_WebGPUColorWriteMaskBlue >>=
\ r ->
case r of
True
-> return
(Just WebGPUColorWriteMaskBlue)
False
-> x `strictEqual`
js_WebGPUColorWriteMaskAlpha
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUColorWriteMaskAlpha)
False
-> x `strictEqual`
js_WebGPUColorWriteMaskAll
>>=
\ r ->
case r of
True
-> return
(Just
WebGPUColorWriteMaskAll)
False
-> return
Nothing
js_WebGPUColorWriteMaskNone = "none"
js_WebGPUColorWriteMaskRed = "red"
js_WebGPUColorWriteMaskGreen = "green"
js_WebGPUColorWriteMaskBlue = "blue"
js_WebGPUColorWriteMaskAlpha = "alpha"
js_WebGPUColorWriteMaskAll = "all"
data WebGPUMultisampleDepthResolveFilter = WebGPUMultisampleDepthResolveFilterSample0
| WebGPUMultisampleDepthResolveFilterMin
| WebGPUMultisampleDepthResolveFilterMax
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUMultisampleDepthResolveFilter where
toJSVal WebGPUMultisampleDepthResolveFilterSample0
= toJSVal js_WebGPUMultisampleDepthResolveFilterSample0
toJSVal WebGPUMultisampleDepthResolveFilterMin
= toJSVal js_WebGPUMultisampleDepthResolveFilterMin
toJSVal WebGPUMultisampleDepthResolveFilterMax
= toJSVal js_WebGPUMultisampleDepthResolveFilterMax
instance FromJSVal WebGPUMultisampleDepthResolveFilter where
fromJSVal x
= x `strictEqual` js_WebGPUMultisampleDepthResolveFilterSample0 >>=
\ r ->
case r of
True -> return (Just WebGPUMultisampleDepthResolveFilterSample0)
False
-> x `strictEqual` js_WebGPUMultisampleDepthResolveFilterMin >>=
\ r ->
case r of
True -> return (Just WebGPUMultisampleDepthResolveFilterMin)
False
-> x `strictEqual` js_WebGPUMultisampleDepthResolveFilterMax >>=
\ r ->
case r of
True
-> return
(Just WebGPUMultisampleDepthResolveFilterMax)
False -> return Nothing
js_WebGPUMultisampleDepthResolveFilterSample0 = "sample0"
js_WebGPUMultisampleDepthResolveFilterMin = "min"
js_WebGPUMultisampleDepthResolveFilterMax = "max"
data WebGPUFeatureSet = WebGPUFeatureSetLevel1
| WebGPUFeatureSetLevel2
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal WebGPUFeatureSet where
toJSVal WebGPUFeatureSetLevel1 = toJSVal js_WebGPUFeatureSetLevel1
toJSVal WebGPUFeatureSetLevel2 = toJSVal js_WebGPUFeatureSetLevel2
instance FromJSVal WebGPUFeatureSet where
fromJSVal x
= x `strictEqual` js_WebGPUFeatureSetLevel1 >>=
\ r ->
case r of
True -> return (Just WebGPUFeatureSetLevel1)
False
-> x `strictEqual` js_WebGPUFeatureSetLevel2 >>=
\ r ->
case r of
True -> return (Just WebGPUFeatureSetLevel2)
False -> return Nothing
js_WebGPUFeatureSetLevel1 = "level1"
js_WebGPUFeatureSetLevel2 = "level2"
data VideoPresentationMode = VideoPresentationModeFullscreen
| VideoPresentationModePictureInPicture
| VideoPresentationModeInline
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal VideoPresentationMode where
toJSVal VideoPresentationModeFullscreen
= toJSVal js_VideoPresentationModeFullscreen
toJSVal VideoPresentationModePictureInPicture
= toJSVal js_VideoPresentationModePictureInPicture
toJSVal VideoPresentationModeInline
= toJSVal js_VideoPresentationModeInline
instance FromJSVal VideoPresentationMode where
fromJSVal x
= x `strictEqual` js_VideoPresentationModeFullscreen >>=
\ r ->
case r of
True -> return (Just VideoPresentationModeFullscreen)
False
-> x `strictEqual` js_VideoPresentationModePictureInPicture >>=
\ r ->
case r of
True -> return (Just VideoPresentationModePictureInPicture)
False
-> x `strictEqual` js_VideoPresentationModeInline >>=
\ r ->
case r of
True -> return (Just VideoPresentationModeInline)
False -> return Nothing
js_VideoPresentationModeFullscreen = "fullscreen"
js_VideoPresentationModePictureInPicture = "picture-in-picture"
js_VideoPresentationModeInline = "inline"
data TextTrackMode = TextTrackModeDisabled
| TextTrackModeHidden
| TextTrackModeShowing
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal TextTrackMode where
toJSVal TextTrackModeDisabled = toJSVal js_TextTrackModeDisabled
toJSVal TextTrackModeHidden = toJSVal js_TextTrackModeHidden
toJSVal TextTrackModeShowing = toJSVal js_TextTrackModeShowing
instance FromJSVal TextTrackMode where
fromJSVal x
= x `strictEqual` js_TextTrackModeDisabled >>=
\ r ->
case r of
True -> return (Just TextTrackModeDisabled)
False
-> x `strictEqual` js_TextTrackModeHidden >>=
\ r ->
case r of
True -> return (Just TextTrackModeHidden)
False
-> x `strictEqual` js_TextTrackModeShowing >>=
\ r ->
case r of
True -> return (Just TextTrackModeShowing)
False -> return Nothing
js_TextTrackModeDisabled = "disabled"
js_TextTrackModeHidden = "hidden"
js_TextTrackModeShowing = "showing"
data TextTrackKind = TextTrackKindSubtitles
| TextTrackKindCaptions
| TextTrackKindDescriptions
| TextTrackKindChapters
| TextTrackKindMetadata
| TextTrackKindForced
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal TextTrackKind where
toJSVal TextTrackKindSubtitles = toJSVal js_TextTrackKindSubtitles
toJSVal TextTrackKindCaptions = toJSVal js_TextTrackKindCaptions
toJSVal TextTrackKindDescriptions
= toJSVal js_TextTrackKindDescriptions
toJSVal TextTrackKindChapters = toJSVal js_TextTrackKindChapters
toJSVal TextTrackKindMetadata = toJSVal js_TextTrackKindMetadata
toJSVal TextTrackKindForced = toJSVal js_TextTrackKindForced
instance FromJSVal TextTrackKind where
fromJSVal x
= x `strictEqual` js_TextTrackKindSubtitles >>=
\ r ->
case r of
True -> return (Just TextTrackKindSubtitles)
False
-> x `strictEqual` js_TextTrackKindCaptions >>=
\ r ->
case r of
True -> return (Just TextTrackKindCaptions)
False
-> x `strictEqual` js_TextTrackKindDescriptions >>=
\ r ->
case r of
True -> return (Just TextTrackKindDescriptions)
False
-> x `strictEqual` js_TextTrackKindChapters >>=
\ r ->
case r of
True
-> return (Just TextTrackKindChapters)
False
-> x `strictEqual`
js_TextTrackKindMetadata
>>=
\ r ->
case r of
True
-> return
(Just
TextTrackKindMetadata)
False
-> x `strictEqual`
js_TextTrackKindForced
>>=
\ r ->
case r of
True
-> return
(Just
TextTrackKindForced)
False
-> return
Nothing
js_TextTrackKindSubtitles = "subtitles"
js_TextTrackKindCaptions = "captions"
js_TextTrackKindDescriptions = "descriptions"
js_TextTrackKindChapters = "chapters"
js_TextTrackKindMetadata = "metadata"
js_TextTrackKindForced = "forced"
data ApplePayErrorCode = ApplePayErrorCodeUnknown
| ApplePayErrorCodeShippingContactInvalid
| ApplePayErrorCodeBillingContactInvalid
| ApplePayErrorCodeAddressUnservicable
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayErrorCode where
toJSVal ApplePayErrorCodeUnknown
= toJSVal js_ApplePayErrorCodeUnknown
toJSVal ApplePayErrorCodeShippingContactInvalid
= toJSVal js_ApplePayErrorCodeShippingContactInvalid
toJSVal ApplePayErrorCodeBillingContactInvalid
= toJSVal js_ApplePayErrorCodeBillingContactInvalid
toJSVal ApplePayErrorCodeAddressUnservicable
= toJSVal js_ApplePayErrorCodeAddressUnservicable
instance FromJSVal ApplePayErrorCode where
fromJSVal x
= x `strictEqual` js_ApplePayErrorCodeUnknown >>=
\ r ->
case r of
True -> return (Just ApplePayErrorCodeUnknown)
False
-> x `strictEqual` js_ApplePayErrorCodeShippingContactInvalid >>=
\ r ->
case r of
True -> return (Just ApplePayErrorCodeShippingContactInvalid)
False
-> x `strictEqual` js_ApplePayErrorCodeBillingContactInvalid >>=
\ r ->
case r of
True
-> return
(Just ApplePayErrorCodeBillingContactInvalid)
False
-> x `strictEqual`
js_ApplePayErrorCodeAddressUnservicable
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayErrorCodeAddressUnservicable)
False -> return Nothing
js_ApplePayErrorCodeUnknown = "unknown"
js_ApplePayErrorCodeShippingContactInvalid
= "shippingContactInvalid"
js_ApplePayErrorCodeBillingContactInvalid = "billingContactInvalid"
js_ApplePayErrorCodeAddressUnservicable = "addressUnservicable"
data ApplePayErrorContactField = ApplePayErrorContactFieldPhoneNumber
| ApplePayErrorContactFieldEmailAddress
| ApplePayErrorContactFieldName
| ApplePayErrorContactFieldPostalAddress
| ApplePayErrorContactFieldAddressLines
| ApplePayErrorContactFieldLocality
| ApplePayErrorContactFieldPostalCode
| ApplePayErrorContactFieldAdministrativeArea
| ApplePayErrorContactFieldCountry
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayErrorContactField where
toJSVal ApplePayErrorContactFieldPhoneNumber
= toJSVal js_ApplePayErrorContactFieldPhoneNumber
toJSVal ApplePayErrorContactFieldEmailAddress
= toJSVal js_ApplePayErrorContactFieldEmailAddress
toJSVal ApplePayErrorContactFieldName
= toJSVal js_ApplePayErrorContactFieldName
toJSVal ApplePayErrorContactFieldPostalAddress
= toJSVal js_ApplePayErrorContactFieldPostalAddress
toJSVal ApplePayErrorContactFieldAddressLines
= toJSVal js_ApplePayErrorContactFieldAddressLines
toJSVal ApplePayErrorContactFieldLocality
= toJSVal js_ApplePayErrorContactFieldLocality
toJSVal ApplePayErrorContactFieldPostalCode
= toJSVal js_ApplePayErrorContactFieldPostalCode
toJSVal ApplePayErrorContactFieldAdministrativeArea
= toJSVal js_ApplePayErrorContactFieldAdministrativeArea
toJSVal ApplePayErrorContactFieldCountry
= toJSVal js_ApplePayErrorContactFieldCountry
instance FromJSVal ApplePayErrorContactField where
fromJSVal x
= x `strictEqual` js_ApplePayErrorContactFieldPhoneNumber >>=
\ r ->
case r of
True -> return (Just ApplePayErrorContactFieldPhoneNumber)
False
-> x `strictEqual` js_ApplePayErrorContactFieldEmailAddress >>=
\ r ->
case r of
True -> return (Just ApplePayErrorContactFieldEmailAddress)
False
-> x `strictEqual` js_ApplePayErrorContactFieldName >>=
\ r ->
case r of
True -> return (Just ApplePayErrorContactFieldName)
False
-> x `strictEqual`
js_ApplePayErrorContactFieldPostalAddress
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayErrorContactFieldPostalAddress)
False
-> x `strictEqual`
js_ApplePayErrorContactFieldAddressLines
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayErrorContactFieldAddressLines)
False
-> x `strictEqual`
js_ApplePayErrorContactFieldLocality
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayErrorContactFieldLocality)
False
-> x `strictEqual`
js_ApplePayErrorContactFieldPostalCode
>>=
\ r ->
case r
of
True
-> return
(Just
ApplePayErrorContactFieldPostalCode)
False
-> x `strictEqual`
js_ApplePayErrorContactFieldAdministrativeArea
>>=
\ r
->
case
r
of
True
-> return
(Just
ApplePayErrorContactFieldAdministrativeArea)
False
-> x `strictEqual`
js_ApplePayErrorContactFieldCountry
>>=
\ r
->
case
r
of
True
-> return
(Just
ApplePayErrorContactFieldCountry)
False
-> return
Nothing
js_ApplePayErrorContactFieldPhoneNumber = "phoneNumber"
js_ApplePayErrorContactFieldEmailAddress = "emailAddress"
js_ApplePayErrorContactFieldName = "name"
js_ApplePayErrorContactFieldPostalAddress = "postalAddress"
js_ApplePayErrorContactFieldAddressLines = "addressLines"
js_ApplePayErrorContactFieldLocality = "locality"
js_ApplePayErrorContactFieldPostalCode = "postalCode"
js_ApplePayErrorContactFieldAdministrativeArea
= "administrativeArea"
js_ApplePayErrorContactFieldCountry = "country"
data ApplePayLineItemType = ApplePayLineItemTypePending
| ApplePayLineItemTypeFinal
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayLineItemType where
toJSVal ApplePayLineItemTypePending
= toJSVal js_ApplePayLineItemTypePending
toJSVal ApplePayLineItemTypeFinal
= toJSVal js_ApplePayLineItemTypeFinal
instance FromJSVal ApplePayLineItemType where
fromJSVal x
= x `strictEqual` js_ApplePayLineItemTypePending >>=
\ r ->
case r of
True -> return (Just ApplePayLineItemTypePending)
False
-> x `strictEqual` js_ApplePayLineItemTypeFinal >>=
\ r ->
case r of
True -> return (Just ApplePayLineItemTypeFinal)
False -> return Nothing
js_ApplePayLineItemTypePending = "pending"
js_ApplePayLineItemTypeFinal = "final"
data ApplePayPaymentMethodType = ApplePayPaymentMethodTypeDebit
| ApplePayPaymentMethodTypeCredit
| ApplePayPaymentMethodTypePrepaid
| ApplePayPaymentMethodTypeStore
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayPaymentMethodType where
toJSVal ApplePayPaymentMethodTypeDebit
= toJSVal js_ApplePayPaymentMethodTypeDebit
toJSVal ApplePayPaymentMethodTypeCredit
= toJSVal js_ApplePayPaymentMethodTypeCredit
toJSVal ApplePayPaymentMethodTypePrepaid
= toJSVal js_ApplePayPaymentMethodTypePrepaid
toJSVal ApplePayPaymentMethodTypeStore
= toJSVal js_ApplePayPaymentMethodTypeStore
instance FromJSVal ApplePayPaymentMethodType where
fromJSVal x
= x `strictEqual` js_ApplePayPaymentMethodTypeDebit >>=
\ r ->
case r of
True -> return (Just ApplePayPaymentMethodTypeDebit)
False
-> x `strictEqual` js_ApplePayPaymentMethodTypeCredit >>=
\ r ->
case r of
True -> return (Just ApplePayPaymentMethodTypeCredit)
False
-> x `strictEqual` js_ApplePayPaymentMethodTypePrepaid >>=
\ r ->
case r of
True -> return (Just ApplePayPaymentMethodTypePrepaid)
False
-> x `strictEqual` js_ApplePayPaymentMethodTypeStore
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayPaymentMethodTypeStore)
False -> return Nothing
js_ApplePayPaymentMethodTypeDebit = "debit"
js_ApplePayPaymentMethodTypeCredit = "credit"
js_ApplePayPaymentMethodTypePrepaid = "prepaid"
js_ApplePayPaymentMethodTypeStore = "store"
data ApplePayPaymentPassActivationState = ApplePayPaymentPassActivationStateActivated
| ApplePayPaymentPassActivationStateRequiresActivation
| ApplePayPaymentPassActivationStateActivating
| ApplePayPaymentPassActivationStateSuspended
| ApplePayPaymentPassActivationStateDeactivated
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayPaymentPassActivationState where
toJSVal ApplePayPaymentPassActivationStateActivated
= toJSVal js_ApplePayPaymentPassActivationStateActivated
toJSVal ApplePayPaymentPassActivationStateRequiresActivation
= toJSVal js_ApplePayPaymentPassActivationStateRequiresActivation
toJSVal ApplePayPaymentPassActivationStateActivating
= toJSVal js_ApplePayPaymentPassActivationStateActivating
toJSVal ApplePayPaymentPassActivationStateSuspended
= toJSVal js_ApplePayPaymentPassActivationStateSuspended
toJSVal ApplePayPaymentPassActivationStateDeactivated
= toJSVal js_ApplePayPaymentPassActivationStateDeactivated
instance FromJSVal ApplePayPaymentPassActivationState where
fromJSVal x
= x `strictEqual` js_ApplePayPaymentPassActivationStateActivated
>>=
\ r ->
case r of
True -> return (Just ApplePayPaymentPassActivationStateActivated)
False
-> x `strictEqual`
js_ApplePayPaymentPassActivationStateRequiresActivation
>>=
\ r ->
case r of
True
-> return
(Just ApplePayPaymentPassActivationStateRequiresActivation)
False
-> x `strictEqual`
js_ApplePayPaymentPassActivationStateActivating
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayPaymentPassActivationStateActivating)
False
-> x `strictEqual`
js_ApplePayPaymentPassActivationStateSuspended
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayPaymentPassActivationStateSuspended)
False
-> x `strictEqual`
js_ApplePayPaymentPassActivationStateDeactivated
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayPaymentPassActivationStateDeactivated)
False -> return Nothing
js_ApplePayPaymentPassActivationStateActivated = "activated"
js_ApplePayPaymentPassActivationStateRequiresActivation
= "requiresActivation"
js_ApplePayPaymentPassActivationStateActivating = "activating"
js_ApplePayPaymentPassActivationStateSuspended = "suspended"
js_ApplePayPaymentPassActivationStateDeactivated = "deactivated"
data ApplePayMerchantCapability = ApplePayMerchantCapabilitySupports3DS
| ApplePayMerchantCapabilitySupportsEMV
| ApplePayMerchantCapabilitySupportsCredit
| ApplePayMerchantCapabilitySupportsDebit
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayMerchantCapability where
toJSVal ApplePayMerchantCapabilitySupports3DS
= toJSVal js_ApplePayMerchantCapabilitySupports3DS
toJSVal ApplePayMerchantCapabilitySupportsEMV
= toJSVal js_ApplePayMerchantCapabilitySupportsEMV
toJSVal ApplePayMerchantCapabilitySupportsCredit
= toJSVal js_ApplePayMerchantCapabilitySupportsCredit
toJSVal ApplePayMerchantCapabilitySupportsDebit
= toJSVal js_ApplePayMerchantCapabilitySupportsDebit
instance FromJSVal ApplePayMerchantCapability where
fromJSVal x
= x `strictEqual` js_ApplePayMerchantCapabilitySupports3DS >>=
\ r ->
case r of
True -> return (Just ApplePayMerchantCapabilitySupports3DS)
False
-> x `strictEqual` js_ApplePayMerchantCapabilitySupportsEMV >>=
\ r ->
case r of
True -> return (Just ApplePayMerchantCapabilitySupportsEMV)
False
-> x `strictEqual` js_ApplePayMerchantCapabilitySupportsCredit
>>=
\ r ->
case r of
True
-> return
(Just ApplePayMerchantCapabilitySupportsCredit)
False
-> x `strictEqual`
js_ApplePayMerchantCapabilitySupportsDebit
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayMerchantCapabilitySupportsDebit)
False -> return Nothing
js_ApplePayMerchantCapabilitySupports3DS = "supports3DS"
js_ApplePayMerchantCapabilitySupportsEMV = "supportsEMV"
js_ApplePayMerchantCapabilitySupportsCredit = "supportsCredit"
js_ApplePayMerchantCapabilitySupportsDebit = "supportsDebit"
data ApplePayContactField = ApplePayContactFieldEmail
| ApplePayContactFieldName
| ApplePayContactFieldPhone
| ApplePayContactFieldPostalAddress
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayContactField where
toJSVal ApplePayContactFieldEmail
= toJSVal js_ApplePayContactFieldEmail
toJSVal ApplePayContactFieldName
= toJSVal js_ApplePayContactFieldName
toJSVal ApplePayContactFieldPhone
= toJSVal js_ApplePayContactFieldPhone
toJSVal ApplePayContactFieldPostalAddress
= toJSVal js_ApplePayContactFieldPostalAddress
instance FromJSVal ApplePayContactField where
fromJSVal x
= x `strictEqual` js_ApplePayContactFieldEmail >>=
\ r ->
case r of
True -> return (Just ApplePayContactFieldEmail)
False
-> x `strictEqual` js_ApplePayContactFieldName >>=
\ r ->
case r of
True -> return (Just ApplePayContactFieldName)
False
-> x `strictEqual` js_ApplePayContactFieldPhone >>=
\ r ->
case r of
True -> return (Just ApplePayContactFieldPhone)
False
-> x `strictEqual`
js_ApplePayContactFieldPostalAddress
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayContactFieldPostalAddress)
False -> return Nothing
js_ApplePayContactFieldEmail = "email"
js_ApplePayContactFieldName = "name"
js_ApplePayContactFieldPhone = "phone"
js_ApplePayContactFieldPostalAddress = "postalAddress"
data ApplePayShippingType = ApplePayShippingTypeShipping
| ApplePayShippingTypeDelivery
| ApplePayShippingTypeStorePickup
| ApplePayShippingTypeServicePickup
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ApplePayShippingType where
toJSVal ApplePayShippingTypeShipping
= toJSVal js_ApplePayShippingTypeShipping
toJSVal ApplePayShippingTypeDelivery
= toJSVal js_ApplePayShippingTypeDelivery
toJSVal ApplePayShippingTypeStorePickup
= toJSVal js_ApplePayShippingTypeStorePickup
toJSVal ApplePayShippingTypeServicePickup
= toJSVal js_ApplePayShippingTypeServicePickup
instance FromJSVal ApplePayShippingType where
fromJSVal x
= x `strictEqual` js_ApplePayShippingTypeShipping >>=
\ r ->
case r of
True -> return (Just ApplePayShippingTypeShipping)
False
-> x `strictEqual` js_ApplePayShippingTypeDelivery >>=
\ r ->
case r of
True -> return (Just ApplePayShippingTypeDelivery)
False
-> x `strictEqual` js_ApplePayShippingTypeStorePickup >>=
\ r ->
case r of
True -> return (Just ApplePayShippingTypeStorePickup)
False
-> x `strictEqual`
js_ApplePayShippingTypeServicePickup
>>=
\ r ->
case r of
True
-> return
(Just
ApplePayShippingTypeServicePickup)
False -> return Nothing
js_ApplePayShippingTypeShipping = "shipping"
js_ApplePayShippingTypeDelivery = "delivery"
js_ApplePayShippingTypeStorePickup = "storePickup"
js_ApplePayShippingTypeServicePickup = "servicePickup"
data MediaKeyMessageType = MediaKeyMessageTypeLicenseRequest
| MediaKeyMessageTypeLicenseRenewal
| MediaKeyMessageTypeLicenseRelease
| MediaKeyMessageTypeIndividualizationRequest
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal MediaKeyMessageType where
toJSVal MediaKeyMessageTypeLicenseRequest
= toJSVal js_MediaKeyMessageTypeLicenseRequest
toJSVal MediaKeyMessageTypeLicenseRenewal
= toJSVal js_MediaKeyMessageTypeLicenseRenewal
toJSVal MediaKeyMessageTypeLicenseRelease
= toJSVal js_MediaKeyMessageTypeLicenseRelease
toJSVal MediaKeyMessageTypeIndividualizationRequest
= toJSVal js_MediaKeyMessageTypeIndividualizationRequest
instance FromJSVal MediaKeyMessageType where
fromJSVal x
= x `strictEqual` js_MediaKeyMessageTypeLicenseRequest >>=
\ r ->
case r of
True -> return (Just MediaKeyMessageTypeLicenseRequest)
False
-> x `strictEqual` js_MediaKeyMessageTypeLicenseRenewal >>=
\ r ->
case r of
True -> return (Just MediaKeyMessageTypeLicenseRenewal)
False
-> x `strictEqual` js_MediaKeyMessageTypeLicenseRelease >>=
\ r ->
case r of
True
-> return (Just MediaKeyMessageTypeLicenseRelease)
False
-> x `strictEqual`
js_MediaKeyMessageTypeIndividualizationRequest
>>=
\ r ->
case r of
True
-> return
(Just
MediaKeyMessageTypeIndividualizationRequest)
False -> return Nothing
js_MediaKeyMessageTypeLicenseRequest = "license-request"
js_MediaKeyMessageTypeLicenseRenewal = "license-renewal"
js_MediaKeyMessageTypeLicenseRelease = "license-release"
js_MediaKeyMessageTypeIndividualizationRequest
= "individualization-request"
data MediaKeySessionType = MediaKeySessionTypeTemporary
| MediaKeySessionTypePersistentUsageRecord
| MediaKeySessionTypePersistentLicense
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal MediaKeySessionType where
toJSVal MediaKeySessionTypeTemporary
= toJSVal js_MediaKeySessionTypeTemporary
toJSVal MediaKeySessionTypePersistentUsageRecord
= toJSVal js_MediaKeySessionTypePersistentUsageRecord
toJSVal MediaKeySessionTypePersistentLicense
= toJSVal js_MediaKeySessionTypePersistentLicense
instance FromJSVal MediaKeySessionType where
fromJSVal x
= x `strictEqual` js_MediaKeySessionTypeTemporary >>=
\ r ->
case r of
True -> return (Just MediaKeySessionTypeTemporary)
False
-> x `strictEqual` js_MediaKeySessionTypePersistentUsageRecord >>=
\ r ->
case r of
True -> return (Just MediaKeySessionTypePersistentUsageRecord)
False
-> x `strictEqual` js_MediaKeySessionTypePersistentLicense >>=
\ r ->
case r of
True
-> return
(Just MediaKeySessionTypePersistentLicense)
False -> return Nothing
js_MediaKeySessionTypeTemporary = "temporary"
js_MediaKeySessionTypePersistentUsageRecord
= "persistent-usage-record"
js_MediaKeySessionTypePersistentLicense = "persistent-license"
data MediaKeysRequirement = MediaKeysRequirementRequired
| MediaKeysRequirementOptional
| MediaKeysRequirementNotAllowed
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal MediaKeysRequirement where
toJSVal MediaKeysRequirementRequired
= toJSVal js_MediaKeysRequirementRequired
toJSVal MediaKeysRequirementOptional
= toJSVal js_MediaKeysRequirementOptional
toJSVal MediaKeysRequirementNotAllowed
= toJSVal js_MediaKeysRequirementNotAllowed
instance FromJSVal MediaKeysRequirement where
fromJSVal x
= x `strictEqual` js_MediaKeysRequirementRequired >>=
\ r ->
case r of
True -> return (Just MediaKeysRequirementRequired)
False
-> x `strictEqual` js_MediaKeysRequirementOptional >>=
\ r ->
case r of
True -> return (Just MediaKeysRequirementOptional)
False
-> x `strictEqual` js_MediaKeysRequirementNotAllowed >>=
\ r ->
case r of
True -> return (Just MediaKeysRequirementNotAllowed)
False -> return Nothing
js_MediaKeysRequirementRequired = "required"
js_MediaKeysRequirementOptional = "optional"
js_MediaKeysRequirementNotAllowed = "not-allowed"
data MediaKeyStatus = MediaKeyStatusUsable
| MediaKeyStatusExpired
| MediaKeyStatusReleased
| MediaKeyStatusOutputRestricted
| MediaKeyStatusOutputDownscaled
| MediaKeyStatusStatusPending
| MediaKeyStatusInternalError
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal MediaKeyStatus where
toJSVal MediaKeyStatusUsable = toJSVal js_MediaKeyStatusUsable
toJSVal MediaKeyStatusExpired = toJSVal js_MediaKeyStatusExpired
toJSVal MediaKeyStatusReleased = toJSVal js_MediaKeyStatusReleased
toJSVal MediaKeyStatusOutputRestricted
= toJSVal js_MediaKeyStatusOutputRestricted
toJSVal MediaKeyStatusOutputDownscaled
= toJSVal js_MediaKeyStatusOutputDownscaled
toJSVal MediaKeyStatusStatusPending
= toJSVal js_MediaKeyStatusStatusPending
toJSVal MediaKeyStatusInternalError
= toJSVal js_MediaKeyStatusInternalError
instance FromJSVal MediaKeyStatus where
fromJSVal x
= x `strictEqual` js_MediaKeyStatusUsable >>=
\ r ->
case r of
True -> return (Just MediaKeyStatusUsable)
False
-> x `strictEqual` js_MediaKeyStatusExpired >>=
\ r ->
case r of
True -> return (Just MediaKeyStatusExpired)
False
-> x `strictEqual` js_MediaKeyStatusReleased >>=
\ r ->
case r of
True -> return (Just MediaKeyStatusReleased)
False
-> x `strictEqual` js_MediaKeyStatusOutputRestricted
>>=
\ r ->
case r of
True
-> return
(Just
MediaKeyStatusOutputRestricted)
False
-> x `strictEqual`
js_MediaKeyStatusOutputDownscaled
>>=
\ r ->
case r of
True
-> return
(Just
MediaKeyStatusOutputDownscaled)
False
-> x `strictEqual`
js_MediaKeyStatusStatusPending
>>=
\ r ->
case r of
True
-> return
(Just
MediaKeyStatusStatusPending)
False
-> x `strictEqual`
js_MediaKeyStatusInternalError
>>=
\ r ->
case r
of
True
-> return
(Just
MediaKeyStatusInternalError)
False
-> return
Nothing
js_MediaKeyStatusUsable = "usable"
js_MediaKeyStatusExpired = "expired"
js_MediaKeyStatusReleased = "released"
js_MediaKeyStatusOutputRestricted = "output-restricted"
js_MediaKeyStatusOutputDownscaled = "output-downscaled"
js_MediaKeyStatusStatusPending = "status-pending"
js_MediaKeyStatusInternalError = "internal-error"
data RequestType = RequestType
| RequestTypeAudio
| RequestTypeFont
| RequestTypeImage
| RequestTypeScript
| RequestTypeStyle
| RequestTypeTrack
| RequestTypeVideo
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RequestType where
toJSVal RequestType = toJSVal js_RequestType
toJSVal RequestTypeAudio = toJSVal js_RequestTypeAudio
toJSVal RequestTypeFont = toJSVal js_RequestTypeFont
toJSVal RequestTypeImage = toJSVal js_RequestTypeImage
toJSVal RequestTypeScript = toJSVal js_RequestTypeScript
toJSVal RequestTypeStyle = toJSVal js_RequestTypeStyle
toJSVal RequestTypeTrack = toJSVal js_RequestTypeTrack
toJSVal RequestTypeVideo = toJSVal js_RequestTypeVideo
instance FromJSVal RequestType where
fromJSVal x
= x `strictEqual` js_RequestType >>=
\ r ->
case r of
True -> return (Just RequestType)
False
-> x `strictEqual` js_RequestTypeAudio >>=
\ r ->
case r of
True -> return (Just RequestTypeAudio)
False
-> x `strictEqual` js_RequestTypeFont >>=
\ r ->
case r of
True -> return (Just RequestTypeFont)
False
-> x `strictEqual` js_RequestTypeImage >>=
\ r ->
case r of
True -> return (Just RequestTypeImage)
False
-> x `strictEqual` js_RequestTypeScript
>>=
\ r ->
case r of
True
-> return
(Just
RequestTypeScript)
False
-> x `strictEqual`
js_RequestTypeStyle
>>=
\ r ->
case r of
True
-> return
(Just
RequestTypeStyle)
False
-> x `strictEqual`
js_RequestTypeTrack
>>=
\ r ->
case r
of
True
-> return
(Just
RequestTypeTrack)
False
-> x `strictEqual`
js_RequestTypeVideo
>>=
\ r
->
case
r
of
True
-> return
(Just
RequestTypeVideo)
False
-> return
Nothing
js_RequestType = ""
js_RequestTypeAudio = "audio"
js_RequestTypeFont = "font"
js_RequestTypeImage = "image"
js_RequestTypeScript = "script"
js_RequestTypeStyle = "style"
js_RequestTypeTrack = "track"
js_RequestTypeVideo = "video"
data RequestDestination = RequestDestination
| RequestDestinationDocument
| RequestDestinationSharedworker
| RequestDestinationSubresource
| RequestDestinationUnknown
| RequestDestinationWorker
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RequestDestination where
toJSVal RequestDestination = toJSVal js_RequestDestination
toJSVal RequestDestinationDocument
= toJSVal js_RequestDestinationDocument
toJSVal RequestDestinationSharedworker
= toJSVal js_RequestDestinationSharedworker
toJSVal RequestDestinationSubresource
= toJSVal js_RequestDestinationSubresource
toJSVal RequestDestinationUnknown
= toJSVal js_RequestDestinationUnknown
toJSVal RequestDestinationWorker
= toJSVal js_RequestDestinationWorker
instance FromJSVal RequestDestination where
fromJSVal x
= x `strictEqual` js_RequestDestination >>=
\ r ->
case r of
True -> return (Just RequestDestination)
False
-> x `strictEqual` js_RequestDestinationDocument >>=
\ r ->
case r of
True -> return (Just RequestDestinationDocument)
False
-> x `strictEqual` js_RequestDestinationSharedworker >>=
\ r ->
case r of
True -> return (Just RequestDestinationSharedworker)
False
-> x `strictEqual` js_RequestDestinationSubresource
>>=
\ r ->
case r of
True
-> return
(Just
RequestDestinationSubresource)
False
-> x `strictEqual`
js_RequestDestinationUnknown
>>=
\ r ->
case r of
True
-> return
(Just
RequestDestinationUnknown)
False
-> x `strictEqual`
js_RequestDestinationWorker
>>=
\ r ->
case r of
True
-> return
(Just
RequestDestinationWorker)
False
-> return
Nothing
js_RequestDestination = ""
js_RequestDestinationDocument = "document"
js_RequestDestinationSharedworker = "sharedworker"
js_RequestDestinationSubresource = "subresource"
js_RequestDestinationUnknown = "unknown"
js_RequestDestinationWorker = "worker"
data RequestMode = RequestModeNavigate
| RequestModeSameOrigin
| RequestModeNoCors
| RequestModeCors
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RequestMode where
toJSVal RequestModeNavigate = toJSVal js_RequestModeNavigate
toJSVal RequestModeSameOrigin = toJSVal js_RequestModeSameOrigin
toJSVal RequestModeNoCors = toJSVal js_RequestModeNoCors
toJSVal RequestModeCors = toJSVal js_RequestModeCors
instance FromJSVal RequestMode where
fromJSVal x
= x `strictEqual` js_RequestModeNavigate >>=
\ r ->
case r of
True -> return (Just RequestModeNavigate)
False
-> x `strictEqual` js_RequestModeSameOrigin >>=
\ r ->
case r of
True -> return (Just RequestModeSameOrigin)
False
-> x `strictEqual` js_RequestModeNoCors >>=
\ r ->
case r of
True -> return (Just RequestModeNoCors)
False
-> x `strictEqual` js_RequestModeCors >>=
\ r ->
case r of
True -> return (Just RequestModeCors)
False -> return Nothing
js_RequestModeNavigate = "navigate"
js_RequestModeSameOrigin = "same-origin"
js_RequestModeNoCors = "no-cors"
js_RequestModeCors = "cors"
data RequestCredentials = RequestCredentialsOmit
| RequestCredentialsSameOrigin
| RequestCredentialsInclude
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RequestCredentials where
toJSVal RequestCredentialsOmit = toJSVal js_RequestCredentialsOmit
toJSVal RequestCredentialsSameOrigin
= toJSVal js_RequestCredentialsSameOrigin
toJSVal RequestCredentialsInclude
= toJSVal js_RequestCredentialsInclude
instance FromJSVal RequestCredentials where
fromJSVal x
= x `strictEqual` js_RequestCredentialsOmit >>=
\ r ->
case r of
True -> return (Just RequestCredentialsOmit)
False
-> x `strictEqual` js_RequestCredentialsSameOrigin >>=
\ r ->
case r of
True -> return (Just RequestCredentialsSameOrigin)
False
-> x `strictEqual` js_RequestCredentialsInclude >>=
\ r ->
case r of
True -> return (Just RequestCredentialsInclude)
False -> return Nothing
js_RequestCredentialsOmit = "omit"
js_RequestCredentialsSameOrigin = "same-origin"
js_RequestCredentialsInclude = "include"
data RequestCache = RequestCacheDefault
| RequestCacheNoStore
| RequestCacheReload
| RequestCacheNoCache
| RequestCacheForceCache
| RequestCacheOnlyIfCached
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RequestCache where
toJSVal RequestCacheDefault = toJSVal js_RequestCacheDefault
toJSVal RequestCacheNoStore = toJSVal js_RequestCacheNoStore
toJSVal RequestCacheReload = toJSVal js_RequestCacheReload
toJSVal RequestCacheNoCache = toJSVal js_RequestCacheNoCache
toJSVal RequestCacheForceCache = toJSVal js_RequestCacheForceCache
toJSVal RequestCacheOnlyIfCached
= toJSVal js_RequestCacheOnlyIfCached
instance FromJSVal RequestCache where
fromJSVal x
= x `strictEqual` js_RequestCacheDefault >>=
\ r ->
case r of
True -> return (Just RequestCacheDefault)
False
-> x `strictEqual` js_RequestCacheNoStore >>=
\ r ->
case r of
True -> return (Just RequestCacheNoStore)
False
-> x `strictEqual` js_RequestCacheReload >>=
\ r ->
case r of
True -> return (Just RequestCacheReload)
False
-> x `strictEqual` js_RequestCacheNoCache >>=
\ r ->
case r of
True -> return (Just RequestCacheNoCache)
False
-> x `strictEqual`
js_RequestCacheForceCache
>>=
\ r ->
case r of
True
-> return
(Just
RequestCacheForceCache)
False
-> x `strictEqual`
js_RequestCacheOnlyIfCached
>>=
\ r ->
case r of
True
-> return
(Just
RequestCacheOnlyIfCached)
False
-> return
Nothing
js_RequestCacheDefault = "default"
js_RequestCacheNoStore = "no-store"
js_RequestCacheReload = "reload"
js_RequestCacheNoCache = "no-cache"
js_RequestCacheForceCache = "force-cache"
js_RequestCacheOnlyIfCached = "only-if-cached"
data RequestRedirect = RequestRedirectFollow
| RequestRedirectError
| RequestRedirectManual
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RequestRedirect where
toJSVal RequestRedirectFollow = toJSVal js_RequestRedirectFollow
toJSVal RequestRedirectError = toJSVal js_RequestRedirectError
toJSVal RequestRedirectManual = toJSVal js_RequestRedirectManual
instance FromJSVal RequestRedirect where
fromJSVal x
= x `strictEqual` js_RequestRedirectFollow >>=
\ r ->
case r of
True -> return (Just RequestRedirectFollow)
False
-> x `strictEqual` js_RequestRedirectError >>=
\ r ->
case r of
True -> return (Just RequestRedirectError)
False
-> x `strictEqual` js_RequestRedirectManual >>=
\ r ->
case r of
True -> return (Just RequestRedirectManual)
False -> return Nothing
js_RequestRedirectFollow = "follow"
js_RequestRedirectError = "error"
js_RequestRedirectManual = "manual"
data ReferrerPolicy = ReferrerPolicy
| ReferrerPolicyNoReferrer
| ReferrerPolicyNoReferrerWhenDowngrade
| ReferrerPolicyOrigin
| ReferrerPolicyOriginWhenCrossOrigin
| ReferrerPolicyUnsafeUrl
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ReferrerPolicy where
toJSVal ReferrerPolicy = toJSVal js_ReferrerPolicy
toJSVal ReferrerPolicyNoReferrer
= toJSVal js_ReferrerPolicyNoReferrer
toJSVal ReferrerPolicyNoReferrerWhenDowngrade
= toJSVal js_ReferrerPolicyNoReferrerWhenDowngrade
toJSVal ReferrerPolicyOrigin = toJSVal js_ReferrerPolicyOrigin
toJSVal ReferrerPolicyOriginWhenCrossOrigin
= toJSVal js_ReferrerPolicyOriginWhenCrossOrigin
toJSVal ReferrerPolicyUnsafeUrl
= toJSVal js_ReferrerPolicyUnsafeUrl
instance FromJSVal ReferrerPolicy where
fromJSVal x
= x `strictEqual` js_ReferrerPolicy >>=
\ r ->
case r of
True -> return (Just ReferrerPolicy)
False
-> x `strictEqual` js_ReferrerPolicyNoReferrer >>=
\ r ->
case r of
True -> return (Just ReferrerPolicyNoReferrer)
False
-> x `strictEqual` js_ReferrerPolicyNoReferrerWhenDowngrade >>=
\ r ->
case r of
True
-> return
(Just ReferrerPolicyNoReferrerWhenDowngrade)
False
-> x `strictEqual` js_ReferrerPolicyOrigin >>=
\ r ->
case r of
True
-> return (Just ReferrerPolicyOrigin)
False
-> x `strictEqual`
js_ReferrerPolicyOriginWhenCrossOrigin
>>=
\ r ->
case r of
True
-> return
(Just
ReferrerPolicyOriginWhenCrossOrigin)
False
-> x `strictEqual`
js_ReferrerPolicyUnsafeUrl
>>=
\ r ->
case r of
True
-> return
(Just
ReferrerPolicyUnsafeUrl)
False
-> return
Nothing
js_ReferrerPolicy = ""
js_ReferrerPolicyNoReferrer = "no-referrer"
js_ReferrerPolicyNoReferrerWhenDowngrade
= "no-referrer-when-downgrade"
js_ReferrerPolicyOrigin = "origin"
js_ReferrerPolicyOriginWhenCrossOrigin = "origin-when-cross-origin"
js_ReferrerPolicyUnsafeUrl = "unsafe-url"
data ResponseType = ResponseTypeBasic
| ResponseTypeCors
| ResponseTypeDefault
| ResponseTypeError
| ResponseTypeOpaque
| ResponseTypeOpaqueredirect
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ResponseType where
toJSVal ResponseTypeBasic = toJSVal js_ResponseTypeBasic
toJSVal ResponseTypeCors = toJSVal js_ResponseTypeCors
toJSVal ResponseTypeDefault = toJSVal js_ResponseTypeDefault
toJSVal ResponseTypeError = toJSVal js_ResponseTypeError
toJSVal ResponseTypeOpaque = toJSVal js_ResponseTypeOpaque
toJSVal ResponseTypeOpaqueredirect
= toJSVal js_ResponseTypeOpaqueredirect
instance FromJSVal ResponseType where
fromJSVal x
= x `strictEqual` js_ResponseTypeBasic >>=
\ r ->
case r of
True -> return (Just ResponseTypeBasic)
False
-> x `strictEqual` js_ResponseTypeCors >>=
\ r ->
case r of
True -> return (Just ResponseTypeCors)
False
-> x `strictEqual` js_ResponseTypeDefault >>=
\ r ->
case r of
True -> return (Just ResponseTypeDefault)
False
-> x `strictEqual` js_ResponseTypeError >>=
\ r ->
case r of
True -> return (Just ResponseTypeError)
False
-> x `strictEqual`
js_ResponseTypeOpaque
>>=
\ r ->
case r of
True
-> return
(Just
ResponseTypeOpaque)
False
-> x `strictEqual`
js_ResponseTypeOpaqueredirect
>>=
\ r ->
case r of
True
-> return
(Just
ResponseTypeOpaqueredirect)
False
-> return
Nothing
js_ResponseTypeBasic = "basic"
js_ResponseTypeCors = "cors"
js_ResponseTypeDefault = "default"
js_ResponseTypeError = "error"
js_ResponseTypeOpaque = "opaque"
js_ResponseTypeOpaqueredirect = "opaqueredirect"
data IDBCursorDirection = IDBCursorDirectionNext
| IDBCursorDirectionNextunique
| IDBCursorDirectionPrev
| IDBCursorDirectionPrevunique
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal IDBCursorDirection where
toJSVal IDBCursorDirectionNext = toJSVal js_IDBCursorDirectionNext
toJSVal IDBCursorDirectionNextunique
= toJSVal js_IDBCursorDirectionNextunique
toJSVal IDBCursorDirectionPrev = toJSVal js_IDBCursorDirectionPrev
toJSVal IDBCursorDirectionPrevunique
= toJSVal js_IDBCursorDirectionPrevunique
instance FromJSVal IDBCursorDirection where
fromJSVal x
= x `strictEqual` js_IDBCursorDirectionNext >>=
\ r ->
case r of
True -> return (Just IDBCursorDirectionNext)
False
-> x `strictEqual` js_IDBCursorDirectionNextunique >>=
\ r ->
case r of
True -> return (Just IDBCursorDirectionNextunique)
False
-> x `strictEqual` js_IDBCursorDirectionPrev >>=
\ r ->
case r of
True -> return (Just IDBCursorDirectionPrev)
False
-> x `strictEqual` js_IDBCursorDirectionPrevunique
>>=
\ r ->
case r of
True
-> return
(Just
IDBCursorDirectionPrevunique)
False -> return Nothing
js_IDBCursorDirectionNext = "next"
js_IDBCursorDirectionNextunique = "nextunique"
js_IDBCursorDirectionPrev = "prev"
js_IDBCursorDirectionPrevunique = "prevunique"
data IDBRequestReadyState = IDBRequestReadyStatePending
| IDBRequestReadyStateDone
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal IDBRequestReadyState where
toJSVal IDBRequestReadyStatePending
= toJSVal js_IDBRequestReadyStatePending
toJSVal IDBRequestReadyStateDone
= toJSVal js_IDBRequestReadyStateDone
instance FromJSVal IDBRequestReadyState where
fromJSVal x
= x `strictEqual` js_IDBRequestReadyStatePending >>=
\ r ->
case r of
True -> return (Just IDBRequestReadyStatePending)
False
-> x `strictEqual` js_IDBRequestReadyStateDone >>=
\ r ->
case r of
True -> return (Just IDBRequestReadyStateDone)
False -> return Nothing
js_IDBRequestReadyStatePending = "pending"
js_IDBRequestReadyStateDone = "done"
data IDBTransactionMode = IDBTransactionModeReadonly
| IDBTransactionModeReadwrite
| IDBTransactionModeVersionchange
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal IDBTransactionMode where
toJSVal IDBTransactionModeReadonly
= toJSVal js_IDBTransactionModeReadonly
toJSVal IDBTransactionModeReadwrite
= toJSVal js_IDBTransactionModeReadwrite
toJSVal IDBTransactionModeVersionchange
= toJSVal js_IDBTransactionModeVersionchange
instance FromJSVal IDBTransactionMode where
fromJSVal x
= x `strictEqual` js_IDBTransactionModeReadonly >>=
\ r ->
case r of
True -> return (Just IDBTransactionModeReadonly)
False
-> x `strictEqual` js_IDBTransactionModeReadwrite >>=
\ r ->
case r of
True -> return (Just IDBTransactionModeReadwrite)
False
-> x `strictEqual` js_IDBTransactionModeVersionchange >>=
\ r ->
case r of
True -> return (Just IDBTransactionModeVersionchange)
False -> return Nothing
js_IDBTransactionModeReadonly = "readonly"
js_IDBTransactionModeReadwrite = "readwrite"
js_IDBTransactionModeVersionchange = "versionchange"
data DeviceType = DeviceTypeNone
| DeviceTypeAirplay
| DeviceTypeTvout
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal DeviceType where
toJSVal DeviceTypeNone = toJSVal js_DeviceTypeNone
toJSVal DeviceTypeAirplay = toJSVal js_DeviceTypeAirplay
toJSVal DeviceTypeTvout = toJSVal js_DeviceTypeTvout
instance FromJSVal DeviceType where
fromJSVal x
= x `strictEqual` js_DeviceTypeNone >>=
\ r ->
case r of
True -> return (Just DeviceTypeNone)
False
-> x `strictEqual` js_DeviceTypeAirplay >>=
\ r ->
case r of
True -> return (Just DeviceTypeAirplay)
False
-> x `strictEqual` js_DeviceTypeTvout >>=
\ r ->
case r of
True -> return (Just DeviceTypeTvout)
False -> return Nothing
js_DeviceTypeNone = "none"
js_DeviceTypeAirplay = "airplay"
js_DeviceTypeTvout = "tvout"
data MediaSessionKind = MediaSessionKindContent
| MediaSessionKindTransient
| MediaSessionKindTransientSolo
| MediaSessionKindAmbient
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal MediaSessionKind where
toJSVal MediaSessionKindContent
= toJSVal js_MediaSessionKindContent
toJSVal MediaSessionKindTransient
= toJSVal js_MediaSessionKindTransient
toJSVal MediaSessionKindTransientSolo
= toJSVal js_MediaSessionKindTransientSolo
toJSVal MediaSessionKindAmbient
= toJSVal js_MediaSessionKindAmbient
instance FromJSVal MediaSessionKind where
fromJSVal x
= x `strictEqual` js_MediaSessionKindContent >>=
\ r ->
case r of
True -> return (Just MediaSessionKindContent)
False
-> x `strictEqual` js_MediaSessionKindTransient >>=
\ r ->
case r of
True -> return (Just MediaSessionKindTransient)
False
-> x `strictEqual` js_MediaSessionKindTransientSolo >>=
\ r ->
case r of
True -> return (Just MediaSessionKindTransientSolo)
False
-> x `strictEqual` js_MediaSessionKindAmbient >>=
\ r ->
case r of
True
-> return
(Just MediaSessionKindAmbient)
False -> return Nothing
js_MediaSessionKindContent = "content"
js_MediaSessionKindTransient = "transient"
js_MediaSessionKindTransientSolo = "transient-solo"
js_MediaSessionKindAmbient = "ambient"
data EndOfStreamError = EndOfStreamErrorNetwork
| EndOfStreamErrorDecode
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal EndOfStreamError where
toJSVal EndOfStreamErrorNetwork
= toJSVal js_EndOfStreamErrorNetwork
toJSVal EndOfStreamErrorDecode = toJSVal js_EndOfStreamErrorDecode
instance FromJSVal EndOfStreamError where
fromJSVal x
= x `strictEqual` js_EndOfStreamErrorNetwork >>=
\ r ->
case r of
True -> return (Just EndOfStreamErrorNetwork)
False
-> x `strictEqual` js_EndOfStreamErrorDecode >>=
\ r ->
case r of
True -> return (Just EndOfStreamErrorDecode)
False -> return Nothing
js_EndOfStreamErrorNetwork = "network"
js_EndOfStreamErrorDecode = "decode"
data ReadyState = ReadyStateClosed
| ReadyStateOpen
| ReadyStateEnded
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ReadyState where
toJSVal ReadyStateClosed = toJSVal js_ReadyStateClosed
toJSVal ReadyStateOpen = toJSVal js_ReadyStateOpen
toJSVal ReadyStateEnded = toJSVal js_ReadyStateEnded
instance FromJSVal ReadyState where
fromJSVal x
= x `strictEqual` js_ReadyStateClosed >>=
\ r ->
case r of
True -> return (Just ReadyStateClosed)
False
-> x `strictEqual` js_ReadyStateOpen >>=
\ r ->
case r of
True -> return (Just ReadyStateOpen)
False
-> x `strictEqual` js_ReadyStateEnded >>=
\ r ->
case r of
True -> return (Just ReadyStateEnded)
False -> return Nothing
js_ReadyStateClosed = "closed"
js_ReadyStateOpen = "open"
js_ReadyStateEnded = "ended"
data AppendMode = AppendModeSegments
| AppendModeSequence
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal AppendMode where
toJSVal AppendModeSegments = toJSVal js_AppendModeSegments
toJSVal AppendModeSequence = toJSVal js_AppendModeSequence
instance FromJSVal AppendMode where
fromJSVal x
= x `strictEqual` js_AppendModeSegments >>=
\ r ->
case r of
True -> return (Just AppendModeSegments)
False
-> x `strictEqual` js_AppendModeSequence >>=
\ r ->
case r of
True -> return (Just AppendModeSequence)
False -> return Nothing
js_AppendModeSegments = "segments"
js_AppendModeSequence = "sequence"
data MediaDeviceKind = MediaDeviceKindAudioinput
| MediaDeviceKindAudiooutput
| MediaDeviceKindVideoinput
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal MediaDeviceKind where
toJSVal MediaDeviceKindAudioinput
= toJSVal js_MediaDeviceKindAudioinput
toJSVal MediaDeviceKindAudiooutput
= toJSVal js_MediaDeviceKindAudiooutput
toJSVal MediaDeviceKindVideoinput
= toJSVal js_MediaDeviceKindVideoinput
instance FromJSVal MediaDeviceKind where
fromJSVal x
= x `strictEqual` js_MediaDeviceKindAudioinput >>=
\ r ->
case r of
True -> return (Just MediaDeviceKindAudioinput)
False
-> x `strictEqual` js_MediaDeviceKindAudiooutput >>=
\ r ->
case r of
True -> return (Just MediaDeviceKindAudiooutput)
False
-> x `strictEqual` js_MediaDeviceKindVideoinput >>=
\ r ->
case r of
True -> return (Just MediaDeviceKindVideoinput)
False -> return Nothing
js_MediaDeviceKindAudioinput = "audioinput"
js_MediaDeviceKindAudiooutput = "audiooutput"
js_MediaDeviceKindVideoinput = "videoinput"
data MediaStreamTrackState = MediaStreamTrackStateLive
| MediaStreamTrackStateEnded
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal MediaStreamTrackState where
toJSVal MediaStreamTrackStateLive
= toJSVal js_MediaStreamTrackStateLive
toJSVal MediaStreamTrackStateEnded
= toJSVal js_MediaStreamTrackStateEnded
instance FromJSVal MediaStreamTrackState where
fromJSVal x
= x `strictEqual` js_MediaStreamTrackStateLive >>=
\ r ->
case r of
True -> return (Just MediaStreamTrackStateLive)
False
-> x `strictEqual` js_MediaStreamTrackStateEnded >>=
\ r ->
case r of
True -> return (Just MediaStreamTrackStateEnded)
False -> return Nothing
js_MediaStreamTrackStateLive = "live"
js_MediaStreamTrackStateEnded = "ended"
data RTCIceTransportPolicy = RTCIceTransportPolicyRelay
| RTCIceTransportPolicyAll
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCIceTransportPolicy where
toJSVal RTCIceTransportPolicyRelay
= toJSVal js_RTCIceTransportPolicyRelay
toJSVal RTCIceTransportPolicyAll
= toJSVal js_RTCIceTransportPolicyAll
instance FromJSVal RTCIceTransportPolicy where
fromJSVal x
= x `strictEqual` js_RTCIceTransportPolicyRelay >>=
\ r ->
case r of
True -> return (Just RTCIceTransportPolicyRelay)
False
-> x `strictEqual` js_RTCIceTransportPolicyAll >>=
\ r ->
case r of
True -> return (Just RTCIceTransportPolicyAll)
False -> return Nothing
js_RTCIceTransportPolicyRelay = "relay"
js_RTCIceTransportPolicyAll = "all"
data RTCBundlePolicy = RTCBundlePolicyBalanced
| RTCBundlePolicyMaxCompat
| RTCBundlePolicyMaxBundle
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCBundlePolicy where
toJSVal RTCBundlePolicyBalanced
= toJSVal js_RTCBundlePolicyBalanced
toJSVal RTCBundlePolicyMaxCompat
= toJSVal js_RTCBundlePolicyMaxCompat
toJSVal RTCBundlePolicyMaxBundle
= toJSVal js_RTCBundlePolicyMaxBundle
instance FromJSVal RTCBundlePolicy where
fromJSVal x
= x `strictEqual` js_RTCBundlePolicyBalanced >>=
\ r ->
case r of
True -> return (Just RTCBundlePolicyBalanced)
False
-> x `strictEqual` js_RTCBundlePolicyMaxCompat >>=
\ r ->
case r of
True -> return (Just RTCBundlePolicyMaxCompat)
False
-> x `strictEqual` js_RTCBundlePolicyMaxBundle >>=
\ r ->
case r of
True -> return (Just RTCBundlePolicyMaxBundle)
False -> return Nothing
js_RTCBundlePolicyBalanced = "balanced"
js_RTCBundlePolicyMaxCompat = "max-compat"
js_RTCBundlePolicyMaxBundle = "max-bundle"
data RTCDataChannelState = RTCDataChannelStateConnecting
| RTCDataChannelStateOpen
| RTCDataChannelStateClosing
| RTCDataChannelStateClosed
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCDataChannelState where
toJSVal RTCDataChannelStateConnecting
= toJSVal js_RTCDataChannelStateConnecting
toJSVal RTCDataChannelStateOpen
= toJSVal js_RTCDataChannelStateOpen
toJSVal RTCDataChannelStateClosing
= toJSVal js_RTCDataChannelStateClosing
toJSVal RTCDataChannelStateClosed
= toJSVal js_RTCDataChannelStateClosed
instance FromJSVal RTCDataChannelState where
fromJSVal x
= x `strictEqual` js_RTCDataChannelStateConnecting >>=
\ r ->
case r of
True -> return (Just RTCDataChannelStateConnecting)
False
-> x `strictEqual` js_RTCDataChannelStateOpen >>=
\ r ->
case r of
True -> return (Just RTCDataChannelStateOpen)
False
-> x `strictEqual` js_RTCDataChannelStateClosing >>=
\ r ->
case r of
True -> return (Just RTCDataChannelStateClosing)
False
-> x `strictEqual` js_RTCDataChannelStateClosed >>=
\ r ->
case r of
True
-> return
(Just RTCDataChannelStateClosed)
False -> return Nothing
js_RTCDataChannelStateConnecting = "connecting"
js_RTCDataChannelStateOpen = "open"
js_RTCDataChannelStateClosing = "closing"
js_RTCDataChannelStateClosed = "closed"
data RTCIceConnectionState = RTCIceConnectionStateNew
| RTCIceConnectionStateChecking
| RTCIceConnectionStateConnected
| RTCIceConnectionStateCompleted
| RTCIceConnectionStateFailed
| RTCIceConnectionStateDisconnected
| RTCIceConnectionStateClosed
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCIceConnectionState where
toJSVal RTCIceConnectionStateNew
= toJSVal js_RTCIceConnectionStateNew
toJSVal RTCIceConnectionStateChecking
= toJSVal js_RTCIceConnectionStateChecking
toJSVal RTCIceConnectionStateConnected
= toJSVal js_RTCIceConnectionStateConnected
toJSVal RTCIceConnectionStateCompleted
= toJSVal js_RTCIceConnectionStateCompleted
toJSVal RTCIceConnectionStateFailed
= toJSVal js_RTCIceConnectionStateFailed
toJSVal RTCIceConnectionStateDisconnected
= toJSVal js_RTCIceConnectionStateDisconnected
toJSVal RTCIceConnectionStateClosed
= toJSVal js_RTCIceConnectionStateClosed
instance FromJSVal RTCIceConnectionState where
fromJSVal x
= x `strictEqual` js_RTCIceConnectionStateNew >>=
\ r ->
case r of
True -> return (Just RTCIceConnectionStateNew)
False
-> x `strictEqual` js_RTCIceConnectionStateChecking >>=
\ r ->
case r of
True -> return (Just RTCIceConnectionStateChecking)
False
-> x `strictEqual` js_RTCIceConnectionStateConnected >>=
\ r ->
case r of
True -> return (Just RTCIceConnectionStateConnected)
False
-> x `strictEqual` js_RTCIceConnectionStateCompleted
>>=
\ r ->
case r of
True
-> return
(Just
RTCIceConnectionStateCompleted)
False
-> x `strictEqual`
js_RTCIceConnectionStateFailed
>>=
\ r ->
case r of
True
-> return
(Just
RTCIceConnectionStateFailed)
False
-> x `strictEqual`
js_RTCIceConnectionStateDisconnected
>>=
\ r ->
case r of
True
-> return
(Just
RTCIceConnectionStateDisconnected)
False
-> x `strictEqual`
js_RTCIceConnectionStateClosed
>>=
\ r ->
case r
of
True
-> return
(Just
RTCIceConnectionStateClosed)
False
-> return
Nothing
js_RTCIceConnectionStateNew = "new"
js_RTCIceConnectionStateChecking = "checking"
js_RTCIceConnectionStateConnected = "connected"
js_RTCIceConnectionStateCompleted = "completed"
js_RTCIceConnectionStateFailed = "failed"
js_RTCIceConnectionStateDisconnected = "disconnected"
js_RTCIceConnectionStateClosed = "closed"
data RTCIceGatheringState = RTCIceGatheringStateNew
| RTCIceGatheringStateGathering
| RTCIceGatheringStateComplete
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCIceGatheringState where
toJSVal RTCIceGatheringStateNew
= toJSVal js_RTCIceGatheringStateNew
toJSVal RTCIceGatheringStateGathering
= toJSVal js_RTCIceGatheringStateGathering
toJSVal RTCIceGatheringStateComplete
= toJSVal js_RTCIceGatheringStateComplete
instance FromJSVal RTCIceGatheringState where
fromJSVal x
= x `strictEqual` js_RTCIceGatheringStateNew >>=
\ r ->
case r of
True -> return (Just RTCIceGatheringStateNew)
False
-> x `strictEqual` js_RTCIceGatheringStateGathering >>=
\ r ->
case r of
True -> return (Just RTCIceGatheringStateGathering)
False
-> x `strictEqual` js_RTCIceGatheringStateComplete >>=
\ r ->
case r of
True -> return (Just RTCIceGatheringStateComplete)
False -> return Nothing
js_RTCIceGatheringStateNew = "new"
js_RTCIceGatheringStateGathering = "gathering"
js_RTCIceGatheringStateComplete = "complete"
data RTCIceTransportState = RTCIceTransportStateNew
| RTCIceTransportStateChecking
| RTCIceTransportStateConnected
| RTCIceTransportStateCompleted
| RTCIceTransportStateFailed
| RTCIceTransportStateDisconnected
| RTCIceTransportStateClosed
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCIceTransportState where
toJSVal RTCIceTransportStateNew
= toJSVal js_RTCIceTransportStateNew
toJSVal RTCIceTransportStateChecking
= toJSVal js_RTCIceTransportStateChecking
toJSVal RTCIceTransportStateConnected
= toJSVal js_RTCIceTransportStateConnected
toJSVal RTCIceTransportStateCompleted
= toJSVal js_RTCIceTransportStateCompleted
toJSVal RTCIceTransportStateFailed
= toJSVal js_RTCIceTransportStateFailed
toJSVal RTCIceTransportStateDisconnected
= toJSVal js_RTCIceTransportStateDisconnected
toJSVal RTCIceTransportStateClosed
= toJSVal js_RTCIceTransportStateClosed
instance FromJSVal RTCIceTransportState where
fromJSVal x
= x `strictEqual` js_RTCIceTransportStateNew >>=
\ r ->
case r of
True -> return (Just RTCIceTransportStateNew)
False
-> x `strictEqual` js_RTCIceTransportStateChecking >>=
\ r ->
case r of
True -> return (Just RTCIceTransportStateChecking)
False
-> x `strictEqual` js_RTCIceTransportStateConnected >>=
\ r ->
case r of
True -> return (Just RTCIceTransportStateConnected)
False
-> x `strictEqual` js_RTCIceTransportStateCompleted
>>=
\ r ->
case r of
True
-> return
(Just
RTCIceTransportStateCompleted)
False
-> x `strictEqual`
js_RTCIceTransportStateFailed
>>=
\ r ->
case r of
True
-> return
(Just
RTCIceTransportStateFailed)
False
-> x `strictEqual`
js_RTCIceTransportStateDisconnected
>>=
\ r ->
case r of
True
-> return
(Just
RTCIceTransportStateDisconnected)
False
-> x `strictEqual`
js_RTCIceTransportStateClosed
>>=
\ r ->
case r
of
True
-> return
(Just
RTCIceTransportStateClosed)
False
-> return
Nothing
js_RTCIceTransportStateNew = "new"
js_RTCIceTransportStateChecking = "checking"
js_RTCIceTransportStateConnected = "connected"
js_RTCIceTransportStateCompleted = "completed"
js_RTCIceTransportStateFailed = "failed"
js_RTCIceTransportStateDisconnected = "disconnected"
js_RTCIceTransportStateClosed = "closed"
data RTCPeerConnectionState = RTCPeerConnectionStateNew
| RTCPeerConnectionStateConnecting
| RTCPeerConnectionStateConnected
| RTCPeerConnectionStateDisconnected
| RTCPeerConnectionStateFailed
| RTCPeerConnectionStateClosed
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCPeerConnectionState where
toJSVal RTCPeerConnectionStateNew
= toJSVal js_RTCPeerConnectionStateNew
toJSVal RTCPeerConnectionStateConnecting
= toJSVal js_RTCPeerConnectionStateConnecting
toJSVal RTCPeerConnectionStateConnected
= toJSVal js_RTCPeerConnectionStateConnected
toJSVal RTCPeerConnectionStateDisconnected
= toJSVal js_RTCPeerConnectionStateDisconnected
toJSVal RTCPeerConnectionStateFailed
= toJSVal js_RTCPeerConnectionStateFailed
toJSVal RTCPeerConnectionStateClosed
= toJSVal js_RTCPeerConnectionStateClosed
instance FromJSVal RTCPeerConnectionState where
fromJSVal x
= x `strictEqual` js_RTCPeerConnectionStateNew >>=
\ r ->
case r of
True -> return (Just RTCPeerConnectionStateNew)
False
-> x `strictEqual` js_RTCPeerConnectionStateConnecting >>=
\ r ->
case r of
True -> return (Just RTCPeerConnectionStateConnecting)
False
-> x `strictEqual` js_RTCPeerConnectionStateConnected >>=
\ r ->
case r of
True -> return (Just RTCPeerConnectionStateConnected)
False
-> x `strictEqual`
js_RTCPeerConnectionStateDisconnected
>>=
\ r ->
case r of
True
-> return
(Just
RTCPeerConnectionStateDisconnected)
False
-> x `strictEqual`
js_RTCPeerConnectionStateFailed
>>=
\ r ->
case r of
True
-> return
(Just
RTCPeerConnectionStateFailed)
False
-> x `strictEqual`
js_RTCPeerConnectionStateClosed
>>=
\ r ->
case r of
True
-> return
(Just
RTCPeerConnectionStateClosed)
False
-> return
Nothing
js_RTCPeerConnectionStateNew = "new"
js_RTCPeerConnectionStateConnecting = "connecting"
js_RTCPeerConnectionStateConnected = "connected"
js_RTCPeerConnectionStateDisconnected = "disconnected"
js_RTCPeerConnectionStateFailed = "failed"
js_RTCPeerConnectionStateClosed = "closed"
data RTCDegradationPreference = RTCDegradationPreferenceMaintainFramerate
| RTCDegradationPreferenceMaintainResolution
| RTCDegradationPreferenceBalanced
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCDegradationPreference where
toJSVal RTCDegradationPreferenceMaintainFramerate
= toJSVal js_RTCDegradationPreferenceMaintainFramerate
toJSVal RTCDegradationPreferenceMaintainResolution
= toJSVal js_RTCDegradationPreferenceMaintainResolution
toJSVal RTCDegradationPreferenceBalanced
= toJSVal js_RTCDegradationPreferenceBalanced
instance FromJSVal RTCDegradationPreference where
fromJSVal x
= x `strictEqual` js_RTCDegradationPreferenceMaintainFramerate >>=
\ r ->
case r of
True -> return (Just RTCDegradationPreferenceMaintainFramerate)
False
-> x `strictEqual` js_RTCDegradationPreferenceMaintainResolution
>>=
\ r ->
case r of
True -> return (Just RTCDegradationPreferenceMaintainResolution)
False
-> x `strictEqual` js_RTCDegradationPreferenceBalanced >>=
\ r ->
case r of
True -> return (Just RTCDegradationPreferenceBalanced)
False -> return Nothing
js_RTCDegradationPreferenceMaintainFramerate = "maintain-framerate"
js_RTCDegradationPreferenceMaintainResolution
= "maintain-resolution"
js_RTCDegradationPreferenceBalanced = "balanced"
data RTCDtxStatus = RTCDtxStatusDisabled
| RTCDtxStatusEnabled
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCDtxStatus where
toJSVal RTCDtxStatusDisabled = toJSVal js_RTCDtxStatusDisabled
toJSVal RTCDtxStatusEnabled = toJSVal js_RTCDtxStatusEnabled
instance FromJSVal RTCDtxStatus where
fromJSVal x
= x `strictEqual` js_RTCDtxStatusDisabled >>=
\ r ->
case r of
True -> return (Just RTCDtxStatusDisabled)
False
-> x `strictEqual` js_RTCDtxStatusEnabled >>=
\ r ->
case r of
True -> return (Just RTCDtxStatusEnabled)
False -> return Nothing
js_RTCDtxStatusDisabled = "disabled"
js_RTCDtxStatusEnabled = "enabled"
data RTCPriorityType = RTCPriorityTypeVeryLow
| RTCPriorityTypeLow
| RTCPriorityTypeMedium
| RTCPriorityTypeHigh
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCPriorityType where
toJSVal RTCPriorityTypeVeryLow = toJSVal js_RTCPriorityTypeVeryLow
toJSVal RTCPriorityTypeLow = toJSVal js_RTCPriorityTypeLow
toJSVal RTCPriorityTypeMedium = toJSVal js_RTCPriorityTypeMedium
toJSVal RTCPriorityTypeHigh = toJSVal js_RTCPriorityTypeHigh
instance FromJSVal RTCPriorityType where
fromJSVal x
= x `strictEqual` js_RTCPriorityTypeVeryLow >>=
\ r ->
case r of
True -> return (Just RTCPriorityTypeVeryLow)
False
-> x `strictEqual` js_RTCPriorityTypeLow >>=
\ r ->
case r of
True -> return (Just RTCPriorityTypeLow)
False
-> x `strictEqual` js_RTCPriorityTypeMedium >>=
\ r ->
case r of
True -> return (Just RTCPriorityTypeMedium)
False
-> x `strictEqual` js_RTCPriorityTypeHigh >>=
\ r ->
case r of
True -> return (Just RTCPriorityTypeHigh)
False -> return Nothing
js_RTCPriorityTypeVeryLow = "very-low"
js_RTCPriorityTypeLow = "low"
js_RTCPriorityTypeMedium = "medium"
js_RTCPriorityTypeHigh = "high"
data RTCRtpTransceiverDirection = RTCRtpTransceiverDirectionSendrecv
| RTCRtpTransceiverDirectionSendonly
| RTCRtpTransceiverDirectionRecvonly
| RTCRtpTransceiverDirectionInactive
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCRtpTransceiverDirection where
toJSVal RTCRtpTransceiverDirectionSendrecv
= toJSVal js_RTCRtpTransceiverDirectionSendrecv
toJSVal RTCRtpTransceiverDirectionSendonly
= toJSVal js_RTCRtpTransceiverDirectionSendonly
toJSVal RTCRtpTransceiverDirectionRecvonly
= toJSVal js_RTCRtpTransceiverDirectionRecvonly
toJSVal RTCRtpTransceiverDirectionInactive
= toJSVal js_RTCRtpTransceiverDirectionInactive
instance FromJSVal RTCRtpTransceiverDirection where
fromJSVal x
= x `strictEqual` js_RTCRtpTransceiverDirectionSendrecv >>=
\ r ->
case r of
True -> return (Just RTCRtpTransceiverDirectionSendrecv)
False
-> x `strictEqual` js_RTCRtpTransceiverDirectionSendonly >>=
\ r ->
case r of
True -> return (Just RTCRtpTransceiverDirectionSendonly)
False
-> x `strictEqual` js_RTCRtpTransceiverDirectionRecvonly >>=
\ r ->
case r of
True
-> return (Just RTCRtpTransceiverDirectionRecvonly)
False
-> x `strictEqual`
js_RTCRtpTransceiverDirectionInactive
>>=
\ r ->
case r of
True
-> return
(Just
RTCRtpTransceiverDirectionInactive)
False -> return Nothing
js_RTCRtpTransceiverDirectionSendrecv = "sendrecv"
js_RTCRtpTransceiverDirectionSendonly = "sendonly"
js_RTCRtpTransceiverDirectionRecvonly = "recvonly"
js_RTCRtpTransceiverDirectionInactive = "inactive"
data RTCSdpType = RTCSdpTypeOffer
| RTCSdpTypePranswer
| RTCSdpTypeAnswer
| RTCSdpTypeRollback
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCSdpType where
toJSVal RTCSdpTypeOffer = toJSVal js_RTCSdpTypeOffer
toJSVal RTCSdpTypePranswer = toJSVal js_RTCSdpTypePranswer
toJSVal RTCSdpTypeAnswer = toJSVal js_RTCSdpTypeAnswer
toJSVal RTCSdpTypeRollback = toJSVal js_RTCSdpTypeRollback
instance FromJSVal RTCSdpType where
fromJSVal x
= x `strictEqual` js_RTCSdpTypeOffer >>=
\ r ->
case r of
True -> return (Just RTCSdpTypeOffer)
False
-> x `strictEqual` js_RTCSdpTypePranswer >>=
\ r ->
case r of
True -> return (Just RTCSdpTypePranswer)
False
-> x `strictEqual` js_RTCSdpTypeAnswer >>=
\ r ->
case r of
True -> return (Just RTCSdpTypeAnswer)
False
-> x `strictEqual` js_RTCSdpTypeRollback >>=
\ r ->
case r of
True -> return (Just RTCSdpTypeRollback)
False -> return Nothing
js_RTCSdpTypeOffer = "offer"
js_RTCSdpTypePranswer = "pranswer"
js_RTCSdpTypeAnswer = "answer"
js_RTCSdpTypeRollback = "rollback"
data RTCSignalingState = RTCSignalingStateStable
| RTCSignalingStateHaveLocalOffer
| RTCSignalingStateHaveRemoteOffer
| RTCSignalingStateHaveLocalPranswer
| RTCSignalingStateHaveRemotePranswer
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCSignalingState where
toJSVal RTCSignalingStateStable
= toJSVal js_RTCSignalingStateStable
toJSVal RTCSignalingStateHaveLocalOffer
= toJSVal js_RTCSignalingStateHaveLocalOffer
toJSVal RTCSignalingStateHaveRemoteOffer
= toJSVal js_RTCSignalingStateHaveRemoteOffer
toJSVal RTCSignalingStateHaveLocalPranswer
= toJSVal js_RTCSignalingStateHaveLocalPranswer
toJSVal RTCSignalingStateHaveRemotePranswer
= toJSVal js_RTCSignalingStateHaveRemotePranswer
instance FromJSVal RTCSignalingState where
fromJSVal x
= x `strictEqual` js_RTCSignalingStateStable >>=
\ r ->
case r of
True -> return (Just RTCSignalingStateStable)
False
-> x `strictEqual` js_RTCSignalingStateHaveLocalOffer >>=
\ r ->
case r of
True -> return (Just RTCSignalingStateHaveLocalOffer)
False
-> x `strictEqual` js_RTCSignalingStateHaveRemoteOffer >>=
\ r ->
case r of
True -> return (Just RTCSignalingStateHaveRemoteOffer)
False
-> x `strictEqual`
js_RTCSignalingStateHaveLocalPranswer
>>=
\ r ->
case r of
True
-> return
(Just
RTCSignalingStateHaveLocalPranswer)
False
-> x `strictEqual`
js_RTCSignalingStateHaveRemotePranswer
>>=
\ r ->
case r of
True
-> return
(Just
RTCSignalingStateHaveRemotePranswer)
False -> return Nothing
js_RTCSignalingStateStable = "stable"
js_RTCSignalingStateHaveLocalOffer = "have-local-offer"
js_RTCSignalingStateHaveRemoteOffer = "have-remote-offer"
js_RTCSignalingStateHaveLocalPranswer = "have-local-pranswer"
js_RTCSignalingStateHaveRemotePranswer = "have-remote-pranswer"
data RTCStatsType = RTCStatsTypeCodec
| RTCStatsTypeInboundRtp
| RTCStatsTypeOutboundRtp
| RTCStatsTypePeerConnection
| RTCStatsTypeDataChannel
| RTCStatsTypeTrack
| RTCStatsTypeTransport
| RTCStatsTypeCandidatePair
| RTCStatsTypeLocalCandidate
| RTCStatsTypeRemoteCandidate
| RTCStatsTypeCertificate
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal RTCStatsType where
toJSVal RTCStatsTypeCodec = toJSVal js_RTCStatsTypeCodec
toJSVal RTCStatsTypeInboundRtp = toJSVal js_RTCStatsTypeInboundRtp
toJSVal RTCStatsTypeOutboundRtp
= toJSVal js_RTCStatsTypeOutboundRtp
toJSVal RTCStatsTypePeerConnection
= toJSVal js_RTCStatsTypePeerConnection
toJSVal RTCStatsTypeDataChannel
= toJSVal js_RTCStatsTypeDataChannel
toJSVal RTCStatsTypeTrack = toJSVal js_RTCStatsTypeTrack
toJSVal RTCStatsTypeTransport = toJSVal js_RTCStatsTypeTransport
toJSVal RTCStatsTypeCandidatePair
= toJSVal js_RTCStatsTypeCandidatePair
toJSVal RTCStatsTypeLocalCandidate
= toJSVal js_RTCStatsTypeLocalCandidate
toJSVal RTCStatsTypeRemoteCandidate
= toJSVal js_RTCStatsTypeRemoteCandidate
toJSVal RTCStatsTypeCertificate
= toJSVal js_RTCStatsTypeCertificate
instance FromJSVal RTCStatsType where
fromJSVal x
= x `strictEqual` js_RTCStatsTypeCodec >>=
\ r ->
case r of
True -> return (Just RTCStatsTypeCodec)
False
-> x `strictEqual` js_RTCStatsTypeInboundRtp >>=
\ r ->
case r of
True -> return (Just RTCStatsTypeInboundRtp)
False
-> x `strictEqual` js_RTCStatsTypeOutboundRtp >>=
\ r ->
case r of
True -> return (Just RTCStatsTypeOutboundRtp)
False
-> x `strictEqual` js_RTCStatsTypePeerConnection >>=
\ r ->
case r of
True
-> return
(Just RTCStatsTypePeerConnection)
False
-> x `strictEqual`
js_RTCStatsTypeDataChannel
>>=
\ r ->
case r of
True
-> return
(Just
RTCStatsTypeDataChannel)
False
-> x `strictEqual`
js_RTCStatsTypeTrack
>>=
\ r ->
case r of
True
-> return
(Just
RTCStatsTypeTrack)
False
-> x `strictEqual`
js_RTCStatsTypeTransport
>>=
\ r ->
case r
of
True
-> return
(Just
RTCStatsTypeTransport)
False
-> x `strictEqual`
js_RTCStatsTypeCandidatePair
>>=
\ r
->
case
r
of
True
-> return
(Just
RTCStatsTypeCandidatePair)
False
-> x `strictEqual`
js_RTCStatsTypeLocalCandidate
>>=
\ r
->
case
r
of
True
-> return
(Just
RTCStatsTypeLocalCandidate)
False
-> x `strictEqual`
js_RTCStatsTypeRemoteCandidate
>>=
\ r
->
case
r
of
True
-> return
(Just
RTCStatsTypeRemoteCandidate)
False
-> x `strictEqual`
js_RTCStatsTypeCertificate
>>=
\ r
->
case
r
of
True
-> return
(Just
RTCStatsTypeCertificate)
False
-> return
Nothing
js_RTCStatsTypeCodec = "codec"
js_RTCStatsTypeInboundRtp = "inbound-rtp"
js_RTCStatsTypeOutboundRtp = "outbound-rtp"
js_RTCStatsTypePeerConnection = "peer-connection"
js_RTCStatsTypeDataChannel = "data-channel"
js_RTCStatsTypeTrack = "track"
js_RTCStatsTypeTransport = "transport"
js_RTCStatsTypeCandidatePair = "candidate-pair"
js_RTCStatsTypeLocalCandidate = "local-candidate"
js_RTCStatsTypeRemoteCandidate = "remote-candidate"
js_RTCStatsTypeCertificate = "certificate"
data NotificationDirection = NotificationDirectionAuto
| NotificationDirectionLtr
| NotificationDirectionRtl
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal NotificationDirection where
toJSVal NotificationDirectionAuto
= toJSVal js_NotificationDirectionAuto
toJSVal NotificationDirectionLtr
= toJSVal js_NotificationDirectionLtr
toJSVal NotificationDirectionRtl
= toJSVal js_NotificationDirectionRtl
instance FromJSVal NotificationDirection where
fromJSVal x
= x `strictEqual` js_NotificationDirectionAuto >>=
\ r ->
case r of
True -> return (Just NotificationDirectionAuto)
False
-> x `strictEqual` js_NotificationDirectionLtr >>=
\ r ->
case r of
True -> return (Just NotificationDirectionLtr)
False
-> x `strictEqual` js_NotificationDirectionRtl >>=
\ r ->
case r of
True -> return (Just NotificationDirectionRtl)
False -> return Nothing
js_NotificationDirectionAuto = "auto"
js_NotificationDirectionLtr = "ltr"
js_NotificationDirectionRtl = "rtl"
data AudioContextState = AudioContextStateSuspended
| AudioContextStateRunning
| AudioContextStateInterrupted
| AudioContextStateClosed
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal AudioContextState where
toJSVal AudioContextStateSuspended
= toJSVal js_AudioContextStateSuspended
toJSVal AudioContextStateRunning
= toJSVal js_AudioContextStateRunning
toJSVal AudioContextStateInterrupted
= toJSVal js_AudioContextStateInterrupted
toJSVal AudioContextStateClosed
= toJSVal js_AudioContextStateClosed
instance FromJSVal AudioContextState where
fromJSVal x
= x `strictEqual` js_AudioContextStateSuspended >>=
\ r ->
case r of
True -> return (Just AudioContextStateSuspended)
False
-> x `strictEqual` js_AudioContextStateRunning >>=
\ r ->
case r of
True -> return (Just AudioContextStateRunning)
False
-> x `strictEqual` js_AudioContextStateInterrupted >>=
\ r ->
case r of
True -> return (Just AudioContextStateInterrupted)
False
-> x `strictEqual` js_AudioContextStateClosed >>=
\ r ->
case r of
True
-> return
(Just AudioContextStateClosed)
False -> return Nothing
js_AudioContextStateSuspended = "suspended"
js_AudioContextStateRunning = "running"
js_AudioContextStateInterrupted = "interrupted"
js_AudioContextStateClosed = "closed"
data BiquadFilterType = BiquadFilterTypeLowpass
| BiquadFilterTypeHighpass
| BiquadFilterTypeBandpass
| BiquadFilterTypeLowshelf
| BiquadFilterTypeHighshelf
| BiquadFilterTypePeaking
| BiquadFilterTypeNotch
| BiquadFilterTypeAllpass
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal BiquadFilterType where
toJSVal BiquadFilterTypeLowpass
= toJSVal js_BiquadFilterTypeLowpass
toJSVal BiquadFilterTypeHighpass
= toJSVal js_BiquadFilterTypeHighpass
toJSVal BiquadFilterTypeBandpass
= toJSVal js_BiquadFilterTypeBandpass
toJSVal BiquadFilterTypeLowshelf
= toJSVal js_BiquadFilterTypeLowshelf
toJSVal BiquadFilterTypeHighshelf
= toJSVal js_BiquadFilterTypeHighshelf
toJSVal BiquadFilterTypePeaking
= toJSVal js_BiquadFilterTypePeaking
toJSVal BiquadFilterTypeNotch = toJSVal js_BiquadFilterTypeNotch
toJSVal BiquadFilterTypeAllpass
= toJSVal js_BiquadFilterTypeAllpass
instance FromJSVal BiquadFilterType where
fromJSVal x
= x `strictEqual` js_BiquadFilterTypeLowpass >>=
\ r ->
case r of
True -> return (Just BiquadFilterTypeLowpass)
False
-> x `strictEqual` js_BiquadFilterTypeHighpass >>=
\ r ->
case r of
True -> return (Just BiquadFilterTypeHighpass)
False
-> x `strictEqual` js_BiquadFilterTypeBandpass >>=
\ r ->
case r of
True -> return (Just BiquadFilterTypeBandpass)
False
-> x `strictEqual` js_BiquadFilterTypeLowshelf >>=
\ r ->
case r of
True
-> return
(Just BiquadFilterTypeLowshelf)
False
-> x `strictEqual`
js_BiquadFilterTypeHighshelf
>>=
\ r ->
case r of
True
-> return
(Just
BiquadFilterTypeHighshelf)
False
-> x `strictEqual`
js_BiquadFilterTypePeaking
>>=
\ r ->
case r of
True
-> return
(Just
BiquadFilterTypePeaking)
False
-> x `strictEqual`
js_BiquadFilterTypeNotch
>>=
\ r ->
case r
of
True
-> return
(Just
BiquadFilterTypeNotch)
False
-> x `strictEqual`
js_BiquadFilterTypeAllpass
>>=
\ r
->
case
r
of
True
-> return
(Just
BiquadFilterTypeAllpass)
False
-> return
Nothing
js_BiquadFilterTypeLowpass = "lowpass"
js_BiquadFilterTypeHighpass = "highpass"
js_BiquadFilterTypeBandpass = "bandpass"
js_BiquadFilterTypeLowshelf = "lowshelf"
js_BiquadFilterTypeHighshelf = "highshelf"
js_BiquadFilterTypePeaking = "peaking"
js_BiquadFilterTypeNotch = "notch"
js_BiquadFilterTypeAllpass = "allpass"
data OscillatorType = OscillatorTypeSine
| OscillatorTypeSquare
| OscillatorTypeSawtooth
| OscillatorTypeTriangle
| OscillatorTypeCustom
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal OscillatorType where
toJSVal OscillatorTypeSine = toJSVal js_OscillatorTypeSine
toJSVal OscillatorTypeSquare = toJSVal js_OscillatorTypeSquare
toJSVal OscillatorTypeSawtooth = toJSVal js_OscillatorTypeSawtooth
toJSVal OscillatorTypeTriangle = toJSVal js_OscillatorTypeTriangle
toJSVal OscillatorTypeCustom = toJSVal js_OscillatorTypeCustom
instance FromJSVal OscillatorType where
fromJSVal x
= x `strictEqual` js_OscillatorTypeSine >>=
\ r ->
case r of
True -> return (Just OscillatorTypeSine)
False
-> x `strictEqual` js_OscillatorTypeSquare >>=
\ r ->
case r of
True -> return (Just OscillatorTypeSquare)
False
-> x `strictEqual` js_OscillatorTypeSawtooth >>=
\ r ->
case r of
True -> return (Just OscillatorTypeSawtooth)
False
-> x `strictEqual` js_OscillatorTypeTriangle >>=
\ r ->
case r of
True
-> return (Just OscillatorTypeTriangle)
False
-> x `strictEqual`
js_OscillatorTypeCustom
>>=
\ r ->
case r of
True
-> return
(Just
OscillatorTypeCustom)
False -> return Nothing
js_OscillatorTypeSine = "sine"
js_OscillatorTypeSquare = "square"
js_OscillatorTypeSawtooth = "sawtooth"
js_OscillatorTypeTriangle = "triangle"
js_OscillatorTypeCustom = "custom"
data PanningModelType = PanningModelTypeEqualpower
| PanningModelTypeHRTF
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal PanningModelType where
toJSVal PanningModelTypeEqualpower
= toJSVal js_PanningModelTypeEqualpower
toJSVal PanningModelTypeHRTF = toJSVal js_PanningModelTypeHRTF
instance FromJSVal PanningModelType where
fromJSVal x
= x `strictEqual` js_PanningModelTypeEqualpower >>=
\ r ->
case r of
True -> return (Just PanningModelTypeEqualpower)
False
-> x `strictEqual` js_PanningModelTypeHRTF >>=
\ r ->
case r of
True -> return (Just PanningModelTypeHRTF)
False -> return Nothing
js_PanningModelTypeEqualpower = "equalpower"
js_PanningModelTypeHRTF = "HRTF"
data DistanceModelType = DistanceModelTypeLinear
| DistanceModelTypeInverse
| DistanceModelTypeExponential
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal DistanceModelType where
toJSVal DistanceModelTypeLinear
= toJSVal js_DistanceModelTypeLinear
toJSVal DistanceModelTypeInverse
= toJSVal js_DistanceModelTypeInverse
toJSVal DistanceModelTypeExponential
= toJSVal js_DistanceModelTypeExponential
instance FromJSVal DistanceModelType where
fromJSVal x
= x `strictEqual` js_DistanceModelTypeLinear >>=
\ r ->
case r of
True -> return (Just DistanceModelTypeLinear)
False
-> x `strictEqual` js_DistanceModelTypeInverse >>=
\ r ->
case r of
True -> return (Just DistanceModelTypeInverse)
False
-> x `strictEqual` js_DistanceModelTypeExponential >>=
\ r ->
case r of
True -> return (Just DistanceModelTypeExponential)
False -> return Nothing
js_DistanceModelTypeLinear = "linear"
js_DistanceModelTypeInverse = "inverse"
js_DistanceModelTypeExponential = "exponential"
data OverSampleType = OverSampleTypeNone
| OverSampleType2x
| OverSampleType4x
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal OverSampleType where
toJSVal OverSampleTypeNone = toJSVal js_OverSampleTypeNone
toJSVal OverSampleType2x = toJSVal js_OverSampleType2x
toJSVal OverSampleType4x = toJSVal js_OverSampleType4x
instance FromJSVal OverSampleType where
fromJSVal x
= x `strictEqual` js_OverSampleTypeNone >>=
\ r ->
case r of
True -> return (Just OverSampleTypeNone)
False
-> x `strictEqual` js_OverSampleType2x >>=
\ r ->
case r of
True -> return (Just OverSampleType2x)
False
-> x `strictEqual` js_OverSampleType4x >>=
\ r ->
case r of
True -> return (Just OverSampleType4x)
False -> return Nothing
js_OverSampleTypeNone = "none"
js_OverSampleType2x = "2x"
js_OverSampleType4x = "4x"
data ScrollRestoration = ScrollRestorationAuto
| ScrollRestorationManual
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal ScrollRestoration where
toJSVal ScrollRestorationAuto = toJSVal js_ScrollRestorationAuto
toJSVal ScrollRestorationManual
= toJSVal js_ScrollRestorationManual
instance FromJSVal ScrollRestoration where
fromJSVal x
= x `strictEqual` js_ScrollRestorationAuto >>=
\ r ->
case r of
True -> return (Just ScrollRestorationAuto)
False
-> x `strictEqual` js_ScrollRestorationManual >>=
\ r ->
case r of
True -> return (Just ScrollRestorationManual)
False -> return Nothing
js_ScrollRestorationAuto = "auto"
js_ScrollRestorationManual = "manual"
data XMLHttpRequestResponseType = XMLHttpRequestResponseType
| XMLHttpRequestResponseTypeArraybuffer
| XMLHttpRequestResponseTypeBlob
| XMLHttpRequestResponseTypeDocument
| XMLHttpRequestResponseTypeJson
| XMLHttpRequestResponseTypeText
deriving (Show, Read, Eq, Ord, Typeable)
instance ToJSVal XMLHttpRequestResponseType where
toJSVal XMLHttpRequestResponseType
= toJSVal js_XMLHttpRequestResponseType
toJSVal XMLHttpRequestResponseTypeArraybuffer
= toJSVal js_XMLHttpRequestResponseTypeArraybuffer
toJSVal XMLHttpRequestResponseTypeBlob
= toJSVal js_XMLHttpRequestResponseTypeBlob
toJSVal XMLHttpRequestResponseTypeDocument
= toJSVal js_XMLHttpRequestResponseTypeDocument
toJSVal XMLHttpRequestResponseTypeJson
= toJSVal js_XMLHttpRequestResponseTypeJson
toJSVal XMLHttpRequestResponseTypeText
= toJSVal js_XMLHttpRequestResponseTypeText
instance FromJSVal XMLHttpRequestResponseType where
fromJSVal x
= x `strictEqual` js_XMLHttpRequestResponseType >>=
\ r ->
case r of
True -> return (Just XMLHttpRequestResponseType)
False
-> x `strictEqual` js_XMLHttpRequestResponseTypeArraybuffer >>=
\ r ->
case r of
True -> return (Just XMLHttpRequestResponseTypeArraybuffer)
False
-> x `strictEqual` js_XMLHttpRequestResponseTypeBlob >>=
\ r ->
case r of
True -> return (Just XMLHttpRequestResponseTypeBlob)
False
-> x `strictEqual`
js_XMLHttpRequestResponseTypeDocument
>>=
\ r ->
case r of
True
-> return
(Just
XMLHttpRequestResponseTypeDocument)
False
-> x `strictEqual`
js_XMLHttpRequestResponseTypeJson
>>=
\ r ->
case r of
True
-> return
(Just
XMLHttpRequestResponseTypeJson)
False
-> x `strictEqual`
js_XMLHttpRequestResponseTypeText
>>=
\ r ->
case r of
True
-> return
(Just
XMLHttpRequestResponseTypeText)
False
-> return
Nothing
js_XMLHttpRequestResponseType = ""
js_XMLHttpRequestResponseTypeArraybuffer = "arraybuffer"
js_XMLHttpRequestResponseTypeBlob = "blob"
js_XMLHttpRequestResponseTypeDocument = "document"
js_XMLHttpRequestResponseTypeJson = "json"
js_XMLHttpRequestResponseTypeText = "text"
| ghcjs/jsaddle-dom | src/JSDOM/Generated/Enums.hs | mit | 301,388 | 90 | 73 | 176,582 | 27,599 | 15,057 | 12,542 | 4,649 | 1 |
mple :: Int -> Int -> Int
mple m n
| m < 1 || n < 1 = error "m and n must be >= 1"
| n > m = error "n cannot be > m"
| n == m = 1
| n == 1 = m
| n <= m `div` 2 = m
| otherwise = 2 * m - 2 * n
mplo :: Int -> Int -> Int
mplo m n
| m < 1 || n < 1 = error "m and n must be >= 1"
| n > m = error "n cannot be > m"
| n == m = 1
| n == 1 = m
| n <= (m `div` 2 + 1) = m
| otherwise = m + 1 - n | RAFIRAF/HASKELL | MaxPalindromeLength.hs | mit | 412 | 3 | 11 | 162 | 290 | 134 | 156 | 16 | 1 |
module AccumulateRight where
import Data.Semigroup
import Test.QuickCheck (Arbitrary, arbitrary, oneof)
import Validation
newtype AccumulateRight a b = AccumulateRight (Validation a b) deriving (Eq, Show)
instance Semigroup b => Semigroup (AccumulateRight a b) where
(AccumulateRight (Success x)) <> (AccumulateRight (Success y)) = AccumulateRight (Success (x <> y))
x@(AccumulateRight (Success _)) <> _ = x
_ <> x@(AccumulateRight _) = x
instance (Arbitrary a, Arbitrary b) => Arbitrary (AccumulateRight a b) where
arbitrary = do
a <- arbitrary
b <- arbitrary
oneof $ fmap return [AccumulateRight (Failure a), AccumulateRight (Success b)]
| JoshuaGross/haskell-learning-log | Code/Haskellbook/Semigroups/src/AccumulateRight.hs | mit | 694 | 0 | 13 | 143 | 263 | 136 | 127 | 14 | 0 |
import Diagrams.Backend.CmdLine (mainRender)
import Args
import Demos
import TSSMess
import WarActivity
import Wars
main :: IO ()
main = do
args <- parseArgs
case args of
-- demos first
Demo n o -> mainRender o $ selectDemo (Tutorial n)
ADemo n o -> mainRender o $ selectDemo (Arrow' n)
TDemo n o -> mainRender o $ selectDemo (Trails n)
VDemo n o -> mainRender o $ selectDemo (Vector n)
-- special demos
Arrow o -> mainRender o demoArrow
Tournament o -> mainRender o demoTournament
-- other
TSSMess m o -> doTssMess m (mainRender o)
Wars o -> doWars (mainRender o)
Activity d off o -> doWA d off (mainRender o)
-- default catch
_ -> print args
| mihaimaruseac/petulant-octo-avenger | src-draw/Main.hs | mit | 774 | 0 | 13 | 247 | 276 | 130 | 146 | 20 | 10 |
module Language.LeatherScript.SyntaxDef where
import Control.Arrow
import Control.Applicative
import Control.Lens
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified Data.HashSet as HashSet
import qualified Data.HashMap.Strict as HashMap
import qualified Data.IORef as IORef
import qualified Text.Trifecta
import Language.LeatherScript.Tokenizer as Tokenizer
import Language.LeatherScript.Parser as Parser
data SyntaxDef
= TokenDef Text.Text
| NotationDef Text.Text Text.Text Int Associativity
parseToken :: Text.Trifecta.Parser SyntaxDef
parseToken = TokenDef . Text.pack <$ Text.Trifecta.symbol "Token" <*> Text.Trifecta.stringLiteral
parseNotation :: Text.Trifecta.Parser SyntaxDef
parseNotation = (\x y -> NotationDef (Text.pack x) (Text.pack y)) <$ Text.Trifecta.symbol "Notation" <*> Text.Trifecta.stringLiteral <* Text.Trifecta.symbol ":=" <*> Text.Trifecta.stringLiteral <*> parseLevel <*> parseAssociativity
parseLevel :: Text.Trifecta.Parser Int
parseLevel = fromInteger <$ Text.Trifecta.symbol "level" <*> Text.Trifecta.natural
parseAssociativity :: Text.Trifecta.Parser Associativity
parseAssociativity = (l <|> r <|> no) <* Text.Trifecta.symbol "associativity" where
l = LeftAssoc <$ Text.Trifecta.symbol "left"
r = RightAssoc <$ Text.Trifecta.symbol "right"
no = NoAssoc <$ Text.Trifecta.symbol "no"
parseSyntaxDef :: Text.Trifecta.Parser (Vector.Vector SyntaxDef)
parseSyntaxDef = Vector.fromList <$> many (parseToken <|> parseNotation)
parseText :: FilePath -> TokenDef -> Keywords -> Notations -> Text.Text -> Either ParseError SyntaxTree
parseText filepath tokenDef_ keywords_ notations_ source = do
let tokens = runTokenizer (tokenizeIgnoreSpaces filepath source) tokenDef_
let tokens1 = Vector.map (\(Tokenizer.Token tk _ _ _) -> tk) tokens
let parserState = emptyParserState & keywords .~ keywords_ & notations .~ notations_
runParser (parse tokens1) parserState
mkParserFromFile :: FilePath -> IO (Maybe (TokenDef, Keywords, Notations))
mkParserFromFile path = do
maybeVec <- Text.Trifecta.parseFromFile parseSyntaxDef path
case maybeVec of
Nothing -> return Nothing
Just vec -> do
tokenDef <- IORef.newIORef Vector.empty
syntaxs <- IORef.newIORef (HashSet.empty, HashMap.empty)
Vector.forM_ vec $ \x -> case x of
TokenDef tk -> do
tkDef <- IORef.readIORef tokenDef
IORef.writeIORef tokenDef (Vector.cons tk tkDef)
NotationDef x y level assoc -> do
tkDef <- IORef.readIORef tokenDef
sxDef <- IORef.readIORef syntaxs
let pattern = patternFromVector (Vector.map (\(Tokenizer.Token tk _ _ _) -> tk) (runTokenizer (tokenizeIgnoreSpaces path x) tkDef))
case parseText path tkDef (fst sxDef) (snd sxDef) y of
Left err -> print err
Right replacement -> do
let notation = Notation pattern replacement assoc level
let kws = keywordsInPattern pattern
let kw = if Vector.length kws == 0 then Text.pack "" else Vector.head kws
let newSxDef = (HashSet.union (HashSet.fromList (Vector.toList kws)) (fst sxDef), HashMap.insert kw notation (snd sxDef))
IORef.writeIORef syntaxs newSxDef
tkDef <- IORef.readIORef tokenDef
sxDef <- IORef.readIORef syntaxs
return $ Just (tkDef, fst sxDef, snd sxDef)
| pasberth/LeatherScript-prototype | Language/LeatherScript/SyntaxDef.hs | mit | 3,527 | 0 | 33 | 769 | 1,050 | 535 | 515 | 61 | 5 |
{-# LANGUAGE Safe #-}
module Crypto.Pbkdf2 (pbkdf2, pbkdf2_blocks, pbkdf2_iterative, pbkdf2_iterative_blocks) where
import Data.Bits (shiftR)
import Data.Bits (xor)
import Data.Word (Word8, Word32)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
octetsBE :: Word32 -> [Word8]
octetsBE w =
[ fromIntegral (w `shiftR` 24)
, fromIntegral (w `shiftR` 16)
, fromIntegral (w `shiftR` 8)
, fromIntegral w
]
xorByteStrings x y
| B.length x == B.length y = B.pack $ B.zipWith xor x y
| otherwise = error "xor bytestrings are not of equal length"
pbkdf2_internal createBlocks prf password salt iterations = createBlocks $ first_iteration . hash'
where
hash' = prf password
first_iteration hash = additional_iterations hash hash 1
additional_iterations prev_hash prev_result i
| i == iterations = prev_result
| i > iterations = error "Count must be at least 1"
| otherwise = additional_iterations current_hash result (i + 1)
where
current_hash = (hash' prev_hash)
result = xorByteStrings current_hash prev_result
-- | This is a non standard variation of PBKDF2 which recursively uses the last
-- generated value to improve the salt. In difference to pbkdf2 the salt can
-- not be precalculated for every iteration (with a simple append of 4 bytes),
-- but has to be calculated for every single iteration. This also creates a
-- function where you cannot jump in the stream without calculating everything
-- before it. Compared to the standard this function only changes the salt for
-- the initial PBKDF2 value of each iteration to include a salt iterated from
-- earlier parts of the PBKDF2 stream. This can be verified by removing the
-- blockSalt from (hash $ B.concat [blockSalt, salt, B.pack $ octetsBE c]).
--
-- The added salt for the first iteration will be "", and all following will be
-- calculated as (PRF output input), where output is the output of the previous
-- block and input is the added salt for the previous block. Notice that the
-- output from the previous block is put in the secrets field of the PRF.
pbkdf2_iterative_blocks :: (B.ByteString -> B.ByteString -> B.ByteString)
-- ^ @PRF@, the PRF function to be used for the
-- iterative PBKDF2. The first argument is secret, the
-- second argument is not.
-> B.ByteString -- ^ @Password@, the secret to use in the PBKDF2 computations.
-> B.ByteString -- ^ @Salt@, the not neccesarily secret data to use in the PBKDF2 computations.
-> Integer -- ^ @c@, number of iterations for the the PBKDF2 computations.
-> [B.ByteString] -- ^ @DK@, the output data in the
-- format of an unlimited lazy list of strict
-- ByteStrings, each of which is a block from
-- @PRF@. This can be useful for precalculations of
-- the next block, but by the design of this
-- algorithm it cannot be used to compute blocks in
-- parallel.
pbkdf2_iterative_blocks prf password salt iterations = pbkdf2_internal (createBlocks (B.pack []) 1) prf password salt iterations
where
createBlocks :: B.ByteString -> Word32 -> (B.ByteString -> B.ByteString) -> [B.ByteString]
createBlocks blockSalt i hash = let prev = (hash $ B.concat [blockSalt, salt, B.pack $ octetsBE i])
in prev:(createBlocks (prf prev blockSalt) (i + 1) hash)
-- | This is the same as 'pbkdf2_iterative_blocks', except that it returns a lazy bytestring instead.
pbkdf2_iterative :: (B.ByteString -> B.ByteString -> B.ByteString)
-- ^ @PRF@, the PRF function to be used for the
-- iterative PBKDF2. The first argument is secret, the
-- second argument is not.
-> B.ByteString -- ^ @Password@, the secret to use in the PBKDF2 computations.
-> B.ByteString -- ^ @Salt@, the not neccesarily secret data to use in the PBKDF2 computations.
-> Integer -- ^ @c@, number of iterations for the the PBKDF2 computations.
-> LB.ByteString -- ^ @DK@, the output data in the format of an unlimited lazy ByteString.
pbkdf2_iterative prf password salt iterations = LB.concat $ map LB.fromStrict $ pbkdf2_iterative_blocks prf password salt iterations
-- | This is the standard PBKDF2 algorithm.
pbkdf2_blocks :: (B.ByteString -> B.ByteString -> B.ByteString)
-- ^ @PRF@, the PRF function to be used for PBKDF2. The first
-- argument is secret, the second argument is not.
-> B.ByteString -- ^ @Password@, the secret to use in the PBKDF2 computations.
-> B.ByteString -- ^ @Salt@, the not neccesarily secret data to use in the PBKDF2 computations.
-> Integer -- ^ @c@, number of iterations for the the PBKDF2 computations.
-> [B.ByteString] -- ^ @DK@, the output data in the
-- format of an unlimited lazy list of strict
-- ByteStrings, each of which is a block from
-- @PRF@. These can be calculated in parallel.
pbkdf2_blocks prf password salt iterations = pbkdf2_internal (createBlocks True 1) prf password salt iterations
where
createBlocks :: Bool -> Word32 -> (B.ByteString -> B.ByteString) -> [B.ByteString]
createBlocks False 1 _ = error "Hashing algorithm looped, stopping to maintain security of data" -- Paranoia, but that's useful when doing crypto
createBlocks _ i hash = (hash $ B.concat [salt, B.pack $ octetsBE i]):(createBlocks False (i + 1) hash)
-- | This is the same as 'pbkdf2_blocks', except that it returns a lazy bytestring instead.
pbkdf2 :: (B.ByteString -> B.ByteString -> B.ByteString)
-- ^ @PRF@, the PRF function to be used for PBKDF2. The first
-- argument is secret, the second argument is not.
-> B.ByteString -- ^ @Password@, the secret to use in the PBKDF2 computations.
-> B.ByteString -- ^ @Salt@, the not neccesarily secret data to use in the PBKDF2 computations.
-> Integer -- ^ @c@, number of iterations for the the PBKDF2 computations.
-> LB.ByteString -- ^ @DK@, the output data in the format of an unlimited lazy ByteString.
pbkdf2 prf password salt iterations = LB.concat $ map LB.fromStrict $ pbkdf2_blocks prf password salt iterations
| Ofenhed/LazyPbkdf2 | Crypto/Pbkdf2.hs | mit | 6,563 | 0 | 16 | 1,711 | 948 | 518 | 430 | 55 | 2 |
import Control.Monad (filterM)
import System.Directory (doesFileExist, removeFile)
import System.FilePath (replaceExtension)
import Test.DocTest
import Text.Printf (printf)
numProblems = 99 :: Int
dir = "src"
objectForSource :: String -> String
objectForSource s = replaceExtension s ".o"
removePeskyObjectFiles :: [String] -> IO ()
removePeskyObjectFiles hs = do
let os = map objectForSource hs
existingOs <- filterM doesFileExist os
mapM_ removeFile existingOs
doctestFiles :: IO [String]
doctestFiles = do
let names = [prefix ++ suffix |
i <- [1 .. numProblems],
prefix <- [printf "%s/PE%04d" dir i],
suffix <- [".hs", ".lhs"]
]
peFiles <- filterM doesFileExist names
let libFiles = map ((dir ++ "/") ++) [ "Benchmark.hs"
, "PrimeFactors.hs"
, "Primes.hs"
]
return $ peFiles ++ libFiles
main = do
fs <- doctestFiles
removePeskyObjectFiles fs
doctest $ ["-i" ++ dir] ++ fs
| mvidner/projecteuler | doctests.hs | mit | 1,110 | 2 | 14 | 363 | 342 | 167 | 175 | 29 | 1 |
module Print4 where
myGreeting :: String
myGreeting = "hello" ++ " world!"
hello :: String
hello = "hello"
world :: String
world = "world!"
main :: IO ()
main = do
putStrLn myGreeting
putStrLn secondGreeting
where secondGreeting = concat [hello, " ", world]
| fboyer/haskell-book | chapter3/print4.hs | mit | 268 | 0 | 8 | 53 | 84 | 46 | 38 | 12 | 1 |
import FileTools
import System.FilePath
import qualified Data.ByteString.Lazy.Char8 as B
main = find "/etc" >>= mapM judgeBashFile >>= mapM handleBashFile
judgeBashFile :: FilePath -> IO (String,Bool)
judgeBashFile file = cat file >>= return . (,) file . isBash
where isBash bs = B.take 11 bs == B.pack "#!/bin/bash"
handleBashFile :: (String,Bool) -> IO ()
handleBashFile (file,False) = return ()
handleBashFile (file,True) = cat file >>= B.writeFile dest . chg
where dest = "/home/ueda/hoge/" ++ takeFileName file
chg cs = B.append (B.pack "#!/usr/local/bin/bash\n")
(B.unlines $ drop 1 $ B.lines cs)
| ryuichiueda/UspMagazineHaskell | Study1_Q3/q1_3_8.hs | mit | 652 | 6 | 9 | 137 | 266 | 126 | 140 | 13 | 1 |
data Date = DMY Int Int Int
instance Show Date where
show (DMY d m y) = show d ++ " " ++ show m ++ " " ++ show y
isLeapYear :: Int -> Bool
isLeapYear y = y `mod` 4==0 && (y `mod` 100/=0 || y`mod`400==0)
monthLength :: Int -> Int -> Int
monthLength y m
| m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12 = 31
| m==4 || m==6 || m==9 || m==11 = 30
| m==2 && isLeapYear y = 29
| otherwise = 28
monthLengthDate :: Date -> Int
monthLengthDate (DMY _ m y) = monthLength y m
yearLength y = if isLeapYear y then 366 else 365
nextDay :: Date -> Date
nextDay (DMY d m y) = (DMY d' m' y')
where lastDayMonth = (d == monthLength y m)
lastDayYear = (m == 12 && lastDayMonth)
d' = if lastDayMonth then 1 else d+1
m' = if lastDayYear then 1 else if lastDayMonth then m+1 else m
y' = if lastDayYear then y+1 else y
nextMonth :: Date -> Date
nextMonth (DMY d m y) = (DMY d' m' y')
where lastMonthYear = m == 12
d' = d
m' = if lastMonthYear then 1 else m+1
y' = if lastMonthYear then y+1 else y
genMonthlyDates :: Date -> [Date]
genMonthlyDates today = today : genMonthlyDates (nextMonth today)
datesToMonthLengths :: [Date] -> [Int]
datesToMonthLengths dates = map monthLengthDate dates
shiftDay d l = (d+l) `mod` 7
theDates = takeWhile (\(DMY _ _ y) -> y<=2000) $ genMonthlyDates (DMY 1 1 1901)
theLengths = datesToMonthLengths theDates
startDay = shiftDay 1 $ yearLength 1900
cumulativeLengths = scanl (+) startDay theLengths
daysOfTheWeek = map ((flip mod) 7) cumulativeLengths
nSundays = length $ filter (==0) daysOfTheWeek
| arekfu/project_euler | p0019/p0019.hs | mit | 1,687 | 18 | 20 | 466 | 842 | 404 | 438 | 38 | 5 |
module Latte.FrontEnd.TypeCheck where
import Control.Monad.Except
import Control.Monad.State
import Data.Map
import qualified Data.Map as Map
import Data.Set
import qualified Data.Set as Set
import Latte.Commons
import Latte.Errors
import Latte.Lang.Abs
data FeTcType
= FnType FeTcType [FeTcType]
| VarType Type
deriving (Show, Eq)
data FeTcState = FeTcState {
declared :: Map String FeTcType,
wrongType :: Set (Expr, FeTcType, FeTcType),
currentFunction :: Maybe String
} deriving (Show, Eq)
initialFeTcState :: FeTcState
initialFeTcState = FeTcState {
declared = Map.empty,
wrongType = Set.empty,
currentFunction = Nothing
}
runFeTc :: Program -> ReturnType () FeTcState
runFeTc p = runRunner (feTcProgram p) initialFeTcState
feTcProgram :: Program -> Runner FeTcState ()
feTcProgram (Program []) = return ()
feTcProgram (Program tds) = do
collectFunctionsTypes tds
feTcProgram' tds
where
collectFunctionsTypes :: [TopDef] -> Runner FeTcState ()
collectFunctionsTypes [] = return ()
collectFunctionsTypes (h:t) = do
st <- get
let (name, tp) = fnDefToType h
put $ st { declared = Map.insert name tp $ declared st }
collectFunctionsTypes t
feTcProgram' :: [TopDef] -> Runner FeTcState ()
feTcProgram' [] = return ()
feTcProgram' (h:t) = feTcTopDef h >> feTcProgram' t
feTcTopDef :: TopDef -> Runner FeTcState ()
feTcTopDef (FnDef _ (Ident name) args block) = do
oldState <- get
collectArguments args
put $ oldState { currentFunction = Just name }
feTcBlock block
newState <- get
put $ oldState { wrongType = wrongType newState }
where
collectArguments :: [Arg] -> Runner FeTcState ()
collectArguments [] = return ()
collectArguments ((Arg argType (Ident argName)):t) = do
stArg <- get
put $ stArg { declared = Map.insert argName (VarType argType) $ declared stArg }
collectArguments t
fnDefToType :: TopDef -> (String, FeTcType)
fnDefToType (FnDef t (Ident name) args _) = (name, FnType (VarType t) (Prelude.map (\(Arg a _) -> VarType a) args))
feTcBlock :: Block -> Runner FeTcState ()
feTcBlock (Block []) = return ()
feTcBlock (Block stmts) = do
oldState <- get
feTcStmts stmts
newState <- get
put $ newState { declared = declared oldState }
return ()
feTcStmts :: [Stmt] -> Runner FeTcState ()
feTcStmts [] = return ()
feTcStmts (h:t) = feTcStmt h >> feTcStmts t
feTcStmt :: Stmt -> Runner FeTcState ()
feTcStmt Empty = return ()
feTcStmt (BStmt block) = feTcBlock block
-- decl
-- ass
feTcStmt (Incr name) = feTcStmt (SExp (EVar name))
feTcStmt (Decr name) = feTcStmt (Incr name)
-- ret
-- vret
feTcStmt (Cond expr stmt) = feTcStmt (CondElse expr stmt Empty)
feTcStmt (CondElse expr stmt1 stmt2) = feTcBlock $ Block [SExp expr, BStmt $ Block [stmt1], BStmt $ Block [stmt2]]
feTcStmt (While expr stmt) = feTcStmt (Cond expr stmt)
feTcStmt (SExp expr) = feTcExpr expr >> return ()
feTcStmt _ = throwError $ NotImplementedError "stmt at type check"
feTcExpr :: Expr -> Runner FeTcState FeTcType
feTcExpr (EVar (Ident name)) = do
st <- get
return $ (declared st) ! name
feTcExpr (ELitInt _) = return $ VarType Int
feTcExpr ELitTrue = return $ VarType Bool
feTcExpr ELitFalse = feTcExpr ELitTrue
-- EApp
feTcExpr (EString _) = return $ VarType Str
-- Neg
-- Not
-- EMul
feTcExpr (EAdd e1 _ e2) = feTcExpr (EMul e1 Times e2)
-- ERel
-- EAnd
-- EOr
feTcExpr _ = throwError $ NotImplementedError "expr at type check" | mpsk2/LatteCompiler | src/Latte/FrontEnd/TypeCheck.hs | mit | 3,404 | 116 | 8 | 616 | 667 | 498 | 169 | 88 | 3 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
module Metronome.Types where
import Options.Generic
import qualified Data.Map as M
import Data.Maybe
type SoundMap = M.Map Text Text
type Subdivision = Int
data Options = Options
{ beats :: Maybe Int
, bpm :: Maybe Int
, subdivision :: Maybe Subdivision
} deriving (Generic, Show, Eq)
instance ParseRecord Options
data Config = Config
{ cBeats :: !Int
, cBpm :: !Int
, cSubdivision :: !Subdivision
} deriving (Show, Eq)
data SayEnv = SayEnv
{ saySounds :: SoundMap
, sayWords :: [Text]
, sayConfig :: Config
} deriving (Show, Eq)
defaultConfig :: Config
defaultConfig = Config 4 120 1
fromOpts :: Options -> Config
fromOpts Options{..} =
Config (fromMaybe 4 beats) (fromMaybe 120 bpm) (fromMaybe 1 subdivision)
| 5outh/metronome | lib/Metronome/Types.hs | mit | 886 | 0 | 9 | 180 | 258 | 146 | 112 | 37 | 1 |
module Rebase.Data.HashMap.Lazy
(
module Data.HashMap.Lazy
)
where
import Data.HashMap.Lazy
| nikita-volkov/rebase | library/Rebase/Data/HashMap/Lazy.hs | mit | 95 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
module Y2021.M03.D09.Exercise where
import System.Directory
import System.Environment (getEnv)
{--
Today's #haskell problem: list the contents of a directory and then do
something with each file, like: print the first line of the file.
--}
withDirectoryDo :: FilePath -> (FilePath -> String -> IO ()) -> IO ()
withDirectoryDo dir fileFn = undefined
{-- BONUS -------------------------------------------------------
Add a file-filter into your file-function to work with only Haskell files.
--}
| geophf/1HaskellADay | exercises/HAD/Y2021/M03/D09/Exercise.hs | mit | 498 | 0 | 11 | 72 | 69 | 39 | 30 | 5 | 1 |
module HsToCoq.Util.Functor ((<&>), passThrough, (.<$), (??)) where
import Control.Lens ((<&>), (??))
passThrough :: Functor f => (a -> f b) -> (a -> f a)
passThrough f = \x -> x <$ f x
{-# INLINABLE passThrough #-}
(.<$) :: Functor f => (f a -> c) -> (a -> f b) -> a -> c
f .<$ g = f . passThrough g
infixr 9 .<$
{-# INLINABLE (.<$) #-}
| antalsz/hs-to-coq | src/lib/HsToCoq/Util/Functor.hs | mit | 341 | 0 | 10 | 74 | 171 | 97 | 74 | 7 | 1 |
module Main where
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit (testCase)
import Test.QuickCheck()
import Test.HUnit (Assertion, assertBool)
import Control.Applicative
import Data.Serialize
import qualified Data.AER.Types as AER
import qualified Data.AER.DVS128 as DVS
import qualified Network.AER.UDP as UDP
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.Vector.Storable as S
import Arbitraries()
main :: IO ()
main = defaultMain tests
tests :: [Test]
tests = [ testGroup "DVS tests"
[ testProperty "dvs addr codec" propDvsAddrCodec
, testProperty "dvs codec" propDvsCodec
, testProperty "aer packet codec" propAerPacketCodec
, testCase "dvs aerdat io" testDvsDatIO
, testCase "dvs mmapped io" testDvsDatMMappedIO
{-, testCase "aer over udp" testAEROverUDP-}
]
]
propDvsAddrCodec :: DVS.Address -> Bool
propDvsAddrCodec e = Right e == (decode . encode $ e)
propDvsCodec :: AER.Event DVS.Address -> Bool
propDvsCodec e = Right e == (decode . encode $ e)
testDvsDatIO :: Assertion
testDvsDatIO = do
let sampleFile = "data/DVS128-2014-09-16T15-49-51+0200-20000-0.aedat"
testFile = "data/test-output.aedat"
(Right es) <- DVS.readDVSData sampleFile
-- rewrite the data
DVS.writeDVSData testFile es
{-let t = readTime defaultTimeLocale "%a %b %d %H:%M:%S %Z %Y" "Tue Sep 16 15:49:51 CEST 2014"-}
{-AER.writeAERData' "test-output.aedat" t es-}
-- compare the files
originalData <- dropLinesWhile ((== '#') . B8.head) <$> B.readFile sampleFile
testData <- dropLinesWhile ((== '#') . B8.head) <$> B.readFile testFile
assertBool "aedat filewriting and reading does not work" (originalData == testData)
testDvsDatMMappedIO :: Assertion
testDvsDatMMappedIO = do
let sampleFile = "data/DVS128-2014-09-16T15-49-51+0200-20000-0.aedat"
testFile = "data/test-output.aedat"
es <- DVS.mmapDVSData sampleFile
-- rewrite the data
DVS.writeDVSData testFile (S.toList es)
{-let t = readTime defaultTimeLocale "%a %b %d %H:%M:%S %Z %Y" "Tue Sep 16 15:49:51 CEST 2014"-}
{-AER.writeAERData' "test-output.aedat" t es-}
-- compare the files
originalData <- dropLinesWhile ((== '#') . B8.head) <$> B.readFile sampleFile
testData <- dropLinesWhile ((== '#') . B8.head) <$> B.readFile testFile
assertBool "aedat filewriting and reading does not work" (originalData == testData)
testAEROverUDP :: Assertion
testAEROverUDP = do
let sampleFile = "data/DVS128-2014-09-16T15-49-51+0200-20000-0.aedat"
(Right es) <- DVS.readDVSData sampleFile
-- open server socket
recvEs <- UDP.withAEROverUDP "9999" $ return
-- send events
UDP.sendAEROverUDP "localhost" "9999" [es]
assertBool "aer over udp does not work" (es == recvEs)
dropLinesWhile :: (B.ByteString -> Bool) -> B.ByteString -> B.ByteString
dropLinesWhile f = B8.unlines . dropWhile f . B8.lines
propAerPacketCodec :: AER.Packet DVS.Address -> Bool
propAerPacketCodec p = Right p == (decode . encode $ p)
| fhaust/aer | test/Main.hs | mit | 3,255 | 0 | 12 | 649 | 741 | 399 | 342 | 57 | 1 |
module Fitness where
-- | Conversion helper
toFloat :: Int -> Float
toFloat = fromIntegral . toInteger
fitness :: Float -> Int -> Int -> Float
fitness coverage towersUsed towersCount = coverage * minimal
where
minimal = 1 - (toFloat towersUsed / toFloat towersCount) | NCrashed/radio-problem | scripts/DefaultFitness.hs | mit | 275 | 0 | 10 | 52 | 80 | 43 | 37 | 6 | 1 |
module Backhand.Modules.Reversi where
import Backhand
import Backhand.Message
import Backhand.Unique
import Control.Concurrent.Chan.Unagi.Bounded
import Data.Maybe
import Game.Reversi
data Reversi = Reversi
{ lightPlayer :: LightPlayer
, darkPlayer :: DarkPlayer
, rBoard :: Board
, turn :: Player
}
newReversi :: (LightPlayer, DarkPlayer) -> IO Reversi
newReversi (lp,dp) =
pure Reversi <*> pure lp <*> pure dp <*> pure newBoard <*>
pure Dark
-- startReversiGame :: (c -> Message ReversiMsg) -> OutChan c -> IO ()
-- startReversiGame fn chan =
-- -- Recursive function that blocks until both player slots are filled.
-- fillPlayerSlots
-- fn
-- chan
-- -- Take the players and generate a new game.
-- >>=
-- newReversi
-- -- Now let the games begin.
-- >>=
-- reversiGameLoop chan
fillPlayerSlots :: (c -> Message ReversiMsg)
-> OutChan c
-> IO (LightPlayer, DarkPlayer)
fillPlayerSlots fn chan = tryFillPlayerSlot Nothing Nothing
where
tryFillPlayerSlot :: Maybe LightPlayer
-> Maybe DarkPlayer
-> IO (LightPlayer, DarkPlayer)
-- Once we have both player slots filled we'll exit with those players.
tryFillPlayerSlot (Just l) (Just d) = pure (l, d)
tryFillPlayerSlot ml md = do
rmsg <- readChan chan -- blocks until fufilled
case fn rmsg of
(u,Join Light) ->
case ml of
-- Fill the player slot
-- TODO: Broadcast the new player
Nothing -> tryFillPlayerSlot (Just $ LightPlayer u) md
-- Already exists
-- TODO: Return a warning to the sender
Just _ -> tryFillPlayerSlot ml md
(u,Join Dark) ->
case md of
Nothing -> tryFillPlayerSlot ml (Just $ DarkPlayer u)
Just _ -> tryFillPlayerSlot ml md
-- reversiGameLoop :: OutChan c -> Reversi -> IO ()
-- reversiGameLoop chan game = _
data LightPlayer
= LightPlayer UniqueRequester
data DarkPlayer
= DarkPlayer UniqueRequester
data ReversiMsg
= Join Player
| quietspace/Backhand | modules/reversi/src/Backhand/Modules/Reversi.hs | mit | 2,218 | 0 | 18 | 704 | 430 | 233 | 197 | 41 | 5 |
-------------------------------------------------------------------------------
-- |
-- Module : System.Hardware.Arduino.SamplePrograms.Morse
-- Copyright : (c) Antoine R. Dumont, Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Morse code blinker. Original by Antoine R. Dumont, modified to simplify
-- and fit into the existing examples structure.
-------------------------------------------------------------------------------
module System.Hardware.Arduino.SamplePrograms.Morse where
import Control.Monad (forever)
import Control.Monad.Trans (liftIO)
import Data.Char (toUpper)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
import System.Hardware.Arduino
-- | A dit or a dah is all we need for Morse:
-- A @dit@ is a dot; and a @dah@ is a dash in the Morsian world.
-- We use 'LBreak' and 'WBreak' to indicate a letter and a word break
-- so we can insert some delay between letters and words as we
-- transmit.
data Morse = Dit | Dah | LBreak | WBreak
deriving Show
-- | Morse code dictionary
dict :: [(Char, [Morse])]
dict = map encode m
where encode (k, s) = (k, map (\c -> if c == '.' then Dit else Dah) s)
m = [ ('A', ".-" ), ('B', "-..." ), ('C', "-.-." ), ('D', "-.." ), ('E', "." )
, ('F', "..-." ), ('G', "--." ), ('H', "...." ), ('I', ".." ), ('J', ".---" )
, ('K', "-.-" ), ('L', ".-.." ), ('M', "--" ), ('N', "-." ), ('O', "---" )
, ('P', ".--." ), ('Q', "--.-" ), ('R', ".-." ), ('S', "..." ), ('T', "-" )
, ('U', "..-" ), ('V', "...-" ), ('W', ".--" ), ('X', "-..-" ), ('Y', "-.--" )
, ('Z', "--.." ), ('0', "-----"), ('1', ".----"), ('2', "..---"), ('3', "...--")
, ('4', "....-"), ('5', "....."), ('6', "-...."), ('7', "--..."), ('8', "---..")
, ('9', "----."), ('+', ".-.-."), ('/', "-..-."), ('=', "-...-")
]
-- | Given a sentence, decode it. We simply drop any letters that we
-- do not have a mapping for.
decode :: String -> [Morse]
decode = intercalate [WBreak] . map (intercalate [LBreak] . map cvt) . words
where cvt c = fromMaybe [] $ toUpper c `lookup` dict
-- | Given a morsified sentence, compute the delay times. A 'Left' value means
-- turn the led on that long, a 'Right' value means turn it off that long.
morsify :: [Morse] -> [Either Int Int]
morsify = map t
where unit = 300
t Dit = Left $ 1 * unit
t Dah = Left $ 3 * unit
t LBreak = Right $ 3 * unit
t WBreak = Right $ 7 * unit
-- | Finally, turn a full sentence into a sequence of blink on/off codes
transmit :: Pin -> String -> Arduino ()
transmit p = sequence_ . concatMap code . morsify . decode
where code (Left i) = [digitalWrite p True, delay i, digitalWrite p False, delay i]
code (Right i) = [digitalWrite p False, delay i]
-- | A simple demo driver. To run this example, you only need the Arduino connected to your
-- computer, no other hardware is needed. We use the internal led on pin 13. Of course,
-- you can attach a led to pin 13 as well, for artistic effect.
--
-- <<http://github.com/LeventErkok/hArduino/raw/master/System/Hardware/Arduino/SamplePrograms/Schematics/Blink.png>>
morseDemo :: IO ()
morseDemo = withArduino False "/dev/cu.usbmodemfd131" $ do
setPinMode led OUTPUT
forever send
where led = digital 13
send = do liftIO $ putStr "Message? "
m <- liftIO getLine
transmit led m
| aufheben/lambda-arduino | packages/hArduino-0.9/System/Hardware/Arduino/SamplePrograms/Morse.hs | mit | 3,600 | 0 | 12 | 899 | 913 | 544 | 369 | 42 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module GitMail.App where
import qualified Data.ByteString as BS
import qualified Database.Redis as R
import Network.Wai
import Servant
import Servant.HTML.Blaze
import Text.Blaze.Html
import GitMail.Csrf as C
import GitMail.Handlers
import GitMail.Html
import GitMail.Types
type API = "github_oauth"
:> QueryParam "state" String
:> QueryParam "code" String
:> Get '[HTML] Html
:<|> "github_start"
:> Get '[HTML] Html
api :: Proxy API
api = Proxy
server :: App (Server API)
server c s = githubOAuth c s
:<|> githubStart c s
app :: App Application
app c s = serve api $ server c s
newAppState :: IO AppState
newAppState = do
conn <- R.connect R.defaultConnectInfo
return AppState { stateRedisConn = conn
}
| ShivanKaul/gitmail | github/src/GitMail/App.hs | mit | 997 | 0 | 12 | 294 | 246 | 134 | 112 | 32 | 1 |
module Main where
import Lib
import Control.Exception(catch)
import System.Environment(getProgName)
import System.IO.Error(isUserError)
main :: IO ()
main = ui `catch` handler
handler :: IOError -> IO ()
handler e
| isUserError e = do
progName <- getProgName
putStrLn ("Usage: " ++ progName ++ " 180")
| otherwise = ioError e
| dimus/zones | app/Main.hs | mit | 365 | 0 | 11 | 88 | 126 | 66 | 60 | 13 | 1 |
{-# LANGUAGE FlexibleInstances, UndecidableInstances, OverloadedStrings, TypeFamilies, RankNTypes, DeriveDataTypeable, StandaloneDeriving, FlexibleContexts, TypeSynonymInstances, ScopedTypeVariables, GADTs, GeneralizedNewtypeDeriving, BangPatterns, DeriveGeneric #-}
-----------------------------------------------------------------------------
{- |
Module : Language.Javascript.JMacro.Base
Copyright : (c) Gershom Bazerman, 2009
License : BSD 3 Clause
Maintainer : gershomb@gmail.com
Stability : experimental
Simple DSL for lightweight (untyped) programmatic generation of Javascript.
-}
-----------------------------------------------------------------------------
module Compiler.JMacro.Base (
-- * ADT
JStat(..), JExpr(..), JVal(..), JOp(..), JUOp(..),
Ident(..), IdentSupply(..), JsLabel,
-- * Generic traversal (via compos)
JMacro(..), JMGadt(..), Compos(..),
composOp, composOpM, composOpM_, composOpFold,
-- * Hygienic transformation
withHygiene, scopify,
-- * Display/Output
renderJs, renderJs',
renderPrefixJs, renderPrefixJs',
JsToDoc(..), defaultRenderJs, RenderJs(..), jsToDoc,
-- * Ad-hoc data marshalling
ToJExpr(..),
-- * Literals
jsv,
-- * Occasionally helpful combinators
jLam, jVar, jVarTy, jFor, jForIn, jForEachIn, jTryCatchFinally,
expr2stat, ToStat(..), nullStat,
-- * Hash combinators
jhEmpty, jhSingle, jhAdd, jhFromList,
-- * Utility
jsSaturate, SaneDouble(..)
) where
import Prelude hiding (tail, init, head, last, minimum, maximum, foldr1, foldl1, (!!), read)
import Control.Arrow (second, (***))
import Control.DeepSeq
import Control.Monad.State.Strict
import Control.Monad.Identity
import Data.Function
import Data.Bits ((.&.), shiftR)
import Data.Binary (Binary)
import Data.Char (toLower, isControl, ord)
import qualified Data.Map as M
import qualified Data.Text.Lazy as TL
import Data.Text (Text)
import qualified Data.Text as T
import Data.Data
import Data.Hashable (Hashable)
import Data.Text.Binary ()
import GHC.Generics
import Numeric(showHex)
import Safe
import Data.Aeson
import qualified Data.Vector as V
import qualified Data.HashMap.Strict as HM
import Text.PrettyPrint.Leijen.Text hiding ((<$>))
import qualified Text.PrettyPrint.Leijen.Text as PP
-- wl-pprint-text compatibility with pretty
infixl 5 $$, $+$
($+$), ($$), ($$$) :: Doc -> Doc -> Doc
x $+$ y = x PP.<$> y
x $$ y = align (x $+$ y)
x $$$ y = align (nest 2 $ x $+$ y)
{--------------------------------------------------------------------
ADTs
--------------------------------------------------------------------}
newtype IdentSupply a = IS {runIdentSupply :: State [Ident] a} deriving Typeable
instance NFData (IdentSupply a) where rnf (IS{}) = ()
inIdentSupply :: (State [Ident] a -> State [Ident] b) -> IdentSupply a -> IdentSupply b
inIdentSupply f x = IS $ f (runIdentSupply x)
instance Data a => Data (IdentSupply a) where
gunfold _ _ _ = error "gunfold IdentSupply"
toConstr _ = error "toConstr IdentSupply"
dataTypeOf _ = mkNoRepType "IdentSupply"
instance Functor IdentSupply where
fmap f x = inIdentSupply (fmap f) x
takeOne :: State [Ident] Ident
takeOne = do
(x:xs) <- get
put xs
return x
newIdentSupply :: Maybe Text -> [Ident]
newIdentSupply Nothing = newIdentSupply (Just "jmId")
newIdentSupply (Just pfx') = [TxtI (pfx `mappend` T.pack (show x)) | x <- [(0::Integer)..]]
where pfx = pfx' `mappend` "_"
sat_ :: IdentSupply a -> a
sat_ x = evalState (runIdentSupply x) $ newIdentSupply (Just "<<unsatId>>")
instance Eq a => Eq (IdentSupply a) where
(==) = (==) `on` sat_
instance Ord a => Ord (IdentSupply a) where
compare = compare `on` sat_
instance Show a => Show (IdentSupply a) where
show x = "(" ++ show (sat_ x) ++ ")"
-- array comprehensions/generators?
-- | Statements
data JStat = DeclStat Ident
| ReturnStat JExpr
| IfStat JExpr JStat JStat
| WhileStat Bool JExpr JStat -- bool is "do"
| ForInStat Bool Ident JExpr JStat -- bool is "each"
| SwitchStat JExpr [(JExpr, JStat)] JStat
| TryStat JStat Ident JStat JStat
| BlockStat [JStat]
| ApplStat JExpr [JExpr]
| UOpStat JUOp JExpr
| AssignStat JExpr JExpr
| UnsatBlock (IdentSupply JStat)
| AntiStat Text
| LabelStat JsLabel JStat
| BreakStat (Maybe JsLabel)
| ContinueStat (Maybe JsLabel)
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData JStat
type JsLabel = Text
instance Monoid JStat where
mempty = BlockStat []
mappend (BlockStat xs) (BlockStat ys) = BlockStat $ xs ++ ys
mappend (BlockStat xs) ys = BlockStat $ xs ++ [ys]
mappend xs (BlockStat ys) = BlockStat $ xs : ys
mappend xs ys = BlockStat [xs,ys]
-- TODO: annotate expressions with type
-- | Expressions
data JExpr = ValExpr JVal
| SelExpr JExpr Ident
| IdxExpr JExpr JExpr
| InfixExpr JOp JExpr JExpr
| UOpExpr JUOp JExpr
| IfExpr JExpr JExpr JExpr
| ApplExpr JExpr [JExpr]
| UnsatExpr (IdentSupply JExpr)
| AntiExpr Text
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData JExpr
-- | Values
data JVal = JVar Ident
| JList [JExpr]
| JDouble SaneDouble
| JInt Integer
| JStr Text
| JRegEx Text
| JHash (M.Map Text JExpr)
| JFunc [Ident] JStat
| UnsatVal (IdentSupply JVal)
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData JVal
data JOp =
EqOp -- ==
| StrictEqOp -- ===
| NeqOp -- !=
| StrictNeqOp -- !==
| GtOp -- >
| GeOp -- >=
| LtOp -- <
| LeOp -- <=
| AddOp -- +
| SubOp -- -
| MulOp -- "*"
| DivOp -- /
| ModOp -- %
| LeftShiftOp -- <<
| RightShiftOp -- >>
| ZRightShiftOp -- >>>
| BAndOp -- &
| BOrOp -- |
| BXorOp -- ^
| LAndOp -- &&
| LOrOp -- ||
| InstanceofOp -- instanceof
| InOp -- in
deriving (Show, Eq, Ord, Enum, Data, Typeable, Generic)
instance NFData JOp
opText :: JOp -> TL.Text
opText EqOp = "=="
opText StrictEqOp = "==="
opText NeqOp = "!="
opText StrictNeqOp = "!=="
opText GtOp = ">"
opText GeOp = ">="
opText LtOp = "<"
opText LeOp = "<="
opText AddOp = "+"
opText SubOp = "-"
opText MulOp = "*"
opText DivOp = "/"
opText ModOp = "%"
opText LeftShiftOp = "<<"
opText RightShiftOp = ">>"
opText ZRightShiftOp = ">>>"
opText BAndOp = "&"
opText BOrOp = "|"
opText BXorOp = "^"
opText LAndOp = "&&"
opText LOrOp = "||"
opText InstanceofOp = "instanceof"
opText InOp = "in"
data JUOp =
NotOp -- !
| BNotOp -- ~
| NegOp -- -
| PlusOp -- +x
| NewOp -- new x
| TypeofOp -- typeof x
| DeleteOp -- delete x
| YieldOp -- yield x
| VoidOp -- void x
| PreInc -- ++x
| PostInc -- x++
| PreDec -- --x
| PostDec -- x--
deriving (Show, Eq, Ord, Enum, Data, Typeable, Generic)
instance NFData JUOp
isPre :: JUOp -> Bool
isPre PostInc = False
isPre PostDec = False
isPre _ = True
isAlphaOp :: JUOp -> Bool
isAlphaOp NewOp = True
isAlphaOp TypeofOp = True
isAlphaOp DeleteOp = True
isAlphaOp YieldOp = True
isAlphaOp VoidOp = True
isAlphaOp _ = False
uOpText :: JUOp -> TL.Text
uOpText NotOp = "!"
uOpText BNotOp = "~"
uOpText NegOp = "-"
uOpText PlusOp = "+"
uOpText NewOp = "new"
uOpText TypeofOp = "typeof"
uOpText DeleteOp = "delete"
uOpText YieldOp = "yield"
uOpText VoidOp = "void"
uOpText PreInc = "++"
uOpText PostInc = "++"
uOpText PreDec = "--"
uOpText PostDec = "--"
newtype SaneDouble = SaneDouble { unSaneDouble :: Double }
deriving (Data, Typeable, Fractional, Num, Generic, NFData)
instance Eq SaneDouble where
(SaneDouble x) == (SaneDouble y) = x == y || (isNaN x && isNaN y)
instance Ord SaneDouble where
compare (SaneDouble x) (SaneDouble y) = compare (fromNaN x) (fromNaN y)
where fromNaN z | isNaN z = Nothing
| otherwise = Just z
instance Show SaneDouble where
show (SaneDouble x) = show x
-- | Identifiers
newtype Ident = TxtI Text
deriving (Show, Data, Typeable, Hashable, Eq, Ord, Binary, Generic, NFData)
expr2stat :: JExpr -> JStat
expr2stat (ApplExpr x y) = (ApplStat x y)
expr2stat (IfExpr x y z) = IfStat x (expr2stat y) (expr2stat z)
expr2stat (UOpExpr o x) = UOpStat o x
expr2stat (AntiExpr x) = AntiStat x
expr2stat _ = nullStat
{--------------------------------------------------------------------
Compos
--------------------------------------------------------------------}
-- | Compos and ops for generic traversal as defined over
-- the JMacro ADT.
-- | Utility class to coerce the ADT into a regular structure.
class JMacro a where
jtoGADT :: a -> JMGadt a
jfromGADT :: JMGadt a -> a
instance JMacro Ident where
jtoGADT = JMGId
jfromGADT (JMGId x) = x
jfromGADT _ = error "impossible"
instance JMacro JStat where
jtoGADT = JMGStat
jfromGADT (JMGStat x) = x
jfromGADT _ = error "impossible"
instance JMacro JExpr where
jtoGADT = JMGExpr
jfromGADT (JMGExpr x) = x
jfromGADT _ = error "impossible"
instance JMacro JVal where
jtoGADT = JMGVal
jfromGADT (JMGVal x) = x
jfromGADT _ = error "impossible"
-- | Union type to allow regular traversal by compos.
data JMGadt a where
JMGId :: Ident -> JMGadt Ident
JMGStat :: JStat -> JMGadt JStat
JMGExpr :: JExpr -> JMGadt JExpr
JMGVal :: JVal -> JMGadt JVal
composOp :: Compos t => (forall a. t a -> t a) -> t b -> t b
composOp f = runIdentity . composOpM (Identity . f)
composOpM :: (Compos t, Monad m) => (forall a. t a -> m (t a)) -> t b -> m (t b)
composOpM = compos return ap
composOpM_ :: (Compos t, Monad m) => (forall a. t a -> m ()) -> t b -> m ()
composOpM_ = composOpFold (return ()) (>>)
composOpFold :: Compos t => b -> (b -> b -> b) -> (forall a. t a -> b) -> t c -> b
composOpFold z c f = unC . compos (\_ -> C z) (\(C x) (C y) -> C (c x y)) (C . f)
newtype C b a = C { unC :: b }
class Compos t where
compos :: (forall a. a -> m a) -> (forall a b. m (a -> b) -> m a -> m b)
-> (forall a. t a -> m (t a)) -> t c -> m (t c)
instance Compos JMGadt where
compos = jmcompos
jmcompos :: forall m c. (forall a. a -> m a) -> (forall a b. m (a -> b) -> m a -> m b) -> (forall a. JMGadt a -> m (JMGadt a)) -> JMGadt c -> m (JMGadt c)
jmcompos ret app f' v =
case v of
JMGId _ -> ret v
JMGStat v' -> ret JMGStat `app` case v' of
DeclStat i -> ret DeclStat `app` f i
ReturnStat i -> ret ReturnStat `app` f i
IfStat e s s' -> ret IfStat `app` f e `app` f s `app` f s'
WhileStat b e s -> ret (WhileStat b) `app` f e `app` f s
ForInStat b i e s -> ret (ForInStat b) `app` f i `app` f e `app` f s
SwitchStat e l d -> ret SwitchStat `app` f e `app` l' `app` f d
where l' = mapM' (\(c,s) -> ret (,) `app` f c `app` f s) l
BlockStat xs -> ret BlockStat `app` mapM' f xs
ApplStat e xs -> ret ApplStat `app` f e `app` mapM' f xs
TryStat s i s1 s2 -> ret TryStat `app` f s `app` f i `app` f s1 `app` f s2
UOpStat o e -> ret (UOpStat o) `app` f e
AssignStat e e' -> ret AssignStat `app` f e `app` f e'
UnsatBlock _ -> ret v'
AntiStat _ -> ret v'
ContinueStat l -> ret (ContinueStat l)
BreakStat l -> ret (BreakStat l)
LabelStat l s -> ret (LabelStat l) `app` f s
JMGExpr v' -> ret JMGExpr `app` case v' of
ValExpr e -> ret ValExpr `app` f e
SelExpr e e' -> ret SelExpr `app` f e `app` f e'
IdxExpr e e' -> ret IdxExpr `app` f e `app` f e'
InfixExpr o e e' -> ret (InfixExpr o) `app` f e `app` f e'
UOpExpr o e -> ret (UOpExpr o) `app` f e
IfExpr e e' e'' -> ret IfExpr `app` f e `app` f e' `app` f e''
ApplExpr e xs -> ret ApplExpr `app` f e `app` mapM' f xs
UnsatExpr _ -> ret v'
AntiExpr _ -> ret v'
JMGVal v' -> ret JMGVal `app` case v' of
JVar i -> ret JVar `app` f i
JList xs -> ret JList `app` mapM' f xs
JDouble _ -> ret v'
JInt _ -> ret v'
JStr _ -> ret v'
JRegEx _ -> ret v'
JHash m -> ret JHash `app` m'
where (ls, vs) = unzip (M.toList m)
m' = ret (M.fromAscList . zip ls) `app` mapM' f vs
JFunc xs s -> ret JFunc `app` mapM' f xs `app` f s
UnsatVal _ -> ret v'
where
mapM' :: forall a. (a -> m a) -> [a] -> m [a]
mapM' g = foldr (app . app (ret (:)) . g) (ret [])
f :: forall b. JMacro b => b -> m b
f x = ret jfromGADT `app` f' (jtoGADT x)
{--------------------------------------------------------------------
New Identifiers
--------------------------------------------------------------------}
class ToSat a where
toSat_ :: a -> [Ident] -> IdentSupply (JStat, [Ident])
instance ToSat [JStat] where
toSat_ f vs = IS $ return $ (BlockStat f, reverse vs)
instance ToSat JStat where
toSat_ f vs = IS $ return $ (f, reverse vs)
instance ToSat JExpr where
toSat_ f vs = IS $ return $ (expr2stat f, reverse vs)
instance ToSat [JExpr] where
toSat_ f vs = IS $ return $ (BlockStat $ map expr2stat f, reverse vs)
instance (ToSat a, b ~ JExpr) => ToSat (b -> a) where
toSat_ f vs = IS $ do
x <- takeOne
runIdentSupply $ toSat_ (f (ValExpr $ JVar x)) (x:vs)
{-
splitIdentSupply :: ([Ident] -> ([Ident], [Ident]))
splitIdentSupply is = (takeAlt is, takeAlt (drop 1 is))
where takeAlt (x:_:xs) = x : takeAlt xs
takeAlt _ = error "splitIdentSupply: stream is not infinite"
-}
{--------------------------------------------------------------------
Saturation
--------------------------------------------------------------------}
-- | Given an optional prefix, fills in all free variable names with a supply
-- of names generated by the prefix.
jsSaturate :: (JMacro a) => Maybe Text -> a -> a
jsSaturate str x = evalState (runIdentSupply $ jsSaturate_ x) (newIdentSupply str)
jsSaturate_ :: (JMacro a) => a -> IdentSupply a
jsSaturate_ e = IS $ jfromGADT <$> go (jtoGADT e)
where
go :: forall a. JMGadt a -> State [Ident] (JMGadt a)
go v = case v of
JMGStat (UnsatBlock us) -> go =<< (JMGStat <$> runIdentSupply us)
JMGExpr (UnsatExpr us) -> go =<< (JMGExpr <$> runIdentSupply us)
JMGVal (UnsatVal us) -> go =<< (JMGVal <$> runIdentSupply us)
_ -> composOpM go v
{--------------------------------------------------------------------
Transformation
--------------------------------------------------------------------}
-- doesn't apply to unsaturated bits
jsReplace_ :: JMacro a => [(Ident, Ident)] -> a -> a
jsReplace_ xs e = jfromGADT $ go (jtoGADT e)
where
go :: forall a. JMGadt a -> JMGadt a
go v = case v of
JMGId i -> maybe v JMGId (M.lookup i mp)
_ -> composOp go v
mp = M.fromList xs
-- only works on fully saturated things
jsUnsat_ :: JMacro a => [Ident] -> a -> IdentSupply a
jsUnsat_ xs e = IS $ do
(idents,is') <- splitAt (length xs) <$> get
put is'
return $ jsReplace_ (zip xs idents) e
-- | Apply a transformation to a fully saturated syntax tree,
-- taking care to return any free variables back to their free state
-- following the transformation. As the transformation preserves
-- free variables, it is hygienic.
withHygiene :: JMacro a => (a -> a) -> a -> a
withHygiene f x = jfromGADT $ case jtoGADT x of
JMGExpr z -> JMGExpr $ UnsatExpr $ inScope z
JMGStat z -> JMGStat $ UnsatBlock $ inScope z
JMGVal z -> JMGVal $ UnsatVal $ inScope z
JMGId _ -> jtoGADT $ f x
where
inScope z = IS $ do
([TxtI a], b) <- splitAt 1 `fmap` get
put b
return $ withHygiene_ a f z
withHygiene_ :: JMacro a => Text -> (a -> a) -> a -> a
withHygiene_ un f x = jfromGADT $ case jtoGADT x of
JMGStat _ -> jtoGADT $ UnsatBlock (jsUnsat_ is' x'')
JMGExpr _ -> jtoGADT $ UnsatExpr (jsUnsat_ is' x'')
JMGVal _ -> jtoGADT $ UnsatVal (jsUnsat_ is' x'')
JMGId _ -> jtoGADT $ f x
where
(x', (TxtI l : _)) = runState (runIdentSupply $ jsSaturate_ x) is
is' = take lastVal is
x'' = f x'
lastVal = readNote ("inSat" ++ T.unpack un) (reverse . takeWhile (/= '_') . reverse $ T.unpack l) :: Int
is = newIdentSupply $ Just ("inSat" `mappend` un)
-- | Takes a fully saturated expression and transforms it to use unique variables that respect scope.
scopify :: JStat -> JStat
scopify x = evalState (jfromGADT <$> go (jtoGADT x)) (newIdentSupply Nothing)
where go :: forall a. JMGadt a -> State [Ident] (JMGadt a)
go v = case v of
(JMGStat (BlockStat ss)) -> JMGStat . BlockStat <$>
blocks ss
where blocks [] = return []
blocks (DeclStat (TxtI i) : xs)
| "!!" `T.isPrefixOf` i = (DeclStat (TxtI (T.drop 2 i)):) <$> blocks xs
| "!" `T.isPrefixOf` i = (DeclStat (TxtI $ T.tail i):) <$> blocks xs
| otherwise = do
(newI:st) <- get
put st
rest <- blocks xs
return $ [DeclStat newI `mappend` jsReplace_ [(TxtI i, newI)] (BlockStat rest)]
blocks (x':xs) = (jfromGADT <$> go (jtoGADT x')) <:> blocks xs
(<:>) = liftM2 (:)
(JMGStat (TryStat s (TxtI i) s1 s2)) -> do
(newI:st) <- get
put st
t <- jfromGADT <$> go (jtoGADT s)
c <- jfromGADT <$> go (jtoGADT s1)
f <- jfromGADT <$> go (jtoGADT s2)
return . JMGStat . TryStat t newI (jsReplace_ [(TxtI i, newI)] c) $ f
(JMGExpr (ValExpr (JFunc is s))) -> do
st <- get
let (newIs,newSt) = splitAt (length is) st
put (newSt)
rest <- jfromGADT <$> go (jtoGADT s)
return . JMGExpr . ValExpr $ JFunc newIs $ (jsReplace_ $ zip is newIs) rest
_ -> composOpM go v
{--------------------------------------------------------------------
Pretty Printing
--------------------------------------------------------------------}
-- | Render a syntax tree as a pretty-printable document
-- (simply showing the resultant doc produces a nice,
-- well formatted String).
renderJs :: (JsToDoc a, JMacro a) => a -> Doc
renderJs = renderJs' defaultRenderJs
renderJs' :: (JsToDoc a, JMacro a) => RenderJs -> a -> Doc
renderJs' r = jsToDocR r . jsSaturate Nothing
data RenderJs = RenderJs { renderJsS :: RenderJs -> JStat -> Doc
, renderJsE :: RenderJs -> JExpr -> Doc
, renderJsV :: RenderJs -> JVal -> Doc
, renderJsI :: RenderJs -> Ident -> Doc
}
defaultRenderJs :: RenderJs
defaultRenderJs = RenderJs defRenderJsS defRenderJsE defRenderJsV defRenderJsI
jsToDoc :: JsToDoc a => a -> Doc
jsToDoc = jsToDocR defaultRenderJs
-- | Render a syntax tree as a pretty-printable document, using a given prefix to all generated names. Use this with distinct prefixes to ensure distinct generated names between independent calls to render(Prefix)Js.
renderPrefixJs :: (JsToDoc a, JMacro a) => Text -> a -> Doc
renderPrefixJs pfx = renderPrefixJs' defaultRenderJs pfx
renderPrefixJs' :: (JsToDoc a, JMacro a) => RenderJs -> Text -> a -> Doc
renderPrefixJs' r pfx = jsToDocR r . jsSaturate (Just $ "jmId_" `mappend` pfx)
braceNest :: Doc -> Doc
braceNest x = char '{' <+> nest 2 x $$ char '}'
braceNest' :: Doc -> Doc
braceNest' x = nest 2 (char '{' $+$ x) $$ char '}'
class JsToDoc a where jsToDocR :: RenderJs -> a -> Doc
instance JsToDoc JStat where jsToDocR r = renderJsS r r
instance JsToDoc JExpr where jsToDocR r = renderJsE r r
instance JsToDoc JVal where jsToDocR r = renderJsV r r
instance JsToDoc Ident where jsToDocR r = renderJsI r r
instance JsToDoc [JExpr] where
jsToDocR r = vcat . map ((<> semi) . jsToDocR r)
instance JsToDoc [JStat] where
jsToDocR r = vcat . map ((<> semi) . jsToDocR r)
defRenderJsS :: RenderJs -> JStat -> Doc
defRenderJsS r (IfStat cond x y) = text "if" <> parens (jsToDocR r cond) $$ braceNest' (jsToDocR r x) $$ mbElse
where mbElse | y == BlockStat [] = PP.empty
| otherwise = text "else" $$ braceNest' (jsToDocR r y)
defRenderJsS r (DeclStat x) = text "var" <+> jsToDocR r x
defRenderJsS r (WhileStat False p b) = text "while" <> parens (jsToDocR r p) $$ braceNest' (jsToDocR r b)
defRenderJsS r (WhileStat True p b) = (text "do" $$ braceNest' (jsToDocR r b)) $+$ text "while" <+> parens (jsToDocR r p)
defRenderJsS r (UnsatBlock e) = jsToDocR r $ sat_ e
defRenderJsS _ (BreakStat l) = maybe (text "break") (((<+>) `on` text) "break" . TL.fromStrict) l
defRenderJsS _ (ContinueStat l) = maybe (text "continue") (((<+>) `on` text) "continue" . TL.fromStrict) l
defRenderJsS r (LabelStat l s) = text (TL.fromStrict l) <> char ':' $$ printBS s
where
printBS (BlockStat ss) = vcat $ interSemi $ flattenBlocks ss
printBS x = jsToDocR r x
interSemi [x] = [jsToDocR r x]
interSemi [] = []
interSemi (x:xs) = (jsToDocR r x <> semi) : interSemi xs
defRenderJsS r (ForInStat each i e b) = text txt <> parens (jsToDocR r i <+> text "in" <+> jsToDocR r e) $$ braceNest' (jsToDocR r b)
where txt | each = "for each"
| otherwise = "for"
defRenderJsS r (SwitchStat e l d) = text "switch" <+> parens (jsToDocR r e) $$ braceNest' cases
where l' = map (\(c,s) -> (text "case" <+> parens (jsToDocR r c) <> char ':') $$$ (jsToDocR r s)) l ++ [text "default:" $$$ (jsToDocR r d)]
cases = vcat l'
defRenderJsS r (ReturnStat e) = text "return" <+> jsToDocR r e
defRenderJsS r (ApplStat e es) = jsToDocR r e <> (parens . fillSep . punctuate comma $ map (jsToDocR r) es)
defRenderJsS r (TryStat s i s1 s2) = text "try" $$ braceNest' (jsToDocR r s) $$ mbCatch $$ mbFinally
where mbCatch | s1 == BlockStat [] = PP.empty
| otherwise = text "catch" <> parens (jsToDocR r i) $$ braceNest' (jsToDocR r s1)
mbFinally | s2 == BlockStat [] = PP.empty
| otherwise = text "finally" $$ braceNest' (jsToDocR r s2)
defRenderJsS r (AssignStat i x) = jsToDocR r i <+> char '=' <+> jsToDocR r x
defRenderJsS r (UOpStat op x)
| isPre op && isAlphaOp op = text (uOpText op) <+> optParens r x
| isPre op = text (uOpText op) <> optParens r x
| otherwise = optParens r x <> text (uOpText op)
defRenderJsS _ (AntiStat{}) = error "defRenderJsS: AntiStat"
defRenderJsS r (BlockStat xs) = jsToDocR r (flattenBlocks xs)
flattenBlocks :: [JStat] -> [JStat]
flattenBlocks (BlockStat y:ys) = flattenBlocks y ++ flattenBlocks ys
flattenBlocks (y:ys) = y : flattenBlocks ys
flattenBlocks [] = []
optParens :: RenderJs -> JExpr -> Doc
optParens r x = case x of
(UOpExpr _ _) -> parens (jsToDocR r x)
_ -> jsToDocR r x
defRenderJsE :: RenderJs -> JExpr -> Doc
defRenderJsE r (ValExpr x) = jsToDocR r x
defRenderJsE r (SelExpr x y) = cat [jsToDocR r x <> char '.', jsToDocR r y]
defRenderJsE r (IdxExpr x y) = jsToDocR r x <> brackets (jsToDocR r y)
defRenderJsE r (IfExpr x y z) = parens (jsToDocR r x <+> char '?' <+> jsToDocR r y <+> char ':' <+> jsToDocR r z)
defRenderJsE r (InfixExpr op x y) = parens $ hsep [jsToDocR r x, text (opText op), jsToDocR r y]
defRenderJsE r (UOpExpr op x)
| isPre op && isAlphaOp op = text (uOpText op) <+> optParens r x
| isPre op = text (uOpText op) <> optParens r x
| otherwise = optParens r x <> text (uOpText op)
defRenderJsE r (ApplExpr je xs) = jsToDocR r je <> (parens . fillSep . punctuate comma $ map (jsToDocR r) xs)
defRenderJsE _ (AntiExpr{}) = error "defRenderJsE: AntiExpr" -- text . TL.fromChunks $ ["`(", s, ")`"]
defRenderJsE r (UnsatExpr e) = jsToDocR r $ sat_ e
defRenderJsV :: RenderJs -> JVal -> Doc
defRenderJsV r (JVar i) = jsToDocR r i
defRenderJsV r (JList xs) = brackets . fillSep . punctuate comma $ map (jsToDocR r) xs
defRenderJsV _ (JDouble (SaneDouble d))
| d < 0 || isNegativeZero d = parens (double d)
| otherwise = double d
defRenderJsV _ (JInt i) | i < 0 = parens (integer i)
| otherwise = integer i
defRenderJsV _ (JStr s) = text . TL.fromChunks $ ["\"",encodeJson s,"\""]
defRenderJsV _ (JRegEx s) = text . TL.fromChunks $ ["/",s,"/"]
defRenderJsV r (JHash m)
| M.null m = text "{}"
| otherwise = braceNest . fillSep . punctuate comma .
map (\(x,y) -> squotes (text (TL.fromStrict x)) <> colon <+> jsToDocR r y) $ M.toList m
defRenderJsV r (JFunc is b) = parens $ text "function" <> parens (fillSep . punctuate comma . map (jsToDocR r) $ is) $$ braceNest' (jsToDocR r b)
defRenderJsV r (UnsatVal f) = jsToDocR r $ sat_ f
defRenderJsI :: RenderJs -> Ident -> Doc
defRenderJsI _ (TxtI t) = text (TL.fromStrict t)
{--------------------------------------------------------------------
ToJExpr Class
--------------------------------------------------------------------}
-- | Things that can be marshalled into javascript values.
-- Instantiate for any necessary data structures.
class ToJExpr a where
toJExpr :: a -> JExpr
toJExprFromList :: [a] -> JExpr
toJExprFromList = ValExpr . JList . map toJExpr
instance ToJExpr a => ToJExpr [a] where
toJExpr = toJExprFromList
instance ToJExpr JExpr where
toJExpr = id
instance ToJExpr () where
toJExpr _ = ValExpr $ JList []
instance ToJExpr Bool where
toJExpr True = jsv "true"
toJExpr False = jsv "false"
instance ToJExpr JVal where
toJExpr = ValExpr
instance ToJExpr a => ToJExpr (M.Map Text a) where
toJExpr = ValExpr . JHash . M.map toJExpr
instance ToJExpr a => ToJExpr (M.Map String a) where
toJExpr = ValExpr . JHash . M.fromList . map (T.pack *** toJExpr) . M.toList
instance ToJExpr Double where
toJExpr = ValExpr . JDouble . SaneDouble
instance ToJExpr Int where
toJExpr = ValExpr . JInt . fromIntegral
instance ToJExpr Integer where
toJExpr = ValExpr . JInt
instance ToJExpr Char where
toJExpr = ValExpr . JStr . T.pack . (:[])
toJExprFromList = ValExpr . JStr . T.pack
-- where escQuotes = tailDef "" . initDef "" . show
instance ToJExpr Ident where
toJExpr = ValExpr . JVar
instance ToJExpr T.Text where
toJExpr = ValExpr . JStr
instance ToJExpr TL.Text where
toJExpr = ValExpr . JStr . TL.toStrict
instance (ToJExpr a, ToJExpr b) => ToJExpr (a,b) where
toJExpr (a,b) = ValExpr . JList $ [toJExpr a, toJExpr b]
instance (ToJExpr a, ToJExpr b, ToJExpr c) => ToJExpr (a,b,c) where
toJExpr (a,b,c) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c]
instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d) => ToJExpr (a,b,c,d) where
toJExpr (a,b,c,d) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d]
instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d, ToJExpr e) => ToJExpr (a,b,c,d,e) where
toJExpr (a,b,c,d,e) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d, toJExpr e]
instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d, ToJExpr e, ToJExpr f) => ToJExpr (a,b,c,d,e,f) where
toJExpr (a,b,c,d,e,f) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d, toJExpr e, toJExpr f]
instance Num JExpr where
fromInteger = ValExpr . JInt . fromIntegral
x + y = InfixExpr AddOp x y
x - y = InfixExpr SubOp x y
x * y = InfixExpr MulOp x y
abs x = ApplExpr (jsv "Math.abs") [x]
signum x = IfExpr (InfixExpr GtOp x 0) 1 (IfExpr (InfixExpr EqOp x 0) 0 (-1))
{--------------------------------------------------------------------
Block Sugar
--------------------------------------------------------------------}
class ToStat a where
toStat :: a -> JStat
instance ToStat JStat where
toStat = id
instance ToStat [JStat] where
toStat = BlockStat
instance ToStat JExpr where
toStat = expr2stat
instance ToStat [JExpr] where
toStat = BlockStat . map expr2stat
{--------------------------------------------------------------------
Combinators
--------------------------------------------------------------------}
-- | Create a new anonymous function. The result is an expression.
-- Usage:
-- @jLam $ \ x y -> {JExpr involving x and y}@
jLam :: ToSat a => a -> JExpr
jLam f = ValExpr . UnsatVal . IS $ do
(block,is) <- runIdentSupply $ toSat_ f []
return $ JFunc is block
-- | Introduce a new variable into scope for the duration
-- of the enclosed expression. The result is a block statement.
-- Usage:
-- @jVar $ \ x y -> {JExpr involving x and y}@
jVar :: ToSat a => a -> JStat
jVar f = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let addDecls (BlockStat ss) =
BlockStat $ map (\x -> DeclStat x) is ++ ss
addDecls x = x
return $ addDecls block
-- | Introduce a new variable with optional type into scope for the duration
-- of the enclosed expression. The result is a block statement.
-- Usage:
-- @jVar $ \ x y -> {JExpr involving x and y}@
jVarTy :: ToSat a => a -> {- Maybe JLocalType -> -} JStat
jVarTy f {- t -} = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let addDecls (BlockStat ss) =
BlockStat $ map (\x -> DeclStat x {- t -}) is ++ ss
addDecls x = x
return $ addDecls block
-- | Create a for in statement.
-- Usage:
-- @jForIn {expression} $ \x -> {block involving x}@
jForIn :: ToSat a => JExpr -> (JExpr -> a) -> JStat
jForIn e f = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let i = headNote "jForIn" is
return $ DeclStat i `mappend` ForInStat False i e block
-- | As with "jForIn" but creating a \"for each in\" statement.
jForEachIn :: ToSat a => JExpr -> (JExpr -> a) -> JStat
jForEachIn e f = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let i = headNote "jForEachIn" is
return $ DeclStat i `mappend` ForInStat True i e block
jTryCatchFinally :: (ToSat a) => JStat -> a -> JStat -> JStat
jTryCatchFinally s f s2 = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let i = headNote "jTryCatchFinally" is
return $ TryStat s i block s2
jsv :: Text -> JExpr
jsv = ValExpr . JVar . TxtI
jFor :: (ToJExpr a, ToStat b) => JStat -> a -> JStat -> b -> JStat
jFor before p after b = BlockStat [before, WhileStat False (toJExpr p) b']
where b' = case toStat b of
BlockStat xs -> BlockStat $ xs ++ [after]
x -> BlockStat [x,after]
jhEmpty :: M.Map Text JExpr
jhEmpty = M.empty
jhSingle :: ToJExpr a => Text -> a -> M.Map Text JExpr
jhSingle k v = jhAdd k v $ jhEmpty
jhAdd :: ToJExpr a => Text -> a -> M.Map Text JExpr -> M.Map Text JExpr
jhAdd k v m = M.insert k (toJExpr v) m
jhFromList :: [(Text, JExpr)] -> JVal
jhFromList = JHash . M.fromList
nullStat :: JStat
nullStat = BlockStat []
-- Aeson instance
instance ToJExpr Value where
toJExpr Null = ValExpr $ JVar $ TxtI "null"
toJExpr (Bool b) = ValExpr $ JVar $ TxtI $ T.pack $ map toLower (show b)
toJExpr (Number n) = ValExpr $ JDouble $ realToFrac n
toJExpr (String s) = ValExpr $ JStr $ s
toJExpr (Array vs) = ValExpr $ JList $ map toJExpr $ V.toList vs
toJExpr (Object obj) = ValExpr $ JHash $ M.fromList $ map (second toJExpr) $ HM.toList obj
encodeJson :: Text -> Text
encodeJson = T.concatMap encodeJsonChar
encodeJsonChar :: Char -> Text
encodeJsonChar '/' = "\\/"
encodeJsonChar '\b' = "\\b"
encodeJsonChar '\f' = "\\f"
encodeJsonChar '\n' = "\\n"
encodeJsonChar '\r' = "\\r"
encodeJsonChar '\t' = "\\t"
encodeJsonChar '"' = "\\\""
encodeJsonChar '\\' = "\\\\"
encodeJsonChar c
| not (isControl c) && ord c <= 127 = T.singleton c
| ord c <= 0xff = hexxs "\\x" 2 (ord c)
| ord c <= 0xffff = hexxs "\\u" 4 (ord c)
| otherwise = let cp0 = ord c - 0x10000 -- output surrogate pair
in hexxs "\\u" 4 ((cp0 `shiftR` 10) + 0xd800) `mappend`
hexxs "\\u" 4 ((cp0 .&. 0x3ff) + 0xdc00)
where hexxs prefix pad cp =
let h = showHex cp ""
in T.pack (prefix ++ replicate (pad - length h) '0' ++ h)
| forked-upstream-packages-for-ghcjs/ghcjs | ghcjs/src/Compiler/JMacro/Base.hs | mit | 33,902 | 0 | 21 | 9,637 | 12,039 | 6,164 | 5,875 | 645 | 35 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main (Main.main) where
import GHC.IO.Handle
import GHC.IO.Handle.FD
import qualified Database.SQLite3 as DB
import SQLUtil
import System.Environment
import Control.Concurrent
import qualified Control.Exception as E
import Control.Monad
import System.Time
main :: IO ()
main = do
-- [dbSubject,dbShow,dbLog]<-getArgs>>=mapM mawaru.take 3
[dbSubjectS,dbLogS]<-getArgs
dbSubject<-mawaru dbSubjectS
dbLog<-DB.open dbLogS
-- readFile "monitor_vis_setup.sql">>=(\s->DB.runScript dbShow s [])
readFile "monitor_log_setup.sql">>=(\s->DB.runScript dbLog s [])
putStrLn "This is the MONITOR"
hFlush stdout
forever (threadDelay 100000>>showStats dbSubject dbLog)
showStats dbSubject dbLog = do
-- print 111
hFlush stdout
tm'<-getClockTime>>=return.DB.SQLInteger .fromIntegral.(\(TOD secs psecs)->secs*1000+(psecs `div` (10^9)))
sql dbSubject "SELECT sum(buffer_size) FROM gl_sync_geometry_attrib_group_has_auto_buffers" []
>>=(\[[bts']]->sql dbLog "INSERT INTO buffer_total_size VALUES (?1,?2)" [tm',bts']>>print bts')
sql dbSubject "SELECT type,count(gl_id) FROM gl_objects GROUP BY type" []
>>=(\rows->mapM_ (sql dbLog "INSERT INTO num_gl_objects VALUES (?,?,?)".(tm':)) rows>>print rows)
{- sql dbLog "SELECT val FROM buffer_total_size ORDER BY time DESC LIMIT 19" []
>>=visualize tm' "dc_bts"
sequence_ $ zipWith (\tp dcn->sql dbLog "SELECT val FROM num_gl_objects WHERE type=? ORDER BY time DESC LIMIT 19"
[DB.SQLText tp]>>=visualize tm' dcn) ["p","s","b","v"] ["dc_n_p","dc_n_s","dc_n_b","dc_n_v"]
sql dbShow "UPDATE playback_countrol SET force_to_play=?1" [tm']-}
where
sql = runStrB
{- visualize tm' dcName rows = let
xs = map (\[DB.SQLInteger i]->fromIntegral i) rows
hs = map (/maximum xs) xs
in mapM_ (\h->sql dbShow "INSERT INTO shader_constants_v4 VALUES (?,?,'h',?,0,0,0)" [DB.SQLText dcName,tm',DB.SQLFloat h]) hs
-}
mawaru s = try>>=decide
where
try = do
db<-DB.open s
E.catch (runStr db "SELECT * FROM playback_control">>return (Just db))
(\(e::E.SomeException)->threadDelay 100000>>DB.close db>>return Nothing)
decide (Just db) = return db
decide Nothing = try>>=decide
| ducis/haAni | hs/monitor.hs | gpl-2.0 | 2,180 | 8 | 16 | 301 | 500 | 260 | 240 | 35 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import KlaczMonad
import IRC
import Functionality
import Network.Fancy
import Network.FastIRC
import Network.FastIRC.Session
import Control.Monad.State
import Control.Monad.Error
import Control.Applicative
import qualified Data.Map as M
configNickname = return "klacz2Adam"
configUser = return "klacz"
configRealName = return "Klacz"
configPassword = Nothing
configAddress = IPv4 "irc.freenode.net" 6667
klaczParams = Params
configNickname
configUser
configRealName
configPassword
configAddress
configChannels = ["#klacztest"]
botOnConnect :: Bot ()
botOnConnect = do
ircJoin configChannels
dispatchMessage :: Message -> Bot (Either KlaczError ())
dispatchMessage message = runErrorT $ do
case msgCommand message of
PrivMsgCmd targets msgText ->
handlePrivMsg (msgOrigin message) targets msgText
_ -> throwError $
UnhandledMessage message
botOnMessage :: Message -> Bot ()
botOnMessage message = do
result <- dispatchMessage message
case result of
Left error -> liftIO . putStrLn . show $ error
Right () -> return ()
initBot :: BotSession -> IO ()
initBot session = do
onConnect session botOnConnect
onMessage session botOnMessage
return ()
main = do
r <- startBot klaczParams
case r of
Left err -> putStrLn . show $ err
Right session -> initBot session >> waitForInput
waitForInput = do
_ <- getLine
return ()
| kubov/klacz2 | Main.hs | gpl-3.0 | 1,512 | 0 | 13 | 334 | 417 | 207 | 210 | 53 | 2 |
tupleToElem :: (String, String, Int) -> Element
tupleToElem (n, s, a) = Element { name = n
, symbol = s
, atomicNumber = a } | hmemcpy/milewski-ctfp-pdf | src/content/1.6/code/haskell/snippet16.hs | gpl-3.0 | 190 | 0 | 6 | 91 | 56 | 34 | 22 | 4 | 1 |
{-
Author: Ka Wai
License: GPL 3.0
File: OutputModel_test.hs
Description: tests for outputs generated by OutputModel.hs
-}
module OutputModel_test where
import System.IO
import OutputModel
import Signature
import TestUtils
import Test.HUnit
domainTests = maplabel "Output model domain test"
[domaintest1, domaintest2, domaintest3, domaintest4]
nodesizeTests = maplabel "Output model nodesize test"
[nodesizetest1, nodesizetest2, nodesizetest3, nodesizetest4]
errorTests = maplabel "Output model error test"
[errortest1, errortest2, errortest3, errortest4]
alltests = do putStrLn "==== Testing the model output"
runTestTT domainTests
runTestTT nodesizeTests
runTestTT errorTests
-- Testing setup
dom0 = []
dom1 = [1]
dom2 = [1,2,3]
dom3 = [1,2,3,4]
dom4 = [1,2,3,4,5,6]
domall = dom1 ++ dom2
unary0 = []
unary1 = [("A",[])]
unary2 = [("B",[1])]
unary3 = [("C",[1]), ("D",[2,3])]
unary4 = [("E",[1,3]), ("A",[2,4,1])]
unaryall = concat [unary2, unary3, unary4]
binary0 = []
binary1 = [("R",[(1,1)])]
binary2 = [("R",[(1,2),(1,2)])]
binary3 = [("R",[(1,2),(2,3)])]
binary4 = [("A",[(4,1)]),("R",[(4,1)])]
binaryall = binary1 ++ binary4
-- Expected results
emptydom = begin ++ "label = \"Domain is empty, no model to draw\" ;\n" ++ end
dupdomain = begin ++ "label = \"Domain contains duplicated individuals\" ;\n" ++ end
dupunary = begin ++ "label = \"Duplicated unary relation names exist\" ;\n" ++ end
dupbinary = begin ++ "label = \"Duplicated binary relation names exist\" ;\n" ++ end
begin = "digraph {\n "
end = "}"
-- Tests
domaintest1 = testequality msg target result "([1],[(A,[])], [(R,[(1,1)])])"
where msg = "Failed to produce correct output for simple model"
result = modelToGraph (dom1, unary1, binary1)
target = begin ++ "1 [label=\"1\"] ;\n 1 -> 1 [label=\"R\"] ;\n " ++ end
domaintest2 = testequality msg target result
"([1,2,3],[(B,[1])], [(R,[(1,2),(2,1)])])"
where msg = "Failed to produce correct output for simple model"
result = modelToGraph (dom2, unary2, binary2)
target = begin ++ "1 [label=\"1: B\"] ;\n 2 [label=\"2\"] ;\n 3 " ++
"[label=\"3\"] ;\n 1 -> 2 [label=\"R\"] ;\n " ++ end
domaintest3 = testequality msg target result
"([1,2,3,4],[(C,[1]), (D,[2,3])], [(R,[(1,2),(2,3)])])"
where msg = "Failed to produce correct output for simple model"
result = modelToGraph (dom3, unary3, binary3)
target = begin ++ "1 [label=\"1: C\"] ;\n 2 [label=\"2: D\"] ;\n " ++
"3 [label=\"3: D\"] ;\n 4 [label=\"4\"] ;\n 1 -> 2 " ++
"[label=\"R\"] ;\n 2 -> 3 [label=\"R\"] ;\n " ++ end
domaintest4 = testequality msg target result "([1,1,2,3,1,2,3,4,5,6],[(E,[1,3]), (A,[2,4,1])], [(A,[(4,1)]),(R,[(4,1)])])"
where msg = "Failed to produce correct output for simple model"
result = modelToGraph (dom4, unary4, binary4)
target = begin ++ "1 [label=\"1: A, E\"] ;\n 2 [label=\"2: A\"] ;\n" ++
" 3 [label=\"3: E\"] ;\n 4 [label=\"4: A\"] ;\n 5 " ++
"[label=\"5\"] ;\n 6 [label=\"6\"] ;\n 4 -> 1 " ++
"[label=\"A\"] ;\n 4 -> 1 [label=\"R\"] ;\n " ++ end
nodesizetest1 = testequality msg target result
"([1,2,3,4,5,6],[(B,[1]),(C,[1]),(D,[2,3]),(E,[1,3]),(A,[2,4,1])], [(A,[(4,1)]),(R,[(4,1)])]))"
where msg = "Failed to produce correct output for many unary relations"
result = modelToGraph (dom4, unaryall, binary4)
target = begin ++ "1 [label=\"1: A, E, C, \\nB\"] ;\n 2 [label=\"2: " ++
"A, D\"] ;\n 3 [label=\"3: E, D\"] ;\n 4 [label=\"4: A\"]" ++
" ;\n 5 [label=\"5\"] ;\n 6 [label=\"6\"] ;\n 4 -> 1 " ++
"[label=\"A\"] ;\n 4 -> 1 [label=\"R\"] ;\n " ++ end
-- Unary name of just right length (8 characters)
nodesizetest2 = testequality msg target result "([1],[(justsize,[1])],[])"
where msg = "Failed to produce correct output for short length unary name"
result = modelToGraph ([1], [("justsize",[1])], [])
target = begin ++ "1 [label=\"1: justsize\"] ;\n " ++ end
-- Unary name of just over length (9 characters)
nodesizetest3 = testequality msg target result "([1],[(istoolong,[1])],[])"
where msg = "Failed to produce correct output for simple model"
result = modelToGraph ([1], [("istoolong",[1])], [])
target = begin ++ "1 [label=\"1: istoolo-\\nng\"] ;\n " ++ end
nodesizetest4 = testequality msg target result "([1],[(A,[1]),(justsize,[1]),(B,[1]),(C,[1]),(istoolong,[1]),(D,[1]),(E,[1])],[])"
where msg = "Failed to produce correct output for mixture of unary name lengths"
result = modelToGraph ([1], [("A",[1]),("justsize",[1]),("B",[1]),
("C",[1]),("istoolong",[1]),("D",[1]),("E",[1])], [])
target = begin ++ "1 [label=\"1: E, D, \\nistoolo-\\nng, C, B, \\n" ++
"justsize, \\nA\"] ;\n " ++ end
errortest1 = testequality msg target result "empty model ([],[],[])"
where msg = "Failed to detect empty domain"
result = modelToGraph (dom0, unary0, binary0)
target = emptydom
errortest2 = testequality msg target result "duplicates in domain ([1,1,2,3],[],[])"
where msg = "Failed to detect duplicated individuals in domain"
result = modelToGraph (domall, unary0, binary0)
target = dupdomain
errortest3 = testequality msg target result "duplicates in domain ([1,2,3,4],[(A,[]),(E,[1,3]),(A,[2,4,1])],[])"
where msg = "Failed to detect duplicated unary concepts in unarys"
result = modelToGraph (dom3, unary1 ++ unary4, binary0)
target = dupunary
errortest4 = testequality msg target result "duplicates in domain ([1,2,3,4],[],[(R,[(1,1)]),(A,[(4,1)]),(R,[(4,1)])])"
where msg = "Failed to detect duplicated unary concepts in binarys"
result = modelToGraph (dom3, unary0, binaryall)
target = dupbinary | j5b/ps-pc | OutputModel_test.hs | gpl-3.0 | 6,118 | 0 | 11 | 1,462 | 1,282 | 751 | 531 | 102 | 1 |
--------------------------------------------------------------------------------
-- This file is part of diplomarbeit ("Diplomarbeit Johannes Weiß"). --
-- --
-- diplomarbeit 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. --
-- --
-- diplomarbeit 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 diplomarbeit. If not, see <http://www.gnu.org/licenses/>. --
-- --
-- Copyright 2012, Johannes Weiß --
--------------------------------------------------------------------------------
{-# LANGUAGE FlexibleContexts #-}
-- | Send all kinds of OAFE and RAE related data types over the network.
module Data.RAE.Conduit
( oafeConfigParseConduit
, oafeConfigSerializeConduit
, oafeEvaluationRequestParseConduit
, oafeEvaluationResponseSerializeConduit
, oafeEvaluationResponseParseConduit
, oafeEvaluationRequestSerializeConduit
, racFragmentSerializeConduit
, racFragmentParseConduit
, ByteSerializable(..)
) where
-- # STDLIB
import qualified Data.Foldable as F
import qualified Data.Sequence as S
-- # SITE PACKAGES
import Control.Monad.Trans.Resource (MonadResource)
import Data.Conduit (Conduit, (=$=))
import Data.Text (Text)
import Data.Vector (Vector)
import Text.ProtocolBuffers.Basic (Utf8(Utf8))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Conduit.List as CL
import qualified Data.Text.Encoding as TE
import qualified Data.Vector as V
-- # LOCAL
import Data.Conduit.ProtoBufConduit (pbufParse, pbufSerialize)
import Data.OAFE ( OAFEEvaluationRequest, OAFEEvaluationResponse
, OAFEReference(..)
)
import Data.RAE.Types (RAE(..), RACFragment, RadicalTuple(..))
import Data.FieldTypes (Field(..))
import Data.LinearExpression (VariableName)
import Math.FiniteFields.F2Pow256 (F2Pow256, f2Pow256FromBytes, f2Pow256ToBytes)
-- # PROTOBUF
import qualified Data.ProtoBufs.OAFE.LinearExpr as Pb
import qualified Data.ProtoBufs.OAFE.OAFEConfig as Pb
import qualified Data.ProtoBufs.OAFE.OAFEEvaluationRequest as Pb
import qualified Data.ProtoBufs.OAFE.OAFEEvaluationResponse as Pb
import qualified Data.ProtoBufs.RAE.RAE as PbRAE
import qualified Data.ProtoBufs.RAE.MulTerm as PbRAE
import qualified Data.ProtoBufs.RAE.OAFEReference as PbRAE
import qualified Data.ProtoBufs.RAE.OAFERefRadicals as PbRAE
class ByteSerializable el where
serializeBytes :: el -> BSL.ByteString
parseBytes :: BSL.ByteString -> el
instance ByteSerializable F2Pow256 where
serializeBytes = BSL.fromStrict . f2Pow256ToBytes
parseBytes = f2Pow256FromBytes . BSL.toStrict
uToText :: Utf8 -> Text
uToText (Utf8 bs) = TE.decodeUtf8 $ BSL.toStrict bs
uFromText :: Text -> Utf8
uFromText = Utf8 . BSL.fromStrict . TE.encodeUtf8
-- # CONDUITS
oafeConfigParseConduit :: (MonadResource m, Field el, ByteSerializable el)
=> Conduit BS.ByteString m
(VariableName, Vector (el, el))
oafeConfigParseConduit = pbufParse =$= CL.map oafeConfigFromProtoBuf
oafeEvaluationRequestParseConduit :: ( MonadResource m, Field el
, ByteSerializable el
)
=> Conduit BS.ByteString m (VariableName, el)
oafeEvaluationRequestParseConduit =
pbufParse =$= CL.map oafeEvaluationRequestFromProtoBuf
oafeConfigSerializeConduit :: (MonadResource m, Field el, ByteSerializable el)
=> Conduit (VariableName, Vector (el, el)) m
BS.ByteString
oafeConfigSerializeConduit = CL.map oafeConfigAsProtoBuf =$= pbufSerialize
oafeEvaluationResponseSerializeConduit :: ( MonadResource m, Field el
, ByteSerializable el
)
=> Conduit (OAFEEvaluationResponse el)
m BS.ByteString
oafeEvaluationResponseSerializeConduit =
CL.map oafeEvaluationResponseAsProtoBuf =$= pbufSerialize
oafeEvaluationResponseParseConduit :: ( MonadResource m, Field el
, ByteSerializable el
)
=> Conduit BS.ByteString
m (OAFEEvaluationResponse el)
oafeEvaluationResponseParseConduit =
pbufParse =$= CL.map oafeEvaluationResponseFromProtoBuf
oafeEvaluationRequestSerializeConduit :: ( MonadResource m, Field el
, ByteSerializable el
)
=> Conduit (OAFEEvaluationRequest el)
m BS.ByteString
oafeEvaluationRequestSerializeConduit =
CL.map oafeEvaluationRequestAsProtoBuf =$= pbufSerialize
racFragmentSerializeConduit :: (MonadResource m, Field el, ByteSerializable el)
=> Conduit (RACFragment el) m BS.ByteString
racFragmentSerializeConduit = CL.map encodeRAE =$= pbufSerialize
racFragmentParseConduit :: (MonadResource m, Field el, ByteSerializable el)
=> Conduit BS.ByteString m (RACFragment el)
racFragmentParseConduit = pbufParse =$= CL.map decodeRACFragment
-- # DE/ENCODING
oafeConfigFromProtoBuf :: (Field el, ByteSerializable el)
=> Pb.OAFEConfig
-> (VariableName, Vector (el, el))
oafeConfigFromProtoBuf = decodeOAFEConfiguration
oafeEvaluationResponseAsProtoBuf :: (Field el, ByteSerializable el)
=> (VariableName, Vector el)
-> Pb.OAFEEvaluationResponse
oafeEvaluationResponseAsProtoBuf (var, vals) =
Pb.OAFEEvaluationResponse (uFromText var)
(S.fromList $ map serializeBytes $ V.toList vals)
oafeEvaluationRequestFromProtoBuf :: (Field el, ByteSerializable el)
=> Pb.OAFEEvaluationRequest
-> (VariableName, el)
oafeEvaluationRequestFromProtoBuf (Pb.OAFEEvaluationRequest var val) =
(uToText var, parseBytes val)
oafeEvaluationRequestAsProtoBuf :: (Field el, ByteSerializable el)
=> OAFEEvaluationRequest el
-> Pb.OAFEEvaluationRequest
oafeEvaluationRequestAsProtoBuf (var, el) =
Pb.OAFEEvaluationRequest (uFromText var) (serializeBytes el)
oafeEvaluationResponseFromProtoBuf :: (Field el, ByteSerializable el)
=> Pb.OAFEEvaluationResponse
-> OAFEEvaluationResponse el
oafeEvaluationResponseFromProtoBuf (Pb.OAFEEvaluationResponse var vals) =
(uToText var, V.fromList $ map parseBytes $ F.toList vals)
decodeOAFEConfiguration :: (Field el, ByteSerializable el)
=> Pb.OAFEConfig
-> (VariableName, Vector (el, el))
decodeOAFEConfiguration (Pb.OAFEConfig var exprs) =
(uToText var, V.map decodeLinearExpr $ (V.fromList . F.toList) exprs)
oafeConfigAsProtoBuf :: (Field el, ByteSerializable el)
=> (VariableName, Vector (el, el))
-> Pb.OAFEConfig
oafeConfigAsProtoBuf (v, les) =
Pb.OAFEConfig (uFromText v) (S.fromList $ V.toList $
V.map encodeLinearExpr les)
encodeLinearExpr :: (Field el, ByteSerializable el) => (el, el) -> Pb.LinearExpr
encodeLinearExpr (s, i) =
let enc = serializeBytes
in Pb.LinearExpr (enc s) (enc i)
decodeLinearExpr :: (Field el, ByteSerializable el) => Pb.LinearExpr -> (el, el)
decodeLinearExpr lePb =
let dec = parseBytes
in (dec $ Pb.scale lePb, dec $ Pb.intercept lePb)
encodeOAFERef :: OAFEReference -> PbRAE.OAFEReference
encodeOAFERef (OAFERef var idx) =
PbRAE.OAFEReference (uFromText var) (fromIntegral idx)
encodeOAFERefRadicals :: RadicalTuple OAFEReference -> PbRAE.OAFERefRadicals
encodeOAFERefRadicals (RT (or1, or2)) =
let or1enc = encodeOAFERef or1
or2enc = encodeOAFERef or2
in PbRAE.OAFERefRadicals or1enc or2enc
decodeOAFERef :: PbRAE.OAFEReference -> OAFEReference
decodeOAFERef (PbRAE.OAFEReference var idx) =
OAFERef (uToText var) (fromIntegral idx)
decodeOAFERefRadicals :: PbRAE.OAFERefRadicals -> RadicalTuple OAFEReference
decodeOAFERefRadicals (PbRAE.OAFERefRadicals orr1 orr2) =
let orr1dec = decodeOAFERef orr1
orr2dec = decodeOAFERef orr2
in RT (orr1dec, orr2dec)
encodeMulTerm :: (RadicalTuple OAFEReference, RadicalTuple OAFEReference)
-> PbRAE.MulTerm
encodeMulTerm (l, r) = PbRAE.MulTerm (encodeOAFERefRadicals l)
(encodeOAFERefRadicals r)
decodeMulTerm :: PbRAE.MulTerm
-> (RadicalTuple OAFEReference, RadicalTuple OAFEReference)
decodeMulTerm (PbRAE.MulTerm l r) =
(decodeOAFERefRadicals l, decodeOAFERefRadicals r)
encodeRAE :: ByteSerializable el => RACFragment el -> PbRAE.RAE
encodeRAE (var, RAE muls adds cnst) =
let encConst = serializeBytes cnst
encAdds = S.fromList $ map encodeOAFERef adds
encMuls = S.fromList $ map encodeMulTerm muls
in PbRAE.RAE (uFromText var) encMuls encAdds encConst
decodeRACFragment :: (Field el, ByteSerializable el)
=> PbRAE.RAE -> RACFragment el
decodeRACFragment (PbRAE.RAE encVar encMuls encAdds encConst) =
let var = uToText encVar
muls = map decodeMulTerm $ F.toList encMuls
adds = map decodeOAFERef $ F.toList encAdds
cnst = parseBytes encConst
in (var, RAE muls adds cnst)
| weissi/diplomarbeit | lib/Data/RAE/Conduit.hs | gpl-3.0 | 10,633 | 0 | 11 | 3,079 | 2,157 | 1,187 | 970 | 167 | 1 |
{- Some types and utilities for cryptography -}
module CryptoChallenge where
import Data.Char (ord, chr)
import Data.Bits (xor, (.&.), shiftR)
import Data.List
import Data.List.Split
type Cipher = [Int]
type Key = [Int]
type Plain = [Int]
aesBlocksize :: Int
aesBlocksize = 0x10 -- Because the standard says so
fromString = map ord
toString = map chr
charToKey :: Char -> [Int]
charToKey c = [ord c]
{- Hamming Distance -}
bitcount :: Int -> Int
bitcount 0 = 0
bitcount n = (n .&. 1) + (bitcount (shiftR n 1))
hamming :: Int -> Int -> Int
hamming a b = bitcount (a `xor` b)
hammingDistance :: Cipher -> Cipher -> Int
hammingDistance s1 s2 = sum $ map (\p -> hamming (fst p) (snd p))
(zip s1 s2)
hasDuplicateChunks :: Eq a => Int -> [a] -> Bool
hasDuplicateChunks chunkSize xs =
(length chunks) /= (length $ nub chunks)
where chunks = chunksOf chunkSize xs
| CharlesRandles/cryptoChallenge | cryptochallenge.hs | gpl-3.0 | 898 | 0 | 11 | 198 | 343 | 190 | 153 | 26 | 1 |
module Scheme.Evaluator.Primitives (
primitives
) where
import Scheme.Internal
import Control.Arrow ((>>>))
--- Functions
primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
primitives = [
-- Core
("equal?", checkNumArg2 $ \x -> \y -> Bool (x == y)),
-- Type checking etc
("number?", checkNumArg1 $ \val -> case val of Number _ -> Bool True; _ -> Bool False),
("boolean?", checkNumArg1 $ \val -> case val of Bool _ -> Bool True; _ -> Bool False),
("char?", checkNumArg1 $ \val -> case val of Character _ -> Bool True; _ -> Bool False),
("string?", checkNumArg1 $ \val -> case val of String _ -> Bool True; _ -> Bool False),
("symbol?", checkNumArg1 $ \val -> case val of Symbol _ -> Bool True; _ -> Bool False),
("procedure?",checkNumArg1 $ \val -> case val of Func _ _ _ _ -> Bool True; PrimitiveFunc _ -> Bool True; _ -> Bool False),
("list?", checkNumArg1 $ \val -> case val of List _ -> Bool True; _ -> Bool False), -- [Library]
("null?", checkNumArg1 $ \val -> case val of List [] -> Bool True; _ -> Bool False),
("pair?", checkNumArg1 $ \val -> case val of DottedList _ _ -> Bool True; List [] -> Bool False; List _ -> Bool True; _ -> Bool False),
-- Type casting
("symbol->string", \vals -> checkNumArg1M vals >>= unpackSym >>= (String >>> return)),
("string->symbol", \vals -> checkNumArg1M vals >>= unpackStr >>= (Symbol >>> return)),
("number->string", \vals -> checkNumArg1M vals >>= unpackNum >>= (show >>> String >>> return)),
("string->number", \vals -> checkNumArg1M vals >>= unpackStr >>= (read >>> Number >>> return)), -- [TODO] input check
-- Numeric
("+", numericBinop (+)),
("-", numericBinop (-)),
("*", numericBinop (*)),
("/", numericBinop div),
("=", numBoolBinop (==)),
("<", numBoolBinop (<)),
(">", numBoolBinop (>)),
(">=", numBoolBinop (>=)),
("<=", numBoolBinop (<=)),
("mod", numericBinop mod),
("quotient", numericBinop quot),
("remainder", numericBinop rem),
-- Bool
("not", \vals -> checkNumArg1M vals >>= unpackBool >>= (not >>> Bool >>> return)),
-- String
("string-append", strBinop (++)),
("string=?", strBoolBinop (==)),
("string>?", strBoolBinop (>)),
("string<?", strBoolBinop (<)),
("string<=?", strBoolBinop (<=)),
("string>=?", strBoolBinop (>=)),
-- List
("cons",cons),
("car",car),
("cdr",cdr),
-- etc
("undefined",\[] -> return Undefined)]
where checkNumArg1M vals = case vals of [val] -> return val; _ -> throwError (NumArgs 1 vals)
checkNumArg1 p vals = case vals of [val] -> return (p val); _ -> throwError (NumArgs 1 vals)
checkNumArg2 p vals = case vals of [val1,val2] -> return (p val1 val2); _ -> throwError (NumArgs 2 vals)
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal
numericBinop op list = mapM unpackNum list >>= return . Number . foldr1 op
boolBinop :: (LispVal -> ThrowsError a) -> (a -> a -> Bool) -> [LispVal] -> ThrowsError LispVal
boolBinop unpacker op args = if length args /= 2
then throwError $ NumArgs 2 args
else do
left <- unpacker $ args !! 0
right <- unpacker $ args !! 1
return $ Bool $ left `op` right
strBinop :: (String -> String -> String) -> [LispVal] -> ThrowsError LispVal
strBinop op list = mapM unpackStr list >>= return . String . foldr1 op
numBoolBinop :: (Integer -> Integer -> Bool) -> [LispVal] -> ThrowsError LispVal
numBoolBinop = boolBinop unpackNum
strBoolBinop :: (String -> String -> Bool) -> [LispVal] -> ThrowsError LispVal
strBoolBinop = boolBinop unpackStr
boolBoolBinop :: (Bool -> Bool -> Bool) -> [LispVal] -> ThrowsError LispVal
boolBoolBinop = boolBinop unpackBool
unpackNum :: LispVal -> ThrowsError Integer
unpackNum (Number num) = return num
unpackNum notNum = throwError $ TypeMismatch "number" notNum
unpackBool :: LispVal -> ThrowsError Bool
unpackBool (Bool num) = return num
unpackBool notBool = throwError $ TypeMismatch "bool" notBool
unpackSym :: LispVal -> ThrowsError String
unpackSym (Symbol str) = return str
unpackSym notSymbol = throwError $ TypeMismatch "symbol" notSymbol
unpackStr :: LispVal -> ThrowsError String
unpackStr (String str) = return str
unpackStr notString = throwError $ TypeMismatch "symbol" notString
cons :: [LispVal] -> ThrowsError LispVal
cons [x, List []] = return $ List [x]
cons [x, List xs] = return $ List (x:xs)
cons [x, DottedList xs xlast] = return $ DottedList (x:xs) xlast
cons [x1, x2] = return $ DottedList [x1] x2
cons badArgList = throwError $ NumArgs 1 badArgList
car :: [LispVal] -> ThrowsError LispVal
car [List (x:_)] = return x
car [DottedList (x:_) _] = return x
car [badArg] = throwError $ TypeMismatch "pair" badArg
car badArgList = throwError $ NumArgs 1 badArgList
cdr :: [LispVal] -> ThrowsError LispVal
cdr [List (_:xs)] = return $ List xs
cdr [DottedList [_] tl] = return tl
cdr [DottedList (_:xs) tl] = return $ DottedList xs tl
cdr [badArg] = throwError $ TypeMismatch "pair" badArg
cdr badArgList = throwError $ NumArgs 1 badArgList
| Altech/haScm | src/Scheme/Evaluator/Primitives.hs | gpl-3.0 | 5,166 | 0 | 13 | 1,092 | 2,094 | 1,120 | 974 | 92 | 16 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AdSenseHost.CustomChannels.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Delete a specific custom channel from the host AdSense account.
--
-- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> for @adsensehost.customchannels.delete@.
module Network.Google.Resource.AdSenseHost.CustomChannels.Delete
(
-- * REST Resource
CustomChannelsDeleteResource
-- * Creating a Request
, customChannelsDelete
, CustomChannelsDelete
-- * Request Lenses
, ccdCustomChannelId
, ccdAdClientId
) where
import Network.Google.AdSenseHost.Types
import Network.Google.Prelude
-- | A resource alias for @adsensehost.customchannels.delete@ method which the
-- 'CustomChannelsDelete' request conforms to.
type CustomChannelsDeleteResource =
"adsensehost" :>
"v4.1" :>
"adclients" :>
Capture "adClientId" Text :>
"customchannels" :>
Capture "customChannelId" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] CustomChannel
-- | Delete a specific custom channel from the host AdSense account.
--
-- /See:/ 'customChannelsDelete' smart constructor.
data CustomChannelsDelete =
CustomChannelsDelete'
{ _ccdCustomChannelId :: !Text
, _ccdAdClientId :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomChannelsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccdCustomChannelId'
--
-- * 'ccdAdClientId'
customChannelsDelete
:: Text -- ^ 'ccdCustomChannelId'
-> Text -- ^ 'ccdAdClientId'
-> CustomChannelsDelete
customChannelsDelete pCcdCustomChannelId_ pCcdAdClientId_ =
CustomChannelsDelete'
{ _ccdCustomChannelId = pCcdCustomChannelId_
, _ccdAdClientId = pCcdAdClientId_
}
-- | Custom channel to delete.
ccdCustomChannelId :: Lens' CustomChannelsDelete Text
ccdCustomChannelId
= lens _ccdCustomChannelId
(\ s a -> s{_ccdCustomChannelId = a})
-- | Ad client from which to delete the custom channel.
ccdAdClientId :: Lens' CustomChannelsDelete Text
ccdAdClientId
= lens _ccdAdClientId
(\ s a -> s{_ccdAdClientId = a})
instance GoogleRequest CustomChannelsDelete where
type Rs CustomChannelsDelete = CustomChannel
type Scopes CustomChannelsDelete =
'["https://www.googleapis.com/auth/adsensehost"]
requestClient CustomChannelsDelete'{..}
= go _ccdAdClientId _ccdCustomChannelId
(Just AltJSON)
adSenseHostService
where go
= buildClient
(Proxy :: Proxy CustomChannelsDeleteResource)
mempty
| brendanhay/gogol | gogol-adsense-host/gen/Network/Google/Resource/AdSenseHost/CustomChannels/Delete.hs | mpl-2.0 | 3,478 | 0 | 14 | 771 | 381 | 229 | 152 | 67 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.RemoteBuildExecution.Blobs.GetTree
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Fetch the entire directory tree rooted at a node. This request must be
-- targeted at a Directory stored in the ContentAddressableStorage (CAS).
-- The server will enumerate the \`Directory\` tree recursively and return
-- every node descended from the root. The GetTreeRequest.page_token
-- parameter can be used to skip ahead in the stream (e.g. when retrying a
-- partially completed and aborted request), by setting it to a value taken
-- from GetTreeResponse.next_page_token of the last successfully processed
-- GetTreeResponse). The exact traversal order is unspecified and, unless
-- retrieving subsequent pages from an earlier request, is not guaranteed
-- to be stable across multiple invocations of \`GetTree\`. If part of the
-- tree is missing from the CAS, the server will return the portion present
-- and omit the rest. Errors: * \`NOT_FOUND\`: The requested tree root is
-- not present in the CAS.
--
-- /See:/ <https://cloud.google.com/remote-build-execution/docs/ Remote Build Execution API Reference> for @remotebuildexecution.blobs.getTree@.
module Network.Google.Resource.RemoteBuildExecution.Blobs.GetTree
(
-- * REST Resource
BlobsGetTreeResource
-- * Creating a Request
, blobsGetTree
, BlobsGetTree
-- * Request Lenses
, bgtSizeBytes
, bgtXgafv
, bgtHash
, bgtUploadProtocol
, bgtAccessToken
, bgtUploadType
, bgtPageToken
, bgtPageSize
, bgtInstanceName
, bgtCallback
) where
import Network.Google.Prelude
import Network.Google.RemoteBuildExecution.Types
-- | A resource alias for @remotebuildexecution.blobs.getTree@ method which the
-- 'BlobsGetTree' request conforms to.
type BlobsGetTreeResource =
"v2" :>
Capture "instanceName" Text :>
"blobs" :>
Capture "hash" Text :>
CaptureMode "sizeBytes" "getTree" (Textual Int64) :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
BuildBazelRemoteExecutionV2GetTreeResponse
-- | Fetch the entire directory tree rooted at a node. This request must be
-- targeted at a Directory stored in the ContentAddressableStorage (CAS).
-- The server will enumerate the \`Directory\` tree recursively and return
-- every node descended from the root. The GetTreeRequest.page_token
-- parameter can be used to skip ahead in the stream (e.g. when retrying a
-- partially completed and aborted request), by setting it to a value taken
-- from GetTreeResponse.next_page_token of the last successfully processed
-- GetTreeResponse). The exact traversal order is unspecified and, unless
-- retrieving subsequent pages from an earlier request, is not guaranteed
-- to be stable across multiple invocations of \`GetTree\`. If part of the
-- tree is missing from the CAS, the server will return the portion present
-- and omit the rest. Errors: * \`NOT_FOUND\`: The requested tree root is
-- not present in the CAS.
--
-- /See:/ 'blobsGetTree' smart constructor.
data BlobsGetTree =
BlobsGetTree'
{ _bgtSizeBytes :: !(Textual Int64)
, _bgtXgafv :: !(Maybe Xgafv)
, _bgtHash :: !Text
, _bgtUploadProtocol :: !(Maybe Text)
, _bgtAccessToken :: !(Maybe Text)
, _bgtUploadType :: !(Maybe Text)
, _bgtPageToken :: !(Maybe Text)
, _bgtPageSize :: !(Maybe (Textual Int32))
, _bgtInstanceName :: !Text
, _bgtCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BlobsGetTree' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bgtSizeBytes'
--
-- * 'bgtXgafv'
--
-- * 'bgtHash'
--
-- * 'bgtUploadProtocol'
--
-- * 'bgtAccessToken'
--
-- * 'bgtUploadType'
--
-- * 'bgtPageToken'
--
-- * 'bgtPageSize'
--
-- * 'bgtInstanceName'
--
-- * 'bgtCallback'
blobsGetTree
:: Int64 -- ^ 'bgtSizeBytes'
-> Text -- ^ 'bgtHash'
-> Text -- ^ 'bgtInstanceName'
-> BlobsGetTree
blobsGetTree pBgtSizeBytes_ pBgtHash_ pBgtInstanceName_ =
BlobsGetTree'
{ _bgtSizeBytes = _Coerce # pBgtSizeBytes_
, _bgtXgafv = Nothing
, _bgtHash = pBgtHash_
, _bgtUploadProtocol = Nothing
, _bgtAccessToken = Nothing
, _bgtUploadType = Nothing
, _bgtPageToken = Nothing
, _bgtPageSize = Nothing
, _bgtInstanceName = pBgtInstanceName_
, _bgtCallback = Nothing
}
-- | The size of the blob, in bytes.
bgtSizeBytes :: Lens' BlobsGetTree Int64
bgtSizeBytes
= lens _bgtSizeBytes (\ s a -> s{_bgtSizeBytes = a})
. _Coerce
-- | V1 error format.
bgtXgafv :: Lens' BlobsGetTree (Maybe Xgafv)
bgtXgafv = lens _bgtXgafv (\ s a -> s{_bgtXgafv = a})
-- | The hash. In the case of SHA-256, it will always be a lowercase hex
-- string exactly 64 characters long.
bgtHash :: Lens' BlobsGetTree Text
bgtHash = lens _bgtHash (\ s a -> s{_bgtHash = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bgtUploadProtocol :: Lens' BlobsGetTree (Maybe Text)
bgtUploadProtocol
= lens _bgtUploadProtocol
(\ s a -> s{_bgtUploadProtocol = a})
-- | OAuth access token.
bgtAccessToken :: Lens' BlobsGetTree (Maybe Text)
bgtAccessToken
= lens _bgtAccessToken
(\ s a -> s{_bgtAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bgtUploadType :: Lens' BlobsGetTree (Maybe Text)
bgtUploadType
= lens _bgtUploadType
(\ s a -> s{_bgtUploadType = a})
-- | A page token, which must be a value received in a previous
-- GetTreeResponse. If present, the server will use that token as an
-- offset, returning only that page and the ones that succeed it.
bgtPageToken :: Lens' BlobsGetTree (Maybe Text)
bgtPageToken
= lens _bgtPageToken (\ s a -> s{_bgtPageToken = a})
-- | A maximum page size to request. If present, the server will request no
-- more than this many items. Regardless of whether a page size is
-- specified, the server may place its own limit on the number of items to
-- be returned and require the client to retrieve more items using a
-- subsequent request.
bgtPageSize :: Lens' BlobsGetTree (Maybe Int32)
bgtPageSize
= lens _bgtPageSize (\ s a -> s{_bgtPageSize = a}) .
mapping _Coerce
-- | The instance of the execution system to operate against. A server may
-- support multiple instances of the execution system (with their own
-- workers, storage, caches, etc.). The server MAY require use of this
-- field to select between them in an implementation-defined fashion,
-- otherwise it can be omitted.
bgtInstanceName :: Lens' BlobsGetTree Text
bgtInstanceName
= lens _bgtInstanceName
(\ s a -> s{_bgtInstanceName = a})
-- | JSONP
bgtCallback :: Lens' BlobsGetTree (Maybe Text)
bgtCallback
= lens _bgtCallback (\ s a -> s{_bgtCallback = a})
instance GoogleRequest BlobsGetTree where
type Rs BlobsGetTree =
BuildBazelRemoteExecutionV2GetTreeResponse
type Scopes BlobsGetTree =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient BlobsGetTree'{..}
= go _bgtInstanceName _bgtHash _bgtSizeBytes
_bgtXgafv
_bgtUploadProtocol
_bgtAccessToken
_bgtUploadType
_bgtPageToken
_bgtPageSize
_bgtCallback
(Just AltJSON)
remoteBuildExecutionService
where go
= buildClient (Proxy :: Proxy BlobsGetTreeResource)
mempty
| brendanhay/gogol | gogol-remotebuildexecution/gen/Network/Google/Resource/RemoteBuildExecution/Blobs/GetTree.hs | mpl-2.0 | 8,666 | 0 | 20 | 1,970 | 1,084 | 638 | 446 | 148 | 1 |
module TinyThreePassCompiler where
import Data.Char
import Data.List
import Data.List.Split (splitOn)
import Data.Maybe
import Control.Monad
import Control.Applicative hiding (many, some)
data AST = Imm Int
| Arg Int
| Tmp String
| Add AST AST
| Sub AST AST
| Mul AST AST
| Div AST AST
deriving (Eq, Show)
--
alpha = ['a'..'z'] ++ ['A'..'Z']
-----------------------------------------------------
--------------- my parser combinator ----------------
-----------------------------------------------------
newtype Parser val = Parser { parse :: String -> [(val, String)] }
parseCode :: Parser a -> String -> a
parseCode m s = case parse m s of
[(res, [])] -> res
_ -> error "Hugh?"
--
instance Functor Parser where
fmap f (Parser ps) = Parser $ \p -> [(f a, b) | (a, b) <- ps p]
--
instance Applicative Parser where
pure = return
(Parser p1) <*> (Parser p2) = Parser $ \p ->
[(f a, s2) | (f, s1) <- p1 p, (a, s2) <- p2 s1]
--
instance Monad Parser where
return a = Parser $ \s -> [(a, s)]
p >>= f = Parser $ concatMap (\(a, s1) -> parse (f a) s1) . parse p
--
instance MonadPlus Parser where
mzero = Parser $ const []
mplus p q = Parser $ \s -> parse p s ++ parse q s
--
instance Alternative Parser where
empty = mzero
p <|> q = Parser $ \s -> case parse p s of
[] -> parse q s
rs -> rs
--
item :: Parser Char
item = Parser $ \s -> case s of
[ ] -> []
(h : t) -> [(h, t)]
--
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = item >>= \c -> if p c then return c else empty
chainl1 :: Parser a -> Parser (a -> a -> a) -> Parser a
chainl1 p op = do
a <- p
rest a
where rest a = (do
f <- op
b <- p
rest $ f a b)
<|> return a
--
chainl p op = (chainl1 p op <|>) . return
-- | 1+
some v = someV
where manyV = someV <|> pure []
someV = (:) <$> v <*> manyV
--
-- | 0+
many v = manyV
where manyV = someV <|> pure []
someV = (:) <$> v <*> manyV
--
oneOf = satisfy . flip elem
char = satisfy . (==)
nat = read <$> some digit :: Parser Int
digit = satisfy isDigit
reserved = token . string
spaces = many $ oneOf " \n\r\t"
string [ ] = return []
string (c : cs) = do
char c
string cs
return $ c : cs
--
token p = do
a <- p
spaces
return a
--
number = do
s <- string "-" <|> return []
cs <- some digit
return $ read $ s ++ cs
--
parens m = do
reserved "("
n <- m
reserved ")"
return n
--
int :: Parser AST
int = do
n <- number
spaces
return $ Imm n
--
arg :: Parser AST
arg = do
n <- some $ oneOf alpha
spaces
return $ Tmp n
--
binOp x = (reserved x >>) . return
addop = binOp "+" Add <|> binOp "-" Sub
mulop = binOp "*" Mul <|> binOp "/" Div
expr = chainl1 term addop
term = chainl1 factor mulop
factor = int <|> arg <|> parens expr
function = do
reserved "["
args <- many $ oneOf $ alpha ++ " "
reserved "]"
spaces
ex <- expr
return ([ arg | arg <- splitOn " " args, arg /= "" ], ex)
--
compile :: String -> [String]
compile = pass3 . pass2 . pass1
firstTwoPass = pass2 . pass1
pass1 :: String -> AST
pass1 = f . parseCode function
where f (args, (Imm i)) = Imm i
f (args, (Tmp a)) = Arg $ fromJust $ elemIndex a args
f (args, (Add a b)) = Add (f (args, a)) $ f (args, b)
f (args, (Sub a b)) = Sub (f (args, a)) $ f (args, b)
f (args, (Mul a b)) = Mul (f (args, a)) $ f (args, b)
f (args, (Div a b)) = Div (f (args, a)) $ f (args, b)
--
pass2 :: AST -> AST
pass2 (Imm i) = Imm i
pass2 (Arg a) = Arg a
pass2 (Add a b) = case (pass2 a, pass2 b) of
(Imm x, Imm y) -> Imm $ x + y
( x , y ) -> Add x y
pass2 (Sub a b) = case (pass2 a, pass2 b) of
(Imm x, Imm y) -> Imm $ x - y
( x , y ) -> Sub x y
pass2 (Mul a b) = case (pass2 a, pass2 b) of
(Imm x, Imm y) -> Imm $ x * y
( x , y ) -> Mul x y
pass2 (Div a b) = case (pass2 a, pass2 b) of
(Imm x, Imm y) -> Imm $ div x y
( x , y ) -> Div x y
--
pass3 :: AST -> [String]
pass3 (Imm i) = ["IM " ++ show i]
pass3 (Arg a) = ["AR " ++ show a]
pass3 (Add a b) = pass3 a ++ ["PU"] ++ pass3 b ++ ["SW", "PO", "AD"]
pass3 (Sub a b) = pass3 a ++ ["PU"] ++ pass3 b ++ ["SW", "PO", "SU"]
pass3 (Mul a b) = pass3 a ++ ["PU"] ++ pass3 b ++ ["SW", "PO", "MU"]
pass3 (Div a b) = pass3 a ++ ["PU"] ++ pass3 b ++ ["SW", "PO", "DI"]
| ice1000/OI-codes | codewars/301-400/tiny-three-pass-compiler.hs | agpl-3.0 | 4,411 | 0 | 13 | 1,301 | 2,281 | 1,181 | 1,100 | 140 | 6 |
module Addition where
import Test.Hspec
import Test.QuickCheck
dividedBy :: Integral a => a -> a -> (a, a)
dividedBy num denom = go num denom 0
where go n d count
| n < d = (count, n)
| otherwise = go (n - d) d (count + 1)
multiplyBy :: Integral a => a -> a -> a
multiplyBy num multi = go num multi 0
where go n m count
| m == 0 = count
| otherwise = go n (m -1) (count + n)
trivialInt :: Gen Int
trivialInt = return 1
genBool :: Gen Bool
genBool = choose (False, True)
genBool' :: Gen Bool
genBool' = elements [False, True]
genOrdering :: Gen Ordering
genOrdering = elements [LT, EQ, GT]
genChar :: Gen Char
genChar = elements ['a'..'z']
-- usage requires specifying types: sample ( genTuple :: Gen (Int, Float))
genTuple :: (Arbitrary a, Arbitrary b) => Gen (a, b)
genTuple = do
a <- arbitrary
b <- arbitrary
return (a, b)
-- usage reuires specifying types: sample ( genThreeple :: Gen (Int, Float, Char))
genThreeple :: (Arbitrary a, Arbitrary b, Arbitrary c) => Gen (a, b, c)
genThreeple = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
return (a, b, c)
prop_additionGreater :: Int -> Bool
prop_additionGreater x = x + 1 > x
runQc :: IO ()
runQc = quickCheck prop_additionGreater
main :: IO ()
main = hspec $ do
describe "Addition" $ do
-- it "1 + 1 is greater than 1" $ do
-- (1 + 1) > 1 `shouldBe` True
-- it "2 + 2 is equal to 4" $ do
-- 2 + 2 `shouldBe` 4
it "15 divided by 4 is 5" $ do
dividedBy 15 3 `shouldBe` (5, 0)
it "22 divided by 5 is 4 remainder 2" $ do
dividedBy 22 5 `shouldBe` (4,2)
it "5 multiplied by 3 is 15" $ do
multiplyBy 5 3 `shouldBe` 15
it "5 multiplied by 0 is 0" $ do
multiplyBy 5 0 `shouldBe` 0
it "5 multplied by 1 is 5" $ do
multiplyBy 5 1 `shouldBe` 5
it "x + 1 is always greater than x" $ do
property $ \x-> x + 1> (x :: Int)
| thewoolleyman/haskellbook | 14/04/maor/addition/Addition.hs | unlicense | 1,913 | 0 | 17 | 521 | 699 | 357 | 342 | 53 | 1 |
-- quicksort, but not in-place
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (pivot:xs) =
let lower = quicksort [x | x <- xs, x <= pivot]
upper = quicksort [x | x <- xs, x > pivot]
in lower ++ [pivot] ++ upper
-- merge two sorted lists into a single sorted list
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge l1@(x:xs) l2@(y:ys)
| x <= y = x:(merge xs l2)
| otherwise = y:(merge l1 ys)
mergesort :: (Ord a) => [a] -> [a]
mergesort [] = []
mergesort [x] = [x]
mergesort l =
let (xs, ys) = splitAt ((length l) `quot` 2) l
in merge (mergesort xs) (mergesort ys)
| cbare/Etudes | haskell/sort.hs | apache-2.0 | 650 | 0 | 13 | 173 | 366 | 193 | 173 | 18 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Model.Plan
( selectUserPlansSince
, NewPlan(..), createPlan
, updatePlan
, planDone
, planDoneDay
) where
import Prelude
import Yesod
import Control.Applicative
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON, parseJSON, (.:), ToJSON, toJSON)
import Data.Maybe (isJust)
import Data.Text (Text)
import Data.Time (Day, TimeZone, UTCTime)
import Database.Persist.GenericSql (SqlPersist)
import Model
import Util
instance ToJSON Plan where
toJSON plan = object [
"body" .= planBody plan
, "created_at" .= planCreatedAt plan
, "done_at" .= planDoneAt plan
]
instance ToJSON (Entity Plan) where
toJSON (Entity k p) = object ["id" .= k, "plan" .= p]
selectUserPlansSince :: PersistQuery SqlPersist m => UserId -> UTCTime -> [SelectOpt Plan] -> SqlPersist m [Entity Plan]
selectUserPlansSince userId doneSince = selectList (belongsToUser ++ doneSinceLimit)
where
belongsToUser = [PlanUser ==. userId]
doneSinceLimit = [PlanDoneAt ==. Nothing] ||. [PlanDoneAt >=. Just doneSince]
data NewPlan = NewPlan { newPlanBody :: Text } deriving (Show)
instance FromJSON NewPlan where
parseJSON (Object o) = NewPlan <$> (o .: "body")
parseJSON v = fail $ "can't parse plan: " ++ show v
newPlan :: UserId -> UTCTime -> NewPlan -> Plan
newPlan uid createdAt (NewPlan body) = Plan {
planUser = uid
, planBody = body
, planCreatedAt = createdAt
, planDoneAt = Nothing
}
createPlan :: (MonadIO m, PersistQuery SqlPersist m) => UserId -> NewPlan -> SqlPersist m (Entity Plan)
createPlan uid plan = do
time <- now
let plan' = newPlan uid time plan
planId <- insert plan'
return $ Entity planId plan'
planDone :: Plan -> Bool
planDone = isJust . planDoneAt
planDoneDay :: TimeZone -> Plan -> Maybe Day
planDoneDay tz = fmap (utcToLocalDay tz) . planDoneAt
updatePlan :: PersistQuery SqlPersist m => NewPlan -> PlanId -> SqlPersist m (Bool, Maybe Plan)
updatePlan editedPlan planId = do
mplan <- get planId
case mplan of
Just plan -> do
updated <- updatePlan' editedPlan plan
(updated,) <$> if updated then get planId else return $ Just plan
Nothing -> return (False, Nothing)
where
updatePlan' (NewPlan body) plan
| planBody plan /= body = update planId [PlanBody =. body] >> return True
| otherwise = return False
| samstokes/yesodoro-reboot | Model/Plan.hs | bsd-2-clause | 2,496 | 0 | 15 | 498 | 809 | 426 | 383 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Web.Routes.Quasi.Parse
( -- * Quasi quoter
parseRoutes
, parseRoutesFile
, parseRoutesNoCheck
, parseRoutesFileNoCheck
, Resource (..)
, Piece (..)
) where
import Language.Haskell.TH (appE)
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Quote
import Data.Data (Data,Typeable)
import Data.Maybe
import qualified System.IO as SIO
-- | A quasi-quoter to parse a string into a list of 'Resource's. Checks for
-- overlapping routes, failing if present; use 'parseRoutesNoCheck' to skip the
-- checking. See documentation site for details on syntax.
parseRoutes :: QuasiQuoter
parseRoutes = QuasiQuoter
{ quoteExp = x
, quotePat = y
}
where
x s = do
let res = resourcesFromString s
case findOverlaps res of
[] -> lift res
z -> error $ "Overlapping routes: " ++ unlines (map show z)
y = dataToPatQ (const Nothing) . resourcesFromString
parseRoutesFile :: FilePath -> Q Exp
parseRoutesFile fp = do
s <- qRunIO $ readUtf8File fp
quoteExp parseRoutes s
parseRoutesFileNoCheck :: FilePath -> Q Exp
parseRoutesFileNoCheck fp = do
s <- qRunIO $ readUtf8File fp
quoteExp parseRoutesNoCheck s
readUtf8File :: FilePath -> IO String
readUtf8File fp = do
h <- SIO.openFile fp SIO.ReadMode
SIO.hSetEncoding h SIO.utf8_bom
SIO.hGetContents h
-- | Same as 'parseRoutes', but performs no overlap checking.
parseRoutesNoCheck :: QuasiQuoter
parseRoutesNoCheck = QuasiQuoter
{ quoteExp = x
, quotePat = y
}
where
x = lift . resourcesFromString
y = dataToPatQ (const Nothing) . resourcesFromString
instance Lift Resource where
lift (Resource s ps h) =
[|Resource|] `appE` lift s `appE` lift ps `appE` lift h
-- | A single resource pattern.
--
-- First argument is the name of the constructor, second is the URL pattern to
-- match, third is how to dispatch.
data Resource = Resource String [Piece] [String]
deriving (Read, Show, Eq, Data, Typeable)
-- | A single piece of a URL, delimited by slashes.
--
-- In the case of StaticPiece, the argument is the value of the piece; for the
-- other constructors, it is the name of the parameter represented by this
-- piece. That value is not used here, but may be useful elsewhere.
data Piece = StaticPiece String
| SinglePiece String
| MultiPiece String
deriving (Read, Show, Eq, Data, Typeable)
instance Lift Piece where
lift (StaticPiece s) = [| StaticPiece |] `appE` lift s
lift (SinglePiece s) = [| SinglePiece |] `appE` lift s
lift (MultiPiece s) = [| MultiPiece |] `appE` lift s
-- | Convert a multi-line string to a set of resources. See documentation for
-- the format of this string. This is a partial function which calls 'error' on
-- invalid input.
resourcesFromString :: String -> [Resource]
resourcesFromString =
mapMaybe go . lines
where
go s =
case takeWhile (/= "--") $ words s of
(pattern:constr:rest) ->
let pieces = piecesFromString $ drop1Slash pattern
in Just $ Resource constr pieces rest
[] -> Nothing
_ -> error $ "Invalid resource line: " ++ s
drop1Slash :: String -> String
drop1Slash ('/':x) = x
drop1Slash x = x
piecesFromString :: String -> [Piece]
piecesFromString "" = []
piecesFromString x =
let (y, z) = break (== '/') x
in pieceFromString y : piecesFromString (drop1Slash z)
pieceFromString :: String -> Piece
pieceFromString ('#':x) = SinglePiece x
pieceFromString ('*':x) = MultiPiece x
pieceFromString x = StaticPiece x
findOverlaps :: [Resource] -> [(Resource, Resource)]
findOverlaps = gos . map justPieces
where
justPieces r@(Resource _ ps _) = (ps, r)
gos [] = []
gos (x:xs) = mapMaybe (go x) xs ++ gos xs
go (StaticPiece x:xs, xr) (StaticPiece y:ys, yr)
| x == y = go (xs, xr) (ys, yr)
| otherwise = Nothing
go (MultiPiece _:_, xr) (_, yr) = Just (xr, yr)
go (_, xr) (MultiPiece _:_, yr) = Just (xr, yr)
go ([], xr) ([], yr) = Just (xr, yr)
go ([], _) (_, _) = Nothing
go (_, _) ([], _) = Nothing
go (_:xs, xr) (_:ys, yr) = go (xs, xr) (ys, yr)
| snoyberg/web-routes-quasi | Web/Routes/Quasi/Parse.hs | bsd-2-clause | 4,291 | 2 | 16 | 1,044 | 1,301 | 705 | 596 | 94 | 8 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( withJabaraster
, withDevelAppPort
) where
import Import
import Settings
import Settings.StaticFiles (staticSite)
import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Data.Dynamic (Dynamic, toDyn)
#if DEVELOPMENT
import Yesod.Logger (Logger, logBS, flushLogger)
import Network.Wai.Middleware.RequestLogger (logHandleDev)
#else
import Yesod.Logger (Logger)
import Network.Wai.Middleware.RequestLogger (logStdout)
#endif
import qualified Database.Persist.Base
import Database.Persist.GenericSql (runMigration)
-- Import all relevant handler modules here.
import Handler.Root
import Handler.Thread
import Handler.ThreadDelete
import Handler.Entry
import Handler.EntryDelete
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see
-- the comments there for more details.
mkYesodDispatch "Jabaraster" resourcesJabaraster
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
withJabaraster :: AppConfig DefaultEnv () -> Logger -> (Application -> IO ()) -> IO ()
withJabaraster conf logger f = do
s <- staticSite
dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf)
$ either error return . Database.Persist.Base.loadConfig
Database.Persist.Base.withPool (dbconf :: Settings.PersistConfig) $ \p -> do
Database.Persist.Base.runPool dbconf (runMigration migrateAll) p
let h = Jabaraster conf logger s p
defaultRunner (f . logWare) h
where
#ifdef DEVELOPMENT
logWare = logHandleDev (\msg -> logBS logger msg >> flushLogger logger)
#else
logWare = logStdout
#endif
-- for yesod devel
withDevelAppPort :: Dynamic
withDevelAppPort = toDyn $ defaultDevelApp withJabaraster
| jabaraster/yefib | Application.hs | bsd-2-clause | 2,046 | 0 | 14 | 315 | 381 | 215 | 166 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
module Reflex.Dom.SimpleMDE where
import Control.Lens (makeLenses)
import Control.Monad (when, void)
import Control.Monad.IO.Class
import Control.Lens.Operators ((^.))
import Data.Default
import Data.FileEmbed
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Text (Text)
import Data.ByteString (ByteString)
import Language.Javascript.JSaddle.Object
import Language.Javascript.JSaddle.Types
import Language.Javascript.JSaddle.Classes
import Language.Javascript.JSaddle.Evaluate
import Language.Javascript.JSaddle.Value
import Reflex.Dom.Builder.Class
import Reflex.Dom.Builder.Immediate
import Reflex.Dom.Widget.Basic
import GHCJS.Marshal.Pure (pToJSVal, PToJSVal)
import Reflex.Dom.Widget.Input
import Reflex.Dom.Time (delay)
import Reflex.PostBuild.Class
import Reflex.TriggerEvent.Class
import Reflex
data AutoSave = AutoSave
{ _autoSave_delay :: Int
, _autoSave_uniqueId :: String
}
makeLenses ''AutoSave
data BlockStyles = BlockStyles
{ _blockStyles_bold :: BoldBlockStyle
, _blockStyles_code :: CodeBlockStyle
, _blockStyles_italic :: ItalicBlockStyle
}
instance Default BlockStyles where
def = BlockStyles
{ _blockStyles_bold = def
, _blockStyles_code = def
, _blockStyles_italic = def
}
data BoldBlockStyle = TwoStars | TwoUnderscores
instance Default BoldBlockStyle where
def = TwoStars
data CodeBlockStyle = Ticks | Wave
instance Default CodeBlockStyle where
def = Ticks
data ItalicBlockStyle = SingleStar | SingleUnderscore
instance Default ItalicBlockStyle where
def = SingleStar
data InsertTexts = InsertTexts
{ _insertTexts_horizontalRule :: Maybe (String, String)
, _insertTexts_image :: Maybe (String, String)
, _insertTexts_link :: Maybe (String, String)
, _insertTexts_table :: Maybe (String, String)
}
makeLenses ''InsertTexts
instance Default InsertTexts where
def = InsertTexts
{ _insertTexts_horizontalRule = Nothing
, _insertTexts_image = Nothing
, _insertTexts_link = Nothing
, _insertTexts_table = Nothing
}
data ParsingConfig = ParsingConfig
{ _parsingConfig_allowAtxHeaderWithoutSpace :: Bool
, _parsingConfig_strikethrough :: Bool
, _parsingConfig_underscoresBreakWords :: Bool
}
makeLenses ''ParsingConfig
instance Default ParsingConfig where
def = ParsingConfig
{ _parsingConfig_allowAtxHeaderWithoutSpace = False
, _parsingConfig_strikethrough = True
, _parsingConfig_underscoresBreakWords = False
}
data RenderingConfig = RenderingConfig
{ _renderingConfig_singleLineBreaks :: Bool
, _renderingConfig_codeSyntaxHighlighting :: Bool
}
makeLenses ''RenderingConfig
instance Default RenderingConfig where
def = RenderingConfig
{ _renderingConfig_singleLineBreaks = True
, _renderingConfig_codeSyntaxHighlighting = False
}
data SimpleMDEConfig = SimpleMDEConfig
{ _simpleMDEConfig_autoDownloadFontAwesome :: Maybe Bool
, _simpleMDEConfig_autofocus :: Bool
, _simpleMDEConfig_autosave :: Maybe AutoSave
, _simpleMDEConfig_blockStyles :: BlockStyles
, _simpleMDEConfig_forceSync :: Bool
, _simpleMDEConfig_hideIcons :: [String]
, _simpleMDEConfig_indentWithTabs :: Bool
, _simpleMDEConfig_initialValue :: String
, _simpleMDEConfig_insertTexts :: InsertTexts
, _simpleMDEConfig_lineWrapping :: Bool
, _simpleMDEConfig_parsingConfig :: ParsingConfig
, _simpleMDEConfig_placeholder :: Maybe String
, _simpleMDEConfig_promptURLs :: Bool
, _simpleMDEConfig_renderingConfig :: RenderingConfig
, _simpleMDEConfig_shortcuts :: Maybe [(String, String)]
, _simpleMDEConfig_showIcons :: [String]
, _simpleMDEConfig_spellChecker :: Bool
, _simpleMDEConfig_status :: Maybe [String]
, _simpleMDEConfig_styleSelectedText :: Bool
, _simpleMDEConfig_tabSize :: Int
, _simpleMDEConfig_toolbar :: Maybe [String]
, _simpleMDEConfig_toolbarTips :: Bool
}
makeLenses ''SimpleMDEConfig
instance Default SimpleMDEConfig where
def = SimpleMDEConfig
{ _simpleMDEConfig_autoDownloadFontAwesome = Nothing
, _simpleMDEConfig_autofocus = False
, _simpleMDEConfig_autosave = Nothing
, _simpleMDEConfig_blockStyles = def
, _simpleMDEConfig_forceSync = False
, _simpleMDEConfig_hideIcons = []
, _simpleMDEConfig_indentWithTabs = True
, _simpleMDEConfig_initialValue = ""
, _simpleMDEConfig_insertTexts = def
, _simpleMDEConfig_lineWrapping = True
, _simpleMDEConfig_parsingConfig = def
, _simpleMDEConfig_placeholder = Nothing
, _simpleMDEConfig_promptURLs = False
, _simpleMDEConfig_renderingConfig = def
, _simpleMDEConfig_shortcuts = Nothing
, _simpleMDEConfig_showIcons = []
, _simpleMDEConfig_spellChecker = True
, _simpleMDEConfig_status = Nothing
, _simpleMDEConfig_styleSelectedText = True
, _simpleMDEConfig_tabSize = 2
, _simpleMDEConfig_toolbar = Nothing
, _simpleMDEConfig_toolbarTips = True
}
#ifdef ghcjs_HOST_OS
-- compiled with ghcjs; simpleMDE is bundled and executed by ghcjs
-- due to the js-sources entry in simple-mde.cabal. Thus
-- we don't need to do anything here.
importSimpleMdeJs :: JSM ()
importSimpleMdeJs = return ()
#else
-- Compiled with ghc, running in browser via jsaddle
-- As opposed to ghcjs, this setup doesn't automatically bundle
-- and run dependencies listed under js-sources in simple-mde.cabal
-- Thus we need to bundle the source via template-haskell and run
-- it via eval the first time this component is included.
-- | The contents of the upstream simpleMde js as a Text value.
simpleMdeCode :: Text
simpleMdeCode = $(embedStringFile "jslib/simplemde-markdown-editor/dist/simplemde.min.js")
importSimpleMdeJs :: JSM ()
importSimpleMdeJs = do
simpleMDE <- jsg ("SimpleMDE" :: String)
-- stop importing if it's already been imported
notYetLoaded <- valIsUndefined simpleMDE
when notYetLoaded $
void $ eval simpleMdeCode
#endif
simpleMdeCss :: ByteString
simpleMdeCss = $(embedFile "jslib/simplemde-markdown-editor/dist/simplemde.min.css")
startSimpleMDE :: PToJSVal a => Text -> a -> JSM JSVal
startSimpleMDE initialVal el = do
conf <- obj
(conf <# ("element" :: Text)) (pToJSVal el)
(conf <# ("initialValue" :: Text)) initialVal
new (jsg ("SimpleMDE" :: Text)) (toJSVal conf)
simpleMDEWidget :: (
MonadJSM m,
DomBuilder t m,
DomBuilderSpace m ~ GhcjsDomSpace,
TriggerEvent t m,
MonadHold t m,
PostBuild t m,
PerformEvent t m,
MonadJSM (Performable m)
) => Text -> m (Dynamic t Text)
simpleMDEWidget initialValue =
elClass "div" "simplemde-root" $ do
liftJSM importSimpleMdeJs
-- txtArea <- fst <$> (elClass' "textarea" "simplemde-textarea" $ text initialValue)
txtArea <- fst <$> (elClass' "textarea" "simplemde-textarea" $ blank)
let mdeEl = _element_raw txtArea
simpleMDEObj <- liftJSM $ startSimpleMDE initialValue mdeEl
-- workaround for https://github.com/nestor-qa/nestor/issues/98
postBuildE <- getPostBuild
delayedPostBuildE <- delay 1 postBuildE
let refreshE = (refresh simpleMDEObj) <$ delayedPostBuildE
performEvent refreshE
mdeChangeE <- getChangeEvent simpleMDEObj
holdDyn initialValue mdeChangeE
refresh :: MonadJSM m => JSVal -> m ()
refresh simpleMDEObj = do
liftJSM $ simpleMDEObj ! ("codemirror" :: Text) ^. js0 ("refresh" :: Text)
return ()
setVal :: MonadJSM m => JSVal -> Text -> m ()
setVal simpleMDEObj initialValue = do
liftJSM $ simpleMDEObj ^. js1 ("value" :: Text) initialValue
return ()
getChangeEvent :: (MonadJSM m, TriggerEvent t m) => JSVal -> m (Event t Text)
getChangeEvent simpleMDEObj = do
let codemirror = simpleMDEObj ! ("codemirror"::Text)
(ev, trigger) <- newTriggerEvent
liftJSM $ do
funJsv <- function $ \ _ _ args -> do
-- a <- parseEvent (fromMaybe jsNull $ listToMaybe args)
txtVal <- liftJSM $ simpleMDEObj ^. js0 ("value" :: Text)
(maybeTxt :: Maybe Text) <- liftJSM $ fromJSVal txtVal
let txt = fromMaybe "" maybeTxt
liftIO $ trigger txt
void $ codemirror ^. js2 ("on" :: Text) ("change" :: Text) funJsv
pure ev
-- adapted from https://github.com/ConferHealth/reflex-stripe/blob/1842b100e6275bbb343ed9be4161bb8821299f80/src/Reflex/Stripe/Elements/Types.hs#L186 courtesy of dridus
getElementEvent :: (MonadJSM m, TriggerEvent t m, MakeObject el) => Text -> (JSVal -> JSM a) -> el -> m (Event t a)
getElementEvent eventType parseEvent el = do
-- FIXME would newEventWithLazyTriggerWithOnComplete be good to use here?
(ev, trigger) <- newTriggerEvent
liftJSM $ do
funJsv <- function $ \ _ _ args -> do
a <- parseEvent (fromMaybe jsNull $ listToMaybe args)
liftIO $ trigger a
-- FIXME Function never gets explicitly freed
void $ el ^. js2 ("on" :: Text) eventType funJsv
pure ev
| Haskell-Praxis/hakyll-cms | simple-mde/src/Reflex/Dom/SimpleMDE.hs | bsd-2-clause | 10,026 | 0 | 19 | 2,565 | 1,847 | 1,027 | 820 | 198 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Stashh.Model.Type where
import Control.Applicative
import Data.Maybe
import qualified Data.Vector as V
import Data.Aeson
import Data.List (transpose, intercalate, intersperse, stripPrefix)
data Link = Link
{ linkUrl :: String
, linkRel :: String
}
deriving (Show, Eq)
instance FromJSON Link where
parseJSON (Object v) = Link
<$> v .: "url"
<*> v .: "rel"
parseJSON _ = fail "Link"
data Member = Member
{ user :: User
, role :: String
, approved ::Bool
} deriving (Show, Eq)
instance FromJSON Member where
parseJSON (Object v) = Member
<$> v .: "user"
<*> v .: "role"
<*> v .: "approved"
parseJSON _ = fail "Member"
data User = User
{ userName :: String
, emailAddress :: String
, userId :: Int
, displayName :: String
, active :: Bool
, userSlug :: Maybe String
} deriving (Show, Eq)
instance FromJSON User where
parseJSON (Object v) = User
<$> v .: "name"
<*> v .: "emailAddress"
<*> v .: "id"
<*> v .: "displayName"
<*> v .: "active"
<*> v .:? "slug"
parseJSON _ = fail "User"
data Ref = Ref
{ refId :: String
, repository :: ShortRepository
} deriving (Show, Eq)
instance FromJSON Ref where
parseJSON (Object v) = Ref
<$> v .: "id"
<*> v .: "repository"
parseJSON _ = fail "Ref"
data ShortRepository = ShortRepository
{ repositorySlug :: String
, repositoryName :: Maybe String
, shortProject :: ShortProject
} deriving (Show, Eq)
instance FromJSON ShortRepository where
parseJSON (Object v) = ShortRepository
<$> v .: "slug"
<*> v .:? "name"
<*> v .: "project"
parseJSON _ = fail "ShortRepository"
data ShortProject = ShortProject
{ shortProjectKey :: String
} deriving (Show, Eq)
instance FromJSON ShortProject where
parseJSON (Object v) = ShortProject
<$> v .: "key"
parseJSON _ = fail "ShortProject"
userNameFromMember :: Member -> String
userNameFromMember = userName . user
showRefId :: Ref -> String
showRefId ref = fromMaybe (refId ref) $ stripPrefix "refs/heads/" (refId ref)
| yuroyoro/stashh | src/Stashh/Model/Type.hs | bsd-3-clause | 2,555 | 0 | 17 | 944 | 671 | 363 | 308 | 75 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.PL.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Locale
import Duckling.Ordinal.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale PL Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples =
examples (OrdinalData 4)
[ "4ty"
, "czwarty"
]
| facebookincubator/duckling | Duckling/Ordinal/PL/Corpus.hs | bsd-3-clause | 661 | 0 | 8 | 127 | 111 | 70 | 41 | 16 | 1 |
{-# LANGUAGE TypeFamilies, FlexibleInstances, GADTs, StandaloneDeriving #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : ForSyDe.Atom.MoC.DE.Core
-- Copyright : (c) George Ungureanu, KTH/ICT/ESY 2016
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : ugeorge@kth.se
-- Stability : experimental
-- Portability : portable
--
-- This module implements the core semantics of the DE MoC.
-----------------------------------------------------------------------------
module ForSyDe.Atom.MoC.DE.Core where
import ForSyDe.Atom.MoC
import ForSyDe.Atom.MoC.TimeStamp
import ForSyDe.Atom.Utility.Tuple (($$),($$$),($$$$))
import Prelude hiding (until)
-- | Type synonym for a base DE signal as a stream of 'DE' events, where the type of
-- tags has not been determined yet. In designs, it is advised to define a type alias
-- for signals, using an appropriate numerical type for tags, e.g.
--
-- > import ForSyDe.Atom.MoC.DE hiding (Signal) -- hide provided alias, to use your own
-- >
-- > type Signal a = SignalBase Int a
type SignalBase t a = Stream (DE t a)
-- | Convenience alias for a DE signal, where tags are represented using our exported
-- 'TimeStamp' type.
type Signal a = SignalBase TimeStamp a
-- | The DE event. It identifies a discrete event signal. The type of the tag system
-- needs to satisfy all of the three properties, as suggested by the type constraints
-- imposed on it:
--
-- * it needs to be a numerical type, to express value 0 (global start) and every
-- representable number needs to have an additive inverse.
--
-- * it needs to be unambiguously comparable (defines a total order).
--
-- * it needs to unambiguously define an equality operation.
--
-- Due to these properties not all numerical types can represent DE tags. A typical
-- example of inappropriate representation is 'Float'.
data DE t a where
DE :: (Num t, Ord t, Eq t)
=> { tag :: t, -- ^ timestamp
val :: a -- ^ the value
} -> DE t a
deriving instance (Num t, Ord t, Eq t, Eq t, Eq a) => Eq (DE t a)
-- | Implenents the execution semantics for the DE MoC atoms.
instance (Num t, Ord t, Eq t) => MoC (DE t) where
type Fun (DE t) a b = a -> b
type Ret (DE t) b = b
---------------------
(-.-) = fmap . fmap
---------------------
_ -*- NullS = NullS
NullS -*- _ = NullS
(f:-fs) -*- (x:-xs) = f <*> x :- comb f x fs xs
where comb pf px s1@(f :- fs) s2@(x :- xs)
| tag f == tag x = f %> f <*> x :- comb f x fs xs
| tag f < tag x = f %> f <*> px :- comb f px fs s2
| tag f > tag x = x %> pf <*> x :- comb pf x s1 xs
comb _ px (f :- fs) NullS = f %> f <*> px :- comb f px fs NullS
comb pf _ NullS (x :- xs) = x %> pf <*> x :- comb pf x NullS xs
comb _ _ NullS NullS = NullS
---------------------
(-*) = id
---------------------
(DE _ v :- _) -<- xs = pure v :- xs
---------------------
(_ :- DE d _ :- _) -&- xs = (\(DE t v) -> DE (t + d) v) <$> xs
(_ :- NullS) -&- _ = error "[MoC.DE] signal delayed to infinity"
---------------------
-- | Shows the event with tag @t@ and value @v@ as @v\@t@.
instance (Show a, Show t) => Show (DE t a) where
showsPrec _ (DE t x) = (++) ( show x ++ "@" ++ show t )
-- | Reads the string of type @v\@t@ as an event @DE t v@.
instance (Read a,Read t, Num t, Ord t, Eq t, Eq t) => Read (DE t a) where
readsPrec _ x = [ (DE tg val, r2)
| (val,r1) <- reads $ takeWhile (/='@') x
, (tg, r2) <- reads $ tail $ dropWhile (/='@') x ]
-- | Allows for mapping of functions on a DE event.
instance (Num t, Ord t, Eq t) => Functor (DE t) where
fmap f (DE t a) = DE t (f a)
-- | Allows for lifting functions on a pair of DE events.
instance (Num t, Ord t, Eq t) => Applicative (DE t) where
pure = DE 0
(DE tf f) <*> (DE _ x) = DE tf (f x)
-----------------------------------------------------------------------------
unit :: (Num t, Ord t, Eq t) => (t, a) -> SignalBase t a
-- | Wraps a (tuple of) pair(s) @(tag, value)@ into the equivalent
-- unit signal(s). A unit signal is a signal with one event with the
-- period @tag@ carrying @value@.
--
-- Helpers: @unit|unit[2-4]@.
unit2 :: (Num t, Ord t, Eq t)
=> ((t,a1),(t, a2))
-> (SignalBase t a1, SignalBase t a2)
unit3 :: (Num t, Ord t, Eq t)
=> ((t,a1),(t, a2),(t, a3))
-> (SignalBase t a1, SignalBase t a2, SignalBase t a3)
unit4 :: (Num t, Ord t, Eq t)
=> ((t,a1),(t, a2),(t, a3),(t, a4))
-> (SignalBase t a1, SignalBase t a2, SignalBase t a3, SignalBase t a4)
unit (t,v) = (DE 0 v :- DE t v :- NullS)
unit2 = ($$) (unit,unit)
unit3 = ($$$) (unit,unit,unit)
unit4 = ($$$$) (unit,unit,unit,unit)
-- | Creates an infinite signal.
infinite :: (Num t, Ord t, Eq t) => a -> SignalBase t a
infinite v = DE 0 v :- NullS
-- | Transforms a list of tuples @(tag, value)@ into a DE
-- signal. Checks if it is well-formed.
signal :: (Num t, Ord t, Eq t) => [(t, a)] -> SignalBase t a
signal = checkSignal . stream . fmap (\(t, v) -> DE t v)
-- | Takes the first part of the signal util a given timestamp. The
-- last event of the resulting signal is at the given timestamp and
-- carries the previous value. This utility is useful when plotting
-- a signal, to specify the interval of plotting.
until :: (Num t, Ord t, Eq t) => t -> SignalBase t a -> SignalBase t a
until _ NullS = NullS
until u (DE t v:-NullS)
| t < u = DE t v :- DE u v :- NullS
| otherwise = DE u v :- NullS
until u (DE t v:-xs)
| t < u = DE t v :- until u xs
| otherwise = DE u v :- NullS
-- | Reads a signal from a string and checks if it is well-formed.
-- Like with the @read@ function from @Prelude@, you must specify the
-- type of the signal.
--
-- >>> readSignal "{ 1@0, 2@2, 3@5, 4@7, 5@10 }" :: Signal Int
-- {1@0s,2@2s,3@5s,4@7s,5@10s}
--
-- Incorrect usage (not covered by @doctest@):
--
-- > λ> readSignal "{ 1@0, 2@2, 3@5, 4@10, 5@7 }" :: Signal Int
-- > {1@0s,2@2s,3@5s*** Exception: [MoC.DE] malformed signal
-- > λ> readSignal "{ 1@1, 2@2, 3@5, 4@7, 5@10 }" :: Signal Int
-- > *** Exception: [MoC.DE] signal does not start from global 0
readSignal :: (Num t, Ord t, Eq t, Read t, Read a) => String -> SignalBase t a
readSignal s = checkSignal $ read s
-- | Checks if a signal is well-formed or not, according to the DE MoC
-- interpretation in ForSyDe-Atom.
checkSignal NullS = NullS
checkSignal s@(x:-_)
| tag x == 0 = checkOrder s
| otherwise = error "[MoC.DE] signal does not start from global 0"
where
checkOrder NullS = NullS
checkOrder (x:-NullS) = (x:-NullS)
checkOrder (x:-y:-xs) | tag x < tag y = x :-checkOrder (y:-xs)
| otherwise = error "[MoC.DE] malformed signal"
-----------------------------------------------------------------------------
-- These functions are not exported and are used internally.
infixl 7 %>
(DE t _) %> (DE _ x) = DE t x
-----------------------------------------------------------------------------
| forsyde/forsyde-atom | src/ForSyDe/Atom/MoC/DE/Core.hs | bsd-3-clause | 7,182 | 0 | 12 | 1,732 | 2,077 | 1,121 | 956 | -1 | -1 |
{-|
Module : Example.Main
Description : Show various examples.
Copyright : (c) Alexander Vieth, 2016
Licence : BSD3
Maintainer : aovieth@gmail.com
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Arrows #-}
import Prelude hiding ((.), id, div)
import Control.Category
import Control.Arrow
import Data.Void
import qualified Data.Text as T
import GHCJS.DOM
import GHCJS.DOM.Window
import GHCJS.DOM.Document
import Reactive.Banana.Combinators
import Reactive.Banana.Frameworks
import Reactive.Sequence
import Reactive.DOM.Node
import Reactive.DOM.Widget.Common
import Examples.Calculator
main :: IO ()
main = runWebGUI $ \webView -> do
Just document <- webViewGetDomDocument webView
Just body <- getBody document
let networkDescription :: MomentIO ()
networkDescription = do
let calc = div calculator `modifyr` (arr (const False) >>> makeDraggable)
(_, calculatorEvent) <- render document body (ui calc)
reactimate (Prelude.print <$> calculatorEvent)
pure ()
network <- compile networkDescription
actuate network
pure ()
| avieth/reactive-dom | Examples/Main.hs | bsd-3-clause | 1,186 | 0 | 22 | 238 | 272 | 145 | 127 | 29 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS -Wall -fno-warn-unused-do-bind #-}
module Main (
main
) where
import Control.Applicative ((<$>))
import Control.Monad.Reader
import Data.IORef
import Data.Maybe
import qualified Graphics.UI.Gtk as G
import System.Environment (getArgs)
import Paths_heapscope_cairo as My
import Scope.Layer
import Scope.Types
import Scope.Cairo
import HeapScope.Scope
----------------------------------------------------------------------
windowWidth, windowHeight :: Int
windowWidth = 500
windowHeight = 500
main :: IO ()
main = do
_ <- G.initGUI
args <- getArgs
window <- G.windowNew
G.widgetSetSizeRequest window windowWidth windowHeight
G.widgetSetAppPaintable window True
G.widgetSetDoubleBuffered window True
vbox <- G.vBoxNew False 0
G.containerAdd window vbox
ui <- G.uiManagerNew
filename <- My.getDataFileName "data/actions.ui"
G.uiManagerAddUiFromFile ui filename
let getWidget = fmap fromJust . G.uiManagerGetWidget ui
-- Menubar
fma <- G.actionNew "FMA" "File" Nothing Nothing
ema <- G.actionNew "EMA" "Edit" Nothing Nothing
vma <- G.actionNew "VMA" "View" Nothing Nothing
hma <- G.actionNew "HMA" "Help" Nothing Nothing
-- File menu
newa <- G.actionNew "NEWA" "New" (Just "Just a Stub") (Just G.stockNew)
newa `G.on` G.actionActivated $ myNew
opena <- G.actionNew "OPENA" "Open" (Just "Just a Stub") (Just G.stockOpen)
savea <- G.actionNew "SAVEA" "Save" (Just "Just a Stub") (Just G.stockSave)
saveasa <- G.actionNew "SAVEASA" "Save As" (Just "Just a Stub") (Just G.stockSaveAs)
quita <- G.actionNew "QUITA" "Quit" (Just "Just a Stub") (Just G.stockQuit)
let fChooser action label = G.fileChooserDialogNew Nothing (Just window) action
[(G.stockCancel, G.ResponseCancel), (label, G.ResponseAccept)]
openDialog <- fChooser G.FileChooserActionOpen G.stockOpen
demoPath <- My.getDataFileName "demo"
G.fileChooserSetCurrentFolder openDialog demoPath
opena `G.on` G.actionActivated $ G.widgetShow openDialog
saveDialog <- fChooser G.FileChooserActionSave G.stockSave
savea `G.on` G.actionActivated $ G.widgetShow saveDialog
saveasa `G.on` G.actionActivated $ G.widgetShow saveDialog
-- Edit menu
cut1 <- G.actionNew "cut1" "Cut" (Just "Just a Stub") (Just G.stockCut)
cut1 `G.on` G.actionActivated $ myCut
copy1 <- G.actionNew "copy1" "Copy" (Just "Just a Stub") (Just G.stockCopy)
copy1 `G.on` G.actionActivated $ myCopy
paste1 <- G.actionNew "paste1" "Paste" (Just "Just a Stub") (Just G.stockPaste)
paste1 `G.on` G.actionActivated $ myPaste
delete1 <- G.actionNew "delete1" "Delete" (Just "Just a Stub") (Just G.stockDelete)
delete1 `G.on` G.actionActivated $ myDelete
-- Help menu
-- About dialog
aboutdialog <- G.aboutDialogNew
abouta <- G.actionNew "ABOUTA" "About" (Just "Just a Stub") Nothing
abouta `G.on` G.actionActivated $ G.widgetShow aboutdialog
aboutdialog `G.on` G.response $ const $ G.widgetHide aboutdialog
-- Action group
agr <- G.actionGroupNew "AGR"
mapM_ (G.actionGroupAddAction agr) [fma, ema, vma, hma]
mapM_ (\act -> G.actionGroupAddActionWithAccel agr act Nothing)
[ newa, opena, savea, saveasa, quita
, cut1, copy1, paste1, delete1
, abouta
]
G.uiManagerInsertActionGroup ui agr 0
menubar <- getWidget "/ui/menubar1"
G.boxPackStart vbox menubar G.PackNatural 0
scopeRef <- scopeCairoNew
ViewCairo{..} <- viewUI . view <$> readIORef scopeRef
quita `G.on` G.actionActivated $ myQuit scopeRef window
mapM_ (modifyIORefM scopeRef . addLayersFromFile scopeReadHeapProfile) args
openDialog `G.on` G.response $ myFileOpen scopeRef openDialog
saveDialog `G.on` G.response $ myFileSave scopeRef saveDialog
G.boxPackStart vbox frame G.PackGrow 0
scopeCairoDefaultEvents scopeRef
statusbar <- G.statusbarNew
G.boxPackStart vbox statusbar G.PackNatural 0
G.onDestroy window G.mainQuit
G.widgetShowAll window
G.mainGUI
myQuit :: G.WidgetClass cls => IORef (Scope ViewCairo) -> cls -> IO ()
myQuit scopeRef window = do
scopeModifyMUpdate scopeRef scopeClose
G.widgetDestroy window
myNew :: IO ()
myNew = putStrLn "New"
myFileOpen :: IORef (Scope ViewCairo) -> G.FileChooserDialog -> G.ResponseId -> IO ()
myFileOpen scopeRef fcdialog response = do
case response of
G.ResponseAccept -> do
Just filename <- G.fileChooserGetFilename fcdialog
scopeModifyMUpdate scopeRef (addLayersFromFile scopeReadHeapProfile filename)
_ -> return ()
G.widgetHide fcdialog
myFileSave :: IORef (Scope ViewCairo) -> G.FileChooserDialog -> G.ResponseId -> IO ()
myFileSave scopeRef fcdialog response = do
case response of
G.ResponseAccept -> do
Just filename <- G.fileChooserGetFilename fcdialog
writePng filename scopeRef
_ -> return ()
G.widgetHide fcdialog
myCut :: IO ()
myCut = putStrLn "Cut"
myCopy :: IO ()
myCopy = putStrLn "Copy"
myPaste :: IO ()
myPaste = putStrLn "Paste"
myDelete :: IO ()
myDelete = putStrLn "Delete"
| kfish/heapscope-cairo | src/GUI.hs | bsd-3-clause | 5,032 | 0 | 14 | 874 | 1,647 | 798 | 849 | 115 | 2 |
{-# LANGUAGE QuasiQuotes #-}
{-@ LIQUID "--no-termination "@-}
{-@ LIQUID "--short-names "@-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude (liquidAssert)
import Data.IORef
[lq| data variance IO bivariant |]
[lq| data variance IORef bivariant |]
job :: IO ()
job = do
p <- newIORef (0 :: Int)
writeIORef p 10
v <- readIORef p
liquidAssert (v >= 0) $ return ()
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/contra0.hs | bsd-3-clause | 392 | 0 | 10 | 76 | 109 | 59 | 50 | 12 | 1 |
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Astro.LunarCoordinates (lunarCoordinates) where
import Astro.Time
import Astro.Coords
import Astrodynamics (r_Earth)
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.LinearAlgebra
import Numeric.Units.Dimensional.LinearAlgebra.PosVel (CPos, Sph (Sph), toZenith)
import Numeric.Units.Dimensional.NonSI (century)
import qualified Prelude
{- |
This module implements the "Low-precision formulae for geocentric
coordinates of the Moon" from page D22 of The Astronomical Almanac
(2009).
According to the almanac (2018), during the period 1900 to 2100
the errors will rarely exceed
0.3° in ecliptic longitude,
0.2° in ecliptic latitude,
0.003° in horizontal parallax,
0.001° in semidiameter,
0.2 Earth radii in distance,
0.3° in right ascension
and 0.2° in declination.
The coordinate system of the computation result is not well
specified. However, with the given accuracy any Earth-centered
inertial coordinate system should do.
-}
-- | Computes the Moon's coordinates to an accuracy of about 0.3°
-- during the period of 1900 to 2100.
lunarCoordinates :: forall a . RealFloat a => E UT1 a -> Coord GCRS a
lunarCoordinates ut1 = C (x <: y <:. z)
where
lambda = lunarEclipticLongitude ut1
beta = lunarEclipticLatitude ut1
r = lunarDistance0 ut1
-- Geocentric direction cosines (l, m, n).
cosine_l = cos beta * cos lambda -- cos decl * cos ra
cosine_m = 0.9175 *~ one * cos beta * sin lambda - 0.3978 *~ one * sin beta -- = cos decl * sin ra
cosine_n = 0.3978 *~ one * cos beta * sin lambda + 0.9175 *~ one * sin beta -- = sin decl
-- Geocentric rectangular coordinates
x, y, z :: Length a
x = r * cosine_l -- = r * cos decl * cos ra
y = r * cosine_m -- = r * cos decl * sin ra
z = r * cosine_n -- = r * sin decl
{-
-- Right ascension and declination are referred to the mean equator and equinox of date.
rightAscension_alpha = atan2 cosine_m cosine_l :: PlaneAngle a
declination_delta = asin cosine_n :: PlaneAngle a
spherical = S $ Sph r (toZenith declination_delta) rightAscension_alpha
-}
lunarEclipticLongitude :: RealFloat a => E UT1 a -> PlaneAngle a
lunarEclipticLongitude ut1 = let t = sinceJ2000' ut1 in
deg 218.32 + dpc 481_267.881 * t
+ deg 6.29 * sin (deg 135.0 + dpc 477_198.87 * t) - deg 1.27 * sin (deg 259.3 - dpc 413_335.36 * t)
+ deg 0.66 * sin (deg 235.7 + dpc 890_534.22 * t) + deg 0.21 * sin (deg 269.9 + dpc 954_397.74 * t)
- deg 0.19 * sin (deg 357.5 + dpc 035_999.05 * t) - deg 0.11 * sin (deg 186.5 + dpc 966_404.03 * t)
lunarEclipticLatitude :: RealFloat a => E UT1 a -> PlaneAngle a
lunarEclipticLatitude ut1 = let t = sinceJ2000' ut1 in _0
+ deg 5.13 * sin (deg 093.3 + dpc 483_202.02 * t) + deg 0.28 * sin (deg 228.2 + dpc 960_400.89 * t)
- deg 0.28 * sin (deg 235.7 + dpc 006_002.15 * t) - deg 0.17 * sin (deg 217.6 - dpc 407_332.21 * t)
-- | The horizontal parallax of the Moon as seen from the center of Earth.
lunarHorizontalParallax0 :: RealFloat a => E UT1 a -> PlaneAngle a
lunarHorizontalParallax0 ut1 = let t = sinceJ2000' ut1 in _0
+ deg 0.9508
+ deg 0.0518 * cos (deg 135.0 + dpc 477_198.87 * t) + deg 0.0095 * cos (deg 259.3 - dpc 413_335.36 * t)
+ deg 0.0078 * cos (deg 235.7 + dpc 890_534.22 * t) + deg 0.0028 * cos (deg 269.9 + dpc 954_397.74 * t)
-- | The semidiameter (SD) of the Moon as seen from the center of Earth.
lunarSemidiameter0 :: RealFloat a => E UT1 a -> PlaneAngle a
lunarSemidiameter0 ut1 = 0.0274 *~ one * lunarHorizontalParallax0 ut1
-- | The distance to the Moon from the center of Earth.
lunarDistance0 :: RealFloat a => E UT1 a -> Length a
lunarDistance0 ut1 = r_Earth / sin (lunarHorizontalParallax0 ut1)
-- | Convenience function for angles in degrees.
deg :: Floating a => a -> PlaneAngle a
deg x = x *~ degree
-- | Convenience function for angular velocity in degrees per Julian century.
dpc :: Floating a => a -> AngularVelocity a
dpc x = x *~ (degree / century)
{-
-- | The horizontal parallax of the Moon as seen from the given coordinates.
lunarHorizontalParallax :: RealFloat a => Coord GCRS a -> E UT1 a -> PlaneAngle a
lunarHorizontalParallax xyz ut1 = undefined
-- | The semidiameter (SD) of the Moon as seen from the given coordinates.
lunarSemidiameter :: forall a . Coord GCRS a -> E UT1 a -> PlaneAngle a
lunarSemidiameter xyz ut1 = undefined
-}
| bjornbm/astro | src/Astro/LunarCoordinates.hs | bsd-3-clause | 4,454 | 0 | 22 | 902 | 1,061 | 523 | 538 | 46 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
module Snap.Snaplet.ActionLog.Resource
( actionLogR
, indexH
, showH
, actionLogSplices
, actionLogISplices
) where
------------------------------------------------------------------------------
import Blaze.ByteString.Builder.Char8
import Control.Applicative as A
import Control.Error
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Syntax as MS
import Data.Monoid as Monoid
import qualified Data.Readable as R
import Data.Semigroup as Semigroup
import Data.Text (Text)
import qualified Data.Text as T
import Database.Persist
import Heist
import Heist.Compiled
import qualified Heist.Interpreted as I
import Snap
import Snap.Restful
import Snap.Snaplet.ActionLog.API
import Snap.Snaplet.ActionLog.Types
import Snap.Snaplet.Heist.Generic
import Snap.Snaplet.Persistent
import Text.Digestive
import qualified Text.Digestive as Form
import qualified Text.Digestive.Heist as DHI
import Text.Digestive.Heist.Compiled
import Text.Digestive.Snap hiding (method)
import qualified Text.Digestive.Snap as Form
import qualified Text.XmlHtml as X
------------------------------------------------------------------------------
snapletRender :: HasHeist b => ByteString -> Handler b v ()
snapletRender name = do
root <- getSnapletRootURL
let p = B.intercalate "/" $ filter (not . B.null) [root, name]
gRender p
indexH :: HasHeist b => Handler b v ()
indexH = snapletRender "index"
showH :: HasHeist b => Handler b v ()
showH = snapletRender "show"
-------------------------------------------------------------------------------
-- | A restful-snap resource for the action log CRUD.
actionLogR :: Resource
actionLogR = Resource
{ rName = "actionlog"
, rRoot = ""
, rResourceEndpoints = []
, rItemEndpoints = []
}
data LogFilter = LogFilter
{ filterUser :: Maybe Int
, filterEntity :: Maybe Text
, filterEntityId :: Maybe Int
, filterAction :: Maybe ActionType
} deriving (Show)
instance Semigroup LogFilter where
(LogFilter u1 e1 i1 a1) <> (LogFilter u2 e2 i2 a2) =
LogFilter
(Semigroup.getFirst $ (Semigroup.First u1) Semigroup.<> (Semigroup.First u2))
(Semigroup.getFirst $ (Semigroup.First e1) Semigroup.<> (Semigroup.First e2))
(Semigroup.getFirst $ (Semigroup.First i1) Semigroup.<> (Semigroup.First i2))
(Semigroup.getFirst $ (Semigroup.First a1) Semigroup.<> (Semigroup.First a2))
instance Monoid.Monoid LogFilter where
mempty = LogFilter Nothing Nothing Nothing Nothing
mappend = (Semigroup.<>)
mkFilters :: LogFilter -> [Filter LoggedAction]
mkFilters (LogFilter u e eid a) =
maybe [] (\x -> [LoggedActionUserId ==. x]) u ++
maybe [] (\x -> [LoggedActionEntityName ==. x]) e ++
maybe [] (\x -> [LoggedActionEntityId ==. x]) eid ++
maybe [] (\x -> [LoggedActionAction ==. x]) a
disableOnJust :: (Maybe a -> Form v m b) -> Maybe a -> Form v m b
disableOnJust f Nothing = f Nothing
disableOnJust f def = disable $ f def
------------------------------------------------------------------------------
-- |
logFilterForm :: HasActionLog m
=> Bool
-> Maybe LogFilter -> Form Text m LogFilter
logFilterForm isDisabling d = monadic $ do
entities <- getTenantEntities
let entityPairs = noFilter : map (\x -> (Just x,x)) entities
uids <- getTenantUids
names <- mapM alGetName uids
let userPairs = noFilter : (map firstJust $ zip uids names)
return $ LogFilter
A.<$> "user" .: choice userPairs ?$ (filterUser <$> d)
<*> "entity" .: choice entityPairs ?$ (filterEntity <$> d)
<*> "entity-id" .: optionalStringRead "id must be an int" ?$
(filterEntityId =<< d)
<*> "action" .: choice actions ?$ (filterAction <$> d)
where
noFilter = (Nothing, "Any")
firstJust (k,u) = (Just k, u)
actions = noFilter : map (\x -> (Just x,T.pack $ show x)) [minBound..maxBound]
-- An infix function here makes the syntax nice
infixr 6 ?$
(?$) :: (Maybe a -> Form v m b) -> Maybe a -> Form v m b
(?$) = if isDisabling then disableOnJust else ($)
logFilterFormName :: Text
logFilterFormName = "log-filter-form"
-------------------------------------------------------------------------------
runLogFilterForm :: (HasActionLog m, MonadSnap m)
=> Bool -> Maybe LogFilter -> m (View Text, Maybe LogFilter)
runLogFilterForm isDisabling def =
runFormWith cfg logFilterFormName (logFilterForm isDisabling def)
where
cfg = defaultSnapFormConfig { Form.method = Just Form.Post }
-------------------------------------------------------------------------------
-- Splices
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
actionLogSplices :: (HasActionLog n, MonadSnap n)
=> Resource -> Splices (Splice n)
actionLogSplices r = mconcat
[ MS.mapV ($ mempty) (coupledSplices r False)
, splices ]
where
splices = do
"actionDetails" MS.## actionViewSplice r
"defaultActions" MS.## defaultActionsSplice r
coupledSplices :: (HasActionLog n, MonadSnap n)
=> Resource
-> Bool
-> Splices (RuntimeSplice n LogFilter -> Splice n)
coupledSplices r b = do
"actionlogListing" MS.## actionsSplice r (runLogFilterForm b)
"actionlogFilterForm" MS.## logFilterFormSplice (runLogFilterForm b)
getFilterFunc :: Monad n => HeistT n IO (RuntimeSplice n LogFilter)
getFilterFunc = do
n <- getParamNode
attrFunc <- runAttributesRaw $ X.elementAttrs n
return $ do
as <- attrFunc
return $ filterCommon as
filterCommon :: [(Text, Text)] -> LogFilter
filterCommon as =
LogFilter
(R.fromText =<< lookup "uid" as)
(lookup "entity" as)
(R.fromText =<< lookup "entity-id" as)
(R.fromText =<< lookup "action" as)
------------------------------------------------------------------------------
-- | This is a splice that wraps both the action log filter form splice and
-- the listing splice. It handles greying out the appropriate form fields and
-- limiting the things in the listing.
defaultActionsSplice :: (MonadSnap m, HasActionLog m) => Resource -> Splice m
defaultActionsSplice r = do
filterFunc <- getFilterFunc
withSplices runChildren (coupledSplices r True) filterFunc
actionFromId :: (MonadSnap m, HasPersistPool m)
=> m (Maybe (Entity LoggedAction))
actionFromId = runMaybeT $ do
idBS <- MaybeT $ getParam "id"
_id <- R.fromBS idBS
let key = mkKey _id
action <- MaybeT $ getLoggedAction key
return $ Entity key action
actionViewSplice :: (HasActionLog n, MonadSnap n) => Resource -> Splice n
actionViewSplice r = manyWithSplices runChildren (actionSplices r) $ do
ma <- lift actionFromId
return $ maybe [] (:[]) ma
actionsSplice :: HasActionLog n
=> Resource
-> (Maybe a -> n (t, Maybe LogFilter))
-> RuntimeSplice n LogFilter
-> Splice n
actionsSplice res form rt = manyWithSplices runChildren (actionSplices res) $ do
f <- rt
(_,r) <- lift $ form Nothing
let filters = case r of
Nothing -> []
Just lf -> mkFilters (f `mappend` lf)
lift $ getTenantActions filters []
actionSplices :: HasActionLog n
=> Resource
-> Splices (RuntimeSplice n (Entity LoggedAction) -> Splice n)
actionSplices r = mconcat
[ MS.mapV pureSplice loggedActionCSplices
, alCustomCSplices
, MS.mapV ( deferMap (return . Just . DBId . mkWord64 . entityKey)
. pureSplice . textSplice) (itemCSplices r)
, splices
]
where
splices = do
"loggedActionUserName" MS.## getUserName
"loggedActionDetails" MS.## detailsSplice
detailsSplice :: HasActionLog n
=> RuntimeSplice n (Entity LoggedAction)
-> Splice n
detailsSplice rt =
manyWithSplices runChildren (MS.mapV pureSplice detailsCSplices)
(lift . getActionDetails . entityKey =<< rt)
getUserName :: HasActionLog n
=> RuntimeSplice n (Entity LoggedAction)
-> Splice n
getUserName = bindLater $ \entity -> lift $ do
name <- alGetName $ loggedActionUserId $ entityVal entity
return $ fromText name
-------------------------------------------------------------------------------
logFilterFormSplice :: MonadIO m
=> (Maybe a -> m (View Text, b))
-> RuntimeSplice m a
-> Splice m
logFilterFormSplice form rt =
formSplice mempty mempty $ do
f <- rt
lift $ liftM fst $ form (Just f)
-------------------------------------------------------------------------------
-- Interpreted
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
logFilterFormISplice :: MonadIO m
=> (Maybe a -> m (View Text, t))
-> a -> HeistT m m Template
logFilterFormISplice form f = do
(v,_) <- lift $ form (Just f)
localHS (DHI.bindDigestiveSplices v) (DHI.dfForm v >>= I.runNodeList)
--crudUrlISplice :: MonadSnap m => ByteString -> CRUD -> HeistT n m Template
--crudUrlISplice root crud =
-- I.textSplice . decodeUtf8 . (root -/-) =<< go crud
-- where
-- go RIndex = return ""
-- go RCreate = return ""
-- go RShow = (getParam "id") >>= maybe (go RIndex) return
-- go RNew = return "new"
-- go REdit = (getParam "id") >>= maybe (go RIndex) (return . (-/- "edit"))
-- go RUpdate = (getParam "id") >>= maybe (go RIndex) return
-- go RDestroy =
-- (getParam "id") >>= maybe (go RIndex) (return . (-/- "/destroy"))
--
--
--viewLinkISplice :: MonadSnap m => ByteString -> I.Splice m
--viewLinkISplice root = do
-- n <- getParamNode
-- case X.getAttribute "entity" n of
-- Nothing -> return []
-- Just e -> do
-- mid <- lift $ getParam "id"
-- case mid of
-- Nothing -> return []
-- Just _id -> do
-- let page = printf "%s?%s&%s" (kv "entity" e)
-- (kv "entity-id" (decodeUtf8 _id))
-- url = root -/- encodeUtf8 (T.pack page)
-- I.runChildrenWithText [("linkUrl", decodeUtf8 url)]
-- where
-- kv :: Text -> Text -> String
-- kv k v = printf "%s.%s=%s" (T.unpack logFilterFormName)
-- (T.unpack k) (T.unpack v)
-------------------------------------------------------------------------------
-- | Interpreted splice for an action log listing.
actionLogISplices :: (HasActionLog n, MonadSnap n)
=> Resource -> Splices (I.Splice n)
actionLogISplices r =
splices `mappend` coupledISplices r False mempty
where
splices = do
"actionDetails" MS.## actionDetailsISplice r
"defaultActions" MS.## defaultActionsISplice r
coupledISplices :: (HasActionLog m, MonadSnap m)
=> Resource -> Bool -> LogFilter -> Splices (I.Splice m)
coupledISplices r b f = do
"actionlogListing" MS.## actionLogListingISplice r (runLogFilterForm b) f
"actionlogFilterForm" MS.## logFilterFormISplice (runLogFilterForm b) f
actionDetailsISplice :: (HasActionLog n, MonadSnap n)
=> Resource -> I.Splice n
actionDetailsISplice r = do
ma <- lift $ actionFromId
maybe (return []) (I.runChildrenWith . actionISplices r) ma
actionLogListingISplice :: HasActionLog m
=> Resource
-> (Maybe a -> m (t, Maybe LogFilter))
-> LogFilter
-> I.Splice m
actionLogListingISplice res form f = do
(_,r) <- lift $ form Nothing
let filters = case r of
Nothing -> []
Just lf -> mkFilters (f `mappend` lf)
actions <- lift $ getTenantActions filters []
I.mapSplices (I.runChildrenWith . actionISplices res) actions
actionISplices :: HasActionLog m
=> Resource
-> Entity LoggedAction
-> Splices (I.Splice m)
actionISplices r e = mconcat
[ splices
, loggedActionISplices (entityVal e)
, alCustomISplices e
, itemSplices r (DBId $ mkWord64 $ entityKey e)
]
where
splices = do
"loggedActionUserName" MS.## I.textSplice =<< getUserName
"loggedActionDetails" MS.## detailsISplice
getUserName = lift $ alGetName $ loggedActionUserId $ entityVal e
detailsISplice = do
ds <- lift $ getActionDetails $ entityKey e
I.mapSplices (I.runChildrenWith . detailsISplices . entityVal) ds
------------------------------------------------------------------------------
-- | This is a splice that wraps both the action log filter form splice and
-- the listing splice. It handles greying out the appropriate form fields and
-- limiting the things in the listing.
defaultActionsISplice :: (MonadSnap m, HasActionLog m)
=> Resource -> I.Splice m
defaultActionsISplice r = do
n <- getParamNode
let f = filterCommon $ X.elementAttrs n
I.runChildrenWith $ coupledISplices r True f
| Soostone/snaplet-actionlog | src/Snap/Snaplet/ActionLog/Resource.hs | bsd-3-clause | 14,118 | 0 | 20 | 3,761 | 3,407 | 1,768 | 1,639 | 255 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Prompt.Ssh
-- Copyright : (C) 2007 Andrea Rossato
-- License : BSD3
--
-- Maintainer : andrea.rossato@unibz.it
-- Stability : unstable
-- Portability : unportable
--
-- A ssh prompt for XMonad
--
-----------------------------------------------------------------------------
module XMonad.Prompt.Ssh
( -- * Usage
-- $usage
sshPrompt,
Ssh,
) where
import XMonad
import XMonad.Util.Run
import XMonad.Prompt
import System.Directory
import System.Environment
import Control.Exception as E
import Control.Monad
import Data.Maybe
econst :: Monad m => a -> IOException -> m a
econst = const . return
-- $usage
-- 1. In your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Prompt
-- > import XMonad.Prompt.Ssh
--
-- 2. In your keybindings add something like:
--
-- > , ((modm .|. controlMask, xK_s), sshPrompt def)
--
-- Keep in mind, that if you want to use the completion you have to
-- disable the "HashKnownHosts" option in your ssh_config
--
-- For detailed instruction on editing the key binding see
-- "XMonad.Doc.Extending#Editing_key_bindings".
data Ssh = Ssh
instance XPrompt Ssh where
showXPrompt Ssh = "SSH to: "
commandToComplete _ c = c
nextCompletion _ = getNextCompletion
sshPrompt :: XPConfig -> X ()
sshPrompt c = do
sc <- io sshComplList
mkXPrompt Ssh c (mkComplFunFromList sc) ssh
ssh :: String -> X ()
ssh = runInTerm "" . ("ssh " ++ )
sshComplList :: IO [String]
sshComplList = uniqSort `fmap` liftM2 (++) sshComplListLocal sshComplListGlobal
sshComplListLocal :: IO [String]
sshComplListLocal = do
h <- getEnv "HOME"
s1 <- sshComplListFile $ h ++ "/.ssh/known_hosts"
s2 <- sshComplListConf $ h ++ "/.ssh/config"
return $ s1 ++ s2
sshComplListGlobal :: IO [String]
sshComplListGlobal = do
env <- getEnv "SSH_KNOWN_HOSTS" `E.catch` econst "/nonexistent"
fs <- mapM fileExists [ env
, "/usr/local/etc/ssh/ssh_known_hosts"
, "/usr/local/etc/ssh_known_hosts"
, "/etc/ssh/ssh_known_hosts"
, "/etc/ssh_known_hosts"
]
case catMaybes fs of
[] -> return []
(f:_) -> sshComplListFile' f
sshComplListFile :: String -> IO [String]
sshComplListFile kh = do
f <- doesFileExist kh
if f then sshComplListFile' kh
else return []
sshComplListFile' :: String -> IO [String]
sshComplListFile' kh = do
l <- readFile kh
return $ map (getWithPort . takeWhile (/= ',') . concat . take 1 . words)
$ filter nonComment
$ lines l
sshComplListConf :: String -> IO [String]
sshComplListConf kh = do
f <- doesFileExist kh
if f then sshComplListConf' kh
else return []
sshComplListConf' :: String -> IO [String]
sshComplListConf' kh = do
l <- readFile kh
return $ map (!!1)
$ filter isHost
$ map words
$ lines l
where
isHost ws = take 1 ws == ["Host"] && length ws > 1
fileExists :: String -> IO (Maybe String)
fileExists kh = do
f <- doesFileExist kh
if f then return $ Just kh
else return Nothing
nonComment :: String -> Bool
nonComment [] = False
nonComment ('#':_) = False
nonComment ('|':_) = False -- hashed, undecodeable
nonComment _ = True
getWithPort :: String -> String
getWithPort ('[':str) = host ++ " -p " ++ port
where (host,p) = break (==']') str
port = case p of
']':':':x -> x
_ -> "22"
getWithPort str = str
| eb-gh-cr/XMonadContrib1 | XMonad/Prompt/Ssh.hs | bsd-3-clause | 3,610 | 0 | 17 | 906 | 939 | 491 | 448 | 85 | 2 |
{-
Data types for untyped lambda calculus with and without names.
NB: it's possible to do this and much of boilerplate descents
along recursive data types with Haskell typeclass magic,
see:
* http://dev.stephendiehl.com/hask/#interpreters
* http://dev.stephendiehl.com/hask/#languages
The drawback is you have to use a number of language
extensions, so the code gets terse and opaque.
-}
module Untyped.Data (
Sym
, NamedλTerm(..)
, UnnamedλTerm(..)
) where
import Text.PrettyPrint.Leijen ((<>), char, int, string, pretty, Pretty(..))
-------------------------------------
-- 1: untyped calculus with names --
-------------------------------------
-- | Use a 'String' instead of 'Char' so 'Sym' can be name, e.g. for
--
-- @id = (λx.x);@ NamedλTerm
--
type Sym = String
data NamedλTerm =
Var Sym
| Abs Sym NamedλTerm
| App NamedλTerm NamedλTerm
deriving (Show, Eq)
-- | Pretty print 'NamedλTerm'
--
-- >>> pretty $ (App (Abs "x"(Var "x")) (Var "x"))
-- (λx.x x)
--
instance Pretty NamedλTerm where
pretty (Var s) = string s
pretty (Abs s t) = string "λ" <> string s <> string "." <> pretty t
pretty (App t1 t2) = char '(' <> pretty t1 <> string " " <> pretty t2 <> char ')'
--------------------------------------------
-- 2: untyped calculus de Bruijn indexes --
--------------------------------------------
-- | Nameless terms.
data UnnamedλTerm =
Var2 Int
| Abs2 UnnamedλTerm
| App2 UnnamedλTerm UnnamedλTerm
deriving (Show, Eq)
-- | Pretty print 'UnnamedλTerm'
--
-- >>> pretty $ (App2 (Abs2 (Var2 0)) (Var2 0))
-- (λ.0 0)
--
instance Pretty UnnamedλTerm where
pretty (Var2 i) = int i
pretty (Abs2 t) = string "λ." <> pretty t
pretty (App2 t1 t2) = char '(' <> pretty t1 <> string " " <> pretty t2 <> char ')'
| tomtitchener/TypesAndProgrammingLanguages | src/untyped/data.hs | bsd-3-clause | 1,855 | 2 | 10 | 400 | 379 | 209 | 170 | 24 | 0 |
module Main where
import Hangman
import Test.Hspec
import Test.QuickCheck
-- Preamble
-- Generate match and miss pairs
alphabet :: String
alphabet = ['a'..'z']
isWord :: String -> Bool
isWord w = foldr (\a b -> a `elem` alphabet && b) True w
genMatch :: Gen ([Char], Char)
genMatch = do
xs <- arbitrary `suchThat` (\xs -> xs /= [] && isWord xs)
x <- arbitrary `suchThat` (\x -> x `elem` xs && x `elem` alphabet)
return (xs, x)
genMiss :: Gen ([Char], Char)
genMiss = do
xs <- arbitrary `suchThat` (\xs -> xs /= [] && isWord xs)
x <- arbitrary `suchThat` (\x -> x `notElem` xs && x `elem` alphabet)
return (xs, x)
-- Properties
-- We need Maybes
justify :: Eq a => a -> a -> Maybe a
justify x y = if x == y
then Just x
else Nothing
-- We need an Eq instance for Puzzle
instance Eq Puzzle where
(==) (Puzzle word discovered guessed)
(Puzzle word' discovered' guessed') =
word == word' &&
discovered == discovered' &&
guessed == guessed'
-- Now we can write properties
-- Note, though, that these will only have the "Property" type
-- once we apply forAll in the main function. This path allows
-- us to reuse code at least twice for every "property".
prop_fillInCharacter :: (String, Char) -> Bool
prop_fillInCharacter (xs, x) =
fillInCharacter (freshPuzzle xs) x ==
Puzzle xs (map (justify x) xs) [x]
prop_checkCharInWord :: Bool -> (String, Char) -> Bool
prop_checkCharInWord b (xs, x) =
charInWord (Puzzle xs (map (justify x) xs) [x] ) x == b
prop_checkAlreadyGuessed :: Bool -> (String, Char) -> Bool
prop_checkAlreadyGuessed b (xs, x) =
alreadyGuessed (Puzzle xs (map (justify x) xs) (consIf b x)) x == b
where
consIf :: Bool -> Char -> String
consIf t c = if t then [c] else []
-- Losing hope? Just print the damn Puzzle
puzzShow :: IO ()
puzzShow = do
print (fillInCharacter (freshPuzzle "lhs") 'l')
-- OK, run tests
main :: IO ()
main = hspec $ do
describe "Hangman tests -- fillInCharacter" $ do
it "Guesses the wrong character - does not fill in" $ do
forAll genMiss prop_fillInCharacter
it "Guesses the right character - fills in" $ do
forAll genMatch prop_fillInCharacter
describe "Hangman tests -- charInWord" $ do
it "Checks if Char is in word - returns False" $ do
forAll genMiss (prop_checkCharInWord False)
it "Checks if Char is in word - returns True" $ do
forAll genMatch (prop_checkCharInWord True)
describe "Hangman tests - alreadyGuessed" $ do
it "Checks if Char has been guessed (miss) - returns False" $ do
forAll genMiss (prop_checkAlreadyGuessed False)
it "Checks the same for a match" $ do
forAll genMatch (prop_checkAlreadyGuessed False)
it "Checks if Char has been guessed (miss) - returns True" $ do
forAll genMiss (prop_checkAlreadyGuessed True)
it "Checks the same for a match" $ do
forAll genMatch (prop_checkAlreadyGuessed True)
| dmvianna/hangman | tests/tests.hs | bsd-3-clause | 2,992 | 0 | 16 | 713 | 922 | 476 | 446 | 64 | 2 |
{-# OPTIONS -Wall -fno-warn-unused-binds #-}
module Benchmark.Euphoria (
benchmark1
, benchmark2
, main
) where
import FRP.Euphoria.Event
import Control.Monad
import Control.Applicative
import Data.Monoid
import Data.Time
import System.Random.MWC
import qualified Data.IntMap as IM
import Text.Printf
import System.IO
import System.Mem
benchmark1 :: Int -> Int -> IO (NominalDiffTime, NominalDiffTime)
benchmark1 netsize dur = do
starttime <- getCurrentTime
(eventGens, sinks) <- unzip <$> replicateM netsize externalEvent
let sinkMap = IM.fromList $ zip [0..netsize - 1] sinks
let network :: SignalGen (Signal [String])
network = eventToSignal . mconcat <$> sequence eventGens
sample <- start network
void sample
midtime <- getCurrentTime
randGen <- create
forM_ [1..dur] $ \n -> do
let str = show n
replicateM_ 10 $ do
ev <- uniformR (0,netsize-1) randGen
maybe (return ()) ($ str) $ IM.lookup ev sinkMap
mapM_ ePutStrLn =<< sample
endtime <- getCurrentTime
return (midtime `diffUTCTime` starttime, endtime `diffUTCTime` midtime)
benchmark2 :: Int -> Int -> IO (NominalDiffTime, NominalDiffTime)
benchmark2 netsize dur = do
startTime <- getCurrentTime
(unitEventGens, sinks) <- unzip <$> replicateM netsize externalEvent
(stepEventGen, stepSink) <- externalEvent
let sinkMap = IM.fromList $ zip [0..netsize-1] sinks
let network :: SignalGen (Signal Int)
network = do
countDs <- mapM (>>= count) unitEventGens
stepE <- stepEventGen
let collector (d:ds@(_:_)) = (ds,d)
collector ([d]) = ([d],d)
collector _ = error "benchmark2, empty network"
selectedD_E <- scanAccumE (tail countDs) . (collector <$) $ filterE (\cnt -> cnt `rem` 10 == 0) stepE
discreteToSignal . join =<< stepperD (head countDs) selectedD_E
sample <- start network
midTime <- getCurrentTime
randGen <- create
forM_ [1..dur] $ \step -> do
stepSink step
replicateM_ 10 $ do
ev <- uniformR (0,netsize-1) randGen
maybe (error "euphoria bench2: sink not found") ($ ()) $ IM.lookup ev sinkMap
(ePutStrLn . show) =<< sample
endTime <- getCurrentTime
return (midTime `diffUTCTime` startTime, endTime `diffUTCTime` midTime)
main :: IO ()
main = do
let testN (lbl,bench) netsize dur = do
putStrLn $ printf "%s iterations: %d netsize: %d" lbl dur netsize
performGC
(setup, run) <- bench netsize dur
putStrLn $ printf "setup: %s\nruntime: %s" (show setup) (show run)
let benches = [("benchmark 1", benchmark1)
,("benchmark 2", benchmark2)
]
durs = [100, 1000]
sizes = [100,1000,10000,100000]
sequence_ $ testN <$> benches <*> sizes <*> durs
ePutStrLn :: String -> IO ()
ePutStrLn = hPutStrLn stderr
count :: Event a -> SignalGen (Discrete Int)
count = accumD 0 . ((+1) <$)
| tsurucapital/frp-benchmarks | src/Benchmark/Euphoria.hs | bsd-3-clause | 3,009 | 0 | 20 | 767 | 1,052 | 537 | 515 | 76 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import Settings
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Network.Wai.Middleware.RequestLogger
import qualified Database.Persist
import Database.Persist.Sql (runMigration)
import Network.HTTP.Conduit (newManager, def)
import Control.Monad.Logger (runLoggingT)
import System.IO (stdout)
import System.Log.FastLogger (mkLogger)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Home
import Handler.User
import Handler.API
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = Logger $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
return $ logWare app
-- | Loads up any necessary settings, creates your foundation datatype, and
-- performs some initialization.
makeFoundation :: AppConfig DefaultEnv Extra -> IO App
makeFoundation conf = do
manager <- newManager def
s <- staticSite
dbconf <- withYamlEnvironment "config/postgresql.yml" (appEnv conf)
Database.Persist.loadConfig >>=
Database.Persist.applyEnv
p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf)
logger <- mkLogger True stdout
let foundation = App conf s p manager dbconf logger
-- Perform database migration using our application's logging settings.
runLoggingT
(Database.Persist.runPool dbconf (runMigration migrateAll) p)
(messageLoggerSource foundation logger)
return foundation
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader makeApplication
where
loader = Yesod.Default.Config.loadConfig (configSettings Development)
{ csParseExtra = parseExtra
}
| tanakh/icfp2013-clone | Application.hs | bsd-3-clause | 2,730 | 0 | 12 | 537 | 468 | 254 | 214 | -1 | -1 |
-- |
-- Module : NestedUnfoldOps
-- Copyright : (c) 2019 Composewell Technologies
--
-- License : BSD3
-- Maintainer : streamly@composewell.com
module NestedUnfoldOps where
import Control.Monad.IO.Class (MonadIO (..))
import Streamly.Internal.Data.Unfold (Unfold)
import qualified Streamly.Internal.Data.Unfold as UF
import qualified Streamly.Internal.Data.Fold as FL
linearCount :: Int
linearCount = 100000
-- n * (n + 1) / 2 == linearCount
concatCount :: Int
concatCount = 450
-- double nested loop
nestedCount2 :: Int
nestedCount2 = round (fromIntegral linearCount**(1/2::Double))
-- triple nested loop
nestedCount3 :: Int
nestedCount3 = round (fromIntegral linearCount**(1/3::Double))
-------------------------------------------------------------------------------
-- Stream generation and elimination
-------------------------------------------------------------------------------
-- generate numbers up to the argument value
{-# INLINE source #-}
source :: Monad m => Int -> Unfold m Int Int
source n = UF.enumerateFromToIntegral n
-------------------------------------------------------------------------------
-- Benchmark ops
-------------------------------------------------------------------------------
{-# INLINE toNull #-}
toNull :: MonadIO m => Int -> m ()
toNull start = do
let end = start + nestedCount2
UF.fold
(UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end))
FL.drain (start, start)
{-# INLINE toNull3 #-}
toNull3 :: MonadIO m => Int -> m ()
toNull3 start = do
let end = start + nestedCount3
UF.fold
(UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end)
((UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end))))
FL.drain (start, (start, start))
{-# INLINE concat #-}
concat :: MonadIO m => Int -> m ()
concat start = do
let end = start + concatCount
UF.fold
(UF.concat (source end) (source end))
FL.drain start
{-# INLINE toList #-}
toList :: MonadIO m => Int -> m [Int]
toList start = do
let end = start + nestedCount2
UF.fold
(UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end))
FL.toList (start, start)
{-# INLINE toListSome #-}
toListSome :: MonadIO m => Int -> m [Int]
toListSome start = do
let end = start + nestedCount2
UF.fold
(UF.take 1000 $ (UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end)))
FL.toList (start, start)
{-# INLINE filterAllOut #-}
filterAllOut :: MonadIO m => Int -> m ()
filterAllOut start = do
let end = start + nestedCount2
UF.fold
(UF.filter (< 0)
$ UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end))
FL.drain (start, start)
{-# INLINE filterAllIn #-}
filterAllIn :: MonadIO m => Int -> m ()
filterAllIn start = do
let end = start + nestedCount2
UF.fold
(UF.filter (> 0)
$ UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end))
FL.drain (start, start)
{-# INLINE filterSome #-}
filterSome :: MonadIO m => Int -> m ()
filterSome start = do
let end = start + nestedCount2
UF.fold
(UF.filter (> 1100000)
$ UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end))
FL.drain (start, start)
{-# INLINE breakAfterSome #-}
breakAfterSome :: MonadIO m => Int -> m ()
breakAfterSome start = do
let end = start + nestedCount2
UF.fold
(UF.takeWhile (<= 1100000)
$ UF.map (\(x, y) -> x + y)
$ UF.outerProduct (source end) (source end))
FL.drain (start, start)
| harendra-kumar/asyncly | benchmark/NestedUnfoldOps.hs | bsd-3-clause | 3,719 | 0 | 17 | 901 | 1,284 | 679 | 605 | 93 | 1 |
module UnSafe
(
hackageUrl,
getUrlFromData
) where
import Config(getDataFromFile,getData,pickerData)
import System.IO.Unsafe
hackageUrlIO :: IO String
hackageUrlIO = do
configData <- getDataFromFile "./.xhsk.home.config"
return . (\(Just x) -> x) $ getData configData pickerData "hackage-url"
hackageUrl :: String
hackageUrl = unsafeDupablePerformIO hackageUrlIO
getUrlFromDataIO :: String -> IO String
getUrlFromDataIO url = do
configData <- getDataFromFile "./.xhsk.home.config"
return . (\(Just x) -> x) $ getData configData pickerData url
getUrlFromData :: String -> String
getUrlFromData url = unsafeDupablePerformIO $ getUrlFromDataIO url
| Xidian-Haskell-Server-Keeper/XHSK-Home | src/UnSafe.hs | bsd-3-clause | 764 | 0 | 12 | 196 | 186 | 97 | 89 | 18 | 1 |
-- | Module providing a function to parse a page from a file
--
module Hakyll.Web.Page.Read
( readPage
) where
import Control.Applicative ((<$>), (<*>), (<*), (<|>))
import qualified Data.Map as M
import Text.Parsec.Char (alphaNum, anyChar, char, oneOf, string)
import Text.Parsec.Combinator (choice, many1, manyTill, option, skipMany1)
import Text.Parsec.Prim (many, parse, skipMany, (<?>))
import Text.Parsec.String (Parser)
import Hakyll.Core.Util.String
import Hakyll.Web.Page.Internal
-- | Space or tab, no newline
inlineSpace :: Parser Char
inlineSpace = oneOf ['\t', ' '] <?> "space"
-- | Parse Windows newlines as well (i.e. "\n" or "\r\n")
newline :: Parser String
newline = string "\n" -- Unix
<|> string "\r\n" -- DOS
-- | Parse a single metadata field
--
metadataField :: Parser (String, String)
metadataField = do
key <- manyTill alphaNum $ char ':'
skipMany1 inlineSpace <?> "space followed by metadata for: " ++ key
value <- manyTill anyChar newline
trailing' <- many trailing
return (key, trim $ value ++ concat trailing')
where
trailing = (++) <$> many1 inlineSpace <*> manyTill anyChar newline
-- | Parse a metadata block, including delimiters and trailing newlines
--
metadata :: Parser [(String, String)]
metadata = do
open <- many1 (char '-') <* many inlineSpace <* newline
metadata' <- many metadataField
_ <- choice $ map (string . replicate (length open)) ['-', '.']
skipMany inlineSpace
skipMany1 newline
return metadata'
-- | Parse a Hakyll page
--
page :: Parser ([(String, String)], String)
page = do
metadata' <- option [] metadata
body <- many anyChar
return (metadata', body)
readPage :: String -> Page String
readPage input = case parse page "page" input of
Left err -> error (show err)
Right (md, b) -> Page (M.fromList md) b
| sol/hakyll | src/Hakyll/Web/Page/Read.hs | bsd-3-clause | 1,859 | 0 | 14 | 374 | 578 | 315 | 263 | 40 | 2 |
{-# LANGUAGE CPP #-}
#ifdef __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable #-}
#if __GLASGOW_HASKELL__ >= 704
{-# LANGUAGE DeriveGeneric #-}
#endif
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
#endif
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
----------------------------------------------------------------------------
module Bound.Var
( Var(..)
, unvar
, _B
, _F
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.DeepSeq
import Control.Monad (liftM, ap)
#if __GLASGOW_HASKELL__ < 710
import Data.Foldable
import Data.Traversable
import Data.Monoid (Monoid(..))
#endif
import Data.Hashable (Hashable(..))
import Data.Hashable.Lifted (Hashable1(..), Hashable2(..))
import Data.Bifunctor
import Data.Bifoldable
import qualified Data.Binary as Binary
import Data.Binary (Binary)
import Data.Bitraversable
import Data.Bytes.Get
import Data.Bytes.Put
import Data.Bytes.Serial
import Data.Functor.Classes
#ifdef __GLASGOW_HASKELL__
import Data.Data
# if __GLASGOW_HASKELL__ >= 704
import GHC.Generics
# endif
#endif
import Data.Profunctor
import qualified Data.Serialize as Serialize
import Data.Serialize (Serialize)
#if __GLASGOW_HASKELL__ < 710
import Data.Word
#endif
----------------------------------------------------------------------------
-- Bound and Free Variables
----------------------------------------------------------------------------
-- | \"I am not a number, I am a /free monad/!\"
--
-- A @'Var' b a@ is a variable that may either be \"bound\" ('B') or \"free\" ('F').
--
-- (It is also technically a free monad in the same near-trivial sense as
-- 'Either'.)
data Var b a
= B b -- ^ this is a bound variable
| F a -- ^ this is a free variable
deriving
( Eq
, Ord
, Show
, Read
#ifdef __GLASGOW_HASKELL__
, Data
, Typeable
# if __GLASGOW_HASKELL__ >= 704
, Generic
# endif
#endif
)
distinguisher :: Int
distinguisher = fromIntegral $ (maxBound :: Word) `quot` 3
instance Hashable2 Var where
liftHashWithSalt2 h _ s (B b) = h s b
liftHashWithSalt2 _ h s (F a) = h s a `hashWithSalt` distinguisher
{-# INLINE liftHashWithSalt2 #-}
instance Hashable b => Hashable1 (Var b) where
liftHashWithSalt = liftHashWithSalt2 hashWithSalt
{-# INLINE liftHashWithSalt #-}
instance (Hashable b, Hashable a) => Hashable (Var b a) where
hashWithSalt s (B b) = hashWithSalt s b
hashWithSalt s (F a) = hashWithSalt s a `hashWithSalt` distinguisher
{-# INLINE hashWithSalt #-}
instance Serial2 Var where
serializeWith2 pb _ (B b) = putWord8 0 >> pb b
serializeWith2 _ pf (F f) = putWord8 1 >> pf f
{-# INLINE serializeWith2 #-}
deserializeWith2 gb gf = getWord8 >>= \b -> case b of
0 -> liftM B gb
1 -> liftM F gf
_ -> fail $ "getVar: Unexpected constructor code: " ++ show b
{-# INLINE deserializeWith2 #-}
instance Serial b => Serial1 (Var b) where
serializeWith = serializeWith2 serialize
{-# INLINE serializeWith #-}
deserializeWith = deserializeWith2 deserialize
{-# INLINE deserializeWith #-}
instance (Serial b, Serial a) => Serial (Var b a) where
serialize = serializeWith2 serialize serialize
{-# INLINE serialize #-}
deserialize = deserializeWith2 deserialize deserialize
{-# INLINE deserialize #-}
instance (Binary b, Binary a) => Binary (Var b a) where
put = serializeWith2 Binary.put Binary.put
get = deserializeWith2 Binary.get Binary.get
instance (Serialize b, Serialize a) => Serialize (Var b a) where
put = serializeWith2 Serialize.put Serialize.put
get = deserializeWith2 Serialize.get Serialize.get
unvar :: (b -> r) -> (a -> r) -> Var b a -> r
unvar f _ (B b) = f b
unvar _ g (F a) = g a
{-# INLINE unvar #-}
-- |
-- This provides a @Prism@ that can be used with @lens@ library to access a bound 'Var'.
--
-- @
-- '_B' :: 'Prism' (Var b a) (Var b' a) b b'@
-- @
_B :: (Choice p, Applicative f) => p b (f b') -> p (Var b a) (f (Var b' a))
_B = dimap (unvar Right (Left . F)) (either pure (fmap B)) . right'
{-# INLINE _B #-}
-- |
-- This provides a @Prism@ that can be used with @lens@ library to access a free 'Var'.
--
-- @
-- '_F' :: 'Prism' (Var b a) (Var b a') a a'@
-- @
_F :: (Choice p, Applicative f) => p a (f a') -> p (Var b a) (f (Var b a'))
_F = dimap (unvar (Left . B) Right) (either pure (fmap F)) . right'
{-# INLINE _F #-}
----------------------------------------------------------------------------
-- Instances
----------------------------------------------------------------------------
instance Functor (Var b) where
fmap _ (B b) = B b
fmap f (F a) = F (f a)
{-# INLINE fmap #-}
instance Foldable (Var b) where
foldMap f (F a) = f a
foldMap _ _ = mempty
{-# INLINE foldMap #-}
instance Traversable (Var b) where
traverse f (F a) = F <$> f a
traverse _ (B b) = pure (B b)
{-# INLINE traverse #-}
instance Applicative (Var b) where
pure = F
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance Monad (Var b) where
return = pure
{-# INLINE return #-}
F a >>= f = f a
B b >>= _ = B b
{-# INLINE (>>=) #-}
instance Bifunctor Var where
bimap f _ (B b) = B (f b)
bimap _ g (F a) = F (g a)
{-# INLINE bimap #-}
instance Bifoldable Var where
bifoldMap f _ (B b) = f b
bifoldMap _ g (F a) = g a
{-# INLINE bifoldMap #-}
instance Bitraversable Var where
bitraverse f _ (B b) = B <$> f b
bitraverse _ g (F a) = F <$> g a
{-# INLINE bitraverse #-}
#if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0))
instance Eq2 Var where
liftEq2 f _ (B a) (B c) = f a c
liftEq2 _ g (F b) (F d) = g b d
liftEq2 _ _ _ _ = False
instance Ord2 Var where
liftCompare2 f _ (B a) (B c) = f a c
liftCompare2 _ _ B{} F{} = LT
liftCompare2 _ _ F{} B{} = GT
liftCompare2 _ g (F b) (F d) = g b d
instance Show2 Var where
liftShowsPrec2 f _ _ _ d (B a) = showsUnaryWith f "B" d a
liftShowsPrec2 _ _ h _ d (F a) = showsUnaryWith h "F" d a
instance Read2 Var where
liftReadsPrec2 f _ h _ = readsData $ readsUnaryWith f "B" B `mappend` readsUnaryWith h "F" F
instance Eq b => Eq1 (Var b) where
liftEq = liftEq2 (==)
instance Ord b => Ord1 (Var b) where
liftCompare = liftCompare2 compare
instance Show b => Show1 (Var b) where
liftShowsPrec = liftShowsPrec2 showsPrec showList
instance Read b => Read1 (Var b) where
liftReadsPrec = liftReadsPrec2 readsPrec readList
#else
--instance Eq2 Var where eq2 = (==)
--instance Ord2 Var where compare2 = compare
--instance Show2 Var where showsPrec2 = showsPrec
--instance Read2 Var where readsPrec2 = readsPrec
instance Eq b => Eq1 (Var b) where eq1 = (==)
instance Ord b => Ord1 (Var b) where compare1 = compare
instance Show b => Show1 (Var b) where showsPrec1 = showsPrec
instance Read b => Read1 (Var b) where readsPrec1 = readsPrec
#endif
# if __GLASGOW_HASKELL__ >= 704
instance (NFData a, NFData b) => NFData (Var b a)
# endif
| treeowl/bound | src/Bound/Var.hs | bsd-3-clause | 7,138 | 0 | 12 | 1,417 | 2,036 | 1,085 | 951 | 140 | 1 |
module DoLet where
main = do
first
second
third
fourth
fifth
sixth
first = do
let x = 123
print x
second = do
let x = 123
x <- return 10
print x
third = do
x <- return 123
let x = 777
print x
fourth = do
x <- return 123
let y = 777
print x
print y
fifth = do
print 123
x <- return 123
print 10
let y = 777
print y
print x
sixth = do
print 123
Just x <- return (Just 123)
print 10
let y = 777
print y
print x
| fpco/fay | tests/doLet.hs | bsd-3-clause | 475 | 0 | 26 | 169 | 247 | 104 | 143 | 38 | 1 |
--------------------------------------------------------------------------------
-- | The LLVM abstract syntax.
--
module Llvm.AbsSyn where
import Llvm.Types
import Unique
-- | Block labels
type LlvmBlockId = Unique
-- | A block of LLVM code.
data LlvmBlock = LlvmBlock {
-- | The code label for this block
blockLabel :: LlvmBlockId,
-- | A list of LlvmStatement's representing the code for this block.
-- This list must end with a control flow statement.
blockStmts :: [LlvmStatement]
}
type LlvmBlocks = [LlvmBlock]
-- | An LLVM Module. This is a top level container in LLVM.
data LlvmModule = LlvmModule {
-- | Comments to include at the start of the module.
modComments :: [LMString],
-- | LLVM Alias type definitions.
modAliases :: [LlvmAlias],
-- | LLVM meta data.
modMeta :: [LlvmMeta],
-- | Global variables to include in the module.
modGlobals :: [LMGlobal],
-- | LLVM Functions used in this module but defined in other modules.
modFwdDecls :: LlvmFunctionDecls,
-- | LLVM Functions defined in this module.
modFuncs :: LlvmFunctions
}
-- | An LLVM Function
data LlvmFunction = LlvmFunction {
-- | The signature of this declared function.
funcDecl :: LlvmFunctionDecl,
-- | The functions arguments
funcArgs :: [LMString],
-- | The function attributes.
funcAttrs :: [LlvmFuncAttr],
-- | The section to put the function into,
funcSect :: LMSection,
-- | The body of the functions.
funcBody :: LlvmBlocks
}
type LlvmFunctions = [LlvmFunction]
-- | LLVM ordering types for synchronization purposes. (Introduced in LLVM
-- 3.0). Please see the LLVM documentation for a better description.
data LlvmSyncOrdering
-- | Some partial order of operations exists.
= SyncUnord
-- | A single total order for operations at a single address exists.
| SyncMonotonic
-- | Acquire synchronization operation.
| SyncAcquire
-- | Release synchronization operation.
| SyncRelease
-- | Acquire + Release synchronization operation.
| SyncAcqRel
-- | Full sequential Consistency operation.
| SyncSeqCst
deriving (Show, Eq)
-- | Llvm Statements
data LlvmStatement
{- |
Assign an expression to an variable:
* dest: Variable to assign to
* source: Source expression
-}
= Assignment LlvmVar LlvmExpression
{- |
Memory fence operation
-}
| Fence Bool LlvmSyncOrdering
{- |
Always branch to the target label
-}
| Branch LlvmVar
{- |
Branch to label targetTrue if cond is true otherwise to label targetFalse
* cond: condition that will be tested, must be of type i1
* targetTrue: label to branch to if cond is true
* targetFalse: label to branch to if cond is false
-}
| BranchIf LlvmVar LlvmVar LlvmVar
{- |
Comment
Plain comment.
-}
| Comment [LMString]
{- |
Set a label on this position.
* name: Identifier of this label, unique for this module
-}
| MkLabel LlvmBlockId
{- |
Store variable value in pointer ptr. If value is of type t then ptr must
be of type t*.
* value: Variable/Constant to store.
* ptr: Location to store the value in
-}
| Store LlvmVar LlvmVar
{- |
Mutliway branch
* scrutinee: Variable or constant which must be of integer type that is
determines which arm is chosen.
* def: The default label if there is no match in target.
* target: A list of (value,label) where the value is an integer
constant and label the corresponding label to jump to if the
scrutinee matches the value.
-}
| Switch LlvmVar LlvmVar [(LlvmVar, LlvmVar)]
{- |
Return a result.
* result: The variable or constant to return
-}
| Return (Maybe LlvmVar)
{- |
An instruction for the optimizer that the code following is not reachable
-}
| Unreachable
{- |
Raise an expression to a statement (if don't want result or want to use
Llvm unnamed values.
-}
| Expr LlvmExpression
{- |
A nop LLVM statement. Useful as its often more efficient to use this
then to wrap LLvmStatement in a Just or [].
-}
| Nop
{- |
A LLVM statement with metadata attached to it.
-}
| MetaStmt [MetaData] LlvmStatement
deriving (Show, Eq)
type MetaData = (LMString, LlvmMetaUnamed)
-- | Llvm Expressions
data LlvmExpression
{- |
Allocate amount * sizeof(tp) bytes on the stack
* tp: LlvmType to reserve room for
* amount: The nr of tp's which must be allocated
-}
= Alloca LlvmType Int
{- |
Perform the machine operator op on the operands left and right
* op: operator
* left: left operand
* right: right operand
-}
| LlvmOp LlvmMachOp LlvmVar LlvmVar
{- |
Perform a compare operation on the operands left and right
* op: operator
* left: left operand
* right: right operand
-}
| Compare LlvmCmpOp LlvmVar LlvmVar
{- |
Allocate amount * sizeof(tp) bytes on the heap
* tp: LlvmType to reserve room for
* amount: The nr of tp's which must be allocated
-}
| Malloc LlvmType Int
{- |
Load the value at location ptr
-}
| Load LlvmVar
{- |
Navigate in an structure, selecting elements
* inbound: Is the pointer inbounds? (computed pointer doesn't overflow)
* ptr: Location of the structure
* indexes: A list of indexes to select the correct value.
-}
| GetElemPtr Bool LlvmVar [LlvmVar]
{- |
Cast the variable from to the to type. This is an abstraction of three
cast operators in Llvm, inttoptr, prttoint and bitcast.
* cast: Cast type
* from: Variable to cast
* to: type to cast to
-}
| Cast LlvmCastOp LlvmVar LlvmType
{- |
Call a function. The result is the value of the expression.
* tailJumps: CallType to signal if the function should be tail called
* fnptrval: An LLVM value containing a pointer to a function to be
invoked. Can be indirect. Should be LMFunction type.
* args: Concrete arguments for the parameters
* attrs: A list of function attributes for the call. Only NoReturn,
NoUnwind, ReadOnly and ReadNone are valid here.
-}
| Call LlvmCallType LlvmVar [LlvmVar] [LlvmFuncAttr]
{- |
Merge variables from different basic blocks which are predecessors of this
basic block in a new variable of type tp.
* tp: type of the merged variable, must match the types of the
predecessor variables.
* precessors: A list of variables and the basic block that they originate
from.
-}
| Phi LlvmType [(LlvmVar,LlvmVar)]
{- |
Inline assembly expression. Syntax is very similar to the style used by GCC.
* assembly: Actual inline assembly code.
* contraints: Operand constraints.
* return ty: Return type of function.
* vars: Any variables involved in the assembly code.
* sideeffect: Does the expression have side effects not visible from the
constraints list.
* alignstack: Should the stack be conservatively aligned before this
expression is executed.
-}
| Asm LMString LMString LlvmType [LlvmVar] Bool Bool
{- |
A LLVM expression with metadata attached to it.
-}
| MetaExpr [MetaData] LlvmExpression
deriving (Show, Eq)
| nomeata/ghc | compiler/llvmGen/Llvm/AbsSyn.hs | bsd-3-clause | 7,525 | 0 | 9 | 2,085 | 511 | 332 | 179 | 59 | 0 |
{-# LANGUAGE Arrows #-}
module Parse.Bitmask where
import Spec.Bitmask
import Parse.Utils
import Text.XML.HXT.Core
import Prelude hiding(elem)
parseBitmask :: IOStateArrow s XmlTree Spec.Bitmask.Bitmask
parseBitmask = hasName "enums" >>> hasAttrValue "type" (== "bitmask") >>>
(extract `orElse` failA "Failed to extract bitmask fields")
where extract = proc bitmask -> do
name <- requiredAttrValue "name" -< bitmask
namespace <- optionalAttrValue "namespace" -< bitmask
comment <- optionalAttrValue "comment" -< bitmask
values <- listA (parseBitmaskValue <<< getChildren) -< bitmask
bitPositions <-
listA (parseBitmaskBitPos <<< getChildren) -< bitmask
returnA -< Bitmask{ bmName = name
, bmNamespace = namespace
, bmComment = comment
, bmValues = values
, bmBitPositions = bitPositions
}
parseBitmaskValue :: IOStateArrow s XmlTree BitmaskValue
parseBitmaskValue = hasName "enum" >>> hasAttr "value" >>>
(extract `orElse`
failA "Failed to extract bitmask value fields")
where extract = proc elem -> do
name <- requiredAttrValue "name" -< elem
value <- requiredRead <<< requiredAttrValue "value" -< elem
comment <- optionalAttrValue "comment" -< elem
returnA -< BitmaskValue{ bmvName = name
, bmvValue = value
, bmvComment = comment
}
parseBitmaskBitPos :: IOStateArrow s XmlTree BitmaskBitPosition
parseBitmaskBitPos = hasName "enum" >>> hasAttr "bitpos" >>>
(extract `orElse`
failA "Failed to extract bitmask bitposition fields")
where extract = proc elem -> do
name <- requiredAttrValue "name" -< elem
bitpos <- requiredRead <<< requiredAttrValue "bitpos" -< elem
comment <- optionalAttrValue "comment" -< elem
returnA -< BitmaskBitPosition{ bmbpName = name
, bmbpBitPos = bitpos
, bmbpComment = comment
}
| oldmanmike/vulkan | generate/src/Parse/Bitmask.hs | bsd-3-clause | 2,373 | 3 | 14 | 898 | 483 | 249 | 234 | 43 | 1 |
--module Data.Float.BinString.Test where
{-# LANGUAGE OverloadedStrings #-}
import Data.Float.BinString
import Control.Applicative
import Data.Text (pack,unpack,Text)
import Control.Monad
import Data.Monoid
import Test.Hspec
import Test.QuickCheck
import Test.HUnit
import Test.Hspec.HUnit
import Debug.Trace
rev_prop x = Just True == liftA2 eq (Just x) (readFloat (showFloat x))
eq :: Double -> Double -> Bool
eq a b | isNaN a, isNaN b = True
| otherwise = a == b
nan = 0/0
main = hspec $ do
describe "triv read" $ do
it "0" $ readFloat "0x0p0" @?= Just 0.0
it "1" $ readFloat "0x1p0" @?= Just 1.0
it "-0" $ readFloat "-0x0p0" @?= Just (-0.0)
it "inf" $ readFloat "inf" @?= Just (1/0)
describe "triv show" $ do
it "0" $ showFloat 0 @?= "0x0p+0"
it "pi" $ showFloat pi @?= "0x1.921fb54442d18p+1"
describe "quickcheck" $ do
it "rev" $ property rev_prop
describe "predef" $ do
it "..." $ predefined
predefined = do c <- readFile "tests/tests.pairs.10k"
let vs = map parse $ lines c
forM_ vs $ \(x,s) ->
do liftA2 eq (readFloat s) (Just x) `shouldBe` Just True
showFloat x `shouldBe` s
where parse s = (readF a, pack b) :: (Double,Text) where [a,b] = words s
readF "nan" = 0/0
readF s = read s
| llelf/float-binstring | tests/Test.hs | bsd-3-clause | 1,441 | 73 | 8 | 453 | 497 | 269 | 228 | 37 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Snap.Snaplet.OAuth.Github
(
-- * Routes
routes
-- * Handlers
, githubLoginH
, githubCallbackH
, githubUserH
-- * Types and API
, module Snap.Snaplet.OAuth.Github.Api
) where
------------------------------------------------------------------------------
import Control.Category
import Control.Monad
import Data.ByteString (ByteString)
import Data.Maybe
import Prelude hiding ((.))
import Snap
import Snap.Snaplet.OAuth.Github.Api
import Snap.Snaplet.OAuth.Internal.Handlers
import Snap.Snaplet.OAuth.Internal.Types
------------------------------------------------------------------------------
-- Github
------------------------------------------------------------------------------
githubLoginH :: HasOAuth b => Handler b v ()
githubLoginH = loginWithOauthH github Nothing
-- | token access callback.
-- return a @OAuthValue@ having access token has been filled.
--
githubCallbackH :: HasOAuth b => Handler b v OAuthValue
githubCallbackH = oauthCallbackH github
-- | token access callback
-- return a @Maybe@ @GithubUser@ if everything goes well otherwise @Nothing@.
--
githubUserH :: HasOAuth b => Handler b v (Maybe GithubUser)
githubUserH = githubCallbackH >>= liftIO . apiUser
------------------------------------------------------------------------------
-- | The application's routes.
--
routes :: HasOAuth b => [(ByteString, Handler b v ())]
routes = [ ("/github" , githubLoginH)
]
-- where the callback handler is suppose to be added by user.
----------------------------------------------------------------------------
| HaskellCNOrg/snaplet-oauth | src/Snap/Snaplet/OAuth/Github.hs | bsd-3-clause | 1,872 | 0 | 9 | 455 | 254 | 157 | 97 | 26 | 1 |
module Network.WaiSpec (spec) where
import Test.Hspec
import Test.Hspec.QuickCheck (prop)
import Network.Wai
import Network.Wai.Internal (Request (Request))
import Data.IORef
import Data.Monoid
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Blaze.ByteString.Builder (toByteString, Builder, fromWord8)
import Control.Monad (forM_)
spec :: Spec
spec = do
describe "responseToStream" $ do
let getBody res = do
let (_, _, f) = responseToStream res
f $ \streamingBody -> do
builderRef <- newIORef mempty
let add :: Builder -> IO ()
add b = atomicModifyIORef builderRef $ \builder ->
(builder `mappend` b, ())
flush :: IO ()
flush = return ()
streamingBody add flush
fmap toByteString $ readIORef builderRef
prop "responseLBS" $ \bytes -> do
body <- getBody $ responseLBS undefined undefined $ L.pack bytes
body `shouldBe` S.pack bytes
prop "responseBuilder" $ \bytes -> do
body <- getBody $ responseBuilder undefined undefined
$ mconcat $ map fromWord8 bytes
body `shouldBe` S.pack bytes
prop "responseStream" $ \chunks -> do
body <- getBody $ responseStream undefined undefined $ \sendChunk _ ->
forM_ chunks $ \chunk -> sendChunk $ mconcat $ map fromWord8 chunk
body `shouldBe` S.concat (map S.pack chunks)
it "responseFile total" $ do
let fp = "wai.cabal"
body <- getBody $ responseFile undefined undefined fp Nothing
expected <- S.readFile fp
body `shouldBe` expected
prop "responseFile partial" $ \offset' count' -> do
let fp = "wai.cabal"
totalBS <- S.readFile fp
let total = S.length totalBS
offset = abs offset' `mod` total
count = abs count' `mod` (total - offset)
body <- getBody $ responseFile undefined undefined fp $ Just FilePart
{ filePartOffset = fromIntegral offset
, filePartByteCount = fromIntegral count
, filePartFileSize = fromIntegral total
}
let expected = S.take count $ S.drop offset totalBS
body `shouldBe` expected
describe "lazyRequestBody" $ do
prop "works" $ \chunks -> do
ref <- newIORef $ map S.pack $ filter (not . null) chunks
let req = Request
{ requestBody = atomicModifyIORef ref $ \bss ->
case bss of
[] -> ([], S.empty)
x:y -> (y, x)
}
body <- lazyRequestBody req
body `shouldBe` L.fromChunks (map S.pack chunks)
it "is lazy" $ do
let req = Request
{ requestBody = error "requestBody"
}
_ <- lazyRequestBody req
return ()
| beni55/wai | wai/test/Network/WaiSpec.hs | mit | 3,188 | 0 | 25 | 1,247 | 914 | 455 | 459 | 68 | 2 |
{-# LANGUAGE RecordWildCards #-}
-- | The main goal of this module is to encapsulate recovery mechanism
-- and provide helpers related to it.
module Pos.Infra.Recovery.Info
( CurrentSlot (..)
, TipSlot (..)
, SyncStatus (..)
, MonadRecoveryInfo
, getSyncStatus
, recoveryInProgress
, recoveryCommGuard
, needTriggerRecovery
) where
import Universum
import qualified Control.Concurrent.STM as STM
import Control.Monad.Except (runExceptT, throwError)
import Formatting (bprint, build, sformat, stext, (%))
import qualified Formatting.Buildable
import Pos.Core (BlockCount, SlotCount, SlotId, epochOrSlotG,
epochOrSlotToSlot, flattenSlotId, kEpochSlots,
kSlotSecurityParam, slotIdF)
import qualified Pos.DB.BlockIndex as DB
import Pos.DB.Class (MonadDBRead)
import Pos.Infra.Recovery.Types (RecoveryHeader, RecoveryHeaderTag)
import Pos.Infra.Slotting.Class (MonadSlots (getCurrentSlot))
import Pos.Util.Util (HasLens (..))
import Pos.Util.Wlog (WithLogger, logDebug)
newtype TipSlot = TipSlot SlotId
newtype CurrentSlot = CurrentSlot SlotId
-- | An algebraic data type which represents how well we are
-- synchronized with the network.
data SyncStatus
= SSDoingRecovery
-- ^ We are doing recovery right now, so it's better to wait until
-- we finish.
| SSUnknownSlot
-- ^ We don't know current slot, so we are definitely not
-- synchronized well enough.
| SSLagBehind !TipSlot
!CurrentSlot
-- ^ Our tip's slot (if our tip is genesis, we use 0
-- as local slot).
-- We know current slot, but our tip's slot lags behind
-- current slot too much.
| SSInFuture !TipSlot
!CurrentSlot
-- ^ We know current slot and our tip's slot is greater than
-- the current one. Most likely we are misconfigured or we are
-- cheating somehow (e. g. creating blocks using block-gen).
| SSKindaSynced
-- ^ We are kinda synchronized, i. e. all previously described
-- statuses are not about us.
instance Buildable SyncStatus where
build =
\case
SSDoingRecovery -> "we're doing recovery"
SSUnknownSlot -> "we don't know current slot"
SSLagBehind (TipSlot sslbTipSlot) (CurrentSlot sslbCurrentSlot) ->
bprint
("we lag behind too much, our tip's slot is: " %slotIdF %
", but current slot is " %slotIdF)
sslbTipSlot
sslbCurrentSlot
SSInFuture (TipSlot sslbTipSlot) (CurrentSlot sslbCurrentSlot) ->
bprint
("we invented a time machine, our tip's slot is: " %slotIdF %
" and it's greater than current slot: " %slotIdF)
sslbTipSlot
sslbCurrentSlot
SSKindaSynced -> "we are moderately synchronized"
type MonadRecoveryInfo ctx m =
( Monad m
, MonadIO m
, MonadDBRead m
, MonadSlots ctx m
, MonadReader ctx m
, HasLens RecoveryHeaderTag ctx RecoveryHeader
)
-- | Returns our synchronization status. The argument determines
-- how much we should lag behind for 'SSLagBehind' status to take
-- place. See 'SyncStatus' for details.
-- Implementation must check conditions in the same order as they
-- are enumerated in 'SyncStatus'.
getSyncStatus :: MonadRecoveryInfo ctx m => SlotCount -> SlotCount -> m SyncStatus
getSyncStatus epochSlots lagBehindParam =
fmap convertRes . runExceptT $ do
recoveryIsInProgress >>= \case
False -> pass
True -> throwError SSDoingRecovery
curSlotId <- note SSUnknownSlot =<< getCurrentSlot epochSlots
tipHeader <- lift DB.getTipHeader
let curSlot = CurrentSlot curSlotId
let tipSlot@(TipSlot tipSlotId) = TipSlot $
epochOrSlotToSlot (tipHeader ^. epochOrSlotG)
unless (tipSlotId <= curSlotId) $
throwError $
SSInFuture tipSlot curSlot
let slotDiff = flattenSlotId epochSlots curSlotId - flattenSlotId epochSlots tipSlotId
unless (slotDiff < fromIntegral lagBehindParam) $
throwError $
SSLagBehind tipSlot curSlot
where
recoveryIsInProgress = do
var <- view (lensOf @RecoveryHeaderTag)
isJust <$> atomically (STM.tryReadTMVar var)
convertRes :: Either SyncStatus () -> SyncStatus
convertRes (Left ss) = ss
convertRes (Right ()) = SSKindaSynced
-- | Returns if our 'SyncStatus' is 'SSDoingRecovery' (which is
-- equivalent to “we're doing recovery”).
recoveryInProgress :: MonadRecoveryInfo ctx m => SlotCount -> m Bool
recoveryInProgress epochSlots =
getSyncStatus epochSlots 0 {- 0 doesn't matter -} <&> \case
SSDoingRecovery -> True
_ -> False
-- | This is a helper function which runs given action only if we are
-- kinda synchronized with the network. It is useful for workers
-- which shouldn't do anything while we are not synchronized.
recoveryCommGuard
:: (MonadRecoveryInfo ctx m, WithLogger m) => BlockCount -> Text -> m () -> m ()
recoveryCommGuard k actionName action =
getSyncStatus (kEpochSlots k) (kSlotSecurityParam k) >>= \case
SSKindaSynced -> action
status ->
logDebug $
sformat ("recoveryCommGuard: we are skipping action '"%stext%
"', because "%build) actionName status
-- | This function checks that last known block is more than K slots
-- away from the current slot, or current slot isn't known. It also
-- returns False when we're actually doing recovery. So basically it
-- returns true if we actually need to ask for tips right now.
needTriggerRecovery :: SyncStatus -> Bool
needTriggerRecovery = \case
SSKindaSynced -> False
SSDoingRecovery -> False
SSInFuture{} -> False
_ -> True
| input-output-hk/pos-haskell-prototype | infra/src/Pos/Infra/Recovery/Info.hs | mit | 6,138 | 0 | 14 | 1,766 | 993 | 543 | 450 | -1 | -1 |
module BgExplicitVarBind where
f :: Bool
f = True
g = if f then 3 else f
| roberth/uu-helium | test/typeerrors/Examples/BgExplicitVarBind.hs | gpl-3.0 | 75 | 0 | 5 | 19 | 27 | 17 | 10 | 4 | 2 |
{-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses #-}
module Data.Time.Recurrence.AndThen
(
AndThen (..)
)
where
infixr 0 >==>
class AndThen a b c | a b -> c where
(>==>) :: a -> b -> c
| sdiehl/time-recurrence | src/Data/Time/Recurrence/AndThen.hs | lgpl-3.0 | 215 | 0 | 8 | 53 | 58 | 36 | 22 | 7 | 0 |
{-
Copyright 2016 Markus Ongyerth
This file is part of Monky.
Monky is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Monky 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Monky. If not, see <http://www.gnu.org/licenses/>.
-}
{-|
Module : Monky.Outputs.Unicode
Description : Provides helper functions for output generators that use unicode
Maintainer : ongy
Stability : testing
Portability : Linux
-}
module Monky.Outputs.Unicode
where
-- |Unicode block char for vertical bar (in %)
barChar :: Integral a => a -> Char
barChar i
| i <= 0 = ' '
| i < (100 `div` 8) = '▁'
| i < (100 `div` 4) = '▂'
| i < (100 `div` 8 * 3) = '▃'
| i < (100 `div` 2) = '▄'
| i < (100 `div` 8 * 5) = '▅'
| i < (100 `div` 4 * 3) = '▆'
| i < (100 `div` 8 * 7) = '▇'
| otherwise = '█'
-- |Horizontalblock char for horizontal bar (in % of char)
hBarChar :: Integral a => a -> Char
hBarChar i
| i < (100 `div` 8) = '▏'
| i < (100 `div` 4) = '▎'
| i < (100 `div` 8 * 3) = '▍'
| i < (100 `div` 2) = '▌'
| i < (100 `div` 8 * 5) = '▋'
| i < (100 `div` 4 * 3) = '▊'
| i < (100 `div` 8 * 7) = '▉'
| otherwise = '█'
| Ongy/monky | Monky/Outputs/Unicode.hs | lgpl-3.0 | 1,723 | 0 | 11 | 484 | 424 | 227 | 197 | 22 | 1 |
-----------------------------------------------------------------------------------------
-- |
-- Module : FRP.Yampa.Event
-- Copyright : (c) Antony Courtney and Henrik Nilsson, Yale University, 2003
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : nilsson@cs.yale.edu
-- Stability : provisional
-- Portability : portable
--
-- Definition of Yampa Event type.
--
-- Note on naming conventions used in this module.
--
-- Names here might have to be rethought. It's really a bit messy.
-- In general, the aim has been short and convenient names (like 'tag',
-- 'attach', 'lMerge') and thus we have tried to stay away from suffixing/
-- prefixing conventions. E.g. 'Event' as a common suffix would be very
-- verbose.
--
-- However, part of the names come from a desire to stay close to similar
-- functions for the Maybe type. e.g. 'event', 'fromEvent', 'isEvent'.
-- In many cases, this use of 'Event' can could understood to refer to the
-- constructor 'Event', not to the type name 'Event'. Thus this use of
-- event should not be seen as a suffixing-with-type-name convention. But
-- that is obviously not easy to see, and, more over, interpreting 'Event'
-- as the name of the type might make equally good or better sense. E.g.
-- 'fromEvent' can also be seen as a function taking an event signal,
-- which is a partial function on time, to a normal signal. The latter is
-- then undefined when the source event function is undefined.
--
-- In other cases, it has been necessary to somehow stay out of the way of
-- names used by the prelude or other commonly imported modules/modules
-- which could be expected to be used heavily in Yampa code. In those cases
-- a suffix 'E' have been added. Examples are 'filterE' (exists in Prelude)
-- and 'joinE' (exists in Monad). Maybe the suffix isn't necessary in the
-- last case.
--
-- Some functions (actually only one currently, 'mapFilterE') have got an 'E'
-- suffix just because they're closely related (by name or semantics) to one
-- which already has an 'E' suffix. Another candidate would be 'splitE' to
-- complement 'joinE'. But events carrying pairs could obviously have other
-- sources than a 'joinE', so currently it is called 'split'.
--
-- 2003-05-19: Actually, have now changed to 'splitE' to avoid a clash
-- with the method 'split' in the class RandomGen.
--
-- 2003-05-19: What about 'gate'? Stands out compared to e.g. 'filterE'.
--
-- Currently the 'E' suffix is considered an exception. Maybe we should use
-- completely different names to avoid the 'E' suffix. If the functions
-- are not used that often, 'Event' might be approriate. Alternatively the
-- suffix 'E' should be adopted globaly (except if the name already contains
-- 'event' in some form?).
--
-- Arguably, having both a type 'Event' and a constructor 'Event' is confusing
-- since there are more than one constructor. But the name 'Event' for the
-- constructor is quite apt. It's really the type name that is wrong. But
-- no one has found a better name, and changing it would be a really major
-- undertaking. Yes, the constructor 'Event' is not exported, but we still
-- need to talk conceptually about them. On the other hand, if we consider
-- Event-signals as partial functions on time, maybe it isn't so confusing:
-- they just don't have a value between events, so 'NoEvent' does not really
-- exist conceptually.
--
-- ToDo:
-- - Either: reveal NoEvent and Event
-- or: introcuce 'event = Event', call what's now 'event' 'fromEvent',
-- and call what's now called 'fromEvent' something else, like
-- 'unsafeFromEvent'??? Better, dump it! After all, using current
-- names, 'fromEvent = event undefined'!
-----------------------------------------------------------------------------------------
module FRP.Yampa.Event where
-- Event is an instance of Functor, Eq, and Ord. Some method instances:
-- fmap :: (a -> b) -> Event a -> Event b
-- (==) :: Event a -> Event a -> Bool
-- (<=) :: Event a -> Event a -> Bool
import Control.DeepSeq (NFData(..))
import FRP.Yampa.Diagnostics
import FRP.Yampa.Forceable
infixl 8 `tag`, `attach`, `gate`
infixl 7 `joinE`
infixl 6 `lMerge`, `rMerge`, `merge`
------------------------------------------------------------------------------
-- The Event type
------------------------------------------------------------------------------
-- The type Event represents a single possible event occurrence.
-- It is isomorphic to Maybe, but its constructors are not exposed outside
-- the AFRP implementation.
-- There could possibly be further constructors, but note that the NeverEvent-
-- idea does not work, at least not in the current AFRP implementation.
-- Also note that it unfortunately is possible to partially break the
-- abstractions through judicious use of e.g. snap and switching.
-- | A single possible event occurrence, that is, a value that may or may
-- not occur. Events are used to represent values that are not produced
-- continuously, such as mouse clicks (only produced when the mouse is clicked,
-- as opposed to mouse positions, which are always defined).
data Event a = NoEvent | Event a deriving (Show)
-- | Make the NoEvent constructor available. Useful e.g. for initialization,
-- ((-->) & friends), and it's easily available anyway (e.g. mergeEvents []).
noEvent :: Event a
noEvent = NoEvent
-- | Suppress any event in the first component of a pair.
noEventFst :: (Event a, b) -> (Event c, b)
noEventFst (_, b) = (NoEvent, b)
-- | Suppress any event in the second component of a pair.
noEventSnd :: (a, Event b) -> (a, Event c)
noEventSnd (a, _) = (a, NoEvent)
------------------------------------------------------------------------------
-- Eq instance
------------------------------------------------------------------------------
-- Right now, we could derive this instance. But that could possibly change.
instance Eq a => Eq (Event a) where
NoEvent == NoEvent = True
(Event x) == (Event y) = x == y
_ == _ = False
------------------------------------------------------------------------------
-- Ord instance
------------------------------------------------------------------------------
instance Ord a => Ord (Event a) where
compare NoEvent NoEvent = EQ
compare NoEvent (Event _) = LT
compare (Event _) NoEvent = GT
compare (Event x) (Event y) = compare x y
------------------------------------------------------------------------------
-- Functor instance
------------------------------------------------------------------------------
instance Functor Event where
fmap _ NoEvent = NoEvent
fmap f (Event a) = Event (f a)
------------------------------------------------------------------------------
-- Forceable instance
------------------------------------------------------------------------------
instance Forceable a => Forceable (Event a) where
force ea@NoEvent = ea
force ea@(Event a) = force a `seq` ea
------------------------------------------------------------------------------
-- NFData instance
------------------------------------------------------------------------------
instance NFData a => NFData (Event a) where
rnf NoEvent = ()
rnf (Event a) = rnf a `seq` ()
------------------------------------------------------------------------------
-- Internal utilities for event construction
------------------------------------------------------------------------------
-- These utilities are to be considered strictly internal to AFRP for the
-- time being.
maybeToEvent :: Maybe a -> Event a
maybeToEvent Nothing = NoEvent
maybeToEvent (Just a) = Event a
------------------------------------------------------------------------------
-- Utility functions similar to those available for Maybe
------------------------------------------------------------------------------
-- | An event-based version of the maybe function.
event :: a -> (b -> a) -> Event b -> a
event a _ NoEvent = a
event _ f (Event b) = f b
-- | Extract the value from an event. Fails if there is no event.
fromEvent :: Event a -> a
fromEvent (Event a) = a
fromEvent NoEvent = usrErr "AFRP" "fromEvent" "Not an event."
-- | Tests whether the input represents an actual event.
isEvent :: Event a -> Bool
isEvent NoEvent = False
isEvent (Event _) = True
-- | Negation of 'isEvent'.
isNoEvent :: Event a -> Bool
isNoEvent = not . isEvent
------------------------------------------------------------------------------
-- Event tagging
------------------------------------------------------------------------------
-- | Tags an (occurring) event with a value ("replacing" the old value).
tag :: Event a -> b -> Event b
e `tag` b = fmap (const b) e
-- | Tags an (occurring) event with a value ("replacing" the old value). Same
-- as 'tag' with the arguments swapped.
tagWith :: b -> Event a -> Event b
tagWith = flip tag
-- | Attaches an extra value to the value of an occurring event.
attach :: Event a -> b -> Event (a, b)
e `attach` b = fmap (\a -> (a, b)) e
------------------------------------------------------------------------------
-- Event merging (disjunction) and joining (conjunction)
------------------------------------------------------------------------------
-- !!! I think this is too complicated. rMerge can be obtained simply by
-- !!! swapping the arguments. So the only time it is possibly of any
-- !!! interest is for partial app. "merge" is inherently dangerous.
-- !!! But this is NOT obvious from its type: it's type is just like
-- !!! the others. This is the only example of such a def.
-- !!! Finally: mergeEvents is left-biased, but this is not reflected in
-- !!! its name.
-- | Left-biased event merge (always prefer left event, if present).
lMerge :: Event a -> Event a -> Event a
le `lMerge` re = event re Event le
-- | Right-biased event merge (always prefer right event, if present).
rMerge :: Event a -> Event a -> Event a
le `rMerge` re = event le Event re
-- | Unbiased event merge: simultaneous occurrence is an error.
merge :: Event a -> Event a -> Event a
merge = mergeBy (usrErr "AFRP" "merge" "Simultaneous event occurrence.")
-- | Event merge parameterized by a conflict resolution function.
mergeBy :: (a -> a -> a) -> Event a -> Event a -> Event a
mergeBy _ NoEvent NoEvent = NoEvent
mergeBy _ le@(Event _) NoEvent = le
mergeBy _ NoEvent re@(Event _) = re
mergeBy resolve (Event l) (Event r) = Event (resolve l r)
-- | A generic event merge-map utility that maps event occurrences,
-- merging the results. The first three arguments are mapping functions,
-- the third of which will only be used when both events are present.
-- Therefore, 'mergeBy' = 'mapMerge' 'id' 'id'
mapMerge :: (a -> c) -> (b -> c) -> (a -> b -> c)
-> Event a -> Event b -> Event c
mapMerge _ _ _ NoEvent NoEvent = NoEvent
mapMerge lf _ _ (Event l) NoEvent = Event (lf l)
mapMerge _ rf _ NoEvent (Event r) = Event (rf r)
mapMerge _ _ lrf (Event l) (Event r) = Event (lrf l r)
-- | Merge a list of events; foremost event has priority.
mergeEvents :: [Event a] -> Event a
mergeEvents = foldr lMerge NoEvent
-- | Collect simultaneous event occurrences; no event if none.
catEvents :: [Event a] -> Event [a]
catEvents eas = case [ a | Event a <- eas ] of
[] -> NoEvent
as -> Event as
-- | Join (conjunction) of two events. Only produces an event
-- if both events exist.
joinE :: Event a -> Event b -> Event (a,b)
joinE NoEvent _ = NoEvent
joinE _ NoEvent = NoEvent
joinE (Event l) (Event r) = Event (l,r)
-- | Split event carrying pairs into two events.
splitE :: Event (a,b) -> (Event a, Event b)
splitE NoEvent = (NoEvent, NoEvent)
splitE (Event (a,b)) = (Event a, Event b)
------------------------------------------------------------------------------
-- Event filtering
------------------------------------------------------------------------------
-- | Filter out events that don't satisfy some predicate.
filterE :: (a -> Bool) -> Event a -> Event a
filterE p e@(Event a) = if p a then e else NoEvent
filterE _ NoEvent = NoEvent
-- | Combined event mapping and filtering. Note: since 'Event' is a 'Functor',
-- see 'fmap' for a simpler version of this function with no filtering.
mapFilterE :: (a -> Maybe b) -> Event a -> Event b
mapFilterE _ NoEvent = NoEvent
mapFilterE f (Event a) = case f a of
Nothing -> NoEvent
Just b -> Event b
-- | Enable/disable event occurences based on an external condition.
gate :: Event a -> Bool -> Event a
_ `gate` False = NoEvent
e `gate` True = e
| meimisaki/Yampa | src/FRP/Yampa/Event.hs | bsd-3-clause | 12,761 | 0 | 10 | 2,379 | 1,864 | 1,034 | 830 | 93 | 2 |
-----------------------------------------------------------------------------
--
-- The register allocator
--
-- (c) The University of Glasgow 2004
--
-----------------------------------------------------------------------------
{-
The algorithm is roughly:
1) Compute strongly connected components of the basic block list.
2) Compute liveness (mapping from pseudo register to
point(s) of death?).
3) Walk instructions in each basic block. We keep track of
(a) Free real registers (a bitmap?)
(b) Current assignment of temporaries to machine registers and/or
spill slots (call this the "assignment").
(c) Partial mapping from basic block ids to a virt-to-loc mapping.
When we first encounter a branch to a basic block,
we fill in its entry in this table with the current mapping.
For each instruction:
(a) For each temporary *read* by the instruction:
If the temporary does not have a real register allocation:
- Allocate a real register from the free list. If
the list is empty:
- Find a temporary to spill. Pick one that is
not used in this instruction (ToDo: not
used for a while...)
- generate a spill instruction
- If the temporary was previously spilled,
generate an instruction to read the temp from its spill loc.
(optimisation: if we can see that a real register is going to
be used soon, then don't use it for allocation).
(b) For each real register clobbered by this instruction:
If a temporary resides in it,
If the temporary is live after this instruction,
Move the temporary to another (non-clobbered & free) reg,
or spill it to memory. Mark the temporary as residing
in both memory and a register if it was spilled (it might
need to be read by this instruction).
(ToDo: this is wrong for jump instructions?)
We do this after step (a), because if we start with
movq v1, %rsi
which is an instruction that clobbers %rsi, if v1 currently resides
in %rsi we want to get
movq %rsi, %freereg
movq %rsi, %rsi -- will disappear
instead of
movq %rsi, %freereg
movq %freereg, %rsi
(c) Update the current assignment
(d) If the instruction is a branch:
if the destination block already has a register assignment,
Generate a new block with fixup code and redirect the
jump to the new block.
else,
Update the block id->assignment mapping with the current
assignment.
(e) Delete all register assignments for temps which are read
(only) and die here. Update the free register list.
(f) Mark all registers clobbered by this instruction as not free,
and mark temporaries which have been spilled due to clobbering
as in memory (step (a) marks then as in both mem & reg).
(g) For each temporary *written* by this instruction:
Allocate a real register as for (b), spilling something
else if necessary.
- except when updating the assignment, drop any memory
locations that the temporary was previously in, since
they will be no longer valid after this instruction.
(h) Delete all register assignments for temps which are
written and die here (there should rarely be any). Update
the free register list.
(i) Rewrite the instruction with the new mapping.
(j) For each spilled reg known to be now dead, re-add its stack slot
to the free list.
-}
module RegAlloc.Linear.Main (
regAlloc,
module RegAlloc.Linear.Base,
module RegAlloc.Linear.Stats
) where
#include "HsVersions.h"
import RegAlloc.Linear.State
import RegAlloc.Linear.Base
import RegAlloc.Linear.StackMap
import RegAlloc.Linear.FreeRegs
import RegAlloc.Linear.Stats
import RegAlloc.Linear.JoinToTargets
import qualified RegAlloc.Linear.PPC.FreeRegs as PPC
import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC
import qualified RegAlloc.Linear.X86.FreeRegs as X86
import qualified RegAlloc.Linear.X86_64.FreeRegs as X86_64
import TargetReg
import RegAlloc.Liveness
import Instruction
import Reg
import BlockId
import Cmm hiding (RegSet)
import Digraph
import DynFlags
import Unique
import UniqSet
import UniqFM
import UniqSupply
import Outputable
import Platform
import Data.Maybe
import Data.List
import Control.Monad
-- -----------------------------------------------------------------------------
-- Top level of the register allocator
-- Allocate registers
regAlloc
:: (Outputable instr, Instruction instr)
=> DynFlags
-> LiveCmmDecl statics instr
-> UniqSM ( NatCmmDecl statics instr
, Maybe Int -- number of extra stack slots required,
-- beyond maxSpillSlots
, Maybe RegAllocStats)
regAlloc _ (CmmData sec d)
= return
( CmmData sec d
, Nothing
, Nothing )
regAlloc _ (CmmProc (LiveInfo info _ _ _) lbl live [])
= return ( CmmProc info lbl live (ListGraph [])
, Nothing
, Nothing )
regAlloc dflags (CmmProc static lbl live sccs)
| LiveInfo info (Just first_id) (Just block_live) _ <- static
= do
-- do register allocation on each component.
(final_blocks, stats, stack_use)
<- linearRegAlloc dflags first_id block_live sccs
-- make sure the block that was first in the input list
-- stays at the front of the output
let ((first':_), rest')
= partition ((== first_id) . blockId) final_blocks
let max_spill_slots = maxSpillSlots dflags
extra_stack
| stack_use > max_spill_slots
= Just (stack_use - max_spill_slots)
| otherwise
= Nothing
return ( CmmProc info lbl live (ListGraph (first' : rest'))
, extra_stack
, Just stats)
-- bogus. to make non-exhaustive match warning go away.
regAlloc _ (CmmProc _ _ _ _)
= panic "RegAllocLinear.regAlloc: no match"
-- -----------------------------------------------------------------------------
-- Linear sweep to allocate registers
-- | Do register allocation on some basic blocks.
-- But be careful to allocate a block in an SCC only if it has
-- an entry in the block map or it is the first block.
--
linearRegAlloc
:: (Outputable instr, Instruction instr)
=> DynFlags
-> BlockId -- ^ the first block
-> BlockMap RegSet -- ^ live regs on entry to each basic block
-> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths"
-> UniqSM ([NatBasicBlock instr], RegAllocStats, Int)
linearRegAlloc dflags first_id block_live sccs
= let platform = targetPlatform dflags
in case platformArch platform of
ArchX86 -> linearRegAlloc' dflags (frInitFreeRegs platform :: X86.FreeRegs) first_id block_live sccs
ArchX86_64 -> linearRegAlloc' dflags (frInitFreeRegs platform :: X86_64.FreeRegs) first_id block_live sccs
ArchSPARC -> linearRegAlloc' dflags (frInitFreeRegs platform :: SPARC.FreeRegs) first_id block_live sccs
ArchPPC -> linearRegAlloc' dflags (frInitFreeRegs platform :: PPC.FreeRegs) first_id block_live sccs
ArchARM _ _ _ -> panic "linearRegAlloc ArchARM"
ArchPPC_64 -> panic "linearRegAlloc ArchPPC_64"
ArchAlpha -> panic "linearRegAlloc ArchAlpha"
ArchMipseb -> panic "linearRegAlloc ArchMipseb"
ArchMipsel -> panic "linearRegAlloc ArchMipsel"
ArchJavaScript -> panic "linearRegAlloc ArchJavaScript"
ArchUnknown -> panic "linearRegAlloc ArchUnknown"
linearRegAlloc'
:: (FR freeRegs, Outputable instr, Instruction instr)
=> DynFlags
-> freeRegs
-> BlockId -- ^ the first block
-> BlockMap RegSet -- ^ live regs on entry to each basic block
-> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths"
-> UniqSM ([NatBasicBlock instr], RegAllocStats, Int)
linearRegAlloc' dflags initFreeRegs first_id block_live sccs
= do us <- getUs
let (_, stack, stats, blocks) =
runR dflags emptyBlockMap initFreeRegs emptyRegMap (emptyStackMap dflags) us
$ linearRA_SCCs first_id block_live [] sccs
return (blocks, stats, getStackUse stack)
linearRA_SCCs :: (FR freeRegs, Instruction instr, Outputable instr)
=> BlockId
-> BlockMap RegSet
-> [NatBasicBlock instr]
-> [SCC (LiveBasicBlock instr)]
-> RegM freeRegs [NatBasicBlock instr]
linearRA_SCCs _ _ blocksAcc []
= return $ reverse blocksAcc
linearRA_SCCs first_id block_live blocksAcc (AcyclicSCC block : sccs)
= do blocks' <- processBlock block_live block
linearRA_SCCs first_id block_live
((reverse blocks') ++ blocksAcc)
sccs
linearRA_SCCs first_id block_live blocksAcc (CyclicSCC blocks : sccs)
= do
blockss' <- process first_id block_live blocks [] (return []) False
linearRA_SCCs first_id block_live
(reverse (concat blockss') ++ blocksAcc)
sccs
{- from John Dias's patch 2008/10/16:
The linear-scan allocator sometimes allocates a block
before allocating one of its predecessors, which could lead to
inconsistent allocations. Make it so a block is only allocated
if a predecessor has set the "incoming" assignments for the block, or
if it's the procedure's entry block.
BL 2009/02: Careful. If the assignment for a block doesn't get set for
some reason then this function will loop. We should probably do some
more sanity checking to guard against this eventuality.
-}
process :: (FR freeRegs, Instruction instr, Outputable instr)
=> BlockId
-> BlockMap RegSet
-> [GenBasicBlock (LiveInstr instr)]
-> [GenBasicBlock (LiveInstr instr)]
-> [[NatBasicBlock instr]]
-> Bool
-> RegM freeRegs [[NatBasicBlock instr]]
process _ _ [] [] accum _
= return $ reverse accum
process first_id block_live [] next_round accum madeProgress
| not madeProgress
{- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming.
pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out."
( text "Unreachable blocks:"
$$ vcat (map ppr next_round)) -}
= return $ reverse accum
| otherwise
= process first_id block_live
next_round [] accum False
process first_id block_live (b@(BasicBlock id _) : blocks)
next_round accum madeProgress
= do
block_assig <- getBlockAssigR
if isJust (mapLookup id block_assig)
|| id == first_id
then do
b' <- processBlock block_live b
process first_id block_live blocks
next_round (b' : accum) True
else process first_id block_live blocks
(b : next_round) accum madeProgress
-- | Do register allocation on this basic block
--
processBlock
:: (FR freeRegs, Outputable instr, Instruction instr)
=> BlockMap RegSet -- ^ live regs on entry to each basic block
-> LiveBasicBlock instr -- ^ block to do register allocation on
-> RegM freeRegs [NatBasicBlock instr] -- ^ block with registers allocated
processBlock block_live (BasicBlock id instrs)
= do initBlock id block_live
(instrs', fixups)
<- linearRA block_live [] [] id instrs
return $ BasicBlock id instrs' : fixups
-- | Load the freeregs and current reg assignment into the RegM state
-- for the basic block with this BlockId.
initBlock :: FR freeRegs
=> BlockId -> BlockMap RegSet -> RegM freeRegs ()
initBlock id block_live
= do dflags <- getDynFlags
let platform = targetPlatform dflags
block_assig <- getBlockAssigR
case mapLookup id block_assig of
-- no prior info about this block: we must consider
-- any fixed regs to be allocated, but we can ignore
-- virtual regs (presumably this is part of a loop,
-- and we'll iterate again). The assignment begins
-- empty.
Nothing
-> do -- pprTrace "initFreeRegs" (text $ show initFreeRegs) (return ())
case mapLookup id block_live of
Nothing ->
setFreeRegsR (frInitFreeRegs platform)
Just live ->
setFreeRegsR $ foldr (frAllocateReg platform) (frInitFreeRegs platform) [ r | RegReal r <- uniqSetToList live ]
setAssigR emptyRegMap
-- load info about register assignments leading into this block.
Just (freeregs, assig)
-> do setFreeRegsR freeregs
setAssigR assig
-- | Do allocation for a sequence of instructions.
linearRA
:: (FR freeRegs, Outputable instr, Instruction instr)
=> BlockMap RegSet -- ^ map of what vregs are live on entry to each block.
-> [instr] -- ^ accumulator for instructions already processed.
-> [NatBasicBlock instr] -- ^ accumulator for blocks of fixup code.
-> BlockId -- ^ id of the current block, for debugging.
-> [LiveInstr instr] -- ^ liveness annotated instructions in this block.
-> RegM freeRegs
( [instr] -- instructions after register allocation
, [NatBasicBlock instr]) -- fresh blocks of fixup code.
linearRA _ accInstr accFixup _ []
= return
( reverse accInstr -- instrs need to be returned in the correct order.
, accFixup) -- it doesn't matter what order the fixup blocks are returned in.
linearRA block_live accInstr accFixups id (instr:instrs)
= do
(accInstr', new_fixups) <- raInsn block_live accInstr id instr
linearRA block_live accInstr' (new_fixups ++ accFixups) id instrs
-- | Do allocation for a single instruction.
raInsn
:: (FR freeRegs, Outputable instr, Instruction instr)
=> BlockMap RegSet -- ^ map of what vregs are love on entry to each block.
-> [instr] -- ^ accumulator for instructions already processed.
-> BlockId -- ^ the id of the current block, for debugging
-> LiveInstr instr -- ^ the instr to have its regs allocated, with liveness info.
-> RegM freeRegs
( [instr] -- new instructions
, [NatBasicBlock instr]) -- extra fixup blocks
raInsn _ new_instrs _ (LiveInstr ii Nothing)
| Just n <- takeDeltaInstr ii
= do setDeltaR n
return (new_instrs, [])
raInsn _ new_instrs _ (LiveInstr ii Nothing)
| isMetaInstr ii
= return (new_instrs, [])
raInsn block_live new_instrs id (LiveInstr (Instr instr) (Just live))
= do
assig <- getAssigR
-- If we have a reg->reg move between virtual registers, where the
-- src register is not live after this instruction, and the dst
-- register does not already have an assignment,
-- and the source register is assigned to a register, not to a spill slot,
-- then we can eliminate the instruction.
-- (we can't eliminate it if the source register is on the stack, because
-- we do not want to use one spill slot for different virtual registers)
case takeRegRegMoveInstr instr of
Just (src,dst) | src `elementOfUniqSet` (liveDieRead live),
isVirtualReg dst,
not (dst `elemUFM` assig),
isRealReg src || isInReg src assig -> do
case src of
(RegReal rr) -> setAssigR (addToUFM assig dst (InReg rr))
-- if src is a fixed reg, then we just map dest to this
-- reg in the assignment. src must be an allocatable reg,
-- otherwise it wouldn't be in r_dying.
_virt -> case lookupUFM assig src of
Nothing -> panic "raInsn"
Just loc ->
setAssigR (addToUFM (delFromUFM assig src) dst loc)
-- we have eliminated this instruction
{-
freeregs <- getFreeRegsR
assig <- getAssigR
pprTrace "raInsn" (text "ELIMINATED: " <> docToSDoc (pprInstr instr)
$$ ppr r_dying <+> ppr w_dying $$ text (show freeregs) $$ ppr assig) $ do
-}
return (new_instrs, [])
_ -> genRaInsn block_live new_instrs id instr
(uniqSetToList $ liveDieRead live)
(uniqSetToList $ liveDieWrite live)
raInsn _ _ _ instr
= pprPanic "raInsn" (text "no match for:" <> ppr instr)
-- ToDo: what can we do about
--
-- R1 = x
-- jump I64[x] // [R1]
--
-- where x is mapped to the same reg as R1. We want to coalesce x and
-- R1, but the register allocator doesn't know whether x will be
-- assigned to again later, in which case x and R1 should be in
-- different registers. Right now we assume the worst, and the
-- assignment to R1 will clobber x, so we'll spill x into another reg,
-- generating another reg->reg move.
isInReg :: Reg -> RegMap Loc -> Bool
isInReg src assig | Just (InReg _) <- lookupUFM assig src = True
| otherwise = False
genRaInsn :: (FR freeRegs, Instruction instr, Outputable instr)
=> BlockMap RegSet
-> [instr]
-> BlockId
-> instr
-> [Reg]
-> [Reg]
-> RegM freeRegs ([instr], [NatBasicBlock instr])
genRaInsn block_live new_instrs block_id instr r_dying w_dying = do
dflags <- getDynFlags
let platform = targetPlatform dflags
case regUsageOfInstr platform instr of { RU read written ->
do
let real_written = [ rr | (RegReal rr) <- written ]
let virt_written = [ vr | (RegVirtual vr) <- written ]
-- we don't need to do anything with real registers that are
-- only read by this instr. (the list is typically ~2 elements,
-- so using nub isn't a problem).
let virt_read = nub [ vr | (RegVirtual vr) <- read ]
-- debugging
{- freeregs <- getFreeRegsR
assig <- getAssigR
pprDebugAndThen (defaultDynFlags Settings{ sTargetPlatform=platform }) trace "genRaInsn"
(ppr instr
$$ text "r_dying = " <+> ppr r_dying
$$ text "w_dying = " <+> ppr w_dying
$$ text "virt_read = " <+> ppr virt_read
$$ text "virt_written = " <+> ppr virt_written
$$ text "freeregs = " <+> text (show freeregs)
$$ text "assig = " <+> ppr assig)
$ do
-}
-- (a), (b) allocate real regs for all regs read by this instruction.
(r_spills, r_allocd) <-
allocateRegsAndSpill True{-reading-} virt_read [] [] virt_read
-- (c) save any temporaries which will be clobbered by this instruction
clobber_saves <- saveClobberedTemps real_written r_dying
-- (d) Update block map for new destinations
-- NB. do this before removing dead regs from the assignment, because
-- these dead regs might in fact be live in the jump targets (they're
-- only dead in the code that follows in the current basic block).
(fixup_blocks, adjusted_instr)
<- joinToTargets block_live block_id instr
-- (e) Delete all register assignments for temps which are read
-- (only) and die here. Update the free register list.
releaseRegs r_dying
-- (f) Mark regs which are clobbered as unallocatable
clobberRegs real_written
-- (g) Allocate registers for temporaries *written* (only)
(w_spills, w_allocd) <-
allocateRegsAndSpill False{-writing-} virt_written [] [] virt_written
-- (h) Release registers for temps which are written here and not
-- used again.
releaseRegs w_dying
let
-- (i) Patch the instruction
patch_map
= listToUFM
[ (t, RegReal r)
| (t, r) <- zip virt_read r_allocd
++ zip virt_written w_allocd ]
patched_instr
= patchRegsOfInstr adjusted_instr patchLookup
patchLookup x
= case lookupUFM patch_map x of
Nothing -> x
Just y -> y
-- (j) free up stack slots for dead spilled regs
-- TODO (can't be bothered right now)
-- erase reg->reg moves where the source and destination are the same.
-- If the src temp didn't die in this instr but happened to be allocated
-- to the same real reg as the destination, then we can erase the move anyway.
let squashed_instr = case takeRegRegMoveInstr patched_instr of
Just (src, dst)
| src == dst -> []
_ -> [patched_instr]
let code = squashed_instr ++ w_spills ++ reverse r_spills
++ clobber_saves ++ new_instrs
-- pprTrace "patched-code" ((vcat $ map (docToSDoc . pprInstr) code)) $ do
-- pprTrace "pached-fixup" ((ppr fixup_blocks)) $ do
return (code, fixup_blocks)
}
-- -----------------------------------------------------------------------------
-- releaseRegs
releaseRegs :: FR freeRegs => [Reg] -> RegM freeRegs ()
releaseRegs regs = do
dflags <- getDynFlags
let platform = targetPlatform dflags
assig <- getAssigR
free <- getFreeRegsR
let loop _ free _ | free `seq` False = undefined
loop assig free [] = do setAssigR assig; setFreeRegsR free; return ()
loop assig free (RegReal rr : rs) = loop assig (frReleaseReg platform rr free) rs
loop assig free (r:rs) =
case lookupUFM assig r of
Just (InBoth real _) -> loop (delFromUFM assig r)
(frReleaseReg platform real free) rs
Just (InReg real) -> loop (delFromUFM assig r)
(frReleaseReg platform real free) rs
_ -> loop (delFromUFM assig r) free rs
loop assig free regs
-- -----------------------------------------------------------------------------
-- Clobber real registers
-- For each temp in a register that is going to be clobbered:
-- - if the temp dies after this instruction, do nothing
-- - otherwise, put it somewhere safe (another reg if possible,
-- otherwise spill and record InBoth in the assignment).
-- - for allocateRegs on the temps *read*,
-- - clobbered regs are allocatable.
--
-- for allocateRegs on the temps *written*,
-- - clobbered regs are not allocatable.
--
saveClobberedTemps
:: (Outputable instr, Instruction instr, FR freeRegs)
=> [RealReg] -- real registers clobbered by this instruction
-> [Reg] -- registers which are no longer live after this insn
-> RegM freeRegs [instr] -- return: instructions to spill any temps that will
-- be clobbered.
saveClobberedTemps [] _
= return []
saveClobberedTemps clobbered dying
= do
assig <- getAssigR
let to_spill
= [ (temp,reg)
| (temp, InReg reg) <- ufmToList assig
, any (realRegsAlias reg) clobbered
, temp `notElem` map getUnique dying ]
(instrs,assig') <- clobber assig [] to_spill
setAssigR assig'
return instrs
where
clobber assig instrs []
= return (instrs, assig)
clobber assig instrs ((temp, reg) : rest)
= do dflags <- getDynFlags
let platform = targetPlatform dflags
freeRegs <- getFreeRegsR
let regclass = targetClassOfRealReg platform reg
freeRegs_thisClass = frGetFreeRegs platform regclass freeRegs
case filter (`notElem` clobbered) freeRegs_thisClass of
-- (1) we have a free reg of the right class that isn't
-- clobbered by this instruction; use it to save the
-- clobbered value.
(my_reg : _) -> do
setFreeRegsR (frAllocateReg platform my_reg freeRegs)
let new_assign = addToUFM assig temp (InReg my_reg)
let instr = mkRegRegMoveInstr platform
(RegReal reg) (RegReal my_reg)
clobber new_assign (instr : instrs) rest
-- (2) no free registers: spill the value
[] -> do
(spill, slot) <- spillR (RegReal reg) temp
-- record why this reg was spilled for profiling
recordSpill (SpillClobber temp)
let new_assign = addToUFM assig temp (InBoth reg slot)
clobber new_assign (spill : instrs) rest
-- | Mark all these real regs as allocated,
-- and kick out their vreg assignments.
--
clobberRegs :: FR freeRegs => [RealReg] -> RegM freeRegs ()
clobberRegs []
= return ()
clobberRegs clobbered
= do dflags <- getDynFlags
let platform = targetPlatform dflags
freeregs <- getFreeRegsR
setFreeRegsR $! foldr (frAllocateReg platform) freeregs clobbered
assig <- getAssigR
setAssigR $! clobber assig (ufmToList assig)
where
-- if the temp was InReg and clobbered, then we will have
-- saved it in saveClobberedTemps above. So the only case
-- we have to worry about here is InBoth. Note that this
-- also catches temps which were loaded up during allocation
-- of read registers, not just those saved in saveClobberedTemps.
clobber assig []
= assig
clobber assig ((temp, InBoth reg slot) : rest)
| any (realRegsAlias reg) clobbered
= clobber (addToUFM assig temp (InMem slot)) rest
clobber assig (_:rest)
= clobber assig rest
-- -----------------------------------------------------------------------------
-- allocateRegsAndSpill
-- Why are we performing a spill?
data SpillLoc = ReadMem StackSlot -- reading from register only in memory
| WriteNew -- writing to a new variable
| WriteMem -- writing to register only in memory
-- Note that ReadNew is not valid, since you don't want to be reading
-- from an uninitialized register. We also don't need the location of
-- the register in memory, since that will be invalidated by the write.
-- Technically, we could coalesce WriteNew and WriteMem into a single
-- entry as well. -- EZY
-- This function does several things:
-- For each temporary referred to by this instruction,
-- we allocate a real register (spilling another temporary if necessary).
-- We load the temporary up from memory if necessary.
-- We also update the register assignment in the process, and
-- the list of free registers and free stack slots.
allocateRegsAndSpill
:: (FR freeRegs, Outputable instr, Instruction instr)
=> Bool -- True <=> reading (load up spilled regs)
-> [VirtualReg] -- don't push these out
-> [instr] -- spill insns
-> [RealReg] -- real registers allocated (accum.)
-> [VirtualReg] -- temps to allocate
-> RegM freeRegs ( [instr] , [RealReg])
allocateRegsAndSpill _ _ spills alloc []
= return (spills, reverse alloc)
allocateRegsAndSpill reading keep spills alloc (r:rs)
= do assig <- getAssigR
let doSpill = allocRegsAndSpill_spill reading keep spills alloc r rs assig
case lookupUFM assig r of
-- case (1a): already in a register
Just (InReg my_reg) ->
allocateRegsAndSpill reading keep spills (my_reg:alloc) rs
-- case (1b): already in a register (and memory)
-- NB1. if we're writing this register, update its assignment to be
-- InReg, because the memory value is no longer valid.
-- NB2. This is why we must process written registers here, even if they
-- are also read by the same instruction.
Just (InBoth my_reg _)
-> do when (not reading) (setAssigR (addToUFM assig r (InReg my_reg)))
allocateRegsAndSpill reading keep spills (my_reg:alloc) rs
-- Not already in a register, so we need to find a free one...
Just (InMem slot) | reading -> doSpill (ReadMem slot)
| otherwise -> doSpill WriteMem
Nothing | reading ->
pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr r)
-- NOTE: if the input to the NCG contains some
-- unreachable blocks with junk code, this panic
-- might be triggered. Make sure you only feed
-- sensible code into the NCG. In CmmPipeline we
-- call removeUnreachableBlocks at the end for this
-- reason.
| otherwise -> doSpill WriteNew
-- reading is redundant with reason, but we keep it around because it's
-- convenient and it maintains the recursive structure of the allocator. -- EZY
allocRegsAndSpill_spill :: (FR freeRegs, Instruction instr, Outputable instr)
=> Bool
-> [VirtualReg]
-> [instr]
-> [RealReg]
-> VirtualReg
-> [VirtualReg]
-> UniqFM Loc
-> SpillLoc
-> RegM freeRegs ([instr], [RealReg])
allocRegsAndSpill_spill reading keep spills alloc r rs assig spill_loc
= do dflags <- getDynFlags
let platform = targetPlatform dflags
freeRegs <- getFreeRegsR
let freeRegs_thisClass = frGetFreeRegs platform (classOfVirtualReg r) freeRegs
case freeRegs_thisClass of
-- case (2): we have a free register
(my_reg : _) ->
do spills' <- loadTemp r spill_loc my_reg spills
setAssigR (addToUFM assig r $! newLocation spill_loc my_reg)
setFreeRegsR $ frAllocateReg platform my_reg freeRegs
allocateRegsAndSpill reading keep spills' (my_reg : alloc) rs
-- case (3): we need to push something out to free up a register
[] ->
do let keep' = map getUnique keep
-- the vregs we could kick out that are already in a slot
let candidates_inBoth
= [ (temp, reg, mem)
| (temp, InBoth reg mem) <- ufmToList assig
, temp `notElem` keep'
, targetClassOfRealReg platform reg == classOfVirtualReg r ]
-- the vregs we could kick out that are only in a reg
-- this would require writing the reg to a new slot before using it.
let candidates_inReg
= [ (temp, reg)
| (temp, InReg reg) <- ufmToList assig
, temp `notElem` keep'
, targetClassOfRealReg platform reg == classOfVirtualReg r ]
let result
-- we have a temporary that is in both register and mem,
-- just free up its register for use.
| (temp, my_reg, slot) : _ <- candidates_inBoth
= do spills' <- loadTemp r spill_loc my_reg spills
let assig1 = addToUFM assig temp (InMem slot)
let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg
setAssigR assig2
allocateRegsAndSpill reading keep spills' (my_reg:alloc) rs
-- otherwise, we need to spill a temporary that currently
-- resides in a register.
| (temp_to_push_out, (my_reg :: RealReg)) : _
<- candidates_inReg
= do
(spill_insn, slot) <- spillR (RegReal my_reg) temp_to_push_out
let spill_store = (if reading then id else reverse)
[ -- COMMENT (fsLit "spill alloc")
spill_insn ]
-- record that this temp was spilled
recordSpill (SpillAlloc temp_to_push_out)
-- update the register assignment
let assig1 = addToUFM assig temp_to_push_out (InMem slot)
let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg
setAssigR assig2
-- if need be, load up a spilled temp into the reg we've just freed up.
spills' <- loadTemp r spill_loc my_reg spills
allocateRegsAndSpill reading keep
(spill_store ++ spills')
(my_reg:alloc) rs
-- there wasn't anything to spill, so we're screwed.
| otherwise
= pprPanic ("RegAllocLinear.allocRegsAndSpill: no spill candidates\n")
$ vcat
[ text "allocating vreg: " <> text (show r)
, text "assignment: " <> text (show $ ufmToList assig)
, text "freeRegs: " <> text (show freeRegs)
, text "initFreeRegs: " <> text (show (frInitFreeRegs platform `asTypeOf` freeRegs)) ]
result
-- | Calculate a new location after a register has been loaded.
newLocation :: SpillLoc -> RealReg -> Loc
-- if the tmp was read from a slot, then now its in a reg as well
newLocation (ReadMem slot) my_reg = InBoth my_reg slot
-- writes will always result in only the register being available
newLocation _ my_reg = InReg my_reg
-- | Load up a spilled temporary if we need to (read from memory).
loadTemp
:: (Outputable instr, Instruction instr)
=> VirtualReg -- the temp being loaded
-> SpillLoc -- the current location of this temp
-> RealReg -- the hreg to load the temp into
-> [instr]
-> RegM freeRegs [instr]
loadTemp vreg (ReadMem slot) hreg spills
= do
insn <- loadR (RegReal hreg) slot
recordSpill (SpillLoad $ getUnique vreg)
return $ {- COMMENT (fsLit "spill load") : -} insn : spills
loadTemp _ _ _ spills =
return spills
| jwiegley/ghc-release | compiler/nativeGen/RegAlloc/Linear/Main.hs | gpl-3.0 | 36,788 | 6 | 29 | 12,994 | 5,713 | 2,911 | 2,802 | -1 | -1 |
{-
(c) The AQUA Project, Glasgow University, 1994-1998
\section[LiberateCase]{Unroll recursion to allow evals to be lifted from a loop}
-}
{-# LANGUAGE CPP #-}
module ETA.SimplCore.LiberateCase ( liberateCase ) where
#include "HsVersions.h"
import ETA.Main.DynFlags
import ETA.Core.CoreSyn
import ETA.Core.CoreUnfold ( couldBeSmallEnoughToInline )
import ETA.BasicTypes.Id
import ETA.BasicTypes.VarEnv
import ETA.Utils.Util ( notNull )
{-
The liberate-case transformation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module walks over @Core@, and looks for @case@ on free variables.
The criterion is:
if there is case on a free on the route to the recursive call,
then the recursive call is replaced with an unfolding.
Example
f = \ t -> case v of
V a b -> a : f t
=> the inner f is replaced.
f = \ t -> case v of
V a b -> a : (letrec
f = \ t -> case v of
V a b -> a : f t
in f) t
(note the NEED for shadowing)
=> Simplify
f = \ t -> case v of
V a b -> a : (letrec
f = \ t -> a : f t
in f t)
Better code, because 'a' is free inside the inner letrec, rather
than needing projection from v.
Note that this deals with *free variables*. SpecConstr deals with
*arguments* that are of known form. E.g.
last [] = error
last (x:[]) = x
last (x:xs) = last xs
Note [Scrutinee with cast]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:
f = \ t -> case (v `cast` co) of
V a b -> a : f t
Exactly the same optimisation (unrolling one call to f) will work here,
despite the cast. See mk_alt_env in the Case branch of libCase.
Note [Only functions!]
~~~~~~~~~~~~~~~~~~~~~~
Consider the following code
f = g (case v of V a b -> a : t f)
where g is expensive. If we aren't careful, liberate case will turn this into
f = g (case v of
V a b -> a : t (letrec f = g (case v of V a b -> a : f t)
in f)
)
Yikes! We evaluate g twice. This leads to a O(2^n) explosion
if g calls back to the same code recursively.
Solution: make sure that we only do the liberate-case thing on *functions*
To think about (Apr 94)
~~~~~~~~~~~~~~
Main worry: duplicating code excessively. At the moment we duplicate
the entire binding group once at each recursive call. But there may
be a group of recursive calls which share a common set of evaluated
free variables, in which case the duplication is a plain waste.
Another thing we could consider adding is some unfold-threshold thing,
so that we'll only duplicate if the size of the group rhss isn't too
big.
Data types
~~~~~~~~~~
The ``level'' of a binder tells how many
recursive defns lexically enclose the binding
A recursive defn "encloses" its RHS, not its
scope. For example:
\begin{verbatim}
letrec f = let g = ... in ...
in
let h = ...
in ...
\end{verbatim}
Here, the level of @f@ is zero, the level of @g@ is one,
and the level of @h@ is zero (NB not one).
************************************************************************
* *
Top-level code
* *
************************************************************************
-}
liberateCase :: DynFlags -> CoreProgram -> CoreProgram
liberateCase dflags binds = do_prog (initEnv dflags) binds
where
do_prog _ [] = []
do_prog env (bind:binds) = bind' : do_prog env' binds
where
(env', bind') = libCaseBind env bind
{-
************************************************************************
* *
Main payload
* *
************************************************************************
Bindings
~~~~~~~~
-}
libCaseBind :: LibCaseEnv -> CoreBind -> (LibCaseEnv, CoreBind)
libCaseBind env (NonRec binder rhs)
= (addBinders env [binder], NonRec binder (libCase env rhs))
libCaseBind env (Rec pairs)
= (env_body, Rec pairs')
where
binders = map fst pairs
env_body = addBinders env binders
pairs' = [(binder, libCase env_rhs rhs) | (binder,rhs) <- pairs]
-- We extend the rec-env by binding each Id to its rhs, first
-- processing the rhs with an *un-extended* environment, so
-- that the same process doesn't occur for ever!
env_rhs = addRecBinds env [ (localiseId binder, libCase env_body rhs)
| (binder, rhs) <- pairs
, rhs_small_enough binder rhs ]
-- localiseID : see Note [Need to localiseId in libCaseBind]
rhs_small_enough id rhs -- Note [Small enough]
= idArity id > 0 -- Note [Only functions!]
&& maybe True (\size -> couldBeSmallEnoughToInline (lc_dflags env) size rhs)
(bombOutSize env)
{-
Note [Need to localiseId in libCaseBind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The call to localiseId is needed for two subtle reasons
(a) Reset the export flags on the binders so
that we don't get name clashes on exported things if the
local binding floats out to top level. This is most unlikely
to happen, since the whole point concerns free variables.
But resetting the export flag is right regardless.
(b) Make the name an Internal one. External Names should never be
nested; if it were floated to the top level, we'd get a name
clash at code generation time.
Note [Small enough]
~~~~~~~~~~~~~~~~~~~
Consider
\fv. letrec
f = \x. BIG...(case fv of { (a,b) -> ...g.. })...
g = \y. SMALL...f...
Then we *can* do liberate-case on g (small RHS) but not for f (too big).
But we can choose on a item-by-item basis, and that's what the
rhs_small_enough call in the comprehension for env_rhs does.
Expressions
~~~~~~~~~~~
-}
libCase :: LibCaseEnv
-> CoreExpr
-> CoreExpr
libCase env (Var v) = libCaseId env v
libCase _ (Lit lit) = Lit lit
libCase _ (Type ty) = Type ty
libCase _ (Coercion co) = Coercion co
libCase env (App fun arg) = App (libCase env fun) (libCase env arg)
libCase env (Tick tickish body) = Tick tickish (libCase env body)
libCase env (Cast e co) = Cast (libCase env e) co
libCase env (Lam binder body)
= Lam binder (libCase (addBinders env [binder]) body)
libCase env (Let bind body)
= Let bind' (libCase env_body body)
where
(env_body, bind') = libCaseBind env bind
libCase env (Case scrut bndr ty alts)
= Case (libCase env scrut) bndr ty (map (libCaseAlt env_alts) alts)
where
env_alts = addBinders (mk_alt_env scrut) [bndr]
mk_alt_env (Var scrut_var) = addScrutedVar env scrut_var
mk_alt_env (Cast scrut _) = mk_alt_env scrut -- Note [Scrutinee with cast]
mk_alt_env _ = env
libCaseAlt :: LibCaseEnv -> (AltCon, [CoreBndr], CoreExpr)
-> (AltCon, [CoreBndr], CoreExpr)
libCaseAlt env (con,args,rhs) = (con, args, libCase (addBinders env args) rhs)
{-
Ids
~~~
-}
libCaseId :: LibCaseEnv -> Id -> CoreExpr
libCaseId env v
| Just the_bind <- lookupRecId env v -- It's a use of a recursive thing
, notNull free_scruts -- with free vars scrutinised in RHS
= Let the_bind (Var v)
| otherwise
= Var v
where
rec_id_level = lookupLevel env v
free_scruts = freeScruts env rec_id_level
freeScruts :: LibCaseEnv
-> LibCaseLevel -- Level of the recursive Id
-> [Id] -- Ids that are scrutinised between the binding
-- of the recursive Id and here
freeScruts env rec_bind_lvl
= [v | (v, scrut_bind_lvl, scrut_at_lvl) <- lc_scruts env
, scrut_bind_lvl <= rec_bind_lvl
, scrut_at_lvl > rec_bind_lvl]
-- Note [When to specialise]
-- Note [Avoiding fruitless liberate-case]
{-
Note [When to specialise]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f = \x. letrec g = \y. case x of
True -> ... (f a) ...
False -> ... (g b) ...
We get the following levels
f 0
x 1
g 1
y 2
Then 'x' is being scrutinised at a deeper level than its binding, so
it's added to lc_sruts: [(x,1)]
We do *not* want to specialise the call to 'f', because 'x' is not free
in 'f'. So here the bind-level of 'x' (=1) is not <= the bind-level of 'f' (=0).
We *do* want to specialise the call to 'g', because 'x' is free in g.
Here the bind-level of 'x' (=1) is <= the bind-level of 'g' (=1).
Note [Avoiding fruitless liberate-case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider also:
f = \x. case top_lvl_thing of
I# _ -> let g = \y. ... g ...
in ...
Here, top_lvl_thing is scrutinised at a level (1) deeper than its
binding site (0). Nevertheless, we do NOT want to specialise the call
to 'g' because all the structure in its free variables is already
visible at the definition site for g. Hence, when considering specialising
an occurrence of 'g', we want to check that there's a scruted-var v st
a) v's binding site is *outside* g
b) v's scrutinisation site is *inside* g
************************************************************************
* *
Utility functions
* *
************************************************************************
-}
addBinders :: LibCaseEnv -> [CoreBndr] -> LibCaseEnv
addBinders env@(LibCaseEnv { lc_lvl = lvl, lc_lvl_env = lvl_env }) binders
= env { lc_lvl_env = lvl_env' }
where
lvl_env' = extendVarEnvList lvl_env (binders `zip` repeat lvl)
addRecBinds :: LibCaseEnv -> [(Id,CoreExpr)] -> LibCaseEnv
addRecBinds env@(LibCaseEnv {lc_lvl = lvl, lc_lvl_env = lvl_env,
lc_rec_env = rec_env}) pairs
= env { lc_lvl = lvl', lc_lvl_env = lvl_env', lc_rec_env = rec_env' }
where
lvl' = lvl + 1
lvl_env' = extendVarEnvList lvl_env [(binder,lvl) | (binder,_) <- pairs]
rec_env' = extendVarEnvList rec_env [(binder, Rec pairs) | (binder,_) <- pairs]
addScrutedVar :: LibCaseEnv
-> Id -- This Id is being scrutinised by a case expression
-> LibCaseEnv
addScrutedVar env@(LibCaseEnv { lc_lvl = lvl, lc_lvl_env = lvl_env,
lc_scruts = scruts }) scrut_var
| bind_lvl < lvl
= env { lc_scruts = scruts' }
-- Add to scruts iff the scrut_var is being scrutinised at
-- a deeper level than its defn
| otherwise = env
where
scruts' = (scrut_var, bind_lvl, lvl) : scruts
bind_lvl = case lookupVarEnv lvl_env scrut_var of
Just lvl -> lvl
Nothing -> topLevel
lookupRecId :: LibCaseEnv -> Id -> Maybe CoreBind
lookupRecId env id = lookupVarEnv (lc_rec_env env) id
lookupLevel :: LibCaseEnv -> Id -> LibCaseLevel
lookupLevel env id
= case lookupVarEnv (lc_lvl_env env) id of
Just lvl -> lvl
Nothing -> topLevel
{-
************************************************************************
* *
The environment
* *
************************************************************************
-}
type LibCaseLevel = Int
topLevel :: LibCaseLevel
topLevel = 0
data LibCaseEnv
= LibCaseEnv {
lc_dflags :: DynFlags,
lc_lvl :: LibCaseLevel, -- Current level
-- The level is incremented when (and only when) going
-- inside the RHS of a (sufficiently small) recursive
-- function.
lc_lvl_env :: IdEnv LibCaseLevel,
-- Binds all non-top-level in-scope Ids (top-level and
-- imported things have a level of zero)
lc_rec_env :: IdEnv CoreBind,
-- Binds *only* recursively defined ids, to their own
-- binding group, and *only* in their own RHSs
lc_scruts :: [(Id, LibCaseLevel, LibCaseLevel)]
-- Each of these Ids was scrutinised by an enclosing
-- case expression, at a level deeper than its binding
-- level.
--
-- The first LibCaseLevel is the *binding level* of
-- the scrutinised Id,
-- The second is the level *at which it was scrutinised*.
-- (see Note [Avoiding fruitless liberate-case])
-- The former is a bit redundant, since you could always
-- look it up in lc_lvl_env, but it's just cached here
--
-- The order is insignificant; it's a bag really
--
-- There's one element per scrutinisation;
-- in principle the same Id may appear multiple times,
-- although that'd be unusual:
-- case x of { (a,b) -> ....(case x of ...) .. }
}
initEnv :: DynFlags -> LibCaseEnv
initEnv dflags
= LibCaseEnv { lc_dflags = dflags,
lc_lvl = 0,
lc_lvl_env = emptyVarEnv,
lc_rec_env = emptyVarEnv,
lc_scruts = [] }
-- Bomb-out size for deciding if
-- potential liberatees are too big.
-- (passed in from cmd-line args)
bombOutSize :: LibCaseEnv -> Maybe Int
bombOutSize = liberateCaseThreshold . lc_dflags
| alexander-at-github/eta | compiler/ETA/SimplCore/LiberateCase.hs | bsd-3-clause | 13,988 | 0 | 13 | 4,477 | 1,695 | 929 | 766 | 117 | 3 |
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeOperators #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Functor.Contravariant
-- Copyright : (C) 2007-2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- 'Contravariant' functors, sometimes referred to colloquially as @Cofunctor@,
-- even though the dual of a 'Functor' is just a 'Functor'. As with 'Functor'
-- the definition of 'Contravariant' for a given ADT is unambiguous.
--
-- @since 4.12.0.0
----------------------------------------------------------------------------
module Data.Functor.Contravariant (
-- * Contravariant Functors
Contravariant(..)
, phantom
-- * Operators
, (>$<), (>$$<), ($<)
-- * Predicates
, Predicate(..)
-- * Comparisons
, Comparison(..)
, defaultComparison
-- * Equivalence Relations
, Equivalence(..)
, defaultEquivalence
, comparisonEquivalence
-- * Dual arrows
, Op(..)
) where
import Control.Applicative
import Control.Category
import Data.Function (on)
import Data.Functor.Product
import Data.Functor.Sum
import Data.Functor.Compose
import Data.Monoid (Alt(..))
import Data.Proxy
import GHC.Generics
import Prelude hiding ((.),id)
-- | The class of contravariant functors.
--
-- Whereas in Haskell, one can think of a 'Functor' as containing or producing
-- values, a contravariant functor is a functor that can be thought of as
-- /consuming/ values.
--
-- As an example, consider the type of predicate functions @a -> Bool@. One
-- such predicate might be @negative x = x < 0@, which
-- classifies integers as to whether they are negative. However, given this
-- predicate, we can re-use it in other situations, providing we have a way to
-- map values /to/ integers. For instance, we can use the @negative@ predicate
-- on a person's bank balance to work out if they are currently overdrawn:
--
-- @
-- newtype Predicate a = Predicate { getPredicate :: a -> Bool }
--
-- instance Contravariant Predicate where
-- contramap f (Predicate p) = Predicate (p . f)
-- | `- First, map the input...
-- `----- then apply the predicate.
--
-- overdrawn :: Predicate Person
-- overdrawn = contramap personBankBalance negative
-- @
--
-- Any instance should be subject to the following laws:
--
-- [Identity] @'contramap' 'id' = 'id'@
-- [Composition] @'contramap' (g . f) = 'contramap' f . 'contramap' g@
--
-- Note, that the second law follows from the free theorem of the type of
-- 'contramap' and the first law, so you need only check that the former
-- condition holds.
class Contravariant f where
contramap :: (a -> b) -> f b -> f a
-- | Replace all locations in the output with the same value.
-- The default definition is @'contramap' . 'const'@, but this may be
-- overridden with a more efficient version.
(>$) :: b -> f b -> f a
(>$) = contramap . const
-- | If @f@ is both 'Functor' and 'Contravariant' then by the time you factor
-- in the laws of each of those classes, it can't actually use its argument in
-- any meaningful capacity.
--
-- This method is surprisingly useful. Where both instances exist and are
-- lawful we have the following laws:
--
-- @
-- 'fmap' f ≡ 'phantom'
-- 'contramap' f ≡ 'phantom'
-- @
phantom :: (Functor f, Contravariant f) => f a -> f b
phantom x = () <$ x $< ()
infixl 4 >$, $<, >$<, >$$<
-- | This is '>$' with its arguments flipped.
($<) :: Contravariant f => f b -> b -> f a
($<) = flip (>$)
-- | This is an infix alias for 'contramap'.
(>$<) :: Contravariant f => (a -> b) -> f b -> f a
(>$<) = contramap
-- | This is an infix version of 'contramap' with the arguments flipped.
(>$$<) :: Contravariant f => f b -> (a -> b) -> f a
(>$$<) = flip contramap
deriving instance Contravariant f => Contravariant (Alt f)
deriving instance Contravariant f => Contravariant (Rec1 f)
deriving instance Contravariant f => Contravariant (M1 i c f)
instance Contravariant V1 where
contramap _ x = case x of
instance Contravariant U1 where
contramap _ _ = U1
instance Contravariant (K1 i c) where
contramap _ (K1 c) = K1 c
instance (Contravariant f, Contravariant g) => Contravariant (f :*: g) where
contramap f (xs :*: ys) = contramap f xs :*: contramap f ys
instance (Functor f, Contravariant g) => Contravariant (f :.: g) where
contramap f (Comp1 fg) = Comp1 (fmap (contramap f) fg)
instance (Contravariant f, Contravariant g) => Contravariant (f :+: g) where
contramap f (L1 xs) = L1 (contramap f xs)
contramap f (R1 ys) = R1 (contramap f ys)
instance (Contravariant f, Contravariant g) => Contravariant (Sum f g) where
contramap f (InL xs) = InL (contramap f xs)
contramap f (InR ys) = InR (contramap f ys)
instance (Contravariant f, Contravariant g)
=> Contravariant (Product f g) where
contramap f (Pair a b) = Pair (contramap f a) (contramap f b)
instance Contravariant (Const a) where
contramap _ (Const a) = Const a
instance (Functor f, Contravariant g) => Contravariant (Compose f g) where
contramap f (Compose fga) = Compose (fmap (contramap f) fga)
instance Contravariant Proxy where
contramap _ _ = Proxy
newtype Predicate a = Predicate { getPredicate :: a -> Bool }
-- | A 'Predicate' is a 'Contravariant' 'Functor', because 'contramap' can
-- apply its function argument to the input of the predicate.
instance Contravariant Predicate where
contramap f g = Predicate $ getPredicate g . f
instance Semigroup (Predicate a) where
Predicate p <> Predicate q = Predicate $ \a -> p a && q a
instance Monoid (Predicate a) where
mempty = Predicate $ const True
-- | Defines a total ordering on a type as per 'compare'.
--
-- This condition is not checked by the types. You must ensure that the
-- supplied values are valid total orderings yourself.
newtype Comparison a = Comparison { getComparison :: a -> a -> Ordering }
deriving instance Semigroup (Comparison a)
deriving instance Monoid (Comparison a)
-- | A 'Comparison' is a 'Contravariant' 'Functor', because 'contramap' can
-- apply its function argument to each input of the comparison function.
instance Contravariant Comparison where
contramap f g = Comparison $ on (getComparison g) f
-- | Compare using 'compare'.
defaultComparison :: Ord a => Comparison a
defaultComparison = Comparison compare
-- | This data type represents an equivalence relation.
--
-- Equivalence relations are expected to satisfy three laws:
--
-- [Reflexivity]: @'getEquivalence' f a a = True@
-- [Symmetry]: @'getEquivalence' f a b = 'getEquivalence' f b a@
-- [Transitivity]:
-- If @'getEquivalence' f a b@ and @'getEquivalence' f b c@ are both 'True'
-- then so is @'getEquivalence' f a c@.
--
-- The types alone do not enforce these laws, so you'll have to check them
-- yourself.
newtype Equivalence a = Equivalence { getEquivalence :: a -> a -> Bool }
-- | Equivalence relations are 'Contravariant', because you can
-- apply the contramapped function to each input to the equivalence
-- relation.
instance Contravariant Equivalence where
contramap f g = Equivalence $ on (getEquivalence g) f
instance Semigroup (Equivalence a) where
Equivalence p <> Equivalence q = Equivalence $ \a b -> p a b && q a b
instance Monoid (Equivalence a) where
mempty = Equivalence (\_ _ -> True)
-- | Check for equivalence with '=='.
--
-- Note: The instances for 'Double' and 'Float' violate reflexivity for @NaN@.
defaultEquivalence :: Eq a => Equivalence a
defaultEquivalence = Equivalence (==)
comparisonEquivalence :: Comparison a -> Equivalence a
comparisonEquivalence (Comparison p) = Equivalence $ \a b -> p a b == EQ
-- | Dual function arrows.
newtype Op a b = Op { getOp :: b -> a }
deriving instance Semigroup a => Semigroup (Op a b)
deriving instance Monoid a => Monoid (Op a b)
instance Category Op where
id = Op id
Op f . Op g = Op (g . f)
instance Contravariant (Op a) where
contramap f g = Op (getOp g . f)
instance Num a => Num (Op a b) where
Op f + Op g = Op $ \a -> f a + g a
Op f * Op g = Op $ \a -> f a * g a
Op f - Op g = Op $ \a -> f a - g a
abs (Op f) = Op $ abs . f
signum (Op f) = Op $ signum . f
fromInteger = Op . const . fromInteger
instance Fractional a => Fractional (Op a b) where
Op f / Op g = Op $ \a -> f a / g a
recip (Op f) = Op $ recip . f
fromRational = Op . const . fromRational
instance Floating a => Floating (Op a b) where
pi = Op $ const pi
exp (Op f) = Op $ exp . f
sqrt (Op f) = Op $ sqrt . f
log (Op f) = Op $ log . f
sin (Op f) = Op $ sin . f
tan (Op f) = Op $ tan . f
cos (Op f) = Op $ cos . f
asin (Op f) = Op $ asin . f
atan (Op f) = Op $ atan . f
acos (Op f) = Op $ acos . f
sinh (Op f) = Op $ sinh . f
tanh (Op f) = Op $ tanh . f
cosh (Op f) = Op $ cosh . f
asinh (Op f) = Op $ asinh . f
atanh (Op f) = Op $ atanh . f
acosh (Op f) = Op $ acosh . f
Op f ** Op g = Op $ \a -> f a ** g a
logBase (Op f) (Op g) = Op $ \a -> logBase (f a) (g a)
| sdiehl/ghc | libraries/base/Data/Functor/Contravariant.hs | bsd-3-clause | 9,248 | 0 | 10 | 1,976 | 2,451 | 1,306 | 1,145 | -1 | -1 |
module Distribution.Simple.Test.Log
( PackageLog(..)
, TestLogs(..)
, TestSuiteLog(..)
, countTestResults
, localPackageLog
, summarizePackage
, summarizeSuiteFinish, summarizeSuiteStart
, summarizeTest
, suiteError, suiteFailed, suitePassed
, testSuiteLogPath
) where
import Distribution.Package ( PackageId )
import qualified Distribution.PackageDescription as PD
import Distribution.Simple.Compiler ( Compiler(..), compilerInfo, CompilerId )
import Distribution.Simple.InstallDirs
( fromPathTemplate, initialPathTemplateEnv, PathTemplateVariable(..)
, substPathTemplate , toPathTemplate, PathTemplate )
import qualified Distribution.Simple.LocalBuildInfo as LBI
import Distribution.Simple.Setup ( TestShowDetails(..) )
import Distribution.Simple.Utils ( notice )
import Distribution.System ( Platform )
import Distribution.TestSuite ( Options, Result(..) )
import Distribution.Verbosity ( Verbosity )
import Control.Monad ( when )
import Data.Char ( toUpper )
-- | Logs all test results for a package, broken down first by test suite and
-- then by test case.
data PackageLog = PackageLog
{ package :: PackageId
, compiler :: CompilerId
, platform :: Platform
, testSuites :: [TestSuiteLog]
}
deriving (Read, Show, Eq)
-- | A 'PackageLog' with package and platform information specified.
localPackageLog :: PD.PackageDescription -> LBI.LocalBuildInfo -> PackageLog
localPackageLog pkg_descr lbi = PackageLog
{ package = PD.package pkg_descr
, compiler = compilerId $ LBI.compiler lbi
, platform = LBI.hostPlatform lbi
, testSuites = []
}
-- | Logs test suite results, itemized by test case.
data TestSuiteLog = TestSuiteLog
{ testSuiteName :: String
, testLogs :: TestLogs
, logFile :: FilePath -- path to human-readable log file
}
deriving (Read, Show, Eq)
data TestLogs
= TestLog
{ testName :: String
, testOptionsReturned :: Options
, testResult :: Result
}
| GroupLogs String [TestLogs]
deriving (Read, Show, Eq)
-- | Count the number of pass, fail, and error test results in a 'TestLogs'
-- tree.
countTestResults :: TestLogs
-> (Int, Int, Int) -- ^ Passes, fails, and errors,
-- respectively.
countTestResults = go (0, 0, 0)
where
go (p, f, e) (TestLog { testResult = r }) =
case r of
Pass -> (p + 1, f, e)
Fail _ -> (p, f + 1, e)
Error _ -> (p, f, e + 1)
go (p, f, e) (GroupLogs _ ts) = foldl go (p, f, e) ts
-- | From a 'TestSuiteLog', determine if the test suite passed.
suitePassed :: TestLogs -> Bool
suitePassed l =
case countTestResults l of
(_, 0, 0) -> True
_ -> False
-- | From a 'TestSuiteLog', determine if the test suite failed.
suiteFailed :: TestLogs -> Bool
suiteFailed l =
case countTestResults l of
(_, 0, _) -> False
_ -> True
-- | From a 'TestSuiteLog', determine if the test suite encountered errors.
suiteError :: TestLogs -> Bool
suiteError l =
case countTestResults l of
(_, _, 0) -> False
_ -> True
resultString :: TestLogs -> String
resultString l | suiteError l = "error"
| suiteFailed l = "fail"
| otherwise = "pass"
testSuiteLogPath :: PathTemplate
-> PD.PackageDescription
-> LBI.LocalBuildInfo
-> String -- ^ test suite name
-> TestLogs -- ^ test suite results
-> FilePath
testSuiteLogPath template pkg_descr lbi name result =
fromPathTemplate $ substPathTemplate env template
where
env = initialPathTemplateEnv
(PD.package pkg_descr) (LBI.localComponentId lbi)
(compilerInfo $ LBI.compiler lbi) (LBI.hostPlatform lbi)
++ [ (TestSuiteNameVar, toPathTemplate name)
, (TestSuiteResultVar, toPathTemplate $ resultString result)
]
-- | Print a summary to the console after all test suites have been run
-- indicating the number of successful test suites and cases. Returns 'True' if
-- all test suites passed and 'False' otherwise.
summarizePackage :: Verbosity -> PackageLog -> IO Bool
summarizePackage verbosity packageLog = do
let counts = map (countTestResults . testLogs) $ testSuites packageLog
(passed, failed, errors) = foldl1 addTriple counts
totalCases = passed + failed + errors
passedSuites = length
$ filter (suitePassed . testLogs)
$ testSuites packageLog
totalSuites = length $ testSuites packageLog
notice verbosity $ show passedSuites ++ " of " ++ show totalSuites
++ " test suites (" ++ show passed ++ " of "
++ show totalCases ++ " test cases) passed."
return $! passedSuites == totalSuites
where
addTriple (p1, f1, e1) (p2, f2, e2) = (p1 + p2, f1 + f2, e1 + e2)
-- | Print a summary of a single test case's result to the console, supressing
-- output for certain verbosity or test filter levels.
summarizeTest :: Verbosity -> TestShowDetails -> TestLogs -> IO ()
summarizeTest _ _ (GroupLogs {}) = return ()
summarizeTest verbosity details t =
when shouldPrint $ notice verbosity $ "Test case " ++ testName t
++ ": " ++ show (testResult t)
where shouldPrint = (details > Never) && (notPassed || details == Always)
notPassed = testResult t /= Pass
-- | Print a summary of the test suite's results on the console, suppressing
-- output for certain verbosity or test filter levels.
summarizeSuiteFinish :: TestSuiteLog -> String
summarizeSuiteFinish testLog = unlines
[ "Test suite " ++ testSuiteName testLog ++ ": " ++ resStr
, "Test suite logged to: " ++ logFile testLog
]
where resStr = map toUpper (resultString $ testLogs testLog)
summarizeSuiteStart :: String -> String
summarizeSuiteStart n = "Test suite " ++ n ++ ": RUNNING...\n"
| trskop/cabal | Cabal/Distribution/Simple/Test/Log.hs | bsd-3-clause | 6,072 | 0 | 15 | 1,603 | 1,427 | 795 | 632 | 118 | 4 |
module Options.Applicative.Builder.Completer
( Completer
, mkCompleter
, listIOCompleter
, listCompleter
, bashCompleter
) where
import Control.Applicative ((<$>), pure)
import Control.Exception (IOException, try)
import Data.List (isPrefixOf)
import System.Process (readProcess)
import Options.Applicative.Types
listIOCompleter :: IO [String] -> Completer
listIOCompleter ss = Completer $ \s ->
filter (isPrefixOf s) <$> ss
listCompleter :: [String] -> Completer
listCompleter = listIOCompleter . pure
bashCompleter :: String -> Completer
bashCompleter action = Completer $ \word -> do
let cmd = unwords ["compgen", "-A", action, "--", word]
result <- tryIO $ readProcess "bash" ["-c", cmd] ""
return . lines . either (const []) id $ result
tryIO :: IO a -> IO (Either IOException a)
tryIO = try
| begriffs/optparse-applicative | Options/Applicative/Builder/Completer.hs | bsd-3-clause | 823 | 0 | 14 | 137 | 278 | 154 | 124 | 23 | 1 |
-- Record construction should fail statically
-- if there are any strict fields,
-- including in the non-record case.
module ShouldFail where
data S = S { x::Int, y:: ! Int }
data T = T Int !Int
data U = U Int Int
s1 = S {} -- Bad
s2 = S { x=3 } -- Bad
s3 = S { y=3 } -- Ok
t = T {} -- Bad
u = U {} -- Ok
| sgillespie/ghc | testsuite/tests/typecheck/should_fail/tcfail112.hs | bsd-3-clause | 331 | 2 | 8 | 104 | 114 | 71 | 43 | 13 | 1 |
{-# OPTIONS_GHC -fwarn-unused-imports #-}
module RedundantImport where
-- this import is redundant, but GHC does not spot it
import qualified Foreign.Storable
import Foreign.Storable (Storable, sizeOf, alignment, peek, poke, )
import Foreign.Ptr (castPtr, )
newtype T a = Cons a
instance Storable a => Storable (T a) where
sizeOf (Cons a) = sizeOf a
alignment (Cons a) = alignment a
peek = fmap Cons . peek . castPtr
poke p (Cons a) = poke (castPtr p) a
| urbanslug/ghc | testsuite/tests/rename/should_fail/T5211.hs | bsd-3-clause | 488 | 0 | 8 | 110 | 153 | 84 | 69 | 11 | 0 |
module HyperStrUse where
f :: (Int, Int) -> Bool -> Int
f (x,y) True = error (show x)
f (x,y) False = x +1
| urbanslug/ghc | testsuite/tests/stranal/sigs/HyperStrUse.hs | bsd-3-clause | 108 | 0 | 7 | 25 | 68 | 38 | 30 | 4 | 1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.ProtocolInfoProtos.ProtocolInfoService
(ProtocolInfoService, protocolInfoService, GetProtocolVersions, GetProtocolSignature, getProtocolVersions,
getProtocolSignature)
where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
import qualified Hadoop.Protos.ProtocolInfoProtos.GetProtocolVersionsRequestProto as ProtocolInfoProtos
(GetProtocolVersionsRequestProto)
import qualified Hadoop.Protos.ProtocolInfoProtos.GetProtocolSignatureRequestProto as ProtocolInfoProtos
(GetProtocolSignatureRequestProto)
import qualified Hadoop.Protos.ProtocolInfoProtos.GetProtocolVersionsResponseProto as ProtocolInfoProtos
(GetProtocolVersionsResponseProto)
import qualified Hadoop.Protos.ProtocolInfoProtos.GetProtocolSignatureResponseProto as ProtocolInfoProtos
(GetProtocolSignatureResponseProto)
type ProtocolInfoService = P'.Service '[GetProtocolVersions, GetProtocolSignature]
protocolInfoService :: ProtocolInfoService
protocolInfoService = P'.Service
type GetProtocolVersions =
P'.Method ".hadoop.common.ProtocolInfoService.getProtocolVersions" ProtocolInfoProtos.GetProtocolVersionsRequestProto
ProtocolInfoProtos.GetProtocolVersionsResponseProto
type GetProtocolSignature =
P'.Method ".hadoop.common.ProtocolInfoService.getProtocolSignature" ProtocolInfoProtos.GetProtocolSignatureRequestProto
ProtocolInfoProtos.GetProtocolSignatureResponseProto
getProtocolVersions :: GetProtocolVersions
getProtocolVersions = P'.Method
getProtocolSignature :: GetProtocolSignature
getProtocolSignature = P'.Method | alexbiehl/hoop | hadoop-protos/src/Hadoop/Protos/ProtocolInfoProtos/ProtocolInfoService.hs | mit | 1,897 | 0 | 7 | 191 | 234 | 156 | 78 | 31 | 1 |
module P021Spec where
import qualified P021 as P
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "solveBasic" $
it "N未満の友愛数の和" $
map P.solveBasic [0,1,2,500,1000,1500] `shouldBe` [0,0,0,504,504,2898]
| yyotti/euler_haskell | test/P021Spec.hs | mit | 262 | 0 | 8 | 49 | 106 | 63 | 43 | 10 | 1 |
module LinkedList
( LinkedList
, datum
, fromList
, isNil
, new
, next
, nil
, reverseLinkedList
, toList
) where
import Data.List (unfoldr)
data LinkedList a = Nil | Item a (LinkedList a) deriving (Eq, Show)
datum :: LinkedList a -> a
datum (Item x _) = x
datum Nil = error "nil has no entry"
fromList :: [a] -> LinkedList a
fromList = foldr new nil
isNil :: LinkedList a -> Bool
isNil Nil = True
isNil _ = False
new :: a -> LinkedList a -> LinkedList a
new = Item
next :: LinkedList a -> LinkedList a
next Nil = Nil
next (Item _ linkedList) = linkedList
nil :: LinkedList a
nil = Nil
reverseLinkedList :: LinkedList a -> LinkedList a
reverseLinkedList = fromList . reverse . toList
toList :: LinkedList a -> [a]
toList = unfoldr getElem
where
getElem Nil = Nothing
getElem (Item a linkedList) = Just (a, linkedList) | enolive/exercism | haskell/simple-linked-list/src/LinkedList.hs | mit | 857 | 0 | 9 | 195 | 329 | 174 | 155 | 33 | 2 |
{-# LANGUAGE BangPatterns #-}
module Data.Smashy.Encoding where
import Data.Smashy.Types
import Data.ByteString (ByteString)
import Control.Monad.ST.Strict (runST, ST)
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VM
import qualified Data.Vector.Storable.ByteString as VB
import Data.Word (Word8)
escapeBs :: ByteString -> Escaped
escapeBs = escape . VB.byteStringToVector
unescapeBs :: Escaped -> ByteString
unescapeBs = VB.vectorToByteString . unescape
escape :: VS.Vector Word8 -> Escaped
escape vec =
let size = VS.length vec
newSize = size + countEscapable size
in
if size == newSize
then Escaped vec
else Escaped (runST $ VM.unsafeNew newSize >>= \mvec -> esc mvec 0 0 size)
where
esc :: VM.MVector s Word8 -> Int -> Int -> Int -> ST s (VS.Vector Word8)
esc mvec i j size
| i == size = VS.unsafeFreeze mvec
| otherwise =
let x = VS.unsafeIndex vec i
in
if x == 10 || x == 92
then do
VM.unsafeWrite mvec j 92
VM.unsafeWrite mvec (j + 1) x
esc mvec (i + 1) (j + 2) size
else do
VM.unsafeWrite mvec j x
esc mvec (i + 1) (j + 1) size
countEscapable :: Int -> Int
countEscapable size = go 0 0
where
go !acc i
| i == size = acc
| otherwise =
let x = VS.unsafeIndex vec i
in
if x == 10 || x == 92
then go (acc+1) (i+1)
else go acc (i+1)
unescape :: Escaped -> VS.Vector Word8
unescape (Escaped vec) =
let size = VS.length vec
origSize = size - countEscaped size
in
if size == origSize
then vec
else runST $ VM.unsafeNew origSize >>= \mvec -> unesc mvec 0 0 size
where
unesc :: VM.MVector s Word8 -> Int -> Int -> Int -> ST s (VS.Vector Word8)
unesc mvec i j size
| i == size = VS.unsafeFreeze mvec
| otherwise =
let x = VS.unsafeIndex vec i
in
if x == 92
then do
VM.unsafeWrite mvec j (VS.unsafeIndex vec (i+1))
unesc mvec (i+2) (j+1) size
else do
VM.unsafeWrite mvec j x
unesc mvec (i+1) (j+1) size
countEscaped :: Int -> Int
countEscaped size = go 0 0
where
go !acc i
| i == size = acc
| VS.unsafeIndex vec i == 92 = go (acc+1) (i+2)
| otherwise = go acc (i+1) | jahaynes/smashy2 | src/Data/Smashy/Encoding.hs | mit | 2,701 | 0 | 17 | 1,063 | 957 | 482 | 475 | 67 | 4 |
module Machine where
import EnigmaChars
import Wheel
import Wheels
import Control.Monad
import Control.Monad.State
-- | An enigma machine is composed of wheels and their positions
data Machine = Machine [Wheel] WheelPositions deriving (Show, Eq)
-- |
encode :: EnigmaChar -> State Machine EnigmaChar
encode c = do
(Machine w p) <- get
put (Machine w (incWheelPositions p))
return $ multiWheel c w p
-- |
decode :: EnigmaChar -> State Machine EnigmaChar
decode c = do
(Machine w p) <- get
put (Machine w (incWheelPositions p))
return $ multiWheelRev c w p
-- |
encodeMessage :: [EnigmaChar] -> State Machine [EnigmaChar]
encodeMessage xs = mapM encode xs
-- |
decodeMessage :: [EnigmaChar] -> State Machine [EnigmaChar]
decodeMessage xs = mapM decode xs
| Raphexion/SimplifiedEnigmaMachine | Machine.hs | mit | 776 | 0 | 11 | 145 | 262 | 135 | 127 | 21 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Web.GetHandler where
import qualified Data.Text as T
import Web.Spock.Safe hiding (head, SessionId)
import Data.List
import Data.Maybe
import System.Directory (getDirectoryContents)
import Control.Monad.IO.Class (liftIO)
import Web.View
import Web.Utils
import Web.PostParser
import Web.FileHandler
import Model.Types
import Model.Model
handleGets :: [Route] -> String -> String -> BlogApp
handleGets staticRoutes rootDir filesDir = do
handleUploads filesDir
sequence_ $ map handleStaticSite staticRoutes
handleDrivel
handleDrivelEntry
handleLogin
handleLogout
handleEdit
handleUpload
handleWhyiliketrees rootDir
handleWhyiliketreesBare rootDir
handleLD29
handleUnknown
-- TODO: Content Type!!
-- TODO: send 404 error and also in Utils ~ send access HTML error
-- TODO: SUPER UGLY
handleUploads :: String -> BlogApp
handleUploads filesDir = subcomponent "uploads" $ do
get (var <//> var) $ \perm fileName -> handl perm fileName
get (var <//> var <//> var) $ \perm fn1 fn2 -> handl perm
(fn1 ++ "/" ++ fn2)
get (var <//> var <//> var <//> var) $ \perm fn1 fn2 fn3 -> handl perm
(fn1 ++ "/" ++
fn2 ++ "/" ++
fn3)
where handl perm fileName = do
muser <- loadUserSession
reqRightFile muser perm $ do
let filePath = concat ["/upload/access/",
show perm, "/", fileName]
mfilep <- liftIO $ checkFile filesDir filePath
case mfilep of
Just path -> do file "" path
Nothing -> do text "requested file not found"
handleStaticSite :: Route -> BlogApp
handleStaticSite (Redirect from to) = get (static $ T.unpack from) $
redirect to
handleStaticSite (DB from pid) = get (static $ T.unpack from) $ do
muser <- loadUserSession
mpost <- runSQL $ queryPost pid
case mpost of
Nothing -> blaze $ do
siteHead ""
infBackHeader "invalid pid" (relPath from)
siteBody siteInvPid
Just post -> blaze $ do
siteHead $ relPath from
siteHeader $ relPath from
genericBody (procURL from) $ parsePost (snd post) 0
siteFooter (fmap snd muser) (Just $ snd post)
where procURL "/" = "index"
procURL "whyiliketrees" = "wilt"
procURL u = T.unpack u
handleDrivel :: BlogApp
handleDrivel = get "drivel" $ do
muser <- loadUserSession
blaze $ do
siteHead "./"
siteHeader "./../"
drivelBody (fmap snd muser)
siteFooter (fmap snd muser) Nothing
handleDrivelEntry :: BlogApp
handleDrivelEntry = get ("drivel" <//> "post" <//> var) $ \pid -> do
muser <- loadUserSession
mpost <- runSQL $ queryPost (pid :: Int)
let access = if isNothing muser
then 0
else userAccess $ snd $ fromJust muser
case mpost of
Nothing -> error404 (fmap snd muser)
Just post -> do
-- prevent serving statically handled sites (should never happen but ok)
if postPtype (snd post) < 1
then error404 (fmap snd muser)
else
if access < postAccess (snd post)
then accessError (fmap snd muser)
else blaze $ do
siteHead "./../../"
siteHeader "./../../"
siteBody $ parsePost (snd post) (postPtype $ snd post)
katex "./../../"
siteFooter (fmap snd muser) (Just $ snd post)
error404 user = blaze $ do siteHead $ "./../../"
infBackHeader "invalid url" "./../../"
siteBody $ site404
siteFooter user Nothing
accessError user = blaze $ do siteHead $ "./../../"
infBackHeader "access denied" "./../../"
siteBody $ siteAccessError
siteFooter user Nothing
handleEdit :: BlogApp
handleEdit = get "edit" $ do
muser <- loadUserSession
posts <- runSQL $ queryAllPosts
reqRightPage muser 5 $ blaze $ do
inputHead
minimalHeader "edit" "./"
siteEdit posts
siteFooter (fmap snd muser) Nothing
handleUpload :: BlogApp
handleUpload = get "upload" $ do
muser <- loadUserSession
reqRightPage muser 5 $ blaze $ do
inputHead
infBackHeader "upload" "./"
siteUpload
siteFooter (fmap snd muser) Nothing
handleLogin :: BlogApp
handleLogin = get "login" $ blaze $ do
inputHead
infBackHeader "login" "./"
siteLogin
handleLogout :: BlogApp
handleLogout = get "logout" $ do
muser <- loadUserSession
case muser of
Nothing -> redirect "/whyiliketrees/"
Just (userId, user) -> do
runSQL $ logoutUser userId
writeSession Nothing
liftIO $ logAuth True 0 (Just user) "logout"
redirect "/"
handleWhyiliketrees :: String -> BlogApp
handleWhyiliketrees rootDir = get "games/whyiliketrees" $ do
gameFiles <- liftIO $ getDirectoryContents
(rootDir ++ "/static/games/whyiliketrees/")
muser <- loadUserSession
blaze $ do
siteHead "../"
darkHeader "../"
whyiliketreesBody (filter onlyJs gameFiles)
siteFooter (fmap snd muser) Nothing
handleWhyiliketreesBare :: String -> BlogApp
handleWhyiliketreesBare rootDir = get "games/whyiliketrees_bare" $ do
gameFiles <- liftIO $ getDirectoryContents
(rootDir ++ "/static/games/whyiliketrees/")
muser <- loadUserSession
blaze $ do
siteHead "../"
whyiliketreesBody (filter onlyJs gameFiles)
handleLD29 :: BlogApp
handleLD29 = do
get "games/LD29" $ do
blaze $ do
siteHead "../"
--darkHeader "../"
ld29Body
--siteFooter (fmap snd muser) Nothing
get "games/letterMap.png" $ redirect "/static/games/LD29/letterMap.png"
handleUnknown :: BlogApp
handleUnknown = hookAny GET $ \path -> do
muser <- loadUserSession
let from = foldl T.append "" (intersperse "/" path)
blaze $ do
siteHead $ relPath from
infBackHeader "invalid url" (relPath from)
siteBody $ site404
siteFooter (fmap snd muser) Nothing
relPath :: T.Text -> String
relPath from = "./" ++ foldl (++) "" (replicate d "../")
where d = length $ [f | f <- T.unpack from, f == '/']
onlyJs :: String -> Bool
onlyJs xs = "sj." == take 3 (reverse xs)
| elfeck/elfeckcom | src/Web/GetHandler.hs | mit | 6,439 | 0 | 23 | 1,853 | 1,874 | 882 | 992 | 173 | 5 |
{-|
Module : Database.Orville.PostgreSQL.Internal.MigrateSequence
Copyright : Flipstone Technology Partners 2016-2019
License : MIT
-}
module Database.Orville.PostgreSQL.Internal.MigrateSequence
( createSequencePlan
, dropSequencePlan
) where
import Control.Monad (guard)
import Data.List (intercalate)
import Database.Orville.PostgreSQL.Internal.MigrationPlan
import Database.Orville.PostgreSQL.Internal.SchemaState
import Database.Orville.PostgreSQL.Internal.Types
createSequencePlan :: SequenceDefinition -> SchemaState -> Maybe MigrationPlan
createSequencePlan seqDef schemaState = do
guard (not $ schemaStateSequenceExists (sequenceName seqDef) schemaState)
pure $
migrationDDLForItem
(Sequence seqDef)
(intercalate
" "
[ "CREATE SEQUENCE"
, "\"" ++ sequenceName seqDef ++ "\""
, maybe "" ("INCREMENT BY " ++) $ show <$> sequenceIncrement seqDef
, maybe "" ("MINVALUE " ++) $ show <$> sequenceMinValue seqDef
, maybe "" ("MAXVALUE " ++) $ show <$> sequenceMaxValue seqDef
, maybe "" ("START WITH " ++) $ show <$> sequenceStart seqDef
, maybe "" ("CACHE " ++) $ show <$> sequenceCache seqDef
, cycleClause $ sequenceCycle seqDef
])
where
cycleClause True = "CYCLE"
cycleClause _ = "NO CYCLE"
dropSequencePlan :: String -> SchemaState -> Maybe MigrationPlan
dropSequencePlan name schemaState = do
guard (schemaStateSequenceExists name schemaState)
pure $ migrationDDLForItem (DropSequence name) ("DROP SEQUENCE " ++ "\"" ++ name ++ "\"" )
| flipstone/orville | orville-postgresql/src/Database/Orville/PostgreSQL/Internal/MigrateSequence.hs | mit | 1,581 | 0 | 15 | 316 | 371 | 197 | 174 | 30 | 2 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import System.Environment (getArgs)
import Data.Maybe
main :: IO ()
main = do
[file] <- getArgs
ip <- readFile file
writeFile ((takeWhile (/= '.') file) ++ ".out" ) (processInput ip)
processInput' :: String -> [String]
processInput' = map unwords . map reverse . map words . tail . lines
processInput :: String -> String
processInput = unlines . map (\(n, ln) -> "Case #" ++ (show n) ++ ": " ++ ln) . zip [1..] . processInput'
| cbrghostrider/Hacking | codeJam/africa2010/reverseWords/reverseWords.hs | mit | 852 | 0 | 15 | 149 | 203 | 106 | 97 | 11 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-orphans #-}
{-# LANGUAGE QuasiQuotes, TemplateHaskell, CPP, GADTs, TypeFamilies, OverloadedStrings, FlexibleContexts, EmptyDataDecls, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
module RenameTest where
#ifndef WITH_NOSQL
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Control.Monad.Trans.Resource (runResourceT)
#endif
import Data.Time (getCurrentTime, Day, UTCTime(..))
import qualified Data.Map as Map
import qualified Data.Text as T
import Data.Aeson
import Init
#if MIN_VERSION_aeson(0,10,0)
import Data.Aeson.Types
#else
instance ToJSON Day where toJSON = error "Day.toJSON"
instance FromJSON Day where parseJSON = error "Day.parseJSON"
#endif
-- persistent used to not allow types with an "Id" suffix
-- this verifies that the issue is fixed
type TextId = Text
-- Test lower case names
#if WITH_NOSQL
mkPersist persistSettings [persistUpperCase|
#else
share [mkPersist sqlSettings, mkMigrate "migration"] [persistLowerCase|
#endif
-- This just tests that a field can be named "key"
KeyTable
key Text
deriving Eq Show
IdTable
Id Day default=CURRENT_DATE
name Text
-- This was added to test the ability to break a cycle
-- getting rid of the Maybe should be a compilation failure
keyTableEmbed IdTable Maybe
deriving Eq Show
LowerCaseTable
Id sql=my_id
fullName Text
ExtraBlock
foo bar
baz
bin
ExtraBlock2
something
RefTable
someVal Int sql=something_else
lct LowerCaseTableId
text TextId
UniqueRefTable someVal
|]
#if WITH_NOSQL
cleanDB :: ReaderT Context IO ()
cleanDB = do
deleteWhere ([] :: [Filter IdTable])
deleteWhere ([] :: [Filter LowerCaseTable])
deleteWhere ([] :: [Filter RefTable])
db :: Action IO () -> Assertion
db = db' cleanDB
#endif
specs :: Spec
specs = describe "rename specs" $ do
#ifndef WITH_NOSQL
it "handles lower casing" $ asIO $
runConn $ do
runResourceT $ rawQuery "SELECT full_name from lower_case_table WHERE my_id=5" [] C.$$ CL.sinkNull
runResourceT $ rawQuery "SELECT something_else from ref_table WHERE id=4" [] C.$$ CL.sinkNull
#endif
it "user specified id, insertKey, no default=" $ db $ do
let rec2 = IdTable "Foo2" Nothing
let rec1 = IdTable "Foo1" $ Just rec2
let rec = IdTable "Foo" $ Just rec1
now <- liftIO getCurrentTime
let key = IdTableKey $ utctDay now
insertKey key rec
Just rec' <- get key
rec' @== rec
(Entity key' _):_ <- selectList ([] :: [Filter IdTable]) []
key' @== key
#ifndef WITH_MYSQL
# ifndef WITH_NOSQL
-- this uses default=
it "user specified id, default=" $ db $ do
let rec = IdTable "Foo" Nothing
k <- insert rec
Just rec' <- get k
rec' @== rec
# endif
#endif
it "extra blocks" $
entityExtra (entityDef (Nothing :: Maybe LowerCaseTable)) @?=
Map.fromList
[ ("ExtraBlock", map T.words ["foo bar", "baz", "bin"])
, ("ExtraBlock2", map T.words ["something"])
]
asIO :: IO a -> IO a
asIO = id
| greydot/persistent | persistent-test/RenameTest.hs | mit | 3,205 | 0 | 15 | 759 | 629 | 328 | 301 | 44 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Data.S3Config
( S3Config
, parse
, regionOf
) where
-- For now, only very little information needs to be extracted from the S3
-- config file, but extracting it into a separate module is consistent with
-- `Data.Romefile` and `Data.Carthage` and avoids dealing with the raw INI
-- file representation (String-keyed hashmaps) in the main logic.
import Control.Monad ((<=<))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Ini (Ini, lookupValue, parseIni)
import qualified Network.AWS as AWS
import qualified Network.AWS.Data as AWS
newtype S3Config = S3Config { _ini :: Ini }
regionOf :: Text -> S3Config -> Either String AWS.Region
regionOf profile = parseRegion <=< lookupValue profile "region" . _ini
where
parseRegion s = if T.null s
-- better error message
then Left "Failed reading: Failure parsing Region from empty string"
else AWS.fromText s
parse :: Text -> Either String S3Config
parse = fmap S3Config . parseIni
| mheinzel/Rome | src/Data/S3Config.hs | mit | 1,101 | 0 | 9 | 268 | 197 | 117 | 80 | -1 | -1 |
-- | Common handler functions.
module Handler.Common where
import Data.FileEmbed (embedFile)
import Import
-- These handlers embed files in the executable at compile time to avoid a
-- runtime dependency, and for efficiency.
getFaviconR :: Handler TypedContent
getFaviconR = do cacheSeconds $ 60 * 60 * 24 * 30 -- cache for a month
return $ TypedContent "image/x-icon"
$ toContent $(embedFile "config/favicon.ico")
getRobotsR :: Handler TypedContent
getRobotsR = return $ TypedContent typePlain
$ toContent $(embedFile "config/robots.txt")
getLoggedInR :: Handler Value
getLoggedInR = do
mAuth <- maybeAuth
return $ object ["auth" .=
case mAuth of
Just _ -> True
Nothing -> False
]
| quantum-dan/HasKnowledge | Handler/Common.hs | mit | 828 | 0 | 14 | 248 | 169 | 85 | 84 | 17 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.