code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
module Dampf.ConfigFile.Pretty
( pShowDampfConfig
) where
import Control.Lens
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import Text.PrettyPrint
import Dampf.ConfigFile.Types
pShowDampfConfig :: DampfConfig -> String
pShowDampfConfig = render . hang (text "Config File:") 4 . pprDampfConfig
pprDampfConfig :: DampfConfig -> Doc
pprDampfConfig cfg = vcat
[ pprDatabaseServer d
]
where
d = cfg ^. postgres
pprLiveCertificate :: Maybe FilePath -> Doc
pprLiveCertificate (Just l) = vcat
[ text "Live Certificate:"
, text ""
, nest 4 (text l)
, text ""
]
pprLiveCertificate Nothing = empty
pprDatabaseServer :: Maybe PostgresConfig -> Doc
pprDatabaseServer (Just s) = vcat
[ text "Database Server:"
, text ""
, nest 4 (pprPostgresConfig s)
, text ""
]
pprDatabaseServer Nothing = empty
pprPostgresConfig :: PostgresConfig -> Doc
pprPostgresConfig cfg = vcat
[ text "host:" <+> text h
, text "port:" <+> int p
, text "users:"
, nest 4 (pprMap u)
]
where
h = cfg ^. host . to T.unpack
p = cfg ^. port
u = cfg ^. users . to Map.toList
pprMap :: (Show a) => [(a, a)] -> Doc
pprMap kvs = vcat
$ fmap (\(k, v) -> text (show k) <> colon <+> text (show v)) kvs
|
diffusionkinetics/open
|
dampf/lib/Dampf/ConfigFile/Pretty.hs
|
Haskell
|
mit
| 1,322
|
module Main where
import Console.Options
import Data.Char (isDigit)
import Data.Monoid
data MyADT = A | B | C
deriving (Show,Eq)
main = defaultMain $ do
programName "my-simple-program"
programDescription "an optional description of your program that can be found in the help"
-- a simple boolean flag -v or --verbose
showFlag <- flag (FlagShort 'v' <> FlagLong "verbose" <> FlagDescription "activate verbose mode")
-- a flag '-n' or '--name' requiring a string as parameter
nameFlag <- flagParam (FlagShort 'n' <> FlagLong "name" <> FlagDescription "name of something")
(FlagRequired $ \s -> Right s)
-- a flag 'i' or '--int' requiring an integer as parameter
valueFlag <- flagParam (FlagShort 'i' <> FlagLong "int" <> FlagDescription "an integer value")
(FlagRequired $ \s -> if all isDigit s then Right (read s :: Int) else Left "invalid integer")
-- a flag with an optional parameter, defaulting to some value
xyzFlag <- flagParam (FlagShort 'x' <> FlagLong "xyz" <> FlagDescription "some ADT option")
(FlagOptional B (\s -> if s == "A" then Right A else if s == "B" then Right B else if s == "C" then Right C else Left "invalid value"))
action $ \toParam -> do
putStrLn $ show $ toParam showFlag
putStrLn $ show $ toParam nameFlag
putStrLn $ show $ toParam valueFlag
putStrLn $ show $ toParam xyzFlag
|
NicolasDP/hs-cli
|
examples/Simple.hs
|
Haskell
|
bsd-3-clause
| 1,477
|
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Arrays where
import Language.VHDL (Mode(..))
import Language.Embedded.Hardware
import Control.Monad.Identity
import Control.Monad.Operational.Higher
import Data.ALaCarte
import Data.Int
import Data.Word
import Text.PrettyPrint
import Prelude hiding (and, or, not)
--------------------------------------------------------------------------------
-- * Example of a program that words with variable length bit arrarys.
--------------------------------------------------------------------------------
-- | Command set used for our programs.
type CMD =
SignalCMD
:+: VariableCMD
:+: ArrayCMD
:+: VArrayCMD
:+: LoopCMD
:+: ConditionalCMD
:+: ComponentCMD
:+: ProcessCMD
:+: VHDLCMD
type HProg = Program CMD (Param2 HExp HType)
type HSig = Sig CMD HExp HType Identity
--------------------------------------------------------------------------------
arrays :: HProg ()
arrays =
do a :: Array Word8 <- newArray 20
b :: VArray Word8 <- newVArray 10
setArray a 0 0
setVArray b 1 1
resetArray a 1
va :: HExp Word8 <- getArray a 0
vb :: HExp Word8 <- getVArray b 1
setArray a 0 (va + 2 - vb)
setVArray b 1 (vb + 2 - va)
copyArray (a, 0) (a, 2) 4
--------------------------------------------------------------------------------
test = icompile arrays
--------------------------------------------------------------------------------
|
markus-git/imperative-edsl-vhdl
|
examples/Array.hs
|
Haskell
|
bsd-3-clause
| 1,557
|
{-# LANGUAGE CPP #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
------------------------------------------------------------------------
-- |
-- Module : Data.Hashable
-- Copyright : (c) Milan Straka 2010
-- (c) Johan Tibell 2011
-- (c) Bryan O'Sullivan 2011, 2012
-- License : BSD-style
-- Maintainer : johan.tibell@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- This module defines a class, 'Hashable', for types that can be
-- converted to a hash value. This class exists for the benefit of
-- hashing-based data structures. The module provides instances for
-- most standard types. Efficient instances for other types can be
-- generated automatically and effortlessly using the generics support
-- in GHC 7.2 and above.
--
-- The easiest way to get started is to use the 'hash' function. Here
-- is an example session with @ghci@.
--
-- > ghci> import Data.Hashable
-- > ghci> hash "foo"
-- > 60853164
module Data.Hashable
(
-- * Hashing and security
-- $security
-- * Computing hash values
Hashable(..)
-- * Creating new instances
-- | There are two ways to create new instances: by deriving
-- instances automatically using GHC's generic programming
-- support or by writing instances manually.
-- ** Generic instances
-- $generics
-- *** Understanding a compiler error
-- $generic_err
-- ** Writing instances by hand
-- $blocks
-- *** Hashing contructors with multiple fields
-- $multiple-fields
-- *** Hashing types with multiple constructors
-- $multiple-ctors
, hashUsing
, hashPtr
, hashPtrWithSalt
#if defined(__GLASGOW_HASKELL__)
, hashByteArray
, hashByteArrayWithSalt
#endif
) where
import Data.Hashable.Class
#ifdef GENERICS
import Data.Hashable.Generic ()
#endif
-- $security
-- #security#
--
-- Applications that use hash-based data structures to store input
-- from untrusted users can be susceptible to \"hash DoS\", a class of
-- denial-of-service attack that uses deliberately chosen colliding
-- inputs to force an application into unexpectedly behaving with
-- quadratic time complexity.
--
-- At this time, the string hashing functions used in this library are
-- susceptible to such attacks and users are recommended to either use
-- a 'Data.Map' to store keys derived from untrusted input or to use a
-- hash function (e.g. SipHash) that's resistant to such attacks. A
-- future version of this library might ship with such hash functions.
-- $generics
--
-- Beginning with GHC 7.2, the recommended way to make instances of
-- 'Hashable' for most types is to use the compiler's support for
-- automatically generating default instances.
--
-- > {-# LANGUAGE DeriveGeneric #-}
-- >
-- > import GHC.Generics (Generic)
-- > import Data.Hashable
-- >
-- > data Foo a = Foo a String
-- > deriving (Eq, Generic)
-- >
-- > instance Hashable a => Hashable (Foo a)
-- >
-- > data Colour = Red | Green | Blue
-- > deriving Generic
-- >
-- > instance Hashable Colour
--
-- If you omit a body for the instance declaration, GHC will generate
-- a default instance that correctly and efficiently hashes every
-- constructor and parameter.
-- $generic_err
--
-- Suppose you intend to use the generic machinery to automatically
-- generate a 'Hashable' instance.
--
-- > data Oops = Oops
-- > -- forgot to add "deriving Generic" here!
-- >
-- > instance Hashable Oops
--
-- And imagine that, as in the example above, you forget to add a
-- \"@deriving 'Generic'@\" clause to your data type. At compile time,
-- you will get an error message from GHC that begins roughly as
-- follows:
--
-- > No instance for (GHashable (Rep Oops))
--
-- This error can be confusing, as 'GHashable' is not exported (it is
-- an internal typeclass used by this library's generics machinery).
-- The correct fix is simply to add the missing \"@deriving
-- 'Generic'@\".
-- $blocks
--
-- To maintain high quality hashes, new 'Hashable' instances should be
-- built using existing 'Hashable' instances, combinators, and hash
-- functions.
--
-- The functions below can be used when creating new instances of
-- 'Hashable'. For example, for many string-like types the
-- 'hashWithSalt' method can be defined in terms of either
-- 'hashPtrWithSalt' or 'hashByteArrayWithSalt'. Here's how you could
-- implement an instance for the 'B.ByteString' data type, from the
-- @bytestring@ package:
--
-- > import qualified Data.ByteString as B
-- > import qualified Data.ByteString.Internal as B
-- > import qualified Data.ByteString.Unsafe as B
-- > import Data.Hashable
-- > import Foreign.Ptr (castPtr)
-- >
-- > instance Hashable B.ByteString where
-- > hashWithSalt salt bs = B.inlinePerformIO $
-- > B.unsafeUseAsCStringLen bs $ \(p, len) ->
-- > hashPtrWithSalt p (fromIntegral len) salt
-- $multiple-fields
--
-- Hash constructors with multiple fields by chaining 'hashWithSalt':
--
-- > data Date = Date Int Int Int
-- >
-- > instance Hashable Date where
-- > hashWithSalt s (Date yr mo dy) =
-- > s `hashWithSalt`
-- > yr `hashWithSalt`
-- > mo `hashWithSalt` dy
--
-- If you need to chain hashes together, use 'hashWithSalt' and follow
-- this recipe:
--
-- > combineTwo h1 h2 = h1 `hashWithSalt` h2
-- $multiple-ctors
--
-- For a type with several value constructors, there are a few
-- possible approaches to writing a 'Hashable' instance.
--
-- If the type is an instance of 'Enum', the easiest path is to
-- convert it to an 'Int', and use the existing 'Hashable' instance
-- for 'Int'.
--
-- > data Color = Red | Green | Blue
-- > deriving Enum
-- >
-- > instance Hashable Color where
-- > hashWithSalt = hashUsing fromEnum
--
-- If the type's constructors accept parameters, it is important to
-- distinguish the constructors. To distinguish the constructors, add
-- a different integer to the hash computation of each constructor:
--
-- > data Time = Days Int
-- > | Weeks Int
-- > | Months Int
-- >
-- > instance Hashable Time where
-- > hashWithSalt s (Days n) = s `hashWithSalt`
-- > (0::Int) `hashWithSalt` n
-- > hashWithSalt s (Weeks n) = s `hashWithSalt`
-- > (1::Int) `hashWithSalt` n
-- > hashWithSalt s (Months n) = s `hashWithSalt`
-- > (2::Int) `hashWithSalt` n
|
ekmett/hashable
|
Data/Hashable.hs
|
Haskell
|
bsd-3-clause
| 6,626
|
module WithCli.Normalize (
normalize,
matches,
) where
import Data.Char
matches :: String -> String -> Bool
matches a b =
normalize a == normalize b
normalize :: String -> String
normalize s =
if all (not . isAllowedChar) s
then s
else
slugify $
dropWhile (== '-') $
filter isAllowedChar $
map (\ c -> if c == '_' then '-' else c) $
s
where
slugify (a : r)
| isUpper a = slugify (toLower a : r)
slugify (a : b : r)
| isUpper b = a : '-' : slugify (toLower b : r)
| otherwise = a : slugify (b : r)
slugify x = x
isAllowedChar :: Char -> Bool
isAllowedChar c = (isAscii c && isAlphaNum c) || (c `elem` "-_")
|
kosmikus/getopt-generics
|
src/WithCli/Normalize.hs
|
Haskell
|
bsd-3-clause
| 700
|
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.IO.Unsafe
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- \"Unsafe\" IO operations.
--
-----------------------------------------------------------------------------
module System.IO.Unsafe (
-- * Unsafe 'System.IO.IO' operations
unsafePerformIO,
unsafeDupablePerformIO,
unsafeInterleaveIO,
unsafeFixIO,
) where
import GHC.Base
import GHC.IO
import GHC.IORef
import GHC.Exception
import Control.Exception
-- | A slightly faster version of `System.IO.fixIO` that may not be
-- safe to use with multiple threads. The unsafety arises when used
-- like this:
--
-- > unsafeFixIO $ \r -> do
-- > forkIO (print r)
-- > return (...)
--
-- In this case, the child thread will receive a @NonTermination@
-- exception instead of waiting for the value of @r@ to be computed.
--
-- @since 4.5.0.0
unsafeFixIO :: (a -> IO a) -> IO a
unsafeFixIO k = do
ref <- newIORef (throw NonTermination)
ans <- unsafeDupableInterleaveIO (readIORef ref)
result <- k ans
writeIORef ref result
return result
|
alexander-at-github/eta
|
libraries/base/System/IO/Unsafe.hs
|
Haskell
|
bsd-3-clause
| 1,363
|
module MonadIn2 where
f (a, b, c)
= do let (z, y) = (a, b)
case (z, y) of
(l, m) -> return (l, m)
f_1 (a, b, c)
= do let (z, y) = (a, b)
case (z, y) of
(l, m) -> return 0
|
kmate/HaRe
|
old/testing/simplifyExpr/MonadIn2AST.hs
|
Haskell
|
bsd-3-clause
| 238
|
module DemoSpec where
import Test.Hspec
spec :: Spec
spec =
describe "demo" $
specify "trivial" $
() `shouldBe` ()
|
Javran/misc
|
yesod-min/test/DemoSpec.hs
|
Haskell
|
mit
| 130
|
{-# OPTIONS -XOverloadedStrings #-}
import Network.AMQP
import qualified Data.ByteString.Lazy.Char8 as BL
main :: IO ()
main = do
conn <- openConnection "127.0.0.1" "/" "guest" "guest"
ch <- openChannel conn
declareQueue ch newQueue {queueName = "hello",
queueAutoDelete = False,
queueDurable = False}
publishMsg ch "" "hello"
(newMsg {msgBody = (BL.pack "Hello World!"),
msgDeliveryMode = Just NonPersistent})
putStrLn " [x] Sent 'Hello World!'"
closeConnection conn
|
yepesasecas/rabbitmq-tutorials
|
haskell/send.hs
|
Haskell
|
apache-2.0
| 625
|
-- !!! test RealFrac ops (ceiling/floor/etc.) on Floats/Doubles
--
main =
putStr $
unlines
[ -- just for fun, we show the floats to
-- exercise the code responsible.
'A' : show (float_list :: [Float])
, 'B' : show (double_list :: [Double])
-- {Float,Double} inputs, {Int,Integer} outputs
, 'C' : show ((map ceiling small_float_list) :: [Int])
, 'D' : show ((map ceiling float_list) :: [Integer])
, 'E' : show ((map ceiling small_double_list) :: [Int])
, 'F' : show ((map ceiling double_list) :: [Integer])
, 'G' : show ((map floor small_float_list) :: [Int])
, 'H' : show ((map floor float_list) :: [Integer])
, 'I' : show ((map floor small_double_list) :: [Int])
, 'J' : show ((map floor double_list) :: [Integer])
, 'K' : show ((map truncate small_float_list) :: [Int])
, 'L' : show ((map truncate float_list) :: [Integer])
, 'M' : show ((map truncate small_double_list) :: [Int])
, 'N' : show ((map truncate double_list) :: [Integer])
, 'n' : show ((map round small_float_list) :: [Int])
, 'O' : show ((map round float_list) :: [Integer])
, 'P' : show ((map round small_double_list) :: [Int])
, 'Q' : show ((map round double_list) :: [Integer])
, 'R' : show ((map properFraction small_float_list) :: [(Int,Float)])
, 'S' : show ((map properFraction float_list) :: [(Integer,Float)])
, 'T' : show ((map properFraction small_double_list) :: [(Int,Double)])
, 'U' : show ((map properFraction double_list) :: [(Integer,Double)])
]
where
-- these fit into an Int when truncated. Truncation when the
-- result does not fit into the target is undefined - not explicitly
-- so in Haskell 98, but that's the interpretation we've taken in GHC.
-- See bug #1254
small_float_list :: [Float]
small_float_list = [
0.0, -0.0, 1.1, 2.8, 3.5, 4.5, -1.0000000001, -2.9999995,
-3.50000000001, -4.49999999999, 1000012.0, 123.456, 100.25,
102.5, 0.0012, -0.00000012, 1.7e4, -1.7e-4, 0.15e-6, pi
]
float_list :: [Float]
float_list = small_float_list ++ [
1.18088e+11, 1.2111e+14
]
-- these fit into an Int
small_double_list :: [Double]
small_double_list = [
0.0, -0.0, 1.1, 2.8, 3.5, 4.5, -1.0000000001, -2.9999995,
-3.50000000001, -4.49999999999, 1000012.0, 123.456, 100.25,
102.5, 0.0012, -0.00000012, 1.7e4, -1.7e-4, 0.15e-6, pi
]
double_list :: [Double]
double_list = small_double_list ++ [
1.18088e+11, 1.2111e+14
]
|
siddhanathan/ghc
|
testsuite/tests/numeric/should_run/arith005.hs
|
Haskell
|
bsd-3-clause
| 2,533
|
-- | Test for GHC 7.10+'s @BinaryLiterals@ extensions (see GHC #9224)
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Types
main = do
print [ I# 0b0#, I# -0b0#, I# 0b1#, I# -0b1#
, I# 0b00000000000000000000000000000000000000000000000000000000000000000000000000001#
, I# -0b00000000000000000000000000000000000000000000000000000000000000000000000000001#
, I# -0b11001001#, I# -0b11001001#
, I# -0b11111111#, I# -0b11111111#
]
print [ W# 0b0##, W# 0b1##, W# 0b11001001##, W# 0b11##, W# 0b11111111##
, W# 0b00000000000000000000000000000000000000000000000000000000000000000000000000001##
]
print [ 0b0, 0b1, 0b10, 0b11, 0b100, 0b101, 0b110, 0b111 :: Integer
, -0b0, -0b1, -0b10, -0b11, -0b100, -0b101, -0b110, -0b111
, 0b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
, -0b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
]
|
urbanslug/ghc
|
testsuite/tests/parser/should_run/BinaryLiterals1.hs
|
Haskell
|
bsd-3-clause
| 1,148
|
{-# LANGUAGE Trustworthy #-}
module Main where
import Prelude
import safe M_SafePkg6
main = putStrLn "test"
|
urbanslug/ghc
|
testsuite/tests/safeHaskell/check/pkg01/ImpSafeOnly07.hs
|
Haskell
|
bsd-3-clause
| 111
|
module Test where
data Fun = MkFun (Fun -> Fun)
data LList a = Nill | Conss a (LList a)
g :: Fun -> Fun
g f = f
|
siddhanathan/ghc
|
testsuite/tests/stranal/should_compile/fun.hs
|
Haskell
|
bsd-3-clause
| 113
|
{-# LANGUAGE OverloadedStrings #-}
module ModelTests
( vertexFileParts
, normalFileParts
, texCoordFileParts
, vertexOnlyFaceFileParts
, vertexNormalFaceFileParts
, completeFaceFileParts
, completeModel
, splittedFileParts
, assembleVertP
, assembleVertPN
, assembleVertPNTx
) where
import Test.HUnit
import qualified BigE.Attribute.Vert_P as Vert_P
import qualified BigE.Attribute.Vert_P_N as Vert_P_N
import qualified BigE.Attribute.Vert_P_N_Tx as Vert_P_N_Tx
import qualified BigE.Model.Assembler as Assembler
import BigE.Model.Parser (FilePart (..), Point (..), parser,
splitParts)
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as LBS
import Linear (V2 (..), V3 (..))
import Text.Megaparsec (runParser)
-- | Test parsing of vertex 'FilePart's only.
vertexFileParts :: Assertion
vertexFileParts = do
let parts1 = runParser parser "test" "v 1.1 2.2 3.3"
parts2 = runParser parser "test" "v 1.1 2.2 3.3\nv 4.4 5.5 6.6"
Right [ Vertex $ V3 1.1 2.2 3.3 ] @=? parts1
Right [ Vertex $ V3 1.1 2.2 3.3
, Vertex $ V3 4.4 5.5 6.6 ] @=? parts2
-- | Test parsing of vertex 'FilePart's only.
normalFileParts :: Assertion
normalFileParts = do
let parts1 = runParser parser "test" "vn 1.1 2.2 3.3"
parts2 = runParser parser "test" "vn 1.1 2.2 3.3\nvn 4.4 5.5 6.6"
Right [ Normal $ V3 1.1 2.2 3.3 ] @=? parts1
Right [ Normal $ V3 1.1 2.2 3.3
, Normal $ V3 4.4 5.5 6.6 ] @=? parts2
-- | Test parsing of texture coordinates 'FilePart's only.
texCoordFileParts :: Assertion
texCoordFileParts = do
let parts1 = runParser parser "test" "vt 1.1 2.2"
parts2 = runParser parser "test" "vt 1.1 2.2\nvt 4.4 5.5"
Right [ TexCoord $ V2 1.1 2.2 ] @=? parts1
Right [ TexCoord $ V2 1.1 2.2
, TexCoord $ V2 4.4 5.5 ] @=? parts2
-- | Test parsing of face coordinates for vertex only triangle faces.
vertexOnlyFaceFileParts :: Assertion
vertexOnlyFaceFileParts = do
let parts1 = runParser parser "test" "f 1// 2// 3//"
parts2 = runParser parser "test" "f 1// 2// 3//\nf 4// 5// 6//"
Right [ Triangle (Point 1 Nothing Nothing)
(Point 2 Nothing Nothing)
(Point 3 Nothing Nothing)
] @=? parts1
Right [ Triangle (Point 1 Nothing Nothing)
(Point 2 Nothing Nothing)
(Point 3 Nothing Nothing)
, Triangle (Point 4 Nothing Nothing)
(Point 5 Nothing Nothing)
(Point 6 Nothing Nothing)
] @=? parts2
-- | Test parsing of face coordinates for vertex//normal triangle faces.
vertexNormalFaceFileParts :: Assertion
vertexNormalFaceFileParts = do
let parts1 = runParser parser "test" "f 1//1 2//2 3//3"
parts2 = runParser parser "test" "f 1//1 2//2 3//3\nf 4//4 5//5 6//6"
Right [ Triangle (Point 1 Nothing (Just 1))
(Point 2 Nothing (Just 2))
(Point 3 Nothing (Just 3))
] @=? parts1
Right [ Triangle (Point 1 Nothing (Just 1))
(Point 2 Nothing (Just 2))
(Point 3 Nothing (Just 3))
, Triangle (Point 4 Nothing (Just 4))
(Point 5 Nothing (Just 5))
(Point 6 Nothing (Just 6))
] @=? parts2
-- | Test parsing of face coordinates for vertex/tex/normal triangle faces.
completeFaceFileParts :: Assertion
completeFaceFileParts = do
let parts1 = runParser parser "test" "f 1/2/3 2/3/4 3/4/5"
parts2 = runParser parser "test" "f 1/2/3 2/3/4 3/4/5\nf 4/5/6 5/6/7 6/7/8"
Right [ Triangle (Point 1 (Just 2) (Just 3))
(Point 2 (Just 3) (Just 4))
(Point 3 (Just 4) (Just 5))
] @=? parts1
Right [ Triangle (Point 1 (Just 2) (Just 3))
(Point 2 (Just 3) (Just 4))
(Point 3 (Just 4) (Just 5))
, Triangle (Point 4 (Just 5) (Just 6))
(Point 5 (Just 6) (Just 7))
(Point 6 (Just 7) (Just 8))
] @=? parts2
-- | Split the list of file parts into a tuple of components.
splittedFileParts :: Assertion
splittedFileParts = do
let (verts, normals, texCoords, triangles) = splitParts modelParts
[ Vertex $ V3 1 1 1, Vertex $ V3 (-1) 0 (-1) ] @=? verts
[ Normal $ V3 1 0 0, Normal $ V3 0.7 0.7 0 ] @=? normals
[ TexCoord $ V2 0 1, TexCoord $ V2 1 0 ] @=? texCoords
[ Triangle (Point 1 (Just 2) (Just 3)) (Point 2 (Just 3) (Just 4)) (Point 3 (Just 4) (Just 5))
, Triangle (Point 4 (Just 5) (Just 6)) (Point 5 (Just 6) (Just 7)) (Point 6 (Just 7) (Just 8))] @=? triangles
-- | Test parsing of a complete model.
completeModel :: Assertion
completeModel =
Right modelParts @=? runParser parser "test" model
-- | Test assembly of a simple model to vert_Ps.
assembleVertP :: Assertion
assembleVertP =
Just ([ Vert_P.Vertex { Vert_P.position = V3 1 1 0 }
, Vert_P.Vertex { Vert_P.position = V3 (-1) 1 0 }
, Vert_P.Vertex { Vert_P.position = V3 (-1) (-1) 0 }
, Vert_P.Vertex { Vert_P.position = V3 1 (-1) 0 }
], [0, 1, 2, 0, 2, 3])
@=? Assembler.assembleVertP squareParts
-- | Test assembly of a simple model to vert_P_Ns.
assembleVertPN :: Assertion
assembleVertPN =
Just ([ Vert_P_N.Vertex { Vert_P_N.position = V3 1 1 0
, Vert_P_N.normal = V3 0 0 1
}
, Vert_P_N.Vertex { Vert_P_N.position = V3 (-1) 1 0
, Vert_P_N.normal = V3 0 0 1
}
, Vert_P_N.Vertex { Vert_P_N.position = V3 (-1) (-1) 0
, Vert_P_N.normal = V3 0 0 1
}
, Vert_P_N.Vertex { Vert_P_N.position = V3 1 (-1) 0
, Vert_P_N.normal = V3 0 0 1
}
], [0, 1, 2, 0, 2, 3])
@=? Assembler.assembleVertPN squareParts
-- | Test assembly of a simple model to vert_P_N_Txs.
assembleVertPNTx :: Assertion
assembleVertPNTx =
Just ([ Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 1 1 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 1 1
}
, Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 (-1) 1 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 0 1
}
, Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 (-1) (-1) 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 0 0
}
, Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 1 (-1) 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 1 0
}
], [0, 1, 2, 0, 2, 3])
@=? Assembler.assembleVertPNTx squareParts
-- | Dummy model. Makes no sense geometerically.
model :: ByteString
model = LBS.pack $ unlines
[ "# Test model"
, "mtllib test.mtl"
, "# Vertices"
, "v 1.0 1.0 1.0"
, "v -1.0 0.0 -1.0"
, "# Texture coordinates"
, "vt 0.0 1.0"
, "vt 1.0 0.0"
, "# Normals"
, "vn 1.0 0.0 0.0"
, "vn 0.7 0.7 0.0"
, "usemtl test.png"
, "s off"
, "# Faces"
, "f 1/2/3 2/3/4 3/4/5"
, "f 4/5/6 5/6/7 6/7/8"
]
-- | The file parts that should be the result of the above model.
modelParts :: [FilePart]
modelParts =
[ Mtllib "test.mtl"
, Vertex $ V3 1 1 1
, Vertex $ V3 (-1) 0 (-1)
, TexCoord $ V2 0 1
, TexCoord $ V2 1 0
, Normal $ V3 1 0 0
, Normal $ V3 0.7 0.7 0
, Usemtl "test.png"
, Smooth "off"
, Triangle (Point 1 (Just 2) (Just 3))
(Point 2 (Just 3) (Just 4))
(Point 3 (Just 4) (Just 5))
, Triangle (Point 4 (Just 5) (Just 6))
(Point 5 (Just 6) (Just 7))
(Point 6 (Just 7) (Just 8))
]
-- | Simple model which shall result in a square.
squareParts :: [FilePart]
squareParts =
[ Vertex $ V3 1 1 0
, Vertex $ V3 (-1) 1 0
, Vertex $ V3 (-1) (-1) 0
, Vertex $ V3 1 (-1) 0
, Normal $ V3 0 0 1
, TexCoord $ V2 0 0
, TexCoord $ V2 1 0
, TexCoord $ V2 0 1
, TexCoord $ V2 1 1
, Triangle (Point 1 (Just 4) (Just 1))
(Point 2 (Just 3) (Just 1))
(Point 3 (Just 1) (Just 1))
, Triangle (Point 1 (Just 4) (Just 1))
(Point 3 (Just 1) (Just 1))
(Point 4 (Just 2) (Just 1))
]
|
psandahl/big-engine
|
test/ModelTests.hs
|
Haskell
|
mit
| 8,876
|
{-# LANGUAGE RecursiveDo #-}
module Widgets where
import Reflex.Dom
import qualified GHCJS.DOM.HTMLInputElement as J
import qualified GHCJS.DOM.Element as J
import Control.Lens (view, (^.))
import Data.Monoid ((<>))
import Control.Monad (forM)
--------------- a link opening on a new tab ------
linkNewTab :: MonadWidget t m => String -> String -> m ()
linkNewTab href s = elAttr "a" ("href" =: href <> "target" =: "_blank") $ text s
------------------ radio checkboxes ----------------------
--
radiocheckW :: (MonadHold t m,MonadWidget t m) => Eq a => a -> [(String,a)] -> m (Event t a)
radiocheckW j xs = do
rec es <- forM xs $ \(s,x) -> divClass "icheck" $ do
let d = def & setValue .~ (fmap (== x) $ updated result)
e <- fmap (const x) <$> view checkbox_change <$> checkbox (x == j) d
text s
return e
result <- holdDyn j $ leftmost es
return $ updated result
---------------- input widgets -----------------------------------------------
insertAt :: Int -> String -> String -> (Int, String)
insertAt n e s = let (u,v) = splitAt n s
in (n + length e, u ++ e ++ v)
attachSelectionStart :: MonadWidget t m => TextInput t -> Event t a -> m (Event t (Int, a))
attachSelectionStart t ev = performEvent . ffor ev $ \e -> do
n <- J.getSelectionStart (t ^. textInput_element)
return (n,e)
setCaret :: MonadWidget t m => TextInput t -> Event t Int -> m ()
setCaret t e = performEvent_ . ffor e $ \n -> do
let el = t ^. textInput_element
J.setSelectionStart el n
J.setSelectionEnd el n
inputW :: MonadWidget t m => m (Event t String)
inputW = do
rec let send = ffilter (==13) $ view textInput_keypress input -- send signal firing on *return* key press
input <- textInput $ def & setValue .~ fmap (const "") send -- textInput with content reset on send
return $ tag (current $ view textInput_value input) send -- tag the send signal with the inputText value BEFORE resetting
selInputW
:: MonadWidget t m =>
Event t String -> Event t String -> Event t b -> m (Dynamic t String)
selInputW insertionE refreshE resetE = do
rec insertionLocE <- attachSelectionStart t insertionE
let newE = attachWith (\s (n,e) -> insertAt n e s) (current (value t)) insertionLocE
setCaret t (fmap fst newE)
t <- textInput $ def & setValue .~ leftmost [fmap snd newE, fmap (const "") resetE, refreshE]
return $ view textInput_value t
|
paolino/LambdaCalculus
|
Widgets.hs
|
Haskell
|
mit
| 2,506
|
module Indexing where
import Types
import Control.Monad.State
import Control.Lens ((^.), (&), (+~), (-~))
import Data.List
indexing :: UnIndexedTerm -> IndexedTerm
indexing t = evalState (indexing' t) []
indexing' :: UnIndexedTerm -> State [Name] IndexedTerm
indexing' t = case t of
TmApp t1 t2 -> TmApp <$> indexing' t1 <*> indexing' t2
TmLambda nameStr t1 -> do
modify incrementIndex
modify (\xs -> Name nameStr 0 : xs)
TmLambda nameStr <$> indexing' t1
TmName nameStr -> do
nameMaybe <- findName nameStr
return $ case nameMaybe of
Nothing -> NoRuleApplies ("undefined value:" ++ nameStr)
Just n -> TmName . Name nameStr $ (n^.index)
TmZero -> return TmZero
TmTrue -> return TmTrue
TmFalse -> return TmFalse
TmIsZero -> return TmIsZero
TmPred -> return TmPred
TmSucc -> return TmSucc
TmIf -> return TmIf
NoRuleApplies str -> return $ NoRuleApplies str
incrementIndex :: [Name] -> [Name]
incrementIndex = map (\n -> n&index+~1)
decrementIndex :: [Name] -> [Name]
decrementIndex = map (\n -> n&index-~1)
type Key = String
findName :: Key -> State [Name] (Maybe Name)
findName key = find (\n -> (n^.name) == key) <$> get
betaReduction :: IndexedTerm -> IndexedTerm -> IndexedTerm
betaReduction = betaReduction' 0
betaReduction' :: Int -- index
-> IndexedTerm -- source
-> IndexedTerm -- source内のindexと一致したものをこの項で置換
-> IndexedTerm -- output
betaReduction' i t1 var = case t1 of
TmApp t11 t12 -> TmApp (betaReduction' i t11 var) (betaReduction' i t12 var)
TmLambda n t11 -> TmLambda n $ betaReduction' (i+1) t11 var
TmName n -> if i == n^.index then var else TmName n
TmZero -> TmZero
TmTrue -> TmTrue
TmFalse -> TmFalse
TmIsZero -> TmIsZero
TmPred -> TmPred
TmSucc -> TmSucc
TmIf -> TmIf
NoRuleApplies str -> NoRuleApplies str
|
eliza0x/Mikan
|
src/Indexing.hs
|
Haskell
|
mit
| 2,271
|
module Rebase.Data.Vector.Mutable
(
module Data.Vector.Mutable
)
where
import Data.Vector.Mutable
|
nikita-volkov/rebase
|
library/Rebase/Data/Vector/Mutable.hs
|
Haskell
|
mit
| 101
|
module Test where
import Prelude ()
import Zeno
data Nat = Zero | Succ Nat
length :: [a] -> Nat
length [] = Zero
length (x:xs) = Succ (length xs)
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
class Num a where
(+) :: a -> a -> a
instance Num Nat where
Zero + y = y
Succ x + y = Succ (x + y)
class Eq a where
(==) :: a -> a -> Bool
instance Eq Nat where
Zero == Zero = True
Succ x == Succ y = x == y
_ == _ = False
prop_eq_ref :: Nat -> Prop
prop_eq_ref x = proveBool (x == x)
prop_length :: [a] -> [a] -> Prop
prop_length xs ys
= prove (length (xs ++ ys) :=: length xs + length ys)
elem :: Eq a => a -> [a] -> Bool
elem _ [] = False
elem n (x:xs)
| n == x = True
| otherwise = elem n xs
prop_elem :: Nat -> [Nat] -> [Nat] -> Prop
prop_elem n xs ys
= givenBool (n `elem` ys)
$ proveBool (n `elem` (xs ++ ys))
|
Gurmeet-Singh/Zeno
|
test/test.hs
|
Haskell
|
mit
| 868
|
module SpecHelper where
import Control.Monad (void)
import qualified System.IO.Error as E
import System.Environment (getEnv)
import qualified Data.ByteString.Base64 as B64 (encode, decodeLenient)
import Data.CaseInsensitive (CI(..))
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Data.List (lookup)
import Text.Regex.TDFA ((=~))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BL
import System.Process (readProcess)
import Text.Heredoc
import PostgREST.Config (AppConfig(..))
import PostgREST.Types (JSPathExp(..))
import Test.Hspec
import Test.Hspec.Wai
import Network.HTTP.Types
import Network.Wai.Test (SResponse(simpleStatus, simpleHeaders, simpleBody))
import Data.Maybe (fromJust)
import Data.Aeson (decode, Value(..))
import qualified JSONSchema.Draft4 as D4
import Protolude
matchContentTypeJson :: MatchHeader
matchContentTypeJson = "Content-Type" <:> "application/json; charset=utf-8"
matchContentTypeSingular :: MatchHeader
matchContentTypeSingular = "Content-Type" <:> "application/vnd.pgrst.object+json; charset=utf-8"
validateOpenApiResponse :: [Header] -> WaiSession ()
validateOpenApiResponse headers = do
r <- request methodGet "/" headers ""
liftIO $
let respStatus = simpleStatus r in
respStatus `shouldSatisfy`
\s -> s == Status { statusCode = 200, statusMessage="OK" }
liftIO $
let respHeaders = simpleHeaders r in
respHeaders `shouldSatisfy`
\hs -> ("Content-Type", "application/openapi+json; charset=utf-8") `elem` hs
liftIO $
let respBody = simpleBody r
schema :: D4.Schema
schema = D4.emptySchema { D4._schemaRef = Just "openapi.json" }
schemaContext :: D4.SchemaWithURI D4.Schema
schemaContext = D4.SchemaWithURI
{ D4._swSchema = schema
, D4._swURI = Just "test/fixtures/openapi.json"
}
in
D4.fetchFilesystemAndValidate schemaContext ((fromJust . decode) respBody) `shouldReturn` Right ()
getEnvVarWithDefault :: Text -> Text -> IO Text
getEnvVarWithDefault var def = toS <$>
getEnv (toS var) `E.catchIOError` const (return $ toS def)
_baseCfg :: AppConfig
_baseCfg = -- Connection Settings
AppConfig mempty "postgrest_test_anonymous" Nothing "test" "localhost" 3000
-- Jwt settings
(Just $ encodeUtf8 "reallyreallyreallyreallyverysafe") False Nothing
-- Connection Modifiers
10 Nothing (Just "test.switch_role")
-- Debug Settings
True
[ ("app.settings.app_host", "localhost")
, ("app.settings.external_api_secret", "0123456789abcdef")
]
-- Default role claim key
(Right [JSPKey "role"])
-- Empty db-extra-search-path
[]
testCfg :: Text -> AppConfig
testCfg testDbConn = _baseCfg { configDatabase = testDbConn }
testCfgNoJWT :: Text -> AppConfig
testCfgNoJWT testDbConn = (testCfg testDbConn) { configJwtSecret = Nothing }
testUnicodeCfg :: Text -> AppConfig
testUnicodeCfg testDbConn = (testCfg testDbConn) { configSchema = "تست" }
testLtdRowsCfg :: Text -> AppConfig
testLtdRowsCfg testDbConn = (testCfg testDbConn) { configMaxRows = Just 2 }
testProxyCfg :: Text -> AppConfig
testProxyCfg testDbConn = (testCfg testDbConn) { configProxyUri = Just "https://postgrest.com/openapi.json" }
testCfgBinaryJWT :: Text -> AppConfig
testCfgBinaryJWT testDbConn = (testCfg testDbConn) {
configJwtSecret = Just . B64.decodeLenient $
"cmVhbGx5cmVhbGx5cmVhbGx5cmVhbGx5dmVyeXNhZmU="
}
testCfgAudienceJWT :: Text -> AppConfig
testCfgAudienceJWT testDbConn = (testCfg testDbConn) {
configJwtSecret = Just . B64.decodeLenient $
"cmVhbGx5cmVhbGx5cmVhbGx5cmVhbGx5dmVyeXNhZmU=",
configJwtAudience = Just "youraudience"
}
testCfgAsymJWK :: Text -> AppConfig
testCfgAsymJWK testDbConn = (testCfg testDbConn) {
configJwtSecret = Just $ encodeUtf8
[str|{"alg":"RS256","e":"AQAB","key_ops":["verify"],"kty":"RSA","n":"0etQ2Tg187jb04MWfpuogYGV75IFrQQBxQaGH75eq_FpbkyoLcEpRUEWSbECP2eeFya2yZ9vIO5ScD-lPmovePk4Aa4SzZ8jdjhmAbNykleRPCxMg0481kz6PQhnHRUv3nF5WP479CnObJKqTVdEagVL66oxnX9VhZG9IZA7k0Th5PfKQwrKGyUeTGczpOjaPqbxlunP73j9AfnAt4XCS8epa-n3WGz1j-wfpr_ys57Aq-zBCfqP67UYzNpeI1AoXsJhD9xSDOzvJgFRvc3vm2wjAW4LEMwi48rCplamOpZToIHEPIaPzpveYQwDnB1HFTR1ove9bpKJsHmi-e2uzQ","use":"sig"}|]
}
testCfgAsymJWKSet :: Text -> AppConfig
testCfgAsymJWKSet testDbConn = (testCfg testDbConn) {
configJwtSecret = Just $ encodeUtf8
[str|{"keys": [{"alg":"RS256","e":"AQAB","key_ops":["verify"],"kty":"RSA","n":"0etQ2Tg187jb04MWfpuogYGV75IFrQQBxQaGH75eq_FpbkyoLcEpRUEWSbECP2eeFya2yZ9vIO5ScD-lPmovePk4Aa4SzZ8jdjhmAbNykleRPCxMg0481kz6PQhnHRUv3nF5WP479CnObJKqTVdEagVL66oxnX9VhZG9IZA7k0Th5PfKQwrKGyUeTGczpOjaPqbxlunP73j9AfnAt4XCS8epa-n3WGz1j-wfpr_ys57Aq-zBCfqP67UYzNpeI1AoXsJhD9xSDOzvJgFRvc3vm2wjAW4LEMwi48rCplamOpZToIHEPIaPzpveYQwDnB1HFTR1ove9bpKJsHmi-e2uzQ","use":"sig"}]}|]
}
testNonexistentSchemaCfg :: Text -> AppConfig
testNonexistentSchemaCfg testDbConn = (testCfg testDbConn) { configSchema = "nonexistent" }
testCfgExtraSearchPath :: Text -> AppConfig
testCfgExtraSearchPath testDbConn = (testCfg testDbConn) { configExtraSearchPath = ["public", "extensions"] }
setupDb :: Text -> IO ()
setupDb dbConn = do
loadFixture dbConn "database"
loadFixture dbConn "roles"
loadFixture dbConn "schema"
loadFixture dbConn "jwt"
loadFixture dbConn "privileges"
resetDb dbConn
resetDb :: Text -> IO ()
resetDb dbConn = loadFixture dbConn "data"
loadFixture :: Text -> FilePath -> IO()
loadFixture dbConn name =
void $ readProcess "psql" [toS dbConn, "-a", "-f", "test/fixtures/" ++ name ++ ".sql"] []
rangeHdrs :: ByteRange -> [Header]
rangeHdrs r = [rangeUnit, (hRange, renderByteRange r)]
rangeHdrsWithCount :: ByteRange -> [Header]
rangeHdrsWithCount r = ("Prefer", "count=exact") : rangeHdrs r
acceptHdrs :: BS.ByteString -> [Header]
acceptHdrs mime = [(hAccept, mime)]
rangeUnit :: Header
rangeUnit = ("Range-Unit" :: CI BS.ByteString, "items")
matchHeader :: CI BS.ByteString -> BS.ByteString -> [Header] -> Bool
matchHeader name valRegex headers =
maybe False (=~ valRegex) $ lookup name headers
authHeaderBasic :: BS.ByteString -> BS.ByteString -> Header
authHeaderBasic u p =
(hAuthorization, "Basic " <> (toS . B64.encode . toS $ u <> ":" <> p))
authHeaderJWT :: BS.ByteString -> Header
authHeaderJWT token =
(hAuthorization, "Bearer " <> token)
-- | Tests whether the text can be parsed as a json object comtaining
-- the key "message", and optional keys "details", "hint", "code",
-- and no extraneous keys
isErrorFormat :: BL.ByteString -> Bool
isErrorFormat s =
"message" `S.member` keys &&
S.null (S.difference keys validKeys)
where
obj = decode s :: Maybe (M.Map Text Value)
keys = maybe S.empty M.keysSet obj
validKeys = S.fromList ["message", "details", "hint", "code"]
|
begriffs/postgrest
|
test/SpecHelper.hs
|
Haskell
|
mit
| 6,950
|
module Lib
( pythagoreanTripletSummingTo
) where
pythagoreanTripletSummingTo :: Integer -> [Integer]
pythagoreanTripletSummingTo n =
head [ [a,b,c] | a <- [1..n-4], b <- [a+1..n-3], c <- [b+1..n-2], -- max. c can only be n-2, since a & b must be at least 1.
a^2 + b^2 == c^2,
a + b + c == n]
|
JohnL4/ProjectEuler
|
Haskell/Problem009/src/Lib.hs
|
Haskell
|
mit
| 321
|
-- Use a partially applied function to define a function that will return half
-- of a number and another that will append \n to the end of any string.
module Main where
half x = (/ 2)
addNewline s = (++ "\n")
|
ryanplusplus/seven-languages-in-seven-weeks
|
haskell/day2/partial.hs
|
Haskell
|
mit
| 215
|
{- | Support for resource pagination.
-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module Pos.Util.Pagination (
Page(..)
, PerPage(..)
, maxPerPageEntries
, defaultPerPageEntries
, PaginationMetadata(..)
, PaginationParams(..)
) where
import Universum
import Control.Lens (at, ix, (?~))
import Data.Aeson (Value (Number))
import qualified Data.Aeson.Options as Aeson
import Data.Aeson.TH
import qualified Data.Char as Char
import Data.Default
import Data.Swagger as S
import Formatting (bprint, build, (%))
import qualified Formatting.Buildable
import Test.QuickCheck (Arbitrary (..), choose, getPositive)
import Web.HttpApiData
-- | A `Page` is used in paginated endpoints to request access to a particular
-- subset of a collection.
newtype Page = Page Int
deriving (Show, Eq, Ord, Num)
deriveJSON Aeson.defaultOptions ''Page
instance Arbitrary Page where
arbitrary = Page . getPositive <$> arbitrary
instance FromHttpApiData Page where
parseQueryParam qp = case parseQueryParam qp of
Right (p :: Int) | p < 1 -> Left "A page number cannot be less than 1."
Right (p :: Int) -> Right (Page p)
Left e -> Left e
instance ToHttpApiData Page where
toQueryParam (Page p) = fromString (show p)
instance ToSchema Page where
declareNamedSchema =
pure . NamedSchema (Just "Page") . paramSchemaToSchema
instance ToParamSchema Page where
toParamSchema _ = mempty
& type_ ?~ SwaggerInteger
& default_ ?~ (Number 1) -- Always show the first page by default.
& minimum_ ?~ 1
-- | If not specified otherwise, return first page.
instance Default Page where
def = Page 1
instance Buildable Page where
build (Page p) = bprint build p
-- | A `PerPage` is used to specify the number of entries which should be returned
-- as part of a paginated response.
newtype PerPage = PerPage Int
deriving (Show, Eq, Num, Ord)
deriveJSON Aeson.defaultOptions ''PerPage
instance ToSchema PerPage where
declareNamedSchema =
pure . NamedSchema (Just "PerPage") . paramSchemaToSchema
instance ToParamSchema PerPage where
toParamSchema _ = mempty
& type_ ?~ SwaggerInteger
& default_ ?~ (Number $ fromIntegral defaultPerPageEntries)
& minimum_ ?~ 1
& maximum_ ?~ (fromIntegral maxPerPageEntries)
-- | The maximum number of entries a paginated request can return on a single call.
-- This value is currently arbitrary and it might need to be tweaked down to strike
-- the right balance between number of requests and load of each of them on the system.
maxPerPageEntries :: Int
maxPerPageEntries = 50
-- | If not specified otherwise, a default number of 10 entries from the collection will
-- be returned as part of each paginated response.
defaultPerPageEntries :: Int
defaultPerPageEntries = 10
instance Arbitrary PerPage where
arbitrary = PerPage <$> choose (1, maxPerPageEntries)
instance FromHttpApiData PerPage where
parseQueryParam qp = case parseQueryParam qp of
Right (p :: Int) | p < 1 -> Left "per_page should be at least 1."
Right (p :: Int) | p > maxPerPageEntries ->
Left $ fromString $ "per_page cannot be greater than " <> show maxPerPageEntries <> "."
Right (p :: Int) -> Right (PerPage p)
Left e -> Left e
instance ToHttpApiData PerPage where
toQueryParam (PerPage p) = fromString (show p)
instance Default PerPage where
def = PerPage defaultPerPageEntries
instance Buildable PerPage where
build (PerPage p) = bprint build p
-- | Extra information associated with pagination
data PaginationMetadata = PaginationMetadata
{ metaTotalPages :: Int -- ^ The total pages returned by this query.
, metaPage :: Page -- ^ The current page number (index starts at 1).
, metaPerPage :: PerPage -- ^ The number of entries contained in this page.
, metaTotalEntries :: Int -- ^ The total number of entries in the collection.
} deriving (Show, Eq, Generic)
deriveJSON Aeson.defaultOptions ''PaginationMetadata
instance Arbitrary PaginationMetadata where
arbitrary = PaginationMetadata <$> fmap getPositive arbitrary
<*> arbitrary
<*> arbitrary
<*> fmap getPositive arbitrary
instance ToSchema PaginationMetadata where
declareNamedSchema proxy = do
schm <- genericDeclareNamedSchema defaultSchemaOptions
{ S.fieldLabelModifier =
over (ix 0) Char.toLower . drop 4 -- length "meta"
} proxy
pure $ over schema (over properties adjustPropsSchema) schm
where
totalSchema = Inline $ mempty
& type_ ?~ SwaggerNumber
& minimum_ ?~ 0
& maximum_ ?~ fromIntegral (maxBound :: Int)
adjustPropsSchema s = s
& at "totalPages" ?~ totalSchema
& at "totalEntries" ?~ totalSchema
instance Buildable PaginationMetadata where
build PaginationMetadata{..} =
bprint (build%"/"%build%" total="%build%" per_page="%build)
metaPage
metaTotalPages
metaTotalEntries
metaPerPage
-- | `PaginationParams` is datatype which combines request params related
-- to pagination together.
data PaginationParams = PaginationParams
{ ppPage :: Page -- ^ Greater than 0.
, ppPerPage :: PerPage
} deriving (Show, Eq, Generic)
instance Buildable PaginationParams where
build PaginationParams{..} =
bprint ("page=" % build % ", per_page=" % build)
ppPage
ppPerPage
|
input-output-hk/cardano-sl
|
lib/src/Pos/Util/Pagination.hs
|
Haskell
|
apache-2.0
| 5,923
|
module Binary.A309576 (a309576, a309576_rows) where
import Helpers.Binary (lastBits)
-- Table read by rows: T(n, k) is the last k bits of n, 0 <= k <= A070939 n.
a309576_rows :: [[Int]]
a309576_rows = map (\n -> lastBits n ++ [n]) [1..]
a309576_list :: [Int]
a309576_list = concat a309576_rows
a309576 :: Int -> Int
a309576 n = a309576_list !! (n - 1)
|
peterokagey/haskellOEIS
|
src/Binary/A309576.hs
|
Haskell
|
apache-2.0
| 355
|
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, LambdaCase #-}
module HERMIT.Dictionary.Kure
( -- * KURE Strategies
externals
, anyCallR
, betweenR
, anyCallR_LCore
, testQuery
, hfocusR
, hfocusT
) where
import Control.Arrow
import Control.Monad (liftM)
import HERMIT.Core
import HERMIT.Context
import HERMIT.GHC
import HERMIT.Kure
import HERMIT.External
------------------------------------------------------------------------------------
-- | -- This list contains reflections of the KURE strategies as 'External's.
externals :: [External]
externals = map (.+ KURE)
[ external "id" (idR :: RewriteH LCore)
[ "Perform an identity rewrite."] .+ Shallow
, external "id" (idR :: RewriteH LCoreTC)
[ "Perform an identity rewrite."] .+ Shallow
, external "success" (successT :: TransformH LCore ())
[ "An always succeeding translation." ]
, external "fail" (fail :: String -> RewriteH LCore)
[ "A failing rewrite."]
, external "<+" ((<+) :: RewriteH LCore -> RewriteH LCore -> RewriteH LCore)
[ "Perform the first rewrite, and then, if it fails, perform the second rewrite." ]
, external "<+" ((<+) :: TransformH LCore () -> TransformH LCore () -> TransformH LCore ())
[ "Perform the first check, and then, if it fails, perform the second check." ]
, external ">>>" ((>>>) :: RewriteH LCore -> RewriteH LCore -> RewriteH LCore)
[ "Compose rewrites, requiring both to succeed." ]
, external ">>>" ((>>>) :: BiRewriteH LCore -> BiRewriteH LCore -> BiRewriteH LCore)
[ "Compose bidirectional rewrites, requiring both to succeed." ]
, external ">>>" ((>>>) :: RewriteH LCoreTC -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "Compose rewrites, requiring both to succeed." ]
, external ">+>" ((>+>) :: RewriteH LCore -> RewriteH LCore -> RewriteH LCore)
[ "Compose rewrites, allowing one to fail." ]
, external "try" (tryR :: RewriteH LCore -> RewriteH LCore)
[ "Try a rewrite, and perform the identity if the rewrite fails." ]
, external "repeat" (repeatR :: RewriteH LCore -> RewriteH LCore)
[ "Repeat a rewrite until it would fail." ] .+ Loop
, external "replicate" ((\ n -> andR . replicate n) :: Int -> RewriteH LCore -> RewriteH LCore)
[ "Repeat a rewrite n times." ]
, external "all" (allR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to all children of the node, requiring success at every child." ] .+ Shallow
, external "any" (anyR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to all children of the node, requiring success for at least one child." ] .+ Shallow
, external "one" (oneR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to the first child of the node for which it can succeed." ] .+ Shallow
, external "all-bu" (allbuR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in bottom-up order, requiring success at every node." ] .+ Deep
, external "all-td" (alltdR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in top-down order, requiring success at every node." ] .+ Deep
, external "all-du" (allduR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite twice, in a top-down and bottom-up way, using one single tree traversal,",
"succeeding if they all succeed."] .+ Deep
, external "any-bu" (anybuR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in bottom-up order, requiring success for at least one node." ] .+ Deep
, external "any-td" (anytdR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in top-down order, requiring success for at least one node." ] .+ Deep
, external "any-du" (anyduR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite twice, in a top-down and bottom-up way, using one single tree traversal,",
"succeeding if any succeed."] .+ Deep
, external "one-td" (onetdR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to the first node (in a top-down order) for which it can succeed." ] .+ Deep
, external "one-bu" (onebuR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to the first node (in a bottom-up order) for which it can succeed." ] .+ Deep
, external "prune-td" (prunetdR :: RewriteH LCore -> RewriteH LCore)
[ "Attempt to apply a rewrite in a top-down manner, prunning at successful rewrites." ] .+ Deep
, external "innermost" (innermostR :: RewriteH LCore -> RewriteH LCore)
[ "A fixed-point traveral, starting with the innermost term." ] .+ Deep .+ Loop
, external "focus" (hfocusR :: TransformH LCoreTC LocalPathH -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" (hfocusT :: TransformH LCoreTC LocalPathH -> TransformH LCoreTC String -> TransformH LCoreTC String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusR (return p)) :: LocalPathH -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusT (return p)) :: LocalPathH -> TransformH LCoreTC String -> TransformH LCoreTC String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "focus" (hfocusR :: TransformH LCore LocalPathH -> RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" (hfocusT :: TransformH LCore LocalPathH -> TransformH LCore String -> TransformH LCore String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusR (return p)) :: LocalPathH -> RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusT (return p)) :: LocalPathH -> TransformH LCore String -> TransformH LCore String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "when" ((>>) :: TransformH LCore () -> RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite only if the check succeeds." ] .+ Predicate
, external "not" (notM :: TransformH LCore () -> TransformH LCore ())
[ "Cause a failing check to succeed, a succeeding check to fail." ] .+ Predicate
, external "invert" (invertBiT :: BiRewriteH LCore -> BiRewriteH LCore)
[ "Reverse a bidirectional rewrite." ]
, external "forward" (forwardT :: BiRewriteH LCore -> RewriteH LCore)
[ "Apply a bidirectional rewrite forewards." ]
, external "backward" (backwardT :: BiRewriteH LCore -> RewriteH LCore)
[ "Apply a bidirectional rewrite backwards." ]
, external "test" (testQuery :: RewriteH LCore -> TransformH LCore String)
[ "Determine if a rewrite could be successfully applied." ]
, external "any-call" (anyCallR_LCore :: RewriteH LCore -> RewriteH LCore)
[ "any-call (.. unfold command ..) applies an unfold command to all applications."
, "Preference is given to applications with more arguments." ] .+ Deep
, external "promote" (promoteR :: RewriteH LCore -> RewriteH LCoreTC)
[ "Promote a RewriteCore to a RewriteCoreTC" ]
, external "extract" (extractR :: RewriteH LCoreTC -> RewriteH LCore)
[ "Extract a RewriteCore from a RewriteCoreTC" ]
, external "extract" (extractT :: TransformH LCoreTC String -> TransformH LCore String)
[ "Extract a TransformLCoreString from a TransformLCoreTCString" ]
, external "between" (betweenR :: Int -> Int -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "between x y rr -> perform rr at least x times and at most y times." ]
, external "atPath" (flip hfocusT idR :: TransformH LCore LocalPathH -> TransformH LCore LCore)
[ "return the expression found at the given path" ]
, external "atPath" (flip hfocusT idR :: TransformH LCoreTC LocalPathH -> TransformH LCoreTC LCoreTC)
[ "return the expression found at the given path" ]
, external "atPath" (extractT . flip hfocusT projectT :: TransformH LCoreTC LocalPathH -> TransformH LCore LCore)
[ "return the expression found at the given path" ]
]
------------------------------------------------------------------------------------
hfocusR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, Walker c u, MonadCatch m)
=> Transform c m u LocalPathH -> Rewrite c m u -> Rewrite c m u
hfocusR tp r = do lp <- tp
localPathR lp r
{-# INLINE hfocusR #-}
hfocusT :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, Walker c u, MonadCatch m)
=> Transform c m u LocalPathH -> Transform c m u b -> Transform c m u b
hfocusT tp t = do lp <- tp
localPathT lp t
{-# INLINE hfocusT #-}
------------------------------------------------------------------------------------
-- | Test if a rewrite would succeed, producing a string describing the result.
testQuery :: MonadCatch m => Rewrite c m g -> Transform c m g String
testQuery r = f `liftM` testM r
where
f :: Bool -> String
f True = "Rewrite would succeed."
f False = "Rewrite would fail."
{-# INLINE testQuery #-}
------------------------------------------------------------------------------------
-- | Top-down traversal tuned to matching function calls.
anyCallR :: forall c m. (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, MonadCatch m)
=> Rewrite c m Core -> Rewrite c m Core
anyCallR rr = prefixFailMsg "any-call failed: " $
readerT $ \case
ExprCore (App {}) -> childR App_Arg (anyCallR rr)
>+> (rr <+ childR App_Fun (anyCallR rr))
ExprCore (Var {}) -> rr
_ -> anyR (anyCallR rr)
-- | Top-down traversal tuned to matching function calls.
anyCallR_LCore :: forall c m. (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, LemmaContext c, MonadCatch m)
=> Rewrite c m LCore -> Rewrite c m LCore
anyCallR_LCore rr = prefixFailMsg "any-call failed: " $
readerT $ \case
LCore (ExprCore (App {})) -> childR App_Arg (anyCallR_LCore rr)
>+> (rr <+ childR App_Fun (anyCallR_LCore rr))
LCore (ExprCore (Var {})) -> rr
_ -> anyR (anyCallR_LCore rr)
-- TODO: sort out this duplication
------------------------------------------------------------------------------------
-- | betweenR x y rr -> perform rr at least x times and at most y times.
betweenR :: MonadCatch m => Int -> Int -> Rewrite c m a -> Rewrite c m a
betweenR l h rr | l < 0 = fail "betweenR: lower limit below zero"
| h < l = fail "betweenR: upper limit less than lower limit"
| otherwise = go 0
where -- 'c' is number of times rr has run already
go c | c >= h = idR -- done
| c < l = rr >>> go (c+1) -- haven't hit lower bound yet
| otherwise = tryR (rr >>> go (c+1)) -- met lower bound
------------------------------------------------------------------------------------
|
beni55/hermit
|
src/HERMIT/Dictionary/Kure.hs
|
Haskell
|
bsd-2-clause
| 11,723
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QErrorMessage.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:18
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QErrorMessage (
QqErrorMessage(..)
,qErrorMessageQtHandler
,qErrorMessage_delete
,qErrorMessage_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QErrorMessage ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QErrorMessage_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QErrorMessage_userMethod" qtc_QErrorMessage_userMethod :: Ptr (TQErrorMessage a) -> CInt -> IO ()
instance QuserMethod (QErrorMessageSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QErrorMessage_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QErrorMessage ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QErrorMessage_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QErrorMessage_userMethodVariant" qtc_QErrorMessage_userMethodVariant :: Ptr (TQErrorMessage a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QErrorMessageSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QErrorMessage_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqErrorMessage x1 where
qErrorMessage :: x1 -> IO (QErrorMessage ())
instance QqErrorMessage (()) where
qErrorMessage ()
= withQErrorMessageResult $
qtc_QErrorMessage
foreign import ccall "qtc_QErrorMessage" qtc_QErrorMessage :: IO (Ptr (TQErrorMessage ()))
instance QqErrorMessage ((QWidget t1)) where
qErrorMessage (x1)
= withQErrorMessageResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage1 cobj_x1
foreign import ccall "qtc_QErrorMessage1" qtc_QErrorMessage1 :: Ptr (TQWidget t1) -> IO (Ptr (TQErrorMessage ()))
instance QchangeEvent (QErrorMessage ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_changeEvent_h" qtc_QErrorMessage_changeEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QErrorMessageSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_changeEvent_h cobj_x0 cobj_x1
instance Qdone (QErrorMessage ()) ((Int)) where
done x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_done cobj_x0 (toCInt x1)
foreign import ccall "qtc_QErrorMessage_done" qtc_QErrorMessage_done :: Ptr (TQErrorMessage a) -> CInt -> IO ()
instance Qdone (QErrorMessageSc a) ((Int)) where
done x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_done cobj_x0 (toCInt x1)
qErrorMessageQtHandler :: (()) -> IO (QErrorMessage ())
qErrorMessageQtHandler ()
= withQErrorMessageResult $
qtc_QErrorMessage_qtHandler
foreign import ccall "qtc_QErrorMessage_qtHandler" qtc_QErrorMessage_qtHandler :: IO (Ptr (TQErrorMessage ()))
instance QshowMessage (QErrorMessage a) ((String)) where
showMessage x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_showMessage cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_showMessage" qtc_QErrorMessage_showMessage :: Ptr (TQErrorMessage a) -> CWString -> IO ()
qErrorMessage_delete :: QErrorMessage a -> IO ()
qErrorMessage_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_delete cobj_x0
foreign import ccall "qtc_QErrorMessage_delete" qtc_QErrorMessage_delete :: Ptr (TQErrorMessage a) -> IO ()
qErrorMessage_deleteLater :: QErrorMessage a -> IO ()
qErrorMessage_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_deleteLater cobj_x0
foreign import ccall "qtc_QErrorMessage_deleteLater" qtc_QErrorMessage_deleteLater :: Ptr (TQErrorMessage a) -> IO ()
instance Qaccept (QErrorMessage ()) (()) where
accept x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_accept_h cobj_x0
foreign import ccall "qtc_QErrorMessage_accept_h" qtc_QErrorMessage_accept_h :: Ptr (TQErrorMessage a) -> IO ()
instance Qaccept (QErrorMessageSc a) (()) where
accept x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_accept_h cobj_x0
instance QadjustPosition (QErrorMessage ()) ((QWidget t1)) where
adjustPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_adjustPosition cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_adjustPosition" qtc_QErrorMessage_adjustPosition :: Ptr (TQErrorMessage a) -> Ptr (TQWidget t1) -> IO ()
instance QadjustPosition (QErrorMessageSc a) ((QWidget t1)) where
adjustPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_adjustPosition cobj_x0 cobj_x1
instance QcloseEvent (QErrorMessage ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_closeEvent_h" qtc_QErrorMessage_closeEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QErrorMessageSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_closeEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QErrorMessage ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_contextMenuEvent_h" qtc_QErrorMessage_contextMenuEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QErrorMessageSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_contextMenuEvent_h cobj_x0 cobj_x1
instance Qevent (QErrorMessage ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_event_h" qtc_QErrorMessage_event_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QErrorMessageSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_event_h cobj_x0 cobj_x1
instance QeventFilter (QErrorMessage ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QErrorMessage_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QErrorMessage_eventFilter" qtc_QErrorMessage_eventFilter :: Ptr (TQErrorMessage a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QErrorMessageSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QErrorMessage_eventFilter cobj_x0 cobj_x1 cobj_x2
instance QkeyPressEvent (QErrorMessage ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_keyPressEvent_h" qtc_QErrorMessage_keyPressEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QErrorMessageSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyPressEvent_h cobj_x0 cobj_x1
instance QqminimumSizeHint (QErrorMessage ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QErrorMessage_minimumSizeHint_h" qtc_QErrorMessage_minimumSizeHint_h :: Ptr (TQErrorMessage a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QErrorMessageSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QErrorMessage ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QErrorMessage_minimumSizeHint_qth_h" qtc_QErrorMessage_minimumSizeHint_qth_h :: Ptr (TQErrorMessage a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QErrorMessageSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance Qreject (QErrorMessage ()) (()) where
reject x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_reject_h cobj_x0
foreign import ccall "qtc_QErrorMessage_reject_h" qtc_QErrorMessage_reject_h :: Ptr (TQErrorMessage a) -> IO ()
instance Qreject (QErrorMessageSc a) (()) where
reject x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_reject_h cobj_x0
instance QresizeEvent (QErrorMessage ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_resizeEvent_h" qtc_QErrorMessage_resizeEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QErrorMessageSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resizeEvent_h cobj_x0 cobj_x1
instance QsetVisible (QErrorMessage ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_setVisible_h" qtc_QErrorMessage_setVisible_h :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QsetVisible (QErrorMessageSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QErrorMessage ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_showEvent_h" qtc_QErrorMessage_showEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QErrorMessageSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_showEvent_h cobj_x0 cobj_x1
instance QqsizeHint (QErrorMessage ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_h cobj_x0
foreign import ccall "qtc_QErrorMessage_sizeHint_h" qtc_QErrorMessage_sizeHint_h :: Ptr (TQErrorMessage a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QErrorMessageSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_h cobj_x0
instance QsizeHint (QErrorMessage ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QErrorMessage_sizeHint_qth_h" qtc_QErrorMessage_sizeHint_qth_h :: Ptr (TQErrorMessage a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QErrorMessageSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QactionEvent (QErrorMessage ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_actionEvent_h" qtc_QErrorMessage_actionEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QErrorMessageSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QErrorMessage ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_addAction" qtc_QErrorMessage_addAction :: Ptr (TQErrorMessage a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QErrorMessageSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_addAction cobj_x0 cobj_x1
instance Qcreate (QErrorMessage ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_create cobj_x0
foreign import ccall "qtc_QErrorMessage_create" qtc_QErrorMessage_create :: Ptr (TQErrorMessage a) -> IO ()
instance Qcreate (QErrorMessageSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_create cobj_x0
instance Qcreate (QErrorMessage ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_create1" qtc_QErrorMessage_create1 :: Ptr (TQErrorMessage a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QErrorMessageSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create1 cobj_x0 cobj_x1
instance Qcreate (QErrorMessage ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QErrorMessage_create2" qtc_QErrorMessage_create2 :: Ptr (TQErrorMessage a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QErrorMessageSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QErrorMessage ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QErrorMessage_create3" qtc_QErrorMessage_create3 :: Ptr (TQErrorMessage a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QErrorMessageSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QErrorMessage ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy cobj_x0
foreign import ccall "qtc_QErrorMessage_destroy" qtc_QErrorMessage_destroy :: Ptr (TQErrorMessage a) -> IO ()
instance Qdestroy (QErrorMessageSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy cobj_x0
instance Qdestroy (QErrorMessage ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_destroy1" qtc_QErrorMessage_destroy1 :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance Qdestroy (QErrorMessageSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QErrorMessage ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QErrorMessage_destroy2" qtc_QErrorMessage_destroy2 :: Ptr (TQErrorMessage a) -> CBool -> CBool -> IO ()
instance Qdestroy (QErrorMessageSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QErrorMessage ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_devType_h cobj_x0
foreign import ccall "qtc_QErrorMessage_devType_h" qtc_QErrorMessage_devType_h :: Ptr (TQErrorMessage a) -> IO CInt
instance QdevType (QErrorMessageSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_devType_h cobj_x0
instance QdragEnterEvent (QErrorMessage ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dragEnterEvent_h" qtc_QErrorMessage_dragEnterEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QErrorMessageSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QErrorMessage ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dragLeaveEvent_h" qtc_QErrorMessage_dragLeaveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QErrorMessageSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QErrorMessage ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dragMoveEvent_h" qtc_QErrorMessage_dragMoveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QErrorMessageSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QErrorMessage ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dropEvent_h" qtc_QErrorMessage_dropEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QErrorMessageSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QErrorMessage ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_enabledChange" qtc_QErrorMessage_enabledChange :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QenabledChange (QErrorMessageSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QErrorMessage ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_enterEvent_h" qtc_QErrorMessage_enterEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QErrorMessageSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_enterEvent_h cobj_x0 cobj_x1
instance QfocusInEvent (QErrorMessage ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_focusInEvent_h" qtc_QErrorMessage_focusInEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QErrorMessageSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QErrorMessage ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextChild cobj_x0
foreign import ccall "qtc_QErrorMessage_focusNextChild" qtc_QErrorMessage_focusNextChild :: Ptr (TQErrorMessage a) -> IO CBool
instance QfocusNextChild (QErrorMessageSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextChild cobj_x0
instance QfocusNextPrevChild (QErrorMessage ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_focusNextPrevChild" qtc_QErrorMessage_focusNextPrevChild :: Ptr (TQErrorMessage a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QErrorMessageSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QErrorMessage ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_focusOutEvent_h" qtc_QErrorMessage_focusOutEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QErrorMessageSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusOutEvent_h cobj_x0 cobj_x1
instance QfocusPreviousChild (QErrorMessage ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusPreviousChild cobj_x0
foreign import ccall "qtc_QErrorMessage_focusPreviousChild" qtc_QErrorMessage_focusPreviousChild :: Ptr (TQErrorMessage a) -> IO CBool
instance QfocusPreviousChild (QErrorMessageSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusPreviousChild cobj_x0
instance QfontChange (QErrorMessage ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_fontChange" qtc_QErrorMessage_fontChange :: Ptr (TQErrorMessage a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QErrorMessageSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QErrorMessage ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QErrorMessage_heightForWidth_h" qtc_QErrorMessage_heightForWidth_h :: Ptr (TQErrorMessage a) -> CInt -> IO CInt
instance QheightForWidth (QErrorMessageSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QErrorMessage ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_hideEvent_h" qtc_QErrorMessage_hideEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QErrorMessageSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QErrorMessage ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_inputMethodEvent" qtc_QErrorMessage_inputMethodEvent :: Ptr (TQErrorMessage a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QErrorMessageSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QErrorMessage ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QErrorMessage_inputMethodQuery_h" qtc_QErrorMessage_inputMethodQuery_h :: Ptr (TQErrorMessage a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QErrorMessageSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyReleaseEvent (QErrorMessage ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_keyReleaseEvent_h" qtc_QErrorMessage_keyReleaseEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QErrorMessageSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QErrorMessage ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_languageChange cobj_x0
foreign import ccall "qtc_QErrorMessage_languageChange" qtc_QErrorMessage_languageChange :: Ptr (TQErrorMessage a) -> IO ()
instance QlanguageChange (QErrorMessageSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_languageChange cobj_x0
instance QleaveEvent (QErrorMessage ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_leaveEvent_h" qtc_QErrorMessage_leaveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QErrorMessageSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QErrorMessage ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QErrorMessage_metric" qtc_QErrorMessage_metric :: Ptr (TQErrorMessage a) -> CLong -> IO CInt
instance Qmetric (QErrorMessageSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QmouseDoubleClickEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mouseDoubleClickEvent_h" qtc_QErrorMessage_mouseDoubleClickEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mouseMoveEvent_h" qtc_QErrorMessage_mouseMoveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mousePressEvent_h" qtc_QErrorMessage_mousePressEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mouseReleaseEvent_h" qtc_QErrorMessage_mouseReleaseEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qmove (QErrorMessage ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QErrorMessage_move1" qtc_QErrorMessage_move1 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qmove (QErrorMessageSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QErrorMessage ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QErrorMessage_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QErrorMessage_move_qth" qtc_QErrorMessage_move_qth :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qmove (QErrorMessageSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QErrorMessage_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QErrorMessage ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_move cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_move" qtc_QErrorMessage_move :: Ptr (TQErrorMessage a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QErrorMessageSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_move cobj_x0 cobj_x1
instance QmoveEvent (QErrorMessage ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_moveEvent_h" qtc_QErrorMessage_moveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QErrorMessageSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QErrorMessage ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_paintEngine_h cobj_x0
foreign import ccall "qtc_QErrorMessage_paintEngine_h" qtc_QErrorMessage_paintEngine_h :: Ptr (TQErrorMessage a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QErrorMessageSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_paintEngine_h cobj_x0
instance QpaintEvent (QErrorMessage ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_paintEvent_h" qtc_QErrorMessage_paintEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QErrorMessageSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paintEvent_h cobj_x0 cobj_x1
instance QpaletteChange (QErrorMessage ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_paletteChange" qtc_QErrorMessage_paletteChange :: Ptr (TQErrorMessage a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QErrorMessageSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QErrorMessage ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint cobj_x0
foreign import ccall "qtc_QErrorMessage_repaint" qtc_QErrorMessage_repaint :: Ptr (TQErrorMessage a) -> IO ()
instance Qrepaint (QErrorMessageSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint cobj_x0
instance Qrepaint (QErrorMessage ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QErrorMessage_repaint2" qtc_QErrorMessage_repaint2 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QErrorMessageSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QErrorMessage ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_repaint1" qtc_QErrorMessage_repaint1 :: Ptr (TQErrorMessage a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QErrorMessageSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QErrorMessage ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resetInputContext cobj_x0
foreign import ccall "qtc_QErrorMessage_resetInputContext" qtc_QErrorMessage_resetInputContext :: Ptr (TQErrorMessage a) -> IO ()
instance QresetInputContext (QErrorMessageSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resetInputContext cobj_x0
instance Qresize (QErrorMessage ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QErrorMessage_resize1" qtc_QErrorMessage_resize1 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qresize (QErrorMessageSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QErrorMessage ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_resize" qtc_QErrorMessage_resize :: Ptr (TQErrorMessage a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QErrorMessageSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resize cobj_x0 cobj_x1
instance Qresize (QErrorMessage ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QErrorMessage_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QErrorMessage_resize_qth" qtc_QErrorMessage_resize_qth :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qresize (QErrorMessageSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QErrorMessage_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QErrorMessage ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QErrorMessage_setGeometry1" qtc_QErrorMessage_setGeometry1 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QErrorMessageSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QErrorMessage ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_setGeometry" qtc_QErrorMessage_setGeometry :: Ptr (TQErrorMessage a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QErrorMessageSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QErrorMessage ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QErrorMessage_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QErrorMessage_setGeometry_qth" qtc_QErrorMessage_setGeometry_qth :: Ptr (TQErrorMessage a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QErrorMessageSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QErrorMessage_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QErrorMessage ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_setMouseTracking" qtc_QErrorMessage_setMouseTracking :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QsetMouseTracking (QErrorMessageSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setMouseTracking cobj_x0 (toCBool x1)
instance QtabletEvent (QErrorMessage ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_tabletEvent_h" qtc_QErrorMessage_tabletEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QErrorMessageSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QErrorMessage ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_updateMicroFocus cobj_x0
foreign import ccall "qtc_QErrorMessage_updateMicroFocus" qtc_QErrorMessage_updateMicroFocus :: Ptr (TQErrorMessage a) -> IO ()
instance QupdateMicroFocus (QErrorMessageSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_updateMicroFocus cobj_x0
instance QwheelEvent (QErrorMessage ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_wheelEvent_h" qtc_QErrorMessage_wheelEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QErrorMessageSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QErrorMessage ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_windowActivationChange" qtc_QErrorMessage_windowActivationChange :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QwindowActivationChange (QErrorMessageSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QErrorMessage ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_childEvent" qtc_QErrorMessage_childEvent :: Ptr (TQErrorMessage a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QErrorMessageSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QErrorMessage ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_connectNotify" qtc_QErrorMessage_connectNotify :: Ptr (TQErrorMessage a) -> CWString -> IO ()
instance QconnectNotify (QErrorMessageSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QErrorMessage ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_customEvent" qtc_QErrorMessage_customEvent :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QErrorMessageSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QErrorMessage ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_disconnectNotify" qtc_QErrorMessage_disconnectNotify :: Ptr (TQErrorMessage a) -> CWString -> IO ()
instance QdisconnectNotify (QErrorMessageSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_disconnectNotify cobj_x0 cstr_x1
instance Qreceivers (QErrorMessage ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_receivers" qtc_QErrorMessage_receivers :: Ptr (TQErrorMessage a) -> CWString -> IO CInt
instance Qreceivers (QErrorMessageSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_receivers cobj_x0 cstr_x1
instance Qsender (QErrorMessage ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sender cobj_x0
foreign import ccall "qtc_QErrorMessage_sender" qtc_QErrorMessage_sender :: Ptr (TQErrorMessage a) -> IO (Ptr (TQObject ()))
instance Qsender (QErrorMessageSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sender cobj_x0
instance QtimerEvent (QErrorMessage ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_timerEvent" qtc_QErrorMessage_timerEvent :: Ptr (TQErrorMessage a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QErrorMessageSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_timerEvent cobj_x0 cobj_x1
|
uduki/hsQt
|
Qtc/Gui/QErrorMessage.hs
|
Haskell
|
bsd-2-clause
| 46,961
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionButton.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionButton (
QqStyleOptionButton(..)
,QqStyleOptionButton_nf(..)
,qStyleOptionButton_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QStyleOptionButton
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionButton x1 where
qStyleOptionButton :: x1 -> IO (QStyleOptionButton ())
instance QqStyleOptionButton (()) where
qStyleOptionButton ()
= withQStyleOptionButtonResult $
qtc_QStyleOptionButton
foreign import ccall "qtc_QStyleOptionButton" qtc_QStyleOptionButton :: IO (Ptr (TQStyleOptionButton ()))
instance QqStyleOptionButton ((QStyleOptionButton t1)) where
qStyleOptionButton (x1)
= withQStyleOptionButtonResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton1 cobj_x1
foreign import ccall "qtc_QStyleOptionButton1" qtc_QStyleOptionButton1 :: Ptr (TQStyleOptionButton t1) -> IO (Ptr (TQStyleOptionButton ()))
class QqStyleOptionButton_nf x1 where
qStyleOptionButton_nf :: x1 -> IO (QStyleOptionButton ())
instance QqStyleOptionButton_nf (()) where
qStyleOptionButton_nf ()
= withObjectRefResult $
qtc_QStyleOptionButton
instance QqStyleOptionButton_nf ((QStyleOptionButton t1)) where
qStyleOptionButton_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton1 cobj_x1
instance Qfeatures (QStyleOptionButton a) (()) (IO (ButtonFeatures)) where
features x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_features cobj_x0
foreign import ccall "qtc_QStyleOptionButton_features" qtc_QStyleOptionButton_features :: Ptr (TQStyleOptionButton a) -> IO CLong
instance Qicon (QStyleOptionButton a) (()) (IO (QIcon ())) where
icon x0 ()
= withQIconResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_icon cobj_x0
foreign import ccall "qtc_QStyleOptionButton_icon" qtc_QStyleOptionButton_icon :: Ptr (TQStyleOptionButton a) -> IO (Ptr (TQIcon ()))
instance QqiconSize (QStyleOptionButton a) (()) where
qiconSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_iconSize cobj_x0
foreign import ccall "qtc_QStyleOptionButton_iconSize" qtc_QStyleOptionButton_iconSize :: Ptr (TQStyleOptionButton a) -> IO (Ptr (TQSize ()))
instance QiconSize (QStyleOptionButton a) (()) where
iconSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_iconSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QStyleOptionButton_iconSize_qth" qtc_QStyleOptionButton_iconSize_qth :: Ptr (TQStyleOptionButton a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsetFeatures (QStyleOptionButton a) ((ButtonFeatures)) where
setFeatures x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_setFeatures cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QStyleOptionButton_setFeatures" qtc_QStyleOptionButton_setFeatures :: Ptr (TQStyleOptionButton a) -> CLong -> IO ()
instance QsetIcon (QStyleOptionButton a) ((QIcon t1)) where
setIcon x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton_setIcon cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionButton_setIcon" qtc_QStyleOptionButton_setIcon :: Ptr (TQStyleOptionButton a) -> Ptr (TQIcon t1) -> IO ()
instance QqsetIconSize (QStyleOptionButton a) ((QSize t1)) where
qsetIconSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton_setIconSize cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionButton_setIconSize" qtc_QStyleOptionButton_setIconSize :: Ptr (TQStyleOptionButton a) -> Ptr (TQSize t1) -> IO ()
instance QsetIconSize (QStyleOptionButton a) ((Size)) where
setIconSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QStyleOptionButton_setIconSize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QStyleOptionButton_setIconSize_qth" qtc_QStyleOptionButton_setIconSize_qth :: Ptr (TQStyleOptionButton a) -> CInt -> CInt -> IO ()
instance QsetText (QStyleOptionButton a) ((String)) where
setText x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStyleOptionButton_setText cobj_x0 cstr_x1
foreign import ccall "qtc_QStyleOptionButton_setText" qtc_QStyleOptionButton_setText :: Ptr (TQStyleOptionButton a) -> CWString -> IO ()
instance Qtext (QStyleOptionButton a) (()) (IO (String)) where
text x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_text cobj_x0
foreign import ccall "qtc_QStyleOptionButton_text" qtc_QStyleOptionButton_text :: Ptr (TQStyleOptionButton a) -> IO (Ptr (TQString ()))
qStyleOptionButton_delete :: QStyleOptionButton a -> IO ()
qStyleOptionButton_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_delete cobj_x0
foreign import ccall "qtc_QStyleOptionButton_delete" qtc_QStyleOptionButton_delete :: Ptr (TQStyleOptionButton a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QStyleOptionButton.hs
|
Haskell
|
bsd-2-clause
| 5,615
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE CPP #-}
#ifdef LANGUAGE_DeriveDataTypeable
{-# LANGUAGE DeriveDataTypeable #-}
#endif
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE PolyKinds #-}
#endif
#if __GLASGOW_HASKELL__ >= 702 && __GLASGOW_HASKELL__ < 710
{-# LANGUAGE Trustworthy #-}
#endif
----------------------------------------------------------------------------
-- |
-- Module : Data.Functor.Trans.Tagged
-- Copyright : 2011-2013 Edward Kmett
-- License : BSD3
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module Data.Functor.Trans.Tagged
(
-- * Tagged values
TaggedT(..), Tagged
, tag, tagT
, untag
, retag
, mapTaggedT
, reflected, reflectedM
, asTaggedTypeOf
, proxy, proxyT
, unproxy, unproxyT
, tagSelf, tagTSelf
, untagSelf, untagTSelf
, tagWith, tagTWith
, witness, witnessT
) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 706)
import Prelude hiding (foldr, foldl, mapM, sequence, foldr1, foldl1)
#else
import Prelude hiding (catch, foldr, foldl, mapM, sequence, foldr1, foldl1)
#endif
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Alternative(..), Applicative(..), (<$), (<$>))
#else
import Control.Applicative (Alternative(..))
#endif
import Control.Monad (liftM, MonadPlus(..))
import Control.Monad.Catch (MonadCatch(..), MonadThrow(..), MonadMask(..))
import Control.Monad.Fix (MonadFix(..))
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.Trans (MonadIO(..), MonadTrans(..))
import Control.Monad.Reader (MonadReader(..))
import Control.Monad.Writer (MonadWriter(..))
import Control.Monad.State (MonadState(..))
import Control.Monad.Cont (MonadCont(..))
import Control.Comonad.Trans.Class (ComonadTrans(..))
import Control.Comonad.Hoist.Class (ComonadHoist(..))
import Control.Comonad (Comonad(..))
import Data.Traversable (Traversable(..))
import Data.Typeable
import Data.Foldable (Foldable(..))
import Data.Distributive (Distributive(..))
import Data.Functor.Bind (Apply(..), Bind(..))
import Data.Functor.Extend (Extend(..))
import Data.Functor.Plus (Alt(..), Plus(..))
import Data.Functor.Contravariant (Contravariant(..))
#if !(defined(__GLASGOW_HASKELL__)) || __GLASGOW_HASKELL__ < 707
import Data.Proxy (Proxy(..))
#endif
import Data.Reflection (Reifies(..))
-- ---------------------------------------------------------------------------
-- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@.
-- This can be used in place of the more traditional but less safe idiom of
-- passing in an undefined value with the type, because unlike an @(s -> b)@,
-- a @'Tagged' s b@ can't try to use the argument @s@ as a real value.
--
-- Moreover, you don't have to rely on the compiler to inline away the extra
-- argument, because the newtype is \"free\"
type Tagged s b = TaggedT s Identity b
-- | Tag a value in Identity monad
tag :: b -> Tagged s b
tag = TagT . return
{-# INLINE tag #-}
-- | Untag a value in Identity monad
untag :: Tagged s b -> b
untag = runIdentity . untagT
{-# INLINE untag #-}
-- | Convert from a 'Tagged' representation to a representation
-- based on a 'Proxy'.
proxy :: Tagged s b -> Proxy s -> b
proxy x _ = untag x
{-# INLINE proxy #-}
-- | Convert from a representation based on a 'Proxy' to a 'Tagged'
-- representation.
unproxy :: (Proxy s -> a) -> Tagged s a
unproxy f = TagT (return $ f Proxy)
{-# INLINE unproxy #-}
-- | Tag a value with its own type.
tagSelf :: a -> Tagged a a
tagSelf = TagT . return
{-# INLINE tagSelf #-}
-- | 'untagSelf' is a type-restricted version of 'untag'.
untagSelf :: Tagged a a -> a
untagSelf = untag
{-# INLINE untagSelf #-}
-- | Another way to convert a proxy to a tag.
tagWith :: proxy s -> a -> Tagged s a
tagWith _ = TagT . return
{-# INLINE tagWith #-}
witness :: Tagged a b -> a -> b
witness x _ = untag x
{-# INLINE witness #-}
-- ---------------------------------------------------------------------------
-- | A Tagged monad parameterized by:
--
-- * @s@ - the phantom type
--
-- * @m@ - the inner monad
--
-- * @b@ - the tagged value
--
-- | A @'TaggedT' s m b@ value is a monadic value @m b@ with an attached phantom type @s@.
-- This can be used in place of the more traditional but less safe idiom of
-- passing in an undefined value with the type, because unlike an @(s -> m b)@,
-- a @'TaggedT' s m b@ can't try to use the argument @s@ as a real value.
--
-- Moreover, you don't have to rely on the compiler to inline away the extra
-- argument, because the newtype is \"free\"
newtype TaggedT s m b = TagT { untagT :: m b }
deriving ( Eq, Ord, Read, Show
#if __GLASGOW_HASKELL__ >= 707
, Typeable
#endif
)
instance Functor m => Functor (TaggedT s m) where
fmap f (TagT x) = TagT (fmap f x)
{-# INLINE fmap #-}
b <$ (TagT x) = TagT (b <$ x)
{-# INLINE (<$) #-}
instance Contravariant m => Contravariant (TaggedT s m) where
contramap f (TagT x) = TagT (contramap f x)
{-# INLINE contramap #-}
instance Apply m => Apply (TaggedT s m) where
TagT f <.> TagT x = TagT (f <.> x)
{-# INLINE (<.>) #-}
TagT f .> TagT x = TagT (f .> x)
{-# INLINE ( .>) #-}
TagT f <. TagT x = TagT (f <. x)
{-# INLINE (<. ) #-}
instance Applicative m => Applicative (TaggedT s m) where
pure = TagT . pure
{-# INLINE pure #-}
TagT f <*> TagT x = TagT (f <*> x)
{-# INLINE (<*>) #-}
TagT f *> TagT x = TagT (f *> x)
{-# INLINE ( *>) #-}
TagT f <* TagT x = TagT (f <* x)
{-# INLINE (<* ) #-}
instance Bind m => Bind (TaggedT s m) where
TagT m >>- k = TagT (m >>- untagT . k)
{-# INLINE (>>-) #-}
instance Monad m => Monad (TaggedT s m) where
TagT m >>= k = TagT (m >>= untagT . k)
{-# INLINE (>>=) #-}
#if !(MIN_VERSION_base(4,11,0))
return = TagT . return
{-# INLINE return #-}
TagT m >> TagT n = TagT (m >> n)
{-# INLINE (>>) #-}
#endif
instance Alt m => Alt (TaggedT s m) where
TagT a <!> TagT b = TagT (a <!> b)
{-# INLINE (<!>) #-}
instance Alternative m => Alternative (TaggedT s m) where
empty = TagT empty
{-# INLINE empty #-}
TagT a <|> TagT b = TagT (a <|> b)
{-# INLINE (<|>) #-}
instance Plus m => Plus (TaggedT s m) where
zero = TagT zero
{-# INLINE zero #-}
instance MonadPlus m => MonadPlus (TaggedT s m) where
mzero = TagT mzero
{-# INLINE mzero #-}
mplus (TagT a) (TagT b) = TagT (mplus a b)
{-# INLINE mplus #-}
instance MonadFix m => MonadFix (TaggedT s m) where
mfix f = TagT $ mfix (untagT . f)
{-# INLINE mfix #-}
instance MonadTrans (TaggedT s) where
lift = TagT
{-# INLINE lift #-}
instance MonadIO m => MonadIO (TaggedT s m) where
liftIO = lift . liftIO
{-# INLINE liftIO #-}
instance MonadWriter w m => MonadWriter w (TaggedT s m) where
#if MIN_VERSION_mtl(2,1,0)
writer = lift . writer
{-# INLINE writer #-}
#endif
tell = lift . tell
{-# INLINE tell #-}
listen = lift . listen . untagT
{-# INLINE listen #-}
pass = lift . pass . untagT
{-# INLINE pass #-}
instance MonadReader r m => MonadReader r (TaggedT s m) where
ask = lift ask
{-# INLINE ask #-}
local f = lift . local f . untagT
{-# INLINE local #-}
#if MIN_VERSION_mtl(2,1,0)
reader = lift . reader
{-# INLINE reader #-}
#endif
instance MonadState t m => MonadState t (TaggedT s m) where
get = lift get
{-# INLINE get #-}
put = lift . put
{-# INLINE put #-}
#if MIN_VERSION_mtl(2,1,0)
state = lift . state
{-# INLINE state #-}
#endif
instance MonadCont m => MonadCont (TaggedT s m) where
callCC f = lift . callCC $ \k -> untagT (f (TagT . k))
{-# INLINE callCC #-}
instance Foldable f => Foldable (TaggedT s f) where
foldMap f (TagT x) = foldMap f x
{-# INLINE foldMap #-}
fold (TagT x) = fold x
{-# INLINE fold #-}
foldr f z (TagT x) = foldr f z x
{-# INLINE foldr #-}
foldl f z (TagT x) = foldl f z x
{-# INLINE foldl #-}
foldl1 f (TagT x) = foldl1 f x
{-# INLINE foldl1 #-}
foldr1 f (TagT x) = foldr1 f x
{-# INLINE foldr1 #-}
instance Traversable f => Traversable (TaggedT s f) where
traverse f (TagT x) = TagT <$> traverse f x
{-# INLINE traverse #-}
sequenceA (TagT x) = TagT <$> sequenceA x
{-# INLINE sequenceA #-}
mapM f (TagT x) = liftM TagT (mapM f x)
{-# INLINE mapM #-}
sequence (TagT x) = liftM TagT (sequence x)
{-# INLINE sequence #-}
instance Distributive f => Distributive (TaggedT s f) where
distribute = TagT . distribute . fmap untagT
{-# INLINE distribute #-}
instance Extend f => Extend (TaggedT s f) where
extended f (TagT w) = TagT (extended (f . TagT) w)
{-# INLINE extended #-}
instance Comonad w => Comonad (TaggedT s w) where
extract (TagT w) = extract w
{-# INLINE extract #-}
duplicate (TagT w) = TagT (extend TagT w)
{-# INLINE duplicate #-}
instance ComonadTrans (TaggedT s) where
lower (TagT w) = w
{-# INLINE lower #-}
instance ComonadHoist (TaggedT s) where
cohoist f = TagT . f . untagT
{-# INLINE cohoist #-}
instance MonadThrow m => MonadThrow (TaggedT s m) where
throwM e = lift $ throwM e
{-# INLINE throwM #-}
instance MonadCatch m => MonadCatch (TaggedT s m) where
catch m f = TagT (catch (untagT m) (untagT . f))
{-# INLINE catch #-}
instance MonadMask m => MonadMask (TaggedT s m) where
mask a = TagT $ mask $ \u -> untagT (a $ q u)
where q u = TagT . u . untagT
{-# INLINE mask #-}
uninterruptibleMask a = TagT $ uninterruptibleMask $ \u -> untagT (a $ q u)
where q u = TagT . u . untagT
{-# INLINE uninterruptibleMask#-}
#if MIN_VERSION_exceptions(0,10,0)
generalBracket acquire release use = TagT $
generalBracket
(untagT acquire)
(\resource exitCase -> untagT (release resource exitCase))
(\resource -> untagT (use resource))
#endif
-- | Easier to type alias for 'TagT'
tagT :: m b -> TaggedT s m b
tagT = TagT
{-# INLINE tagT #-}
-- | Some times you need to change the tag you have lying around.
-- Idiomatic usage is to make a new combinator for the relationship between the
-- tags that you want to enforce, and define that combinator using 'retag'.
--
-- > data Succ n
-- > retagSucc :: Tagged n a -> Tagged (Succ n) a
-- > retagSucc = retag
retag :: TaggedT s m b -> TaggedT t m b
retag = TagT . untagT
{-# INLINE retag #-}
-- | Lift an operation on underlying monad
mapTaggedT :: (m a -> n b) -> TaggedT s m a -> TaggedT s n b
mapTaggedT f = TagT . f . untagT
{-# INLINE mapTaggedT #-}
-- | Reflect reified value back in 'Applicative' context
reflected :: forall s m a. (Applicative m, Reifies s a) => TaggedT s m a
reflected = TagT . pure . reflect $ (Proxy :: Proxy s)
{-# INLINE reflected #-}
-- | Reflect reified value back in 'Monad' context
reflectedM :: forall s m a. (Monad m, Reifies s a) => TaggedT s m a
reflectedM = TagT . return . reflect $ (Proxy :: Proxy s)
{-# INLINE reflectedM #-}
-- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second.
asTaggedTypeOf :: s -> TaggedT s m b -> s
asTaggedTypeOf = const
{-# INLINE asTaggedTypeOf #-}
-- | Convert from a 'TaggedT' representation to a representation
-- based on a 'Proxy'.
proxyT :: TaggedT s m b -> Proxy s -> m b
proxyT x _ = untagT x
{-# INLINE proxyT #-}
-- | Convert from a representation based on a 'Proxy' to a 'TaggedT'
-- representation.
unproxyT :: (Proxy s -> m a) -> TaggedT s m a
unproxyT f = TagT (f Proxy)
{-# INLINE unproxyT #-}
-- | Tag a value with its own type.
tagTSelf :: m a -> TaggedT a m a
tagTSelf = TagT
{-# INLINE tagTSelf #-}
-- | 'untagSelf' is a type-restricted version of 'untag'.
untagTSelf :: TaggedT a m a -> m a
untagTSelf = untagT
{-# INLINE untagTSelf #-}
-- | Another way to convert a proxy to a tag.
tagTWith :: proxy s -> m a -> TaggedT s m a
tagTWith _ = TagT
{-# INLINE tagTWith #-}
witnessT :: TaggedT a m b -> a -> m b
witnessT x _ = untagT x
{-# INLINE witnessT #-}
|
ekmett/tagged-transformer
|
src/Data/Functor/Trans/Tagged.hs
|
Haskell
|
bsd-2-clause
| 12,208
|
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
module Cryptol.ModuleSystem.NamingEnv where
import Cryptol.ModuleSystem.Interface
import Cryptol.Parser.AST
import Cryptol.Parser.Names (namesP)
import Cryptol.Parser.Position
import qualified Cryptol.TypeCheck.AST as T
import Cryptol.Utils.PP
import Cryptol.Utils.Panic (panic)
import Data.Monoid (Monoid(..))
import Data.Foldable (foldMap)
import qualified Data.Map as Map
-- Name Locations --------------------------------------------------------------
data NameOrigin = Local (Located QName)
| Imported QName
deriving (Show)
instance PP NameOrigin where
ppPrec _ o = case o of
Local lqn -> pp lqn
Imported (QName m n) -> pp n <+> trailer
where
trailer = case m of
Just mn -> text "from module" <+> pp mn
_ -> empty
-- Names -----------------------------------------------------------------------
data EName = EFromBind (Located QName)
| EFromNewtype (Located QName)
| EFromMod QName
deriving (Show)
data TName = TFromParam QName
| TFromSyn (Located QName)
| TFromNewtype (Located QName)
| TFromMod QName
deriving (Show)
class HasQName a where
qname :: a -> QName
origin :: a -> NameOrigin
instance HasQName TName where
qname tn = case tn of
TFromParam qn -> qn
TFromSyn lqn -> thing lqn
TFromNewtype lqn -> thing lqn
TFromMod qn -> qn
origin tn = case tn of
TFromParam qn -> Local Located { srcRange = emptyRange, thing = qn }
TFromSyn lqn -> Local lqn
TFromNewtype lqn -> Local lqn
TFromMod qn -> Imported qn
instance HasQName EName where
qname en = case en of
EFromBind lqn -> thing lqn
EFromNewtype lqn -> thing lqn
EFromMod qn -> qn
origin en = case en of
EFromBind lqn -> Local lqn
EFromNewtype lqn -> Local lqn
EFromMod qn -> Imported qn
-- Naming Environment ----------------------------------------------------------
data NamingEnv = NamingEnv { neExprs :: Map.Map QName [EName]
-- ^ Expr renaming environment
, neTypes :: Map.Map QName [TName]
-- ^ Type renaming environment
} deriving (Show)
instance Monoid NamingEnv where
mempty =
NamingEnv { neExprs = Map.empty
, neTypes = Map.empty }
mappend l r =
NamingEnv { neExprs = Map.unionWith (++) (neExprs l) (neExprs r)
, neTypes = Map.unionWith (++) (neTypes l) (neTypes r) }
mconcat envs =
NamingEnv { neExprs = Map.unionsWith (++) (map neExprs envs)
, neTypes = Map.unionsWith (++) (map neTypes envs) }
-- | Singleton type renaming environment.
singletonT :: QName -> TName -> NamingEnv
singletonT qn tn = mempty { neTypes = Map.singleton qn [tn] }
-- | Singleton expression renaming environment.
singletonE :: QName -> EName -> NamingEnv
singletonE qn en = mempty { neExprs = Map.singleton qn [en] }
-- | Like mappend, but when merging, prefer values on the lhs.
shadowing :: NamingEnv -> NamingEnv -> NamingEnv
shadowing l r = NamingEnv
{ neExprs = Map.union (neExprs l) (neExprs r)
, neTypes = Map.union (neTypes l) (neTypes r) }
-- | Things that define exported names.
class BindsNames a where
namingEnv :: a -> NamingEnv
instance BindsNames NamingEnv where
namingEnv = id
instance BindsNames a => BindsNames (Maybe a) where
namingEnv = foldMap namingEnv
instance BindsNames a => BindsNames [a] where
namingEnv = foldMap namingEnv
-- | Generate a type renaming environment from the parameters that are bound by
-- this schema.
instance BindsNames Schema where
namingEnv (Forall ps _ _ _) = foldMap namingEnv ps
-- | Produce a naming environment from an interface file, that contains a
-- mapping only from unqualified names to qualified ones.
instance BindsNames Iface where
namingEnv = namingEnv . ifPublic
-- | Translate a set of declarations from an interface into a naming
-- environment.
instance BindsNames IfaceDecls where
namingEnv binds = mconcat [ types, newtypes, vars ]
where
types = mempty
{ neTypes = Map.map (map (TFromMod . ifTySynName)) (ifTySyns binds)
}
newtypes = mempty
{ neTypes = Map.map (map (TFromMod . T.ntName)) (ifNewtypes binds)
, neExprs = Map.map (map (EFromMod . T.ntName)) (ifNewtypes binds)
}
vars = mempty
{ neExprs = Map.map (map (EFromMod . ifDeclName)) (ifDecls binds)
}
-- | Translate names bound by the patterns of a match into a renaming
-- environment.
instance BindsNames Match where
namingEnv m = case m of
Match p _ -> namingEnv p
MatchLet b -> namingEnv b
instance BindsNames Bind where
namingEnv b = singletonE (thing qn) (EFromBind qn)
where
qn = bName b
-- | Generate the naming environment for a type parameter.
instance BindsNames TParam where
namingEnv p = singletonT qn (TFromParam qn)
where
qn = mkUnqual (tpName p)
-- | Generate an expression renaming environment from a pattern. This ignores
-- type parameters that can be bound by the pattern.
instance BindsNames Pattern where
namingEnv p = foldMap unqualBind (namesP p)
where
unqualBind qn = singletonE (thing qn) (EFromBind qn)
-- | The naming environment for a single module. This is the mapping from
-- unqualified internal names to fully qualified names.
instance BindsNames Module where
namingEnv m = foldMap topDeclEnv (mDecls m)
where
topDeclEnv td = case td of
Decl d -> declEnv (tlValue d)
TDNewtype n -> newtypeEnv (tlValue n)
Include _ -> mempty
qual = fmap (\qn -> mkQual (thing (mName m)) (unqual qn))
qualBind ln = singletonE (thing ln) (EFromBind (qual ln))
qualType ln = singletonT (thing ln) (TFromSyn (qual ln))
declEnv d = case d of
DSignature ns _sig -> foldMap qualBind ns
DPragma ns _p -> foldMap qualBind ns
DBind b -> qualBind (bName b)
DPatBind _pat _e -> panic "ModuleSystem" ["Unexpected pattern binding"]
DType (TySyn lqn _ _) -> qualType lqn
DLocated d' _ -> declEnv d'
newtypeEnv n = singletonT (thing qn) (TFromNewtype (qual qn))
`mappend` singletonE (thing qn) (EFromNewtype (qual qn))
where
qn = nName n
-- | The naming environment for a single declaration, unqualified. This is
-- meanat to be used for things like where clauses.
instance BindsNames Decl where
namingEnv d = case d of
DSignature ns _sig -> foldMap qualBind ns
DPragma ns _p -> foldMap qualBind ns
DBind b -> qualBind (bName b)
DPatBind _pat _e -> panic "ModuleSystem" ["Unexpected pattern binding"]
DType (TySyn lqn _ _) -> qualType lqn
DLocated d' _ -> namingEnv d'
where
qualBind ln = singletonE (thing ln) (EFromBind ln)
qualType ln = singletonT (thing ln) (TFromSyn ln)
|
dylanmc/cryptol
|
src/Cryptol/ModuleSystem/NamingEnv.hs
|
Haskell
|
bsd-3-clause
| 7,203
|
-- © 2002 Peter Thiemann
module WASH.CGI.StateItem where
import Data.Char
--
-- |type of handles to a PE of type @a@
data T a = T String Int | Tvirtual { tvirtual :: a }
instance Show (T a) where
showsPrec _ (T s i) = showChar 'T' . shows s . shows i
showsPrec _ (Tvirtual _) = showChar 'V'
instance Read (T a) where
readsPrec i str =
case dropWhile isSpace str of
'T' : str' ->
[(T s i, str''') | (s, str'') <- reads str', (i, str''') <- reads str'']
'V' : str' ->
[(Tvirtual (error "uninitialized tvirtual"), str')]
_ -> []
|
nh2/WashNGo
|
WASH/CGI/StateItem.hs
|
Haskell
|
bsd-3-clause
| 574
|
-- |
-- Module: $Header$
-- Description: Implementation of internal command named version
-- Copyright: (c) 2018-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Implementation of internal command named @version@.
module CommandWrapper.Toolset.InternalSubcommand.Version
( VersionInfo(..)
, PrettyVersion(..)
, version
, versionQQ
, versionSubcommandCompleter
, versionSubcommandDescription
, versionSubcommandHelp
)
where
import Prelude (fromIntegral)
import Control.Applicative ((<*>), (<|>), optional, pure)
import Data.Bool (Bool(True), (||), not, otherwise)
import Data.Foldable (length, null)
import Data.Function (($), (.), const)
import Data.Functor (Functor, (<$>), (<&>), fmap)
import qualified Data.List as List (drop, elem, filter, isPrefixOf, take)
import Data.Maybe (Maybe(Just), fromMaybe)
import Data.Monoid (Endo(Endo, appEndo), mempty)
import Data.Semigroup ((<>))
import Data.String (String, fromString)
import Data.Version (showVersion)
import Data.Word (Word)
import GHC.Generics (Generic)
import System.IO (Handle, IO, IOMode(WriteMode), stdout, withFile)
import Text.Show (Show)
import Data.Monoid.Endo.Fold (foldEndo)
import Data.Output
( OutputFile(OutputFile)
, OutputHandle(OutputHandle, OutputNotHandle)
, OutputStdoutOrFile
, pattern OutputStdoutOnly
)
import Data.Text (Text)
import qualified Data.Text as Text (unlines)
import qualified Data.Text.IO as Text (hPutStr)
import Data.Text.Prettyprint.Doc (Pretty(pretty), (<+>))
import qualified Data.Text.Prettyprint.Doc as Pretty
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Pretty (AnsiStyle)
import qualified Data.Text.Prettyprint.Doc.Util as Pretty (reflow)
import qualified Dhall
import qualified Dhall.Pretty as Dhall (CharacterSet(Unicode))
import qualified Mainplate (applySimpleDefaults)
import qualified Options.Applicative as Options (Parser, defaultPrefs, info)
import qualified Options.Applicative.Standard as Options (outputOption)
import Safe (atMay, headMay, lastMay)
import CommandWrapper.Core.Completion.FileSystem
( FileSystemOptions
( appendSlashToSingleDirectoryResult
, expandTilde
, prefix
, word
)
, defFileSystemOptions
, fileSystemCompleter
)
--import CommandWrapper.Core.Config.Alias (applyAlias)
import CommandWrapper.Core.Config.Shell (Shell(Bash, Fish, Zsh))
import qualified CommandWrapper.Core.Config.Shell as Shell (shellOption)
import CommandWrapper.Core.Dhall as Dhall (hPut)
import CommandWrapper.Core.Environment (AppNames(AppNames, usedName))
import CommandWrapper.Core.Help.Pretty
( globalOptionsHelp
, helpOptions
, longOption
, longOptionWithArgument
, metavar
, optionDescription
, section
, shortOption
, toolsetCommand
, usageSection
)
import CommandWrapper.Core.Message (Result, out)
import CommandWrapper.Toolset.Config.Global
( Config(Config, colourOutput, verbosity)
)
import CommandWrapper.Toolset.InternalSubcommand.Utils (runMain)
import qualified CommandWrapper.Toolset.InternalSubcommand.Utils as Options
( dhallFlag
, helpFlag
)
import CommandWrapper.Toolset.InternalSubcommand.Version.Info
( PrettyVersion(..)
, VersionInfo(..)
, VersionInfoField(..)
, versionQQ
)
import qualified CommandWrapper.Toolset.Options.Optparse as Options
( internalSubcommandParse
)
data VersionMode a
= FullVersion OutputFormat OutputStdoutOrFile a
| NumericVersion (Maybe VersionInfoField) OutputStdoutOrFile a
| VersionHelp a
deriving stock (Functor, Generic, Show)
data OutputFormat
= PlainFormat
| DhallFormat
| ShellFormat Shell
deriving stock (Generic, Show)
version
:: VersionInfo
-> AppNames
-> [String]
-> Config
-> IO ()
version versionInfo appNames options config =
runMain (parseOptions appNames config options) defaults \case
FullVersion format output Config{colourOutput, verbosity} -> do
withOutputHandle output \handle -> case format of
DhallFormat ->
Dhall.hPut colourOutput Dhall.Unicode handle Dhall.inject
versionInfo
ShellFormat shell ->
(\f -> Text.hPutStr handle $ f versionInfo) case shell of
Bash -> versionInfoBash
Fish -> versionInfoFish
Zsh -> versionInfoBash -- Same syntax as Bash.
PlainFormat ->
out verbosity colourOutput handle
(versionInfoDoc versionInfo)
NumericVersion _field output Config{colourOutput, verbosity} -> do
withOutputHandle output \handle ->
out verbosity colourOutput handle "TODO: Implement"
VersionHelp config'@Config{colourOutput, verbosity} -> do
out verbosity colourOutput stdout
(versionSubcommandHelp appNames config')
where
defaults = Mainplate.applySimpleDefaults
(FullVersion PlainFormat OutputStdoutOnly config)
withOutputHandle :: OutputStdoutOrFile -> (Handle -> IO a) -> IO a
withOutputHandle = \case
OutputHandle _ -> ($ stdout)
OutputNotHandle (OutputFile fn) -> withFile fn WriteMode
versionInfoDoc :: VersionInfo -> Pretty.Doc (Result Pretty.AnsiStyle)
versionInfoDoc VersionInfo{..} = Pretty.vsep
[ "Command Wrapper Tool:" <+> pretty commandWrapper
, "Subcommand Protocol: " <+> pretty subcommandProtocol
, "Dhall Library: " <+> pretty dhallLibrary
, "Dhall Standard: " <+> pretty dhallStandard
, ""
]
versionInfoBash :: VersionInfo -> Text
versionInfoBash VersionInfo{..} = Text.unlines
[ var "TOOL" (showVersion' commandWrapper)
, var "SUBCOMMAND_PROTOCOL" (showVersion' subcommandProtocol)
, var "DHALL_LIBRARY" (showVersion' dhallLibrary)
, var "DHALL_STANDARD" (showVersion' dhallStandard)
]
where
showVersion' = fromString . showVersion . rawVersion
var n v = "COMMAND_WRAPPER_" <> n <> "_VERSION='" <> v <> "'"
versionInfoFish :: VersionInfo -> Text
versionInfoFish VersionInfo{..} = Text.unlines
[ var "TOOL" (showVersion' commandWrapper)
, var "SUBCOMMAND_PROTOCOL" (showVersion' subcommandProtocol)
, var "DHALL_LIBRARY" (showVersion' dhallLibrary)
, var "DHALL_STANDARD" (showVersion' dhallStandard)
]
where
showVersion' = fromString . showVersion . rawVersion
var n v = "set COMMAND_WRAPPER_" <> n <> "_VERSION '" <> v <> "'"
parseOptions :: AppNames -> Config -> [String] -> IO (Endo (VersionMode Config))
parseOptions appNames config options =
execParser $ foldEndo
<$> ( Options.dhallFlag switchToDhallFormat
<|> fmap switchToShellFormat Shell.shellOption
<|> Options.helpFlag switchToHelpMode
)
<*> optional outputOption
where
switchTo f = Endo \case
FullVersion _ o a -> f o a
NumericVersion _ o a -> f o a
VersionHelp a -> f OutputStdoutOnly a
switchToDhallFormat = switchTo (FullVersion DhallFormat)
switchToHelpMode = switchTo (const VersionHelp)
switchToShellFormat f =
let shell = f `appEndo` Bash
in switchTo (FullVersion (ShellFormat shell))
outputOption :: Options.Parser (Endo (VersionMode Config))
outputOption = Options.outputOption <&> \o -> Endo \case
FullVersion format _ a -> FullVersion format o a
NumericVersion field _ a -> NumericVersion field o a
VersionHelp a -> VersionHelp a
execParser parser =
Options.internalSubcommandParse appNames config "version"
Options.defaultPrefs (Options.info parser mempty) options
versionSubcommandDescription :: String
versionSubcommandDescription = "Display version information."
versionSubcommandHelp
:: AppNames
-> Config
-> Pretty.Doc (Result Pretty.AnsiStyle)
versionSubcommandHelp AppNames{usedName} _config = Pretty.vsep
[ Pretty.reflow (fromString versionSubcommandDescription)
, ""
, usageSection usedName
[ "version"
<+> Pretty.brackets
( longOption "dhall"
<> "|" <> longOptionWithArgument "shell" "SHELL"
-- <> "|" <> longOptionWithArgument "numeric" "COMPONENT"
)
<+> Pretty.brackets (longOption "output" <> "=" <> metavar "FILE")
, "version" <+> helpOptions
, "help version"
, Pretty.braces (longOption "version" <> "|" <> shortOption 'V')
]
, section "Options:"
[ optionDescription ["--dhall"]
[ Pretty.reflow "Print version information in Dhall format."
]
, optionDescription ["--shell=SHELL"]
[ Pretty.reflow
"Print version information in format suitable for SHELL."
]
, optionDescription ["--output=FILE", "--output FILE", "-o FILE"]
[ Pretty.reflow "Write optput into", metavar "FILE"
, Pretty.reflow "instead of standard output."
]
-- , optionDescription ["--numeric=COMPONENT"]
-- [ Pretty.reflow "Print version of ", metavar "COMPONENT"
-- , Pretty.reflow " in machine readable form."
-- ]
, optionDescription ["--help", "-h"]
[ Pretty.reflow "Print this help and exit. Same as"
, Pretty.squotes (toolsetCommand usedName "help version") <> "."
]
, globalOptionsHelp usedName
]
, ""
]
versionSubcommandCompleter
:: AppNames
-> Config
-> Shell
-> Word
-> [String]
-> IO [String]
versionSubcommandCompleter _appNames _config _shell index words
| Just "-o" <- lastMay wordsBeforePattern =
fsCompleter ""
| Just "--output" <- lastMay wordsBeforePattern =
fsCompleter ""
| null pat =
pure versionOptions
| "--shell=" `List.isPrefixOf` pat =
pure $ List.filter (pat `List.isPrefixOf`) shellOptions
| "--output=" `List.isPrefixOf` pat =
fsCompleter "--output="
| Just '-' <- headMay pat =
pure case List.filter (pat `List.isPrefixOf`) versionOptions of
["--shell="] -> shellOptions
opts -> opts
| otherwise =
pure []
where
wordsBeforePattern = List.take (fromIntegral index) words
pat = fromMaybe "" $ atMay words (fromIntegral index)
hadHelp =
("--help" `List.elem` wordsBeforePattern)
|| ("-h" `List.elem` wordsBeforePattern)
hadDhall = "--dhall" `List.elem` wordsBeforePattern
hadShell =
not . null
$ List.filter ("--shell=" `List.isPrefixOf`) wordsBeforePattern
versionOptions =
munless (hadDhall || hadShell || hadHelp)
["--help", "-h", "--dhall", "--shell="]
<> munless hadHelp ["-o", "--output="]
shellOptions = ("--shell=" <>) <$> ["bash", "fish", "zsh"]
munless p x = if not p then x else mempty
fsCompleter prefix =
fileSystemCompleter defFileSystemOptions
{ appendSlashToSingleDirectoryResult = True
, expandTilde = not (null prefix)
, prefix
, word = List.drop (length prefix) pat
}
|
trskop/command-wrapper
|
command-wrapper/src/CommandWrapper/Toolset/InternalSubcommand/Version.hs
|
Haskell
|
bsd-3-clause
| 11,390
|
module Main (main) where
import Cudd
import Prop
import Control.Monad (guard)
import Data.List (sort)
import System.Mem (performGC)
import Text.Printf (printf)
isPermutationOf :: [Int] -> [Int] -> Bool
isPermutationOf vs vs' = sort vs == sort vs'
implies :: Prop -> Prop -> Prop
implies p q = PNot p `POr` q
conjoin = foldl PAnd PTrue
disjoin = foldl POr PFalse
-- Returns a proposition representing the nxn board with values specified
-- in row-major order according to perm.
modelBoard :: Int -> [Int] -> Prop
modelBoard n perm
| not (isPermutationOf perm [0..n * n - 1]) =
error "modelBoard: given board is not a permutation"
| otherwise = cellAssigns
where
numVals = n * n
vals = [0..n*n-1]
cells = [(i, j) | i <- [0..n-1], j <- [0..n-1]]
idxToCell 0 = (0, 0)
idxToCell i = i `divMod` (numVals * i * n)
cellHasVal (i, j) v = PVar (numVals * (i * n + j) + v)
cellAssigns = conjoin $ do
(i, v) <- zip [0..] perm
v' <- vals
let p = cellHasVal (idxToCell i) v'
return $ if v == v' then p else PNot p
-- Returns a proposition representing all valid nxn boards.
modelBoards :: Int -> Prop
modelBoards n
| n <= 0 = error "modelBoard: n is not positive"
| otherwise =
let numVals = n*n
vals = [0..n*n-1]
cells = [(i, j) | i <- [0..n-1], j <- [0..n-1]]
-- One variable per possible value ([0..n*n-1]) per cell
cellHasVal (i, j) v = PVar (numVals * (i * n + j) + v)
cellAtLeastOne c = disjoin [ cellHasVal c v | v <- vals ]
cellAtMostOne c =
conjoin [ cellHasVal c v `implies` PNot (cellHasVal c v') |
v <- vals, v' <- vals, v /= v' ]
cellsUnique = conjoin $ do
c <- cells
c' <- cells
guard (c /= c')
v <- vals
return $ cellHasVal c v `implies` PNot (cellHasVal c' v)
in conjoin ([cellAtLeastOne c `PAnd` cellAtMostOne c | c <- cells] ++
[cellsUnique])
main :: IO ()
main = do
let startPerm = [9, 11, 10, 15, 12, 7, 8, 3, 13, 6, 14, 4, 5, 1, 0, 2]
-- let goalPerm = [0..15]
mgr <- newMgr
do oldNodeLimit <- nodeLimit mgr
setNodeLimit mgr 20000000
newNodeLimit <- nodeLimit mgr
printf "changed node limit from %d to %d\n" oldNodeLimit newNodeLimit
-- enableDynamicReordering mgr cudd_reorder_window3
-- enableDynamicReordering mgr cudd_reorder_sift
-- enableReorderingReporting mgr
startBoard <- synthesizeBdd mgr (modelBoard 4 startPerm)
-- goalBoard <- modelBoard goalPerm
performGC
printf "%d BDD variables\n" =<< numVars mgr
printf "%d BDD nodes\n" =<< numNodes mgr
printf "startBoard has %.0f minterms\n" =<< bddCountMinterms startBoard
printf "startBoard has %d BDD nodes\n" =<< bddNumNodes startBoard
-- printf "goalBoard has %d minterms\n" =<< bddCountMinterms goalBoard
|
bradlarsen/hs-cudd
|
test/SlidingTile.hs
|
Haskell
|
bsd-3-clause
| 2,917
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE TemplateHaskell #-}
module Mapnik.Color (
Color(..)
, parse
, toText
, colorParser
) where
import Mapnik.Imports
import Mapnik.Util
import Data.Monoid
import Data.Word
import Data.Text (Text)
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder
import qualified Data.Text.Lazy.Builder.Int as B
import qualified Data.Text.Lazy.Builder.RealFloat as B
import Data.Attoparsec.Text hiding (parse)
data Color = RGBA !Word8 !Word8 !Word8 !Word8
deriving (Eq, Show, Generic)
deriveMapnikJSON ''Color
parse :: Text -> Either String Color
parse = parseOnly (colorParser <* endOfInput)
colorParser :: Parser Color
--TODO Hex parser
colorParser = choice (rgb:rgba:namedColors) where
rgb = "rgb" *> bracketed (do
[r,g,b] <- sepByCommas decimal
pure (RGBA r g b 255)
)
rgba = "rgba" *> bracketed (do
r <- decimal <* commaWs
g <- decimal <* commaWs
b <- decimal <* commaWs
a <- cppDouble
pure (RGBA r g b (round (a*255)))
)
namedColors :: [Parser Color]
namedColors = ("transparent" *> pure (RGBA 0 0 0 0)) :
map (\(c,(r,g,b)) -> c *> pure (RGBA r g b 255))
[ ("aliceblue", (240, 248, 255))
, ("antiquewhite", (250, 235, 215))
, ("aqua", (0, 255, 255))
, ("aquamarine", (127, 255, 212))
, ("azure", (240, 255, 255))
, ("beige", (245, 245, 220))
, ("bisque", (255, 228, 196))
, ("black", (0, 0, 0))
, ("blanchedalmond", (255,235,205))
, ("blue", (0, 0, 255))
, ("blueviolet", (138, 43, 226))
, ("brown", (165, 42, 42))
, ("burlywood", (222, 184, 135))
, ("cadetblue", (95, 158, 160))
, ("chartreuse", (127, 255, 0))
, ("chocolate", (210, 105, 30))
, ("coral", (255, 127, 80))
, ("cornflowerblue", (100, 149, 237))
, ("cornsilk", (255, 248, 220))
, ("crimson", (220, 20, 60))
, ("cyan", (0, 255, 255))
, ("darkblue", (0, 0, 139))
, ("darkcyan", (0, 139, 139))
, ("darkgoldenrod", (184, 134, 11))
, ("darkgray", (169, 169, 169))
, ("darkgreen", (0, 100, 0))
, ("darkgrey", (169, 169, 169))
, ("darkkhaki", (189, 183, 107))
, ("darkmagenta", (139, 0, 139))
, ("darkolivegreen", (85, 107, 47))
, ("darkorange", (255, 140, 0))
, ("darkorchid", (153, 50, 204))
, ("darkred", (139, 0, 0))
, ("darksalmon", (233, 150, 122))
, ("darkseagreen", (143, 188, 143))
, ("darkslateblue", (72, 61, 139))
, ("darkslategrey", (47, 79, 79))
, ("darkturquoise", (0, 206, 209))
, ("darkviolet", (148, 0, 211))
, ("deeppink", (255, 20, 147))
, ("deepskyblue", (0, 191, 255))
, ("dimgray", (105, 105, 105))
, ("dimgrey", (105, 105, 105))
, ("dodgerblue", (30, 144, 255))
, ("firebrick", (178, 34, 34))
, ("floralwhite", (255, 250, 240))
, ("forestgreen", (34, 139, 34))
, ("fuchsia", (255, 0, 255))
, ("gainsboro", (220, 220, 220))
, ("ghostwhite", (248, 248, 255))
, ("gold", (255, 215, 0))
, ("goldenrod", (218, 165, 32))
, ("gray", (128, 128, 128))
, ("grey", (128, 128, 128))
, ("green", (0, 128, 0))
, ("greenyellow", (173, 255, 47))
, ("honeydew", (240, 255, 240))
, ("hotpink", (255, 105, 180))
, ("indianred", (205, 92, 92))
, ("indigo", (75, 0, 130))
, ("ivory", (255, 255, 240))
, ("khaki", (240, 230, 140))
, ("lavender", (230, 230, 250))
, ("lavenderblush", (255, 240, 245))
, ("lawngreen", (124, 252, 0))
, ("lemonchiffon", (255, 250, 205))
, ("lightblue", (173, 216, 230))
, ("lightcoral", (240, 128, 128))
, ("lightcyan", (224, 255, 255))
, ("lightgoldenrodyellow", (250, 250, 210))
, ("lightgray", (211, 211, 211))
, ("lightgreen", (144, 238, 144))
, ("lightgrey", (211, 211, 211))
, ("lightpink", (255, 182, 193))
, ("lightsalmon", (255, 160, 122))
, ("lightseagreen", (32, 178, 170))
, ("lightskyblue", (135, 206, 250))
, ("lightslategray", (119, 136, 153))
, ("lightslategrey", (119, 136, 153))
, ("lightsteelblue", (176, 196, 222))
, ("lightyellow", (255, 255, 224))
, ("lime", (0, 255, 0))
, ("limegreen", (50, 205, 50))
, ("linen", (250, 240, 230))
, ("magenta", (255, 0, 255))
, ("maroon", (128, 0, 0))
, ("mediumaquamarine", (102, 205, 170))
, ("mediumblue", (0, 0, 205))
, ("mediumorchid", (186, 85, 211))
, ("mediumpurple", (147, 112, 219))
, ("mediumseagreen", (60, 179, 113))
, ("mediumslateblue", (123, 104, 238))
, ("mediumspringgreen", (0, 250, 154))
, ("mediumturquoise", (72, 209, 204))
, ("mediumvioletred", (199, 21, 133))
, ("midnightblue", (25, 25, 112))
, ("mintcream", (245, 255, 250))
, ("mistyrose", (255, 228, 225))
, ("moccasin", (255, 228, 181))
, ("navajowhite", (255, 222, 173))
, ("navy", (0, 0, 128))
, ("oldlace", (253, 245, 230))
, ("olive", (128, 128, 0))
, ("olivedrab", (107, 142, 35))
, ("orange", (255, 165, 0))
, ("orangered", (255, 69, 0))
, ("orchid", (218, 112, 214))
, ("palegoldenrod", (238, 232, 170))
, ("palegreen", (152, 251, 152))
, ("paleturquoise", (175, 238, 238))
, ("palevioletred", (219, 112, 147))
, ("papayawhip", (255, 239, 213))
, ("peachpuff", (255, 218, 185))
, ("peru", (205, 133, 63))
, ("pink", (255, 192, 203))
, ("plum", (221, 160, 221))
, ("powderblue", (176, 224, 230))
, ("purple", (128, 0, 128))
, ("red", (255, 0, 0))
, ("rosybrown", (188, 143, 143))
, ("royalblue", (65, 105, 225))
, ("saddlebrown", (139, 69, 19))
, ("salmon", (250, 128, 114))
, ("sandybrown", (244, 164, 96))
, ("seagreen", (46, 139, 87))
, ("seashell", (255, 245, 238))
, ("sienna", (160, 82, 45))
, ("silver", (192, 192, 192))
, ("skyblue", (135, 206, 235))
, ("slateblue", (106, 90, 205))
, ("slategray", (112, 128, 144))
, ("slategrey", (112, 128, 144))
, ("snow", (255, 250, 250))
, ("springgreen", (0, 255, 127))
, ("steelblue", (70, 130, 180))
, ("tan", (210, 180, 140))
, ("teal", (0, 128, 128))
, ("thistle", (216, 191, 216))
, ("tomato", (255, 99, 71))
, ("turquoise", (64, 224, 208))
, ("violet", (238, 130, 238))
, ("wheat", (245, 222, 179))
, ("white", (255, 255, 255))
, ("whitesmoke", (245, 245, 245))
, ("yellow", (255, 255, 0))
, ("yellowgreen", (154, 205, 50))
]
toText :: Color -> Text
toText (RGBA r g b 255) = toStrict $ toLazyText $
"rgb(" <> B.decimal r <> ", "
<> B.decimal g <> ", "
<> B.decimal b
<> ")"
toText (RGBA r g b a) = toStrict $ toLazyText $
"rgba(" <> B.decimal r <> ", "
<> B.decimal g <> ", "
<> B.decimal b <> ", "
<> B.formatRealFloat B.Fixed (Just 3) (fromIntegral a / 255 :: Float)
<> ")"
|
albertov/hs-mapnik
|
pure/src/Mapnik/Color.hs
|
Haskell
|
bsd-3-clause
| 7,184
|
{-# LANGUAGE CPP #-}
module Options.Applicative.Help.Chunk
( mappendWith
, Chunk(..)
, chunked
, listToChunk
, (<<+>>)
, (<</>>)
, vcatChunks
, vsepChunks
, isEmpty
, stringChunk
, paragraph
, extractChunk
, tabulate
) where
import Control.Applicative
import Control.Monad
import Data.Maybe
import Data.Monoid
import Options.Applicative.Help.Pretty
mappendWith :: Monoid a => a -> a -> a -> a
mappendWith s x y = mconcat [x, s, y]
-- | The free monoid on a semigroup 'a'.
newtype Chunk a = Chunk
{ unChunk :: Maybe a }
deriving (Eq, Show)
instance Functor Chunk where
fmap f = Chunk . fmap f . unChunk
instance Applicative Chunk where
pure = Chunk . pure
Chunk f <*> Chunk x = Chunk (f <*> x)
instance Monad Chunk where
return = pure
m >>= f = Chunk $ unChunk m >>= unChunk . f
instance MonadPlus Chunk where
mzero = Chunk mzero
mplus m1 m2 = Chunk $ mplus (unChunk m1) (unChunk m2)
-- | Given a semigroup structure on 'a', return a monoid structure on 'Chunk a'.
--
-- Note that this is /not/ the same as 'liftA2'.
chunked :: (a -> a -> a)
-> Chunk a -> Chunk a -> Chunk a
chunked _ (Chunk Nothing) y = y
chunked _ x (Chunk Nothing) = x
chunked f (Chunk (Just x)) (Chunk (Just y)) = Chunk (Just (f x y))
-- | Concatenate a list into a Chunk. 'listToChunk' satisfies:
--
-- > isEmpty . listToChunk = null
-- > listToChunk = mconcat . fmap pure
listToChunk :: Monoid a => [a] -> Chunk a
listToChunk [] = mempty
listToChunk xs = pure (mconcat xs)
instance Monoid a => Monoid (Chunk a) where
mempty = Chunk Nothing
mappend = chunked mappend
-- | Part of a constrained comonad instance.
--
-- This is the counit of the adjunction between 'Chunk' and the forgetful
-- functor from monoids to semigroups. It satisfies:
--
-- > extractChunk . pure = id
-- > extractChunk . fmap pure = id
extractChunk :: Monoid a => Chunk a -> a
extractChunk = fromMaybe mempty . unChunk
-- we could also define:
-- duplicate :: Monoid a => Chunk a -> Chunk (Chunk a)
-- duplicate = fmap pure
-- | Concatenate two 'Chunk's with a space in between. If one is empty, this
-- just returns the other one.
--
-- Unlike '<+>' for 'Doc', this operation has a unit element, namely the empty
-- 'Chunk'.
(<<+>>) :: Chunk Doc -> Chunk Doc -> Chunk Doc
(<<+>>) = chunked (<+>)
-- | Concatenate two 'Chunk's with a softline in between. This is exactly like
-- '<<+>>', but uses a softline instead of a space.
(<</>>) :: Chunk Doc -> Chunk Doc -> Chunk Doc
(<</>>) = chunked (</>)
-- | Concatenate 'Chunk's vertically.
vcatChunks :: [Chunk Doc] -> Chunk Doc
vcatChunks = foldr (chunked (.$.)) mempty
-- | Concatenate 'Chunk's vertically separated by empty lines.
vsepChunks :: [Chunk Doc] -> Chunk Doc
vsepChunks = foldr (chunked (\x y -> x .$. mempty .$. y)) mempty
-- | Whether a 'Chunk' is empty. Note that something like 'pure mempty' is not
-- considered an empty chunk, even though the underlying 'Doc' is empty.
isEmpty :: Chunk a -> Bool
isEmpty = isNothing . unChunk
-- | Convert a 'String' into a 'Chunk'. This satisfies:
--
-- > isEmpty . stringChunk = null
-- > extractChunk . stringChunk = string
stringChunk :: String -> Chunk Doc
stringChunk "" = mempty
stringChunk s = pure (string s)
-- | Convert a paragraph into a 'Chunk'. The resulting chunk is composed by the
-- words of the original paragraph separated by softlines, so it will be
-- automatically word-wrapped when rendering the underlying document.
--
-- This satisfies:
--
-- > isEmpty . paragraph = null . words
paragraph :: String -> Chunk Doc
paragraph = foldr (chunked (</>)) mempty
. map stringChunk
. words
tabulate' :: Int -> [(Doc, Doc)] -> Chunk Doc
tabulate' _ [] = mempty
tabulate' size table = pure $ vcat
[ indent 2 (fillBreak size key <+> value)
| (key, value) <- table ]
-- | Display pairs of strings in a table.
tabulate :: [(Doc, Doc)] -> Chunk Doc
tabulate = tabulate' 24
|
thielema/optparse-applicative
|
Options/Applicative/Help/Chunk.hs
|
Haskell
|
bsd-3-clause
| 3,939
|
{--
--- Day 4: The Ideal Stocking Stuffer ---
Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.
To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash.
For example:
If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so.
If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....
--- Part Two ---
Now find one that starts with six zeroes.
--}
{-# LANGUAGE OverloadedStrings #-}
module Day4
( answers
) where
import Data.Digest.Pure.MD5
import qualified Data.ByteString.Lazy.Char8 as B
secretKey :: String
secretKey = "bgvyzdsv"
findInt :: [Int] -> String -> Int -> Int
findInt (x:xs) key zeros = let hashKey = secretKey ++ show x
hash = B.pack . show $ md5 (B.pack hashKey)
zs = B.pack . take zeros $ repeat '0'
in if B.isPrefixOf zs hash
then x
else findInt xs key zeros
mine :: Int -> Int
mine = findInt [0..] secretKey
answers :: IO ()
answers = do
putStrLn $ "day 4 part 1 = " ++ show (mine 5)
putStrLn $ "day 4 part 2 = " ++ show (mine 6)
|
hlmerscher/advent-of-code-2015
|
src/Day4.hs
|
Haskell
|
bsd-3-clause
| 1,766
|
{-# LANGUAGE OverloadedStrings #-}
module Trello.Request (
getBoardById
, getCardById
, getListById
, getMemberById
, getCardsByBoardId
, getListsByBoardId
, getMembersByBoardId
) where
import Trello.Data
import Control.Applicative ((<$>), (<*>))
import Control.Monad hiding (join)
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON (..), Value (..), decode, (.:), (.:?))
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.List
import Network.HTTP.Base
import Network.HTTP.Conduit
import Trello.ApiData
baseUrl = "https://api.trello.com/1/"
boardPath = "boards"
listPath = "lists"
cardPath = "cards"
memberPath = "members"
requestURL = "https://trello.com/1/OAuthGetRequestToken"
accessURL = "https://trello.com/1/OAuthGetAccessToken"
authorizeURL = "https://trello.com/1/OAuthAuthorizeToken"
boardParams = [("lists", "all"), ("members", "all")]
listParams = [("cards", "all")]
cardParams = []
memberParams = []
type HttpParams = [(String, String)]
getBoardById :: MonadIO m => OAuth -> BoardRef -> m ByteString
getBoardById oauth (BoardRef id) = board' oauth [boardPath, id]
getCardById :: MonadIO m => OAuth -> CardRef -> m ByteString
getCardById oauth (CardRef id) = card' oauth [cardPath, id]
getListById :: MonadIO m => OAuth -> ListRef -> m ByteString
getListById oauth (ListRef id) = list' oauth [listPath, id]
getMemberById :: MonadIO m => OAuth -> MemberRef -> m ByteString
getMemberById oauth (MemberRef id) = member' oauth [memberPath, id]
getCardsByBoardId :: MonadIO m => OAuth -> BoardRef -> Maybe CardFilter -> m ByteString
getCardsByBoardId oauth (BoardRef id) Nothing = card' oauth [boardPath, id, cardPath]
getCardsByBoardId oauth (BoardRef id) (Just filter) = card' oauth [boardPath, id, cardPath, show filter]
getListsByBoardId :: MonadIO m => OAuth -> BoardRef -> Maybe ListFilter -> m ByteString
getListsByBoardId oauth (BoardRef id) Nothing = list' oauth [boardPath, id, listPath]
getListsByBoardId oauth (BoardRef id) (Just filter) = list' oauth [boardPath, id, listPath, show filter]
getMembersByBoardId :: MonadIO m => OAuth -> BoardRef -> Maybe MemberFilter -> m ByteString
getMembersByBoardId oauth (BoardRef id) Nothing = member' oauth [boardPath, id, memberPath]
getMembersByBoardId oauth (BoardRef id) (Just filter) = member' oauth [boardPath, id, memberPath, show filter]
board', card', list', member' :: MonadIO m => OAuth -> [String] -> m ByteString
board' oauth path = api' oauth path boardParams
card' oauth path = api' oauth path cardParams
list' oauth path = api' oauth path listParams
member' oauth path = api' oauth path memberParams
api' :: MonadIO m => OAuth -> [String] -> [(String, String)] -> m ByteString
api' oauth path params = simpleHttp requestURL
where requestURL = baseUrl ++ intercalate "/" path ++ "?" ++ urlEncodeVars (params ++ oauthList oauth)
oauthList :: OAuth -> [(String, String)]
oauthList (OAuth key token) = [("key", key),("token", token)]
|
vamega/haskell-trello
|
src/Trello/Request.hs
|
Haskell
|
bsd-3-clause
| 3,115
|
module FindFlowCover where
import Control.Monad.ST
import Control.Monad.ST.Unsafe
import Data.Array.MArray (getElems)
import Grid (initG, updateCoord, Coord, Direction)
import FindTrails
-- | Solve the Grid used depth wise back tracking search
searchForTrails :: Grid -> [FTrail]
searchForTrails (Grid size endpoints) = runST $ do
gf <- initG (maxCoords size) (map epSource endpoints) (map epSink endpoints)
result <- solveGrid1 gf True (zip endpoints [0,1..])
-- Success continuation
(\_grid route -> return $ SFinished [route])
case result of
SFinished trail -> return trail
SNext -> error "No solution exists"
-- | Solve the Grid used depth wise back tracking search
searchForCover :: Grid -> [FTrail]
searchForCover (Grid size endpoints) = runST $ do
gf <- initG maxBound (map epSource endpoints) (map epSink endpoints)
-- grid <- initBoolG maxBound False
result <- solveGrid1 gf False (zip endpoints [0,1..])
(\grid route -> do
-- Here we are at the bottom of the recursion. We only have the route
-- of the last color.
-- Check whether we have a complete cover.
elems <- getElems grid
let unCovCount = length $ filter not elems
-- I am guessing it is the case that if there is a solution with
-- exactly one square uncovered, then there is no solution with
-- all squares covered.
if unCovCount < 2 then return $ SFinished [route]
-- In this case we would like to show all the routes to see how
-- close we got, but not too often. How to do that?
-- Would need to accumulate the routes.
else return SNext)
case result of
SFinished trail -> return trail
SNext -> error "No solution exists"
where maxBound = maxCoords size
-- | Solve the grid and return solutions as coordinates
--traceTrail :: Grid -> [[Coord]]
traceTrail :: [FTrail] -> [[Coord]]
traceTrail = map (\trail -> scanl updateCoord (fst $ head trail) $ map snd trail)
trailFind :: Grid -> [[Coord]]
trailFind = traceTrail . searchForTrails
trailCover :: Grid -> [[Coord]]
trailCover = traceTrail . searchForCover
|
habbler/GridFlowCover
|
src/FindFlowCover.hs
|
Haskell
|
bsd-3-clause
| 2,416
|
--------------------------------------------------------------------------------
-- | Pretty print LLVM IR Code.
--
module Llvm.PpLlvm (
-- * Top level LLVM objects.
ppLlvmModule,
ppLlvmComments,
ppLlvmComment,
ppLlvmGlobals,
ppLlvmGlobal,
ppLlvmAliases,
ppLlvmAlias,
ppLlvmMetas,
ppLlvmMeta,
ppLlvmFunctionDecls,
ppLlvmFunctionDecl,
ppLlvmFunctions,
ppLlvmFunction,
) where
#include "HsVersions.h"
import Llvm.AbsSyn
import Llvm.MetaData
import Llvm.Types
import Data.List ( intersperse )
import Outputable
import Unique
import FastString ( sLit )
--------------------------------------------------------------------------------
-- * Top Level Print functions
--------------------------------------------------------------------------------
-- | Print out a whole LLVM module.
ppLlvmModule :: LlvmModule -> SDoc
ppLlvmModule (LlvmModule comments aliases meta globals decls funcs)
= ppLlvmComments comments $+$ newLine
$+$ ppLlvmAliases aliases $+$ newLine
$+$ ppLlvmMetas meta $+$ newLine
$+$ ppLlvmGlobals globals $+$ newLine
$+$ ppLlvmFunctionDecls decls $+$ newLine
$+$ ppLlvmFunctions funcs
-- | Print out a multi-line comment, can be inside a function or on its own
ppLlvmComments :: [LMString] -> SDoc
ppLlvmComments comments = vcat $ map ppLlvmComment comments
-- | Print out a comment, can be inside a function or on its own
ppLlvmComment :: LMString -> SDoc
ppLlvmComment com = semi <+> ftext com
-- | Print out a list of global mutable variable definitions
ppLlvmGlobals :: [LMGlobal] -> SDoc
ppLlvmGlobals ls = vcat $ map ppLlvmGlobal ls
-- | Print out a global mutable variable definition
ppLlvmGlobal :: LMGlobal -> SDoc
ppLlvmGlobal (LMGlobal var@(LMGlobalVar _ _ link x a c) dat) =
let sect = case x of
Just x' -> text ", section" <+> doubleQuotes (ftext x')
Nothing -> empty
align = case a of
Just a' -> text ", align" <+> int a'
Nothing -> empty
rhs = case dat of
Just stat -> ppr stat
Nothing -> ppr (pLower $ getVarType var)
-- Position of linkage is different for aliases.
const_link = case c of
Global -> ppr link <+> text "global"
Constant -> ppr link <+> text "constant"
Alias -> ppr link <+> text "alias"
in ppAssignment var $ const_link <+> rhs <> sect <> align
$+$ newLine
ppLlvmGlobal (LMGlobal var val) = sdocWithDynFlags $ \dflags ->
error $ "Non Global var ppr as global! "
++ showSDoc dflags (ppr var) ++ " " ++ showSDoc dflags (ppr val)
-- | Print out a list of LLVM type aliases.
ppLlvmAliases :: [LlvmAlias] -> SDoc
ppLlvmAliases tys = vcat $ map ppLlvmAlias tys
-- | Print out an LLVM type alias.
ppLlvmAlias :: LlvmAlias -> SDoc
ppLlvmAlias (name, ty)
= char '%' <> ftext name <+> equals <+> text "type" <+> ppr ty
-- | Print out a list of LLVM metadata.
ppLlvmMetas :: [MetaDecl] -> SDoc
ppLlvmMetas metas = vcat $ map ppLlvmMeta metas
-- | Print out an LLVM metadata definition.
ppLlvmMeta :: MetaDecl -> SDoc
ppLlvmMeta (MetaUnamed n m)
= exclamation <> int n <> text " = " <> ppLlvmMetaExpr m
ppLlvmMeta (MetaNamed n m)
= exclamation <> ftext n <> text " = !" <> braces nodes
where
nodes = hcat $ intersperse comma $ map pprNode m
pprNode n = exclamation <> int n
-- | Print out an LLVM metadata value.
ppLlvmMetaExpr :: MetaExpr -> SDoc
ppLlvmMetaExpr (MetaStr s ) = text "metadata !" <> doubleQuotes (ftext s)
ppLlvmMetaExpr (MetaNode n ) = text "metadata !" <> int n
ppLlvmMetaExpr (MetaVar v ) = ppr v
ppLlvmMetaExpr (MetaStruct es) =
text "metadata !{" <> hsep (punctuate comma (map ppLlvmMetaExpr es)) <> char '}'
-- | Print out a list of function definitions.
ppLlvmFunctions :: LlvmFunctions -> SDoc
ppLlvmFunctions funcs = vcat $ map ppLlvmFunction funcs
-- | Print out a function definition.
ppLlvmFunction :: LlvmFunction -> SDoc
ppLlvmFunction (LlvmFunction dec args attrs sec body) =
let attrDoc = ppSpaceJoin attrs
secDoc = case sec of
Just s' -> text "section" <+> (doubleQuotes $ ftext s')
Nothing -> empty
in text "define" <+> ppLlvmFunctionHeader dec args
<+> attrDoc <+> secDoc
$+$ lbrace
$+$ ppLlvmBlocks body
$+$ rbrace
$+$ newLine
$+$ newLine
-- | Print out a function defenition header.
ppLlvmFunctionHeader :: LlvmFunctionDecl -> [LMString] -> SDoc
ppLlvmFunctionHeader (LlvmFunctionDecl n l c r varg p a) args
= let varg' = case varg of
VarArgs | null p -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
align = case a of
Just a' -> text " align " <> ppr a'
Nothing -> empty
args' = map (\((ty,p),n) -> ppr ty <+> ppSpaceJoin p <+> char '%'
<> ftext n)
(zip p args)
in ppr l <+> ppr c <+> ppr r <+> char '@' <> ftext n <> lparen <>
(hsep $ punctuate comma args') <> ptext varg' <> rparen <> align
-- | Print out a list of function declaration.
ppLlvmFunctionDecls :: LlvmFunctionDecls -> SDoc
ppLlvmFunctionDecls decs = vcat $ map ppLlvmFunctionDecl decs
-- | Print out a function declaration.
-- Declarations define the function type but don't define the actual body of
-- the function.
ppLlvmFunctionDecl :: LlvmFunctionDecl -> SDoc
ppLlvmFunctionDecl (LlvmFunctionDecl n l c r varg p a)
= let varg' = case varg of
VarArgs | null p -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
align = case a of
Just a' -> text " align" <+> ppr a'
Nothing -> empty
args = hcat $ intersperse (comma <> space) $
map (\(t,a) -> ppr t <+> ppSpaceJoin a) p
in text "declare" <+> ppr l <+> ppr c <+> ppr r <+> char '@' <>
ftext n <> lparen <> args <> ptext varg' <> rparen <> align $+$ newLine
-- | Print out a list of LLVM blocks.
ppLlvmBlocks :: LlvmBlocks -> SDoc
ppLlvmBlocks blocks = vcat $ map ppLlvmBlock blocks
-- | Print out an LLVM block.
-- It must be part of a function definition.
ppLlvmBlock :: LlvmBlock -> SDoc
ppLlvmBlock (LlvmBlock blockId stmts) =
let isLabel (MkLabel _) = True
isLabel _ = False
(block, rest) = break isLabel stmts
ppRest = case rest of
MkLabel id:xs -> ppLlvmBlock (LlvmBlock id xs)
_ -> empty
in ppLlvmBlockLabel blockId
$+$ (vcat $ map ppLlvmStatement block)
$+$ newLine
$+$ ppRest
-- | Print out an LLVM block label.
ppLlvmBlockLabel :: LlvmBlockId -> SDoc
ppLlvmBlockLabel id = pprUnique id <> colon
-- | Print out an LLVM statement.
ppLlvmStatement :: LlvmStatement -> SDoc
ppLlvmStatement stmt =
let ind = (text " " <>)
in case stmt of
Assignment dst expr -> ind $ ppAssignment dst (ppLlvmExpression expr)
Fence st ord -> ind $ ppFence st ord
Branch target -> ind $ ppBranch target
BranchIf cond ifT ifF -> ind $ ppBranchIf cond ifT ifF
Comment comments -> ind $ ppLlvmComments comments
MkLabel label -> ppLlvmBlockLabel label
Store value ptr -> ind $ ppStore value ptr
Switch scrut def tgs -> ind $ ppSwitch scrut def tgs
Return result -> ind $ ppReturn result
Expr expr -> ind $ ppLlvmExpression expr
Unreachable -> ind $ text "unreachable"
Nop -> empty
MetaStmt meta s -> ppMetaStatement meta s
-- | Print out an LLVM expression.
ppLlvmExpression :: LlvmExpression -> SDoc
ppLlvmExpression expr
= case expr of
Alloca tp amount -> ppAlloca tp amount
LlvmOp op left right -> ppMachOp op left right
Call tp fp args attrs -> ppCall tp fp (map MetaVar args) attrs
CallM tp fp args attrs -> ppCall tp fp args attrs
Cast op from to -> ppCast op from to
Compare op left right -> ppCmpOp op left right
Extract vec idx -> ppExtract vec idx
Insert vec elt idx -> ppInsert vec elt idx
GetElemPtr inb ptr indexes -> ppGetElementPtr inb ptr indexes
Load ptr -> ppLoad ptr
Malloc tp amount -> ppMalloc tp amount
Phi tp precessors -> ppPhi tp precessors
Asm asm c ty v se sk -> ppAsm asm c ty v se sk
MExpr meta expr -> ppMetaExpr meta expr
--------------------------------------------------------------------------------
-- * Individual print functions
--------------------------------------------------------------------------------
-- | Should always be a function pointer. So a global var of function type
-- (since globals are always pointers) or a local var of pointer function type.
ppCall :: LlvmCallType -> LlvmVar -> [MetaExpr] -> [LlvmFuncAttr] -> SDoc
ppCall ct fptr args attrs = case fptr of
--
-- if local var function pointer, unwrap
LMLocalVar _ (LMPointer (LMFunction d)) -> ppCall' d
-- should be function type otherwise
LMGlobalVar _ (LMFunction d) _ _ _ _ -> ppCall' d
-- not pointer or function, so error
_other -> error $ "ppCall called with non LMFunction type!\nMust be "
++ " called with either global var of function type or "
++ "local var of pointer function type."
where
ppCall' (LlvmFunctionDecl _ _ cc ret argTy params _) =
let tc = if ct == TailCall then text "tail " else empty
ppValues = ppCommaJoin args
ppArgTy = (ppCommaJoin $ map fst params) <>
(case argTy of
VarArgs -> text ", ..."
FixedArgs -> empty)
fnty = space <> lparen <> ppArgTy <> rparen <> char '*'
attrDoc = ppSpaceJoin attrs
in tc <> text "call" <+> ppr cc <+> ppr ret
<> fnty <+> ppName fptr <> lparen <+> ppValues
<+> rparen <+> attrDoc
ppMachOp :: LlvmMachOp -> LlvmVar -> LlvmVar -> SDoc
ppMachOp op left right =
(ppr op) <+> (ppr (getVarType left)) <+> ppName left
<> comma <+> ppName right
ppCmpOp :: LlvmCmpOp -> LlvmVar -> LlvmVar -> SDoc
ppCmpOp op left right =
let cmpOp
| isInt (getVarType left) && isInt (getVarType right) = text "icmp"
| isFloat (getVarType left) && isFloat (getVarType right) = text "fcmp"
| otherwise = text "icmp" -- Just continue as its much easier to debug
{-
| otherwise = error ("can't compare different types, left = "
++ (show $ getVarType left) ++ ", right = "
++ (show $ getVarType right))
-}
in cmpOp <+> ppr op <+> ppr (getVarType left)
<+> ppName left <> comma <+> ppName right
ppAssignment :: LlvmVar -> SDoc -> SDoc
ppAssignment var expr = ppName var <+> equals <+> expr
ppFence :: Bool -> LlvmSyncOrdering -> SDoc
ppFence st ord =
let singleThread = case st of True -> text "singlethread"
False -> empty
in text "fence" <+> singleThread <+> ppSyncOrdering ord
ppSyncOrdering :: LlvmSyncOrdering -> SDoc
ppSyncOrdering SyncUnord = text "unordered"
ppSyncOrdering SyncMonotonic = text "monotonic"
ppSyncOrdering SyncAcquire = text "acquire"
ppSyncOrdering SyncRelease = text "release"
ppSyncOrdering SyncAcqRel = text "acq_rel"
ppSyncOrdering SyncSeqCst = text "seq_cst"
-- XXX: On x86, vector types need to be 16-byte aligned for aligned access, but
-- we have no way of guaranteeing that this is true with GHC (we would need to
-- modify the layout of the stack and closures, change the storage manager,
-- etc.). So, we blindly tell LLVM that *any* vector store or load could be
-- unaligned. In the future we may be able to guarantee that certain vector
-- access patterns are aligned, in which case we will need a more granular way
-- of specifying alignment.
ppLoad :: LlvmVar -> SDoc
ppLoad var
| isVecPtrVar var = text "load" <+> ppr var <>
comma <+> text "align 1"
| otherwise = text "load" <+> ppr var
where
isVecPtrVar :: LlvmVar -> Bool
isVecPtrVar = isVector . pLower . getVarType
ppStore :: LlvmVar -> LlvmVar -> SDoc
ppStore val dst
| isVecPtrVar dst = text "store" <+> ppr val <> comma <+> ppr dst <>
comma <+> text "align 1"
| otherwise = text "store" <+> ppr val <> comma <+> ppr dst
where
isVecPtrVar :: LlvmVar -> Bool
isVecPtrVar = isVector . pLower . getVarType
ppCast :: LlvmCastOp -> LlvmVar -> LlvmType -> SDoc
ppCast op from to
= ppr op
<+> ppr (getVarType from) <+> ppName from
<+> text "to"
<+> ppr to
ppMalloc :: LlvmType -> Int -> SDoc
ppMalloc tp amount =
let amount' = LMLitVar $ LMIntLit (toInteger amount) i32
in text "malloc" <+> ppr tp <> comma <+> ppr amount'
ppAlloca :: LlvmType -> Int -> SDoc
ppAlloca tp amount =
let amount' = LMLitVar $ LMIntLit (toInteger amount) i32
in text "alloca" <+> ppr tp <> comma <+> ppr amount'
ppGetElementPtr :: Bool -> LlvmVar -> [LlvmVar] -> SDoc
ppGetElementPtr inb ptr idx =
let indexes = comma <+> ppCommaJoin idx
inbound = if inb then text "inbounds" else empty
in text "getelementptr" <+> inbound <+> ppr ptr <> indexes
ppReturn :: Maybe LlvmVar -> SDoc
ppReturn (Just var) = text "ret" <+> ppr var
ppReturn Nothing = text "ret" <+> ppr LMVoid
ppBranch :: LlvmVar -> SDoc
ppBranch var = text "br" <+> ppr var
ppBranchIf :: LlvmVar -> LlvmVar -> LlvmVar -> SDoc
ppBranchIf cond trueT falseT
= text "br" <+> ppr cond <> comma <+> ppr trueT <> comma <+> ppr falseT
ppPhi :: LlvmType -> [(LlvmVar,LlvmVar)] -> SDoc
ppPhi tp preds =
let ppPreds (val, label) = brackets $ ppName val <> comma <+> ppName label
in text "phi" <+> ppr tp <+> hsep (punctuate comma $ map ppPreds preds)
ppSwitch :: LlvmVar -> LlvmVar -> [(LlvmVar,LlvmVar)] -> SDoc
ppSwitch scrut dflt targets =
let ppTarget (val, lab) = ppr val <> comma <+> ppr lab
ppTargets xs = brackets $ vcat (map ppTarget xs)
in text "switch" <+> ppr scrut <> comma <+> ppr dflt
<+> ppTargets targets
ppAsm :: LMString -> LMString -> LlvmType -> [LlvmVar] -> Bool -> Bool -> SDoc
ppAsm asm constraints rty vars sideeffect alignstack =
let asm' = doubleQuotes $ ftext asm
cons = doubleQuotes $ ftext constraints
rty' = ppr rty
vars' = lparen <+> ppCommaJoin vars <+> rparen
side = if sideeffect then text "sideeffect" else empty
align = if alignstack then text "alignstack" else empty
in text "call" <+> rty' <+> text "asm" <+> side <+> align <+> asm' <> comma
<+> cons <> vars'
ppExtract :: LlvmVar -> LlvmVar -> SDoc
ppExtract vec idx =
text "extractelement"
<+> ppr (getVarType vec) <+> ppName vec <> comma
<+> ppr idx
ppInsert :: LlvmVar -> LlvmVar -> LlvmVar -> SDoc
ppInsert vec elt idx =
text "insertelement"
<+> ppr (getVarType vec) <+> ppName vec <> comma
<+> ppr (getVarType elt) <+> ppName elt <> comma
<+> ppr idx
ppMetaStatement :: [MetaAnnot] -> LlvmStatement -> SDoc
ppMetaStatement meta stmt = ppLlvmStatement stmt <> ppMetaAnnots meta
ppMetaExpr :: [MetaAnnot] -> LlvmExpression -> SDoc
ppMetaExpr meta expr = ppLlvmExpression expr <> ppMetaAnnots meta
ppMetaAnnots :: [MetaAnnot] -> SDoc
ppMetaAnnots meta = hcat $ map ppMeta meta
where
ppMeta (MetaAnnot name e)
= comma <+> exclamation <> ftext name <+>
case e of
MetaNode n -> exclamation <> int n
MetaStruct ms -> exclamation <> braces (ppCommaJoin ms)
other -> exclamation <> braces (ppr other) -- possible?
--------------------------------------------------------------------------------
-- * Misc functions
--------------------------------------------------------------------------------
-- | Blank line.
newLine :: SDoc
newLine = empty
-- | Exclamation point.
exclamation :: SDoc
exclamation = char '!'
|
lukexi/ghc-7.8-arm64
|
compiler/llvmGen/Llvm/PpLlvm.hs
|
Haskell
|
bsd-3-clause
| 16,501
|
c2n :: Num a => Char -> a
c2n x = case x of
'0' -> 0
'1' -> 1
'2' -> 2
'3' -> 3
'4' -> 4
'5' -> 5
'6' -> 6
'7' -> 7
'8' -> 8
'9' -> 9
main :: IO ()
main = print . sum [c2n x | x <- show (2 ^ 1000)]
|
tricorder42/project-euler
|
16_sum_digits_power/16_sum_digits_power.hs
|
Haskell
|
bsd-3-clause
| 277
|
module CVSU.Edges
( Orientation(..)
, Edge(..)
, EdgeImage(..)
, allocEdgeImage
, createEdgeImage
) where
import CVSU.Bindings.Types
import CVSU.Bindings.PixelImage
import CVSU.Bindings.Edges
import CVSU.PixelImage
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.C.Types
import Foreign.Marshal.Array
import Foreign.Storable
import Data.Maybe
import System.IO.Unsafe
data Orientation = HEdge | VEdge deriving Eq
data Edge =
Edge
{ x :: Int
, y :: Int
, orientation :: Orientation
, value :: Float
} deriving Eq
data EdgeImage =
NullEdge |
EdgeImage
{ edgePtr :: !(ForeignPtr C'edge_image)
, original :: PixelImage
, hstep :: Int
, vstep :: Int
, hmargin :: Int
, vmargin :: Int
, boxWidth :: Int
, boxHeight :: Int
, dx :: Int
, dy :: Int
, hedges :: [[Edge]]
, vedges :: [[Edge]]
}
allocEdgeImage :: IO (Maybe (ForeignPtr C'edge_image))
allocEdgeImage = do
ptr <- c'edge_image_alloc
if ptr /= nullPtr
then do
foreignPtr <- newForeignPtr p'edge_image_free ptr
return $ Just foreignPtr
else do
return Nothing
createEdgeImage :: Int -> Int -> Int -> Int -> Int -> Int -> PixelImage -> IO (EdgeImage)
createEdgeImage hstep vstep hmargin vmargin bwidth blength i = do
e <- allocEdgeImage
if isNothing e
then do
return NullEdge
else do
withForeignPtr (fromJust e) $ \e_ptr ->
withForeignPtr (imagePtr i) $ \i_ptr -> do
r <- c'edge_image_create e_ptr i_ptr
(fromIntegral hstep)
(fromIntegral vstep)
(fromIntegral hmargin)
(fromIntegral vmargin)
(fromIntegral bwidth)
(fromIntegral blength)
if r /= c'SUCCESS
then return NullEdge
else do
r <- c'edge_image_update e_ptr
if r /= c'SUCCESS
then return NullEdge
else ptrToEdgeImage i (fromJust e)
eValue :: Ptr CSChar -> Int -> Float
eValue p o = fromIntegral $ unsafePerformIO $ peek (advancePtr p o)
imageToVEdgeList :: Int -> Int -> Int -> C'pixel_image -> [[Edge]]
imageToVEdgeList step hmargin vmargin
C'pixel_image
{ c'pixel_image'data = d
, c'pixel_image'width = w
, c'pixel_image'height = h
, c'pixel_image'stride = s
} = [[toVEdge d (x,vmargin+y*step,y*(fromIntegral s)+x) | x <- [hmargin..(fromIntegral w)-hmargin-1]] | y <- [0..(fromIntegral h)-1]]
where
toVEdge ptr (x,y,offset) = (Edge x y VEdge $ eValue (castPtr ptr) offset)
imageToHEdgeList :: Int -> Int -> Int -> C'pixel_image -> [[Edge]]
imageToHEdgeList step hmargin vmargin
C'pixel_image
{ c'pixel_image'data = d
, c'pixel_image'width = w
, c'pixel_image'height = h
, c'pixel_image'stride = s
} = [[toHEdge d (hmargin+x*step,y,y*(fromIntegral s)+x) | y <- [vmargin..(fromIntegral h)-vmargin-1]] | x <- [0..(fromIntegral w)-1]]
where
toHEdge ptr (x,y,offset) = (Edge x y HEdge $ eValue (castPtr ptr) offset)
ptrToEdgeImage :: PixelImage -> ForeignPtr C'edge_image -> IO (EdgeImage)
ptrToEdgeImage i fptr = do
withForeignPtr fptr $ \ptr ->
if ptr == nullPtr then return NullEdge
else do
C'edge_image{
c'edge_image'hedges = ih,
c'edge_image'vedges = iv,
c'edge_image'width = w,
c'edge_image'height = h,
c'edge_image'hstep = hs,
c'edge_image'vstep = vs,
c'edge_image'hmargin = hm,
c'edge_image'vmargin = vm,
c'edge_image'box_width = bw,
c'edge_image'box_length = bl,
c'edge_image'dx = dx,
c'edge_image'dy = dy
} <- peek ptr
return $ (EdgeImage fptr i
(fromIntegral hs)
(fromIntegral vs)
(fromIntegral hm)
(fromIntegral vm)
(fromIntegral bw)
(fromIntegral bl)
(fromIntegral dx)
(fromIntegral dy)
(imageToHEdgeList (fromIntegral hs) (fromIntegral (dx+hm)) (fromIntegral (dy+vm)) ih)
(imageToVEdgeList (fromIntegral vs) (fromIntegral (dx+hm)) (fromIntegral (dy+vm)) iv))
|
amnipar/hs-cvsu
|
CVSU/Edges.hs
|
Haskell
|
bsd-3-clause
| 3,993
|
import Cookbook.Essential.IO
import Cookbook.Project.Preprocess.Preprocess
import Cookbook.Recipes.Sanitize
import Cookbook.Ingredients.Tupples.Look
import Cookbook.Essential.Continuous
import Cookbook.Ingredients.Lists.Modify
import Cookbook.Ingredients.Lists.Replace
import System.IO
import System.Environment
import System.Directory
getShortName :: String -> String
getShortName x = (rev (before (rev x) '/'))
main = do
(a:b:c:_) <- getArgs
ppFolder <- getHomePath "/.preprocess/"
files_ <- getDirectoryContents $ ppFolder
let files = blacklist files_ [".",".."]
allContents <- mapM filelines (map (ppFolder ++) files)
input <- filelines b
let appropriateParams = gPL (head $ lookList (zip (map getShortName files) allContents) a)
let translated = map ((flip replace) appropriateParams) input
writeFile c (unlines translated)
|
natepisarski/WriteUtils
|
preprocess.hs
|
Haskell
|
bsd-3-clause
| 856
|
{-# LANGUAGE RankNTypes, TypeOperators, DefaultSignatures #-}
-- | Compare to indexed.Control.Comonad.Indexed (IxComonad)
module MHask.Indexed.Comonad where
import MHask.Arrow
import qualified MHask.Indexed.Functor as MHask
import qualified MHask.Indexed.Duplicate as MHask
import qualified MHask.Indexed.Copointed as MHask
-- | Indexed version of "MHask.Comonad".
-- Dual of "MHask.Indexed.Monad"
--
-- Instances must satisfy the following law:
--
-- > iextract ~<~ iduplicate ≡ identityArrow
-- > imap iextract ~<~ iduplicate ≡ identityArrow
class (MHask.IxDuplicate t, MHask.IxCopointed t) => IxComonad t where
-- | Instances must satisfy the following law:
--
-- > iextend iextract ≡ identityArrow
iextend :: (Monad m, Monad n)
=> (m <~ t j k n) -> (t i j m <~ t i k n)
default iextend ::
(Monad m, Monad n,
Monad (t i j m), Monad (t j k n), Monad (t i k n),
Monad (t i j (t j k n)))
=> (m <~ t j k n) -> (t i j m <~ t i k n)
iextend f = MHask.imap f ~<~ MHask.iduplicate
-- | If you define your IxComonad in terms of iextend and iextract,
-- then you get a free implementation of imap which can
-- be used for IxFunctor.
imapComonad :: (Monad m, Monad n, Monad (t j j n), IxComonad t)
=> (m <~ n) -> (t i j m <~ t i j n)
imapComonad f = iextend (f ~<~ MHask.iextract)
iduplicateComonad :: (Monad m, Monad (t j k m), IxComonad t)
=> t i j (t j k m) <~ t i k m
iduplicateComonad = iextend identityArrow
|
DanBurton/MHask
|
MHask/Indexed/Comonad.hs
|
Haskell
|
bsd-3-clause
| 1,470
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE Safe #-}
module Data.Hexagon.LineDraw (lineDraw) where
import Control.Lens.Review
import Control.Lens.Getter
import Data.Hexagon.Distance
import Data.Hexagon.Types
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
lineDraw :: (HexCoordinate t a, Integral a) => t a -> t a -> Seq (t a)
lineDraw a b =
fmap (view _CoordinateIso) $
lineDrawCube (a ^. re _CoordinateCubeIso) (b ^. re _CoordinateCubeIso)
lineDrawCube :: (Integral t) =>
CubeCoordinate t -> CubeCoordinate t -> Seq (CubeCoordinate t)
lineDrawCube a b =
let n = (fromIntegral $ distance a b) :: Double
a' = fmap fromIntegral a
b' = fmap fromIntegral b
in fmap cubeRound . Seq.fromList $
[cubeLerp a' b' $ 1 / n * i | i <- [0..n]]
cubeLerp :: Num t => CubeCoordinate t -> CubeCoordinate t -> t -> CubeCoordinate t
cubeLerp a b t =
let x' = (a ^. cubeX + (b ^. cubeX - a ^. cubeX) * t)
y' = (a ^. cubeY + (b ^. cubeY - a ^. cubeY) * t)
z' = (a ^. cubeZ + (b ^. cubeZ - a ^. cubeZ) * t)
in _CubeCoordinate # (x', y', z')
--cubeRound' :: (Real a, Integral b) => CubeCoordinate a -> CubeCoordinate b
--cubeRound' = cubeRound . fmap (fromRational . toRational)
cubeRound :: (Integral b) => CubeCoordinate Double -> CubeCoordinate b
cubeRound h =
let r = fmap ((fromIntegral :: Integer -> Double) . round) h
diff = _CubeCoordinate # ( r ^. cubeX - h ^. cubeX
, r ^. cubeY - h ^. cubeY
, r ^. cubeZ - h ^. cubeZ
)
(rx,ry,rz) =
if ((diff ^. cubeX > diff ^. cubeY) &&
(diff ^. cubeX > diff ^. cubeZ))
then (-(r ^. cubeY)-(r ^. cubeZ), r ^. cubeY, r ^. cubeZ)
else if (diff ^. cubeY > diff ^. cubeZ)
then (r ^. cubeX, -(r ^. cubeX)-(r ^. cubeZ), r ^. cubeZ)
else (r ^. cubeX, r ^. cubeY, -(r ^. cubeX)-(r ^. cubeY))
in _CubeCoordinate # (round rx, round ry, round rz)
{-
function cube_round(h):
var rx = round(h.x)
var ry = round(h.y)
var rz = round(h.z)
var x_diff = abs(rx - h.x)
var y_diff = abs(ry - h.y)
var z_diff = abs(rz - h.z)
if x_diff > y_diff and x_diff > z_diff:
rx = -ry-rz
else if y_diff > z_diff:
ry = -rx-rz
else:
rz = -rx-ry
return Cube(rx, ry, rz)
-}
|
alios/hexagon
|
src/Data/Hexagon/LineDraw.hs
|
Haskell
|
bsd-3-clause
| 2,463
|
import qualified Data.ByteString.Char8 as BLC
import System.Environment (getArgs, getExecutablePath)
import qualified System.Log.Logger as L
import Control.Distributed.Task.TaskSpawning.DeployFullBinary
import Control.Distributed.Task.Types.TaskTypes
import Control.Distributed.Task.Util.Configuration
import Control.Distributed.Task.Util.Logging
import RemoteExecutable
main :: IO ()
main = do
args <- getArgs
case args of
[ioHandling] -> executeFunction (unpackIOHandling ioHandling)
_ -> error "Syntax for relinked task: <ioHandling>\n"
executeFunction :: IOHandling -> IO ()
executeFunction ioHandling = do
initTaskLogging
fullBinaryExecution ioHandling executeF
where
executeF :: Task
executeF = remoteExecutable
initTaskLogging :: IO ()
initTaskLogging = do
conf <- getConfiguration
initLogging L.ERROR L.INFO (_taskLogFile conf)
self <- getExecutablePath
logInfo $ "started task execution for: "++self
|
michaxm/task-distribution
|
object-code-app/RemoteExecutor.hs
|
Haskell
|
bsd-3-clause
| 946
|
{-# LANGUAGE CPP #-}
-- | Prelude replacement
-- Remember to import Prelude () if using this
module Util.Prelewd ( module Prelude
, module Control.Applicative
, module Control.Monad
, module Data.Bool
, module Data.Eq
, module Data.Foldable
, module Data.Function
, module Data.Int
, module Data.Maybe
, module Data.Monoid
, module Data.Ord
, module Data.Traversable
, module Data.Word
, Indeterminate (..)
, apmap
, ordEq
, mconcat
, minBy
, maxBy
, bool
, iff
, if'
, partition
, head
, last
, init
, tail
, deleteBy
, length
, div
, divMod
, mcast
, mcond
, ifm
, (!)
, (<&>)
, (.)
, (.^)
, (.$)
, ($$)
, null
, reverse
, intersperse
, intercalate
, transpose
, subsequences
, permutations
, foldl1'
, scanl
, scanl1
, scanr
, scanr1
, iterate
, repeat
, replicate
, cycle
, unfoldr
, take
, drop
, splitAt
, takeWhile
, dropWhile
, dropWhileEnd
, span
, break
, stripPrefix
, group
, isPrefixOf
, isSuffixOf
, isInfixOf
, lookup
, filter
, zip
, zipWith
, (++)
, unzip
, sequence
, sequence_
, onBoth
) where
import Prelude ( Int
, Integer
, Float
, Double
, Rational
, Enum (..)
, Bounded (..)
, Num (..)
, Real (..)
, Integral
, Fractional (..)
, Floating (..)
, RealFrac (..)
, RealFloat (..)
, quot
, rem
, mod
, quotRem
, toInteger
, subtract
, even, odd
, gcd
, lcm
, (^)
, (^^)
, fromIntegral
, realToFrac
, String
)
import Control.Applicative hiding (optional, some, many)
import Control.Monad hiding (mapM, mapM_, sequence, sequence_, msum, forM, forM_, forever, void)
import Data.Bool
import Data.Either
import Data.Eq
import Data.Fixed
import Data.Foldable hiding (concat, sequence_)
import Data.Function hiding (fix, (.))
import Data.List hiding (head, last, init, tail, partition, length, foldl, foldr, minimumBy, maximumBy, concat, deleteBy, foldr1, filter)
import Data.Int
import Data.Maybe
import Data.Monoid hiding (mconcat)
import Data.Ord
import Data.Traversable hiding (sequence)
import Data.Word
import Test.QuickCheck hiding (Fixed)
import Text.Show
import Util.Impure
#if __GLASGOW_HASKELL__ < 704
instance HasResolution a => Arbitrary (Fixed a) where
arbitrary = realToFrac <$> (arbitrary :: Gen Double)
#endif
-- | Objects with Infinity support
data Indeterminate a = Finite a
| Infinite
deriving (Show, Eq)
instance Ord a => Ord (Indeterminate a) where
compare (Finite _) Infinite = LT
compare Infinite Infinite = EQ
compare Infinite (Finite _) = GT
compare (Finite x) (Finite y) = compare x y
instance Monad Indeterminate where
return = Finite
Infinite >>= _ = Infinite
(Finite x) >>= f = f x
instance MonadPlus Indeterminate where
mzero = empty
mplus = (<|>)
instance Functor Indeterminate where
fmap = apmap
instance Applicative Indeterminate where
pure = return
(<*>) = ap
instance Alternative Indeterminate where
empty = Infinite
Infinite <|> x = x
x <|> _ = x
instance Arbitrary a => Arbitrary (Indeterminate a) where
arbitrary = maybe Infinite Finite <$> arbitrary
-- | Default fmap inmplementation for Monads
apmap :: Applicative f => (a -> b) -> f a -> f b
apmap = (<*>) . pure
-- | Default == implementation for Ords
ordEq :: Ord a => a -> a -> Bool
ordEq x y = compare x y == EQ
-- | Generalized `mconcat`
mconcat :: (Foldable t, Monoid m) => t m -> m
mconcat = foldr (<>) mempty
-- | `min` with user-supplied ordering
minBy :: (a -> a -> Ordering) -> a -> a -> a
minBy f x y = minimumBy f [x, y]
-- | `max` with user-supplied ordering
maxBy :: (a -> a -> Ordering) -> a -> a -> a
maxBy f x y = maximumBy f [x, y]
-- | Process conditionals in the same form as `maybe` and `either`
bool :: a -> a -> Bool -> a
bool f t b = iff b t f
-- | Function synonym for `if.. then.. else ..`
iff :: Bool -> a -> a -> a
iff b t f = if b then t else f
-- | Conditionally apply a transformation function
if' :: Bool -> (a -> a) -> a -> a
if' b f = f >>= iff b
-- | First element of a list
head :: [a] -> Maybe a
head = listToMaybe
-- | Last element of a finite list
last :: [a] -> Maybe a
last = Util.Prelewd.head . reverse
-- | All but the first element of a list
tail :: [a] -> Maybe [a]
tail [] = Nothing
tail (_:xs) = Just xs
-- | All but the last element of a list
init :: [a] -> Maybe [a]
init = Util.Prelewd.tail . reverse
-- | Find and remove the first occurance for which the supplied predicate is true
deleteBy :: (a -> Bool) -> [a] -> Maybe [a]
deleteBy _ [] = Nothing
deleteBy p (x:xs) = iff (p x) (Just xs) $ (x:) <$> deleteBy p xs
infixl 9 !
-- | `x ! i` is the `ith` element of `x`
(!) :: Foldable t => t a -> Integer -> a
(!) l n = case foldl (\v x -> v >>= go x) (Right n) l of
Left x -> x
Right i -> error $ "Foldable index too large by " ++ show (i + 1) ++ "."
where
go x 0 = Left x
go _ k = Right (k - 1)
-- | Split a list into a pair of lists
partition :: (a -> Either b c) -> [a] -> ([b], [c])
partition f = partitionEithers . fmap f
-- | Length of a foldable structure
-- O(n)
length :: (Integral i, Foldable t) => t a -> i
length = foldr (const (+1)) 0
-- | Division with integral result
div :: (Real a, Integral b) => a -> a -> Indeterminate b
div x y = mcond (y /= 0) $ div' x y
-- | `divMod a b = (div a b, mod a b)`
divMod :: (Real a, Integral b) => a -> a -> Indeterminate (b, a)
divMod x y = mcond (y /= 0) $ divMod' x y
-- | Interpret something as a monad
mcast :: MonadPlus m
=> (a -> Bool) -- ^ Casting function
-> a -- ^ Value to cast
-> m a -- ^ `return value` if cast succeeded, `mzero` otherwise
mcast = (mcond =<<)
-- | Conditionally create a monad
mcond :: MonadPlus m
=> Bool -- ^ If this condition is false, mzero.
-- Otherwise, return the value.
-> a -- ^ Value to make into a monad.
-> m a
mcond = ifm .^ return
-- | Conditionally nullify a monad
ifm :: MonadPlus m
=> Bool -- ^ If this condition is false, mzero.
-- Otherwise, return the monad.
-> m a -- ^ Monad to filter
-> m a
ifm = (>>) . guard
infixl 4 <&>
-- | `(<$>)` with arguments interchanged
(<&>) :: Functor f => f a -> (a -> b) -> f b
(<&>) = flip (<$>)
infixl 9 ., .^
infixl 8 .$, $$
-- | `(f . g) x = f (g x)`
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(.) = fmap
-- | `(f .$ g) x y = f x (g y)`
(.^) :: (a -> b -> c) -> (r -> b) -> a -> r -> c
(.^) f g x = f x . g
-- | Composition across two arguments
(.$) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(.$) = (.).(.)
-- | (f $$ g) x y = f x y $ g x y
($$) :: (x -> y -> a -> r) -> (x -> y -> a) -> x -> y -> r
($$) f g x = f x <*> g x
-- | Keep only elements which satisfy a predicate
filter :: MonadPlus m => (a -> Bool) -> m a -> m a
filter = mfilter
-- | Collect actions in a traversable structure
sequence :: (Traversable t, Applicative f) => t (f a) -> f (t a)
sequence = sequenceA
-- | Collect actions and discard results
sequence_ :: (Foldable t, Applicative f) => t (f a) -> f ()
sequence_ = sequenceA_
-- | Apply a function across both parameters only if both exist;
-- otherwise default to the extant one
onBoth :: Alternative f => (a -> a -> a) -> f a -> f a -> f a
onBoth f x y = (f <$> x <*> y) <|> x <|> y
|
cgaebel/GPG-Chat
|
src/Util/Prelewd.hs
|
Haskell
|
bsd-3-clause
| 9,213
|
{-# OPTIONS -Wall -Werror -cpp #-}
-- | POSIX time, if you need to deal with timestamps and the like.
-- Most people won't need this module.
module Data.Time.Clock.POSIX
(
posixDayLength,POSIXTime,posixSecondsToUTCTime,utcTimeToPOSIXSeconds,getPOSIXTime
) where
import Data.Time.Clock.UTC
import Data.Time.Calendar.Days
import Data.Fixed
import Control.Monad
#ifdef mingw32_HOST_OS
import Data.Word ( Word64)
import System.Win32.Time
#else
import Data.Time.Clock.CTimeval
#endif
-- | 86400 nominal seconds in every day
posixDayLength :: NominalDiffTime
posixDayLength = 86400
-- | POSIX time is the nominal time since 1970-01-01 00:00 UTC
type POSIXTime = NominalDiffTime
unixEpochDay :: Day
unixEpochDay = ModifiedJulianDay 40587
posixSecondsToUTCTime :: POSIXTime -> UTCTime
posixSecondsToUTCTime i = let
(d,t) = divMod' i posixDayLength
in UTCTime (addDays d unixEpochDay) (realToFrac t)
utcTimeToPOSIXSeconds :: UTCTime -> POSIXTime
utcTimeToPOSIXSeconds (UTCTime d t) =
(fromInteger (diffDays d unixEpochDay) * posixDayLength) + min posixDayLength (realToFrac t)
-- | Get the current POSIX time from the system clock.
getPOSIXTime :: IO POSIXTime
#ifdef mingw32_HOST_OS
-- On Windows, the equlvalent of POSIX time is "file time", defined as
-- the number of 100-nanosecond intervals that have elapsed since
-- 12:00 A.M. January 1, 1601 (UTC). We can convert this into a POSIX
-- time by adjusting the offset to be relative to the POSIX epoch.
getPOSIXTime = do
FILETIME ft <- System.Win32.Time.getSystemTimeAsFileTime
return (fromIntegral (ft - win32_epoch_adjust) / 10000000)
win32_epoch_adjust :: Word64
win32_epoch_adjust = 116444736000000000
#else
-- Use POSIX time
ctimevalToPosixSeconds :: CTimeval -> POSIXTime
ctimevalToPosixSeconds (MkCTimeval s mus) = (fromIntegral s) + (fromIntegral mus) / 1000000
getPOSIXTime = liftM ctimevalToPosixSeconds getCTimeval
#endif
|
FranklinChen/hugs98-plus-Sep2006
|
packages/time/Data/Time/Clock/POSIX.hs
|
Haskell
|
bsd-3-clause
| 1,904
|
{-
Copyright 2014 Google Inc. 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.
-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Language.C.Clang.Location
( SourceRange()
, rangeStart, rangeEnd
, SourceLocation()
, spellingLocation
, isInSystemHeader
, isFromMainFile
, Location(..)
)
where
import Language.C.Clang.Internal.FFI
import Language.C.Clang.Internal.Types
deriving instance Eq Location
deriving instance Show Location
|
chpatrick/clang-lens
|
src/Language/C/Clang/Location.hs
|
Haskell
|
apache-2.0
| 943
|
<?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="es-ES">
<title>Customizable HTML Report</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/customreport/src/main/javahelp/org/zaproxy/zap/extension/customreport/resources/help_es_ES/helpset_es_ES.hs
|
Haskell
|
apache-2.0
| 970
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Package
-- Copyright : Isaac Jones 2003-2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Defines a package identifier along with a parser and pretty printer for it.
-- 'PackageIdentifier's consist of a name and an exact version. It also defines
-- a 'Dependency' data type. A dependency is a package name and a version
-- range, like @\"foo >= 1.2 && < 2\"@.
module Distribution.Package (
-- * Package ids
PackageName(..),
PackageIdentifier(..),
PackageId,
-- * Package keys/installed package IDs (used for linker symbols)
ComponentId(..),
UnitId(..),
mkUnitId,
mkLegacyUnitId,
getHSLibraryName,
InstalledPackageId, -- backwards compat
-- * ABI hash
AbiHash(..),
-- * Package source dependencies
Dependency(..),
thisPackageVersion,
notThisPackageVersion,
simplifyDependency,
-- * Package classes
Package(..), packageName, packageVersion,
HasUnitId(..),
installedPackageId,
PackageInstalled(..),
) where
import Distribution.Version
( Version(..), VersionRange, anyVersion, thisVersion
, notThisVersion, simplifyVersionRange )
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import Distribution.Compat.ReadP
import Distribution.Compat.Binary
import Distribution.Text
import Control.DeepSeq (NFData(..))
import qualified Data.Char as Char
( isDigit, isAlphaNum, )
import Data.Data ( Data )
import Data.List ( intercalate )
import Data.Typeable ( Typeable )
import GHC.Generics (Generic)
import Text.PrettyPrint ((<>), (<+>), text)
newtype PackageName = PackageName { unPackageName :: String }
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data)
instance Binary PackageName
instance Text PackageName where
disp (PackageName n) = Disp.text n
parse = do
ns <- Parse.sepBy1 component (Parse.char '-')
return (PackageName (intercalate "-" ns))
where
component = do
cs <- Parse.munch1 Char.isAlphaNum
if all Char.isDigit cs then Parse.pfail else return cs
-- each component must contain an alphabetic character, to avoid
-- ambiguity in identifiers like foo-1 (the 1 is the version number).
instance NFData PackageName where
rnf (PackageName pkg) = rnf pkg
-- | Type alias so we can use the shorter name PackageId.
type PackageId = PackageIdentifier
-- | The name and version of a package.
data PackageIdentifier
= PackageIdentifier {
pkgName :: PackageName, -- ^The name of this package, eg. foo
pkgVersion :: Version -- ^the version of this package, eg 1.2
}
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data)
instance Binary PackageIdentifier
instance Text PackageIdentifier where
disp (PackageIdentifier n v) = case v of
Version [] _ -> disp n -- if no version, don't show version.
_ -> disp n <> Disp.char '-' <> disp v
parse = do
n <- parse
v <- (Parse.char '-' >> parse) <++ return (Version [] [])
return (PackageIdentifier n v)
instance NFData PackageIdentifier where
rnf (PackageIdentifier name version) = rnf name `seq` rnf version
-- ------------------------------------------------------------
-- * Component Source Hash
-- ------------------------------------------------------------
-- | A 'ComponentId' uniquely identifies the transitive source
-- code closure of a component. For non-Backpack components, it also
-- serves as the basis for install paths, symbols, etc.
--
data ComponentId
= ComponentId String
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data)
{-# DEPRECATED InstalledPackageId "Use UnitId instead" #-}
type InstalledPackageId = UnitId
instance Binary ComponentId
instance Text ComponentId where
disp (ComponentId str) = text str
parse = ComponentId `fmap` Parse.munch1 abi_char
where abi_char c = Char.isAlphaNum c || c `elem` "-_."
instance NFData ComponentId where
rnf (ComponentId pk) = rnf pk
-- | Returns library name prefixed with HS, suitable for filenames
getHSLibraryName :: UnitId -> String
getHSLibraryName (SimpleUnitId (ComponentId s)) = "HS" ++ s
-- | For now, there is no distinction between component IDs
-- and unit IDs in Cabal.
newtype UnitId = SimpleUnitId ComponentId
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data, Binary, Text, NFData)
-- | Makes a simple-style UnitId from a string.
mkUnitId :: String -> UnitId
mkUnitId = SimpleUnitId . ComponentId
-- | Make an old-style UnitId from a package identifier
mkLegacyUnitId :: PackageId -> UnitId
mkLegacyUnitId = SimpleUnitId . ComponentId . display
-- ------------------------------------------------------------
-- * Package source dependencies
-- ------------------------------------------------------------
-- | Describes a dependency on a source package (API)
--
data Dependency = Dependency PackageName VersionRange
deriving (Generic, Read, Show, Eq, Typeable, Data)
instance Binary Dependency
instance Text Dependency where
disp (Dependency name ver) =
disp name <+> disp ver
parse = do name <- parse
Parse.skipSpaces
ver <- parse <++ return anyVersion
Parse.skipSpaces
return (Dependency name ver)
thisPackageVersion :: PackageIdentifier -> Dependency
thisPackageVersion (PackageIdentifier n v) =
Dependency n (thisVersion v)
notThisPackageVersion :: PackageIdentifier -> Dependency
notThisPackageVersion (PackageIdentifier n v) =
Dependency n (notThisVersion v)
-- | Simplify the 'VersionRange' expression in a 'Dependency'.
-- See 'simplifyVersionRange'.
--
simplifyDependency :: Dependency -> Dependency
simplifyDependency (Dependency name range) =
Dependency name (simplifyVersionRange range)
-- | Class of things that have a 'PackageIdentifier'
--
-- Types in this class are all notions of a package. This allows us to have
-- different types for the different phases that packages go though, from
-- simple name\/id, package description, configured or installed packages.
--
-- Not all kinds of packages can be uniquely identified by a
-- 'PackageIdentifier'. In particular, installed packages cannot, there may be
-- many installed instances of the same source package.
--
class Package pkg where
packageId :: pkg -> PackageIdentifier
packageName :: Package pkg => pkg -> PackageName
packageName = pkgName . packageId
packageVersion :: Package pkg => pkg -> Version
packageVersion = pkgVersion . packageId
instance Package PackageIdentifier where
packageId = id
-- | Packages that have an installed package ID
class Package pkg => HasUnitId pkg where
installedUnitId :: pkg -> UnitId
{-# DEPRECATED installedPackageId "Use installedUnitId instead" #-}
-- | Compatibility wrapper for pre-Cabal 1.23.
installedPackageId :: HasUnitId pkg => pkg -> UnitId
installedPackageId = installedUnitId
-- | Class of installed packages.
--
-- The primary data type which is an instance of this package is
-- 'InstalledPackageInfo', but when we are doing install plans in Cabal install
-- we may have other, installed package-like things which contain more metadata.
-- Installed packages have exact dependencies 'installedDepends'.
class (HasUnitId pkg) => PackageInstalled pkg where
installedDepends :: pkg -> [UnitId]
-- -----------------------------------------------------------------------------
-- ABI hash
newtype AbiHash = AbiHash String
deriving (Eq, Show, Read, Generic)
instance Binary AbiHash
instance Text AbiHash where
disp (AbiHash abi) = Disp.text abi
parse = fmap AbiHash (Parse.munch Char.isAlphaNum)
|
edsko/cabal
|
Cabal/src/Distribution/Package.hs
|
Haskell
|
bsd-3-clause
| 7,999
|
module Servant.Swagger.Internal.TypeLevel (
module Servant.Swagger.Internal.TypeLevel.API,
module Servant.Swagger.Internal.TypeLevel.Every,
module Servant.Swagger.Internal.TypeLevel.TMap,
) where
import Servant.Swagger.Internal.TypeLevel.API
import Servant.Swagger.Internal.TypeLevel.Every
import Servant.Swagger.Internal.TypeLevel.TMap
|
dmjio/servant-swagger
|
src/Servant/Swagger/Internal/TypeLevel.hs
|
Haskell
|
bsd-3-clause
| 374
|
{-# LANGUAGE ScopedTypeVariables, TemplateHaskell #-}
module Main where
--------------------------------------------------------------------------
-- imports
import Test.QuickCheck
import Text.Show.Functions
import Data.List
( sort
, group
, nub
, (\\)
)
import Control.Monad
( liftM
, liftM2
)
import Data.Maybe
--import Text.Show.Functions
--------------------------------------------------------------------------
-- binary search trees
data Set a
= Node a (Set a) (Set a)
| Empty
deriving ( Eq, Ord, Show )
empty :: Set a
empty = Empty
isEmpty :: Set a -> Bool
isEmpty Empty = True
isEmpty _ = False
unit :: a -> Set a
unit x = Node x empty empty
size :: Set a -> Int
size Empty = 0
size (Node _ s1 s2) = 1 + size s1 + size s2
insert :: Ord a => a -> Set a -> Set a
insert x s = s `union` unit x
merge :: Set a -> Set a -> Set a
s `merge` Empty = s
s `merge` Node x Empty s2 = Node x s s2
s `merge` Node x (Node y s11 s12) s2 = Node y s (Node x (s11 `merge` s12) s2)
delete :: Ord a => a -> Set a -> Set a
delete x Empty = Empty
delete x (Node x' s1 s2) =
case x `compare` x' of
LT -> Node x' (delete x s1) s2
EQ -> s1 `merge` s2
GT -> Node x' s1 (delete x s2)
union :: Ord a => Set a -> Set a -> Set a
{-
s1 `union` Empty = s1
Empty `union` s2 = s2
s1@(Node x s11 s12) `union` s2@(Node y s21 s22) =
case x `compare` y of
LT -> Node x s11 (s12 `union` Node y Empty s22) `union` s21
EQ -> Node x (s11 `union` s21) (s12 `union` s22)
--GT -> s11 `union` Node y s21 (Node x Empty s12 `union` s22)
GT -> Node x (s11 `union` Node y s21 Empty) s12 `union` s22
-}
s1 `union` Empty = s1
Empty `union` s2 = s2
Node x s11 s12 `union` s2 = Node x (s11 `union` s21) (s12 `union` s22)
where
(s21,s22) = split x s2
split :: Ord a => a -> Set a -> (Set a, Set a)
split x Empty = (Empty, Empty)
split x (Node y s1 s2) =
case x `compare` y of
LT -> (s11, Node y s12 s2)
EQ -> (s1, s2)
GT -> (Node y s1 s21, s22)
where
(s11,s12) = split x s1
(s21,s22) = split x s2
mapp :: (a -> b) -> Set a -> Set b
mapp f Empty = Empty
mapp f (Node x s1 s2) = Node (f x) (mapp f s1) (mapp f s2)
fromList :: Ord a => [a] -> Set a
--fromList xs = build [ (empty,x) | x <- sort xs ]
fromList xs = build [ (empty,head x) | x <- group (sort xs) ]
where
build [] = empty
build [(s,x)] = attach x s
build sxs = build (sweep sxs)
sweep [] = []
sweep [sx] = [sx]
sweep ((s1,x1):(s2,x2):sxs) = (Node x1 s1 s2,x2) : sweep sxs
attach x Empty = unit x
attach x (Node y s1 s2) = Node y s1 (attach x s2)
toList :: Set a -> [a]
toList s = toSortedList s
toSortedList :: Set a -> [a]
toSortedList s = toList' s []
where
toList' Empty xs = xs
toList' (Node x s1 s2) xs = toList' s1 (x : toList' s2 xs)
--------------------------------------------------------------------------
-- generators
instance (Ord a, Arbitrary a) => Arbitrary (Set a) where
arbitrary = sized (arbSet Nothing Nothing)
where
arbSet mx my n =
frequency $
[ (1, return Empty) ] ++
[ (7, do mz <- arbitrary `suchThatMaybe` (isOK mx my)
case mz of
Nothing -> return Empty
Just z -> liftM2 (Node z) (arbSet mx mz n2)
(arbSet mz my n2)
where n2 = n `div` 2)
| n > 0
]
isOK mx my z =
maybe True (<z) mx && maybe True (z<) my
shrink Empty = []
shrink t@(Node x s1 s2) = [ s1, s2 ]
++ [ t' | x' <- shrink x, let t' = Node x' s1 s2, invariant t' ]
-- instance (Ord a, ShrinkSub a) => ShrinkSub (Set a)
--------------------------------------------------------------------------
-- properties
(.<) :: Ord a => Set a -> a -> Bool
Empty .< x = True
Node y _ s .< x = y < x && s .< x
(<.) :: Ord a => a -> Set a -> Bool
x <. Empty = True
x <. Node y _ s = x < y && x <. s
(==?) :: Ord a => Set a -> [a] -> Bool
s ==? xs = invariant s && sort (toList s) == nub (sort xs)
invariant :: Ord a => Set a -> Bool
invariant Empty = True
invariant (Node x s1 s2) = s1 .< x && x <. s2 && invariant s1 && invariant s2
prop_Invariant (s :: Set Int) =
invariant s
prop_Empty =
empty ==? ([] :: [Int])
prop_Unit (x :: Int) =
unit x ==? [x]
prop_Size (s :: Set Int) =
cover (size s >= 15) 60 "large" $
size s == length (toList s)
prop_Insert x (s :: Set Int) =
insert x s ==? (x : toList s)
prop_Delete x (s :: Set Int) =
delete x s ==? (toList s \\ [x])
prop_Union s1 (s2 :: Set Int) =
(s1 `union` s2) ==? (toList s1 ++ toList s2)
prop_Mapp (f :: Int -> Int) (s :: Set Int) =
expectFailure $
whenFail (putStrLn ("Fun: " ++ show [ (x,f x) | x <- toList s])) $
mapp f s ==? map f (toList s)
prop_FromList (xs :: [Int]) =
fromList xs ==? xs
prop_ToSortedList (s :: Set Int) =
s ==? xs && xs == sort xs
where
xs = toSortedList s
-- whenFail (putStrLn ("Result: " ++ show (fromList xs))) $
prop_FromList' (xs :: [Int]) =
shrinking shrink xs $ \xs' ->
fromList xs ==? xs
--------------------------------------------------------------------------
-- main
main =
do quickCheck prop_Invariant
quickCheck prop_Empty
quickCheck prop_Unit
quickCheck prop_Size
quickCheck prop_Insert
quickCheck prop_Delete
quickCheck prop_Union
quickCheck prop_Mapp
quickCheck prop_FromList
quickCheck prop_ToSortedList
--------------------------------------------------------------------------
-- the end.
|
nh2/quickcheck
|
examples/Set.hs
|
Haskell
|
bsd-3-clause
| 5,702
|
--
-- (c) The University of Glasgow
--
{-# LANGUAGE DeriveDataTypeable #-}
module Avail (
Avails,
AvailInfo(..),
availsToNameSet,
availsToNameSetWithSelectors,
availsToNameEnv,
availName, availNames, availNonFldNames,
availNamesWithSelectors,
availFlds,
stableAvailCmp
) where
import Name
import NameEnv
import NameSet
import FieldLabel
import Binary
import Outputable
import Util
import Data.Function
-- -----------------------------------------------------------------------------
-- The AvailInfo type
-- | Records what things are "available", i.e. in scope
data AvailInfo = Avail Name -- ^ An ordinary identifier in scope
| AvailTC Name
[Name]
[FieldLabel]
-- ^ A type or class in scope. Parameters:
--
-- 1) The name of the type or class
-- 2) The available pieces of type or class,
-- excluding field selectors.
-- 3) The record fields of the type
-- (see Note [Representing fields in AvailInfo]).
--
-- The AvailTC Invariant:
-- * If the type or class is itself
-- to be in scope, it must be
-- *first* in this list. Thus,
-- typically: @AvailTC Eq [Eq, ==, \/=]@
deriving( Eq )
-- Equality used when deciding if the
-- interface has changed
-- | A collection of 'AvailInfo' - several things that are \"available\"
type Avails = [AvailInfo]
{-
Note [Representing fields in AvailInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When -XDuplicateRecordFields is disabled (the normal case), a
datatype like
data T = MkT { foo :: Int }
gives rise to the AvailInfo
AvailTC T [T, MkT] [FieldLabel "foo" False foo],
whereas if -XDuplicateRecordFields is enabled it gives
AvailTC T [T, MkT] [FieldLabel "foo" True $sel:foo:MkT]
since the label does not match the selector name.
The labels in a field list are not necessarily unique:
data families allow the same parent (the family tycon) to have
multiple distinct fields with the same label. For example,
data family F a
data instance F Int = MkFInt { foo :: Int }
data instance F Bool = MkFBool { foo :: Bool}
gives rise to
AvailTC F [F, MkFInt, MkFBool]
[FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" True $sel:foo:MkFBool].
Moreover, note that the flIsOverloaded flag need not be the same for
all the elements of the list. In the example above, this occurs if
the two data instances are defined in different modules, one with
`-XDuplicateRecordFields` enabled and one with it disabled. Thus it
is possible to have
AvailTC F [F, MkFInt, MkFBool]
[FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" False foo].
If the two data instances are defined in different modules, both
without `-XDuplicateRecordFields`, it will be impossible to export
them from the same module (even with `-XDuplicateRecordfields`
enabled), because they would be represented identically. The
workaround here is to enable `-XDuplicateRecordFields` on the defining
modules.
-}
-- | Compare lexicographically
stableAvailCmp :: AvailInfo -> AvailInfo -> Ordering
stableAvailCmp (Avail n1) (Avail n2) = n1 `stableNameCmp` n2
stableAvailCmp (Avail {}) (AvailTC {}) = LT
stableAvailCmp (AvailTC n ns nfs) (AvailTC m ms mfs) =
(n `stableNameCmp` m) `thenCmp`
(cmpList stableNameCmp ns ms) `thenCmp`
(cmpList (stableNameCmp `on` flSelector) nfs mfs)
stableAvailCmp (AvailTC {}) (Avail {}) = GT
-- -----------------------------------------------------------------------------
-- Operations on AvailInfo
availsToNameSet :: [AvailInfo] -> NameSet
availsToNameSet avails = foldr add emptyNameSet avails
where add avail set = extendNameSetList set (availNames avail)
availsToNameSetWithSelectors :: [AvailInfo] -> NameSet
availsToNameSetWithSelectors avails = foldr add emptyNameSet avails
where add avail set = extendNameSetList set (availNamesWithSelectors avail)
availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
availsToNameEnv avails = foldr add emptyNameEnv avails
where add avail env = extendNameEnvList env
(zip (availNames avail) (repeat avail))
-- | Just the main name made available, i.e. not the available pieces
-- of type or class brought into scope by the 'GenAvailInfo'
availName :: AvailInfo -> Name
availName (Avail n) = n
availName (AvailTC n _ _) = n
-- | All names made available by the availability information (excluding overloaded selectors)
availNames :: AvailInfo -> [Name]
availNames (Avail n) = [n]
availNames (AvailTC _ ns fs) = ns ++ [ flSelector f | f <- fs, not (flIsOverloaded f) ]
-- | All names made available by the availability information (including overloaded selectors)
availNamesWithSelectors :: AvailInfo -> [Name]
availNamesWithSelectors (Avail n) = [n]
availNamesWithSelectors (AvailTC _ ns fs) = ns ++ map flSelector fs
-- | Names for non-fields made available by the availability information
availNonFldNames :: AvailInfo -> [Name]
availNonFldNames (Avail n) = [n]
availNonFldNames (AvailTC _ ns _) = ns
-- | Fields made available by the availability information
availFlds :: AvailInfo -> [FieldLabel]
availFlds (AvailTC _ _ fs) = fs
availFlds _ = []
-- -----------------------------------------------------------------------------
-- Printing
instance Outputable AvailInfo where
ppr = pprAvail
pprAvail :: AvailInfo -> SDoc
pprAvail (Avail n) = ppr n
pprAvail (AvailTC n ns fs) = ppr n <> braces (hsep (punctuate comma (map ppr ns ++ map (ppr . flLabel) fs)))
instance Binary AvailInfo where
put_ bh (Avail aa) = do
putByte bh 0
put_ bh aa
put_ bh (AvailTC ab ac ad) = do
putByte bh 1
put_ bh ab
put_ bh ac
put_ bh ad
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
return (Avail aa)
_ -> do ab <- get bh
ac <- get bh
ad <- get bh
return (AvailTC ab ac ad)
|
AlexanderPankiv/ghc
|
compiler/basicTypes/Avail.hs
|
Haskell
|
bsd-3-clause
| 6,603
|
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
module TcRnExports (tcRnExports) where
import HsSyn
import PrelNames
import RdrName
import TcRnMonad
import TcEnv
import TcMType
import TcType
import RnNames
import RnEnv
import ErrUtils
import Id
import IdInfo
import Module
import Name
import NameEnv
import NameSet
import Avail
import TyCon
import SrcLoc
import HscTypes
import Outputable
import ConLike
import DataCon
import PatSyn
import FastString
import Maybes
import qualified GHC.LanguageExtensions as LangExt
import Util (capitalise)
import Control.Monad
import DynFlags
import RnHsDoc ( rnHsDoc )
import RdrHsSyn ( setRdrNameSpace )
import Data.Either ( partitionEithers )
{-
************************************************************************
* *
\subsection{Export list processing}
* *
************************************************************************
Processing the export list.
You might think that we should record things that appear in the export
list as ``occurrences'' (using @addOccurrenceName@), but you'd be
wrong. We do check (here) that they are in scope, but there is no
need to slurp in their actual declaration (which is what
@addOccurrenceName@ forces).
Indeed, doing so would big trouble when compiling @PrelBase@, because
it re-exports @GHC@, which includes @takeMVar#@, whose type includes
@ConcBase.StateAndSynchVar#@, and so on...
Note [Exports of data families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose you see (Trac #5306)
module M where
import X( F )
data instance F Int = FInt
What does M export? AvailTC F [FInt]
or AvailTC F [F,FInt]?
The former is strictly right because F isn't defined in this module.
But then you can never do an explicit import of M, thus
import M( F( FInt ) )
because F isn't exported by M. Nor can you import FInt alone from here
import M( FInt )
because we don't have syntax to support that. (It looks like an import of
the type FInt.)
At one point I implemented a compromise:
* When constructing exports with no export list, or with module M(
module M ), we add the parent to the exports as well.
* But not when you see module M( f ), even if f is a
class method with a parent.
* Nor when you see module M( module N ), with N /= M.
But the compromise seemed too much of a hack, so we backed it out.
You just have to use an explicit export list:
module M( F(..) ) where ...
-}
data ExportAccum -- The type of the accumulating parameter of
-- the main worker function in rnExports
= ExportAccum
[LIE Name] -- Export items with Names
ExportOccMap -- Tracks exported occurrence names
[AvailInfo] -- The accumulated exported stuff
-- Not nub'd!
emptyExportAccum :: ExportAccum
emptyExportAccum = ExportAccum [] emptyOccEnv []
type ExportOccMap = OccEnv (Name, IE RdrName)
-- Tracks what a particular exported OccName
-- in an export list refers to, and which item
-- it came from. It's illegal to export two distinct things
-- that have the same occurrence name
tcRnExports :: Bool -- False => no 'module M(..) where' header at all
-> Maybe (Located [LIE RdrName]) -- Nothing => no explicit export list
-> TcGblEnv
-> RnM TcGblEnv
-- Complains if two distinct exports have same OccName
-- Warns about identical exports.
-- Complains about exports items not in scope
tcRnExports explicit_mod exports
tcg_env@TcGblEnv { tcg_mod = this_mod,
tcg_rdr_env = rdr_env,
tcg_imports = imports }
= unsetWOptM Opt_WarnWarningsDeprecations $
-- Do not report deprecations arising from the export
-- list, to avoid bleating about re-exporting a deprecated
-- thing (especially via 'module Foo' export item)
do {
-- If the module header is omitted altogether, then behave
-- as if the user had written "module Main(main) where..."
-- EXCEPT in interactive mode, when we behave as if he had
-- written "module Main where ..."
-- Reason: don't want to complain about 'main' not in scope
-- in interactive mode
; dflags <- getDynFlags
; let real_exports
| explicit_mod = exports
| ghcLink dflags == LinkInMemory = Nothing
| otherwise
= Just (noLoc [noLoc (IEVar (noLoc main_RDR_Unqual))])
-- ToDo: the 'noLoc' here is unhelpful if 'main'
-- turns out to be out of scope
; (rn_exports, final_avails)
<- exports_from_avail real_exports rdr_env imports this_mod
; let final_ns = availsToNameSetWithSelectors final_avails
; traceRn "rnExports: Exports:" (ppr final_avails)
; let new_tcg_env =
tcg_env { tcg_exports = final_avails,
tcg_rn_exports = case tcg_rn_exports tcg_env of
Nothing -> Nothing
Just _ -> rn_exports,
tcg_dus = tcg_dus tcg_env `plusDU`
usesOnly final_ns }
; failIfErrsM
; return new_tcg_env }
exports_from_avail :: Maybe (Located [LIE RdrName])
-- Nothing => no explicit export list
-> GlobalRdrEnv
-> ImportAvails
-> Module
-> RnM (Maybe [LIE Name], [AvailInfo])
exports_from_avail Nothing rdr_env _imports _this_mod
-- The same as (module M) where M is the current module name,
-- so that's how we handle it, except we also export the data family
-- when a data instance is exported.
= let avails =
map fix_faminst . gresToAvailInfo
. filter isLocalGRE . globalRdrEnvElts $ rdr_env
in return (Nothing, avails)
where
-- #11164: when we define a data instance
-- but not data family, re-export the family
-- Even though we don't check whether this is actually a data family
-- only data families can locally define subordinate things (`ns` here)
-- without locally defining (and instead importing) the parent (`n`)
fix_faminst (AvailTC n ns flds) =
let new_ns =
case ns of
[] -> [n]
(p:_) -> if p == n then ns else n:ns
in AvailTC n new_ns flds
fix_faminst avail = avail
exports_from_avail (Just (L _ rdr_items)) rdr_env imports this_mod
= do ExportAccum ie_names _ exports
<- checkNoErrs $ foldAndRecoverM do_litem emptyExportAccum rdr_items
let final_exports = nubAvails exports -- Combine families
return (Just ie_names, final_exports)
where
do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
-- Maps a parent to its in-scope children
kids_env :: NameEnv [GlobalRdrElt]
kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
imported_modules = [ imv_name imv
| xs <- moduleEnvElts $ imp_mods imports, imv <- xs ]
exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
exports_from_item acc@(ExportAccum ie_names occs exports)
(L loc (IEModuleContents (L lm mod)))
| let earlier_mods = [ mod
| (L _ (IEModuleContents (L _ mod))) <- ie_names ]
, mod `elem` earlier_mods -- Duplicate export of M
= do { warnIf (Reason Opt_WarnDuplicateExports) True
(dupModuleExport mod) ;
return acc }
| otherwise
= do { let { exportValid = (mod `elem` imported_modules)
|| (moduleName this_mod == mod)
; gre_prs = pickGREsModExp mod (globalRdrEnvElts rdr_env)
; new_exports = map (availFromGRE . fst) gre_prs
; names = map (gre_name . fst) gre_prs
; all_gres = foldr (\(gre1,gre2) gres -> gre1 : gre2 : gres) [] gre_prs
}
; checkErr exportValid (moduleNotImported mod)
; warnIf (Reason Opt_WarnDodgyExports)
(exportValid && null gre_prs)
(nullModuleExport mod)
; traceRn "efa" (ppr mod $$ ppr all_gres)
; addUsedGREs all_gres
; occs' <- check_occs (IEModuleContents (noLoc mod)) occs names
-- This check_occs not only finds conflicts
-- between this item and others, but also
-- internally within this item. That is, if
-- 'M.x' is in scope in several ways, we'll have
-- several members of mod_avails with the same
-- OccName.
; traceRn "export_mod"
(vcat [ ppr mod
, ppr new_exports ])
; return (ExportAccum (L loc (IEModuleContents (L lm mod)) : ie_names)
occs'
(new_exports ++ exports)) }
exports_from_item acc@(ExportAccum lie_names occs exports) (L loc ie)
| isDoc ie
= do new_ie <- lookup_doc_ie ie
return (ExportAccum (L loc new_ie : lie_names) occs exports)
| otherwise
= do (new_ie, avail) <-
setSrcSpan loc $ lookup_ie ie
if isUnboundName (ieName new_ie)
then return acc -- Avoid error cascade
else do
occs' <- check_occs ie occs (availNames avail)
return (ExportAccum (L loc new_ie : lie_names) occs' (avail : exports))
-------------
lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
lookup_ie (IEVar (L l rdr))
= do (name, avail) <- lookupGreAvailRn rdr
return (IEVar (L l name), avail)
lookup_ie (IEThingAbs (L l rdr))
= do (name, avail) <- lookupGreAvailRn rdr
return (IEThingAbs (L l name), avail)
lookup_ie ie@(IEThingAll n)
= do
(n, avail, flds) <- lookup_ie_all ie n
let name = unLoc n
return (IEThingAll n, AvailTC name (name:avail) flds)
lookup_ie ie@(IEThingWith l wc sub_rdrs _)
= do
(lname, subs, avails, flds)
<- addExportErrCtxt ie $ lookup_ie_with l sub_rdrs
(_, all_avail, all_flds) <-
case wc of
NoIEWildcard -> return (lname, [], [])
IEWildcard _ -> lookup_ie_all ie l
let name = unLoc lname
return (IEThingWith lname wc subs (map noLoc (flds ++ all_flds)),
AvailTC name (name : avails ++ all_avail)
(flds ++ all_flds))
lookup_ie _ = panic "lookup_ie" -- Other cases covered earlier
lookup_ie_with :: Located RdrName -> [Located RdrName]
-> RnM (Located Name, [Located Name], [Name], [FieldLabel])
lookup_ie_with (L l rdr) sub_rdrs
= do name <- lookupGlobalOccRn rdr
(non_flds, flds) <- lookupChildrenExport name sub_rdrs
if isUnboundName name
then return (L l name, [], [name], [])
else return (L l name, non_flds
, map unLoc non_flds
, map unLoc flds)
lookup_ie_all :: IE RdrName -> Located RdrName
-> RnM (Located Name, [Name], [FieldLabel])
lookup_ie_all ie (L l rdr) =
do name <- lookupGlobalOccRn rdr
let gres = findChildren kids_env name
(non_flds, flds) = classifyGREs gres
addUsedKids rdr gres
warnDodgyExports <- woptM Opt_WarnDodgyExports
when (null gres) $
if isTyConName name
then when warnDodgyExports $
addWarn (Reason Opt_WarnDodgyExports)
(dodgyExportWarn name)
else -- This occurs when you export T(..), but
-- only import T abstractly, or T is a synonym.
addErr (exportItemErr ie)
return (L l name, non_flds, flds)
-------------
lookup_doc_ie :: IE RdrName -> RnM (IE Name)
lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
return (IEGroup lev rn_doc)
lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
return (IEDoc rn_doc)
lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
lookup_doc_ie _ = panic "lookup_doc_ie" -- Other cases covered earlier
-- In an export item M.T(A,B,C), we want to treat the uses of
-- A,B,C as if they were M.A, M.B, M.C
-- Happily pickGREs does just the right thing
addUsedKids :: RdrName -> [GlobalRdrElt] -> RnM ()
addUsedKids parent_rdr kid_gres = addUsedGREs (pickGREs parent_rdr kid_gres)
classifyGREs :: [GlobalRdrElt] -> ([Name], [FieldLabel])
classifyGREs = partitionEithers . map classifyGRE
classifyGRE :: GlobalRdrElt -> Either Name FieldLabel
classifyGRE gre = case gre_par gre of
FldParent _ Nothing -> Right (FieldLabel (occNameFS (nameOccName n)) False n)
FldParent _ (Just lbl) -> Right (FieldLabel lbl True n)
_ -> Left n
where
n = gre_name gre
isDoc :: IE RdrName -> Bool
isDoc (IEDoc _) = True
isDoc (IEDocNamed _) = True
isDoc (IEGroup _ _) = True
isDoc _ = False
-- Renaming and typechecking of exports happens after everything else has
-- been typechecked.
-- Renaming exports lists is a minefield. Five different things can appear in
-- children export lists ( T(A, B, C) ).
-- 1. Record selectors
-- 2. Type constructors
-- 3. Data constructors
-- 4. Pattern Synonyms
-- 5. Pattern Synonym Selectors
--
-- However, things get put into weird name spaces.
-- 1. Some type constructors are parsed as variables (-.->) for example.
-- 2. All data constructors are parsed as type constructors
-- 3. When there is ambiguity, we default type constructors to data
-- constructors and require the explicit `type` keyword for type
-- constructors.
--
-- This function first establishes the possible namespaces that an
-- identifier might be in (`choosePossibleNameSpaces`).
--
-- Then for each namespace in turn, tries to find the correct identifier
-- there returning the first positive result or the first terminating
-- error.
--
-- Records the result of looking up a child.
data ChildLookupResult
= NameNotFound -- We couldn't find a suitable name
| NameErr ErrMsg -- We found an unambiguous name
-- but there's another error
-- we should abort from
| FoundName Name -- We resolved to a normal name
| FoundFL FieldLabel -- We resolved to a FL
instance Outputable ChildLookupResult where
ppr NameNotFound = text "NameNotFound"
ppr (FoundName n) = text "Found:" <+> ppr n
ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls
ppr (NameErr _) = text "Error"
-- Left biased accumulation monoid. Chooses the left-most positive occurence.
instance Monoid ChildLookupResult where
mempty = NameNotFound
NameNotFound `mappend` m2 = m2
NameErr m `mappend` _ = NameErr m -- Abort from the first error
FoundName n1 `mappend` _ = FoundName n1
FoundFL fls `mappend` _ = FoundFL fls
lookupChildrenExport :: Name -> [Located RdrName]
-> RnM ([Located Name], [Located FieldLabel])
lookupChildrenExport parent rdr_items =
do
xs <- mapAndReportM doOne rdr_items
return $ partitionEithers xs
where
-- Pick out the possible namespaces in order of priority
-- This is a consequence of how the parser parses all
-- data constructors as type constructors.
choosePossibleNamespaces :: NameSpace -> [NameSpace]
choosePossibleNamespaces ns
| ns == varName = [varName, tcName]
| ns == tcName = [dataName, tcName]
| otherwise = [ns]
-- Process an individual child
doOne :: Located RdrName
-> RnM (Either (Located Name) (Located FieldLabel))
doOne n = do
let bareName = unLoc n
lkup v = lookupExportChild parent (setRdrNameSpace bareName v)
name <- fmap mconcat . mapM lkup $
(choosePossibleNamespaces (rdrNameSpace bareName))
-- Default to data constructors for slightly better error
-- messages
let unboundName :: RdrName
unboundName = if rdrNameSpace bareName == varName
then bareName
else setRdrNameSpace bareName dataName
case name of
NameNotFound -> Left . L (getLoc n) <$> reportUnboundName unboundName
FoundFL fls -> return $ Right (L (getLoc n) fls)
FoundName name -> return $ Left (L (getLoc n) name)
NameErr err_msg -> reportError err_msg >> failM
-- | Also captures the current context
mkNameErr :: SDoc -> TcM ChildLookupResult
mkNameErr errMsg = do
tcinit <- tcInitTidyEnv
NameErr <$> mkErrTcM (tcinit, errMsg)
-- | Used in export lists to lookup the children.
lookupExportChild :: Name -> RdrName -> RnM ChildLookupResult
lookupExportChild parent rdr_name
| isUnboundName parent
-- Avoid an error cascade
= return (FoundName (mkUnboundNameRdr rdr_name))
| otherwise = do
gre_env <- getGlobalRdrEnv
let original_gres = lookupGRE_RdrName rdr_name gre_env
-- Disambiguate the lookup based on the parent information.
-- The remaining GREs are things that we *could* export here, note that
-- this includes things which have `NoParent`. Those are sorted in
-- `checkPatSynParent`.
traceRn "lookupExportChild original_gres:" (ppr original_gres)
case picked_gres original_gres of
NoOccurence ->
noMatchingParentErr original_gres
UniqueOccurence g ->
checkPatSynParent parent (gre_name g)
DisambiguatedOccurence g ->
checkFld g
AmbiguousOccurence gres ->
mkNameClashErr gres
where
-- Convert into FieldLabel if necessary
checkFld :: GlobalRdrElt -> RnM ChildLookupResult
checkFld g@GRE{gre_name, gre_par} = do
addUsedGRE True g
return $ case gre_par of
FldParent _ mfs -> do
FoundFL (fldParentToFieldLabel gre_name mfs)
_ -> FoundName gre_name
fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel
fldParentToFieldLabel name mfs =
case mfs of
Nothing ->
let fs = occNameFS (nameOccName name)
in FieldLabel fs False name
Just fs -> FieldLabel fs True name
-- Called when we fine no matching GREs after disambiguation but
-- there are three situations where this happens.
-- 1. There were none to begin with.
-- 2. None of the matching ones were the parent but
-- a. They were from an overloaded record field so we can report
-- a better error
-- b. The original lookup was actually ambiguous.
-- For example, the case where overloading is off and two
-- record fields are in scope from different record
-- constructors, neither of which is the parent.
noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult
noMatchingParentErr original_gres = do
overload_ok <- xoptM LangExt.DuplicateRecordFields
case original_gres of
[] -> return NameNotFound
[g] -> mkDcErrMsg parent (gre_name g) [p | Just p <- [getParent g]]
gss@(g:_:_) ->
if all isRecFldGRE gss && overload_ok
then mkNameErr (dcErrMsg parent "record selector"
(expectJust "noMatchingParentErr" (greLabel g))
[ppr p | x <- gss, Just p <- [getParent x]])
else mkNameClashErr gss
mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult
mkNameClashErr gres = do
addNameClashErrRn rdr_name gres
return (FoundName (gre_name (head gres)))
getParent :: GlobalRdrElt -> Maybe Name
getParent (GRE { gre_par = p } ) =
case p of
ParentIs cur_parent -> Just cur_parent
FldParent { par_is = cur_parent } -> Just cur_parent
NoParent -> Nothing
picked_gres :: [GlobalRdrElt] -> DisambigInfo
picked_gres gres
| isUnqual rdr_name = mconcat (map right_parent gres)
| otherwise = mconcat (map right_parent (pickGREs rdr_name gres))
right_parent :: GlobalRdrElt -> DisambigInfo
right_parent p
| Just cur_parent <- getParent p
= if parent == cur_parent
then DisambiguatedOccurence p
else NoOccurence
| otherwise
= UniqueOccurence p
-- This domain specific datatype is used to record why we decided it was
-- possible that a GRE could be exported with a parent.
data DisambigInfo
= NoOccurence
-- The GRE could never be exported. It has the wrong parent.
| UniqueOccurence GlobalRdrElt
-- The GRE has no parent. It could be a pattern synonym.
| DisambiguatedOccurence GlobalRdrElt
-- The parent of the GRE is the correct parent
| AmbiguousOccurence [GlobalRdrElt]
-- For example, two normal identifiers with the same name are in
-- scope. They will both be resolved to "UniqueOccurence" and the
-- monoid will combine them to this failing case.
instance Monoid DisambigInfo where
mempty = NoOccurence
-- This is the key line: We prefer disambiguated occurences to other
-- names.
UniqueOccurence _ `mappend` DisambiguatedOccurence g' = DisambiguatedOccurence g'
DisambiguatedOccurence g' `mappend` UniqueOccurence _ = DisambiguatedOccurence g'
NoOccurence `mappend` m = m
m `mappend` NoOccurence = m
UniqueOccurence g `mappend` UniqueOccurence g' = AmbiguousOccurence [g, g']
UniqueOccurence g `mappend` AmbiguousOccurence gs = AmbiguousOccurence (g:gs)
DisambiguatedOccurence g `mappend` DisambiguatedOccurence g' = AmbiguousOccurence [g, g']
DisambiguatedOccurence g `mappend` AmbiguousOccurence gs = AmbiguousOccurence (g:gs)
AmbiguousOccurence gs `mappend` UniqueOccurence g' = AmbiguousOccurence (g':gs)
AmbiguousOccurence gs `mappend` DisambiguatedOccurence g' = AmbiguousOccurence (g':gs)
AmbiguousOccurence gs `mappend` AmbiguousOccurence gs' = AmbiguousOccurence (gs ++ gs')
--
-- Note: [Typing Pattern Synonym Exports]
-- It proved quite a challenge to precisely specify which pattern synonyms
-- should be allowed to be bundled with which type constructors.
-- In the end it was decided to be quite liberal in what we allow. Below is
-- how Simon described the implementation.
--
-- "Personally I think we should Keep It Simple. All this talk of
-- satisfiability makes me shiver. I suggest this: allow T( P ) in all
-- situations except where `P`'s type is ''visibly incompatible'' with
-- `T`.
--
-- What does "visibly incompatible" mean? `P` is visibly incompatible
-- with
-- `T` if
-- * `P`'s type is of form `... -> S t1 t2`
-- * `S` is a data/newtype constructor distinct from `T`
--
-- Nothing harmful happens if we allow `P` to be exported with
-- a type it can't possibly be useful for, but specifying a tighter
-- relationship is very awkward as you have discovered."
--
-- Note that this allows *any* pattern synonym to be bundled with any
-- datatype type constructor. For example, the following pattern `P` can be
-- bundled with any type.
--
-- ```
-- pattern P :: (A ~ f) => f
-- ```
--
-- So we provide basic type checking in order to help the user out, most
-- pattern synonyms are defined with definite type constructors, but don't
-- actually prevent a library author completely confusing their users if
-- they want to.
--
-- So, we check for exactly four things
-- 1. The name arises from a pattern synonym definition. (Either a pattern
-- synonym constructor or a pattern synonym selector)
-- 2. The pattern synonym is only bundled with a datatype or newtype.
-- 3. Check that the head of the result type constructor is an actual type
-- constructor and not a type variable. (See above example)
-- 4. Is so, check that this type constructor is the same as the parent
-- type constructor.
--
--
-- Note: [Types of TyCon]
--
-- This check appears to be overlly complicated, Richard asked why it
-- is not simply just `isAlgTyCon`. The answer for this is that
-- a classTyCon is also an `AlgTyCon` which we explicitly want to disallow.
-- (It is either a newtype or data depending on the number of methods)
--
-- | Given a resolved name in the children export list and a parent. Decide
-- whether we are allowed to export the child with the parent.
-- Invariant: gre_par == NoParent
-- See note [Typing Pattern Synonym Exports]
checkPatSynParent :: Name -- ^ Type constructor
-> Name -- ^ Either a
-- a) Pattern Synonym Constructor
-- b) A pattern synonym selector
-> TcM ChildLookupResult
checkPatSynParent parent mpat_syn = do
parent_ty_con <- tcLookupTyCon parent
mpat_syn_thing <- tcLookupGlobal mpat_syn
let expected_res_ty =
mkTyConApp parent_ty_con (mkTyVarTys (tyConTyVars parent_ty_con))
handlePatSyn errCtxt =
addErrCtxt errCtxt
. tc_one_ps_export_with expected_res_ty parent_ty_con
-- 1. Check that the Id was actually from a thing associated with patsyns
case mpat_syn_thing of
AnId i
| isId i ->
case idDetails i of
RecSelId { sel_tycon = RecSelPatSyn p } -> handlePatSyn (selErr i) p
_ -> mkDcErrMsg parent mpat_syn []
AConLike (PatSynCon p) -> handlePatSyn (psErr p) p
_ -> mkDcErrMsg parent mpat_syn []
where
psErr = exportErrCtxt "pattern synonym"
selErr = exportErrCtxt "pattern synonym record selector"
assocClassErr :: SDoc
assocClassErr =
text "Pattern synonyms can be bundled only with datatypes."
tc_one_ps_export_with :: TcTauType -- ^ TyCon type
-> TyCon -- ^ Parent TyCon
-> PatSyn -- ^ Corresponding bundled PatSyn
-- and pretty printed origin
-> TcM ChildLookupResult
tc_one_ps_export_with expected_res_ty ty_con pat_syn
-- 2. See note [Types of TyCon]
| not $ isTyConWithSrcDataCons ty_con = mkNameErr assocClassErr
-- 3. Is the head a type variable?
| Nothing <- mtycon = return (FoundName mpat_syn)
-- 4. Ok. Check they are actually the same type constructor.
| Just p_ty_con <- mtycon, p_ty_con /= ty_con = mkNameErr typeMismatchError
-- 5. We passed!
| otherwise = return (FoundName mpat_syn)
where
(_, _, _, _, _, res_ty) = patSynSig pat_syn
mtycon = fst <$> tcSplitTyConApp_maybe res_ty
typeMismatchError :: SDoc
typeMismatchError =
text "Pattern synonyms can only be bundled with matching type constructors"
$$ text "Couldn't match expected type of"
<+> quotes (ppr expected_res_ty)
<+> text "with actual type of"
<+> quotes (ppr res_ty)
{-===========================================================================-}
check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
check_occs ie occs names -- 'names' are the entities specifed by 'ie'
= foldlM check occs names
where
check occs name
= case lookupOccEnv occs name_occ of
Nothing -> return (extendOccEnv occs name_occ (name, ie))
Just (name', ie')
| name == name' -- Duplicate export
-- But we don't want to warn if the same thing is exported
-- by two different module exports. See ticket #4478.
-> do { warnIf (Reason Opt_WarnDuplicateExports)
(not (dupExport_ok name ie ie'))
(dupExportWarn name_occ ie ie')
; return occs }
| otherwise -- Same occ name but different names: an error
-> do { global_env <- getGlobalRdrEnv ;
addErr (exportClashErr global_env name' name ie' ie) ;
return occs }
where
name_occ = nameOccName name
dupExport_ok :: Name -> IE RdrName -> IE RdrName -> Bool
-- The Name is exported by both IEs. Is that ok?
-- "No" iff the name is mentioned explicitly in both IEs
-- or one of the IEs mentions the name *alone*
-- "Yes" otherwise
--
-- Examples of "no": module M( f, f )
-- module M( fmap, Functor(..) )
-- module M( module Data.List, head )
--
-- Example of "yes"
-- module M( module A, module B ) where
-- import A( f )
-- import B( f )
--
-- Example of "yes" (Trac #2436)
-- module M( C(..), T(..) ) where
-- class C a where { data T a }
-- instance C Int where { data T Int = TInt }
--
-- Example of "yes" (Trac #2436)
-- module Foo ( T ) where
-- data family T a
-- module Bar ( T(..), module Foo ) where
-- import Foo
-- data instance T Int = TInt
dupExport_ok n ie1 ie2
= not ( single ie1 || single ie2
|| (explicit_in ie1 && explicit_in ie2) )
where
explicit_in (IEModuleContents _) = False -- module M
explicit_in (IEThingAll r) = nameOccName n == rdrNameOcc (unLoc r) -- T(..)
explicit_in _ = True
single IEVar {} = True
single IEThingAbs {} = True
single _ = False
dupModuleExport :: ModuleName -> SDoc
dupModuleExport mod
= hsep [text "Duplicate",
quotes (text "Module" <+> ppr mod),
text "in export list"]
moduleNotImported :: ModuleName -> SDoc
moduleNotImported mod
= text "The export item `module" <+> ppr mod <>
text "' is not imported"
nullModuleExport :: ModuleName -> SDoc
nullModuleExport mod
= text "The export item `module" <+> ppr mod <> ptext (sLit "' exports nothing")
dodgyExportWarn :: Name -> SDoc
dodgyExportWarn item = dodgyMsg (text "export") item
exportErrCtxt :: Outputable o => String -> o -> SDoc
exportErrCtxt herald exp =
text "In the" <+> text (herald ++ ":") <+> ppr exp
addExportErrCtxt :: (HasOccName s, OutputableBndr s) => IE s -> TcM a -> TcM a
addExportErrCtxt ie = addErrCtxt exportCtxt
where
exportCtxt = text "In the export:" <+> ppr ie
exportItemErr :: IE RdrName -> SDoc
exportItemErr export_item
= sep [ text "The export item" <+> quotes (ppr export_item),
text "attempts to export constructors or class methods that are not visible here" ]
dupExportWarn :: OccName -> IE RdrName -> IE RdrName -> SDoc
dupExportWarn occ_name ie1 ie2
= hsep [quotes (ppr occ_name),
text "is exported by", quotes (ppr ie1),
text "and", quotes (ppr ie2)]
dcErrMsg :: Outputable a => Name -> String -> a -> [SDoc] -> SDoc
dcErrMsg ty_con what_is thing parents =
text "The type constructor" <+> quotes (ppr ty_con)
<+> text "is not the parent of the" <+> text what_is
<+> quotes (ppr thing) <> char '.'
$$ text (capitalise what_is)
<> text "s can only be exported with their parent type constructor."
$$ (case parents of
[] -> empty
[_] -> text "Parent:"
_ -> text "Parents:") <+> fsep (punctuate comma parents)
mkDcErrMsg :: Name -> Name -> [Name] -> TcM ChildLookupResult
mkDcErrMsg parent thing parents = do
ty_thing <- tcLookupGlobal thing
mkNameErr (dcErrMsg parent (tyThingCategory' ty_thing) thing (map ppr parents))
where
tyThingCategory' :: TyThing -> String
tyThingCategory' (AnId i)
| isRecordSelector i = "record selector"
tyThingCategory' i = tyThingCategory i
exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
-> MsgDoc
exportClashErr global_env name1 name2 ie1 ie2
= vcat [ text "Conflicting exports for" <+> quotes (ppr occ) <> colon
, ppr_export ie1' name1'
, ppr_export ie2' name2' ]
where
occ = nameOccName name1
ppr_export ie name = nest 3 (hang (quotes (ppr ie) <+> text "exports" <+>
quotes (ppr name))
2 (pprNameProvenance (get_gre name)))
-- get_gre finds a GRE for the Name, so that we can show its provenance
get_gre name
= fromMaybe (pprPanic "exportClashErr" (ppr name)) (lookupGRE_Name global_env name)
get_loc name = greSrcSpan (get_gre name)
(name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
then (name1, ie1, name2, ie2)
else (name2, ie2, name1, ie1)
|
olsner/ghc
|
compiler/typecheck/TcRnExports.hs
|
Haskell
|
bsd-3-clause
| 33,896
|
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.LHC
-- Copyright : Isaac Jones 2003-2007
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is a fairly large module. It contains most of the GHC-specific code for
-- configuring, building and installing packages. It also exports a function
-- for finding out what packages are already installed. Configuring involves
-- finding the @ghc@ and @ghc-pkg@ programs, finding what language extensions
-- this version of ghc supports and returning a 'Compiler' value.
--
-- 'getInstalledPackages' involves calling the @ghc-pkg@ program to find out
-- what packages are installed.
--
-- Building is somewhat complex as there is quite a bit of information to take
-- into account. We have to build libs and programs, possibly for profiling and
-- shared libs. We have to support building libraries that will be usable by
-- GHCi and also ghc's @-split-objs@ feature. We have to compile any C files
-- using ghc. Linking, especially for @split-objs@ is remarkably complex,
-- partly because there tend to be 1,000's of @.o@ files and this can often be
-- more than we can pass to the @ld@ or @ar@ programs in one go.
--
-- Installing for libs and exes involves finding the right files and copying
-- them to the right places. One of the more tricky things about this module is
-- remembering the layout of files in the build directory (which is not
-- explicitly documented) and thus what search dirs are used for various kinds
-- of files.
module Distribution.Simple.LHC (
configure, getInstalledPackages,
buildLib, buildExe,
installLib, installExe,
registerPackage,
hcPkgInfo,
ghcOptions,
ghcVerbosityOptions
) where
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), Executable(..)
, Library(..), libModules, hcOptions, hcProfOptions, hcSharedOptions
, usedExtensions, allExtensions )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo
, parseInstalledPackageInfo )
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo(..) )
import Distribution.Simple.PackageIndex
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.ParseUtils ( ParseResult(..) )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), ComponentLocalBuildInfo(..) )
import Distribution.Simple.InstallDirs
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Package
( Package(..), getHSLibraryName, ComponentId )
import qualified Distribution.ModuleName as ModuleName
import Distribution.Simple.Program
( Program(..), ConfiguredProgram(..), ProgramConfiguration
, ProgramSearchPath, ProgramLocation(..)
, rawSystemProgram, rawSystemProgramConf
, rawSystemProgramStdout, rawSystemProgramStdoutConf
, requireProgramVersion
, userMaybeSpecifyPath, programPath, lookupProgram, addKnownProgram
, arProgram, ldProgram
, gccProgram, stripProgram
, lhcProgram, lhcPkgProgram )
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import Distribution.Simple.Compiler
( CompilerFlavor(..), CompilerId(..), Compiler(..), compilerVersion
, OptimisationLevel(..), PackageDB(..), PackageDBStack, AbiTag(..)
, Flag, languageToFlags, extensionsToFlags )
import Distribution.Version
( Version(..), orLaterVersion )
import Distribution.System
( OS(..), buildOS )
import Distribution.Verbosity
import Distribution.Text
( display, simpleParse )
import Language.Haskell.Extension
( Language(Haskell98), Extension(..), KnownExtension(..) )
import Control.Monad ( unless, when )
import Data.List
import qualified Data.Map as M ( empty )
import Data.Maybe ( catMaybes )
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid ( Monoid(..) )
#endif
import System.Directory ( removeFile, renameFile,
getDirectoryContents, doesFileExist,
getTemporaryDirectory )
import System.FilePath ( (</>), (<.>), takeExtension,
takeDirectory, replaceExtension )
import System.IO (hClose, hPutStrLn)
import Distribution.Compat.Exception (catchExit, catchIO)
import Distribution.System ( Platform )
-- -----------------------------------------------------------------------------
-- Configuring
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity hcPath hcPkgPath conf = do
(lhcProg, lhcVersion, conf') <-
requireProgramVersion verbosity lhcProgram
(orLaterVersion (Version [0,7] []))
(userMaybeSpecifyPath "lhc" hcPath conf)
(lhcPkgProg, lhcPkgVersion, conf'') <-
requireProgramVersion verbosity lhcPkgProgram
(orLaterVersion (Version [0,7] []))
(userMaybeSpecifyPath "lhc-pkg" hcPkgPath conf')
when (lhcVersion /= lhcPkgVersion) $ die $
"Version mismatch between lhc and lhc-pkg: "
++ programPath lhcProg ++ " is version " ++ display lhcVersion ++ " "
++ programPath lhcPkgProg ++ " is version " ++ display lhcPkgVersion
languages <- getLanguages verbosity lhcProg
extensions <- getExtensions verbosity lhcProg
let comp = Compiler {
compilerId = CompilerId LHC lhcVersion,
compilerAbiTag = NoAbiTag,
compilerCompat = [],
compilerLanguages = languages,
compilerExtensions = extensions,
compilerProperties = M.empty
}
conf''' = configureToolchain lhcProg conf'' -- configure gcc and ld
compPlatform = Nothing
return (comp, compPlatform, conf''')
-- | Adjust the way we find and configure gcc and ld
--
configureToolchain :: ConfiguredProgram -> ProgramConfiguration
-> ProgramConfiguration
configureToolchain lhcProg =
addKnownProgram gccProgram {
programFindLocation = findProg gccProgram (baseDir </> "gcc.exe"),
programPostConf = configureGcc
}
. addKnownProgram ldProgram {
programFindLocation = findProg ldProgram (libDir </> "ld.exe"),
programPostConf = configureLd
}
where
compilerDir = takeDirectory (programPath lhcProg)
baseDir = takeDirectory compilerDir
libDir = baseDir </> "gcc-lib"
includeDir = baseDir </> "include" </> "mingw"
isWindows = case buildOS of Windows -> True; _ -> False
-- on Windows finding and configuring ghc's gcc and ld is a bit special
findProg :: Program -> FilePath
-> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
findProg prog location | isWindows = \verbosity searchpath -> do
exists <- doesFileExist location
if exists then return (Just location)
else do warn verbosity ("Couldn't find " ++ programName prog ++ " where I expected it. Trying the search path.")
programFindLocation prog verbosity searchpath
| otherwise = programFindLocation prog
configureGcc :: Verbosity -> ConfiguredProgram -> IO ConfiguredProgram
configureGcc
| isWindows = \_ gccProg -> case programLocation gccProg of
-- if it's found on system then it means we're using the result
-- of programFindLocation above rather than a user-supplied path
-- that means we should add this extra flag to tell ghc's gcc
-- where it lives and thus where gcc can find its various files:
FoundOnSystem {} -> return gccProg {
programDefaultArgs = ["-B" ++ libDir,
"-I" ++ includeDir]
}
UserSpecified {} -> return gccProg
| otherwise = \_ gccProg -> return gccProg
-- we need to find out if ld supports the -x flag
configureLd :: Verbosity -> ConfiguredProgram -> IO ConfiguredProgram
configureLd verbosity ldProg = do
tempDir <- getTemporaryDirectory
ldx <- withTempFile tempDir ".c" $ \testcfile testchnd ->
withTempFile tempDir ".o" $ \testofile testohnd -> do
hPutStrLn testchnd "int foo() { return 0; }"
hClose testchnd; hClose testohnd
rawSystemProgram verbosity lhcProg ["-c", testcfile,
"-o", testofile]
withTempFile tempDir ".o" $ \testofile' testohnd' ->
do
hClose testohnd'
_ <- rawSystemProgramStdout verbosity ldProg
["-x", "-r", testofile, "-o", testofile']
return True
`catchIO` (\_ -> return False)
`catchExit` (\_ -> return False)
if ldx
then return ldProg { programDefaultArgs = ["-x"] }
else return ldProg
getLanguages :: Verbosity -> ConfiguredProgram -> IO [(Language, Flag)]
getLanguages _ _ = return [(Haskell98, "")]
--FIXME: does lhc support -XHaskell98 flag? from what version?
getExtensions :: Verbosity -> ConfiguredProgram -> IO [(Extension, Flag)]
getExtensions verbosity lhcProg = do
exts <- rawSystemStdout verbosity (programPath lhcProg)
["--supported-languages"]
-- GHC has the annoying habit of inverting some of the extensions
-- so we have to try parsing ("No" ++ ghcExtensionName) first
let readExtension str = do
ext <- simpleParse ("No" ++ str)
case ext of
UnknownExtension _ -> simpleParse str
_ -> return ext
return $ [ (ext, "-X" ++ display ext)
| Just ext <- map readExtension (lines exts) ]
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity packagedbs conf = do
checkPackageDbStack packagedbs
pkgss <- getInstalledPackages' lhcPkg verbosity packagedbs conf
let indexes = [ PackageIndex.fromList (map (substTopDir topDir) pkgs)
| (_, pkgs) <- pkgss ]
return $! (mconcat indexes)
where
-- On Windows, various fields have $topdir/foo rather than full
-- paths. We need to substitute the right value in so that when
-- we, for example, call gcc, we have proper paths to give it
Just ghcProg = lookupProgram lhcProgram conf
Just lhcPkg = lookupProgram lhcPkgProgram conf
compilerDir = takeDirectory (programPath ghcProg)
topDir = takeDirectory compilerDir
checkPackageDbStack :: PackageDBStack -> IO ()
checkPackageDbStack (GlobalPackageDB:rest)
| GlobalPackageDB `notElem` rest = return ()
checkPackageDbStack _ =
die $ "GHC.getInstalledPackages: the global package db must be "
++ "specified first and cannot be specified multiple times"
-- | Get the packages from specific PackageDBs, not cumulative.
--
getInstalledPackages' :: ConfiguredProgram -> Verbosity
-> [PackageDB] -> ProgramConfiguration
-> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' lhcPkg verbosity packagedbs conf
=
sequence
[ do str <- rawSystemProgramStdoutConf verbosity lhcPkgProgram conf
["dump", packageDbGhcPkgFlag packagedb]
`catchExit` \_ -> die $ "ghc-pkg dump failed"
case parsePackages str of
Left ok -> return (packagedb, ok)
_ -> die "failed to parse output of 'ghc-pkg dump'"
| packagedb <- packagedbs ]
where
parsePackages str =
let parsed = map parseInstalledPackageInfo (splitPkgs str)
in case [ msg | ParseFailed msg <- parsed ] of
[] -> Left [ pkg | ParseOk _ pkg <- parsed ]
msgs -> Right msgs
splitPkgs :: String -> [String]
splitPkgs = map unlines . splitWith ("---" ==) . lines
where
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs = ys : case zs of
[] -> []
_:ws -> splitWith p ws
where (ys,zs) = break p xs
packageDbGhcPkgFlag GlobalPackageDB = "--global"
packageDbGhcPkgFlag UserPackageDB = "--user"
packageDbGhcPkgFlag (SpecificPackageDB path) = "--" ++ packageDbFlag ++ "=" ++ path
packageDbFlag
| programVersion lhcPkg < Just (Version [7,5] [])
= "package-conf"
| otherwise
= "package-db"
substTopDir :: FilePath -> InstalledPackageInfo -> InstalledPackageInfo
substTopDir topDir ipo
= ipo {
InstalledPackageInfo.importDirs
= map f (InstalledPackageInfo.importDirs ipo),
InstalledPackageInfo.libraryDirs
= map f (InstalledPackageInfo.libraryDirs ipo),
InstalledPackageInfo.includeDirs
= map f (InstalledPackageInfo.includeDirs ipo),
InstalledPackageInfo.frameworkDirs
= map f (InstalledPackageInfo.frameworkDirs ipo),
InstalledPackageInfo.haddockInterfaces
= map f (InstalledPackageInfo.haddockInterfaces ipo),
InstalledPackageInfo.haddockHTMLs
= map f (InstalledPackageInfo.haddockHTMLs ipo)
}
where f ('$':'t':'o':'p':'d':'i':'r':rest) = topDir ++ rest
f x = x
-- -----------------------------------------------------------------------------
-- Building
-- | Build a library with LHC.
--
buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
let libName = componentId clbi
pref = buildDir lbi
pkgid = packageId pkg_descr
runGhcProg = rawSystemProgramConf verbosity lhcProgram (withPrograms lbi)
ifVanillaLib forceVanilla = when (forceVanilla || withVanillaLib lbi)
ifProfLib = when (withProfLib lbi)
ifSharedLib = when (withSharedLib lbi)
ifGHCiLib = when (withGHCiLib lbi && withVanillaLib lbi)
libBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfLib lbi) (libBuildInfo lib)
let libTargetDir = pref
forceVanillaLib = EnableExtension TemplateHaskell `elem` allExtensions libBi
-- TH always needs vanilla libs, even when building for profiling
createDirectoryIfMissingVerbose verbosity True libTargetDir
-- TODO: do we need to put hs-boot files into place for mutually recursive modules?
let ghcArgs =
["-package-name", display pkgid ]
++ constructGHCCmdLine lbi libBi clbi libTargetDir verbosity
++ map display (libModules lib)
lhcWrap x = ["--build-library", "--ghc-opts=" ++ unwords x]
ghcArgsProf = ghcArgs
++ ["-prof",
"-hisuf", "p_hi",
"-osuf", "p_o"
]
++ hcProfOptions GHC libBi
ghcArgsShared = ghcArgs
++ ["-dynamic",
"-hisuf", "dyn_hi",
"-osuf", "dyn_o", "-fPIC"
]
++ hcSharedOptions GHC libBi
unless (null (libModules lib)) $
do ifVanillaLib forceVanillaLib (runGhcProg $ lhcWrap ghcArgs)
ifProfLib (runGhcProg $ lhcWrap ghcArgsProf)
ifSharedLib (runGhcProg $ lhcWrap ghcArgsShared)
-- build any C sources
unless (null (cSources libBi)) $ do
info verbosity "Building C Sources..."
sequence_ [do let (odir,args) = constructCcCmdLine lbi libBi clbi pref
filename verbosity
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg args
ifSharedLib (runGhcProg (args ++ ["-fPIC", "-osuf dyn_o"]))
| filename <- cSources libBi]
-- link:
info verbosity "Linking..."
let cObjs = map (`replaceExtension` objExtension) (cSources libBi)
cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension)) (cSources libBi)
cid = compilerId (compiler lbi)
vanillaLibFilePath = libTargetDir </> mkLibName libName
profileLibFilePath = libTargetDir </> mkProfLibName libName
sharedLibFilePath = libTargetDir </> mkSharedLibName cid libName
ghciLibFilePath = libTargetDir </> mkGHCiLibName libName
stubObjs <- fmap catMaybes $ sequence
[ findFileWithExtension [objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| x <- libModules lib ]
stubProfObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["p_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| x <- libModules lib ]
stubSharedObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| x <- libModules lib ]
hObjs <- getHaskellObjects lib lbi
pref objExtension True
hProfObjs <-
if (withProfLib lbi)
then getHaskellObjects lib lbi
pref ("p_" ++ objExtension) True
else return []
hSharedObjs <-
if (withSharedLib lbi)
then getHaskellObjects lib lbi
pref ("dyn_" ++ objExtension) False
else return []
unless (null hObjs && null cObjs && null stubObjs) $ do
-- first remove library files if they exists
sequence_
[ removeFile libFilePath `catchIO` \_ -> return ()
| libFilePath <- [vanillaLibFilePath, profileLibFilePath
,sharedLibFilePath, ghciLibFilePath] ]
let arVerbosity | verbosity >= deafening = "v"
| verbosity >= normal = ""
| otherwise = "c"
arArgs = ["q"++ arVerbosity]
++ [vanillaLibFilePath]
arObjArgs =
hObjs
++ map (pref </>) cObjs
++ stubObjs
arProfArgs = ["q"++ arVerbosity]
++ [profileLibFilePath]
arProfObjArgs =
hProfObjs
++ map (pref </>) cObjs
++ stubProfObjs
ldArgs = ["-r"]
++ ["-o", ghciLibFilePath <.> "tmp"]
ldObjArgs =
hObjs
++ map (pref </>) cObjs
++ stubObjs
ghcSharedObjArgs =
hSharedObjs
++ map (pref </>) cSharedObjs
++ stubSharedObjs
-- After the relocation lib is created we invoke ghc -shared
-- with the dependencies spelled out as -package arguments
-- and ghc invokes the linker with the proper library paths
ghcSharedLinkArgs =
[ "-no-auto-link-packages",
"-shared",
"-dynamic",
"-o", sharedLibFilePath ]
++ ghcSharedObjArgs
++ ["-package-name", display pkgid ]
++ ghcPackageFlags lbi clbi
++ ["-l"++extraLib | extraLib <- extraLibs libBi]
++ ["-L"++extraLibDir | extraLibDir <- extraLibDirs libBi]
runLd ldLibName args = do
exists <- doesFileExist ldLibName
-- This method is called iteratively by xargs. The
-- output goes to <ldLibName>.tmp, and any existing file
-- named <ldLibName> is included when linking. The
-- output is renamed to <libName>.
rawSystemProgramConf verbosity ldProgram (withPrograms lbi)
(args ++ if exists then [ldLibName] else [])
renameFile (ldLibName <.> "tmp") ldLibName
runAr = rawSystemProgramConf verbosity arProgram (withPrograms lbi)
--TODO: discover this at configure time or runtime on Unix
-- The value is 32k on Windows and POSIX specifies a minimum of 4k
-- but all sensible Unixes use more than 4k.
-- we could use getSysVar ArgumentLimit but that's in the Unix lib
maxCommandLineSize = 30 * 1024
ifVanillaLib False $ xargs maxCommandLineSize
runAr arArgs arObjArgs
ifProfLib $ xargs maxCommandLineSize
runAr arProfArgs arProfObjArgs
ifGHCiLib $ xargs maxCommandLineSize
(runLd ghciLibFilePath) ldArgs ldObjArgs
ifSharedLib $ runGhcProg ghcSharedLinkArgs
-- | Build an executable with LHC.
--
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity _pkg_descr lbi
exe@Executable { exeName = exeName', modulePath = modPath } clbi = do
let pref = buildDir lbi
runGhcProg = rawSystemProgramConf verbosity lhcProgram (withPrograms lbi)
exeBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfExe lbi) (buildInfo exe)
-- exeNameReal, the name that GHC really uses (with .exe on Windows)
let exeNameReal = exeName' <.>
(if null $ takeExtension exeName' then exeExtension else "")
let targetDir = pref </> exeName'
let exeDir = targetDir </> (exeName' ++ "-tmp")
createDirectoryIfMissingVerbose verbosity True targetDir
createDirectoryIfMissingVerbose verbosity True exeDir
-- TODO: do we need to put hs-boot files into place for mutually recursive modules?
-- FIX: what about exeName.hi-boot?
-- build executables
unless (null (cSources exeBi)) $ do
info verbosity "Building C Sources."
sequence_ [do let (odir,args) = constructCcCmdLine lbi exeBi clbi
exeDir filename verbosity
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg args
| filename <- cSources exeBi]
srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath
let cObjs = map (`replaceExtension` objExtension) (cSources exeBi)
let lhcWrap x = ("--ghc-opts\"":x) ++ ["\""]
let binArgs linkExe profExe =
(if linkExe
then ["-o", targetDir </> exeNameReal]
else ["-c"])
++ constructGHCCmdLine lbi exeBi clbi exeDir verbosity
++ [exeDir </> x | x <- cObjs]
++ [srcMainFile]
++ ["-optl" ++ opt | opt <- PD.ldOptions exeBi]
++ ["-l"++lib | lib <- extraLibs exeBi]
++ ["-L"++libDir | libDir <- extraLibDirs exeBi]
++ concat [["-framework", f] | f <- PD.frameworks exeBi]
++ if profExe
then ["-prof",
"-hisuf", "p_hi",
"-osuf", "p_o"
] ++ hcProfOptions GHC exeBi
else []
-- For building exe's for profiling that use TH we actually
-- have to build twice, once without profiling and the again
-- with profiling. This is because the code that TH needs to
-- run at compile time needs to be the vanilla ABI so it can
-- be loaded up and run by the compiler.
when (withProfExe lbi && EnableExtension TemplateHaskell `elem` allExtensions exeBi)
(runGhcProg $ lhcWrap (binArgs False False))
runGhcProg (binArgs True (withProfExe lbi))
-- | Filter the "-threaded" flag when profiling as it does not
-- work with ghc-6.8 and older.
hackThreadedFlag :: Verbosity -> Compiler -> Bool -> BuildInfo -> IO BuildInfo
hackThreadedFlag verbosity comp prof bi
| not mustFilterThreaded = return bi
| otherwise = do
warn verbosity $ "The ghc flag '-threaded' is not compatible with "
++ "profiling in ghc-6.8 and older. It will be disabled."
return bi { options = filterHcOptions (/= "-threaded") (options bi) }
where
mustFilterThreaded = prof && compilerVersion comp < Version [6, 10] []
&& "-threaded" `elem` hcOptions GHC bi
filterHcOptions p hcoptss =
[ (hc, if hc == GHC then filter p opts else opts)
| (hc, opts) <- hcoptss ]
-- when using -split-objs, we need to search for object files in the
-- Module_split directory for each module.
getHaskellObjects :: Library -> LocalBuildInfo
-> FilePath -> String -> Bool -> IO [FilePath]
getHaskellObjects lib lbi pref wanted_obj_ext allow_split_objs
| splitObjs lbi && allow_split_objs = do
let dirs = [ pref </> (ModuleName.toFilePath x ++ "_split")
| x <- libModules lib ]
objss <- mapM getDirectoryContents dirs
let objs = [ dir </> obj
| (objs',dir) <- zip objss dirs, obj <- objs',
let obj_ext = takeExtension obj,
'.':wanted_obj_ext == obj_ext ]
return objs
| otherwise =
return [ pref </> ModuleName.toFilePath x <.> wanted_obj_ext
| x <- libModules lib ]
constructGHCCmdLine
:: LocalBuildInfo
-> BuildInfo
-> ComponentLocalBuildInfo
-> FilePath
-> Verbosity
-> [String]
constructGHCCmdLine lbi bi clbi odir verbosity =
["--make"]
++ ghcVerbosityOptions verbosity
-- Unsupported extensions have already been checked by configure
++ ghcOptions lbi bi clbi odir
ghcVerbosityOptions :: Verbosity -> [String]
ghcVerbosityOptions verbosity
| verbosity >= deafening = ["-v"]
| verbosity >= normal = []
| otherwise = ["-w", "-v0"]
ghcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> [String]
ghcOptions lbi bi clbi odir
= ["-hide-all-packages"]
++ ghcPackageDbOptions lbi
++ (if splitObjs lbi then ["-split-objs"] else [])
++ ["-i"]
++ ["-i" ++ odir]
++ ["-i" ++ l | l <- nub (hsSourceDirs bi)]
++ ["-i" ++ autogenModulesDir lbi]
++ ["-I" ++ autogenModulesDir lbi]
++ ["-I" ++ odir]
++ ["-I" ++ dir | dir <- PD.includeDirs bi]
++ ["-optP" ++ opt | opt <- cppOptions bi]
++ [ "-optP-include", "-optP"++ (autogenModulesDir lbi </> cppHeaderName) ]
++ [ "-#include \"" ++ inc ++ "\"" | inc <- PD.includes bi ]
++ [ "-odir", odir, "-hidir", odir ]
++ (if compilerVersion c >= Version [6,8] []
then ["-stubdir", odir] else [])
++ ghcPackageFlags lbi clbi
++ (case withOptimization lbi of
NoOptimisation -> []
NormalOptimisation -> ["-O"]
MaximumOptimisation -> ["-O2"])
++ hcOptions GHC bi
++ languageToFlags c (defaultLanguage bi)
++ extensionsToFlags c (usedExtensions bi)
where c = compiler lbi
ghcPackageFlags :: LocalBuildInfo -> ComponentLocalBuildInfo -> [String]
ghcPackageFlags lbi clbi
| ghcVer >= Version [6,11] []
= concat [ ["-package-id", display ipkgid]
| (ipkgid, _) <- componentPackageDeps clbi ]
| otherwise = concat [ ["-package", display pkgid]
| (_, pkgid) <- componentPackageDeps clbi ]
where
ghcVer = compilerVersion (compiler lbi)
ghcPackageDbOptions :: LocalBuildInfo -> [String]
ghcPackageDbOptions lbi = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> concatMap specific dbs
(GlobalPackageDB:dbs) -> ("-no-user-" ++ packageDbFlag)
: concatMap specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = [ '-':packageDbFlag, db ]
specific _ = ierror
ierror = error ("internal error: unexpected package db stack: " ++ show dbstack)
dbstack = withPackageDB lbi
packageDbFlag
| compilerVersion (compiler lbi) < Version [7,5] []
= "package-conf"
| otherwise
= "package-db"
constructCcCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> FilePath -> Verbosity -> (FilePath,[String])
constructCcCmdLine lbi bi clbi pref filename verbosity
= let odir | compilerVersion (compiler lbi) >= Version [6,4,1] [] = pref
| otherwise = pref </> takeDirectory filename
-- ghc 6.4.1 fixed a bug in -odir handling
-- for C compilations.
in
(odir,
ghcCcOptions lbi bi clbi odir
++ (if verbosity >= deafening then ["-v"] else [])
++ ["-c",filename])
ghcCcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> [String]
ghcCcOptions lbi bi clbi odir
= ["-I" ++ dir | dir <- PD.includeDirs bi]
++ ghcPackageDbOptions lbi
++ ghcPackageFlags lbi clbi
++ ["-optc" ++ opt | opt <- PD.ccOptions bi]
++ (case withOptimization lbi of
NoOptimisation -> []
_ -> ["-optc-O2"])
++ ["-odir", odir]
mkGHCiLibName :: ComponentId -> String
mkGHCiLibName lib = getHSLibraryName lib <.> "o"
-- -----------------------------------------------------------------------------
-- Installing
-- |Install executables for GHC.
installExe :: Verbosity
-> LocalBuildInfo
-> InstallDirs FilePath -- ^Where to copy the files to
-> FilePath -- ^Build location
-> (FilePath, FilePath) -- ^Executable (prefix,suffix)
-> PackageDescription
-> Executable
-> IO ()
installExe verbosity lbi installDirs buildPref (progprefix, progsuffix) _pkg exe = do
let binDir = bindir installDirs
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = exeName exe <.> exeExtension
fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix
installBinary dest = do
installExecutableFile verbosity
(buildPref </> exeName exe </> exeFileName)
(dest <.> exeExtension)
stripExe verbosity lbi exeFileName (dest <.> exeExtension)
installBinary (binDir </> fixedExeBaseName)
stripExe :: Verbosity -> LocalBuildInfo -> FilePath -> FilePath -> IO ()
stripExe verbosity lbi name path = when (stripExes lbi) $
case lookupProgram stripProgram (withPrograms lbi) of
Just strip -> rawSystemProgram verbosity strip args
Nothing -> unless (buildOS == Windows) $
-- Don't bother warning on windows, we don't expect them to
-- have the strip program anyway.
warn verbosity $ "Unable to strip executable '" ++ name
++ "' (missing the 'strip' program)"
where
args = path : case buildOS of
OSX -> ["-x"] -- By default, stripping the ghc binary on at least
-- some OS X installations causes:
-- HSbase-3.0.o: unknown symbol `_environ'"
-- The -x flag fixes that.
_ -> []
-- |Install for ghc, .hi, .a and, if --with-ghci given, .o
installLib :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^install location
-> FilePath -- ^install location for dynamic libraries
-> FilePath -- ^Build location
-> PackageDescription
-> Library
-> ComponentLocalBuildInfo
-> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do
-- copy .hi files over:
let copy src dst n = do
createDirectoryIfMissingVerbose verbosity True dst
installOrdinaryFile verbosity (src </> n) (dst </> n)
copyModuleFiles ext =
findModuleFiles [builtDir] [ext] (libModules lib)
>>= installOrdinaryFiles verbosity targetDir
ifVanilla $ copyModuleFiles "hi"
ifProf $ copyModuleFiles "p_hi"
hcrFiles <- findModuleFiles (builtDir : hsSourceDirs (libBuildInfo lib)) ["hcr"] (libModules lib)
flip mapM_ hcrFiles $ \(srcBase, srcFile) -> runLhc ["--install-library", srcBase </> srcFile]
-- copy the built library files over:
ifVanilla $ copy builtDir targetDir vanillaLibName
ifProf $ copy builtDir targetDir profileLibName
ifGHCi $ copy builtDir targetDir ghciLibName
ifShared $ copy builtDir dynlibTargetDir sharedLibName
where
cid = compilerId (compiler lbi)
libName = componentId clbi
vanillaLibName = mkLibName libName
profileLibName = mkProfLibName libName
ghciLibName = mkGHCiLibName libName
sharedLibName = mkSharedLibName cid libName
hasLib = not $ null (libModules lib)
&& null (cSources (libBuildInfo lib))
ifVanilla = when (hasLib && withVanillaLib lbi)
ifProf = when (hasLib && withProfLib lbi)
ifGHCi = when (hasLib && withGHCiLib lbi)
ifShared = when (hasLib && withSharedLib lbi)
runLhc = rawSystemProgramConf verbosity lhcProgram (withPrograms lbi)
-- -----------------------------------------------------------------------------
-- Registering
registerPackage
:: Verbosity
-> InstalledPackageInfo
-> PackageDescription
-> LocalBuildInfo
-> Bool
-> PackageDBStack
-> IO ()
registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs =
HcPkg.reregister (hcPkgInfo $ withPrograms lbi) verbosity packageDbs
(Right installedPkgInfo)
hcPkgInfo :: ProgramConfiguration -> HcPkg.HcPkgInfo
hcPkgInfo conf = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = lhcPkgProg
, HcPkg.noPkgDbStack = False
, HcPkg.noVerboseFlag = False
, HcPkg.flagPackageConf = False
, HcPkg.useSingleFileDb = True
}
where
Just lhcPkgProg = lookupProgram lhcPkgProgram conf
|
enolan/cabal
|
Cabal/Distribution/Simple/LHC.hs
|
Haskell
|
bsd-3-clause
| 33,686
|
{-|
Module : CSH.Eval.Frontend.Data
Description : Yesod data declarations for the EvalFrontend site
Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015
License : MIT
Maintainer : pvals@csh.rit.edu
Stability : Provisional
Portability : POSIX
Defines the web application layer of Evals
-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
module CSH.Eval.Frontend.Data where
import CSH.Eval.Routes (evalAPI)
import Text.Hamlet (hamletFile)
import Text.Lucius (luciusFile)
import CSH.Eval.Config (ServerCmd (..))
import CSH.Eval.Model
import Yesod
import Yesod.Static
import System.Log.Logger hiding (getLogger)
-- Declaration of location of static files
staticFiles "frontend/static"
-- | datatype for Yesod
data EvalFrontend = EvalFrontend
{ getStatic :: Static
, getConfig :: ServerCmd
, getCache :: Cache
, getFrontendLogger :: Logger
}
-- | DOCUMENT THIS!
data AccessLvl = FreshmanAccess
| MemberAccess
| EboardAccess
| AdminAccess
deriving (Eq, Ord)
-- This makes the datatypes for the evaluations frontend, for use by
-- page hanlders in different files without having recursive importing.
mkYesodData "EvalFrontend" $(parseRoutesFile "config/routes")
-- | A Yesod subsite for the evalAPI defined using servant in "CSH.Eval.Routes"
getEvalAPI :: EvalFrontend -> WaiSubsite
getEvalAPI _ = WaiSubsite evalAPI
-- | The basic layout for every CSH Eval page
evalLayout :: Widget -> Handler Html
evalLayout widget = do
pc <- widgetToPageContent $ do
widget
addStylesheetRemote "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"
addScriptRemote "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"
addStylesheet $ StaticR csh_bootstrap_min_css
addStylesheet $ StaticR syntax_css
addStylesheet $ StaticR csh_eval_css
toWidget $(luciusFile "frontend/templates/csh-eval.lucius")
addScript $ StaticR salvattore_min_js
withUrlRenderer $(hamletFile "frontend/templates/base.hamlet")
-- | The Yesod instance for the EvalFrontend
instance Yesod EvalFrontend where
defaultLayout = evalLayout
makeSessionBackend s = if tls then ssl "key.aes" else nossl
where tls = withTLS (getConfig s)
ssl = sslOnlySessions . fmap Just . defaultClientSessionBackend 120
nossl = return Nothing
yesodMiddleware = ssl . defaultYesodMiddleware
where ssl s = withTLS . getConfig <$> getYesod >>=
(\x -> if x
then sslOnlyMiddleware 120 s
else s)
|
robgssp/csh-eval
|
src/CSH/Eval/Frontend/Data.hs
|
Haskell
|
mit
| 3,013
|
{-# LANGUAGE StandaloneDeriving, DeriveGeneric #-}
module SizedSeq
( SizedSeq(..)
, emptySS
, addToSS
, addListToSS
, ssElts
, sizeSS
) where
import Prelude -- See note [Why do we import Prelude here?]
import Control.DeepSeq
import Data.Binary
import Data.List
import GHC.Generics
data SizedSeq a = SizedSeq {-# UNPACK #-} !Word [a]
deriving (Generic, Show)
instance Functor SizedSeq where
fmap f (SizedSeq sz l) = SizedSeq sz (fmap f l)
instance Foldable SizedSeq where
foldr f c ss = foldr f c (ssElts ss)
instance Traversable SizedSeq where
traverse f (SizedSeq sz l) = SizedSeq sz . reverse <$> traverse f (reverse l)
instance Binary a => Binary (SizedSeq a)
instance NFData a => NFData (SizedSeq a) where
rnf (SizedSeq _ xs) = rnf xs
emptySS :: SizedSeq a
emptySS = SizedSeq 0 []
addToSS :: SizedSeq a -> a -> SizedSeq a
addToSS (SizedSeq n r_xs) x = SizedSeq (n+1) (x:r_xs)
addListToSS :: SizedSeq a -> [a] -> SizedSeq a
addListToSS (SizedSeq n r_xs) xs
= SizedSeq (n + genericLength xs) (reverse xs ++ r_xs)
ssElts :: SizedSeq a -> [a]
ssElts (SizedSeq _ r_xs) = reverse r_xs
sizeSS :: SizedSeq a -> Word
sizeSS (SizedSeq n _) = n
|
sdiehl/ghc
|
libraries/ghci/SizedSeq.hs
|
Haskell
|
bsd-3-clause
| 1,176
|
module C4 where
import D4
instance SameOrNot Double where
isSameOrNot a b = a ==b
isNotSame a b = a /=b
myFringe:: Tree a -> [a]
myFringe (Leaf x ) = [x]
myFringe (Branch left right) = myFringe left
|
kmate/HaRe
|
old/testing/renaming/C4_TokOut.hs
|
Haskell
|
bsd-3-clause
| 216
|
module A1 where
import C1
import D1
sumSq xs
= ((sum (map (sq sq_f) xs)) + (sumSquares xs)) +
(sumSquares1 xs)
main = sumSq [1 .. 4]
|
kmate/HaRe
|
old/testing/addOneParameter/A1_AstOut.hs
|
Haskell
|
bsd-3-clause
| 147
|
<?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="en-GB">
<title>Form Handler | 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/formhandler/src/main/javahelp/org/zaproxy/zap/extension/formhandler/resources/help/helpset.hs
|
Haskell
|
apache-2.0
| 986
|
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wall #-}
-- | Bug(?) in Coercible constraint solving
module T13083 where
import Data.Kind
import GHC.Generics (Par1(..),(:*:)(..))
import GHC.Exts (coerce)
-- Representation as free vector space
type family V (a :: Type) :: Type -> Type
type instance V R = Par1
type instance V (a,b) = V a :*: V b
type instance V (Par1 a) = V a
data R = R
-- Linear map in row-major order
newtype L a b = L (V b (V a R))
-- Use coerce to drop newtype wrapper
bar :: L a b -> V b (V a R)
bar = coerce
{-
[W] L a b ~R V b (V a R)
-->
V b (V a R) ~R V b (V a R)
-}
{--------------------------------------------------------------------
Bug demo
--------------------------------------------------------------------}
-- A rejected type specialization of bar with a ~ (R,R), b ~ (Par1 R,R)
foo :: L (R,R) (Par1 R,R) -> V (Par1 R,R) (V (R,R) R)
-- foo :: L (a1,R) (Par1 b1,b2) -> V (Par1 b1,b2) (V (a1,R) R)
foo = coerce
{-
[W] L (a1,R) (Par1 b1, b2) ~R V (Par1 b1,b2) (V (a1,R) R)
-->
V (Par1 b1, b2) (V (a1,R) R) ~R same
-> (V (Par1 b1) :*: V b2) ((V a1 :*: V R) R)
-> (:*:) (V b1) (V b2) (:*: (V a1) Par1 R)
-->
L (a1,R) (Par1 b1, b2) ~R (:*:) (V b1) (V b2) (:*: (V a1) Par1 R)
-}
-- • Couldn't match representation of type ‘V Par1’
-- with that of ‘Par1’
-- arising from a use of ‘coerce’
-- Note that Par1 has the wrong kind (Type -> Type) for V Par1
-- Same error:
--
-- foo :: (a ~ (R,R), b ~ (Par1 R,R)) => L a b -> V b (V a R)
-- The following similar signatures work:
-- foo :: L (R,R) (R,Par1 R) -> V (R,Par1 R) (V (R,R) R)
-- foo :: L (Par1 R,R) (R,R) -> V (R,R) (V (Par1 R,R) R)
-- Same error:
-- -- Linear map in column-major order
-- newtype L a b = L (V a (V b s))
-- foo :: L (R,R) (Par1 R,R) -> V (R,R) (V (Par1 R,R) R)
-- foo = coerce
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_compile/T13083.hs
|
Haskell
|
bsd-3-clause
| 1,966
|
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE TypeFamilies, FlexibleInstances, UndecidableInstances, FlexibleContexts #-}
class A a
class B a where b :: a -> ()
instance A a => B a where b = undefined
newtype Y a = Y (a -> ())
okIn701 :: B a => Y a
okIn701 = wrap $ const () . b
okIn702 :: B a => Y a
okIn702 = wrap $ b
okInBoth :: B a => Y a
okInBoth = Y $ const () . b
class Wrapper a where
type Wrapped a
wrap :: Wrapped a -> a
instance Wrapper (Y a) where
type Wrapped (Y a) = a -> ()
wrap = Y
fromTicket3018 :: Eq [a] => a -> ()
fromTicket3018 x = let {g :: Int -> Int; g = [x]==[x] `seq` id} in ()
main = undefined
|
ghc-android/ghc
|
testsuite/tests/indexed-types/should_compile/T5002.hs
|
Haskell
|
bsd-3-clause
| 661
|
{-# LANGUAGE DeriveFunctor #-}
module Game.TurnCounter
( TurnCounter (..)
, newTurnCounter
, nextTurn, nextTurnWith
, previousTurn, previousTurnWith
, currentPlayer
, nextPlayer
, previousPlayer
, currentRound
) where
import Data.List (find)
data TurnCounter p
= TurnCounter
{ tcPlayers :: [p]
, tcCounter :: Int
} deriving (Eq, Show, Functor)
newTurnCounter :: [p] -> TurnCounter p
newTurnCounter players =
TurnCounter
{ tcPlayers = players
, tcCounter = 0
}
nextTurn :: TurnCounter p -> TurnCounter p
nextTurn (TurnCounter ps c) = TurnCounter ps (c+1)
nextTurnWith :: (p -> Bool) -> TurnCounter p -> Maybe (TurnCounter p)
nextTurnWith predicate tc =
find (predicate . currentPlayer) $
take (length (tcPlayers tc)) $
iterate nextTurn (nextTurn tc)
previousTurn :: TurnCounter p -> TurnCounter p
previousTurn (TurnCounter ps c) = TurnCounter ps (c-1)
previousTurnWith :: (p -> Bool) -> TurnCounter p -> Maybe (TurnCounter p)
previousTurnWith predicate tc =
find (predicate . currentPlayer) $
take (length (tcPlayers tc)) $
iterate previousTurn (previousTurn tc)
currentPlayer :: TurnCounter p -> p
currentPlayer (TurnCounter ps c) = ps !! (c `mod` length ps)
nextPlayer :: TurnCounter p -> p
nextPlayer = currentPlayer . nextTurn
previousPlayer :: TurnCounter p -> p
previousPlayer = currentPlayer . previousTurn
currentRound :: TurnCounter p -> Int
currentRound (TurnCounter ps c) = c `div` length ps
|
timjb/halma
|
halma/src/Game/TurnCounter.hs
|
Haskell
|
mit
| 1,466
|
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
import Text.Hamlet (HtmlUrl, hamlet)
import Text.Blaze.Html.Renderer.String (renderHtml)
import Data.Text (Text)
import Yesod
data MyRoute = Home
render :: MyRoute -> [(Text, Text)] -> Text
render Home _ = "/home"
footer :: HtmlUrl MyRoute
footer = [hamlet|
<footer>
Return to #
<a href=@{Home}>Homepage
.
|]
main :: IO ()
main = putStrLn $ renderHtml $ [hamlet|
<body>
<p>This is my page.
^{footer}
|] render
|
cirquit/quizlearner
|
resources/html/footer.hs
|
Haskell
|
mit
| 497
|
module Grammar.Common.Pretty where
import Data.Text (Text)
import qualified Data.Text as Text
import Grammar.Common.Types
textShow :: Show a => a -> Text
textShow = Text.pack . show
prettyMilestone :: Maybe Division :* Maybe Paragraph -> Text
prettyMilestone (Nothing, _) = ""
prettyMilestone (Just (Division b c v s l), _)
= Text.intercalate "."
. filter (\x -> not . Text.null $ x)
$ [ms b, ms c, ms v, ms s, ms l]
where
ms Nothing = ""
ms (Just x) = textShow x
prettySource :: Show a => SourceId :* Milestone :* a -> Text
prettySource (SourceId g s, (m, x)) = Text.intercalate " " $
[ g
, s
, prettyMilestone m
, "--"
, textShow $ x
]
prettyMilestoned :: Show a => Milestone :* a -> Text
prettyMilestoned (m, x) = Text.intercalate " " $
[ prettyMilestone m
, "--"
, textShow $ x
]
prettyMilestonedString :: Milestone :* String -> Text
prettyMilestonedString (m, x) = Text.intercalate " " $
[ prettyMilestone m
, "--"
, Text.pack x
]
prettyMilestoneCtx :: Milestone :* Text :* [Text] :* [Text] -> (Text, Text, Text, Text)
prettyMilestoneCtx (m, (w, (ls, rs))) =
( prettyMilestone m
, Text.intercalate " " ls
, w
, Text.intercalate " " rs
)
|
ancientlanguage/haskell-analysis
|
grammar/src/Grammar/Common/Pretty.hs
|
Haskell
|
mit
| 1,199
|
module Hahet.Targets.Services where
import Hahet.Targets
import Hahet.Imports
type Started = Maybe Bool
data Service = Service Text Started
deriving (Typeable, Show)
instance Typeable c => Target c Service where
targetDesc _ (Service service _) = service
targetApply (Service _ Nothing) = return ResNoop
targetApply (Service _ (Just False)) = return $ ResFailed "Not yet implemented"
targetApply (Service _ (Just True)) = return $ ResFailed "Not yet implemented"
|
SimSaladin/hahet
|
src/Hahet/Targets/Services.hs
|
Haskell
|
mit
| 495
|
import Network
import System.IO
import Control.Exception
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad
import Control.Monad.Fix (fix)
type Msg = (Int, String)
filename = "primes.log"
main :: IO ()
main = do
chan <- newEmptyMVar
-- sock <- socket AF_INET Stream 0
-- setSocketOption sock ReuseAddr 1
-- bindSocket sock (SockAddrInet 4242 iNADDR_ANY)
-- listen sock 2
sock <- listenOn $ PortNumber 4242
reader <- forkIO $ fix $ \loop -> do
(nr', line) <- takeMVar chan
putStrLn $ "Results returned from slave " ++ show nr'
appendFile filename (line ++ "\n")
loop
mainLoop sock chan 0
mainLoop :: Socket -> MVar (Msg) -> Int -> IO ()
mainLoop sock chan nr = do
(handle, _, _) <- accept sock
hSetBuffering handle NoBuffering
forkIO $ runConn handle chan nr
mainLoop sock chan $! nr+1
runConn :: Handle -> MVar (Msg) -> Int -> IO ()
runConn hdl chan nr = do
let broadcast msg = putMVar chan (nr, msg)
handle (\(SomeException _) -> return ()) $ fix $ \loop -> do
line <- hGetLine hdl
broadcast line
loop
hClose hdl
|
Joss-Steward/Primality
|
logger.hs
|
Haskell
|
mit
| 1,132
|
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
import Prelude hiding ((.), id)
-- Morphisms
type (a ~> b) c = c a b
class Category (c :: k -> k -> *) where
id :: (a ~> a) c
(.) :: (y ~> z) c -> (x ~> y) c -> (x ~> z) c
type Hask = (->)
instance Category Hask where
id x = x
(f . g) x = f (g x)
|
riwsky/wiwinwlh
|
src/categories.hs
|
Haskell
|
mit
| 356
|
main= return()
|
geraldus/transient-universe
|
app/client/Transient/Move/Services/MonitorService.hs
|
Haskell
|
mit
| 15
|
module Selection where
|
fatuhoku/haskell-ball-mosaic
|
src/Selection.hs
|
Haskell
|
mit
| 24
|
module Board where
import Data.List (intercalate, unfoldr)
data Cell = O | X | E deriving (Read, Show, Eq)
data Board = Board [Cell] deriving Eq
type Index = Int
instance Show Board where
show (Board cs) =
"\n" ++ intercalate "\n" (map unwords [topRow,midRow,botRow]) ++ "\n"
where lst = map show cs
[topRow,midRow,botRow] = chunks 3 lst
-- | Found this on SO. Isn't it beautiful?
chunks :: Index -> [a] -> [[a]]
chunks n = takeWhile (not . null) . unfoldr (Just . splitAt n)
-- | The "zero board"
emptyBoard :: Board
emptyBoard = Board (replicate 9 E)
-- | Convenience function that turns Xs into Os and vice versa.
invert :: Board -> Board
invert (Board cs) = Board $ map invert' cs
where invert' X = O
invert' O = X
invert' E = E
-- | Not using Maybe because this will not be exposed.
getCell :: Index -> Board -> Cell
getCell ix (Board cs)
| 0 <= ix && ix <= 8 = cs !! ix
| otherwise = error $ "Invalid index " ++ show ix
-- | Set a cell of a board to a particular value.
-- | FIXME fail if user attempts to update non-empty cell?
setCell :: Index -> Cell -> Board -> Board
setCell ix cell (Board cs) =
Board $ cs // (ix,cell)
where ls // (n,item) = a ++ (item : b)
where (a,_:b) = splitAt n ls
-- | Functions for working with the three kinds of subsets of a board
-- | that a player can "win": rows, columns and diagonals.
rows, cols, diags :: Board -> [[Cell]]
rows (Board cs) = chunks 3 cs
cols (Board cs) =
map (col cs)
[0,1,2]
where col :: [Cell] -> Index -> [Cell]
col cs ix =
map (\n -> cs !! (ix + 3 * n))
[0,1,2]
diags (Board cs) = [diag,antidiag]
where diag = map (cs !!) [0,4,8]
antidiag = map (cs !!) [2,4,7]
|
mrkgnao/tictactoe-minimax
|
Board.hs
|
Haskell
|
mit
| 1,742
|
{-|
Copyright: (c) Guilherme Azzi, 2014
License: MIT
Maintainer: ggazzi@inf.ufrgs.br
Stability: experimental
A 'Monitor' for the CPU activity.
This module is meant to be imported qualified, e.g.:
> import qualified Reactive.Banana.Monitors.Cpu as Cpu
-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module Reactive.Banana.Monitors.Cpu
( CpuMonitor
, busy
, user
, nice
, system
, idle
, iowait
, irq
, softirq
, newMonitor
) where
import Reactive.Banana.Monitors.Class
import Reactive.Banana.Sources
import Control.Monad (zipWithM_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Reactive.Banana
import qualified Reactive.Banana.Monitors.Internal.Procfs as Procfs
-- | A monitor for the CPU activity.
--
-- Provides behaviors for the fraction of time that the
-- CPU is spending in several states.
data CpuMonitor t = CpuMonitor { busy :: Behavior t Double
, user :: Behavior t Double
, nice :: Behavior t Double
, system :: Behavior t Double
, idle :: Behavior t Double
, iowait :: Behavior t Double
, irq :: Behavior t Double
, softirq :: Behavior t Double
}
newMonitor :: IO (SourceOf CpuMonitor)
newMonitor = do
sources <- sequence . take 8 $ repeat (newBehavior 0)
let [busy, user, nice, system, idle, iowait, irq, softirq] = sources
return CpuSource
{ sbusy = busy
, suser = user
, snice = nice
, ssystem = system
, sidle = idle
, siowait = iowait
, sirq = irq
, ssoftirq = softirq
, updateCpuMonitor = updateMany sources
}
instance Monitor CpuMonitor where
data SourceOf CpuMonitor = CpuSource
{ sbusy :: BehaviorSource Double
, suser :: BehaviorSource Double
, snice :: BehaviorSource Double
, ssystem :: BehaviorSource Double
, sidle :: BehaviorSource Double
, siowait :: BehaviorSource Double
, sirq :: BehaviorSource Double
, ssoftirq :: BehaviorSource Double
, updateCpuMonitor :: [Double] -> IO ()
}
-- Just obtain all behaviors from behavior sources
fromMonitorSource src = CpuMonitor <$>
fromBehaviorSource (sbusy src) <*>
fromBehaviorSource (suser src) <*>
fromBehaviorSource (snice src) <*>
fromBehaviorSource (ssystem src) <*>
fromBehaviorSource (sidle src) <*>
fromBehaviorSource (siowait src) <*>
fromBehaviorSource (sirq src) <*>
fromBehaviorSource (ssoftirq src)
initMonitor src = do
-- Obtain an IORef with the current CPU time
initial <- Procfs.readStatCpu
cpuTimeRef <- newIORef initial
-- Use the IORef to update (comparing the previous times
-- with the current, for how much time was spent in each
-- state)
return $ checkCpu cpuTimeRef >>= updateCpuMonitor src
-- | Reads the current CPU state, updates it on the given
-- 'IORef' and returns the fraction of time spent on
-- each of the following states: busy (user + nice + system),
-- user, nice, system, idle, iowait, irq, softirq.
checkCpu :: IORef [Double] -> IO [Double]
checkCpu cref = do
-- Obtain the current and previous times
prev <- readIORef cref
curr <- Procfs.readStatCpu
-- Update the IORef
writeIORef cref curr
-- Calculate the time spent since last check
let dif = zipWith (-) curr prev
tot = sum dif
-- Calculate the fractions for each state
frac = map (nanProof . (/ tot)) dif
nanProof x = if isNaN x || isInfinite x then 0 else x
t = sum $ take 3 frac
return (t:frac)
-- | Update the given behaviors with the corresponding values.
--
-- Given @m@ 'BehaviorSource's and @n@ values, update the first
-- @min m n@ behaviors with the corresponding values.
updateMany :: [BehaviorSource a] -> [a] -> IO ()
updateMany = zipWithM_ update
|
ggazzi/hzen
|
src/Reactive/Banana/Monitors/Cpu.hs
|
Haskell
|
mit
| 4,494
|
-- chaper3.hs
safetail_1 :: [a] -> [a]
safetail_1 xs = if null xs
then []
else tail xs
safetail_2 :: [a] -> [a]
safetail_2 xs | null xs = []
| otherwise = tail xs
safetail_3 :: [a] -> [a]
safetail_3 [] = []
safetail_3 (_:xs) = xs
|
hnfmr/fp101x
|
playground/chapter3.hs
|
Haskell
|
mit
| 279
|
-- | Core functionality of the package. Import from either "System.Console.Ansigraph" or
-- "System.Console.Ansigraph.Core".
module System.Console.Ansigraph.Internal.Core where
import System.Console.ANSI
import System.IO (hFlush, stdout)
import Control.Monad.IO.Class (MonadIO, liftIO)
-- for GHC <= 7.8
import Control.Applicative
---- Basics ----
-- | ANSI colors are characterized by a 'Color' and a 'ColorIntensity'.
data AnsiColor = AnsiColor {
intensity :: ColorIntensity
, color :: Color
} deriving Show
-- | Record that holds graphing options.
data GraphSettings = GraphSettings {
-- | Foreground color for real number component.
realColor :: AnsiColor
-- | Foreground color for imaginary number component.
, imagColor :: AnsiColor
-- | Foreground color for negative real values. For matrix graphs only.
, realNegColor :: AnsiColor
-- | Foreground color for negative imaginary values. For matrix graphs only.
, imagNegColor :: AnsiColor
-- | Background color for real number component.
, realBG :: AnsiColor
-- | Background color for imaginary number component.
, imagBG :: AnsiColor
-- | Framerate in FPS.
, framerate :: Int
}
-- | 'Vivid' 'Blue' – used as the default real foreground color.
blue = AnsiColor Vivid Blue
-- | 'Vivid' 'Magenta' – used as the default foreground color for imaginary
-- graph component.
pink = AnsiColor Vivid Magenta
-- | 'Vivid' 'White' – used as the default graph background color
-- for both real and imaginary graph components.
white = AnsiColor Vivid White
-- | 'Vivid' 'Red' – used as the default foreground color for negative real component.
red = AnsiColor Vivid Red
-- | 'Dull' 'Green' – used as the default foreground color for negative imaginary component.
green = AnsiColor Dull Green
-- | 'Dull' 'Black'.
black = AnsiColor Dull Blue
-- | 'Vivid' 'Yellow'.
yellow = AnsiColor Vivid Yellow
-- | 'Vivid' 'Magenta'.
magenta = AnsiColor Vivid Magenta
-- | 'Vivid' 'Cyan'.
cyan = AnsiColor Vivid Cyan
-- | Default graph settings.
graphDefaults = GraphSettings blue pink red green white white 15
-- | Holds two 'Maybe' 'AnsiColor's representing foreground and background colors for display via ANSI.
-- 'Nothing' means use the default terminal color.
data Coloring = Coloring { foreground :: Maybe AnsiColor,
background :: Maybe AnsiColor } deriving Show
-- | A 'Coloring' representing default terminal colors, i.e. two 'Nothing's.
noColoring = Coloring Nothing Nothing
-- | Helper constructor function for 'Coloring' that takes straight 'AnsiColor's without 'Maybe'.
mkColoring :: AnsiColor -> AnsiColor -> Coloring
mkColoring c1 c2 = Coloring (Just c1) (Just c2)
-- | Projection retrieving foreground and background colors
-- for real number graphs in the form of a 'Coloring'.
realColors :: GraphSettings -> Coloring
realColors s = mkColoring (realColor s) (realBG s)
-- | Projection retrieving foreground and background colors
-- for imaginary component of complex number graphs in the form of a 'Coloring'.
imagColors :: GraphSettings -> Coloring
imagColors s = mkColoring (imagColor s) (imagBG s)
-- | Retrieves a pair of 'Coloring's for real and imaginary graph components respectively.
colorSets :: GraphSettings -> (Coloring,Coloring)
colorSets s = (realColors s, imagColors s)
-- | Swaps foreground and background colors within a 'Coloring'.
invert :: Coloring -> Coloring
invert (Coloring fg bg) = Coloring bg fg
-- | Easily create a 'Coloring' by specifying the background 'AnsiColor' and no custom foreground.
fromBG :: AnsiColor -> Coloring
fromBG c = Coloring Nothing (Just c)
-- | Easily create a 'Coloring' by specifying the foreground 'AnsiColor' and no custom background.
fromFG :: AnsiColor -> Coloring
fromFG c = Coloring (Just c) Nothing
-- | The SGR command corresponding to a particular 'ConsoleLayer' and 'AnsiColor'.
interpAnsiColor :: ConsoleLayer -> AnsiColor -> SGR
interpAnsiColor l (AnsiColor i c) = SetColor l i c
-- | Produce a (possibly empty) list of 'SGR' commands from a 'ConsoleLayer' and 'AnsiColor'.
-- An empty 'SGR' list is equivalent to 'Reset'.
sgrList :: ConsoleLayer -> Maybe AnsiColor -> [SGR]
sgrList l = fmap (interpAnsiColor l) . maybe [] pure
-- | Set the given 'AnsiColor' on the given 'ConsoleLayer'.
setColor :: MonadIO m => ConsoleLayer -> AnsiColor -> m ()
setColor l c = liftIO $ setSGR [interpAnsiColor l c]
-- | Apply both foreground and background color contained in a 'Coloring'.
applyColoring :: MonadIO m => Coloring -> m ()
applyColoring (Coloring fg bg) = liftIO $ do
setSGR [Reset]
setSGR $ sgrList Foreground fg ++ sgrList Background bg
-- | Clear any SGR settings and then flush stdout.
clear :: MonadIO m => m ()
clear = liftIO $ setSGR [Reset] >> hFlush stdout
putStrLn', putStr' :: MonadIO m => String -> m ()
putStrLn' = liftIO . putStrLn
putStr' = liftIO . putStr
-- | Clear any SGR settings, flush stdout and print a new line.
clearLn :: MonadIO m => m ()
clearLn = clear >> putStrLn' ""
-- | Use a particular ANSI 'Coloring' to print a string at the terminal (without a new line),
-- then clear all ANSI SGR codes and flush stdout.
colorStr :: MonadIO m => Coloring -> String -> m ()
colorStr c s = do
applyColoring c
putStr' s
clear
-- | Use a particular ANSI 'Coloring' to print a string at the terminal,
-- then clear all ANSI SGR codes, flush stdout and print a new line.
colorStrLn :: MonadIO m => Coloring -> String -> m ()
colorStrLn c s = do
applyColoring c
putStr' s
clearLn
-- | Like 'colorStr' but prints bold text.
boldStr :: MonadIO m => Coloring -> String -> m ()
boldStr c s = do
applyColoring c
liftIO $ setSGR [SetConsoleIntensity BoldIntensity]
putStr' s
clear
-- | Like 'colorStrLn' but prints bold text.
boldStrLn :: MonadIO m => Coloring -> String -> m ()
boldStrLn c s = boldStr c s >> putStrLn' ""
|
BlackBrane/ansigraph
|
src/System/Console/Ansigraph/Internal/Core.hs
|
Haskell
|
mit
| 5,951
|
module DevelMain where
import Control.Concurrent
import Control.Exception (finally)
import Control.Monad ((>=>))
import Data.IORef
import Data.Time.Clock
import Foreign.Store
import GHC.Word
import Main
import Network.Wai.Handler.Warp
-- | Start or restart the server.
-- newStore is from foreign-store.
-- A Store holds onto some data across ghci reloads
update :: IO ()
update = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
-- no server running
Nothing -> do
done <- storeAction doneStore newEmptyMVar
tid <- start done
_ <- storeAction (Store tidStoreNum) (newIORef tid)
return ()
-- server is already running
Just tidStore -> restartAppInNewThread tidStore
where
doneStore :: Store (MVar ())
doneStore = Store 0
-- shut the server down with killThread and wait for the done signal
restartAppInNewThread :: Store (IORef ThreadId) -> IO ()
restartAppInNewThread tidStore = modifyStoredIORef tidStore $ \tid -> do
killThread tid
withStore doneStore takeMVar
readStore doneStore >>= start
-- | Start the server in a separate thread.
start :: MVar () -- ^ Written to when the thread is killed.
-> IO ThreadId
start done = do
app <- gitIssuesServerApp
tid <- forkIO (finally (runSettings (setPort 3000 defaultSettings) app)
-- Note that this implies concurrency
-- between shutdownApp and the next app that is starting.
-- Normally this should be fine
(putMVar done ()))
writeFile "devel-main-since" =<< show <$> getCurrentTime
return tid
-- | kill the server
shutdown :: IO ()
shutdown = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
-- no server running
Nothing -> putStrLn "no Yesod app running"
Just tidStore -> do
withStore tidStore $ readIORef >=> killThread
putStrLn "Yesod app is shutdown"
tidStoreNum :: Word32
tidStoreNum = 1
modifyStoredIORef :: Store (IORef a) -> (a -> IO a) -> IO ()
modifyStoredIORef store f = withStore store $ \ref -> do
v <- readIORef ref
f v >>= writeIORef ref
|
yamadapc/git-issues
|
src/DevelMain.hs
|
Haskell
|
mit
| 2,358
|
module PerfectNumbers (classify, Classification(..)) where
data Classification = Deficient | Perfect | Abundant deriving (Eq, Show)
classify :: Int -> Maybe Classification
classify = error "You need to implement this function."
|
exercism/xhaskell
|
exercises/practice/perfect-numbers/src/PerfectNumbers.hs
|
Haskell
|
mit
| 230
|
import Data.List
parts :: [Integer] -> [[(Integer, Integer)]]
parts ps = foldl' f [] (reverse ps)
where
f [] price = [(price, price)] : []
f result@(cur@((price', maxprice) : _) : rest') price | price > maxprice = [(price, price)] : result
| otherwise = ((price, maxprice) : cur) : rest'
sol = sum . (map (sum . (map (uncurry $ flip (-)))))
explode = unfoldr f
where f str = let (chunk, rest) = span (/= ' ') str in if null chunk then Nothing else if null rest then Just (chunk, rest) else Just (chunk, tail rest)
tst = getLine >> getLine >>= (putStrLn . show . sol . parts . (map read) . explode)
main = getLine >>= (\t -> mapM_ (const tst) [1 .. (read t)])
|
pbl64k/CodeSprints
|
CodeSprint-2012-02-25-Systems/StockTrading/st.accepted.hs
|
Haskell
|
bsd-2-clause
| 753
|
{-# LANGUAGE OverloadedStrings #-}
module Handler.TimesGallery where
import Import
import qualified Data.Map as M
import Andon.Types
import Andon.ClassData
import Andon.Gallery
getTimesGalleryR :: OrdInt -> Handler RepHtml
getTimesGalleryR times = defaultLayout $ do
setTitle $ toHtml $ "Gallery " ++ show times
$(widgetFile "times-gallery")
where
classes = filter ((== times) . getTimes) classData
|
amutake/andon-yesod
|
Handler/TimesGallery.hs
|
Haskell
|
bsd-2-clause
| 416
|
{-# LANGUAGE FlexibleInstances #-}
import Test.Framework (defaultMain)
import Data.Object.Json
import Data.Object
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit hiding (Test)
import Test.QuickCheck (Arbitrary (..), oneof)
import Control.Applicative
import Numeric
import qualified Data.ByteString.Char8 as S8
input :: String
input = "{\"this\":[\"is\",\"a\",\"sample\"],\"numbers\":[5,6,7890,\"456\",1234567890]}"
output :: StringObject
output = Mapping
[ ("numbers", Sequence $ map Scalar
[ "5"
, "6"
, "7890"
, "456"
, "1234567890"
])
, ("this", Sequence $ map Scalar ["is", "a", "sample"])
]
caseInputOutput :: Assertion
caseInputOutput = do
so <- decode $ S8.pack input
output @=? so
propInputOutput :: StringObject -> Bool
propInputOutput so = decode (encode so) == Just so
main :: IO ()
main = defaultMain
[ testCase "caseInputOutput" caseInputOutput
, testProperty "propInputOutput" propInputOutput
, testProperty "propShowSignedInt" propShowSignedInt
]
instance Arbitrary (Object String String) where
arbitrary = oneof
[ Scalar <$> arbitrary
, do
i <- arbitrary
let s = showSignedInt (i * 1000000000 :: Integer)
return $ Scalar s
, do
a <- arbitrary
b <- arbitrary
return $ Sequence [a, b]
, do
k1 <- arbitrary
v1 <- arbitrary
return $ Mapping [(k1, v1)]
]
propShowSignedInt :: Integer -> Bool
propShowSignedInt i = read (showSignedInt i) == i
showSignedInt :: Integral a => a -> String
showSignedInt i
| i < 0 = '-' : showSignedInt (negate i)
| otherwise = showInt i ""
|
snoyberg/data-object-json
|
runtests.hs
|
Haskell
|
bsd-2-clause
| 2,098
|
module Main (main) where
import Control.Monad (when)
import Bankotrav.Formatting
import Bankotrav.Random
import Bankotrav.Compression
main :: IO ()
main = do
putStrLn "Generating random board..."
board <- randomBoardIO
putStr $ formatBoard board
putStrLn "Compressing board..."
let idx = compressBoard board
putStrLn ("Board index: " ++ show idx ++ "; binary: " ++ formatBinary idx)
putStrLn "Decompressing board..."
let board' = decompressBoard idx
putStr $ formatBoard board'
when (board /= board') $ putStrLn "BOARDS NOT EQUAL!"
|
Athas/banko
|
bankotrav/src/bankotrav.hs
|
Haskell
|
bsd-2-clause
| 556
|
module Hint.GHC (
module GHC,
module Outputable,
module ErrUtils, Message,
module Pretty,
module DriverPhases,
module StringBuffer,
module Lexer,
module Parser,
module DynFlags,
module FastString,
#if __GLASGOW_HASKELL__ >= 610
module Control.Monad.Ghc,
module HscTypes,
module Bag,
#endif
#if __GLASGOW_HASKELL__ >= 608
module PprTyThing,
#elif __GLASGOW_HASKELL__ < 608
module SrcLoc,
#endif
#if __GLASGOW_HASKELL__ >= 702
module SrcLoc,
#endif
#if __GLASGOW_HASKELL__ >= 708
module ConLike,
#endif
)
where
#if __GLASGOW_HASKELL__ >= 610
import GHC hiding ( Phase, GhcT, runGhcT )
import Control.Monad.Ghc ( GhcT, runGhcT )
import HscTypes ( SourceError, srcErrorMessages, GhcApiError )
import Bag ( bagToList )
#else
import GHC hiding ( Phase )
#endif
import Outputable ( PprStyle, SDoc, Outputable(ppr),
showSDoc, showSDocForUser, showSDocUnqual,
withPprStyle, defaultErrStyle )
import ErrUtils ( mkLocMessage )
#if __GLASGOW_HASKELL__ < 706
import ErrUtils ( Message )
#else
import ErrUtils ( MsgDoc ) -- we alias it as Message below
#endif
import Pretty ( Doc )
import DriverPhases ( Phase(Cpp), HscSource(HsSrcFile) )
import StringBuffer ( stringToStringBuffer )
import Lexer ( P(..), ParseResult(..), mkPState )
import Parser ( parseStmt, parseType )
import FastString ( fsLit )
#if __GLASGOW_HASKELL__ >= 700
import DynFlags ( supportedLanguagesAndExtensions, xFlags, xopt )
#else
import DynFlags ( supportedLanguages )
#endif
#if __GLASGOW_HASKELL__ >=704
import DynFlags ( LogAction )
#endif
#if __GLASGOW_HASKELL__ >= 608
import PprTyThing ( pprTypeForUser )
#elif __GLASGOW_HASKELL__ < 608
import SrcLoc ( SrcSpan )
#endif
#if __GLASGOW_HASKELL__ >= 702
import SrcLoc ( mkRealSrcLoc )
#endif
#if __GLASGOW_HASKELL__ >= 708
import ConLike ( ConLike(RealDataCon) )
#endif
#if __GLASGOW_HASKELL__ >= 706
type Message = MsgDoc
#endif
|
flowbox-public/hint
|
src/Hint/GHC.hs
|
Haskell
|
bsd-3-clause
| 2,033
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoRebindableSyntax #-}
module Duckling.Numeral.FA.Rules
( rules ) where
import Control.Monad (join)
import Data.HashMap.Strict (HashMap)
import Data.Maybe
import Data.String
import Data.Text (Text)
import Prelude
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
zeroNineteenMap :: HashMap Text Integer
zeroNineteenMap = HashMap.fromList
[ ("صفر", 0)
, ("یک", 1)
, ("دو", 2)
, ("سه", 3)
, ("چهار", 4)
, ("پنج", 5)
, ("شش", 6)
, ("شیش", 6)
, ("هفت", 7)
, ("هشت", 8)
, ("نه", 9)
, ("ده", 10)
, ("یازده", 11)
, ("دوازده", 12)
, ("سیزده", 13)
, ("چهارده", 14)
, ("پانزده", 15)
, ("پونزده", 15)
, ("شانزده", 16)
, ("شونزده", 16)
, ("هفده", 17)
, ("هیفده", 17)
, ("هجده", 18)
, ("هیجده", 18)
, ("نوزده", 19)
]
ruleToNineteen :: Rule
ruleToNineteen = Rule
{ name = "integer (0..19)"
, pattern =
[ regex "(صفر|یک|سه|چهارده|چهار|پنج|شی?ش|هفت|هشت|نه|یازده|دوازده|سیزده|پ(ا|و)نزده|ش(ا|و)نزده|هی?فده|هی?جده|نوزده|ده|دو)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
let x = Text.toLower match in
(HashMap.lookup x zeroNineteenMap >>= integer)
_ -> Nothing
}
tensMap :: HashMap Text Integer
tensMap = HashMap.fromList
[ ( "بیست" , 20 )
, ( "سی" , 30 )
, ( "چهل" , 40 )
, ( "پنجاه" , 50 )
, ( "شصت" , 60 )
, ( "هفتاد" , 70 )
, ( "هشتاد" , 80 )
, ( "نود" , 90 )
, ( "صد" , 100 )
, ( "دویست" , 200 )
, ( "سیصد" , 300 )
, ( "سی صد" , 300 )
, ( "چهارصد" , 400 )
, ( "چهار صد" , 400 )
, ( "پانصد" , 500 )
, ( "پونصد" , 500 )
, ( "شیشصد" , 600 )
, ( "شیش صد" , 600 )
, ( "ششصد" , 600 )
, ( "شش صد" , 600 )
, ( "هفتصد" , 700 )
, ( "هفت صد" , 700 )
, ( "هشتصد" , 800 )
, ( "هشت صد" , 800 )
, ( "نهصد" , 900 )
, ( "نه صد" , 900 )
]
ruleTens :: Rule
ruleTens = Rule
{ name = "integer (20..90)"
, pattern =
[ regex "(دویست|(سی|چهار|پان|پون|شی?ش|هفت|هشت|نه)? ?صد|بیست|سی|چهل|پنجاه|شصت|هفتاد|هشتاد|نود)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) tensMap >>= integer
_ -> Nothing
}
rulePowersOfTen :: Rule
rulePowersOfTen = Rule
{ name = "powers of tens"
, pattern =
[ regex "(هزار|میلیون|ملیون|میلیارد)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"هزار" -> double 1e3 >>= withGrain 2 >>= withMultipliable
"میلیون" -> double 1e6 >>= withGrain 3 >>= withMultipliable
"ملیون" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"میلیارد" -> double 1e9 >>= withGrain 9 >>= withMultipliable
_ -> Nothing
_ -> Nothing
}
ruleCompositeTens :: Rule
ruleCompositeTens = Rule
{ name = "integer 21..99"
, pattern =
[ oneOf [20,30..90]
, regex "و"
, numberBetween 1 10
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = tens}:
_:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ tens + units
_ -> Nothing
}
ruleCompositeHundred :: Rule
ruleCompositeHundred = Rule
{ name = "integer 21..99"
, pattern =
[ oneOf [100,200..900]
, regex "و"
, numberBetween 1 100
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = tens}:
_:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ tens + units
_ -> Nothing
}
ruleSum :: Rule
ruleSum = Rule
{ name = "intersect 2 numbers"
, pattern =
[ Predicate $ and . sequence [hasGrain, isPositive]
, Predicate $ and . sequence [not . isMultipliable, isPositive]
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleSumAnd :: Rule
ruleSumAnd = Rule
{ name = "intersect 2 numbers (with and)"
, pattern =
[ Predicate $ and . sequence [hasGrain, isPositive]
, regex "و"
, Predicate $ and . sequence [not . isMultipliable, isPositive]
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
_:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleMultiply :: Rule
ruleMultiply = Rule
{ name = "compose by multiplication"
, pattern =
[ dimension Numeral
, Predicate isMultipliable
]
, prod = \tokens -> case tokens of
(token1:token2:_) -> multiply token1 token2
_ -> Nothing
}
numeralToStringMap :: HashMap Char String
numeralToStringMap =
HashMap.fromList
[ ('۰', "0")
, ('۱', "1")
, ('۲', "2")
, ('۳', "3")
, ('۴', "4")
, ('۵', "5")
, ('۶', "6")
, ('۷', "7")
, ('۸', "8")
, ('۹', "9")
]
parseIntAsText :: Text -> Text
parseIntAsText =
Text.pack
. join
. mapMaybe (`HashMap.lookup` numeralToStringMap)
. Text.unpack
parseIntegerFromText :: Text -> Maybe Integer
parseIntegerFromText = parseInteger . parseIntAsText
ruleIntegerNumeric :: Rule
ruleIntegerNumeric = Rule
{ name = "Persian integer numeric"
, pattern =
[ regex "([۰-۹]{1,18})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseIntegerFromText match >>= integer
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleIntegerNumeric
, ruleToNineteen
, ruleTens
, rulePowersOfTen
, ruleCompositeTens
, ruleCompositeHundred
, ruleSum
, ruleSumAnd
, ruleMultiply
]
|
facebookincubator/duckling
|
Duckling/Numeral/FA/Rules.hs
|
Haskell
|
bsd-3-clause
| 6,842
|
{-
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2001-2003
--
-- Access to system tools: gcc, cp, rm etc
--
-----------------------------------------------------------------------------
-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module SysTools (
-- Initialisation
initSysTools,
-- Interface to system tools
runUnlit, runCpp, runCc, -- [Option] -> IO ()
runPp, -- [Option] -> IO ()
runSplit, -- [Option] -> IO ()
runAs, runLink, runLibtool, -- [Option] -> IO ()
runMkDLL,
runWindres,
runLlvmOpt,
runLlvmLlc,
runClang,
figureLlvmVersion,
readElfSection,
getLinkerInfo,
getCompilerInfo,
linkDynLib,
askCc,
touch, -- String -> String -> IO ()
copy,
copyWithHeader,
-- Temporary-file management
setTmpDir,
newTempName,
cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
addFilesToClean,
Option(..)
) where
#include "HsVersions.h"
import DriverPhases
import Module
import Packages
import Config
import Outputable
import ErrUtils
import Panic
import Platform
import Util
import DynFlags
import Exception
import Data.IORef
import Control.Monad
import System.Exit
import System.Environment
import System.FilePath
import System.IO
import System.IO.Error as IO
import System.Directory
import Data.Char
import Data.List
import qualified Data.Map as Map
import Text.ParserCombinators.ReadP hiding (char)
import qualified Text.ParserCombinators.ReadP as R
#ifndef mingw32_HOST_OS
import qualified System.Posix.Internals
#else /* Must be Win32 */
import Foreign
import Foreign.C.String
#endif
import System.Process
import Control.Concurrent
import FastString
import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
#ifdef mingw32_HOST_OS
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
{-
How GHC finds its files
~~~~~~~~~~~~~~~~~~~~~~~
[Note topdir]
GHC needs various support files (library packages, RTS etc), plus
various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
the root of GHC's support files
On Unix:
- ghc always has a shell wrapper that passes a -B<dir> option
On Windows:
- ghc never has a shell wrapper.
- we can find the location of the ghc binary, which is
$topdir/bin/<something>.exe
where <something> may be "ghc", "ghc-stage2", or similar
- we strip off the "bin/<something>.exe" to leave $topdir.
from topdir we can find package.conf, ghc-asm, etc.
SysTools.initSysProgs figures out exactly where all the auxiliary programs
are, and initialises mutable variables to make it easy to call them.
To to this, it makes use of definitions in Config.hs, which is a Haskell
file containing variables whose value is figured out by the build system.
Config.hs contains two sorts of things
cGCC, The *names* of the programs
cCPP e.g. cGCC = gcc
cUNLIT cCPP = gcc -E
etc They do *not* include paths
cUNLIT_DIR The *path* to the directory containing unlit, split etc
cSPLIT_DIR *relative* to the root of the build tree,
for use when running *in-place* in a build tree (only)
---------------------------------------------
NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
Another hair-brained scheme for simplifying the current tool location
nightmare in GHC: Simon originally suggested using another
configuration file along the lines of GCC's specs file - which is fine
except that it means adding code to read yet another configuration
file. What I didn't notice is that the current package.conf is
general enough to do this:
Package
{name = "tools", import_dirs = [], source_dirs = [],
library_dirs = [], hs_libraries = [], extra_libraries = [],
include_dirs = [], c_includes = [], package_deps = [],
extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
extra_cc_opts = [], extra_ld_opts = []}
Which would have the advantage that we get to collect together in one
place the path-specific package stuff with the path-specific tool
stuff.
End of NOTES
---------------------------------------------
************************************************************************
* *
\subsection{Initialisation}
* *
************************************************************************
-}
initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
-> IO Settings -- Set all the mutable variables above, holding
-- (a) the system programs
-- (b) the package-config file
-- (c) the GHC usage message
initSysTools mbMinusB
= do top_dir <- findTopDir mbMinusB
-- see [Note topdir]
-- NB: top_dir is assumed to be in standard Unix
-- format, '/' separated
let settingsFile = top_dir </> "settings"
platformConstantsFile = top_dir </> "platformConstants"
installed :: FilePath -> FilePath
installed file = top_dir </> file
settingsStr <- readFile settingsFile
platformConstantsStr <- readFile platformConstantsFile
mySettings <- case maybeReadFuzzy settingsStr of
Just s ->
return s
Nothing ->
pgmError ("Can't parse " ++ show settingsFile)
platformConstants <- case maybeReadFuzzy platformConstantsStr of
Just s ->
return s
Nothing ->
pgmError ("Can't parse " ++
show platformConstantsFile)
let getSetting key = case lookup key mySettings of
Just xs ->
return $ case stripPrefix "$topdir" xs of
Just [] ->
top_dir
Just xs'@(c:_)
| isPathSeparator c ->
top_dir ++ xs'
_ ->
xs
Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
getBooleanSetting key = case lookup key mySettings of
Just "YES" -> return True
Just "NO" -> return False
Just xs -> pgmError ("Bad value for " ++ show key ++ ": " ++ show xs)
Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
readSetting key = case lookup key mySettings of
Just xs ->
case maybeRead xs of
Just v -> return v
Nothing -> pgmError ("Failed to read " ++ show key ++ " value " ++ show xs)
Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
targetArch <- readSetting "target arch"
targetOS <- readSetting "target os"
targetWordSize <- readSetting "target word size"
targetUnregisterised <- getBooleanSetting "Unregisterised"
targetHasGnuNonexecStack <- readSetting "target has GNU nonexec stack"
targetHasIdentDirective <- readSetting "target has .ident directive"
targetHasSubsectionsViaSymbols <- readSetting "target has subsections via symbols"
myExtraGccViaCFlags <- getSetting "GCC extra via C opts"
-- On Windows, mingw is distributed with GHC,
-- so we look in TopDir/../mingw/bin
-- It would perhaps be nice to be able to override this
-- with the settings file, but it would be a little fiddly
-- to make that possible, so for now you can't.
gcc_prog <- getSetting "C compiler command"
gcc_args_str <- getSetting "C compiler flags"
cpp_prog <- getSetting "Haskell CPP command"
cpp_args_str <- getSetting "Haskell CPP flags"
let unreg_gcc_args = if targetUnregisterised
then ["-DNO_REGS", "-DUSE_MINIINTERPRETER"]
else []
-- TABLES_NEXT_TO_CODE affects the info table layout.
tntc_gcc_args
| mkTablesNextToCode targetUnregisterised
= ["-DTABLES_NEXT_TO_CODE"]
| otherwise = []
cpp_args= map Option (words cpp_args_str)
gcc_args = map Option (words gcc_args_str
++ unreg_gcc_args
++ tntc_gcc_args)
ldSupportsCompactUnwind <- getBooleanSetting "ld supports compact unwind"
ldSupportsBuildId <- getBooleanSetting "ld supports build-id"
ldSupportsFilelist <- getBooleanSetting "ld supports filelist"
ldIsGnuLd <- getBooleanSetting "ld is GNU ld"
perl_path <- getSetting "perl command"
let pkgconfig_path = installed "package.conf.d"
ghc_usage_msg_path = installed "ghc-usage.txt"
ghci_usage_msg_path = installed "ghci-usage.txt"
-- For all systems, unlit, split, mangle are GHC utilities
-- architecture-specific stuff is done when building Config.hs
unlit_path = installed cGHC_UNLIT_PGM
-- split is a Perl script
split_script = installed cGHC_SPLIT_PGM
windres_path <- getSetting "windres command"
libtool_path <- getSetting "libtool command"
tmpdir <- getTemporaryDirectory
touch_path <- getSetting "touch command"
let -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
-- a call to Perl to get the invocation of split.
-- On Unix, scripts are invoked using the '#!' method. Binary
-- installations of GHC on Unix place the correct line on the
-- front of the script at installation time, so we don't want
-- to wire-in our knowledge of $(PERL) on the host system here.
(split_prog, split_args)
| isWindowsHost = (perl_path, [Option split_script])
| otherwise = (split_script, [])
mkdll_prog <- getSetting "dllwrap command"
let mkdll_args = []
-- cpp is derived from gcc on all platforms
-- HACK, see setPgmP below. We keep 'words' here to remember to fix
-- Config.hs one day.
-- Other things being equal, as and ld are simply gcc
gcc_link_args_str <- getSetting "C compiler link flags"
let as_prog = gcc_prog
as_args = gcc_args
ld_prog = gcc_prog
ld_args = gcc_args ++ map Option (words gcc_link_args_str)
-- We just assume on command line
lc_prog <- getSetting "LLVM llc command"
lo_prog <- getSetting "LLVM opt command"
let platform = Platform {
platformArch = targetArch,
platformOS = targetOS,
platformWordSize = targetWordSize,
platformUnregisterised = targetUnregisterised,
platformHasGnuNonexecStack = targetHasGnuNonexecStack,
platformHasIdentDirective = targetHasIdentDirective,
platformHasSubsectionsViaSymbols = targetHasSubsectionsViaSymbols
}
return $ Settings {
sTargetPlatform = platform,
sTmpDir = normalise tmpdir,
sGhcUsagePath = ghc_usage_msg_path,
sGhciUsagePath = ghci_usage_msg_path,
sTopDir = top_dir,
sRawSettings = mySettings,
sExtraGccViaCFlags = words myExtraGccViaCFlags,
sSystemPackageConfig = pkgconfig_path,
sLdSupportsCompactUnwind = ldSupportsCompactUnwind,
sLdSupportsBuildId = ldSupportsBuildId,
sLdSupportsFilelist = ldSupportsFilelist,
sLdIsGnuLd = ldIsGnuLd,
sPgm_L = unlit_path,
sPgm_P = (cpp_prog, cpp_args),
sPgm_F = "",
sPgm_c = (gcc_prog, gcc_args),
sPgm_s = (split_prog,split_args),
sPgm_a = (as_prog, as_args),
sPgm_l = (ld_prog, ld_args),
sPgm_dll = (mkdll_prog,mkdll_args),
sPgm_T = touch_path,
sPgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan",
sPgm_windres = windres_path,
sPgm_libtool = libtool_path,
sPgm_lo = (lo_prog,[]),
sPgm_lc = (lc_prog,[]),
-- Hans: this isn't right in general, but you can
-- elaborate it in the same way as the others
sOpt_L = [],
sOpt_P = [],
sOpt_F = [],
sOpt_c = [],
sOpt_a = [],
sOpt_l = [],
sOpt_windres = [],
sOpt_lo = [],
sOpt_lc = [],
sPlatformConstants = platformConstants
}
-- returns a Unix-format path (relying on getBaseDir to do so too)
findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
-> IO String -- TopDir (in Unix format '/' separated)
findTopDir (Just minusb) = return (normalise minusb)
findTopDir Nothing
= do -- Get directory of executable
maybe_exec_dir <- getBaseDir
case maybe_exec_dir of
-- "Just" on Windows, "Nothing" on unix
Nothing -> throwGhcExceptionIO (InstallationError "missing -B<dir> option")
Just dir -> return dir
{-
************************************************************************
* *
\subsection{Running an external program}
* *
************************************************************************
-}
runUnlit :: DynFlags -> [Option] -> IO ()
runUnlit dflags args = do
let prog = pgm_L dflags
opts = getOpts dflags opt_L
runSomething dflags "Literate pre-processor" prog
(map Option opts ++ args)
runCpp :: DynFlags -> [Option] -> IO ()
runCpp dflags args = do
let (p,args0) = pgm_P dflags
args1 = map Option (getOpts dflags opt_P)
args2 = if gopt Opt_WarnIsError dflags
then [Option "-Werror"]
else []
mb_env <- getGccEnv args2
runSomethingFiltered dflags id "C pre-processor" p
(args0 ++ args1 ++ args2 ++ args) mb_env
runPp :: DynFlags -> [Option] -> IO ()
runPp dflags args = do
let prog = pgm_F dflags
opts = map Option (getOpts dflags opt_F)
runSomething dflags "Haskell pre-processor" prog (args ++ opts)
runCc :: DynFlags -> [Option] -> IO ()
runCc dflags args = do
let (p,args0) = pgm_c dflags
args1 = map Option (getOpts dflags opt_c)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
runSomethingFiltered dflags cc_filter "C Compiler" p args2 mb_env
where
-- discard some harmless warnings from gcc that we can't turn off
cc_filter = unlines . doFilter . lines
{-
gcc gives warnings in chunks like so:
In file included from /foo/bar/baz.h:11,
from /foo/bar/baz2.h:22,
from wibble.c:33:
/foo/flibble:14: global register variable ...
/foo/flibble:15: warning: call-clobbered r...
We break it up into its chunks, remove any call-clobbered register
warnings from each chunk, and then delete any chunks that we have
emptied of warnings.
-}
doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
-- We can't assume that the output will start with an "In file inc..."
-- line, so we start off expecting a list of warnings rather than a
-- location stack.
chunkWarnings :: [String] -- The location stack to use for the next
-- list of warnings
-> [String] -- The remaining lines to look at
-> [([String], [String])]
chunkWarnings loc_stack [] = [(loc_stack, [])]
chunkWarnings loc_stack xs
= case break loc_stack_start xs of
(warnings, lss:xs') ->
case span loc_start_continuation xs' of
(lsc, xs'') ->
(loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
_ -> [(loc_stack, xs)]
filterWarnings :: [([String], [String])] -> [([String], [String])]
filterWarnings [] = []
-- If the warnings are already empty then we are probably doing
-- something wrong, so don't delete anything
filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
[] -> filterWarnings zs
ys' -> (xs, ys') : filterWarnings zs
unChunkWarnings :: [([String], [String])] -> [String]
unChunkWarnings [] = []
unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
loc_stack_start s = "In file included from " `isPrefixOf` s
loc_start_continuation s = " from " `isPrefixOf` s
wantedWarning w
| "warning: call-clobbered register used" `isContainedIn` w = False
| otherwise = True
isContainedIn :: String -> String -> Bool
xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
askCc :: DynFlags -> [Option] -> IO String
askCc dflags args = do
let (p,args0) = pgm_c dflags
args1 = map Option (getOpts dflags opt_c)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
runSomethingWith dflags "gcc" p args2 $ \real_args ->
readCreateProcess (proc p real_args){ env = mb_env }
-- Version of System.Process.readProcessWithExitCode that takes an environment
readCreateProcess
:: CreateProcess
-> IO (ExitCode, String) -- ^ stdout
readCreateProcess proc = do
(_, Just outh, _, pid) <-
createProcess proc{ std_out = CreatePipe }
-- fork off a thread to start consuming the output
output <- hGetContents outh
outMVar <- newEmptyMVar
_ <- forkIO $ evaluate (length output) >> putMVar outMVar ()
-- wait on the output
takeMVar outMVar
hClose outh
-- wait on the process
ex <- waitForProcess pid
return (ex, output)
readProcessEnvWithExitCode
:: String -- ^ program path
-> [String] -- ^ program args
-> [(String, String)] -- ^ environment to override
-> IO (ExitCode, String, String) -- ^ (exit_code, stdout, stderr)
readProcessEnvWithExitCode prog args env_update = do
current_env <- getEnvironment
let new_env = env_update ++ [ (k, v)
| let overriden_keys = map fst env_update
, (k, v) <- current_env
, k `notElem` overriden_keys
]
p = proc prog args
(_stdin, Just stdoh, Just stdeh, pid) <-
createProcess p{ std_out = CreatePipe
, std_err = CreatePipe
, env = Just new_env
}
outMVar <- newEmptyMVar
errMVar <- newEmptyMVar
_ <- forkIO $ do
stdo <- hGetContents stdoh
_ <- evaluate (length stdo)
putMVar outMVar stdo
_ <- forkIO $ do
stde <- hGetContents stdeh
_ <- evaluate (length stde)
putMVar errMVar stde
out <- takeMVar outMVar
hClose stdoh
err <- takeMVar errMVar
hClose stdeh
ex <- waitForProcess pid
return (ex, out, err)
-- Don't let gcc localize version info string, #8825
en_locale_env :: [(String, String)]
en_locale_env = [("LANGUAGE", "en")]
-- If the -B<dir> option is set, add <dir> to PATH. This works around
-- a bug in gcc on Windows Vista where it can't find its auxiliary
-- binaries (see bug #1110).
getGccEnv :: [Option] -> IO (Maybe [(String,String)])
getGccEnv opts =
if null b_dirs
then return Nothing
else do env <- getEnvironment
return (Just (map mangle_path env))
where
(b_dirs, _) = partitionWith get_b_opt opts
get_b_opt (Option ('-':'B':dir)) = Left dir
get_b_opt other = Right other
mangle_path (path,paths) | map toUpper path == "PATH"
= (path, '\"' : head b_dirs ++ "\";" ++ paths)
mangle_path other = other
runSplit :: DynFlags -> [Option] -> IO ()
runSplit dflags args = do
let (p,args0) = pgm_s dflags
runSomething dflags "Splitter" p (args0++args)
runAs :: DynFlags -> [Option] -> IO ()
runAs dflags args = do
let (p,args0) = pgm_a dflags
args1 = map Option (getOpts dflags opt_a)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
runSomethingFiltered dflags id "Assembler" p args2 mb_env
-- | Run the LLVM Optimiser
runLlvmOpt :: DynFlags -> [Option] -> IO ()
runLlvmOpt dflags args = do
let (p,args0) = pgm_lo dflags
args1 = map Option (getOpts dflags opt_lo)
runSomething dflags "LLVM Optimiser" p (args0 ++ args1 ++ args)
-- | Run the LLVM Compiler
runLlvmLlc :: DynFlags -> [Option] -> IO ()
runLlvmLlc dflags args = do
let (p,args0) = pgm_lc dflags
args1 = map Option (getOpts dflags opt_lc)
runSomething dflags "LLVM Compiler" p (args0 ++ args1 ++ args)
-- | Run the clang compiler (used as an assembler for the LLVM
-- backend on OS X as LLVM doesn't support the OS X system
-- assembler)
runClang :: DynFlags -> [Option] -> IO ()
runClang dflags args = do
-- we simply assume its available on the PATH
let clang = "clang"
-- be careful what options we call clang with
-- see #5903 and #7617 for bugs caused by this.
(_,args0) = pgm_a dflags
args1 = map Option (getOpts dflags opt_a)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
Exception.catch (do
runSomethingFiltered dflags id "Clang (Assembler)" clang args2 mb_env
)
(\(err :: SomeException) -> do
errorMsg dflags $
text ("Error running clang! you need clang installed to use the" ++
"LLVM backend") $+$
text "(or GHC tried to execute clang incorrectly)"
throwIO err
)
-- | Figure out which version of LLVM we are running this session
figureLlvmVersion :: DynFlags -> IO (Maybe Int)
figureLlvmVersion dflags = do
let (pgm,opts) = pgm_lc dflags
args = filter notNull (map showOpt opts)
-- we grab the args even though they should be useless just in
-- case the user is using a customised 'llc' that requires some
-- of the options they've specified. llc doesn't care what other
-- options are specified when '-version' is used.
args' = args ++ ["-version"]
ver <- catchIO (do
(pin, pout, perr, _) <- runInteractiveProcess pgm args'
Nothing Nothing
{- > llc -version
Low Level Virtual Machine (http://llvm.org/):
llvm version 2.8 (Ubuntu 2.8-0Ubuntu1)
...
-}
hSetBinaryMode pout False
_ <- hGetLine pout
vline <- hGetLine pout
v <- case filter isDigit vline of
[] -> fail "no digits!"
[x] -> fail $ "only 1 digit! (" ++ show x ++ ")"
(x:y:_) -> return ((read [x,y]) :: Int)
hClose pin
hClose pout
hClose perr
return $ Just v
)
(\err -> do
debugTraceMsg dflags 2
(text "Error (figuring out LLVM version):" <+>
text (show err))
errorMsg dflags $ vcat
[ text "Warning:", nest 9 $
text "Couldn't figure out LLVM version!" $$
text "Make sure you have installed LLVM"]
return Nothing)
return ver
{- Note [Windows stack usage]
See: Trac #8870 (and #8834 for related info)
On Windows, occasionally we need to grow the stack. In order to do
this, we would normally just bump the stack pointer - but there's a
catch on Windows.
If the stack pointer is bumped by more than a single page, then the
pages between the initial pointer and the resulting location must be
properly committed by the Windows virtual memory subsystem. This is
only needed in the event we bump by more than one page (i.e 4097 bytes
or more).
Windows compilers solve this by emitting a call to a special function
called _chkstk, which does this committing of the pages for you.
The reason this was causing a segfault was because due to the fact the
new code generator tends to generate larger functions, we needed more
stack space in GHC itself. In the x86 codegen, we needed approximately
~12kb of stack space in one go, which caused the process to segfault,
as the intervening pages were not committed.
In the future, we should do the same thing, to make the problem
completely go away. In the mean time, we're using a workaround: we
instruct the linker to specify the generated PE as having an initial
reserved stack size of 8mb, as well as a initial *committed* stack
size of 8mb. The default committed size was previously only 4k.
Theoretically it's possible to still hit this problem if you request a
stack bump of more than 8mb in one go. But the amount of code
necessary is quite large, and 8mb "should be more than enough for
anyone" right now (he said, before millions of lines of code cried out
in terror).
-}
{- Note [Run-time linker info]
See also: Trac #5240, Trac #6063
Before 'runLink', we need to be sure to get the relevant information
about the linker we're using at runtime to see if we need any extra
options. For example, GNU ld requires '--reduce-memory-overheads' and
'--hash-size=31' in order to use reasonable amounts of memory (see
trac #5240.) But this isn't supported in GNU gold.
Generally, the linker changing from what was detected at ./configure
time has always been possible using -pgml, but on Linux it can happen
'transparently' by installing packages like binutils-gold, which
change what /usr/bin/ld actually points to.
Clang vs GCC notes:
For gcc, 'gcc -Wl,--version' gives a bunch of output about how to
invoke the linker before the version information string. For 'clang',
the version information for 'ld' is all that's output. For this
reason, we typically need to slurp up all of the standard error output
and look through it.
Other notes:
We cache the LinkerInfo inside DynFlags, since clients may link
multiple times. The definition of LinkerInfo is there to avoid a
circular dependency.
-}
neededLinkArgs :: LinkerInfo -> [Option]
neededLinkArgs (GnuLD o) = o
neededLinkArgs (GnuGold o) = o
neededLinkArgs (DarwinLD o) = o
neededLinkArgs (SolarisLD o) = o
neededLinkArgs UnknownLD = []
-- Grab linker info and cache it in DynFlags.
getLinkerInfo :: DynFlags -> IO LinkerInfo
getLinkerInfo dflags = do
info <- readIORef (rtldInfo dflags)
case info of
Just v -> return v
Nothing -> do
v <- getLinkerInfo' dflags
writeIORef (rtldInfo dflags) (Just v)
return v
-- See Note [Run-time linker info].
getLinkerInfo' :: DynFlags -> IO LinkerInfo
getLinkerInfo' dflags = do
let platform = targetPlatform dflags
os = platformOS platform
(pgm,args0) = pgm_l dflags
args1 = map Option (getOpts dflags opt_l)
args2 = args0 ++ args1
args3 = filter notNull (map showOpt args2)
-- Try to grab the info from the process output.
parseLinkerInfo stdo _stde _exitc
| any ("GNU ld" `isPrefixOf`) stdo =
-- GNU ld specifically needs to use less memory. This especially
-- hurts on small object files. Trac #5240.
return (GnuLD $ map Option ["-Wl,--hash-size=31",
"-Wl,--reduce-memory-overheads"])
| any ("GNU gold" `isPrefixOf`) stdo =
-- GNU gold does not require any special arguments.
return (GnuGold [])
-- Unknown linker.
| otherwise = fail "invalid --version output, or linker is unsupported"
-- Process the executable call
info <- catchIO (do
case os of
OSSolaris2 ->
-- Solaris uses its own Solaris linker. Even all
-- GNU C are recommended to configure with Solaris
-- linker instead of using GNU binutils linker. Also
-- all GCC distributed with Solaris follows this rule
-- precisely so we assume here, the Solaris linker is
-- used.
return $ SolarisLD []
OSDarwin ->
-- Darwin has neither GNU Gold or GNU LD, but a strange linker
-- that doesn't support --version. We can just assume that's
-- what we're using.
return $ DarwinLD []
OSiOS ->
-- Ditto for iOS
return $ DarwinLD []
OSMinGW32 ->
-- GHC doesn't support anything but GNU ld on Windows anyway.
-- Process creation is also fairly expensive on win32, so
-- we short-circuit here.
return $ GnuLD $ map Option
[ -- Reduce ld memory usage
"-Wl,--hash-size=31"
, "-Wl,--reduce-memory-overheads"
-- Increase default stack, see
-- Note [Windows stack usage]
, "-Xlinker", "--stack=0x800000,0x800000" ]
_ -> do
-- In practice, we use the compiler as the linker here. Pass
-- -Wl,--version to get linker version info.
(exitc, stdo, stde) <- readProcessEnvWithExitCode pgm
(["-Wl,--version"] ++ args3)
en_locale_env
-- Split the output by lines to make certain kinds
-- of processing easier. In particular, 'clang' and 'gcc'
-- have slightly different outputs for '-Wl,--version', but
-- it's still easy to figure out.
parseLinkerInfo (lines stdo) (lines stde) exitc
)
(\err -> do
debugTraceMsg dflags 2
(text "Error (figuring out linker information):" <+>
text (show err))
errorMsg dflags $ hang (text "Warning:") 9 $
text "Couldn't figure out linker information!" $$
text "Make sure you're using GNU ld, GNU gold" <+>
text "or the built in OS X linker, etc."
return UnknownLD)
return info
-- Grab compiler info and cache it in DynFlags.
getCompilerInfo :: DynFlags -> IO CompilerInfo
getCompilerInfo dflags = do
info <- readIORef (rtccInfo dflags)
case info of
Just v -> return v
Nothing -> do
v <- getCompilerInfo' dflags
writeIORef (rtccInfo dflags) (Just v)
return v
-- See Note [Run-time linker info].
getCompilerInfo' :: DynFlags -> IO CompilerInfo
getCompilerInfo' dflags = do
let (pgm,_) = pgm_c dflags
-- Try to grab the info from the process output.
parseCompilerInfo _stdo stde _exitc
-- Regular GCC
| any ("gcc version" `isPrefixOf`) stde =
return GCC
-- Regular clang
| any ("clang version" `isPrefixOf`) stde =
return Clang
-- XCode 5.1 clang
| any ("Apple LLVM version 5.1" `isPrefixOf`) stde =
return AppleClang51
-- XCode 5 clang
| any ("Apple LLVM version" `isPrefixOf`) stde =
return AppleClang
-- XCode 4.1 clang
| any ("Apple clang version" `isPrefixOf`) stde =
return AppleClang
-- Unknown linker.
| otherwise = fail "invalid -v output, or compiler is unsupported"
-- Process the executable call
info <- catchIO (do
(exitc, stdo, stde) <-
readProcessEnvWithExitCode pgm ["-v"] en_locale_env
-- Split the output by lines to make certain kinds
-- of processing easier.
parseCompilerInfo (lines stdo) (lines stde) exitc
)
(\err -> do
debugTraceMsg dflags 2
(text "Error (figuring out C compiler information):" <+>
text (show err))
errorMsg dflags $ hang (text "Warning:") 9 $
text "Couldn't figure out C compiler information!" $$
text "Make sure you're using GNU gcc, or clang"
return UnknownCC)
return info
runLink :: DynFlags -> [Option] -> IO ()
runLink dflags args = do
-- See Note [Run-time linker info]
linkargs <- neededLinkArgs `fmap` getLinkerInfo dflags
let (p,args0) = pgm_l dflags
args1 = map Option (getOpts dflags opt_l)
args2 = args0 ++ args1 ++ args ++ linkargs
mb_env <- getGccEnv args2
runSomethingFiltered dflags ld_filter "Linker" p args2 mb_env
where
ld_filter = case (platformOS (targetPlatform dflags)) of
OSSolaris2 -> sunos_ld_filter
_ -> id
{-
SunOS/Solaris ld emits harmless warning messages about unresolved
symbols in case of compiling into shared library when we do not
link against all the required libs. That is the case of GHC which
does not link against RTS library explicitly in order to be able to
choose the library later based on binary application linking
parameters. The warnings look like:
Undefined first referenced
symbol in file
stg_ap_n_fast ./T2386_Lib.o
stg_upd_frame_info ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_litE_closure ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_appE_closure ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_conE_closure ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziSyntax_mkNameGzud_closure ./T2386_Lib.o
newCAF ./T2386_Lib.o
stg_bh_upd_frame_info ./T2386_Lib.o
stg_ap_ppp_fast ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_stringL_closure ./T2386_Lib.o
stg_ap_p_fast ./T2386_Lib.o
stg_ap_pp_fast ./T2386_Lib.o
ld: warning: symbol referencing errors
this is actually coming from T2386 testcase. The emitting of those
warnings is also a reason why so many TH testcases fail on Solaris.
Following filter code is SunOS/Solaris linker specific and should
filter out only linker warnings. Please note that the logic is a
little bit more complex due to the simple reason that we need to preserve
any other linker emitted messages. If there are any. Simply speaking
if we see "Undefined" and later "ld: warning:..." then we omit all
text between (including) the marks. Otherwise we copy the whole output.
-}
sunos_ld_filter :: String -> String
sunos_ld_filter = unlines . sunos_ld_filter' . lines
sunos_ld_filter' x = if (undefined_found x && ld_warning_found x)
then (ld_prefix x) ++ (ld_postfix x)
else x
breakStartsWith x y = break (isPrefixOf x) y
ld_prefix = fst . breakStartsWith "Undefined"
undefined_found = not . null . snd . breakStartsWith "Undefined"
ld_warn_break = breakStartsWith "ld: warning: symbol referencing errors"
ld_postfix = tail . snd . ld_warn_break
ld_warning_found = not . null . snd . ld_warn_break
runLibtool :: DynFlags -> [Option] -> IO ()
runLibtool dflags args = do
linkargs <- neededLinkArgs `fmap` getLinkerInfo dflags
let args1 = map Option (getOpts dflags opt_l)
args2 = [Option "-static"] ++ args1 ++ args ++ linkargs
libtool = pgm_libtool dflags
mb_env <- getGccEnv args2
runSomethingFiltered dflags id "Linker" libtool args2 mb_env
runMkDLL :: DynFlags -> [Option] -> IO ()
runMkDLL dflags args = do
let (p,args0) = pgm_dll dflags
args1 = args0 ++ args
mb_env <- getGccEnv (args0++args)
runSomethingFiltered dflags id "Make DLL" p args1 mb_env
runWindres :: DynFlags -> [Option] -> IO ()
runWindres dflags args = do
let (gcc, gcc_args) = pgm_c dflags
windres = pgm_windres dflags
opts = map Option (getOpts dflags opt_windres)
quote x = "\"" ++ x ++ "\""
args' = -- If windres.exe and gcc.exe are in a directory containing
-- spaces then windres fails to run gcc. We therefore need
-- to tell it what command to use...
Option ("--preprocessor=" ++
unwords (map quote (gcc :
map showOpt gcc_args ++
map showOpt opts ++
["-E", "-xc", "-DRC_INVOKED"])))
-- ...but if we do that then if windres calls popen then
-- it can't understand the quoting, so we have to use
-- --use-temp-file so that it interprets it correctly.
-- See #1828.
: Option "--use-temp-file"
: args
mb_env <- getGccEnv gcc_args
runSomethingFiltered dflags id "Windres" windres args' mb_env
touch :: DynFlags -> String -> String -> IO ()
touch dflags purpose arg =
runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
-> IO ()
copyWithHeader dflags purpose maybe_header from to = do
showPass dflags purpose
hout <- openBinaryFile to WriteMode
hin <- openBinaryFile from ReadMode
ls <- hGetContents hin -- inefficient, but it'll do for now. ToDo: speed up
maybe (return ()) (header hout) maybe_header
hPutStr hout ls
hClose hout
hClose hin
where
-- write the header string in UTF-8. The header is something like
-- {-# LINE "foo.hs" #-}
-- and we want to make sure a Unicode filename isn't mangled.
header h str = do
hSetEncoding h utf8
hPutStr h str
hSetBinaryMode h True
-- | read the contents of the named section in an ELF object as a
-- String.
readElfSection :: DynFlags -> String -> FilePath -> IO (Maybe String)
readElfSection _dflags section exe = do
let
prog = "readelf"
args = [Option "-p", Option section, FileOption "" exe]
--
r <- readProcessEnvWithExitCode prog (filter notNull (map showOpt args))
en_locale_env
case r of
(ExitSuccess, out, _err) -> return (doFilter (lines out))
_ -> return Nothing
where
doFilter [] = Nothing
doFilter (s:r) = case readP_to_S parse s of
[(p,"")] -> Just p
_r -> doFilter r
where parse = do
skipSpaces
_ <- R.char '['
skipSpaces
_ <- string "0]"
skipSpaces
munch (const True)
{-
************************************************************************
* *
\subsection{Managing temporary files
* *
************************************************************************
-}
cleanTempDirs :: DynFlags -> IO ()
cleanTempDirs dflags
= unless (gopt Opt_KeepTmpFiles dflags)
$ mask_
$ do let ref = dirsToClean dflags
ds <- atomicModifyIORef ref $ \ds -> (Map.empty, ds)
removeTmpDirs dflags (Map.elems ds)
cleanTempFiles :: DynFlags -> IO ()
cleanTempFiles dflags
= unless (gopt Opt_KeepTmpFiles dflags)
$ mask_
$ do let ref = filesToClean dflags
fs <- atomicModifyIORef ref $ \fs -> ([],fs)
removeTmpFiles dflags fs
cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
cleanTempFilesExcept dflags dont_delete
= unless (gopt Opt_KeepTmpFiles dflags)
$ mask_
$ do let ref = filesToClean dflags
to_delete <- atomicModifyIORef ref $ \files ->
let (to_keep,to_delete) = partition (`elem` dont_delete) files
in (to_keep,to_delete)
removeTmpFiles dflags to_delete
-- Return a unique numeric temp file suffix
newTempSuffix :: DynFlags -> IO Int
newTempSuffix dflags = atomicModifyIORef (nextTempSuffix dflags) $ \n -> (n+1,n)
-- Find a temporary name that doesn't already exist.
newTempName :: DynFlags -> Suffix -> IO FilePath
newTempName dflags extn
= do d <- getTempDir dflags
x <- getProcessID
findTempName (d </> "ghc" ++ show x ++ "_")
where
findTempName :: FilePath -> IO FilePath
findTempName prefix
= do n <- newTempSuffix dflags
let filename = prefix ++ show n <.> extn
b <- doesFileExist filename
if b then findTempName prefix
else do -- clean it up later
consIORef (filesToClean dflags) filename
return filename
-- Return our temporary directory within tmp_dir, creating one if we
-- don't have one yet.
getTempDir :: DynFlags -> IO FilePath
getTempDir dflags = do
mapping <- readIORef dir_ref
case Map.lookup tmp_dir mapping of
Nothing -> do
pid <- getProcessID
let prefix = tmp_dir </> "ghc" ++ show pid ++ "_"
mask_ $ mkTempDir prefix
Just dir -> return dir
where
tmp_dir = tmpDir dflags
dir_ref = dirsToClean dflags
mkTempDir :: FilePath -> IO FilePath
mkTempDir prefix = do
n <- newTempSuffix dflags
let our_dir = prefix ++ show n
-- 1. Speculatively create our new directory.
createDirectory our_dir
-- 2. Update the dirsToClean mapping unless an entry already exists
-- (i.e. unless another thread beat us to it).
their_dir <- atomicModifyIORef dir_ref $ \mapping ->
case Map.lookup tmp_dir mapping of
Just dir -> (mapping, Just dir)
Nothing -> (Map.insert tmp_dir our_dir mapping, Nothing)
-- 3. If there was an existing entry, return it and delete the
-- directory we created. Otherwise return the directory we created.
case their_dir of
Nothing -> do
debugTraceMsg dflags 2 $
text "Created temporary directory:" <+> text our_dir
return our_dir
Just dir -> do
removeDirectory our_dir
return dir
`catchIO` \e -> if isAlreadyExistsError e
then mkTempDir prefix else ioError e
addFilesToClean :: DynFlags -> [FilePath] -> IO ()
-- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
addFilesToClean dflags new_files
= atomicModifyIORef (filesToClean dflags) $ \files -> (new_files++files, ())
removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
removeTmpDirs dflags ds
= traceCmd dflags "Deleting temp dirs"
("Deleting: " ++ unwords ds)
(mapM_ (removeWith dflags removeDirectory) ds)
removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
removeTmpFiles dflags fs
= warnNon $
traceCmd dflags "Deleting temp files"
("Deleting: " ++ unwords deletees)
(mapM_ (removeWith dflags removeFile) deletees)
where
-- Flat out refuse to delete files that are likely to be source input
-- files (is there a worse bug than having a compiler delete your source
-- files?)
--
-- Deleting source files is a sign of a bug elsewhere, so prominently flag
-- the condition.
warnNon act
| null non_deletees = act
| otherwise = do
putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
act
(non_deletees, deletees) = partition isHaskellUserSrcFilename fs
removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
removeWith dflags remover f = remover f `catchIO`
(\e ->
let msg = if isDoesNotExistError e
then ptext (sLit "Warning: deleting non-existent") <+> text f
else ptext (sLit "Warning: exception raised when deleting")
<+> text f <> colon
$$ text (show e)
in debugTraceMsg dflags 2 msg
)
-----------------------------------------------------------------------------
-- Running an external program
runSomething :: DynFlags
-> String -- For -v message
-> String -- Command name (possibly a full path)
-- assumed already dos-ified
-> [Option] -- Arguments
-- runSomething will dos-ify them
-> IO ()
runSomething dflags phase_name pgm args =
runSomethingFiltered dflags id phase_name pgm args Nothing
runSomethingFiltered
:: DynFlags -> (String->String) -> String -> String -> [Option]
-> Maybe [(String,String)] -> IO ()
runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
runSomethingWith dflags phase_name pgm args $ \real_args -> do
r <- builderMainLoop dflags filter_fn pgm real_args mb_env
return (r,())
runSomethingWith
:: DynFlags -> String -> String -> [Option]
-> ([String] -> IO (ExitCode, a))
-> IO a
runSomethingWith dflags phase_name pgm args io = do
let real_args = filter notNull (map showOpt args)
cmdLine = showCommandForUser pgm real_args
traceCmd dflags phase_name cmdLine $ handleProc pgm phase_name $ io real_args
handleProc :: String -> String -> IO (ExitCode, r) -> IO r
handleProc pgm phase_name proc = do
(rc, r) <- proc `catchIO` handler
case rc of
ExitSuccess{} -> return r
ExitFailure n
-- rawSystem returns (ExitFailure 127) if the exec failed for any
-- reason (eg. the program doesn't exist). This is the only clue
-- we have, but we need to report something to the user because in
-- the case of a missing program there will otherwise be no output
-- at all.
| n == 127 -> does_not_exist
| otherwise -> throwGhcExceptionIO (PhaseFailed phase_name rc)
where
handler err =
if IO.isDoesNotExistError err
then does_not_exist
else IO.ioError err
does_not_exist = throwGhcExceptionIO (InstallationError ("could not execute: " ++ pgm))
builderMainLoop :: DynFlags -> (String -> String) -> FilePath
-> [String] -> Maybe [(String, String)]
-> IO ExitCode
builderMainLoop dflags filter_fn pgm real_args mb_env = do
chan <- newChan
(hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
-- and run a loop piping the output from the compiler to the log_action in DynFlags
hSetBuffering hStdOut LineBuffering
hSetBuffering hStdErr LineBuffering
_ <- forkIO (readerProc chan hStdOut filter_fn)
_ <- forkIO (readerProc chan hStdErr filter_fn)
-- we don't want to finish until 2 streams have been completed
-- (stdout and stderr)
-- nor until 1 exit code has been retrieved.
rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
-- after that, we're done here.
hClose hStdIn
hClose hStdOut
hClose hStdErr
return rc
where
-- status starts at zero, and increments each time either
-- a reader process gets EOF, or the build proc exits. We wait
-- for all of these to happen (status==3).
-- ToDo: we should really have a contingency plan in case any of
-- the threads dies, such as a timeout.
loop _ _ 0 0 exitcode = return exitcode
loop chan hProcess t p exitcode = do
mb_code <- if p > 0
then getProcessExitCode hProcess
else return Nothing
case mb_code of
Just code -> loop chan hProcess t (p-1) code
Nothing
| t > 0 -> do
msg <- readChan chan
case msg of
BuildMsg msg -> do
log_action dflags dflags SevInfo noSrcSpan defaultUserStyle msg
loop chan hProcess t p exitcode
BuildError loc msg -> do
log_action dflags dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
loop chan hProcess t p exitcode
EOF ->
loop chan hProcess (t-1) p exitcode
| otherwise -> loop chan hProcess t p exitcode
readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
readerProc chan hdl filter_fn =
(do str <- hGetContents hdl
loop (linesPlatform (filter_fn str)) Nothing)
`finally`
writeChan chan EOF
-- ToDo: check errors more carefully
-- ToDo: in the future, the filter should be implemented as
-- a stream transformer.
where
loop [] Nothing = return ()
loop [] (Just err) = writeChan chan err
loop (l:ls) in_err =
case in_err of
Just err@(BuildError srcLoc msg)
| leading_whitespace l -> do
loop ls (Just (BuildError srcLoc (msg $$ text l)))
| otherwise -> do
writeChan chan err
checkError l ls
Nothing -> do
checkError l ls
_ -> panic "readerProc/loop"
checkError l ls
= case parseError l of
Nothing -> do
writeChan chan (BuildMsg (text l))
loop ls Nothing
Just (file, lineNum, colNum, msg) -> do
let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
loop ls (Just (BuildError srcLoc (text msg)))
leading_whitespace [] = False
leading_whitespace (x:_) = isSpace x
parseError :: String -> Maybe (String, Int, Int, String)
parseError s0 = case breakColon s0 of
Just (filename, s1) ->
case breakIntColon s1 of
Just (lineNum, s2) ->
case breakIntColon s2 of
Just (columnNum, s3) ->
Just (filename, lineNum, columnNum, s3)
Nothing ->
Just (filename, lineNum, 0, s2)
Nothing -> Nothing
Nothing -> Nothing
breakColon :: String -> Maybe (String, String)
breakColon xs = case break (':' ==) xs of
(ys, _:zs) -> Just (ys, zs)
_ -> Nothing
breakIntColon :: String -> Maybe (Int, String)
breakIntColon xs = case break (':' ==) xs of
(ys, _:zs)
| not (null ys) && all isAscii ys && all isDigit ys ->
Just (read ys, zs)
_ -> Nothing
data BuildMessage
= BuildMsg !SDoc
| BuildError !SrcLoc !SDoc
| EOF
traceCmd :: DynFlags -> String -> String -> IO a -> IO a
-- trace the command (at two levels of verbosity)
traceCmd dflags phase_name cmd_line action
= do { let verb = verbosity dflags
; showPass dflags phase_name
; debugTraceMsg dflags 3 (text cmd_line)
; case flushErr dflags of
FlushErr io -> io
-- And run it!
; action `catchIO` handle_exn verb
}
where
handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
; throwGhcExceptionIO (PhaseFailed phase_name (ExitFailure 1)) }
{-
************************************************************************
* *
\subsection{Support code}
* *
************************************************************************
-}
-----------------------------------------------------------------------------
-- Define getBaseDir :: IO (Maybe String)
getBaseDir :: IO (Maybe String)
#if defined(mingw32_HOST_OS)
-- Assuming we are running ghc, accessed by path $(stuff)/bin/ghc.exe,
-- return the path $(stuff)/lib.
getBaseDir = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
where
try_size size = allocaArray (fromIntegral size) $ \buf -> do
ret <- c_GetModuleFileName nullPtr buf size
case ret of
0 -> return Nothing
_ | ret < size -> fmap (Just . rootDir) $ peekCWString buf
| otherwise -> try_size (size * 2)
rootDir s = case splitFileName $ normalise s of
(d, ghc_exe)
| lower ghc_exe `elem` ["ghc.exe",
"ghc-stage1.exe",
"ghc-stage2.exe",
"ghc-stage3.exe"] ->
case splitFileName $ takeDirectory d of
-- ghc is in $topdir/bin/ghc.exe
(d', bin) | lower bin == "bin" -> takeDirectory d' </> "lib"
_ -> fail
_ -> fail
where fail = panic ("can't decompose ghc.exe path: " ++ show s)
lower = map toLower
foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
#else
getBaseDir = return Nothing
#endif
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
#else
getProcessID :: IO Int
getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
#endif
-- Divvy up text stream into lines, taking platform dependent
-- line termination into account.
linesPlatform :: String -> [String]
#if !defined(mingw32_HOST_OS)
linesPlatform ls = lines ls
#else
linesPlatform "" = []
linesPlatform xs =
case lineBreak xs of
(as,xs1) -> as : linesPlatform xs1
where
lineBreak "" = ("","")
lineBreak ('\r':'\n':xs) = ([],xs)
lineBreak ('\n':xs) = ([],xs)
lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)
#endif
linkDynLib :: DynFlags -> [String] -> [PackageKey] -> IO ()
linkDynLib dflags0 o_files dep_packages
= do
let -- This is a rather ugly hack to fix dynamically linked
-- GHC on Windows. If GHC is linked with -threaded, then
-- it links against libHSrts_thr. But if base is linked
-- against libHSrts, then both end up getting loaded,
-- and things go wrong. We therefore link the libraries
-- with the same RTS flags that we link GHC with.
dflags1 = if cGhcThreaded then addWay' WayThreaded dflags0
else dflags0
dflags2 = if cGhcDebugged then addWay' WayDebug dflags1
else dflags1
dflags = updateWays dflags2
verbFlags = getVerbFlags dflags
o_file = outputFile dflags
pkgs <- getPreloadPackagesAnd dflags dep_packages
let pkg_lib_paths = collectLibraryPaths pkgs
let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
get_pkg_lib_path_opts l
| ( osElfTarget (platformOS (targetPlatform dflags)) ||
osMachOTarget (platformOS (targetPlatform dflags)) ) &&
dynLibLoader dflags == SystemDependent &&
not (gopt Opt_Static dflags)
= ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
| otherwise = ["-L" ++ l]
let lib_paths = libraryPaths dflags
let lib_path_opts = map ("-L"++) lib_paths
-- We don't want to link our dynamic libs against the RTS package,
-- because the RTS lib comes in several flavours and we want to be
-- able to pick the flavour when a binary is linked.
-- On Windows we need to link the RTS import lib as Windows does
-- not allow undefined symbols.
-- The RTS library path is still added to the library search path
-- above in case the RTS is being explicitly linked in (see #3807).
let platform = targetPlatform dflags
os = platformOS platform
pkgs_no_rts = case os of
OSMinGW32 ->
pkgs
_ ->
filter ((/= rtsPackageKey) . packageConfigId) pkgs
let pkg_link_opts = let (package_hs_libs, extra_libs, other_flags) = collectLinkOpts dflags pkgs_no_rts
in package_hs_libs ++ extra_libs ++ other_flags
-- probably _stub.o files
-- and last temporary shared object file
let extra_ld_inputs = ldInputs dflags
case os of
OSMinGW32 -> do
-------------------------------------------------------------
-- Making a DLL
-------------------------------------------------------------
let output_fn = case o_file of
Just s -> s
Nothing -> "HSdll.dll"
runLink dflags (
map Option verbFlags
++ [ Option "-o"
, FileOption "" output_fn
, Option "-shared"
] ++
[ FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
| gopt Opt_SharedImplib dflags
]
++ map (FileOption "") o_files
-- Permit the linker to auto link _symbol to _imp_symbol
-- This lets us link against DLLs without needing an "import library"
++ [Option "-Wl,--enable-auto-import"]
++ extra_ld_inputs
++ map Option (
lib_path_opts
++ pkg_lib_path_opts
++ pkg_link_opts
))
OSDarwin -> do
-------------------------------------------------------------------
-- Making a darwin dylib
-------------------------------------------------------------------
-- About the options used for Darwin:
-- -dynamiclib
-- Apple's way of saying -shared
-- -undefined dynamic_lookup:
-- Without these options, we'd have to specify the correct
-- dependencies for each of the dylibs. Note that we could
-- (and should) do without this for all libraries except
-- the RTS; all we need to do is to pass the correct
-- HSfoo_dyn.dylib files to the link command.
-- This feature requires Mac OS X 10.3 or later; there is
-- a similar feature, -flat_namespace -undefined suppress,
-- which works on earlier versions, but it has other
-- disadvantages.
-- -single_module
-- Build the dynamic library as a single "module", i.e. no
-- dynamic binding nonsense when referring to symbols from
-- within the library. The NCG assumes that this option is
-- specified (on i386, at least).
-- -install_name
-- Mac OS/X stores the path where a dynamic library is (to
-- be) installed in the library itself. It's called the
-- "install name" of the library. Then any library or
-- executable that links against it before it's installed
-- will search for it in its ultimate install location.
-- By default we set the install name to the absolute path
-- at build time, but it can be overridden by the
-- -dylib-install-name option passed to ghc. Cabal does
-- this.
-------------------------------------------------------------------
let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
instName <- case dylibInstallName dflags of
Just n -> return n
Nothing -> return $ "@rpath" `combine` (takeFileName output_fn)
runLink dflags (
map Option verbFlags
++ [ Option "-dynamiclib"
, Option "-o"
, FileOption "" output_fn
]
++ map Option o_files
++ [ Option "-undefined",
Option "dynamic_lookup",
Option "-single_module" ]
++ (if platformArch platform == ArchX86_64
then [ ]
else [ Option "-Wl,-read_only_relocs,suppress" ])
++ [ Option "-install_name", Option instName ]
++ map Option lib_path_opts
++ extra_ld_inputs
++ map Option pkg_lib_path_opts
++ map Option pkg_link_opts
)
OSiOS -> throwGhcExceptionIO (ProgramError "dynamic libraries are not supported on iOS target")
_ -> do
-------------------------------------------------------------------
-- Making a DSO
-------------------------------------------------------------------
let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
let buildingRts = thisPackage dflags == rtsPackageKey
let bsymbolicFlag = if buildingRts
then -- -Bsymbolic breaks the way we implement
-- hooks in the RTS
[]
else -- we need symbolic linking to resolve
-- non-PIC intra-package-relocations
["-Wl,-Bsymbolic"]
runLink dflags (
map Option verbFlags
++ [ Option "-o"
, FileOption "" output_fn
]
++ map Option o_files
++ [ Option "-shared" ]
++ map Option bsymbolicFlag
-- Set the library soname. We use -h rather than -soname as
-- Solaris 10 doesn't support the latter:
++ [ Option ("-Wl,-h," ++ takeFileName output_fn) ]
++ extra_ld_inputs
++ map Option lib_path_opts
++ map Option pkg_lib_path_opts
++ map Option pkg_link_opts
)
|
bitemyapp/ghc
|
compiler/main/SysTools.hs
|
Haskell
|
bsd-3-clause
| 63,869
|
{-# LANGUAGE GeneralizedNewtypeDeriving,FlexibleInstances,MultiParamTypeClasses,UndecidableInstances #-}
module Counter (CounterT(CounterT), runCounterT, getAndInc) where
import Control.Applicative
import Control.Monad.Trans
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.State
newtype CounterT s m a = CounterT { unCounterT :: StateT s m a } deriving (Monad,Functor,MonadTrans,Applicative)
instance MonadReader r m => MonadReader r (CounterT s m) where
ask = lift ask
local fun m = CounterT (local fun (unCounterT m))
instance MonadIO m => MonadIO (CounterT s m) where
liftIO = lift . liftIO
instance (MonadWriter w m) => MonadWriter w (CounterT s m) where
tell = lift . tell
listen m = CounterT (listen (unCounterT m))
pass m = CounterT (pass (unCounterT m))
instance (MonadState s m) => MonadState s (CounterT c m) where
get = lift get
put = lift . put
runCounterT :: Monad m => s -> CounterT s m a -> m a
runCounterT s m = liftM fst (runStateT (unCounterT m) s)
getAndInc :: Functor m => Monad m => Enum s => CounterT s m s
getAndInc = CounterT (get <* modify succ)
|
olsner/m3
|
Counter.hs
|
Haskell
|
bsd-3-clause
| 1,122
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE LambdaCase #-}
module Data.Type.Product.Quote
( qP
) where
import Data.Type.Quote
import Data.Type.Product
import Language.Haskell.TH
import Language.Haskell.TH.Quote
qP :: QuasiQuoter
qP = QuasiQuoter
{ quoteExp = parseProd (parseExp qq) prodExp
, quotePat = parseProd (parsePat qq) prodPat
, quoteType = stub qq "quoteType not provided"
, quoteDec = stub qq "quoteDec not provided"
}
where
qq = "qP"
parseProd :: (String -> Q a) -> ([Q a] -> Q a) -> String -> Q a
parseProd prs bld = bld . map prs . commaSep
prodExp :: [Q Exp] -> Q Exp
prodExp = \case
e : es -> [| $e :< $(prodExp es) |]
_ -> [| Ø |]
prodPat :: [Q Pat] -> Q Pat
prodPat = \case
e : es -> [p| $e :< $(prodPat es) |]
_ -> [p| Ø |]
|
kylcarte/type-combinators-quote
|
src/Data/Type/Product/Quote.hs
|
Haskell
|
bsd-3-clause
| 889
|
module Playground08 where
import qualified Data.Text.All as T
-- Using map 8.1
reverseMyDogs :: [[a]] -> [[a]]
reverseMyDogs dogs = map reverse dogs
filterMyDogs :: [String] -> [String]
filterMyDogs dogs = filter (\ x -> (T.toLower (T.pack x)) == (T.toLower ( T.pack "Axel")) ) dogs
-- Folding a list 8.4
foldMyDogs :: Foldable t => t [a] -> [a]
foldMyDogs dogs = foldl (++) [] dogs
myReverse :: Foldable t => t a -> [a]
myReverse xs = foldl rcons [] xs
where rcons x y = y:x
|
stefanocerruti/haskell-primer-alpha
|
src/Playground08.hs
|
Haskell
|
bsd-3-clause
| 490
|
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, FlexibleContexts, RankNTypes, GADTs #-}
module QueryArrow.DBMap where
import QueryArrow.DB.DB
import QueryArrow.Syntax.Type
import QueryArrow.Semantics.TypeChecker
import QueryArrow.Config
import QueryArrow.Translation
import QueryArrow.Cache
import QueryArrow.Plugin
import QueryArrow.Sum
import QueryArrow.Include
import Data.Maybe
import Prelude hiding (lookup)
import Data.Map.Strict (fromList, Map, lookup)
-- import Plugins
import qualified QueryArrow.SQL.HDBC.PostgreSQL as PostgreSQL
import qualified QueryArrow.SQL.HDBC.CockroachDB as CockroachDB
import qualified QueryArrow.Cypher.Neo4j as Neo4j
import QueryArrow.InMemory.BuiltIn
import QueryArrow.InMemory.Map
import qualified QueryArrow.ElasticSearch.ElasticSearch as ElasticSearch
import qualified QueryArrow.SQL.HDBC.Sqlite3 as Sqlite3
-- import qualified QueryArrow.Remote.NoTranslation.TCP.TCP as Remote.TCP
-- import qualified QueryArrow.FileSystem.FileSystem as FileSystem
import qualified QueryArrow.SQL.LibPQ.PostgreSQL as LibPQ
type DBMap = Map String (AbstractPlugin MapResultRow)
getDB2 :: DBMap -> GetDBFunction MapResultRow
getDB2 dbMap ps = case lookup (catalog_database_type ps) dbMap of
Just (AbstractPlugin getDBFunc) ->
getDB getDBFunc (getDB2 dbMap) ps
Nothing -> error ("unimplemented database type " ++ (catalog_database_type ps))
dbMap0 :: DBMap
dbMap0 = fromList [
("SQL/HDBC/PostgreSQL", AbstractPlugin PostgreSQL.PostgreSQLPlugin),
("SQL/HDBC/CockroachDB", AbstractPlugin CockroachDB.CockroachDBPlugin),
("SQL/HDBC/Sqlite3", AbstractPlugin Sqlite3.SQLite3Plugin),
("SQL/LibPQ", AbstractPlugin LibPQ.PostgreSQLPlugin),
("Cypher/Neo4j", AbstractPlugin Neo4j.Neo4jPlugin),
("InMemory/BuiltIn", AbstractPlugin builtInPlugin),
("InMemory/Map", AbstractPlugin mapPlugin),
("InMemory/MutableMap", AbstractPlugin stateMapPlugin),
("ElasticSearch/ElasticSearch", AbstractPlugin ElasticSearch.ElasticSearchPlugin),
-- ("Remote/TCP", AbstractPlugin Remote.TCP.RemoteTCPPlugin),
-- ("FileSystem", AbstractPlugin FileSystem.FileSystemPlugin),
("Cache", AbstractPlugin CachePlugin),
("Translation", AbstractPlugin TransPlugin),
("Include", AbstractPlugin IncludePlugin),
("Sum", AbstractPlugin SumPlugin)
];
transDB :: TranslationInfo -> IO (AbstractDatabase MapResultRow FormulaT)
transDB transinfo =
getDB2 dbMap0 (db_plugin transinfo)
|
xu-hao/QueryArrow
|
QueryArrow-plugins/src/QueryArrow/DBMap.hs
|
Haskell
|
bsd-3-clause
| 2,554
|
-- | Dyck paths, lattice paths, etc
--
-- For example, the following figure represents a Dyck path of height 5 with 3 zero-touches (not counting the starting point,
-- but counting the endpoint) and 7 peaks:
--
-- <<svg/dyck_path.svg>>
--
{-# LANGUAGE BangPatterns #-}
module Math.Combinat.LatticePaths where
--------------------------------------------------------------------------------
import Data.List
import System.Random
import Math.Combinat.Numbers
import Math.Combinat.Trees.Binary
import Math.Combinat.ASCII as ASCII
--------------------------------------------------------------------------------
-- * Types
-- | A step in a lattice path
data Step
= UpStep -- ^ the step @(1,1)@
| DownStep -- ^ the step @(1,-1)@
deriving (Eq,Ord,Show)
-- | A lattice path is a path using only the allowed steps, never going below the zero level line @y=0@.
--
-- Note that if you rotate such a path by 45 degrees counterclockwise,
-- you get a path which uses only the steps @(1,0)@ and @(0,1)@, and stays
-- above the main diagonal (hence the name, we just use a different convention).
--
type LatticePath = [Step]
--------------------------------------------------------------------------------
-- * ascii drawing of paths
-- | Draws the path into a list of lines. For example try:
--
-- > autotabulate RowMajor (Right 5) (map asciiPath $ dyckPaths 4)
--
asciiPath :: LatticePath -> ASCII
asciiPath p = asciiFromLines $ transpose (go 0 p) where
go !h [] = []
go !h (x:xs) = case x of
UpStep -> ee h x : go (h+1) xs
DownStep -> ee (h-1) x : go (h-1) xs
maxh = pathHeight p
ee h x = replicate (maxh-h-1) ' ' ++ [ch x] ++ replicate h ' '
ch x = case x of
UpStep -> '/'
DownStep -> '\\'
--------------------------------------------------------------------------------
-- * elementary queries
-- | A lattice path is called \"valid\", if it never goes below the @y=0@ line.
isValidPath :: LatticePath -> Bool
isValidPath = go 0 where
go !y [] = y>=0
go !y (t:ts) = let y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
in if y'<0 then False
else go y' ts
-- | A Dyck path is a lattice path whose last point lies on the @y=0@ line
isDyckPath :: LatticePath -> Bool
isDyckPath = go 0 where
go !y [] = y==0
go !y (t:ts) = let y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
in if y'<0 then False
else go y' ts
-- | Maximal height of a lattice path
pathHeight :: LatticePath -> Int
pathHeight = go 0 0 where
go !h !y [] = h
go !h !y (t:ts) = case t of
UpStep -> go (max h (y+1)) (y+1) ts
DownStep -> go h (y-1) ts
-- | Endpoint of a lattice path, which starts from @(0,0)@.
pathEndpoint :: LatticePath -> (Int,Int)
pathEndpoint = go 0 0 where
go !x !y [] = (x,y)
go !x !y (t:ts) = case t of
UpStep -> go (x+1) (y+1) ts
DownStep -> go (x+1) (y-1) ts
-- | Returns the coordinates of the path (excluding the starting point @(0,0)@, but including
-- the endpoint)
pathCoordinates :: LatticePath -> [(Int,Int)]
pathCoordinates = go 0 0 where
go _ _ [] = []
go !x !y (t:ts) = let x' = x + 1
y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
in (x',y') : go x' y' ts
-- | Counts the up-steps
pathNumberOfUpSteps :: LatticePath -> Int
pathNumberOfUpSteps = fst . pathNumberOfUpDownSteps
-- | Counts the down-steps
pathNumberOfDownSteps :: LatticePath -> Int
pathNumberOfDownSteps = snd . pathNumberOfUpDownSteps
-- | Counts both the up-steps and down-steps
pathNumberOfUpDownSteps :: LatticePath -> (Int,Int)
pathNumberOfUpDownSteps = go 0 0 where
go !u !d (p:ps) = case p of
UpStep -> go (u+1) d ps
DownStep -> go u (d+1) ps
go !u !d [] = (u,d)
--------------------------------------------------------------------------------
-- * path-specific queries
-- | Number of peaks of a path (excluding the endpoint)
pathNumberOfPeaks :: LatticePath -> Int
pathNumberOfPeaks = go 0 where
go !k (x:xs@(y:_)) = go (if x==UpStep && y==DownStep then k+1 else k) xs
go !k [x] = k
go !k [ ] = k
-- | Number of points on the path which touch the @y=0@ zero level line
-- (excluding the starting point @(0,0)@, but including the endpoint; that is, for Dyck paths it this is always positive!).
pathNumberOfZeroTouches :: LatticePath -> Int
pathNumberOfZeroTouches = pathNumberOfTouches' 0
-- | Number of points on the path which touch the level line at height @h@
-- (excluding the starting point @(0,0)@, but including the endpoint).
pathNumberOfTouches'
:: Int -- ^ @h@ = the touch level
-> LatticePath -> Int
pathNumberOfTouches' h = go 0 0 0 where
go !cnt _ _ [] = cnt
go !cnt !x !y (t:ts) = let y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
cnt' = if y'==h then cnt+1 else cnt
in go cnt' (x+1) y' ts
--------------------------------------------------------------------------------
-- * Dyck paths
-- | @dyckPaths m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@.
--
-- Remark: Dyck paths are obviously in bijection with nested parentheses, and thus
-- also with binary trees.
--
-- Order is reverse lexicographical:
--
-- > sort (dyckPaths m) == reverse (dyckPaths m)
--
dyckPaths :: Int -> [LatticePath]
dyckPaths = map nestedParensToDyckPath . nestedParentheses
-- | @dyckPaths m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@.
--
-- > sort (dyckPathsNaive m) == sort (dyckPaths m)
--
-- Naive recursive algorithm, order is ad-hoc
--
dyckPathsNaive :: Int -> [LatticePath]
dyckPathsNaive = worker where
worker 0 = [[]]
worker m = as ++ bs where
as = [ bracket p | p <- worker (m-1) ]
bs = [ bracket p ++ q | k <- [1..m-1] , p <- worker (k-1) , q <- worker (m-k) ]
bracket p = UpStep : p ++ [DownStep]
-- | The number of Dyck paths from @(0,0)@ to @(2m,0)@ is simply the m\'th Catalan number.
countDyckPaths :: Int -> Integer
countDyckPaths m = catalan m
-- | The trivial bijection
nestedParensToDyckPath :: [Paren] -> LatticePath
nestedParensToDyckPath = map f where
f p = case p of { LeftParen -> UpStep ; RightParen -> DownStep }
-- | The trivial bijection in the other direction
dyckPathToNestedParens :: LatticePath -> [Paren]
dyckPathToNestedParens = map g where
g s = case s of { UpStep -> LeftParen ; DownStep -> RightParen }
--------------------------------------------------------------------------------
-- * Bounded Dyck paths
-- | @boundedDyckPaths h m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ whose height is at most @h@.
-- Synonym for 'boundedDyckPathsNaive'.
--
boundedDyckPaths
:: Int -- ^ @h@ = maximum height
-> Int -- ^ @m@ = half-length
-> [LatticePath]
boundedDyckPaths = boundedDyckPathsNaive
-- | @boundedDyckPathsNaive h m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ whose height is at most @h@.
--
-- > sort (boundedDyckPaths h m) == sort [ p | p <- dyckPaths m , pathHeight p <= h ]
-- > sort (boundedDyckPaths m m) == sort (dyckPaths m)
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
boundedDyckPathsNaive
:: Int -- ^ @h@ = maximum height
-> Int -- ^ @m@ = half-length
-> [LatticePath]
boundedDyckPathsNaive = worker where
worker !h !m
| h<0 = []
| m<0 = []
| m==0 = [[]]
| h<=0 = []
| otherwise = as ++ bs
where
bracket p = UpStep : p ++ [DownStep]
as = [ bracket p | p <- boundedDyckPaths (h-1) (m-1) ]
bs = [ bracket p ++ q | k <- [1..m-1] , p <- boundedDyckPaths (h-1) (k-1) , q <- boundedDyckPaths h (m-k) ]
--------------------------------------------------------------------------------
-- * More general lattice paths
-- | All lattice paths from @(0,0)@ to @(x,y)@. Clearly empty unless @x-y@ is even.
-- Synonym for 'latticePathsNaive'
--
latticePaths :: (Int,Int) -> [LatticePath]
latticePaths = latticePathsNaive
-- | All lattice paths from @(0,0)@ to @(x,y)@. Clearly empty unless @x-y@ is even.
--
-- Note that
--
-- > sort (dyckPaths n) == sort (latticePaths (0,2*n))
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
latticePathsNaive :: (Int,Int) -> [LatticePath]
latticePathsNaive (x,y) = worker x y where
worker !x !y
| odd (x-y) = []
| x<0 = []
| y<0 = []
| y==0 = dyckPaths (div x 2)
| x==1 && y==1 = [[UpStep]]
| otherwise = as ++ bs
where
bracket p = UpStep : p ++ [DownStep]
as = [ UpStep : p | p <- worker (x-1) (y-1) ]
bs = [ bracket p ++ q | k <- [1..(div x 2)] , p <- dyckPaths (k-1) , q <- worker (x-2*k) y ]
-- | Lattice paths are counted by the numbers in the Catalan triangle.
countLatticePaths :: (Int,Int) -> Integer
countLatticePaths (x,y)
| even (x+y) = catalanTriangle (div (x+y) 2) (div (x-y) 2)
| otherwise = 0
--------------------------------------------------------------------------------
-- * Zero-level touches
-- | @touchingDyckPaths k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ which touch the
-- zero level line @y=0@ exactly @k@ times (excluding the starting point, but including the endpoint;
-- thus, @k@ should be positive). Synonym for 'touchingDyckPathsNaive'.
touchingDyckPaths
:: Int -- ^ @k@ = number of zero-touches
-> Int -- ^ @m@ = half-length
-> [LatticePath]
touchingDyckPaths = touchingDyckPathsNaive
-- | @touchingDyckPathsNaive k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ which touch the
-- zero level line @y=0@ exactly @k@ times (excluding the starting point, but including the endpoint;
-- thus, @k@ should be positive).
--
-- > sort (touchingDyckPathsNaive k m) == sort [ p | p <- dyckPaths m , pathNumberOfZeroTouches p == k ]
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
touchingDyckPathsNaive
:: Int -- ^ @k@ = number of zero-touches
-> Int -- ^ @m@ = half-length
-> [LatticePath]
touchingDyckPathsNaive = worker where
worker !k !m
| m == 0 = if k==0 then [[]] else []
| k <= 0 = []
| m < 0 = []
| k == 1 = [ bracket p | p <- dyckPaths (m-1) ]
| otherwise = [ bracket p ++ q | l <- [1..m-1] , p <- dyckPaths (l-1) , q <- worker (k-1) (m-l) ]
where
bracket p = UpStep : p ++ [DownStep]
-- | There is a bijection from the set of non-empty Dyck paths of length @2n@ which touch the zero lines @t@ times,
-- to lattice paths from @(0,0)@ to @(2n-t-1,t-1)@ (just remove all the down-steps just before touching
-- the zero line, and also the very first up-step). This gives us a counting formula.
countTouchingDyckPaths
:: Int -- ^ @k@ = number of zero-touches
-> Int -- ^ @m@ = half-length
-> Integer
countTouchingDyckPaths t n
| t==0 && n==0 = 1
| otherwise = countLatticePaths (2*n-t-1,t-1)
--------------------------------------------------------------------------------
-- * Dyck paths with given number of peaks
-- | @peakingDyckPaths k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ with exactly @k@ peaks.
--
-- Synonym for 'peakingDyckPathsNaive'
--
peakingDyckPaths
:: Int -- ^ @k@ = number of peaks
-> Int -- ^ @m@ = half-length
-> [LatticePath]
peakingDyckPaths = peakingDyckPathsNaive
-- | @peakingDyckPathsNaive k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ with exactly @k@ peaks.
--
-- > sort (peakingDyckPathsNaive k m) = sort [ p | p <- dyckPaths m , pathNumberOfPeaks p == k ]
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
peakingDyckPathsNaive
:: Int -- ^ @k@ = number of peaks
-> Int -- ^ @m@ = half-length
-> [LatticePath]
peakingDyckPathsNaive = worker where
worker !k !m
| m == 0 = if k==0 then [[]] else []
| k <= 0 = []
| m < 0 = []
| k == 1 = [ singlePeak m ]
| otherwise = as ++ bs ++ cs
where
as = [ bracket p | p <- worker k (m-1) ]
bs = [ smallHill ++ q | q <- worker (k-1) (m-1) ]
cs = [ bracket p ++ q | l <- [2..m-1] , a <- [1..k-1] , p <- worker a (l-1) , q <- worker (k-a) (m-l) ]
smallHill = [ UpStep , DownStep ]
singlePeak !m = replicate m UpStep ++ replicate m DownStep
bracket p = UpStep : p ++ [DownStep]
-- | Dyck paths of length @2m@ with @k@ peaks are counted by the Narayana numbers @N(m,k) = \binom{m}{k} \binom{m}{k-1} / m@
countPeakingDyckPaths
:: Int -- ^ @k@ = number of peaks
-> Int -- ^ @m@ = half-length
-> Integer
countPeakingDyckPaths k m
| m == 0 = if k==0 then 1 else 0
| k <= 0 = 0
| m < 0 = 0
| k == 1 = 1
| otherwise = div (binomial m k * binomial m (k-1)) (fromIntegral m)
--------------------------------------------------------------------------------
-- * Random lattice paths
-- | A uniformly random Dyck path of length @2m@
randomDyckPath :: RandomGen g => Int -> g -> (LatticePath,g)
randomDyckPath m g0 = (nestedParensToDyckPath parens, g1) where
(parens,g1) = randomNestedParentheses m g0
--------------------------------------------------------------------------------
|
chadbrewbaker/combinat
|
Math/Combinat/LatticePaths.hs
|
Haskell
|
bsd-3-clause
| 13,782
|
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Data.Gogol.DatastoreEntity (
EntityTransform(..)
, DatastoreEntity(..)
, _ToDatastoreEntity
, _FromDatastoreEntity
) where
import Control.Applicative ((<|>))
import Control.Lens (Getter, at, over, view, (&), (.~),
(?~), (^.), (^?), _1, _Just, _head)
import qualified Control.Lens.Getter as L
import Data.ByteString (ByteString)
import qualified Data.HashMap.Lazy as HM
import Data.Int (Int32, Int64)
import Data.List.NonEmpty (NonEmpty, fromList, toList)
import Data.Maybe (fromMaybe)
import Data.Text (Text, pack)
import Data.Time.Clock (UTCTime)
import GHC.Float (double2Float, float2Double)
import GHC.Generics
import Network.Google.Datastore (Entity, Key, LatLng, Value,
arrayValue, avValues, eKey,
eProperties, eProperties, entity,
entityProperties, epAddtional, kPath,
key, pathElement, peKind,
vArrayValue, vBlobValue,
vBooleanValue, vDoubleValue,
vEntityValue, vGeoPointValue,
vIntegerValue, vKeyValue,
vStringValue, vTimestampValue, value)
data EntityTransform
= EntityC Text [(Text, Value)]
| EntityP [(Text, Value)]
| V Value
| None
deriving (Eq, Show)
class DatastoreEntity a where
toEntity :: a -> EntityTransform
fromEntity :: EntityTransform -> Maybe a
default toEntity :: (Generic a, GDatastorePut (Rep a)) => a -> EntityTransform
toEntity = gEntPut . from
default fromEntity ::(Generic a, GDatastoreGet (Rep a)) => EntityTransform -> Maybe a
fromEntity x = to <$> gEntGet x
class GDatastorePut f where
gEntPut :: f a -> EntityTransform
class GDatastoreGet f where
gEntGet :: EntityTransform -> Maybe (f a)
instance GDatastorePut U1 where
gEntPut _ = None
instance GDatastoreGet U1 where
gEntGet _ = Nothing
instance (GDatastorePut a, GDatastorePut b) => GDatastorePut (a :+: b) where
gEntPut (L1 x) = gEntPut x
gEntPut (R1 x) = gEntPut x
instance (GDatastoreGet a, GDatastoreGet b) => GDatastoreGet (a :+: b) where
gEntGet e = L1 <$> gEntGet e <|> R1 <$> gEntGet e
instance (GDatastorePut a, GDatastorePut b) => GDatastorePut (a :*: b) where
gEntPut (a :*: b) = case (gEntPut a, gEntPut b) of
(EntityP xs, EntityP ys) -> EntityP $ xs ++ ys
_ -> None
instance (GDatastoreGet a, GDatastoreGet b) => GDatastoreGet (a :*: b) where
gEntGet e = (:*:) <$> gEntGet e <*> gEntGet e
instance GDatastorePut f => GDatastorePut (D1 d f) where
gEntPut = gEntPut . unM1
instance GDatastoreGet f => GDatastoreGet (D1 d f) where
gEntGet = fmap M1 . gEntGet
instance (GDatastorePut f, Constructor c) => GDatastorePut (C1 c f) where
gEntPut x
| conIsRecord x = case gEntPut $ unM1 x of
EntityP xs -> EntityC (pack (conName x)) xs
v -> v
| otherwise = gEntPut $ unM1 x
instance (GDatastoreGet f, Constructor c) => GDatastoreGet (C1 c f) where
gEntGet (EntityC _ xs) = M1 <$> gEntGet (EntityP xs)
gEntGet (EntityP xs) = M1 <$> gEntGet (EntityP xs)
gEntGet (V v) = do props <- v^.vEntityValue
ep <- props^.eProperties
gEntGet (EntityP . HM.toList $ ep^.epAddtional)
gEntGet None = Nothing
instance (GDatastorePut f, Selector c) => GDatastorePut (S1 c f) where
gEntPut s@(M1 x) = case gEntPut x of
V v -> EntityP [(pack (selName s), v)]
EntityP xs -> EntityP $ over _1 (const (pack (selName s))) <$> xs
EntityC _ xs -> EntityP [(pack (selName s), mkEntityV xs)]
_ -> None
where mkEntityV xs = value & vEntityValue ?~
(entity & eProperties ?~
entityProperties (HM.fromList xs))
instance (GDatastoreGet f, Selector c) => GDatastoreGet (S1 c f) where
gEntGet (EntityP xs) = gEntGet =<< V <$> HM.fromList xs^.at s
where s = pack $ selName (undefined :: t c f p)
gEntGet (V v) = M1 <$> gEntGet (V v)
gEntGet _ = Nothing
instance DatastoreEntity a => GDatastorePut (K1 i a) where
gEntPut = toEntity . unK1
instance DatastoreEntity a => GDatastoreGet (K1 i a) where
gEntGet = fmap K1 . fromEntity
instance DatastoreEntity Bool where
toEntity b = V $ value & vBooleanValue ?~ b
fromEntity (V v) = v^.vBooleanValue
fromEntity _ = Nothing
instance DatastoreEntity Int where
toEntity i = V $ value & vIntegerValue ?~ fromIntegral i
fromEntity (V v) = fromIntegral <$> v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Integer where
toEntity i = V $ value & vIntegerValue ?~ fromIntegral i
fromEntity (V v) = fromIntegral <$> v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Int32 where
toEntity i = V $ value & vIntegerValue ?~ fromIntegral i
fromEntity (V v) = fromIntegral <$> v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Int64 where
toEntity i = V $ value & vIntegerValue ?~ i
fromEntity (V v) = v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Float where
toEntity f = V $ value & vDoubleValue ?~ float2Double f
fromEntity (V v) = double2Float <$> v^.vDoubleValue
fromEntity _ = Nothing
instance DatastoreEntity Double where
toEntity d = V $ value & vDoubleValue ?~ d
fromEntity (V v) = v^.vDoubleValue
fromEntity _ = Nothing
instance DatastoreEntity ByteString where
toEntity b = V $ value & vBlobValue ?~ b
fromEntity (V v) = v^.vBlobValue
fromEntity _ = Nothing
instance DatastoreEntity Text where
toEntity x = V $ value & vStringValue ?~ x
fromEntity (V v) = v^.vStringValue
fromEntity _ = Nothing
instance DatastoreEntity Key where
toEntity k = V $ value & vKeyValue ?~ k
fromEntity (V v) = v^.vKeyValue
fromEntity _ = Nothing
instance DatastoreEntity UTCTime where
toEntity t = V $ value & vTimestampValue ?~ t
fromEntity (V v) = v^.vTimestampValue
fromEntity _ = Nothing
instance DatastoreEntity LatLng where
toEntity l = V $ value & vGeoPointValue ?~ l
fromEntity (V v) = v^.vGeoPointValue
fromEntity _ = Nothing
instance DatastoreEntity a => DatastoreEntity (NonEmpty a) where
toEntity xs = V $ value & vArrayValue ?~ (arrayValue & avValues .~
(toList xs >>= indiv))
where indiv x = case toEntity x of
V v -> [v]
ec@(EntityC _ _) -> [value & vEntityValue .~ toEntity' ec]
_ -> []
fromEntity (V v) = do av <- v^.vArrayValue
parsed <- traverse fromEntity (V <$> av^.avValues)
return $ fromList parsed
fromEntity _ = Nothing
instance DatastoreEntity a => DatastoreEntity [a] where
toEntity xs = V $ value & vArrayValue ?~ (arrayValue & avValues .~
(xs >>= indiv))
where indiv x = case toEntity x of
V v -> [v]
ec@(EntityC _ _) -> [value & vEntityValue .~ toEntity' ec]
_ -> []
fromEntity (V v) = do av <- v^.vArrayValue
traverse fromEntity (V <$> av^.avValues)
fromEntity _ = Nothing
instance DatastoreEntity a => DatastoreEntity (Maybe a) where
toEntity (Just x) = toEntity x
toEntity Nothing = V value
fromEntity z@(V _) = (pure <$> fromEntity z) <|> pure Nothing
fromEntity _ = Nothing
_ToDatastoreEntity :: DatastoreEntity a => Getter a (Maybe Entity)
_ToDatastoreEntity = L.to (toEntity' . toEntity)
toEntity' :: EntityTransform -> Maybe Entity
toEntity' (EntityC k params) =
pure $ entity & eKey ?~ (key & kPath .~ [pathElement & peKind ?~ k])
& eProperties ?~ entityProperties (HM.fromList params)
toEntity' _ = Nothing
_FromDatastoreEntity :: DatastoreEntity a => Getter Entity (Maybe a)
_FromDatastoreEntity = L.to (fromEntity . toTransform)
where toTransform e =
fromMaybe None $ EntityC <$> (view kPath <$> e^.eKey)^._Just._head.peKind
<*> (HM.toList <$> (e^?eProperties._Just.epAddtional))
|
jamesthompson/nosql-generic
|
src/Data/Gogol/DatastoreEntity.hs
|
Haskell
|
bsd-3-clause
| 8,885
|
{-# LANGUAGE OverloadedStrings, LambdaCase, RankNTypes #-}
module Main where
import Criterion
import Criterion.Main
import Data.RDF
import qualified Data.Text as T
-- The `bills.102.rdf` XML file is needed to run this benchmark suite
--
-- $ wget https://www.govtrack.us/data/rdf/bills.102.rdf.gz
-- $ gzip -d bills.102.rdf.gz
parseTurtle :: RDF rdf => String -> rdf
parseTurtle s =
let (Right rdf) = parseString (TurtleParser Nothing Nothing) (T.pack s)
in rdf
queryGr :: RDF rdf => (Maybe Node,Maybe Node,Maybe Node,rdf) -> [Triple]
queryGr (maybeS,maybeP,maybeO,rdf) = query rdf maybeS maybeP maybeO
selectGr :: RDF rdf => (NodeSelector,NodeSelector,NodeSelector,rdf) -> [Triple]
selectGr (selectorS,selectorP,selectorO,rdf) = select rdf selectorS selectorP selectorO
main :: IO ()
main = defaultMain [
env (readFile "bills.102.ttl") $ \ ~(ttl_countries) ->
bgroup "parse" [
bench "HashMapS" $
nf (parseTurtle :: String -> HashMapS) ttl_countries
, bench "HashMapSP" $
nf (parseTurtle :: String -> HashMapSP) ttl_countries
, bench "MapSP" $
nf (parseTurtle :: String -> MapSP) ttl_countries
, bench "TriplesList" $
nf (parseTurtle :: String -> TriplesList) ttl_countries
, bench "ListPatriciaTree" $
nf (parseTurtle :: String -> TriplesPatriciaTree) ttl_countries
]
,
env (do ttl_countries <- readFile "bills.102.ttl"
let (Right rdf1) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf2) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf3) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf4) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf5) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
return (rdf1 :: TriplesPatriciaTree,rdf2 :: TriplesList,rdf3 :: HashMapS,rdf4 :: MapSP,rdf5::HashMapSP) )
$ \ ~(triplesPatriciaTree,triplesList,hashMapS,mapSP,hashMapSP) ->
bgroup "query"
(queryBench "TriplesList" triplesList
++ queryBench "HashMapS" hashMapS
++ queryBench "MapSP" mapSP
++ queryBench "HashMapSP" hashMapSP
++ queryBench "TriplesPatriciaTree" triplesPatriciaTree)
,
env (do ttl_countries <- readFile "bills.102.ttl"
let (Right rdf1) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf2) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf3) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf4) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf5) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
return (rdf1 :: TriplesPatriciaTree,rdf2 :: TriplesList,rdf3 :: HashMapS,rdf4 :: MapSP,rdf5 :: HashMapSP) )
$ \ ~(triplesPatriciaTree,triplesList,hashMapS,mapSP,hashMapSP) ->
bgroup "select"
(selectBench "TriplesList" triplesList
++ selectBench "HashMapS" hashMapS
++ selectBench "MapSP" mapSP
++ selectBench "HashMapSP" hashMapSP
++ selectBench "TriplesPatriciaTree" triplesPatriciaTree)
]
selectBench :: forall rdf. RDF rdf => String -> rdf -> [Benchmark]
selectBench label gr =
[ bench (label ++ " SPO") $ nf selectGr (subjSelect,predSelect,objSelect,gr)
, bench (label ++ " SP") $ nf selectGr (subjSelect,predSelect,selectNothing,gr)
, bench (label ++ " S") $ nf selectGr (subjSelect,selectNothing,selectNothing,gr)
, bench (label ++ " PO") $ nf selectGr (selectNothing,predSelect,objSelect,gr)
, bench (label ++ " SO") $ nf selectGr (subjSelect,selectNothing,objSelect,gr)
, bench (label ++ " P") $ nf selectGr (selectNothing,predSelect,selectNothing,gr)
, bench (label ++ " O") $ nf selectGr (selectNothing,selectNothing,objSelect,gr)
]
subjSelect, predSelect, objSelect, selectNothing :: Maybe (Node -> Bool)
subjSelect = Just (\case { (UNode n) -> T.length n > 12 ; _ -> False })
predSelect = Just (\case { (UNode n) -> T.length n > 12 ; _ -> False })
objSelect = Just (\case { (UNode n) -> T.length n > 12 ; _ -> False })
selectNothing = Nothing
subjQuery, predQuery, objQuery, queryNothing :: Maybe Node
subjQuery = Just (UNode "http://www.rdfabout.com/rdf/usgov/congress/102/bills/h5694")
predQuery = Just (UNode "bill:congress")
objQuery = Just (LNode (PlainL (T.pack "102")))
queryNothing = Nothing
queryBench :: forall rdf. RDF rdf => String -> rdf -> [Benchmark]
queryBench label gr =
[ bench (label ++ " SPO") $ nf queryGr (subjQuery,predQuery,objQuery,gr)
, bench (label ++ " SP") $ nf queryGr (subjQuery,predQuery,queryNothing,gr)
, bench (label ++ " S") $ nf queryGr (subjQuery,queryNothing,queryNothing,gr)
, bench (label ++ " PO") $ nf queryGr (queryNothing,predQuery,objQuery,gr)
, bench (label ++ " SO") $ nf queryGr (subjQuery,queryNothing,objQuery,gr)
, bench (label ++ " P") $ nf queryGr (queryNothing,predQuery,queryNothing,gr)
, bench (label ++ " O") $ nf queryGr (queryNothing,queryNothing,objQuery,gr)
]
|
jutaro/rdf4h
|
bench/MainCriterion.hs
|
Haskell
|
bsd-3-clause
| 5,204
|
-- | Context-free grammars.
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Cfg.Cfg(
-- * Class
Cfg(..),
-- * Vocabulary
V(..),
Vs,
isNT,
isT,
vocabulary,
usedVocabulary,
undeclaredVocabulary,
isFullyDeclared,
-- * productions
Production(..),
productions,
lookupProductions,
-- * production maps
ProductionMap,
productionMap,
-- * Utility functions
eqCfg {- ,
compareCfg -}) where
import Data.Bifunctor
import Data.Data(Data, Typeable)
import qualified Data.Map as M
import qualified Data.Set as S
------------------------------------------------------------
-- | Represents a context-free grammar with its nonterminal and
-- terminal types.
class Cfg cfg t nt where
nonterminals :: cfg t nt -> S.Set nt
-- ^ the nonterminals of the grammar
terminals :: cfg t nt -> S.Set t
-- ^ the terminals of the grammar
productionRules :: cfg t nt -> nt -> S.Set (Vs t nt)
-- ^ the productions of the grammar
startSymbol :: cfg t nt -> nt
-- ^ the start symbol of the grammar; must be an element of
-- 'nonterminals' 'cfg'
------------------------------------------------------------
-- | Vocabulary symbols of the grammar.
data V t nt = T t -- ^ a terminal
| NT nt -- ^ a nonterminal
deriving (Eq, Ord, Show, Data, Typeable)
instance Functor (V t) where
fmap _f (T t) = T t
fmap f (NT nt) = NT $ f nt
instance Bifunctor V where
bimap f _g (T t) = T $ f t
bimap _f g (NT nt) = NT $ g nt
-- | Returns 'True' iff the vocabularly symbols is a terminal.
isT :: V t nt -> Bool
isT (T _) = True
isT _ = False
-- | Returns 'True' iff the vocabularly symbols is a nonterminal.
isNT :: V t nt -> Bool
isNT (NT _) = True
isNT _ = False
-- | Returns the vocabulary symbols of the grammar: elements of
-- 'terminals' and 'nonterminals'.
vocabulary :: (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> S.Set (V t nt)
vocabulary cfg = S.map T (terminals cfg)
`S.union` S.map NT (nonterminals cfg)
-- | Synonym for lists of vocabulary symbols.
type Vs t nt = [V t nt]
-- | Productions over vocabulary symbols
data Production t nt = Production {
productionHead :: nt,
productionRhs :: Vs t nt
}
deriving (Eq, Ord, Show, Data, Typeable)
instance Bifunctor Production where
bimap f g (Production nt rhs) = Production (g nt) (map (bimap f g) rhs)
-- | The productions of the grammar.
productions :: (Cfg cfg t nt) => cfg t nt -> [Production t nt]
productions cfg = do
nt <- S.toList $ nonterminals cfg
vs <- S.toList $ productionRules cfg nt
return $ Production nt vs
-- | The productions for the given nonterminal
lookupProductions :: Eq nt => nt -> [Production t nt] -> [Vs t nt]
lookupProductions nt prods = [ rhs | Production nt' rhs <- prods,
nt == nt' ]
-- | Productions of a grammar collected by their left-hand sides.
type ProductionMap t nt = M.Map nt (S.Set (Vs t nt))
-- | The 'ProductionMap' for the grammar
productionMap :: (Cfg cfg t nt, Ord nt) => cfg t nt -> ProductionMap t nt
productionMap cfg
= M.fromList [(nt, productionRules cfg nt)
| nt <- S.toList $ nonterminals cfg]
-- | Returns 'True' iff the two inhabitants of 'Cfg' are equal.
eqCfg :: forall cfg cfg' t nt
. (Cfg cfg t nt, Cfg cfg' t nt, Eq nt, Eq t)
=> cfg t nt -> cfg' t nt -> Bool
eqCfg cfg cfg' = to4Tuple cfg == to4Tuple cfg'
{------------------------------------------------------------
-- | Compares the two inhabitants of 'Cfg'.
compareCfg :: forall cfg cfg' t nt
. (Cfg cfg t nt, Cfg cfg' t nt, Ord nt, Ord t)
=> cfg t nt -> cfg' t nt -> Ordering
compareCfg cfg cfg' = compare (to4Tuple cfg) (to4Tuple cfg')
------------------------------------------------------------}
-- | Converts the 'Cfg' to a 4-tuple that inhabits both 'Eq' and 'Ord'
-- if 't' and 'nt' do.
to4Tuple :: forall cfg t nt . (Cfg cfg t nt)
=> cfg t nt -> (nt, S.Set nt, S.Set t, [Production t nt])
-- We move the start symbol first to optimize the operations
-- since it's most likely to differ.
to4Tuple cfg = (
startSymbol cfg,
nonterminals cfg,
terminals cfg,
productions cfg)
-- | Returns all vocabulary used in the productions plus the start
-- symbol.
usedVocabulary :: (Cfg cfg t nt, Ord nt, Ord t)
=> cfg t nt -> S.Set (V t nt)
usedVocabulary cfg
= S.fromList
$ NT (startSymbol cfg) :
concat [ NT nt : vs | Production nt vs <- productions cfg]
-- | Returns all vocabulary used in the productions plus the start
-- symbol but not declared in 'nonterminals' or 'terminals'.
undeclaredVocabulary :: (Cfg cfg t nt, Ord nt, Ord t)
=> cfg t nt -> S.Set (V t nt)
undeclaredVocabulary cfg = usedVocabulary cfg S.\\ vocabulary cfg
------------------------------------------------------------
-- | Returns 'True' all the vocabulary used in the grammar is
-- declared.
isFullyDeclared :: (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> Bool
isFullyDeclared = S.null . undeclaredVocabulary
|
nedervold/context-free-grammar
|
src/Data/Cfg/Cfg.hs
|
Haskell
|
bsd-3-clause
| 5,238
|
module Passman.Engine.KeyDerivationSpec where
import Test.Hspec (Spec, describe, it)
import Test.Hspec.Expectations.Pretty
import qualified Passman.Engine.ByteString as B
import Passman.Engine.KeyDerivation
k :: String -> Key
k = Key . B.fromString
pbkdf2Salt :: Salt
pbkdf2Salt = Salt $ B.pack [ 0x19, 0x2a, 0x3b, 0x4c, 0x5d, 0x6e, 0x7f, 0x80 ]
pbkdf2DerivesExpectedKeyAscii :: () -> Expectation
pbkdf2DerivesExpectedKeyAscii _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey (PBKDF2WithHmacSHA1 1000) (Parameters 1 20) (k "passw0rd") pbkdf2Salt
expected = [ 0xac, 0x22, 0x98, 0xff, 0x9e, 0xc6, 0xd2, 0xaa
, 0x17, 0x16, 0x81, 0x29, 0x12, 0x48, 0xb5, 0x16
, 0xc7, 0x79, 0xca, 0xaa ]
pbkdf2DerivesExpectedKeyUtf8 :: () -> Expectation
pbkdf2DerivesExpectedKeyUtf8 _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey (PBKDF2WithHmacSHA1 1000) (Parameters 1 20) (k "pässw0rð") pbkdf2Salt
expected = [ 0x3a, 0xb9, 0xe9, 0xd1, 0x97, 0xd1, 0x40, 0x50
, 0x25, 0xfd, 0xd3, 0x1e, 0x24, 0x7d, 0xd5, 0xb0
, 0xba, 0x2d, 0x7b, 0x04 ]
sha512DigestSalt :: Salt
sha512DigestSalt = Salt $ B.pack [ 0x24, 0x78, 0x5a, 0x5b, 0x75, 0x28, 0x2d, 0x54, 0x72, 0x66 ]
sha512DigestDerivesExpectedKeyAscii :: () -> Expectation
sha512DigestDerivesExpectedKeyAscii _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Digest (Parameters 1 64) (k "password") sha512DigestSalt
expected = [ 0x8b, 0x0e, 0x37, 0x48, 0x61, 0xb5, 0xbc, 0xe4
, 0x79, 0xf3, 0x8d, 0x70, 0x81, 0xf5, 0xea, 0x43
, 0xcc, 0xfc, 0xa4, 0x82, 0x36, 0x01, 0x59, 0xdc
, 0xd5, 0xfe, 0x22, 0x63, 0x49, 0xff, 0x92, 0xa2
, 0x62, 0xa6, 0x9e, 0xc9, 0xac, 0x8a, 0x30, 0x3f
, 0x0b, 0xdd, 0xf6, 0xd7, 0xf1, 0xac, 0xd6, 0x2f
, 0x8a, 0x16, 0x0e, 0x11, 0xd3, 0x49, 0xbf, 0x5e
, 0xc3, 0x8b, 0x23, 0xf8, 0x25, 0x54, 0x77, 0xc3
]
sha512DigestDerivesExpectedKeyUtf8 :: () -> Expectation
sha512DigestDerivesExpectedKeyUtf8 _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Digest (Parameters 1 64) (k "pássw0rð") sha512DigestSalt
expected = [ 0x01, 0x7b, 0x8c, 0xc2, 0xb5, 0xcb, 0xc9, 0x34
, 0x09, 0xe1, 0x64, 0x6e, 0xaa, 0x3e, 0x97, 0x93
, 0x25, 0x45, 0xdc, 0xbe, 0x6b, 0x99, 0xf0, 0x53
, 0xd5, 0xf6, 0x9b, 0x31, 0xdd, 0x6f, 0xa9, 0xa3
, 0xa6, 0xd2, 0x5e, 0xa1, 0xcf, 0x6f, 0xf2, 0x45
, 0xef, 0xfc, 0x56, 0x18, 0x79, 0xaf, 0x29, 0xb3
, 0x00, 0xc8, 0x1f, 0xa2, 0x6e, 0x65, 0xe8, 0xa7
, 0xe4, 0x6e, 0xd4, 0x5b, 0x92, 0xbf, 0xc4, 0xf3
]
sha512PasswordSalt :: Salt
sha512PasswordSalt = Salt $ B.pack [ 0x73, 0x61, 0x6c, 0x74, 0x73, 0x61, 0x6c, 0x74 ]
sha512PasswordDerivesExpectedKeyAscii :: () -> Expectation
sha512PasswordDerivesExpectedKeyAscii _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Password (Parameters 1 64) (k "password") sha512PasswordSalt
expected = [ 0x45, 0x44, 0x33, 0xaa, 0xef, 0x02, 0xa4, 0x0c
, 0xa7, 0x21, 0x24, 0xad, 0x7a, 0xad, 0x26, 0x40
, 0x67, 0x8b, 0x0e, 0x54, 0xde, 0xa8, 0x98, 0xe7
, 0x67, 0xa4, 0x13, 0xa6, 0xda, 0x18, 0xc8, 0x5f
, 0x8a, 0xca, 0x07, 0x95, 0x96, 0xf3, 0xbe, 0x2f
, 0x95, 0xe1, 0xcf, 0xdd, 0x01, 0x42, 0x5b, 0xf5
, 0x82, 0x89, 0x31, 0x86, 0xfb, 0x2c, 0x90, 0x7c
, 0x70, 0x3c, 0xdd, 0xf0, 0xa3, 0xa2, 0x08, 0x50
]
sha512PasswordDerivesExpectedKey2Iterations :: () -> Expectation
sha512PasswordDerivesExpectedKey2Iterations _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Password (Parameters 2 64) (k "password") sha512PasswordSalt
expected = [ 0xbe, 0x87, 0x8f, 0xa3, 0x35, 0xfb, 0xe1, 0xe7
, 0x34, 0xbb, 0xec, 0x35, 0xbc, 0x12, 0x10, 0x60
, 0x92, 0xa3, 0x1a, 0xc5, 0x37, 0xe1, 0xd1, 0xcb
, 0x33, 0xed, 0x49, 0xdb, 0x1c, 0xfa, 0x2a, 0xeb
, 0x8d, 0x4c, 0x7b, 0x59, 0x9a, 0x59, 0xcd, 0x72
, 0xdc, 0x06, 0x9b, 0x36, 0x63, 0x89, 0x70, 0x1e
, 0x41, 0x01, 0x79, 0x98, 0x2b, 0xaa, 0x6e, 0x5a
, 0x19, 0x4a, 0x95, 0x7a, 0x5b, 0x40, 0x61, 0x43
]
sha512PasswordDerivesExpectedKeyUtf8 :: () -> Expectation
sha512PasswordDerivesExpectedKeyUtf8 _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Password (Parameters 1 64) (k "pássw0rð") sha512PasswordSalt
expected = [ 0x47, 0xbc, 0x66, 0x00, 0xae, 0x7f, 0xbc, 0xb6
, 0x74, 0xe9, 0x99, 0x8f, 0x3a, 0x12, 0x0c, 0x02
, 0x21, 0xbd, 0x44, 0x53, 0xf1, 0xf5, 0x13, 0x0f
, 0x55, 0x42, 0x75, 0x15, 0x9d, 0xd4, 0xbe, 0xcf
, 0x65, 0xff, 0x7d, 0x0e, 0x69, 0xba, 0x3a, 0xdc
, 0x68, 0x7e, 0xc8, 0xdd, 0x30, 0xcb, 0x09, 0x74
, 0x10, 0x65, 0x32, 0x1b, 0xe1, 0xf5, 0x1b, 0xd8
, 0xba, 0xe7, 0xc5, 0xd6, 0x85, 0x33, 0xfc, 0x49
]
spec :: Spec
spec = do
describe "PBKDF2/SHA1 derivation" $ do
it "should produce the expected key from ascii password" $
pbkdf2DerivesExpectedKeyAscii ()
it "should produce the expected key from non-ascii password" $
pbkdf2DerivesExpectedKeyUtf8 ()
describe "SHA512 digest derivation" $ do
it "should produce the expected key from ascii password" $
sha512DigestDerivesExpectedKeyAscii ()
it "should produce the expected key from non-ascii password" $
sha512DigestDerivesExpectedKeyUtf8 ()
describe "SHA512 password derivation" $ do
it "should produce the expected key from ascii password" $
sha512PasswordDerivesExpectedKeyAscii ()
it "should produce the expected key from ascii password with 2 iterations" $
sha512PasswordDerivesExpectedKey2Iterations ()
it "should produce the expected key from non-ascii password" $
sha512PasswordDerivesExpectedKeyUtf8 ()
|
chwthewke/passman-hs
|
test/Passman/Engine/KeyDerivationSpec.hs
|
Haskell
|
bsd-3-clause
| 6,604
|
module Day10 where
import Data.List
repeatLookAndSay :: Int -> String -> String
repeatLookAndSay n = (!! n) . iterate lookAndSay
lookAndSay :: String -> String
lookAndSay = (>>= say) . group
where say g = show (length g) ++ take 1 g
|
patrickherrmann/advent
|
src/Day10.hs
|
Haskell
|
bsd-3-clause
| 237
|
{-# LANGUAGE DeriveDataTypeable #-}
-- | The central type in TagSoup
module Text.HTML.TagSoup.Type(
-- * Data structures and parsing
StringLike, Tag(..), Attribute, Row, Column,
-- * Position manipulation
Position(..), tagPosition, nullPosition, positionChar, positionString,
-- * Tag identification
isTagOpen, isTagClose, isTagText, isTagWarning, isTagPosition,
isTagOpenName, isTagCloseName, isTagComment,
-- * Extraction
fromTagText, fromAttrib,
maybeTagText, maybeTagWarning,
innerText,
) where
import Data.List (foldl')
import Data.Maybe (fromMaybe, mapMaybe)
import Text.StringLike
import Data.Data(Data, Typeable)
-- | An HTML attribute @id=\"name\"@ generates @(\"id\",\"name\")@
type Attribute str = (str,str)
-- | The row/line of a position, starting at 1
type Row = Int
-- | The column of a position, starting at 1
type Column = Int
--- All positions are stored as a row and a column, with (1,1) being the
--- top-left position
data Position = Position !Row !Column deriving (Show,Eq,Ord)
nullPosition :: Position
nullPosition = Position 1 1
positionString :: Position -> String -> Position
positionString = foldl' positionChar
positionChar :: Position -> Char -> Position
positionChar (Position r c) x = case x of
'\n' -> Position (r+1) 1
'\t' -> Position r (c + 8 - mod (c-1) 8)
_ -> Position r (c+1)
tagPosition :: Position -> Tag str
tagPosition (Position r c) = TagPosition r c
-- | A single HTML element. A whole document is represented by a list of @Tag@.
-- There is no requirement for 'TagOpen' and 'TagClose' to match.
data Tag str =
TagOpen str [Attribute str] -- ^ An open tag with 'Attribute's in their original order
| TagClose str -- ^ A closing tag
| TagText str -- ^ A text node, guaranteed not to be the empty string
| TagComment str -- ^ A comment
| TagWarning str -- ^ Meta: A syntax error in the input file
| TagPosition !Row !Column -- ^ Meta: The position of a parsed element
deriving (Show, Eq, Ord, Data, Typeable)
instance Functor Tag where
fmap f (TagOpen x y) = TagOpen (f x) [(f a, f b) | (a,b) <- y]
fmap f (TagClose x) = TagClose (f x)
fmap f (TagText x) = TagText (f x)
fmap f (TagComment x) = TagComment (f x)
fmap f (TagWarning x) = TagWarning (f x)
fmap f (TagPosition x y) = TagPosition x y
-- | Test if a 'Tag' is a 'TagOpen'
isTagOpen :: Tag str -> Bool
isTagOpen (TagOpen {}) = True; isTagOpen _ = False
-- | Test if a 'Tag' is a 'TagClose'
isTagClose :: Tag str -> Bool
isTagClose (TagClose {}) = True; isTagClose _ = False
-- | Test if a 'Tag' is a 'TagText'
isTagText :: Tag str -> Bool
isTagText (TagText {}) = True; isTagText _ = False
-- | Extract the string from within 'TagText', otherwise 'Nothing'
maybeTagText :: Tag str -> Maybe str
maybeTagText (TagText x) = Just x
maybeTagText _ = Nothing
-- | Extract the string from within 'TagText', crashes if not a 'TagText'
fromTagText :: Show str => Tag str -> str
fromTagText (TagText x) = x
fromTagText x = error $ "(" ++ show x ++ ") is not a TagText"
-- | Extract all text content from tags (similar to Verbatim found in HaXml)
innerText :: StringLike str => [Tag str] -> str
innerText = strConcat . mapMaybe maybeTagText
-- | Test if a 'Tag' is a 'TagWarning'
isTagWarning :: Tag str -> Bool
isTagWarning (TagWarning {}) = True; isTagWarning _ = False
-- | Extract the string from within 'TagWarning', otherwise 'Nothing'
maybeTagWarning :: Tag str -> Maybe str
maybeTagWarning (TagWarning x) = Just x
maybeTagWarning _ = Nothing
-- | Test if a 'Tag' is a 'TagPosition'
isTagPosition :: Tag str -> Bool
isTagPosition TagPosition{} = True; isTagPosition _ = False
-- | Extract an attribute, crashes if not a 'TagOpen'.
-- Returns @\"\"@ if no attribute present.
--
-- Warning: does not distinquish between missing attribute
-- and present attribute with value @\"\"@.
fromAttrib :: (Show str, Eq str, StringLike str) => str -> Tag str -> str
fromAttrib att tag = fromMaybe empty $ maybeAttrib att tag
-- | Extract an attribute, crashes if not a 'TagOpen'.
-- Returns @Nothing@ if no attribute present.
maybeAttrib :: (Show str, Eq str) => str -> Tag str -> Maybe str
maybeAttrib att (TagOpen _ atts) = lookup att atts
maybeAttrib _ x = error ("(" ++ show x ++ ") is not a TagOpen")
-- | Returns True if the 'Tag' is 'TagOpen' and matches the given name
isTagOpenName :: Eq str => str -> Tag str -> Bool
isTagOpenName name (TagOpen n _) = n == name
isTagOpenName _ _ = False
-- | Returns True if the 'Tag' is 'TagClose' and matches the given name
isTagCloseName :: Eq str => str -> Tag str -> Bool
isTagCloseName name (TagClose n) = n == name
isTagCloseName _ _ = False
-- | Test if a 'Tag' is a 'TagComment'
isTagComment :: Tag str -> Bool
isTagComment TagComment {} = True; isTagComment _ = False
|
ndmitchell/tagsoup
|
src/Text/HTML/TagSoup/Type.hs
|
Haskell
|
bsd-3-clause
| 4,929
|
{-# LANGUAGE MagicHash #-}
-- |
-- Module: $HEADER$
-- Description: Splitting numbers in to digits and vice versa.
-- Copyright: (c) 2009, 2013, 2014 Peter Trsko
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: non-portable (MagicHash, uses GHC internals)
--
-- Functions for splitting numbers in to digits and summing them back together.
module Data.Digits
(
-- * Counting Digits of a Number
numberOfDigits
, numberOfDigitsInBase
-- * Splitting Number in to Digits
, digits
, reverseDigits
, digitsInBase
, reverseDigitsInBase
, genericDigitsInBase
-- * Joining Digits to a Number
, fromDigits
, fromDigitsInBase
)
where
import GHC.Base (Int(..), (+#))
import Data.Word (Word, Word8, Word16, Word32, Word64)
-- Solely required for SPECIALIZE pragmas.
-- | Return number of digits number is consisting from in a specified base.
--
-- Zero is an exception, because this function returns zero for it and not one
-- as it might be expected. This is due to the fact, that if numbers are
-- represented as a list of digits, it's often desired to interpret zero as an
-- empty list and not list with one element that is zero.
--
-- Some properties that hold:
--
-- > forall b. Integral b > 0 =>
-- > numberOfDigitsInBase b 0 = 0
-- > numberOfDigitsInBase b n /= 0 when n /= 0
-- > numberOfDigitsInBase b (negate n) = numberOfDigits b n
numberOfDigitsInBase :: Integral a => a -> a -> Int
numberOfDigitsInBase = numberOfDigitsInBaseImpl "numberOfDigitsInBase"
-- | Implementation behind 'numberOfDigitsInBase' that is parametrized by
-- function name which allows it to print more specific error messages.
--
-- *Should not be exported.*
numberOfDigitsInBaseImpl :: Integral a => String -> a -> a -> Int
numberOfDigitsInBaseImpl _ _ 0 = 0
numberOfDigitsInBaseImpl functionName base n
| base <= 0 = negativeOrZeroBaseError functionName
| otherwise = numberOfDigitsInBase# 1# $ if n < 0 then negate n else n
where
numberOfDigitsInBase# d# m = case m `quot` base of
0 -> I# d#
o -> numberOfDigitsInBase# (d# +# 1#) o
{-# INLINE numberOfDigitsInBaseImpl #-}
-- | Return number of digits in base 10. It's implemented in terms of
-- 'numberOfDigitsInBase' so all it's properties apply also here.
numberOfDigits :: Integral a => a -> Int
numberOfDigits = numberOfDigitsInBaseImpl "numberOfDigits" 10
{-# SPECIALIZE numberOfDigits :: Int -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word8 -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word16 -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word32 -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word64 -> Int #-}
-- | Split number in to digits.
--
-- Negative nubers are negated before they are split in to digits. It's similar
-- to how 'numberOfDigitsInBase' handles it.
--
-- This function uses very generic interface so it's possible to use it for any
-- list-like data type. It also works for string/text types like @ByteString@s.
--
-- For an example, of how it can be used, we can look in to definitions of
-- 'digitsInBase' and 'reverseDigitsInBase':
--
-- > digitsInBase :: Integral a => a -> a -> [a]
-- > digitsInBase base n = genericDigitsInBase (:) (.) base n []
-- >
-- > reverseDigitsInBase :: Integral a => a -> a -> [a]
-- > reverseDigitsInBase base n = genericDigitsInBase (:) (flip (.)) base n []
genericDigitsInBase
:: Integral a
=> (a -> l -> l)
-- ^ Cons function, for @[a]@ it's @(:) :: a -> [a] -> [a]@.
-> ((l -> l) -> (l -> l) -> l -> l)
-- ^ Composition function of list transformation, most commonly it's
-- either @(.)@ or @flip (.)@. This allows to implement 'digits' and
-- 'reverseDigits' using one underlying function.
-> a
-- ^ Base in which we are operating.
-> a
-- ^ Number to be split in to digits.
-> l -> l
genericDigitsInBase = genericDigitsInBaseImpl "genericDigitsInBase"
-- | Implementation behind 'genericDigitsInBase' that is parametrized by
-- function name which allows it to print more specific error messages.
--
-- *Should not be exported.*
genericDigitsInBaseImpl
:: Integral a
=> String
-> (a -> l -> l)
-> ((l -> l) -> (l -> l) -> l -> l)
-> a
-> a
-> l -> l
genericDigitsInBaseImpl _ _ _ _ 0 = id
genericDigitsInBaseImpl functionName cons o base n
| base <= 0 = negativeOrZeroBaseError functionName
| otherwise = genericDigitsInBase' $ if n < 0 then negate n else n
where
genericDigitsInBase' m
| rest == 0 = cons d
| otherwise = genericDigitsInBase' rest `o` cons d
where
(rest, d) = m `quotRem` base
{-# INLINE genericDigitsInBaseImpl #-}
-- | Split number in to list of digits in specified base.
--
-- Example:
--
-- >>> digitsInBase 10 1234567890
-- [1,2,3,4,5,6,7,8,9,0]
digitsInBase :: Integral a => a -> a -> [a]
digitsInBase = digitsInBaseImpl "digitsInBase"
{-# SPECIALIZE digitsInBase :: Int -> Int -> [Int] #-}
{-# SPECIALIZE digitsInBase :: Word -> Word -> [Word] #-}
{-# SPECIALIZE digitsInBase :: Word8 -> Word8 -> [Word8] #-}
{-# SPECIALIZE digitsInBase :: Word16 -> Word16 -> [Word16] #-}
{-# SPECIALIZE digitsInBase :: Word32 -> Word32 -> [Word32] #-}
{-# SPECIALIZE digitsInBase :: Word64 -> Word64 -> [Word64] #-}
-- | Implementation behind 'digitsInBase' that is parametrized by function name
-- which allows it to print more specific error messages.
--
-- *Should not be exported.*
digitsInBaseImpl :: Integral a => String -> a -> a -> [a]
digitsInBaseImpl functionName base n =
genericDigitsInBaseImpl functionName (:) (.) base n []
-- | Split number in to list of digits in base 10.
--
-- Example:
--
-- >>> digits 1234567890
-- [1,2,3,4,5,6,7,8,9,0]
digits :: Integral a => a -> [a]
digits = digitsInBaseImpl "digits" 10
{-# SPECIALIZE digits :: Int -> [Int] #-}
{-# SPECIALIZE digits :: Word -> [Word] #-}
{-# SPECIALIZE digits :: Word8 -> [Word8] #-}
{-# SPECIALIZE digits :: Word16 -> [Word16] #-}
{-# SPECIALIZE digits :: Word32 -> [Word32] #-}
{-# SPECIALIZE digits :: Word64 -> [Word64] #-}
-- | Split number in to list of digits in specified base, but in reverse order.
--
-- Example:
--
-- >>> reverseDigitsInBase 10 1234567890
-- [0,9,8,7,6,5,4,3,2,1]
reverseDigitsInBase :: Integral a => a -> a -> [a]
reverseDigitsInBase = reverseDigitsInBaseImpl "reverseDigitsInBase"
{-# SPECIALIZE reverseDigitsInBase :: Int -> Int -> [Int] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word -> Word -> [Word] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word8 -> Word8 -> [Word8] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word16 -> Word16 -> [Word16] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word32 -> Word32 -> [Word32] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word64 -> Word64 -> [Word64] #-}
-- | Implementation behind 'reverseDigitsInBase' that is parametrized by
-- function name which allows it to print more specific error messages.
--
-- *Should not be exported.*
reverseDigitsInBaseImpl :: Integral a => String -> a -> a -> [a]
reverseDigitsInBaseImpl functionName base n =
genericDigitsInBaseImpl functionName (:) (flip (.)) base n []
-- | Split number in to list of digits in base 10, but in reverse order.
--
-- Example:
--
-- >>> reverseDigits 1234567890
-- [0,9,8,7,6,5,4,3,2,1]
reverseDigits :: Integral a => a -> [a]
reverseDigits = reverseDigitsInBaseImpl "reverseDigits" 10
{-# SPECIALIZE reverseDigits :: Int -> [Int] #-}
{-# SPECIALIZE reverseDigits :: Word -> [Word] #-}
{-# SPECIALIZE reverseDigits :: Word8 -> [Word8] #-}
{-# SPECIALIZE reverseDigits :: Word16 -> [Word16] #-}
{-# SPECIALIZE reverseDigits :: Word32 -> [Word32] #-}
{-# SPECIALIZE reverseDigits :: Word64 -> [Word64] #-}
-- | Sum list of digits in specified base.
fromDigitsInBase :: Integral a => a -> [a] -> a
fromDigitsInBase base = foldl ((+) . (base *)) 0
{-# SPECIALIZE fromDigitsInBase :: Int -> [Int] -> Int #-}
{-# SPECIALIZE fromDigitsInBase :: Word -> [Word] -> Word #-}
{-# SPECIALIZE fromDigitsInBase :: Word8 -> [Word8] -> Word8 #-}
{-# SPECIALIZE fromDigitsInBase :: Word16 -> [Word16] -> Word16 #-}
{-# SPECIALIZE fromDigitsInBase :: Word32 -> [Word32] -> Word32 #-}
{-# SPECIALIZE fromDigitsInBase :: Word64 -> [Word64] -> Word64 #-}
-- | Sum list of digits in base 10.
fromDigits :: Integral a => [a] -> a
fromDigits = fromDigitsInBase 10
{-# SPECIALIZE fromDigits :: [Int] -> Int #-}
{-# SPECIALIZE fromDigits :: [Word] -> Word #-}
{-# SPECIALIZE fromDigits :: [Word8] -> Word8 #-}
{-# SPECIALIZE fromDigits :: [Word16] -> Word16 #-}
{-# SPECIALIZE fromDigits :: [Word32] -> Word32 #-}
{-# SPECIALIZE fromDigits :: [Word64] -> Word64 #-}
-- | Throw error in case when base value doesn't make sense.
--
-- *Should not be exported.*
negativeOrZeroBaseError :: String -> a
negativeOrZeroBaseError =
error . (++ ": Negative or zero base doesn't make sense.")
{-# INLINE negativeOrZeroBaseError #-}
|
trskop/hs-not-found
|
not-found-digits/src/Data/Digits.hs
|
Haskell
|
bsd-3-clause
| 8,996
|
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -fno-warn-unused-imports #-}
module Main where
import Control.Monad (unless)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Config.Parser
import Data.Config.Types (Config)
import Data.Config.Pretty (pretty)
import Data.Text (Text)
import qualified Data.Text.IO as T
import Data.Attoparsec.Text
import System.Environment (getArgs)
import System.Exit (die)
main :: IO ()
main = do
args <- getArgs
let file = case length args of
1 -> head args
_ -> error "Die a horrible death"
body <- T.readFile file
let result = parseOnly konvigParser body
let text = case result of
Right config -> pretty config
Left msg -> error msg
T.putStr text
|
afcowie/konvig
|
tests/RoundTrip.hs
|
Haskell
|
bsd-3-clause
| 778
|
module Ivory.Tower.AST.Init where
data Init = Init
deriving (Eq, Show, Ord)
|
GaloisInc/tower
|
tower/src/Ivory/Tower/AST/Init.hs
|
Haskell
|
bsd-3-clause
| 80
|
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Real.CBOR (serialise, deserialise, deserialiseNull) where
import Real.Types
import Data.Binary.Serialise.CBOR.Class
import Data.Binary.Serialise.CBOR.Encoding hiding (Tokens(..))
import Data.Binary.Serialise.CBOR.Decoding
import Data.Binary.Serialise.CBOR.Read
import Data.Binary.Serialise.CBOR.Write
import qualified Data.Binary.Get as Bin
import Data.Word
import Data.Monoid
import Control.Applicative
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Internal as BS
import qualified Data.ByteString.Builder as BS
serialise :: [GenericPackageDescription] -> BS.ByteString
--serialise :: Serialise a => a -> BS.ByteString
serialise = BS.toLazyByteString . toBuilder . encode
deserialise :: BS.ByteString -> [GenericPackageDescription]
--deserialise :: Serialise a => BS.ByteString -> a
deserialise bs = feedAll (deserialiseIncremental decode) bs
where
feedAll (Bin.Done _ _ x) _ = x
feedAll (Bin.Partial k) lbs = case lbs of
BS.Chunk bs lbs' -> feedAll (k (Just bs)) lbs'
BS.Empty -> feedAll (k Nothing) BS.empty
feedAll (Bin.Fail _ pos msg) _ =
error ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg)
deserialiseNull :: BS.ByteString -> ()
deserialiseNull bs = feedAll (deserialiseIncremental decodeListNull) bs
where
decodeListNull = do decodeListLenIndef; go
go = do stop <- decodeBreakOr
if stop then return ()
else do !x <- decode :: Decoder GenericPackageDescription
go
feedAll (Bin.Done _ _ x) _ = x
feedAll (Bin.Partial k) lbs = case lbs of
BS.Chunk bs lbs' -> feedAll (k (Just bs)) lbs'
BS.Empty -> feedAll (k Nothing) BS.empty
feedAll (Bin.Fail _ pos msg) _ =
error ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg)
encodeCtr0 :: Word -> Encoding
encodeCtr1 :: Serialise a => Word -> a -> Encoding
encodeCtr2 :: (Serialise a, Serialise b) => Word -> a -> b -> Encoding
encodeCtr0 n = encodeListLen 1 <> encode (n :: Word)
encodeCtr1 n a = encodeListLen 2 <> encode (n :: Word) <> encode a
encodeCtr2 n a b = encodeListLen 3 <> encode (n :: Word) <> encode a <> encode b
encodeCtr3 n a b c
= encodeListLen 4 <> encode (n :: Word) <> encode a <> encode b
<> encode c
encodeCtr4 n a b c d
= encodeListLen 5 <> encode (n :: Word) <> encode a <> encode b
<> encode c <> encode d
encodeCtr6 n a b c d e f
= encodeListLen 7 <> encode (n :: Word) <> encode a <> encode b
<> encode c <> encode d <> encode e <> encode f
encodeCtr7 n a b c d e f g
= encodeListLen 8 <> encode (n :: Word) <> encode a <> encode b
<> encode c <> encode d <> encode e <> encode f
<> encode g
{-# INLINE encodeCtr0 #-}
{-# INLINE encodeCtr1 #-}
{-# INLINE encodeCtr2 #-}
{-# INLINE encodeCtr3 #-}
{-# INLINE encodeCtr4 #-}
{-# INLINE encodeCtr6 #-}
{-# INLINE encodeCtr7 #-}
{-# INLINE decodeCtrTag #-}
{-# INLINE decodeCtrBody0 #-}
{-# INLINE decodeCtrBody1 #-}
{-# INLINE decodeCtrBody2 #-}
{-# INLINE decodeCtrBody3 #-}
decodeCtrTag = (\len tag -> (tag, len)) <$> decodeListLen <*> decodeWord
decodeCtrBody0 1 f = pure f
decodeCtrBody1 2 f = do x1 <- decode
return $! f x1
decodeCtrBody2 3 f = do x1 <- decode
x2 <- decode
return $! f x1 x2
decodeCtrBody3 4 f = do x1 <- decode
x2 <- decode
x3 <- decode
return $! f x1 x2 x3
{-# INLINE decodeSingleCtr0 #-}
{-# INLINE decodeSingleCtr1 #-}
{-# INLINE decodeSingleCtr2 #-}
{-# INLINE decodeSingleCtr3 #-}
{-# INLINE decodeSingleCtr4 #-}
{-# INLINE decodeSingleCtr6 #-}
{-# INLINE decodeSingleCtr7 #-}
decodeSingleCtr0 v f = decodeListLenOf 1 *> decodeWordOf v *> pure f
decodeSingleCtr1 v f = decodeListLenOf 2 *> decodeWordOf v *> pure f <*> decode
decodeSingleCtr2 v f = decodeListLenOf 3 *> decodeWordOf v *> pure f <*> decode <*> decode
decodeSingleCtr3 v f = decodeListLenOf 4 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode
decodeSingleCtr4 v f = decodeListLenOf 5 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode
decodeSingleCtr6 v f = decodeListLenOf 7 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode
decodeSingleCtr7 v f = decodeListLenOf 8 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode
instance Serialise PackageName where
encode (PackageName a) = encodeCtr1 1 a
decode = decodeSingleCtr1 1 PackageName
instance Serialise Version where
encode (Version a b) = encodeCtr2 1 a b
decode = decodeSingleCtr2 1 Version
instance Serialise PackageId where
encode (PackageId a b) = encodeCtr2 1 a b
decode = decodeSingleCtr2 1 PackageId
instance Serialise VersionRange where
encode AnyVersion = encodeCtr0 1
encode (ThisVersion a) = encodeCtr1 2 a
encode (LaterVersion a) = encodeCtr1 3 a
encode (EarlierVersion a) = encodeCtr1 4 a
encode (WildcardVersion a) = encodeCtr1 5 a
encode (UnionVersionRanges a b) = encodeCtr2 6 a b
encode (IntersectVersionRanges a b) = encodeCtr2 7 a b
encode (VersionRangeParens a) = encodeCtr1 8 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l AnyVersion
2 -> decodeCtrBody1 l ThisVersion
3 -> decodeCtrBody1 l LaterVersion
4 -> decodeCtrBody1 l EarlierVersion
5 -> decodeCtrBody1 l WildcardVersion
6 -> decodeCtrBody2 l UnionVersionRanges
7 -> decodeCtrBody2 l IntersectVersionRanges
8 -> decodeCtrBody1 l VersionRangeParens
instance Serialise Dependency where
encode (Dependency a b) = encodeCtr2 1 a b
decode = decodeSingleCtr2 1 Dependency
instance Serialise CompilerFlavor where
encode GHC = encodeCtr0 1
encode NHC = encodeCtr0 2
encode YHC = encodeCtr0 3
encode Hugs = encodeCtr0 4
encode HBC = encodeCtr0 5
encode Helium = encodeCtr0 6
encode JHC = encodeCtr0 7
encode LHC = encodeCtr0 8
encode UHC = encodeCtr0 9
encode (HaskellSuite a) = encodeCtr1 10 a
encode (OtherCompiler a) = encodeCtr1 11 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l GHC
2 -> decodeCtrBody0 l NHC
3 -> decodeCtrBody0 l YHC
4 -> decodeCtrBody0 l Hugs
5 -> decodeCtrBody0 l HBC
6 -> decodeCtrBody0 l Helium
7 -> decodeCtrBody0 l JHC
8 -> decodeCtrBody0 l LHC
9 -> decodeCtrBody0 l UHC
10 -> decodeCtrBody1 l HaskellSuite
11 -> decodeCtrBody1 l OtherCompiler
instance Serialise License where
encode (GPL a) = encodeCtr1 1 a
encode (AGPL a) = encodeCtr1 2 a
encode (LGPL a) = encodeCtr1 3 a
encode BSD3 = encodeCtr0 4
encode BSD4 = encodeCtr0 5
encode MIT = encodeCtr0 6
encode (Apache a) = encodeCtr1 7 a
encode PublicDomain = encodeCtr0 8
encode AllRightsReserved = encodeCtr0 9
encode OtherLicense = encodeCtr0 10
encode (UnknownLicense a) = encodeCtr1 11 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l GPL
2 -> decodeCtrBody1 l AGPL
3 -> decodeCtrBody1 l LGPL
4 -> decodeCtrBody0 l BSD3
5 -> decodeCtrBody0 l BSD4
6 -> decodeCtrBody0 l MIT
7 -> decodeCtrBody1 l Apache
8 -> decodeCtrBody0 l PublicDomain
9 -> decodeCtrBody0 l AllRightsReserved
10 -> decodeCtrBody0 l OtherLicense
11 -> decodeCtrBody1 l UnknownLicense
instance Serialise SourceRepo where
encode (SourceRepo a b c d e f g) = encodeCtr7 1 a b c d e f g
decode = decodeSingleCtr7 1 SourceRepo
instance Serialise RepoKind where
encode RepoHead = encodeCtr0 1
encode RepoThis = encodeCtr0 2
encode (RepoKindUnknown a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l RepoHead
2 -> decodeCtrBody0 l RepoThis
3 -> decodeCtrBody1 l RepoKindUnknown
instance Serialise RepoType where
encode Darcs = encodeCtr0 1
encode Git = encodeCtr0 2
encode SVN = encodeCtr0 3
encode CVS = encodeCtr0 4
encode Mercurial = encodeCtr0 5
encode GnuArch = encodeCtr0 6
encode Bazaar = encodeCtr0 7
encode Monotone = encodeCtr0 8
encode (OtherRepoType a) = encodeCtr1 9 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Darcs
2 -> decodeCtrBody0 l Git
3 -> decodeCtrBody0 l SVN
4 -> decodeCtrBody0 l CVS
5 -> decodeCtrBody0 l Mercurial
6 -> decodeCtrBody0 l GnuArch
7 -> decodeCtrBody0 l Bazaar
8 -> decodeCtrBody0 l Monotone
9 -> decodeCtrBody1 l OtherRepoType
instance Serialise BuildType where
encode Simple = encodeCtr0 1
encode Configure = encodeCtr0 2
encode Make = encodeCtr0 3
encode Custom = encodeCtr0 4
encode (UnknownBuildType a) = encodeCtr1 5 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Simple
2 -> decodeCtrBody0 l Configure
3 -> decodeCtrBody0 l Make
4 -> decodeCtrBody0 l Custom
5 -> decodeCtrBody1 l UnknownBuildType
instance Serialise Library where
encode (Library a b c) = encodeCtr3 1 a b c
decode = decodeSingleCtr3 1 Library
instance Serialise Executable where
encode (Executable a b c) = encodeCtr3 1 a b c
decode = decodeSingleCtr3 1 Executable
instance Serialise TestSuite where
encode (TestSuite a b c d) = encodeCtr4 1 a b c d
decode = decodeSingleCtr4 1 TestSuite
instance Serialise TestSuiteInterface where
encode (TestSuiteExeV10 a b) = encodeCtr2 1 a b
encode (TestSuiteLibV09 a b) = encodeCtr2 2 a b
encode (TestSuiteUnsupported a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody2 l TestSuiteExeV10
2 -> decodeCtrBody2 l TestSuiteLibV09
3 -> decodeCtrBody1 l TestSuiteUnsupported
instance Serialise TestType where
encode (TestTypeExe a) = encodeCtr1 1 a
encode (TestTypeLib a) = encodeCtr1 2 a
encode (TestTypeUnknown a b) = encodeCtr2 3 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l TestTypeExe
2 -> decodeCtrBody1 l TestTypeLib
3 -> decodeCtrBody2 l TestTypeUnknown
instance Serialise Benchmark where
encode (Benchmark a b c d) = encodeCtr4 1 a b c d
decode = decodeSingleCtr4 1 Benchmark
instance Serialise BenchmarkInterface where
encode (BenchmarkExeV10 a b) = encodeCtr2 1 a b
encode (BenchmarkUnsupported a) = encodeCtr1 2 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody2 l BenchmarkExeV10
2 -> decodeCtrBody1 l BenchmarkUnsupported
instance Serialise BenchmarkType where
encode (BenchmarkTypeExe a) = encodeCtr1 1 a
encode (BenchmarkTypeUnknown a b) = encodeCtr2 2 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l BenchmarkTypeExe
2 -> decodeCtrBody2 l BenchmarkTypeUnknown
instance Serialise ModuleName where
encode (ModuleName a) = encodeCtr1 1 a
decode = decodeSingleCtr1 1 ModuleName
instance Serialise BuildInfo where
encode (BuildInfo a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20
a21 a22 a23 a24 a25) =
encodeListLen 26 <> encode (1 :: Word) <>
encode a1 <> encode a2 <> encode a3 <> encode a4 <> encode a5 <>
encode a6 <> encode a7 <> encode a8 <> encode a9 <> encode a10 <>
encode a11 <> encode a12 <> encode a13 <> encode a14 <> encode a15 <>
encode a16 <> encode a17 <> encode a18 <> encode a19 <> encode a20 <>
encode a21 <> encode a22 <> encode a23 <> encode a24 <> encode a25
decode = decodeListLenOf 26 *> decodeWordOf 1 *>
pure BuildInfo <*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
instance Serialise Language where
encode Haskell98 = encodeCtr0 1
encode Haskell2010 = encodeCtr0 2
encode (UnknownLanguage a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Haskell98
2 -> decodeCtrBody0 l Haskell2010
3 -> decodeCtrBody1 l UnknownLanguage
instance Serialise Extension where
encode (EnableExtension a) = encodeCtr1 1 a
encode (DisableExtension a) = encodeCtr1 2 a
encode (UnknownExtension a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l EnableExtension
2 -> decodeCtrBody1 l DisableExtension
3 -> decodeCtrBody1 l UnknownExtension
instance Serialise KnownExtension where
encode ke = encodeCtr1 1 (fromEnum ke)
decode = decodeSingleCtr1 1 toEnum
instance Serialise PackageDescription where
encode (PackageDescription a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20
a21 a22 a23 a24 a25 a26 a27 a28) =
encodeListLen 29 <> encode (1 :: Word) <>
encode a1 <> encode a2 <> encode a3 <> encode a4 <> encode a5 <>
encode a6 <> encode a7 <> encode a8 <> encode a9 <> encode a10 <>
encode a11 <> encode a12 <> encode a13 <> encode a14 <> encode a15 <>
encode a16 <> encode a17 <> encode a18 <> encode a19 <> encode a20 <>
encode a21 <> encode a22 <> encode a23 <> encode a24 <> encode a25 <>
encode a26 <> encode a27 <> encode a28
decode = decodeListLenOf 29 *> decodeWordOf 1 *>
pure PackageDescription
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode
instance Serialise OS where
encode Linux = encodeCtr0 1
encode Windows = encodeCtr0 2
encode OSX = encodeCtr0 3
encode FreeBSD = encodeCtr0 4
encode OpenBSD = encodeCtr0 5
encode NetBSD = encodeCtr0 6
encode Solaris = encodeCtr0 7
encode AIX = encodeCtr0 8
encode HPUX = encodeCtr0 9
encode IRIX = encodeCtr0 10
encode HaLVM = encodeCtr0 11
encode IOS = encodeCtr0 12
encode (OtherOS a) = encodeCtr1 13 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Linux
2 -> decodeCtrBody0 l Windows
3 -> decodeCtrBody0 l OSX
4 -> decodeCtrBody0 l FreeBSD
5 -> decodeCtrBody0 l OpenBSD
6 -> decodeCtrBody0 l NetBSD
7 -> decodeCtrBody0 l Solaris
8 -> decodeCtrBody0 l AIX
9 -> decodeCtrBody0 l HPUX
10 -> decodeCtrBody0 l IRIX
11 -> decodeCtrBody0 l HaLVM
12 -> decodeCtrBody0 l IOS
13 -> decodeCtrBody1 l OtherOS
instance Serialise Arch where
encode I386 = encodeCtr0 1
encode X86_64 = encodeCtr0 2
encode PPC = encodeCtr0 3
encode PPC64 = encodeCtr0 4
encode Sparc = encodeCtr0 5
encode Arm = encodeCtr0 6
encode Mips = encodeCtr0 7
encode SH = encodeCtr0 8
encode IA64 = encodeCtr0 9
encode S390 = encodeCtr0 10
encode Alpha = encodeCtr0 11
encode Hppa = encodeCtr0 12
encode Rs6000 = encodeCtr0 13
encode M68k = encodeCtr0 14
encode (OtherArch a) = encodeCtr1 15 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l I386
2 -> decodeCtrBody0 l X86_64
3 -> decodeCtrBody0 l PPC
4 -> decodeCtrBody0 l PPC64
5 -> decodeCtrBody0 l Sparc
6 -> decodeCtrBody0 l Arm
7 -> decodeCtrBody0 l Mips
8 -> decodeCtrBody0 l SH
9 -> decodeCtrBody0 l IA64
10 -> decodeCtrBody0 l S390
11 -> decodeCtrBody0 l Alpha
12 -> decodeCtrBody0 l Hppa
13 -> decodeCtrBody0 l Rs6000
14 -> decodeCtrBody0 l M68k
15 -> decodeCtrBody1 l OtherArch
instance Serialise Flag where
encode (MkFlag a b c d) = encodeCtr4 1 a b c d
decode = decodeSingleCtr4 1 MkFlag
instance Serialise FlagName where
encode (FlagName a) = encodeCtr1 1 a
decode = decodeSingleCtr1 1 FlagName
instance (Serialise a, Serialise b, Serialise c) => Serialise (CondTree a b c) where
encode (CondNode a b c) = encodeCtr3 1 a b c
decode = decodeSingleCtr3 1 CondNode
{-# SPECIALIZE instance Serialise c => Serialise (CondTree ConfVar [Dependency] c) #-}
instance Serialise ConfVar where
encode (OS a) = encodeCtr1 1 a
encode (Arch a) = encodeCtr1 2 a
encode (Flag a) = encodeCtr1 3 a
encode (Impl a b) = encodeCtr2 4 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l OS
2 -> decodeCtrBody1 l Arch
3 -> decodeCtrBody1 l Flag
4 -> decodeCtrBody2 l Impl
instance Serialise a => Serialise (Condition a) where
encode (Var a) = encodeCtr1 1 a
encode (Lit a) = encodeCtr1 2 a
encode (CNot a) = encodeCtr1 3 a
encode (COr a b) = encodeCtr2 4 a b
encode (CAnd a b) = encodeCtr2 5 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l Var
2 -> decodeCtrBody1 l Lit
3 -> decodeCtrBody1 l CNot
4 -> decodeCtrBody2 l COr
5 -> decodeCtrBody2 l CAnd
{-# SPECIALIZE instance Serialise (Condition ConfVar) #-}
instance Serialise GenericPackageDescription where
encode (GenericPackageDescription a b c d e f) = encodeCtr6 1 a b c d e f
decode = decodeSingleCtr6 1 GenericPackageDescription
|
thoughtpolice/binary-serialise-cbor
|
bench/Real/CBOR.hs
|
Haskell
|
bsd-3-clause
| 18,142
|
{-# LANGUAGE OverloadedStrings #-}
module Site
( app
) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad.Trans
import Data.ByteString (ByteString)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time.Clock
import Snap.Snaplet
import Snap.Snaplet.Auth hiding (session)
import Snap.Snaplet.Auth.Backends.JsonFile
import Snap.Snaplet.Fay
import Snap.Snaplet.Heist
import Snap.Snaplet.Session.Backends.CookieSession
import Snap.Util.FileServe
------------------------------------------------------------------------------
import Application
import Application.SharedTypes
currentTimeAjax :: AppHandler Time
currentTimeAjax = Time . T.pack . show <$> liftIO getCurrentTime
-- TODO this can be handled automatically by heistServe
registerForm :: AppHandler ()
registerForm = render "register-form"
loginForm :: AppHandler ()
loginForm = render "login-form"
register :: UserRegister -> Handler App (AuthManager App) UserRegisterResponse
register (UserRegister u p pc)
| T.length u < 4 || T.length p < 4 || p /= pc = return Fail
| otherwise = do
exists <- usernameExists u
if exists then return Fail else (createUser u (T.encodeUtf8 p) >> return OK)
login :: UserLogin -> Handler App (AuthManager App) UserLoginResponse
login (UserLogin u p r) =
either (return BadLogin) (return LoggedIn) <$>
loginByUsername u (ClearText $ T.encodeUtf8 p) r
------------------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = [
("/ajax/current-time", toFayax currentTimeAjax)
, ("/ajax/login", with auth $ fayax login)
, ("/ajax/login-form", loginForm)
, ("/ajax/logout", with auth logout)
, ("/ajax/register", with auth $ fayax register)
, ("/ajax/register-form", registerForm)
, ("/fay", with fay fayServe)
, ("/static", serveDirectory "static")
]
------------------------------------------------------------------------------
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
s <- nestSnaplet "sess" session $
initCookieSessionManager "site_key.txt" "sess" (Just 3600)
h <- nestSnaplet "" heist $ heistInit "templates"
f <- nestSnaplet "fay" fay $ initFay
a <- nestSnaplet "auth" auth $ initJsonFileAuthManager defAuthSettings session "users.json"
addAuthSplices h auth
addRoutes routes
return $ App h f s a
|
faylang/snaplet-fay
|
example/src/Site.hs
|
Haskell
|
bsd-3-clause
| 2,933
|
{-# Language ScopedTypeVariables #-}
module Symmetry.IL.Deadlock where
import Data.List
import Data.Maybe
import Data.Generics
import Symmetry.IL.AST as AST
import Symmetry.IL.Model
import Symmetry.IL.ConfigInfo
{-
A configuration is deadlocked if
1. All processes are either blocked (i.e. at a receive) or stopped (PC = -1)
2. At least one process is not done
-}
-- Collect blocked states
-- /\_p (blocked-or-done p) /\ (\/_p' blocked p')
blockedLocs :: (Data a, Identable a)
=> Config a -> [(Pid, [(Type, Int)])]
blockedLocs Config{ cProcs = ps }
= blockedLocsOfProc <$> ps
procAtRecv :: ILModel e => ConfigInfo Int -> Pid -> [(Type, Int)] -> e
procAtRecv ci p tis
= ors [ readPC ci (extAbs p) (extAbs p) `eq` int i | (_, i) <- tis ]
procDone :: ILModel e => ConfigInfo a -> Pid -> e
procDone ci p@(PAbs _ _)
= readPC ci (univAbs p) (univAbs p) `eq` int (-1)
procDone ci p
= readPC ci (univAbs p) (univAbs p) `eq` int (-1)
extAbs :: Pid -> Pid
extAbs p@(PAbs _ s) = PAbs (GV (pidIdx p ++ "_1")) s
extAbs p = p
univAbs :: Pid -> Pid
univAbs p@(PAbs _ s) = PAbs (GV (pidIdx p ++ "_0")) s
univAbs p = p
procBlocked :: (Identable a, ILModel e) => ConfigInfo a -> Pid -> [(Type, Int)] -> e
procBlocked ci p@(PAbs _ s) tis
= ors [ ands [ readPC ci p' p' `eq` int i, blocked t ] | (t, i) <- tis ]
where
blocked t = lte (readPtrW ci p' p' t) (readPtrR ci p' p' t)
p' = extAbs p
procBlocked ci p tis
= ors [ ands [readPC ci p p `eq` (int i), blocked t] | (t, i) <- tis ]
where
blocked t = lte (readPtrW ci p p t) (readPtrR ci p p t)
-- (P, Q) P ==> Q where P = \forall procs p, p blocked or done
-- Q = \forall procs p, p done
deadlockFree :: (Data a, Identable a, ILModel e) => ConfigInfo a -> (e, e)
deadlockFree ci@CInfo { config = Config { cProcs = ps } }
= (assumption, consequence)
-- , ands (procDone ci . fst <$> ps) -- ors (badConfig <$> locs)
-- ]
where
badConfig (p, tis) = procBlocked ci p tis
assumption = ands [ blockedOrDone q | q <- fst <$> ps ]
consequence = ands [ procDone ci q | q <- fst <$> ps ]
locs = blockedLocs (config ci)
lkup p = fromJust $ lookup p locs
blockedOrDone p@(PConc _) = ors [ procDone ci p, procBlocked ci p (lkup p) ]
-- blockedOrDone p@(PAbs _ _) = ands [ ors [ procDone ci p, procBlocked ci p (lkup p) ]
-- , eq (counters p (lkup p))
-- (decr (readRoleBound ci p))
-- ]
blockedOrDone p@(PAbs _ _) = ands [ eq (readEnabled ci p) emptySet
, ors [ ands [ procDone ci p, eq (readPCK p (-1)) (readRoleBound ci p) ]
, procBlocked ci p (lkup p)
]
]
-- (readPCK p (-1) `add` blockedCounter ci p p) `lt` (readRoleBound ci p)
counters p = (foldl' add (readPCK p (-1)) . (readPCK p . snd <$>))
readPCK p i = readMap (readPCCounter ci p) (int i)
|
gokhankici/symmetry
|
checker/src/Symmetry/IL/Deadlock.hs
|
Haskell
|
mit
| 3,198
|
{-# LANGUAGE LambdaCase #-}
foo = f >>= \case
Just h -> loadTestDB (h ++ "/.testdb")
Nothing -> fmap S.Right initTestDB
{-| Is the alarm set - i.e. will it go off at some point in the future even if `setAlarm` is not called? -}
isAlarmSetSTM :: AlarmClock -> STM Bool
isAlarmSetSTM AlarmClock{..} = readTVar acNewSetting
>>= \case { AlarmNotSet -> readTVar acIsSet; _ -> return True }
|
mpickering/ghc-exactprint
|
tests/examples/ghc710/LambdaCase.hs
|
Haskell
|
bsd-3-clause
| 405
|
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}
-- |
-- Module : Scion.Configure
-- Copyright : (c) Thomas Schilling 2008
-- License : BSD-style
--
-- Maintainer : nominolo@googlemail.com
-- Stability : experimental
-- Portability : portable
--
module Scion.Configure where
import Scion.Types
import Scion.Session
import GHC hiding ( load )
import DynFlags ( dopt_set )
import GHC.Paths ( ghc, ghc_pkg )
import Exception
import Data.Typeable
import Outputable
import System.Directory
import System.FilePath
import System.IO ( openTempFile, hPutStr, hClose )
import Control.Monad
import Control.Exception ( IOException )
import Distribution.Simple.Configure
import Distribution.PackageDescription.Parse ( readPackageDescription )
import qualified Distribution.Verbosity as V ( normal, deafening )
import Distribution.Simple.Program ( defaultProgramConfiguration, userSpecifyPaths )
import Distribution.Simple.Setup ( defaultConfigFlags, ConfigFlags(..), Flag(..) )
------------------------------------------------------------------------------
-- | Open or configure a Cabal project using the Cabal library.
--
-- Tries to open an existing Cabal project or configures it if opening
-- failed.
--
-- Throws:
--
-- * 'CannotOpenCabalProject' if configuration failed.
--
openOrConfigureCabalProject ::
FilePath -- ^ The project root. (Where the .cabal file resides)
-> FilePath -- ^ dist dir, i.e., directory where to put generated files.
-> [String] -- ^ command line arguments to "configure".
-> ScionM ()
openOrConfigureCabalProject root_dir dist_dir extra_args =
openCabalProject root_dir dist_dir
`gcatch` (\(_ :: CannotOpenCabalProject) ->
configureCabalProject root_dir dist_dir extra_args)
-- | Configure a Cabal project using the Cabal library.
--
-- This is roughly equivalent to calling "./Setup configure" on the command
-- line. The difference is that this makes sure to use the same version of
-- Cabal and the GHC API that Scion was built against. This is important to
-- avoid compatibility problems.
--
-- If configuration succeeded, sets it as the current project.
--
-- TODO: Figure out a way to report more helpful error messages.
--
-- Throws:
--
-- * 'CannotOpenCabalProject' if configuration failed.
--
configureCabalProject ::
FilePath -- ^ The project root. (Where the .cabal file resides)
-> FilePath -- ^ dist dir, i.e., directory where to put generated files.
-> [String] -- ^ command line arguments to "configure". [XXX: currently
-- ignored!]
-> ScionM ()
configureCabalProject root_dir dist_dir _extra_args = do
cabal_file <- find_cabal_file
gen_pkg_descr <- liftIO $ readPackageDescription V.normal cabal_file
let prog_conf =
userSpecifyPaths [("ghc", ghc), ("ghc-pkg", ghc_pkg)]
defaultProgramConfiguration
let config_flags =
(defaultConfigFlags prog_conf)
{ configDistPref = Flag dist_dir
, configVerbosity = Flag V.deafening
, configUserInstall = Flag True
-- TODO: parse flags properly
}
setWorkingDir root_dir
ghandle (\(_ :: IOError) ->
liftIO $ throwIO $
CannotOpenCabalProject "Failed to configure") $ do
lbi <- liftIO $ configure (Left gen_pkg_descr, (Nothing, [])) config_flags
liftIO $ writePersistBuildConfig dist_dir lbi
openCabalProject root_dir dist_dir
where
find_cabal_file = do
fs <- liftIO $ getDirectoryContents root_dir
case [ f | f <- fs, takeExtension f == ".cabal" ] of
[f] -> return $ root_dir </> f
[] -> liftIO $ throwIO $ CannotOpenCabalProject "no .cabal file"
_ -> liftIO $ throwIO $ CannotOpenCabalProject "Too many .cabal files"
-- | Something went wrong during "cabal configure".
--
-- TODO: Add more detail.
data ConfigException = ConfigException deriving (Show, Typeable)
instance Exception ConfigException
-- | Do the equivalent of @runghc Setup.hs <args>@ using the GHC API.
--
-- Instead of "runghc", this function uses the GHC API so that the correct
-- version of GHC and package database is used.
--
-- TODO: Return exception or error message in failure case.
cabalSetupWithArgs ::
FilePath -- ^ Path to .cabal file. TODO: ATM, we only need the
-- directory
-> [String] -- ^ Command line arguments.
-> ScionM Bool
cabalSetupWithArgs cabal_file args =
ghandle (\(_ :: ConfigException) -> return False) $ do
ensureCabalFileExists
let dir = dropFileName cabal_file
(setup, delete_when_done) <- findSetup dir
liftIO $ putStrLn $ "Using setup file: " ++ setup
_mainfun <- compileMain setup
when (delete_when_done) $
liftIO (removeFile setup)
return True
where
ensureCabalFileExists = do
ok <- liftIO (doesFileExist cabal_file)
unless ok (liftIO $ throwIO ConfigException)
findSetup dir = do
let candidates = map ((dir </> "Setup.")++) ["lhs", "hs"]
existing <- mapM (liftIO . doesFileExist) candidates
case [ f | (f,ok) <- zip candidates existing, ok ] of
f:_ -> return (f, False)
[] -> liftIO $ do
ghandle (\(_ :: IOException) -> throwIO $ ConfigException) $ do
tmp_dir <- getTemporaryDirectory
(fp, hdl) <- openTempFile tmp_dir "Setup.hs"
hPutStr hdl (unlines default_cabal_setup)
hClose hdl
return (fp, True)
default_cabal_setup =
["#!/usr/bin/env runhaskell",
"import Distribution.Simple",
"main :: IO ()",
"main = defaultMain"]
compileMain file = do
resetSessionState
dflags <- getSessionDynFlags
setSessionDynFlags $
dopt_set (dflags { hscTarget = HscInterpreted
, ghcLink = LinkInMemory
})
Opt_ForceRecomp -- to avoid picking up Setup.{hi,o}
t <- guessTarget file Nothing
liftIO $ putStrLn $ "target: " ++ (showSDoc $ ppr t)
setTargets [t]
load LoadAllTargets
m <- findModule (mkModuleName "Main") Nothing
env <- findModule (mkModuleName "System.Environment") Nothing
GHC.setContext [m] [env]
mainfun <- runStmt ("System.Environment.withArgs "
++ show args
++ "(main)")
RunToCompletion
return mainfun
|
CristhianMotoche/scion
|
lib/Scion/Configure.hs
|
Haskell
|
bsd-3-clause
| 6,450
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.