code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE GADTs #-}
module KernelCategory where
import qualified Data.Set as DS
newtype Pairwise a = Pairwise { unPairwise :: DS.Set a }
deriving (Eq,Ord)
instance (Monoid m, Ord m) => Monoid (Pairwise m) where
mempty = Pairwise $ DS.singleton mempty
ms1 `mappend` ms2 = Pairwise $ DS.fromList [ m1 `mappend` m2 | m1 <- DS.toList (unPairwise ms1), m2 <- DS.toList (unPairwise ms2) ]
class (Ord m, Monoid m) => FinMonoid m where
allElems :: DS.Set m
-- data FinMonRelMorphism m n where
-- Morph :: (Monoid m, Monoid n) => { morph :: m -> DS.Set n } -> FinMonRelMorphism m n
isRelMorph :: (FinMonoid m, FinMonoid n) => (m -> DS.Set n) -> Bool
isRelMorph phi = mempty `DS.member` phi mempty
&&
let pairs = [ (m1,m2) | m1 <- DS.toList allElems, m2 <- DS.toList allElems ]
checkMul (m1,m2) = unPairwise (Pairwise (phi m1) `mappend` Pairwise (phi m2)) `DS.isSubsetOf` phi (m1 `mappend` m2)
in all checkMul pairs
isMorph :: (FinMonoid m, FinMonoid n) => (m -> n) -> Bool
isMorph = isRelMorph . morphToRelMorph
morphToRelMorph :: (FinMonoid m, FinMonoid n) => (m -> n) -> (m -> DS.Set n)
morphToRelMorph = (.) DS.singleton
class Category cat where
objects :: cat o a -> DS.Set o
arrows :: cat o a -> o -> o -> DS.Set a
id :: cat o a -> o -> DS.Set a
comp :: cat o a -> a -> a -> a
-- image :: (FinMonoid m, FinMonoid n) => FinMonRelMorphism m n -> DS.Set n
-- image (Morph phi) = DS.fold (\m ns -> phi m `DS.union` ns) DS.empty allElems
image :: (FinMonoid m, FinMonoid n) => (m -> DS.Set n) -> DS.Set n
image phi = DS.fold (\m ns -> phi m `DS.union` ns) DS.empty allElems
preimage :: (FinMonoid m, FinMonoid n) => (m -> DS.Set n) -> n -> DS.Set m
preimage phi n = DS.filter (\m -> n `DS.member` phi m) allElems
data DerivedCat m n where
DC :: { obj :: DS.Set n , arr :: n -> n -> DS.Set (DS.Set (m,n)), compose :: DS.Set (m,n) -> DS.Set (m,n) -> DS.Set (m,n) } -> DerivedCat m n
derive :: (FinMonoid m, FinMonoid n) => (m -> DS.Set n) -> DerivedCat m n
derive phi = DC { obj = image phi, arr = a, compose = c }
where
a n n' = let green_rs = DS.toList $ DS.filter (\n'' -> n `mappend` n'' == n) allElems
pairs = concatMap (\n -> [ (m,n) | m <- DS.toList (preimage phi n) ] ) green_rs
in undefined
c = undefined
| skingo/kernel_category | kernelCategory/src/KernelCategory.hs | bsd-3-clause | 2,399 | 0 | 19 | 626 | 1,013 | 539 | 474 | 37 | 1 |
module Utils.DependencyAnalysis(dependencyAnalysis, AnalysisTy(..)) where
import Control.Monad.Reader
import Data.Array ((!))
import Data.Graph
import qualified Data.IntMap as IMap
import Data.List (intersect, nub)
import qualified Data.Map as Map
import Data.Maybe (fromJust, catMaybes)
import Data.Tree (flatten)
import Utils.Id
import Utils.Env
import Utils.Nameable
import Utils.Debug
-- this module implements the dependency analysis algorithm
-- specified in SPJ book.
-- first the definition of a data type for the analysis type
data AnalysisTy = KindAnalysis | TypeAnalysis
deriving (Eq, Ord, Show)
dependencyAnalysis :: (Show a, Nameable a, Referenceable a) => AnalysisTy -> [a] -> [[a]]
dependencyAnalysis ty ds
= runReader (analysis ty ds) table
where
table = mkIdTable ds
-- the analysis algorithm is done within a reader monad
type AnalysisM a = Reader (Env Vertex) a
analysis :: (Nameable a, Referenceable a) => AnalysisTy -> [a] -> AnalysisM [[a]]
analysis ty ds = do
graph <- dependencyGraph ty ds
(cgraph,table) <- coalesce graph
finish (topSort cgraph) table ds
-- finishing the dependency analysis
finish :: Nameable a => [Vertex] -> IMap.IntMap [Vertex] -> [a] -> AnalysisM [[a]]
finish vs m ds
= do
env <- asks reverseEnv
let
table = foldr (\d ac -> insert (name d) d ac) empty ds
vss = map (\v -> fromJust $ IMap.lookup v m) vs
f = map (fromJust . flip Map.lookup env)
g = map (fromJust . flip Map.lookup table)
return (reverse (map (g . f) vss))
-- creating a map from id's to decls
mkIdTable :: Nameable a => [a] -> Env Vertex
mkIdTable = fst . foldr (step . name) (empty, 1)
where
step d (ac,n) = insert' d n ac
insert' n' v m = if member n' m then (m,v)
else (insert n' v m, v + 1)
-- creating the dependency graph
dependencyGraph :: (Nameable a, Referenceable a) => AnalysisTy -> [a] -> AnalysisM Graph
dependencyGraph ty ds
= do
let
-- here it was necessary to force strict evaluation
-- of the list of id's
ds' = map (\d -> let ts = referencedNames ty d ns in (name d, ts)) ds
ns = map name ds
n <- asks size
edges <- createEdges ds'
return (buildG (1,n) edges)
-- creating the dependency edges for the graph
createEdges :: [(Id,[Id])] -> AnalysisM [Edge]
createEdges is = foldM step [] is
where
f x = asks (lookupEnv x)
step ac (d,ds)
= do
-- here is safe to use fromJust
source <- liftM fromJust (f d)
targets <- liftM catMaybes (mapM f ds)
return (foldr (\d' ac' -> (source, d') : ac') ac targets)
-- coalescing the dependency graph
coalesce :: Graph -> AnalysisM (Graph, IMap.IntMap [Vertex])
coalesce g = do
let
n = length ns
ns = map flatten (scc g)
table = Map.fromList (zip ns [1..])
table' = IMap.fromList (zip [1..n] ns)
reach xs ys = any (\x -> not $ null ((g ! x) `intersect` ys)) xs
f (x, y) = (g' x, g' y)
g' x = fromJust (Map.lookup x table)
es = [(x,y) | x <- ns, y <- ns, reach x y, x /= y]
es' = map f es
return (buildG (1,n) es', table')
-- some auxiliar functions
reverseEnv = foldrWithId revins Map.empty
where
revins k v ac = Map.insert v k ac
referencedNames KindAnalysis d ns = kindRefNames d `intersect` ns
referencedNames TypeAnalysis d ns = typeRefNames d `intersect` ns | rodrigogribeiro/mptc | src/Utils/DependencyAnalysis.hs | bsd-3-clause | 3,971 | 0 | 18 | 1,400 | 1,321 | 698 | 623 | 74 | 2 |
{-# OPTIONS_GHC -Wall #-}
module AST.Pattern where
import AST.V0_16
import qualified Reporting.Annotation as A
type Pattern =
A.Located Pattern'
data Pattern'
= Anything
| UnitPattern Comments
| Literal Literal
| VarPattern LowercaseIdentifier
| OpPattern SymbolIdentifier
| Data [UppercaseIdentifier] [(Comments, Pattern)]
| PatternParens (Commented Pattern)
| Tuple [Commented Pattern]
| EmptyListPattern Comments
| List [Commented Pattern]
| ConsPattern
{ first :: (Pattern, Maybe String)
, rest :: [(Comments, Comments, Pattern, Maybe String)]
}
| Record [Commented LowercaseIdentifier]
| Alias (Pattern, Comments) (Comments, LowercaseIdentifier)
deriving (Eq, Show)
| rgrempel/frelm.org | vendor/elm-format/parser/src/AST/Pattern.hs | mit | 760 | 0 | 11 | 174 | 200 | 120 | 80 | 23 | 0 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Tests.Writers.Markdown (tests) where
import Test.Framework
import Text.Pandoc.Builder
import Text.Pandoc
import Tests.Helpers
import Tests.Arbitrary()
markdown :: (ToString a, ToPandoc a) => a -> String
markdown = writeMarkdown defaultWriterOptions . toPandoc
{-
"my test" =: X =?> Y
is shorthand for
test markdown "my test" $ X =?> Y
which is in turn shorthand for
test markdown "my test" (X,Y)
-}
infix 5 =:
(=:) :: (ToString a, ToPandoc a)
=> String -> (a, String) -> Test
(=:) = test markdown
tests :: [Test]
tests = [ "indented code after list"
=: (orderedList [ para "one" +++ para "two" ] +++ codeBlock "test")
=?> "1. one\n\n two\n\n<!-- -->\n\n test"
]
| Lythimus/lptv | sites/all/modules/jgm-pandoc-8be6cc2/src/Tests/Writers/Markdown.hs | gpl-2.0 | 778 | 0 | 13 | 175 | 180 | 103 | 77 | 17 | 1 |
-- Module : Network.AWS.EC2
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides
-- resizable compute capacity in the cloud. It is designed to make web-scale
-- computing easier for developers. Amazon EC2’s simple web service interface
-- allows you to obtain and configure capacity with minimal friction. It
-- provides you with complete control of your computing resources and lets you
-- run on Amazon’s proven computing environment. Amazon EC2 reduces the time
-- required to obtain and boot new server instances to minutes, allowing you to
-- quickly scale capacity, both up and down, as your computing requirements
-- change. Amazon EC2 changes the economics of computing by allowing you to pay
-- only for capacity that you actually use. Amazon EC2 provides developers the
-- tools to build failure resilient applications and isolate themselves from
-- common failure scenarios.
module Network.AWS.EC2
( module Network.AWS.EC2.AcceptVpcPeeringConnection
, module Network.AWS.EC2.AllocateAddress
, module Network.AWS.EC2.AssignPrivateIpAddresses
, module Network.AWS.EC2.AssociateAddress
, module Network.AWS.EC2.AssociateDhcpOptions
, module Network.AWS.EC2.AssociateRouteTable
, module Network.AWS.EC2.AttachClassicLinkVpc
, module Network.AWS.EC2.AttachInternetGateway
, module Network.AWS.EC2.AttachNetworkInterface
, module Network.AWS.EC2.AttachVolume
, module Network.AWS.EC2.AttachVpnGateway
, module Network.AWS.EC2.AuthorizeSecurityGroupEgress
, module Network.AWS.EC2.AuthorizeSecurityGroupIngress
, module Network.AWS.EC2.BundleInstance
, module Network.AWS.EC2.CancelBundleTask
, module Network.AWS.EC2.CancelConversionTask
, module Network.AWS.EC2.CancelExportTask
, module Network.AWS.EC2.CancelReservedInstancesListing
, module Network.AWS.EC2.CancelSpotInstanceRequests
, module Network.AWS.EC2.ConfirmProductInstance
, module Network.AWS.EC2.CopyImage
, module Network.AWS.EC2.CopySnapshot
, module Network.AWS.EC2.CreateCustomerGateway
, module Network.AWS.EC2.CreateDhcpOptions
, module Network.AWS.EC2.CreateImage
, module Network.AWS.EC2.CreateInstanceExportTask
, module Network.AWS.EC2.CreateInternetGateway
, module Network.AWS.EC2.CreateKeyPair
, module Network.AWS.EC2.CreateNetworkAcl
, module Network.AWS.EC2.CreateNetworkAclEntry
, module Network.AWS.EC2.CreateNetworkInterface
, module Network.AWS.EC2.CreatePlacementGroup
, module Network.AWS.EC2.CreateReservedInstancesListing
, module Network.AWS.EC2.CreateRoute
, module Network.AWS.EC2.CreateRouteTable
, module Network.AWS.EC2.CreateSecurityGroup
, module Network.AWS.EC2.CreateSnapshot
, module Network.AWS.EC2.CreateSpotDatafeedSubscription
, module Network.AWS.EC2.CreateSubnet
, module Network.AWS.EC2.CreateTags
, module Network.AWS.EC2.CreateVolume
, module Network.AWS.EC2.CreateVpc
, module Network.AWS.EC2.CreateVpcPeeringConnection
, module Network.AWS.EC2.CreateVpnConnection
, module Network.AWS.EC2.CreateVpnConnectionRoute
, module Network.AWS.EC2.CreateVpnGateway
, module Network.AWS.EC2.DeleteCustomerGateway
, module Network.AWS.EC2.DeleteDhcpOptions
, module Network.AWS.EC2.DeleteInternetGateway
, module Network.AWS.EC2.DeleteKeyPair
, module Network.AWS.EC2.DeleteNetworkAcl
, module Network.AWS.EC2.DeleteNetworkAclEntry
, module Network.AWS.EC2.DeleteNetworkInterface
, module Network.AWS.EC2.DeletePlacementGroup
, module Network.AWS.EC2.DeleteRoute
, module Network.AWS.EC2.DeleteRouteTable
, module Network.AWS.EC2.DeleteSecurityGroup
, module Network.AWS.EC2.DeleteSnapshot
, module Network.AWS.EC2.DeleteSpotDatafeedSubscription
, module Network.AWS.EC2.DeleteSubnet
, module Network.AWS.EC2.DeleteTags
, module Network.AWS.EC2.DeleteVolume
, module Network.AWS.EC2.DeleteVpc
, module Network.AWS.EC2.DeleteVpcPeeringConnection
, module Network.AWS.EC2.DeleteVpnConnection
, module Network.AWS.EC2.DeleteVpnConnectionRoute
, module Network.AWS.EC2.DeleteVpnGateway
, module Network.AWS.EC2.DeregisterImage
, module Network.AWS.EC2.DescribeAccountAttributes
, module Network.AWS.EC2.DescribeAddresses
, module Network.AWS.EC2.DescribeAvailabilityZones
, module Network.AWS.EC2.DescribeBundleTasks
, module Network.AWS.EC2.DescribeClassicLinkInstances
, module Network.AWS.EC2.DescribeConversionTasks
, module Network.AWS.EC2.DescribeCustomerGateways
, module Network.AWS.EC2.DescribeDhcpOptions
, module Network.AWS.EC2.DescribeExportTasks
, module Network.AWS.EC2.DescribeImageAttribute
, module Network.AWS.EC2.DescribeImages
, module Network.AWS.EC2.DescribeInstanceAttribute
, module Network.AWS.EC2.DescribeInstanceStatus
, module Network.AWS.EC2.DescribeInstances
, module Network.AWS.EC2.DescribeInternetGateways
, module Network.AWS.EC2.DescribeKeyPairs
, module Network.AWS.EC2.DescribeNetworkAcls
, module Network.AWS.EC2.DescribeNetworkInterfaceAttribute
, module Network.AWS.EC2.DescribeNetworkInterfaces
, module Network.AWS.EC2.DescribePlacementGroups
, module Network.AWS.EC2.DescribeRegions
, module Network.AWS.EC2.DescribeReservedInstances
, module Network.AWS.EC2.DescribeReservedInstancesListings
, module Network.AWS.EC2.DescribeReservedInstancesModifications
, module Network.AWS.EC2.DescribeReservedInstancesOfferings
, module Network.AWS.EC2.DescribeRouteTables
, module Network.AWS.EC2.DescribeSecurityGroups
, module Network.AWS.EC2.DescribeSnapshotAttribute
, module Network.AWS.EC2.DescribeSnapshots
, module Network.AWS.EC2.DescribeSpotDatafeedSubscription
, module Network.AWS.EC2.DescribeSpotInstanceRequests
, module Network.AWS.EC2.DescribeSpotPriceHistory
, module Network.AWS.EC2.DescribeSubnets
, module Network.AWS.EC2.DescribeTags
, module Network.AWS.EC2.DescribeVolumeAttribute
, module Network.AWS.EC2.DescribeVolumeStatus
, module Network.AWS.EC2.DescribeVolumes
, module Network.AWS.EC2.DescribeVpcAttribute
, module Network.AWS.EC2.DescribeVpcClassicLink
, module Network.AWS.EC2.DescribeVpcPeeringConnections
, module Network.AWS.EC2.DescribeVpcs
, module Network.AWS.EC2.DescribeVpnConnections
, module Network.AWS.EC2.DescribeVpnGateways
, module Network.AWS.EC2.DetachClassicLinkVpc
, module Network.AWS.EC2.DetachInternetGateway
, module Network.AWS.EC2.DetachNetworkInterface
, module Network.AWS.EC2.DetachVolume
, module Network.AWS.EC2.DetachVpnGateway
, module Network.AWS.EC2.DisableVgwRoutePropagation
, module Network.AWS.EC2.DisableVpcClassicLink
, module Network.AWS.EC2.DisassociateAddress
, module Network.AWS.EC2.DisassociateRouteTable
, module Network.AWS.EC2.EnableVgwRoutePropagation
, module Network.AWS.EC2.EnableVolumeIO
, module Network.AWS.EC2.EnableVpcClassicLink
, module Network.AWS.EC2.GetConsoleOutput
, module Network.AWS.EC2.GetPasswordData
, module Network.AWS.EC2.ImportInstance
, module Network.AWS.EC2.ImportKeyPair
, module Network.AWS.EC2.ImportVolume
, module Network.AWS.EC2.ModifyImageAttribute
, module Network.AWS.EC2.ModifyInstanceAttribute
, module Network.AWS.EC2.ModifyNetworkInterfaceAttribute
, module Network.AWS.EC2.ModifyReservedInstances
, module Network.AWS.EC2.ModifySnapshotAttribute
, module Network.AWS.EC2.ModifySubnetAttribute
, module Network.AWS.EC2.ModifyVolumeAttribute
, module Network.AWS.EC2.ModifyVpcAttribute
, module Network.AWS.EC2.MonitorInstances
, module Network.AWS.EC2.PurchaseReservedInstancesOffering
, module Network.AWS.EC2.RebootInstances
, module Network.AWS.EC2.RegisterImage
, module Network.AWS.EC2.RejectVpcPeeringConnection
, module Network.AWS.EC2.ReleaseAddress
, module Network.AWS.EC2.ReplaceNetworkAclAssociation
, module Network.AWS.EC2.ReplaceNetworkAclEntry
, module Network.AWS.EC2.ReplaceRoute
, module Network.AWS.EC2.ReplaceRouteTableAssociation
, module Network.AWS.EC2.ReportInstanceStatus
, module Network.AWS.EC2.RequestSpotInstances
, module Network.AWS.EC2.ResetImageAttribute
, module Network.AWS.EC2.ResetInstanceAttribute
, module Network.AWS.EC2.ResetNetworkInterfaceAttribute
, module Network.AWS.EC2.ResetSnapshotAttribute
, module Network.AWS.EC2.RevokeSecurityGroupEgress
, module Network.AWS.EC2.RevokeSecurityGroupIngress
, module Network.AWS.EC2.RunInstances
, module Network.AWS.EC2.StartInstances
, module Network.AWS.EC2.StopInstances
, module Network.AWS.EC2.TerminateInstances
, module Network.AWS.EC2.Types
, module Network.AWS.EC2.UnassignPrivateIpAddresses
, module Network.AWS.EC2.UnmonitorInstances
, module Network.AWS.EC2.Waiters
) where
import Network.AWS.EC2.AcceptVpcPeeringConnection
import Network.AWS.EC2.AllocateAddress
import Network.AWS.EC2.AssignPrivateIpAddresses
import Network.AWS.EC2.AssociateAddress
import Network.AWS.EC2.AssociateDhcpOptions
import Network.AWS.EC2.AssociateRouteTable
import Network.AWS.EC2.AttachClassicLinkVpc
import Network.AWS.EC2.AttachInternetGateway
import Network.AWS.EC2.AttachNetworkInterface
import Network.AWS.EC2.AttachVolume
import Network.AWS.EC2.AttachVpnGateway
import Network.AWS.EC2.AuthorizeSecurityGroupEgress
import Network.AWS.EC2.AuthorizeSecurityGroupIngress
import Network.AWS.EC2.BundleInstance
import Network.AWS.EC2.CancelBundleTask
import Network.AWS.EC2.CancelConversionTask
import Network.AWS.EC2.CancelExportTask
import Network.AWS.EC2.CancelReservedInstancesListing
import Network.AWS.EC2.CancelSpotInstanceRequests
import Network.AWS.EC2.ConfirmProductInstance
import Network.AWS.EC2.CopyImage
import Network.AWS.EC2.CopySnapshot
import Network.AWS.EC2.CreateCustomerGateway
import Network.AWS.EC2.CreateDhcpOptions
import Network.AWS.EC2.CreateImage
import Network.AWS.EC2.CreateInstanceExportTask
import Network.AWS.EC2.CreateInternetGateway
import Network.AWS.EC2.CreateKeyPair
import Network.AWS.EC2.CreateNetworkAcl
import Network.AWS.EC2.CreateNetworkAclEntry
import Network.AWS.EC2.CreateNetworkInterface
import Network.AWS.EC2.CreatePlacementGroup
import Network.AWS.EC2.CreateReservedInstancesListing
import Network.AWS.EC2.CreateRoute
import Network.AWS.EC2.CreateRouteTable
import Network.AWS.EC2.CreateSecurityGroup
import Network.AWS.EC2.CreateSnapshot
import Network.AWS.EC2.CreateSpotDatafeedSubscription
import Network.AWS.EC2.CreateSubnet
import Network.AWS.EC2.CreateTags
import Network.AWS.EC2.CreateVolume
import Network.AWS.EC2.CreateVpc
import Network.AWS.EC2.CreateVpcPeeringConnection
import Network.AWS.EC2.CreateVpnConnection
import Network.AWS.EC2.CreateVpnConnectionRoute
import Network.AWS.EC2.CreateVpnGateway
import Network.AWS.EC2.DeleteCustomerGateway
import Network.AWS.EC2.DeleteDhcpOptions
import Network.AWS.EC2.DeleteInternetGateway
import Network.AWS.EC2.DeleteKeyPair
import Network.AWS.EC2.DeleteNetworkAcl
import Network.AWS.EC2.DeleteNetworkAclEntry
import Network.AWS.EC2.DeleteNetworkInterface
import Network.AWS.EC2.DeletePlacementGroup
import Network.AWS.EC2.DeleteRoute
import Network.AWS.EC2.DeleteRouteTable
import Network.AWS.EC2.DeleteSecurityGroup
import Network.AWS.EC2.DeleteSnapshot
import Network.AWS.EC2.DeleteSpotDatafeedSubscription
import Network.AWS.EC2.DeleteSubnet
import Network.AWS.EC2.DeleteTags
import Network.AWS.EC2.DeleteVolume
import Network.AWS.EC2.DeleteVpc
import Network.AWS.EC2.DeleteVpcPeeringConnection
import Network.AWS.EC2.DeleteVpnConnection
import Network.AWS.EC2.DeleteVpnConnectionRoute
import Network.AWS.EC2.DeleteVpnGateway
import Network.AWS.EC2.DeregisterImage
import Network.AWS.EC2.DescribeAccountAttributes
import Network.AWS.EC2.DescribeAddresses
import Network.AWS.EC2.DescribeAvailabilityZones
import Network.AWS.EC2.DescribeBundleTasks
import Network.AWS.EC2.DescribeClassicLinkInstances
import Network.AWS.EC2.DescribeConversionTasks
import Network.AWS.EC2.DescribeCustomerGateways
import Network.AWS.EC2.DescribeDhcpOptions
import Network.AWS.EC2.DescribeExportTasks
import Network.AWS.EC2.DescribeImageAttribute
import Network.AWS.EC2.DescribeImages
import Network.AWS.EC2.DescribeInstanceAttribute
import Network.AWS.EC2.DescribeInstanceStatus
import Network.AWS.EC2.DescribeInstances
import Network.AWS.EC2.DescribeInternetGateways
import Network.AWS.EC2.DescribeKeyPairs
import Network.AWS.EC2.DescribeNetworkAcls
import Network.AWS.EC2.DescribeNetworkInterfaceAttribute
import Network.AWS.EC2.DescribeNetworkInterfaces
import Network.AWS.EC2.DescribePlacementGroups
import Network.AWS.EC2.DescribeRegions
import Network.AWS.EC2.DescribeReservedInstances
import Network.AWS.EC2.DescribeReservedInstancesListings
import Network.AWS.EC2.DescribeReservedInstancesModifications
import Network.AWS.EC2.DescribeReservedInstancesOfferings
import Network.AWS.EC2.DescribeRouteTables
import Network.AWS.EC2.DescribeSecurityGroups
import Network.AWS.EC2.DescribeSnapshotAttribute
import Network.AWS.EC2.DescribeSnapshots
import Network.AWS.EC2.DescribeSpotDatafeedSubscription
import Network.AWS.EC2.DescribeSpotInstanceRequests
import Network.AWS.EC2.DescribeSpotPriceHistory
import Network.AWS.EC2.DescribeSubnets
import Network.AWS.EC2.DescribeTags
import Network.AWS.EC2.DescribeVolumeAttribute
import Network.AWS.EC2.DescribeVolumeStatus
import Network.AWS.EC2.DescribeVolumes
import Network.AWS.EC2.DescribeVpcAttribute
import Network.AWS.EC2.DescribeVpcClassicLink
import Network.AWS.EC2.DescribeVpcPeeringConnections
import Network.AWS.EC2.DescribeVpcs
import Network.AWS.EC2.DescribeVpnConnections
import Network.AWS.EC2.DescribeVpnGateways
import Network.AWS.EC2.DetachClassicLinkVpc
import Network.AWS.EC2.DetachInternetGateway
import Network.AWS.EC2.DetachNetworkInterface
import Network.AWS.EC2.DetachVolume
import Network.AWS.EC2.DetachVpnGateway
import Network.AWS.EC2.DisableVgwRoutePropagation
import Network.AWS.EC2.DisableVpcClassicLink
import Network.AWS.EC2.DisassociateAddress
import Network.AWS.EC2.DisassociateRouteTable
import Network.AWS.EC2.EnableVgwRoutePropagation
import Network.AWS.EC2.EnableVolumeIO
import Network.AWS.EC2.EnableVpcClassicLink
import Network.AWS.EC2.GetConsoleOutput
import Network.AWS.EC2.GetPasswordData
import Network.AWS.EC2.ImportInstance
import Network.AWS.EC2.ImportKeyPair
import Network.AWS.EC2.ImportVolume
import Network.AWS.EC2.ModifyImageAttribute
import Network.AWS.EC2.ModifyInstanceAttribute
import Network.AWS.EC2.ModifyNetworkInterfaceAttribute
import Network.AWS.EC2.ModifyReservedInstances
import Network.AWS.EC2.ModifySnapshotAttribute
import Network.AWS.EC2.ModifySubnetAttribute
import Network.AWS.EC2.ModifyVolumeAttribute
import Network.AWS.EC2.ModifyVpcAttribute
import Network.AWS.EC2.MonitorInstances
import Network.AWS.EC2.PurchaseReservedInstancesOffering
import Network.AWS.EC2.RebootInstances
import Network.AWS.EC2.RegisterImage
import Network.AWS.EC2.RejectVpcPeeringConnection
import Network.AWS.EC2.ReleaseAddress
import Network.AWS.EC2.ReplaceNetworkAclAssociation
import Network.AWS.EC2.ReplaceNetworkAclEntry
import Network.AWS.EC2.ReplaceRoute
import Network.AWS.EC2.ReplaceRouteTableAssociation
import Network.AWS.EC2.ReportInstanceStatus
import Network.AWS.EC2.RequestSpotInstances
import Network.AWS.EC2.ResetImageAttribute
import Network.AWS.EC2.ResetInstanceAttribute
import Network.AWS.EC2.ResetNetworkInterfaceAttribute
import Network.AWS.EC2.ResetSnapshotAttribute
import Network.AWS.EC2.RevokeSecurityGroupEgress
import Network.AWS.EC2.RevokeSecurityGroupIngress
import Network.AWS.EC2.RunInstances
import Network.AWS.EC2.StartInstances
import Network.AWS.EC2.StopInstances
import Network.AWS.EC2.TerminateInstances
import Network.AWS.EC2.Types
import Network.AWS.EC2.UnassignPrivateIpAddresses
import Network.AWS.EC2.UnmonitorInstances
import Network.AWS.EC2.Waiters
| kim/amazonka | amazonka-ec2/gen/Network/AWS/EC2.hs | mpl-2.0 | 16,641 | 0 | 5 | 1,747 | 2,462 | 1,811 | 651 | 325 | 0 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Token Generator | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/tokengen/src/main/javahelp/org/zaproxy/zap/extension/tokengen/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 977 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
import Blaze.ByteString.Builder (copyByteString)
import Control.Concurrent (runInUnboundThread)
import Data.Aeson ((.=), object, encode)
import qualified Data.ByteString.Lazy as L
import Data.Text (Text)
import Network.HTTP.Types (status200)
import Network.Wai (responseBuilder)
import qualified Network.Wai.Handler.Warp as W
main :: IO ()
main =
runInUnboundThread $ W.runSettings settings app
where
settings = W.setPort 8000
$ W.setOnException (\_ _ -> return ()) W.defaultSettings
app _ respond = respond response
!response = responseBuilder status200 ct json
ct = [("Content-Type", "application/json")]
!json = copyByteString
$ L.toStrict
$ encode
$ object ["message" .= ("Hello, World!" :: Text)]
| kellabyte/FrameworkBenchmarks | frameworks/Haskell/wai/bench/wai.hs | bsd-3-clause | 822 | 0 | 12 | 161 | 235 | 133 | 102 | 21 | 1 |
module Language.StreamIt
(
module Language.StreamIt.Backend,
module Language.StreamIt.Compile,
module Language.StreamIt.Core,
module Language.StreamIt.Filter,
module Language.StreamIt.Graph,
module Language.StreamIt.Runtime
) where
import Language.StreamIt.Backend
import Language.StreamIt.Compile
import Language.StreamIt.Core
import Language.StreamIt.Filter
import Language.StreamIt.Graph
import Language.StreamIt.Runtime
| adk9/haskell-streamit | Language/StreamIt.hs | bsd-3-clause | 453 | 0 | 5 | 58 | 86 | 59 | 27 | 14 | 0 |
main = defaultMain
| lucasdicioccio/distcat | Setup.hs | bsd-3-clause | 20 | 0 | 4 | 4 | 6 | 3 | 3 | 1 | 1 |
-- Test Example for Push Notifications.
-- This is a simple example of a Yesod server, where devices can register
-- and play the multiplayer "Connect 4" game, and send/receive messages.
{-# LANGUAGE OverloadedStrings, TypeFamilies, TemplateHaskell, QuasiQuotes, MultiParamTypeClasses #-}
module Main where
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Database.Persist.Sqlite
import Data.Aeson
import Data.Default
import Data.IORef
import Data.List ((\\))
import Data.Text (Text,pack,unpack,empty)
import Data.Time.Clock.POSIX
import qualified Data.Array as DA
import Control.Concurrent
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TChan (TChan, newTChan, tryReadTChan, readTChan)
import Control.Monad.Logger
import Control.Monad.Trans.Resource (runResourceT)
import System.Environment (getEnv)
import System.Timeout
import Network.PushNotify.Gcm
import Network.PushNotify.General
import Network.HTTP.Conduit
import Connect4
import CommWebUsers
import CommDevices
import DataBase
import Extra
import Handlers
import Import
-- Yesod App:
staticFiles "static"
data Messages = Messages {
connectionPool :: ConnectionPool -- Connection to the Database.
, getStatic :: Static -- Reference point of the static data.
, pushManager :: PushManager
, httpManager :: Manager
, onlineUsers :: IORef WebUsers
}
readMaybe :: (Read a) => String -> Maybe a
readMaybe s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
mkYesod "Messages" [parseRoutes|
/ RootR GET
/fromweb FromWebR POST
/receive ReceiveR GET
/fromdevices PushManagerR PushManager pushManager
/getusers GetUsersR GET
/static StaticR Static getStatic
/auth AuthR Auth getAuth
|]
-- Instances:
instance Yesod Messages where
approot = ApprootStatic "http://192.168.0.52:3000"
defaultLayout widget = do
pc <- widgetToPageContent $ do
widget
base <- widgetToPageContent ($(widgetFile "base"))
giveUrlRenderer [hamlet|
$doctype 5
<html>
<head>
^{pageHead base}
^{pageHead pc}
<body>
<div id="main">
^{pageBody base}
^{pageBody pc}
<div id="footer">
<div id="source">
Source code available on <a href="https://github.com/MarcosPividori/Connect4-GSoCExample"><b>GitHub</b></a>
<div id="deployment">
Deployed on <a href="https://www.fpcomplete.com/"><b>FPComplete</b></a>
|]
instance YesodAuth Messages where
type AuthId Messages = Text
getAuthId = return . Just . credsIdent
loginDest _ = RootR
logoutDest _ = RootR
authPlugins _ =
[ authBrowserId def
, authGoogleEmail
]
authHttpManager = httpManager
maybeAuthId = lookupSession "_ID"
instance YesodPersist Messages where
type YesodPersistBackend Messages = SqlPersistT
runDB action = do
Messages pool _ _ _ _ <- getYesod
runSqlPool action pool
instance RenderMessage Messages FormMessage where
renderMessage _ _ = defaultFormMessage
-- Handlers:
-- This function actualizes the time of the last communication with a web user.
actualize :: Text -> Handler WebUsers
actualize user1 = do
Messages _ _ _ _ webUsers <- getYesod
ctime <- liftIO $ getPOSIXTime
liftIO $ atomicModifyIORef webUsers (\s ->
case getClient user1 s of
Just (c,_) -> let s' = addClient user1 c ctime s in (s',s')
_ -> (s,s) )
-- 'postFromWebR' receives messages from the website user. (POST messages to '/fromweb')
postFromWebR :: Handler ()
postFromWebR = do
maid <- maybeAuthId
case maid of
Nothing -> redirect $ AuthR LoginR
Just user1 -> do
Messages pool _ man _ _ <- getYesod
list <- actualize user1
case getClient user1 list of
Nothing -> redirect $ AuthR LoginR
Just (id1,_) -> do
m <- runInputGet $ iopt textField "message"
$(logInfo) . pack $ "New Message : " ++ show m
case m >>= readMaybe . unpack of
Just msg -> do
$(logInfo) . pack $ "New parsed Message : " ++ show msg
liftIO $ handleMessage pool list man (Web id1) user1 msg
_ -> return ()
redirect RootR
-- 'getReceiveR' wait for an event. (GET messages to '/receive')
getReceiveR :: Handler ()
getReceiveR = do
maid <- maybeAuthId
case maid of
Nothing -> return ()
Just user1 -> do
Messages _ _ _ _ webRef <- getYesod
webUsers <- liftIO $ readIORef webRef
case getClient user1 webUsers of
Nothing -> sendResponse $ RepJson $ toContent $ object []
Just (ch,_) -> do
actualize user1
res <- liftIO $ timeout 10000000 $ (atomically $ readTChan ch)
$(logInfo) $ pack $ "Sending MESSAGE TO WEBUSER" ++ show res
case res of
Nothing -> sendResponse $ RepJson $ toContent $ object []
Just r -> sendResponse $ RepJson $ toContent $ setMessageValue r
-- 'getRootR' provides the main page.
getRootR :: Handler Html
getRootR = do
maid <- maybeAuthId
case maid of
Nothing -> redirect $ AuthR LoginR
Just user1 -> do
Messages _ _ _ _ webRef <- getYesod
webUsers <- liftIO $ readIORef webRef
case getClient user1 webUsers of
Nothing -> do
ctime <- liftIO $ getPOSIXTime
chan <- liftIO $ atomically $ newTChan
liftIO $ atomicModifyIORef webRef (\s ->
let s' = addClient user1 chan ctime s
in (s', ()) )
Just (ch,_) -> liftIO $ cleanTChan ch
g1 <- runDB $ getBy $ UniqueUser1 user1
g2 <- runDB $ getBy $ UniqueUser2 user1
let (game,numUser) = case g1 of
Nothing -> (g2,-1)
_ -> (g1,1)
case game of
Just g -> do
let list = concat $ map (\i -> map (\j -> (DA.!) (gamesMatrix(entityVal g)) (i,j)) [0..6]) [0..5]
user2 = case gamesUser1 (entityVal g) == user1 of
True -> gamesUser2 (entityVal g)
False -> gamesUser1 (entityVal g)
turn = gamesTurn (entityVal g)
jsonData = object [ "grid" .= array list , "numUser" .= show numUser , "user2" .= user2
, "playing" .= True , "turn" .= turn , "user1" .= user1 ]
defaultLayout $(widgetFile "Home")
Nothing -> do
let jsonData = object ["playing" .= False , "user1" .= user1 ]
defaultLayout $(widgetFile "Home")
where
cleanTChan ch = do
r <- atomically $ tryReadTChan ch
case r of
Just _ -> cleanTChan ch
Nothing -> return ()
getFreelist :: Handler [Text]
getFreelist = do
connect4list <- (runDB $ selectList [] [Desc DevicesUser])
>>= return . map (\a -> devicesUser(entityVal a))
Messages _ _ _ _ refUsers <- getYesod
webList <- liftIO $ readIORef refUsers
>>= return . getClients
playinglist1 <- runDB (selectList [] [Desc GamesUser1])
>>= return . map (\a -> gamesUser1(entityVal a))
playinglist2 <- runDB (selectList [] [Desc GamesUser2])
>>= return . map (\a -> gamesUser2(entityVal a))
let mCon4 = ((connect4list ++ webList) \\ playinglist1) \\ playinglist2
return mCon4
-- 'getGetUsersR' provides the list of users that are available to play ("con4").
getGetUsersR :: Handler RepJson
getGetUsersR = do
maid <- maybeAuthId
case maid of
Just user1 -> actualize user1 >> return ()
Nothing -> return ()
con4List <- getFreelist
sendResponse $ toTypedContent $ object ["con4" .= array con4List ]
main :: IO ()
main = runResourceT . runNoLoggingT $ withSqlitePool "DevicesDateBase.db3" 10 $ \pool -> do
runSqlPool (runMigration migrateAll) pool
liftIO $ do
ref <- newIORef Nothing
onlineUsers <- newIORef newWebUsersState
man <- startPushService $ PushServiceConfig{
pushConfig = def{ gcmConfig = Just $ Ccs $ def{
apiKey = "api key for connect 4 app"
senderId = "sender id for connect 4 app" } }
, newMessageCallback = handleNewMessage pool onlineUsers ref
, newDeviceCallback = handleNewDevice pool
, unRegisteredCallback = handleUnregistered pool
, newIdCallback = handleNewId pool
}
m <- newManager def
forkIO $ checker onlineUsers man pool
writeIORef ref $ Just man
static@(Static settings) <- static "static"
warp 3000 $ Messages pool static man m onlineUsers
limit :: POSIXTime
limit = 240
-- 'checker' checks every 30 seconds the webUsers list and removes inactive users.
checker :: IORef WebUsers -> PushManager -> ConnectionPool -> IO ()
checker onlineUsers man pool = do
ctime <- getPOSIXTime
(r,c,s) <- atomicModifyIORef onlineUsers (\s ->
let rem = filterClients (\(c,t) -> (ctime - t) > limit) s
names = getClients $ rem
chans = getClientsElems $ rem
s' = filterClients (\(c,t) -> (ctime - t) <= limit) s
in (s', (names,chans,s)) )
putStrLn $ "Remove: " ++ show r
mapM_ (\(us,(ch,_)) -> handleMessage pool s man (Web ch) us Cancel) $ zip r c
threadDelay 30000000
checker onlineUsers man pool
| jimpeak/GSoC-Communicating-with-mobile-devices | test/Connect4/Yesod-App/Main.hs | mit | 10,431 | 1 | 31 | 3,612 | 2,638 | 1,329 | 1,309 | -1 | -1 |
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module TcEvidence (
-- HsWrapper
HsWrapper(..),
(<.>), mkWpTyApps, mkWpEvApps, mkWpEvVarApps, mkWpTyLams, mkWpLams, mkWpLet, mkWpCast,
mkWpFun, idHsWrapper, isIdHsWrapper, pprHsWrapper,
-- Evidence bindings
TcEvBinds(..), EvBindsVar(..),
EvBindMap(..), emptyEvBindMap, extendEvBinds,
lookupEvBind, evBindMapBinds, foldEvBindMap,
EvBind(..), emptyTcEvBinds, isEmptyTcEvBinds, mkGivenEvBind, mkWantedEvBind,
EvTerm(..), mkEvCast, evVarsOfTerm, mkEvScSelectors,
EvLit(..), evTermCoercion,
EvCallStack(..),
EvTypeable(..),
-- TcCoercion
TcCoercion(..), LeftOrRight(..), pickLR,
mkTcReflCo, mkTcNomReflCo, mkTcRepReflCo,
mkTcTyConAppCo, mkTcAppCo, mkTcAppCos, mkTcFunCo,
mkTcAxInstCo, mkTcUnbranchedAxInstCo, mkTcForAllCo, mkTcForAllCos,
mkTcSymCo, mkTcTransCo, mkTcNthCo, mkTcLRCo, mkTcSubCo, maybeTcSubCo,
tcDowngradeRole, mkTcTransAppCo,
mkTcAxiomRuleCo, mkTcPhantomCo,
tcCoercionKind, coVarsOfTcCo, isEqVar, mkTcCoVarCo,
isTcReflCo, getTcCoVar_maybe,
tcCoercionRole, eqVarRole,
unwrapIP, wrapIP
) where
#include "HsVersions.h"
import Var
import Coercion
import PprCore () -- Instance OutputableBndr TyVar
import TypeRep -- Knows type representation
import TcType
import Type
import TyCon
import Class( Class )
import CoAxiom
import PrelNames
import VarEnv
import VarSet
import Name
import Util
import Bag
import Pair
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
import Data.Traversable (traverse, sequenceA)
#endif
import qualified Data.Data as Data
import Outputable
import FastString
import SrcLoc
import Data.IORef( IORef )
{-
Note [TcCoercions]
~~~~~~~~~~~~~~~~~~
| TcCoercions are a hack used by the typechecker. Normally,
Coercions have free variables of type (a ~# b): we call these
CoVars. However, the type checker passes around equality evidence
(boxed up) at type (a ~ b).
An TcCoercion is simply a Coercion whose free variables have the
boxed type (a ~ b). After we are done with typechecking the
desugarer finds the free variables, unboxes them, and creates a
resulting real Coercion with kosher free variables.
We can use most of the Coercion "smart constructors" to build TcCoercions.
However, mkCoVarCo will not work! The equivalent is mkTcCoVarCo.
The data type is similar to Coercion.Coercion, with the following
differences
* Most important, TcLetCo adds let-bindings for coercions.
This is what lets us unify two for-all types and generate
equality constraints underneath
* The kind of a TcCoercion is t1 ~ t2 (resp. Coercible t1 t2)
of a Coercion is t1 ~# t2 (resp. t1 ~#R t2)
* UnsafeCo aren't required, but we do have TcPhantomCo
* Representation invariants are weaker:
- we are allowed to have type synonyms in TcTyConAppCo
- the first arg of a TcAppCo can be a TcTyConAppCo
- TcSubCo is not applied as deep as done with mkSubCo
Reason: they'll get established when we desugar to Coercion
* TcAxiomInstCo has a [TcCoercion] parameter, and not a [Type] parameter.
This differs from the formalism, but corresponds to AxiomInstCo (see
[Coercion axioms applied to coercions]).
Note [mkTcTransAppCo]
~~~~~~~~~~~~~~~~~~~~~
Suppose we have
co1 :: a ~R Maybe
co2 :: b ~R Int
and we want
co3 :: a b ~R Maybe Int
This seems sensible enough. But, we can't let (co3 = co1 co2), because
that's ill-roled! Note that mkTcAppCo requires a *nominal* second coercion.
The way around this is to use transitivity:
co3 = (co1 <b>_N) ; (Maybe co2) :: a b ~R Maybe Int
Or, it's possible everything is the other way around:
co1' :: Maybe ~R a
co2' :: Int ~R b
and we want
co3' :: Maybe Int ~R a b
then
co3' = (Maybe co2') ; (co1' <b>_N)
This is exactly what `mkTcTransAppCo` builds for us. Information for all
the arguments tends to be to hand at call sites, so it's quicker than
using, say, tcCoercionKind.
-}
data TcCoercion
= TcRefl Role TcType
| TcTyConAppCo Role TyCon [TcCoercion]
| TcAppCo TcCoercion TcCoercion
| TcForAllCo TyVar TcCoercion
| TcCoVarCo EqVar
| TcAxiomInstCo (CoAxiom Branched) Int [TcCoercion] -- Int specifies branch number
-- See [CoAxiom Index] in Coercion.hs
-- This is number of types and coercions are expected to match to CoAxiomRule
-- (i.e., the CoAxiomRules are always fully saturated)
| TcAxiomRuleCo CoAxiomRule [TcType] [TcCoercion]
| TcPhantomCo TcType TcType
| TcSymCo TcCoercion
| TcTransCo TcCoercion TcCoercion
| TcNthCo Int TcCoercion
| TcLRCo LeftOrRight TcCoercion
| TcSubCo TcCoercion
| TcCastCo TcCoercion TcCoercion -- co1 |> co2
| TcLetCo TcEvBinds TcCoercion
| TcCoercion Coercion -- embed a Core Coercion
deriving (Data.Data, Data.Typeable)
isEqVar :: Var -> Bool
-- Is lifted coercion variable (only!)
isEqVar v = case tyConAppTyCon_maybe (varType v) of
Just tc -> tc `hasKey` eqTyConKey
Nothing -> False
isTcReflCo_maybe :: TcCoercion -> Maybe TcType
isTcReflCo_maybe (TcRefl _ ty) = Just ty
isTcReflCo_maybe (TcCoercion co) = isReflCo_maybe co
isTcReflCo_maybe _ = Nothing
isTcReflCo :: TcCoercion -> Bool
isTcReflCo (TcRefl {}) = True
isTcReflCo (TcCoercion co) = isReflCo co
isTcReflCo _ = False
getTcCoVar_maybe :: TcCoercion -> Maybe CoVar
getTcCoVar_maybe (TcCoVarCo v) = Just v
getTcCoVar_maybe _ = Nothing
mkTcReflCo :: Role -> TcType -> TcCoercion
mkTcReflCo = TcRefl
mkTcNomReflCo :: TcType -> TcCoercion
mkTcNomReflCo = TcRefl Nominal
mkTcRepReflCo :: TcType -> TcCoercion
mkTcRepReflCo = TcRefl Representational
mkTcFunCo :: Role -> TcCoercion -> TcCoercion -> TcCoercion
mkTcFunCo role co1 co2 = mkTcTyConAppCo role funTyCon [co1, co2]
mkTcTyConAppCo :: Role -> TyCon -> [TcCoercion] -> TcCoercion
mkTcTyConAppCo role tc cos -- No need to expand type synonyms
-- See Note [TcCoercions]
| Just tys <- traverse isTcReflCo_maybe cos
= TcRefl role (mkTyConApp tc tys) -- See Note [Refl invariant]
| otherwise = TcTyConAppCo role tc cos
-- input coercion is Nominal
-- mkSubCo will do some normalisation. We do not do it for TcCoercions, but
-- defer that to desugaring; just to reduce the code duplication a little bit
mkTcSubCo :: TcCoercion -> TcCoercion
mkTcSubCo co = ASSERT2( tcCoercionRole co == Nominal, ppr co)
TcSubCo co
-- See Note [Role twiddling functions] in Coercion
-- | Change the role of a 'TcCoercion'. Returns 'Nothing' if this isn't
-- a downgrade.
tcDowngradeRole_maybe :: Role -- desired role
-> Role -- current role
-> TcCoercion -> Maybe TcCoercion
tcDowngradeRole_maybe Representational Nominal = Just . mkTcSubCo
tcDowngradeRole_maybe Nominal Representational = const Nothing
tcDowngradeRole_maybe Phantom _
= panic "tcDowngradeRole_maybe Phantom"
-- not supported (not needed at the moment)
tcDowngradeRole_maybe _ Phantom = const Nothing
tcDowngradeRole_maybe _ _ = Just
-- See Note [Role twiddling functions] in Coercion
-- | Change the role of a 'TcCoercion'. Panics if this isn't a downgrade.
tcDowngradeRole :: Role -- ^ desired role
-> Role -- ^ current role
-> TcCoercion -> TcCoercion
tcDowngradeRole r1 r2 co
= case tcDowngradeRole_maybe r1 r2 co of
Just co' -> co'
Nothing -> pprPanic "tcDowngradeRole" (ppr r1 <+> ppr r2 <+> ppr co)
-- | If the EqRel is ReprEq, makes a TcSubCo; otherwise, does nothing.
-- Note that the input coercion should always be nominal.
maybeTcSubCo :: EqRel -> TcCoercion -> TcCoercion
maybeTcSubCo NomEq = id
maybeTcSubCo ReprEq = mkTcSubCo
mkTcAxInstCo :: Role -> CoAxiom br -> Int -> [TcType] -> TcCoercion
mkTcAxInstCo role ax index tys
| ASSERT2( not (role == Nominal && ax_role == Representational) , ppr (ax, tys) )
arity == n_tys = tcDowngradeRole role ax_role $
TcAxiomInstCo ax_br index rtys
| otherwise = ASSERT( arity < n_tys )
tcDowngradeRole role ax_role $
foldl TcAppCo (TcAxiomInstCo ax_br index (take arity rtys))
(drop arity rtys)
where
n_tys = length tys
ax_br = toBranchedAxiom ax
branch = coAxiomNthBranch ax_br index
arity = length $ coAxBranchTyVars branch
ax_role = coAxiomRole ax
arg_roles = coAxBranchRoles branch
rtys = zipWith mkTcReflCo (arg_roles ++ repeat Nominal) tys
mkTcAxiomRuleCo :: CoAxiomRule -> [TcType] -> [TcCoercion] -> TcCoercion
mkTcAxiomRuleCo = TcAxiomRuleCo
mkTcUnbranchedAxInstCo :: Role -> CoAxiom Unbranched -> [TcType] -> TcCoercion
mkTcUnbranchedAxInstCo role ax tys
= mkTcAxInstCo role ax 0 tys
mkTcAppCo :: TcCoercion -> TcCoercion -> TcCoercion
-- No need to deal with TyConApp on the left; see Note [TcCoercions]
-- Second coercion *must* be nominal
mkTcAppCo (TcRefl r ty1) (TcRefl _ ty2) = TcRefl r (mkAppTy ty1 ty2)
mkTcAppCo co1 co2 = TcAppCo co1 co2
-- | Like `mkTcAppCo`, but allows the second coercion to be other than
-- nominal. See Note [mkTcTransAppCo]. Role r3 cannot be more stringent
-- than either r1 or r2.
mkTcTransAppCo :: Role -- ^ r1
-> TcCoercion -- ^ co1 :: ty1a ~r1 ty1b
-> TcType -- ^ ty1a
-> TcType -- ^ ty1b
-> Role -- ^ r2
-> TcCoercion -- ^ co2 :: ty2a ~r2 ty2b
-> TcType -- ^ ty2a
-> TcType -- ^ ty2b
-> Role -- ^ r3
-> TcCoercion -- ^ :: ty1a ty2a ~r3 ty1b ty2b
mkTcTransAppCo r1 co1 ty1a ty1b r2 co2 ty2a ty2b r3
-- How incredibly fiddly! Is there a better way??
= case (r1, r2, r3) of
(_, _, Phantom)
-> mkTcPhantomCo (mkAppTy ty1a ty2a) (mkAppTy ty1b ty2b)
(_, _, Nominal)
-> ASSERT( r1 == Nominal && r2 == Nominal )
mkTcAppCo co1 co2
(Nominal, Nominal, Representational)
-> mkTcSubCo (mkTcAppCo co1 co2)
(_, Nominal, Representational)
-> ASSERT( r1 == Representational )
mkTcAppCo co1 co2
(Nominal, Representational, Representational)
-> go (mkTcSubCo co1)
(_ , _, Representational)
-> ASSERT( r1 == Representational && r2 == Representational )
go co1
where
go co1_repr
| Just (tc1b, tys1b) <- tcSplitTyConApp_maybe ty1b
, nextRole ty1b == r2
= (co1_repr `mkTcAppCo` mkTcNomReflCo ty2a) `mkTcTransCo`
(mkTcTyConAppCo Representational tc1b
(zipWith mkTcReflCo (tyConRolesX Representational tc1b) tys1b
++ [co2]))
| Just (tc1a, tys1a) <- tcSplitTyConApp_maybe ty1a
, nextRole ty1a == r2
= (mkTcTyConAppCo Representational tc1a
(zipWith mkTcReflCo (tyConRolesX Representational tc1a) tys1a
++ [co2]))
`mkTcTransCo`
(co1_repr `mkTcAppCo` mkTcNomReflCo ty2b)
| otherwise
= pprPanic "mkTcTransAppCo" (vcat [ ppr r1, ppr co1, ppr ty1a, ppr ty1b
, ppr r2, ppr co2, ppr ty2a, ppr ty2b
, ppr r3 ])
mkTcSymCo :: TcCoercion -> TcCoercion
mkTcSymCo co@(TcRefl {}) = co
mkTcSymCo (TcSymCo co) = co
mkTcSymCo co = TcSymCo co
mkTcTransCo :: TcCoercion -> TcCoercion -> TcCoercion
mkTcTransCo (TcRefl {}) co = co
mkTcTransCo co (TcRefl {}) = co
mkTcTransCo co1 co2 = TcTransCo co1 co2
mkTcNthCo :: Int -> TcCoercion -> TcCoercion
mkTcNthCo n (TcRefl r ty) = TcRefl r (tyConAppArgN n ty)
mkTcNthCo n co = TcNthCo n co
mkTcLRCo :: LeftOrRight -> TcCoercion -> TcCoercion
mkTcLRCo lr (TcRefl r ty) = TcRefl r (pickLR lr (tcSplitAppTy ty))
mkTcLRCo lr co = TcLRCo lr co
mkTcPhantomCo :: TcType -> TcType -> TcCoercion
mkTcPhantomCo = TcPhantomCo
mkTcAppCos :: TcCoercion -> [TcCoercion] -> TcCoercion
mkTcAppCos co1 tys = foldl mkTcAppCo co1 tys
mkTcForAllCo :: Var -> TcCoercion -> TcCoercion
-- note that a TyVar should be used here, not a CoVar (nor a TcTyVar)
mkTcForAllCo tv (TcRefl r ty) = ASSERT( isTyVar tv ) TcRefl r (mkForAllTy tv ty)
mkTcForAllCo tv co = ASSERT( isTyVar tv ) TcForAllCo tv co
mkTcForAllCos :: [Var] -> TcCoercion -> TcCoercion
mkTcForAllCos tvs (TcRefl r ty) = ASSERT( all isTyVar tvs ) TcRefl r (mkForAllTys tvs ty)
mkTcForAllCos tvs co = ASSERT( all isTyVar tvs ) foldr TcForAllCo co tvs
mkTcCoVarCo :: EqVar -> TcCoercion
-- ipv :: s ~ t (the boxed equality type) or Coercible s t (the boxed representational equality type)
mkTcCoVarCo ipv = TcCoVarCo ipv
-- Previously I checked for (ty ~ ty) and generated Refl,
-- but in fact ipv may not even (visibly) have a (t1 ~ t2) type, because
-- the constraint solver does not substitute in the types of
-- evidence variables as it goes. In any case, the optimisation
-- will be done in the later zonking phase
tcCoercionKind :: TcCoercion -> Pair Type
tcCoercionKind co = go co
where
go (TcRefl _ ty) = Pair ty ty
go (TcLetCo _ co) = go co
go (TcCastCo _ co) = case getEqPredTys (pSnd (go co)) of
(ty1,ty2) -> Pair ty1 ty2
go (TcTyConAppCo _ tc cos)= mkTyConApp tc <$> (sequenceA $ map go cos)
go (TcAppCo co1 co2) = mkAppTy <$> go co1 <*> go co2
go (TcForAllCo tv co) = mkForAllTy tv <$> go co
go (TcCoVarCo cv) = eqVarKind cv
go (TcAxiomInstCo ax ind cos)
= let branch = coAxiomNthBranch ax ind
tvs = coAxBranchTyVars branch
Pair tys1 tys2 = sequenceA (map go cos)
in ASSERT( cos `equalLength` tvs )
Pair (substTyWith tvs tys1 (coAxNthLHS ax ind))
(substTyWith tvs tys2 (coAxBranchRHS branch))
go (TcPhantomCo ty1 ty2) = Pair ty1 ty2
go (TcSymCo co) = swap (go co)
go (TcTransCo co1 co2) = Pair (pFst (go co1)) (pSnd (go co2))
go (TcNthCo d co) = tyConAppArgN d <$> go co
go (TcLRCo lr co) = (pickLR lr . tcSplitAppTy) <$> go co
go (TcSubCo co) = go co
go (TcAxiomRuleCo ax ts cs) =
case coaxrProves ax ts (map tcCoercionKind cs) of
Just res -> res
Nothing -> panic "tcCoercionKind: malformed TcAxiomRuleCo"
go (TcCoercion co) = coercionKind co
eqVarRole :: EqVar -> Role
eqVarRole cv = getEqPredRole (varType cv)
eqVarKind :: EqVar -> Pair Type
eqVarKind cv
| Just (tc, [_kind,ty1,ty2]) <- tcSplitTyConApp_maybe (varType cv)
= ASSERT(tc `hasKey` eqTyConKey)
Pair ty1 ty2
| otherwise = pprPanic "eqVarKind, non coercion variable" (ppr cv <+> dcolon <+> ppr (varType cv))
tcCoercionRole :: TcCoercion -> Role
tcCoercionRole = go
where
go (TcRefl r _) = r
go (TcTyConAppCo r _ _) = r
go (TcAppCo co _) = go co
go (TcForAllCo _ co) = go co
go (TcCoVarCo cv) = eqVarRole cv
go (TcAxiomInstCo ax _ _) = coAxiomRole ax
go (TcPhantomCo _ _) = Phantom
go (TcSymCo co) = go co
go (TcTransCo co1 _) = go co1 -- same as go co2
go (TcNthCo n co) = let Pair ty1 _ = tcCoercionKind co
(tc, _) = tcSplitTyConApp ty1
in nthRole (go co) tc n
go (TcLRCo _ _) = Nominal
go (TcSubCo _) = Representational
go (TcAxiomRuleCo c _ _) = coaxrRole c
go (TcCastCo c _) = go c
go (TcLetCo _ c) = go c
go (TcCoercion co) = coercionRole co
coVarsOfTcCo :: TcCoercion -> VarSet
-- Only works on *zonked* coercions, because of TcLetCo
coVarsOfTcCo tc_co
= go tc_co
where
go (TcRefl _ _) = emptyVarSet
go (TcTyConAppCo _ _ cos) = mapUnionVarSet go cos
go (TcAppCo co1 co2) = go co1 `unionVarSet` go co2
go (TcCastCo co1 co2) = go co1 `unionVarSet` go co2
go (TcForAllCo _ co) = go co
go (TcCoVarCo v) = unitVarSet v
go (TcAxiomInstCo _ _ cos) = mapUnionVarSet go cos
go (TcPhantomCo _ _) = emptyVarSet
go (TcSymCo co) = go co
go (TcTransCo co1 co2) = go co1 `unionVarSet` go co2
go (TcNthCo _ co) = go co
go (TcLRCo _ co) = go co
go (TcSubCo co) = go co
go (TcLetCo (EvBinds bs) co) = foldrBag (unionVarSet . go_bind) (go co) bs
`minusVarSet` get_bndrs bs
go (TcLetCo {}) = emptyVarSet -- Harumph. This does legitimately happen in the call
-- to evVarsOfTerm in the DEBUG check of setEvBind
go (TcAxiomRuleCo _ _ cos) = mapUnionVarSet go cos
go (TcCoercion co) = -- the use of coVarsOfTcCo in dsTcCoercion will
-- fail if there are any proper, unlifted covars
ASSERT( isEmptyVarSet (coVarsOfCo co) )
emptyVarSet
-- We expect only coercion bindings, so use evTermCoercion
go_bind :: EvBind -> VarSet
go_bind (EvBind { eb_rhs =tm }) = go (evTermCoercion tm)
get_bndrs :: Bag EvBind -> VarSet
get_bndrs = foldrBag (\ (EvBind { eb_lhs = b }) bs -> extendVarSet bs b) emptyVarSet
-- Pretty printing
instance Outputable TcCoercion where
ppr = pprTcCo
pprTcCo, pprParendTcCo :: TcCoercion -> SDoc
pprTcCo co = ppr_co TopPrec co
pprParendTcCo co = ppr_co TyConPrec co
ppr_co :: TyPrec -> TcCoercion -> SDoc
ppr_co _ (TcRefl r ty) = angleBrackets (ppr ty) <> ppr_role r
ppr_co p co@(TcTyConAppCo _ tc [_,_])
| tc `hasKey` funTyConKey = ppr_fun_co p co
ppr_co p (TcTyConAppCo r tc cos) = pprTcApp p ppr_co tc cos <> ppr_role r
ppr_co p (TcLetCo bs co) = maybeParen p TopPrec $
sep [ptext (sLit "let") <+> braces (ppr bs), ppr co]
ppr_co p (TcAppCo co1 co2) = maybeParen p TyConPrec $
pprTcCo co1 <+> ppr_co TyConPrec co2
ppr_co p (TcCastCo co1 co2) = maybeParen p FunPrec $
ppr_co FunPrec co1 <+> ptext (sLit "|>") <+> ppr_co FunPrec co2
ppr_co p co@(TcForAllCo {}) = ppr_forall_co p co
ppr_co _ (TcCoVarCo cv) = parenSymOcc (getOccName cv) (ppr cv)
ppr_co p (TcAxiomInstCo con ind cos)
= pprPrefixApp p (ppr (getName con) <> brackets (ppr ind)) (map pprParendTcCo cos)
ppr_co p (TcTransCo co1 co2) = maybeParen p FunPrec $
ppr_co FunPrec co1
<+> ptext (sLit ";")
<+> ppr_co FunPrec co2
ppr_co p (TcPhantomCo t1 t2) = pprPrefixApp p (ptext (sLit "PhantomCo")) [pprParendType t1, pprParendType t2]
ppr_co p (TcSymCo co) = pprPrefixApp p (ptext (sLit "Sym")) [pprParendTcCo co]
ppr_co p (TcNthCo n co) = pprPrefixApp p (ptext (sLit "Nth:") <+> int n) [pprParendTcCo co]
ppr_co p (TcLRCo lr co) = pprPrefixApp p (ppr lr) [pprParendTcCo co]
ppr_co p (TcSubCo co) = pprPrefixApp p (ptext (sLit "Sub")) [pprParendTcCo co]
ppr_co p (TcAxiomRuleCo co ts ps) = maybeParen p TopPrec
$ ppr_tc_axiom_rule_co co ts ps
ppr_co p (TcCoercion co) = pprPrefixApp p (text "Core co:") [ppr co]
ppr_tc_axiom_rule_co :: CoAxiomRule -> [TcType] -> [TcCoercion] -> SDoc
ppr_tc_axiom_rule_co co ts ps = ppr (coaxrName co) <> ppTs ts $$ nest 2 (ppPs ps)
where
ppTs [] = Outputable.empty
ppTs [t] = ptext (sLit "@") <> ppr_type TopPrec t
ppTs ts = ptext (sLit "@") <>
parens (hsep $ punctuate comma $ map pprType ts)
ppPs [] = Outputable.empty
ppPs [p] = pprParendTcCo p
ppPs (p : ps) = ptext (sLit "(") <+> pprTcCo p $$
vcat [ ptext (sLit ",") <+> pprTcCo q | q <- ps ] $$
ptext (sLit ")")
ppr_role :: Role -> SDoc
ppr_role r = underscore <> pp_role
where pp_role = case r of
Nominal -> char 'N'
Representational -> char 'R'
Phantom -> char 'P'
ppr_fun_co :: TyPrec -> TcCoercion -> SDoc
ppr_fun_co p co = pprArrowChain p (split co)
where
split :: TcCoercion -> [SDoc]
split (TcTyConAppCo _ f [arg,res])
| f `hasKey` funTyConKey
= ppr_co FunPrec arg : split res
split co = [ppr_co TopPrec co]
ppr_forall_co :: TyPrec -> TcCoercion -> SDoc
ppr_forall_co p ty
= maybeParen p FunPrec $
sep [pprForAll tvs, ppr_co TopPrec rho]
where
(tvs, rho) = split1 [] ty
split1 tvs (TcForAllCo tv ty) = split1 (tv:tvs) ty
split1 tvs ty = (reverse tvs, ty)
{-
************************************************************************
* *
HsWrapper
* *
************************************************************************
-}
data HsWrapper
= WpHole -- The identity coercion
| WpCompose HsWrapper HsWrapper
-- (wrap1 `WpCompose` wrap2)[e] = wrap1[ wrap2[ e ]]
--
-- Hence (\a. []) `WpCompose` (\b. []) = (\a b. [])
-- But ([] a) `WpCompose` ([] b) = ([] b a)
| WpFun HsWrapper HsWrapper TcType TcType
-- (WpFun wrap1 wrap2 t1 t2)[e] = \(x:t1). wrap2[ e wrap1[x] ] :: t2
-- So note that if wrap1 :: exp_arg <= act_arg
-- wrap2 :: act_res <= exp_res
-- then WpFun wrap1 wrap2 : (act_arg -> arg_res) <= (exp_arg -> exp_res)
-- This isn't the same as for mkTcFunCo, but it has to be this way
-- because we can't use 'sym' to flip around these HsWrappers
| WpCast TcCoercion -- A cast: [] `cast` co
-- Guaranteed not the identity coercion
-- At role Representational
-- Evidence abstraction and application
-- (both dictionaries and coercions)
| WpEvLam EvVar -- \d. [] the 'd' is an evidence variable
| WpEvApp EvTerm -- [] d the 'd' is evidence for a constraint
-- Kind and Type abstraction and application
| WpTyLam TyVar -- \a. [] the 'a' is a type/kind variable (not coercion var)
| WpTyApp KindOrType -- [] t the 't' is a type (not coercion)
| WpLet TcEvBinds -- Non-empty (or possibly non-empty) evidence bindings,
-- so that the identity coercion is always exactly WpHole
deriving (Data.Data, Data.Typeable)
(<.>) :: HsWrapper -> HsWrapper -> HsWrapper
WpHole <.> c = c
c <.> WpHole = c
c1 <.> c2 = c1 `WpCompose` c2
mkWpFun :: HsWrapper -> HsWrapper -> TcType -> TcType -> HsWrapper
mkWpFun WpHole WpHole _ _ = WpHole
mkWpFun WpHole (WpCast co2) t1 _ = WpCast (mkTcFunCo Representational (mkTcRepReflCo t1) co2)
mkWpFun (WpCast co1) WpHole _ t2 = WpCast (mkTcFunCo Representational (mkTcSymCo co1) (mkTcRepReflCo t2))
mkWpFun (WpCast co1) (WpCast co2) _ _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) co2)
mkWpFun co1 co2 t1 t2 = WpFun co1 co2 t1 t2
mkWpCast :: TcCoercion -> HsWrapper
mkWpCast co
| isTcReflCo co = WpHole
| otherwise = ASSERT2(tcCoercionRole co == Representational, ppr co)
WpCast co
mkWpTyApps :: [Type] -> HsWrapper
mkWpTyApps tys = mk_co_app_fn WpTyApp tys
mkWpEvApps :: [EvTerm] -> HsWrapper
mkWpEvApps args = mk_co_app_fn WpEvApp args
mkWpEvVarApps :: [EvVar] -> HsWrapper
mkWpEvVarApps vs = mkWpEvApps (map EvId vs)
mkWpTyLams :: [TyVar] -> HsWrapper
mkWpTyLams ids = mk_co_lam_fn WpTyLam ids
mkWpLams :: [Var] -> HsWrapper
mkWpLams ids = mk_co_lam_fn WpEvLam ids
mkWpLet :: TcEvBinds -> HsWrapper
-- This no-op is a quite a common case
mkWpLet (EvBinds b) | isEmptyBag b = WpHole
mkWpLet ev_binds = WpLet ev_binds
mk_co_lam_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
mk_co_lam_fn f as = foldr (\x wrap -> f x <.> wrap) WpHole as
mk_co_app_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
-- For applications, the *first* argument must
-- come *last* in the composition sequence
mk_co_app_fn f as = foldr (\x wrap -> wrap <.> f x) WpHole as
idHsWrapper :: HsWrapper
idHsWrapper = WpHole
isIdHsWrapper :: HsWrapper -> Bool
isIdHsWrapper WpHole = True
isIdHsWrapper _ = False
{-
************************************************************************
* *
Evidence bindings
* *
************************************************************************
-}
data TcEvBinds
= TcEvBinds -- Mutable evidence bindings
EvBindsVar -- Mutable because they are updated "later"
-- when an implication constraint is solved
| EvBinds -- Immutable after zonking
(Bag EvBind)
deriving( Data.Typeable )
data EvBindsVar = EvBindsVar (IORef EvBindMap) Unique
-- The Unique is only for debug printing
instance Data.Data TcEvBinds where
-- Placeholder; we can't travers into TcEvBinds
toConstr _ = abstractConstr "TcEvBinds"
gunfold _ _ = error "gunfold"
dataTypeOf _ = Data.mkNoRepType "TcEvBinds"
-----------------
newtype EvBindMap
= EvBindMap {
ev_bind_varenv :: VarEnv EvBind
} -- Map from evidence variables to evidence terms
emptyEvBindMap :: EvBindMap
emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyVarEnv }
extendEvBinds :: EvBindMap -> EvBind -> EvBindMap
extendEvBinds bs ev_bind
= EvBindMap { ev_bind_varenv = extendVarEnv (ev_bind_varenv bs)
(eb_lhs ev_bind)
ev_bind }
lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind
lookupEvBind bs = lookupVarEnv (ev_bind_varenv bs)
evBindMapBinds :: EvBindMap -> Bag EvBind
evBindMapBinds = foldEvBindMap consBag emptyBag
foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a
foldEvBindMap k z bs = foldVarEnv k z (ev_bind_varenv bs)
-----------------
-- All evidence is bound by EvBinds; no side effects
data EvBind
= EvBind { eb_lhs :: EvVar
, eb_rhs :: EvTerm
, eb_is_given :: Bool -- True <=> given
-- See Note [Tracking redundant constraints] in TcSimplify
}
mkWantedEvBind :: EvVar -> EvTerm -> EvBind
mkWantedEvBind ev tm = EvBind { eb_is_given = False, eb_lhs = ev, eb_rhs = tm }
mkGivenEvBind :: EvVar -> EvTerm -> EvBind
mkGivenEvBind ev tm = EvBind { eb_is_given = True, eb_lhs = ev, eb_rhs = tm }
data EvTerm
= EvId EvId -- Any sort of evidence Id, including coercions
| EvCoercion TcCoercion -- (Boxed) coercion bindings
-- See Note [Coercion evidence terms]
| EvCast EvTerm TcCoercion -- d |> co, the coercion being at role representational
| EvDFunApp DFunId -- Dictionary instance application
[Type] [EvId]
| EvDelayedError Type FastString -- Used with Opt_DeferTypeErrors
-- See Note [Deferring coercion errors to runtime]
-- in TcSimplify
| EvSuperClass EvTerm Int -- n'th superclass. Used for both equalities and
-- dictionaries, even though the former have no
-- selector Id. We count up from _0_
| EvLit EvLit -- Dictionary for KnownNat and KnownSymbol classes.
-- Note [KnownNat & KnownSymbol and EvLit]
| EvCallStack EvCallStack -- Dictionary for CallStack implicit parameters
| EvTypeable EvTypeable -- Dictionary for `Typeable`
deriving( Data.Data, Data.Typeable )
-- | Instructions on how to make a 'Typeable' dictionary.
data EvTypeable
= EvTypeableTyCon TyCon [Kind]
-- ^ Dicitionary for concrete type constructors.
| EvTypeableTyApp (EvTerm,Type) (EvTerm,Type)
-- ^ Dictionary for type applications; this is used when we have
-- a type expression starting with a type variable (e.g., @Typeable (f a)@)
| EvTypeableTyLit Type
-- ^ Dictionary for a type literal.
deriving ( Data.Data, Data.Typeable )
data EvLit
= EvNum Integer
| EvStr FastString
deriving( Data.Data, Data.Typeable )
-- | Evidence for @CallStack@ implicit parameters.
data EvCallStack
-- See Note [Overview of implicit CallStacks]
= EvCsEmpty
| EvCsPushCall Name RealSrcSpan EvTerm
-- ^ @EvCsPushCall name loc stk@ represents a call to @name@, occurring at
-- @loc@, in a calling context @stk@.
| EvCsTop FastString RealSrcSpan EvTerm
-- ^ @EvCsTop name loc stk@ represents a use of an implicit parameter
-- @?name@, occurring at @loc@, in a calling context @stk@.
deriving( Data.Data, Data.Typeable )
{-
Note [Coercion evidence terms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A "coercion evidence term" takes one of these forms
co_tm ::= EvId v where v :: t1 ~ t2
| EvCoercion co
| EvCast co_tm co
We do quite often need to get a TcCoercion from an EvTerm; see
'evTermCoercion'.
INVARIANT: The evidence for any constraint with type (t1~t2) is
a coercion evidence term. Consider for example
[G] d :: F Int a
If we have
ax7 a :: F Int a ~ (a ~ Bool)
then we do NOT generate the constraint
[G] (d |> ax7 a) :: a ~ Bool
because that does not satisfy the invariant (d is not a coercion variable).
Instead we make a binding
g1 :: a~Bool = g |> ax7 a
and the constraint
[G] g1 :: a~Bool
See Trac [7238] and Note [Bind new Givens immediately] in TcRnTypes
Note [EvBinds/EvTerm]
~~~~~~~~~~~~~~~~~~~~~
How evidence is created and updated. Bindings for dictionaries,
and coercions and implicit parameters are carried around in TcEvBinds
which during constraint generation and simplification is always of the
form (TcEvBinds ref). After constraint simplification is finished it
will be transformed to t an (EvBinds ev_bag).
Evidence for coercions *SHOULD* be filled in using the TcEvBinds
However, all EvVars that correspond to *wanted* coercion terms in
an EvBind must be mutable variables so that they can be readily
inlined (by zonking) after constraint simplification is finished.
Conclusion: a new wanted coercion variable should be made mutable.
[Notice though that evidence variables that bind coercion terms
from super classes will be "given" and hence rigid]
Note [KnownNat & KnownSymbol and EvLit]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A part of the type-level literals implementation are the classes
"KnownNat" and "KnownSymbol", which provide a "smart" constructor for
defining singleton values. Here is the key stuff from GHC.TypeLits
class KnownNat (n :: Nat) where
natSing :: SNat n
newtype SNat (n :: Nat) = SNat Integer
Conceptually, this class has infinitely many instances:
instance KnownNat 0 where natSing = SNat 0
instance KnownNat 1 where natSing = SNat 1
instance KnownNat 2 where natSing = SNat 2
...
In practice, we solve `KnownNat` predicates in the type-checker
(see typecheck/TcInteract.hs) because we can't have infinately many instances.
The evidence (aka "dictionary") for `KnownNat` is of the form `EvLit (EvNum n)`.
We make the following assumptions about dictionaries in GHC:
1. The "dictionary" for classes with a single method---like `KnownNat`---is
a newtype for the type of the method, so using a evidence amounts
to a coercion, and
2. Newtypes use the same representation as their definition types.
So, the evidence for `KnownNat` is just a value of the representation type,
wrapped in two newtype constructors: one to make it into a `SNat` value,
and another to make it into a `KnownNat` dictionary.
Also note that `natSing` and `SNat` are never actually exposed from the
library---they are just an implementation detail. Instead, users see
a more convenient function, defined in terms of `natSing`:
natVal :: KnownNat n => proxy n -> Integer
The reason we don't use this directly in the class is that it is simpler
and more efficient to pass around an integer rather than an entier function,
especialy when the `KnowNat` evidence is packaged up in an existential.
The story for kind `Symbol` is analogous:
* class KnownSymbol
* newtype SSymbol
* Evidence: EvLit (EvStr n)
Note [Overview of implicit CallStacks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(See https://ghc.haskell.org/trac/ghc/wiki/ExplicitCallStack/ImplicitLocations)
The goal of CallStack evidence terms is to reify locations
in the program source as runtime values, without any support
from the RTS. We accomplish this by assigning a special meaning
to implicit parameters of type GHC.Stack.CallStack. A use of
a CallStack IP, e.g.
head [] = error (show (?loc :: CallStack))
head (x:_) = x
will be solved with the source location that gave rise to the IP
constraint (here, the use of ?loc). If there is already
a CallStack IP in scope, e.g. passed-in as an argument
head :: (?loc :: CallStack) => [a] -> a
head [] = error (show (?loc :: CallStack))
head (x:_) = x
we will push the new location onto the CallStack that was passed
in. These two cases are reflected by the EvCallStack evidence
type. In the first case, we will create an evidence term
EvCsTop "?loc" <?loc's location> EvCsEmpty
and in the second we'll have a given constraint
[G] d :: IP "loc" CallStack
in scope, and will create an evidence term
EvCsTop "?loc" <?loc's location> d
When we call a function that uses a CallStack IP, e.g.
f = head xs
we create an evidence term
EvCsPushCall "head" <head's location> EvCsEmpty
again pushing onto a given evidence term if one exists.
This provides a lightweight mechanism for building up call-stacks
explicitly, but is notably limited by the fact that the stack will
stop at the first function whose type does not include a CallStack IP.
For example, using the above definition of head:
f :: [a] -> a
f = head
g = f []
the resulting CallStack will include use of ?loc inside head and
the call to head inside f, but NOT the call to f inside g, because f
did not explicitly request a CallStack.
Important Details:
- GHC should NEVER report an insoluble CallStack constraint.
- A CallStack (defined in GHC.Stack) is a [(String, SrcLoc)], where the String
is the name of the binder that is used at the SrcLoc. SrcLoc is defined in
GHC.SrcLoc and contains the package/module/file name, as well as the full
source-span. Both CallStack and SrcLoc are kept abstract so only GHC can
construct new values.
- Consider the use of ?stk in:
head :: (?stk :: CallStack) => [a] -> a
head [] = error (show ?stk)
When solving the use of ?stk we'll have a given
[G] d :: IP "stk" CallStack
in scope. In the interaction phase, GHC would normally solve the use of ?stk
directly from the given, i.e. re-using the dicionary. But this is NOT what we
want! We want to generate a *new* CallStack with ?loc's SrcLoc pushed onto
the given CallStack. So we must take care in TcInteract.interactDict to
prioritize solving wanted CallStacks.
- We will automatically solve any wanted CallStack regardless of the name of the
IP, i.e.
f = show (?stk :: CallStack)
g = show (?loc :: CallStack)
are both valid. However, we will only push new SrcLocs onto existing
CallStacks when the IP names match, e.g. in
head :: (?loc :: CallStack) => [a] -> a
head [] = error (show (?stk :: CallStack))
the printed CallStack will NOT include head's call-site. This reflects the
standard scoping rules of implicit-parameters. (See TcInteract.interactDict)
- An EvCallStack term desugars to a CoreExpr of type `IP "some str" CallStack`.
The desugarer will need to unwrap the IP newtype before pushing a new
call-site onto a given stack (See DsBinds.dsEvCallStack)
- We only want to intercept constraints that arose due to the use of an IP or a
function call. In particular, we do NOT want to intercept the
(?stk :: CallStack) => [a] -> a
~
(?stk :: CallStack) => [a] -> a
constraint that arises from the ambiguity check on `head`s type signature.
(See TcEvidence.isCallStackIP)
-}
mkEvCast :: EvTerm -> TcCoercion -> EvTerm
mkEvCast ev lco
| ASSERT2(tcCoercionRole lco == Representational, (vcat [ptext (sLit "Coercion of wrong role passed to mkEvCast:"), ppr ev, ppr lco]))
isTcReflCo lco = ev
| otherwise = EvCast ev lco
mkEvScSelectors :: EvTerm -> Class -> [TcType] -> [(TcPredType, EvTerm)]
mkEvScSelectors ev cls tys
= zipWith mk_pr (immSuperClasses cls tys) [0..]
where
mk_pr pred i = (pred, EvSuperClass ev i)
emptyTcEvBinds :: TcEvBinds
emptyTcEvBinds = EvBinds emptyBag
isEmptyTcEvBinds :: TcEvBinds -> Bool
isEmptyTcEvBinds (EvBinds b) = isEmptyBag b
isEmptyTcEvBinds (TcEvBinds {}) = panic "isEmptyTcEvBinds"
evTermCoercion :: EvTerm -> TcCoercion
-- Applied only to EvTerms of type (s~t)
-- See Note [Coercion evidence terms]
evTermCoercion (EvId v) = mkTcCoVarCo v
evTermCoercion (EvCoercion co) = co
evTermCoercion (EvCast tm co) = TcCastCo (evTermCoercion tm) co
evTermCoercion tm = pprPanic "evTermCoercion" (ppr tm)
evVarsOfTerm :: EvTerm -> VarSet
evVarsOfTerm (EvId v) = unitVarSet v
evVarsOfTerm (EvCoercion co) = coVarsOfTcCo co
evVarsOfTerm (EvDFunApp _ _ evs) = mkVarSet evs
evVarsOfTerm (EvSuperClass v _) = evVarsOfTerm v
evVarsOfTerm (EvCast tm co) = evVarsOfTerm tm `unionVarSet` coVarsOfTcCo co
evVarsOfTerm (EvDelayedError _ _) = emptyVarSet
evVarsOfTerm (EvLit _) = emptyVarSet
evVarsOfTerm (EvCallStack cs) = evVarsOfCallStack cs
evVarsOfTerm (EvTypeable ev) = evVarsOfTypeable ev
evVarsOfTerms :: [EvTerm] -> VarSet
evVarsOfTerms = mapUnionVarSet evVarsOfTerm
evVarsOfCallStack :: EvCallStack -> VarSet
evVarsOfCallStack cs = case cs of
EvCsEmpty -> emptyVarSet
EvCsTop _ _ tm -> evVarsOfTerm tm
EvCsPushCall _ _ tm -> evVarsOfTerm tm
evVarsOfTypeable :: EvTypeable -> VarSet
evVarsOfTypeable ev =
case ev of
EvTypeableTyCon _ _ -> emptyVarSet
EvTypeableTyApp e1 e2 -> evVarsOfTerms (map fst [e1,e2])
EvTypeableTyLit _ -> emptyVarSet
{-
************************************************************************
* *
Pretty printing
* *
************************************************************************
-}
instance Outputable HsWrapper where
ppr co_fn = pprHsWrapper (ptext (sLit "<>")) co_fn
pprHsWrapper :: SDoc -> HsWrapper -> SDoc
-- In debug mode, print the wrapper
-- otherwise just print what's inside
pprHsWrapper doc wrap
= getPprStyle (\ s -> if debugStyle s then (help (add_parens doc) wrap False) else doc)
where
help :: (Bool -> SDoc) -> HsWrapper -> Bool -> SDoc
-- True <=> appears in function application position
-- False <=> appears as body of let or lambda
help it WpHole = it
help it (WpCompose f1 f2) = help (help it f2) f1
help it (WpFun f1 f2 t1 _) = add_parens $ ptext (sLit "\\(x") <> dcolon <> ppr t1 <> ptext (sLit ").") <+>
help (\_ -> it True <+> help (\_ -> ptext (sLit "x")) f1 True) f2 False
help it (WpCast co) = add_parens $ sep [it False, nest 2 (ptext (sLit "|>")
<+> pprParendTcCo co)]
help it (WpEvApp id) = no_parens $ sep [it True, nest 2 (ppr id)]
help it (WpTyApp ty) = no_parens $ sep [it True, ptext (sLit "@") <+> pprParendType ty]
help it (WpEvLam id) = add_parens $ sep [ ptext (sLit "\\") <> pp_bndr id, it False]
help it (WpTyLam tv) = add_parens $ sep [ptext (sLit "/\\") <> pp_bndr tv, it False]
help it (WpLet binds) = add_parens $ sep [ptext (sLit "let") <+> braces (ppr binds), it False]
pp_bndr v = pprBndr LambdaBind v <> dot
add_parens, no_parens :: SDoc -> Bool -> SDoc
add_parens d True = parens d
add_parens d False = d
no_parens d _ = d
instance Outputable TcEvBinds where
ppr (TcEvBinds v) = ppr v
ppr (EvBinds bs) = ptext (sLit "EvBinds") <> braces (vcat (map ppr (bagToList bs)))
instance Outputable EvBindsVar where
ppr (EvBindsVar _ u) = ptext (sLit "EvBindsVar") <> angleBrackets (ppr u)
instance Outputable EvBind where
ppr (EvBind { eb_lhs = v, eb_rhs = e, eb_is_given = is_given })
= sep [ pp_gw <+> ppr v
, nest 2 $ equals <+> ppr e ]
where
pp_gw = brackets (if is_given then char 'G' else char 'W')
-- We cheat a bit and pretend EqVars are CoVars for the purposes of pretty printing
instance Outputable EvTerm where
ppr (EvId v) = ppr v
ppr (EvCast v co) = ppr v <+> (ptext (sLit "`cast`")) <+> pprParendTcCo co
ppr (EvCoercion co) = ptext (sLit "CO") <+> ppr co
ppr (EvSuperClass d n) = ptext (sLit "sc") <> parens (ppr (d,n))
ppr (EvDFunApp df tys ts) = ppr df <+> sep [ char '@' <> ppr tys, ppr ts ]
ppr (EvLit l) = ppr l
ppr (EvCallStack cs) = ppr cs
ppr (EvDelayedError ty msg) = ptext (sLit "error")
<+> sep [ char '@' <> ppr ty, ppr msg ]
ppr (EvTypeable ev) = ppr ev
instance Outputable EvLit where
ppr (EvNum n) = integer n
ppr (EvStr s) = text (show s)
instance Outputable EvCallStack where
ppr EvCsEmpty
= ptext (sLit "[]")
ppr (EvCsTop name loc tm)
= angleBrackets (ppr (name,loc)) <+> ptext (sLit ":") <+> ppr tm
ppr (EvCsPushCall name loc tm)
= angleBrackets (ppr (name,loc)) <+> ptext (sLit ":") <+> ppr tm
instance Outputable EvTypeable where
ppr ev =
case ev of
EvTypeableTyCon tc ks -> parens (ppr tc <+> sep (map ppr ks))
EvTypeableTyApp t1 t2 -> parens (ppr (fst t1) <+> ppr (fst t2))
EvTypeableTyLit x -> ppr x
----------------------------------------------------------------------
-- Helper functions for dealing with IP newtype-dictionaries
----------------------------------------------------------------------
-- | Create a 'Coercion' that unwraps an implicit-parameter dictionary
-- to expose the underlying value. We expect the 'Type' to have the form
-- `IP sym ty`, return a 'Coercion' `co :: IP sym ty ~ ty`.
unwrapIP :: Type -> Coercion
unwrapIP ty =
case unwrapNewTyCon_maybe tc of
Just (_,_,ax) -> mkUnbranchedAxInstCo Representational ax tys
Nothing -> pprPanic "unwrapIP" $
text "The dictionary for" <+> quotes (ppr tc)
<+> text "is not a newtype!"
where
(tc, tys) = splitTyConApp ty
-- | Create a 'Coercion' that wraps a value in an implicit-parameter
-- dictionary. See 'unwrapIP'.
wrapIP :: Type -> Coercion
wrapIP ty = mkSymCo (unwrapIP ty)
| fmthoma/ghc | compiler/typecheck/TcEvidence.hs | bsd-3-clause | 43,414 | 0 | 17 | 11,637 | 9,033 | 4,657 | 4,376 | 576 | 17 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns, NoImplicitPrelude #-}
module GHC.Event.Thread
( getSystemEventManager
, getSystemTimerManager
, ensureIOManagerIsRunning
, ioManagerCapabilitiesChanged
, threadWaitRead
, threadWaitWrite
, threadWaitReadSTM
, threadWaitWriteSTM
, closeFdWith
, threadDelay
, registerDelay
, blockedOnBadFD -- used by RTS
) where
import Control.Exception (finally, SomeException, toException)
import Control.Monad (forM, forM_, sequence_, zipWithM, when)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.List (zipWith3)
import Data.Maybe (Maybe(..))
import Data.Tuple (snd)
import Foreign.C.Error (eBADF, errnoToIOError)
import Foreign.Ptr (Ptr)
import GHC.Base
import GHC.Conc.Sync (TVar, ThreadId, ThreadStatus(..), atomically, forkIO,
labelThread, modifyMVar_, withMVar, newTVar, sharedCAF,
getNumCapabilities, threadCapability, myThreadId, forkOn,
threadStatus, writeTVar, newTVarIO, readTVar, retry,throwSTM,STM)
import GHC.IO (mask_, onException)
import GHC.IO.Exception (ioError)
import GHC.IOArray (IOArray, newIOArray, readIOArray, writeIOArray,
boundsIOArray)
import GHC.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)
import GHC.Event.Internal (eventIs, evtClose)
import GHC.Event.Manager (Event, EventManager, evtRead, evtWrite, loop,
new, registerFd, unregisterFd_)
import qualified GHC.Event.Manager as M
import qualified GHC.Event.TimerManager as TM
import GHC.Num ((-), (+))
import System.IO.Unsafe (unsafePerformIO)
import System.Posix.Types (Fd)
-- | Suspends the current thread for a given number of microseconds
-- (GHC only).
--
-- There is no guarantee that the thread will be rescheduled promptly
-- when the delay has expired, but the thread will never continue to
-- run /earlier/ than specified.
threadDelay :: Int -> IO ()
threadDelay usecs = mask_ $ do
mgr <- getSystemTimerManager
m <- newEmptyMVar
reg <- TM.registerTimeout mgr usecs (putMVar m ())
takeMVar m `onException` TM.unregisterTimeout mgr reg
-- | Set the value of returned TVar to True after a given number of
-- microseconds. The caveats associated with threadDelay also apply.
--
registerDelay :: Int -> IO (TVar Bool)
registerDelay usecs = do
t <- atomically $ newTVar False
mgr <- getSystemTimerManager
_ <- TM.registerTimeout mgr usecs . atomically $ writeTVar t True
return t
-- | Block the current thread until data is available to read from the
-- given file descriptor.
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitRead', use 'closeFdWith'.
threadWaitRead :: Fd -> IO ()
threadWaitRead = threadWait evtRead
{-# INLINE threadWaitRead #-}
-- | Block the current thread until the given file descriptor can
-- accept data to write.
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitWrite', use 'closeFdWith'.
threadWaitWrite :: Fd -> IO ()
threadWaitWrite = threadWait evtWrite
{-# INLINE threadWaitWrite #-}
-- | Close a file descriptor in a concurrency-safe way.
--
-- Any threads that are blocked on the file descriptor via
-- 'threadWaitRead' or 'threadWaitWrite' will be unblocked by having
-- IO exceptions thrown.
closeFdWith :: (Fd -> IO ()) -- ^ Action that performs the close.
-> Fd -- ^ File descriptor to close.
-> IO ()
closeFdWith close fd = do
eventManagerArray <- readIORef eventManager
let (low, high) = boundsIOArray eventManagerArray
mgrs <- forM [low..high] $ \i -> do
Just (_,!mgr) <- readIOArray eventManagerArray i
return mgr
mask_ $ do
tables <- forM mgrs $ \mgr -> takeMVar $ M.callbackTableVar mgr fd
cbApps <- zipWithM (\mgr table -> M.closeFd_ mgr table fd) mgrs tables
close fd `finally` sequence_ (zipWith3 finish mgrs tables cbApps)
where
finish mgr table cbApp = putMVar (M.callbackTableVar mgr fd) table >> cbApp
threadWait :: Event -> Fd -> IO ()
threadWait evt fd = mask_ $ do
m <- newEmptyMVar
mgr <- getSystemEventManager_
reg <- registerFd mgr (\_ e -> putMVar m e) fd evt
evt' <- takeMVar m `onException` unregisterFd_ mgr reg
if evt' `eventIs` evtClose
then ioError $ errnoToIOError "threadWait" eBADF Nothing Nothing
else return ()
-- used at least by RTS in 'select()' IO manager backend
blockedOnBadFD :: SomeException
blockedOnBadFD = toException $ errnoToIOError "awaitEvent" eBADF Nothing Nothing
threadWaitSTM :: Event -> Fd -> IO (STM (), IO ())
threadWaitSTM evt fd = mask_ $ do
m <- newTVarIO Nothing
mgr <- getSystemEventManager_
reg <- registerFd mgr (\_ e -> atomically (writeTVar m (Just e))) fd evt
let waitAction =
do mevt <- readTVar m
case mevt of
Nothing -> retry
Just evt' ->
if evt' `eventIs` evtClose
then throwSTM $ errnoToIOError "threadWaitSTM" eBADF Nothing Nothing
else return ()
return (waitAction, unregisterFd_ mgr reg >> return ())
-- | Allows a thread to use an STM action to wait for a file descriptor to be readable.
-- The STM action will retry until the file descriptor has data ready.
-- The second element of the return value pair is an IO action that can be used
-- to deregister interest in the file descriptor.
--
-- The STM action will throw an 'IOError' if the file descriptor was closed
-- while the STM action is being executed. To safely close a file descriptor
-- that has been used with 'threadWaitReadSTM', use 'closeFdWith'.
threadWaitReadSTM :: Fd -> IO (STM (), IO ())
threadWaitReadSTM = threadWaitSTM evtRead
{-# INLINE threadWaitReadSTM #-}
-- | Allows a thread to use an STM action to wait until a file descriptor can accept a write.
-- The STM action will retry while the file until the given file descriptor can accept a write.
-- The second element of the return value pair is an IO action that can be used to deregister
-- interest in the file descriptor.
--
-- The STM action will throw an 'IOError' if the file descriptor was closed
-- while the STM action is being executed. To safely close a file descriptor
-- that has been used with 'threadWaitWriteSTM', use 'closeFdWith'.
threadWaitWriteSTM :: Fd -> IO (STM (), IO ())
threadWaitWriteSTM = threadWaitSTM evtWrite
{-# INLINE threadWaitWriteSTM #-}
-- | Retrieve the system event manager for the capability on which the
-- calling thread is running.
--
-- This function always returns 'Just' the current thread's event manager
-- when using the threaded RTS and 'Nothing' otherwise.
getSystemEventManager :: IO (Maybe EventManager)
getSystemEventManager = do
t <- myThreadId
(cap, _) <- threadCapability t
eventManagerArray <- readIORef eventManager
mmgr <- readIOArray eventManagerArray cap
return $ fmap snd mmgr
getSystemEventManager_ :: IO EventManager
getSystemEventManager_ = do
Just mgr <- getSystemEventManager
return mgr
{-# INLINE getSystemEventManager_ #-}
foreign import ccall unsafe "getOrSetSystemEventThreadEventManagerStore"
getOrSetSystemEventThreadEventManagerStore :: Ptr a -> IO (Ptr a)
eventManager :: IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager = unsafePerformIO $ do
numCaps <- getNumCapabilities
eventManagerArray <- newIOArray (0, numCaps - 1) Nothing
em <- newIORef eventManagerArray
sharedCAF em getOrSetSystemEventThreadEventManagerStore
{-# NOINLINE eventManager #-}
numEnabledEventManagers :: IORef Int
numEnabledEventManagers = unsafePerformIO $ do
newIORef 0
{-# NOINLINE numEnabledEventManagers #-}
foreign import ccall unsafe "getOrSetSystemEventThreadIOManagerThreadStore"
getOrSetSystemEventThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)
-- | The ioManagerLock protects the 'eventManager' value:
-- Only one thread at a time can start or shutdown event managers.
{-# NOINLINE ioManagerLock #-}
ioManagerLock :: MVar ()
ioManagerLock = unsafePerformIO $ do
m <- newMVar ()
sharedCAF m getOrSetSystemEventThreadIOManagerThreadStore
getSystemTimerManager :: IO TM.TimerManager
getSystemTimerManager = do
Just mgr <- readIORef timerManager
return mgr
foreign import ccall unsafe "getOrSetSystemTimerThreadEventManagerStore"
getOrSetSystemTimerThreadEventManagerStore :: Ptr a -> IO (Ptr a)
timerManager :: IORef (Maybe TM.TimerManager)
timerManager = unsafePerformIO $ do
em <- newIORef Nothing
sharedCAF em getOrSetSystemTimerThreadEventManagerStore
{-# NOINLINE timerManager #-}
foreign import ccall unsafe "getOrSetSystemTimerThreadIOManagerThreadStore"
getOrSetSystemTimerThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)
{-# NOINLINE timerManagerThreadVar #-}
timerManagerThreadVar :: MVar (Maybe ThreadId)
timerManagerThreadVar = unsafePerformIO $ do
m <- newMVar Nothing
sharedCAF m getOrSetSystemTimerThreadIOManagerThreadStore
ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning
| not threaded = return ()
| otherwise = do
startIOManagerThreads
startTimerManagerThread
startIOManagerThreads :: IO ()
startIOManagerThreads =
withMVar ioManagerLock $ \_ -> do
eventManagerArray <- readIORef eventManager
let (_, high) = boundsIOArray eventManagerArray
forM_ [0..high] (startIOManagerThread eventManagerArray)
writeIORef numEnabledEventManagers (high+1)
restartPollLoop :: EventManager -> Int -> IO ThreadId
restartPollLoop mgr i = do
M.release mgr
!t <- forkOn i $ loop mgr
labelThread t "IOManager"
return t
startIOManagerThread :: IOArray Int (Maybe (ThreadId, EventManager))
-> Int
-> IO ()
startIOManagerThread eventManagerArray i = do
let create = do
!mgr <- new True
!t <- forkOn i $ loop mgr
labelThread t "IOManager"
writeIOArray eventManagerArray i (Just (t,mgr))
old <- readIOArray eventManagerArray i
case old of
Nothing -> create
Just (t,em) -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> do
-- Sanity check: if the thread has died, there is a chance
-- that event manager is still alive. This could happend during
-- the fork, for example. In this case we should clean up
-- open pipes and everything else related to the event manager.
-- See #4449
M.cleanup em
create
_other -> return ()
startTimerManagerThread :: IO ()
startTimerManagerThread = modifyMVar_ timerManagerThreadVar $ \old -> do
let create = do
!mgr <- TM.new
writeIORef timerManager $ Just mgr
!t <- forkIO $ TM.loop mgr `finally` shutdownManagers
labelThread t "TimerManager"
return $ Just t
case old of
Nothing -> create
st@(Just t) -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> do
-- Sanity check: if the thread has died, there is a chance
-- that event manager is still alive. This could happend during
-- the fork, for example. In this case we should clean up
-- open pipes and everything else related to the event manager.
-- See #4449
mem <- readIORef timerManager
_ <- case mem of
Nothing -> return ()
Just em -> TM.cleanup em
create
_other -> return st
shutdownManagers :: IO ()
shutdownManagers =
withMVar ioManagerLock $ \_ -> do
eventManagerArray <- readIORef eventManager
let (_, high) = boundsIOArray eventManagerArray
forM_ [0..high] $ \i -> do
mmgr <- readIOArray eventManagerArray i
case mmgr of
Nothing -> return ()
Just (_,mgr) -> M.shutdown mgr
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
ioManagerCapabilitiesChanged :: IO ()
ioManagerCapabilitiesChanged = do
withMVar ioManagerLock $ \_ -> do
new_n_caps <- getNumCapabilities
numEnabled <- readIORef numEnabledEventManagers
writeIORef numEnabledEventManagers new_n_caps
eventManagerArray <- readIORef eventManager
let (_, high) = boundsIOArray eventManagerArray
let old_n_caps = high + 1
if new_n_caps > old_n_caps
then do new_eventManagerArray <- newIOArray (0, new_n_caps - 1) Nothing
-- copy the existing values into the new array:
forM_ [0..high] $ \i -> do
Just (tid,mgr) <- readIOArray eventManagerArray i
if i < numEnabled
then writeIOArray new_eventManagerArray i (Just (tid,mgr))
else do tid' <- restartPollLoop mgr i
writeIOArray new_eventManagerArray i (Just (tid',mgr))
-- create new IO managers for the new caps:
forM_ [old_n_caps..new_n_caps-1] $
startIOManagerThread new_eventManagerArray
-- update the event manager array reference:
writeIORef eventManager new_eventManagerArray
else when (new_n_caps > numEnabled) $
forM_ [numEnabled..new_n_caps-1] $ \i -> do
Just (_,mgr) <- readIOArray eventManagerArray i
tid <- restartPollLoop mgr i
writeIOArray eventManagerArray i (Just (tid,mgr))
| frantisekfarka/ghc-dsi | libraries/base/GHC/Event/Thread.hs | bsd-3-clause | 13,594 | 0 | 24 | 3,074 | 2,993 | 1,528 | 1,465 | 250 | 5 |
import qualified Data.ByteString.Char8 as C
import System.Time
main = do
getClockTime
let text = "pineapple"
C.putStrLn $ C.pack text
| jwiegley/ghc-release | libraries/Cabal/cabal/tests/PackageTests/BuildDeps/SameDepsAllRound/pineapple.hs | gpl-3.0 | 147 | 0 | 9 | 32 | 46 | 24 | 22 | 6 | 1 |
{-# OPTIONS_GHC -Wall #-}
module Chapter2.LogAnalysis2 (parseMessage,
parse,
insert,
build,
inOrder,
whatWentWrong,
safeParseInt,
safeParseInt2,
verify1,
verify2,
verify3,
verify4,
verify5,
verify6,
verify7)
where
import Chapter2.Log
import Data.List (isInfixOf)
import Data.Char
import Data.Maybe (listToMaybe, fromMaybe)
import Control.Applicative
import System.FilePath.Posix
-- LogFormat
-- ^[I|W|(E Severity)] Timestamp Text$
-- exercise 1
parseMessage :: String -> LogMessage
parseMessage line = case words line of
"I" : ts : msg | isTS ts -> LogMessage Info (toTS ts) (unwords msg)
"W" : ts : msg | isTS ts -> LogMessage Warning (toTS ts) (unwords msg)
"E" : sv : ts : msg | isSeverity sv && isTS ts -> LogMessage (Error (toSeverity sv)) (toTS ts) (unwords msg)
_ -> Unknown line
parse :: String -> [LogMessage]
parse content = map parseMessage (lines content)
isNumeric :: String -> Bool
isNumeric = all isDigit
isTS :: String -> Bool
isTS = isNumeric
isSeverity :: String -> Bool
isSeverity xs = isNumeric xs && (let val = (read xs :: Int) in val >= 1 && val <= 100)
toTS :: String -> Int
toTS s = read s :: Int
toSeverity :: String -> Int
toSeverity s = read s :: Int
-- exercise 2
insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) ms = ms
insert lm Leaf = Node Leaf lm Leaf
insert (LogMessage {}) un@(Node _ (Unknown _) _) = un
insert lmi@(LogMessage _ tsi _) (Node left lme@(LogMessage _ tse _) right) =
if tsi > tse then
Node left lme (insert lmi right)
else Node (insert lmi left) lme right
-- exercise 3
build :: [LogMessage] -> MessageTree
build = foldr insert Leaf
-- exercise 4
inOrder :: MessageTree -> [LogMessage]
inOrder Leaf = []
inOrder (Node _ (Unknown _) _) = []
inOrder (Node left lm@(LogMessage {}) right) = inOrder left ++ [lm] ++ inOrder right
-- exercise 5
whatWentWrong :: [LogMessage] -> [String]
whatWentWrong = map getMessage . filter (matchingSeverity 50) . sortByTimestamp
containingWord :: String -> [LogMessage] -> [String]
containingWord w = filter (isInfixOf w) . map getMessage . sortByTimestamp
getMessage :: LogMessage -> String
getMessage (LogMessage _ _ msg) = msg
getMessage (Unknown _) = ""
sortByTimestamp :: [LogMessage] -> [LogMessage]
sortByTimestamp = inOrder . build
matchingSeverity :: Int -> LogMessage -> Bool
matchingSeverity severity (LogMessage (Error sev) _ _) | sev > severity = True
matchingSeverity _ _ = False
-- more safety functions
safeParseInt :: String -> Maybe Int
safeParseInt = listToMaybe . map fst . filter (null . snd) . reads
-- not sure if this version of safeParseInt is "clearer" as the matching and extraction happen in the match
safeParseInt2 :: String -> Maybe Int
safeParseInt2 value = case (reads value) of
[(x, "")] -> Just x
_ -> Nothing
{-# ANN safeParseMessage "HLint: ignore" #-}
safeParseMessage :: String -> LogMessage
safeParseMessage s = fromMaybe (Unknown s) $ case words s of
"I" : l : xs -> buildM (pure Info) l xs
"W" : l : xs -> buildM (pure Warning) l xs
"E" : e : l : xs -> buildM (Error <$> safeParseInt e) l xs
_ -> Nothing
where
buildM mt l xs = LogMessage <$> mt <*> safeParseInt l <*> pure (unwords xs)
{-# ANN leanerParseMessage "HLint: ignore" #-}
-- less duplication
leanerParseMessage :: String -> LogMessage
leanerParseMessage msg = case words msg of
"I" : xs -> mkMessage Info xs
"W" : xs -> mkMessage Warning xs
"E" : err : xs -> mkMessage (mkError err) xs
_ -> Unknown msg
where
mkError s = Error (read s)
mkMessage _ [] = Unknown msg
mkMessage mt (t : xs) = LogMessage mt (read t) (unwords xs)
-- verification methods
basePath :: FilePath
basePath = "src/Chapter2"
errorLog :: FilePath
errorLog = basePath </> "error.log"
sampleLog :: FilePath
sampleLog = basePath </> "sample.log"
verify1 :: LogMessage
verify1 = parseMessage "E 2 562 help help"
verify2 :: LogMessage
verify2 = parseMessage "I 29 la la la"
verify3 :: LogMessage
verify3 = parseMessage "This is not in the right format"
verify4 :: IO [LogMessage]
verify4 = testParse parse 10 (errorLog)
verify5 :: IO [String]
verify5 = testWhatWentWrong parse whatWentWrong sampleLog
verify6 :: IO [String]
verify6 = testWhatWentWrong parse whatWentWrong errorLog
verify7 :: IO [String]
verify7 = testWhatWentWrong parse (containingWord "mustard") errorLog
| ssanj/YorgeyCourse | src/Chapter2/LogAnalysis2.hs | mit | 4,787 | 0 | 13 | 1,254 | 1,558 | 806 | 752 | 110 | 5 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Document (
Tag,
Document(..),
insertDoc,
parse,
parseFile,
) where
import Data.HashMap (Map, alter)
import Data.Maybe (fromMaybe)
import Data.Time.Clock
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import Text.Blaze.Html (Html)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Text.Parsec hiding (parse)
import qualified Text.Parsec as P
import Document.Internal
type Tag = T.Text
instance Eq Html where
a == b = (renderHtml a == renderHtml b)
data Document = Document {
dTitle :: T.Text
, dSlug :: T.Text
, dDisqusId :: T.Text
, dPosted :: UTCTime
, dTags :: [ Tag ]
, dAboveFold :: Html
, dBelowFold :: Html
, dHasFold :: Bool
} deriving (Eq)
instance Show Document where
show d = T.unpack $ T.unlines $ map ($ d)
[dTitle, dSlug, above, below]
where
above = T.append "Above:\n" . render . dAboveFold
below = T.append "Below:\n" . render . dBelowFold
render = L.toStrict . renderHtml
parse :: String -> Either ParseError Document
parse = parse' ""
parseFile :: FilePath -> IO (Either ParseError Document)
parseFile path = do
contents <- readFile path
return $ parse' (show path) contents
parse' :: String -> String -> Either ParseError Document
parse' filename = P.parse document filename
where
document = do
(dTitle, mSlug, mDisqusId, dPosted, dTags) <- fields
let dSlug = if T.null mSlug
then slugify dTitle
else mSlug
dDisqusId = if T.null mDisqusId
then dSlug
else mDisqusId
dAboveFold <- try aboveFold <|> belowFold
dBelowFold <- try belowFold <|> (return "")
eof
let dHasFold = not $ L.null $ renderHtml dBelowFold
return Document {..}
type DocMap = Map T.Text [Document]
insertDoc :: Document -> DocMap -> DocMap
insertDoc d h = foldr insertMe h $ dTags d
where
insertMe tag hash = alter (\l -> Just $ d : fromMaybe [] l) tag hash
| ErinCall/bloge | src/Document.hs | mit | 2,359 | 0 | 14 | 745 | 681 | 373 | 308 | 64 | 3 |
{-# LANGUAGE RecordWildCards #-}
import Data.Set (fromList)
import Stackage.Build (build, defaultBuildSettings)
import Stackage.BuildPlan (readBuildPlan, writeBuildPlan)
import Stackage.CheckPlan (checkPlan)
import Stackage.GhcPkg (getGhcVersion)
import Stackage.Init (stackageInit)
import Stackage.Select (defaultSelectSettings, select)
import Stackage.Tarballs (makeTarballs)
import Stackage.Test (runTestSuites)
import Stackage.Types
import Stackage.Util (allowPermissive)
import System.Environment (getArgs, getProgName)
import System.IO (hFlush, stdout)
data SelectArgs = SelectArgs
{ excluded :: [String]
, noPlatform :: Bool
, onlyPermissive :: Bool
, allowed :: [String]
, buildPlanDest :: FilePath
, globalDB :: Bool
}
parseSelectArgs :: [String] -> IO SelectArgs
parseSelectArgs =
loop SelectArgs
{ excluded = []
, noPlatform = False
, onlyPermissive = False
, allowed = []
, buildPlanDest = defaultBuildPlan
, globalDB = False
}
where
loop x [] = return x
loop x ("--exclude":y:rest) = loop x { excluded = y : excluded x } rest
loop x ("--no-platform":rest) = loop x { noPlatform = True } rest
loop x ("--only-permissive":rest) = loop x { onlyPermissive = True } rest
loop x ("--allow":y:rest) = loop x { allowed = y : allowed x } rest
loop x ("--build-plan":y:rest) = loop x { buildPlanDest = y } rest
loop x ("--use-global-db":rest) = loop x { globalDB = True } rest
loop _ (y:_) = error $ "Did not understand argument: " ++ y
data BuildArgs = BuildArgs
{ sandbox :: String
, buildPlanSrc :: FilePath
, extraArgs' :: [String] -> [String]
, noDocs :: Bool
, buildCores :: Maybe Int
}
parseBuildArgs :: GhcMajorVersion -> [String] -> IO BuildArgs
parseBuildArgs version =
loop BuildArgs
{ sandbox = sandboxRoot $ defaultBuildSettings Nothing version
, buildPlanSrc = defaultBuildPlan
, extraArgs' = id
, noDocs = False
, buildCores = Nothing
}
where
loop x [] = return x
loop x ("--sandbox":y:rest) = loop x { sandbox = y } rest
loop x ("--build-plan":y:rest) = loop x { buildPlanSrc = y } rest
loop x ("--arg":y:rest) = loop x { extraArgs' = extraArgs' x . (y:) } rest
loop x ("--no-docs":rest) = loop x { noDocs = True } rest
loop x ("-j":y:rest) = loop x { buildCores = Just $ read y } rest
loop _ (y:_) = error $ "Did not understand argument: " ++ y
defaultBuildPlan :: FilePath
defaultBuildPlan = "build-plan.txt"
withBuildSettings :: [String] -> (BuildSettings -> BuildPlan -> IO a) -> IO a
withBuildSettings args f = do
version <- getGhcVersion
BuildArgs {..} <- parseBuildArgs version args
bp <- readBuildPlan buildPlanSrc
let bs = defaultBuildSettings buildCores version
let settings = bs
{ sandboxRoot = sandbox
, extraArgs = extraArgs' . extraArgs bs
, buildDocs = not noDocs
}
f settings bp
main :: IO ()
main = do
args <- getArgs
case args of
"select":rest -> do
SelectArgs {..} <- parseSelectArgs rest
ghcVersion <- getGhcVersion
bp <- select
(defaultSelectSettings ghcVersion)
{ excludedPackages = fromList $ map PackageName excluded
, requireHaskellPlatform = not noPlatform
, allowedPackage =
if onlyPermissive
then allowPermissive allowed
else const $ Right ()
, useGlobalDatabase = globalDB
}
writeBuildPlan buildPlanDest bp
("check":rest) -> withBuildSettings rest checkPlan
("build":rest) -> withBuildSettings rest build
("test":rest) -> withBuildSettings rest runTestSuites
("tarballs":rest) -> withBuildSettings rest $ const makeTarballs
["init"] -> do
putStrLn "Note: init isn't really ready for prime time use."
putStrLn "Using it may make it impossible to build stackage."
putStr "Are you sure you want continue (y/n)? "
hFlush stdout
x <- getLine
case x of
c:_ | c `elem` "yY" -> stackageInit
_ -> putStrLn "Probably a good decision, exiting."
["update"] -> stackageInit >> error "FIXME update"
_ -> do
pn <- getProgName
putStrLn $ "Usage: " ++ pn ++ " <command>"
putStrLn "Available commands:"
--putStrLn " update Download updated Stackage databases. Automatically calls init."
--putStrLn " init Initialize your cabal file to use Stackage"
putStrLn " uploads"
putStrLn " select [--no-clean] [--no-platform] [--exclude package...] [--only-permissive] [--allow package] [--build-plan file]"
putStrLn " check [--build-plan file] [--sandbox rootdir] [--arg cabal-arg]"
putStrLn " build [--build-plan file] [--sandbox rootdir] [--arg cabal-arg]"
putStrLn " test [--build-plan file] [--sandbox rootdir] [--arg cabal-arg] [--no-docs]"
| sinelaw/stackage | app/stackage.hs | mit | 5,474 | 0 | 19 | 1,763 | 1,385 | 728 | 657 | 112 | 10 |
{-
Various helper operators for assertions
-}
module Codex.QuickCheck.Assertions (
testing,
(?==), (==?), (?/=), (/=?),
(?>), (?>=), (?<), (?<=),
(<?>),
absoluteEq,
relativeEq,
assertCond,
assertAbsEq,
assertRelEq
) where
import Test.QuickCheck.Property
infix 2 <?>
infix 4 ?==, ==?, ?/=, /=?, ?>, ?>=, ?<, ?<=
-- | Left argument should be equal to right one
(?==) :: (Eq a, Show a) => a -> a -> Property
x ?== y = counterexample fmt (x==y)
where fmt = "Expected:\n\t" ++ show y ++
"\nGot:\n\t" ++ show x ++ "\n"
(==?) :: (Eq a, Show a) => a -> a -> Property
(==?) = flip (?==)
-- | Left argument should not be equal to right one
(?/=) :: (Eq a, Show a) => a -> a -> Property
x ?/= y = counterexample fmt (x/=y)
where fmt = "Expected not equal to:\n\t" ++ show y ++ "\n"
(/=?) :: (Eq a, Show a) => a -> a -> Property
(/=?) = flip (?/=)
(?>) :: (Ord a, Show a) => a -> a -> Property
x ?> y = counterexample fmt (x>y)
where fmt = "Expected greater than:\n\t" ++ show y ++
"\nGot:\n\t" ++ show x ++ "\n"
(?>=):: (Ord a, Show a) => a -> a -> Property
x ?>= y = counterexample fmt (x>=y)
where fmt ="Expected greater than or equal:\n\t" ++ show y ++
"\nGot:\n\t" ++ show x ++ "\n"
(?<) :: (Ord a, Show a) => a -> a -> Property
x ?< y = counterexample fmt (x<y)
where fmt ="Expected less than:\n\t" ++ show y ++
"\nGot:\n\t" ++ show x ++ "\n"
(?<=) :: (Ord a, Show a) => a -> a -> Property
x ?<= y = counterexample fmt (x<=y)
where fmt ="Expected less than or equal:\n\t" ++ show y ++
"\nGot:\n\t" ++ show x ++ "\n"
-- | append explanatory messages in case of failure
(<?>) :: Property -> String -> Property
prop <?> info
= counterexample ("Testing " ++ info) prop
testing :: String -> Property -> Property
testing info prop
= counterexample ("Testing " ++ info ++ " with:") prop
-- | comparing floating point numbers
absoluteEq :: RealFloat a => a -> a -> a -> Bool
absoluteEq eps x y = abs (x-y) <= eps
relativeEq :: RealFloat a => a -> a -> a -> Bool
relativeEq eps x y = abs (x-y) <= max (abs x) (abs y) * eps
-- blames the second argument when a condition fails
assertCond :: Show a => (a -> a -> Bool) -> a -> a -> Property
assertCond cond answer trial = counterexample msg (cond answer trial)
where msg = "Expected:\n\t" ++ show answer ++
"\nGot:\n\t" ++ show trial ++ "\n"
assertAbsEq eps = assertCond (absoluteEq eps)
assertRelEq eps = assertCond (relativeEq eps)
| pbv/codex-quickcheck | src/Codex/QuickCheck/Assertions.hs | mit | 2,510 | 0 | 11 | 603 | 1,001 | 541 | 460 | 56 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Fields
--
-- Implements the fields command.
--
module Fields (fields) where
import Data.Csv
import Data.Vector (Vector, (!), toList)
import System.IO
import Text.Printf (printf)
import Util
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Lazy.Char8 as LC
parse :: LB.ByteString -> [LB.ByteString]
parse s =
case decode NoHeader s :: Either String (Vector (Vector LB.ByteString)) of
Right v -> toList (v ! 0)
Left _ -> [LB.empty]
guessType :: LB.ByteString -> LB.ByteString
guessType s | isInt s = "Integer"
| isFloat s = "Floating point"
| isBool s = "Boolean"
| isDate s = "Date"
| isAlpha s = "Alphanumeric"
getTypes :: BS.ByteString -> [LB.ByteString]
getTypes record = map guessType $ parse (LB.fromChunks [record])
getFields :: BS.ByteString -> BS.ByteString -> [(Int, LB.ByteString)]
getFields header record = zip fnums names
where fnames = parse $ LB.fromChunks [header]
names = if BS.null record then fnames else map append tnames
tnames = zip fnames $ getTypes record
append = (\(x, y) -> x `LB.append` ", " `LB.append` y)
fnums = [1..length names]
printFields :: [(Int, LB.ByteString)] -> IO ()
printFields field = mapM_ display field
where display (a,s) = printf "%3d) " a >> LC.putStrLn s
processFile :: Bool -> String -> IO ()
processFile types path = do
handle <- openFile path ReadMode
header <- BS.hGetLine handle
record <- if types then BS.hGetLine handle else return ""
hClose handle
putStrLn path
printFields $ getFields header record
interactive :: Bool -> IO ()
interactive types = do
header <- BS.getLine
record <- if types then BS.getLine else return ""
printFields $ getFields header record
parseCmd :: [String] -> (Bool, [String])
parseCmd [] = (False, [])
parseCmd a@(x:xs) = if x == "-t" || x == "--types" then (True, xs) else (False, a)
-- | Lists the field names from the first line.
fields :: [String] -> IO ()
fields args =
let (types, files) = parseCmd args in
if null files
then interactive types
else mapM_ (processFile types) files
| blancas/trex | src/Fields.hs | mit | 2,405 | 0 | 11 | 624 | 834 | 439 | 395 | 56 | 2 |
module Hogldev.ShadowMapFBO (
ShadowMapFBO(..)
, initializeShadowMapFBO
, bindForWriting
, bindForReading
) where
import Control.Monad (when)
import GHC.Ptr (nullPtr)
import Graphics.Rendering.OpenGL
data ShadowMapFBO = ShadowMapFBO FramebufferObject TextureObject
deriving (Show, Eq)
initializeShadowMapFBO :: GLsizei -> GLsizei -> IO ShadowMapFBO
initializeShadowMapFBO windowWidth windowHeight = do
-- Create the FBO.
fbo <- genObjectName
-- Create the depth buffer.
shadowMap <- genObjectName
textureBinding Texture2D $= Just shadowMap
texImage2D Texture2D NoProxy 0 DepthComponent' screenSize 0 pixelData
textureFilter Texture2D $= ((Linear', Nothing), Linear')
textureCompareMode Texture2D $= Nothing
textureWrapMode Texture2D S $= (Repeated, ClampToEdge)
textureWrapMode Texture2D T $= (Repeated, ClampToEdge)
bindFramebuffer Framebuffer $= fbo
framebufferTexture2D DrawFramebuffer DepthAttachment Texture2D shadowMap 0
-- Disable writes to the color buffer.
drawBuffer $= NoBuffers
readBuffer $= NoBuffers
status <- framebufferStatus Framebuffer
when (Complete /= status) $
putStrLn ("FB error, status: " ++ show status)
return (ShadowMapFBO fbo shadowMap)
where
screenSize = TextureSize2D windowWidth windowHeight
pixelData = PixelData DepthComponent Float nullPtr
bindForWriting :: ShadowMapFBO -> IO ()
bindForWriting (ShadowMapFBO fbo _) = bindFramebuffer DrawFramebuffer $= fbo
bindForReading :: ShadowMapFBO -> TextureUnit -> IO ()
bindForReading (ShadowMapFBO _ shadowMap) textureUnit = do
activeTexture $= textureUnit
textureBinding Texture2D $= Just shadowMap
| triplepointfive/hogldev | common/Hogldev/ShadowMapFBO.hs | mit | 1,700 | 0 | 11 | 309 | 423 | 209 | 214 | 36 | 1 |
module Development.Duplo.Server where
import Control.Monad.Trans (liftIO)
import Data.List (intercalate)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as LT
import Network.HTTP.Types (status200)
import Network.Wai (pathInfo)
import Network.Wai.Handler.Warp (Port)
import System.Directory (doesFileExist)
import System.Environment (getArgs)
import System.FilePath.Posix (takeExtension)
import Web.Scotty
serve :: Port -> IO ()
serve port = do
putStrLn $ "\n>> Starting server on port " ++ show port
scotty port serve'
serve' :: ScottyM ()
serve' =
-- Always match because we're checking for files, not routes
notFound $ do
path <- fmap (intercalate "/" . fmap T.unpack . pathInfo) request
-- Setting root
let path' = "public/" ++ path
exists <- liftIO $ doesFileExist path'
status status200
if exists
then normalFile path'
else returnDefault path'
normalFile :: FilePath -> ActionM ()
normalFile path = do
let contentType = guessType path
file path
setHeader "Content-Type" $ LT.pack contentType
-- | Return a default file depending on file type. Return the default HTML
-- file otherwise.
returnDefault :: FilePath -> ActionM ()
returnDefault path = do
let extension = takeExtension path
file $ case extension of
".css" -> "public/index.css"
".js" -> "public/index.js"
_ -> "public/index.html"
setHeader "Content-Type" $ case extension of
".css" -> "text/css"
".js" -> "text/javascript"
_ -> "text/html"
-- | "Guess" the content type from the path's file type
guessType :: String -> String
guessType path = case takeExtension path of
".htm" -> "text/html"
".html" -> "text/html"
".css" -> "text/css"
".js" -> "application/x-javascript"
".png" -> "image/png"
".jpeg" -> "image/jpeg"
".jpg" -> "image/jpeg"
".woff" -> "application/font-woff"
".ttf" -> "application/font-ttf"
".eot" -> "application/vnd.ms-fontobject"
".otf" -> "application/font-otf"
".svg" -> "image/svg+xml"
otherwise -> "application/octet-stream"
| pixbi/duplo | src/Development/Duplo/Server.hs | mit | 2,698 | 0 | 14 | 982 | 536 | 278 | 258 | 59 | 13 |
module Crackers.Gmail (
gmailCreds
)
where
import Crackers.Smtp
gmailCreds :: String -> String -> IO (String, Bool)
gmailCreds = creds "smtp.gmail.com"
| mom0/crackers | Crackers/Gmail.hs | mit | 159 | 0 | 8 | 28 | 46 | 26 | 20 | 5 | 1 |
import System.Random
import Control.Monad.State
rand :: IO Int
rand = getStdRandom (randomR (0, maxBound))
twoBadRandoms :: RandomGen g => g -> (Int, Int)
twoBadRandoms gen = (fst $ random gen, fst $ random gen)
twoGoodRandoms :: RandomGen g => g -> ((Int, Int), g, g, g)
twoGoodRandoms gen = let (a, gen') = random gen
(b, gen'') = random gen'
in ((a, b), gen, gen', gen'')
type RandomState a = State StdGen a
getRandom :: Random a => RandomState a
getRandom =
get >>= \gen ->
let (val, gen') = random gen in
put gen' >>
return val
getTwoRandoms :: Random a => RandomState (a, a)
getTwoRandoms = liftM2 (,) getRandom getRandom
getRandom' :: Random a => RandomState a
getRandom' = do
gen <- get
let (val, gen') = random gen
put gen'
return val
runTwoRandoms :: IO (Int, Int)
runTwoRandoms = do
oldState <- getStdGen
let (result, newState) = runState getTwoRandoms oldState
setStdGen newState
return result
data CountedRandom = CountedRandom {
crGen :: StdGen
, crCount :: Int
}
type CRState = State CountedRandom
getCountedRandom :: Random a => CRState a
getCountedRandom = do
st <- get
let (val, gen') = random (crGen st)
put CountedRandom { crGen = gen', crCount = (crCount st) + 1 }
return val
getCount :: CRState Int
getCount = crCount `liftM` get
putCount :: Int -> CRState ()
putCount a = do
st <- get
put st { crCount = a }
putCountModify :: Int -> CRState ()
putCountModify a = modify $ \st -> st { crCount = a }
| zhangjiji/real-world-haskell | ch14/Random.hs | mit | 1,526 | 0 | 12 | 363 | 630 | 325 | 305 | 49 | 1 |
module Ch24.Practice where
import Text.Trifecta
one :: Parser Char
one = char '1'
oneTwo :: Parser Char
oneTwo = one >> char '2'
oneTwoStop :: Parser ()
oneTwoStop = oneTwo >> eof
allThree :: Parser String
allThree = do
n <- (show <$> integer)
_ <- eof
return n
string' :: String -> Parser String
string' str = go str mempty
where
go (x:xs) parsed = char x >>= (\x' -> go xs (parsed ++ [x']))
go [] parsed = return parsed
main :: IO ()
main = do
print $ parseString oneTwo mempty "12"
print $ parseString oneTwoStop mempty "12"
print $ parseString oneTwoStop mempty "123"
print $ parseString allThree mempty "12"
print $ parseString allThree mempty "123"
print $ parseString (string' "hello") mempty "hello"
| andrewMacmurray/haskell-book-solutions | src/ch24/Practice.hs | mit | 749 | 0 | 13 | 167 | 300 | 146 | 154 | 25 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE QuasiQuotes #-}
module Test.GBA.Thumb.T4
(tests)
where
import Control.Applicative
import Data.Bits
import Data.Word
import Language.Literals.Binary
import Test.HUnit
import Test.QuickCheck hiding ((.&.))
import Test.QuickCheck.Modifiers
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase)
import Test.Tasty.QuickCheck (testProperty)
import Game.GBA.Monad
import Game.GBA.Register
import Game.GBA.Thumb.Execution
import Game.GBA.Thumb.Instruction
import Test.GBA.Common
tests :: TestTree
tests = testGroup "[t4] alu operations"
[ testGroup "[t4.0] parser"
[ t4parser1
, t4parser2
, t4parser3
, t4parser4
, t4parser5
, t4parser6
, t4parser7
, t4parser8
, t4parser9
, t4parser10
, t4parser11
, t4parser12
, t4parser13
, t4parser14
, t4parser15
, t4parser16
]
, testGroup "[t4.1] and"
[ t4and1a
, t4and1b
, t4and2a
, t4and2b
, t4and2c
, t4and3a
]
, testGroup "[t4.2] eor"
[ t4eor1a
, t4eor1b
, t4eor2a
, t4eor2b
, t4eor3a
]
, testGroup "[t4.3] lsl"
[
]
, testGroup "[t4.4] lsr"
[
]
, testGroup "[t4.5] asr"
[
]
, testGroup "[t4.6] adc"
[ t4adc1a
, t4adc2a
, t4adc2b
, t4adc2c
, t4adc2d
, t4adc3a
, t4adc3b
, t4adc3c
, t4adc4a
, t4adc4b
, t4adc5a
, t4adc5b
, t4adc5c
, t4adc6a
, t4adc6b
]
, testGroup "[t4.7] sbc"
[ t4sbc1a
, t4sbc2a
, t4sbc2b
, t4sbc2c
, t4sbc2d
, t4sbc2e
, t4sbc3a
, t4sbc3b
, t4sbc3c
, t4sbc3d
, t4sbc4a
, t4sbc5a
, t4sbc5b
]
, testGroup "[t4.8] ror"
[
]
, testGroup "[t4.9] tst"
[ t4tst1a
, t4tst2a
, t4tst3a
]
, testGroup "[t4.a] neg"
[ t4neg1a
, t4neg1b
, t4neg1c
, t4neg2a
, t4neg2b
, t4neg3a
, t4neg3b
, t4neg4a
, t4neg4b
, t4neg4c
, t4neg4d
, t4neg5a
, t4neg5b
, t4neg5c
]
, testGroup "[t4.b] cmp"
[ t4cmp1a
, t4cmp2a
, t4cmp2b
, t4cmp3a
, t4cmp3b
, t4cmp3c
, t4cmp4a
, t4cmp5a
, t4cmp5b
]
, testGroup "[t4.c] cmn"
[ t4cmn1a
, t4cmn2a
, t4cmn2b
, t4cmn3a
]
]
t4parser1 :: TestTree
t4parser1 = testCase "[t4parser1] and" $ parseT [b|010000 0000 010 100|]
@?= Just (T4 T4_AND [b|010|] [b|100|])
t4parser2 :: TestTree
t4parser2 = testCase "[t4parser2] eor" $ parseT [b|010000 0001 010 100|]
@?= Just (T4 T4_EOR [b|010|] [b|100|])
t4parser3 :: TestTree
t4parser3 = testCase "[t4parser3] lsl" $ parseT [b|010000 0010 010 100|]
@?= Just (T4 T4_LSL [b|010|] [b|100|])
t4parser4 :: TestTree
t4parser4 = testCase "[t4parser4] lsr" $ parseT [b|010000 0011 010 100|]
@?= Just (T4 T4_LSR [b|010|] [b|100|])
t4parser5 :: TestTree
t4parser5 = testCase "[t4parser5] asr" $ parseT [b|010000 0100 011 101|]
@?= Just (T4 T4_ASR [b|011|] [b|101|])
t4parser6 :: TestTree
t4parser6 = testCase "[t4parser6] adc" $ parseT [b|010000 0101 011 101|]
@?= Just (T4 T4_ADC [b|011|] [b|101|])
t4parser7 :: TestTree
t4parser7 = testCase "[t4parser7] sbc" $ parseT [b|010000 0110 011 101|]
@?= Just (T4 T4_SBC [b|011|] [b|101|])
t4parser8 :: TestTree
t4parser8 = testCase "[t4parser8] ror" $ parseT [b|010000 0111 011 101|]
@?= Just (T4 T4_ROR [b|011|] [b|101|])
t4parser9 :: TestTree
t4parser9 = testCase "[t4parser9] tst" $ parseT [b|010000 1000 011 101|]
@?= Just (T4 T4_TST [b|011|] [b|101|])
t4parser10 :: TestTree
t4parser10 = testCase "[t4parser10] neg" $ parseT [b|010000 1001 011 101|]
@?= Just (T4 T4_NEG [b|011|] [b|101|])
t4parser11 :: TestTree
t4parser11 = testCase "[t4parser11] sbc" $ parseT [b|010000 1010 011 101|]
@?= Just (T4 T4_CMP [b|011|] [b|101|])
t4parser12 :: TestTree
t4parser12 = testCase "[t4parser12] ror" $ parseT [b|010000 1011 011 101|]
@?= Just (T4 T4_CMN [b|011|] [b|101|])
t4parser13 :: TestTree
t4parser13 = testCase "[t4parser13] orr" $ parseT [b|010000 1100 011 101|]
@?= Just (T4 T4_ORR [b|011|] [b|101|])
t4parser14 :: TestTree
t4parser14 = testCase "[t4parser14] mul" $ parseT [b|010000 1101 011 101|]
@?= Just (T4 T4_MUL [b|011|] [b|101|])
t4parser15 :: TestTree
t4parser15 = testCase "[t4parser15] bic" $ parseT [b|010000 1110 011 101|]
@?= Just (T4 T4_BIC [b|011|] [b|101|])
t4parser16 :: TestTree
t4parser16 = testCase "[t4parser16] mvn" $ parseT [b|010000 1111 011 101|]
@?= Just (T4 T4_MVN [b|011|] [b|101|])
-- t4.1
-------
t4and1a :: TestTree
t4and1a = testProperty "[t4and1a] correctly sets register (src /= dest)" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src n1
writeSafeRegister dest n2
execute $ T4 T4_AND src dest
result <- readSafeRegister dest
return $ result == n1 .&. n2
t4and1b :: TestTree
t4and1b = testProperty "[t4and1b] correctly sets register (src == dest)" $
\(n, (ThumbRegister r)) -> runPure $ do
writeSafeRegister r n
execute $ T4 T4_AND r r
result <- readSafeRegister r
return $ result == n
t4and2a :: TestTree
t4and2a = testProperty "[t4and2a] Z flag" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src n1
writeSafeRegister dest n2
execute $ T4 T4_AND src dest
result <- readSafeRegister dest
z <- readStatus statusZ
return $ z == (result == 0)
t4and2b :: TestTree
t4and2b = testProperty "[t4and2b] Z flag set with zero src" $
\(n2, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
let n1 = 0
writeSafeRegister src n1
writeSafeRegister dest n2
execute $ T4 T4_AND src dest
result <- readSafeRegister dest
readStatus statusZ
t4and2c :: TestTree
t4and2c = testProperty "[t4and2c] Z flag set with zero dest" $
\(n1, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
let n2 = 0
writeSafeRegister src n1
writeSafeRegister dest n2
execute $ T4 T4_AND src dest
result <- readSafeRegister dest
readStatus statusZ
t4and3a :: TestTree
t4and3a = testProperty "[t3and3a] N flag" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_AND src dest
n <- readStatus statusN
return $ n == testBit (getLarge n1 .&. getLarge n2) 31
t4eor1a :: TestTree
t4eor1a = testProperty "[t4eor1a] correctly sets register (src /= dest)" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_EOR src dest
result <- readSafeRegister dest
return $ result == getLarge n1 `xor` getLarge n2
t4eor1b :: TestTree
t4eor1b = testProperty "[t4eor1b] correctly sets register (src == dest)" $
\(n, (ThumbRegister src)) -> runPure $ do
writeSafeRegister src $ getLarge n
writeSafeRegister src $ getLarge n
execute $ T4 T4_EOR src src
result <- readSafeRegister src
return $ result == 0
t4eor2a :: TestTree
t4eor2a = testProperty "[t4eor2a] Z flag, set to 1" $
\(n, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src n
writeSafeRegister dest n
execute $ T4 T4_EOR src dest
readStatus statusZ
t4eor2b :: TestTree
t4eor2b = testProperty "[t4eor2b] Z flag, set to 0" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest)) ->
src /= dest && n1 /= n2 ==> runPure $ do
writeSafeRegister src n1
writeSafeRegister dest n2
execute $ T4 T4_EOR src dest
not <$> readStatus statusZ
t4eor3a :: TestTree
t4eor3a = testProperty "[t4eor3a] N flag" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_EOR src dest
n <- readStatus statusN
return $ n == testBit (getLarge n1 `xor` getLarge n2) 31
-- t4.6
t4adc1a :: TestTree
t4adc1a = testProperty "[t4adc1a] correctly sets register (src /= dest)" $
\(n1, n2, c, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src n1
writeSafeRegister dest n2
writeStatus statusC c
execute $ T4 T4_ADC src dest
result <- readSafeRegister dest
return $ result == n1 + n2 + fromIntegral (fromEnum c)
t4adc2a :: TestTree
t4adc2a = testCase "[t4adc2a] Z flag, set to 0" $ do
z <- runTest $ do
writeSafeRegister 0 4
writeSafeRegister 1 5
writeStatus statusC True
execute $ T4 T4_ADC 0 1
result <- readSafeRegister 1
readStatus statusZ
z @?= False
t4adc2b :: TestTree
t4adc2b = testProperty "[t4adc2b] Z flag, set to 0, with no pre-carry" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest)) ->
src /= dest && n1 + n2 /= 0 ==> runPure $ do
writeSafeRegister src n1
writeSafeRegister dest n2
writeStatus statusC False
execute $ T4 T4_ADC src dest
not <$> readStatus statusZ
t4adc2c :: TestTree
t4adc2c = testProperty "[t4adc2c] Z flag, set to 1, with no pre-carry" $
\(n, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src n
writeSafeRegister dest $ maxBound - n + 1
writeStatus statusC False
execute $ T4 T4_ADC src dest
readStatus statusZ
t4adc2d :: TestTree
t4adc2d = testProperty "[t4adc2d] Z flag, set to 1, with pre-carry" $
\(n, (ThumbRegister src), (ThumbRegister dest)) -> src /= dest ==> runPure $ do
writeSafeRegister src n
writeSafeRegister dest $ maxBound - n
writeStatus statusC True
execute $ T4 T4_ADC src dest
readStatus statusZ
t4adc3a :: TestTree
t4adc3a = testCase "[t4adc3a] C flag, set to 0" $ do
c <- runTest $ do
writeSafeRegister 0 [b|11111111 11111111 11111111 11111110|]
writeSafeRegister 1 1
writeStatus statusC False
execute $ T4 T4_ADC 0 1
readStatus statusC
c @?= False
t4adc3b :: TestTree
t4adc3b = testCase "[t4adc3b] C flag, set to 1" $ do
c <- runTest $ do
writeSafeRegister 0 [b|11111111 11111111 11111111 11111110|]
writeSafeRegister 1 1
writeStatus statusC True
execute $ T4 T4_ADC 0 1
readStatus statusC
c @?= True
t4adc3c :: TestTree
t4adc3c = testProperty "[t4adc3c] C flag, set to 0 for small" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest), c) -> src /= dest ==> runPure $ do
let n1' = setBit (clearBit (getLarge n1) 31) 1 - 1
n2' = clearBit (getLarge n2) 31
writeSafeRegister src n1'
writeSafeRegister dest n2'
writeStatus statusC c
execute $ T4 T4_ADC src dest
not <$> readStatus statusC
t4adc4a :: TestTree
t4adc4a = testCase "[t4adc4a] N flag, set to 1" $ do
n <- runTest $ do
writeSafeRegister 0 [b|01111111 11111111 11111111 11111110|]
writeSafeRegister 1 1
writeStatus statusC True
execute $ T4 T4_ADC 0 1
readStatus statusN
n @?= True
t4adc4b :: TestTree
t4adc4b = testCase "[t4adc4b] N flag, set to 0" $ do
n <- runTest $ do
writeSafeRegister 0 [b|01111111 11111111 11111111 11111110|]
writeSafeRegister 1 1
writeStatus statusC False
execute $ T4 T4_ADC 0 1
readStatus statusN
n @?= False
t4adc5a :: TestTree
t4adc5a = testProperty "[t4adc5a] V flag, set to 0 for positive & negative" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest), c) -> src /= dest ==> runPure $ do
let n1' = setBit (clearBit (getLarge n1) 31) 1
n2' = clearBit (setBit (getLarge n2) 31) 1
writeSafeRegister src n1'
writeSafeRegister dest n2'
writeStatus statusC c
execute $ T4 T4_ADC src dest
not <$> readStatus statusV
t4adc5b :: TestTree
t4adc5b = testCase "[t4adc5b] V flag, set to 1" $ do
v <- runTest $ do
writeSafeRegister 0 [b|10000000 00000000 00000000 00000000|]
writeSafeRegister 1 [b|11111111 11111111 11111111 11111111|]
writeStatus statusC False
execute $ T4 T4_ADC 0 1
readStatus statusV
v @?= True
t4adc5c :: TestTree
t4adc5c = testCase "[t4adc5c] V flag, set to 0" $ do
v <- runTest $ do
writeSafeRegister 0 [b|10000000 00000000 00000000 00000000|]
writeSafeRegister 1 [b|11111111 11111111 11111111 11111111|]
writeStatus statusC True
execute $ T4 T4_ADC 0 1
readStatus statusV
v @?= False
t4adc6a :: TestTree
t4adc6a = testCase "[t4adc6a] corner case 1" $ do
r <- runTest $ do
writeSafeRegister 0 [b|10000000 00000000 00000000 00000000|]
writeSafeRegister 1 [b|11111111 11111111 11111111 11111111|]
writeStatus statusC False
execute $ T4 T4_ADC 0 1
readSafeRegister 1
r @?= [b|01111111 11111111 11111111 11111111|]
t4adc6b :: TestTree
t4adc6b = testCase "[t4adc6b] corner case 2" $ do
r <- runTest $ do
writeSafeRegister 0 [b|10000000 00000000 00000000 00000000|]
writeSafeRegister 1 [b|11111111 11111111 11111111 11111111|]
writeStatus statusC True
execute $ T4 T4_ADC 0 1
readSafeRegister 1
r @?= [b|10000000 00000000 00000000 00000000|]
-- t4.7
-------
t4sbc1a :: TestTree
t4sbc1a = testProperty "[t4sbc1a] correctly sets register" $
\(n1, n2, (ThumbRegister src), (ThumbRegister dest), c) -> src /= dest ==> runPure $ do
writeSafeRegister src (getLarge n1)
writeSafeRegister dest (getLarge n2)
writeStatus statusC c
execute $ T4 T4_SBC src dest
result <- readSafeRegister dest
return $ result == getLarge n2 - getLarge n1 - fromIntegral (fromEnum (not c))
t4sbc2a :: TestTree
t4sbc2a = testProperty "[t4sbc2a] Z flag, set to 1, carry-in" $
\(n, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src (getLarge n)
writeSafeRegister dest (getLarge n)
writeStatus statusC True
execute $ T4 T4_SBC src dest
readStatus statusZ
t4sbc2b :: TestTree
t4sbc2b = testProperty "[t4sbc2b] Z flag, set to 1, no carry-in" $
\(n, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src (getLarge n)
writeSafeRegister dest (getLarge n + 1)
writeStatus statusC False
execute $ T4 T4_SBC src dest
readStatus statusZ
t4sbc2c :: TestTree
t4sbc2c = testProperty "[t4sbc2c] Z flag, set to 0, carry-in" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n1 /= n2 ==> runPure $ do
writeSafeRegister src (getLarge n1)
writeSafeRegister dest (getLarge n2)
writeStatus statusC True
execute $ T4 T4_SBC src dest
not <$> readStatus statusZ
t4sbc2d :: TestTree
t4sbc2d = testProperty "[t4sbc2d] Z flag, set to 0, no carry-in" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n1 /= n2 + 1 && n1 /= n2 - 1 ==> runPure $ do
writeSafeRegister src (getLarge n1)
writeSafeRegister dest (getLarge n2)
writeStatus statusC False
execute $ T4 T4_SBC src dest
not <$> readStatus statusZ
t4sbc2e :: TestTree
t4sbc2e = testProperty "[t4sbc2e] Z flag, set to 0, equal, no carry-in" $
\(n, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src (getLarge n)
writeSafeRegister dest (getLarge n)
writeStatus statusC False
execute $ T4 T4_SBC src dest
not <$> readStatus statusZ
t4sbc3a :: TestTree
t4sbc3a = testCase "[t4sbc3a] C flag, set to 0" $ do
c <- runTest $ do
writeSafeRegister 0 1
writeSafeRegister 1 1
writeStatus statusC False
execute $ T4 T4_SBC 0 1
readStatus statusC
c @?= False
t4sbc3b :: TestTree
t4sbc3b = testCase "[t4sbc3b] C flag, set to 1" $ do
c <- runTest $ do
writeSafeRegister 0 1
writeSafeRegister 1 1
writeStatus statusC True
execute $ T4 T4_SBC 0 1
readStatus statusC
c @?= True
t4sbc3c :: TestTree
t4sbc3c = testCase "[t4sbc3c] C flag, set to 0, with dest = 0" $ do
c <- runTest $ do
writeSafeRegister 0 0
writeSafeRegister 1 0
writeStatus statusC False
execute $ T4 T4_SBC 0 1
readStatus statusC
c @?= False
t4sbc3d :: TestTree
t4sbc3d = testCase "[t4sbc3d] C flag, set to 1, with dest = 0" $ do
c <- runTest $ do
writeSafeRegister 0 0
writeSafeRegister 1 0
writeStatus statusC True
execute $ T4 T4_SBC 0 1
readStatus statusC
c @?= True
t4sbc4a :: TestTree
t4sbc4a = testProperty "[t4sbc4a] N flag" $
\(n1, n2, c, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src (getLarge n1)
writeSafeRegister dest (getLarge n2)
writeStatus statusC c
execute $ T4 T4_SBC src dest
res <- readSafeRegister dest
n <- readStatus statusN
return $ n == testBit res 31
t4sbc5a :: TestTree
t4sbc5a = testCase "[t4sbc5a] V flag, set to 0" $ do
v <- runTest $ do
writeSafeRegister 0 1
writeSafeRegister 1 0x80000001
writeStatus statusC True
execute $ T4 T4_SBC 0 1
readStatus statusV
v @?= False
t4sbc5b :: TestTree
t4sbc5b = testCase "[t4sbc5b] V flag, set to 1" $ do
v <- runTest $ do
writeSafeRegister 0 1
writeSafeRegister 1 0x80000001
writeStatus statusC False
execute $ T4 T4_SBC 0 1
readStatus statusV
v @?= True
t4tst1a :: TestTree
t4tst1a = testProperty "[t4tst1a] does not change register" $ do
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_TST src dest
result <- readSafeRegister dest
return $ result == getLarge n2
t4tst2a :: TestTree
t4tst2a = testProperty "[t4tst2a] Z flag" $ do
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_TST src dest
z <- readStatus statusZ
return $ z == (getLarge n1 .&. getLarge n2 == 0)
t4tst3a :: TestTree
t4tst3a = testProperty "[t4tst3a] N flag" $ do
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_TST src dest
n <- readStatus statusN
return $ n == testBit (getLarge n1 .&. getLarge n2) 31
t4neg1a :: TestTree
t4neg1a = testProperty "[t4neg1a] correctly sets register" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src n1
writeSafeRegister dest n2
execute $ T4 T4_NEG src dest
result <- readSafeRegister dest
return $ result == 0 - n1
t4neg1b :: TestTree
t4neg1b = testCase "[t4neg1b] correctly sets register, src == 0" $ do
res <- runTest $ do
writeSafeRegister 0 0
execute $ T4 T4_NEG 0 1
readSafeRegister 1
res @?= 0
t4neg1c :: TestTree
t4neg1c = testCase "[t4neg1c] correctly sets register, src == 0x80000000" $ do
res <- runTest $ do
writeSafeRegister 0 0x80000000
execute $ T4 T4_NEG 0 1
readSafeRegister 1
res @?= 0x80000000
t4neg2a :: TestTree
t4neg2a = testProperty "[t4neg2a] Z flag, src /= 0" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n1 /= 0 ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_NEG src dest
not <$> readStatus statusZ
t4neg2b :: TestTree
t4neg2b = testCase "[t4neg2b] Z flag, src == 0" $ do
z <- runTest $ do
writeSafeRegister 0 0
execute $ T4 T4_NEG 0 1
readStatus statusZ
z @?= True
t4neg3a :: TestTree
t4neg3a = testProperty "[t4neg3a] C flag, src /= 0" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n1 /= 0 ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_NEG src dest
not <$> readStatus statusC
t4neg3b :: TestTree
t4neg3b = testCase "[t4neg3b] C flag, src == 0" $ do
c <- runTest $ do
writeSafeRegister 0 0
execute $ T4 T4_NEG 0 1
readStatus statusC
c @?= True
t4neg4a :: TestTree
t4neg4a = testProperty "[t4neg4a] N flag" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_NEG src dest
n <- readStatus statusN
return $ n == testBit (0 - getLarge n1) 31
t4neg4b :: TestTree
t4neg4b = testProperty "[t4neg4b] N flag, src /= 0, src /= 0x80000000" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n1 /= 0 && n1 /= 0x80000000 ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_NEG src dest
n <- readStatus statusN
return $ n == not (testBit (getLarge n1) 31)
t4neg4c :: TestTree
t4neg4c = testCase "[t4neg4c] N flag, src == 0" $ do
n <- runTest $ do
writeSafeRegister 0 0
execute $ T4 T4_NEG 0 1
readStatus statusN
n @?= False
t4neg4d :: TestTree
t4neg4d = testCase "[t4neg4d] N flag, src == 0x80000000" $ do
n <- runTest $ do
writeSafeRegister 0 0x80000000
execute $ T4 T4_NEG 0 1
readStatus statusN
n @?= True
t4neg5a :: TestTree
t4neg5a = testProperty "[t4neg5a] V flag, src /= 0x80000000" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n1 /= 0x80000000 ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_NEG src dest
not <$> readStatus statusV
t4neg5b :: TestTree
t4neg5b = testCase "[t4neg5b] V flag, src == 0x80000000" $ do
v <- runTest $ do
writeSafeRegister 0 0x80000000
execute $ T4 T4_NEG 0 1
readStatus statusV
v @?= True
t4neg5c :: TestTree
t4neg5c = testCase "[t4neg5c] V flag, src == 0x80000001" $ do
v <- runTest $ do
writeSafeRegister 0 0x80000001
execute $ T4 T4_NEG 0 1
readStatus statusV
v @?= False
t4cmp1a :: TestTree
t4cmp1a = testProperty "[t4cmp1a] does not change register" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_CMP src dest
result <- readSafeRegister dest
return $ result == getLarge n2
t4cmp2a :: TestTree
t4cmp2a = testProperty "[t4cmp2a] Z flag, src val /= dest val" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n1 /= n2 ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_CMP src dest
not <$> readStatus statusZ
t4cmp2b :: TestTree
t4cmp2b = testProperty "[t4cmp2a] Z flag, src val == dest val" $
\(n1, ThumbRegister src, ThumbRegister dest) ->
src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n1
execute $ T4 T4_CMP src dest
readStatus statusZ
t4cmp3a :: TestTree
t4cmp3a = testProperty "[t4cmp3a] C flag, dest val > src val" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n2 > n1 ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_CMP src dest
readStatus statusC
t4cmp3b :: TestTree
t4cmp3b = testProperty "[t4cmp3b] C flag, dest val == src val" $
\(n1, ThumbRegister src, ThumbRegister dest) ->
src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n1
execute $ T4 T4_CMP src dest
readStatus statusC
t4cmp3c :: TestTree
t4cmp3c = testProperty "[t4cmp3c] C flag, dest val < src val" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n2 < n1 ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_CMP src dest
not <$> readStatus statusC
t4cmp4a :: TestTree
t4cmp4a = testProperty "[t4cmp4a] N flag" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_CMP src dest
n <- readStatus statusN
return $ n == testBit (getLarge n2 - getLarge n1) 31
t4cmp5a :: TestTree
t4cmp5a = testCase "[t4cmp5a] V flag, set to 0" $ do
v <- runTest $ do
writeSafeRegister 0 0xFFFFFFFF
writeSafeRegister 1 0x7FFFFFFE
execute $ T4 T4_CMP 0 1
readStatus statusV
v @?= False
t4cmp5b :: TestTree
t4cmp5b = testCase "[t4cmp5b] V flag, set to 1" $ do
v <- runTest $ do
writeSafeRegister 0 0xFFFFFFFE
writeSafeRegister 1 0x7FFFFFFE
execute $ T4 T4_CMP 0 1
readStatus statusV
v @?= True
t4cmn1a :: TestTree
t4cmn1a = testProperty "[t4cmn1a] does not change register" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src n1
writeSafeRegister dest n2
execute $ T4 T4_CMN src dest
result <- readSafeRegister dest
return $ result == n2
t4cmn2a :: TestTree
t4cmn2a = testProperty "[t4cmn2a] Z flag, set to 0" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) ->
src /= dest && n2 /= (-n1) ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_CMN src dest
not <$> readStatus statusZ
t4cmn2b :: TestTree
t4cmn2b = testProperty "[t4cmn2b] Z flag, set to 1" $
\(n1, ThumbRegister src, ThumbRegister dest) ->
src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ -(getLarge n1)
execute $ T4 T4_CMN src dest
readStatus statusZ
t4cmn3a :: TestTree
t4cmn3a = testProperty "[t4cmn3a] C,N,V flag" $
\(n1, n2, ThumbRegister src, ThumbRegister dest) -> src /= dest ==> runPure $ do
writeSafeRegister src $ getLarge n1
writeSafeRegister dest $ getLarge n2
execute $ T4 T4_CMN src dest
cnv <- (,,) <$> readStatus statusC <*> readStatus statusN <*> readStatus statusV
writeSafeRegister src $ -(getLarge n1)
execute $ T4 T4_CMP src dest
cnv' <- (,,) <$> readStatus statusC <*> readStatus statusN <*> readStatus statusV
return $ cnv == cnv'
| jhance/gba-hs | test/Test/GBA/Thumb/T4.hs | mit | 28,063 | 0 | 18 | 8,044 | 8,477 | 4,162 | 4,315 | 748 | 1 |
{--
- Problem 61
Count the leaves of a binary tree
A leaf is a node with no successors. Write a predicate count_leaves/2 to count them.
Example:
% count_leaves(T,N) :‐ the binary tree T has N leaves
Example in Haskell:
> countLeaves tree4
2
--}
data Tree a = Empty | Branch a (Tree a) (Tree a) deriving (Show, Eq)
tree4 = Branch 1 (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)
countLeaves :: Tree a -> Int
countLeaves Empty = 0
countLeaves (Branch _ Empty Empty) = 1
countLeaves (Branch _ l r) = countLeaves l + countLeaves r
| sighingnow/Functional-99-Problems | Haskell/61.hs | mit | 603 | 0 | 9 | 161 | 150 | 76 | 74 | 6 | 1 |
{-# htermination elem :: Int -> [Int] -> Bool #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_elem_5.hs | mit | 50 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
module Paths_jsonparser (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/home/gaurav/Documents/Programming/Haskell/jsonparser/.stack-work/install/x86_64-linux/lts-6.7/7.10.3/bin"
libdir = "/home/gaurav/Documents/Programming/Haskell/jsonparser/.stack-work/install/x86_64-linux/lts-6.7/7.10.3/lib/x86_64-linux-ghc-7.10.3/jsonparser-0.1.0.0-H3TOLW0i3agEZY8MO1lX92"
datadir = "/home/gaurav/Documents/Programming/Haskell/jsonparser/.stack-work/install/x86_64-linux/lts-6.7/7.10.3/share/x86_64-linux-ghc-7.10.3/jsonparser-0.1.0.0"
libexecdir = "/home/gaurav/Documents/Programming/Haskell/jsonparser/.stack-work/install/x86_64-linux/lts-6.7/7.10.3/libexec"
sysconfdir = "/home/gaurav/Documents/Programming/Haskell/jsonparser/.stack-work/install/x86_64-linux/lts-6.7/7.10.3/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "jsonparser_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "jsonparser_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "jsonparser_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "jsonparser_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "jsonparser_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| gitrookie/functionalcode | code/Haskell/stackjsonparser/.stack-work/dist/x86_64-linux/Cabal-1.22.5.0/build/autogen/Paths_jsonparser.hs | mit | 1,769 | 0 | 10 | 177 | 362 | 206 | 156 | 28 | 1 |
module Main where
import Data.Foldable (traverse_)
countGT :: [Int] -> [Int] -> Int
countGT xs = length . filter id . zipWith (<) xs
part1 :: [Int] -> Int
part1 = countGT <*> tail
part2 :: [Int] -> Int
part2 = countGT <*> drop 3
main :: IO ()
main = do
depths <- fmap read . lines <$> readFile "input.txt"
traverse_ (print . ($ depths)) [part1, part2]
| genos/online_problems | advent_of_code_2021/day01/Main.hs | mit | 361 | 0 | 10 | 77 | 165 | 89 | 76 | 12 | 1 |
module Language
where
import Types
recursive, nonRecursive :: IsRec
recursive = True
nonRecursive = False
rhssOf :: [(a, b)] -> [b]
rhssOf defns = [rhs | (_, rhs) <- defns]
bindersOf :: [(a, b)] -> [a]
bindersOf defns = [name | (name, _) <- defns]
isAtomicExpr :: Expr a -> Bool
isAtomicExpr (EVar _) = True
isAtomicExpr (ENum _) = True
isAtomicExpr _ = False
preludeDefs :: CoreProgram
preludeDefs = [("I", ["x"], EVar "x"),
("K", ["x", "y"], EVar "x"),
("K1", ["x", "y"], EVar "y"),
("S", ["f", "g", "x"], EAp (EAp (EVar "f") (EVar "x")) (EAp (EVar "g") (EVar "x"))),
("compose", ["f", "g", "x"], EAp (EVar "f") (EAp (EVar "g") (EVar "x"))),
("twice", ["f"], EAp (EAp (EVar "compose") (EVar "f")) (EVar "f"))]
extraPreludeDefs :: CoreProgram
extraPreludeDefs = []
-- Sample Programs
mkMultiAp :: Int -> CoreExpr -> CoreExpr -> CoreExpr
mkMultiAp n e1 e2 = foldl EAp e1 (take n e2s)
where
e2s = e2 : e2s
-- end of file
| typedvar/hLand | hcore/Language.hs | mit | 1,005 | 0 | 11 | 245 | 467 | 264 | 203 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module LLVM.Examples.Structs (structs) where
import qualified LLVM.General.AST as AST
import Control.Monad
import Control.Lens ((.=))
import LLVM.Gen
import LLVM.General.AST.Type (double)
import LLVM.General.AST.AddrSpace (AddrSpace(..))
import qualified LLVM.General.AST.Type as T
{-
## Errors encountered
- Invalid GetElementPtrInst indices for type
-}
structs :: AST.Module
structs = mapLLVM . runLLVM defaultModule $ do
moduleName .= "Structs"
let pointT = T.StructureType True [T.i32, T.i32]
let pointTPtr = T.PointerType pointT (AddrSpace 0)
-- | Creates a stuct of type `{ i32, i32 }` and stores `54`
-- in the first indice and stores `34` in the second indice
defn double "main" [] $ do
myPoint <- alloca pointT 8
x <- getElemPtr' pointTPtr myPoint [i32 0, i32 0]
y <- getElemPtr' pointTPtr myPoint [i32 0, i32 1]
store T.i32 4 (i32 54) x
store T.i32 4 (i32 34) y
ret (i32 0)
| AKST/scheme.llvm | src/LLVM/Examples/Structs.hs | mit | 978 | 0 | 14 | 199 | 295 | 157 | 138 | 21 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Rendering Graphviz code from Haphviz graphs
module Text.Dot.Render (
renderGraph
, renderToFile
, renderToStdOut
) where
import Control.Monad (unless)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Control.Monad.Identity (Identity (..))
import Control.Monad.Reader (ReaderT, ask, runReaderT)
import Control.Monad.State (StateT, execStateT, get, modify)
import Control.Monad.Writer (WriterT, execWriterT, tell)
import Text.Dot.Types.Internal
type Render = ReaderT GraphType (StateT Int (WriterT Text Identity))
-- | Render a given graph and write the result to the given file
renderToFile :: FilePath -> DotGraph -> IO ()
renderToFile file g = T.writeFile file $ renderGraph g
-- | Render a given graph and print it to std out
renderToStdOut :: DotGraph -> IO ()
renderToStdOut = T.putStrLn . renderGraph
-- | Render a graph to graphviz code
renderGraph :: DotGraph -> Text
renderGraph (Graph gtype name content) = mconcat
[ case gtype of
DirectedGraph -> "digraph"
UndirectedGraph -> "graph"
, " "
, name
, " "
, "{"
, "\n"
, runIdentity $ execWriterT $ execStateT (runReaderT (renderDot content) gtype) 1
, "}"
]
renderDot :: Dot -> Render ()
renderDot (Node nid ats) = do
indent
renderId nid
renderAttributes ats
finishCommand
newline
renderDot (Edge from to ats) = do
indent
renderId from
tell " "
t <- ask
tell $ case t of
UndirectedGraph -> "--"
DirectedGraph -> "->"
tell " "
renderId to
renderAttributes ats
finishCommand
newline
renderDot (Declaration t ats) = do
indent
renderDecType t
renderAttributes ats
finishCommand
newline
renderDot (Subgraph name content) = do
indent
tell "subgraph"
tell " "
tell name
tell " "
tell "{"
newline
indented $ renderDot content
indent
tell "}"
newline
renderDot (RawDot t) = tell t
renderDot (Rankdir t) = do
indent
tell "rankdir"
tell " = "
renderRankDirType t
finishCommand
newline
renderDot (Label t) = do
indent
tell "label"
tell " = "
tell $ quoted t
finishCommand
newline
renderDot (Ranksame d) = do
indent
braced $ do
tell " rank=same"
newline
indented $ renderDot d
indent
newline
renderDot (DotSeq d1 d2) = do
renderDot d1
renderDot d2
renderDot DotEmpty = return ()
renderAttributes :: [Attribute] -> Render ()
renderAttributes ats = unless (null ats) $ do
tell " "
tell "["
commaSeparated $ map renderAttribute ats
tell "]"
where
commaSeparated [] = return ()
commaSeparated [r] = r
commaSeparated (r:rs) = do
r
tell ", "
commaSeparated rs
renderAttribute :: Attribute -> Render ()
renderAttribute (name, value) = do
tell name
tell "="
tell $ quoteHtml value
renderId :: NodeId -> Render ()
renderId (Nameless i) = tell $ T.pack $ show i
renderId (UserId t) = tell $ quoted t
renderDecType :: DecType -> Render ()
renderDecType DecGraph = tell "graph"
renderDecType DecNode = tell "node"
renderDecType DecEdge = tell "edge"
renderRankDirType :: RankdirType -> Render ()
renderRankDirType TB = tell "TB"
renderRankDirType BT = tell "BT"
renderRankDirType RL = tell "RL"
renderRankDirType LR = tell "LR"
newline :: Render ()
newline = tell "\n"
finishCommand :: Render ()
finishCommand = tell ";"
braced :: Render () -> Render ()
braced content = do
tell "{"
content
tell "}"
indent :: Render ()
indent = do
level <- get
tell $ T.pack $ replicate (level * 2) ' '
indented :: Render () -> Render ()
indented func = do
modify ((+) 1)
func
modify (flip (-) 1)
-- | Text processing utilities
quoted :: Text -> Text
quoted t = if needsQuoting t then "\"" <> t <> "\"" else t
quoteHtml :: Text -> Text
quoteHtml t = "<" <> t <> ">"
needsQuoting :: Text -> Bool
needsQuoting = T.any (== ' ')
| NorfairKing/haphviz | src/Text/Dot/Render.hs | mit | 4,235 | 0 | 12 | 1,192 | 1,385 | 667 | 718 | 150 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Lexer
(
lexer
) where
import Core
import Lexer.Literal
import Lexer.Type
lexer :: SpecWith ()
lexer = describe "Lexer" $ do
testDecimalLiteral
testOctalLiteral
testHexLiteral
testIntLiteral
testFloatLiteral
testEscapeCode
testRuneLiteral
testRawString
testInterpretedString
testIdentifier
testType | djeik/goto | test/Lexer.hs | mit | 389 | 0 | 7 | 86 | 78 | 37 | 41 | 20 | 1 |
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, CPP #-}
{-|
Module : Madl.Islands
Description : Extract transfer islands from a madl network.
Copyright : (c) Sanne Wouda 2015-2016, Tessa Belder 2015-2016
Provides a data type for transfer islands. Provides a function to extract these islands from a madl network.
-}
module Madl.Islands (Island(..), IslandSet, transferIslands, condition, dataPropagation
#ifdef TESTING
-- * Tests
, Madl.Islands.unitTests
#endif
) where
import qualified Data.IntMap as IM
import qualified Data.Map as M
import Data.Foldable (foldl')
import Data.List (intersect, elemIndex)
import Data.Maybe (mapMaybe,maybeToList,catMaybes,isNothing,fromMaybe)
import Utils.Map
import Utils.Text
import Madl.Network
import Madl.MsgTypes
#ifdef TESTING
import Test.HUnit
import Madl.Identifiers
#endif
-- import Debug.Trace
-- Error function
fileName :: Text
fileName = "Madl.Islands"
fatal :: Int -> String -> a
fatal i s = error ("Fatal "++show i++" in " ++utxt fileName ++":\n "++ s)
src :: Int -> (Text, Int)
src i = (fileName, i)
_okWhenNotUsed :: a
_okWhenNotUsed = undefined fatal src
-- End of error function
-- | An island with channels of type @a@ and transitions of automata
data Island a = Island
{ islandChannels :: Map ChannelID a,
islandTransitions :: Map ComponentID (AutomatonTransition, Int)
} deriving (Eq, Show)
-- | A set of islands with channels of type @a@
type IslandSet a = IntMap (Island a)
newKey :: IslandSet a -> Int
newKey is = if IM.null is then 0 else 1 + fst (IM.findMax is)
filterWithChannel :: ChannelID -> IslandSet a -> IslandSet a
filterWithChannel c = IM.filter (islandHasChannel c)
islandHasChannel :: forall a. ChannelID -> Island a -> Bool
islandHasChannel c = M.member c . islandChannels
type LNode a b = (a,b)
-- | Extract the set of transfer islands from a madl network.
transferIslands :: forall b. Show b => Network Component b -> IslandSet b
transferIslands g = {-# SCC "BuildTransferIslands" #-} foldl' (flip f) s $ transferOrder g where
f :: ComponentID -> IslandSet b -> IslandSet b
f n is =
-- if checkIslands g is' then
is'
-- else fatal 78 (show l)
where
is' = updateIslands n l (getInChannels g n) (outChannels n) is
l = getComponent g n
s = IM.empty
outChannels :: ComponentID -> [LNode ChannelID b]
outChannels n = map labelChannel (getOutChannels g n)
labelChannel :: ChannelID -> LNode ChannelID b
labelChannel node = (node, getChannel g node)
_checkIslands :: forall a t b . (Show t, Show a) => Network (XComponent t) b -> IslandSet a -> Bool
_checkIslands net isles = IM.null $ IM.filter illegal isles where
illegal :: Island a -> Bool
illegal (isle@Island{islandChannels=xs}) = res where
res = any (invalidChannel isle . fst) $ M.toList xs
invalidChannel :: Island a -> ChannelID -> Bool
invalidChannel (Island{islandTransitions=ts}) xID = let cID = getInitiator net xID in case getComponent net cID of
Automaton{} -> isNothing ph where
_idx :: Int
(AutomatonT{phi=ph}, _idx) = lookupM (src 92) cID ts
_ -> False
type Transition a = ([ChannelID], Maybe (ComponentID, (AutomatonTransition, Int)), [(ChannelID, a)])
maybeAddTrans :: Maybe (ComponentID, (AutomatonTransition, Int)) -> Island a -> Island a
maybeAddTrans (Just p) = addTrans p
maybeAddTrans Nothing = id
updateIslands' :: forall a. Show a => [Transition a] -> IslandSet a -> IslandSet a
-- ts transition list
-- isles: current island set
-- return updated island set
updateIslands' ts isles = if valid isles then foldr f non_con ts else fatal 113 ("inputs without islands: " ++ show all_is) where
-- initial island set is non-con (non relevant islands)
--
f :: Transition a -> IslandSet a -> IslandSet a
f (is, trans, os) isles' = IM.union new isles' where
-- con = connected islands (from split on list) one island per input channel (see 120)
-- combine first
-- extend adds output channels to all islands and possibly transitions
new = (extend . combine) con
extend = IM.map (addChannels os . maybeAddTrans trans)
combine = foldr (cartProd isles') identity
identity = IM.singleton (newKey isles') $ Island M.empty M.empty
(con,_) = splitOnList is isles
all_is = concat [is | (is, _, _) <- ts]
-- list of all inputs from the transitions
non_con = IM.filter (\Island{islandChannels=xs} -> all (\c -> M.notMember c xs) all_is) isles
-- from isles, select irrelevant islands for the set of transitions
valid = all (not . IM.null) . fst . splitOnList all_is
-- valid check that islands have at least one channel
updateIslands :: forall a .Show a => ComponentID -> Component -> [ChannelID] -> [(ChannelID, a)] -> IslandSet a -> IslandSet a
updateIslands _ Sink{} [i] [] isles =
updateIslands' [([i], Nothing, [])] isles
updateIslands _ DeadSink{} [_] [] isles = isles
updateIslands _ Source{} [] [o] islands =
updateIslands' [([], Nothing, [o])] islands
updateIslands _ PatientSource{} [] [o] islands =
updateIslands' [([], Nothing, [o])] islands
updateIslands _ Queue{} _ [o] islands =
updateIslands' [([], Nothing, [o])] islands
updateIslands _ Vars{} [i] [o] islands =
updateIslands' [([i], Nothing, [o])] islands
updateIslands _ Function{} [i] [o] islands =
updateIslands' [([i], Nothing, [o])] islands
updateIslands _ Fork{} [i] os islands =
updateIslands' [([i], Nothing, os)] islands
updateIslands _ ControlJoin{} is [o] islands =
updateIslands' [(is, Nothing, [o])] islands
updateIslands _ FControlJoin{} is [o] islands =
updateIslands' [(is, Nothing, [o])] islands
updateIslands _ Switch{} [i] os islands = updateIslands' ts islands where
ts = map (\o -> ([i], Nothing, [o])) os
updateIslands _ Merge{} is [o] islands = updateIslands' ts islands where
ts = map (\i -> ([i], Nothing, [o])) is
updateIslands _ (Match{}) (m:i:[]) (t:f:[]) isles = updateIslands' ts isles where
ts = [([i,m], Nothing, [t]), ([i], Nothing, [f])]
updateIslands _ MultiMatch{} is os isles = updateIslands' ts isles where
ts = [([m,d], Nothing, [o]) | (m, o) <- zip ms os, d <- ds]
(ms, ds) = splitAt (length os) is
updateIslands _ LoadBalancer{} [i] os isles = updateIslands' ts isles where
ts = map (\o -> ([i], Nothing, [o])) os
updateIslands _ Joitch{} (in1:in2:[]) os isles = updateIslands' ts isles where
ts = map (\(o1,o2) -> ([in1,in2], Nothing, [o1,o2])) $ pairs os
pairs [] = []
pairs [_] = fatal 104 "Illegal network"
pairs (c1:c2:cs) = (c1, c2) : pairs cs
updateIslands cID Automaton{transitions=ts} is os isles = updateIslands' groups isles where
groups :: [Transition a]
groups = map at2t (zip ts [0..])
at2t :: (AutomatonTransition, Int) -> Transition a
at2t (t@AutomatonT{inPort=i,outPort=maybeO}, idx) =
(map (findX 162 is) [i], Just (cID, (t, idx)), map (findX 163 os) (maybeToList maybeO))
findX :: Show b => Int -> [b] -> Int -> b
findX i ps = flip (lookupM (src i)) ps
updateIslands _ c@Match{} _ _ _ = fatal 95 ("invalid network; component: " ++ show c)
updateIslands _ c@Sink{} _ _ _ = fatal 60 ("invalid network; component: " ++ show c)
updateIslands _ c@DeadSink{} _ _ _ = fatal 62 ("invalid network; component: " ++ show c)
updateIslands _ c@Source{} _ _ _ = fatal 64 ("invalid network; component: " ++ show c)
updateIslands _ c@PatientSource{} _ _ _ = fatal 66 ("invalid network; component: " ++ show c)
updateIslands _ c@Queue{} _ _ _ = fatal 68 ("invalid network; component: " ++ show c)
updateIslands _ c@Vars{} _ _ _ = fatal 114 ("invalid network; component: " ++ show c)
updateIslands _ c@Function{} _ _ _ = fatal 70 ("invalid network; component: " ++ show c)
updateIslands _ c@Fork{} _ _ _ = fatal 72 ("invalid network; component: " ++ show c)
updateIslands _ c@ControlJoin{} _ _ _ = fatal 80 ("invalid network; component: " ++ show c)
updateIslands _ c@FControlJoin{} _ _ _ = fatal 109 ("invalid network; component: " ++ show c)
updateIslands _ c@Switch{} _ _ _ = fatal 86 ("invalid network; component: " ++ show c)
updateIslands _ c@Merge{} _ _ _ = fatal 92 ("invalid network; component: " ++ show c)
updateIslands _ c@LoadBalancer{} _ _ _ = fatal 102 ("invalid network; component: " ++ show c)
updateIslands _ c@Joitch{} _ _ _ = fatal 120 ("invalid network; component: " ++ show c)
cartProd :: IslandSet a -> IslandSet a -> IslandSet a -> IslandSet a
-- islands: ilsands until now
-- compute product between as and bs
cartProd islands as bs =
IM.fromList (zip [newKey islands..] $ catMaybes
[ if M.null (M.intersection ts ts')
-- ts and ts' are automaton transitions
-- check intersection between (process) transitions part of the two islands
-- if intersection is empty, return Just and compute union (merge islands)
-- if intersection not empty, return Nothing and islands not mergeable.
-- note that intersection is computed using process ID only.
-- ts and ts' are maps where the key is the component ID
-- this will not work if processes can write (or read) to more than one channel
-- on a transition.
then Just $ Island (M.union xs xs') (M.union ts ts')
else Nothing |
(_, Island xs ts) <- IM.toList as,
(_, Island xs' ts') <- IM.toList bs
])
splitOnList :: forall a . Show a => [ChannelID] -> IslandSet a -> ([IslandSet a], IslandSet a)
splitOnList cs is = (islandsByInput, otherIslands) where
-- cs = list of channel ID's (should be an xs)
-- is = island set
-- compute islands relevant to the channels. (example: input channels of a join)
islandsByInput :: [IslandSet a]
islandsByInput = map (flip filterWithChannel is) cs
-- for each channel is cs, returns the set of islands with this channel.
-- otherIslands is the complement, islands without the channel.
otherIslands = IM.difference is (foldr IM.union IM.empty islandsByInput)
addChannels :: [(ChannelID, a)] -> Island a -> Island a
addChannels cs island = foldr addChannel island cs
addChannel :: (ChannelID, a) -> Island a -> Island a
addChannel (xID, x) isle@Island{islandChannels=xs} =
isle{islandChannels = M.insert xID x xs}
addTrans :: (ComponentID, (AutomatonTransition, Int)) -> Island a -> Island a
addTrans (cID, trans) isle@Island{islandTransitions=ts} =
isle{islandTransitions = M.insertWith (fatal 219 "transition exists") cID trans ts}
-- | Produces an 'MFunctionDisj' which evaluates to the data type of the channel identified by the given channelID.
dataPropagation :: (Show b, Show d) => Network (XComponent c) b -> Island d -> ChannelID -> MFunctionDisj
-- TODO(snnw): check that x is in island with islandId
dataPropagation net island x =
-- if M.member x (islandChannels island) then
dataPropagation' c
-- else fatal 211 ("illegal call to dataPropagation " ++ show x ++ " " ++ show island)
where
cID = getInitiator net x
c = getComponent net cID
forward = dataPropagation net island
is = getInChannels net cID
os = getOutChannels net cID
[i] = is
dataPropagation' :: XComponent c -> MFunctionDisj
dataPropagation' Source{} = XInput cID
dataPropagation' PatientSource{} = XInput cID
dataPropagation' Sink{} = fatal 90 "a sink cannot be an initiator"
dataPropagation' DeadSink{} = fatal 117 "a sink cannot be an initiator"
dataPropagation' Queue{} = XInput cID
dataPropagation' Vars{} = forward i
dataPropagation' Switch{} = forward i
dataPropagation' Fork{} = forward i
dataPropagation' Merge{} = forward enabledInput where
channelsInIsland = M.keys (islandChannels island)
enabledInput = case intersect channelsInIsland is of
[input] -> input
_ -> fatal 145 "Illegal island"
dataPropagation' ControlJoin{} = forward (head is)
dataPropagation' (FControlJoin _ f) = XIfThenElseD (XAppliedToB f input) input1 input2 where
input@(input1:input2:[]) = map forward is
dataPropagation' (Function _ f _) = f `XAppliedTo` input where
input = map forward is
dataPropagation' Match{} = forward (lookupM (src 164) (1::Int) is)
dataPropagation' MultiMatch{} = forward enabledDataInput where
channelsInIsland = M.keys (islandChannels island)
dataInputs = drop (getNrOutputs net cID) is
enabledDataInput = case intersect channelsInIsland dataInputs of
[input] -> input
_ -> fatal 157 "Illegal island"
dataPropagation' LoadBalancer{} = forward i
dataPropagation' Joitch{} = forward enabledInput where
[evenIn, oddIn] = getInChannels net cID
(evenOuts, oddOuts) = splitOuts os
enabledInput = if x `elem` evenOuts then evenIn else
if x `elem` oddOuts then oddIn else fatal 178 "Illegal island"
splitOuts [] = ([], [])
splitOuts [_] = fatal 176 "Illegal network"
splitOuts (c1:c2:cs) = (c1:cs', c2:cs'') where
(cs', cs'') = splitOuts cs
dataPropagation' Automaton{} =
(fromMaybe (fatal 254 "missing expected output function") (phi trans))
`XAppliedTo` inputs where
inputs = map forward is
trans :: AutomatonTransition
_idx :: Int
(trans, _idx) = lookupM (src 255) cID (islandTransitions island)
-- | Produces a list of boolean conditions which must evaluate to True in order for a transtion to take place on the given island.
condition :: (Show b, Show d) => Network (XComponent c) b -> Island d -> [MFunctionBool]
condition net island = mapMaybe getCondition (getComponentsWithID net) where
getCondition :: (ComponentID, XComponent c) -> Maybe MFunctionBool
getCondition (node, Switch _ preds) = if length xs == 0 then Nothing
else Just $ p `XAppliedToB` [dataPropagation net island x] where
outputs = zip (getOutChannels net node) preds
xs = filter ((`elem` channelsInIsland) . fst) outputs
channelsInIsland = M.keys (islandChannels island)
[(x, p)] = xs
getCondition (node, Match _ f) = case (islandHasChannel mIn island, islandHasChannel dIn island) of
(False, False) -> Nothing
(True, True) -> Just match
(False, True) -> Just $ XUnOpBool Not match
(True, False) -> fatal 174 "Illegal island"
where
match = f `XAppliedToB` [dataPropagation net island dIn, dataPropagation net island mIn]
(mIn:dIn:[]) = getInChannels net node
getCondition (node, MultiMatch _ f) = case (filter (flip islandHasChannel island) mIns, filter (flip islandHasChannel island) dIns) of
([], []) -> Nothing
([mIn], [dIn]) -> Just $ f `XAppliedToB` [dataPropagation net island dIn, dataPropagation net island mIn]
p -> fatal 182 ("Illegal island " ++ show p)
where
(mIns, dIns) = splitAt (getNrOutputs net node) $ getInChannels net node
getCondition (node, Joitch _ preds) = case map (flip elemIndex outs) $ filter (flip islandHasChannel island) outs of
[] -> Nothing
[Just x, Just y] -> if abs (x - y) /= 1 then fatal 212 "Illegal island"
else Just $ (lookupM (src 209) (x `div` 2) preds) `XAppliedToB` [dataPropagation net island evenIn, dataPropagation net island oddIn]
_ -> fatal 210 "Illegal island"
where
[evenIn, oddIn] = getInChannels net node
outs = getOutChannels net node
getCondition (node, Automaton{}) = case M.lookup node (islandTransitions island) of
Nothing -> Nothing
Just (AutomatonT{epsilon=eps}, _) -> Just $ eps `XAppliedToB` map (dataPropagation net island) ins where
ins = getInChannels net node
getCondition (_, _) = Nothing
----------------
-- Unit Tests --
----------------
#ifdef TESTING
-- | List of tests to execute
unitTests :: [Test]
unitTests = [testSourceIsland, testSourceIsland2] where
testSourceIsland = TestLabel "Source Island" $ TestCase $ (do c1; c2) where
isles :: IslandSet String
isles = updateIslands' [([], Nothing, [(ChannelIDImpl 0,"a")])] IM.empty
c1 = assertEqual "num island" 1 (IM.size isles)
c2 = assertEqual "num channels in island" 1 (M.size xs) where
[(_, Island xs _)] = IM.toList isles
testSourceIsland2 = TestLabel "Source with existing island" $ TestCase $ (do c1; c2) where
isles, isles' :: IslandSet String
isles = updateIslands' [([], Nothing, [(ChannelIDImpl 0,"a")])] IM.empty
isles' = updateIslands' [([], Nothing, [(ChannelIDImpl 1,"b")])] isles
c1 = assertEqual "num islands" 1 (IM.size isles)
c2 = assertEqual "num islands" 2 (IM.size isles')
#endif
| julienschmaltz/madl | src/Madl/Islands.hs | mit | 16,924 | 0 | 17 | 3,862 | 5,739 | 3,045 | 2,694 | 235 | 23 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLUListElement
(js_setCompact, setCompact, js_getCompact, getCompact, js_setType,
setType, js_getType, getType, HTMLUListElement,
castToHTMLUListElement, gTypeHTMLUListElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"compact\"] = $2;"
js_setCompact :: JSRef HTMLUListElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLUListElement.compact Mozilla HTMLUListElement.compact documentation>
setCompact :: (MonadIO m) => HTMLUListElement -> Bool -> m ()
setCompact self val
= liftIO (js_setCompact (unHTMLUListElement self) val)
foreign import javascript unsafe "($1[\"compact\"] ? 1 : 0)"
js_getCompact :: JSRef HTMLUListElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLUListElement.compact Mozilla HTMLUListElement.compact documentation>
getCompact :: (MonadIO m) => HTMLUListElement -> m Bool
getCompact self = liftIO (js_getCompact (unHTMLUListElement self))
foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType ::
JSRef HTMLUListElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLUListElement.type Mozilla HTMLUListElement.type documentation>
setType ::
(MonadIO m, ToJSString val) => HTMLUListElement -> val -> m ()
setType self val
= liftIO (js_setType (unHTMLUListElement self) (toJSString val))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
JSRef HTMLUListElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLUListElement.type Mozilla HTMLUListElement.type documentation>
getType ::
(MonadIO m, FromJSString result) => HTMLUListElement -> m result
getType self
= liftIO (fromJSString <$> (js_getType (unHTMLUListElement self))) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/HTMLUListElement.hs | mit | 2,642 | 28 | 11 | 351 | 640 | 374 | 266 | 40 | 1 |
{-# LANGUAGE OverloadedStrings, MultiParamTypeClasses #-}
module Data.API.Twitter.UserSearch
( UserSearchQuery(..)
, UserSearchPage(..)
) where
import Data.Text (Text, unpack)
import Data.Default (Default(..))
import Data.Aeson
import qualified Data.Vector as V
import Data.API.Twitter.Query
import Data.API.Twitter.QueryResponsePair
import Data.API.Twitter.Type
data UserSearchQuery = UserSearchQuery
{ queryText :: Text
, page :: Maybe Int
, perPage :: Maybe Int
, includeEntities :: Maybe Bool
} deriving (Show)
instance Default UserSearchQuery where
def = UserSearchQuery { queryText = ""
, page = Nothing
, perPage = Nothing
, includeEntities = Nothing
}
instance Query UserSearchQuery where
toPathSegments _ = ["users", "search.json"]
toQueryItems u = [("q", unpack $ queryText u)]
newtype UserSearchPage = UserSearchPage
{ users :: [User]
} deriving (Show)
instance FromJSON UserSearchPage where
parseJSON (Array a) = fmap (UserSearchPage . V.toList) $ V.mapM parseJSON a
instance QueryResponsePair UserSearchQuery UserSearchPage
| whittle/twitter-api | Data/API/Twitter/UserSearch.hs | mit | 1,335 | 0 | 10 | 429 | 297 | 177 | 120 | 31 | 0 |
elementAt :: [a] -> Int -> a
elementAt xs i = last $ take i xs
| tamasgal/haskell_exercises | 99questions/Problem03.hs | mit | 63 | 0 | 6 | 16 | 36 | 18 | 18 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-metricdimension.html
module Stratosphere.ResourceProperties.EMRInstanceGroupConfigMetricDimension where
import Stratosphere.ResourceImports
-- | Full data type definition for EMRInstanceGroupConfigMetricDimension. See
-- 'emrInstanceGroupConfigMetricDimension' for a more convenient
-- constructor.
data EMRInstanceGroupConfigMetricDimension =
EMRInstanceGroupConfigMetricDimension
{ _eMRInstanceGroupConfigMetricDimensionKey :: Val Text
, _eMRInstanceGroupConfigMetricDimensionValue :: Val Text
} deriving (Show, Eq)
instance ToJSON EMRInstanceGroupConfigMetricDimension where
toJSON EMRInstanceGroupConfigMetricDimension{..} =
object $
catMaybes
[ (Just . ("Key",) . toJSON) _eMRInstanceGroupConfigMetricDimensionKey
, (Just . ("Value",) . toJSON) _eMRInstanceGroupConfigMetricDimensionValue
]
-- | Constructor for 'EMRInstanceGroupConfigMetricDimension' containing
-- required fields as arguments.
emrInstanceGroupConfigMetricDimension
:: Val Text -- ^ 'emrigcmdKey'
-> Val Text -- ^ 'emrigcmdValue'
-> EMRInstanceGroupConfigMetricDimension
emrInstanceGroupConfigMetricDimension keyarg valuearg =
EMRInstanceGroupConfigMetricDimension
{ _eMRInstanceGroupConfigMetricDimensionKey = keyarg
, _eMRInstanceGroupConfigMetricDimensionValue = valuearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-metricdimension.html#cfn-elasticmapreduce-instancegroupconfig-metricdimension-key
emrigcmdKey :: Lens' EMRInstanceGroupConfigMetricDimension (Val Text)
emrigcmdKey = lens _eMRInstanceGroupConfigMetricDimensionKey (\s a -> s { _eMRInstanceGroupConfigMetricDimensionKey = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-metricdimension.html#cfn-elasticmapreduce-instancegroupconfig-metricdimension-value
emrigcmdValue :: Lens' EMRInstanceGroupConfigMetricDimension (Val Text)
emrigcmdValue = lens _eMRInstanceGroupConfigMetricDimensionValue (\s a -> s { _eMRInstanceGroupConfigMetricDimensionValue = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EMRInstanceGroupConfigMetricDimension.hs | mit | 2,347 | 0 | 13 | 221 | 266 | 152 | 114 | 29 | 1 |
{-
module SolidTexture (square_wave, triangle_wave, sine_wave,
stripe, noise, turbulence
) where -}
module Data.Glome.Texture where
import Data.Glome.Vec
import Data.Array.IArray
-- INTERPOLATION FUNCTIONS --
square_wave :: Flt -> Flt
square_wave x =
let offset = x - (fromIntegral (floor x))
in if offset < 0.5 then 0 else 1
triangle_wave :: Flt -> Flt
triangle_wave x =
let offset = x - (fromIntegral (floor x))
in if offset < 0.5
then (offset*2)
else (2-(offset*2))
sine_wave :: Flt -> Flt
sine_wave x = (sin (x*2*pi))*0.5 + 0.5
lump_wave :: Flt -> Flt
lump_wave x = 1 - x*x*x
-- SCALAR TEXTURE FUNCTIONS --
-- These are simple solid texture functions that take a
-- point as argument and return a number 0 < n < 1
stripe :: Vec -> (Flt -> Flt) -> (Vec -> Flt)
stripe axis interp =
let len = vlen axis
in
(\pos -> let offset = vdot pos axis
in interp offset)
-- PERLIN NOISE --
-- (-6 t^5 + 15 t^4 - 10t^3 +1)
-- "realistic ray tracing 2nd edition" inconsistent
-- on whether it should be t^5 or t^6,
-- but t^5 works and t^6 doesn't.
omega :: Flt -> Flt
omega t_ =
let t = fabs t_
tsqr = t*t
tcube = tsqr*t
in (-6)*tcube*tsqr + 15*tcube*t - 10*tcube + 1
-- questionably random
phi :: Array Int Int
phi = listArray (0,11) [3,0,2,7,4,1,5,11,8,10,9,6]
grad :: Array Int Vec
grad = listArray (0,11)
$ filter (\x -> let l = vlen x in l < 1.5 && l > 1.1)
[Vec x y z | x <- [(-1),0,1],
y <- [(-1),0,1],
z <- [(-1),0,1]]
gamma :: Int -> Int -> Int -> Vec
gamma i j k =
let a = phi!(mod (iabs k) 12)
b = phi!(mod (iabs (j+a)) 12)
c = phi!(mod (iabs (i+b)) 12)
in grad!c
knot :: Int -> Int -> Int -> Vec -> Flt
knot i j k v =
let Vec x y z = v
in (omega x) * (omega y) * (omega z) * (vdot (gamma i j k) v)
intGamma :: Int -> Int -> Int
intGamma i j =
let a = phi!(mod (iabs j) 16)
b = phi!(mod (iabs (i+a)) 16)
in b
turbulence :: Vec -> Int -> Flt
turbulence p 1 = fabs(noise(p))
turbulence p n =
let newp = vscale p 0.5
t = fabs (noise p)
in t + (0.5 * (turbulence newp (n-1)))
noise :: Vec -> Flt
noise (Vec x y z) =
let i = floor x
j = floor y
k = floor z
u = x-(fromIntegral i)
v = y-(fromIntegral j)
w = z-(fromIntegral k)
in knot i j k (Vec u v w) +
knot (i+1) j k (Vec (u-1) v w) +
knot i (j+1) k (Vec u (v-1) w) +
knot i j (k+1) (Vec u v (w-1)) +
knot (i+1) (j+1) k (Vec (u-1) (v-1) w) +
knot (i+1) j (k+1) (Vec (u-1) v (w-1)) +
knot i (j+1) (k+1) (Vec u (v-1) (w-1)) +
knot (i+1) (j+1) (k+1) (Vec (u-1) (v-1) (w-1))
perlin :: Vec -> Flt
perlin v =
let p = ((noise v)+1)*0.5
in if p > 1
then error $ "perlin noise error, 1 < " ++ (show p)
else if p < 0
then error $ "perlin noise error, 0 > " ++ (show p)
else p
--untested
perlin_turb :: Vec -> Int -> Flt
perlin_turb v l =
let p = turbulence v l
in if p > 1
then error $ "perlin turbulence error, 1 < " ++ (show p)
else if p < 0
then error $ "perlin turbulence error, 0 > " ++ (show p)
else p
| jimsnow/glome | GlomeVec/Data/Glome/Texture.hs | gpl-2.0 | 3,243 | 0 | 18 | 1,016 | 1,649 | 869 | 780 | 89 | 3 |
module Gt where
import Git ( Commit )
import Git.Libgit2 ( LgRepo )
type GtCommit = Commit LgRepo
| cblp/gt | Gt.hs | gpl-2.0 | 111 | 0 | 5 | 31 | 31 | 19 | 12 | 4 | 0 |
{-
Copyright (C) 2017 WATANABE Yuki <magicant@wonderwand.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -Wno-orphans #-}
module Flesh.Language.Parser.ClassSpec (spec) where
import Control.Applicative ((<|>))
import Flesh.Language.Parser.Class
import Flesh.Language.Parser.ClassTestUtil ()
import Flesh.Language.Parser.Error
import Flesh.Language.Parser.ErrorTestUtil ()
import Flesh.Language.Parser.TestUtil
import Flesh.Source.Position
import Flesh.Source.PositionTestUtil ()
import Test.Hspec (Spec, describe, parallel)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck ((===))
run :: FullInputTester a
-> PositionedString -> Either Failure (a, PositionedString)
run = runFullInputTester
spec :: Spec
spec = parallel $ do
describe "notFollowedBy" $ do
prop "succeeds if argument fails" $ \e i ->
let f = failureOfError e
in run (notFollowedBy f) i === run (return ()) i
prop "fails if argument succeeds" $ \v i ->
let _ = v :: Int
in run (notFollowedBy (return v)) i === run failure i
describe "Alternative (ParserT m) (<|>)" $ do
prop "returns hard errors intact" $ \e a i ->
let _ = a :: FullInputTester Int
f = require $ failureOfError e
in run (f <|> a) i === run f i
prop "returns success intact" $ \v a i ->
let _ = a :: FullInputTester Int
s = return v
in run (s <|> a) i === run s i
prop "recovers soft errors" $ \e a i ->
let _ = a :: FullInputTester Int
f = failureOfError e
in run (f <|> a) i === run a i
-- vim: set et sw=2 sts=2 tw=78:
| magicant/flesh | hspec-src/Flesh/Language/Parser/ClassSpec.hs | gpl-2.0 | 2,218 | 0 | 20 | 470 | 509 | 267 | 242 | 39 | 1 |
module Problem019 (answer) where
-- I could compute manually the answer in a pure fashion but this will
-- be an exercise in using the date/time facilities of haskell instead
import Data.Time.Calendar (fromGregorian)
import Data.Time.Calendar.WeekDate (toWeekDate)
answer :: Int
answer = length [1 | y <- [1901..2000], m <- [1..12], isSunday y m 1]
isSunday :: Integer -> Int -> Int -> Bool
isSunday year month day = 7 == dayOfWeek
where
calendarDay = fromGregorian year month day
dayOfWeek = third $ toWeekDate calendarDay
third (_,_,c) = c
| geekingfrog/project-euler | Problem019.hs | gpl-3.0 | 561 | 0 | 9 | 107 | 163 | 91 | 72 | 10 | 1 |
module Test.Chords where
import Data.Music.Chords
import Test.QuickCheck
import Test.Scales
instance Arbitrary Chord where
arbitrary = do
noteCount <- choose (1,12)
scale <- arbitrary
degrees <- vectorOf noteCount arbitrary
slash <- arbitrary
return $ mkChord scale degrees </> slash
-----------------------------------------------------------------------------
-- Properties for chords
-----------------------------------------------------------------------------
--
| talanis85/rechord | haScales/src/Test/Chords.hs | gpl-3.0 | 518 | 0 | 10 | 95 | 97 | 51 | 46 | 11 | 0 |
module Generator (generate)
where
import qualified Data.Matrix as M
import Field
import Dictionary
generate :: Dictionary -> Field -> [Field]
generate d f = generate' (extractAllPatterns f) d f
generate' :: [Placement] -> Dictionary -> Field -> [Field]
generate' [] d f = [f]
generate' (p:pls) d f = concat $ map (generate' pls d) fields
where
pattern = extractPattern f p
wrds = getByPattern d pattern
fields = map (emplaceWord f p) wrds
| IUdalov/crossword-sketch | src/Generator.hs | gpl-3.0 | 471 | 0 | 9 | 106 | 178 | 96 | 82 | 12 | 1 |
module Fizz.Utils where
import Data.Time
import Data.Time.Calendar.WeekDate
import Data.Fixed
import Text.Printf
data WeekDate
= WeekDate
{ getWeekDateYear :: Integer
, getWeekDateWeek :: Int
, getWeekDateDow :: Int
} deriving(Show, Read)
data MonthDate
= MonthDate
{ getMonthDateMonth :: Int
, getMonthDateDom :: Int
} deriving(Show, Read)
getTime :: IO LocalTime
getTime = do
zt <- getZonedTime
return $ zonedTimeToLocalTime zt
makeTime :: Integer -> Int -> Int -> Int -> Int -> Pico -> LocalTime
makeTime year month day hour minute second
= LocalTime
(fromGregorian year month day)
(TimeOfDay hour minute second)
whiteChars :: String
whiteChars = " \n\t"
fromIntegerToDouble :: Integer -> Double
fromIntegerToDouble = fromInteger
maybeRead :: Read a => String -> Maybe a
maybeRead s =
case reads s of
((r,_):_) -> Just r
_ -> Nothing
ifxy :: Bool -> a -> a -> a
ifxy True x _ = x
ifxy _ _ y = y
between :: Ord a => a -> a -> a -> Bool
between begin end x = x >= begin && x <= end
getDom :: LocalTime -> Int
getDom = getMonthDateDom . getMonthDate
getDow :: LocalTime -> Int
getDow = getWeekDateDow . getWeekDate
getMonth :: LocalTime -> Int
getMonth = getMonthDateMonth . getMonthDate
getWeek :: LocalTime -> Int
getWeek = getWeekDateWeek . getWeekDate
getYear :: LocalTime -> Integer
getYear = getWeekDateYear . getWeekDate
getMonthDate :: LocalTime -> MonthDate
getMonthDate t =
let
(_, month, dom) = toGregorian . localDay $ t
in
MonthDate month dom
getWeekDate :: LocalTime -> WeekDate
getWeekDate t =
let
(year, week, dow) = toWeekDate . localDay $ t
in
WeekDate year week dow
getDiffTime :: LocalTime -> DiffTime
getDiffTime = timeOfDayToTime
. localTimeOfDay
isEmpty :: String -> Bool
isEmpty = (=="") . filter (not . flip elem whiteChars)
showDollars :: Double -> String
showDollars d
| d >= 0 = printf "$%.2f" d
| otherwise = printf "-$%.2f" (abs d)
| josuf107/Fizzckle | src/Fizz/Utils.hs | gpl-3.0 | 2,046 | 0 | 10 | 500 | 676 | 357 | 319 | 68 | 2 |
module ADT.Tree
( Tree(..)
, leaf
, left
, right
, height
, balanced
, preorder
, inorder
, postorder
, levelorder
, printT
) where
data Tree a = Nil | Node (Tree a) a (Tree a) deriving (Show, Eq)
empty :: Tree a -> Bool
empty Nil = True
empty _ = False
val :: Tree a -> a
val Nil = undefined
val (Node _ x _) = x
left :: Tree a -> Tree a
left Nil = undefined
left (Node l _ _) = l
right :: Tree a -> Tree a
right Nil = undefined
right (Node _ _ r) = r
children :: Tree a -> [Tree a]
children Nil = []
children (Node l _ r) = filter (not . empty) [l, r]
leaf :: a -> Tree a
leaf x = Node Nil x Nil
height :: Tree a -> Int
height Nil = -1
height (Node l _ r) = 1 + max (height l) (height r)
balanced :: Tree a -> Bool
balanced Nil = True
balanced (Node l _ r) = abs (height l - height r) <= 1 &&
balanced l &&
balanced r
preorder :: Tree a -> [a]
preorder Nil = []
preorder (Node l x r) = [x] ++ preorder l ++ preorder r
inorder :: Tree a -> [a]
inorder Nil = []
inorder (Node l x r) = inorder l ++ [x] ++ inorder r
postorder :: Tree a -> [a]
postorder Nil = []
postorder (Node l x r) = postorder l ++ postorder r ++ [x]
levelorder :: Tree a -> [a]
levelorder Nil = []
levelorder t = go [t]
where
go [] = []
go ts = map val ts ++ go (concatMap children ts)
printT :: Show a => Tree a -> IO ()
printT (Node l x r) = go "" (Node l x r)
where
go _ Nil = return ()
go padding (Node l x r) = do
putStrLn $ padding ++ show x
go (" " ++ padding) l
go (" " ++ padding) r
| zcesur/h99 | src/ADT/Tree.hs | gpl-3.0 | 1,567 | 0 | 11 | 457 | 856 | 430 | 426 | 59 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTubeAnalytics.GroupItems.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)
--
-- Removes an item from a group.
--
-- /See:/ <http://developers.google.com/youtube/analytics/ YouTube Analytics API Reference> for @youtubeAnalytics.groupItems.delete@.
module Network.Google.Resource.YouTubeAnalytics.GroupItems.Delete
(
-- * REST Resource
GroupItemsDeleteResource
-- * Creating a Request
, groupItemsDelete
, GroupItemsDelete
-- * Request Lenses
, gidOnBehalfOfContentOwner
, gidId
) where
import Network.Google.Prelude
import Network.Google.YouTubeAnalytics.Types
-- | A resource alias for @youtubeAnalytics.groupItems.delete@ method which the
-- 'GroupItemsDelete' request conforms to.
type GroupItemsDeleteResource =
"youtube" :>
"analytics" :>
"v1" :>
"groupItems" :>
QueryParam "id" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Removes an item from a group.
--
-- /See:/ 'groupItemsDelete' smart constructor.
data GroupItemsDelete = GroupItemsDelete'
{ _gidOnBehalfOfContentOwner :: !(Maybe Text)
, _gidId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'GroupItemsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gidOnBehalfOfContentOwner'
--
-- * 'gidId'
groupItemsDelete
:: Text -- ^ 'gidId'
-> GroupItemsDelete
groupItemsDelete pGidId_ =
GroupItemsDelete'
{ _gidOnBehalfOfContentOwner = Nothing
, _gidId = pGidId_
}
-- | Note: This parameter is intended exclusively for YouTube content
-- partners. The onBehalfOfContentOwner parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The CMS account that the user authenticates with must be linked
-- to the specified YouTube content owner.
gidOnBehalfOfContentOwner :: Lens' GroupItemsDelete (Maybe Text)
gidOnBehalfOfContentOwner
= lens _gidOnBehalfOfContentOwner
(\ s a -> s{_gidOnBehalfOfContentOwner = a})
-- | The id parameter specifies the YouTube group item ID for the group that
-- is being deleted.
gidId :: Lens' GroupItemsDelete Text
gidId = lens _gidId (\ s a -> s{_gidId = a})
instance GoogleRequest GroupItemsDelete where
type Rs GroupItemsDelete = ()
type Scopes GroupItemsDelete =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtubepartner"]
requestClient GroupItemsDelete'{..}
= go (Just _gidId) _gidOnBehalfOfContentOwner
(Just AltJSON)
youTubeAnalyticsService
where go
= buildClient
(Proxy :: Proxy GroupItemsDeleteResource)
mempty
| rueshyna/gogol | gogol-youtube-analytics/gen/Network/Google/Resource/YouTubeAnalytics/GroupItems/Delete.hs | mpl-2.0 | 4,021 | 0 | 14 | 888 | 409 | 248 | 161 | 63 | 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.Content.Datafeedstatuses.Custombatch
-- 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)
--
-- /See:/ <https://developers.google.com/shopping-content Content API for Shopping Reference> for @content.datafeedstatuses.custombatch@.
module Network.Google.Resource.Content.Datafeedstatuses.Custombatch
(
-- * REST Resource
DatafeedstatusesCustombatchResource
-- * Creating a Request
, datafeedstatusesCustombatch
, DatafeedstatusesCustombatch
-- * Request Lenses
, dcPayload
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.datafeedstatuses.custombatch@ method which the
-- 'DatafeedstatusesCustombatch' request conforms to.
type DatafeedstatusesCustombatchResource =
"content" :>
"v2" :>
"datafeedstatuses" :>
"batch" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] DatafeedstatusesCustomBatchRequest :>
Post '[JSON] DatafeedstatusesCustomBatchResponse
--
-- /See:/ 'datafeedstatusesCustombatch' smart constructor.
newtype DatafeedstatusesCustombatch = DatafeedstatusesCustombatch'
{ _dcPayload :: DatafeedstatusesCustomBatchRequest
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'DatafeedstatusesCustombatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dcPayload'
datafeedstatusesCustombatch
:: DatafeedstatusesCustomBatchRequest -- ^ 'dcPayload'
-> DatafeedstatusesCustombatch
datafeedstatusesCustombatch pDcPayload_ =
DatafeedstatusesCustombatch'
{ _dcPayload = pDcPayload_
}
-- | Multipart request metadata.
dcPayload :: Lens' DatafeedstatusesCustombatch DatafeedstatusesCustomBatchRequest
dcPayload
= lens _dcPayload (\ s a -> s{_dcPayload = a})
instance GoogleRequest DatafeedstatusesCustombatch
where
type Rs DatafeedstatusesCustombatch =
DatafeedstatusesCustomBatchResponse
type Scopes DatafeedstatusesCustombatch =
'["https://www.googleapis.com/auth/content"]
requestClient DatafeedstatusesCustombatch'{..}
= go (Just AltJSON) _dcPayload shoppingContentService
where go
= buildClient
(Proxy :: Proxy DatafeedstatusesCustombatchResource)
mempty
| rueshyna/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Datafeedstatuses/Custombatch.hs | mpl-2.0 | 3,131 | 0 | 13 | 651 | 305 | 186 | 119 | 51 | 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.CommentAnalyzer.Comments.Suggestscore
-- 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)
--
-- Suggest comment scores as training data.
--
-- /See:/ <https://github.com/conversationai/perspectiveapi/blob/master/README.md Perspective Comment Analyzer API Reference> for @commentanalyzer.comments.suggestscore@.
module Network.Google.Resource.CommentAnalyzer.Comments.Suggestscore
(
-- * REST Resource
CommentsSuggestscoreResource
-- * Creating a Request
, commentsSuggestscore
, CommentsSuggestscore
-- * Request Lenses
, csXgafv
, csUploadProtocol
, csAccessToken
, csUploadType
, csPayload
, csCallback
) where
import Network.Google.CommentAnalyzer.Types
import Network.Google.Prelude
-- | A resource alias for @commentanalyzer.comments.suggestscore@ method which the
-- 'CommentsSuggestscore' request conforms to.
type CommentsSuggestscoreResource =
"v1alpha1" :>
"comments:suggestscore" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SuggestCommentScoreRequest :>
Post '[JSON] SuggestCommentScoreResponse
-- | Suggest comment scores as training data.
--
-- /See:/ 'commentsSuggestscore' smart constructor.
data CommentsSuggestscore =
CommentsSuggestscore'
{ _csXgafv :: !(Maybe Xgafv)
, _csUploadProtocol :: !(Maybe Text)
, _csAccessToken :: !(Maybe Text)
, _csUploadType :: !(Maybe Text)
, _csPayload :: !SuggestCommentScoreRequest
, _csCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentsSuggestscore' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csXgafv'
--
-- * 'csUploadProtocol'
--
-- * 'csAccessToken'
--
-- * 'csUploadType'
--
-- * 'csPayload'
--
-- * 'csCallback'
commentsSuggestscore
:: SuggestCommentScoreRequest -- ^ 'csPayload'
-> CommentsSuggestscore
commentsSuggestscore pCsPayload_ =
CommentsSuggestscore'
{ _csXgafv = Nothing
, _csUploadProtocol = Nothing
, _csAccessToken = Nothing
, _csUploadType = Nothing
, _csPayload = pCsPayload_
, _csCallback = Nothing
}
-- | V1 error format.
csXgafv :: Lens' CommentsSuggestscore (Maybe Xgafv)
csXgafv = lens _csXgafv (\ s a -> s{_csXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
csUploadProtocol :: Lens' CommentsSuggestscore (Maybe Text)
csUploadProtocol
= lens _csUploadProtocol
(\ s a -> s{_csUploadProtocol = a})
-- | OAuth access token.
csAccessToken :: Lens' CommentsSuggestscore (Maybe Text)
csAccessToken
= lens _csAccessToken
(\ s a -> s{_csAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
csUploadType :: Lens' CommentsSuggestscore (Maybe Text)
csUploadType
= lens _csUploadType (\ s a -> s{_csUploadType = a})
-- | Multipart request metadata.
csPayload :: Lens' CommentsSuggestscore SuggestCommentScoreRequest
csPayload
= lens _csPayload (\ s a -> s{_csPayload = a})
-- | JSONP
csCallback :: Lens' CommentsSuggestscore (Maybe Text)
csCallback
= lens _csCallback (\ s a -> s{_csCallback = a})
instance GoogleRequest CommentsSuggestscore where
type Rs CommentsSuggestscore =
SuggestCommentScoreResponse
type Scopes CommentsSuggestscore =
'["https://www.googleapis.com/auth/userinfo.email"]
requestClient CommentsSuggestscore'{..}
= go _csXgafv _csUploadProtocol _csAccessToken
_csUploadType
_csCallback
(Just AltJSON)
_csPayload
commentAnalyzerService
where go
= buildClient
(Proxy :: Proxy CommentsSuggestscoreResource)
mempty
| brendanhay/gogol | gogol-commentanalyzer/gen/Network/Google/Resource/CommentAnalyzer/Comments/Suggestscore.hs | mpl-2.0 | 4,771 | 0 | 16 | 1,077 | 703 | 410 | 293 | 103 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.ECS.ListTasks
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns a list of tasks for a specified cluster. You can filter the results
-- by family name or by a particular container instance with the 'family' and 'containerInstance' parameters.
--
-- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListTasks.html>
module Network.AWS.ECS.ListTasks
(
-- * Request
ListTasks
-- ** Request constructor
, listTasks
-- ** Request lenses
, ltCluster
, ltContainerInstance
, ltFamily
, ltMaxResults
, ltNextToken
-- * Response
, ListTasksResponse
-- ** Response constructor
, listTasksResponse
-- ** Response lenses
, ltrNextToken
, ltrTaskArns
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.ECS.Types
import qualified GHC.Exts
data ListTasks = ListTasks
{ _ltCluster :: Maybe Text
, _ltContainerInstance :: Maybe Text
, _ltFamily :: Maybe Text
, _ltMaxResults :: Maybe Int
, _ltNextToken :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListTasks' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ltCluster' @::@ 'Maybe' 'Text'
--
-- * 'ltContainerInstance' @::@ 'Maybe' 'Text'
--
-- * 'ltFamily' @::@ 'Maybe' 'Text'
--
-- * 'ltMaxResults' @::@ 'Maybe' 'Int'
--
-- * 'ltNextToken' @::@ 'Maybe' 'Text'
--
listTasks :: ListTasks
listTasks = ListTasks
{ _ltCluster = Nothing
, _ltContainerInstance = Nothing
, _ltFamily = Nothing
, _ltNextToken = Nothing
, _ltMaxResults = Nothing
}
-- | The short name or full Amazon Resource Name (ARN) of the cluster that hosts
-- the tasks you want to list. If you do not specify a cluster, the default
-- cluster is assumed..
ltCluster :: Lens' ListTasks (Maybe Text)
ltCluster = lens _ltCluster (\s a -> s { _ltCluster = a })
-- | The container instance UUID or full Amazon Resource Name (ARN) of the
-- container instance that you want to filter the 'ListTasks' results with.
-- Specifying a 'containerInstance' will limit the results to tasks that belong to
-- that container instance.
ltContainerInstance :: Lens' ListTasks (Maybe Text)
ltContainerInstance =
lens _ltContainerInstance (\s a -> s { _ltContainerInstance = a })
-- | The name of the family that you want to filter the 'ListTasks' results with.
-- Specifying a 'family' will limit the results to tasks that belong to that
-- family.
ltFamily :: Lens' ListTasks (Maybe Text)
ltFamily = lens _ltFamily (\s a -> s { _ltFamily = a })
-- | The maximum number of task results returned by 'ListTasks' in paginated output.
-- When this parameter is used, 'ListTasks' only returns 'maxResults' results in a
-- single page along with a 'nextToken' response element. The remaining results of
-- the initial request can be seen by sending another 'ListTasks' request with the
-- returned 'nextToken' value. This value can be between 1 and 100. If this
-- parameter is not used, then 'ListTasks' returns up to 100 results and a 'nextToken' value if applicable.
ltMaxResults :: Lens' ListTasks (Maybe Int)
ltMaxResults = lens _ltMaxResults (\s a -> s { _ltMaxResults = a })
-- | The 'nextToken' value returned from a previous paginated 'ListTasks' request
-- where 'maxResults' was used and the results exceeded the value of that
-- parameter. Pagination continues from the end of the previous results that
-- returned the 'nextToken' value. This value is 'null' when there are no more
-- results to return.
ltNextToken :: Lens' ListTasks (Maybe Text)
ltNextToken = lens _ltNextToken (\s a -> s { _ltNextToken = a })
data ListTasksResponse = ListTasksResponse
{ _ltrNextToken :: Maybe Text
, _ltrTaskArns :: List "taskArns" Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListTasksResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ltrNextToken' @::@ 'Maybe' 'Text'
--
-- * 'ltrTaskArns' @::@ ['Text']
--
listTasksResponse :: ListTasksResponse
listTasksResponse = ListTasksResponse
{ _ltrTaskArns = mempty
, _ltrNextToken = Nothing
}
-- | The 'nextToken' value to include in a future 'ListTasks' request. When the
-- results of a 'ListTasks' request exceed 'maxResults', this value can be used to
-- retrieve the next page of results. This value is 'null' when there are no more
-- results to return.
ltrNextToken :: Lens' ListTasksResponse (Maybe Text)
ltrNextToken = lens _ltrNextToken (\s a -> s { _ltrNextToken = a })
-- | The list of task Amazon Resource Name (ARN) entries for the 'ListTasks' request.
ltrTaskArns :: Lens' ListTasksResponse [Text]
ltrTaskArns = lens _ltrTaskArns (\s a -> s { _ltrTaskArns = a }) . _List
instance ToPath ListTasks where
toPath = const "/"
instance ToQuery ListTasks where
toQuery = const mempty
instance ToHeaders ListTasks
instance ToJSON ListTasks where
toJSON ListTasks{..} = object
[ "cluster" .= _ltCluster
, "containerInstance" .= _ltContainerInstance
, "family" .= _ltFamily
, "nextToken" .= _ltNextToken
, "maxResults" .= _ltMaxResults
]
instance AWSRequest ListTasks where
type Sv ListTasks = ECS
type Rs ListTasks = ListTasksResponse
request = post "ListTasks"
response = jsonResponse
instance FromJSON ListTasksResponse where
parseJSON = withObject "ListTasksResponse" $ \o -> ListTasksResponse
<$> o .:? "nextToken"
<*> o .:? "taskArns" .!= mempty
| dysinger/amazonka | amazonka-ecs/gen/Network/AWS/ECS/ListTasks.hs | mpl-2.0 | 6,565 | 0 | 12 | 1,473 | 827 | 498 | 329 | 85 | 1 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE UnicodeSyntax #-}
import Data.List (tails)
pattern Three x y z ← x:y:z:_
localMaxima :: [Integer] → [Integer]
localMaxima xs = [ mid | Three left mid right ← tails xs, left < mid, mid > right ]
| spanners/cis194 | 03-rec-poly/ex2.hs | unlicense | 249 | 0 | 8 | 46 | 100 | 52 | 48 | 6 | 1 |
renderJValue :: JValue -> Doc
renderJValue (JBool True) = text "true"
renderJValue (JBool False) = text "false"
renderJValue JNull = text "null"
renderJValue (JNumber num) = double num
renderJValue (JString str) = string str
| caiorss/Functional-Programming | haskell/rwh/ch05/PrettyJSON.hs | unlicense | 235 | 0 | 7 | 44 | 89 | 42 | 47 | 6 | 1 |
module ParserSupport(range, contents) where
import Text.Parsec
import Text.Parsec.String (Parser)
import qualified Text.Parsec.Char as Ch
import Lexer
import Syntax
-- |Returns a parser that skips initial whitespace and then parses
-- the entire input, expecting @<EOF>@ when it is done parsing
contents :: Parser a -> Parser a
contents p = do
whitespace
r <- p
eof
return r
-- |Range is "[" @decimal ".." @decimal@ "]" or @decimal@, for example
-- 5 ~> Exact 5
-- [0..3] ~> Between 0 3
-- [1..0] ~> fail
range :: Parser Range
range =
between <|> exact <?> "range (n; [m..n] | n > m)"
where
between = do
Ch.char '['
lower <- int
Ch.string ".."
upper <- int
Ch.char ']'
if (lower > upper) then fail "range: lower > upper!" else return $ Between lower upper
exact = do
val <- int
return $ Exact val
| eigengo/hwsexp | core/main/ParserSupport.hs | apache-2.0 | 856 | 0 | 11 | 203 | 209 | 108 | 101 | 25 | 2 |
#!/usr/bin/env stack
{-
stack
--resolver lts-11.10
--install-ghc
runghc
--package base
--package containers
--
-hide-all-packages
-}
-- Copyright 2018 Google LLC. All Rights Reserved.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Main where
import qualified Data.Map.Strict as M
{- Syntax -}
data Expr
= Var String
| IntLit Int
| BoolLit Bool
| Plus Expr Expr
| Lt Expr Expr
deriving (Show)
data Instr
= Assign String Expr
| If Expr Instr Instr
| While Expr Instr
| Seq Instr Instr
| Noop
deriving (Show)
{- Concrete interpreter -}
data Value
= VBool Bool
| VInt Int
deriving (Show)
type Store = M.Map String Value
emptyStore = M.empty
evalExpr :: Expr -> Store -> Value
evalExpr (Var x) s = s M.! x
evalExpr (IntLit i) _ = VInt i
evalExpr (BoolLit b) _ = VBool b
evalExpr (Plus e1 e2) s = VInt (i1 + i2)
where VInt i1 = evalExpr e1 s
VInt i2 = evalExpr e2 s
evalExpr (Lt e1 e2) s = VBool (i1 < i2)
where VInt i1 = evalExpr e1 s
VInt i2 = evalExpr e2 s
evalInstr :: Instr -> Store -> Store
evalInstr (Assign x e) s = M.insert x (evalExpr e s) s
evalInstr (If e i1 i2) s = if ve then evalInstr i1 s else evalInstr i2 s
where VBool ve = evalExpr e s
evalInstr (While e i) s = if ve then evalInstr (While e i) (evalInstr i s) else s
where VBool ve = evalExpr e s
evalInstr (Seq i1 i2) s = evalInstr i2 (evalInstr i1 s)
evalInstr Noop s = s
{- Abstract interpreter -}
data ABool = AFalse | ATrue | AnyBool
deriving (Eq, Show)
data AInt = Zero | Neg | Pos | AnyInt
deriving (Eq, Show)
data AValue
= AVBool ABool
| AVInt AInt
deriving (Eq, Show)
type AStore = M.Map String AValue
emptyAStore = M.empty
aEvalExpr :: Expr -> AStore -> AValue
aEvalExpr (Var x) s = s M.! x
aEvalExpr (IntLit i) _ = AVInt ai
where ai | i == 0 = Zero
| i < 0 = Neg
| i > 0 = Pos
aEvalExpr (BoolLit b) _ = AVBool (if b then ATrue else AFalse)
aEvalExpr (Plus e1 e2) s = AVInt (i1 `aplus` i2)
where AVInt i1 = aEvalExpr e1 s
AVInt i2 = aEvalExpr e2 s
aplus Pos Pos = Pos
aplus Pos Zero = Pos
aplus Zero Pos = Pos
aplus Neg Neg = Neg
aplus Neg Zero = Neg
aplus Zero Neg = Neg
aplus Zero Zero = Zero
aplus _ _ = AnyInt
aEvalExpr (Lt e1 e2) s = AVBool (i1 `alt` i2)
where AVInt i1 = aEvalExpr e1 s
AVInt i2 = aEvalExpr e2 s
alt Neg Zero = ATrue
alt Neg Pos = ATrue
alt Zero Pos = ATrue
alt Zero Neg = AFalse
alt Pos Neg = AFalse
alt Pos Zero = AFalse
alt _ _ = AnyBool
joinAInt :: AInt -> AInt -> AInt
joinAInt x y | x == y = x
| otherwise = AnyInt
joinABool :: ABool -> ABool -> ABool
joinABool x y | x == y = x
| otherwise = AnyBool
joinAValue :: AValue -> AValue -> AValue
joinAValue (AVInt x) (AVInt y) = AVInt (joinAInt x y)
joinAValue (AVBool x) (AVBool y) = AVBool (joinABool x y)
joinAValue _ _ = error "type error"
joinAStore :: AStore -> AStore -> AStore
joinAStore = M.unionWith joinAValue
aEvalInstr :: Instr -> AStore -> AStore
aEvalInstr (Assign x e) s = M.insert x (aEvalExpr e s) s
aEvalInstr (If e i1 i2) s =
case ve of
ATrue -> aEvalInstr i1 s
AFalse -> aEvalInstr i2 s
AnyBool -> aEvalInstr i1 s `joinAStore` aEvalInstr i2 s
where AVBool ve = aEvalExpr e s
aEvalInstr (While e i) s =
case ve of
ATrue -> aEvalInstr (While e i) (aEvalInstr i s)
AFalse -> s
AnyBool -> fixpoint i s
where AVBool ve = aEvalExpr e s
aEvalInstr (Seq i1 i2) s = aEvalInstr i2 (aEvalInstr i1 s)
aEvalInstr Noop s = s
fixpoint i s =
let s' = aEvalInstr i s
in if s == s' then s else fixpoint i s'
{- Example -}
block = foldl1 Seq
example =
block [
"x" `Assign` IntLit (-1),
If (Var "x" `Lt` IntLit (-2))
("y" `Assign` IntLit 1)
("y" `Assign` IntLit 2),
While (Var "x" `Lt` Var "y")
(block [
"x" `Assign` (Var "x" `Plus` IntLit 3),
"y" `Assign` (Var "y" `Plus` IntLit 1)
])
]
main = do
print (evalInstr example emptyStore)
print (aEvalInstr example emptyAStore)
| polux/snippets | AbstractInterpreter.hs | apache-2.0 | 4,639 | 0 | 14 | 1,249 | 1,739 | 889 | 850 | 123 | 15 |
module Data.Kibr.Message where
import Preamble
import Data.Kibr.Language
data Message
= LojbanDictionary
deriving (Eq, Show)
message :: Language -> Message -> Text
message English m = case m of
LojbanDictionary -> "Lojban Dictionary"
message Lojban m = case m of
LojbanDictionary -> "vlaste fu la lojban"
| dag/kibr | src/Data/Kibr/Message.hs | bsd-2-clause | 319 | 0 | 7 | 59 | 87 | 48 | 39 | 11 | 1 |
{-| Implementation of the RAPI client interface.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
{-# LANGUAGE BangPatterns, CPP #-}
module Ganeti.HTools.Backend.Rapi
( loadData
, parseData
) where
import Control.Exception
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Network.Curl
import Network.Curl.Types ()
import Control.Monad
import Text.JSON (JSObject, fromJSObject, decodeStrict)
import Text.JSON.Types (JSValue(..))
import Text.Printf (printf)
import System.FilePath
import Ganeti.BasicTypes
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import Ganeti.JSON
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.Constants as C
{-# ANN module "HLint: ignore Eta reduce" #-}
-- | File method prefix.
filePrefix :: String
filePrefix = "file://"
-- | Read an URL via curl and return the body if successful.
getUrl :: (Monad m) => String -> IO (m String)
-- | Connection timeout (when using non-file methods).
connTimeout :: Long
connTimeout = 15
-- | The default timeout for queries (when using non-file methods).
queryTimeout :: Long
queryTimeout = 60
-- | The curl options we use.
curlOpts :: [CurlOption]
curlOpts = [ CurlSSLVerifyPeer False
, CurlSSLVerifyHost 0
, CurlTimeout queryTimeout
, CurlConnectTimeout connTimeout
]
getUrl url = do
(code, !body) <- curlGetString url curlOpts
return (case code of
CurlOK -> return body
_ -> fail $ printf "Curl error for '%s', error %s"
url (show code))
-- | Helper to convert I/O errors in 'Bad' values.
ioErrToResult :: IO a -> IO (Result a)
ioErrToResult ioaction =
Control.Exception.catch (liftM Ok ioaction)
(\e -> return . Bad . show $ (e::IOException))
-- | Append the default port if not passed in.
formatHost :: String -> String
formatHost master =
if ':' `elem` master
then master
else "https://" ++ master ++ ":" ++ show C.defaultRapiPort
-- | Parse a instance list in JSON format.
getInstances :: NameAssoc
-> String
-> Result [(String, Instance.Instance)]
getInstances ktn body =
loadJSArray "Parsing instance data" body >>=
mapM (parseInstance ktn . fromJSObject)
-- | Parse a node list in JSON format.
getNodes :: NameAssoc -> String -> Result [(String, Node.Node)]
getNodes ktg body = loadJSArray "Parsing node data" body >>=
mapM (parseNode ktg . fromJSObject)
-- | Parse a group list in JSON format.
getGroups :: String -> Result [(String, Group.Group)]
getGroups body = loadJSArray "Parsing group data" body >>=
mapM (parseGroup . fromJSObject)
-- | Construct an instance from a JSON object.
parseInstance :: NameAssoc
-> JSRecord
-> Result (String, Instance.Instance)
parseInstance ktn a = do
name <- tryFromObj "Parsing new instance" a "name"
let owner_name = "Instance '" ++ name ++ "', error while parsing data"
let extract s x = tryFromObj owner_name x s
disk <- extract "disk_usage" a
dsizes <- extract "disk.sizes" a
dspindles <- tryArrayMaybeFromObj owner_name a "disk.spindles"
beparams <- liftM fromJSObject (extract "beparams" a)
omem <- extract "oper_ram" a
mem <- case omem of
JSRational _ _ -> annotateResult owner_name (fromJVal omem)
_ -> extract "memory" beparams `mplus` extract "maxmem" beparams
vcpus <- extract "vcpus" beparams
pnode <- extract "pnode" a >>= lookupNode ktn name
snodes <- extract "snodes" a
snode <- case snodes of
[] -> return Node.noSecondary
x:_ -> readEitherString x >>= lookupNode ktn name
running <- extract "status" a
tags <- extract "tags" a
auto_balance <- extract "auto_balance" beparams
dt <- extract "disk_template" a
su <- extract "spindle_use" beparams
-- Not forthcoming by default.
forthcoming <- extract "forthcoming" a `orElse` Ok False
let disks = zipWith Instance.Disk dsizes dspindles
let inst = Instance.create name mem disk disks vcpus running tags
auto_balance pnode snode dt su [] forthcoming
return (name, inst)
-- | Construct a node from a JSON object.
parseNode :: NameAssoc -> JSRecord -> Result (String, Node.Node)
parseNode ktg a = do
name <- tryFromObj "Parsing new node" a "name"
let desc = "Node '" ++ name ++ "', error while parsing data"
extract key = tryFromObj desc a key
extractDef def key = fromObjWithDefault a key def
offline <- extract "offline"
drained <- extract "drained"
vm_cap <- annotateResult desc $ maybeFromObj a "vm_capable"
let vm_cap' = fromMaybe True vm_cap
ndparams <- extract "ndparams" >>= asJSObject
excl_stor <- tryFromObj desc (fromJSObject ndparams) "exclusive_storage"
guuid <- annotateResult desc $ maybeFromObj a "group.uuid"
guuid' <- lookupGroup ktg name (fromMaybe defaultGroupID guuid)
let live = not offline && vm_cap'
lvextract def = eitherLive live def . extract
lvextractDef def = eitherLive live def . extractDef def
sptotal <- if excl_stor
then lvextract 0 "sptotal"
else tryFromObj desc (fromJSObject ndparams) "spindle_count"
spfree <- lvextractDef 0 "spfree"
mtotal <- lvextract 0.0 "mtotal"
mnode <- lvextract 0 "mnode"
mfree <- lvextract 0 "mfree"
dtotal <- lvextractDef 0.0 "dtotal"
dfree <- lvextractDef 0 "dfree"
ctotal <- lvextract 0.0 "ctotal"
cnos <- lvextract 0 "cnos"
tags <- extract "tags"
hv_state <- extractDef emptyContainer "hv_state"
let node_mem = obtainNodeMemory hv_state mnode
node = flip Node.setNodeTags tags $
Node.create name mtotal node_mem mfree dtotal dfree ctotal cnos
(not live || drained) sptotal spfree guuid' excl_stor
return (name, node)
-- | Construct a group from a JSON object.
parseGroup :: JSRecord -> Result (String, Group.Group)
parseGroup a = do
name <- tryFromObj "Parsing new group" a "name"
let extract s = tryFromObj ("Group '" ++ name ++ "'") a s
let extractDef s d = fromObjWithDefault a s d
uuid <- extract "uuid"
apol <- extract "alloc_policy"
ipol <- extract "ipolicy"
tags <- extract "tags"
nets <- extractDef "networks" []
return (uuid, Group.create name uuid apol nets ipol tags)
-- | Parse cluster data from the info resource.
parseCluster :: JSObject JSValue -> Result ([String], IPolicy, String)
parseCluster obj = do
let obj' = fromJSObject obj
extract s = tryFromObj "Parsing cluster data" obj' s
master <- extract "master"
tags <- extract "tags"
ipolicy <- extract "ipolicy"
return (tags, ipolicy, master)
-- | Loads the raw cluster data from an URL.
readDataHttp :: String -- ^ Cluster or URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readDataHttp master = do
let url = formatHost master
group_body <- getUrl $ printf "%s/2/groups?bulk=1" url
node_body <- getUrl $ printf "%s/2/nodes?bulk=1" url
inst_body <- getUrl $ printf "%s/2/instances?bulk=1" url
info_body <- getUrl $ printf "%s/2/info" url
return (group_body, node_body, inst_body, info_body)
-- | Loads the raw cluster data from the filesystem.
readDataFile:: String -- ^ Path to the directory containing the files
-> IO (Result String, Result String, Result String, Result String)
readDataFile path = do
group_body <- ioErrToResult . readFile $ path </> "groups.json"
node_body <- ioErrToResult . readFile $ path </> "nodes.json"
inst_body <- ioErrToResult . readFile $ path </> "instances.json"
info_body <- ioErrToResult . readFile $ path </> "info.json"
return (group_body, node_body, inst_body, info_body)
-- | Loads data via either 'readDataFile' or 'readDataHttp'.
readData :: String -- ^ URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readData url =
if filePrefix `isPrefixOf` url
then readDataFile (drop (length filePrefix) url)
else readDataHttp url
-- | Builds the cluster data from the raw Rapi content.
parseData :: (Result String, Result String, Result String, Result String)
-> Result ClusterData
parseData (group_body, node_body, inst_body, info_body) = do
group_data <- group_body >>= getGroups
let (group_names, group_idx) = assignIndices group_data
node_data <- node_body >>= getNodes group_names
let (node_names, node_idx) = assignIndices node_data
inst_data <- inst_body >>= getInstances node_names
let (_, inst_idx) = assignIndices inst_data
(tags, ipolicy, master) <-
info_body >>=
(fromJResult "Parsing cluster info" . decodeStrict) >>=
parseCluster
node_idx' <- setMaster node_names node_idx master
return (ClusterData group_idx node_idx' inst_idx tags ipolicy)
-- | Top level function for data loading.
loadData :: String -- ^ Cluster or URL to use as source
-> IO (Result ClusterData)
loadData = fmap parseData . readData
| leshchevds/ganeti | src/Ganeti/HTools/Backend/Rapi.hs | bsd-2-clause | 10,279 | 0 | 15 | 2,083 | 2,494 | 1,232 | 1,262 | 188 | 3 |
module Instances.ListGraphs.DslInterpreter (
interpretAsNewDiGEdges
, interpretAsDiGEdgesModification
) where
import PolyGraph.Common (OPair(..))
import qualified FreeDSL.GraphBuilder as DSL
import qualified Instances.ListGraphs as ListGraphs
interpretAsNewDiGEdges :: forall v edata . (Eq v) => DSL.GraphDSL v edata -> ListGraphs.DiEdges v
interpretAsNewDiGEdges program = interpretAsDiGEdgesModification program (ListGraphs.Edges [])
interpretAsDiGEdgesModification :: forall v edata . (Eq v)
=> DSL.GraphDSL v edata -> ListGraphs.DiEdges v -> ListGraphs.DiEdges v
interpretAsDiGEdgesModification program graph =
let (_, listOfEdgesWithData) = DSL.runDefaultInterpreter program ([], [])
newEdges = map (\(v1,v2,_) -> OPair (v1, v2)) listOfEdgesWithData
oldEdges = ListGraphs.getEdges graph
in ListGraphs.Edges (oldEdges ++ newEdges)
| rpeszek/GraphPlay | src/Instances/ListGraphs/DslInterpreter.hs | bsd-3-clause | 927 | 0 | 13 | 183 | 252 | 139 | 113 | -1 | -1 |
import System.Environment
import Test.DocTest
main = doctest ["yak", "YakCli", "Yak/Org"]
| mostalive/yak-o-matic | yak-test.hs | bsd-3-clause | 91 | 0 | 6 | 11 | 28 | 16 | 12 | 3 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
--
-- RNG/Regs.hs --- Random Number Generator registers
--
-- Copyright (C) 2015, Galois, Inc.
-- All Rights Reserved.
--
module Ivory.BSP.STM32.Peripheral.RNG.Regs where
import Ivory.Language
[ivory|
bitdata RNG_CR :: Bits 32 = rng_cr
{ _ :: Bits 28
, rng_cr_ie :: Bit
, rng_cr_rngen :: Bit
, _ :: Bits 2
}
|]
[ivory|
bitdata RNG_SR :: Bits 32 = rng_sr
{ _ :: Bits 25
, rng_sr_seis :: Bit
, rng_sr_ceis :: Bit
, _ :: Bits 2
, rng_sr_secs :: Bit
, rng_sr_cecs :: Bit
, rng_sr_drdy :: Bit
}
|]
[ivory|
bitdata RNG_DR :: Bits 32 = rng_dr
{ rng_dr_data :: Bits 32
}
|]
| GaloisInc/ivory-tower-stm32 | ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/RNG/Regs.hs | bsd-3-clause | 806 | 0 | 4 | 234 | 46 | 36 | 10 | 9 | 0 |
import qualified Test
main :: IO ()
main = Test.printAllTests
| garethrowlands/marsrover | test/TestMain.hs | bsd-3-clause | 63 | 0 | 6 | 11 | 22 | 12 | 10 | 3 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.Kontiki.MemLog (
Log
, MemLog
, runMemLog
, IntMap.empty
, IntMap.insert
) where
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Control.Monad.Reader (MonadReader, Reader, ask, runReader)
import Network.Kontiki.Raft (Entry, MonadLog (..), unIndex)
type Log a = IntMap (Entry a)
newtype MemLog a r = MemLog { unMemLog :: Reader (Log a) r }
deriving ( Functor
, Applicative
, Monad
, MonadReader (Log a)
)
instance MonadLog (MemLog a) a where
logEntry i = IntMap.lookup (fromIntegral $ unIndex i) `fmap` ask
logLastEntry = do
l <- ask
return $ if IntMap.null l
then Nothing
else Just $ snd $ IntMap.findMax l
runMemLog :: MemLog a r -> Log a -> r
runMemLog = runReader . unMemLog
| abailly/kontiki | src/Data/Kontiki/MemLog.hs | bsd-3-clause | 1,044 | 0 | 12 | 340 | 279 | 159 | 120 | 28 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Module : $Header$
Copyright : (c) 2015 Swinburne Software Innovation Lab
License : BSD3
Maintainer : Rhys Adams <rhysadams@swin.edu.au>
Stability : unstable
Portability : portable
-}
module Eclogues.State.Types where
import qualified Eclogues.Job as Job
import Control.Lens.TH (makeClassy)
import Data.Default.Generics (Default)
import Data.HashMap.Lazy (HashMap)
import GHC.Generics (Generic)
type Jobs = HashMap Job.Name Job.Status
type RevDeps = HashMap Job.Name [Job.Name]
data AppState = AppState { -- | Map of jobs names to status.
_jobs :: Jobs
-- | Map of job names to jobs that depend on them
-- and have yet to terminate.
, _revDeps :: RevDeps }
deriving (Generic, Show, Eq)
$(makeClassy ''AppState)
instance Default AppState
| futufeld/eclogues | eclogues-mock/src/Eclogues/State/Types.hs | bsd-3-clause | 1,023 | 0 | 8 | 274 | 154 | 93 | 61 | 18 | 0 |
-- This module is copied from the Elm compiler with small changes
-- https://github.com/elm/compiler/blob/94715a520f499591ac6901c8c822bc87cd1af24f/compiler/src/Reporting/Annotation.hs
{-# OPTIONS_GHC -Wall #-}
module Reporting.Annotation
( Located(..)
, Position(..)
, Region(..)
, toValue
, merge
, at
, toRegion
, mergeRegions
, zero
, one
)
where
import Control.Monad (liftM2)
import Data.Coapplicative
import Data.Binary (Binary, get, put)
import Data.Word (Word16)
import Data.String (unwords)
-- LOCATED
data Located a =
At Region a -- PERF see if unpacking region is helpful
deriving Eq
instance (Show a) => Show (Located a) where
showsPrec p (At ann a) = showParen (p > 10) $
showString $ unwords
[ show ann
, showsPrec 99 a ""
]
instance Functor Located where
fmap f (At region a) =
At region (f a)
instance Foldable Located where
foldMap f (At _ a) = f a
instance Traversable Located where
traverse f (At region a) = fmap (At region) $ f a
instance Coapplicative Located where
extract (At _ x) = x
{-# INLINE extract #-}
traverse :: (Functor f) => (a -> f b) -> Located a -> f (Located b)
traverse func (At region value) =
At region <$> func value
toValue :: Located a -> a
toValue (At _ value) =
value
merge :: Located a -> Located b -> value -> Located value
merge (At r1 _) (At r2 _) value =
At (mergeRegions r1 r2) value
-- POSITION
data Position =
Position
{-# UNPACK #-} !Word16
{-# UNPACK #-} !Word16
deriving Eq
at :: Position -> Position -> a -> Located a
at start end a =
At (Region start end) a
-- REGION
data Region = Region Position Position
deriving Eq
instance Show Region where
showsPrec p (Region (Position r1 c1) (Position r2 c2)) = showParen (p > 10) $
showString $ unwords
[ "at"
, show r1
, show c1
, show r2
, show c2
]
toRegion :: Located a -> Region
toRegion (At region _) =
region
mergeRegions :: Region -> Region -> Region
mergeRegions (Region start _) (Region _ end) =
Region start end
zero :: Region
zero =
Region (Position 0 0) (Position 0 0)
one :: Region
one =
Region (Position 1 1) (Position 1 1)
instance Binary Region where
put (Region a b) = put a >> put b
get = liftM2 Region get get
instance Binary Position where
put (Position a b) = put a >> put b
get = liftM2 Position get get
| avh4/elm-format | elm-format-lib/src/Reporting/Annotation.hs | bsd-3-clause | 2,498 | 0 | 10 | 677 | 894 | 463 | 431 | 80 | 1 |
module AdventOfCode
( loadDay
, runDay
, Day(..)
, module P
, module S
) where
import Text.Parsec as P hiding (State)
import Text.Parsec.String as P
import Search as S
import System.Environment (getArgs)
import Control.Monad (when)
data Day i = Day
{ dayNum :: Int
, dayParser :: Parser i
, dayPartA :: i -> IO String
, dayPartB :: i -> IO String
}
loadDay :: Day i -> IO i
loadDay d = do
result <-
parseFromFile (dayParser d <* eof) ("input/" ++ show (dayNum d) ++ ".txt")
case result of
Right input -> return input
Left e -> error (show e)
runDay :: Day i -> IO ()
runDay d = do
args <- getArgs
input <- loadDay d
when (null args || "a" `elem` args) $
do putStrLn $ banner "a"
putStrLn =<< dayPartA d input
when (null args || "b" `elem` args) $
do putStrLn $ "\n" ++ banner "b"
putStrLn =<< dayPartB d input
where
banner ab = "==== DAY " ++ show (dayNum d) ++ ab ++ " ====\n"
| purcell/adventofcode2016 | lib/AdventOfCode.hs | bsd-3-clause | 956 | 0 | 14 | 254 | 399 | 206 | 193 | 34 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
-- Part of a hypothetical test module for the semigroups package.
module HypotheticalSemigroupsSpec where
import qualified Data.List.NonEmpty as NonEmpty
import Data.Semigroup ((<>))
import Test.Hspec (Spec, hspec, describe, it, shouldBe, shouldSatisfy)
import Test.Hspec.QuickCheck (prop)
import qualified Test.QuickCheck as QuickCheck
import qualified Data.Maybe as Maybe
-- | Required for auto-discovery.
spec :: Spec
spec =
describe "semigroups" $ do
describe "Data.List.NonEmpty" $ do
describe "constructor NonEmpty.nonEmpty" $ do
it "fails on trying to construct from an empty regular list" $ do
NonEmpty.nonEmpty ([] :: [Int]) `shouldBe` Nothing
prop "succeeds on any nonempty list" $ do
\(QuickCheck.NonEmpty (xs :: [Int])) ->
NonEmpty.nonEmpty xs `shouldSatisfy` Maybe.isJust
describe "conversion to regular list" $ do
prop "converts back to the original regular list" $ do
\(QuickCheck.NonEmpty (xs :: [Int])) ->
let Just nonEmptyXs = NonEmpty.nonEmpty xs
in NonEmpty.toList nonEmptyXs `shouldBe` xs
describe "Data.Semigroup.Semigroup" $ do
prop "<> is associative for String" $ do
\(x :: String) y z -> (x <> y) <> z `shouldBe` x <> (y <> z)
main :: IO ()
main = hspec spec
| FranklinChen/twenty-four-days2015-of-hackage | test/HypotheticalSemigroupsSpec.hs | bsd-3-clause | 1,353 | 0 | 23 | 307 | 363 | 195 | 168 | 28 | 1 |
-- Top-level module for re-exports
module Calypso
(
module Calypso.Core,
module Calypso.Instance.PsoVect,
module Calypso.Instance.Grade
) where
import Calypso.Core
import Calypso.Instance.PsoVect
import Calypso.Instance.Grade
| brianshourd/haskell-Calypso | Calypso.hs | bsd-3-clause | 247 | 0 | 5 | 43 | 44 | 30 | 14 | 8 | 0 |
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Control.Category1
( Functor1
, map1
, Expo(Expo)
, runExpo
, Apply1
, ap1
, lift2_1
, lift3_1
, Applicative1
, pure1
, Traversable_1
, traverse_1
, sequence_1
, sequence_1I
, Record1Fields(Nil, Cons)
, foldRecord1Fields
, Record1Builder(Constructor)
, (<::>)
, foldRecord1Builder
, Record1
, record1Builder
, record1
, record1I
, record1Map1
, record1Ap1
, record1Pure1
, record1Sequence_1
) where
import Data.Functor.Identity
import Data.Functor.Compose
import Control.Applicative (liftA2)
class Functor1 t where
map1 :: (forall α. f α -> g α) -> t f -> t g
newtype Expo f g a = Expo
{ runExpo :: f a -> g a
}
class Functor1 t =>
Apply1 t where
ap1 :: t (Expo f g) -> t f -> t g
class Apply1 t =>
Applicative1 t where
pure1 :: (forall α. f α) -> t f
lift2_1
:: Apply1 t
=> (forall α. f α -> g α -> h α) -> t f -> t g -> t h
lift2_1 f = ap1 . map1 (Expo . f)
lift3_1
:: Apply1 t
=> (forall α. f α -> g α -> h α -> i α) -> t f -> t g -> t h -> t i
lift3_1 f x y z = (Expo . ((.) . (.)) Expo f) `map1` x `ap1` y `ap1` z
--TODO dont use default members
class Functor1 t =>
Traversable_1 t where
traverse_1
:: Applicative g
=> (forall α. f α -> g (h α)) -> t f -> g (t h)
traverse_1 f = sequence_1 . map1 (Compose . f)
sequence_1
:: Applicative f
=> t (Compose f g) -> f (t g)
sequence_1 = traverse_1 getCompose
sequence_1I
:: (Traversable_1 t, Applicative f)
=> t f -> f (t Identity)
sequence_1I = sequence_1 . map1 (Compose . fmap Identity)
data Record1Fields :: ((k -> *) -> *) -> (k -> *) -> * -> * where
Nil :: Record1Fields t f (t f)
Cons ::
(forall φ . t φ -> φ a) ->
Record1Fields t f b -> Record1Fields t f (f a -> b)
infixr 5 <::>
(<::>)
:: (forall (φ :: * -> *). t φ -> φ a)
-> Record1Fields t f b
-> Record1Fields t f (f a -> b)
(<::>) = Cons
data Record1Builder :: ((k -> *) -> *) -> (k -> *) -> * where
Constructor :: a -> Record1Fields t f a -> Record1Builder t f
foldRecord1Fields
:: (forall α β. (forall φ. t φ -> φ α) -> r β -> r (f α -> β))
-> r (t f)
-> Record1Fields t f a
-> r a
foldRecord1Fields _ z Nil = z
foldRecord1Fields f z (Cons x xs) = f x (foldRecord1Fields f z xs)
foldRecord1Builder
:: (forall α. α -> r α -> b)
-> (forall α β. (forall φ. t φ -> φ α) -> r β -> r (f α -> β))
-> r (t f)
-> Record1Builder t f
-> b
foldRecord1Builder g f z (Constructor c flds) = g c (foldRecord1Fields f z flds)
record1
:: forall t f r b.
Record1 t
=> (forall α. α -> r α -> b)
-> (forall α β. (forall φ. t φ -> φ α) -> r β -> r (f α -> β))
-> r (t f)
-> b
record1 g f z = foldRecord1Builder g f z record1Builder
class Record1 t where
record1Builder :: Record1Builder t f
newtype F0 t f α = F0
{ runF0 :: α -> t f
}
record1I
:: forall t f.
Record1 t
=> (forall α. (forall φ. t φ -> φ α) -> f α) -> t f
record1I f = record1 (flip runF0) (\φ (F0 g) -> F0 $ \h -> g . h $ f φ) (F0 id)
record1Ap1
:: Record1 t
=> t (Expo f1 f) -> t f1 -> t f
record1Ap1 ff tf = record1I (\φ -> runExpo (φ ff) (φ tf))
record1Map1
:: Record1 t
=> (forall α. f α -> g α) -> t f -> t g
record1Map1 f tf = record1I (\φ -> f (φ tf))
record1Pure1
:: Record1 t
=> (forall α. f α) -> t f
record1Pure1 z = record1I (const z)
newtype F1 f t g α = F1 (f (α -> t g))
record1Sequence_1
:: forall t f g.
(Record1 t, Applicative f)
=> t (Compose f g) -> f (t g)
record1Sequence_1 tfg =
record1
(\a (F1 ff) -> ($ a) <$> ff)
(\φ (F1 b) -> F1 . liftA2 (\x y f -> x (f y)) b . getCompose $ φ tfg)
(F1 $ pure id)
| aaronvargo/htut | src/Control/Category1.hs | bsd-3-clause | 3,926 | 0 | 16 | 1,077 | 1,899 | 990 | 909 | 142 | 1 |
{-# LANGUAGE CPP, NondecreasingIndentation, ScopedTypeVariables #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2012
--
-- The GHC API
--
-- -----------------------------------------------------------------------------
module ETA.Main.GHC (
-- * Initialisation
defaultErrorHandler,
defaultCleanupHandler,
prettyPrintGhcErrors,
-- * GHC Monad
Ghc, GhcT, GhcMonad(..), HscEnv,
runGhc, runGhcT, initGhcMonad,
gcatch, gbracket, gfinally,
printException,
handleSourceError,
needsTemplateHaskell,
-- * Flags and settings
DynFlags(..), GeneralFlag(..), Severity(..), HscTarget(..), gopt,
GhcMode(..), GhcLink(..), defaultObjectTarget,
parseDynamicFlags,
getSessionDynFlags, setSessionDynFlags,
getProgramDynFlags, setProgramDynFlags,
getInteractiveDynFlags, setInteractiveDynFlags,
parseStaticFlags,
-- * Targets
Target(..), TargetId(..), Phase,
setTargets,
getTargets,
addTarget,
removeTarget,
guessTarget,
-- * Loading\/compiling the program
depanal,
load, LoadHowMuch(..), InteractiveImport(..),
SuccessFlag(..), succeeded, failed,
defaultWarnErrLogger, WarnErrLogger,
workingDirectoryChanged,
parseModule, typecheckModule, desugarModule, loadModule,
ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
TypecheckedSource, ParsedSource, RenamedSource, -- ditto
TypecheckedMod, ParsedMod,
moduleInfo, renamedSource, typecheckedSource,
parsedSource, coreModule,
-- ** Compiling to Core
CoreModule(..),
compileToCoreModule, compileToCoreSimplified,
-- * Inspecting the module structure of the program
ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
getModSummary,
getModuleGraph,
isLoaded,
topSortModuleGraph,
-- * Inspecting modules
ModuleInfo,
getModuleInfo,
modInfoTyThings,
modInfoTopLevelScope,
modInfoExports,
modInfoInstances,
modInfoIsExportedName,
modInfoLookupName,
modInfoIface,
modInfoSafe,
lookupGlobalName,
findGlobalAnns,
mkPrintUnqualifiedForModule,
ModIface(..),
SafeHaskellMode(..),
-- * Querying the environment
-- packageDbModules,
-- * Printing
PrintUnqualified, alwaysQualify,
-- * Interactive evaluation
getBindings, getInsts, getPrintUnqual,
findModule, lookupModule,
#ifdef GHCI
isModuleTrusted,
moduleTrustReqs,
setContext, getContext,
getNamesInScope,
getRdrNamesInScope,
getGRE,
moduleIsInterpreted,
getInfo,
exprType,
typeKind,
parseName,
RunResult(..),
runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
runTcInteractive, -- Desired by some clients (Trac #8878)
parseImportDecl, SingleStep(..),
resume,
Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
resumeHistory, resumeHistoryIx),
History(historyBreakInfo, historyEnclosingDecls),
GHC.getHistorySpan, getHistoryModule,
getResumeContext,
abandon, abandonAll,
InteractiveEval.back,
InteractiveEval.forward,
showModule,
isModuleInterpreted,
InteractiveEval.compileExpr, HValue, dynCompileExpr,
GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
modInfoModBreaks,
ModBreaks(..), BreakIndex,
BreakInfo(breakInfo_number, breakInfo_module),
BreakArray, setBreakOn, setBreakOff, getBreak,
#endif
lookupName,
#ifdef GHCI
-- ** EXPERIMENTAL
setGHCiMonad,
#endif
-- * Abstract syntax elements
-- ** Packages
UnitId,
-- ** Modules
Module, mkModule, pprModule, moduleName, moduleUnitId,
ModuleName, mkModuleName, moduleNameString,
-- ** Names
Name,
isExternalName, nameModule, pprParenSymName, nameSrcSpan,
NamedThing(..),
RdrName(Qual,Unqual),
-- ** Identifiers
Id, idType,
isImplicitId, isDeadBinder,
isExportedId, isLocalId, isGlobalId,
isRecordSelector,
isPrimOpId, isFCallId, isClassOpId_maybe,
isDataConWorkId, idDataCon,
isBottomingId, isDictonaryId,
recordSelectorFieldLabel,
-- ** Type constructors
TyCon,
tyConTyVars, tyConDataCons, tyConArity,
isClassTyCon, isTypeSynonymTyCon, isTypeFamilyTyCon, isNewTyCon,
isPrimTyCon, isFunTyCon,
isFamilyTyCon, isOpenFamilyTyCon, isOpenTypeFamilyTyCon,
tyConClass_maybe,
synTyConRhs_maybe, synTyConDefn_maybe, synTyConResKind,
-- ** Type variables
TyVar,
alphaTyVars,
-- ** Data constructors
DataCon,
dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
dataConIsInfix, isVanillaDataCon, dataConUserType,
dataConSrcBangs,
StrictnessMark(..), isMarkedStrict,
-- ** Classes
Class,
classMethods, classSCTheta, classTvsFds, classATs,
pprFundeps,
-- ** Instances
ClsInst,
instanceDFunId,
pprInstance, pprInstanceHdr,
pprFamInst,
FamInst,
-- ** Types and Kinds
Type, splitForAllTys, funResultTy,
pprParendType, pprTypeApp,
Kind,
PredType,
ThetaType, pprForAll, pprThetaArrowTy,
-- ** Entities
TyThing(..),
-- ** Syntax
module HsSyn, -- ToDo: remove extraneous bits
-- ** Fixities
FixityDirection(..),
defaultFixity, maxPrecedence,
negateFixity,
compareFixity,
-- ** Source locations
SrcLoc(..), RealSrcLoc,
mkSrcLoc, noSrcLoc,
srcLocFile, srcLocLine, srcLocCol,
SrcSpan(..), RealSrcSpan,
mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
srcSpanStart, srcSpanEnd,
srcSpanFile,
srcSpanStartLine, srcSpanEndLine,
srcSpanStartCol, srcSpanEndCol,
-- ** Located
GenLocated(..), Located,
-- *** Constructing Located
noLoc, mkGeneralLocated,
-- *** Deconstructing Located
getLoc, unLoc,
-- *** Combining and comparing Located values
eqLocated, cmpLocated, combineLocs, addCLoc,
leftmost_smallest, leftmost_largest, rightmost,
spans, isSubspanOf,
-- * Exceptions
GhcException(..), showGhcException,
-- * Token stream manipulations
Token,
getTokenStream, getRichTokenStream,
showRichTokenStream, addSourceToTokens,
-- * Pure interface to the parser
parser,
-- * API Annotations
ApiAnns,AnnKeywordId(..),AnnotationComment(..),
getAnnotation, getAndRemoveAnnotation,
getAnnotationComments, getAndRemoveAnnotationComments,
-- * Miscellaneous
--sessionHscEnv,
cyclicModuleErr,
) where
{-
ToDo:
* inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
* what StaticFlags should we expose, if any?
-}
#ifdef GHCI
import ETA.Interactive.ByteCodeInstr
import ETA.Main.BreakArray
import InteractiveEval
import TcRnDriver ( runTcInteractive )
#endif
import ETA.Main.PprTyThing ( pprFamInst )
import ETA.Main.HscMain
import ETA.Main.GhcMake
import ETA.Main.DriverPipeline ( compileOne' )
import ETA.Main.GhcMonad
import ETA.TypeCheck.TcRnMonad ( finalSafeMode )
import ETA.TypeCheck.TcRnTypes
import ETA.Main.Packages
import ETA.BasicTypes.NameSet
import ETA.BasicTypes.RdrName
import qualified ETA.HsSyn.HsSyn as HsSyn -- hack as we want to reexport the whole module
import ETA.HsSyn.HsSyn
import ETA.Types.Type hiding( typeKind )
import ETA.Types.Kind ( synTyConResKind )
import ETA.TypeCheck.TcType hiding( typeKind )
import ETA.BasicTypes.Id
import ETA.Prelude.TysPrim ( alphaTyVars )
import ETA.Types.TyCon
import ETA.Types.Class
import ETA.BasicTypes.DataCon
import ETA.BasicTypes.Name hiding ( varName )
import ETA.BasicTypes.Avail
import ETA.Types.InstEnv
import ETA.Types.FamInstEnv ( FamInst )
import ETA.BasicTypes.SrcLoc
import ETA.Core.CoreSyn
import ETA.Main.TidyPgm
import ETA.Main.DriverPhases ( Phase(..), isHaskellSrcFilename )
import ETA.Main.Finder
import ETA.Main.HscTypes
import ETA.Main.DynFlags
import ETA.Main.StaticFlags
import ETA.Main.SysTools
import ETA.Main.Annotations
import ETA.BasicTypes.Module
import ETA.Utils.UniqFM
import ETA.Utils.Panic
-- import ETA.Utils.Platform
import ETA.Utils.Bag ( unitBag )
import ETA.Main.ErrUtils
import ETA.Utils.MonadUtils
import ETA.Utils.Util
import ETA.Utils.StringBuffer
import ETA.Utils.Outputable
import ETA.BasicTypes.BasicTypes
import ETA.Utils.Maybes ( expectJust )
import ETA.Utils.FastString
import qualified ETA.Parser.Parser as Parser
import ETA.Parser.Lexer
import ETA.Parser.ApiAnnotation
import System.Directory ( doesFileExist )
import Data.Maybe
import Data.List ( find )
import Data.Time
import Data.Typeable ( Typeable )
import Data.Word ( Word8 )
import Control.Monad
import System.Exit ( exitWith, ExitCode(..) )
import ETA.Utils.Exception
import Data.IORef
import System.FilePath
import System.IO
import Prelude hiding (init)
-- %************************************************************************
-- %* *
-- Initialisation: exception handlers
-- %* *
-- %************************************************************************
-- | Install some default exception handlers and run the inner computation.
-- Unless you want to handle exceptions yourself, you should wrap this around
-- the top level of your program. The default handlers output the error
-- message(s) to stderr and exit cleanly.
defaultErrorHandler :: (ExceptionMonad m, MonadIO m)
=> FatalMessager -> FlushOut -> m a -> m a
defaultErrorHandler fm (FlushOut flushOut) inner =
-- top-level exception handler: any unrecognised exception is a compiler bug.
ghandle (\exception -> liftIO $ do
flushOut
case fromException exception of
-- an IO exception probably isn't our fault, so don't panic
Just (ioe :: IOException) ->
fatalErrorMsg'' fm (show ioe)
_ -> case fromException exception of
Just UserInterrupt ->
-- Important to let this one propagate out so our
-- calling process knows we were interrupted by ^C
liftIO $ throwIO UserInterrupt
Just StackOverflow ->
fatalErrorMsg'' fm "stack overflow: use +RTS -K<size> to increase it"
_ -> case fromException exception of
Just (ex :: ExitCode) -> liftIO $ throwIO ex
_ ->
fatalErrorMsg'' fm
(show (Panic (show exception)))
exitWith (ExitFailure 1)
) $
-- error messages propagated as exceptions
handleGhcException
(\ge -> liftIO $ do
flushOut
case ge of
PhaseFailed _ code -> exitWith code
Signal _ -> exitWith (ExitFailure 1)
_ -> do fatalErrorMsg'' fm (show ge)
exitWith (ExitFailure 1)
) $
inner
-- | Install a default cleanup handler to remove temporary files deposited by
-- a GHC run. This is separate from 'defaultErrorHandler', because you might
-- want to override the error handling, but still get the ordinary cleanup
-- behaviour.
defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
DynFlags -> m a -> m a
defaultCleanupHandler dflags inner =
-- make sure we clean up after ourselves
inner `gfinally`
(liftIO $ do
cleanTempFiles dflags
cleanTempDirs dflags
)
-- exceptions will be blocked while we clean the temporary files,
-- so there shouldn't be any difficulty if we receive further
-- signals.
-- %************************************************************************
-- %* *
-- The Ghc Monad
-- %* *
-- %************************************************************************
-- | Run function for the 'Ghc' monad.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
--
-- Any errors not handled inside the 'Ghc' action are propagated as IO
-- exceptions.
runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> Ghc a -- ^ The action to perform.
-> IO a
runGhc mb_top_dir ghc = do
ref <- newIORef (panic "empty session")
let session = Session ref
flip unGhc session $ do
initGhcMonad mb_top_dir
ghc
-- XXX: unregister interrupt handlers here?
-- | Run function for 'GhcT' monad transformer.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> GhcT m a -- ^ The action to perform.
-> m a
runGhcT mb_top_dir ghct = do
ref <- liftIO $ newIORef (panic "empty session")
let session = Session ref
flip unGhcT session $ do
initGhcMonad mb_top_dir
ghct
-- | Initialise a GHC session.
--
-- If you implement a custom 'GhcMonad' you must call this function in the
-- monad run function. It will initialise the session variable and clear all
-- warnings.
--
-- The first argument should point to the directory where GHC's library files
-- reside. More precisely, this should be the output of @ghc --print-libdir@
-- of the version of GHC the module using this API is compiled with. For
-- portability, you should use the @ghc-paths@ package, available at
-- <http://hackage.haskell.org/package/ghc-paths>.
initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
initGhcMonad mb_top_dir
= do { env <- liftIO $
do { installSignalHandlers -- catch ^C
; initStaticOpts
; mySettings <- initSysTools mb_top_dir
; dflags <- initDynFlags (defaultDynFlags mySettings)
; setUnsafeGlobalDynFlags dflags
-- c.f. DynFlags.parseDynamicFlagsFull, which
-- creates DynFlags and sets the UnsafeGlobalDynFlags
; newHscEnv dflags }
; setSession env }
-- %************************************************************************
-- %* *
-- Flags & settings
-- %* *
-- %************************************************************************
-- $DynFlags
--
-- The GHC session maintains two sets of 'DynFlags':
--
-- * The "interactive" @DynFlags@, which are used for everything
-- related to interactive evaluation, including 'runStmt',
-- 'runDecls', 'exprType', 'lookupName' and so on (everything
-- under \"Interactive evaluation\" in this module).
--
-- * The "program" @DynFlags@, which are used when loading
-- whole modules with 'load'
--
-- 'setInteractiveDynFlags', 'getInteractiveDynFlags' work with the
-- interactive @DynFlags@.
--
-- 'setProgramDynFlags', 'getProgramDynFlags' work with the
-- program @DynFlags@.
--
-- 'setSessionDynFlags' sets both @DynFlags@, and 'getSessionDynFlags'
-- retrieves the program @DynFlags@ (for backwards compatibility).
-- | Updates both the interactive and program DynFlags in a Session.
-- This also reads the package database (unless it has already been
-- read), and prepares the compilers knowledge about packages. It can
-- be called again to load new packages: just add new package flags to
-- (packageFlags dflags).
--
-- Returns a list of new packages that may need to be linked in using
-- the dynamic linker (see 'linkPackages') as a result of new package
-- flags. If you are not doing linking or doing static linking, you
-- can ignore the list of packages returned.
--
setSessionDynFlags :: GhcMonad m => DynFlags -> m [InstalledUnitId]
setSessionDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
(dflags'', preload) <- liftIO $ initPackages dflags'
modifySession $ \h -> h{ hsc_dflags = dflags''
, hsc_IC = (hsc_IC h){ ic_dflags = dflags'' } }
invalidateModSummaryCache
return preload
-- | Sets the program 'DynFlags'.
setProgramDynFlags :: GhcMonad m => DynFlags -> m [InstalledUnitId]
setProgramDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
(dflags'', preload) <- liftIO $ initPackages dflags'
modifySession $ \h -> h{ hsc_dflags = dflags'' }
invalidateModSummaryCache
return preload
-- When changing the DynFlags, we want the changes to apply to future
-- loads, but without completely discarding the program. But the
-- DynFlags are cached in each ModSummary in the hsc_mod_graph, so
-- after a change to DynFlags, the changes would apply to new modules
-- but not existing modules; this seems undesirable.
--
-- Furthermore, the GHC API client might expect that changing
-- log_action would affect future compilation messages, but for those
-- modules we have cached ModSummaries for, we'll continue to use the
-- old log_action. This is definitely wrong (#7478).
--
-- Hence, we invalidate the ModSummary cache after changing the
-- DynFlags. We do this by tweaking the date on each ModSummary, so
-- that the next downsweep will think that all the files have changed
-- and preprocess them again. This won't necessarily cause everything
-- to be recompiled, because by the time we check whether we need to
-- recopmile a module, we'll have re-summarised the module and have a
-- correct ModSummary.
--
invalidateModSummaryCache :: GhcMonad m => m ()
invalidateModSummaryCache =
modifySession $ \h -> h { hsc_mod_graph = map inval (hsc_mod_graph h) }
where
inval ms = ms { ms_hs_date = addUTCTime (-1) (ms_hs_date ms) }
-- | Returns the program 'DynFlags'.
getProgramDynFlags :: GhcMonad m => m DynFlags
getProgramDynFlags = getSessionDynFlags
-- | Set the 'DynFlags' used to evaluate interactive expressions.
-- Note: this cannot be used for changes to packages. Use
-- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the
-- 'pkgState' into the interactive @DynFlags@.
setInteractiveDynFlags :: GhcMonad m => DynFlags -> m ()
setInteractiveDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
modifySession $ \h -> h{ hsc_IC = (hsc_IC h) { ic_dflags = dflags' }}
-- | Get the 'DynFlags' used to evaluate interactive expressions.
getInteractiveDynFlags :: GhcMonad m => m DynFlags
getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h))
parseDynamicFlags :: MonadIO m =>
DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
parseDynamicFlags = parseDynamicFlagsCmdLine
-- | Checks the set of new DynFlags for possibly erroneous option
-- combinations when invoking 'setSessionDynFlags' and friends, and if
-- found, returns a fixed copy (if possible).
checkNewDynFlags :: MonadIO m => DynFlags -> m DynFlags
checkNewDynFlags dflags = do
-- See Note [DynFlags consistency]
let (dflags', warnings) = makeDynFlagsConsistent dflags
liftIO $ handleFlagWarnings dflags warnings
return dflags'
-- %************************************************************************
-- %* *
-- Setting, getting, and modifying the targets
-- %* *
-- %************************************************************************
-- ToDo: think about relative vs. absolute file paths. And what
-- happens when the current directory changes.
-- | Sets the targets for this session. Each target may be a module name
-- or a filename. The targets correspond to the set of root modules for
-- the program\/library. Unloading the current program is achieved by
-- setting the current set of targets to be empty, followed by 'load'.
setTargets :: GhcMonad m => [Target] -> m ()
setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
-- | Returns the current set of targets
getTargets :: GhcMonad m => m [Target]
getTargets = withSession (return . hsc_targets)
-- | Add another target.
addTarget :: GhcMonad m => Target -> m ()
addTarget target
= modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
-- | Remove a target
removeTarget :: GhcMonad m => TargetId -> m ()
removeTarget target_id
= modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
where
filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
-- | Attempts to guess what Target a string refers to. This function
-- implements the @--make@/GHCi command-line syntax for filenames:
--
-- - if the string looks like a Haskell source filename, then interpret it
-- as such
--
-- - if adding a .hs or .lhs suffix yields the name of an existing file,
-- then use that
--
-- - otherwise interpret the string as a module name
--
guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
guessTarget str (Just phase)
= return (Target (TargetFile str (Just phase)) True Nothing)
guessTarget str Nothing
| isHaskellSrcFilename file
= return (target (TargetFile file Nothing))
| otherwise
= do exists <- liftIO $ doesFileExist hs_file
if exists
then return (target (TargetFile hs_file Nothing))
else do
exists <- liftIO $ doesFileExist lhs_file
if exists
then return (target (TargetFile lhs_file Nothing))
else do
if looksLikeModuleName file
then return (target (TargetModule (mkModuleName file)))
else do
dflags <- getDynFlags
liftIO $ throwGhcExceptionIO
(ProgramError (showSDoc dflags $
text "target" <+> quotes (text file) <+>
text "is not a module name or a source file"))
where
(file,obj_allowed)
| '*':rest <- str = (rest, False)
| otherwise = (str, True)
hs_file = file <.> "hs"
lhs_file = file <.> "lhs"
target tid = Target tid obj_allowed Nothing
-- | Inform GHC that the working directory has changed. GHC will flush
-- its cache of module locations, since it may no longer be valid.
--
-- Note: Before changing the working directory make sure all threads running
-- in the same session have stopped. If you change the working directory,
-- you should also unload the current program (set targets to empty,
-- followed by load).
workingDirectoryChanged :: GhcMonad m => m ()
workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
-- %************************************************************************
-- %* *
-- Running phases one at a time
-- %* *
-- %************************************************************************
class ParsedMod m where
modSummary :: m -> ModSummary
parsedSource :: m -> ParsedSource
class ParsedMod m => TypecheckedMod m where
renamedSource :: m -> Maybe RenamedSource
typecheckedSource :: m -> TypecheckedSource
moduleInfo :: m -> ModuleInfo
tm_internals :: m -> (TcGblEnv, ModDetails)
-- ToDo: improvements that could be made here:
-- if the module succeeded renaming but not typechecking,
-- we can still get back the GlobalRdrEnv and exports, so
-- perhaps the ModuleInfo should be split up into separate
-- fields.
class TypecheckedMod m => DesugaredMod m where
coreModule :: m -> ModGuts
-- | The result of successful parsing.
data ParsedModule =
ParsedModule { pm_mod_summary :: ModSummary
, pm_parsed_source :: ParsedSource
, pm_extra_src_files :: [FilePath]
, pm_annotations :: ApiAnns }
-- See Note [Api annotations] in ApiAnnotation.hs
instance ParsedMod ParsedModule where
modSummary m = pm_mod_summary m
parsedSource m = pm_parsed_source m
-- | The result of successful typechecking. It also contains the parser
-- result.
data TypecheckedModule =
TypecheckedModule { tm_parsed_module :: ParsedModule
, tm_renamed_source :: Maybe RenamedSource
, tm_typechecked_source :: TypecheckedSource
, tm_checked_module_info :: ModuleInfo
, tm_internals_ :: (TcGblEnv, ModDetails)
}
instance ParsedMod TypecheckedModule where
modSummary m = modSummary (tm_parsed_module m)
parsedSource m = parsedSource (tm_parsed_module m)
instance TypecheckedMod TypecheckedModule where
renamedSource m = tm_renamed_source m
typecheckedSource m = tm_typechecked_source m
moduleInfo m = tm_checked_module_info m
tm_internals m = tm_internals_ m
-- | The result of successful desugaring (i.e., translation to core). Also
-- contains all the information of a typechecked module.
data DesugaredModule =
DesugaredModule { dm_typechecked_module :: TypecheckedModule
, dm_core_module :: ModGuts
}
instance ParsedMod DesugaredModule where
modSummary m = modSummary (dm_typechecked_module m)
parsedSource m = parsedSource (dm_typechecked_module m)
instance TypecheckedMod DesugaredModule where
renamedSource m = renamedSource (dm_typechecked_module m)
typecheckedSource m = typecheckedSource (dm_typechecked_module m)
moduleInfo m = moduleInfo (dm_typechecked_module m)
tm_internals m = tm_internals_ (dm_typechecked_module m)
instance DesugaredMod DesugaredModule where
coreModule m = dm_core_module m
type ParsedSource = Located (HsModule RdrName)
type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
Maybe LHsDocString)
type TypecheckedSource = LHsBinds Id
-- NOTE:
-- - things that aren't in the output of the typechecker right now:
-- - the export list
-- - the imports
-- - type signatures
-- - type/data/newtype declarations
-- - class declarations
-- - instances
-- - extra things in the typechecker's output:
-- - default methods are turned into top-level decls.
-- - dictionary bindings
-- | Return the 'ModSummary' of a module with the given name.
--
-- The module must be part of the module graph (see 'hsc_mod_graph' and
-- 'ModuleGraph'). If this is not the case, this function will throw a
-- 'GhcApiError'.
--
-- This function ignores boot modules and requires that there is only one
-- non-boot module with the given name.
getModSummary :: GhcMonad m => ModuleName -> m ModSummary
getModSummary mod = do
mg <- liftM hsc_mod_graph getSession
case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
[] -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "Module not part of module graph")
[ms] -> return ms
multiple -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "getModSummary is ambiguous: " <+> ppr multiple)
-- | Parse a module.
--
-- Throws a 'SourceError' on parse error.
parseModule :: GhcMonad m => ModSummary -> m ParsedModule
parseModule ms = do
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
hpm <- liftIO $ hscParse hsc_env_tmp ms
return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm)
(hpm_annotations hpm))
-- See Note [Api annotations] in ApiAnnotation.hs
-- | Typecheck and rename a parsed module.
--
-- Throws a 'SourceError' if either fails.
typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
typecheckModule pmod = do
let ms = modSummary pmod
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
(tc_gbl_env, rn_info)
<- liftIO $ hscTypecheckRename hsc_env_tmp ms $
HsParsedModule { hpm_module = parsedSource pmod,
hpm_src_files = pm_extra_src_files pmod,
hpm_annotations = pm_annotations pmod }
details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env
safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env
return $
TypecheckedModule {
tm_internals_ = (tc_gbl_env, details),
tm_parsed_module = pmod,
tm_renamed_source = rn_info,
tm_typechecked_source = tcg_binds tc_gbl_env,
tm_checked_module_info =
ModuleInfo {
minf_type_env = md_types details,
minf_exports = availsToNameSet $ md_exports details,
minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
minf_instances = md_insts details,
minf_iface = Nothing,
minf_safe = safe
#ifdef GHCI
,minf_modBreaks = emptyModBreaks
#endif
}}
-- | Desugar a typechecked module.
desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
desugarModule tcm = do
let ms = modSummary tcm
let (tcg, _) = tm_internals tcm
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg
return $
DesugaredModule {
dm_typechecked_module = tcm,
dm_core_module = guts
}
-- | Load a module. Input doesn't need to be desugared.
--
-- A module must be loaded before dependent modules can be typechecked. This
-- always includes generating a 'ModIface' and, depending on the
-- 'DynFlags.hscTarget', may also include code generation.
--
-- This function will always cause recompilation and will always overwrite
-- previous compilation results (potentially files on disk).
--
loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
loadModule tcm = do
let ms = modSummary tcm
let mod = ms_mod_name ms
let loc = ms_location ms
let (tcg, _details) = tm_internals tcm
mb_linkable <- case ms_obj_date ms of
Just t | t > ms_hs_date ms -> do
l <- liftIO $ findObjectLinkable (ms_mod ms)
(ml_obj_file loc) t
return (Just l)
_otherwise -> return Nothing
let source_modified | isNothing mb_linkable = SourceModified
| otherwise = SourceUnmodified
-- we can't determine stability here
-- compile doesn't change the session
hsc_env <- getSession
mod_info <- liftIO $ compileOne' (Just tcg) Nothing
hsc_env ms 1 1 Nothing mb_linkable
source_modified
modifySession $ \e -> e{ hsc_HPT = addToUFM (hsc_HPT e) mod mod_info }
return tcm
-- %************************************************************************
-- %* *
-- Dealing with Core
-- %* *
-- %************************************************************************
-- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
-- the 'GHC.compileToCoreModule' interface.
data CoreModule
= CoreModule {
-- | Module name
cm_module :: !Module,
-- | Type environment for types declared in this module
cm_types :: !TypeEnv,
-- | Declarations
cm_binds :: CoreProgram,
-- | Safe Haskell mode
cm_safe :: SafeHaskellMode
}
instance Outputable CoreModule where
ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb,
cm_safe = sf})
= text "%module" <+> ppr mn <+> parens (ppr sf) <+> ppr te
$$ vcat (map ppr cb)
-- | This is the way to get access to the Core bindings corresponding
-- to a module. 'compileToCore' parses, typechecks, and
-- desugars the module, then returns the resulting Core module (consisting of
-- the module name, type declarations, and function declarations) if
-- successful.
compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
compileToCoreModule = compileCore False
-- | Like compileToCoreModule, but invokes the simplifier, so
-- as to return simplified and tidied Core.
compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
compileToCoreSimplified = compileCore True
compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
compileCore simplify fn = do
-- First, set the target to the desired filename
target <- guessTarget fn Nothing
addTarget target
_ <- load LoadAllTargets
-- Then find dependencies
modGraph <- depanal [] True
case find ((== fn) . msHsFilePath) modGraph of
Just modSummary -> do
-- Now we have the module name;
-- parse, typecheck and desugar the module
mod_guts <- coreModule `fmap`
-- TODO: space leaky: call hsc* directly?
(desugarModule =<< typecheckModule =<< parseModule modSummary)
liftM (gutsToCoreModule (mg_safe_haskell mod_guts)) $
if simplify
then do
-- If simplify is true: simplify (hscSimplify), then tidy
-- (tidyProgram).
hsc_env <- getSession
simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts
tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
return $ Left tidy_guts
else
return $ Right mod_guts
Nothing -> panic "compileToCoreModule: target FilePath not found in\
module dependency graph"
where -- two versions, based on whether we simplify (thus run tidyProgram,
-- which returns a (CgGuts, ModDetails) pair, or not (in which case
-- we just have a ModGuts.
gutsToCoreModule :: SafeHaskellMode
-> Either (CgGuts, ModDetails) ModGuts
-> CoreModule
gutsToCoreModule safe_mode (Left (cg, md)) = CoreModule {
cm_module = cg_module cg,
cm_types = md_types md,
cm_binds = cg_binds cg,
cm_safe = safe_mode
}
gutsToCoreModule safe_mode (Right mg) = CoreModule {
cm_module = mg_module mg,
cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg))
(mg_tcs mg)
(mg_fam_insts mg),
cm_binds = mg_binds mg,
cm_safe = safe_mode
}
-- %************************************************************************
-- %* *
-- Inspecting the session
-- %* *
-- %************************************************************************
-- | Get the module dependency graph.
getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
getModuleGraph = liftM hsc_mod_graph getSession
-- | Determines whether a set of modules requires Template Haskell.
--
-- Note that if the session's 'DynFlags' enabled Template Haskell when
-- 'depanal' was called, then each module in the returned module graph will
-- have Template Haskell enabled whether it is actually needed or not.
needsTemplateHaskell :: ModuleGraph -> Bool
needsTemplateHaskell ms =
any (xopt Opt_TemplateHaskell . ms_hspp_opts) ms
-- | Return @True@ <==> module is loaded.
isLoaded :: GhcMonad m => ModuleName -> m Bool
isLoaded m = withSession $ \hsc_env ->
return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
-- | Return the bindings for the current interactive session.
getBindings :: GhcMonad m => m [TyThing]
getBindings = withSession $ \hsc_env ->
return $ icInScopeTTs $ hsc_IC hsc_env
-- | Return the instances for the current interactive session.
getInsts :: GhcMonad m => m ([ClsInst], [FamInst])
getInsts = withSession $ \hsc_env ->
return $ ic_instances (hsc_IC hsc_env)
getPrintUnqual :: GhcMonad m => m PrintUnqualified
getPrintUnqual = withSession $ \hsc_env ->
return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
-- | Container for information about a 'Module'.
data ModuleInfo = ModuleInfo {
minf_type_env :: TypeEnv,
minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
minf_instances :: [ClsInst],
minf_iface :: Maybe ModIface,
minf_safe :: SafeHaskellMode
#ifdef GHCI
,minf_modBreaks :: ModBreaks
#endif
}
-- We don't want HomeModInfo here, because a ModuleInfo applies
-- to package modules too.
-- | Request information about a loaded 'Module'
getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
getModuleInfo mdl = withSession $ \hsc_env -> do
let mg = hsc_mod_graph hsc_env
if mdl `elem` map ms_mod mg
then liftIO $ getHomeModuleInfo hsc_env mdl
else do
{- if isHomeModule (hsc_dflags hsc_env) mdl
then return Nothing
else -} liftIO $ getPackageModuleInfo hsc_env mdl
-- ToDo: we don't understand what the following comment means.
-- (SDM, 19/7/2011)
-- getPackageModuleInfo will attempt to find the interface, so
-- we don't want to call it for a home module, just in case there
-- was a problem loading the module and the interface doesn't
-- exist... hence the isHomeModule test here. (ToDo: reinstate)
getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
#ifdef GHCI
getPackageModuleInfo hsc_env mdl
= do eps <- hscEPS hsc_env
iface <- hscGetModuleInterface hsc_env mdl
let
avails = mi_exports iface
names = availsToNameSet avails
pte = eps_PTE eps
tys = [ ty | name <- concatMap availNames avails,
Just ty <- [lookupTypeEnv pte name] ]
--
return (Just (ModuleInfo {
minf_type_env = mkTypeEnv tys,
minf_exports = names,
minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
minf_instances = error "getModuleInfo: instances for package module unimplemented",
minf_iface = Just iface,
minf_safe = getSafeMode $ mi_trust iface,
minf_modBreaks = emptyModBreaks
}))
#else
-- bogusly different for non-GHCI (ToDo)
getPackageModuleInfo _hsc_env _mdl = do
return Nothing
#endif
getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
getHomeModuleInfo hsc_env mdl =
case lookupUFM (hsc_HPT hsc_env) (moduleName mdl) of
Nothing -> return Nothing
Just hmi -> do
let details = hm_details hmi
iface = hm_iface hmi
return (Just (ModuleInfo {
minf_type_env = md_types details,
minf_exports = availsToNameSet (md_exports details),
minf_rdr_env = mi_globals $! hm_iface hmi,
minf_instances = md_insts details,
minf_iface = Just iface,
minf_safe = getSafeMode $ mi_trust iface
#ifdef GHCI
,minf_modBreaks = getModBreaks hmi
#endif
}))
-- | The list of top-level entities defined in a module
modInfoTyThings :: ModuleInfo -> [TyThing]
modInfoTyThings minf = typeEnvElts (minf_type_env minf)
modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
modInfoTopLevelScope minf
= fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
modInfoExports :: ModuleInfo -> [Name]
modInfoExports minf = nameSetElems $! minf_exports minf
-- | Returns the instances defined by the specified module.
-- Warning: currently unimplemented for package modules.
modInfoInstances :: ModuleInfo -> [ClsInst]
modInfoInstances = minf_instances
modInfoIsExportedName :: ModuleInfo -> Name -> Bool
modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
mkPrintUnqualifiedForModule :: GhcMonad m =>
ModuleInfo
-> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
modInfoLookupName :: GhcMonad m =>
ModuleInfo -> Name
-> m (Maybe TyThing) -- XXX: returns a Maybe X
modInfoLookupName minf name = withSession $ \hsc_env -> do
case lookupTypeEnv (minf_type_env minf) name of
Just tyThing -> return (Just tyThing)
Nothing -> do
eps <- liftIO $ readIORef (hsc_EPS hsc_env)
return $! lookupType (hsc_dflags hsc_env)
(hsc_HPT hsc_env) (eps_PTE eps) name
modInfoIface :: ModuleInfo -> Maybe ModIface
modInfoIface = minf_iface
-- | Retrieve module safe haskell mode
modInfoSafe :: ModuleInfo -> SafeHaskellMode
modInfoSafe = minf_safe
#ifdef GHCI
modInfoModBreaks :: ModuleInfo -> ModBreaks
modInfoModBreaks = minf_modBreaks
#endif
isDictonaryId :: Id -> Bool
isDictonaryId id
= case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
-- | Looks up a global name: that is, any top-level name in any
-- visible module. Unlike 'lookupName', lookupGlobalName does not use
-- the interactive context, and therefore does not require a preceding
-- 'setContext'.
lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
lookupGlobalName name = withSession $ \hsc_env -> do
liftIO $ lookupTypeHscEnv hsc_env name
findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
findGlobalAnns deserialize target = withSession $ \hsc_env -> do
ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
return (findAnns deserialize ann_env target)
#ifdef GHCI
-- | get the GlobalRdrEnv for a session
getGRE :: GhcMonad m => m GlobalRdrEnv
getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
#endif
-- -----------------------------------------------------------------------------
{- ToDo: Move the primary logic here to compiler/main/Packages.lhs
-- | Return all /external/ modules available in the package database.
-- Modules from the current session (i.e., from the 'HomePackageTable') are
-- not included. This includes module names which are reexported by packages.
packageDbModules :: GhcMonad m =>
Bool -- ^ Only consider exposed packages.
-> m [Module]
packageDbModules only_exposed = do
dflags <- getSessionDynFlags
let pkgs = eltsUFM (pkgIdMap (pkgState dflags))
return $
[ mkModule pid modname
| p <- pkgs
, not only_exposed || exposed p
, let pid = packageConfigId p
, modname <- exposedModules p
++ map exportName (reexportedModules p) ]
-}
-- -----------------------------------------------------------------------------
-- Misc exported utils
dataConType :: DataCon -> Type
dataConType dc = idType (dataConWrapId dc)
-- | print a 'NamedThing', adding parentheses if the name is an operator.
pprParenSymName :: NamedThing a => a -> SDoc
pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
-- ----------------------------------------------------------------------------
#if 0
-- ToDo:
-- - Data and Typeable instances for HsSyn.
-- ToDo: check for small transformations that happen to the syntax in
-- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
-- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
-- to get from TyCons, Ids etc. to TH syntax (reify).
-- :browse will use either lm_toplev or inspect lm_interface, depending
-- on whether the module is interpreted or not.
#endif
-- Extract the filename, stringbuffer content and dynflags associed to a module
--
-- XXX: Explain pre-conditions
getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
getModuleSourceAndFlags mod = do
m <- getModSummary (moduleName mod)
case ml_hs_file $ ms_location m of
Nothing -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "No source available for module " <+> ppr mod)
Just sourceFile -> do
source <- liftIO $ hGetStringBuffer sourceFile
return (sourceFile, source, ms_hspp_opts m)
-- | Return module source as token stream, including comments.
--
-- The module must be in the module graph and its source must be available.
-- Throws a 'HscTypes.SourceError' on parse error.
getTokenStream :: GhcMonad m => Module -> m [Located Token]
getTokenStream mod = do
(sourceFile, source, flags) <- getModuleSourceAndFlags mod
let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
case lexTokenStream source startLoc flags of
POk _ ts -> return ts
PFailed span err ->
do dflags <- getDynFlags
liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
-- | Give even more information on the source than 'getTokenStream'
-- This function allows reconstructing the source completely with
-- 'showRichTokenStream'.
getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
getRichTokenStream mod = do
(sourceFile, source, flags) <- getModuleSourceAndFlags mod
let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
case lexTokenStream source startLoc flags of
POk _ ts -> return $ addSourceToTokens startLoc source ts
PFailed span err ->
do dflags <- getDynFlags
liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
-- | Given a source location and a StringBuffer corresponding to this
-- location, return a rich token stream with the source associated to the
-- tokens.
addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token]
-> [(Located Token, String)]
addSourceToTokens _ _ [] = []
addSourceToTokens loc buf (t@(L span _) : ts)
= case span of
UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts
RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts
where
(newLoc, newBuf, str) = go "" loc buf
start = realSrcSpanStart s
end = realSrcSpanEnd s
go acc loc buf | loc < start = go acc nLoc nBuf
| start <= loc && loc < end = go (ch:acc) nLoc nBuf
| otherwise = (loc, buf, reverse acc)
where (ch, nBuf) = nextChar buf
nLoc = advanceSrcLoc loc ch
-- | Take a rich token stream such as produced from 'getRichTokenStream' and
-- return source code almost identical to the original code (except for
-- insignificant whitespace.)
showRichTokenStream :: [(Located Token, String)] -> String
showRichTokenStream ts = go startLoc ts ""
where sourceFile = getFile $ map (getLoc . fst) ts
getFile [] = panic "showRichTokenStream: No source file found"
getFile (UnhelpfulSpan _ : xs) = getFile xs
getFile (RealSrcSpan s : _) = srcSpanFile s
startLoc = mkRealSrcLoc sourceFile 1 1
go _ [] = id
go loc ((L span _, str):ts)
= case span of
UnhelpfulSpan _ -> go loc ts
RealSrcSpan s
| locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
. (str ++)
. go tokEnd ts
| otherwise -> ((replicate (tokLine - locLine) '\n') ++)
. ((replicate (tokCol - 1) ' ') ++)
. (str ++)
. go tokEnd ts
where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
(tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
tokEnd = realSrcSpanEnd s
-- -----------------------------------------------------------------------------
-- Interactive evaluation
-- | Takes a 'ModuleName' and possibly a 'UnitId', and consults the
-- filesystem and package database to find the corresponding 'Module',
-- using the algorithm that is used for an @import@ declaration.
findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
let
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
--
case maybe_pkg of
Just pkg | fsToUnitId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
res <- findImportedModule hsc_env mod_name maybe_pkg
case res of
Found _ m -> return m
err -> throwOneError $ noModError dflags noSrcSpan mod_name err
_otherwise -> do
home <- lookupLoadedHomeModule mod_name
case home of
Just m -> return m
Nothing -> liftIO $ do
res <- findImportedModule hsc_env mod_name maybe_pkg
case res of
Found loc m | moduleUnitId m /= this_pkg -> return m
| otherwise -> modNotLoadedError dflags m loc
err -> throwOneError $ noModError dflags noSrcSpan mod_name err
modNotLoadedError :: DynFlags -> Module -> ModLocation -> IO a
modNotLoadedError dflags m loc = throwGhcExceptionIO $ CmdLineError $ showSDoc dflags $
text "module is not loaded:" <+>
quotes (ppr (moduleName m)) <+>
parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
-- | Like 'findModule', but differs slightly when the module refers to
-- a source file, and the file has not been loaded via 'load'. In
-- this case, 'findModule' will throw an error (module not loaded),
-- but 'lookupModule' will check to see whether the module can also be
-- found in a package, and if so, that package 'Module' will be
-- returned. If not, the usual module-not-found error will be thrown.
--
lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
lookupModule mod_name Nothing = withSession $ \hsc_env -> do
home <- lookupLoadedHomeModule mod_name
case home of
Just m -> return m
Nothing -> liftIO $ do
res <- findExposedPackageModule hsc_env mod_name Nothing
case res of
Found _ m -> return m
err -> throwOneError $ noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
case lookupUFM (hsc_HPT hsc_env) mod_name of
Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
_not_a_home_module -> return Nothing
#ifdef GHCI
-- | Check that a module is safe to import (according to Safe Haskell).
--
-- We return True to indicate the import is safe and False otherwise
-- although in the False case an error may be thrown first.
isModuleTrusted :: GhcMonad m => Module -> m Bool
isModuleTrusted m = withSession $ \hsc_env ->
liftIO $ hscCheckSafe hsc_env m noSrcSpan
-- | Return if a module is trusted and the pkgs it depends on to be trusted.
moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [UnitId])
moduleTrustReqs m = withSession $ \hsc_env ->
liftIO $ hscGetSafe hsc_env m noSrcSpan
-- | EXPERIMENTAL: DO NOT USE.
--
-- Set the monad GHCi lifts user statements into.
--
-- Checks that a type (in string form) is an instance of the
-- @GHC.GHCi.GHCiSandboxIO@ type class. Sets it to be the GHCi monad if it is,
-- throws an error otherwise.
{-# WARNING setGHCiMonad "This is experimental! Don't use." #-}
setGHCiMonad :: GhcMonad m => String -> m ()
setGHCiMonad name = withSession $ \hsc_env -> do
ty <- liftIO $ hscIsGHCiMonad hsc_env name
modifySession $ \s ->
let ic = (hsc_IC s) { ic_monad = ty }
in s { hsc_IC = ic }
getHistorySpan :: GhcMonad m => History -> m SrcSpan
getHistorySpan h = withSession $ \hsc_env ->
return $ InteractiveEval.getHistorySpan hsc_env h
obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
obtainTermFromVal bound force ty a = withSession $ \hsc_env ->
liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
obtainTermFromId bound force id = withSession $ \hsc_env ->
liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id
#endif
-- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
-- entity known to GHC, including 'Name's defined using 'runStmt'.
lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
lookupName name =
withSession $ \hsc_env ->
liftIO $ hscTcRcLookupName hsc_env name
-- -----------------------------------------------------------------------------
-- Pure API
-- | A pure interface to the module parser.
--
parser :: String -- ^ Haskell module source text (full Unicode is supported)
-> DynFlags -- ^ the flags
-> FilePath -- ^ the filename (for source locations)
-> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
parser str dflags filename =
let
loc = mkRealSrcLoc (mkFastString filename) 1 1
buf = stringToStringBuffer str
in
case unP Parser.parseModule (mkPState dflags buf loc) of
PFailed span err ->
Left (unitBag (mkPlainErrMsg dflags span err))
POk pst rdr_module ->
let (warns,_) = getMessages pst in
Right (warns, rdr_module)
| AlexeyRaga/eta | compiler/ETA/Main/GHC.hs | bsd-3-clause | 55,097 | 4 | 28 | 14,852 | 9,844 | 5,344 | 4,500 | -1 | -1 |
{-|
Module : Game.Werewolf.Variant.Standard.Engine
Description : Suite of engine messages used throughout the game.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer : public@hjwylde.com
A 'Message' is used to relay information back to either all players or a single player. This module
defines suite of engine messages used throughout the werewolf game for the 'Standard' variant.
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Game.Werewolf.Variant.Standard.Engine (
-- * Druid's turn
druidsTurnText,
-- * General
playerBootedText, playerKilledText, spitefulVillagerKilledText, zombiesReturnedToGraveText,
-- * Game over
allegianceWonText, dullahanWonText, everyoneLostText, fallenAngelWonText, necromancerWonText,
playerContributedText, playerLostText, playerRolesText, playerWonText,
-- * Hunter's turn
huntersTurnPrivateText, huntersTurnPublicText,
-- * Lynching
jesterLynchedText, noPlayerLynchedText, playerLynchedText, saintLynchedText,
scapegoatLynchedText, werewolfLynchedText,
-- * Necromancer's turn
necromancersTurnPrivateText, necromancersTurnPublicText,
-- * New game
beholderText, dullahanText, gameVariantText, newPlayerText, playersInGameText, rolesInGameText,
trueVillagerText,
-- * Oracle's turn
oraclesTurnPrivateText, oraclesTurnPublicText,
-- * Orphan's turn
orphanJoinedWerewolvesGroupText, orphanJoinedWerewolvesPrivateText, orphansTurnPrivateText,
orphansTurnPublicText,
-- * Protector's turn
protectorsTurnPrivateText, protectorsTurnPublicText,
-- * Scapegoat's turn
scapegoatsTurnText, scapegoatsTurnEndedText,
-- * Seer's turn
seersTurnPrivateText, seersTurnPublicText, alphaWolfSeenText, lycanSeenText,
-- * Sunrise
noPlayerDevouredText, playerDevouredText, playerDivinedText, playerPoisonedText, playerSeenText,
sunriseText, playerTurnedToStoneText,
-- * Sunset
sunsetText,
-- * Village Drunk's turn
villageDrunkJoinedVillageText, villageDrunkJoinedWerewolvesGroupText,
villageDrunkJoinedWerewolvesPrivateText, villageDrunksTurnText,
-- * Village's turn
villagesTurnText,
-- * Werewolves' turn
firstWerewolvesTurnText, werewolvesTurnPrivateText, werewolvesTurnPublicText,
-- * Witch's turn
healText, passText, poisonText, witchsTurnText,
) where
import Control.Arrow
import Control.Lens.Extra
import Data.List.Extra
import Data.String.Humanise
import Data.String.Interpolate.Extra
import Data.Text (Text)
import qualified Data.Text as T
import Game.Werewolf
import Game.Werewolf.Message
druidsTurnText :: Text
druidsTurnText = [iFile|variant/standard/engine/druids-turn/start.txt|]
playerBootedText :: Player -> Text
playerBootedText player = [iFile|variant/standard/engine/general/player-booted.txt|]
playerKilledText :: Text
playerKilledText = [iFile|variant/standard/engine/general/player-killed.txt|]
spitefulVillagerKilledText :: Game -> Text
spitefulVillagerKilledText game = [iFile|variant/standard/engine/general/spiteful-villager-killed.txt|]
zombiesReturnedToGraveText :: Game -> Text
zombiesReturnedToGraveText game = [iFile|variant/standard/engine/general/zombies-returned-to-grave.txt|]
allegianceWonText :: Allegiance -> Text
allegianceWonText allegiance = [iFile|variant/standard/engine/game-over/allegiance-won.txt|]
dullahanWonText :: Game -> Text
dullahanWonText game = [iFile|variant/standard/engine/game-over/dullahan-won.txt|]
everyoneLostText :: Text
everyoneLostText = [iFile|variant/standard/engine/game-over/everyone-lost.txt|]
fallenAngelWonText :: Text
fallenAngelWonText = [iFile|variant/standard/engine/game-over/fallen-angel-won.txt|]
necromancerWonText :: Text
necromancerWonText = [iFile|variant/standard/engine/game-over/necromancer-won.txt|]
playerContributedText :: Text
playerContributedText = [iFile|variant/standard/engine/game-over/player-contributed.txt|]
playerLostText :: Text
playerLostText = [iFile|variant/standard/engine/game-over/player-lost.txt|]
playerRolesText :: Game -> Text
playerRolesText game = [iFile|variant/standard/engine/game-over/player-roles.txt|]
playerWonText :: Text
playerWonText = [iFile|variant/standard/engine/game-over/player-won.txt|]
huntersTurnPrivateText :: Text
huntersTurnPrivateText = [iFile|variant/standard/engine/hunters-turn/start-private.txt|]
huntersTurnPublicText :: Game -> Text
huntersTurnPublicText game = [iFile|variant/standard/engine/hunters-turn/start-public.txt|]
where
hunter = game ^?! players . hunters
jesterLynchedText :: Game -> Text
jesterLynchedText game = [iFile|variant/standard/engine/lynching/jester-lynched.txt|]
where
jester = game ^?! players . jesters
noPlayerLynchedText :: Text
noPlayerLynchedText = [iFile|variant/standard/engine/lynching/no-player-lynched.txt|]
playerLynchedText :: Player -> Text
playerLynchedText player = [iFile|variant/standard/engine/lynching/player-lynched.txt|]
saintLynchedText :: [Player] -> Text
saintLynchedText voters = [iFile|variant/standard/engine/lynching/saint-lynched.txt|]
scapegoatLynchedText :: Game -> Text
scapegoatLynchedText game = [iFile|variant/standard/engine/lynching/scapegoat-lynched.txt|]
where
scapegoat = game ^?! players . scapegoats
werewolfLynchedText :: Player -> Text
werewolfLynchedText werewolf = [iFile|variant/standard/engine/lynching/werewolf-lynched.txt|]
necromancersTurnPrivateText :: Text
necromancersTurnPrivateText = [iFile|variant/standard/engine/necromancers-turn/start-private.txt|]
necromancersTurnPublicText :: Text
necromancersTurnPublicText = [iFile|variant/standard/engine/necromancers-turn/start-public.txt|]
beholderText :: Game -> Text
beholderText game = [iFile|variant/standard/engine/new-game/beholder.txt|]
where
seer = game ^?! players . seers
dullahanText :: Game -> Text
dullahanText game = [iFile|variant/standard/engine/new-game/dullahan.txt|]
gameVariantText :: Game -> Text
gameVariantText game = [iFile|variant/standard/engine/new-game/game-variant.txt|]
newPlayerText :: Player -> Text
newPlayerText player = [iFile|variant/standard/engine/new-game/new-player.txt|]
playersInGameText :: Game -> Text
playersInGameText game = [iFile|variant/standard/engine/new-game/players-in-game.txt|]
rolesInGameText :: Game -> Text
rolesInGameText game = [iFile|variant/standard/engine/new-game/roles-in-game.txt|]
where
roles = game ^.. players . traverse . role
roleCounts = map (head &&& length) (groupSortOn humanise roles)
totalBalance = sumOf (traverse . balance) roles
trueVillagerText :: Game -> Text
trueVillagerText game = [iFile|variant/standard/engine/new-game/true-villager.txt|]
where
trueVillager = game ^?! players . trueVillagers
oraclesTurnPrivateText :: Text
oraclesTurnPrivateText = [iFile|variant/standard/engine/oracles-turn/start-private.txt|]
oraclesTurnPublicText :: Text
oraclesTurnPublicText = [iFile|variant/standard/engine/oracles-turn/start-public.txt|]
orphanJoinedWerewolvesGroupText :: Game -> Text
orphanJoinedWerewolvesGroupText game = [iFile|variant/standard/engine/orphans-turn/player-joined-werewolves-group.txt|]
where
orphan = game ^?! players . orphans
orphanJoinedWerewolvesPrivateText :: Game -> Text
orphanJoinedWerewolvesPrivateText game = [iFile|variant/standard/engine/orphans-turn/player-joined-werewolves-private.txt|]
where
orphan = game ^?! players . orphans
werewolves = game ^.. players . traverse . alive . filtered (is werewolf) \\ [orphan]
orphansTurnPrivateText :: Text
orphansTurnPrivateText = [iFile|variant/standard/engine/orphans-turn/start-private.txt|]
orphansTurnPublicText :: Text
orphansTurnPublicText = [iFile|variant/standard/engine/orphans-turn/start-public.txt|]
protectorsTurnPrivateText :: Text
protectorsTurnPrivateText = [iFile|variant/standard/engine/protectors-turn/start-private.txt|]
protectorsTurnPublicText :: Text
protectorsTurnPublicText = [iFile|variant/standard/engine/protectors-turn/start-public.txt|]
scapegoatsTurnText :: Game -> Text
scapegoatsTurnText game = [iFile|variant/standard/engine/scapegoats-turn/start.txt|]
where
scapegoat = game ^?! players . scapegoats
scapegoatsTurnEndedText :: Game -> Text
scapegoatsTurnEndedText game = [iFile|variant/standard/engine/scapegoats-turn/end.txt|]
seersTurnPrivateText :: Text
seersTurnPrivateText = [iFile|variant/standard/engine/seers-turn/start-private.txt|]
seersTurnPublicText :: Text
seersTurnPublicText = [iFile|variant/standard/engine/seers-turn/start-public.txt|]
alphaWolfSeenText :: Player -> Text
alphaWolfSeenText alphaWolf = [iFile|variant/standard/engine/sunrise/alpha-wolf-seen.txt|]
lycanSeenText :: Player -> Text
lycanSeenText lycan = [iFile|variant/standard/engine/sunrise/lycan-seen.txt|]
noPlayerDevouredText :: Text
noPlayerDevouredText = [iFile|variant/standard/engine/sunrise/no-player-devoured.txt|]
playerDevouredText :: Player -> Text
playerDevouredText player = [iFile|variant/standard/engine/sunrise/player-devoured.txt|]
playerDivinedText :: Player -> Text
playerDivinedText player = [iFile|variant/standard/engine/sunrise/player-divined.txt|]
playerPoisonedText :: Player -> Text
playerPoisonedText player = [iFile|variant/standard/engine/sunrise/player-poisoned.txt|]
playerSeenText :: Player -> Text
playerSeenText player = [iFile|variant/standard/engine/sunrise/player-seen.txt|]
where
article = if is loner player then "" else "the " :: Text
sunriseText :: Text
sunriseText = [iFile|variant/standard/engine/sunrise/start.txt|]
playerTurnedToStoneText :: Player -> Text
playerTurnedToStoneText player = [iFile|variant/standard/engine/sunrise/player-turned-to-stone.txt|]
sunsetText :: Text
sunsetText = [iFile|variant/standard/engine/sunset/start.txt|]
villageDrunkJoinedVillageText :: Text
villageDrunkJoinedVillageText = [iFile|variant/standard/engine/village-drunks-turn/player-joined-village.txt|]
villageDrunkJoinedWerewolvesGroupText :: Game -> Text
villageDrunkJoinedWerewolvesGroupText game = [iFile|variant/standard/engine/village-drunks-turn/player-joined-werewolves-group.txt|]
where
villageDrunk = game ^?! players . villageDrunks
villageDrunkJoinedWerewolvesPrivateText :: Game -> Text
villageDrunkJoinedWerewolvesPrivateText game = [iFile|variant/standard/engine/village-drunks-turn/player-joined-werewolves-private.txt|]
where
villageDrunk = game ^?! players . villageDrunks
werewolves = game ^.. players . traverse . alive . filtered (is werewolf) \\ [villageDrunk]
villageDrunksTurnText :: Text
villageDrunksTurnText = [iFile|variant/standard/engine/village-drunks-turn/start.txt|]
villagesTurnText :: Text
villagesTurnText = [iFile|variant/standard/engine/villages-turn/start.txt|]
firstWerewolvesTurnText :: Player -> Game -> Text
firstWerewolvesTurnText player game = [iFile|variant/standard/engine/werewolves-turn/start-first-round-private.txt|]
where
werewolves = game ^.. players . traverse . alive . filtered (is werewolf)
werewolvesTurnPrivateText :: Text
werewolvesTurnPrivateText = [iFile|variant/standard/engine/werewolves-turn/start-private.txt|]
werewolvesTurnPublicText :: Text
werewolvesTurnPublicText = [iFile|variant/standard/engine/werewolves-turn/start-public.txt|]
healText :: Game -> Text
healText game = [iFile|variant/standard/engine/witchs-turn/heal.txt|]
where
victim = game ^?! votee
passText :: Text
passText = [iFile|variant/standard/engine/witchs-turn/pass.txt|]
poisonText :: Text
poisonText = [iFile|variant/standard/engine/witchs-turn/poison.txt|]
witchsTurnText :: Text
witchsTurnText = [iFile|variant/standard/engine/witchs-turn/start.txt|]
| hjwylde/werewolf | app/Game/Werewolf/Variant/Standard/Engine.hs | bsd-3-clause | 11,911 | 0 | 11 | 1,481 | 1,795 | 1,141 | 654 | -1 | -1 |
module Graphics.BlankSlate.Prim.Buffer where
import Foreign (allocaArray,withArrayLen,peekArray)
import Graphics.Rendering.OpenGL.Raw.Core31
-- Data Buffers ----------------------------------------------------------------
newtype Buffer = Buffer { getBuffer :: GLuint }
deriving (Show)
-- | Generate a single buffer.
genBuffer :: IO Buffer
genBuffer = do
bufs <- genBuffers 1
case bufs of
[buf] -> return buf
_ -> fail "genBuffer: Unexpected number of results"
-- | Gen many buffers all at once.
genBuffers :: Int -> IO [Buffer]
genBuffers n = allocaArray n $ \ ptr -> do
glGenBuffers (fromIntegral n) ptr
map Buffer `fmap` peekArray n ptr
deleteBuffer :: Buffer -> IO ()
deleteBuffer buf = deleteBuffers [buf]
-- | Free a list of buffer objects.
deleteBuffers :: [Buffer] -> IO ()
deleteBuffers bufs = withArrayLen (map getBuffer bufs) $ \ len ptr ->
glDeleteBuffers (fromIntegral len) ptr
bindBuffer :: GLenum -> Buffer -> IO ()
bindBuffer name = glBindBuffer name . getBuffer
unbindBuffer :: GLenum -> IO ()
unbindBuffer name = bindBuffer name (Buffer 0)
| elliottt/blank-slate | src/Graphics/BlankSlate/Prim/Buffer.hs | bsd-3-clause | 1,095 | 0 | 11 | 195 | 323 | 169 | 154 | 24 | 2 |
module BodeShooting where
import qualified Data.Matrix as M
import qualified Data.Vector as V
import Function
import Library
import SodeRungeKutta
compute :: (Vector, FMatrix, Matrix) -> Either ComputeError Matrix
compute (domain, equations, bounds) = do
eta3' <- eta3
integrate eta3' (zeta eta3')
where
[[a, b, c ], [d, e, f ]] = M.toLists equations
[[p, q, r1], [s, t, r2]] = M.toLists bounds
integrate eta zeta = SodeRungeKutta.compute (domain V.! 1 / 100, M.fromLists
[ [ Function "a(x0)x1 + b(x0)x2 + c(x0)" (linearFunction a b c)
, Function "const" (Right . const eta)
]
, [ Function "a(x0)x1 + b(x0)x2 + c(x0)" (linearFunction d e f)
, Function "const" (Right . const zeta)
]
])
eta1 = domain V.! 0
eta2 = domain V.! 1
eta3 = do
psi_eta1 <- psi eta1
psi_eta2 <- psi eta2
return $ eta2 - (eta2 - eta1) * (psi_eta2) / (psi_eta2 - psi_eta1)
zeta eta = (r1 - p * eta) / q
psi eta = do
uvs <- integrate eta (zeta eta)
let [_, u, v] = V.toList $ last $ M.toRows $ uvs
return $ s * u + t * v - r2
linearFunction a b c v = do
ax <- runFunction a v
bx <- runFunction b v
cx <- runFunction c v
return $ ax * (v V.! 1) + bx * (v V.! 2) + cx
| hrsrashid/nummet | lib/BodeShooting.hs | bsd-3-clause | 1,314 | 0 | 15 | 405 | 557 | 292 | 265 | 33 | 1 |
{-# LANGUAGE EmptyCase #-}
module Language.BCoPL.DataLevel.ML1 (
-- * Types
Val(..)
, Exp(..)
-- * Utilities
-- , operator
-- , loperand
-- , roperand
) where
import Data.Char (isDigit,toLower,digitToInt)
import Text.ParserCombinators.ReadP
data Val = Int Int
| Bool Bool
deriving (Eq)
instance Show Val where
show (Int n) = show n
show (Bool b) = map toLower (show b)
instance Read Val where
readsPrec _ = readP_to_S pVal
pVal :: ReadP Val
pVal = skipSpaces >> (pInt +++ pBool)
pInt = pNegInt +++ pPosInt
pNegInt = char '-' >> pPosInt >>= \ (Int n) -> return (Int (negate n))
pPosInt = many1 (satisfy isDigit) >>= return . Int . foldl ((+) . (10 *)) 0 . map digitToInt
pBool = pFalse +++ pTrue
pFalse = string "false" >> return (Bool False)
pTrue = string "true" >> return (Bool True)
data Exp = Val Val
| Exp :+: Exp
| Exp :-: Exp
| Exp :*: Exp
| Exp :<: Exp
| IF Exp Exp Exp
deriving (Eq)
{- -}
instance Show Exp where
show e = case e of
Val v -> show v
e1 :+: e2 -> show e1 ++ " + " ++ show e2
e1 :-: e2 -> show e1 ++ " - " ++ show e2
e1 :*: e2 -> show' e1 ++ " * " ++ show' e2
e1 :<: e2 -> show e1 ++ " < " ++ show e2
IF e1 e2 e3 -> "if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show e3
where
show' e' = case e' of
e1' :+: e2' -> "("++show e'++")"
e1' :-: e2' -> "("++show e'++")"
_ -> show e'
-- -}
{- -
instance Show Exp where
show e = case e of
Val v -> show v
e1 :+: e2 -> "(" ++ show e1 ++ " + " ++ show e2 ++ ")"
e1 :-: e2 -> "(" ++ show e1 ++ " - " ++ show e2 ++ ")"
e1 :*: e2 -> "(" ++ show e1 ++ " * " ++ show e2 ++ ")"
e1 :<: e2 -> "(" ++ show e1 ++ " < " ++ show e2 ++ ")"
IF e1 e2 e3 -> "(" ++ "if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show e3 ++")"
-- -}
instance Read Exp where
readsPrec _ = readP_to_S expr1
expr1 :: ReadP Exp
expr1 = ifexpr +++ binop +++ expr2
expr2 :: ReadP Exp
expr2 = chainl1 expr3 cmpop
expr3 :: ReadP Exp
expr3 = chainl1 expr4 addop
expr4 :: ReadP Exp
expr4 = chainl1 aexpr mulop
aexpr :: ReadP Exp
aexpr = val +++ parens expr1
ifexpr :: ReadP Exp
ifexpr = do
{ skipSpaces
; string "if"
; skipSpaces
; e1 <- expr1
; skipSpaces
; string "then"
; skipSpaces
; e2 <- expr1
; skipSpaces
; string "else"
; skipSpaces
; e3 <- expr1
; return $ IF e1 e2 e3
}
binop :: ReadP Exp
binop = cmpexp +++ addexp +++ mulexp
cmpexp :: ReadP Exp
cmpexp = do { skipSpaces
; e1 <- expr3
; op <- cmpop
; e2 <- ifexpr
; skipSpaces
; return (op e1 e2)
}
addexp :: ReadP Exp
addexp = do { skipSpaces
; e1 <- expr4
; op <- addop
; e2 <- ifexpr
; skipSpaces
; return (op e1 e2)
}
mulexp :: ReadP Exp
mulexp = do { skipSpaces
; e1 <- aexpr
; op <- mulop
; e2 <- ifexpr
; skipSpaces
; return (op e1 e2)
}
cmpop :: ReadP (Exp -> Exp -> Exp)
cmpop = do { skipSpaces
; string "<"
; skipSpaces
; return (:<:)
}
addop :: ReadP (Exp -> Exp -> Exp)
addop = do { skipSpaces
; op <- string "+" +++ string "-"
; skipSpaces
; return (if op == "+" then (:+:) else (:-:))
}
mulop :: ReadP (Exp -> Exp -> Exp)
mulop = do { skipSpaces
; string "*"
; skipSpaces
; return (:*:)
}
val :: ReadP Exp
val = pVal >>= return . Val
parens :: ReadP a -> ReadP a
parens = between (char '(') (char ')')
| nobsun/hs-bcopl | src/Language/BCoPL/DataLevel/ML1.hs | bsd-3-clause | 3,721 | 0 | 14 | 1,315 | 1,259 | 647 | 612 | 110 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett 2013
-- License : BSD3
-- Maintainer: Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Control.Task.Monad
( Task(..), (|>>)
, Env(..)
, dynamicWind
, done
, mask
, MonadTask(..)
-- * Stacks
, Stack(Empty)
, switch, rewind, unwind
) where
import Control.Applicative
import Control.Exception as Exception hiding (mask)
import Control.Exception.Lens as Lens
import Control.Lens
import Control.Monad
import Control.Monad.CatchIO as CatchIO
import Control.Monad.Cont.Class
import Control.Monad.Error.Class
import Control.Monad.IO.Class
import Control.Monad.Cont
import Control.Monad.State.Lazy as Lazy
import Control.Monad.State.Strict as Strict
import Control.Monad.Writer.Lazy as Lazy
import Control.Monad.Writer.Strict as Strict
import Control.Monad.Reader as Reader
import Control.Task.STM
import Data.Typeable
import GHC.Prim
data EmptyTask = EmptyTask deriving (Show,Typeable)
instance Exception EmptyTask
type Depth = Int
data Stack
= Frame
{ _frameDepth :: {-# UNPACK #-} !Depth
, _frameRewind :: IO ()
, _frameUnwind :: IO ()
, _frameNext :: Stack }
| Empty
depth :: Stack -> Int
depth (Frame i _ _ _) = i
depth Empty = 0
data Env = Env
{ envHandler :: SomeException -> IO ()
, envBackground :: Stack -> IO ()
, envSpawn :: Task () -> IO ()
, envStack :: Stack
}
newtype Task a = Task { runTask :: (a -> IO ()) -> Env -> IO () }
instance Functor Task where
fmap f (Task m) = Task $ \k -> m (k . f)
{-# INLINE fmap #-}
instance Applicative Task where
pure a = Task $ \kp _ -> kp a
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance Monad Task where
return a = Task $ \kp _ -> kp a
{-# INLINE return #-}
m >>= f = Task $ \kp h -> runTask m (\a -> runTask (f a) kp h) h
{-# INLINE (>>=) #-}
fail s = Task $ \_ h -> envHandler h (_ErrorCall # s)
{-# INLINE fail #-}
instance MonadIO Task where
liftIO m = Task $ \kp e -> Exception.try m >>= either (envHandler e) kp
{-# INLINE liftIO #-}
instance MonadError SomeException Task where
throwError e = Task $ \_ env -> envHandler env e
{-# INLINE throwError #-}
Task m `catchError` f = Task $ \kp e -> m kp e { envHandler = \ se -> runTask (f se) kp e }
{-# INLINE catchError #-}
instance MonadCatchIO Task where
catch (Task m) f = Task $ \kp e ->
m kp e {
envHandler = \ se -> case cast se of
Just x -> runTask (f x) kp e
Nothing -> envHandler e se
}
{-# INLINE catch #-}
-- TODO: figure out a better story for these.
block (Task m) = Task $ \kp e -> Exception.block (m kp e)
-- block = dynamicWind Exception.block Exception.unblock
{-# INLINE block #-}
unblock (Task m) = Task $ \kp e -> Exception.unblock (m kp e)
-- unblock = dynamicWind Exception.unblock Exception.block
{-# INLINE unblock #-}
instance Alternative Task where
empty = Task $ \_ e -> envHandler e (toException EmptyTask)
{-# INLINE empty #-}
Task m <|> Task n = Task $ \kp e ->
m kp e { envHandler = \_ -> n kp e }
instance MonadPlus Task where
mzero = empty
{-# INLINE mzero #-}
mplus (Task m) (Task n) = Task $ \kp e ->
m kp e { envHandler = \_ -> n kp e }
{-# INLINE mplus #-}
done :: Task a
done = Task $ \_ e -> envBackground e (envStack e)
{-# INLINE done #-}
dynamicWind :: IO () -> IO () -> Task a -> Task a
dynamicWind before after (Task m) = Task $ \kp e@Env { envStack = s } -> do
before
m kp $! e { envStack = Frame (depth s) before after $! s }
{-# INLINE dynamicWind #-}
-- switch contexts
switch :: Stack -> Stack -> IO ()
switch l@(Frame i _ a l') r@(Frame j b _ r') = case compare i j of
LT -> switch l r' >> b
EQ -> case reallyUnsafePtrEquality# l r of
1# -> return ()
_ -> a >> switch l' r' >> b
GT -> a >> switch l' r
switch l Empty = unwind l
switch Empty r = rewind r
{-# INLINEABLE switch #-}
unwind :: Stack -> IO ()
unwind (Frame _ _ a as) = a >> unwind as
unwind Empty = return ()
{-# INLINEABLE unwind #-}
rewind :: Stack -> IO ()
rewind (Frame _ b _ bs) = rewind bs >> b
rewind Empty = return ()
{-# INLINEABLE rewind #-}
-- | The continuation is assumed to be single shot!
instance MonadCont Task where
callCC h = Task $ \kp e@Env { envStack = s } ->
let go x = Task $ \ _ Env { envStack = s' } -> switch s' s >> kp x
in runTask (h go) kp e
{-# INLINE callCC #-}
-- | A generalized 'mask' for 'MonadCatchIO'
mask :: MonadCatchIO m => ((forall a. m a -> m a) -> m b) -> m b
mask f = liftIO getMaskingState >>= \b -> case b of
Unmasked -> CatchIO.block $ f CatchIO.unblock
_ -> f id
{-# INLINE mask #-}
#ifndef HLINT
class Monad m => MonadTask m where
spawn :: Task () -> m ()
default spawn :: (MonadTrans t, MonadTask n, m ~ t n) => Task () -> m ()
spawn = lift . spawn
{-# INLINE spawn #-}
#endif
instance MonadTask Task where
spawn t = Task $ \kp e -> do
envSpawn e t
kp ()
{-# INLINE spawn #-}
(|>>) :: MonadTask m => Task () -> m b -> m b
m |>> r = spawn m >> r
instance MonadTask m => MonadTask (Strict.StateT s m)
instance MonadTask m => MonadTask (Lazy.StateT s m)
instance MonadTask m => MonadTask (ReaderT e m)
instance (MonadTask m, Monoid w) => MonadTask (Strict.WriterT w m)
instance (MonadTask m, Monoid w) => MonadTask (Lazy.WriterT w m)
instance MonadTask m => MonadTask (ContT r m)
instance MonadSTM Task where
stm = liftIO . stm
{-# INLINE stm #-}
newTV = liftIO . newTV
{-# INLINE newTV #-}
readTV = liftIO . readTV
{-# INLINE readTV #-}
newTMV = liftIO . newTMV
{-# INLINE newTMV #-}
newEmptyTMV = liftIO newEmptyTMV
{-# INLINE newEmptyTMV #-}
newTC = liftIO newTC
{-# INLINE newTC #-}
| ekmett/tasks | src/Control/Task/Monad.hs | bsd-3-clause | 6,136 | 0 | 17 | 1,397 | 2,140 | 1,139 | 1,001 | 166 | 4 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE StandaloneDeriving #-}
import Generics.Instant
import Generics.Instant.TH
import Generics.Instant.Functions
-------------------------------------------------------------------------------
-- Simple Datatype
-------------------------------------------------------------------------------
-- Example datatype
data Exp = Const Int | Plus Exp Exp
data Const
data Plus
instance Constructor Const where conName _ = "Const"
instance Constructor Plus where conName _ = "Plus"
-- Representable instance
instance Representable Exp where
type Rep Exp = C Const (Var Int) :+: C Plus (Rec Exp :*: Rec Exp)
from (Const n) = L (C (Var n))
from (Plus e e') = R (C (Rec e :*: Rec e'))
to (L (C (Var n))) = Const n
to (R (C (Rec e :*: Rec e'))) = Plus e e'
exp1 = Plus (Const 1) (Const 2)
exp2 = Plus exp1 (Const 3)
instance GEq Exp where geq = geqDefault
testExp1 :: (Bool, Bool)
testExp1 = (geq exp2 exp2, geq exp1 exp2)
instance Empty Exp where empty' = empty
testExp2 :: Exp
testExp2 = empty
instance GShow Exp where gshow = gshowDefault
instance Show Exp where show = gshow -- convenience
testExp3 :: String
testExp3 = show exp2
{-
instance Update Exp where update' = update
instance MapOn Int where mapOn = (+1)
testExp4 :: Exp
testExp4 = update exp2
-}
-------------------------------------------------------------------------------
-- Mutually recursive datatypes
-------------------------------------------------------------------------------
data Decl = None | Seq Decl Decl | Assign String Expr
data Expr = V String | Lam String Expr | App Expr Expr | Let Decl Expr
-- Using TH
$(deriveAll ''Decl)
$(deriveAll ''Expr)
decls = Seq (Assign "x" (Lam "z" (V "z"))) (Assign "y" (V "x"))
expr = Let decls (App (V "x") (V "y"))
instance GShow Expr where gshow = gshowDefault
instance GShow Decl where gshow = gshowDefault
instance Show Expr where show = gshow -- convenience
instance Show Decl where show = gshow -- convenience
testAST1 :: String
testAST1 = show expr
instance Empty Expr where empty' = empty
instance Empty Decl where empty' = empty
testAST2 :: Expr
testAST2 = empty
testAST3 :: Decl
testAST3 = empty
instance GEq Expr where geq = geqDefault
instance GEq Decl where geq = geqDefault
testAST4 :: Bool
testAST4 = geq expr expr
{-
instance Update Decl where update' = update
instance Update Expr where update' = update
instance MapOn [Char] where mapOn _ = "a"
testAST5 :: Decl
testAST5 = update decls
testAST6 :: Expr
testAST6 = update expr
-}
-------------------------------------------------------------------------------
-- Equality constraints
-------------------------------------------------------------------------------
-- Example 1
-- G1 has one index
data G1 :: * -> * where
G11 :: Int -> G1 Int
G12 :: G1 Int -> G1 a
$(deriveAll ''G1)
-- Generic function instances
simplInstance ''GShow ''G1 'gshow 'gshowDefault
gadtInstance ''GEnum ''G1 'genum' 'genum
-- Testing
gshowG1 = gshow (G12 (G11 3))
genumG1 = gshow (take 100 $ genum :: [G1 Int])
-- Example 2: vectors
data Ze
data Su n
-- Vec has a parameter 'a' and an index 'n'
data Vec a :: * -> * where
Nil :: Vec a Ze
Cons :: a -> Vec a n -> Vec a (Su n)
deriveAll ''Vec
-- Generic function instances
-- These are not automatically generated because of the parameter `a`
-- The user needs to supply the instance context
instance (GShow a) => GShow (Vec a n) where gshow = gshowDefault
instance (GEnum a, GEnum (Vec a n)) => GEnum (Vec a (Su n)) where
genum' = genum
instance (GEnum a) => GEnum (Vec a Ze) where
genum' = genum
-- Testing
gshowVec = gshow (Cons 'p' Nil)
genumVec = gshow . take 10 $ (genum :: [Vec Int (Su (Su Ze))])
-- Example 3: terms
-- Term has one index
data Term :: * -> * where
Lit :: Int -> Term Int
IsZero :: Term Int -> Term Bool
Pair :: Term a -> Term b -> Term (a,b)
If :: Term Bool -> Term a -> Term a -> Term a
deriveAll ''Term
-- Generic function instances
simplInstance ''GShow ''Term 'gshow 'gshowDefault
gadtInstance ''GEnum ''Term 'genum' 'genum
-- Testing
gshowTerm = gshow (Pair (If (IsZero (Lit 1)) (Lit 2) (Lit 0)) (Lit 1))
genumTerm = gshow (take 10 (genum :: [Term (Bool,Int)]))
-- Example 4: Fin
data Fin n where
FZe :: Fin (Su n)
FSu :: Fin n -> Fin (Su n)
deriveAll ''Fin
simplInstance ''GShow ''Fin 'gshow 'gshowDefault
gadtInstance ''GEnum ''Fin 'genum' 'genum
-- We need to give this instance manually because the index Ze is never
-- used in the datatype definition
instance GEnum (Fin Ze) where genum' = []
gshowFin = gshow (FSu (FSu FZe))
genumFin = gshow (take 10 (genum :: [Fin (Su (Su Ze))]))
| bergmark/instant-generics | examples/Test.hs | bsd-3-clause | 5,347 | 0 | 14 | 1,255 | 1,511 | 801 | 710 | -1 | -1 |
module State.Reactions
( asyncFetchReactionsForPost
, addReactions
, removeReaction
)
where
import Prelude ()
import Prelude.MH
import qualified Data.Map.Strict as Map
import Lens.Micro.Platform
import Network.Mattermost.Endpoints
import Network.Mattermost.Lenses
import Network.Mattermost.Types
import State.Async
import Types
asyncFetchReactionsForPost :: ChannelId -> Post -> MH ()
asyncFetchReactionsForPost cId p
| not (p^.postHasReactionsL) = return ()
| otherwise = doAsyncChannelMM Normal cId
(\s _ _ -> fmap toList (mmGetReactionsForPost (p^.postIdL) s))
addReactions
addReactions :: ChannelId -> [Reaction] -> MH ()
addReactions cId rs = csChannel(cId).ccContents.cdMessages %= fmap upd
where upd msg = msg & mReactions %~ insertAll (msg^.mMessageId)
insert mId r
| mId == Just (MessagePostId (r^.reactionPostIdL)) = Map.insertWith (+) (r^.reactionEmojiNameL) 1
| otherwise = id
insertAll mId msg = foldr (insert mId) msg rs
removeReaction :: Reaction -> ChannelId -> MH ()
removeReaction r cId = csChannel(cId).ccContents.cdMessages %= fmap upd
where upd m | m^.mMessageId == Just (MessagePostId $ r^.reactionPostIdL) =
m & mReactions %~ (Map.insertWith (+) (r^.reactionEmojiNameL) (-1))
| otherwise = m
| aisamanra/matterhorn | src/State/Reactions.hs | bsd-3-clause | 1,403 | 0 | 15 | 345 | 456 | 237 | 219 | -1 | -1 |
import Network.UDP.Pal
import Shared
main :: IO ()
main = do
echoServer serverName serverPort 4096
threadDelaySec 1000000
| lukexi/udp-pal | exec/Server.hs | bsd-3-clause | 147 | 0 | 7 | 42 | 41 | 20 | 21 | 6 | 1 |
module Lang.LF.ChangeT where
data ChangeT m a
= Unchanged a
| Changed (m a)
instance Functor m => Functor (ChangeT m) where
fmap f (Unchanged a) = Unchanged (f a)
fmap f (Changed x) = Changed (fmap f x)
instance Applicative m => Applicative (ChangeT m) where
pure = Unchanged
(Unchanged f) <*> (Unchanged x) = Unchanged (f x)
(Unchanged f) <*> (Changed x) = Changed (pure f <*> x)
(Changed f) <*> (Unchanged x) = Changed (f <*> pure x)
(Changed f) <*> (Changed x) = Changed (f <*> x)
instance Monad m => Monad (ChangeT m) where
return = Unchanged
Unchanged x >>= f = f x
Changed x >>= f = Changed (x >>= runChangeT . f)
runChangeT :: Monad m => ChangeT m a -> m a
runChangeT (Unchanged x) = return x
runChangeT (Changed x) = x
mapChange :: Monad m => (a -> b) -> (a -> m b) -> ChangeT m a -> ChangeT m b
mapChange f _ (Unchanged x) = Unchanged (f x)
mapChange _ g (Changed y) = Changed (g =<< y)
onChange :: Monad m => b -> (a -> m b) -> ChangeT m a -> ChangeT m b
onChange x = mapChange (const x)
| robdockins/canonical-lf | src/Lang/LF/ChangeT.hs | bsd-3-clause | 1,043 | 0 | 10 | 252 | 558 | 271 | 287 | 25 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : ./Maude/AS_Maude.hs
Description : Abstract Maude Syntax
Copyright : (c) DFKI GmbH 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : ariesco@fdi.ucm.es
Stability : experimental
Portability : portable
The abstract syntax of maude. Basic specs are a list of statements excluding
imports. Sentences are equations, membership axioms, and rules. Sort, subsort
and operations should be converted to signature.
Because maude parses and typechecks an input string in one go, basic specs for
the logic instance are just a wrapped string that is created by a simple
parser.
-}
module Maude.AS_Maude where
import Common.Id hiding (Id)
import Common.Doc (specBraces, text)
import Common.DocUtils (Pretty (..))
import Data.Data
-- * Types
newtype MaudeText = MaudeText String deriving (Show, Typeable)
instance Pretty MaudeText where
pretty (MaudeText s) = specBraces $ text s
instance GetRange MaudeText
type Qid = Token
data Spec = SpecMod Module
| SpecTh Module
| SpecView View
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Module = Module ModId [Parameter] [Statement]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data View = View ModId ModExp ModExp [Renaming]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Parameter = Parameter Sort ModExp
deriving (Show, Read, Ord, Eq, Typeable, Data)
data ModExp = ModExp ModId
| SummationModExp ModExp ModExp
| RenamingModExp ModExp [Renaming]
| InstantiationModExp ModExp [ViewId]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Renaming = SortRenaming Sort Sort
| LabelRenaming LabelId LabelId
| OpRenaming1 OpId ToPartRenaming
| OpRenaming2 OpId [Type] Type ToPartRenaming
| TermMap Term Term
deriving (Show, Read, Ord, Eq, Typeable, Data)
data ToPartRenaming = To OpId [Attr]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Statement = ImportStmnt Import
| SortStmnt Sort
| SubsortStmnt SubsortDecl
| OpStmnt Operator
| EqStmnt Equation
| MbStmnt Membership
| RlStmnt Rule
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Import = Including ModExp
| Extending ModExp
| Protecting ModExp
deriving (Show, Read, Ord, Eq, Typeable, Data)
data SubsortDecl = Subsort Sort Sort
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Operator = Op OpId [Type] Type [Attr]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Membership = Mb Term Sort [Condition] [StmntAttr]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Equation = Eq Term Term [Condition] [StmntAttr]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Rule = Rl Term Term [Condition] [StmntAttr]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Condition = EqCond Term Term
| MbCond Term Sort
| MatchCond Term Term
| RwCond Term Term
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Attr = Assoc
| Comm
| Idem
| Iter
| Id Term
| LeftId Term
| RightId Term
| Strat [Int]
| Memo
| Prec Int
| Gather [Qid]
| Format [Qid]
| Ctor
| Config
| Object
| Msg
| Frozen [Int]
| Poly [Int]
| Special [Hook]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data StmntAttr = Label Qid
| Metadata String
| Owise
| Nonexec
| Print [Qid]
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Hook = IdHook Qid [Qid]
| OpHook Qid Qid [Qid] Qid
| TermHook Qid Term
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Term = Const Qid Type
| Var Qid Type
| Apply Qid [Term] Type
deriving (Show, Read, Ord, Eq, Typeable, Data)
data Type = TypeSort Sort
| TypeKind Kind
deriving (Show, Read, Ord, Eq, Typeable, Data)
newtype Sort = SortId Qid
deriving (Show, Read, Ord, Eq, Typeable, Data)
newtype Kind = KindId Qid
deriving (Show, Read, Ord, Eq, Typeable, Data)
newtype ParamId = ParamId Qid
deriving (Show, Read, Ord, Eq, Typeable, Data)
newtype ViewId = ViewId Qid
deriving (Show, Read, Ord, Eq, Typeable, Data)
newtype ModId = ModId Qid
deriving (Show, Read, Ord, Eq, Typeable, Data)
newtype LabelId = LabelId Qid
deriving (Show, Read, Ord, Eq, Typeable, Data)
newtype OpId = OpId Qid
deriving (Show, Read, Ord, Eq, Typeable, Data)
-- * Construction
-- | Create a 'Var' 'Term' from the given arguments.
mkVar :: String -> Type -> Term
mkVar = Var . mkSimpleId
-- * Information Extraction
-- | Extract the 'Type' from the given 'Term'.
getTermType :: Term -> Type
getTermType term = case term of
Const _ typ -> typ
Var _ typ -> typ
Apply _ _ typ -> typ
-- * Attribute Classification
-- | True iff the argument is the @assoc@ attribute.
assoc :: Attr -> Bool
assoc attr = case attr of
Assoc -> True
_ -> False
-- | True iff the argument is the @comm@ attribute.
comm :: Attr -> Bool
comm attr = case attr of
Comm -> True
_ -> False
-- | True iff the argument is the @idem@ attribute.
idem :: Attr -> Bool
idem attr = case attr of
Idem -> True
_ -> False
-- | True iff the argument is the identity attribute.
idtty :: Attr -> Bool
idtty attr = case attr of
Id _ -> True
_ -> False
-- | True iff the argument is the left identity attribute.
leftId :: Attr -> Bool
leftId attr = case attr of
LeftId _ -> True
_ -> False
-- | True iff the argument is the right identity attribute.
rightId :: Attr -> Bool
rightId attr = case attr of
RightId _ -> True
_ -> False
-- | True iff the argument is the @ctor@ attribute.
ctor :: Attr -> Bool
ctor attr = case attr of
Ctor -> True
_ -> False
-- | True iff the argument is the @owise@ attribute.
owise :: StmntAttr -> Bool
owise attr = case attr of
Owise -> True
_ -> False
| spechub/Hets | Maude/AS_Maude.hs | gpl-2.0 | 6,447 | 0 | 8 | 2,003 | 1,816 | 993 | 823 | 151 | 3 |
<?xml version='1.0' encoding='ISO-8859-1' ?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN"
"http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0">
<title>jDip Help</title>
<maps>
<homeID>Welcome</homeID>
<mapref location="applicationhelp_map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Table of Contents</label>
<type>javax.help.TOCView</type>
<data>applicationhelp_toc.xml</data>
</view>
<presentation default="true" displayviewimages="false">
<name>main_help_window</name>
<size width="640" height="480"/>
<location x="150" y="150"/>
<title>jDip Help</title>
<image>cornericon</image>
<toolbar>
<helpaction>javax.help.BackAction</helpaction>
<helpaction>javax.help.ForwardAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction>javax.help.HomeAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction>javax.help.PrintAction</helpaction>
<helpaction>javax.help.PrintSetupAction</helpaction>
</toolbar>
</presentation>
</helpset>
| rgo/jDip | src/resource/help/applicationhelp.hs | gpl-2.0 | 1,158 | 84 | 67 | 159 | 462 | 230 | 232 | -1 | -1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses,
ViewPatterns#-}
{-
Copyright (C) 2006-2015 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Readers.HTML
Copyright : Copyright (C) 2006-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of HTML to 'Pandoc' document.
-}
module Text.Pandoc.Readers.HTML ( readHtml
, htmlTag
, htmlInBalanced
, isInlineTag
, isBlockTag
, isTextTag
, isCommentTag
) where
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match
import Text.Pandoc.Definition
import qualified Text.Pandoc.Builder as B
import Text.Pandoc.Builder (Blocks, Inlines, trimInlines, HasMeta(..))
import Text.Pandoc.Shared ( extractSpaces, renderTags'
, escapeURI, safeRead, mapLeft )
import Text.Pandoc.Options (ReaderOptions(readerParseRaw, readerTrace)
, Extension (Ext_epub_html_exts,
Ext_native_divs, Ext_native_spans))
import Text.Pandoc.Parsing hiding ((<|>))
import Text.Pandoc.Walk
import Data.Maybe ( fromMaybe, isJust)
import Data.List ( intercalate, isInfixOf, isPrefixOf, isSuffixOf )
import Data.Char ( isDigit )
import Control.Monad ( liftM, guard, when, mzero, void, unless )
import Control.Arrow ((***))
import Control.Applicative ( (<$>), (<$), (<*), (*>), (<|>))
import Data.Monoid (mconcat, Monoid, mempty, (<>), First (..))
import Text.Printf (printf)
import Debug.Trace (trace)
import Text.TeXMath (readMathML, writeTeX)
import Data.Default (Default (..), def)
import Control.Monad.Reader (Reader,ask, asks, local, runReader)
import Network.URI (isURI)
import Text.Pandoc.Error
import Text.Parsec.Error
-- | Convert HTML-formatted string to 'Pandoc' document.
readHtml :: ReaderOptions -- ^ Reader options
-> String -- ^ String to parse (assumes @'\n'@ line endings)
-> Either PandocError Pandoc
readHtml opts inp =
mapLeft (ParseFailure . getError) . flip runReader def $
runParserT parseDoc (HTMLState def{ stateOptions = opts } [] Nothing)
"source" tags
where tags = stripPrefixes . canonicalizeTags $
parseTagsOptions parseOptions{ optTagPosition = True } inp
parseDoc = do
blocks <- (fixPlains False) . mconcat <$> manyTill block eof
meta <- stateMeta . parserState <$> getState
bs' <- replaceNotes (B.toList blocks)
return $ Pandoc meta bs'
getError (errorMessages -> ms) = case ms of
[] -> ""
(m:_) -> messageString m
replaceNotes :: [Block] -> TagParser [Block]
replaceNotes = walkM replaceNotes'
replaceNotes' :: Inline -> TagParser Inline
replaceNotes' (RawInline (Format "noteref") ref) = maybe (Str "") (Note . B.toList) . lookup ref <$> getNotes
where
getNotes = noteTable <$> getState
replaceNotes' x = return x
data HTMLState =
HTMLState
{ parserState :: ParserState,
noteTable :: [(String, Blocks)],
baseHref :: Maybe String
}
data HTMLLocal = HTMLLocal { quoteContext :: QuoteContext
, inChapter :: Bool -- ^ Set if in chapter section
, inPlain :: Bool -- ^ Set if in pPlain
}
setInChapter :: HTMLParser s a -> HTMLParser s a
setInChapter = local (\s -> s {inChapter = True})
setInPlain :: HTMLParser s a -> HTMLParser s a
setInPlain = local (\s -> s {inPlain = True})
type HTMLParser s = ParserT s HTMLState (Reader HTMLLocal)
type TagParser = HTMLParser [Tag String]
pBody :: TagParser Blocks
pBody = pInTags "body" block
pHead :: TagParser Blocks
pHead = pInTags "head" $ pTitle <|> pMetaTag <|> pBaseTag <|> (mempty <$ pAnyTag)
where pTitle = pInTags "title" inline >>= setTitle . trimInlines
setTitle t = mempty <$ (updateState $ B.setMeta "title" t)
pMetaTag = do
mt <- pSatisfy (~== TagOpen "meta" [])
let name = fromAttrib "name" mt
if null name
then return mempty
else do
let content = fromAttrib "content" mt
updateState $ B.setMeta name (B.text content)
return mempty
pBaseTag = do
bt <- pSatisfy (~== TagOpen "base" [])
let baseH = fromAttrib "href" bt
if null baseH
then return mempty
else do
let baseH' = case reverse baseH of
'/':_ -> baseH
_ -> baseH ++ "/"
updateState $ \st -> st{ baseHref = Just baseH' }
return mempty
block :: TagParser Blocks
block = do
tr <- getOption readerTrace
pos <- getPosition
res <- choice
[ eSection
, eSwitch B.para block
, mempty <$ eFootnote
, mempty <$ eTOC
, mempty <$ eTitlePage
, pPara
, pHeader
, pBlockQuote
, pCodeBlock
, pList
, pHrule
, pTable
, pHead
, pBody
, pDiv
, pPlain
, pRawHtmlBlock
]
when tr $ trace (printf "line %d: %s" (sourceLine pos)
(take 60 $ show $ B.toList res)) (return ())
return res
namespaces :: [(String, TagParser Inlines)]
namespaces = [(mathMLNamespace, pMath True)]
mathMLNamespace :: String
mathMLNamespace = "http://www.w3.org/1998/Math/MathML"
eSwitch :: Monoid a => (Inlines -> a) -> TagParser a -> TagParser a
eSwitch constructor parser = try $ do
guardEnabled Ext_epub_html_exts
pSatisfy (~== TagOpen "switch" [])
cases <- getFirst . mconcat <$>
manyTill (First <$> (eCase <* skipMany pBlank) )
(lookAhead $ try $ pSatisfy (~== TagOpen "default" []))
skipMany pBlank
fallback <- pInTags "default" (skipMany pBlank *> parser <* skipMany pBlank)
skipMany pBlank
pSatisfy (~== TagClose "switch")
return $ maybe fallback constructor cases
eCase :: TagParser (Maybe Inlines)
eCase = do
skipMany pBlank
TagOpen _ attr <- lookAhead $ pSatisfy $ (~== TagOpen "case" [])
case (flip lookup namespaces) =<< lookup "required-namespace" attr of
Just p -> Just <$> (pInTags "case" (skipMany pBlank *> p <* skipMany pBlank))
Nothing -> Nothing <$ manyTill pAnyTag (pSatisfy (~== TagClose "case"))
eFootnote :: TagParser ()
eFootnote = try $ do
let notes = ["footnote", "rearnote"]
guardEnabled Ext_epub_html_exts
(TagOpen tag attr) <- lookAhead $ pAnyTag
guard (maybe False (flip elem notes) (lookup "type" attr))
let ident = fromMaybe "" (lookup "id" attr)
content <- pInTags tag block
addNote ident content
addNote :: String -> Blocks -> TagParser ()
addNote uid cont = updateState (\s -> s {noteTable = (uid, cont) : (noteTable s)})
eNoteref :: TagParser Inlines
eNoteref = try $ do
guardEnabled Ext_epub_html_exts
TagOpen tag attr <- lookAhead $ pAnyTag
guard (maybe False (== "noteref") (lookup "type" attr))
let ident = maybe "" (dropWhile (== '#')) (lookup "href" attr)
guard (not (null ident))
pInTags tag block
return $ B.rawInline "noteref" ident
-- Strip TOC if there is one, better to generate again
eTOC :: TagParser ()
eTOC = try $ do
guardEnabled Ext_epub_html_exts
(TagOpen tag attr) <- lookAhead $ pAnyTag
guard (maybe False (== "toc") (lookup "type" attr))
void (pInTags tag block)
pList :: TagParser Blocks
pList = pBulletList <|> pOrderedList <|> pDefinitionList
pBulletList :: TagParser Blocks
pBulletList = try $ do
pSatisfy (~== TagOpen "ul" [])
let nonItem = pSatisfy (\t ->
not (tagOpen (`elem` ["li","ol","ul","dl"]) (const True) t) &&
not (t ~== TagClose "ul"))
-- note: if they have an <ol> or <ul> not in scope of a <li>,
-- treat it as a list item, though it's not valid xhtml...
skipMany nonItem
items <- manyTill (pListItem nonItem) (pCloses "ul")
return $ B.bulletList $ map (fixPlains True) items
pListItem :: TagParser a -> TagParser Blocks
pListItem nonItem = do
TagOpen _ attr <- lookAhead $ pSatisfy (~== TagOpen "li" [])
let liDiv = maybe mempty (\x -> B.divWith (x, [], []) mempty) (lookup "id" attr)
(liDiv <>) <$> pInTags "li" block <* skipMany nonItem
pOrderedList :: TagParser Blocks
pOrderedList = try $ do
TagOpen _ attribs <- pSatisfy (~== TagOpen "ol" [])
let (start, style) = (sta', sty')
where sta = fromMaybe "1" $
lookup "start" attribs
sta' = if all isDigit sta
then read sta
else 1
sty = fromMaybe (fromMaybe "" $
lookup "style" attribs) $
lookup "class" attribs
sty' = case sty of
"lower-roman" -> LowerRoman
"upper-roman" -> UpperRoman
"lower-alpha" -> LowerAlpha
"upper-alpha" -> UpperAlpha
"decimal" -> Decimal
_ ->
case lookup "type" attribs of
Just "1" -> Decimal
Just "I" -> UpperRoman
Just "i" -> LowerRoman
Just "A" -> UpperAlpha
Just "a" -> LowerAlpha
_ -> DefaultStyle
let nonItem = pSatisfy (\t ->
not (tagOpen (`elem` ["li","ol","ul","dl"]) (const True) t) &&
not (t ~== TagClose "ol"))
-- note: if they have an <ol> or <ul> not in scope of a <li>,
-- treat it as a list item, though it's not valid xhtml...
skipMany nonItem
items <- manyTill (pListItem nonItem) (pCloses "ol")
return $ B.orderedListWith (start, style, DefaultDelim) $ map (fixPlains True) items
pDefinitionList :: TagParser Blocks
pDefinitionList = try $ do
pSatisfy (~== TagOpen "dl" [])
items <- manyTill pDefListItem (pCloses "dl")
return $ B.definitionList items
pDefListItem :: TagParser (Inlines, [Blocks])
pDefListItem = try $ do
let nonItem = pSatisfy (\t -> not (t ~== TagOpen "dt" []) &&
not (t ~== TagOpen "dd" []) && not (t ~== TagClose "dl"))
terms <- many1 (try $ skipMany nonItem >> pInTags "dt" inline)
defs <- many1 (try $ skipMany nonItem >> pInTags "dd" block)
skipMany nonItem
let term = foldl1 (\x y -> x <> B.linebreak <> y) terms
return (term, map (fixPlains True) defs)
fixPlains :: Bool -> Blocks -> Blocks
fixPlains inList bs = if any isParaish bs'
then B.fromList $ map plainToPara bs'
else bs
where isParaish (Para _) = True
isParaish (CodeBlock _ _) = True
isParaish (Header _ _ _) = True
isParaish (BlockQuote _) = True
isParaish (BulletList _) = not inList
isParaish (OrderedList _ _) = not inList
isParaish (DefinitionList _) = not inList
isParaish _ = False
plainToPara (Plain xs) = Para xs
plainToPara x = x
bs' = B.toList bs
pRawTag :: TagParser String
pRawTag = do
tag <- pAnyTag
let ignorable x = x `elem` ["html","head","body","!DOCTYPE","?xml"]
if tagOpen ignorable (const True) tag || tagClose ignorable tag
then return []
else return $ renderTags' [tag]
pDiv :: TagParser Blocks
pDiv = try $ do
guardEnabled Ext_native_divs
TagOpen _ attr <- lookAhead $ pSatisfy $ tagOpen (=="div") (const True)
contents <- pInTags "div" block
return $ B.divWith (mkAttr attr) contents
pRawHtmlBlock :: TagParser Blocks
pRawHtmlBlock = do
raw <- pHtmlBlock "script" <|> pHtmlBlock "style" <|> pRawTag
parseRaw <- getOption readerParseRaw
if parseRaw && not (null raw)
then return $ B.rawBlock "html" raw
else return mempty
pHtmlBlock :: String -> TagParser String
pHtmlBlock t = try $ do
open <- pSatisfy (~== TagOpen t [])
contents <- manyTill pAnyTag (pSatisfy (~== TagClose t))
return $ renderTags' $ [open] ++ contents ++ [TagClose t]
-- Sets chapter context
eSection :: TagParser Blocks
eSection = try $ do
let matchChapter as = maybe False (isInfixOf "chapter") (lookup "type" as)
let sectTag = tagOpen (`elem` sectioningContent) matchChapter
TagOpen tag _ <- lookAhead $ pSatisfy sectTag
setInChapter (pInTags tag block)
headerLevel :: String -> TagParser Int
headerLevel tagtype = do
let level = read (drop 1 tagtype)
(try $ do
guardEnabled Ext_epub_html_exts
asks inChapter >>= guard
return (level - 1))
<|>
return level
eTitlePage :: TagParser ()
eTitlePage = try $ do
let isTitlePage as = maybe False (isInfixOf "titlepage") (lookup "type" as)
let groupTag = tagOpen (\x -> x `elem` groupingContent || x == "section")
isTitlePage
TagOpen tag _ <- lookAhead $ pSatisfy groupTag
() <$ pInTags tag block
pHeader :: TagParser Blocks
pHeader = try $ do
TagOpen tagtype attr <- pSatisfy $
tagOpen (`elem` ["h1","h2","h3","h4","h5","h6"])
(const True)
let bodyTitle = TagOpen tagtype attr ~== TagOpen "h1" [("class","title")]
level <- headerLevel tagtype
contents <- trimInlines . mconcat <$> manyTill inline (pCloses tagtype <|> eof)
let ident = fromMaybe "" $ lookup "id" attr
let classes = maybe [] words $ lookup "class" attr
let keyvals = [(k,v) | (k,v) <- attr, k /= "class", k /= "id"]
return $ if bodyTitle
then mempty -- skip a representation of the title in the body
else B.headerWith (ident, classes, keyvals) level contents
pHrule :: TagParser Blocks
pHrule = do
pSelfClosing (=="hr") (const True)
return B.horizontalRule
pTable :: TagParser Blocks
pTable = try $ do
TagOpen _ _ <- pSatisfy (~== TagOpen "table" [])
skipMany pBlank
caption <- option mempty $ pInTags "caption" inline <* skipMany pBlank
-- TODO actually read these and take width information from them
widths' <- (mconcat <$> many1 pColgroup) <|> many pCol
let pTh = option [] $ pInTags "tr" (pCell "th")
pTr = try $ skipMany pBlank >> pInTags "tr" (pCell "td" <|> pCell "th")
pTBody = do pOptInTag "tbody" $ many1 pTr
head'' <- pOptInTag "thead" pTh
head' <- pOptInTag "tbody" $ do
if null head''
then pTh
else return head''
rowsLs <- many pTBody
rows' <- pOptInTag "tfoot" $ many pTr
TagClose _ <- pSatisfy (~== TagClose "table")
let rows = (concat rowsLs) ++ rows'
-- fail on empty table
guard $ not $ null head' && null rows
let isSinglePlain x = case B.toList x of
[Plain _] -> True
_ -> False
let isSimple = all isSinglePlain $ concat (head':rows)
let cols = length $ if null head' then head rows else head'
-- fail if there are colspans or rowspans
guard $ all (\r -> length r == cols) rows
let aligns = replicate cols AlignDefault
let widths = if null widths'
then if isSimple
then replicate cols 0
else replicate cols (1.0 / fromIntegral cols)
else widths'
return $ B.table caption (zip aligns widths) head' rows
pCol :: TagParser Double
pCol = try $ do
TagOpen _ attribs <- pSatisfy (~== TagOpen "col" [])
skipMany pBlank
optional $ pSatisfy (~== TagClose "col")
skipMany pBlank
return $ case lookup "width" attribs of
Just x | not (null x) && last x == '%' ->
fromMaybe 0.0 $ safeRead ('0':'.':init x)
_ -> 0.0
pColgroup :: TagParser [Double]
pColgroup = try $ do
pSatisfy (~== TagOpen "colgroup" [])
skipMany pBlank
manyTill pCol (pCloses "colgroup" <|> eof) <* skipMany pBlank
pCell :: String -> TagParser [Blocks]
pCell celltype = try $ do
skipMany pBlank
res <- pInTags celltype block
skipMany pBlank
return [res]
pBlockQuote :: TagParser Blocks
pBlockQuote = do
contents <- pInTags "blockquote" block
return $ B.blockQuote $ fixPlains False contents
pPlain :: TagParser Blocks
pPlain = do
contents <- setInPlain $ trimInlines . mconcat <$> many1 inline
if B.isNull contents
then return mempty
else return $ B.plain contents
pPara :: TagParser Blocks
pPara = do
contents <- trimInlines <$> pInTags "p" inline
return $ B.para contents
pCodeBlock :: TagParser Blocks
pCodeBlock = try $ do
TagOpen _ attr <- pSatisfy (~== TagOpen "pre" [])
contents <- manyTill pAnyTag (pCloses "pre" <|> eof)
let rawText = concatMap tagToString contents
-- drop leading newline if any
let result' = case rawText of
'\n':xs -> xs
_ -> rawText
-- drop trailing newline if any
let result = case reverse result' of
'\n':_ -> init result'
_ -> result'
return $ B.codeBlockWith (mkAttr attr) result
tagToString :: Tag String -> String
tagToString (TagText s) = s
tagToString (TagOpen "br" _) = "\n"
tagToString _ = ""
inline :: TagParser Inlines
inline = choice
[ eNoteref
, eSwitch id inline
, pTagText
, pQ
, pEmph
, pStrong
, pSuperscript
, pSubscript
, pStrikeout
, pLineBreak
, pLink
, pImage
, pCode
, pSpan
, pMath False
, pRawHtmlInline
]
pLocation :: TagParser ()
pLocation = do
(TagPosition r c) <- pSat isTagPosition
setPosition $ newPos "input" r c
pSat :: (Tag String -> Bool) -> TagParser (Tag String)
pSat f = do
pos <- getPosition
token show (const pos) (\x -> if f x then Just x else Nothing)
pSatisfy :: (Tag String -> Bool) -> TagParser (Tag String)
pSatisfy f = try $ optional pLocation >> pSat f
pAnyTag :: TagParser (Tag String)
pAnyTag = pSatisfy (const True)
pSelfClosing :: (String -> Bool) -> ([Attribute String] -> Bool)
-> TagParser (Tag String)
pSelfClosing f g = do
open <- pSatisfy (tagOpen f g)
optional $ pSatisfy (tagClose f)
return open
pQ :: TagParser Inlines
pQ = do
context <- asks quoteContext
let quoteType = case context of
InDoubleQuote -> SingleQuote
_ -> DoubleQuote
let innerQuoteContext = if quoteType == SingleQuote
then InSingleQuote
else InDoubleQuote
let constructor = case quoteType of
SingleQuote -> B.singleQuoted
DoubleQuote -> B.doubleQuoted
withQuoteContext innerQuoteContext $
pInlinesInTags "q" constructor
pEmph :: TagParser Inlines
pEmph = pInlinesInTags "em" B.emph <|> pInlinesInTags "i" B.emph
pStrong :: TagParser Inlines
pStrong = pInlinesInTags "strong" B.strong <|> pInlinesInTags "b" B.strong
pSuperscript :: TagParser Inlines
pSuperscript = pInlinesInTags "sup" B.superscript
pSubscript :: TagParser Inlines
pSubscript = pInlinesInTags "sub" B.subscript
pStrikeout :: TagParser Inlines
pStrikeout = do
pInlinesInTags "s" B.strikeout <|>
pInlinesInTags "strike" B.strikeout <|>
pInlinesInTags "del" B.strikeout <|>
try (do pSatisfy (~== TagOpen "span" [("class","strikeout")])
contents <- mconcat <$> manyTill inline (pCloses "span")
return $ B.strikeout contents)
pLineBreak :: TagParser Inlines
pLineBreak = do
pSelfClosing (=="br") (const True)
return B.linebreak
pLink :: TagParser Inlines
pLink = pRelLink <|> pAnchor
pAnchor :: TagParser Inlines
pAnchor = try $ do
tag <- pSatisfy (tagOpenLit "a" (isJust . lookup "id"))
return $ B.spanWith (fromAttrib "id" tag , [], []) mempty
pRelLink :: TagParser Inlines
pRelLink = try $ do
tag <- pSatisfy (tagOpenLit "a" (isJust . lookup "href"))
mbBaseHref <- baseHref <$> getState
let url' = fromAttrib "href" tag
let url = case (isURI url', mbBaseHref) of
(False, Just h) -> h ++ url'
_ -> url'
let title = fromAttrib "title" tag
let uid = fromAttrib "id" tag
let spanC = case uid of
[] -> id
s -> B.spanWith (s, [], [])
lab <- trimInlines . mconcat <$> manyTill inline (pCloses "a")
return $ spanC $ B.link (escapeURI url) title lab
pImage :: TagParser Inlines
pImage = do
tag <- pSelfClosing (=="img") (isJust . lookup "src")
mbBaseHref <- baseHref <$> getState
let url' = fromAttrib "src" tag
let url = case (isURI url', mbBaseHref) of
(False, Just h) -> h ++ url'
_ -> url'
let title = fromAttrib "title" tag
let alt = fromAttrib "alt" tag
return $ B.image (escapeURI url) title (B.text alt)
pCode :: TagParser Inlines
pCode = try $ do
(TagOpen open attr) <- pSatisfy $ tagOpen (`elem` ["code","tt"]) (const True)
result <- manyTill pAnyTag (pCloses open)
return $ B.codeWith (mkAttr attr) $ intercalate " " $ lines $ innerText result
pSpan :: TagParser Inlines
pSpan = try $ do
guardEnabled Ext_native_spans
TagOpen _ attr <- lookAhead $ pSatisfy $ tagOpen (=="span") (const True)
contents <- pInTags "span" inline
let attr' = mkAttr attr
return $ case attr' of
("",[],[("style",s)])
| filter (`notElem` " \t;") s == "font-variant:small-caps" ->
B.smallcaps contents
_ -> B.spanWith (mkAttr attr) contents
pRawHtmlInline :: TagParser Inlines
pRawHtmlInline = do
inplain <- asks inPlain
result <- pSatisfy (tagComment (const True))
<|> if inplain
then pSatisfy (not . isBlockTag)
else pSatisfy isInlineTag
parseRaw <- getOption readerParseRaw
if parseRaw
then return $ B.rawInline "html" $ renderTags' [result]
else return mempty
mathMLToTeXMath :: String -> Either String String
mathMLToTeXMath s = writeTeX <$> readMathML s
pMath :: Bool -> TagParser Inlines
pMath inCase = try $ do
open@(TagOpen _ attr) <- pSatisfy $ tagOpen (=="math") (const True)
unless (inCase) (guard (maybe False (== mathMLNamespace) (lookup "xmlns" attr)))
contents <- manyTill pAnyTag (pSatisfy (~== TagClose "math"))
let math = mathMLToTeXMath $
(renderTags $ [open] ++ contents ++ [TagClose "math"])
let constructor =
maybe B.math (\x -> if (x == "inline") then B.math else B.displayMath)
(lookup "display" attr)
return $ either (const mempty)
(\x -> if null x then mempty else constructor x) math
pInlinesInTags :: String -> (Inlines -> Inlines)
-> TagParser Inlines
pInlinesInTags tagtype f = extractSpaces f <$> pInTags tagtype inline
pInTags :: (Monoid a) => String -> TagParser a
-> TagParser a
pInTags tagtype parser = try $ do
pSatisfy (~== TagOpen tagtype [])
mconcat <$> manyTill parser (pCloses tagtype <|> eof)
-- parses p, preceeded by an optional opening tag
-- and followed by an optional closing tags
pOptInTag :: String -> TagParser a -> TagParser a
pOptInTag tagtype p = try $ do
skipMany pBlank
optional $ pSatisfy (~== TagOpen tagtype [])
skipMany pBlank
x <- p
skipMany pBlank
optional $ pSatisfy (~== TagClose tagtype)
skipMany pBlank
return x
pCloses :: String -> TagParser ()
pCloses tagtype = try $ do
t <- lookAhead $ pSatisfy $ \tag -> isTagClose tag || isTagOpen tag
case t of
(TagClose t') | t' == tagtype -> pAnyTag >> return ()
(TagOpen t' _) | t' `closes` tagtype -> return ()
(TagClose "ul") | tagtype == "li" -> return ()
(TagClose "ol") | tagtype == "li" -> return ()
(TagClose "dl") | tagtype == "li" -> return ()
(TagClose "table") | tagtype == "td" -> return ()
(TagClose "table") | tagtype == "tr" -> return ()
_ -> mzero
pTagText :: TagParser Inlines
pTagText = try $ do
(TagText str) <- pSatisfy isTagText
st <- getState
qu <- ask
case flip runReader qu $ runParserT (many pTagContents) st "text" str of
Left _ -> fail $ "Could not parse `" ++ str ++ "'"
Right result -> return $ mconcat result
pBlank :: TagParser ()
pBlank = try $ do
(TagText str) <- pSatisfy isTagText
guard $ all isSpace str
type InlinesParser = HTMLParser String
pTagContents :: InlinesParser Inlines
pTagContents =
B.displayMath <$> mathDisplay
<|> B.math <$> mathInline
<|> pStr
<|> pSpace
<|> smartPunctuation pTagContents
<|> pSymbol
<|> pBad
pStr :: InlinesParser Inlines
pStr = do
result <- many1 $ satisfy $ \c ->
not (isSpace c) && not (isSpecial c) && not (isBad c)
updateLastStrPos
return $ B.str result
isSpecial :: Char -> Bool
isSpecial '"' = True
isSpecial '\'' = True
isSpecial '.' = True
isSpecial '-' = True
isSpecial '$' = True
isSpecial '\8216' = True
isSpecial '\8217' = True
isSpecial '\8220' = True
isSpecial '\8221' = True
isSpecial _ = False
pSymbol :: InlinesParser Inlines
pSymbol = satisfy isSpecial >>= return . B.str . (:[])
isBad :: Char -> Bool
isBad c = c >= '\128' && c <= '\159' -- not allowed in HTML
pBad :: InlinesParser Inlines
pBad = do
c <- satisfy isBad
let c' = case c of
'\128' -> '\8364'
'\130' -> '\8218'
'\131' -> '\402'
'\132' -> '\8222'
'\133' -> '\8230'
'\134' -> '\8224'
'\135' -> '\8225'
'\136' -> '\710'
'\137' -> '\8240'
'\138' -> '\352'
'\139' -> '\8249'
'\140' -> '\338'
'\142' -> '\381'
'\145' -> '\8216'
'\146' -> '\8217'
'\147' -> '\8220'
'\148' -> '\8221'
'\149' -> '\8226'
'\150' -> '\8211'
'\151' -> '\8212'
'\152' -> '\732'
'\153' -> '\8482'
'\154' -> '\353'
'\155' -> '\8250'
'\156' -> '\339'
'\158' -> '\382'
'\159' -> '\376'
_ -> '?'
return $ B.str [c']
pSpace :: InlinesParser Inlines
pSpace = many1 (satisfy isSpace) >> return B.space
--
-- Constants
--
eitherBlockOrInline :: [String]
eitherBlockOrInline = ["audio", "applet", "button", "iframe", "embed",
"del", "ins",
"progress", "map", "area", "noscript", "script",
"object", "svg", "video", "source"]
{-
inlineHtmlTags :: [[Char]]
inlineHtmlTags = ["a", "abbr", "acronym", "b", "basefont", "bdo", "big",
"br", "cite", "code", "dfn", "em", "font", "i", "img",
"input", "kbd", "label", "q", "s", "samp", "select",
"small", "span", "strike", "strong", "sub", "sup",
"textarea", "tt", "u", "var"]
-}
blockHtmlTags :: [String]
blockHtmlTags = ["?xml", "!DOCTYPE", "address", "article", "aside",
"blockquote", "body", "button", "canvas",
"caption", "center", "col", "colgroup", "dd", "dir", "div",
"dl", "dt", "fieldset", "figcaption", "figure",
"footer", "form", "h1", "h2", "h3", "h4",
"h5", "h6", "head", "header", "hgroup", "hr", "html",
"isindex", "menu", "noframes", "ol", "output", "p", "pre",
"section", "table", "tbody", "textarea",
"thead", "tfoot", "ul", "dd",
"dt", "frameset", "li", "tbody", "td", "tfoot",
"th", "thead", "tr", "script", "style"]
-- We want to allow raw docbook in markdown documents, so we
-- include docbook block tags here too.
blockDocBookTags :: [String]
blockDocBookTags = ["calloutlist", "bibliolist", "glosslist", "itemizedlist",
"orderedlist", "segmentedlist", "simplelist",
"variablelist", "caution", "important", "note", "tip",
"warning", "address", "literallayout", "programlisting",
"programlistingco", "screen", "screenco", "screenshot",
"synopsis", "example", "informalexample", "figure",
"informalfigure", "table", "informaltable", "para",
"simpara", "formalpara", "equation", "informalequation",
"figure", "screenshot", "mediaobject", "qandaset",
"procedure", "task", "cmdsynopsis", "funcsynopsis",
"classsynopsis", "blockquote", "epigraph", "msgset",
"sidebar", "title"]
epubTags :: [String]
epubTags = ["case", "switch", "default"]
blockTags :: [String]
blockTags = blockHtmlTags ++ blockDocBookTags ++ epubTags
isInlineTag :: Tag String -> Bool
isInlineTag t = tagOpen isInlineTagName (const True) t ||
tagClose isInlineTagName t ||
tagComment (const True) t
where isInlineTagName x = x `notElem` blockTags
isBlockTag :: Tag String -> Bool
isBlockTag t = tagOpen isBlockTagName (const True) t ||
tagClose isBlockTagName t ||
tagComment (const True) t
where isBlockTagName ('?':_) = True
isBlockTagName ('!':_) = True
isBlockTagName x = x `elem` blockTags
|| x `elem` eitherBlockOrInline
isTextTag :: Tag String -> Bool
isTextTag = tagText (const True)
isCommentTag :: Tag String -> Bool
isCommentTag = tagComment (const True)
-- taken from HXT and extended
-- See http://www.w3.org/TR/html5/syntax.html sec 8.1.2.4 optional tags
closes :: String -> String -> Bool
_ `closes` "body" = False
_ `closes` "html" = False
"body" `closes` "head" = True
"a" `closes` "a" = True
"li" `closes` "li" = True
"th" `closes` t | t `elem` ["th","td"] = True
"tr" `closes` t | t `elem` ["th","td","tr"] = True
"dd" `closes` t | t `elem` ["dt", "dd"] = True
"dt" `closes` t | t `elem` ["dt","dd"] = True
"rt" `closes` t | t `elem` ["rb", "rt", "rtc"] = True
"optgroup" `closes` "optgroup" = True
"optgroup" `closes` "option" = True
"option" `closes` "option" = True
-- http://www.w3.org/TR/html-markup/p.html
x `closes` "p" | x `elem` ["address", "article", "aside", "blockquote",
"dir", "div", "dl", "fieldset", "footer", "form", "h1", "h2", "h3", "h4",
"h5", "h6", "header", "hr", "menu", "nav", "ol", "p", "pre", "section",
"table", "ul"] = True
"meta" `closes` "meta" = True
"form" `closes` "form" = True
"label" `closes` "label" = True
"map" `closes` "map" = True
"object" `closes` "object" = True
_ `closes` t | t `elem` ["option","style","script","textarea","title"] = True
t `closes` "select" | t /= "option" = True
"thead" `closes` t | t `elem` ["colgroup"] = True
"tfoot" `closes` t | t `elem` ["thead","colgroup"] = True
"tbody" `closes` t | t `elem` ["tbody","tfoot","thead","colgroup"] = True
t `closes` t2 |
t `elem` ["h1","h2","h3","h4","h5","h6","dl","ol","ul","table","div","p"] &&
t2 `elem` ["h1","h2","h3","h4","h5","h6","p" ] = True -- not "div"
t1 `closes` t2 |
t1 `elem` blockTags &&
t2 `notElem` (blockTags ++ eitherBlockOrInline) = True
_ `closes` _ = False
--- parsers for use in markdown, textile readers
-- | Matches a stretch of HTML in balanced tags.
htmlInBalanced :: (Monad m)
=> (Tag String -> Bool)
-> ParserT String st m String
htmlInBalanced f = try $ do
(TagOpen t _, tag) <- htmlTag f
guard $ not $ "/>" `isSuffixOf` tag -- not a self-closing tag
let stopper = htmlTag (~== TagClose t)
let anytag = snd <$> htmlTag (const True)
contents <- many $ notFollowedBy' stopper >>
(htmlInBalanced f <|> anytag <|> count 1 anyChar)
endtag <- liftM snd stopper
return $ tag ++ concat contents ++ endtag
-- | Matches a tag meeting a certain condition.
htmlTag :: Monad m
=> (Tag String -> Bool)
-> ParserT [Char] st m (Tag String, String)
htmlTag f = try $ do
lookAhead (char '<')
inp <- getInput
let hasTagWarning (TagWarning _:_) = True
hasTagWarning _ = False
let (next : rest) = canonicalizeTags $ parseTagsOptions
parseOptions{ optTagWarning = True } inp
guard $ f next
case next of
TagComment s
| "<!--" `isPrefixOf` inp -> do
count (length s + 4) anyChar
skipMany (satisfy (/='>'))
char '>'
return (next, "<!--" ++ s ++ "-->")
| otherwise -> fail "bogus comment mode, HTML5 parse error"
_ -> do
-- we get a TagWarning on things like
-- <www.boe.es/buscar/act.php?id=BOE-A-1996-8930#a66>
-- which should NOT be parsed as an HTML tag, see #2277
guard $ not $ hasTagWarning rest
rendered <- manyTill anyChar (char '>')
return (next, rendered ++ ">")
mkAttr :: [(String, String)] -> Attr
mkAttr attr = (attribsId, attribsClasses, attribsKV)
where attribsId = fromMaybe "" $ lookup "id" attr
attribsClasses = (words $ fromMaybe "" $ lookup "class" attr) ++ epubTypes
attribsKV = filter (\(k,_) -> k /= "class" && k /= "id") attr
epubTypes = words $ fromMaybe "" $ lookup "epub:type" attr
-- Strip namespace prefixes
stripPrefixes :: [Tag String] -> [Tag String]
stripPrefixes = map stripPrefix
stripPrefix :: Tag String -> Tag String
stripPrefix (TagOpen s as) =
TagOpen (stripPrefix' s) (map (stripPrefix' *** id) as)
stripPrefix (TagClose s) = TagClose (stripPrefix' s)
stripPrefix x = x
stripPrefix' :: String -> String
stripPrefix' s =
case span (/= ':') s of
(_, "") -> s
(_, (_:ts)) -> ts
isSpace :: Char -> Bool
isSpace ' ' = True
isSpace '\t' = True
isSpace '\n' = True
isSpace '\r' = True
isSpace _ = False
-- Instances
-- This signature should be more general
-- MonadReader HTMLLocal m => HasQuoteContext st m
instance HasQuoteContext st (Reader HTMLLocal) where
getQuoteContext = asks quoteContext
withQuoteContext q = local (\s -> s{quoteContext = q})
instance HasReaderOptions HTMLState where
extractReaderOptions = extractReaderOptions . parserState
instance Default HTMLState where
def = HTMLState def [] Nothing
instance HasMeta HTMLState where
setMeta s b st = st {parserState = setMeta s b $ parserState st}
deleteMeta s st = st {parserState = deleteMeta s $ parserState st}
instance Default HTMLLocal where
def = HTMLLocal NoQuote False False
instance HasLastStrPosition HTMLState where
setLastStrPos s st = st {parserState = setLastStrPos s (parserState st)}
getLastStrPos = getLastStrPos . parserState
-- EPUB Specific
--
--
sectioningContent :: [String]
sectioningContent = ["article", "aside", "nav", "section"]
groupingContent :: [String]
groupingContent = ["p", "hr", "pre", "blockquote", "ol"
, "ul", "li", "dl", "dt", "dt", "dd"
, "figure", "figcaption", "div", "main"]
{-
types :: [(String, ([String], Int))]
types = -- Document divisions
map (\s -> (s, (["section", "body"], 0)))
["volume", "part", "chapter", "division"]
++ -- Document section and components
[
("abstract", ([], 0))]
-}
| mwahab1/pandoc | src/Text/Pandoc/Readers/HTML.hs | gpl-2.0 | 36,633 | 0 | 20 | 10,724 | 11,345 | 5,777 | 5,568 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.OpsWorks.DeregisterRdsDbInstance
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deregisters an Amazon RDS instance.
--
-- Required Permissions: To use this action, an IAM user must have a Manage
-- permissions level for the stack, or an attached policy that explicitly grants
-- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DeregisterRdsDbInstance.html>
module Network.AWS.OpsWorks.DeregisterRdsDbInstance
(
-- * Request
DeregisterRdsDbInstance
-- ** Request constructor
, deregisterRdsDbInstance
-- ** Request lenses
, drdiRdsDbInstanceArn
-- * Response
, DeregisterRdsDbInstanceResponse
-- ** Response constructor
, deregisterRdsDbInstanceResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
newtype DeregisterRdsDbInstance = DeregisterRdsDbInstance
{ _drdiRdsDbInstanceArn :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeregisterRdsDbInstance' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drdiRdsDbInstanceArn' @::@ 'Text'
--
deregisterRdsDbInstance :: Text -- ^ 'drdiRdsDbInstanceArn'
-> DeregisterRdsDbInstance
deregisterRdsDbInstance p1 = DeregisterRdsDbInstance
{ _drdiRdsDbInstanceArn = p1
}
-- | The Amazon RDS instance's ARN.
drdiRdsDbInstanceArn :: Lens' DeregisterRdsDbInstance Text
drdiRdsDbInstanceArn =
lens _drdiRdsDbInstanceArn (\s a -> s { _drdiRdsDbInstanceArn = a })
data DeregisterRdsDbInstanceResponse = DeregisterRdsDbInstanceResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeregisterRdsDbInstanceResponse' constructor.
deregisterRdsDbInstanceResponse :: DeregisterRdsDbInstanceResponse
deregisterRdsDbInstanceResponse = DeregisterRdsDbInstanceResponse
instance ToPath DeregisterRdsDbInstance where
toPath = const "/"
instance ToQuery DeregisterRdsDbInstance where
toQuery = const mempty
instance ToHeaders DeregisterRdsDbInstance
instance ToJSON DeregisterRdsDbInstance where
toJSON DeregisterRdsDbInstance{..} = object
[ "RdsDbInstanceArn" .= _drdiRdsDbInstanceArn
]
instance AWSRequest DeregisterRdsDbInstance where
type Sv DeregisterRdsDbInstance = OpsWorks
type Rs DeregisterRdsDbInstance = DeregisterRdsDbInstanceResponse
request = post "DeregisterRdsDbInstance"
response = nullResponse DeregisterRdsDbInstanceResponse
| romanb/amazonka | amazonka-opsworks/gen/Network/AWS/OpsWorks/DeregisterRdsDbInstance.hs | mpl-2.0 | 3,646 | 0 | 9 | 688 | 360 | 221 | 139 | 49 | 1 |
-- test the representation of unboxed literals
{-# LANGUAGE TemplateHaskell #-}
module Main
where
$(
[d|
foo :: Int -> Int
foo x
| x == 5 = 6
foo x = 7
|]
)
$(
[d|
bar :: Maybe Int -> Int
bar x
| Just y <- x = y
bar _ = 9
|]
)
main :: IO ()
main = do putStrLn $ show $ foo 5
putStrLn $ show $ foo 8
putStrLn $ show $ bar (Just 2)
putStrLn $ show $ bar Nothing
| rahulmutt/ghcvm | tests/suite/templateHaskell/run/TH_repGuardOutput.hs | bsd-3-clause | 481 | 0 | 10 | 211 | 105 | 54 | 51 | 19 | 1 |
-- | This module defines a generator for @getopt@ based command
-- line argument parsing. Each option is associated with arbitrary
-- Python code that will perform side effects, usually by setting some
-- global variables.
module Futhark.CodeGen.Backends.GenericPython.Options
( Option (..)
, OptionArgument (..)
, generateOptionParser
)
where
import Futhark.CodeGen.Backends.GenericPython.AST
-- | Specification if a single command line option. The option must
-- have a long name, and may also have a short name.
--
-- When the statement is being executed, the argument (if any) will be
-- stored in the variable @optarg@.
data Option = Option { optionLongName :: String
, optionShortName :: Maybe Char
, optionArgument :: OptionArgument
, optionAction :: [PyStmt]
}
-- | Whether an option accepts an argument.
data OptionArgument = NoArgument
| RequiredArgument
| OptionalArgument
-- | Generate option parsing code that accepts the given command line options. Will read from @sys.argv@.
--
-- If option parsing fails for any reason, the entire process will
-- terminate with error code 1.
generateOptionParser :: [Option] -> [PyStmt]
generateOptionParser options =
[Assign (Var "parser")
(Call "argparse.ArgumentParser"
[ArgKeyword "description" $
StringLiteral "A compiled Futhark program."])] ++
map parseOption options ++
[Assign (Var "parser_result") $
Call "vars" [Arg $ Call "parser.parse_args" [Arg $ Var "sys.argv[1:]"]]] ++
map executeOption options
where parseOption option =
Exp $ Call "parser.add_argument" $
map (Arg . StringLiteral) name_args ++ argument_args
where name_args = maybe id ((:) . ('-':) . (:[])) (optionShortName option)
["--" ++ optionLongName option]
argument_args = case optionArgument option of
RequiredArgument ->
[ArgKeyword "action" (StringLiteral "append"),
ArgKeyword "default" $ List []]
NoArgument ->
[ArgKeyword "action" (StringLiteral "append_const"),
ArgKeyword "const" None]
OptionalArgument ->
[ArgKeyword "action" (StringLiteral "append"),
ArgKeyword "default" $ List [],
ArgKeyword "nargs" $ StringLiteral "?"]
executeOption option =
For "optarg" (Index (Var "parser_result") $
IdxExp $ StringLiteral $ fieldName option) $
optionAction option
fieldName = map escape . optionLongName
where escape '-' = '_'
escape c = c
| CulpaBS/wbBach | src/Futhark/CodeGen/Backends/GenericPython/Options.hs | bsd-3-clause | 2,823 | 0 | 15 | 874 | 517 | 279 | 238 | 45 | 4 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-missing-methods #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Apollonian
-- Copyright : (c) 2011, 2016 Brent Yorgey
-- License : BSD-style (see LICENSE)
-- Maintainer : byorgey@cis.upenn.edu
--
-- Generation of Apollonian gaskets. Any three mutually tangent
-- circles uniquely determine exactly two others which are mutually
-- tangent to all three. This process can be repeated, generating a
-- fractal circle packing.
--
-- See J. Lagarias, C. Mallows, and A. Wilks, \"Beyond the Descartes
-- circle theorem\", /Amer. Math. Monthly/ 109 (2002), 338--361.
-- <http://arxiv.org/abs/math/0101066>.
--
-- A few examples:
--
-- > import Diagrams.TwoD.Apollonian
-- > apollonian1 = apollonianGasket 0.01 2 2 2
--
-- <<diagrams/src_Diagrams_TwoD_Apollonian_apollonian1.svg#diagram=apollonian1&width=400>>
--
-- > import Diagrams.TwoD.Apollonian
-- > apollonian2 = apollonianGasket 0.01 2 3 3
--
-- <<diagrams/src_Diagrams_TwoD_Apollonian_apollonian2.svg#diagram=apollonian2&width=400>>
--
-- > import Diagrams.TwoD.Apollonian
-- > apollonian3 = apollonianGasket 0.01 2 4 7
--
-- <<diagrams/src_Diagrams_TwoD_Apollonian_apollonian3.svg#diagram=apollonian3&width=400>>
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Apollonian
( -- * Circles
Circle(..), mkCircle, center, radius
-- * Descartes' Theorem
, descartes, other, initialConfig
-- * Apollonian gasket generation
, apollonian
-- ** Kissing sets
, KissingSet(..), kissingSets, flipSelected, selectOthers
-- ** Apollonian trees
, apollonianTrees, apollonianTree
-- * Diagram generation
, drawCircle
, drawGasket
, apollonianGasket
) where
import Data.Complex
import qualified Data.Foldable as F
import Data.Maybe (catMaybes)
import Data.Tree
import Diagrams.Prelude hiding (center, radius)
import Control.Arrow (second, (&&&))
------------------------------------------------------------
-- Circles
------------------------------------------------------------
-- | Representation for circles that lets us quickly compute an
-- Apollonian gasket.
data Circle n = Circle
{ bend :: n
-- ^ The bend is the reciprocal of signed
-- radius: a negative radius means the
-- outside and inside of the circle are
-- switched. The bends of any four mutually
-- tangent circles satisfy Descartes'
-- Theorem.
, cb :: Complex n
-- ^ /Product/ of bend and center represented
-- as a complex number. Amazingly, these
-- products also satisfy the equation of
-- Descartes' Theorem.
}
deriving (Eq, Show)
-- | Create a @Circle@ given a signed radius and a location for its center.
mkCircle :: Fractional n =>
n -- ^ signed radius
-> P2 n -- ^ center
-> Circle n
mkCircle r (unp2 -> (x,y)) = Circle (1/r) (b*x :+ b*y)
where b = 1/r
-- | Get the center of a circle.
center :: Fractional n => Circle n -> P2 n
center (Circle b (cbx :+ cby)) = p2 (cbx / b, cby / b)
-- | Get the (unsigned) radius of a circle.
radius :: Fractional n => Circle n -> n
radius = abs . recip . bend
liftF :: RealFloat n => (forall a. Floating a => a -> a) -> Circle n -> Circle n
liftF f (Circle b c) = Circle (f b) (f c)
liftF2 :: RealFloat n => (forall a. Floating a => a -> a -> a) ->
Circle n -> Circle n -> Circle n
liftF2 f (Circle b1 cb1) (Circle b2 cb2) = Circle (f b1 b2) (f cb1 cb2)
instance RealFloat n => Num (Circle n) where
(+) = liftF2 (+)
(-) = liftF2 (-)
(*) = liftF2 (*)
negate = liftF negate
abs = liftF abs
fromInteger n = Circle (fromInteger n) (fromInteger n)
instance RealFloat n => Fractional (Circle n) where
(/) = liftF2 (/)
recip = liftF recip
-- | The @Num@, @Fractional@, and @Floating@ instances for @Circle@
-- (all simply lifted elementwise over @Circle@'s fields) let us use
-- Descartes' Theorem directly on circles.
instance RealFloat n => Floating (Circle n) where
sqrt = liftF sqrt
------------------------------------------------------------
-- Descartes' Theorem
------------------------------------------------------------
-- XXX generalize these for higher dimensions?
-- | Descartes' Theorem states that if @b1@, @b2@, @b3@ and @b4@ are
-- the bends of four mutually tangent circles, then
--
-- @
-- b1^2 + b2^2 + b3^2 + b4^2 = 1/2 * (b1 + b2 + b3 + b4)^2.
-- @
--
-- Surprisingly, if we replace each of the @bi@ with the /product/
-- of @bi@ and the center of the corresponding circle (represented
-- as a complex number), the equation continues to hold! (See the
-- paper referenced at the top of the module.)
--
-- @descartes [b1,b2,b3]@ solves for @b4@, returning both solutions.
-- Notably, @descartes@ works for any instance of @Floating@, which
-- includes both @Double@ (for bends), @Complex Double@ (for
-- bend/center product), and @Circle@ (for both at once).
descartes :: Floating n => [n] -> [n]
descartes [b1,b2,b3] = [r + s, -r + s]
where r = 2 * sqrt (b1*b2 + b1*b3 + b2*b3)
s = b1+b2+b3
descartes _ = error "descartes must be called on a list of length 3"
-- | If we have /four/ mutually tangent circles we can choose one of
-- them to replace; the remaining three determine exactly one other
-- circle which is mutually tangent. However, in this situation
-- there is no need to apply 'descartes' again, since the two
-- solutions @b4@ and @b4'@ satisfy
--
-- @
-- b4 + b4' = 2 * (b1 + b2 + b3)
-- @
--
-- Hence, to replace @b4@ with its dual, we need only sum the other
-- three, multiply by two, and subtract @b4@. Again, this works for
-- bends as well as bend/center products.
other :: Num n => [n] -> n -> n
other xs x = 2 * sum xs - x
-- | Generate an initial configuration of four mutually tangent
-- circles, given just the signed bends of three of them.
initialConfig :: RealFloat n => n -> n -> n -> [Circle n]
initialConfig b1 b2 b3 = cs ++ [c4]
where cs = [Circle b1 0, Circle b2 ((b2/b1 + 1) :+ 0), Circle b3 cb3]
a = 1/b1 + 1/b2
b = 1/b1 + 1/b3
c = 1/b2 + 1/b3
x = (b*b + a*a - c*c)/(2*a)
y = sqrt (b*b - x*x)
cb3 = b3*x :+ b3*y
[c4,_] = descartes cs
------------------------------------------------------------
-- Gasket generation
------------------------------------------------------------
select :: [a] -> [(a, [a])]
select [] = []
select (x:xs) = (x,xs) : (map . second) (x:) (select xs)
-- | The basic idea of a kissing set is supposed to represent a set of
-- four mutually tangent circles with one selected, though in fact
-- it is more general than that: it represents any set of objects
-- with one distinguished object selected.
data KissingSet n = KS { selected :: n, others :: [n] }
deriving (Show)
-- | Generate all possible kissing sets from a set of objects by
-- selecting each object in turn.
kissingSets :: [n] -> [KissingSet n]
kissingSets = map (uncurry KS) . select
-- | \"Flip\" the selected circle to the 'other' circle mutually tangent
-- to the other three. The new circle remains selected.
flipSelected :: Num n => KissingSet n -> KissingSet n
flipSelected (KS c cs) = KS (other cs c) cs
-- | Make the selected circle unselected, and select each of the
-- others, generating a new kissing set for each.
selectOthers :: KissingSet n -> [KissingSet n]
selectOthers (KS c cs) = [ KS c' (c:cs') | (c',cs') <- select cs ]
-- | Given a threshold radius and a list of /four/ mutually tangent
-- circles, generate the Apollonian gasket containing those circles.
-- Stop the recursion when encountering a circle with an (unsigned)
-- radius smaller than the threshold.
apollonian :: RealFloat n => n -> [Circle n] -> [Circle n]
apollonian thresh cs
= (cs++)
. concat
. map (maybe [] flatten . prune p . fmap selected)
. apollonianTrees
$ cs
where
p c = radius c >= thresh
-- | Given a set of /four/ mutually tangent circles, generate the
-- infinite Apollonian tree rooted at the given set, represented as
-- a list of four subtrees. Each node in the tree is a kissing set
-- with one circle selected which has just been flipped. The three
-- children of a node represent the kissing sets obtained by
-- selecting each of the other three circles and flipping them. The
-- initial roots of the four trees are chosen by selecting and
-- flipping each of the circles in the starting set. This
-- representation has the property that each circle in the
-- Apollonian gasket is the selected circle in exactly one node
-- (except that the initial four circles never appear as the
-- selected circle in any node).
apollonianTrees :: RealFloat n => [Circle n] -> [Tree (KissingSet (Circle n))]
apollonianTrees = map (apollonianTree . flipSelected) . kissingSets
-- | Generate a single Apollonian tree from a root kissing set. See
-- the documentation for 'apollonianTrees' for an explanation.
apollonianTree :: RealFloat n => KissingSet (Circle n) -> Tree (KissingSet (Circle n))
apollonianTree = unfoldTree (id &&& (map flipSelected . selectOthers))
-- | Prune a tree at the shallowest points where the predicate is not
-- satisfied.
prune :: (a -> Bool) -> Tree a -> Maybe (Tree a)
prune p (Node a ts)
| not (p a) = Nothing
| otherwise = Just $ Node a (catMaybes (map (prune p) ts))
------------------------------------------------------------
-- Diagram generation
------------------------------------------------------------
-- | Draw a circle.
drawCircle :: (Renderable (Path V2 n) b, TypeableFloat n) =>
Circle n -> QDiagram b V2 n Any
drawCircle c = circle (radius c) # moveTo (center c)
# fcA transparent
-- | Draw a generated gasket, using a line width 0.003 times the
-- radius of the largest circle.
drawGasket :: (Renderable (Path V2 n) b, TypeableFloat n) =>
[Circle n] -> QDiagram b V2 n Any
drawGasket cs = F.foldMap drawCircle cs
-- | Draw an Apollonian gasket: the first argument is the threshold;
-- the recursion will stop upon reaching circles with radii less than
-- it. The next three arguments are bends of three circles.
apollonianGasket :: (Renderable (Path V2 n) b, TypeableFloat n)
=> n -> n -> n -> n -> QDiagram b V2 n Any
apollonianGasket thresh b1 b2 b3 = drawGasket . apollonian thresh $ (initialConfig b1 b2 b3)
------------------------------------------------------------
-- Some notes on floating-point error
-- (only for the intrepid)
------------------------------------------------------------
{-
-- code from Gerald Gutierrez, personal communication
module Main where
import Data.Complex
import Diagrams.Backend.SVG.CmdLine
import Diagrams.Prelude
-- ------^---------^---------^---------^---------^---------^---------^--------
data Circle = Circle Double (Complex Double) deriving (Show)
descartes a b c
= (s + r, s - r)
where
s = a + b + c
r = 2 * sqrt ((a * b) + (b * c) + (c * a))
descartesDual a b c d
= 2 * (a + b + c) - d
soddies (Circle k1 b1) (Circle k2 b2) (Circle k3 b3)
= ( Circle k4 b4
, Circle k5 b5 )
where
(k4, k5) = descartes k1 k2 k3
(b4, b5) = descartes b1 b2 b3
soddiesDual (Circle k1 b1) (Circle k2 b2) (Circle k3 b3) (Circle k4 b4)
= Circle (descartesDual k1 k2 k3 k4) (descartesDual b1 b2 b3 b4)
mutuallyTangentCirclesFromTriangle z1 z2 z3
= ( Circle k1 (z1 * (k1 :+ 0))
, Circle k2 (z2 * (k2 :+ 0))
, Circle k3 (z3 * (k3 :+ 0)) )
where
a = magnitude (z2 - z3)
b = magnitude (z3 - z1)
c = magnitude (z1 - z2)
s = (a + b + c) / 2
k1 = 1 / (s - a)
k2 = 1 / (s - b)
k3 = 1 / (s - c)
main :: IO ()
main = mainWith picture
pic = mainWith picture
mkCircle :: Circle -> Diagram B
mkCircle (Circle k b)
= circle (1 / k) # moveTo (p2 (realPart z, imagPart z))
where
z = b / (k :+ 0)
picture :: Diagram B
picture
= mkCircle c1 <> mkCircle c2 <> mkCircle c3 <> mkCircle c4 <> mkCircle c5
where
(c1, c2, c3) = mutuallyTangentCirclesFromTriangle z1 z2 z3
(c4, c5) = soddies c1 c2 c3
-- z1 = 0 :+ 0
-- z2 = 3 :+ 0
-- z3 = 0 :+ 4
-- z1 = (-0.546) :+ (-0.755)
-- z2 = ( 0.341) :+ (-0.755)
-- z3 = (-0.250) :+ ( 0.428)
ofsBad = 0.15397 -- doesn't work
ofsGood = 0.15398 -- works
ofs = ofsGood
z1 = ofs + ((-0.546) :+ (-0.755))
z2 = ofs + (( 0.341) :+ (-0.755))
z3 = ofs + ((-0.250) :+ ( 0.428))
------------------------------------------------------------
Email to Gerald Gutierrez, 30 Sep 2016:
I got a chance to sit down and think hard about your code today, and
I think I have figured out what the problem is.
If you look at the outputs of 'soddies c1 c2 c3' using the two
different values for 'ofs', you will see that they are *almost* the
same, except that the complex numbers have been switched (though in
fact their real components are almost the same so you only notice the
difference in the imaginary components). This clearly causes
incorrect results since the y-coordinates represented by the imaginary
components are now getting scaled by different bend values. So the
resulting circles are of the right size and have (close to) the
correct x-coordinates, but their y-coordinates are wrong.
The problem is that in the 'soddies' function, you make independent
calls to 'descartes k1 k2 k3' (to solve for the bends) and 'descartes
b1 b2 b3' (to solve for the bend-center products), and then *assume*
that they return their solutions *in the same order*, so that you can
match up the first values to make one circle and the second values to
make another circle. I would guess that this is *usually* true but
apparently not when certain values are hovering right around a branch
cut of sqrt, or something like that.
I think my code in Diagrams.TwoD.Apollonian suffers from the same
problem. Ultimately I think it is due to the inherent inaccuracy of
floating-point numbers; there is nothing wrong with the formula
itself. It would be nice to figure out how to correct for this, but I
am not sure how off the top of my head. The interesting thing is that
switching the bend-center products does not seem to violate the
generalized Descartes' Theorem at all --- so it would seem that it
does not actually completely characterize mutually tangent circles,
that is, there exist sets of circles satisfying the theorem which are
not in fact mutually tangent.
-}
| diagrams/diagrams-contrib | src/Diagrams/TwoD/Apollonian.hs | bsd-3-clause | 14,924 | 0 | 14 | 3,358 | 2,086 | 1,162 | 924 | 106 | 1 |
{-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.IOState
-- Copyright : (c) Sven Panne 2002-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- This is a purely internal module for an IO monad with a pointer as an
-- additional state, basically a /StateT (Ptr s) IO a/.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.IOState (
IOState(..), getIOState, peekIOState, evalIOState, nTimes
) where
import Control.Monad(replicateM)
import Foreign.Ptr ( Ptr, plusPtr )
import Foreign.Storable ( Storable(sizeOf,peek) )
--------------------------------------------------------------------------------
newtype IOState s a = IOState { runIOState :: Ptr s -> IO (a, Ptr s) }
instance Functor (IOState s) where
fmap f m = IOState $ \s -> do (x, s') <- runIOState m s ; return (f x, s')
instance Monad (IOState s) where
return a = IOState $ \s -> return (a, s)
m >>= k = IOState $ \s -> do (a, s') <- runIOState m s ; runIOState (k a) s'
fail str = IOState $ \_ -> fail str
getIOState :: IOState s (Ptr s)
getIOState = IOState $ \s -> return (s, s)
putIOState :: Ptr s -> IOState s ()
putIOState s = IOState $ \_ -> return ((), s)
peekIOState :: Storable a => IOState a a
peekIOState = do
ptr <- getIOState
x <- liftIOState $ peek ptr
putIOState (ptr `plusPtr` sizeOf x)
return x
liftIOState :: IO a -> IOState s a
liftIOState m = IOState $ \s -> do a <- m ; return (a, s)
evalIOState :: IOState s a -> Ptr s -> IO a
evalIOState m s = do (a, _) <- runIOState m s ; return a
nTimes :: Integral a => a -> IOState b c -> IOState b [c]
nTimes n = replicateM (fromIntegral n)
| mfpi/OpenGL | Graphics/Rendering/OpenGL/GL/IOState.hs | bsd-3-clause | 1,876 | 0 | 12 | 365 | 615 | 328 | 287 | 29 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudFront.ListDistributions
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | List distributions.
--
-- <http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/ListDistributions.html>
module Network.AWS.CloudFront.ListDistributions
(
-- * Request
ListDistributions
-- ** Request constructor
, listDistributions
-- ** Request lenses
, ldMarker
, ldMaxItems
-- * Response
, ListDistributionsResponse
-- ** Response constructor
, listDistributionsResponse
-- ** Response lenses
, ldrDistributionList
) where
import Network.AWS.Prelude
import Network.AWS.Request.RestXML
import Network.AWS.CloudFront.Types
import qualified GHC.Exts
data ListDistributions = ListDistributions
{ _ldMarker :: Maybe Text
, _ldMaxItems :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListDistributions' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ldMarker' @::@ 'Maybe' 'Text'
--
-- * 'ldMaxItems' @::@ 'Maybe' 'Text'
--
listDistributions :: ListDistributions
listDistributions = ListDistributions
{ _ldMarker = Nothing
, _ldMaxItems = Nothing
}
-- | Use this when paginating results to indicate where to begin in your list of
-- distributions. The results include distributions in the list that occur after
-- the marker. To get the next page of results, set the Marker to the value of
-- the NextMarker from the current page's response (which is also the ID of the
-- last distribution on that page).
ldMarker :: Lens' ListDistributions (Maybe Text)
ldMarker = lens _ldMarker (\s a -> s { _ldMarker = a })
-- | The maximum number of distributions you want in the response body.
ldMaxItems :: Lens' ListDistributions (Maybe Text)
ldMaxItems = lens _ldMaxItems (\s a -> s { _ldMaxItems = a })
newtype ListDistributionsResponse = ListDistributionsResponse
{ _ldrDistributionList :: DistributionList
} deriving (Eq, Read, Show)
-- | 'ListDistributionsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ldrDistributionList' @::@ 'DistributionList'
--
listDistributionsResponse :: DistributionList -- ^ 'ldrDistributionList'
-> ListDistributionsResponse
listDistributionsResponse p1 = ListDistributionsResponse
{ _ldrDistributionList = p1
}
-- | The DistributionList type.
ldrDistributionList :: Lens' ListDistributionsResponse DistributionList
ldrDistributionList =
lens _ldrDistributionList (\s a -> s { _ldrDistributionList = a })
instance ToPath ListDistributions where
toPath = const "/2014-11-06/distribution"
instance ToQuery ListDistributions where
toQuery ListDistributions{..} = mconcat
[ "Marker" =? _ldMarker
, "MaxItems" =? _ldMaxItems
]
instance ToHeaders ListDistributions
instance ToXMLRoot ListDistributions where
toXMLRoot = const (namespaced ns "ListDistributions" [])
instance ToXML ListDistributions
instance AWSRequest ListDistributions where
type Sv ListDistributions = CloudFront
type Rs ListDistributions = ListDistributionsResponse
request = get
response = xmlResponse
instance FromXML ListDistributionsResponse where
parseXML x = ListDistributionsResponse
<$> x .@ "DistributionList"
instance AWSPager ListDistributions where
page rq rs
| stop (rs ^. ldrDistributionList . dlIsTruncated) = Nothing
| otherwise = Just $ rq
& ldMarker .~ rs ^. ldrDistributionList . dlNextMarker
| romanb/amazonka | amazonka-cloudfront/gen/Network/AWS/CloudFront/ListDistributions.hs | mpl-2.0 | 4,495 | 0 | 12 | 953 | 582 | 343 | 239 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module GameEngine.Graphics.Culling
( cullSurfaces
) where
import Control.Monad
import Data.Bits
import Data.Vect.Float
import Data.Vect.Float.Instances
import qualified Data.Vector as V
import LambdaCube.GL
import GameEngine.Data.BSP
import GameEngine.Graphics.Frustum
import GameEngine.Scene
isClusterVisible :: BSPLevel -> Int -> Int -> Bool
isClusterVisible bl a b
| a >= 0 = 0 /= (visSet .&. (shiftL 1 (b .&. 7)))
| otherwise = True
where
Visibility nvecs szvecs vecs = blVisibility bl
i = a * szvecs + (shiftR b 3)
visSet = vecs V.! i
findLeafIdx :: BSPLevel -> Vec3 -> Int -> Int
findLeafIdx bl camPos i
| i >= 0 = if dist >= 0 then findLeafIdx bl camPos f else findLeafIdx bl camPos b
| otherwise = (-i) - 1
where
node = blNodes bl V.! i
(f,b) = ndChildren node
plane = blPlanes bl V.! ndPlaneNum node
dist = plNormal plane `dotprod` camPos - plDist plane
cullSurfaces :: BSPLevel -> Vec3 -> Frustum -> V.Vector [Object] -> IO ()
cullSurfaces bsp cameraPosition cameraFrustum objs = case leafIdx < 0 || leafIdx >= V.length leaves of
True -> {-trace "findLeafIdx error" $ -}V.forM_ objs $ \objList -> forM_ objList $ \obj -> enableObject obj True
False -> {-trace ("findLeafIdx ok " ++ show leafIdx ++ " " ++ show camCluster) -}surfaceMask
where
leafIdx = findLeafIdx bsp cameraPosition 0
leaves = blLeaves bsp
camCluster = lfCluster $ leaves V.! leafIdx
visibleLeafs = V.filter (\a -> (isClusterVisible bsp camCluster $ lfCluster a) && inFrustum a) leaves
surfaceMask = do
let leafSurfaces = blLeafSurfaces bsp
V.forM_ objs $ \objList -> forM_ objList $ \obj -> enableObject obj False
V.forM_ visibleLeafs $ \l ->
V.forM_ (V.slice (lfFirstLeafSurface l) (lfNumLeafSurfaces l) leafSurfaces) $ \i ->
forM_ (objs V.! i) $ \obj -> enableObject obj True
inFrustum a = boxInFrustum (lfMaxs a) (lfMins a) cameraFrustum
| csabahruska/quake3 | game-engine/GameEngine/Graphics/Culling.hs | bsd-3-clause | 2,012 | 0 | 16 | 461 | 694 | 356 | 338 | 42 | 2 |
-----------------------------------------------------------------------------
-- Mutable arrays in the IO monad:
--
-- Suitable for use with Hugs 98.
-----------------------------------------------------------------------------
module Hugs.IOArray
( IOArray -- instance of: Eq, Typeable
, newIOArray
, boundsIOArray
, readIOArray
, writeIOArray
, freezeIOArray
, thawIOArray
, unsafeFreezeIOArray
, unsafeReadIOArray
, unsafeWriteIOArray
) where
import Hugs.Array
-----------------------------------------------------------------------------
data IOArray ix elt -- implemented as an internal primitive
newIOArray :: Ix ix => (ix,ix) -> elt -> IO (IOArray ix elt)
boundsIOArray :: Ix ix => IOArray ix elt -> (ix, ix)
readIOArray :: Ix ix => IOArray ix elt -> ix -> IO elt
writeIOArray :: Ix ix => IOArray ix elt -> ix -> elt -> IO ()
thawIOArray :: Ix ix => Array ix elt -> IO (IOArray ix elt)
freezeIOArray :: Ix ix => IOArray ix elt -> IO (Array ix elt)
unsafeFreezeIOArray :: Ix ix => IOArray ix elt -> IO (Array ix elt)
unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
unsafeReadIOArray = primReadArr
unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
unsafeWriteIOArray = primWriteArr
newIOArray bs e = primNewArr bs (rangeSize bs) e
boundsIOArray a = primBounds a
readIOArray a i = unsafeReadIOArray a (index (boundsIOArray a) i)
writeIOArray a i e = unsafeWriteIOArray a (index (boundsIOArray a) i) e
thawIOArray arr = do a <- newIOArray (bounds arr) err
let fillin [] = return a
fillin((ix,v):ixs) = do writeIOArray a ix v
fillin ixs
fillin (assocs arr)
where err = error "thawArray: element not overwritten"
freezeIOArray a = primFreeze a
unsafeFreezeIOArray = freezeIOArray -- not as fast as GHC
instance Eq (IOArray ix elt) where
(==) = eqIOArray
primitive primNewArr "IONewArr"
:: (a,a) -> Int -> b -> IO (IOArray a b)
primitive primReadArr "IOReadArr"
:: IOArray a b -> Int -> IO b
primitive primWriteArr "IOWriteArr"
:: IOArray a b -> Int -> b -> IO ()
primitive primFreeze "IOFreeze"
:: IOArray a b -> IO (Array a b)
primitive primBounds "IOBounds"
:: IOArray a b -> (a,a)
primitive eqIOArray "IOArrEq"
:: IOArray a b -> IOArray a b -> Bool
-----------------------------------------------------------------------------
| kaoskorobase/mescaline | resources/hugs/packages/hugsbase/Hugs/IOArray.hs | gpl-3.0 | 2,557 | 23 | 11 | 659 | 756 | 387 | 369 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hi-IN">
<title>Plug-n-Hack | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 972 | 91 | 29 | 158 | 402 | 215 | 187 | -1 | -1 |
{-# LANGUAGE RoleAnnotations #-}
module T14101 where
type role Array representational
data Array a
type Arr = Array
data Foo a = Foo (Arr a)
type role Foo representational
| ezyang/ghc | testsuite/tests/roles/should_compile/T14101.hs | bsd-3-clause | 175 | 0 | 8 | 32 | 43 | 28 | 15 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, PatternGuards #-}
{-
Copyright (C) 2006-2015 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.Docbook
Copyright : Copyright (C) 2006-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to Docbook XML.
-}
module Text.Pandoc.Writers.Docbook ( writeDocbook) where
import Text.Pandoc.Definition
import Text.Pandoc.XML
import Text.Pandoc.Shared
import Text.Pandoc.Walk
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Options
import Text.Pandoc.Templates (renderTemplate')
import Text.Pandoc.Readers.TeXMath
import Data.List ( stripPrefix, isPrefixOf, intercalate, isSuffixOf )
import Data.Char ( toLower )
import Control.Applicative ((<$>))
import Data.Monoid ( Any(..) )
import Text.Pandoc.Highlighting ( languages, languagesByExtension )
import Text.Pandoc.Pretty
import qualified Text.Pandoc.Builder as B
import Text.TeXMath
import qualified Text.XML.Light as Xml
import Data.Generics (everywhere, mkT)
-- | Convert list of authors to a docbook <author> section
authorToDocbook :: WriterOptions -> [Inline] -> B.Inlines
authorToDocbook opts name' =
let name = render Nothing $ inlinesToDocbook opts name'
colwidth = if writerWrapText opts
then Just $ writerColumns opts
else Nothing
in B.rawInline "docbook" $ render colwidth $
if ',' `elem` name
then -- last name first
let (lastname, rest) = break (==',') name
firstname = triml rest in
inTagsSimple "firstname" (text $ escapeStringForXML firstname) <>
inTagsSimple "surname" (text $ escapeStringForXML lastname)
else -- last name last
let namewords = words name
lengthname = length namewords
(firstname, lastname) = case lengthname of
0 -> ("","")
1 -> ("", name)
n -> (intercalate " " (take (n-1) namewords), last namewords)
in inTagsSimple "firstname" (text $ escapeStringForXML firstname) $$
inTagsSimple "surname" (text $ escapeStringForXML lastname)
-- | Convert Pandoc document to string in Docbook format.
writeDocbook :: WriterOptions -> Pandoc -> String
writeDocbook opts (Pandoc meta blocks) =
let elements = hierarchicalize blocks
colwidth = if writerWrapText opts
then Just $ writerColumns opts
else Nothing
render' = render colwidth
opts' = if "/book>" `isSuffixOf`
(trimr $ writerTemplate opts)
then opts{ writerChapters = True }
else opts
startLvl = if writerChapters opts' then 0 else 1
auths' = map (authorToDocbook opts) $ docAuthors meta
meta' = B.setMeta "author" auths' meta
Just metadata = metaToJSON opts
(Just . render colwidth . (vcat .
(map (elementToDocbook opts' startLvl)) . hierarchicalize))
(Just . render colwidth . inlinesToDocbook opts')
meta'
main = render' $ vcat (map (elementToDocbook opts' startLvl) elements)
context = defField "body" main
$ defField "mathml" (case writerHTMLMathMethod opts of
MathML _ -> True
_ -> False)
$ metadata
in if writerStandalone opts
then renderTemplate' (writerTemplate opts) context
else main
-- | Convert an Element to Docbook.
elementToDocbook :: WriterOptions -> Int -> Element -> Doc
elementToDocbook opts _ (Blk block) = blockToDocbook opts block
elementToDocbook opts lvl (Sec _ _num (id',_,_) title elements) =
-- Docbook doesn't allow sections with no content, so insert some if needed
let elements' = if null elements
then [Blk (Para [])]
else elements
tag = case lvl of
n | n == 0 -> "chapter"
| n >= 1 && n <= 5 -> "sect" ++ show n
| otherwise -> "simplesect"
in inTags True tag [("id", writerIdentifierPrefix opts ++ id') |
not (null id')] $
inTagsSimple "title" (inlinesToDocbook opts title) $$
vcat (map (elementToDocbook opts (lvl + 1)) elements')
-- | Convert a list of Pandoc blocks to Docbook.
blocksToDocbook :: WriterOptions -> [Block] -> Doc
blocksToDocbook opts = vcat . map (blockToDocbook opts)
-- | Auxiliary function to convert Plain block to Para.
plainToPara :: Block -> Block
plainToPara (Plain x) = Para x
plainToPara x = x
-- | Convert a list of pairs of terms and definitions into a list of
-- Docbook varlistentrys.
deflistItemsToDocbook :: WriterOptions -> [([Inline],[[Block]])] -> Doc
deflistItemsToDocbook opts items =
vcat $ map (\(term, defs) -> deflistItemToDocbook opts term defs) items
-- | Convert a term and a list of blocks into a Docbook varlistentry.
deflistItemToDocbook :: WriterOptions -> [Inline] -> [[Block]] -> Doc
deflistItemToDocbook opts term defs =
let def' = concatMap (map plainToPara) defs
in inTagsIndented "varlistentry" $
inTagsIndented "term" (inlinesToDocbook opts term) $$
inTagsIndented "listitem" (blocksToDocbook opts def')
-- | Convert a list of lists of blocks to a list of Docbook list items.
listItemsToDocbook :: WriterOptions -> [[Block]] -> Doc
listItemsToDocbook opts items = vcat $ map (listItemToDocbook opts) items
-- | Convert a list of blocks into a Docbook list item.
listItemToDocbook :: WriterOptions -> [Block] -> Doc
listItemToDocbook opts item =
inTagsIndented "listitem" $ blocksToDocbook opts $ map plainToPara item
-- | Convert a Pandoc block element to Docbook.
blockToDocbook :: WriterOptions -> Block -> Doc
blockToDocbook _ Null = empty
-- Add ids to paragraphs in divs with ids - this is needed for
-- pandoc-citeproc to get link anchors in bibliographies:
blockToDocbook opts (Div (ident,_,_) [Para lst]) =
let attribs = [("id", ident) | not (null ident)] in
if hasLineBreaks lst
then flush $ nowrap $ inTags False "literallayout" attribs
$ inlinesToDocbook opts lst
else inTags True "para" attribs $ inlinesToDocbook opts lst
blockToDocbook opts (Div _ bs) = blocksToDocbook opts $ map plainToPara bs
blockToDocbook _ (Header _ _ _) = empty -- should not occur after hierarchicalize
blockToDocbook opts (Plain lst) = inlinesToDocbook opts lst
-- title beginning with fig: indicates that the image is a figure
blockToDocbook opts (Para [Image txt (src,'f':'i':'g':':':_)]) =
let alt = inlinesToDocbook opts txt
capt = if null txt
then empty
else inTagsSimple "title" alt
in inTagsIndented "figure" $
capt $$
(inTagsIndented "mediaobject" $
(inTagsIndented "imageobject"
(selfClosingTag "imagedata" [("fileref",src)])) $$
inTagsSimple "textobject" (inTagsSimple "phrase" alt))
blockToDocbook opts (Para lst)
| hasLineBreaks lst = flush $ nowrap $ inTagsSimple "literallayout" $ inlinesToDocbook opts lst
| otherwise = inTagsIndented "para" $ inlinesToDocbook opts lst
blockToDocbook opts (BlockQuote blocks) =
inTagsIndented "blockquote" $ blocksToDocbook opts blocks
blockToDocbook _ (CodeBlock (_,classes,_) str) =
text ("<programlisting" ++ lang ++ ">") <> cr <>
flush (text (escapeStringForXML str) <> cr <> text "</programlisting>")
where lang = if null langs
then ""
else " language=\"" ++ escapeStringForXML (head langs) ++
"\""
isLang l = map toLower l `elem` map (map toLower) languages
langsFrom s = if isLang s
then [s]
else languagesByExtension . map toLower $ s
langs = concatMap langsFrom classes
blockToDocbook opts (BulletList lst) =
let attribs = [("spacing", "compact") | isTightList lst]
in inTags True "itemizedlist" attribs $ listItemsToDocbook opts lst
blockToDocbook _ (OrderedList _ []) = empty
blockToDocbook opts (OrderedList (start, numstyle, _) (first:rest)) =
let numeration = case numstyle of
DefaultStyle -> []
Decimal -> [("numeration", "arabic")]
Example -> [("numeration", "arabic")]
UpperAlpha -> [("numeration", "upperalpha")]
LowerAlpha -> [("numeration", "loweralpha")]
UpperRoman -> [("numeration", "upperroman")]
LowerRoman -> [("numeration", "lowerroman")]
spacing = [("spacing", "compact") | isTightList (first:rest)]
attribs = numeration ++ spacing
items = if start == 1
then listItemsToDocbook opts (first:rest)
else (inTags True "listitem" [("override",show start)]
(blocksToDocbook opts $ map plainToPara first)) $$
listItemsToDocbook opts rest
in inTags True "orderedlist" attribs items
blockToDocbook opts (DefinitionList lst) =
let attribs = [("spacing", "compact") | isTightList $ concatMap snd lst]
in inTags True "variablelist" attribs $ deflistItemsToDocbook opts lst
blockToDocbook _ (RawBlock f str)
| f == "docbook" = text str -- raw XML block
| f == "html" = text str -- allow html for backwards compatibility
| otherwise = empty
blockToDocbook _ HorizontalRule = empty -- not semantic
blockToDocbook opts (Table caption aligns widths headers rows) =
let captionDoc = if null caption
then empty
else inTagsIndented "title"
(inlinesToDocbook opts caption)
tableType = if isEmpty captionDoc then "informaltable" else "table"
percent w = show (truncate (100*w) :: Integer) ++ "*"
coltags = vcat $ zipWith (\w al -> selfClosingTag "colspec"
([("colwidth", percent w) | w > 0] ++
[("align", alignmentToString al)])) widths aligns
head' = if all null headers
then empty
else inTagsIndented "thead" $
tableRowToDocbook opts headers
body' = inTagsIndented "tbody" $
vcat $ map (tableRowToDocbook opts) rows
in inTagsIndented tableType $ captionDoc $$
(inTags True "tgroup" [("cols", show (length headers))] $
coltags $$ head' $$ body')
hasLineBreaks :: [Inline] -> Bool
hasLineBreaks = getAny . query isLineBreak . walk removeNote
where
removeNote :: Inline -> Inline
removeNote (Note _) = Str ""
removeNote x = x
isLineBreak :: Inline -> Any
isLineBreak LineBreak = Any True
isLineBreak _ = Any False
alignmentToString :: Alignment -> [Char]
alignmentToString alignment = case alignment of
AlignLeft -> "left"
AlignRight -> "right"
AlignCenter -> "center"
AlignDefault -> "left"
tableRowToDocbook :: WriterOptions
-> [[Block]]
-> Doc
tableRowToDocbook opts cols =
inTagsIndented "row" $ vcat $ map (tableItemToDocbook opts) cols
tableItemToDocbook :: WriterOptions
-> [Block]
-> Doc
tableItemToDocbook opts item =
inTags True "entry" [] $ vcat $ map (blockToDocbook opts) item
-- | Convert a list of inline elements to Docbook.
inlinesToDocbook :: WriterOptions -> [Inline] -> Doc
inlinesToDocbook opts lst = hcat $ map (inlineToDocbook opts) lst
-- | Convert an inline element to Docbook.
inlineToDocbook :: WriterOptions -> Inline -> Doc
inlineToDocbook _ (Str str) = text $ escapeStringForXML str
inlineToDocbook opts (Emph lst) =
inTagsSimple "emphasis" $ inlinesToDocbook opts lst
inlineToDocbook opts (Strong lst) =
inTags False "emphasis" [("role", "strong")] $ inlinesToDocbook opts lst
inlineToDocbook opts (Strikeout lst) =
inTags False "emphasis" [("role", "strikethrough")] $
inlinesToDocbook opts lst
inlineToDocbook opts (Superscript lst) =
inTagsSimple "superscript" $ inlinesToDocbook opts lst
inlineToDocbook opts (Subscript lst) =
inTagsSimple "subscript" $ inlinesToDocbook opts lst
inlineToDocbook opts (SmallCaps lst) =
inTags False "emphasis" [("role", "smallcaps")] $
inlinesToDocbook opts lst
inlineToDocbook opts (Quoted _ lst) =
inTagsSimple "quote" $ inlinesToDocbook opts lst
inlineToDocbook opts (Cite _ lst) =
inlinesToDocbook opts lst
inlineToDocbook opts (Span _ ils) =
inlinesToDocbook opts ils
inlineToDocbook _ (Code _ str) =
inTagsSimple "literal" $ text (escapeStringForXML str)
inlineToDocbook opts (Math t str)
| isMathML (writerHTMLMathMethod opts) =
case writeMathML dt <$> readTeX str of
Right r -> inTagsSimple tagtype
$ text $ Xml.ppcElement conf
$ fixNS
$ removeAttr r
Left _ -> inlinesToDocbook opts
$ texMathToInlines t str
| otherwise = inlinesToDocbook opts $ texMathToInlines t str
where (dt, tagtype) = case t of
InlineMath -> (DisplayInline,"inlineequation")
DisplayMath -> (DisplayBlock,"informalequation")
conf = Xml.useShortEmptyTags (const False) Xml.defaultConfigPP
removeAttr e = e{ Xml.elAttribs = [] }
fixNS' qname = qname{ Xml.qPrefix = Just "mml" }
fixNS = everywhere (mkT fixNS')
inlineToDocbook _ (RawInline f x) | f == "html" || f == "docbook" = text x
| otherwise = empty
inlineToDocbook _ LineBreak = text "\n"
inlineToDocbook _ Space = space
inlineToDocbook opts (Link txt (src, _))
| Just email <- stripPrefix "mailto:" src =
let emailLink = inTagsSimple "email" $ text $
escapeStringForXML $ email
in case txt of
[Str s] | escapeURI s == email -> emailLink
_ -> inlinesToDocbook opts txt <+>
char '(' <> emailLink <> char ')'
| otherwise =
(if isPrefixOf "#" src
then inTags False "link" [("linkend", drop 1 src)]
else inTags False "ulink" [("url", src)]) $
inlinesToDocbook opts txt
inlineToDocbook _ (Image _ (src, tit)) =
let titleDoc = if null tit
then empty
else inTagsIndented "objectinfo" $
inTagsIndented "title" (text $ escapeStringForXML tit)
in inTagsIndented "inlinemediaobject" $ inTagsIndented "imageobject" $
titleDoc $$ selfClosingTag "imagedata" [("fileref", src)]
inlineToDocbook opts (Note contents) =
inTagsIndented "footnote" $ blocksToDocbook opts contents
isMathML :: HTMLMathMethod -> Bool
isMathML (MathML _) = True
isMathML _ = False
| gbataille/pandoc | src/Text/Pandoc/Writers/Docbook.hs | gpl-2.0 | 15,916 | 0 | 21 | 4,513 | 4,141 | 2,120 | 2,021 | 284 | 15 |
import Data.Bits
import Data.Word
import Debug.Trace
fl :: Word64 -> Word64 -> Word64
fl fin sk =
let (x1, x2) = w64tow32 fin in
let (k1, k2) = w64tow32 sk in
let y2 = x2 `xor` ((x1 .&. k1) `rotateL` 1) in
let y1 = x1 `xor` (y2 .|. k2) in
trace (show fin ++ " " ++ show sk ++ " -> " ++ show (w32tow64 (y1, y2))) $ w32tow64 (y1, y2)
w64tow32 :: Word64 -> (Word32, Word32)
w64tow32 w = (fromIntegral (w `shiftR` 32), fromIntegral (w .&. 0xffffffff))
w32tow64 :: (Word32, Word32) -> Word64
w32tow64 (x1, x2) = ((fromIntegral x1) `shiftL` 32) .|. (fromIntegral x2)
a, b :: Word64
a = 1238988323332265734
b = 11185553392205053542
main :: IO ()
main =
putStrLn $ "fl " ++ show a ++ " " ++ show b ++ " -> " ++ show (fl a b)
| urbanslug/ghc | testsuite/tests/codeGen/should_run/T5900.hs | bsd-3-clause | 731 | 10 | 20 | 159 | 382 | 204 | 178 | 20 | 1 |
-- !!! testing hGetLine on a file without a final '\n'.
-- According to the Haskell 98 report, getLine should discard a line without a
-- closing newline character (see implementation of getLine).
--
-- However, we don't believe that this is the right behaviour.
import System.IO
import System.IO.Error
main = catchIOError loop (\e -> print e)
loop = do
hSetBuffering stdin LineBuffering
l <- hGetLine stdin
putStrLn l
loop
| wxwxwwxxx/ghc | libraries/base/tests/IO/hGetLine002.hs | bsd-3-clause | 438 | 0 | 8 | 84 | 70 | 36 | 34 | 8 | 1 |
-- test 'lookupTypeName' and 'lookupValueName'
import Language.Haskell.TH
import qualified TH_lookupName_Lib
import qualified TH_lookupName_Lib as TheLib
f :: String
f = "TH_lookupName.f"
data D = D
$(return [])
main = mapM_ print [
-- looking up values
$(do { Just n <- lookupValueName "f" ; varE n }),
$(do { Nothing <- lookupTypeName "f"; [| "" |] }),
-- looking up types
$(do { Just n <- lookupTypeName "String"; sigE [| "" |] (conT n) }),
$(do { Nothing <- lookupValueName "String"; [| "" |] }),
-- namespacing
$(do { Just n <- lookupValueName "D"; DataConI{} <- reify n; [| "" |] }),
$(do { Just n <- lookupTypeName "D"; TyConI{} <- reify n; [| "" |] }),
-- qualified lookup
$(do { Just n <- lookupValueName "TH_lookupName_Lib.f"; varE n }),
$(do { Just n <- lookupValueName "TheLib.f"; varE n }),
-- shadowing
$(TheLib.lookup_f),
$( [| let f = "local f" in $(TheLib.lookup_f) |] ),
$( [| let f = "local f" in $(do { Just n <- lookupValueName "f"; varE n }) |] ),
$( [| let f = "local f" in $(varE 'f) |] ),
let f = "local f" in $(TheLib.lookup_f),
let f = "local f" in $(varE 'f)
]
| siddhanathan/ghc | testsuite/tests/th/TH_lookupName.hs | bsd-3-clause | 1,135 | 0 | 13 | 248 | 410 | 224 | 186 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Request sending and Response parsing
module Lastfm.Response
( -- * Compute request signature
-- $sign
Secret(..)
, sign
-- * Perform requests
, Connection
, withConnection
, newConnection
, lastfm
, lastfm_
, Supported
, Format(..)
-- ** Errors
, LastfmError(..)
, _LastfmBadResponse
, _LastfmEncodedError
, _LastfmHttpError
#ifdef TEST
, parse
, md5
#endif
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Exception (SomeException(..), Exception(..), catch)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Crypto.Hash (Digest, MD5, hash)
import Data.Aeson ((.:), Value(..), decode)
import Data.Aeson.Types (parseMaybe)
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.ByteString as Strict
import Data.Map (Map)
import qualified Data.Map as M
import Data.Monoid
import Data.Profunctor (Choice, dimap, right')
import Data.String (IsString(..))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Read as T
import Data.Typeable (Typeable, cast)
import qualified Network.HTTP.Client as Http
import qualified Network.HTTP.Client.TLS as Http
import Text.XML (Document, parseLBS, def)
import Text.XML.Cursor
import Lastfm.Internal
-- $sign
--
-- The signature is required for every
-- authenticated API request. Basically,
-- every such request appends the md5 footprint
-- of its arguments to the query as
-- described at <http://www.last.fm/api/authspec#8>
-- | 'Supported' provides parsing for the chosen 'Format'
--
-- 'JSON' is parsed to 'Value' type from aeson, while 'XML'
-- is parsed to 'Document' from xml-conduit
class Supported f r | f -> r, r -> f where
prepareRequest :: R f -> R f
parseResponseBody :: Lazy.ByteString -> Maybe r
parseResponseEncodedError :: r -> Maybe LastfmError
instance Supported 'JSON Value where
prepareRequest r = r { _query = M.singleton "format" "json" `M.union` _query r }
parseResponseBody = decode
parseResponseEncodedError = parseMaybe $ \(Object o) -> do
code <- o .: "error"
msg <- o .: "message"
return (LastfmEncodedError code msg)
instance Supported 'XML Document where
prepareRequest = id
parseResponseBody = either (const Nothing) Just . parseLBS def
parseResponseEncodedError doc = case fromDocument doc of
cur
| [mcode] <- cur $| element "lfm" >=> child >=> element "error" >=> attribute "code"
, Right (code, _) <- T.decimal mcode
, [msg] <- cur $| element "lfm" >=> child >=> element "error" >=> child >=> content
-> Just (LastfmEncodedError code (T.strip msg))
|
otherwise -> Nothing
parse :: Supported f r => Lazy.ByteString -> Either LastfmError r
parse body = case parseResponseBody body of
Just v
| Just e <- parseResponseEncodedError v -> Left e
| otherwise -> Right v
Nothing -> Left (LastfmBadResponse body)
base :: R f
base = R
{ _host = "https://ws.audioscrobbler.com/2.0/"
, _method = "GET"
, _query = mempty
}
-- | Different ways last.fm response can be unusable
data LastfmError =
-- | last.fm thinks it responded with something legible, but it really isn't
LastfmBadResponse Lazy.ByteString
-- | last.fm error code and message string
| LastfmEncodedError Int Text
-- | wrapped http-conduit exception
| LastfmHttpError Http.HttpException
deriving (Show, Typeable)
-- | Admittedly, this isn't the best 'Eq' instance ever
-- but not having 'Eq' 'C.HttpException' does not leave much a choice
instance Eq LastfmError where
LastfmBadResponse bs == LastfmBadResponse bs' = bs == bs'
LastfmEncodedError e s == LastfmEncodedError e' t = e == e' && s == t
LastfmHttpError _ == LastfmHttpError _ = True
_ == _ = False
instance Exception LastfmError where
fromException e@(SomeException se)
| Just e' <- fromException e = Just (LastfmHttpError e')
| otherwise = cast se
class AsLastfmError t where
_LastfmError :: (Choice p, Applicative m) => p LastfmError (m LastfmError) -> p t (m t)
instance AsLastfmError LastfmError where
_LastfmError = id
{-# INLINE _LastfmError #-}
instance AsLastfmError SomeException where
_LastfmError = dimap (\e -> maybe (Left e) Right (fromException e)) (either pure (fmap toException)) . right'
{-# INLINE _LastfmError #-}
-- | This is a @ Prism' 'LastfmError' 'Lazy.ByteString' @ in disguise
_LastfmBadResponse
:: (Choice p, Applicative m, AsLastfmError e)
=> p Lazy.ByteString (m Lazy.ByteString) -> p e (m e)
_LastfmBadResponse = _LastfmError . dimap go (either pure (fmap LastfmBadResponse)) . right' where
go (LastfmBadResponse bs) = Right bs
go x = Left x
{-# INLINE go #-}
{-# INLINE _LastfmBadResponse #-}
-- | This is a @ Prism' 'LastfmError' ('Int', 'String') @ in disguise
_LastfmEncodedError
:: (Choice p, Applicative m, AsLastfmError e)
=> p (Int, Text) (m (Int, Text)) -> p e (m e)
_LastfmEncodedError = _LastfmError . dimap go (either pure (fmap (uncurry LastfmEncodedError))) . right' where
go (LastfmEncodedError n v) = Right (n, v)
go x = Left x
{-# INLINE go #-}
{-# INLINE _LastfmEncodedError #-}
-- | This is a @ Prism' 'LastfmError' 'C.HttpException' @ in disguise
_LastfmHttpError
:: (Choice p, Applicative m, AsLastfmError e)
=> p Http.HttpException (m Http.HttpException) -> p e (m e)
_LastfmHttpError = _LastfmError . dimap go (either pure (fmap LastfmHttpError)) . right' where
go (LastfmHttpError e) = Right e
go x = Left x
{-# INLINE go #-}
{-# INLINE _LastfmHttpError #-}
-- | Application secret
newtype Secret = Secret Text deriving (Show, Eq, Typeable)
instance IsString Secret where
fromString = Secret . fromString
-- | Sign the 'Request' with the 'Secret' so it's ready to be sent
sign :: Secret -> Request f Sign -> Request f Ready
sign s = coerce . (<* signature)
where
signature = wrap $
\r@R { _query = q } -> r { _query = apiSig s . authToken $ q }
authToken :: Map Text Text -> Map Text Text
authToken q = maybe q (M.delete "password") $ do
password <- M.lookup "password" q
username <- M.lookup "username" q
return (M.insert "authToken" (md5 (username <> md5 password)) q)
apiSig :: Secret -> Map Text Text -> Map Text Text
apiSig (Secret s) q = M.insert "api_sig" (signer (foldr M.delete q ["format", "callback"])) q
where
signer = md5 . M.foldrWithKey (\k v xs -> k <> v <> xs) s
-- | Get supplied string md5 hash hex representation
md5 :: Text -> Text
md5 = T.pack . show . (hash :: Strict.ByteString -> Digest MD5) . T.encodeUtf8
-- | Lastfm connection manager
newtype Connection = Connection Http.Manager
-- | Creating an HTTPS connection manager is expensive; it's advised to use
-- a single 'Connection' for all communications with last.fm
withConnection :: MonadIO m => (Connection -> m a) -> m a
withConnection f = f =<< newConnection
-- | Create a 'Connection'. Note that there's no need to close the connection manually,
-- as it will be closed automatically when no longer in use, that is, all the requests have
-- been processed and it's about to be garbage collected.
newConnection :: MonadIO m => m Connection
newConnection = liftIO (fmap Connection (Http.newManager Http.tlsManagerSettings))
-- | Perform the 'Request' and parse the response
lastfm :: Supported f r => Connection -> Request f Ready -> IO (Either LastfmError r)
lastfm man = lastfmWith man parse . finalize
-- | Perform the 'Request' ignoring any responses
lastfm_ :: Supported f r => Connection -> Request f Ready -> IO (Either LastfmError ())
lastfm_ man = lastfmWith man (\_ -> Right ()) . finalize
-- | Send the 'R' and parse the 'Response' with the supplied parser
lastfmWith
:: Connection
-> (Lazy.ByteString -> Either LastfmError a)
-> R f
-> IO (Either LastfmError a)
lastfmWith (Connection man) p r = do
req <- Http.parseUrlThrow (render r)
let req' = req
{ Http.method = _method r
}
p . Http.responseBody <$> Http.httpLbs req' man
`catch`
(return . Left)
-- | Get the 'R' from the 'Request'
finalize :: Supported f r => Request f Ready -> R f
finalize x = (prepareRequest . unwrap x) base
| supki/liblastfm | src/Lastfm/Response.hs | mit | 8,682 | 0 | 18 | 1,917 | 2,346 | 1,247 | 1,099 | 163 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveGeneric #-}
module Connector(http) where
import Network.Wai
import Network.Wai.Handler.WebSockets
import Network.HTTP.Types
import Network.WebSockets
import GHC.Generics
import Database.Persist hiding (get)
import Data.Aeson
import qualified Data.Text as T
import Data.Maybe
import Data.Typeable
import Control.Monad
import Control.Exception
import Data.Text.Encoding
import qualified Data.ByteString.Lazy as BL
import qualified Data.Vault.Lazy as V
import Ledger as L
import Model.Account as M
import DB.Schema as S
import Http
data Connector = Connector {
id :: T.Text,
name :: T.Text,
connector :: T.Text
} deriving (Show, Generic)
instance ToJSON Connector
http ledger uriParams req respond = doit `catch` (respond . caught)
where
doit = do
let method = requestMethod req
if | method == methodGet -> get ledger req respond
| otherwise -> throw UnknownMethod
get ledger req respond = do
list <- runDB ledger $ selectList [AccountConnector !=. Nothing] []
respond $ responseLBS status200
standardHeaders
(encode $ map (build . entityVal) list)
where build e = Connector uri name (fromJust $ accountConnector e)
where name = accountName e
uri = T.concat [baseUri ledger, "/accounts/", name]
| gip/cinq-cloches-ledger | src/Connector.hs | mit | 1,437 | 0 | 13 | 284 | 396 | 224 | 172 | 44 | 2 |
module PA1Helper(runProgram,Lexp(..)) where
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Expr
import Text.Parsec.Token
import Text.Parsec.Language
import Text.Parsec.Char
-- Use previously defined parser to parse a given String
parseLExpr :: String -> Either ParseError Lexp
parseLExpr input = parse start "" input
-- Gracefully handle parse errors, proceeding to the next expression in the file and printing a helpful message
handler :: (Lexp -> Lexp) -> Int -> String -> IO ()
handler reducer n str = case parseLExpr str of
Left err -> putStrLn ("Parse error for expression " ++ show n ++ ": " ++ show err)
Right lexp -> outputPrinter n lexp (reducer lexp)
-- Pretty printer for outputting inputted lambda expressions along with
-- their reduced expressions. Integer used to distiguish between test cases.
outputPrinter :: Int -> Lexp -> Lexp -> IO ()
outputPrinter n lexp lexp' = do
putStrLn ("Input " ++ (show n) ++ ": " ++ (show lexp))
putStrLn ("Result " ++ (show n) ++ ": " ++ (show lexp'))
-- Given a filename and function for reducing lambda expressions,
-- reduce all valid lambda expressions in the file and output results.
runProgram :: String -> (Lexp -> Lexp) -> IO ()
runProgram fileName reducer = do
fcontents <- readFile fileName
let inList = lines fcontents
sequence_ (zipWith (handler reducer) [1..] inList)
calculus :: String -> String
calculus
main = do
putStrLn "Please enter a filename containing lambda expressions:"
f <- getLine
let outStr = runProgram f calculus
-- Haskell representation of lambda expression
data Lexp = Atom String | Lambda String Lexp | Apply Lexp Lexp deriving Eq
-- Allow for Lexp datatype to be printed like the Oz representation of a lambda expression
instance Show Lexp where
show (Atom v) = v
show (Lambda exp1 exp2) = "\\" ++ exp1 ++ "." ++ (show exp2)
show (Apply exp1 exp2) = "(" ++ (show exp1) ++ " " ++ (show exp2) ++ ")"
-- Reserved keywords in Oz
-- P. 841 Table C.8, "Concepts, Techniques, and Models of Computer Programming",
-- Van Roy, Haridi
ozKeywords = ["andthen","at","attr","break"
,"case","catch","choice","class"
,"collect","cond","continue"
,"declare","default","define"
,"dis","div","do","else"
,"elsecase","elseif","elseof"
,"end","export","fail","false"
,"feat","finally","for","from"
,"fun","functor","if","import"
,"in","lazy","local","lock"
,"meth","mod","not","of","or"
,"orelse","prepare","proc"
,"prop","raise","require"
,"return","self","skip","then"
,"thread","true","try","unit"
]
-- Sparse language definition to define a proper Oz identifier
-- An atom is defined as follows:
-- 1. sequence of alphanumeric chars starting with a lowercase letter,
-- excluding language keywords
-- 2. arbitrary printable chars enclosed in single quotes,
-- excluding "'", "\", and "NUL"
-- lDef defines an atom as only 1.
-- P. 825,"Concepts, Techniques, and Models of Computer Programming",
-- Van Roy, Haridi
lDef = emptyDef { identStart = lower
, identLetter = alphaNum
, reservedNames = ozKeywords
}
-- Obtains helper functions for parsing
TokenParser{ parens = m_parens
, identifier = m_identifier
, reserved = m_reserved
, brackets = m_brackets
} = makeTokenParser lDef
-- Below is code to parse Oz lambda expressions and represent them in Haskell
atom = do
var <- m_identifier
return (Atom var)
lambargs = do
var1 <- m_identifier
char '.'
var2 <- start
return (Lambda var1 var2)
lamb = do
char '\\'
p <- lambargs
return p
appargs = do
var1 <- start
spaces
var2 <- start
return (Apply var1 var2)
app = do
p <- m_parens appargs
return p
start = atom <|> lamb <|> app
| Yelmogus/Lambda_Interpreter | main.hs | mit | 4,173 | 13 | 21 | 1,159 | 976 | 514 | 462 | -1 | -1 |
module HAD.Y2014.M02.D24.Exercise where
-- | Filter a list, keeping an element only if it is equal to the next one.
--
-- Examples:
-- >>> filterByPair []
-- []
-- >>> filterByPair [1 .. 10]
-- []
-- >>> filterByPair [1, 2, 2, 2, 3, 3, 4]
-- [2,2,3]
filter' :: (Eq a) => a -> ([a], Maybe a) -> ([a], Maybe a)
filter' c (_, Nothing) = ([], Just c)
filter' c (xs, Just x)
| c == x = (x:xs, Just c)
| otherwise = (xs, Just c)
filterByPair :: (Eq x) => [x] -> [x]
filterByPair l = fst $ foldr filter' ([], Nothing) l
main = print $ filterByPair [1,2,2,3,3,3,4,4]
| espencer/1HAD | exercises/HAD/Y2014/M02/D24/Exercise.hs | mit | 575 | 0 | 9 | 130 | 238 | 137 | 101 | 9 | 1 |
data Lista a = Nill | Cost a (Lista a) deriving (Show, Eq, Ord)
veces :: (Eq a) a -> [a] -> Int
veces x [] = 0
vecces x (h:t) = if x == h then 1 + (veces x t) else veces x t
| josegury/HaskellFuntions | Listas/Int-NumElementRepetido.hs | mit | 178 | 0 | 8 | 50 | 127 | 64 | 63 | 4 | 2 |
-- |
-- Module : HGE2D.Datas
-- Copyright : (c) 2016 Martin Buck
-- License : see LICENSE
--
-- Containing data definitions used within HGE2D
module HGE2D.Datas where
import HGE2D.Types
import qualified Graphics.Rendering.OpenGL as GL
-- | A physical object with position, sizes, velocities, accelerations, mass, drag etc.
data PhysicalObject = PhysicalObject
{ physicalPos :: RealPosition
, physicalVel :: Velocity
, physicalAcc :: Acceleration
, physicalBB :: BoundingBox
, physicalRot :: Radian
, physicalRotSpeed :: RotationSpeed ---TODO rename to ..Vel
, physicalRotAcceleration :: RotationAcceleration ---TODO rename to Acc
, physicalMass :: Mass
, physicalDrag :: Drag
, physicalRotDrag :: Drag ---TODO RotDrag?
} deriving (Show, Read, Eq)
-- | A rigidbody defined by position, size and velocity
data RigidBody = RigidBody
{ rigidPos :: RealPosition -- current position
, rigidVel :: Velocity -- current velocity
, rigidBB :: BoundingBox -- bounding box
} deriving (Show, Read, Eq)
-- | A bounding box defined by two positions in space
data BoundingBox = BBEmpty
| BB
{ bbMin :: RealPosition -- lower left corner of bb
, bbMax :: RealPosition -- upper right corner of bb
}
deriving (Show, Read, Eq)
-- | A position defined in number of tiles in x and y direction
data TilePosition = TilePosition
{ tileX :: Int -- position in number of tiles from left starting with 0
, tileY :: Int -- position in number of tiles from top starting with 0
} deriving (Show, Read, Eq)
--------------------------------------------------------------------------------
-- | The enginestate which defines multiple callbacks required by the engine to interact with the gamestate
data EngineState a = EngineState
{ click :: PosX -> PosY -> a -> a -- how your game should change when clicked
, mUp :: PosX -> PosY -> a -> a -- how your game should change when mouse up happens
, hover :: PosX -> PosY -> a -> a -- how your game should change when hovered
, drag :: PosX -> PosY -> a -> a -- how your game should change when dragged
, kDown :: PosX -> PosY -> Char -> a -> a -- how your game should change when a keyDown happened
, kUp :: PosX -> PosY -> Char -> a -> a -- how your game should change when a keyUp happened
, resize :: (Width, Height) -> a -> a -- how to resize your game
, getSize :: a -> (Width, Height) -- how to get the size of your game
, moveTime :: Millisecond -> a -> a -- how your game should change over time
, getTime :: a -> Millisecond -- how to get the current time of your game
, setTime :: Millisecond -> a -> a -- how to set the time of your game
, getTitle :: a -> String -- how to get the title of your game
, toGlInstr :: a -> RenderInstruction -- how to receive a render instruction to display your game
}
--------------------------------------------------------------------------------
-- | The instructions used to render the game
data RenderInstruction = RenderNothing -- do nothing
| RenderWithCamera GlPosX GlPosY GlScaleX GlScaleY RenderInstruction -- render with a given camera view
| RenderText String -- render a string
| RenderPoints GlShape -- render as points
| RenderLineStrip GlShape GL.GLfloat -- render as line strip
| RenderTriangle GlShape -- render as triangles / faces
| RenderLineLoop GlShape GL.GLfloat -- render as line which connects first and last
| RenderScale GlScaleX GlScaleY -- change scale
| RenderTranslate GlPosX GlPosY -- translate / move following instructions
| RenderRotate Double -- rotate following instructions
| RenderColorize GlColorRGB -- colorize following instructions
| RenderColorizeAlpha GlColorRGBA -- colorize following instructions with alpha setting
| RenderPreserve RenderInstruction -- render instruction while preserving rotation / translation
| RenderMany [RenderInstruction] -- render multiple other instructions
| I3ck/HGE2D | src/HGE2D/Datas.hs | mit | 5,133 | 0 | 12 | 1,978 | 587 | 368 | 219 | 57 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module MonadBot.Plugins.Auth
where
import Data.List
import qualified Data.Text as T
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import MonadBot.Plugin.Development
-- data AuthState = AuthState (Maybe (Text, Text))
-- addGroup :: PluginM a ()
-- addGroup =
-- onUserCmd "$addgroup" $
-- whenInGroup "owner" $ do
-- (chan:_:g:_) <- getParams
-- void $ modifyAuthEntries $ \ae ->
-- ae { groups = S.insert g (groups ae) }
-- sendPrivmsg chan ["Group " <> g <> " added."]
-- addUser :: PluginM AuthState ()
-- addUser =
-- onUserCmd "$adduser" $
-- whenInGroup "owner" $ do
-- (AuthEntries gs _) <- getAuthEntries
-- (chan:_:u:g:_) <- getParams
-- if g `elem` gs
-- then do
-- void $ swapState (AuthState (Just (g, chan)))
-- sendCommand "WHOIS" [u]
-- else sendPrivmsg chan ["Group " <> g <> " does not exist."]
-- handleWhois :: PluginM AuthState ()
-- handleWhois =
-- onCmd "311" $ do
-- (AuthState (Just (g, chan))) <- readState
-- (_:n:u:h:_) <- getParams
-- sendPrivmsg chan ["Added user " <> n <> "."]
-- (AuthEntries _ um) <- getAuthEntries
-- void $ modifyAuthEntries $ \ae ->
-- ae { users = M.insertWith S.union (UserPrefix n (Just u) (Just h)) (S.singleton g) um}
-- return ()
-- listGroups :: PluginM a ()
-- listGroups =
-- onUserCmd "$listgroups" $
-- whenInGroup "owner" $ do
-- (AuthEntries gs _) <- getAuthEntries
-- (chan:_) <- getParams
-- sendPrivmsg chan ["My user groups are: " <> T.intercalate ", " (S.toList gs)]
-- listUsers :: PluginM a ()
-- listUsers =
-- onUserCmd "$listusers" $
-- whenInGroup "owner" $ do
-- (AuthEntries _ um) <- getAuthEntries
-- (chan:_) <- getParams
-- sendPrivmsg chan ["These are my operators:"]
-- forM_ (M.toList um) $ \(u, gs) ->
-- sendPrivmsg chan [pNick u <> " - {" <> T.intercalate ", " (S.toList gs) <> "}"]
-- plugin :: Plugin AuthState
-- plugin =
-- Plugin
-- "User and group management plugin"
-- [addGroup, addUser, listGroups, listUsers, handleWhois]
-- (return (AuthState Nothing))
-- (const $ return ())
| saevarb/Monadbot | lib/MonadBot/Plugins/Auth.hs | mit | 2,246 | 0 | 4 | 558 | 97 | 85 | 12 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.